@sleep2agi/commhub-server 0.9.0-preview.264 → 0.9.0-preview.266
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/agent-access.ts +100 -2
- package/src/agent-department-grants.test.ts +129 -0
- package/src/db.ts +16 -0
- package/src/node-secret-vault-inject.test.ts +132 -0
- package/src/scoped-secrets.ts +28 -2
- package/src/server.ts +10 -3
- package/src/tools.ts +2 -2
package/build-info.json
CHANGED
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.266",
|
|
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",
|
package/src/agent-access.ts
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
// 成员资格仍由调用方原有的 getUserNetworkRole 判定。两件事分开,别合并成一个判据。
|
|
12
12
|
|
|
13
13
|
import { db } from "./db.js";
|
|
14
|
+
import { departmentSubtree } from "./department-heads.js";
|
|
14
15
|
|
|
15
16
|
const UNRESTRICTED_ROLES = new Set(["owner", "admin"]);
|
|
16
17
|
|
|
@@ -98,7 +99,7 @@ export function visibleAgents(userId: string, networkId: string): VisibleAgents
|
|
|
98
99
|
const messageNodeIds = new Set<string>();
|
|
99
100
|
// RFC-038 §8:组授权展开成「该组此刻的成员节点」—— 每次现算,组里新加的节点下一次请求就可见。
|
|
100
101
|
// 只并同网络、且 nodes 表里还在的节点;可对话取并集(直接授权或任一组给了就算)。
|
|
101
|
-
const grants: AgentGrant[] = [...listAgentGrants(networkId, userId), ...groupGrantNodes(networkId, userId)];
|
|
102
|
+
const grants: AgentGrant[] = [...listAgentGrants(networkId, userId), ...groupGrantNodes(networkId, userId), ...departmentGrantNodes(networkId, userId)];
|
|
102
103
|
// #2133:所有授权节点的 alias 一次查完(原来每个节点单独查一次 nodes ∪ sessions:300 条授权 ≈ 300 次查询,
|
|
103
104
|
// 而受限成员的每次 /api/status 轮询都走这里)。结果与原实现逐字一致:授权按上面数组的顺序,
|
|
104
105
|
// 同一节点内的 alias 按 UNION 的去重升序 —— agent-access-batch.test.ts 在随机夹具上逐字比对。
|
|
@@ -168,6 +169,68 @@ export function listGroupGrants(networkId: string, userId: string): AgentGroupGr
|
|
|
168
169
|
).map((row) => ({ group_id: row.group_id, name: row.name, can_message: row.can_message === 1 }));
|
|
169
170
|
}
|
|
170
171
|
|
|
172
|
+
// ══════════════ 部门维度授权(admin 2026-11-05) ══════════════
|
|
173
|
+
//
|
|
174
|
+
// 用户问的是「给某个用户授权,让他看到**某个组织架构下**的所有节点」。
|
|
175
|
+
// Agent 组授权(RFC-038 §8)回答的是 Agent 侧的树;人的组织架构是另一条轴
|
|
176
|
+
// (network_departments + nodes.department_id),此前**没有**这一档。
|
|
177
|
+
//
|
|
178
|
+
// 语义与组授权完全同构,只有展开源不同:
|
|
179
|
+
// 组 ⇒ agent_group_members
|
|
180
|
+
// 部门 ⇒ departmentSubtree(dept) 里的所有部门 → nodes.department_id ∈ 该集合
|
|
181
|
+
// 同样是**每次现算**:部门里新挂的节点,下一次请求就可见,不需要重新授权。
|
|
182
|
+
//
|
|
183
|
+
// 已知边界(必须让调用方看见,否则会静默少人):
|
|
184
|
+
// 没有填 department_id 的节点**永远**不会因为部门授权而可见。
|
|
185
|
+
// ⇒ 接口把它作为 `coverage` 一起返回,而不是让人以为「授权了就应该全看见」。
|
|
186
|
+
|
|
187
|
+
export type DepartmentGrant = { department_id: string; name: string; can_message: boolean };
|
|
188
|
+
|
|
189
|
+
export function departmentGrantNodes(networkId: string, userId: string): AgentGrant[] {
|
|
190
|
+
const rows = db.all<{ department_id: string; can_message: number }>(
|
|
191
|
+
"SELECT department_id, can_message FROM network_member_department_grants WHERE network_id = ?1 AND user_id = ?2",
|
|
192
|
+
networkId, userId,
|
|
193
|
+
);
|
|
194
|
+
if (rows.length === 0) return [];
|
|
195
|
+
const canMessage = new Map<string, boolean>();
|
|
196
|
+
for (const row of rows) {
|
|
197
|
+
for (const deptId of departmentSubtree(networkId, row.department_id)) {
|
|
198
|
+
// 任一授权允许对话即允许(与组授权「取并集」一致)。
|
|
199
|
+
canMessage.set(deptId, (canMessage.get(deptId) ?? false) || row.can_message === 1);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
if (canMessage.size === 0) return [];
|
|
203
|
+
const deptIds = [...canMessage.keys()];
|
|
204
|
+
const inList = deptIds.map((_, i) => `?${i + 2}`).join(", ");
|
|
205
|
+
return db.all<{ node_id: string; department_id: string }>(
|
|
206
|
+
`SELECT node_id, department_id FROM nodes WHERE network_id = ?1 AND department_id IN (${inList}) ORDER BY node_id`,
|
|
207
|
+
networkId, ...deptIds,
|
|
208
|
+
).map((row) => ({ node_id: row.node_id, alias: null, can_message: canMessage.get(row.department_id) === true }));
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export function listDepartmentGrants(networkId: string, userId: string): DepartmentGrant[] {
|
|
212
|
+
return db.all<{ department_id: string; name: string | null; can_message: number }>(
|
|
213
|
+
`SELECT g.department_id, d.name, g.can_message
|
|
214
|
+
FROM network_member_department_grants g
|
|
215
|
+
LEFT JOIN network_departments d ON d.department_id = g.department_id AND d.network_id = g.network_id
|
|
216
|
+
WHERE g.network_id = ?1 AND g.user_id = ?2 ORDER BY d.name, g.department_id`,
|
|
217
|
+
networkId, userId,
|
|
218
|
+
).map((row) => ({ department_id: row.department_id, name: row.name ?? row.department_id, can_message: row.can_message === 1 }));
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** 覆盖率:网络里有多少节点填了部门、有多少没填(没填的永远不可能被部门授权覆盖)。 */
|
|
222
|
+
export function departmentCoverage(networkId: string): { nodes_total: number; nodes_with_department: number; nodes_without_department: number } {
|
|
223
|
+
const row = db.get<{ total: number; with_dept: number }>(
|
|
224
|
+
`SELECT COUNT(*) AS total,
|
|
225
|
+
SUM(CASE WHEN department_id IS NOT NULL AND department_id <> '' THEN 1 ELSE 0 END) AS with_dept
|
|
226
|
+
FROM nodes WHERE network_id = ?1`,
|
|
227
|
+
networkId,
|
|
228
|
+
);
|
|
229
|
+
const total = row?.total ?? 0;
|
|
230
|
+
const withDept = row?.with_dept ?? 0;
|
|
231
|
+
return { nodes_total: total, nodes_with_department: withDept, nodes_without_department: total - withDept };
|
|
232
|
+
}
|
|
233
|
+
|
|
171
234
|
export function listAgentGroups(networkId: string): AgentGroup[] {
|
|
172
235
|
const groups = db.all<{ group_id: string; network_id: string; name: string; description: string | null; created_at: string; updated_at: string | null }>(
|
|
173
236
|
"SELECT group_id, network_id, name, description, created_at, updated_at FROM agent_groups WHERE network_id = ?1 ORDER BY name",
|
|
@@ -331,7 +394,7 @@ export function canMessageAgent(userId: string, networkId: string | null | undef
|
|
|
331
394
|
export type AgentGrantInput = { node_id?: unknown; alias?: unknown; can_message?: unknown };
|
|
332
395
|
|
|
333
396
|
export type ReplaceGrantsResult =
|
|
334
|
-
| { ok: true; agent_access: AgentAccessMode; grants: AgentGrant[]; group_grants: AgentGroupGrant[] }
|
|
397
|
+
| { ok: true; agent_access: AgentAccessMode; grants: AgentGrant[]; group_grants: AgentGroupGrant[]; department_grants: DepartmentGrant[] }
|
|
335
398
|
| { ok: false; error: string; status: number; detail?: unknown };
|
|
336
399
|
|
|
337
400
|
const MAX_GRANTS = 1000;
|
|
@@ -347,6 +410,8 @@ export function replaceAgentGrants(input: {
|
|
|
347
410
|
agentAccess?: unknown;
|
|
348
411
|
/** RFC-038 §8:组授权。undefined = 保持原样(旧 app 的 PUT 不带它,不能把组授权清掉)。 */
|
|
349
412
|
groupGrants?: unknown;
|
|
413
|
+
/** 部门维度授权。undefined = 保持原样(旧客户端的 PUT 不带它,不能把部门授权清掉)。 */
|
|
414
|
+
departmentGrants?: unknown;
|
|
350
415
|
actorUserId: string;
|
|
351
416
|
}): ReplaceGrantsResult {
|
|
352
417
|
const member = db.get<{ role: string }>(
|
|
@@ -415,7 +480,38 @@ export function replaceAgentGrants(input: {
|
|
|
415
480
|
}
|
|
416
481
|
}
|
|
417
482
|
|
|
483
|
+
let departmentRows: Array<{ department_id: string; can_message: number }> | undefined;
|
|
484
|
+
if (input.departmentGrants !== undefined) {
|
|
485
|
+
if (!Array.isArray(input.departmentGrants)) return { ok: false, error: "department_grants_must_be_array", status: 400 };
|
|
486
|
+
if (input.departmentGrants.length > MAX_GRANTS) return { ok: false, error: "too_many_grants", status: 400, detail: { limit: MAX_GRANTS } };
|
|
487
|
+
const seenDepts = new Set<string>();
|
|
488
|
+
departmentRows = [];
|
|
489
|
+
for (const [index, raw] of input.departmentGrants.entries()) {
|
|
490
|
+
const item = typeof raw === "string" ? { department_id: raw } : (raw && typeof raw === "object" && !Array.isArray(raw) ? raw as { department_id?: unknown; can_message?: unknown } : {});
|
|
491
|
+
const deptId = typeof item.department_id === "string" ? item.department_id.trim() : "";
|
|
492
|
+
if (!deptId) return { ok: false, error: "department_grant_needs_department_id", status: 400, detail: { index } };
|
|
493
|
+
if (item.can_message !== undefined && typeof item.can_message !== "boolean") {
|
|
494
|
+
return { ok: false, error: "can_message_must_be_boolean", status: 400, detail: { index } };
|
|
495
|
+
}
|
|
496
|
+
if (!db.get("SELECT 1 FROM network_departments WHERE department_id = ?1 AND network_id = ?2", deptId, input.networkId)) {
|
|
497
|
+
return { ok: false, error: "department_not_in_network", status: 400, detail: { index, department_id: deptId } };
|
|
498
|
+
}
|
|
499
|
+
if (seenDepts.has(deptId)) continue;
|
|
500
|
+
seenDepts.add(deptId);
|
|
501
|
+
departmentRows.push({ department_id: deptId, can_message: item.can_message === false ? 0 : 1 });
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
|
|
418
505
|
db.transaction(() => {
|
|
506
|
+
if (departmentRows) {
|
|
507
|
+
db.run("DELETE FROM network_member_department_grants WHERE network_id = ?1 AND user_id = ?2", [input.networkId, input.userId]);
|
|
508
|
+
for (const row of departmentRows) {
|
|
509
|
+
db.run(
|
|
510
|
+
`INSERT INTO network_member_department_grants (network_id, user_id, department_id, can_message, created_by) VALUES (?1, ?2, ?3, ?4, ?5)`,
|
|
511
|
+
[input.networkId, input.userId, row.department_id, row.can_message, input.actorUserId],
|
|
512
|
+
);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
419
515
|
if (groupRows) {
|
|
420
516
|
db.run("DELETE FROM network_member_group_grants WHERE network_id = ?1 AND user_id = ?2", [input.networkId, input.userId]);
|
|
421
517
|
for (const row of groupRows) {
|
|
@@ -445,6 +541,7 @@ export function replaceAgentGrants(input: {
|
|
|
445
541
|
agent_access: getAgentAccessMode(input.networkId, input.userId) ?? "granted",
|
|
446
542
|
grants: listAgentGrants(input.networkId, input.userId),
|
|
447
543
|
group_grants: listGroupGrants(input.networkId, input.userId),
|
|
544
|
+
department_grants: listDepartmentGrants(input.networkId, input.userId),
|
|
448
545
|
};
|
|
449
546
|
}
|
|
450
547
|
|
|
@@ -452,6 +549,7 @@ export function replaceAgentGrants(input: {
|
|
|
452
549
|
export function deleteAgentGrants(networkId: string, userId: string): void {
|
|
453
550
|
db.run("DELETE FROM network_member_agent_grants WHERE network_id = ?1 AND user_id = ?2", [networkId, userId]);
|
|
454
551
|
db.run("DELETE FROM network_member_group_grants WHERE network_id = ?1 AND user_id = ?2", [networkId, userId]);
|
|
552
|
+
db.run("DELETE FROM network_member_department_grants WHERE network_id = ?1 AND user_id = ?2", [networkId, userId]);
|
|
455
553
|
}
|
|
456
554
|
|
|
457
555
|
// 多用户 Agent 权限 —— 受限成员(只看授权 Agent 的成员)能调的 MCP 工具。每一个都逐条审过:
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// #3432 —— 部门维度授权:把「人的组织架构」当授权单位。
|
|
2
|
+
//
|
|
3
|
+
// 用户问的是「给某个用户授权,让他看到某个组织架构下的所有节点」。
|
|
4
|
+
// 此前只有三档:all / 逐 Agent / Agent 组 —— 前两档都不回答这个问题,
|
|
5
|
+
// 第三档是 **Agent 侧**的树,而人的组织架构是另一条轴(network_departments + nodes.department_id)。
|
|
6
|
+
//
|
|
7
|
+
// 判据分两半,缺一半就只是「能写进去」:
|
|
8
|
+
// ① 能看到:授权部门 D ⇒ D 与全部下级部门里的节点可见(含下级,这才是「组织架构下」)
|
|
9
|
+
// ② 不该看到的看不到:没填部门的节点、别的部门的节点,都不出现(镜像否定)
|
|
10
|
+
import './require-explicit-test-db';
|
|
11
|
+
// network_departments 是在 departments.ts 的模块顶层建的(不是 db.ts)。
|
|
12
|
+
// 不把这个 import 放进来,测试会直接报 no such table —— 而生产是因为 server.ts 导入了它。
|
|
13
|
+
import './departments';
|
|
14
|
+
import { afterAll, beforeEach, describe, expect, test } from 'bun:test';
|
|
15
|
+
import { db } from './db';
|
|
16
|
+
import {
|
|
17
|
+
departmentGrantNodes,
|
|
18
|
+
visibleAgents,
|
|
19
|
+
replaceAgentGrants,
|
|
20
|
+
listDepartmentGrants,
|
|
21
|
+
departmentCoverage,
|
|
22
|
+
} from './agent-access';
|
|
23
|
+
|
|
24
|
+
const net = 'net_deptgrant';
|
|
25
|
+
const user = 'u_deptgrant';
|
|
26
|
+
const actor = 'u_deptgrant_actor';
|
|
27
|
+
const root = 'd_root';
|
|
28
|
+
const child = 'd_child';
|
|
29
|
+
const other = 'd_other';
|
|
30
|
+
|
|
31
|
+
function cleanup() {
|
|
32
|
+
for (const t of ['network_member_agent_grants', 'network_member_group_grants', 'network_member_department_grants']) {
|
|
33
|
+
try { db.run(`DELETE FROM ${t} WHERE network_id = ?1`, [net]); } catch {}
|
|
34
|
+
}
|
|
35
|
+
db.run('DELETE FROM nodes WHERE network_id = ?1', [net]);
|
|
36
|
+
db.run('DELETE FROM network_departments WHERE network_id = ?1', [net]);
|
|
37
|
+
db.run('DELETE FROM network_members WHERE network_id = ?1', [net]);
|
|
38
|
+
db.run('DELETE FROM networks WHERE network_id = ?1', [net]);
|
|
39
|
+
db.run('DELETE FROM users WHERE user_id IN (?1, ?2)', [user, actor]);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
beforeEach(() => {
|
|
43
|
+
cleanup();
|
|
44
|
+
db.run("INSERT INTO users(user_id,username,password_hash,role) VALUES(?1,?1,'x','user')", [user]);
|
|
45
|
+
db.run("INSERT INTO users(user_id,username,password_hash,role) VALUES(?1,?1,'x','user')", [actor]);
|
|
46
|
+
db.run('INSERT INTO networks(network_id,network_name,owner_id) VALUES(?1,?1,?2)', [net, actor]);
|
|
47
|
+
db.run("INSERT INTO network_members(user_id,network_id,role,agent_access) VALUES(?1,?2,'member','granted')", [user, net]);
|
|
48
|
+
db.run("INSERT INTO network_members(user_id,network_id,role,agent_access) VALUES(?1,?2,'owner','all')", [actor, net]);
|
|
49
|
+
// 三棵子树:root(父) → child(子);另一棵 other。
|
|
50
|
+
for (const [id, parent] of [[root, null], [child, root], [other, null]] as const) {
|
|
51
|
+
db.run('INSERT INTO network_departments(network_id,department_id,name,parent_id) VALUES(?1,?2,?2,?3)', [net, id, parent]);
|
|
52
|
+
}
|
|
53
|
+
const node = (id: string, dept: string | null) => db.run(
|
|
54
|
+
'INSERT INTO nodes(node_id,node_name,alias,network_id,department_id) VALUES(?1,?1,?1,?2,?3)', [id, net, dept]);
|
|
55
|
+
node('n_root_direct', root);
|
|
56
|
+
node('n_child_member', child); // 下级部门里的节点
|
|
57
|
+
node('n_other_dept', other);
|
|
58
|
+
node('n_no_dept', null); // 没填部门:永远不该因部门授权而可见
|
|
59
|
+
});
|
|
60
|
+
afterAll(cleanup);
|
|
61
|
+
|
|
62
|
+
const grantDept = (deptId: string, canMessage = true) => replaceAgentGrants({
|
|
63
|
+
networkId: net, userId: user, grants: [], actorUserId: actor,
|
|
64
|
+
departmentGrants: [{ department_id: deptId, can_message: canMessage }],
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
describe("#3432 部门维度授权", () => {
|
|
68
|
+
test("① 授权部门 root ⇒ root 自己与**下级** child 里的节点都可见", () => {
|
|
69
|
+
const r = grantDept(root);
|
|
70
|
+
expect(r.ok).toBe(true);
|
|
71
|
+
const ids = departmentGrantNodes(net, user).map((g) => g.node_id).sort();
|
|
72
|
+
expect(ids).toEqual(['n_child_member', 'n_root_direct']);
|
|
73
|
+
const visible = visibleAgents(user, net);
|
|
74
|
+
expect(visible.nodeIds.sort()).toEqual(['n_child_member', 'n_root_direct']);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
test("② 镜像否定:没填部门的节点、别的部门的节点都不出现", () => {
|
|
78
|
+
grantDept(root);
|
|
79
|
+
const ids = departmentGrantNodes(net, user).map((g) => g.node_id);
|
|
80
|
+
expect(ids).not.toContain('n_no_dept');
|
|
81
|
+
expect(ids).not.toContain('n_other_dept');
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
test("can_message 随部门授权传递;一处 false 不影响另一处 true(取并集)", () => {
|
|
85
|
+
replaceAgentGrants({
|
|
86
|
+
networkId: net, userId: user, grants: [], actorUserId: actor,
|
|
87
|
+
departmentGrants: [{ department_id: root, can_message: false }, { department_id: other, can_message: true }],
|
|
88
|
+
});
|
|
89
|
+
const byId = new Map(departmentGrantNodes(net, user).map((g) => [g.node_id, g.can_message]));
|
|
90
|
+
expect(byId.get('n_root_direct')).toBe(false);
|
|
91
|
+
expect(byId.get('n_other_dept')).toBe(true);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
test("撤掉授权 ⇒ 立刻看不见(现算,不留缓存)", () => {
|
|
95
|
+
grantDept(root);
|
|
96
|
+
expect(departmentGrantNodes(net, user).length).toBe(2);
|
|
97
|
+
grantDept('') /* 非法,整批拒绝 */;
|
|
98
|
+
replaceAgentGrants({ networkId: net, userId: user, grants: [], actorUserId: actor, departmentGrants: [] });
|
|
99
|
+
expect(departmentGrantNodes(net, user)).toEqual([]);
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
test("部门里新挂的节点,下一次请求就可见(与组授权同一语义)", () => {
|
|
103
|
+
grantDept(root);
|
|
104
|
+
db.run('INSERT INTO nodes(node_id,node_name,alias,network_id,department_id) VALUES(?1,?1,?1,?2,?3)',
|
|
105
|
+
['n_new_in_child', net, child]);
|
|
106
|
+
expect(departmentGrantNodes(net, user).map((g) => g.node_id)).toContain('n_new_in_child');
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
test("不在本网络的部门 ⇒ department_not_in_network(不静默忽略)", () => {
|
|
110
|
+
const r = replaceAgentGrants({
|
|
111
|
+
networkId: net, userId: user, grants: [], actorUserId: actor,
|
|
112
|
+
departmentGrants: [{ department_id: 'd_does_not_exist' }],
|
|
113
|
+
});
|
|
114
|
+
expect(r.ok).toBe(false);
|
|
115
|
+
if (!r.ok) expect(r.error).toBe('department_not_in_network');
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
test("listDepartmentGrants 带出部门名;coverage 把「没填部门」明说出来", () => {
|
|
119
|
+
grantDept(root);
|
|
120
|
+
expect(listDepartmentGrants(net, user)).toEqual([{ department_id: root, name: root, can_message: true }]);
|
|
121
|
+
expect(departmentCoverage(net)).toEqual({ nodes_total: 4, nodes_with_department: 3, nodes_without_department: 1 });
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
test("传 undefined 时不清空已有部门授权(旧客户端的 PUT 不带这个键)", () => {
|
|
125
|
+
grantDept(root);
|
|
126
|
+
replaceAgentGrants({ networkId: net, userId: user, grants: [], actorUserId: actor });
|
|
127
|
+
expect(listDepartmentGrants(net, user).length).toBe(1);
|
|
128
|
+
});
|
|
129
|
+
});
|
package/src/db.ts
CHANGED
|
@@ -1219,6 +1219,22 @@ db.exec(`
|
|
|
1219
1219
|
-- 展开查询本身走各表主键,见 agent-groups-perf.test.ts 的 EXPLAIN QUERY PLAN。
|
|
1220
1220
|
CREATE INDEX IF NOT EXISTS idx_group_grants_group ON network_member_group_grants(group_id);
|
|
1221
1221
|
`);
|
|
1222
|
+
// ── #3432(admin 2026-11-05) 部门维度授权:把「人的组织架构」当成授权单位 ──
|
|
1223
|
+
// 与组授权同构(每次现算展开),差别只在展开源是 departments 子树 + nodes.department_id。
|
|
1224
|
+
// 单独一张表:组那张表的主键/语义都是 Agent 侧的,部门是人的树,混在一张表里以后分不清。
|
|
1225
|
+
db.exec(`
|
|
1226
|
+
CREATE TABLE IF NOT EXISTS network_member_department_grants (
|
|
1227
|
+
network_id TEXT NOT NULL,
|
|
1228
|
+
user_id TEXT NOT NULL,
|
|
1229
|
+
department_id TEXT NOT NULL,
|
|
1230
|
+
can_message INTEGER NOT NULL DEFAULT 1,
|
|
1231
|
+
created_by TEXT,
|
|
1232
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1233
|
+
PRIMARY KEY (network_id, user_id, department_id)
|
|
1234
|
+
);
|
|
1235
|
+
CREATE INDEX IF NOT EXISTS idx_dept_grants_user ON network_member_department_grants(network_id, user_id);
|
|
1236
|
+
`);
|
|
1237
|
+
|
|
1222
1238
|
|
|
1223
1239
|
// ── #84: node rename — rename_txn table (RFC-010 §4) ──
|
|
1224
1240
|
// Single isolated table holding the rename 2PC transaction state. It doubles
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// #3148 —— 保险库的值要能**流向**真正要用的那个进程,但任何人仍然**读不出来**。
|
|
2
|
+
//
|
|
3
|
+
// admin 2026-11-01 在客户端里撞到的死结:
|
|
4
|
+
// 密钥已经在保险库里了,可没有任何路径把它送到目标节点;
|
|
5
|
+
// 于是人只能把明文再复制一遍,或者写进工作区文件 —— 两条都比保险库更差。
|
|
6
|
+
//
|
|
7
|
+
// 本文件的判据分两半,缺一半就只是「加了个功能」:
|
|
8
|
+
// ① 流向成立:owner/admin 只给键名,节点真的收到值(用节点侧 pull 来验,不靠内部字段)
|
|
9
|
+
// ② 读权不成立:任何读接口都不回值(getScopedSecrets / ack 回来的 snapshot / 响应体本身)
|
|
10
|
+
import './require-explicit-test-db';
|
|
11
|
+
import { afterAll, beforeEach, describe, expect, test } from 'bun:test';
|
|
12
|
+
import { db } from './db';
|
|
13
|
+
import { getScopedSecrets, pullNodeSecrets, ackNodeSecrets, requestNodeSecrets } from './scoped-secrets';
|
|
14
|
+
import { vaultUpsert, vaultListKeys, vaultDelete } from './vault';
|
|
15
|
+
|
|
16
|
+
const net = 'net_vaultinject';
|
|
17
|
+
const baseNode = 'n_vaultinject';
|
|
18
|
+
let node = baseNode;
|
|
19
|
+
const owner = 'u_vaultinject_owner';
|
|
20
|
+
const member = 'u_vaultinject_member';
|
|
21
|
+
const KEY = 'TMPAT';
|
|
22
|
+
const VALUE = 'pat-value-that-must-never-be-readable-0123456789';
|
|
23
|
+
|
|
24
|
+
function cleanup() {
|
|
25
|
+
db.run('DELETE FROM nodes WHERE network_id=?1', [net]);
|
|
26
|
+
db.run('DELETE FROM network_members WHERE network_id=?1', [net]);
|
|
27
|
+
db.run('DELETE FROM networks WHERE network_id=?1', [net]);
|
|
28
|
+
db.run('DELETE FROM users WHERE user_id IN (?1, ?2)', [owner, member]);
|
|
29
|
+
for (const k of vaultListKeys(net)) vaultDelete(net, k);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function makeNode(name: string) {
|
|
33
|
+
node = name;
|
|
34
|
+
db.run('INSERT INTO nodes(node_id,node_name,alias,network_id,config_snapshot) VALUES(?1,?1,?1,?2,?3)',
|
|
35
|
+
[node, net, JSON.stringify({ node_secrets_capable: true })]);
|
|
36
|
+
return node;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
beforeEach(() => {
|
|
40
|
+
cleanup();
|
|
41
|
+
node = baseNode;
|
|
42
|
+
process.env.ANET_HUB_SECRET_VAULT_KEY = '43'.repeat(32);
|
|
43
|
+
db.run("INSERT INTO users(user_id,username,password_hash,role) VALUES(?1,?1,'x','user')", [owner]);
|
|
44
|
+
db.run("INSERT INTO users(user_id,username,password_hash,role) VALUES(?1,?1,'x','user')", [member]);
|
|
45
|
+
db.run('INSERT INTO networks(network_id,network_name,owner_id) VALUES(?1,?1,?2)', [net, owner]);
|
|
46
|
+
db.run("INSERT INTO network_members(user_id,network_id,role) VALUES(?1,?2,'owner')", [owner, net]);
|
|
47
|
+
db.run("INSERT INTO network_members(user_id,network_id,role) VALUES(?1,?2,'member')", [member, net]);
|
|
48
|
+
vaultUpsert(net, KEY, VALUE);
|
|
49
|
+
});
|
|
50
|
+
afterAll(cleanup);
|
|
51
|
+
|
|
52
|
+
const human = (userId: string) => ({ userId, isNode: false, networkId: net });
|
|
53
|
+
// 必须是函数:node 每个用例都不同,写成常量会把第一个用例的节点名焊死。
|
|
54
|
+
const asDaemon = () => ({ ok: true as const, networkId: net, daemonNodeId: node, daemonAlias: node });
|
|
55
|
+
|
|
56
|
+
/** 节点侧真正会收到的那个请求(不是内部字段:走 pullNodeSecrets 这条公开路径)。 */
|
|
57
|
+
function pulledFor(requestId: string) {
|
|
58
|
+
const pulled = pullNodeSecrets(asDaemon()) as any;
|
|
59
|
+
expect(pulled.ok).toBe(true);
|
|
60
|
+
return (pulled.requests as any[]).find((r) => r.request_id === requestId);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
describe("#3148 保险库 → 节点:值能流过去,但读不回来", () => {
|
|
64
|
+
test("① 流向:owner 只给键名(from_vault),节点 pull 到的那条请求里带着保险库的值", () => {
|
|
65
|
+
makeNode("n_vi_flow");
|
|
66
|
+
const created = requestNodeSecrets(human(owner), node, 'put', KEY, undefined, 0, true) as any;
|
|
67
|
+
expect(created.ok).toBe(true);
|
|
68
|
+
const pulled = pulledFor(created.request_id);
|
|
69
|
+
expect(pulled).toBeDefined();
|
|
70
|
+
expect(pulled.action).toBe('put');
|
|
71
|
+
expect(pulled.key).toBe(KEY);
|
|
72
|
+
// 这一条是「值真的到了目标进程手上」——流向成立。
|
|
73
|
+
expect(pulled.value).toBe(VALUE);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test("② 读权:ack 回来的回执里只有键名与来源,没有任何值", () => {
|
|
77
|
+
makeNode("n_vi_ack");
|
|
78
|
+
const created = requestNodeSecrets(human(owner), node, 'put', KEY, undefined, 0, true) as any;
|
|
79
|
+
pulledFor(created.request_id);
|
|
80
|
+
const ack = ackNodeSecrets(asDaemon(), created.request_id, {
|
|
81
|
+
network_id: net, daemon_node_id: null, node_id: node, revision: 1, activation: 'next_start',
|
|
82
|
+
keys: [{ key: KEY, source: 'node' }],
|
|
83
|
+
}) as any;
|
|
84
|
+
expect(ack.ok).toBe(true);
|
|
85
|
+
expect(JSON.stringify(ack)).not.toContain(VALUE);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
test("② 镜像否定:getScopedSecrets 的回执里没有值,也没有请求体里的明文", () => {
|
|
89
|
+
makeNode("n_vi_noread");
|
|
90
|
+
const created = requestNodeSecrets(human(owner), node, 'put', KEY, undefined, 0, true) as any;
|
|
91
|
+
const got = getScopedSecrets(human(owner), created.request_id) as any;
|
|
92
|
+
expect(got.ok).toBe(true);
|
|
93
|
+
expect(JSON.stringify(got)).not.toContain(VALUE);
|
|
94
|
+
expect(JSON.stringify(got)).not.toContain('"value"');
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
test("保险库里没有这个键 ⇒ vault_key_missing(不许回一个看起来成功的请求)", () => {
|
|
98
|
+
makeNode("n_vi_missing");
|
|
99
|
+
expect(requestNodeSecrets(human(owner), node, 'put', 'NOT_THERE', undefined, 0, true)).toEqual({
|
|
100
|
+
ok: false, error: 'vault_key_missing',
|
|
101
|
+
});
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test("from_vault 只对 put 有意义:list / delete 用它是无效输入", () => {
|
|
105
|
+
makeNode("n_vi_list");
|
|
106
|
+
expect((requestNodeSecrets(human(owner), node, 'list', KEY, undefined, 0, true) as any).error).toBe('invalid_secret_input');
|
|
107
|
+
expect((requestNodeSecrets(human(owner), node, 'delete', KEY, undefined, 0, true) as any).error).toBe('invalid_secret_input');
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
test("同时给 value 与 from_vault ⇒ 无效输入(两种来源不许混用,否则说不清写进去的是哪一个)", () => {
|
|
111
|
+
makeNode("n_vi_mix");
|
|
112
|
+
expect((requestNodeSecrets(human(owner), node, 'put', KEY, 'another-value', 0, true) as any).error).toBe('invalid_secret_input');
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
test("普通成员用 from_vault ⇒ secret_admin_required(这是权限边界,不是能力边界)", () => {
|
|
116
|
+
makeNode("n_vi_member");
|
|
117
|
+
expect((requestNodeSecrets(human(member), node, 'put', KEY, undefined, 0, true) as any).error).toBe('secret_admin_required');
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
test("节点令牌(isNode)自己调 ⇒ user_token_required(机器不能给自己发密钥)", () => {
|
|
121
|
+
makeNode("n_vi_nodetoken");
|
|
122
|
+
expect((requestNodeSecrets({ userId: null, isNode: true, networkId: net }, node, 'put', KEY, undefined, 0, true) as any)
|
|
123
|
+
.error).toBe('user_token_required');
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
test("不支持的节点 ⇒ node_secrets_upgrade_required(先升级,不是先提权)", () => {
|
|
127
|
+
makeNode("n_vi_oldnode");
|
|
128
|
+
db.run('UPDATE nodes SET config_snapshot=?1 WHERE node_id=?2', [JSON.stringify({}), node]);
|
|
129
|
+
expect((requestNodeSecrets(human(owner), node, 'put', KEY, undefined, 0, true) as any).error)
|
|
130
|
+
.toBe('node_secrets_upgrade_required');
|
|
131
|
+
});
|
|
132
|
+
});
|
package/src/scoped-secrets.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { providerScanTargets } from './daemon-provider-snapshots';
|
|
|
6
6
|
import { validScopedSecretKey } from './shared/scoped-secret-contract';
|
|
7
7
|
import { observeSecretWrite, transportOf } from './env-transport-gate.js';
|
|
8
8
|
import { secretTransportVerdict } from './env-transport-policy.js';
|
|
9
|
+
import { vaultGet } from './vault';
|
|
9
10
|
type Human = { userId?: string | null; isNode: boolean; networkId: string | null };
|
|
10
11
|
type Daemon = { ok: false; error: string } | { ok: true; networkId: string; daemonNodeId: string; daemonAlias: string };
|
|
11
12
|
type Request = { request_id: string; network_id: string; daemon_node_id: string | null; node_id: string | null;
|
|
@@ -33,9 +34,33 @@ function nodeSupported(network: string, node: string) {
|
|
|
33
34
|
try { return JSON.parse(row?.config_snapshot ?? '{}').node_secrets_capable === true; } catch { return false; }
|
|
34
35
|
}
|
|
35
36
|
// Independent node lane: no supervisor lookup, binding, or Daemon credential.
|
|
36
|
-
|
|
37
|
+
//
|
|
38
|
+
// `fromVault`(2026-11-01,#3148)—— **把保险库里的值直接推给这个节点**,调用方不必再持有明文。
|
|
39
|
+
//
|
|
40
|
+
// 背景:RFC-028 的保险库是「只进不出」——`list_network_secrets` 只回键名,没有任何取值接口。
|
|
41
|
+
// 这是对的:给 agent 一个读口,等于把整个网络的密钥变成任何一次 prompt 注入都能 dump 的东西。
|
|
42
|
+
// 但它带来一个真实的死结(admin 2026-11-01 在客户端里撞到):
|
|
43
|
+
//
|
|
44
|
+
// 密钥已经在保险库里了,可**没有任何路径**把它送到真正要用的那个进程;
|
|
45
|
+
// 于是人只能把明文再复制一遍,或者干脆写进工作区文件 —— 两条都比保险库更差。
|
|
46
|
+
//
|
|
47
|
+
// 所以这里补的是**流向**而不是**读权**:值从保险库直接写进目标节点的那次请求,
|
|
48
|
+
// 调用方(必须是 owner/admin)只提供键名。读侧仍然拿不到任何明文:
|
|
49
|
+
// · getScopedSecrets 只回 status/snapshot/error
|
|
50
|
+
// · 节点 ack 回来的 snapshot 里只有 {key, source},没有值
|
|
51
|
+
export function requestNodeSecrets(h: Human, node: string, action: Request['action'], key?: string, value?: string, revision?: number, fromVault?: boolean) {
|
|
37
52
|
const refusal = authorize(h); if (refusal) return refusal;
|
|
38
53
|
if (!nodeSupported(h.networkId!, node)) return denied('node_secrets_upgrade_required');
|
|
54
|
+
// from_vault 只在 put 上有意义:list/delete 没有值可推。
|
|
55
|
+
if (fromVault && action !== 'put') return denied('invalid_secret_input');
|
|
56
|
+
if (fromVault && value !== undefined) return denied('invalid_secret_input');
|
|
57
|
+
if (fromVault) {
|
|
58
|
+
if (!validScopedSecretKey(key)) return denied('invalid_secret_input');
|
|
59
|
+
// 保险库里没有这个名字 ⇒ 明确说「没有」,不要回一个看起来成功的请求。
|
|
60
|
+
const fromVaultValue = vaultGet(h.networkId!, key!);
|
|
61
|
+
if (typeof fromVaultValue !== 'string' || !fromVaultValue) return denied('vault_key_missing');
|
|
62
|
+
value = fromVaultValue;
|
|
63
|
+
}
|
|
39
64
|
if (action !== 'list' && (!validScopedSecretKey(key) || !Number.isSafeInteger(revision) || revision! < 0
|
|
40
65
|
|| (action === 'put' && (typeof value !== 'string' || !value || Buffer.byteLength(value) > 8192 || value.includes('\0'))))) return denied('invalid_secret_input');
|
|
41
66
|
expire();
|
|
@@ -45,7 +70,8 @@ export function requestNodeSecrets(h: Human, node: string, action: Request['acti
|
|
|
45
70
|
const transport = transportOf(h.networkId!, node);
|
|
46
71
|
const verdict = secretTransportVerdict(transport);
|
|
47
72
|
if (verdict) return denied(verdict);
|
|
48
|
-
|
|
73
|
+
// 记录的是**来源**,不是值:from_vault 的注入要能从审计里区分出来。
|
|
74
|
+
observeSecretWrite(h.networkId!, node, `node_secret_${action}${fromVault ? '_from_vault' : ''}`);
|
|
49
75
|
}
|
|
50
76
|
if ([...requests.values()].some(r => r.network_id === h.networkId && r.daemon_node_id === null && r.node_id === node && r.status === 'pending')) return denied('secret_store_busy');
|
|
51
77
|
if (requests.size >= 1000) return denied('secret_queue_busy');
|
package/src/server.ts
CHANGED
|
@@ -53,7 +53,7 @@ import { restrictedMemberSeesFile, restrictedMemberAttachmentsDenied } from "./r
|
|
|
53
53
|
import { dmParticipantSeesFile, listDmThread, listDmThreads, sendHumanDm } from "./human-dm.js";
|
|
54
54
|
import { groupMemberSeesFile, groupUnreadFor, listGroupMessages, listGroupThreads, markGroupRead, memberGroup, sendGroupMessage } from "./group-messages.js";
|
|
55
55
|
import { getTaskAccessMode, isTaskScoped, listProjectGrants, replaceTaskGrants, newMemberTaskAccess } from "./task-access.js";
|
|
56
|
-
import { canMessageAgent, isAgentRestricted, visibleAgents, listAgentGrants, listGroupGrants, getAgentAccessMode, replaceAgentGrants, restrictedNetworkIds, usernameIsAgentAlias, listAgentGroups, createAgentGroup, updateAgentGroup, replaceAgentGroupMembers, deleteAgentGroup, usersGrantedGroup } from "./agent-access.js";
|
|
56
|
+
import { canMessageAgent, isAgentRestricted, visibleAgents, listAgentGrants, listGroupGrants, getAgentAccessMode, replaceAgentGrants, restrictedNetworkIds, usernameIsAgentAlias, listAgentGroups, createAgentGroup, updateAgentGroup, replaceAgentGroupMembers, deleteAgentGroup, usersGrantedGroup, listDepartmentGrants, departmentCoverage } from "./agent-access.js";
|
|
57
57
|
import { broadcastVerdict, dispatchVerdict, humanOnlyVerdict, NODE_PERMISSION_MODES, nodeDecide, nodeIdentity, nodePermissionDeniedBody, nodePermissionsFlag, streamVerdict, writeVerdict, type NodeIdentity, type NodePermissionMode, type Verdict } from "./node-permissions.js";
|
|
58
58
|
import { validateAvatarUrl } from "./avatar-validate.js";
|
|
59
59
|
import { narrowTags, parseStoredTags, validateScalarAttr } from "./node-attrs-validate.js";
|
|
@@ -3050,6 +3050,11 @@ return Bun.serve({
|
|
|
3050
3050
|
restricted: isAgentRestricted(targetUid, netId),
|
|
3051
3051
|
grants: listAgentGrants(netId, targetUid),
|
|
3052
3052
|
group_grants: listGroupGrants(netId, targetUid),
|
|
3053
|
+
// 部门维度授权(admin 2026-11-05):与组授权同构,展开源是部门子树。
|
|
3054
|
+
department_grants: listDepartmentGrants(netId, targetUid),
|
|
3055
|
+
// 覆盖率必须一起给:没填 department_id 的节点永远不可能被部门授权覆盖,
|
|
3056
|
+
// 否则用户会以为「授权了就该全看见」,然后在界面上找不到人。
|
|
3057
|
+
department_coverage: departmentCoverage(netId),
|
|
3053
3058
|
}));
|
|
3054
3059
|
}
|
|
3055
3060
|
// 网络 admin 不能改 owner / 其他 admin 的授权(对他们本来也不生效,但别让 admin 去碰平级)。
|
|
@@ -3059,7 +3064,8 @@ return Bun.serve({
|
|
|
3059
3064
|
let body: any;
|
|
3060
3065
|
try { body = await req.json(); } catch { return withCors(req, Response.json({ ok: false, error: "invalid JSON" }, { status: 400 })); }
|
|
3061
3066
|
if (!body || typeof body !== "object" || Array.isArray(body)) return withCors(req, Response.json({ ok: false, error: "invalid JSON" }, { status: 400 }));
|
|
3062
|
-
if (body.grants === undefined && body.node_ids === undefined && body.agent_access === undefined
|
|
3067
|
+
if (body.grants === undefined && body.node_ids === undefined && body.agent_access === undefined
|
|
3068
|
+
&& body.group_grants === undefined && body.department_grants === undefined) {
|
|
3063
3069
|
return withCors(req, Response.json({ ok: false, error: "grants or agent_access required" }, { status: 400 }));
|
|
3064
3070
|
}
|
|
3065
3071
|
const result = replaceAgentGrants({
|
|
@@ -3068,13 +3074,14 @@ return Bun.serve({
|
|
|
3068
3074
|
grants: body.grants ?? body.node_ids,
|
|
3069
3075
|
agentAccess: body.agent_access,
|
|
3070
3076
|
groupGrants: body.group_grants,
|
|
3077
|
+
departmentGrants: body.department_grants,
|
|
3071
3078
|
actorUserId: resolved.user.user_id,
|
|
3072
3079
|
});
|
|
3073
3080
|
if (!result.ok) {
|
|
3074
3081
|
return withCors(req, Response.json({ ok: false, error: result.error, ...(result.detail ? { detail: result.detail } : {}) }, { status: result.status }));
|
|
3075
3082
|
}
|
|
3076
3083
|
logAudit(resolved.user.user_id, resolved.user.username, "member_agent_grants_changed", "network", netId,
|
|
3077
|
-
JSON.stringify({ user_id: targetUid, agent_access: result.agent_access, grants: result.grants.map((g) => ({ node_id: g.node_id, alias: g.alias, can_message: g.can_message })), group_grants: result.group_grants.map((g) => ({ group_id: g.group_id, can_message: g.can_message })) }).slice(0, 4000),
|
|
3084
|
+
JSON.stringify({ user_id: targetUid, agent_access: result.agent_access, grants: result.grants.map((g) => ({ node_id: g.node_id, alias: g.alias, can_message: g.can_message })), group_grants: result.group_grants.map((g) => ({ group_id: g.group_id, can_message: g.can_message })), department_grants: result.department_grants.map((g) => ({ department_id: g.department_id, can_message: g.can_message })) }).slice(0, 4000),
|
|
3078
3085
|
undefined, netId);
|
|
3079
3086
|
// 已连着的观察流 / 用户流按旧权限鉴权过,断开让它按新权限重连。
|
|
3080
3087
|
closeUserStreamsInNetwork(netId, targetUid);
|
package/src/tools.ts
CHANGED
|
@@ -4607,8 +4607,8 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
4607
4607
|
// No additional tools in model context; ordinary Provider actions unchanged.
|
|
4608
4608
|
if (action === 'secret_read') return providerReply(getScopedSecrets(human, id));
|
|
4609
4609
|
if (action === 'node_secret_list' || action === 'node_secret_put' || action === 'node_secret_delete') {
|
|
4610
|
-
const input = provider as { key?: string; value?: string } | undefined;
|
|
4611
|
-
const result = requestNodeSecrets(human, id, action === 'node_secret_list' ? 'list' : action === 'node_secret_put' ? 'put' : 'delete', input?.key, input?.value, revision);
|
|
4610
|
+
const input = provider as { key?: string; value?: string; from_vault?: boolean } | undefined;
|
|
4611
|
+
const result = requestNodeSecrets(human, id, action === 'node_secret_list' ? 'list' : action === 'node_secret_put' ? 'put' : 'delete', input?.key, input?.value, revision, input?.from_vault === true);
|
|
4612
4612
|
if (result.ok) {
|
|
4613
4613
|
const target = db.get<{ alias: string }>('SELECT alias FROM nodes WHERE node_id=?1 AND network_id=?2', id, human.networkId!);
|
|
4614
4614
|
if (target) pushEvent(target.alias, { type: 'node_secrets', request_id: result.request_id }, human.networkId!);
|