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,260 @@
1
+ /**
2
+ * core/service/winsw.js
3
+ *
4
+ * WinSW — the service wrapper that lets a plain console program run as a real
5
+ * Windows Service.
6
+ *
7
+ * Windows has no equivalent of systemd's "just run this command": a service
8
+ * executable must implement the Service Control Manager protocol, which a Node
9
+ * process cannot. WinSW is a small wrapper that implements it and runs our
10
+ * command as a child, giving automatic start, restart-on-failure with backoff,
11
+ * and rolling logs for free.
12
+ *
13
+ * ── Which build, and why ───────────────────────────────────────────────────
14
+ *
15
+ * `WinSW-x64.exe` from v2.12.0: the self-contained .NET build. It is 18MB
16
+ * rather than the 850KB `WinSW.NET4.exe`, and that is the point — the small
17
+ * build needs a matching .NET Framework already present, and "install the
18
+ * service" failing on a fresh Windows Server because of a missing runtime is a
19
+ * far worse outcome than a one-time 18MB download. v2.12.0 is the newest
20
+ * non-prerelease; the v3 line is still alpha.
21
+ *
22
+ * ── The hash ───────────────────────────────────────────────────────────────
23
+ *
24
+ * Pinned below, computed from the actual file downloaded from the release URL.
25
+ * Install REFUSES on a mismatch and does not fall back to running it anyway:
26
+ * this binary is about to be registered as a service running with elevated
27
+ * privileges, so an unexpected byte is a reason to stop, not a warning.
28
+ */
29
+
30
+ import fs from 'fs';
31
+ import path from 'path';
32
+ import { createHash } from 'crypto';
33
+ import { pipeline } from 'stream/promises';
34
+
35
+ import { isDefaultDataDir } from '../platform.js';
36
+
37
+ /** The pinned release. Changing any of these three means re-computing the hash. */
38
+ export const WINSW_VERSION = 'v2.12.0';
39
+ export const WINSW_ASSET = 'WinSW-x64.exe';
40
+ export const WINSW_URL = `https://github.com/winsw/winsw/releases/download/${WINSW_VERSION}/${WINSW_ASSET}`;
41
+
42
+ /**
43
+ * SHA-256 of the pinned asset.
44
+ *
45
+ * Measured, not copied from anywhere: the file was downloaded from WINSW_URL
46
+ * and hashed. Verified alongside the size below, and that it is a real PE
47
+ * image (MZ header, PE signature).
48
+ */
49
+ export const WINSW_SHA256 = '05b82d46ad331cc16bdc00de5c6332c1ef818df8ceefcd49c726553209b3a0da';
50
+
51
+ /** Expected size in bytes, as the release metadata reports it. */
52
+ export const WINSW_BYTES = 18_243_033;
53
+
54
+ /** Service identity. The display name is what appears in services.msc. */
55
+ export const SERVICE_ID = 'EasyDevOps';
56
+ export const SERVICE_DISPLAY_NAME = 'Easy DevOps';
57
+ export const SERVICE_DESCRIPTION =
58
+ 'Monitors nginx, domains and certificates, sends notifications, and runs the Easy DevOps Hub agent.';
59
+
60
+ /**
61
+ * The virtual service account.
62
+ *
63
+ * `NT SERVICE\<name>` is created by Windows for a service of that name and has
64
+ * NO PASSWORD — nobody has to type one, and there is none to leak or rotate.
65
+ * This is the whole reason the old Task Scheduler approach was removed: that
66
+ * one needed the user's own password to create an at-boot task.
67
+ */
68
+ export const SERVICE_ACCOUNT = `NT SERVICE\\${SERVICE_ID}`;
69
+
70
+ /** SHA-256 of a file, streamed so an 18MB binary is not held in memory twice. */
71
+ export async function hashFile(file) {
72
+ const hash = createHash('sha256');
73
+ await pipeline(fs.createReadStream(file), hash);
74
+ return hash.digest('hex');
75
+ }
76
+
77
+ /**
78
+ * Checks a downloaded WinSW against the pin.
79
+ *
80
+ * @param {string} file
81
+ * @returns {Promise<{ ok: boolean, reason?: string, sha256?: string, bytes?: number }>}
82
+ */
83
+ export async function verifyWinsw(file) {
84
+ let bytes;
85
+ try {
86
+ bytes = fs.statSync(file).size;
87
+ } catch (err) {
88
+ return { ok: false, reason: `cannot read ${file}: ${err.message}` };
89
+ }
90
+
91
+ // Size first: it is free, and a truncated download is the common failure.
92
+ if (bytes !== WINSW_BYTES) {
93
+ return {
94
+ ok: false,
95
+ bytes,
96
+ reason: `size mismatch: expected ${WINSW_BYTES} bytes, got ${bytes}. `
97
+ + 'The download is incomplete or the release asset has changed.',
98
+ };
99
+ }
100
+
101
+ const sha256 = await hashFile(file);
102
+ if (sha256 !== WINSW_SHA256) {
103
+ return {
104
+ ok: false,
105
+ bytes,
106
+ sha256,
107
+ reason: `SHA-256 mismatch for ${WINSW_ASSET} ${WINSW_VERSION}.\n`
108
+ + ` expected: ${WINSW_SHA256}\n`
109
+ + ` actual : ${sha256}\n`
110
+ + 'Refusing to install it as a service. Delete the file and try again; '
111
+ + 'if it keeps failing, do not work around it — the binary is not the one this release pins.',
112
+ };
113
+ }
114
+
115
+ return { ok: true, sha256, bytes };
116
+ }
117
+
118
+ /**
119
+ * Downloads WinSW to `dest` and verifies it. Never leaves a failed download in
120
+ * place under the final name, so a later run cannot pick up a bad file.
121
+ *
122
+ * @param {Object} opts
123
+ * @param {string} opts.dest
124
+ * @param {(line: string) => void} [opts.log]
125
+ * @param {typeof fetch} [opts.fetchImpl] Injectable, for tests
126
+ * @returns {Promise<{ ok: boolean, path?: string, reason?: string, sha256?: string }>}
127
+ */
128
+ export async function downloadWinsw({ dest, log = () => {}, fetchImpl = fetch } = {}) {
129
+ // Already there and correct: do not download 18MB again.
130
+ if (fs.existsSync(dest)) {
131
+ const existing = await verifyWinsw(dest);
132
+ if (existing.ok) {
133
+ log(`${WINSW_ASSET} ${WINSW_VERSION} already present and verified.`);
134
+ return { ok: true, path: dest, sha256: existing.sha256 };
135
+ }
136
+ log(`An existing ${path.basename(dest)} did not verify (${existing.reason.split('\n')[0]}); re-downloading.`);
137
+ }
138
+
139
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
140
+
141
+ // Downloaded to a temporary name and renamed only after verification, so an
142
+ // interrupted download can never be mistaken for a good one.
143
+ const temp = `${dest}.download`;
144
+
145
+ log(`Downloading ${WINSW_ASSET} ${WINSW_VERSION} (${(WINSW_BYTES / 1e6).toFixed(1)} MB)…`);
146
+
147
+ try {
148
+ const response = await fetchImpl(WINSW_URL, { redirect: 'follow' });
149
+ if (!response.ok) {
150
+ return { ok: false, reason: `download failed: HTTP ${response.status} from ${WINSW_URL}` };
151
+ }
152
+
153
+ const bytes = Buffer.from(await response.arrayBuffer());
154
+ fs.writeFileSync(temp, bytes);
155
+ } catch (err) {
156
+ try { fs.rmSync(temp, { force: true }); } catch { /* nothing to clean */ }
157
+ return { ok: false, reason: `download failed: ${err.message}` };
158
+ }
159
+
160
+ const verified = await verifyWinsw(temp);
161
+ if (!verified.ok) {
162
+ try { fs.rmSync(temp, { force: true }); } catch { /* nothing to clean */ }
163
+ return { ok: false, reason: verified.reason };
164
+ }
165
+
166
+ try {
167
+ fs.rmSync(dest, { force: true });
168
+ fs.renameSync(temp, dest);
169
+ } catch (err) {
170
+ return { ok: false, reason: `could not put the verified file in place: ${err.message}` };
171
+ }
172
+
173
+ log(`Verified SHA-256 ${verified.sha256}`);
174
+ return { ok: true, path: dest, sha256: verified.sha256 };
175
+ }
176
+
177
+ /**
178
+ * The WinSW XML that defines the service.
179
+ *
180
+ * Choices worth knowing:
181
+ *
182
+ * - `<serviceaccount><username>` is the virtual account, with
183
+ * `allowservicelogon` so Windows grants it the "log on as a service" right.
184
+ * No password element exists, and none is needed.
185
+ * - `onfailure` restarts with a growing delay rather than immediately: a
186
+ * daemon that crashes on a bad config would otherwise spin, and the Service
187
+ * Control Manager would give up and mark it failed within a minute.
188
+ * - `log mode="roll-by-size"` keeps the log bounded. A service that runs for
189
+ * months with an unbounded log is a disk-full incident waiting to happen.
190
+ * - `stoptimeout` gives the daemon time to release the lock and close the
191
+ * database cleanly before it is killed.
192
+ *
193
+ * @param {Object} opts
194
+ * @param {string} opts.nodeExe Absolute path to the pinned node.exe
195
+ * @param {string} opts.entry Absolute path to the ez entry script
196
+ * @param {string} opts.dataDir Passed through the environment
197
+ * @param {string} opts.logDir
198
+ * @param {string} [opts.workingDir]
199
+ * @returns {string}
200
+ */
201
+ export function buildServiceXml({ nodeExe, entry, dataDir, logDir, workingDir = null }) {
202
+ const escape = (value) => String(value)
203
+ .replace(/&/g, '&amp;')
204
+ .replace(/</g, '&lt;')
205
+ .replace(/>/g, '&gt;')
206
+ .replace(/"/g, '&quot;');
207
+
208
+ // Only passed when it is NOT the default. In Server mode it normally IS
209
+ // needed — ProgramData is only the default once the marker exists, and the
210
+ // service must not depend on reading that marker first. But a service
211
+ // installed against the per-user default would otherwise be handed a
212
+ // variable it does not need, and that variable used to mean "dev mode":
213
+ // staging certificates on real domains. See isDevDataDir() in platform.js.
214
+ const dataDirEnv = isDefaultDataDir(dataDir)
215
+ ? ' <!-- EASY_DEVOPS_DATA_DIR is not set: this is the default directory. -->'
216
+ : ` <env name="EASY_DEVOPS_DATA_DIR" value="${escape(dataDir)}"/>`;
217
+
218
+ return `<service>
219
+ <id>${SERVICE_ID}</id>
220
+ <name>${escape(SERVICE_DISPLAY_NAME)}</name>
221
+ <description>${escape(SERVICE_DESCRIPTION)}</description>
222
+
223
+ <executable>${escape(nodeExe)}</executable>
224
+ <arguments>${escape(entry)} daemon</arguments>
225
+ <workingdirectory>${escape(workingDir ?? path.dirname(entry))}</workingdirectory>
226
+
227
+ <!-- Starts at boot, before anyone logs in. -->
228
+ <startmode>Automatic</startmode>
229
+
230
+ <!-- nginx is the thing being monitored, so start after it when it exists.
231
+ A missing dependency is tolerated: Windows nginx is often not a service
232
+ at all, and refusing to start without it would be wrong. -->
233
+ <depend>Tcpip</depend>
234
+
235
+ <!-- The virtual account: no password anywhere, ever. -->
236
+ <serviceaccount>
237
+ <username>${SERVICE_ACCOUNT}</username>
238
+ <allowservicelogon>true</allowservicelogon>
239
+ </serviceaccount>
240
+
241
+ <!-- Backoff, not a tight loop: 5s, 20s, then every minute. -->
242
+ <onfailure action="restart" delay="5 sec"/>
243
+ <onfailure action="restart" delay="20 sec"/>
244
+ <onfailure action="restart" delay="60 sec"/>
245
+ <resetfailure>1 hour</resetfailure>
246
+
247
+ <stoptimeout>15 sec</stoptimeout>
248
+
249
+ <log mode="roll-by-size">
250
+ <logpath>${escape(logDir)}</logpath>
251
+ <sizeThreshold>10240</sizeThreshold>
252
+ <keepFiles>8</keepFiles>
253
+ </log>
254
+
255
+ ${dataDirEnv}
256
+ <!-- Node writes diagnostics to stderr; keep them in the rolling log. -->
257
+ <env name="NODE_ENV" value="production"/>
258
+ </service>
259
+ `;
260
+ }
@@ -0,0 +1,331 @@
1
+ /**
2
+ * core/setupCode.js
3
+ *
4
+ * The one-time code that protects first-run setup from being taken over.
5
+ *
6
+ * ── The hole this closes ───────────────────────────────────────────────────
7
+ *
8
+ * `POST /api/setup` has to be public: it is how the first password gets set,
9
+ * and there is no session to require before that password exists. So on a
10
+ * freshly started dashboard with no password, whoever reaches that endpoint
11
+ * first owns the installation. The transport checks (Host/Origin/X-EZ-Request)
12
+ * stop a hostile *page* in the user's browser, and they are a real defence,
13
+ * but they do nothing against a direct request from anything that can reach
14
+ * the port — which, on a server deliberately bound to 0.0.0.0, is the network.
15
+ *
16
+ * The code is proof that the person setting the password can read the server's
17
+ * terminal or its service log. That is the property we actually want: setup is
18
+ * for whoever runs the machine.
19
+ *
20
+ * ── Why six digits are enough here ─────────────────────────────────────────
21
+ *
22
+ * Six digits is 10^6, which a script could exhaust in minutes if it were
23
+ * allowed to try. It is not:
24
+ *
25
+ * - per-IP rate limiting, in its own budget (so setup guesses cannot
26
+ * exhaust the login budget, or the reverse), and
27
+ * - a GLOBAL cap of 20 failed attempts across every address, after which the
28
+ * code is invalidated and only the machine's own terminal can issue
29
+ * another, and
30
+ * - a 24-hour expiry, so an abandoned pending setup does not leave a
31
+ * guessable code outstanding for ever.
32
+ *
33
+ * The global cap is the one that matters: a per-IP limit alone is bypassable
34
+ * from many addresses, and it is the part that bounds the whole attack to 20
35
+ * guesses rather than 20 per attacker.
36
+ *
37
+ * ── It never leaves the machine ────────────────────────────────────────────
38
+ *
39
+ * The code is printed to the local terminal and written to the local service
40
+ * log, and nowhere else. It is NOT in `GET /api/auth`, not in any other API
41
+ * response, not in a Socket.io event, and not in anything the Hub agent sends.
42
+ * A client may learn *whether* a code is required; never what it is.
43
+ *
44
+ * That is why only the HASH is stored, in the same scrypt form as the
45
+ * dashboard password (core/passwords.js) and compared the same way: a code
46
+ * readable from the database would be readable by anything that can read the
47
+ * database, including the Hub telemetry paths that legitimately read config.
48
+ * The cleartext exists in this process only long enough to be printed.
49
+ */
50
+
51
+ import { randomInt } from 'node:crypto';
52
+
53
+ import { dbGet, dbSet } from './db.js';
54
+ import { hashPassword, verifyPassword } from './passwords.js';
55
+ import { AUTH_MODES, effectiveAuthMode } from './config.js';
56
+
57
+ /** DB key holding the outstanding code's hash and its counters. */
58
+ const KEY = 'setup-code';
59
+
60
+ /** Six digits: readable off a terminal, typable on a phone. */
61
+ const DIGITS = 6;
62
+
63
+ /** How long an outstanding code stays valid. */
64
+ export const CODE_TTL_MS = 24 * 60 * 60 * 1000;
65
+
66
+ /**
67
+ * Failed attempts across ALL addresses before the code is burned.
68
+ *
69
+ * Twenty rather than a round hundred because a person typing a code they can
70
+ * see gets it right in one or two tries; twenty is already generous for a
71
+ * human and negligible against 10^6 for a script.
72
+ */
73
+ export const MAX_GLOBAL_FAILURES = 20;
74
+
75
+ /** The stored record, or null. */
76
+ function read() {
77
+ const value = dbGet(KEY);
78
+ if (!value || typeof value !== 'object' || typeof value.hash !== 'string') return null;
79
+ return value;
80
+ }
81
+
82
+ /**
83
+ * Whether a stored record is still usable.
84
+ *
85
+ * Expiry and the failure cap are checked here rather than at write time
86
+ * because nothing runs on a schedule to sweep them: the record goes stale on
87
+ * its own, and every reader has to agree on when.
88
+ */
89
+ function usable(record, now = Date.now()) {
90
+ if (!record) return { ok: false, reason: 'none' };
91
+ if (record.burned) return { ok: false, reason: 'burned' };
92
+ if (Number(record.failures ?? 0) >= MAX_GLOBAL_FAILURES) return { ok: false, reason: 'burned' };
93
+ if (Number(record.expiresAt ?? 0) <= now) return { ok: false, reason: 'expired' };
94
+ return { ok: true, reason: 'ok' };
95
+ }
96
+
97
+ /** `418902` → `418 902`. Printed form only; input is accepted either way. */
98
+ export function format(code) {
99
+ const digits = String(code).replace(/\D/g, '');
100
+ if (digits.length !== DIGITS) return String(code);
101
+ return `${digits.slice(0, 3)} ${digits.slice(3)}`;
102
+ }
103
+
104
+ /** Strips everything that is not a digit, so `418 902` and `418-902` both work. */
105
+ export function normalize(input) {
106
+ return String(input ?? '').replace(/\D/g, '');
107
+ }
108
+
109
+ /**
110
+ * True when first-run setup still has to happen.
111
+ *
112
+ * `none` mode is already configured — there is nothing to take over — and a
113
+ * stored password means setup is done.
114
+ *
115
+ * @param {Object} config
116
+ * @returns {boolean}
117
+ */
118
+ export function setupPending(config) {
119
+ if (effectiveAuthMode(config) === AUTH_MODES.NONE) return false;
120
+ const stored = config.dashboardPasswordHash || config.dashboardPassword || '';
121
+ return String(stored) === '';
122
+ }
123
+
124
+ /**
125
+ * Whether a client must supply a code with a password setup right now.
126
+ *
127
+ * False when setup is already done, and false when no code is outstanding —
128
+ * a dashboard started before this feature existed, or one whose code was
129
+ * cleared, must not become impossible to set up. The code is *created* by
130
+ * ensureCode() at startup, so in practice one is always outstanding; this stays
131
+ * tolerant of the case where it is not rather than locking the user out.
132
+ *
133
+ * @param {Object} [opts]
134
+ * @returns {boolean}
135
+ */
136
+ export function required() {
137
+ const record = read();
138
+ if (!record) return false;
139
+ // An expired or burned code still REQUIRES a code: the answer to "can I set
140
+ // up without one" must not become yes by waiting or by guessing twenty
141
+ // times. It requires a NEW one, which is what the message says.
142
+ return true;
143
+ }
144
+
145
+ /**
146
+ * What a client may be told: whether a code is needed and when it stops being
147
+ * valid. Never the code itself.
148
+ *
149
+ * @param {Object} [opts]
150
+ * @returns {{ required: boolean, expiresAt: number|null, state: string }}
151
+ */
152
+ export function publicState({ now = Date.now() } = {}) {
153
+ const record = read();
154
+ if (!record) return { required: false, expiresAt: null, state: 'none' };
155
+ const state = usable(record, now);
156
+ return {
157
+ required: true,
158
+ // Null once it is no longer valid: a timestamp in the past would read as
159
+ // "expires soon" in a UI that only compares it to the clock.
160
+ expiresAt: state.ok ? Number(record.expiresAt) : null,
161
+ state: state.reason,
162
+ };
163
+ }
164
+
165
+ /**
166
+ * Issues a new code, replacing any outstanding one.
167
+ *
168
+ * Returns the cleartext ONCE, to the caller that is about to print it. It is
169
+ * never readable again from anywhere.
170
+ *
171
+ * @param {Object} [opts]
172
+ * @returns {Promise<{ code: string, expiresAt: number }>}
173
+ */
174
+ export async function issue({ now = Date.now() } = {}) {
175
+ // randomInt, not Math.random: this is a credential.
176
+ const code = String(randomInt(0, 10 ** DIGITS)).padStart(DIGITS, '0');
177
+ const expiresAt = now + CODE_TTL_MS;
178
+
179
+ dbSet(KEY, {
180
+ hash: await hashPassword(code),
181
+ issuedAt: now,
182
+ expiresAt,
183
+ failures: 0,
184
+ burned: false,
185
+ });
186
+
187
+ return { code, expiresAt };
188
+ }
189
+
190
+ /**
191
+ * Makes sure a code exists while setup is pending, and returns the cleartext
192
+ * only when a NEW one had to be created.
193
+ *
194
+ * Called at dashboard startup and at daemon startup. Both run against the same
195
+ * database, so whichever starts first creates the code and the other reports
196
+ * that one is outstanding without being able to print it — which is correct:
197
+ * re-printing would require storing the cleartext.
198
+ *
199
+ * @param {Object} opts
200
+ * @param {Object} opts.config
201
+ * @returns {Promise<{ pending: boolean, code: string|null, expiresAt: number|null, state: string }>}
202
+ */
203
+ export async function ensureCode({ config, now = Date.now() } = {}) {
204
+ if (!setupPending(config)) {
205
+ // Nothing to protect. An outstanding code from before a password was set
206
+ // is removed rather than left to expire.
207
+ clear();
208
+ return { pending: false, code: null, expiresAt: null, state: 'not-needed' };
209
+ }
210
+
211
+ const existing = read();
212
+ const state = usable(existing, now);
213
+
214
+ if (state.ok) {
215
+ return { pending: true, code: null, expiresAt: Number(existing.expiresAt), state: 'outstanding' };
216
+ }
217
+
218
+ // Expired or burned: a fresh one, so a pending setup stays completable.
219
+ const issued = await issue({ now });
220
+ return {
221
+ pending: true,
222
+ code: issued.code,
223
+ expiresAt: issued.expiresAt,
224
+ state: existing ? `reissued-${state.reason}` : 'issued',
225
+ };
226
+ }
227
+
228
+ /**
229
+ * Checks a submitted code and counts the attempt.
230
+ *
231
+ * @param {string} input
232
+ * @param {Object} [opts]
233
+ * @returns {Promise<{ ok: boolean, reason: string, failures: number, burned: boolean }>}
234
+ */
235
+ export async function verify(input, { now = Date.now() } = {}) {
236
+ const record = read();
237
+ const state = usable(record, now);
238
+
239
+ if (!state.ok) {
240
+ return {
241
+ ok: false,
242
+ reason: state.reason,
243
+ failures: Number(record?.failures ?? 0),
244
+ burned: state.reason === 'burned',
245
+ };
246
+ }
247
+
248
+ const digits = normalize(input);
249
+ if (digits.length !== DIGITS) {
250
+ // Counted: a malformed guess is still a guess.
251
+ return countFailure(record, 'invalid');
252
+ }
253
+
254
+ const matches = await verifyPassword(digits, record.hash);
255
+ if (!matches) return countFailure(record, 'invalid');
256
+
257
+ return { ok: true, reason: 'ok', failures: Number(record.failures ?? 0), burned: false };
258
+ }
259
+
260
+ /** Records one failure, burning the code at the cap. */
261
+ function countFailure(record, reason) {
262
+ const failures = Number(record.failures ?? 0) + 1;
263
+ const burned = failures >= MAX_GLOBAL_FAILURES;
264
+
265
+ dbSet(KEY, { ...record, failures, burned });
266
+
267
+ return { ok: false, reason: burned ? 'burned' : reason, failures, burned };
268
+ }
269
+
270
+ /** Removes the outstanding code. Called once a password is set. */
271
+ export function clear() {
272
+ if (read() === null) return false;
273
+ dbSet(KEY, null);
274
+ return true;
275
+ }
276
+
277
+ /**
278
+ * `YYYY-MM-DD HH:mm` in local time.
279
+ *
280
+ * Not the locale formatter: ICU emits a narrow no-break space before AM/PM in
281
+ * recent Node versions, and these lines go to a Windows console in the legacy
282
+ * OEM code page and to a WinSW-captured log file, where anything above ASCII
283
+ * arrives as mojibake. Local time rather than ISO/UTC because the person
284
+ * reading it is standing at the machine.
285
+ */
286
+ function localStamp(ms) {
287
+ const d = new Date(ms);
288
+ const p = (n) => String(n).padStart(2, '0');
289
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} `
290
+ + `${p(d.getHours())}:${p(d.getMinutes())}`;
291
+ }
292
+
293
+ /**
294
+ * The block printed to a terminal or a service log.
295
+ *
296
+ * ASCII only: this reaches a Windows console in the legacy OEM code page and a
297
+ * WinSW-captured log file, where an em dash or an ellipsis arrives as mojibake.
298
+ *
299
+ * @param {Object} opts
300
+ * @param {string|null} opts.code Cleartext, when this process issued it
301
+ * @param {number|null} opts.expiresAt
302
+ * @param {string} [opts.state]
303
+ * @returns {string[]} Lines, so the caller chooses how to write them
304
+ */
305
+ export function describe({ code = null, expiresAt = null, state = 'issued' } = {}) {
306
+ const lines = [];
307
+ lines.push('');
308
+ lines.push(' First-run setup code');
309
+ lines.push(' ' + '-'.repeat(48));
310
+
311
+ if (code) {
312
+ lines.push(` ${format(code)}`);
313
+ lines.push('');
314
+ lines.push(' Enter it on the dashboard\'s first-run screen together with');
315
+ lines.push(' the password you want to set. It is required because that');
316
+ lines.push(' screen is reachable by anything that can reach this port.');
317
+ if (expiresAt) lines.push(` Valid until ${localStamp(expiresAt)} (24 hours).`);
318
+ } else if (state === 'outstanding') {
319
+ lines.push(' A setup code is already outstanding.');
320
+ lines.push(' It was printed when the first process started. To see a new one:');
321
+ lines.push(' ezz dashboard setup-code');
322
+ if (expiresAt) lines.push(` The current one is valid until ${localStamp(expiresAt)}.`);
323
+ } else {
324
+ lines.push(' The setup code is no longer valid.');
325
+ lines.push(' Issue a new one on this machine:');
326
+ lines.push(' ezz dashboard setup-code');
327
+ }
328
+
329
+ lines.push('');
330
+ return lines;
331
+ }