easy-devops 1.3.5 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +1 -0
  2. package/dist/ui/assets/index-Bu7af-Kj.css +1 -0
  3. package/dist/ui/assets/index-gndgYe3K.js +532 -0
  4. package/dist/ui/assets/socket-Bv0wCEgi.js +65 -0
  5. package/dist/ui/index.html +2 -2
  6. package/package.json +2 -2
  7. package/src/cli/index.js +8 -0
  8. package/src/cli/managers/domain-manager.js +37 -6
  9. package/src/cli/managers/nginx-manager.js +14 -5
  10. package/src/cli/managers/node-manager.js +19 -13
  11. package/src/cli/managers/ssl-manager.js +89 -26
  12. package/src/cli/menu.js +8 -2
  13. package/src/cli/menus/cleanup.js +4 -2
  14. package/src/cli/menus/dashboard.js +22 -15
  15. package/src/cli/menus/hub.js +381 -0
  16. package/src/cli/menus/runtime.js +12 -0
  17. package/src/cli/menus/service.js +28 -10
  18. package/src/cli/menus/settings.js +46 -12
  19. package/src/cli/menus/uninstall.js +13 -5
  20. package/src/cli/menus/update.js +24 -14
  21. package/src/cli/ui/page.js +123 -0
  22. package/src/core/cert-operations.js +34 -4
  23. package/src/core/cert-reader.js +67 -22
  24. package/src/core/cert-renewal.js +65 -9
  25. package/src/core/cert-suggest.js +120 -0
  26. package/src/core/cleanup.js +221 -1
  27. package/src/core/cloudflare-ips.js +161 -0
  28. package/src/core/daemon/ipc.js +1 -1
  29. package/src/core/daemon/lock.js +296 -9
  30. package/src/core/dashboardProcess.js +134 -6
  31. package/src/core/deploy/apps.js +36 -62
  32. package/src/core/deploy/deployKey.js +331 -0
  33. package/src/core/deploy/domainLink.js +280 -23
  34. package/src/core/deploy/engine.js +382 -63
  35. package/src/core/deploy/ezfile.js +496 -29
  36. package/src/core/deploy/githubApi.js +100 -13
  37. package/src/core/deploy/hubCommands.js +158 -18
  38. package/src/core/deploy/status.js +28 -1
  39. package/src/core/domains-db.js +1 -0
  40. package/src/core/hub/agent.js +238 -32
  41. package/src/core/hub/deployProgress.js +411 -0
  42. package/src/core/hubConnect.js +205 -0
  43. package/src/core/hubPermissions.js +48 -10
  44. package/src/core/jobs/bus.js +1 -1
  45. package/src/core/jobs/owner.js +268 -6
  46. package/src/core/nginx-conf-generator.js +124 -19
  47. package/src/core/notifications/claim.js +26 -3
  48. package/src/core/permissions.js +277 -59
  49. package/src/core/platform.js +48 -2
  50. package/src/core/runner.js +96 -40
  51. package/src/core/ssl/preflight.js +548 -0
  52. package/src/core/ssl/progress.js +196 -0
  53. package/src/core/ssl-issuer.js +502 -148
  54. package/src/core/validators.js +24 -0
  55. package/src/dashboard/controllers/authController.js +12 -5
  56. package/src/dashboard/controllers/deploymentsController.js +76 -11
  57. package/src/dashboard/controllers/domainsController.js +35 -1
  58. package/src/dashboard/controllers/hubController.js +4 -3
  59. package/src/dashboard/controllers/settingsController.js +73 -68
  60. package/src/dashboard/controllers/sslController.js +135 -15
  61. package/src/dashboard/public/js/app.js +42 -7
  62. package/src/dashboard/routes/deployments.js +2 -0
  63. package/src/dashboard/routes/domains.js +1 -0
  64. package/src/dashboard/server.js +73 -8
  65. package/src/dashboard/socketManager.js +19 -25
  66. package/src/dashboard/views/partials/settings-panel.ejs +29 -10
  67. package/dist/ui/assets/index-BUpPxWmp.css +0 -1
  68. package/dist/ui/assets/index-DD0JjK0Q.js +0 -475
  69. package/dist/ui/assets/socket-4tfdap-e.js +0 -65
@@ -25,6 +25,7 @@ import ora from 'ora';
25
25
  import { dbGet, dbSet } from '../../core/db.js';
26
26
  import { loadConfig } from '../../core/config.js';
27
27
  import { getDashboardStatus, startDashboard, stopDashboard } from '../../core/dashboardProcess.js';
28
+ import { page, pause } from '../ui/page.js';
28
29
 
29
30
 
30
31
  // ─── Recover interrupted update ───────────────────────────────────────────────
@@ -150,15 +151,29 @@ async function warnStaleDaemon(targetVersion) {
150
151
  *
151
152
  * @param {Object} [opts]
152
153
  * @param {boolean} [opts.yes] Skip the confirmation
154
+ * @param {boolean} [opts.heading] Print the "Update Easy DevOps" heading
153
155
  * @returns {Promise<number>} Process exit code
154
156
  */
155
- export async function updateCommand({ yes = false } = {}) {
157
+ export async function updateCommand({ yes = false, heading = true } = {}) {
158
+ const code = await runUpdate({ yes, heading });
159
+
160
+ // A long operation's outcome is read, not scrolled past. No-op without a
161
+ // TTY, so `ezz update` in a script is unaffected. A dismissed confirmation
162
+ // (code 2) ran nothing and has nothing to read.
163
+ if (code !== 2) await pause();
164
+
165
+ return code;
166
+ }
167
+
168
+ async function runUpdate({ yes = false, heading = true } = {}) {
156
169
  const updater = await import('../../core/updater.js');
157
170
 
158
- console.log();
159
- console.log(' ' + chalk.bold('Update Easy DevOps'));
160
- console.log(' ' + chalk.gray('-'.repeat(58)));
161
- console.log();
171
+ if (heading) {
172
+ console.log();
173
+ console.log(' ' + chalk.bold('Update Easy DevOps'));
174
+ console.log(' ' + chalk.gray('-'.repeat(58)));
175
+ console.log();
176
+ }
162
177
 
163
178
  const spinner = ora('Checking the registry...').start();
164
179
  const check = await updater.checkForUpdate();
@@ -282,18 +297,13 @@ export default async function updateMenu() {
282
297
  // A crashed previous update is finished before another one is offered.
283
298
  await recoverIfNeeded();
284
299
 
285
- let code;
300
+ page(['Update']);
301
+
286
302
  try {
287
- code = await updateCommand();
303
+ // The page header is the heading; the command's own title would repeat it.
304
+ await updateCommand({ heading: false });
288
305
  } catch (err) {
289
306
  if (err.name === 'ExitPromptError') return;
290
307
  throw err;
291
308
  }
292
-
293
- // Dismissed at the confirmation prompt: nothing ran, nothing to read.
294
- if (code === 2) return;
295
-
296
- try {
297
- await inquirer.prompt([{ type: 'input', name: '_', message: 'Press Enter to continue...' }]);
298
- } catch { /* ExitPromptError on the pause */ }
299
309
  }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * cli/ui/page.js
3
+ *
4
+ * One way to draw a CLI page, so every menu looks the same and the screen holds
5
+ * one menu instead of a scrollback of every menu visited on the way here.
6
+ *
7
+ * page(['SSL', 'Issue']);
8
+ *
9
+ * clears the screen (only where that is safe) and prints the breadcrumb
10
+ *
11
+ * Easy DevOps > SSL > Issue
12
+ *
13
+ * before the page body. `pause()` is the other half: a long operation leaves
14
+ * its result on screen until Enter, and returns at once when nobody can press
15
+ * it (a pipe, a script, CI), so `ezz service start | tee log` still works.
16
+ */
17
+
18
+ import chalk from 'chalk';
19
+ import inquirer from 'inquirer';
20
+
21
+ /** The one label every submenu uses for "leave this menu". */
22
+ export const BACK = '← Back';
23
+ /** The one label the main menu uses for "leave the program". */
24
+ export const EXIT = '✖ Exit';
25
+
26
+ /**
27
+ * The clear sequence.
28
+ *
29
+ * `ESC[2J` erases the visible screen, `ESC[3J` erases the scrollback (so the
30
+ * previous menu cannot be scrolled back into view, which is the whole point),
31
+ * and `ESC[H` homes the cursor. Windows Terminal, PowerShell 7 and every
32
+ * mainstream Linux terminal (xterm, VTE, kitty, alacritty) understand all
33
+ * three. The legacy conhost window does not implement `ESC[3J`; it ignores
34
+ * that one parameter and still clears and homes on the other two, which is
35
+ * why this sequence is used rather than `console.clear()`: Node's
36
+ * `console.clear()` writes the same kind of escape on POSIX but a bare form
37
+ * feed on some Windows consoles, which leaves the previous page visible.
38
+ *
39
+ * Colour is never part of this: chalk is left to decide for itself, so a pipe
40
+ * gets plain text.
41
+ */
42
+ const CLEAR_SEQUENCE = '\x1b[2J\x1b[3J\x1b[H';
43
+
44
+ /** What "truthy" means for an environment variable: set and not '0'. */
45
+ function envTruthy(value) {
46
+ if (value === undefined || value === null) return false;
47
+ const text = String(value).trim().toLowerCase();
48
+ return text !== '' && text !== '0' && text !== 'false';
49
+ }
50
+
51
+ /**
52
+ * Whether the screen may be cleared, as a pure decision so it can be tested
53
+ * without a terminal.
54
+ *
55
+ * Clearing is allowed ONLY when:
56
+ * - stdout is a real TTY (a pipe or a file gets every line, never an escape);
57
+ * - CI is not set, because a CI log is read later and must stay complete;
58
+ * - this is not an EZ_TEST-driven run with no TTY, where the output is being
59
+ * captured by a suite and a clear would only add noise to the assertion.
60
+ *
61
+ * @param {Object} [opts]
62
+ * @param {boolean} [opts.isTTY] Defaults to process.stdout.isTTY
63
+ * @param {Object} [opts.env] Defaults to process.env
64
+ * @returns {boolean}
65
+ */
66
+ export function shouldClearScreen({
67
+ isTTY = Boolean(process.stdout.isTTY),
68
+ env = process.env,
69
+ } = {}) {
70
+ const inCI = envTruthy(env.CI);
71
+ const testCapture = envTruthy(env.EZ_TEST) && !isTTY;
72
+ return Boolean(isTTY) && !inCI && !testCapture;
73
+ }
74
+
75
+ /** `Easy DevOps > SSL > Issue`, with the product name in the brand colour. */
76
+ function breadcrumb(titlePath) {
77
+ const parts = ['Easy DevOps', ...titlePath.filter(Boolean).map(String)];
78
+ const separator = chalk.gray(' > ');
79
+ return parts
80
+ .map((part, index) => (index === 0 ? chalk.hex('#d64a29').bold(part) : chalk.bold.white(part)))
81
+ .join(separator);
82
+ }
83
+
84
+ /**
85
+ * Starts a page: clears the screen where that is safe, then prints the
86
+ * breadcrumb. Pass `{ clear: false }` for a command whose output is not a
87
+ * menu screen (`ezz service status`, `ezz cleanup`): it gets no escape code
88
+ * even in a terminal.
89
+ *
90
+ * @param {string[]} [titlePath] e.g. ['SSL', 'Issue']
91
+ * @param {Object} [opts]
92
+ * @param {boolean} [opts.clear] Force the decision one way or the other
93
+ */
94
+ export function page(titlePath = [], { clear } = {}) {
95
+ const clearNow = clear === undefined
96
+ ? shouldClearScreen()
97
+ : Boolean(clear) && Boolean(process.stdout.isTTY) && !envTruthy(process.env.CI);
98
+
99
+ if (clearNow) process.stdout.write(CLEAR_SEQUENCE);
100
+ process.stdout.write(`${breadcrumb(titlePath)}\n`);
101
+ }
102
+
103
+ /** True only when a person can actually see a prompt and answer it. */
104
+ export function isInteractiveIO() {
105
+ return Boolean(process.stdin.isTTY && process.stdout.isTTY);
106
+ }
107
+
108
+ /**
109
+ * Waits for Enter so a result stays on screen — and returns immediately when
110
+ * there is no TTY (or in CI), because a prompt there would hang a script.
111
+ *
112
+ * @param {string} [message]
113
+ */
114
+ export async function pause(message = 'Press Enter to continue') {
115
+ if (!isInteractiveIO() || envTruthy(process.env.CI)) return;
116
+
117
+ try {
118
+ await inquirer.prompt([{ type: 'input', name: '_', message }]);
119
+ } catch (err) {
120
+ // Ctrl+C at the pause is the user leaving, not a failed command.
121
+ if (err?.name !== 'ExitPromptError') throw err;
122
+ }
123
+ }
@@ -16,6 +16,7 @@ import { describeIssuance, issueCertificate, prepareDomainForHttpChallenge } fro
16
16
  import { renewCertificate, describeRenewal, failureReason } from './cert-renewal.js';
17
17
  import { bumpHubRevision } from './hubLink.js';
18
18
  import { listAllCerts } from './cert-reader.js';
19
+ import { findCertificateForDomain } from './cert-suggest.js';
19
20
  import { getDomains, findDomain } from './domains-db.js';
20
21
 
21
22
  /** Shape shared by every SSL result so the Hub can render it uniformly. */
@@ -63,13 +64,23 @@ async function prepare(domainName) {
63
64
  /**
64
65
  * Handles a hub:manageSSL command.
65
66
  *
66
- * @param {Object} payload { action, domain?, www? }
67
+ * @param {Object} payload { action, domain?, www?, opId? }
68
+ * @param {Object} [options]
69
+ * @param {(step: string, status: string, detail?: string) => void} [options.onProgress]
70
+ * Live command progress from core/hub/agent.js. Step is the SSL stage name.
67
71
  * @returns {Promise<Object>} { ok, error, ... }
68
72
  */
69
- export async function handleHubSslCommand(payload) {
73
+ export async function handleHubSslCommand(payload, options = {}) {
70
74
  const { action, domain } = payload ?? {};
75
+ const { onProgress = null } = options ?? {};
71
76
  const config = loadConfig();
72
77
 
78
+ // Every SSL stage belongs to a name; the Hub needs that to show renewAll
79
+ // per domain. The agent's onProgress accepts it as its fourth argument.
80
+ const progressFor = (name) => (typeof onProgress === 'function'
81
+ ? (step, status, detail) => onProgress(step, status, detail, name)
82
+ : null);
83
+
73
84
  switch (action) {
74
85
  // ── Renew one ─────────────────────────────────────────────────────────
75
86
  case 'renew': {
@@ -79,7 +90,11 @@ export async function handleHubSslCommand(payload) {
79
90
  // renewCertificate() keeps the names the certificate already covers
80
91
  // (a `www` certificate stays a `www` certificate), prepares the nginx
81
92
  // config, and reloads nginx afterwards.
82
- const result = await renewCertificate(domain, { email: config.acmeEmail });
93
+ const result = await renewCertificate(domain, {
94
+ email: config.acmeEmail,
95
+ opId: payload?.opId,
96
+ onProgress: progressFor(domain),
97
+ });
83
98
  const out = renewalResult(domain, result);
84
99
  if (out.ok) bumpHubRevision();
85
100
  console.log('[hubAgent] ssl renew:', domain, out.ok ? 'OK' : 'FAILED', '—', out.summary || out.error);
@@ -97,7 +112,11 @@ export async function handleHubSslCommand(payload) {
97
112
  const renewed = [];
98
113
 
99
114
  for (const cert of expiring) {
100
- const result = await renewCertificate(cert.domain, { email: config.acmeEmail });
115
+ const result = await renewCertificate(cert.domain, {
116
+ email: config.acmeEmail,
117
+ opId: payload?.opId,
118
+ onProgress: progressFor(cert.domain),
119
+ });
101
120
  renewed.push(renewalResult(cert.domain, result));
102
121
  }
103
122
 
@@ -131,6 +150,8 @@ export async function handleHubSslCommand(payload) {
131
150
  www: Boolean(payload?.www),
132
151
  validationMethod: 'http',
133
152
  email: config.acmeEmail,
153
+ opId: payload?.opId,
154
+ onProgress: progressFor(domain),
134
155
  });
135
156
 
136
157
  const out = issuanceResult(domain, result);
@@ -139,6 +160,15 @@ export async function handleHubSslCommand(payload) {
139
160
  return out;
140
161
  }
141
162
 
163
+ // ── Suggest an existing certificate ──────────────────────────────────
164
+ // Read-only, like the server's own dashboard: it reports which
165
+ // certificate could serve the domain and the paths that hold it. The Hub
166
+ // fills them into the form and the operator still has to save.
167
+ case 'suggest': {
168
+ if (!domain) return { ok: false, error: 'domain is required' };
169
+ return { ok: true, ...(await findCertificateForDomain(domain)) };
170
+ }
171
+
142
172
  // ── Delete a certificate ──────────────────────────────────────────────
143
173
  case 'delete': {
144
174
  if (!domain) return { ok: false, error: 'domain is required' };
@@ -1,11 +1,24 @@
1
1
  import fs from 'fs/promises';
2
2
  import path from 'path';
3
+ import { X509Certificate } from 'node:crypto';
3
4
  import { run } from './shell.js';
4
5
  import { loadConfig } from './config.js';
5
6
 
6
- export async function listAllCerts() {
7
- const { sslDir } = loadConfig();
8
- const liveDir = sslDir;
7
+ /**
8
+ * Reads every certificate directory.
9
+ *
10
+ * Two different "there is no usable certificate here" cases are kept apart:
11
+ *
12
+ * not_issued the directory exists but no fullchain.pem was ever written
13
+ * (a failed first issuance leaves exactly this), label
14
+ * "Not issued yet"
15
+ * unreadable fullchain.pem exists but neither Node nor openssl can parse it
16
+ *
17
+ * Collapsing them into one "error" made a domain whose certificate had simply
18
+ * not been requested yet look broken.
19
+ */
20
+ export async function listAllCerts({ sslDir, includeUnusable = false } = {}) {
21
+ const liveDir = sslDir ?? loadConfig().sslDir;
9
22
  let entries;
10
23
  try {
11
24
  entries = await fs.readdir(liveDir, { withFileTypes: true });
@@ -16,10 +29,13 @@ export async function listAllCerts() {
16
29
  const dirs = entries.filter(e => e.isDirectory() && !e.name.startsWith('.'));
17
30
  const certs = [];
18
31
  for (const dir of dirs) {
19
- const { expiry, daysLeft } = await getCertExpiry(dir.name);
32
+ const info = await getCertExpiry(dir.name, { sslDir: liveDir });
33
+ const { expiry, daysLeft } = info;
20
34
  let status;
21
- if (daysLeft === null) {
22
- status = 'error';
35
+ if (info.state === 'not_issued') {
36
+ status = 'not_issued';
37
+ } else if (info.state === 'unreadable' || daysLeft === null) {
38
+ status = 'unreadable';
23
39
  } else if (daysLeft <= 0) {
24
40
  status = 'expired';
25
41
  } else if (daysLeft < 30) {
@@ -27,33 +43,62 @@ export async function listAllCerts() {
27
43
  } else {
28
44
  status = 'valid';
29
45
  }
30
- certs.push({ domain: dir.name, expiry: expiry?.toISOString() ?? null, daysLeft, status });
46
+ // Callers that act on certificates (suggestion, renewal, monitoring) must
47
+ // see only usable ones; the SSL list passes includeUnusable so it can show
48
+ // "Not issued yet" instead of silently omitting the domain.
49
+ if (!includeUnusable && (status === 'not_issued' || status === 'unreadable')) continue;
50
+ certs.push({
51
+ domain: dir.name,
52
+ expiry: expiry?.toISOString() ?? null,
53
+ daysLeft,
54
+ status,
55
+ label: status === 'not_issued' ? 'Not issued yet' : null,
56
+ });
31
57
  }
32
58
  return certs;
33
59
  }
34
60
 
35
- export async function getCertExpiry(name) {
36
- const { sslDir } = loadConfig();
37
- const certPath = path.join(sslDir, name, 'fullchain.pem');
61
+ /**
62
+ * Expiry of one certificate, with the reason when there is none.
63
+ *
64
+ * @returns {Promise<{ expiry: Date|null, daysLeft: number|null,
65
+ * valid: boolean|null, state: 'ok'|'not_issued'|'unreadable' }>}
66
+ */
67
+ export async function getCertExpiry(name, { sslDir } = {}) {
68
+ const certPath = path.join(sslDir ?? loadConfig().sslDir, name, 'fullchain.pem');
38
69
 
39
- const result = await run(`openssl x509 -enddate -noout -in "${certPath}"`);
70
+ let pem = null;
71
+ try {
72
+ pem = await fs.readFile(certPath, 'utf8');
73
+ } catch (err) {
74
+ if (err.code === 'ENOENT') {
75
+ return { expiry: null, daysLeft: null, valid: null, state: 'not_issued' };
76
+ }
77
+ return { expiry: null, daysLeft: null, valid: null, state: 'unreadable' };
78
+ }
40
79
 
80
+ // Node's own parser first: it works on Windows without an openssl binary.
81
+ try {
82
+ const cert = new X509Certificate(pem);
83
+ const expiry = new Date(cert.validTo);
84
+ if (!Number.isNaN(expiry.getTime())) {
85
+ const daysLeft = Math.floor((expiry - Date.now()) / 86400000);
86
+ return { expiry, daysLeft, valid: daysLeft > 0, state: 'ok' };
87
+ }
88
+ } catch { /* fall through to openssl */ }
89
+
90
+ // openssl remains the fallback for a PEM chain or an older/odd encoding.
91
+ const result = await run(`openssl x509 -enddate -noout -in "${certPath}"`);
41
92
  if (result.success && result.stdout) {
42
93
  const match = result.stdout.match(/notAfter=(.+)/);
43
94
  if (match) {
44
95
  const expiry = new Date(match[1].trim());
45
- const daysLeft = Math.floor((expiry - Date.now()) / 86400000);
46
- return { expiry, daysLeft, valid: daysLeft > 0 };
96
+ if (!Number.isNaN(expiry.getTime())) {
97
+ const daysLeft = Math.floor((expiry - Date.now()) / 86400000);
98
+ return { expiry, daysLeft, valid: daysLeft > 0, state: 'ok' };
99
+ }
47
100
  }
48
101
  }
49
102
 
50
- // Fallback: mtime + 90 days if file exists but openssl failed
51
- try {
52
- const stat = await fs.stat(certPath);
53
- const expiry = new Date(stat.mtime.getTime() + 90 * 86400000);
54
- const daysLeft = Math.floor((expiry - Date.now()) / 86400000);
55
- return { expiry, daysLeft, valid: daysLeft > 0 };
56
- } catch {
57
- return { expiry: null, daysLeft: null, valid: null };
58
- }
103
+ return { expiry: null, daysLeft: null, valid: null, state: 'unreadable' };
59
104
  }
@@ -54,7 +54,9 @@ import {
54
54
  issueCertificate,
55
55
  prepareDomainForHttpChallenge,
56
56
  reloadNginx,
57
+ verifyServedCertificate,
57
58
  } from './ssl-issuer.js';
59
+ import { createSslProgress, isValidOpId, newOpId } from './ssl/progress.js';
58
60
 
59
61
  /** Renew this many days before expiry unless the setting says otherwise. */
60
62
  export const DEFAULT_AUTO_RENEW_DAYS = 7;
@@ -197,6 +199,10 @@ export function failureReason(result) {
197
199
  return String(cause).split('\n')[0].trim();
198
200
  }
199
201
 
202
+ function firstLine(value) {
203
+ return String(value ?? '').split('\n')[0].trim();
204
+ }
205
+
200
206
  /**
201
207
  * Renews one certificate, keeping the names it already covers, and reloads
202
208
  * nginx when nginx was left running so the new certificate is actually served.
@@ -215,7 +221,11 @@ export function failureReason(result) {
215
221
  * @returns {Promise<Object>}
216
222
  */
217
223
  export async function renewCertificate(domainName, options = {}) {
218
- const { email = null, mode = null, unattended = false, deps = {} } = options;
224
+ const {
225
+ email = null, mode = null, unattended = false, deps = {},
226
+ opId: rawOpId = null, onEvent = null, onProgress = null,
227
+ behindCloudflare = false,
228
+ } = options;
219
229
  const {
220
230
  issue = issueCertificate,
221
231
  prepare = prepareDomainForHttpChallenge,
@@ -223,8 +233,16 @@ export async function renewCertificate(domainName, options = {}) {
223
233
  nginxStatus = getStatus,
224
234
  describe = describeCertificate,
225
235
  lookupDomain = findDomain,
236
+ verify = verifyServedCertificate,
226
237
  } = deps;
227
238
 
239
+ const opId = isValidOpId(rawOpId) ? rawOpId : newOpId();
240
+ const progress = createSslProgress({
241
+ opId, domain: domainName, onEvent, onProgress,
242
+ ...(deps.progress ?? {}),
243
+ });
244
+ const report = (stage, status, detail) => progress.report(stage, status, detail);
245
+
228
246
  const config = loadConfig();
229
247
  const info = await describe(domainName);
230
248
 
@@ -287,6 +305,11 @@ export async function renewCertificate(domainName, options = {}) {
287
305
  www: info.www,
288
306
  validationMethod: 'http',
289
307
  email: email || config.acmeEmail,
308
+ opId,
309
+ onEvent,
310
+ onProgress,
311
+ // This caller reports the nginx stages itself, so they appear exactly once.
312
+ manageNginx: false,
290
313
  ...(chosenMode ? { mode: chosenMode } : {}),
291
314
  });
292
315
 
@@ -294,14 +317,46 @@ export async function renewCertificate(domainName, options = {}) {
294
317
  // Proxy mode leaves it running with the old one in memory.
295
318
  let nginxReloaded = null;
296
319
  let reloadDetail = null;
297
- if (result?.success && result.mode === CHALLENGE_MODES.PROXY) {
298
- try {
299
- const reloaded = await reload();
300
- nginxReloaded = Boolean(reloaded?.ok);
301
- if (!nginxReloaded) reloadDetail = reloaded?.output ?? null;
302
- } catch (err) {
303
- nginxReloaded = false;
304
- reloadDetail = err.message;
320
+ let httpsVerified = null;
321
+
322
+ if (result?.success) {
323
+ if (result.mode === CHALLENGE_MODES.PROXY) {
324
+ report('nginx config test', 'running');
325
+ try {
326
+ const reloaded = await reload();
327
+ nginxReloaded = Boolean(reloaded?.ok);
328
+ if (!nginxReloaded) reloadDetail = reloaded?.output ?? null;
329
+ } catch (err) {
330
+ nginxReloaded = false;
331
+ reloadDetail = err.message;
332
+ }
333
+ const detail = nginxReloaded ? undefined : (firstLine(reloadDetail) || 'nginx did not reload');
334
+ report('nginx config test', nginxReloaded ? 'ok' : 'failed', detail);
335
+ report('nginx reload', 'running');
336
+ report('nginx reload', nginxReloaded ? 'ok' : 'failed', detail);
337
+ } else if (result.mode === 'dns-01') {
338
+ report('nginx config test', 'skipped', 'DNS-01 leaves nginx untouched');
339
+ report('nginx reload', 'skipped', 'DNS-01 leaves nginx untouched');
340
+ } else {
341
+ report('nginx config test', 'skipped', 'standalone mode restarted nginx');
342
+ report('nginx reload', 'skipped', 'standalone mode restarted nginx');
343
+ }
344
+
345
+ const proxied = Boolean(behindCloudflare || result.preflight?.proxied);
346
+ if (proxied) {
347
+ report('https verified', 'skipped', "served by Cloudflare's edge");
348
+ } else if (!result.certPath) {
349
+ report('https verified', 'skipped', 'no certificate file to compare');
350
+ } else {
351
+ report('https verified', 'running');
352
+ try {
353
+ const checked = await verify(domainName, result.certPath);
354
+ httpsVerified = Boolean(checked?.ok);
355
+ report('https verified', checked?.ok ? 'ok' : 'failed', checked?.ok ? undefined : checked?.message);
356
+ } catch (err) {
357
+ httpsVerified = false;
358
+ report('https verified', 'failed', firstLine(err.message));
359
+ }
305
360
  }
306
361
  }
307
362
 
@@ -313,6 +368,7 @@ export async function renewCertificate(domainName, options = {}) {
313
368
  configRegenerated: Boolean(result?.configRegenerated || prepared?.regenerated),
314
369
  nginxReloaded,
315
370
  reloadDetail,
371
+ httpsVerified,
316
372
  };
317
373
  }
318
374
 
@@ -0,0 +1,120 @@
1
+ /**
2
+ * core/cert-suggest.js
3
+ *
4
+ * Finds an existing certificate that can serve a domain, so a domain added
5
+ * without SSL can be pointed at it in one click instead of having the operator
6
+ * retype a path that is almost always `<sslDir>/<name>/fullchain.pem`.
7
+ *
8
+ * Matching is deliberately conservative — a wrong suggestion writes the wrong
9
+ * certificate onto a live site:
10
+ *
11
+ * 1. exact the certificate directory is named after the domain, which is
12
+ * how every certificate issued here is stored;
13
+ * 2. san one of the certificate's names is the domain itself (a cert
14
+ * issued for `example.com` that lists `api.example.com`);
15
+ * 3. wildcard a name like `*.example.com` covers `api.example.com` — but
16
+ * only one label, because `*.example.com` does not cover
17
+ * `a.b.example.com` (RFC 6125), and offering it would produce a
18
+ * site that fails certificate validation.
19
+ *
20
+ * Exact beats SAN beats wildcard; among wildcards the most specific suffix
21
+ * wins. Nothing is suggested from a certificate that could not be read.
22
+ */
23
+
24
+ import { loadConfig } from './config.js';
25
+ import { listAllCerts } from './cert-reader.js';
26
+ import { describeCertificate } from './cert-renewal.js';
27
+ import { getDefaultCertPaths } from './nginx-conf-generator.js';
28
+
29
+ const MATCH_RANK = { exact: 0, san: 1, wildcard: 2 };
30
+
31
+ /** Lowercase, trim, drop trailing dots. `*.` is meaningful and kept. */
32
+ export function normalizeForMatch(value) {
33
+ return String(value ?? '').trim().toLowerCase().replace(/\.+$/, '');
34
+ }
35
+
36
+ /** True when a certificate name like `*.example.com` covers `api.example.com`. */
37
+ export function wildcardCovers(pattern, domain) {
38
+ const p = normalizeForMatch(pattern);
39
+ const d = normalizeForMatch(domain);
40
+ if (!p.startsWith('*.') || !d) return false;
41
+
42
+ const suffix = p.slice(2);
43
+ if (!suffix || !d.endsWith(`.${suffix}`)) return false;
44
+
45
+ const label = d.slice(0, -(suffix.length + 1));
46
+ return label.length > 0 && !label.includes('.');
47
+ }
48
+
49
+ /**
50
+ * @param {string} domainName The bare domain (a leading `*.` is ignored)
51
+ * @param {Object} [opts]
52
+ * @param {string} [opts.sslDir] Certificates directory (defaults to the setting)
53
+ * @returns {Promise<{ found: false } | {
54
+ * found: true,
55
+ * match: 'exact'|'san'|'wildcard',
56
+ * certificate: {
57
+ * domain: string, names: string[], certPath: string, keyPath: string,
58
+ * expiry: string|null, daysLeft: number|null, status: string
59
+ * }
60
+ * }>}
61
+ */
62
+ export async function findCertificateForDomain(domainName, { sslDir } = {}) {
63
+ const dir = sslDir ?? loadConfig().sslDir;
64
+ const domain = normalizeForMatch(String(domainName ?? '').replace(/^\*\./, ''));
65
+ if (!domain) return { found: false };
66
+
67
+ // A folder whose certificate cannot be read has no usable paths to offer.
68
+ const certs = (await listAllCerts({ sslDir: dir })).filter((c) => c.status !== 'error');
69
+ if (certs.length === 0) return { found: false };
70
+
71
+ const candidates = [];
72
+ for (const cert of certs) {
73
+ if (normalizeForMatch(cert.domain) === domain) {
74
+ candidates.push({ match: 'exact', cert, specificity: 0 });
75
+ }
76
+ }
77
+
78
+ if (candidates.length === 0) {
79
+ for (const cert of certs) {
80
+ const info = await describeCertificate(cert.domain, { sslDir: dir });
81
+ const names = (info.names ?? []).map(normalizeForMatch);
82
+
83
+ if (names.includes(domain)) {
84
+ candidates.push({ match: 'san', cert, specificity: 0 });
85
+ continue;
86
+ }
87
+ const wildcard = names.find((n) => wildcardCovers(n, domain));
88
+ if (wildcard) {
89
+ candidates.push({ match: 'wildcard', cert, specificity: wildcard.length });
90
+ }
91
+ }
92
+ }
93
+
94
+ if (candidates.length === 0) return { found: false };
95
+
96
+ candidates.sort(
97
+ (a, b) =>
98
+ MATCH_RANK[a.match] - MATCH_RANK[b.match] ||
99
+ b.specificity - a.specificity ||
100
+ a.cert.domain.localeCompare(b.cert.domain)
101
+ );
102
+
103
+ const best = candidates[0];
104
+ const paths = getDefaultCertPaths(best.cert.domain, process.platform, dir);
105
+ const info = await describeCertificate(best.cert.domain, { sslDir: dir });
106
+
107
+ return {
108
+ found: true,
109
+ match: best.match,
110
+ certificate: {
111
+ domain: best.cert.domain,
112
+ names: info.names ?? [best.cert.domain],
113
+ certPath: paths.certPath,
114
+ keyPath: paths.keyPath,
115
+ expiry: best.cert.expiry ?? null,
116
+ daysLeft: best.cert.daysLeft ?? null,
117
+ status: best.cert.status,
118
+ },
119
+ };
120
+ }