acme.html 34 KB

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