@sleep2agi/commhub-server 0.9.0-preview.280 → 0.9.0-preview.282
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/build-info.json +2 -2
- package/package.json +1 -1
- package/src/anet-variant-real-daemon-http.test.ts +3 -2
- package/src/api-host-supervisors-source-capabilities.test.ts +107 -0
- package/src/auth_login_guard.test.ts +15 -0
- package/src/auth_login_guard.ts +20 -1
- package/src/board-grants.test.ts +134 -0
- package/src/broadcast-attribution.test.ts +93 -0
- package/src/build-commit-report-http.test.ts +13 -2
- package/src/clone-node-adopted-db.test.ts +78 -0
- package/src/clone-node.ts +5 -1
- package/src/create-node.ts +17 -0
- package/src/department-heads.ts +3 -0
- package/src/expiry-counters.test.ts +50 -1
- package/src/expiry-counters.ts +31 -9
- package/src/health-redaction.test.ts +8 -4
- package/src/launched-by-cli-report-http.test.ts +155 -0
- package/src/mcp-write-network-resolution.test.ts +36 -0
- package/src/node-config-last-update.test.ts +103 -1
- package/src/node-config-last-update.ts +70 -5
- package/src/node-daemon-bindings.ts +9 -0
- package/src/node-grants-http.test.ts +239 -0
- package/src/node-grants.ts +234 -0
- package/src/node-inbox-allowlist-http.test.ts +355 -0
- package/src/node-lifecycle-read.ts +1 -1
- package/src/node-permissions.ts +168 -2
- package/src/opencode-v2-catalog.test.ts +22 -1
- package/src/opencode-v2-catalog.ts +36 -3
- package/src/peer-allowlist.test.ts +29 -0
- package/src/registration-switch-http.test.ts +60 -0
- package/src/reply-bare-infer-4315.test.ts +86 -0
- package/src/requirements-comment-http.test.ts +1 -1
- package/src/requirements-status-participants-http.test.ts +3 -3
- package/src/requirements.ts +29 -4
- package/src/schedule-agent.ts +45 -10
- package/src/scheduled-tasks-http.test.ts +25 -0
- package/src/scheduled-tasks.ts +65 -5
- package/src/server.ts +186 -11
- package/src/session-project-attach-migration.test.ts +2 -1
- package/src/session-project-attach-native.test.ts +3 -1
- package/src/session-project-create-http.test.ts +3 -2
- package/src/session-project-create-native.test.ts +3 -1
- package/src/session-source-delivery.ts +5 -0
- package/src/session-source-directory-http.test.ts +5 -1
- package/src/session-source-evidence.test.ts +11 -4
- package/src/session-source-transport.ts +7 -1
- package/src/steer-send-message.test.ts +121 -0
- package/src/task-access.ts +21 -1
- package/src/test-work-root.ts +18 -0
- package/src/tools.ts +117 -33
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
// 收件白名单(接收侧)—— 节点的主人限定「谁能给它派活 / 发消息」。全部经真实 HTTP 入口(bootServer + REST / /mcp)。
|
|
2
|
+
//
|
|
3
|
+
// 钉住:
|
|
4
|
+
// 1. PUT /api/nodes/:id/inbox-allowlist 与 peer-allowlist 同形:{ senders } / 200 回 { ok, node_id, senders } /
|
|
5
|
+
// [] 拒收 / 非数组 400 / 超 200 条 400 / 普通成员 403 且行没变 / 节点令牌 403 / 不存在 404 / null 清空 / 审计一行。
|
|
6
|
+
// 2. GET /api/nodes 读回 inbox_allowlist;/health 的 capabilities 带 node_inbox_allowlist。
|
|
7
|
+
// 3. 节点发件人按 alias / node_id 匹配;不在名单 ⇒ node_permission_denied + sender_not_allowed + hint,
|
|
8
|
+
// 覆盖 MCP send_task / send_message / retry_task / reassign_task 与 REST POST /api/task;开关 off 也照拒(显式原因)。
|
|
9
|
+
// 4. 人类发件人按 user:<username> / user:<user_id> / user:* 匹配;节点主人、网络 owner/admin 隐式放行,!strict 关掉隐式放行。
|
|
10
|
+
// 5. 发给自己永远放行(含 !strict)。6. 广播跳过不收的收件人并在 inbox_skipped 里报告(没人被跳过时没有这个键),不让整条广播失败。
|
|
11
|
+
//
|
|
12
|
+
// 跑法:COMMHUB_DB=/tmp/x.db bun test server/src/node-inbox-allowlist-http.test.ts
|
|
13
|
+
import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test";
|
|
14
|
+
import { addNetworkMember, createNetworkTokenForNode, register } from "./auth.js";
|
|
15
|
+
import { db } from "./db.js";
|
|
16
|
+
import { inboxAllows } from "./node-permissions.js";
|
|
17
|
+
|
|
18
|
+
const activeDbPath = process.env.COMMHUB_DB ?? (process.env.COMMHUB_TEST_PG_URL ? "postgres" : undefined);
|
|
19
|
+
if (!activeDbPath) throw new Error("node-inbox-allowlist requires COMMHUB_DB (or COMMHUB_TEST_PG_URL) before module import");
|
|
20
|
+
|
|
21
|
+
const stamp = Date.now();
|
|
22
|
+
const PW = "InboxAllow123!";
|
|
23
|
+
let server: any, base = "", net = "";
|
|
24
|
+
const user: Record<string, { id: string; name: string; token: string }> = {};
|
|
25
|
+
const node: Record<string, { id: string; alias: string; token: string }> = {};
|
|
26
|
+
|
|
27
|
+
async function call(token: string, method: string, path: string, body?: unknown) {
|
|
28
|
+
const r = await fetch(`${base}${path}`, {
|
|
29
|
+
method, headers: { Authorization: `Bearer ${token}`, ...(body === undefined ? {} : { "Content-Type": "application/json" }) },
|
|
30
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
31
|
+
});
|
|
32
|
+
const text = await r.text();
|
|
33
|
+
let json: any = null; try { json = JSON.parse(text); } catch {}
|
|
34
|
+
return { status: r.status, body: json, text };
|
|
35
|
+
}
|
|
36
|
+
async function mcp(token: string, name: string, args: Record<string, unknown>): Promise<any> {
|
|
37
|
+
const r = await fetch(`${base}/mcp`, {
|
|
38
|
+
method: "POST",
|
|
39
|
+
headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", Accept: "application/json, text/event-stream" },
|
|
40
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }),
|
|
41
|
+
});
|
|
42
|
+
const text = await r.text();
|
|
43
|
+
const data = text.split("\n").find((l) => l.startsWith("data: "));
|
|
44
|
+
const msg = JSON.parse(data ? data.slice(6) : text);
|
|
45
|
+
const inner = msg.result?.content?.[0]?.text;
|
|
46
|
+
try { return JSON.parse(inner); } catch { return { raw: inner ?? msg }; }
|
|
47
|
+
}
|
|
48
|
+
const setInbox = (list: string[] | null) =>
|
|
49
|
+
db.run("UPDATE nodes SET inbox_allowlist = ?1 WHERE node_id = ?2", [list ? JSON.stringify(list) : null, node.tgt.id]);
|
|
50
|
+
const storedInbox = () => db.get<{ v: string | null }>("SELECT inbox_allowlist AS v FROM nodes WHERE node_id = ?1", node.tgt.id)!.v;
|
|
51
|
+
const inboxRowsFor = (alias: string) => Number(db.get<{ n: number | string }>(
|
|
52
|
+
"SELECT COUNT(*) AS n FROM inbox WHERE session_name = ?1 AND network_id = ?2", alias, net)!.n);
|
|
53
|
+
const expectSenderDenied = (body: any, sender: string) => {
|
|
54
|
+
expect(body.ok).toBe(false);
|
|
55
|
+
expect(body.error).toBe("node_permission_denied");
|
|
56
|
+
expect(body.reason).toBe("sender_not_allowed");
|
|
57
|
+
expect(typeof body.hint).toBe("string");
|
|
58
|
+
expect(body.hint).toContain("inbox allowlist");
|
|
59
|
+
expect(body.target).toBe(node.tgt.alias);
|
|
60
|
+
expect(body.sender).toBe(sender);
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
beforeAll(async () => {
|
|
64
|
+
const boss = register(`ia_boss_${stamp}`, PW);
|
|
65
|
+
net = boss.network_id!;
|
|
66
|
+
user.boss = { id: boss.user!.user_id, name: `ia_boss_${stamp}`, token: boss.token! };
|
|
67
|
+
for (const [k, role] of [["own", "member"], ["adm", "admin"], ["mem", "member"], ["out", null]] as const) {
|
|
68
|
+
const name = `ia_${k}_${stamp}`;
|
|
69
|
+
const u = register(name, PW);
|
|
70
|
+
user[k] = { id: u.user!.user_id, name, token: u.token! };
|
|
71
|
+
if (role) expect(addNetworkMember(net, user[k].id, role, user.boss.id, { agentAccess: "all" }).ok).toBe(true);
|
|
72
|
+
}
|
|
73
|
+
// tgt 的主人是普通成员 own(不是网络 owner),这样「节点主人放行」与「网络 owner 放行」能分开测。
|
|
74
|
+
for (const [key, owner] of [["tgt", "own"], ["a", "boss"], ["b", "boss"], ["c", "boss"]] as const) {
|
|
75
|
+
const alias = `ia-${key}-${stamp}`, id = `n_ia_${key}_${stamp}`;
|
|
76
|
+
const t = createNetworkTokenForNode(user[owner].id, net, alias, id);
|
|
77
|
+
expect(t.ok).toBe(true);
|
|
78
|
+
node[key] = { id, alias, token: t.token! };
|
|
79
|
+
db.run("INSERT INTO sessions (resume_id, alias, status, node_id, network_id) VALUES (?1, ?2, 'idle', ?3, ?4)", [`r_${id}`, alias, id, net]);
|
|
80
|
+
}
|
|
81
|
+
const mod: any = await import("./server.js");
|
|
82
|
+
server = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
|
|
83
|
+
base = `http://127.0.0.1:${server.port}`;
|
|
84
|
+
}, 60_000);
|
|
85
|
+
afterEach(() => { delete process.env.COMMHUB_NODE_PERMISSIONS; setInbox(null); });
|
|
86
|
+
afterAll(() => { server?.stop?.(true); });
|
|
87
|
+
|
|
88
|
+
describe("PUT /api/nodes/:id/inbox-allowlist —— 与 peer-allowlist 同形", () => {
|
|
89
|
+
const put = (token: string, body: unknown, nodeId = node.tgt.id) => call(token, "PUT", `/api/nodes/${nodeId}/inbox-allowlist`, body);
|
|
90
|
+
|
|
91
|
+
test("节点主人设 → 200 { ok, node_id, senders },GET 读回,审计一行 {from,to}", async () => {
|
|
92
|
+
const r = await put(user.own.token, { senders: [node.a.alias, " user:" + user.mem.name + " "] });
|
|
93
|
+
expect(r.status).toBe(200);
|
|
94
|
+
expect(r.body).toEqual({ ok: true, node_id: node.tgt.id, senders: [node.a.alias, `user:${user.mem.name}`] });
|
|
95
|
+
const g = await call(user.boss.token, "GET", `/api/nodes?network_id=${net}&node_id=${node.tgt.id}`);
|
|
96
|
+
expect(g.body.nodes[0].inbox_allowlist).toEqual([node.a.alias, `user:${user.mem.name}`]);
|
|
97
|
+
const audit = db.get<{ detail: string | null; user_id: string | null }>(
|
|
98
|
+
"SELECT detail, user_id FROM audit_log WHERE action = 'node_inbox_allowlist_changed' AND target_id = ?1 ORDER BY id DESC LIMIT 1", node.tgt.id);
|
|
99
|
+
expect(audit?.user_id).toBe(user.own.id);
|
|
100
|
+
expect(JSON.parse(audit!.detail!)).toEqual({ from: null, to: JSON.stringify([node.a.alias, `user:${user.mem.name}`]) });
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
test("网络 owner / admin 也能设;null 清空 → GET 读回 null", async () => {
|
|
104
|
+
expect((await put(user.boss.token, { senders: ["x"] })).status).toBe(200);
|
|
105
|
+
expect((await put(user.adm.token, { senders: ["y"] })).body.senders).toEqual(["y"]);
|
|
106
|
+
const cleared = await put(user.adm.token, { senders: null });
|
|
107
|
+
expect(cleared.status).toBe(200);
|
|
108
|
+
expect(cleared.body.senders).toBeNull();
|
|
109
|
+
expect(storedInbox()).toBeNull();
|
|
110
|
+
const g = await call(user.boss.token, "GET", `/api/nodes?network_id=${net}&node_id=${node.tgt.id}`);
|
|
111
|
+
expect(g.body.nodes[0].inbox_allowlist).toBeNull();
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
test("普通成员 403 且行没变;主人 200 且行真的变(镜像)", async () => {
|
|
115
|
+
setInbox(["keep"]);
|
|
116
|
+
const denied = await put(user.mem.token, { senders: ["sneak"] });
|
|
117
|
+
expect(denied.status).toBe(403);
|
|
118
|
+
expect(denied.body.error).toBe("permission_denied");
|
|
119
|
+
expect(storedInbox()).toBe(JSON.stringify(["keep"]));
|
|
120
|
+
expect((await put(user.own.token, { senders: ["changed"] })).status).toBe(200);
|
|
121
|
+
expect(storedInbox()).toBe(JSON.stringify(["changed"]));
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
test("错误形状:[] / 非数组 / 超 200 条 / 坏 JSON → 400,库没变", async () => {
|
|
125
|
+
setInbox(["keep"]);
|
|
126
|
+
const empty = await put(user.own.token, { senders: [] });
|
|
127
|
+
expect(empty.status).toBe(400);
|
|
128
|
+
expect(empty.body.error).toBe("empty_allowlist_ambiguous");
|
|
129
|
+
expect((await put(user.own.token, { senders: "a" })).body.error).toBe("invalid_senders");
|
|
130
|
+
const many = await put(user.own.token, { senders: Array.from({ length: 201 }, (_, i) => `s${i}`) });
|
|
131
|
+
expect(many.status).toBe(400);
|
|
132
|
+
expect(many.body.error).toBe("too_many_senders");
|
|
133
|
+
const bad = await fetch(`${base}/api/nodes/${node.tgt.id}/inbox-allowlist`, {
|
|
134
|
+
method: "PUT", headers: { Authorization: `Bearer ${user.own.token}`, "Content-Type": "application/json" }, body: "{",
|
|
135
|
+
});
|
|
136
|
+
expect(bad.status).toBe(400);
|
|
137
|
+
expect(storedInbox()).toBe(JSON.stringify(["keep"]));
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
test("节点令牌 403 user_token_required;网络外的人 / 不存在的节点 404;无令牌 401", async () => {
|
|
141
|
+
const asNode = await put(node.tgt.token, { senders: ["x"] });
|
|
142
|
+
expect(asNode.status).toBe(403);
|
|
143
|
+
expect(asNode.body.error).toBe("user_token_required");
|
|
144
|
+
expect((await put(user.out.token, { senders: ["x"] })).status).toBe(404);
|
|
145
|
+
expect((await put(user.boss.token, { senders: ["x"] }, "n_does_not_exist")).status).toBe(404);
|
|
146
|
+
const anon = await fetch(`${base}/api/nodes/${node.tgt.id}/inbox-allowlist`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: "{}" });
|
|
147
|
+
expect(anon.status).toBe(401);
|
|
148
|
+
expect(storedInbox()).toBeNull();
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
test("/health 宣告 node_inbox_allowlist", async () => {
|
|
152
|
+
const r = await fetch(`${base}/health`);
|
|
153
|
+
expect((await r.json()).capabilities).toContain("node_inbox_allowlist");
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
describe("节点发件人 —— alias / node_id 匹配,显式原因", () => {
|
|
158
|
+
test("null = 谁都能发(与今天一致)", async () => {
|
|
159
|
+
expect((await mcp(node.b.token, "send_task", { alias: node.tgt.alias, task: "open inbox" })).ok).toBe(true);
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
test("MCP send_task:名单上的(alias)放行,不在名单上的拒并记在目标节点名下,且不入库", async () => {
|
|
163
|
+
setInbox([node.a.alias]);
|
|
164
|
+
expect((await mcp(node.a.token, "send_task", { alias: node.tgt.alias, task: "from a" })).ok).toBe(true);
|
|
165
|
+
const before = inboxRowsFor(node.tgt.alias);
|
|
166
|
+
const denied = await mcp(node.b.token, "send_task", { alias: node.tgt.alias, task: "from b" });
|
|
167
|
+
expectSenderDenied(denied, node.b.alias);
|
|
168
|
+
expect(denied.route).toBe("mcp:send_task");
|
|
169
|
+
expect(inboxRowsFor(node.tgt.alias)).toBe(before);
|
|
170
|
+
const row = db.get<{ hits: number | string; sample: string | null }>(
|
|
171
|
+
"SELECT hits, sample FROM node_permission_log WHERE network_id = ?1 AND node_id = ?2 AND reason = 'sender_not_allowed' AND route = 'mcp:send_task'", net, node.tgt.id);
|
|
172
|
+
expect(Number(row?.hits)).toBeGreaterThan(0);
|
|
173
|
+
expect(row?.sample).toBe(node.b.alias);
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
test("按 node_id 写也命中", async () => {
|
|
177
|
+
setInbox([node.b.id]);
|
|
178
|
+
expect((await mcp(node.b.token, "send_task", { alias: node.tgt.alias, task: "by id" })).ok).toBe(true);
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
test("显式原因:COMMHUB_NODE_PERMISSIONS=off 也照拒", async () => {
|
|
182
|
+
process.env.COMMHUB_NODE_PERMISSIONS = "off";
|
|
183
|
+
setInbox([node.a.alias]);
|
|
184
|
+
expectSenderDenied(await mcp(node.b.token, "send_task", { alias: node.tgt.alias, task: "off" }), node.b.alias);
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
test("MCP send_message / retry_task / reassign_task 同样拒", async () => {
|
|
188
|
+
setInbox([node.a.alias]);
|
|
189
|
+
expectSenderDenied(await mcp(node.b.token, "send_message", { alias: node.tgt.alias, message: "hi" }), node.b.alias);
|
|
190
|
+
|
|
191
|
+
setInbox(null);
|
|
192
|
+
const t = await mcp(node.a.token, "send_task", { alias: node.tgt.alias, task: "to retry" });
|
|
193
|
+
expect(t.ok).toBe(true);
|
|
194
|
+
db.run("UPDATE tasks SET status = 'failed' WHERE task_id = ?1", [t.message_id]);
|
|
195
|
+
setInbox([node.a.alias]);
|
|
196
|
+
const retry = await mcp(node.b.token, "retry_task", { task_id: t.message_id });
|
|
197
|
+
expectSenderDenied(retry, node.b.alias);
|
|
198
|
+
expect(retry.route).toBe("mcp:retry_task");
|
|
199
|
+
expect(db.get<{ status: string }>("SELECT status FROM tasks WHERE task_id = ?1", t.message_id)!.status).toBe("failed");
|
|
200
|
+
|
|
201
|
+
const r = await mcp(node.a.token, "send_task", { alias: node.c.alias, task: "to reassign" });
|
|
202
|
+
expect(r.ok).toBe(true);
|
|
203
|
+
const re = await mcp(node.b.token, "reassign_task", { task_id: r.message_id, new_alias: node.tgt.alias });
|
|
204
|
+
expectSenderDenied(re, node.b.alias);
|
|
205
|
+
expect(db.get<{ to_name: string }>("SELECT to_name FROM tasks WHERE task_id = ?1", r.message_id)!.to_name).toBe(node.c.alias);
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
test("REST POST /api/task(节点令牌)→ 403 同一形状", async () => {
|
|
209
|
+
setInbox([node.a.alias]);
|
|
210
|
+
const r = await call(node.b.token, "POST", "/api/task", { alias: node.tgt.alias, task: "rest from b", network_id: net });
|
|
211
|
+
expect(r.status).toBe(403);
|
|
212
|
+
expectSenderDenied(r.body, node.b.alias);
|
|
213
|
+
expect(r.body.route).toBe("POST /api/task");
|
|
214
|
+
expect((await call(node.a.token, "POST", "/api/task", { alias: node.tgt.alias, task: "rest from a", network_id: net })).status).toBe(200);
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
test("发给自己永远放行(含 !strict)", async () => {
|
|
218
|
+
setInbox(["!strict"]);
|
|
219
|
+
expect((await mcp(node.tgt.token, "send_task", { alias: node.tgt.alias, task: "note to self" })).ok).toBe(true);
|
|
220
|
+
});
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
describe("人类发件人 —— user:<username|user_id> / user:*,主人与管理员隐式放行", () => {
|
|
224
|
+
const send = (who: string, task = "hello") =>
|
|
225
|
+
call(user[who].token, "POST", "/api/task", { alias: node.tgt.alias, task: `${task} ${who} ${Math.random()}`, network_id: net });
|
|
226
|
+
|
|
227
|
+
test("名单只有节点 ⇒ 普通成员被拒;节点主人、网络 owner、网络 admin 照常能发", async () => {
|
|
228
|
+
setInbox([node.a.alias]);
|
|
229
|
+
const denied = await send("mem");
|
|
230
|
+
expect(denied.status).toBe(403);
|
|
231
|
+
expectSenderDenied(denied.body, `user:${user.mem.name}`);
|
|
232
|
+
for (const who of ["own", "boss", "adm"]) expect((await send(who)).status).toBe(200);
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
test("user:<username>、user:<user_id>、user:* 都命中", async () => {
|
|
236
|
+
for (const entry of [`user:${user.mem.name}`, `user:${user.mem.id}`, "user:*"]) {
|
|
237
|
+
setInbox([node.a.alias, entry]);
|
|
238
|
+
expect((await send("mem")).status).toBe(200);
|
|
239
|
+
}
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
test("!strict 关掉隐式放行:主人与网络 owner 也必须在名单上", async () => {
|
|
243
|
+
setInbox([node.a.alias, "!strict"]);
|
|
244
|
+
expect((await send("own")).status).toBe(403);
|
|
245
|
+
expect((await send("boss")).status).toBe(403);
|
|
246
|
+
setInbox([node.a.alias, "!strict", `user:${user.own.name}`]);
|
|
247
|
+
expect((await send("own")).status).toBe(200);
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
test("MCP 用户令牌同一口径", async () => {
|
|
251
|
+
setInbox([node.a.alias]);
|
|
252
|
+
expectSenderDenied(await mcp(user.mem.token, "send_task", { alias: node.tgt.alias, task: "mcp human", network_id: net }), `user:${user.mem.name}`);
|
|
253
|
+
expect((await mcp(user.own.token, "send_task", { alias: node.tgt.alias, task: "mcp owner", network_id: net })).ok).toBe(true);
|
|
254
|
+
});
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
describe("广播 —— 跳过不收的收件人,报告而不失败", () => {
|
|
258
|
+
test("REST /api/broadcast:tgt 被跳过并出现在 inbox_skipped,其他人照收", async () => {
|
|
259
|
+
setInbox([node.a.alias]);
|
|
260
|
+
const before = { tgt: inboxRowsFor(node.tgt.alias), c: inboxRowsFor(node.c.alias) };
|
|
261
|
+
const r = await call(user.mem.token, "POST", `/api/broadcast?network_id=${net}`, { message: `bc ${stamp}`, network_id: net });
|
|
262
|
+
expect(r.status).toBe(200);
|
|
263
|
+
expect(r.body.ok).toBe(true);
|
|
264
|
+
expect(r.body.inbox_skipped).toEqual([{ alias: node.tgt.alias, node_id: node.tgt.id, reason: "sender_not_allowed" }]);
|
|
265
|
+
expect(inboxRowsFor(node.tgt.alias)).toBe(before.tgt);
|
|
266
|
+
expect(inboxRowsFor(node.c.alias)).toBe(before.c + 1);
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
test("MCP broadcast(节点令牌)同样跳过;没人被跳过时回执恰好三键、没有 inbox_skipped", async () => {
|
|
270
|
+
const open = await mcp(node.b.token, "broadcast", { message: `open ${stamp}` });
|
|
271
|
+
expect(open.ok).toBe(true);
|
|
272
|
+
expect(Object.keys(open).sort()).toEqual(["message_ids", "ok", "recipients"]);
|
|
273
|
+
setInbox([node.a.alias]);
|
|
274
|
+
const r = await mcp(node.b.token, "broadcast", { message: `mcp bc ${stamp}` });
|
|
275
|
+
expect(r.ok).toBe(true);
|
|
276
|
+
expect(r.inbox_skipped.map((s: any) => s.alias)).toEqual([node.tgt.alias]);
|
|
277
|
+
expect(r.recipients).toBe(open.recipients - 1);
|
|
278
|
+
});
|
|
279
|
+
});
|
|
280
|
+
|
|
281
|
+
describe("排程 —— 每次触发按建排程的人现判", () => {
|
|
282
|
+
test("普通成员建的排程:名单不收他 ⇒ 这次运行 failed / sender_not_allowed,不建任务;收他 ⇒ 照常派发", async () => {
|
|
283
|
+
const { dispatchScheduledOccurrence } = await import("./scheduled-tasks.js");
|
|
284
|
+
const schedule = (suffix: string) => {
|
|
285
|
+
const id = `sched_ia_${suffix}_${stamp}`;
|
|
286
|
+
db.run(
|
|
287
|
+
`INSERT INTO scheduled_tasks (schedule_id, network_id, created_by, name, target_node_id, target_alias, task_content, schedule_type, schedule_json, next_run_at)
|
|
288
|
+
VALUES (?1, ?2, ?3, 'n', ?4, ?5, 'scheduled work', 'interval', '{"type":"interval","minutes":60}', datetime('now'))`,
|
|
289
|
+
[id, net, user.mem.id, node.tgt.id, node.tgt.alias],
|
|
290
|
+
);
|
|
291
|
+
return db.get<any>("SELECT * FROM scheduled_tasks WHERE schedule_id = ?1", id);
|
|
292
|
+
};
|
|
293
|
+
setInbox([node.a.alias]);
|
|
294
|
+
const denied = dispatchScheduledOccurrence(schedule("deny"), new Date().toISOString(), false);
|
|
295
|
+
expect(denied.status).toBe("failed");
|
|
296
|
+
expect(denied.taskId).toBeUndefined();
|
|
297
|
+
expect(db.get<{ error_code: string }>("SELECT error_code FROM scheduled_task_runs WHERE run_id = ?1", denied.runId)?.error_code).toBe("sender_not_allowed");
|
|
298
|
+
setInbox([node.a.alias, `user:${user.mem.name}`]);
|
|
299
|
+
const ok = dispatchScheduledOccurrence(schedule("allow"), new Date().toISOString(), false);
|
|
300
|
+
expect(ok.taskId).toBeTruthy();
|
|
301
|
+
});
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
describe("部门授权 dept:<department_id>(admin 11-11「以部门去授权」)", () => {
|
|
305
|
+
const mkDept = (id: string, parent: string | null) =>
|
|
306
|
+
db.run("INSERT INTO network_departments (network_id, department_id, name, parent_id, sort, created_by) VALUES (?1, ?2, ?3, ?4, 0, ?5)", [net, id, id, parent, user.boss.id]);
|
|
307
|
+
const setDept = (nodeId: string, dept: string | null) => db.run("UPDATE nodes SET department_id = ?1 WHERE node_id = ?2", [dept, nodeId]);
|
|
308
|
+
test("名单写上级部门:子部门里的节点能派活,别的部门 / 未分配的被拒", async () => {
|
|
309
|
+
const top = `dept_top_${stamp}`, child = `dept_child_${stamp}`, other = `dept_other_${stamp}`;
|
|
310
|
+
mkDept(top, null); mkDept(child, top); mkDept(other, null);
|
|
311
|
+
setDept(node.a.id, child); setDept(node.b.id, other); setDept(node.c.id, null);
|
|
312
|
+
try {
|
|
313
|
+
setInbox([`dept:${top}`]);
|
|
314
|
+
const ok = await mcp(node.a.token, "send_task", { alias: node.tgt.alias, task: "dept ok" });
|
|
315
|
+
expect(ok.ok).not.toBe(false);
|
|
316
|
+
expectSenderDenied(await mcp(node.b.token, "send_task", { alias: node.tgt.alias, task: "dept other" }), node.b.alias);
|
|
317
|
+
expectSenderDenied(await mcp(node.c.token, "send_task", { alias: node.tgt.alias, task: "dept none" }), node.c.alias);
|
|
318
|
+
} finally {
|
|
319
|
+
setDept(node.a.id, null); setDept(node.b.id, null);
|
|
320
|
+
db.run("DELETE FROM network_departments WHERE network_id = ?1 AND department_id IN (?2, ?3, ?4)", [net, top, child, other]);
|
|
321
|
+
}
|
|
322
|
+
});
|
|
323
|
+
test("人按 network_members.department_id 匹配;!strict 下同样只看名单", async () => {
|
|
324
|
+
const d = `dept_people_${stamp}`;
|
|
325
|
+
mkDept(d, null);
|
|
326
|
+
db.run("UPDATE network_members SET department_id = ?1 WHERE network_id = ?2 AND user_id = ?3", [d, net, user.mem.id]);
|
|
327
|
+
try {
|
|
328
|
+
const ctx = { targetNodeId: node.tgt.id, targetAlias: node.tgt.alias, ownerUserId: user.own.id, networkId: net };
|
|
329
|
+
const mem = { kind: "user" as const, userId: user.mem.id, username: user.mem.name };
|
|
330
|
+
expect(inboxAllows([`dept:${d}`, "!strict"], mem, ctx)).toBe(true);
|
|
331
|
+
expect(inboxAllows(["dept:dept_nope", "!strict"], mem, ctx)).toBe(false);
|
|
332
|
+
} finally {
|
|
333
|
+
db.run("UPDATE network_members SET department_id = NULL WHERE network_id = ?1 AND user_id = ?2", [net, user.mem.id]);
|
|
334
|
+
db.run("DELETE FROM network_departments WHERE network_id = ?1 AND department_id = ?2", [net, d]);
|
|
335
|
+
}
|
|
336
|
+
});
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
describe("inboxAllows —— 纯判定", () => {
|
|
340
|
+
const ctx = { targetNodeId: "n_t", targetAlias: "t", ownerUserId: "u_owner", networkId: null };
|
|
341
|
+
test("null 放行一切;legacy 默认放行,!strict 拒", () => {
|
|
342
|
+
expect(inboxAllows(null, { kind: "legacy" }, ctx)).toBe(true);
|
|
343
|
+
expect(inboxAllows(["x"], { kind: "legacy" }, ctx)).toBe(true);
|
|
344
|
+
expect(inboxAllows(["x", "!strict"], { kind: "legacy" }, ctx)).toBe(false);
|
|
345
|
+
});
|
|
346
|
+
test("Hub 管理员隐式放行;!strict 下不放行", () => {
|
|
347
|
+
const admin = { kind: "user" as const, userId: "u_admin", username: "root", isHubAdmin: true };
|
|
348
|
+
expect(inboxAllows(["x"], admin, ctx)).toBe(true);
|
|
349
|
+
expect(inboxAllows(["x", "!strict"], admin, ctx)).toBe(false);
|
|
350
|
+
});
|
|
351
|
+
test("节点条目不会匹配到同名的人(user: 前缀才是人)", () => {
|
|
352
|
+
expect(inboxAllows(["alice"], { kind: "user", userId: "u_a", username: "alice" }, ctx)).toBe(false);
|
|
353
|
+
expect(inboxAllows(["user:*"], { kind: "node", nodeId: "n_x", aliases: ["x"] }, ctx)).toBe(false);
|
|
354
|
+
});
|
|
355
|
+
});
|
|
@@ -24,7 +24,7 @@ const publicLifecycleErrors = new Set([
|
|
|
24
24
|
"adopt_workdir_outside_roots", "adopt_workdir_not_absolute",
|
|
25
25
|
"adopt_alias_invalid", "adopt_alias_mismatch", "adopt_config_invalid",
|
|
26
26
|
"adopt_config_network_mismatch", "adopt_network_mismatch",
|
|
27
|
-
"adopt_hub_invalid", "adopt_hub_missing", "adopt_hub_mismatch",
|
|
27
|
+
"adopt_hub_invalid", "adopt_hub_missing", "adopt_hub_mismatch", "adopt_hub_unverifiable",
|
|
28
28
|
"adopt_identity_ambiguous", "adopt_identity_not_found", "adopt_identity_changed",
|
|
29
29
|
"adopt_path_not_regular", "adopt_path_owner_mismatch", "adopt_path_writable_by_others",
|
|
30
30
|
"adopt_process_argv_mismatch", "adopt_process_home_mismatch",
|
package/src/node-permissions.ts
CHANGED
|
@@ -36,17 +36,23 @@ export type NodePermissionReason =
|
|
|
36
36
|
* 这类令牌**没有 nodes 行**,两张白名单都管不到它;先按「记录」模式跑,看有多少。 */
|
|
37
37
|
| "unbound_token"
|
|
38
38
|
/** #2969 续 —— 主人在这个节点的 REST 白名单里没有列这条写路由。 */
|
|
39
|
-
| "rest_not_allowed"
|
|
39
|
+
| "rest_not_allowed"
|
|
40
|
+
/** 收件白名单 —— **目标**节点的主人设了收件白名单,发件人不在名单上。判的是收件方,不是调用方。 */
|
|
41
|
+
| "sender_not_allowed";
|
|
40
42
|
|
|
41
43
|
/** 显式模式的原因:不看开关,永远拒。 */
|
|
42
44
|
// 白名单和 readonly/restricted 同类:**主人主动设的,设了就立刻生效**,不看开关。
|
|
43
|
-
const MODE_REASONS: ReadonlySet<NodePermissionReason> = new Set(["mode_readonly", "mode_restricted_not_assigned", "peer_not_allowed", "tool_not_allowed", "rest_not_allowed"]);
|
|
45
|
+
const MODE_REASONS: ReadonlySet<NodePermissionReason> = new Set(["mode_readonly", "mode_restricted_not_assigned", "peer_not_allowed", "tool_not_allowed", "rest_not_allowed", "sender_not_allowed"]);
|
|
44
46
|
|
|
45
47
|
// #2969 —— 节点级对端白名单:JSON 数组(alias 或 node_id);NULL = 不限制。
|
|
46
48
|
// 只增不改:旧代码不读这一列;设为 NULL 时行为与现在完全一致。
|
|
47
49
|
// #2969 后半 —— 接口白名单:JSON 数组(MCP 工具名);NULL = 不限制。
|
|
48
50
|
// #2969 续 —— REST 写接口白名单:JSON 数组(形如 "POST /api/task");NULL = 不限制。
|
|
49
51
|
// 只对**节点令牌的写方法**生效(GET / SSE 永不经过它,否则节点会变聋)。
|
|
52
|
+
// 收件白名单:JSON 数组(alias / node_id / user:<username|user_id> / user:* / !strict);NULL = 谁都能发。
|
|
53
|
+
try { db.exec("ALTER TABLE nodes ADD COLUMN inbox_allowlist TEXT"); } catch (e: any) {
|
|
54
|
+
if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
|
|
55
|
+
}
|
|
50
56
|
try { db.exec("ALTER TABLE nodes ADD COLUMN rest_allowlist TEXT"); } catch (e: any) {
|
|
51
57
|
if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
|
|
52
58
|
}
|
|
@@ -304,6 +310,7 @@ const HINTS: Record<NodePermissionReason, string> = {
|
|
|
304
310
|
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",
|
|
305
311
|
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",
|
|
306
312
|
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",
|
|
313
|
+
sender_not_allowed: "the target node only accepts tasks and messages from an explicit inbox allowlist and you are not on it — ask the target node's owner to add you (alias, node_id, or user:<username>), or clear its inbox allowlist",
|
|
307
314
|
};
|
|
308
315
|
|
|
309
316
|
export function nodePermissionDeniedBody(reason: NodePermissionReason, route: string): { ok: false; error: "node_permission_denied"; reason: NodePermissionReason; route: string; hint: string } {
|
|
@@ -400,6 +407,165 @@ export function broadcastVerdict(id: NodeIdentity): Verdict {
|
|
|
400
407
|
return null;
|
|
401
408
|
}
|
|
402
409
|
|
|
410
|
+
// ── 收件白名单(接收侧) ──
|
|
411
|
+
//
|
|
412
|
+
// 上面几条判的都是**调用方**能不能发;这里判**收件方**愿不愿意收。两边独立、都要过。
|
|
413
|
+
// 名单条目:
|
|
414
|
+
// alias / node_id → 匹配 Agent 发件人(节点令牌)
|
|
415
|
+
// user:<username|user_id> → 匹配人(Dashboard / 桌面端的用户令牌);user:* = 任何人
|
|
416
|
+
// !strict → 关掉下面的隐式放行
|
|
417
|
+
// 隐式放行(没有 !strict 时):节点主人、网络 owner/admin、Hub 管理员、旧的无身份调用(open/legacy 模式,
|
|
418
|
+
// 本来就「谁都是谁」,名单在那里无从判起)。目的:主人设名单时不会把自己锁在门外。
|
|
419
|
+
// 节点发给自己永远放行(含 !strict)。
|
|
420
|
+
export const INBOX_STRICT_ENTRY = "!strict";
|
|
421
|
+
|
|
422
|
+
export type InboxSender =
|
|
423
|
+
| { kind: "node"; nodeId: string | null; aliases: string[] }
|
|
424
|
+
| { kind: "user"; userId: string; username: string | null; isHubAdmin?: boolean }
|
|
425
|
+
| { kind: "legacy" };
|
|
426
|
+
|
|
427
|
+
/** 从调用方的令牌上下文得出发件人(REST 与 MCP 共用,免得两边口径漂)。 */
|
|
428
|
+
export function inboxSenderFromAuth(auth: { isNodeToken: boolean; tokenId: string | null; boundNetworkId: string | null; userId: string | null; username: string | null }): InboxSender {
|
|
429
|
+
if (auth.isNodeToken) {
|
|
430
|
+
const id = auth.boundNetworkId ? nodeIdentity(auth.tokenId, auth.boundNetworkId) : null;
|
|
431
|
+
return { kind: "node", nodeId: id?.nodeId ?? null, aliases: id?.aliases ?? [] };
|
|
432
|
+
}
|
|
433
|
+
if (auth.userId) {
|
|
434
|
+
const isHubAdmin = db.get<{ role: string | null }>("SELECT role FROM users WHERE user_id = ?1", auth.userId)?.role === "admin";
|
|
435
|
+
return { kind: "user", userId: auth.userId, username: auth.username, isHubAdmin };
|
|
436
|
+
}
|
|
437
|
+
return { kind: "legacy" };
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
export function inboxSenderLabel(sender: InboxSender): string {
|
|
441
|
+
if (sender.kind === "node") return sender.aliases[0] ?? (sender.nodeId ? `node:${sender.nodeId}` : "node:?");
|
|
442
|
+
if (sender.kind === "user") return `user:${sender.username ?? sender.userId}`;
|
|
443
|
+
return "legacy";
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
type InboxTargetRow = { node_id: string; alias: string | null; owner_user_id: string | null; inbox_allowlist: string | null };
|
|
447
|
+
|
|
448
|
+
function inboxTargetRow(networkId: string | null, target: AgentRef): InboxTargetRow | null {
|
|
449
|
+
if (target.nodeId) {
|
|
450
|
+
const row = db.get<InboxTargetRow>(
|
|
451
|
+
"SELECT node_id, alias, owner_user_id, inbox_allowlist FROM nodes WHERE node_id = ?1", target.nodeId);
|
|
452
|
+
if (row) return row;
|
|
453
|
+
}
|
|
454
|
+
if (target.alias && networkId) {
|
|
455
|
+
return db.get<InboxTargetRow>(
|
|
456
|
+
"SELECT node_id, alias, owner_user_id, inbox_allowlist FROM nodes WHERE alias = ?1 AND network_id = ?2 LIMIT 1", target.alias, networkId);
|
|
457
|
+
}
|
|
458
|
+
return null;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/** 名单里的部门项:`dept:<department_id>`(含它下面的子部门)。admin 2026-11-11「以部门去授权」。 */
|
|
462
|
+
export const INBOX_DEPT_PREFIX = "dept:";
|
|
463
|
+
|
|
464
|
+
/** 发件人所在部门及其所有上级部门(自下而上,最多 32 层防环)。拿不到部门 = 空。 */
|
|
465
|
+
function senderDepartmentChain(sender: InboxSender, networkId: string | null): string[] {
|
|
466
|
+
if (!networkId) return [];
|
|
467
|
+
let dept: string | null = null;
|
|
468
|
+
if (sender.kind === "node") {
|
|
469
|
+
const row = sender.nodeId
|
|
470
|
+
? db.get<{ department_id: string | null }>("SELECT department_id FROM nodes WHERE node_id = ?1", sender.nodeId)
|
|
471
|
+
: sender.aliases[0]
|
|
472
|
+
? db.get<{ department_id: string | null }>("SELECT department_id FROM nodes WHERE alias = ?1 AND network_id = ?2 LIMIT 1", sender.aliases[0], networkId)
|
|
473
|
+
: null;
|
|
474
|
+
dept = row?.department_id ?? null;
|
|
475
|
+
} else if (sender.kind === "user") {
|
|
476
|
+
dept = db.get<{ department_id: string | null }>(
|
|
477
|
+
"SELECT department_id FROM network_members WHERE network_id = ?1 AND user_id = ?2", networkId, sender.userId)?.department_id ?? null;
|
|
478
|
+
}
|
|
479
|
+
const chain: string[] = [];
|
|
480
|
+
for (let i = 0; dept && i < 32 && !chain.includes(dept); i++) {
|
|
481
|
+
chain.push(dept);
|
|
482
|
+
dept = db.get<{ parent_id: string | null }>(
|
|
483
|
+
"SELECT parent_id FROM network_departments WHERE network_id = ?1 AND department_id = ?2", networkId, dept)?.parent_id ?? null;
|
|
484
|
+
}
|
|
485
|
+
return chain;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
function inboxDeptAllows(list: string[], sender: InboxSender, networkId: string | null): boolean {
|
|
489
|
+
const depts = list.filter(e => e.startsWith(INBOX_DEPT_PREFIX)).map(e => e.slice(INBOX_DEPT_PREFIX.length));
|
|
490
|
+
if (!depts.length) return false;
|
|
491
|
+
return senderDepartmentChain(sender, networkId).some(d => depts.includes(d));
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/** 纯判定(不记账):名单 + 发件人 → 放不放行。 */
|
|
495
|
+
export function inboxAllows(
|
|
496
|
+
list: string[] | null,
|
|
497
|
+
sender: InboxSender,
|
|
498
|
+
ctx: { targetNodeId: string; targetAlias: string | null; ownerUserId: string | null; networkId: string | null },
|
|
499
|
+
): boolean {
|
|
500
|
+
if (!list) return true;
|
|
501
|
+
if (sender.kind === "node") {
|
|
502
|
+
if ((sender.nodeId && sender.nodeId === ctx.targetNodeId) || (ctx.targetAlias && sender.aliases.includes(ctx.targetAlias))) return true;
|
|
503
|
+
return (!!sender.nodeId && list.includes(sender.nodeId)) || sender.aliases.some(a => list.includes(a))
|
|
504
|
+
|| inboxDeptAllows(list, sender, ctx.networkId);
|
|
505
|
+
}
|
|
506
|
+
const strict = list.includes(INBOX_STRICT_ENTRY);
|
|
507
|
+
if (sender.kind === "legacy") return !strict;
|
|
508
|
+
if (!strict) {
|
|
509
|
+
if (sender.isHubAdmin) return true;
|
|
510
|
+
if (ctx.ownerUserId && sender.userId === ctx.ownerUserId) return true;
|
|
511
|
+
if (ctx.networkId) {
|
|
512
|
+
const role = db.get<{ role: string }>("SELECT role FROM network_members WHERE network_id = ?1 AND user_id = ?2", ctx.networkId, sender.userId)?.role;
|
|
513
|
+
if (role === "owner" || role === "admin") return true;
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
return list.includes("user:*")
|
|
517
|
+
|| list.includes(`user:${sender.userId}`)
|
|
518
|
+
|| (!!sender.username && list.includes(`user:${sender.username}`))
|
|
519
|
+
|| inboxDeptAllows(list, sender, ctx.networkId);
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
export type InboxDenial = ReturnType<typeof nodePermissionDeniedBody> & { target: string; sender: string };
|
|
523
|
+
|
|
524
|
+
/**
|
|
525
|
+
* 发往 target 之前判一次收件白名单。放行 → null;拒绝 → 拒绝体(REST 403 / MCP 文本同形),
|
|
526
|
+
* 并按**目标节点**记一行 node_permission_log(主人在报表里能看到谁被挡在门外)。
|
|
527
|
+
*/
|
|
528
|
+
export function inboxDenied(networkId: string | null, target: AgentRef, sender: InboxSender, route: string): InboxDenial | null {
|
|
529
|
+
const row = inboxTargetRow(networkId, target);
|
|
530
|
+
if (!row) return null;
|
|
531
|
+
const list = normalizePeerAllowlist(row.inbox_allowlist);
|
|
532
|
+
if (!list) return null;
|
|
533
|
+
if (inboxAllows(list, sender, { targetNodeId: row.node_id, targetAlias: row.alias ?? target.alias, ownerUserId: row.owner_user_id, networkId })) return null;
|
|
534
|
+
const senderLabel = inboxSenderLabel(sender);
|
|
535
|
+
const targetLabel = row.alias ?? target.alias ?? row.node_id;
|
|
536
|
+
if (networkId) {
|
|
537
|
+
recordNodePermission({
|
|
538
|
+
networkId, nodeId: row.node_id, logKey: row.node_id, aliases: row.alias ? [row.alias] : [], ownerUserId: row.owner_user_id,
|
|
539
|
+
mode: "normal", peerAllowlist: null, toolAllowlist: null, restAllowlist: null,
|
|
540
|
+
}, route, "sender_not_allowed", senderLabel);
|
|
541
|
+
}
|
|
542
|
+
return { ...nodePermissionDeniedBody("sender_not_allowed", route), target: targetLabel, sender: senderLabel };
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
export type InboxSkipped = { alias: string; node_id: string | null; reason: "sender_not_allowed" };
|
|
546
|
+
|
|
547
|
+
/**
|
|
548
|
+
* 广播:收件白名单不收这个发件人的收件人**跳过**(不让整条广播失败),并报告给调用方。
|
|
549
|
+
* 快路径:全库没有任何节点设收件白名单时一次查询就返回,不逐个判。
|
|
550
|
+
*/
|
|
551
|
+
export function filterBroadcastByInbox<T extends { alias: string; node_id: string | null; network_id: string | null }>(
|
|
552
|
+
targets: readonly T[], effectiveNetId: string | null, sender: InboxSender, route: string,
|
|
553
|
+
): { allowed: T[]; skipped: InboxSkipped[] } {
|
|
554
|
+
if (!targets.length || !db.get("SELECT 1 AS ok FROM nodes WHERE inbox_allowlist IS NOT NULL LIMIT 1")) {
|
|
555
|
+
return { allowed: [...targets], skipped: [] };
|
|
556
|
+
}
|
|
557
|
+
const allowed: T[] = [];
|
|
558
|
+
const skipped: InboxSkipped[] = [];
|
|
559
|
+
for (const t of targets) {
|
|
560
|
+
if (inboxDenied(effectiveNetId ?? t.network_id ?? null, { alias: t.alias, nodeId: t.node_id }, sender, route)) {
|
|
561
|
+
skipped.push({ alias: t.alias, node_id: t.node_id ?? null, reason: "sender_not_allowed" });
|
|
562
|
+
} else {
|
|
563
|
+
allowed.push(t);
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
return { allowed, skipped };
|
|
567
|
+
}
|
|
568
|
+
|
|
403
569
|
/** 一般的写(管节点、提交技能、探测模型…):只读 / 受限拒;正常放行(由各自的既有规则管)。 */
|
|
404
570
|
export function writeVerdict(id: NodeIdentity, sample?: string): Verdict {
|
|
405
571
|
if (id.mode === "readonly") return { reason: "mode_readonly", sample };
|
|
@@ -35,7 +35,7 @@ const PROJECT = resolve(mkdtempSync(join(tmpdir(), "oc-hub-proj-")));
|
|
|
35
35
|
function cleanup() {
|
|
36
36
|
resetOpenCodeCatalogForTest();
|
|
37
37
|
for (const net of [NET, OTHER]) {
|
|
38
|
-
for (const table of ["node_create_requests", "audit_log", "nodes", "sessions", "api_tokens", "network_members"]) {
|
|
38
|
+
for (const table of ["node_create_requests", "node_daemon_bindings", "audit_log", "nodes", "sessions", "api_tokens", "network_members"]) {
|
|
39
39
|
try { db.run(`DELETE FROM ${table} WHERE network_id = ?1`, [net]); } catch {}
|
|
40
40
|
}
|
|
41
41
|
try { db.run("DELETE FROM networks WHERE network_id = ?1", [net]); } catch {}
|
|
@@ -198,6 +198,27 @@ describe("hub authorizes an owned OpenCode V2 catalog read", () => {
|
|
|
198
198
|
expect(queue(USER, "node_missing")).toEqual({ ok: false, error: "node_not_found" });
|
|
199
199
|
});
|
|
200
200
|
|
|
201
|
+
test("an ADOPTED OpenCode V2 node (no create row) may be read; directory = binding workdir (admin 2026-11-11)", () => {
|
|
202
|
+
seed();
|
|
203
|
+
const adopt = (nodeId: string, runtime: string, generation: string | null, status = "active") => {
|
|
204
|
+
db.run(`INSERT INTO nodes (node_id, node_name, alias, network_id, runtime, config_snapshot, hostname, created_at, updated_at, lifecycle_state)
|
|
205
|
+
VALUES (?1, ?1, ?1, ?2, ?3, ?4, 'host-x', datetime('now'), datetime('now'), 'active')`,
|
|
206
|
+
[nodeId, NET, runtime, JSON.stringify(generation ? { flags: { opencodeGeneration: generation } } : {})]);
|
|
207
|
+
db.run(`INSERT INTO node_daemon_bindings(request_id,network_id,node_id,daemon_node_id,workdir,requested_by,status,created_at,updated_at)
|
|
208
|
+
VALUES(?1,?2,?3,?4,?5,'u',?6,1,1)`, [`adopt_${nodeId}`, NET, nodeId, DAEMON, PROJECT, status]);
|
|
209
|
+
};
|
|
210
|
+
adopt("node_adopted_v2", "opencode-sdk", "v2");
|
|
211
|
+
adopt("node_adopted_v1", "opencode-sdk", "v1");
|
|
212
|
+
adopt("node_adopted_refused", "opencode-sdk", "v2", "refused");
|
|
213
|
+
const ok = queue(USER, "node_adopted_v2");
|
|
214
|
+
expect(ok.ok).toBe(true);
|
|
215
|
+
const taken = takeOpenCodeCatalogRequest((ok as any).request_id, DAEMON);
|
|
216
|
+
expect(taken.ok && taken.alias).toBe("node_adopted_v2");
|
|
217
|
+
expect(taken.ok && taken.directory).toBe(PROJECT);
|
|
218
|
+
expect(queue(USER, "node_adopted_v1")).toEqual({ ok: false, error: "not_opencode_v2" });
|
|
219
|
+
expect(queue(USER, "node_adopted_refused")).toEqual({ ok: false, error: "node_not_found" });
|
|
220
|
+
});
|
|
221
|
+
|
|
201
222
|
test("pending is not a snapshot; expiry, bad acks, and a missing endpoint stay closed", async () => {
|
|
202
223
|
seed();
|
|
203
224
|
const queued = queue(USER, V2);
|