@sleep2agi/commhub-server 0.9.0-preview.202 → 0.9.0-preview.204

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sleep2agi/commhub-server",
3
- "version": "0.9.0-preview.202",
3
+ "version": "0.9.0-preview.204",
4
4
  "description": "CommHub Server — AI Agent communication hub with MCP protocol, multi-network isolation, user auth, and MCP tools (17 collaboration-core + node/provider ops tools; authoritative list: docs-site/docs/api/mcp-tools.md).",
5
5
  "type": "module",
6
6
  "main": "src/index.ts",
@@ -24,6 +24,11 @@ const TLS = "n_gate_tls";
24
24
  // could rot without anyone noticing it is still accepted — seed it as its own
25
25
  // node rather than folding it in with TLS, so a regression reads by name.
26
26
  const LOOPBACK = "n_gate_loopback";
27
+ const UNKNOWN = "n_gate_unknown";
28
+ // #1510 补档 —— 生产里占绝大多数的是「从未上报」:2026-10-29 只读统计 373 个会话,
29
+ // env_transport = NULL 有 332 个(89%)。原实现是拒绝名单(只拒 plain),
30
+ // null 一路放行;卡里的口径是允许名单(只许 loopback/https)。这两者只在 null 上分歧,
31
+ // 所以这里把 null 当成一等公民单独种一个节点。
27
32
 
28
33
  const post = async (path: string, token: string, body: unknown) => {
29
34
  const r = await fetch(`${base}${path}`, {
@@ -48,7 +53,7 @@ beforeAll(async () => {
48
53
  net = owner.network_id!;
49
54
  ownerId = db.get<{ user_id: string }>("SELECT user_id FROM users WHERE username = ?1", `gate_owner_${stamp}`)!.user_id;
50
55
 
51
- const seed = (nodeId: string, transport: string) => db.run(
56
+ const seed = (nodeId: string, transport: string | null) => db.run(
52
57
  `INSERT INTO nodes (node_id, node_name, alias, network_id, lifecycle_state, config_snapshot)
53
58
  VALUES (?1, ?1, ?1, ?2, 'active', ?3)`,
54
59
  [nodeId, net, JSON.stringify({ node_secrets_capable: true })],
@@ -56,9 +61,10 @@ beforeAll(async () => {
56
61
  seed(PLAIN, "plain");
57
62
  seed(TLS, "https");
58
63
  seed(LOOPBACK, "loopback");
64
+ seed(UNKNOWN, null);
59
65
  // The transport is reported on the session row (that is where report_status
60
66
  // writes it).
61
- const session = (nodeId: string, transport: string) => db.run(
67
+ const session = (nodeId: string, transport: string | null) => db.run(
62
68
  `INSERT INTO sessions (resume_id, alias, status, node_id, network_id, env_transport, updated_at, last_seen_at)
63
69
  VALUES (?1, ?1, 'idle', ?1, ?2, ?3, datetime('now'), datetime('now'))`,
64
70
  [nodeId, net, transport],
@@ -66,6 +72,7 @@ beforeAll(async () => {
66
72
  session(PLAIN, "plain");
67
73
  session(TLS, "https");
68
74
  session(LOOPBACK, "loopback");
75
+ session(UNKNOWN, null); // 从未上报 transport
69
76
 
70
77
  const mod = await import("./server.js");
71
78
  server = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
@@ -81,12 +88,13 @@ beforeEach(async () => {
81
88
  // The lane allows one pending request per node; drain whatever the previous
82
89
  // case left so the next one starts clean.
83
90
  const { pullNodeSecrets, ackNodeSecrets } = await import("./scoped-secrets.js");
84
- for (const nodeId of [PLAIN, TLS, LOOPBACK]) {
91
+ for (const nodeId of [PLAIN, TLS, LOOPBACK, UNKNOWN]) {
85
92
  const daemon = { ok: true as const, networkId: net, daemonNodeId: nodeId, daemonAlias: nodeId };
86
93
  const pulled = pullNodeSecrets(daemon) as any;
87
94
  for (const r of (pulled?.requests ?? [])) ackNodeSecrets(daemon, r.request_id, null, true);
88
95
  }
89
96
  process.env.ANET_SECRET_TRANSPORT_GATE = "log";
97
+ delete process.env.ANET_SECRET_TRANSPORT_GATE_STRICT;
90
98
  });
91
99
 
92
100
  describe("log mode (default)", () => {
@@ -175,3 +183,58 @@ describe("the log endpoint is owner/admin only", () => {
175
183
  expect(r.status).toBe(403);
176
184
  });
177
185
  });
186
+
187
+ // #1510 补档 —— 「未知 transport」必须有名字,而且默认不能被当成「不安全」。
188
+ //
189
+ // 生产数据(2026-10-29 只读):373 个会话里 332 个 env_transport = NULL。
190
+ // 如果 enforce 默认就把 null 拒掉,打开开关当天就会拦掉近九成节点 —— 那不是收紧,
191
+ // 那是一次不在计划内的下线。所以:
192
+ // · 默认(strict 关):null 放行,且不进 would-refuse 表(不制造噪声)
193
+ // · 显式 ANET_SECRET_TRANSPORT_GATE_STRICT=1:null 拒,原因码单独叫
194
+ // secret_transport_unknown —— 运维看到这个码,知道要去做的是「让节点上报」,
195
+ // 而不是去查某台机器的网络链路
196
+ describe("#1510 未知 transport(未上报)", () => {
197
+ const putTo = (nodeId: string, key: string) =>
198
+ post(`/api/nodes/${nodeId}/secrets?network_id=${net}`, ownerToken, { action: "put", key, value: "v", revision: 1 });
199
+
200
+ test("log 模式:未上报的节点不受影响,也不进 would-refuse 表", async () => {
201
+ const before = (await get(`/api/networks/${net}/env-transport-log`, ownerToken)).body.total;
202
+ const r = await putTo(UNKNOWN, "U1_KEY");
203
+ expect(r.status).toBe(200);
204
+ expect(r.body.ok).toBe(true);
205
+ const after = (await get(`/api/networks/${net}/env-transport-log`, ownerToken)).body.total;
206
+ expect(after).toBe(before);
207
+ });
208
+
209
+ test("enforce 但 strict 关:未上报仍然放行(默认不收紧到「未知即拒」)", async () => {
210
+ process.env.ANET_SECRET_TRANSPORT_GATE = "enforce";
211
+ const r = await putTo(UNKNOWN, "U2_KEY");
212
+ expect(r.status).toBe(200);
213
+ expect(r.body.ok).toBe(true);
214
+ });
215
+
216
+ test("enforce + strict:未上报被拒,原因码是 secret_transport_unknown(不是 plain)", async () => {
217
+ process.env.ANET_SECRET_TRANSPORT_GATE = "enforce";
218
+ process.env.ANET_SECRET_TRANSPORT_GATE_STRICT = "1";
219
+ const r = await putTo(UNKNOWN, "U3_KEY");
220
+ expect(r.status).toBe(400);
221
+ expect(r.body.error).toBe("secret_transport_unknown");
222
+ });
223
+
224
+ test("enforce + strict:明确 plain 的原因码不受影响,仍是 secret_transport_plain", async () => {
225
+ process.env.ANET_SECRET_TRANSPORT_GATE = "enforce";
226
+ process.env.ANET_SECRET_TRANSPORT_GATE_STRICT = "1";
227
+ const r = await putTo(PLAIN, "U4_KEY");
228
+ expect(r.status).toBe(400);
229
+ expect(r.body.error).toBe("secret_transport_plain");
230
+ });
231
+
232
+ test("enforce + strict:loopback / https 仍然放行(收紧不能倒向坏另一边)", async () => {
233
+ process.env.ANET_SECRET_TRANSPORT_GATE = "enforce";
234
+ process.env.ANET_SECRET_TRANSPORT_GATE_STRICT = "1";
235
+ for (const [node, key] of [[LOOPBACK, "U5_KEY"], [TLS, "U6_KEY"]] as const) {
236
+ const r = await putTo(node, key);
237
+ expect(r.body.ok).toBe(true);
238
+ }
239
+ });
240
+ });
@@ -10,7 +10,7 @@
10
10
  // Hourly aggregation, like node_permission_log: a chatty node must not turn this
11
11
  // into one row per write.
12
12
  import { db } from "./db.js";
13
- import { getEnvTransportMode } from "./env-transport-policy.js";
13
+ import { getEnvTransportMode, secretTransportVerdict } from "./env-transport-policy.js";
14
14
 
15
15
  const HOURS_RETAINED = 30 * 24;
16
16
  const MAX_ROWS = 20_000;
@@ -57,12 +57,18 @@ export function transportOf(networkId: string, nodeId: string): string | null {
57
57
  return row?.env_transport ?? null;
58
58
  }
59
59
 
60
- /** Called from the write lanes. Logs when the current policy would refuse. */
60
+ /** Called from the write lanes. Logs when the current policy would refuse.
61
+ *
62
+ * #1510 补丁:以前这里写死了「只有 plain 才记」,于是日得表**永远只反映一种原因**。
63
+ * 现在改成问 `secretTransportVerdict`(把模式仮定为 enforce):
64
+ * 「如果现在打开 enforce,这一笔会不会被拒、原因是什么」—— 表格才是决策输入。
65
+ * 默认 strict 关闭时结果与以前完全一致(只记 plain)。 */
61
66
  export function observeSecretWrite(networkId: string, nodeId: string, route: string): void {
62
67
  if (getEnvTransportMode() !== "log") return;
63
68
  const transport = transportOf(networkId, nodeId);
64
- if (transport !== "plain") return;
65
- noteEnvTransportWouldRefuse(networkId, nodeId, route, `transport=${transport}`);
69
+ const would = secretTransportVerdict(transport, { ...process.env, ANET_SECRET_TRANSPORT_GATE: "enforce" });
70
+ if (!would) return;
71
+ noteEnvTransportWouldRefuse(networkId, nodeId, route, `${would} transport=${transport ?? "unknown"}`);
66
72
  }
67
73
 
68
74
  export function readEnvTransportLog(networkId: string, sinceHour: string) {
@@ -15,7 +15,42 @@ export function getEnvTransportMode(env: Record<string, string | undefined> = pr
15
15
  return "log";
16
16
  }
17
17
 
18
- /** True when a write to a node reporting `plain` must be refused. */
19
- export function refusesPlainTransport(transport: string | null, env: Record<string, string | undefined> = process.env): boolean {
20
- return getEnvTransportMode(env) === "enforce" && transport === "plain";
18
+
19
+ /**
20
+ * #1510(补「未知」这一档)—— enforce 到底拒什么。
21
+ *
22
+ * 原实现是**拒绝名单**:只拒 `plain`,其余(含 `null` = 从未上报)一律放行。
23
+ * 卡里的口径是**允许名单**:「只有 loopback 或 https 才允许把密钥转发给节点」。
24
+ * 两者在 `null` 上分歧最大,而生产现状是(2026-10-29 只读统计,373 个会话):
25
+ *
26
+ * env_transport = NULL 332 ← 89% 从未上报
27
+ * plain 33
28
+ * loopback 7
29
+ * https 1
30
+ *
31
+ * 所以「未知即拒」不能直接当成默认:一打开 enforce 就会拦掉近九成节点。
32
+ * 它必须是一个**额外显式打开**的开关(`ANET_SECRET_TRANSPORT_GATE_STRICT=1`),
33
+ * 让运维在看清「未知有多少」之后自己决定什么时候收紧。
34
+ *
35
+ * 返回值直接就是拒绝原因码,避免调用方各自拼自符串:
36
+ * "secret_transport_plain" — 明确是明文公网
37
+ * "secret_transport_unknown" — 从未上报(仅 strict 下拒)
38
+ * null — 允许
39
+ */
40
+ export type SecretTransportVerdict = "secret_transport_plain" | "secret_transport_unknown" | null;
41
+
42
+ /** 「未知即拒」的显式开关。默认关。 */
43
+ export function getEnvTransportStrict(env: Record<string, string | undefined> = process.env): boolean {
44
+ const raw = (env.ANET_SECRET_TRANSPORT_GATE_STRICT ?? "").trim().toLowerCase();
45
+ return raw === "1" || raw === "true" || raw === "on" || raw === "yes";
46
+ }
47
+
48
+ export function secretTransportVerdict(
49
+ transport: string | null,
50
+ env: Record<string, string | undefined> = process.env,
51
+ ): SecretTransportVerdict {
52
+ if (getEnvTransportMode(env) !== "enforce") return null;
53
+ if (transport === "plain") return "secret_transport_plain";
54
+ if (transport === "loopback" || transport === "https") return null;
55
+ return getEnvTransportStrict(env) ? "secret_transport_unknown" : null;
21
56
  }
@@ -343,3 +343,107 @@ describe("bookkeeping", () => {
343
343
  expect(db.get("SELECT 1 AS hit FROM node_permission_log WHERE route = 'old'")).toBeFalsy();
344
344
  });
345
345
  });
346
+
347
+ // #2969 / #1510 —— 「能设」之外还差一半:「能看到当前设的是什么」。
348
+ //
349
+ // 两张白名单原先只有 PUT,`GET /api/nodes` 里一个字都没有,客户端因此做不出
350
+ // 「当前设置」这一屏 —— 能写不能读,等于逼用户凭记忆操作。
351
+ // 同一处还给 #1510 的严格模式留了眼睛:管理员要能看出谁的 transport 未知。
352
+ describe("GET /api/nodes 读回白名单与 transport", () => {
353
+ const rowOf = async (nodeId: string) => {
354
+ const r = await call(user.boss.token, "GET", `/api/nodes?network_id=${net}&node_id=${nodeId}`);
355
+ expect(r.status).toBe(200);
356
+ expect(r.body.nodes).toHaveLength(1);
357
+ return r.body.nodes[0];
358
+ };
359
+
360
+ test("默认是 null(= 不限制),不是空数组", async () => {
361
+ const row = await rowOf(node.other.id);
362
+ expect(row.peer_allowlist).toBeNull();
363
+ expect(row.tool_allowlist).toBeNull();
364
+ });
365
+
366
+ test("写进去什么,读出来就是什么", async () => {
367
+ expect((await call(user.boss.token, "PUT", `/api/nodes/${node.other.id}/peer-allowlist`, { peers: ["boss", node.nR.id] })).status).toBe(200);
368
+ expect((await call(user.boss.token, "PUT", `/api/nodes/${node.other.id}/tool-allowlist`, { tools: ["send_task", "get_inbox"] })).status).toBe(200);
369
+ const row = await rowOf(node.other.id);
370
+ expect(row.peer_allowlist).toEqual(["boss", node.nR.id]);
371
+ expect(row.tool_allowlist).toEqual(["send_task", "get_inbox"]);
372
+ });
373
+
374
+ test("清空后回到 null,而不是 []", async () => {
375
+ expect((await call(user.boss.token, "PUT", `/api/nodes/${node.other.id}/peer-allowlist`, { peers: null })).status).toBe(200);
376
+ expect((await call(user.boss.token, "PUT", `/api/nodes/${node.other.id}/tool-allowlist`, { tools: null })).status).toBe(200);
377
+ const row = await rowOf(node.other.id);
378
+ expect(row.peer_allowlist).toBeNull();
379
+ expect(row.tool_allowlist).toBeNull();
380
+ });
381
+
382
+ test("env_transport 取该节点最新一次上报(老上报不能盖掉新的)", async () => {
383
+ // 两行同 node_id、不同时间:取 updated_at 更大的那条。
384
+ db.run("DELETE FROM sessions WHERE node_id = ?1", [node.nR.id]);
385
+ db.run("INSERT INTO sessions (resume_id, alias, status, node_id, network_id, env_transport, updated_at) VALUES (?1, ?2, 'idle', ?3, ?4, 'plain', datetime('now','-2 hour'))",
386
+ [`r_old_${node.nR.id}`, "r-old-alias", node.nR.id, net]);
387
+ db.run("INSERT INTO sessions (resume_id, alias, status, node_id, network_id, env_transport, updated_at) VALUES (?1, ?2, 'idle', ?3, ?4, 'https', datetime('now','-1 minute'))",
388
+ [`r_new_${node.nR.id}`, "r-new-alias", node.nR.id, net]);
389
+ expect((await rowOf(node.nR.id)).env_transport).toBe("https");
390
+ });
391
+
392
+ test("从没上报过的节点是 null(不是猜一个值填上)", async () => {
393
+ db.run("UPDATE sessions SET env_transport = NULL WHERE node_id = ?1", [node.nR.id]);
394
+ expect((await rowOf(node.nR.id)).env_transport).toBeNull();
395
+ });
396
+
397
+ test("别的网络里的同名字段不会串到这一格(alias 兜底必须带网络约束)", async () => {
398
+ // 场景:本网络有一台节点,它的 sessions 行只用 alias 命中(node_id 为空,
399
+ // alias 就等于节点 id —— 老注册路径就是这样)。
400
+ // 另一个网络里**恰好也有一个 alias 相同的 sessions 行**,而且是明文公网、时间更新。
401
+ //
402
+ // 如果兜底查询不按网络约束,这一格会把 B 网的 'plain' 显示成 A 网这台节点的 transport。
403
+ // 这一格是给人做安全决策用的(决定要不要打开 strict)——
404
+ // 显示错的 'plain' 会让人以为挡住了,其实挡的是别人;显示 null 至少会让人去查。
405
+ const shadowId = `n_np_shadow_${stamp}`;
406
+ db.run("INSERT INTO nodes (node_id, node_name, alias, network_id, lifecycle_state) VALUES (?1, ?1, ?2, ?3, 'active')",
407
+ [shadowId, `shadow-${stamp}`, net]);
408
+ db.run("INSERT INTO sessions (resume_id, alias, status, node_id, network_id, env_transport, updated_at) VALUES (?1, ?2, 'idle', NULL, ?3, 'https', datetime('now','-1 hour'))",
409
+ [`s_shadow_${stamp}`, shadowId, net]);
410
+ const otherOwner = register(`np_othernet_${stamp}_${Date.now()}`, PW);
411
+ db.run("INSERT INTO sessions (resume_id, alias, status, node_id, network_id, env_transport, updated_at) VALUES (?1, ?2, 'idle', NULL, ?3, 'plain', datetime('now','+1 hour'))",
412
+ [`s_shadow_other_${stamp}`, shadowId, otherOwner.network_id!]);
413
+
414
+ // 本网络这台的 'https' 必须赢;时间更新的 'plain' 不能跨网络串进来。
415
+ expect((await rowOf(shadowId)).env_transport).toBe("https");
416
+ });
417
+ });
418
+
419
+ // #2969 —— 空数组是歧义的,Hub 直接拒,不猜。
420
+ //
421
+ // 客户端(PR #1165)把「[] = 不允许任何」做进了界面,而 Hub 的 `length ? … : null`
422
+ // 会把 [] 规范化成 null = 不限制。两边语义相反:用户以为收紧了,系统其实放开了。
423
+ // 三种做法里选了最不含糊的一种 —— 拒收,让调用方当场看到 400 和「清空请传 null」。
424
+ describe("空数组不猜:拒收,清空请传 null", () => {
425
+ test("PUT tool-allowlist [] → 400 empty_allowlist_ambiguous,且没改动库里已有值", async () => {
426
+ expect((await call(user.boss.token, "PUT", `/api/nodes/${node.other.id}/tool-allowlist`, { tools: ["send_task"] })).status).toBe(200);
427
+ const r = await call(user.boss.token, "PUT", `/api/nodes/${node.other.id}/tool-allowlist`, { tools: [] });
428
+ expect(r.status).toBe(400);
429
+ expect(r.body.error).toBe("empty_allowlist_ambiguous");
430
+ // 关键:拒收不能顺手把它清掉 —— 那等于「报错了,但行为已经变了」。
431
+ const row = await call(user.boss.token, "GET", `/api/nodes?network_id=${net}&node_id=${node.other.id}`);
432
+ expect(row.body.nodes[0].tool_allowlist).toEqual(["send_task"]);
433
+ });
434
+
435
+ test("PUT peer-allowlist [] → 400,库里也没变", async () => {
436
+ expect((await call(user.boss.token, "PUT", `/api/nodes/${node.other.id}/peer-allowlist`, { peers: ["boss"] })).status).toBe(200);
437
+ const r = await call(user.boss.token, "PUT", `/api/nodes/${node.other.id}/peer-allowlist`, { peers: [] });
438
+ expect(r.status).toBe(400);
439
+ expect(r.body.error).toBe("empty_allowlist_ambiguous");
440
+ const row = await call(user.boss.token, "GET", `/api/nodes?network_id=${net}&node_id=${node.other.id}`);
441
+ expect(row.body.nodes[0].peer_allowlist).toEqual(["boss"]);
442
+ });
443
+
444
+ test("清空走 null:200,读回来是 null(不是 [])", async () => {
445
+ expect((await call(user.boss.token, "PUT", `/api/nodes/${node.other.id}/tool-allowlist`, { tools: null })).status).toBe(200);
446
+ const row = await call(user.boss.token, "GET", `/api/nodes?network_id=${net}&node_id=${node.other.id}`);
447
+ expect(row.body.nodes[0].tool_allowlist).toBeNull();
448
+ });
449
+ });
@@ -150,7 +150,7 @@ export type NodeIdentity = {
150
150
  toolAllowlist: string[] | null;
151
151
  };
152
152
 
153
- function normalizePeerAllowlist(raw: unknown): string[] | null {
153
+ export function normalizePeerAllowlist(raw: unknown): string[] | null {
154
154
  if (typeof raw !== "string" || !raw.trim()) return null;
155
155
  try {
156
156
  const parsed = JSON.parse(raw);
@@ -160,7 +160,7 @@ function normalizePeerAllowlist(raw: unknown): string[] | null {
160
160
  } catch { return null; }
161
161
  }
162
162
 
163
- const normalizeToolAllowlist = normalizePeerAllowlist;
163
+ export const normalizeToolAllowlist = normalizePeerAllowlist;
164
164
 
165
165
  function normalizeMode(raw: unknown): NodePermissionMode {
166
166
  return raw === "readonly" || raw === "restricted" ? raw : "normal";
@@ -5,7 +5,7 @@ import { getUserNetworkRole } from './auth';
5
5
  import { providerScanTargets } from './daemon-provider-snapshots';
6
6
  import { validScopedSecretKey } from './shared/scoped-secret-contract';
7
7
  import { observeSecretWrite, transportOf } from './env-transport-gate.js';
8
- import { refusesPlainTransport } from './env-transport-policy.js';
8
+ import { secretTransportVerdict } from './env-transport-policy.js';
9
9
  type Human = { userId?: string | null; isNode: boolean; networkId: string | null };
10
10
  type Daemon = { ok: false; error: string } | { ok: true; networkId: string; daemonNodeId: string; daemonAlias: string };
11
11
  type Request = { request_id: string; network_id: string; daemon_node_id: string | null; node_id: string | null;
@@ -43,7 +43,8 @@ export function requestNodeSecrets(h: Human, node: string, action: Request['acti
43
43
  // that is the only action worth observing; delete/list leak nothing.
44
44
  if (action === 'put') {
45
45
  const transport = transportOf(h.networkId!, node);
46
- if (refusesPlainTransport(transport)) return denied('secret_transport_plain');
46
+ const verdict = secretTransportVerdict(transport);
47
+ if (verdict) return denied(verdict);
47
48
  observeSecretWrite(h.networkId!, node, `node_secret_${action}`);
48
49
  }
49
50
  if ([...requests.values()].some(r => r.network_id === h.networkId && r.daemon_node_id === null && r.node_id === node && r.status === 'pending')) return denied('secret_store_busy');
@@ -89,7 +90,8 @@ export function requestScopedSecrets(h: Human, daemon: string, node: string | nu
89
90
  // #1510 — same observation on the daemon lane (the daemon applies the value).
90
91
  if (action === 'put') {
91
92
  const transport = transportOf(h.networkId!, daemon);
92
- if (refusesPlainTransport(transport)) return denied('secret_transport_plain');
93
+ const verdict = secretTransportVerdict(transport);
94
+ if (verdict) return denied(verdict);
93
95
  observeSecretWrite(h.networkId!, daemon, `secret_${action}`);
94
96
  }
95
97
  if ([...requests.values()].some(r => r.network_id === h.networkId && r.daemon_node_id === daemon && r.status === 'pending')) return denied('secret_store_busy');
package/src/server.ts CHANGED
@@ -107,6 +107,7 @@ import { handleRequirementsRequest } from "./requirements.js";
107
107
  import { readHubProviders } from "./hub-provider-config.js";
108
108
  import { requestNodeSecrets, getScopedSecrets } from "./scoped-secrets.js";
109
109
  import { readEnvTransportLog } from "./env-transport-gate.js";
110
+ import { normalizePeerAllowlist, normalizeToolAllowlist } from "./node-permissions.js";
110
111
  import { labelRoute, mcpRouteLabel, recordRouteTiming, routeStats, setRouteCallerMasterToken, setRouteCallerTokenReader } from "./route-timing.js";
111
112
  import { handleExternalScheduleEditRequest } from "./external-schedule-edits.js";
112
113
  import { createNodeSessionControlRelay } from "./node-session-control.js";
@@ -2952,6 +2953,23 @@ return Bun.serve({
2952
2953
  const tools = Array.isArray(rawTools)
2953
2954
  ? rawTools.filter((x: unknown): x is string => typeof x === "string" && x.trim().length > 0).map((x: string) => x.trim())
2954
2955
  : [];
2956
+ // #2969 —— 空数组是**歧义的**,直接拒,不猜。
2957
+ //
2958
+ // 发生过的事:客户端把「[] = 不允许任何工具」做进了界面(PR #1165),
2959
+ // 而 Hub 这边 `tools.length ? ... : null` 会把 [] 规范化成 null = **不限制**。
2960
+ // 两边语义相反,结果是「用户以为收紧了,系统其实放开了」——比没有这个选项更糟。
2961
+ //
2962
+ // 三种做法里选了最不含糊的一种:
2963
+ // · 把 [] 当「禁止一切」 → 老客户端「清空」按钮会变成把节点封死,回归风险太大
2964
+ // · 把 [] 当 null(现状) → 界面可以无声地说「全部禁止」而实际全放开,安全洞
2965
+ // · 拒收 [](本实现) → 调用方当场看到 400 和一句「清空请传 null」,没有静默行为
2966
+ if (Array.isArray(rawTools) && tools.length === 0) {
2967
+ return withCors(req, Response.json({
2968
+ ok: false,
2969
+ error: "empty_allowlist_ambiguous",
2970
+ message: "send null to clear the allowlist (no restriction); an empty array is ambiguous and is rejected",
2971
+ }, { status: 400 }));
2972
+ }
2955
2973
  if (tools.length > 500) {
2956
2974
  return withCors(req, Response.json({ ok: false, error: "too_many_tools", message: "at most 500 entries" }, { status: 400 }));
2957
2975
  }
@@ -2984,6 +3002,14 @@ return Bun.serve({
2984
3002
  const peers = Array.isArray(rawPeers)
2985
3003
  ? rawPeers.filter((x: unknown): x is string => typeof x === "string" && x.trim().length > 0).map((x: string) => x.trim())
2986
3004
  : [];
3005
+ // 同 tool-allowlist:空数组歧义,拒收;清空请传 null。
3006
+ if (Array.isArray(rawPeers) && peers.length === 0) {
3007
+ return withCors(req, Response.json({
3008
+ ok: false,
3009
+ error: "empty_allowlist_ambiguous",
3010
+ message: "send null to clear the allowlist (no restriction); an empty array is ambiguous and is rejected",
3011
+ }, { status: 400 }));
3012
+ }
2987
3013
  if (peers.length > 200) {
2988
3014
  return withCors(req, Response.json({ ok: false, error: "too_many_peers", message: "at most 200 entries" }, { status: 400 }));
2989
3015
  }
@@ -5310,7 +5336,7 @@ return Bun.serve({
5310
5336
  network_id, created_at, updated_at,
5311
5337
  config_snapshot, lifecycle_state, avatar_url,
5312
5338
  display_name, team, tags, attrs_revision, permission_mode, owner_user_id,
5313
- department_id
5339
+ department_id, peer_allowlist, tool_allowlist
5314
5340
  FROM nodes WHERE 1=1`;
5315
5341
  const params: any[] = [];
5316
5342
  sql = addAgentNetworkScope(sql, params, restScope, { alias: "alias", nodeId: "node_id" });
@@ -5353,6 +5379,47 @@ return Bun.serve({
5353
5379
  const blockedByInFlight = lifecycle === "active" && inFlight > 0;
5354
5380
  return { path, in_flight: inFlight, can_restart_now: path !== "manual" && !blockedByInFlight };
5355
5381
  };
5382
+ // #1510 —— 节点的 transport 记在 sessions 行上(report_status 每次上报刷新)。
5383
+ // 逐行查就是 N 次查询,所以先把 wanted 里所有 id / alias 一次取回、按 updated_at 倒序,
5384
+ // 每个节点只认最新那条(与 transportOf() 的取法一致:node_id 或 alias 命中)。
5385
+ const wantedIds = new Set<string>(wanted.map((r) => String(r.node_id)));
5386
+ const transportByKey = new Map<string, string | null>();
5387
+ const aliasTransport = new Map<string, string | null>();
5388
+ if (wanted.length) {
5389
+ // 🔴 编号参数不能复用:`?1..?n` 出现两次,而实参给了 2n 个 ——
5390
+ // SQLite 只认得 n 个绑定位置,多出来的直接抛错,整条 GET /api/nodes 变 500。
5391
+ // (#3214 首版就这么写的;CI 上三条互不相干的 workflow 同时红,
5392
+ // 共同点只有一个:它们都要先 `GET /api/nodes` 把 alias 解析成 node_id。)
5393
+ // 正确做法是第二组参数从 n+1 开始编号。
5394
+ const ids = wanted.map((r) => String(r.node_id));
5395
+ const phA = ids.map((_, i) => `?${i + 1}`).join(",");
5396
+ const phB = ids.map((_, i) => `?${ids.length + i + 1}`).join(",");
5397
+ for (const row of db.all<{ node_id: string | null; alias: string | null; network_id: string | null; env_transport: string | null }>(
5398
+ `SELECT node_id, alias, network_id, env_transport FROM sessions
5399
+ WHERE node_id IN (${phA}) OR alias IN (${phB})
5400
+ ORDER BY updated_at DESC`,
5401
+ ...ids, ...ids,
5402
+ )) {
5403
+ if (row.node_id && wantedIds.has(row.node_id) && !transportByKey.has(row.node_id)) transportByKey.set(row.node_id, row.env_transport);
5404
+ // alias 只在**同一网络**内兜底:不同网络可以有同名 alias,
5405
+ // 跨网络命中会把 A 网的 transport 显示成 B 网那台 —— 这一格是给人做安全决策用的,
5406
+ // 宁可显示 null(未知)也不能显示错的值。
5407
+ if (row.alias && row.network_id && wantedIds.has(row.alias)) {
5408
+ const key = `${row.network_id}|${row.alias}`;
5409
+ if (!aliasTransport.has(key)) aliasTransport.set(key, row.env_transport);
5410
+ }
5411
+ }
5412
+ }
5413
+ const envTransportOf = (nodeId: string, alias: string | null, networkId: string | null): string | null => {
5414
+ const direct = transportByKey.get(nodeId);
5415
+ if (direct !== undefined) return direct;
5416
+ if (!networkId) return null;
5417
+ // 兜底顺序与 transportOf() 一致:sessions 行的 alias 可能等于**节点 id**
5418
+ // (老注册路径就是这样),也可能等于**人给的 alias**。两种都要试,且都带网络。
5419
+ const byId = aliasTransport.get(`${networkId}|${nodeId}`);
5420
+ if (byId !== undefined) return byId;
5421
+ return alias ? aliasTransport.get(`${networkId}|${alias}`) ?? null : null;
5422
+ };
5356
5423
  // Add a single new field `role: string | null` per row, extracted from
5357
5424
  // config_snapshot JSON. Daemon nodes that posted role='host_supervisor'
5358
5425
  // via report_status surface here; dashboard uses this for daemon
@@ -5429,7 +5496,9 @@ return Bun.serve({
5429
5496
  if (typeof flags?.opencodeMode === "string" && flags.opencodeMode.length <= 32) opencodeMode = flags.opencodeMode;
5430
5497
  if (typeof parsed?.opencode_server === "string" && parsed.opencode_server.length <= 200) opencodeServer = parsed.opencode_server;
5431
5498
  }
5432
- const { config_snapshot, owner_user_id, ...rest } = r;
5499
+ // #2969 —— 两张白名单原来**只能写不能读**(PUT 有了,GET 里没有),
5500
+ // 客户端因此做不出「当前设置」这一屏。这里把原始列解构出来,下面换成解析后的数组。
5501
+ const { config_snapshot, owner_user_id, peer_allowlist, tool_allowlist, ...rest } = r;
5433
5502
  // `tags` is stored as JSON text; hand the dashboard a real array so
5434
5503
  // it can map() without a guard, and normalise legacy/absent values
5435
5504
  // to [] rather than null. attrs_revision is normalised to a number
@@ -5451,6 +5520,12 @@ return Bun.serve({
5451
5520
  lifecycle_daemon_node_id: controllable.get(r.node_id) ?? null,
5452
5521
  ...(management ? (management.get(r.node_id) ?? { managed: "none", adoption: null }) : {}),
5453
5522
  viewer_can: { permission_mode: canSetPermissionMode(r) },
5523
+ // #2969 —— 白名单读回来:null = 不限制;[] 不该出现(空数组在写入时已规范成 null)。
5524
+ peer_allowlist: normalizePeerAllowlist(peer_allowlist),
5525
+ tool_allowlist: normalizeToolAllowlist(tool_allowlist),
5526
+ // #1510 —— 管理员要能看出「谁的 transport 未知」才敢打开 strict。
5527
+ // 这一格**只读**,不参与任何判定(判定在 env-transport-policy.ts)。
5528
+ env_transport: envTransportOf(r.node_id, r.alias, r.network_id),
5454
5529
  restart_readiness: restartReadiness(r.node_id, r.alias, r.network_id, role, r.lifecycle_state ?? null),
5455
5530
  };
5456
5531
  });