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,458 @@
1
+ /**
2
+ * core/service/systemd.js
3
+ *
4
+ * The Linux service: a systemd unit that runs `ezz daemon`.
5
+ *
6
+ * ── Why the unit runs as the invoking user, not root ───────────────────────
7
+ *
8
+ * The daemon writes to `~/.config/easy-devops` and reads the user's nginx
9
+ * configuration. Running it as root would put root-owned files in the user's
10
+ * data directory, which then breaks every subsequent `ezz` command run
11
+ * normally — a failure that looks like corruption rather than a permission
12
+ * problem. `User=` is the invoking user for that reason, and it is also the
13
+ * least privilege that works: nginx control already goes through `sudo -n`
14
+ * with specific sudoers rules, so the daemon does not need to be root to
15
+ * reload nginx.
16
+ *
17
+ * ── Why sudo is asked for by sudo ──────────────────────────────────────────
18
+ *
19
+ * Writing to `/etc/systemd/system` needs root. The command is run with
20
+ * `runInteractive`, so sudo prompts on the user's own terminal and the
21
+ * password never passes through this process. Nothing here ever reads,
22
+ * stores, or asks for a password itself.
23
+ */
24
+
25
+ import fs from 'fs';
26
+ import os from 'os';
27
+ import path from 'path';
28
+
29
+ import { run, runInteractive } from '../shell.js';
30
+ import { isDefaultDataDir } from '../platform.js';
31
+ import { runtimeNodePath } from './runtime.js';
32
+
33
+ /** Unit name and path. One unit, one name, no per-user variants. */
34
+ export const UNIT_NAME = 'easy-devops.service';
35
+ export const UNIT_PATH = `/etc/systemd/system/${UNIT_NAME}`;
36
+
37
+ /** How long to wait for the daemon's heartbeat after starting the service. */
38
+ export const STARTUP_GRACE_MS = 10_000;
39
+
40
+ /**
41
+ * The package root for an entry script, used as the unit's WorkingDirectory.
42
+ *
43
+ * The entry is `<root>/src/cli/index.js`, so the directory containing it is
44
+ * two levels below the root. Using `dirname(entry)` would set the working
45
+ * directory to `src/cli`, where a relative path such as `package.json` does
46
+ * not resolve.
47
+ *
48
+ * @param {string} entry
49
+ * @returns {string}
50
+ */
51
+ export function packageRootFor(entry) {
52
+ // `path.posix`, not `path`: every path in a systemd unit is a Linux path,
53
+ // and the platform-sensitive `path` would rewrite one with a drive letter
54
+ // when this runs anywhere else — which is exactly what made this testable
55
+ // only on Linux before. It also means no `path.resolve`, which consults the
56
+ // host's cwd.
57
+ const dir = path.posix.dirname(entry);
58
+
59
+ // Only climb when the layout is the one we ship. Anything else is left alone
60
+ // rather than guessed at.
61
+ if (path.posix.basename(dir) === 'cli' && path.posix.basename(path.posix.dirname(dir)) === 'src') {
62
+ return path.posix.dirname(path.posix.dirname(dir));
63
+ }
64
+ return dir;
65
+ }
66
+
67
+ /** Whether this machine has systemd at all. */
68
+ export async function hasSystemd({ runner = run } = {}) {
69
+ // The directory is the cheapest reliable signal; `systemctl --version` also
70
+ // exists on machines where systemd is installed but not the init system,
71
+ // which is exactly the case that must not be treated as supported.
72
+ if (!fs.existsSync('/run/systemd/system')) return false;
73
+
74
+ const probe = await runner('systemctl --version', { timeout: 10_000 });
75
+ return probe.success;
76
+ }
77
+
78
+ /**
79
+ * The unit file.
80
+ *
81
+ * Choices worth knowing:
82
+ *
83
+ * - `After=network-online.target nginx.service` plus `Wants=network-online`:
84
+ * the daemon's first action is to probe domains and reach the Hub, both of
85
+ * which fail noisily on a machine whose network is not up yet. `After` on
86
+ * `nginx.service` is ordering only — a machine without nginx as a service
87
+ * still starts, because it is not listed under `Requires`.
88
+ * - `Restart=always` with `RestartSec=5`: a crash loop is handled by
89
+ * `StartLimitBurst` below rather than by giving up after one failure.
90
+ * - `StartLimitIntervalSec`/`StartLimitBurst` let systemd stop restarting a
91
+ * daemon that cannot start at all, which is what makes `status` able to
92
+ * report a crash loop instead of showing "activating" for ever.
93
+ * - No `ExecStop`: the daemon handles SIGTERM, releases the lock and closes
94
+ * the database. systemd's default is exactly that signal.
95
+ *
96
+ * @param {Object} opts
97
+ * @param {string} opts.nodeExe The pinned runtime path (a symlink)
98
+ * @param {string} opts.entry Absolute path to the ez entry script
99
+ * @param {string} opts.user
100
+ * @param {string} opts.dataDir
101
+ * @param {string} [opts.workingDir]
102
+ * @returns {string}
103
+ */
104
+ export function buildUnit({ nodeExe, entry, user, dataDir, workingDir = null }) {
105
+ // Only passed when it is NOT the default. A unit that sets it to the very
106
+ // directory the code already resolves on its own adds nothing, and the one
107
+ // that did set it needlessly turned the service into a dev run — staging
108
+ // certificates on real domains. See isDevDataDir() in core/platform.js.
109
+ const dataDirLine = isDefaultDataDir(dataDir)
110
+ ? '# EASY_DEVOPS_DATA_DIR is not set: this is the default directory.'
111
+ : `Environment=EASY_DEVOPS_DATA_DIR=${dataDir}`;
112
+
113
+ return `[Unit]
114
+ Description=Easy DevOps background service
115
+ Documentation=https://github.com/farghaly/easy-devops
116
+ After=network-online.target nginx.service
117
+ Wants=network-online.target
118
+
119
+ # These belong in [Unit], not [Service]: systemd moved them in v229 and still
120
+ # accepts the old position only with a deprecation warning in the journal.
121
+ # Stop restarting after 5 failures inside 60s, so a daemon that cannot start
122
+ # ends in a state 'systemctl status' reports plainly instead of thrashing.
123
+ StartLimitIntervalSec=60
124
+ StartLimitBurst=5
125
+
126
+ [Service]
127
+ Type=simple
128
+ User=${user}
129
+ WorkingDirectory=${workingDir ?? packageRootFor(entry)}
130
+
131
+ # The pinned runtime, not whatever "node" resolves to in a shell. A version
132
+ # manager can change that at any time; this path is ours.
133
+ ExecStart=${nodeExe} ${entry} daemon
134
+
135
+ Environment=NODE_ENV=production
136
+ ${dataDirLine}
137
+
138
+ Restart=always
139
+ RestartSec=5
140
+
141
+ # Give the daemon time to release its lock and close the database.
142
+ TimeoutStopSec=20
143
+ KillSignal=SIGTERM
144
+
145
+ StandardOutput=journal
146
+ StandardError=journal
147
+ SyslogIdentifier=easy-devops
148
+
149
+ [Install]
150
+ WantedBy=multi-user.target
151
+ `;
152
+ }
153
+
154
+ /** What to print when systemd is absent. */
155
+ export function manualInstructions({ nodeExe, entry, dataDir }) {
156
+ return [
157
+ 'This machine does not use systemd, so there is no unit to install.',
158
+ '',
159
+ 'Run the daemon yourself with whatever supervisor you use. The command is:',
160
+ '',
161
+ ` EASY_DEVOPS_DATA_DIR=${dataDir} ${nodeExe} ${entry} daemon`,
162
+ '',
163
+ 'It runs in the foreground, logs to stdout and stderr, and stops cleanly on',
164
+ 'SIGTERM. Anything that can keep a foreground process alive will do:',
165
+ '',
166
+ ' • OpenRC — an /etc/init.d script with supervise-daemon',
167
+ ' • runit — a run script under /etc/service/easy-devops/',
168
+ ' • s6 — an s6-rc service definition',
169
+ ' • supervisord — a [program:easy-devops] section',
170
+ '',
171
+ 'Only one daemon may run at a time; a second refuses to start and says so,',
172
+ 'so a supervisor that accidentally starts two cannot duplicate notifications.',
173
+ ].join('\n');
174
+ }
175
+
176
+ /**
177
+ * Installs and starts the unit.
178
+ *
179
+ * `runInteractive` is used for every privileged step so SUDO asks for the
180
+ * password, on the user's terminal, in its own words. This process never sees
181
+ * it. That also means a real TTY is required, which is checked first rather
182
+ * than discovered as a hang.
183
+ *
184
+ * @param {Object} opts
185
+ * @param {string} opts.nodeExe
186
+ * @param {string} opts.entry
187
+ * @param {string} opts.dataDir
188
+ * @param {string} [opts.user]
189
+ * @param {(line: string) => void} [opts.log]
190
+ * @param {Function} [opts.runner]
191
+ * @param {Function} [opts.interactive]
192
+ * @param {string} [opts.unitPath]
193
+ * @returns {Promise<{ ok: boolean, reason?: string, unitPath?: string }>}
194
+ */
195
+ export async function install({
196
+ nodeExe,
197
+ entry,
198
+ dataDir,
199
+ user = os.userInfo().username,
200
+ log = () => {},
201
+ runner = run,
202
+ interactive = runInteractive,
203
+ unitPath = UNIT_PATH,
204
+ } = {}) {
205
+ if (!process.stdin.isTTY) {
206
+ return {
207
+ ok: false,
208
+ reason: 'installing the service needs a real terminal, because sudo has to ask for your password. '
209
+ + 'Run `ezz service install` from a shell rather than from a script or the dashboard.',
210
+ };
211
+ }
212
+
213
+ const unit = buildUnit({ nodeExe, entry, user, dataDir });
214
+
215
+ // Written to a temp file and copied with sudo, rather than piping into a
216
+ // privileged shell redirect. `sudo tee` or `sudo sh -c '… > file'` both put
217
+ // the content through a shell, where every character in the unit has to be
218
+ // escaped correctly; a plain `cp` of a file does not.
219
+ const staged = path.join(os.tmpdir(), `easy-devops-${process.pid}.service`);
220
+ try {
221
+ fs.writeFileSync(staged, unit, 'utf8');
222
+ } catch (err) {
223
+ return { ok: false, reason: `could not stage the unit file: ${err.message}` };
224
+ }
225
+
226
+ log(`Installing ${unitPath} (sudo will ask for your password)`);
227
+
228
+ try {
229
+ const copy = await interactive(`sudo cp "${staged}" "${unitPath}" && sudo chmod 644 "${unitPath}"`);
230
+ if (!copy.success) {
231
+ return { ok: false, reason: `could not write ${unitPath}. sudo exited ${copy.exitCode ?? 'non-zero'}.` };
232
+ }
233
+
234
+ const reload = await interactive('sudo systemctl daemon-reload');
235
+ if (!reload.success) return { ok: false, reason: 'systemctl daemon-reload failed' };
236
+
237
+ const enable = await interactive(`sudo systemctl enable ${UNIT_NAME}`);
238
+ if (!enable.success) return { ok: false, reason: `systemctl enable ${UNIT_NAME} failed` };
239
+
240
+ const start = await interactive(`sudo systemctl restart ${UNIT_NAME}`);
241
+ if (!start.success) {
242
+ const recent = await journal({ lines: 20, runner });
243
+ return {
244
+ ok: false,
245
+ reason: `the service was installed but would not start.\n\nLast log lines:\n${recent.output}`,
246
+ unitPath,
247
+ };
248
+ }
249
+ } finally {
250
+ try { fs.rmSync(staged, { force: true }); } catch { /* best effort */ }
251
+ }
252
+
253
+ return { ok: true, unitPath };
254
+ }
255
+
256
+ /**
257
+ * Stops, disables and removes the unit.
258
+ *
259
+ * Every step tolerates "already gone": uninstall must succeed on a machine
260
+ * where the user removed the unit by hand, or they are left unable to clean up
261
+ * through the tool at all.
262
+ */
263
+ export async function uninstall({ log = () => {}, interactive = runInteractive, unitPath = UNIT_PATH } = {}) {
264
+ if (!process.stdin.isTTY) {
265
+ return {
266
+ ok: false,
267
+ reason: 'removing the service needs a real terminal, because sudo has to ask for your password.',
268
+ };
269
+ }
270
+
271
+ log(`Removing ${unitPath} (sudo will ask for your password)`);
272
+
273
+ // `|| true` on each: a stop of something not running, or a disable of
274
+ // something not enabled, exits non-zero and must not abort the rest.
275
+ const steps = [
276
+ `sudo systemctl stop ${UNIT_NAME} || true`,
277
+ `sudo systemctl disable ${UNIT_NAME} || true`,
278
+ `sudo rm -f "${unitPath}"`,
279
+ 'sudo systemctl daemon-reload',
280
+ // Clears systemd's record of a failed unit, so a reinstall does not start
281
+ // against a start-limit counter from before.
282
+ `sudo systemctl reset-failed ${UNIT_NAME} || true`,
283
+ ];
284
+
285
+ for (const step of steps) {
286
+ const result = await interactive(step);
287
+ if (!result.success && !step.endsWith('|| true')) {
288
+ return { ok: false, reason: `\`${step}\` failed` };
289
+ }
290
+ }
291
+
292
+ return { ok: true };
293
+ }
294
+
295
+ /** `systemctl restart`, which needs no password beyond sudo's own prompt. */
296
+ export async function restart({ interactive = runInteractive } = {}) {
297
+ const result = await interactive(`sudo systemctl restart ${UNIT_NAME}`);
298
+ return { ok: result.success, reason: result.success ? null : `systemctl restart ${UNIT_NAME} failed` };
299
+ }
300
+
301
+ /**
302
+ * `systemctl stop` — temporary. The unit stays enabled, so the daemon comes
303
+ * back at the next boot. Removing it permanently is `ezz service uninstall`.
304
+ */
305
+ export async function stop({ interactive = runInteractive } = {}) {
306
+ if (!fs.existsSync(UNIT_PATH)) {
307
+ return { ok: false, reason: 'the service is not installed, so there is nothing to stop' };
308
+ }
309
+ if (!process.stdin.isTTY) {
310
+ return {
311
+ ok: false,
312
+ reason: 'stopping the service needs a terminal, because sudo has to ask for your password.',
313
+ };
314
+ }
315
+
316
+ const result = await interactive(`sudo systemctl stop ${UNIT_NAME}`);
317
+ return { ok: result.success, reason: result.success ? null : `systemctl stop ${UNIT_NAME} failed` };
318
+ }
319
+
320
+ /** `systemctl start`. */
321
+ export async function start({ interactive = runInteractive } = {}) {
322
+ if (!fs.existsSync(UNIT_PATH)) {
323
+ return { ok: false, reason: 'the service is not installed; run `ezz service install` first' };
324
+ }
325
+ if (!process.stdin.isTTY) {
326
+ return {
327
+ ok: false,
328
+ reason: 'starting the service needs a terminal, because sudo has to ask for your password.',
329
+ };
330
+ }
331
+
332
+ const result = await interactive(`sudo systemctl start ${UNIT_NAME}`);
333
+ return { ok: result.success, reason: result.success ? null : `systemctl start ${UNIT_NAME} failed` };
334
+ }
335
+
336
+ /**
337
+ * Recent log lines, from the journal.
338
+ *
339
+ * Read with plain `journalctl` and no sudo: a unit running as the current user
340
+ * logs where that user can read it, and requiring sudo to read your own logs
341
+ * would be a password prompt for a status command.
342
+ */
343
+ export async function journal({ lines = 50, runner = run } = {}) {
344
+ const result = await runner(
345
+ `journalctl -u ${UNIT_NAME} -n ${Math.max(1, Math.min(5000, Number(lines) || 50))} --no-pager`,
346
+ { timeout: 20_000 },
347
+ );
348
+
349
+ const output = [result.stdout, result.stderr].filter(Boolean).join('\n').trim();
350
+
351
+ if (!result.success) {
352
+ return {
353
+ ok: false,
354
+ output: output || `journalctl could not read the unit's logs. If this says "No journal files were found", `
355
+ + 'the journal is not persistent on this machine.',
356
+ };
357
+ }
358
+
359
+ return { ok: true, output };
360
+ }
361
+
362
+ /**
363
+ * The unit's state, including whether it is in a crash loop.
364
+ *
365
+ * A crash loop is the failure mode a naive status read misses: `is-active`
366
+ * says `activating` while systemd is restarting a daemon that dies every five
367
+ * seconds, which reads as "starting up" for ever. `NRestarts` is what reveals
368
+ * it, so it is read explicitly and reported.
369
+ *
370
+ * @param {Object} [opts]
371
+ * @returns {Promise<Object>}
372
+ */
373
+ export async function status({ runner = run } = {}) {
374
+ const installed = fs.existsSync(UNIT_PATH);
375
+
376
+ if (!installed) {
377
+ return {
378
+ installed: false,
379
+ running: false,
380
+ enabledOnBoot: false,
381
+ state: 'not installed',
382
+ restarts: 0,
383
+ crashLooping: false,
384
+ unitPath: UNIT_PATH,
385
+ };
386
+ }
387
+
388
+ // One call for several properties: cheaper than four systemctl invocations,
389
+ // and consistent — four calls can straddle a state change.
390
+ const props = await runner(
391
+ `systemctl show ${UNIT_NAME} --property=ActiveState --property=SubState --property=NRestarts `
392
+ + '--property=UnitFileState --property=ExecMainStartTimestamp --property=Result --no-pager',
393
+ { timeout: 15_000 },
394
+ );
395
+
396
+ const parsed = Object.fromEntries(
397
+ (props.stdout || '').split('\n')
398
+ .map((line) => line.split('='))
399
+ .filter((pair) => pair.length >= 2)
400
+ .map(([key, ...rest]) => [key.trim(), rest.join('=').trim()]),
401
+ );
402
+
403
+ const activeState = parsed.ActiveState || 'unknown';
404
+ const restarts = Number(parsed.NRestarts) || 0;
405
+
406
+ // Restarting repeatedly, or stopped by the start limit. Either way the
407
+ // daemon is not staying up, which is the thing worth saying.
408
+ const crashLooping = restarts >= 3 && activeState !== 'active'
409
+ || parsed.Result === 'start-limit-hit'
410
+ || (activeState === 'failed' && restarts >= 3);
411
+
412
+ return {
413
+ installed: true,
414
+ running: activeState === 'active',
415
+ enabledOnBoot: parsed.UnitFileState === 'enabled',
416
+ state: parsed.SubState ? `${activeState} (${parsed.SubState})` : activeState,
417
+ restarts,
418
+ crashLooping,
419
+ result: parsed.Result || null,
420
+ startedAt: parsed.ExecMainStartTimestamp || null,
421
+ unitPath: UNIT_PATH,
422
+ };
423
+ }
424
+
425
+ /**
426
+ * Re-points the runtime symlink and reloads the unit.
427
+ *
428
+ * The repair case this exists for: the user upgraded Node through nvm, the old
429
+ * version was removed, and the link now points at nothing. Re-pointing the
430
+ * link is enough — the unit itself refers to the link, not to a Node version,
431
+ * which is the entire reason it is a link.
432
+ */
433
+ export async function repair({ dataDir, nodeExe = process.execPath, log = () => {}, interactive = runInteractive } = {}) {
434
+ const { linkRuntime } = await import('./runtime.js');
435
+
436
+ const linked = linkRuntime({ dataDir, nodeExe });
437
+ if (!linked.ok) return { ok: false, reason: linked.reason };
438
+ log(`Runtime link → ${linked.target}`);
439
+
440
+ if (!fs.existsSync(UNIT_PATH)) {
441
+ return { ok: true, relinked: true, reason: 'the runtime link was fixed; no unit is installed' };
442
+ }
443
+
444
+ if (!process.stdin.isTTY) {
445
+ return {
446
+ ok: false,
447
+ reason: 'the runtime link was fixed, but restarting the unit needs a terminal for sudo.',
448
+ };
449
+ }
450
+
451
+ const result = await interactive(`sudo systemctl restart ${UNIT_NAME}`);
452
+ return result.success
453
+ ? { ok: true, relinked: true, target: linked.target }
454
+ : { ok: false, reason: `the link was fixed but \`systemctl restart ${UNIT_NAME}\` failed` };
455
+ }
456
+
457
+ /** The pinned runtime path for this data directory. Re-exported for the installer. */
458
+ export { runtimeNodePath };