@sleep2agi/commhub-server 0.9.0-preview.4 → 0.9.0-preview.40

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 (117) hide show
  1. package/README.md +125 -7
  2. package/bin/commhub.ts +10 -2
  3. package/package.json +5 -5
  4. package/src/ack-create-request-transport.test.ts +159 -0
  5. package/src/ack-create-request.test.ts +331 -0
  6. package/src/admin-networks-http.test.ts +84 -0
  7. package/src/alias-filter.test.ts +72 -0
  8. package/src/alias-filter.ts +32 -0
  9. package/src/api-host-supervisors-fallback.test.ts +267 -0
  10. package/src/api-nodes-shape.test.ts +107 -13
  11. package/src/auth.ts +93 -14
  12. package/src/avatar-validate.test.ts +163 -0
  13. package/src/avatar-validate.ts +103 -0
  14. package/src/boot-side-effect.test.ts +124 -0
  15. package/src/config-apply-sec1.test.ts +107 -0
  16. package/src/config-apply-validate.test.ts +92 -0
  17. package/src/config-apply-validate.ts +81 -3
  18. package/src/create-node-tool-schema.test.ts +39 -0
  19. package/src/create-node-validate.test.ts +80 -1
  20. package/src/create-node-validate.ts +49 -5
  21. package/src/create-node.ts +51 -1
  22. package/src/dashboard-slash-routing-http.test.ts +103 -0
  23. package/src/db-adapter-guard.test.ts +85 -0
  24. package/src/db-adapter.ts +64 -23
  25. package/src/db-timestamp.test.ts +38 -0
  26. package/src/db-timestamp.ts +15 -0
  27. package/src/db.ts +622 -33
  28. package/src/delivered-without-push.test.ts +140 -0
  29. package/src/desktop-message.test.ts +286 -0
  30. package/src/ext-token-shared.test.ts +60 -0
  31. package/src/ext-validation-regression.test.ts +131 -0
  32. package/src/external-schedule-edits-http.test.ts +316 -0
  33. package/src/external-schedule-edits.ts +314 -0
  34. package/src/file-download-authz-dev-open.test.ts +135 -0
  35. package/src/file-download-authz.test.ts +403 -0
  36. package/src/file-download-date-bucket.test.ts +436 -0
  37. package/src/file-network-scope-dev-open.test.ts +97 -0
  38. package/src/file-network-scope.test.ts +731 -0
  39. package/src/health-redaction.test.ts +637 -0
  40. package/src/inbox-count-sse.test.ts +310 -0
  41. package/src/inbox-count.ts +29 -0
  42. package/src/index.ts +15 -2187
  43. package/src/lifecycle-guard.ts +50 -0
  44. package/src/list-host-supervisors.test.ts +314 -0
  45. package/src/mcp-write-network-resolution.test.ts +429 -0
  46. package/src/network-name-http.test.ts +71 -0
  47. package/src/network-scope.ts +101 -0
  48. package/src/node-attrs-validate.ts +88 -0
  49. package/src/node-attrs.test.ts +213 -0
  50. package/src/node-id-alias.test.ts +147 -0
  51. package/src/node-lifecycle-controllable.test.ts +64 -0
  52. package/src/node-lifecycle-controllable.ts +51 -0
  53. package/src/observer-avatar-http.test.ts +424 -0
  54. package/src/observer-push.test.ts +252 -0
  55. package/src/package-version-consistency.test.ts +25 -0
  56. package/src/peer-reply-atomic.test.ts +455 -0
  57. package/src/peer-reply-capability.test.ts +70 -0
  58. package/src/probe-validate.test.ts +221 -0
  59. package/src/probe-validate.ts +104 -0
  60. package/src/probe.test.ts +80 -0
  61. package/src/probe.ts +200 -0
  62. package/src/push.ts +163 -7
  63. package/src/reply-target-derivation.test.ts +96 -0
  64. package/src/require-explicit-test-db.ts +9 -0
  65. package/src/resolve-port.test.ts +57 -0
  66. package/src/resolve-port.ts +44 -0
  67. package/src/response-charset.test.ts +130 -0
  68. package/src/rest-explicit-columns-http.test.ts +212 -0
  69. package/src/rest-identity.test.ts +129 -0
  70. package/src/rest-identity.ts +100 -0
  71. package/src/rest-projections.ts +67 -0
  72. package/src/rest-write-network-resolution.test.ts +133 -0
  73. package/src/runtime-label.test.ts +22 -0
  74. package/src/runtime-label.ts +21 -0
  75. package/src/scheduled-run-terminal.test.ts +268 -0
  76. package/src/scheduled-tasks-http.test.ts +479 -0
  77. package/src/scheduled-tasks.ts +549 -0
  78. package/src/send-reply-agent-warning.test.ts +202 -0
  79. package/src/send-reply-alias-optional.test.ts +131 -0
  80. package/src/send-reply-attachments.test.ts +437 -0
  81. package/src/server.ts +3591 -0
  82. package/src/shared/external-schedule-contract.ts +60 -0
  83. package/src/shared/probe-host-allowlist-drift.test.ts +54 -0
  84. package/src/shared/probe-host-allowlist.ts +128 -0
  85. package/src/side-thread-command-transport.test.ts +302 -0
  86. package/src/side-thread-command-transport.ts +318 -0
  87. package/src/side-thread-http-integration.test.ts +229 -0
  88. package/src/side-thread-http.ts +504 -0
  89. package/src/side-thread-production.test.ts +72 -0
  90. package/src/side-thread-production.ts +118 -0
  91. package/src/side-thread.test.ts +1067 -0
  92. package/src/side-thread.ts +2495 -0
  93. package/src/skillhub-http.test.ts +88 -0
  94. package/src/start-node.test.ts +109 -0
  95. package/src/stop-delete-node.test.ts +952 -0
  96. package/src/task-auth-origin-http.test.ts +87 -0
  97. package/src/task-auth-origin.test.ts +24 -0
  98. package/src/task-auth-origin.ts +7 -0
  99. package/src/task-consumption.test.ts +471 -0
  100. package/src/task-diagnostic-http.test.ts +145 -0
  101. package/src/task-diagnostic.test.ts +115 -0
  102. package/src/task-diagnostic.ts +118 -0
  103. package/src/task-idempotency-mcp.test.ts +142 -0
  104. package/src/task-idempotency.test.ts +60 -0
  105. package/src/task-idempotency.ts +75 -0
  106. package/src/task-lifecycle-watcher.test.ts +200 -0
  107. package/src/task-lifecycle-watcher.ts +49 -0
  108. package/src/task-network-resolution-http.test.ts +137 -0
  109. package/src/tasks-pagination-http.test.ts +137 -0
  110. package/src/tools.ts +2952 -191
  111. package/src/update-provider.test.ts +234 -0
  112. package/src/upload-early-reject-guard.test.ts +155 -0
  113. package/src/uploads-http.test.ts +92 -14
  114. package/src/uploads.test.ts +66 -0
  115. package/src/uploads.ts +130 -5
  116. package/src/vault.test.ts +200 -0
  117. package/src/vault.ts +156 -0
package/src/server.ts ADDED
@@ -0,0 +1,3591 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { parseDbTimestampMs } from "./db-timestamp.js";
3
+ import { buildControllableMap, isLifecycleControllable } from "./node-lifecycle-controllable.js";
4
+ import { resolvePort } from "./resolve-port.js";
5
+ import { normalizeSessionRuntime } from "./runtime-label.js";
6
+ import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
7
+ import { z } from "zod/v4";
8
+ import { registerTools } from "./tools.js";
9
+ import { db, logTaskEvent, logAudit, syncScheduledRunForTask } from "./db.js";
10
+ import { createSSEStream, createNetworkObserverStream, createUserEventStream, pushEvent, pushNetworkObserverEvent, getSSEStats, PRINTABLE_OBSERVER_KEY_PREFIX } from "./push.js";
11
+ import { assertNodeActive } from "./lifecycle-guard.js";
12
+ import { pendingInboxCount } from "./inbox-count.js";
13
+ import { addNetworkScope, canRestWriteNetwork, getUserNetworkIds, resolveRestNetworkScope, resolveRestWriteNetworkId, singleNetworkId, type RestNetworkScope } from "./network-scope.js";
14
+ import { validateAvatarUrl } from "./avatar-validate.js";
15
+ import { narrowTags, parseStoredTags, validateScalarAttr } from "./node-attrs-validate.js";
16
+ import { register, login, resolveToken, getUserNetworks, getUserAllNetworks, createNetwork, deleteNetwork, renameNetwork, changePassword, issueUserToken, listTokens, createToken, revokeToken, getNetworkMembers, getUserNetworkRole, addNetworkMember, updateMemberRole, removeNetworkMember, createInvite, joinByInvite, createNetworkTokenForNode, type AuthUser } from "./auth.js";
17
+ import { abortRename, cleanupCommittedRenameSessions, commitRename, prepareRename, resolveCanonicalAlias } from "./rename.js";
18
+ import { sharedSendDedup, buildDuplicateSendPayload } from "./send_dedup.js";
19
+ import { getLoginClientIp, sharedLoginFailureLockout, sharedLoginIpRateLimiter } from "./auth_login_guard.js";
20
+ import {
21
+ FILE_ID_REGEX,
22
+ MAX_REQUEST_CONTENT_LENGTH,
23
+ MAX_UPLOAD_BYTES,
24
+ buildStoragePath,
25
+ pathForExistingBlob,
26
+ isValidCalendarBucket,
27
+ generateFileId,
28
+ getUploadsRoot,
29
+ indexEntryPath,
30
+ isPathInsideUploadsRoot,
31
+ sanitizeExt,
32
+ sharedUploadRateLimiter,
33
+ stripHostLocalPathsForCrossHostSafe,
34
+ validateAttachments,
35
+ validateIndexEntry,
36
+ } from "./uploads.js";
37
+ import { mkdirSync, writeFileSync, readFileSync, existsSync, statSync, unlinkSync, renameSync } from "fs";
38
+ import { dirname as pathDirname } from "path";
39
+ import { startRetentionSweeper } from "./retention.js";
40
+ import { startStaleSessionSweeper } from "./stale-sweeper.js";
41
+ import {
42
+ AUDIT_LOG_REST_SELECT,
43
+ COMPLETION_REST_SELECT,
44
+ NETWORK_REST_SELECT,
45
+ SESSION_REST_SELECT,
46
+ TASK_EVENT_REST_SELECT,
47
+ TASK_REST_SELECT,
48
+ } from "./rest-projections.js";
49
+ import { resolveRestFromSession } from "./rest-identity.js";
50
+ import { stampTaskAuthOrigin, type TaskAuthOrigin } from "./task-auth-origin.js";
51
+ import { diagnoseTask } from "./task-diagnostic.js";
52
+ import { assertScheduledTaskBackendSupported, handleScheduledTaskRequest, startScheduledTaskScheduler } from "./scheduled-tasks.js";
53
+ import { handleExternalScheduleEditRequest } from "./external-schedule-edits.js";
54
+ import { recordDeliveredStaleEvents } from "./task-lifecycle-watcher.js";
55
+ import { SIDE_THREAD_FEATURE_FLAG, SideThreadCoordinator, SideThreadPortRegistry, SideThreadStore, type SideThreadActor, type SideThreadAttachmentRef, type SideThreadExecutionPort } from "./side-thread.js";
56
+ import { handleSideThreadHttpRequest } from "./side-thread-http.js";
57
+ import { createProductionSideThreadTransport } from "./side-thread-production.js";
58
+
59
+ const PORT = resolvePort(process.env.PORT);
60
+ const HOST = process.env.HOST || "127.0.0.1";
61
+ const AUTH_TOKEN = process.env.COMMHUB_AUTH_TOKEN;
62
+ const DEV_OPEN = process.argv.includes("--dev-open") || process.env.COMMHUB_DEV_OPEN === "1";
63
+ const TMUX_ENABLED = process.env.COMMHUB_ENABLE_TMUX === "1";
64
+ const SECURITY_LABEL = DEV_OPEN ? "⚠️ DEV OPEN MODE" : "🔒 secured";
65
+ const TMUX_ALLOWLIST = new Set(
66
+ (process.env.COMMHUB_TMUX_ALLOWLIST || "")
67
+ .split(",")
68
+ .map((s) => s.trim())
69
+ .filter(Boolean)
70
+ );
71
+ let masterTokenDeprecationLogged = false;
72
+
73
+ // #175 PR2 starts fail-closed. Only a verified native adapter can be installed;
74
+ // the execution port deliberately has no ordinary task/FIFO delivery method.
75
+ export const sideThreadPortRegistry = new SideThreadPortRegistry();
76
+ export function installSideThreadExecutionPort(port: SideThreadExecutionPort): () => void {
77
+ return sideThreadPortRegistry.install(port);
78
+ }
79
+ const sideThreadCoordinator = new SideThreadCoordinator(new SideThreadStore(db), sideThreadPortRegistry, {
80
+ enabled: process.env[SIDE_THREAD_FEATURE_FLAG] === "1",
81
+ authorizeNode: (actor, networkId, nodeId) => authorizeSideThreadNode(actor, networkId, nodeId),
82
+ authorizeAttachment: (actor, networkId, ref) => authorizeSideThreadAttachment(actor, networkId, ref),
83
+ });
84
+ const productionSideThreadTransport = process.env[SIDE_THREAD_FEATURE_FLAG] === "1"
85
+ ? createProductionSideThreadTransport(db)
86
+ : null;
87
+ if (productionSideThreadTransport) installSideThreadExecutionPort(productionSideThreadTransport.port);
88
+
89
+ if (AUTH_TOKEN) {
90
+ console.warn("[commhub] COMMHUB_AUTH_TOKEN is deprecated and will be removed in v1.0. See RFC-001.");
91
+ }
92
+
93
+ // Read version from package.json so banners and /health stay in sync.
94
+ const SERVER_VERSION = (() => {
95
+ try {
96
+ const url = new URL("../package.json", import.meta.url);
97
+ return JSON.parse(require("fs").readFileSync(url, "utf8")).version || "?";
98
+ } catch { return "?"; }
99
+ })();
100
+
101
+ // In-memory log ring buffer — last N lines streamed via /api/server-logs.
102
+ // Wraps console.log/info/warn/error so EVERY existing log call lands here
103
+ // without source changes. Dashboard tails this buffer for "hub server log
104
+ // view" feature.
105
+ const LOG_RING_CAP = Number(process.env.COMMHUB_LOG_RING || 500);
106
+ type LogEntry = { ts: string; level: "log" | "info" | "warn" | "error"; line: string };
107
+ const logRing: LogEntry[] = [];
108
+ const _origConsole = { log: console.log.bind(console), info: console.info.bind(console), warn: console.warn.bind(console), error: console.error.bind(console) };
109
+ function pushLog(level: LogEntry["level"], args: any[]) {
110
+ const line = args.map(a => typeof a === "string" ? a : (() => { try { return JSON.stringify(a); } catch { return String(a); } })()).join(" ");
111
+ logRing.push({ ts: new Date().toISOString(), level, line: line.slice(0, 4000) });
112
+ if (logRing.length > LOG_RING_CAP) logRing.splice(0, logRing.length - LOG_RING_CAP);
113
+ }
114
+ console.log = (...args: any[]) => { pushLog("log", args); _origConsole.log(...args); };
115
+ console.info = (...args: any[]) => { pushLog("info", args); _origConsole.info(...args); };
116
+ console.warn = (...args: any[]) => { pushLog("warn", args); _origConsole.warn(...args); };
117
+ console.error = (...args: any[]) => { pushLog("error", args); _origConsole.error(...args); };
118
+
119
+ function normalizeMetaJson(meta: unknown): string | null {
120
+ if (!meta || typeof meta !== "object") return null;
121
+ // #222 cross-host safety — same sanitization as tools.ts so REST
122
+ // /api/task and MCP send_task produce identical meta_json shapes.
123
+ // Conditional: only strips `path` when `file_id` is also present
124
+ // (preserves single-host feishu fallback per team rule — assume-unit-before-threshold: cap is in bytes
125
+ // discipline of not breaking other call sites).
126
+ try { return JSON.stringify(stripHostLocalPathsForCrossHostSafe(meta)); } catch { return null; }
127
+ }
128
+
129
+ // ── Rate limiter (in-memory, per IP) ──
130
+ const rateLimits = new Map<string, { count: number; resetAt: number }>();
131
+ function checkRateLimit(ip: string, maxPerMinute = 60): boolean {
132
+ // Skip rate limiting for localhost/internal/unknown (dev/test)
133
+ if (!ip || ip === "unknown" || ip === "127.0.0.1" || ip === "::1") return true;
134
+ const now = Date.now();
135
+ const entry = rateLimits.get(ip);
136
+ if (!entry || now > entry.resetAt) {
137
+ rateLimits.set(ip, { count: 1, resetAt: now + 60000 });
138
+ return true;
139
+ }
140
+ if (entry.count >= maxPerMinute) return false;
141
+ entry.count++;
142
+ return true;
143
+ }
144
+ // Cleanup stale entries every 5 minutes. Interval is registered in
145
+ // startHub() (#476) — module scope must stay timer-free so importing
146
+ // this module neither holds the event loop open nor does periodic work.
147
+ function sweepStaleRateLimits(): void {
148
+ const now = Date.now();
149
+ for (const [ip, entry] of rateLimits) {
150
+ if (now > entry.resetAt) rateLimits.delete(ip);
151
+ }
152
+ }
153
+
154
+ // ── Factory: 每个请求创建新的 McpServer(stateless 模式)──
155
+ function createServer(clientIP?: string, enforceNetworkId?: string | null, enforceUserId?: string | null, callerAlias?: string | null, callerTokenIsNetwork = false, callerTokenId?: string | null): McpServer {
156
+ const server = new McpServer({
157
+ name: "commhub",
158
+ version: "0.5.0",
159
+ });
160
+ registerTools(server, clientIP, enforceNetworkId, enforceUserId, callerAlias, callerTokenIsNetwork, callerTokenId);
161
+ return server;
162
+ }
163
+
164
+ // ── Auth helper ─────────────────────────────────────
165
+ type RequestTokenOptions = { allowQueryToken?: boolean };
166
+
167
+ function requestToken(req: Request, options: RequestTokenOptions = {}): string {
168
+ const header = req.headers.get("Authorization")?.replace("Bearer ", "");
169
+ if (options.allowQueryToken === false) return header || "";
170
+ const url = new URL(req.url);
171
+ return header || url.searchParams.get("token") || "";
172
+ }
173
+
174
+ function isLegacyAuthToken(req: Request, options: RequestTokenOptions = {}): boolean {
175
+ const token = requestToken(req, options);
176
+ return !!AUTH_TOKEN && token === AUTH_TOKEN;
177
+ }
178
+
179
+ function requireAuth(req: Request, options: RequestTokenOptions = {}): Response | null {
180
+ const token = requestToken(req, options);
181
+
182
+ // V3: check api_tokens first
183
+ if (token) {
184
+ const resolved = resolveToken(token);
185
+ if (resolved) return null; // valid user token
186
+ }
187
+
188
+ // Legacy: check global COMMHUB_AUTH_TOKEN
189
+ if (!AUTH_TOKEN && DEV_OPEN) return null; // explicit local/dev open mode
190
+ if (token === AUTH_TOKEN) {
191
+ const u = new URL(req.url);
192
+ const readOnlyApi = u.pathname.startsWith("/api/") && (req.method === "GET" || req.method === "HEAD" || req.method === "OPTIONS");
193
+ if (!readOnlyApi) return Response.json({ ok: false, error: "master-token auth is deprecated; use admin utok_" }, { status: 401 });
194
+ if (!masterTokenDeprecationLogged) {
195
+ console.warn("[commhub] master-token auth is deprecated and will be removed in v1.0. See RFC-001.");
196
+ masterTokenDeprecationLogged = true;
197
+ }
198
+ return null;
199
+ }
200
+
201
+ return Response.json({ error: "unauthorized" }, { status: 401 });
202
+ }
203
+
204
+ function getClientIP(req: Request, server?: any): string {
205
+ const direct = server?.requestIP?.(req)?.address;
206
+ if (direct) return direct;
207
+ const fwd = req.headers.get("x-forwarded-for");
208
+ return fwd ? fwd.split(",")[0].trim() : (req.headers.get("x-real-ip") ?? "unknown");
209
+ }
210
+
211
+ function isLocalhostIP(ip: string): boolean {
212
+ return ip === "127.0.0.1" || ip === "::1" || ip === "::ffff:127.0.0.1" || ip === "localhost";
213
+ }
214
+
215
+ // Normalize the raw `agent` field into a canonical runtime identifier for the
216
+ // dashboard's Runtime badge. Returns null for unknown/absent agents so the
217
+ // frontend can fall back to a placeholder.
218
+ const normalizeRuntime = normalizeSessionRuntime;
219
+
220
+ function isTmuxAllowedIP(ip: string): boolean {
221
+ return isLocalhostIP(ip) || TMUX_ALLOWLIST.has(ip);
222
+ }
223
+
224
+ function requireAdminAuth(req: Request): Response | null {
225
+ const token = requestToken(req);
226
+ if (!token) return Response.json({ ok: false, error: "auth required" }, { status: 401 });
227
+ const resolved = resolveToken(token);
228
+ if (!resolved) return Response.json({ ok: false, error: "invalid token" }, { status: 401 });
229
+ if (resolved.user.role !== "admin") return Response.json({ ok: false, error: "admin required" }, { status: 403 });
230
+ return null;
231
+ }
232
+
233
+ function requireTmuxAccess(req: Request, server?: any): Response | null {
234
+ if (!TMUX_ENABLED) return Response.json({ ok: false, error: "tmux disabled" }, { status: 404 });
235
+ const ip = getClientIP(req, server);
236
+ if (!isTmuxAllowedIP(ip)) return Response.json({ ok: false, error: "tmux access denied from this ip" }, { status: 403 });
237
+ return requireAdminAuth(req);
238
+ }
239
+
240
+ // Extract user + network + token-binding identity from request token.
241
+ function resolveRequestAuth(req: Request, options: RequestTokenOptions = {}): { userId: string; networkId: string | null; username: string; tokenName: string | null; tokenId: string | null } | null {
242
+ const token = requestToken(req, options);
243
+ if (!token) return null;
244
+ const resolved = resolveToken(token);
245
+ if (!resolved) return null;
246
+ return { userId: resolved.user.user_id, networkId: resolved.networkId, username: resolved.user.username, tokenName: resolved.tokenName, tokenId: resolved.tokenId };
247
+ }
248
+
249
+ function resolveSideThreadActor(req: Request, auth: ReturnType<typeof resolveRequestAuth>, isAdmin: boolean): SideThreadActor | null {
250
+ // Legacy master and DEV_OPEN cannot own durable records because neither
251
+ // supplies a stable per-user identity for later window hydration.
252
+ if (!auth?.userId || !auth.tokenId) return null;
253
+ const nodeCredential = requestToken(req).startsWith("ntok_");
254
+ const tokenRow = nodeCredential
255
+ ? db.get<{ bound_node_id: string | null }>("SELECT bound_node_id FROM api_tokens WHERE token_id = ?1", auth.tokenId)
256
+ : null;
257
+ return {
258
+ userId: auth.userId,
259
+ username: auth.username,
260
+ tokenId: auth.tokenId,
261
+ kind: nodeCredential ? "node" : "user",
262
+ ...(auth.networkId ? { boundNetworkId: auth.networkId } : {}),
263
+ ...(tokenRow?.bound_node_id ? { boundNodeId: tokenRow.bound_node_id } : {}),
264
+ isAdmin,
265
+ };
266
+ }
267
+
268
+ // #503 — the credential kinds that authorization decisions branch on.
269
+ // Resolved once per request at the handler, so the authz helpers stay
270
+ // pure functions of (principal, entry) and every credential kind is a
271
+ // directly constructible test input instead of a hand-assembled Request.
272
+ export type Principal =
273
+ | { kind: "anonymous" }
274
+ | { kind: "dev-open-anon" }
275
+ | { kind: "legacy-master" }
276
+ | { kind: "utok"; userId: string; username: string; isAdmin: false }
277
+ | { kind: "ntok"; userId: string; boundNetworkId: string }
278
+ | { kind: "admin-utok"; userId: string; username: string };
279
+
280
+ export function resolvePrincipal(req: Request, options: RequestTokenOptions = {}): Principal {
281
+ const authCtx = resolveRequestAuth(req, options);
282
+ if (!authCtx) {
283
+ if (isLegacyAuthToken(req, options)) return { kind: "legacy-master" };
284
+ if (DEV_OPEN) return { kind: "dev-open-anon" };
285
+ return { kind: "anonymous" };
286
+ }
287
+ const token = requestToken(req, options);
288
+ const resolved = token ? resolveToken(token) : null;
289
+ const isAdmin = !!resolved && resolved.user.role === "admin";
290
+ // Bound network wins over admin classification: a ntok_ issued BY an
291
+ // admin is still a ntok_, and its bound scope defines its identity.
292
+ // Inverting this order would silently re-grant every production agent
293
+ // node cross-network read, since production node tokens resolve to an
294
+ // admin user (see the 生产影响 note on authorizeFileDownload).
295
+ if (authCtx.networkId) return { kind: "ntok", userId: authCtx.userId, boundNetworkId: authCtx.networkId };
296
+ if (isAdmin) return { kind: "admin-utok", userId: authCtx.userId, username: authCtx.username };
297
+ return { kind: "utok", userId: authCtx.userId, username: authCtx.username, isAdmin: false };
298
+ }
299
+
300
+ // #503 — coerce the on-disk (untrusted, hand-editable) index entry into
301
+ // the shape the authz helper reasons about. Every `typeof` narrowing for
302
+ // these two fields lives here and nowhere else, so the authz rules can be
303
+ // read as rules rather than as string-checks.
304
+ export function normalizeEntry(
305
+ entry: { owner_id?: unknown; network_id?: unknown },
306
+ ): { ownerId: string | null; networkId: string | null } {
307
+ const ownerId = typeof entry.owner_id === "string" && entry.owner_id.length > 0
308
+ ? entry.owner_id
309
+ : null;
310
+ const networkId = typeof entry.network_id === "string" && entry.network_id.length > 0
311
+ ? entry.network_id
312
+ : null;
313
+ return { ownerId, networkId };
314
+ }
315
+
316
+ // #495/#503 — shared authorization gate for /api/files/:file_id downloads.
317
+ // Called from the GET handler and any future HEAD/Range/dashboard-proxy
318
+ // entry so the allow-list can't drift between methods (通信龙 clause 2:
319
+ // "授权若只在 GET 分支实现, HEAD 或 Range 走别路径 = 等于没修").
320
+ //
321
+ // Returns true if the caller may read this entry; false otherwise. The
322
+ // caller emits 404 on false — never 403; 403 would leak that the
323
+ // file_id exists and enables enumeration.
324
+ //
325
+ // Allow-list — network scope enforced by #503:
326
+ // - Legacy master AUTH_TOKEN (RFC-001 read-only) → allow.
327
+ // - admin utok_ → allow (mirrors requireAdminAuth).
328
+ // - entry.network_id present → caller must belong to THAT network:
329
+ // ntok_ must be bound to it; utok_ must hold any role in it
330
+ // (viewer included — viewer is read-only, and a viewer who can see
331
+ // a task but not open its attachment is a broken product).
332
+ // - entry.network_id absent (legacy / unattributed) → the pre-#503
333
+ // rules stand unchanged: owner match, or null owner_id + DEV_OPEN.
334
+ // - Everything else → deny (404). New uploads in production always
335
+ // carry a truthy owner_id (requireAuth blocks the null-owner-
336
+ // producing path when DEV_OPEN=off and no legacy master token is
337
+ // configured), so denying null-owner in production closes the
338
+ // enumeration vector for legacy blobs without breaking new uploads.
339
+ //
340
+ // 生产影响: 新的 ntok 归属文件走 network gate, admin 签发的 ntok 也走 gate
341
+ // (kind='ntok' 分类优先绑定). 98 历史文件无 network_id 走老文件兼容分支
342
+ // (owner/admin 可读, 存量行为不变).
343
+ //
344
+ // 行为变更: admin 的节点令牌 (ntok_) 失去它今天拥有的跨网络读权. 生产今天
345
+ // 所有文件在同一 network → 无实际影响, 但语义变更须明写, 不能悄悄发生.
346
+ export function authorizeFileDownload(
347
+ principal: Principal,
348
+ entry: { ownerId: string | null; networkId: string | null },
349
+ ): boolean {
350
+ if (principal.kind === "legacy-master") return true;
351
+ if (principal.kind === "admin-utok") return true;
352
+
353
+ if (entry.networkId !== null) {
354
+ if (principal.kind === "anonymous" || principal.kind === "dev-open-anon") return false;
355
+ if (principal.kind === "ntok") return principal.boundNetworkId === entry.networkId;
356
+ return !!getUserNetworkRole(principal.userId, entry.networkId);
357
+ }
358
+
359
+ if (principal.kind === "ntok" || principal.kind === "utok") {
360
+ if (entry.ownerId !== null && principal.userId === entry.ownerId) return true;
361
+ }
362
+ // Kept env-gated rather than narrowed to kind==='dev-open-anon': the
363
+ // pre-#503 rule allowed ANY caller to read a null-owner entry while
364
+ // DEV_OPEN is on, and #503 is scoped to adding network scope, not to
365
+ // tightening the local-dev carve-out.
366
+ if (entry.ownerId === null && DEV_OPEN) return true;
367
+ return false;
368
+ }
369
+
370
+ function authorizeSideThreadNode(actor: SideThreadActor, networkId: string, nodeId: string): boolean {
371
+ const node = db.get<{ network_id: string | null; owner_user_id: string | null }>(
372
+ "SELECT network_id, owner_user_id FROM nodes WHERE node_id = ?1", nodeId,
373
+ );
374
+ if (!node || node.network_id !== networkId) return false;
375
+ if (!getUserNetworkRole(actor.userId, networkId)) return false;
376
+ if (!node.owner_user_id || node.owner_user_id !== actor.userId) return false;
377
+ if (actor.boundNetworkId && actor.boundNetworkId !== networkId) return false;
378
+ if (actor.kind === "node" && actor.boundNodeId !== nodeId) return false;
379
+ return true;
380
+ }
381
+
382
+ function resolveSideThreadCapabilityTarget(input: { actor: SideThreadActor; alias?: string; nodeId?: string; networkId?: string }): { nodeId: string; networkId: string } | undefined {
383
+ if ((!input.alias && !input.nodeId) || (input.alias && input.nodeId)) return undefined;
384
+ const networkId = input.actor.boundNetworkId ?? input.networkId;
385
+ const params: unknown[] = [input.nodeId ?? input.alias];
386
+ let sql = input.nodeId
387
+ ? "SELECT node_id,network_id FROM nodes WHERE node_id=?1"
388
+ : "SELECT node_id,network_id FROM nodes WHERE alias=?1";
389
+ if (networkId) { params.push(networkId); sql += " AND network_id=?2"; }
390
+ const authorized = db.all<{ node_id: string; network_id: string | null }>(sql, ...params)
391
+ .filter(row => !!row.network_id && authorizeSideThreadNode(input.actor, row.network_id, row.node_id));
392
+ if (authorized.length !== 1) return undefined;
393
+ return { nodeId: authorized[0].node_id, networkId: authorized[0].network_id! };
394
+ }
395
+
396
+ function authorizeSideThreadAttachment(actor: SideThreadActor, networkId: string, ref: SideThreadAttachmentRef): boolean {
397
+ if (!FILE_ID_REGEX.test(ref.fileId)) return false;
398
+ const path = indexEntryPath(ref.fileId);
399
+ if (!path || !existsSync(path)) return false;
400
+ try {
401
+ const entry = JSON.parse(readFileSync(path, "utf8"));
402
+ if (!validateIndexEntry(entry) || entry.file_id !== ref.fileId) return false;
403
+ if (entry.network_id !== networkId || entry.owner_id !== actor.userId) return false;
404
+ if (!isValidCalendarBucket(entry.date_bucket)) return false;
405
+ const storage = pathForExistingBlob(entry.date_bucket, entry.file_id, entry.ext);
406
+ return isPathInsideUploadsRoot(storage.absolutePath) && existsSync(storage.absolutePath);
407
+ } catch { return false; }
408
+ }
409
+
410
+ type ByteRange =
411
+ | { ok: true; start: number; end: number; length: number }
412
+ | { ok: false };
413
+
414
+ function parseSingleByteRange(rangeHeader: string | null, size: number): ByteRange | null {
415
+ if (rangeHeader === null) return null;
416
+ if (!Number.isSafeInteger(size) || size < 0) return { ok: false };
417
+ const match = /^bytes=(\d*)-(\d*)$/.exec(rangeHeader.trim());
418
+ if (!match) return { ok: false };
419
+ const [, rawStart, rawEnd] = match;
420
+ if (rawStart === "" && rawEnd === "") return { ok: false };
421
+
422
+ let start: number;
423
+ let end: number;
424
+ if (rawStart === "") {
425
+ const suffixLength = Number(rawEnd);
426
+ if (!Number.isSafeInteger(suffixLength) || suffixLength <= 0) return { ok: false };
427
+ if (size === 0) return { ok: false };
428
+ start = Math.max(0, size - suffixLength);
429
+ end = size - 1;
430
+ } else {
431
+ start = Number(rawStart);
432
+ if (!Number.isSafeInteger(start) || start < 0) return { ok: false };
433
+ if (start >= size) return { ok: false };
434
+ if (rawEnd === "") {
435
+ end = size - 1;
436
+ } else {
437
+ end = Number(rawEnd);
438
+ if (!Number.isSafeInteger(end) || end < start) return { ok: false };
439
+ end = Math.min(end, size - 1);
440
+ }
441
+ }
442
+
443
+ return { ok: true, start, end, length: end - start + 1 };
444
+ }
445
+
446
+ function sqliteTime(date: Date): string {
447
+ return date.toISOString().replace("T", " ").slice(0, 19);
448
+ }
449
+
450
+ function parseSqliteTime(value: string | null | undefined): number {
451
+ if (!value) return 0;
452
+ const normalized = value.includes("T") ? value : `${value.replace(" ", "T")}Z`;
453
+ const ts = Date.parse(normalized);
454
+ return Number.isFinite(ts) ? ts : 0;
455
+ }
456
+
457
+ function normalizeTaskBeforeCursor(value: string): string | null {
458
+ const cursor = value.trim();
459
+ if (!cursor) return null;
460
+ const sqliteShape = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
461
+ if (sqliteShape.test(cursor)) {
462
+ const parsed = new Date(`${cursor.replace(" ", "T")}Z`);
463
+ if (!Number.isFinite(parsed.getTime()) || sqliteTime(parsed) !== cursor) return null;
464
+ return cursor;
465
+ }
466
+ const timestamp = Date.parse(cursor);
467
+ if (!Number.isFinite(timestamp)) return null;
468
+ return sqliteTime(new Date(timestamp));
469
+ }
470
+
471
+ function normalizeTaskBeforeTaskId(value: string): string | null {
472
+ const taskId = value.trim();
473
+ if (!taskId || taskId.length > 256 || /[\u0000-\u001f\u007f]/.test(taskId)) return null;
474
+ return taskId;
475
+ }
476
+
477
+ function cpuPct(load: number | null | undefined, cores: number | null | undefined): number | null {
478
+ if (typeof load !== "number" || typeof cores !== "number" || cores <= 0) return null;
479
+ return Math.round((load / cores) * 1000) / 10;
480
+ }
481
+
482
+ function serverAlertLevel(row: any): { level: "green" | "yellow" | "red"; alerts: string[] } {
483
+ const alerts: string[] = [];
484
+ const pct = cpuPct(row?.cpu_load_1min, row?.cpu_cores);
485
+ if (pct !== null && pct >= 80) alerts.push(`cpu ${pct}%`);
486
+ if (typeof row?.mem_avail_gb === "number" && row.mem_avail_gb < 0.5) alerts.push(`memory ${row.mem_avail_gb}GB available`);
487
+ if (typeof row?.disk_avail_gb === "number" && row.disk_avail_gb < 1) alerts.push(`disk ${row.disk_avail_gb}GB available`);
488
+ if (alerts.length > 0) return { level: "red", alerts };
489
+
490
+ if (pct !== null && pct >= 60) alerts.push(`cpu ${pct}%`);
491
+ if (typeof row?.mem_avail_gb === "number" && row.mem_avail_gb < 1) alerts.push(`memory ${row.mem_avail_gb}GB available`);
492
+ if (typeof row?.disk_avail_gb === "number" && row.disk_avail_gb < 5) alerts.push(`disk ${row.disk_avail_gb}GB available`);
493
+ return { level: alerts.length > 0 ? "yellow" : "green", alerts };
494
+ }
495
+
496
+ function agentHealthChip(status: unknown, lastSeen: string | null | undefined): "online" | "offline" | "stale" {
497
+ if (String(status || "").toLowerCase() === "offline") return "offline";
498
+ const ts = parseSqliteTime(lastSeen);
499
+ if (!ts || Date.now() - ts > 5 * 60 * 1000) return "stale";
500
+ return "online";
501
+ }
502
+
503
+ function bucketTelemetry(rows: any[], fromMs: number, bucketMs: number) {
504
+ const buckets = new Map<number, {
505
+ ts: number;
506
+ count: number;
507
+ cpu_pct_sum: number;
508
+ cpu_pct_count: number;
509
+ cpu_load_sum: number;
510
+ cpu_load_count: number;
511
+ mem_avail_min: number | null;
512
+ mem_used_max: number | null;
513
+ disk_avail_min: number | null;
514
+ disk_used_max: number | null;
515
+ }>();
516
+
517
+ for (const row of rows) {
518
+ const ts = parseSqliteTime(row.created_at);
519
+ if (!ts || ts < fromMs) continue;
520
+ const bucketTs = Math.floor(ts / bucketMs) * bucketMs;
521
+ const bucket = buckets.get(bucketTs) ?? {
522
+ ts: bucketTs,
523
+ count: 0,
524
+ cpu_pct_sum: 0,
525
+ cpu_pct_count: 0,
526
+ cpu_load_sum: 0,
527
+ cpu_load_count: 0,
528
+ mem_avail_min: null,
529
+ mem_used_max: null,
530
+ disk_avail_min: null,
531
+ disk_used_max: null,
532
+ };
533
+ bucket.count += 1;
534
+ const pct = cpuPct(row.cpu_load_1min, row.cpu_cores);
535
+ if (pct !== null) {
536
+ bucket.cpu_pct_sum += pct;
537
+ bucket.cpu_pct_count += 1;
538
+ }
539
+ if (typeof row.cpu_load_1min === "number") {
540
+ bucket.cpu_load_sum += row.cpu_load_1min;
541
+ bucket.cpu_load_count += 1;
542
+ }
543
+ if (typeof row.mem_avail_gb === "number") bucket.mem_avail_min = bucket.mem_avail_min === null ? row.mem_avail_gb : Math.min(bucket.mem_avail_min, row.mem_avail_gb);
544
+ if (typeof row.mem_used_gb === "number") bucket.mem_used_max = bucket.mem_used_max === null ? row.mem_used_gb : Math.max(bucket.mem_used_max, row.mem_used_gb);
545
+ if (typeof row.disk_avail_gb === "number") bucket.disk_avail_min = bucket.disk_avail_min === null ? row.disk_avail_gb : Math.min(bucket.disk_avail_min, row.disk_avail_gb);
546
+ if (typeof row.disk_used_gb === "number") bucket.disk_used_max = bucket.disk_used_max === null ? row.disk_used_gb : Math.max(bucket.disk_used_max, row.disk_used_gb);
547
+ buckets.set(bucketTs, bucket);
548
+ }
549
+
550
+ return Array.from(buckets.values())
551
+ .sort((a, b) => a.ts - b.ts)
552
+ .map((b) => ({
553
+ ts: new Date(b.ts).toISOString(),
554
+ count: b.count,
555
+ cpu_pct: b.cpu_pct_count ? Math.round((b.cpu_pct_sum / b.cpu_pct_count) * 10) / 10 : null,
556
+ cpu_load_1min: b.cpu_load_count ? Math.round((b.cpu_load_sum / b.cpu_load_count) * 100) / 100 : null,
557
+ mem_avail_gb: b.mem_avail_min,
558
+ mem_used_gb: b.mem_used_max,
559
+ disk_avail_gb: b.disk_avail_min,
560
+ disk_used_gb: b.disk_used_max,
561
+ }));
562
+ }
563
+
564
+
565
+ type RestDeliveryTarget =
566
+ | { state: "online"; alias: string; session: any }
567
+ | { state: "offline"; alias: string; session: any; message: string }
568
+ | { state: "not_found"; alias: string; message: string };
569
+
570
+ // Build this only after authorization and a network-scoped lookup succeeded.
571
+ // In particular, not-found and permission-denied responses must not become a
572
+ // cross-network alias/node enumeration oracle.
573
+ function restActualTo(target: Exclude<RestDeliveryTarget, { state: "not_found" }>, networkId: string | null) {
574
+ return {
575
+ alias: target.alias,
576
+ to_node_id: target.session?.node_id ?? null,
577
+ network_id: networkId,
578
+ };
579
+ }
580
+
581
+ function resolveRestDeliveryTarget(alias: string, networkId: string | null): RestDeliveryTarget {
582
+ const params: any[] = [alias];
583
+ let sql = "SELECT status, updated_at, last_seen_at, node_id FROM sessions WHERE alias = ?1";
584
+ if (networkId) {
585
+ sql += " AND network_id = ?2";
586
+ params.push(networkId);
587
+ }
588
+ const session = db.get<any>(sql, ...params);
589
+ if (!session) {
590
+ return { state: "not_found", alias, message: `alias not found: ${alias}` };
591
+ }
592
+ const lastSeen = session.last_seen_at || session.updated_at;
593
+ const lastSeenAt = lastSeen ? new Date(String(lastSeen).replace(" ", "T") + "Z").getTime() : 0;
594
+ const stale = !lastSeenAt || Date.now() - lastSeenAt > 5 * 60 * 1000;
595
+ if (String(session.status || "").toLowerCase() === "offline" || stale) {
596
+ return {
597
+ state: "offline",
598
+ alias,
599
+ session,
600
+ message: `alias is offline; task queued in inbox: ${alias}`,
601
+ };
602
+ }
603
+ return { state: "online", alias, session };
604
+ }
605
+
606
+ function resolveRestNodeIdForAlias(alias: string, networkId: string | null): string | null {
607
+ if (!alias || alias === "hub" || alias === "api") return null;
608
+ const canonical = resolveCanonicalAlias(networkId, alias);
609
+ const target = resolveRestDeliveryTarget(canonical.alias, networkId);
610
+ return target.state === "not_found" ? null : (target.session?.node_id ?? null);
611
+ }
612
+
613
+ function withNetworkNameAlias<T extends { network_name?: unknown }>(row: T): T & { name: string | null } {
614
+ return {
615
+ ...row,
616
+ // `network_name` is the canonical V3 storage/API field and remains for
617
+ // existing CLI/Dashboard clients. `name` is the documented REST-friendly
618
+ // compatibility alias; never let it drift or serialize as null when the
619
+ // canonical NOT NULL field is present.
620
+ name: typeof row.network_name === "string" ? row.network_name : null,
621
+ };
622
+ }
623
+
624
+ // ── REST input schema ───────────────────────────────
625
+ const TaskSchema = z.object({
626
+ alias: z.string().min(1).max(200),
627
+ task: z.string().min(1).max(10000),
628
+ priority: z.enum(["high", "normal", "low"]).default("normal"),
629
+ from: z.string().max(200).optional(),
630
+ network_id: z.string().max(200).optional(),
631
+ parent_task_id: z.string().max(200).optional(),
632
+ ttl_seconds: z.number().min(1).max(86400).optional(),
633
+ // #221 — top-level attachments mirror the MCP send_task tool. They are
634
+ // merged into `meta.attachments` for persistence so the on-disk shape
635
+ // stays unified regardless of transport (REST or MCP).
636
+ attachments: z.any().optional(),
637
+ meta: z.any().optional(),
638
+ });
639
+
640
+ const BroadcastSchema = z.object({
641
+ message: z.string().min(1).max(10000),
642
+ filter_server: z.string().max(200).optional(),
643
+ filter_status: z.string().max(50).optional(),
644
+ });
645
+
646
+ // ── HTTP Server (Bun native) ────────────────────────
647
+ const CORS_ORIGINS = process.env.COMMHUB_CORS_ORIGINS
648
+ ? process.env.COMMHUB_CORS_ORIGINS.split(",").map((s) => s.trim())
649
+ : ["http://localhost:3000", "http://localhost:3001"];
650
+
651
+ function corsHeaders(req: Request): Record<string, string> {
652
+ const origin = req.headers.get("Origin") || "";
653
+ // CORS allowlist is driven entirely by COMMHUB_CORS_ORIGINS env (comma-separated).
654
+ // Default (env unset) allows localhost dev origins only — see CORS_ORIGINS above.
655
+ // No author-specific domains are hardcoded; production deployments must set
656
+ // COMMHUB_CORS_ORIGINS explicitly. See docs/concepts/security.md "CORS 配置".
657
+ const allowed = CORS_ORIGINS.includes(origin) ? origin : "";
658
+ return {
659
+ "Access-Control-Allow-Origin": allowed,
660
+ "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
661
+ "Access-Control-Allow-Headers": "Content-Type, Authorization",
662
+ "Access-Control-Max-Age": "86400",
663
+ };
664
+ }
665
+
666
+ function withCors(req: Request, res: Response): Response {
667
+ const headers = corsHeaders(req);
668
+ for (const [k, v] of Object.entries(headers)) {
669
+ res.headers.set(k, v);
670
+ }
671
+ return res;
672
+ }
673
+
674
+ /**
675
+ * #426 — append `charset=utf-8` to text-y Content-Type headers that
676
+ * omit it. Legacy Windows clients (PowerShell 5.1 Invoke-RestMethod /
677
+ * Invoke-WebRequest) default to ISO-8859-1 when the charset is
678
+ * unspecified, which double-encodes our clean UTF-8 payloads on the
679
+ * way in.
680
+ *
681
+ * Applied to Responses whose Content-Type header we can't influence at
682
+ * construction time — notably the MCP SDK transport, which builds its
683
+ * own `text/event-stream` / `application/json` reply. Response headers
684
+ * from `fetch` are mutable, so this rewrites in place rather than
685
+ * reconstructing the Response (which would break streamed bodies).
686
+ *
687
+ * No-ops when: charset is already set, the type is binary
688
+ * (application/octet-stream, image/*, video/*, application/pdf, etc.),
689
+ * or the header is missing entirely.
690
+ */
691
+ function withUtf8CharsetContentType(res: Response): Response {
692
+ const ct = res.headers.get("content-type");
693
+ if (!ct) return res;
694
+ if (/;\s*charset=/i.test(ct)) return res;
695
+ const trimmed = ct.trim();
696
+ // Text-y types that legacy clients decode via charset. Everything
697
+ // else (binary, opaque) is left alone.
698
+ if (
699
+ trimmed === "application/json" ||
700
+ trimmed.startsWith("text/") ||
701
+ trimmed.startsWith("application/json;") ||
702
+ trimmed === "application/ld+json" ||
703
+ trimmed === "application/xml"
704
+ ) {
705
+ res.headers.set("content-type", `${trimmed}; charset=utf-8`);
706
+ }
707
+ return res;
708
+ }
709
+
710
+ // ── WebSocket tmux sessions ────────────────────────
711
+ const wsTmuxIntervals = new Map<object, ReturnType<typeof setInterval>>();
712
+
713
+
714
+ // ── Task expiration patrol (every 5 minutes) ──
715
+ // Registered in startHub() (#476): this WRITES the DB, so it must never
716
+ // run as an import side effect — a tool/test importing this module with
717
+ // COMMHUB_DB unset would patrol the production database.
718
+ export function patrolExpiredTasks(): void {
719
+ try {
720
+ const expired = db.transaction(() => {
721
+ const due = db.all<{ task_id: string; network_id: string | null }>(
722
+ `SELECT task_id, network_id FROM tasks
723
+ WHERE expires_at IS NOT NULL AND expires_at < datetime('now')
724
+ AND status IN ('created', 'delivered')`,
725
+ );
726
+ const changed: Array<{ task_id: string; network_id: string | null }> = [];
727
+ for (const task of due) {
728
+ const result = db.run(
729
+ `UPDATE tasks SET status = 'expired', completed_at = datetime('now')
730
+ WHERE task_id = ?1 AND status IN ('created', 'delivered')`,
731
+ [task.task_id],
732
+ );
733
+ // SQLite may include the AFTER UPDATE terminal-journal trigger write
734
+ // in this count. The WHERE clause still targets one exact guarded
735
+ // task, so any positive count proves the task transition happened.
736
+ if (result.changes < 1) continue;
737
+ syncScheduledRunForTask(task.task_id, task.network_id);
738
+ changed.push(task);
739
+ }
740
+ return changed;
741
+ });
742
+ if (expired.length > 0) {
743
+ console.log(`[patrol] expired ${expired.length} stale task(s)`);
744
+ for (const task of expired) logTaskEvent(task.task_id, null, "expired", "patrol");
745
+ }
746
+ } catch {}
747
+ }
748
+
749
+ function patrolDeliveredStaleTasks(): void {
750
+ try {
751
+ const result = recordDeliveredStaleEvents();
752
+ if (result.inserted > 0) {
753
+ console.warn(`[patrol] recorded ${result.inserted} delivered-stale task warning(s)`);
754
+ }
755
+ } catch (error: any) {
756
+ console.error(`[patrol] delivered-stale watcher failed: ${error?.message || error}`);
757
+ }
758
+ }
759
+
760
+ // #434 — test-safety seam, same signature as PR #438 so the two branches
761
+ // merge cleanly. Wraps the sole Bun.serve config in a factory so
762
+ // integration tests can request an OS-assigned ephemeral port
763
+ // (`bootServer({ port: 0 })`) and read the actual bound port back from
764
+ // the returned server. In an aggregate `bun test` run only the FIRST test
765
+ // file's import boots the default server (module cache) — later files'
766
+ // PORT env is ignored, so a suite that hard-codes its own port gets
767
+ // ConnectionRefused on every fetch while still "running" (审查修复 per
768
+ // 通信龙 #461 review, finding 2). Suites boot a private instance via this
769
+ // seam instead. #438 additionally moves the default boot below under
770
+ // `import.meta.main`; until that lands, import keeps booting (pre-#434
771
+ // behavior) so the not-yet-migrated suites stay green.
772
+ //
773
+ // Note: `opts.port ?? PORT` uses nullish-coalescing on purpose — `||`
774
+ // would swallow a legitimate `0`. Same for hostname.
775
+ export function bootServer(opts?: { port?: number; hostname?: string }): ReturnType<typeof Bun.serve> {
776
+ return Bun.serve({
777
+ port: opts?.port ?? PORT,
778
+ hostname: opts?.hostname ?? HOST,
779
+ idleTimeout: 255, // max value: keep SSE connections alive (seconds)
780
+ // #221 — defense-in-depth cap on the raw request body. The /api/upload
781
+ // handler also pre-checks Content-Length and post-checks parsed size
782
+ // against the documented 12 MiB cap (MAX_UPLOAD_BYTES); this knob
783
+ // simply guarantees Bun's own buffer won't grow past 13 MiB on any
784
+ // route. Default Bun ceiling is 128 MiB which is too permissive for
785
+ // a hub now exposed to the public internet.
786
+ maxRequestBodySize: MAX_REQUEST_CONTENT_LENGTH,
787
+
788
+ async fetch(req, server) {
789
+ const url = new URL(req.url, `http://localhost:${PORT}`);
790
+
791
+ // ── CORS preflight ──
792
+ if (req.method === "OPTIONS") {
793
+ return new Response(null, { status: 204, headers: corsHeaders(req) });
794
+ }
795
+
796
+ // ── WebSocket: tmux terminal ──
797
+ const wsMatch = url.pathname.match(/^\/ws\/tmux\/([a-zA-Z0-9_-]+)$/);
798
+ if (wsMatch) {
799
+ const tmuxErr = requireTmuxAccess(req, server);
800
+ if (tmuxErr) return withCors(req, tmuxErr);
801
+ if (server.upgrade(req, { data: { tmuxName: wsMatch[1] } } as any)) return;
802
+ }
803
+
804
+ // ── MCP Streamable HTTP endpoint ──
805
+ if (url.pathname === "/mcp") {
806
+ const authErr = requireAuth(req);
807
+ if (authErr) return withCors(req, authErr);
808
+ const clientIP = getClientIP(req, server);
809
+ // V3: resolve token → enforce network_id in all MCP tools.
810
+ // utok_ (user token, not network-bound) is allowed — the tool layer
811
+ // scopes to the user's accessible networks. Without this Dashboard
812
+ // (which logs in as a user) cannot call send_task.
813
+ const token = requestToken(req);
814
+ const authCtx = resolveRequestAuth(req);
815
+ const enforceNetId = authCtx?.networkId || null;
816
+ // Derive the calling alias from the token name (e.g., 'node:视频审查')
817
+ // so peer agents see the real sender instead of 'hub' on send_task.
818
+ const callerAlias = authCtx?.tokenName?.startsWith("node:")
819
+ ? authCtx.tokenName.slice("node:".length)
820
+ : (authCtx?.username || null);
821
+ const transport = new WebStandardStreamableHTTPServerTransport({
822
+ sessionIdGenerator: undefined,
823
+ });
824
+ const mcpServer = createServer(clientIP, enforceNetId, authCtx?.userId || null, callerAlias, !!token?.startsWith("ntok_"), authCtx?.tokenId || null);
825
+ await mcpServer.connect(transport);
826
+ const response = await transport.handleRequest(req);
827
+ // Disconnect after response to prevent McpServer leak
828
+ setImmediate(() => mcpServer.close().catch(() => {}));
829
+ // #426: the MCP SDK's WebStandardStreamableHTTPServerTransport builds
830
+ // its own Response with `Content-Type: text/event-stream` (or
831
+ // `application/json` for JSON-mode) but WITHOUT charset. Legacy
832
+ // Windows clients (PowerShell 5.1 Invoke-WebRequest / RestMethod)
833
+ // default to ISO-8859-1 when the charset is unspecified and 双重-
834
+ // 编码 our clean UTF-8 payload on the way in — the reported
835
+ // mojibake is client-side, but the header is what tells them to
836
+ // guess. We can't tell the SDK to add it, so wrap the response and
837
+ // rewrite the header. Streamed bodies (SSE) pass through untouched
838
+ // because Response takes the original ReadableStream verbatim.
839
+ return withUtf8CharsetContentType(response);
840
+ }
841
+
842
+ // ── #461 SSE network observer stream ──
843
+ // GET /events/network/:network_id → 网络级摘要事件(new_task / new_reply
844
+ // routing metadata only, no content)。Dashboard 用它实时感知第三方流量,
845
+ // 退役 15s 软轮询。MUST be matched before the generic /events/(.+) route
846
+ // below, which would otherwise swallow the path as a session name.
847
+ //
848
+ // Auth mirrors /events/:session's three paths:
849
+ // 1. legacy AUTH_TOKEN (master) → any network
850
+ // 2/3. ntok_ / utok_ → must CURRENTLY be a member of the requested
851
+ // network. Membership is checked unconditionally — there is NO
852
+ // token-bound-network shortcut. removeNetworkMember deletes the
853
+ // membership row but does NOT revoke the user's ntok, so the
854
+ // network_members lookup IS the revocation mechanism: an ntok
855
+ // bound to this network whose owner was removed must lose the
856
+ // stream (审查修复 per 通信龙 #461 review, finding 1).
857
+ const netEventsMatch = url.pathname.match(/^\/events\/network\/(.+)$/);
858
+ if (netEventsMatch && req.method === "GET") {
859
+ const authErr = requireAuth(req);
860
+ if (authErr) return authErr;
861
+ const observedNetId = decodeURIComponent(netEventsMatch[1]);
862
+ const authCtx = resolveRequestAuth(req);
863
+ if (!authCtx && isLegacyAuthToken(req)) {
864
+ return createNetworkObserverStream(observedNetId);
865
+ }
866
+ if (!authCtx) {
867
+ return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 403 }));
868
+ }
869
+ const observerRole = getUserNetworkRole(authCtx.userId, observedNetId);
870
+ if (!observerRole) {
871
+ return withCors(req, Response.json({ ok: false, error: "not a member of this network" }, { status: 403 }));
872
+ }
873
+ return createNetworkObserverStream(observedNetId);
874
+ }
875
+
876
+ // GET /events/users/me?network_id=... → Desktop/user-client stream.
877
+ // This is intentionally keyed by authenticated user_id, not alias.
878
+ // Desktop must use its utok_; ntok_ is a node credential and cannot
879
+ // subscribe to user channels.
880
+ if (url.pathname === "/events/users/me" && req.method === "GET") {
881
+ const authErr = requireAuth(req);
882
+ if (authErr) return authErr;
883
+ const token = requestToken(req);
884
+ if (!token?.startsWith("utok_")) {
885
+ return withCors(req, Response.json({ ok: false, error: "user_token_required" }, { status: 403 }));
886
+ }
887
+ const authCtx = resolveRequestAuth(req);
888
+ if (!authCtx) {
889
+ return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 403 }));
890
+ }
891
+ const networkId = url.searchParams.get("network_id");
892
+ if (!networkId) {
893
+ return withCors(req, Response.json({ ok: false, error: "network_id required" }, { status: 400 }));
894
+ }
895
+ const role = getUserNetworkRole(authCtx.userId, networkId);
896
+ if (!role) {
897
+ return withCors(req, Response.json({ ok: false, error: "not a member of this network" }, { status: 403 }));
898
+ }
899
+ return createUserEventStream(networkId, authCtx.userId);
900
+ }
901
+
902
+ // ── SSE push: Agent 实时接收任务推送 ──
903
+ // GET /events/知识哥 → 保持长连接,send_task 时秒推
904
+ const eventsMatch = url.pathname.match(/^\/events\/(.+)$/);
905
+ if (eventsMatch && req.method === "GET") {
906
+ const authErr = requireAuth(req);
907
+ if (authErr) return authErr;
908
+ const sessionName = decodeURIComponent(eventsMatch[1]);
909
+ const token = requestToken(req);
910
+ const authCtx = resolveRequestAuth(req);
911
+ const scopedNetId = authCtx?.networkId || url.searchParams.get("network_id");
912
+
913
+ // ── Path 1: legacy AUTH_TOKEN (master token) — unchanged ──
914
+ if (!authCtx && isLegacyAuthToken(req)) {
915
+ if (scopedNetId) {
916
+ const session = db.get<any>(
917
+ "SELECT 1 FROM sessions WHERE alias = ?1 AND network_id = ?2",
918
+ sessionName, scopedNetId
919
+ );
920
+ if (!session) return withCors(req, Response.json({ ok: false, error: "session not in requested network" }, { status: 403 }));
921
+ }
922
+ return createSSEStream(sessionName, scopedNetId);
923
+ }
924
+
925
+ // ── Path 2: ntok_ (network-bound agent token) — pre-#247 behavior preserved ──
926
+ if (token?.startsWith("ntok_")) {
927
+ if (!authCtx || !scopedNetId) {
928
+ return withCors(req, Response.json({ ok: false, error: "network-scoped token required for SSE" }, { status: 403 }));
929
+ }
930
+ const role = getUserNetworkRole(authCtx.userId, scopedNetId);
931
+ if (!role) return withCors(req, Response.json({ ok: false, error: "not a member of this network" }, { status: 403 }));
932
+ const session = db.get<any>(
933
+ "SELECT 1 FROM sessions WHERE alias = ?1 AND network_id = ?2",
934
+ sessionName, scopedNetId
935
+ );
936
+ if (!session && authCtx.networkId !== scopedNetId) {
937
+ return withCors(req, Response.json({ ok: false, error: "session not in requested network" }, { status: 403 }));
938
+ }
939
+ return createSSEStream(sessionName, scopedNetId);
940
+ }
941
+
942
+ // ── Path 3 (#247): utok_ (user token, dashboard SSE path) — 4 gates ──
943
+ //
944
+ // Pre-#247 the only V3 path required `ntok_` and rejected `utok_` outright,
945
+ // which locked the dashboard out of SSE (the dashboard proxy authenticates
946
+ // with the user's `utok_`). That broke real-time chat updates — replies
947
+ // were persisted but never live-pushed to the UI.
948
+ //
949
+ // Auth-scoping rules (all four must pass — see #247 design):
950
+ // gate 1: token resolves to a valid user context (authCtx non-null)
951
+ // gate 2: network scope is explicit — `utok_` has no implicit network,
952
+ // so the caller must pass `?network_id=<id>`
953
+ // gate 3: user is a member of that network (any role: owner / admin / member)
954
+ // gate 4: channel-ownership — one of:
955
+ // (a) sessionName === own username (the dashboard's default channel —
956
+ // `send_reply` pushes to the original sender's alias which equals
957
+ // the dashboard user's username; NO `sessions` row required for
958
+ // this branch since the dashboard user is not a registered agent)
959
+ // (b) sessionName is an existing agent alias in `scopedNetId`
960
+ // (lets members monitor agents within their network)
961
+ //
962
+ // Security: rule 4(a) uses strict equality, so a `utok_` user cannot subscribe
963
+ // to another user's username channel (no cross-user eavesdrop). Rule 4(b) is
964
+ // scoped to `scopedNetId` + gate 3 membership, so cross-network eavesdrop is
965
+ // blocked too. There is intentionally NO org-admin bypass — even users with
966
+ // global `admin` role must be a member of the network they want to listen on.
967
+ if (!authCtx) {
968
+ return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 403 }));
969
+ }
970
+ if (!scopedNetId) {
971
+ return withCors(req, Response.json({
972
+ ok: false,
973
+ error: "network_id required (utok has no implicit network; pass ?network_id=<id>)"
974
+ }, { status: 403 }));
975
+ }
976
+ const utokRole = getUserNetworkRole(authCtx.userId, scopedNetId);
977
+ if (!utokRole) {
978
+ return withCors(req, Response.json({ ok: false, error: "not a member of this network" }, { status: 403 }));
979
+ }
980
+ if (sessionName === authCtx.username) {
981
+ return createSSEStream(sessionName, scopedNetId);
982
+ }
983
+ const utokSession = db.get<any>(
984
+ "SELECT 1 FROM sessions WHERE alias = ?1 AND network_id = ?2",
985
+ sessionName, scopedNetId
986
+ );
987
+ if (!utokSession) {
988
+ return withCors(req, Response.json({
989
+ ok: false,
990
+ error: "channel not allowed: must be your username or an existing agent in your network"
991
+ }, { status: 403 }));
992
+ }
993
+ return createSSEStream(sessionName, scopedNetId);
994
+ }
995
+
996
+ // ── V3: License endpoints ──
997
+ if (url.pathname === "/api/license" && req.method === "GET") {
998
+ const license = db.get<any>(
999
+ "SELECT type, expires_at, max_agents, max_networks, max_tasks_day FROM licenses ORDER BY created_at LIMIT 1",
1000
+ );
1001
+ if (!license) return withCors(req, Response.json({ ok: true, status: "no_license" }));
1002
+ const now = new Date().toISOString().replace("T", " ").slice(0, 19);
1003
+ const expired = license.expires_at && license.expires_at < now;
1004
+ const daysLeft = license.expires_at
1005
+ ? Math.max(0, Math.ceil((new Date(license.expires_at).getTime() - Date.now()) / 86400000))
1006
+ : null;
1007
+ return withCors(req, Response.json({
1008
+ ok: true,
1009
+ license: { type: license.type, expires_at: license.expires_at, days_left: daysLeft, expired },
1010
+ limits: { max_agents: license.max_agents, max_networks: license.max_networks, max_tasks_day: license.max_tasks_day },
1011
+ }));
1012
+ }
1013
+
1014
+ if (url.pathname === "/api/license/activate" && req.method === "POST") {
1015
+ try {
1016
+ const body = await req.json() as any;
1017
+ const key = body.key;
1018
+ if (!key) return withCors(req, Response.json({ ok: false, error: "key required" }, { status: 400 }));
1019
+ // For now: accept any key starting with "anet-" as valid pro license
1020
+ if (!key.startsWith("anet-") || key.length < 16) {
1021
+ return withCors(req, Response.json({ ok: false, error: "invalid license key" }, { status: 400 }));
1022
+ }
1023
+ // Upgrade existing license or create new
1024
+ db.run("DELETE FROM licenses");
1025
+ const licId = `lic_${crypto.randomUUID().replace(/-/g, "").slice(0, 12)}`;
1026
+ db.run(
1027
+ "INSERT INTO licenses (id, license_key, type, max_agents, max_networks, max_tasks_day, activated_at, expires_at) VALUES (?1, ?2, 'pro', 50, 10, 10000, datetime('now'), datetime('now', '+365 days'))",
1028
+ [licId, key]
1029
+ );
1030
+ return withCors(req, Response.json({ ok: true, type: "pro", expires_in_days: 365 }));
1031
+ } catch (e: any) {
1032
+ return withCors(req, Response.json({ ok: false, error: e.message }, { status: 400 }));
1033
+ }
1034
+ }
1035
+
1036
+ // ── V3: Auth endpoints (public) ──
1037
+ if (url.pathname === "/api/auth/register" && req.method === "POST") {
1038
+ const clientIP = req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || "unknown";
1039
+ if (!checkRateLimit(clientIP, 30)) {
1040
+ return withCors(req, Response.json({ ok: false, error: "too many requests, try again later" }, { status: 429 }));
1041
+ }
1042
+ try {
1043
+ const body = await req.json() as any;
1044
+ const result = register(body.username, body.password, body.email, body.display_name);
1045
+ if (result.ok) logAudit(result.user!.user_id, body.username, "register", "user", result.user!.user_id);
1046
+ return withCors(req, Response.json(result, { status: result.ok ? 200 : 400 }));
1047
+ } catch (e: any) {
1048
+ return withCors(req, Response.json({ ok: false, error: e.message }, { status: 400 }));
1049
+ }
1050
+ }
1051
+
1052
+ if (url.pathname === "/api/auth/login" && req.method === "POST") {
1053
+ const clientIP = getLoginClientIp(req);
1054
+ const ipRate = sharedLoginIpRateLimiter.check(clientIP || "unknown");
1055
+ if (!ipRate.allowed) {
1056
+ logAudit(null, null, "login_rate_limited", "auth", undefined, clientIP);
1057
+ return withCors(req, Response.json(
1058
+ { ok: false, error: "rate_limited", message: "Too many login attempts. Try again later.", retry_after_ms: ipRate.retryAfterMs },
1059
+ { status: 429, headers: { "Retry-After": String(Math.ceil((ipRate.retryAfterMs ?? 1000) / 1000)) } }
1060
+ ));
1061
+ }
1062
+ try {
1063
+ const body = await req.json() as any;
1064
+ const lock = sharedLoginFailureLockout.check(body.username);
1065
+ if (lock.locked) {
1066
+ logAudit(null, body.username, "login_locked", "auth", undefined, `retry_after_ms=${lock.retryAfterMs ?? 0}`);
1067
+ return withCors(req, Response.json(
1068
+ { ok: false, error: "login_locked", message: "Too many failed login attempts. Try again later.", retry_after_ms: lock.retryAfterMs },
1069
+ { status: 429, headers: { "Retry-After": String(Math.ceil((lock.retryAfterMs ?? 1000) / 1000)) } }
1070
+ ));
1071
+ }
1072
+ const result = login(body.username, body.password);
1073
+ if (result.ok) {
1074
+ sharedLoginFailureLockout.recordSuccess(body.username);
1075
+ logAudit(result.user!.user_id, body.username, "login", "user", result.user!.user_id);
1076
+ } else {
1077
+ const failure = sharedLoginFailureLockout.recordFailure(body.username);
1078
+ if (failure.locked) {
1079
+ const safeUsername = String(body.username ?? "").replace(/[\r\n\t]/g, " ").slice(0, 80);
1080
+ console.warn(`[auth] login locked for username=${safeUsername} failures=${failure.failures} retry_after_ms=${failure.lockMs}`);
1081
+ }
1082
+ logAudit(null, body.username, "login_failed", "user", undefined, "invalid credentials");
1083
+ }
1084
+ return withCors(req, Response.json(result, { status: result.ok ? 200 : 401 }));
1085
+ } catch (e: any) {
1086
+ return withCors(req, Response.json({ ok: false, error: e.message }, { status: 400 }));
1087
+ }
1088
+ }
1089
+
1090
+ if (url.pathname === "/api/auth/me" && req.method === "GET") {
1091
+ const token = req.headers.get("Authorization")?.replace("Bearer ", "") || url.searchParams.get("token");
1092
+ if (!token) return withCors(req, Response.json({ ok: false, error: "token required" }, { status: 401 }));
1093
+ const resolved = resolveToken(token);
1094
+ if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
1095
+ const networks = getUserAllNetworks(resolved.user.user_id);
1096
+ return withCors(req, Response.json({ ok: true, user: resolved.user, networks, current_network: resolved.networkId }));
1097
+ }
1098
+
1099
+ if (url.pathname === "/api/auth/me" && req.method === "PUT") {
1100
+ const token = req.headers.get("Authorization")?.replace("Bearer ", "");
1101
+ if (!token) return withCors(req, Response.json({ ok: false, error: "token required" }, { status: 401 }));
1102
+ const resolved = resolveToken(token);
1103
+ if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
1104
+ try {
1105
+ const body = await req.json() as any;
1106
+ const updates: string[] = [];
1107
+ const params: any[] = [];
1108
+ if (body.display_name) { updates.push(`display_name = ?${params.length + 1}`); params.push(body.display_name); }
1109
+ if (body.email) { updates.push(`email = ?${params.length + 1}`); params.push(body.email); }
1110
+ if (updates.length > 0) {
1111
+ updates.push(`updated_at = datetime('now')`);
1112
+ params.push(resolved.user.user_id);
1113
+ db.run(`UPDATE users SET ${updates.join(", ")} WHERE user_id = ?${params.length}`, params);
1114
+ }
1115
+ // Re-fetch
1116
+ const user = db.get<any>("SELECT user_id, username, display_name, email, role FROM users WHERE user_id = ?1", resolved.user.user_id);
1117
+ return withCors(req, Response.json({ ok: true, user }));
1118
+ } catch (e: any) {
1119
+ return withCors(req, Response.json({ ok: false, error: e.message }, { status: 400 }));
1120
+ }
1121
+ }
1122
+
1123
+ if (url.pathname === "/api/auth/password" && req.method === "POST") {
1124
+ const token = req.headers.get("Authorization")?.replace("Bearer ", "");
1125
+ if (!token) return withCors(req, Response.json({ ok: false, error: "token required" }, { status: 401 }));
1126
+ const resolved = resolveToken(token);
1127
+ if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
1128
+ try {
1129
+ const body = await req.json() as any;
1130
+ const result = changePassword(resolved.user.user_id, body.old_password, body.new_password, resolved.tokenId);
1131
+ if (result.ok) {
1132
+ const issued = issueUserToken(resolved.user.user_id, "password-change");
1133
+ if (resolved.tokenId) revokeToken(resolved.user.user_id, resolved.tokenId);
1134
+ logAudit(resolved.user.user_id, resolved.user.username, "password_changed", "user", resolved.user.user_id);
1135
+ return withCors(req, Response.json({ ...result, token: issued.token, token_id: issued.token_id }));
1136
+ }
1137
+ return withCors(req, Response.json(result, { status: 400 }));
1138
+ } catch (e: any) {
1139
+ return withCors(req, Response.json({ ok: false, error: e.message }, { status: 400 }));
1140
+ }
1141
+ }
1142
+
1143
+ // ── V3.13: Create network token for a node ──
1144
+ if (url.pathname === "/api/auth/node-token" && req.method === "POST") {
1145
+ const token = req.headers.get("Authorization")?.replace("Bearer ", "");
1146
+ if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
1147
+ const resolved = resolveToken(token);
1148
+ if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
1149
+ try {
1150
+ const body = await req.json() as any;
1151
+ if (!body.network_id || !body.node_name) return withCors(req, Response.json({ ok: false, error: "network_id and node_name required" }, { status: 400 }));
1152
+ const result = createNetworkTokenForNode(resolved.user.user_id, body.network_id, body.node_name, body.node_id);
1153
+ if (result.ok) logAudit(resolved.user.user_id, resolved.user.username, "node_token_created", "network", body.network_id, body.node_name);
1154
+ return withCors(req, Response.json(result, { status: result.ok ? 200 : 400 }));
1155
+ } catch (e: any) {
1156
+ return withCors(req, Response.json({ ok: false, error: e.message }, { status: 400 }));
1157
+ }
1158
+ }
1159
+
1160
+ // ── #84: node rename 2PC — Server surface (RFC-010 §4) ──
1161
+ // The CLI orchestrates the 2PC; these endpoints are the Server steps:
1162
+ // prepare = PHASE 1 P3, commit = PHASE 2 C1, abort = PHASE 1 rollback.
1163
+ if (url.pathname === "/api/node-rename/prepare" && req.method === "POST") {
1164
+ const token = req.headers.get("Authorization")?.replace("Bearer ", "");
1165
+ if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
1166
+ const resolved = resolveToken(token);
1167
+ if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
1168
+ try {
1169
+ const body = await req.json() as any;
1170
+ if (!body.network_id || !body.old_alias || !body.new_alias) {
1171
+ return withCors(req, Response.json({ ok: false, error: "network_id, old_alias, new_alias required" }, { status: 400 }));
1172
+ }
1173
+ const result = prepareRename(resolved.user.user_id, body.network_id, body.old_alias, body.new_alias);
1174
+ if (result.ok) logAudit(resolved.user.user_id, resolved.user.username, "node_rename_prepared", "node", body.old_alias, body.new_alias);
1175
+ return withCors(req, Response.json(result, { status: result.ok || result.code === "node_local_only" ? 200 : 400 }));
1176
+ } catch (e: any) {
1177
+ return withCors(req, Response.json({ ok: false, error: e.message }, { status: 400 }));
1178
+ }
1179
+ }
1180
+
1181
+ if (url.pathname === "/api/node-rename/commit" && req.method === "POST") {
1182
+ const token = req.headers.get("Authorization")?.replace("Bearer ", "");
1183
+ if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
1184
+ const resolved = resolveToken(token);
1185
+ if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
1186
+ try {
1187
+ const body = await req.json() as any;
1188
+ if (!body.txn_id) return withCors(req, Response.json({ ok: false, error: "txn_id required" }, { status: 400 }));
1189
+ const result = commitRename(resolved.user.user_id, body.txn_id);
1190
+ if (result.ok) logAudit(resolved.user.user_id, resolved.user.username, "node_rename_committed", "node", body.txn_id);
1191
+ return withCors(req, Response.json(result, { status: result.ok ? 200 : 400 }));
1192
+ } catch (e: any) {
1193
+ return withCors(req, Response.json({ ok: false, error: e.message }, { status: 400 }));
1194
+ }
1195
+ }
1196
+
1197
+ if (url.pathname === "/api/node-rename/abort" && req.method === "POST") {
1198
+ const token = req.headers.get("Authorization")?.replace("Bearer ", "");
1199
+ if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
1200
+ const resolved = resolveToken(token);
1201
+ if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
1202
+ try {
1203
+ const body = await req.json() as any;
1204
+ if (!body.txn_id) return withCors(req, Response.json({ ok: false, error: "txn_id required" }, { status: 400 }));
1205
+ const result = abortRename(resolved.user.user_id, body.txn_id);
1206
+ if (result.ok) logAudit(resolved.user.user_id, resolved.user.username, "node_rename_aborted", "node", body.txn_id);
1207
+ return withCors(req, Response.json(result, { status: result.ok ? 200 : 400 }));
1208
+ } catch (e: any) {
1209
+ return withCors(req, Response.json({ ok: false, error: e.message }, { status: 400 }));
1210
+ }
1211
+ }
1212
+
1213
+ // ── V3: Token management ──
1214
+ if (url.pathname === "/api/auth/tokens" && req.method === "GET") {
1215
+ const token = req.headers.get("Authorization")?.replace("Bearer ", "");
1216
+ if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
1217
+ const resolved = resolveToken(token);
1218
+ if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
1219
+ const tokens = listTokens(resolved.user.user_id);
1220
+ return withCors(req, Response.json({ ok: true, tokens }));
1221
+ }
1222
+
1223
+ if (url.pathname === "/api/auth/tokens" && req.method === "POST") {
1224
+ const token = req.headers.get("Authorization")?.replace("Bearer ", "");
1225
+ if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
1226
+ const resolved = resolveToken(token);
1227
+ if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
1228
+ try {
1229
+ const body = await req.json() as any;
1230
+ const result = createToken(resolved.user.user_id, body.name || "api-token", body.network_id);
1231
+ if (result.ok) logAudit(resolved.user.user_id, resolved.user.username, "token_created", "token", result.token_id);
1232
+ return withCors(req, Response.json(result));
1233
+ } catch (e: any) {
1234
+ return withCors(req, Response.json({ ok: false, error: e.message }, { status: 400 }));
1235
+ }
1236
+ }
1237
+
1238
+ const tokenDeleteMatch = url.pathname.match(/^\/api\/auth\/tokens\/([^/]+)$/);
1239
+ if (tokenDeleteMatch && req.method === "DELETE") {
1240
+ const token = req.headers.get("Authorization")?.replace("Bearer ", "");
1241
+ if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
1242
+ const resolved = resolveToken(token);
1243
+ if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
1244
+ const result = revokeToken(resolved.user.user_id, tokenDeleteMatch[1]);
1245
+ if (result.ok) logAudit(resolved.user.user_id, resolved.user.username, "token_revoked", "token", tokenDeleteMatch[1]);
1246
+ return withCors(req, Response.json(result, { status: result.ok ? 200 : 404 }));
1247
+ }
1248
+
1249
+ // ── V3: Network management ──
1250
+ if (url.pathname === "/api/networks" && req.method === "GET") {
1251
+ const token = req.headers.get("Authorization")?.replace("Bearer ", "") || url.searchParams.get("token");
1252
+ if (!token) return withCors(req, Response.json({ ok: false, error: "token required" }, { status: 401 }));
1253
+ const resolved = resolveToken(token);
1254
+ if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
1255
+ // V3.13: ntok_ can only see its bound network; utok_ sees all member networks
1256
+ if (resolved.networkId) {
1257
+ // ntok_ — only return the bound network
1258
+ const net = db.get<any>(`SELECT ${NETWORK_REST_SELECT} FROM networks WHERE network_id = ?1`, resolved.networkId);
1259
+ return withCors(req, Response.json({ ok: true, networks: net ? [withNetworkNameAlias(net)] : [] }));
1260
+ }
1261
+ // Global Hub admins have cross-network authority throughout the REST
1262
+ // surface, so limiting this discovery endpoint to their membership rows
1263
+ // made otherwise-authorized networks impossible to select (#94). Keep
1264
+ // ordinary utok_ callers membership-scoped; ntok_ returned above stays
1265
+ // bound to exactly one network.
1266
+ const networks = resolved.user.role === "admin"
1267
+ ? db.all<any>(
1268
+ `SELECT ${NETWORK_REST_SELECT},
1269
+ COALESCE((SELECT nm.role FROM network_members nm
1270
+ WHERE nm.network_id = networks.network_id
1271
+ AND nm.user_id = ?1), 'admin') AS member_role
1272
+ FROM networks ORDER BY created_at`,
1273
+ resolved.user.user_id,
1274
+ )
1275
+ : getUserAllNetworks(resolved.user.user_id);
1276
+ const visibleNetworks = networks.map(withNetworkNameAlias);
1277
+ return withCors(req, Response.json({ ok: true, networks: visibleNetworks }));
1278
+ }
1279
+
1280
+ if (url.pathname === "/api/networks" && req.method === "POST") {
1281
+ const token = req.headers.get("Authorization")?.replace("Bearer ", "") || url.searchParams.get("token");
1282
+ if (!token) return withCors(req, Response.json({ ok: false, error: "token required" }, { status: 401 }));
1283
+ const resolved = resolveToken(token);
1284
+ if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
1285
+ try {
1286
+ const body = await req.json() as any;
1287
+ const result = createNetwork(resolved.user.user_id, body.name, body.description);
1288
+ return withCors(req, Response.json(result, { status: result.ok ? 200 : 400 }));
1289
+ } catch (e: any) {
1290
+ return withCors(req, Response.json({ ok: false, error: e.message }, { status: 400 }));
1291
+ }
1292
+ }
1293
+
1294
+ // ── V3.13: Network members + invites ──
1295
+ const membersMatch = url.pathname.match(/^\/api\/networks\/([^/]+)\/members(?:\/([^/]+))?$/);
1296
+ if (membersMatch) {
1297
+ const token = req.headers.get("Authorization")?.replace("Bearer ", "") || url.searchParams.get("token");
1298
+ if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
1299
+ const resolved = resolveToken(token);
1300
+ if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
1301
+ const netId = membersMatch[1];
1302
+ const targetUid = membersMatch[2];
1303
+ const callerRole = getUserNetworkRole(resolved.user.user_id, netId);
1304
+ if (!callerRole) return withCors(req, Response.json({ ok: false, error: "not a member of this network" }, { status: 403 }));
1305
+
1306
+ if (req.method === "GET") {
1307
+ if (!["owner", "admin"].includes(callerRole)) return withCors(req, Response.json({ ok: false, error: "owner/admin required" }, { status: 403 }));
1308
+ const members = getNetworkMembers(netId);
1309
+ return withCors(req, Response.json({ ok: true, members }));
1310
+ }
1311
+ if (req.method === "POST") {
1312
+ if (!["owner", "admin"].includes(callerRole)) return withCors(req, Response.json({ ok: false, error: "owner/admin required" }, { status: 403 }));
1313
+ const body = await req.json() as any;
1314
+ const result = addNetworkMember(netId, body.user_id, body.role || "member", resolved.user.user_id);
1315
+ if (result.ok) logAudit(resolved.user.user_id, resolved.user.username, "member_added", "network", netId, `${body.user_id} as ${body.role || "member"}`);
1316
+ return withCors(req, Response.json(result, { status: result.ok ? 200 : 400 }));
1317
+ }
1318
+ if (req.method === "PUT" && targetUid) {
1319
+ if (callerRole !== "owner") return withCors(req, Response.json({ ok: false, error: "owner required" }, { status: 403 }));
1320
+ const body = await req.json() as any;
1321
+ const result = updateMemberRole(netId, targetUid, body.role);
1322
+ if (result.ok) logAudit(resolved.user.user_id, resolved.user.username, "member_role_changed", "network", netId, `${targetUid} → ${body.role}`);
1323
+ return withCors(req, Response.json(result, { status: result.ok ? 200 : 400 }));
1324
+ }
1325
+ if (req.method === "DELETE" && targetUid) {
1326
+ if (!["owner", "admin"].includes(callerRole)) return withCors(req, Response.json({ ok: false, error: "owner/admin required" }, { status: 403 }));
1327
+ const result = removeNetworkMember(netId, targetUid);
1328
+ if (result.ok) logAudit(resolved.user.user_id, resolved.user.username, "member_removed", "network", netId, targetUid);
1329
+ return withCors(req, Response.json(result, { status: result.ok ? 200 : 400 }));
1330
+ }
1331
+ }
1332
+
1333
+ if (url.pathname.match(/^\/api\/networks\/([^/]+)\/invite$/) && req.method === "POST") {
1334
+ const token = req.headers.get("Authorization")?.replace("Bearer ", "") || url.searchParams.get("token");
1335
+ if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
1336
+ const resolved = resolveToken(token);
1337
+ if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
1338
+ const netId = url.pathname.split("/")[3];
1339
+ const callerRole = getUserNetworkRole(resolved.user.user_id, netId);
1340
+ if (!callerRole || !["owner", "admin"].includes(callerRole)) {
1341
+ return withCors(req, Response.json({ ok: false, error: "owner/admin required" }, { status: 403 }));
1342
+ }
1343
+ const body = await req.json() as any;
1344
+ const result = createInvite(netId, resolved.user.user_id, body.role || "member", body.max_uses || 1, body.expires_days);
1345
+ if (result.ok) logAudit(resolved.user.user_id, resolved.user.username, "invite_created", "network", netId, result.invite_code);
1346
+ return withCors(req, Response.json(result));
1347
+ }
1348
+
1349
+ if (url.pathname === "/api/networks/join" && req.method === "POST") {
1350
+ const token = req.headers.get("Authorization")?.replace("Bearer ", "") || url.searchParams.get("token");
1351
+ if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
1352
+ const resolved = resolveToken(token);
1353
+ if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
1354
+ const body = await req.json() as any;
1355
+ const result = joinByInvite(body.invite_code, resolved.user.user_id);
1356
+ if (result.ok) logAudit(resolved.user.user_id, resolved.user.username, "network_joined", "network", result.network_id, `via invite, role=${result.role}`);
1357
+ return withCors(req, Response.json(result, { status: result.ok ? 200 : 400 }));
1358
+ }
1359
+
1360
+ // ── V3: Admin APIs (require auth) ──
1361
+ if (url.pathname === "/api/users" && req.method === "GET") {
1362
+ const token = req.headers.get("Authorization")?.replace("Bearer ", "");
1363
+ if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
1364
+ const resolved = resolveToken(token);
1365
+ if (!resolved || resolved.user.role !== "admin") {
1366
+ return withCors(req, Response.json({ ok: false, error: "admin required" }, { status: 403 }));
1367
+ }
1368
+ const users = db.all("SELECT user_id, username, display_name, email, role, created_at FROM users ORDER BY created_at");
1369
+ return withCors(req, Response.json({ ok: true, users }));
1370
+ }
1371
+
1372
+ const netDetailMatch = url.pathname.match(/^\/api\/networks\/([^/]+)$/);
1373
+ if (netDetailMatch && req.method === "GET") {
1374
+ const token = req.headers.get("Authorization")?.replace("Bearer ", "") || url.searchParams.get("token");
1375
+ if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
1376
+ const resolved = resolveToken(token);
1377
+ if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
1378
+ const networkId = netDetailMatch[1];
1379
+ const network = db.get<any>(`SELECT ${NETWORK_REST_SELECT} FROM networks WHERE network_id = ?1`, networkId);
1380
+ if (!network) return withCors(req, Response.json({ ok: false, error: "network not found" }, { status: 404 }));
1381
+ // Membership check: must be a member or system admin
1382
+ const viewerRole = getUserNetworkRole(resolved.user.user_id, networkId);
1383
+ if (!viewerRole && resolved.user.role !== "admin") {
1384
+ return withCors(req, Response.json({ ok: false, error: "access denied" }, { status: 403 }));
1385
+ }
1386
+ // Get network stats
1387
+ const nodeCount = db.get<{ cnt: number }>("SELECT COUNT(*) as cnt FROM nodes WHERE network_id = ?1", networkId);
1388
+ const sessionCount = db.get<{ cnt: number }>("SELECT COUNT(*) as cnt FROM sessions WHERE network_id = ?1", networkId);
1389
+ const taskStats = db.all<any>("SELECT status, COUNT(*) as count FROM tasks WHERE network_id = ?1 GROUP BY status", networkId);
1390
+ return withCors(req, Response.json({
1391
+ ok: true, network,
1392
+ stats: { nodes: nodeCount?.cnt || 0, sessions: sessionCount?.cnt || 0, tasks: taskStats },
1393
+ }));
1394
+ }
1395
+
1396
+ if (netDetailMatch && req.method === "DELETE") {
1397
+ const token = req.headers.get("Authorization")?.replace("Bearer ", "") || url.searchParams.get("token");
1398
+ if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
1399
+ const resolved = resolveToken(token);
1400
+ if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
1401
+ const result = deleteNetwork(resolved.user.user_id, netDetailMatch[1]);
1402
+ if (result.ok) logAudit(resolved.user.user_id, resolved.user.username, "network_deleted", "network", netDetailMatch[1]);
1403
+ return withCors(req, Response.json(result, { status: result.ok ? 200 : 400 }));
1404
+ }
1405
+
1406
+ if (netDetailMatch && req.method === "PUT") {
1407
+ const token = req.headers.get("Authorization")?.replace("Bearer ", "") || url.searchParams.get("token");
1408
+ if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
1409
+ const resolved = resolveToken(token);
1410
+ if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
1411
+ try {
1412
+ const body = await req.json() as any;
1413
+ if (body.name) {
1414
+ const result = renameNetwork(resolved.user.user_id, netDetailMatch[1], body.name);
1415
+ if (result.ok) logAudit(resolved.user.user_id, resolved.user.username, "network_renamed", "network", netDetailMatch[1], body.name);
1416
+ return withCors(req, Response.json(result, { status: result.ok ? 200 : 400 }));
1417
+ }
1418
+ return withCors(req, Response.json({ ok: false, error: "name required" }, { status: 400 }));
1419
+ } catch (e: any) {
1420
+ return withCors(req, Response.json({ ok: false, error: e.message }, { status: 400 }));
1421
+ }
1422
+ }
1423
+
1424
+ // ── REST: health (public, no auth) ──
1425
+ if (url.pathname === "/health") {
1426
+ // #473 — /health is ANONYMOUS BY CONTRACT (the central watchdog
1427
+ // cron curls it every minute to decide dead-or-alive; adding auth
1428
+ // here would blind it — do NOT add requireAuth, do NOT change the
1429
+ // 200-with-JSON shape without telling the watchdog owner first).
1430
+ // Anonymous callers get AGGREGATES ONLY. The per-key SSE detail
1431
+ // (`{networkId}:{alias}` + observer keys) used to be inlined here,
1432
+ // which handed any internet stranger the full network id + all
1433
+ // agent aliases (95 on the public hub when audited) — that detail
1434
+ // now lives behind auth at GET /api/stats/sse.
1435
+ // `version` stays: it does help fingerprinting, but ops needs it
1436
+ // to verify deploys land, and the tradeoff was accepted in review.
1437
+ //
1438
+ // #495-followup / f28a6c1b — auth-gated `sse_sessions` restored so
1439
+ // the dashboard's own "online" widget can compute per-agent status
1440
+ // in one round-trip. Rules:
1441
+ // - anonymous (no valid token): NO sse_sessions field → watchdog
1442
+ // contract untouched, no topology leak (mutation removing this
1443
+ // gate turns the anonymous test RED — see health-redaction.test)
1444
+ // - admin utok_ / legacy master / DEV_OPEN: full sessions map
1445
+ // (parity with /api/stats/sse ops path)
1446
+ // - regular utok_ member: sessions map FILTERED to network_ids
1447
+ // the caller is a member of — safe against the "any account
1448
+ // sees all-network topology" regression the #473 fix closed;
1449
+ // dashboard user proxies with the logged-in user's utok_ so
1450
+ // their own network's aliases surface; strangers' networks do
1451
+ // not
1452
+ const count = db.get<{ cnt: number }>("SELECT COUNT(*) as cnt FROM sessions");
1453
+ const sse = getSSEStats();
1454
+ const license = db.get<any>("SELECT type, expires_at FROM licenses LIMIT 1");
1455
+
1456
+ // Non-fatal auth probe (no 401 — /health must stay 200 anonymous).
1457
+ const healthAuth = resolveRequestAuth(req);
1458
+ const healthIsMaster = !healthAuth && isLegacyAuthToken(req);
1459
+ const healthIsDevOpen = !healthAuth && !AUTH_TOKEN && DEV_OPEN;
1460
+ const healthIsAdmin = !!(healthAuth?.username && db.get<any>(
1461
+ "SELECT role FROM users WHERE username = ?1", healthAuth.username,
1462
+ )?.role === "admin");
1463
+
1464
+ let scopedSessions: Record<string, number> | undefined;
1465
+ if (healthIsMaster || healthIsDevOpen || healthIsAdmin) {
1466
+ // Ops parity with /api/stats/sse — full map.
1467
+ scopedSessions = sse.sessions;
1468
+ } else if (healthAuth?.userId) {
1469
+ // Regular authenticated member — filter to networks they belong
1470
+ // to. Keys are `{networkId}:{alias}` (or observer keys shaped
1471
+ // `\0netobs:{networkId}`); parse the network prefix and keep
1472
+ // only entries whose network is in the member's set.
1473
+ //
1474
+ // 🔴 ntok_ (network-scoped token) MUST be forced to its single
1475
+ // bound network (parity with resolveRestNetworkScope L277:
1476
+ // `if (authCtx.networkId) return { networkId: authCtx.networkId }`).
1477
+ // Falling through to the utok_ union query would return
1478
+ // sessions from every network the underlying user belongs to,
1479
+ // silently escalating a network-scoped token to a user-scoped
1480
+ // token — the exact "认证 ≠ 已授权" mistake this whole change
1481
+ // is meant to prevent. Same shape as f28a6c1b root cause; see
1482
+ // CR3 audit 4703b0e7.
1483
+ const memberNets = new Set<string>(
1484
+ healthAuth.networkId
1485
+ ? [healthAuth.networkId] // ntok_ single-network enforce
1486
+ : db.all<{ network_id: string }>(
1487
+ "SELECT network_id FROM network_members WHERE user_id = ?1",
1488
+ healthAuth.userId,
1489
+ ).map((r) => r.network_id),
1490
+ );
1491
+ // If member has no networks at all, keep field present but empty
1492
+ // so the dashboard can distinguish "authenticated + none active"
1493
+ // from "not authenticated at all".
1494
+ const filtered: Record<string, number> = {};
1495
+ for (const [key, n] of Object.entries(sse.sessions)) {
1496
+ // Observer keys are shape `\0netobs:<networkId>` raw; keyed
1497
+ // through `printableKey()` in push.ts, they surface here as
1498
+ // the literal string `\\0netobs:<networkId>` (backslash-zero,
1499
+ // not NUL byte). Use the shared `PRINTABLE_OBSERVER_KEY_PREFIX`
1500
+ // export so this side and the emitter side stay locked to the
1501
+ // same literal — CR3 audit 4703b0e7 caught prior check
1502
+ // `startsWith("netobs:")` was always false → observer keys
1503
+ // silently over-filtered out of member views.
1504
+ const isObserver = key.startsWith(PRINTABLE_OBSERVER_KEY_PREFIX);
1505
+ const netId = isObserver
1506
+ ? key.slice(PRINTABLE_OBSERVER_KEY_PREFIX.length)
1507
+ : key.split(":")[0];
1508
+ if (memberNets.has(netId)) filtered[key] = n;
1509
+ }
1510
+ scopedSessions = filtered;
1511
+ }
1512
+ // healthAuth == null AND no legacy master AND no DEV_OPEN → leave
1513
+ // scopedSessions undefined → sse_sessions field omitted entirely
1514
+ // (watchdog + arbitrary internet strangers see aggregates only).
1515
+
1516
+ const body: Record<string, unknown> = {
1517
+ ok: true,
1518
+ version: SERVER_VERSION,
1519
+ api_version: "v3",
1520
+ transport: "streamable-http",
1521
+ sessions_count: count?.cnt ?? 0,
1522
+ sse_connections: sse.total,
1523
+ auth: DEV_OPEN ? "dev-open" : "user-token",
1524
+ security: DEV_OPEN ? "dev-open" : "secured",
1525
+ tmux: TMUX_ENABLED ? "enabled" : "disabled",
1526
+ v3_auth: true,
1527
+ multi_network: true,
1528
+ license: license?.type || "none",
1529
+ uptime: Math.floor(process.uptime()),
1530
+ // #496 — public, stable capability data. Dashboard upload proxies
1531
+ // need the Hub's real limits before opening a streaming request;
1532
+ // duplicating these constants client-side creates a silent
1533
+ // lower-limit drift that the Hub can never observe.
1534
+ limits: {
1535
+ max_upload_bytes: MAX_UPLOAD_BYTES,
1536
+ max_request_content_length: MAX_REQUEST_CONTENT_LENGTH,
1537
+ },
1538
+ };
1539
+ if (scopedSessions !== undefined) body.sse_sessions = scopedSessions;
1540
+ return withCors(req, Response.json(body));
1541
+ }
1542
+
1543
+ // ── All REST /api endpoints require auth (if token configured) ──
1544
+ const authErr = requireAuth(req);
1545
+ if (authErr) return withCors(req, authErr);
1546
+
1547
+ // Resolve network scope for REST queries — enforce isolation
1548
+ // Token-bound networkId takes precedence (ntok_ → forced), then query param
1549
+ const restAuth = resolveRequestAuth(req);
1550
+ const isAdmin = !!(restAuth?.username && db.get<any>("SELECT role FROM users WHERE username = ?1", restAuth.username)?.role === "admin");
1551
+ const restScope = resolveRestNetworkScope(url.searchParams.get("network_id"), restAuth, isAdmin);
1552
+ if (restScope.denied) {
1553
+ return withCors(req, Response.json({ ok: false, error: restScope.denied }, { status: 403 }));
1554
+ }
1555
+
1556
+ const sideActor = resolveSideThreadActor(req, resolveRequestAuth(req, { allowQueryToken: false }), isAdmin);
1557
+ const nodeCommandActor = sideActor?.kind === "node" && sideActor.boundNodeId && sideActor.boundNetworkId
1558
+ ? { tokenId: sideActor.tokenId, networkId: sideActor.boundNetworkId, nodeId: sideActor.boundNodeId }
1559
+ : null;
1560
+ if (productionSideThreadTransport) {
1561
+ const attachmentResponse = await productionSideThreadTransport.attachment(req, url, nodeCommandActor);
1562
+ if (attachmentResponse) return withCors(req, attachmentResponse);
1563
+ const commandResponse = await productionSideThreadTransport.handle({ req, url, actor: nodeCommandActor });
1564
+ if (commandResponse) return withCors(req, commandResponse);
1565
+ }
1566
+
1567
+ const sideThreadResponse = await handleSideThreadHttpRequest({
1568
+ req,
1569
+ url,
1570
+ // Durable prompts/results never accept query-string credentials.
1571
+ actor: sideActor,
1572
+ coordinator: sideThreadCoordinator,
1573
+ resolveCapabilityTarget: resolveSideThreadCapabilityTarget,
1574
+ });
1575
+ if (sideThreadResponse) return withCors(req, sideThreadResponse);
1576
+
1577
+ // RFC-036 owner-gated host schedule edits. This handler independently
1578
+ // verifies exact node ownership and node-token binding; network admin is
1579
+ // deliberately not an override.
1580
+ const requestCredential = requestToken(req);
1581
+ const externalScheduleEditResponse = await handleExternalScheduleEditRequest({
1582
+ req,
1583
+ url,
1584
+ auth: restAuth,
1585
+ isUserToken: requestCredential.startsWith("utok_"),
1586
+ isNodeToken: requestCredential.startsWith("ntok_"),
1587
+ });
1588
+ if (externalScheduleEditResponse) return withCors(req, externalScheduleEditResponse);
1589
+
1590
+ // Hub-owned scheduled tasks. Dashboard and mobile are management
1591
+ // clients only; each occurrence is dispatched as an ordinary task by the
1592
+ // scheduler started in startHub(). Node tokens are rejected in the
1593
+ // handler so an agent cannot grant itself a persistent execution loop.
1594
+ const scheduledResponse = await handleScheduledTaskRequest({
1595
+ req,
1596
+ url,
1597
+ auth: restAuth,
1598
+ isAdmin,
1599
+ isNodeToken: requestToken(req).startsWith("ntok_"),
1600
+ scope: restScope,
1601
+ });
1602
+ if (scheduledResponse) return withCors(req, scheduledResponse);
1603
+
1604
+ // ── #473 REST: SSE connection detail (ops-only) ──
1605
+ // The per-key breakdown /health used to expose anonymously: keys are
1606
+ // `{networkId}:{alias}` (+ `\0netobs:{networkId}` observer keys via
1607
+ // printableKey), i.e. the full network/agent topology. Ops-scoped:
1608
+ // legacy master token (restAuth null once requireAuth passed) or an
1609
+ // admin user. Regular members get 403 — the detail spans EVERY
1610
+ // network, so per-network filtering would be required to open it
1611
+ // wider; no consumer needs that today.
1612
+ if (url.pathname === "/api/stats/sse") {
1613
+ // restAuth === null here means the caller passed the legacy master
1614
+ // token (requireAuth already accepted it above) OR the hub runs in
1615
+ // DEV_OPEN mode. Both are treated as ops: master token is root, and
1616
+ // under DEV_OPEN this endpoint is anonymously readable BY DESIGN
1617
+ // (dev convenience — production never sets COMMHUB_DEV_OPEN, so the
1618
+ // topology detail stays gated in every real deployment).
1619
+ if (restAuth && !isAdmin) {
1620
+ return withCors(req, Response.json({ ok: false, error: "admin or master token required" }, { status: 403 }));
1621
+ }
1622
+ const sse = getSSEStats();
1623
+ return withCors(req, Response.json({ ok: true, total: sse.total, sessions: sse.sessions }));
1624
+ }
1625
+
1626
+ // ── REST: all sessions status ──
1627
+ if (url.pathname === "/api/status") {
1628
+ // Round-2/4 review ③: stale-marking moved to startStaleSessionSweeper()
1629
+ // (background timer, ~60s cadence). Read paths no longer fire UPDATE.
1630
+ // Per-request UPDATE was a write-amp vector — see stale-sweeper.ts.
1631
+ cleanupCommittedRenameSessions(restScope.networkId ? [restScope.networkId] : restScope.networkIds ?? null);
1632
+ // `?light=1` returns a narrow projection (alias / status / agent / task /
1633
+ // server / updated_at + runtime + network_id) — used by the mobile APP
1634
+ // list view, where pulling 30+ fields × 150 agents was making cold open
1635
+ // take 12s+ on flaky cellular (Vincent tg, #220 PWA). Default response
1636
+ // is unchanged so the dashboard / scripts that read full telemetry are
1637
+ // unaffected.
1638
+ const isLight = url.searchParams.get("light") === "1";
1639
+ const params: any[] = [];
1640
+ let sql = isLight
1641
+ ? "SELECT alias, status, agent, task, server, updated_at, network_id FROM sessions WHERE 1=1"
1642
+ : `SELECT ${SESSION_REST_SELECT} FROM sessions WHERE 1=1`;
1643
+ sql = addNetworkScope(sql, params, restScope);
1644
+ sql += " ORDER BY updated_at DESC";
1645
+ // `model` comes straight from the explicit sessions projection; `runtime` is
1646
+ // derived from the raw `agent` field. Both default to null for old nodes
1647
+ // that never reported a model — the dashboard falls back to a placeholder.
1648
+ const sessions = db.all(sql, ...params).map((s: any) => {
1649
+ if (isLight) {
1650
+ return {
1651
+ alias: s.alias,
1652
+ status: s.status,
1653
+ agent: s.agent ?? null,
1654
+ task: s.task ?? null,
1655
+ server: s.server ?? null,
1656
+ updated_at: s.updated_at ?? null,
1657
+ runtime: normalizeRuntime(s.agent),
1658
+ network_id: s.network_id ?? null,
1659
+ };
1660
+ }
1661
+ const externalSchedules = (() => {
1662
+ if (typeof s.external_schedules !== "string") return null;
1663
+ try { return JSON.parse(s.external_schedules); } catch { return null; }
1664
+ })();
1665
+ const { external_schedules: _externalSchedulesJson, ...publicSession } = s;
1666
+ return {
1667
+ ...publicSession,
1668
+ external_schedules: externalSchedules,
1669
+ model: s.model ?? null,
1670
+ runtime: normalizeRuntime(s.agent),
1671
+ host: {
1672
+ hostname: s.hostname ?? null,
1673
+ ip: s.ip ?? null,
1674
+ cpu_load_1min: s.cpu_load_1min ?? null,
1675
+ cpu_cores: s.cpu_cores ?? null,
1676
+ mem_total_gb: s.mem_total_gb ?? null,
1677
+ mem_used_gb: s.mem_used_gb ?? null,
1678
+ mem_avail_gb: s.mem_avail_gb ?? null,
1679
+ disk_total_gb: s.disk_total_gb ?? null,
1680
+ disk_used_gb: s.disk_used_gb ?? null,
1681
+ disk_avail_gb: s.disk_avail_gb ?? null,
1682
+ },
1683
+ process_telemetry: {
1684
+ rss_bytes: s.process_rss_bytes ?? null,
1685
+ rss_mb: s.process_rss_mb ?? null,
1686
+ cpu_pct: s.process_cpu_pct ?? null,
1687
+ uptime_seconds: s.process_uptime_seconds ?? null,
1688
+ in_flight_count: s.process_in_flight_count ?? null,
1689
+ },
1690
+ };
1691
+ });
1692
+ const summary = sessions.reduce((acc: any, session: any) => {
1693
+ const raw = String(session.status || "").toLowerCase();
1694
+ if (raw === "offline") acc.offline++;
1695
+ else if (["working", "blocked", "error", "waiting_input", "running", "busy"].includes(raw)) acc.working++;
1696
+ else acc.idle++;
1697
+ return acc;
1698
+ }, { idle: 0, working: 0, offline: 0, total: sessions.length });
1699
+ return withCors(req, Response.json({ ok: true, sessions, summary }));
1700
+ }
1701
+
1702
+ // ── REST: aggregate agents by physical server ──
1703
+ if (url.pathname === "/api/servers") {
1704
+ // Round-2/4 review ③: stale-marking moved to background sweeper.
1705
+ const params: any[] = [];
1706
+ let sql = `
1707
+ SELECT hostname, ip, cpu_load_1min, cpu_cores, mem_avail_gb, mem_used_gb,
1708
+ COALESCE(last_seen_at, updated_at) AS last_seen
1709
+ FROM sessions
1710
+ WHERE 1=1
1711
+ `;
1712
+ sql = addNetworkScope(sql, params, restScope);
1713
+ sql += " ORDER BY COALESCE(last_seen_at, updated_at) DESC";
1714
+
1715
+ const grouped = new Map<string, {
1716
+ hostname: string;
1717
+ ip: string;
1718
+ agent_count: number;
1719
+ cpu_load_1min: number | null;
1720
+ cpu_cores: number | null;
1721
+ mem_avail_gb: number | null;
1722
+ mem_used_gb: number | null;
1723
+ last_seen: string | null;
1724
+ }>();
1725
+
1726
+ const preferDisplayIp = (current: string, next: string) => {
1727
+ const isWeak = (ip: string) => !ip || ip === "unknown" || ip === "127.0.0.1" || ip === "::1";
1728
+ if (isWeak(current) && !isWeak(next)) return next;
1729
+ return current;
1730
+ };
1731
+ const hasHostTelemetry = (row: any) =>
1732
+ row.cpu_load_1min != null || row.cpu_cores != null || row.mem_avail_gb != null || row.mem_used_gb != null;
1733
+
1734
+ for (const row of db.all<any>(sql, ...params)) {
1735
+ const hostname = row.hostname || "unknown";
1736
+ const ip = row.ip || "unknown";
1737
+ // Group primarily by hostname. A single host can report both a
1738
+ // routable/container IP and loopback (127.0.0.1); splitting those
1739
+ // into separate cards makes the dashboard show one useful load row
1740
+ // plus one "n/a" duplicate. Unknown hostnames still fall back to IP.
1741
+ const key = hostname !== "unknown" ? `host:${hostname}` : `ip:${ip}`;
1742
+ const existing = grouped.get(key);
1743
+ if (existing) {
1744
+ existing.agent_count += 1;
1745
+ existing.ip = preferDisplayIp(existing.ip, ip);
1746
+ if (parseSqliteTime(row.last_seen) > parseSqliteTime(existing.last_seen)) existing.last_seen = row.last_seen ?? existing.last_seen;
1747
+ if (hasHostTelemetry(row) && (
1748
+ existing.cpu_load_1min == null ||
1749
+ existing.cpu_cores == null ||
1750
+ existing.mem_avail_gb == null ||
1751
+ existing.mem_used_gb == null
1752
+ )) {
1753
+ existing.cpu_load_1min = row.cpu_load_1min ?? existing.cpu_load_1min;
1754
+ existing.cpu_cores = row.cpu_cores ?? existing.cpu_cores;
1755
+ existing.mem_avail_gb = row.mem_avail_gb ?? existing.mem_avail_gb;
1756
+ existing.mem_used_gb = row.mem_used_gb ?? existing.mem_used_gb;
1757
+ }
1758
+ continue;
1759
+ }
1760
+ grouped.set(key, {
1761
+ hostname,
1762
+ ip,
1763
+ agent_count: 1,
1764
+ cpu_load_1min: row.cpu_load_1min ?? null,
1765
+ cpu_cores: row.cpu_cores ?? null,
1766
+ mem_avail_gb: row.mem_avail_gb ?? null,
1767
+ mem_used_gb: row.mem_used_gb ?? null,
1768
+ last_seen: row.last_seen ?? null,
1769
+ });
1770
+ }
1771
+
1772
+ return withCors(req, Response.json(Array.from(grouped.values())));
1773
+ }
1774
+
1775
+ const serverDetailMatch = url.pathname.match(/^\/api\/server\/([^/]+)\/(health|agents)$/);
1776
+ if (serverDetailMatch && req.method === "GET") {
1777
+ const host = decodeURIComponent(serverDetailMatch[1]);
1778
+ const detailKind = serverDetailMatch[2];
1779
+ if (!host) return withCors(req, Response.json({ ok: false, error: "host required" }, { status: 400 }));
1780
+
1781
+ // Round-2/4 review ③: stale-marking moved to background sweeper.
1782
+ if (detailKind === "agents") {
1783
+ const params: any[] = [host, host];
1784
+ let sql = `
1785
+ SELECT alias, agent, status, task, progress, model, hostname, ip, external_schedules,
1786
+ cpu_load_1min, cpu_cores, mem_avail_gb, mem_used_gb, mem_total_gb,
1787
+ disk_avail_gb, disk_used_gb, disk_total_gb,
1788
+ process_rss_bytes, process_rss_mb, process_cpu_pct, process_uptime_seconds, process_in_flight_count,
1789
+ COALESCE(last_seen_at, updated_at) AS last_seen
1790
+ FROM sessions
1791
+ WHERE (hostname = ?1 OR ip = ?2)
1792
+ `;
1793
+ sql = addNetworkScope(sql, params, restScope);
1794
+ sql += " ORDER BY alias";
1795
+ const agents = db.all<any>(sql, ...params).map((s) => ({
1796
+ alias: s.alias,
1797
+ runtime: normalizeRuntime(s.agent),
1798
+ raw_agent: s.agent ?? null,
1799
+ model: s.model ?? null,
1800
+ status: s.status ?? "offline",
1801
+ task: s.task ?? null,
1802
+ progress: s.progress ?? 0,
1803
+ external_schedules: (() => {
1804
+ if (typeof s.external_schedules !== "string") return null;
1805
+ try { return JSON.parse(s.external_schedules); } catch { return null; }
1806
+ })(),
1807
+ last_seen: s.last_seen ?? null,
1808
+ health: agentHealthChip(s.status, s.last_seen),
1809
+ hostname: s.hostname ?? null,
1810
+ ip: s.ip ?? null,
1811
+ telemetry: {
1812
+ cpu_load_1min: s.cpu_load_1min ?? null,
1813
+ cpu_cores: s.cpu_cores ?? null,
1814
+ cpu_pct: cpuPct(s.cpu_load_1min, s.cpu_cores),
1815
+ mem_total_gb: s.mem_total_gb ?? null,
1816
+ mem_used_gb: s.mem_used_gb ?? null,
1817
+ mem_avail_gb: s.mem_avail_gb ?? null,
1818
+ disk_total_gb: s.disk_total_gb ?? null,
1819
+ disk_used_gb: s.disk_used_gb ?? null,
1820
+ disk_avail_gb: s.disk_avail_gb ?? null,
1821
+ process_rss_bytes: s.process_rss_bytes ?? null,
1822
+ process_rss_mb: s.process_rss_mb ?? null,
1823
+ process_cpu_pct: s.process_cpu_pct ?? null,
1824
+ process_uptime_seconds: s.process_uptime_seconds ?? null,
1825
+ process_in_flight_count: s.process_in_flight_count ?? null,
1826
+ },
1827
+ process_telemetry: {
1828
+ rss_bytes: s.process_rss_bytes ?? null,
1829
+ rss_mb: s.process_rss_mb ?? null,
1830
+ cpu_pct: s.process_cpu_pct ?? null,
1831
+ uptime_seconds: s.process_uptime_seconds ?? null,
1832
+ in_flight_count: s.process_in_flight_count ?? null,
1833
+ },
1834
+ }));
1835
+ if (agents.length === 0) return withCors(req, Response.json({ ok: false, error: "server not found" }, { status: 404 }));
1836
+ return withCors(req, Response.json({ ok: true, host, agent_count: agents.length, agents }));
1837
+ }
1838
+
1839
+ const latestParams: any[] = [host, host];
1840
+ let latestSql = `
1841
+ SELECT hostname, ip, COUNT(*) OVER () AS agent_count,
1842
+ cpu_load_1min, cpu_cores, mem_total_gb, mem_used_gb, mem_avail_gb,
1843
+ disk_total_gb, disk_used_gb, disk_avail_gb,
1844
+ COALESCE(last_seen_at, updated_at) AS last_seen
1845
+ FROM sessions
1846
+ WHERE (hostname = ?1 OR ip = ?2)
1847
+ `;
1848
+ latestSql = addNetworkScope(latestSql, latestParams, restScope);
1849
+ latestSql += " ORDER BY COALESCE(last_seen_at, updated_at) DESC LIMIT 1";
1850
+ const latest = db.get<any>(latestSql, ...latestParams);
1851
+ if (!latest) return withCors(req, Response.json({ ok: false, error: "server not found" }, { status: 404 }));
1852
+
1853
+ const since24h = sqliteTime(new Date(Date.now() - 24 * 60 * 60 * 1000));
1854
+ const histParams: any[] = [host, host, since24h];
1855
+ let histSql = `
1856
+ SELECT created_at, cpu_load_1min, cpu_cores, mem_total_gb, mem_used_gb, mem_avail_gb,
1857
+ disk_total_gb, disk_used_gb, disk_avail_gb
1858
+ FROM agent_telemetry
1859
+ WHERE (hostname = ?1 OR ip = ?2) AND created_at >= ?3
1860
+ `;
1861
+ histSql = addNetworkScope(histSql, histParams, restScope);
1862
+ histSql += " ORDER BY created_at ASC";
1863
+ const historyRows = db.all<any>(histSql, ...histParams);
1864
+ const now = Date.now();
1865
+ const alert = serverAlertLevel(latest);
1866
+
1867
+ return withCors(req, Response.json({
1868
+ ok: true,
1869
+ host,
1870
+ hostname: latest.hostname ?? null,
1871
+ ip: latest.ip ?? null,
1872
+ agent_count: latest.agent_count ?? 0,
1873
+ alert_level: alert.level,
1874
+ alerts: alert.alerts,
1875
+ latest: {
1876
+ cpu_load_1min: latest.cpu_load_1min ?? null,
1877
+ cpu_cores: latest.cpu_cores ?? null,
1878
+ cpu_pct: cpuPct(latest.cpu_load_1min, latest.cpu_cores),
1879
+ mem_total_gb: latest.mem_total_gb ?? null,
1880
+ mem_used_gb: latest.mem_used_gb ?? null,
1881
+ mem_avail_gb: latest.mem_avail_gb ?? null,
1882
+ disk_total_gb: latest.disk_total_gb ?? null,
1883
+ disk_used_gb: latest.disk_used_gb ?? null,
1884
+ disk_avail_gb: latest.disk_avail_gb ?? null,
1885
+ last_seen: latest.last_seen ?? null,
1886
+ },
1887
+ history: {
1888
+ "5m": bucketTelemetry(historyRows, now - 5 * 60 * 1000, 60 * 1000),
1889
+ "1h": bucketTelemetry(historyRows, now - 60 * 60 * 1000, 5 * 60 * 1000),
1890
+ "24h": bucketTelemetry(historyRows, now - 24 * 60 * 60 * 1000, 60 * 60 * 1000),
1891
+ },
1892
+ }));
1893
+ }
1894
+
1895
+ // ── REST: file upload (#221) ──
1896
+ // POST multipart/form-data with a single `file` field. Bearer auth.
1897
+ // 12 MiB cap (two-stage: Content-Length pre-check + post-parse size
1898
+ // verify). Returns { ok, file_id, path, url, size, mime }. The
1899
+ // file_id is server-generated (crypto.randomUUID with hyphens
1900
+ // stripped) so a client-supplied filename never enters the storage
1901
+ // path. The download URL `/api/files/<file_id>` requires the same
1902
+ // Bearer auth and forces Content-Disposition: attachment +
1903
+ // X-Content-Type-Options: nosniff so uploaded files can never be
1904
+ // executed or served as HTML.
1905
+ if (url.pathname === "/api/upload" && req.method === "POST") {
1906
+ // #503 Finding 3 = Option A (lead 40be9845): every 4xx returned
1907
+ // BEFORE `req.formData()` drains the request body MUST include
1908
+ // `Connection: close`. Otherwise the client's still-inbound bytes
1909
+ // land on a keepalive connection the server already answered on,
1910
+ // poisoning the next pooled request. Bug is pre-existing (411/
1911
+ // 413/415/429/401 all have this shape) — the #503 authz block
1912
+ // just made it visible under aggregate `bun test` with a 12MiB
1913
+ // upload immediately followed by another request. Per-file green
1914
+ // hides this class of bug.
1915
+ const earlyReject = (res: Response): Response => {
1916
+ const wrapped = withCors(req, res);
1917
+ wrapped.headers.set("Connection", "close");
1918
+ return wrapped;
1919
+ };
1920
+ const authErr = requireAuth(req);
1921
+ if (authErr) return earlyReject(authErr);
1922
+
1923
+ // Rate-limit key prefers the token id (so 60/h is per-token, not
1924
+ // per-IP); falls back to IP for legacy or anonymous-but-dev-open.
1925
+ const authCtx = resolveRequestAuth(req);
1926
+ const rateKey = authCtx?.tokenId ?? `ip:${getClientIP(req, server)}`;
1927
+ const rate = sharedUploadRateLimiter.check(rateKey);
1928
+ if (!rate.allowed) {
1929
+ const headers: Record<string, string> = {
1930
+ "X-RateLimit-Limit": String(60),
1931
+ "X-RateLimit-Remaining": "0",
1932
+ "X-RateLimit-Reset": String(Math.floor(rate.resetAt / 1000)),
1933
+ };
1934
+ if (rate.retryAfterMs) headers["Retry-After"] = String(Math.ceil(rate.retryAfterMs / 1000));
1935
+ return earlyReject(new Response(
1936
+ JSON.stringify({ ok: false, error: "rate_limited", message: "Upload rate limit exceeded (60/hour). Try again later.", retry_after_ms: rate.retryAfterMs }),
1937
+ { status: 429, headers: { ...headers, "Content-Type": "application/json; charset=utf-8" } }, // #426 — legacy clients default to ISO-8859-1 without charset
1938
+ ));
1939
+ }
1940
+
1941
+ // Two-stage size cap per 通信龙 dispatch c38de7a9:
1942
+ // stage 1 — reject before reading body when Content-Length
1943
+ // exceeds the cap (saves bandwidth, fails fast)
1944
+ // stage 2 — re-verify the parsed File.size after Bun has parsed
1945
+ // the multipart envelope (defends against a missing
1946
+ // or lied Content-Length header)
1947
+ const contentLength = req.headers.get("Content-Length");
1948
+ if (!contentLength) {
1949
+ return earlyReject(Response.json(
1950
+ { ok: false, error: "length_required", message: "Content-Length header is required for /api/upload" },
1951
+ { status: 411 },
1952
+ ));
1953
+ }
1954
+ const declaredBytes = Number(contentLength);
1955
+ if (!Number.isFinite(declaredBytes) || declaredBytes < 0) {
1956
+ return earlyReject(Response.json({ ok: false, error: "bad_content_length" }, { status: 400 }));
1957
+ }
1958
+ if (declaredBytes > MAX_REQUEST_CONTENT_LENGTH) {
1959
+ return earlyReject(Response.json(
1960
+ { ok: false, error: "payload_too_large", message: `Upload exceeds the ${MAX_UPLOAD_BYTES} byte limit`, limit_bytes: MAX_UPLOAD_BYTES },
1961
+ { status: 413 },
1962
+ ));
1963
+ }
1964
+
1965
+ // #503 — decide which network this upload is attributed to, then
1966
+ // check the caller may write there. Attribution and authorization
1967
+ // are two questions; neither substitutes for the other. Placed
1968
+ // after the in-memory rate limiter (above) and before the body is
1969
+ // read, so an unauthorized caller never gets a DB query per byte
1970
+ // uploaded and never gets their multipart envelope parsed.
1971
+ const principal = resolvePrincipal(req);
1972
+ const requestedNetId = url.searchParams.get("network_id");
1973
+ let uploadNetId: string | null = null;
1974
+
1975
+ switch (principal.kind) {
1976
+ case "anonymous":
1977
+ // Unreachable: requireAuth above already 401s. Kept so the
1978
+ // switch stays exhaustive and a future auth change fails loud.
1979
+ return earlyReject(Response.json({ ok: false, error: "auth_required" }, { status: 401 }));
1980
+ case "dev-open-anon":
1981
+ // Local dev only. Deliberately does NOT claim a real network,
1982
+ // even if one was requested — an unauthenticated caller must
1983
+ // not be able to file blobs into a tenant's network.
1984
+ uploadNetId = null;
1985
+ break;
1986
+ case "legacy-master":
1987
+ // Unreachable today: requireAuth 401s master tokens on every
1988
+ // non-GET /api/ request (RFC-001 made them read-only). Kept
1989
+ // fail-closed so relaxing that rule cannot silently start
1990
+ // producing unattributed blobs.
1991
+ if (!requestedNetId) {
1992
+ return earlyReject(Response.json({
1993
+ ok: false, error: "network_id_required",
1994
+ message: "legacy master uploads must specify a network_id query param",
1995
+ }, { status: 400 }));
1996
+ }
1997
+ uploadNetId = requestedNetId;
1998
+ break;
1999
+ case "ntok":
2000
+ if (requestedNetId && requestedNetId !== principal.boundNetworkId) {
2001
+ return earlyReject(Response.json({
2002
+ ok: false, error: "network_id_conflict",
2003
+ message: "network_id query param conflicts with the token-bound network",
2004
+ }, { status: 400 }));
2005
+ }
2006
+ uploadNetId = principal.boundNetworkId;
2007
+ break;
2008
+ case "admin-utok": {
2009
+ // #503 Finding 2 = Option F (lead 40be9845): admin follows the same
2010
+ // "auto-derive when unambiguous / require param when ambiguous" rule
2011
+ // as utok_. Rule 4's REASON (no unowned files) is preserved — the
2012
+ // derived network is a real membership. Strict on genuine ambiguity:
2013
+ // 0 or ≥2 memberships → 400. Preserves prod upload contract (in
2014
+ // prod admin is in exactly 1 network; auto-derive succeeds).
2015
+ if (requestedNetId) {
2016
+ // Admin bypasses membership; network existence validated below.
2017
+ uploadNetId = requestedNetId;
2018
+ break;
2019
+ }
2020
+ const adminNetworks = getUserNetworkIds(principal.userId);
2021
+ if (adminNetworks.length === 1) {
2022
+ uploadNetId = adminNetworks[0];
2023
+ } else {
2024
+ return earlyReject(Response.json({
2025
+ ok: false, error: "network_id_required",
2026
+ message: "admin has 0 or ≥2 network memberships; network_id query param required",
2027
+ }, { status: 400 }));
2028
+ }
2029
+ break;
2030
+ }
2031
+ case "utok": {
2032
+ if (requestedNetId) {
2033
+ // A non-member asking for someone else's network never gets
2034
+ // here: the REST scope guard (`restScope.denied`) already
2035
+ // 403'd, with the same body whether the network exists or
2036
+ // not. Re-checking membership here would be a second, drifting
2037
+ // copy of a decision this codebase makes in one place.
2038
+ uploadNetId = requestedNetId;
2039
+ break;
2040
+ }
2041
+ uploadNetId = singleNetworkId(resolveRestNetworkScope(url.searchParams.get("network_id"), authCtx, false));
2042
+ if (!uploadNetId) {
2043
+ return earlyReject(Response.json({
2044
+ ok: false, error: "network_id_required",
2045
+ message: "network_id query param required for a multi-network user token; 'first network' is not assumed",
2046
+ }, { status: 400 }));
2047
+ }
2048
+ break;
2049
+ }
2050
+ }
2051
+
2052
+ if (uploadNetId !== null) {
2053
+ const networkRow = db.get<any>("SELECT network_id FROM networks WHERE network_id = ?1", uploadNetId);
2054
+ if (!networkRow) {
2055
+ if (principal.kind === "admin-utok" || principal.kind === "legacy-master") {
2056
+ return earlyReject(Response.json({
2057
+ ok: false, error: "unknown_network",
2058
+ message: "network_id does not exist",
2059
+ }, { status: 400 }));
2060
+ }
2061
+ // Byte-identical to the non-member 404 above: distinguishing
2062
+ // the two would hand an unprivileged caller a network-existence
2063
+ // oracle.
2064
+ return earlyReject(Response.json({ ok: false, error: "not_found" }, { status: 404 }));
2065
+ }
2066
+ }
2067
+
2068
+ if (!canRestWriteNetwork(authCtx, uploadNetId, principal.kind === "admin-utok")) {
2069
+ return earlyReject(Response.json({ ok: false, error: "permission_denied" }, { status: 403 }));
2070
+ }
2071
+
2072
+ const contentType = req.headers.get("Content-Type") ?? "";
2073
+ if (!/^multipart\/form-data/i.test(contentType)) {
2074
+ return earlyReject(Response.json(
2075
+ { ok: false, error: "unsupported_media_type", message: "Use multipart/form-data with a 'file' field" },
2076
+ { status: 415 },
2077
+ ));
2078
+ }
2079
+
2080
+ let form: FormData;
2081
+ try {
2082
+ form = await req.formData();
2083
+ } catch (e: any) {
2084
+ return withCors(req, Response.json(
2085
+ { ok: false, error: "multipart_parse_failed", message: e?.message?.slice(0, 200) ?? "multipart parse failed" },
2086
+ { status: 400 },
2087
+ ));
2088
+ }
2089
+ const file = form.get("file");
2090
+ if (!file || typeof file === "string") {
2091
+ return withCors(req, Response.json(
2092
+ { ok: false, error: "missing_file", message: "Expected a 'file' field with binary content" },
2093
+ { status: 400 },
2094
+ ));
2095
+ }
2096
+
2097
+ // Stage 2 — re-verify parsed size against the documented cap.
2098
+ if (file.size > MAX_UPLOAD_BYTES) {
2099
+ return withCors(req, Response.json(
2100
+ { ok: false, error: "payload_too_large", message: `Upload exceeds the ${MAX_UPLOAD_BYTES} byte limit`, limit_bytes: MAX_UPLOAD_BYTES, observed_bytes: file.size },
2101
+ { status: 413 },
2102
+ ));
2103
+ }
2104
+
2105
+ const fileId = generateFileId();
2106
+ const ext = sanitizeExt(file.name);
2107
+ let storage;
2108
+ try {
2109
+ storage = buildStoragePath(fileId, ext);
2110
+ } catch (e: any) {
2111
+ // Should be unreachable — we generated the id ourselves — but
2112
+ // surface as 500 if our own primitives reject our own input.
2113
+ console.error("[/api/upload] buildStoragePath rejected:", e?.message);
2114
+ return withCors(req, Response.json({ ok: false, error: "internal_path_error" }, { status: 500 }));
2115
+ }
2116
+
2117
+ try {
2118
+ mkdirSync(pathDirname(storage.absolutePath), { recursive: true });
2119
+ const buf = Buffer.from(await file.arrayBuffer());
2120
+ // #693 — write blob to .tmp then rename for crash-safe durability.
2121
+ const tmpPath = storage.absolutePath + ".tmp";
2122
+ writeFileSync(tmpPath, buf);
2123
+ // Defense-in-depth: after writing, confirm the path still sits
2124
+ // inside the uploads root (catches a symlink swap or root env
2125
+ // poisoning across processes).
2126
+ if (!isPathInsideUploadsRoot(tmpPath) || !isPathInsideUploadsRoot(storage.absolutePath)) {
2127
+ try { unlinkSync(tmpPath); } catch { /* best-effort */ }
2128
+ console.error("[/api/upload] write escaped uploads root:", storage.absolutePath);
2129
+ return withCors(req, Response.json({ ok: false, error: "internal_path_escape" }, { status: 500 }));
2130
+ }
2131
+
2132
+ // Persist the index entry so /api/files/<file_id> can do an
2133
+ // O(1) lookup without scanning every date bucket.
2134
+ const idxPath = indexEntryPath(fileId);
2135
+ if (idxPath) {
2136
+ mkdirSync(pathDirname(idxPath), { recursive: true });
2137
+ writeFileSync(idxPath, JSON.stringify({
2138
+ file_id: fileId,
2139
+ date_bucket: storage.dateBucket,
2140
+ ext: storage.ext,
2141
+ name: typeof file.name === "string" ? file.name.slice(0, 255) : "",
2142
+ mime: typeof file.type === "string" ? file.type.slice(0, 100) : "application/octet-stream",
2143
+ size: file.size,
2144
+ owner: authCtx?.username ?? null,
2145
+ owner_id: authCtx?.userId ?? null,
2146
+ // Key omitted (not null) when unattributed — see UploadIndexEntry.
2147
+ ...(uploadNetId ? { network_id: uploadNetId } : {}),
2148
+ uploaded_at: new Date().toISOString(),
2149
+ }, null, 2));
2150
+ } else {
2151
+ // No index path → refuse to leave an unindexed blob.
2152
+ try { unlinkSync(tmpPath); } catch { /* best-effort */ }
2153
+ return withCors(req, Response.json({ ok: false, error: "index_path_error" }, { status: 500 }));
2154
+ }
2155
+ // Index first, then publish blob via rename — if rename fails, drop index.
2156
+ try {
2157
+ renameSync(tmpPath, storage.absolutePath);
2158
+ } catch (renameErr: any) {
2159
+ try { unlinkSync(tmpPath); } catch { /* best-effort */ }
2160
+ try { if (idxPath) unlinkSync(idxPath); } catch { /* best-effort */ }
2161
+ throw renameErr;
2162
+ }
2163
+ } catch (e: any) {
2164
+ console.error("[/api/upload] write failed:", e?.message);
2165
+ return withCors(req, Response.json({ ok: false, error: "write_failed", message: e?.message?.slice(0, 200) ?? "write failed" }, { status: 500 }));
2166
+ }
2167
+
2168
+ return withCors(req, Response.json({
2169
+ ok: true,
2170
+ file_id: fileId,
2171
+ path: storage.absolutePath,
2172
+ url: `/api/files/${fileId}`,
2173
+ size: file.size,
2174
+ mime: typeof file.type === "string" ? file.type : "application/octet-stream",
2175
+ }));
2176
+ }
2177
+
2178
+ // ── REST: file download (#221 + #495 + #500 CR2 HEAD) ──
2179
+ // GET or HEAD /api/files/:file_id with Bearer auth + ownership
2180
+ // check. Always forces Content-Disposition: attachment +
2181
+ // X-Content-Type-Options: nosniff so the served file can never be
2182
+ // executed or rendered as HTML. The file_id is validated against
2183
+ // the same strict regex used at generation time before any
2184
+ // filesystem access.
2185
+ //
2186
+ // Ownership gate is factored into `authorizeFileDownload` (see
2187
+ // src/server.ts near resolveRequestAuth). HEAD MUST route through
2188
+ // the same helper — pre-#500-CR2, HEAD fell through to a fallback
2189
+ // 200 page whose body happened to be byte-identical to the
2190
+ // "unknown file" case, so no enumeration oracle formed in practice.
2191
+ // That was coincidence, not a gate. A change to the fallback (e.g.
2192
+ // adding "Requested resource: <hint>") would materialize the oracle
2193
+ // with zero failing tests. Any future Range, conditional-request,
2194
+ // or dashboard-proxy path for /api/files MUST route through this
2195
+ // handler (via authorizeFileDownload) — do not duplicate the
2196
+ // allow-list inline, or the branches will drift.
2197
+ const fileMatch = url.pathname.match(/^\/api\/files\/(.+)$/);
2198
+ if (fileMatch && (req.method === "GET" || req.method === "HEAD")) {
2199
+ // #501: file credentials must never travel in the URL. Query tokens
2200
+ // leak through browser history, access/proxy logs, copied links, and
2201
+ // Referer. SSE/EventSource compatibility keeps the global query-token
2202
+ // fallback for now; file GET/HEAD deliberately opt out here.
2203
+ const authErr = requireAuth(req, { allowQueryToken: false });
2204
+ if (authErr) return withCors(req, authErr);
2205
+
2206
+ const fileId = decodeURIComponent(fileMatch[1]);
2207
+ if (!FILE_ID_REGEX.test(fileId)) {
2208
+ return withCors(req, Response.json({ ok: false, error: "bad_file_id" }, { status: 400 }));
2209
+ }
2210
+
2211
+ const idxPath = indexEntryPath(fileId);
2212
+ if (!idxPath || !existsSync(idxPath)) {
2213
+ return withCors(req, Response.json({ ok: false, error: "not_found" }, { status: 404 }));
2214
+ }
2215
+
2216
+ let entry: any;
2217
+ try { entry = JSON.parse(readFileSync(idxPath, "utf-8")); } catch {
2218
+ // #509 副指挥 66983a19: corrupted index must not leak "server
2219
+ // failed" signal — 404 with same shape as unknown file_id
2220
+ // (input refused at boundary, no enumeration).
2221
+ return withCors(req, Response.json({ ok: false, error: "not_found" }, { status: 404 }));
2222
+ }
2223
+ if (!validateIndexEntry(entry)) {
2224
+ // #509 副指挥 66983a19: schema-invalid index (bucket "../etc",
2225
+ // missing fields, wrong types) is also 404 — same discipline.
2226
+ return withCors(req, Response.json({ ok: false, error: "not_found" }, { status: 404 }));
2227
+ }
2228
+
2229
+ // #495 ownership gate — placed AFTER file-exists so denied
2230
+ // callers cannot distinguish "you don't own this" from
2231
+ // "no such file". Both branches return the same 404 shape
2232
+ // for BOTH GET and HEAD (HEAD honours body-omission but the
2233
+ // status code and headers are the authoritative signal).
2234
+ if (!authorizeFileDownload(resolvePrincipal(req, { allowQueryToken: false }), normalizeEntry(entry))) {
2235
+ return withCors(req, Response.json({ ok: false, error: "not_found" }, { status: 404 }));
2236
+ }
2237
+
2238
+ // #509 defence-in-depth: pre-check date_bucket against BOTH
2239
+ // shape regex AND real-calendar semantics. A poisoned index (e.g.
2240
+ // "../etc", "2026-02-30", "2026-13-01") must return 404 not 500
2241
+ // — 500 says "server failed"; 404 says "input refused at boundary".
2242
+ // 副指挥 b1082017 / 66983a19 hard doors:
2243
+ // • 稳定 404 非 500 for invalid/missing/poisoned date_bucket
2244
+ // • 真日历语义校验, 不仅 regex 形状
2245
+ if (!isValidCalendarBucket(entry.date_bucket)) {
2246
+ return withCors(req, Response.json({ ok: false, error: "not_found" }, { status: 404 }));
2247
+ }
2248
+
2249
+ let storage;
2250
+ try {
2251
+ // #509 fix: use the date_bucket recorded in the index at upload
2252
+ // time, NOT today's date. buildStoragePath computes today; that is
2253
+ // correct for new uploads only. Yesterday's file lives in
2254
+ // yesterday's bucket forever — read path must respect that.
2255
+ storage = pathForExistingBlob(entry.date_bucket, entry.file_id, entry.ext);
2256
+ } catch {
2257
+ // Defence-in-depth: unreachable given the pre-check above, but
2258
+ // keep as fallback. Return 404 not 500 to match the pre-check
2259
+ // shape — caller sees the same code for all invalid-bucket cases.
2260
+ return withCors(req, Response.json({ ok: false, error: "not_found" }, { status: 404 }));
2261
+ }
2262
+ if (!isPathInsideUploadsRoot(storage.absolutePath)) {
2263
+ // Defence: should be unreachable since buildStoragePath rejected
2264
+ // malformed inputs, but a poisoned index could try to fool us.
2265
+ return withCors(req, Response.json({ ok: false, error: "path_escape" }, { status: 500 }));
2266
+ }
2267
+ if (!existsSync(storage.absolutePath)) {
2268
+ return withCors(req, Response.json({ ok: false, error: "blob_missing" }, { status: 404 }));
2269
+ }
2270
+
2271
+ // Defence: verify the on-disk size matches what the index claims
2272
+ // before serving — a tampered index could otherwise mislead the
2273
+ // caller about file integrity.
2274
+ const st = statSync(storage.absolutePath);
2275
+ if (st.size !== entry.size) {
2276
+ console.error("[/api/files] size mismatch:", { fileId, indexed: entry.size, onDisk: st.size });
2277
+ return withCors(req, Response.json({ ok: false, error: "size_mismatch" }, { status: 500 }));
2278
+ }
2279
+
2280
+ const safeFilename = (entry.name && /^[\x20-\x7e]+$/.test(entry.name))
2281
+ ? entry.name
2282
+ : `${fileId}${entry.ext}`;
2283
+ const responseHeaders: Record<string, string> = {
2284
+ ...corsHeaders(req),
2285
+ "Content-Type": "application/octet-stream", // always opaque; nosniff prevents the client from re-deciding
2286
+ "Content-Length": String(entry.size),
2287
+ "Content-Disposition": `attachment; filename="${safeFilename.replace(/"/g, "")}"`,
2288
+ "X-Content-Type-Options": "nosniff",
2289
+ "Cache-Control": "private, no-store",
2290
+ "Accept-Ranges": "bytes",
2291
+ };
2292
+ const range = parseSingleByteRange(req.headers.get("Range"), entry.size);
2293
+ if (range && !range.ok) {
2294
+ return new Response(null, {
2295
+ status: 416,
2296
+ headers: {
2297
+ ...responseHeaders,
2298
+ "Content-Length": "0",
2299
+ "Content-Range": `bytes */${entry.size}`,
2300
+ },
2301
+ });
2302
+ }
2303
+ if (range?.ok) {
2304
+ const headers = {
2305
+ ...responseHeaders,
2306
+ "Content-Length": String(range.length),
2307
+ "Content-Range": `bytes ${range.start}-${range.end}/${entry.size}`,
2308
+ };
2309
+ if (req.method === "HEAD") {
2310
+ return new Response(null, { status: 206, headers });
2311
+ }
2312
+ const blob = Bun.file(storage.absolutePath).slice(range.start, range.end + 1);
2313
+ return new Response(blob, { status: 206, headers });
2314
+ }
2315
+ // HEAD: return the same status and headers as GET, but no body,
2316
+ // per RFC 9110 §9.3.2. This ensures HEAD passes through the same
2317
+ // authorization helper — a cross-owner HEAD is 404 (same as GET),
2318
+ // not a fallback 200. Status/headers are the authoritative
2319
+ // signal; body omission is HTTP-standard for HEAD.
2320
+ if (req.method === "HEAD") {
2321
+ return new Response(null, { status: 200, headers: responseHeaders });
2322
+ }
2323
+ const blob = Bun.file(storage.absolutePath);
2324
+ return new Response(blob, { status: 200, headers: responseHeaders });
2325
+ }
2326
+
2327
+ // ── REST: send task ──
2328
+ if (url.pathname === "/api/task" && req.method === "POST") {
2329
+ let raw: unknown;
2330
+ try {
2331
+ raw = await req.json();
2332
+ } catch {
2333
+ return withCors(req, Response.json({ error: "invalid JSON" }, { status: 400 }));
2334
+ }
2335
+ const parsed = TaskSchema.safeParse(raw);
2336
+ if (!parsed.success) {
2337
+ return withCors(req, Response.json({ error: "invalid input", details: parsed.error.format() }, { status: 400 }));
2338
+ }
2339
+ const body = parsed.data;
2340
+ let taskNetId: string | null = null;
2341
+ if (restAuth?.networkId) {
2342
+ taskNetId = restAuth.networkId;
2343
+ } else if (body.network_id) {
2344
+ if (restAuth && !isAdmin && !getUserNetworkRole(restAuth.userId, body.network_id)) {
2345
+ return withCors(req, Response.json({ ok: false, error: "access denied to requested network" }, { status: 403 }));
2346
+ }
2347
+ taskNetId = body.network_id;
2348
+ } else {
2349
+ taskNetId = restAuth
2350
+ ? resolveRestWriteNetworkId(restScope, restAuth, isAdmin)
2351
+ : null;
2352
+ }
2353
+ if (restAuth && !taskNetId) {
2354
+ return withCors(req, Response.json({
2355
+ ok: false,
2356
+ error: "network_id_required",
2357
+ message: "network_id is required when the user token has zero or multiple network memberships",
2358
+ }, { status: 400 }));
2359
+ }
2360
+ if (!canRestWriteNetwork(restAuth, taskNetId, isAdmin)) {
2361
+ return withCors(req, Response.json({ ok: false, error: "permission_denied" }, { status: 403 }));
2362
+ }
2363
+ const canonical = resolveCanonicalAlias(taskNetId, body.alias);
2364
+ const targetAlias = canonical.alias;
2365
+ const target = resolveRestDeliveryTarget(targetAlias, taskNetId);
2366
+ if (target.state === "not_found") {
2367
+ return withCors(req, Response.json({
2368
+ ok: false,
2369
+ error: "alias_not_found",
2370
+ message: target.message,
2371
+ alias: targetAlias,
2372
+ queued: false,
2373
+ ...(canonical.renamed ? { renamed_from: body.alias, renamed_to: targetAlias } : {}),
2374
+ }, { status: 404 }));
2375
+ }
2376
+ const id = crypto.randomUUID();
2377
+ // Identity binding, mirroring the MCP transport (tools.ts defaultFrom /
2378
+ // fromIdentityMismatchReply). Both transports resolve the same
2379
+ // api_tokens row through resolveToken, and auth.ts already documents the
2380
+ // invariant: "Network-bound node tokens are an identity boundary: they
2381
+ // must not spoof another node via from_session."
2382
+ //
2383
+ // MCP enforced it; this REST handler did not — it took `body.from`
2384
+ // verbatim, so any node could POST /api/task with another node's alias
2385
+ // and be recorded (and, once sender labels ship, *rendered in a human's
2386
+ // TUI*) as that node. Same table, same token, one transport hardened and
2387
+ // its sibling not.
2388
+ //
2389
+ // User tokens keep the previous behaviour: the Dashboard legitimately
2390
+ // posts as its logged-in user, and tightening that is a separate change
2391
+ // with its own compatibility surface.
2392
+ // The decision itself lives in rest-identity.ts as a pure function so the
2393
+ // shipped path and the tested path are the same code.
2394
+ const identity = resolveRestFromSession({
2395
+ token: requestToken(req),
2396
+ tokenName: restAuth?.tokenName,
2397
+ authenticatedUsername: restAuth?.username,
2398
+ requestedFrom: body.from,
2399
+ });
2400
+ if (!identity.ok) {
2401
+ return withCors(req, Response.json({
2402
+ ok: false,
2403
+ error: identity.error,
2404
+ message: identity.message,
2405
+ token_alias: identity.tokenAlias,
2406
+ requested_from_session: identity.requestedFromSession,
2407
+ }, { status: 403 }));
2408
+ }
2409
+ const fromSession = identity.fromSession;
2410
+ const ttlSeconds = (body as any).ttl_seconds || 3600;
2411
+ const fromNodeId = resolveRestNodeIdForAlias(fromSession, taskNetId);
2412
+ const targetNodeId = target.session?.node_id ?? null;
2413
+ const actualTo = restActualTo(target, taskNetId);
2414
+ // #221 — fold top-level `attachments` into `meta.attachments` so
2415
+ // the REST and MCP send_task transports produce identical
2416
+ // tasks.meta_json shape downstream. Top-level wins over any
2417
+ // duplicate `meta.attachments` the client supplied. Validation
2418
+ // matches the MCP-side schema (max 20 entries, file_id regex,
2419
+ // size cap, etc.).
2420
+ const attachmentsResult = validateAttachments((body as any).attachments ?? (body as any).meta?.attachments);
2421
+ if (!attachmentsResult.ok) {
2422
+ return withCors(req, Response.json({ ok: false, error: "bad_attachments", message: attachmentsResult.error }, { status: 400 }));
2423
+ }
2424
+ const mergedMeta = attachmentsResult.attachments.length
2425
+ ? { ...((body as any).meta && typeof (body as any).meta === "object" ? (body as any).meta : {}), attachments: attachmentsResult.attachments }
2426
+ : (body as any).meta;
2427
+ const rawToken = requestToken(req);
2428
+ const authOrigin: TaskAuthOrigin = rawToken.startsWith("ntok_")
2429
+ ? "node"
2430
+ : restAuth
2431
+ ? "user"
2432
+ : "legacy";
2433
+ const metaJson = normalizeMetaJson(stampTaskAuthOrigin(mergedMeta, authOrigin));
2434
+
2435
+ // #212 dedup guardrail. Mirrors the MCP `send_task` tool: same
2436
+ // (from_session, target_alias, task) within COMMHUB_SEND_DEDUP_WINDOW_MS
2437
+ // is rejected with a structured `duplicate_send` error so dashboard
2438
+ // dispatch buttons and scripted REST callers get the same guarantee
2439
+ // as agent-driven MCP traffic.
2440
+ const dedup = sharedSendDedup.check(fromSession, targetAlias, body.task);
2441
+ if (dedup.duplicate) {
2442
+ const payload = buildDuplicateSendPayload({
2443
+ from: fromSession,
2444
+ to: targetAlias,
2445
+ ageMs: dedup.ageMs,
2446
+ windowMs: sharedSendDedup.windowMs,
2447
+ });
2448
+ console.log(`[/api/task] ${fromSession} → ${targetAlias}: DROPPED duplicate (age=${dedup.ageMs}ms, window=${sharedSendDedup.windowMs}ms)`);
2449
+ return withCors(req, Response.json(payload, { status: 429 }));
2450
+ }
2451
+
2452
+ // RFC-027 §2.3 inbox-enqueue lifecycle guard (PR1.2a REST site
2453
+ // 1/2 — paired with the 6 MCP sites guarded in tools.ts at PR1.1).
2454
+ // Dashboard's "Dispatch" button hits this endpoint, so without
2455
+ // the guard a stopping/stopped/deleting node still got tasks
2456
+ // routed through REST. Returns 409 with the same structured
2457
+ // payload the MCP handlers use.
2458
+ {
2459
+ const lc = assertNodeActive(targetAlias, taskNetId ?? null);
2460
+ if (!lc.ok) {
2461
+ return withCors(req, Response.json(lc, { status: 409 }));
2462
+ }
2463
+ }
2464
+ // Mirror send_task MCP: write inbox + tasks rows in a single
2465
+ // transaction so the dispatch is visible to dashboard's Tasks page
2466
+ // and the parent_task_id lineage chain. Previously this endpoint
2467
+ // only wrote inbox, leaving GET /api/tasks empty for any task
2468
+ // dispatched via REST (anet demo, dashboard Dispatch button, etc.).
2469
+ db.transaction(() => {
2470
+ db.run(
2471
+ `INSERT INTO inbox (id, task_id, session_name, node_id, type, priority, content, from_session, requires_response, network_id, meta_json)
2472
+ VALUES (?1, ?1, ?2, ?3, 'task', ?4, ?5, ?6, 'reply', ?7, ?8)`,
2473
+ [id, targetAlias, targetNodeId, body.priority, body.task, fromSession, taskNetId, metaJson]
2474
+ );
2475
+ db.run(
2476
+ `INSERT INTO tasks (task_id, from_node_id, from_name, to_node_id, to_name, priority, status, content, requires_response, created_at, delivered_at, expires_at, network_id, parent_task_id, meta_json)
2477
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'delivered', ?7, 'reply', datetime('now'), datetime('now'), datetime('now', ?8), ?9, ?10, ?11)`,
2478
+ [id, fromNodeId, fromSession, targetNodeId, targetAlias, body.priority, body.task, `+${ttlSeconds} seconds`, taskNetId, body.parent_task_id ?? null, metaJson]
2479
+ );
2480
+ // Touch session row so the dashboard reflects "task in flight"
2481
+ // immediately, without waiting for the agent's report_status to
2482
+ // arrive. Updating both `task` and `updated_at` is enough — we
2483
+ // leave `status` to the agent (idle → working → idle).
2484
+ const touchParams: any[] = [body.task.slice(0, 200), targetAlias];
2485
+ let touchSql = "UPDATE sessions SET task = ?1, updated_at = datetime('now') WHERE alias = ?2";
2486
+ if (taskNetId) { touchSql += " AND network_id = ?3"; touchParams.push(taskNetId); }
2487
+ db.run(touchSql, touchParams);
2488
+ });
2489
+ // SSE push: 秒达
2490
+ const pendingParams: any[] = [targetAlias];
2491
+ let pendingSql = "SELECT COUNT(*) as cnt FROM inbox WHERE session_name = ?1 AND acked = 0";
2492
+ if (taskNetId) { pendingSql += " AND network_id = ?2"; pendingParams.push(taskNetId); }
2493
+ const pending = db.get<{ cnt: number }>(pendingSql, ...pendingParams);
2494
+ if (target.state === "online") {
2495
+ pushEvent(targetAlias, { type: "new_task", inbox_count: pending?.cnt ?? 1, priority: body.priority, from: fromSession, ...(canonical.renamed ? { renamed_from: body.alias } : {}) }, taskNetId);
2496
+ }
2497
+ // #461 network observer summary — unconditional (the task row
2498
+ // exists even when the target is offline/queued), metadata only.
2499
+ pushNetworkObserverEvent(taskNetId, { type: "new_task", task_id: id, from: fromSession, to: targetAlias, status: target.state === "online" ? "delivered" : "queued", priority: body.priority });
2500
+ // #212 — stamp the dedup index only after the inbox/tasks insert
2501
+ // succeeds. Mirrors the MCP `send_task` path so a failed write
2502
+ // never shadows a legitimate retry.
2503
+ sharedSendDedup.record(fromSession, targetAlias, body.task);
2504
+ if (target.state === "offline") {
2505
+ return withCors(req, Response.json({
2506
+ ok: false,
2507
+ error: "alias_offline",
2508
+ message: target.message,
2509
+ alias: targetAlias,
2510
+ queued: true,
2511
+ task_id: id,
2512
+ message_id: id,
2513
+ session_status: target.session.status ?? "offline",
2514
+ actual_to: actualTo,
2515
+ ...(canonical.renamed ? { renamed_from: body.alias, renamed_to: targetAlias } : {}),
2516
+ }, { status: 202 }));
2517
+ }
2518
+ return withCors(req, Response.json({
2519
+ ok: true,
2520
+ task_id: id,
2521
+ message_id: id,
2522
+ actual_to: actualTo,
2523
+ ...(canonical.renamed ? { renamed_from: body.alias, renamed_to: targetAlias } : {}),
2524
+ }));
2525
+ }
2526
+
2527
+ // ── REST: broadcast ──
2528
+ if (url.pathname === "/api/broadcast" && req.method === "POST") {
2529
+ let raw: unknown;
2530
+ try {
2531
+ raw = await req.json();
2532
+ } catch {
2533
+ return withCors(req, Response.json({ error: "invalid JSON" }, { status: 400 }));
2534
+ }
2535
+ const parsed = BroadcastSchema.safeParse(raw);
2536
+ if (!parsed.success) {
2537
+ return withCors(req, Response.json({ error: "invalid input", details: parsed.error.format() }, { status: 400 }));
2538
+ }
2539
+ const body = parsed.data;
2540
+ if (restAuth && !restScope.networkId && !isAdmin) {
2541
+ return withCors(req, Response.json({ ok: false, error: "network_id required for user token when broadcasting" }, { status: 400 }));
2542
+ }
2543
+ if (!canRestWriteNetwork(restAuth, restScope.networkId, isAdmin)) {
2544
+ return withCors(req, Response.json({ ok: false, error: "permission_denied" }, { status: 403 }));
2545
+ }
2546
+ let sql = "SELECT alias, node_id, network_id FROM sessions WHERE alias IS NOT NULL";
2547
+ const params: any[] = [];
2548
+ sql = addNetworkScope(sql, params, restScope);
2549
+ if (body.filter_server) { sql += " AND server = ?"; params.push(body.filter_server); }
2550
+ if (body.filter_status) { sql += " AND status = ?"; params.push(body.filter_status); }
2551
+ const targets = db.all<{ alias: string; node_id: string | null; network_id: string | null }>(sql, ...params);
2552
+ const ids: string[] = [];
2553
+ // #1440 ① — mirrors the MCP handler: push to the recipients that
2554
+ // actually got an inbox row, not to every candidate target.
2555
+ const delivered: Array<{ alias: string; netId: string | null }> = [];
2556
+ for (const t of targets) {
2557
+ // RFC-027 §2.3 inbox-enqueue lifecycle guard (PR1.2a REST site
2558
+ // 2/2). Broadcast skips non-active recipients silently per its
2559
+ // best-effort semantics — mirrors the MCP broadcast handler
2560
+ // in tools.ts (PR1.1 site 6/6).
2561
+ const lc = assertNodeActive(t.alias, t.network_id ?? null);
2562
+ if (!lc.ok) continue;
2563
+ const id = crypto.randomUUID();
2564
+ db.run(
2565
+ `INSERT INTO inbox (id, session_name, node_id, type, priority, content, from_session, network_id)
2566
+ VALUES (?1, ?2, ?3, 'broadcast', 'normal', ?4, 'api', ?5)`,
2567
+ [id, t.alias, t.node_id ?? null, body.message, t.network_id]
2568
+ );
2569
+ ids.push(id);
2570
+ delivered.push({ alias: t.alias, netId: t.network_id });
2571
+ }
2572
+ for (const d of delivered) {
2573
+ pushEvent(d.alias, { type: "broadcast", inbox_count: pendingInboxCount(d.alias, d.netId) }, d.netId);
2574
+ }
2575
+ return withCors(req, Response.json({ ok: true, recipients: ids.length, message_ids: ids }));
2576
+ }
2577
+
2578
+ // ── REST: tmux capture-pane ──
2579
+ const tmuxCapture = url.pathname.match(/^\/api\/tmux\/([a-zA-Z0-9_-]+)$/);
2580
+ if (tmuxCapture && req.method === "GET") {
2581
+ const tmuxErr = requireTmuxAccess(req, server);
2582
+ if (tmuxErr) return withCors(req, tmuxErr);
2583
+ const name = tmuxCapture[1];
2584
+ const lines = Number(url.searchParams.get("lines")) || 30;
2585
+ try {
2586
+ const proc = Bun.spawn(["tmux", "capture-pane", "-t", name, "-p"], {
2587
+ stdout: "pipe", stderr: "pipe",
2588
+ });
2589
+ const text = await new Response(proc.stdout).text();
2590
+ const err = await new Response(proc.stderr).text();
2591
+ const code = await proc.exited;
2592
+ if (code !== 0) {
2593
+ return withCors(req, Response.json({ ok: false, error: err.trim() || `exit ${code}` }, { status: 400 }));
2594
+ }
2595
+ const trimmed = text.split("\n").slice(-lines).join("\n");
2596
+ return withCors(req, Response.json({ ok: true, tmux_name: name, lines: lines, output: trimmed }));
2597
+ } catch (e) {
2598
+ return withCors(req, Response.json({ ok: false, error: (e as Error).message }, { status: 500 }));
2599
+ }
2600
+ }
2601
+
2602
+ // ── REST: tmux send-keys ──
2603
+ const tmuxSend = url.pathname.match(/^\/api\/tmux\/([a-zA-Z0-9_-]+)\/send$/);
2604
+ if (tmuxSend && req.method === "POST") {
2605
+ const tmuxErr = requireTmuxAccess(req, server);
2606
+ if (tmuxErr) return withCors(req, tmuxErr);
2607
+ const name = tmuxSend[1];
2608
+ let body: { text?: string; enter?: boolean };
2609
+ try { body = await req.json(); } catch {
2610
+ return withCors(req, Response.json({ error: "invalid JSON" }, { status: 400 }));
2611
+ }
2612
+ if (!body.text || typeof body.text !== "string") {
2613
+ return withCors(req, Response.json({ error: "text is required" }, { status: 400 }));
2614
+ }
2615
+ const args = ["tmux", "send-keys", "-t", name, body.text];
2616
+ if (body.enter !== false) args.push("Enter");
2617
+ try {
2618
+ const proc = Bun.spawn(args, { stdout: "pipe", stderr: "pipe" });
2619
+ const err = await new Response(proc.stderr).text();
2620
+ const code = await proc.exited;
2621
+ if (code !== 0) {
2622
+ return withCors(req, Response.json({ ok: false, error: err.trim() || `exit ${code}` }, { status: 400 }));
2623
+ }
2624
+ return withCors(req, Response.json({ ok: true, sent: body.text }));
2625
+ } catch (e) {
2626
+ return withCors(req, Response.json({ ok: false, error: (e as Error).message }, { status: 500 }));
2627
+ }
2628
+ }
2629
+
2630
+ // ── REST: recent messages (for Dashboard communication graph) ──
2631
+ if (url.pathname === "/api/messages") {
2632
+ const limit = Math.min(Number(url.searchParams.get("limit")) || 100, 500);
2633
+ const since = url.searchParams.get("since") ?? new Date(Date.now() - 3600000).toISOString().replace("T", " ").slice(0, 19);
2634
+ const alias = url.searchParams.get("alias")?.trim() || null;
2635
+ const params: any[] = [since];
2636
+ let sql = "SELECT id, session_name as to_alias, from_session as from_alias, type, priority, content, acked, created_at, network_id FROM inbox WHERE created_at >= ?1";
2637
+ if (alias) {
2638
+ params.push(alias);
2639
+ sql += ` AND session_name = ?${params.length}`;
2640
+ }
2641
+ sql = addNetworkScope(sql, params, restScope);
2642
+ sql += ` ORDER BY created_at DESC LIMIT ?${params.length + 1}`;
2643
+ params.push(limit);
2644
+ const rows = db.all(sql, ...params);
2645
+
2646
+ let pendingCount: number | undefined;
2647
+ if (alias) {
2648
+ const countParams: any[] = [alias];
2649
+ let countSql = "SELECT COUNT(*) AS cnt FROM inbox WHERE session_name = ?1 AND acked = 0";
2650
+ countSql = addNetworkScope(countSql, countParams, restScope);
2651
+ pendingCount = db.get<{ cnt: number }>(countSql, ...countParams)?.cnt ?? 0;
2652
+ }
2653
+
2654
+ return withCors(req, Response.json({ ok: true, messages: rows, ...(alias ? { pending_count: pendingCount ?? 0 } : {}) }));
2655
+ }
2656
+
2657
+ // ── REST: stats summary ──
2658
+ if (url.pathname === "/api/stats") {
2659
+ const taskStatsParams: any[] = [];
2660
+ let taskStatsSql = "SELECT status, COUNT(*) as count FROM tasks WHERE 1=1";
2661
+ taskStatsSql = addNetworkScope(taskStatsSql, taskStatsParams, restScope);
2662
+ taskStatsSql += " GROUP BY status";
2663
+ const taskStats = db.all<any>(taskStatsSql, ...taskStatsParams);
2664
+
2665
+ const sessionStatsParams: any[] = [];
2666
+ let sessionStatsSql = "SELECT status, COUNT(*) as count FROM sessions WHERE 1=1";
2667
+ sessionStatsSql = addNetworkScope(sessionStatsSql, sessionStatsParams, restScope);
2668
+ sessionStatsSql += " GROUP BY status";
2669
+ const sessionStats = db.all<any>(sessionStatsSql, ...sessionStatsParams);
2670
+
2671
+ const totalTasksParams: any[] = [];
2672
+ let totalTasksSql = "SELECT COUNT(*) as cnt FROM tasks WHERE 1=1";
2673
+ totalTasksSql = addNetworkScope(totalTasksSql, totalTasksParams, restScope);
2674
+ const totalTasks = db.get<{ cnt: number }>(totalTasksSql, ...totalTasksParams);
2675
+
2676
+ const totalNodesParams: any[] = [];
2677
+ let totalNodesSql = "SELECT COUNT(*) as cnt FROM nodes WHERE 1=1";
2678
+ totalNodesSql = addNetworkScope(totalNodesSql, totalNodesParams, restScope);
2679
+ const totalNodes = db.get<{ cnt: number }>(totalNodesSql, ...totalNodesParams);
2680
+
2681
+ const recentTasksParams: any[] = [];
2682
+ let recentTasksSql = "SELECT task_id, from_name, to_name, status, created_at FROM tasks WHERE 1=1";
2683
+ recentTasksSql = addNetworkScope(recentTasksSql, recentTasksParams, restScope);
2684
+ recentTasksSql += " ORDER BY created_at DESC LIMIT 5";
2685
+ const recentTasks = db.all<any>(recentTasksSql, ...recentTasksParams);
2686
+ return withCors(req, Response.json({
2687
+ ok: true,
2688
+ network_id: restScope.networkId || null,
2689
+ tasks: { total: totalTasks?.cnt || 0, by_status: taskStats },
2690
+ sessions: { by_status: sessionStats },
2691
+ nodes: { total: totalNodes?.cnt || 0 },
2692
+ recent_tasks: recentTasks,
2693
+ }));
2694
+ }
2695
+
2696
+ // ── REST: server log tail (in-memory ring buffer, last LOG_RING_CAP lines) ──
2697
+ // Admin-only because logs may include user names + task content.
2698
+ if (url.pathname === "/api/server-logs") {
2699
+ const token = req.headers.get("Authorization")?.replace("Bearer ", "") || url.searchParams.get("token");
2700
+ if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
2701
+ const resolved = resolveToken(token);
2702
+ if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
2703
+ if (resolved.user.role !== "admin") return withCors(req, Response.json({ ok: false, error: "admin only" }, { status: 403 }));
2704
+ const limit = Math.min(Number(url.searchParams.get("limit")) || 200, LOG_RING_CAP);
2705
+ const since = url.searchParams.get("since"); // ISO timestamp; only return logs newer
2706
+ let entries = logRing.slice(-limit);
2707
+ if (since) entries = entries.filter(e => e.ts > since);
2708
+ // Newest first
2709
+ entries = entries.slice().reverse();
2710
+ return withCors(req, Response.json({ ok: true, logs: entries, capacity: LOG_RING_CAP }));
2711
+ }
2712
+
2713
+ // ── REST: audit log (V3) ──
2714
+ if (url.pathname === "/api/audit-log") {
2715
+ const token = req.headers.get("Authorization")?.replace("Bearer ", "") || url.searchParams.get("token");
2716
+ if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
2717
+ const resolved = resolveToken(token);
2718
+ if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
2719
+ const limit = Math.min(Number(url.searchParams.get("limit")) || 50, 200);
2720
+ const action = url.searchParams.get("action");
2721
+ const userId = url.searchParams.get("user_id");
2722
+ let sql = `SELECT ${AUDIT_LOG_REST_SELECT} FROM audit_log WHERE 1=1`;
2723
+ const params: any[] = [];
2724
+ // Non-admin can only see own logs
2725
+ if (resolved.user.role !== "admin") { sql += ` AND user_id = ?${params.length + 1}`; params.push(resolved.user.user_id); }
2726
+ if (action) { sql += ` AND action = ?${params.length + 1}`; params.push(action); }
2727
+ if (userId && resolved.user.role === "admin") { sql += ` AND user_id = ?${params.length + 1}`; params.push(userId); }
2728
+ sql += ` ORDER BY created_at DESC LIMIT ?${params.length + 1}`;
2729
+ params.push(limit);
2730
+ const logs = db.all(sql, ...params);
2731
+ return withCors(req, Response.json({ ok: true, logs, count: logs.length }));
2732
+ }
2733
+
2734
+ // ── REST: task events (V2 Sprint 2) ──
2735
+ if (url.pathname === "/api/task_events") {
2736
+ const taskId = url.searchParams.get("task_id");
2737
+ const limit = Math.min(Number(url.searchParams.get("limit")) || 50, 500);
2738
+ let sql = `SELECT ${TASK_EVENT_REST_SELECT} FROM task_events WHERE 1=1`;
2739
+ const params: any[] = [];
2740
+ sql = addNetworkScope(sql, params, restScope);
2741
+ if (taskId) { sql += ` AND task_id = ?${params.length + 1}`; params.push(taskId); }
2742
+ sql += ` ORDER BY created_at DESC LIMIT ?${params.length + 1}`;
2743
+ params.push(limit);
2744
+ const rows = db.all(sql, ...params);
2745
+ return withCors(req, Response.json({ ok: true, events: rows, count: rows.length }));
2746
+ }
2747
+
2748
+ // ── REST: delete node (Dashboard/CLI remote cleanup) ──
2749
+ const nodeDeleteMatch = url.pathname.match(/^\/api\/nodes\/([^/]+)$/);
2750
+ if (nodeDeleteMatch && req.method === "DELETE") {
2751
+ const ref = decodeURIComponent(nodeDeleteMatch[1]);
2752
+ const params: any[] = [ref, ref, ref];
2753
+ let sql = "SELECT node_id, node_name, alias, network_id FROM nodes WHERE (node_id = ?1 OR node_name = ?2 OR alias = ?3)";
2754
+ sql = addNetworkScope(sql, params, restScope);
2755
+ sql += " ORDER BY updated_at DESC LIMIT 1";
2756
+ const node = db.get<any>(sql, ...params);
2757
+ if (!node) return withCors(req, Response.json({ ok: false, error: "node not found" }, { status: 404 }));
2758
+
2759
+ const nodeNetId = node.network_id ?? singleNetworkId(restScope);
2760
+ if (!canRestWriteNetwork(restAuth, nodeNetId, isAdmin)) {
2761
+ return withCors(req, Response.json({ ok: false, error: "permission_denied" }, { status: 403 }));
2762
+ }
2763
+
2764
+ db.transaction(() => {
2765
+ db.run("DELETE FROM nodes WHERE node_id = ?1", [node.node_id]);
2766
+ if (node.alias) {
2767
+ db.run(
2768
+ "DELETE FROM sessions WHERE alias = ?1 AND (network_id = ?2 OR (?2 IS NULL AND network_id IS NULL))",
2769
+ [node.alias, node.network_id ?? null]
2770
+ );
2771
+ }
2772
+ });
2773
+
2774
+ if (node.alias) {
2775
+ pushEvent(node.alias, {
2776
+ type: "node_deleted",
2777
+ node_id: node.node_id,
2778
+ node_name: node.node_name,
2779
+ alias: node.alias,
2780
+ network_id: node.network_id ?? null,
2781
+ }, node.network_id ?? null);
2782
+ }
2783
+
2784
+ return withCors(req, Response.json({
2785
+ ok: true,
2786
+ deleted: true,
2787
+ node_id: node.node_id,
2788
+ node_name: node.node_name,
2789
+ alias: node.alias,
2790
+ network_id: node.network_id ?? null,
2791
+ }));
2792
+ }
2793
+
2794
+ // ── REST: single node config snapshot (RFC-024 B5) ──
2795
+ // Dashboard calls this for the snapshot path. Returns the masked
2796
+ // {model, flags, config_revision} the node last posted via
2797
+ // report_status (B6). NEVER reads per-node files. Network-scoped
2798
+ // via addNetworkScope so a netA viewer can't read a netB node.
2799
+ const nodeConfigMatch = url.pathname.match(/^\/api\/nodes\/([^/]+)\/config$/);
2800
+ if (nodeConfigMatch && req.method === "GET") {
2801
+ const nodeId = decodeURIComponent(nodeConfigMatch[1] ?? "");
2802
+ const params: any[] = [nodeId];
2803
+ let sql = "SELECT node_id, alias, network_id, config_revision, config_snapshot FROM nodes WHERE node_id = ?1";
2804
+ sql = addNetworkScope(sql, params, restScope);
2805
+ sql += " LIMIT 1";
2806
+ const node = db.get<any>(sql, ...params);
2807
+ if (!node) {
2808
+ return withCors(req, Response.json({ ok: false, error: "node_not_found", node_id: nodeId }, { status: 404 }));
2809
+ }
2810
+ let snapshot: any = {};
2811
+ if (node.config_snapshot) {
2812
+ try { snapshot = JSON.parse(node.config_snapshot); } catch { snapshot = {}; }
2813
+ }
2814
+ return withCors(req, Response.json({
2815
+ ok: true,
2816
+ node_id: node.node_id,
2817
+ alias: node.alias,
2818
+ network_id: node.network_id,
2819
+ config_revision: node.config_revision || 0,
2820
+ model: snapshot.model ?? null,
2821
+ flags: snapshot.flags ?? {},
2822
+ config_update_capable: snapshot.config_update_capable ?? false,
2823
+ }));
2824
+ }
2825
+
2826
+ // ── #462 REST: set / clear a node's custom avatar ──
2827
+ // PUT /api/nodes/:ref/avatar body: { "avatar_url": "https://…" | null }
2828
+ //
2829
+ // Deliberately NOT part of the RFC-024 config-apply pipeline: avatar
2830
+ // is a pure display attribute — nothing for agent-node to consume, no
2831
+ // config_revision / ack round-trip, no restart tier. Persisted on the
2832
+ // nodes row and served back via GET /api/nodes (cross-device).
2833
+ //
2834
+ // Auth: same write gate as node delete above — network-scoped lookup
2835
+ // + canRestWriteNetwork (member with role above viewer, or admin, or
2836
+ // legacy master token). Value passes validateAvatarUrl (http/https
2837
+ // only, ≤ 2048 chars, no control chars — XSS boundary, see
2838
+ // avatar-validate.ts).
2839
+ // ── REST: node DISPLAY attributes (display_name / team / tags) ──
2840
+ // Companion to the avatar route below: hub-side presentation fields that
2841
+ // agent-node does not consume, so they deliberately bypass the RFC-024
2842
+ // config-apply pipeline (no doorbell, no ack, no config_revision bump).
2843
+ //
2844
+ // Unlike avatar, these are multi-field and multi-editor, so they carry
2845
+ // their OWN optimistic lock (`attrs_revision`). A stale base revision is
2846
+ // a 409 with the current value, mirroring update_node_config's contract
2847
+ // so the dashboard can reuse its conflict-resolution UX.
2848
+ //
2849
+ // NOT editable here: `alias` (message-routing key) and `node_name`
2850
+ // (addressing key). Renaming those must go through the rename 2PC at
2851
+ // /api/node-rename/* which cascades sessions + api_tokens + SSE cleanup;
2852
+ // a single-table UPDATE would strand the node (see #146).
2853
+ const nodeAttrsMatch = url.pathname.match(/^\/api\/nodes\/([^/]+)\/attrs$/);
2854
+ if (nodeAttrsMatch && req.method === "PUT") {
2855
+ let attrsBody: any;
2856
+ try {
2857
+ attrsBody = await req.json();
2858
+ } catch {
2859
+ return withCors(req, Response.json({ ok: false, error: "invalid JSON" }, { status: 400 }));
2860
+ }
2861
+ const ref = decodeURIComponent(nodeAttrsMatch[1]);
2862
+ const params: any[] = [ref, ref, ref];
2863
+ let sql = "SELECT node_id, alias, network_id, display_name, team, tags, attrs_revision FROM nodes WHERE (node_id = ?1 OR node_name = ?2 OR alias = ?3)";
2864
+ sql = addNetworkScope(sql, params, restScope);
2865
+ sql += " ORDER BY updated_at DESC LIMIT 1";
2866
+ const node = db.get<any>(sql, ...params);
2867
+ if (!node) return withCors(req, Response.json({ ok: false, error: "node not found" }, { status: 404 }));
2868
+
2869
+ const nodeNetId = node.network_id ?? singleNetworkId(restScope);
2870
+ if (!canRestWriteNetwork(restAuth, nodeNetId, isAdmin)) {
2871
+ return withCors(req, Response.json({ ok: false, error: "permission_denied" }, { status: 403 }));
2872
+ }
2873
+
2874
+ // Optimistic lock BEFORE any narrowing work, so a losing writer never
2875
+ // has side effects.
2876
+ const currentRev = Number(node.attrs_revision ?? 0);
2877
+ const baseRev = attrsBody?.base_attrs_revision;
2878
+ if (typeof baseRev !== "number" || !Number.isInteger(baseRev) || baseRev < 0) {
2879
+ return withCors(req, Response.json({
2880
+ ok: false, error: "base_attrs_revision required (integer >= 0)",
2881
+ }, { status: 400 }));
2882
+ }
2883
+ if (baseRev !== currentRev) {
2884
+ return withCors(req, Response.json({
2885
+ ok: false,
2886
+ error: "attrs_revision_conflict",
2887
+ current_attrs_revision: currentRev,
2888
+ message: "another editor changed this node's attributes; re-read and retry",
2889
+ }, { status: 409 }));
2890
+ }
2891
+
2892
+ // Scalars reject on wrong type (never coerce); tags drop junk per item.
2893
+ const nextDisplay = "display_name" in attrsBody
2894
+ ? validateScalarAttr(attrsBody.display_name, "display_name")
2895
+ : null;
2896
+ if (nextDisplay && !nextDisplay.ok) {
2897
+ return withCors(req, Response.json({ ok: false, error: "invalid_display_name", reason: nextDisplay.reason }, { status: 400 }));
2898
+ }
2899
+ const nextTeam = "team" in attrsBody ? validateScalarAttr(attrsBody.team, "team") : null;
2900
+ if (nextTeam && !nextTeam.ok) {
2901
+ return withCors(req, Response.json({ ok: false, error: "invalid_team", reason: nextTeam.reason }, { status: 400 }));
2902
+ }
2903
+ const nextTags = "tags" in attrsBody ? narrowTags(attrsBody.tags) : null;
2904
+
2905
+ // Only the supplied fields move; the rest keep their stored value.
2906
+ const sets: string[] = [];
2907
+ const vals: any[] = [];
2908
+ if (nextDisplay) { sets.push(`display_name = ?${vals.length + 1}`); vals.push(nextDisplay.value); }
2909
+ if (nextTeam) { sets.push(`team = ?${vals.length + 1}`); vals.push(nextTeam.value); }
2910
+ if (nextTags) { sets.push(`tags = ?${vals.length + 1}`); vals.push(JSON.stringify(nextTags)); }
2911
+ // A no-op patch still bumps the revision: the caller observed a state
2912
+ // and asserted it, so honouring the CAS keeps client counters in step.
2913
+ sets.push(`attrs_revision = ?${vals.length + 1}`); vals.push(currentRev + 1);
2914
+ sets.push(`updated_at = datetime('now')`);
2915
+ vals.push(node.node_id);
2916
+ // Guard the UPDATE with the same revision so two concurrent writers
2917
+ // that both passed the read above cannot both land.
2918
+ vals.push(currentRev);
2919
+ const res = db.run(
2920
+ `UPDATE nodes SET ${sets.join(", ")} WHERE node_id = ?${vals.length - 1} AND attrs_revision = ?${vals.length}`,
2921
+ vals,
2922
+ );
2923
+ if (!res.changes) {
2924
+ const fresh = db.get<any>("SELECT attrs_revision FROM nodes WHERE node_id = ?1", node.node_id);
2925
+ return withCors(req, Response.json({
2926
+ ok: false,
2927
+ error: "attrs_revision_conflict",
2928
+ current_attrs_revision: Number(fresh?.attrs_revision ?? currentRev),
2929
+ message: "another editor changed this node's attributes; re-read and retry",
2930
+ }, { status: 409 }));
2931
+ }
2932
+ logAudit(restAuth?.userId ?? null, restAuth?.username ?? null, "node_attrs_updated", "node", node.node_id,
2933
+ JSON.stringify({ display_name: nextDisplay?.value ?? undefined, team: nextTeam?.value ?? undefined, tags: nextTags ?? undefined }),
2934
+ undefined, nodeNetId ?? undefined);
2935
+ const after = db.get<any>(
2936
+ "SELECT display_name, team, tags, attrs_revision FROM nodes WHERE node_id = ?1", node.node_id);
2937
+ return withCors(req, Response.json({
2938
+ ok: true,
2939
+ node_id: node.node_id,
2940
+ alias: node.alias,
2941
+ display_name: after?.display_name ?? null,
2942
+ team: after?.team ?? null,
2943
+ tags: parseStoredTags(after?.tags),
2944
+ attrs_revision: Number(after?.attrs_revision ?? currentRev + 1),
2945
+ }));
2946
+ }
2947
+
2948
+ const nodeAvatarMatch = url.pathname.match(/^\/api\/nodes\/([^/]+)\/avatar$/);
2949
+ if (nodeAvatarMatch && req.method === "PUT") {
2950
+ let avatarBody: any;
2951
+ try {
2952
+ avatarBody = await req.json();
2953
+ } catch {
2954
+ return withCors(req, Response.json({ ok: false, error: "invalid JSON" }, { status: 400 }));
2955
+ }
2956
+ const validated = validateAvatarUrl(avatarBody?.avatar_url);
2957
+ if (!validated.ok) {
2958
+ return withCors(req, Response.json({ ok: false, error: "invalid_avatar_url", reason: validated.reason }, { status: 400 }));
2959
+ }
2960
+ const ref = decodeURIComponent(nodeAvatarMatch[1]);
2961
+ const params: any[] = [ref, ref, ref];
2962
+ let sql = "SELECT node_id, alias, network_id FROM nodes WHERE (node_id = ?1 OR node_name = ?2 OR alias = ?3)";
2963
+ sql = addNetworkScope(sql, params, restScope);
2964
+ sql += " ORDER BY updated_at DESC LIMIT 1";
2965
+ const node = db.get<any>(sql, ...params);
2966
+ if (!node) return withCors(req, Response.json({ ok: false, error: "node not found" }, { status: 404 }));
2967
+
2968
+ const nodeNetId = node.network_id ?? singleNetworkId(restScope);
2969
+ if (!canRestWriteNetwork(restAuth, nodeNetId, isAdmin)) {
2970
+ return withCors(req, Response.json({ ok: false, error: "permission_denied" }, { status: 403 }));
2971
+ }
2972
+
2973
+ db.run(
2974
+ "UPDATE nodes SET avatar_url = ?1, updated_at = datetime('now') WHERE node_id = ?2",
2975
+ [validated.value, node.node_id]
2976
+ );
2977
+ return withCors(req, Response.json({ ok: true, node_id: node.node_id, alias: node.alias, avatar_url: validated.value }));
2978
+ }
2979
+
2980
+ // ── REST: nodes table (V2 Sprint 2) ──
2981
+ // Explicit column list — NOT `SELECT *`. Two reasons:
2982
+ // 1. `SELECT *` silently broadcasts any column added later to the
2983
+ // response (RFC-024 added config_revision/config_snapshot which
2984
+ // the dashboard's GET /api/nodes/:id/config endpoint owns;
2985
+ // RFC-028 will add more vault-flavored columns). Tests asserting
2986
+ // response shape break on every ALTER; integrations that key
2987
+ // off Object.keys() can pick up internals.
2988
+ // 2. The list endpoint and the per-node config snapshot endpoint
2989
+ // have different consumer contracts; this list should be the
2990
+ // stable, dashboard-facing fields only.
2991
+ // Add a new column to this list explicitly when a real client needs
2992
+ // it; do NOT switch back to SELECT *.
2993
+ // ── REST: list host_supervisor daemons (RFC-026 §9.2.2 / #338 PR2) ──
2994
+ // Mirror of the `list_host_supervisors` MCP tool for non-MCP callers.
2995
+ // Same SQL + role-extract + member-脱敏 logic; SEC-1 scoped via REST
2996
+ // auth pipeline (restScope). Returns {ok, daemons:[...], count}.
2997
+ if (url.pathname === "/api/host-supervisors") {
2998
+ // #380 — utok callers with exactly one accessible network get a
2999
+ // safe fallback so the create-node wizard doesn't have to bake
3000
+ // network_id into every request (it was hard-4xxing when the
3001
+ // dashboard omitted the query param — that's what "hub 400" was).
3002
+ // `singleNetworkId` returns:
3003
+ // - scope.networkId when it's set (ntok binding, or an
3004
+ // explicitly-requested network the user has verified access to)
3005
+ // - the sole member of scope.networkIds when the utok user
3006
+ // belongs to exactly one network (safe unambiguous fallback)
3007
+ // - null when the user belongs to 0 or 2+ networks (authz
3008
+ // boundary — refuse to guess which one, mirrors 通信龙 spec
3009
+ // "别 fallback 到错 network")
3010
+ // The 400 branch is retained for the ambiguous / no-access cases
3011
+ // and distinguishes them in the error message so the client can
3012
+ // recover (send network_id explicitly).
3013
+ const effectiveNetId = singleNetworkId(restScope);
3014
+ if (!effectiveNetId) {
3015
+ const memberships = restScope.networkIds?.length ?? 0;
3016
+ const error = memberships > 1
3017
+ ? "network_id_required_multi"
3018
+ : "missing_network_id";
3019
+ return withCors(req, Response.json({ ok: false, error, memberships }, { status: 400 }));
3020
+ }
3021
+ // Role for member-脱敏 (admin/owner = full host_telemetry, others = masked)
3022
+ let isPrivileged = false;
3023
+ if (restAuth?.userId) {
3024
+ const role = getUserNetworkRole(restAuth.userId, effectiveNetId);
3025
+ isPrivileged = role === "admin" || role === "owner";
3026
+ } else {
3027
+ // Network-token caller (no user) — treat as privileged within its network
3028
+ isPrivileged = true;
3029
+ }
3030
+
3031
+ // EXISTS subquery handles BOTH revoked_at SET and DELETEd token
3032
+ // rows (revokeToken DELETEs the row in production — PR2 v1
3033
+ // SHOULD-FIX per 通信龙 audit). EXISTS naturally dedupes daemons
3034
+ // with rotated tokens.
3035
+ const sqlRows = db.all<Record<string, any>>(`
3036
+ SELECT
3037
+ n.node_id, n.alias, n.hostname, n.network_id,
3038
+ n.runtimes_supported, n.allowed_secret_keys,
3039
+ n.created_at, n.updated_at,
3040
+ s.last_seen_at AS session_last_seen,
3041
+ s.cpu_cores AS session_cpu_cores,
3042
+ s.mem_total_gb AS session_mem_total_gb,
3043
+ s.ip AS session_ip,
3044
+ n.config_snapshot
3045
+ FROM nodes n
3046
+ LEFT JOIN sessions s ON s.alias = n.alias AND (s.network_id = n.network_id OR s.network_id IS NULL)
3047
+ WHERE n.network_id = ?1
3048
+ AND EXISTS (
3049
+ SELECT 1 FROM api_tokens t
3050
+ WHERE t.network_id = n.network_id
3051
+ AND t.name = 'node:' || n.alias
3052
+ AND t.revoked_at IS NULL
3053
+ )
3054
+ ORDER BY n.updated_at DESC
3055
+ `, effectiveNetId);
3056
+
3057
+ const nowMs = Date.now();
3058
+ // 心跳周期是 3 分钟(agent-node/src/cli.ts 的 report_status 定时器),
3059
+ // 窗口必须大于它,否则每次心跳后的 60s~180s 之间必然抖成 offline
3060
+ // (通信评审牛 #1279 独审④)。取 5min,与仓内既有 stale 口径一致。
3061
+ const ONLINE_MS = 5 * 60_000;
3062
+ const daemons = sqlRows
3063
+ .map(r => {
3064
+ let snapRole: string | null = null;
3065
+ if (r.config_snapshot) {
3066
+ try {
3067
+ const parsed = typeof r.config_snapshot === "string" ? JSON.parse(r.config_snapshot) : r.config_snapshot;
3068
+ snapRole = typeof parsed?.role === "string" ? parsed.role : null;
3069
+ } catch { /* malformed */ }
3070
+ }
3071
+ return { row: r, role: snapRole };
3072
+ })
3073
+ .filter(({ role }) => role === "host_supervisor")
3074
+ .map(({ row: r }) => {
3075
+ let online = false;
3076
+ let lastSeenAt: string | null = null;
3077
+ if (r.session_last_seen) {
3078
+ lastSeenAt = r.session_last_seen;
3079
+ const t = parseDbTimestampMs(r.session_last_seen);
3080
+ if (!isNaN(t)) online = (nowMs - t) <= ONLINE_MS;
3081
+ }
3082
+ let runtimes: string[] = [];
3083
+ let secrets: string[] = [];
3084
+ try {
3085
+ if (r.runtimes_supported) {
3086
+ const parsed = JSON.parse(r.runtimes_supported);
3087
+ runtimes = Array.isArray(parsed) ? parsed.filter((s: unknown) => typeof s === "string") : [];
3088
+ }
3089
+ } catch {}
3090
+ try {
3091
+ if (r.allowed_secret_keys) {
3092
+ const parsed = JSON.parse(r.allowed_secret_keys);
3093
+ secrets = Array.isArray(parsed) ? parsed.filter((s: unknown) => typeof s === "string") : [];
3094
+ }
3095
+ } catch {}
3096
+ const telemetry: Record<string, unknown> = {
3097
+ alert_level: online ? "green" : "gray",
3098
+ };
3099
+ if (isPrivileged) {
3100
+ telemetry.cpu_cores = r.session_cpu_cores ?? null;
3101
+ telemetry.mem_gb = r.session_mem_total_gb ?? null;
3102
+ telemetry.ip_internal = r.session_ip ?? null;
3103
+ }
3104
+ return {
3105
+ daemon_node_id: r.node_id,
3106
+ alias: r.alias,
3107
+ hostname: r.hostname,
3108
+ online,
3109
+ last_seen_at: lastSeenAt,
3110
+ runtimes_supported: runtimes,
3111
+ allowed_secret_keys: secrets,
3112
+ host_telemetry: telemetry,
3113
+ };
3114
+ });
3115
+ return withCors(req, Response.json({ ok: true, daemons, count: daemons.length }));
3116
+ }
3117
+
3118
+ if (url.pathname === "/api/nodes") {
3119
+ const nodeId = url.searchParams.get("node_id");
3120
+ const alias = url.searchParams.get("alias");
3121
+ // `config_snapshot` SELECTed ONLY to extract the daemon `role` field
3122
+ // for dashboard discovery — full snapshot is NOT broadcast (would
3123
+ // re-introduce the #312 SELECT * fragility). Mapping step pulls
3124
+ // `role` out then drops `config_snapshot` from the response row.
3125
+ // RFC-027 PR2 dashboard prereq: lifecycle_state is needed
3126
+ // client-side to drive the ⋮ menu (active → "停止/删除";
3127
+ // stopped → "重启/删除"). Hub schema gained the column at PR1
3128
+ // (#345) but /api/nodes never SELECTed it. Following #312
3129
+ // "explicit SELECT" discipline — extend the projection here,
3130
+ // do NOT switch to SELECT *.
3131
+ // #462: avatar_url added to the projection so custom avatars are
3132
+ // cross-device (dashboard hydrates from here; localStorage was the
3133
+ // only store before). Nullable — null means "use default set".
3134
+ let sql = `SELECT node_id, node_name, alias, runtime, model,
3135
+ config_path, channels, server, hostname,
3136
+ network_id, created_at, updated_at,
3137
+ config_snapshot, lifecycle_state, avatar_url,
3138
+ display_name, team, tags, attrs_revision
3139
+ FROM nodes WHERE 1=1`;
3140
+ const params: any[] = [];
3141
+ sql = addNetworkScope(sql, params, restScope);
3142
+ if (nodeId) { sql += ` AND node_id = ?${params.length + 1}`; params.push(nodeId); }
3143
+ if (alias) { sql += ` AND alias = ?${params.length + 1}`; params.push(alias); }
3144
+ sql += " ORDER BY updated_at DESC";
3145
+ const rawRows = db.all<Record<string, any>>(sql, ...params);
3146
+ // Add a single new field `role: string | null` per row, extracted from
3147
+ // config_snapshot JSON. Daemon nodes that posted role='host_supervisor'
3148
+ // via report_status surface here; dashboard uses this for daemon
3149
+ // discovery (replacing the prior `node_daemon_` prefix heuristic).
3150
+ // RFC-026 P1 P2 §9 will supersede this REST proxy with the
3151
+ // `list_host_supervisors` MCP tool.
3152
+ // app#196 —— 哪些节点能走 stop_node / restart_node / delete_node。
3153
+ //
3154
+ // 背景:那三个工具的 schema 是 `regex(/^node_[a-z0-9_-]+$/)`,而节点 id 有两种:
3155
+ // node_xxxx daemon 建出来的子节点(+ daemon 自己)
3156
+ // n_xxxx 人手工 `anet node start` 起的
3157
+ // 2026-08-28 对生产 hub 实测:218 个节点里 **207 个是 n_**,
3158
+ // 在桌面端点「停止」只会看到一段 zod 正则原文。
3159
+ //
3160
+ // 🔴 这不是「正则写窄了」——那三个工具的做法是**让那台机器上的 daemon 去停它
3161
+ // 自己建的子进程**。手工起的节点没有 daemon 可问,放宽正则只会把失败推到更深处。
3162
+ //
3163
+ // 所以这里给出一个显式标志,**让前端不必靠 id 前缀去猜**。判据不是前缀,
3164
+ // 是 node_create_requests 里真的有对应的创建记录 ——
3165
+ // 子节点 id 由 request_id 确定性推导:`node_${request_id.replace(/^cr_/,"")}`
3166
+ // (2026-08-28 用真实一对验过:cr_59723b24-… → node_59723b24-…)。
3167
+ const controllable = (() => {
3168
+ try {
3169
+ const crParams: any[] = [];
3170
+ let crSql = "SELECT request_id, daemon_node_id FROM node_create_requests WHERE 1=1";
3171
+ crSql = addNetworkScope(crSql, crParams, restScope);
3172
+ return buildControllableMap(db.all<Record<string, any>>(crSql, ...crParams));
3173
+ } catch {
3174
+ // 表不存在/查询失败 ⇒ 全部按不可控处理,不让这一格拖垮整个列表
3175
+ return new Map<string, string>();
3176
+ }
3177
+ })();
3178
+
3179
+ const rows = rawRows.map(r => {
3180
+ let role: string | null = null;
3181
+ const snap = r.config_snapshot;
3182
+ if (snap) {
3183
+ try { role = (typeof snap === "string" ? JSON.parse(snap) : snap)?.role ?? null; }
3184
+ catch { /* malformed snapshot — leave role null */ }
3185
+ }
3186
+ const { config_snapshot, ...rest } = r;
3187
+ // `tags` is stored as JSON text; hand the dashboard a real array so
3188
+ // it can map() without a guard, and normalise legacy/absent values
3189
+ // to [] rather than null. attrs_revision is normalised to a number
3190
+ // so pre-migration rows (NULL) read as 0.
3191
+ // app#196 —— 显式告诉前端这个节点能不能走生命周期操作,以及该找哪个 daemon。
3192
+ // daemon 自己(role=host_supervisor)也能被 restart/stop,它的 id 同样是 node_ 前缀
3193
+ // 且在 node_create_requests 里没有记录,所以单独放行。
3194
+ const lifecycle_controllable = isLifecycleControllable(r.node_id, role, controllable);
3195
+ return {
3196
+ ...rest,
3197
+ tags: parseStoredTags(r.tags),
3198
+ attrs_revision: Number(r.attrs_revision ?? 0),
3199
+ role,
3200
+ lifecycle_controllable,
3201
+ lifecycle_daemon_node_id: controllable.get(r.node_id) ?? null,
3202
+ };
3203
+ });
3204
+ return withCors(req, Response.json({ ok: true, nodes: rows, count: rows.length }));
3205
+ }
3206
+
3207
+ // ── REST: single task lookup (V2) ──
3208
+ const taskPathMatch = url.pathname.match(/^\/api\/tasks?\/([^/]+)$/);
3209
+ if (taskPathMatch && req.method === "GET") {
3210
+ const taskId = decodeURIComponent(taskPathMatch[1] ?? "");
3211
+ const params: any[] = [taskId];
3212
+ let sql = `SELECT ${TASK_REST_SELECT} FROM tasks WHERE task_id = ?1`;
3213
+ sql = addNetworkScope(sql, params, restScope);
3214
+ sql += " LIMIT 1";
3215
+ const task = db.get(sql, ...params);
3216
+ if (!task) {
3217
+ return withCors(req, Response.json({ ok: false, error: "task_not_found", task_id: taskId }, { status: 404 }));
3218
+ }
3219
+ const taskNetworkId = typeof task.network_id === "string" ? task.network_id : null;
3220
+ const canonicalTarget = task.to_node_id
3221
+ ? null
3222
+ : resolveCanonicalAlias(taskNetworkId, String(task.to_name ?? "")).alias;
3223
+ const targetParams: unknown[] = [];
3224
+ let targetSql = "SELECT alias, status FROM sessions WHERE ";
3225
+ if (task.to_node_id) {
3226
+ targetSql += "node_id = ?1";
3227
+ targetParams.push(task.to_node_id);
3228
+ } else {
3229
+ targetSql += "alias = ?1";
3230
+ targetParams.push(canonicalTarget);
3231
+ }
3232
+ if (taskNetworkId) {
3233
+ targetSql += " AND network_id = ?2";
3234
+ targetParams.push(taskNetworkId);
3235
+ } else {
3236
+ targetSql += " AND network_id IS NULL";
3237
+ }
3238
+ targetSql += " ORDER BY updated_at DESC LIMIT 1";
3239
+ const targetSession = db.get<{ alias: string; status: string }>(targetSql, ...targetParams);
3240
+ const targetAlias = targetSession?.alias ?? canonicalTarget ?? String(task.to_name ?? "");
3241
+ const liveSseConnections = getSSEStats().sessions[`${taskNetworkId || "global"}:${targetAlias}`] ?? 0;
3242
+ // 🔴 #1083:这个目标【历史上有没有报过任何一次】运行时证据。
3243
+ // 只用 Hub 自己已有的数据算,不需要 agent 侧任何改动。
3244
+ // 为空时 runtime_submitted_at/consumed_at 是「不会走到」而不是「还没走到」,
3245
+ // 两者处置相反(别等去接线 vs 等)。参数编号沿用上面 targetSql 的写法。
3246
+ const evidenceParams: unknown[] = [];
3247
+ let evidenceSql = "SELECT 1 AS seen FROM tasks WHERE runtime_submitted_at IS NOT NULL AND ";
3248
+ if (task.to_node_id) {
3249
+ evidenceSql += "to_node_id = ?1";
3250
+ evidenceParams.push(task.to_node_id);
3251
+ } else {
3252
+ evidenceSql += "to_node_id IS NULL AND to_name = ?1";
3253
+ evidenceParams.push(canonicalTarget ?? String(task.to_name ?? ""));
3254
+ }
3255
+ if (taskNetworkId) {
3256
+ evidenceSql += " AND network_id = ?2";
3257
+ evidenceParams.push(taskNetworkId);
3258
+ } else {
3259
+ evidenceSql += " AND network_id IS NULL";
3260
+ }
3261
+ evidenceSql += " LIMIT 1";
3262
+ const targetEverReportedRuntimeEvidence =
3263
+ Boolean(db.get<{ seen: number }>(evidenceSql, ...evidenceParams));
3264
+ const diagnostic = diagnoseTask({
3265
+ status: String(task.status ?? "unknown"),
3266
+ runtimeSubmittedAt: typeof task.runtime_submitted_at === "string" ? task.runtime_submitted_at : null,
3267
+ consumedAt: typeof task.consumed_at === "string" ? task.consumed_at : null,
3268
+ targetSessionStatus: targetSession?.status ?? null,
3269
+ targetSessionExists: Boolean(targetSession),
3270
+ liveSseConnections,
3271
+ targetEverReportedRuntimeEvidence,
3272
+ });
3273
+ return withCors(req, Response.json({ ok: true, task, diagnostic }));
3274
+ }
3275
+
3276
+ // ── REST: tasks table (V2) ──
3277
+ if (url.pathname === "/api/tasks") {
3278
+ const taskId = url.searchParams.get("task_id");
3279
+ const status = url.searchParams.get("status");
3280
+ const toName = url.searchParams.get("to_name");
3281
+ const fromName = url.searchParams.get("from_name");
3282
+ const rawBefore = url.searchParams.get("before");
3283
+ const before = rawBefore === null ? null : normalizeTaskBeforeCursor(rawBefore);
3284
+ if (rawBefore !== null && before === null) {
3285
+ return withCors(req, Response.json({ ok: false, error: "invalid_before" }, { status: 400 }));
3286
+ }
3287
+ const rawBeforeTaskId = url.searchParams.get("before_task_id");
3288
+ const beforeTaskId = rawBeforeTaskId === null ? null : normalizeTaskBeforeTaskId(rawBeforeTaskId);
3289
+ if (rawBeforeTaskId !== null && (before === null || beforeTaskId === null)) {
3290
+ return withCors(req, Response.json({ ok: false, error: "invalid_before_task_id" }, { status: 400 }));
3291
+ }
3292
+ const limit = Math.min(Number(url.searchParams.get("limit")) || 50, 200);
3293
+ // #248 — opt-out of the stats GROUP-BY scan. The dashboard chat panel
3294
+ // never consumes `stats`; it's a global per-status table scan that
3295
+ // dominates the request time on a large DB (270 MB / many tasks).
3296
+ // Existing callers that don't pass `skip_stats=1` get the same
3297
+ // {ok, tasks, count, stats} shape — backwards-compatible.
3298
+ const skipStats = url.searchParams.get("skip_stats") === "1";
3299
+
3300
+ let sql = `SELECT ${TASK_REST_SELECT} FROM tasks WHERE 1=1`;
3301
+ const params: any[] = [];
3302
+ sql = addNetworkScope(sql, params, restScope);
3303
+ if (taskId) { sql += ` AND task_id = ?${params.length + 1}`; params.push(taskId); }
3304
+ if (status) { sql += ` AND status = ?${params.length + 1}`; params.push(status); }
3305
+ if (toName) { sql += ` AND to_name = ?${params.length + 1}`; params.push(toName); }
3306
+ if (fromName) { sql += ` AND from_name = ?${params.length + 1}`; params.push(fromName); }
3307
+ if (before && beforeTaskId) {
3308
+ const createdAtParam = params.length + 1;
3309
+ const taskIdParam = params.length + 2;
3310
+ sql += ` AND (created_at < ?${createdAtParam} OR (created_at = ?${createdAtParam} AND task_id < ?${taskIdParam}))`;
3311
+ params.push(before, beforeTaskId);
3312
+ } else if (before) {
3313
+ sql += ` AND created_at < ?${params.length + 1}`;
3314
+ params.push(before);
3315
+ }
3316
+ sql += ` ORDER BY created_at DESC, task_id DESC LIMIT ?${params.length + 1}`;
3317
+ params.push(limit);
3318
+
3319
+ const rows = db.all(sql, ...params);
3320
+ if (skipStats) {
3321
+ return withCors(req, Response.json({ ok: true, tasks: rows, count: rows.length }));
3322
+ }
3323
+ const statsParams: any[] = [];
3324
+ let statsSql = "SELECT status, COUNT(*) as count FROM tasks WHERE 1=1";
3325
+ statsSql = addNetworkScope(statsSql, statsParams, restScope);
3326
+ statsSql += " GROUP BY status";
3327
+ const stats = db.all<any>(statsSql, ...statsParams);
3328
+ return withCors(req, Response.json({ ok: true, tasks: rows, count: rows.length, stats }));
3329
+ }
3330
+
3331
+ // ── REST: recent completions ──
3332
+ if (url.pathname === "/api/completions") {
3333
+ const since = url.searchParams.get("since") ?? new Date(Date.now() - 86400000).toISOString();
3334
+ const params: any[] = [since];
3335
+ let sql = `SELECT ${COMPLETION_REST_SELECT} FROM completions WHERE completed_at >= ?1`;
3336
+ sql = addNetworkScope(sql, params, restScope);
3337
+ sql += " ORDER BY completed_at DESC LIMIT 100";
3338
+ const rows = db.all(sql, ...params);
3339
+ return withCors(req, Response.json({ ok: true, completions: rows }));
3340
+ }
3341
+
3342
+ return withCors(req, new Response(
3343
+ `CommHub MCP Server v${SERVER_VERSION} (Streamable HTTP + SSE Push)
3344
+
3345
+ Endpoints:
3346
+ POST /mcp - MCP Streamable HTTP (for Claude Code / Codex)
3347
+ GET /events/:session - SSE realtime push (Agent subscribes here)
3348
+ GET /health - Health check
3349
+ GET /api/status - All sessions (auth required)
3350
+ POST /api/task - Send task via REST (auth required)
3351
+ GET /api/tasks - Tasks table (V2) (auth required)
3352
+ GET /api/completions - Recent completions (auth required)
3353
+ GET /api/tmux/:name - Capture tmux pane output (${TMUX_ENABLED ? "admin + localhost/allowlist required" : "disabled"})
3354
+ POST /api/tmux/:name/send - Send keys to tmux (${TMUX_ENABLED ? "admin + localhost/allowlist required" : "disabled"})
3355
+
3356
+ Security: ${SECURITY_LABEL}
3357
+ `,
3358
+ { status: 200, headers: { "Content-Type": "text/plain; charset=utf-8" } } // #426
3359
+ ));
3360
+ },
3361
+
3362
+ // ── WebSocket handler for tmux terminal streaming ──
3363
+ websocket: {
3364
+ open(ws) {
3365
+ const { tmuxName } = ws.data as unknown as { tmuxName: string };
3366
+ console.log(`[ws] tmux terminal opened: ${tmuxName}`);
3367
+ let lastOutput = "";
3368
+
3369
+ // Poll capture-pane every 200ms and send diffs
3370
+ const interval = setInterval(async () => {
3371
+ try {
3372
+ const proc = Bun.spawn(["tmux", "capture-pane", "-t", tmuxName, "-p", "-e"], {
3373
+ stdout: "pipe", stderr: "pipe",
3374
+ });
3375
+ const output = await new Response(proc.stdout).text();
3376
+ const code = await proc.exited;
3377
+ if (code !== 0) return;
3378
+
3379
+ if (output !== lastOutput) {
3380
+ lastOutput = output;
3381
+ ws.send(JSON.stringify({ type: "output", data: output }));
3382
+ }
3383
+ } catch { /* session gone */ }
3384
+ }, 200);
3385
+
3386
+ wsTmuxIntervals.set(ws, interval);
3387
+
3388
+ // Send initial capture immediately
3389
+ (async () => {
3390
+ try {
3391
+ const proc = Bun.spawn(["tmux", "capture-pane", "-t", tmuxName, "-p", "-e"], {
3392
+ stdout: "pipe", stderr: "pipe",
3393
+ });
3394
+ const output = await new Response(proc.stdout).text();
3395
+ const code = await proc.exited;
3396
+ if (code === 0) {
3397
+ lastOutput = output;
3398
+ ws.send(JSON.stringify({ type: "output", data: output }));
3399
+ } else {
3400
+ const err = await new Response(proc.stderr).text();
3401
+ ws.send(JSON.stringify({ type: "error", data: err.trim() || "tmux session not found" }));
3402
+ }
3403
+ } catch (e) {
3404
+ ws.send(JSON.stringify({ type: "error", data: (e as Error).message }));
3405
+ }
3406
+ })();
3407
+ },
3408
+
3409
+ async message(ws, message) {
3410
+ const { tmuxName } = ws.data as unknown as { tmuxName: string };
3411
+ try {
3412
+ const msg = JSON.parse(typeof message === "string" ? message : new TextDecoder().decode(message));
3413
+
3414
+ if (msg.type === "input" && typeof msg.data === "string") {
3415
+ // Send individual characters/sequences via send-keys
3416
+ const proc = Bun.spawn(["tmux", "send-keys", "-t", tmuxName, "-l", msg.data], {
3417
+ stdout: "pipe", stderr: "pipe",
3418
+ });
3419
+ await proc.exited;
3420
+ } else if (msg.type === "key" && typeof msg.data === "string") {
3421
+ // Send special key names (Enter, C-c, etc.)
3422
+ const proc = Bun.spawn(["tmux", "send-keys", "-t", tmuxName, msg.data], {
3423
+ stdout: "pipe", stderr: "pipe",
3424
+ });
3425
+ await proc.exited;
3426
+ } else if (msg.type === "resize" && msg.cols && msg.rows) {
3427
+ // Resize tmux pane
3428
+ Bun.spawn(["tmux", "resize-window", "-t", tmuxName, "-x", String(msg.cols), "-y", String(msg.rows)], {
3429
+ stdout: "pipe", stderr: "pipe",
3430
+ });
3431
+ }
3432
+ } catch { /* ignore malformed messages */ }
3433
+ },
3434
+
3435
+ close(ws) {
3436
+ const { tmuxName } = ws.data as unknown as { tmuxName: string };
3437
+ console.log(`[ws] tmux terminal closed: ${tmuxName}`);
3438
+ const interval = wsTmuxIntervals.get(ws);
3439
+ if (interval) { clearInterval(interval); wsTmuxIntervals.delete(ws); }
3440
+ },
3441
+ },
3442
+ });
3443
+ } // end bootServer
3444
+
3445
+ // ── Explicit startup (#438 corrective / 通信龙派单) ──────────────────
3446
+ //
3447
+ // Importing this module NO LONGER binds a port. The two failure modes
3448
+ // this design dodges, both field-verified:
3449
+ //
3450
+ // 1. `if (import.meta.main)` guard — the published package's process
3451
+ // entry is bin/commhub.ts which DYNAMICALLY imports this module, so
3452
+ // import.meta.main is always false there: the process comes up but
3453
+ // listens on nothing (#438 review finding; would have shipped dead).
3454
+ // 2. Module-level `export const server = bootServer()` side effect —
3455
+ // fixes (1) but makes EVERY import bind a port: tooling scripts,
3456
+ // typechecks, and unrelated tests all grab the port by accident.
3457
+ //
3458
+ // The contract instead: bin/commhub.ts (and anything else that wants a
3459
+ // running hub) calls `startHub()` explicitly. Tests that need a private
3460
+ // throwaway instance keep using `bootServer({ port: 0 })`, which stays
3461
+ // side-effect-free (no sweepers / signal handlers / banner).
3462
+ //
3463
+ // startHub is SINGLE-SHOT and observable: a second call throws with the
3464
+ // first boot's coordinates rather than silently no-op'ing — "I thought I
3465
+ // started it but nothing happened" is the same failure family as (1)
3466
+ // (承 通信测试马 verification design requirement).
3467
+
3468
+ let startedHub: { server: ReturnType<typeof Bun.serve>; startedAt: string } | null = null;
3469
+
3470
+ /** The hub instance startHub() booted, or null before startHub() runs.
3471
+ * Read-only introspection for diagnostics; do not boot through this. */
3472
+ export function getStartedHub(): { server: ReturnType<typeof Bun.serve>; startedAt: string } | null {
3473
+ return startedHub;
3474
+ }
3475
+
3476
+ export function startHub(opts?: { port?: number; hostname?: string }): ReturnType<typeof Bun.serve> {
3477
+ if (startedHub) {
3478
+ throw new Error(
3479
+ `startHub() already ran at ${startedHub.startedAt} (listening on ` +
3480
+ `${startedHub.server.hostname}:${startedHub.server.port}) — it is single-shot ` +
3481
+ `by design (sweepers + signal handlers must register exactly once). ` +
3482
+ `For an additional throwaway instance use bootServer({ port: 0 }).`
3483
+ );
3484
+ }
3485
+ // The current PostgreSQL adapter opens a fresh process/connection for each
3486
+ // statement, so its transaction() cannot provide the occurrence claim +
3487
+ // task creation atomicity this scheduler requires. Refuse before opening a
3488
+ // listening socket instead of silently running an unsafe scheduler.
3489
+ assertScheduledTaskBackendSupported();
3490
+ const server = bootServer(opts);
3491
+
3492
+ // Round-2/4 review ② — periodic retention sweep + incremental VACUUM.
3493
+ // Sweeps every hour by default. Operators can disable any single table
3494
+ // by setting COMMHUB_RETENTION_*_DAYS to a negative value, or shorten
3495
+ // the sweep window via COMMHUB_RETENTION_SWEEP_MINUTES.
3496
+ const sweepIntervalMinutes = Number(process.env.COMMHUB_RETENTION_SWEEP_MINUTES);
3497
+ const sweepIntervalMs = Number.isFinite(sweepIntervalMinutes) && sweepIntervalMinutes > 0
3498
+ ? sweepIntervalMinutes * 60 * 1000
3499
+ : 60 * 60 * 1000;
3500
+ const retentionSweeperTimer = startRetentionSweeper(sweepIntervalMs);
3501
+
3502
+ // Round-2/4 review ③ — stale session sweeper (coexists with the
3503
+ // retention sweeper above; different concerns + different cadences).
3504
+ // Replaces the per-request UPDATE in GET /api/status (+ /api/servers,
3505
+ // /api/server-detail/*, MCP get_all_status). Each of those endpoints
3506
+ // used to run UPDATE on the sessions table just to maintain the
3507
+ // derived `offline` status; with the dashboard polling fast that was
3508
+ // 99% no-op write-amp under hot read paths. Now done globally once
3509
+ // every COMMHUB_STALE_SWEEP_SECONDS (default 60s).
3510
+ const staleSweeperTimer = startStaleSessionSweeper();
3511
+
3512
+ // #476 — the two legacy module-level intervals, now owned by startHub
3513
+ // like every other periodic job: rate-limit map cleanup (memory only)
3514
+ // and task expiration patrol (writes DB — must never run on import).
3515
+ // Periods env-overridable so tests can observe a real firing without
3516
+ // waiting minutes (mirrors COMMHUB_RETENTION_SWEEP_MINUTES above).
3517
+ const rateLimitSweepMs = Number(process.env.COMMHUB_RATELIMIT_SWEEP_MS) > 0
3518
+ ? Number(process.env.COMMHUB_RATELIMIT_SWEEP_MS) : 300000;
3519
+ const taskPatrolMs = Number(process.env.COMMHUB_TASK_PATROL_MS) > 0
3520
+ ? Number(process.env.COMMHUB_TASK_PATROL_MS) : 5 * 60 * 1000;
3521
+ const deliveredStalePatrolMs = Number(process.env.COMMHUB_DELIVERED_STALE_PATROL_MS) > 0
3522
+ ? Number(process.env.COMMHUB_DELIVERED_STALE_PATROL_MS) : 5 * 1000;
3523
+ const rateLimitSweepTimer = setInterval(sweepStaleRateLimits, rateLimitSweepMs);
3524
+ const taskPatrolTimer = setInterval(patrolExpiredTasks, taskPatrolMs);
3525
+ patrolDeliveredStaleTasks();
3526
+ const deliveredStalePatrolTimer = setInterval(patrolDeliveredStaleTasks, deliveredStalePatrolMs);
3527
+ const scheduledTaskTimer = startScheduledTaskScheduler();
3528
+
3529
+ // The Bun.serve socket is what keeps the process alive; the periodic
3530
+ // jobs must not — otherwise a test (or a future caller) that stops the
3531
+ // server would still hang on live intervals it cannot reach.
3532
+ (retentionSweeperTimer as any)?.unref?.();
3533
+ (staleSweeperTimer as any)?.unref?.();
3534
+ (rateLimitSweepTimer as any)?.unref?.();
3535
+ (taskPatrolTimer as any)?.unref?.();
3536
+ (deliveredStalePatrolTimer as any)?.unref?.();
3537
+ (scheduledTaskTimer as any)?.unref?.();
3538
+
3539
+ // ── Graceful shutdown ───────────────────────────────
3540
+ function shutdown() {
3541
+ console.log("[commhub] shutting down...");
3542
+ clearInterval(retentionSweeperTimer);
3543
+ clearInterval(staleSweeperTimer);
3544
+ clearInterval(rateLimitSweepTimer);
3545
+ clearInterval(taskPatrolTimer);
3546
+ clearInterval(deliveredStalePatrolTimer);
3547
+ clearInterval(scheduledTaskTimer);
3548
+ db.close();
3549
+ process.exit(0);
3550
+ }
3551
+ process.on("SIGTERM", shutdown);
3552
+ process.on("SIGINT", shutdown);
3553
+
3554
+ // Banner reports the ACTUAL bound address (matters for port 0).
3555
+ const bHost = server.hostname ?? HOST;
3556
+ const bPort = server.port ?? PORT;
3557
+ console.log(`
3558
+ ╔══════════════════════════════════════════════════╗
3559
+ ║ CommHub MCP Server v${SERVER_VERSION} ║
3560
+ ║ Transport: Streamable HTTP (Bun native) ║
3561
+ ║ Security: ${SECURITY_LABEL}${" ".repeat(Math.max(0, 33 - SECURITY_LABEL.length))}║
3562
+ ║ Tmux: ${TMUX_ENABLED ? "ENABLED (admin + localhost/allowlist)" : "DISABLED (set COMMHUB_ENABLE_TMUX=1)"}${" ".repeat(Math.max(0, TMUX_ENABLED ? 0 : 2))}║
3563
+ ║ ║
3564
+ ║ MCP: http://${bHost}:${bPort}/mcp ║
3565
+ ║ REST: http://${bHost}:${bPort}/api ║
3566
+ ║ Health: http://${bHost}:${bPort}/health ║
3567
+ ╚══════════════════════════════════════════════════╝
3568
+ `);
3569
+
3570
+ // RFC-028 P1 boot banner — vault key configuration status.
3571
+ // F2 invariant: hub MUST boot regardless of vault state. Banner-only
3572
+ // (informational), fire-and-forget so startHub stays synchronous;
3573
+ // errors are raised lazily at vault op time. needsKeyToOp=true means
3574
+ // the operator should set ANET_HUB_SECRET_VAULT_KEY before
3575
+ // vault/provider features will work.
3576
+ import("./vault.js").then(({ vaultStatusForBoot }) => {
3577
+ const s = vaultStatusForBoot();
3578
+ if (s.needsKeyToOp) {
3579
+ console.warn("[rfc-028 vault] ⚠️ network_secrets/providers have data BUT ANET_HUB_SECRET_VAULT_KEY is unset — vault ops will throw vault_master_key_missing until you set the env. Generate one: `openssl rand -hex 32` (must match the key used at write time).");
3580
+ } else if (s.configured) {
3581
+ console.log(`[rfc-028 vault] master key configured (tables_have_data=${s.tablesHaveData})`);
3582
+ } else {
3583
+ console.log("[rfc-028 vault] master key not set + no vault rows — vault gating is lazy; boot OK. Set ANET_HUB_SECRET_VAULT_KEY when enabling provider/secret features.");
3584
+ }
3585
+ }).catch((e: any) => {
3586
+ console.warn(`[rfc-028 vault] boot banner skipped (${e?.message || e})`);
3587
+ });
3588
+
3589
+ startedHub = { server, startedAt: new Date().toISOString() };
3590
+ return server;
3591
+ }