@sleep2agi/commhub-server 0.9.0-preview.7 → 0.9.0-preview.70

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/README.md +125 -7
  2. package/bin/commhub.ts +10 -2
  3. package/package.json +5 -5
  4. package/src/ack-create-request-transport.test.ts +159 -0
  5. package/src/ack-create-request.test.ts +331 -0
  6. package/src/admin-networks-http.test.ts +88 -0
  7. package/src/agent-access.ts +267 -0
  8. package/src/agent-acl-http.test.ts +510 -0
  9. package/src/agent-acl-slice3-http.test.ts +267 -0
  10. package/src/alias-filter.test.ts +72 -0
  11. package/src/alias-filter.ts +32 -0
  12. package/src/api-host-supervisors-can-create-nodes.test.ts +350 -0
  13. package/src/api-host-supervisors-fallback.test.ts +271 -0
  14. package/src/api-nodes-shape.test.ts +26 -10
  15. package/src/auth-sessions-http.test.ts +250 -0
  16. package/src/auth-validate.test.ts +5 -1
  17. package/src/auth.ts +348 -29
  18. package/src/avatar-validate.test.ts +163 -0
  19. package/src/avatar-validate.ts +103 -0
  20. package/src/blocked-exit-on-reply.test.ts +122 -0
  21. package/src/boot-side-effect.test.ts +124 -0
  22. package/src/config-apply-sec1.test.ts +107 -0
  23. package/src/config-apply-validate.test.ts +92 -0
  24. package/src/config-apply-validate.ts +81 -3
  25. package/src/create-node-blocked-gate.test.ts +356 -0
  26. package/src/create-node-tool-schema.test.ts +39 -0
  27. package/src/create-node-validate.test.ts +89 -1
  28. package/src/create-node-validate.ts +89 -7
  29. package/src/create-node-workdir.test.ts +255 -0
  30. package/src/create-node.ts +51 -1
  31. package/src/dashboard-slash-routing-http.test.ts +107 -0
  32. package/src/db-adapter-guard.test.ts +85 -0
  33. package/src/db-adapter.ts +64 -23
  34. package/src/db-timestamp.test.ts +38 -0
  35. package/src/db-timestamp.ts +15 -0
  36. package/src/db.ts +762 -33
  37. package/src/delivered-without-push.test.ts +140 -0
  38. package/src/desktop-message-seam.test.ts +150 -0
  39. package/src/desktop-message.test.ts +368 -0
  40. package/src/ext-token-shared.test.ts +60 -0
  41. package/src/ext-validation-regression.test.ts +131 -0
  42. package/src/external-schedule-edits-http.test.ts +321 -0
  43. package/src/external-schedule-edits-timestamps.test.ts +64 -0
  44. package/src/external-schedule-edits.ts +327 -0
  45. package/src/file-download-authz-dev-open.test.ts +135 -0
  46. package/src/file-download-authz.test.ts +404 -0
  47. package/src/file-download-date-bucket.test.ts +436 -0
  48. package/src/file-network-scope-dev-open.test.ts +97 -0
  49. package/src/file-network-scope.test.ts +732 -0
  50. package/src/health-redaction.test.ts +642 -0
  51. package/src/http-gzip.test.ts +73 -0
  52. package/src/http-gzip.ts +60 -0
  53. package/src/hub-timestamp.test.ts +38 -0
  54. package/src/hub-timestamp.ts +27 -0
  55. package/src/human-dm.ts +149 -0
  56. package/src/inbox-count-sse.test.ts +310 -0
  57. package/src/inbox-count.ts +29 -0
  58. package/src/index.ts +15 -2331
  59. package/src/lifecycle-guard.ts +50 -0
  60. package/src/mcp-write-network-resolution.test.ts +429 -0
  61. package/src/messages-ack-by-agent-http.test.ts +142 -0
  62. package/src/network-name-http.test.ts +75 -0
  63. package/src/network-scope.ts +224 -0
  64. package/src/node-attrs-validate.ts +88 -0
  65. package/src/node-attrs.test.ts +217 -0
  66. package/src/node-create-request-status-http.test.ts +92 -0
  67. package/src/node-files-transport.test.ts +344 -0
  68. package/src/node-id-alias.test.ts +188 -0
  69. package/src/node-lifecycle-controllable.test.ts +64 -0
  70. package/src/node-lifecycle-controllable.ts +51 -0
  71. package/src/node-logs-transport.test.ts +263 -0
  72. package/src/node-request-retention.test.ts +281 -0
  73. package/src/node-request-retention.ts +120 -0
  74. package/src/node-skills-transport.test.ts +209 -0
  75. package/src/node-token-privilege-http.test.ts +149 -0
  76. package/src/observer-avatar-http.test.ts +429 -0
  77. package/src/observer-push.test.ts +252 -0
  78. package/src/package-version-consistency.test.ts +25 -0
  79. package/src/peer-reply-atomic.test.ts +455 -0
  80. package/src/peer-reply-capability.test.ts +70 -0
  81. package/src/push.ts +204 -7
  82. package/src/redact-tokens.test.ts +65 -0
  83. package/src/redact-tokens.ts +40 -0
  84. package/src/rename.ts +7 -2
  85. package/src/reply-target-derivation.test.ts +96 -0
  86. package/src/report-status-host-schema.test.ts +211 -0
  87. package/src/report-status-resume-id-handover.test.ts +150 -0
  88. package/src/require-explicit-test-db.ts +9 -0
  89. package/src/requirement-tags.ts +16 -0
  90. package/src/requirements-http.test.ts +708 -0
  91. package/src/requirements-mcp.test.ts +142 -0
  92. package/src/requirements-migrate.ts +83 -0
  93. package/src/requirements-priority-lowest.test.ts +114 -0
  94. package/src/requirements-upgrade-e2e.test.ts +126 -0
  95. package/src/requirements-upgrade-migration.test.ts +85 -0
  96. package/src/requirements.ts +865 -0
  97. package/src/resolve-port.test.ts +57 -0
  98. package/src/resolve-port.ts +44 -0
  99. package/src/response-charset.test.ts +130 -0
  100. package/src/rest-explicit-columns-http.test.ts +216 -0
  101. package/src/rest-identity.test.ts +129 -0
  102. package/src/rest-identity.ts +100 -0
  103. package/src/rest-projections.ts +68 -0
  104. package/src/rest-write-network-resolution.test.ts +133 -0
  105. package/src/restricted-files.ts +73 -0
  106. package/src/retention.ts +10 -1
  107. package/src/rules-file-duplicate-alias.test.ts +234 -0
  108. package/src/rules-file-session-target.test.ts +207 -0
  109. package/src/rules-file-transport.test.ts +237 -0
  110. package/src/runtime-label.test.ts +22 -0
  111. package/src/runtime-label.ts +21 -0
  112. package/src/scheduled-doorbell-nodeless-session.test.ts +130 -0
  113. package/src/scheduled-run-terminal.test.ts +268 -0
  114. package/src/scheduled-skip-blocking-task.test.ts +120 -0
  115. package/src/scheduled-tasks-http.test.ts +574 -0
  116. package/src/scheduled-tasks.ts +596 -0
  117. package/src/send-dedup-request-id.test.ts +229 -0
  118. package/src/send-reply-agent-warning.test.ts +202 -0
  119. package/src/send-reply-alias-optional.test.ts +131 -0
  120. package/src/send-reply-attachments.test.ts +458 -0
  121. package/src/send_dedup.test.ts +54 -0
  122. package/src/send_dedup.ts +52 -6
  123. package/src/serve-error.test.ts +38 -0
  124. package/src/serve-error.ts +27 -0
  125. package/src/server.ts +4279 -0
  126. package/src/shared/external-schedule-contract.ts +60 -0
  127. package/src/side-thread-command-transport.test.ts +302 -0
  128. package/src/side-thread-command-transport.ts +318 -0
  129. package/src/side-thread-http-integration.test.ts +233 -0
  130. package/src/side-thread-http.ts +504 -0
  131. package/src/side-thread-production.test.ts +72 -0
  132. package/src/side-thread-production.ts +118 -0
  133. package/src/side-thread.test.ts +1067 -0
  134. package/src/side-thread.ts +2495 -0
  135. package/src/skillhub-http.test.ts +92 -0
  136. package/src/start-node.test.ts +109 -0
  137. package/src/stop-delete-node.test.ts +1164 -0
  138. package/src/task-auth-origin-http.test.ts +91 -0
  139. package/src/task-auth-origin.test.ts +24 -0
  140. package/src/task-auth-origin.ts +7 -0
  141. package/src/task-consumption.test.ts +482 -0
  142. package/src/task-diagnostic-http.test.ts +149 -0
  143. package/src/task-diagnostic.test.ts +115 -0
  144. package/src/task-diagnostic.ts +118 -0
  145. package/src/task-idempotency-mcp.test.ts +142 -0
  146. package/src/task-idempotency.test.ts +60 -0
  147. package/src/task-idempotency.ts +75 -0
  148. package/src/task-lifecycle-watcher.test.ts +204 -0
  149. package/src/task-lifecycle-watcher.ts +49 -0
  150. package/src/task-network-resolution-http.test.ts +141 -0
  151. package/src/tasks-pagination-http.test.ts +141 -0
  152. package/src/tools-list-json-schema.test.ts +66 -0
  153. package/src/tools.ts +3445 -257
  154. package/src/update-provider.test.ts +65 -0
  155. package/src/upload-early-reject-guard.test.ts +155 -0
  156. package/src/uploads-http.test.ts +97 -15
  157. package/src/uploads.test.ts +66 -0
  158. package/src/uploads.ts +130 -5
  159. package/src/user-inbox-by-agent-http.test.ts +161 -0
  160. package/src/user-inbox-netid-notnull.test.ts +122 -0
  161. package/src/user-inbox-read-http.test.ts +223 -0
  162. package/src/user-inbox-schema.test.ts +54 -0
package/src/index.ts CHANGED
@@ -1,2331 +1,15 @@
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, pushEvent, getSSEStats } from "./push.js";
7
- 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";
8
- import { abortRename, cleanupCommittedRenameSessions, commitRename, prepareRename, resolveCanonicalAlias } from "./rename.js";
9
- import { sharedSendDedup, buildDuplicateSendPayload } from "./send_dedup.js";
10
- import { getLoginClientIp, sharedLoginFailureLockout, sharedLoginIpRateLimiter } from "./auth_login_guard.js";
11
- import {
12
- FILE_ID_REGEX,
13
- MAX_REQUEST_CONTENT_LENGTH,
14
- MAX_UPLOAD_BYTES,
15
- buildStoragePath,
16
- generateFileId,
17
- getUploadsRoot,
18
- indexEntryPath,
19
- isPathInsideUploadsRoot,
20
- sanitizeExt,
21
- sharedUploadRateLimiter,
22
- validateAttachments,
23
- validateIndexEntry,
24
- } from "./uploads.js";
25
- import { mkdirSync, writeFileSync, readFileSync, existsSync, statSync } from "fs";
26
- import { dirname as pathDirname } from "path";
27
- import { startRetentionSweeper } from "./retention.js";
28
- import { startStaleSessionSweeper } from "./stale-sweeper.js";
29
-
30
- const PORT = Number(process.env.PORT) || 9200;
31
- const HOST = process.env.HOST || "127.0.0.1";
32
- const AUTH_TOKEN = process.env.COMMHUB_AUTH_TOKEN;
33
- const DEV_OPEN = process.argv.includes("--dev-open") || process.env.COMMHUB_DEV_OPEN === "1";
34
- const TMUX_ENABLED = process.env.COMMHUB_ENABLE_TMUX === "1";
35
- const SECURITY_LABEL = DEV_OPEN ? "⚠️ DEV OPEN MODE" : "🔒 secured";
36
- const TMUX_ALLOWLIST = new Set(
37
- (process.env.COMMHUB_TMUX_ALLOWLIST || "")
38
- .split(",")
39
- .map((s) => s.trim())
40
- .filter(Boolean)
41
- );
42
- let masterTokenDeprecationLogged = false;
43
-
44
- if (AUTH_TOKEN) {
45
- console.warn("[commhub] COMMHUB_AUTH_TOKEN is deprecated and will be removed in v1.0. See RFC-001.");
46
- }
47
-
48
- // Read version from package.json so banners and /health stay in sync.
49
- const SERVER_VERSION = (() => {
50
- try {
51
- const url = new URL("../package.json", import.meta.url);
52
- return JSON.parse(require("fs").readFileSync(url, "utf8")).version || "?";
53
- } catch { return "?"; }
54
- })();
55
-
56
- // In-memory log ring buffer — last N lines streamed via /api/server-logs.
57
- // Wraps console.log/info/warn/error so EVERY existing log call lands here
58
- // without source changes. Dashboard tails this buffer for "hub server log
59
- // view" feature.
60
- const LOG_RING_CAP = Number(process.env.COMMHUB_LOG_RING || 500);
61
- type LogEntry = { ts: string; level: "log" | "info" | "warn" | "error"; line: string };
62
- const logRing: LogEntry[] = [];
63
- const _origConsole = { log: console.log.bind(console), info: console.info.bind(console), warn: console.warn.bind(console), error: console.error.bind(console) };
64
- function pushLog(level: LogEntry["level"], args: any[]) {
65
- const line = args.map(a => typeof a === "string" ? a : (() => { try { return JSON.stringify(a); } catch { return String(a); } })()).join(" ");
66
- logRing.push({ ts: new Date().toISOString(), level, line: line.slice(0, 4000) });
67
- if (logRing.length > LOG_RING_CAP) logRing.splice(0, logRing.length - LOG_RING_CAP);
68
- }
69
- console.log = (...args: any[]) => { pushLog("log", args); _origConsole.log(...args); };
70
- console.info = (...args: any[]) => { pushLog("info", args); _origConsole.info(...args); };
71
- console.warn = (...args: any[]) => { pushLog("warn", args); _origConsole.warn(...args); };
72
- console.error = (...args: any[]) => { pushLog("error", args); _origConsole.error(...args); };
73
-
74
- function normalizeMetaJson(meta: unknown): string | null {
75
- if (!meta || typeof meta !== "object") return null;
76
- try { return JSON.stringify(meta); } catch { return null; }
77
- }
78
-
79
- // ── Rate limiter (in-memory, per IP) ──
80
- const rateLimits = new Map<string, { count: number; resetAt: number }>();
81
- function checkRateLimit(ip: string, maxPerMinute = 60): boolean {
82
- // Skip rate limiting for localhost/internal/unknown (dev/test)
83
- if (!ip || ip === "unknown" || ip === "127.0.0.1" || ip === "::1") return true;
84
- const now = Date.now();
85
- const entry = rateLimits.get(ip);
86
- if (!entry || now > entry.resetAt) {
87
- rateLimits.set(ip, { count: 1, resetAt: now + 60000 });
88
- return true;
89
- }
90
- if (entry.count >= maxPerMinute) return false;
91
- entry.count++;
92
- return true;
93
- }
94
- // Cleanup stale entries every 5 minutes
95
- setInterval(() => {
96
- const now = Date.now();
97
- for (const [ip, entry] of rateLimits) {
98
- if (now > entry.resetAt) rateLimits.delete(ip);
99
- }
100
- }, 300000);
101
-
102
- // ── Factory: 每个请求创建新的 McpServer(stateless 模式)──
103
- function createServer(clientIP?: string, enforceNetworkId?: string | null, enforceUserId?: string | null, callerAlias?: string | null, callerTokenIsNetwork = false, callerTokenId?: string | null): McpServer {
104
- const server = new McpServer({
105
- name: "commhub",
106
- version: "0.5.0",
107
- });
108
- registerTools(server, clientIP, enforceNetworkId, enforceUserId, callerAlias, callerTokenIsNetwork, callerTokenId);
109
- return server;
110
- }
111
-
112
- // ── Auth helper ─────────────────────────────────────
113
- function requestToken(req: Request): string {
114
- const header = req.headers.get("Authorization")?.replace("Bearer ", "");
115
- const url = new URL(req.url);
116
- return header || url.searchParams.get("token") || "";
117
- }
118
-
119
- function isLegacyAuthToken(req: Request): boolean {
120
- const token = requestToken(req);
121
- return !!AUTH_TOKEN && token === AUTH_TOKEN;
122
- }
123
-
124
- function requireAuth(req: Request): Response | null {
125
- const token = requestToken(req);
126
-
127
- // V3: check api_tokens first
128
- if (token) {
129
- const resolved = resolveToken(token);
130
- if (resolved) return null; // valid user token
131
- }
132
-
133
- // Legacy: check global COMMHUB_AUTH_TOKEN
134
- if (!AUTH_TOKEN && DEV_OPEN) return null; // explicit local/dev open mode
135
- if (token === AUTH_TOKEN) {
136
- const u = new URL(req.url);
137
- const readOnlyApi = u.pathname.startsWith("/api/") && (req.method === "GET" || req.method === "HEAD" || req.method === "OPTIONS");
138
- if (!readOnlyApi) return Response.json({ ok: false, error: "master-token auth is deprecated; use admin utok_" }, { status: 401 });
139
- if (!masterTokenDeprecationLogged) {
140
- console.warn("[commhub] master-token auth is deprecated and will be removed in v1.0. See RFC-001.");
141
- masterTokenDeprecationLogged = true;
142
- }
143
- return null;
144
- }
145
-
146
- return Response.json({ error: "unauthorized" }, { status: 401 });
147
- }
148
-
149
- function getClientIP(req: Request, server?: any): string {
150
- const direct = server?.requestIP?.(req)?.address;
151
- if (direct) return direct;
152
- const fwd = req.headers.get("x-forwarded-for");
153
- return fwd ? fwd.split(",")[0].trim() : (req.headers.get("x-real-ip") ?? "unknown");
154
- }
155
-
156
- function isLocalhostIP(ip: string): boolean {
157
- return ip === "127.0.0.1" || ip === "::1" || ip === "::ffff:127.0.0.1" || ip === "localhost";
158
- }
159
-
160
- // Normalize the raw `agent` field into a canonical runtime identifier for the
161
- // dashboard's Runtime badge. Returns null for unknown/absent agents so the
162
- // frontend can fall back to a placeholder.
163
- function normalizeRuntime(agent: unknown): string | null {
164
- if (typeof agent !== "string" || agent.length === 0) return null;
165
- if (agent === "claude-code") return "claude-code-cli";
166
- if (agent.startsWith("agent-node:codex")) return "codex-sdk";
167
- if (agent.startsWith("agent-node:claude")) return "claude-agent-sdk";
168
- if (agent === "http-api" || agent === "http" || agent === "api") return "http-api";
169
- return null;
170
- }
171
-
172
- function isTmuxAllowedIP(ip: string): boolean {
173
- return isLocalhostIP(ip) || TMUX_ALLOWLIST.has(ip);
174
- }
175
-
176
- function requireAdminAuth(req: Request): Response | null {
177
- const token = requestToken(req);
178
- if (!token) return Response.json({ ok: false, error: "auth required" }, { status: 401 });
179
- const resolved = resolveToken(token);
180
- if (!resolved) return Response.json({ ok: false, error: "invalid token" }, { status: 401 });
181
- if (resolved.user.role !== "admin") return Response.json({ ok: false, error: "admin required" }, { status: 403 });
182
- return null;
183
- }
184
-
185
- function requireTmuxAccess(req: Request, server?: any): Response | null {
186
- if (!TMUX_ENABLED) return Response.json({ ok: false, error: "tmux disabled" }, { status: 404 });
187
- const ip = getClientIP(req, server);
188
- if (!isTmuxAllowedIP(ip)) return Response.json({ ok: false, error: "tmux access denied from this ip" }, { status: 403 });
189
- return requireAdminAuth(req);
190
- }
191
-
192
- // Extract user + network + token-binding identity from request token.
193
- function resolveRequestAuth(req: Request): { userId: string; networkId: string | null; username: string; tokenName: string | null; tokenId: string | null } | null {
194
- const token = requestToken(req);
195
- if (!token) return null;
196
- const resolved = resolveToken(token);
197
- if (!resolved) return null;
198
- return { userId: resolved.user.user_id, networkId: resolved.networkId, username: resolved.user.username, tokenName: resolved.tokenName, tokenId: resolved.tokenId };
199
- }
200
-
201
- type RestNetworkScope = {
202
- networkId: string | null;
203
- networkIds: string[] | null;
204
- denied?: string;
205
- };
206
-
207
- function getUserNetworkIds(userId: string): string[] {
208
- return db.all<{ network_id: string }>(
209
- "SELECT network_id FROM network_members WHERE user_id = ?1",
210
- userId
211
- ).map((row) => row.network_id);
212
- }
213
-
214
- function resolveRestNetworkScope(url: URL, authCtx: { userId: string; networkId: string | null } | null, isAdmin: boolean): RestNetworkScope {
215
- const requested = url.searchParams.get("network_id");
216
-
217
- // Legacy global token or open dev mode keeps the old global behavior.
218
- if (!authCtx) return { networkId: requested || null, networkIds: null };
219
-
220
- // Network tokens are forcibly scoped to their bound network.
221
- if (authCtx.networkId) return { networkId: authCtx.networkId, networkIds: null };
222
-
223
- // System admins may intentionally inspect all networks.
224
- if (isAdmin) return { networkId: requested || null, networkIds: null };
225
-
226
- if (requested) {
227
- const role = getUserNetworkRole(authCtx.userId, requested);
228
- if (!role) return { networkId: null, networkIds: [], denied: "access denied to requested network" };
229
- return { networkId: requested, networkIds: null };
230
- }
231
-
232
- return { networkId: null, networkIds: getUserNetworkIds(authCtx.userId) };
233
- }
234
-
235
- function addNetworkScope(sql: string, params: any[], scope: RestNetworkScope, column = "network_id"): string {
236
- if (scope.networkId) {
237
- sql += ` AND ${column} = ?${params.length + 1}`;
238
- params.push(scope.networkId);
239
- } else if (scope.networkIds) {
240
- if (scope.networkIds.length === 0) {
241
- sql += " AND 1=0";
242
- } else {
243
- const placeholders = scope.networkIds.map((_, i) => `?${params.length + i + 1}`).join(", ");
244
- sql += ` AND ${column} IN (${placeholders})`;
245
- params.push(...scope.networkIds);
246
- }
247
- }
248
- return sql;
249
- }
250
-
251
- function singleNetworkId(scope: RestNetworkScope): string | null {
252
- if (scope.networkId) return scope.networkId;
253
- if (scope.networkIds?.length === 1) return scope.networkIds[0];
254
- return null;
255
- }
256
-
257
- function sqliteTime(date: Date): string {
258
- return date.toISOString().replace("T", " ").slice(0, 19);
259
- }
260
-
261
- function parseSqliteTime(value: string | null | undefined): number {
262
- if (!value) return 0;
263
- const normalized = value.includes("T") ? value : `${value.replace(" ", "T")}Z`;
264
- const ts = Date.parse(normalized);
265
- return Number.isFinite(ts) ? ts : 0;
266
- }
267
-
268
- function cpuPct(load: number | null | undefined, cores: number | null | undefined): number | null {
269
- if (typeof load !== "number" || typeof cores !== "number" || cores <= 0) return null;
270
- return Math.round((load / cores) * 1000) / 10;
271
- }
272
-
273
- function serverAlertLevel(row: any): { level: "green" | "yellow" | "red"; alerts: string[] } {
274
- const alerts: string[] = [];
275
- const pct = cpuPct(row?.cpu_load_1min, row?.cpu_cores);
276
- if (pct !== null && pct >= 80) alerts.push(`cpu ${pct}%`);
277
- if (typeof row?.mem_avail_gb === "number" && row.mem_avail_gb < 0.5) alerts.push(`memory ${row.mem_avail_gb}GB available`);
278
- if (typeof row?.disk_avail_gb === "number" && row.disk_avail_gb < 1) alerts.push(`disk ${row.disk_avail_gb}GB available`);
279
- if (alerts.length > 0) return { level: "red", alerts };
280
-
281
- if (pct !== null && pct >= 60) alerts.push(`cpu ${pct}%`);
282
- if (typeof row?.mem_avail_gb === "number" && row.mem_avail_gb < 1) alerts.push(`memory ${row.mem_avail_gb}GB available`);
283
- if (typeof row?.disk_avail_gb === "number" && row.disk_avail_gb < 5) alerts.push(`disk ${row.disk_avail_gb}GB available`);
284
- return { level: alerts.length > 0 ? "yellow" : "green", alerts };
285
- }
286
-
287
- function agentHealthChip(status: unknown, lastSeen: string | null | undefined): "online" | "offline" | "stale" {
288
- if (String(status || "").toLowerCase() === "offline") return "offline";
289
- const ts = parseSqliteTime(lastSeen);
290
- if (!ts || Date.now() - ts > 5 * 60 * 1000) return "stale";
291
- return "online";
292
- }
293
-
294
- function bucketTelemetry(rows: any[], fromMs: number, bucketMs: number) {
295
- const buckets = new Map<number, {
296
- ts: number;
297
- count: number;
298
- cpu_pct_sum: number;
299
- cpu_pct_count: number;
300
- cpu_load_sum: number;
301
- cpu_load_count: number;
302
- mem_avail_min: number | null;
303
- mem_used_max: number | null;
304
- disk_avail_min: number | null;
305
- disk_used_max: number | null;
306
- }>();
307
-
308
- for (const row of rows) {
309
- const ts = parseSqliteTime(row.created_at);
310
- if (!ts || ts < fromMs) continue;
311
- const bucketTs = Math.floor(ts / bucketMs) * bucketMs;
312
- const bucket = buckets.get(bucketTs) ?? {
313
- ts: bucketTs,
314
- count: 0,
315
- cpu_pct_sum: 0,
316
- cpu_pct_count: 0,
317
- cpu_load_sum: 0,
318
- cpu_load_count: 0,
319
- mem_avail_min: null,
320
- mem_used_max: null,
321
- disk_avail_min: null,
322
- disk_used_max: null,
323
- };
324
- bucket.count += 1;
325
- const pct = cpuPct(row.cpu_load_1min, row.cpu_cores);
326
- if (pct !== null) {
327
- bucket.cpu_pct_sum += pct;
328
- bucket.cpu_pct_count += 1;
329
- }
330
- if (typeof row.cpu_load_1min === "number") {
331
- bucket.cpu_load_sum += row.cpu_load_1min;
332
- bucket.cpu_load_count += 1;
333
- }
334
- 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);
335
- 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);
336
- 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);
337
- 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);
338
- buckets.set(bucketTs, bucket);
339
- }
340
-
341
- return Array.from(buckets.values())
342
- .sort((a, b) => a.ts - b.ts)
343
- .map((b) => ({
344
- ts: new Date(b.ts).toISOString(),
345
- count: b.count,
346
- cpu_pct: b.cpu_pct_count ? Math.round((b.cpu_pct_sum / b.cpu_pct_count) * 10) / 10 : null,
347
- cpu_load_1min: b.cpu_load_count ? Math.round((b.cpu_load_sum / b.cpu_load_count) * 100) / 100 : null,
348
- mem_avail_gb: b.mem_avail_min,
349
- mem_used_gb: b.mem_used_max,
350
- disk_avail_gb: b.disk_avail_min,
351
- disk_used_gb: b.disk_used_max,
352
- }));
353
- }
354
-
355
- function canRestWriteNetwork(authCtx: { userId: string; networkId: string | null } | null, networkId: string | null, isAdmin: boolean): boolean {
356
- if (!authCtx) return true; // legacy global token or open dev mode
357
- if (isAdmin) return true;
358
- if (!networkId) return false;
359
- const role = getUserNetworkRole(authCtx.userId, networkId);
360
- return !!role && role !== "viewer";
361
- }
362
-
363
- type RestDeliveryTarget =
364
- | { state: "online"; alias: string; session: any }
365
- | { state: "offline"; alias: string; session: any; message: string }
366
- | { state: "not_found"; alias: string; message: string };
367
-
368
- function resolveRestDeliveryTarget(alias: string, networkId: string | null): RestDeliveryTarget {
369
- const params: any[] = [alias];
370
- let sql = "SELECT status, updated_at, last_seen_at, node_id FROM sessions WHERE alias = ?1";
371
- if (networkId) {
372
- sql += " AND network_id = ?2";
373
- params.push(networkId);
374
- }
375
- const session = db.get<any>(sql, ...params);
376
- if (!session) {
377
- return { state: "not_found", alias, message: `alias not found: ${alias}` };
378
- }
379
- const lastSeen = session.last_seen_at || session.updated_at;
380
- const lastSeenAt = lastSeen ? new Date(String(lastSeen).replace(" ", "T") + "Z").getTime() : 0;
381
- const stale = !lastSeenAt || Date.now() - lastSeenAt > 5 * 60 * 1000;
382
- if (String(session.status || "").toLowerCase() === "offline" || stale) {
383
- return {
384
- state: "offline",
385
- alias,
386
- session,
387
- message: `alias is offline; task queued in inbox: ${alias}`,
388
- };
389
- }
390
- return { state: "online", alias, session };
391
- }
392
-
393
- function resolveRestNodeIdForAlias(alias: string, networkId: string | null): string | null {
394
- if (!alias || alias === "hub" || alias === "api") return null;
395
- const canonical = resolveCanonicalAlias(networkId, alias);
396
- const target = resolveRestDeliveryTarget(canonical.alias, networkId);
397
- return target.state === "not_found" ? null : (target.session?.node_id ?? null);
398
- }
399
-
400
- // ── REST input schema ───────────────────────────────
401
- const TaskSchema = z.object({
402
- alias: z.string().min(1).max(200),
403
- task: z.string().min(1).max(10000),
404
- priority: z.enum(["high", "normal", "low"]).default("normal"),
405
- from: z.string().max(200).optional(),
406
- network_id: z.string().max(200).optional(),
407
- parent_task_id: z.string().max(200).optional(),
408
- ttl_seconds: z.number().min(1).max(86400).optional(),
409
- // #221 — top-level attachments mirror the MCP send_task tool. They are
410
- // merged into `meta.attachments` for persistence so the on-disk shape
411
- // stays unified regardless of transport (REST or MCP).
412
- attachments: z.any().optional(),
413
- meta: z.any().optional(),
414
- });
415
-
416
- const BroadcastSchema = z.object({
417
- message: z.string().min(1).max(10000),
418
- filter_server: z.string().max(200).optional(),
419
- filter_status: z.string().max(50).optional(),
420
- });
421
-
422
- // ── HTTP Server (Bun native) ────────────────────────
423
- const CORS_ORIGINS = process.env.COMMHUB_CORS_ORIGINS
424
- ? process.env.COMMHUB_CORS_ORIGINS.split(",").map((s) => s.trim())
425
- : ["http://localhost:3000", "http://localhost:3001"];
426
-
427
- function corsHeaders(req: Request): Record<string, string> {
428
- const origin = req.headers.get("Origin") || "";
429
- // CORS allowlist is driven entirely by COMMHUB_CORS_ORIGINS env (comma-separated).
430
- // Default (env unset) allows localhost dev origins only — see CORS_ORIGINS above.
431
- // No author-specific domains are hardcoded; production deployments must set
432
- // COMMHUB_CORS_ORIGINS explicitly. See docs/concepts/security.md "CORS 配置".
433
- const allowed = CORS_ORIGINS.includes(origin) ? origin : "";
434
- return {
435
- "Access-Control-Allow-Origin": allowed,
436
- "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
437
- "Access-Control-Allow-Headers": "Content-Type, Authorization",
438
- "Access-Control-Max-Age": "86400",
439
- };
440
- }
441
-
442
- function withCors(req: Request, res: Response): Response {
443
- const headers = corsHeaders(req);
444
- for (const [k, v] of Object.entries(headers)) {
445
- res.headers.set(k, v);
446
- }
447
- return res;
448
- }
449
-
450
- // ── WebSocket tmux sessions ────────────────────────
451
- const wsTmuxIntervals = new Map<object, ReturnType<typeof setInterval>>();
452
-
453
-
454
- // ── Task expiration patrol (every 5 minutes) ──
455
- setInterval(() => {
456
- try {
457
- const result = db.run(
458
- `UPDATE tasks SET status = 'expired', completed_at = datetime('now')
459
- WHERE expires_at IS NOT NULL AND expires_at < datetime('now')
460
- AND status IN ('created', 'delivered')`
461
- );
462
- if (result.changes > 0) {
463
- console.log(`[patrol] expired ${result.changes} stale task(s)`);
464
- // Log events for expired tasks
465
- const expired = db.all<{ task_id: string }>(
466
- "SELECT task_id FROM tasks WHERE status = 'expired' AND completed_at >= datetime('now', '-1 minute')");
467
- for (const t of expired) logTaskEvent(t.task_id, null, "expired", "patrol");
468
- }
469
- } catch {}
470
- }, 5 * 60 * 1000);
471
-
472
- Bun.serve({
473
- port: PORT,
474
- hostname: HOST,
475
- idleTimeout: 255, // max value: keep SSE connections alive (seconds)
476
- // #221 — defense-in-depth cap on the raw request body. The /api/upload
477
- // handler also pre-checks Content-Length and post-checks parsed size
478
- // against the documented 12 MiB cap (MAX_UPLOAD_BYTES); this knob
479
- // simply guarantees Bun's own buffer won't grow past 13 MiB on any
480
- // route. Default Bun ceiling is 128 MiB which is too permissive for
481
- // a hub now exposed to the public internet.
482
- maxRequestBodySize: MAX_REQUEST_CONTENT_LENGTH,
483
-
484
- async fetch(req, server) {
485
- const url = new URL(req.url, `http://localhost:${PORT}`);
486
-
487
- // ── CORS preflight ──
488
- if (req.method === "OPTIONS") {
489
- return new Response(null, { status: 204, headers: corsHeaders(req) });
490
- }
491
-
492
- // ── WebSocket: tmux terminal ──
493
- const wsMatch = url.pathname.match(/^\/ws\/tmux\/([a-zA-Z0-9_-]+)$/);
494
- if (wsMatch) {
495
- const tmuxErr = requireTmuxAccess(req, server);
496
- if (tmuxErr) return withCors(req, tmuxErr);
497
- if (server.upgrade(req, { data: { tmuxName: wsMatch[1] } } as any)) return;
498
- }
499
-
500
- // ── MCP Streamable HTTP endpoint ──
501
- if (url.pathname === "/mcp") {
502
- const authErr = requireAuth(req);
503
- if (authErr) return withCors(req, authErr);
504
- const clientIP = getClientIP(req, server);
505
- // V3: resolve token → enforce network_id in all MCP tools.
506
- // utok_ (user token, not network-bound) is allowed — the tool layer
507
- // scopes to the user's accessible networks. Without this Dashboard
508
- // (which logs in as a user) cannot call send_task.
509
- const token = requestToken(req);
510
- const authCtx = resolveRequestAuth(req);
511
- const enforceNetId = authCtx?.networkId || null;
512
- // Derive the calling alias from the token name (e.g., 'node:视频审查')
513
- // so peer agents see the real sender instead of 'hub' on send_task.
514
- const callerAlias = authCtx?.tokenName?.startsWith("node:")
515
- ? authCtx.tokenName.slice("node:".length)
516
- : (authCtx?.username || null);
517
- const transport = new WebStandardStreamableHTTPServerTransport({
518
- sessionIdGenerator: undefined,
519
- });
520
- const mcpServer = createServer(clientIP, enforceNetId, authCtx?.userId || null, callerAlias, !!token?.startsWith("ntok_"), authCtx?.tokenId || null);
521
- await mcpServer.connect(transport);
522
- const response = await transport.handleRequest(req);
523
- // Disconnect after response to prevent McpServer leak
524
- setImmediate(() => mcpServer.close().catch(() => {}));
525
- return response;
526
- }
527
-
528
- // ── SSE push: Agent 实时接收任务推送 ──
529
- // GET /events/知识哥 → 保持长连接,send_task 时秒推
530
- const eventsMatch = url.pathname.match(/^\/events\/(.+)$/);
531
- if (eventsMatch && req.method === "GET") {
532
- const authErr = requireAuth(req);
533
- if (authErr) return authErr;
534
- const sessionName = decodeURIComponent(eventsMatch[1]);
535
- const token = requestToken(req);
536
- const authCtx = resolveRequestAuth(req);
537
- const scopedNetId = authCtx?.networkId || url.searchParams.get("network_id");
538
-
539
- // ── Path 1: legacy AUTH_TOKEN (master token) — unchanged ──
540
- if (!authCtx && isLegacyAuthToken(req)) {
541
- if (scopedNetId) {
542
- const session = db.get<any>(
543
- "SELECT 1 FROM sessions WHERE alias = ?1 AND network_id = ?2",
544
- sessionName, scopedNetId
545
- );
546
- if (!session) return withCors(req, Response.json({ ok: false, error: "session not in requested network" }, { status: 403 }));
547
- }
548
- return createSSEStream(sessionName, scopedNetId);
549
- }
550
-
551
- // ── Path 2: ntok_ (network-bound agent token) — pre-#247 behavior preserved ──
552
- if (token?.startsWith("ntok_")) {
553
- if (!authCtx || !scopedNetId) {
554
- return withCors(req, Response.json({ ok: false, error: "network-scoped token required for SSE" }, { status: 403 }));
555
- }
556
- const role = getUserNetworkRole(authCtx.userId, scopedNetId);
557
- if (!role) return withCors(req, Response.json({ ok: false, error: "not a member of this network" }, { status: 403 }));
558
- const session = db.get<any>(
559
- "SELECT 1 FROM sessions WHERE alias = ?1 AND network_id = ?2",
560
- sessionName, scopedNetId
561
- );
562
- if (!session && authCtx.networkId !== scopedNetId) {
563
- return withCors(req, Response.json({ ok: false, error: "session not in requested network" }, { status: 403 }));
564
- }
565
- return createSSEStream(sessionName, scopedNetId);
566
- }
567
-
568
- // ── Path 3 (#247): utok_ (user token, dashboard SSE path) — 4 gates ──
569
- //
570
- // Pre-#247 the only V3 path required `ntok_` and rejected `utok_` outright,
571
- // which locked the dashboard out of SSE (the dashboard proxy authenticates
572
- // with the user's `utok_`). That broke real-time chat updates — replies
573
- // were persisted but never live-pushed to the UI.
574
- //
575
- // Auth-scoping rules (all four must pass — see #247 design):
576
- // gate 1: token resolves to a valid user context (authCtx non-null)
577
- // gate 2: network scope is explicit — `utok_` has no implicit network,
578
- // so the caller must pass `?network_id=<id>`
579
- // gate 3: user is a member of that network (any role: owner / admin / member)
580
- // gate 4: channel-ownership — one of:
581
- // (a) sessionName === own username (the dashboard's default channel —
582
- // `send_reply` pushes to the original sender's alias which equals
583
- // the dashboard user's username; NO `sessions` row required for
584
- // this branch since the dashboard user is not a registered agent)
585
- // (b) sessionName is an existing agent alias in `scopedNetId`
586
- // (lets members monitor agents within their network)
587
- //
588
- // Security: rule 4(a) uses strict equality, so a `utok_` user cannot subscribe
589
- // to another user's username channel (no cross-user eavesdrop). Rule 4(b) is
590
- // scoped to `scopedNetId` + gate 3 membership, so cross-network eavesdrop is
591
- // blocked too. There is intentionally NO org-admin bypass — even users with
592
- // global `admin` role must be a member of the network they want to listen on.
593
- if (!authCtx) {
594
- return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 403 }));
595
- }
596
- if (!scopedNetId) {
597
- return withCors(req, Response.json({
598
- ok: false,
599
- error: "network_id required (utok has no implicit network; pass ?network_id=<id>)"
600
- }, { status: 403 }));
601
- }
602
- const utokRole = getUserNetworkRole(authCtx.userId, scopedNetId);
603
- if (!utokRole) {
604
- return withCors(req, Response.json({ ok: false, error: "not a member of this network" }, { status: 403 }));
605
- }
606
- if (sessionName === authCtx.username) {
607
- return createSSEStream(sessionName, scopedNetId);
608
- }
609
- const utokSession = db.get<any>(
610
- "SELECT 1 FROM sessions WHERE alias = ?1 AND network_id = ?2",
611
- sessionName, scopedNetId
612
- );
613
- if (!utokSession) {
614
- return withCors(req, Response.json({
615
- ok: false,
616
- error: "channel not allowed: must be your username or an existing agent in your network"
617
- }, { status: 403 }));
618
- }
619
- return createSSEStream(sessionName, scopedNetId);
620
- }
621
-
622
- // ── V3: License endpoints ──
623
- if (url.pathname === "/api/license" && req.method === "GET") {
624
- const license = db.get<any>("SELECT * FROM licenses ORDER BY created_at LIMIT 1");
625
- if (!license) return withCors(req, Response.json({ ok: true, status: "no_license" }));
626
- const now = new Date().toISOString().replace("T", " ").slice(0, 19);
627
- const expired = license.expires_at && license.expires_at < now;
628
- const daysLeft = license.expires_at
629
- ? Math.max(0, Math.ceil((new Date(license.expires_at).getTime() - Date.now()) / 86400000))
630
- : null;
631
- return withCors(req, Response.json({
632
- ok: true,
633
- license: { type: license.type, expires_at: license.expires_at, days_left: daysLeft, expired },
634
- limits: { max_agents: license.max_agents, max_networks: license.max_networks, max_tasks_day: license.max_tasks_day },
635
- }));
636
- }
637
-
638
- if (url.pathname === "/api/license/activate" && req.method === "POST") {
639
- try {
640
- const body = await req.json() as any;
641
- const key = body.key;
642
- if (!key) return withCors(req, Response.json({ ok: false, error: "key required" }, { status: 400 }));
643
- // For now: accept any key starting with "anet-" as valid pro license
644
- if (!key.startsWith("anet-") || key.length < 16) {
645
- return withCors(req, Response.json({ ok: false, error: "invalid license key" }, { status: 400 }));
646
- }
647
- // Upgrade existing license or create new
648
- db.run("DELETE FROM licenses");
649
- const licId = `lic_${crypto.randomUUID().replace(/-/g, "").slice(0, 12)}`;
650
- db.run(
651
- "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'))",
652
- [licId, key]
653
- );
654
- return withCors(req, Response.json({ ok: true, type: "pro", expires_in_days: 365 }));
655
- } catch (e: any) {
656
- return withCors(req, Response.json({ ok: false, error: e.message }, { status: 400 }));
657
- }
658
- }
659
-
660
- // ── V3: Auth endpoints (public) ──
661
- if (url.pathname === "/api/auth/register" && req.method === "POST") {
662
- const clientIP = req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || "unknown";
663
- if (!checkRateLimit(clientIP, 30)) {
664
- return withCors(req, Response.json({ ok: false, error: "too many requests, try again later" }, { status: 429 }));
665
- }
666
- try {
667
- const body = await req.json() as any;
668
- const result = register(body.username, body.password, body.email, body.display_name);
669
- if (result.ok) logAudit(result.user!.user_id, body.username, "register", "user", result.user!.user_id);
670
- return withCors(req, Response.json(result, { status: result.ok ? 200 : 400 }));
671
- } catch (e: any) {
672
- return withCors(req, Response.json({ ok: false, error: e.message }, { status: 400 }));
673
- }
674
- }
675
-
676
- if (url.pathname === "/api/auth/login" && req.method === "POST") {
677
- const clientIP = getLoginClientIp(req);
678
- const ipRate = sharedLoginIpRateLimiter.check(clientIP || "unknown");
679
- if (!ipRate.allowed) {
680
- logAudit(null, null, "login_rate_limited", "auth", undefined, clientIP);
681
- return withCors(req, Response.json(
682
- { ok: false, error: "rate_limited", message: "Too many login attempts. Try again later.", retry_after_ms: ipRate.retryAfterMs },
683
- { status: 429, headers: { "Retry-After": String(Math.ceil((ipRate.retryAfterMs ?? 1000) / 1000)) } }
684
- ));
685
- }
686
- try {
687
- const body = await req.json() as any;
688
- const lock = sharedLoginFailureLockout.check(body.username);
689
- if (lock.locked) {
690
- logAudit(null, body.username, "login_locked", "auth", undefined, `retry_after_ms=${lock.retryAfterMs ?? 0}`);
691
- return withCors(req, Response.json(
692
- { ok: false, error: "login_locked", message: "Too many failed login attempts. Try again later.", retry_after_ms: lock.retryAfterMs },
693
- { status: 429, headers: { "Retry-After": String(Math.ceil((lock.retryAfterMs ?? 1000) / 1000)) } }
694
- ));
695
- }
696
- const result = login(body.username, body.password);
697
- if (result.ok) {
698
- sharedLoginFailureLockout.recordSuccess(body.username);
699
- logAudit(result.user!.user_id, body.username, "login", "user", result.user!.user_id);
700
- } else {
701
- const failure = sharedLoginFailureLockout.recordFailure(body.username);
702
- if (failure.locked) {
703
- const safeUsername = String(body.username ?? "").replace(/[\r\n\t]/g, " ").slice(0, 80);
704
- console.warn(`[auth] login locked for username=${safeUsername} failures=${failure.failures} retry_after_ms=${failure.lockMs}`);
705
- }
706
- logAudit(null, body.username, "login_failed", "user", undefined, "invalid credentials");
707
- }
708
- return withCors(req, Response.json(result, { status: result.ok ? 200 : 401 }));
709
- } catch (e: any) {
710
- return withCors(req, Response.json({ ok: false, error: e.message }, { status: 400 }));
711
- }
712
- }
713
-
714
- if (url.pathname === "/api/auth/me" && req.method === "GET") {
715
- const token = req.headers.get("Authorization")?.replace("Bearer ", "") || url.searchParams.get("token");
716
- if (!token) return withCors(req, Response.json({ ok: false, error: "token required" }, { status: 401 }));
717
- const resolved = resolveToken(token);
718
- if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
719
- const networks = getUserAllNetworks(resolved.user.user_id);
720
- return withCors(req, Response.json({ ok: true, user: resolved.user, networks, current_network: resolved.networkId }));
721
- }
722
-
723
- if (url.pathname === "/api/auth/me" && req.method === "PUT") {
724
- const token = req.headers.get("Authorization")?.replace("Bearer ", "");
725
- if (!token) return withCors(req, Response.json({ ok: false, error: "token required" }, { status: 401 }));
726
- const resolved = resolveToken(token);
727
- if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
728
- try {
729
- const body = await req.json() as any;
730
- const updates: string[] = [];
731
- const params: any[] = [];
732
- if (body.display_name) { updates.push(`display_name = ?${params.length + 1}`); params.push(body.display_name); }
733
- if (body.email) { updates.push(`email = ?${params.length + 1}`); params.push(body.email); }
734
- if (updates.length > 0) {
735
- updates.push(`updated_at = datetime('now')`);
736
- params.push(resolved.user.user_id);
737
- db.run(`UPDATE users SET ${updates.join(", ")} WHERE user_id = ?${params.length}`, params);
738
- }
739
- // Re-fetch
740
- const user = db.get<any>("SELECT user_id, username, display_name, email, role FROM users WHERE user_id = ?1", resolved.user.user_id);
741
- return withCors(req, Response.json({ ok: true, user }));
742
- } catch (e: any) {
743
- return withCors(req, Response.json({ ok: false, error: e.message }, { status: 400 }));
744
- }
745
- }
746
-
747
- if (url.pathname === "/api/auth/password" && req.method === "POST") {
748
- const token = req.headers.get("Authorization")?.replace("Bearer ", "");
749
- if (!token) return withCors(req, Response.json({ ok: false, error: "token required" }, { status: 401 }));
750
- const resolved = resolveToken(token);
751
- if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
752
- try {
753
- const body = await req.json() as any;
754
- const result = changePassword(resolved.user.user_id, body.old_password, body.new_password, resolved.tokenId);
755
- if (result.ok) {
756
- const issued = issueUserToken(resolved.user.user_id, "password-change");
757
- if (resolved.tokenId) revokeToken(resolved.user.user_id, resolved.tokenId);
758
- logAudit(resolved.user.user_id, resolved.user.username, "password_changed", "user", resolved.user.user_id);
759
- return withCors(req, Response.json({ ...result, token: issued.token, token_id: issued.token_id }));
760
- }
761
- return withCors(req, Response.json(result, { status: 400 }));
762
- } catch (e: any) {
763
- return withCors(req, Response.json({ ok: false, error: e.message }, { status: 400 }));
764
- }
765
- }
766
-
767
- // ── V3.13: Create network token for a node ──
768
- if (url.pathname === "/api/auth/node-token" && req.method === "POST") {
769
- const token = req.headers.get("Authorization")?.replace("Bearer ", "");
770
- if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
771
- const resolved = resolveToken(token);
772
- if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
773
- try {
774
- const body = await req.json() as any;
775
- if (!body.network_id || !body.node_name) return withCors(req, Response.json({ ok: false, error: "network_id and node_name required" }, { status: 400 }));
776
- const result = createNetworkTokenForNode(resolved.user.user_id, body.network_id, body.node_name);
777
- if (result.ok) logAudit(resolved.user.user_id, resolved.user.username, "node_token_created", "network", body.network_id, body.node_name);
778
- return withCors(req, Response.json(result, { status: result.ok ? 200 : 400 }));
779
- } catch (e: any) {
780
- return withCors(req, Response.json({ ok: false, error: e.message }, { status: 400 }));
781
- }
782
- }
783
-
784
- // ── #84: node rename 2PC — Server surface (RFC-010 §4) ──
785
- // The CLI orchestrates the 2PC; these endpoints are the Server steps:
786
- // prepare = PHASE 1 P3, commit = PHASE 2 C1, abort = PHASE 1 rollback.
787
- if (url.pathname === "/api/node-rename/prepare" && req.method === "POST") {
788
- const token = req.headers.get("Authorization")?.replace("Bearer ", "");
789
- if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
790
- const resolved = resolveToken(token);
791
- if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
792
- try {
793
- const body = await req.json() as any;
794
- if (!body.network_id || !body.old_alias || !body.new_alias) {
795
- return withCors(req, Response.json({ ok: false, error: "network_id, old_alias, new_alias required" }, { status: 400 }));
796
- }
797
- const result = prepareRename(resolved.user.user_id, body.network_id, body.old_alias, body.new_alias);
798
- if (result.ok) logAudit(resolved.user.user_id, resolved.user.username, "node_rename_prepared", "node", body.old_alias, body.new_alias);
799
- return withCors(req, Response.json(result, { status: result.ok || result.code === "node_local_only" ? 200 : 400 }));
800
- } catch (e: any) {
801
- return withCors(req, Response.json({ ok: false, error: e.message }, { status: 400 }));
802
- }
803
- }
804
-
805
- if (url.pathname === "/api/node-rename/commit" && req.method === "POST") {
806
- const token = req.headers.get("Authorization")?.replace("Bearer ", "");
807
- if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
808
- const resolved = resolveToken(token);
809
- if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
810
- try {
811
- const body = await req.json() as any;
812
- if (!body.txn_id) return withCors(req, Response.json({ ok: false, error: "txn_id required" }, { status: 400 }));
813
- const result = commitRename(resolved.user.user_id, body.txn_id);
814
- if (result.ok) logAudit(resolved.user.user_id, resolved.user.username, "node_rename_committed", "node", body.txn_id);
815
- return withCors(req, Response.json(result, { status: result.ok ? 200 : 400 }));
816
- } catch (e: any) {
817
- return withCors(req, Response.json({ ok: false, error: e.message }, { status: 400 }));
818
- }
819
- }
820
-
821
- if (url.pathname === "/api/node-rename/abort" && req.method === "POST") {
822
- const token = req.headers.get("Authorization")?.replace("Bearer ", "");
823
- if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
824
- const resolved = resolveToken(token);
825
- if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
826
- try {
827
- const body = await req.json() as any;
828
- if (!body.txn_id) return withCors(req, Response.json({ ok: false, error: "txn_id required" }, { status: 400 }));
829
- const result = abortRename(resolved.user.user_id, body.txn_id);
830
- if (result.ok) logAudit(resolved.user.user_id, resolved.user.username, "node_rename_aborted", "node", body.txn_id);
831
- return withCors(req, Response.json(result, { status: result.ok ? 200 : 400 }));
832
- } catch (e: any) {
833
- return withCors(req, Response.json({ ok: false, error: e.message }, { status: 400 }));
834
- }
835
- }
836
-
837
- // ── V3: Token management ──
838
- if (url.pathname === "/api/auth/tokens" && req.method === "GET") {
839
- const token = req.headers.get("Authorization")?.replace("Bearer ", "");
840
- if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
841
- const resolved = resolveToken(token);
842
- if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
843
- const tokens = listTokens(resolved.user.user_id);
844
- return withCors(req, Response.json({ ok: true, tokens }));
845
- }
846
-
847
- if (url.pathname === "/api/auth/tokens" && req.method === "POST") {
848
- const token = req.headers.get("Authorization")?.replace("Bearer ", "");
849
- if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
850
- const resolved = resolveToken(token);
851
- if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
852
- try {
853
- const body = await req.json() as any;
854
- const result = createToken(resolved.user.user_id, body.name || "api-token", body.network_id);
855
- if (result.ok) logAudit(resolved.user.user_id, resolved.user.username, "token_created", "token", result.token_id);
856
- return withCors(req, Response.json(result));
857
- } catch (e: any) {
858
- return withCors(req, Response.json({ ok: false, error: e.message }, { status: 400 }));
859
- }
860
- }
861
-
862
- const tokenDeleteMatch = url.pathname.match(/^\/api\/auth\/tokens\/([^/]+)$/);
863
- if (tokenDeleteMatch && req.method === "DELETE") {
864
- const token = req.headers.get("Authorization")?.replace("Bearer ", "");
865
- if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
866
- const resolved = resolveToken(token);
867
- if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
868
- const result = revokeToken(resolved.user.user_id, tokenDeleteMatch[1]);
869
- if (result.ok) logAudit(resolved.user.user_id, resolved.user.username, "token_revoked", "token", tokenDeleteMatch[1]);
870
- return withCors(req, Response.json(result, { status: result.ok ? 200 : 404 }));
871
- }
872
-
873
- // ── V3: Network management ──
874
- if (url.pathname === "/api/networks" && req.method === "GET") {
875
- const token = req.headers.get("Authorization")?.replace("Bearer ", "") || url.searchParams.get("token");
876
- if (!token) return withCors(req, Response.json({ ok: false, error: "token required" }, { status: 401 }));
877
- const resolved = resolveToken(token);
878
- if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
879
- // V3.13: ntok_ can only see its bound network; utok_ sees all member networks
880
- if (resolved.networkId) {
881
- // ntok_ — only return the bound network
882
- const net = db.get<any>("SELECT * FROM networks WHERE network_id = ?1", resolved.networkId);
883
- return withCors(req, Response.json({ ok: true, networks: net ? [net] : [] }));
884
- }
885
- const networks = getUserAllNetworks(resolved.user.user_id);
886
- return withCors(req, Response.json({ ok: true, networks }));
887
- }
888
-
889
- if (url.pathname === "/api/networks" && req.method === "POST") {
890
- const token = req.headers.get("Authorization")?.replace("Bearer ", "") || url.searchParams.get("token");
891
- if (!token) return withCors(req, Response.json({ ok: false, error: "token required" }, { status: 401 }));
892
- const resolved = resolveToken(token);
893
- if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
894
- try {
895
- const body = await req.json() as any;
896
- const result = createNetwork(resolved.user.user_id, body.name, body.description);
897
- return withCors(req, Response.json(result, { status: result.ok ? 200 : 400 }));
898
- } catch (e: any) {
899
- return withCors(req, Response.json({ ok: false, error: e.message }, { status: 400 }));
900
- }
901
- }
902
-
903
- // ── V3.13: Network members + invites ──
904
- const membersMatch = url.pathname.match(/^\/api\/networks\/([^/]+)\/members(?:\/([^/]+))?$/);
905
- if (membersMatch) {
906
- const token = req.headers.get("Authorization")?.replace("Bearer ", "") || url.searchParams.get("token");
907
- if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
908
- const resolved = resolveToken(token);
909
- if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
910
- const netId = membersMatch[1];
911
- const targetUid = membersMatch[2];
912
- const callerRole = getUserNetworkRole(resolved.user.user_id, netId);
913
- if (!callerRole) return withCors(req, Response.json({ ok: false, error: "not a member of this network" }, { status: 403 }));
914
-
915
- if (req.method === "GET") {
916
- if (!["owner", "admin"].includes(callerRole)) return withCors(req, Response.json({ ok: false, error: "owner/admin required" }, { status: 403 }));
917
- const members = getNetworkMembers(netId);
918
- return withCors(req, Response.json({ ok: true, members }));
919
- }
920
- if (req.method === "POST") {
921
- if (!["owner", "admin"].includes(callerRole)) return withCors(req, Response.json({ ok: false, error: "owner/admin required" }, { status: 403 }));
922
- const body = await req.json() as any;
923
- const result = addNetworkMember(netId, body.user_id, body.role || "member", resolved.user.user_id);
924
- if (result.ok) logAudit(resolved.user.user_id, resolved.user.username, "member_added", "network", netId, `${body.user_id} as ${body.role || "member"}`);
925
- return withCors(req, Response.json(result, { status: result.ok ? 200 : 400 }));
926
- }
927
- if (req.method === "PUT" && targetUid) {
928
- if (callerRole !== "owner") return withCors(req, Response.json({ ok: false, error: "owner required" }, { status: 403 }));
929
- const body = await req.json() as any;
930
- const result = updateMemberRole(netId, targetUid, body.role);
931
- if (result.ok) logAudit(resolved.user.user_id, resolved.user.username, "member_role_changed", "network", netId, `${targetUid} → ${body.role}`);
932
- return withCors(req, Response.json(result, { status: result.ok ? 200 : 400 }));
933
- }
934
- if (req.method === "DELETE" && targetUid) {
935
- if (!["owner", "admin"].includes(callerRole)) return withCors(req, Response.json({ ok: false, error: "owner/admin required" }, { status: 403 }));
936
- const result = removeNetworkMember(netId, targetUid);
937
- if (result.ok) logAudit(resolved.user.user_id, resolved.user.username, "member_removed", "network", netId, targetUid);
938
- return withCors(req, Response.json(result, { status: result.ok ? 200 : 400 }));
939
- }
940
- }
941
-
942
- if (url.pathname.match(/^\/api\/networks\/([^/]+)\/invite$/) && req.method === "POST") {
943
- const token = req.headers.get("Authorization")?.replace("Bearer ", "") || url.searchParams.get("token");
944
- if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
945
- const resolved = resolveToken(token);
946
- if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
947
- const netId = url.pathname.split("/")[3];
948
- const callerRole = getUserNetworkRole(resolved.user.user_id, netId);
949
- if (!callerRole || !["owner", "admin"].includes(callerRole)) {
950
- return withCors(req, Response.json({ ok: false, error: "owner/admin required" }, { status: 403 }));
951
- }
952
- const body = await req.json() as any;
953
- const result = createInvite(netId, resolved.user.user_id, body.role || "member", body.max_uses || 1, body.expires_days);
954
- if (result.ok) logAudit(resolved.user.user_id, resolved.user.username, "invite_created", "network", netId, result.invite_code);
955
- return withCors(req, Response.json(result));
956
- }
957
-
958
- if (url.pathname === "/api/networks/join" && req.method === "POST") {
959
- const token = req.headers.get("Authorization")?.replace("Bearer ", "") || url.searchParams.get("token");
960
- if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
961
- const resolved = resolveToken(token);
962
- if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
963
- const body = await req.json() as any;
964
- const result = joinByInvite(body.invite_code, resolved.user.user_id);
965
- if (result.ok) logAudit(resolved.user.user_id, resolved.user.username, "network_joined", "network", result.network_id, `via invite, role=${result.role}`);
966
- return withCors(req, Response.json(result, { status: result.ok ? 200 : 400 }));
967
- }
968
-
969
- // ── V3: Admin APIs (require auth) ──
970
- if (url.pathname === "/api/users" && req.method === "GET") {
971
- const token = req.headers.get("Authorization")?.replace("Bearer ", "");
972
- if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
973
- const resolved = resolveToken(token);
974
- if (!resolved || resolved.user.role !== "admin") {
975
- return withCors(req, Response.json({ ok: false, error: "admin required" }, { status: 403 }));
976
- }
977
- const users = db.all("SELECT user_id, username, display_name, email, role, created_at FROM users ORDER BY created_at");
978
- return withCors(req, Response.json({ ok: true, users }));
979
- }
980
-
981
- const netDetailMatch = url.pathname.match(/^\/api\/networks\/([^/]+)$/);
982
- if (netDetailMatch && req.method === "GET") {
983
- const token = req.headers.get("Authorization")?.replace("Bearer ", "") || url.searchParams.get("token");
984
- if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
985
- const resolved = resolveToken(token);
986
- if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
987
- const networkId = netDetailMatch[1];
988
- const network = db.get<any>("SELECT * FROM networks WHERE network_id = ?1", networkId);
989
- if (!network) return withCors(req, Response.json({ ok: false, error: "network not found" }, { status: 404 }));
990
- // Membership check: must be a member or system admin
991
- const viewerRole = getUserNetworkRole(resolved.user.user_id, networkId);
992
- if (!viewerRole && resolved.user.role !== "admin") {
993
- return withCors(req, Response.json({ ok: false, error: "access denied" }, { status: 403 }));
994
- }
995
- // Get network stats
996
- const nodeCount = db.get<{ cnt: number }>("SELECT COUNT(*) as cnt FROM nodes WHERE network_id = ?1", networkId);
997
- const sessionCount = db.get<{ cnt: number }>("SELECT COUNT(*) as cnt FROM sessions WHERE network_id = ?1", networkId);
998
- const taskStats = db.all<any>("SELECT status, COUNT(*) as count FROM tasks WHERE network_id = ?1 GROUP BY status", networkId);
999
- return withCors(req, Response.json({
1000
- ok: true, network,
1001
- stats: { nodes: nodeCount?.cnt || 0, sessions: sessionCount?.cnt || 0, tasks: taskStats },
1002
- }));
1003
- }
1004
-
1005
- if (netDetailMatch && req.method === "DELETE") {
1006
- const token = req.headers.get("Authorization")?.replace("Bearer ", "") || url.searchParams.get("token");
1007
- if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
1008
- const resolved = resolveToken(token);
1009
- if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
1010
- const result = deleteNetwork(resolved.user.user_id, netDetailMatch[1]);
1011
- if (result.ok) logAudit(resolved.user.user_id, resolved.user.username, "network_deleted", "network", netDetailMatch[1]);
1012
- return withCors(req, Response.json(result, { status: result.ok ? 200 : 400 }));
1013
- }
1014
-
1015
- if (netDetailMatch && req.method === "PUT") {
1016
- const token = req.headers.get("Authorization")?.replace("Bearer ", "") || url.searchParams.get("token");
1017
- if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
1018
- const resolved = resolveToken(token);
1019
- if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
1020
- try {
1021
- const body = await req.json() as any;
1022
- if (body.name) {
1023
- const result = renameNetwork(resolved.user.user_id, netDetailMatch[1], body.name);
1024
- if (result.ok) logAudit(resolved.user.user_id, resolved.user.username, "network_renamed", "network", netDetailMatch[1], body.name);
1025
- return withCors(req, Response.json(result, { status: result.ok ? 200 : 400 }));
1026
- }
1027
- return withCors(req, Response.json({ ok: false, error: "name required" }, { status: 400 }));
1028
- } catch (e: any) {
1029
- return withCors(req, Response.json({ ok: false, error: e.message }, { status: 400 }));
1030
- }
1031
- }
1032
-
1033
- // ── REST: health (public, no auth) ──
1034
- if (url.pathname === "/health") {
1035
- const count = db.get<{ cnt: number }>("SELECT COUNT(*) as cnt FROM sessions");
1036
- const sse = getSSEStats();
1037
- const license = db.get<any>("SELECT type, expires_at FROM licenses LIMIT 1");
1038
- return withCors(req, Response.json({
1039
- ok: true,
1040
- version: SERVER_VERSION,
1041
- api_version: "v3",
1042
- transport: "streamable-http",
1043
- sessions_count: count?.cnt ?? 0,
1044
- sse_connections: sse.total,
1045
- sse_sessions: sse.sessions,
1046
- auth: DEV_OPEN ? "dev-open" : "user-token",
1047
- security: DEV_OPEN ? "dev-open" : "secured",
1048
- tmux: TMUX_ENABLED ? "enabled" : "disabled",
1049
- v3_auth: true,
1050
- multi_network: true,
1051
- license: license?.type || "none",
1052
- uptime: Math.floor(process.uptime()),
1053
- }));
1054
- }
1055
-
1056
- // ── All REST /api endpoints require auth (if token configured) ──
1057
- const authErr = requireAuth(req);
1058
- if (authErr) return withCors(req, authErr);
1059
-
1060
- // Resolve network scope for REST queries — enforce isolation
1061
- // Token-bound networkId takes precedence (ntok_ → forced), then query param
1062
- const restAuth = resolveRequestAuth(req);
1063
- const isAdmin = !!(restAuth?.username && db.get<any>("SELECT role FROM users WHERE username = ?1", restAuth.username)?.role === "admin");
1064
- const restScope = resolveRestNetworkScope(url, restAuth, isAdmin);
1065
- if (restScope.denied) {
1066
- return withCors(req, Response.json({ ok: false, error: restScope.denied }, { status: 403 }));
1067
- }
1068
-
1069
- // ── REST: all sessions status ──
1070
- if (url.pathname === "/api/status") {
1071
- // Round-2/4 review ③: stale-marking moved to startStaleSessionSweeper()
1072
- // (background timer, ~60s cadence). Read paths no longer fire UPDATE.
1073
- // Per-request UPDATE was a write-amp vector — see stale-sweeper.ts.
1074
- cleanupCommittedRenameSessions(restScope.networkId ? [restScope.networkId] : restScope.networkIds ?? null);
1075
- // `?light=1` returns a narrow projection (alias / status / agent / task /
1076
- // server / updated_at + runtime + network_id) — used by the mobile APP
1077
- // list view, where pulling 30+ fields × 150 agents was making cold open
1078
- // take 12s+ on flaky cellular (Vincent tg, #220 PWA). Default response
1079
- // is unchanged so the dashboard / scripts that read full telemetry are
1080
- // unaffected.
1081
- const isLight = url.searchParams.get("light") === "1";
1082
- const params: any[] = [];
1083
- let sql = isLight
1084
- ? "SELECT alias, status, agent, task, server, updated_at, network_id FROM sessions WHERE 1=1"
1085
- : "SELECT * FROM sessions WHERE 1=1";
1086
- sql = addNetworkScope(sql, params, restScope);
1087
- sql += " ORDER BY updated_at DESC";
1088
- // `model` comes straight from the sessions row (SELECT *); `runtime` is
1089
- // derived from the raw `agent` field. Both default to null for old nodes
1090
- // that never reported a model — the dashboard falls back to a placeholder.
1091
- const sessions = db.all(sql, ...params).map((s: any) => {
1092
- if (isLight) {
1093
- return {
1094
- alias: s.alias,
1095
- status: s.status,
1096
- agent: s.agent ?? null,
1097
- task: s.task ?? null,
1098
- server: s.server ?? null,
1099
- updated_at: s.updated_at ?? null,
1100
- runtime: normalizeRuntime(s.agent),
1101
- network_id: s.network_id ?? null,
1102
- };
1103
- }
1104
- return {
1105
- ...s,
1106
- model: s.model ?? null,
1107
- runtime: normalizeRuntime(s.agent),
1108
- host: {
1109
- hostname: s.hostname ?? null,
1110
- ip: s.ip ?? null,
1111
- cpu_load_1min: s.cpu_load_1min ?? null,
1112
- cpu_cores: s.cpu_cores ?? null,
1113
- mem_total_gb: s.mem_total_gb ?? null,
1114
- mem_used_gb: s.mem_used_gb ?? null,
1115
- mem_avail_gb: s.mem_avail_gb ?? null,
1116
- disk_total_gb: s.disk_total_gb ?? null,
1117
- disk_used_gb: s.disk_used_gb ?? null,
1118
- disk_avail_gb: s.disk_avail_gb ?? null,
1119
- },
1120
- process_telemetry: {
1121
- rss_bytes: s.process_rss_bytes ?? null,
1122
- rss_mb: s.process_rss_mb ?? null,
1123
- cpu_pct: s.process_cpu_pct ?? null,
1124
- uptime_seconds: s.process_uptime_seconds ?? null,
1125
- in_flight_count: s.process_in_flight_count ?? null,
1126
- },
1127
- };
1128
- });
1129
- const summary = sessions.reduce((acc: any, session: any) => {
1130
- const raw = String(session.status || "").toLowerCase();
1131
- if (raw === "offline") acc.offline++;
1132
- else if (["working", "blocked", "error", "waiting_input", "running", "busy"].includes(raw)) acc.working++;
1133
- else acc.idle++;
1134
- return acc;
1135
- }, { idle: 0, working: 0, offline: 0, total: sessions.length });
1136
- return withCors(req, Response.json({ ok: true, sessions, summary }));
1137
- }
1138
-
1139
- // ── REST: aggregate agents by physical server ──
1140
- if (url.pathname === "/api/servers") {
1141
- // Round-2/4 review ③: stale-marking moved to background sweeper.
1142
- const params: any[] = [];
1143
- let sql = `
1144
- SELECT hostname, ip, cpu_load_1min, cpu_cores, mem_avail_gb, mem_used_gb,
1145
- COALESCE(last_seen_at, updated_at) AS last_seen
1146
- FROM sessions
1147
- WHERE 1=1
1148
- `;
1149
- sql = addNetworkScope(sql, params, restScope);
1150
- sql += " ORDER BY COALESCE(last_seen_at, updated_at) DESC";
1151
-
1152
- const grouped = new Map<string, {
1153
- hostname: string;
1154
- ip: string;
1155
- agent_count: number;
1156
- cpu_load_1min: number | null;
1157
- cpu_cores: number | null;
1158
- mem_avail_gb: number | null;
1159
- mem_used_gb: number | null;
1160
- last_seen: string | null;
1161
- }>();
1162
-
1163
- const preferDisplayIp = (current: string, next: string) => {
1164
- const isWeak = (ip: string) => !ip || ip === "unknown" || ip === "127.0.0.1" || ip === "::1";
1165
- if (isWeak(current) && !isWeak(next)) return next;
1166
- return current;
1167
- };
1168
- const hasHostTelemetry = (row: any) =>
1169
- row.cpu_load_1min != null || row.cpu_cores != null || row.mem_avail_gb != null || row.mem_used_gb != null;
1170
-
1171
- for (const row of db.all<any>(sql, ...params)) {
1172
- const hostname = row.hostname || "unknown";
1173
- const ip = row.ip || "unknown";
1174
- // Group primarily by hostname. A single host can report both a
1175
- // routable/container IP and loopback (127.0.0.1); splitting those
1176
- // into separate cards makes the dashboard show one useful load row
1177
- // plus one "n/a" duplicate. Unknown hostnames still fall back to IP.
1178
- const key = hostname !== "unknown" ? `host:${hostname}` : `ip:${ip}`;
1179
- const existing = grouped.get(key);
1180
- if (existing) {
1181
- existing.agent_count += 1;
1182
- existing.ip = preferDisplayIp(existing.ip, ip);
1183
- if (parseSqliteTime(row.last_seen) > parseSqliteTime(existing.last_seen)) existing.last_seen = row.last_seen ?? existing.last_seen;
1184
- if (hasHostTelemetry(row) && (
1185
- existing.cpu_load_1min == null ||
1186
- existing.cpu_cores == null ||
1187
- existing.mem_avail_gb == null ||
1188
- existing.mem_used_gb == null
1189
- )) {
1190
- existing.cpu_load_1min = row.cpu_load_1min ?? existing.cpu_load_1min;
1191
- existing.cpu_cores = row.cpu_cores ?? existing.cpu_cores;
1192
- existing.mem_avail_gb = row.mem_avail_gb ?? existing.mem_avail_gb;
1193
- existing.mem_used_gb = row.mem_used_gb ?? existing.mem_used_gb;
1194
- }
1195
- continue;
1196
- }
1197
- grouped.set(key, {
1198
- hostname,
1199
- ip,
1200
- agent_count: 1,
1201
- cpu_load_1min: row.cpu_load_1min ?? null,
1202
- cpu_cores: row.cpu_cores ?? null,
1203
- mem_avail_gb: row.mem_avail_gb ?? null,
1204
- mem_used_gb: row.mem_used_gb ?? null,
1205
- last_seen: row.last_seen ?? null,
1206
- });
1207
- }
1208
-
1209
- return withCors(req, Response.json(Array.from(grouped.values())));
1210
- }
1211
-
1212
- const serverDetailMatch = url.pathname.match(/^\/api\/server\/([^/]+)\/(health|agents)$/);
1213
- if (serverDetailMatch && req.method === "GET") {
1214
- const host = decodeURIComponent(serverDetailMatch[1]);
1215
- const detailKind = serverDetailMatch[2];
1216
- if (!host) return withCors(req, Response.json({ ok: false, error: "host required" }, { status: 400 }));
1217
-
1218
- // Round-2/4 review ③: stale-marking moved to background sweeper.
1219
- if (detailKind === "agents") {
1220
- const params: any[] = [host, host];
1221
- let sql = `
1222
- SELECT alias, agent, status, task, progress, model, hostname, ip,
1223
- cpu_load_1min, cpu_cores, mem_avail_gb, mem_used_gb, mem_total_gb,
1224
- disk_avail_gb, disk_used_gb, disk_total_gb,
1225
- process_rss_bytes, process_rss_mb, process_cpu_pct, process_uptime_seconds, process_in_flight_count,
1226
- COALESCE(last_seen_at, updated_at) AS last_seen
1227
- FROM sessions
1228
- WHERE (hostname = ?1 OR ip = ?2)
1229
- `;
1230
- sql = addNetworkScope(sql, params, restScope);
1231
- sql += " ORDER BY alias";
1232
- const agents = db.all<any>(sql, ...params).map((s) => ({
1233
- alias: s.alias,
1234
- runtime: normalizeRuntime(s.agent),
1235
- raw_agent: s.agent ?? null,
1236
- model: s.model ?? null,
1237
- status: s.status ?? "offline",
1238
- task: s.task ?? null,
1239
- progress: s.progress ?? 0,
1240
- last_seen: s.last_seen ?? null,
1241
- health: agentHealthChip(s.status, s.last_seen),
1242
- hostname: s.hostname ?? null,
1243
- ip: s.ip ?? null,
1244
- telemetry: {
1245
- cpu_load_1min: s.cpu_load_1min ?? null,
1246
- cpu_cores: s.cpu_cores ?? null,
1247
- cpu_pct: cpuPct(s.cpu_load_1min, s.cpu_cores),
1248
- mem_total_gb: s.mem_total_gb ?? null,
1249
- mem_used_gb: s.mem_used_gb ?? null,
1250
- mem_avail_gb: s.mem_avail_gb ?? null,
1251
- disk_total_gb: s.disk_total_gb ?? null,
1252
- disk_used_gb: s.disk_used_gb ?? null,
1253
- disk_avail_gb: s.disk_avail_gb ?? null,
1254
- process_rss_bytes: s.process_rss_bytes ?? null,
1255
- process_rss_mb: s.process_rss_mb ?? null,
1256
- process_cpu_pct: s.process_cpu_pct ?? null,
1257
- process_uptime_seconds: s.process_uptime_seconds ?? null,
1258
- process_in_flight_count: s.process_in_flight_count ?? null,
1259
- },
1260
- process_telemetry: {
1261
- rss_bytes: s.process_rss_bytes ?? null,
1262
- rss_mb: s.process_rss_mb ?? null,
1263
- cpu_pct: s.process_cpu_pct ?? null,
1264
- uptime_seconds: s.process_uptime_seconds ?? null,
1265
- in_flight_count: s.process_in_flight_count ?? null,
1266
- },
1267
- }));
1268
- if (agents.length === 0) return withCors(req, Response.json({ ok: false, error: "server not found" }, { status: 404 }));
1269
- return withCors(req, Response.json({ ok: true, host, agent_count: agents.length, agents }));
1270
- }
1271
-
1272
- const latestParams: any[] = [host, host];
1273
- let latestSql = `
1274
- SELECT hostname, ip, COUNT(*) OVER () AS agent_count,
1275
- cpu_load_1min, cpu_cores, mem_total_gb, mem_used_gb, mem_avail_gb,
1276
- disk_total_gb, disk_used_gb, disk_avail_gb,
1277
- COALESCE(last_seen_at, updated_at) AS last_seen
1278
- FROM sessions
1279
- WHERE (hostname = ?1 OR ip = ?2)
1280
- `;
1281
- latestSql = addNetworkScope(latestSql, latestParams, restScope);
1282
- latestSql += " ORDER BY COALESCE(last_seen_at, updated_at) DESC LIMIT 1";
1283
- const latest = db.get<any>(latestSql, ...latestParams);
1284
- if (!latest) return withCors(req, Response.json({ ok: false, error: "server not found" }, { status: 404 }));
1285
-
1286
- const since24h = sqliteTime(new Date(Date.now() - 24 * 60 * 60 * 1000));
1287
- const histParams: any[] = [host, host, since24h];
1288
- let histSql = `
1289
- SELECT created_at, cpu_load_1min, cpu_cores, mem_total_gb, mem_used_gb, mem_avail_gb,
1290
- disk_total_gb, disk_used_gb, disk_avail_gb
1291
- FROM agent_telemetry
1292
- WHERE (hostname = ?1 OR ip = ?2) AND created_at >= ?3
1293
- `;
1294
- histSql = addNetworkScope(histSql, histParams, restScope);
1295
- histSql += " ORDER BY created_at ASC";
1296
- const historyRows = db.all<any>(histSql, ...histParams);
1297
- const now = Date.now();
1298
- const alert = serverAlertLevel(latest);
1299
-
1300
- return withCors(req, Response.json({
1301
- ok: true,
1302
- host,
1303
- hostname: latest.hostname ?? null,
1304
- ip: latest.ip ?? null,
1305
- agent_count: latest.agent_count ?? 0,
1306
- alert_level: alert.level,
1307
- alerts: alert.alerts,
1308
- latest: {
1309
- cpu_load_1min: latest.cpu_load_1min ?? null,
1310
- cpu_cores: latest.cpu_cores ?? null,
1311
- cpu_pct: cpuPct(latest.cpu_load_1min, latest.cpu_cores),
1312
- mem_total_gb: latest.mem_total_gb ?? null,
1313
- mem_used_gb: latest.mem_used_gb ?? null,
1314
- mem_avail_gb: latest.mem_avail_gb ?? null,
1315
- disk_total_gb: latest.disk_total_gb ?? null,
1316
- disk_used_gb: latest.disk_used_gb ?? null,
1317
- disk_avail_gb: latest.disk_avail_gb ?? null,
1318
- last_seen: latest.last_seen ?? null,
1319
- },
1320
- history: {
1321
- "5m": bucketTelemetry(historyRows, now - 5 * 60 * 1000, 60 * 1000),
1322
- "1h": bucketTelemetry(historyRows, now - 60 * 60 * 1000, 5 * 60 * 1000),
1323
- "24h": bucketTelemetry(historyRows, now - 24 * 60 * 60 * 1000, 60 * 60 * 1000),
1324
- },
1325
- }));
1326
- }
1327
-
1328
- // ── REST: file upload (#221) ──
1329
- // POST multipart/form-data with a single `file` field. Bearer auth.
1330
- // 12 MiB cap (two-stage: Content-Length pre-check + post-parse size
1331
- // verify). Returns { ok, file_id, path, url, size, mime }. The
1332
- // file_id is server-generated (crypto.randomUUID with hyphens
1333
- // stripped) so a client-supplied filename never enters the storage
1334
- // path. The download URL `/api/files/<file_id>` requires the same
1335
- // Bearer auth and forces Content-Disposition: attachment +
1336
- // X-Content-Type-Options: nosniff so uploaded files can never be
1337
- // executed or served as HTML.
1338
- if (url.pathname === "/api/upload" && req.method === "POST") {
1339
- const authErr = requireAuth(req);
1340
- if (authErr) return withCors(req, authErr);
1341
-
1342
- // Rate-limit key prefers the token id (so 60/h is per-token, not
1343
- // per-IP); falls back to IP for legacy or anonymous-but-dev-open.
1344
- const authCtx = resolveRequestAuth(req);
1345
- const rateKey = authCtx?.tokenId ?? `ip:${getClientIP(req, server)}`;
1346
- const rate = sharedUploadRateLimiter.check(rateKey);
1347
- if (!rate.allowed) {
1348
- const headers: Record<string, string> = {
1349
- "X-RateLimit-Limit": String(60),
1350
- "X-RateLimit-Remaining": "0",
1351
- "X-RateLimit-Reset": String(Math.floor(rate.resetAt / 1000)),
1352
- };
1353
- if (rate.retryAfterMs) headers["Retry-After"] = String(Math.ceil(rate.retryAfterMs / 1000));
1354
- return withCors(req, new Response(
1355
- JSON.stringify({ ok: false, error: "rate_limited", message: "Upload rate limit exceeded (60/hour). Try again later.", retry_after_ms: rate.retryAfterMs }),
1356
- { status: 429, headers: { ...headers, "Content-Type": "application/json" } },
1357
- ));
1358
- }
1359
-
1360
- // Two-stage size cap per 通信龙 dispatch c38de7a9:
1361
- // stage 1 — reject before reading body when Content-Length
1362
- // exceeds the cap (saves bandwidth, fails fast)
1363
- // stage 2 — re-verify the parsed File.size after Bun has parsed
1364
- // the multipart envelope (defends against a missing
1365
- // or lied Content-Length header)
1366
- const contentLength = req.headers.get("Content-Length");
1367
- if (!contentLength) {
1368
- return withCors(req, Response.json(
1369
- { ok: false, error: "length_required", message: "Content-Length header is required for /api/upload" },
1370
- { status: 411 },
1371
- ));
1372
- }
1373
- const declaredBytes = Number(contentLength);
1374
- if (!Number.isFinite(declaredBytes) || declaredBytes < 0) {
1375
- return withCors(req, Response.json({ ok: false, error: "bad_content_length" }, { status: 400 }));
1376
- }
1377
- if (declaredBytes > MAX_REQUEST_CONTENT_LENGTH) {
1378
- return withCors(req, Response.json(
1379
- { ok: false, error: "payload_too_large", message: `Upload exceeds the ${MAX_UPLOAD_BYTES} byte limit`, limit_bytes: MAX_UPLOAD_BYTES },
1380
- { status: 413 },
1381
- ));
1382
- }
1383
-
1384
- const contentType = req.headers.get("Content-Type") ?? "";
1385
- if (!/^multipart\/form-data/i.test(contentType)) {
1386
- return withCors(req, Response.json(
1387
- { ok: false, error: "unsupported_media_type", message: "Use multipart/form-data with a 'file' field" },
1388
- { status: 415 },
1389
- ));
1390
- }
1391
-
1392
- let form: FormData;
1393
- try {
1394
- form = await req.formData();
1395
- } catch (e: any) {
1396
- return withCors(req, Response.json(
1397
- { ok: false, error: "multipart_parse_failed", message: e?.message?.slice(0, 200) ?? "multipart parse failed" },
1398
- { status: 400 },
1399
- ));
1400
- }
1401
- const file = form.get("file");
1402
- if (!file || typeof file === "string") {
1403
- return withCors(req, Response.json(
1404
- { ok: false, error: "missing_file", message: "Expected a 'file' field with binary content" },
1405
- { status: 400 },
1406
- ));
1407
- }
1408
-
1409
- // Stage 2 — re-verify parsed size against the documented cap.
1410
- if (file.size > MAX_UPLOAD_BYTES) {
1411
- return withCors(req, Response.json(
1412
- { ok: false, error: "payload_too_large", message: `Upload exceeds the ${MAX_UPLOAD_BYTES} byte limit`, limit_bytes: MAX_UPLOAD_BYTES, observed_bytes: file.size },
1413
- { status: 413 },
1414
- ));
1415
- }
1416
-
1417
- const fileId = generateFileId();
1418
- const ext = sanitizeExt(file.name);
1419
- let storage;
1420
- try {
1421
- storage = buildStoragePath(fileId, ext);
1422
- } catch (e: any) {
1423
- // Should be unreachable — we generated the id ourselves — but
1424
- // surface as 500 if our own primitives reject our own input.
1425
- console.error("[/api/upload] buildStoragePath rejected:", e?.message);
1426
- return withCors(req, Response.json({ ok: false, error: "internal_path_error" }, { status: 500 }));
1427
- }
1428
-
1429
- try {
1430
- mkdirSync(pathDirname(storage.absolutePath), { recursive: true });
1431
- const buf = Buffer.from(await file.arrayBuffer());
1432
- writeFileSync(storage.absolutePath, buf);
1433
- // Defense-in-depth: after writing, confirm the path still sits
1434
- // inside the uploads root (catches a symlink swap or root env
1435
- // poisoning across processes).
1436
- if (!isPathInsideUploadsRoot(storage.absolutePath)) {
1437
- // Refuse to acknowledge a write that landed outside the root.
1438
- // Don't try to clean up — better to keep evidence on disk than
1439
- // chase a symlink for cleanup.
1440
- console.error("[/api/upload] write escaped uploads root:", storage.absolutePath);
1441
- return withCors(req, Response.json({ ok: false, error: "internal_path_escape" }, { status: 500 }));
1442
- }
1443
-
1444
- // Persist the index entry so /api/files/<file_id> can do an
1445
- // O(1) lookup without scanning every date bucket.
1446
- const idxPath = indexEntryPath(fileId);
1447
- if (idxPath) {
1448
- mkdirSync(pathDirname(idxPath), { recursive: true });
1449
- writeFileSync(idxPath, JSON.stringify({
1450
- file_id: fileId,
1451
- date_bucket: storage.dateBucket,
1452
- ext: storage.ext,
1453
- name: typeof file.name === "string" ? file.name.slice(0, 255) : "",
1454
- mime: typeof file.type === "string" ? file.type.slice(0, 100) : "application/octet-stream",
1455
- size: file.size,
1456
- owner: authCtx?.username ?? null,
1457
- owner_id: authCtx?.userId ?? null,
1458
- uploaded_at: new Date().toISOString(),
1459
- }, null, 2));
1460
- }
1461
- } catch (e: any) {
1462
- console.error("[/api/upload] write failed:", e?.message);
1463
- return withCors(req, Response.json({ ok: false, error: "write_failed", message: e?.message?.slice(0, 200) ?? "write failed" }, { status: 500 }));
1464
- }
1465
-
1466
- return withCors(req, Response.json({
1467
- ok: true,
1468
- file_id: fileId,
1469
- path: storage.absolutePath,
1470
- url: `/api/files/${fileId}`,
1471
- size: file.size,
1472
- mime: typeof file.type === "string" ? file.type : "application/octet-stream",
1473
- }));
1474
- }
1475
-
1476
- // ── REST: file download (#221) ──
1477
- // GET /api/files/:file_id with Bearer auth. Always forces
1478
- // Content-Disposition: attachment + X-Content-Type-Options: nosniff
1479
- // so the served file can never be executed or rendered as HTML.
1480
- // The file_id is validated against the same strict regex used at
1481
- // generation time before any filesystem access.
1482
- const fileMatch = url.pathname.match(/^\/api\/files\/(.+)$/);
1483
- if (fileMatch && req.method === "GET") {
1484
- const authErr = requireAuth(req);
1485
- if (authErr) return withCors(req, authErr);
1486
-
1487
- const fileId = decodeURIComponent(fileMatch[1]);
1488
- if (!FILE_ID_REGEX.test(fileId)) {
1489
- return withCors(req, Response.json({ ok: false, error: "bad_file_id" }, { status: 400 }));
1490
- }
1491
-
1492
- const idxPath = indexEntryPath(fileId);
1493
- if (!idxPath || !existsSync(idxPath)) {
1494
- return withCors(req, Response.json({ ok: false, error: "not_found" }, { status: 404 }));
1495
- }
1496
-
1497
- let entry: any;
1498
- try { entry = JSON.parse(readFileSync(idxPath, "utf-8")); } catch {
1499
- return withCors(req, Response.json({ ok: false, error: "index_corrupt" }, { status: 500 }));
1500
- }
1501
- if (!validateIndexEntry(entry)) {
1502
- return withCors(req, Response.json({ ok: false, error: "index_invalid" }, { status: 500 }));
1503
- }
1504
-
1505
- let storage;
1506
- try {
1507
- storage = buildStoragePath(entry.file_id, entry.ext);
1508
- } catch {
1509
- return withCors(req, Response.json({ ok: false, error: "index_invalid" }, { status: 500 }));
1510
- }
1511
- if (!isPathInsideUploadsRoot(storage.absolutePath)) {
1512
- // Defence: should be unreachable since buildStoragePath rejected
1513
- // malformed inputs, but a poisoned index could try to fool us.
1514
- return withCors(req, Response.json({ ok: false, error: "path_escape" }, { status: 500 }));
1515
- }
1516
- if (!existsSync(storage.absolutePath)) {
1517
- return withCors(req, Response.json({ ok: false, error: "blob_missing" }, { status: 404 }));
1518
- }
1519
-
1520
- // Defence: verify the on-disk size matches what the index claims
1521
- // before serving — a tampered index could otherwise mislead the
1522
- // caller about file integrity.
1523
- const st = statSync(storage.absolutePath);
1524
- if (st.size !== entry.size) {
1525
- console.error("[/api/files] size mismatch:", { fileId, indexed: entry.size, onDisk: st.size });
1526
- return withCors(req, Response.json({ ok: false, error: "size_mismatch" }, { status: 500 }));
1527
- }
1528
-
1529
- const safeFilename = (entry.name && /^[\x20-\x7e]+$/.test(entry.name))
1530
- ? entry.name
1531
- : `${fileId}${entry.ext}`;
1532
- const blob = Bun.file(storage.absolutePath);
1533
- const responseHeaders: Record<string, string> = {
1534
- ...corsHeaders(req),
1535
- "Content-Type": "application/octet-stream", // always opaque; nosniff prevents the client from re-deciding
1536
- "Content-Length": String(entry.size),
1537
- "Content-Disposition": `attachment; filename="${safeFilename.replace(/"/g, "")}"`,
1538
- "X-Content-Type-Options": "nosniff",
1539
- "Cache-Control": "private, no-store",
1540
- };
1541
- return new Response(blob, { status: 200, headers: responseHeaders });
1542
- }
1543
-
1544
- // ── REST: send task ──
1545
- if (url.pathname === "/api/task" && req.method === "POST") {
1546
- let raw: unknown;
1547
- try {
1548
- raw = await req.json();
1549
- } catch {
1550
- return withCors(req, Response.json({ error: "invalid JSON" }, { status: 400 }));
1551
- }
1552
- const parsed = TaskSchema.safeParse(raw);
1553
- if (!parsed.success) {
1554
- return withCors(req, Response.json({ error: "invalid input", details: parsed.error.format() }, { status: 400 }));
1555
- }
1556
- const body = parsed.data;
1557
- let taskNetId: string | null = null;
1558
- if (restAuth?.networkId) {
1559
- taskNetId = restAuth.networkId;
1560
- } else if (body.network_id) {
1561
- if (restAuth && !isAdmin && !getUserNetworkRole(restAuth.userId, body.network_id)) {
1562
- return withCors(req, Response.json({ ok: false, error: "access denied to requested network" }, { status: 403 }));
1563
- }
1564
- taskNetId = body.network_id;
1565
- } else {
1566
- taskNetId = restAuth ? singleNetworkId(restScope) : null;
1567
- }
1568
- if (restAuth && !taskNetId) {
1569
- return withCors(req, Response.json({ ok: false, error: "network_id required for user token when multiple networks are available" }, { status: 400 }));
1570
- }
1571
- if (!canRestWriteNetwork(restAuth, taskNetId, isAdmin)) {
1572
- return withCors(req, Response.json({ ok: false, error: "permission_denied" }, { status: 403 }));
1573
- }
1574
- const canonical = resolveCanonicalAlias(taskNetId, body.alias);
1575
- const targetAlias = canonical.alias;
1576
- const target = resolveRestDeliveryTarget(targetAlias, taskNetId);
1577
- if (target.state === "not_found") {
1578
- return withCors(req, Response.json({
1579
- ok: false,
1580
- error: "alias_not_found",
1581
- message: target.message,
1582
- alias: targetAlias,
1583
- queued: false,
1584
- ...(canonical.renamed ? { renamed_from: body.alias, renamed_to: targetAlias } : {}),
1585
- }, { status: 404 }));
1586
- }
1587
- const id = crypto.randomUUID();
1588
- const fromSession = body.from || "api";
1589
- const ttlSeconds = (body as any).ttl_seconds || 3600;
1590
- const fromNodeId = resolveRestNodeIdForAlias(fromSession, taskNetId);
1591
- const targetNodeId = target.session?.node_id ?? null;
1592
- // #221 — fold top-level `attachments` into `meta.attachments` so
1593
- // the REST and MCP send_task transports produce identical
1594
- // tasks.meta_json shape downstream. Top-level wins over any
1595
- // duplicate `meta.attachments` the client supplied. Validation
1596
- // matches the MCP-side schema (max 20 entries, file_id regex,
1597
- // size cap, etc.).
1598
- const attachmentsResult = validateAttachments((body as any).attachments ?? (body as any).meta?.attachments);
1599
- if (!attachmentsResult.ok) {
1600
- return withCors(req, Response.json({ ok: false, error: "bad_attachments", message: attachmentsResult.error }, { status: 400 }));
1601
- }
1602
- const mergedMeta = attachmentsResult.attachments.length
1603
- ? { ...((body as any).meta && typeof (body as any).meta === "object" ? (body as any).meta : {}), attachments: attachmentsResult.attachments }
1604
- : (body as any).meta;
1605
- const metaJson = normalizeMetaJson(mergedMeta);
1606
-
1607
- // #212 dedup guardrail. Mirrors the MCP `send_task` tool: same
1608
- // (from_session, target_alias, task) within COMMHUB_SEND_DEDUP_WINDOW_MS
1609
- // is rejected with a structured `duplicate_send` error so dashboard
1610
- // dispatch buttons and scripted REST callers get the same guarantee
1611
- // as agent-driven MCP traffic.
1612
- const dedup = sharedSendDedup.check(fromSession, targetAlias, body.task);
1613
- if (dedup.duplicate) {
1614
- const payload = buildDuplicateSendPayload({
1615
- from: fromSession,
1616
- to: targetAlias,
1617
- ageMs: dedup.ageMs,
1618
- windowMs: sharedSendDedup.windowMs,
1619
- });
1620
- console.log(`[/api/task] ${fromSession} → ${targetAlias}: DROPPED duplicate (age=${dedup.ageMs}ms, window=${sharedSendDedup.windowMs}ms)`);
1621
- return withCors(req, Response.json(payload, { status: 429 }));
1622
- }
1623
-
1624
- // Mirror send_task MCP: write inbox + tasks rows in a single
1625
- // transaction so the dispatch is visible to dashboard's Tasks page
1626
- // and the parent_task_id lineage chain. Previously this endpoint
1627
- // only wrote inbox, leaving GET /api/tasks empty for any task
1628
- // dispatched via REST (anet demo, dashboard Dispatch button, etc.).
1629
- db.transaction(() => {
1630
- db.run(
1631
- `INSERT INTO inbox (id, session_name, node_id, type, priority, content, from_session, requires_response, network_id, meta_json)
1632
- VALUES (?1, ?2, ?3, 'task', ?4, ?5, ?6, 'reply', ?7, ?8)`,
1633
- [id, targetAlias, targetNodeId, body.priority, body.task, fromSession, taskNetId, metaJson]
1634
- );
1635
- db.run(
1636
- `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)
1637
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'delivered', ?7, 'reply', datetime('now'), datetime('now'), datetime('now', ?8), ?9, ?10, ?11)`,
1638
- [id, fromNodeId, fromSession, targetNodeId, targetAlias, body.priority, body.task, `+${ttlSeconds} seconds`, taskNetId, body.parent_task_id ?? null, metaJson]
1639
- );
1640
- // Touch session row so the dashboard reflects "task in flight"
1641
- // immediately, without waiting for the agent's report_status to
1642
- // arrive. Updating both `task` and `updated_at` is enough — we
1643
- // leave `status` to the agent (idle → working → idle).
1644
- const touchParams: any[] = [body.task.slice(0, 200), targetAlias];
1645
- let touchSql = "UPDATE sessions SET task = ?1, updated_at = datetime('now') WHERE alias = ?2";
1646
- if (taskNetId) { touchSql += " AND network_id = ?3"; touchParams.push(taskNetId); }
1647
- db.run(touchSql, touchParams);
1648
- });
1649
- // SSE push: 秒达
1650
- const pendingParams: any[] = [targetAlias];
1651
- let pendingSql = "SELECT COUNT(*) as cnt FROM inbox WHERE session_name = ?1 AND acked = 0";
1652
- if (taskNetId) { pendingSql += " AND network_id = ?2"; pendingParams.push(taskNetId); }
1653
- const pending = db.get<{ cnt: number }>(pendingSql, ...pendingParams);
1654
- if (target.state === "online") {
1655
- pushEvent(targetAlias, { type: "new_task", inbox_count: pending?.cnt ?? 1, priority: body.priority, from: fromSession, ...(canonical.renamed ? { renamed_from: body.alias } : {}) }, taskNetId);
1656
- }
1657
- // #212 — stamp the dedup index only after the inbox/tasks insert
1658
- // succeeds. Mirrors the MCP `send_task` path so a failed write
1659
- // never shadows a legitimate retry.
1660
- sharedSendDedup.record(fromSession, targetAlias, body.task);
1661
- if (target.state === "offline") {
1662
- return withCors(req, Response.json({
1663
- ok: false,
1664
- error: "alias_offline",
1665
- message: target.message,
1666
- alias: targetAlias,
1667
- queued: true,
1668
- task_id: id,
1669
- message_id: id,
1670
- session_status: target.session.status ?? "offline",
1671
- ...(canonical.renamed ? { renamed_from: body.alias, renamed_to: targetAlias } : {}),
1672
- }, { status: 202 }));
1673
- }
1674
- return withCors(req, Response.json({ ok: true, task_id: id, message_id: id, ...(canonical.renamed ? { renamed_from: body.alias, renamed_to: targetAlias } : {}) }));
1675
- }
1676
-
1677
- // ── REST: broadcast ──
1678
- if (url.pathname === "/api/broadcast" && req.method === "POST") {
1679
- let raw: unknown;
1680
- try {
1681
- raw = await req.json();
1682
- } catch {
1683
- return withCors(req, Response.json({ error: "invalid JSON" }, { status: 400 }));
1684
- }
1685
- const parsed = BroadcastSchema.safeParse(raw);
1686
- if (!parsed.success) {
1687
- return withCors(req, Response.json({ error: "invalid input", details: parsed.error.format() }, { status: 400 }));
1688
- }
1689
- const body = parsed.data;
1690
- if (restAuth && !restScope.networkId && !isAdmin) {
1691
- return withCors(req, Response.json({ ok: false, error: "network_id required for user token when broadcasting" }, { status: 400 }));
1692
- }
1693
- if (!canRestWriteNetwork(restAuth, restScope.networkId, isAdmin)) {
1694
- return withCors(req, Response.json({ ok: false, error: "permission_denied" }, { status: 403 }));
1695
- }
1696
- let sql = "SELECT alias, node_id, network_id FROM sessions WHERE alias IS NOT NULL";
1697
- const params: any[] = [];
1698
- sql = addNetworkScope(sql, params, restScope);
1699
- if (body.filter_server) { sql += " AND server = ?"; params.push(body.filter_server); }
1700
- if (body.filter_status) { sql += " AND status = ?"; params.push(body.filter_status); }
1701
- const targets = db.all<{ alias: string; node_id: string | null; network_id: string | null }>(sql, ...params);
1702
- const ids: string[] = [];
1703
- for (const t of targets) {
1704
- const id = crypto.randomUUID();
1705
- db.run(
1706
- `INSERT INTO inbox (id, session_name, node_id, type, priority, content, from_session, network_id)
1707
- VALUES (?1, ?2, ?3, 'broadcast', 'normal', ?4, 'api', ?5)`,
1708
- [id, t.alias, t.node_id ?? null, body.message, t.network_id]
1709
- );
1710
- ids.push(id);
1711
- }
1712
- for (const t of targets) {
1713
- pushEvent(t.alias, { type: "broadcast", inbox_count: 1 }, t.network_id);
1714
- }
1715
- return withCors(req, Response.json({ ok: true, recipients: targets.length, message_ids: ids }));
1716
- }
1717
-
1718
- // ── REST: tmux capture-pane ──
1719
- const tmuxCapture = url.pathname.match(/^\/api\/tmux\/([a-zA-Z0-9_-]+)$/);
1720
- if (tmuxCapture && req.method === "GET") {
1721
- const tmuxErr = requireTmuxAccess(req, server);
1722
- if (tmuxErr) return withCors(req, tmuxErr);
1723
- const name = tmuxCapture[1];
1724
- const lines = Number(url.searchParams.get("lines")) || 30;
1725
- try {
1726
- const proc = Bun.spawn(["tmux", "capture-pane", "-t", name, "-p"], {
1727
- stdout: "pipe", stderr: "pipe",
1728
- });
1729
- const text = await new Response(proc.stdout).text();
1730
- const err = await new Response(proc.stderr).text();
1731
- const code = await proc.exited;
1732
- if (code !== 0) {
1733
- return withCors(req, Response.json({ ok: false, error: err.trim() || `exit ${code}` }, { status: 400 }));
1734
- }
1735
- const trimmed = text.split("\n").slice(-lines).join("\n");
1736
- return withCors(req, Response.json({ ok: true, tmux_name: name, lines: lines, output: trimmed }));
1737
- } catch (e) {
1738
- return withCors(req, Response.json({ ok: false, error: (e as Error).message }, { status: 500 }));
1739
- }
1740
- }
1741
-
1742
- // ── REST: tmux send-keys ──
1743
- const tmuxSend = url.pathname.match(/^\/api\/tmux\/([a-zA-Z0-9_-]+)\/send$/);
1744
- if (tmuxSend && req.method === "POST") {
1745
- const tmuxErr = requireTmuxAccess(req, server);
1746
- if (tmuxErr) return withCors(req, tmuxErr);
1747
- const name = tmuxSend[1];
1748
- let body: { text?: string; enter?: boolean };
1749
- try { body = await req.json(); } catch {
1750
- return withCors(req, Response.json({ error: "invalid JSON" }, { status: 400 }));
1751
- }
1752
- if (!body.text || typeof body.text !== "string") {
1753
- return withCors(req, Response.json({ error: "text is required" }, { status: 400 }));
1754
- }
1755
- const args = ["tmux", "send-keys", "-t", name, body.text];
1756
- if (body.enter !== false) args.push("Enter");
1757
- try {
1758
- const proc = Bun.spawn(args, { stdout: "pipe", stderr: "pipe" });
1759
- const err = await new Response(proc.stderr).text();
1760
- const code = await proc.exited;
1761
- if (code !== 0) {
1762
- return withCors(req, Response.json({ ok: false, error: err.trim() || `exit ${code}` }, { status: 400 }));
1763
- }
1764
- return withCors(req, Response.json({ ok: true, sent: body.text }));
1765
- } catch (e) {
1766
- return withCors(req, Response.json({ ok: false, error: (e as Error).message }, { status: 500 }));
1767
- }
1768
- }
1769
-
1770
- // ── REST: recent messages (for Dashboard communication graph) ──
1771
- if (url.pathname === "/api/messages") {
1772
- const limit = Math.min(Number(url.searchParams.get("limit")) || 100, 500);
1773
- const since = url.searchParams.get("since") ?? new Date(Date.now() - 3600000).toISOString().replace("T", " ").slice(0, 19);
1774
- const params: any[] = [since];
1775
- 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";
1776
- sql = addNetworkScope(sql, params, restScope);
1777
- sql += ` ORDER BY created_at DESC LIMIT ?${params.length + 1}`;
1778
- params.push(limit);
1779
- const rows = db.all(sql, ...params);
1780
- return withCors(req, Response.json({ ok: true, messages: rows }));
1781
- }
1782
-
1783
- // ── REST: stats summary ──
1784
- if (url.pathname === "/api/stats") {
1785
- const taskStatsParams: any[] = [];
1786
- let taskStatsSql = "SELECT status, COUNT(*) as count FROM tasks WHERE 1=1";
1787
- taskStatsSql = addNetworkScope(taskStatsSql, taskStatsParams, restScope);
1788
- taskStatsSql += " GROUP BY status";
1789
- const taskStats = db.all<any>(taskStatsSql, ...taskStatsParams);
1790
-
1791
- const sessionStatsParams: any[] = [];
1792
- let sessionStatsSql = "SELECT status, COUNT(*) as count FROM sessions WHERE 1=1";
1793
- sessionStatsSql = addNetworkScope(sessionStatsSql, sessionStatsParams, restScope);
1794
- sessionStatsSql += " GROUP BY status";
1795
- const sessionStats = db.all<any>(sessionStatsSql, ...sessionStatsParams);
1796
-
1797
- const totalTasksParams: any[] = [];
1798
- let totalTasksSql = "SELECT COUNT(*) as cnt FROM tasks WHERE 1=1";
1799
- totalTasksSql = addNetworkScope(totalTasksSql, totalTasksParams, restScope);
1800
- const totalTasks = db.get<{ cnt: number }>(totalTasksSql, ...totalTasksParams);
1801
-
1802
- const totalNodesParams: any[] = [];
1803
- let totalNodesSql = "SELECT COUNT(*) as cnt FROM nodes WHERE 1=1";
1804
- totalNodesSql = addNetworkScope(totalNodesSql, totalNodesParams, restScope);
1805
- const totalNodes = db.get<{ cnt: number }>(totalNodesSql, ...totalNodesParams);
1806
-
1807
- const recentTasksParams: any[] = [];
1808
- let recentTasksSql = "SELECT task_id, from_name, to_name, status, created_at FROM tasks WHERE 1=1";
1809
- recentTasksSql = addNetworkScope(recentTasksSql, recentTasksParams, restScope);
1810
- recentTasksSql += " ORDER BY created_at DESC LIMIT 5";
1811
- const recentTasks = db.all<any>(recentTasksSql, ...recentTasksParams);
1812
- return withCors(req, Response.json({
1813
- ok: true,
1814
- network_id: restScope.networkId || null,
1815
- tasks: { total: totalTasks?.cnt || 0, by_status: taskStats },
1816
- sessions: { by_status: sessionStats },
1817
- nodes: { total: totalNodes?.cnt || 0 },
1818
- recent_tasks: recentTasks,
1819
- }));
1820
- }
1821
-
1822
- // ── REST: server log tail (in-memory ring buffer, last LOG_RING_CAP lines) ──
1823
- // Admin-only because logs may include user names + task content.
1824
- if (url.pathname === "/api/server-logs") {
1825
- const token = req.headers.get("Authorization")?.replace("Bearer ", "") || url.searchParams.get("token");
1826
- if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
1827
- const resolved = resolveToken(token);
1828
- if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
1829
- if (resolved.user.role !== "admin") return withCors(req, Response.json({ ok: false, error: "admin only" }, { status: 403 }));
1830
- const limit = Math.min(Number(url.searchParams.get("limit")) || 200, LOG_RING_CAP);
1831
- const since = url.searchParams.get("since"); // ISO timestamp; only return logs newer
1832
- let entries = logRing.slice(-limit);
1833
- if (since) entries = entries.filter(e => e.ts > since);
1834
- // Newest first
1835
- entries = entries.slice().reverse();
1836
- return withCors(req, Response.json({ ok: true, logs: entries, capacity: LOG_RING_CAP }));
1837
- }
1838
-
1839
- // ── REST: audit log (V3) ──
1840
- if (url.pathname === "/api/audit-log") {
1841
- const token = req.headers.get("Authorization")?.replace("Bearer ", "") || url.searchParams.get("token");
1842
- if (!token) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
1843
- const resolved = resolveToken(token);
1844
- if (!resolved) return withCors(req, Response.json({ ok: false, error: "invalid token" }, { status: 401 }));
1845
- const limit = Math.min(Number(url.searchParams.get("limit")) || 50, 200);
1846
- const action = url.searchParams.get("action");
1847
- const userId = url.searchParams.get("user_id");
1848
- let sql = "SELECT * FROM audit_log WHERE 1=1";
1849
- const params: any[] = [];
1850
- // Non-admin can only see own logs
1851
- if (resolved.user.role !== "admin") { sql += ` AND user_id = ?${params.length + 1}`; params.push(resolved.user.user_id); }
1852
- if (action) { sql += ` AND action = ?${params.length + 1}`; params.push(action); }
1853
- if (userId && resolved.user.role === "admin") { sql += ` AND user_id = ?${params.length + 1}`; params.push(userId); }
1854
- sql += ` ORDER BY created_at DESC LIMIT ?${params.length + 1}`;
1855
- params.push(limit);
1856
- const logs = db.all(sql, ...params);
1857
- return withCors(req, Response.json({ ok: true, logs, count: logs.length }));
1858
- }
1859
-
1860
- // ── REST: task events (V2 Sprint 2) ──
1861
- if (url.pathname === "/api/task_events") {
1862
- const taskId = url.searchParams.get("task_id");
1863
- const limit = Math.min(Number(url.searchParams.get("limit")) || 50, 500);
1864
- let sql = "SELECT * FROM task_events WHERE 1=1";
1865
- const params: any[] = [];
1866
- sql = addNetworkScope(sql, params, restScope);
1867
- if (taskId) { sql += ` AND task_id = ?${params.length + 1}`; params.push(taskId); }
1868
- sql += ` ORDER BY created_at DESC LIMIT ?${params.length + 1}`;
1869
- params.push(limit);
1870
- const rows = db.all(sql, ...params);
1871
- return withCors(req, Response.json({ ok: true, events: rows, count: rows.length }));
1872
- }
1873
-
1874
- // ── REST: delete node (Dashboard/CLI remote cleanup) ──
1875
- const nodeDeleteMatch = url.pathname.match(/^\/api\/nodes\/([^/]+)$/);
1876
- if (nodeDeleteMatch && req.method === "DELETE") {
1877
- const ref = decodeURIComponent(nodeDeleteMatch[1]);
1878
- const params: any[] = [ref, ref, ref];
1879
- let sql = "SELECT * FROM nodes WHERE (node_id = ?1 OR node_name = ?2 OR alias = ?3)";
1880
- sql = addNetworkScope(sql, params, restScope);
1881
- sql += " ORDER BY updated_at DESC LIMIT 1";
1882
- const node = db.get<any>(sql, ...params);
1883
- if (!node) return withCors(req, Response.json({ ok: false, error: "node not found" }, { status: 404 }));
1884
-
1885
- const nodeNetId = node.network_id ?? singleNetworkId(restScope);
1886
- if (!canRestWriteNetwork(restAuth, nodeNetId, isAdmin)) {
1887
- return withCors(req, Response.json({ ok: false, error: "permission_denied" }, { status: 403 }));
1888
- }
1889
-
1890
- db.transaction(() => {
1891
- db.run("DELETE FROM nodes WHERE node_id = ?1", [node.node_id]);
1892
- if (node.alias) {
1893
- db.run(
1894
- "DELETE FROM sessions WHERE alias = ?1 AND (network_id = ?2 OR (?2 IS NULL AND network_id IS NULL))",
1895
- [node.alias, node.network_id ?? null]
1896
- );
1897
- }
1898
- });
1899
-
1900
- if (node.alias) {
1901
- pushEvent(node.alias, {
1902
- type: "node_deleted",
1903
- node_id: node.node_id,
1904
- node_name: node.node_name,
1905
- alias: node.alias,
1906
- network_id: node.network_id ?? null,
1907
- }, node.network_id ?? null);
1908
- }
1909
-
1910
- return withCors(req, Response.json({
1911
- ok: true,
1912
- deleted: true,
1913
- node_id: node.node_id,
1914
- node_name: node.node_name,
1915
- alias: node.alias,
1916
- network_id: node.network_id ?? null,
1917
- }));
1918
- }
1919
-
1920
- // ── REST: single node config snapshot (RFC-024 B5) ──
1921
- // Dashboard calls this for the snapshot path. Returns the masked
1922
- // {model, flags, config_revision} the node last posted via
1923
- // report_status (B6). NEVER reads per-node files. Network-scoped
1924
- // via addNetworkScope so a netA viewer can't read a netB node.
1925
- const nodeConfigMatch = url.pathname.match(/^\/api\/nodes\/([^/]+)\/config$/);
1926
- if (nodeConfigMatch && req.method === "GET") {
1927
- const nodeId = decodeURIComponent(nodeConfigMatch[1] ?? "");
1928
- const params: any[] = [nodeId];
1929
- let sql = "SELECT node_id, alias, network_id, config_revision, config_snapshot FROM nodes WHERE node_id = ?1";
1930
- sql = addNetworkScope(sql, params, restScope);
1931
- sql += " LIMIT 1";
1932
- const node = db.get<any>(sql, ...params);
1933
- if (!node) {
1934
- return withCors(req, Response.json({ ok: false, error: "node_not_found", node_id: nodeId }, { status: 404 }));
1935
- }
1936
- let snapshot: any = {};
1937
- if (node.config_snapshot) {
1938
- try { snapshot = JSON.parse(node.config_snapshot); } catch { snapshot = {}; }
1939
- }
1940
- return withCors(req, Response.json({
1941
- ok: true,
1942
- node_id: node.node_id,
1943
- alias: node.alias,
1944
- network_id: node.network_id,
1945
- config_revision: node.config_revision || 0,
1946
- model: snapshot.model ?? null,
1947
- flags: snapshot.flags ?? {},
1948
- config_update_capable: snapshot.config_update_capable ?? false,
1949
- }));
1950
- }
1951
-
1952
- // ── REST: nodes table (V2 Sprint 2) ──
1953
- // Explicit column list — NOT `SELECT *`. Two reasons:
1954
- // 1. `SELECT *` silently broadcasts any column added later to the
1955
- // response (RFC-024 added config_revision/config_snapshot which
1956
- // the dashboard's GET /api/nodes/:id/config endpoint owns;
1957
- // RFC-028 will add more vault-flavored columns). Tests asserting
1958
- // response shape break on every ALTER; integrations that key
1959
- // off Object.keys() can pick up internals.
1960
- // 2. The list endpoint and the per-node config snapshot endpoint
1961
- // have different consumer contracts; this list should be the
1962
- // stable, dashboard-facing fields only.
1963
- // Add a new column to this list explicitly when a real client needs
1964
- // it; do NOT switch back to SELECT *.
1965
- // ── REST: list host_supervisor daemons (RFC-026 §9.2.2 / #338 PR2) ──
1966
- // Mirror of the `list_host_supervisors` MCP tool for non-MCP callers.
1967
- // Same SQL + role-extract + member-脱敏 logic; SEC-1 scoped via REST
1968
- // auth pipeline (restScope). Returns {ok, daemons:[...], count}.
1969
- if (url.pathname === "/api/host-supervisors") {
1970
- const netParam = url.searchParams.get("network_id");
1971
- const effectiveNetId = restScope.networkId ?? netParam ?? null;
1972
- if (!effectiveNetId) {
1973
- return withCors(req, Response.json({ ok: false, error: "missing_network_id" }, { status: 400 }));
1974
- }
1975
- // Role for member-脱敏 (admin/owner = full host_telemetry, others = masked)
1976
- let isPrivileged = false;
1977
- if (restAuth?.userId) {
1978
- const role = getUserNetworkRole(restAuth.userId, effectiveNetId);
1979
- isPrivileged = role === "admin" || role === "owner";
1980
- } else {
1981
- // Network-token caller (no user) — treat as privileged within its network
1982
- isPrivileged = true;
1983
- }
1984
-
1985
- // EXISTS subquery handles BOTH revoked_at SET and DELETEd token
1986
- // rows (revokeToken DELETEs the row in production — PR2 v1
1987
- // SHOULD-FIX per 通信龙 audit). EXISTS naturally dedupes daemons
1988
- // with rotated tokens.
1989
- const sqlRows = db.all<Record<string, any>>(`
1990
- SELECT
1991
- n.node_id, n.alias, n.hostname, n.network_id,
1992
- n.runtimes_supported, n.allowed_secret_keys,
1993
- n.created_at, n.updated_at,
1994
- s.last_seen_at AS session_last_seen,
1995
- s.cpu_cores AS session_cpu_cores,
1996
- s.mem_total_gb AS session_mem_total_gb,
1997
- s.ip AS session_ip,
1998
- n.config_snapshot
1999
- FROM nodes n
2000
- LEFT JOIN sessions s ON s.alias = n.alias AND (s.network_id = n.network_id OR s.network_id IS NULL)
2001
- WHERE n.network_id = ?1
2002
- AND EXISTS (
2003
- SELECT 1 FROM api_tokens t
2004
- WHERE t.network_id = n.network_id
2005
- AND t.name = 'node:' || n.alias
2006
- AND t.revoked_at IS NULL
2007
- )
2008
- ORDER BY n.updated_at DESC
2009
- `, effectiveNetId);
2010
-
2011
- const nowMs = Date.now();
2012
- const ONLINE_MS = 60_000;
2013
- const daemons = sqlRows
2014
- .map(r => {
2015
- let snapRole: string | null = null;
2016
- if (r.config_snapshot) {
2017
- try {
2018
- const parsed = typeof r.config_snapshot === "string" ? JSON.parse(r.config_snapshot) : r.config_snapshot;
2019
- snapRole = typeof parsed?.role === "string" ? parsed.role : null;
2020
- } catch { /* malformed */ }
2021
- }
2022
- return { row: r, role: snapRole };
2023
- })
2024
- .filter(({ role }) => role === "host_supervisor")
2025
- .map(({ row: r }) => {
2026
- let online = false;
2027
- let lastSeenAt: string | null = null;
2028
- if (r.session_last_seen) {
2029
- lastSeenAt = r.session_last_seen;
2030
- const t = Date.parse(r.session_last_seen);
2031
- if (!isNaN(t)) online = (nowMs - t) <= ONLINE_MS;
2032
- }
2033
- let runtimes: string[] = [];
2034
- let secrets: string[] = [];
2035
- try {
2036
- if (r.runtimes_supported) {
2037
- const parsed = JSON.parse(r.runtimes_supported);
2038
- runtimes = Array.isArray(parsed) ? parsed.filter((s: unknown) => typeof s === "string") : [];
2039
- }
2040
- } catch {}
2041
- try {
2042
- if (r.allowed_secret_keys) {
2043
- const parsed = JSON.parse(r.allowed_secret_keys);
2044
- secrets = Array.isArray(parsed) ? parsed.filter((s: unknown) => typeof s === "string") : [];
2045
- }
2046
- } catch {}
2047
- const telemetry: Record<string, unknown> = {
2048
- alert_level: online ? "green" : "gray",
2049
- };
2050
- if (isPrivileged) {
2051
- telemetry.cpu_cores = r.session_cpu_cores ?? null;
2052
- telemetry.mem_gb = r.session_mem_total_gb ?? null;
2053
- telemetry.ip_internal = r.session_ip ?? null;
2054
- }
2055
- return {
2056
- daemon_node_id: r.node_id,
2057
- alias: r.alias,
2058
- hostname: r.hostname,
2059
- online,
2060
- last_seen_at: lastSeenAt,
2061
- runtimes_supported: runtimes,
2062
- allowed_secret_keys: secrets,
2063
- host_telemetry: telemetry,
2064
- };
2065
- });
2066
- return withCors(req, Response.json({ ok: true, daemons, count: daemons.length }));
2067
- }
2068
-
2069
- if (url.pathname === "/api/nodes") {
2070
- const nodeId = url.searchParams.get("node_id");
2071
- const alias = url.searchParams.get("alias");
2072
- // `config_snapshot` SELECTed ONLY to extract the daemon `role` field
2073
- // for dashboard discovery — full snapshot is NOT broadcast (would
2074
- // re-introduce the #312 SELECT * fragility). Mapping step pulls
2075
- // `role` out then drops `config_snapshot` from the response row.
2076
- let sql = `SELECT node_id, node_name, alias, runtime, model,
2077
- config_path, channels, server, hostname,
2078
- network_id, created_at, updated_at,
2079
- config_snapshot
2080
- FROM nodes WHERE 1=1`;
2081
- const params: any[] = [];
2082
- sql = addNetworkScope(sql, params, restScope);
2083
- if (nodeId) { sql += ` AND node_id = ?${params.length + 1}`; params.push(nodeId); }
2084
- if (alias) { sql += ` AND alias = ?${params.length + 1}`; params.push(alias); }
2085
- sql += " ORDER BY updated_at DESC";
2086
- const rawRows = db.all<Record<string, any>>(sql, ...params);
2087
- // Add a single new field `role: string | null` per row, extracted from
2088
- // config_snapshot JSON. Daemon nodes that posted role='host_supervisor'
2089
- // via report_status surface here; dashboard uses this for daemon
2090
- // discovery (replacing the prior `node_daemon_` prefix heuristic).
2091
- // RFC-026 P1 P2 §9 will supersede this REST proxy with the
2092
- // `list_host_supervisors` MCP tool.
2093
- const rows = rawRows.map(r => {
2094
- let role: string | null = null;
2095
- const snap = r.config_snapshot;
2096
- if (snap) {
2097
- try { role = (typeof snap === "string" ? JSON.parse(snap) : snap)?.role ?? null; }
2098
- catch { /* malformed snapshot — leave role null */ }
2099
- }
2100
- const { config_snapshot, ...rest } = r;
2101
- return { ...rest, role };
2102
- });
2103
- return withCors(req, Response.json({ ok: true, nodes: rows, count: rows.length }));
2104
- }
2105
-
2106
- // ── REST: single task lookup (V2) ──
2107
- const taskPathMatch = url.pathname.match(/^\/api\/tasks?\/([^/]+)$/);
2108
- if (taskPathMatch && req.method === "GET") {
2109
- const taskId = decodeURIComponent(taskPathMatch[1] ?? "");
2110
- const params: any[] = [taskId];
2111
- let sql = "SELECT * FROM tasks WHERE task_id = ?1";
2112
- sql = addNetworkScope(sql, params, restScope);
2113
- sql += " LIMIT 1";
2114
- const task = db.get(sql, ...params);
2115
- if (!task) {
2116
- return withCors(req, Response.json({ ok: false, error: "task_not_found", task_id: taskId }, { status: 404 }));
2117
- }
2118
- return withCors(req, Response.json({ ok: true, task }));
2119
- }
2120
-
2121
- // ── REST: tasks table (V2) ──
2122
- if (url.pathname === "/api/tasks") {
2123
- const taskId = url.searchParams.get("task_id");
2124
- const status = url.searchParams.get("status");
2125
- const toName = url.searchParams.get("to_name");
2126
- const fromName = url.searchParams.get("from_name");
2127
- const limit = Math.min(Number(url.searchParams.get("limit")) || 50, 200);
2128
- // #248 — opt-out of the stats GROUP-BY scan. The dashboard chat panel
2129
- // never consumes `stats`; it's a global per-status table scan that
2130
- // dominates the request time on a large DB (270 MB / many tasks).
2131
- // Existing callers that don't pass `skip_stats=1` get the same
2132
- // {ok, tasks, count, stats} shape — backwards-compatible.
2133
- const skipStats = url.searchParams.get("skip_stats") === "1";
2134
-
2135
- let sql = "SELECT * FROM tasks WHERE 1=1";
2136
- const params: any[] = [];
2137
- sql = addNetworkScope(sql, params, restScope);
2138
- if (taskId) { sql += ` AND task_id = ?${params.length + 1}`; params.push(taskId); }
2139
- if (status) { sql += ` AND status = ?${params.length + 1}`; params.push(status); }
2140
- if (toName) { sql += ` AND to_name = ?${params.length + 1}`; params.push(toName); }
2141
- if (fromName) { sql += ` AND from_name = ?${params.length + 1}`; params.push(fromName); }
2142
- sql += ` ORDER BY created_at DESC LIMIT ?${params.length + 1}`;
2143
- params.push(limit);
2144
-
2145
- const rows = db.all(sql, ...params);
2146
- if (skipStats) {
2147
- return withCors(req, Response.json({ ok: true, tasks: rows, count: rows.length }));
2148
- }
2149
- const statsParams: any[] = [];
2150
- let statsSql = "SELECT status, COUNT(*) as count FROM tasks WHERE 1=1";
2151
- statsSql = addNetworkScope(statsSql, statsParams, restScope);
2152
- statsSql += " GROUP BY status";
2153
- const stats = db.all<any>(statsSql, ...statsParams);
2154
- return withCors(req, Response.json({ ok: true, tasks: rows, count: rows.length, stats }));
2155
- }
2156
-
2157
- // ── REST: recent completions ──
2158
- if (url.pathname === "/api/completions") {
2159
- const since = url.searchParams.get("since") ?? new Date(Date.now() - 86400000).toISOString();
2160
- const params: any[] = [since];
2161
- let sql = "SELECT * FROM completions WHERE completed_at >= ?1";
2162
- sql = addNetworkScope(sql, params, restScope);
2163
- sql += " ORDER BY completed_at DESC LIMIT 100";
2164
- const rows = db.all(sql, ...params);
2165
- return withCors(req, Response.json({ ok: true, completions: rows }));
2166
- }
2167
-
2168
- return withCors(req, new Response(
2169
- `CommHub MCP Server v${SERVER_VERSION} (Streamable HTTP + SSE Push)
2170
-
2171
- Endpoints:
2172
- POST /mcp - MCP Streamable HTTP (for Claude Code / Codex)
2173
- GET /events/:session - SSE realtime push (Agent subscribes here)
2174
- GET /health - Health check
2175
- GET /api/status - All sessions (auth required)
2176
- POST /api/task - Send task via REST (auth required)
2177
- GET /api/tasks - Tasks table (V2) (auth required)
2178
- GET /api/completions - Recent completions (auth required)
2179
- GET /api/tmux/:name - Capture tmux pane output (${TMUX_ENABLED ? "admin + localhost/allowlist required" : "disabled"})
2180
- POST /api/tmux/:name/send - Send keys to tmux (${TMUX_ENABLED ? "admin + localhost/allowlist required" : "disabled"})
2181
-
2182
- Security: ${SECURITY_LABEL}
2183
- `,
2184
- { status: 200, headers: { "Content-Type": "text/plain" } }
2185
- ));
2186
- },
2187
-
2188
- // ── WebSocket handler for tmux terminal streaming ──
2189
- websocket: {
2190
- open(ws) {
2191
- const { tmuxName } = ws.data as unknown as { tmuxName: string };
2192
- console.log(`[ws] tmux terminal opened: ${tmuxName}`);
2193
- let lastOutput = "";
2194
-
2195
- // Poll capture-pane every 200ms and send diffs
2196
- const interval = setInterval(async () => {
2197
- try {
2198
- const proc = Bun.spawn(["tmux", "capture-pane", "-t", tmuxName, "-p", "-e"], {
2199
- stdout: "pipe", stderr: "pipe",
2200
- });
2201
- const output = await new Response(proc.stdout).text();
2202
- const code = await proc.exited;
2203
- if (code !== 0) return;
2204
-
2205
- if (output !== lastOutput) {
2206
- lastOutput = output;
2207
- ws.send(JSON.stringify({ type: "output", data: output }));
2208
- }
2209
- } catch { /* session gone */ }
2210
- }, 200);
2211
-
2212
- wsTmuxIntervals.set(ws, interval);
2213
-
2214
- // Send initial capture immediately
2215
- (async () => {
2216
- try {
2217
- const proc = Bun.spawn(["tmux", "capture-pane", "-t", tmuxName, "-p", "-e"], {
2218
- stdout: "pipe", stderr: "pipe",
2219
- });
2220
- const output = await new Response(proc.stdout).text();
2221
- const code = await proc.exited;
2222
- if (code === 0) {
2223
- lastOutput = output;
2224
- ws.send(JSON.stringify({ type: "output", data: output }));
2225
- } else {
2226
- const err = await new Response(proc.stderr).text();
2227
- ws.send(JSON.stringify({ type: "error", data: err.trim() || "tmux session not found" }));
2228
- }
2229
- } catch (e) {
2230
- ws.send(JSON.stringify({ type: "error", data: (e as Error).message }));
2231
- }
2232
- })();
2233
- },
2234
-
2235
- async message(ws, message) {
2236
- const { tmuxName } = ws.data as unknown as { tmuxName: string };
2237
- try {
2238
- const msg = JSON.parse(typeof message === "string" ? message : new TextDecoder().decode(message));
2239
-
2240
- if (msg.type === "input" && typeof msg.data === "string") {
2241
- // Send individual characters/sequences via send-keys
2242
- const proc = Bun.spawn(["tmux", "send-keys", "-t", tmuxName, "-l", msg.data], {
2243
- stdout: "pipe", stderr: "pipe",
2244
- });
2245
- await proc.exited;
2246
- } else if (msg.type === "key" && typeof msg.data === "string") {
2247
- // Send special key names (Enter, C-c, etc.)
2248
- const proc = Bun.spawn(["tmux", "send-keys", "-t", tmuxName, msg.data], {
2249
- stdout: "pipe", stderr: "pipe",
2250
- });
2251
- await proc.exited;
2252
- } else if (msg.type === "resize" && msg.cols && msg.rows) {
2253
- // Resize tmux pane
2254
- Bun.spawn(["tmux", "resize-window", "-t", tmuxName, "-x", String(msg.cols), "-y", String(msg.rows)], {
2255
- stdout: "pipe", stderr: "pipe",
2256
- });
2257
- }
2258
- } catch { /* ignore malformed messages */ }
2259
- },
2260
-
2261
- close(ws) {
2262
- const { tmuxName } = ws.data as unknown as { tmuxName: string };
2263
- console.log(`[ws] tmux terminal closed: ${tmuxName}`);
2264
- const interval = wsTmuxIntervals.get(ws);
2265
- if (interval) { clearInterval(interval); wsTmuxIntervals.delete(ws); }
2266
- },
2267
- },
2268
- });
2269
-
2270
- // Round-2/4 review ② — periodic retention sweep + incremental VACUUM.
2271
- // Sweeps every hour by default. Operators can disable any single table
2272
- // by setting COMMHUB_RETENTION_*_DAYS to a negative value, or shorten
2273
- // the sweep window via COMMHUB_RETENTION_SWEEP_MINUTES.
2274
- const sweepIntervalMinutes = Number(process.env.COMMHUB_RETENTION_SWEEP_MINUTES);
2275
- const sweepIntervalMs = Number.isFinite(sweepIntervalMinutes) && sweepIntervalMinutes > 0
2276
- ? sweepIntervalMinutes * 60 * 1000
2277
- : 60 * 60 * 1000;
2278
- const retentionSweeperTimer = startRetentionSweeper(sweepIntervalMs);
2279
-
2280
- // Round-2/4 review ③ — stale session sweeper (coexists with the
2281
- // retention sweeper above; different concerns + different cadences).
2282
- // Replaces the per-request UPDATE in GET /api/status (+ /api/servers,
2283
- // /api/server-detail/*, MCP get_all_status). Each of those endpoints
2284
- // used to run UPDATE on the sessions table just to maintain the
2285
- // derived `offline` status; with the dashboard polling fast that was
2286
- // 99% no-op write-amp under hot read paths. Now done globally once
2287
- // every COMMHUB_STALE_SWEEP_SECONDS (default 60s).
2288
- const staleSweeperTimer = startStaleSessionSweeper();
2289
-
2290
- // ── Graceful shutdown ───────────────────────────────
2291
- function shutdown() {
2292
- console.log("[commhub] shutting down...");
2293
- clearInterval(retentionSweeperTimer);
2294
- clearInterval(staleSweeperTimer);
2295
- db.close();
2296
- process.exit(0);
2297
- }
2298
- process.on("SIGTERM", shutdown);
2299
- process.on("SIGINT", shutdown);
2300
-
2301
- console.log(`
2302
- ╔══════════════════════════════════════════════════╗
2303
- ║ CommHub MCP Server v${SERVER_VERSION} ║
2304
- ║ Transport: Streamable HTTP (Bun native) ║
2305
- ║ Security: ${SECURITY_LABEL}${" ".repeat(Math.max(0, 33 - SECURITY_LABEL.length))}║
2306
- ║ Tmux: ${TMUX_ENABLED ? "ENABLED (admin + localhost/allowlist)" : "DISABLED (set COMMHUB_ENABLE_TMUX=1)"}${" ".repeat(Math.max(0, TMUX_ENABLED ? 0 : 2))}║
2307
- ║ ║
2308
- ║ MCP: http://${HOST}:${PORT}/mcp ║
2309
- ║ REST: http://${HOST}:${PORT}/api ║
2310
- ║ Health: http://${HOST}:${PORT}/health ║
2311
- ╚══════════════════════════════════════════════════╝
2312
- `);
2313
-
2314
- // RFC-028 P1 boot banner — vault key configuration status.
2315
- // F2 invariant: hub MUST boot regardless of vault state. This is
2316
- // banner-only (informational); errors are raised lazily at vault op
2317
- // time. needsKeyToOp=true means the operator should set
2318
- // ANET_HUB_SECRET_VAULT_KEY before vault/provider features will work.
2319
- try {
2320
- const { vaultStatusForBoot } = await import("./vault.js");
2321
- const s = vaultStatusForBoot();
2322
- if (s.needsKeyToOp) {
2323
- 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).");
2324
- } else if (s.configured) {
2325
- console.log(`[rfc-028 vault] master key configured (tables_have_data=${s.tablesHaveData})`);
2326
- } else {
2327
- 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.");
2328
- }
2329
- } catch (e: any) {
2330
- console.warn(`[rfc-028 vault] boot banner skipped (${e?.message || e})`);
2331
- }
1
+ // Run-entry shim (#438 corrective, 方案 C per 通信龙).
2
+ //
3
+ // Running this module IS running the hub: `bun run src/index.ts` keeps
4
+ // working for the 50+ e2e/dev scripts that boot the hub that way. All
5
+ // real code lives in ./server.ts, which is side-effect-free to import —
6
+ // tests and tooling import "./server.js" and get bootServer/startHub
7
+ // without binding any port. Do NOT add logic here, and do NOT import
8
+ // this module to "get at the server" — that starts one.
9
+ // The default production DB path is deliberately unavailable to ordinary
10
+ // imports / bun -e probes. This run-entry is one of the two canonical places
11
+ // allowed to opt in, and it must do so before dynamically importing server.ts
12
+ // (whose dependency graph constructs the DB adapter at module evaluation).
13
+ process.env.COMMHUB_SERVER = "1";
14
+ const { startHub } = await import("./server.js");
15
+ startHub();