acme.html 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <!-- Notes: This should be open in its original path-->
  5. <meta charset="utf-8">
  6. <meta name="zoraxy.csrf.Token" content="{{.csrfToken}}">
  7. <link rel="stylesheet" href="../script/semantic/semantic.min.css">
  8. <script src="../script/jquery-3.6.0.min.js"></script>
  9. <script src="../script/semantic/semantic.min.js"></script>
  10. <script src="../script/utils.js"></script>
  11. <style>
  12. .disabled.table{
  13. opacity: 0.5;
  14. pointer-events: none;
  15. }
  16. .expiredDomain{
  17. color: rgb(238, 31, 31);
  18. }
  19. .validDomain{
  20. color: rgb(49, 192, 113);
  21. }
  22. </style>
  23. </head>
  24. <body>
  25. <br>
  26. <div class="ui container">
  27. <div class="ui header">
  28. <div class="content">
  29. Certificates Auto Renew Settings
  30. <div class="sub header">Fetch and renew your certificates with Automated Certificate Management Environment (ACME) protocol</div>
  31. </div>
  32. </div>
  33. <div class="ui basic segment">
  34. <p style="float: right; color: #21ba45; display:none;" id="enableToggleSucc"><i class="green checkmark icon"></i> Setting Updated</p>
  35. <div class="ui toggle checkbox">
  36. <input type="checkbox" id="enableCertAutoRenew">
  37. <label>Enable Certificate Auto Renew</label>
  38. </div>
  39. <br>
  40. <h3>ACME Email</h3>
  41. <p>Email is required by many CAs for renewing via ACME protocol</p>
  42. <div class="ui fluid action input">
  43. <input id="caRegisterEmail" type="text" placeholder="[email protected]">
  44. <button class="ui icon basic button" onclick="saveEmailToConfig(this);">
  45. <i class="blue save icon"></i>
  46. </button>
  47. </div>
  48. <small>If you don't want to share your private email address, you can also fill in an email address that point to a mailbox not exists on your domain.</small>
  49. </div>
  50. <div class="ui basic segment advanceoptions">
  51. <div class="ui accordion advanceSettings">
  52. <div class="title">
  53. <i class="dropdown icon"></i>
  54. Advance Renew Policy
  55. </div>
  56. <div class="content">
  57. <p>Renew all certificates with ACME supported CAs</p>
  58. <div class="ui toggle checkbox">
  59. <input type="checkbox" id="renewAllSupported" onchange="setAutoRenewIfCASupportMode(this.checked);">
  60. <label>Renew All Certs</label>
  61. </div><br>
  62. <button id="renewNowBtn" onclick="renewNow();" class="ui basic right floated button" style="margin-top: -2em;"><i class="yellow refresh icon"></i> Renew Now</button>
  63. <div class="ui horizontal divider"> OR </div>
  64. <p>Select the certificates to automatic renew in the list below</p>
  65. <table id="domainCertFileTable" class="ui very compact unstackable basic disabled table">
  66. <thead>
  67. <tr>
  68. <th>Domain Name</th>
  69. <th>Match Rule</th>
  70. <th>Auto-Renew</th>
  71. </tr>
  72. </thead>
  73. <tbody id="domainTableBody"></tbody>
  74. </table>
  75. <small><i class="ui red info circle icon"></i> Domain in red are expired</small><br>
  76. <div class="ui yellow message">
  77. Certificate Renew only works on the certification authority (CA) supported by Zoraxy. Check Zoraxy wiki for more information on supported list of CAs.
  78. </div>
  79. <button class="ui basic right floated button" onclick="saveAutoRenewPolicy();"><i class="blue save icon"></i> Save Changes</button>
  80. <button id="renewSelectedButton" onclick="renewNow();" class="ui basic right floated disabled button"><i class="yellow refresh icon"></i> Renew Selected</button>
  81. <br><br>
  82. </div>
  83. </div>
  84. </div>
  85. <div class="ui divider"></div>
  86. <h3>Generate New Certificate</h3>
  87. <p>Enter a new / existing domain(s) to request new certificate(s)</p>
  88. <div class="ui form">
  89. <div class="field">
  90. <label>Domain(s)</label>
  91. <input id="domainsInput" type="text" placeholder="example.com" onkeyup="handlePostInputAutomation();">
  92. <small>If you have more than one domain in a single certificate, enter the domains separated by commas (e.g. s1.dev.example.com,s2.dev.example.com)
  93. <span id="caNoDNSSupportWarning" style="color: #ffaf2e; display:none;"><br> <i class="exclamation triangle icon"></i> Current selected CA do not support DNS challenge</span>
  94. </small>
  95. </div>
  96. <div class="field multiDomainOnly" style="display:none;">
  97. <label>Matching Rule</label>
  98. <input id="filenameInput" type="text" placeholder="Enter filename (no file extension)">
  99. <small>Matching rule to let Zoraxy pick which certificate to use (Also be used as filename). Usually is the longest common suffix of the entered addresses. (e.g. dev.example.com)</small>
  100. </div>
  101. <div class="field multiDomainOnly" style="display:none;">
  102. <button class="ui basic fluid button" onclick="autoDetectMatchingRules();">Auto Detect Matching Rule</button>
  103. </div>
  104. <div class="field">
  105. <label>Certificate Authority (CA)</label>
  106. <div class="ui selection dropdown" id="ca">
  107. <input type="hidden" name="ca">
  108. <i class="dropdown icon"></i>
  109. <div class="default text">Let's Encrypt</div>
  110. <div class="menu">
  111. <div class="item" data-value="Let's Encrypt">Let's Encrypt</div>
  112. <div class="item" data-value="Buypass">Buypass</div>
  113. <div class="item" data-value="ZeroSSL">ZeroSSL</div>
  114. <div class="item" data-value="Custom ACME Server">Custom ACME Server</div>
  115. </div>
  116. </div>
  117. </div>
  118. <div class="field" id="dnsChallenge">
  119. <div class="ui checkbox">
  120. <input type="checkbox" id="useDnsChallenge" onchange="toggleDnsChallenge()">
  121. <label>Use a DNS Challenge<br>
  122. </div>
  123. </div>
  124. <div class="field dnsChallengeOnly" style="display:none;">
  125. <label>DNS Provider</label>
  126. <div class="ui search selection dropdown" id="dnsProvider">
  127. <input type="hidden" name="dnsProvider" value="">
  128. <i class="dropdown icon"></i>
  129. <div class="default text">Pick a DNS Provider</div>
  130. <div class="menu" id="dnsProviderList">
  131. <!-- Auto populate moved to acmedns module and initDNSProviderList() -->
  132. </div>
  133. </div>
  134. </div>
  135. <div class="field dnsChallengeOnly" style="display:none;">
  136. <div class="ui divider"></div>
  137. <p>DNS Credentials</p>
  138. <div id="dnsProviderAPIFields">
  139. <p><i class="ui loading circle notch icon"></i> Generating WebForm</p>
  140. </div>
  141. <h4><i class="yellow exclamation triangle icon"></i> Notes & FAQ</h4>
  142. <div class="ui bulleted list">
  143. <div class="item">Domain DNS credentials are stored separately. For each new subdomain, you will need to enter a new DNS credentials.</div>
  144. <div class="item">For some DNS providers like CloudFlare, you do not need to fill in all fields.</div>
  145. <div class="item">If you are not sure what to fill in, check out the documentation from <a href="https://go-acme.github.io/lego/dns/" target="_blank">lego (DNS challenge library)</a></div>
  146. </div>
  147. <!--
  148. <label>Credentials File Content</label>
  149. <textarea id="dnsCredentials" placeholder=""></textarea>
  150. <small>For more information on the supported DNS Providers and their attirbutes look <a href="https://go-acme.github.io/lego/dns/" target="_blank">here</a>! </small>
  151. <div class="ui negative message">
  152. <i class="icon exclamation triangle"></i>
  153. These credentials will be stored as plaintext in the database and in environment variables!
  154. </div>
  155. -->
  156. </div>
  157. <div class="field" id="caInput" style="display:none;">
  158. <label>ACME Server URL</label>
  159. <input id="caURL" type="text" placeholder="https://example.com/acme/dictionary">
  160. </div>
  161. <div class="field" id="kidInput" style="display:none;">
  162. <label>EAB Credentials (KID) for current provider</label>
  163. <input id="eab_kid" type="text" placeholder="Leave this field blank to keep the current configuration">
  164. </div>
  165. <div class="field" id="hmacInput" style="display:none;">
  166. <label>EAB HMAC Key for current provider</label>
  167. <input id="eab_hmac" type="text" placeholder="Leave this field blank to keep the current configuration">
  168. </div>
  169. <div class="field" id="skipTLS" style="display:none;">
  170. <div class="ui checkbox">
  171. <input type="checkbox" id="skipTLSCheckbox">
  172. <label>Ignore TLS/SSL Verification Error<br><small>E.g. self-signed, expired certificate (Not Recommended)</small></label>
  173. </div>
  174. </div>
  175. <button id="obtainButton" class="ui basic button" type="submit"><i class="yellow refresh icon"></i> Get Certificate</button>
  176. </div>
  177. <div class="ui divider"></div>
  178. <small>First time setting up HTTPS?<br>Try out our <a href="../tools/https.html" target="_blank">wizard</a></small>
  179. <button class="ui basic button" style="float: right;" onclick="parent.hideSideWrapper();"><i class="remove icon"></i> Cancel</button>
  180. <br><br><br><br>
  181. </div>
  182. <script>
  183. let expiredDomains = [];
  184. let enableTrigerOnChangeEvent = true;
  185. $(".accordion").accordion();
  186. $(".dropdown").dropdown();
  187. $(".checkbox").checkbox();
  188. function setAutoRenewIfCASupportMode(useAutoMode = true){
  189. if (useAutoMode){
  190. $("#domainCertFileTable").addClass("disabled");
  191. $("#renewNowBtn").removeClass("disabled");
  192. $("#renewSelectedButton").addClass("disabled");
  193. }else{
  194. $("#domainCertFileTable").removeClass("disabled");
  195. $("#renewNowBtn").addClass("disabled");
  196. $("#renewSelectedButton").removeClass("disabled");
  197. }
  198. }
  199. function initRenewerConfigFromFile(){
  200. //Set the renew switch state
  201. $.get("/api/acme/autoRenew/enable", function(data){
  202. if (data == true){
  203. $("#enableCertAutoRenew").parent().checkbox("set checked");
  204. }
  205. $("#enableCertAutoRenew").on("change", function(){
  206. if (!enableTrigerOnChangeEvent){
  207. return;
  208. }
  209. toggleAutoRenew();
  210. })
  211. });
  212. //Load the email from server side
  213. $.get("/api/acme/autoRenew/email", function(data){
  214. if (data != "" && data != undefined && data != null){
  215. $("#caRegisterEmail").val(data);
  216. }
  217. });
  218. //Load the domain selection options
  219. $.get("/api/acme/autoRenew/renewPolicy", function(data){
  220. if (data == true){
  221. $("#renewAllSupported").parent().checkbox("set checked");
  222. }else{
  223. $("#renewAllSupported").parent().checkbox("set unchecked");
  224. }
  225. });
  226. }
  227. initRenewerConfigFromFile();
  228. function saveEmailToConfig(btn){
  229. $.cjax({
  230. url: "/api/acme/autoRenew/email",
  231. method: "POST",
  232. data: {set: $("#caRegisterEmail").val()},
  233. success: function(data){
  234. if (data.error != undefined){
  235. parent.msgbox(data.error, false, 5000);
  236. }else{
  237. parent.msgbox("Email updated");
  238. $(btn).html(`<i class="green check icon"></i>`);
  239. $(btn).addClass("disabled");
  240. setTimeout(function(){
  241. $(btn).html(`<i class="blue save icon"></i>`);
  242. $(btn).removeClass("disabled");
  243. }, 3000);
  244. }
  245. }
  246. });
  247. }
  248. function toggleAutoRenew(){
  249. var enabled = $("#enableCertAutoRenew").parent().checkbox("is checked");
  250. $.cjax({
  251. url: "/api/acme/autoRenew/enable",
  252. method: "POST",
  253. data: {"enable": enabled},
  254. success: function(data){
  255. if (data.error){
  256. parent.msgbox(data.error, false, 5000);
  257. if (enabled){
  258. enableTrigerOnChangeEvent = false;
  259. $("#enableCertAutoRenew").parent().checkbox("set unchecked");
  260. enableTrigerOnChangeEvent = true;
  261. }
  262. if (parent && parent.setACMEEnableStates){
  263. parent.setACMEEnableStates(!enabled);
  264. }
  265. }else{
  266. $("#enableToggleSucc").stop().finish().fadeIn("fast").delay(3000).fadeOut("fast");
  267. if (parent && parent.setACMEEnableStates){
  268. parent.setACMEEnableStates(enabled);
  269. }
  270. }
  271. }
  272. });
  273. }
  274. //Render the domains table that exists in this zoraxy host
  275. function renderDomainTable(domainFileList) {
  276. // Get the table body element
  277. var tableBody = $('#domainTableBody');
  278. // Clear the table body
  279. tableBody.empty();
  280. // Iterate over the domain names
  281. var counter = 0;
  282. for (const [srcfile, domains] of Object.entries(domainFileList)) {
  283. // Create a table row
  284. var row = $('<tr>');
  285. // Create the domain name cell
  286. var domainClass = "validDomain";
  287. for (var i = 0; i < domains.length; i++){
  288. let thisDomain = domains[i];
  289. if (expiredDomains.includes(thisDomain)){
  290. domainClass = "expiredDomain";
  291. }
  292. }
  293. var domainCell = $('<td class="' + domainClass +'">').html(domains.join("<br>"));
  294. row.append(domainCell);
  295. var srcFileCell = $('<td>').text(srcfile);
  296. row.append(srcFileCell);
  297. // Create the auto-renew checkbox cell
  298. let domainsEncoded = encodeURIComponent(JSON.stringify(domains));
  299. var checkboxCell = $(`<td domain="${domainsEncoded}" srcfile="${srcfile}">`);
  300. var checkbox = $(`<input name="${srcfile}">`).attr('type', 'checkbox');
  301. checkboxCell.append(checkbox);
  302. row.append(checkboxCell);
  303. // Add the row to the table body
  304. tableBody.append(row);
  305. counter++;
  306. }
  307. if (Object.keys(domainFileList).length == 0){
  308. //No certificate in this system
  309. tableBody.append(`<tr>
  310. <td colspan="3"><i class="ui green circle check icon"></i> No certificate in use</td>
  311. </tr>`);
  312. }
  313. }
  314. //Initiate domain table. If you needs to update the expired domain as well
  315. //call from initDomainFileList() instead
  316. function initDomainTable(){
  317. $.get("/api/cert/listdomains?compact=true", function(data){
  318. if (data.error != undefined){
  319. parent.msgbox(data.error, false);
  320. }else{
  321. renderDomainTable(data);
  322. }
  323. initAutoRenewPolicy();
  324. })
  325. }
  326. function initDomainFileList() {
  327. $.ajax({
  328. url: "/api/acme/listExpiredDomains",
  329. method: "GET",
  330. success: function(response) {
  331. // Render domain table
  332. expiredDomains = response.domain;
  333. initDomainTable();
  334. //renderDomainTable(response.domain);
  335. },
  336. error: function(error) {
  337. console.log("Failed to fetch expired domains:", error);
  338. }
  339. });
  340. }
  341. initDomainFileList();
  342. // Button click event handler for obtaining certificate
  343. $("#obtainButton").click(function() {
  344. $("#obtainButton").addClass("loading").addClass("disabled");
  345. updateCertificateEAB(function(succ){
  346. if (succ){
  347. //Continue to next step
  348. updateCertificateDNS(function(succ){
  349. if (succ){
  350. obtainCertificate(function(succ){
  351. $("#obtainButton").removeClass("loading").removeClass("disabled");
  352. });
  353. }else{
  354. $("#obtainButton").removeClass("loading").removeClass("disabled");
  355. console.log("update Certificate DNS process halted");
  356. }
  357. });
  358. }else{
  359. console.log("Update Certificate EAB process halted");
  360. $("#obtainButton").removeClass("loading").removeClass("disabled");
  361. }
  362. });
  363. });
  364. //On CA change in dropdown
  365. $("input[name=ca]").on('change', function() {
  366. if(this.value == "Custom ACME Server") {
  367. $("#caInput").show();
  368. $("#kidInput").show();
  369. $("#hmacInput").show();
  370. $("#skipTLS").show();
  371. $("#dnsChallenge").hide();
  372. $(".dnsChallengeOnly").hide();
  373. } else if (this.value == "ZeroSSL") {
  374. $("#kidInput").show();
  375. $("#hmacInput").show();
  376. $("#dnsChallenge").hide();
  377. $(".dnsChallengeOnly").hide();
  378. $("#skipTLS").hide();
  379. } else if (this.value == "Buypass") {
  380. $("#kidInput").show();
  381. $("#hmacInput").show();
  382. $("#dnsChallenge").hide();
  383. $(".dnsChallengeOnly").hide();
  384. $("#skipTLS").hide();
  385. }else {
  386. $("#caInput").hide();
  387. $("#skipTLS").hide();
  388. $("#kidInput").hide();
  389. $("#hmacInput").hide();
  390. $("#dnsChallenge").show();
  391. if ($("#useDnsChallenge")[0].checked){
  392. $(".dnsChallengeOnly").show();
  393. }
  394. }
  395. })
  396. //On DNS provider dropdown change
  397. $("input[name=dnsProvider]").on('change', function() {
  398. let newProviderName = $("#dnsProvider").find("input").val();
  399. $.get("/api/acme/dns/providers?name=" + newProviderName, function(data){
  400. console.log("Loaded required config", data);
  401. $("#dnsProviderAPIFields").html("");
  402. //Generate a form for this config
  403. let booleanFieldsHTML = "";
  404. let optionalFieldsHTML = "";
  405. for (const [key, datatype] of Object.entries(data)) {
  406. if (datatype == "int"){
  407. let defaultValue = 10;
  408. if (key == "HTTPTimeout"){
  409. defaultValue = 300;
  410. }
  411. $("#dnsProviderAPIFields").append(`<div class="ui fluid labeled dnsConfigField input typeint" key="${key}" style="margin-top: 0.2em;">
  412. <div class="ui basic blue label" style="font-weight: 300;">
  413. ${key}
  414. </div>
  415. <input type="number" value="${defaultValue}">
  416. </div>`);
  417. }else if (datatype == "bool"){
  418. booleanFieldsHTML += (`<div class="ui checkbox dnsConfigField" key="${key}" style="margin-top: 1em !important; padding-left: 0.4em;">
  419. <input type="checkbox">
  420. <label>${key}</label>
  421. </div>`);
  422. }else if (datatype == "time.Duration"){
  423. let defaultIntValue = 120;
  424. let defaultMinValue = 30;
  425. if (key == "PollingInterval"){
  426. defaultIntValue = 2;
  427. defaultMinValue = 1;
  428. }else if (key == "PropagationTimeout"){
  429. defaultIntValue = 120;
  430. defaultMinValue = 30;
  431. }
  432. optionalFieldsHTML += (`<div class="ui fluid labeled dnsConfigField small input" key="${key}" style="margin-top: 0.2em;">
  433. <div class="ui basic blue label" style="font-weight: 300;">
  434. ${key}
  435. </div>
  436. <input type="number" min="${defaultMinValue}" value="${defaultIntValue}">
  437. <div class="ui basic label" style="font-weight: 300;">
  438. secs
  439. </div>
  440. </div>`);
  441. }else{
  442. //Default to string
  443. $("#dnsProviderAPIFields").append(`<div class="ui fluid labeled input dnsConfigField" key="${key}" style="margin-top: 0.2em;">
  444. <div class="ui basic label" style="font-weight: 300;">
  445. ${key}
  446. </div>
  447. <input type="text">
  448. </div>`);
  449. }
  450. }
  451. //Append the boolean fields at the bottom, if exists
  452. $("#dnsProviderAPIFields").append(booleanFieldsHTML);
  453. if (booleanFieldsHTML != ""){
  454. $(".dnsConfigField.checkbox").checkbox();
  455. }
  456. //Append the optional fields at the bottom, if exists
  457. $("#dnsProviderAPIFields").append(optionalFieldsHTML);
  458. });
  459. });
  460. // Get filename form domains and input
  461. function getFilename() {
  462. var domains = $("#domainsInput").val();
  463. var filename = $("#filenameInput").val();
  464. if (filename.trim() == "" && !domains.includes(",")){
  465. //Zoraxy filename are the matching name for domains.
  466. //Use the same as domains
  467. filename = domains;
  468. }else if (filename != "" && !domains.includes(",")){
  469. //Invalid settings. Force the filename to be same as domain
  470. //if there are only 1 domain
  471. filename = domains;
  472. }else if (filename == "" && domains.includes(",")){
  473. parent.msgbox("Filename cannot be empty for certs containing multiple domains.", false, 5000);
  474. $("#obtainButton").removeClass("loading").removeClass("disabled");
  475. return;
  476. }
  477. //Filename cannot contain wildcards, and wildcards are possible with DNS challenges
  478. filename = filename.replace("*", "_");
  479. return filename;
  480. }
  481. // Update EAB values for autorenewal
  482. function updateCertificateEAB(callback=undefined) {
  483. var ca = $("#ca").dropdown("get value");
  484. var caURL = "";
  485. if (ca == "Custom ACME Server") {
  486. ca = "custom";
  487. caURL = $("#caURL").val();
  488. }else if(ca == "Buypass") {
  489. caURL = "https://api.buypass.com/acme/directory";
  490. }else if(ca == "ZeroSSL") {
  491. caURL = "https://acme.zerossl.com/v2/DV90";
  492. }
  493. if(caURL == "") {
  494. //Skip update
  495. if (callback != undefined){
  496. callback(true);
  497. }
  498. return;
  499. }
  500. var kid = $("#eab_kid").val();
  501. var hmac = $("#eab_hmac").val();
  502. if(kid == "" || hmac == "") {
  503. //Skip update
  504. if (callback != undefined){
  505. callback(true);
  506. }
  507. return;
  508. }
  509. console.log(caURL + " " + kid + " " + hmac);
  510. $.ajax({
  511. url: "/api/acme/autoRenew/setEAB",
  512. method: "GET",
  513. data: {
  514. acmeDirectoryURL: caURL,
  515. kid: kid,
  516. hmacEncoded: hmac,
  517. },
  518. success: function(response) {
  519. //$("#obtainButton").removeClass("loading").removeClass("disabled");
  520. if (response.error) {
  521. console.log("Error:", response.error);
  522. // Show error message
  523. parent.msgbox(response.error, false, 12000);
  524. if (callback != undefined){
  525. callback(false);
  526. }
  527. } else {
  528. console.log("Certificate EAB updated successfully");
  529. // Show success message
  530. parent.msgbox("Certificate EAB updated successfully");
  531. // Renew the parent certificate list
  532. parent.initManagedDomainCertificateList();
  533. if (callback != undefined){
  534. callback(true);
  535. }
  536. }
  537. },
  538. error: function(error) {
  539. //$("#obtainButton").removeClass("loading").removeClass("disabled");
  540. console.log("Failed to update EAB configuration:", error);
  541. parent.msgbox("Failed to update EAB configuration");
  542. if (callback != undefined){
  543. callback(false);
  544. }
  545. }
  546. });
  547. }
  548. //Read DNS credential from form and generate a key value structure that looks like
  549. // the old DNSCredential TextArea input
  550. function readDnsCredentials(){
  551. let dnsCredentials = {};
  552. $(".dnsConfigField").each(function(){
  553. let thisKey = $(this).attr("key");
  554. let value = "";
  555. if ($(this).hasClass("checkbox")){
  556. //Boolean option
  557. let checked = $(this).find("input")[0].checked;
  558. dnsCredentials[thisKey] = checked;
  559. }else if ($(this).hasClass("typeint")){
  560. //Int options
  561. let value = $(this).find("input").val();
  562. dnsCredentials[thisKey] = parseInt(value);
  563. }else{
  564. //String options
  565. let value = $(this).find("input").val().trim();
  566. dnsCredentials[thisKey] = value;
  567. }
  568. });
  569. return dnsCredentials;
  570. }
  571. // Update DNS values for autorenewal
  572. function updateCertificateDNS(callback=undefined) {
  573. var dns = $("#useDnsChallenge")[0].checked;
  574. var dnsProvider = "";
  575. var dnsCredentials = "";
  576. if (!dns) {
  577. if (callback != undefined){
  578. callback(true);
  579. }
  580. return;
  581. }
  582. //Check if all fields is empty. If yes, do not update the config
  583. let allFieldsEmpty = true;
  584. $(".dnsConfigField").each(function(){
  585. if ($(this).find("input").val().trim() != ""){
  586. allFieldsEmpty = false;
  587. }
  588. });
  589. if (allFieldsEmpty){
  590. //Do not update config on server side
  591. if (callback != undefined){
  592. callback(true);
  593. }
  594. return;
  595. }
  596. dnsProvider = $("#dnsProvider").dropdown("get value");
  597. //dnsCredentials = $("#dnsCredentials").val();
  598. dnsCredentials = readDnsCredentials();
  599. if(dnsProvider == "") {
  600. parent.msgbox("DNS Provider cannot be empty", false, 5000);
  601. $("#obtainButton").removeClass("loading").removeClass("disabled");
  602. if (callback != undefined){
  603. callback(false);
  604. }
  605. return;
  606. }
  607. var filename = getFilename();
  608. if (filename == '') {
  609. parent.msgbox("Domain to renew cannot be empty", false, 5000);
  610. if (callback != undefined){
  611. callback(false);
  612. }
  613. return;
  614. }
  615. $.cjax({
  616. url: "/api/acme/autoRenew/setDNS",
  617. method: "POST",
  618. data: {
  619. filename: filename,
  620. dnsProvider: dnsProvider,
  621. dnsCredentials: JSON.stringify(dnsCredentials),
  622. },
  623. success: function(response) {
  624. //$("#obtainButton").removeClass("loading").removeClass("disabled");
  625. if (response.error) {
  626. console.log("Error:", response.error);
  627. // Show error message
  628. parent.msgbox(response.error, false, 12000);
  629. if (callback != undefined){
  630. callback(false);
  631. }
  632. } else {
  633. console.log("Certificate DNS Credentials updated successfully");
  634. // Show success message
  635. parent.msgbox("Certificate DNS Credentials updated successfully");
  636. if (callback != undefined){
  637. callback(true);
  638. }
  639. }
  640. },
  641. error: function(error) {
  642. //$("#obtainButton").removeClass("loading").removeClass("disabled");
  643. console.log("Failed to update DNS configuration:", error);
  644. parent.msgbox("Failed to update DNS configuration");
  645. if (callback != undefined){
  646. callback(false);
  647. }
  648. }
  649. });
  650. }
  651. // Obtain certificate from API
  652. function obtainCertificate(callback=undefined) {
  653. var domains = $("#domainsInput").val();
  654. var filename = getFilename();
  655. if (filename == '') {
  656. if (callback != undefined){
  657. parent.msgbox("Domain to obtain certificate cannot be empty", false)
  658. callback(false);
  659. }
  660. return;
  661. }
  662. var email = $("#caRegisterEmail").val();
  663. if (email == ""){
  664. parent.msgbox("ACME renew email is not set", false)
  665. if (callback != undefined){callback(false);}
  666. return;
  667. }
  668. var ca = $("#ca").dropdown("get value");
  669. var caURL = "";
  670. if (ca == "Custom ACME Server") {
  671. ca = "custom";
  672. caURL = $("#caURL").val();
  673. }
  674. var dns = $("#useDnsChallenge")[0].checked;
  675. var skipTLSValue = $("#skipTLSCheckbox")[0].checked;
  676. $.ajax({
  677. url: "/api/acme/obtainCert",
  678. method: "GET",
  679. data: {
  680. domains: domains,
  681. filename: filename,
  682. email: email,
  683. ca: ca,
  684. caURL: caURL,
  685. skipTLS: skipTLSValue,
  686. dns: dns,
  687. },
  688. success: function(response) {
  689. $("#obtainButton").removeClass("loading").removeClass("disabled");
  690. if (response.error) {
  691. console.log("Error:", response.error);
  692. // Show error message
  693. parent.msgbox(response.error, false, 12000);
  694. if (callback != undefined){callback(false);}
  695. } else {
  696. console.log("Certificate renewed successfully");
  697. // Show success message
  698. parent.msgbox("Certificate renewed successfully");
  699. // Renew the parent certificate list
  700. parent.initManagedDomainCertificateList();
  701. if (callback != undefined){callback(true);}
  702. }
  703. },
  704. error: function(error) {
  705. $("#obtainButton").removeClass("loading").removeClass("disabled");
  706. console.log("Failed to renewed certificate:", error);
  707. if (callback != undefined){callback(false);}
  708. }
  709. });
  710. }
  711. //Check if the entered domain contains multiple domains
  712. function checkIfInputDomainIsMultiple(){
  713. var inputDomains = $("#domainsInput").val();
  714. if (inputDomains.includes(",")){
  715. $(".multiDomainOnly").show();
  716. }else{
  717. $(".multiDomainOnly").hide();
  718. }
  719. }
  720. //Validate if the current combinations of domain and CA supports DNS challenge
  721. function validateDNSChallengeSupport(){
  722. if ($("#domainsInput").val().includes("*")){
  723. var ca = $("#ca").dropdown("get value");
  724. if (ca == "Let's Encrypt" || ca == ""){
  725. $("#caNoDNSSupportWarning").hide();
  726. }else{
  727. $("#caNoDNSSupportWarning").show();
  728. }
  729. }else{
  730. $("#caNoDNSSupportWarning").hide();
  731. }
  732. }
  733. //call to validateDNSChallengeSupport() on #ca value change
  734. $("#ca").dropdown({
  735. onChange: function(value, text, $selectedItem) {
  736. validateDNSChallengeSupport();
  737. }
  738. });
  739. //Handle the input change event on domain input
  740. function handlePostInputAutomation(){
  741. checkIfInputDomainIsMultiple();
  742. validateDNSChallengeSupport();
  743. }
  744. function toggleDnsChallenge(){
  745. if ( $("#useDnsChallenge")[0].checked){
  746. $(".dnsChallengeOnly").show();
  747. setTimeout(function(){
  748. $("#dnsProvider").dropdown("set text", "Cloudflare");
  749. }, 500);
  750. }else{
  751. $(".dnsChallengeOnly").hide();
  752. }
  753. }
  754. //Grab the longest common suffix of all domains
  755. //not that smart technically
  756. function autoDetectMatchingRules(){
  757. var domainsString = $("#domainsInput").val();
  758. if (!domainsString.includes(",")){
  759. return domainsString;
  760. }
  761. let domains = domainsString.split(",");
  762. //Clean out any spacing between commas
  763. for (var i = 0; i < domains.length; i++){
  764. domains[i] = domains[i].trim();
  765. }
  766. function getLongestCommonSuffix(strings) {
  767. if (strings.length === 0) {
  768. return ''; // Return an empty string if the array is empty
  769. }
  770. var sortedStrings = strings.slice().sort(); // Create a sorted copy of the array
  771. var firstString = sortedStrings[0];
  772. var lastString = sortedStrings[sortedStrings.length - 1];
  773. var suffix = '';
  774. var minLength = Math.min(firstString.length, lastString.length);
  775. for (var i = 0; i < minLength; i++) {
  776. if (firstString[firstString.length - 1 - i] !== lastString[lastString.length - 1 - i]) {
  777. break; // Stop iterating if characters don't match
  778. }
  779. suffix = firstString[firstString.length - 1 - i] + suffix;
  780. }
  781. return suffix;
  782. }
  783. let longestSuffix = getLongestCommonSuffix(domains);
  784. //Check if the suffix is a valid domain
  785. if (longestSuffix.substr(0,1) == "."){
  786. //Trim off the first dot
  787. longestSuffix = longestSuffix.substr(1);
  788. }
  789. if (!longestSuffix.includes(".")){
  790. parent.msgbox("Auto Detect failed: Multiple Domains", false, 5000);
  791. return;
  792. }
  793. $("#filenameInput").val(longestSuffix);
  794. }
  795. //Handle the renew now btn click
  796. function renewNow(){
  797. $.get("/api/acme/autoRenew/renewNow", function(data){
  798. if (data.error != undefined){
  799. parent.msgbox(data.error, false, 6000);
  800. }else{
  801. parent.msgbox(data)
  802. }
  803. })
  804. }
  805. function initAutoRenewPolicy(){
  806. $.get("/api/acme/autoRenew/listDomains", function(data){
  807. if (data.error != undefined){
  808. parent.msgbox(data.error, false)
  809. }else{
  810. if (data[0] == "*"){
  811. //Auto select and renew is enabled
  812. $("#renewAllSupported").parent().checkbox("set checked");
  813. }else{
  814. //This is a list of domain files
  815. data.forEach(function(name) {
  816. $('#domainTableBody input[type="checkbox"][name="' + name + '"]').prop('checked', true);
  817. });
  818. $("#domainCertFileTable").removeClass("disabled");
  819. $("#renewNowBtn").addClass("disabled");
  820. $("#renewSelectedButton").removeClass("disabled");
  821. }
  822. }
  823. })
  824. }
  825. function saveAutoRenewPolicy(){
  826. let autoRenewAll = $("#renewAllSupported").parent().checkbox("is checked");
  827. if (autoRenewAll == true){
  828. $.cjax({
  829. url: "/api/acme/autoRenew/setDomains",
  830. method: "POST",
  831. data: {opr: "setAuto"},
  832. success: function(data){
  833. parent.msgbox("Renew policy rule updated")
  834. }
  835. });
  836. }else{
  837. let checkedNames = [];
  838. $('#domainTableBody input[type="checkbox"]:checked').each(function() {
  839. checkedNames.push($(this).attr('name'));
  840. });
  841. $.cjax({
  842. url: "/api/acme/autoRenew/setDomains",
  843. method: "POST",
  844. data: {opr: "setSelected", domains: JSON.stringify(checkedNames)},
  845. success: function(data){
  846. parent.msgbox("Renew policy rule updated")
  847. }
  848. });
  849. }
  850. }
  851. //Load the json map and create the dropdown for DNS provider names
  852. let dnsProviderNameMap = {};
  853. function initDNSProviderList(){
  854. $.get("dnsnames.json", function(namemap){
  855. dnsProviderNameMap = namemap;
  856. //Load a list of supported DNS provider from backend
  857. $("#dnsProviderList").html("");
  858. $.get("/api/acme/dns/providers", function(providerList){
  859. providerList.sort();
  860. providerList.forEach(providerid => {
  861. let providerName = providerid;
  862. if (dnsProviderNameMap[providerid] != undefined){
  863. providerName = dnsProviderNameMap[providerid];
  864. }
  865. $("#dnsProviderList").append(`<div class="item" data-value="${providerid}">${providerName}</div>`);
  866. });
  867. $("#dnsProvider").dropdown();
  868. setTimeout(function(){
  869. //The dropdown is large, it takes some time to load
  870. $("#dnsProvider").dropdown("set selected", "cloudflare");
  871. }, 300)
  872. });
  873. });
  874. }
  875. initDNSProviderList();
  876. //Clear up the input field when page load
  877. $("#filenameInput").val("");
  878. </script>
  879. </body>
  880. </html>