cert.html 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. <style>
  2. .expired.certdate{
  3. font-weight: bolder;
  4. color: #bd001c;
  5. }
  6. .valid.certdate{
  7. color: #31c071;
  8. }
  9. </style>
  10. <div class="standardContainer">
  11. <div class="ui basic segment">
  12. <h2>TLS / SSL Certificates</h2>
  13. <p>Setup TLS cert for different domains of your reverse proxy server names</p>
  14. </div>
  15. <div class="ui divider"></div>
  16. <h3>Hosts Certificates</h3>
  17. <p>Provide certificates for multiple domains reverse proxy</p>
  18. <div class="ui fluid form">
  19. <div class="three fields">
  20. <div class="field">
  21. <label>Server Name (Domain)</label>
  22. <input type="text" id="certdomain" placeholder="example.com / blog.example.com">
  23. <small><i class="exclamation circle yellow icon"></i> Match the server name with your CN/DNS entry in certificate for faster resolve time</small>
  24. </div>
  25. <div class="field">
  26. <label>Public Key (.pem)</label>
  27. <input type="file" id="pubkeySelector" onchange="handleFileSelect(event, 'pub')">
  28. <small>or .crt files in order systems</small>
  29. </div>
  30. <div class="field">
  31. <label>Private Key (.key)</label>
  32. <input type="file" id="prikeySelector" onchange="handleFileSelect(event, 'pri')">
  33. </div>
  34. </div>
  35. <button class="ui basic button" onclick="handleDomainUploadByKeypress();"><i class="ui teal upload icon"></i> Upload</button><br>
  36. <small>You have intermediate certificate? <a style="cursor:pointer;" onclick="showSideWrapper('snippet/intermediateCertConv.html');">Open Conversion Tool</a></small>
  37. </div>
  38. <div id="certUploadSuccMsg" class="ui green message" style="display:none;">
  39. <i class="ui checkmark icon"></i> Certificate for domain <span id="certUploadingDomain"></span> uploaded.
  40. </div>
  41. <div class="ui message">
  42. <h4>Tips about Server Names & SNI</h4>
  43. <div class="ui bulleted list">
  44. <div class="item">
  45. If you have two subdomains like <code>a.example.com</code> and <code>b.example.com</code> ,
  46. for faster response speed, you might want to setup them one by one (i.e. having two seperate certificate for
  47. <code>a.example.com</code> and <code>b.example.com</code>).
  48. </div>
  49. <div class="item">
  50. If you have a wildcard certificate that covers <code>*.example.com</code>,
  51. you can just enter <code>example.com</code> as server name to add a certificate.
  52. </div>
  53. <div class="item">
  54. If you have a certificate contain multiple host, you can enter the first domain in your certificate
  55. and Zoraxy will try to match the remaining CN/DNS for you.
  56. </div>
  57. </div>
  58. </div>
  59. <p>Current list of loaded certificates</p>
  60. <div>
  61. <div style="width: 100%; overflow-x: auto; margin-bottom: 1em;">
  62. <table class="ui sortable unstackable basic celled table">
  63. <thead>
  64. <tr><th>Domain</th>
  65. <th>Last Update</th>
  66. <th>Expire At</th>
  67. <th>DNS Challenge</th>
  68. <th class="no-sort">Renew</th>
  69. <th class="no-sort">Remove</th>
  70. </tr></thead>
  71. <tbody id="certifiedDomainList">
  72. </tbody>
  73. </table>
  74. </div>
  75. <button class="ui basic button" onclick="initManagedDomainCertificateList();"><i class="green refresh icon"></i> Refresh List</button>
  76. </div>
  77. <div class="ui divider"></div>
  78. <h3>Fallback Certificate</h3>
  79. <p>When there are no matching certificate for the requested server name, reverse proxy router will always fallback to this one.<br>Note that you need both of them uploaded for it to fallback properly</p>
  80. <table class="ui very basic unstackable celled table">
  81. <thead>
  82. <tr><th class="no-sort">Key Type</th>
  83. <th class="no-sort">Found</th>
  84. </tr></thead>
  85. <tbody>
  86. <tr>
  87. <td><i class="globe icon"></i> Fallback Public Key</td>
  88. <td id="pubkeyExists"></td>
  89. </tr>
  90. <tr>
  91. <td><i class="lock icon"></i> Fallback Private Key</td>
  92. <td id="prikeyExists"></td>
  93. </tr>
  94. </tbody>
  95. </table>
  96. <p style="margin-bottom: 0.4em;"><i class="ui upload icon"></i> Upload Default Keypairs</p>
  97. <div class="ui buttons">
  98. <button class="ui basic grey button" onclick="uploadPublicKey();"><i class="globe icon"></i> Public Key</button>
  99. <button class="ui basic black button" onclick="uploadPrivateKey();"><i class="black lock icon"></i> Private Key</button>
  100. </div>
  101. <div class="ui divider"></div>
  102. <h3>Certificate Authority (CA) and Auto Renew (ACME)</h3>
  103. <p>Management features regarding CA and ACME</p>
  104. <h4>Prefered Certificate Authority</h4>
  105. <p>The default CA to use when create a new subdomain proxy endpoint with TLS certificate</p>
  106. <div class="ui fluid form">
  107. <div class="field">
  108. <label>Preferred CA</label>
  109. <div class="ui selection dropdown" id="defaultCA">
  110. <input type="hidden" name="defaultCA">
  111. <i class="dropdown icon"></i>
  112. <div class="default text">Let's Encrypt</div>
  113. <div class="menu">
  114. <div class="item" data-value="Let's Encrypt">Let's Encrypt</div>
  115. <div class="item" data-value="Buypass">Buypass</div>
  116. <div class="item" data-value="ZeroSSL">ZeroSSL</div>
  117. </div>
  118. </div>
  119. </div>
  120. <div class="field">
  121. <label>ACME Email</label>
  122. <input id="prefACMEEmail" type="text" placeholder="ACME Email">
  123. </div>
  124. <button class="ui basic icon button" onclick="saveDefaultCA();"><i class="ui blue save icon"></i> Save Settings</button>
  125. </div><br>
  126. <h5>Certificate Renew / Generation (ACME) Settings</h5>
  127. <div class="ui basic segment acmeRenewStateWrapper">
  128. <h4 class="ui header" id="acmeAutoRenewer">
  129. <i class="white remove icon"></i>
  130. <div class="content">
  131. <span id="acmeAutoRenewerStatus">Disabled</span>
  132. <div class="sub header">ACME Auto-Renewer</div>
  133. </div>
  134. </h4>
  135. </div>
  136. <p>This tool provide you a graphical interface to setup auto certificate renew on your (sub)domains. You can also manually generate a certificate if one of your domain do not have certificate.</p>
  137. <button class="ui basic button" onclick="openACMEManager();"><i class="yellow external icon"></i> Open ACME Tool</button>
  138. </div>
  139. <script>
  140. var uploadPendingPublicKey = undefined;
  141. var uploadPendingPrivateKey = undefined;
  142. $("#defaultCA").dropdown();
  143. //Renew certificate by button press
  144. function renewCertificate(domain, dns, btn=undefined){
  145. let defaultCA = $("#defaultCA").dropdown("get value");
  146. if (defaultCA.trim() == ""){
  147. defaultCA = "Let's Encrypt";
  148. }
  149. //Get a new cert using ACME
  150. msgbox("Requesting certificate via " + defaultCA +"...");
  151. //Request ACME for certificate
  152. if (btn != undefined){
  153. $(btn).addClass('disabled');
  154. $(btn).html(`<i class="ui loading spinner icon"></i>`);
  155. }
  156. if (domain.includes("_.")){
  157. domain = domain.replace("_.","*.");
  158. }
  159. obtainCertificate(domain, dns, defaultCA.trim(), function(succ){
  160. if (btn != undefined){
  161. $(btn).removeClass('disabled');
  162. if (succ){
  163. $(btn).html(`<i class="ui green check icon"></i>`);
  164. }else{
  165. $(btn).html(`<i class="ui red times icon"></i>`);
  166. }
  167. setTimeout(function(){
  168. initManagedDomainCertificateList();
  169. }, 3000);
  170. }
  171. });
  172. }
  173. /*
  174. Obtain Certificate via ACME
  175. */
  176. // Obtain certificate from API, only support one domain
  177. function obtainCertificate(domains, dns, usingCa = "Let's Encrypt", callback=undefined) {
  178. //Load the ACME email from server side
  179. let acmeEmail = "";
  180. $.get("/api/acme/autoRenew/email", function(data){
  181. if (data != "" && data != undefined && data != null){
  182. acmeEmail = data;
  183. }
  184. let filename = "";
  185. let email = acmeEmail;
  186. if (acmeEmail == ""){
  187. msgbox("Unable to obtain certificate: ACME email not set", false, 8000);
  188. if (callback != undefined){
  189. callback(false);
  190. }
  191. return;
  192. }
  193. if (filename.trim() == "" && !domains.includes(",")){
  194. //Zoraxy filename are the matching name for domains.
  195. //Use the same as domains
  196. filename = domains;
  197. }else if (filename != "" && !domains.includes(",")){
  198. //Invalid settings. Force the filename to be same as domain
  199. //if there are only 1 domain
  200. filename = domains;
  201. }else{
  202. msgbox("Filename cannot be empty for certs containing multiple domains.")
  203. if (callback != undefined){
  204. callback(false);
  205. }
  206. return;
  207. }
  208. //Filename cannot contain wildcards, and wildcards are possible with DNS challenges
  209. filename = filename.replace("*", "_");
  210. $.ajax({
  211. url: "/api/acme/obtainCert",
  212. method: "GET",
  213. data: {
  214. domains: domains,
  215. filename: filename,
  216. email: email,
  217. ca: usingCa,
  218. dns: dns
  219. },
  220. success: function(response) {
  221. if (response.error) {
  222. console.log("Error:", response.error);
  223. // Show error message
  224. msgbox(response.error, false, 12000);
  225. if (callback != undefined){
  226. callback(false);
  227. }
  228. } else {
  229. console.log("Certificate installed successfully");
  230. // Show success message
  231. msgbox("Certificate installed successfully");
  232. if (callback != undefined){
  233. callback(true);
  234. }
  235. }
  236. },
  237. error: function(error) {
  238. console.log("Failed to install certificate:", error);
  239. }
  240. });
  241. });
  242. }
  243. //Delete the certificate by its domain
  244. function deleteCertificate(domain){
  245. if (confirm("Confirm delete certificate for " + domain + " ?")){
  246. $.ajax({
  247. url: "/api/cert/delete",
  248. method: "POST",
  249. data: {domain: domain},
  250. success: function(data){
  251. if (data.error != undefined){
  252. msgbox(data.error, false, 5000);
  253. }else{
  254. initManagedDomainCertificateList();
  255. initDefaultKeypairCheck();
  256. }
  257. }
  258. });
  259. }
  260. }
  261. function initAcmeStatus(){
  262. //Initialize the current default CA options
  263. $.get("/api/acme/autoRenew/email", function(data){
  264. $("#prefACMEEmail").val(data);
  265. if (data.trim() == ""){
  266. //acme email is not yet set
  267. $(".renewButton").addClass('disabled');
  268. }else{
  269. $(".renewButton").removeClass('disabled');
  270. }
  271. });
  272. $.get("/api/acme/autoRenew/ca", function(data){
  273. $("#defaultCA").dropdown("set value", data);
  274. });
  275. $.get("/api/acme/autoRenew/enable", function(data){
  276. setACMEEnableStates(data);
  277. })
  278. }
  279. //Set the status of the acme enable icon
  280. function setACMEEnableStates(enabled){
  281. $("#acmeAutoRenewerStatus").text(enabled?"Enabled":"Disabled");
  282. if (enabled){
  283. $(".acmeRenewStateWrapper").addClass("enabled");
  284. }else{
  285. $(".acmeRenewStateWrapper").removeClass("enabled");
  286. }
  287. $("#acmeAutoRenewer").find("i").attr("class", enabled?"white circle check icon":"white circle times icon");
  288. }
  289. initAcmeStatus();
  290. function saveDefaultCA(){
  291. let newDefaultEmail = $("#prefACMEEmail").val().trim();
  292. let newDefaultCA = $("#defaultCA").dropdown("get value");
  293. if (newDefaultEmail == ""){
  294. msgbox("Invalid acme email given", false);
  295. return;
  296. }
  297. $.ajax({
  298. url: "/api/acme/autoRenew/email",
  299. method: "POST",
  300. data: {"set": newDefaultEmail},
  301. success: function(data){
  302. if (data.error != undefined){
  303. msgbox(data.error, false);
  304. }else{
  305. //Update the renew button states
  306. $(".renewButton").removeClass('disabled');
  307. }
  308. }
  309. });
  310. $.ajax({
  311. url: "/api/acme/autoRenew/ca",
  312. data: {"set": newDefaultCA},
  313. method: "POST",
  314. success: function(data){
  315. if (data.error != undefined){
  316. msgbox(data.error, false);
  317. }
  318. }
  319. });
  320. msgbox("Settings updated");
  321. }
  322. //List the stored certificates
  323. function initManagedDomainCertificateList(){
  324. $.get("/api/cert/list?date=true", function(data){
  325. if (data.error != undefined){
  326. msgbox(data.error, false, 5000);
  327. }else{
  328. $("#certifiedDomainList").html("");
  329. data.sort((a,b) => {
  330. return a.Domain > b.Domain
  331. });
  332. data.forEach(entry => {
  333. let isExpired = entry.RemainingDays <= 0;
  334. $("#certifiedDomainList").append(`<tr>
  335. <td><a style="cursor: pointer;" title="Download certificate" onclick="handleCertDownload('${entry.Domain}');">${entry.Domain}</a></td>
  336. <td>${entry.LastModifiedDate}</td>
  337. <td class="${isExpired?"expired":"valid"} certdate">${entry.ExpireDate} (${!isExpired?entry.RemainingDays+" days left":"Expired"})</td>
  338. <td><i class="${entry.UseDNS?"green check": "red times"} icon"></i></td>
  339. <td><button title="Renew Certificate" class="ui mini basic icon button renewButton" onclick="renewCertificate('${entry.Domain}', '${entry.UseDNS}', this);"><i class="ui green refresh icon"></i></button></td>
  340. <td><button title="Delete key-pair" class="ui mini basic red icon button" onclick="deleteCertificate('${entry.Domain}');"><i class="ui red trash icon"></i></button></td>
  341. </tr>`);
  342. });
  343. if (data.length == 0){
  344. $("#certifiedDomainList").append(`<tr>
  345. <td colspan="4"><i class="ui times red circle icon"></i> No valid keypairs found</td>
  346. </tr>`);
  347. }
  348. }
  349. })
  350. }
  351. initManagedDomainCertificateList();
  352. function openACMEManager(){
  353. showSideWrapper('snippet/acme.html');
  354. }
  355. function handleDomainUploadByKeypress(){
  356. handleDomainKeysUpload(function(){
  357. $("#certUploadingDomain").text($("#certdomain").val().trim());
  358. //After uploaded, reset the file selector
  359. document.getElementById('pubkeySelector').value = '';
  360. document.getElementById('prikeySelector').value = '';
  361. document.getElementById('certdomain').value = '';
  362. uploadPendingPublicKey = undefined;
  363. uploadPendingPrivateKey = undefined;
  364. //Show succ
  365. $("#certUploadSuccMsg").stop().finish().slideDown("fast").delay(3000).slideUp("fast");
  366. initManagedDomainCertificateList();
  367. });
  368. }
  369. function handleCertDownload(certName){
  370. $.get("/api/cert/download?seek=true&certname=" + certName, function(data){
  371. if (data.error != undefined){
  372. //Error resolving certificate
  373. msgbox(data.error, false);
  374. }else{
  375. //Continue to download
  376. window.open("/api/cert/download?certname=" + certName);
  377. }
  378. });
  379. }
  380. //Handle domain keys upload
  381. function handleDomainKeysUpload(callback=undefined){
  382. let domain = $("#certdomain").val();
  383. if (domain.trim() == ""){
  384. msgbox("Missing domain", false, 5000);
  385. return;
  386. }
  387. if (uploadPendingPublicKey && uploadPendingPrivateKey && typeof uploadPendingPublicKey === 'object' && typeof uploadPendingPrivateKey === 'object') {
  388. const publicKeyForm = new FormData();
  389. publicKeyForm.append('file', uploadPendingPublicKey, 'publicKey');
  390. const privateKeyForm = new FormData();
  391. privateKeyForm.append('file', uploadPendingPrivateKey, 'privateKey');
  392. const publicKeyRequest = new XMLHttpRequest();
  393. publicKeyRequest.open('POST', '/api/cert/upload?ktype=pub&domain=' + domain);
  394. publicKeyRequest.onreadystatechange = function() {
  395. if (publicKeyRequest.readyState === XMLHttpRequest.DONE) {
  396. if (publicKeyRequest.status !== 200) {
  397. msgbox('Error uploading public key: ' + publicKeyRequest.statusText, false, 5000);
  398. }
  399. if (callback != undefined){
  400. callback();
  401. }
  402. }
  403. };
  404. publicKeyRequest.send(publicKeyForm);
  405. const privateKeyRequest = new XMLHttpRequest();
  406. privateKeyRequest.open('POST', '/api/cert/upload?ktype=pri&domain=' + domain);
  407. privateKeyRequest.onreadystatechange = function() {
  408. if (privateKeyRequest.readyState === XMLHttpRequest.DONE) {
  409. if (privateKeyRequest.status !== 200) {
  410. msgbox('Error uploading private key: ' + privateKeyRequest.statusText, false, 5000);
  411. }
  412. if (callback != undefined){
  413. callback();
  414. }
  415. }
  416. };
  417. privateKeyRequest.send(privateKeyForm);
  418. } else {
  419. msgbox('One or both of the files is missing or not a file object');
  420. }
  421. }
  422. //Handlers for selecting domain based key pairs
  423. //ktype = {"pub" / "pri"}
  424. function handleFileSelect(event, ktype="pub") {
  425. const file = event.target.files[0];
  426. //const fileNameInput = document.getElementById('selected-file-name');
  427. if (ktype == "pub"){
  428. uploadPendingPublicKey = file;
  429. }else if (ktype == "pri"){
  430. uploadPendingPrivateKey = file;
  431. }
  432. //fileNameInput.value = file.name;
  433. }
  434. //Check if the default keypairs exists
  435. function initDefaultKeypairCheck(){
  436. $.get("/api/cert/checkDefault", function(data){
  437. let tick = `<i class="ui green checkmark icon"></i>`;
  438. let cross = `<i class="ui red times icon"></i>`;
  439. $("#pubkeyExists").html(data.DefaultPubExists?tick:cross);
  440. $("#prikeyExists").html(data.DefaultPriExists?tick:cross);
  441. });
  442. }
  443. initDefaultKeypairCheck();
  444. function uploadPrivateKey(){
  445. // create file input element
  446. const input = document.createElement('input');
  447. input.type = 'file';
  448. // add change listener to file input
  449. input.addEventListener('change', () => {
  450. // create form data object
  451. const formData = new FormData();
  452. // add selected file to form data
  453. formData.append('file', input.files[0]);
  454. // send form data to server
  455. fetch('/api/cert/upload?ktype=pri', {
  456. method: 'POST',
  457. body: formData
  458. })
  459. .then(response => {
  460. initDefaultKeypairCheck();
  461. if (response.ok) {
  462. msgbox('File upload successful!');
  463. } else {
  464. response.text().then(text => {
  465. msgbox(text, false, 5000);
  466. });
  467. //console.log(response.text());
  468. //alert('File upload failed!');
  469. }
  470. })
  471. .catch(error => {
  472. msgbox('An error occurred while uploading the file.', false, 5000);
  473. console.error(error);
  474. });
  475. });
  476. // click file input to open file selector
  477. input.click();
  478. }
  479. function uploadPublicKey() {
  480. // create file input element
  481. const input = document.createElement('input');
  482. input.type = 'file';
  483. // add change listener to file input
  484. input.addEventListener('change', () => {
  485. // create form data object
  486. const formData = new FormData();
  487. // add selected file to form data
  488. formData.append('file', input.files[0]);
  489. // send form data to server
  490. fetch('/api/cert/upload?ktype=pub', {
  491. method: 'POST',
  492. body: formData
  493. })
  494. .then(response => {
  495. if (response.ok) {
  496. msgbox('File upload successful!');
  497. initDefaultKeypairCheck();
  498. } else {
  499. response.text().then(text => {
  500. msgbox(text, false, 5000);
  501. });
  502. //console.log(response.text());
  503. //alert('File upload failed!');
  504. }
  505. })
  506. .catch(error => {
  507. msgbox('An error occurred while uploading the file.', false, 5000);
  508. console.error(error);
  509. });
  510. });
  511. // click file input to open file selector
  512. input.click();
  513. }
  514. </script>