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
@@ -43,6 +43,24 @@ export const STALE_AFTER_MS = 20_000;
43
43
  /** Lock file name inside the data directory. */
44
44
  const LOCK_FILE = 'daemon.lock';
45
45
 
46
+ /**
47
+ * How long a recovery guard left by a crashed process must sit before another
48
+ * process may clear it. Long enough that a slow (but live) recovery is never
49
+ * cleared out from under itself, short enough that a crash does not need a
50
+ * reboot to recover from.
51
+ */
52
+ const RECOVERY_GUARD_STALE_MS = 30_000;
53
+
54
+ /**
55
+ * How long an empty, unreadable lock file may exist before another process may
56
+ * treat it as abandoned.
57
+ *
58
+ * Creating a lock is `writeFileSync(path, data, { flag: 'wx' })`, which creates
59
+ * the file and THEN writes it — so a brand-new lock is briefly empty. A reader
60
+ * in that window must not "recover" a lock created microseconds earlier.
61
+ */
62
+ const UNREADABLE_GRACE_MS = 2_000;
63
+
46
64
  /** @returns {string} Absolute path to the lock file. */
47
65
  export function lockPath(dataDir = getDataDir()) {
48
66
  return path.join(dataDir, LOCK_FILE);
@@ -69,12 +87,14 @@ export function isPidAlive(pid) {
69
87
  }
70
88
 
71
89
  /**
72
- * Reads the lock without judging it.
90
+ * Reads a lock file without judging it.
91
+ *
92
+ * @param {string} file Absolute path to the lock file
73
93
  * @returns {{ pid: number, startedAt: number, heartbeatAt: number, version: string|null, mode: string|null }|null}
74
94
  */
75
- export function readLock(dataDir = getDataDir()) {
95
+ function readLockAt(file) {
76
96
  try {
77
- const raw = fs.readFileSync(lockPath(dataDir), 'utf8');
97
+ const raw = fs.readFileSync(file, 'utf8');
78
98
  const parsed = JSON.parse(raw);
79
99
  if (!Number.isInteger(parsed?.pid)) return null;
80
100
  return {
@@ -92,6 +112,35 @@ export function readLock(dataDir = getDataDir()) {
92
112
  }
93
113
  }
94
114
 
115
+ /**
116
+ * True when an unreadable lock file is a create that has not been written yet.
117
+ *
118
+ * An empty file younger than the grace is somebody's `wx` create in flight, so
119
+ * it counts as LIVE. An empty file older than the grace is a crash between the
120
+ * create and the write, and may be recovered. A file that has content but does
121
+ * not parse is a truncated write, which has no live owner at all.
122
+ *
123
+ * @param {string} file
124
+ * @param {number} now
125
+ * @returns {boolean}
126
+ */
127
+ function isWriteInFlight(file, now) {
128
+ try {
129
+ const stat = fs.statSync(file);
130
+ return stat.size === 0 && now - stat.mtimeMs < UNREADABLE_GRACE_MS;
131
+ } catch {
132
+ return false;
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Reads the lock in a data directory without judging it.
138
+ * @returns {{ pid: number, startedAt: number, heartbeatAt: number, version: string|null, mode: string|null }|null}
139
+ */
140
+ export function readLock(dataDir = getDataDir()) {
141
+ return readLockAt(lockPath(dataDir));
142
+ }
143
+
95
144
  /**
96
145
  * The state of the daemon as far as anyone else can tell.
97
146
  *
@@ -137,10 +186,38 @@ export function isDaemonRunning(opts = {}) {
137
186
  /**
138
187
  * Takes the lock for this process.
139
188
  *
140
- * Recovers an abandoned lock, refuses a live one. The write is atomic — a
141
- * temporary file renamed into place — so a reader can never see a half-written
142
- * lock, and `wx` on the temp name means two daemons racing cannot both believe
143
- * they created it.
189
+ * Refuses a live lock, recovers an abandoned one. Creating a lock is a single
190
+ * EXCLUSIVE open (`wx`), so two daemons can never both believe they created
191
+ * it, and there is no check-then-write window.
192
+ *
193
+ * Recovering a STALE lock is the subtle half. Deciding from `inspect()` before
194
+ * the race is not enough: several processes see the same dead lock, all are
195
+ * entitled to recover it, and if each one deletes "the stale file" it saw, the
196
+ * second deletes the FIRST ONE'S BRAND-NEW LOCK. Both report success and one of
197
+ * them owns nothing.
198
+ *
199
+ * Moving the file aside first does not fix that either: the path is empty for
200
+ * as long as it takes to judge and re-create, and on a machine with real-time
201
+ * scanning that can be milliseconds — long enough for another process to create
202
+ * there. Measured with six contenders, that produced two winners.
203
+ *
204
+ * So recovery is serialised and the lock is only ever REPLACED, never removed:
205
+ *
206
+ * 1. exactly one process can create `daemon.lock.recovery` (`wx`), which is
207
+ * the permission to recover; everyone else is refused;
208
+ * 2. inside that guard the lock is re-read — that read is authoritative,
209
+ * because no other process may touch it — and a live lock is refused;
210
+ * 3. a dead one is replaced by an atomic `rename` of a prepared candidate
211
+ * over it. The path is never empty, so there is nothing for a third
212
+ * process to slip into.
213
+ *
214
+ * The guard is removed in a `finally`. One left behind by a crash is only
215
+ * cleared when its pid is gone and it has been sitting long enough, so it can
216
+ * never be cleared out from under a live recovery.
217
+ *
218
+ * Re-acquiring as the same pid stays idempotent, and rewriting one's own lock
219
+ * (heartbeat) still goes through the atomic temp-file rename: only the owner
220
+ * does that, so a reader always sees either the old lock or the new one.
144
221
  *
145
222
  * @param {Object} [opts]
146
223
  * @param {string} [opts.dataDir]
@@ -167,7 +244,192 @@ export function acquire({
167
244
  return { ok: false, reason: state.reason, lock: state.lock };
168
245
  }
169
246
 
170
- return { ok: true, recovered: state.stale, lock: write({ dataDir, version, mode, now }) };
247
+ const payload = { pid: process.pid, startedAt: now, heartbeatAt: now, version, mode };
248
+
249
+ const first = createExclusive(dataDir, payload);
250
+ if (first.ok) return { ok: true, recovered: state.stale, lock: payload };
251
+
252
+ if (first.code !== 'EEXIST') {
253
+ return { ok: false, reason: `could not create the lock: ${first.message}`, lock: null };
254
+ }
255
+
256
+ // A lock file appeared after inspect() saw none. If it is a readable lock, it
257
+ // is somebody's and nothing here is recoverable. A file that exists but
258
+ // cannot be read (truncated by a crash) has no owner to respect, so it falls
259
+ // through to the guard below, which replaces it rather than blocking for ever.
260
+ if (!state.lock && !fs.existsSync(lockPath(dataDir))) {
261
+ return { ok: false, reason: 'another process created the lock first', lock: readLock(dataDir) };
262
+ }
263
+
264
+ // Empty and just created: that is a `wx` create whose write has not landed
265
+ // yet. Reading it in that window is not permission to take it over.
266
+ if (!state.lock && isWriteInFlight(lockPath(dataDir), now)) {
267
+ return { ok: false, reason: 'another process is writing its lock', lock: readLock(dataDir) };
268
+ }
269
+
270
+ const guard = acquireRecoveryGuard({ dataDir, now });
271
+ if (!guard.ok) {
272
+ return { ok: false, reason: guard.reason, lock: readLock(dataDir) };
273
+ }
274
+
275
+ try {
276
+ // Authoritative: nobody else may change the lock while we hold the guard.
277
+ const current = inspect({ dataDir, now });
278
+
279
+ if (current.running) {
280
+ if (current.lock?.pid === process.pid) {
281
+ return { ok: true, recovered: false, lock: write({ dataDir, version, mode, now }) };
282
+ }
283
+ return { ok: false, reason: current.reason, lock: current.lock };
284
+ }
285
+
286
+ if (!current.lock) {
287
+ // Empty and just created is still a create in flight — treat it as live.
288
+ if (isWriteInFlight(lockPath(dataDir), now)) {
289
+ return { ok: false, reason: 'another process is writing its lock', lock: null };
290
+ }
291
+
292
+ // Nothing readable is at the path: either the file vanished (a release,
293
+ // or a crash being cleaned up) or it is truncated/half-written. A lock
294
+ // with no readable owner cannot be waited on, so it is abandoned —
295
+ // created over if it is gone, replaced under the guard if it is still
296
+ // there. Blocking here for ever is what a crash would otherwise cause.
297
+ const again = createExclusive(dataDir, payload);
298
+ if (again.ok) return { ok: true, recovered: true, lock: payload };
299
+
300
+ if (again.code !== 'EEXIST') {
301
+ return { ok: false, reason: `could not create the lock: ${again.message}`, lock: null };
302
+ }
303
+
304
+ const replaced = replaceLock({ dataDir, payload });
305
+ return replaced.ok
306
+ ? { ok: true, recovered: true, lock: payload }
307
+ : { ok: false, reason: `could not replace the unreadable lock: ${replaced.message}`, lock: null };
308
+ }
309
+
310
+ const replaced = replaceLock({ dataDir, payload });
311
+ if (!replaced.ok) {
312
+ return { ok: false, reason: `could not replace the stale lock: ${replaced.message}`, lock: readLock(dataDir) };
313
+ }
314
+
315
+ return { ok: true, recovered: true, lock: payload };
316
+ } finally {
317
+ guard.release();
318
+ }
319
+ }
320
+
321
+ /**
322
+ * Creates the recovery guard exclusively, or explains why recovery may not run.
323
+ *
324
+ * @param {Object} opts
325
+ * @param {string} opts.dataDir
326
+ * @param {number} opts.now
327
+ * @returns {{ ok: true, release: () => void } | { ok: false, reason: string }}
328
+ */
329
+ function acquireRecoveryGuard({ dataDir, now }) {
330
+ const file = `${lockPath(dataDir)}.recovery`;
331
+ const payload = { pid: process.pid, at: now };
332
+
333
+ const attempt = () => {
334
+ try {
335
+ fs.writeFileSync(file, `${JSON.stringify(payload)}\n`, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
336
+ return { ok: true };
337
+ } catch (err) {
338
+ return { ok: false, code: err?.code ?? 'UNKNOWN', message: err?.message ?? String(err) };
339
+ }
340
+ };
341
+
342
+ const release = () => {
343
+ try { fs.unlinkSync(file); } catch { /* already gone */ }
344
+ };
345
+
346
+ const first = attempt();
347
+ if (first.ok) return { ok: true, release };
348
+ if (first.code !== 'EEXIST') {
349
+ return { ok: false, reason: `could not create the recovery guard: ${first.message}` };
350
+ }
351
+
352
+ // A guard left behind by a process that died mid-recovery. It is not the
353
+ // lock itself, so it may be cleared — but only once its owner is provably
354
+ // gone and it is old enough that a slow recovery cannot be the one holding it.
355
+ let existing = null;
356
+ try {
357
+ existing = JSON.parse(fs.readFileSync(file, 'utf8'));
358
+ } catch { /* unreadable: treat it as live */ }
359
+
360
+ const abandoned = Boolean(existing)
361
+ && Number.isInteger(existing.pid)
362
+ && !isPidAlive(existing.pid)
363
+ && now - (Number(existing.at) || 0) > RECOVERY_GUARD_STALE_MS;
364
+
365
+ if (!abandoned) return { ok: false, reason: 'another process is recovering the lock' };
366
+
367
+ try { fs.unlinkSync(file); } catch { /* another process cleared it first */ }
368
+
369
+ const second = attempt();
370
+ return second.ok
371
+ ? { ok: true, release }
372
+ : { ok: false, reason: 'another process is recovering the lock' };
373
+ }
374
+
375
+ /**
376
+ * Replaces the lock file with this process's payload, atomically.
377
+ *
378
+ * A `rename` within the directory is a replace: the lock path goes from the old
379
+ * file to the new one in one step, so it is never absent and no third process
380
+ * can create there. Called only while the recovery guard is held.
381
+ *
382
+ * @param {Object} opts
383
+ * @param {string} opts.dataDir
384
+ * @param {Object} opts.payload
385
+ * @returns {{ ok: true } | { ok: false, message: string }}
386
+ */
387
+ function replaceLock({ dataDir, payload }) {
388
+ const target = lockPath(dataDir);
389
+ const candidate = `${target}.candidate-${process.pid}-${Math.random().toString(36).slice(2, 10)}`;
390
+ const body = `${JSON.stringify(payload)}\n`;
391
+
392
+ try {
393
+ fs.writeFileSync(candidate, body, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
394
+ } catch (err) {
395
+ return { ok: false, message: err?.message ?? String(err) };
396
+ }
397
+
398
+ const moved = renameWithRetry(candidate, target);
399
+ if (!moved.ok) {
400
+ try { fs.unlinkSync(candidate); } catch { /* already gone */ }
401
+ return { ok: false, message: moved.message };
402
+ }
403
+
404
+ return { ok: true };
405
+ }
406
+
407
+ /**
408
+ * `rename`, retried briefly while Windows refuses it.
409
+ *
410
+ * On Windows a file another process currently has open for reading cannot be
411
+ * replaced — the rename fails with EPERM/EBUSY until that handle closes. Every
412
+ * reader in this module reads and closes immediately, so a bounded retry is
413
+ * enough; bounded, so a genuinely stuck file can never hang an acquisition.
414
+ *
415
+ * @param {string} from
416
+ * @param {string} to
417
+ * @returns {{ ok: true } | { ok: false, message: string }}
418
+ */
419
+ function renameWithRetry(from, to, attempts = 200, waitMs = 1) {
420
+ for (let i = 0; ; i++) {
421
+ try {
422
+ fs.renameSync(from, to);
423
+ return { ok: true };
424
+ } catch (err) {
425
+ const transient = err?.code === 'EPERM' || err?.code === 'EBUSY' || err?.code === 'EACCES';
426
+ if (!transient || i >= attempts) {
427
+ return { ok: false, message: err?.message ?? String(err) };
428
+ }
429
+ // A real blocking pause: no busy spin, no async in a synchronous path.
430
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, waitMs);
431
+ }
432
+ }
171
433
  }
172
434
 
173
435
  /**
@@ -268,11 +530,36 @@ export function watchLock({ dataDir = getDataDir(), onChange, debounceMs = 50 }
268
530
  };
269
531
  }
270
532
 
533
+ /**
534
+ * Creates the lock file exclusively, or reports why it could not.
535
+ *
536
+ * `wx` is the whole guarantee: the open fails with EEXIST when the file
537
+ * exists, atomically, with no window between checking and creating. The file
538
+ * is written 0600 like the temp file it replaces.
539
+ *
540
+ * @returns {{ ok: true } | { ok: false, code: string, message: string }}
541
+ */
542
+ function createExclusive(dataDir, payload) {
543
+ try {
544
+ fs.mkdirSync(dataDir, { recursive: true });
545
+ fs.writeFileSync(lockPath(dataDir), `${JSON.stringify(payload)}\n`, {
546
+ encoding: 'utf8',
547
+ mode: 0o600,
548
+ flag: 'wx',
549
+ });
550
+ return { ok: true };
551
+ } catch (err) {
552
+ return { ok: false, code: err?.code ?? 'UNKNOWN', message: err?.message ?? String(err) };
553
+ }
554
+ }
555
+
271
556
  /**
272
557
  * Writes the lock atomically.
273
558
  *
274
559
  * `rename` is atomic on both platforms for a same-directory move, so a reader
275
- * either sees the old file or the new one — never a partial write.
560
+ * either sees the old file or the new one — never a partial write. Used only
561
+ * to refresh a lock this process already owns; taking it in the first place is
562
+ * createExclusive() above.
276
563
  */
277
564
  function write({ dataDir, version, mode, now, startedAt }) {
278
565
  const payload = {
@@ -23,17 +23,23 @@ import path from 'path';
23
23
  import { fileURLToPath } from 'url';
24
24
  import { loadConfig } from './config.js';
25
25
  import { dbGet, dbSet } from './db.js';
26
- import { getDataDir } from './platform.js';
26
+ import { getDataDir, isWindows, readProcessCommandLine } from './platform.js';
27
27
  import { run } from './shell.js';
28
28
 
29
29
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
30
- const isWindows = process.platform === 'win32';
31
30
 
32
31
  // Principle IV: logs live in the user's data directory, never inside the
33
32
  // package — a package-relative path is wiped by `npm update`. Follows
34
33
  // EASY_DEVOPS_DATA_DIR in dev mode like the database and sessions do.
35
34
  export const DASHBOARD_LOG_PATH = path.join(getDataDir(), 'logs', 'dashboard.log');
36
- const SERVER_PATH = path.resolve(__dirname, '..', 'dashboard', 'server.js');
35
+ /**
36
+ * The entry script of the dashboard, exactly as startDashboard() spawns it.
37
+ *
38
+ * Exported and used by stopDashboard(): "our" dashboard is identified by this
39
+ * path in its command line, so an unrelated process that inherited a recorded
40
+ * pid is never signalled.
41
+ */
42
+ export const DASHBOARD_ENTRY_SCRIPT = path.resolve(__dirname, '..', 'dashboard', 'server.js');
37
43
 
38
44
  // ─── Port helpers ─────────────────────────────────────────────────────────────
39
45
 
@@ -126,7 +132,7 @@ export async function startDashboard(port, { env = {} } = {}) {
126
132
  const logFd = openSync(DASHBOARD_LOG_PATH, 'a');
127
133
  writeSync(logFd, `\n--- dashboard start ${new Date().toISOString()} port=${port} ---\n`);
128
134
 
129
- const child = spawn(process.execPath, [SERVER_PATH], {
135
+ const child = spawn(process.execPath, [DASHBOARD_ENTRY_SCRIPT], {
130
136
  detached: true,
131
137
  stdio: ['ignore', logFd, logFd],
132
138
  windowsHide: true,
@@ -143,8 +149,130 @@ export async function startDashboard(port, { env = {} } = {}) {
143
149
  return { success: up, pid: child.pid, port, logPath: DASHBOARD_LOG_PATH };
144
150
  }
145
151
 
146
- export async function stopDashboard(pid) {
147
- if (!pid) return { success: false };
152
+ /**
153
+ * Splits a command line into argv, honouring double quotes.
154
+ *
155
+ * Enough for what the platform reports for one of our own dashboards — a
156
+ * quoted executable path, a script path, maybe an interpreter option — without
157
+ * pretending to be a general Windows command-line parser.
158
+ *
159
+ * @param {string} commandLine
160
+ * @returns {string[]}
161
+ */
162
+ function splitCommandLine(commandLine) {
163
+ const args = [];
164
+ let current = '';
165
+ let quoted = false;
166
+ let started = false;
167
+
168
+ for (const ch of commandLine) {
169
+ if (ch === '"') {
170
+ quoted = !quoted;
171
+ started = true;
172
+ continue;
173
+ }
174
+
175
+ if (!quoted && /\s/.test(ch)) {
176
+ if (started) {
177
+ args.push(current);
178
+ current = '';
179
+ started = false;
180
+ }
181
+ continue;
182
+ }
183
+
184
+ current += ch;
185
+ started = true;
186
+ }
187
+
188
+ if (started) args.push(current);
189
+ return args;
190
+ }
191
+
192
+ /** A path in comparable form: forward slashes, and case-folded on Windows. */
193
+ function normalizePath(value) {
194
+ const forward = String(value).replace(/\\/g, '/');
195
+ return isWindows ? forward.toLowerCase() : forward;
196
+ }
197
+
198
+ /**
199
+ * True when a process command line IS `node <dashboard entry script>`.
200
+ *
201
+ * Parsed, not substring-matched: a pid can be reused by an editor with
202
+ * server.js open, a grep, or a test runner that merely mentions the path, and
203
+ * killing one of those would be killing a stranger's process. The executable
204
+ * must be node, and the first non-option argument after it must be exactly the
205
+ * entry script — `node other.js <script>` is not our dashboard either.
206
+ *
207
+ * Exported so the stop path can be tested against those shapes directly.
208
+ *
209
+ * @param {string|null} commandLine
210
+ * @returns {boolean}
211
+ */
212
+ export function isDashboardCommandLine(commandLine) {
213
+ if (typeof commandLine !== 'string' || commandLine.trim() === '') return false;
214
+
215
+ const argv = splitCommandLine(commandLine);
216
+ if (argv.length < 2) return false;
217
+
218
+ const exe = path.basename(argv[0]).toLowerCase();
219
+ if (exe !== 'node' && exe !== 'node.exe') return false;
220
+
221
+ const entry = normalizePath(DASHBOARD_ENTRY_SCRIPT);
222
+
223
+ for (const arg of argv.slice(1)) {
224
+ // Interpreter options come before the script; the script is the first
225
+ // argument that is not one.
226
+ if (arg.startsWith('-')) continue;
227
+ return normalizePath(arg) === entry;
228
+ }
229
+
230
+ return false;
231
+ }
232
+
233
+ /**
234
+ * Stops the dashboard recorded at `pid`, but only if that pid still belongs to
235
+ * it.
236
+ *
237
+ * A pid read back from the settings table is not proof of anything: the
238
+ * dashboard may have exited and the OS handed the same number to an unrelated
239
+ * process. Killing that would be killing a stranger's work, so the recorded
240
+ * value is verified against the process's command line first. Anything we
241
+ * cannot verify — no pid, a pid that is gone, a command line we may not read,
242
+ * a line that is not `node <entry script>` — is NOT killed; the stale record
243
+ * is cleared and the caller is told why.
244
+ *
245
+ * @param {number} pid
246
+ * @param {Object} [deps]
247
+ * @param {(pid: number) => Promise<string|null>} [deps.readCommandLine]
248
+ * Injectable for tests; defaults to platform.readProcessCommandLine()
249
+ * @returns {Promise<{ success: boolean, reason?: string }>}
250
+ */
251
+ export async function stopDashboard(pid, deps = {}) {
252
+ const readCommandLine = deps.readCommandLine ?? readProcessCommandLine;
253
+
254
+ if (!Number.isInteger(pid) || pid <= 0) {
255
+ return { success: false, reason: 'no valid dashboard pid was recorded' };
256
+ }
257
+
258
+ let commandLine = null;
259
+ try {
260
+ commandLine = await readCommandLine(pid);
261
+ } catch {
262
+ commandLine = null;
263
+ }
264
+
265
+ if (!isDashboardCommandLine(commandLine)) {
266
+ // Clear the record either way: whatever was stored is not a dashboard we
267
+ // may stop, so keeping it would make every later action repeat this check.
268
+ dbSet('dashboard-pid', null);
269
+ dbSet('dashboard-port', null);
270
+ return {
271
+ success: false,
272
+ reason: `pid ${pid} no longer belongs to the Easy DevOps dashboard; the stale record was cleared`,
273
+ };
274
+ }
275
+
148
276
  try {
149
277
  if (isWindows) {
150
278
  await run(`taskkill /PID ${pid} /F`);