easy-devops 1.2.1 → 1.3.1

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-CMRzkIKj.css +1 -0
  3. package/dist/ui/assets/index-DEouL3IK.js +452 -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 +222 -47
  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 +80 -61
  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 +288 -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 +10 -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,135 @@
1
+ // src/dashboard/controllers/hubController.js
2
+ //
3
+ // Thin HTTP layer over core/hubLink.js. All link parsing, persistence and
4
+ // permission logic lives in core so a future CLI menu can reuse it — this
5
+ // controller only translates between HTTP and that module.
6
+ //
7
+ // The hub issues connection strings; this server never generates them.
8
+
9
+ import {
10
+ parseConnectionString,
11
+ saveHubLink,
12
+ clearHubLink,
13
+ saveHubPermissions,
14
+ getLinkStatus,
15
+ } from '../../core/hubLink.js';
16
+ import { PERMISSION_TREE, COMING_SOON_PERMISSION_IDS } from '../../core/hubPermissions.js';
17
+ import { getDataDir, isDevDataDir, isDefaultDataDir } from '../../core/platform.js';
18
+ import { inspect } from '../../core/daemon/lock.js';
19
+ import { stopHubAgent, initHubAgent, getHubAgentStatus, pushPermissions } from '../../core/hub/agent.js';
20
+
21
+ // POST /api/hub/connect
22
+ // Body: { connectionString: 'ezops://hubUrl|serverId|secret' }
23
+ // Saves the pasted link, then starts the agent. Nothing connects until a
24
+ // valid string has been saved.
25
+ export function connectAgent(req, res) {
26
+ const parsed = parseConnectionString(req.body?.connectionString);
27
+ if (!parsed.ok) return res.status(400).json({ error: parsed.error });
28
+
29
+ const saved = saveHubLink(parsed.link);
30
+ if (!saved.ok) return res.status(400).json({ error: saved.error });
31
+
32
+ // The agent belongs to whichever process owns the background jobs. Starting
33
+ // one HERE while a daemon is running produced two sockets with the same
34
+ // serverId, and the hub keeps only one per server — so they evicted each
35
+ // other every few seconds, for ever.
36
+ //
37
+ // saveHubLink() bumps the revision counter, which the daemon's watcher picks
38
+ // up within a few seconds and reconciles its own agent against. So the
39
+ // correct action in that case is to do nothing more.
40
+ const daemon = inspect();
41
+
42
+ if (daemon.running) {
43
+ return res.json({
44
+ ok: true,
45
+ status: hubStatusPayload(),
46
+ agentOwner: 'daemon',
47
+ detail: `The background service (pid ${daemon.lock?.pid}) owns the Hub connection `
48
+ + 'and will pick up the new pairing within a few seconds.',
49
+ });
50
+ }
51
+
52
+ // No daemon: this dashboard is the job owner, so it holds the agent.
53
+ // initHubAgent() is idempotent, but stopping first keeps the intent explicit.
54
+ stopHubAgent();
55
+ initHubAgent();
56
+
57
+ return res.json({ ok: true, status: hubStatusPayload(), agentOwner: 'dashboard' });
58
+ }
59
+
60
+ // DELETE /api/hub/link
61
+ // Unlinks from the hub: stops the agent and clears stored link + permissions.
62
+ export function unlinkHub(req, res) {
63
+ // Stopping a local agent is always safe: if the daemon owns it, there is no
64
+ // socket here to stop. clearHubLink() bumps the revision, which is how the
65
+ // daemon learns to drop its own.
66
+ stopHubAgent();
67
+ clearHubLink();
68
+
69
+ const daemon = inspect();
70
+ return res.json({
71
+ ok: true,
72
+ ...(daemon.running
73
+ ? {
74
+ agentOwner: 'daemon',
75
+ detail: 'The background service will drop its Hub connection within a few seconds.',
76
+ }
77
+ : {}),
78
+ });
79
+ }
80
+
81
+ // GET /api/hub/status
82
+ // Returns the link state plus the agent's live connection status.
83
+ export function hubStatus(req, res) {
84
+ return res.json(hubStatusPayload());
85
+ }
86
+
87
+ // PUT /api/hub/permissions
88
+ // Body: { reloadNginx?: boolean, manageDomains?: boolean, manageSSL?: boolean }
89
+ export function updatePermissions(req, res) {
90
+ const permissions = saveHubPermissions(req.body ?? {});
91
+
92
+ // Push the new state to the Hub immediately so its UI greys out actions
93
+ // without waiting for a poll. Non-fatal: the agent may not be connected.
94
+ try {
95
+ pushPermissions();
96
+ } catch { /* not linked, or socket down */ }
97
+
98
+ return res.json({ permissions, tree: PERMISSION_TREE, comingSoon: COMING_SOON_PERMISSION_IDS });
99
+ }
100
+
101
+ /**
102
+ * Builds the status response. Deliberately omits the secret — it is only ever
103
+ * shown once by the hub, and is never echoed back by this API.
104
+ */
105
+ function hubStatusPayload() {
106
+ const link = getLinkStatus();
107
+ const agent = getHubAgentStatus();
108
+
109
+ return {
110
+ linked: link.linked,
111
+ hubUrl: link.hubUrl,
112
+ serverId: link.serverId,
113
+ permissions: link.permissions,
114
+ // The catalog travels with the status so the UI never hard-codes it.
115
+ tree: PERMISSION_TREE,
116
+ comingSoon: COMING_SOON_PERMISSION_IDS,
117
+ connected: agent.connected,
118
+ status: agent.status,
119
+ lastError: agent.lastError,
120
+ attempts: agent.attempts,
121
+ // Which database this dashboard — and therefore this agent — is actually
122
+ // using. A non-default directory means a CLI and a dashboard can be editing
123
+ // two separate domain lists with no visible sign of it, so the path is
124
+ // shown to make that obvious instead of looking like a sync bug.
125
+ //
126
+ // The two flags answer different questions, and conflating them was a bug:
127
+ // defaultDataDir — is this the ordinary location? A service install
128
+ // passes EASY_DEVOPS_DATA_DIR and is still ordinary.
129
+ // devDataDir — is this a DEVELOPMENT run (staging certificates,
130
+ // `-dev` names)? Only `--dev`/EZ_DEV or `.dev-data`.
131
+ dataDir: getDataDir(),
132
+ defaultDataDir: isDefaultDataDir(getDataDir()),
133
+ devDataDir: isDevDataDir(),
134
+ };
135
+ }
@@ -12,7 +12,7 @@ import {
12
12
  NginxNotFoundError,
13
13
  NginxConfigError,
14
14
  InvalidFilenameError,
15
- } from '../lib/nginx-service.js';
15
+ } from '../../core/nginx-service.js';
16
16
 
17
17
  class NginxController {
18
18
  handleError(err, res) {
@@ -115,10 +115,28 @@ class NginxController {
115
115
  }
116
116
  }
117
117
 
118
+ /**
119
+ * GET /api/nginx/logs?file=error|access&lines=N
120
+ *
121
+ * Both parameters are additive: the previous endpoint took none and always
122
+ * returned 100 lines of the ERROR log, which is what the defaults still do.
123
+ * The access log was simply unreachable before — the contract has always
124
+ * described this endpoint as "access/error lines", so the gap was here.
125
+ *
126
+ * `file` is echoed back so a client cannot mistake which log it is showing.
127
+ */
118
128
  async getLogs(req, res, next) {
119
129
  try {
120
- const result = await getLogs(100);
121
- res.json(result);
130
+ const which = req.query?.file === 'access' ? 'access' : 'error';
131
+
132
+ // Clamped rather than rejected, matching the clamp in core/runner.js for
133
+ // process logs: an out-of-range number is a client bug, not a reason to
134
+ // show the operator an error instead of their logs.
135
+ const requested = Number(req.query?.lines);
136
+ const lines = Math.max(1, Math.min(5000, Number.isFinite(requested) ? requested : 100));
137
+
138
+ const result = await getLogs(lines, which);
139
+ res.json({ ...result, file: which });
122
140
  } catch (err) {
123
141
  this.handleError(err, res);
124
142
  }
@@ -0,0 +1,368 @@
1
+ /**
2
+ * dashboard/controllers/processesController.js
3
+ *
4
+ * The Processes page and the service status panel.
5
+ *
6
+ * Two rules shape this controller:
7
+ *
8
+ * 1. PM2 apps that Easy DevOps did not create are listed but never acted on
9
+ * implicitly. A request naming one is honoured — the user clicked it —
10
+ * but nothing here iterates over "all apps" and restarts them.
11
+ * 2. The dashboard never installs, elevates or prompts. Installing the
12
+ * Windows service in Server mode needs an Administrator context, and
13
+ * systemd needs sudo; neither can be obtained from inside a web request.
14
+ * So those answers name the exact command instead. No password is
15
+ * involved in any mode.
16
+ */
17
+
18
+ import { isWindows, isDevDataDir, getDataDir } from '../../core/platform.js';
19
+ import * as runner from '../../core/runner.js';
20
+ import * as service from '../../core/service/index.js';
21
+ import { MODES } from '../../core/service/index.js';
22
+ import { daemonStatus } from '../lib/daemonBridge.js';
23
+ import { probe } from '../../core/probeCache.js';
24
+
25
+ const SERVER_MODE = MODES.SERVER;
26
+
27
+ /**
28
+ * PM2 detection, cached beside the service probes.
29
+ *
30
+ * `where.exe pm2` measured at about 2 s on the machine that reported this
31
+ * endpoint as slow, and `pm2 --version` at about 4 s. Whether PM2 is installed
32
+ * changes when the user installs PM2, so a minute is a long time to be wrong
33
+ * and a short time to be slow. The `service:` prefix means
34
+ * `invalidateProbes()` drops this too.
35
+ */
36
+ const PM2_PROBE_KEY = 'service:pm2';
37
+ const PM2_TTL_MS = 60_000;
38
+
39
+ /** Produces the PM2 detection result. One place, so the warm-up matches the read. */
40
+ const detectPm2 = () => runner.detect({ probeVersion: runner.isDaemonRunning() });
41
+
42
+ /**
43
+ * Fills every probe `GET /api/service` reads, so the next request is warm.
44
+ *
45
+ * It has to cover the PM2 probe as well as core's three: warming only core's
46
+ * left this endpoint's first call waiting on `where.exe pm2` and answering
47
+ * `pending: true` anyway, which defeated the warm-up entirely. Measured, not
48
+ * reasoned about - that is exactly what happened the first time.
49
+ *
50
+ * Never awaited by a request. Called when the dashboard starts and again after
51
+ * any lifecycle action, so a user who just pressed Start finds the new state
52
+ * already measured rather than paying for the probes on their next poll.
53
+ *
54
+ * @returns {Promise<void>}
55
+ */
56
+ export async function warmProbes() {
57
+ await Promise.allSettled([
58
+ service.warmProbes(),
59
+ probe(PM2_PROBE_KEY, detectPm2, { ttlMs: PM2_TTL_MS, coldWaitMs: 60_000 }),
60
+ ]);
61
+ }
62
+
63
+ /**
64
+ * What to tell a client that cannot install or elevate by itself.
65
+ *
66
+ * Machine-readable, because the UI must show the command rather than pretend
67
+ * it can elevate. No password is involved in any mode: the Windows service
68
+ * runs as the virtual account `NT SERVICE\EasyDevOps`, and sudo asks for its
69
+ * own on the user's terminal.
70
+ */
71
+ function installGuidance(mode) {
72
+ const needsElevation = isWindows && mode === SERVER_MODE;
73
+ return {
74
+ command: 'ezz service install',
75
+ needsElevation,
76
+ shell: needsElevation ? 'Administrator PowerShell' : null,
77
+ };
78
+ }
79
+
80
+ /**
81
+ * Runs one lifecycle action and answers in a shape the UI can act on.
82
+ *
83
+ * An action the dashboard cannot perform is NOT a 500: it is a 403 naming the
84
+ * exact command and the shell to run it in. Windows Server mode needs an
85
+ * Administrator context and systemd needs sudo, and neither can be obtained
86
+ * from inside a web request — so the honest answer is the command, never a
87
+ * password prompt.
88
+ */
89
+ async function runLifecycle(res, action, fn) {
90
+ try {
91
+ const result = await fn();
92
+
93
+ // The cached probes describe what just changed. core/service/ invalidates
94
+ // them before it acts, which keeps a concurrent read honest; this second
95
+ // call is for after, so the next GET /api/service measures the new state
96
+ // rather than whatever was true mid-operation.
97
+ service.invalidateProbes();
98
+
99
+ // And re-measure immediately, without the client waiting: a UI that just
100
+ // pressed Start polls within a second or two, and this is what makes that
101
+ // poll fast instead of making it pay for the probes.
102
+ warmProbes().catch(() => { /* the next request probes anyway */ });
103
+
104
+ if (result.ok) {
105
+ return res.json({
106
+ ok: true,
107
+ action,
108
+ output: result.detail ?? null,
109
+ backgroundService: daemonStatus(),
110
+ });
111
+ }
112
+
113
+ if (result.needsElevation) {
114
+ const elevated = isWindows
115
+ ? { command: `ezz service ${action}`, shell: 'Administrator PowerShell' }
116
+ : { command: `sudo systemctl ${action} easy-devops`, shell: 'a terminal with sudo' };
117
+
118
+ return res.status(403).json({
119
+ error: 'elevation_required',
120
+ action,
121
+ message: result.reason,
122
+ ...elevated,
123
+ backgroundService: daemonStatus(),
124
+ });
125
+ }
126
+
127
+ // "Nothing is installed" is a precondition, not a server fault.
128
+ if (/not installed/i.test(result.reason ?? '')) {
129
+ return res.status(409).json({
130
+ error: 'not_installed',
131
+ action,
132
+ message: result.reason,
133
+ command: 'ezz service install',
134
+ backgroundService: daemonStatus(),
135
+ });
136
+ }
137
+
138
+ if (result.alreadyRunning) {
139
+ return res.status(409).json({
140
+ error: 'already_running',
141
+ action,
142
+ message: result.reason,
143
+ backgroundService: daemonStatus(),
144
+ });
145
+ }
146
+
147
+ return res.status(500).json({
148
+ error: 'action_failed',
149
+ action,
150
+ message: result.reason ?? `could not ${action} the service`,
151
+ backgroundService: daemonStatus(),
152
+ });
153
+ } catch (err) {
154
+ return res.status(500).json({ error: 'Internal server error' });
155
+ }
156
+ }
157
+
158
+ /** Actions a request may ask for, mapped to the runner function. */
159
+ const ACTIONS = {
160
+ start: runner.restart, // PM2 "start" for an existing app is a restart
161
+ restart: runner.restart,
162
+ stop: runner.stop,
163
+ reload: runner.reload,
164
+ };
165
+
166
+ class ProcessesController {
167
+ /**
168
+ * GET /api/processes
169
+ * The PM2 app list plus enough service context for the page header.
170
+ */
171
+ async list(req, res) {
172
+ try {
173
+ const pm2 = await runner.detect();
174
+ if (!pm2.installed) {
175
+ return res.json({
176
+ pm2: { installed: false, version: null, path: null },
177
+ apps: [],
178
+ currentUser: runner.currentUser(),
179
+ hint: 'PM2 is not installed. Run `ezz service install` to set up the background service.',
180
+ });
181
+ }
182
+
183
+ const listed = await runner.list({ pm2Path: pm2.path ?? 'pm2' });
184
+ if (!listed.ok) {
185
+ return res.status(502).json({ error: 'Could not read the PM2 process list', detail: listed.error });
186
+ }
187
+
188
+ res.json({
189
+ pm2: { installed: true, version: pm2.version, path: pm2.path },
190
+ apps: listed.apps,
191
+ currentUser: runner.currentUser(),
192
+ pm2Home: runner.pm2Home(),
193
+ });
194
+ } catch (err) {
195
+ res.status(500).json({ error: 'Internal server error' });
196
+ }
197
+ }
198
+
199
+ /**
200
+ * POST /api/processes/:name/:action
201
+ * action ∈ start | stop | restart | reload
202
+ *
203
+ * Acting on an app Easy DevOps did not create is allowed, because reaching
204
+ * this endpoint means the user clicked that row's button. It is recorded in
205
+ * the response so the UI can be explicit about what it just did.
206
+ */
207
+ async action(req, res) {
208
+ try {
209
+ const { name, action } = req.params;
210
+ const fn = ACTIONS[action];
211
+ if (!fn) {
212
+ return res.status(400).json({ error: `Unknown action: ${action}` });
213
+ }
214
+ if (typeof name !== 'string' || !name.trim()) {
215
+ return res.status(400).json({ error: 'A process name is required' });
216
+ }
217
+
218
+ const pm2 = await runner.detect();
219
+ if (!pm2.installed) {
220
+ return res.status(409).json({ error: 'PM2 is not installed' });
221
+ }
222
+ const pm2Path = pm2.path ?? 'pm2';
223
+
224
+ // Only act on something PM2 actually knows, so a typo cannot be
225
+ // reported as a success.
226
+ const listed = await runner.list({ pm2Path });
227
+ const app = listed.ok ? listed.apps.find((a) => a.name === name) : null;
228
+ if (!app) {
229
+ return res.status(404).json({ error: `PM2 has no process named "${name}"` });
230
+ }
231
+
232
+ // PM2 is per-user: another account's app is visible in some setups but
233
+ // cannot be controlled from here, and would fail confusingly.
234
+ if (app.user && app.user !== runner.currentUser()) {
235
+ return res.status(409).json({
236
+ error: `"${name}" belongs to OS user "${app.user}", not "${runner.currentUser()}".`,
237
+ hint: 'PM2 keeps a separate process list per user. Sign in as that user to control it.',
238
+ });
239
+ }
240
+
241
+ const result = await fn(name, { pm2Path });
242
+ if (!result.ok) {
243
+ return res.status(500).json({ error: `pm2 ${action} failed`, output: result.output });
244
+ }
245
+
246
+ res.json({ ok: true, name, action, managed: app.managed, output: result.output });
247
+ } catch (err) {
248
+ res.status(500).json({ error: 'Internal server error' });
249
+ }
250
+ }
251
+
252
+ /**
253
+ * GET /api/processes/:name/logs?lines=200
254
+ */
255
+ async logs(req, res) {
256
+ try {
257
+ const { name } = req.params;
258
+ const lines = Number(req.query.lines) || 200;
259
+
260
+ const pm2 = await runner.detect();
261
+ if (!pm2.installed) {
262
+ return res.status(409).json({ error: 'PM2 is not installed' });
263
+ }
264
+
265
+ const result = await runner.logs(name, { lines, pm2Path: pm2.path ?? 'pm2' });
266
+ res.json({ name, lines: result.lines });
267
+ } catch (err) {
268
+ res.status(500).json({ error: 'Internal server error' });
269
+ }
270
+ }
271
+
272
+ /**
273
+ * GET /api/service
274
+ *
275
+ * `backgroundService` is the single authority on the native daemon. The
276
+ * PM2-era top-level fields are gone: on a machine where the daemon WAS
277
+ * running they said `installed: false, running: false`, so a client reading
278
+ * them rendered "Not installed" over a working service. They described a PM2
279
+ * app that no longer exists.
280
+ *
281
+ * What remains at the top level is only what is still true and still used:
282
+ * `pm2` and the Processes page beneath it (the user's OWN apps), the dev
283
+ * badge, the data directory, and the per-mode install guidance.
284
+ */
285
+ async status(req, res) {
286
+ try {
287
+ const [native, pm2] = await Promise.all([
288
+ // `cache: true`: the cheap lock-based state is read fresh every time,
289
+ // and the three probes that each cost a subprocess come from the cache
290
+ // and refresh behind the response. See core/probeCache.js for the
291
+ // measurements that made this necessary - this endpoint took about 20
292
+ // seconds on Windows, where one spawn costs about a second.
293
+ service.status({ cache: true }),
294
+ // Cached for the same reason, and under the same `service:` prefix so
295
+ // one invalidation covers it. `probeVersion: false` unless PM2's daemon
296
+ // is already up, and no daemon start: reporting must never bring a PM2
297
+ // daemon to life on a machine that does not use one.
298
+ probe(PM2_PROBE_KEY, detectPm2, { ttlMs: PM2_TTL_MS }),
299
+ ]);
300
+
301
+ // The cheap, synchronous state plus `connected` — the same object the
302
+ // `service:changed` socket event carries, so the UI has one shape.
303
+ const live = daemonStatus();
304
+
305
+ res.json({
306
+ // ── The native background service ────────────────────────────────
307
+ backgroundService: {
308
+ ...live,
309
+
310
+ // From the full status: these need the service manager and the
311
+ // runtime probes, so they are not in the cheap state.
312
+ state: native.service?.state ?? null,
313
+ enabledOnBoot: native.service?.enabledOnBoot ?? null,
314
+ restarts: native.service?.restarts ?? 0,
315
+ crashLooping: Boolean(native.service?.crashLooping),
316
+ warnings: native.warnings ?? [],
317
+ runtime: native.runtime ?? null,
318
+ },
319
+
320
+ // ── Still true, still used ────────────────────────────────────────
321
+ pm2: {
322
+ installed: pm2.value?.installed ?? null,
323
+ version: pm2.value?.version ?? null,
324
+ path: pm2.value?.path ?? null,
325
+ },
326
+
327
+ // How old the measured parts are, and whether anything is still being
328
+ // measured. A client can render immediately and ask again rather than
329
+ // waiting for a probe it cannot see.
330
+ probes: {
331
+ ageMs: Math.max(native.probes?.ageMs ?? 0, pm2.ageMs ?? 0),
332
+ fresh: Boolean(native.probes?.fresh) && Boolean(pm2.fresh),
333
+ pending: Boolean(native.probes?.pending) || Boolean(pm2.pending),
334
+ refreshing: Boolean(native.probes?.refreshing) || Boolean(pm2.refreshing),
335
+ },
336
+ dev: isDevDataDir(),
337
+ dataDir: getDataDir(),
338
+
339
+ // Per-mode guidance for a client that cannot elevate itself.
340
+ install: installGuidance(native.mode),
341
+ });
342
+ } catch (err) {
343
+ res.status(500).json({ error: 'Internal server error' });
344
+ }
345
+ }
346
+
347
+ /** POST /api/service/start */
348
+ async start(req, res) {
349
+ return runLifecycle(res, 'start', () => service.start({}));
350
+ }
351
+
352
+ /** POST /api/service/stop */
353
+ async stop(req, res) {
354
+ return runLifecycle(res, 'stop', () => service.stop({}));
355
+ }
356
+
357
+ /**
358
+ * POST /api/service/restart
359
+ *
360
+ * Clears the "stopped by you" marker, so a restart from the UI behaves like
361
+ * one from the CLI.
362
+ */
363
+ async restart(req, res) {
364
+ return runLifecycle(res, 'restart', () => service.restart({}));
365
+ }
366
+ }
367
+
368
+ export default ProcessesController;