acme.html 32 KB

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