easy-devops 1.2.1 → 1.3.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 (126) hide show
  1. package/README.md +97 -6
  2. package/dist/ui/assets/index-CMRzkIKj.css +1 -0
  3. package/dist/ui/assets/index-DEouL3IK.js +452 -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 +15 -4
  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 +92 -1
  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 +222 -47
  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/cleanup.js +600 -0
  42. package/src/core/config.js +169 -2
  43. package/src/core/daemon/ipc.js +292 -0
  44. package/src/core/daemon/lock.js +294 -0
  45. package/src/core/daemon/run.js +241 -0
  46. package/src/core/daemon/stopRequest.js +162 -0
  47. package/src/core/db.js +37 -8
  48. package/src/core/deploy/apps.js +491 -0
  49. package/src/core/deploy/domainLink.js +200 -0
  50. package/src/core/deploy/engine.js +973 -0
  51. package/src/core/deploy/ezfile.js +361 -0
  52. package/src/core/deploy/github.js +239 -0
  53. package/src/core/deploy/githubApi.js +261 -0
  54. package/src/core/deploy/hookServer.js +325 -0
  55. package/src/core/deploy/hubCommands.js +267 -0
  56. package/src/core/deploy/launcher.js +57 -0
  57. package/src/core/deploy/status.js +91 -0
  58. package/src/core/deploy/store.js +398 -0
  59. package/src/core/domainNotifier.js +94 -28
  60. package/src/core/domains-db.js +234 -0
  61. package/src/core/events.js +94 -2
  62. package/src/core/hub/agent.js +842 -0
  63. package/src/core/hubLink.js +306 -0
  64. package/src/core/hubPermissions.js +430 -0
  65. package/src/core/installSource.js +162 -0
  66. package/src/core/jobs/bus.js +120 -0
  67. package/src/core/jobs/index.js +371 -0
  68. package/src/core/jobs/monitors.js +368 -0
  69. package/src/core/jobs/owner.js +217 -0
  70. package/src/core/jobs/revisionWatcher.js +106 -0
  71. package/src/core/nginx-apply.js +213 -0
  72. package/src/core/nginx-conf-generator.js +253 -17
  73. package/src/{dashboard/lib → core}/nginx-service.js +18 -9
  74. package/src/core/notifications/claim.js +214 -0
  75. package/src/core/notifications/dispatch.js +154 -0
  76. package/src/core/notifier.js +31 -1
  77. package/src/core/passwords.js +172 -0
  78. package/src/core/permissions.js +8 -4
  79. package/src/core/platform.js +709 -2
  80. package/src/core/probeCache.js +258 -0
  81. package/src/core/purge.js +372 -0
  82. package/src/core/runner.js +488 -0
  83. package/src/core/service/acl.js +226 -0
  84. package/src/core/service/dataDir.js +345 -0
  85. package/src/core/service/index.js +1128 -0
  86. package/src/core/service/legacy.js +218 -0
  87. package/src/core/service/runtime.js +446 -0
  88. package/src/core/service/runtimeUpdate.js +800 -0
  89. package/src/core/service/systemd.js +458 -0
  90. package/src/core/service/windowsPersonal.js +530 -0
  91. package/src/core/service/windowsService.js +576 -0
  92. package/src/core/service/winsw.js +260 -0
  93. package/src/core/setupCode.js +331 -0
  94. package/src/core/shell.js +70 -7
  95. package/src/core/ssl-issuer.js +627 -0
  96. package/src/core/updater.js +295 -0
  97. package/src/core/validators.js +99 -0
  98. package/src/dashboard/controllers/authController.js +302 -15
  99. package/src/dashboard/controllers/deploymentsController.js +479 -0
  100. package/src/dashboard/controllers/domainsController.js +80 -61
  101. package/src/dashboard/controllers/hubController.js +135 -0
  102. package/src/dashboard/controllers/nginxController.js +21 -3
  103. package/src/dashboard/controllers/processesController.js +368 -0
  104. package/src/dashboard/controllers/settingsController.js +180 -12
  105. package/src/dashboard/controllers/sslController.js +288 -10
  106. package/src/dashboard/lib/daemonBridge.js +163 -0
  107. package/src/dashboard/lib/localRequest.js +235 -0
  108. package/src/dashboard/lib/loginRateLimit.js +119 -0
  109. package/src/dashboard/lib/requireAuth.js +80 -0
  110. package/src/dashboard/public/js/app.js +489 -19
  111. package/src/dashboard/routes/auth.js +10 -10
  112. package/src/dashboard/routes/deployments.js +46 -0
  113. package/src/dashboard/routes/domains.js +9 -0
  114. package/src/dashboard/routes/hub.js +22 -0
  115. package/src/dashboard/routes/nginx.js +9 -0
  116. package/src/dashboard/routes/processes.js +29 -0
  117. package/src/dashboard/routes/settings.js +9 -0
  118. package/src/dashboard/routes/ssl.js +10 -0
  119. package/src/dashboard/server.js +288 -21
  120. package/src/dashboard/socketManager.js +171 -207
  121. package/src/dashboard/views/index.ejs +1 -0
  122. package/src/dashboard/views/partials/login.ejs +68 -7
  123. package/src/dashboard/views/partials/processes-panel.ejs +261 -0
  124. package/src/dashboard/views/partials/settings-panel.ejs +287 -0
  125. package/src/dashboard/views/partials/sidebar.ejs +2 -0
  126. package/src/dashboard/lib/domains-db.js +0 -51
@@ -2,23 +2,58 @@ import fs from 'fs/promises';
2
2
  import path from 'path';
3
3
  import os from 'os';
4
4
  import crypto from 'crypto';
5
- import { loadConfig, saveConfig } from '../../core/config.js';
5
+ import {
6
+ loadConfig, saveConfig, BIND_ALL, BIND_LOOPBACK, BIND_LOOPBACK_V6,
7
+ AUTH_MODES, UI_MODES, isLoopbackBind, effectiveAuthMode,
8
+ } from '../../core/config.js';
9
+ import { isLoopbackAddress } from '../lib/localRequest.js';
10
+ import { hashPassword, validateNewPassword } from '../../core/passwords.js';
6
11
  import { validatePort, validateEmail } from '../../core/validators.js';
12
+ import {
13
+ getAutoRenewSettings, normalizeAutoRenewDays, MIN_AUTO_RENEW_DAYS, MAX_AUTO_RENEW_DAYS,
14
+ } from '../../core/cert-renewal.js';
7
15
  import { run, runWithStdin } from '../../core/shell.js';
8
16
  import { checkPermissionsConfigured } from '../../core/permissions.js';
9
17
  import { dbGet, dbSet } from '../../core/db.js';
18
+ import { deployRoot, defaultDeployRoot, validateDeployDir } from '../../core/deploy/store.js';
19
+ import { saveDomains } from '../../core/domains-db.js';
10
20
  import { loadChannels, saveChannels, sendNotification } from '../../core/notifier.js';
11
21
 
12
22
  class SettingsController {
13
23
  get(req, res) {
14
24
  try {
15
25
  const config = loadConfig();
16
- const { dashboardPort, nginxDir, sslDir, acmeEmail } = config;
26
+ const { dashboardPort, nginxDir, sslDir, acmeEmail, dashboardBindAddress } = config;
27
+ const hasPassword = Boolean(config.dashboardPasswordHash || config.dashboardPassword);
28
+ const autoRenew = getAutoRenewSettings(config);
29
+ // Neither the password nor its hash is ever returned.
17
30
  res.json({
18
31
  dashboardPort,
19
32
  nginxDir,
20
33
  sslDir,
21
34
  acmeEmail,
35
+ // Background renewal of HTTP-01 certificates (core/cert-renewal.js).
36
+ // The limits are published so no client hard-codes them.
37
+ sslAutoRenew: autoRenew.enabled,
38
+ sslAutoRenewDays: autoRenew.days,
39
+ sslAutoRenewDaysMin: MIN_AUTO_RENEW_DAYS,
40
+ sslAutoRenewDaysMax: MAX_AUTO_RENEW_DAYS,
41
+ // Where NEW deployed apps are created. Existing apps stay where they
42
+ // were created; moving one is an action on the Deployments page.
43
+ deployDir: deployRoot(),
44
+ deployDirDefault: defaultDeployRoot(),
45
+ deployDirIsDefault: !config.deployDir,
46
+ dashboardBindAddress,
47
+ bindsToLoopbackOnly: isLoopbackBind(dashboardBindAddress),
48
+ dashboardAuth: effectiveAuthMode(config),
49
+ // Anything unrecognised reads as classic, which is also the
50
+ // default. The value only takes effect on restart.
51
+ dashboardUi: config.dashboardUi === UI_MODES.NEW ? UI_MODES.NEW : UI_MODES.CLASSIC,
52
+ // Whether the UI may offer 'none' at all: the bind must be loopback
53
+ // and the person asking must be on this machine.
54
+ canUseNoPassword: isLoopbackBind(dashboardBindAddress) &&
55
+ isLoopbackAddress(req.ip ?? req.socket?.remoteAddress),
56
+ hasPassword,
22
57
  platform: process.platform === 'win32' ? 'win32' : 'linux',
23
58
  });
24
59
  } catch (err) {
@@ -26,17 +61,79 @@ class SettingsController {
26
61
  }
27
62
  }
28
63
 
29
- update(req, res) {
64
+ async update(req, res) {
30
65
  try {
31
- const { dashboardPort, dashboardPassword, nginxDir, sslDir, acmeEmail } = req.body;
66
+ const {
67
+ dashboardPort, dashboardPassword, nginxDir, sslDir, acmeEmail, dashboardBindAddress,
68
+ dashboardAuth, dashboardUi, sslAutoRenew, sslAutoRenewDays, deployDir,
69
+ } = req.body;
70
+
71
+ const current = loadConfig();
32
72
 
33
73
  if (dashboardPort !== undefined) {
34
74
  const portError = validatePort(parseInt(dashboardPort, 10));
35
75
  if (portError) return res.status(400).json({ error: portError });
36
76
  }
37
77
 
38
- if (dashboardPassword !== undefined && typeof dashboardPassword !== 'string') {
39
- return res.status(400).json({ error: 'Password must be a string' });
78
+ // A password set from here is held to the same minimum as the
79
+ // first-run one, and is never stored in clear.
80
+ if (dashboardPassword !== undefined) {
81
+ const problem = validateNewPassword(dashboardPassword);
82
+ if (problem) return res.status(400).json({ error: problem });
83
+ }
84
+
85
+ if (dashboardBindAddress !== undefined &&
86
+ ![BIND_ALL, BIND_LOOPBACK, BIND_LOOPBACK_V6].includes(dashboardBindAddress)) {
87
+ return res.status(400).json({
88
+ error: `Bind address must be ${BIND_LOOPBACK} (this machine only) or ${BIND_ALL} (all interfaces)`,
89
+ });
90
+ }
91
+
92
+ if (dashboardAuth !== undefined &&
93
+ ![AUTH_MODES.PASSWORD, AUTH_MODES.NONE].includes(dashboardAuth)) {
94
+ return res.status(400).json({
95
+ error: `Authentication must be '${AUTH_MODES.PASSWORD}' or '${AUTH_MODES.NONE}'`,
96
+ });
97
+ }
98
+
99
+ if (dashboardUi !== undefined &&
100
+ ![UI_MODES.CLASSIC, UI_MODES.NEW].includes(dashboardUi)) {
101
+ return res.status(400).json({
102
+ error: `Dashboard UI must be '${UI_MODES.CLASSIC}' or '${UI_MODES.NEW}'`,
103
+ });
104
+ }
105
+
106
+ // ── The auth/bind interlock ──────────────────────────────────────
107
+ //
108
+ // 'none' is only safe while nothing but this machine can reach the
109
+ // listener, so the two settings are validated TOGETHER against the
110
+ // state this request would produce — not against the current state.
111
+ // Otherwise a single request could set both and slip through by
112
+ // checking each against the old value.
113
+ const nextAuth = dashboardAuth ?? current.dashboardAuth;
114
+ const nextBind = dashboardBindAddress ?? current.dashboardBindAddress;
115
+
116
+ if (nextAuth === AUTH_MODES.NONE && !isLoopbackBind(nextBind)) {
117
+ // Which half the user is changing decides which message helps.
118
+ const changingBind = dashboardBindAddress !== undefined &&
119
+ dashboardBindAddress !== current.dashboardBindAddress;
120
+
121
+ return res.status(400).json({
122
+ error: changingBind
123
+ ? 'This dashboard has no password, so it can only listen on this machine. Set a password first, then change where it listens.'
124
+ : `Running without a password requires the dashboard to listen on this machine only (currently ${nextBind}).`,
125
+ reason: changingBind ? 'bind_requires_password' : 'no_auth_requires_loopback',
126
+ });
127
+ }
128
+
129
+ // Turning auth OFF is only ever done from the machine itself.
130
+ if (dashboardAuth === AUTH_MODES.NONE &&
131
+ current.dashboardAuth !== AUTH_MODES.NONE &&
132
+ !isLoopbackAddress(req.ip ?? req.socket?.remoteAddress)) {
133
+ return res.status(403).json({
134
+ error: 'Removing the password can only be done from this machine.',
135
+ reason: 'no_auth_requires_local_request',
136
+ });
40
137
  }
41
138
 
42
139
  if (nginxDir !== undefined && (typeof nginxDir !== 'string' || nginxDir.trim() === '')) {
@@ -51,17 +148,68 @@ class SettingsController {
51
148
  if (emailError) return res.status(400).json({ error: emailError });
52
149
  }
53
150
 
54
- const currentConfig = loadConfig();
151
+ if (sslAutoRenew !== undefined && typeof sslAutoRenew !== 'boolean') {
152
+ return res.status(400).json({ error: 'sslAutoRenew must be true or false' });
153
+ }
154
+ if (sslAutoRenewDays !== undefined && normalizeAutoRenewDays(sslAutoRenewDays) === null) {
155
+ return res.status(400).json({
156
+ error: `Auto-renew days must be a whole number from ${MIN_AUTO_RENEW_DAYS} to ${MAX_AUTO_RENEW_DAYS}`,
157
+ });
158
+ }
159
+
160
+ // An empty value means "back to the default".
161
+ const resetDeployDir = deployDir === null || (typeof deployDir === 'string' && deployDir.trim() === '');
162
+ if (deployDir !== undefined && !resetDeployDir) {
163
+ const dirError = validateDeployDir(deployDir);
164
+ if (dirError) return res.status(400).json({ error: dirError });
165
+ try {
166
+ await fs.mkdir(path.resolve(deployDir.trim()), { recursive: true });
167
+ } catch (err) {
168
+ return res.status(400).json({ error: `That folder cannot be created or written to: ${err.message}` });
169
+ }
170
+ }
171
+
172
+ const currentConfig = current;
55
173
  const updates = {};
56
174
 
57
175
  if (dashboardPort !== undefined) updates.dashboardPort = parseInt(dashboardPort, 10);
58
- if (dashboardPassword !== undefined) updates.dashboardPassword = dashboardPassword;
176
+ if (dashboardPassword !== undefined) {
177
+ updates.dashboardPasswordHash = await hashPassword(dashboardPassword);
178
+ // Drop any legacy plain-text copy at the same time.
179
+ updates.dashboardPassword = '';
180
+ }
181
+ if (dashboardBindAddress !== undefined) updates.dashboardBindAddress = dashboardBindAddress;
182
+ if (dashboardAuth !== undefined) updates.dashboardAuth = dashboardAuth;
183
+ if (dashboardUi !== undefined) updates.dashboardUi = dashboardUi;
184
+
185
+ // Setting a password implies wanting one; switching to 'password'
186
+ // without one leaves the first-run screen as the way back in, which
187
+ // is recoverable but not what anyone means by saving a password.
188
+ if (dashboardPassword !== undefined && dashboardAuth === undefined) {
189
+ updates.dashboardAuth = AUTH_MODES.PASSWORD;
190
+ }
59
191
  if (nginxDir !== undefined) updates.nginxDir = nginxDir.trim();
60
192
  if (sslDir !== undefined) updates.sslDir = sslDir.trim();
61
193
  if (acmeEmail !== undefined) updates.acmeEmail = acmeEmail.trim();
194
+ if (deployDir !== undefined) updates.deployDir = resetDeployDir ? null : path.resolve(deployDir.trim());
195
+ if (sslAutoRenew !== undefined) updates.sslAutoRenew = sslAutoRenew;
196
+ if (sslAutoRenewDays !== undefined) updates.sslAutoRenewDays = normalizeAutoRenewDays(sslAutoRenewDays);
62
197
 
63
198
  saveConfig({ ...currentConfig, ...updates });
64
- res.json({ success: true });
199
+
200
+ // The port, the bind address and the UI choice only take effect on
201
+ // restart, so say so rather than letting the user think the change is
202
+ // already live.
203
+ const needsRestart = updates.dashboardPort !== undefined ||
204
+ updates.dashboardBindAddress !== undefined ||
205
+ updates.dashboardUi !== undefined;
206
+
207
+ res.json({
208
+ success: true,
209
+ needsRestart,
210
+ dashboardAuth: effectiveAuthMode({ ...currentConfig, ...updates }),
211
+ dashboardUi: updates.dashboardUi ?? currentConfig.dashboardUi,
212
+ });
65
213
  } catch (err) {
66
214
  res.status(500).json({ error: 'Internal server error' });
67
215
  }
@@ -149,7 +297,14 @@ class SettingsController {
149
297
  try {
150
298
  const config = loadConfig();
151
299
  const domains = dbGet('domains') || [];
152
- const { dashboardPassword: _pw, ...safeConfig } = config;
300
+ // Strip BOTH the legacy plain-text password and the hash: a backup is
301
+ // a file the user downloads and may share, and a scrypt hash is still
302
+ // a credential worth cracking offline.
303
+ const {
304
+ dashboardPassword: _pw,
305
+ dashboardPasswordHash: _pwHash,
306
+ ...safeConfig
307
+ } = config;
153
308
  const backup = {
154
309
  version: 1,
155
310
  exportedAt: new Date().toISOString(),
@@ -171,10 +326,23 @@ class SettingsController {
171
326
  return res.status(400).json({ error: 'Invalid backup: missing config' });
172
327
  }
173
328
  const current = loadConfig();
174
- const merged = { ...current, ...config, dashboardPassword: current.dashboardPassword };
329
+ // A backup may predate hashed passwords and the bind setting. Never let
330
+ // one restore a plain-text password or silently re-open the listener.
331
+ const merged = {
332
+ ...current,
333
+ ...config,
334
+ dashboardPassword: current.dashboardPassword,
335
+ dashboardPasswordHash: current.dashboardPasswordHash,
336
+ dashboardBindAddress: current.dashboardBindAddress,
337
+ dashboardAuth: current.dashboardAuth,
338
+ };
175
339
  saveConfig(merged);
340
+ // Through saveDomains(), not dbSet: restoring a backup replaces the
341
+ // whole domain set, which the Hub must learn about like any other
342
+ // domain write. A bare dbSet skipped the revision bump and left the
343
+ // Hub showing the pre-restore list until the next restart.
176
344
  if (Array.isArray(domains)) {
177
- dbSet('domains', domains);
345
+ saveDomains(domains);
178
346
  }
179
347
  res.json({ success: true });
180
348
  } catch (err) {
@@ -1,14 +1,33 @@
1
- import { listAllCerts } from '../lib/cert-reader.js';
2
- import { issueCert, renewCert } from '../../cli/managers/ssl-manager.js';
1
+ import { listAllCerts } from '../../core/cert-reader.js';
2
+ import { issueCert } from '../../cli/managers/ssl-manager.js';
3
+ import {
4
+ renewCertificate,
5
+ describeRenewal,
6
+ describeCertificate,
7
+ getAutoRenewSettings,
8
+ getAutoRenewState,
9
+ autoRenewPlan,
10
+ } from '../../core/cert-renewal.js';
11
+ import { describeIssuance, prepareDomainForHttpChallenge } from '../../core/ssl-issuer.js';
12
+ import { findDomain, getDomains } from '../../core/domains-db.js';
3
13
  import { loadConfig } from '../../core/config.js';
14
+ import { isWindows } from '../../core/platform.js';
4
15
  import { promises as dns } from 'dns';
16
+ import fs from 'fs/promises';
17
+ import path from 'path';
18
+
19
+ // nginx writes its logs and scratch files here; those can grow large and never
20
+ // contain certificate paths.
21
+ const NGINX_SKIP_DIRS = new Set([
22
+ 'logs', 'temp', 'client_body_temp', 'proxy_temp', 'fastcgi_temp', 'uwsgi_temp', 'scgi_temp',
23
+ ]);
5
24
 
6
25
  // In-memory DNS challenge state
7
26
  // Keyed by domain name. Entries are cleaned up when the ACME process exits
8
27
  // or when cancelled. Entries older than 10 minutes are forcibly removed.
9
28
  const pendingDnsChallenges = new Map();
10
29
 
11
- setInterval(() => {
30
+ const dnsSweepTimer = setInterval(() => {
12
31
  const now = Date.now();
13
32
  for (const [domain, state] of pendingDnsChallenges) {
14
33
  if (now - state.createdAt > 10 * 60 * 1000) {
@@ -18,6 +37,90 @@ setInterval(() => {
18
37
  }
19
38
  }, 60000);
20
39
 
40
+ /**
41
+ * Stops the DNS-challenge sweep and rejects anything still pending.
42
+ *
43
+ * Called by the dashboard's shutdown(): this interval is created at module
44
+ * load and would otherwise keep the event loop alive, so `ezz --dash` would
45
+ * never exit on Ctrl+C. Safe to call more than once.
46
+ */
47
+ export function stopSslController() {
48
+ clearInterval(dnsSweepTimer);
49
+
50
+ for (const [domain, state] of pendingDnsChallenges) {
51
+ try {
52
+ state.confirmDeferred.reject(new Error('Dashboard is shutting down'));
53
+ } catch { /* already settled */ }
54
+ pendingDnsChallenges.delete(domain);
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Flattens a path so nginx configs written with forward slashes, Windows
60
+ * backslashes or doubled separators all compare equal.
61
+ */
62
+ function comparablePath(value) {
63
+ const slashed = String(value ?? '').replace(/\\/g, '/').replace(/\/{2,}/g, '/');
64
+ return isWindows ? slashed.toLowerCase() : slashed;
65
+ }
66
+
67
+ /**
68
+ * Collects every nginx configuration file under `dir` — the main nginx.conf,
69
+ * domain configs, and the `.conf.disabled` copies a disabled domain leaves.
70
+ */
71
+ async function collectConfigFiles(dir, found = []) {
72
+ let entries;
73
+ try {
74
+ entries = await fs.readdir(dir, { withFileTypes: true });
75
+ } catch {
76
+ return found;
77
+ }
78
+
79
+ for (const entry of entries) {
80
+ const full = path.join(dir, entry.name);
81
+ if (entry.isDirectory()) {
82
+ if (!NGINX_SKIP_DIRS.has(entry.name.toLowerCase())) {
83
+ await collectConfigFiles(full, found);
84
+ }
85
+ continue;
86
+ }
87
+ if (!entry.isFile() && !entry.isSymbolicLink()) continue;
88
+ const name = entry.name.toLowerCase();
89
+ if (name.endsWith('.conf') || name.endsWith('.conf.disabled')) found.push(full);
90
+ }
91
+
92
+ return found;
93
+ }
94
+
95
+ /**
96
+ * Finds every nginx config line that points at a file inside the certificate's
97
+ * directory, so deletion cannot leave nginx referencing missing files.
98
+ *
99
+ * @returns {Promise<Array<{ file: string, line: number, text: string }>>}
100
+ */
101
+ async function findCertReferences(domain, config) {
102
+ const target = `${comparablePath(path.join(config.sslDir, domain)).replace(/\/+$/, '')}/`;
103
+ const files = await collectConfigFiles(config.nginxDir);
104
+ const references = [];
105
+
106
+ for (const file of files) {
107
+ let content;
108
+ try {
109
+ content = await fs.readFile(file, 'utf8');
110
+ } catch {
111
+ continue;
112
+ }
113
+
114
+ content.split(/\r?\n/).forEach((text, index) => {
115
+ if (comparablePath(text).includes(target)) {
116
+ references.push({ file, line: index + 1, text: text.trim() });
117
+ }
118
+ });
119
+ }
120
+
121
+ return references;
122
+ }
123
+
21
124
  class SslController {
22
125
  async create(req, res, next) {
23
126
  try {
@@ -110,11 +213,40 @@ class SslController {
110
213
  return;
111
214
  }
112
215
 
113
- // HTTP validation path (synchronous — responds when complete)
216
+ // HTTP validation path (synchronous — responds when complete).
217
+ //
218
+ // Flow 2: make sure nginx can answer the challenge first. For a domain
219
+ // that is already configured this regenerates a stale config; for a new
220
+ // one it writes a temporary HTTP-only config. Either way nginx is only
221
+ // reloaded, never stopped.
222
+ const existing = findDomain(domainKey);
223
+ let prepared = null;
224
+ if (existing) {
225
+ prepared = await prepareDomainForHttpChallenge(existing);
226
+ if (!prepared.ok) {
227
+ return res.status(500).json({
228
+ error: 'challenge_setup_failed',
229
+ detail: prepared.error,
230
+ hint: 'nginx could not be prepared to answer the ACME challenge. Check the nginx config and try again.',
231
+ });
232
+ }
233
+ }
234
+
114
235
  const result = await issueCert(domainKey, { www: !!www, validationMethod: 'http', email: acmeEmail });
115
236
 
116
237
  if (result.success) {
117
- return res.json({ success: true, certPath: result.certPath, keyPath: result.keyPath });
238
+ // Tell the UI how the challenge ran: proxy (nginx stayed up), or a
239
+ // standalone fallback with how long nginx was stopped.
240
+ return res.json({
241
+ success: true,
242
+ certPath: result.certPath,
243
+ keyPath: result.keyPath,
244
+ mode: result.mode,
245
+ fellBack: result.fellBack,
246
+ nginxDownMs: result.nginxDownMs,
247
+ staging: result.staging,
248
+ summary: describeIssuance(result),
249
+ });
118
250
  }
119
251
 
120
252
  const { step } = result.error;
@@ -178,7 +310,18 @@ class SslController {
178
310
  pendingDnsChallenges.delete(domainKey);
179
311
 
180
312
  if (result.success) {
181
- return res.json({ success: true, certPath: result.certPath, keyPath: result.keyPath });
313
+ // Tell the UI how the challenge ran: proxy (nginx stayed up), or a
314
+ // standalone fallback with how long nginx was stopped.
315
+ return res.json({
316
+ success: true,
317
+ certPath: result.certPath,
318
+ keyPath: result.keyPath,
319
+ mode: result.mode,
320
+ fellBack: result.fellBack,
321
+ nginxDownMs: result.nginxDownMs,
322
+ staging: result.staging,
323
+ summary: describeIssuance(result),
324
+ });
182
325
  }
183
326
  return res.status(500).json({ success: false, error: result.error });
184
327
  } catch (error) {
@@ -212,7 +355,80 @@ class SslController {
212
355
  async list(req, res, next) {
213
356
  try {
214
357
  const certs = await listAllCerts();
215
- res.json(certs);
358
+
359
+ // Additive: what the background job intends for each certificate, so the
360
+ // UI can show "auto-renews" / "manual renewal" instead of leaving the
361
+ // operator to guess. Computed by the same function the job uses.
362
+ const config = loadConfig();
363
+ const settings = getAutoRenewSettings(config);
364
+ const domains = getDomains();
365
+ const state = getAutoRenewState();
366
+
367
+ const withPlan = await Promise.all(certs.map(async (cert) => {
368
+ let plan = 'off';
369
+ try {
370
+ const info = await describeCertificate(cert.domain);
371
+ plan = autoRenewPlan({ certDomain: cert.domain, info, settings, domains, sslDir: config.sslDir });
372
+ } catch { /* unreadable certificate: report it as not handled */ }
373
+
374
+ const last = state[cert.domain] ?? null;
375
+ return {
376
+ ...cert,
377
+ autoRenew: plan,
378
+ autoRenewDays: settings.days,
379
+ lastAutoRenew: last
380
+ ? {
381
+ at: last.lastAttemptAt ?? null,
382
+ result: last.lastResult ?? null,
383
+ error: last.lastError ?? null,
384
+ }
385
+ : null,
386
+ };
387
+ }));
388
+
389
+ res.json(withPlan);
390
+ } catch (error) {
391
+ next(error);
392
+ }
393
+ }
394
+
395
+ async remove(req, res, next) {
396
+ try {
397
+ const domain = req.params.domain;
398
+ const config = loadConfig();
399
+ const certs = await listAllCerts();
400
+ const cert = certs.find(entry => entry.domain === domain);
401
+
402
+ // listAllCerts() only returns direct children of sslDir, so taking the
403
+ // domain from it — not from the URL — also rules out path traversal.
404
+ if (!cert) {
405
+ return res.status(404).json({ error: `Certificate '${domain}' not found` });
406
+ }
407
+
408
+ const directory = path.join(config.sslDir, cert.domain);
409
+ const references = await findCertReferences(cert.domain, config);
410
+
411
+ if (references.length > 0) {
412
+ return res.status(409).json({
413
+ error: 'cert_in_use',
414
+ directory,
415
+ references,
416
+ hint:
417
+ 'At least one nginx config still points at this certificate. ' +
418
+ 'Disable SSL on those domains (or remove the lines) before deleting it.',
419
+ });
420
+ }
421
+
422
+ try {
423
+ await fs.rm(directory, { recursive: true, force: true });
424
+ } catch (error) {
425
+ return res.status(500).json({
426
+ error: 'delete_failed',
427
+ detail: `Could not delete ${directory}: ${error.message}`,
428
+ });
429
+ }
430
+
431
+ res.json({ deleted: cert.domain, directory });
216
432
  } catch (error) {
217
433
  next(error);
218
434
  }
@@ -236,13 +452,44 @@ class SslController {
236
452
  return res.status(404).json({ error: `Domain '${domain}' not found` });
237
453
  }
238
454
 
239
- const result = await renewCert(domain, { validationMethod: 'http', email: config.acmeEmail });
455
+ // renewCertificate() is the one renewal path (core/cert-renewal.js): it
456
+ // regenerates a config that predates the ACME challenge location, keeps
457
+ // the names the certificate already covers, and reloads nginx so the new
458
+ // certificate is the one being served.
459
+ const result = await renewCertificate(domain, { email: config.acmeEmail });
240
460
 
241
461
  if (result.success) {
242
- return res.json({ success: true, certPath: result.certPath, keyPath: result.keyPath });
462
+ // Tell the UI how the challenge ran: proxy (nginx stayed up), or a
463
+ // standalone fallback with how long nginx was stopped.
464
+ return res.json({
465
+ success: true,
466
+ certPath: result.certPath,
467
+ keyPath: result.keyPath,
468
+ mode: result.mode,
469
+ fellBack: result.fellBack,
470
+ nginxDownMs: result.nginxDownMs,
471
+ staging: result.staging,
472
+ nginxReloaded: result.nginxReloaded,
473
+ summary: describeRenewal(result),
474
+ });
475
+ }
476
+
477
+ if (result.skipped === 'manual') {
478
+ return res.status(409).json({
479
+ error: 'manual_renewal_required',
480
+ detail: result.error.cause,
481
+ hint: 'Create the certificate again from the SSL page using the DNS method.',
482
+ });
243
483
  }
244
484
 
245
485
  const { step } = result.error;
486
+ if (step === 'challenge setup') {
487
+ return res.status(500).json({
488
+ error: 'challenge_setup_failed',
489
+ detail: result.error.cause,
490
+ hint: 'nginx could not be prepared to answer the ACME challenge.',
491
+ });
492
+ }
246
493
  if (step === 'port 80 check') {
247
494
  return res.status(409).json({
248
495
  error: 'port_busy',
@@ -272,12 +519,43 @@ class SslController {
272
519
  const results = [];
273
520
 
274
521
  for (const cert of expiring) {
275
- const result = await renewCert(cert.domain, { validationMethod: 'http', email: config.acmeEmail });
522
+ const result = await renewCertificate(cert.domain, { email: config.acmeEmail });
523
+
524
+ if (!result.success && result.error?.step === 'challenge setup') {
525
+ results.push({
526
+ domain: cert.domain,
527
+ success: false,
528
+ certPath: null,
529
+ keyPath: null,
530
+ error: 'challenge_setup_failed',
531
+ detail: result.error.cause,
532
+ });
533
+ continue;
534
+ }
535
+
536
+ if (result.skipped === 'manual') {
537
+ results.push({
538
+ domain: cert.domain,
539
+ success: false,
540
+ certPath: null,
541
+ keyPath: null,
542
+ error: 'manual_renewal_required',
543
+ detail: result.error.cause,
544
+ });
545
+ continue;
546
+ }
547
+
276
548
  results.push({
277
549
  domain: cert.domain,
278
550
  success: result.success,
279
551
  certPath: result.certPath,
280
552
  keyPath: result.keyPath,
553
+ mode: result.mode,
554
+ fellBack: result.fellBack,
555
+ nginxDownMs: result.nginxDownMs,
556
+ configRegenerated: Boolean(result.configRegenerated),
557
+ nginxReloaded: result.nginxReloaded,
558
+ summary: describeRenewal(result),
281
559
  });
282
560
  }
283
561