easy-devops 1.3.6 → 1.4.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 (69) hide show
  1. package/README.md +1 -0
  2. package/dist/ui/assets/index-Bu7af-Kj.css +1 -0
  3. package/dist/ui/assets/index-gndgYe3K.js +532 -0
  4. package/dist/ui/assets/socket-Bv0wCEgi.js +65 -0
  5. package/dist/ui/index.html +2 -2
  6. package/package.json +2 -2
  7. package/src/cli/index.js +8 -0
  8. package/src/cli/managers/domain-manager.js +37 -6
  9. package/src/cli/managers/nginx-manager.js +14 -5
  10. package/src/cli/managers/node-manager.js +19 -13
  11. package/src/cli/managers/ssl-manager.js +89 -26
  12. package/src/cli/menu.js +8 -2
  13. package/src/cli/menus/cleanup.js +4 -2
  14. package/src/cli/menus/dashboard.js +22 -15
  15. package/src/cli/menus/hub.js +381 -0
  16. package/src/cli/menus/runtime.js +12 -0
  17. package/src/cli/menus/service.js +28 -10
  18. package/src/cli/menus/settings.js +46 -12
  19. package/src/cli/menus/uninstall.js +13 -5
  20. package/src/cli/menus/update.js +24 -14
  21. package/src/cli/ui/page.js +123 -0
  22. package/src/core/cert-operations.js +34 -4
  23. package/src/core/cert-reader.js +67 -22
  24. package/src/core/cert-renewal.js +65 -9
  25. package/src/core/cert-suggest.js +120 -0
  26. package/src/core/cleanup.js +221 -1
  27. package/src/core/cloudflare-ips.js +161 -0
  28. package/src/core/daemon/ipc.js +1 -1
  29. package/src/core/daemon/lock.js +296 -9
  30. package/src/core/dashboardProcess.js +134 -6
  31. package/src/core/deploy/apps.js +36 -62
  32. package/src/core/deploy/deployKey.js +331 -0
  33. package/src/core/deploy/domainLink.js +280 -23
  34. package/src/core/deploy/engine.js +382 -63
  35. package/src/core/deploy/ezfile.js +496 -29
  36. package/src/core/deploy/githubApi.js +100 -13
  37. package/src/core/deploy/hubCommands.js +158 -18
  38. package/src/core/deploy/status.js +28 -1
  39. package/src/core/domains-db.js +1 -0
  40. package/src/core/hub/agent.js +238 -32
  41. package/src/core/hub/deployProgress.js +411 -0
  42. package/src/core/hubConnect.js +205 -0
  43. package/src/core/hubPermissions.js +48 -10
  44. package/src/core/jobs/bus.js +1 -1
  45. package/src/core/jobs/owner.js +268 -6
  46. package/src/core/nginx-conf-generator.js +124 -19
  47. package/src/core/notifications/claim.js +26 -3
  48. package/src/core/permissions.js +277 -59
  49. package/src/core/platform.js +48 -2
  50. package/src/core/runner.js +96 -40
  51. package/src/core/ssl/preflight.js +548 -0
  52. package/src/core/ssl/progress.js +196 -0
  53. package/src/core/ssl-issuer.js +502 -148
  54. package/src/core/validators.js +24 -0
  55. package/src/dashboard/controllers/authController.js +12 -5
  56. package/src/dashboard/controllers/deploymentsController.js +76 -11
  57. package/src/dashboard/controllers/domainsController.js +35 -1
  58. package/src/dashboard/controllers/hubController.js +4 -3
  59. package/src/dashboard/controllers/settingsController.js +73 -68
  60. package/src/dashboard/controllers/sslController.js +135 -15
  61. package/src/dashboard/public/js/app.js +42 -7
  62. package/src/dashboard/routes/deployments.js +2 -0
  63. package/src/dashboard/routes/domains.js +1 -0
  64. package/src/dashboard/server.js +42 -7
  65. package/src/dashboard/socketManager.js +19 -25
  66. package/src/dashboard/views/partials/settings-panel.ejs +29 -10
  67. package/dist/ui/assets/index-BUpPxWmp.css +0 -1
  68. package/dist/ui/assets/index-DD0JjK0Q.js +0 -475
  69. package/dist/ui/assets/socket-4tfdap-e.js +0 -65
@@ -87,6 +87,12 @@ export function claimPath(domain, eventType, status, dataDir = getDataDir()) {
87
87
 
88
88
  /**
89
89
  * Reads a claim file.
90
+ *
91
+ * An unreadable (half-written) claim is dated from the file's mtime, never from
92
+ * zero. `at: 0` would make it look ancient, and every reader would then be
93
+ * allowed to take it over immediately — which is how two processes ended up
94
+ * both sending one notification while the winner was still writing its claim.
95
+ *
90
96
  * @returns {{ pid: number, at: number }|null}
91
97
  */
92
98
  function readClaim(file) {
@@ -94,9 +100,14 @@ function readClaim(file) {
94
100
  const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
95
101
  return { pid: Number(parsed?.pid) || 0, at: Number(parsed?.at) || 0 };
96
102
  } catch {
97
- // Unreadable or half-written: treat as a claim with no useful owner, so
98
- // the TTL path below can reclaim it rather than blocking for ever.
99
- return { pid: 0, at: 0 };
103
+ try {
104
+ // No usable owner, but the file's own age is still evidence: a claim
105
+ // written a moment ago must be waited out, not reclaimed.
106
+ return { pid: 0, at: fs.statSync(file).mtimeMs };
107
+ } catch {
108
+ // Gone (a release, or a commit) — nothing to reclaim.
109
+ return null;
110
+ }
100
111
  }
101
112
  }
102
113
 
@@ -147,6 +158,17 @@ export function claim({
147
158
 
148
159
  // Someone holds it. Take it over only if they are gone AND it is old.
149
160
  const held = readClaim(file);
161
+ if (!held) {
162
+ // It vanished between the exclusive create and this read — its owner
163
+ // committed or released. Try once more to take it.
164
+ try {
165
+ fs.writeFileSync(file, payload, { flag: 'wx', encoding: 'utf8', mode: 0o600 });
166
+ return finish(false);
167
+ } catch (err) {
168
+ return { ok: false, heldBy: null, reason: `could not write a claim: ${err.message}` };
169
+ }
170
+ }
171
+
150
172
  const age = now - held.at;
151
173
  const ownerGone = held.pid === 0 || !isPidAlive(held.pid);
152
174
 
@@ -200,6 +222,7 @@ export function sweepAbandoned({ dataDir = getDataDir(), now = Date.now() } = {}
200
222
  if (!name.endsWith('.claim')) continue;
201
223
  const file = path.join(claimDir(dataDir), name);
202
224
  const held = readClaim(file);
225
+ if (!held) continue;
203
226
 
204
227
  const ownerGone = held.pid === 0 || !isPidAlive(held.pid);
205
228
  if (!ownerGone) continue;
@@ -1,75 +1,293 @@
1
- import { runInteractive, run } from './shell.js';
1
+ /**
2
+ * core/permissions.js
3
+ *
4
+ * The ONLY source of the sudo rules Easy DevOps installs on Linux, and of the
5
+ * one-time terminal commands that install them.
6
+ *
7
+ * ── Why this file is small and strict ──────────────────────────────────────
8
+ *
9
+ * A NOPASSWD sudoers rule is a standing grant of root to whoever runs as this
10
+ * user — including anything that compromises the dashboard. Earlier versions
11
+ * granted bare `/usr/bin/systemctl`, the unrestricted nginx binary, `mkdir`,
12
+ * `chown`, `cp`, `chmod`, `tee` and `certbot`. Each of those is a root shell on
13
+ * its own: `tee /etc/sudoers`, `chown $USER /etc/shadow`, `nginx -c <file>`,
14
+ * `systemctl link <unit>`. The dashboard also used to RECEIVE the operator's
15
+ * sudo password in an HTTP request to install them.
16
+ *
17
+ * Now:
18
+ * - the rules are exactly the five commands Easy DevOps runs with `sudo -n`,
19
+ * byte for byte, and nothing else (see SUDO_COMMANDS);
20
+ * - nothing here ever accepts, stores or forwards a password. The setup is a
21
+ * short script the operator runs in their own terminal, where sudo asks for
22
+ * their password itself. The dashboard only shows that script.
23
+ * - directories that used to need `sudo mkdir` / `sudo chown` at runtime are
24
+ * created and handed to the operator ONCE, by that same script, so no
25
+ * standing grant is needed for them.
26
+ *
27
+ * ── Matching is literal ────────────────────────────────────────────────────
28
+ *
29
+ * sudo compares the command line exactly. Every call site must invoke these
30
+ * strings verbatim (`sudo -n /usr/bin/systemctl reload nginx`), which is why
31
+ * they live in one exported list: a caller that builds its own string is a
32
+ * caller whose `sudo -n` fails silently. No wildcards are used anywhere — a
33
+ * `*` in a sudoers rule matches spaces too, so `chown user /srv/*` also matches
34
+ * `chown user /srv/x /etc/shadow`.
35
+ */
36
+
2
37
  import os from 'os';
38
+ import path from 'path';
39
+
40
+ import { run, runInteractive } from './shell.js';
41
+ import { isWindows } from './platform.js';
42
+ import { loadConfig } from './config.js';
43
+
44
+ /** Where the rule file is installed. */
45
+ export const SUDOERS_PATH = '/etc/sudoers.d/easy-devops';
46
+
47
+ /**
48
+ * Every command Easy DevOps runs non-interactively with `sudo -n`.
49
+ *
50
+ * Adding a line here is a security decision: it grants root to that exact
51
+ * command for the operator's account, permanently. Do not add a binary
52
+ * without its full argument list, and never add a shell, an editor, a file
53
+ * writer (`tee`, `cp`, `install`), an ownership or mode changer, or a service
54
+ * manager without a fixed unit.
55
+ */
56
+ export const SUDO_COMMANDS = Object.freeze([
57
+ '/usr/bin/systemctl start nginx',
58
+ '/usr/bin/systemctl stop nginx',
59
+ '/usr/bin/systemctl reload nginx',
60
+ '/usr/bin/systemctl restart nginx',
61
+ '/usr/bin/systemctl status nginx',
62
+ ]);
3
63
 
4
- async function findNginxPath() {
5
- const result = await run('which nginx');
6
- if (result.success && result.stdout.trim()) {
7
- return result.stdout.trim().split('\n')[0].trim();
64
+ /**
65
+ * The prefix a call site uses to run one of SUDO_COMMANDS.
66
+ *
67
+ * @param {string} command One entry of SUDO_COMMANDS
68
+ * @returns {string} e.g. `sudo -n /usr/bin/systemctl reload nginx`
69
+ */
70
+ export function sudoCommand(command) {
71
+ if (!SUDO_COMMANDS.includes(command)) {
72
+ // Refusing loudly is the point: an unlisted command would fail under
73
+ // `sudo -n` anyway, but silently, at the worst moment.
74
+ throw new Error(`"${command}" is not a granted sudo command; add it to SUDO_COMMANDS deliberately`);
8
75
  }
9
- throw new Error('nginx not found. Is nginx installed?');
76
+ return `sudo -n ${command}`;
10
77
  }
11
78
 
12
- export async function checkPermissionsConfigured() {
13
- const result = await run('sudo -n /usr/bin/systemctl status nginx 2>/dev/null');
14
- return result.success || !result.stderr?.includes('password');
79
+ /**
80
+ * Whether a name is safe to write into a sudoers line and a shell command.
81
+ *
82
+ * Deliberately narrower than what Linux allows: lowercase POSIX-portable
83
+ * names only. A name outside this set is refused rather than escaped, because
84
+ * the sudoers grammar and the shell have different quoting rules and getting
85
+ * either wrong is a privilege escalation.
86
+ *
87
+ * @param {string} name
88
+ * @returns {boolean}
89
+ */
90
+ export function isSafeUserName(name) {
91
+ return typeof name === 'string' && /^[a-z_][a-z0-9_-]{0,31}$/.test(name);
92
+ }
93
+
94
+ /**
95
+ * Whether a directory path is safe to put in the setup script.
96
+ *
97
+ * Absolute, normalised, and made only of characters that need no quoting.
98
+ * `/` itself and the system roots are refused: handing one of those to the
99
+ * operator would be the very ownership grant this file exists to avoid.
100
+ *
101
+ * @param {string} dir
102
+ * @returns {boolean}
103
+ */
104
+ export function isSafeSetupDir(dir) {
105
+ if (typeof dir !== 'string' || !dir.startsWith('/')) return false;
106
+ if (path.posix.normalize(dir) !== dir || dir.endsWith('/')) return false;
107
+ if (!/^[A-Za-z0-9._/-]+$/.test(dir)) return false;
108
+ if (dir.split('/').includes('..')) return false;
109
+
110
+ // Top-level directories are never handed over: at least two segments, so
111
+ // `/etc/ssl/easy-devops` is possible and `/srv` is not.
112
+ if (dir.split('/').filter(Boolean).length < 2) return false;
113
+
114
+ // Directories whose ownership is itself a root grant. `/etc/ssl` holds the
115
+ // system CA trust store; `/etc/nginx` holds nginx.conf, whose main context
116
+ // can `load_module` and set the worker `user` — only `/etc/nginx/conf.d`
117
+ // (included inside `http {}`) is safe to give away.
118
+ const forbidden = new Set([
119
+ '/etc/sudoers.d', '/etc/systemd', '/etc/ssl', '/etc/ssl/certs', '/etc/ssl/private',
120
+ '/etc/pki', '/etc/nginx', '/etc/letsencrypt', '/etc/cron.d', '/etc/init.d', '/etc/pam.d',
121
+ '/usr/bin', '/usr/sbin', '/usr/lib', '/usr/local', '/usr/local/bin', '/usr/share',
122
+ '/var/lib', '/var/log', '/var/spool', '/var/www',
123
+ ]);
124
+ return !forbidden.has(dir);
125
+ }
126
+
127
+ /**
128
+ * The directories Easy DevOps writes to at runtime on Linux.
129
+ *
130
+ * These are the ones that used to be created with `sudo mkdir` and handed over
131
+ * with `sudo chown` on every issuance. Instead they are created ONCE by the
132
+ * setup script, so no standing grant is needed for them:
133
+ *
134
+ * - the configured sslDir, where certificates and the ACME account key live
135
+ * - nginx's conf.d, where the per-domain configs are written
136
+ *
137
+ * There is deliberately no HTML webroot in this list: HTTP-01 challenges are
138
+ * never written to disk for nginx to serve. They are answered by the loopback
139
+ * listener this process starts and nginx proxies to (see the header of
140
+ * core/ssl-issuer.js and core/acme-challenge.js), so handing a webroot to the
141
+ * operator would grant ownership of a directory nothing uses.
142
+ *
143
+ * Both the dashboard and the CLI call this, so the commands they show and run
144
+ * cannot drift apart. Anything that is not a safe path for the script is
145
+ * returned in `refused` with the reason, rather than silently dropped: the
146
+ * operator has to know that directory will still need root.
147
+ *
148
+ * @param {Object} [config] Defaults to loadConfig()
149
+ * @returns {{ ownDirs: string[], refused: Array<{ dir: string, reason: string }> }}
150
+ */
151
+ export function deriveOwnDirs(config = loadConfig()) {
152
+ const nginxDir = typeof config?.nginxDir === 'string' ? config.nginxDir : '';
153
+
154
+ const candidates = [
155
+ typeof config?.sslDir === 'string' ? config.sslDir : '',
156
+ // POSIX join throughout: this derivation only ever describes a Linux
157
+ // machine, so the host platform must not influence it. nginx's Linux
158
+ // layout has no extra `conf/` level (that is the Windows layout in
159
+ // nginx-conf-generator's getConfDDir()).
160
+ nginxDir ? path.posix.join(nginxDir, 'conf.d') : '',
161
+ ];
162
+
163
+ const ownDirs = [];
164
+ const refused = [];
165
+
166
+ for (const dir of candidates) {
167
+ if (!dir) continue;
168
+
169
+ if (!isSafeSetupDir(dir)) {
170
+ refused.push({
171
+ dir,
172
+ reason: 'not an absolute, plain Linux path below a system directory, or it is a system directory itself',
173
+ });
174
+ continue;
175
+ }
176
+
177
+ if (!ownDirs.includes(dir)) ownDirs.push(dir);
178
+ }
179
+
180
+ return { ownDirs, refused };
181
+ }
182
+
183
+ /**
184
+ * The single sudoers line.
185
+ *
186
+ * `(root)` rather than `(ALL)`: these commands only ever run as root, and
187
+ * `(ALL)` would also allow them as any other account for no reason.
188
+ *
189
+ * @param {string} user
190
+ * @returns {string}
191
+ */
192
+ export function buildSudoersLine(user) {
193
+ if (!isSafeUserName(user)) {
194
+ throw new Error(`refusing to write a sudoers rule for an unsafe user name: ${JSON.stringify(user)}`);
195
+ }
196
+ return `${user} ALL=(root) NOPASSWD: ${SUDO_COMMANDS.join(', ')}`;
15
197
  }
16
198
 
17
- export async function setupLinuxPermissions() {
18
- if (process.platform === 'win32') return { success: false, reason: 'Windows not supported' };
199
+ /**
200
+ * The exact commands the operator runs once, in their own terminal.
201
+ *
202
+ * Returned as lines so the dashboard can display them and the CLI can run
203
+ * them through `runInteractive`, where sudo prompts on the real terminal.
204
+ * Nothing here is ever given a password.
205
+ *
206
+ * The rule file is validated with `visudo -cf` BEFORE it is installed. A
207
+ * syntax error in /etc/sudoers.d disables sudo for the whole machine, so an
208
+ * unvalidated install could lock the operator out of root entirely.
209
+ *
210
+ * @param {Object} opts
211
+ * @param {string} [opts.user] Defaults to the current account
212
+ * @param {string[]} [opts.ownDirs] Directories to create and hand to `user`
213
+ * once (certificate dir, nginx conf.d) so no
214
+ * runtime sudo is needed. deriveOwnDirs()
215
+ * above is the one place they are chosen.
216
+ * @returns {{ ok: true, lines: string[] } | { ok: false, reason: string }}
217
+ */
218
+ export function buildSetupScript({ user = os.userInfo().username, ownDirs = [] } = {}) {
219
+ if (!isSafeUserName(user)) {
220
+ return { ok: false, reason: `the account name ${JSON.stringify(user)} cannot be used safely in a sudoers rule` };
221
+ }
222
+
223
+ for (const dir of ownDirs) {
224
+ if (!isSafeSetupDir(dir)) {
225
+ return {
226
+ ok: false,
227
+ reason: `refusing to hand ${JSON.stringify(dir)} to ${user}: it must be an absolute, plain path below a system directory, not a system directory itself`,
228
+ };
229
+ }
230
+ }
19
231
 
20
- const user = os.userInfo().username;
232
+ // ONE chained line, through a `mktemp` file. A fixed name in /tmp would be a
233
+ // privilege escalation: another local account could replace the file between
234
+ // `visudo -cf` validating it and `sudo install` copying it, and have ITS
235
+ // content installed as root's sudoers. `mktemp` gives a random name created
236
+ // 0600 by the operator, and /tmp's sticky bit stops anyone else deleting or
237
+ // replacing it. Chaining with && means a failed validation installs nothing,
238
+ // and the file is removed either way.
239
+ const lines = [
240
+ `t="$(mktemp)" && printf '%s\\n' '${buildSudoersLine(user)}' > "$t" && sudo visudo -cf "$t" `
241
+ + `&& sudo install -o root -g root -m 0440 "$t" ${SUDOERS_PATH}; rc=$?; rm -f "$t"; test $rc -eq 0`,
242
+ ];
21
243
 
22
- let nginxPath;
23
- try {
24
- nginxPath = await findNginxPath();
25
- } catch (err) {
26
- return { success: false, reason: err.message };
244
+ for (const dir of ownDirs) {
245
+ lines.push(`sudo mkdir -p ${dir}`);
246
+ // Not recursive: only the directory itself changes hands, never anything
247
+ // that already sits inside it.
248
+ lines.push(`sudo chown ${user}:${user} ${dir}`);
27
249
  }
28
250
 
29
- // Step 1: authenticate sudo
30
- const auth = await runInteractive('sudo -v');
31
- if (!auth.success) return { success: false, reason: 'sudo authentication failed' };
251
+ return { ok: true, lines };
252
+ }
253
+
254
+ /**
255
+ * Whether the rule is installed and works.
256
+ *
257
+ * `systemctl status` exits non-zero for an inactive unit even when sudo let
258
+ * it run, so the signal is whether sudo itself refused (it says "password").
259
+ *
260
+ * @returns {Promise<boolean>}
261
+ */
262
+ export async function checkPermissionsConfigured() {
263
+ if (isWindows) return true;
264
+ const result = await run(`${sudoCommand('/usr/bin/systemctl status nginx')} 2>/dev/null`);
265
+ return result.success || !String(result.stderr ?? '').includes('password');
266
+ }
267
+
268
+ /**
269
+ * CLI only: runs the setup script in the operator's terminal.
270
+ *
271
+ * Each line goes through `runInteractive`, so sudo asks for the password on
272
+ * the real TTY. It stops at the first failure — in particular, if
273
+ * `visudo -cf` rejects the file, nothing is installed.
274
+ *
275
+ * @param {Object} [opts]
276
+ * @param {string[]} [opts.ownDirs]
277
+ * @returns {Promise<{ success: boolean, reason?: string, failedAt?: string }>}
278
+ */
279
+ export async function setupLinuxPermissions({ ownDirs = [] } = {}) {
280
+ if (isWindows) return { success: false, reason: 'sudo rules are a Linux concept; nothing to set up on Windows' };
281
+
282
+ const script = buildSetupScript({ ownDirs });
283
+ if (!script.ok) return { success: false, reason: script.reason };
32
284
 
33
- // Step 2: create required directories and set ownership
34
- const dirs = ['/etc/easy-devops', '/var/log/easy-devops'];
35
- for (const dir of dirs) {
36
- const mkResult = await runInteractive(`sudo mkdir -p ${dir}`);
37
- if (mkResult.success) {
38
- await runInteractive(`sudo chown ${user}:${user} ${dir}`);
285
+ for (const line of script.lines) {
286
+ const result = await runInteractive(line);
287
+ if (!result.success) {
288
+ return { success: false, reason: `stopped at: ${line}`, failedAt: line };
39
289
  }
40
290
  }
41
291
 
42
- // Step 3: fix nginx conf.d ownership
43
- await runInteractive(`sudo chown -R ${user}:${user} /etc/nginx/conf.d 2>/dev/null || true`);
44
-
45
- // Step 4: write sudoers file
46
- // Exactly the commands Easy DevOps runs, and nothing more.
47
- //
48
- // A bare '/usr/bin/systemctl' used to be granted here, which allowed every
49
- // systemctl verb against every unit — far beyond what this tool needs, and
50
- // enough to disable or mask unrelated services. certbot is also gone: SSL is
51
- // issued in-process with acme-client and no binary is ever invoked.
52
- const SUDO_RULES = [
53
- '/usr/bin/systemctl start nginx',
54
- '/usr/bin/systemctl stop nginx',
55
- '/usr/bin/systemctl reload nginx',
56
- '/usr/bin/systemctl restart nginx',
57
- '/usr/bin/systemctl is-active nginx',
58
- '/usr/bin/systemctl status nginx',
59
- `${nginxPath}`,
60
- `${nginxPath} -t`,
61
- `${nginxPath} -s reload`,
62
- `${nginxPath} -s stop`,
63
- `${nginxPath} -s quit`,
64
- '/usr/bin/mkdir',
65
- '/usr/bin/chown',
66
- '/usr/bin/tee',
67
- ].join(', ');
68
-
69
- const sudoersContent = `${user} ALL=(ALL) NOPASSWD: ${SUDO_RULES}`;
70
- const result = await runInteractive(
71
- `echo '${sudoersContent}' | sudo tee /etc/sudoers.d/easy-devops > /dev/null && sudo chmod 440 /etc/sudoers.d/easy-devops`
72
- );
73
-
74
- return { success: result.success };
292
+ return { success: true };
75
293
  }
@@ -5,8 +5,9 @@
5
5
  * Used by CLI managers, dashboard routes, and dashboard lib.
6
6
  * Centralises the isWindows guard, the persistent data directory, and nginx
7
7
  * shell invocations so they are defined exactly once and behave identically
8
- * everywhere. This module imports nothing from the project, so it is safe to
9
- * load before the database is initialised.
8
+ * everywhere. It reaches nothing that touches the database — the one project
9
+ * import is core/shell.js, which only spawns when it is called — so it is safe
10
+ * to load before the database is initialised.
10
11
  */
11
12
 
12
13
  import fs from 'fs';
@@ -14,6 +15,8 @@ import path from 'path';
14
15
  import os from 'os';
15
16
  import { createHash } from 'crypto';
16
17
 
18
+ import { run as runShell } from './shell.js';
19
+
17
20
  export const isWindows = process.platform === 'win32';
18
21
 
19
22
  /** Env var that redirects every persistent artifact to a chosen directory. */
@@ -362,6 +365,49 @@ export function nginxLogPath(nginxDir, which = 'error') {
362
365
  */
363
366
  export const platformName = process.platform;
364
367
 
368
+ /**
369
+ * The full command line of a running process, or null when it cannot be read.
370
+ *
371
+ * Exists for one reason: a pid recorded on disk (`dashboard-pid`) may belong
372
+ * to a completely unrelated process by the time someone acts on it, because
373
+ * the OS reuses pids. Before signalling such a pid, the caller must be able to
374
+ * ask what that process actually is — and that question differs by platform,
375
+ * which is why it lives here and nowhere else:
376
+ *
377
+ * - Linux: `/proc/<pid>/cmdline` is NUL-separated argv. Read directly, with
378
+ * no subprocess at all, so this works in a context with no shell.
379
+ * - Windows: there is no such file, so `Get-CimInstance` is asked through
380
+ * core/shell.js like every other command.
381
+ *
382
+ * The result is a display string, not a parsed argv: callers only ever look
383
+ * for a path inside it. A process that has exited, a pid that never existed,
384
+ * and a machine that denies access all answer null — "I could not check" —
385
+ * which callers must treat as "not verified".
386
+ *
387
+ * @param {number} pid
388
+ * @returns {Promise<string|null>}
389
+ */
390
+ export async function readProcessCommandLine(pid) {
391
+ // Never interpolate an unvalidated value into a shell command.
392
+ if (!Number.isInteger(pid) || pid <= 0) return null;
393
+
394
+ if (isWindows) {
395
+ const query = `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CommandLine`;
396
+ const result = await runShell(query);
397
+ if (!result.success) return null;
398
+ const text = String(result.stdout ?? '').trim();
399
+ return text || null;
400
+ }
401
+
402
+ try {
403
+ const raw = await fs.promises.readFile(`/proc/${pid}/cmdline`);
404
+ const text = raw.toString('utf8').split('\0').filter(Boolean).join(' ').trim();
405
+ return text || null;
406
+ } catch {
407
+ return null;
408
+ }
409
+ }
410
+
365
411
  /**
366
412
  * Returns the nginx binary invocation string suitable for use in shell commands.
367
413
  * On Windows returns `& "path\nginx.exe"` (PowerShell call operator + quoted path).