@sleep2agi/commhub-server 0.9.0-preview.4 → 0.9.0-preview.41

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 (122) 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 +107 -13
  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-tool-schema.test.ts +39 -0
  19. package/src/create-node-validate.test.ts +80 -1
  20. package/src/create-node-validate.ts +49 -5
  21. package/src/create-node.ts +51 -1
  22. package/src/dashboard-slash-routing-http.test.ts +103 -0
  23. package/src/db-adapter-guard.test.ts +85 -0
  24. package/src/db-adapter.ts +64 -23
  25. package/src/db-timestamp.test.ts +38 -0
  26. package/src/db-timestamp.ts +15 -0
  27. package/src/db.ts +654 -33
  28. package/src/delivered-without-push.test.ts +140 -0
  29. package/src/desktop-message-seam.test.ts +150 -0
  30. package/src/desktop-message.test.ts +368 -0
  31. package/src/ext-token-shared.test.ts +60 -0
  32. package/src/ext-validation-regression.test.ts +131 -0
  33. package/src/external-schedule-edits-http.test.ts +316 -0
  34. package/src/external-schedule-edits.ts +314 -0
  35. package/src/file-download-authz-dev-open.test.ts +135 -0
  36. package/src/file-download-authz.test.ts +403 -0
  37. package/src/file-download-date-bucket.test.ts +436 -0
  38. package/src/file-network-scope-dev-open.test.ts +97 -0
  39. package/src/file-network-scope.test.ts +731 -0
  40. package/src/health-redaction.test.ts +637 -0
  41. package/src/inbox-count-sse.test.ts +310 -0
  42. package/src/inbox-count.ts +29 -0
  43. package/src/index.ts +15 -2187
  44. package/src/lifecycle-guard.ts +50 -0
  45. package/src/list-host-supervisors.test.ts +314 -0
  46. package/src/mcp-write-network-resolution.test.ts +429 -0
  47. package/src/network-name-http.test.ts +71 -0
  48. package/src/network-scope.ts +101 -0
  49. package/src/node-attrs-validate.ts +88 -0
  50. package/src/node-attrs.test.ts +213 -0
  51. package/src/node-id-alias.test.ts +147 -0
  52. package/src/node-lifecycle-controllable.test.ts +64 -0
  53. package/src/node-lifecycle-controllable.ts +51 -0
  54. package/src/observer-avatar-http.test.ts +424 -0
  55. package/src/observer-push.test.ts +252 -0
  56. package/src/package-version-consistency.test.ts +25 -0
  57. package/src/peer-reply-atomic.test.ts +455 -0
  58. package/src/peer-reply-capability.test.ts +70 -0
  59. package/src/probe-validate.test.ts +221 -0
  60. package/src/probe-validate.ts +104 -0
  61. package/src/probe.test.ts +80 -0
  62. package/src/probe.ts +200 -0
  63. package/src/push.ts +163 -7
  64. package/src/redact-tokens.test.ts +65 -0
  65. package/src/redact-tokens.ts +40 -0
  66. package/src/reply-target-derivation.test.ts +96 -0
  67. package/src/require-explicit-test-db.ts +9 -0
  68. package/src/resolve-port.test.ts +57 -0
  69. package/src/resolve-port.ts +44 -0
  70. package/src/response-charset.test.ts +130 -0
  71. package/src/rest-explicit-columns-http.test.ts +212 -0
  72. package/src/rest-identity.test.ts +129 -0
  73. package/src/rest-identity.ts +100 -0
  74. package/src/rest-projections.ts +67 -0
  75. package/src/rest-write-network-resolution.test.ts +133 -0
  76. package/src/runtime-label.test.ts +22 -0
  77. package/src/runtime-label.ts +21 -0
  78. package/src/scheduled-run-terminal.test.ts +268 -0
  79. package/src/scheduled-tasks-http.test.ts +479 -0
  80. package/src/scheduled-tasks.ts +549 -0
  81. package/src/send-reply-agent-warning.test.ts +202 -0
  82. package/src/send-reply-alias-optional.test.ts +131 -0
  83. package/src/send-reply-attachments.test.ts +437 -0
  84. package/src/server.ts +3664 -0
  85. package/src/shared/external-schedule-contract.ts +60 -0
  86. package/src/shared/probe-host-allowlist-drift.test.ts +54 -0
  87. package/src/shared/probe-host-allowlist.ts +128 -0
  88. package/src/side-thread-command-transport.test.ts +302 -0
  89. package/src/side-thread-command-transport.ts +318 -0
  90. package/src/side-thread-http-integration.test.ts +229 -0
  91. package/src/side-thread-http.ts +504 -0
  92. package/src/side-thread-production.test.ts +72 -0
  93. package/src/side-thread-production.ts +118 -0
  94. package/src/side-thread.test.ts +1067 -0
  95. package/src/side-thread.ts +2495 -0
  96. package/src/skillhub-http.test.ts +88 -0
  97. package/src/start-node.test.ts +109 -0
  98. package/src/stop-delete-node.test.ts +952 -0
  99. package/src/task-auth-origin-http.test.ts +87 -0
  100. package/src/task-auth-origin.test.ts +24 -0
  101. package/src/task-auth-origin.ts +7 -0
  102. package/src/task-consumption.test.ts +471 -0
  103. package/src/task-diagnostic-http.test.ts +145 -0
  104. package/src/task-diagnostic.test.ts +115 -0
  105. package/src/task-diagnostic.ts +118 -0
  106. package/src/task-idempotency-mcp.test.ts +142 -0
  107. package/src/task-idempotency.test.ts +60 -0
  108. package/src/task-idempotency.ts +75 -0
  109. package/src/task-lifecycle-watcher.test.ts +200 -0
  110. package/src/task-lifecycle-watcher.ts +49 -0
  111. package/src/task-network-resolution-http.test.ts +137 -0
  112. package/src/tasks-pagination-http.test.ts +137 -0
  113. package/src/tools.ts +2994 -191
  114. package/src/update-provider.test.ts +234 -0
  115. package/src/upload-early-reject-guard.test.ts +155 -0
  116. package/src/uploads-http.test.ts +92 -14
  117. package/src/uploads.test.ts +66 -0
  118. package/src/uploads.ts +130 -5
  119. package/src/user-inbox-read-http.test.ts +220 -0
  120. package/src/user-inbox-schema.test.ts +53 -0
  121. package/src/vault.test.ts +200 -0
  122. package/src/vault.ts +156 -0
@@ -0,0 +1,331 @@
1
+ import { afterAll, beforeEach, describe, expect, test } from "bun:test";
2
+ import { db } from "./db.js";
3
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
+ import { registerTools } from "./tools.js";
5
+
6
+ // RFC-026 §9.3 D2 / #338 PR3 — ack_create_request HANDLER tests.
7
+ //
8
+ // 通信龙 pre-review caught B1 + B2: my first cut of PR3 added a new daemon
9
+ // ack status `runtime_capability_check_failed` to create-node-daemon.ts but
10
+ // the hub's zod enum only accepted ["started", "failed", "rejected"] — the
11
+ // new status was silently zod-rejected on the hub side and the daemon's
12
+ // `.catch(()=>{})` swallowed the rejection. The PR body also claimed
13
+ // `daemon_capability_lied` audit was written when in fact the action wasn't
14
+ // in the audit enum and no insert ran.
15
+ //
16
+ // This handler-driven suite captures and invokes the registered callback
17
+ // directly. It validates handler branches and DB effects, but deliberately
18
+ // does NOT claim to exercise the MCP SDK's zod transport gate. The
19
+ // complementary in-process transport coverage lives in
20
+ // ack-create-request-transport.test.ts (#344).
21
+
22
+ const NET = "net_ack_t";
23
+ const DAEMON_NODE_ID = "node_ack_daemon";
24
+ const DAEMON_ALIAS = "ack-daemon";
25
+ const DAEMON_USER = "u_ack_owner";
26
+ const DAEMON_TOKEN_ID = "tok_ack_daemon";
27
+ const DAEMON_TOKEN_HASH = "hash_ack_daemon";
28
+
29
+ interface ToolHandler { (args: any, extra?: any): Promise<{ content: Array<{ type: "text"; text: string }> }>; }
30
+ interface AckReply { ok?: boolean; error?: string; status?: string; }
31
+
32
+ function cleanup() {
33
+ try { db.run("DELETE FROM audit_log WHERE network_id = ?1", [NET]); } catch {}
34
+ try { db.run("DELETE FROM node_create_requests WHERE network_id = ?1", [NET]); } catch {}
35
+ try { db.run("DELETE FROM nodes WHERE network_id = ?1", [NET]); } catch {}
36
+ try { db.run("DELETE FROM api_tokens WHERE network_id = ?1", [NET]); } catch {}
37
+ try { db.run("DELETE FROM network_members WHERE network_id = ?1", [NET]); } catch {}
38
+ try { db.run("DELETE FROM networks WHERE network_id = ?1", [NET]); } catch {}
39
+ try { db.run("DELETE FROM users WHERE user_id = ?1", [DAEMON_USER]); } catch {}
40
+ }
41
+
42
+ beforeEach(cleanup);
43
+ afterAll(cleanup);
44
+
45
+ function seedDaemonWorld() {
46
+ db.run(
47
+ `INSERT INTO users (user_id, username, password_hash, role, created_at)
48
+ VALUES (?1, ?2, 'x', 'user', datetime('now'))`,
49
+ [DAEMON_USER, DAEMON_USER],
50
+ );
51
+ db.run(
52
+ `INSERT OR REPLACE INTO networks (network_id, network_name, owner_id, created_at)
53
+ VALUES (?1, ?2, ?3, datetime('now'))`,
54
+ [NET, NET, DAEMON_USER],
55
+ );
56
+ db.run(
57
+ `INSERT INTO network_members (user_id, network_id, role, joined_at)
58
+ VALUES (?1, ?2, 'owner', datetime('now'))`,
59
+ [DAEMON_USER, NET],
60
+ );
61
+ // daemon node — must exist for resolveCallerDaemonTokenBound to bind.
62
+ db.run(
63
+ `INSERT INTO nodes (node_id, node_name, alias, network_id, created_at, updated_at)
64
+ VALUES (?1, ?2, ?3, ?4, datetime('now'), datetime('now'))`,
65
+ [DAEMON_NODE_ID, DAEMON_ALIAS, DAEMON_ALIAS, NET],
66
+ );
67
+ // daemon ntok — bound to the daemon node via name='node:<alias>'.
68
+ db.run(
69
+ `INSERT INTO api_tokens (token_id, user_id, network_id, scope, name, token_hash, expires_at, revoked_at)
70
+ VALUES (?1, ?2, ?3, 'network', ?4, ?5, NULL, NULL)`,
71
+ [DAEMON_TOKEN_ID, DAEMON_USER, NET, `node:${DAEMON_ALIAS}`, DAEMON_TOKEN_HASH],
72
+ );
73
+ }
74
+
75
+ function seedCreateRequest(opts: {
76
+ request_id: string,
77
+ child_token_id?: string,
78
+ status?: "pending" | "delivered" | "succeeded" | "failed",
79
+ child_name?: string,
80
+ runtime?: string,
81
+ }) {
82
+ const childName = opts.child_name ?? `child_${opts.request_id}`;
83
+ if (opts.child_token_id) {
84
+ db.run(
85
+ `INSERT INTO api_tokens (token_id, user_id, network_id, scope, name, token_hash, expires_at, revoked_at)
86
+ VALUES (?1, ?2, ?3, 'network', ?4, ?5, NULL, NULL)`,
87
+ [opts.child_token_id, DAEMON_USER, NET, `node:${childName}`, `hash_${opts.child_token_id}`],
88
+ );
89
+ }
90
+ db.run(
91
+ `INSERT INTO node_create_requests
92
+ (request_id, daemon_node_id, child_name, network_id, runtime, model, flags_json, env_keys, status, child_token_id, created_at, created_by_token)
93
+ VALUES (?1, ?2, ?3, ?4, ?5, 'x', '{}', '[]', ?6, ?7, ?8, ?9)`,
94
+ [
95
+ opts.request_id, DAEMON_NODE_ID, childName, NET,
96
+ opts.runtime ?? "claude-agent-sdk",
97
+ opts.status ?? "delivered",
98
+ opts.child_token_id ?? null,
99
+ Date.now(),
100
+ DAEMON_TOKEN_ID,
101
+ ],
102
+ );
103
+ }
104
+
105
+ /** Build a server with registerTools wired as if the daemon's ntok bound. */
106
+ function buildAckHandler(): ToolHandler {
107
+ const server = new McpServer({ name: "test", version: "0" }) as any;
108
+ const tools: Record<string, ToolHandler> = {};
109
+ const origTool = server.tool.bind(server);
110
+ server.tool = (name: string, _desc: string, _schema: any, handler: ToolHandler) => {
111
+ tools[name] = handler;
112
+ return origTool(name, _desc, _schema, handler);
113
+ };
114
+ const origRegisterTool = server.registerTool?.bind(server);
115
+ if (origRegisterTool) {
116
+ server.registerTool = (name: string, _cfg: any, handler: ToolHandler) => {
117
+ tools[name] = handler;
118
+ return origRegisterTool(name, _cfg, handler);
119
+ };
120
+ }
121
+ registerTools(
122
+ server,
123
+ /* clientIP */ undefined,
124
+ /* enforceNetworkId */ NET,
125
+ /* enforceUserId */ DAEMON_USER,
126
+ /* callerAlias */ DAEMON_ALIAS,
127
+ /* callerTokenIsNetwork */ true,
128
+ /* callerTokenId */ DAEMON_TOKEN_ID,
129
+ );
130
+ const h = tools["ack_create_request"];
131
+ if (!h) throw new Error("ack_create_request tool not registered");
132
+ return h;
133
+ }
134
+
135
+ async function callAck(handler: ToolHandler, args: any): Promise<AckReply> {
136
+ const r = await handler(args);
137
+ return JSON.parse(r.content[0].text) as AckReply;
138
+ }
139
+
140
+ function readRequest(request_id: string) {
141
+ return db.get<{ status: string; error: string | null; acked_at: number | null }>(
142
+ `SELECT status, error, acked_at FROM node_create_requests WHERE request_id = ?1`,
143
+ request_id,
144
+ );
145
+ }
146
+
147
+ function readToken(token_id: string) {
148
+ return db.get<{ revoked_at: string | null }>(
149
+ `SELECT revoked_at FROM api_tokens WHERE token_id = ?1`,
150
+ token_id,
151
+ );
152
+ }
153
+
154
+ function readAuditRows(action: string, target_id: string) {
155
+ return db.all<{ action: string; network_id: string; target_id: string; detail: string }>(
156
+ `SELECT action, network_id, target_id, detail FROM audit_log
157
+ WHERE action = ?1 AND target_id = ?2 ORDER BY id DESC`,
158
+ [action, target_id],
159
+ );
160
+ }
161
+
162
+ describe("ack_create_request HANDLER — B1 schema accepts runtime_capability_check_failed", () => {
163
+ test("schema accepts runtime_capability_check_failed + runtime field (no zod reject)", async () => {
164
+ seedDaemonWorld();
165
+ const reqId = "cr_ack_b1_accept";
166
+ seedCreateRequest({ request_id: reqId });
167
+ const handler = buildAckHandler();
168
+ const reply = await callAck(handler, {
169
+ request_id: reqId,
170
+ status: "runtime_capability_check_failed",
171
+ error: "child died within 5000ms post-spawn",
172
+ runtime: "codex-sdk",
173
+ });
174
+ // PR3 v1 BUG: hub zod enum rejected this status → reply.ok=false /
175
+ // tool would even throw before getting here. Now must accept.
176
+ expect(reply.ok).toBe(true);
177
+ expect(reply.status).toBe("runtime_capability_check_failed");
178
+ });
179
+
180
+ test("request flips to terminal runtime_capability_check_failed status", async () => {
181
+ seedDaemonWorld();
182
+ const reqId = "cr_ack_b1_terminal";
183
+ seedCreateRequest({ request_id: reqId, status: "delivered" });
184
+ const handler = buildAckHandler();
185
+ await callAck(handler, {
186
+ request_id: reqId,
187
+ status: "runtime_capability_check_failed",
188
+ error: "boom",
189
+ runtime: "codex-sdk",
190
+ });
191
+ const row = readRequest(reqId);
192
+ expect(row?.status).toBe("runtime_capability_check_failed");
193
+ expect(row?.error).toBe("boom");
194
+ expect(row?.acked_at).toBeGreaterThan(0);
195
+ });
196
+
197
+ test("child ntok is revoked on capability-check-failed (same teardown as 'failed')", async () => {
198
+ seedDaemonWorld();
199
+ const reqId = "cr_ack_b1_revoke";
200
+ const childTok = "tok_ack_child_b1";
201
+ seedCreateRequest({ request_id: reqId, child_token_id: childTok });
202
+ expect(readToken(childTok)?.revoked_at).toBeNull();
203
+ const handler = buildAckHandler();
204
+ await callAck(handler, {
205
+ request_id: reqId,
206
+ status: "runtime_capability_check_failed",
207
+ runtime: "codex-sdk",
208
+ });
209
+ expect(readToken(childTok)?.revoked_at).not.toBeNull();
210
+ });
211
+ });
212
+
213
+ describe("ack_create_request HANDLER — B2 audit_log daemon_capability_lied", () => {
214
+ test("writes daemon_capability_lied audit row with runtime + daemon + error in detail", async () => {
215
+ seedDaemonWorld();
216
+ const reqId = "cr_ack_b2_audit";
217
+ seedCreateRequest({ request_id: reqId });
218
+ const handler = buildAckHandler();
219
+ await callAck(handler, {
220
+ request_id: reqId,
221
+ status: "runtime_capability_check_failed",
222
+ error: "OPENAI_API_KEY unset",
223
+ runtime: "codex-sdk",
224
+ });
225
+ const rows = readAuditRows("daemon_capability_lied", reqId);
226
+ // PR3 v1 BUG: action wasn't in auditCreateNode enum → 0 rows + no
227
+ // surface for ops to spot lying daemons. Now must write exactly 1.
228
+ expect(rows.length).toBe(1);
229
+ expect(rows[0].network_id).toBe(NET);
230
+ const detail = JSON.parse(rows[0].detail);
231
+ expect(detail.runtime).toBe("codex-sdk");
232
+ expect(detail.daemon_node_id).toBe(DAEMON_NODE_ID);
233
+ expect(detail.error).toBe("OPENAI_API_KEY unset");
234
+ expect(typeof detail.acked_at).toBe("number");
235
+ });
236
+
237
+ test("does NOT write daemon_capability_lied on generic 'failed' ack (status discriminates)", async () => {
238
+ seedDaemonWorld();
239
+ const reqId = "cr_ack_b2_no_audit_on_failed";
240
+ seedCreateRequest({ request_id: reqId });
241
+ const handler = buildAckHandler();
242
+ await callAck(handler, {
243
+ request_id: reqId,
244
+ status: "failed",
245
+ error: "child died immediately after spawn",
246
+ });
247
+ const rows = readAuditRows("daemon_capability_lied", reqId);
248
+ expect(rows.length).toBe(0);
249
+ });
250
+
251
+ test("does NOT write daemon_capability_lied on 'started' (happy path silence)", async () => {
252
+ seedDaemonWorld();
253
+ const reqId = "cr_ack_b2_no_audit_on_started";
254
+ seedCreateRequest({ request_id: reqId });
255
+ const handler = buildAckHandler();
256
+ await callAck(handler, { request_id: reqId, status: "started", child_pid: 12345 });
257
+ const rows = readAuditRows("daemon_capability_lied", reqId);
258
+ expect(rows.length).toBe(0);
259
+ });
260
+
261
+ test("runtime field nullable if daemon omitted it (older daemon back-compat)", async () => {
262
+ // Older daemon (preview.10 and earlier) wouldn't send `runtime`.
263
+ // The hub must still accept + audit, just with runtime=null.
264
+ seedDaemonWorld();
265
+ const reqId = "cr_ack_b2_nullable_runtime";
266
+ seedCreateRequest({ request_id: reqId });
267
+ const handler = buildAckHandler();
268
+ const reply = await callAck(handler, {
269
+ request_id: reqId,
270
+ status: "runtime_capability_check_failed",
271
+ error: "child died",
272
+ });
273
+ expect(reply.ok).toBe(true);
274
+ const rows = readAuditRows("daemon_capability_lied", reqId);
275
+ expect(rows.length).toBe(1);
276
+ const detail = JSON.parse(rows[0].detail);
277
+ expect(detail.runtime).toBeNull();
278
+ });
279
+
280
+ test("error string is truncated to 500 chars in audit detail (defense vs giant payload)", async () => {
281
+ seedDaemonWorld();
282
+ const reqId = "cr_ack_b2_trunc";
283
+ seedCreateRequest({ request_id: reqId });
284
+ const handler = buildAckHandler();
285
+ const giant = "x".repeat(900);
286
+ await callAck(handler, {
287
+ request_id: reqId,
288
+ status: "runtime_capability_check_failed",
289
+ error: giant,
290
+ runtime: "codex-sdk",
291
+ });
292
+ const rows = readAuditRows("daemon_capability_lied", reqId);
293
+ expect(rows.length).toBe(1);
294
+ const detail = JSON.parse(rows[0].detail);
295
+ expect(detail.error.length).toBe(500);
296
+ });
297
+ });
298
+
299
+ describe("ack_create_request HANDLER — pre-existing happy-path stays green (regression)", () => {
300
+ test("status='started' still flips acked_at without terminal teardown", async () => {
301
+ seedDaemonWorld();
302
+ const reqId = "cr_ack_started_regression";
303
+ const childTok = "tok_ack_child_started";
304
+ seedCreateRequest({ request_id: reqId, child_token_id: childTok });
305
+ const handler = buildAckHandler();
306
+ const reply = await callAck(handler, { request_id: reqId, status: "started", child_pid: 7777 });
307
+ expect(reply.ok).toBe(true);
308
+ expect(reply.status).toBe("awaiting_register");
309
+ const row = readRequest(reqId);
310
+ // 'started' doesn't flip to terminal; status stays 'delivered'.
311
+ expect(row?.status).toBe("delivered");
312
+ expect(row?.acked_at).toBeGreaterThan(0);
313
+ // child ntok is NOT revoked on 'started'.
314
+ expect(readToken(childTok)?.revoked_at).toBeNull();
315
+ });
316
+
317
+ test("status='failed' still revokes child + flips to failed (no audit_log daemon_capability_lied)", async () => {
318
+ seedDaemonWorld();
319
+ const reqId = "cr_ack_failed_regression";
320
+ const childTok = "tok_ack_child_failed";
321
+ seedCreateRequest({ request_id: reqId, child_token_id: childTok });
322
+ const handler = buildAckHandler();
323
+ const reply = await callAck(handler, { request_id: reqId, status: "failed", error: "fork failed" });
324
+ expect(reply.ok).toBe(true);
325
+ const row = readRequest(reqId);
326
+ expect(row?.status).toBe("failed");
327
+ expect(row?.error).toBe("fork failed");
328
+ expect(readToken(childTok)?.revoked_at).not.toBeNull();
329
+ expect(readAuditRows("daemon_capability_lied", reqId).length).toBe(0);
330
+ });
331
+ });
@@ -0,0 +1,84 @@
1
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
+ import { mkdtempSync, rmSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { NETWORK_REST_COLUMNS } from "./rest-projections.js";
6
+
7
+ const PRIVATE_DB_DIR = mkdtempSync(join(tmpdir(), "anet-admin-networks-"));
8
+ process.env.COMMHUB_DB ||= join(PRIVATE_DB_DIR, "hub.db");
9
+
10
+ let server: ReturnType<typeof Bun.serve>;
11
+ let base = "";
12
+ let adminToken = "";
13
+ let memberToken = "";
14
+ let nodeToken = "";
15
+ let adminNetworkId = "";
16
+ let memberNetworkId = "";
17
+
18
+ async function listNetworks(token: string): Promise<any[]> {
19
+ const response = await fetch(`${base}/api/networks`, {
20
+ headers: { Authorization: `Bearer ${token}` },
21
+ });
22
+ expect(response.status).toBe(200);
23
+ const body = await response.json() as any;
24
+ expect(body.ok).toBe(true);
25
+ return body.networks;
26
+ }
27
+
28
+ beforeAll(async () => {
29
+ const { db } = await import("./db.js");
30
+ const { createNetworkTokenForNode, register } = await import("./auth.js");
31
+
32
+ // The first registered user is the global Hub admin. The second user owns a
33
+ // separate network and is intentionally not a member of the admin's network.
34
+ const admin = register(`admin_networks_${Date.now()}`, "AdminNetworks-Strong-1!", undefined, "admin");
35
+ expect(admin.ok).toBe(true);
36
+ adminToken = admin.token!;
37
+ adminNetworkId = admin.network_id!;
38
+
39
+ const member = register(`member_networks_${Date.now()}`, "MemberNetworks-Strong-1!", undefined, "member");
40
+ expect(member.ok).toBe(true);
41
+ memberToken = member.token!;
42
+ memberNetworkId = member.network_id!;
43
+
44
+ const memberUserId = db.get<{ user_id: string }>(
45
+ "SELECT user_id FROM users WHERE username LIKE 'member_networks_%' ORDER BY created_at DESC LIMIT 1",
46
+ )!.user_id;
47
+ const minted = createNetworkTokenForNode(memberUserId, memberNetworkId, "admin-networks-node");
48
+ expect(minted.ok).toBe(true);
49
+ nodeToken = minted.token!;
50
+
51
+ const mod = await import("./server.js");
52
+ server = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
53
+ base = `http://127.0.0.1:${server.port}`;
54
+ });
55
+
56
+ afterAll(() => {
57
+ try { server?.stop(true); } catch {}
58
+ try { rmSync(PRIVATE_DB_DIR, { recursive: true, force: true }); } catch {}
59
+ });
60
+
61
+ describe("GET /api/networks global-admin visibility (#94)", () => {
62
+ test("global admin utok sees every network without losing public shape", async () => {
63
+ const rows = await listNetworks(adminToken);
64
+ expect(new Set(rows.map((row) => row.network_id))).toEqual(new Set([adminNetworkId, memberNetworkId]));
65
+
66
+ const own = rows.find((row) => row.network_id === adminNetworkId);
67
+ const foreign = rows.find((row) => row.network_id === memberNetworkId);
68
+ expect(own.member_role).toBe("owner");
69
+ expect(foreign.member_role).toBe("admin");
70
+ expect(Object.keys(foreign).sort()).toEqual([...NETWORK_REST_COLUMNS, "member_role", "name"].sort());
71
+ });
72
+
73
+ test("ordinary utok remains limited to member networks", async () => {
74
+ const rows = await listNetworks(memberToken);
75
+ expect(rows.map((row) => row.network_id)).toEqual([memberNetworkId]);
76
+ expect(rows.some((row) => row.network_id === adminNetworkId)).toBe(false);
77
+ });
78
+
79
+ test("network token remains limited to its bound network", async () => {
80
+ const rows = await listNetworks(nodeToken);
81
+ expect(rows.map((row) => row.network_id)).toEqual([memberNetworkId]);
82
+ expect(rows.some((row) => row.network_id === adminNetworkId)).toBe(false);
83
+ });
84
+ });
@@ -0,0 +1,72 @@
1
+ import { expect, test } from "bun:test";
2
+ import { parseAliasFilter } from "./alias-filter";
3
+
4
+ test("no filter given means no filtering, not an empty match", () => {
5
+ for (const raw of [undefined, null, "", " ", ",", " , , "]) {
6
+ const f = parseAliasFilter(raw as any);
7
+ expect(f.aliases).toEqual([]);
8
+ expect(f.sql).toBe("");
9
+ }
10
+ });
11
+
12
+ test("a single alias produces one placeholder", () => {
13
+ const f = parseAliasFilter("TM门户马");
14
+ expect(f.aliases).toEqual(["TM门户马"]);
15
+ expect(f.sql).toBe(" AND alias IN (?)");
16
+ });
17
+
18
+ test("several aliases keep their order and count", () => {
19
+ const f = parseAliasFilter("A站内容,A站内容牛,hub");
20
+ expect(f.aliases).toEqual(["A站内容", "A站内容牛", "hub"]);
21
+ expect(f.sql).toBe(" AND alias IN (?,?,?)");
22
+ });
23
+
24
+ test("surrounding whitespace is trimmed", () => {
25
+ expect(parseAliasFilter(" a , b ").aliases).toEqual(["a", "b"]);
26
+ });
27
+
28
+ // The point of the module. A trailing comma must not become `alias = ''`,
29
+ // which matches nothing and reads exactly like "those nodes do not exist".
30
+ test("blank entries are dropped, never turned into a match-nothing term", () => {
31
+ const f = parseAliasFilter("a,,b,");
32
+ expect(f.aliases).toEqual(["a", "b"]);
33
+ expect(f.sql).toBe(" AND alias IN (?,?)");
34
+ expect(f.aliases).not.toContain("");
35
+ });
36
+
37
+ test("a filter of only commas is the same as no filter — it must not silently match zero rows", () => {
38
+ const f = parseAliasFilter(",,,");
39
+ expect(f.sql).toBe("");
40
+ });
41
+
42
+ test("placeholder count always equals alias count, so params can never misalign", () => {
43
+ for (const raw of ["a", "a,b", "a,,b", " a , b , c ", ",x,"]) {
44
+ const f = parseAliasFilter(raw);
45
+ expect((f.sql.match(/\?/g) ?? []).length).toBe(f.aliases.length);
46
+ }
47
+ });
48
+
49
+ test("aliases are passed through verbatim — no globbing, no case folding", () => {
50
+ const f = parseAliasFilter("A站内容,a站内容");
51
+ expect(f.aliases).toEqual(["A站内容", "a站内容"]);
52
+ expect(f.sql).not.toContain("LIKE");
53
+ });
54
+
55
+ // Wiring: the tool must actually use this module, and must say what its
56
+ // `summary` counted — a caller who asked about three aliases and gets back
57
+ // "idle: 96" can easily read the 96 as being about their three.
58
+ import { readFileSync } from "fs";
59
+ import { join } from "path";
60
+
61
+ test("get_all_status uses parseAliasFilter and declares what summary counted", () => {
62
+ const source = readFileSync(join(import.meta.dir, "tools.ts"), "utf8");
63
+ const a = source.indexOf('"get_all_status"');
64
+ expect(a).toBeGreaterThan(-1);
65
+ const body = source.slice(a, source.indexOf('server.tool(', a + 10));
66
+ expect(body).toContain("filter_alias");
67
+ expect(body).toContain("parseAliasFilter(filter_alias)");
68
+ expect(body).toContain("summary_scope");
69
+ expect(body).toContain("sessions_returned");
70
+ // The alias list must go through parameters, never be interpolated.
71
+ expect(body).not.toMatch(/alias IN \(\$\{/);
72
+ });
@@ -0,0 +1,32 @@
1
+ // Parse the `filter_alias` argument of `get_all_status` into an exact-match
2
+ // IN list.
3
+ //
4
+ // Why this exists at all: on a 222-session hub the unfiltered response is about
5
+ // 259 KB — past what an MCP client accepts in one result. A caller who wanted
6
+ // the status of three specific nodes could not get it from the tool, and had to
7
+ // go around it to the REST API. The filter is the fix; this module is the part
8
+ // of it worth pinning, because the interesting behaviour is what happens to the
9
+ // inputs that are not a clean alias.
10
+ //
11
+ // Blank entries are DROPPED rather than matched. A trailing comma would
12
+ // otherwise produce `alias = ''`, which matches no row — and "no rows" reads
13
+ // exactly like "those nodes do not exist". The failure and the true answer
14
+ // would be indistinguishable to the caller, which is the thing to avoid.
15
+
16
+ export interface AliasFilter {
17
+ /** Exact aliases to match. Empty means "no alias filtering". */
18
+ aliases: string[];
19
+ /** SQL fragment to append, or "" when there is nothing to filter on. */
20
+ sql: string;
21
+ }
22
+
23
+ export function parseAliasFilter(raw: string | undefined | null): AliasFilter {
24
+ const aliases = (raw ?? "")
25
+ .split(",")
26
+ .map(a => a.trim())
27
+ .filter(Boolean);
28
+ return {
29
+ aliases,
30
+ sql: aliases.length > 0 ? ` AND alias IN (${aliases.map(() => "?").join(",")})` : "",
31
+ };
32
+ }