@kenhkl/agent-gate 0.7.5 → 0.8.0

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/dist/v3/cli.js CHANGED
@@ -50,7 +50,7 @@ var init_version = __esm({
50
50
  "src/version.ts"() {
51
51
  "use strict";
52
52
  init_cjs_shims();
53
- _version = true ? "0.7.5" : (() => {
53
+ _version = true ? "0.8.0" : (() => {
54
54
  try {
55
55
  const require2 = createRequire(importMetaUrl);
56
56
  const pkg = require2("../package.json");
@@ -63,6 +63,546 @@ var init_version = __esm({
63
63
  }
64
64
  });
65
65
 
66
+ // src/shared/security.ts
67
+ var security_exports = {};
68
+ __export(security_exports, {
69
+ AUTH_MODE_AUTO: () => AUTH_MODE_AUTO,
70
+ AUTH_MODE_OFF: () => AUTH_MODE_OFF,
71
+ DASHBOARD_COOKIE: () => DASHBOARD_COOKIE,
72
+ DASHBOARD_SECURITY_HEADERS: () => DASHBOARD_SECURITY_HEADERS,
73
+ PUBLIC_PATHS: () => PUBLIC_PATHS,
74
+ PooledLimiter: () => PooledLimiter,
75
+ RateLimiter: () => RateLimiter,
76
+ agentInflight: () => agentInflight,
77
+ agentTokens: () => agentTokens,
78
+ allowedOrigins: () => allowedOrigins,
79
+ authConfigError: () => authConfigError,
80
+ authEnabled: () => authEnabled,
81
+ authMode: () => authMode,
82
+ authToken: () => authToken,
83
+ authTokenPath: () => authTokenPath,
84
+ autoTokenHint: () => autoTokenHint,
85
+ bindAgent: () => bindAgent,
86
+ boundAgentOf: () => boundAgentOf,
87
+ checkRequestAuth: () => checkRequestAuth,
88
+ checkToken: () => checkToken,
89
+ cookiePathAllowed: () => cookiePathAllowed,
90
+ describe: () => describe,
91
+ ensureAutoToken: () => ensureAutoToken,
92
+ ensurePrivateDir: () => ensurePrivateDir,
93
+ failFastOnAuthError: () => failFastOnAuthError,
94
+ hardenDbFiles: () => hardenDbFiles,
95
+ hardenFilesEnabled: () => hardenFilesEnabled,
96
+ hardenPermissions: () => hardenPermissions,
97
+ isGlobalToken: () => isGlobalToken,
98
+ keepAliveSec: () => keepAliveSec,
99
+ maxBodyBytes: () => maxBodyBytes,
100
+ maxConnections: () => maxConnections,
101
+ maxInflight: () => maxInflight,
102
+ maxQueue: () => maxQueue,
103
+ normalizeOrigin: () => normalizeOrigin,
104
+ noteQueueReject: () => noteQueueReject,
105
+ noteSessionAccess: () => noteSessionAccess,
106
+ originAllowed: () => originAllowed,
107
+ originCheckEnabled: () => originCheckEnabled,
108
+ poolLimit: () => poolLimit,
109
+ poolOf: () => poolOf,
110
+ principalOf: () => principalOf,
111
+ queueAbuseAction: () => queueAbuseAction,
112
+ rateLimitQps: () => rateLimitQps,
113
+ resetCounters: () => resetCounters,
114
+ resolveMossToken: () => resolveMossToken,
115
+ sessionSweepAction: () => sessionSweepAction,
116
+ unauthInflight: () => unauthInflight,
117
+ unauthPerIp: () => unauthPerIp
118
+ });
119
+ function env(name, dflt = "") {
120
+ return (process.env[name] ?? dflt).trim();
121
+ }
122
+ function envInt(name, dflt) {
123
+ const raw = env(name);
124
+ if (!raw) return dflt;
125
+ const n = parseInt(raw, 10);
126
+ return Number.isFinite(n) ? n : dflt;
127
+ }
128
+ function envFloat(name, dflt) {
129
+ const raw = env(name);
130
+ if (!raw) return dflt;
131
+ const n = parseFloat(raw);
132
+ return Number.isFinite(n) ? n : dflt;
133
+ }
134
+ function split(raw) {
135
+ return raw.replace(/;/g, ",").split(",").map((x) => x.trim()).filter(Boolean);
136
+ }
137
+ function originCheckEnabled() {
138
+ return TRUTHY.includes(env("AGENT_GATE_ORIGIN_CHECK", "1").toLowerCase());
139
+ }
140
+ function allowedOrigins() {
141
+ return split(env("AGENT_GATE_CORS_ORIGINS"));
142
+ }
143
+ function normalizeOrigin(origin) {
144
+ return (origin || "").trim().replace(/\/+$/, "");
145
+ }
146
+ function originAllowed(origin, hostHeader, extra) {
147
+ const o = normalizeOrigin(origin);
148
+ if (!o) return true;
149
+ const entries = (extra ?? allowedOrigins()).map(normalizeOrigin);
150
+ if (entries.includes(o)) return true;
151
+ const host = (hostHeader || "").trim();
152
+ if (!host) return false;
153
+ try {
154
+ const u = new URL(o);
155
+ return !!u.host && u.host === host;
156
+ } catch {
157
+ return false;
158
+ }
159
+ }
160
+ function authMode() {
161
+ return (env("AGENT_GATE_AUTH_MODE", AUTH_MODE_AUTO) || AUTH_MODE_AUTO).toLowerCase();
162
+ }
163
+ function authTokenPath() {
164
+ const home = process.env.SUDO_USER && existsDir(`/home/${process.env.SUDO_USER}`) ? `/home/${process.env.SUDO_USER}` : (0, import_node_os.homedir)();
165
+ const xdg = process.env.XDG_CONFIG_HOME || (0, import_node_path.join)(home, ".config");
166
+ return (0, import_node_path.join)(xdg, "agentgate", "auth_token");
167
+ }
168
+ function existsDir(p) {
169
+ try {
170
+ return (0, import_node_fs.statSync)(p).isDirectory();
171
+ } catch {
172
+ return false;
173
+ }
174
+ }
175
+ function ensurePrivateDir(p, mode = 448) {
176
+ try {
177
+ (0, import_node_fs.mkdirSync)(p, { recursive: true });
178
+ const st = (0, import_node_fs.statSync)(p);
179
+ if (st.uid === process.getuid?.() && (st.mode & 511) !== mode) (0, import_node_fs.chmodSync)(p, mode);
180
+ } catch {
181
+ }
182
+ }
183
+ function hardenPermissions(p, mode) {
184
+ try {
185
+ const st = (0, import_node_fs.lstatSync)(p);
186
+ if (st.isSymbolicLink()) return;
187
+ if (st.uid !== process.getuid?.()) return;
188
+ if ((st.mode & 511) !== mode) (0, import_node_fs.chmodSync)(p, mode);
189
+ } catch {
190
+ }
191
+ }
192
+ function readFdToken() {
193
+ const raw = env("AGENT_GATE_AUTH_TOKEN_FD");
194
+ if (!raw) return "";
195
+ const fd = parseInt(raw, 10);
196
+ if (!Number.isFinite(fd)) return "";
197
+ const cached = fdTokenCache.get(fd);
198
+ if (cached !== void 0) return cached;
199
+ try {
200
+ const buf = Buffer.alloc(8192);
201
+ const n = (0, import_node_fs.readSync)(fd, buf, 0, buf.length, null);
202
+ (0, import_node_fs.closeSync)(fd);
203
+ const tok = buf.subarray(0, n).toString("utf-8").trim();
204
+ fdTokenCache.set(fd, tok);
205
+ return tok;
206
+ } catch {
207
+ fdTokenCache.set(fd, "");
208
+ return "";
209
+ }
210
+ }
211
+ function readExplicitToken() {
212
+ const t = env("AGENT_GATE_AUTH_TOKEN");
213
+ if (t) return t;
214
+ const fromFd = readFdToken();
215
+ if (fromFd) return fromFd;
216
+ const file = env("AGENT_GATE_AUTH_TOKEN_FILE");
217
+ if (file) {
218
+ try {
219
+ return (0, import_node_fs.readFileSync)(file, "utf-8").trim();
220
+ } catch {
221
+ return "";
222
+ }
223
+ }
224
+ return "";
225
+ }
226
+ function ensureAutoToken() {
227
+ const p = authTokenPath();
228
+ try {
229
+ try {
230
+ const existing = (0, import_node_fs.readFileSync)(p, "utf-8").trim();
231
+ if (existing) {
232
+ hardenPermissions(p, 384);
233
+ return existing;
234
+ }
235
+ } catch {
236
+ }
237
+ const tok = (0, import_node_crypto.randomBytes)(32).toString("base64url");
238
+ ensurePrivateDir(p.replace(/\/[^/]+$/, ""));
239
+ try {
240
+ (0, import_node_fs.writeFileSync)(p, tok + "\n", { mode: 384, flag: "wx" });
241
+ } catch (e) {
242
+ if (e?.code === "EEXIST") return (0, import_node_fs.readFileSync)(p, "utf-8").trim();
243
+ throw e;
244
+ }
245
+ console.warn(
246
+ `[AgentGate] \u5DF2\u751F\u6210\u8BBF\u95EE token \u5E76\u5199\u5165 ${p}\uFF080600\uFF09\u3002\u5BA2\u6237\u7AEF\u9700\u5E26 \`Authorization: Bearer <token>\`\uFF1B\u5982\u9700\u5173\u95ED\u9274\u6743\uFF1AAGENT_GATE_AUTH_MODE=off`
247
+ );
248
+ return tok;
249
+ } catch (e) {
250
+ console.error(`[AgentGate] \u751F\u6210\u8BBF\u95EE token \u5931\u8D25\uFF08\u672C\u6B21\u8FD0\u884C\u5C06\u4E0D\u9274\u6743\uFF09: ${e?.message ?? e}`);
251
+ return "";
252
+ }
253
+ }
254
+ function parseAgentTokens(raw) {
255
+ const out = {};
256
+ for (const pair of split(raw)) {
257
+ const i = pair.indexOf("=");
258
+ if (i > 0) {
259
+ const a = pair.slice(0, i).trim();
260
+ const t = pair.slice(i + 1).trim();
261
+ if (a && t) out[a] = t;
262
+ }
263
+ }
264
+ return out;
265
+ }
266
+ function resolveAuth() {
267
+ const rawAgents = env("AGENT_GATE_AGENT_TOKENS");
268
+ const key = [
269
+ authMode(),
270
+ env("AGENT_GATE_AUTH_TOKEN"),
271
+ env("AGENT_GATE_AUTH_TOKEN_FILE"),
272
+ env("AGENT_GATE_AUTH_TOKEN_FD"),
273
+ rawAgents,
274
+ env("AGENT_GATE_DATA_DIR"),
275
+ env("XDG_CONFIG_HOME"),
276
+ env("SUDO_USER")
277
+ ].join("\0");
278
+ if (tokenCache && tokenCache.key === key) return tokenCache;
279
+ let error = "";
280
+ let token = readExplicitToken();
281
+ if (!token && env("AGENT_GATE_AUTH_TOKEN_FD") && authMode() !== AUTH_MODE_OFF) {
282
+ error = "AGENT_GATE_AUTH_TOKEN_FD \u5DF2\u8BBE\u7F6E\uFF0C\u4F46\u6CA1\u80FD\u4ECE\u8BE5\u6587\u4EF6\u63CF\u8FF0\u7B26\u8BFB\u5230 token\u3002\u62D2\u7EDD\u964D\u7EA7\u5230\u78C1\u76D8 token\uFF08\u90A3\u4F1A\u5728\u672C\u673A\u7559\u4E0B\u4E00\u4EFD\u540C\u7528\u6237\u53EF\u8BFB\u7684\u51ED\u8BC1\uFF09\u3002";
283
+ console.error(`[AgentGate] ${error}`);
284
+ }
285
+ if (!token && !error && authMode() !== AUTH_MODE_OFF) token = ensureAutoToken();
286
+ const agents = parseAgentTokens(rawAgents);
287
+ tokenCache = { key, token, agents, error };
288
+ return tokenCache;
289
+ }
290
+ function authToken() {
291
+ return resolveAuth().token;
292
+ }
293
+ function agentTokens() {
294
+ return resolveAuth().agents;
295
+ }
296
+ function authConfigError() {
297
+ return resolveAuth().error;
298
+ }
299
+ function failFastOnAuthError() {
300
+ const err = authConfigError();
301
+ if (err) {
302
+ console.error(`[AgentGate] \u9274\u6743\u914D\u7F6E\u9519\u8BEF\uFF0C\u62D2\u7EDD\u542F\u52A8: ${err}`);
303
+ process.exit(1);
304
+ }
305
+ }
306
+ function authEnabled() {
307
+ if (authMode() === AUTH_MODE_OFF) return false;
308
+ const { token, agents } = resolveAuth();
309
+ return !!token || Object.keys(agents).length > 0;
310
+ }
311
+ function constEq(a, b) {
312
+ const ba = Buffer.from(a, "utf-8");
313
+ const bb = Buffer.from(b, "utf-8");
314
+ if (ba.length !== bb.length) return false;
315
+ return (0, import_node_crypto.timingSafeEqual)(ba, bb);
316
+ }
317
+ function principalOf(token) {
318
+ if (!token) return "";
319
+ const { agents } = resolveAuth();
320
+ for (const [agent, atok] of Object.entries(agents)) {
321
+ if (constEq(token, atok)) return `agent:${agent}`;
322
+ }
323
+ return "tok:" + (0, import_node_crypto.createHash)("sha256").update(token, "utf-8").digest("hex").slice(0, 12);
324
+ }
325
+ function checkToken(token) {
326
+ if (!token) return false;
327
+ const { token: globalTok, agents } = resolveAuth();
328
+ if (globalTok && constEq(token, globalTok)) return true;
329
+ return Object.values(agents).some((t) => constEq(token, t));
330
+ }
331
+ function isGlobalToken(token) {
332
+ if (!token) return false;
333
+ const { token: globalTok } = resolveAuth();
334
+ return Boolean(globalTok) && constEq(token, globalTok);
335
+ }
336
+ function boundAgentOf(principal) {
337
+ return principal.startsWith("agent:") ? principal.slice("agent:".length) : "";
338
+ }
339
+ function cookiePathAllowed(path11) {
340
+ if (path11 === "/api/v1/analyze" || path11.startsWith("/api/v1/analyze/")) return false;
341
+ return path11 === "/dashboard" || path11.startsWith("/dashboard/") || path11.startsWith("/ws/") || path11.startsWith("/api/");
342
+ }
343
+ function checkRequestAuth(headers, path11, cookie = "", requireGlobal = false) {
344
+ if (authMode() === AUTH_MODE_OFF) return { ok: true, principal: "" };
345
+ const isHealth = PUBLIC_PATHS.includes(path11.replace(/\/+$/, ""));
346
+ const { token: globalTok, agents, error } = resolveAuth();
347
+ if (error) return { ok: isHealth, principal: "" };
348
+ if (!globalTok && Object.keys(agents).length === 0) return { ok: true, principal: "" };
349
+ if (isHealth) return { ok: true, principal: "" };
350
+ if (cookie && cookiePathAllowed(path11) && checkToken(cookie)) {
351
+ const principal = principalOf(cookie);
352
+ if (requireGlobal && principal.startsWith("agent:")) {
353
+ return { ok: false, principal };
354
+ }
355
+ return { ok: true, principal };
356
+ }
357
+ const authHeader = headers["authorization"] || "";
358
+ const tok = authHeader.toLowerCase().startsWith("bearer ") ? authHeader.slice(7).trim() : "";
359
+ if (!tok) return { ok: false, principal: "" };
360
+ if (globalTok && constEq(tok, globalTok)) return { ok: true, principal: principalOf(tok) };
361
+ for (const atok of Object.values(agents)) {
362
+ if (constEq(tok, atok)) {
363
+ const principal = principalOf(tok);
364
+ if (requireGlobal) return { ok: false, principal };
365
+ return { ok: true, principal };
366
+ }
367
+ }
368
+ return { ok: false, principal: "" };
369
+ }
370
+ function bindAgent(principal, agentType) {
371
+ if (authMode() === AUTH_MODE_OFF) return { ok: true, reason: "" };
372
+ const { agents } = resolveAuth();
373
+ if (Object.keys(agents).length === 0) return { ok: true, reason: "" };
374
+ if (!principal.startsWith("agent:")) return { ok: true, reason: "" };
375
+ const bound = principal.slice("agent:".length);
376
+ const claimed = (agentType || "").trim();
377
+ if (!claimed) {
378
+ return { ok: false, reason: `\u8BE5\u51ED\u8BC1\u7ED1\u5B9A\u5230 agent '${bound}'\uFF0C\u8BF7\u6C42\u5FC5\u987B\u58F0\u660E agent_type` };
379
+ }
380
+ if (claimed.toLowerCase() !== bound.toLowerCase()) {
381
+ return { ok: false, reason: `agent_type '${claimed}' \u4E0E\u51ED\u8BC1\u7ED1\u5B9A\u7684 '${bound}' \u4E0D\u4E00\u81F4` };
382
+ }
383
+ return { ok: true, reason: bound };
384
+ }
385
+ function maxBodyBytes() {
386
+ return envInt("AGENT_GATE_MAX_BODY_BYTES", 16 * 1024 * 1024);
387
+ }
388
+ function maxInflight() {
389
+ return poolLimit("biz");
390
+ }
391
+ function maxQueue() {
392
+ return envInt("AGENT_GATE_MAX_QUEUE", 256);
393
+ }
394
+ function maxConnections() {
395
+ return envInt("AGENT_GATE_MAX_CONNECTIONS", 256);
396
+ }
397
+ function keepAliveSec() {
398
+ return envInt("AGENT_GATE_KEEP_ALIVE_SEC", 5);
399
+ }
400
+ function rateLimitQps() {
401
+ return envInt("AGENT_GATE_RATE_LIMIT_QPS", 100);
402
+ }
403
+ function poolOf(path11) {
404
+ if (path11 === "/api/v1/analyze" || path11.startsWith("/api/v1/analyze/")) return "biz";
405
+ if (path11.startsWith("/api/v1/sessions") || path11.startsWith("/api/v1/agents") || path11.startsWith("/api/v1/tool_calls")) return "read";
406
+ if (path11 === "/dashboard" || path11.startsWith("/dashboard/") || path11.startsWith("/ws/")) return "ops";
407
+ if (path11 === "/api/v1/health") return "health";
408
+ return "other";
409
+ }
410
+ function poolLimit(name) {
411
+ let dflt = POOL_DEFAULTS[name] ?? 4;
412
+ if (name === "biz") dflt = envInt("AGENT_GATE_MAX_INFLIGHT", dflt);
413
+ return envInt(`AGENT_GATE_POOL_${name.toUpperCase()}`, dflt);
414
+ }
415
+ function unauthInflight() {
416
+ return envInt("AGENT_GATE_MAX_UNAUTH_INFLIGHT", 4);
417
+ }
418
+ function unauthPerIp() {
419
+ return envInt("AGENT_GATE_MAX_UNAUTH_PER_IP", 2);
420
+ }
421
+ function agentInflight() {
422
+ return envInt("AGENT_GATE_MAX_AGENT_INFLIGHT", 8);
423
+ }
424
+ function bump(kind, key, windowSec, extra) {
425
+ const now = Date.now() / 1e3;
426
+ const k = `${kind}|${key}`;
427
+ let b = counters.get(k);
428
+ if (!b || now - b.start >= windowSec) {
429
+ b = { start: now, n: 0, seen: /* @__PURE__ */ new Set() };
430
+ counters.set(k, b);
431
+ }
432
+ b.n += 1;
433
+ if (extra !== void 0) b.seen.add(extra);
434
+ if (counters.size > 4096) {
435
+ for (const [kk, v] of counters) {
436
+ if (now - v.start >= windowSec) counters.delete(kk);
437
+ }
438
+ }
439
+ return extra !== void 0 ? b.seen.size : b.n;
440
+ }
441
+ function noteSessionAccess(key, sessionId) {
442
+ const threshold = envInt("AGENT_GATE_SESSION_SWEEP_THRESHOLD", 50);
443
+ if (threshold <= 0) return [0, false];
444
+ const window2 = envFloat("AGENT_GATE_SESSION_SWEEP_WINDOW", 300);
445
+ const n = bump("sweep", key, window2, sessionId || "-");
446
+ return [n, n > threshold];
447
+ }
448
+ function sessionSweepAction() {
449
+ return (env("AGENT_GATE_SESSION_SWEEP_ACTION", "log") || "log").toLowerCase();
450
+ }
451
+ function noteQueueReject(key) {
452
+ const threshold = envInt("AGENT_GATE_QUEUE_ABUSE_THRESHOLD", 10);
453
+ if (threshold <= 0) return [0, false];
454
+ const window2 = envFloat("AGENT_GATE_QUEUE_ABUSE_WINDOW", 60);
455
+ const n = bump("queue", key, window2);
456
+ return [n, n > threshold];
457
+ }
458
+ function queueAbuseAction() {
459
+ return (env("AGENT_GATE_QUEUE_ABUSE_ACTION", "log") || "log").toLowerCase();
460
+ }
461
+ function resetCounters() {
462
+ counters.clear();
463
+ tokenCache = null;
464
+ fdTokenCache.clear();
465
+ }
466
+ function hardenFilesEnabled() {
467
+ return TRUTHY.includes(env("AGENT_GATE_HARDEN_FILES", "1").toLowerCase());
468
+ }
469
+ function hardenDbFiles(dbPath) {
470
+ if (!hardenFilesEnabled()) return;
471
+ hardenPermissions(dbPath, 384);
472
+ hardenPermissions(`${dbPath}-wal`, 384);
473
+ hardenPermissions(`${dbPath}-shm`, 384);
474
+ const parent2 = dbPath.replace(/\/[^/]+$/, "");
475
+ if (parent2.endsWith("/agent_gate")) {
476
+ try {
477
+ const st = (0, import_node_fs.statSync)(parent2);
478
+ if (st.uid === process.getuid?.() && ![448, 488].includes(st.mode & 511)) {
479
+ (0, import_node_fs.chmodSync)(parent2, 448);
480
+ }
481
+ } catch {
482
+ }
483
+ }
484
+ }
485
+ function mossTokenPath() {
486
+ const root = env("AGENT_MOSS_DATA_DIR");
487
+ if (root) return (0, import_node_path.join)(root, "auth_token");
488
+ const home = process.env.SUDO_USER && existsDir(`/home/${process.env.SUDO_USER}`) ? `/home/${process.env.SUDO_USER}` : (0, import_node_os.homedir)();
489
+ return (0, import_node_path.join)(home, ".config", "agentmoss", "auth_token");
490
+ }
491
+ function resolveMossToken(force = false) {
492
+ const now = Date.now() / 1e3;
493
+ if (!force && mossTokenCache.expires > now) return mossTokenCache.value;
494
+ let tok = env("AGENT_GATE_MOSS_TOKEN");
495
+ if (!tok) tok = env("AGENT_MOSS_AUTH_TOKEN");
496
+ if (!tok) {
497
+ const f = env("AGENT_MOSS_AUTH_TOKEN_FILE");
498
+ if (f) {
499
+ try {
500
+ tok = (0, import_node_fs.readFileSync)(f, "utf-8").trim();
501
+ } catch {
502
+ tok = "";
503
+ }
504
+ }
505
+ }
506
+ if (!tok) {
507
+ try {
508
+ tok = (0, import_node_fs.readFileSync)(mossTokenPath(), "utf-8").trim();
509
+ } catch {
510
+ tok = "";
511
+ }
512
+ }
513
+ mossTokenCache = { value: tok, expires: now + 60 };
514
+ return tok;
515
+ }
516
+ function describe() {
517
+ let auth;
518
+ const err = authConfigError();
519
+ if (err) {
520
+ auth = `\u26A0\uFE0F \u914D\u7F6E\u9519\u8BEF\uFF08\u62D2\u7EDD\u542F\u52A8\uFF09: ${err}`;
521
+ } else if (authMode() === AUTH_MODE_OFF) {
522
+ auth = "off\uFF08\u4E0D\u9274\u6743\uFF0C\u7B49\u4EF7 0.7.6 \u884C\u4E3A\uFF09";
523
+ } else if (authEnabled()) {
524
+ const agents = Object.keys(agentTokens());
525
+ auth = `auto\uFF08token: ${autoTokenHint()}\uFF09`;
526
+ if (agents.length) auth += `\uFF0C\u6BCF agent \u7ED1\u5B9A: ${agents.sort().join(",")}`;
527
+ } else {
528
+ auth = "auto\uFF08token \u751F\u6210\u5931\u8D25\uFF0C\u672C\u6B21\u4E0D\u9274\u6743\uFF09";
529
+ }
530
+ return `\u5B89\u5168\u7B56\u7565: auth=${auth} | origin_check=${originCheckEnabled() ? "on" : "off"} | \u8BF7\u6C42\u4F53\u4E0A\u9650=${maxBodyBytes()}B | \u9650\u6D41=${rateLimitQps() || "off"}`;
531
+ }
532
+ function autoTokenHint() {
533
+ if (authMode() === AUTH_MODE_OFF) return "-";
534
+ if (env("AGENT_GATE_AUTH_TOKEN")) return "env";
535
+ if (env("AGENT_GATE_AUTH_TOKEN_FD")) return "fd";
536
+ if (env("AGENT_GATE_AUTH_TOKEN_FILE")) return env("AGENT_GATE_AUTH_TOKEN_FILE");
537
+ return authTokenPath();
538
+ }
539
+ var import_node_crypto, import_node_fs, import_node_os, import_node_path, TRUTHY, PUBLIC_PATHS, DASHBOARD_COOKIE, AUTH_MODE_AUTO, AUTH_MODE_OFF, DASHBOARD_SECURITY_HEADERS, tokenCache, fdTokenCache, POOL_DEFAULTS, counters, mossTokenCache, RateLimiter, PooledLimiter;
540
+ var init_security = __esm({
541
+ "src/shared/security.ts"() {
542
+ "use strict";
543
+ init_cjs_shims();
544
+ import_node_crypto = require("crypto");
545
+ import_node_fs = require("fs");
546
+ import_node_os = require("os");
547
+ import_node_path = require("path");
548
+ TRUTHY = ["1", "true", "yes", "on"];
549
+ PUBLIC_PATHS = ["/api/v1/health"];
550
+ DASHBOARD_COOKIE = "agent_gate_token";
551
+ AUTH_MODE_AUTO = "auto";
552
+ AUTH_MODE_OFF = "off";
553
+ DASHBOARD_SECURITY_HEADERS = {
554
+ "Content-Security-Policy": "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
555
+ "X-Frame-Options": "DENY",
556
+ "X-Content-Type-Options": "nosniff",
557
+ "Referrer-Policy": "no-referrer"
558
+ };
559
+ tokenCache = null;
560
+ fdTokenCache = /* @__PURE__ */ new Map();
561
+ POOL_DEFAULTS = { biz: 16, read: 8, ops: 4, health: 4, other: 4 };
562
+ counters = /* @__PURE__ */ new Map();
563
+ mossTokenCache = { value: "", expires: 0 };
564
+ RateLimiter = class {
565
+ constructor(qps, burst) {
566
+ this.qps = qps;
567
+ this.burst = burst;
568
+ this.burst = burst ?? Math.max(qps, 1);
569
+ }
570
+ qps;
571
+ burst;
572
+ buckets = /* @__PURE__ */ new Map();
573
+ get enabled() {
574
+ return this.qps > 0;
575
+ }
576
+ allow(key) {
577
+ const now = Date.now() / 1e3;
578
+ const cur = this.buckets.get(key) ?? { tokens: this.burst, last: now };
579
+ const tokens = Math.min(this.burst, cur.tokens + (now - cur.last) * this.qps);
580
+ if (tokens < 1) {
581
+ this.buckets.set(key, { tokens, last: now });
582
+ return false;
583
+ }
584
+ this.buckets.set(key, { tokens: tokens - 1, last: now });
585
+ return true;
586
+ }
587
+ };
588
+ PooledLimiter = class {
589
+ counts = /* @__PURE__ */ new Map();
590
+ tryAcquire(key, limit) {
591
+ if (limit <= 0) return true;
592
+ const cur = this.counts.get(key) || 0;
593
+ if (cur >= limit) return false;
594
+ this.counts.set(key, cur + 1);
595
+ return true;
596
+ }
597
+ release(key) {
598
+ const cur = this.counts.get(key) || 0;
599
+ if (cur <= 1) this.counts.delete(key);
600
+ else this.counts.set(key, cur - 1);
601
+ }
602
+ };
603
+ }
604
+ });
605
+
66
606
  // src/shared/storage/json-storage.ts
67
607
  var json_storage_exports = {};
68
608
  __export(json_storage_exports, {
@@ -83,6 +623,7 @@ var init_json_storage = __esm({
83
623
  init_cjs_shims();
84
624
  import_fs = require("fs");
85
625
  import_path = require("path");
626
+ init_security();
86
627
  JsonStorage = class {
87
628
  dataDir;
88
629
  agentsPath;
@@ -98,10 +639,39 @@ var init_json_storage = __esm({
98
639
  this.agentsPath = (0, import_path.join)(this.dataDir, "agents.json");
99
640
  this.sessionsPath = (0, import_path.join)(this.dataDir, "sessions.json");
100
641
  this.toolCallsDir = (0, import_path.join)(this.dataDir, "tool_calls");
101
- if (!(0, import_fs.existsSync)(this.dataDir)) (0, import_fs.mkdirSync)(this.dataDir, { recursive: true });
102
- if (!(0, import_fs.existsSync)(this.toolCallsDir)) (0, import_fs.mkdirSync)(this.toolCallsDir, { recursive: true });
642
+ if (!(0, import_fs.existsSync)(this.dataDir)) (0, import_fs.mkdirSync)(this.dataDir, { recursive: true, mode: 448 });
643
+ if (!(0, import_fs.existsSync)(this.toolCallsDir)) (0, import_fs.mkdirSync)(this.toolCallsDir, { recursive: true, mode: 448 });
644
+ this.hardenStoragePermissions();
103
645
  this.nextId = this.recoverNextId();
104
646
  }
647
+ /** 把存储目录收紧到 0700、已有 JSON 文件收紧到 0600。
648
+ * 新建文件由 `writeJsonFile` 的 mode 保证;这里处理**存量**文件
649
+ * (旧版本按 umask 创建的 0644)以及 mkdirSync 对已存在目录不生效的问题。 */
650
+ hardenStoragePermissions() {
651
+ if (!hardenFilesEnabled()) return;
652
+ const uid = process.getuid?.();
653
+ const tighten = (p, mode) => {
654
+ try {
655
+ const st = (0, import_fs.statSync)(p);
656
+ if (st.isSymbolicLink()) return;
657
+ if (uid !== void 0 && st.uid !== uid) return;
658
+ if ((st.mode & 511) !== mode) (0, import_fs.chmodSync)(p, mode);
659
+ } catch {
660
+ }
661
+ };
662
+ tighten(this.dataDir, 448);
663
+ tighten(this.toolCallsDir, 448);
664
+ tighten(this.agentsPath, 384);
665
+ tighten(this.sessionsPath, 384);
666
+ try {
667
+ for (const f of (0, import_fs.readdirSync)(this.toolCallsDir)) {
668
+ if (f.endsWith(".json") || f.endsWith(".tmp")) {
669
+ tighten((0, import_path.join)(this.toolCallsDir, f), 384);
670
+ }
671
+ }
672
+ } catch {
673
+ }
674
+ }
105
675
  /** 扫描所有 tool_calls 文件,找到最大 id + 1 */
106
676
  recoverNextId() {
107
677
  let maxId = 0;
@@ -125,12 +695,12 @@ var init_json_storage = __esm({
125
695
  return fallback2;
126
696
  }
127
697
  }
128
- /** 原子写入:先写 .tmp 再 rename */
698
+ /** 原子写入:先写 .tmp 再 rename(rename 保留 tmp 的 0600 权限) */
129
699
  writeJsonFile(path11, data) {
130
700
  const dir2 = (0, import_path.dirname)(path11);
131
- if (!(0, import_fs.existsSync)(dir2)) (0, import_fs.mkdirSync)(dir2, { recursive: true });
701
+ if (!(0, import_fs.existsSync)(dir2)) (0, import_fs.mkdirSync)(dir2, { recursive: true, mode: 448 });
132
702
  const tmp = path11 + ".tmp";
133
- (0, import_fs.writeFileSync)(tmp, JSON.stringify(data, null, 2), "utf-8");
703
+ (0, import_fs.writeFileSync)(tmp, JSON.stringify(data, null, 2), { encoding: "utf-8", mode: 384 });
134
704
  (0, import_fs.renameSync)(tmp, path11);
135
705
  }
136
706
  loadAgents() {
@@ -244,6 +814,9 @@ var init_json_storage = __esm({
244
814
  } catch {
245
815
  }
246
816
  }
817
+ if (params.agentType) {
818
+ allRecords = allRecords.filter((r) => r.agent_type === params.agentType);
819
+ }
247
820
  if (params.decision) {
248
821
  allRecords = allRecords.filter((r) => r.decision === params.decision);
249
822
  }
@@ -254,6 +827,7 @@ var init_json_storage = __esm({
254
827
  }
255
828
  countToolCalls(params) {
256
829
  const sessions = this.loadSessions();
830
+ const agents = this.loadAgents();
257
831
  let allRecords = [];
258
832
  try {
259
833
  const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
@@ -263,6 +837,12 @@ var init_json_storage = __esm({
263
837
  }
264
838
  } catch {
265
839
  }
840
+ if (params.agentType) {
841
+ const allowed = new Set(
842
+ [...sessions.values()].filter((s) => (agents.get(s.agent_id)?.agent_type || "") === params.agentType).map((s) => s.id)
843
+ );
844
+ allRecords = allRecords.filter((r) => allowed.has(r.session_id));
845
+ }
266
846
  if (params.decision) {
267
847
  allRecords = allRecords.filter((r) => r.decision === params.decision);
268
848
  }
@@ -308,11 +888,12 @@ var init_json_storage = __esm({
308
888
  hostname: agent?.hostname || ""
309
889
  };
310
890
  }
311
- getAgentsList() {
891
+ getAgentsList(agentType) {
312
892
  const agents = this.loadAgents();
313
893
  const sessions = this.loadSessions();
314
894
  const result = [];
315
895
  for (const agent of agents.values()) {
896
+ if (agentType && agent.agent_type !== agentType) continue;
316
897
  let sessionCount = 0;
317
898
  let callCount = 0;
318
899
  for (const session of sessions.values()) {
@@ -333,6 +914,11 @@ var init_json_storage = __esm({
333
914
  result.sort((a, b) => b.call_count - a.call_count);
334
915
  return result.slice(0, 20);
335
916
  }
917
+ getSessionAgentType(sessionId) {
918
+ const session = this.loadSessions().get(sessionId);
919
+ if (!session) return void 0;
920
+ return this.loadAgents().get(session.agent_id)?.agent_type;
921
+ }
336
922
  getTimeline(limit = 100) {
337
923
  const buckets = /* @__PURE__ */ new Map();
338
924
  try {
@@ -516,6 +1102,10 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
516
1102
  conditions.push("tc.session_id = ?");
517
1103
  values.push(params.sessionId);
518
1104
  }
1105
+ if (params.agentType) {
1106
+ conditions.push("a.agent_type = ?");
1107
+ values.push(params.agentType);
1108
+ }
519
1109
  if (params.decision) {
520
1110
  conditions.push("tc.decision = ?");
521
1111
  values.push(params.decision);
@@ -538,9 +1128,16 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
538
1128
  conditions.push("tc.decision = ?");
539
1129
  values.push(params.decision);
540
1130
  }
1131
+ if (params.agentType) {
1132
+ conditions.push("a.agent_type = ?");
1133
+ values.push(params.agentType);
1134
+ }
541
1135
  const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
542
1136
  const row = this.db.prepare(
543
- `SELECT COUNT(*) as total FROM tool_calls tc ${where}`
1137
+ `SELECT COUNT(*) as total FROM tool_calls tc
1138
+ LEFT JOIN sessions s ON tc.session_id = s.id
1139
+ LEFT JOIN agents a ON s.agent_id = a.id
1140
+ ${where}`
544
1141
  ).get(...values);
545
1142
  return row?.total ?? 0;
546
1143
  }
@@ -548,11 +1145,11 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
548
1145
  const row = this.db.prepare("SELECT COUNT(*) as total FROM tool_calls").get();
549
1146
  let dbBytes = 0;
550
1147
  try {
551
- const { statSync: statSync9, existsSync: existsSync12 } = require("fs");
552
- dbBytes = statSync9(this.dbPath).size;
1148
+ const { statSync: statSync10, existsSync: existsSync12 } = require("fs");
1149
+ dbBytes = statSync10(this.dbPath).size;
553
1150
  for (const suffix of ["-wal", "-shm"]) {
554
1151
  const p = this.dbPath + suffix;
555
- if (existsSync12(p)) dbBytes += statSync9(p).size;
1152
+ if (existsSync12(p)) dbBytes += statSync10(p).size;
556
1153
  }
557
1154
  } catch {
558
1155
  }
@@ -566,7 +1163,8 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
566
1163
  })();
567
1164
  return result;
568
1165
  }
569
- getAgentsList() {
1166
+ getAgentsList(agentType) {
1167
+ const where = agentType ? "WHERE a.agent_type = ?" : "";
570
1168
  return this.db.prepare(`
571
1169
  SELECT a.agent_type, a.hostname, a.agent_version as version,
572
1170
  COUNT(DISTINCT s.id) as session_count,
@@ -574,10 +1172,19 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
574
1172
  FROM agents a
575
1173
  LEFT JOIN sessions s ON s.agent_id = a.id
576
1174
  LEFT JOIN tool_calls tc ON tc.session_id = s.id
1175
+ ${where}
577
1176
  GROUP BY a.id
578
1177
  ORDER BY call_count DESC
579
1178
  LIMIT 20
580
- `).all();
1179
+ `).all(...agentType ? [agentType] : []);
1180
+ }
1181
+ getSessionAgentType(sessionId) {
1182
+ const row = this.db.prepare(
1183
+ `SELECT a.agent_type as agent_type
1184
+ FROM sessions s JOIN agents a ON s.agent_id = a.id
1185
+ WHERE s.id = ?`
1186
+ ).get(sessionId);
1187
+ return row?.agent_type;
581
1188
  }
582
1189
  getTimeline(limit = 100) {
583
1190
  const rows = this.db.prepare(`
@@ -646,14 +1253,14 @@ function getDb(dbPath) {
646
1253
  if (rawDb) return rawDb;
647
1254
  try {
648
1255
  const Database = require("better-sqlite3");
649
- const { existsSync: existsSync12, mkdirSync: mkdirSync4 } = require("fs");
650
- const { join: join11, dirname: dirname5 } = require("path");
1256
+ const { existsSync: existsSync12, mkdirSync: mkdirSync5 } = require("fs");
1257
+ const { join: join12, dirname: dirname5 } = require("path");
651
1258
  const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
652
- const xdgData = process.env.XDG_DATA_HOME || join11(home, ".local", "share");
653
- const defaultPath = join11(xdgData, "agent_gate", "agent_gate_ts.db");
1259
+ const xdgData = process.env.XDG_DATA_HOME || join12(home, ".local", "share");
1260
+ const defaultPath = join12(xdgData, "agent_gate", "agent_gate_ts.db");
654
1261
  const path11 = dbPath || defaultPath;
655
1262
  const dir2 = dirname5(path11);
656
- if (!existsSync12(dir2)) mkdirSync4(dir2, { recursive: true });
1263
+ if (!existsSync12(dir2)) mkdirSync5(dir2, { recursive: true });
657
1264
  rawDb = new Database(path11);
658
1265
  rawDb.pragma("journal_mode = WAL");
659
1266
  return rawDb;
@@ -698,20 +1305,34 @@ var init_db = __esm({
698
1305
 
699
1306
  // src/shared/multi-session.ts
700
1307
  function isMultiSessionEnabled() {
701
- return process.env.AGENT_GATE_MULTI_SESSION === "1";
1308
+ const raw = (process.env.AGENT_GATE_MULTI_SESSION ?? "").trim().toLowerCase();
1309
+ if (raw === "") return true;
1310
+ return !MULTI_SESSION_OFF_VALUES.has(raw);
1311
+ }
1312
+ function sessionHistoryLimit() {
1313
+ const raw = (process.env.AGENT_GATE_SESSION_HISTORY_LIMIT ?? "").trim();
1314
+ const n = raw ? parseInt(raw, 10) : DEFAULT_MAX_SESSIONS;
1315
+ const v = Number.isFinite(n) ? n : DEFAULT_MAX_SESSIONS;
1316
+ return Math.max(1, Math.min(v, 50));
702
1317
  }
703
1318
  function buildSessionHistory(queryToolCalls2, sessionId) {
704
1319
  if (!isMultiSessionEnabled()) return [];
1320
+ const maxSessions = sessionHistoryLimit();
705
1321
  try {
706
- const recent = queryToolCalls2({ limit: DEFAULT_HISTORY_LIMIT });
1322
+ const scanLimit = Math.max(DEFAULT_HISTORY_LIMIT, maxSessions * DEFAULT_ACTIONS_PER_SESSION);
1323
+ const recent = queryToolCalls2({ limit: scanLimit });
707
1324
  const bySession = /* @__PURE__ */ new Map();
708
1325
  for (const tc of recent) {
709
1326
  if (tc.session_id === sessionId) continue;
710
1327
  const list = bySession.get(tc.session_id) || [];
711
- list.unshift({ action_type: tc.action_type, action_detail: tc.action_detail });
1328
+ list.unshift({
1329
+ action_type: tc.action_type,
1330
+ action_detail: tc.action_detail,
1331
+ ...tc.called_at ? { called_at: tc.called_at } : {}
1332
+ });
712
1333
  bySession.set(tc.session_id, list);
713
1334
  }
714
- return [...bySession.entries()].slice(0, DEFAULT_MAX_SESSIONS).map(([sid, actions]) => ({
1335
+ return [...bySession.entries()].slice(0, maxSessions).map(([sid, actions]) => ({
715
1336
  session_id: sid,
716
1337
  action_history: actions.slice(0, DEFAULT_ACTIONS_PER_SESSION)
717
1338
  }));
@@ -722,7 +1343,7 @@ function buildSessionHistory(queryToolCalls2, sessionId) {
722
1343
  function isStatefulIncrementalEnabled() {
723
1344
  return isMultiSessionEnabled();
724
1345
  }
725
- var DEFAULT_HISTORY_LIMIT, DEFAULT_MAX_SESSIONS, DEFAULT_ACTIONS_PER_SESSION;
1346
+ var DEFAULT_HISTORY_LIMIT, DEFAULT_MAX_SESSIONS, DEFAULT_ACTIONS_PER_SESSION, MULTI_SESSION_OFF_VALUES;
726
1347
  var init_multi_session = __esm({
727
1348
  "src/shared/multi-session.ts"() {
728
1349
  "use strict";
@@ -730,17 +1351,25 @@ var init_multi_session = __esm({
730
1351
  DEFAULT_HISTORY_LIMIT = 500;
731
1352
  DEFAULT_MAX_SESSIONS = 5;
732
1353
  DEFAULT_ACTIONS_PER_SESSION = 100;
1354
+ MULTI_SESSION_OFF_VALUES = /* @__PURE__ */ new Set(["0", "false", "no", "off"]);
733
1355
  }
734
1356
  });
735
1357
 
736
1358
  // src/shared/moss-client.ts
737
1359
  var moss_client_exports = {};
738
1360
  __export(moss_client_exports, {
1361
+ authHeaders: () => authHeaders,
739
1362
  callAgentMoss: () => callAgentMoss,
740
1363
  callAgentMossReview: () => callAgentMossReview,
741
1364
  fetchMossHealth: () => fetchMossHealth,
742
1365
  setMossUrl: () => setMossUrl
743
1366
  });
1367
+ function authHeaders() {
1368
+ const h = { "Content-Type": "application/json" };
1369
+ const tok = resolveMossToken();
1370
+ if (tok) h["Authorization"] = `Bearer ${tok}`;
1371
+ return h;
1372
+ }
744
1373
  function setMossUrl(url) {
745
1374
  mossUrl = url;
746
1375
  }
@@ -750,14 +1379,23 @@ async function callAgentMoss(request3) {
750
1379
  if (isStatefulIncrementalEnabled() && req && typeof req === "object" && req.metadata === void 0) {
751
1380
  req.metadata = { stateful_incremental: true };
752
1381
  }
753
- const resp = await (0, import_node_fetch.default)(`${mossUrl}/api/v1/analyze`, {
1382
+ const body = JSON.stringify(req);
1383
+ let resp = await (0, import_node_fetch.default)(`${mossUrl}/api/v1/analyze`, {
754
1384
  method: "POST",
755
- headers: { "Content-Type": "application/json" },
756
- body: JSON.stringify(req),
757
- // 100s:覆盖 AgentMoss 总超时(90s)+ 余量,避免 AgentMoss 还在分析时
758
- // 被 AgentGate 抢断后 fail-closed 误杀。AgentGate 这层不重试(AgentMoss 内部已重试)。
1385
+ headers: authHeaders(),
1386
+ body,
759
1387
  timeout: 1e5
760
1388
  });
1389
+ if (resp.status === 401) {
1390
+ console.warn("[AgentGate] AgentMoss \u8FD4\u56DE 401\uFF0C\u5DF2\u91CD\u65B0\u8BFB\u53D6\u8BBF\u95EE token\uFF0C\u91CD\u8BD5\u4E00\u6B21");
1391
+ resolveMossToken(true);
1392
+ resp = await (0, import_node_fetch.default)(`${mossUrl}/api/v1/analyze`, {
1393
+ method: "POST",
1394
+ headers: authHeaders(),
1395
+ body,
1396
+ timeout: 1e5
1397
+ });
1398
+ }
761
1399
  if (!resp.ok) {
762
1400
  console.error(`[AgentGate] AgentMoss HTTP ${resp.status}: ${resp.statusText}`);
763
1401
  return failClosedResponse(`AgentMoss returned ${resp.status}`);
@@ -797,7 +1435,7 @@ async function callAgentMossReview(options) {
797
1435
  try {
798
1436
  const resp = await (0, import_node_fetch.default)(`${mossUrl}/api/v1/review`, {
799
1437
  method: "POST",
800
- headers: { "Content-Type": "application/json" },
1438
+ headers: authHeaders(),
801
1439
  body: JSON.stringify({ agent_id: agentId, db_path: dbPath }),
802
1440
  timeout: 3e4
803
1441
  });
@@ -825,8 +1463,9 @@ var init_moss_client = __esm({
825
1463
  init_cjs_shims();
826
1464
  import_node_fetch = __toESM(require("node-fetch"));
827
1465
  init_multi_session();
1466
+ init_security();
828
1467
  DEFAULT_MOSS_URL = "http://127.0.0.1:9090";
829
- mossUrl = DEFAULT_MOSS_URL;
1468
+ mossUrl = process.env.AGENT_MOSS_URL || process.env.MOSS_URL || DEFAULT_MOSS_URL;
830
1469
  }
831
1470
  });
832
1471
 
@@ -901,7 +1540,8 @@ var init_models = __esm({
901
1540
  status: import_zod.z.string().default("healthy"),
902
1541
  version: import_zod.z.string().default(version),
903
1542
  moss_version: import_zod.z.string().default("N/A"),
904
- moss_status: import_zod.z.string().default("unknown")
1543
+ moss_status: import_zod.z.string().default("unknown"),
1544
+ instance: import_zod.z.string().default("")
905
1545
  });
906
1546
  }
907
1547
  });
@@ -1113,12 +1753,15 @@ function getStorageStats() {
1113
1753
  function clearToolCalls() {
1114
1754
  return store().clearToolCalls();
1115
1755
  }
1116
- function getAgentsList() {
1117
- return store().getAgentsList();
1756
+ function getAgentsList(agentType) {
1757
+ return store().getAgentsList(agentType);
1118
1758
  }
1119
1759
  function getTimeline(limit) {
1120
1760
  return store().getTimeline(limit);
1121
1761
  }
1762
+ function getSessionAgentType(sessionId) {
1763
+ return store().getSessionAgentType(sessionId);
1764
+ }
1122
1765
  var init_repository = __esm({
1123
1766
  "src/shared/storage/repository.ts"() {
1124
1767
  "use strict";
@@ -1148,7 +1791,11 @@ async function healthRoute(c) {
1148
1791
  status: "healthy",
1149
1792
  version,
1150
1793
  moss_version: mossHealth.moss_version,
1151
- moss_status: mossHealth.moss_status
1794
+ moss_status: mossHealth.moss_status,
1795
+ // 归属标识:由启动方注入 AGENT_GATE_INSTANCE(同机多套 AgentGate 时用于区分是谁起的),
1796
+ // 未注入时为空串。与 agent-moss 的 AGENT_MOSS_INSTANCE 同一套约定,供探测端在
1797
+ // /proc 不可读、无法做 PID↔端口校验时退化为按实例字符串判归属。
1798
+ instance: process.env.AGENT_GATE_INSTANCE || ""
1152
1799
  });
1153
1800
  }
1154
1801
  function storageOversizeInfo() {
@@ -1162,6 +1809,12 @@ async function analyzeRoute(c) {
1162
1809
  try {
1163
1810
  const body = await c.req.json();
1164
1811
  const input = AgentGateInputSchema.parse(body);
1812
+ const principal = c.get("principal") || "";
1813
+ const bind = bindAgent(principal, input.agent_type || "");
1814
+ if (!bind.ok) {
1815
+ console.warn(`[AgentGate] \u62D2\u7EDD\u8EAB\u4EFD\u4E0D\u5339\u914D\u7684\u8BF7\u6C42: principal=${principal} claimed=${input.agent_type}`);
1816
+ return c.json({ detail: bind.reason }, 403);
1817
+ }
1165
1818
  const toolName = input.tool_name || input.a_next?.action_type || "unknown";
1166
1819
  const command = input.command || input.a_next?.action_detail || "";
1167
1820
  const key = cacheKey(input.session_id, input.cwd, command);
@@ -1242,7 +1895,22 @@ async function analyzeRoute(c) {
1242
1895
  }
1243
1896
  }
1244
1897
  async function sessionsRoute(c) {
1245
- const sessionId = c.req.param("id");
1898
+ const sessionId = c.req.param("id") || "";
1899
+ const principal = c.get("principal") || "ip:unknown";
1900
+ const [n, hit] = noteSessionAccess(principal, sessionId);
1901
+ if (hit) {
1902
+ if (sessionSweepAction() === "deny") {
1903
+ return c.json({ detail: "\u4F1A\u8BDD\u8BBF\u95EE\u8FC7\u4E8E\u96C6\u4E2D\uFF0C\u7591\u4F3C\u6279\u91CF\u626B\u63CF" }, 429);
1904
+ }
1905
+ console.warn(`[AgentGate] \u26A0\uFE0F \u7591\u4F3C\u8DE8\u4F1A\u8BDD\u626B\u63CF: key=${principal} \u7A97\u53E3\u5185\u8BBF\u95EE\u4E86 ${n} \u4E2A\u4E0D\u540C session`);
1906
+ }
1907
+ const bound = boundAgentOf(c.get("principal") || "");
1908
+ if (bound) {
1909
+ const owner = getSessionAgentType(sessionId);
1910
+ if ((owner || "").toLowerCase() !== bound.toLowerCase()) {
1911
+ return c.json({ detail: "\u8BE5\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u5F53\u524D\u51ED\u8BC1\u7ED1\u5B9A\u7684 agent" }, 403);
1912
+ }
1913
+ }
1246
1914
  const rows = queryToolCalls({ sessionId, limit: 100 });
1247
1915
  return c.json({ session_id: sessionId, tool_calls: rows });
1248
1916
  }
@@ -1250,26 +1918,38 @@ async function toolCallsRoute(c) {
1250
1918
  const decision = c.req.query("decision");
1251
1919
  const limit = parseInt(c.req.query("limit") || "50", 10);
1252
1920
  const offset = parseInt(c.req.query("offset") || "0", 10);
1253
- const total = countToolCalls({ decision });
1254
- const data = queryToolCalls({ decision, limit, offset });
1921
+ const bound = boundAgentOf(c.get("principal") || "");
1922
+ const agentType = bound || void 0;
1923
+ const total = countToolCalls({ decision: decision ?? void 0, agentType });
1924
+ const data = queryToolCalls({ decision: decision ?? void 0, agentType, limit, offset });
1255
1925
  return c.json({ total, data });
1256
1926
  }
1257
1927
  async function agentsRoute(c) {
1258
- const agents = getAgentsList();
1928
+ const bound = boundAgentOf(c.get("principal") || "");
1929
+ const agents = getAgentsList(bound || void 0);
1259
1930
  return c.json(agents);
1260
1931
  }
1261
1932
  async function timelineRoute(c) {
1933
+ if (boundAgentOf(c.get("principal") || "")) {
1934
+ return c.json({ detail: "\u8BE5\u51ED\u8BC1\u7ED1\u5B9A\u5230 agent\uFF0C\u65E0\u6743\u67E5\u770B\u5168\u5C40\u65F6\u95F4\u7EBF" }, 403);
1935
+ }
1262
1936
  const limit = parseInt(c.req.query("limit") || "100", 10);
1263
1937
  const rows = getTimeline(limit);
1264
1938
  return c.json(rows);
1265
1939
  }
1266
1940
  function storageStatsRoute(c) {
1941
+ if (boundAgentOf(c.get("principal") || "")) {
1942
+ return c.json({ detail: "\u8BE5\u51ED\u8BC1\u7ED1\u5B9A\u5230 agent\uFF0C\u65E0\u6743\u67E5\u770B\u5B58\u50A8\u7EDF\u8BA1" }, 403);
1943
+ }
1267
1944
  const storageStats = getStorageStats();
1268
1945
  const defaultThreshold = parseFloat(process.env.AGENT_GATE_CLEANUP_THRESHOLD_MB || "100");
1269
1946
  const totalMB = (storageStats.dbBytes + storageStats.jsonBytes) / 1024 / 1024;
1270
1947
  return c.json({ stats: storageStats, oversize: totalMB > defaultThreshold, thresholdMB: defaultThreshold });
1271
1948
  }
1272
1949
  function deleteToolCallsRoute(c) {
1950
+ if (boundAgentOf(c.get("principal") || "")) {
1951
+ return c.json({ detail: "\u8BE5\u51ED\u8BC1\u7ED1\u5B9A\u5230 agent\uFF0C\u65E0\u6743\u6E05\u7406\u8BB0\u5F55" }, 403);
1952
+ }
1273
1953
  const deleted = clearToolCalls();
1274
1954
  return c.json({ deleted });
1275
1955
  }
@@ -1286,6 +1966,7 @@ var init_routes = __esm({
1286
1966
  init_repository();
1287
1967
  init_multi_session();
1288
1968
  init_agent_identity();
1969
+ init_security();
1289
1970
  init_version();
1290
1971
  v1ReviewCounter = 0;
1291
1972
  }
@@ -1298,8 +1979,97 @@ __export(server_exports, {
1298
1979
  });
1299
1980
  function createApp() {
1300
1981
  const app = new import_hono.Hono();
1301
- app.use("*", (0, import_cors.cors)({ origin: "*", allowMethods: ["GET", "POST", "OPTIONS", "DELETE"], allowHeaders: ["*"] }));
1982
+ const rateLimiter = new RateLimiter(rateLimitQps());
1983
+ const pools = new PooledLimiter();
1984
+ app.use("*", (0, import_cors.cors)({
1985
+ origin: (origin) => allowedOrigins().includes(normalizeOrigin(origin)) ? origin : null,
1986
+ allowMethods: ["GET", "POST", "OPTIONS", "DELETE"],
1987
+ allowHeaders: ["*"]
1988
+ }));
1302
1989
  app.use("*", (0, import_logger.logger)());
1990
+ app.use("*", async (c, next) => {
1991
+ const path11 = new URL(c.req.url).pathname;
1992
+ const method = c.req.method.toUpperCase();
1993
+ if (method === "OPTIONS") return next();
1994
+ const cl = c.req.header("content-length");
1995
+ const maxBody = maxBodyBytes();
1996
+ if (cl && maxBody > 0) {
1997
+ const n = parseInt(cl, 10);
1998
+ if (Number.isFinite(n) && n > maxBody) {
1999
+ return c.json({ detail: `\u8BF7\u6C42\u4F53\u8D85\u8FC7\u4E0A\u9650 ${maxBody} \u5B57\u8282` }, 413);
2000
+ }
2001
+ }
2002
+ if (originCheckEnabled()) {
2003
+ const origin = c.req.header("origin") || "";
2004
+ if (origin && !originAllowed(origin, c.req.header("host") || "")) {
2005
+ console.warn(`[AgentGate] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path11}`);
2006
+ return c.json({ detail: `\u8DE8\u6E90\u6765\u6E90\u672A\u88AB\u5141\u8BB8: ${origin}` }, 403);
2007
+ }
2008
+ }
2009
+ const headers = { authorization: c.req.header("authorization") };
2010
+ const cookie = (0, import_cookie.getCookie)(c, DASHBOARD_COOKIE) || "";
2011
+ const requireGlobal = path11.startsWith("/dashboard") || path11.startsWith("/ws/");
2012
+ const { ok, principal } = checkRequestAuth(headers, path11, cookie, requireGlobal);
2013
+ if (!ok && !PUBLIC_PAGE_PATHS.includes(path11)) {
2014
+ if (boundAgentOf(principal)) {
2015
+ return c.json({ detail: "\u8BE5\u51ED\u8BC1\u7ED1\u5B9A\u5230 agent\uFF0C\u65E0\u6743\u8BBF\u95EE\u770B\u677F\uFF1B\u8BF7\u4F7F\u7528\u5168\u5C40 token" }, 403);
2016
+ }
2017
+ c.header("WWW-Authenticate", "Bearer");
2018
+ return c.json({ detail: "Unauthorized: invalid or missing Bearer token" }, 401);
2019
+ }
2020
+ c.set("principal", principal);
2021
+ if (rateLimiter.enabled) {
2022
+ const key = principal || `ip:${c.req.header("x-forwarded-for") || "unknown"}`;
2023
+ if (!rateLimiter.allow(key)) {
2024
+ c.header("Retry-After", "1");
2025
+ return c.json({ detail: "\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" }, 429);
2026
+ }
2027
+ }
2028
+ const ip = c.req.header("x-forwarded-for") || "unknown";
2029
+ const keys = [];
2030
+ const take = (key, limit) => {
2031
+ if (pools.tryAcquire(key, limit)) {
2032
+ keys.push(key);
2033
+ return true;
2034
+ }
2035
+ return false;
2036
+ };
2037
+ const busy = (detail, status = 503) => {
2038
+ c.header("Retry-After", "1");
2039
+ c.header("Connection", "close");
2040
+ return c.json({ detail }, status);
2041
+ };
2042
+ try {
2043
+ if (!principal && authEnabled()) {
2044
+ if (!take("unauth:total", unauthInflight())) {
2045
+ return busy("\u672A\u8BA4\u8BC1\u8BF7\u6C42\u5E76\u53D1\u8D85\u9650\uFF0C\u8BF7\u6301\u51ED\u8BC1\u8BBF\u95EE");
2046
+ }
2047
+ if (!take(`unauth:ip:${ip}`, unauthPerIp())) {
2048
+ return busy("\u8BE5\u6765\u6E90\u7684\u672A\u8BA4\u8BC1\u8BF7\u6C42\u5E76\u53D1\u8D85\u9650");
2049
+ }
2050
+ } else {
2051
+ const bound = boundAgentOf(principal);
2052
+ if (bound && !take(`agent:${bound}`, agentInflight())) {
2053
+ return busy(`agent '${bound}' \u7684\u5E76\u53D1\u8D85\u9650\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`, 429);
2054
+ }
2055
+ }
2056
+ const pool = poolOf(path11);
2057
+ if (!take(`pool:${pool}`, poolLimit(pool))) {
2058
+ const qkey = principal || `ip:${ip}`;
2059
+ const [n, abusive] = noteQueueReject(qkey);
2060
+ if (abusive && queueAbuseAction() === "deny") {
2061
+ return busy("\u5E76\u53D1\u62D2\u7EDD\u8FC7\u4E8E\u9891\u7E41\uFF0C\u7591\u4F3C\u6076\u610F\u8BF7\u6C42", 429);
2062
+ }
2063
+ if (abusive) {
2064
+ console.warn(`[AgentGate] \u26A0\uFE0F \u7591\u4F3C\u6076\u610F\u5E76\u53D1\u5360\u7528: key=${qkey} \u7A97\u53E3\u5185\u88AB\u62D2 ${n} \u6B21`);
2065
+ }
2066
+ return busy("\u670D\u52A1\u7E41\u5FD9\uFF08\u5E76\u53D1\u5DF2\u6EE1\uFF09\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");
2067
+ }
2068
+ return await next();
2069
+ } finally {
2070
+ while (keys.length) pools.release(keys.pop());
2071
+ }
2072
+ });
1303
2073
  app.get("/api/v1/health", healthRoute);
1304
2074
  app.post("/api/v1/analyze", analyzeRoute);
1305
2075
  app.get("/api/v1/sessions/:id/traces", sessionsRoute);
@@ -1313,7 +2083,26 @@ function createApp() {
1313
2083
  return app;
1314
2084
  }
1315
2085
  async function dashboardRoute(c) {
1316
- const { readFileSync: readFileSync13, existsSync: existsSync12 } = await import("fs");
2086
+ if (authEnabled()) {
2087
+ const token = c.req.query("token") || "";
2088
+ if (token && isGlobalToken(token)) {
2089
+ (0, import_cookie.setCookie)(c, DASHBOARD_COOKIE, token, {
2090
+ httpOnly: true,
2091
+ sameSite: "Strict",
2092
+ path: "/"
2093
+ });
2094
+ c.header("Referrer-Policy", "no-referrer");
2095
+ return c.redirect("/dashboard/", 302);
2096
+ }
2097
+ const cookie = (0, import_cookie.getCookie)(c, DASHBOARD_COOKIE) || "";
2098
+ if (!isGlobalToken(cookie)) {
2099
+ if (token && checkToken(token) || cookie && checkToken(cookie)) {
2100
+ return c.html(AGENT_FORBIDDEN_HTML, 403, DASHBOARD_SECURITY_HEADERS);
2101
+ }
2102
+ return c.html(UNAUTHORIZED_HTML, 401, DASHBOARD_SECURITY_HEADERS);
2103
+ }
2104
+ }
2105
+ const { readFileSync: readFileSync14, existsSync: existsSync12 } = await import("fs");
1317
2106
  const { resolve: resolve3, dirname: dirname5 } = await import("path");
1318
2107
  const { fileURLToPath } = await import("url");
1319
2108
  const __dirname2 = dirname5(fileURLToPath(importMetaUrl));
@@ -1323,10 +2112,10 @@ async function dashboardRoute(c) {
1323
2112
  resolve3(__dirname2, "../src/v1/dashboard.html")
1324
2113
  ];
1325
2114
  const htmlPath = paths.find((p) => existsSync12(p)) || paths[0];
1326
- const html = readFileSync13(htmlPath, "utf-8");
1327
- return c.html(html);
2115
+ const html = readFileSync14(htmlPath, "utf-8");
2116
+ return c.html(html, 200, DASHBOARD_SECURITY_HEADERS);
1328
2117
  }
1329
- var import_hono, import_cors, import_logger;
2118
+ var import_hono, import_cors, import_logger, import_cookie, PUBLIC_PAGE_PATHS, UNAUTHORIZED_HTML, AGENT_FORBIDDEN_HTML;
1330
2119
  var init_server = __esm({
1331
2120
  "src/v1/server.ts"() {
1332
2121
  "use strict";
@@ -1334,7 +2123,40 @@ var init_server = __esm({
1334
2123
  import_hono = require("hono");
1335
2124
  import_cors = require("hono/cors");
1336
2125
  import_logger = require("hono/logger");
2126
+ import_cookie = require("hono/cookie");
1337
2127
  init_routes();
2128
+ init_security();
2129
+ PUBLIC_PAGE_PATHS = ["/dashboard", "/dashboard/"];
2130
+ UNAUTHORIZED_HTML = `<!DOCTYPE html>
2131
+ <html lang="zh-CN"><head><meta charset="UTF-8"><title>AgentGate Dashboard</title>
2132
+ <style>body{font:14px/1.6 -apple-system,'Segoe UI',sans-serif;background:#FAFAFA;color:#1d1d1f;
2133
+ display:flex;align-items:center;justify-content:center;height:100vh;margin:0}
2134
+ .box{background:#fff;border:1px solid #eee;border-radius:10px;padding:28px 32px;max-width:560px}
2135
+ code{background:#F5F5F7;padding:1px 6px;border-radius:4px;font-size:13px}
2136
+ p{margin:8px 0;color:#555}</style></head><body>
2137
+ <div class="box">
2138
+ <h3 style="margin-top:0">\u9700\u8981\u8BBF\u95EE\u51ED\u8BC1</h3>
2139
+ <p>Dashboard \u73B0\u5728\u9700\u8981\u4EE4\u724C\u3002\u6D4F\u89C8\u5668\u65E0\u6CD5\u81EA\u52A8\u5E26\u4E0A <code>Authorization</code> \u5934\uFF0C\u8BF7\u7528\u4E0B\u9762\u8FD9\u79CD\u5730\u5740\u6253\u5F00\u4E00\u6B21\uFF1A</p>
2140
+ <p><code>/dashboard/?token=&lt;token&gt;</code></p>
2141
+ <p>\u4EE4\u724C\u4F4D\u7F6E\uFF1A<code>~/.config/agentgate/auth_token</code>\uFF08\u6216\u542F\u52A8\u65E5\u5FD7\u91CC\u6253\u5370\u7684\u90A3\u4E00\u884C\uFF09\u3002
2142
+ \u6362 Cookie \u540E\u5C31\u53EA\u9700\u6253\u5F00 <code>/dashboard/</code>\u3002</p>
2143
+ <p>\u5982\u9700\u6062\u590D\u65E7\u884C\u4E3A\uFF1A<code>AGENT_GATE_AUTH_MODE=off</code>\u3002</p>
2144
+ </div></body></html>`;
2145
+ AGENT_FORBIDDEN_HTML = `<!DOCTYPE html>
2146
+ <html lang="zh-CN"><head><meta charset="UTF-8"><title>AgentGate Dashboard</title>
2147
+ <style>body{font:14px/1.6 -apple-system,'Segoe UI',sans-serif;background:#FAFAFA;color:#1d1d1f;
2148
+ display:flex;align-items:center;justify-content:center;height:100vh;margin:0}
2149
+ .box{background:#fff;border:1px solid #eee;border-radius:10px;padding:28px 32px;max-width:560px}
2150
+ code{background:#F5F5F7;padding:1px 6px;border-radius:4px;font-size:13px}
2151
+ p{margin:8px 0;color:#555}</style></head><body>
2152
+ <div class="box">
2153
+ <h3 style="margin-top:0">\u8BE5\u51ED\u8BC1\u65E0\u6743\u8BBF\u95EE\u770B\u677F</h3>
2154
+ <p>\u4F60\u4F7F\u7528\u7684\u662F <b>agent \u4E13\u5C5E token</b>\u3002\u770B\u677F\u662F\u5168\u5C40\u805A\u5408\u89C6\u56FE\uFF0C\u53EA\u63A5\u53D7\u5168\u5C40\uFF08\u7BA1\u7406\u5458\uFF09token \u2014\u2014
2155
+ \u5426\u5219 agent A \u5C31\u80FD\u770B\u5230 agent B \u7684\u5168\u90E8\u547D\u4EE4\u539F\u6587\u548C\u7528\u6237 prompt\u3002</p>
2156
+ <p>agent \u81EA\u67E5\u8BF7\u7528\u8BFB\u63A5\u53E3\uFF08\u6309\u51ED\u8BC1\u7ED1\u5B9A\u7684 agent \u81EA\u52A8\u8FC7\u6EE4\uFF09\uFF1A
2157
+ <code>/api/v1/sessions/&lt;id&gt;/traces</code>\u3001<code>/api/v1/tool_calls</code>\u3002</p>
2158
+ <p>\u8FD0\u7EF4\u8BF7\u4F7F\u7528\u5168\u5C40 token\uFF1A<code>~/.config/agentgate/auth_token</code>\u3002</p>
2159
+ </div></body></html>`;
1338
2160
  }
1339
2161
  });
1340
2162
 
@@ -5454,7 +6276,7 @@ var require_websocket = __commonJS({
5454
6276
  var http5 = require("http");
5455
6277
  var net2 = require("net");
5456
6278
  var tls = require("tls");
5457
- var { randomBytes, createHash: createHash3 } = require("crypto");
6279
+ var { randomBytes: randomBytes2, createHash: createHash4 } = require("crypto");
5458
6280
  var { Duplex, Readable } = require("stream");
5459
6281
  var { URL: URL5 } = require("url");
5460
6282
  var PerMessageDeflate = require_permessage_deflate();
@@ -5992,7 +6814,7 @@ var require_websocket = __commonJS({
5992
6814
  }
5993
6815
  }
5994
6816
  const defaultPort = isSecure ? 443 : 80;
5995
- const key = randomBytes(16).toString("base64");
6817
+ const key = randomBytes2(16).toString("base64");
5996
6818
  const request3 = isSecure ? https2.request : http5.request;
5997
6819
  const protocolSet = /* @__PURE__ */ new Set();
5998
6820
  let perMessageDeflate;
@@ -6122,7 +6944,7 @@ var require_websocket = __commonJS({
6122
6944
  abortHandshake(websocket, socket, "Invalid Upgrade header");
6123
6945
  return;
6124
6946
  }
6125
- const digest = createHash3("sha1").update(key + GUID).digest("base64");
6947
+ const digest = createHash4("sha1").update(key + GUID).digest("base64");
6126
6948
  if (res.headers["sec-websocket-accept"] !== digest) {
6127
6949
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
6128
6950
  return;
@@ -6494,7 +7316,7 @@ var require_websocket_server = __commonJS({
6494
7316
  var EventEmitter2 = require("events");
6495
7317
  var http5 = require("http");
6496
7318
  var { Duplex } = require("stream");
6497
- var { createHash: createHash3 } = require("crypto");
7319
+ var { createHash: createHash4 } = require("crypto");
6498
7320
  var extension = require_extension();
6499
7321
  var PerMessageDeflate = require_permessage_deflate();
6500
7322
  var subprotocol = require_subprotocol();
@@ -6801,7 +7623,7 @@ var require_websocket_server = __commonJS({
6801
7623
  );
6802
7624
  }
6803
7625
  if (this._state > RUNNING) return abortHandshake(socket, 503);
6804
- const digest = createHash3("sha1").update(key + GUID).digest("base64");
7626
+ const digest = createHash4("sha1").update(key + GUID).digest("base64");
6805
7627
  const headers = [
6806
7628
  "HTTP/1.1 101 Switching Protocols",
6807
7629
  "Upgrade: websocket",
@@ -27300,7 +28122,7 @@ function normalizeProxyEvent(toolCall2, toolResponse, requestMeta, sessionId, ag
27300
28122
  const url = arguments_.url || "";
27301
28123
  const tr = toolResponse || {};
27302
28124
  return {
27303
- eventId: (0, import_node_crypto.randomUUID)(),
28125
+ eventId: (0, import_node_crypto2.randomUUID)(),
27304
28126
  timestamp: {
27305
28127
  timestampNs: now.getTime() * 1e6,
27306
28128
  iso: now.toISOString()
@@ -27337,16 +28159,16 @@ function deriveSessionId(meta, headers) {
27337
28159
  if (meta.threadId) return meta.threadId;
27338
28160
  const apiKey = headers["x-api-key"] || headers["authorization"] || "";
27339
28161
  if (apiKey) {
27340
- return `apikey_${(0, import_node_crypto.createHash)("sha256").update(apiKey).digest("hex").slice(0, 12)}`;
28162
+ return `apikey_${(0, import_node_crypto2.createHash)("sha256").update(apiKey).digest("hex").slice(0, 12)}`;
27341
28163
  }
27342
- return (0, import_node_crypto.randomUUID)();
28164
+ return (0, import_node_crypto2.randomUUID)();
27343
28165
  }
27344
- var import_node_crypto;
28166
+ var import_node_crypto2;
27345
28167
  var init_normalizer2 = __esm({
27346
28168
  "src/v3/proxy/normalizer.ts"() {
27347
28169
  "use strict";
27348
28170
  init_cjs_shims();
27349
- import_node_crypto = require("crypto");
28171
+ import_node_crypto2 = require("crypto");
27350
28172
  }
27351
28173
  });
27352
28174
 
@@ -27355,12 +28177,12 @@ var privacy_exports = {};
27355
28177
  __export(privacy_exports, {
27356
28178
  PrivacyFilter: () => PrivacyFilter
27357
28179
  });
27358
- var import_node_crypto2, DEFAULT_CONFIG, SENSITIVE_PATTERNS, PrivacyFilter;
28180
+ var import_node_crypto3, DEFAULT_CONFIG, SENSITIVE_PATTERNS, PrivacyFilter;
27359
28181
  var init_privacy = __esm({
27360
28182
  "src/v3/proxy/privacy.ts"() {
27361
28183
  "use strict";
27362
28184
  init_cjs_shims();
27363
- import_node_crypto2 = require("crypto");
28185
+ import_node_crypto3 = require("crypto");
27364
28186
  DEFAULT_CONFIG = {
27365
28187
  mode: "auto",
27366
28188
  redactApiKeys: true,
@@ -27447,7 +28269,7 @@ var init_privacy = __esm({
27447
28269
  for (const key of Object.keys(payload)) {
27448
28270
  const value = payload[key];
27449
28271
  if (typeof value === "string" && value.length > 50) {
27450
- payload[`${key}_hash`] = (0, import_node_crypto2.createHash)("sha256").update(value).digest("hex").slice(0, 16);
28272
+ payload[`${key}_hash`] = (0, import_node_crypto3.createHash)("sha256").update(value).digest("hex").slice(0, 16);
27451
28273
  payload[`${key}_length`] = value.length;
27452
28274
  delete payload[key];
27453
28275
  } else if (Array.isArray(value)) {
@@ -27582,12 +28404,12 @@ var session_exports = {};
27582
28404
  __export(session_exports, {
27583
28405
  ProxySessionAggregator: () => ProxySessionAggregator
27584
28406
  });
27585
- var import_node_crypto3, ProxySessionAggregator;
28407
+ var import_node_crypto4, ProxySessionAggregator;
27586
28408
  var init_session = __esm({
27587
28409
  "src/v3/proxy/session.ts"() {
27588
28410
  "use strict";
27589
28411
  init_cjs_shims();
27590
- import_node_crypto3 = require("crypto");
28412
+ import_node_crypto4 = require("crypto");
27591
28413
  ProxySessionAggregator = class {
27592
28414
  _sessions = /* @__PURE__ */ new Map();
27593
28415
  _apiSessionMap = /* @__PURE__ */ new Map();
@@ -27624,7 +28446,7 @@ var init_session = __esm({
27624
28446
  return session2;
27625
28447
  }
27626
28448
  const session = {
27627
- id: (0, import_node_crypto3.randomUUID)(),
28449
+ id: (0, import_node_crypto4.randomUUID)(),
27628
28450
  label: `${event.agentType || "unknown"}-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 19)}`,
27629
28451
  inferredAgentType: event.agentType || "unknown",
27630
28452
  eventCount: 0,
@@ -27674,12 +28496,12 @@ var trigger_exports = {};
27674
28496
  __export(trigger_exports, {
27675
28497
  TriggerEngine: () => TriggerEngine
27676
28498
  });
27677
- var import_node_fs, import_yaml, TriggerEngine;
28499
+ var import_node_fs2, import_yaml, TriggerEngine;
27678
28500
  var init_trigger = __esm({
27679
28501
  "src/v3/proxy/trigger.ts"() {
27680
28502
  "use strict";
27681
28503
  init_cjs_shims();
27682
- import_node_fs = require("fs");
28504
+ import_node_fs2 = require("fs");
27683
28505
  import_yaml = require("yaml");
27684
28506
  TriggerEngine = class {
27685
28507
  _rules = [];
@@ -27687,7 +28509,7 @@ var init_trigger = __esm({
27687
28509
  _rateLimitSeconds = 5;
27688
28510
  constructor(rulesPath) {
27689
28511
  const path11 = rulesPath || "config/trigger_rules.yaml";
27690
- if (!(0, import_node_fs.existsSync)(path11)) {
28512
+ if (!(0, import_node_fs2.existsSync)(path11)) {
27691
28513
  console.error(
27692
28514
  `[AgentGate] \u672A\u627E\u5230\u89E6\u53D1\u89C4\u5219\u6587\u4EF6 ${path11} \u2014\u2014 \u4F7F\u7528\u7A7A\u89C4\u5219\u96C6\uFF0C\u6240\u6709\u89E6\u53D1\u89C4\u5219\u90FD\u4E0D\u4F1A\u547D\u4E2D\uFF01\uFF08\u8BF7\u68C0\u67E5\u542F\u52A8\u76EE\u5F55\u6216\u663E\u5F0F\u4F20\u5165 rulesPath\uFF09`
27693
28515
  );
@@ -27703,7 +28525,7 @@ var init_trigger = __esm({
27703
28525
  return this._rules;
27704
28526
  }
27705
28527
  _loadRules(path11) {
27706
- const content = (0, import_node_fs.readFileSync)(path11, "utf-8");
28528
+ const content = (0, import_node_fs2.readFileSync)(path11, "utf-8");
27707
28529
  const data = (0, import_yaml.parse)(content) || {};
27708
28530
  const rulesData = data.rules || [];
27709
28531
  this._rules = rulesData.map((r) => {
@@ -27833,21 +28655,37 @@ var server_exports2 = {};
27833
28655
  __export(server_exports2, {
27834
28656
  ProxyServer: () => ProxyServer
27835
28657
  });
27836
- var import_node_http, import_node_url, import_node_path, import_node_fs2, import_node_stream, import_http_mitm_proxy, DASHBOARD_HTML, ProxyServer;
28658
+ function cookieValue(raw, name) {
28659
+ for (const part of (raw ?? "").split(";")) {
28660
+ const [k, ...rest] = part.trim().split("=");
28661
+ if (k === name) return rest.join("=");
28662
+ }
28663
+ return "";
28664
+ }
28665
+ function timingSafeEqualStr(a, b) {
28666
+ const ba = Buffer.from(a, "utf-8");
28667
+ const bb = Buffer.from(b, "utf-8");
28668
+ if (ba.length !== bb.length) return false;
28669
+ return (0, import_node_crypto5.timingSafeEqual)(ba, bb);
28670
+ }
28671
+ var import_node_http, import_node_crypto5, import_node_url, import_node_path2, import_node_fs3, import_node_stream, import_http_mitm_proxy, DASHBOARD_COOKIE2, DASHBOARD_HTML, ProxyServer;
27837
28672
  var init_server2 = __esm({
27838
28673
  "src/v3/proxy/server.ts"() {
27839
28674
  "use strict";
27840
28675
  init_cjs_shims();
27841
28676
  import_node_http = __toESM(require("http"));
28677
+ import_node_crypto5 = require("crypto");
27842
28678
  import_node_url = require("url");
27843
- import_node_path = __toESM(require("path"));
27844
- import_node_fs2 = __toESM(require("fs"));
28679
+ import_node_path2 = __toESM(require("path"));
28680
+ import_node_fs3 = __toESM(require("fs"));
27845
28681
  import_node_stream = require("stream");
27846
28682
  import_http_mitm_proxy = __toESM(require_dist());
27847
28683
  init_interceptor();
27848
28684
  init_session();
27849
28685
  init_trigger();
27850
28686
  init_storage();
28687
+ init_security();
28688
+ DASHBOARD_COOKIE2 = "agent_gate_dashboard_token";
27851
28689
  DASHBOARD_HTML = `<!DOCTYPE html>
27852
28690
  <html><head><meta charset="UTF-8"><title>AgentGate v3 Dashboard</title>
27853
28691
  <style>
@@ -27871,6 +28709,9 @@ td{padding:10px 16px;border-bottom:1px solid #334155;font-size:14px}tr:hover{bac
27871
28709
  </tr></thead><tbody id="eb"></tbody></table></div>
27872
28710
  <script>
27873
28711
  async function j(p){return(await fetch(location.origin+p)).json()}
28712
+ // HTML \u8F6C\u4E49\uFF1Asession_id / agent_type / tool_name / target_command \u5168\u90E8\u6765\u81EA
28713
+ // \u8C03\u7528\u65B9\u4E0A\u62A5\uFF0C\u5C5E\u4E0D\u53EF\u4FE1\u5185\u5BB9\u3002\u4E0E Python \u7248 dashboard \u7684\u8F6C\u4E49\u5B57\u7B26\u96C6\u4FDD\u6301\u4E00\u81F4\u3002
28714
+ function esc(s){return String(s==null?'':s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;')}
27874
28715
  async function load(){
27875
28716
  const s=await j('/api/stats');
27876
28717
  document.getElementById('stats').innerHTML=
@@ -27881,9 +28722,9 @@ async function load(){
27881
28722
  document.getElementById('st').textContent='Live | '+(s.total_events||0)+' events';
27882
28723
  const e=await j('/api/events?limit=30');
27883
28724
  document.getElementById('eb').innerHTML=(e.events||[]).map(r=>
27884
- '<tr><td>'+(r.captured_at||'')+'</td><td><code>'+(r.session_id||'').slice(0,8)+'</code></td>'+
27885
- '<td>'+(r.agent_type||'')+'</td><td><span class="badge tool">'+(r.tool_name||'')+'</span></td>'+
27886
- '<td><span class="cmd">'+(r.target_command||'')+'</span></td></tr>').join('');
28725
+ '<tr><td>'+esc(r.captured_at||'')+'</td><td><code>'+esc((r.session_id||'').slice(0,8))+'</code></td>'+
28726
+ '<td>'+esc(r.agent_type||'')+'</td><td><span class="badge tool">'+esc(r.tool_name||'')+'</span></td>'+
28727
+ '<td><span class="cmd">'+esc(r.target_command||'')+'</span></td></tr>').join('');
27887
28728
  }
27888
28729
  load();setInterval(load,5000);
27889
28730
  </script></body></html>`;
@@ -27919,9 +28760,9 @@ load();setInterval(load,5000);
27919
28760
  this._interceptor = new LLMInterceptor(config, this._sessionAgg, this._triggerEngine, options.coordinator);
27920
28761
  }
27921
28762
  start() {
27922
- const caDir = this._options.sslCaDir || import_node_path.default.join(process.cwd(), ".agentgate-ssl");
27923
- if (!import_node_fs2.default.existsSync(caDir)) {
27924
- import_node_fs2.default.mkdirSync(caDir, { recursive: true });
28763
+ const caDir = this._options.sslCaDir || import_node_path2.default.join(process.cwd(), ".agentgate-ssl");
28764
+ if (!import_node_fs3.default.existsSync(caDir)) {
28765
+ import_node_fs3.default.mkdirSync(caDir, { recursive: true });
27925
28766
  }
27926
28767
  this._mitmProxy = new import_http_mitm_proxy.Proxy();
27927
28768
  this._mitmProxy.onError((_ctx, err) => {
@@ -28097,20 +28938,40 @@ load();setInterval(load,5000);
28097
28938
  _startDashboard() {
28098
28939
  const dashPort = this._options.port + 1;
28099
28940
  this._dashServer = import_node_http.default.createServer((req, res) => {
28100
- if (req.url === "/" || req.url === "/dashboard") {
28101
- res.writeHead(200, { "Content-Type": "text/html" });
28941
+ const url = new import_node_url.URL(req.url ?? "/", "http://localhost");
28942
+ const pathname = url.pathname;
28943
+ const queryToken = url.searchParams.get("token") || "";
28944
+ const expected = (process.env.AGENT_GATE_DASHBOARD_TOKEN ?? "").trim();
28945
+ if (expected) {
28946
+ const got = queryToken || String(req.headers["x-agentgate-token"] ?? "") || cookieValue(req.headers.cookie, DASHBOARD_COOKIE2);
28947
+ if (!timingSafeEqualStr(got, expected)) {
28948
+ res.writeHead(401, { "Content-Type": "text/plain" });
28949
+ res.end("Unauthorized");
28950
+ return;
28951
+ }
28952
+ }
28953
+ if (pathname === "/" || pathname === "/dashboard") {
28954
+ const headers = {
28955
+ "Content-Type": "text/html; charset=utf-8",
28956
+ // 与 Python 版 dashboard 同一套安全响应头(CSP / 防点击劫持 / nosniff)
28957
+ ...DASHBOARD_SECURITY_HEADERS
28958
+ };
28959
+ if (expected && queryToken) {
28960
+ headers["Set-Cookie"] = `${DASHBOARD_COOKIE2}=${queryToken}; HttpOnly; SameSite=Strict; Path=/`;
28961
+ }
28962
+ res.writeHead(200, headers);
28102
28963
  res.end(DASHBOARD_HTML);
28103
28964
  return;
28104
28965
  }
28105
- if (req.url === "/api/stats") {
28966
+ if (pathname === "/api/stats") {
28106
28967
  this._serveStats(res);
28107
28968
  return;
28108
28969
  }
28109
- if (req.url?.startsWith("/api/events")) {
28970
+ if (pathname.startsWith("/api/events")) {
28110
28971
  this._serveEvents(req, res);
28111
28972
  return;
28112
28973
  }
28113
- if (req.url === "/api/sessions") {
28974
+ if (pathname === "/api/sessions") {
28114
28975
  this._serveSessions(res);
28115
28976
  return;
28116
28977
  }
@@ -29111,21 +29972,21 @@ var whitelist_exports = {};
29111
29972
  __export(whitelist_exports, {
29112
29973
  WhitelistEngine: () => WhitelistEngine
29113
29974
  });
29114
- var import_node_fs3, import_yaml2, WhitelistEngine;
29975
+ var import_node_fs4, import_yaml2, WhitelistEngine;
29115
29976
  var init_whitelist = __esm({
29116
29977
  "src/v3/proxy/whitelist.ts"() {
29117
29978
  "use strict";
29118
29979
  init_cjs_shims();
29119
- import_node_fs3 = require("fs");
29980
+ import_node_fs4 = require("fs");
29120
29981
  import_yaml2 = require("yaml");
29121
29982
  WhitelistEngine = class {
29122
29983
  _rules = [];
29123
29984
  constructor(rulesPath) {
29124
29985
  const path11 = rulesPath || "config/trigger_rules.yaml";
29125
- if ((0, import_node_fs3.existsSync)(path11)) this._loadRules(path11);
29986
+ if ((0, import_node_fs4.existsSync)(path11)) this._loadRules(path11);
29126
29987
  }
29127
29988
  _loadRules(path11) {
29128
- const content = (0, import_node_fs3.readFileSync)(path11, "utf-8");
29989
+ const content = (0, import_node_fs4.readFileSync)(path11, "utf-8");
29129
29990
  const data = (0, import_yaml2.parse)(content) || {};
29130
29991
  const rulesData = data.rules || [];
29131
29992
  this._rules = rulesData.filter((r) => r.action === "allow").map((r) => {
@@ -29282,13 +30143,20 @@ var server_exports3 = {};
29282
30143
  __export(server_exports3, {
29283
30144
  GatewayServer: () => GatewayServer
29284
30145
  });
29285
- var import_node_http2, import_node_https, import_node_url2, GatewayServer, DASHBOARD_HTML2;
30146
+ function timingSafeEqualStr2(a, b) {
30147
+ const ba = Buffer.from(a, "utf-8");
30148
+ const bb = Buffer.from(b, "utf-8");
30149
+ if (ba.length !== bb.length) return false;
30150
+ return (0, import_node_crypto6.timingSafeEqual)(ba, bb);
30151
+ }
30152
+ var import_node_http2, import_node_https, import_node_crypto6, import_node_url2, GatewayServer, DASHBOARD_HTML2;
29286
30153
  var init_server3 = __esm({
29287
30154
  "src/v3/gateway/server.ts"() {
29288
30155
  "use strict";
29289
30156
  init_cjs_shims();
29290
30157
  import_node_http2 = __toESM(require("http"));
29291
30158
  import_node_https = __toESM(require("https"));
30159
+ import_node_crypto6 = require("crypto");
29292
30160
  import_node_url2 = require("url");
29293
30161
  init_router();
29294
30162
  init_parsers();
@@ -29297,6 +30165,7 @@ var init_server3 = __esm({
29297
30165
  init_trigger();
29298
30166
  init_privacy();
29299
30167
  init_storage();
30168
+ init_security();
29300
30169
  GatewayServer = class {
29301
30170
  host;
29302
30171
  port;
@@ -29345,6 +30214,13 @@ var init_server3 = __esm({
29345
30214
  }
29346
30215
  async handleRequest(req, res) {
29347
30216
  const path11 = (req.url ?? "/").replace(/\/+$/, "") || "/";
30217
+ const expected = (process.env.AGENT_GATE_GATEWAY_TOKEN ?? "").trim();
30218
+ if (expected && path11 !== "/health") {
30219
+ const got = String(req.headers["x-agentgate-token"] ?? "");
30220
+ if (!timingSafeEqualStr2(got, expected)) {
30221
+ return this.json(res, 401, { error: "Unauthorized: missing or invalid X-AgentGate-Token" });
30222
+ }
30223
+ }
29348
30224
  if (req.method === "GET") {
29349
30225
  if (path11 === "" || path11 === "/") {
29350
30226
  return this.serveDashboard(res);
@@ -29571,8 +30447,10 @@ var init_server3 = __esm({
29571
30447
  serveDashboard(res) {
29572
30448
  const html = DASHBOARD_HTML2;
29573
30449
  res.writeHead(200, {
29574
- "Content-Type": "text/html",
29575
- "Content-Length": String(Buffer.byteLength(html))
30450
+ "Content-Type": "text/html; charset=utf-8",
30451
+ "Content-Length": String(Buffer.byteLength(html)),
30452
+ // 与 Python 版 dashboard 同一套安全响应头(CSP / 防点击劫持 / nosniff)
30453
+ ...DASHBOARD_SECURITY_HEADERS
29576
30454
  });
29577
30455
  res.end(html);
29578
30456
  }
@@ -29650,6 +30528,9 @@ td{padding:10px 16px;border-bottom:1px solid #334155;font-size:14px}tr:hover{bac
29650
30528
  </tr></thead><tbody id="eb"></tbody></table></div>
29651
30529
  <script>
29652
30530
  async function j(p){return(await fetch(location.origin+p)).json()}
30531
+ // HTML \u8F6C\u4E49\uFF1Asession_id / agent_type / tool_name / target_command \u5168\u90E8\u6765\u81EA
30532
+ // \u8C03\u7528\u65B9\u4E0A\u62A5\uFF0C\u5C5E\u4E0D\u53EF\u4FE1\u5185\u5BB9\u3002\u4E0E Python \u7248 dashboard \u7684\u8F6C\u4E49\u5B57\u7B26\u96C6\u4FDD\u6301\u4E00\u81F4\u3002
30533
+ function esc(s){return String(s==null?'':s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;')}
29653
30534
  async function load(){
29654
30535
  try{
29655
30536
  const s=await j('/api/stats');
@@ -29660,9 +30541,9 @@ async function load(){
29660
30541
  '<div class="sc"><div class="l">Tools</div><div class="v">'+(s.unique_tools||0)+'</div></div>';
29661
30542
  const e=await j('/api/events?limit=30');
29662
30543
  document.getElementById('eb').innerHTML=(e.events||[]).map(r=>
29663
- '<tr><td>'+(r.captured_at||'')+'</td><td><code>'+(r.session_id||'').slice(0,8)+'</code></td>'+
29664
- '<td>'+(r.agent_type||'')+'</td><td><span class="badge tool">'+(r.tool_name||'')+'</span></td>'+
29665
- '<td><span class="cmd">'+(r.target_command||'')+'</span></td></tr>').join('');
30544
+ '<tr><td>'+esc(r.captured_at||'')+'</td><td><code>'+esc((r.session_id||'').slice(0,8))+'</code></td>'+
30545
+ '<td>'+esc(r.agent_type||'')+'</td><td><span class="badge tool">'+esc(r.tool_name||'')+'</span></td>'+
30546
+ '<td><span class="cmd">'+esc(r.target_command||'')+'</span></td></tr>').join('');
29666
30547
  }catch(e){console.error(e)}
29667
30548
  }
29668
30549
  load();setInterval(load,5000);
@@ -30496,8 +31377,8 @@ var init_opencode = __esm({
30496
31377
 
30497
31378
  // src/v3/transcript/opendesk.ts
30498
31379
  function defaultRoot() {
30499
- for (const env of [OPENDESK_CONFIG_DIR_ENV, LEGACY_ENV]) {
30500
- if (process.env[env]) return path6.resolve(process.env[env]);
31380
+ for (const env2 of [OPENDESK_CONFIG_DIR_ENV, LEGACY_ENV]) {
31381
+ if (process.env[env2]) return path6.resolve(process.env[env2]);
30501
31382
  }
30502
31383
  if (process.env.APPDATA) return path6.join(process.env.APPDATA, "opendesk");
30503
31384
  return path6.join(os7.homedir(), ".opendesk");
@@ -31813,9 +32694,9 @@ var init_stdio_proxy = __esm({
31813
32694
  this.opts = opts;
31814
32695
  }
31815
32696
  start() {
31816
- const { command, env = {}, cwd, stdin = process.stdin, stdout = process.stdout, stderr = process.stderr } = this.opts;
32697
+ const { command, env: env2 = {}, cwd, stdin = process.stdin, stdout = process.stdout, stderr = process.stderr } = this.opts;
31817
32698
  this.child = (0, import_node_child_process.spawn)(command[0], command.slice(1), {
31818
- env: { ...process.env, ...env },
32699
+ env: { ...process.env, ...env2 },
31819
32700
  cwd,
31820
32701
  stdio: ["pipe", "pipe", "pipe"]
31821
32702
  });
@@ -32269,13 +33150,13 @@ var init_launcher = __esm({
32269
33150
  this.coordinator = options.coordinator;
32270
33151
  this.sessionId = options.sessionId ?? `pty-${Date.now()}`;
32271
33152
  }
32272
- async run(command, args = [], env = {}) {
33153
+ async run(command, args = [], env2 = {}) {
32273
33154
  console.log(`[AgentGate] Starting agent: ${command} ${args.join(" ")}`);
32274
33155
  console.log(`[AgentGate] Layer 1 (API Gateway): ${this.enableLayer1 ? "enabled" : "disabled"}`);
32275
33156
  console.log(`[AgentGate] Layer 2 (PTY Interception): enabled`);
32276
33157
  console.log();
32277
33158
  const fullEnv = {
32278
- ...env,
33159
+ ...env2,
32279
33160
  AGENTGATE_SESSION_ID: this.sessionId
32280
33161
  };
32281
33162
  const wrapper = new PTYWrapper({
@@ -33188,7 +34069,7 @@ var init_loader = __esm({
33188
34069
 
33189
34070
  // src/v3/cli.ts
33190
34071
  init_cjs_shims();
33191
- var import_node_fs4 = require("fs");
34072
+ var import_node_fs5 = require("fs");
33192
34073
  var path10 = __toESM(require("path"));
33193
34074
  var import_yaml3 = require("yaml");
33194
34075
  init_version();
@@ -33274,8 +34155,14 @@ Run options:
33274
34155
  }
33275
34156
  mossUrl2 = mossUrl2 || process.env.MOSS_URL;
33276
34157
  const dataDir = process.env.AGENT_GATE_DATA_DIR;
33277
- const { createStorage: createStorage2 } = await Promise.resolve().then(() => (init_db(), db_exports));
34158
+ const { createStorage: createStorage2, getAgentGateDbPath: getAgentGateDbPath2 } = await Promise.resolve().then(() => (init_db(), db_exports));
33278
34159
  createStorage2({ dbPath, dataDir });
34160
+ const { hardenDbFiles: hardenDbFiles2, describe: describe2, authEnabled: authEnabled2, authToken: authToken2, failFastOnAuthError: failFastOnAuthError2 } = await Promise.resolve().then(() => (init_security(), security_exports));
34161
+ if ((process.env.AGENT_GATE_STORAGE || "sqlite").toLowerCase() !== "json") {
34162
+ hardenDbFiles2(getAgentGateDbPath2());
34163
+ }
34164
+ console.log(describe2());
34165
+ failFastOnAuthError2();
33279
34166
  if (mossUrl2) {
33280
34167
  const { setMossUrl: setMossUrl2 } = await Promise.resolve().then(() => (init_moss_client(), moss_client_exports));
33281
34168
  setMossUrl2(mossUrl2);
@@ -33284,6 +34171,9 @@ Run options:
33284
34171
  const { createApp: createApp2 } = await Promise.resolve().then(() => (init_server(), server_exports));
33285
34172
  const app = createApp2();
33286
34173
  console.log(`AgentGate HTTP server on ${host}:${port}`);
34174
+ if (authEnabled2() && authToken2()) {
34175
+ console.log(`Dashboard: http://localhost:${port}/dashboard/?token=${authToken2()}`);
34176
+ }
33287
34177
  serve({ fetch: app.fetch, hostname: host, port }, (info) => {
33288
34178
  console.log(`Listening on http://${host}:${port}`);
33289
34179
  });
@@ -33397,12 +34287,12 @@ Run options:
33397
34287
  if (envLevel && !args.includes("--level")) level = parseInt(envLevel, 10);
33398
34288
  const envDeny = process.env.AGENT_GATE_DENY_ACTION;
33399
34289
  if (envDeny && !args.includes("--deny-action")) denyAction = envDeny;
33400
- if (!(0, import_node_fs4.existsSync)(configPath)) {
34290
+ if (!(0, import_node_fs5.existsSync)(configPath)) {
33401
34291
  console.error(`Config file not found: ${configPath}`);
33402
34292
  console.error("Create it with model_routes or use --config <path>");
33403
34293
  process.exit(1);
33404
34294
  }
33405
- const yamlContent = (0, import_node_fs4.readFileSync)(configPath, "utf-8");
34295
+ const yamlContent = (0, import_node_fs5.readFileSync)(configPath, "utf-8");
33406
34296
  const config = (0, import_yaml3.parse)(yamlContent);
33407
34297
  const gatewayCfg = config.gateway ?? {};
33408
34298
  const modelRoutes = gatewayCfg.model_routes ?? [];
@@ -33544,7 +34434,7 @@ Run options:
33544
34434
  const jsonOut = args.includes("--json");
33545
34435
  let files = [];
33546
34436
  try {
33547
- files = (0, import_node_fs4.readdirSync)(dir2).filter((f) => f.endsWith(".jsonl")).map((f) => path10.join(dir2, f)).sort((a, b) => (0, import_node_fs4.statSync)(b).mtimeMs - (0, import_node_fs4.statSync)(a).mtimeMs);
34437
+ files = (0, import_node_fs5.readdirSync)(dir2).filter((f) => f.endsWith(".jsonl")).map((f) => path10.join(dir2, f)).sort((a, b) => (0, import_node_fs5.statSync)(b).mtimeMs - (0, import_node_fs5.statSync)(a).mtimeMs);
33548
34438
  } catch {
33549
34439
  }
33550
34440
  if (files.length === 0) {