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