@sleep2agi/commhub-server 0.9.0-preview.6 → 0.9.0-preview.61

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