@kenhkl/agent-gate 0.7.6 → 0.8.1
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/dashboard.html +11 -2
- package/dist/shared/storage/db.d.ts +6 -1
- package/dist/shared/storage/db.js +104 -17
- package/dist/v1/cli.js +879 -49
- package/dist/v1/server.d.ts +8 -2
- package/dist/v1/server.js +735 -40
- package/dist/v3/cli.js +983 -96
- package/package.json +1 -1
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.
|
|
53
|
+
_version = true ? "0.8.1" : (() => {
|
|
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
|
|
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:
|
|
552
|
-
dbBytes =
|
|
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 +=
|
|
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:
|
|
650
|
-
const { join:
|
|
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 ||
|
|
653
|
-
const defaultPath =
|
|
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))
|
|
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
|
-
|
|
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
|
|
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({
|
|
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,
|
|
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
|
|
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:
|
|
756
|
-
body
|
|
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:
|
|
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
|
|
|
@@ -1114,12 +1753,15 @@ function getStorageStats() {
|
|
|
1114
1753
|
function clearToolCalls() {
|
|
1115
1754
|
return store().clearToolCalls();
|
|
1116
1755
|
}
|
|
1117
|
-
function getAgentsList() {
|
|
1118
|
-
return store().getAgentsList();
|
|
1756
|
+
function getAgentsList(agentType) {
|
|
1757
|
+
return store().getAgentsList(agentType);
|
|
1119
1758
|
}
|
|
1120
1759
|
function getTimeline(limit) {
|
|
1121
1760
|
return store().getTimeline(limit);
|
|
1122
1761
|
}
|
|
1762
|
+
function getSessionAgentType(sessionId) {
|
|
1763
|
+
return store().getSessionAgentType(sessionId);
|
|
1764
|
+
}
|
|
1123
1765
|
var init_repository = __esm({
|
|
1124
1766
|
"src/shared/storage/repository.ts"() {
|
|
1125
1767
|
"use strict";
|
|
@@ -1167,6 +1809,12 @@ async function analyzeRoute(c) {
|
|
|
1167
1809
|
try {
|
|
1168
1810
|
const body = await c.req.json();
|
|
1169
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
|
+
}
|
|
1170
1818
|
const toolName = input.tool_name || input.a_next?.action_type || "unknown";
|
|
1171
1819
|
const command = input.command || input.a_next?.action_detail || "";
|
|
1172
1820
|
const key = cacheKey(input.session_id, input.cwd, command);
|
|
@@ -1247,7 +1895,22 @@ async function analyzeRoute(c) {
|
|
|
1247
1895
|
}
|
|
1248
1896
|
}
|
|
1249
1897
|
async function sessionsRoute(c) {
|
|
1250
|
-
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
|
+
}
|
|
1251
1914
|
const rows = queryToolCalls({ sessionId, limit: 100 });
|
|
1252
1915
|
return c.json({ session_id: sessionId, tool_calls: rows });
|
|
1253
1916
|
}
|
|
@@ -1255,26 +1918,38 @@ async function toolCallsRoute(c) {
|
|
|
1255
1918
|
const decision = c.req.query("decision");
|
|
1256
1919
|
const limit = parseInt(c.req.query("limit") || "50", 10);
|
|
1257
1920
|
const offset = parseInt(c.req.query("offset") || "0", 10);
|
|
1258
|
-
const
|
|
1259
|
-
const
|
|
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 });
|
|
1260
1925
|
return c.json({ total, data });
|
|
1261
1926
|
}
|
|
1262
1927
|
async function agentsRoute(c) {
|
|
1263
|
-
const
|
|
1928
|
+
const bound = boundAgentOf(c.get("principal") || "");
|
|
1929
|
+
const agents = getAgentsList(bound || void 0);
|
|
1264
1930
|
return c.json(agents);
|
|
1265
1931
|
}
|
|
1266
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
|
+
}
|
|
1267
1936
|
const limit = parseInt(c.req.query("limit") || "100", 10);
|
|
1268
1937
|
const rows = getTimeline(limit);
|
|
1269
1938
|
return c.json(rows);
|
|
1270
1939
|
}
|
|
1271
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
|
+
}
|
|
1272
1944
|
const storageStats = getStorageStats();
|
|
1273
1945
|
const defaultThreshold = parseFloat(process.env.AGENT_GATE_CLEANUP_THRESHOLD_MB || "100");
|
|
1274
1946
|
const totalMB = (storageStats.dbBytes + storageStats.jsonBytes) / 1024 / 1024;
|
|
1275
1947
|
return c.json({ stats: storageStats, oversize: totalMB > defaultThreshold, thresholdMB: defaultThreshold });
|
|
1276
1948
|
}
|
|
1277
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
|
+
}
|
|
1278
1953
|
const deleted = clearToolCalls();
|
|
1279
1954
|
return c.json({ deleted });
|
|
1280
1955
|
}
|
|
@@ -1291,6 +1966,7 @@ var init_routes = __esm({
|
|
|
1291
1966
|
init_repository();
|
|
1292
1967
|
init_multi_session();
|
|
1293
1968
|
init_agent_identity();
|
|
1969
|
+
init_security();
|
|
1294
1970
|
init_version();
|
|
1295
1971
|
v1ReviewCounter = 0;
|
|
1296
1972
|
}
|
|
@@ -1303,8 +1979,97 @@ __export(server_exports, {
|
|
|
1303
1979
|
});
|
|
1304
1980
|
function createApp() {
|
|
1305
1981
|
const app = new import_hono.Hono();
|
|
1306
|
-
|
|
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
|
+
}));
|
|
1307
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
|
+
});
|
|
1308
2073
|
app.get("/api/v1/health", healthRoute);
|
|
1309
2074
|
app.post("/api/v1/analyze", analyzeRoute);
|
|
1310
2075
|
app.get("/api/v1/sessions/:id/traces", sessionsRoute);
|
|
@@ -1318,7 +2083,28 @@ function createApp() {
|
|
|
1318
2083
|
return app;
|
|
1319
2084
|
}
|
|
1320
2085
|
async function dashboardRoute(c) {
|
|
1321
|
-
|
|
2086
|
+
if (authEnabled()) {
|
|
2087
|
+
const token = c.req.query("token") || "";
|
|
2088
|
+
const cookie = (0, import_cookie.getCookie)(c, DASHBOARD_COOKIE) || "";
|
|
2089
|
+
const authHeader = c.req.header("authorization") || "";
|
|
2090
|
+
const bearer = authHeader.toLowerCase().startsWith("bearer ") ? authHeader.slice(7).trim() : "";
|
|
2091
|
+
if (bearer && isGlobalToken(bearer)) {
|
|
2092
|
+
} else if (token && isGlobalToken(token)) {
|
|
2093
|
+
(0, import_cookie.setCookie)(c, DASHBOARD_COOKIE, token, {
|
|
2094
|
+
httpOnly: true,
|
|
2095
|
+
sameSite: "Strict",
|
|
2096
|
+
path: "/"
|
|
2097
|
+
});
|
|
2098
|
+
c.header("Referrer-Policy", "no-referrer");
|
|
2099
|
+
return c.redirect("/dashboard/", 302);
|
|
2100
|
+
} else if (!isGlobalToken(cookie)) {
|
|
2101
|
+
if (bearer && checkToken(bearer) || token && checkToken(token) || cookie && checkToken(cookie)) {
|
|
2102
|
+
return c.html(AGENT_FORBIDDEN_HTML, 403, DASHBOARD_SECURITY_HEADERS);
|
|
2103
|
+
}
|
|
2104
|
+
return c.html(UNAUTHORIZED_HTML, 401, DASHBOARD_SECURITY_HEADERS);
|
|
2105
|
+
}
|
|
2106
|
+
}
|
|
2107
|
+
const { readFileSync: readFileSync14, existsSync: existsSync12 } = await import("fs");
|
|
1322
2108
|
const { resolve: resolve3, dirname: dirname5 } = await import("path");
|
|
1323
2109
|
const { fileURLToPath } = await import("url");
|
|
1324
2110
|
const __dirname2 = dirname5(fileURLToPath(importMetaUrl));
|
|
@@ -1328,10 +2114,10 @@ async function dashboardRoute(c) {
|
|
|
1328
2114
|
resolve3(__dirname2, "../src/v1/dashboard.html")
|
|
1329
2115
|
];
|
|
1330
2116
|
const htmlPath = paths.find((p) => existsSync12(p)) || paths[0];
|
|
1331
|
-
const html =
|
|
1332
|
-
return c.html(html);
|
|
2117
|
+
const html = readFileSync14(htmlPath, "utf-8");
|
|
2118
|
+
return c.html(html, 200, DASHBOARD_SECURITY_HEADERS);
|
|
1333
2119
|
}
|
|
1334
|
-
var import_hono, import_cors, import_logger;
|
|
2120
|
+
var import_hono, import_cors, import_logger, import_cookie, PUBLIC_PAGE_PATHS, UNAUTHORIZED_HTML, AGENT_FORBIDDEN_HTML;
|
|
1335
2121
|
var init_server = __esm({
|
|
1336
2122
|
"src/v1/server.ts"() {
|
|
1337
2123
|
"use strict";
|
|
@@ -1339,7 +2125,40 @@ var init_server = __esm({
|
|
|
1339
2125
|
import_hono = require("hono");
|
|
1340
2126
|
import_cors = require("hono/cors");
|
|
1341
2127
|
import_logger = require("hono/logger");
|
|
2128
|
+
import_cookie = require("hono/cookie");
|
|
1342
2129
|
init_routes();
|
|
2130
|
+
init_security();
|
|
2131
|
+
PUBLIC_PAGE_PATHS = ["/dashboard", "/dashboard/"];
|
|
2132
|
+
UNAUTHORIZED_HTML = `<!DOCTYPE html>
|
|
2133
|
+
<html lang="zh-CN"><head><meta charset="UTF-8"><title>AgentGate Dashboard</title>
|
|
2134
|
+
<style>body{font:14px/1.6 -apple-system,'Segoe UI',sans-serif;background:#FAFAFA;color:#1d1d1f;
|
|
2135
|
+
display:flex;align-items:center;justify-content:center;height:100vh;margin:0}
|
|
2136
|
+
.box{background:#fff;border:1px solid #eee;border-radius:10px;padding:28px 32px;max-width:560px}
|
|
2137
|
+
code{background:#F5F5F7;padding:1px 6px;border-radius:4px;font-size:13px}
|
|
2138
|
+
p{margin:8px 0;color:#555}</style></head><body>
|
|
2139
|
+
<div class="box">
|
|
2140
|
+
<h3 style="margin-top:0">\u9700\u8981\u8BBF\u95EE\u51ED\u8BC1</h3>
|
|
2141
|
+
<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>
|
|
2142
|
+
<p><code>/dashboard/?token=<token></code></p>
|
|
2143
|
+
<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
|
|
2144
|
+
\u6362 Cookie \u540E\u5C31\u53EA\u9700\u6253\u5F00 <code>/dashboard/</code>\u3002</p>
|
|
2145
|
+
<p>\u5982\u9700\u6062\u590D\u65E7\u884C\u4E3A\uFF1A<code>AGENT_GATE_AUTH_MODE=off</code>\u3002</p>
|
|
2146
|
+
</div></body></html>`;
|
|
2147
|
+
AGENT_FORBIDDEN_HTML = `<!DOCTYPE html>
|
|
2148
|
+
<html lang="zh-CN"><head><meta charset="UTF-8"><title>AgentGate Dashboard</title>
|
|
2149
|
+
<style>body{font:14px/1.6 -apple-system,'Segoe UI',sans-serif;background:#FAFAFA;color:#1d1d1f;
|
|
2150
|
+
display:flex;align-items:center;justify-content:center;height:100vh;margin:0}
|
|
2151
|
+
.box{background:#fff;border:1px solid #eee;border-radius:10px;padding:28px 32px;max-width:560px}
|
|
2152
|
+
code{background:#F5F5F7;padding:1px 6px;border-radius:4px;font-size:13px}
|
|
2153
|
+
p{margin:8px 0;color:#555}</style></head><body>
|
|
2154
|
+
<div class="box">
|
|
2155
|
+
<h3 style="margin-top:0">\u8BE5\u51ED\u8BC1\u65E0\u6743\u8BBF\u95EE\u770B\u677F</h3>
|
|
2156
|
+
<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
|
|
2157
|
+
\u5426\u5219 agent A \u5C31\u80FD\u770B\u5230 agent B \u7684\u5168\u90E8\u547D\u4EE4\u539F\u6587\u548C\u7528\u6237 prompt\u3002</p>
|
|
2158
|
+
<p>agent \u81EA\u67E5\u8BF7\u7528\u8BFB\u63A5\u53E3\uFF08\u6309\u51ED\u8BC1\u7ED1\u5B9A\u7684 agent \u81EA\u52A8\u8FC7\u6EE4\uFF09\uFF1A
|
|
2159
|
+
<code>/api/v1/sessions/<id>/traces</code>\u3001<code>/api/v1/tool_calls</code>\u3002</p>
|
|
2160
|
+
<p>\u8FD0\u7EF4\u8BF7\u4F7F\u7528\u5168\u5C40 token\uFF1A<code>~/.config/agentgate/auth_token</code>\u3002</p>
|
|
2161
|
+
</div></body></html>`;
|
|
1343
2162
|
}
|
|
1344
2163
|
});
|
|
1345
2164
|
|
|
@@ -5459,7 +6278,7 @@ var require_websocket = __commonJS({
|
|
|
5459
6278
|
var http5 = require("http");
|
|
5460
6279
|
var net2 = require("net");
|
|
5461
6280
|
var tls = require("tls");
|
|
5462
|
-
var { randomBytes, createHash:
|
|
6281
|
+
var { randomBytes: randomBytes2, createHash: createHash4 } = require("crypto");
|
|
5463
6282
|
var { Duplex, Readable } = require("stream");
|
|
5464
6283
|
var { URL: URL5 } = require("url");
|
|
5465
6284
|
var PerMessageDeflate = require_permessage_deflate();
|
|
@@ -5997,7 +6816,7 @@ var require_websocket = __commonJS({
|
|
|
5997
6816
|
}
|
|
5998
6817
|
}
|
|
5999
6818
|
const defaultPort = isSecure ? 443 : 80;
|
|
6000
|
-
const key =
|
|
6819
|
+
const key = randomBytes2(16).toString("base64");
|
|
6001
6820
|
const request3 = isSecure ? https2.request : http5.request;
|
|
6002
6821
|
const protocolSet = /* @__PURE__ */ new Set();
|
|
6003
6822
|
let perMessageDeflate;
|
|
@@ -6127,7 +6946,7 @@ var require_websocket = __commonJS({
|
|
|
6127
6946
|
abortHandshake(websocket, socket, "Invalid Upgrade header");
|
|
6128
6947
|
return;
|
|
6129
6948
|
}
|
|
6130
|
-
const digest =
|
|
6949
|
+
const digest = createHash4("sha1").update(key + GUID).digest("base64");
|
|
6131
6950
|
if (res.headers["sec-websocket-accept"] !== digest) {
|
|
6132
6951
|
abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
|
|
6133
6952
|
return;
|
|
@@ -6499,7 +7318,7 @@ var require_websocket_server = __commonJS({
|
|
|
6499
7318
|
var EventEmitter2 = require("events");
|
|
6500
7319
|
var http5 = require("http");
|
|
6501
7320
|
var { Duplex } = require("stream");
|
|
6502
|
-
var { createHash:
|
|
7321
|
+
var { createHash: createHash4 } = require("crypto");
|
|
6503
7322
|
var extension = require_extension();
|
|
6504
7323
|
var PerMessageDeflate = require_permessage_deflate();
|
|
6505
7324
|
var subprotocol = require_subprotocol();
|
|
@@ -6806,7 +7625,7 @@ var require_websocket_server = __commonJS({
|
|
|
6806
7625
|
);
|
|
6807
7626
|
}
|
|
6808
7627
|
if (this._state > RUNNING) return abortHandshake(socket, 503);
|
|
6809
|
-
const digest =
|
|
7628
|
+
const digest = createHash4("sha1").update(key + GUID).digest("base64");
|
|
6810
7629
|
const headers = [
|
|
6811
7630
|
"HTTP/1.1 101 Switching Protocols",
|
|
6812
7631
|
"Upgrade: websocket",
|
|
@@ -27305,7 +28124,7 @@ function normalizeProxyEvent(toolCall2, toolResponse, requestMeta, sessionId, ag
|
|
|
27305
28124
|
const url = arguments_.url || "";
|
|
27306
28125
|
const tr = toolResponse || {};
|
|
27307
28126
|
return {
|
|
27308
|
-
eventId: (0,
|
|
28127
|
+
eventId: (0, import_node_crypto2.randomUUID)(),
|
|
27309
28128
|
timestamp: {
|
|
27310
28129
|
timestampNs: now.getTime() * 1e6,
|
|
27311
28130
|
iso: now.toISOString()
|
|
@@ -27342,16 +28161,16 @@ function deriveSessionId(meta, headers) {
|
|
|
27342
28161
|
if (meta.threadId) return meta.threadId;
|
|
27343
28162
|
const apiKey = headers["x-api-key"] || headers["authorization"] || "";
|
|
27344
28163
|
if (apiKey) {
|
|
27345
|
-
return `apikey_${(0,
|
|
28164
|
+
return `apikey_${(0, import_node_crypto2.createHash)("sha256").update(apiKey).digest("hex").slice(0, 12)}`;
|
|
27346
28165
|
}
|
|
27347
|
-
return (0,
|
|
28166
|
+
return (0, import_node_crypto2.randomUUID)();
|
|
27348
28167
|
}
|
|
27349
|
-
var
|
|
28168
|
+
var import_node_crypto2;
|
|
27350
28169
|
var init_normalizer2 = __esm({
|
|
27351
28170
|
"src/v3/proxy/normalizer.ts"() {
|
|
27352
28171
|
"use strict";
|
|
27353
28172
|
init_cjs_shims();
|
|
27354
|
-
|
|
28173
|
+
import_node_crypto2 = require("crypto");
|
|
27355
28174
|
}
|
|
27356
28175
|
});
|
|
27357
28176
|
|
|
@@ -27360,12 +28179,12 @@ var privacy_exports = {};
|
|
|
27360
28179
|
__export(privacy_exports, {
|
|
27361
28180
|
PrivacyFilter: () => PrivacyFilter
|
|
27362
28181
|
});
|
|
27363
|
-
var
|
|
28182
|
+
var import_node_crypto3, DEFAULT_CONFIG, SENSITIVE_PATTERNS, PrivacyFilter;
|
|
27364
28183
|
var init_privacy = __esm({
|
|
27365
28184
|
"src/v3/proxy/privacy.ts"() {
|
|
27366
28185
|
"use strict";
|
|
27367
28186
|
init_cjs_shims();
|
|
27368
|
-
|
|
28187
|
+
import_node_crypto3 = require("crypto");
|
|
27369
28188
|
DEFAULT_CONFIG = {
|
|
27370
28189
|
mode: "auto",
|
|
27371
28190
|
redactApiKeys: true,
|
|
@@ -27452,7 +28271,7 @@ var init_privacy = __esm({
|
|
|
27452
28271
|
for (const key of Object.keys(payload)) {
|
|
27453
28272
|
const value = payload[key];
|
|
27454
28273
|
if (typeof value === "string" && value.length > 50) {
|
|
27455
|
-
payload[`${key}_hash`] = (0,
|
|
28274
|
+
payload[`${key}_hash`] = (0, import_node_crypto3.createHash)("sha256").update(value).digest("hex").slice(0, 16);
|
|
27456
28275
|
payload[`${key}_length`] = value.length;
|
|
27457
28276
|
delete payload[key];
|
|
27458
28277
|
} else if (Array.isArray(value)) {
|
|
@@ -27587,12 +28406,12 @@ var session_exports = {};
|
|
|
27587
28406
|
__export(session_exports, {
|
|
27588
28407
|
ProxySessionAggregator: () => ProxySessionAggregator
|
|
27589
28408
|
});
|
|
27590
|
-
var
|
|
28409
|
+
var import_node_crypto4, ProxySessionAggregator;
|
|
27591
28410
|
var init_session = __esm({
|
|
27592
28411
|
"src/v3/proxy/session.ts"() {
|
|
27593
28412
|
"use strict";
|
|
27594
28413
|
init_cjs_shims();
|
|
27595
|
-
|
|
28414
|
+
import_node_crypto4 = require("crypto");
|
|
27596
28415
|
ProxySessionAggregator = class {
|
|
27597
28416
|
_sessions = /* @__PURE__ */ new Map();
|
|
27598
28417
|
_apiSessionMap = /* @__PURE__ */ new Map();
|
|
@@ -27629,7 +28448,7 @@ var init_session = __esm({
|
|
|
27629
28448
|
return session2;
|
|
27630
28449
|
}
|
|
27631
28450
|
const session = {
|
|
27632
|
-
id: (0,
|
|
28451
|
+
id: (0, import_node_crypto4.randomUUID)(),
|
|
27633
28452
|
label: `${event.agentType || "unknown"}-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 19)}`,
|
|
27634
28453
|
inferredAgentType: event.agentType || "unknown",
|
|
27635
28454
|
eventCount: 0,
|
|
@@ -27679,12 +28498,12 @@ var trigger_exports = {};
|
|
|
27679
28498
|
__export(trigger_exports, {
|
|
27680
28499
|
TriggerEngine: () => TriggerEngine
|
|
27681
28500
|
});
|
|
27682
|
-
var
|
|
28501
|
+
var import_node_fs2, import_yaml, TriggerEngine;
|
|
27683
28502
|
var init_trigger = __esm({
|
|
27684
28503
|
"src/v3/proxy/trigger.ts"() {
|
|
27685
28504
|
"use strict";
|
|
27686
28505
|
init_cjs_shims();
|
|
27687
|
-
|
|
28506
|
+
import_node_fs2 = require("fs");
|
|
27688
28507
|
import_yaml = require("yaml");
|
|
27689
28508
|
TriggerEngine = class {
|
|
27690
28509
|
_rules = [];
|
|
@@ -27692,7 +28511,7 @@ var init_trigger = __esm({
|
|
|
27692
28511
|
_rateLimitSeconds = 5;
|
|
27693
28512
|
constructor(rulesPath) {
|
|
27694
28513
|
const path11 = rulesPath || "config/trigger_rules.yaml";
|
|
27695
|
-
if (!(0,
|
|
28514
|
+
if (!(0, import_node_fs2.existsSync)(path11)) {
|
|
27696
28515
|
console.error(
|
|
27697
28516
|
`[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`
|
|
27698
28517
|
);
|
|
@@ -27708,7 +28527,7 @@ var init_trigger = __esm({
|
|
|
27708
28527
|
return this._rules;
|
|
27709
28528
|
}
|
|
27710
28529
|
_loadRules(path11) {
|
|
27711
|
-
const content = (0,
|
|
28530
|
+
const content = (0, import_node_fs2.readFileSync)(path11, "utf-8");
|
|
27712
28531
|
const data = (0, import_yaml.parse)(content) || {};
|
|
27713
28532
|
const rulesData = data.rules || [];
|
|
27714
28533
|
this._rules = rulesData.map((r) => {
|
|
@@ -27838,21 +28657,37 @@ var server_exports2 = {};
|
|
|
27838
28657
|
__export(server_exports2, {
|
|
27839
28658
|
ProxyServer: () => ProxyServer
|
|
27840
28659
|
});
|
|
27841
|
-
|
|
28660
|
+
function cookieValue(raw, name) {
|
|
28661
|
+
for (const part of (raw ?? "").split(";")) {
|
|
28662
|
+
const [k, ...rest] = part.trim().split("=");
|
|
28663
|
+
if (k === name) return rest.join("=");
|
|
28664
|
+
}
|
|
28665
|
+
return "";
|
|
28666
|
+
}
|
|
28667
|
+
function timingSafeEqualStr(a, b) {
|
|
28668
|
+
const ba = Buffer.from(a, "utf-8");
|
|
28669
|
+
const bb = Buffer.from(b, "utf-8");
|
|
28670
|
+
if (ba.length !== bb.length) return false;
|
|
28671
|
+
return (0, import_node_crypto5.timingSafeEqual)(ba, bb);
|
|
28672
|
+
}
|
|
28673
|
+
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;
|
|
27842
28674
|
var init_server2 = __esm({
|
|
27843
28675
|
"src/v3/proxy/server.ts"() {
|
|
27844
28676
|
"use strict";
|
|
27845
28677
|
init_cjs_shims();
|
|
27846
28678
|
import_node_http = __toESM(require("http"));
|
|
28679
|
+
import_node_crypto5 = require("crypto");
|
|
27847
28680
|
import_node_url = require("url");
|
|
27848
|
-
|
|
27849
|
-
|
|
28681
|
+
import_node_path2 = __toESM(require("path"));
|
|
28682
|
+
import_node_fs3 = __toESM(require("fs"));
|
|
27850
28683
|
import_node_stream = require("stream");
|
|
27851
28684
|
import_http_mitm_proxy = __toESM(require_dist());
|
|
27852
28685
|
init_interceptor();
|
|
27853
28686
|
init_session();
|
|
27854
28687
|
init_trigger();
|
|
27855
28688
|
init_storage();
|
|
28689
|
+
init_security();
|
|
28690
|
+
DASHBOARD_COOKIE2 = "agent_gate_dashboard_token";
|
|
27856
28691
|
DASHBOARD_HTML = `<!DOCTYPE html>
|
|
27857
28692
|
<html><head><meta charset="UTF-8"><title>AgentGate v3 Dashboard</title>
|
|
27858
28693
|
<style>
|
|
@@ -27876,6 +28711,9 @@ td{padding:10px 16px;border-bottom:1px solid #334155;font-size:14px}tr:hover{bac
|
|
|
27876
28711
|
</tr></thead><tbody id="eb"></tbody></table></div>
|
|
27877
28712
|
<script>
|
|
27878
28713
|
async function j(p){return(await fetch(location.origin+p)).json()}
|
|
28714
|
+
// HTML \u8F6C\u4E49\uFF1Asession_id / agent_type / tool_name / target_command \u5168\u90E8\u6765\u81EA
|
|
28715
|
+
// \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
|
|
28716
|
+
function esc(s){return String(s==null?'':s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/'/g,''')}
|
|
27879
28717
|
async function load(){
|
|
27880
28718
|
const s=await j('/api/stats');
|
|
27881
28719
|
document.getElementById('stats').innerHTML=
|
|
@@ -27886,9 +28724,9 @@ async function load(){
|
|
|
27886
28724
|
document.getElementById('st').textContent='Live | '+(s.total_events||0)+' events';
|
|
27887
28725
|
const e=await j('/api/events?limit=30');
|
|
27888
28726
|
document.getElementById('eb').innerHTML=(e.events||[]).map(r=>
|
|
27889
|
-
'<tr><td>'+(r.captured_at||'')+'</td><td><code>'+(r.session_id||'').slice(0,8)+'</code></td>'+
|
|
27890
|
-
'<td>'+(r.agent_type||'')+'</td><td><span class="badge tool">'+(r.tool_name||'')+'</span></td>'+
|
|
27891
|
-
'<td><span class="cmd">'+(r.target_command||'')+'</span></td></tr>').join('');
|
|
28727
|
+
'<tr><td>'+esc(r.captured_at||'')+'</td><td><code>'+esc((r.session_id||'').slice(0,8))+'</code></td>'+
|
|
28728
|
+
'<td>'+esc(r.agent_type||'')+'</td><td><span class="badge tool">'+esc(r.tool_name||'')+'</span></td>'+
|
|
28729
|
+
'<td><span class="cmd">'+esc(r.target_command||'')+'</span></td></tr>').join('');
|
|
27892
28730
|
}
|
|
27893
28731
|
load();setInterval(load,5000);
|
|
27894
28732
|
</script></body></html>`;
|
|
@@ -27924,9 +28762,9 @@ load();setInterval(load,5000);
|
|
|
27924
28762
|
this._interceptor = new LLMInterceptor(config, this._sessionAgg, this._triggerEngine, options.coordinator);
|
|
27925
28763
|
}
|
|
27926
28764
|
start() {
|
|
27927
|
-
const caDir = this._options.sslCaDir ||
|
|
27928
|
-
if (!
|
|
27929
|
-
|
|
28765
|
+
const caDir = this._options.sslCaDir || import_node_path2.default.join(process.cwd(), ".agentgate-ssl");
|
|
28766
|
+
if (!import_node_fs3.default.existsSync(caDir)) {
|
|
28767
|
+
import_node_fs3.default.mkdirSync(caDir, { recursive: true });
|
|
27930
28768
|
}
|
|
27931
28769
|
this._mitmProxy = new import_http_mitm_proxy.Proxy();
|
|
27932
28770
|
this._mitmProxy.onError((_ctx, err) => {
|
|
@@ -28102,20 +28940,40 @@ load();setInterval(load,5000);
|
|
|
28102
28940
|
_startDashboard() {
|
|
28103
28941
|
const dashPort = this._options.port + 1;
|
|
28104
28942
|
this._dashServer = import_node_http.default.createServer((req, res) => {
|
|
28105
|
-
|
|
28106
|
-
|
|
28943
|
+
const url = new import_node_url.URL(req.url ?? "/", "http://localhost");
|
|
28944
|
+
const pathname = url.pathname;
|
|
28945
|
+
const queryToken = url.searchParams.get("token") || "";
|
|
28946
|
+
const expected = (process.env.AGENT_GATE_DASHBOARD_TOKEN ?? "").trim();
|
|
28947
|
+
if (expected) {
|
|
28948
|
+
const got = queryToken || String(req.headers["x-agentgate-token"] ?? "") || cookieValue(req.headers.cookie, DASHBOARD_COOKIE2);
|
|
28949
|
+
if (!timingSafeEqualStr(got, expected)) {
|
|
28950
|
+
res.writeHead(401, { "Content-Type": "text/plain" });
|
|
28951
|
+
res.end("Unauthorized");
|
|
28952
|
+
return;
|
|
28953
|
+
}
|
|
28954
|
+
}
|
|
28955
|
+
if (pathname === "/" || pathname === "/dashboard") {
|
|
28956
|
+
const headers = {
|
|
28957
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
28958
|
+
// 与 Python 版 dashboard 同一套安全响应头(CSP / 防点击劫持 / nosniff)
|
|
28959
|
+
...DASHBOARD_SECURITY_HEADERS
|
|
28960
|
+
};
|
|
28961
|
+
if (expected && queryToken) {
|
|
28962
|
+
headers["Set-Cookie"] = `${DASHBOARD_COOKIE2}=${queryToken}; HttpOnly; SameSite=Strict; Path=/`;
|
|
28963
|
+
}
|
|
28964
|
+
res.writeHead(200, headers);
|
|
28107
28965
|
res.end(DASHBOARD_HTML);
|
|
28108
28966
|
return;
|
|
28109
28967
|
}
|
|
28110
|
-
if (
|
|
28968
|
+
if (pathname === "/api/stats") {
|
|
28111
28969
|
this._serveStats(res);
|
|
28112
28970
|
return;
|
|
28113
28971
|
}
|
|
28114
|
-
if (
|
|
28972
|
+
if (pathname.startsWith("/api/events")) {
|
|
28115
28973
|
this._serveEvents(req, res);
|
|
28116
28974
|
return;
|
|
28117
28975
|
}
|
|
28118
|
-
if (
|
|
28976
|
+
if (pathname === "/api/sessions") {
|
|
28119
28977
|
this._serveSessions(res);
|
|
28120
28978
|
return;
|
|
28121
28979
|
}
|
|
@@ -29116,21 +29974,21 @@ var whitelist_exports = {};
|
|
|
29116
29974
|
__export(whitelist_exports, {
|
|
29117
29975
|
WhitelistEngine: () => WhitelistEngine
|
|
29118
29976
|
});
|
|
29119
|
-
var
|
|
29977
|
+
var import_node_fs4, import_yaml2, WhitelistEngine;
|
|
29120
29978
|
var init_whitelist = __esm({
|
|
29121
29979
|
"src/v3/proxy/whitelist.ts"() {
|
|
29122
29980
|
"use strict";
|
|
29123
29981
|
init_cjs_shims();
|
|
29124
|
-
|
|
29982
|
+
import_node_fs4 = require("fs");
|
|
29125
29983
|
import_yaml2 = require("yaml");
|
|
29126
29984
|
WhitelistEngine = class {
|
|
29127
29985
|
_rules = [];
|
|
29128
29986
|
constructor(rulesPath) {
|
|
29129
29987
|
const path11 = rulesPath || "config/trigger_rules.yaml";
|
|
29130
|
-
if ((0,
|
|
29988
|
+
if ((0, import_node_fs4.existsSync)(path11)) this._loadRules(path11);
|
|
29131
29989
|
}
|
|
29132
29990
|
_loadRules(path11) {
|
|
29133
|
-
const content = (0,
|
|
29991
|
+
const content = (0, import_node_fs4.readFileSync)(path11, "utf-8");
|
|
29134
29992
|
const data = (0, import_yaml2.parse)(content) || {};
|
|
29135
29993
|
const rulesData = data.rules || [];
|
|
29136
29994
|
this._rules = rulesData.filter((r) => r.action === "allow").map((r) => {
|
|
@@ -29287,13 +30145,20 @@ var server_exports3 = {};
|
|
|
29287
30145
|
__export(server_exports3, {
|
|
29288
30146
|
GatewayServer: () => GatewayServer
|
|
29289
30147
|
});
|
|
29290
|
-
|
|
30148
|
+
function timingSafeEqualStr2(a, b) {
|
|
30149
|
+
const ba = Buffer.from(a, "utf-8");
|
|
30150
|
+
const bb = Buffer.from(b, "utf-8");
|
|
30151
|
+
if (ba.length !== bb.length) return false;
|
|
30152
|
+
return (0, import_node_crypto6.timingSafeEqual)(ba, bb);
|
|
30153
|
+
}
|
|
30154
|
+
var import_node_http2, import_node_https, import_node_crypto6, import_node_url2, GatewayServer, DASHBOARD_HTML2;
|
|
29291
30155
|
var init_server3 = __esm({
|
|
29292
30156
|
"src/v3/gateway/server.ts"() {
|
|
29293
30157
|
"use strict";
|
|
29294
30158
|
init_cjs_shims();
|
|
29295
30159
|
import_node_http2 = __toESM(require("http"));
|
|
29296
30160
|
import_node_https = __toESM(require("https"));
|
|
30161
|
+
import_node_crypto6 = require("crypto");
|
|
29297
30162
|
import_node_url2 = require("url");
|
|
29298
30163
|
init_router();
|
|
29299
30164
|
init_parsers();
|
|
@@ -29302,6 +30167,7 @@ var init_server3 = __esm({
|
|
|
29302
30167
|
init_trigger();
|
|
29303
30168
|
init_privacy();
|
|
29304
30169
|
init_storage();
|
|
30170
|
+
init_security();
|
|
29305
30171
|
GatewayServer = class {
|
|
29306
30172
|
host;
|
|
29307
30173
|
port;
|
|
@@ -29350,6 +30216,13 @@ var init_server3 = __esm({
|
|
|
29350
30216
|
}
|
|
29351
30217
|
async handleRequest(req, res) {
|
|
29352
30218
|
const path11 = (req.url ?? "/").replace(/\/+$/, "") || "/";
|
|
30219
|
+
const expected = (process.env.AGENT_GATE_GATEWAY_TOKEN ?? "").trim();
|
|
30220
|
+
if (expected && path11 !== "/health") {
|
|
30221
|
+
const got = String(req.headers["x-agentgate-token"] ?? "");
|
|
30222
|
+
if (!timingSafeEqualStr2(got, expected)) {
|
|
30223
|
+
return this.json(res, 401, { error: "Unauthorized: missing or invalid X-AgentGate-Token" });
|
|
30224
|
+
}
|
|
30225
|
+
}
|
|
29353
30226
|
if (req.method === "GET") {
|
|
29354
30227
|
if (path11 === "" || path11 === "/") {
|
|
29355
30228
|
return this.serveDashboard(res);
|
|
@@ -29576,8 +30449,10 @@ var init_server3 = __esm({
|
|
|
29576
30449
|
serveDashboard(res) {
|
|
29577
30450
|
const html = DASHBOARD_HTML2;
|
|
29578
30451
|
res.writeHead(200, {
|
|
29579
|
-
"Content-Type": "text/html",
|
|
29580
|
-
"Content-Length": String(Buffer.byteLength(html))
|
|
30452
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
30453
|
+
"Content-Length": String(Buffer.byteLength(html)),
|
|
30454
|
+
// 与 Python 版 dashboard 同一套安全响应头(CSP / 防点击劫持 / nosniff)
|
|
30455
|
+
...DASHBOARD_SECURITY_HEADERS
|
|
29581
30456
|
});
|
|
29582
30457
|
res.end(html);
|
|
29583
30458
|
}
|
|
@@ -29655,6 +30530,9 @@ td{padding:10px 16px;border-bottom:1px solid #334155;font-size:14px}tr:hover{bac
|
|
|
29655
30530
|
</tr></thead><tbody id="eb"></tbody></table></div>
|
|
29656
30531
|
<script>
|
|
29657
30532
|
async function j(p){return(await fetch(location.origin+p)).json()}
|
|
30533
|
+
// HTML \u8F6C\u4E49\uFF1Asession_id / agent_type / tool_name / target_command \u5168\u90E8\u6765\u81EA
|
|
30534
|
+
// \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
|
|
30535
|
+
function esc(s){return String(s==null?'':s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/'/g,''')}
|
|
29658
30536
|
async function load(){
|
|
29659
30537
|
try{
|
|
29660
30538
|
const s=await j('/api/stats');
|
|
@@ -29665,9 +30543,9 @@ async function load(){
|
|
|
29665
30543
|
'<div class="sc"><div class="l">Tools</div><div class="v">'+(s.unique_tools||0)+'</div></div>';
|
|
29666
30544
|
const e=await j('/api/events?limit=30');
|
|
29667
30545
|
document.getElementById('eb').innerHTML=(e.events||[]).map(r=>
|
|
29668
|
-
'<tr><td>'+(r.captured_at||'')+'</td><td><code>'+(r.session_id||'').slice(0,8)+'</code></td>'+
|
|
29669
|
-
'<td>'+(r.agent_type||'')+'</td><td><span class="badge tool">'+(r.tool_name||'')+'</span></td>'+
|
|
29670
|
-
'<td><span class="cmd">'+(r.target_command||'')+'</span></td></tr>').join('');
|
|
30546
|
+
'<tr><td>'+esc(r.captured_at||'')+'</td><td><code>'+esc((r.session_id||'').slice(0,8))+'</code></td>'+
|
|
30547
|
+
'<td>'+esc(r.agent_type||'')+'</td><td><span class="badge tool">'+esc(r.tool_name||'')+'</span></td>'+
|
|
30548
|
+
'<td><span class="cmd">'+esc(r.target_command||'')+'</span></td></tr>').join('');
|
|
29671
30549
|
}catch(e){console.error(e)}
|
|
29672
30550
|
}
|
|
29673
30551
|
load();setInterval(load,5000);
|
|
@@ -30501,8 +31379,8 @@ var init_opencode = __esm({
|
|
|
30501
31379
|
|
|
30502
31380
|
// src/v3/transcript/opendesk.ts
|
|
30503
31381
|
function defaultRoot() {
|
|
30504
|
-
for (const
|
|
30505
|
-
if (process.env[
|
|
31382
|
+
for (const env2 of [OPENDESK_CONFIG_DIR_ENV, LEGACY_ENV]) {
|
|
31383
|
+
if (process.env[env2]) return path6.resolve(process.env[env2]);
|
|
30506
31384
|
}
|
|
30507
31385
|
if (process.env.APPDATA) return path6.join(process.env.APPDATA, "opendesk");
|
|
30508
31386
|
return path6.join(os7.homedir(), ".opendesk");
|
|
@@ -31818,9 +32696,9 @@ var init_stdio_proxy = __esm({
|
|
|
31818
32696
|
this.opts = opts;
|
|
31819
32697
|
}
|
|
31820
32698
|
start() {
|
|
31821
|
-
const { command, env = {}, cwd, stdin = process.stdin, stdout = process.stdout, stderr = process.stderr } = this.opts;
|
|
32699
|
+
const { command, env: env2 = {}, cwd, stdin = process.stdin, stdout = process.stdout, stderr = process.stderr } = this.opts;
|
|
31822
32700
|
this.child = (0, import_node_child_process.spawn)(command[0], command.slice(1), {
|
|
31823
|
-
env: { ...process.env, ...
|
|
32701
|
+
env: { ...process.env, ...env2 },
|
|
31824
32702
|
cwd,
|
|
31825
32703
|
stdio: ["pipe", "pipe", "pipe"]
|
|
31826
32704
|
});
|
|
@@ -32274,13 +33152,13 @@ var init_launcher = __esm({
|
|
|
32274
33152
|
this.coordinator = options.coordinator;
|
|
32275
33153
|
this.sessionId = options.sessionId ?? `pty-${Date.now()}`;
|
|
32276
33154
|
}
|
|
32277
|
-
async run(command, args = [],
|
|
33155
|
+
async run(command, args = [], env2 = {}) {
|
|
32278
33156
|
console.log(`[AgentGate] Starting agent: ${command} ${args.join(" ")}`);
|
|
32279
33157
|
console.log(`[AgentGate] Layer 1 (API Gateway): ${this.enableLayer1 ? "enabled" : "disabled"}`);
|
|
32280
33158
|
console.log(`[AgentGate] Layer 2 (PTY Interception): enabled`);
|
|
32281
33159
|
console.log();
|
|
32282
33160
|
const fullEnv = {
|
|
32283
|
-
...
|
|
33161
|
+
...env2,
|
|
32284
33162
|
AGENTGATE_SESSION_ID: this.sessionId
|
|
32285
33163
|
};
|
|
32286
33164
|
const wrapper = new PTYWrapper({
|
|
@@ -33193,7 +34071,7 @@ var init_loader = __esm({
|
|
|
33193
34071
|
|
|
33194
34072
|
// src/v3/cli.ts
|
|
33195
34073
|
init_cjs_shims();
|
|
33196
|
-
var
|
|
34074
|
+
var import_node_fs5 = require("fs");
|
|
33197
34075
|
var path10 = __toESM(require("path"));
|
|
33198
34076
|
var import_yaml3 = require("yaml");
|
|
33199
34077
|
init_version();
|
|
@@ -33279,8 +34157,14 @@ Run options:
|
|
|
33279
34157
|
}
|
|
33280
34158
|
mossUrl2 = mossUrl2 || process.env.MOSS_URL;
|
|
33281
34159
|
const dataDir = process.env.AGENT_GATE_DATA_DIR;
|
|
33282
|
-
const { createStorage: createStorage2 } = await Promise.resolve().then(() => (init_db(), db_exports));
|
|
34160
|
+
const { createStorage: createStorage2, getAgentGateDbPath: getAgentGateDbPath2 } = await Promise.resolve().then(() => (init_db(), db_exports));
|
|
33283
34161
|
createStorage2({ dbPath, dataDir });
|
|
34162
|
+
const { hardenDbFiles: hardenDbFiles2, describe: describe2, authEnabled: authEnabled2, authToken: authToken2, failFastOnAuthError: failFastOnAuthError2 } = await Promise.resolve().then(() => (init_security(), security_exports));
|
|
34163
|
+
if ((process.env.AGENT_GATE_STORAGE || "sqlite").toLowerCase() !== "json") {
|
|
34164
|
+
hardenDbFiles2(getAgentGateDbPath2());
|
|
34165
|
+
}
|
|
34166
|
+
console.log(describe2());
|
|
34167
|
+
failFastOnAuthError2();
|
|
33284
34168
|
if (mossUrl2) {
|
|
33285
34169
|
const { setMossUrl: setMossUrl2 } = await Promise.resolve().then(() => (init_moss_client(), moss_client_exports));
|
|
33286
34170
|
setMossUrl2(mossUrl2);
|
|
@@ -33289,6 +34173,9 @@ Run options:
|
|
|
33289
34173
|
const { createApp: createApp2 } = await Promise.resolve().then(() => (init_server(), server_exports));
|
|
33290
34174
|
const app = createApp2();
|
|
33291
34175
|
console.log(`AgentGate HTTP server on ${host}:${port}`);
|
|
34176
|
+
if (authEnabled2() && authToken2()) {
|
|
34177
|
+
console.log(`Dashboard: http://localhost:${port}/dashboard/?token=${authToken2()}`);
|
|
34178
|
+
}
|
|
33292
34179
|
serve({ fetch: app.fetch, hostname: host, port }, (info) => {
|
|
33293
34180
|
console.log(`Listening on http://${host}:${port}`);
|
|
33294
34181
|
});
|
|
@@ -33402,12 +34289,12 @@ Run options:
|
|
|
33402
34289
|
if (envLevel && !args.includes("--level")) level = parseInt(envLevel, 10);
|
|
33403
34290
|
const envDeny = process.env.AGENT_GATE_DENY_ACTION;
|
|
33404
34291
|
if (envDeny && !args.includes("--deny-action")) denyAction = envDeny;
|
|
33405
|
-
if (!(0,
|
|
34292
|
+
if (!(0, import_node_fs5.existsSync)(configPath)) {
|
|
33406
34293
|
console.error(`Config file not found: ${configPath}`);
|
|
33407
34294
|
console.error("Create it with model_routes or use --config <path>");
|
|
33408
34295
|
process.exit(1);
|
|
33409
34296
|
}
|
|
33410
|
-
const yamlContent = (0,
|
|
34297
|
+
const yamlContent = (0, import_node_fs5.readFileSync)(configPath, "utf-8");
|
|
33411
34298
|
const config = (0, import_yaml3.parse)(yamlContent);
|
|
33412
34299
|
const gatewayCfg = config.gateway ?? {};
|
|
33413
34300
|
const modelRoutes = gatewayCfg.model_routes ?? [];
|
|
@@ -33549,7 +34436,7 @@ Run options:
|
|
|
33549
34436
|
const jsonOut = args.includes("--json");
|
|
33550
34437
|
let files = [];
|
|
33551
34438
|
try {
|
|
33552
|
-
files = (0,
|
|
34439
|
+
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);
|
|
33553
34440
|
} catch {
|
|
33554
34441
|
}
|
|
33555
34442
|
if (files.length === 0) {
|