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
@@ -0,0 +1,1128 @@
1
+ /**
2
+ * core/service/index.js
3
+ *
4
+ * One interface over three genuinely different native service mechanisms:
5
+ *
6
+ * | platform / mode | mechanism | elevation | starts |
7
+ * |--------------------|-------------------------------|-----------|----------|
8
+ * | Linux | systemd unit | sudo once | at boot |
9
+ * | Windows "Server" | Windows Service via WinSW | UAC once | at boot |
10
+ * | Windows "Personal" | Startup-folder supervisor | none | at logon |
11
+ *
12
+ * **No password is ever requested, stored or passed through this code.** On
13
+ * Linux sudo does its own asking, on the user's terminal. On Windows the
14
+ * service runs as the virtual account `NT SERVICE\EasyDevOps`, which has no
15
+ * password at all. The previous design needed the user's password for a
16
+ * scheduled task; that mode is gone, and core/service/legacy.js exists to find
17
+ * and remove what it left behind.
18
+ *
19
+ * PM2 is no longer involved in running Easy DevOps itself. `core/runner.js`
20
+ * and the Processes page remain, for the user's OWN applications — that is a
21
+ * supported feature and is untouched.
22
+ *
23
+ * ── What this module does and does not decide ──────────────────────────────
24
+ *
25
+ * It decides which mechanism applies and sequences the steps. It does not
26
+ * prompt: every question — Server or Personal, remove the legacy setup, move
27
+ * the data back on uninstall — is asked by the CLI, which has a terminal, and
28
+ * passed in as a plain option. That keeps this module callable from a test
29
+ * with no TTY, and keeps the dashboard unable to trigger anything interactive.
30
+ */
31
+
32
+ import fs from 'fs';
33
+ import path from 'path';
34
+ import { fileURLToPath } from 'url';
35
+
36
+ import {
37
+ isWindows,
38
+ getDataDir,
39
+ isServerMode,
40
+ programDataDir,
41
+ windowsEditionQueryCmd,
42
+ windowsProductNameCmd,
43
+ } from '../platform.js';
44
+ import { run as shellRun } from '../shell.js';
45
+ import { loadConfig } from '../config.js';
46
+ import { dbGet, dbSet } from '../db.js';
47
+ import { inspect as inspectLock, HEARTBEAT_INTERVAL_MS } from '../daemon/lock.js';
48
+ import { requestStop, clearStopRequest, isStopRequested } from '../daemon/stopRequest.js';
49
+ import { inspect as inspectOwner } from '../jobs/owner.js';
50
+ import { probe, invalidate } from '../probeCache.js';
51
+
52
+ import * as systemd from './systemd.js';
53
+ import * as windowsService from './windowsService.js';
54
+ import * as windowsPersonal from './windowsPersonal.js';
55
+ import * as legacy from './legacy.js';
56
+ import { enableServerMode, disableServerMode } from './dataDir.js';
57
+ import { linkRuntime, inspectRuntime, runtimeNodePath } from './runtime.js';
58
+
59
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
60
+
61
+ /** Where install details are recorded. Shared with the old module's key. */
62
+ const STATE_KEY = 'service-state';
63
+
64
+ /** The two Windows modes. */
65
+ export const MODES = Object.freeze({ SERVER: 'server', PERSONAL: 'personal' });
66
+
67
+ /** How long to wait for the daemon's heartbeat after starting a service. */
68
+ export const STARTUP_GRACE_MS = 10_000;
69
+
70
+ /** How long to wait for a stopping daemon to actually release its lock. */
71
+ export const STOP_GRACE_MS = 15_000;
72
+
73
+ /**
74
+ * The `ezz` entry script, resolved from this file rather than from `cwd`.
75
+ *
76
+ * A service unit records this path, so it has to be the installed package's
77
+ * real location — `process.argv[1]` would be whatever shim the user invoked,
78
+ * which on Windows is a `.cmd` wrapper that a service cannot run directly.
79
+ */
80
+ export function entryScript() {
81
+ return path.resolve(__dirname, '..', '..', 'cli', 'index.js');
82
+ }
83
+
84
+ /** The package root, used as a working directory and as the copy source. */
85
+ export function appRoot() {
86
+ return path.resolve(__dirname, '..', '..', '..');
87
+ }
88
+
89
+ /**
90
+ * Which mechanism applies here.
91
+ *
92
+ * @param {Object} [opts]
93
+ * @param {string} [opts.mode] Windows only; defaults to the recorded or detected mode
94
+ * @returns {{ platform: 'linux'|'windows', mode: string|null, mechanism: string }}
95
+ */
96
+ export function resolveMechanism({ mode = null } = {}) {
97
+ if (!isWindows) {
98
+ return { platform: 'linux', mode: null, mechanism: 'systemd' };
99
+ }
100
+
101
+ const recorded = dbGet(STATE_KEY)?.mode ?? null;
102
+ // Server mode is also inferable from the marker, which survives a database
103
+ // that was moved or rebuilt — so it wins over a stale record.
104
+ const effective = mode ?? (isServerMode() ? MODES.SERVER : recorded);
105
+
106
+ return {
107
+ platform: 'windows',
108
+ mode: effective,
109
+ mechanism: effective === MODES.SERVER ? 'winsw' : 'startup-supervisor',
110
+ };
111
+ }
112
+
113
+ /**
114
+ * The default Windows mode for this machine.
115
+ *
116
+ * Server on a Windows Server edition, because that machine exists to serve and
117
+ * nobody is logged in; ask otherwise. The caller does the asking — this only
118
+ * supplies the default.
119
+ *
120
+ * @returns {Promise<{ mode: string, isServerEdition: boolean, detail: string }>}
121
+ */
122
+ export async function suggestWindowsMode({ run = shellRun } = {}) {
123
+ if (!isWindows) return { mode: null, isServerEdition: false, detail: 'not Windows' };
124
+
125
+ let isServerEdition = false;
126
+ let detail = 'could not determine the Windows edition';
127
+
128
+ try {
129
+ const type = await run(windowsEditionQueryCmd(), { timeout: 15_000 });
130
+ const value = (type.stdout ?? '').trim();
131
+
132
+ if (type.success && value) {
133
+ // `Server` and `Server Core` both mean a machine that exists to serve.
134
+ isServerEdition = /^server/i.test(value);
135
+
136
+ const named = await run(windowsProductNameCmd(), { timeout: 15_000 });
137
+ const product = (named.stdout ?? '').trim();
138
+ detail = product || value;
139
+ }
140
+ } catch {
141
+ // Unreadable registry: fall through to Personal, which needs no elevation
142
+ // and therefore cannot be the wrong answer in a damaging way. Choosing
143
+ // Server by default on an unknown machine would ask for UAC it may not get.
144
+ }
145
+
146
+ return {
147
+ mode: isServerEdition ? MODES.SERVER : MODES.PERSONAL,
148
+ isServerEdition,
149
+ detail,
150
+ };
151
+ }
152
+
153
+ /**
154
+ * Waits for the daemon to prove it is alive, by its heartbeat.
155
+ *
156
+ * "The service manager says it started" is not the same as "the daemon is
157
+ * running": WinSW and systemd both report success as soon as the process is
158
+ * spawned, and a daemon that throws on startup is reported as started and then
159
+ * restarted for ever. The lock's heartbeat is the only evidence that the
160
+ * daemon actually reached a working state.
161
+ *
162
+ * @param {Object} opts
163
+ * @param {string} opts.dataDir
164
+ * @param {number} [opts.timeoutMs]
165
+ * @returns {Promise<{ alive: boolean, waitedMs: number, lock: Object|null }>}
166
+ */
167
+ export async function waitForDaemon({ dataDir, timeoutMs = STARTUP_GRACE_MS } = {}) {
168
+ const started = Date.now();
169
+ const deadline = started + timeoutMs;
170
+
171
+ while (Date.now() < deadline) {
172
+ const state = inspectLock({ dataDir });
173
+ if (state.running) {
174
+ return { alive: true, waitedMs: Date.now() - started, lock: state.lock };
175
+ }
176
+ await new Promise((r) => setTimeout(r, Math.min(500, HEARTBEAT_INTERVAL_MS)));
177
+ }
178
+
179
+ return { alive: false, waitedMs: Date.now() - started, lock: inspectLock({ dataDir }).lock };
180
+ }
181
+
182
+ /**
183
+ * Waits for a running daemon to go away.
184
+ *
185
+ * The mirror of waitForDaemon(): a `stop` that reported success while the
186
+ * daemon was still up would be worse than one that took a moment longer.
187
+ *
188
+ * @param {Object} opts
189
+ * @returns {Promise<{ gone: boolean, waitedMs: number }>}
190
+ */
191
+ export async function waitForDaemonGone({ dataDir, timeoutMs = STOP_GRACE_MS } = {}) {
192
+ const started = Date.now();
193
+ const deadline = started + timeoutMs;
194
+
195
+ while (Date.now() < deadline) {
196
+ if (!inspectLock({ dataDir }).running) {
197
+ return { gone: true, waitedMs: Date.now() - started };
198
+ }
199
+ await new Promise((r) => setTimeout(r, 300));
200
+ }
201
+
202
+ return { gone: false, waitedMs: Date.now() - started };
203
+ }
204
+
205
+ /**
206
+ * The background-service state, cheaply and synchronously.
207
+ *
208
+ * This is the object the UI treats as the single authority, and it is
209
+ * deliberately separate from `status()`: that one queries the service manager
210
+ * (`sc query`, `systemctl show`), probes Node runtimes and reads PM2, which is
211
+ * far too expensive to run on every lock change. Everything here is a lock
212
+ * read, a `existsSync` and a database read.
213
+ *
214
+ * `installed` cannot be derived from `running` — a daemon started by hand runs
215
+ * without being installed, and a stopped service is installed without running.
216
+ * Both are reported.
217
+ *
218
+ * @param {Object} [opts]
219
+ * @returns {Object}
220
+ */
221
+ export function backgroundServiceState({ dataDir = getDataDir() } = {}) {
222
+ const mech = resolveMechanism();
223
+ const lock = inspectLock({ dataDir });
224
+ const owner = inspectOwner({ dataDir });
225
+ const recorded = dbGet(STATE_KEY) ?? {};
226
+
227
+ const stoppedRequested = isStopRequested({ dataDir });
228
+ const stoppedByUser = (Boolean(recorded.stoppedAt) || stoppedRequested) && !lock.running;
229
+
230
+ return {
231
+ running: lock.running,
232
+ pid: lock.lock?.pid ?? null,
233
+ version: lock.lock?.version ?? null,
234
+ startedAt: lock.lock?.startedAt ?? null,
235
+ heartbeatAgeMs: lock.age,
236
+
237
+ // Which process is doing the work. Exactly one holds the marker.
238
+ jobsRunningHere: owner.held && owner.mine,
239
+ jobsOwnerPid: owner.owner?.pid ?? null,
240
+ jobsOwnerRole: owner.owner?.role ?? null,
241
+
242
+ mechanism: mech.mechanism,
243
+ mode: mech.mode,
244
+ installed: isInstalled({ mech, dataDir }),
245
+ startsAt: startsAtFor(mech),
246
+
247
+ stoppedByUser,
248
+ stoppedAt: recorded.stoppedAt ?? null,
249
+
250
+ dataDir,
251
+ serverMode: isServerMode(),
252
+ detail: lock.reason,
253
+ };
254
+ }
255
+
256
+ /**
257
+ * Whether a native service is installed, by the only cheap evidence there is:
258
+ * the artifact each mechanism leaves behind.
259
+ */
260
+ function isInstalled({ mech = resolveMechanism(), dataDir = getDataDir() } = {}) {
261
+ try {
262
+ if (!isWindows) return fs.existsSync(systemd.UNIT_PATH);
263
+ if (mech.mode === MODES.SERVER) {
264
+ return fs.existsSync(windowsService.winswPath()) && fs.existsSync(windowsService.serviceXmlPath());
265
+ }
266
+ const launcher = windowsPersonal.launcherPath();
267
+ return Boolean(launcher && fs.existsSync(launcher));
268
+ } catch {
269
+ return false;
270
+ }
271
+ }
272
+
273
+ /** When the service starts itself: at logon (Personal) or at boot. */
274
+ function startsAtFor(mech = resolveMechanism()) {
275
+ if (!isWindows) return 'boot';
276
+ return mech.mode === MODES.SERVER ? 'boot' : 'logon';
277
+ }
278
+
279
+ /** Records that the user stopped it, so `status` can say so. */
280
+ function recordStopped() {
281
+ const existing = dbGet(STATE_KEY) ?? {};
282
+ dbSet(STATE_KEY, { ...existing, stoppedAt: new Date().toISOString() });
283
+ }
284
+
285
+ /** Clears that record. */
286
+ function recordStarted() {
287
+ const existing = dbGet(STATE_KEY) ?? {};
288
+ if (existing.stoppedAt) dbSet(STATE_KEY, { ...existing, stoppedAt: null });
289
+ }
290
+
291
+ /**
292
+ * Installs the native service.
293
+ *
294
+ * @param {Object} opts
295
+ * @param {string} [opts.mode] Windows: 'server' | 'personal'
296
+ * @param {boolean} [opts.removeLegacy] Remove the old PM2 setup (the CLI asks)
297
+ * @param {(line: string) => void} [opts.log]
298
+ * @param {Object} [opts.deps] Injected for tests
299
+ * @returns {Promise<Object>}
300
+ */
301
+ export async function install({ mode = null, removeLegacy = false, log = () => {}, deps = {} } = {}) {
302
+ // What the probes measure is about to change.
303
+ invalidateProbes();
304
+ // A stop request left over from a previous install would make the daemon
305
+ // exit the moment it started. Install is an explicit "I want this running".
306
+ (deps.clearStopRequest ?? clearStopRequest)({ dataDir: getDataDir() });
307
+ recordStarted();
308
+
309
+ const found = await legacy.detectLegacy(deps.legacy ?? {});
310
+ const legacyResult = { found: found.items, removed: [], failed: [] };
311
+
312
+ if (found.found && removeLegacy) {
313
+ log('Removing the old PM2-based service…');
314
+ const cleaned = await legacy.removeLegacy({ items: found.items, log, ...(deps.legacy ?? {}) });
315
+ legacyResult.removed = cleaned.removed;
316
+ legacyResult.failed = cleaned.failed;
317
+ }
318
+
319
+ const entry = entryScript();
320
+ const root = appRoot();
321
+
322
+ if (!isWindows) {
323
+ return installLinux({ entry, log, legacyResult, deps });
324
+ }
325
+
326
+ const resolved = mode ?? (await suggestWindowsMode()).mode;
327
+
328
+ return resolved === MODES.SERVER
329
+ ? installWindowsServer({ entry, root, log, legacyResult, deps })
330
+ : installWindowsPersonal({ entry, log, legacyResult, deps });
331
+ }
332
+
333
+ /** Linux: pin the runtime, write the unit, start it, verify the heartbeat. */
334
+ async function installLinux({ entry, log, legacyResult, deps = {} }) {
335
+ const dataDir = getDataDir();
336
+ const sd = deps.systemd ?? systemd;
337
+
338
+ if (!(await sd.hasSystemd(deps.systemdOpts ?? {}))) {
339
+ return {
340
+ ok: false,
341
+ mechanism: 'none',
342
+ manual: sd.manualInstructions({ nodeExe: process.execPath, entry, dataDir }),
343
+ reason: 'this machine does not use systemd',
344
+ legacy: legacyResult,
345
+ };
346
+ }
347
+
348
+ log('Pinning the Node runtime…');
349
+ const linked = linkRuntime({ dataDir });
350
+ if (!linked.ok) return { ok: false, mechanism: 'systemd', reason: linked.reason, legacy: legacyResult };
351
+ log(` ${linked.link} → ${linked.target}`);
352
+
353
+ const installed = await sd.install({
354
+ nodeExe: linked.link,
355
+ entry,
356
+ dataDir,
357
+ log,
358
+ ...(deps.systemdOpts ?? {}),
359
+ });
360
+ if (!installed.ok) {
361
+ return { ok: false, mechanism: 'systemd', reason: installed.reason, legacy: legacyResult };
362
+ }
363
+
364
+ const alive = await waitForDaemon({ dataDir, timeoutMs: deps.startupGraceMs ?? STARTUP_GRACE_MS });
365
+ if (!alive.alive) {
366
+ const recent = await sd.journal({ lines: 25, ...(deps.systemdOpts ?? {}) });
367
+ return {
368
+ ok: false,
369
+ mechanism: 'systemd',
370
+ reason: `the unit was installed and started, but the daemon did not report in within `
371
+ + `${Math.round(alive.waitedMs / 1000)}s — so it is starting and failing.\n\n`
372
+ + `Last log lines:\n${recent.output}`,
373
+ installedButNotRunning: true,
374
+ legacy: legacyResult,
375
+ };
376
+ }
377
+
378
+ record({ mode: null, mechanism: 'systemd', nodeExe: linked.target, runtimeLink: linked.link, entry, dataDir });
379
+
380
+ return {
381
+ ok: true,
382
+ mechanism: 'systemd',
383
+ dataDir,
384
+ unitPath: installed.unitPath,
385
+ runtime: { link: linked.link, target: linked.target },
386
+ daemon: { pid: alive.lock?.pid ?? null, waitedMs: alive.waitedMs },
387
+ legacy: legacyResult,
388
+ };
389
+ }
390
+
391
+ /** Windows Server: move the data, copy the runtime, register the service. */
392
+ async function installWindowsServer({ entry, root, log, legacyResult, deps = {} }) {
393
+ const ws = deps.windowsService ?? windowsService;
394
+
395
+ // The data directory moves FIRST: everything after this — the ACL grants,
396
+ // the service XML's EASY_DEVOPS_DATA_DIR — has to refer to the final
397
+ // location, and a half-installed service pointing at the old one would see
398
+ // an empty database.
399
+ log('Switching to the machine-wide data directory…');
400
+ const switched = (deps.enableServerMode ?? enableServerMode)({ log });
401
+ if (!switched.ok) {
402
+ return { ok: false, mechanism: 'winsw', mode: MODES.SERVER, reason: switched.reason, legacy: legacyResult };
403
+ }
404
+
405
+ const dataDir = switched.dataDir;
406
+ if (switched.migrated) log(` migrated; backup at ${switched.backup}`);
407
+
408
+ const config = loadConfig();
409
+
410
+ const installed = await ws.install({
411
+ dataDir,
412
+ appRoot: root,
413
+ config,
414
+ log,
415
+ ...(deps.windowsServiceOpts ?? {}),
416
+ });
417
+ if (!installed.ok) {
418
+ return {
419
+ ok: false,
420
+ mechanism: 'winsw',
421
+ mode: MODES.SERVER,
422
+ reason: installed.reason,
423
+ needsElevation: installed.needsElevation ?? false,
424
+ dataDir,
425
+ legacy: legacyResult,
426
+ };
427
+ }
428
+
429
+ const alive = await waitForDaemon({ dataDir, timeoutMs: deps.startupGraceMs ?? STARTUP_GRACE_MS });
430
+ if (!alive.alive) {
431
+ const logs = ws.readLogs({ lines: 25, which: 'err' });
432
+ return {
433
+ ok: false,
434
+ mechanism: 'winsw',
435
+ mode: MODES.SERVER,
436
+ reason: `the service was registered and started, but the daemon did not report in within `
437
+ + `${Math.round(alive.waitedMs / 1000)}s — so it is starting and failing.\n\n`
438
+ + `Last log lines (${logs.file}):\n${logs.output}`,
439
+ installedButNotRunning: true,
440
+ dataDir,
441
+ legacy: legacyResult,
442
+ };
443
+ }
444
+
445
+ record({
446
+ mode: MODES.SERVER,
447
+ mechanism: 'winsw',
448
+ nodeExe: installed.runtime?.nodeExe ?? null,
449
+ entry: installed.runtime?.entry ?? entry,
450
+ dataDir,
451
+ granted: installed.granted ?? [],
452
+ });
453
+
454
+ return {
455
+ ok: true,
456
+ mechanism: 'winsw',
457
+ mode: MODES.SERVER,
458
+ dataDir,
459
+ migrated: switched.migrated,
460
+ backup: switched.backup,
461
+ granted: installed.granted,
462
+ aclFailures: installed.aclFailures,
463
+ runtime: installed.runtime,
464
+ daemon: { pid: alive.lock?.pid ?? null, waitedMs: alive.waitedMs },
465
+ legacy: legacyResult,
466
+ };
467
+ }
468
+
469
+ /** Windows Personal: a Startup-folder supervisor. No elevation, no data move. */
470
+ async function installWindowsPersonal({ entry, log, legacyResult, deps = {} }) {
471
+ const dataDir = getDataDir();
472
+ const wp = deps.windowsPersonal ?? windowsPersonal;
473
+
474
+ const installed = wp.install({ dataDir, entry, log, ...(deps.windowsPersonalOpts ?? {}) });
475
+ if (!installed.ok) {
476
+ return { ok: false, mechanism: 'startup-supervisor', mode: MODES.PERSONAL, reason: installed.reason, legacy: legacyResult };
477
+ }
478
+
479
+ record({
480
+ mode: MODES.PERSONAL,
481
+ mechanism: 'startup-supervisor',
482
+ nodeExe: installed.nodeExe,
483
+ entry,
484
+ dataDir,
485
+ launcher: installed.launcher,
486
+ });
487
+
488
+ // Not started here, and not waited for: Personal mode starts at LOGON. The
489
+ // user is logged in right now, so the honest thing is to say it will start
490
+ // next time they sign in — and to offer `ezz daemon` meanwhile — rather than
491
+ // to launch a detached process whose lifetime nothing manages.
492
+ return {
493
+ ok: true,
494
+ mechanism: 'startup-supervisor',
495
+ mode: MODES.PERSONAL,
496
+ dataDir,
497
+ launcher: installed.launcher,
498
+ logFile: installed.logFile,
499
+ startsAt: 'logon',
500
+ legacy: legacyResult,
501
+ };
502
+ }
503
+
504
+ /**
505
+ * Removes the native service.
506
+ *
507
+ * `keepServerDataLocation` implements decision 5: uninstalling in Server mode
508
+ * must NEVER silently move the data back to `%APPDATA%`. The default is to
509
+ * keep using ProgramData; moving back is an explicit choice, and then it is a
510
+ * real verified move with a backup.
511
+ *
512
+ * @param {Object} opts
513
+ * @param {boolean} [opts.keepServerDataLocation] Default true
514
+ * @param {boolean} [opts.removeLegacy]
515
+ * @param {(line: string) => void} [opts.log]
516
+ * @returns {Promise<Object>}
517
+ */
518
+ export async function uninstall({
519
+ keepServerDataLocation = true,
520
+ removeLegacy = false,
521
+ log = () => {},
522
+ deps = {},
523
+ } = {}) {
524
+ // What the probes measure is about to change.
525
+ invalidateProbes();
526
+ const mech = resolveMechanism();
527
+ const result = { mechanism: mech.mechanism, mode: mech.mode, notes: [], dataDir: getDataDir() };
528
+
529
+ if (!isWindows) {
530
+ const removed = await (deps.systemd ?? systemd).uninstall({ log, ...(deps.systemdOpts ?? {}) });
531
+ if (!removed.ok) return { ok: false, ...result, reason: removed.reason };
532
+ } else if (mech.mode === MODES.SERVER) {
533
+ const config = loadConfig();
534
+ const removed = await (deps.windowsService ?? windowsService).uninstall({
535
+ dataDir: getDataDir(),
536
+ config,
537
+ log,
538
+ ...(deps.windowsServiceOpts ?? {}),
539
+ });
540
+ if (!removed.ok) {
541
+ return { ok: false, ...result, reason: removed.reason, needsElevation: removed.needsElevation ?? false };
542
+ }
543
+ result.notes.push(...(removed.notes ?? []));
544
+
545
+ if (keepServerDataLocation) {
546
+ result.notes.push(
547
+ `The data stays at ${programDataDir()}. The Server-mode marker is kept, so the CLI and `
548
+ + 'the dashboard keep reading it. Run `ezz service uninstall` again and choose to move it '
549
+ + 'back if you change your mind.',
550
+ );
551
+ result.dataDir = programDataDir();
552
+ } else {
553
+ log('Moving the data back to %APPDATA%…');
554
+ const moved = (deps.disableServerMode ?? disableServerMode)({ log });
555
+ if (!moved.ok) return { ok: false, ...result, reason: moved.reason };
556
+ result.dataDir = moved.dataDir;
557
+ result.movedData = moved.moved;
558
+ result.backup = moved.backup;
559
+ if (moved.backup) result.notes.push(`A backup was kept at ${moved.backup}`);
560
+ }
561
+ } else {
562
+ const removed = (deps.windowsPersonal ?? windowsPersonal).uninstall({ log, ...(deps.windowsPersonalOpts ?? {}) });
563
+ if (!removed.ok) return { ok: false, ...result, reason: removed.reason };
564
+ result.notes.push(...(removed.notes ?? []));
565
+ }
566
+
567
+ // Legacy cleanup is offered on uninstall too: a user removing our service
568
+ // almost certainly does not want the old PM2 boot hook left behind.
569
+ const found = await legacy.detectLegacy(deps.legacy ?? {});
570
+ result.legacy = { found: found.items, removed: [], failed: [] };
571
+ if (found.found && removeLegacy) {
572
+ const cleaned = await legacy.removeLegacy({ items: found.items, log, ...(deps.legacy ?? {}) });
573
+ result.legacy.removed = cleaned.removed;
574
+ result.legacy.failed = cleaned.failed;
575
+ }
576
+
577
+ const existing = dbGet(STATE_KEY) ?? {};
578
+ dbSet(STATE_KEY, { ...existing, mode: null, mechanism: null, uninstalledAt: new Date().toISOString() });
579
+
580
+ return { ok: true, ...result };
581
+ }
582
+
583
+ /**
584
+ * Stops the daemon, temporarily.
585
+ *
586
+ * "Temporarily" is the whole distinction from uninstall: the service stays
587
+ * installed and comes back at the next boot or logon. `ezz service start`
588
+ * brings it back now.
589
+ *
590
+ * Personal mode has no service manager to ask, so it goes through the stop
591
+ * request file that the daemon and its supervisor both watch — see
592
+ * core/daemon/stopRequest.js for why that is a file and not an IPC command.
593
+ *
594
+ * @param {Object} [opts]
595
+ * @param {(line: string) => void} [opts.log]
596
+ * @returns {Promise<Object>}
597
+ */
598
+ export async function stop({ log = () => {}, deps = {} } = {}) {
599
+ // What the probes measure is about to change.
600
+ invalidateProbes();
601
+ const mech = resolveMechanism();
602
+ const dataDir = getDataDir();
603
+ const before = inspectLock({ dataDir });
604
+
605
+ let result;
606
+
607
+ if (!isWindows) {
608
+ result = await (deps.systemd ?? systemd).stop({ log, ...(deps.systemdOpts ?? {}) });
609
+ } else if (mech.mode === MODES.SERVER) {
610
+ result = await (deps.windowsService ?? windowsService).stop(deps.windowsServiceOpts ?? {});
611
+ } else {
612
+ // Personal mode. The request has to be written even when no daemon is
613
+ // running right now: the supervisor may be mid-backoff and about to start
614
+ // one, and the file is what stops that.
615
+ const requested = (deps.requestStop ?? requestStop)({ dataDir, reason: 'ezz service stop' });
616
+ if (!requested.ok) {
617
+ return { ok: false, mechanism: mech.mechanism, mode: mech.mode, reason: requested.reason };
618
+ }
619
+ log(`Wrote the stop request: ${requested.path}`);
620
+
621
+ if (!before.running) {
622
+ recordStopped();
623
+ return {
624
+ ok: true,
625
+ mechanism: mech.mechanism,
626
+ mode: mech.mode,
627
+ alreadyStopped: true,
628
+ detail: 'No daemon was running. The request is in place, so the supervisor will not start one '
629
+ + 'until the next logon or `ezz service start`.',
630
+ };
631
+ }
632
+
633
+ // Wait for the daemon to actually go, so the command does not report
634
+ // success while it is still running.
635
+ const gone = await waitForDaemonGone({ dataDir, timeoutMs: deps.stopGraceMs ?? STOP_GRACE_MS });
636
+ if (!gone.gone) {
637
+ return {
638
+ ok: false,
639
+ mechanism: mech.mechanism,
640
+ mode: mech.mode,
641
+ reason: `the stop request was written but the daemon (pid ${before.lock?.pid}) was still running after `
642
+ + `${Math.round(gone.waitedMs / 1000)}s. Check the supervisor log: ezz service logs`,
643
+ };
644
+ }
645
+
646
+ recordStopped();
647
+ return { ok: true, mechanism: mech.mechanism, mode: mech.mode, waitedMs: gone.waitedMs };
648
+ }
649
+
650
+ if (!result.ok) {
651
+ return {
652
+ ok: false,
653
+ mechanism: mech.mechanism,
654
+ mode: mech.mode,
655
+ reason: result.reason,
656
+ needsElevation: result.needsElevation ?? false,
657
+ };
658
+ }
659
+
660
+ const gone = await waitForDaemonGone({ dataDir, timeoutMs: deps.stopGraceMs ?? STOP_GRACE_MS });
661
+ recordStopped();
662
+
663
+ return {
664
+ ok: true,
665
+ mechanism: mech.mechanism,
666
+ mode: mech.mode,
667
+ alreadyStopped: result.alreadyStopped ?? false,
668
+ waitedMs: gone.waitedMs,
669
+ ...(gone.gone ? {} : { detail: 'The service manager accepted the stop; the daemon lock has not cleared yet.' }),
670
+ };
671
+ }
672
+
673
+ /**
674
+ * Starts the daemon again after a stop.
675
+ *
676
+ * @param {Object} [opts]
677
+ * @returns {Promise<Object>}
678
+ */
679
+ export async function start({ log = () => {}, deps = {} } = {}) {
680
+ // What the probes measure is about to change.
681
+ invalidateProbes();
682
+ const mech = resolveMechanism();
683
+ const dataDir = getDataDir();
684
+
685
+ // Refuse rather than start a second one. The daemon lock would refuse it
686
+ // anyway, but saying so here is a clearer answer than a service that starts
687
+ // and immediately exits.
688
+ const existing = inspectLock({ dataDir });
689
+ if (existing.running) {
690
+ return {
691
+ ok: false,
692
+ mechanism: mech.mechanism,
693
+ mode: mech.mode,
694
+ alreadyRunning: true,
695
+ reason: `a daemon is already running (pid ${existing.lock?.pid}). `
696
+ + 'Use `ezz service restart` to replace it.',
697
+ };
698
+ }
699
+
700
+ // Clearing the request is what makes a stop temporary. Done for every mode:
701
+ // a stale request from a Personal-mode stop must not silently kill a daemon
702
+ // started later by any route.
703
+ (deps.clearStopRequest ?? clearStopRequest)({ dataDir });
704
+ recordStarted();
705
+
706
+ let result;
707
+
708
+ if (!isWindows) {
709
+ result = await (deps.systemd ?? systemd).start({ log, ...(deps.systemdOpts ?? {}) });
710
+ } else if (mech.mode === MODES.SERVER) {
711
+ result = await (deps.windowsService ?? windowsService).start(deps.windowsServiceOpts ?? {});
712
+ } else {
713
+ result = await (deps.windowsPersonal ?? windowsPersonal).startNow({
714
+ dataDir,
715
+ log,
716
+ ...(deps.windowsPersonalOpts ?? {}),
717
+ });
718
+ }
719
+
720
+ if (!result.ok) {
721
+ return {
722
+ ok: false,
723
+ mechanism: mech.mechanism,
724
+ mode: mech.mode,
725
+ reason: result.reason,
726
+ needsElevation: result.needsElevation ?? false,
727
+ };
728
+ }
729
+
730
+ const alive = await waitForDaemon({ dataDir, timeoutMs: deps.startupGraceMs ?? STARTUP_GRACE_MS });
731
+ if (!alive.alive) {
732
+ return {
733
+ ok: false,
734
+ mechanism: mech.mechanism,
735
+ mode: mech.mode,
736
+ reason: `it was started but the daemon did not report in within `
737
+ + `${Math.round(alive.waitedMs / 1000)}s. Check the logs: ezz service logs`,
738
+ };
739
+ }
740
+
741
+ return {
742
+ ok: true,
743
+ mechanism: mech.mechanism,
744
+ mode: mech.mode,
745
+ pid: alive.lock?.pid ?? null,
746
+ waitedMs: alive.waitedMs,
747
+ };
748
+ }
749
+
750
+ /**
751
+ * Restarts the service, in every mode.
752
+ *
753
+ * Personal mode has no service manager, so it is a stop followed by a start —
754
+ * which is exactly what the two commands already do correctly, including
755
+ * clearing the stop request so the restart is not immediately undone by it.
756
+ * It used to refuse outright and tell the user to find the process themselves.
757
+ */
758
+ export async function restart({ log = () => {}, deps = {} } = {}) {
759
+ // What the probes measure is about to change.
760
+ invalidateProbes();
761
+ const mech = resolveMechanism();
762
+ const dataDir = getDataDir();
763
+
764
+ if (isWindows && mech.mode !== MODES.SERVER) {
765
+ const stopped = await stop({ log, deps });
766
+ if (!stopped.ok) {
767
+ return { ok: false, reason: `could not stop it first: ${stopped.reason}`, needsElevation: stopped.needsElevation };
768
+ }
769
+
770
+ const started = await start({ log, deps });
771
+ return started.ok
772
+ ? { ok: true, pid: started.pid, waitedMs: started.waitedMs, viaStopStart: true }
773
+ : { ok: false, reason: started.reason };
774
+ }
775
+
776
+ if (!isWindows) {
777
+ const result = await (deps.systemd ?? systemd).restart(deps.systemdOpts ?? {});
778
+ if (!result.ok) return { ok: false, reason: result.reason };
779
+ } else {
780
+ const result = await (deps.windowsService ?? windowsService).restart(deps.windowsServiceOpts ?? {});
781
+ if (!result.ok) return { ok: false, reason: result.reason };
782
+ }
783
+
784
+ // A restart also ends a deliberate stop: the service is running again, so
785
+ // `status` must stop saying the user stopped it.
786
+ (deps.clearStopRequest ?? clearStopRequest)({ dataDir });
787
+ recordStarted();
788
+
789
+ const alive = await waitForDaemon({ dataDir, timeoutMs: deps.startupGraceMs ?? STARTUP_GRACE_MS });
790
+ return alive.alive
791
+ ? { ok: true, pid: alive.lock?.pid ?? null, waitedMs: alive.waitedMs }
792
+ : {
793
+ ok: false,
794
+ reason: `the restart was accepted but the daemon did not report in within `
795
+ + `${Math.round(alive.waitedMs / 1000)}s. Check the logs: ezz service logs`,
796
+ };
797
+ }
798
+
799
+ /**
800
+ * Cache keys for the probes in `status()`.
801
+ *
802
+ * Named rather than inline so `invalidateProbes()` and the tests refer to the
803
+ * same strings, and prefixed so one call drops them all.
804
+ */
805
+ export const PROBE_KEYS = Object.freeze({
806
+ manager: 'service:manager',
807
+ runtime: 'service:runtime',
808
+ legacy: 'service:legacy',
809
+ });
810
+
811
+ /**
812
+ * How long each probe stays fresh.
813
+ *
814
+ * Different numbers because the questions change at different rates, and the
815
+ * cost of a stale answer differs too:
816
+ *
817
+ * - the service MANAGER's view changes when the user starts or stops
818
+ * something, so it has the shortest life - though every one of those
819
+ * commands also calls invalidateProbes(), which is what actually keeps it
820
+ * correct. The TTL is the backstop for a change made outside this process,
821
+ * such as `sc stop` or systemctl by hand.
822
+ * - the RUNTIME changes on a repair or a runtime update, both of which
823
+ * invalidate.
824
+ * - LEGACY leftovers change only when install or uninstall removes them, and
825
+ * it is the most expensive probe of the three (PM2 detection, a PM2 app
826
+ * list and a schtasks query), so it gets the longest life.
827
+ */
828
+ export const PROBE_TTL_MS = Object.freeze({
829
+ [PROBE_KEYS.manager]: 10_000,
830
+ [PROBE_KEYS.runtime]: 60_000,
831
+ [PROBE_KEYS.legacy]: 300_000,
832
+ });
833
+
834
+ /** Drops every cached probe. See the note in core/probeCache.js. */
835
+ export function invalidateProbes() {
836
+ return invalidate('service:');
837
+ }
838
+
839
+ /**
840
+ * Everything `ezz service status` and `GET /api/service` need to say.
841
+ *
842
+ * ── Fast and correct at the same time ──────────────────────────────────────
843
+ *
844
+ * The cheap facts - the daemon lock, its heartbeat age, whether a stop was
845
+ * requested, what install recorded - are read FRESH on every call. They cost
846
+ * microseconds and they are the ones that change on their own.
847
+ *
848
+ * The expensive facts each cost a subprocess, and on Windows a subprocess
849
+ * costs about a second. Those three are:
850
+ *
851
+ * the service manager's view `sc query` / `systemctl is-active` / a file
852
+ * the pinned runtime `<node> --version`
853
+ * legacy PM2 leftovers PM2 detection, `pm2 jlist`, `schtasks`
854
+ *
855
+ * They run in PARALLEL rather than one after another, and with `cache: true`
856
+ * they come from core/probeCache.js, which answers immediately and refreshes
857
+ * behind the request. Measured on the machine that reported this: about 20 s
858
+ * sequential and uncached, about 2 s cold and parallel, single-digit
859
+ * milliseconds warm.
860
+ *
861
+ * `cache: false` is the default, so the CLI keeps getting a freshly measured
862
+ * answer - someone who has just typed `ezz service status` is asking BECAUSE
863
+ * something changed. The dashboard passes `cache: true`.
864
+ *
865
+ * @param {Object} [opts]
866
+ * @param {boolean} [opts.cache] Serve cached probes, refresh behind
867
+ * @param {number} [opts.coldWaitMs] Max wait when a probe has never run
868
+ * @returns {Promise<Object>}
869
+ */
870
+ export async function status({ cache = false, coldWaitMs, deps = {} } = {}) {
871
+ const mech = resolveMechanism();
872
+ const dataDir = getDataDir();
873
+ const config = loadConfig();
874
+ const recorded = dbGet(STATE_KEY) ?? {};
875
+
876
+ // The daemon's own view, which is the authority on whether work is happening.
877
+ const lock = inspectLock({ dataDir });
878
+
879
+ const out = {
880
+ platform: mech.platform,
881
+ mode: mech.mode,
882
+ mechanism: mech.mechanism,
883
+ dataDir,
884
+ serverMode: isServerMode(),
885
+ dashboardUi: config.dashboardUi ?? null,
886
+ daemon: {
887
+ running: lock.running,
888
+ pid: lock.lock?.pid ?? null,
889
+ version: lock.lock?.version ?? null,
890
+ startedAt: lock.lock?.startedAt ?? null,
891
+ heartbeatAgeMs: lock.age,
892
+ detail: lock.reason,
893
+ },
894
+ warnings: [],
895
+ };
896
+
897
+ // ── The three expensive probes, together ─────────────────────────────────
898
+ const managerProbe = () => {
899
+ if (!isWindows) return (deps.systemd ?? systemd).status(deps.systemdOpts ?? {});
900
+ if (mech.mode === MODES.SERVER) {
901
+ return (deps.windowsService ?? windowsService).status({
902
+ dataDir,
903
+ config,
904
+ granted: recorded.granted ?? [],
905
+ ...(deps.windowsServiceOpts ?? {}),
906
+ });
907
+ }
908
+ // Personal mode reads files only, so it is already cheap; it goes through
909
+ // the same path for one shape rather than for speed.
910
+ return (deps.windowsPersonal ?? windowsPersonal).status(deps.windowsPersonalOpts ?? {});
911
+ };
912
+
913
+ const runtimeProbe = () => (deps.inspectRuntime ?? inspectRuntime)({
914
+ dataDir,
915
+ recordedNodeExe: recorded.nodeExe ?? null,
916
+ });
917
+
918
+ const legacyProbe = () => (deps.detectLegacy ?? legacy.detectLegacy)(deps.legacy ?? {});
919
+
920
+ const read = async (key, producer) => {
921
+ if (!cache) return { value: await producer(), ageMs: 0, fresh: true, pending: false, refreshing: false };
922
+ return probe(key, producer, {
923
+ ttlMs: PROBE_TTL_MS[key],
924
+ ...(coldWaitMs === undefined ? {} : { coldWaitMs }),
925
+ });
926
+ };
927
+
928
+ const [manager, runtimeRead, legacyRead] = await Promise.all([
929
+ read(PROBE_KEYS.manager, managerProbe),
930
+ read(PROBE_KEYS.runtime, runtimeProbe),
931
+ read(PROBE_KEYS.legacy, legacyProbe),
932
+ ]);
933
+
934
+ // A pending probe must not become a crash or a lie. The shape stays the
935
+ // same and `probes` below says which parts are not measured yet, so a client
936
+ // can render the rest and ask again.
937
+ out.service = manager.value ?? { installed: null, running: null, state: null, pending: true, warnings: [] };
938
+ out.runtime = runtimeRead.value ?? null;
939
+ out.legacy = legacyRead.value?.items ?? [];
940
+
941
+ if (isWindows && mech.mode === MODES.SERVER && out.service.acl && !out.service.acl.ok) {
942
+ out.warnings.push(out.service.acl.reason);
943
+ }
944
+ if (isWindows && mech.mode !== MODES.SERVER) {
945
+ out.warnings.push(...(out.service.warnings ?? []));
946
+ }
947
+ out.warnings.push(...(out.runtime?.warnings ?? []));
948
+
949
+ // What the caller needs to know about the measurement itself: how old it is,
950
+ // and whether anything is still being measured.
951
+ out.probes = {
952
+ cached: Boolean(cache),
953
+ ageMs: Math.max(manager.ageMs ?? 0, runtimeRead.ageMs ?? 0, legacyRead.ageMs ?? 0),
954
+ fresh: manager.fresh && runtimeRead.fresh && legacyRead.fresh,
955
+ pending: manager.pending || runtimeRead.pending || legacyRead.pending,
956
+ refreshing: manager.refreshing || runtimeRead.refreshing || legacyRead.refreshing,
957
+ };
958
+
959
+ if (out.service.crashLooping) {
960
+ out.warnings.push(
961
+ `The service is in a crash loop: ${out.service.restarts} restart(s) recorded. `
962
+ + 'It starts and dies rather than staying up. `ezz service logs` shows why.',
963
+ );
964
+ }
965
+
966
+ // Installed but the daemon is not reporting in: the most useful single thing
967
+ // status can tell a user, and the one a service-manager-only check misses.
968
+ if (out.service.installed && out.service.running && !lock.running) {
969
+ out.warnings.push(
970
+ 'The service is running but no daemon has reported in. Either it is still starting, '
971
+ + 'or it is failing immediately — `ezz service logs` will say which.',
972
+ );
973
+ }
974
+
975
+ // "Stopped by you" and "not running" look identical to a service manager, and
976
+ // telling a user their service crashed when they stopped it themselves is
977
+ // both wrong and alarming. The distinction comes from two recorded facts: an
978
+ // explicit stop writes `stoppedAt`, and Personal mode also leaves a stop
979
+ // request file that is the actual reason nothing restarts.
980
+ const stoppedOnPurpose = Boolean(recorded.stoppedAt)
981
+ || (deps.isStopRequested ?? isStopRequested)({ dataDir });
982
+
983
+ out.stoppedByUser = stoppedOnPurpose && !lock.running;
984
+ out.stoppedAt = recorded.stoppedAt ?? null;
985
+
986
+ if (out.stoppedByUser) {
987
+ out.daemon.detail = recorded.stoppedAt
988
+ ? `stopped by you at ${recorded.stoppedAt}`
989
+ : 'stopped by you';
990
+ // Anything on Windows that is not Server mode starts at LOGON, including
991
+ // the case where no mode is recorded yet — Personal is the Windows default.
992
+ const comesBack = isWindows && mech.mode !== MODES.SERVER
993
+ ? 'at your next logon'
994
+ : 'at the next boot';
995
+
996
+ out.warnings.push(
997
+ `The background service is stopped. This is temporary — it starts again ${comesBack}, `
998
+ + 'or now with: ezz service start',
999
+ );
1000
+ } else if (out.service.installed && !out.service.running && mech.mode !== MODES.PERSONAL) {
1001
+ out.warnings.push('The service is installed but not running. Start it with: ezz service start');
1002
+ } else if (out.service.installed && mech.mode === MODES.PERSONAL && !lock.running) {
1003
+ out.warnings.push(
1004
+ 'The launcher is installed but no daemon is running. It starts at logon — '
1005
+ + 'or now with: ezz service start',
1006
+ );
1007
+ }
1008
+
1009
+ if (out.legacy.length > 0) {
1010
+ out.warnings.push(
1011
+ `${out.legacy.length} leftover(s) from the old PM2-based service are still set up. `
1012
+ + 'Run `ezz service install` or `ezz service uninstall` to be offered their removal.',
1013
+ );
1014
+ }
1015
+
1016
+ return out;
1017
+ }
1018
+
1019
+ /**
1020
+ * Fills the probe cache without anyone waiting for it.
1021
+ *
1022
+ * Called once when the dashboard starts, so the first page load finds the
1023
+ * answers already there instead of paying for six subprocesses while someone
1024
+ * is watching a spinner.
1025
+ *
1026
+ * @param {Object} [opts]
1027
+ * @returns {Promise<void>}
1028
+ */
1029
+ export async function warmProbes({ deps = {} } = {}) {
1030
+ try {
1031
+ await status({ cache: true, coldWaitMs: 60_000, deps });
1032
+ } catch (err) {
1033
+ // A warm-up that fails changes nothing: the next real request probes
1034
+ // again. It must never stop the dashboard from starting.
1035
+ process.stderr?.write?.(`[service] could not warm the status probes: ${err.message}\n`);
1036
+ }
1037
+ }
1038
+
1039
+ /** Recent service logs. */
1040
+ export async function logs({ lines = 50, which = 'out', deps = {} } = {}) {
1041
+ const mech = resolveMechanism();
1042
+
1043
+ if (!isWindows) {
1044
+ const result = await (deps.systemd ?? systemd).journal({ lines, ...(deps.systemdOpts ?? {}) });
1045
+ return { ok: result.ok, source: `journalctl -u ${systemd.UNIT_NAME}`, output: result.output };
1046
+ }
1047
+
1048
+ if (mech.mode === MODES.SERVER) {
1049
+ const result = (deps.windowsService ?? windowsService).readLogs({ lines, which });
1050
+ return { ok: result.ok, source: result.file, output: result.output };
1051
+ }
1052
+
1053
+ const result = (deps.windowsPersonal ?? windowsPersonal).readLogs({ dataDir: getDataDir(), lines });
1054
+ return { ok: result.ok, source: result.file, output: result.output };
1055
+ }
1056
+
1057
+ /**
1058
+ * Fixes what drifts: a broken runtime pin, stale ACLs, an outdated launcher.
1059
+ *
1060
+ * This is the command every "it stopped working after I upgraded Node" message
1061
+ * points at, which is why `status` names it in its warnings.
1062
+ */
1063
+ export async function repair({ log = () => {}, deps = {} } = {}) {
1064
+ // What the probes measure is about to change.
1065
+ invalidateProbes();
1066
+ const mech = resolveMechanism();
1067
+ const dataDir = getDataDir();
1068
+
1069
+ if (!isWindows) {
1070
+ return { ...(await (deps.systemd ?? systemd).repair({ dataDir, log, ...(deps.systemdOpts ?? {}) })), mechanism: 'systemd' };
1071
+ }
1072
+
1073
+ if (mech.mode === MODES.SERVER) {
1074
+ const result = await (deps.windowsService ?? windowsService).repair({
1075
+ dataDir,
1076
+ appRoot: appRoot(),
1077
+ config: loadConfig(),
1078
+ log,
1079
+ ...(deps.windowsServiceOpts ?? {}),
1080
+ });
1081
+ if (result.ok) {
1082
+ const existing = dbGet(STATE_KEY) ?? {};
1083
+ dbSet(STATE_KEY, { ...existing, granted: result.granted ?? existing.granted ?? [], repairedAt: new Date().toISOString() });
1084
+ }
1085
+ return { ...result, mechanism: 'winsw' };
1086
+ }
1087
+
1088
+ const result = (deps.windowsPersonal ?? windowsPersonal).repair({
1089
+ dataDir,
1090
+ entry: entryScript(),
1091
+ log,
1092
+ ...(deps.windowsPersonalOpts ?? {}),
1093
+ });
1094
+ if (result.ok) {
1095
+ const existing = dbGet(STATE_KEY) ?? {};
1096
+ dbSet(STATE_KEY, { ...existing, nodeExe: result.nodeExe, repairedAt: new Date().toISOString() });
1097
+ }
1098
+ return { ...result, mechanism: 'startup-supervisor' };
1099
+ }
1100
+
1101
+ /** Records what was installed, merged over whatever is already there. */
1102
+ function record(details) {
1103
+ const existing = dbGet(STATE_KEY) ?? {};
1104
+ dbSet(STATE_KEY, { ...existing, ...details, installedAt: new Date().toISOString() });
1105
+ }
1106
+
1107
+ /** The recorded install details, for callers that only need to read them. */
1108
+ export function recordedState() {
1109
+ return dbGet(STATE_KEY) ?? {};
1110
+ }
1111
+
1112
+ /**
1113
+ * Updates the recorded runtime path without re-recording an install.
1114
+ *
1115
+ * `ezz runtime update` needs exactly this and nothing else: the service is
1116
+ * already installed, only the binary it runs changed. Exported rather than
1117
+ * duplicated there so `service-state` keeps one writer, and so `installedAt`
1118
+ * is not overwritten by what is not an install.
1119
+ *
1120
+ * @param {Object} details
1121
+ * @param {string} details.nodeExe
1122
+ */
1123
+ export function recordRuntime({ nodeExe }) {
1124
+ const existing = dbGet(STATE_KEY) ?? {};
1125
+ dbSet(STATE_KEY, { ...existing, nodeExe, runtimeUpdatedAt: new Date().toISOString() });
1126
+ }
1127
+
1128
+ export { legacy, runtimeNodePath };