easy-devops 1.2.1 → 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 (126) 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 +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 +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/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 +39 -52
  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 +171 -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 +9 -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
@@ -0,0 +1,46 @@
1
+ import express from 'express';
2
+ import DeploymentsController from '../controllers/deploymentsController.js';
3
+ import { requireAuth } from '../lib/requireAuth.js';
4
+
5
+ const router = express.Router();
6
+ const controller = new DeploymentsController();
7
+
8
+ /**
9
+ * These routes fetch code from a repository and run its build and start
10
+ * commands on this machine. They are behind the shared session gate like
11
+ * everything else, and that is not optional: without it, anything that can
12
+ * reach the dashboard port could run commands here.
13
+ *
14
+ * The deploy hook that CI calls is NOT one of these routes. It is a separate,
15
+ * opt-in listener with its own per-app token (core/deploy/hookServer.js), so
16
+ * that nothing on the dashboard has to be public for a GitHub Action to work.
17
+ */
18
+ router.use(requireAuth);
19
+
20
+ // The hook settings come first so "hook" is never read as an app id.
21
+ // (apps.js also refuses to create an app with that name.)
22
+ router.get('/hook', (req, res, next) => controller.hook(req, res, next));
23
+ router.put('/hook', (req, res, next) => controller.updateHook(req, res, next));
24
+
25
+ router.get('/', (req, res, next) => controller.list(req, res, next));
26
+ router.post('/', (req, res, next) => controller.create(req, res, next));
27
+
28
+ router.get('/:id', (req, res, next) => controller.get(req, res, next));
29
+ router.put('/:id', (req, res, next) => controller.update(req, res, next));
30
+ router.delete('/:id', (req, res, next) => controller.remove(req, res, next));
31
+
32
+ router.put('/:id/domain', (req, res, next) => controller.linkDomain(req, res, next));
33
+ router.delete('/:id/domain', (req, res, next) => controller.unlinkDomain(req, res, next));
34
+ router.post('/:id/move', (req, res, next) => controller.move(req, res, next));
35
+
36
+ router.post('/:id/deploy', (req, res, next) => controller.deploy(req, res, next));
37
+ router.post('/:id/rollback', (req, res, next) => controller.rollback(req, res, next));
38
+ router.get('/:id/runs/:runId', (req, res, next) => controller.run(req, res, next));
39
+
40
+ router.post('/:id/hook-token', (req, res, next) => controller.hookToken(req, res, next));
41
+ router.delete('/:id/hook-token', (req, res, next) => controller.revokeHookToken(req, res, next));
42
+ router.post('/:id/deploy-key', (req, res, next) => controller.deployKey(req, res, next));
43
+ router.get('/:id/github', (req, res, next) => controller.github(req, res, next));
44
+ router.post('/:id/github/apply', (req, res, next) => controller.githubApply(req, res, next));
45
+
46
+ export default router;
@@ -1,9 +1,18 @@
1
1
  import express from 'express';
2
2
  import DomainsController from '../controllers/domainsController.js';
3
+ import { requireAuth } from '../lib/requireAuth.js';
3
4
 
4
5
  const router = express.Router();
5
6
  const controller = new DomainsController();
6
7
 
8
+ /**
9
+ * Every route below requires a dashboard session. See lib/requireAuth.js —
10
+ * this is the single gate, and removing it exposes these endpoints to anyone
11
+ * who can reach the dashboard port.
12
+ */
13
+ router.use(requireAuth);
14
+
15
+
7
16
  router.get('/', (req, res, next) => controller.list(req, res, next));
8
17
  router.post('/', (req, res, next) => controller.create(req, res, next));
9
18
  router.put('/:name', (req, res, next) => controller.update(req, res, next));
@@ -0,0 +1,22 @@
1
+ // src/dashboard/routes/hub.js
2
+ import { Router } from 'express';
3
+ import {
4
+ connectAgent,
5
+ unlinkHub,
6
+ hubStatus,
7
+ updatePermissions,
8
+ } from '../controllers/hubController.js';
9
+ import { requireAuth } from '../lib/requireAuth.js';
10
+
11
+ const router = Router();
12
+
13
+ // The shared gate — see lib/requireAuth.js.
14
+ router.use(requireAuth);
15
+
16
+ // The hub generates connection strings; this server only consumes them.
17
+ router.post('/connect', connectAgent);
18
+ router.delete('/link', unlinkHub);
19
+ router.get('/status', hubStatus);
20
+ router.put('/permissions', updatePermissions);
21
+
22
+ export default router;
@@ -1,9 +1,18 @@
1
1
  import express from 'express';
2
2
  import NginxController from '../controllers/nginxController.js';
3
+ import { requireAuth } from '../lib/requireAuth.js';
3
4
 
4
5
  const router = express.Router();
5
6
  const controller = new NginxController();
6
7
 
8
+ /**
9
+ * Every route below requires a dashboard session. See lib/requireAuth.js —
10
+ * this is the single gate, and removing it exposes these endpoints to anyone
11
+ * who can reach the dashboard port.
12
+ */
13
+ router.use(requireAuth);
14
+
15
+
7
16
  router.get('/status', (req, res, next) => controller.status(req, res, next));
8
17
  router.post('/reload', (req, res, next) => controller.reload(req, res, next));
9
18
  router.post('/restart', (req, res, next) => controller.restart(req, res, next));
@@ -0,0 +1,29 @@
1
+ import express from 'express';
2
+ import ProcessesController from '../controllers/processesController.js';
3
+ import { requireAuth } from '../lib/requireAuth.js';
4
+
5
+ const router = express.Router();
6
+ const controller = new ProcessesController();
7
+
8
+ /**
9
+ * These routes can start and stop processes, so they are behind the shared
10
+ * session gate. Do not remove it: without it, anything that can reach the
11
+ * dashboard port could control PM2.
12
+ */
13
+ router.use(requireAuth);
14
+
15
+ // Service status and lifecycle come first so they are not shadowed by /:name.
16
+ //
17
+ // All of them sit behind requireAuth above, exactly like every other route:
18
+ // starting and stopping the background service is as privileged as anything
19
+ // else the dashboard can do.
20
+ router.get('/service', (req, res) => controller.status(req, res));
21
+ router.post('/service/start', (req, res) => controller.start(req, res));
22
+ router.post('/service/stop', (req, res) => controller.stop(req, res));
23
+ router.post('/service/restart', (req, res) => controller.restart(req, res));
24
+
25
+ router.get('/processes', (req, res) => controller.list(req, res));
26
+ router.get('/processes/:name/logs', (req, res) => controller.logs(req, res));
27
+ router.post('/processes/:name/:action', (req, res) => controller.action(req, res));
28
+
29
+ export default router;
@@ -1,9 +1,18 @@
1
1
  import express from 'express';
2
2
  import SettingsController from '../controllers/settingsController.js';
3
+ import { requireAuth } from '../lib/requireAuth.js';
3
4
 
4
5
  const router = express.Router();
5
6
  const controller = new SettingsController();
6
7
 
8
+ /**
9
+ * Every route below requires a dashboard session. See lib/requireAuth.js —
10
+ * this is the single gate, and removing it exposes these endpoints to anyone
11
+ * who can reach the dashboard port.
12
+ */
13
+ router.use(requireAuth);
14
+
15
+
7
16
  router.get('/settings', (req, res, next) => controller.get(req, res, next));
8
17
  router.post('/settings', (req, res, next) => controller.update(req, res, next));
9
18
  router.get('/settings/permissions', (req, res, next) => controller.getPermissions(req, res, next));
@@ -1,9 +1,18 @@
1
1
  import express from 'express';
2
2
  import SslController from '../controllers/sslController.js';
3
+ import { requireAuth } from '../lib/requireAuth.js';
3
4
 
4
5
  const router = express.Router();
5
6
  const controller = new SslController();
6
7
 
8
+ /**
9
+ * Every route below requires a dashboard session. See lib/requireAuth.js —
10
+ * this is the single gate, and removing it exposes these endpoints to anyone
11
+ * who can reach the dashboard port.
12
+ */
13
+ router.use(requireAuth);
14
+
15
+
7
16
  router.post('/create', (req, res, next) => controller.create(req, res, next));
8
17
  router.post('/create-confirm', (req, res, next) => controller.createConfirm(req, res, next));
9
18
  router.post('/create-cancel', (req, res, next) => controller.createCancel(req, res, next));
@@ -1,19 +1,29 @@
1
1
  import { createServer } from 'http';
2
2
  import { createRequire } from 'module';
3
3
  import express from 'express';
4
+ import fs from 'fs';
4
5
  import { fileURLToPath } from 'url';
5
6
  import path from 'path';
6
- import os from 'os';
7
7
  import crypto from 'crypto';
8
8
  import session from 'express-session';
9
- import { loadConfig } from '../core/config.js';
10
- 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';
11
12
  import authRouter from './routes/auth.js';
12
13
  import domainsRouter from './routes/domains.js';
13
14
  import sslRouter from './routes/ssl.js';
14
15
  import nginxRouter from './routes/nginx.js';
15
16
  import settingsRouter from './routes/settings.js';
16
- import { initSocket } from './socketManager.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';
17
27
 
18
28
  const require = createRequire(import.meta.url);
19
29
  const FileStore = require('session-file-store')(session);
@@ -35,42 +45,299 @@ if (!sessionSecret) {
35
45
  dbSet('session_secret', sessionSecret);
36
46
  }
37
47
 
38
- // Sessions stored on disk so they survive restarts
39
- const SESSION_DIR = process.platform === 'win32'
40
- ? path.join(process.env.APPDATA || os.homedir(), 'easy-devops', 'sessions')
41
- : 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');
42
51
 
43
- 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({
44
61
  secret: sessionSecret,
45
62
  resave: false,
46
63
  saveUninitialized: false,
47
- store: new FileStore({ path: SESSION_DIR, retries: 1, logFn() {} }),
48
- cookie: { httpOnly: true },
49
- }));
64
+ store: sessionStore,
65
+ cookie: {
66
+ httpOnly: true,
67
+ sameSite: 'lax',
68
+ },
69
+ });
70
+
71
+ app.use(sessionMiddleware);
72
+
73
+ // ─── Listener configuration ───────────────────────────────────────────────────
74
+
75
+ const startupConfig = loadConfig();
76
+ const { dashboardPort, dashboardBindAddress } = startupConfig;
77
+ const port = Number(process.env.DASHBOARD_PORT) || dashboardPort;
78
+
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;
100
+ try {
101
+ configured = loadConfig().dashboardBindAddress ?? bindAddress;
102
+ } catch { /* unreadable config: fall back to what we started with */ }
103
+
104
+ return { port: boundPort ?? port, bindAddress: configured };
105
+ }
106
+
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
+ );
148
+ }
50
149
 
51
- // Static files - disable index serving so EJS handles root
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.
52
152
  app.use(express.static(path.join(__dirname, 'public'), { index: false }));
53
153
 
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));
168
+
54
169
  app.use('/api', authRouter);
55
170
  app.use('/api/domains', domainsRouter);
56
171
  app.use('/api/ssl', sslRouter);
57
172
  app.use('/api/nginx', nginxRouter);
58
173
  app.use('/api', settingsRouter);
174
+ app.use('/api/hub', hubRouter);
175
+ app.use('/api', processesRouter);
176
+ app.use('/api/deployments', deploymentsRouter);
59
177
 
60
- // Render EJS template for all other routes
61
- app.use((req, res) => res.render('index'));
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' } });
190
+ });
191
+ } else {
192
+ // Render EJS template for all other routes
193
+ app.use((req, res) => res.render('index'));
194
+ }
62
195
 
63
196
  // ─── HTTP server + Socket.io ──────────────────────────────────────────────────
64
197
 
65
198
  const httpServer = createServer(app);
66
- initSocket(httpServer);
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`);
244
+ }
67
245
 
68
246
  // ─── Start ────────────────────────────────────────────────────────────────────
69
247
 
70
- const { dashboardPort } = loadConfig();
71
- const port = Number(process.env.DASHBOARD_PORT) || dashboardPort;
72
- httpServer.listen(port, () => {
73
- process.stdout.write(`Dashboard running on port ${port}\n`);
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
+ );
267
+
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
+ });
292
+
293
+ resolve(bound);
294
+ });
74
295
  });
75
296
 
76
- export { app };
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
+ });
319
+
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 */ }
336
+
337
+ try { closeDb(); } catch { /* already closed */ }
338
+ })();
339
+
340
+ return shutdownPromise;
341
+ }
342
+
343
+ export { app, httpServer, whenListening, shutdown, daemonStatus };