easy-devops 1.3.6 → 1.4.1

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 (78) 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/install.bat +14 -7
  7. package/package.json +2 -2
  8. package/src/cli/index.js +8 -0
  9. package/src/cli/managers/domain-manager.js +37 -6
  10. package/src/cli/managers/nginx-manager.js +14 -5
  11. package/src/cli/managers/node-manager.js +19 -13
  12. package/src/cli/managers/ssl-manager.js +89 -26
  13. package/src/cli/menu.js +8 -2
  14. package/src/cli/menus/cleanup.js +4 -2
  15. package/src/cli/menus/dashboard.js +22 -15
  16. package/src/cli/menus/hub.js +402 -0
  17. package/src/cli/menus/runtime.js +12 -0
  18. package/src/cli/menus/service.js +80 -13
  19. package/src/cli/menus/settings.js +46 -12
  20. package/src/cli/menus/uninstall.js +13 -5
  21. package/src/cli/menus/update.js +24 -14
  22. package/src/cli/ui/page.js +123 -0
  23. package/src/core/cert-operations.js +34 -4
  24. package/src/core/cert-reader.js +67 -22
  25. package/src/core/cert-renewal.js +65 -9
  26. package/src/core/cert-suggest.js +120 -0
  27. package/src/core/cleanup.js +221 -1
  28. package/src/core/cloudflare-ips.js +161 -0
  29. package/src/core/daemon/ipc.js +1 -1
  30. package/src/core/daemon/lock.js +296 -9
  31. package/src/core/daemon/run.js +12 -0
  32. package/src/core/daemon/stateFile.js +128 -0
  33. package/src/core/dashboardProcess.js +134 -6
  34. package/src/core/db.js +26 -1
  35. package/src/core/deploy/apps.js +36 -62
  36. package/src/core/deploy/deployKey.js +331 -0
  37. package/src/core/deploy/domainLink.js +280 -23
  38. package/src/core/deploy/engine.js +382 -63
  39. package/src/core/deploy/ezfile.js +496 -29
  40. package/src/core/deploy/githubApi.js +100 -13
  41. package/src/core/deploy/hubCommands.js +158 -18
  42. package/src/core/deploy/status.js +28 -1
  43. package/src/core/domains-db.js +1 -0
  44. package/src/core/hub/agent.js +238 -32
  45. package/src/core/hub/deployProgress.js +411 -0
  46. package/src/core/hubConnect.js +205 -0
  47. package/src/core/hubPermissions.js +48 -10
  48. package/src/core/jobs/bus.js +1 -1
  49. package/src/core/jobs/owner.js +268 -6
  50. package/src/core/nginx-conf-generator.js +124 -19
  51. package/src/core/notifications/claim.js +26 -3
  52. package/src/core/permissions.js +277 -59
  53. package/src/core/platform.js +73 -2
  54. package/src/core/runner.js +96 -40
  55. package/src/core/service/dataDir.js +34 -9
  56. package/src/core/service/index.js +203 -24
  57. package/src/core/service/runtime.js +40 -3
  58. package/src/core/service/windowsService.js +452 -107
  59. package/src/core/service/winsw.js +44 -3
  60. package/src/core/ssl/preflight.js +548 -0
  61. package/src/core/ssl/progress.js +196 -0
  62. package/src/core/ssl-issuer.js +502 -148
  63. package/src/core/validators.js +24 -0
  64. package/src/dashboard/controllers/authController.js +12 -5
  65. package/src/dashboard/controllers/deploymentsController.js +76 -11
  66. package/src/dashboard/controllers/domainsController.js +35 -1
  67. package/src/dashboard/controllers/hubController.js +4 -3
  68. package/src/dashboard/controllers/settingsController.js +73 -68
  69. package/src/dashboard/controllers/sslController.js +135 -15
  70. package/src/dashboard/public/js/app.js +42 -7
  71. package/src/dashboard/routes/deployments.js +2 -0
  72. package/src/dashboard/routes/domains.js +1 -0
  73. package/src/dashboard/server.js +42 -7
  74. package/src/dashboard/socketManager.js +19 -25
  75. package/src/dashboard/views/partials/settings-panel.ejs +29 -10
  76. package/dist/ui/assets/index-BUpPxWmp.css +0 -1
  77. package/dist/ui/assets/index-DD0JjK0Q.js +0 -475
  78. package/dist/ui/assets/socket-4tfdap-e.js +0 -65
@@ -19,13 +19,20 @@
19
19
 
20
20
  import fs from 'fs/promises';
21
21
  import path from 'path';
22
- import os from 'os';
22
+ import tls from 'node:tls';
23
+ import { X509Certificate } from 'node:crypto';
23
24
  import * as acme from 'acme-client';
24
25
 
25
26
  import { loadConfig } from './config.js';
27
+ import { runPreflight, summarizePreflight, fixForAcmeError } from './ssl/preflight.js';
28
+ import {
29
+ createSslProgress,
30
+ isValidOpId,
31
+ newOpId,
32
+ sanitizeDetail,
33
+ } from './ssl/progress.js';
26
34
  import { run as defaultRun } from './shell.js';
27
35
  import {
28
- isWindows,
29
36
  isDevDataDir,
30
37
  nginxServiceStartCmd,
31
38
  nginxServiceStopCmd,
@@ -39,10 +46,9 @@ import {
39
46
  import {
40
47
  getConfDDir,
41
48
  hasChallengeLocation,
42
- parseListenAddresses,
43
49
  DEFAULT_ACME_CHALLENGE_PORT,
44
50
  } from './nginx-conf-generator.js';
45
- import { withChallengeServer, preflight, resolveProbeHosts } from './acme-challenge.js';
51
+ import { withChallengeServer } from './acme-challenge.js';
46
52
 
47
53
  /**
48
54
  * Written next to fullchain.pem after every successful issuance. It records
@@ -59,15 +65,6 @@ export const CHALLENGE_MODES = Object.freeze({
59
65
  STANDALONE: 'standalone',
60
66
  });
61
67
 
62
- /** Advice shown when neither mode could complete the challenge. */
63
- const EXTERNAL_CAUSE_HINT = [
64
- 'Both challenge modes failed locally, which usually means the cause is outside Easy DevOps:',
65
- ' • the domain\'s DNS A record does not point at this server',
66
- ' • port 80 is blocked by a firewall or security group',
67
- ' • an AAAA/IPv6 record points somewhere else (Let\'s Encrypt prefers IPv6)',
68
- ' • a CDN or proxy in front of the server forces HTTPS or intercepts the path',
69
- ].join('\n');
70
-
71
68
  /**
72
69
  * One-line human summary of how an issuance went, for the CLI, the dashboard
73
70
  * toast and the Hub command result — so all three report the same thing.
@@ -101,8 +98,8 @@ export function describeIssuance(result) {
101
98
  }
102
99
 
103
100
  /** ACME directory for the configured environment. */
104
- function directoryUrl(staging) {
105
- return staging ? acme.directory.letsencrypt.staging : acme.directory.letsencrypt.production;
101
+ function directoryUrl(staging, acmeLib = acme) {
102
+ return staging ? acmeLib.directory.letsencrypt.staging : acmeLib.directory.letsencrypt.production;
106
103
  }
107
104
 
108
105
  /**
@@ -160,25 +157,41 @@ export async function reloadNginx(run = defaultRun) {
160
157
  return { ok: result.success, output: combineOutput(result) };
161
158
  }
162
159
 
163
- /** Ensures the certificate directory exists, with the right ownership. */
164
- async function ensureCertDir(certDir, run) {
165
- if (isWindows) {
160
+ /**
161
+ * Ensures the certificate directory exists.
162
+ *
163
+ * No sudo: the directory is created and handed to this account ONCE by the
164
+ * setup script in core/permissions.js (`Settings -> Linux permissions`), so
165
+ * there is no standing grant for mkdir or chown to abuse. If the directory
166
+ * was never handed over, the failure names that setup rather than looking
167
+ * like an unexplained issuance error.
168
+ *
169
+ * @param {string} certDir
170
+ */
171
+ async function ensureCertDir(certDir) {
172
+ try {
166
173
  await fs.mkdir(certDir, { recursive: true });
167
- return;
174
+ } catch (err) {
175
+ if (err?.code === 'EACCES' || err?.code === 'EPERM') {
176
+ throw new Error(
177
+ `Cannot create the certificate directory ${certDir}: permission denied. `
178
+ + 'Run the one-time setup from a terminal so this account owns it '
179
+ + '(dashboard: Settings -> Linux permissions; CLI: Settings -> Linux Permissions), '
180
+ + 'then try again.',
181
+ );
182
+ }
183
+ throw err;
168
184
  }
169
- const user = os.userInfo().username;
170
- await run(`sudo -n mkdir -p "${certDir}"`);
171
- await run(`sudo -n chown ${user}:${user} "${certDir}"`);
172
185
  }
173
186
 
174
187
  /** Loads or creates the persistent ACME account key. */
175
- async function getAccountKey(sslDir) {
188
+ async function getAccountKey(sslDir, acmeLib = acme) {
176
189
  const keyPath = path.join(sslDir, '.account', 'account.key');
177
190
  await fs.mkdir(path.dirname(keyPath), { recursive: true });
178
191
  try {
179
192
  return await fs.readFile(keyPath);
180
193
  } catch {
181
- const key = await acme.crypto.createPrivateKey();
194
+ const key = await acmeLib.crypto.createPrivateKey();
182
195
  await fs.writeFile(keyPath, key);
183
196
  return key;
184
197
  }
@@ -253,6 +266,199 @@ export async function prepareDomainForHttpChallenge(domain, run = defaultRun) {
253
266
  };
254
267
  }
255
268
 
269
+ /** The whole operation is bounded, so a stuck ACME server cannot hang a job. */
270
+ export const ISSUANCE_TIMEOUT_MS = 5 * 60 * 1000;
271
+
272
+ /**
273
+ * The stages every certificate operation reports, in order. Exported so the
274
+ * tests and the documentation cannot drift from the implementation.
275
+ */
276
+ export const ISSUANCE_STAGES = Object.freeze([
277
+ 'preflight',
278
+ 'account and order',
279
+ 'challenge ready',
280
+ 'waiting for validation',
281
+ 'certificate received',
282
+ 'files written',
283
+ 'nginx config test',
284
+ 'nginx reload',
285
+ 'https verified',
286
+ ]);
287
+
288
+ function firstLine(value) {
289
+ return String(value ?? '').split('\n')[0].trim();
290
+ }
291
+
292
+ function timeoutError(ms, stage) {
293
+ const seconds = Math.max(1, Math.round(ms / 1000));
294
+ const err = new Error(`The certificate operation timed out after ${seconds}s while ${stage}.`);
295
+ err.code = 'EZ_TIMEOUT';
296
+ err.stage = stage;
297
+ return err;
298
+ }
299
+
300
+ /**
301
+ * Rejects if `promise` does not settle in time. The stage may be a function so
302
+ * the message names the stage that was actually running when the clock ran out.
303
+ */
304
+ function withTimeout(promise, ms, stage) {
305
+ if (!Number.isFinite(ms) || ms <= 0) return promise;
306
+ const stageName = () => (typeof stage === 'function' ? stage() : stage);
307
+ return new Promise((resolve, reject) => {
308
+ let settled = false;
309
+ const timer = setTimeout(() => {
310
+ if (settled) return;
311
+ settled = true;
312
+ reject(timeoutError(ms, stageName()));
313
+ }, ms);
314
+ if (timer && typeof timer.unref === 'function') timer.unref();
315
+
316
+ Promise.resolve(promise).then(
317
+ (value) => {
318
+ if (settled) return;
319
+ settled = true;
320
+ clearTimeout(timer);
321
+ resolve(value);
322
+ },
323
+ (err) => {
324
+ if (settled) return;
325
+ settled = true;
326
+ clearTimeout(timer);
327
+ reject(err);
328
+ },
329
+ );
330
+ });
331
+ }
332
+
333
+ /** A one-second-granularity "still waiting" heartbeat, throttled downstream. */
334
+ function startValidationHeartbeat(report) {
335
+ const startedAt = Date.now();
336
+ const timer = setInterval(() => {
337
+ const seconds = Math.round((Date.now() - startedAt) / 1000);
338
+ report(
339
+ 'waiting for validation',
340
+ 'running',
341
+ `Waiting for Let's Encrypt validation (${seconds}s)`,
342
+ );
343
+ }, 2000);
344
+ if (timer && typeof timer.unref === 'function') timer.unref();
345
+ return timer;
346
+ }
347
+
348
+ function stopHeartbeat(timer) {
349
+ if (timer) clearInterval(timer);
350
+ }
351
+
352
+ /**
353
+ * Compares the certificate nginx serves with the file just written.
354
+ *
355
+ * A missing file, a refused connection or a timeout is reported as a skipped
356
+ * check rather than a failed issuance: the certificate exists either way.
357
+ *
358
+ * @returns {Promise<{ ok: boolean, message: string }>}
359
+ */
360
+ export async function verifyServedCertificate(domainName, certPath, { timeoutMs = 5000, deps = {} } = {}) {
361
+ const readFile = deps.readFile ?? fs.readFile;
362
+ const connect = deps.tlsConnect ?? tls.connect;
363
+
364
+ try {
365
+ const localPem = deps.localCertificate ?? await readFile(certPath, 'utf8');
366
+ const local = new X509Certificate(localPem);
367
+ const expected = local.fingerprint256.replace(/:/g, '').toLowerCase();
368
+
369
+ const peer = await new Promise((resolve, reject) => {
370
+ let settled = false;
371
+ const socket = connect({
372
+ host: deps.host ?? domainName,
373
+ port: deps.port ?? 443,
374
+ servername: domainName,
375
+ timeout: timeoutMs,
376
+ rejectUnauthorized: false,
377
+ });
378
+ const finish = (err, value) => {
379
+ if (settled) return;
380
+ settled = true;
381
+ try { socket.destroy(); } catch { /* already gone */ }
382
+ if (err) reject(err);
383
+ else resolve(value);
384
+ };
385
+ socket.once('secureConnect', () => finish(null, socket.getPeerCertificate(true)));
386
+ socket.once('timeout', () => finish(new Error('timed out')));
387
+ socket.once('error', (err) => finish(err));
388
+ });
389
+
390
+ if (!peer?.raw) return { ok: false, message: 'the server did not present a certificate' };
391
+ const served = new X509Certificate(peer.raw);
392
+ const actual = served.fingerprint256.replace(/:/g, '').toLowerCase();
393
+ if (actual !== expected) {
394
+ return {
395
+ ok: false,
396
+ message: 'the server is not serving the new certificate yet (nginx may not have reloaded)',
397
+ };
398
+ }
399
+ return { ok: true, message: 'the server is serving the new certificate' };
400
+ } catch (err) {
401
+ return { ok: false, message: `could not verify HTTPS: ${firstLine(err.message)}` };
402
+ }
403
+ }
404
+
405
+ /**
406
+ * The stages after the certificate files exist: test, reload, and verify.
407
+ * Failures here are reported but do not turn a certificate that was issued
408
+ * into "no certificate": the files are already on disk for the next retry.
409
+ */
410
+ async function applyNginxAndVerify({
411
+ report, run, domainName, certPath, mode, preflightInfo, behindCloudflare,
412
+ manageNginx, remaining, deps,
413
+ }) {
414
+ let nginxReloaded = null;
415
+ let httpsVerified = null;
416
+
417
+ if (mode === 'dns-01') {
418
+ report('nginx config test', 'skipped', 'DNS-01 leaves nginx untouched');
419
+ report('nginx reload', 'skipped', 'DNS-01 leaves nginx untouched');
420
+ } else if (manageNginx) {
421
+ report('nginx config test', 'running');
422
+
423
+ let reloaded;
424
+ try {
425
+ reloaded = await withTimeout(reloadNginx(run), remaining(), 'nginx reload');
426
+ } catch (err) {
427
+ reloaded = { ok: false, output: err.message };
428
+ }
429
+
430
+ const detail = reloaded.ok ? undefined : firstLine(reloaded.output) || 'nginx did not reload';
431
+ report('nginx config test', reloaded.ok ? 'ok' : 'failed', detail);
432
+ report('nginx reload', 'running');
433
+ report('nginx reload', reloaded.ok ? 'ok' : 'failed', detail);
434
+ nginxReloaded = Boolean(reloaded.ok);
435
+ }
436
+
437
+ const proxied = Boolean(behindCloudflare || preflightInfo?.proxied);
438
+ if (proxied) {
439
+ report('https verified', 'skipped', "served by Cloudflare's edge");
440
+ } else if (!certPath) {
441
+ report('https verified', 'skipped', 'no certificate file to compare');
442
+ } else {
443
+ report('https verified', 'running');
444
+ let verified;
445
+ try {
446
+ const verify = deps.verifyHttps ?? verifyServedCertificate;
447
+ verified = await withTimeout(
448
+ verify(domainName, certPath, deps.https ?? {}),
449
+ remaining(),
450
+ 'https verified',
451
+ );
452
+ } catch (err) {
453
+ verified = { ok: false, message: firstLine(err.message) };
454
+ }
455
+ httpsVerified = Boolean(verified?.ok);
456
+ report('https verified', verified?.ok ? 'ok' : 'failed', verified?.ok ? undefined : verified?.message);
457
+ }
458
+
459
+ return { nginxReloaded, httpsVerified };
460
+ }
461
+
256
462
  /**
257
463
  * Issues or renews a certificate.
258
464
  *
@@ -266,16 +472,25 @@ export async function prepareDomainForHttpChallenge(domain, run = defaultRun) {
266
472
  * @param {'auto'|'proxy'|'standalone'} [options.mode] Overrides sslChallengeMode
267
473
  * @param {boolean} [options.staging] Overrides the staging setting
268
474
  * @param {Function} [options.run] Injected shell runner (testing only)
475
+ * @param {string} [options.opId] Client operation id (validated, generated when absent)
476
+ * @param {(event: Object) => void} [options.onEvent] Full progress payload
477
+ * @param {(stage: string, status: string, detail?: string) => void} [options.onProgress]
478
+ * @param {boolean} [options.manageNginx] Run the test/reload/verify stages here
479
+ * @param {number} [options.timeoutMs] Overall bound (testing only)
480
+ * @param {Object} [options.deps] Injected collaborators (testing only)
269
481
  * @returns {Promise<{
270
482
  * success: boolean,
483
+ * opId: string,
271
484
  * certPath: string|null,
272
485
  * keyPath: string|null,
273
486
  * mode: string|null,
274
487
  * fellBack: boolean,
275
488
  * nginxDownMs: number,
276
489
  * staging: boolean,
277
- * preflight: { ok: boolean, detail: string }|null,
490
+ * preflight: { ok: boolean, detail: string, results?: Array<Object>, proxied?: boolean }|null,
278
491
  * configRegenerated: boolean,
492
+ * nginxReloaded: boolean|null,
493
+ * httpsVerified: boolean|null,
279
494
  * error: object|null
280
495
  * }>}
281
496
  */
@@ -289,8 +504,34 @@ export async function issueCertificate(domainName, options = {}) {
289
504
  mode: modeOverride = null,
290
505
  staging: stagingOverride,
291
506
  run = defaultRun,
507
+ opId: rawOpId = null,
508
+ onEvent = null,
509
+ onProgress = null,
510
+ manageNginx = true,
511
+ timeoutMs = ISSUANCE_TIMEOUT_MS,
512
+ deps = {},
292
513
  } = options;
293
514
 
515
+ const acmeLib = deps.acme ?? acme;
516
+ const preflightFn = deps.preflight ?? runPreflight;
517
+ const challengeServer = deps.withChallengeServer ?? withChallengeServer;
518
+ const now = deps.now ?? Date.now;
519
+ const opId = isValidOpId(rawOpId) ? rawOpId : newOpId();
520
+ const progress = createSslProgress({
521
+ opId, domain: domainName, onEvent, onProgress, now,
522
+ ...(deps.progress ?? {}),
523
+ });
524
+
525
+ const startedAt = now();
526
+ const deadlineAt = Number.isFinite(timeoutMs) && timeoutMs > 0 ? startedAt + timeoutMs : Infinity;
527
+ const remaining = () => (deadlineAt === Infinity ? Infinity : Math.max(1, deadlineAt - now()));
528
+
529
+ let currentStage = 'preflight';
530
+ const report = (stage, status, detail) => {
531
+ currentStage = stage;
532
+ progress.report(stage, status, detail);
533
+ };
534
+
294
535
  const config = loadConfig();
295
536
  const sslDir = config.sslDir;
296
537
  const nginxDir = config.nginxDir;
@@ -299,6 +540,8 @@ export async function issueCertificate(domainName, options = {}) {
299
540
 
300
541
  const base = {
301
542
  success: false,
543
+ opId,
544
+ domain: domainName,
302
545
  certPath: null,
303
546
  keyPath: null,
304
547
  mode: null,
@@ -307,9 +550,26 @@ export async function issueCertificate(domainName, options = {}) {
307
550
  staging,
308
551
  preflight: null,
309
552
  configRegenerated: false,
553
+ nginxReloaded: null,
554
+ httpsVerified: null,
310
555
  error: null,
311
556
  };
312
557
 
558
+ const fail = (stage, err, consequence, extra = {}) => {
559
+ const cause = sanitizeDetail(err?.message || String(err ?? 'Certificate request failed.'));
560
+ return {
561
+ ...base,
562
+ ...extra,
563
+ error: buildError(stage, cause, consequence, {
564
+ stage,
565
+ fix: fixForAcmeError(cause, domainName),
566
+ nginxRunning: true,
567
+ configSaved: false,
568
+ ...extra,
569
+ }),
570
+ };
571
+ };
572
+
313
573
  const acmeEmail = email || config.acmeEmail;
314
574
  if (!acmeEmail) {
315
575
  return {
@@ -335,17 +595,104 @@ export async function issueCertificate(domainName, options = {}) {
335
595
  };
336
596
  }
337
597
 
338
- const certDir = path.join(sslDir, domainName);
339
- await ensureCertDir(certDir, run);
598
+ // ─── Preflight: nothing below this may run if a check fails ────────────────
599
+ let nginxUp = false;
600
+ if (validationMethod !== 'dns') {
601
+ try { nginxUp = await nginxRunning(run); } catch { nginxUp = false; }
602
+ }
603
+ const requestedMode = modeOverride || config.sslChallengeMode || CHALLENGE_MODES.AUTO;
604
+ const wantProxy = validationMethod !== 'dns'
605
+ && (requestedMode === CHALLENGE_MODES.PROXY
606
+ || (requestedMode === CHALLENGE_MODES.AUTO && nginxUp));
607
+ const preflightMode = validationMethod === 'dns'
608
+ ? 'dns'
609
+ : (wantProxy ? CHALLENGE_MODES.PROXY : CHALLENGE_MODES.STANDALONE);
610
+
611
+ report('preflight', 'running', 'Checking DNS and port 80');
612
+
613
+ let pre;
614
+ try {
615
+ pre = await withTimeout(
616
+ preflightFn(domainName, {
617
+ www: Boolean(www),
618
+ validationMethod,
619
+ mode: preflightMode,
620
+ challengePort,
621
+ deps: deps.preflightDeps ?? {},
622
+ }),
623
+ remaining(),
624
+ 'preflight',
625
+ );
626
+ } catch (err) {
627
+ report('preflight', 'failed', firstLine(err.message));
628
+ return {
629
+ ...base,
630
+ mode: validationMethod === 'dns' ? 'dns-01' : preflightMode,
631
+ preflight: { ok: false, detail: firstLine(err.message), results: [] },
632
+ error: buildError('preflight', err.message, "No certificate was requested, so Let's Encrypt rate limits are untouched.", {
633
+ stage: 'preflight',
634
+ fix: fixForAcmeError(err.message, domainName),
635
+ nginxRunning: true,
636
+ configSaved: false,
637
+ }),
638
+ };
639
+ }
340
640
 
341
- const accountKey = await getAccountKey(sslDir);
342
- const client = new acme.Client({ directoryUrl: directoryUrl(staging), accountKey });
641
+ const preflightInfo = {
642
+ ok: Boolean(pre?.ok),
643
+ detail: summarizePreflight(pre),
644
+ results: Array.isArray(pre?.results) ? pre.results : [],
645
+ proxied: Boolean(pre?.proxied),
646
+ reachesUs: Boolean(pre?.reachesUs),
647
+ };
648
+
649
+ if (!preflightInfo.ok) {
650
+ const summary = preflightInfo.detail || 'A preflight check failed.';
651
+ const failedCheck = preflightInfo.results.find((entry) => entry.status === 'fail');
652
+ report('preflight', 'failed', firstLine(summary));
653
+ return {
654
+ ...base,
655
+ mode: validationMethod === 'dns' ? 'dns-01' : preflightMode,
656
+ preflight: preflightInfo,
657
+ error: buildError('preflight', summary, "No certificate was requested, so Let's Encrypt rate limits are untouched.", {
658
+ stage: 'preflight',
659
+ fix: failedCheck?.fix || fixForAcmeError(summary, domainName),
660
+ nginxRunning: true,
661
+ configSaved: false,
662
+ }),
663
+ };
664
+ }
343
665
 
344
- const altNames = wildcard
345
- ? [domainName, `*.${domainName}`]
346
- : (www ? [domainName, `www.${domainName}`] : [domainName]);
347
- const [domainKey, csr] = await acme.crypto.createCsr({ commonName: domainName, altNames });
666
+ report(
667
+ 'preflight',
668
+ 'ok',
669
+ preflightInfo.results.some((entry) => entry.status === 'warn')
670
+ ? 'Checks passed with warnings'
671
+ : 'All checks passed',
672
+ );
673
+
674
+ // ─── Account, order and key material ──────────────────────────────────────
675
+ let client;
676
+ let csr;
677
+ let domainKey;
678
+ let altNames;
679
+ try {
680
+ report('account and order', 'running', "Preparing the Let's Encrypt account and order");
681
+ await ensureCertDir(path.join(sslDir, domainName));
682
+ const accountKey = await getAccountKey(sslDir, acmeLib);
683
+ client = new acmeLib.Client({ directoryUrl: directoryUrl(staging, acmeLib), accountKey });
684
+
685
+ altNames = wildcard
686
+ ? [domainName, `*.${domainName}`]
687
+ : (www ? [domainName, `www.${domainName}`] : [domainName]);
688
+ [domainKey, csr] = await acmeLib.crypto.createCsr({ commonName: domainName, altNames });
689
+ report('account and order', 'ok', 'ACME account ready');
690
+ } catch (err) {
691
+ report('account and order', 'failed', firstLine(err.message));
692
+ return fail('account and order', err, 'No certificate was issued.');
693
+ }
348
694
 
695
+ const certDir = path.join(sslDir, domainName);
349
696
  const writeCert = async (cert) => {
350
697
  const certPath = path.join(certDir, 'fullchain.pem');
351
698
  const keyPath = path.join(certDir, 'privkey.pem');
@@ -371,82 +718,69 @@ export async function issueCertificate(domainName, options = {}) {
371
718
  return { certPath, keyPath };
372
719
  };
373
720
 
374
- // ─── DNS-01 (wildcards) — unchanged, nginx is never touched ────────────────
721
+ // ─── DNS-01 (wildcards) — nginx is never touched ──────────────────────────
375
722
  if (validationMethod === 'dns') {
723
+ let phase = 'challenge ready';
724
+ let heartbeat = null;
725
+ report('challenge ready', 'running', 'Waiting for the DNS TXT record');
376
726
  try {
377
- const cert = await client.auto({
727
+ const cert = await withTimeout(client.auto({
378
728
  csr,
379
729
  email: acmeEmail,
380
730
  termsOfServiceAgreed: true,
381
731
  challengePriority: ['dns-01'],
382
732
  challengeCreateFn: async (authz, challenge, keyAuthorization) => {
383
733
  if (onDnsChallenge) await onDnsChallenge(`_acme-challenge.${domainName}`, keyAuthorization);
734
+ report('challenge ready', 'ok', 'The DNS TXT record is ready');
735
+ phase = 'waiting for validation';
736
+ report('waiting for validation', 'running', "Waiting for Let's Encrypt validation");
737
+ heartbeat = startValidationHeartbeat(report);
384
738
  },
385
739
  challengeRemoveFn: async () => { /* TXT cleanup is the user's */ },
386
- });
740
+ }), remaining(), () => phase);
741
+
742
+ stopHeartbeat(heartbeat);
743
+ report('waiting for validation', 'ok', "Let's Encrypt validated the DNS record");
744
+ report('certificate received', 'ok', "Certificate received from Let's Encrypt");
745
+
746
+ report('files written', 'running');
387
747
  const paths = await writeCert(cert);
388
- return { ...base, success: true, mode: 'dns-01', ...paths };
748
+ report('files written', 'ok', 'Certificate and key saved');
749
+
750
+ const finish = manageNginx
751
+ ? await applyNginxAndVerify({
752
+ report, run, domainName, certPath: paths.certPath, mode: 'dns-01',
753
+ preflightInfo, behindCloudflare: Boolean(options.behindCloudflare), manageNginx,
754
+ remaining, deps,
755
+ })
756
+ : {};
757
+
758
+ return { ...base, success: true, mode: 'dns-01', preflight: preflightInfo, ...paths, ...finish };
389
759
  } catch (err) {
390
- return {
391
- ...base,
392
- mode: 'dns-01',
393
- error: buildError(
394
- 'ACME validation',
395
- err.message || 'DNS-01 challenge failed.',
396
- 'No certificate was issued. nginx was not touched.',
397
- { nginxRunning: true, configSaved: false }
398
- ),
399
- };
760
+ stopHeartbeat(heartbeat);
761
+ const stage = err?.code === 'EZ_TIMEOUT' ? 'timeout' : phase;
762
+ report(phase, 'failed', firstLine(err.message));
763
+ return fail(stage, err, 'No certificate was issued. nginx was not touched.', {
764
+ mode: 'dns-01', preflight: preflightInfo,
765
+ });
400
766
  }
401
767
  }
402
768
 
403
769
  // ─── HTTP-01 ───────────────────────────────────────────────────────────────
404
- const requestedMode = modeOverride || config.sslChallengeMode || CHALLENGE_MODES.AUTO;
405
- const nginxUp = await nginxRunning(run);
406
-
407
- let result = { ...base };
408
-
409
- // Proxy mode is viable only when nginx is actually serving port 80.
410
- const wantProxy =
411
- requestedMode === CHALLENGE_MODES.PROXY ||
412
- (requestedMode === CHALLENGE_MODES.AUTO && nginxUp);
770
+ const shared = {
771
+ client, csr, acmeEmail, domainName, nginxDir, challengePort, run, writeCert, base,
772
+ report, preflightInfo, behindCloudflare: Boolean(options.behindCloudflare),
773
+ manageNginx, remaining, deps, challengeServer, fail,
774
+ };
413
775
 
414
776
  if (wantProxy) {
415
- result = await issueViaProxy({
416
- client, csr, acmeEmail, domainName, nginxDir, challengePort, run, writeCert, base,
417
- });
418
-
419
- if (result.success) return result;
420
-
421
- // Only a FAILED LOCAL PREFLIGHT may trigger the fallback. A Let's Encrypt
422
- // failure must not, or a broken DNS record would cost two attempts.
423
- const preflightFailed = result.preflight && result.preflight.ok === false;
424
- const mayFallBack = requestedMode === CHALLENGE_MODES.AUTO && preflightFailed;
425
-
426
- if (!mayFallBack) return result;
777
+ return issueViaProxy(shared);
427
778
  }
428
779
 
429
- // ─── Standalone fallback ───────────────────────────────────────────────────
430
- if (requestedMode === CHALLENGE_MODES.PROXY) return result;
431
-
432
- const standalone = await issueViaStandalone({
433
- client, csr, acmeEmail, nginxDir, run, writeCert, base, nginxWasRunning: nginxUp,
780
+ return issueViaStandalone({
781
+ ...shared,
782
+ nginxWasRunning: nginxUp,
434
783
  });
435
-
436
- standalone.fellBack = wantProxy;
437
- standalone.preflight = result.preflight ?? null;
438
-
439
- if (!standalone.success && wantProxy) {
440
- const seen = result.preflight?.detail ? `\n\nPreflight saw: ${result.preflight.detail}` : '';
441
- standalone.error = buildError(
442
- standalone.error?.step ?? 'ACME validation',
443
- `${standalone.error?.cause ?? 'Challenge failed.'}\n\n${EXTERNAL_CAUSE_HINT}${seen}`,
444
- standalone.error?.consequence ?? 'No certificate was issued.',
445
- { nginxRunning: standalone.error?.nginxRunning ?? true, configSaved: false }
446
- );
447
- }
448
-
449
- return standalone;
450
784
  }
451
785
 
452
786
  /**
@@ -454,93 +788,88 @@ export async function issueCertificate(domainName, options = {}) {
454
788
  */
455
789
  async function issueViaProxy({
456
790
  client, csr, acmeEmail, domainName, nginxDir, challengePort, run, writeCert, base,
791
+ report, preflightInfo, behindCloudflare, manageNginx, remaining, deps, challengeServer, fail,
457
792
  }) {
458
793
  // Flow 1: a config generated before this feature has no challenge location.
459
794
  const { confPath, text } = await readDomainConf(nginxDir, domainName);
460
795
  let configRegenerated = false;
461
796
 
462
797
  if (text !== null && !hasChallengeLocation(text)) {
798
+ const detail =
799
+ `${confPath} has no ACME challenge location (it predates this feature). ` +
800
+ 'Regenerate the domain config first — saving the domain does this.';
801
+ report('challenge ready', 'failed', detail);
463
802
  return {
464
803
  ...base,
465
804
  mode: CHALLENGE_MODES.PROXY,
466
805
  configRegenerated: false,
467
- preflight: {
468
- ok: false,
469
- detail:
470
- `${confPath} has no ACME challenge location (it predates this feature). ` +
471
- 'Regenerate the domain config first — saving the domain does this.',
472
- },
806
+ preflight: preflightInfo,
473
807
  error: buildError(
474
808
  'challenge configuration',
475
809
  `The nginx config for ${domainName} does not forward ${'/.well-known/acme-challenge/'} to Easy DevOps.`,
476
810
  'No certificate was issued. Save the domain once to regenerate its config, then retry.',
477
- { nginxRunning: true, configSaved: false }
811
+ { stage: 'challenge ready', fix: 'Save the domain once to regenerate its nginx config, then retry.', nginxRunning: true, configSaved: false }
478
812
  ),
479
813
  };
480
814
  }
481
815
 
482
- // Adjustment 3: probe the address nginx actually listens on.
483
- const listens = text !== null ? parseListenAddresses(text, 80) : [];
484
- const probeHosts = resolveProbeHosts(listens);
485
-
486
- const pre = await preflight({ domain: domainName, challengePort, probeHosts });
487
-
488
- if (!pre.ok) {
489
- const bound = listens.length > 0
490
- ? ` The config binds: ${listens.map((l) => `${l.host}:${l.port}`).join(', ')}.`
491
- : '';
492
- return {
493
- ...base,
494
- mode: CHALLENGE_MODES.PROXY,
495
- configRegenerated,
496
- preflight: pre,
497
- error: buildError(
498
- 'local preflight',
499
- `nginx did not return the challenge token on ${pre.triedHosts.join(', ')}.${bound} ${pre.detail}`,
500
- "No certificate was requested, so Let's Encrypt rate limits are untouched.",
501
- { nginxRunning: true, configSaved: false }
502
- ),
503
- };
504
- }
816
+ let phase = 'challenge ready';
817
+ let heartbeat = null;
818
+ report('challenge ready', 'running', 'Starting the ACME challenge listener');
505
819
 
506
820
  try {
507
- const cert = await withChallengeServer(challengePort, async ({ setToken, removeToken }) => {
508
- return client.auto({
821
+ const cert = await challengeServer(challengePort, async ({ setToken, removeToken }) => {
822
+ return withTimeout(client.auto({
509
823
  csr,
510
824
  email: acmeEmail,
511
825
  termsOfServiceAgreed: true,
512
826
  challengePriority: ['http-01'],
513
827
  challengeCreateFn: async (authz, challenge, keyAuthorization) => {
514
828
  setToken(challenge.token, keyAuthorization);
829
+ report('challenge ready', 'ok', 'The challenge token is being served over HTTP');
830
+ phase = 'waiting for validation';
831
+ report('waiting for validation', 'running', "Waiting for Let's Encrypt validation");
832
+ heartbeat = startValidationHeartbeat(report);
515
833
  },
516
834
  challengeRemoveFn: async (authz, challenge) => {
517
835
  removeToken(challenge.token);
518
836
  },
519
- });
837
+ }), remaining(), () => phase);
520
838
  });
521
839
 
840
+ stopHeartbeat(heartbeat);
841
+ report('waiting for validation', 'ok', "Let's Encrypt accepted the challenge");
842
+ report('certificate received', 'ok', "Certificate received from Let's Encrypt");
843
+
844
+ report('files written', 'running');
522
845
  const paths = await writeCert(cert);
846
+ report('files written', 'ok', 'Certificate and key saved');
847
+
848
+ const finish = manageNginx
849
+ ? await applyNginxAndVerify({
850
+ report, run, domainName, certPath: paths.certPath, mode: CHALLENGE_MODES.PROXY,
851
+ preflightInfo, behindCloudflare, manageNginx, remaining, deps,
852
+ })
853
+ : {};
854
+
523
855
  return {
524
856
  ...base,
525
857
  success: true,
526
858
  mode: CHALLENGE_MODES.PROXY,
527
859
  configRegenerated,
528
- preflight: pre,
860
+ preflight: preflightInfo,
529
861
  ...paths,
862
+ ...finish,
530
863
  };
531
864
  } catch (err) {
532
- return {
533
- ...base,
865
+ stopHeartbeat(heartbeat);
866
+ const stage = err?.code === 'EZ_TIMEOUT' ? 'timeout' : phase;
867
+ report(phase, 'failed', firstLine(err.message));
868
+ return fail(stage, err, 'No certificate was issued. nginx kept running throughout.', {
534
869
  mode: CHALLENGE_MODES.PROXY,
535
870
  configRegenerated,
536
- preflight: pre,
537
- error: buildError(
538
- 'ACME validation',
539
- err.message || 'HTTP-01 challenge failed.',
540
- 'No certificate was issued. nginx kept running throughout.',
541
- { nginxRunning: true, configSaved: false }
542
- ),
543
- };
871
+ preflight: preflightInfo,
872
+ });
544
873
  }
545
874
  }
546
875
 
@@ -549,14 +878,13 @@ async function issueViaProxy({
549
878
  * back the way it was found.
550
879
  */
551
880
  async function issueViaStandalone({
552
- client, csr, acmeEmail, nginxDir, run, writeCert, base, nginxWasRunning,
881
+ client, csr, acmeEmail, domainName, nginxDir, run, writeCert, base, nginxWasRunning,
882
+ report, preflightInfo, behindCloudflare, manageNginx, remaining, deps, challengeServer,
553
883
  }) {
554
884
  let stoppedAt = null;
555
-
556
- // The result is built up in place so the finally block can record how long
557
- // nginx was down — a `return { ...base }` would have been evaluated before
558
- // finally ran, and the timing would never reach the caller.
559
885
  const outcome = { ...base, mode: CHALLENGE_MODES.STANDALONE, nginxRestored: !nginxWasRunning };
886
+ let phase = 'challenge ready';
887
+ let heartbeat = null;
560
888
 
561
889
  try {
562
890
  if (nginxWasRunning) {
@@ -564,34 +892,50 @@ async function issueViaStandalone({
564
892
  await run(nginxServiceStopCmd(nginxDir), { cwd: nginxDir });
565
893
  }
566
894
 
567
- const cert = await withChallengeServer(80, async ({ setToken, removeToken }) => {
568
- return client.auto({
895
+ report('challenge ready', 'running', 'Starting the ACME challenge listener on port 80');
896
+
897
+ const cert = await challengeServer(80, async ({ setToken, removeToken }) => {
898
+ return withTimeout(client.auto({
569
899
  csr,
570
900
  email: acmeEmail,
571
901
  termsOfServiceAgreed: true,
572
902
  challengePriority: ['http-01'],
573
903
  challengeCreateFn: async (authz, challenge, keyAuthorization) => {
574
904
  setToken(challenge.token, keyAuthorization);
905
+ report('challenge ready', 'ok', 'The challenge token is being served on port 80');
906
+ phase = 'waiting for validation';
907
+ report('waiting for validation', 'running', "Waiting for Let's Encrypt validation");
908
+ heartbeat = startValidationHeartbeat(report);
575
909
  },
576
910
  challengeRemoveFn: async (authz, challenge) => {
577
911
  removeToken(challenge.token);
578
912
  },
579
- });
913
+ }), remaining(), () => phase);
580
914
  });
581
915
 
916
+ stopHeartbeat(heartbeat);
917
+ report('waiting for validation', 'ok', "Let's Encrypt accepted the challenge");
918
+ report('certificate received', 'ok', "Certificate received from Let's Encrypt");
919
+
920
+ report('files written', 'running');
582
921
  const paths = await writeCert(cert);
922
+ report('files written', 'ok', 'Certificate and key saved');
923
+
583
924
  outcome.success = true;
584
925
  outcome.certPath = paths.certPath;
585
926
  outcome.keyPath = paths.keyPath;
586
- return outcome;
927
+ outcome.preflight = preflightInfo;
587
928
  } catch (err) {
588
- outcome.error = buildError(
589
- 'ACME validation',
590
- err.message || 'HTTP-01 challenge failed in standalone mode.',
591
- 'No certificate was issued.',
592
- { nginxRunning: true, configSaved: false }
593
- );
594
- return outcome;
929
+ stopHeartbeat(heartbeat);
930
+ const stage = err?.code === 'EZ_TIMEOUT' ? 'timeout' : phase;
931
+ report(phase, 'failed', firstLine(err.message));
932
+ outcome.error = buildError(stage, err.message || 'HTTP-01 challenge failed in standalone mode.', 'No certificate was issued.', {
933
+ stage,
934
+ fix: fixForAcmeError(err.message, domainName),
935
+ nginxRunning: true,
936
+ configSaved: false,
937
+ });
938
+ outcome.preflight = preflightInfo;
595
939
  } finally {
596
940
  // Restore nginx no matter how we leave this block — success, failure, or
597
941
  // an exception thrown past the catch.
@@ -624,4 +968,14 @@ async function issueViaStandalone({
624
968
  }
625
969
  }
626
970
  }
971
+
972
+ if (outcome.success && manageNginx) {
973
+ const finish = await applyNginxAndVerify({
974
+ report, run, domainName: base.domain, certPath: outcome.certPath,
975
+ mode: CHALLENGE_MODES.STANDALONE, preflightInfo, behindCloudflare, manageNginx, remaining, deps,
976
+ });
977
+ Object.assign(outcome, finish);
978
+ }
979
+
980
+ return outcome;
627
981
  }