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,235 @@
1
+ /**
2
+ * dashboard/lib/localRequest.js
3
+ *
4
+ * Defends the dashboard against *other websites* in the same browser.
5
+ *
6
+ * A session cookie, or no login at all, protects nothing from a page the user
7
+ * happens to have open in another tab. Two attacks matter here:
8
+ *
9
+ * DNS rebinding — a hostile domain resolves to 127.0.0.1, so the browser
10
+ * sends the request to the dashboard with the attacker's hostname in the
11
+ * Host header. Checking Host defeats it: the dashboard only answers to
12
+ * names that mean "this machine".
13
+ *
14
+ * Cross-site request forgery — a hostile page submits a form or fires a
15
+ * fetch at the dashboard, and the browser attaches the session cookie.
16
+ * Checking Origin defeats the fetch case; requiring a custom header
17
+ * defeats the rest, because a cross-site form POST cannot set one and a
18
+ * cross-site fetch that tries triggers a CORS preflight the dashboard
19
+ * never approves.
20
+ *
21
+ * Both apply in BOTH auth modes. They are not a substitute for a password —
22
+ * they stop a different attacker, one the password never protected against.
23
+ *
24
+ * ── On the Host check and non-loopback binds ───────────────────────────────
25
+ *
26
+ * When the dashboard is bound to loopback, Host must be a loopback name. That
27
+ * covers every `dashboardAuth: 'none'` install by construction, since that
28
+ * mode requires a loopback bind.
29
+ *
30
+ * When the user has deliberately bound to every interface to reach the
31
+ * dashboard from another machine, demanding Host=localhost would make the
32
+ * dashboard unreachable — so there the rule becomes same-origin instead:
33
+ * Origin, when present, must match the Host the request arrived on. That
34
+ * keeps the anti-CSRF guarantee without breaking the feature.
35
+ */
36
+
37
+ import { isLoopbackBind } from '../../core/config.js';
38
+
39
+ /** Header a legitimate dashboard client must send. */
40
+ export const REQUEST_HEADER = 'x-ez-request';
41
+ export const REQUEST_HEADER_VALUE = '1';
42
+
43
+ /** Hostnames that mean "this machine". */
44
+ const LOOPBACK_HOSTNAMES = Object.freeze(['localhost', '127.0.0.1', '::1', '[::1]']);
45
+
46
+ /** Methods that change state, and therefore need the custom header. */
47
+ const STATE_CHANGING = Object.freeze(['POST', 'PUT', 'PATCH', 'DELETE']);
48
+
49
+ /**
50
+ * Splits a Host header into hostname and port.
51
+ *
52
+ * Handles the bracketed IPv6 form (`[::1]:6443`), where splitting on the last
53
+ * colon would otherwise cut the address in half.
54
+ *
55
+ * @param {string} hostHeader
56
+ * @returns {{ hostname: string, port: string|null }|null}
57
+ */
58
+ export function parseHost(hostHeader) {
59
+ const raw = String(hostHeader ?? '').trim();
60
+ if (!raw) return null;
61
+
62
+ if (raw.startsWith('[')) {
63
+ const close = raw.indexOf(']');
64
+ if (close === -1) return null;
65
+ const hostname = raw.slice(1, close);
66
+ const rest = raw.slice(close + 1);
67
+ const port = rest.startsWith(':') ? rest.slice(1) : null;
68
+ return { hostname, port: port || null };
69
+ }
70
+
71
+ const colon = raw.lastIndexOf(':');
72
+ if (colon === -1) return { hostname: raw, port: null };
73
+ return { hostname: raw.slice(0, colon), port: raw.slice(colon + 1) || null };
74
+ }
75
+
76
+ /** True when a hostname means "this machine". */
77
+ export function isLoopbackHostname(hostname) {
78
+ return LOOPBACK_HOSTNAMES.includes(String(hostname ?? '').toLowerCase());
79
+ }
80
+
81
+ /** True when a remote address is a loopback address. */
82
+ export function isLoopbackAddress(addr) {
83
+ const a = String(addr ?? '');
84
+ // Express reports IPv4-mapped IPv6 as ::ffff:127.0.0.1.
85
+ return a === '127.0.0.1' || a === '::1' || a === '::ffff:127.0.0.1' ||
86
+ a.startsWith('127.');
87
+ }
88
+
89
+ /**
90
+ * Checks one request's Host, Origin and custom header.
91
+ *
92
+ * @param {Object} req Anything with { method, headers }
93
+ * @param {Object} opts
94
+ * @param {number} opts.port The port the dashboard is listening on
95
+ * @param {string} opts.bindAddress
96
+ * @param {boolean} [opts.requireHeader] Override the method-based decision
97
+ * @returns {{ ok: boolean, reason: string|null, detail: string|null }}
98
+ */
99
+ export function checkLocalRequest(req, { port, bindAddress, requireHeader } = {}) {
100
+ const headers = req?.headers ?? {};
101
+ const method = String(req?.method ?? 'GET').toUpperCase();
102
+ const loopbackOnly = isLoopbackBind(bindAddress);
103
+
104
+ // ── Host ──────────────────────────────────────────────────────────────────
105
+ const host = parseHost(headers.host);
106
+ if (!host) {
107
+ return { ok: false, reason: 'host_missing', detail: 'No Host header' };
108
+ }
109
+
110
+ // A mismatched port means the request was aimed somewhere else and arrived
111
+ // here — exactly the shape of a rebinding attempt.
112
+ if (host.port !== null && port !== undefined && String(port) !== host.port) {
113
+ return {
114
+ ok: false,
115
+ reason: 'host_port_mismatch',
116
+ detail: `Host port ${host.port} is not the dashboard port ${port}`,
117
+ };
118
+ }
119
+
120
+ if (loopbackOnly && !isLoopbackHostname(host.hostname)) {
121
+ return {
122
+ ok: false,
123
+ reason: 'host_not_local',
124
+ detail: `Host '${host.hostname}' is not a loopback name, and this dashboard is bound to ${bindAddress}`,
125
+ };
126
+ }
127
+
128
+ // ── Origin ────────────────────────────────────────────────────────────────
129
+ // Absent on same-origin navigations and simple GETs; present on anything a
130
+ // script sends cross-site, which is the case worth refusing.
131
+ const originHeader = headers.origin;
132
+ if (originHeader && originHeader !== 'null') {
133
+ let origin;
134
+ try {
135
+ origin = new URL(originHeader);
136
+ } catch {
137
+ return { ok: false, reason: 'origin_malformed', detail: `Origin '${originHeader}' is not a URL` };
138
+ }
139
+
140
+ const originPort = origin.port || (origin.protocol === 'https:' ? '443' : '80');
141
+ if (port !== undefined && String(port) !== originPort) {
142
+ return {
143
+ ok: false,
144
+ reason: 'origin_port_mismatch',
145
+ detail: `Origin port ${originPort} is not the dashboard port ${port}`,
146
+ };
147
+ }
148
+
149
+ if (loopbackOnly) {
150
+ if (!isLoopbackHostname(origin.hostname)) {
151
+ return {
152
+ ok: false,
153
+ reason: 'origin_not_local',
154
+ detail: `Origin '${origin.hostname}' is not a loopback name`,
155
+ };
156
+ }
157
+ } else if (origin.hostname.toLowerCase() !== host.hostname.toLowerCase()) {
158
+ // Non-loopback bind: same-origin instead of loopback-only, so remote
159
+ // access keeps working while cross-site requests still do not.
160
+ return {
161
+ ok: false,
162
+ reason: 'origin_cross_site',
163
+ detail: `Origin '${origin.hostname}' does not match Host '${host.hostname}'`,
164
+ };
165
+ }
166
+ }
167
+
168
+ // ── Custom header ─────────────────────────────────────────────────────────
169
+ const needsHeader = requireHeader ?? STATE_CHANGING.includes(method);
170
+ if (needsHeader && headers[REQUEST_HEADER] !== REQUEST_HEADER_VALUE) {
171
+ return {
172
+ ok: false,
173
+ reason: 'missing_request_header',
174
+ detail: `${method} requests must send ${REQUEST_HEADER}: ${REQUEST_HEADER_VALUE}`,
175
+ };
176
+ }
177
+
178
+ return { ok: true, reason: null, detail: null };
179
+ }
180
+
181
+ /**
182
+ * Express middleware factory.
183
+ *
184
+ * The port and bind address are read per request rather than captured, so a
185
+ * settings change does not leave a stale rule behind until restart.
186
+ *
187
+ * @param {() => { port: number, bindAddress: string }} getBinding
188
+ */
189
+ export function requireLocalRequest(getBinding) {
190
+ return function localRequestGuard(req, res, next) {
191
+ const { port, bindAddress } = getBinding();
192
+ const verdict = checkLocalRequest(req, { port, bindAddress });
193
+
194
+ if (verdict.ok) return next();
195
+
196
+ // 403, not 401: this is not "log in", it is "this request may not be made
197
+ // from where it came from". A 401 would send the UI to the login screen
198
+ // for a problem a login cannot fix.
199
+ return res.status(403).json({
200
+ error: 'Forbidden',
201
+ reason: verdict.reason,
202
+ detail: verdict.detail,
203
+ });
204
+ };
205
+ }
206
+
207
+ /**
208
+ * Socket.io middleware factory.
209
+ *
210
+ * The handshake is held to the same rules, with the custom header required
211
+ * unconditionally — there is no "safe method" for opening a socket.
212
+ *
213
+ * Browsers cannot set headers on a WebSocket upgrade, which is why the client
214
+ * must not force `transports: ['websocket']`: socket.io's default starts with
215
+ * HTTP polling, where extraHeaders does apply, and the handshake is
216
+ * authenticated there before any upgrade.
217
+ *
218
+ * @param {() => { port: number, bindAddress: string }} getBinding
219
+ */
220
+ export function socketRequireLocalRequest(getBinding) {
221
+ return function socketLocalGuard(socket, next) {
222
+ const { port, bindAddress } = getBinding();
223
+ const verdict = checkLocalRequest(socket.request, {
224
+ port,
225
+ bindAddress,
226
+ requireHeader: true,
227
+ });
228
+
229
+ if (verdict.ok) return next();
230
+
231
+ const err = new Error('FORBIDDEN');
232
+ err.data = { reason: verdict.reason, detail: verdict.detail };
233
+ return next(err);
234
+ };
235
+ }
@@ -0,0 +1,119 @@
1
+ /**
2
+ * dashboard/lib/loginRateLimit.js
3
+ *
4
+ * In-memory rate limiting for the login endpoint: 10 attempts per 15 minutes
5
+ * per client IP.
6
+ *
7
+ * Deliberately not `express-rate-limit`, which the hub backend uses — the
8
+ * easy-devops constitution forbids adding a dependency here, and a fixed
9
+ * window over a Map is enough for one login route on a single-process
10
+ * dashboard.
11
+ *
12
+ * In memory means the counters reset when the dashboard restarts. That is an
13
+ * accepted limit: the point is to make online guessing impractical, not to
14
+ * survive a restart, and an attacker cannot trigger a restart from outside.
15
+ *
16
+ * ── Separate budgets ───────────────────────────────────────────────────────
17
+ *
18
+ * Callers name a BUCKET, and each bucket counts independently per IP. Login
19
+ * and first-run setup are different questions, and sharing one counter would
20
+ * mean a few mistyped setup codes locked the user out of logging in, or that
21
+ * an attacker could burn the setup budget by failing logins. The setup code
22
+ * additionally has a global cap of its own, in core/setupCode.js — that is the
23
+ * part a per-IP limit cannot provide.
24
+ */
25
+
26
+ /** Attempts allowed per window, per IP. */
27
+ const MAX_ATTEMPTS = 10;
28
+
29
+ /** Window length. */
30
+ const WINDOW_MS = 15 * 60 * 1000;
31
+
32
+ /**
33
+ * Entries are dropped once their window has passed, so the map cannot grow
34
+ * without bound. The sweep is lazy — it runs on access rather than on a
35
+ * timer, because a module-level setInterval would keep the event loop alive
36
+ * and stop `ezz --dash` exiting on Ctrl+C (a bug this project has hit twice).
37
+ */
38
+ const attempts = new Map();
39
+
40
+ /** Sweeps expired entries. Cheap: the map only holds recent IPs. */
41
+ function prune(now) {
42
+ for (const [key, entry] of attempts) {
43
+ if (now >= entry.resetAt) attempts.delete(key);
44
+ }
45
+ }
46
+
47
+ /**
48
+ * The client's address.
49
+ *
50
+ * `req.ip` already honours Express's trust-proxy setting, which this app does
51
+ * not enable — so this is the socket address, not a spoofable header. That is
52
+ * the right default: trusting X-Forwarded-For without a configured proxy
53
+ * would let anyone reset their own limit by sending a header.
54
+ *
55
+ * @param {import('express').Request} req
56
+ * @returns {string}
57
+ */
58
+ export function clientKey(req, bucket = 'login') {
59
+ const ip = req.ip || req.socket?.remoteAddress || 'unknown';
60
+ return `${bucket}:${ip}`;
61
+ }
62
+
63
+ /**
64
+ * Records an attempt and reports whether it is allowed.
65
+ *
66
+ * Call once per login attempt, before checking the password.
67
+ *
68
+ * @param {import('express').Request} req
69
+ * @param {number} [now] Injectable clock, for tests
70
+ * @param {string} [bucket] Which budget to count against ('login' | 'setup')
71
+ * @returns {{ allowed: boolean, remaining: number, retryAfterSeconds: number }}
72
+ */
73
+ export function recordAttempt(req, now = Date.now(), bucket = 'login') {
74
+ prune(now);
75
+
76
+ const key = clientKey(req, bucket);
77
+ const existing = attempts.get(key);
78
+
79
+ if (!existing || now >= existing.resetAt) {
80
+ attempts.set(key, { count: 1, resetAt: now + WINDOW_MS });
81
+ return { allowed: true, remaining: MAX_ATTEMPTS - 1, retryAfterSeconds: 0 };
82
+ }
83
+
84
+ existing.count += 1;
85
+
86
+ if (existing.count > MAX_ATTEMPTS) {
87
+ return {
88
+ allowed: false,
89
+ remaining: 0,
90
+ retryAfterSeconds: Math.max(1, Math.ceil((existing.resetAt - now) / 1000)),
91
+ };
92
+ }
93
+
94
+ return {
95
+ allowed: true,
96
+ remaining: MAX_ATTEMPTS - existing.count,
97
+ retryAfterSeconds: 0,
98
+ };
99
+ }
100
+
101
+ /**
102
+ * Clears the counter for a client.
103
+ *
104
+ * Called after a successful login, so that someone who mistyped a few times
105
+ * and then got in is not left near the limit.
106
+ *
107
+ * @param {import('express').Request} req
108
+ * @param {string} [bucket]
109
+ */
110
+ export function clearAttempts(req, bucket = 'login') {
111
+ attempts.delete(clientKey(req, bucket));
112
+ }
113
+
114
+ /** Drops every counter. For tests and for a clean shutdown. */
115
+ export function resetAll() {
116
+ attempts.clear();
117
+ }
118
+
119
+ export const LOGIN_RATE_LIMIT = Object.freeze({ MAX_ATTEMPTS, WINDOW_MS });
@@ -0,0 +1,80 @@
1
+ /**
2
+ * dashboard/lib/requireAuth.js
3
+ *
4
+ * The dashboard's single authentication gate, for HTTP and for Socket.io.
5
+ *
6
+ * Every API router mounts `requireAuth`, and every Socket.io connection goes
7
+ * through `socketRequireAuth`. The only public endpoints are the ones needed
8
+ * to get a session in the first place: the session check, login, logout and
9
+ * the first-run setup.
10
+ *
11
+ * This matters more than it used to. The dashboard can now run 24/7 as a
12
+ * background service, so an unprotected endpoint is not "exposed while I have
13
+ * a terminal open" — it is exposed permanently, on every boot.
14
+ *
15
+ * Socket.io is covered because it is not a lesser surface: the dashboard's
16
+ * socket streams nginx status, domain health and live log tails, and those
17
+ * are exactly the things the HTTP routes are being protected for.
18
+ *
19
+ * ── dashboardAuth: 'none' ──────────────────────────────────────────────────
20
+ *
21
+ * A single-user machine may legitimately run without a password. That is an
22
+ * explicit setting, not an empty password, and it is honoured ONLY while the
23
+ * dashboard is bound to loopback — effectiveAuthMode() in core/config.js
24
+ * decides, and falls back to requiring a password if the two ever disagree.
25
+ *
26
+ * Skipping the password does NOT skip lib/localRequest.js. Those checks defend
27
+ * against other websites in the same browser, which a password never did, and
28
+ * they are the reason "no password on loopback" is a defensible option rather
29
+ * than an open door.
30
+ */
31
+
32
+ import { loadConfig, AUTH_MODES, effectiveAuthMode } from '../../core/config.js';
33
+
34
+ /** Whether a password is required right now. */
35
+ function passwordRequired() {
36
+ try {
37
+ return effectiveAuthMode(loadConfig()) !== AUTH_MODES.NONE;
38
+ } catch {
39
+ // An unreadable config must not become an open dashboard.
40
+ return true;
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Express middleware: refuses anything without a logged-in session.
46
+ *
47
+ * Returns 401 with a JSON body, matching what the already-protected routers
48
+ * returned, so the frontend has one shape to handle.
49
+ *
50
+ * The public endpoints are not listed here. routes/auth.js is simply not
51
+ * mounted behind this middleware, which keeps the rule "everything except
52
+ * that one router" visible at the mount points rather than hidden in a path
53
+ * allowlist that could drift.
54
+ */
55
+ export function requireAuth(req, res, next) {
56
+ if (!passwordRequired()) return next();
57
+ if (req.session?.authenticated === true) return next();
58
+ return res.status(401).json({ error: 'Unauthorized' });
59
+ }
60
+
61
+ /**
62
+ * Socket.io middleware: refuses a connection without a logged-in session.
63
+ *
64
+ * The session is attached to `socket.request` by running the express-session
65
+ * middleware on the engine — see initSocket() in socketManager.js. Without
66
+ * that, `socket.request.session` is undefined and every connection is
67
+ * correctly refused rather than silently allowed.
68
+ *
69
+ * @param {import('socket.io').Socket} socket
70
+ * @param {(err?: Error) => void} next
71
+ */
72
+ export function socketRequireAuth(socket, next) {
73
+ if (!passwordRequired()) return next();
74
+ if (socket.request?.session?.authenticated === true) return next();
75
+
76
+ const err = new Error('UNAUTHORIZED');
77
+ // socket.io passes `data` through to the client's connect_error handler.
78
+ err.data = { reason: 'unauthorized' };
79
+ return next(err);
80
+ }