@sleep2agi/commhub-server 0.9.0-preview.281 → 0.9.0-preview.283

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 (43) hide show
  1. package/build-info.json +2 -2
  2. package/package.json +1 -1
  3. package/src/agent-acl-slice3-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 +10 -0
  10. package/src/clone-node-adopted-db.test.ts +78 -0
  11. package/src/clone-node.ts +5 -1
  12. package/src/create-node-department.test.ts +145 -0
  13. package/src/create-node.ts +35 -0
  14. package/src/db.ts +11 -0
  15. package/src/department-heads.ts +3 -0
  16. package/src/expiry-counters.test.ts +50 -1
  17. package/src/expiry-counters.ts +31 -9
  18. package/src/mcp-write-network-resolution.test.ts +36 -0
  19. package/src/node-attrs-validate.ts +34 -0
  20. package/src/node-attrs.test.ts +32 -0
  21. package/src/node-config-last-update.test.ts +103 -1
  22. package/src/node-config-last-update.ts +70 -5
  23. package/src/node-daemon-bindings.ts +9 -0
  24. package/src/node-description-http.test.ts +121 -0
  25. package/src/node-description.test.ts +34 -0
  26. package/src/node-grants-http.test.ts +239 -0
  27. package/src/node-grants.ts +234 -0
  28. package/src/node-inbox-allowlist-http.test.ts +35 -0
  29. package/src/node-permissions.ts +37 -2
  30. package/src/opencode-v2-catalog.test.ts +22 -1
  31. package/src/opencode-v2-catalog.ts +36 -3
  32. package/src/peer-allowlist.test.ts +29 -0
  33. package/src/registration-switch-http.test.ts +60 -0
  34. package/src/reply-bare-infer-4315.test.ts +86 -0
  35. package/src/requirements.ts +29 -4
  36. package/src/schedule-agent.ts +45 -10
  37. package/src/scheduled-tasks-http.test.ts +25 -0
  38. package/src/scheduled-tasks.ts +46 -2
  39. package/src/server.ts +132 -11
  40. package/src/steer-send-message.test.ts +121 -0
  41. package/src/task-access.ts +21 -1
  42. package/src/tool-audience-http.test.ts +5 -0
  43. package/src/tools.ts +147 -42
@@ -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
+ }
@@ -301,6 +301,41 @@ describe("排程 —— 每次触发按建排程的人现判", () => {
301
301
  });
302
302
  });
303
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
+
304
339
  describe("inboxAllows —— 纯判定", () => {
305
340
  const ctx = { targetNodeId: "n_t", targetAlias: "t", ownerUserId: "u_owner", networkId: null };
306
341
  test("null 放行一切;legacy 默认放行,!strict 拒", () => {
@@ -458,6 +458,39 @@ function inboxTargetRow(networkId: string | null, target: AgentRef): InboxTarget
458
458
  return null;
459
459
  }
460
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
+
461
494
  /** 纯判定(不记账):名单 + 发件人 → 放不放行。 */
462
495
  export function inboxAllows(
463
496
  list: string[] | null,
@@ -467,7 +500,8 @@ export function inboxAllows(
467
500
  if (!list) return true;
468
501
  if (sender.kind === "node") {
469
502
  if ((sender.nodeId && sender.nodeId === ctx.targetNodeId) || (ctx.targetAlias && sender.aliases.includes(ctx.targetAlias))) return true;
470
- return (!!sender.nodeId && list.includes(sender.nodeId)) || sender.aliases.some(a => list.includes(a));
503
+ return (!!sender.nodeId && list.includes(sender.nodeId)) || sender.aliases.some(a => list.includes(a))
504
+ || inboxDeptAllows(list, sender, ctx.networkId);
471
505
  }
472
506
  const strict = list.includes(INBOX_STRICT_ENTRY);
473
507
  if (sender.kind === "legacy") return !strict;
@@ -481,7 +515,8 @@ export function inboxAllows(
481
515
  }
482
516
  return list.includes("user:*")
483
517
  || list.includes(`user:${sender.userId}`)
484
- || (!!sender.username && list.includes(`user:${sender.username}`));
518
+ || (!!sender.username && list.includes(`user:${sender.username}`))
519
+ || inboxDeptAllows(list, sender, ctx.networkId);
485
520
  }
486
521
 
487
522
  export type InboxDenial = ReturnType<typeof nodePermissionDeniedBody> & { target: string; sender: string };
@@ -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);
@@ -191,6 +191,26 @@ function evictExpired(now = Date.now()): void {
191
191
  }
192
192
  }
193
193
 
194
+ const OPENCODE_RUNTIME_LABELS = new Set(["opencode-cli", "opencode-sdk", "opencode"]);
195
+ /** An actively adopted child of this daemon that reports OpenCode V2 (projection only). */
196
+ function adoptedOpenCodeV2Child(nodeId: string, networkId: string, daemonNodeId: string):
197
+ { child_name: string; workdir: string | null } | "not_v2" | null {
198
+ let b: { workdir: string } | null = null;
199
+ try {
200
+ b = db.get<{ workdir: string }>(
201
+ "SELECT workdir FROM node_daemon_bindings WHERE node_id=?1 AND network_id=?2 AND daemon_node_id=?3 AND status='active'",
202
+ nodeId, networkId, daemonNodeId);
203
+ } catch { return null; }
204
+ if (!b) return null;
205
+ const n = db.get<{ alias: string | null; runtime: string | null; config_snapshot: string | null }>(
206
+ "SELECT alias, runtime, config_snapshot FROM nodes WHERE node_id=?1 AND network_id=?2", nodeId, networkId);
207
+ if (!n?.alias) return null;
208
+ let generation: unknown;
209
+ try { generation = JSON.parse(n.config_snapshot || "{}")?.flags?.opencodeGeneration; } catch { generation = undefined; }
210
+ if (!OPENCODE_RUNTIME_LABELS.has(n.runtime ?? "") || generation !== "v2") return "not_v2";
211
+ return { child_name: n.alias, workdir: b.workdir || null };
212
+ }
213
+
194
214
  export function queueOpenCodeCatalogRead(input: QueueCatalogInput):
195
215
  | { ok: true; request_id: string; status: "pending"; daemon_alias: string; network_id: string }
196
216
  | { ok: false; error: string } {
@@ -225,9 +245,22 @@ export function queueOpenCodeCatalogRead(input: QueueCatalogInput):
225
245
  input.networkId, input.daemonNodeId,
226
246
  );
227
247
  const owned = creates.filter(row => childNodeId(row.request_id) === input.nodeId && row.daemon_node_id === input.daemonNodeId);
228
- if (owned.length !== 1) return { ok: false, error: "node_not_found" };
229
- const row = owned[0]!;
230
- if (row.runtime !== "opencode-cli" || !v2Flags(row.flags_json)) return { ok: false, error: "not_opencode_v2" };
248
+ let row: { child_name: string; workdir: string | null };
249
+ if (owned.length === 1) {
250
+ const created = owned[0]!;
251
+ if (created.runtime !== "opencode-cli" || !v2Flags(created.flags_json)) return { ok: false, error: "not_opencode_v2" };
252
+ row = created;
253
+ } else if (owned.length === 0) {
254
+ // admin 2026-11-11:被这个 daemon **收编**的节点没有创建记录,此前一律 node_not_found,
255
+ // 客户端模型面板只剩一行错误码。active 绑定 + 节点自报 OpenCode V2 就允许代读;
256
+ // 目录用绑定登记的 workdir(daemon 侧照样用它核对 endpoint 的目录)。
257
+ const adopted = adoptedOpenCodeV2Child(input.nodeId, input.networkId, input.daemonNodeId);
258
+ if (adopted === "not_v2") return { ok: false, error: "not_opencode_v2" };
259
+ if (!adopted) return { ok: false, error: "node_not_found" };
260
+ row = adopted;
261
+ } else {
262
+ return { ok: false, error: "node_not_found" };
263
+ }
231
264
 
232
265
  const requestId = `cat_${uuidv4()}`;
233
266
  const directory = typeof row.workdir === "string" && row.workdir.length > 0 ? row.workdir : null;
@@ -0,0 +1,29 @@
1
+ // 2026-11-11 安全排查:COMMHUB_ALLOWED_PEER_IPS —— Hub 端口只接名单里的对端 + 本机回环。
2
+ import { describe, expect, test } from "bun:test";
3
+ import { mkdtempSync } from "fs";
4
+ import { join } from "path";
5
+ import { tmpdir } from "os";
6
+
7
+ process.env.COMMHUB_DB ||= join(mkdtempSync(join(tmpdir(), "anet-peer-")), "hub.db");
8
+ const { peerAllowed } = await import("./server.js");
9
+
10
+ describe("peerAllowed", () => {
11
+ const list = new Set(["47.0.0.1"]);
12
+ test("unset = no restriction (old behaviour)", () => {
13
+ expect(peerAllowed("203.0.113.9", null)).toBe(true);
14
+ });
15
+ test("loopback always allowed (frp, local nodes)", () => {
16
+ for (const ip of ["127.0.0.1", "::1", "::ffff:127.0.0.1", "127.0.1.1"]) expect(peerAllowed(ip, list)).toBe(true);
17
+ });
18
+ test("listed proxy allowed, IPv4-mapped too", () => {
19
+ expect(peerAllowed("47.0.0.1", list)).toBe(true);
20
+ expect(peerAllowed("::ffff:47.0.0.1", list)).toBe(true);
21
+ });
22
+ test("anyone else refused", () => {
23
+ expect(peerAllowed("203.0.113.9", list)).toBe(false);
24
+ expect(peerAllowed("::ffff:203.0.113.9", list)).toBe(false);
25
+ });
26
+ test("unknown peer is not refused (never lock everyone out on a missing address)", () => {
27
+ expect(peerAllowed(null, list)).toBe(true);
28
+ });
29
+ });
@@ -0,0 +1,60 @@
1
+ // 2026-11-11 安全排查:生产 Hub 的公开注册没有开关(任何人都能注册、领令牌、按令牌限额上传)。
2
+ // COMMHUB_REGISTRATION=closed 关掉注册;不设 = 旧行为。库里还没有用户时(装机第一个 admin)照常放行。
3
+ import { describe, expect, test, beforeAll, afterAll } from "bun:test";
4
+ import { mkdtempSync, rmSync } from "fs";
5
+ import { join } from "path";
6
+ import { tmpdir } from "os";
7
+ import { register } from "./auth.js";
8
+
9
+ const DIR = mkdtempSync(join(tmpdir(), "anet-regswitch-"));
10
+ let BASE = "";
11
+ let hub: any = null;
12
+
13
+ const reg = (username: string) => fetch(`${BASE}/api/auth/register`, {
14
+ method: "POST",
15
+ headers: { "Content-Type": "application/json" },
16
+ body: JSON.stringify({ username, password: "RegSwitchPassw0rd!" }),
17
+ }).then(async r => ({ status: r.status, body: await r.json() as any }));
18
+
19
+ beforeAll(async () => {
20
+ process.env.COMMHUB_DB ||= join(DIR, "hub.db");
21
+ process.env.COMMHUB_UPLOADS_DIR = join(DIR, "uploads");
22
+ process.env.HOST = "127.0.0.1";
23
+ delete process.env.COMMHUB_REGISTRATION;
24
+ const mod: any = await import("./server.js");
25
+ hub = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
26
+ BASE = `http://127.0.0.1:${hub.port}`;
27
+ }, 30_000);
28
+
29
+ afterAll(() => {
30
+ delete process.env.COMMHUB_REGISTRATION;
31
+ try { hub?.stop?.(true); } catch {}
32
+ try { rmSync(DIR, { recursive: true, force: true }); } catch {}
33
+ });
34
+
35
+ describe("COMMHUB_REGISTRATION", () => {
36
+ test("unset: registration stays open (unchanged)", async () => {
37
+ register(`seed_${Date.now()}`, "RegSwitchPassw0rd!");
38
+ const r = await reg(`open_${Date.now()}`);
39
+ expect(r.status).toBe(200);
40
+ expect(r.body.ok).toBe(true);
41
+ });
42
+
43
+ test("closed: new sign-ups get 403 registration_closed; login still works", async () => {
44
+ const name = `before_${Date.now()}`;
45
+ expect((await reg(name)).status).toBe(200);
46
+ process.env.COMMHUB_REGISTRATION = "closed";
47
+ try {
48
+ const r = await reg(`late_${Date.now()}`);
49
+ expect(r.status).toBe(403);
50
+ expect(r.body.error).toBe("registration_closed");
51
+ const login = await fetch(`${BASE}/api/auth/login`, {
52
+ method: "POST", headers: { "Content-Type": "application/json" },
53
+ body: JSON.stringify({ username: name, password: "RegSwitchPassw0rd!" }),
54
+ });
55
+ expect(login.status).toBe(200);
56
+ } finally {
57
+ delete process.env.COMMHUB_REGISTRATION;
58
+ }
59
+ });
60
+ });
@@ -0,0 +1,86 @@
1
+ // #4315 —— 裸回执(既无 alias 也无 in_reply_to)会把那笔任务留成 expired,
2
+ // 攒够 3 条就把节点挡成 target_never_consumes。
3
+ // 判据:**这台节点手上恰好一条非终态任务**时才推断 in_reply_to;多条并存保持原拒绝。
4
+ import { afterAll, beforeEach, describe, expect, test } from "bun:test";
5
+ import { db, uuidv4 } from "./db.js";
6
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
7
+ import { registerTools } from "./tools.js";
8
+
9
+ const NET = "net_4315";
10
+ const SENDER = "sender-4315";
11
+ const NODE_ALIAS = "node-4315";
12
+ const NODE_ID = "node_4315_x";
13
+ const TOKEN_ID = "tok_4315_x";
14
+ const USER = "u4315";
15
+
16
+ function reset() {
17
+ for (const t of ["tasks", "inbox", "task_events"]) {
18
+ try { db.run(`DELETE FROM ${t} WHERE network_id = ?1`, [NET]); } catch {}
19
+ }
20
+ try { db.run("DELETE FROM sessions WHERE network_id = ?1", [NET]); } catch {}
21
+ try { db.run("DELETE FROM nodes WHERE network_id = ?1", [NET]); } catch {}
22
+ }
23
+
24
+ function seed() {
25
+ reset();
26
+ db.run(
27
+ `INSERT INTO nodes (node_id, node_name, alias, network_id, created_at) VALUES (?1, ?2, ?2, ?3, datetime('now'))`,
28
+ [NODE_ID, NODE_ALIAS, NET],
29
+ );
30
+ try { db.run("DELETE FROM users WHERE user_id = ?1", [USER]); } catch {}
31
+ db.run(`INSERT INTO users (user_id, username, password_hash, role, created_at) VALUES (?1, ?1, 'x', 'user', datetime('now'))`, [USER]);
32
+ try { db.run("DELETE FROM api_tokens WHERE token_id = ?1", [TOKEN_ID]); } catch {}
33
+ db.run(
34
+ `INSERT INTO api_tokens (token_id, token_hash, user_id, network_id, name, scope, bound_node_id, node_identity_epoch)
35
+ VALUES (?1, 'h4315', ?2, ?3, ?4, 'network', ?5, 2)`,
36
+ [TOKEN_ID, USER, NET, `node:${NODE_ALIAS}`, NODE_ID],
37
+ );
38
+ }
39
+
40
+ function makeTask(status: string, content: string): string {
41
+ const id = uuidv4();
42
+ db.run(
43
+ `INSERT INTO tasks (task_id, from_name, to_name, priority, status, content, requires_response, created_at, network_id)
44
+ VALUES (?1, ?2, ?3, 'normal', ?4, ?5, 'reply', datetime('now'), ?6)`,
45
+ [id, SENDER, NODE_ALIAS, status, content, NET],
46
+ );
47
+ return id;
48
+ }
49
+
50
+ function buildNodeTokenTools() {
51
+ const server = new McpServer({ name: "t", version: "0" }) as any;
52
+ const tools: Record<string, any> = {};
53
+ const orig = server.tool.bind(server);
54
+ server.tool = (name: string, desc: string, schema: any, handler: any) => {
55
+ tools[name] = handler;
56
+ return orig(name, desc, schema, handler);
57
+ };
58
+ // bound_node_id 就是「这台节点」——推断靠它定位手上的任务
59
+ registerTools(server, undefined, NET, null, NODE_ALIAS, true, TOKEN_ID);
60
+ return tools;
61
+ }
62
+
63
+ const call = async (h: any, args: any) =>
64
+ JSON.parse((await h(args)).content[0].text);
65
+
66
+ describe("#4315 裸回执的单候选推断", () => {
67
+ beforeEach(seed);
68
+
69
+ test("恰好一条在手任务 ⇒ 推断 in_reply_to,任务被正常结束(不再留 expired)", async () => {
70
+ const tools = buildNodeTokenTools();
71
+ const t = makeTask("delivered", "x4315 single open task");
72
+ const r = await call(tools["send_reply"], { text: "done, single open task" });
73
+ expect(r.ok).toBe(true);
74
+ const row = db.get<{ status: string }>("SELECT status FROM tasks WHERE task_id = ?1", t);
75
+ expect(row?.status).toBe("replied");
76
+ });
77
+
78
+ test("两条在手任务 ⇒ 不推断,仍按原样拒绝(宁可拒绝也不赌对象)", async () => {
79
+ const tools = buildNodeTokenTools();
80
+ makeTask("delivered", "x4315 open A");
81
+ makeTask("delivered", "x4315 open B");
82
+ const r = await call(tools["send_reply"], { text: "ambiguous" });
83
+ expect(r.ok).toBe(false);
84
+ expect(r.error).toBe("reply_target_required");
85
+ });
86
+ });