acme.html 32 KB

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