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
@@ -1,564 +1,564 @@
1
- // Live agent connections + relay state: everything the hub keeps in memory about
2
- // currently/recently connected agents, and everyone subscribed to their metrics/logs.
3
- // Shared by ws/agent-relay.js (the only writer of agentState/lastMetrics) and the
4
- // metrics/logs/instances route modules (readers + SSE subscribers).
5
-
6
- const crypto = require('crypto');
7
- const db = require('./db');
8
- const config = require('../config');
9
- const { serviceMatches } = require('./authz/scope');
10
- const authz = require('./authz');
11
- const authzStore = require('./authz-store');
12
-
13
- const agentState = new Map(); // instanceId -> { ws, lastMetrics, version, capabilities }
14
- // Every long-lived SSE subscriber holds the user's id plus the revision (rev) its cached
15
- // grants were computed at — never a rule snapshot it trusts forever. On a revision change
16
- // (authz.onRevision, below) or a stale rev at write time, the grants are re-derived from a
17
- // freshly built subject, and a stream whose access is gone gets `event: revoked` + end.
18
- const metricsSubscribers = new Map(); // instanceId -> Map<res, {userId, instanceId, rev, matchers}>
19
- const logTailSubscribers = new Map(); // `${instanceId}:${kind}:${app}:${stream}` -> Map<res, {userId, instanceId, app, rev}>
20
- const pendingLogRequests = new Map(); // requestId -> { resolve, timer }
21
- const pendingAgentRequests = new Map(); // requestId -> { instanceId, resolve, timer } — see requestAgent
22
- const instancesSubscribers = new Map(); // res -> {userId, rev, access, hadAccess} — see computeInstanceAccess
23
- // Set by a 'metrics' push (see ws/agent-relay.js's 'message' handler) rather than
24
- // broadcasting immediately on every single one — with several instances pushing every
25
- // few seconds, an immediate broadcast could be chattier than the polling this replaced.
26
- // A shared timer flushes at the same cadence the old client-side poll used, only when
27
- // something actually changed; a connect/disconnect/add/remove broadcasts immediately
28
- // instead of waiting for it, since those are rarer and worth showing right away.
29
- let instancesDirty = false;
30
-
31
- function sendToAgent(instanceId, frame) {
32
- const state = agentState.get(instanceId);
33
- if (state && state.ws && state.ws.readyState === state.ws.OPEN) {
34
- state.ws.send(JSON.stringify(frame));
35
- return true;
36
- }
37
- return false;
38
- }
39
-
40
- function isAgentConnected(instanceId) {
41
- const state = agentState.get(instanceId);
42
- return !!(state && state.ws && state.ws.readyState === state.ws.OPEN);
43
- }
44
-
45
- function desiredMetricsInterval(instanceId) {
46
- const subs = metricsSubscribers.get(instanceId);
47
- if (!subs || subs.size === 0) return config.IDLE_METRICS_INTERVAL_MS;
48
- let min = config.IDLE_METRICS_INTERVAL_MS;
49
- subs.forEach((sub, res) => {
50
- if (res._wantedIntervalMs < min) min = res._wantedIntervalMs;
51
- });
52
- return min;
53
- }
54
-
55
- // ---- SSE plumbing shared by every stream: safe writes, the revoke handshake, heartbeats ----
56
-
57
- function safeWrite(res, chunk) {
58
- if (res.writableEnded || res.destroyed) return false;
59
- try {
60
- res.write(chunk);
61
- return true;
62
- } catch (e) {
63
- return false;
64
- }
65
- }
66
-
67
- // The revocation handshake (docs/auth-model.md): `event: revoked` so the browser can tell a
68
- // permission loss from a network blip, then end the response. The frontend reconnects and
69
- // gets a 403 / an empty list from the normal gate.
70
- function endRevoked(res) {
71
- safeWrite(res, 'event: revoked\ndata: {}\n\n');
72
- try {
73
- res.end();
74
- } catch (e) {
75
- /* already gone */
76
- }
77
- }
78
-
79
- // Keeps an SSE connection alive through proxies. Stops as soon as the response closes OR
80
- // ends (a revoked stream is ended server-side) so it can never write after end.
81
- function startHeartbeat(res, ms = 15000) {
82
- const hb = setInterval(() => safeWrite(res, ':hb\n\n'), ms);
83
- hb.unref();
84
- const stop = () => clearInterval(hb);
85
- res.on('close', stop);
86
- res.on('finish', stop);
87
- return stop;
88
- }
89
-
90
- // A fresh authorization context for a user id, or null if the user no longer exists.
91
- // Always built from the database at call time — never cached across calls.
92
- function contextForUser(userId) {
93
- const user = db.getUserById(userId);
94
- return user ? authz.forRequest(user) : null;
95
- }
96
-
97
- // ---- metrics SSE ----
98
-
99
- function removeMetricsSub(instanceId, res) {
100
- const subs = metricsSubscribers.get(instanceId);
101
- if (!subs || !subs.delete(res)) return;
102
- if (subs.size === 0) metricsSubscribers.delete(instanceId);
103
- sendToAgent(instanceId, { type: 'set_interval', ms: desiredMetricsInterval(instanceId) });
104
- }
105
-
106
- // Re-derives this subscriber's grants from a fresh subject. Returns false (after ending the
107
- // stream with `revoked`) if the user is gone, the server is gone, or they no longer hold
108
- // servers.view + metrics.view on it. Otherwise refreshes the service matchers.
109
- function revalidateMetricsSub(instanceId, res, sub) {
110
- const rev = authz.getRevision();
111
- const ctx = contextForUser(sub.userId);
112
- let matchers = [];
113
- if (ctx && db.getInstance(instanceId) && ctx.can('servers.view', { instanceId })) {
114
- matchers = ctx.serviceMatchersFor('metrics.view', instanceId);
115
- }
116
- // null = unrestricted; [] = no rule grants metrics.view here.
117
- if (matchers !== null && matchers.length === 0) {
118
- removeMetricsSub(instanceId, res);
119
- endRevoked(res);
120
- return false;
121
- }
122
- sub.matchers = matchers;
123
- sub.rev = rev;
124
- return true;
125
- }
126
-
127
- // Returns false if the stream was revoked on the spot (the caller must stop using res).
128
- function subscribeMetrics(instanceId, res, wantedIntervalMs, userId) {
129
- res._wantedIntervalMs = wantedIntervalMs;
130
- const sub = { userId, instanceId, rev: null, matchers: null };
131
- if (!metricsSubscribers.has(instanceId)) metricsSubscribers.set(instanceId, new Map());
132
- metricsSubscribers.get(instanceId).set(res, sub);
133
- res.on('close', () => removeMetricsSub(instanceId, res));
134
- if (!revalidateMetricsSub(instanceId, res, sub)) return false;
135
- sendToAgent(instanceId, { type: 'set_interval', ms: desiredMetricsInterval(instanceId) });
136
- return true;
137
- }
138
-
139
- // Each subscriber has its own service restriction, so the same push from the agent gets
140
- // filtered differently per open browser tab rather than broadcasting one shared payload.
141
- // A subscriber whose rev is stale is revalidated before anything is written to it.
142
- function broadcastMetrics(instanceId, metrics) {
143
- const subs = metricsSubscribers.get(instanceId);
144
- if (!subs) return;
145
- const rev = authz.getRevision();
146
- subs.forEach((sub, res) => {
147
- if (sub.rev !== rev && !revalidateMetricsSub(instanceId, res, sub)) return;
148
- safeWrite(res, `data: ${JSON.stringify(filterMetricsForProcesses(metrics, sub.matchers))}\n\n`);
149
- });
150
- }
151
-
152
- // Whether a process/app/container name passes a policy's service matchers (see
153
- // authz/scope.js). `matchers` null means unrestricted. An empty list is NOT "all" here
154
- // (unlike scope.serviceMatches) — it means no grant at all, so it denies everything.
155
- function serviceAllowed(name, matchers) {
156
- if (!matchers) return true;
157
- if (matchers.length === 0) return false;
158
- return serviceMatches(matchers, name);
159
- }
160
-
161
- // Narrows a raw agent sample's process-shaped fields to the services a user's policies
162
- // allow (see gate() in middleware/authz.js) — used by every route that could otherwise
163
- // leak process detail outside a policy's service scope. `matchers` null means
164
- // unrestricted, so this is a no-op for anyone not service-scoped.
165
- function filterMetricsForProcesses(metrics, matchers) {
166
- if (!metrics || !matchers) return metrics;
167
- const keep = (p) => serviceAllowed(p.name, matchers);
168
- return {
169
- ...metrics,
170
- top_cpu: (metrics.top_cpu || []).filter(keep),
171
- top_mem: (metrics.top_mem || []).filter(keep),
172
- processes: (metrics.processes || []).filter(keep),
173
- };
174
- }
175
-
176
- // What a user may see in the instance list, derived from a fresh authorization context
177
- // (never cached across requests): which servers (null = all), on which of them
178
- // metrics.view is NOT granted (their rows carry no metrics/hostname), and on which they
179
- // hold servers.tags.manage (only those rows carry the access tags — they are authorization
180
- // structure, not something every viewer needs).
181
- function computeInstanceAccess(ctx) {
182
- const allowedIds = ctx.resolveInstanceIds('servers.view');
183
- const all = db.listInstances();
184
- const visible = allowedIds ? all.filter((i) => allowedIds.has(i.id)) : all;
185
- const metricsDenied = new Set();
186
- const tagManage = new Set();
187
- for (const i of visible) {
188
- const m = ctx.serviceMatchersFor('metrics.view', i.id);
189
- if (m !== null && m.length === 0) metricsDenied.add(i.id);
190
- if (ctx.can('servers.tags.manage', { instanceId: i.id })) tagManage.add(i.id);
191
- }
192
- return { allowedIds, metricsDenied, tagManage };
193
- }
194
-
195
- // The unrestricted rows (every instance, full metrics) — shape GET /api/instances has
196
- // always returned. See docs/metrics.md for what lastMetrics carries; only a lean subset
197
- // of it travels here (top processes etc. stay fetched on demand for the detail view).
198
- function buildFullInstancesList() {
199
- return db.listInstances().map((i) => {
200
- const state = agentState.get(i.id);
201
- const m = state && state.lastMetrics;
202
- return {
203
- id: i.id,
204
- label: i.label,
205
- createdAt: i.created_at,
206
- connected: isAgentConnected(i.id),
207
- everConnected: !!i.first_connected_at,
208
- hostname: m ? m.hostname : null,
209
- isSelf: !!i.is_self,
210
- tags: db.getInstanceTags(i.id),
211
- // The agent's human-facing semver (see .claude/rules/version-bump-policy.md) — NOT
212
- // the staleness signal. updateAvailable below is computed from the bundle content
213
- // hash instead, which changes with every agent-relevant code change regardless of
214
- // whether anyone remembered to bump appVersion.
215
- agentVersion: state ? state.appVersion : null,
216
- updateAvailable: !!(state && state.bundleHash && state.bundleHash !== config.HUB_BUNDLE_HASH),
217
- metrics: m
218
- ? {
219
- mem_used_percent: m.mem_used_percent,
220
- mem_used_mb: m.mem_used_mb,
221
- mem_total_mb: m.mem_total_mb,
222
- disk_percent: m.disk_percent,
223
- disk_used: m.disk_used,
224
- disk_total: m.disk_total,
225
- load_avg: m.load_avg,
226
- cpu_count: m.cpu_count,
227
- uptime_str: m.uptime_str,
228
- }
229
- : null,
230
- };
231
- });
232
- }
233
-
234
- // Narrows full rows to one user's `access` (see computeInstanceAccess).
235
- function applyInstanceAccess(rows, access) {
236
- const visible = access.allowedIds ? rows.filter((i) => access.allowedIds.has(i.id)) : rows;
237
- return visible.map((i) => {
238
- const out = access.metricsDenied.has(i.id) ? { ...i, metrics: null, hostname: null } : { ...i };
239
- if (access.tagManage.has(i.id)) out.accessTags = authzStore.getInstanceAuthTags(i.id);
240
- return out;
241
- });
242
- }
243
-
244
- // `access` is a computeInstanceAccess() result, or null for the unrestricted internal view.
245
- function buildInstancesList(access) {
246
- const rows = buildFullInstancesList();
247
- return access ? applyInstanceAccess(rows, access) : rows;
248
- }
249
-
250
- function hasAnyInstanceAccess(access) {
251
- return access.allowedIds === null || access.allowedIds.size > 0;
252
- }
253
-
254
- // Re-derives an instances subscriber's view. Returns false (stream ended with `revoked`) if
255
- // the user is gone, or lost every server they could previously see; a partial loss just
256
- // narrows the list (the caller pushes it).
257
- function revalidateInstancesSub(res, sub) {
258
- const rev = authz.getRevision();
259
- const ctx = contextForUser(sub.userId);
260
- if (!ctx) {
261
- instancesSubscribers.delete(res);
262
- endRevoked(res);
263
- return false;
264
- }
265
- const access = computeInstanceAccess(ctx);
266
- const some = hasAnyInstanceAccess(access);
267
- if (!some && sub.hadAccess) {
268
- instancesSubscribers.delete(res);
269
- endRevoked(res);
270
- return false;
271
- }
272
- if (some) sub.hadAccess = true;
273
- sub.access = access;
274
- sub.rev = rev;
275
- return true;
276
- }
277
-
278
- // Registers the stream and derives its access from a fresh subject. Returns the
279
- // subscription (sub.access is what the caller builds the initial list from), or null if the
280
- // user no longer exists (stream already ended with `revoked`).
281
- function subscribeInstances(res, userId) {
282
- const sub = { userId, rev: null, access: null, hadAccess: false };
283
- instancesSubscribers.set(res, sub);
284
- res.on('close', () => instancesSubscribers.delete(res));
285
- return revalidateInstancesSub(res, sub) ? sub : null;
286
- }
287
-
288
- // Computes + writes the list to every open /api/instances/stream connection right now,
289
- // bypassing the throttle — used for events worth showing immediately (connect,
290
- // disconnect, add, remove, mark-self, prune) rather than the ~10s metrics-driven flush
291
- // below. A no-op (skips the DB query entirely) when nobody is subscribed. Builds the
292
- // unrestricted list once and narrows it per subscriber; a subscriber whose rev is stale is
293
- // revalidated first.
294
- function broadcastInstancesNow() {
295
- instancesDirty = false;
296
- if (instancesSubscribers.size === 0) return;
297
- const full = buildFullInstancesList();
298
- const rev = authz.getRevision();
299
- instancesSubscribers.forEach((sub, res) => {
300
- if (sub.rev !== rev && !revalidateInstancesSub(res, sub)) return;
301
- safeWrite(res, `data: ${JSON.stringify(applyInstanceAccess(full, sub.access))}\n\n`);
302
- });
303
- }
304
-
305
- function markInstancesDirty() {
306
- instancesDirty = true;
307
- }
308
-
309
- // ---- log tail SSE ----
310
-
311
- function removeLogTailSub(key, res) {
312
- const subs = logTailSubscribers.get(key);
313
- if (!subs || !subs.delete(res)) return;
314
- if (subs.size === 0) {
315
- logTailSubscribers.delete(key);
316
- const [instanceId, kind, app, stream] = splitLogKey(key);
317
- sendToAgent(instanceId, { type: 'stop_tail', app, stream, kind });
318
- }
319
- }
320
-
321
- // key = `${instanceId}:${kind}:${app}:${stream}`. instanceId/kind/stream never contain ':',
322
- // but an app (a container/unit name) can, so only the first two and the last part are split off.
323
- function splitLogKey(key) {
324
- const first = key.indexOf(':');
325
- const second = key.indexOf(':', first + 1);
326
- const last = key.lastIndexOf(':');
327
- return [
328
- key.slice(0, first),
329
- key.slice(first + 1, second),
330
- key.slice(second + 1, last),
331
- key.slice(last + 1),
332
- ];
333
- }
334
-
335
- function revalidateLogTailSub(key, res, sub) {
336
- const rev = authz.getRevision();
337
- const ctx = contextForUser(sub.userId);
338
- let ok = false;
339
- if (
340
- ctx &&
341
- db.getInstance(sub.instanceId) &&
342
- ctx.can('servers.view', { instanceId: sub.instanceId })
343
- ) {
344
- ok = serviceAllowed(sub.app, ctx.serviceMatchersFor('logs.view', sub.instanceId));
345
- }
346
- if (!ok) {
347
- removeLogTailSub(key, res);
348
- endRevoked(res);
349
- return false;
350
- }
351
- sub.rev = rev;
352
- return true;
353
- }
354
-
355
- // Returns false if the stream was revoked on the spot (the caller must stop using res).
356
- function subscribeLogTail(instanceId, app, stream, kind, search, level, res, userId) {
357
- const key = `${instanceId}:${kind}:${app}:${stream}`;
358
- if (!logTailSubscribers.has(key)) logTailSubscribers.set(key, new Map());
359
- const subs = logTailSubscribers.get(key);
360
- const isFirst = subs.size === 0;
361
- const sub = { userId, instanceId, app, rev: null };
362
- subs.set(res, sub);
363
- res.on('close', () => removeLogTailSub(key, res));
364
- if (!revalidateLogTailSub(key, res, sub)) return false;
365
- if (isFirst) sendToAgent(instanceId, { type: 'tail_logs', app, stream, kind, search, level });
366
- return true;
367
- }
368
-
369
- // Fan-out for an agent's 'log_line' frame (ws/agent-relay.js); revalidates stale subscribers
370
- // before writing.
371
- function broadcastLogLine(instanceId, kind, app, stream, record) {
372
- const key = `${instanceId}:${kind}:${app}:${stream}`;
373
- const subs = logTailSubscribers.get(key);
374
- if (!subs) return;
375
- const rev = authz.getRevision();
376
- const payload = `data: ${JSON.stringify(record)}\n\n`;
377
- subs.forEach((sub, res) => {
378
- if (sub.rev !== rev && !revalidateLogTailSub(key, res, sub)) return;
379
- safeWrite(res, payload);
380
- });
381
- }
382
-
383
- // ---- revocation sweep ----
384
-
385
- // Walks every open stream and re-derives its access from the database. Called immediately
386
- // on an authorization revision event (so an idle stream is closed too, not just the next
387
- // time something is written to it) and on a slow timer as a backstop for any change that
388
- // didn't bump the revision. `push` re-sends the (possibly narrowed) instance list to
389
- // instances subscribers that survive.
390
- function revalidateAll({ push = false } = {}) {
391
- metricsSubscribers.forEach((subs, instanceId) => {
392
- subs.forEach((sub, res) => revalidateMetricsSub(instanceId, res, sub));
393
- });
394
- logTailSubscribers.forEach((subs, key) => {
395
- subs.forEach((sub, res) => revalidateLogTailSub(key, res, sub));
396
- });
397
- const survivors = [];
398
- instancesSubscribers.forEach((sub, res) => {
399
- if (revalidateInstancesSub(res, sub)) survivors.push([sub, res]);
400
- });
401
- if (push && survivors.length) {
402
- const full = buildFullInstancesList();
403
- for (const [sub, res] of survivors) {
404
- safeWrite(res, `data: ${JSON.stringify(applyInstanceAccess(full, sub.access))}\n\n`);
405
- }
406
- }
407
- }
408
-
409
- authz.onRevision(() => {
410
- // Runs after the mutating transaction has committed (and inside the request that made it):
411
- // a failure here must never turn a successful change into an error response. The 30s
412
- // sweep below is the backstop.
413
- try {
414
- revalidateAll({ push: true });
415
- } catch (e) {
416
- console.error('[relay-state] revalidation after an authorization change failed:', e);
417
- }
418
- });
419
-
420
- function requestLogs(instanceId, params) {
421
- return new Promise((resolve) => {
422
- if (!isAgentConnected(instanceId)) {
423
- resolve({ records: [], total: 0, offline: true });
424
- return;
425
- }
426
- const requestId = crypto.randomBytes(8).toString('hex');
427
- const timer = setTimeout(() => {
428
- pendingLogRequests.delete(requestId);
429
- resolve({ records: [], total: 0, offline: true });
430
- }, config.LOG_REQUEST_TIMEOUT_MS);
431
- pendingLogRequests.set(requestId, { resolve, timer });
432
- sendToAgent(instanceId, { type: 'get_logs', requestId, ...params });
433
- });
434
- }
435
-
436
- // Generic hub -> agent request/response (the env-file editor's read/write/restart — see
437
- // docs/env-files.md). Unlike requestLogs, offline and timeout are distinct, and the agent's
438
- // own failure (permission denied, conflict, ...) comes back as `{ ok:false, code, error }`
439
- // rather than being flattened into "offline". Always resolves, never rejects.
440
- function requestAgent(instanceId, frame, timeoutMs) {
441
- return new Promise((resolve) => {
442
- if (!isAgentConnected(instanceId)) {
443
- resolve({ ok: false, code: 'OFFLINE', error: 'Instance is offline.' });
444
- return;
445
- }
446
- const requestId = crypto.randomBytes(8).toString('hex');
447
- const timer = setTimeout(() => {
448
- pendingAgentRequests.delete(requestId);
449
- resolve({ ok: false, code: 'TIMEOUT', error: 'The agent did not respond in time.' });
450
- }, timeoutMs || config.ENV_RPC_TIMEOUT_MS);
451
- pendingAgentRequests.set(requestId, { instanceId, resolve, timer });
452
- if (!sendToAgent(instanceId, { ...frame, requestId })) {
453
- clearTimeout(timer);
454
- pendingAgentRequests.delete(requestId);
455
- resolve({ ok: false, code: 'OFFLINE', error: 'Instance is offline.' });
456
- }
457
- });
458
- }
459
-
460
- // Called by ws/agent-relay.js when an agent's 'rpc_result' frame arrives. Ignores a result
461
- // whose requestId belongs to a different instance's request.
462
- function resolveAgentRequest(instanceId, msg) {
463
- const pending = pendingAgentRequests.get(msg.requestId);
464
- if (!pending || pending.instanceId !== instanceId) return;
465
- clearTimeout(pending.timer);
466
- pendingAgentRequests.delete(msg.requestId);
467
- const result = { ...msg };
468
- delete result.type;
469
- delete result.requestId;
470
- pending.resolve(result);
471
- }
472
-
473
- // A closed socket can never answer, so fail its in-flight requests now instead of making
474
- // the operator wait out the timeout.
475
- function failPendingAgentRequests(instanceId, code, error) {
476
- for (const [requestId, pending] of pendingAgentRequests) {
477
- if (pending.instanceId !== instanceId) continue;
478
- clearTimeout(pending.timer);
479
- pendingAgentRequests.delete(requestId);
480
- pending.resolve({ ok: false, code, error });
481
- }
482
- }
483
-
484
- function agentHasCapability(instanceId, capability) {
485
- const state = agentState.get(instanceId);
486
- return !!(state && Array.isArray(state.capabilities) && state.capabilities.includes(capability));
487
- }
488
-
489
- function readInstanceHistory(instanceId) {
490
- return db.getHistoryForInstance(instanceId, Date.now() - config.HISTORY_RETENTION_MS);
491
- }
492
-
493
- function appendInstanceHistorySample(instanceId, metrics) {
494
- const cpuPercentApprox = Math.min(
495
- 100,
496
- (parseFloat(metrics.load_avg[0]) / metrics.cpu_count) * 100,
497
- );
498
- db.insertMetricSample(instanceId, {
499
- ts: metrics.ts || Date.now(),
500
- cpu: Number(cpuPercentApprox.toFixed(1)),
501
- mem: Number(metrics.mem_used_percent),
502
- disk: parseFloat(metrics.disk_percent) || 0,
503
- net_rx: metrics.network.rx_bytes,
504
- net_tx: metrics.network.tx_bytes,
505
- });
506
- }
507
-
508
- // Replaces the old "read whole file, filter, rewrite whole file" pruning — an indexed
509
- // DELETE across every instance at once. getHistoryForInstance still applies the same
510
- // cutoff itself on every read, so a read never shows stale rows even between prune runs.
511
- // Timers are unref()'d: they must never be what keeps a process (e.g. a test run) alive —
512
- // the hub's HTTP server does that in production.
513
- setInterval(
514
- () => db.pruneMetricsOlderThan(Date.now() - config.HISTORY_RETENTION_MS),
515
- config.HISTORY_PRUNE_INTERVAL_MS,
516
- ).unref();
517
- setInterval(() => {
518
- const before = db.listInstances().length;
519
- db.pruneNeverConnectedInstancesOlderThan(Date.now() - config.NEVER_CONNECTED_TTL_MS);
520
- // A pruned instance is an instance delete: bump the authorization revision so any stream
521
- // still pointing at it revalidates (and closes).
522
- if (db.listInstances().length !== before) authz.bumpRevision();
523
- broadcastInstancesNow();
524
- }, config.HISTORY_PRUNE_INTERVAL_MS).unref();
525
- setInterval(() => {
526
- if (instancesDirty) broadcastInstancesNow();
527
- }, config.INSTANCES_BROADCAST_INTERVAL_MS).unref();
528
- // Backstop for any access change that didn't bump the revision (or a user deleted by some
529
- // other path): every open stream re-derives its grants from the database this often.
530
- setInterval(() => revalidateAll({ push: false }), 30 * 1000).unref();
531
-
532
- module.exports = {
533
- agentState,
534
- metricsSubscribers,
535
- logTailSubscribers,
536
- pendingLogRequests,
537
- instancesSubscribers,
538
- sendToAgent,
539
- isAgentConnected,
540
- desiredMetricsInterval,
541
- subscribeMetrics,
542
- broadcastMetrics,
543
- serviceAllowed,
544
- filterMetricsForProcesses,
545
- buildInstancesList,
546
- computeInstanceAccess,
547
- contextForUser,
548
- safeWrite,
549
- endRevoked,
550
- startHeartbeat,
551
- revalidateAll,
552
- broadcastLogLine,
553
- subscribeInstances,
554
- broadcastInstancesNow,
555
- markInstancesDirty,
556
- subscribeLogTail,
557
- requestLogs,
558
- requestAgent,
559
- resolveAgentRequest,
560
- failPendingAgentRequests,
561
- agentHasCapability,
562
- readInstanceHistory,
563
- appendInstanceHistorySample,
564
- };
1
+ // Live agent connections + relay state: everything the hub keeps in memory about
2
+ // currently/recently connected agents, and everyone subscribed to their metrics/logs.
3
+ // Shared by ws/agent-relay.js (the only writer of agentState/lastMetrics) and the
4
+ // metrics/logs/instances route modules (readers + SSE subscribers).
5
+
6
+ const crypto = require('crypto');
7
+ const db = require('./db');
8
+ const config = require('../config');
9
+ const { serviceMatches } = require('./authz/scope');
10
+ const authz = require('./authz');
11
+ const authzStore = require('./authz-store');
12
+
13
+ const agentState = new Map(); // instanceId -> { ws, lastMetrics, version, capabilities }
14
+ // Every long-lived SSE subscriber holds the user's id plus the revision (rev) its cached
15
+ // grants were computed at — never a rule snapshot it trusts forever. On a revision change
16
+ // (authz.onRevision, below) or a stale rev at write time, the grants are re-derived from a
17
+ // freshly built subject, and a stream whose access is gone gets `event: revoked` + end.
18
+ const metricsSubscribers = new Map(); // instanceId -> Map<res, {userId, instanceId, rev, matchers}>
19
+ const logTailSubscribers = new Map(); // `${instanceId}:${kind}:${app}:${stream}` -> Map<res, {userId, instanceId, app, rev}>
20
+ const pendingLogRequests = new Map(); // requestId -> { resolve, timer }
21
+ const pendingAgentRequests = new Map(); // requestId -> { instanceId, resolve, timer } — see requestAgent
22
+ const instancesSubscribers = new Map(); // res -> {userId, rev, access, hadAccess} — see computeInstanceAccess
23
+ // Set by a 'metrics' push (see ws/agent-relay.js's 'message' handler) rather than
24
+ // broadcasting immediately on every single one — with several instances pushing every
25
+ // few seconds, an immediate broadcast could be chattier than the polling this replaced.
26
+ // A shared timer flushes at the same cadence the old client-side poll used, only when
27
+ // something actually changed; a connect/disconnect/add/remove broadcasts immediately
28
+ // instead of waiting for it, since those are rarer and worth showing right away.
29
+ let instancesDirty = false;
30
+
31
+ function sendToAgent(instanceId, frame) {
32
+ const state = agentState.get(instanceId);
33
+ if (state && state.ws && state.ws.readyState === state.ws.OPEN) {
34
+ state.ws.send(JSON.stringify(frame));
35
+ return true;
36
+ }
37
+ return false;
38
+ }
39
+
40
+ function isAgentConnected(instanceId) {
41
+ const state = agentState.get(instanceId);
42
+ return !!(state && state.ws && state.ws.readyState === state.ws.OPEN);
43
+ }
44
+
45
+ function desiredMetricsInterval(instanceId) {
46
+ const subs = metricsSubscribers.get(instanceId);
47
+ if (!subs || subs.size === 0) return config.IDLE_METRICS_INTERVAL_MS;
48
+ let min = config.IDLE_METRICS_INTERVAL_MS;
49
+ subs.forEach((sub, res) => {
50
+ if (res._wantedIntervalMs < min) min = res._wantedIntervalMs;
51
+ });
52
+ return min;
53
+ }
54
+
55
+ // ---- SSE plumbing shared by every stream: safe writes, the revoke handshake, heartbeats ----
56
+
57
+ function safeWrite(res, chunk) {
58
+ if (res.writableEnded || res.destroyed) return false;
59
+ try {
60
+ res.write(chunk);
61
+ return true;
62
+ } catch (e) {
63
+ return false;
64
+ }
65
+ }
66
+
67
+ // The revocation handshake (docs/auth-model.md): `event: revoked` so the browser can tell a
68
+ // permission loss from a network blip, then end the response. The frontend reconnects and
69
+ // gets a 403 / an empty list from the normal gate.
70
+ function endRevoked(res) {
71
+ safeWrite(res, 'event: revoked\ndata: {}\n\n');
72
+ try {
73
+ res.end();
74
+ } catch (e) {
75
+ /* already gone */
76
+ }
77
+ }
78
+
79
+ // Keeps an SSE connection alive through proxies. Stops as soon as the response closes OR
80
+ // ends (a revoked stream is ended server-side) so it can never write after end.
81
+ function startHeartbeat(res, ms = 15000) {
82
+ const hb = setInterval(() => safeWrite(res, ':hb\n\n'), ms);
83
+ hb.unref();
84
+ const stop = () => clearInterval(hb);
85
+ res.on('close', stop);
86
+ res.on('finish', stop);
87
+ return stop;
88
+ }
89
+
90
+ // A fresh authorization context for a user id, or null if the user no longer exists.
91
+ // Always built from the database at call time — never cached across calls.
92
+ function contextForUser(userId) {
93
+ const user = db.getUserById(userId);
94
+ return user ? authz.forRequest(user) : null;
95
+ }
96
+
97
+ // ---- metrics SSE ----
98
+
99
+ function removeMetricsSub(instanceId, res) {
100
+ const subs = metricsSubscribers.get(instanceId);
101
+ if (!subs || !subs.delete(res)) return;
102
+ if (subs.size === 0) metricsSubscribers.delete(instanceId);
103
+ sendToAgent(instanceId, { type: 'set_interval', ms: desiredMetricsInterval(instanceId) });
104
+ }
105
+
106
+ // Re-derives this subscriber's grants from a fresh subject. Returns false (after ending the
107
+ // stream with `revoked`) if the user is gone, the server is gone, or they no longer hold
108
+ // servers.view + metrics.view on it. Otherwise refreshes the service matchers.
109
+ function revalidateMetricsSub(instanceId, res, sub) {
110
+ const rev = authz.getRevision();
111
+ const ctx = contextForUser(sub.userId);
112
+ let matchers = [];
113
+ if (ctx && db.getInstance(instanceId) && ctx.can('servers.view', { instanceId })) {
114
+ matchers = ctx.serviceMatchersFor('metrics.view', instanceId);
115
+ }
116
+ // null = unrestricted; [] = no rule grants metrics.view here.
117
+ if (matchers !== null && matchers.length === 0) {
118
+ removeMetricsSub(instanceId, res);
119
+ endRevoked(res);
120
+ return false;
121
+ }
122
+ sub.matchers = matchers;
123
+ sub.rev = rev;
124
+ return true;
125
+ }
126
+
127
+ // Returns false if the stream was revoked on the spot (the caller must stop using res).
128
+ function subscribeMetrics(instanceId, res, wantedIntervalMs, userId) {
129
+ res._wantedIntervalMs = wantedIntervalMs;
130
+ const sub = { userId, instanceId, rev: null, matchers: null };
131
+ if (!metricsSubscribers.has(instanceId)) metricsSubscribers.set(instanceId, new Map());
132
+ metricsSubscribers.get(instanceId).set(res, sub);
133
+ res.on('close', () => removeMetricsSub(instanceId, res));
134
+ if (!revalidateMetricsSub(instanceId, res, sub)) return false;
135
+ sendToAgent(instanceId, { type: 'set_interval', ms: desiredMetricsInterval(instanceId) });
136
+ return true;
137
+ }
138
+
139
+ // Each subscriber has its own service restriction, so the same push from the agent gets
140
+ // filtered differently per open browser tab rather than broadcasting one shared payload.
141
+ // A subscriber whose rev is stale is revalidated before anything is written to it.
142
+ function broadcastMetrics(instanceId, metrics) {
143
+ const subs = metricsSubscribers.get(instanceId);
144
+ if (!subs) return;
145
+ const rev = authz.getRevision();
146
+ subs.forEach((sub, res) => {
147
+ if (sub.rev !== rev && !revalidateMetricsSub(instanceId, res, sub)) return;
148
+ safeWrite(res, `data: ${JSON.stringify(filterMetricsForProcesses(metrics, sub.matchers))}\n\n`);
149
+ });
150
+ }
151
+
152
+ // Whether a process/app/container name passes a policy's service matchers (see
153
+ // authz/scope.js). `matchers` null means unrestricted. An empty list is NOT "all" here
154
+ // (unlike scope.serviceMatches) — it means no grant at all, so it denies everything.
155
+ function serviceAllowed(name, matchers) {
156
+ if (!matchers) return true;
157
+ if (matchers.length === 0) return false;
158
+ return serviceMatches(matchers, name);
159
+ }
160
+
161
+ // Narrows a raw agent sample's process-shaped fields to the services a user's policies
162
+ // allow (see gate() in middleware/authz.js) — used by every route that could otherwise
163
+ // leak process detail outside a policy's service scope. `matchers` null means
164
+ // unrestricted, so this is a no-op for anyone not service-scoped.
165
+ function filterMetricsForProcesses(metrics, matchers) {
166
+ if (!metrics || !matchers) return metrics;
167
+ const keep = (p) => serviceAllowed(p.name, matchers);
168
+ return {
169
+ ...metrics,
170
+ top_cpu: (metrics.top_cpu || []).filter(keep),
171
+ top_mem: (metrics.top_mem || []).filter(keep),
172
+ processes: (metrics.processes || []).filter(keep),
173
+ };
174
+ }
175
+
176
+ // What a user may see in the instance list, derived from a fresh authorization context
177
+ // (never cached across requests): which servers (null = all), on which of them
178
+ // metrics.view is NOT granted (their rows carry no metrics/hostname), and on which they
179
+ // hold servers.tags.manage (only those rows carry the access tags — they are authorization
180
+ // structure, not something every viewer needs).
181
+ function computeInstanceAccess(ctx) {
182
+ const allowedIds = ctx.resolveInstanceIds('servers.view');
183
+ const all = db.listInstances();
184
+ const visible = allowedIds ? all.filter((i) => allowedIds.has(i.id)) : all;
185
+ const metricsDenied = new Set();
186
+ const tagManage = new Set();
187
+ for (const i of visible) {
188
+ const m = ctx.serviceMatchersFor('metrics.view', i.id);
189
+ if (m !== null && m.length === 0) metricsDenied.add(i.id);
190
+ if (ctx.can('servers.tags.manage', { instanceId: i.id })) tagManage.add(i.id);
191
+ }
192
+ return { allowedIds, metricsDenied, tagManage };
193
+ }
194
+
195
+ // The unrestricted rows (every instance, full metrics) — shape GET /api/instances has
196
+ // always returned. See docs/metrics.md for what lastMetrics carries; only a lean subset
197
+ // of it travels here (top processes etc. stay fetched on demand for the detail view).
198
+ function buildFullInstancesList() {
199
+ return db.listInstances().map((i) => {
200
+ const state = agentState.get(i.id);
201
+ const m = state && state.lastMetrics;
202
+ return {
203
+ id: i.id,
204
+ label: i.label,
205
+ createdAt: i.created_at,
206
+ connected: isAgentConnected(i.id),
207
+ everConnected: !!i.first_connected_at,
208
+ hostname: m ? m.hostname : null,
209
+ isSelf: !!i.is_self,
210
+ tags: db.getInstanceTags(i.id),
211
+ // The agent's human-facing semver (see .claude/rules/version-bump-policy.md) — NOT
212
+ // the staleness signal. updateAvailable below is computed from the bundle content
213
+ // hash instead, which changes with every agent-relevant code change regardless of
214
+ // whether anyone remembered to bump appVersion.
215
+ agentVersion: state ? state.appVersion : null,
216
+ updateAvailable: !!(state && state.bundleHash && state.bundleHash !== config.HUB_BUNDLE_HASH),
217
+ metrics: m
218
+ ? {
219
+ mem_used_percent: m.mem_used_percent,
220
+ mem_used_mb: m.mem_used_mb,
221
+ mem_total_mb: m.mem_total_mb,
222
+ disk_percent: m.disk_percent,
223
+ disk_used: m.disk_used,
224
+ disk_total: m.disk_total,
225
+ load_avg: m.load_avg,
226
+ cpu_count: m.cpu_count,
227
+ uptime_str: m.uptime_str,
228
+ }
229
+ : null,
230
+ };
231
+ });
232
+ }
233
+
234
+ // Narrows full rows to one user's `access` (see computeInstanceAccess).
235
+ function applyInstanceAccess(rows, access) {
236
+ const visible = access.allowedIds ? rows.filter((i) => access.allowedIds.has(i.id)) : rows;
237
+ return visible.map((i) => {
238
+ const out = access.metricsDenied.has(i.id) ? { ...i, metrics: null, hostname: null } : { ...i };
239
+ if (access.tagManage.has(i.id)) out.accessTags = authzStore.getInstanceAuthTags(i.id);
240
+ return out;
241
+ });
242
+ }
243
+
244
+ // `access` is a computeInstanceAccess() result, or null for the unrestricted internal view.
245
+ function buildInstancesList(access) {
246
+ const rows = buildFullInstancesList();
247
+ return access ? applyInstanceAccess(rows, access) : rows;
248
+ }
249
+
250
+ function hasAnyInstanceAccess(access) {
251
+ return access.allowedIds === null || access.allowedIds.size > 0;
252
+ }
253
+
254
+ // Re-derives an instances subscriber's view. Returns false (stream ended with `revoked`) if
255
+ // the user is gone, or lost every server they could previously see; a partial loss just
256
+ // narrows the list (the caller pushes it).
257
+ function revalidateInstancesSub(res, sub) {
258
+ const rev = authz.getRevision();
259
+ const ctx = contextForUser(sub.userId);
260
+ if (!ctx) {
261
+ instancesSubscribers.delete(res);
262
+ endRevoked(res);
263
+ return false;
264
+ }
265
+ const access = computeInstanceAccess(ctx);
266
+ const some = hasAnyInstanceAccess(access);
267
+ if (!some && sub.hadAccess) {
268
+ instancesSubscribers.delete(res);
269
+ endRevoked(res);
270
+ return false;
271
+ }
272
+ if (some) sub.hadAccess = true;
273
+ sub.access = access;
274
+ sub.rev = rev;
275
+ return true;
276
+ }
277
+
278
+ // Registers the stream and derives its access from a fresh subject. Returns the
279
+ // subscription (sub.access is what the caller builds the initial list from), or null if the
280
+ // user no longer exists (stream already ended with `revoked`).
281
+ function subscribeInstances(res, userId) {
282
+ const sub = { userId, rev: null, access: null, hadAccess: false };
283
+ instancesSubscribers.set(res, sub);
284
+ res.on('close', () => instancesSubscribers.delete(res));
285
+ return revalidateInstancesSub(res, sub) ? sub : null;
286
+ }
287
+
288
+ // Computes + writes the list to every open /api/instances/stream connection right now,
289
+ // bypassing the throttle — used for events worth showing immediately (connect,
290
+ // disconnect, add, remove, mark-self, prune) rather than the ~10s metrics-driven flush
291
+ // below. A no-op (skips the DB query entirely) when nobody is subscribed. Builds the
292
+ // unrestricted list once and narrows it per subscriber; a subscriber whose rev is stale is
293
+ // revalidated first.
294
+ function broadcastInstancesNow() {
295
+ instancesDirty = false;
296
+ if (instancesSubscribers.size === 0) return;
297
+ const full = buildFullInstancesList();
298
+ const rev = authz.getRevision();
299
+ instancesSubscribers.forEach((sub, res) => {
300
+ if (sub.rev !== rev && !revalidateInstancesSub(res, sub)) return;
301
+ safeWrite(res, `data: ${JSON.stringify(applyInstanceAccess(full, sub.access))}\n\n`);
302
+ });
303
+ }
304
+
305
+ function markInstancesDirty() {
306
+ instancesDirty = true;
307
+ }
308
+
309
+ // ---- log tail SSE ----
310
+
311
+ function removeLogTailSub(key, res) {
312
+ const subs = logTailSubscribers.get(key);
313
+ if (!subs || !subs.delete(res)) return;
314
+ if (subs.size === 0) {
315
+ logTailSubscribers.delete(key);
316
+ const [instanceId, kind, app, stream] = splitLogKey(key);
317
+ sendToAgent(instanceId, { type: 'stop_tail', app, stream, kind });
318
+ }
319
+ }
320
+
321
+ // key = `${instanceId}:${kind}:${app}:${stream}`. instanceId/kind/stream never contain ':',
322
+ // but an app (a container/unit name) can, so only the first two and the last part are split off.
323
+ function splitLogKey(key) {
324
+ const first = key.indexOf(':');
325
+ const second = key.indexOf(':', first + 1);
326
+ const last = key.lastIndexOf(':');
327
+ return [
328
+ key.slice(0, first),
329
+ key.slice(first + 1, second),
330
+ key.slice(second + 1, last),
331
+ key.slice(last + 1),
332
+ ];
333
+ }
334
+
335
+ function revalidateLogTailSub(key, res, sub) {
336
+ const rev = authz.getRevision();
337
+ const ctx = contextForUser(sub.userId);
338
+ let ok = false;
339
+ if (
340
+ ctx &&
341
+ db.getInstance(sub.instanceId) &&
342
+ ctx.can('servers.view', { instanceId: sub.instanceId })
343
+ ) {
344
+ ok = serviceAllowed(sub.app, ctx.serviceMatchersFor('logs.view', sub.instanceId));
345
+ }
346
+ if (!ok) {
347
+ removeLogTailSub(key, res);
348
+ endRevoked(res);
349
+ return false;
350
+ }
351
+ sub.rev = rev;
352
+ return true;
353
+ }
354
+
355
+ // Returns false if the stream was revoked on the spot (the caller must stop using res).
356
+ function subscribeLogTail(instanceId, app, stream, kind, search, level, res, userId) {
357
+ const key = `${instanceId}:${kind}:${app}:${stream}`;
358
+ if (!logTailSubscribers.has(key)) logTailSubscribers.set(key, new Map());
359
+ const subs = logTailSubscribers.get(key);
360
+ const isFirst = subs.size === 0;
361
+ const sub = { userId, instanceId, app, rev: null };
362
+ subs.set(res, sub);
363
+ res.on('close', () => removeLogTailSub(key, res));
364
+ if (!revalidateLogTailSub(key, res, sub)) return false;
365
+ if (isFirst) sendToAgent(instanceId, { type: 'tail_logs', app, stream, kind, search, level });
366
+ return true;
367
+ }
368
+
369
+ // Fan-out for an agent's 'log_line' frame (ws/agent-relay.js); revalidates stale subscribers
370
+ // before writing.
371
+ function broadcastLogLine(instanceId, kind, app, stream, record) {
372
+ const key = `${instanceId}:${kind}:${app}:${stream}`;
373
+ const subs = logTailSubscribers.get(key);
374
+ if (!subs) return;
375
+ const rev = authz.getRevision();
376
+ const payload = `data: ${JSON.stringify(record)}\n\n`;
377
+ subs.forEach((sub, res) => {
378
+ if (sub.rev !== rev && !revalidateLogTailSub(key, res, sub)) return;
379
+ safeWrite(res, payload);
380
+ });
381
+ }
382
+
383
+ // ---- revocation sweep ----
384
+
385
+ // Walks every open stream and re-derives its access from the database. Called immediately
386
+ // on an authorization revision event (so an idle stream is closed too, not just the next
387
+ // time something is written to it) and on a slow timer as a backstop for any change that
388
+ // didn't bump the revision. `push` re-sends the (possibly narrowed) instance list to
389
+ // instances subscribers that survive.
390
+ function revalidateAll({ push = false } = {}) {
391
+ metricsSubscribers.forEach((subs, instanceId) => {
392
+ subs.forEach((sub, res) => revalidateMetricsSub(instanceId, res, sub));
393
+ });
394
+ logTailSubscribers.forEach((subs, key) => {
395
+ subs.forEach((sub, res) => revalidateLogTailSub(key, res, sub));
396
+ });
397
+ const survivors = [];
398
+ instancesSubscribers.forEach((sub, res) => {
399
+ if (revalidateInstancesSub(res, sub)) survivors.push([sub, res]);
400
+ });
401
+ if (push && survivors.length) {
402
+ const full = buildFullInstancesList();
403
+ for (const [sub, res] of survivors) {
404
+ safeWrite(res, `data: ${JSON.stringify(applyInstanceAccess(full, sub.access))}\n\n`);
405
+ }
406
+ }
407
+ }
408
+
409
+ authz.onRevision(() => {
410
+ // Runs after the mutating transaction has committed (and inside the request that made it):
411
+ // a failure here must never turn a successful change into an error response. The 30s
412
+ // sweep below is the backstop.
413
+ try {
414
+ revalidateAll({ push: true });
415
+ } catch (e) {
416
+ console.error('[relay-state] revalidation after an authorization change failed:', e);
417
+ }
418
+ });
419
+
420
+ function requestLogs(instanceId, params) {
421
+ return new Promise((resolve) => {
422
+ if (!isAgentConnected(instanceId)) {
423
+ resolve({ records: [], total: 0, offline: true });
424
+ return;
425
+ }
426
+ const requestId = crypto.randomBytes(8).toString('hex');
427
+ const timer = setTimeout(() => {
428
+ pendingLogRequests.delete(requestId);
429
+ resolve({ records: [], total: 0, offline: true });
430
+ }, config.LOG_REQUEST_TIMEOUT_MS);
431
+ pendingLogRequests.set(requestId, { resolve, timer });
432
+ sendToAgent(instanceId, { type: 'get_logs', requestId, ...params });
433
+ });
434
+ }
435
+
436
+ // Generic hub -> agent request/response (the env-file editor's read/write/restart — see
437
+ // docs/env-files.md). Unlike requestLogs, offline and timeout are distinct, and the agent's
438
+ // own failure (permission denied, conflict, ...) comes back as `{ ok:false, code, error }`
439
+ // rather than being flattened into "offline". Always resolves, never rejects.
440
+ function requestAgent(instanceId, frame, timeoutMs) {
441
+ return new Promise((resolve) => {
442
+ if (!isAgentConnected(instanceId)) {
443
+ resolve({ ok: false, code: 'OFFLINE', error: 'Instance is offline.' });
444
+ return;
445
+ }
446
+ const requestId = crypto.randomBytes(8).toString('hex');
447
+ const timer = setTimeout(() => {
448
+ pendingAgentRequests.delete(requestId);
449
+ resolve({ ok: false, code: 'TIMEOUT', error: 'The agent did not respond in time.' });
450
+ }, timeoutMs || config.ENV_RPC_TIMEOUT_MS);
451
+ pendingAgentRequests.set(requestId, { instanceId, resolve, timer });
452
+ if (!sendToAgent(instanceId, { ...frame, requestId })) {
453
+ clearTimeout(timer);
454
+ pendingAgentRequests.delete(requestId);
455
+ resolve({ ok: false, code: 'OFFLINE', error: 'Instance is offline.' });
456
+ }
457
+ });
458
+ }
459
+
460
+ // Called by ws/agent-relay.js when an agent's 'rpc_result' frame arrives. Ignores a result
461
+ // whose requestId belongs to a different instance's request.
462
+ function resolveAgentRequest(instanceId, msg) {
463
+ const pending = pendingAgentRequests.get(msg.requestId);
464
+ if (!pending || pending.instanceId !== instanceId) return;
465
+ clearTimeout(pending.timer);
466
+ pendingAgentRequests.delete(msg.requestId);
467
+ const result = { ...msg };
468
+ delete result.type;
469
+ delete result.requestId;
470
+ pending.resolve(result);
471
+ }
472
+
473
+ // A closed socket can never answer, so fail its in-flight requests now instead of making
474
+ // the operator wait out the timeout.
475
+ function failPendingAgentRequests(instanceId, code, error) {
476
+ for (const [requestId, pending] of pendingAgentRequests) {
477
+ if (pending.instanceId !== instanceId) continue;
478
+ clearTimeout(pending.timer);
479
+ pendingAgentRequests.delete(requestId);
480
+ pending.resolve({ ok: false, code, error });
481
+ }
482
+ }
483
+
484
+ function agentHasCapability(instanceId, capability) {
485
+ const state = agentState.get(instanceId);
486
+ return !!(state && Array.isArray(state.capabilities) && state.capabilities.includes(capability));
487
+ }
488
+
489
+ function readInstanceHistory(instanceId) {
490
+ return db.getHistoryForInstance(instanceId, Date.now() - config.HISTORY_RETENTION_MS);
491
+ }
492
+
493
+ function appendInstanceHistorySample(instanceId, metrics) {
494
+ const cpuPercentApprox = Math.min(
495
+ 100,
496
+ (parseFloat(metrics.load_avg[0]) / metrics.cpu_count) * 100,
497
+ );
498
+ db.insertMetricSample(instanceId, {
499
+ ts: metrics.ts || Date.now(),
500
+ cpu: Number(cpuPercentApprox.toFixed(1)),
501
+ mem: Number(metrics.mem_used_percent),
502
+ disk: parseFloat(metrics.disk_percent) || 0,
503
+ net_rx: metrics.network.rx_bytes,
504
+ net_tx: metrics.network.tx_bytes,
505
+ });
506
+ }
507
+
508
+ // Replaces the old "read whole file, filter, rewrite whole file" pruning — an indexed
509
+ // DELETE across every instance at once. getHistoryForInstance still applies the same
510
+ // cutoff itself on every read, so a read never shows stale rows even between prune runs.
511
+ // Timers are unref()'d: they must never be what keeps a process (e.g. a test run) alive —
512
+ // the hub's HTTP server does that in production.
513
+ setInterval(
514
+ () => db.pruneMetricsOlderThan(Date.now() - config.HISTORY_RETENTION_MS),
515
+ config.HISTORY_PRUNE_INTERVAL_MS,
516
+ ).unref();
517
+ setInterval(() => {
518
+ const before = db.listInstances().length;
519
+ db.pruneNeverConnectedInstancesOlderThan(Date.now() - config.NEVER_CONNECTED_TTL_MS);
520
+ // A pruned instance is an instance delete: bump the authorization revision so any stream
521
+ // still pointing at it revalidates (and closes).
522
+ if (db.listInstances().length !== before) authz.bumpRevision();
523
+ broadcastInstancesNow();
524
+ }, config.HISTORY_PRUNE_INTERVAL_MS).unref();
525
+ setInterval(() => {
526
+ if (instancesDirty) broadcastInstancesNow();
527
+ }, config.INSTANCES_BROADCAST_INTERVAL_MS).unref();
528
+ // Backstop for any access change that didn't bump the revision (or a user deleted by some
529
+ // other path): every open stream re-derives its grants from the database this often.
530
+ setInterval(() => revalidateAll({ push: false }), 30 * 1000).unref();
531
+
532
+ module.exports = {
533
+ agentState,
534
+ metricsSubscribers,
535
+ logTailSubscribers,
536
+ pendingLogRequests,
537
+ instancesSubscribers,
538
+ sendToAgent,
539
+ isAgentConnected,
540
+ desiredMetricsInterval,
541
+ subscribeMetrics,
542
+ broadcastMetrics,
543
+ serviceAllowed,
544
+ filterMetricsForProcesses,
545
+ buildInstancesList,
546
+ computeInstanceAccess,
547
+ contextForUser,
548
+ safeWrite,
549
+ endRevoked,
550
+ startHeartbeat,
551
+ revalidateAll,
552
+ broadcastLogLine,
553
+ subscribeInstances,
554
+ broadcastInstancesNow,
555
+ markInstancesDirty,
556
+ subscribeLogTail,
557
+ requestLogs,
558
+ requestAgent,
559
+ resolveAgentRequest,
560
+ failPendingAgentRequests,
561
+ agentHasCapability,
562
+ readInstanceHistory,
563
+ appendInstanceHistorySample,
564
+ };