acme.html 34 KB

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