pulse-hub 3.5.0 → 3.6.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 (43) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/backend/.env.example +52 -52
  3. package/backend/agent.js +372 -372
  4. package/backend/cli.js +23 -1
  5. package/backend/emails/env-backup.html +52 -52
  6. package/backend/emails/invite.html +53 -53
  7. package/backend/lib/agent-rpc.js +72 -72
  8. package/backend/lib/async-route.js +17 -17
  9. package/backend/lib/authz/bootstrap.js +35 -35
  10. package/backend/lib/authz/catalog.js +291 -291
  11. package/backend/lib/authz/delegation.js +104 -104
  12. package/backend/lib/authz/effective.js +104 -104
  13. package/backend/lib/authz/engine.js +251 -251
  14. package/backend/lib/authz/index.js +134 -134
  15. package/backend/lib/authz/migrate.js +871 -871
  16. package/backend/lib/authz/mutate.js +87 -87
  17. package/backend/lib/authz/preview.js +327 -327
  18. package/backend/lib/authz/scope.js +282 -282
  19. package/backend/lib/env-mask.js +131 -131
  20. package/backend/lib/invite-helpers.js +83 -83
  21. package/backend/lib/invites.js +160 -160
  22. package/backend/lib/logs.js +244 -244
  23. package/backend/lib/metrics.js +249 -249
  24. package/backend/lib/relay-state.js +564 -564
  25. package/backend/lib/session.js +48 -48
  26. package/backend/middleware/authz.js +65 -65
  27. package/backend/public/assets/favicon.svg +6 -6
  28. package/backend/public/assets/index.js +1 -1
  29. package/backend/public/index.html +23 -24
  30. package/backend/routes/access.js +123 -123
  31. package/backend/routes/audit.js +41 -41
  32. package/backend/routes/auth.js +207 -207
  33. package/backend/routes/invites-public.js +91 -91
  34. package/backend/routes/invites.js +121 -121
  35. package/backend/routes/logs.js +68 -68
  36. package/backend/routes/metrics.js +76 -76
  37. package/backend/routes/policies.js +240 -240
  38. package/backend/routes/teams.js +221 -221
  39. package/backend/routes/users.js +100 -100
  40. package/backend/seed-admins.js +68 -68
  41. package/backend/server.js +106 -106
  42. package/backend/ws/agent-relay.js +159 -159
  43. package/package.json +1 -1
package/backend/agent.js CHANGED
@@ -1,372 +1,372 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const WebSocket = require('ws');
4
- const {
5
- getSystemMetrics,
6
- getPm2Processes,
7
- getDockerContainers,
8
- getSystemdUnits,
9
- checkDockerAvailable,
10
- checkSystemdAvailable,
11
- } = require('./lib/metrics');
12
- const {
13
- getFilteredRecords,
14
- getFilteredDockerRecords,
15
- getFilteredJournalRecords,
16
- createTailer,
17
- createDockerTailer,
18
- createJournalTailer,
19
- } = require('./lib/logs');
20
- const { computeBundleVersion, readPackageJson } = require('./lib/bundle-version');
21
- const { selfUpdate } = require('./lib/self-update');
22
- const { readEnvFile, writeEnvFile, restartUnit } = require('./lib/env-files');
23
-
24
- const CONFIG_FILE = path.join(__dirname, 'agent.config.json');
25
- const IDLE_INTERVAL_MS = 5 * 60 * 1000;
26
- const RECONNECT_MIN_MS = 2000;
27
- const RECONNECT_MAX_MS = 30000;
28
-
29
- function loadConfig() {
30
- let fileConfig = {};
31
- try {
32
- fileConfig = JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf-8'));
33
- } catch (e) {}
34
- const hubUrl = process.env.PULSE_HUB_URL || fileConfig.hubUrl;
35
- const instanceId = process.env.PULSE_INSTANCE_ID || fileConfig.instanceId;
36
- const token = process.env.PULSE_TOKEN || fileConfig.token;
37
- if (!hubUrl || !instanceId || !token) {
38
- console.error(
39
- 'Missing agent config. Provide agent.config.json (see agent.config.example.json) or PULSE_HUB_URL/PULSE_INSTANCE_ID/PULSE_TOKEN env vars.',
40
- );
41
- process.exit(1);
42
- }
43
- // Optional — lets the hub's Groups feature match this instance without an admin
44
- // enumerating it explicitly (see CLAUDE.md's "Auth model" / Groups). Set via
45
- // install-agent.sh's --tag flag (agent.config.json's "tags" array) or PULSE_TAGS
46
- // (comma-separated). Re-sent on every hello, so it stays in sync on reconnect.
47
- const tags = process.env.PULSE_TAGS
48
- ? process.env.PULSE_TAGS.split(',')
49
- .map((t) => t.trim())
50
- .filter(Boolean)
51
- : Array.isArray(fileConfig.tags)
52
- ? fileConfig.tags
53
- : [];
54
- return { hubUrl, instanceId, token, tags };
55
- }
56
-
57
- const { hubUrl, instanceId, token, tags } = loadConfig();
58
- // Staleness signal for the hub's self-update check — see maybeAutoUpdateSelf in
59
- // ws/agent-relay.js and .claude/rules/version-bump-policy.md. Not shown to a person.
60
- const AGENT_BUNDLE_HASH = computeBundleVersion(__dirname);
61
- // Human-facing semver, read from whichever package.json ships alongside this agent
62
- // (see lib/bundle-version.js's readPackageJson) — shown in the hub's UI.
63
- const AGENT_APP_VERSION = (readPackageJson(__dirname) || {}).version || 'unknown';
64
- // Tells the hub which optional request types this build understands, so it can say "update
65
- // this agent" instead of waiting out a timeout for a frame an older agent silently ignores.
66
- const AGENT_CAPABILITIES = ['env-files', 'restart-agent'];
67
- // How often to re-scan for new/removed/changed services between metrics pushes. Without
68
- // this the process list only refreshed on the (up to 5 minute) idle metrics push, so a
69
- // freshly deployed service looked "missing" until the agent was restarted.
70
- const DISCOVERY_INTERVAL_MS = 30 * 1000;
71
-
72
- // Last-resort guards: a monitoring agent that dies on one bad frame or a stray rejected
73
- // promise leaves the box unmonitored. Log and keep going; but if errors are arriving in a
74
- // storm the process state is probably bad, so exit and let the supervisor start it clean.
75
- const recentFatals = [];
76
- function survive(kind, err) {
77
- console.error(`${kind}:`, err && err.stack ? err.stack : err);
78
- const now = Date.now();
79
- recentFatals.push(now);
80
- while (recentFatals.length && now - recentFatals[0] > 60 * 1000) recentFatals.shift();
81
- if (recentFatals.length > 10) {
82
- console.error('Too many unexpected errors in the last minute — exiting for a clean restart.');
83
- process.exit(1);
84
- }
85
- }
86
- process.on('uncaughtException', (e) => survive('uncaughtException', e));
87
- process.on('unhandledRejection', (e) => survive('unhandledRejection', e));
88
-
89
- let ws = null;
90
- let discoveryTimer = null;
91
- let lastProcessFingerprint = null;
92
- let updating = false;
93
- let metricsTimer = null;
94
- let reconnectDelay = RECONNECT_MIN_MS;
95
- const activeTails = new Map(); // key `${app}:${stream}` -> tailer handle
96
-
97
- function send(frame) {
98
- if (ws && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(frame));
99
- }
100
-
101
- function pushMetrics() {
102
- send({ type: 'metrics', ts: Date.now(), ...getSystemMetrics() });
103
- }
104
-
105
- function scheduleMetrics(intervalMs) {
106
- if (metricsTimer) clearInterval(metricsTimer);
107
- metricsTimer = setInterval(pushMetrics, intervalMs);
108
- }
109
-
110
- // Identity + state of every service the agent can see (no cpu/memory, which change
111
- // constantly). A change means something was deployed, removed, stopped or restarted.
112
- function processFingerprint() {
113
- const systemd = checkSystemdAvailable();
114
- return [
115
- ...getPm2Processes().map((p) => `pm2:${p.name}:${p.status}`),
116
- ...getDockerContainers().map((c) => `docker:${c.name}:${c.status}`),
117
- ...(systemd.ok ? getSystemdUnits().map((u) => `systemd:${u.name}`) : []),
118
- ]
119
- .sort()
120
- .join('\n');
121
- }
122
-
123
- // Cheap poll that pushes a full metrics frame as soon as the service set changes, so new
124
- // services show up (and become selectable on the Logs page) without waiting for the next
125
- // scheduled push or an agent restart.
126
- function checkForNewServices() {
127
- if (!ws || ws.readyState !== WebSocket.OPEN) return;
128
- try {
129
- const fp = processFingerprint();
130
- if (lastProcessFingerprint !== null && fp !== lastProcessFingerprint) pushMetrics();
131
- lastProcessFingerprint = fp;
132
- } catch (e) {
133
- // Discovery must never take the agent down.
134
- }
135
- }
136
-
137
- function scheduleDiscovery() {
138
- if (discoveryTimer) clearInterval(discoveryTimer);
139
- lastProcessFingerprint = null; // first tick after (re)connect just records a baseline
140
- discoveryTimer = setInterval(checkForNewServices, DISCOVERY_INTERVAL_MS);
141
- }
142
-
143
- // Operator-triggered (hub's restart-agent route). Exits cleanly and relies on the
144
- // supervisor (systemd Restart=always, installed by install-agent.sh; or PM2) to start a
145
- // fresh process — which also picks up OS group changes (docker, systemd-journal) that a
146
- // running process never sees.
147
- function performRestart() {
148
- console.log('Restart requested by hub — exiting so the supervisor restarts this agent.');
149
- stopAllTails();
150
- setTimeout(() => process.exit(0), 200);
151
- }
152
-
153
- function resolveLogFile(app, stream) {
154
- const proc = getPm2Processes().find((p) => p.name === app);
155
- if (!proc) return null;
156
- return stream === 'err' ? proc.err_log : proc.out_log;
157
- }
158
-
159
- function resolveDockerContainer(app) {
160
- const container = getDockerContainers().find((c) => c.name === app);
161
- return container ? container.containerId : null;
162
- }
163
-
164
- // Only ever hand journalctl a unit name that's in the agent's own live list — the name
165
- // arrives over the wire from the hub.
166
- function resolveSystemdUnit(app) {
167
- const unit = getSystemdUnits().find((u) => u.name === app);
168
- return unit ? unit.name : null;
169
- }
170
-
171
- function handleGetLogs(msg) {
172
- let all;
173
- if (msg.kind === 'systemd') {
174
- all = getFilteredJournalRecords(resolveSystemdUnit(msg.app), msg.search, msg.level);
175
- } else if (msg.kind === 'docker') {
176
- const containerId = resolveDockerContainer(msg.app);
177
- all = getFilteredDockerRecords(containerId, msg.stream, msg.search, msg.level);
178
- } else {
179
- const filePath = resolveLogFile(msg.app, msg.stream);
180
- all = getFilteredRecords(filePath, msg.search, msg.level);
181
- }
182
- const records = all.slice(msg.offset || 0, (msg.offset || 0) + (msg.limit || 20));
183
- send({ type: 'logs_chunk', requestId: msg.requestId, records, total: all.length });
184
- }
185
-
186
- function handleTailLogs(msg) {
187
- const key = `${msg.kind}:${msg.app}:${msg.stream}`;
188
- stopTail(key);
189
- const search = msg.search,
190
- level = msg.level;
191
- function matches(record) {
192
- if (level && String(record.level) !== String(level)) return false;
193
- if (search && !JSON.stringify(record).toLowerCase().includes(search.toLowerCase()))
194
- return false;
195
- return true;
196
- }
197
- const onRecord = (record) =>
198
- send({ type: 'log_line', app: msg.app, stream: msg.stream, kind: msg.kind, record });
199
- let tailer;
200
- if (msg.kind === 'systemd')
201
- tailer = createJournalTailer(resolveSystemdUnit(msg.app), matches, onRecord);
202
- else if (msg.kind === 'docker')
203
- tailer = createDockerTailer(resolveDockerContainer(msg.app), msg.stream, matches, onRecord);
204
- else tailer = createTailer(resolveLogFile(msg.app, msg.stream), matches, onRecord);
205
- activeTails.set(key, tailer);
206
- }
207
-
208
- function stopTail(key) {
209
- const existing = activeTails.get(key);
210
- if (existing) {
211
- existing.stop();
212
- activeTails.delete(key);
213
- }
214
- }
215
-
216
- function stopAllTails() {
217
- for (const key of activeTails.keys()) stopTail(key);
218
- }
219
-
220
- // Request/response frames for the env-file editor (see lib/env-files.js,
221
- // docs/env-files.md): every one is answered with exactly one 'rpc_result' carrying the
222
- // hub's requestId, success or failure — a failure must never throw out of here and take
223
- // the agent down.
224
- async function handleRpc(msg, fn) {
225
- try {
226
- const result = await fn();
227
- send({ type: 'rpc_result', requestId: msg.requestId, ...result, ok: true });
228
- } catch (e) {
229
- send({
230
- type: 'rpc_result',
231
- requestId: msg.requestId,
232
- ok: false,
233
- code: e.code || 'ERROR',
234
- error: e.message || String(e),
235
- });
236
- }
237
- }
238
-
239
- // Triggered by the hub, never automatically — see lib/self-update.js. A failure here
240
- // must never take the agent down: it logs and keeps running the code already loaded in
241
- // memory, so a bad bundle doesn't leave this box unmonitored.
242
- async function performSelfUpdate() {
243
- if (updating) {
244
- console.log('Self-update already in progress, ignoring duplicate request.');
245
- return;
246
- }
247
- updating = true;
248
- console.log(
249
- 'Self-update requested by hub — downloading and installing the current agent bundle...',
250
- );
251
- try {
252
- await selfUpdate({ hubUrl, instanceId, token, installDir: __dirname });
253
- console.log(
254
- 'Self-update succeeded — exiting so systemd restarts this service with the new code.',
255
- );
256
- process.exit(0);
257
- } catch (e) {
258
- console.error('Self-update failed, continuing to run the current version:', e.message);
259
- updating = false;
260
- }
261
- }
262
-
263
- function connect() {
264
- ws = new WebSocket(hubUrl);
265
-
266
- ws.on('open', () => {
267
- send({
268
- type: 'hello',
269
- instanceId,
270
- token,
271
- bundleHash: AGENT_BUNDLE_HASH,
272
- appVersion: AGENT_APP_VERSION,
273
- tags,
274
- capabilities: AGENT_CAPABILITIES,
275
- });
276
- });
277
-
278
- ws.on('message', (raw) => {
279
- let msg;
280
- try {
281
- msg = JSON.parse(raw);
282
- } catch (e) {
283
- return;
284
- }
285
- try {
286
- handleFrame(msg);
287
- } catch (e) {
288
- console.error(`Error handling '${msg && msg.type}' frame:`, e && e.message);
289
- }
290
- });
291
-
292
- function handleFrame(msg) {
293
- if (msg.type === 'hello_ack') {
294
- reconnectDelay = RECONNECT_MIN_MS;
295
- pushMetrics();
296
- scheduleMetrics(IDLE_INTERVAL_MS);
297
- scheduleDiscovery();
298
- } else if (msg.type === 'hello_reject') {
299
- // Don't exit: a rejection can be transient (hub mid-deploy/migration) and exiting just
300
- // makes the supervisor respawn us in a tight loop. The socket closes and the normal
301
- // backoff reconnect (max 30s) retries; a genuinely bad token is fixed by reinstalling.
302
- console.error('Hub rejected this agent (will keep retrying):', msg.reason);
303
- } else if (msg.type === 'set_interval') {
304
- scheduleMetrics(msg.ms);
305
- } else if (msg.type === 'get_logs') {
306
- handleGetLogs(msg);
307
- } else if (msg.type === 'tail_logs') {
308
- handleTailLogs(msg);
309
- } else if (msg.type === 'stop_tail') {
310
- stopTail(`${msg.kind}:${msg.app}:${msg.stream}`);
311
- } else if (msg.type === 'self_update') {
312
- performSelfUpdate();
313
- } else if (msg.type === 'restart_agent') {
314
- performRestart();
315
- } else if (msg.type === 'env_read') {
316
- handleRpc(msg, () => readEnvFile(msg.path));
317
- } else if (msg.type === 'env_write') {
318
- handleRpc(msg, () => writeEnvFile(msg.path, msg.content, msg.baseHash));
319
- } else if (msg.type === 'service_restart') {
320
- handleRpc(msg, () => restartUnit(msg.kind, msg.name));
321
- }
322
- }
323
-
324
- ws.on('close', () => {
325
- stopAllTails();
326
- if (metricsTimer) {
327
- clearInterval(metricsTimer);
328
- metricsTimer = null;
329
- }
330
- if (discoveryTimer) {
331
- clearInterval(discoveryTimer);
332
- discoveryTimer = null;
333
- }
334
- scheduleReconnect();
335
- });
336
-
337
- ws.on('error', () => {}); // 'close' fires after 'error'; reconnect handled there
338
- }
339
-
340
- function scheduleReconnect() {
341
- setTimeout(connect, reconnectDelay);
342
- reconnectDelay = Math.min(reconnectDelay * 2, RECONNECT_MAX_MS);
343
- }
344
-
345
- connect();
346
- console.log(
347
- `Pulse agent starting — instance "${instanceId}", hub ${hubUrl}, v${AGENT_APP_VERSION} (bundle ${AGENT_BUNDLE_HASH})`,
348
- );
349
-
350
- const systemdCheck = checkSystemdAvailable();
351
- if (systemdCheck.state === 'ok') {
352
- console.log(
353
- `systemd journal readable — ${getSystemdUnits().length} running service(s) visible to this agent.`,
354
- );
355
- } else if (systemdCheck.state === 'unreadable') {
356
- console.log(
357
- `systemd journal not readable by OS user '${systemdCheck.user}' — service logs won't be available. Fix: sudo usermod -aG systemd-journal ${systemdCheck.user} && sudo systemctl restart pulse-agent`,
358
- );
359
- } else {
360
- console.log("systemd/journalctl not found — service logs won't be available.");
361
- }
362
-
363
- const dockerCheck = checkDockerAvailable();
364
- if (dockerCheck.ok) {
365
- console.log(
366
- `Docker detected — ${getDockerContainers().length} container(s) visible to this agent.`,
367
- );
368
- } else {
369
- console.log(
370
- `Docker not usable from this agent (${dockerCheck.error}) — container logs won't be available. If this box runs Docker, make sure this agent's OS user is in the 'docker' group (or is root).`,
371
- );
372
- }
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const WebSocket = require('ws');
4
+ const {
5
+ getSystemMetrics,
6
+ getPm2Processes,
7
+ getDockerContainers,
8
+ getSystemdUnits,
9
+ checkDockerAvailable,
10
+ checkSystemdAvailable,
11
+ } = require('./lib/metrics');
12
+ const {
13
+ getFilteredRecords,
14
+ getFilteredDockerRecords,
15
+ getFilteredJournalRecords,
16
+ createTailer,
17
+ createDockerTailer,
18
+ createJournalTailer,
19
+ } = require('./lib/logs');
20
+ const { computeBundleVersion, readPackageJson } = require('./lib/bundle-version');
21
+ const { selfUpdate } = require('./lib/self-update');
22
+ const { readEnvFile, writeEnvFile, restartUnit } = require('./lib/env-files');
23
+
24
+ const CONFIG_FILE = path.join(__dirname, 'agent.config.json');
25
+ const IDLE_INTERVAL_MS = 5 * 60 * 1000;
26
+ const RECONNECT_MIN_MS = 2000;
27
+ const RECONNECT_MAX_MS = 30000;
28
+
29
+ function loadConfig() {
30
+ let fileConfig = {};
31
+ try {
32
+ fileConfig = JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf-8'));
33
+ } catch (e) {}
34
+ const hubUrl = process.env.PULSE_HUB_URL || fileConfig.hubUrl;
35
+ const instanceId = process.env.PULSE_INSTANCE_ID || fileConfig.instanceId;
36
+ const token = process.env.PULSE_TOKEN || fileConfig.token;
37
+ if (!hubUrl || !instanceId || !token) {
38
+ console.error(
39
+ 'Missing agent config. Provide agent.config.json (see agent.config.example.json) or PULSE_HUB_URL/PULSE_INSTANCE_ID/PULSE_TOKEN env vars.',
40
+ );
41
+ process.exit(1);
42
+ }
43
+ // Optional — lets the hub's Groups feature match this instance without an admin
44
+ // enumerating it explicitly (see CLAUDE.md's "Auth model" / Groups). Set via
45
+ // install-agent.sh's --tag flag (agent.config.json's "tags" array) or PULSE_TAGS
46
+ // (comma-separated). Re-sent on every hello, so it stays in sync on reconnect.
47
+ const tags = process.env.PULSE_TAGS
48
+ ? process.env.PULSE_TAGS.split(',')
49
+ .map((t) => t.trim())
50
+ .filter(Boolean)
51
+ : Array.isArray(fileConfig.tags)
52
+ ? fileConfig.tags
53
+ : [];
54
+ return { hubUrl, instanceId, token, tags };
55
+ }
56
+
57
+ const { hubUrl, instanceId, token, tags } = loadConfig();
58
+ // Staleness signal for the hub's self-update check — see maybeAutoUpdateSelf in
59
+ // ws/agent-relay.js and .claude/rules/version-bump-policy.md. Not shown to a person.
60
+ const AGENT_BUNDLE_HASH = computeBundleVersion(__dirname);
61
+ // Human-facing semver, read from whichever package.json ships alongside this agent
62
+ // (see lib/bundle-version.js's readPackageJson) — shown in the hub's UI.
63
+ const AGENT_APP_VERSION = (readPackageJson(__dirname) || {}).version || 'unknown';
64
+ // Tells the hub which optional request types this build understands, so it can say "update
65
+ // this agent" instead of waiting out a timeout for a frame an older agent silently ignores.
66
+ const AGENT_CAPABILITIES = ['env-files', 'restart-agent'];
67
+ // How often to re-scan for new/removed/changed services between metrics pushes. Without
68
+ // this the process list only refreshed on the (up to 5 minute) idle metrics push, so a
69
+ // freshly deployed service looked "missing" until the agent was restarted.
70
+ const DISCOVERY_INTERVAL_MS = 30 * 1000;
71
+
72
+ // Last-resort guards: a monitoring agent that dies on one bad frame or a stray rejected
73
+ // promise leaves the box unmonitored. Log and keep going; but if errors are arriving in a
74
+ // storm the process state is probably bad, so exit and let the supervisor start it clean.
75
+ const recentFatals = [];
76
+ function survive(kind, err) {
77
+ console.error(`${kind}:`, err && err.stack ? err.stack : err);
78
+ const now = Date.now();
79
+ recentFatals.push(now);
80
+ while (recentFatals.length && now - recentFatals[0] > 60 * 1000) recentFatals.shift();
81
+ if (recentFatals.length > 10) {
82
+ console.error('Too many unexpected errors in the last minute — exiting for a clean restart.');
83
+ process.exit(1);
84
+ }
85
+ }
86
+ process.on('uncaughtException', (e) => survive('uncaughtException', e));
87
+ process.on('unhandledRejection', (e) => survive('unhandledRejection', e));
88
+
89
+ let ws = null;
90
+ let discoveryTimer = null;
91
+ let lastProcessFingerprint = null;
92
+ let updating = false;
93
+ let metricsTimer = null;
94
+ let reconnectDelay = RECONNECT_MIN_MS;
95
+ const activeTails = new Map(); // key `${app}:${stream}` -> tailer handle
96
+
97
+ function send(frame) {
98
+ if (ws && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(frame));
99
+ }
100
+
101
+ function pushMetrics() {
102
+ send({ type: 'metrics', ts: Date.now(), ...getSystemMetrics() });
103
+ }
104
+
105
+ function scheduleMetrics(intervalMs) {
106
+ if (metricsTimer) clearInterval(metricsTimer);
107
+ metricsTimer = setInterval(pushMetrics, intervalMs);
108
+ }
109
+
110
+ // Identity + state of every service the agent can see (no cpu/memory, which change
111
+ // constantly). A change means something was deployed, removed, stopped or restarted.
112
+ function processFingerprint() {
113
+ const systemd = checkSystemdAvailable();
114
+ return [
115
+ ...getPm2Processes().map((p) => `pm2:${p.name}:${p.status}`),
116
+ ...getDockerContainers().map((c) => `docker:${c.name}:${c.status}`),
117
+ ...(systemd.ok ? getSystemdUnits().map((u) => `systemd:${u.name}`) : []),
118
+ ]
119
+ .sort()
120
+ .join('\n');
121
+ }
122
+
123
+ // Cheap poll that pushes a full metrics frame as soon as the service set changes, so new
124
+ // services show up (and become selectable on the Logs page) without waiting for the next
125
+ // scheduled push or an agent restart.
126
+ function checkForNewServices() {
127
+ if (!ws || ws.readyState !== WebSocket.OPEN) return;
128
+ try {
129
+ const fp = processFingerprint();
130
+ if (lastProcessFingerprint !== null && fp !== lastProcessFingerprint) pushMetrics();
131
+ lastProcessFingerprint = fp;
132
+ } catch (e) {
133
+ // Discovery must never take the agent down.
134
+ }
135
+ }
136
+
137
+ function scheduleDiscovery() {
138
+ if (discoveryTimer) clearInterval(discoveryTimer);
139
+ lastProcessFingerprint = null; // first tick after (re)connect just records a baseline
140
+ discoveryTimer = setInterval(checkForNewServices, DISCOVERY_INTERVAL_MS);
141
+ }
142
+
143
+ // Operator-triggered (hub's restart-agent route). Exits cleanly and relies on the
144
+ // supervisor (systemd Restart=always, installed by install-agent.sh; or PM2) to start a
145
+ // fresh process — which also picks up OS group changes (docker, systemd-journal) that a
146
+ // running process never sees.
147
+ function performRestart() {
148
+ console.log('Restart requested by hub — exiting so the supervisor restarts this agent.');
149
+ stopAllTails();
150
+ setTimeout(() => process.exit(0), 200);
151
+ }
152
+
153
+ function resolveLogFile(app, stream) {
154
+ const proc = getPm2Processes().find((p) => p.name === app);
155
+ if (!proc) return null;
156
+ return stream === 'err' ? proc.err_log : proc.out_log;
157
+ }
158
+
159
+ function resolveDockerContainer(app) {
160
+ const container = getDockerContainers().find((c) => c.name === app);
161
+ return container ? container.containerId : null;
162
+ }
163
+
164
+ // Only ever hand journalctl a unit name that's in the agent's own live list — the name
165
+ // arrives over the wire from the hub.
166
+ function resolveSystemdUnit(app) {
167
+ const unit = getSystemdUnits().find((u) => u.name === app);
168
+ return unit ? unit.name : null;
169
+ }
170
+
171
+ function handleGetLogs(msg) {
172
+ let all;
173
+ if (msg.kind === 'systemd') {
174
+ all = getFilteredJournalRecords(resolveSystemdUnit(msg.app), msg.search, msg.level);
175
+ } else if (msg.kind === 'docker') {
176
+ const containerId = resolveDockerContainer(msg.app);
177
+ all = getFilteredDockerRecords(containerId, msg.stream, msg.search, msg.level);
178
+ } else {
179
+ const filePath = resolveLogFile(msg.app, msg.stream);
180
+ all = getFilteredRecords(filePath, msg.search, msg.level);
181
+ }
182
+ const records = all.slice(msg.offset || 0, (msg.offset || 0) + (msg.limit || 20));
183
+ send({ type: 'logs_chunk', requestId: msg.requestId, records, total: all.length });
184
+ }
185
+
186
+ function handleTailLogs(msg) {
187
+ const key = `${msg.kind}:${msg.app}:${msg.stream}`;
188
+ stopTail(key);
189
+ const search = msg.search,
190
+ level = msg.level;
191
+ function matches(record) {
192
+ if (level && String(record.level) !== String(level)) return false;
193
+ if (search && !JSON.stringify(record).toLowerCase().includes(search.toLowerCase()))
194
+ return false;
195
+ return true;
196
+ }
197
+ const onRecord = (record) =>
198
+ send({ type: 'log_line', app: msg.app, stream: msg.stream, kind: msg.kind, record });
199
+ let tailer;
200
+ if (msg.kind === 'systemd')
201
+ tailer = createJournalTailer(resolveSystemdUnit(msg.app), matches, onRecord);
202
+ else if (msg.kind === 'docker')
203
+ tailer = createDockerTailer(resolveDockerContainer(msg.app), msg.stream, matches, onRecord);
204
+ else tailer = createTailer(resolveLogFile(msg.app, msg.stream), matches, onRecord);
205
+ activeTails.set(key, tailer);
206
+ }
207
+
208
+ function stopTail(key) {
209
+ const existing = activeTails.get(key);
210
+ if (existing) {
211
+ existing.stop();
212
+ activeTails.delete(key);
213
+ }
214
+ }
215
+
216
+ function stopAllTails() {
217
+ for (const key of activeTails.keys()) stopTail(key);
218
+ }
219
+
220
+ // Request/response frames for the env-file editor (see lib/env-files.js,
221
+ // docs/env-files.md): every one is answered with exactly one 'rpc_result' carrying the
222
+ // hub's requestId, success or failure — a failure must never throw out of here and take
223
+ // the agent down.
224
+ async function handleRpc(msg, fn) {
225
+ try {
226
+ const result = await fn();
227
+ send({ type: 'rpc_result', requestId: msg.requestId, ...result, ok: true });
228
+ } catch (e) {
229
+ send({
230
+ type: 'rpc_result',
231
+ requestId: msg.requestId,
232
+ ok: false,
233
+ code: e.code || 'ERROR',
234
+ error: e.message || String(e),
235
+ });
236
+ }
237
+ }
238
+
239
+ // Triggered by the hub, never automatically — see lib/self-update.js. A failure here
240
+ // must never take the agent down: it logs and keeps running the code already loaded in
241
+ // memory, so a bad bundle doesn't leave this box unmonitored.
242
+ async function performSelfUpdate() {
243
+ if (updating) {
244
+ console.log('Self-update already in progress, ignoring duplicate request.');
245
+ return;
246
+ }
247
+ updating = true;
248
+ console.log(
249
+ 'Self-update requested by hub — downloading and installing the current agent bundle...',
250
+ );
251
+ try {
252
+ await selfUpdate({ hubUrl, instanceId, token, installDir: __dirname });
253
+ console.log(
254
+ 'Self-update succeeded — exiting so systemd restarts this service with the new code.',
255
+ );
256
+ process.exit(0);
257
+ } catch (e) {
258
+ console.error('Self-update failed, continuing to run the current version:', e.message);
259
+ updating = false;
260
+ }
261
+ }
262
+
263
+ function connect() {
264
+ ws = new WebSocket(hubUrl);
265
+
266
+ ws.on('open', () => {
267
+ send({
268
+ type: 'hello',
269
+ instanceId,
270
+ token,
271
+ bundleHash: AGENT_BUNDLE_HASH,
272
+ appVersion: AGENT_APP_VERSION,
273
+ tags,
274
+ capabilities: AGENT_CAPABILITIES,
275
+ });
276
+ });
277
+
278
+ ws.on('message', (raw) => {
279
+ let msg;
280
+ try {
281
+ msg = JSON.parse(raw);
282
+ } catch (e) {
283
+ return;
284
+ }
285
+ try {
286
+ handleFrame(msg);
287
+ } catch (e) {
288
+ console.error(`Error handling '${msg && msg.type}' frame:`, e && e.message);
289
+ }
290
+ });
291
+
292
+ function handleFrame(msg) {
293
+ if (msg.type === 'hello_ack') {
294
+ reconnectDelay = RECONNECT_MIN_MS;
295
+ pushMetrics();
296
+ scheduleMetrics(IDLE_INTERVAL_MS);
297
+ scheduleDiscovery();
298
+ } else if (msg.type === 'hello_reject') {
299
+ // Don't exit: a rejection can be transient (hub mid-deploy/migration) and exiting just
300
+ // makes the supervisor respawn us in a tight loop. The socket closes and the normal
301
+ // backoff reconnect (max 30s) retries; a genuinely bad token is fixed by reinstalling.
302
+ console.error('Hub rejected this agent (will keep retrying):', msg.reason);
303
+ } else if (msg.type === 'set_interval') {
304
+ scheduleMetrics(msg.ms);
305
+ } else if (msg.type === 'get_logs') {
306
+ handleGetLogs(msg);
307
+ } else if (msg.type === 'tail_logs') {
308
+ handleTailLogs(msg);
309
+ } else if (msg.type === 'stop_tail') {
310
+ stopTail(`${msg.kind}:${msg.app}:${msg.stream}`);
311
+ } else if (msg.type === 'self_update') {
312
+ performSelfUpdate();
313
+ } else if (msg.type === 'restart_agent') {
314
+ performRestart();
315
+ } else if (msg.type === 'env_read') {
316
+ handleRpc(msg, () => readEnvFile(msg.path));
317
+ } else if (msg.type === 'env_write') {
318
+ handleRpc(msg, () => writeEnvFile(msg.path, msg.content, msg.baseHash));
319
+ } else if (msg.type === 'service_restart') {
320
+ handleRpc(msg, () => restartUnit(msg.kind, msg.name));
321
+ }
322
+ }
323
+
324
+ ws.on('close', () => {
325
+ stopAllTails();
326
+ if (metricsTimer) {
327
+ clearInterval(metricsTimer);
328
+ metricsTimer = null;
329
+ }
330
+ if (discoveryTimer) {
331
+ clearInterval(discoveryTimer);
332
+ discoveryTimer = null;
333
+ }
334
+ scheduleReconnect();
335
+ });
336
+
337
+ ws.on('error', () => {}); // 'close' fires after 'error'; reconnect handled there
338
+ }
339
+
340
+ function scheduleReconnect() {
341
+ setTimeout(connect, reconnectDelay);
342
+ reconnectDelay = Math.min(reconnectDelay * 2, RECONNECT_MAX_MS);
343
+ }
344
+
345
+ connect();
346
+ console.log(
347
+ `Pulse agent starting — instance "${instanceId}", hub ${hubUrl}, v${AGENT_APP_VERSION} (bundle ${AGENT_BUNDLE_HASH})`,
348
+ );
349
+
350
+ const systemdCheck = checkSystemdAvailable();
351
+ if (systemdCheck.state === 'ok') {
352
+ console.log(
353
+ `systemd journal readable — ${getSystemdUnits().length} running service(s) visible to this agent.`,
354
+ );
355
+ } else if (systemdCheck.state === 'unreadable') {
356
+ console.log(
357
+ `systemd journal not readable by OS user '${systemdCheck.user}' — service logs won't be available. Fix: sudo usermod -aG systemd-journal ${systemdCheck.user} && sudo systemctl restart pulse-agent`,
358
+ );
359
+ } else {
360
+ console.log("systemd/journalctl not found — service logs won't be available.");
361
+ }
362
+
363
+ const dockerCheck = checkDockerAvailable();
364
+ if (dockerCheck.ok) {
365
+ console.log(
366
+ `Docker detected — ${getDockerContainers().length} container(s) visible to this agent.`,
367
+ );
368
+ } else {
369
+ console.log(
370
+ `Docker not usable from this agent (${dockerCheck.error}) — container logs won't be available. If this box runs Docker, make sure this agent's OS user is in the 'docker' group (or is root).`,
371
+ );
372
+ }