easy-devops 1.2.0 → 1.3.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 (132) hide show
  1. package/README.md +97 -6
  2. package/dist/ui/assets/index-B6zdwEnG.css +1 -0
  3. package/dist/ui/assets/index-Cy0oNmul.js +442 -0
  4. package/dist/ui/assets/socket-DwLPrgsr.js +1 -0
  5. package/dist/ui/assets/socket-K5ttLD2q.js +65 -0
  6. package/dist/ui/brand/apple-touch-icon.png +0 -0
  7. package/dist/ui/brand/favicon-16.png +0 -0
  8. package/dist/ui/brand/favicon-32.png +0 -0
  9. package/dist/ui/brand/favicon-light-16.png +0 -0
  10. package/dist/ui/brand/favicon-light-32.png +0 -0
  11. package/dist/ui/brand/favicon.ico +0 -0
  12. package/dist/ui/brand/icon-192.png +0 -0
  13. package/dist/ui/brand/icon-48.png +0 -0
  14. package/dist/ui/brand/icon-512.png +0 -0
  15. package/dist/ui/brand/icon-64-light.png +0 -0
  16. package/dist/ui/brand/icon-64.png +0 -0
  17. package/dist/ui/brand/logo-dark.png +0 -0
  18. package/dist/ui/brand/logo-light.png +0 -0
  19. package/dist/ui/brand/mark-dark.png +0 -0
  20. package/dist/ui/brand/mark-light.png +0 -0
  21. package/dist/ui/index.html +71 -0
  22. package/install.ps1 +188 -1
  23. package/install.sh +254 -29
  24. package/package.json +17 -5
  25. package/src/cli/dash.js +110 -0
  26. package/src/cli/index.js +237 -106
  27. package/src/cli/managers/domain-manager.js +60 -40
  28. package/src/cli/managers/ssl-manager.js +47 -330
  29. package/src/cli/menu.js +156 -0
  30. package/src/cli/menus/cleanup.js +205 -0
  31. package/src/cli/menus/dashboard.js +93 -2
  32. package/src/cli/menus/runtime.js +236 -0
  33. package/src/cli/menus/service.js +764 -0
  34. package/src/cli/menus/settings.js +176 -8
  35. package/src/cli/menus/uninstall.js +167 -0
  36. package/src/cli/menus/update.js +221 -65
  37. package/src/core/acme-challenge.js +273 -0
  38. package/src/core/cert-operations.js +189 -0
  39. package/src/{dashboard/lib → core}/cert-reader.js +2 -2
  40. package/src/core/cert-renewal.js +494 -0
  41. package/src/core/channels/discord.js +77 -0
  42. package/src/core/channels/telegram.js +120 -0
  43. package/src/core/cleanup.js +600 -0
  44. package/src/core/config.js +169 -2
  45. package/src/core/daemon/ipc.js +292 -0
  46. package/src/core/daemon/lock.js +294 -0
  47. package/src/core/daemon/run.js +241 -0
  48. package/src/core/daemon/stopRequest.js +162 -0
  49. package/src/core/db.js +44 -8
  50. package/src/core/deploy/apps.js +491 -0
  51. package/src/core/deploy/domainLink.js +200 -0
  52. package/src/core/deploy/engine.js +973 -0
  53. package/src/core/deploy/ezfile.js +361 -0
  54. package/src/core/deploy/github.js +239 -0
  55. package/src/core/deploy/githubApi.js +261 -0
  56. package/src/core/deploy/hookServer.js +325 -0
  57. package/src/core/deploy/hubCommands.js +267 -0
  58. package/src/core/deploy/launcher.js +57 -0
  59. package/src/core/deploy/status.js +91 -0
  60. package/src/core/deploy/store.js +398 -0
  61. package/src/core/domainNotifier.js +364 -0
  62. package/src/core/domains-db.js +234 -0
  63. package/src/core/events.js +222 -0
  64. package/src/core/hub/agent.js +842 -0
  65. package/src/core/hubLink.js +306 -0
  66. package/src/core/hubPermissions.js +430 -0
  67. package/src/core/installSource.js +162 -0
  68. package/src/core/jobs/bus.js +120 -0
  69. package/src/core/jobs/index.js +371 -0
  70. package/src/core/jobs/monitors.js +368 -0
  71. package/src/core/jobs/owner.js +217 -0
  72. package/src/core/jobs/revisionWatcher.js +106 -0
  73. package/src/core/nginx-apply.js +213 -0
  74. package/src/core/nginx-conf-generator.js +253 -17
  75. package/src/{dashboard/lib → core}/nginx-service.js +18 -9
  76. package/src/core/notifications/claim.js +214 -0
  77. package/src/core/notifications/dispatch.js +154 -0
  78. package/src/core/notifier.js +103 -0
  79. package/src/core/passwords.js +172 -0
  80. package/src/core/permissions.js +8 -4
  81. package/src/core/platform.js +709 -2
  82. package/src/core/probeCache.js +258 -0
  83. package/src/core/purge.js +372 -0
  84. package/src/core/runner.js +488 -0
  85. package/src/core/service/acl.js +226 -0
  86. package/src/core/service/dataDir.js +345 -0
  87. package/src/core/service/index.js +1128 -0
  88. package/src/core/service/legacy.js +218 -0
  89. package/src/core/service/runtime.js +446 -0
  90. package/src/core/service/runtimeUpdate.js +800 -0
  91. package/src/core/service/systemd.js +458 -0
  92. package/src/core/service/windowsPersonal.js +530 -0
  93. package/src/core/service/windowsService.js +576 -0
  94. package/src/core/service/winsw.js +260 -0
  95. package/src/core/setupCode.js +331 -0
  96. package/src/core/shell.js +128 -13
  97. package/src/core/ssl-issuer.js +627 -0
  98. package/src/core/updater.js +295 -0
  99. package/src/core/validators.js +99 -0
  100. package/src/dashboard/controllers/authController.js +316 -0
  101. package/src/dashboard/controllers/deploymentsController.js +479 -0
  102. package/src/dashboard/controllers/domainsController.js +403 -0
  103. package/src/dashboard/controllers/hubController.js +135 -0
  104. package/src/dashboard/controllers/nginxController.js +146 -0
  105. package/src/dashboard/controllers/processesController.js +368 -0
  106. package/src/dashboard/controllers/settingsController.js +503 -0
  107. package/src/dashboard/controllers/sslController.js +452 -0
  108. package/src/dashboard/lib/daemonBridge.js +163 -0
  109. package/src/dashboard/lib/localRequest.js +235 -0
  110. package/src/dashboard/lib/loginRateLimit.js +119 -0
  111. package/src/dashboard/lib/requireAuth.js +80 -0
  112. package/src/dashboard/public/img/icon.png +0 -0
  113. package/src/dashboard/public/img/icon_b.png +0 -0
  114. package/src/dashboard/public/js/app.js +595 -19
  115. package/src/dashboard/routes/auth.js +14 -33
  116. package/src/dashboard/routes/deployments.js +46 -0
  117. package/src/dashboard/routes/domains.js +20 -363
  118. package/src/dashboard/routes/hub.js +22 -0
  119. package/src/dashboard/routes/nginx.js +22 -146
  120. package/src/dashboard/routes/processes.js +29 -0
  121. package/src/dashboard/routes/settings.js +25 -232
  122. package/src/dashboard/routes/ssl.js +18 -276
  123. package/src/dashboard/server.js +279 -165
  124. package/src/dashboard/socketManager.js +246 -0
  125. package/src/dashboard/views/index.ejs +1 -0
  126. package/src/dashboard/views/partials/domain-form.ejs +64 -1
  127. package/src/dashboard/views/partials/login.ejs +69 -8
  128. package/src/dashboard/views/partials/processes-panel.ejs +261 -0
  129. package/src/dashboard/views/partials/settings-panel.ejs +549 -118
  130. package/src/dashboard/views/partials/sidebar.ejs +3 -1
  131. package/src/dashboard/lib/domains-db.js +0 -51
  132. /package/src/{dashboard/routes → core/channels}/.gitkeep +0 -0
@@ -0,0 +1,189 @@
1
+ /**
2
+ * core/cert-operations.js
3
+ *
4
+ * Certificate actions the Hub can request. Permission checking happens in
5
+ * core/hub/agent.js before any of this runs; these functions assume they are
6
+ * allowed and concentrate on doing the work and reporting the outcome.
7
+ *
8
+ * Every handler returns { ok, error, ... } so the agent can acknowledge the
9
+ * command with command:result instead of leaving the Hub guessing.
10
+ */
11
+
12
+ import fs from 'fs/promises';
13
+ import path from 'path';
14
+ import { loadConfig } from './config.js';
15
+ import { describeIssuance, issueCertificate, prepareDomainForHttpChallenge } from './ssl-issuer.js';
16
+ import { renewCertificate, describeRenewal, failureReason } from './cert-renewal.js';
17
+ import { bumpHubRevision } from './hubLink.js';
18
+ import { listAllCerts } from './cert-reader.js';
19
+ import { getDomains, findDomain } from './domains-db.js';
20
+
21
+ /** Shape shared by every SSL result so the Hub can render it uniformly. */
22
+ function issuanceResult(domain, result) {
23
+ return {
24
+ ok: Boolean(result?.success),
25
+ domain,
26
+ error: result?.success ? null : (result?.error?.cause ?? 'Certificate operation failed'),
27
+ mode: result?.mode ?? null,
28
+ fellBack: Boolean(result?.fellBack),
29
+ nginxDownMs: result?.nginxDownMs ?? 0,
30
+ staging: Boolean(result?.staging),
31
+ summary: describeIssuance(result),
32
+ };
33
+ }
34
+
35
+ /**
36
+ * The same shape for a renewal, which additionally reports whether nginx was
37
+ * reloaded onto the new certificate and whether the renewal was refused
38
+ * because the certificate needs a manual DNS-01 renewal.
39
+ */
40
+ function renewalResult(domain, result) {
41
+ return {
42
+ ...issuanceResult(domain, result),
43
+ error: result?.success ? null : failureReason(result),
44
+ summary: describeRenewal(result),
45
+ nginxReloaded: result?.nginxReloaded ?? null,
46
+ manual: result?.skipped === 'manual',
47
+ };
48
+ }
49
+
50
+ /**
51
+ * Prepares nginx to answer an HTTP-01 challenge for a domain we know about.
52
+ * @returns {{ ok: boolean, error: string|null, regenerated: boolean }}
53
+ */
54
+ async function prepare(domainName) {
55
+ const record = findDomain(domainName);
56
+ if (!record) return { ok: true, error: null, regenerated: false };
57
+
58
+ const prep = await prepareDomainForHttpChallenge(record);
59
+ if (prep.regenerated) console.log('[hubAgent] ssl:', prep.reason);
60
+ return { ok: prep.ok, error: prep.error, regenerated: prep.regenerated };
61
+ }
62
+
63
+ /**
64
+ * Handles a hub:manageSSL command.
65
+ *
66
+ * @param {Object} payload { action, domain?, www? }
67
+ * @returns {Promise<Object>} { ok, error, ... }
68
+ */
69
+ export async function handleHubSslCommand(payload) {
70
+ const { action, domain } = payload ?? {};
71
+ const config = loadConfig();
72
+
73
+ switch (action) {
74
+ // ── Renew one ─────────────────────────────────────────────────────────
75
+ case 'renew': {
76
+ if (!domain) return { ok: false, error: 'domain is required' };
77
+ if (!config.acmeEmail) return { ok: false, error: 'No acmeEmail configured on this server.' };
78
+
79
+ // renewCertificate() keeps the names the certificate already covers
80
+ // (a `www` certificate stays a `www` certificate), prepares the nginx
81
+ // config, and reloads nginx afterwards.
82
+ const result = await renewCertificate(domain, { email: config.acmeEmail });
83
+ const out = renewalResult(domain, result);
84
+ if (out.ok) bumpHubRevision();
85
+ console.log('[hubAgent] ssl renew:', domain, out.ok ? 'OK' : 'FAILED', '—', out.summary || out.error);
86
+ return out;
87
+ }
88
+
89
+ // ── Renew everything expiring ─────────────────────────────────────────
90
+ case 'renewAll': {
91
+ if (!config.acmeEmail) return { ok: false, error: 'No acmeEmail configured on this server.' };
92
+
93
+ const certs = await listAllCerts();
94
+ const expiring = certs.filter((c) => c.daysLeft !== null && c.daysLeft < 30);
95
+ if (expiring.length === 0) return { ok: true, renewed: [], message: 'Nothing is expiring within 30 days.' };
96
+
97
+ const renewed = [];
98
+
99
+ for (const cert of expiring) {
100
+ const result = await renewCertificate(cert.domain, { email: config.acmeEmail });
101
+ renewed.push(renewalResult(cert.domain, result));
102
+ }
103
+
104
+ bumpHubRevision();
105
+ const failures = renewed.filter((r) => !r.ok);
106
+ return {
107
+ ok: failures.length === 0,
108
+ renewed,
109
+ error: failures.length ? `${failures.length} of ${renewed.length} renewals failed` : null,
110
+ };
111
+ }
112
+
113
+ // ── Issue a new certificate ───────────────────────────────────────────
114
+ case 'issue': {
115
+ if (!domain) return { ok: false, error: 'domain is required' };
116
+ if (!config.acmeEmail) return { ok: false, error: 'No acmeEmail configured on this server.' };
117
+
118
+ // Wildcards need a DNS TXT record the operator adds by hand, so they
119
+ // cannot be driven from the Hub — ssl.issueDns is marked comingSoon.
120
+ if (String(domain).startsWith('*.') || payload?.wildcard) {
121
+ return {
122
+ ok: false,
123
+ error: 'Wildcard certificates need DNS-01 validation, which cannot be completed from the Hub yet. Issue it from the server’s own dashboard.',
124
+ };
125
+ }
126
+
127
+ const prep = await prepare(domain);
128
+ if (!prep.ok) return { ok: false, error: `Challenge setup failed: ${prep.error}` };
129
+
130
+ const result = await issueCertificate(domain, {
131
+ www: Boolean(payload?.www),
132
+ validationMethod: 'http',
133
+ email: config.acmeEmail,
134
+ });
135
+
136
+ const out = issuanceResult(domain, result);
137
+ if (out.ok) bumpHubRevision();
138
+ console.log('[hubAgent] ssl issue:', domain, out.ok ? 'OK' : 'FAILED', '—', out.summary || out.error);
139
+ return out;
140
+ }
141
+
142
+ // ── Delete a certificate ──────────────────────────────────────────────
143
+ case 'delete': {
144
+ if (!domain) return { ok: false, error: 'domain is required' };
145
+
146
+ // Refuse while an enabled domain still points at it: deleting would
147
+ // leave nginx referencing a missing file and fail its next reload.
148
+ const inUse = getDomains().filter(
149
+ (d) => d.enabled !== false && d.ssl?.enabled && certBelongsTo(d, domain, config.sslDir)
150
+ );
151
+
152
+ if (inUse.length > 0) {
153
+ return {
154
+ ok: false,
155
+ error:
156
+ `Certificate for ${domain} is still used by ${inUse.map((d) => d.name).join(', ')}. ` +
157
+ 'Disable SSL on those domains (or disable the domains) before deleting it.',
158
+ };
159
+ }
160
+
161
+ const certDir = path.join(config.sslDir, domain);
162
+ try {
163
+ await fs.rm(certDir, { recursive: true, force: true });
164
+ } catch (err) {
165
+ return { ok: false, error: `Could not delete ${certDir}: ${err.message}` };
166
+ }
167
+
168
+ bumpHubRevision();
169
+ console.log('[hubAgent] ssl delete:', domain, 'OK');
170
+ return { ok: true, domain, deleted: certDir };
171
+ }
172
+
173
+ default:
174
+ return { ok: false, error: `Unknown SSL action: ${action}` };
175
+ }
176
+ }
177
+
178
+ /**
179
+ * True when a domain's configured certificate lives in the directory for
180
+ * `certDomain`. Compares with forward slashes so Windows paths match whichever
181
+ * separator style they were stored with.
182
+ */
183
+ function certBelongsTo(domain, certDomain, sslDir) {
184
+ if (domain.name === certDomain) return true;
185
+
186
+ const norm = (p) => String(p ?? '').replace(/\\/g, '/').toLowerCase();
187
+ const dir = norm(path.join(sslDir, certDomain));
188
+ return norm(domain.ssl?.certPath).startsWith(dir) || norm(domain.ssl?.keyPath).startsWith(dir);
189
+ }
@@ -1,7 +1,7 @@
1
1
  import fs from 'fs/promises';
2
2
  import path from 'path';
3
- import { run } from '../../core/shell.js';
4
- import { loadConfig } from '../../core/config.js';
3
+ import { run } from './shell.js';
4
+ import { loadConfig } from './config.js';
5
5
 
6
6
  export async function listAllCerts() {
7
7
  const { sslDir } = loadConfig();
@@ -0,0 +1,494 @@
1
+ /**
2
+ * core/cert-renewal.js
3
+ *
4
+ * Certificate renewal, in one place: the manual "Renew" buttons (dashboard,
5
+ * CLI, Hub) and the unattended job the daemon runs all go through
6
+ * renewCertificate(), so they cannot disagree about which names a certificate
7
+ * covers or about reloading nginx afterwards.
8
+ *
9
+ * Two things the old per-caller renewals got wrong, and this fixes for all of
10
+ * them at once:
11
+ *
12
+ * 1. They re-issued for the bare domain only. A certificate issued with
13
+ * `www` came back from a renewal WITHOUT `www.example.com`, and the www
14
+ * site started failing certificate validation. The names are now read
15
+ * back from the certificate being replaced.
16
+ * 2. In proxy mode nginx is never stopped — which is the point — but it was
17
+ * never reloaded either, so it kept serving the old certificate from
18
+ * memory until something else happened to reload it.
19
+ *
20
+ * ── What is renewed automatically ────────────────────────────────────────────
21
+ *
22
+ * Only HTTP-01 certificates. A DNS-01 certificate (every wildcard is one)
23
+ * needs a TXT record that a person adds at their DNS provider, so there is
24
+ * nothing a background job can do for it; those keep getting the expiry
25
+ * warning, which says they need a manual renewal.
26
+ *
27
+ * ── Why unattended renewal never stops nginx ─────────────────────────────────
28
+ *
29
+ * `sslChallengeMode: 'auto'` may fall back to standalone mode, which stops
30
+ * nginx for the duration of the challenge. That is acceptable when someone
31
+ * just clicked a button and is watching; it is not acceptable at an arbitrary
32
+ * time of night on every site the server hosts. So an unattended renewal on a
33
+ * running nginx is pinned to proxy mode: if the local preflight fails, the
34
+ * attempt fails, a notification says why, and nothing was taken down. An
35
+ * operator who explicitly configured 'standalone' has chosen the downtime and
36
+ * keeps it.
37
+ */
38
+
39
+ import fs from 'fs/promises';
40
+ import path from 'path';
41
+ import * as acme from 'acme-client';
42
+
43
+ import { loadConfig } from './config.js';
44
+ import { dbGet, dbSet } from './db.js';
45
+ import { listAllCerts } from './cert-reader.js';
46
+ import { findDomain, getDomains } from './domains-db.js';
47
+ import { getStatus } from './nginx-service.js';
48
+ import { bumpHubRevision } from './hubLink.js';
49
+ import { createCertRenewedEvent, createCertRenewFailedEvent } from './events.js';
50
+ import {
51
+ CERT_META_FILE,
52
+ CHALLENGE_MODES,
53
+ describeIssuance,
54
+ issueCertificate,
55
+ prepareDomainForHttpChallenge,
56
+ reloadNginx,
57
+ } from './ssl-issuer.js';
58
+
59
+ /** Renew this many days before expiry unless the setting says otherwise. */
60
+ export const DEFAULT_AUTO_RENEW_DAYS = 7;
61
+ export const MIN_AUTO_RENEW_DAYS = 1;
62
+ /**
63
+ * Let's Encrypt certificates live 90 days. Renewing earlier than a month out
64
+ * buys nothing and spends issuance quota, so the setting is capped there.
65
+ */
66
+ export const MAX_AUTO_RENEW_DAYS = 30;
67
+
68
+ /**
69
+ * Minimum gap between two automatic attempts for the same certificate.
70
+ *
71
+ * The job runs every 12 hours, but it also runs once at every daemon start —
72
+ * so without a persisted gap, a crash-looping service would retry a failing
73
+ * domain on every restart and walk straight into Let's Encrypt's
74
+ * failed-validation limit (5 per hostname per hour). Six hours keeps the
75
+ * normal 12-hour cadence intact while making a restart loop harmless.
76
+ */
77
+ export const RENEW_RETRY_MS = 6 * 60 * 60 * 1000;
78
+
79
+ const STATE_KEY = 'sslAutoRenewState';
80
+
81
+ // ─── Settings ─────────────────────────────────────────────────────────────────
82
+
83
+ /**
84
+ * Validates a "days before expiry" value.
85
+ * @param {*} value
86
+ * @returns {number|null} The integer, or null when it is not acceptable
87
+ */
88
+ export function normalizeAutoRenewDays(value) {
89
+ const n = typeof value === 'string' && value.trim() !== '' ? Number(value) : value;
90
+ if (typeof n !== 'number' || !Number.isInteger(n)) return null;
91
+ if (n < MIN_AUTO_RENEW_DAYS || n > MAX_AUTO_RENEW_DAYS) return null;
92
+ return n;
93
+ }
94
+
95
+ /**
96
+ * The auto-renew settings actually in force.
97
+ *
98
+ * An install that predates the setting has neither key stored; loadConfig()
99
+ * merges the defaults in, so it reads as enabled at 7 days. A stored value
100
+ * that is not usable (hand-edited database) falls back to the default rather
101
+ * than disabling renewal silently.
102
+ *
103
+ * @param {Object} [config]
104
+ * @returns {{ enabled: boolean, days: number }}
105
+ */
106
+ export function getAutoRenewSettings(config = loadConfig()) {
107
+ return {
108
+ enabled: config?.sslAutoRenew !== false,
109
+ days: normalizeAutoRenewDays(config?.sslAutoRenewDays) ?? DEFAULT_AUTO_RENEW_DAYS,
110
+ };
111
+ }
112
+
113
+ // ─── What a certificate covers, and how it was validated ──────────────────────
114
+
115
+ /**
116
+ * Describes an existing certificate well enough to renew it faithfully.
117
+ *
118
+ * The names come from the certificate itself whenever it can be parsed — that
119
+ * is the ground truth for what is being replaced. The validation method comes
120
+ * from the metadata file written at issuance; without one, a wildcard is
121
+ * necessarily DNS-01 and anything else is assumed to be HTTP-01, which is what
122
+ * every certificate issued before the metadata existed was unless it was a
123
+ * wildcard or the operator deliberately picked DNS.
124
+ *
125
+ * @param {string} domainName The certificate's directory name
126
+ * @param {Object} [opts]
127
+ * @param {string} [opts.sslDir]
128
+ * @returns {Promise<{
129
+ * names: string[], www: boolean, wildcard: boolean,
130
+ * validationMethod: 'http'|'dns', source: 'certificate'|'meta'|'unknown'
131
+ * }>}
132
+ */
133
+ export async function describeCertificate(domainName, { sslDir } = {}) {
134
+ const dir = path.join(sslDir ?? loadConfig().sslDir, domainName);
135
+
136
+ let meta = null;
137
+ try {
138
+ meta = JSON.parse(await fs.readFile(path.join(dir, CERT_META_FILE), 'utf8'));
139
+ } catch { /* absent or unreadable: fall back to the certificate */ }
140
+
141
+ let names = null;
142
+ let source = 'unknown';
143
+ try {
144
+ const pem = await fs.readFile(path.join(dir, 'fullchain.pem'));
145
+ const info = acme.crypto.readCertificateInfo(pem);
146
+ const found = [info?.domains?.commonName, ...(info?.domains?.altNames ?? [])]
147
+ .filter((n) => typeof n === 'string' && n.length > 0);
148
+ if (found.length > 0) {
149
+ names = [...new Set(found)];
150
+ source = 'certificate';
151
+ }
152
+ } catch { /* not parseable: fall back to the metadata */ }
153
+
154
+ if (!names && Array.isArray(meta?.altNames) && meta.altNames.length > 0) {
155
+ names = meta.altNames.filter((n) => typeof n === 'string' && n.length > 0);
156
+ source = 'meta';
157
+ }
158
+ if (!names || names.length === 0) names = [domainName];
159
+
160
+ const wildcard = names.some((n) => n.startsWith('*.'));
161
+ const www = names.includes(`www.${domainName}`);
162
+ const validationMethod = wildcard || meta?.validationMethod === 'dns' ? 'dns' : 'http';
163
+
164
+ return { names, www, wildcard, validationMethod, source };
165
+ }
166
+
167
+ /**
168
+ * True when an enabled domain actually serves this certificate.
169
+ *
170
+ * The certificate directory routinely holds leftovers — a site that moved
171
+ * away, a certificate issued by hand to try something. Their DNS often no
172
+ * longer points here, so renewing them would fail every time and spend
173
+ * Let's Encrypt's failed-validation budget on certificates nobody uses.
174
+ *
175
+ * @param {string} certDomain
176
+ * @param {Array<Object>} domains
177
+ * @param {string} sslDir
178
+ * @returns {boolean}
179
+ */
180
+ export function isCertInUse(certDomain, domains, sslDir) {
181
+ const norm = (p) => String(p ?? '').replace(/\\/g, '/').toLowerCase();
182
+ const dir = `${norm(path.join(sslDir, certDomain))}/`;
183
+
184
+ return (domains ?? []).some((d) => {
185
+ if (d?.enabled === false || !d?.ssl?.enabled) return false;
186
+ if (d.name === certDomain) return true;
187
+ return norm(d.ssl?.certPath).startsWith(dir) || norm(d.ssl?.keyPath).startsWith(dir);
188
+ });
189
+ }
190
+
191
+ // ─── Renewing one certificate ─────────────────────────────────────────────────
192
+
193
+ /** Plain-text reason out of an issueCertificate() / renewCertificate() result. */
194
+ export function failureReason(result) {
195
+ const cause = result?.error?.cause ?? result?.error ?? 'Certificate renewal failed';
196
+ // The cause can be a multi-paragraph hint; a notification wants its headline.
197
+ return String(cause).split('\n')[0].trim();
198
+ }
199
+
200
+ /**
201
+ * Renews one certificate, keeping the names it already covers, and reloads
202
+ * nginx when nginx was left running so the new certificate is actually served.
203
+ *
204
+ * Returns issueCertificate()'s result with three additions:
205
+ * - `info` what describeCertificate() found
206
+ * - `skipped` 'manual' when the certificate needs DNS-01 (nothing was attempted)
207
+ * - `nginxReloaded` true/false after a proxy-mode renewal, null otherwise
208
+ *
209
+ * @param {string} domainName
210
+ * @param {Object} [options]
211
+ * @param {string|null} [options.email]
212
+ * @param {'auto'|'proxy'|'standalone'} [options.mode] Explicit challenge mode
213
+ * @param {boolean} [options.unattended] Never stop a running nginx (see header)
214
+ * @param {Object} [options.deps] Injected collaborators (testing only)
215
+ * @returns {Promise<Object>}
216
+ */
217
+ export async function renewCertificate(domainName, options = {}) {
218
+ const { email = null, mode = null, unattended = false, deps = {} } = options;
219
+ const {
220
+ issue = issueCertificate,
221
+ prepare = prepareDomainForHttpChallenge,
222
+ reload = reloadNginx,
223
+ nginxStatus = getStatus,
224
+ describe = describeCertificate,
225
+ lookupDomain = findDomain,
226
+ } = deps;
227
+
228
+ const config = loadConfig();
229
+ const info = await describe(domainName);
230
+
231
+ const base = {
232
+ success: false, certPath: null, keyPath: null, mode: null, fellBack: false,
233
+ nginxDownMs: 0, staging: false, preflight: null, configRegenerated: false,
234
+ error: null, info, skipped: null, nginxReloaded: null,
235
+ };
236
+
237
+ if (info.validationMethod === 'dns') {
238
+ return {
239
+ ...base,
240
+ skipped: 'manual',
241
+ mode: 'dns-01',
242
+ error: {
243
+ step: 'validation method',
244
+ cause: info.wildcard
245
+ ? `${domainName} is a wildcard certificate, which needs DNS-01 validation and a TXT record added by hand.`
246
+ : `${domainName} was validated over DNS-01, which needs a TXT record added by hand.`,
247
+ consequence: 'No certificate was requested. Renew it from the SSL page with the DNS method.',
248
+ nginxRunning: true,
249
+ configSaved: false,
250
+ },
251
+ };
252
+ }
253
+
254
+ // A config written before the challenge location existed cannot answer the
255
+ // challenge in proxy mode. Regenerating it is a reload, never a stop.
256
+ const record = lookupDomain(domainName);
257
+ let prepared = null;
258
+ if (record) {
259
+ prepared = await prepare(record);
260
+ if (!prepared.ok) {
261
+ return {
262
+ ...base,
263
+ error: {
264
+ step: 'challenge setup',
265
+ cause: prepared.error ?? 'nginx could not be prepared to answer the ACME challenge.',
266
+ consequence: 'No certificate was requested.',
267
+ nginxRunning: true,
268
+ configSaved: false,
269
+ },
270
+ };
271
+ }
272
+ }
273
+
274
+ let chosenMode = mode;
275
+ if (!chosenMode && unattended) {
276
+ const requested = config.sslChallengeMode || CHALLENGE_MODES.AUTO;
277
+ if (requested === CHALLENGE_MODES.AUTO) {
278
+ let running = false;
279
+ try { running = Boolean((await nginxStatus())?.running); } catch { running = false; }
280
+ // nginx up: proxy only, so nothing can stop it. nginx down: leave 'auto',
281
+ // whose standalone path then has nothing to stop.
282
+ if (running) chosenMode = CHALLENGE_MODES.PROXY;
283
+ }
284
+ }
285
+
286
+ const result = await issue(domainName, {
287
+ www: info.www,
288
+ validationMethod: 'http',
289
+ email: email || config.acmeEmail,
290
+ ...(chosenMode ? { mode: chosenMode } : {}),
291
+ });
292
+
293
+ // Standalone mode restarts nginx itself, which loads the new certificate.
294
+ // Proxy mode leaves it running with the old one in memory.
295
+ let nginxReloaded = null;
296
+ 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;
305
+ }
306
+ }
307
+
308
+ return {
309
+ ...base,
310
+ ...result,
311
+ info,
312
+ skipped: null,
313
+ configRegenerated: Boolean(result?.configRegenerated || prepared?.regenerated),
314
+ nginxReloaded,
315
+ reloadDetail,
316
+ };
317
+ }
318
+
319
+ /**
320
+ * describeIssuance() plus the reload outcome, for callers reporting a renewal.
321
+ * @param {Object} result Value returned by renewCertificate()
322
+ * @returns {string}
323
+ */
324
+ export function describeRenewal(result) {
325
+ const parts = [describeIssuance(result)].filter(Boolean);
326
+ if (result?.nginxReloaded === true) parts.push('nginx reloaded');
327
+ if (result?.nginxReloaded === false) {
328
+ parts.push('nginx reload FAILED — it is still serving the old certificate until it is reloaded');
329
+ }
330
+ return parts.join(' · ');
331
+ }
332
+
333
+ // ─── The unattended job ───────────────────────────────────────────────────────
334
+
335
+ /** Per-certificate bookkeeping: `{ [domain]: { lastAttemptAt, lastResult, ... } }`. */
336
+ export function getAutoRenewState() {
337
+ const state = dbGet(STATE_KEY);
338
+ return state && typeof state === 'object' && !Array.isArray(state) ? state : {};
339
+ }
340
+
341
+ function saveAutoRenewState(state) {
342
+ dbSet(STATE_KEY, state);
343
+ }
344
+
345
+ /**
346
+ * What the auto-renew job would do with one certificate right now, without
347
+ * doing it. Shared by the job and by the API that shows the plan in the UI, so
348
+ * the badge on the SSL page cannot promise something the job will not do.
349
+ *
350
+ * @returns {'auto'|'manual'|'unused'|'off'}
351
+ * auto — will be renewed in the background
352
+ * manual — DNS-01 / wildcard: warning only
353
+ * unused — no enabled domain serves it, so it is left alone
354
+ * off — auto-renewal is switched off
355
+ */
356
+ export function autoRenewPlan({ certDomain, info, settings, domains, sslDir }) {
357
+ if (!settings.enabled) return 'off';
358
+ if (info.validationMethod === 'dns') return 'manual';
359
+ if (!isCertInUse(certDomain, domains, sslDir)) return 'unused';
360
+ return 'auto';
361
+ }
362
+
363
+ /**
364
+ * One pass of automatic renewal.
365
+ *
366
+ * Runs in whichever process owns the background jobs (core/jobs/index.js
367
+ * elects exactly one), so two processes never renew the same certificate.
368
+ *
369
+ * @param {Object} [opts]
370
+ * @param {number} [opts.now]
371
+ * @param {(event: Object, domain: string) => (void|Promise<void>)} [opts.onEvent]
372
+ * Receives the renewed / failed notification events. The caller decides
373
+ * where they go; this module knows nothing about buses or channels.
374
+ * @param {Object} [opts.deps] Injected collaborators (testing only)
375
+ * @returns {Promise<{
376
+ * enabled: boolean, days: number,
377
+ * results: Array<{ domain: string, action: 'renewed'|'failed'|'manual'|'skipped', reason: string }>
378
+ * }>}
379
+ */
380
+ export async function runAutoRenewal({ now = Date.now(), onEvent = null, deps = {} } = {}) {
381
+ const {
382
+ listCerts = listAllCerts,
383
+ renew = renewCertificate,
384
+ describe = describeCertificate,
385
+ listDomains = getDomains,
386
+ bumpRevision = bumpHubRevision,
387
+ } = deps;
388
+
389
+ const config = loadConfig();
390
+ const settings = getAutoRenewSettings(config);
391
+ const out = { enabled: settings.enabled, days: settings.days, results: [] };
392
+ if (!settings.enabled) return out;
393
+
394
+ let certs;
395
+ try {
396
+ certs = await listCerts();
397
+ } catch {
398
+ // A missing or unreadable certificate directory is normal on a fresh install.
399
+ return out;
400
+ }
401
+
402
+ const state = getAutoRenewState();
403
+ let stateDirty = false;
404
+
405
+ // Forget certificates that no longer exist, so the record cannot grow for ever.
406
+ const present = new Set(certs.map((c) => c.domain));
407
+ for (const name of Object.keys(state)) {
408
+ if (!present.has(name)) { delete state[name]; stateDirty = true; }
409
+ }
410
+
411
+ const emit = async (event, domain) => {
412
+ if (!onEvent) return;
413
+ try { await onEvent(event, domain); } catch (err) {
414
+ console.error('[cert-renewal] notification failed:', err.message);
415
+ }
416
+ };
417
+
418
+ const domains = listDomains();
419
+ let renewedAny = false;
420
+
421
+ for (const cert of certs) {
422
+ if (cert.daysLeft === null || cert.daysLeft > settings.days) continue;
423
+
424
+ const info = await describe(cert.domain);
425
+ const plan = autoRenewPlan({
426
+ certDomain: cert.domain, info, settings, domains, sslDir: config.sslDir,
427
+ });
428
+
429
+ if (plan === 'manual') {
430
+ out.results.push({ domain: cert.domain, action: 'manual', reason: 'DNS-01 certificate — needs a manual renewal' });
431
+ continue;
432
+ }
433
+ if (plan === 'unused') {
434
+ out.results.push({ domain: cert.domain, action: 'skipped', reason: 'no enabled domain uses this certificate' });
435
+ continue;
436
+ }
437
+
438
+ const previous = state[cert.domain] ?? {};
439
+ if (previous.lastAttemptAt && now - previous.lastAttemptAt < RENEW_RETRY_MS) {
440
+ out.results.push({ domain: cert.domain, action: 'skipped', reason: 'attempted recently — waiting before retrying' });
441
+ continue;
442
+ }
443
+
444
+ // Recorded BEFORE the attempt and written straight away: if this process
445
+ // dies mid-issuance, the next start must still see that an attempt was made.
446
+ state[cert.domain] = { ...previous, lastAttemptAt: now };
447
+ saveAutoRenewState(state);
448
+ stateDirty = false;
449
+
450
+ let result;
451
+ if (!config.acmeEmail) {
452
+ result = { success: false, error: { cause: 'No ACME email is configured. Set it in Settings.' } };
453
+ } else {
454
+ try {
455
+ result = await renew(cert.domain, { email: config.acmeEmail, unattended: true });
456
+ } catch (err) {
457
+ result = { success: false, error: { cause: err.message } };
458
+ }
459
+ }
460
+
461
+ if (result?.success) {
462
+ const summary = describeRenewal(result);
463
+ state[cert.domain] = {
464
+ lastAttemptAt: now, lastResult: 'renewed', lastRenewedAt: now, lastError: null, failures: 0,
465
+ };
466
+ renewedAny = true;
467
+ out.results.push({ domain: cert.domain, action: 'renewed', reason: summary });
468
+ console.log(`[cert-renewal] ${cert.domain}: renewed — ${summary}`);
469
+ await emit(createCertRenewedEvent(cert.domain, summary), cert.domain);
470
+ } else {
471
+ const reason = failureReason(result);
472
+ state[cert.domain] = {
473
+ ...previous,
474
+ lastAttemptAt: now,
475
+ lastResult: 'failed',
476
+ lastError: reason,
477
+ failures: (previous.failures ?? 0) + 1,
478
+ };
479
+ out.results.push({ domain: cert.domain, action: 'failed', reason });
480
+ console.error(`[cert-renewal] ${cert.domain}: renewal failed — ${reason}`);
481
+ await emit(createCertRenewFailedEvent(cert.domain, cert.daysLeft, reason), cert.domain);
482
+ }
483
+ stateDirty = true;
484
+ }
485
+
486
+ if (stateDirty) saveAutoRenewState(state);
487
+
488
+ // A linked Hub shows certificate expiry; tell the agent it changed.
489
+ if (renewedAny) {
490
+ try { bumpRevision(); } catch { /* not linked, or nothing to bump */ }
491
+ }
492
+
493
+ return out;
494
+ }