@sleep2agi/commhub-server 0.9.0-preview.67 → 0.9.0-preview.69

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sleep2agi/commhub-server",
3
- "version": "0.9.0-preview.67",
3
+ "version": "0.9.0-preview.69",
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",
@@ -0,0 +1,267 @@
1
+ // 多用户账号与 Agent 权限 —— 「这个人在这个网络里能看见 / 能联系哪些 Agent」的唯一实现。
2
+ //
3
+ // 受限成员(restricted member):网络里 role 为 member/viewer、agent_access 不是 'all'、
4
+ // 且不是 Hub 管理员的用户。他只能看见 network_member_agent_grants 里授权给他的 Agent,
5
+ // 只能给其中 can_message=1 的发任务/消息;人类之间的私信不受影响。
6
+ //
7
+ // 判定是 fail-closed 的:agent_access 只有字面 'all' 才放开;role 只有 owner/admin 才豁免。
8
+ // 读到任何别的值(包括未来新增的角色)都按受限处理。
9
+ //
10
+ // 这里只回答「能不能」,不管「是不是成员」——非成员返回 false(不受限),
11
+ // 成员资格仍由调用方原有的 getUserNetworkRole 判定。两件事分开,别合并成一个判据。
12
+
13
+ import { db } from "./db.js";
14
+
15
+ const UNRESTRICTED_ROLES = new Set(["owner", "admin"]);
16
+
17
+ export type AgentAccessMode = "all" | "granted";
18
+
19
+ export type AgentGrant = {
20
+ node_id: string | null;
21
+ alias: string | null;
22
+ can_message: boolean;
23
+ };
24
+
25
+ /** 某受限成员在某网络里能看见 / 能联系的 Agent,已经展开成 alias 与 node_id 两份清单。 */
26
+ export type VisibleAgents = {
27
+ aliases: string[];
28
+ nodeIds: string[];
29
+ messageAliases: string[];
30
+ messageNodeIds: string[];
31
+ };
32
+
33
+ export function isHubAdmin(userId: string): boolean {
34
+ return db.get<{ role: string | null }>("SELECT role FROM users WHERE user_id = ?1", userId)?.role === "admin";
35
+ }
36
+
37
+ function restrictedRow(row: { member_role: string | null; agent_access: string | null; user_role: string | null } | null | undefined): boolean {
38
+ if (!row) return false;
39
+ if (row.user_role === "admin") return false;
40
+ if (UNRESTRICTED_ROLES.has(String(row.member_role))) return false;
41
+ return row.agent_access !== "all";
42
+ }
43
+
44
+ export function isAgentRestricted(userId: string, networkId: string | null | undefined): boolean {
45
+ if (!userId || !networkId) return false;
46
+ const row = db.get<{ member_role: string | null; agent_access: string | null; user_role: string | null }>(
47
+ `SELECT nm.role AS member_role, nm.agent_access, u.role AS user_role
48
+ FROM network_members nm JOIN users u ON u.user_id = nm.user_id
49
+ WHERE nm.network_id = ?1 AND nm.user_id = ?2`,
50
+ networkId, userId,
51
+ );
52
+ return restrictedRow(row);
53
+ }
54
+
55
+ /** 该用户所有「只看授权 Agent」的网络。Hub 管理员恒为空。 */
56
+ export function restrictedNetworkIds(userId: string): string[] {
57
+ if (!userId) return [];
58
+ return db.all<{ network_id: string; member_role: string | null; agent_access: string | null; user_role: string | null }>(
59
+ `SELECT nm.network_id, nm.role AS member_role, nm.agent_access, u.role AS user_role
60
+ FROM network_members nm
61
+ JOIN users u ON u.user_id = nm.user_id
62
+ JOIN networks n ON n.network_id = nm.network_id
63
+ WHERE nm.user_id = ?1`,
64
+ userId,
65
+ ).filter(restrictedRow).map((row) => row.network_id);
66
+ }
67
+
68
+ export function getAgentAccessMode(networkId: string, userId: string): AgentAccessMode | null {
69
+ const row = db.get<{ agent_access: string | null }>(
70
+ "SELECT agent_access FROM network_members WHERE network_id = ?1 AND user_id = ?2",
71
+ networkId, userId,
72
+ );
73
+ if (!row) return null;
74
+ return row.agent_access === "all" ? "all" : "granted";
75
+ }
76
+
77
+ export function listAgentGrants(networkId: string, userId: string): AgentGrant[] {
78
+ return db.all<{ node_id: string | null; alias: string | null; can_message: number }>(
79
+ `SELECT node_id, alias, can_message FROM network_member_agent_grants
80
+ WHERE network_id = ?1 AND user_id = ?2
81
+ ORDER BY COALESCE(node_id, alias)`,
82
+ networkId, userId,
83
+ ).map((row) => ({ node_id: row.node_id, alias: row.alias, can_message: row.can_message === 1 }));
84
+ }
85
+
86
+ /**
87
+ * 把授权展开成 alias / node_id 两份清单。
88
+ * node_id 授权同时带出:nodes 表里这个节点的 alias、sessions 表里同 node_id 的会话 alias
89
+ * (改名后 sessions 先于 nodes 更新的窗口里两者可能不同,两个都算)。都限定在同一网络。
90
+ */
91
+ export function visibleAgents(userId: string, networkId: string): VisibleAgents {
92
+ const aliases = new Set<string>();
93
+ const nodeIds = new Set<string>();
94
+ const messageAliases = new Set<string>();
95
+ const messageNodeIds = new Set<string>();
96
+ for (const grant of listAgentGrants(networkId, userId)) {
97
+ const grantAliases: string[] = [];
98
+ if (grant.node_id) {
99
+ nodeIds.add(grant.node_id);
100
+ if (grant.can_message) messageNodeIds.add(grant.node_id);
101
+ for (const row of db.all<{ alias: string | null }>(
102
+ `SELECT alias FROM nodes WHERE node_id = ?1 AND network_id = ?2
103
+ UNION SELECT alias FROM sessions WHERE node_id = ?1 AND network_id = ?2`,
104
+ grant.node_id, networkId,
105
+ )) {
106
+ if (row.alias) grantAliases.push(row.alias);
107
+ }
108
+ } else if (grant.alias) {
109
+ grantAliases.push(grant.alias);
110
+ }
111
+ for (const alias of grantAliases) {
112
+ aliases.add(alias);
113
+ if (grant.can_message) messageAliases.add(alias);
114
+ }
115
+ }
116
+ return {
117
+ aliases: [...aliases],
118
+ nodeIds: [...nodeIds],
119
+ messageAliases: [...messageAliases],
120
+ messageNodeIds: [...messageNodeIds],
121
+ };
122
+ }
123
+
124
+ /** 这个用户名在该网络里是否同时是某个 Agent 的 alias(sessions 或 nodes)。 */
125
+ export function usernameIsAgentAlias(networkId: string, username: string): boolean {
126
+ if (!username) return false;
127
+ return !!db.get(
128
+ `SELECT 1 WHERE EXISTS (SELECT 1 FROM sessions WHERE network_id = ?1 AND alias = ?2)
129
+ OR EXISTS (SELECT 1 FROM nodes WHERE network_id = ?1 AND alias = ?2)`,
130
+ networkId, username,
131
+ );
132
+ }
133
+
134
+ export type AgentRef = { alias?: string | null; nodeId?: string | null };
135
+
136
+ function refMatches(ref: AgentRef, aliases: string[], nodeIds: string[]): boolean {
137
+ if (ref.nodeId && nodeIds.includes(ref.nodeId)) return true;
138
+ if (ref.alias && aliases.includes(ref.alias)) return true;
139
+ return false;
140
+ }
141
+
142
+ /** 不受限的成员恒为 true;受限成员只对授权的 Agent 为 true。不判断成员资格。 */
143
+ export function canSeeAgent(userId: string, networkId: string | null | undefined, ref: AgentRef): boolean {
144
+ if (!networkId || !isAgentRestricted(userId, networkId)) return true;
145
+ const visible = visibleAgents(userId, networkId);
146
+ return refMatches(ref, visible.aliases, visible.nodeIds);
147
+ }
148
+
149
+ export function canMessageAgent(userId: string, networkId: string | null | undefined, ref: AgentRef): boolean {
150
+ if (!networkId || !isAgentRestricted(userId, networkId)) return true;
151
+ const visible = visibleAgents(userId, networkId);
152
+ return refMatches(ref, visible.messageAliases, visible.messageNodeIds);
153
+ }
154
+
155
+ export type AgentGrantInput = { node_id?: unknown; alias?: unknown; can_message?: unknown };
156
+
157
+ export type ReplaceGrantsResult =
158
+ | { ok: true; agent_access: AgentAccessMode; grants: AgentGrant[] }
159
+ | { ok: false; error: string; status: number; detail?: unknown };
160
+
161
+ const MAX_GRANTS = 1000;
162
+
163
+ /**
164
+ * 整体替换某成员的授权(PUT 语义)。node_id 必须是本网络里存在的节点;alias 只用于没有
165
+ * node_id 的旧会话,也必须是本网络里存在的会话。任何一条不合法 ⇒ 整批拒绝,不做部分写入。
166
+ */
167
+ export function replaceAgentGrants(input: {
168
+ networkId: string;
169
+ userId: string;
170
+ grants: unknown;
171
+ agentAccess?: unknown;
172
+ actorUserId: string;
173
+ }): ReplaceGrantsResult {
174
+ const member = db.get<{ role: string }>(
175
+ "SELECT role FROM network_members WHERE network_id = ?1 AND user_id = ?2",
176
+ input.networkId, input.userId,
177
+ );
178
+ if (!member) return { ok: false, error: "member_not_found", status: 404 };
179
+
180
+ let mode: AgentAccessMode | undefined;
181
+ if (input.agentAccess !== undefined) {
182
+ if (input.agentAccess !== "all" && input.agentAccess !== "granted") {
183
+ return { ok: false, error: "invalid_agent_access", status: 400 };
184
+ }
185
+ mode = input.agentAccess;
186
+ }
187
+
188
+ let rows: Array<{ node_id: string | null; alias: string | null; can_message: number }> | undefined;
189
+ if (input.grants !== undefined) {
190
+ if (!Array.isArray(input.grants)) return { ok: false, error: "grants_must_be_array", status: 400 };
191
+ if (input.grants.length > MAX_GRANTS) return { ok: false, error: "too_many_grants", status: 400, detail: { limit: MAX_GRANTS } };
192
+ const seen = new Set<string>();
193
+ rows = [];
194
+ for (const [index, raw] of input.grants.entries()) {
195
+ // 兼容直接传 node_id 字符串数组。
196
+ const item: AgentGrantInput = typeof raw === "string" ? { node_id: raw } : (raw && typeof raw === "object" && !Array.isArray(raw) ? raw as AgentGrantInput : {});
197
+ const nodeId = typeof item.node_id === "string" && item.node_id.trim() ? item.node_id.trim() : null;
198
+ const alias = typeof item.alias === "string" && item.alias.trim() ? item.alias.trim() : null;
199
+ if ((nodeId === null) === (alias === null)) {
200
+ return { ok: false, error: "grant_needs_exactly_one_of_node_id_or_alias", status: 400, detail: { index } };
201
+ }
202
+ if (item.can_message !== undefined && typeof item.can_message !== "boolean") {
203
+ return { ok: false, error: "can_message_must_be_boolean", status: 400, detail: { index } };
204
+ }
205
+ const exists = nodeId
206
+ ? db.get("SELECT 1 FROM nodes WHERE node_id = ?1 AND network_id = ?2", nodeId, input.networkId)
207
+ : db.get("SELECT 1 FROM sessions WHERE alias = ?1 AND network_id = ?2", alias, input.networkId);
208
+ if (!exists) {
209
+ return { ok: false, error: "agent_not_in_network", status: 400, detail: { index, ...(nodeId ? { node_id: nodeId } : { alias }) } };
210
+ }
211
+ const key = nodeId ? `n:${nodeId}` : `a:${alias}`;
212
+ if (seen.has(key)) continue;
213
+ seen.add(key);
214
+ rows.push({ node_id: nodeId, alias, can_message: item.can_message === false ? 0 : 1 });
215
+ }
216
+ }
217
+
218
+ db.transaction(() => {
219
+ if (mode) {
220
+ db.run("UPDATE network_members SET agent_access = ?1 WHERE network_id = ?2 AND user_id = ?3", [mode, input.networkId, input.userId]);
221
+ }
222
+ if (rows) {
223
+ db.run("DELETE FROM network_member_agent_grants WHERE network_id = ?1 AND user_id = ?2", [input.networkId, input.userId]);
224
+ for (const row of rows) {
225
+ db.run(
226
+ `INSERT INTO network_member_agent_grants (network_id, user_id, node_id, alias, can_message, created_by)
227
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6)`,
228
+ [input.networkId, input.userId, row.node_id, row.alias, row.can_message, input.actorUserId],
229
+ );
230
+ }
231
+ }
232
+ });
233
+
234
+ return {
235
+ ok: true,
236
+ agent_access: getAgentAccessMode(input.networkId, input.userId) ?? "granted",
237
+ grants: listAgentGrants(input.networkId, input.userId),
238
+ };
239
+ }
240
+
241
+ /** 成员被移出网络时一并清掉授权,重新加入时从零开始。 */
242
+ export function deleteAgentGrants(networkId: string, userId: string): void {
243
+ db.run("DELETE FROM network_member_agent_grants WHERE network_id = ?1 AND user_id = ?2", [networkId, userId]);
244
+ }
245
+
246
+ // 多用户 Agent 权限 —— 受限成员(只看授权 Agent 的成员)能调的 MCP 工具。每一个都逐条审过:
247
+ // 要么自己按授权过滤 / 准入(get_all_status、get_session_status、get_task、list_tasks、send_task、
248
+ // send_message),要么是人类侧(send_desktop_message、需求看板),要么只读且对受限网络 fail-closed
249
+ // (get_completions)。其余工具:受限成员只能在**不受限的**网络里调(必须显式传 network_id),
250
+ // 在受限网络里、或没说是哪个网络时一律拒绝 —— 新增的工具默认落在拒绝这边。
251
+ export const RESTRICTED_MEMBER_TOOLS: ReadonlySet<string> = new Set([
252
+ "get_all_status",
253
+ "get_session_status",
254
+ "get_task",
255
+ "list_tasks",
256
+ "get_completions",
257
+ "send_task",
258
+ "send_message",
259
+ "send_desktop_message",
260
+ "requirements_list",
261
+ "requirements_get",
262
+ "requirements_create",
263
+ "requirements_update",
264
+ "requirements_checklist_toggle",
265
+ "requirements_upsert_by_external_ref",
266
+ "projects_list",
267
+ ]);