acme.html 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  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="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. for (const [key, datatype] of Object.entries(data)) {
  405. if (datatype == "int"){
  406. $("#dnsProviderAPIFields").append(`<div class="ui fluid labeled dnsConfigField input" key="${key}" style="margin-top: 0.2em;">
  407. <div class="ui basic blue label" style="font-weight: 300;">
  408. ${key}
  409. </div>
  410. <input type="number" value="300">
  411. </div>`);
  412. }else if (datatype == "bool"){
  413. booleanFieldsHTML += (`<div class="ui checkbox dnsConfigField" key="${key}" style="margin-top: 1em !important; padding-left: 0.4em;">
  414. <input type="checkbox">
  415. <label>${key}</label>
  416. </div>`);
  417. }else{
  418. //Default to string
  419. $("#dnsProviderAPIFields").append(`<div class="ui fluid labeled input dnsConfigField" key="${key}" style="margin-top: 0.2em;">
  420. <div class="ui basic label" style="font-weight: 300;">
  421. ${key}
  422. </div>
  423. <input type="text">
  424. </div>`);
  425. }
  426. }
  427. //Append the boolean fields at the bottom, if exists
  428. $("#dnsProviderAPIFields").append(booleanFieldsHTML);
  429. if (booleanFieldsHTML != ""){
  430. $(".dnsConfigField.checkbox").checkbox();
  431. }
  432. });
  433. });
  434. // Get filename form domains and input
  435. function getFilename() {
  436. var domains = $("#domainsInput").val();
  437. var filename = $("#filenameInput").val();
  438. if (filename.trim() == "" && !domains.includes(",")){
  439. //Zoraxy filename are the matching name for domains.
  440. //Use the same as domains
  441. filename = domains;
  442. }else if (filename != "" && !domains.includes(",")){
  443. //Invalid settings. Force the filename to be same as domain
  444. //if there are only 1 domain
  445. filename = domains;
  446. }else if (filename == "" && domains.includes(",")){
  447. parent.msgbox("Filename cannot be empty for certs containing multiple domains.", false, 5000);
  448. $("#obtainButton").removeClass("loading").removeClass("disabled");
  449. return;
  450. }
  451. //Filename cannot contain wildcards, and wildcards are possible with DNS challenges
  452. filename = filename.replace("*", "_");
  453. return filename;
  454. }
  455. // Update EAB values for autorenewal
  456. function updateCertificateEAB(callback=undefined) {
  457. var ca = $("#ca").dropdown("get value");
  458. var caURL = "";
  459. if (ca == "Custom ACME Server") {
  460. ca = "custom";
  461. caURL = $("#caURL").val();
  462. }else if(ca == "Buypass") {
  463. caURL = "https://api.buypass.com/acme/directory";
  464. }else if(ca == "ZeroSSL") {
  465. caURL = "https://acme.zerossl.com/v2/DV90";
  466. }
  467. if(caURL == "") {
  468. //Skip update
  469. if (callback != undefined){
  470. callback(true);
  471. }
  472. return;
  473. }
  474. var kid = $("#eab_kid").val();
  475. var hmac = $("#eab_hmac").val();
  476. if(kid == "" || hmac == "") {
  477. //Skip update
  478. if (callback != undefined){
  479. callback(true);
  480. }
  481. return;
  482. }
  483. console.log(caURL + " " + kid + " " + hmac);
  484. $.ajax({
  485. url: "/api/acme/autoRenew/setEAB",
  486. method: "GET",
  487. data: {
  488. acmeDirectoryURL: caURL,
  489. kid: kid,
  490. hmacEncoded: hmac,
  491. },
  492. success: function(response) {
  493. //$("#obtainButton").removeClass("loading").removeClass("disabled");
  494. if (response.error) {
  495. console.log("Error:", response.error);
  496. // Show error message
  497. parent.msgbox(response.error, false, 12000);
  498. if (callback != undefined){
  499. callback(false);
  500. }
  501. } else {
  502. console.log("Certificate EAB updated successfully");
  503. // Show success message
  504. parent.msgbox("Certificate EAB updated successfully");
  505. // Renew the parent certificate list
  506. parent.initManagedDomainCertificateList();
  507. if (callback != undefined){
  508. callback(true);
  509. }
  510. }
  511. },
  512. error: function(error) {
  513. //$("#obtainButton").removeClass("loading").removeClass("disabled");
  514. console.log("Failed to update EAB configuration:", error);
  515. parent.msgbox("Failed to update EAB configuration");
  516. if (callback != undefined){
  517. callback(false);
  518. }
  519. }
  520. });
  521. }
  522. //Read DNS credential from form and generate a key value structure that looks like
  523. // the old DNSCredential TextArea input
  524. function readDnsCredentials(){
  525. let dnsCredentials = {};
  526. $(".dnsConfigField").each(function(){
  527. let thisKey = $(this).attr("key");
  528. let value = "";
  529. if ($(this).hasClass("checkbox")){
  530. //Boolean option
  531. let checked = $(this).find("input")[0].checked;
  532. dnsCredentials[thisKey] = checked;
  533. }else{
  534. //String or int options
  535. let value = $(this).find("input").val().trim();
  536. dnsCredentials[thisKey] = value;
  537. }
  538. });
  539. return dnsCredentials;
  540. }
  541. // Update DNS values for autorenewal
  542. function updateCertificateDNS(callback=undefined) {
  543. var dns = $("#useDnsChallenge")[0].checked;
  544. var dnsProvider = "";
  545. var dnsCredentials = "";
  546. if (!dns) {
  547. if (callback != undefined){
  548. callback(true);
  549. }
  550. return;
  551. }
  552. //Check if all fields is empty. If yes, do not update the config
  553. let allFieldsEmpty = true;
  554. $(".dnsConfigField").each(function(){
  555. if ($(this).find("input").val().trim() != ""){
  556. allFieldsEmpty = false;
  557. }
  558. });
  559. if (allFieldsEmpty){
  560. //Do not update config on server side
  561. if (callback != undefined){
  562. callback(true);
  563. }
  564. return;
  565. }
  566. dnsProvider = $("#dnsProvider").dropdown("get value");
  567. //dnsCredentials = $("#dnsCredentials").val();
  568. dnsCredentials = readDnsCredentials();
  569. if(dnsProvider == "") {
  570. parent.msgbox("DNS Provider cannot be empty", false, 5000);
  571. $("#obtainButton").removeClass("loading").removeClass("disabled");
  572. if (callback != undefined){
  573. callback(false);
  574. }
  575. return;
  576. }
  577. var filename = getFilename();
  578. if (filename == '') {
  579. parent.msgbox("Domain to renew cannot be empty", false, 5000);
  580. if (callback != undefined){
  581. callback(false);
  582. }
  583. return;
  584. }
  585. $.cjax({
  586. url: "/api/acme/autoRenew/setDNS",
  587. method: "POST",
  588. data: {
  589. filename: filename,
  590. dnsProvider: dnsProvider,
  591. dnsCredentials: JSON.stringify(dnsCredentials),
  592. },
  593. success: function(response) {
  594. //$("#obtainButton").removeClass("loading").removeClass("disabled");
  595. if (response.error) {
  596. console.log("Error:", response.error);
  597. // Show error message
  598. parent.msgbox(response.error, false, 12000);
  599. if (callback != undefined){
  600. callback(false);
  601. }
  602. } else {
  603. console.log("Certificate DNS Credentials updated successfully");
  604. // Show success message
  605. parent.msgbox("Certificate DNS Credentials updated successfully");
  606. if (callback != undefined){
  607. callback(true);
  608. }
  609. }
  610. },
  611. error: function(error) {
  612. //$("#obtainButton").removeClass("loading").removeClass("disabled");
  613. console.log("Failed to update DNS configuration:", error);
  614. parent.msgbox("Failed to update DNS configuration");
  615. if (callback != undefined){
  616. callback(false);
  617. }
  618. }
  619. });
  620. }
  621. // Obtain certificate from API
  622. function obtainCertificate(callback=undefined) {
  623. var domains = $("#domainsInput").val();
  624. var filename = getFilename();
  625. if (filename == '') {
  626. if (callback != undefined){
  627. parent.msgbox("Domain to obtain certificate cannot be empty", false)
  628. callback(false);
  629. }
  630. return;
  631. }
  632. var email = $("#caRegisterEmail").val();
  633. if (email == ""){
  634. parent.msgbox("ACME renew email is not set", false)
  635. if (callback != undefined){callback(false);}
  636. return;
  637. }
  638. var ca = $("#ca").dropdown("get value");
  639. var caURL = "";
  640. if (ca == "Custom ACME Server") {
  641. ca = "custom";
  642. caURL = $("#caURL").val();
  643. }
  644. var dns = $("#useDnsChallenge")[0].checked;
  645. var skipTLSValue = $("#skipTLSCheckbox")[0].checked;
  646. $.ajax({
  647. url: "/api/acme/obtainCert",
  648. method: "GET",
  649. data: {
  650. domains: domains,
  651. filename: filename,
  652. email: email,
  653. ca: ca,
  654. caURL: caURL,
  655. skipTLS: skipTLSValue,
  656. dns: dns,
  657. },
  658. success: function(response) {
  659. $("#obtainButton").removeClass("loading").removeClass("disabled");
  660. if (response.error) {
  661. console.log("Error:", response.error);
  662. // Show error message
  663. parent.msgbox(response.error, false, 12000);
  664. if (callback != undefined){callback(false);}
  665. } else {
  666. console.log("Certificate renewed successfully");
  667. // Show success message
  668. parent.msgbox("Certificate renewed successfully");
  669. // Renew the parent certificate list
  670. parent.initManagedDomainCertificateList();
  671. if (callback != undefined){callback(true);}
  672. }
  673. },
  674. error: function(error) {
  675. $("#obtainButton").removeClass("loading").removeClass("disabled");
  676. console.log("Failed to renewed certificate:", error);
  677. if (callback != undefined){callback(false);}
  678. }
  679. });
  680. }
  681. //Check if the entered domain contains multiple domains
  682. function checkIfInputDomainIsMultiple(){
  683. var inputDomains = $("#domainsInput").val();
  684. if (inputDomains.includes(",")){
  685. $(".multiDomainOnly").show();
  686. }else{
  687. $(".multiDomainOnly").hide();
  688. }
  689. }
  690. //Validate if the current combinations of domain and CA supports DNS challenge
  691. function validateDNSChallengeSupport(){
  692. if ($("#domainsInput").val().includes("*")){
  693. var ca = $("#ca").dropdown("get value");
  694. if (ca == "Let's Encrypt" || ca == ""){
  695. $("#caNoDNSSupportWarning").hide();
  696. }else{
  697. $("#caNoDNSSupportWarning").show();
  698. }
  699. }else{
  700. $("#caNoDNSSupportWarning").hide();
  701. }
  702. }
  703. //call to validateDNSChallengeSupport() on #ca value change
  704. $("#ca").dropdown({
  705. onChange: function(value, text, $selectedItem) {
  706. validateDNSChallengeSupport();
  707. }
  708. });
  709. //Handle the input change event on domain input
  710. function handlePostInputAutomation(){
  711. checkIfInputDomainIsMultiple();
  712. validateDNSChallengeSupport();
  713. }
  714. function toggleDnsChallenge(){
  715. if ( $("#useDnsChallenge")[0].checked){
  716. $(".dnsChallengeOnly").show();
  717. setTimeout(function(){
  718. $("#dnsProvider").dropdown("set text", "Cloudflare");
  719. }, 500);
  720. }else{
  721. $(".dnsChallengeOnly").hide();
  722. }
  723. }
  724. //Grab the longest common suffix of all domains
  725. //not that smart technically
  726. function autoDetectMatchingRules(){
  727. var domainsString = $("#domainsInput").val();
  728. if (!domainsString.includes(",")){
  729. return domainsString;
  730. }
  731. let domains = domainsString.split(",");
  732. //Clean out any spacing between commas
  733. for (var i = 0; i < domains.length; i++){
  734. domains[i] = domains[i].trim();
  735. }
  736. function getLongestCommonSuffix(strings) {
  737. if (strings.length === 0) {
  738. return ''; // Return an empty string if the array is empty
  739. }
  740. var sortedStrings = strings.slice().sort(); // Create a sorted copy of the array
  741. var firstString = sortedStrings[0];
  742. var lastString = sortedStrings[sortedStrings.length - 1];
  743. var suffix = '';
  744. var minLength = Math.min(firstString.length, lastString.length);
  745. for (var i = 0; i < minLength; i++) {
  746. if (firstString[firstString.length - 1 - i] !== lastString[lastString.length - 1 - i]) {
  747. break; // Stop iterating if characters don't match
  748. }
  749. suffix = firstString[firstString.length - 1 - i] + suffix;
  750. }
  751. return suffix;
  752. }
  753. let longestSuffix = getLongestCommonSuffix(domains);
  754. //Check if the suffix is a valid domain
  755. if (longestSuffix.substr(0,1) == "."){
  756. //Trim off the first dot
  757. longestSuffix = longestSuffix.substr(1);
  758. }
  759. if (!longestSuffix.includes(".")){
  760. parent.msgbox("Auto Detect failed: Multiple Domains", false, 5000);
  761. return;
  762. }
  763. $("#filenameInput").val(longestSuffix);
  764. }
  765. //Handle the renew now btn click
  766. function renewNow(){
  767. $.get("/api/acme/autoRenew/renewNow", function(data){
  768. if (data.error != undefined){
  769. parent.msgbox(data.error, false, 6000);
  770. }else{
  771. parent.msgbox(data)
  772. }
  773. })
  774. }
  775. function initAutoRenewPolicy(){
  776. $.get("/api/acme/autoRenew/listDomains", function(data){
  777. if (data.error != undefined){
  778. parent.msgbox(data.error, false)
  779. }else{
  780. if (data[0] == "*"){
  781. //Auto select and renew is enabled
  782. $("#renewAllSupported").parent().checkbox("set checked");
  783. }else{
  784. //This is a list of domain files
  785. data.forEach(function(name) {
  786. $('#domainTableBody input[type="checkbox"][name="' + name + '"]').prop('checked', true);
  787. });
  788. $("#domainCertFileTable").removeClass("disabled");
  789. $("#renewNowBtn").addClass("disabled");
  790. $("#renewSelectedButton").removeClass("disabled");
  791. }
  792. }
  793. })
  794. }
  795. function saveAutoRenewPolicy(){
  796. let autoRenewAll = $("#renewAllSupported").parent().checkbox("is checked");
  797. if (autoRenewAll == true){
  798. $.cjax({
  799. url: "/api/acme/autoRenew/setDomains",
  800. method: "POST",
  801. data: {opr: "setAuto"},
  802. success: function(data){
  803. parent.msgbox("Renew policy rule updated")
  804. }
  805. });
  806. }else{
  807. let checkedNames = [];
  808. $('#domainTableBody input[type="checkbox"]:checked').each(function() {
  809. checkedNames.push($(this).attr('name'));
  810. });
  811. $.cjax({
  812. url: "/api/acme/autoRenew/setDomains",
  813. method: "POST",
  814. data: {opr: "setSelected", domains: JSON.stringify(checkedNames)},
  815. success: function(data){
  816. parent.msgbox("Renew policy rule updated")
  817. }
  818. });
  819. }
  820. }
  821. //Load the json map and create the dropdown for DNS provider names
  822. let dnsProviderNameMap = {};
  823. function initDNSProviderList(){
  824. $.get("dnsnames.json", function(namemap){
  825. dnsProviderNameMap = namemap;
  826. //Load a list of supported DNS provider from backend
  827. $("#dnsProviderList").html("");
  828. $.get("/api/acme/dns/providers", function(providerList){
  829. providerList.sort();
  830. providerList.forEach(providerid => {
  831. let providerName = providerid;
  832. if (dnsProviderNameMap[providerid] != undefined){
  833. providerName = dnsProviderNameMap[providerid];
  834. }
  835. $("#dnsProviderList").append(`<div class="item" data-value="${providerid}">${providerName}</div>`);
  836. });
  837. $("#dnsProvider").dropdown();
  838. setTimeout(function(){
  839. //The dropdown is large, it takes some time to load
  840. $("#dnsProvider").dropdown("set selected", "cloudflare");
  841. }, 300)
  842. });
  843. });
  844. }
  845. initDNSProviderList();
  846. //Clear up the input field when page load
  847. $("#filenameInput").val("");
  848. </script>
  849. </body>
  850. </html>