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,488 @@
1
+ /**
2
+ * core/runner.js
3
+ *
4
+ * The one PM2 wrapper. Everything that talks to PM2 — the CLI `service`
5
+ * commands, the dashboard's Processes page, the hub agent's reporting — goes
6
+ * through here.
7
+ *
8
+ * Why PM2 at all: Easy DevOps deliberately does not implement its own daemon.
9
+ * PM2 already solves keeping a process alive, restarting it after a crash and
10
+ * bringing it back after a reboot, on both platforms this project supports.
11
+ * Easy DevOps' job is to manage PM2 on the user's behalf, never to reinvent it.
12
+ *
13
+ * Rules this module keeps:
14
+ * - Every subprocess call goes through core/shell.js.
15
+ * - Every OS difference comes from core/platform.js.
16
+ * - PM2 is NEVER installed silently. install() exists, but the decision to
17
+ * call it belongs to the CLI or the dashboard, which must ask first.
18
+ * - `run` is injectable on every function so tests can assert the exact
19
+ * command without executing it.
20
+ */
21
+
22
+ import fs from 'fs';
23
+ import os from 'os';
24
+ import path from 'path';
25
+ import { run as defaultRun } from './shell.js';
26
+ import { quoteExe, pm2StartupCmd, pm2UnstartupCmd, isWindows } from './platform.js';
27
+
28
+ /** PM2 can be slow to answer while the daemon is starting up. */
29
+ const PM2_TIMEOUT_MS = 60_000;
30
+ /** `npm install -g pm2` pulls a lot of packages. */
31
+ const INSTALL_TIMEOUT_MS = 300_000;
32
+
33
+ /**
34
+ * Name PM2 knows the dashboard by.
35
+ *
36
+ * Dev mode gets its own app so a developer's instance can never be mistaken
37
+ * for — or stop — the real one. The suffix follows the data directory, which
38
+ * is the thing that actually differs.
39
+ *
40
+ * @param {boolean} dev
41
+ * @returns {string}
42
+ */
43
+ export function appName(dev) {
44
+ return dev ? 'ez-dashboard-dev' : 'ez-dashboard';
45
+ }
46
+
47
+ /** Both names, so callers can recognise anything Easy DevOps created. */
48
+ export const EZ_APP_NAMES = Object.freeze(['ez-dashboard', 'ez-dashboard-dev']);
49
+
50
+ /** @returns {boolean} True when PM2 knows this app name as one of ours. */
51
+ export function isEzApp(name) {
52
+ return EZ_APP_NAMES.includes(String(name ?? ''));
53
+ }
54
+
55
+ /**
56
+ * Locates the pm2 executable and its version.
57
+ *
58
+ * Resolution is deliberately a plain `pm2 --version`: PM2 is installed
59
+ * globally by npm, so it is on PATH exactly when it is usable, and asking the
60
+ * shell avoids guessing at npm's global prefix layout per platform.
61
+ *
62
+ * `pm2 --version` has a side effect worth knowing about: it STARTS the PM2
63
+ * daemon if it is not already running. Pass `probeVersion: false` to skip it
64
+ * when you only need to know whether PM2 exists — a status read must not
65
+ * spawn a daemon on a machine that does not use PM2.
66
+ *
67
+ * @param {{ run?: Function, probeVersion?: boolean }} [deps]
68
+ * @returns {Promise<{ installed: boolean, version: string|null, path: string|null, error: string|null }>}
69
+ */
70
+ export async function detect({ run = defaultRun, probeVersion = true } = {}) {
71
+ const which = isWindows ? 'where.exe pm2' : 'command -v pm2';
72
+ const located = await run(which, { timeout: 15_000 });
73
+
74
+ if (!located.success || !located.stdout.trim()) {
75
+ return { installed: false, version: null, path: null, error: null };
76
+ }
77
+
78
+ const candidates = located.stdout.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
79
+ const exePath = pickExecutable(candidates);
80
+
81
+ if (!probeVersion) {
82
+ return { installed: true, version: null, path: exePath, error: null };
83
+ }
84
+
85
+ const ver = await run(`${quoteExe(exePath)} --version`, { timeout: 30_000 });
86
+ // PM2 prints the daemonisation notice before the version, so take the last
87
+ // line that looks like a version rather than the whole output.
88
+ const version = (ver.stdout.match(/\d+\.\d+\.\d+/g) ?? []).pop() ?? null;
89
+
90
+ return {
91
+ installed: true,
92
+ version,
93
+ path: exePath,
94
+ error: version ? null : (ver.stderr || 'Could not read the PM2 version'),
95
+ };
96
+ }
97
+
98
+ /**
99
+ * Chooses the entry that this OS can actually execute.
100
+ *
101
+ * npm's global bin directory holds BOTH a Unix shell script with no extension
102
+ * and a Windows `.cmd` shim, and `where.exe pm2` lists the extensionless one
103
+ * first. Running that on Windows fails silently-ish — the command returns
104
+ * nothing useful — which showed up as "PM2 installed, version null" and an
105
+ * unparseable process list. Prefer an extension Windows knows how to run.
106
+ *
107
+ * @param {string[]} candidates
108
+ * @returns {string|null}
109
+ */
110
+ export function pickExecutable(candidates) {
111
+ if (!Array.isArray(candidates) || candidates.length === 0) return null;
112
+ if (!isWindows) return candidates[0];
113
+
114
+ const runnable = ['.cmd', '.bat', '.exe'];
115
+ const match = candidates.find((c) => runnable.includes(c.slice(c.lastIndexOf('.')).toLowerCase()));
116
+ return match ?? candidates[0];
117
+ }
118
+
119
+ /**
120
+ * Installs PM2 globally.
121
+ *
122
+ * The caller MUST have asked the user first — see the module header.
123
+ *
124
+ * @param {{ run?: Function }} [deps]
125
+ * @returns {Promise<{ ok: boolean, output: string }>}
126
+ */
127
+ export async function install({ run = defaultRun } = {}) {
128
+ const r = await run('npm install -g pm2', { timeout: INSTALL_TIMEOUT_MS });
129
+ return { ok: r.success, output: combine(r) };
130
+ }
131
+
132
+ /**
133
+ * Installs the pm2-logrotate module, so PM2's logs cannot grow without bound.
134
+ *
135
+ * A PM2 module, not an npm dependency of this project: it is installed into
136
+ * the user's PM2, exactly like PM2 itself.
137
+ *
138
+ * @param {{ run?: Function, pm2Path?: string }} [deps]
139
+ * @returns {Promise<{ ok: boolean, output: string }>}
140
+ */
141
+ export async function installLogrotate({ run = defaultRun, pm2Path = 'pm2' } = {}) {
142
+ const r = await run(`${quoteExe(pm2Path)} install pm2-logrotate`, { timeout: INSTALL_TIMEOUT_MS });
143
+ return { ok: r.success, output: combine(r) };
144
+ }
145
+
146
+ /**
147
+ * True when pm2-logrotate is present.
148
+ * @param {{ run?: Function, pm2Path?: string }} [deps]
149
+ * @returns {Promise<boolean>}
150
+ */
151
+ export async function hasLogrotate({ run = defaultRun, pm2Path = 'pm2' } = {}) {
152
+ const r = await run(`${quoteExe(pm2Path)} ls`, { timeout: PM2_TIMEOUT_MS });
153
+ return /pm2-logrotate/.test(combine(r));
154
+ }
155
+
156
+ /**
157
+ * Lists PM2 apps.
158
+ *
159
+ * `pm2 jlist` prints JSON on stdout, but PM2 also writes its daemonisation
160
+ * notices there, so the JSON array has to be extracted rather than parsed
161
+ * from the whole buffer.
162
+ *
163
+ * @param {{ run?: Function, pm2Path?: string }} [deps]
164
+ * @returns {Promise<{ ok: boolean, apps: Array<Object>, error: string|null }>}
165
+ */
166
+ export async function list({ run = defaultRun, pm2Path = 'pm2' } = {}) {
167
+ const r = await run(`${quoteExe(pm2Path)} jlist`, { timeout: PM2_TIMEOUT_MS });
168
+
169
+ const raw = extractJsonArray(r.stdout);
170
+ if (raw === null) {
171
+ return { ok: false, apps: [], error: combine(r) || 'PM2 returned no process list' };
172
+ }
173
+
174
+ let parsed;
175
+ try {
176
+ parsed = JSON.parse(raw);
177
+ } catch (err) {
178
+ return { ok: false, apps: [], error: `Could not parse the PM2 process list: ${err.message}` };
179
+ }
180
+
181
+ if (!Array.isArray(parsed)) {
182
+ return { ok: false, apps: [], error: 'PM2 process list was not an array' };
183
+ }
184
+
185
+ return { ok: true, apps: parsed.map(normalizeApp), error: null };
186
+ }
187
+
188
+ /**
189
+ * Reduces a `pm2 jlist` entry to the fields the UI needs.
190
+ *
191
+ * Shapes the numbers here rather than in each consumer: PM2 reports memory in
192
+ * bytes and uptime as an epoch milliseconds *start* time, which is easy to
193
+ * misread as a duration.
194
+ *
195
+ * @param {Object} app One entry from `pm2 jlist`
196
+ */
197
+ export function normalizeApp(app) {
198
+ const env = app?.pm2_env ?? {};
199
+ const startedAt = typeof env.pm_uptime === 'number' ? env.pm_uptime : null;
200
+
201
+ return {
202
+ name: app?.name ?? '(unnamed)',
203
+ pmId: typeof app?.pm_id === 'number' ? app.pm_id : null,
204
+ pid: typeof app?.pid === 'number' && app.pid > 0 ? app.pid : null,
205
+ status: env.status ?? 'unknown',
206
+ cpu: typeof app?.monit?.cpu === 'number' ? app.monit.cpu : null,
207
+ memoryBytes: typeof app?.monit?.memory === 'number' ? app.monit.memory : null,
208
+ startedAt,
209
+ uptimeMs: startedAt && env.status === 'online' ? Math.max(0, Date.now() - startedAt) : null,
210
+ restarts: typeof env.restart_time === 'number' ? env.restart_time : 0,
211
+ unstableRestarts: typeof env.unstable_restarts === 'number' ? env.unstable_restarts : 0,
212
+ execPath: env.pm_exec_path ?? null,
213
+ cwd: env.pm_cwd ?? null,
214
+ user: env.username ?? null,
215
+ /** True for the apps Easy DevOps created, which the UI may act on freely. */
216
+ managed: isEzApp(app?.name),
217
+ /** The data directory this app was started with, when it carries one. */
218
+ dataDir: env.env?.EASY_DEVOPS_DATA_DIR ?? env.EASY_DEVOPS_DATA_DIR ?? null,
219
+ };
220
+ }
221
+
222
+ /**
223
+ * Starts a script as a named PM2 app.
224
+ *
225
+ * Arguments for the script go after `--`, which is how PM2 separates its own
226
+ * options from the child's. The script path is passed explicitly rather than
227
+ * relying on the `ezz` shim being on PATH: on Windows that shim is a .cmd,
228
+ * which PM2 cannot run as a Node script.
229
+ *
230
+ * @param {Object} opts
231
+ * @param {string} opts.script Absolute path to the script
232
+ * @param {string} opts.name PM2 app name
233
+ * @param {string[]} [opts.args] Arguments passed to the script
234
+ * @param {string} [opts.cwd] Working directory
235
+ * @param {Function} [opts.run]
236
+ * @param {string} [opts.pm2Path]
237
+ * @returns {Promise<{ ok: boolean, output: string }>}
238
+ */
239
+ export async function start({ script, name, args = [], cwd, run = defaultRun, pm2Path = 'pm2' }) {
240
+ const parts = [`${quoteExe(pm2Path)} start "${script}"`, `--name "${name}"`];
241
+ if (args.length > 0) parts.push('--', ...args);
242
+
243
+ const r = await run(parts.join(' '), { timeout: PM2_TIMEOUT_MS, ...(cwd ? { cwd } : {}) });
244
+ return { ok: r.success, output: combine(r) };
245
+ }
246
+
247
+ /**
248
+ * Starts the app(s) described by a PM2 config file.
249
+ *
250
+ * This is how a deployed project is started (core/deploy/engine.js): a config
251
+ * file carries the working directory, the arguments and the environment, none
252
+ * of which survive being squeezed onto a command line on both platforms. PM2
253
+ * recognises the file as a config by its `.json` extension.
254
+ *
255
+ * @param {string} file Absolute path to the config file
256
+ * @param {{ run?: Function, pm2Path?: string }} [deps]
257
+ * @returns {Promise<{ ok: boolean, output: string }>}
258
+ */
259
+ export async function startConfig(file, { run = defaultRun, pm2Path = 'pm2' } = {}) {
260
+ const r = await run(`${quoteExe(pm2Path)} start "${file}"`, { timeout: PM2_TIMEOUT_MS });
261
+ return { ok: r.success, output: combine(r) };
262
+ }
263
+
264
+ /** @returns {Promise<{ ok: boolean, output: string }>} */
265
+ export async function stop(name, { run = defaultRun, pm2Path = 'pm2' } = {}) {
266
+ return simple('stop', name, run, pm2Path);
267
+ }
268
+
269
+ /** @returns {Promise<{ ok: boolean, output: string }>} */
270
+ export async function restart(name, { run = defaultRun, pm2Path = 'pm2' } = {}) {
271
+ return simple('restart', name, run, pm2Path);
272
+ }
273
+
274
+ /**
275
+ * Graceful reload (zero-downtime for apps in cluster mode).
276
+ * @returns {Promise<{ ok: boolean, output: string }>}
277
+ */
278
+ export async function reload(name, { run = defaultRun, pm2Path = 'pm2' } = {}) {
279
+ return simple('reload', name, run, pm2Path);
280
+ }
281
+
282
+ /** Removes the app from PM2 entirely. @returns {Promise<{ ok: boolean, output: string }>} */
283
+ export async function del(name, { run = defaultRun, pm2Path = 'pm2' } = {}) {
284
+ return simple('delete', name, run, pm2Path);
285
+ }
286
+
287
+ /**
288
+ * Reads recent log lines for an app.
289
+ *
290
+ * `--nostream` is what makes this return instead of tailing forever.
291
+ *
292
+ * @param {string} name
293
+ * @param {{ lines?: number, run?: Function, pm2Path?: string }} [opts]
294
+ * @returns {Promise<{ ok: boolean, lines: string[], output: string }>}
295
+ */
296
+ export async function logs(name, { lines = 200, run = defaultRun, pm2Path = 'pm2' } = {}) {
297
+ const n = Math.max(1, Math.min(5000, Number(lines) || 200));
298
+ const r = await run(`${quoteExe(pm2Path)} logs "${name}" --lines ${n} --nostream`, {
299
+ timeout: PM2_TIMEOUT_MS,
300
+ });
301
+ const text = combine(r);
302
+ return { ok: r.success, lines: text ? text.split(/\r?\n/) : [], output: text };
303
+ }
304
+
305
+ /**
306
+ * Saves the current process list, so `pm2 resurrect` can restore it.
307
+ * This is what makes a reboot bring the dashboard back.
308
+ * @returns {Promise<{ ok: boolean, output: string }>}
309
+ */
310
+ export async function save({ run = defaultRun, pm2Path = 'pm2' } = {}) {
311
+ const r = await run(`${quoteExe(pm2Path)} save`, { timeout: PM2_TIMEOUT_MS });
312
+ return { ok: r.success, output: combine(r) };
313
+ }
314
+
315
+ /**
316
+ * Asks PM2 for its init-system startup hook.
317
+ *
318
+ * Linux and macOS only. PM2 has no Windows support here and exits non-zero,
319
+ * which is why Windows gets its own two mechanisms — see core/service.js.
320
+ *
321
+ * PM2 does not install the hook itself when it needs root: it prints a command
322
+ * for the user to run under sudo. That command is returned verbatim rather
323
+ * than executed, so Easy DevOps never needs broad sudoers rules.
324
+ *
325
+ * @param {{ run?: Function, pm2Path?: string }} [deps]
326
+ * @returns {Promise<{ ok: boolean, sudoCommand: string|null, output: string }>}
327
+ */
328
+ export async function startup({ run = defaultRun, pm2Path = 'pm2' } = {}) {
329
+ const r = await run(pm2StartupCmd(pm2Path), { timeout: PM2_TIMEOUT_MS });
330
+ const output = combine(r);
331
+ return { ok: r.success, sudoCommand: parseSudoCommand(output), output };
332
+ }
333
+
334
+ /**
335
+ * Removes PM2's init-system hook (Linux/macOS).
336
+ * Like startup(), this may only print a sudo command for the user to run.
337
+ * @returns {Promise<{ ok: boolean, sudoCommand: string|null, output: string }>}
338
+ */
339
+ export async function unstartup({ run = defaultRun, pm2Path = 'pm2' } = {}) {
340
+ const r = await run(pm2UnstartupCmd(pm2Path), { timeout: PM2_TIMEOUT_MS });
341
+ const output = combine(r);
342
+ return { ok: r.success, sudoCommand: parseSudoCommand(output), output };
343
+ }
344
+
345
+ /**
346
+ * Pulls the `sudo env PATH=… pm2 startup …` line out of PM2's output.
347
+ *
348
+ * PM2 prints guidance around it, so the line is matched rather than the whole
349
+ * output being handed to the user as if it were a command.
350
+ *
351
+ * @param {string} output
352
+ * @returns {string|null}
353
+ */
354
+ export function parseSudoCommand(output) {
355
+ if (!output) return null;
356
+ for (const line of output.split(/\r?\n/)) {
357
+ const trimmed = line.trim();
358
+ if (/^sudo\s/.test(trimmed) && /pm2/.test(trimmed)) return trimmed;
359
+ }
360
+ return null;
361
+ }
362
+
363
+ /**
364
+ * The OS user this process is running as.
365
+ *
366
+ * PM2 keeps a separate daemon and process list per user (under PM2_HOME), so
367
+ * a service installed by another account is invisible here — and stopping or
368
+ * restarting it would not work. Callers compare this against an app's owner
369
+ * to warn rather than silently doing nothing.
370
+ *
371
+ * @returns {string}
372
+ */
373
+ export function currentUser() {
374
+ try {
375
+ return os.userInfo().username;
376
+ } catch {
377
+ return process.env.USERNAME || process.env.USER || 'unknown';
378
+ }
379
+ }
380
+
381
+ /** The PM2_HOME in effect, which decides which process list we see. */
382
+ export function pm2Home() {
383
+ return process.env.PM2_HOME || null;
384
+ }
385
+
386
+ /** The directory PM2 actually uses, whether or not PM2_HOME is set. */
387
+ export function pm2HomeDir() {
388
+ return process.env.PM2_HOME?.trim() || path.join(os.homedir(), '.pm2');
389
+ }
390
+
391
+ /**
392
+ * True when the PM2 daemon for this PM2_HOME is already running.
393
+ *
394
+ * This matters more than it looks: EVERY pm2 command — `pm2 --version`
395
+ * included — starts the daemon if it is not running. A status read must never
396
+ * do that, or simply opening the dashboard (or the hub agent reporting every
397
+ * minute) would spawn a PM2 daemon on a machine that does not use PM2.
398
+ *
399
+ * Checked by pid file rather than by asking PM2, for the same reason.
400
+ *
401
+ * @returns {boolean}
402
+ */
403
+ export function isDaemonRunning() {
404
+ try {
405
+ const pidFile = path.join(pm2HomeDir(), 'pm2.pid');
406
+ const pid = Number(fs.readFileSync(pidFile, 'utf8').trim());
407
+ if (!Number.isInteger(pid) || pid <= 0) return false;
408
+ // A stale pid file outlives a crashed daemon, so confirm the process.
409
+ process.kill(pid, 0);
410
+ return true;
411
+ } catch {
412
+ return false;
413
+ }
414
+ }
415
+
416
+ // ─── internals ────────────────────────────────────────────────────────────────
417
+
418
+ async function simple(verb, name, run, pm2Path) {
419
+ const r = await run(`${quoteExe(pm2Path)} ${verb} "${name}"`, { timeout: PM2_TIMEOUT_MS });
420
+ return { ok: r.success, output: combine(r) };
421
+ }
422
+
423
+ function combine(r) {
424
+ return [r?.stdout, r?.stderr].filter(Boolean).join('\n').trim();
425
+ }
426
+
427
+ /**
428
+ * Extracts the JSON array from a noisy stdout buffer.
429
+ *
430
+ * Brace counting rather than a regex, because app names and cwd values contain
431
+ * brackets. Every candidate `[` is tried in turn and kept only if it actually
432
+ * parses: PM2 prefixes its own log lines with "[PM2]", so the FIRST `[` in the
433
+ * buffer is routinely the start of a notice rather than the process list, and
434
+ * taking it blindly returned the string "[PM2]".
435
+ *
436
+ * @param {string} text
437
+ * @returns {string|null} The JSON array source, or null when there is none
438
+ */
439
+ export function extractJsonArray(text) {
440
+ const s = String(text ?? '');
441
+
442
+ for (let start = s.indexOf('['); start !== -1; start = s.indexOf('[', start + 1)) {
443
+ const candidate = balancedSlice(s, start);
444
+ if (candidate === null) continue;
445
+
446
+ try {
447
+ if (Array.isArray(JSON.parse(candidate))) return candidate;
448
+ } catch { /* this '[' began something else — keep looking */ }
449
+ }
450
+
451
+ return null;
452
+ }
453
+
454
+ /**
455
+ * Returns the substring from `start` to its matching close bracket, honouring
456
+ * strings and escapes, or null when it never balances.
457
+ *
458
+ * @param {string} s
459
+ * @param {number} start Index of the opening '['
460
+ * @returns {string|null}
461
+ */
462
+ function balancedSlice(s, start) {
463
+ let depth = 0;
464
+ let inString = false;
465
+ let escaped = false;
466
+
467
+ for (let i = start; i < s.length; i++) {
468
+ const ch = s[i];
469
+
470
+ if (inString) {
471
+ if (escaped) escaped = false;
472
+ else if (ch === '\\') escaped = true;
473
+ else if (ch === '"') inString = false;
474
+ continue;
475
+ }
476
+
477
+ if (ch === '"') { inString = true; continue; }
478
+
479
+ if (ch === '[' || ch === '{') depth++;
480
+ else if (ch === ']' || ch === '}') {
481
+ depth--;
482
+ if (depth === 0) return s.slice(start, i + 1);
483
+ if (depth < 0) return null;
484
+ }
485
+ }
486
+
487
+ return null;
488
+ }