@sleep2agi/commhub-server 0.9.0-preview.5 → 0.9.0-preview.51

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