@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/v1/cli.js CHANGED
@@ -41,6 +41,546 @@ var init_cjs_shims = __esm({
41
41
  }
42
42
  });
43
43
 
44
+ // src/shared/security.ts
45
+ var security_exports = {};
46
+ __export(security_exports, {
47
+ AUTH_MODE_AUTO: () => AUTH_MODE_AUTO,
48
+ AUTH_MODE_OFF: () => AUTH_MODE_OFF,
49
+ DASHBOARD_COOKIE: () => DASHBOARD_COOKIE,
50
+ DASHBOARD_SECURITY_HEADERS: () => DASHBOARD_SECURITY_HEADERS,
51
+ PUBLIC_PATHS: () => PUBLIC_PATHS,
52
+ PooledLimiter: () => PooledLimiter,
53
+ RateLimiter: () => RateLimiter,
54
+ agentInflight: () => agentInflight,
55
+ agentTokens: () => agentTokens,
56
+ allowedOrigins: () => allowedOrigins,
57
+ authConfigError: () => authConfigError,
58
+ authEnabled: () => authEnabled,
59
+ authMode: () => authMode,
60
+ authToken: () => authToken,
61
+ authTokenPath: () => authTokenPath,
62
+ autoTokenHint: () => autoTokenHint,
63
+ bindAgent: () => bindAgent,
64
+ boundAgentOf: () => boundAgentOf,
65
+ checkRequestAuth: () => checkRequestAuth,
66
+ checkToken: () => checkToken,
67
+ cookiePathAllowed: () => cookiePathAllowed,
68
+ describe: () => describe,
69
+ ensureAutoToken: () => ensureAutoToken,
70
+ ensurePrivateDir: () => ensurePrivateDir,
71
+ failFastOnAuthError: () => failFastOnAuthError,
72
+ hardenDbFiles: () => hardenDbFiles,
73
+ hardenFilesEnabled: () => hardenFilesEnabled,
74
+ hardenPermissions: () => hardenPermissions,
75
+ isGlobalToken: () => isGlobalToken,
76
+ keepAliveSec: () => keepAliveSec,
77
+ maxBodyBytes: () => maxBodyBytes,
78
+ maxConnections: () => maxConnections,
79
+ maxInflight: () => maxInflight,
80
+ maxQueue: () => maxQueue,
81
+ normalizeOrigin: () => normalizeOrigin,
82
+ noteQueueReject: () => noteQueueReject,
83
+ noteSessionAccess: () => noteSessionAccess,
84
+ originAllowed: () => originAllowed,
85
+ originCheckEnabled: () => originCheckEnabled,
86
+ poolLimit: () => poolLimit,
87
+ poolOf: () => poolOf,
88
+ principalOf: () => principalOf,
89
+ queueAbuseAction: () => queueAbuseAction,
90
+ rateLimitQps: () => rateLimitQps,
91
+ resetCounters: () => resetCounters,
92
+ resolveMossToken: () => resolveMossToken,
93
+ sessionSweepAction: () => sessionSweepAction,
94
+ unauthInflight: () => unauthInflight,
95
+ unauthPerIp: () => unauthPerIp
96
+ });
97
+ function env(name, dflt = "") {
98
+ return (process.env[name] ?? dflt).trim();
99
+ }
100
+ function envInt(name, dflt) {
101
+ const raw = env(name);
102
+ if (!raw) return dflt;
103
+ const n = parseInt(raw, 10);
104
+ return Number.isFinite(n) ? n : dflt;
105
+ }
106
+ function envFloat(name, dflt) {
107
+ const raw = env(name);
108
+ if (!raw) return dflt;
109
+ const n = parseFloat(raw);
110
+ return Number.isFinite(n) ? n : dflt;
111
+ }
112
+ function split(raw) {
113
+ return raw.replace(/;/g, ",").split(",").map((x) => x.trim()).filter(Boolean);
114
+ }
115
+ function originCheckEnabled() {
116
+ return TRUTHY.includes(env("AGENT_GATE_ORIGIN_CHECK", "1").toLowerCase());
117
+ }
118
+ function allowedOrigins() {
119
+ return split(env("AGENT_GATE_CORS_ORIGINS"));
120
+ }
121
+ function normalizeOrigin(origin) {
122
+ return (origin || "").trim().replace(/\/+$/, "");
123
+ }
124
+ function originAllowed(origin, hostHeader, extra) {
125
+ const o = normalizeOrigin(origin);
126
+ if (!o) return true;
127
+ const entries = (extra ?? allowedOrigins()).map(normalizeOrigin);
128
+ if (entries.includes(o)) return true;
129
+ const host = (hostHeader || "").trim();
130
+ if (!host) return false;
131
+ try {
132
+ const u = new URL(o);
133
+ return !!u.host && u.host === host;
134
+ } catch {
135
+ return false;
136
+ }
137
+ }
138
+ function authMode() {
139
+ return (env("AGENT_GATE_AUTH_MODE", AUTH_MODE_AUTO) || AUTH_MODE_AUTO).toLowerCase();
140
+ }
141
+ function authTokenPath() {
142
+ const home = process.env.SUDO_USER && existsDir(`/home/${process.env.SUDO_USER}`) ? `/home/${process.env.SUDO_USER}` : (0, import_node_os.homedir)();
143
+ const xdg = process.env.XDG_CONFIG_HOME || (0, import_node_path.join)(home, ".config");
144
+ return (0, import_node_path.join)(xdg, "agentgate", "auth_token");
145
+ }
146
+ function existsDir(p) {
147
+ try {
148
+ return (0, import_node_fs.statSync)(p).isDirectory();
149
+ } catch {
150
+ return false;
151
+ }
152
+ }
153
+ function ensurePrivateDir(p, mode = 448) {
154
+ try {
155
+ (0, import_node_fs.mkdirSync)(p, { recursive: true });
156
+ const st = (0, import_node_fs.statSync)(p);
157
+ if (st.uid === process.getuid?.() && (st.mode & 511) !== mode) (0, import_node_fs.chmodSync)(p, mode);
158
+ } catch {
159
+ }
160
+ }
161
+ function hardenPermissions(p, mode) {
162
+ try {
163
+ const st = (0, import_node_fs.lstatSync)(p);
164
+ if (st.isSymbolicLink()) return;
165
+ if (st.uid !== process.getuid?.()) return;
166
+ if ((st.mode & 511) !== mode) (0, import_node_fs.chmodSync)(p, mode);
167
+ } catch {
168
+ }
169
+ }
170
+ function readFdToken() {
171
+ const raw = env("AGENT_GATE_AUTH_TOKEN_FD");
172
+ if (!raw) return "";
173
+ const fd = parseInt(raw, 10);
174
+ if (!Number.isFinite(fd)) return "";
175
+ const cached = fdTokenCache.get(fd);
176
+ if (cached !== void 0) return cached;
177
+ try {
178
+ const buf = Buffer.alloc(8192);
179
+ const n = (0, import_node_fs.readSync)(fd, buf, 0, buf.length, null);
180
+ (0, import_node_fs.closeSync)(fd);
181
+ const tok = buf.subarray(0, n).toString("utf-8").trim();
182
+ fdTokenCache.set(fd, tok);
183
+ return tok;
184
+ } catch {
185
+ fdTokenCache.set(fd, "");
186
+ return "";
187
+ }
188
+ }
189
+ function readExplicitToken() {
190
+ const t = env("AGENT_GATE_AUTH_TOKEN");
191
+ if (t) return t;
192
+ const fromFd = readFdToken();
193
+ if (fromFd) return fromFd;
194
+ const file = env("AGENT_GATE_AUTH_TOKEN_FILE");
195
+ if (file) {
196
+ try {
197
+ return (0, import_node_fs.readFileSync)(file, "utf-8").trim();
198
+ } catch {
199
+ return "";
200
+ }
201
+ }
202
+ return "";
203
+ }
204
+ function ensureAutoToken() {
205
+ const p = authTokenPath();
206
+ try {
207
+ try {
208
+ const existing = (0, import_node_fs.readFileSync)(p, "utf-8").trim();
209
+ if (existing) {
210
+ hardenPermissions(p, 384);
211
+ return existing;
212
+ }
213
+ } catch {
214
+ }
215
+ const tok = (0, import_node_crypto.randomBytes)(32).toString("base64url");
216
+ ensurePrivateDir(p.replace(/\/[^/]+$/, ""));
217
+ try {
218
+ (0, import_node_fs.writeFileSync)(p, tok + "\n", { mode: 384, flag: "wx" });
219
+ } catch (e) {
220
+ if (e?.code === "EEXIST") return (0, import_node_fs.readFileSync)(p, "utf-8").trim();
221
+ throw e;
222
+ }
223
+ console.warn(
224
+ `[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`
225
+ );
226
+ return tok;
227
+ } catch (e) {
228
+ console.error(`[AgentGate] \u751F\u6210\u8BBF\u95EE token \u5931\u8D25\uFF08\u672C\u6B21\u8FD0\u884C\u5C06\u4E0D\u9274\u6743\uFF09: ${e?.message ?? e}`);
229
+ return "";
230
+ }
231
+ }
232
+ function parseAgentTokens(raw) {
233
+ const out = {};
234
+ for (const pair of split(raw)) {
235
+ const i = pair.indexOf("=");
236
+ if (i > 0) {
237
+ const a = pair.slice(0, i).trim();
238
+ const t = pair.slice(i + 1).trim();
239
+ if (a && t) out[a] = t;
240
+ }
241
+ }
242
+ return out;
243
+ }
244
+ function resolveAuth() {
245
+ const rawAgents = env("AGENT_GATE_AGENT_TOKENS");
246
+ const key = [
247
+ authMode(),
248
+ env("AGENT_GATE_AUTH_TOKEN"),
249
+ env("AGENT_GATE_AUTH_TOKEN_FILE"),
250
+ env("AGENT_GATE_AUTH_TOKEN_FD"),
251
+ rawAgents,
252
+ env("AGENT_GATE_DATA_DIR"),
253
+ env("XDG_CONFIG_HOME"),
254
+ env("SUDO_USER")
255
+ ].join("\0");
256
+ if (tokenCache && tokenCache.key === key) return tokenCache;
257
+ let error = "";
258
+ let token = readExplicitToken();
259
+ if (!token && env("AGENT_GATE_AUTH_TOKEN_FD") && authMode() !== AUTH_MODE_OFF) {
260
+ 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";
261
+ console.error(`[AgentGate] ${error}`);
262
+ }
263
+ if (!token && !error && authMode() !== AUTH_MODE_OFF) token = ensureAutoToken();
264
+ const agents = parseAgentTokens(rawAgents);
265
+ tokenCache = { key, token, agents, error };
266
+ return tokenCache;
267
+ }
268
+ function authToken() {
269
+ return resolveAuth().token;
270
+ }
271
+ function agentTokens() {
272
+ return resolveAuth().agents;
273
+ }
274
+ function authConfigError() {
275
+ return resolveAuth().error;
276
+ }
277
+ function failFastOnAuthError() {
278
+ const err = authConfigError();
279
+ if (err) {
280
+ console.error(`[AgentGate] \u9274\u6743\u914D\u7F6E\u9519\u8BEF\uFF0C\u62D2\u7EDD\u542F\u52A8: ${err}`);
281
+ process.exit(1);
282
+ }
283
+ }
284
+ function authEnabled() {
285
+ if (authMode() === AUTH_MODE_OFF) return false;
286
+ const { token, agents } = resolveAuth();
287
+ return !!token || Object.keys(agents).length > 0;
288
+ }
289
+ function constEq(a, b) {
290
+ const ba = Buffer.from(a, "utf-8");
291
+ const bb = Buffer.from(b, "utf-8");
292
+ if (ba.length !== bb.length) return false;
293
+ return (0, import_node_crypto.timingSafeEqual)(ba, bb);
294
+ }
295
+ function principalOf(token) {
296
+ if (!token) return "";
297
+ const { agents } = resolveAuth();
298
+ for (const [agent, atok] of Object.entries(agents)) {
299
+ if (constEq(token, atok)) return `agent:${agent}`;
300
+ }
301
+ return "tok:" + (0, import_node_crypto.createHash)("sha256").update(token, "utf-8").digest("hex").slice(0, 12);
302
+ }
303
+ function checkToken(token) {
304
+ if (!token) return false;
305
+ const { token: globalTok, agents } = resolveAuth();
306
+ if (globalTok && constEq(token, globalTok)) return true;
307
+ return Object.values(agents).some((t) => constEq(token, t));
308
+ }
309
+ function isGlobalToken(token) {
310
+ if (!token) return false;
311
+ const { token: globalTok } = resolveAuth();
312
+ return Boolean(globalTok) && constEq(token, globalTok);
313
+ }
314
+ function boundAgentOf(principal) {
315
+ return principal.startsWith("agent:") ? principal.slice("agent:".length) : "";
316
+ }
317
+ function cookiePathAllowed(path) {
318
+ if (path === "/api/v1/analyze" || path.startsWith("/api/v1/analyze/")) return false;
319
+ return path === "/dashboard" || path.startsWith("/dashboard/") || path.startsWith("/ws/") || path.startsWith("/api/");
320
+ }
321
+ function checkRequestAuth(headers, path, cookie = "", requireGlobal = false) {
322
+ if (authMode() === AUTH_MODE_OFF) return { ok: true, principal: "" };
323
+ const isHealth = PUBLIC_PATHS.includes(path.replace(/\/+$/, ""));
324
+ const { token: globalTok, agents, error } = resolveAuth();
325
+ if (error) return { ok: isHealth, principal: "" };
326
+ if (!globalTok && Object.keys(agents).length === 0) return { ok: true, principal: "" };
327
+ if (isHealth) return { ok: true, principal: "" };
328
+ if (cookie && cookiePathAllowed(path) && checkToken(cookie)) {
329
+ const principal = principalOf(cookie);
330
+ if (requireGlobal && principal.startsWith("agent:")) {
331
+ return { ok: false, principal };
332
+ }
333
+ return { ok: true, principal };
334
+ }
335
+ const authHeader = headers["authorization"] || "";
336
+ const tok = authHeader.toLowerCase().startsWith("bearer ") ? authHeader.slice(7).trim() : "";
337
+ if (!tok) return { ok: false, principal: "" };
338
+ if (globalTok && constEq(tok, globalTok)) return { ok: true, principal: principalOf(tok) };
339
+ for (const atok of Object.values(agents)) {
340
+ if (constEq(tok, atok)) {
341
+ const principal = principalOf(tok);
342
+ if (requireGlobal) return { ok: false, principal };
343
+ return { ok: true, principal };
344
+ }
345
+ }
346
+ return { ok: false, principal: "" };
347
+ }
348
+ function bindAgent(principal, agentType) {
349
+ if (authMode() === AUTH_MODE_OFF) return { ok: true, reason: "" };
350
+ const { agents } = resolveAuth();
351
+ if (Object.keys(agents).length === 0) return { ok: true, reason: "" };
352
+ if (!principal.startsWith("agent:")) return { ok: true, reason: "" };
353
+ const bound = principal.slice("agent:".length);
354
+ const claimed = (agentType || "").trim();
355
+ if (!claimed) {
356
+ return { ok: false, reason: `\u8BE5\u51ED\u8BC1\u7ED1\u5B9A\u5230 agent '${bound}'\uFF0C\u8BF7\u6C42\u5FC5\u987B\u58F0\u660E agent_type` };
357
+ }
358
+ if (claimed.toLowerCase() !== bound.toLowerCase()) {
359
+ return { ok: false, reason: `agent_type '${claimed}' \u4E0E\u51ED\u8BC1\u7ED1\u5B9A\u7684 '${bound}' \u4E0D\u4E00\u81F4` };
360
+ }
361
+ return { ok: true, reason: bound };
362
+ }
363
+ function maxBodyBytes() {
364
+ return envInt("AGENT_GATE_MAX_BODY_BYTES", 16 * 1024 * 1024);
365
+ }
366
+ function maxInflight() {
367
+ return poolLimit("biz");
368
+ }
369
+ function maxQueue() {
370
+ return envInt("AGENT_GATE_MAX_QUEUE", 256);
371
+ }
372
+ function maxConnections() {
373
+ return envInt("AGENT_GATE_MAX_CONNECTIONS", 256);
374
+ }
375
+ function keepAliveSec() {
376
+ return envInt("AGENT_GATE_KEEP_ALIVE_SEC", 5);
377
+ }
378
+ function rateLimitQps() {
379
+ return envInt("AGENT_GATE_RATE_LIMIT_QPS", 100);
380
+ }
381
+ function poolOf(path) {
382
+ if (path === "/api/v1/analyze" || path.startsWith("/api/v1/analyze/")) return "biz";
383
+ if (path.startsWith("/api/v1/sessions") || path.startsWith("/api/v1/agents") || path.startsWith("/api/v1/tool_calls")) return "read";
384
+ if (path === "/dashboard" || path.startsWith("/dashboard/") || path.startsWith("/ws/")) return "ops";
385
+ if (path === "/api/v1/health") return "health";
386
+ return "other";
387
+ }
388
+ function poolLimit(name) {
389
+ let dflt = POOL_DEFAULTS[name] ?? 4;
390
+ if (name === "biz") dflt = envInt("AGENT_GATE_MAX_INFLIGHT", dflt);
391
+ return envInt(`AGENT_GATE_POOL_${name.toUpperCase()}`, dflt);
392
+ }
393
+ function unauthInflight() {
394
+ return envInt("AGENT_GATE_MAX_UNAUTH_INFLIGHT", 4);
395
+ }
396
+ function unauthPerIp() {
397
+ return envInt("AGENT_GATE_MAX_UNAUTH_PER_IP", 2);
398
+ }
399
+ function agentInflight() {
400
+ return envInt("AGENT_GATE_MAX_AGENT_INFLIGHT", 8);
401
+ }
402
+ function bump(kind, key, windowSec, extra) {
403
+ const now = Date.now() / 1e3;
404
+ const k = `${kind}|${key}`;
405
+ let b = counters.get(k);
406
+ if (!b || now - b.start >= windowSec) {
407
+ b = { start: now, n: 0, seen: /* @__PURE__ */ new Set() };
408
+ counters.set(k, b);
409
+ }
410
+ b.n += 1;
411
+ if (extra !== void 0) b.seen.add(extra);
412
+ if (counters.size > 4096) {
413
+ for (const [kk, v] of counters) {
414
+ if (now - v.start >= windowSec) counters.delete(kk);
415
+ }
416
+ }
417
+ return extra !== void 0 ? b.seen.size : b.n;
418
+ }
419
+ function noteSessionAccess(key, sessionId) {
420
+ const threshold = envInt("AGENT_GATE_SESSION_SWEEP_THRESHOLD", 50);
421
+ if (threshold <= 0) return [0, false];
422
+ const window = envFloat("AGENT_GATE_SESSION_SWEEP_WINDOW", 300);
423
+ const n = bump("sweep", key, window, sessionId || "-");
424
+ return [n, n > threshold];
425
+ }
426
+ function sessionSweepAction() {
427
+ return (env("AGENT_GATE_SESSION_SWEEP_ACTION", "log") || "log").toLowerCase();
428
+ }
429
+ function noteQueueReject(key) {
430
+ const threshold = envInt("AGENT_GATE_QUEUE_ABUSE_THRESHOLD", 10);
431
+ if (threshold <= 0) return [0, false];
432
+ const window = envFloat("AGENT_GATE_QUEUE_ABUSE_WINDOW", 60);
433
+ const n = bump("queue", key, window);
434
+ return [n, n > threshold];
435
+ }
436
+ function queueAbuseAction() {
437
+ return (env("AGENT_GATE_QUEUE_ABUSE_ACTION", "log") || "log").toLowerCase();
438
+ }
439
+ function resetCounters() {
440
+ counters.clear();
441
+ tokenCache = null;
442
+ fdTokenCache.clear();
443
+ }
444
+ function hardenFilesEnabled() {
445
+ return TRUTHY.includes(env("AGENT_GATE_HARDEN_FILES", "1").toLowerCase());
446
+ }
447
+ function hardenDbFiles(dbPath) {
448
+ if (!hardenFilesEnabled()) return;
449
+ hardenPermissions(dbPath, 384);
450
+ hardenPermissions(`${dbPath}-wal`, 384);
451
+ hardenPermissions(`${dbPath}-shm`, 384);
452
+ const parent = dbPath.replace(/\/[^/]+$/, "");
453
+ if (parent.endsWith("/agent_gate")) {
454
+ try {
455
+ const st = (0, import_node_fs.statSync)(parent);
456
+ if (st.uid === process.getuid?.() && ![448, 488].includes(st.mode & 511)) {
457
+ (0, import_node_fs.chmodSync)(parent, 448);
458
+ }
459
+ } catch {
460
+ }
461
+ }
462
+ }
463
+ function mossTokenPath() {
464
+ const root = env("AGENT_MOSS_DATA_DIR");
465
+ if (root) return (0, import_node_path.join)(root, "auth_token");
466
+ const home = process.env.SUDO_USER && existsDir(`/home/${process.env.SUDO_USER}`) ? `/home/${process.env.SUDO_USER}` : (0, import_node_os.homedir)();
467
+ return (0, import_node_path.join)(home, ".config", "agentmoss", "auth_token");
468
+ }
469
+ function resolveMossToken(force = false) {
470
+ const now = Date.now() / 1e3;
471
+ if (!force && mossTokenCache.expires > now) return mossTokenCache.value;
472
+ let tok = env("AGENT_GATE_MOSS_TOKEN");
473
+ if (!tok) tok = env("AGENT_MOSS_AUTH_TOKEN");
474
+ if (!tok) {
475
+ const f = env("AGENT_MOSS_AUTH_TOKEN_FILE");
476
+ if (f) {
477
+ try {
478
+ tok = (0, import_node_fs.readFileSync)(f, "utf-8").trim();
479
+ } catch {
480
+ tok = "";
481
+ }
482
+ }
483
+ }
484
+ if (!tok) {
485
+ try {
486
+ tok = (0, import_node_fs.readFileSync)(mossTokenPath(), "utf-8").trim();
487
+ } catch {
488
+ tok = "";
489
+ }
490
+ }
491
+ mossTokenCache = { value: tok, expires: now + 60 };
492
+ return tok;
493
+ }
494
+ function describe() {
495
+ let auth;
496
+ const err = authConfigError();
497
+ if (err) {
498
+ auth = `\u26A0\uFE0F \u914D\u7F6E\u9519\u8BEF\uFF08\u62D2\u7EDD\u542F\u52A8\uFF09: ${err}`;
499
+ } else if (authMode() === AUTH_MODE_OFF) {
500
+ auth = "off\uFF08\u4E0D\u9274\u6743\uFF0C\u7B49\u4EF7 0.7.6 \u884C\u4E3A\uFF09";
501
+ } else if (authEnabled()) {
502
+ const agents = Object.keys(agentTokens());
503
+ auth = `auto\uFF08token: ${autoTokenHint()}\uFF09`;
504
+ if (agents.length) auth += `\uFF0C\u6BCF agent \u7ED1\u5B9A: ${agents.sort().join(",")}`;
505
+ } else {
506
+ auth = "auto\uFF08token \u751F\u6210\u5931\u8D25\uFF0C\u672C\u6B21\u4E0D\u9274\u6743\uFF09";
507
+ }
508
+ return `\u5B89\u5168\u7B56\u7565: auth=${auth} | origin_check=${originCheckEnabled() ? "on" : "off"} | \u8BF7\u6C42\u4F53\u4E0A\u9650=${maxBodyBytes()}B | \u9650\u6D41=${rateLimitQps() || "off"}`;
509
+ }
510
+ function autoTokenHint() {
511
+ if (authMode() === AUTH_MODE_OFF) return "-";
512
+ if (env("AGENT_GATE_AUTH_TOKEN")) return "env";
513
+ if (env("AGENT_GATE_AUTH_TOKEN_FD")) return "fd";
514
+ if (env("AGENT_GATE_AUTH_TOKEN_FILE")) return env("AGENT_GATE_AUTH_TOKEN_FILE");
515
+ return authTokenPath();
516
+ }
517
+ 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;
518
+ var init_security = __esm({
519
+ "src/shared/security.ts"() {
520
+ "use strict";
521
+ init_cjs_shims();
522
+ import_node_crypto = require("crypto");
523
+ import_node_fs = require("fs");
524
+ import_node_os = require("os");
525
+ import_node_path = require("path");
526
+ TRUTHY = ["1", "true", "yes", "on"];
527
+ PUBLIC_PATHS = ["/api/v1/health"];
528
+ DASHBOARD_COOKIE = "agent_gate_token";
529
+ AUTH_MODE_AUTO = "auto";
530
+ AUTH_MODE_OFF = "off";
531
+ DASHBOARD_SECURITY_HEADERS = {
532
+ "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'",
533
+ "X-Frame-Options": "DENY",
534
+ "X-Content-Type-Options": "nosniff",
535
+ "Referrer-Policy": "no-referrer"
536
+ };
537
+ tokenCache = null;
538
+ fdTokenCache = /* @__PURE__ */ new Map();
539
+ POOL_DEFAULTS = { biz: 16, read: 8, ops: 4, health: 4, other: 4 };
540
+ counters = /* @__PURE__ */ new Map();
541
+ mossTokenCache = { value: "", expires: 0 };
542
+ RateLimiter = class {
543
+ constructor(qps, burst) {
544
+ this.qps = qps;
545
+ this.burst = burst;
546
+ this.burst = burst ?? Math.max(qps, 1);
547
+ }
548
+ qps;
549
+ burst;
550
+ buckets = /* @__PURE__ */ new Map();
551
+ get enabled() {
552
+ return this.qps > 0;
553
+ }
554
+ allow(key) {
555
+ const now = Date.now() / 1e3;
556
+ const cur = this.buckets.get(key) ?? { tokens: this.burst, last: now };
557
+ const tokens = Math.min(this.burst, cur.tokens + (now - cur.last) * this.qps);
558
+ if (tokens < 1) {
559
+ this.buckets.set(key, { tokens, last: now });
560
+ return false;
561
+ }
562
+ this.buckets.set(key, { tokens: tokens - 1, last: now });
563
+ return true;
564
+ }
565
+ };
566
+ PooledLimiter = class {
567
+ counts = /* @__PURE__ */ new Map();
568
+ tryAcquire(key, limit) {
569
+ if (limit <= 0) return true;
570
+ const cur = this.counts.get(key) || 0;
571
+ if (cur >= limit) return false;
572
+ this.counts.set(key, cur + 1);
573
+ return true;
574
+ }
575
+ release(key) {
576
+ const cur = this.counts.get(key) || 0;
577
+ if (cur <= 1) this.counts.delete(key);
578
+ else this.counts.set(key, cur - 1);
579
+ }
580
+ };
581
+ }
582
+ });
583
+
44
584
  // src/shared/storage/json-storage.ts
45
585
  var json_storage_exports = {};
46
586
  __export(json_storage_exports, {
@@ -61,6 +601,7 @@ var init_json_storage = __esm({
61
601
  init_cjs_shims();
62
602
  import_fs = require("fs");
63
603
  import_path = require("path");
604
+ init_security();
64
605
  JsonStorage = class {
65
606
  dataDir;
66
607
  agentsPath;
@@ -76,10 +617,39 @@ var init_json_storage = __esm({
76
617
  this.agentsPath = (0, import_path.join)(this.dataDir, "agents.json");
77
618
  this.sessionsPath = (0, import_path.join)(this.dataDir, "sessions.json");
78
619
  this.toolCallsDir = (0, import_path.join)(this.dataDir, "tool_calls");
79
- if (!(0, import_fs.existsSync)(this.dataDir)) (0, import_fs.mkdirSync)(this.dataDir, { recursive: true });
80
- if (!(0, import_fs.existsSync)(this.toolCallsDir)) (0, import_fs.mkdirSync)(this.toolCallsDir, { recursive: true });
620
+ if (!(0, import_fs.existsSync)(this.dataDir)) (0, import_fs.mkdirSync)(this.dataDir, { recursive: true, mode: 448 });
621
+ if (!(0, import_fs.existsSync)(this.toolCallsDir)) (0, import_fs.mkdirSync)(this.toolCallsDir, { recursive: true, mode: 448 });
622
+ this.hardenStoragePermissions();
81
623
  this.nextId = this.recoverNextId();
82
624
  }
625
+ /** 把存储目录收紧到 0700、已有 JSON 文件收紧到 0600。
626
+ * 新建文件由 `writeJsonFile` 的 mode 保证;这里处理**存量**文件
627
+ * (旧版本按 umask 创建的 0644)以及 mkdirSync 对已存在目录不生效的问题。 */
628
+ hardenStoragePermissions() {
629
+ if (!hardenFilesEnabled()) return;
630
+ const uid = process.getuid?.();
631
+ const tighten = (p, mode) => {
632
+ try {
633
+ const st = (0, import_fs.statSync)(p);
634
+ if (st.isSymbolicLink()) return;
635
+ if (uid !== void 0 && st.uid !== uid) return;
636
+ if ((st.mode & 511) !== mode) (0, import_fs.chmodSync)(p, mode);
637
+ } catch {
638
+ }
639
+ };
640
+ tighten(this.dataDir, 448);
641
+ tighten(this.toolCallsDir, 448);
642
+ tighten(this.agentsPath, 384);
643
+ tighten(this.sessionsPath, 384);
644
+ try {
645
+ for (const f of (0, import_fs.readdirSync)(this.toolCallsDir)) {
646
+ if (f.endsWith(".json") || f.endsWith(".tmp")) {
647
+ tighten((0, import_path.join)(this.toolCallsDir, f), 384);
648
+ }
649
+ }
650
+ } catch {
651
+ }
652
+ }
83
653
  /** 扫描所有 tool_calls 文件,找到最大 id + 1 */
84
654
  recoverNextId() {
85
655
  let maxId = 0;
@@ -103,12 +673,12 @@ var init_json_storage = __esm({
103
673
  return fallback;
104
674
  }
105
675
  }
106
- /** 原子写入:先写 .tmp 再 rename */
676
+ /** 原子写入:先写 .tmp 再 rename(rename 保留 tmp 的 0600 权限) */
107
677
  writeJsonFile(path, data) {
108
678
  const dir = (0, import_path.dirname)(path);
109
- if (!(0, import_fs.existsSync)(dir)) (0, import_fs.mkdirSync)(dir, { recursive: true });
679
+ if (!(0, import_fs.existsSync)(dir)) (0, import_fs.mkdirSync)(dir, { recursive: true, mode: 448 });
110
680
  const tmp = path + ".tmp";
111
- (0, import_fs.writeFileSync)(tmp, JSON.stringify(data, null, 2), "utf-8");
681
+ (0, import_fs.writeFileSync)(tmp, JSON.stringify(data, null, 2), { encoding: "utf-8", mode: 384 });
112
682
  (0, import_fs.renameSync)(tmp, path);
113
683
  }
114
684
  loadAgents() {
@@ -222,6 +792,9 @@ var init_json_storage = __esm({
222
792
  } catch {
223
793
  }
224
794
  }
795
+ if (params.agentType) {
796
+ allRecords = allRecords.filter((r) => r.agent_type === params.agentType);
797
+ }
225
798
  if (params.decision) {
226
799
  allRecords = allRecords.filter((r) => r.decision === params.decision);
227
800
  }
@@ -232,6 +805,7 @@ var init_json_storage = __esm({
232
805
  }
233
806
  countToolCalls(params) {
234
807
  const sessions = this.loadSessions();
808
+ const agents = this.loadAgents();
235
809
  let allRecords = [];
236
810
  try {
237
811
  const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
@@ -241,6 +815,12 @@ var init_json_storage = __esm({
241
815
  }
242
816
  } catch {
243
817
  }
818
+ if (params.agentType) {
819
+ const allowed = new Set(
820
+ [...sessions.values()].filter((s) => (agents.get(s.agent_id)?.agent_type || "") === params.agentType).map((s) => s.id)
821
+ );
822
+ allRecords = allRecords.filter((r) => allowed.has(r.session_id));
823
+ }
244
824
  if (params.decision) {
245
825
  allRecords = allRecords.filter((r) => r.decision === params.decision);
246
826
  }
@@ -286,11 +866,12 @@ var init_json_storage = __esm({
286
866
  hostname: agent?.hostname || ""
287
867
  };
288
868
  }
289
- getAgentsList() {
869
+ getAgentsList(agentType) {
290
870
  const agents = this.loadAgents();
291
871
  const sessions = this.loadSessions();
292
872
  const result = [];
293
873
  for (const agent of agents.values()) {
874
+ if (agentType && agent.agent_type !== agentType) continue;
294
875
  let sessionCount = 0;
295
876
  let callCount = 0;
296
877
  for (const session of sessions.values()) {
@@ -311,6 +892,11 @@ var init_json_storage = __esm({
311
892
  result.sort((a, b) => b.call_count - a.call_count);
312
893
  return result.slice(0, 20);
313
894
  }
895
+ getSessionAgentType(sessionId) {
896
+ const session = this.loadSessions().get(sessionId);
897
+ if (!session) return void 0;
898
+ return this.loadAgents().get(session.agent_id)?.agent_type;
899
+ }
314
900
  getTimeline(limit = 100) {
315
901
  const buckets = /* @__PURE__ */ new Map();
316
902
  try {
@@ -494,6 +1080,10 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
494
1080
  conditions.push("tc.session_id = ?");
495
1081
  values.push(params.sessionId);
496
1082
  }
1083
+ if (params.agentType) {
1084
+ conditions.push("a.agent_type = ?");
1085
+ values.push(params.agentType);
1086
+ }
497
1087
  if (params.decision) {
498
1088
  conditions.push("tc.decision = ?");
499
1089
  values.push(params.decision);
@@ -516,9 +1106,16 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
516
1106
  conditions.push("tc.decision = ?");
517
1107
  values.push(params.decision);
518
1108
  }
1109
+ if (params.agentType) {
1110
+ conditions.push("a.agent_type = ?");
1111
+ values.push(params.agentType);
1112
+ }
519
1113
  const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
520
1114
  const row = this.db.prepare(
521
- `SELECT COUNT(*) as total FROM tool_calls tc ${where}`
1115
+ `SELECT COUNT(*) as total FROM tool_calls tc
1116
+ LEFT JOIN sessions s ON tc.session_id = s.id
1117
+ LEFT JOIN agents a ON s.agent_id = a.id
1118
+ ${where}`
522
1119
  ).get(...values);
523
1120
  return row?.total ?? 0;
524
1121
  }
@@ -526,11 +1123,11 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
526
1123
  const row = this.db.prepare("SELECT COUNT(*) as total FROM tool_calls").get();
527
1124
  let dbBytes = 0;
528
1125
  try {
529
- const { statSync: statSync2, existsSync: existsSync3 } = require("fs");
530
- dbBytes = statSync2(this.dbPath).size;
1126
+ const { statSync: statSync3, existsSync: existsSync3 } = require("fs");
1127
+ dbBytes = statSync3(this.dbPath).size;
531
1128
  for (const suffix of ["-wal", "-shm"]) {
532
1129
  const p = this.dbPath + suffix;
533
- if (existsSync3(p)) dbBytes += statSync2(p).size;
1130
+ if (existsSync3(p)) dbBytes += statSync3(p).size;
534
1131
  }
535
1132
  } catch {
536
1133
  }
@@ -544,7 +1141,8 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
544
1141
  })();
545
1142
  return result;
546
1143
  }
547
- getAgentsList() {
1144
+ getAgentsList(agentType) {
1145
+ const where = agentType ? "WHERE a.agent_type = ?" : "";
548
1146
  return this.db.prepare(`
549
1147
  SELECT a.agent_type, a.hostname, a.agent_version as version,
550
1148
  COUNT(DISTINCT s.id) as session_count,
@@ -552,10 +1150,19 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
552
1150
  FROM agents a
553
1151
  LEFT JOIN sessions s ON s.agent_id = a.id
554
1152
  LEFT JOIN tool_calls tc ON tc.session_id = s.id
1153
+ ${where}
555
1154
  GROUP BY a.id
556
1155
  ORDER BY call_count DESC
557
1156
  LIMIT 20
558
- `).all();
1157
+ `).all(...agentType ? [agentType] : []);
1158
+ }
1159
+ getSessionAgentType(sessionId) {
1160
+ const row = this.db.prepare(
1161
+ `SELECT a.agent_type as agent_type
1162
+ FROM sessions s JOIN agents a ON s.agent_id = a.id
1163
+ WHERE s.id = ?`
1164
+ ).get(sessionId);
1165
+ return row?.agent_type;
559
1166
  }
560
1167
  getTimeline(limit = 100) {
561
1168
  const rows = this.db.prepare(`
@@ -624,14 +1231,14 @@ function getDb(dbPath) {
624
1231
  if (rawDb) return rawDb;
625
1232
  try {
626
1233
  const Database = require("better-sqlite3");
627
- const { existsSync: existsSync3, mkdirSync: mkdirSync3 } = require("fs");
628
- const { join: join3, dirname: dirname3 } = require("path");
1234
+ const { existsSync: existsSync3, mkdirSync: mkdirSync4 } = require("fs");
1235
+ const { join: join4, dirname: dirname3 } = require("path");
629
1236
  const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
630
- const xdgData = process.env.XDG_DATA_HOME || join3(home, ".local", "share");
631
- const defaultPath = join3(xdgData, "agent_gate", "agent_gate_ts.db");
1237
+ const xdgData = process.env.XDG_DATA_HOME || join4(home, ".local", "share");
1238
+ const defaultPath = join4(xdgData, "agent_gate", "agent_gate_ts.db");
632
1239
  const path = dbPath || defaultPath;
633
1240
  const dir = dirname3(path);
634
- if (!existsSync3(dir)) mkdirSync3(dir, { recursive: true });
1241
+ if (!existsSync3(dir)) mkdirSync4(dir, { recursive: true });
635
1242
  rawDb = new Database(path);
636
1243
  rawDb.pragma("journal_mode = WAL");
637
1244
  return rawDb;
@@ -676,20 +1283,34 @@ var init_db = __esm({
676
1283
 
677
1284
  // src/shared/multi-session.ts
678
1285
  function isMultiSessionEnabled() {
679
- return process.env.AGENT_GATE_MULTI_SESSION === "1";
1286
+ const raw = (process.env.AGENT_GATE_MULTI_SESSION ?? "").trim().toLowerCase();
1287
+ if (raw === "") return true;
1288
+ return !MULTI_SESSION_OFF_VALUES.has(raw);
1289
+ }
1290
+ function sessionHistoryLimit() {
1291
+ const raw = (process.env.AGENT_GATE_SESSION_HISTORY_LIMIT ?? "").trim();
1292
+ const n = raw ? parseInt(raw, 10) : DEFAULT_MAX_SESSIONS;
1293
+ const v = Number.isFinite(n) ? n : DEFAULT_MAX_SESSIONS;
1294
+ return Math.max(1, Math.min(v, 50));
680
1295
  }
681
1296
  function buildSessionHistory(queryToolCalls2, sessionId) {
682
1297
  if (!isMultiSessionEnabled()) return [];
1298
+ const maxSessions = sessionHistoryLimit();
683
1299
  try {
684
- const recent = queryToolCalls2({ limit: DEFAULT_HISTORY_LIMIT });
1300
+ const scanLimit = Math.max(DEFAULT_HISTORY_LIMIT, maxSessions * DEFAULT_ACTIONS_PER_SESSION);
1301
+ const recent = queryToolCalls2({ limit: scanLimit });
685
1302
  const bySession = /* @__PURE__ */ new Map();
686
1303
  for (const tc of recent) {
687
1304
  if (tc.session_id === sessionId) continue;
688
1305
  const list = bySession.get(tc.session_id) || [];
689
- list.unshift({ action_type: tc.action_type, action_detail: tc.action_detail });
1306
+ list.unshift({
1307
+ action_type: tc.action_type,
1308
+ action_detail: tc.action_detail,
1309
+ ...tc.called_at ? { called_at: tc.called_at } : {}
1310
+ });
690
1311
  bySession.set(tc.session_id, list);
691
1312
  }
692
- return [...bySession.entries()].slice(0, DEFAULT_MAX_SESSIONS).map(([sid, actions]) => ({
1313
+ return [...bySession.entries()].slice(0, maxSessions).map(([sid, actions]) => ({
693
1314
  session_id: sid,
694
1315
  action_history: actions.slice(0, DEFAULT_ACTIONS_PER_SESSION)
695
1316
  }));
@@ -700,7 +1321,7 @@ function buildSessionHistory(queryToolCalls2, sessionId) {
700
1321
  function isStatefulIncrementalEnabled() {
701
1322
  return isMultiSessionEnabled();
702
1323
  }
703
- var DEFAULT_HISTORY_LIMIT, DEFAULT_MAX_SESSIONS, DEFAULT_ACTIONS_PER_SESSION;
1324
+ var DEFAULT_HISTORY_LIMIT, DEFAULT_MAX_SESSIONS, DEFAULT_ACTIONS_PER_SESSION, MULTI_SESSION_OFF_VALUES;
704
1325
  var init_multi_session = __esm({
705
1326
  "src/shared/multi-session.ts"() {
706
1327
  "use strict";
@@ -708,17 +1329,25 @@ var init_multi_session = __esm({
708
1329
  DEFAULT_HISTORY_LIMIT = 500;
709
1330
  DEFAULT_MAX_SESSIONS = 5;
710
1331
  DEFAULT_ACTIONS_PER_SESSION = 100;
1332
+ MULTI_SESSION_OFF_VALUES = /* @__PURE__ */ new Set(["0", "false", "no", "off"]);
711
1333
  }
712
1334
  });
713
1335
 
714
1336
  // src/shared/moss-client.ts
715
1337
  var moss_client_exports = {};
716
1338
  __export(moss_client_exports, {
1339
+ authHeaders: () => authHeaders,
717
1340
  callAgentMoss: () => callAgentMoss,
718
1341
  callAgentMossReview: () => callAgentMossReview,
719
1342
  fetchMossHealth: () => fetchMossHealth,
720
1343
  setMossUrl: () => setMossUrl
721
1344
  });
1345
+ function authHeaders() {
1346
+ const h = { "Content-Type": "application/json" };
1347
+ const tok = resolveMossToken();
1348
+ if (tok) h["Authorization"] = `Bearer ${tok}`;
1349
+ return h;
1350
+ }
722
1351
  function setMossUrl(url) {
723
1352
  mossUrl = url;
724
1353
  }
@@ -728,14 +1357,23 @@ async function callAgentMoss(request) {
728
1357
  if (isStatefulIncrementalEnabled() && req && typeof req === "object" && req.metadata === void 0) {
729
1358
  req.metadata = { stateful_incremental: true };
730
1359
  }
731
- const resp = await (0, import_node_fetch.default)(`${mossUrl}/api/v1/analyze`, {
1360
+ const body = JSON.stringify(req);
1361
+ let resp = await (0, import_node_fetch.default)(`${mossUrl}/api/v1/analyze`, {
732
1362
  method: "POST",
733
- headers: { "Content-Type": "application/json" },
734
- body: JSON.stringify(req),
735
- // 100s:覆盖 AgentMoss 总超时(90s)+ 余量,避免 AgentMoss 还在分析时
736
- // 被 AgentGate 抢断后 fail-closed 误杀。AgentGate 这层不重试(AgentMoss 内部已重试)。
1363
+ headers: authHeaders(),
1364
+ body,
737
1365
  timeout: 1e5
738
1366
  });
1367
+ if (resp.status === 401) {
1368
+ console.warn("[AgentGate] AgentMoss \u8FD4\u56DE 401\uFF0C\u5DF2\u91CD\u65B0\u8BFB\u53D6\u8BBF\u95EE token\uFF0C\u91CD\u8BD5\u4E00\u6B21");
1369
+ resolveMossToken(true);
1370
+ resp = await (0, import_node_fetch.default)(`${mossUrl}/api/v1/analyze`, {
1371
+ method: "POST",
1372
+ headers: authHeaders(),
1373
+ body,
1374
+ timeout: 1e5
1375
+ });
1376
+ }
739
1377
  if (!resp.ok) {
740
1378
  console.error(`[AgentGate] AgentMoss HTTP ${resp.status}: ${resp.statusText}`);
741
1379
  return failClosedResponse(`AgentMoss returned ${resp.status}`);
@@ -775,7 +1413,7 @@ async function callAgentMossReview(options) {
775
1413
  try {
776
1414
  const resp = await (0, import_node_fetch.default)(`${mossUrl}/api/v1/review`, {
777
1415
  method: "POST",
778
- headers: { "Content-Type": "application/json" },
1416
+ headers: authHeaders(),
779
1417
  body: JSON.stringify({ agent_id: agentId, db_path: dbPath }),
780
1418
  timeout: 3e4
781
1419
  });
@@ -803,8 +1441,9 @@ var init_moss_client = __esm({
803
1441
  init_cjs_shims();
804
1442
  import_node_fetch = __toESM(require("node-fetch"));
805
1443
  init_multi_session();
1444
+ init_security();
806
1445
  DEFAULT_MOSS_URL = "http://127.0.0.1:9090";
807
- mossUrl = DEFAULT_MOSS_URL;
1446
+ mossUrl = process.env.AGENT_MOSS_URL || process.env.MOSS_URL || DEFAULT_MOSS_URL;
808
1447
  }
809
1448
  });
810
1449
 
@@ -814,7 +1453,7 @@ var init_version = __esm({
814
1453
  "src/version.ts"() {
815
1454
  "use strict";
816
1455
  init_cjs_shims();
817
- _version = true ? "0.7.5" : (() => {
1456
+ _version = true ? "0.8.0" : (() => {
818
1457
  try {
819
1458
  const require2 = createRequire(importMetaUrl);
820
1459
  const pkg = require2("../package.json");
@@ -898,7 +1537,8 @@ var init_models = __esm({
898
1537
  status: import_zod.z.string().default("healthy"),
899
1538
  version: import_zod.z.string().default(version),
900
1539
  moss_version: import_zod.z.string().default("N/A"),
901
- moss_status: import_zod.z.string().default("unknown")
1540
+ moss_status: import_zod.z.string().default("unknown"),
1541
+ instance: import_zod.z.string().default("")
902
1542
  });
903
1543
  }
904
1544
  });
@@ -1110,12 +1750,15 @@ function getStorageStats() {
1110
1750
  function clearToolCalls() {
1111
1751
  return store().clearToolCalls();
1112
1752
  }
1113
- function getAgentsList() {
1114
- return store().getAgentsList();
1753
+ function getAgentsList(agentType) {
1754
+ return store().getAgentsList(agentType);
1115
1755
  }
1116
1756
  function getTimeline(limit) {
1117
1757
  return store().getTimeline(limit);
1118
1758
  }
1759
+ function getSessionAgentType(sessionId) {
1760
+ return store().getSessionAgentType(sessionId);
1761
+ }
1119
1762
  var init_repository = __esm({
1120
1763
  "src/shared/storage/repository.ts"() {
1121
1764
  "use strict";
@@ -1145,7 +1788,11 @@ async function healthRoute(c) {
1145
1788
  status: "healthy",
1146
1789
  version,
1147
1790
  moss_version: mossHealth.moss_version,
1148
- moss_status: mossHealth.moss_status
1791
+ moss_status: mossHealth.moss_status,
1792
+ // 归属标识:由启动方注入 AGENT_GATE_INSTANCE(同机多套 AgentGate 时用于区分是谁起的),
1793
+ // 未注入时为空串。与 agent-moss 的 AGENT_MOSS_INSTANCE 同一套约定,供探测端在
1794
+ // /proc 不可读、无法做 PID↔端口校验时退化为按实例字符串判归属。
1795
+ instance: process.env.AGENT_GATE_INSTANCE || ""
1149
1796
  });
1150
1797
  }
1151
1798
  function storageOversizeInfo() {
@@ -1159,6 +1806,12 @@ async function analyzeRoute(c) {
1159
1806
  try {
1160
1807
  const body = await c.req.json();
1161
1808
  const input = AgentGateInputSchema.parse(body);
1809
+ const principal = c.get("principal") || "";
1810
+ const bind = bindAgent(principal, input.agent_type || "");
1811
+ if (!bind.ok) {
1812
+ console.warn(`[AgentGate] \u62D2\u7EDD\u8EAB\u4EFD\u4E0D\u5339\u914D\u7684\u8BF7\u6C42: principal=${principal} claimed=${input.agent_type}`);
1813
+ return c.json({ detail: bind.reason }, 403);
1814
+ }
1162
1815
  const toolName = input.tool_name || input.a_next?.action_type || "unknown";
1163
1816
  const command = input.command || input.a_next?.action_detail || "";
1164
1817
  const key = cacheKey(input.session_id, input.cwd, command);
@@ -1239,7 +1892,22 @@ async function analyzeRoute(c) {
1239
1892
  }
1240
1893
  }
1241
1894
  async function sessionsRoute(c) {
1242
- const sessionId = c.req.param("id");
1895
+ const sessionId = c.req.param("id") || "";
1896
+ const principal = c.get("principal") || "ip:unknown";
1897
+ const [n, hit] = noteSessionAccess(principal, sessionId);
1898
+ if (hit) {
1899
+ if (sessionSweepAction() === "deny") {
1900
+ return c.json({ detail: "\u4F1A\u8BDD\u8BBF\u95EE\u8FC7\u4E8E\u96C6\u4E2D\uFF0C\u7591\u4F3C\u6279\u91CF\u626B\u63CF" }, 429);
1901
+ }
1902
+ 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`);
1903
+ }
1904
+ const bound = boundAgentOf(c.get("principal") || "");
1905
+ if (bound) {
1906
+ const owner = getSessionAgentType(sessionId);
1907
+ if ((owner || "").toLowerCase() !== bound.toLowerCase()) {
1908
+ return c.json({ detail: "\u8BE5\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u5F53\u524D\u51ED\u8BC1\u7ED1\u5B9A\u7684 agent" }, 403);
1909
+ }
1910
+ }
1243
1911
  const rows = queryToolCalls({ sessionId, limit: 100 });
1244
1912
  return c.json({ session_id: sessionId, tool_calls: rows });
1245
1913
  }
@@ -1247,26 +1915,38 @@ async function toolCallsRoute(c) {
1247
1915
  const decision = c.req.query("decision");
1248
1916
  const limit = parseInt(c.req.query("limit") || "50", 10);
1249
1917
  const offset = parseInt(c.req.query("offset") || "0", 10);
1250
- const total = countToolCalls({ decision });
1251
- const data = queryToolCalls({ decision, limit, offset });
1918
+ const bound = boundAgentOf(c.get("principal") || "");
1919
+ const agentType = bound || void 0;
1920
+ const total = countToolCalls({ decision: decision ?? void 0, agentType });
1921
+ const data = queryToolCalls({ decision: decision ?? void 0, agentType, limit, offset });
1252
1922
  return c.json({ total, data });
1253
1923
  }
1254
1924
  async function agentsRoute(c) {
1255
- const agents = getAgentsList();
1925
+ const bound = boundAgentOf(c.get("principal") || "");
1926
+ const agents = getAgentsList(bound || void 0);
1256
1927
  return c.json(agents);
1257
1928
  }
1258
1929
  async function timelineRoute(c) {
1930
+ if (boundAgentOf(c.get("principal") || "")) {
1931
+ return c.json({ detail: "\u8BE5\u51ED\u8BC1\u7ED1\u5B9A\u5230 agent\uFF0C\u65E0\u6743\u67E5\u770B\u5168\u5C40\u65F6\u95F4\u7EBF" }, 403);
1932
+ }
1259
1933
  const limit = parseInt(c.req.query("limit") || "100", 10);
1260
1934
  const rows = getTimeline(limit);
1261
1935
  return c.json(rows);
1262
1936
  }
1263
1937
  function storageStatsRoute(c) {
1938
+ if (boundAgentOf(c.get("principal") || "")) {
1939
+ return c.json({ detail: "\u8BE5\u51ED\u8BC1\u7ED1\u5B9A\u5230 agent\uFF0C\u65E0\u6743\u67E5\u770B\u5B58\u50A8\u7EDF\u8BA1" }, 403);
1940
+ }
1264
1941
  const storageStats = getStorageStats();
1265
1942
  const defaultThreshold = parseFloat(process.env.AGENT_GATE_CLEANUP_THRESHOLD_MB || "100");
1266
1943
  const totalMB = (storageStats.dbBytes + storageStats.jsonBytes) / 1024 / 1024;
1267
1944
  return c.json({ stats: storageStats, oversize: totalMB > defaultThreshold, thresholdMB: defaultThreshold });
1268
1945
  }
1269
1946
  function deleteToolCallsRoute(c) {
1947
+ if (boundAgentOf(c.get("principal") || "")) {
1948
+ return c.json({ detail: "\u8BE5\u51ED\u8BC1\u7ED1\u5B9A\u5230 agent\uFF0C\u65E0\u6743\u6E05\u7406\u8BB0\u5F55" }, 403);
1949
+ }
1270
1950
  const deleted = clearToolCalls();
1271
1951
  return c.json({ deleted });
1272
1952
  }
@@ -1283,6 +1963,7 @@ var init_routes = __esm({
1283
1963
  init_repository();
1284
1964
  init_multi_session();
1285
1965
  init_agent_identity();
1966
+ init_security();
1286
1967
  init_version();
1287
1968
  v1ReviewCounter = 0;
1288
1969
  }
@@ -1295,8 +1976,97 @@ __export(server_exports, {
1295
1976
  });
1296
1977
  function createApp() {
1297
1978
  const app = new import_hono.Hono();
1298
- app.use("*", (0, import_cors.cors)({ origin: "*", allowMethods: ["GET", "POST", "OPTIONS", "DELETE"], allowHeaders: ["*"] }));
1979
+ const rateLimiter = new RateLimiter(rateLimitQps());
1980
+ const pools = new PooledLimiter();
1981
+ app.use("*", (0, import_cors.cors)({
1982
+ origin: (origin) => allowedOrigins().includes(normalizeOrigin(origin)) ? origin : null,
1983
+ allowMethods: ["GET", "POST", "OPTIONS", "DELETE"],
1984
+ allowHeaders: ["*"]
1985
+ }));
1299
1986
  app.use("*", (0, import_logger.logger)());
1987
+ app.use("*", async (c, next) => {
1988
+ const path = new URL(c.req.url).pathname;
1989
+ const method = c.req.method.toUpperCase();
1990
+ if (method === "OPTIONS") return next();
1991
+ const cl = c.req.header("content-length");
1992
+ const maxBody = maxBodyBytes();
1993
+ if (cl && maxBody > 0) {
1994
+ const n = parseInt(cl, 10);
1995
+ if (Number.isFinite(n) && n > maxBody) {
1996
+ return c.json({ detail: `\u8BF7\u6C42\u4F53\u8D85\u8FC7\u4E0A\u9650 ${maxBody} \u5B57\u8282` }, 413);
1997
+ }
1998
+ }
1999
+ if (originCheckEnabled()) {
2000
+ const origin = c.req.header("origin") || "";
2001
+ if (origin && !originAllowed(origin, c.req.header("host") || "")) {
2002
+ console.warn(`[AgentGate] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path}`);
2003
+ return c.json({ detail: `\u8DE8\u6E90\u6765\u6E90\u672A\u88AB\u5141\u8BB8: ${origin}` }, 403);
2004
+ }
2005
+ }
2006
+ const headers = { authorization: c.req.header("authorization") };
2007
+ const cookie = (0, import_cookie.getCookie)(c, DASHBOARD_COOKIE) || "";
2008
+ const requireGlobal = path.startsWith("/dashboard") || path.startsWith("/ws/");
2009
+ const { ok, principal } = checkRequestAuth(headers, path, cookie, requireGlobal);
2010
+ if (!ok && !PUBLIC_PAGE_PATHS.includes(path)) {
2011
+ if (boundAgentOf(principal)) {
2012
+ 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);
2013
+ }
2014
+ c.header("WWW-Authenticate", "Bearer");
2015
+ return c.json({ detail: "Unauthorized: invalid or missing Bearer token" }, 401);
2016
+ }
2017
+ c.set("principal", principal);
2018
+ if (rateLimiter.enabled) {
2019
+ const key = principal || `ip:${c.req.header("x-forwarded-for") || "unknown"}`;
2020
+ if (!rateLimiter.allow(key)) {
2021
+ c.header("Retry-After", "1");
2022
+ return c.json({ detail: "\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" }, 429);
2023
+ }
2024
+ }
2025
+ const ip = c.req.header("x-forwarded-for") || "unknown";
2026
+ const keys = [];
2027
+ const take = (key, limit) => {
2028
+ if (pools.tryAcquire(key, limit)) {
2029
+ keys.push(key);
2030
+ return true;
2031
+ }
2032
+ return false;
2033
+ };
2034
+ const busy = (detail, status = 503) => {
2035
+ c.header("Retry-After", "1");
2036
+ c.header("Connection", "close");
2037
+ return c.json({ detail }, status);
2038
+ };
2039
+ try {
2040
+ if (!principal && authEnabled()) {
2041
+ if (!take("unauth:total", unauthInflight())) {
2042
+ return busy("\u672A\u8BA4\u8BC1\u8BF7\u6C42\u5E76\u53D1\u8D85\u9650\uFF0C\u8BF7\u6301\u51ED\u8BC1\u8BBF\u95EE");
2043
+ }
2044
+ if (!take(`unauth:ip:${ip}`, unauthPerIp())) {
2045
+ return busy("\u8BE5\u6765\u6E90\u7684\u672A\u8BA4\u8BC1\u8BF7\u6C42\u5E76\u53D1\u8D85\u9650");
2046
+ }
2047
+ } else {
2048
+ const bound = boundAgentOf(principal);
2049
+ if (bound && !take(`agent:${bound}`, agentInflight())) {
2050
+ return busy(`agent '${bound}' \u7684\u5E76\u53D1\u8D85\u9650\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`, 429);
2051
+ }
2052
+ }
2053
+ const pool = poolOf(path);
2054
+ if (!take(`pool:${pool}`, poolLimit(pool))) {
2055
+ const qkey = principal || `ip:${ip}`;
2056
+ const [n, abusive] = noteQueueReject(qkey);
2057
+ if (abusive && queueAbuseAction() === "deny") {
2058
+ return busy("\u5E76\u53D1\u62D2\u7EDD\u8FC7\u4E8E\u9891\u7E41\uFF0C\u7591\u4F3C\u6076\u610F\u8BF7\u6C42", 429);
2059
+ }
2060
+ if (abusive) {
2061
+ console.warn(`[AgentGate] \u26A0\uFE0F \u7591\u4F3C\u6076\u610F\u5E76\u53D1\u5360\u7528: key=${qkey} \u7A97\u53E3\u5185\u88AB\u62D2 ${n} \u6B21`);
2062
+ }
2063
+ return busy("\u670D\u52A1\u7E41\u5FD9\uFF08\u5E76\u53D1\u5DF2\u6EE1\uFF09\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");
2064
+ }
2065
+ return await next();
2066
+ } finally {
2067
+ while (keys.length) pools.release(keys.pop());
2068
+ }
2069
+ });
1300
2070
  app.get("/api/v1/health", healthRoute);
1301
2071
  app.post("/api/v1/analyze", analyzeRoute);
1302
2072
  app.get("/api/v1/sessions/:id/traces", sessionsRoute);
@@ -1310,7 +2080,26 @@ function createApp() {
1310
2080
  return app;
1311
2081
  }
1312
2082
  async function dashboardRoute(c) {
1313
- const { readFileSync: readFileSync2, existsSync: existsSync3 } = await import("fs");
2083
+ if (authEnabled()) {
2084
+ const token = c.req.query("token") || "";
2085
+ if (token && isGlobalToken(token)) {
2086
+ (0, import_cookie.setCookie)(c, DASHBOARD_COOKIE, token, {
2087
+ httpOnly: true,
2088
+ sameSite: "Strict",
2089
+ path: "/"
2090
+ });
2091
+ c.header("Referrer-Policy", "no-referrer");
2092
+ return c.redirect("/dashboard/", 302);
2093
+ }
2094
+ const cookie = (0, import_cookie.getCookie)(c, DASHBOARD_COOKIE) || "";
2095
+ if (!isGlobalToken(cookie)) {
2096
+ if (token && checkToken(token) || cookie && checkToken(cookie)) {
2097
+ return c.html(AGENT_FORBIDDEN_HTML, 403, DASHBOARD_SECURITY_HEADERS);
2098
+ }
2099
+ return c.html(UNAUTHORIZED_HTML, 401, DASHBOARD_SECURITY_HEADERS);
2100
+ }
2101
+ }
2102
+ const { readFileSync: readFileSync3, existsSync: existsSync3 } = await import("fs");
1314
2103
  const { resolve, dirname: dirname3 } = await import("path");
1315
2104
  const { fileURLToPath } = await import("url");
1316
2105
  const __dirname = dirname3(fileURLToPath(importMetaUrl));
@@ -1320,10 +2109,10 @@ async function dashboardRoute(c) {
1320
2109
  resolve(__dirname, "../src/v1/dashboard.html")
1321
2110
  ];
1322
2111
  const htmlPath = paths.find((p) => existsSync3(p)) || paths[0];
1323
- const html = readFileSync2(htmlPath, "utf-8");
1324
- return c.html(html);
2112
+ const html = readFileSync3(htmlPath, "utf-8");
2113
+ return c.html(html, 200, DASHBOARD_SECURITY_HEADERS);
1325
2114
  }
1326
- var import_hono, import_cors, import_logger;
2115
+ var import_hono, import_cors, import_logger, import_cookie, PUBLIC_PAGE_PATHS, UNAUTHORIZED_HTML, AGENT_FORBIDDEN_HTML;
1327
2116
  var init_server = __esm({
1328
2117
  "src/v1/server.ts"() {
1329
2118
  "use strict";
@@ -1331,7 +2120,40 @@ var init_server = __esm({
1331
2120
  import_hono = require("hono");
1332
2121
  import_cors = require("hono/cors");
1333
2122
  import_logger = require("hono/logger");
2123
+ import_cookie = require("hono/cookie");
1334
2124
  init_routes();
2125
+ init_security();
2126
+ PUBLIC_PAGE_PATHS = ["/dashboard", "/dashboard/"];
2127
+ UNAUTHORIZED_HTML = `<!DOCTYPE html>
2128
+ <html lang="zh-CN"><head><meta charset="UTF-8"><title>AgentGate Dashboard</title>
2129
+ <style>body{font:14px/1.6 -apple-system,'Segoe UI',sans-serif;background:#FAFAFA;color:#1d1d1f;
2130
+ display:flex;align-items:center;justify-content:center;height:100vh;margin:0}
2131
+ .box{background:#fff;border:1px solid #eee;border-radius:10px;padding:28px 32px;max-width:560px}
2132
+ code{background:#F5F5F7;padding:1px 6px;border-radius:4px;font-size:13px}
2133
+ p{margin:8px 0;color:#555}</style></head><body>
2134
+ <div class="box">
2135
+ <h3 style="margin-top:0">\u9700\u8981\u8BBF\u95EE\u51ED\u8BC1</h3>
2136
+ <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>
2137
+ <p><code>/dashboard/?token=&lt;token&gt;</code></p>
2138
+ <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
2139
+ \u6362 Cookie \u540E\u5C31\u53EA\u9700\u6253\u5F00 <code>/dashboard/</code>\u3002</p>
2140
+ <p>\u5982\u9700\u6062\u590D\u65E7\u884C\u4E3A\uFF1A<code>AGENT_GATE_AUTH_MODE=off</code>\u3002</p>
2141
+ </div></body></html>`;
2142
+ AGENT_FORBIDDEN_HTML = `<!DOCTYPE html>
2143
+ <html lang="zh-CN"><head><meta charset="UTF-8"><title>AgentGate Dashboard</title>
2144
+ <style>body{font:14px/1.6 -apple-system,'Segoe UI',sans-serif;background:#FAFAFA;color:#1d1d1f;
2145
+ display:flex;align-items:center;justify-content:center;height:100vh;margin:0}
2146
+ .box{background:#fff;border:1px solid #eee;border-radius:10px;padding:28px 32px;max-width:560px}
2147
+ code{background:#F5F5F7;padding:1px 6px;border-radius:4px;font-size:13px}
2148
+ p{margin:8px 0;color:#555}</style></head><body>
2149
+ <div class="box">
2150
+ <h3 style="margin-top:0">\u8BE5\u51ED\u8BC1\u65E0\u6743\u8BBF\u95EE\u770B\u677F</h3>
2151
+ <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
2152
+ \u5426\u5219 agent A \u5C31\u80FD\u770B\u5230 agent B \u7684\u5168\u90E8\u547D\u4EE4\u539F\u6587\u548C\u7528\u6237 prompt\u3002</p>
2153
+ <p>agent \u81EA\u67E5\u8BF7\u7528\u8BFB\u63A5\u53E3\uFF08\u6309\u51ED\u8BC1\u7ED1\u5B9A\u7684 agent \u81EA\u52A8\u8FC7\u6EE4\uFF09\uFF1A
2154
+ <code>/api/v1/sessions/&lt;id&gt;/traces</code>\u3001<code>/api/v1/tool_calls</code>\u3002</p>
2155
+ <p>\u8FD0\u7EF4\u8BF7\u4F7F\u7528\u5168\u5C40 token\uFF1A<code>~/.config/agentgate/auth_token</code>\u3002</p>
2156
+ </div></body></html>`;
1335
2157
  }
1336
2158
  });
1337
2159
 
@@ -1342,12 +2164,13 @@ async function main() {
1342
2164
  const command = args[0];
1343
2165
  if (!command || command === "--help" || command === "-h") {
1344
2166
  console.log("AgentGate V1 CLI \u2014 start the HTTP API server\n");
1345
- console.log("Usage: agent-gate-v1 server [--host <host>] [--port <port>] [--db-path <path>] [--moss-url <url>]");
1346
- console.log(" --host Bind host (default 127.0.0.1)");
1347
- console.log(" --port Bind port (default 9100)");
1348
- console.log(" --db-path SQLite db file path (sqlite mode only)");
1349
- console.log(" --moss-url AgentMoss URL (or env MOSS_URL)");
1350
- console.log(" --help, -h Show this help");
2167
+ console.log("Usage: agent-gate-v1 server [--host <host>] [--port <port>] [--db-path <path>] [--security-url <url>]");
2168
+ console.log(" --host Bind host (default 127.0.0.1)");
2169
+ console.log(" --port Bind port (default 9100)");
2170
+ console.log(" --db-path SQLite db file path (sqlite mode only)");
2171
+ console.log(" --security-url AgentMoss URL (default: $AGENT_MOSS_URL / $MOSS_URL / 9090)");
2172
+ console.log(" --moss-url Alias of --security-url (historical name)");
2173
+ console.log(" --help, -h Show this help");
1351
2174
  process.exit(command ? 0 : 1);
1352
2175
  }
1353
2176
  if (command !== "server") {
@@ -1364,11 +2187,18 @@ async function main() {
1364
2187
  else if (args[i] === "--port" && args[i + 1]) port = parseInt(args[++i], 10);
1365
2188
  else if (args[i] === "--db-path" && args[i + 1]) dbPath = args[++i];
1366
2189
  else if (args[i] === "--moss-url" && args[i + 1]) mossUrl2 = args[++i];
2190
+ else if (args[i] === "--security-url" && args[i + 1]) mossUrl2 = args[++i];
1367
2191
  }
1368
- mossUrl2 = mossUrl2 || process.env.MOSS_URL;
2192
+ mossUrl2 = mossUrl2 || process.env.AGENT_MOSS_URL || process.env.MOSS_URL;
1369
2193
  const dataDir = process.env.AGENT_GATE_DATA_DIR;
1370
- const { createStorage: createStorage2 } = await Promise.resolve().then(() => (init_db(), db_exports));
2194
+ const { createStorage: createStorage2, getAgentGateDbPath: getAgentGateDbPath2 } = await Promise.resolve().then(() => (init_db(), db_exports));
1371
2195
  createStorage2({ dbPath, dataDir });
2196
+ const { hardenDbFiles: hardenDbFiles2, describe: describe2, authEnabled: authEnabled2, authToken: authToken2, failFastOnAuthError: failFastOnAuthError2 } = await Promise.resolve().then(() => (init_security(), security_exports));
2197
+ if ((process.env.AGENT_GATE_STORAGE || "sqlite").toLowerCase() !== "json") {
2198
+ hardenDbFiles2(getAgentGateDbPath2());
2199
+ }
2200
+ console.log(describe2());
2201
+ failFastOnAuthError2();
1372
2202
  if (mossUrl2) {
1373
2203
  const { setMossUrl: setMossUrl2 } = await Promise.resolve().then(() => (init_moss_client(), moss_client_exports));
1374
2204
  setMossUrl2(mossUrl2);
@@ -1377,6 +2207,9 @@ async function main() {
1377
2207
  const { createApp: createApp2 } = await Promise.resolve().then(() => (init_server(), server_exports));
1378
2208
  const app = createApp2();
1379
2209
  console.log(`AgentGate HTTP server on ${host}:${port}`);
2210
+ if (authEnabled2() && authToken2()) {
2211
+ console.log(`Dashboard: http://localhost:${port}/dashboard/?token=${authToken2()}`);
2212
+ }
1380
2213
  serve({ fetch: app.fetch, hostname: host, port }, (info) => {
1381
2214
  console.log(`Listening on http://${host}:${port}`);
1382
2215
  });