@sleep2agi/commhub-server 0.9.0-preview.3 → 0.9.0-preview.30

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