@sleep2agi/commhub-server 0.9.0-preview.206 → 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 +1 -1
- package/src/node-permissions-http.test.ts +111 -0
- package/src/node-permissions.ts +50 -4
- package/src/server.ts +75 -5
- package/src/tools.ts +5 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sleep2agi/commhub-server",
|
|
3
|
-
"version": "0.9.0-preview.
|
|
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",
|
|
@@ -502,5 +502,116 @@ describe("未绑定节点的令牌在报表里必须可见", () => {
|
|
|
502
502
|
expect(unbound.tool_calls_total).toBeGreaterThanOrEqual(4);
|
|
503
503
|
const real = r.body.nodes.find((n: any) => n.node_id === node.nN.id);
|
|
504
504
|
expect(real.unbound_token).toBeUndefined();
|
|
505
|
+
// 令牌名要带出来 —— 只看 `token:tok_xxx` 无法处理;名字才是「该改哪个令牌」的答案。
|
|
506
|
+
const tokRow = db.get<{ token_id: string }>("SELECT token_id FROM api_tokens LIMIT 1");
|
|
507
|
+
db.run(`INSERT INTO node_tool_calls (network_id, node_id, tool, hour, hits) VALUES (?1, ?2, 'mcp:send_task', ?3, 1)
|
|
508
|
+
ON CONFLICT(network_id, node_id, tool, hour) DO UPDATE SET hits = node_tool_calls.hits + 1`,
|
|
509
|
+
[net, `token:${tokRow.token_id}`, new Date().toISOString().slice(0, 13)]);
|
|
510
|
+
const r2 = await call(user.boss.token, "GET", `/api/networks/${net}/node-permission-report`);
|
|
511
|
+
const withName = r2.body.nodes.find((n: any) => n.node_id === `token:${tokRow.token_id}`);
|
|
512
|
+
expect(withName.unbound_token_name).toBeTruthy();
|
|
513
|
+
});
|
|
514
|
+
});
|
|
515
|
+
|
|
516
|
+
// #2969 续 —— 令牌解析不到节点行时,两张白名单都管不到它。
|
|
517
|
+
// 先按「记录」跑:`unbound_token` 不在 MODE_REASONS 里 ⇒ 默认 log 模式只记账、不改变行为。
|
|
518
|
+
// 这样「要不要强制要求绑定令牌」这个决定,将来自有数据可依据(而不是靠猜会不会炸)。
|
|
519
|
+
describe("未绑定令牌的写调用:默认只记录,不拦", () => {
|
|
520
|
+
// 造一个**解析不到节点**的令牌:名字里的 alias 在本网络没有对应 nodes 行。
|
|
521
|
+
// 这就是线上那 4 个令牌的真实形状(节点改名、令牌名没跟着改)。
|
|
522
|
+
const unboundKey = () => {
|
|
523
|
+
const alias = `ghost-alias-${stamp}`;
|
|
524
|
+
const tokenId = `tok_ghost_${stamp}`;
|
|
525
|
+
db.run("INSERT OR IGNORE INTO api_tokens (token_id, token_hash, user_id, network_id, name, scope) VALUES (?1, ?2, ?3, ?4, ?5, 'network')",
|
|
526
|
+
[tokenId, `hash_${tokenId}`, user.boss.id, net, `node:${alias}`]);
|
|
527
|
+
return tokenId;
|
|
528
|
+
};
|
|
529
|
+
|
|
530
|
+
test("log 模式:写调用照常成功,但进 node_permission_log(reason=unbound_token)", async () => {
|
|
531
|
+
const tokenId = unboundKey();
|
|
532
|
+
const key = `token:${tokenId}`;
|
|
533
|
+
const before = Number(db.get<{ h: number | string | null }>(
|
|
534
|
+
"SELECT SUM(hits) AS h FROM node_permission_log WHERE network_id = ?1 AND node_id = ?2 AND reason = 'unbound_token'",
|
|
535
|
+
net, key)?.h ?? 0);
|
|
536
|
+
// 用一个「解析不到节点」的身份直接走判定,绕开 HTTP 令牌构造(这里验的是判据与记账)
|
|
537
|
+
const { nodeIdentity, nodeDecide } = await import("./node-permissions.js");
|
|
538
|
+
const id = nodeIdentity(tokenId, net)!;
|
|
539
|
+
expect(id.nodeId).toBeNull();
|
|
540
|
+
const allowed = nodeDecide(id, "mcp:send_task", { reason: "unbound_token", sample: "send_task" });
|
|
541
|
+
expect(allowed).toBe(false); // log 模式:不拦
|
|
542
|
+
const after = Number(db.get<{ h: number | string | null }>(
|
|
543
|
+
"SELECT SUM(hits) AS h FROM node_permission_log WHERE network_id = ?1 AND node_id = ?2 AND reason = 'unbound_token'",
|
|
544
|
+
net, key)?.h ?? 0);
|
|
545
|
+
expect(after).toBe(before + 1); // 但记了一笔
|
|
546
|
+
});
|
|
547
|
+
|
|
548
|
+
test("enforce 模式:同一个调用被拒,原因是 unbound_token", async () => {
|
|
549
|
+
process.env.COMMHUB_NODE_PERMISSIONS = "enforce";
|
|
550
|
+
const { nodeIdentity, nodeDecide } = await import("./node-permissions.js");
|
|
551
|
+
const id = nodeIdentity(unboundKey(), net)!;
|
|
552
|
+
expect(nodeDecide(id, "mcp:send_task", { reason: "unbound_token", sample: "send_task" })).toBe(true);
|
|
553
|
+
});
|
|
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]);
|
|
505
616
|
});
|
|
506
617
|
});
|
package/src/node-permissions.ts
CHANGED
|
@@ -31,15 +31,25 @@ export type NodePermissionReason =
|
|
|
31
31
|
/** #2969 —— 主人给这个节点设了对端白名单,目标不在名单里。 */
|
|
32
32
|
| "peer_not_allowed"
|
|
33
33
|
/** #2969 后半 —— 主人在这个节点的接口白名单里没有列这个工具/路由。 */
|
|
34
|
-
| "tool_not_allowed"
|
|
34
|
+
| "tool_not_allowed"
|
|
35
|
+
/** #2969 续 —— 令牌解析不到节点行(常见成因:节点改过名、令牌名没跟着改)。
|
|
36
|
+
* 这类令牌**没有 nodes 行**,两张白名单都管不到它;先按「记录」模式跑,看有多少。 */
|
|
37
|
+
| "unbound_token"
|
|
38
|
+
/** #2969 续 —— 主人在这个节点的 REST 白名单里没有列这条写路由。 */
|
|
39
|
+
| "rest_not_allowed";
|
|
35
40
|
|
|
36
41
|
/** 显式模式的原因:不看开关,永远拒。 */
|
|
37
42
|
// 白名单和 readonly/restricted 同类:**主人主动设的,设了就立刻生效**,不看开关。
|
|
38
|
-
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"]);
|
|
39
44
|
|
|
40
45
|
// #2969 —— 节点级对端白名单:JSON 数组(alias 或 node_id);NULL = 不限制。
|
|
41
46
|
// 只增不改:旧代码不读这一列;设为 NULL 时行为与现在完全一致。
|
|
42
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
|
+
}
|
|
43
53
|
try { db.exec("ALTER TABLE nodes ADD COLUMN tool_allowlist TEXT"); } catch (e: any) {
|
|
44
54
|
if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
|
|
45
55
|
}
|
|
@@ -148,8 +158,38 @@ export type NodeIdentity = {
|
|
|
148
158
|
peerAllowlist: string[] | null;
|
|
149
159
|
/** #2969 后半 —— 接口白名单(MCP 工具名)。null = 不限制。 */
|
|
150
160
|
toolAllowlist: string[] | null;
|
|
161
|
+
/** #2969 续 —— REST 写接口白名单(形如 "POST /api/task")。null = 不限制。 */
|
|
162
|
+
restAllowlist: string[] | null;
|
|
151
163
|
};
|
|
152
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
|
+
|
|
153
193
|
export function normalizePeerAllowlist(raw: unknown): string[] | null {
|
|
154
194
|
if (typeof raw !== "string" || !raw.trim()) return null;
|
|
155
195
|
try {
|
|
@@ -187,6 +227,7 @@ export function nodeIdentity(tokenId: string | null | undefined, networkId: stri
|
|
|
187
227
|
mode: "normal",
|
|
188
228
|
peerAllowlist: null,
|
|
189
229
|
toolAllowlist: null,
|
|
230
|
+
restAllowlist: null,
|
|
190
231
|
};
|
|
191
232
|
}
|
|
192
233
|
if (!resolved.ok || resolved.networkId !== networkId) {
|
|
@@ -199,6 +240,7 @@ export function nodeIdentity(tokenId: string | null | undefined, networkId: stri
|
|
|
199
240
|
mode: "normal",
|
|
200
241
|
peerAllowlist: null,
|
|
201
242
|
toolAllowlist: null,
|
|
243
|
+
restAllowlist: null,
|
|
202
244
|
};
|
|
203
245
|
}
|
|
204
246
|
if (resolved.kind === "unregistered") {
|
|
@@ -211,10 +253,11 @@ export function nodeIdentity(tokenId: string | null | undefined, networkId: stri
|
|
|
211
253
|
mode: "normal",
|
|
212
254
|
peerAllowlist: null,
|
|
213
255
|
toolAllowlist: null,
|
|
256
|
+
restAllowlist: null,
|
|
214
257
|
};
|
|
215
258
|
}
|
|
216
|
-
const node = db.get<{ owner_user_id: string | null; permission_mode: string | null; peer_allowlist: string | null; tool_allowlist: string | null }>(
|
|
217
|
-
`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`,
|
|
218
261
|
resolved.nodeId, networkId,
|
|
219
262
|
);
|
|
220
263
|
return {
|
|
@@ -226,6 +269,7 @@ export function nodeIdentity(tokenId: string | null | undefined, networkId: stri
|
|
|
226
269
|
mode: normalizeMode(node?.permission_mode),
|
|
227
270
|
peerAllowlist: normalizePeerAllowlist(node?.peer_allowlist),
|
|
228
271
|
toolAllowlist: normalizeToolAllowlist(node?.tool_allowlist),
|
|
272
|
+
restAllowlist: normalizePeerAllowlist(node?.rest_allowlist),
|
|
229
273
|
};
|
|
230
274
|
}
|
|
231
275
|
|
|
@@ -256,6 +300,8 @@ const HINTS: Record<NodePermissionReason, string> = {
|
|
|
256
300
|
owner_unknown: "this node's owner is unknown; recreate the node token from the owner's account",
|
|
257
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",
|
|
258
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",
|
|
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",
|
|
259
305
|
};
|
|
260
306
|
|
|
261
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 或空数组 ⇒ 清空(不限制),与「没有这一列」等价。
|
|
@@ -3044,7 +3104,7 @@ 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 }>();
|
|
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 }>();
|
|
3048
3108
|
for (const r of rows) {
|
|
3049
3109
|
let entry = byNode.get(r.node_id);
|
|
3050
3110
|
if (!entry) {
|
|
@@ -3090,7 +3150,15 @@ return Bun.serve({
|
|
|
3090
3150
|
// 它们**没有 nodes 行**,所以两张白名单都管不到它们(toolAllowlist 为 null ⇒ 不限制)。
|
|
3091
3151
|
// 报表里必须显式标出来,否则管理员会以为「名单之外没有别人在派活」。
|
|
3092
3152
|
// 这里只标注,不改变任何判定。
|
|
3093
|
-
if (entry.node_id.startsWith("token:"))
|
|
3153
|
+
if (entry.node_id.startsWith("token:")) {
|
|
3154
|
+
entry.unbound_token = true;
|
|
3155
|
+
// 令牌名往往就是答案:账本里是 `token:tok_xxx`,光看这个没法处理。
|
|
3156
|
+
// 线上实测这 4 个令牌的名字是 `node:ANet基建` / `node:TMWork` …,而 nodes 表里
|
|
3157
|
+
// 已经没有这些 alias 了 —— 节点改过名、令牌没跟着改,于是解析成「未注册」,
|
|
3158
|
+
// 白名单静默不生效。把名字带出来,管理员才知道该改哪个令牌。
|
|
3159
|
+
const tok = db.get<{ name: string | null }>("SELECT name FROM api_tokens WHERE token_id = ?1", entry.node_id.slice(6));
|
|
3160
|
+
entry.unbound_token_name = tok?.name ?? null;
|
|
3161
|
+
}
|
|
3094
3162
|
}
|
|
3095
3163
|
const nodes = [...byNode.values()].sort((a, b) =>
|
|
3096
3164
|
b.tool_calls_total - a.tool_calls_total || b.total - a.total || a.node_id.localeCompare(b.node_id));
|
|
@@ -5372,7 +5440,7 @@ return Bun.serve({
|
|
|
5372
5440
|
network_id, created_at, updated_at,
|
|
5373
5441
|
config_snapshot, lifecycle_state, avatar_url,
|
|
5374
5442
|
display_name, team, tags, attrs_revision, permission_mode, owner_user_id,
|
|
5375
|
-
department_id, peer_allowlist, tool_allowlist
|
|
5443
|
+
department_id, peer_allowlist, tool_allowlist, rest_allowlist
|
|
5376
5444
|
FROM nodes WHERE 1=1`;
|
|
5377
5445
|
const params: any[] = [];
|
|
5378
5446
|
sql = addAgentNetworkScope(sql, params, restScope, { alias: "alias", nodeId: "node_id" });
|
|
@@ -5534,7 +5602,7 @@ return Bun.serve({
|
|
|
5534
5602
|
}
|
|
5535
5603
|
// #2969 —— 两张白名单原来**只能写不能读**(PUT 有了,GET 里没有),
|
|
5536
5604
|
// 客户端因此做不出「当前设置」这一屏。这里把原始列解构出来,下面换成解析后的数组。
|
|
5537
|
-
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;
|
|
5538
5606
|
// `tags` is stored as JSON text; hand the dashboard a real array so
|
|
5539
5607
|
// it can map() without a guard, and normalise legacy/absent values
|
|
5540
5608
|
// to [] rather than null. attrs_revision is normalised to a number
|
|
@@ -5559,6 +5627,8 @@ return Bun.serve({
|
|
|
5559
5627
|
// #2969 —— 白名单读回来:null = 不限制;[] 不该出现(空数组在写入时已规范成 null)。
|
|
5560
5628
|
peer_allowlist: normalizePeerAllowlist(peer_allowlist),
|
|
5561
5629
|
tool_allowlist: normalizeToolAllowlist(tool_allowlist),
|
|
5630
|
+
// #2969 续 —— REST 写接口白名单(形如 "POST /api/task")。null = 不限制。
|
|
5631
|
+
rest_allowlist: normalizePeerAllowlist(rest_allowlist),
|
|
5562
5632
|
// #1510 —— 管理员要能看出「谁的 transport 未知」才敢打开 strict。
|
|
5563
5633
|
// 这一格**只读**,不参与任何判定(判定在 env-transport-policy.ts)。
|
|
5564
5634
|
env_transport: envTransportOf(r.node_id, r.alias, r.network_id),
|
package/src/tools.ts
CHANGED
|
@@ -306,7 +306,11 @@ function guardNodePermissionTools(server: McpServer, tokenId: string, networkId:
|
|
|
306
306
|
if (cls !== "always") recordNodeToolCall(id, `mcp:${name}`);
|
|
307
307
|
} else {
|
|
308
308
|
const args = callArgs[0] && typeof callArgs[0] === "object" ? callArgs[0] as Record<string, unknown> : {};
|
|
309
|
-
|
|
309
|
+
// #2969 续 —— 令牌解析不到节点行时(nodeId 为 null),两张白名单都管不到它。
|
|
310
|
+
// 先按「记录」模式跑:`unbound_token` **不在 MODE_REASONS 里**,
|
|
311
|
+
// 所以 log(默认)只记账、不改变行为;只有显式 enforce 才会拒。
|
|
312
|
+
// 这样「要不要强制要求绑定令牌」这个决定,将来自有数据可依据。
|
|
313
|
+
const verdict = id.nodeId ? verdictFor(id, name, args) : { reason: "unbound_token" as const, sample: name };
|
|
310
314
|
if (nodeDecide(id, `mcp:${name}`, verdict)) return denied(verdict!.reason, `mcp:${name}`);
|
|
311
315
|
}
|
|
312
316
|
}
|