@sleep2agi/commhub-server 0.9.0-preview.207 → 0.9.0-preview.209

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.207",
3
+ "version": "0.9.0-preview.209",
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",
@@ -552,3 +552,94 @@ describe("未绑定令牌的写调用:默认只记录,不拦", () => {
552
552
  expect(nodeDecide(id, "mcp:send_task", { reason: "unbound_token", sample: "send_task" })).toBe(true);
553
553
  });
554
554
  });
555
+
556
+ // #2969 续 —— REST 写接口白名单:唯一 choke point。
557
+ //
558
+ // 为什么必须在中央判一次:节点令牌的 REST 写面分散在两套判据里
559
+ // (server.ts 的 restNodeDenied + requirements.ts 的 nodeTaskGate)。
560
+ // 逐站点加会变成第三套规则,且漏掉任一处就是「装了一半的安全开关」——
561
+ // 那比没有更危险,因为它会被当成已经收紧了。
562
+ describe("#2969 REST 写白名单", () => {
563
+ test("路径归一化:11 条节点路由的标签逐字一致", async () => {
564
+ const { restRouteLabel } = await import("./node-permissions.js");
565
+ const cases: Array<[string, string, string]> = [
566
+ ["POST", "/api/task", "POST /api/task"],
567
+ ["POST", "/api/broadcast", "POST /api/broadcast"],
568
+ ["DELETE", "/api/nodes/n_abc123", "DELETE /api/nodes/:id"],
569
+ ["PUT", "/api/nodes/n_abc123/attrs", "PUT /api/nodes/:id/attrs"],
570
+ ["PUT", "/api/nodes/node_9f8e7d/avatar", "PUT /api/nodes/:id/avatar"],
571
+ ["PATCH", "/api/requirements/req_123", "PATCH /api/requirements/:id"],
572
+ ["PATCH", "/api/requirements/req_123/checklist/it_9", "PATCH /api/requirements/:id/checklist/:id"],
573
+ ["POST", "/api/requirements", "POST /api/requirements"],
574
+ ["POST", "/api/requirements/req_123/comments", "POST /api/requirements/:id/comments"],
575
+ ["PUT", "/api/nodes/tmwork_4ff6a3ee-f0b1-492c-abf6-132eea7b5e09/attrs", "PUT /api/nodes/:id/attrs"],
576
+ ];
577
+ for (const [m, p, want] of cases) expect(restRouteLabel(m, p)).toBe(want);
578
+ });
579
+
580
+ test("未设置清单 ⇒ 不判(不限制),行为与现在一致", async () => {
581
+ const { nodeIdentity, restAllowlistVerdict } = await import("./node-permissions.js");
582
+ const id = nodeIdentity(node.nN.tokenId, net)!;
583
+ expect(id.restAllowlist).toBeNull();
584
+ expect(restAllowlistVerdict(id, "POST /api/broadcast")).toBeNull();
585
+ });
586
+
587
+ test("设置了清单 ⇒ 清单外的写路由被拒,清单内的放行", async () => {
588
+ const { nodeIdentity, restAllowlistVerdict } = await import("./node-permissions.js");
589
+ db.run("UPDATE nodes SET rest_allowlist = ?1 WHERE node_id = ?2", [JSON.stringify(["POST /api/task"]), node.nN.id]);
590
+ const id = nodeIdentity(node.nN.tokenId, net)!;
591
+ expect(restAllowlistVerdict(id, "POST /api/task")).toBeNull();
592
+ expect(restAllowlistVerdict(id, "POST /api/broadcast")).toMatchObject({ reason: "rest_not_allowed" });
593
+ db.run("UPDATE nodes SET rest_allowlist = NULL WHERE node_id = ?1", [node.nN.id]);
594
+ });
595
+
596
+ test("HTTP:节点只有 POST /api/task 时,广播返回 403 rest_not_allowed", async () => {
597
+ db.run("UPDATE nodes SET rest_allowlist = ?1 WHERE node_id = ?2", [JSON.stringify(["POST /api/task"]), node.nN.id]);
598
+ const r = await call(node.nN.token, "POST", "/api/broadcast", { message: "should be blocked" });
599
+ expect(r.status).toBe(403);
600
+ expect(r.body.reason).toBe("rest_not_allowed");
601
+ db.run("UPDATE nodes SET rest_allowlist = NULL WHERE node_id = ?1", [node.nN.id]);
602
+ });
603
+
604
+ test("HTTP:用户令牌不受 REST 白名单影响(只对节点令牌生效)", async () => {
605
+ db.run("UPDATE nodes SET rest_allowlist = ?1 WHERE node_id = ?2", [JSON.stringify(["POST /api/task"]), node.nN.id]);
606
+ const r = await call(user.boss.token, "POST", `/api/requirements`, { name: `rest-allow-user-${stamp}`, network_id: net });
607
+ expect(r.status).toBe(201);
608
+ db.run("UPDATE nodes SET rest_allowlist = NULL WHERE node_id = ?1", [node.nN.id]);
609
+ });
610
+
611
+ test("GET 读回 rest_allowlist(null = 不限制)", async () => {
612
+ db.run("UPDATE nodes SET rest_allowlist = ?1 WHERE node_id = ?2", [JSON.stringify(["POST /api/task", "PATCH /api/requirements/:id"]), node.nN.id]);
613
+ const r = await call(user.boss.token, "GET", `/api/nodes?network_id=${net}&node_id=${node.nN.id}`);
614
+ expect(r.body.nodes[0].rest_allowlist).toEqual(["POST /api/task", "PATCH /api/requirements/:id"]);
615
+ db.run("UPDATE nodes SET rest_allowlist = NULL WHERE node_id = ?1", [node.nN.id]);
616
+ });
617
+ });
618
+
619
+ // #2970 判据④ —— 演练发现的口径问题:
620
+ // `node_permission_log` 的行数**不等于**「打开 enforce 行为会变」的次数。
621
+ // 演练现场:log 模式下 projects_create 已被处理函数拒(user_token_required),
622
+ // 但仍记了一行 human_only —— 计入影响面就会高估。
623
+ describe("#2970 enforce 影响面分层", () => {
624
+ test("原因码分三类:显式永久拒 / 多数已在下游被拦 / 只有 enforce 才改变行为", async () => {
625
+ const { enforceImpactOf } = await import("./node-permissions.js");
626
+ // 显式原因:与开关无关,永远拒 ⇒ 不是增量
627
+ for (const r of ["mode_readonly", "mode_restricted_not_assigned", "peer_not_allowed", "tool_not_allowed", "rest_not_allowed"]) {
628
+ expect(enforceImpactOf(r as any)).toBe("explicit");
629
+ }
630
+ // human_only:多数写路由自带「只有人能操作」检查,log 下调用方本来就被拒
631
+ expect(enforceImpactOf("human_only")).toBe("likely_already_blocked");
632
+ // 只有这三类 + unbound_token 是 enforce 的真增量
633
+ for (const r of ["beyond_owner_visibility", "agent_not_granted_to_owner", "owner_unknown", "unbound_token"]) {
634
+ expect(enforceImpactOf(r as any)).toBe("changes_behavior");
635
+ }
636
+ });
637
+
638
+ test("报表带 enforce_impact 分层汇总", async () => {
639
+ const r = await call(user.boss.token, "GET", `/api/networks/${net}/node-permission-report`);
640
+ expect(r.status).toBe(200);
641
+ expect(r.body.enforce_impact).toBeTruthy();
642
+ // 每个节点也带同名结构
643
+ for (const n of r.body.nodes) expect(n.enforce_impact).toBeTruthy();
644
+ });
645
+ });
@@ -34,15 +34,22 @@ export type NodePermissionReason =
34
34
  | "tool_not_allowed"
35
35
  /** #2969 续 —— 令牌解析不到节点行(常见成因:节点改过名、令牌名没跟着改)。
36
36
  * 这类令牌**没有 nodes 行**,两张白名单都管不到它;先按「记录」模式跑,看有多少。 */
37
- | "unbound_token";
37
+ | "unbound_token"
38
+ /** #2969 续 —— 主人在这个节点的 REST 白名单里没有列这条写路由。 */
39
+ | "rest_not_allowed";
38
40
 
39
41
  /** 显式模式的原因:不看开关,永远拒。 */
40
42
  // 白名单和 readonly/restricted 同类:**主人主动设的,设了就立刻生效**,不看开关。
41
- const MODE_REASONS: ReadonlySet<NodePermissionReason> = new Set(["mode_readonly", "mode_restricted_not_assigned", "peer_not_allowed", "tool_not_allowed"]);
43
+ const MODE_REASONS: ReadonlySet<NodePermissionReason> = new Set(["mode_readonly", "mode_restricted_not_assigned", "peer_not_allowed", "tool_not_allowed", "rest_not_allowed"]);
42
44
 
43
45
  // #2969 —— 节点级对端白名单:JSON 数组(alias 或 node_id);NULL = 不限制。
44
46
  // 只增不改:旧代码不读这一列;设为 NULL 时行为与现在完全一致。
45
47
  // #2969 后半 —— 接口白名单:JSON 数组(MCP 工具名);NULL = 不限制。
48
+ // #2969 续 —— REST 写接口白名单:JSON 数组(形如 "POST /api/task");NULL = 不限制。
49
+ // 只对**节点令牌的写方法**生效(GET / SSE 永不经过它,否则节点会变聋)。
50
+ try { db.exec("ALTER TABLE nodes ADD COLUMN rest_allowlist TEXT"); } catch (e: any) {
51
+ if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
52
+ }
46
53
  try { db.exec("ALTER TABLE nodes ADD COLUMN tool_allowlist TEXT"); } catch (e: any) {
47
54
  if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
48
55
  }
@@ -151,8 +158,38 @@ export type NodeIdentity = {
151
158
  peerAllowlist: string[] | null;
152
159
  /** #2969 后半 —— 接口白名单(MCP 工具名)。null = 不限制。 */
153
160
  toolAllowlist: string[] | null;
161
+ /** #2969 续 —— REST 写接口白名单(形如 "POST /api/task")。null = 不限制。 */
162
+ restAllowlist: string[] | null;
154
163
  };
155
164
 
165
+ /**
166
+ * #2969 续 —— 路径归一化成路由标签。
167
+ *
168
+ * 为什么要归一化:白名单里存的是 `POST /api/task` 这种**形状稳定的标签**,
169
+ * 而实际请求带的是具体 id(`PUT /api/nodes/n_abc123/attrs`)。不归一化,
170
+ * 白名单就只能写死某台节点的 id —— 换一台就失效。
171
+ *
172
+ * 判据只看段数,不看语义:**看起来像 id 的段换成 `:id`**。
173
+ * 「像 id」= 含下划线/连字符/数字,或纯数字,或 UUID 形状。
174
+ * 宁可多换(把 `checklist` 这种词留下来是因为它不含数字也不含分隔符)。
175
+ */
176
+ const ID_SEGMENT_RE = /^(?:[a-z]+_[A-Za-z0-9_-]+|[A-Za-z0-9]+-[A-Za-z0-9-]+|\d+|[0-9a-f]{8,})$/i;
177
+ export function restRouteLabel(method: string, pathname: string): string {
178
+ const segs = pathname.split("/").filter(Boolean).map(seg => (ID_SEGMENT_RE.test(seg) ? ":id" : seg));
179
+ return `${method.toUpperCase()} /${segs.join("/")}`;
180
+ }
181
+
182
+ /**
183
+ * #2969 续 —— REST 写白名单判定。
184
+ *
185
+ * 只在**设置了清单**时才判(NULL = 不限制,与 MCP 白名单同构);
186
+ * 两条 SSE 流永远不经过这里 —— 调用方只对写方法调用本函数。
187
+ */
188
+ export function restAllowlistVerdict(id: NodeIdentity, label: string): Verdict {
189
+ if (!id.restAllowlist) return null;
190
+ return id.restAllowlist.includes(label) ? null : { reason: "rest_not_allowed", sample: label };
191
+ }
192
+
156
193
  export function normalizePeerAllowlist(raw: unknown): string[] | null {
157
194
  if (typeof raw !== "string" || !raw.trim()) return null;
158
195
  try {
@@ -190,6 +227,7 @@ export function nodeIdentity(tokenId: string | null | undefined, networkId: stri
190
227
  mode: "normal",
191
228
  peerAllowlist: null,
192
229
  toolAllowlist: null,
230
+ restAllowlist: null,
193
231
  };
194
232
  }
195
233
  if (!resolved.ok || resolved.networkId !== networkId) {
@@ -202,6 +240,7 @@ export function nodeIdentity(tokenId: string | null | undefined, networkId: stri
202
240
  mode: "normal",
203
241
  peerAllowlist: null,
204
242
  toolAllowlist: null,
243
+ restAllowlist: null,
205
244
  };
206
245
  }
207
246
  if (resolved.kind === "unregistered") {
@@ -214,10 +253,11 @@ export function nodeIdentity(tokenId: string | null | undefined, networkId: stri
214
253
  mode: "normal",
215
254
  peerAllowlist: null,
216
255
  toolAllowlist: null,
256
+ restAllowlist: null,
217
257
  };
218
258
  }
219
- const node = db.get<{ owner_user_id: string | null; permission_mode: string | null; peer_allowlist: string | null; tool_allowlist: string | null }>(
220
- `SELECT owner_user_id, permission_mode, peer_allowlist, tool_allowlist FROM nodes WHERE node_id = ?1 AND network_id = ?2`,
259
+ const node = db.get<{ owner_user_id: string | null; permission_mode: string | null; peer_allowlist: string | null; tool_allowlist: string | null; rest_allowlist: string | null }>(
260
+ `SELECT owner_user_id, permission_mode, peer_allowlist, tool_allowlist, rest_allowlist FROM nodes WHERE node_id = ?1 AND network_id = ?2`,
221
261
  resolved.nodeId, networkId,
222
262
  );
223
263
  return {
@@ -229,6 +269,7 @@ export function nodeIdentity(tokenId: string | null | undefined, networkId: stri
229
269
  mode: normalizeMode(node?.permission_mode),
230
270
  peerAllowlist: normalizePeerAllowlist(node?.peer_allowlist),
231
271
  toolAllowlist: normalizeToolAllowlist(node?.tool_allowlist),
272
+ restAllowlist: normalizePeerAllowlist(node?.rest_allowlist),
232
273
  };
233
274
  }
234
275
 
@@ -260,6 +301,7 @@ const HINTS: Record<NodePermissionReason, string> = {
260
301
  peer_not_allowed: "this node is limited to an explicit peer allowlist; the target is not on it — ask the node's owner to add it, or clear the allowlist",
261
302
  tool_not_allowed: "this node is limited to an explicit tool allowlist; this tool is not on it — ask the node's owner to add it, or clear the allowlist",
262
303
  unbound_token: "this token does not resolve to a node (usually the node was renamed and the token was not); rename or bind the token, or issue a node-bound token",
304
+ rest_not_allowed: "this node is limited to an explicit REST write allowlist; this route is not on it — ask the node's owner to add it, or clear the allowlist",
263
305
  };
264
306
 
265
307
  export function nodePermissionDeniedBody(reason: NodePermissionReason, route: string): { ok: false; error: "node_permission_denied"; reason: NodePermissionReason; route: string; hint: string } {
@@ -422,3 +464,31 @@ export const NODE_TOOL_CLASS: Readonly<Record<string, ToolClass>> = {
422
464
  projects_create: "human_only", projects_update: "human_only", review_skill: "human_only",
423
465
  read_opencode_catalog: "human_only", get_opencode_catalog: "human_only",
424
466
  };
467
+
468
+ /**
469
+ * #2970 判据④ 演练发现的口径问题 —— `node_permission_log` 的行数**不等于**
470
+ * 「打开 enforce 后行为会改变多少次」。
471
+ *
472
+ * 演练现场(`.208`,独立实例):
473
+ *
474
+ * log 模式 projects_create → user_token_required (调用方**也是被拒的**)
475
+ * node_permission_log += 1(reason=human_only)
476
+ * enforce projects_create → node_permission_denied / human_only
477
+ *
478
+ * 也就是说:`projects_create` 在 log 模式下就已经被处理函数自己的「只有人能做的操作」
479
+ * 检查挡住了。**这一条计入 would-be denial,但它并不是 enforce 的增量。**
480
+ *
481
+ * 所以把原因码分三类,报表按类求和 —— 否则切 enforce 时拿到的是一份高估的影响面:
482
+ *
483
+ * explicit 显式原因(MODE_REASONS):**永远拒**,与开关无关 ⇒ 不计入影响面
484
+ * likely_already_blocked human_only:多数写路由另有一道「只有人能操作」的检查,
485
+ * log 模式下调用方本来就被拒 ⇒ 通常不是增量(逐路由不同,标而不减)
486
+ * changes_behavior 只有 enforce 才会拒的理由 ⇒ **这才是真切会变的**
487
+ */
488
+ export type EnforceImpact = "explicit" | "likely_already_blocked" | "changes_behavior";
489
+
490
+ export function enforceImpactOf(reason: NodePermissionReason): EnforceImpact {
491
+ if (MODE_REASONS.has(reason)) return "explicit";
492
+ if (reason === "human_only") return "likely_already_blocked";
493
+ return "changes_behavior";
494
+ }
@@ -1962,7 +1962,7 @@ async function handleRequirementsRequestInner(ctx: RequirementsRequestContext):
1962
1962
  const row = scopedRow(ctx, decodeURIComponent(itemMatch[1]));
1963
1963
  if (row instanceof Response) return row;
1964
1964
  if (!canWrite(ctx, row.network_id)) return jsonError("permission_denied", 403);
1965
- const nodeDenied = nodeTaskGate(ctx, "PATCH /api/requirements/:id/checklist/:item", row);
1965
+ const nodeDenied = nodeTaskGate(ctx, "PATCH /api/requirements/:id/checklist/:id", row);
1966
1966
  if (nodeDenied) return nodeDenied;
1967
1967
  if (!canEditTask(taskCaller(ctx), row) && !canParticipantEditTask(taskCaller(ctx), row)) return taskDenied(ctx, row, "task_read_only");
1968
1968
  // 读-改-写在同一个同步段里完成(中间没有 await),同一进程里的两次勾选不会交错。
package/src/server.ts CHANGED
@@ -107,7 +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
+ import { enforceImpactOf, normalizePeerAllowlist, normalizeToolAllowlist, restAllowlistVerdict, restRouteLabel } from "./node-permissions.js";
111
111
  import { labelRoute, mcpRouteLabel, recordRouteTiming, routeStats, setRouteCallerMasterToken, setRouteCallerTokenReader } from "./route-timing.js";
112
112
  import { handleExternalScheduleEditRequest } from "./external-schedule-edits.js";
113
113
  import { createNodeSessionControlRelay } from "./node-session-control.js";
@@ -406,6 +406,9 @@ function countNetworkUploads(networkId: string): number {
406
406
  }
407
407
 
408
408
  // RFC-041(#487):节点令牌的一次 REST 写 / 订阅先按 node-permissions.ts 判。用户令牌 → null(不判)。
409
+ /** #2969 续 —— 会被 REST 写白名单检查的方法。GET / HEAD / OPTIONS 永远不在此列。 */
410
+ const WRITE_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
411
+
409
412
  function restNodeDenied(req: Request, restAuth: { networkId: string | null; tokenId: string | null } | null, route: string, verdictOf: (id: NodeIdentity) => Verdict): Response | null {
410
413
  if (!restAuth?.networkId) return null;
411
414
  const id = nodeIdentity(restAuth.tokenId, restAuth.networkId);
@@ -2841,6 +2844,28 @@ return Bun.serve({
2841
2844
  return withCors(req, Response.json({ ok: false, error: restScope.denied }, { status: 403 }));
2842
2845
  }
2843
2846
 
2847
+ // #2969 续 —— REST 写接口白名单:唯一 choke point。
2848
+ //
2849
+ // 为什么在这里而不是逐条路由:节点令牌的 REST 写面分散在两套判据里
2850
+ // (server.ts 的 restNodeDenied + requirements.ts 的 nodeTaskGate)。
2851
+ // 逐站点加会变成第三套规则,且漏掉任一处就是「装了一半的安全开关」——
2852
+ // 那比没有更危险,因为它会被当成已经收紧了。
2853
+ //
2854
+ // 三条边界:
2855
+ // · 只对**节点令牌**生效(用户令牌 / daemon 令牌不受影响)
2856
+ // · 只对**写方法**生效:GET 与 SSE 永不经过这里 —— 挡掉 SSE 节点会变聋
2857
+ // · 只在**设置了清单**时生效:NULL = 不限制,与 MCP 工具白名单同构
2858
+ if (restAuth?.networkId && WRITE_METHODS.has(req.method)) {
2859
+ const restNode = nodeIdentity(restAuth.tokenId, restAuth.networkId);
2860
+ if (restNode?.restAllowlist) {
2861
+ const label = restRouteLabel(req.method, url.pathname);
2862
+ const verdict = restAllowlistVerdict(restNode, label);
2863
+ if (verdict && nodeDecide(restNode, label, verdict)) {
2864
+ return withCors(req, Response.json(nodePermissionDeniedBody(verdict.reason, label), { status: 403 }));
2865
+ }
2866
+ }
2867
+ }
2868
+
2844
2869
  // #629: only actual user credentials gain lifecycle read metadata. Legacy
2845
2870
  // master/dev-open and network/daemon credentials keep their old surface.
2846
2871
  const lifecycleAuth = resolveRequestAuth(req, { allowQueryToken: false });
@@ -2986,6 +3011,41 @@ return Bun.serve({
2986
3011
  logAudit(restAuth.userId, restAuth.username, "node_tool_allowlist_changed", "node", node3.node_id, JSON.stringify({ from: node3.tool_allowlist, to: nextTools }), getClientIP(req), node3.network_id);
2987
3012
  return withCors(req, Response.json({ ok: true, node_id: node3.node_id, tools: tools.length ? tools : null }));
2988
3013
  }
3014
+ // #2969 续 —— REST 写接口白名单:PUT /api/nodes/:id/rest-allowlist { routes: string[] | null }
3015
+ // 与 tool-allowlist 同一套授权口径与空数组语义(拒收 [],清空请传 null)。
3016
+ const restAllowMatch = url.pathname.match(/^\/api\/nodes\/([^/]+)\/rest-allowlist$/);
3017
+ if (restAllowMatch && req.method === "PUT") {
3018
+ if (!restAuth) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
3019
+ if (restAuth.networkId) return userTokenRequired(req);
3020
+ let body: any;
3021
+ try { body = await req.json(); } catch { return withCors(req, Response.json({ ok: false, error: "invalid_json" }, { status: 400 })); }
3022
+ const rawRoutes = body?.routes;
3023
+ if (rawRoutes !== null && rawRoutes !== undefined && !Array.isArray(rawRoutes)) {
3024
+ return withCors(req, Response.json({ ok: false, error: "invalid_routes", message: "routes must be an array of route labels like \"POST /api/task\", or null" }, { status: 400 }));
3025
+ }
3026
+ const routes = Array.isArray(rawRoutes)
3027
+ ? rawRoutes.filter((x: unknown): x is string => typeof x === "string" && x.trim().length > 0).map((x: string) => x.trim())
3028
+ : [];
3029
+ if (Array.isArray(rawRoutes) && routes.length === 0) {
3030
+ return withCors(req, Response.json({ ok: false, error: "empty_allowlist_ambiguous", message: "send null to clear the allowlist (no restriction); an empty array is ambiguous and is rejected" }, { status: 400 }));
3031
+ }
3032
+ if (routes.length > 200) {
3033
+ return withCors(req, Response.json({ ok: false, error: "too_many_routes", message: "at most 200 entries" }, { status: 400 }));
3034
+ }
3035
+ const nodeRef4 = decodeURIComponent(restAllowMatch[1]);
3036
+ const node4 = db.get<{ node_id: string; network_id: string | null; owner_user_id: string | null; rest_allowlist: string | null }>(
3037
+ "SELECT node_id, network_id, owner_user_id, rest_allowlist FROM nodes WHERE node_id = ?1", nodeRef4);
3038
+ const role4 = node4?.network_id ? getUserNetworkRole(restAuth.userId, node4.network_id) : null;
3039
+ if (!node4 || !node4.network_id || (!role4 && !isAdmin)) return withCors(req, Response.json({ ok: false, error: "node_not_found" }, { status: 404 }));
3040
+ if (!isAdmin && node4.owner_user_id !== restAuth.userId && role4 !== "owner" && role4 !== "admin") {
3041
+ return withCors(req, Response.json({ ok: false, error: "permission_denied", message: "only the node's owner or a network owner/admin can change its REST allowlist" }, { status: 403 }));
3042
+ }
3043
+ const nextRoutes = routes.length ? JSON.stringify(routes) : null;
3044
+ db.run("UPDATE nodes SET rest_allowlist = ?1 WHERE node_id = ?2", [nextRoutes, node4.node_id]);
3045
+ logAudit(restAuth.userId, restAuth.username, "node_rest_allowlist_changed", "node", node4.node_id, JSON.stringify({ from: node4.rest_allowlist, to: nextRoutes }), getClientIP(req), node4.network_id);
3046
+ return withCors(req, Response.json({ ok: true, node_id: node4.node_id, routes: routes.length ? routes : null }));
3047
+ }
3048
+
2989
3049
  // #2969 —— 节点级对端白名单:PUT /api/nodes/:id/peer-allowlist { peers: string[] | null }
2990
3050
  // 与 permission-mode 同一套授权口径(用户令牌 + 节点主人 / 网络 owner·admin / Hub 管理员)。
2991
3051
  // peers 为 null 或空数组 ⇒ 清空(不限制),与「没有这一列」等价。
@@ -3044,17 +3104,21 @@ return Bun.serve({
3044
3104
  FROM node_permission_log WHERE network_id = ?1 AND hour >= ?2
3045
3105
  GROUP BY node_id, route, reason ORDER BY node_id, route, reason`,
3046
3106
  networkId, sinceHour);
3047
- const byNode = new Map<string, { node_id: string; alias: string | null; permission_mode: string; total: number; by_reason: Record<string, number>; routes: Array<{ route: string; reason: string; hits: number; sample: string | null; last_hour: string }>; tool_calls?: Array<{ tool: string; hits: number }>; tool_calls_total?: number; unbound_token?: boolean; unbound_token_name?: string | null }>();
3107
+ const byNode = new Map<string, { node_id: string; alias: string | null; permission_mode: string; total: number; by_reason: Record<string, number>; routes: Array<{ route: string; reason: string; hits: number; sample: string | null; last_hour: string }>; tool_calls?: Array<{ tool: string; hits: number }>; tool_calls_total?: number; unbound_token?: boolean; unbound_token_name?: string | null; enforce_impact: Record<string, number> }>();
3048
3108
  for (const r of rows) {
3049
3109
  let entry = byNode.get(r.node_id);
3050
3110
  if (!entry) {
3051
3111
  const n = db.get<{ alias: string | null; permission_mode: string | null }>("SELECT alias, permission_mode FROM nodes WHERE node_id = ?1", r.node_id);
3052
- entry = { node_id: r.node_id, alias: n?.alias ?? null, permission_mode: n?.permission_mode || "normal", total: 0, by_reason: {}, routes: [] };
3112
+ entry = { node_id: r.node_id, alias: n?.alias ?? null, permission_mode: n?.permission_mode || "normal", total: 0, by_reason: {}, routes: [], enforce_impact: {} };
3053
3113
  byNode.set(r.node_id, entry);
3054
3114
  }
3055
3115
  const hits = Number(r.hits);
3056
3116
  entry.total += hits;
3057
3117
  entry.by_reason[r.reason] = (entry.by_reason[r.reason] ?? 0) + hits;
3118
+ // #2970 判据④ 演练发现:这些行数**不等于**「打开 enforce 行为会变」的次数。
3119
+ // 按 enforceImpactOf 分三类,让管理员看得出哪些是真增量、哪些本来就被拦着。
3120
+ const impact = enforceImpactOf(r.reason as any);
3121
+ entry.enforce_impact[impact] = (entry.enforce_impact[impact] ?? 0) + hits;
3058
3122
  entry.routes.push({ route: r.route, reason: r.reason, hits, sample: r.sample, last_hour: r.last_hour });
3059
3123
  }
3060
3124
  // #2969 —— 按节点的工具调用明细。
@@ -3080,7 +3144,7 @@ return Bun.serve({
3080
3144
  for (const nodeId of callsByNode.keys()) {
3081
3145
  if (byNode.has(nodeId)) continue;
3082
3146
  const n = db.get<{ alias: string | null; permission_mode: string | null }>("SELECT alias, permission_mode FROM nodes WHERE node_id = ?1", nodeId);
3083
- byNode.set(nodeId, { node_id: nodeId, alias: n?.alias ?? null, permission_mode: n?.permission_mode || "normal", total: 0, by_reason: {}, routes: [] });
3147
+ byNode.set(nodeId, { node_id: nodeId, alias: n?.alias ?? null, permission_mode: n?.permission_mode || "normal", total: 0, by_reason: {}, routes: [], enforce_impact: {} });
3084
3148
  }
3085
3149
  for (const entry of byNode.values()) {
3086
3150
  const list = callsByNode.get(entry.node_id) ?? [];
@@ -3113,10 +3177,17 @@ return Bun.serve({
3113
3177
  );
3114
3178
  const toolCalls = callRows.map((r) => ({ tool: r.tool, hits: Number(r.hits) }));
3115
3179
  const deniedTotal = nodes.reduce((n, e) => n + e.total, 0);
3180
+ // 顶层汇总:切 enforce 的真实影响面是多少(explicit / likely_already_blocked 都不算)
3181
+ const enforceImpact: Record<string, number> = {};
3182
+ for (const e of nodes) {
3183
+ for (const [k, v] of Object.entries(e.enforce_impact)) enforceImpact[k] = (enforceImpact[k] ?? 0) + v;
3184
+ }
3116
3185
  const callsTotal = toolCalls.reduce((n, e) => n + e.hits, 0);
3117
3186
  return withCors(req, Response.json({
3118
3187
  ok: true, network_id: networkId, since: new Date(sinceMs).toISOString(), mode: nodePermissionsFlag(),
3119
3188
  total: deniedTotal,
3189
+ // changes_behavior 才是「打开 enforce 会改变行为」的次数;另外两类都不是增量。
3190
+ enforce_impact: enforceImpact,
3120
3191
  nodes,
3121
3192
  tool_calls: { total: callsTotal, by_tool: toolCalls },
3122
3193
  }));
@@ -5380,7 +5451,7 @@ return Bun.serve({
5380
5451
  network_id, created_at, updated_at,
5381
5452
  config_snapshot, lifecycle_state, avatar_url,
5382
5453
  display_name, team, tags, attrs_revision, permission_mode, owner_user_id,
5383
- department_id, peer_allowlist, tool_allowlist
5454
+ department_id, peer_allowlist, tool_allowlist, rest_allowlist
5384
5455
  FROM nodes WHERE 1=1`;
5385
5456
  const params: any[] = [];
5386
5457
  sql = addAgentNetworkScope(sql, params, restScope, { alias: "alias", nodeId: "node_id" });
@@ -5542,7 +5613,7 @@ return Bun.serve({
5542
5613
  }
5543
5614
  // #2969 —— 两张白名单原来**只能写不能读**(PUT 有了,GET 里没有),
5544
5615
  // 客户端因此做不出「当前设置」这一屏。这里把原始列解构出来,下面换成解析后的数组。
5545
- const { config_snapshot, owner_user_id, peer_allowlist, tool_allowlist, ...rest } = r;
5616
+ const { config_snapshot, owner_user_id, peer_allowlist, tool_allowlist, rest_allowlist, ...rest } = r;
5546
5617
  // `tags` is stored as JSON text; hand the dashboard a real array so
5547
5618
  // it can map() without a guard, and normalise legacy/absent values
5548
5619
  // to [] rather than null. attrs_revision is normalised to a number
@@ -5567,6 +5638,8 @@ return Bun.serve({
5567
5638
  // #2969 —— 白名单读回来:null = 不限制;[] 不该出现(空数组在写入时已规范成 null)。
5568
5639
  peer_allowlist: normalizePeerAllowlist(peer_allowlist),
5569
5640
  tool_allowlist: normalizeToolAllowlist(tool_allowlist),
5641
+ // #2969 续 —— REST 写接口白名单(形如 "POST /api/task")。null = 不限制。
5642
+ rest_allowlist: normalizePeerAllowlist(rest_allowlist),
5570
5643
  // #1510 —— 管理员要能看出「谁的 transport 未知」才敢打开 strict。
5571
5644
  // 这一格**只读**,不参与任何判定(判定在 env-transport-policy.ts)。
5572
5645
  env_transport: envTransportOf(r.node_id, r.alias, r.network_id),