@sleep2agi/commhub-server 0.9.0-preview.21 → 0.9.0-preview.23

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