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

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.
@@ -36,17 +36,23 @@ export type NodePermissionReason =
36
36
  * 这类令牌**没有 nodes 行**,两张白名单都管不到它;先按「记录」模式跑,看有多少。 */
37
37
  | "unbound_token"
38
38
  /** #2969 续 —— 主人在这个节点的 REST 白名单里没有列这条写路由。 */
39
- | "rest_not_allowed";
39
+ | "rest_not_allowed"
40
+ /** 收件白名单 —— **目标**节点的主人设了收件白名单,发件人不在名单上。判的是收件方,不是调用方。 */
41
+ | "sender_not_allowed";
40
42
 
41
43
  /** 显式模式的原因:不看开关,永远拒。 */
42
44
  // 白名单和 readonly/restricted 同类:**主人主动设的,设了就立刻生效**,不看开关。
43
- const MODE_REASONS: ReadonlySet<NodePermissionReason> = new Set(["mode_readonly", "mode_restricted_not_assigned", "peer_not_allowed", "tool_not_allowed", "rest_not_allowed"]);
45
+ const MODE_REASONS: ReadonlySet<NodePermissionReason> = new Set(["mode_readonly", "mode_restricted_not_assigned", "peer_not_allowed", "tool_not_allowed", "rest_not_allowed", "sender_not_allowed"]);
44
46
 
45
47
  // #2969 —— 节点级对端白名单:JSON 数组(alias 或 node_id);NULL = 不限制。
46
48
  // 只增不改:旧代码不读这一列;设为 NULL 时行为与现在完全一致。
47
49
  // #2969 后半 —— 接口白名单:JSON 数组(MCP 工具名);NULL = 不限制。
48
50
  // #2969 续 —— REST 写接口白名单:JSON 数组(形如 "POST /api/task");NULL = 不限制。
49
51
  // 只对**节点令牌的写方法**生效(GET / SSE 永不经过它,否则节点会变聋)。
52
+ // 收件白名单:JSON 数组(alias / node_id / user:<username|user_id> / user:* / !strict);NULL = 谁都能发。
53
+ try { db.exec("ALTER TABLE nodes ADD COLUMN inbox_allowlist TEXT"); } catch (e: any) {
54
+ if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
55
+ }
50
56
  try { db.exec("ALTER TABLE nodes ADD COLUMN rest_allowlist TEXT"); } catch (e: any) {
51
57
  if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
52
58
  }
@@ -304,6 +310,7 @@ const HINTS: Record<NodePermissionReason, string> = {
304
310
  tool_not_allowed: "this node is limited to an explicit tool allowlist; this tool is not on it — ask the node's owner to add it, or clear the allowlist",
305
311
  unbound_token: "this token does not resolve to a node (usually the node was renamed and the token was not); rename or bind the token, or issue a node-bound token",
306
312
  rest_not_allowed: "this node is limited to an explicit REST write allowlist; this route is not on it — ask the node's owner to add it, or clear the allowlist",
313
+ sender_not_allowed: "the target node only accepts tasks and messages from an explicit inbox allowlist and you are not on it — ask the target node's owner to add you (alias, node_id, or user:<username>), or clear its inbox allowlist",
307
314
  };
308
315
 
309
316
  export function nodePermissionDeniedBody(reason: NodePermissionReason, route: string): { ok: false; error: "node_permission_denied"; reason: NodePermissionReason; route: string; hint: string } {
@@ -400,6 +407,130 @@ export function broadcastVerdict(id: NodeIdentity): Verdict {
400
407
  return null;
401
408
  }
402
409
 
410
+ // ── 收件白名单(接收侧) ──
411
+ //
412
+ // 上面几条判的都是**调用方**能不能发;这里判**收件方**愿不愿意收。两边独立、都要过。
413
+ // 名单条目:
414
+ // alias / node_id → 匹配 Agent 发件人(节点令牌)
415
+ // user:<username|user_id> → 匹配人(Dashboard / 桌面端的用户令牌);user:* = 任何人
416
+ // !strict → 关掉下面的隐式放行
417
+ // 隐式放行(没有 !strict 时):节点主人、网络 owner/admin、Hub 管理员、旧的无身份调用(open/legacy 模式,
418
+ // 本来就「谁都是谁」,名单在那里无从判起)。目的:主人设名单时不会把自己锁在门外。
419
+ // 节点发给自己永远放行(含 !strict)。
420
+ export const INBOX_STRICT_ENTRY = "!strict";
421
+
422
+ export type InboxSender =
423
+ | { kind: "node"; nodeId: string | null; aliases: string[] }
424
+ | { kind: "user"; userId: string; username: string | null; isHubAdmin?: boolean }
425
+ | { kind: "legacy" };
426
+
427
+ /** 从调用方的令牌上下文得出发件人(REST 与 MCP 共用,免得两边口径漂)。 */
428
+ export function inboxSenderFromAuth(auth: { isNodeToken: boolean; tokenId: string | null; boundNetworkId: string | null; userId: string | null; username: string | null }): InboxSender {
429
+ if (auth.isNodeToken) {
430
+ const id = auth.boundNetworkId ? nodeIdentity(auth.tokenId, auth.boundNetworkId) : null;
431
+ return { kind: "node", nodeId: id?.nodeId ?? null, aliases: id?.aliases ?? [] };
432
+ }
433
+ if (auth.userId) {
434
+ const isHubAdmin = db.get<{ role: string | null }>("SELECT role FROM users WHERE user_id = ?1", auth.userId)?.role === "admin";
435
+ return { kind: "user", userId: auth.userId, username: auth.username, isHubAdmin };
436
+ }
437
+ return { kind: "legacy" };
438
+ }
439
+
440
+ export function inboxSenderLabel(sender: InboxSender): string {
441
+ if (sender.kind === "node") return sender.aliases[0] ?? (sender.nodeId ? `node:${sender.nodeId}` : "node:?");
442
+ if (sender.kind === "user") return `user:${sender.username ?? sender.userId}`;
443
+ return "legacy";
444
+ }
445
+
446
+ type InboxTargetRow = { node_id: string; alias: string | null; owner_user_id: string | null; inbox_allowlist: string | null };
447
+
448
+ function inboxTargetRow(networkId: string | null, target: AgentRef): InboxTargetRow | null {
449
+ if (target.nodeId) {
450
+ const row = db.get<InboxTargetRow>(
451
+ "SELECT node_id, alias, owner_user_id, inbox_allowlist FROM nodes WHERE node_id = ?1", target.nodeId);
452
+ if (row) return row;
453
+ }
454
+ if (target.alias && networkId) {
455
+ return db.get<InboxTargetRow>(
456
+ "SELECT node_id, alias, owner_user_id, inbox_allowlist FROM nodes WHERE alias = ?1 AND network_id = ?2 LIMIT 1", target.alias, networkId);
457
+ }
458
+ return null;
459
+ }
460
+
461
+ /** 纯判定(不记账):名单 + 发件人 → 放不放行。 */
462
+ export function inboxAllows(
463
+ list: string[] | null,
464
+ sender: InboxSender,
465
+ ctx: { targetNodeId: string; targetAlias: string | null; ownerUserId: string | null; networkId: string | null },
466
+ ): boolean {
467
+ if (!list) return true;
468
+ if (sender.kind === "node") {
469
+ 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));
471
+ }
472
+ const strict = list.includes(INBOX_STRICT_ENTRY);
473
+ if (sender.kind === "legacy") return !strict;
474
+ if (!strict) {
475
+ if (sender.isHubAdmin) return true;
476
+ if (ctx.ownerUserId && sender.userId === ctx.ownerUserId) return true;
477
+ if (ctx.networkId) {
478
+ const role = db.get<{ role: string }>("SELECT role FROM network_members WHERE network_id = ?1 AND user_id = ?2", ctx.networkId, sender.userId)?.role;
479
+ if (role === "owner" || role === "admin") return true;
480
+ }
481
+ }
482
+ return list.includes("user:*")
483
+ || list.includes(`user:${sender.userId}`)
484
+ || (!!sender.username && list.includes(`user:${sender.username}`));
485
+ }
486
+
487
+ export type InboxDenial = ReturnType<typeof nodePermissionDeniedBody> & { target: string; sender: string };
488
+
489
+ /**
490
+ * 发往 target 之前判一次收件白名单。放行 → null;拒绝 → 拒绝体(REST 403 / MCP 文本同形),
491
+ * 并按**目标节点**记一行 node_permission_log(主人在报表里能看到谁被挡在门外)。
492
+ */
493
+ export function inboxDenied(networkId: string | null, target: AgentRef, sender: InboxSender, route: string): InboxDenial | null {
494
+ const row = inboxTargetRow(networkId, target);
495
+ if (!row) return null;
496
+ const list = normalizePeerAllowlist(row.inbox_allowlist);
497
+ if (!list) return null;
498
+ if (inboxAllows(list, sender, { targetNodeId: row.node_id, targetAlias: row.alias ?? target.alias, ownerUserId: row.owner_user_id, networkId })) return null;
499
+ const senderLabel = inboxSenderLabel(sender);
500
+ const targetLabel = row.alias ?? target.alias ?? row.node_id;
501
+ if (networkId) {
502
+ recordNodePermission({
503
+ networkId, nodeId: row.node_id, logKey: row.node_id, aliases: row.alias ? [row.alias] : [], ownerUserId: row.owner_user_id,
504
+ mode: "normal", peerAllowlist: null, toolAllowlist: null, restAllowlist: null,
505
+ }, route, "sender_not_allowed", senderLabel);
506
+ }
507
+ return { ...nodePermissionDeniedBody("sender_not_allowed", route), target: targetLabel, sender: senderLabel };
508
+ }
509
+
510
+ export type InboxSkipped = { alias: string; node_id: string | null; reason: "sender_not_allowed" };
511
+
512
+ /**
513
+ * 广播:收件白名单不收这个发件人的收件人**跳过**(不让整条广播失败),并报告给调用方。
514
+ * 快路径:全库没有任何节点设收件白名单时一次查询就返回,不逐个判。
515
+ */
516
+ export function filterBroadcastByInbox<T extends { alias: string; node_id: string | null; network_id: string | null }>(
517
+ targets: readonly T[], effectiveNetId: string | null, sender: InboxSender, route: string,
518
+ ): { allowed: T[]; skipped: InboxSkipped[] } {
519
+ if (!targets.length || !db.get("SELECT 1 AS ok FROM nodes WHERE inbox_allowlist IS NOT NULL LIMIT 1")) {
520
+ return { allowed: [...targets], skipped: [] };
521
+ }
522
+ const allowed: T[] = [];
523
+ const skipped: InboxSkipped[] = [];
524
+ for (const t of targets) {
525
+ if (inboxDenied(effectiveNetId ?? t.network_id ?? null, { alias: t.alias, nodeId: t.node_id }, sender, route)) {
526
+ skipped.push({ alias: t.alias, node_id: t.node_id ?? null, reason: "sender_not_allowed" });
527
+ } else {
528
+ allowed.push(t);
529
+ }
530
+ }
531
+ return { allowed, skipped };
532
+ }
533
+
403
534
  /** 一般的写(管节点、提交技能、探测模型…):只读 / 受限拒;正常放行(由各自的既有规则管)。 */
404
535
  export function writeVerdict(id: NodeIdentity, sample?: string): Verdict {
405
536
  if (id.mode === "readonly") return { reason: "mode_readonly", sample };
@@ -168,7 +168,7 @@ describe("requirements_comment", () => {
168
168
  const lines = raw.split("\n").filter(x => x.startsWith("data:"));
169
169
  const tools = (lines.length ? JSON.parse(lines.at(-1)!.slice(5).trim()) : JSON.parse(raw)).result.tools as any[];
170
170
  const byName = new Map(tools.map(t => [t.name, t]));
171
- expect(String(byName.get("requirements_comment")?.description)).toContain("append-only");
171
+ expect(String(byName.get("requirements_comment")?.description)).toMatch(/append-only/i);
172
172
  expect(String(byName.get("requirements_events")?.description)).toContain("kind=comment");
173
173
  });
174
174
  });
@@ -207,14 +207,14 @@ describe("tool descriptions", () => {
207
207
  const tools = (await rpc(U.nodeA.token, "tools/list", {})).result.tools as any[];
208
208
  const byName = new Map(tools.map(t => [t.name, t]));
209
209
  const update = byName.get("requirements_update");
210
- expect(update.description).toContain("REPLACES the whole list");
210
+ expect(update.description).toMatch(/participants REPLACES the (whole )?list/);
211
211
  expect(update.inputSchema.properties.participants.description).toContain("REPLACES");
212
212
  expect(Object.keys(update.inputSchema.properties)).toEqual(expect.arrayContaining(["status", "participants_add", "participants_remove"]));
213
213
  // #478:节点令牌的 tools/list 里本来就没有 projects_create / projects_update(调了也是 403),那两条的说明从人的列表里读。
214
214
  expect(byName.has("projects_create")).toBe(false);
215
215
  const human = new Map(((await rpc(U.member.token, "tools/list", {})).result.tools as any[]).map(t => [t.name, t]));
216
- expect(byName.get("projects_list").description).toMatch(/node (?:\(Agent\) )?tokens can only read projects/i);
217
- for (const name of ["projects_create", "projects_update"]) expect(human.get(name).description).toMatch(/node (?:\(Agent\) )?tokens can only read projects/i);
216
+ expect(byName.get("projects_list").description).toMatch(/node (?:\(Agent\) )?tokens (?:can only read projects|read only)/i);
217
+ for (const name of ["projects_create", "projects_update"]) expect(human.get(name).description).toMatch(/node (?:\(Agent\) )?tokens (?:can only read projects|read only)/i);
218
218
  const denied = await mcp(U.nodeA.token, "projects_create", { name: "示例项目" });
219
219
  expect(denied.status).toBe(403);
220
220
  expect(denied.error).toBe("user_token_required");
@@ -9,7 +9,7 @@ import { assertNodeHealthy } from "./node-health-guard.js";
9
9
  import { nodeCanAcceptDispatch } from "./node-serviceability.js";
10
10
  import { addNetworkScope, canRestWriteNetwork, singleNetworkId, type RestNetworkScope } from "./network-scope.js";
11
11
  import { canMessageAgent, type AgentRef } from "./agent-access.js";
12
- import { dispatchVerdict } from "./node-permissions.js";
12
+ import { dispatchVerdict, inboxDenied, type InboxSender } from "./node-permissions.js";
13
13
  import { hasSubscribers, pushEvent, pushNetworkObserverEvent } from "./push.js";
14
14
  import { SCHEDULED_TASK_STORAGE_SELECT } from "./rest-projections.js";
15
15
  import { blockerTimedOut, blockerTimeoutClock, expireStuckBlocker, sendStuckNotice, skipsBlockedBy, stuckNoticeSkips, stuckTimeoutMs, type StuckNotice } from "./scheduled-stuck.js";
@@ -403,6 +403,22 @@ function agentCreatorDenial(row: ScheduledRow, target: AgentRef): { code: string
403
403
  return null;
404
404
  }
405
405
 
406
+ /** 目标节点的收件白名单每次触发都按「建排程的人 / 节点」现判一次(名单可能在排程建好之后才设)。 */
407
+ function creatorInboxDenial(row: ScheduledRow, target: AgentRef): { code: string; message: string } | null {
408
+ let sender: InboxSender;
409
+ if (row.created_by_node_id) {
410
+ const alias = db.get<{ alias: string | null }>("SELECT alias FROM nodes WHERE node_id = ?1 AND network_id = ?2", row.created_by_node_id, row.network_id)?.alias;
411
+ sender = { kind: "node", nodeId: row.created_by_node_id, aliases: alias ? [alias] : [] };
412
+ } else if (row.created_by) {
413
+ const user = db.get<{ username: string | null; role: string | null }>("SELECT username, role FROM users WHERE user_id = ?1", row.created_by);
414
+ sender = { kind: "user", userId: row.created_by, username: user?.username ?? null, isHubAdmin: user?.role === "admin" };
415
+ } else {
416
+ sender = { kind: "legacy" };
417
+ }
418
+ const denial = inboxDenied(row.network_id, target, sender, "schedule:dispatch");
419
+ return denial ? { code: "sender_not_allowed", message: `The target agent's inbox allowlist does not accept the schedule creator (${denial.sender})` } : null;
420
+ }
421
+
406
422
  type DispatchEvent = { alias: string; networkId: string; taskId: string; priority: string; state: "delivered" | "queued" };
407
423
 
408
424
  export function dispatchScheduledOccurrence(row: ScheduledRow, scheduledFor: string, advanceSchedule: boolean, advanceAfter = new Date()): { runId: string; taskId?: string; status: string; event?: DispatchEvent } {
@@ -574,11 +590,11 @@ export function dispatchScheduledOccurrence(row: ScheduledRow, scheduledFor: str
574
590
  // 给目标 Agent 发任务时,不再代他派发(否则受限前建的排程会永远绕过授权)。
575
591
  // Board #733 — an Agent-created schedule is that node's standing send_task: every run re-evaluates the
576
592
  // creating node as it is NOW (exists, not read-only, current owner) with send_task's own dispatchVerdict.
577
- const creatorDenial = row.created_by_node_id
593
+ const creatorDenial = (row.created_by_node_id
578
594
  ? agentCreatorDenial(row, { alias: node.alias, nodeId: node.node_id })
579
595
  : row.created_by && !canMessageAgent(row.created_by, row.network_id, { alias: node.alias, nodeId: node.node_id })
580
596
  ? { code: "creator_access_revoked", message: "The schedule creator is no longer allowed to message this agent" }
581
- : null;
597
+ : null) ?? creatorInboxDenial(row, { alias: node.alias, nodeId: node.node_id });
582
598
  if (creatorDenial) {
583
599
  finalStatus = "failed";
584
600
  db.run(
package/src/server.ts CHANGED
@@ -54,7 +54,7 @@ import { dmParticipantSeesFile, listDmThread, listDmThreads, sendHumanDm } from
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
56
  import { canMessageAgent, isAgentRestricted, visibleAgents, listAgentGrants, listGroupGrants, getAgentAccessMode, replaceAgentGrants, restrictedNetworkIds, usernameIsAgentAlias, listAgentGroups, createAgentGroup, updateAgentGroup, replaceAgentGroupMembers, deleteAgentGroup, usersGrantedGroup, listDepartmentGrants, departmentCoverage } from "./agent-access.js";
57
- import { broadcastVerdict, dispatchVerdict, humanOnlyVerdict, NODE_PERMISSION_MODES, nodeDecide, nodeIdentity, nodePermissionDeniedBody, nodePermissionsFlag, streamVerdict, writeVerdict, type NodeIdentity, type NodePermissionMode, type Verdict } from "./node-permissions.js";
57
+ import { broadcastVerdict, dispatchVerdict, filterBroadcastByInbox, humanOnlyVerdict, inboxDenied, inboxSenderFromAuth, NODE_PERMISSION_MODES, nodeDecide, nodeIdentity, nodePermissionDeniedBody, nodePermissionsFlag, streamVerdict, writeVerdict, type InboxSender, 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";
60
60
  import { daemonDefaultWorkdirRoot } from "./create-node-validate.js";
@@ -216,7 +216,9 @@ const SERVER_VERSION_SOURCE = RESOLVED_VERSION.source;
216
216
  // PUT /api/nodes/:id/permission-mode 与 GET /api/networks/:id/node-permission-report 可用(RFC-041 第一阶段)。
217
217
  // chat_groups(RFC-042,#457):部门群可用 —— …/departments/:dept/group、…/chat-groups(资料 / 成员 / 消息 / 已读)、
218
218
  // GET /api/dm/threads 的 group_threads;群对象带 viewer_can {manage, post},会话行带 last_message 预览,成员带 username / display_name。
219
- export const HUB_HEALTH_CAPABILITIES = ["status_node_id", "node_permission_mode", "chat_groups"] as const;
219
+ // node_inbox_allowlist:收件白名单可用 —— PUT /api/nodes/:id/inbox-allowlist { senders },GET /api/nodes 每行带 inbox_allowlist,
220
+ // 被挡的派活回 reason=sender_not_allowed,广播回 inbox_skipped(有人被跳过时才出现,没人被跳过时回执与以前逐字节相同)。
221
+ export const HUB_HEALTH_CAPABILITIES = ["status_node_id", "node_permission_mode", "chat_groups", "node_inbox_allowlist"] as const;
220
222
 
221
223
  // In-memory log ring buffer — last N lines streamed via /api/server-logs.
222
224
  // Wraps console.log/info/warn/error so EVERY existing log call lands here
@@ -478,6 +480,13 @@ function restNodeDenied(req: Request, restAuth: { networkId: string | null; toke
478
480
  const verdict = verdictOf(id);
479
481
  return nodeDecide(id, route, verdict) ? withCors(req, Response.json(nodePermissionDeniedBody(verdict!.reason, route), { status: 403 })) : null;
480
482
  }
483
+ /** 收件白名单的发件人:网络绑定令牌 = 节点;用户令牌 = 人;没有身份 = legacy。 */
484
+ function restInboxSender(_req: Request, restAuth: { networkId: string | null; tokenId: string | null; userId?: string | null; username?: string | null } | null): InboxSender {
485
+ return inboxSenderFromAuth({
486
+ isNodeToken: !!restAuth?.networkId, tokenId: restAuth?.tokenId ?? null, boundNetworkId: restAuth?.networkId ?? null,
487
+ userId: restAuth?.userId ?? null, username: restAuth?.username ?? null,
488
+ });
489
+ }
481
490
  /** 写别的节点 = 只有人能做;写自己 = 只看模式。 */
482
491
  const nodeTargetVerdict = (targetNodeId: string) => (id: NodeIdentity): Verdict =>
483
492
  id.nodeId && id.nodeId === targetNodeId ? writeVerdict(id, targetNodeId) : humanOnlyVerdict(id, targetNodeId);
@@ -4352,6 +4361,45 @@ return Bun.serve({
4352
4361
  logAudit(restAuth.userId, restAuth.username, "node_peer_allowlist_changed", "node", node2.node_id, JSON.stringify({ from: node2.peer_allowlist, to: nextValue }), getClientIP(req), node2.network_id);
4353
4362
  return withCors(req, Response.json({ ok: true, node_id: node2.node_id, peers: peers.length ? peers : null }));
4354
4363
  }
4364
+ // 收件白名单:PUT /api/nodes/:id/inbox-allowlist { senders: string[] | null }
4365
+ // 与 peer-allowlist 同一套授权、审计与空数组语义(拒收 [],清空请传 null)。
4366
+ // 条目语法与发件人匹配规则见 node-permissions.ts「收件白名单」。
4367
+ const inboxAllowMatch = url.pathname.match(/^\/api\/nodes\/([^/]+)\/inbox-allowlist$/);
4368
+ if (inboxAllowMatch && req.method === "PUT") {
4369
+ if (!restAuth) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
4370
+ if (restAuth.networkId) return userTokenRequired(req);
4371
+ let body: any;
4372
+ try { body = await req.json(); } catch { return withCors(req, Response.json({ ok: false, error: "invalid_json" }, { status: 400 })); }
4373
+ const rawSenders = body?.senders;
4374
+ if (rawSenders !== null && rawSenders !== undefined && !Array.isArray(rawSenders)) {
4375
+ return withCors(req, Response.json({ ok: false, error: "invalid_senders", message: "senders must be an array of alias / node_id / user:<username> strings, or null" }, { status: 400 }));
4376
+ }
4377
+ const senders = Array.isArray(rawSenders)
4378
+ ? rawSenders.filter((x: unknown): x is string => typeof x === "string" && x.trim().length > 0).map((x: string) => x.trim())
4379
+ : [];
4380
+ if (Array.isArray(rawSenders) && senders.length === 0) {
4381
+ return withCors(req, Response.json({
4382
+ ok: false,
4383
+ error: "empty_allowlist_ambiguous",
4384
+ message: "send null to clear the allowlist (no restriction); an empty array is ambiguous and is rejected",
4385
+ }, { status: 400 }));
4386
+ }
4387
+ if (senders.length > 200) {
4388
+ return withCors(req, Response.json({ ok: false, error: "too_many_senders", message: "at most 200 entries" }, { status: 400 }));
4389
+ }
4390
+ const nodeRef5 = decodeURIComponent(inboxAllowMatch[1]);
4391
+ const node5 = db.get<{ node_id: string; network_id: string | null; owner_user_id: string | null; inbox_allowlist: string | null }>(
4392
+ "SELECT node_id, network_id, owner_user_id, inbox_allowlist FROM nodes WHERE node_id = ?1", nodeRef5);
4393
+ const role5 = node5?.network_id ? getUserNetworkRole(restAuth.userId, node5.network_id) : null;
4394
+ if (!node5 || !node5.network_id || (!role5 && !isAdmin)) return withCors(req, Response.json({ ok: false, error: "node_not_found" }, { status: 404 }));
4395
+ if (!canRestWriteNodeSecurity(restAuth, node5.owner_user_id, role5, isAdmin)) {
4396
+ return withCors(req, Response.json({ ok: false, error: "permission_denied", message: "only the node's owner or a network owner/admin can change its inbox allowlist" }, { status: 403 }));
4397
+ }
4398
+ const nextSenders = senders.length ? JSON.stringify(senders) : null;
4399
+ db.run("UPDATE nodes SET inbox_allowlist = ?1 WHERE node_id = ?2", [nextSenders, node5.node_id]);
4400
+ logAudit(restAuth.userId, restAuth.username, "node_inbox_allowlist_changed", "node", node5.node_id, JSON.stringify({ from: node5.inbox_allowlist, to: nextSenders }), getClientIP(req), node5.network_id);
4401
+ return withCors(req, Response.json({ ok: true, node_id: node5.node_id, senders: senders.length ? senders : null }));
4402
+ }
4355
4403
  const permReportMatch = url.pathname.match(/^\/api\/networks\/([^/]+)\/node-permission-report$/);
4356
4404
  if (permReportMatch && req.method === "GET") {
4357
4405
  if (!restAuth) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
@@ -5766,6 +5814,8 @@ return Bun.serve({
5766
5814
  ...(canonical.renamed ? { renamed_from: body.alias, renamed_to: targetAlias } : {}),
5767
5815
  }, { status: 404 })));
5768
5816
  }
5817
+ const inboxRefused = inboxDenied(taskNetId ?? null, { alias: targetAlias, nodeId: target.session?.node_id ?? null }, restInboxSender(req, restAuth), "POST /api/task");
5818
+ if (inboxRefused) return reject(withCors(req, Response.json(inboxRefused, { status: 403 })));
5769
5819
  // Identity binding, mirroring the MCP transport (tools.ts defaultFrom /
5770
5820
  // fromIdentityMismatchReply). Both transports resolve the same
5771
5821
  // api_tokens row through resolveToken, and auth.ts already documents the
@@ -6025,14 +6075,15 @@ return Bun.serve({
6025
6075
  sql = addNetworkScope(sql, params, restScope);
6026
6076
  if (body.filter_server) { sql += " AND server = ?"; params.push(body.filter_server); }
6027
6077
  if (body.filter_status) { sql += " AND status = ?"; params.push(body.filter_status); }
6028
- const targets = db.all<{ alias: string; node_id: string | null; network_id: string | null }>(sql, ...params);
6078
+ const allTargets = db.all<{ alias: string; node_id: string | null; network_id: string | null }>(sql, ...params);
6079
+ const { allowed: targets, skipped: inboxSkipped } = filterBroadcastByInbox(allTargets, restScope.networkId ?? null, restInboxSender(req, restAuth), "POST /api/broadcast");
6029
6080
  // #2721 —— 与 MCP broadcast 同一条分批路径(reason 见 broadcast-fanout.ts 顶部)。
6030
6081
  const { ids } = await enqueueBroadcast(targets, body.message, "api", null, {
6031
6082
  // RFC-027 §2.3 inbox-enqueue lifecycle guard (PR1.2a REST site 2/2).
6032
6083
  isActive: (alias, netId) => assertNodeActive(alias, netId).ok,
6033
6084
  notify: (alias, netId) => pushEvent(alias, { type: "broadcast", inbox_count: pendingInboxCount(alias, netId) }, netId),
6034
6085
  });
6035
- return withCors(req, Response.json({ ok: true, recipients: ids.length, message_ids: ids }));
6086
+ return withCors(req, Response.json({ ok: true, recipients: ids.length, message_ids: ids, ...(inboxSkipped.length ? { inbox_skipped: inboxSkipped } : {}) }));
6036
6087
  }
6037
6088
 
6038
6089
  // ── REST: tmux capture-pane ──
@@ -6944,7 +6995,7 @@ return Bun.serve({
6944
6995
  network_id, created_at, updated_at,
6945
6996
  config_snapshot, lifecycle_state, avatar_url,
6946
6997
  display_name, team, tags, attrs_revision, permission_mode, owner_user_id,
6947
- department_id, peer_allowlist, tool_allowlist, rest_allowlist
6998
+ department_id, peer_allowlist, tool_allowlist, rest_allowlist, inbox_allowlist
6948
6999
  FROM nodes WHERE 1=1`;
6949
7000
  const params: any[] = [];
6950
7001
  sql = addAgentNetworkScope(sql, params, restScope, { alias: "alias", nodeId: "node_id" });
@@ -7101,6 +7152,11 @@ return Bun.serve({
7101
7152
  let opencodeGeneration: "v1" | "v2" | null = null;
7102
7153
  let opencodeMode: string | null = null;
7103
7154
  let opencodeServer: string | null = null;
7155
+ // 2026-11-10 —— 起这台节点的 anet CLI 版本。**声明在 `if (snap)` 外面**:
7156
+ // 下面的投影对每一行都会求值,块内 `let` 会让部署后的 /api/nodes 直接抛
7157
+ // "launchedByCliVersion is not defined"(#4150-Build 的 opencodeAgents 踩过同一次)。
7158
+ // null = 节点没报(老节点 / 不是 CLI 起的,如 daemon adopt 出来的子节点)。
7159
+ let launchedByCliVersion: string | null = null;
7104
7160
  const snap = r.config_snapshot;
7105
7161
  // #4150-Build — declared outside the `if (snap)` block: the projection below is
7106
7162
  // evaluated for every row, and a block-scoped `let` here made /api/nodes throw
@@ -7108,6 +7164,9 @@ return Bun.serve({
7108
7164
  let opencodeAgents: string[] | null = null;
7109
7165
  let opencodeAgentsSeenAt: string | null = null;
7110
7166
  let opencodeAgentCurrent: string | null = null;
7167
+ // 与 GET /api/nodes/:id/config 保持同一口径:列表里也要能读到「能不能切 agent」,
7168
+ // 否则两个端点对同一台节点会给出不一致的能力结论。
7169
+ let opencodeAgentConfigCapable = false;
7111
7170
  if (snap) {
7112
7171
  let parsed: any = null;
7113
7172
  try { parsed = typeof snap === "string" ? JSON.parse(snap) : snap; }
@@ -7139,14 +7198,21 @@ return Bun.serve({
7139
7198
  if (typeof rawAgentCurrent === "string" && rawAgentCurrent.length > 0 && rawAgentCurrent.length <= 200) {
7140
7199
  opencodeAgentCurrent = rawAgentCurrent;
7141
7200
  }
7201
+ opencodeAgentConfigCapable = parsed?.opencode_agent_config_capable === true;
7142
7202
  const flags = parsed?.flags;
7143
7203
  if (flags?.opencodeGeneration === "v1" || flags?.opencodeGeneration === "v2") opencodeGeneration = flags.opencodeGeneration;
7144
7204
  if (typeof flags?.opencodeMode === "string" && flags.opencodeMode.length <= 32) opencodeMode = flags.opencodeMode;
7145
7205
  if (typeof parsed?.opencode_server === "string" && parsed.opencode_server.length <= 200) opencodeServer = parsed.opencode_server;
7206
+ // 2026-11-10 —— 只做投影:节点报了就给出来,没报就是 null(两种成因见上面的注释)。
7207
+ // 形状再校验一遍:schema 那层已经限了 64 字符,但库里的历史行不受 schema 管。
7208
+ const rawLaunchedBy = parsed?.launched_by_cli_version;
7209
+ if (typeof rawLaunchedBy === "string" && rawLaunchedBy.length > 0 && rawLaunchedBy.length <= 64) {
7210
+ launchedByCliVersion = rawLaunchedBy;
7211
+ }
7146
7212
  }
7147
7213
  // #2969 —— 两张白名单原来**只能写不能读**(PUT 有了,GET 里没有),
7148
7214
  // 客户端因此做不出「当前设置」这一屏。这里把原始列解构出来,下面换成解析后的数组。
7149
- const { config_snapshot, owner_user_id, peer_allowlist, tool_allowlist, rest_allowlist, ...rest } = r;
7215
+ const { config_snapshot, owner_user_id, peer_allowlist, tool_allowlist, rest_allowlist, inbox_allowlist, ...rest } = r;
7150
7216
  // `tags` is stored as JSON text; hand the dashboard a real array so
7151
7217
  // it can map() without a guard, and normalise legacy/absent values
7152
7218
  // to [] rather than null. attrs_revision is normalised to a number
@@ -7163,12 +7229,14 @@ return Bun.serve({
7163
7229
  opencode_catalog: opencodeCatalog,
7164
7230
  opencode_agents: opencodeAgents,
7165
7231
  opencode_agent_current: opencodeAgentCurrent,
7232
+ opencode_agent_config_capable: opencodeAgentConfigCapable,
7166
7233
  opencode_agents_seen_at: opencodeAgentsSeenAt,
7167
7234
  // 见上:null 表示 daemon 未上报;非 null 是它自己给的采集时刻
7168
7235
  opencode_catalog_seen_at: opencodeCatalogSeenAt,
7169
7236
  opencode_generation: opencodeGeneration,
7170
7237
  opencode_mode: opencodeMode,
7171
7238
  opencode_server: opencodeServer,
7239
+ launched_by_cli_version: launchedByCliVersion,
7172
7240
  lifecycle_controllable,
7173
7241
  lifecycle_daemon_node_id: controllable.get(r.node_id) ?? null,
7174
7242
  ...(management ? (management.get(r.node_id) ?? { managed: "none", adoption: null }) : {}),
@@ -7178,6 +7246,8 @@ return Bun.serve({
7178
7246
  tool_allowlist: normalizeToolAllowlist(tool_allowlist),
7179
7247
  // #2969 续 —— REST 写接口白名单(形如 "POST /api/task")。null = 不限制。
7180
7248
  rest_allowlist: normalizePeerAllowlist(rest_allowlist),
7249
+ // 收件白名单(谁能给这个节点派活 / 发消息)。null = 谁都能发。
7250
+ inbox_allowlist: normalizePeerAllowlist(inbox_allowlist),
7181
7251
  // #1510 —— 管理员要能看出「谁的 transport 未知」才敢打开 strict。
7182
7252
  // 这一格**只读**,不参与任何判定(判定在 env-transport-policy.ts)。
7183
7253
  env_transport: envTransportOf(r.node_id, r.alias, r.network_id),
@@ -2,10 +2,11 @@ import { test, expect } from "bun:test";
2
2
  import { Database } from "bun:sqlite";
3
3
  import { mkdtempSync } from "node:fs";
4
4
  import { join } from "node:path";
5
+ import { tmpdir } from "node:os";
5
6
  import { sessionProjectCreateSchema, migrateProjectOperationJournal } from "./session-source-admission-store";
6
7
 
7
8
  test("actual old on-disk journal migrates twice and keeps new-session rows and intent tombstones", () => {
8
- const path = join(mkdtempSync("/work/attach-migration-"), "old.db");
9
+ const path = join(mkdtempSync(join(tmpdir(), "attach-migration-")), "old.db");
9
10
  let sql = new Database(path);
10
11
  sql.exec(sessionProjectCreateSchema);
11
12
  sql.run(`INSERT INTO session_project_creates
@@ -1,5 +1,7 @@
1
+ import { tmpdir } from "node:os";
1
2
  // Opt-in, exact SHA verified patched ELF. No new/fork acceptance rerun.
2
3
  import { test, expect } from "bun:test";
4
+ import { testWorkRoot } from "./test-work-root";
3
5
  import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, symlinkSync, existsSync } from "node:fs";
4
6
  import { join } from "node:path";
5
7
  import { spawn } from "node:child_process";
@@ -12,7 +14,7 @@ import { PROJECT_CREATE_ROOT as P, SESSION_ATTACH_CAPABILITY as CAP } from "../.
12
14
 
13
15
  const delegated = process.env.TEST4150_NATIVE_ATTACH_DERIVED === "1";
14
16
  test.skipIf(!process.env.TEST4150_NATIVE_BINARY)(delegated ? "real patched Linux delegated policy -> one empty existing Session attach, exact CLI registration, zero native mutation" : "real patched Linux existing empty/materialized Session attach, occupied refusal, exact child register and zero attach native writes", async () => {
15
- const root = mkdtempSync("/work/native-attach-"), home = join(root, "home"), project = join(root, "project"), daemonDir = join(root, "daemon");
17
+ const root = mkdtempSync(join(testWorkRoot(), "native-attach-")), home = join(root, "home"), project = join(root, "project"), daemonDir = join(root, "daemon");
16
18
  for (const d of [home, project, daemonDir, join(home, ".anet"), join(project, ".anet"), join(project, ".anet", "nodes"), join(daemonDir, ".anet")]) mkdirSync(d, { mode: 0o700 });
17
19
  process.env.COMMHUB_DB = join(root, "hub.db"); process.env.COMMHUB_SOURCE_DIRECTORY_PREVIEW = "1"; process.env.COMMHUB_SESSION_ATTACH_PREVIEW = "1";
18
20
  delete process.env.COMMHUB_PROJECT_NEW_SESSION_PREVIEW; delete process.env.COMMHUB_SOURCE_FORK_PREVIEW;
@@ -1,4 +1,5 @@
1
1
  import { afterAll, afterEach, beforeAll, beforeEach, expect, setSystemTime, test } from "bun:test";
2
+ import { testWorkRoot } from "./test-work-root";
2
3
  import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, symlinkSync, readdirSync } from "node:fs";
3
4
  import { join } from "node:path";
4
5
  import { tmpdir } from "node:os";
@@ -10,7 +11,7 @@ import { createSourceDirectoryReader } from "../../agent-node/src/runtime/sessio
10
11
  import { createSessionControlPin } from "../../agent-node/src/runtime/session-control-bridge";
11
12
  import { createSessionSourceTransportWorker } from "../../agent-node/src/runtime/session-source-transport";
12
13
 
13
- const root = mkdtempSync(join(tmpdir(), "project-create-http-")); process.env.COMMHUB_DB ||= join(root, "hub.db");
14
+ const root = mkdtempSync(join(testWorkRoot(), "project-create-http-")); process.env.COMMHUB_DB ||= join(root, "hub.db");
14
15
  const gates = ["COMMHUB_SOURCE_DIRECTORY_PREVIEW", "COMMHUB_PROJECT_NEW_SESSION_PREVIEW", "COMMHUB_SESSION_ATTACH_PREVIEW"];
15
16
  const previous = gates.map(g => process.env[g]);
16
17
  const D = "/api/node-session-control/source/directory", serverId = `osrv_${randomUUID()}`;
@@ -268,7 +269,7 @@ test("actual HTTP directory -> project intent -> one native empty create -> exac
268
269
  }, 15000);
269
270
  for (const operation of ["new", "manual", "delegated"]) test(`${operation} HTTP chain uses actual anet CLI -> paired agent-node CLI -> exact shared resume -> actual Hub registration with synthetic native package`, async () => {
270
271
  const attach = operation !== "new";
271
- await worker.stop(); const prefix = mkdtempSync("/work/project-cli-fixture-"); cliFixtureRoot = prefix;
272
+ await worker.stop(); const prefix = mkdtempSync(join(testWorkRoot(), "project-cli-fixture-")); cliFixtureRoot = prefix;
272
273
  const pkg = join(prefix, "node_modules", "@opencode", "cli"); mkdirSync(join(pkg, "bin"), { recursive: true, mode: 0o700 });
273
274
  mkdirSync(join(prefix, "bin"), { mode: 0o700 }); mkdirSync(join(prefix, "safe"), { mode: 0o700 });
274
275
  writeFileSync(join(pkg, "package.json"), JSON.stringify({ name: "@opencode/cli", version: "2.0.22", bin: { opencode: "bin/opencode.exe" } }));
@@ -1,7 +1,9 @@
1
+ import { tmpdir } from "node:os";
1
2
  // Opt-in Docker-only acceptance against the SHA-verified real TEST-ONLY ELF.
2
3
  // No native protocol mock/fake executable or external provider/npm. Fork fixture
3
4
  // may use a deterministic loopback OpenAI-compatible provider via REAL prompt.
4
5
  import { test, expect } from "bun:test";
6
+ import { testWorkRoot } from "./test-work-root";
5
7
  import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, symlinkSync, existsSync } from "node:fs";
6
8
  import { join } from "node:path";
7
9
  import { randomUUID } from "node:crypto";
@@ -15,7 +17,7 @@ import { SOURCE_DELIVERY_CAPABILITY } from "../../contracts/session-source-deliv
15
17
 
16
18
  const forkMode = process.env.TEST4150_NATIVE_FORK === "1";
17
19
  test.skipIf(!process.env.TEST4150_NATIVE_BINARY)(forkMode ? "real patched ELF managed live-source fork, attach refusal and negative-only cleanup" : "real patched 2.0.22 ELF: directory -> project-new -> actual CLI exact child -> native SSE and real Hub registration", async () => {
18
- const root = mkdtempSync("/work/native-project-"), home = join(root, "home"), project = join(root, "project"), daemonDir = join(root, "daemon");
20
+ const root = mkdtempSync(join(testWorkRoot(), "native-project-")), home = join(root, "home"), project = join(root, "project"), daemonDir = join(root, "daemon");
19
21
  for (const d of [home, project, daemonDir, join(home, ".anet"), join(daemonDir, ".anet"), join(project, ".anet"), join(project, ".anet", "nodes")]) mkdirSync(d, { mode: 0o700 });
20
22
  process.env.COMMHUB_DB = join(root, "hub.db"); process.env.COMMHUB_SOURCE_DIRECTORY_PREVIEW = "1"; process.env.COMMHUB_PROJECT_NEW_SESSION_PREVIEW = "1";
21
23
  if (forkMode) process.env.COMMHUB_SOURCE_FORK_PREVIEW = "1";
@@ -94,6 +94,11 @@ export function createSessionSourceDeliveryQueue(executions: ReturnType<typeof c
94
94
  return db.transaction(() => {
95
95
  if (db.run("UPDATE session_source_node_deliveries SET state='registered' WHERE delivery_id=?1 AND state='delivered'", [id]).changes !== 1) return false;
96
96
  db.run("UPDATE api_tokens SET expires_at=NULL WHERE token_id=?1 AND revoked_at IS NULL", [r.token_id]);
97
+ // admin 2026-11-10「fork 开来的节点就是要继承之前的部门的」: the child takes the
98
+ // source node's department, unless someone already placed it explicitly.
99
+ db.run(`UPDATE nodes SET department_id = (SELECT s.department_id FROM nodes s WHERE s.node_id = ?2 AND s.network_id = ?3)
100
+ WHERE node_id = ?1 AND network_id = ?3 AND (department_id IS NULL OR department_id = '')`,
101
+ [r.child_node_id, t.evidence.request.source_node_id, caller.networkId]);
97
102
  return true;
98
103
  });
99
104
  },
@@ -104,7 +104,11 @@ test("actual Hub HTTP -> frozen daemon worker -> native 2.0.22-shaped GET pages
104
104
  });
105
105
  test("HTTP requires human create/source visibility, exact network, explicit daemon capability and secure channel; rejects raw inputs", async () => {
106
106
  await worker.tick();
107
- for (const token of [daemon.token, source.token, outsider.token]) expect((await api(token, "", selection())).status).not.toBe(200);
107
+ // 节点凭据不是 human 凭据 → 403(权限),不是 400(请求)。见 #4467。
108
+ for (const token of [daemon.token, source.token]) expect((await api(token, "", selection())).status).toBe(403);
109
+ expect((await api(outsider.token, "", selection())).status).not.toBe(200);
110
+ // 请求体不合法 → 400,与上面的 403 区分开。
111
+ expect((await api(human.token, "", { ...selection(), extra: 1 })).status).toBe(400);
108
112
  for (const extra of [{ url: "http://127.0.0.1:1" }, { path: project }, { token: "forged" }, { server_id: serverId }, { network_id: "other" }, { daemon_node_id: "dir_source" }]) {
109
113
  expect((await api(human.token, "", { ...selection(), ...extra })).status).not.toBe(200);
110
114
  }
@@ -1,4 +1,5 @@
1
1
  import { afterAll, beforeAll, beforeEach, expect, test } from "bun:test";
2
+ import { testWorkRoot } from "./test-work-root";
2
3
  import { mkdtempSync, mkdirSync, readFileSync, statSync, writeFileSync, chmodSync, chownSync, rmSync, symlinkSync } from "node:fs";
3
4
  import { tmpdir } from "node:os";
4
5
  import { join } from "node:path";
@@ -25,7 +26,7 @@ import { SOURCE_FORK_ROOT, SOURCE_FORK_CAPABILITY } from "../../contracts/sessio
25
26
  let human: ReturnType<typeof register>, daemon: ReturnType<typeof createNetworkTokenForNode>;
26
27
  let source: ReturnType<typeof createNetworkTokenForNode>, selection: SourceSelection;
27
28
  const req = (token?: string) => new Request("http://isolated.invalid", { headers: token ? { authorization: `Bearer ${token}` } : {} });
28
- const root = mkdtempSync(join(tmpdir(), "source-read-")), project = join(root, "project"), daemonDir = join(root, "daemon");
29
+ const root = mkdtempSync(join(testWorkRoot(), "source-read-")), project = join(root, "project"), daemonDir = join(root, "daemon");
29
30
  const nodeDir = join(project, ".anet", "nodes", "source");
30
31
  let version = "2.0.22", sessionDirectory = project, sessionId = "ses_Selected", authGate = true, redirect = false, large = false;
31
32
  let forkPosts = 0, loseForkResponse = false, busy = false, busyDelivery = "";
@@ -228,8 +229,10 @@ test("private registry and actual directory uid are required before network read
228
229
  chmodSync(registry, 0o644);
229
230
  expect((await reader.read(c)).ok).toBe(false);
230
231
  chmodSync(registry, 0o600);
231
- // Docker --user 0 permits a real foreign-owner fixture, never touches host.
232
- expect(process.getuid!()).toBe(0);
232
+ // Docker --user 0 permits a real foreign-owner fixture, never touches host. The unit image runs
233
+ // as a non-root user; there the foreign-owner half cannot be built, so it ends here (the
234
+ // permission checks above still ran).
235
+ if (process.getuid!() !== 0) { console.warn("[session-source-evidence] foreign-owner fixture needs uid 0; skipped that half"); return; }
233
236
  chownSync(project, 65534, 65534);
234
237
  try { expect((await reader.read(c)).ok).toBe(false); }
235
238
  finally { chownSync(project, 0, 0); }
@@ -579,8 +582,12 @@ test("real child token metadata -> one-shot source payload -> private profile ->
579
582
  expect(statSync(input.configPath).mode & 0o777).toBe(0o600);
580
583
  await registerFromPrivateProfile(cfg);
581
584
  }, confirmRegistration: async (id, token) => p.delivery.confirmRegistration(req(token), id) });
585
+ const srcReq = payload.execution.evidence.request;
586
+ db.run("UPDATE nodes SET department_id='dep_fork_parent' WHERE node_id=?1 AND network_id=?2", [srcReq.source_node_id, srcReq.network_id]);
582
587
  expect((await worker.run(payload)).status).toBe("registration_confirmed"); expect(launches).toBe(1);
583
588
  expect(forkPosts).toBe(beforePosts);
589
+ // admin 2026-11-10: a forked child inherits the source node's department.
590
+ expect(db.get<{ department_id: string | null }>("SELECT department_id FROM nodes WHERE node_id=?1", payload.child_node_id)?.department_id).toBe("dep_fork_parent");
584
591
  const token = db.get<{ token_hash: string; bound_node_id: string; expires_at: string | null }>("SELECT token_hash,bound_node_id,expires_at FROM api_tokens WHERE token_id=?1", resolveToken(payload.child_token)!.tokenId!);
585
592
  expect(token!.bound_node_id).toBe(payload.child_node_id); expect(token!.token_hash !== payload.child_token).toBe(true);
586
593
  expect(token!.expires_at).toBeNull();
@@ -681,7 +688,7 @@ test("actual anet CLI -> exact paired agent-node CLI -> shared V2 resume -> real
681
688
  const id = p.delivery.queue(req(human.token), p.id)!;
682
689
  const payload = p.delivery.take(req(daemon.token), id, SOURCE_DELIVERY_CAPABILITY)!;
683
690
  // Container-only safe prefix. NOT a downloaded/real OpenCode binary.
684
- const prefix = mkdtempSync("/work/source-cli-fixture-");
691
+ const prefix = mkdtempSync(join(testWorkRoot(), "source-cli-fixture-"));
685
692
  const pkg = join(prefix, "node_modules", "@opencode", "cli");
686
693
  mkdirSync(join(pkg, "bin"), { recursive: true, mode: 0o700 }); mkdirSync(join(prefix, "bin"), { mode: 0o700 });
687
694
  mkdirSync(join(prefix, "safe"), { mode: 0o700 }); mkdirSync(join(prefix, "home"), { mode: 0o700 });
@@ -176,7 +176,13 @@ export function createSessionSourceTransport(options: { enabled?: boolean; direc
176
176
  if (req.method !== "POST" || url.search) return fail(400);
177
177
  const b = await readSessionControlBody(req, 65536); if (!b) return fail(400);
178
178
  if (!suffix) {
179
- if (!isHumanCredential(credential) || !keys(b, ["network_id", "source_node_id", "daemon_node_id", "server_id", "selection_scope"])
179
+ // 凭据类型与请求体是**两种不同性质**的问题,不能共用一个 400(#4467):
180
+ // · 凭据不是 human 凭据 → 权限问题,403
181
+ // · 请求体键/ID 不合法 → 请求问题,400
182
+ // 混在一起的实际代价:2026-11-10 我用节点 token 验这条链路,
183
+ // 拿到 400 后第一反应是「body 拼错了」,查了半小时才想到是凭据类型。
184
+ if (!isHumanCredential(credential)) return fail(403);
185
+ if (!keys(b, ["network_id", "source_node_id", "daemon_node_id", "server_id", "selection_scope"])
180
186
  || !id(b.network_id) || !id(b.source_node_id) || !id(b.daemon_node_id)
181
187
  || (b.server_id !== undefined && (!isDirectoryServerId(b.server_id) || !isDirectoryRequestId(b.selection_scope)))
182
188
  || (b.server_id === undefined && b.selection_scope !== undefined)) return fail(400);
@@ -0,0 +1,18 @@
1
+ // A private work root for tests that build fixture packages the runtime will execute.
2
+ // The OpenCode/agent-node binary checks refuse anything under a world-writable directory
3
+ // such as /tmp (that is the point of those checks), so these fixtures cannot live in
4
+ // tmpdir(). They used to live under /work, which no current image provides.
5
+ // It must also sit outside the project tree (project-local packages are not trusted either).
6
+ // ANET_TEST_WORK_ROOT overrides; default is $HOME/.anet-test-work, mode 0700.
7
+ import { chmodSync, mkdirSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { homedir } from "node:os";
10
+
11
+ export function testWorkRoot(): string {
12
+ const root = process.env.ANET_TEST_WORK_ROOT ?? join(homedir(), ".anet-test-work");
13
+ mkdirSync(root, { recursive: true, mode: 0o700 });
14
+ chmodSync(root, 0o700);
15
+ return root;
16
+ }
17
+
18
+ export const testWorkPath = (prefix: string) => join(testWorkRoot(), prefix);