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,530 @@
1
+ /**
2
+ * core/service/windowsPersonal.js
3
+ *
4
+ * Windows "Personal" mode: the daemon starts when the user logs in, with no
5
+ * elevation and no password.
6
+ *
7
+ * This is the right mode for a workstation. It is honest about its limits:
8
+ * nothing runs before someone signs in, and the data stays in `%APPDATA%`.
9
+ * A machine that should be monitored while nobody is logged in needs Server
10
+ * mode and its elevation.
11
+ *
12
+ * ── Two files, because of the window ──────────────────────────────────────
13
+ *
14
+ * The first version of this was a single `.cmd` in the Startup folder holding
15
+ * the whole supervisor loop. That meant a **console window open for the entire
16
+ * session**, and closing it — which looks like exactly the right thing to do
17
+ * with a stray black window — killed the daemon with no restart. Unusable.
18
+ *
19
+ * So the Startup entry is now a tiny **bootstrap** that launches the real
20
+ * supervisor hidden and exits immediately. Two files:
21
+ *
22
+ * `<Startup>\easy-devops-daemon.cmd` — the bootstrap. Flashes briefly.
23
+ * `<dataDir>\daemon-supervisor.cmd` — the supervisor loop. Never visible.
24
+ *
25
+ * The hide is `Start-Process -WindowStyle Hidden` through PowerShell, which is
26
+ * the documented way to launch a console program with no window. Deliberately
27
+ * NOT a VBScript wrapper: that is the classic trick and endpoint protection now
28
+ * flags or blocks it on many machines. Deliberately not `start /b` either —
29
+ * that shares the bootstrap's console, so the child's fate is tied to a window
30
+ * we are trying to get rid of.
31
+ *
32
+ * ── The supervisor ─────────────────────────────────────────────────────────
33
+ *
34
+ * Nothing restarts a crashed program in the Startup folder, so the supervisor
35
+ * restarts the daemon with a growing delay. Without it, one crash means no
36
+ * monitoring until the next logon — which could be weeks.
37
+ *
38
+ * Exit code 0 means "asked to stop" and is not restarted. That is how
39
+ * `ezz service stop` works without any service manager: it writes a stop
40
+ * request, the daemon sees it and exits 0, and the supervisor stands down. The
41
+ * bootstrap clears the request at logon, so a stop lasts until the next sign-in
42
+ * or an explicit `ezz service start`.
43
+ */
44
+
45
+ import fs from 'fs';
46
+ import path from 'path';
47
+
48
+ import { getStartupFolder, isWindows, isDefaultDataDir } from '../platform.js';
49
+ import { dbGet, dbSet } from '../db.js';
50
+ import { run as shellRun } from '../shell.js';
51
+ import { stopRequestPath } from '../daemon/stopRequest.js';
52
+
53
+ /** The Startup entry. Distinct from the old PM2 one (`easy-devops-pm2.cmd`). */
54
+ export const LAUNCHER_FILE = 'easy-devops-daemon.cmd';
55
+
56
+ /** The supervisor, which lives in the data directory rather than in Startup. */
57
+ export const SUPERVISOR_FILE = 'daemon-supervisor.cmd';
58
+
59
+ /** Where the recorded install details live. */
60
+ const STATE_KEY = 'service-state';
61
+
62
+ /** Absolute path of the Startup bootstrap, or null when there is no folder. */
63
+ export function launcherPath(startupDir = getStartupFolder()) {
64
+ return startupDir ? path.join(startupDir, LAUNCHER_FILE) : null;
65
+ }
66
+
67
+ /** Absolute path of the supervisor script. */
68
+ export function supervisorPath(dataDir) {
69
+ return path.join(dataDir, SUPERVISOR_FILE);
70
+ }
71
+
72
+ /** Where the supervisor writes its log. */
73
+ export function logFilePath(dataDir) {
74
+ return path.join(dataDir, 'daemon-supervisor.log');
75
+ }
76
+
77
+ /**
78
+ * The PowerShell command that starts a `.cmd` with no window.
79
+ *
80
+ * Shared by the logon bootstrap and `ezz service start`, so both produce an
81
+ * identically hidden process — a `start` that left a visible window would be a
82
+ * confusing difference from a logon start.
83
+ *
84
+ * The supervisor path is passed through the ENVIRONMENT rather than inlined
85
+ * into the command string. That avoids nested quoting entirely: a path with a
86
+ * space (`C:\Users\A B\...`) has to survive cmd, then PowerShell, then
87
+ * Start-Process, and every layer quotes differently. An environment variable
88
+ * crosses all three untouched.
89
+ *
90
+ * @param {string} envVarName Name of the variable holding the script path
91
+ * @returns {string}
92
+ */
93
+ export function hiddenStartCommand(envVarName = 'EZ_SUPERVISOR') {
94
+ return 'powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden '
95
+ + `-Command "Start-Process -FilePath $env:${envVarName} -WindowStyle Hidden"`;
96
+ }
97
+
98
+ /**
99
+ * The Startup bootstrap.
100
+ *
101
+ * Does three things and exits: clears any pending stop request (so a stop
102
+ * lasts until the next logon, not for ever), launches the supervisor hidden,
103
+ * and gets out of the way. Its own window is visible for a fraction of a
104
+ * second, which is the accepted trade-off.
105
+ *
106
+ * @param {Object} opts
107
+ * @param {string} opts.supervisor Absolute path to the supervisor script
108
+ * @param {string} opts.stopFile Absolute path to the stop-request file
109
+ * @returns {string}
110
+ */
111
+ export function buildBootstrap({ supervisor, stopFile }) {
112
+ return `@echo off
113
+ rem Easy DevOps -- logon bootstrap.
114
+ rem
115
+ rem Created by \`ezz service install\` (Personal mode). Safe to delete: doing so
116
+ rem simply stops the daemon from starting when you log in.
117
+ rem
118
+ rem This file does NOT contain the supervisor. It starts it with no window and
119
+ rem exits, so there is no console window left open for the session. The
120
+ rem supervisor itself is at:
121
+ rem ${supervisor}
122
+
123
+ rem A stop requested with \`ezz service stop\` lasts until the next logon. This
124
+ rem is the line that makes it temporary rather than permanent.
125
+ if exist "${stopFile}" del /q "${stopFile}" >nul 2>&1
126
+
127
+ set "EZ_SUPERVISOR=${supervisor}"
128
+ ${hiddenStartCommand()}
129
+
130
+ exit /b 0
131
+ `;
132
+ }
133
+
134
+ /**
135
+ * The supervisor script: runs the daemon, restarts it on crash, stands down
136
+ * when it is asked to stop.
137
+ *
138
+ * Written in plain `cmd` rather than PowerShell because a `.ps1` does not run
139
+ * on a default execution policy, and changing the policy for the user would be
140
+ * a far bigger imposition than a batch file.
141
+ *
142
+ * @param {Object} opts
143
+ * @param {string} opts.nodeExe Absolute path, captured at install
144
+ * @param {string} opts.entry Absolute path to the ez entry script
145
+ * @param {string} opts.dataDir
146
+ * @param {string} opts.logFile
147
+ * @param {string} opts.stopFile
148
+ * @returns {string}
149
+ */
150
+ export function buildSupervisor({ nodeExe, entry, dataDir, logFile, stopFile }) {
151
+ // Only set when it is NOT the default directory. Passing it needlessly is
152
+ // what put the daemon into dev mode -- issuing staging certificates on real
153
+ // domains -- back when dev mode was inferred from the variable's presence.
154
+ // Both halves of that bug are fixed; this is the belt as well as the braces.
155
+ const dataDirLine = isDefaultDataDir(dataDir)
156
+ ? 'rem EASY_DEVOPS_DATA_DIR is not set: this is the default directory.'
157
+ : `set "EASY_DEVOPS_DATA_DIR=${dataDir}"`;
158
+
159
+ // Batch has no arrays and awkward arithmetic, so the backoff is a short
160
+ // explicit ladder rather than a computed sequence. Clearer to read in a file
161
+ // the user may well open.
162
+ return `@echo off
163
+ setlocal EnableDelayedExpansion
164
+
165
+ rem Easy DevOps -- supervisor for the background daemon (Personal mode).
166
+ rem
167
+ rem Started hidden by the logon bootstrap in your Startup folder, or by
168
+ rem \`ezz service start\`. Do not put this file in the Startup folder: it would
169
+ rem then run with a visible console window for the whole session.
170
+
171
+ ${dataDirLine}
172
+ set "NODE_ENV=production"
173
+ set "LOGFILE=${logFile}"
174
+ set "NODEEXE=${nodeExe}"
175
+ set "ENTRY=${entry}"
176
+ set "STOPFILE=${stopFile}"
177
+
178
+ set "DELAY=5"
179
+ set "FAILS=0"
180
+
181
+ :loop
182
+ rem Trim the log if it has grown past ~5 MB, so an unattended machine cannot
183
+ rem fill its disk with restart notices. The \`if exist\` guard is required:
184
+ rem %%~zA on a file that does not exist expands to nothing, which turns the
185
+ rem comparison below into a batch syntax error on the very first run.
186
+ if exist "!LOGFILE!" (
187
+ for %%A in ("!LOGFILE!") do (
188
+ if %%~zA GTR 5242880 (
189
+ del /q "!LOGFILE!" 2>nul
190
+ echo [%DATE% %TIME%] log trimmed>>"!LOGFILE!"
191
+ )
192
+ )
193
+ )
194
+
195
+ rem Checked BEFORE starting, not only after the daemon exits: a stop requested
196
+ rem while this script is in its backoff sleep would otherwise be ignored and a
197
+ rem fresh daemon started on top of it.
198
+ if exist "!STOPFILE!" (
199
+ echo [%DATE% %TIME%] stop requested, not starting>>"!LOGFILE!"
200
+ goto end
201
+ )
202
+
203
+ echo [%DATE% %TIME%] starting daemon>>"!LOGFILE!"
204
+
205
+ "!NODEEXE!" "!ENTRY!" daemon>>"!LOGFILE!" 2>&1
206
+
207
+ set "CODE=!ERRORLEVEL!"
208
+ echo [%DATE% %TIME%] daemon exited with code !CODE!>>"!LOGFILE!"
209
+
210
+ rem Exit code 0 means it was asked to stop -- by \`ezz service stop\`, or by a
211
+ rem signal. Do not restart it: that is the difference between "stopped" and
212
+ rem "crashed", and restarting here would make \`ezz service stop\` impossible.
213
+ if "!CODE!"=="0" (
214
+ echo [%DATE% %TIME%] clean exit, not restarting>>"!LOGFILE!"
215
+ goto end
216
+ )
217
+
218
+ set /a FAILS+=1
219
+
220
+ rem Backoff ladder: 5, 15, 30, then 60 seconds for every attempt after.
221
+ if !FAILS! EQU 1 set "DELAY=5"
222
+ if !FAILS! EQU 2 set "DELAY=15"
223
+ if !FAILS! EQU 3 set "DELAY=30"
224
+ if !FAILS! GEQ 4 set "DELAY=60"
225
+
226
+ echo [%DATE% %TIME%] restarting in !DELAY!s (failure !FAILS!)>>"!LOGFILE!"
227
+
228
+ rem The delay is called by ABSOLUTE path. Plain \`timeout\` resolves through
229
+ rem PATH, and a machine with Git for Windows or any GNU coreutils on PATH gets
230
+ rem the Unix \`timeout\`, which rejects these arguments outright -- measured, not
231
+ rem assumed. The delay would then be skipped and this backoff would become the
232
+ rem tight restart loop it exists to prevent.
233
+ rem
234
+ rem \`ping\` is the fallback: Windows' timeout.exe also refuses to run when stdin
235
+ rem is redirected, which happens in some logon contexts. ping -n N waits N-1
236
+ rem seconds and needs no console.
237
+ set /a PINGS=!DELAY!+1
238
+ "%SystemRoot%\\System32\\timeout.exe" /t !DELAY! /nobreak >nul 2>&1
239
+ if errorlevel 1 ping -n !PINGS! 127.0.0.1 >nul 2>&1
240
+
241
+ goto loop
242
+
243
+ :end
244
+ endlocal
245
+ `;
246
+ }
247
+
248
+ /**
249
+ * Installs the bootstrap and the supervisor, and records what they were pinned
250
+ * to.
251
+ *
252
+ * The absolute `node.exe` path is captured here and checked by `status`. There
253
+ * is no copy and no symlink: Personal mode has no elevation and nowhere
254
+ * admin-only to put one, and a Windows symlink needs either elevation or
255
+ * Developer Mode. So the honest design is to record the path and detect it
256
+ * breaking, which is what `status` does when nvm-windows removes a version.
257
+ *
258
+ * @param {Object} opts
259
+ * @param {string} opts.dataDir
260
+ * @param {string} opts.entry
261
+ * @param {string} [opts.nodeExe]
262
+ * @param {string} [opts.startupDir] Injected by tests
263
+ * @param {(line: string) => void} [opts.log]
264
+ * @param {boolean} [opts.record] Write the recorded state (default true)
265
+ * @returns {{ ok: boolean, reason?: string, launcher?: string, supervisor?: string, nodeExe?: string }}
266
+ */
267
+ export function install({
268
+ dataDir,
269
+ entry,
270
+ nodeExe = process.execPath,
271
+ startupDir = getStartupFolder(),
272
+ log = () => {},
273
+ record = true,
274
+ } = {}) {
275
+ if (!isWindows) return { ok: false, reason: 'Personal mode is Windows-only' };
276
+
277
+ if (!startupDir) {
278
+ return {
279
+ ok: false,
280
+ reason: 'could not find your Startup folder, so there is nowhere to put the launcher. '
281
+ + 'Check that %APPDATA% is set.',
282
+ };
283
+ }
284
+
285
+ const launcher = path.join(startupDir, LAUNCHER_FILE);
286
+ const supervisor = supervisorPath(dataDir);
287
+ const logFile = logFilePath(dataDir);
288
+ const stopFile = stopRequestPath(dataDir);
289
+
290
+ // Resolved to a real path so a shim is not what gets recorded. nvm-windows
291
+ // in particular puts a symlink at a fixed location and repoints it on
292
+ // `nvm use`; recording that link would mean the daemon silently changes Node
293
+ // version the next time the user switches.
294
+ let resolvedNode;
295
+ try {
296
+ resolvedNode = fs.realpathSync(nodeExe);
297
+ } catch {
298
+ resolvedNode = path.resolve(nodeExe);
299
+ }
300
+
301
+ try {
302
+ fs.mkdirSync(dataDir, { recursive: true });
303
+ fs.writeFileSync(
304
+ supervisor,
305
+ buildSupervisor({ nodeExe: resolvedNode, entry, dataDir, logFile, stopFile }),
306
+ 'utf8',
307
+ );
308
+ log(`Wrote ${supervisor}`);
309
+ } catch (err) {
310
+ return { ok: false, reason: `could not write the supervisor: ${err.message}` };
311
+ }
312
+
313
+ try {
314
+ fs.mkdirSync(startupDir, { recursive: true });
315
+ fs.writeFileSync(launcher, buildBootstrap({ supervisor, stopFile }), 'utf8');
316
+ log(`Wrote ${launcher}`);
317
+ } catch (err) {
318
+ return { ok: false, reason: `could not write the launcher: ${err.message}` };
319
+ }
320
+
321
+ if (record) {
322
+ const existing = dbGet(STATE_KEY) ?? {};
323
+ dbSet(STATE_KEY, {
324
+ ...existing,
325
+ mode: 'personal',
326
+ installedAt: new Date().toISOString(),
327
+ stoppedAt: null,
328
+ nodeExe: resolvedNode,
329
+ entry,
330
+ launcher,
331
+ supervisor,
332
+ dataDir,
333
+ });
334
+ }
335
+
336
+ return { ok: true, launcher, supervisor, nodeExe: resolvedNode, logFile };
337
+ }
338
+
339
+ /**
340
+ * Starts the supervisor now, hidden, without waiting for a logon.
341
+ *
342
+ * @param {Object} opts
343
+ * @param {string} opts.dataDir
344
+ * @param {Function} [opts.run]
345
+ * @returns {Promise<{ ok: boolean, reason?: string, supervisor?: string }>}
346
+ */
347
+ export async function startNow({ dataDir, run = shellRun, log = () => {} } = {}) {
348
+ const supervisor = supervisorPath(dataDir);
349
+
350
+ if (!fs.existsSync(supervisor)) {
351
+ return {
352
+ ok: false,
353
+ reason: `the supervisor script is missing (${supervisor}). Run \`ezz service install\` first.`,
354
+ };
355
+ }
356
+
357
+ // The path travels in the environment for the quoting reason explained on
358
+ // hiddenStartCommand(). `run()` goes through PowerShell, so the command is
359
+ // the same one the bootstrap uses.
360
+ const command = `$env:EZ_SUPERVISOR = ${JSON.stringify(supervisor)}; `
361
+ + 'Start-Process -FilePath $env:EZ_SUPERVISOR -WindowStyle Hidden';
362
+
363
+ const result = await run(command, { timeout: 30_000 });
364
+ if (!result.success) {
365
+ return {
366
+ ok: false,
367
+ reason: `could not start the supervisor: ${`${result.stdout ?? ''}${result.stderr ?? ''}`.trim().slice(0, 300)}`,
368
+ };
369
+ }
370
+
371
+ log(`Started ${supervisor} (hidden)`);
372
+ return { ok: true, supervisor };
373
+ }
374
+
375
+ /** Removes the bootstrap and the supervisor. */
376
+ export function uninstall({ dataDir = null, startupDir = getStartupFolder(), log = () => {}, record = true } = {}) {
377
+ if (!isWindows) return { ok: false, reason: 'Personal mode is Windows-only' };
378
+
379
+ const launcher = launcherPath(startupDir);
380
+ const notes = [];
381
+
382
+ if (launcher && fs.existsSync(launcher)) {
383
+ try {
384
+ fs.rmSync(launcher, { force: true });
385
+ log(`Removed ${launcher}`);
386
+ } catch (err) {
387
+ return { ok: false, reason: `could not remove ${launcher}: ${err.message}` };
388
+ }
389
+ } else {
390
+ notes.push('the launcher was not present');
391
+ }
392
+
393
+ // The supervisor lives in the data directory, so it is removed too — leaving
394
+ // it behind would mean `ezz service start` could still run a daemon after an
395
+ // uninstall, which is not what uninstall means.
396
+ const recorded = dbGet(STATE_KEY) ?? {};
397
+ const supervisor = dataDir ? supervisorPath(dataDir) : recorded.supervisor;
398
+
399
+ if (supervisor && fs.existsSync(supervisor)) {
400
+ try {
401
+ fs.rmSync(supervisor, { force: true });
402
+ log(`Removed ${supervisor}`);
403
+ } catch (err) {
404
+ notes.push(`could not remove ${supervisor}: ${err.message}`);
405
+ }
406
+ }
407
+
408
+ if (record && recorded.mode === 'personal') {
409
+ dbSet(STATE_KEY, { ...recorded, mode: null, stoppedAt: null, uninstalledAt: new Date().toISOString() });
410
+ }
411
+
412
+ return { ok: true, notes };
413
+ }
414
+
415
+ /**
416
+ * The state of a Personal-mode install.
417
+ *
418
+ * `running` is not asked of Windows here — there is no service to query. The
419
+ * authority on whether the daemon is up is its own lock file, which the
420
+ * dispatcher reads; this function reports only what Personal mode itself owns.
421
+ *
422
+ * @param {Object} [opts]
423
+ * @returns {Object}
424
+ */
425
+ export function status({ dataDir = null, startupDir = getStartupFolder() } = {}) {
426
+ const launcher = launcherPath(startupDir);
427
+ const installed = Boolean(launcher && fs.existsSync(launcher));
428
+ const recorded = dbGet(STATE_KEY) ?? {};
429
+ const supervisor = dataDir ? supervisorPath(dataDir) : recorded.supervisor ?? null;
430
+
431
+ const out = {
432
+ installed,
433
+ launcher,
434
+ supervisor,
435
+ enabledOnBoot: installed,
436
+ startsAt: 'logon',
437
+ recordedNodeExe: recorded.nodeExe ?? null,
438
+ nodeExeExists: null,
439
+ warnings: [],
440
+ };
441
+
442
+ if (!installed) {
443
+ out.state = 'not installed';
444
+ return out;
445
+ }
446
+
447
+ out.state = 'installed (starts at logon)';
448
+
449
+ if (supervisor && !fs.existsSync(supervisor)) {
450
+ out.warnings.push(
451
+ `The launcher is installed but its supervisor is missing:\n ${supervisor}\n`
452
+ + 'Run `ezz service install` again to recreate it.',
453
+ );
454
+ }
455
+
456
+ if (recorded.nodeExe) {
457
+ out.nodeExeExists = fs.existsSync(recorded.nodeExe);
458
+ if (!out.nodeExeExists) {
459
+ out.warnings.push(
460
+ `The Node the launcher was pinned to no longer exists:\n ${recorded.nodeExe}\n`
461
+ + 'If you use nvm-windows, that version was probably uninstalled or switched. '
462
+ + 'Fix it with: ezz service repair',
463
+ );
464
+ }
465
+ } else {
466
+ out.warnings.push(
467
+ 'No Node path was recorded for this install, so it cannot be checked. '
468
+ + 'Run `ezz service repair` to record one.',
469
+ );
470
+ }
471
+
472
+ // A launcher left over from the single-file design would run the supervisor
473
+ // in a visible window for the whole session. Detected by its size: the
474
+ // bootstrap is small, while the old all-in-one script was not.
475
+ try {
476
+ const script = fs.readFileSync(launcher, 'utf8');
477
+ if (!script.includes('EZ_SUPERVISOR')) {
478
+ out.warnings.push(
479
+ 'Your Startup launcher is from an older version that ran in a visible '
480
+ + 'console window for the whole session. Run `ezz service install` again '
481
+ + 'to replace it with the hidden one.',
482
+ );
483
+ }
484
+ if (recorded.entry && script.includes(recorded.entry) === false && script.includes('EZ_SUPERVISOR') === false) {
485
+ out.warnings.push(
486
+ 'The launcher points at a different entry point than the one recorded at install. '
487
+ + 'Run `ezz service repair` to rewrite it.',
488
+ );
489
+ }
490
+ } catch { /* unreadable launcher: the existence check above already covers it */ }
491
+
492
+ return out;
493
+ }
494
+
495
+ /** Recent supervisor log lines. */
496
+ export function readLogs({ dataDir, lines = 50 } = {}) {
497
+ const file = logFilePath(dataDir);
498
+
499
+ let text;
500
+ try {
501
+ text = fs.readFileSync(file, 'utf8');
502
+ } catch (err) {
503
+ return {
504
+ ok: false,
505
+ file,
506
+ output: err.code === 'ENOENT'
507
+ ? `No supervisor log yet at ${file}. It is written the first time the daemon starts.`
508
+ : `Could not read ${file}: ${err.message}`,
509
+ };
510
+ }
511
+
512
+ const all = text.split(/\r?\n/).filter(Boolean);
513
+ return { ok: true, file, output: all.slice(-Math.max(1, Math.min(5000, Number(lines) || 50))).join('\n') };
514
+ }
515
+
516
+ /** Rewrites both scripts against the Node running now. */
517
+ export function repair({ dataDir, entry, nodeExe = process.execPath, startupDir = getStartupFolder(), log = () => {} } = {}) {
518
+ const recorded = dbGet(STATE_KEY) ?? {};
519
+ const resolvedEntry = entry ?? recorded.entry;
520
+
521
+ if (!resolvedEntry) {
522
+ return { ok: false, reason: 'no entry point is recorded and none was given; run `ezz service install` instead' };
523
+ }
524
+
525
+ const result = install({ dataDir, entry: resolvedEntry, nodeExe, startupDir, log });
526
+ if (!result.ok) return result;
527
+
528
+ log(`Re-pinned to ${result.nodeExe}`);
529
+ return { ok: true, launcher: result.launcher, supervisor: result.supervisor, nodeExe: result.nodeExe };
530
+ }