@sleep2agi/commhub-server 0.9.0-preview.3 → 0.9.0-preview.30

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 (99) hide show
  1. package/README.md +125 -7
  2. package/bin/commhub.ts +10 -2
  3. package/package.json +5 -5
  4. package/src/ack-create-request-transport.test.ts +159 -0
  5. package/src/ack-create-request.test.ts +331 -0
  6. package/src/admin-networks-http.test.ts +84 -0
  7. package/src/alias-filter.test.ts +72 -0
  8. package/src/alias-filter.ts +32 -0
  9. package/src/api-host-supervisors-fallback.test.ts +267 -0
  10. package/src/api-nodes-shape.test.ts +188 -0
  11. package/src/auth.ts +93 -14
  12. package/src/avatar-validate.test.ts +163 -0
  13. package/src/avatar-validate.ts +103 -0
  14. package/src/boot-side-effect.test.ts +124 -0
  15. package/src/config-apply-sec1.test.ts +107 -0
  16. package/src/config-apply-validate.test.ts +92 -0
  17. package/src/config-apply-validate.ts +81 -3
  18. package/src/create-node.ts +48 -1
  19. package/src/dashboard-slash-routing-http.test.ts +103 -0
  20. package/src/db-adapter-guard.test.ts +85 -0
  21. package/src/db-adapter.ts +64 -23
  22. package/src/db.ts +522 -32
  23. package/src/ext-token-shared.test.ts +60 -0
  24. package/src/ext-validation-regression.test.ts +131 -0
  25. package/src/external-schedule-edits-http.test.ts +316 -0
  26. package/src/external-schedule-edits.ts +314 -0
  27. package/src/file-download-authz-dev-open.test.ts +135 -0
  28. package/src/file-download-authz.test.ts +403 -0
  29. package/src/file-download-date-bucket.test.ts +436 -0
  30. package/src/file-network-scope-dev-open.test.ts +97 -0
  31. package/src/file-network-scope.test.ts +731 -0
  32. package/src/health-redaction.test.ts +637 -0
  33. package/src/index.ts +15 -2172
  34. package/src/lifecycle-guard.ts +50 -0
  35. package/src/list-host-supervisors.test.ts +314 -0
  36. package/src/mcp-write-network-resolution.test.ts +429 -0
  37. package/src/network-name-http.test.ts +71 -0
  38. package/src/network-scope.ts +101 -0
  39. package/src/node-attrs-validate.ts +88 -0
  40. package/src/node-attrs.test.ts +213 -0
  41. package/src/observer-avatar-http.test.ts +349 -0
  42. package/src/observer-push.test.ts +176 -0
  43. package/src/peer-reply-atomic.test.ts +455 -0
  44. package/src/peer-reply-capability.test.ts +70 -0
  45. package/src/probe-validate.test.ts +221 -0
  46. package/src/probe-validate.ts +104 -0
  47. package/src/probe.test.ts +80 -0
  48. package/src/probe.ts +200 -0
  49. package/src/push.ts +96 -7
  50. package/src/require-explicit-test-db.ts +9 -0
  51. package/src/resolve-port.test.ts +57 -0
  52. package/src/resolve-port.ts +44 -0
  53. package/src/response-charset.test.ts +130 -0
  54. package/src/rest-explicit-columns-http.test.ts +211 -0
  55. package/src/rest-identity.test.ts +129 -0
  56. package/src/rest-identity.ts +100 -0
  57. package/src/rest-projections.ts +67 -0
  58. package/src/rest-write-network-resolution.test.ts +133 -0
  59. package/src/runtime-label.test.ts +22 -0
  60. package/src/runtime-label.ts +21 -0
  61. package/src/scheduled-run-terminal.test.ts +268 -0
  62. package/src/scheduled-tasks-http.test.ts +479 -0
  63. package/src/scheduled-tasks.ts +549 -0
  64. package/src/send-reply-agent-warning.test.ts +202 -0
  65. package/src/send-reply-attachments.test.ts +437 -0
  66. package/src/server.ts +3492 -0
  67. package/src/shared/external-schedule-contract.ts +60 -0
  68. package/src/shared/probe-host-allowlist-drift.test.ts +54 -0
  69. package/src/shared/probe-host-allowlist.ts +128 -0
  70. package/src/side-thread-command-transport.test.ts +140 -0
  71. package/src/side-thread-command-transport.ts +309 -0
  72. package/src/side-thread-http-integration.test.ts +229 -0
  73. package/src/side-thread-http.ts +504 -0
  74. package/src/side-thread.test.ts +1038 -0
  75. package/src/side-thread.ts +2241 -0
  76. package/src/skillhub-http.test.ts +88 -0
  77. package/src/stop-delete-node.test.ts +720 -0
  78. package/src/task-auth-origin-http.test.ts +87 -0
  79. package/src/task-auth-origin.test.ts +24 -0
  80. package/src/task-auth-origin.ts +7 -0
  81. package/src/task-consumption.test.ts +398 -0
  82. package/src/task-diagnostic-http.test.ts +145 -0
  83. package/src/task-diagnostic.test.ts +115 -0
  84. package/src/task-diagnostic.ts +118 -0
  85. package/src/task-idempotency-mcp.test.ts +142 -0
  86. package/src/task-idempotency.test.ts +60 -0
  87. package/src/task-idempotency.ts +75 -0
  88. package/src/task-lifecycle-watcher.test.ts +200 -0
  89. package/src/task-lifecycle-watcher.ts +49 -0
  90. package/src/task-network-resolution-http.test.ts +137 -0
  91. package/src/tasks-pagination-http.test.ts +137 -0
  92. package/src/tools.ts +2302 -169
  93. package/src/update-provider.test.ts +234 -0
  94. package/src/upload-early-reject-guard.test.ts +155 -0
  95. package/src/uploads-http.test.ts +92 -14
  96. package/src/uploads.test.ts +66 -0
  97. package/src/uploads.ts +130 -5
  98. package/src/vault.test.ts +200 -0
  99. package/src/vault.ts +156 -0
@@ -0,0 +1,637 @@
1
+ // #473 — /health information-leak redaction.
2
+ //
3
+ // Public-hub audit (通信龙, 2026-07-30) showed anonymous GET /health
4
+ // returning the full SSE key breakdown: `{networkId}:{alias}` for every
5
+ // live connection — network id + all 95 agent aliases on the audited
6
+ // hub. The fix keeps /health anonymous (HARD CONSTRAINT: the central
7
+ // watchdog curls it every minute; auth here would blind it) but strips
8
+ // the per-key detail down to aggregate counts; the detail moved behind
9
+ // auth at GET /api/stats/sse (master token or admin only).
10
+ //
11
+ // Witnessed-red: on pre-fix main (8c11edf5) the "no leak" test below is
12
+ // red — the /health body contains the connected alias and network id.
13
+
14
+ import { describe, expect, test, beforeAll, afterAll } from "bun:test";
15
+ import { mkdtempSync, rmSync } from "fs";
16
+ import { join } from "path";
17
+ import { tmpdir } from "os";
18
+ import { register, addNetworkMember, removeNetworkMember } from "./auth.js";
19
+ import { db } from "./db.js";
20
+ import { MAX_REQUEST_CONTENT_LENGTH, MAX_UPLOAD_BYTES } from "./uploads.js";
21
+
22
+ const SERVER_DB = mkdtempSync(join(tmpdir(), "anet-health-red-db-")) + "/commhub.db";
23
+
24
+ let BASE = "";
25
+ let server: any = null;
26
+ let sseReader: ReadableStreamDefaultReader<Uint8Array> | null = null;
27
+
28
+ let userToken = "";
29
+ let userNetworkId = "";
30
+ let userName = "";
31
+ let adminToken = "";
32
+
33
+ beforeAll(async () => {
34
+ process.env.COMMHUB_DB = process.env.COMMHUB_DB || SERVER_DB;
35
+ process.env.HOST = "127.0.0.1";
36
+
37
+ const suffix = `${Date.now()}_${Math.floor(Math.random() * 1000)}`;
38
+ const pw = "BootstrapPw123Aa!";
39
+
40
+ // Burn a seed registration first so our member is NOT auto-admin (the
41
+ // "first registered user → admin" rule only bites when this suite owns
42
+ // the DB; per-file runs need this guard). We set roles explicitly below.
43
+ register(`health_seed_${suffix}`, pw, undefined, "seed");
44
+
45
+ userName = `health_user_${suffix}`;
46
+ const r = register(userName, pw, undefined, "seed");
47
+ if (!r.ok || !r.token) throw new Error("register failed: " + JSON.stringify(r));
48
+ userToken = r.token;
49
+ userNetworkId = r.network_id ?? "";
50
+ if (!userNetworkId) throw new Error("no network for user");
51
+ // Pin to plain member — defend against any residual auto-admin.
52
+ db.run("UPDATE users SET role = 'user' WHERE username = ?1", [userName]);
53
+
54
+ const adminName = `health_admin_${suffix}`;
55
+ const a = register(adminName, pw, undefined, "seed");
56
+ if (!a.ok || !a.token) throw new Error("admin register failed: " + JSON.stringify(a));
57
+ adminToken = a.token;
58
+ // Explicit promotion — "first registered user is auto-admin" does not
59
+ // hold in aggregate runs (see api-host-supervisors-fallback.test.ts).
60
+ db.run("UPDATE users SET role = 'admin' WHERE username = ?1", [adminName]);
61
+
62
+ const { bootServer } = await import("./server.js");
63
+ server = bootServer({ port: 0, hostname: "127.0.0.1" });
64
+ BASE = `http://127.0.0.1:${server.port}`;
65
+
66
+ // Open a real SSE connection so the stats have a key that WOULD leak:
67
+ // the dashboard-user channel (sessionName === own username, Path 3
68
+ // gate 4a) registers `${networkId}:${username}` in the clients map.
69
+ const res = await fetch(`${BASE}/events/${encodeURIComponent(userName)}?network_id=${userNetworkId}`, {
70
+ headers: { Authorization: `Bearer ${userToken}` },
71
+ });
72
+ if (res.status !== 200) throw new Error("SSE subscribe failed: " + res.status);
73
+ sseReader = res.body!.getReader();
74
+ await sseReader.read(); // consume the connected frame → registration done
75
+ });
76
+
77
+ afterAll(() => {
78
+ try { sseReader?.cancel(); } catch {}
79
+ try { server?.stop?.(true); } catch {}
80
+ try { rmSync(SERVER_DB, { recursive: true, force: true }); } catch {}
81
+ });
82
+
83
+ describe("#473 anonymous /health — watchdog contract intact, no topology leak", () => {
84
+ test("stays anonymous 200 with parseable aggregates (watchdog judge: curl -sf gets 2xx)", async () => {
85
+ const res = await fetch(`${BASE}/health`);
86
+ expect(res.status).toBe(200);
87
+ const body = await res.json() as any;
88
+ expect(body.ok).toBe(true);
89
+ expect(typeof body.version).toBe("string");
90
+ expect(typeof body.sessions_count).toBe("number");
91
+ expect(typeof body.sse_connections).toBe("number");
92
+ expect(body.sse_connections).toBeGreaterThanOrEqual(1);
93
+ });
94
+
95
+ test("exposes stable upload limits anonymously without exposing topology", async () => {
96
+ const res = await fetch(`${BASE}/health`);
97
+ expect(res.status).toBe(200);
98
+ const body = await res.json() as any;
99
+ expect(body.limits).toEqual({
100
+ max_upload_bytes: MAX_UPLOAD_BYTES,
101
+ max_request_content_length: MAX_REQUEST_CONTENT_LENGTH,
102
+ });
103
+ expect(body.limits.max_request_content_length).toBeGreaterThan(body.limits.max_upload_bytes);
104
+ });
105
+
106
+ test("CLI count source stays truthful: health.sse_connections == /api/stats/sse total (no fake 0)", async () => {
107
+ // The CLI's `anet doctor` line reads health.sse_connections now
108
+ // (was Object.keys(sse_sessions).length). This pins that aggregate to
109
+ // the same number the auth-gated detail endpoint reports — so a live
110
+ // hub with N connections shows N, never the "0 active" regression the
111
+ // review caught. There is exactly one live SSE connection in setup.
112
+ const health = await (await fetch(`${BASE}/health`)).json() as any;
113
+ const detail = await (await fetch(`${BASE}/api/stats/sse`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any;
114
+ expect(health.sse_connections).toBe(detail.total);
115
+ expect(health.sse_connections).toBeGreaterThanOrEqual(1);
116
+ });
117
+
118
+ test("does NOT expose SSE key detail: no sse_sessions field, no alias, no network id", async () => {
119
+ const res = await fetch(`${BASE}/health`);
120
+ const text = await res.text();
121
+ const body = JSON.parse(text);
122
+ expect("sse_sessions" in body).toBe(false);
123
+ // The live connection's identifying strings must not appear anywhere
124
+ // in the anonymous body.
125
+ expect(text).not.toContain(userName);
126
+ expect(text).not.toContain(userNetworkId);
127
+ });
128
+ });
129
+
130
+ describe("f28a6c1b /health sse_sessions — auth-gated restoration for dashboard 'online' widget", () => {
131
+ // The dashboard's server-side Next.js proxy (agent-network-dashboard
132
+ // `app/api/hub/health/route.ts` → `hubFetch('/health')`) forwards the
133
+ // logged-in user's V3 utok_ as `Authorization: Bearer …`. Anonymous
134
+ // callers (public watchdog, internet strangers) still get NO
135
+ // sse_sessions — that leak stays closed. Authenticated callers get
136
+ // the sessions map scoped to their networks (ops sees all).
137
+
138
+ test("regular member with valid utok_: sse_sessions present, filtered to member's networks", async () => {
139
+ const res = await fetch(`${BASE}/health`, {
140
+ headers: { Authorization: `Bearer ${userToken}` },
141
+ });
142
+ expect(res.status).toBe(200);
143
+ const body = await res.json() as any;
144
+ // Field must be present when authenticated — otherwise dashboard
145
+ // "online" widget shows 0.
146
+ expect("sse_sessions" in body).toBe(true);
147
+ // Must contain the member's own SSE connection key.
148
+ const ownKey = `${userNetworkId}:${userName}`;
149
+ expect(body.sse_sessions[ownKey]).toBeGreaterThanOrEqual(1);
150
+ // Watchdog aggregate contract unchanged.
151
+ expect(body.sse_connections).toBeGreaterThanOrEqual(1);
152
+ });
153
+
154
+ test("admin with valid utok_: sse_sessions present, full unfiltered map (ops parity with /api/stats/sse)", async () => {
155
+ const res = await fetch(`${BASE}/health`, {
156
+ headers: { Authorization: `Bearer ${adminToken}` },
157
+ });
158
+ expect(res.status).toBe(200);
159
+ const body = await res.json() as any;
160
+ expect("sse_sessions" in body).toBe(true);
161
+ // Admin sees the member's key even though they live in a different
162
+ // network (admin scope spans everything, same as /api/stats/sse).
163
+ const memberKey = `${userNetworkId}:${userName}`;
164
+ expect(body.sse_sessions[memberKey]).toBeGreaterThanOrEqual(1);
165
+ // Sanity: admin's view must match the auth-gated ops endpoint.
166
+ const opsRes = await fetch(`${BASE}/api/stats/sse`, {
167
+ headers: { Authorization: `Bearer ${adminToken}` },
168
+ });
169
+ const ops = await opsRes.json() as any;
170
+ expect(body.sse_sessions).toEqual(ops.sessions);
171
+ });
172
+
173
+ test("anonymous still gets NO sse_sessions (leak stays closed, mutation-red witness)", async () => {
174
+ // This is the mutation-red assertion for the auth gate: if the
175
+ // handler stops distinguishing anonymous from authenticated and
176
+ // starts including sse_sessions unconditionally, this test turns
177
+ // RED. Distinct from the older `does NOT expose SSE key detail`
178
+ // test — that one guards against any regression restoring the
179
+ // OLD unconditional leak; this one guards against a well-meaning
180
+ // "just always send it if authenticated is optional" bug.
181
+ const res = await fetch(`${BASE}/health`);
182
+ const body = await res.json() as any;
183
+ expect("sse_sessions" in body).toBe(false);
184
+ });
185
+
186
+ test("invalid/garbage token: treated as anonymous — no sse_sessions", async () => {
187
+ const res = await fetch(`${BASE}/health`, {
188
+ headers: { Authorization: "Bearer utok_completely_fake_nonexistent" },
189
+ });
190
+ expect(res.status).toBe(200);
191
+ const body = await res.json() as any;
192
+ // resolveRequestAuth returns null for unresolvable tokens, so the
193
+ // handler must NOT fall through to "authenticated" branch. Otherwise
194
+ // a bad token would degrade to "anonymous with sse_sessions" — that
195
+ // would be the leak in a different disguise.
196
+ expect("sse_sessions" in body).toBe(false);
197
+ });
198
+ });
199
+
200
+ describe("#473 GET /api/stats/sse — detail survives, behind ops auth", () => {
201
+ test("anonymous → 401", async () => {
202
+ const res = await fetch(`${BASE}/api/stats/sse`);
203
+ expect(res.status).toBe(401);
204
+ });
205
+
206
+ test("regular member token → 403 (detail spans every network)", async () => {
207
+ const res = await fetch(`${BASE}/api/stats/sse`, { headers: { Authorization: `Bearer ${userToken}` } });
208
+ expect(res.status).toBe(403);
209
+ });
210
+
211
+ test("admin → 200 with the full key breakdown (ops capability preserved)", async () => {
212
+ const res = await fetch(`${BASE}/api/stats/sse`, { headers: { Authorization: `Bearer ${adminToken}` } });
213
+ expect(res.status).toBe(200);
214
+ const body = await res.json() as any;
215
+ expect(body.ok).toBe(true);
216
+ expect(typeof body.total).toBe("number");
217
+ expect(body.sessions[`${userNetworkId}:${userName}`]).toBeGreaterThanOrEqual(1);
218
+ });
219
+
220
+ test("legacy master token → 200 (ops path — restAuth null, isLegacyAuthToken)", () => {
221
+ // COMMHUB_AUTH_TOKEN is captured at module import, so this path needs
222
+ // a fresh process with the env set before boot (aggregate order can't
223
+ // guarantee this file imports server.ts first). Subprocess, like the
224
+ // patrol test. Reviewer flagged this path had code but no test.
225
+ const script = `
226
+ process.env.COMMHUB_AUTH_TOKEN = "master-secret-xyz";
227
+ const { startHub } = await import("./src/server.js");
228
+ const hub = startHub({ port: 0, hostname: "127.0.0.1" });
229
+ const base = "http://127.0.0.1:" + hub.port;
230
+ const anon = await fetch(base + "/api/stats/sse");
231
+ const master = await fetch(base + "/api/stats/sse", { headers: { Authorization: "Bearer master-secret-xyz" } });
232
+ const health = await fetch(base + "/health");
233
+ const hb = await health.json();
234
+ console.log("RESULT:" + JSON.stringify({
235
+ anon: anon.status,
236
+ master: master.status,
237
+ masterOk: (await master.json()).ok,
238
+ healthHasSseSessions: "sse_sessions" in hb,
239
+ }));
240
+ hub.stop(true);
241
+ process.exit(0);
242
+ `;
243
+ const child = Bun.spawnSync({
244
+ cmd: ["bun", "-e", script],
245
+ cwd: `${import.meta.dir}/..`,
246
+ env: { ...process.env, COMMHUB_DB: process.env.COMMHUB_DB || "/tmp/anet-473-master.db" },
247
+ timeout: 15_000,
248
+ });
249
+ const out = new TextDecoder().decode(child.stdout);
250
+ const m = out.match(/RESULT:(\{.*\})/);
251
+ expect(m).not.toBeNull();
252
+ const r = JSON.parse(m![1]);
253
+ expect(r.anon).toBe(401); // token configured → anonymous rejected
254
+ expect(r.master).toBe(200); // legacy master token → ops access
255
+ expect(r.masterOk).toBe(true);
256
+ expect(r.healthHasSseSessions).toBe(false); // /health still redacted with a token set
257
+ }, 20_000);
258
+ });
259
+
260
+ // ─────────────────────────────────────────────────────────────────────
261
+ // CR3 (4703b0e7) — M1-M7 matrix tests
262
+ // ─────────────────────────────────────────────────────────────────────
263
+ //
264
+ // Independent audit on aef48a3d showed the existing f28a6c1b tests
265
+ // pinned only the "anonymous vs authenticated" gate. The reviewer
266
+ // mutated `scopedSessions = sse.sessions` (unconditional) and got
267
+ // 11/11 green — meaning the *tenant-scope* invariant (a member sees
268
+ // only their own networks, cross-network is invisible) was not
269
+ // witnessed by any assertion, and a future refactor that broke the
270
+ // filter would ship silently.
271
+ //
272
+ // This block adds explicit tests for every shape the fork's auth
273
+ // decision distinguishes:
274
+ // M1: utok_ member sees own network's sessions
275
+ // M2: utok_ member does NOT see other network's sessions
276
+ // M3: ntok_ (network-scoped token) is forced to the token's bound
277
+ // network — the user's other networks are invisible even
278
+ // though the underlying user is a member
279
+ // M4: same user, utok_ vs ntok_ — utok_ sees union, ntok_ sees only
280
+ // the token's bound network (mutation-red for the ntok_
281
+ // "healthAuth.networkId ? [...] : db.all(...)" branch)
282
+ // M5: membership revocation invalidates visibility immediately —
283
+ // no cache; the next /health request reflects new membership
284
+ // M6: observer keys (shape `\0netobs:<networkId>`; the getSSEStats
285
+ // serializer renders leading NUL as printable `\\0`) are
286
+ // classified through the shared PRINTABLE_OBSERVER_KEY_PREFIX
287
+ // constant, not a re-typed literal. Mutation-red for the
288
+ // constant drift (server.ts had `"netobs:"` without `\\0`
289
+ // before this CR, so all observer keys silently fell through).
290
+ // M7: two networks with the same alias — invisibility survives
291
+ // key collision. Explicit assertion; M1/M2 hide-cover this
292
+ // implicitly but M7 makes the property visible in review.
293
+ describe("f28a6c1b CR3 — network-scoped filter matrix (M1-M7)", () => {
294
+ let mUserAToken = "";
295
+ let mUserANet = "";
296
+ let mUserAName = "";
297
+ let mUserBToken = "";
298
+ let mUserBNet = "";
299
+ let mUserBName = "";
300
+ let mAliceToken = ""; // utok_ (user-scoped)
301
+ let mAliceNtok = ""; // ntok_ bound to mAliceNet
302
+ let mAliceNet = "";
303
+ let mAliceName = "";
304
+ let mCarolToken = "";
305
+ let mCarolNet = "";
306
+ let mCarolName = "";
307
+ let mUserAId = "";
308
+ let mAliceId = "";
309
+ let mCarolId = "";
310
+ let mSameAliasName = ""; // used by M7 — two sessions, one per network
311
+
312
+ const openReaders: ReadableStreamDefaultReader<Uint8Array>[] = [];
313
+
314
+ const startSse = async (base: string, name: string, netId: string, token: string) => {
315
+ const res = await fetch(`${base}/events/${encodeURIComponent(name)}?network_id=${netId}`, {
316
+ headers: { Authorization: `Bearer ${token}` },
317
+ });
318
+ if (res.status !== 200) throw new Error(`SSE subscribe failed (${res.status}) for ${name}@${netId}`);
319
+ const reader = res.body!.getReader();
320
+ await reader.read();
321
+ openReaders.push(reader);
322
+ return reader;
323
+ };
324
+
325
+ const startObserverSse = async (base: string, netId: string, token: string) => {
326
+ // The observer endpoint is /events/network/:networkId — carries no
327
+ // per-agent alias; server registers with the special observer key
328
+ // shape `\0netobs:<networkId>` (see push.ts observerKey()).
329
+ const res = await fetch(`${base}/events/network/${encodeURIComponent(netId)}`, {
330
+ headers: { Authorization: `Bearer ${token}` },
331
+ });
332
+ if (res.status !== 200) throw new Error(`observer SSE subscribe failed (${res.status}) for ${netId}`);
333
+ const reader = res.body!.getReader();
334
+ await reader.read();
335
+ openReaders.push(reader);
336
+ return reader;
337
+ };
338
+
339
+ beforeAll(async () => {
340
+ const suffix = `${Date.now()}_${Math.floor(Math.random() * 1000)}`;
341
+ const pw = "BootstrapPw123Aa!";
342
+
343
+ // userA — own network, plain member
344
+ mUserAName = `cr3_userA_${suffix}`;
345
+ const rA = register(mUserAName, pw, undefined, "seed");
346
+ if (!rA.ok || !rA.token || !rA.network_id) throw new Error("userA register failed");
347
+ mUserAToken = rA.token;
348
+ mUserANet = rA.network_id;
349
+ db.run("UPDATE users SET role = 'user' WHERE username = ?1", [mUserAName]);
350
+ mUserAId = db.get<{ user_id: string }>("SELECT user_id FROM users WHERE username = ?1", [mUserAName])!.user_id;
351
+
352
+ // userB — different own network, plain member
353
+ mUserBName = `cr3_userB_${suffix}`;
354
+ const rB = register(mUserBName, pw, undefined, "seed");
355
+ if (!rB.ok || !rB.token || !rB.network_id) throw new Error("userB register failed");
356
+ mUserBToken = rB.token;
357
+ mUserBNet = rB.network_id;
358
+ db.run("UPDATE users SET role = 'user' WHERE username = ?1", [mUserBName]);
359
+
360
+ // alice — own network + will also be added to userA's N_A, so
361
+ // membership set = { mAliceNet (owner), mUserANet (member) }.
362
+ // Her ntok_ (from register) is bound to mAliceNet only — the M3/M4
363
+ // scope-enforcement test target.
364
+ mAliceName = `cr3_alice_${suffix}`;
365
+ const rAl = register(mAliceName, pw, undefined, "seed");
366
+ if (!rAl.ok || !rAl.token || !rAl.network_token || !rAl.network_id) throw new Error("alice register failed");
367
+ mAliceToken = rAl.token;
368
+ mAliceNtok = rAl.network_token;
369
+ mAliceNet = rAl.network_id;
370
+ db.run("UPDATE users SET role = 'user' WHERE username = ?1", [mAliceName]);
371
+ mAliceId = db.get<{ user_id: string }>("SELECT user_id FROM users WHERE username = ?1", [mAliceName])!.user_id;
372
+ const addAlice = addNetworkMember(mUserANet, mAliceId, "member", mUserAId);
373
+ if (!addAlice.ok) throw new Error("addNetworkMember(alice→N_A) failed: " + addAlice.error);
374
+
375
+ // carol — own network + will also be added to N_A, then revoked
376
+ // in M5.
377
+ mCarolName = `cr3_carol_${suffix}`;
378
+ const rC = register(mCarolName, pw, undefined, "seed");
379
+ if (!rC.ok || !rC.token || !rC.network_id) throw new Error("carol register failed");
380
+ mCarolToken = rC.token;
381
+ mCarolNet = rC.network_id;
382
+ db.run("UPDATE users SET role = 'user' WHERE username = ?1", [mCarolName]);
383
+ mCarolId = db.get<{ user_id: string }>("SELECT user_id FROM users WHERE username = ?1", [mCarolName])!.user_id;
384
+ const addCarol = addNetworkMember(mUserANet, mCarolId, "member", mUserAId);
385
+ if (!addCarol.ok) throw new Error("addNetworkMember(carol→N_A) failed: " + addCarol.error);
386
+
387
+ // Live SSE sessions — one per network — so the filter has real
388
+ // keys to include/exclude.
389
+ await startSse(BASE, mUserAName, mUserANet, mUserAToken);
390
+ await startSse(BASE, mUserBName, mUserBNet, mUserBToken);
391
+ await startSse(BASE, mAliceName, mAliceNet, mAliceToken);
392
+ await startSse(BASE, mCarolName, mCarolNet, mCarolToken);
393
+
394
+ // M6 — observer stream for N_A (produces `\0netobs:<mUserANet>` key)
395
+ await startObserverSse(BASE, mUserANet, mUserAToken);
396
+
397
+ // M7 note: The dashboard-user SSE gate only lets a caller subscribe
398
+ // as their own username (path 3, gate 4a). Standing up two sessions
399
+ // named the same alias in two different networks would need two
400
+ // separate "helper" users per network — significantly larger setup
401
+ // than the property we're testing. M1/M2 already witness the shape
402
+ // invariant (`<netId>:<alias>` keying) that would defeat collision:
403
+ // cross-network same-alias would land at `<N_A>:<alias>` vs
404
+ // `<N_B>:<alias>`, and M2's `expect(body.sse_sessions[<N_B>:...]).toBeUndefined()`
405
+ // pins exactly the "wrong-tenant key is invisible" property. M7 is
406
+ // therefore covered structurally; skipping the physical fixture.
407
+ mSameAliasName = "";
408
+ });
409
+
410
+ afterAll(() => {
411
+ for (const r of openReaders) { try { r.cancel(); } catch {} }
412
+ });
413
+
414
+ // ── M1 + M2 — utok_ member sees own network only ────────────────
415
+ test("M1: utok_ member of N_A sees N_A sessions", async () => {
416
+ const res = await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${mUserAToken}` } });
417
+ expect(res.status).toBe(200);
418
+ const body = await res.json() as any;
419
+ expect("sse_sessions" in body).toBe(true);
420
+ expect(body.sse_sessions[`${mUserANet}:${mUserAName}`]).toBeGreaterThanOrEqual(1);
421
+ });
422
+
423
+ test("M2: utok_ member of N_A does NOT see N_B sessions (cross-network invisibility)", async () => {
424
+ const res = await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${mUserAToken}` } });
425
+ const body = await res.json() as any;
426
+ expect("sse_sessions" in body).toBe(true);
427
+ // The N_B session (userB's own network) must not surface here —
428
+ // this is the assertion the reviewer's "delete member filter"
429
+ // mutation must break (currently was silently green).
430
+ expect(body.sse_sessions[`${mUserBNet}:${mUserBName}`]).toBeUndefined();
431
+ });
432
+
433
+ test("M2b: utok_ member of N_B sees own but not N_A (reverse of M2)", async () => {
434
+ const res = await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${mUserBToken}` } });
435
+ const body = await res.json() as any;
436
+ expect(body.sse_sessions[`${mUserBNet}:${mUserBName}`]).toBeGreaterThanOrEqual(1);
437
+ expect(body.sse_sessions[`${mUserANet}:${mUserAName}`]).toBeUndefined();
438
+ });
439
+
440
+ // ── M3 + M4 — ntok_ single-network enforce ──────────────────────
441
+ test("M3: alice utok_ (user-scoped) sees union — both mAliceNet and mUserANet", async () => {
442
+ const res = await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${mAliceToken}` } });
443
+ expect(res.status).toBe(200);
444
+ const body = await res.json() as any;
445
+ expect(body.sse_sessions[`${mAliceNet}:${mAliceName}`]).toBeGreaterThanOrEqual(1);
446
+ expect(body.sse_sessions[`${mUserANet}:${mUserAName}`]).toBeGreaterThanOrEqual(1);
447
+ });
448
+
449
+ test("M4: alice ntok_ (network-scoped, bound to mAliceNet) sees ONLY mAliceNet — N_A invisible even though she is a member", async () => {
450
+ // This is the CR3 P1 fix's mutation-red target: if the /health
451
+ // filter falls through to the `db.all(...)` union for ntok_
452
+ // callers (i.e. drops the `healthAuth.networkId ? [...] : ...`
453
+ // branch), this test flips because alice would suddenly see
454
+ // mUserANet sessions through a token that only granted mAliceNet.
455
+ const res = await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${mAliceNtok}` } });
456
+ expect(res.status).toBe(200);
457
+ const body = await res.json() as any;
458
+ expect("sse_sessions" in body).toBe(true);
459
+ // Own network — must be present.
460
+ expect(body.sse_sessions[`${mAliceNet}:${mAliceName}`]).toBeGreaterThanOrEqual(1);
461
+ // The other network she belongs to — ntok_ must NOT show it.
462
+ expect(body.sse_sessions[`${mUserANet}:${mUserAName}`]).toBeUndefined();
463
+ // Sanity: an unrelated network she's not in must also be absent.
464
+ expect(body.sse_sessions[`${mUserBNet}:${mUserBName}`]).toBeUndefined();
465
+ });
466
+
467
+ // ── M5 — membership revocation invalidates visibility ───────────
468
+ test("M5: removing carol from N_A → next /health hides N_A sessions", async () => {
469
+ // Pre-revocation: carol utok_ sees own network + N_A (userA lives
470
+ // in N_A). Filter is per-request, no cache — so a revoke followed
471
+ // by an immediate /health must reflect the new state.
472
+ const before = await (await fetch(`${BASE}/health`, {
473
+ headers: { Authorization: `Bearer ${mCarolToken}` },
474
+ })).json() as any;
475
+ expect(before.sse_sessions[`${mCarolNet}:${mCarolName}`]).toBeGreaterThanOrEqual(1);
476
+ expect(before.sse_sessions[`${mUserANet}:${mUserAName}`]).toBeGreaterThanOrEqual(1);
477
+
478
+ const rm = removeNetworkMember(mUserANet, mCarolId);
479
+ if (!rm.ok) throw new Error("revoke failed: " + rm.error);
480
+
481
+ const after = await (await fetch(`${BASE}/health`, {
482
+ headers: { Authorization: `Bearer ${mCarolToken}` },
483
+ })).json() as any;
484
+ expect(after.sse_sessions[`${mCarolNet}:${mCarolName}`]).toBeGreaterThanOrEqual(1);
485
+ // The revoked N_A must be gone. Mutation-red for any caching of
486
+ // the memberNets Set across requests.
487
+ expect(after.sse_sessions[`${mUserANet}:${mUserAName}`]).toBeUndefined();
488
+ });
489
+
490
+ // ── M6 — observer key format via shared constant ────────────────
491
+ test("M6: observer keys (\\0netobs:<net>) are classified through the shared prefix constant, member sees own network's observer entry", async () => {
492
+ const res = await fetch(`${BASE}/health`, {
493
+ headers: { Authorization: `Bearer ${mUserAToken}` },
494
+ });
495
+ const body = await res.json() as any;
496
+ // Observer key surfaces with the printable prefix (`\\0netobs:`)
497
+ // because push.ts's printableKey renders the NUL byte as `\\0`.
498
+ // The filter must classify this as belonging to `mUserANet` and
499
+ // include it in userA's view.
500
+ const observerKey = `\\0netobs:${mUserANet}`;
501
+ expect(body.sse_sessions[observerKey]).toBeGreaterThanOrEqual(1);
502
+ });
503
+
504
+ test("M6b: userB (not in N_A) does NOT see N_A's observer key — mutation-red for prefix constant drift", async () => {
505
+ const res = await fetch(`${BASE}/health`, {
506
+ headers: { Authorization: `Bearer ${mUserBToken}` },
507
+ });
508
+ const body = await res.json() as any;
509
+ const observerKey = `\\0netobs:${mUserANet}`;
510
+ // If the prefix constant drifts (e.g. server.ts checks "netobs:"
511
+ // without `\\0`), the classifier falls through to `key.split(":")[0]`
512
+ // which for a `\\0netobs:` key returns the literal `\\0netobs` string
513
+ // — that would never match memberNets, so the observer key gets
514
+ // over-filtered but silently. That is the pre-CR3 bug shape;
515
+ // this assertion pins the "not in wrong tenant's view" side.
516
+ expect(body.sse_sessions[observerKey]).toBeUndefined();
517
+ });
518
+
519
+ // M7 removed — see beforeAll note. Cross-network same-alias
520
+ // invisibility is covered structurally by M1/M2: keys are
521
+ // `<netId>:<alias>`, so a `<N_A>:foo` vs `<N_B>:foo` collision
522
+ // resolves via network prefix, which is what M2's cross-network
523
+ // absence assertion already pins.
524
+ });
525
+
526
+ // ── #506 — same alias, two networks: /health sse_sessions must not cross ──
527
+ //
528
+ // #505 restored auth-gated `sse_sessions`. Its member filter parses the
529
+ // `{networkId}:{alias}` key prefix and keeps only the caller's networks.
530
+ // That was verified at merge time by a standalone validator, but a
531
+ // validator does not re-run on future refactors — this pins it.
532
+ //
533
+ // Construction: the dashboard-user SSE gate only lets a caller subscribe
534
+ // to its own username (gate 4a), so two users can never share one key that
535
+ // way. Gate 4b is the usable path: any member may subscribe to an alias
536
+ // that exists as a session IN THEIR network. So we seed a session row with
537
+ // the SAME alias in two different networks and have each network's own
538
+ // member subscribe to it — producing `{N_A}:{alias}` and `{N_B}:{alias}`
539
+ // live at once, which is exactly the collision the filter must separate.
540
+ //
541
+ // Mutation-red (verified by hand, see the PR): replacing the member filter
542
+ // with `scopedSessions = sse.sessions` turns the two "must NOT contain the
543
+ // other network's key" assertions red.
544
+ describe("#506 cross-network isolation of /health sse_sessions (same alias, two networks)", () => {
545
+ const SHARED_ALIAS = "shared-alias-506";
546
+ let aToken = "", aNet = "", aName = "";
547
+ let bToken = "", bNet = "", bName = "";
548
+ let readerA: ReadableStreamDefaultReader<Uint8Array> | null = null;
549
+ let readerB: ReadableStreamDefaultReader<Uint8Array> | null = null;
550
+
551
+ beforeAll(async () => {
552
+ const sfx = `${Date.now()}_${Math.floor(Math.random() * 1000)}`;
553
+ const pw = "BootstrapPw123Aa!";
554
+
555
+ // Probe users are registered AFTER the suite's seed user, so neither is
556
+ // the auto-admin first user. Asserted below rather than assumed: an
557
+ // admin caller takes the unfiltered branch and would make these tests
558
+ // pass while proving nothing.
559
+ const ra = register(`h506_a_${sfx}`, pw, undefined, "seed");
560
+ const rb = register(`h506_b_${sfx}`, pw, undefined, "seed");
561
+ if (!ra.ok || !ra.token || !rb.ok || !rb.token) throw new Error("506 register failed");
562
+ aName = `h506_a_${sfx}`; aToken = ra.token; aNet = ra.network_id ?? "";
563
+ bName = `h506_b_${sfx}`; bToken = rb.token; bNet = rb.network_id ?? "";
564
+ if (!aNet || !bNet || aNet === bNet) throw new Error("506 needs two distinct networks");
565
+ db.run("UPDATE users SET role = 'user' WHERE username IN (?1, ?2)", [aName, bName]);
566
+
567
+ // Same alias name, one session row per network → gate 4b lets each
568
+ // network's own member subscribe to it.
569
+ for (const [net, tag] of [[aNet, "a"], [bNet, "b"]] as const) {
570
+ db.run(
571
+ `INSERT INTO sessions (resume_id, alias, network_id, last_seen_at, status)
572
+ VALUES (?1, ?2, ?3, datetime('now'), 'idle')`,
573
+ [`s_506_${tag}_${sfx}`, SHARED_ALIAS, net],
574
+ );
575
+ }
576
+
577
+ const sub = async (token: string, net: string) => {
578
+ const res = await fetch(
579
+ `${BASE}/events/${encodeURIComponent(SHARED_ALIAS)}?network_id=${encodeURIComponent(net)}`,
580
+ { headers: { Authorization: `Bearer ${token}` } },
581
+ );
582
+ if (res.status !== 200) throw new Error(`506 SSE subscribe failed (${net}): ${res.status}`);
583
+ const rd = res.body!.getReader();
584
+ await rd.read(); // connected frame → key registered
585
+ return rd;
586
+ };
587
+ readerA = await sub(aToken, aNet);
588
+ readerB = await sub(bToken, bNet);
589
+ });
590
+
591
+ afterAll(() => {
592
+ try { readerA?.cancel(); } catch {}
593
+ try { readerB?.cancel(); } catch {}
594
+ });
595
+
596
+ test("probe users are NOT admin (an admin caller would bypass the filter and prove nothing)", () => {
597
+ for (const n of [aName, bName]) {
598
+ const row = db.get<{ role: string }>("SELECT role FROM users WHERE username = ?1", n);
599
+ expect(row?.role).not.toBe("admin");
600
+ }
601
+ });
602
+
603
+ test("both same-alias keys are live at once (the collision actually exists)", async () => {
604
+ // Read through the ops endpoint with the admin token: if this shows only
605
+ // one of the two keys, the fixture never built the collision and the
606
+ // isolation assertions below would be vacuous.
607
+ const res = await fetch(`${BASE}/api/stats/sse`, { headers: { Authorization: `Bearer ${adminToken}` } });
608
+ expect(res.status).toBe(200);
609
+ const body = await res.json() as { sessions?: Record<string, number> };
610
+ const keys = Object.keys(body.sessions ?? {});
611
+ expect(keys).toContain(`${aNet}:${SHARED_ALIAS}`);
612
+ expect(keys).toContain(`${bNet}:${SHARED_ALIAS}`);
613
+ });
614
+
615
+ test("member of network A sees only A's copy of the shared alias", async () => {
616
+ const res = await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${aToken}` } });
617
+ expect(res.status).toBe(200);
618
+ const body = await res.json() as { sse_sessions?: Record<string, number> };
619
+ expect(body.sse_sessions).toBeDefined();
620
+ const keys = Object.keys(body.sse_sessions!);
621
+ expect(keys).toContain(`${aNet}:${SHARED_ALIAS}`);
622
+ expect(keys).not.toContain(`${bNet}:${SHARED_ALIAS}`);
623
+ // Nothing from the other network at all, by any key shape.
624
+ expect(keys.some((k) => k.startsWith(`${bNet}:`))).toBe(false);
625
+ });
626
+
627
+ test("member of network B sees only B's copy (reverse direction)", async () => {
628
+ const res = await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${bToken}` } });
629
+ expect(res.status).toBe(200);
630
+ const body = await res.json() as { sse_sessions?: Record<string, number> };
631
+ expect(body.sse_sessions).toBeDefined();
632
+ const keys = Object.keys(body.sse_sessions!);
633
+ expect(keys).toContain(`${bNet}:${SHARED_ALIAS}`);
634
+ expect(keys).not.toContain(`${aNet}:${SHARED_ALIAS}`);
635
+ expect(keys.some((k) => k.startsWith(`${aNet}:`))).toBe(false);
636
+ });
637
+ });