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

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.208",
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,66 @@ 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
+ });
@@ -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 } {
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 { 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 或空数组 ⇒ 清空(不限制),与「没有这一列」等价。
@@ -5380,7 +5440,7 @@ return Bun.serve({
5380
5440
  network_id, created_at, updated_at,
5381
5441
  config_snapshot, lifecycle_state, avatar_url,
5382
5442
  display_name, team, tags, attrs_revision, permission_mode, owner_user_id,
5383
- department_id, peer_allowlist, tool_allowlist
5443
+ department_id, peer_allowlist, tool_allowlist, rest_allowlist
5384
5444
  FROM nodes WHERE 1=1`;
5385
5445
  const params: any[] = [];
5386
5446
  sql = addAgentNetworkScope(sql, params, restScope, { alias: "alias", nodeId: "node_id" });
@@ -5542,7 +5602,7 @@ return Bun.serve({
5542
5602
  }
5543
5603
  // #2969 —— 两张白名单原来**只能写不能读**(PUT 有了,GET 里没有),
5544
5604
  // 客户端因此做不出「当前设置」这一屏。这里把原始列解构出来,下面换成解析后的数组。
5545
- const { config_snapshot, owner_user_id, peer_allowlist, tool_allowlist, ...rest } = r;
5605
+ const { config_snapshot, owner_user_id, peer_allowlist, tool_allowlist, rest_allowlist, ...rest } = r;
5546
5606
  // `tags` is stored as JSON text; hand the dashboard a real array so
5547
5607
  // it can map() without a guard, and normalise legacy/absent values
5548
5608
  // to [] rather than null. attrs_revision is normalised to a number
@@ -5567,6 +5627,8 @@ return Bun.serve({
5567
5627
  // #2969 —— 白名单读回来:null = 不限制;[] 不该出现(空数组在写入时已规范成 null)。
5568
5628
  peer_allowlist: normalizePeerAllowlist(peer_allowlist),
5569
5629
  tool_allowlist: normalizeToolAllowlist(tool_allowlist),
5630
+ // #2969 续 —— REST 写接口白名单(形如 "POST /api/task")。null = 不限制。
5631
+ rest_allowlist: normalizePeerAllowlist(rest_allowlist),
5570
5632
  // #1510 —— 管理员要能看出「谁的 transport 未知」才敢打开 strict。
5571
5633
  // 这一格**只读**,不参与任何判定(判定在 env-transport-policy.ts)。
5572
5634
  env_transport: envTransportOf(r.node_id, r.alias, r.network_id),