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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/build-info.json +2 -2
  2. package/package.json +1 -1
  3. package/src/anet-variant-real-daemon-http.test.ts +3 -2
  4. package/src/api-host-supervisors-source-capabilities.test.ts +107 -0
  5. package/src/auth_login_guard.test.ts +15 -0
  6. package/src/auth_login_guard.ts +20 -1
  7. package/src/board-grants.test.ts +134 -0
  8. package/src/broadcast-attribution.test.ts +93 -0
  9. package/src/build-commit-report-http.test.ts +13 -2
  10. package/src/clone-node-adopted-db.test.ts +78 -0
  11. package/src/clone-node.ts +5 -1
  12. package/src/create-node.ts +17 -0
  13. package/src/department-heads.ts +3 -0
  14. package/src/expiry-counters.test.ts +50 -1
  15. package/src/expiry-counters.ts +31 -9
  16. package/src/health-redaction.test.ts +8 -4
  17. package/src/launched-by-cli-report-http.test.ts +155 -0
  18. package/src/mcp-write-network-resolution.test.ts +36 -0
  19. package/src/node-config-last-update.test.ts +103 -1
  20. package/src/node-config-last-update.ts +70 -5
  21. package/src/node-daemon-bindings.ts +9 -0
  22. package/src/node-grants-http.test.ts +239 -0
  23. package/src/node-grants.ts +234 -0
  24. package/src/node-inbox-allowlist-http.test.ts +355 -0
  25. package/src/node-lifecycle-read.ts +1 -1
  26. package/src/node-permissions.ts +168 -2
  27. package/src/opencode-v2-catalog.test.ts +22 -1
  28. package/src/opencode-v2-catalog.ts +36 -3
  29. package/src/peer-allowlist.test.ts +29 -0
  30. package/src/registration-switch-http.test.ts +60 -0
  31. package/src/reply-bare-infer-4315.test.ts +86 -0
  32. package/src/requirements-comment-http.test.ts +1 -1
  33. package/src/requirements-status-participants-http.test.ts +3 -3
  34. package/src/requirements.ts +29 -4
  35. package/src/schedule-agent.ts +45 -10
  36. package/src/scheduled-tasks-http.test.ts +25 -0
  37. package/src/scheduled-tasks.ts +65 -5
  38. package/src/server.ts +186 -11
  39. package/src/session-project-attach-migration.test.ts +2 -1
  40. package/src/session-project-attach-native.test.ts +3 -1
  41. package/src/session-project-create-http.test.ts +3 -2
  42. package/src/session-project-create-native.test.ts +3 -1
  43. package/src/session-source-delivery.ts +5 -0
  44. package/src/session-source-directory-http.test.ts +5 -1
  45. package/src/session-source-evidence.test.ts +11 -4
  46. package/src/session-source-transport.ts +7 -1
  47. package/src/steer-send-message.test.ts +121 -0
  48. package/src/task-access.ts +21 -1
  49. package/src/test-work-root.ts +18 -0
  50. package/src/tools.ts +117 -33
package/src/server.ts CHANGED
@@ -15,6 +15,7 @@ import { statusAliasResolverRead } from "./status-alias-resolver.js";
15
15
  import { readNodeHealth } from "./node-health-store.js";
16
16
  import { wantsAllTools } from "./tool-audience.js";
17
17
  import { assertNodeHealthy, degradedLayers } from "./node-health-guard.js";
18
+ import { GRANT_CAPABILITIES, grantsWithinManaged, listNodeGrants, parseNodeGrants, replaceNodeGrants } from "./node-grants.js";
18
19
  import { auditDepartment, createDepartment, deleteDepartment, listDepartments, setAgentDepartment, setMemberDepartment, updateDepartment } from "./departments.js";
19
20
  import { activeBinding, createdDaemon } from "./node-daemon-bindings.js";
20
21
  import { countInFlightTasks } from "./node-in-flight-tasks.js";
@@ -54,7 +55,7 @@ import { dmParticipantSeesFile, listDmThread, listDmThreads, sendHumanDm } from
54
55
  import { groupMemberSeesFile, groupUnreadFor, listGroupMessages, listGroupThreads, markGroupRead, memberGroup, sendGroupMessage } from "./group-messages.js";
55
56
  import { getTaskAccessMode, isTaskScoped, listProjectGrants, replaceTaskGrants, newMemberTaskAccess } from "./task-access.js";
56
57
  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";
58
+ 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
59
  import { validateAvatarUrl } from "./avatar-validate.js";
59
60
  import { narrowTags, parseStoredTags, validateScalarAttr } from "./node-attrs-validate.js";
60
61
  import { daemonDefaultWorkdirRoot } from "./create-node-validate.js";
@@ -62,7 +63,7 @@ import { register, login, resolveToken, tokenRejection, isExpiredSessionToken, s
62
63
  import { abortRename, cleanupCommittedRenameSessions, commitRename, prepareRename, resolveCanonicalAlias } from "./rename.js";
63
64
  import { sharedSendDedup, buildDuplicateSendPayload } from "./send_dedup.js";
64
65
  import { clientRequestIdFromMeta, idempotentTaskId, idempotentTaskMatches, type StoredIdempotentTask } from "./task-idempotency.js";
65
- import { getLoginClientIp, sharedLoginFailureLockout, sharedLoginIpRateLimiter } from "./auth_login_guard.js";
66
+ import { getLoginClientIp, normalizePeerIp, sharedLoginFailureLockout, sharedLoginIpRateLimiter } from "./auth_login_guard.js";
66
67
  import {
67
68
  FILE_ID_REGEX,
68
69
  MAX_REQUEST_CONTENT_LENGTH,
@@ -108,6 +109,12 @@ import { startDueReminderTimer } from "./requirement-due-reminders.js";
108
109
  import { clearNodeFromRequirements, handleRequirementsRequest } from "./requirements.js";
109
110
  import { readHubProviders, putHubProvider, providerWriteStatus } from "./hub-provider-config.js";
110
111
  import { readLastConfigUpdate } from "./node-config-last-update.js";
112
+ // #4495 —— 源目录 / 新建节点 / 复用已有 Session 的能力值。Hub 只认这几个**精确**字符串,
113
+ // 别的值一律不投影(daemon 上报的是自由 JSON,不能把任意串透给客户端当能力)。
114
+ import { SOURCE_DIRECTORY_CAPABILITY } from "./contracts/session-source-directory.js";
115
+ import { SOURCE_FORK_CAPABILITY } from "./contracts/session-source-transport.js";
116
+ import { SOURCE_DELIVERY_CAPABILITY } from "./contracts/session-source-delivery.js";
117
+ import { PROJECT_CREATE_CAPABILITY, SESSION_ATTACH_CAPABILITY } from "./contracts/session-project-create.js";
111
118
  import { readTokenUsage, tokenUsageCoverage } from "./node-token-usage.js";
112
119
  import { readBuildInfo } from "./build-info.js";
113
120
  import { requestProviderApplication } from "./daemon-provider-snapshots.js";
@@ -216,7 +223,13 @@ const SERVER_VERSION_SOURCE = RESOLVED_VERSION.source;
216
223
  // PUT /api/nodes/:id/permission-mode 与 GET /api/networks/:id/node-permission-report 可用(RFC-041 第一阶段)。
217
224
  // chat_groups(RFC-042,#457):部门群可用 —— …/departments/:dept/group、…/chat-groups(资料 / 成员 / 消息 / 已读)、
218
225
  // 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;
226
+ // node_inbox_allowlist:收件白名单可用 —— PUT /api/nodes/:id/inbox-allowlist { senders },GET /api/nodes 每行带 inbox_allowlist,
227
+ // 被挡的派活回 reason=sender_not_allowed,广播回 inbox_skipped(有人被跳过时才出现,没人被跳过时回执与以前逐字节相同)。
228
+ // scheduled_task_purge:POST /api/scheduled-tasks/:id/purge 真删一条已停下(cancelled / completed)的计划,连执行记录一起删;
229
+ // 还在跑的回 409 schedule_not_stopped(先 cancel)。
230
+ // node_inbox_allowlist_dept:收件白名单认 dept:<department_id>(该部门及子部门里的节点和人)。
231
+ // node_grants:节点管理授权 GET/PUT /api/nodes/:id/grants(能力 schedules × 范围 network/department/node × read/edit)。
232
+ export const HUB_HEALTH_CAPABILITIES = ["status_node_id", "node_permission_mode", "chat_groups", "node_inbox_allowlist", "scheduled_task_purge", "node_inbox_allowlist_dept", "node_grants"] as const;
220
233
 
221
234
  // In-memory log ring buffer — last N lines streamed via /api/server-logs.
222
235
  // Wraps console.log/info/warn/error so EVERY existing log call lands here
@@ -322,6 +335,28 @@ function requireAuth(req: Request, options: RequestTokenOptions = {}): Response
322
335
  return Response.json({ error: "unauthorized", ...(tokenRejection(token) ?? {}) }, { status: 401 });
323
336
  }
324
337
 
338
+ /** COMMHUB_ALLOWED_PEER_IPS(逗号分隔)。回环地址(127.0.0.0/8、::1)永远放行;拿不到对端地址时放行(不误伤)。 */
339
+ const ALLOWED_PEER_IPS: Set<string> | null = (() => {
340
+ const raw = process.env.COMMHUB_ALLOWED_PEER_IPS?.trim();
341
+ return raw ? new Set(raw.split(",").map(s => normalizePeerIp(s.trim())).filter(Boolean)) : null;
342
+ })();
343
+ export function peerAllowed(peer: string | null, allowed: Set<string> | null = ALLOWED_PEER_IPS): boolean {
344
+ if (!allowed) return true;
345
+ const ip = normalizePeerIp(peer);
346
+ if (!ip) return true;
347
+ if (ip === "::1" || ip.startsWith("127.")) return true;
348
+ return allowed.has(ip);
349
+ }
350
+
351
+ /**
352
+ * COMMHUB_REGISTRATION=closed —— 关掉公开注册(POST /api/auth/register 回 403 registration_closed)。
353
+ * 不设 / 其它值 = 开放(旧行为)。第一个用户(自动成为 admin)不受影响:库里还没有用户时照常放行。
354
+ */
355
+ function registrationClosed(): boolean {
356
+ if ((process.env.COMMHUB_REGISTRATION ?? "").trim().toLowerCase() !== "closed") return false;
357
+ return !!db.get<{ ok: number }>("SELECT 1 AS ok FROM users LIMIT 1");
358
+ }
359
+
325
360
  function getClientIP(req: Request, server?: any): string {
326
361
  const direct = server?.requestIP?.(req)?.address;
327
362
  if (direct) return direct;
@@ -478,6 +513,13 @@ function restNodeDenied(req: Request, restAuth: { networkId: string | null; toke
478
513
  const verdict = verdictOf(id);
479
514
  return nodeDecide(id, route, verdict) ? withCors(req, Response.json(nodePermissionDeniedBody(verdict!.reason, route), { status: 403 })) : null;
480
515
  }
516
+ /** 收件白名单的发件人:网络绑定令牌 = 节点;用户令牌 = 人;没有身份 = legacy。 */
517
+ function restInboxSender(_req: Request, restAuth: { networkId: string | null; tokenId: string | null; userId?: string | null; username?: string | null } | null): InboxSender {
518
+ return inboxSenderFromAuth({
519
+ isNodeToken: !!restAuth?.networkId, tokenId: restAuth?.tokenId ?? null, boundNetworkId: restAuth?.networkId ?? null,
520
+ userId: restAuth?.userId ?? null, username: restAuth?.username ?? null,
521
+ });
522
+ }
481
523
  /** 写别的节点 = 只有人能做;写自己 = 只看模式。 */
482
524
  const nodeTargetVerdict = (targetNodeId: string) => (id: NodeIdentity): Verdict =>
483
525
  id.nodeId && id.nodeId === targetNodeId ? writeVerdict(id, targetNodeId) : humanOnlyVerdict(id, targetNodeId);
@@ -2051,6 +2093,12 @@ return Bun.serve({
2051
2093
  error: (err) => buildServeErrorResponse(err),
2052
2094
 
2053
2095
  async fetch(req, server) {
2096
+ // 2026-11-11 安全排查 —— COMMHUB_ALLOWED_PEER_IPS:Hub 端口只接这些对端(外加本机回环)。
2097
+ // 生产 :9200 直接暴露在公网,但真正的来路只有本机(frp、本机节点)和 https 反代那台机器;
2098
+ // 没有云安全组权限时,在 Hub 里把其它来源挡在门外。不设 = 不限制(旧行为)。
2099
+ if (!peerAllowed(server?.requestIP?.(req)?.address ?? null)) {
2100
+ return new Response(JSON.stringify({ ok: false, error: "peer_not_allowed" }), { status: 403, headers: { "Content-Type": "application/json", Connection: "close" } });
2101
+ }
2054
2102
  // 2026-09-16 —— 所有 JSON/文本响应在客户端要求时 gzip(见 http-gzip.ts);SSE/流式/二进制原样。
2055
2103
  // 2026-09-30 —— 每个请求的路由形状 + 耗时进内存环(route-timing.ts),GET /api/stats/routes 看谁在吃 CPU。
2056
2104
  return recordRouteTiming(req, performance.now(), await maybeGzipResponse(req, explainExpiredSession(req, await (async (): Promise<Response | undefined> => {
@@ -2382,7 +2430,9 @@ return Bun.serve({
2382
2430
  // 现已移除;命中时按未知路径处理(404),不再保留兼容壳。
2383
2431
  // ── V3: Auth endpoints (public) ──
2384
2432
  if (url.pathname === "/api/auth/register" && req.method === "POST") {
2385
- const clientIP = req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || "unknown";
2433
+ // 与登录同一口径(最后一跳 + COMMHUB_TRUSTED_PROXY_IPS):原来取第一跳,客户端随便写就能换桶。
2434
+ const clientIP = getLoginClientIp(req, server?.requestIP?.(req)?.address ?? null);
2435
+ if (registrationClosed()) return withCors(req, Response.json({ ok: false, error: "registration_closed", message: "This Hub does not accept new sign-ups. Ask an admin for an invite." }, { status: 403 }));
2386
2436
  if (!checkRateLimit(clientIP, 30)) {
2387
2437
  noteRegisterRateLimited(clientIP);
2388
2438
  return withCors(req, Response.json({ ok: false, error: "too many requests, try again later" }, { status: 429 }));
@@ -2398,7 +2448,7 @@ return Bun.serve({
2398
2448
  }
2399
2449
 
2400
2450
  if (url.pathname === "/api/auth/login" && req.method === "POST") {
2401
- const clientIP = getLoginClientIp(req);
2451
+ const clientIP = getLoginClientIp(req, server?.requestIP?.(req)?.address ?? null);
2402
2452
  const ipRate = sharedLoginIpRateLimiter.check(clientIP || "unknown");
2403
2453
  if (!ipRate.allowed) {
2404
2454
  logAudit(null, null, "login_rate_limited", "auth", undefined, clientIP);
@@ -4352,6 +4402,81 @@ return Bun.serve({
4352
4402
  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
4403
  return withCors(req, Response.json({ ok: true, node_id: node2.node_id, peers: peers.length ? peers : null }));
4354
4404
  }
4405
+ // 节点管理授权(node-grants.ts):GET / PUT /api/nodes/:id/grants { grants: [{capability, scope_kind, scope_id, level}] }
4406
+ // 读:本网络成员。写:网络 owner / admin、Hub 管理员可授任意范围;部门负责人只能授自己负责子树里的
4407
+ // department / node 范围。**节点主人不行**(否则任何成员都能给自己的节点授全网的权)。PUT 是整份替换,[] 清空。
4408
+ const nodeGrantsMatch = url.pathname.match(/^\/api\/nodes\/([^/]+)\/grants$/);
4409
+ if (nodeGrantsMatch && (req.method === "GET" || req.method === "PUT")) {
4410
+ if (!restAuth) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
4411
+ if (restAuth.networkId) return userTokenRequired(req);
4412
+ const ref = decodeURIComponent(nodeGrantsMatch[1]);
4413
+ const gnode = db.get<{ node_id: string; network_id: string | null }>("SELECT node_id, network_id FROM nodes WHERE node_id = ?1", ref);
4414
+ const grole = gnode?.network_id ? getUserNetworkRole(restAuth.userId, gnode.network_id) : null;
4415
+ if (!gnode || !gnode.network_id || (!grole && !isAdmin)) return withCors(req, Response.json({ ok: false, error: "node_not_found" }, { status: 404 }));
4416
+ if (req.method === "GET") {
4417
+ return withCors(req, Response.json({ ok: true, node_id: gnode.node_id, grants: listNodeGrants(gnode.network_id, gnode.node_id), capabilities: GRANT_CAPABILITIES }));
4418
+ }
4419
+ let body: any;
4420
+ try { body = await req.json(); } catch { return withCors(req, Response.json({ ok: false, error: "invalid_json" }, { status: 400 })); }
4421
+ const parsed = parseNodeGrants(gnode.network_id, body?.grants);
4422
+ if (!parsed.ok) return withCors(req, Response.json(parsed, { status: parsed.error.endsWith("_not_found") ? 404 : 400 }));
4423
+ const fullAdmin = isAdmin || grole === "owner" || grole === "admin";
4424
+ if (!fullAdmin) {
4425
+ const managed = new Set(managedDepartmentIds(gnode.network_id, restAuth.userId).flatMap(d => [...departmentSubtree(gnode.network_id!, d)]));
4426
+ const before = listNodeGrants(gnode.network_id, gnode.node_id);
4427
+ // 负责人改的是整份名单:名单里不在他管辖内的旧授权必须原样保留,新增 / 删除的都得在他的子树里。
4428
+ const outside = (g: { scope_kind: string; scope_id: string }) => !grantsWithinManaged(gnode.network_id!, [g as any], managed);
4429
+ const keptOutside = before.filter(outside).every(b => parsed.grants.some(g => g.capability === b.capability && g.scope_kind === b.scope_kind && g.scope_id === b.scope_id && g.level === b.level));
4430
+ const addedOutside = parsed.grants.filter(outside).some(g => !before.some(b => b.capability === g.capability && b.scope_kind === g.scope_kind && b.scope_id === g.scope_id && b.level === g.level));
4431
+ if (!managed.size || !keptOutside || addedOutside) {
4432
+ return withCors(req, Response.json({ ok: false, error: "permission_denied", message: "only network owners/admins can grant network-wide access; department heads can grant within the departments they lead" }, { status: 403 }));
4433
+ }
4434
+ }
4435
+ const before = listNodeGrants(gnode.network_id, gnode.node_id);
4436
+ replaceNodeGrants(gnode.network_id, gnode.node_id, parsed.grants, restAuth.userId);
4437
+ logAudit(restAuth.userId, restAuth.username, "node_grants_changed", "node", gnode.node_id,
4438
+ JSON.stringify({ from: before.map(({ capability, scope_kind, scope_id, level }) => ({ capability, scope_kind, scope_id, level })), to: parsed.grants }), getClientIP(req), gnode.network_id);
4439
+ return withCors(req, Response.json({ ok: true, node_id: gnode.node_id, grants: listNodeGrants(gnode.network_id, gnode.node_id) }));
4440
+ }
4441
+ // 收件白名单:PUT /api/nodes/:id/inbox-allowlist { senders: string[] | null }
4442
+ // 与 peer-allowlist 同一套授权、审计与空数组语义(拒收 [],清空请传 null)。
4443
+ // 条目语法与发件人匹配规则见 node-permissions.ts「收件白名单」。
4444
+ const inboxAllowMatch = url.pathname.match(/^\/api\/nodes\/([^/]+)\/inbox-allowlist$/);
4445
+ if (inboxAllowMatch && req.method === "PUT") {
4446
+ if (!restAuth) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
4447
+ if (restAuth.networkId) return userTokenRequired(req);
4448
+ let body: any;
4449
+ try { body = await req.json(); } catch { return withCors(req, Response.json({ ok: false, error: "invalid_json" }, { status: 400 })); }
4450
+ const rawSenders = body?.senders;
4451
+ if (rawSenders !== null && rawSenders !== undefined && !Array.isArray(rawSenders)) {
4452
+ 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 }));
4453
+ }
4454
+ const senders = Array.isArray(rawSenders)
4455
+ ? rawSenders.filter((x: unknown): x is string => typeof x === "string" && x.trim().length > 0).map((x: string) => x.trim())
4456
+ : [];
4457
+ if (Array.isArray(rawSenders) && senders.length === 0) {
4458
+ return withCors(req, Response.json({
4459
+ ok: false,
4460
+ error: "empty_allowlist_ambiguous",
4461
+ message: "send null to clear the allowlist (no restriction); an empty array is ambiguous and is rejected",
4462
+ }, { status: 400 }));
4463
+ }
4464
+ if (senders.length > 200) {
4465
+ return withCors(req, Response.json({ ok: false, error: "too_many_senders", message: "at most 200 entries" }, { status: 400 }));
4466
+ }
4467
+ const nodeRef5 = decodeURIComponent(inboxAllowMatch[1]);
4468
+ const node5 = db.get<{ node_id: string; network_id: string | null; owner_user_id: string | null; inbox_allowlist: string | null }>(
4469
+ "SELECT node_id, network_id, owner_user_id, inbox_allowlist FROM nodes WHERE node_id = ?1", nodeRef5);
4470
+ const role5 = node5?.network_id ? getUserNetworkRole(restAuth.userId, node5.network_id) : null;
4471
+ if (!node5 || !node5.network_id || (!role5 && !isAdmin)) return withCors(req, Response.json({ ok: false, error: "node_not_found" }, { status: 404 }));
4472
+ if (!canRestWriteNodeSecurity(restAuth, node5.owner_user_id, role5, isAdmin)) {
4473
+ 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 }));
4474
+ }
4475
+ const nextSenders = senders.length ? JSON.stringify(senders) : null;
4476
+ db.run("UPDATE nodes SET inbox_allowlist = ?1 WHERE node_id = ?2", [nextSenders, node5.node_id]);
4477
+ 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);
4478
+ return withCors(req, Response.json({ ok: true, node_id: node5.node_id, senders: senders.length ? senders : null }));
4479
+ }
4355
4480
  const permReportMatch = url.pathname.match(/^\/api\/networks\/([^/]+)\/node-permission-report$/);
4356
4481
  if (permReportMatch && req.method === "GET") {
4357
4482
  if (!restAuth) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
@@ -5766,6 +5891,8 @@ return Bun.serve({
5766
5891
  ...(canonical.renamed ? { renamed_from: body.alias, renamed_to: targetAlias } : {}),
5767
5892
  }, { status: 404 })));
5768
5893
  }
5894
+ const inboxRefused = inboxDenied(taskNetId ?? null, { alias: targetAlias, nodeId: target.session?.node_id ?? null }, restInboxSender(req, restAuth), "POST /api/task");
5895
+ if (inboxRefused) return reject(withCors(req, Response.json(inboxRefused, { status: 403 })));
5769
5896
  // Identity binding, mirroring the MCP transport (tools.ts defaultFrom /
5770
5897
  // fromIdentityMismatchReply). Both transports resolve the same
5771
5898
  // api_tokens row through resolveToken, and auth.ts already documents the
@@ -6025,14 +6152,15 @@ return Bun.serve({
6025
6152
  sql = addNetworkScope(sql, params, restScope);
6026
6153
  if (body.filter_server) { sql += " AND server = ?"; params.push(body.filter_server); }
6027
6154
  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);
6155
+ const allTargets = db.all<{ alias: string; node_id: string | null; network_id: string | null }>(sql, ...params);
6156
+ const { allowed: targets, skipped: inboxSkipped } = filterBroadcastByInbox(allTargets, restScope.networkId ?? null, restInboxSender(req, restAuth), "POST /api/broadcast");
6029
6157
  // #2721 —— 与 MCP broadcast 同一条分批路径(reason 见 broadcast-fanout.ts 顶部)。
6030
6158
  const { ids } = await enqueueBroadcast(targets, body.message, "api", null, {
6031
6159
  // RFC-027 §2.3 inbox-enqueue lifecycle guard (PR1.2a REST site 2/2).
6032
6160
  isActive: (alias, netId) => assertNodeActive(alias, netId).ok,
6033
6161
  notify: (alias, netId) => pushEvent(alias, { type: "broadcast", inbox_count: pendingInboxCount(alias, netId) }, netId),
6034
6162
  });
6035
- return withCors(req, Response.json({ ok: true, recipients: ids.length, message_ids: ids }));
6163
+ return withCors(req, Response.json({ ok: true, recipients: ids.length, message_ids: ids, ...(inboxSkipped.length ? { inbox_skipped: inboxSkipped } : {}) }));
6036
6164
  }
6037
6165
 
6038
6166
  // ── REST: tmux capture-pane ──
@@ -6493,6 +6621,9 @@ return Bun.serve({
6493
6621
  const lastUpdate = readLastConfigUpdate(
6494
6622
  (sql: string, ...params: any[]) => (db.get as any)(sql, ...params),
6495
6623
  node.node_id,
6624
+ // #4499 —— 排队后被应用的那种下发:ack 当时是 rejected/variant_busy,
6625
+ // 节点随后把档位改过去了。用「当前回读的档位」判断它到底生效了没有。
6626
+ { currentVariant: typeof snapshot.modelVariant === "string" ? snapshot.modelVariant : null },
6496
6627
  );
6497
6628
  return withCors(req, Response.json({
6498
6629
  ok: true,
@@ -6802,6 +6933,8 @@ return Bun.serve({
6802
6933
  // 而这一格存在的全部意义就是让人分辨新鲜和陈旧。
6803
6934
  let snapObservedMsAgo: number | undefined;
6804
6935
  let snapReadiness: ReturnType<typeof sanitizeRuntimeReadiness>;
6936
+ // #4495 —— 源能力,只在 daemon 真的按契约上报时才有键。
6937
+ const snapCaps: Record<string, string> = {};
6805
6938
  if (r.config_snapshot) {
6806
6939
  try {
6807
6940
  const parsed = typeof r.config_snapshot === "string" ? JSON.parse(r.config_snapshot) : r.config_snapshot;
@@ -6823,14 +6956,28 @@ return Bun.serve({
6823
6956
  }
6824
6957
  // #622 —— 逐 runtime 就绪度;旧 daemon 不报 ⇒ undefined ⇒ 响应里没有这个键。
6825
6958
  snapReadiness = sanitizeRuntimeReadiness(caps?.runtime_readiness);
6959
+ // #4495 —— 这五条以前**只存在 nodes.config_snapshot 里,没有任何 REST 出口**:
6960
+ // 客户端想知道「这台 daemon 能不能列已有项目 / 复用已有 Session」只能靠猜
6961
+ // (app 里 NodeSourcePalette 干脆写死 hasProjectCreateCapability: true)。
6962
+ // 现在按精确能力值投影出来;没报 / 报的值不认识 ⇒ 键不出现(与 can_create_nodes 同一套兼容口径)。
6963
+ for (const [key, want] of [
6964
+ ["source_directory_read", SOURCE_DIRECTORY_CAPABILITY],
6965
+ ["project_new_session", PROJECT_CREATE_CAPABILITY],
6966
+ ["session_attach", SESSION_ATTACH_CAPABILITY],
6967
+ ["source_fork_transport", SOURCE_FORK_CAPABILITY],
6968
+ ["source_node_delivery", SOURCE_DELIVERY_CAPABILITY],
6969
+ ] as const) {
6970
+ const v = (caps as Record<string, unknown> | undefined)?.[key];
6971
+ if (typeof v === "string" && v === want) snapCaps[key] = v;
6972
+ }
6826
6973
  } catch { /* malformed */ }
6827
6974
  }
6828
6975
  return { row: r, role: snapRole, canCreate: snapCanCreate, blockedReason: snapBlockedReason,
6829
6976
  observedMsAgo: snapObservedMsAgo, readiness: snapReadiness, adoptCapable: snapAdoptCapable,
6830
- adoptionDiscovery: snapAdoptionDiscovery };
6977
+ adoptionDiscovery: snapAdoptionDiscovery, caps: snapCaps };
6831
6978
  })
6832
6979
  .filter(({ role }) => role === "host_supervisor")
6833
- .map(({ row: r, canCreate, blockedReason, observedMsAgo, readiness, adoptCapable, adoptionDiscovery }) => {
6980
+ .map(({ row: r, canCreate, blockedReason, observedMsAgo, readiness, adoptCapable, adoptionDiscovery, caps }) => {
6834
6981
  let online = false;
6835
6982
  let lastSeenAt: string | null = null;
6836
6983
  if (r.session_last_seen) {
@@ -6869,6 +7016,8 @@ return Bun.serve({
6869
7016
  runtimes_supported: runtimes,
6870
7017
  allowed_secret_keys: secrets,
6871
7018
  host_telemetry: telemetry,
7019
+ // #4495 —— 没上报就不出现这些键(与 can_create_nodes 的「不是 false,是 undefined」同一口径)。
7020
+ ...caps,
6872
7021
  };
6873
7022
  // #973 — only when the daemon actually reported one (see the SQL comment).
6874
7023
  const reportedVersion = (r as unknown as { reported_version?: string | null }).reported_version;
@@ -6944,7 +7093,7 @@ return Bun.serve({
6944
7093
  network_id, created_at, updated_at,
6945
7094
  config_snapshot, lifecycle_state, avatar_url,
6946
7095
  display_name, team, tags, attrs_revision, permission_mode, owner_user_id,
6947
- department_id, peer_allowlist, tool_allowlist, rest_allowlist
7096
+ department_id, peer_allowlist, tool_allowlist, rest_allowlist, inbox_allowlist
6948
7097
  FROM nodes WHERE 1=1`;
6949
7098
  const params: any[] = [];
6950
7099
  sql = addAgentNetworkScope(sql, params, restScope, { alias: "alias", nodeId: "node_id" });
@@ -7098,9 +7247,15 @@ return Bun.serve({
7098
7247
  let opencodeCatalog: string[] | null = null;
7099
7248
  // null = daemon 没报采集时刻(不是「很久以前」,也不是「刚刚」)
7100
7249
  let opencodeCatalogSeenAt: string | null = null;
7250
+ let opencodeCatalogVariants: string[] | null = null;
7101
7251
  let opencodeGeneration: "v1" | "v2" | null = null;
7102
7252
  let opencodeMode: string | null = null;
7103
7253
  let opencodeServer: string | null = null;
7254
+ // 2026-11-10 —— 起这台节点的 anet CLI 版本。**声明在 `if (snap)` 外面**:
7255
+ // 下面的投影对每一行都会求值,块内 `let` 会让部署后的 /api/nodes 直接抛
7256
+ // "launchedByCliVersion is not defined"(#4150-Build 的 opencodeAgents 踩过同一次)。
7257
+ // null = 节点没报(老节点 / 不是 CLI 起的,如 daemon adopt 出来的子节点)。
7258
+ let launchedByCliVersion: string | null = null;
7104
7259
  const snap = r.config_snapshot;
7105
7260
  // #4150-Build — declared outside the `if (snap)` block: the projection below is
7106
7261
  // evaluated for every row, and a block-scoped `let` here made /api/nodes throw
@@ -7108,6 +7263,9 @@ return Bun.serve({
7108
7263
  let opencodeAgents: string[] | null = null;
7109
7264
  let opencodeAgentsSeenAt: string | null = null;
7110
7265
  let opencodeAgentCurrent: string | null = null;
7266
+ // 与 GET /api/nodes/:id/config 保持同一口径:列表里也要能读到「能不能切 agent」,
7267
+ // 否则两个端点对同一台节点会给出不一致的能力结论。
7268
+ let opencodeAgentConfigCapable = false;
7111
7269
  if (snap) {
7112
7270
  let parsed: any = null;
7113
7271
  try { parsed = typeof snap === "string" ? JSON.parse(snap) : snap; }
@@ -7123,6 +7281,11 @@ return Bun.serve({
7123
7281
  const seen = parsed?.opencode_catalog_seen_at;
7124
7282
  opencodeCatalogSeenAt =
7125
7283
  typeof seen === "string" && seen.length > 0 && seen.length <= 40 ? seen : null;
7284
+ // admin 2026-11-11 —— 每个模型的思考档位(`provider/model=a,b,c`),只做投影。
7285
+ const rawVariants = parsed?.opencode_catalog_variants;
7286
+ if (Array.isArray(rawVariants) && rawVariants.every((v: unknown) => typeof v === "string" && v.length <= 600)) {
7287
+ opencodeCatalogVariants = rawVariants.slice(0, 400);
7288
+ }
7126
7289
  }
7127
7290
  // #2293 —— 客户端「Runtime · V2」和「OpenCode Server」两行要的正是快照里这三格标量。
7128
7291
  // PR #1092 之前从 `node.config_snapshot` 读,但这个端点**刻意不带整个快照**
@@ -7139,14 +7302,21 @@ return Bun.serve({
7139
7302
  if (typeof rawAgentCurrent === "string" && rawAgentCurrent.length > 0 && rawAgentCurrent.length <= 200) {
7140
7303
  opencodeAgentCurrent = rawAgentCurrent;
7141
7304
  }
7305
+ opencodeAgentConfigCapable = parsed?.opencode_agent_config_capable === true;
7142
7306
  const flags = parsed?.flags;
7143
7307
  if (flags?.opencodeGeneration === "v1" || flags?.opencodeGeneration === "v2") opencodeGeneration = flags.opencodeGeneration;
7144
7308
  if (typeof flags?.opencodeMode === "string" && flags.opencodeMode.length <= 32) opencodeMode = flags.opencodeMode;
7145
7309
  if (typeof parsed?.opencode_server === "string" && parsed.opencode_server.length <= 200) opencodeServer = parsed.opencode_server;
7310
+ // 2026-11-10 —— 只做投影:节点报了就给出来,没报就是 null(两种成因见上面的注释)。
7311
+ // 形状再校验一遍:schema 那层已经限了 64 字符,但库里的历史行不受 schema 管。
7312
+ const rawLaunchedBy = parsed?.launched_by_cli_version;
7313
+ if (typeof rawLaunchedBy === "string" && rawLaunchedBy.length > 0 && rawLaunchedBy.length <= 64) {
7314
+ launchedByCliVersion = rawLaunchedBy;
7315
+ }
7146
7316
  }
7147
7317
  // #2969 —— 两张白名单原来**只能写不能读**(PUT 有了,GET 里没有),
7148
7318
  // 客户端因此做不出「当前设置」这一屏。这里把原始列解构出来,下面换成解析后的数组。
7149
- const { config_snapshot, owner_user_id, peer_allowlist, tool_allowlist, rest_allowlist, ...rest } = r;
7319
+ const { config_snapshot, owner_user_id, peer_allowlist, tool_allowlist, rest_allowlist, inbox_allowlist, ...rest } = r;
7150
7320
  // `tags` is stored as JSON text; hand the dashboard a real array so
7151
7321
  // it can map() without a guard, and normalise legacy/absent values
7152
7322
  // to [] rather than null. attrs_revision is normalised to a number
@@ -7163,12 +7333,15 @@ return Bun.serve({
7163
7333
  opencode_catalog: opencodeCatalog,
7164
7334
  opencode_agents: opencodeAgents,
7165
7335
  opencode_agent_current: opencodeAgentCurrent,
7336
+ opencode_agent_config_capable: opencodeAgentConfigCapable,
7166
7337
  opencode_agents_seen_at: opencodeAgentsSeenAt,
7167
7338
  // 见上:null 表示 daemon 未上报;非 null 是它自己给的采集时刻
7168
7339
  opencode_catalog_seen_at: opencodeCatalogSeenAt,
7340
+ opencode_catalog_variants: opencodeCatalogVariants,
7169
7341
  opencode_generation: opencodeGeneration,
7170
7342
  opencode_mode: opencodeMode,
7171
7343
  opencode_server: opencodeServer,
7344
+ launched_by_cli_version: launchedByCliVersion,
7172
7345
  lifecycle_controllable,
7173
7346
  lifecycle_daemon_node_id: controllable.get(r.node_id) ?? null,
7174
7347
  ...(management ? (management.get(r.node_id) ?? { managed: "none", adoption: null }) : {}),
@@ -7178,6 +7351,8 @@ return Bun.serve({
7178
7351
  tool_allowlist: normalizeToolAllowlist(tool_allowlist),
7179
7352
  // #2969 续 —— REST 写接口白名单(形如 "POST /api/task")。null = 不限制。
7180
7353
  rest_allowlist: normalizePeerAllowlist(rest_allowlist),
7354
+ // 收件白名单(谁能给这个节点派活 / 发消息)。null = 谁都能发。
7355
+ inbox_allowlist: normalizePeerAllowlist(inbox_allowlist),
7181
7356
  // #1510 —— 管理员要能看出「谁的 transport 未知」才敢打开 strict。
7182
7357
  // 这一格**只读**,不参与任何判定(判定在 env-transport-policy.ts)。
7183
7358
  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);