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
@@ -1,23 +1,29 @@
1
1
  import { createServer } from 'http';
2
- import http from 'http';
3
2
  import { createRequire } from 'module';
4
- import { spawn } from 'child_process';
5
3
  import express from 'express';
4
+ import fs from 'fs';
6
5
  import { fileURLToPath } from 'url';
7
6
  import path from 'path';
8
- import os from 'os';
9
7
  import crypto from 'crypto';
10
8
  import session from 'express-session';
11
- import { Server as SocketIO } from 'socket.io';
12
- import { loadConfig } from '../core/config.js';
13
- import { dbGet, dbSet } from '../core/db.js';
9
+ import { loadConfig, UI_MODES } from '../core/config.js';
10
+ import { dbGet, dbSet, closeDb } from '../core/db.js';
11
+ import { getDataDir, isDevDataDir, TEST_MODE_ENV } from '../core/platform.js';
14
12
  import authRouter from './routes/auth.js';
15
13
  import domainsRouter from './routes/domains.js';
16
14
  import sslRouter from './routes/ssl.js';
17
15
  import nginxRouter from './routes/nginx.js';
18
16
  import settingsRouter from './routes/settings.js';
19
- import { getStatus } from './lib/nginx-service.js';
20
- import { listAllCerts } from './lib/cert-reader.js';
17
+ import hubRouter from './routes/hub.js';
18
+ import processesRouter from './routes/processes.js';
19
+ import deploymentsRouter from './routes/deployments.js';
20
+ import { ensureCode as ensureSetupCode, describe as describeSetupCode } from '../core/setupCode.js';
21
+ import { warmProbes } from './controllers/processesController.js';
22
+ import { stopSslController } from './controllers/sslController.js';
23
+ import { initSocket, stopSocket } from './socketManager.js';
24
+ import { requireLocalRequest } from './lib/localRequest.js';
25
+ import { startJobs } from '../core/jobs/index.js';
26
+ import { startDaemonBridge, daemonStatus } from './lib/daemonBridge.js';
21
27
 
22
28
  const require = createRequire(import.meta.url);
23
29
  const FileStore = require('session-file-store')(session);
@@ -39,191 +45,299 @@ if (!sessionSecret) {
39
45
  dbSet('session_secret', sessionSecret);
40
46
  }
41
47
 
42
- // Sessions stored on disk so they survive restarts
43
- const SESSION_DIR = process.platform === 'win32'
44
- ? path.join(process.env.APPDATA || os.homedir(), 'easy-devops', 'sessions')
45
- : path.join(os.homedir(), '.config', 'easy-devops', 'sessions');
48
+ // Sessions stored on disk so they survive restarts. Same data directory as the
49
+ // database and logs — see getDataDir() in core/platform.js.
50
+ const SESSION_DIR = path.join(getDataDir(), 'sessions');
46
51
 
47
- app.use(session({
52
+ // Kept in a variable so shutdown() can stop its expired-session reaper, which
53
+ // is an un-unref'd setInterval that would otherwise hold the event loop open.
54
+ const sessionStore = new FileStore({ path: SESSION_DIR, retries: 1, logFn() {} });
55
+
56
+ // Kept in a variable so Socket.io can run the SAME middleware and therefore
57
+ // see the same session. Without it, a socket connection has no session to
58
+ // authenticate against and the dashboard's live data would be unprotected
59
+ // even though every HTTP route is not.
60
+ const sessionMiddleware = session({
48
61
  secret: sessionSecret,
49
62
  resave: false,
50
63
  saveUninitialized: false,
51
- store: new FileStore({ path: SESSION_DIR, retries: 1, logFn() {} }),
52
- cookie: { httpOnly: true },
53
- }));
54
-
55
- // Static files - disable index serving so EJS handles root
56
- app.use(express.static(path.join(__dirname, 'public'), { index: false }));
57
-
58
- app.use('/api', authRouter);
59
- app.use('/api/domains', domainsRouter);
60
- app.use('/api/ssl', sslRouter);
61
- app.use('/api/nginx', nginxRouter);
62
- app.use('/api', settingsRouter);
63
-
64
- // Render EJS template for all other routes
65
- app.use((req, res) => res.render('index'));
64
+ store: sessionStore,
65
+ cookie: {
66
+ httpOnly: true,
67
+ sameSite: 'lax',
68
+ },
69
+ });
66
70
 
67
- // ─── HTTP server + Socket.io ──────────────────────────────────────────────────
71
+ app.use(sessionMiddleware);
68
72
 
69
- const httpServer = createServer(app);
70
- const io = new SocketIO(httpServer);
73
+ // ─── Listener configuration ───────────────────────────────────────────────────
71
74
 
72
- let connectedClients = 0;
75
+ const startupConfig = loadConfig();
76
+ const { dashboardPort, dashboardBindAddress } = startupConfig;
77
+ const port = Number(process.env.DASHBOARD_PORT) || dashboardPort;
73
78
 
74
- async function emitNginxStatus(target) {
79
+ // Which interfaces to accept connections on. New Linux installs default to
80
+ // loopback only; existing installs keep listening on every interface, so an
81
+ // upgrade cannot silently cut off a dashboard someone reaches over the
82
+ // network. See core/config.js.
83
+ const bindAddress = process.env.DASHBOARD_BIND_ADDRESS?.trim() || dashboardBindAddress;
84
+
85
+ /** The port actually bound, known only once listening (tests may pass 0). */
86
+ let boundPort = null;
87
+
88
+ /**
89
+ * What the local-request guard should enforce right now.
90
+ *
91
+ * The bind address is re-read from the config on every call rather than taken
92
+ * from the startup value, so changing it in Settings takes effect for the
93
+ * guard immediately instead of waiting for a restart. When the two disagree —
94
+ * the setting has changed but the listener has not been rebound yet — the
95
+ * config value is the user's stated intent, and erring toward the stricter
96
+ * loopback rule is the safe direction.
97
+ */
98
+ function currentBinding() {
99
+ let configured = bindAddress;
75
100
  try {
76
- const status = await getStatus();
77
- target.emit('nginx:status', status);
78
- // Emit notification if nginx is down
79
- if (!status.running) {
80
- target.emit('notification:new', {
81
- id: 'nginx-down',
82
- type: 'nginx_down',
83
- severity: 'danger',
84
- message: 'Nginx is not running',
85
- timestamp: Date.now(),
86
- });
87
- }
88
- } catch (err) {
89
- target.emit('nginx:status', { running: false, version: null, pid: null, error: err.message });
90
- }
91
- }
101
+ configured = loadConfig().dashboardBindAddress ?? bindAddress;
102
+ } catch { /* unreadable config: fall back to what we started with */ }
92
103
 
93
- // ─── Cert expiry notifications ────────────────────────────────────────────────
94
- async function emitCertNotifications(target) {
95
- try {
96
- const certs = await listAllCerts();
97
- for (const cert of certs) {
98
- if (cert.daysLeft !== null && cert.daysLeft < 30) {
99
- const severity = cert.daysLeft < 10 ? 'danger' : 'warning';
100
- target.emit('notification:new', {
101
- id: `cert-expiry-${cert.domain}`,
102
- type: 'cert_expiry',
103
- severity,
104
- message: `SSL cert for ${cert.domain} expires in ${cert.daysLeft} day${cert.daysLeft === 1 ? '' : 's'}`,
105
- domain: cert.domain,
106
- timestamp: Date.now(),
107
- });
108
- }
109
- }
110
- } catch { /* non-fatal */ }
104
+ return { port: boundPort ?? port, bindAddress: configured };
111
105
  }
112
106
 
113
- // ─── Domain health checks ─────────────────────────────────────────────────────
114
- function checkDomainHealth(host, port) {
115
- return new Promise((resolve) => {
116
- const req = http.request({ host, port: Number(port), path: '/', method: 'HEAD', timeout: 5000 }, (res) => {
117
- resolve({ up: true, status: res.statusCode });
118
- res.resume();
119
- });
120
- req.on('timeout', () => { req.destroy(); resolve({ up: false }); });
121
- req.on('error', () => resolve({ up: false }));
122
- req.end();
123
- });
107
+ // ─── Which UI is served at / ─────────────────────────────────────────────────
108
+ //
109
+ // The React build in dist/ui is THE dashboard. The classic EJS + Vue page is
110
+ // kept only as a temporary fallback, reachable by `--classic-ui` for one run
111
+ // or `dashboardUi: "classic"` as a setting. The flag wins, being the one-run
112
+ // override.
113
+ //
114
+ // This reverses the earlier default. It changed because the new UI is now the
115
+ // one being developed against docs/api-contract.md, and leaving the old page
116
+ // as the default meant every new install started on the implementation that is
117
+ // no longer maintained. The EJS files stay in the tree: an operator who hits a
118
+ // regression in the new UI needs a working dashboard in the same minute, not
119
+ // in the next release.
120
+ //
121
+ // The build is produced at publish time (npm run build:ui) and is not required
122
+ // to run from a source checkout, so a MISSING build falls back to classic with
123
+ // the build command printed, rather than failing to start. Falling back keeps
124
+ // the dashboard reachable, which matters most in the middle of an upgrade.
125
+ const uiDistDir = process.env.EASY_DEVOPS_UI_DIST?.trim() ||
126
+ path.resolve(__dirname, '..', '..', 'dist', 'ui');
127
+ const uiIndexFile = path.join(uiDistDir, 'index.html');
128
+
129
+ const classicFlagRequested = process.env.EASY_DEVOPS_CLASSIC_UI === '1';
130
+ const classicRequested = classicFlagRequested || startupConfig.dashboardUi === UI_MODES.CLASSIC;
131
+ const classicRequestedBy = classicFlagRequested ? '--classic-ui' : 'the dashboardUi setting';
132
+
133
+ const uiBuilt = fs.existsSync(uiIndexFile);
134
+ const servingNewUi = !classicRequested && uiBuilt;
135
+
136
+ if (classicRequested) {
137
+ process.stdout.write(
138
+ `\nServing the classic dashboard (requested by ${classicRequestedBy}).\n` +
139
+ ' It is a temporary fallback and will be removed in a future release.\n\n'
140
+ );
141
+ } else if (!uiBuilt) {
142
+ process.stderr.write(
143
+ '\nThe dashboard UI is not built:\n' +
144
+ ` ${uiIndexFile}\n` +
145
+ ' Build it with: npm run build:ui\n' +
146
+ ' Serving the classic dashboard for this run.\n\n'
147
+ );
124
148
  }
125
149
 
126
- async function emitDomainHealth(target) {
127
- try {
128
- const domains = dbGet('domains') || [];
129
- const results = await Promise.all(
130
- domains.map(async (d) => {
131
- const host = d.backendHost || '127.0.0.1';
132
- const port = d.port || 80;
133
- // Skip external URL backends
134
- if (typeof host === 'string' && host.startsWith('http')) return { name: d.name, up: null };
135
- const { up } = await checkDomainHealth(host, port);
136
- return { name: d.name, up };
137
- })
138
- );
139
- target.emit('domain:health', results);
140
- } catch { /* non-fatal */ }
141
- }
150
+ // Static files - disable index serving so the classic EJS page handles root.
151
+ // Kept in both modes: the React build reuses /img assets from here.
152
+ app.use(express.static(path.join(__dirname, 'public'), { index: false }));
142
153
 
143
- // ─── Live log streaming ───────────────────────────────────────────────────────
144
- const activeTails = new Map(); // socketId → { process, logFile }
145
-
146
- function getLogPath(logFile) {
147
- const { nginxDir } = loadConfig();
148
- const file = logFile === 'access' ? 'access.log' : 'error.log';
149
- // Linux standard path first, fall back to nginxDir/logs/
150
- if (process.platform !== 'win32') {
151
- return `/var/log/nginx/${file}`;
152
- }
153
- return path.join(nginxDir, 'logs', file);
154
- }
154
+ /**
155
+ * Host / Origin / X-EZ-Request checks, on EVERY /api route including the
156
+ * public auth ones.
157
+ *
158
+ * Mounted before the routers so no endpoint can be added later that misses
159
+ * it, and above requireAuth because it answers a different question: not
160
+ * "who are you" but "may this request be made from where it came from".
161
+ * A password never defended against a hostile page in another browser tab;
162
+ * this does, in both auth modes.
163
+ *
164
+ * The binding is read per request so a settings change does not leave a stale
165
+ * rule in place until restart.
166
+ */
167
+ app.use('/api', requireLocalRequest(currentBinding));
155
168
 
156
- function startTail(socket, logFile) {
157
- // Kill any existing tail for this socket
158
- stopTail(socket.id);
159
-
160
- const logPath = getLogPath(logFile);
161
- const args = process.platform === 'win32'
162
- ? ['Get-Content', '-Path', logPath, '-Wait', '-Tail', '50']
163
- : ['-n', '50', '-f', logPath];
164
- const cmd = process.platform === 'win32' ? 'powershell' : 'tail';
165
-
166
- const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'ignore'] });
167
- let buf = '';
168
- child.stdout.on('data', (chunk) => {
169
- buf += chunk.toString();
170
- const lines = buf.split('\n');
171
- buf = lines.pop(); // keep incomplete line in buffer
172
- for (const line of lines) {
173
- if (line.trim()) socket.emit('logs:line', { line: line.trim(), logFile });
174
- }
169
+ app.use('/api', authRouter);
170
+ app.use('/api/domains', domainsRouter);
171
+ app.use('/api/ssl', sslRouter);
172
+ app.use('/api/nginx', nginxRouter);
173
+ app.use('/api', settingsRouter);
174
+ app.use('/api/hub', hubRouter);
175
+ app.use('/api', processesRouter);
176
+ app.use('/api/deployments', deploymentsRouter);
177
+
178
+ if (servingNewUi) {
179
+ // Hashed Vite assets are immutable; index.html is served with no-cache
180
+ // below, so a rebuilt bundle is picked up on the next page load.
181
+ app.use(express.static(uiDistDir, { index: false, maxAge: '1y', immutable: true }));
182
+
183
+ // Client-side routes such as /#/domains arrive here as GET / and are
184
+ // handled by the static index. A real path (/domains/example.com) gets the
185
+ // same index.html so the app can resolve it. Static files above win first,
186
+ // and /api and /socket.io never reach this point with a routed request.
187
+ app.use((req, res, next) => {
188
+ if (req.method !== 'GET' && req.method !== 'HEAD') return next();
189
+ res.sendFile(uiIndexFile, { headers: { 'Cache-Control': 'no-cache' } });
175
190
  });
176
- child.on('error', () => {});
177
- child.on('close', () => { activeTails.delete(socket.id); });
178
- activeTails.set(socket.id, { process: child, logFile });
191
+ } else {
192
+ // Render EJS template for all other routes
193
+ app.use((req, res) => res.render('index'));
179
194
  }
180
195
 
181
- function stopTail(socketId) {
182
- const entry = activeTails.get(socketId);
183
- if (entry) {
184
- try { entry.process.kill(); } catch {}
185
- activeTails.delete(socketId);
186
- }
196
+ // ─── HTTP server + Socket.io ──────────────────────────────────────────────────
197
+
198
+ const httpServer = createServer(app);
199
+ initSocket(httpServer, sessionMiddleware, currentBinding);
200
+
201
+ // ─── Background jobs ──────────────────────────────────────────────────────────
202
+ //
203
+ // The dashboard is a STANDBY runner: it does the monitoring, notifications and
204
+ // Hub work only while no daemon is running, and hands them over within one
205
+ // poll of one appearing (core/jobs/index.js). The hub agent is part of that
206
+ // hand-over, which is why it is no longer started here — two agents on one
207
+ // pairing would execute every Hub command twice.
208
+ //
209
+ // The bridge is started unconditionally: when a daemon exists it carries the
210
+ // daemon's events onto this process's bus, and when one does not it retries
211
+ // quietly and connects if the user installs the service later.
212
+ // The bridge starts FIRST so the jobs' first ownership change can already be
213
+ // announced to the browser through it. It also means the lock watcher is in
214
+ // place before anything else looks at the lock.
215
+ const daemonLink = startDaemonBridge();
216
+
217
+ const jobs = startJobs({
218
+ role: 'dashboard',
219
+ onChange(state) {
220
+ process.stdout.write(
221
+ state.running
222
+ ? `Background jobs: running in this dashboard (${state.reason})\n`
223
+ : `Background jobs: not run here - ${state.reason}\n`,
224
+ );
225
+
226
+ // Who owns the jobs is part of the state the UI shows, so a hand-over in
227
+ // either direction reaches open tabs immediately rather than on their next
228
+ // poll of GET /api/service.
229
+ daemonLink.announce();
230
+ },
231
+ });
232
+
233
+ /**
234
+ * Prints the first-run setup code, if one is outstanding.
235
+ *
236
+ * Issues one when none is valid, so a dashboard left at the first-run screen
237
+ * for a day is still completable. Prints the cleartext only when THIS process
238
+ * issued it: nothing stores the cleartext, which is the point.
239
+ */
240
+ async function announceSetupCode() {
241
+ const state = await ensureSetupCode({ config: loadConfig() });
242
+ if (!state.pending) return;
243
+ for (const line of describeSetupCode(state)) process.stdout.write(`${line}\n`);
187
244
  }
188
245
 
189
- io.on('connection', (socket) => {
190
- connectedClients++;
191
- emitNginxStatus(socket);
192
- emitCertNotifications(socket);
246
+ // ─── Start ────────────────────────────────────────────────────────────────────
193
247
 
194
- socket.on('logs:subscribe', ({ logFile }) => startTail(socket, logFile || 'error'));
195
- socket.on('logs:unsubscribe', () => stopTail(socket.id));
248
+ // Resolved above the router mounts, which need them for the local-request
249
+ // guard. `boundPort` is filled in once the server is listening, because a
250
+ // port of 0 (tests) is only known then.
251
+
252
+ /** Resolves with the port actually bound, once the server is listening. */
253
+ const whenListening = new Promise((resolve, reject) => {
254
+ httpServer.once('error', reject);
255
+ httpServer.listen(port, bindAddress, () => {
256
+ const bound = httpServer.address()?.port ?? port;
257
+ boundPort = bound;
258
+ if (isDevDataDir()) {
259
+ process.stdout.write(`DEV MODE (data: ${getDataDir()})\n`);
260
+ }
261
+ process.stdout.write(`Dashboard running on port ${bound} (bound to ${bindAddress})\n`);
262
+ process.stdout.write(
263
+ servingNewUi
264
+ ? `Dashboard UI: new (${uiDistDir})\n`
265
+ : 'Dashboard UI: classic (EJS)\n'
266
+ );
196
267
 
197
- // Send initial domain health on connect
198
- emitDomainHealth(socket);
268
+ // The first-run setup code, while setup is still pending. Printed here
269
+ // because this is the local terminal (or the log file a detached
270
+ // dashboard writes to) - the one place it is allowed to appear. It is
271
+ // never in an API response, a socket event, or anything sent to the Hub.
272
+ //
273
+ // Not awaited: hashing the code takes scrypt-time and the server must not
274
+ // delay listening for it. A failure is reported and nothing else, because
275
+ // a dashboard that cannot print a code must still start.
276
+ // Fill the status probes now, so the first page load finds them already
277
+ // measured. Each one costs a subprocess - about a second each on Windows -
278
+ // and paying for them while someone watches a spinner is what made
279
+ // GET /api/service feel broken. Not awaited: the server is already
280
+ // listening and a warm-up is not a precondition for serving.
281
+ //
282
+ // Not under EZ_TEST. A suite starts and kills dashboards in seconds and
283
+ // never reads a warm answer, so the half-dozen subprocesses per start are
284
+ // pure cost there - and measurably so: they slowed the suite enough to
285
+ // push a latency assertion in another suite over its deadline. The warm
286
+ // path itself is exercised directly in e2e/service-speed.test.mjs.
287
+ if (process.env[TEST_MODE_ENV] !== '1') warmProbes();
288
+
289
+ announceSetupCode().catch((err) => {
290
+ process.stderr.write(`[setup] could not prepare the setup code: ${err.message}\n`);
291
+ });
199
292
 
200
- socket.on('disconnect', () => {
201
- connectedClients--;
202
- stopTail(socket.id);
293
+ resolve(bound);
203
294
  });
204
295
  });
205
296
 
206
- // Poll domain health every 60 seconds
207
- setInterval(() => {
208
- if (connectedClients > 0) emitDomainHealth(io);
209
- }, 60_000);
210
-
211
- // Broadcast nginx status to all clients every 5 seconds
212
- setInterval(() => {
213
- if (connectedClients > 0) emitNginxStatus(io);
214
- }, 5000);
297
+ // ─── Shutdown ─────────────────────────────────────────────────────────────────
298
+
299
+ let shutdownPromise = null;
300
+
301
+ /**
302
+ * Releases everything this module started: the HTTP server, the Socket.io
303
+ * polling intervals and log tails, the hub agent, and the SQLite handle.
304
+ *
305
+ * Idempotent — concurrent or repeated calls (a second Ctrl+C during shutdown)
306
+ * return the same promise and never double-close.
307
+ *
308
+ * @returns {Promise<void>}
309
+ */
310
+ function shutdown() {
311
+ if (shutdownPromise) return shutdownPromise;
312
+
313
+ shutdownPromise = (async () => {
314
+ // Stop accepting connections first so nothing new arrives mid-teardown.
315
+ await new Promise((resolve) => {
316
+ if (!httpServer.listening) return resolve();
317
+ httpServer.close(() => resolve());
318
+ });
215
319
 
216
- // Check cert expiry every 12 hours
217
- setInterval(() => {
218
- if (connectedClients > 0) emitCertNotifications(io);
219
- }, 12 * 60 * 60 * 1000);
320
+ try { await stopSocket(); } catch { /* already down */ }
321
+ try { daemonLink.stop(); } catch { /* never connected */ }
322
+ // Stops the monitors, the revision watcher and the hub agent together, and
323
+ // is a no-op when a daemon owns them.
324
+ try { await jobs.stop(); } catch { /* already stopped */ }
325
+ try { stopSslController(); } catch { /* nothing pending */ }
326
+
327
+ // session-file-store schedules an expired-session reaper with setInterval
328
+ // and offers no stop API; the handle is exposed on its options.
329
+ try {
330
+ const reaper = sessionStore?.options?.reapIntervalObject;
331
+ if (reaper) {
332
+ clearInterval(reaper);
333
+ sessionStore.options.reapIntervalObject = null;
334
+ }
335
+ } catch { /* nothing to clear */ }
220
336
 
221
- // ─── Start ────────────────────────────────────────────────────────────────────
337
+ try { closeDb(); } catch { /* already closed */ }
338
+ })();
222
339
 
223
- const { dashboardPort } = loadConfig();
224
- const port = Number(process.env.DASHBOARD_PORT) || dashboardPort;
225
- httpServer.listen(port, () => {
226
- process.stdout.write(`Dashboard running on port ${port}\n`);
227
- });
340
+ return shutdownPromise;
341
+ }
228
342
 
229
- export { app };
343
+ export { app, httpServer, whenListening, shutdown, daemonStatus };