@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.
Files changed (50) hide show
  1. package/build-info.json +2 -2
  2. package/package.json +1 -1
  3. package/src/anet-variant-real-daemon-http.test.ts +3 -2
  4. package/src/api-host-supervisors-source-capabilities.test.ts +107 -0
  5. package/src/auth_login_guard.test.ts +15 -0
  6. package/src/auth_login_guard.ts +20 -1
  7. package/src/board-grants.test.ts +134 -0
  8. package/src/broadcast-attribution.test.ts +93 -0
  9. package/src/build-commit-report-http.test.ts +13 -2
  10. package/src/clone-node-adopted-db.test.ts +78 -0
  11. package/src/clone-node.ts +5 -1
  12. package/src/create-node.ts +17 -0
  13. package/src/department-heads.ts +3 -0
  14. package/src/expiry-counters.test.ts +50 -1
  15. package/src/expiry-counters.ts +31 -9
  16. package/src/health-redaction.test.ts +8 -4
  17. package/src/launched-by-cli-report-http.test.ts +155 -0
  18. package/src/mcp-write-network-resolution.test.ts +36 -0
  19. package/src/node-config-last-update.test.ts +103 -1
  20. package/src/node-config-last-update.ts +70 -5
  21. package/src/node-daemon-bindings.ts +9 -0
  22. package/src/node-grants-http.test.ts +239 -0
  23. package/src/node-grants.ts +234 -0
  24. package/src/node-inbox-allowlist-http.test.ts +355 -0
  25. package/src/node-lifecycle-read.ts +1 -1
  26. package/src/node-permissions.ts +168 -2
  27. package/src/opencode-v2-catalog.test.ts +22 -1
  28. package/src/opencode-v2-catalog.ts +36 -3
  29. package/src/peer-allowlist.test.ts +29 -0
  30. package/src/registration-switch-http.test.ts +60 -0
  31. package/src/reply-bare-infer-4315.test.ts +86 -0
  32. package/src/requirements-comment-http.test.ts +1 -1
  33. package/src/requirements-status-participants-http.test.ts +3 -3
  34. package/src/requirements.ts +29 -4
  35. package/src/schedule-agent.ts +45 -10
  36. package/src/scheduled-tasks-http.test.ts +25 -0
  37. package/src/scheduled-tasks.ts +65 -5
  38. package/src/server.ts +186 -11
  39. package/src/session-project-attach-migration.test.ts +2 -1
  40. package/src/session-project-attach-native.test.ts +3 -1
  41. package/src/session-project-create-http.test.ts +3 -2
  42. package/src/session-project-create-native.test.ts +3 -1
  43. package/src/session-source-delivery.ts +5 -0
  44. package/src/session-source-directory-http.test.ts +5 -1
  45. package/src/session-source-evidence.test.ts +11 -4
  46. package/src/session-source-transport.ts +7 -1
  47. package/src/steer-send-message.test.ts +121 -0
  48. package/src/task-access.ts +21 -1
  49. package/src/test-work-root.ts +18 -0
  50. package/src/tools.ts +117 -33
@@ -0,0 +1,239 @@
1
+ // 节点管理授权(node-grants.ts)—— 全部经真实 HTTP 入口(bootServer + REST / /mcp)。
2
+ //
3
+ // 钉住:
4
+ // 1. PUT /api/nodes/:id/grants:网络 owner 可授全网;节点主人(普通成员)不行;部门负责人只能授自己子树里的部门范围,
5
+ // 授 network 403;未知能力 / 计划中的 board 能力 400;GET 读回;/health 带 node_grants。
6
+ // 2. 定时任务:没授权时节点看不到别人的计划;schedules·network·read ⇒ 看得到、改不了(not_schedule_creator);
7
+ // edit ⇒ 能改、能取消,审计一行 schedule_changed_via_node_grant;department 范围只覆盖目标节点在子树里的计划;
8
+ // 只读模式的节点 edit 降为 read;撤销([])当场生效。
9
+ //
10
+ // 跑法:COMMHUB_DB=/tmp/x.db bun test server/src/node-grants-http.test.ts
11
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
12
+ import { addNetworkMember, createNetworkTokenForNode, register } from "./auth.js";
13
+ import { db } from "./db.js";
14
+
15
+ const activeDbPath = process.env.COMMHUB_DB ?? (process.env.COMMHUB_TEST_PG_URL ? "postgres" : undefined);
16
+ if (!activeDbPath) throw new Error("node-grants requires COMMHUB_DB (or COMMHUB_TEST_PG_URL) before module import");
17
+
18
+ const stamp = Date.now();
19
+ const PW = "NodeGrants123!";
20
+ let server: any, base = "", net = "";
21
+ const user: Record<string, { id: string; name: string; token: string }> = {};
22
+ const node: Record<string, { id: string; alias: string; token: string }> = {};
23
+ const deptA = `dept_ga_${stamp}`, deptB = `dept_gb_${stamp}`;
24
+
25
+ async function call(token: string, method: string, path: string, body?: unknown) {
26
+ const r = await fetch(`${base}${path}`, {
27
+ method, headers: { Authorization: `Bearer ${token}`, ...(body === undefined ? {} : { "Content-Type": "application/json" }) },
28
+ body: body === undefined ? undefined : JSON.stringify(body),
29
+ });
30
+ const text = await r.text();
31
+ let json: any = null; try { json = JSON.parse(text); } catch {}
32
+ return { status: r.status, body: json };
33
+ }
34
+ async function mcp(token: string, name: string, args: Record<string, unknown>): Promise<any> {
35
+ const r = await fetch(`${base}/mcp`, {
36
+ method: "POST",
37
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", Accept: "application/json, text/event-stream" },
38
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }),
39
+ });
40
+ const text = await r.text();
41
+ const data = text.split("\n").find((l) => l.startsWith("data: "));
42
+ const msg = JSON.parse(data ? data.slice(6) : text);
43
+ const inner = msg.result?.content?.[0]?.text;
44
+ try { return JSON.parse(inner); } catch { return { raw: inner ?? msg }; }
45
+ }
46
+ const putGrants = (token: string, nodeId: string, grants: unknown) => call(token, "PUT", `/api/nodes/${nodeId}/grants`, { grants });
47
+ async function scheduleFor(target: string, name: string): Promise<string> {
48
+ const r = await call(user.boss.token, "POST", "/api/scheduled-tasks", {
49
+ network_id: net, name, target_node_id: target, task: `${name} task`, timezone: "UTC", schedule: { type: "interval", every_seconds: 86400 },
50
+ });
51
+ expect(r.status).toBe(201);
52
+ return r.body.schedule.schedule_id;
53
+ }
54
+ const listIds = async (token: string) => ((await mcp(token, "schedule_list", {})).schedules ?? []).map((s: any) => s.schedule_id);
55
+
56
+ let schedA = "", schedB = "";
57
+
58
+ beforeAll(async () => {
59
+ const boss = register(`ng_boss_${stamp}`, PW);
60
+ net = boss.network_id!;
61
+ user.boss = { id: boss.user!.user_id, name: `ng_boss_${stamp}`, token: boss.token! };
62
+ for (const k of ["own", "lead"] as const) {
63
+ const name = `ng_${k}_${stamp}`;
64
+ const u = register(name, PW);
65
+ user[k] = { id: u.user!.user_id, name, token: u.token! };
66
+ expect(addNetworkMember(net, user[k].id, "member", user.boss.id, { agentAccess: "all" }).ok).toBe(true);
67
+ }
68
+ // mgr 是被授权的节点(主人 own);a 在部门 A,b 在部门 B。
69
+ for (const [key, owner] of [["mgr", "own"], ["a", "boss"], ["b", "boss"]] as const) {
70
+ const alias = `ng-${key}-${stamp}`, id = `n_ng_${key}_${stamp}`;
71
+ const t = createNetworkTokenForNode(user[owner].id, net, alias, id);
72
+ expect(t.ok).toBe(true);
73
+ node[key] = { id, alias, token: t.token! };
74
+ db.run("INSERT INTO sessions (resume_id, alias, status, node_id, network_id) VALUES (?1, ?2, 'idle', ?3, ?4)", [`r_${id}`, alias, id, net]);
75
+ }
76
+ db.run("INSERT INTO network_departments (network_id, department_id, name, parent_id, sort, created_by, leader_user_id) VALUES (?1, ?2, 'A', NULL, 0, ?3, ?4)", [net, deptA, user.boss.id, user.lead.id]);
77
+ db.run("INSERT INTO network_departments (network_id, department_id, name, parent_id, sort, created_by) VALUES (?1, ?2, 'B', NULL, 1, ?3)", [net, deptB, user.boss.id]);
78
+ // board 判「卡的负责人所在部门」⇒ 成员要先有部门。
79
+ db.run("UPDATE network_members SET department_id = ?1 WHERE network_id = ?2 AND user_id IN (?3, ?4)", [deptA, net, user.own.id, user.lead.id]);
80
+ db.run("UPDATE network_members SET department_id = ?1 WHERE network_id = ?2 AND user_id = ?3", [deptB, net, user.boss.id]);
81
+ db.run("UPDATE nodes SET department_id = ?1 WHERE node_id = ?2", [deptA, node.a.id]);
82
+ db.run("UPDATE nodes SET department_id = ?1 WHERE node_id = ?2", [deptB, node.b.id]);
83
+ const mod: any = await import("./server.js");
84
+ server = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
85
+ base = `http://127.0.0.1:${server.port}`;
86
+ schedA = await scheduleFor(node.a.id, "for-a");
87
+ schedB = await scheduleFor(node.b.id, "for-b");
88
+ }, 60_000);
89
+ afterAll(() => { server?.stop?.(true); });
90
+
91
+ describe("PUT /api/nodes/:id/grants —— 谁能授", () => {
92
+ test("/health 报 node_grants", async () => {
93
+ const h = await (await fetch(`${base}/health`)).json() as any;
94
+ expect(h.capabilities).toContain("node_grants");
95
+ });
96
+ test("网络 owner 可授全网;GET 读回;[] 清空", async () => {
97
+ const r = await putGrants(user.boss.token, node.mgr.id, [{ capability: "schedules", scope_kind: "network", level: "read" }]);
98
+ expect(r.status).toBe(200);
99
+ expect(r.body.grants).toEqual([expect.objectContaining({ capability: "schedules", scope_kind: "network", scope_id: "", level: "read" })]);
100
+ expect((await call(user.own.token, "GET", `/api/nodes/${node.mgr.id}/grants`)).body.grants.length).toBe(1);
101
+ expect((await putGrants(user.boss.token, node.mgr.id, [])).body.grants).toEqual([]);
102
+ });
103
+ test("节点主人(普通成员)不能给自己的节点授权", async () => {
104
+ const r = await putGrants(user.own.token, node.mgr.id, [{ capability: "schedules", scope_kind: "network", level: "edit" }]);
105
+ expect(r.status).toBe(403);
106
+ });
107
+ test("部门负责人:授自己部门 OK,授全网 / 别的部门 403", async () => {
108
+ expect((await putGrants(user.lead.token, node.mgr.id, [{ capability: "schedules", scope_kind: "department", scope_id: deptA, level: "edit" }])).status).toBe(200);
109
+ expect((await putGrants(user.lead.token, node.mgr.id, [{ capability: "schedules", scope_kind: "network", level: "edit" }])).status).toBe(403);
110
+ expect((await putGrants(user.lead.token, node.mgr.id, [{ capability: "schedules", scope_kind: "department", scope_id: deptB, level: "edit" }])).status).toBe(403);
111
+ await putGrants(user.boss.token, node.mgr.id, []);
112
+ });
113
+ test("未知能力 400;board(第二期已开闸)200 且可读回;不存在的部门 404", async () => {
114
+ expect((await putGrants(user.boss.token, node.mgr.id, [{ capability: "nope", scope_kind: "network" }])).body.error).toBe("invalid_capability");
115
+ // 第二期:board 与 requirements 读写判定同批上线 ⇒ 写入不再被拒。
116
+ expect((await putGrants(user.boss.token, node.mgr.id, [{ capability: "board", scope_kind: "network", level: "read" }])).status).toBe(200);
117
+ const readBack = await call(user.boss.token, "GET", `/api/nodes/${node.mgr.id}/grants?network_id=${net}`);
118
+ expect((readBack.body.grants || []).some((g: any) => g.capability === "board" && g.level === "read")).toBe(true);
119
+ await putGrants(user.boss.token, node.mgr.id, []);
120
+ expect((await putGrants(user.boss.token, node.mgr.id, [{ capability: "schedules", scope_kind: "department", scope_id: "dept_missing" }])).status).toBe(404);
121
+ });
122
+
123
+ test("部门负责人只能授本部门的 board(跨部门 403)", async () => {
124
+ expect((await putGrants(user.lead.token, node.mgr.id, [{ capability: "board", scope_kind: "department", scope_id: deptA, level: "read" }])).status).toBe(200);
125
+ expect((await putGrants(user.lead.token, node.mgr.id, [{ capability: "board", scope_kind: "department", scope_id: deptB, level: "read" }])).status).toBe(403);
126
+ await putGrants(user.boss.token, node.mgr.id, []);
127
+ });
128
+ });
129
+
130
+ describe("定时任务 —— 授权让节点看得到 / 改得了", () => {
131
+ test("没授权:看不到别人的计划", async () => {
132
+ await putGrants(user.boss.token, node.mgr.id, []);
133
+ const ids = await listIds(node.mgr.token);
134
+ expect(ids).not.toContain(schedA);
135
+ expect((await mcp(node.mgr.token, "schedule_get", { schedule_id: schedA })).error).toBe("schedule_not_found");
136
+ });
137
+ test("network·read:看得到、改不了", async () => {
138
+ await putGrants(user.boss.token, node.mgr.id, [{ capability: "schedules", scope_kind: "network", level: "read" }]);
139
+ const ids = await listIds(node.mgr.token);
140
+ expect(ids).toContain(schedA); expect(ids).toContain(schedB);
141
+ expect((await mcp(node.mgr.token, "schedule_update", { schedule_id: schedA, name: "x" })).error).toBe("not_schedule_creator");
142
+ });
143
+ test("department(A)·edit:只覆盖目标在 A 的;能改能取消;审计一行", async () => {
144
+ await putGrants(user.boss.token, node.mgr.id, [{ capability: "schedules", scope_kind: "department", scope_id: deptA, level: "edit" }]);
145
+ const ids = await listIds(node.mgr.token);
146
+ expect(ids).toContain(schedA); expect(ids).not.toContain(schedB);
147
+ const upd = await mcp(node.mgr.token, "schedule_update", { schedule_id: schedA, name: "renamed by grant" });
148
+ expect(upd.ok).toBe(true);
149
+ expect(upd.schedule.name).toBe("renamed by grant");
150
+ expect((await mcp(node.mgr.token, "schedule_update", { schedule_id: schedB, name: "nope" })).error).toBe("schedule_not_found");
151
+ const audit = db.get<{ n: number | string }>("SELECT COUNT(*) AS n FROM audit_log WHERE action = 'schedule_changed_via_node_grant' AND target_id = ?1", schedA);
152
+ expect(Number(audit!.n)).toBeGreaterThanOrEqual(1);
153
+ });
154
+ test("只读模式的节点:edit 降为 read", async () => {
155
+ db.run("UPDATE nodes SET permission_mode = 'readonly' WHERE node_id = ?1", [node.mgr.id]);
156
+ try {
157
+ const r = await mcp(node.mgr.token, "schedule_update", { schedule_id: schedA, name: "should fail" });
158
+ expect(r.ok).toBe(false);
159
+ } finally {
160
+ db.run("UPDATE nodes SET permission_mode = 'normal' WHERE node_id = ?1", [node.mgr.id]);
161
+ }
162
+ });
163
+ test("撤销([])当场生效", async () => {
164
+ await putGrants(user.boss.token, node.mgr.id, []);
165
+ expect(await listIds(node.mgr.token)).not.toContain(schedA);
166
+ });
167
+ });
168
+
169
+ // ── 第二期:任务看板(board)───────────────────────────────────────────────
170
+ // 判「卡的负责人所在部门」,与定时任务按「目标节点所在部门」不是一回事。
171
+ // 卡:A 的负责人在 deptA(部门负责人 lead 本人),B 的负责人在 deptB(网络 owner boss)。
172
+ // 被授权的节点 mgr 的主人是 own(deptA),但它看不到别人的卡 —— 所以下面看到 A 一定是授权带来的。
173
+ describe("任务看板 —— 授权让节点看得到 / 改得了", () => {
174
+ let cardA = "", cardB = "";
175
+ const cardIds = async (token: string) => ((await mcp(token, "requirements_list", { network_id: net })).requirements ?? []).map((r: any) => r.id);
176
+
177
+ beforeAll(async () => {
178
+ // 🔴 必须在 enforce 下测:默认 "log" 时节点根本不做范围收窄(nodeTaskCaller 返回 null),
179
+ // 那样「授权后才看得到」和「撤销后看不到」都测不出来(无论有没有授权都看得见)。
180
+ process.env.COMMHUB_NODE_PERMISSIONS = "enforce";
181
+ const mk = async (name: string, ownerId: string) => {
182
+ const r = await mcp(user.boss.token, "requirements_create", { network_id: net, name, owner: { kind: "user", id: ownerId } });
183
+ const id = r.requirement?.id;
184
+ expect(typeof id).toBe("string");
185
+ return id as string;
186
+ };
187
+ cardA = await mk(`board A ${stamp}`, user.lead.id);
188
+ cardB = await mk(`board B ${stamp}`, user.boss.id);
189
+ });
190
+ afterAll(() => { delete process.env.COMMHUB_NODE_PERMISSIONS; });
191
+
192
+ test("没授权:别人的卡看不到,也改不了", async () => {
193
+ await putGrants(user.boss.token, node.mgr.id, []);
194
+ const ids = await cardIds(node.mgr.token);
195
+ expect(ids).not.toContain(cardA); expect(ids).not.toContain(cardB);
196
+ const upd = await mcp(node.mgr.token, "requirements_update", { network_id: net, id: cardA, description: "nope" });
197
+ expect(upd.ok).not.toBe(true);
198
+ });
199
+
200
+ test("department(A)·read:看得到 A、看不到 B;B 是 not_found;改不了", async () => {
201
+ await putGrants(user.boss.token, node.mgr.id, [{ capability: "board", scope_kind: "department", scope_id: deptA, level: "read" }]);
202
+ const ids = await cardIds(node.mgr.token);
203
+ expect(ids).toContain(cardA); expect(ids).not.toContain(cardB);
204
+ expect((await mcp(node.mgr.token, "requirements_get", { network_id: net, id: cardB })).error).toBe("requirement_not_found");
205
+ expect((await mcp(node.mgr.token, "requirements_update", { network_id: net, id: cardA, description: "read only" })).ok).not.toBe(true);
206
+ });
207
+
208
+ test("department(A)·edit:能改 A,审计 requirement_changed_via_node_grant;B 仍 not_found", async () => {
209
+ await putGrants(user.boss.token, node.mgr.id, [{ capability: "board", scope_kind: "department", scope_id: deptA, level: "edit" }]);
210
+ const upd = await mcp(node.mgr.token, "requirements_update", { network_id: net, id: cardA, description: "changed by grant" });
211
+ expect(upd.ok).toBe(true);
212
+ const audit = db.get<{ n: number | string }>("SELECT COUNT(*) AS n FROM audit_log WHERE action = 'requirement_changed_via_node_grant' AND target_id = ?1", cardA);
213
+ expect(Number(audit!.n)).toBeGreaterThanOrEqual(1);
214
+ expect((await mcp(node.mgr.token, "requirements_update", { network_id: net, id: cardB, description: "nope" })).error).toBe("requirement_not_found");
215
+ });
216
+
217
+ test("network·read:两张卡都能看到(不拼巨大 IN 列表)", async () => {
218
+ await putGrants(user.boss.token, node.mgr.id, [{ capability: "board", scope_kind: "network", level: "read" }]);
219
+ const ids = await cardIds(node.mgr.token);
220
+ expect(ids).toContain(cardA); expect(ids).toContain(cardB);
221
+ });
222
+
223
+ test("只读模式的节点:edit 降为 read,改不动", async () => {
224
+ await putGrants(user.boss.token, node.mgr.id, [{ capability: "board", scope_kind: "department", scope_id: deptA, level: "edit" }]);
225
+ db.run("UPDATE nodes SET permission_mode = 'readonly' WHERE node_id = ?1", [node.mgr.id]);
226
+ try {
227
+ expect((await mcp(node.mgr.token, "requirements_update", { network_id: net, id: cardA, description: "should fail" })).ok).not.toBe(true);
228
+ // 但看还是能看
229
+ expect(await cardIds(node.mgr.token)).toContain(cardA);
230
+ } finally {
231
+ db.run("UPDATE nodes SET permission_mode = 'normal' WHERE node_id = ?1", [node.mgr.id]);
232
+ }
233
+ });
234
+
235
+ test("撤销([])当场生效", async () => {
236
+ await putGrants(user.boss.token, node.mgr.id, []);
237
+ expect(await cardIds(node.mgr.token)).not.toContain(cardA);
238
+ });
239
+ });
@@ -0,0 +1,234 @@
1
+ // 节点管理授权(admin 2026-11-11「节点的权限要好好设计:某些节点可以有管理员权限去编辑定时任务、管表,
2
+ // 也可以只管某个部门下的」)。
3
+ //
4
+ // 模型 = 能力 × 范围 × 级别,按行存在 node_grants:
5
+ // capability schedules(第一期);board(第二期,随 requirements 读写判定一起上线)
6
+ // scope_kind network(整个网络,scope_id = "")| department(该部门及全部下级,scope_id = department_id)
7
+ // | node(单个节点,scope_id = node_id)
8
+ // level read(只看)| edit(看 + 改)
9
+ //
10
+ // 判定(只加不减):授权只**追加**节点能看 / 能改的东西,从不收回现有规则(节点自己建的 / 发给自己的计划照旧)。
11
+ // • 定时任务按**目标节点**判范围:network 全部;department 看目标节点 nodes.department_id 是否在该部门子树里;
12
+ // node 看 target_node_id。
13
+ // • 节点 permission_mode = readonly 时,edit 授权降为 read(只读节点永远不能改)。
14
+ // • 撤销 = 删行,下一次请求立即生效(不缓存)。
15
+ //
16
+ // 谁能授权(REST PUT /api/nodes/:id/grants):网络 owner / admin 与 Hub 管理员可授任意范围;
17
+ // 部门负责人只能授自己负责的子树里的 department / node 范围(不能授 network)。
18
+ import { db } from "./db.js";
19
+ import { departmentCardsFor, departmentSubtree, isDepartmentCard } from "./department-heads.js";
20
+
21
+ db.exec(`
22
+ CREATE TABLE IF NOT EXISTS node_grants (
23
+ network_id TEXT NOT NULL,
24
+ node_id TEXT NOT NULL,
25
+ capability TEXT NOT NULL,
26
+ scope_kind TEXT NOT NULL,
27
+ scope_id TEXT NOT NULL DEFAULT '',
28
+ level TEXT NOT NULL,
29
+ granted_by TEXT,
30
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
31
+ PRIMARY KEY (network_id, node_id, capability, scope_kind, scope_id)
32
+ );
33
+ CREATE INDEX IF NOT EXISTS idx_node_grants_node ON node_grants(node_id);
34
+ `);
35
+
36
+ export const GRANT_CAPABILITIES = ["schedules", "board"] as const;
37
+ // 第二期(board):能力与判定 + requirements 读写判定已在同一个 PR 里一起上 ⇒ 现在开闸。
38
+ export const GRANT_CAPABILITIES_PLANNED = [] as const;
39
+ export type GrantCapability = (typeof GRANT_CAPABILITIES)[number];
40
+ export type GrantScopeKind = "network" | "department" | "node";
41
+ export type GrantLevel = "read" | "edit";
42
+ export type NodeGrant = { capability: GrantCapability; scope_kind: GrantScopeKind; scope_id: string; level: GrantLevel };
43
+ export type StoredNodeGrant = NodeGrant & { granted_by: string | null; created_at: string };
44
+
45
+ export const MAX_GRANTS_PER_NODE = 50;
46
+
47
+ export function listNodeGrants(networkId: string, nodeId: string): StoredNodeGrant[] {
48
+ return db.all<StoredNodeGrant>(
49
+ "SELECT capability, scope_kind, scope_id, level, granted_by, created_at FROM node_grants WHERE network_id = ?1 AND node_id = ?2 ORDER BY capability, scope_kind, scope_id",
50
+ networkId, nodeId,
51
+ );
52
+ }
53
+
54
+ export type GrantValidation = { ok: true; grants: NodeGrant[] } | { ok: false; error: string; index?: number; message: string };
55
+
56
+ /** 解析 + 校验一整份授权名单(PUT 是整份替换)。部门 / 节点必须属于这个网络。 */
57
+ export function parseNodeGrants(networkId: string, raw: unknown): GrantValidation {
58
+ if (!Array.isArray(raw)) return { ok: false, error: "invalid_grants", message: "grants must be an array (use [] to clear)" };
59
+ if (raw.length > MAX_GRANTS_PER_NODE) return { ok: false, error: "too_many_grants", message: `at most ${MAX_GRANTS_PER_NODE} grants per node` };
60
+ const out: NodeGrant[] = [];
61
+ const seen = new Set<string>();
62
+ for (let i = 0; i < raw.length; i++) {
63
+ const g = raw[i] as Record<string, unknown> | null;
64
+ if (!g || typeof g !== "object") return { ok: false, error: "invalid_grant", index: i, message: "each grant is an object" };
65
+ const capability = g.capability;
66
+ if ((GRANT_CAPABILITIES_PLANNED as readonly unknown[]).includes(capability)) {
67
+ return { ok: false, error: "capability_not_supported", index: i, message: `capability ${String(capability)} is planned but not available on this Hub yet` };
68
+ }
69
+ if (!(GRANT_CAPABILITIES as readonly unknown[]).includes(capability)) return { ok: false, error: "invalid_capability", index: i, message: `capability must be one of ${GRANT_CAPABILITIES.join(", ")}` };
70
+ const kind = g.scope_kind;
71
+ if (kind !== "network" && kind !== "department" && kind !== "node") return { ok: false, error: "invalid_scope_kind", index: i, message: "scope_kind must be network, department or node" };
72
+ const scopeId = kind === "network" ? "" : typeof g.scope_id === "string" ? g.scope_id.trim() : "";
73
+ if (kind === "department" && !db.get("SELECT 1 AS ok FROM network_departments WHERE network_id = ?1 AND department_id = ?2", networkId, scopeId)) {
74
+ return { ok: false, error: "department_not_found", index: i, message: "scope_id must be a department of this network" };
75
+ }
76
+ if (kind === "node" && !db.get("SELECT 1 AS ok FROM nodes WHERE network_id = ?1 AND node_id = ?2", networkId, scopeId)) {
77
+ return { ok: false, error: "node_not_found", index: i, message: "scope_id must be a node of this network" };
78
+ }
79
+ const level = g.level ?? "edit";
80
+ if (level !== "read" && level !== "edit") return { ok: false, error: "invalid_level", index: i, message: "level must be read or edit" };
81
+ const key = `${capability}|${kind}|${scopeId}`;
82
+ if (seen.has(key)) continue;
83
+ seen.add(key);
84
+ out.push({ capability: capability as GrantCapability, scope_kind: kind, scope_id: scopeId, level });
85
+ }
86
+ return { ok: true, grants: out };
87
+ }
88
+
89
+ export function replaceNodeGrants(networkId: string, nodeId: string, grants: NodeGrant[], actorUserId: string | null): void {
90
+ db.transaction(() => {
91
+ db.run("DELETE FROM node_grants WHERE network_id = ?1 AND node_id = ?2", [networkId, nodeId]);
92
+ for (const g of grants) {
93
+ db.run(
94
+ "INSERT INTO node_grants (network_id, node_id, capability, scope_kind, scope_id, level, granted_by) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
95
+ [networkId, nodeId, g.capability, g.scope_kind, g.scope_id, g.level, actorUserId],
96
+ );
97
+ }
98
+ });
99
+ }
100
+
101
+ export function deleteNodeGrants(nodeId: string): void {
102
+ db.run("DELETE FROM node_grants WHERE node_id = ?1 OR (scope_kind = 'node' AND scope_id = ?1)", [nodeId]);
103
+ }
104
+
105
+ /** 部门负责人能授的:只能是自己负责子树里的 department / node 范围。 */
106
+ export function grantsWithinManaged(networkId: string, grants: NodeGrant[], managed: ReadonlySet<string>): boolean {
107
+ for (const g of grants) {
108
+ if (g.scope_kind === "network") return false;
109
+ if (g.scope_kind === "department" && !managed.has(g.scope_id)) return false;
110
+ if (g.scope_kind === "node") {
111
+ const dept = db.get<{ department_id: string | null }>("SELECT department_id FROM nodes WHERE network_id = ?1 AND node_id = ?2", networkId, g.scope_id)?.department_id;
112
+ if (!dept || !managed.has(dept)) return false;
113
+ }
114
+ }
115
+ return true;
116
+ }
117
+
118
+ /**
119
+ * 这个节点对「目标节点」的某个能力有什么级别:edit / read / null(没有授权)。
120
+ * readonly 模式的节点 edit 降为 read。
121
+ */
122
+ export function grantLevelForTarget(
123
+ networkId: string, nodeId: string, capability: GrantCapability, targetNodeId: string | null, mode?: string | null,
124
+ ): GrantLevel | null {
125
+ const rows = db.all<{ scope_kind: GrantScopeKind; scope_id: string; level: GrantLevel }>(
126
+ "SELECT scope_kind, scope_id, level FROM node_grants WHERE network_id = ?1 AND node_id = ?2 AND capability = ?3",
127
+ networkId, nodeId, capability,
128
+ );
129
+ if (!rows.length) return null;
130
+ let targetDept: string | null | undefined;
131
+ let best: GrantLevel | null = null;
132
+ for (const r of rows) {
133
+ let hit = false;
134
+ if (r.scope_kind === "network") hit = true;
135
+ else if (r.scope_kind === "node") hit = !!targetNodeId && r.scope_id === targetNodeId;
136
+ else if (r.scope_kind === "department" && targetNodeId) {
137
+ if (targetDept === undefined) {
138
+ targetDept = db.get<{ department_id: string | null }>("SELECT department_id FROM nodes WHERE network_id = ?1 AND node_id = ?2", networkId, targetNodeId)?.department_id ?? null;
139
+ }
140
+ hit = !!targetDept && departmentSubtree(networkId, r.scope_id).has(targetDept);
141
+ }
142
+ if (hit) { best = r.level === "edit" ? "edit" : best ?? "read"; if (best === "edit") break; }
143
+ }
144
+ if (best === "edit" && mode === "readonly") return "read";
145
+ return best;
146
+ }
147
+
148
+ /** 这个节点有没有任何该能力的授权(列表时决定要不要扫全网的计划)。 */
149
+ export function hasAnyGrant(networkId: string, nodeId: string, capability: GrantCapability): boolean {
150
+ return !!db.get("SELECT 1 AS ok FROM node_grants WHERE network_id = ?1 AND node_id = ?2 AND capability = ?3 LIMIT 1", networkId, nodeId, capability);
151
+ }
152
+
153
+ // ── 第二期:任务看板(board)─────────────────────────────────────────────
154
+ //
155
+ // 与 schedules 的口径**不同**,别混:
156
+ // · schedules 按「目标节点所在部门」判(计划后面挂着一个目标节点)
157
+ // · board 按「**卡的负责人所在部门**」判 —— 卡没有目标节点
158
+ //
159
+ // 部门口径**必须**和部门负责人(RFC-040)完全一致,所以这里直接复用
160
+ // `isDepartmentCard(departmentCardsFor(net, departmentSubtree(net, scope_id)), row)`,
161
+ // 不自己解析 owner_json —— 那边判的是「agent 的主人是否在部门成员里」(nodesOwnedBy),
162
+ // 而不是「agent 节点自己的 department_id」;两套写法会判出不同结果。
163
+ export type BoardCardRef = {
164
+ owner_json: string | null;
165
+ agent_owner_json?: string | null;
166
+ };
167
+
168
+ /** 卡的 agent_owner 节点 id(只有 node 范围需要它)。 */
169
+ function agentOwnerNodeId(row: BoardCardRef): string | null {
170
+ if (!row.agent_owner_json) return null;
171
+ try {
172
+ const ref = JSON.parse(row.agent_owner_json) as { kind?: unknown; id?: unknown };
173
+ return ref && ref.kind === "node" && typeof ref.id === "string" ? ref.id : null;
174
+ } catch {
175
+ return null;
176
+ }
177
+ }
178
+
179
+ /** 这个节点对这张卡有没有 board 授权,以及级别。readonly 模式下 edit 降为 read。 */
180
+ export function boardGrantForCard(
181
+ networkId: string, nodeId: string, row: BoardCardRef, mode?: string | null,
182
+ ): "edit" | "read" | null {
183
+ const grants = db.all<{ scope_kind: GrantScopeKind; scope_id: string; level: GrantLevel }>(
184
+ "SELECT scope_kind, scope_id, level FROM node_grants WHERE network_id = ?1 AND node_id = ?2 AND capability = 'board'",
185
+ networkId, nodeId,
186
+ );
187
+ if (!grants.length) return null;
188
+ const agentNode = agentOwnerNodeId(row);
189
+ const deptScopes = new Map<string, ReturnType<typeof departmentCardsFor>>();
190
+ let best: GrantLevel | null = null;
191
+ for (const g of grants) {
192
+ let hit = false;
193
+ if (g.scope_kind === "network") hit = true;
194
+ else if (g.scope_kind === "node") hit = !!agentNode && g.scope_id === agentNode;
195
+ else if (g.scope_kind === "department") {
196
+ let cards = deptScopes.get(g.scope_id);
197
+ if (!cards) {
198
+ cards = departmentCardsFor(networkId, departmentSubtree(networkId, g.scope_id));
199
+ deptScopes.set(g.scope_id, cards);
200
+ }
201
+ hit = isDepartmentCard(cards, row);
202
+ }
203
+ if (!hit) continue;
204
+ if (g.level === "edit") { best = "edit"; break; }
205
+ best = best ?? "read";
206
+ }
207
+ if (best === "edit" && mode === "readonly") return "read";
208
+ return best;
209
+ }
210
+
211
+ /**
212
+ * 读侧的范围(给 requirements 可见性用):这个节点的 board 授权能覆盖到哪些卡。
213
+ * 返回 null = 没有任何 board 授权(调用方必须**逐字节不变**地走原 SQL)。
214
+ * network 范围用 `network: true` 表示,而不是拼一个巨大的 IN 列表。
215
+ */
216
+ export type BoardScope = { network: boolean; users: Set<string>; nodes: Set<string> };
217
+
218
+ export function boardScopeForNode(networkId: string, nodeId: string): BoardScope | null {
219
+ const grants = db.all<{ scope_kind: GrantScopeKind; scope_id: string }>(
220
+ "SELECT scope_kind, scope_id FROM node_grants WHERE network_id = ?1 AND node_id = ?2 AND capability = 'board'",
221
+ networkId, nodeId,
222
+ );
223
+ if (!grants.length) return null;
224
+ const users = new Set<string>();
225
+ const nodes = new Set<string>();
226
+ for (const g of grants) {
227
+ if (g.scope_kind === "network") return { network: true, users, nodes };
228
+ if (g.scope_kind === "node") { nodes.add(g.scope_id); continue; }
229
+ const cards = departmentCardsFor(networkId, departmentSubtree(networkId, g.scope_id));
230
+ for (const u of cards.users) users.add(u);
231
+ for (const n of cards.nodes) nodes.add(n);
232
+ }
233
+ return { network: false, users, nodes };
234
+ }