@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/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 +884 -51
- package/dist/v1/server.d.ts +8 -2
- package/dist/v1/server.js +740 -42
- package/dist/v3/cli.js +988 -98
- package/package.json +1 -1
package/dist/v1/server.js
CHANGED
|
@@ -42,20 +42,34 @@ var init_cjs_shims = __esm({
|
|
|
42
42
|
|
|
43
43
|
// src/shared/multi-session.ts
|
|
44
44
|
function isMultiSessionEnabled() {
|
|
45
|
-
|
|
45
|
+
const raw = (process.env.AGENT_GATE_MULTI_SESSION ?? "").trim().toLowerCase();
|
|
46
|
+
if (raw === "") return true;
|
|
47
|
+
return !MULTI_SESSION_OFF_VALUES.has(raw);
|
|
48
|
+
}
|
|
49
|
+
function sessionHistoryLimit() {
|
|
50
|
+
const raw = (process.env.AGENT_GATE_SESSION_HISTORY_LIMIT ?? "").trim();
|
|
51
|
+
const n = raw ? parseInt(raw, 10) : DEFAULT_MAX_SESSIONS;
|
|
52
|
+
const v = Number.isFinite(n) ? n : DEFAULT_MAX_SESSIONS;
|
|
53
|
+
return Math.max(1, Math.min(v, 50));
|
|
46
54
|
}
|
|
47
55
|
function buildSessionHistory(queryToolCalls2, sessionId) {
|
|
48
56
|
if (!isMultiSessionEnabled()) return [];
|
|
57
|
+
const maxSessions = sessionHistoryLimit();
|
|
49
58
|
try {
|
|
50
|
-
const
|
|
59
|
+
const scanLimit = Math.max(DEFAULT_HISTORY_LIMIT, maxSessions * DEFAULT_ACTIONS_PER_SESSION);
|
|
60
|
+
const recent = queryToolCalls2({ limit: scanLimit });
|
|
51
61
|
const bySession = /* @__PURE__ */ new Map();
|
|
52
62
|
for (const tc of recent) {
|
|
53
63
|
if (tc.session_id === sessionId) continue;
|
|
54
64
|
const list = bySession.get(tc.session_id) || [];
|
|
55
|
-
list.unshift({
|
|
65
|
+
list.unshift({
|
|
66
|
+
action_type: tc.action_type,
|
|
67
|
+
action_detail: tc.action_detail,
|
|
68
|
+
...tc.called_at ? { called_at: tc.called_at } : {}
|
|
69
|
+
});
|
|
56
70
|
bySession.set(tc.session_id, list);
|
|
57
71
|
}
|
|
58
|
-
return [...bySession.entries()].slice(0,
|
|
72
|
+
return [...bySession.entries()].slice(0, maxSessions).map(([sid, actions]) => ({
|
|
59
73
|
session_id: sid,
|
|
60
74
|
action_history: actions.slice(0, DEFAULT_ACTIONS_PER_SESSION)
|
|
61
75
|
}));
|
|
@@ -66,7 +80,7 @@ function buildSessionHistory(queryToolCalls2, sessionId) {
|
|
|
66
80
|
function isStatefulIncrementalEnabled() {
|
|
67
81
|
return isMultiSessionEnabled();
|
|
68
82
|
}
|
|
69
|
-
var DEFAULT_HISTORY_LIMIT, DEFAULT_MAX_SESSIONS, DEFAULT_ACTIONS_PER_SESSION;
|
|
83
|
+
var DEFAULT_HISTORY_LIMIT, DEFAULT_MAX_SESSIONS, DEFAULT_ACTIONS_PER_SESSION, MULTI_SESSION_OFF_VALUES;
|
|
70
84
|
var init_multi_session = __esm({
|
|
71
85
|
"src/shared/multi-session.ts"() {
|
|
72
86
|
"use strict";
|
|
@@ -74,17 +88,441 @@ var init_multi_session = __esm({
|
|
|
74
88
|
DEFAULT_HISTORY_LIMIT = 500;
|
|
75
89
|
DEFAULT_MAX_SESSIONS = 5;
|
|
76
90
|
DEFAULT_ACTIONS_PER_SESSION = 100;
|
|
91
|
+
MULTI_SESSION_OFF_VALUES = /* @__PURE__ */ new Set(["0", "false", "no", "off"]);
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
// src/shared/security.ts
|
|
96
|
+
function env(name, dflt = "") {
|
|
97
|
+
return (process.env[name] ?? dflt).trim();
|
|
98
|
+
}
|
|
99
|
+
function envInt(name, dflt) {
|
|
100
|
+
const raw = env(name);
|
|
101
|
+
if (!raw) return dflt;
|
|
102
|
+
const n = parseInt(raw, 10);
|
|
103
|
+
return Number.isFinite(n) ? n : dflt;
|
|
104
|
+
}
|
|
105
|
+
function envFloat(name, dflt) {
|
|
106
|
+
const raw = env(name);
|
|
107
|
+
if (!raw) return dflt;
|
|
108
|
+
const n = parseFloat(raw);
|
|
109
|
+
return Number.isFinite(n) ? n : dflt;
|
|
110
|
+
}
|
|
111
|
+
function split(raw) {
|
|
112
|
+
return raw.replace(/;/g, ",").split(",").map((x) => x.trim()).filter(Boolean);
|
|
113
|
+
}
|
|
114
|
+
function originCheckEnabled() {
|
|
115
|
+
return TRUTHY.includes(env("AGENT_GATE_ORIGIN_CHECK", "1").toLowerCase());
|
|
116
|
+
}
|
|
117
|
+
function allowedOrigins() {
|
|
118
|
+
return split(env("AGENT_GATE_CORS_ORIGINS"));
|
|
119
|
+
}
|
|
120
|
+
function normalizeOrigin(origin) {
|
|
121
|
+
return (origin || "").trim().replace(/\/+$/, "");
|
|
122
|
+
}
|
|
123
|
+
function originAllowed(origin, hostHeader, extra) {
|
|
124
|
+
const o = normalizeOrigin(origin);
|
|
125
|
+
if (!o) return true;
|
|
126
|
+
const entries = (extra ?? allowedOrigins()).map(normalizeOrigin);
|
|
127
|
+
if (entries.includes(o)) return true;
|
|
128
|
+
const host = (hostHeader || "").trim();
|
|
129
|
+
if (!host) return false;
|
|
130
|
+
try {
|
|
131
|
+
const u = new URL(o);
|
|
132
|
+
return !!u.host && u.host === host;
|
|
133
|
+
} catch {
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
function authMode() {
|
|
138
|
+
return (env("AGENT_GATE_AUTH_MODE", AUTH_MODE_AUTO) || AUTH_MODE_AUTO).toLowerCase();
|
|
139
|
+
}
|
|
140
|
+
function authTokenPath() {
|
|
141
|
+
const home = process.env.SUDO_USER && existsDir(`/home/${process.env.SUDO_USER}`) ? `/home/${process.env.SUDO_USER}` : (0, import_node_os.homedir)();
|
|
142
|
+
const xdg = process.env.XDG_CONFIG_HOME || (0, import_node_path.join)(home, ".config");
|
|
143
|
+
return (0, import_node_path.join)(xdg, "agentgate", "auth_token");
|
|
144
|
+
}
|
|
145
|
+
function existsDir(p) {
|
|
146
|
+
try {
|
|
147
|
+
return (0, import_node_fs.statSync)(p).isDirectory();
|
|
148
|
+
} catch {
|
|
149
|
+
return false;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
function ensurePrivateDir(p, mode = 448) {
|
|
153
|
+
try {
|
|
154
|
+
(0, import_node_fs.mkdirSync)(p, { recursive: true });
|
|
155
|
+
const st = (0, import_node_fs.statSync)(p);
|
|
156
|
+
if (st.uid === process.getuid?.() && (st.mode & 511) !== mode) (0, import_node_fs.chmodSync)(p, mode);
|
|
157
|
+
} catch {
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
function hardenPermissions(p, mode) {
|
|
161
|
+
try {
|
|
162
|
+
const st = (0, import_node_fs.lstatSync)(p);
|
|
163
|
+
if (st.isSymbolicLink()) return;
|
|
164
|
+
if (st.uid !== process.getuid?.()) return;
|
|
165
|
+
if ((st.mode & 511) !== mode) (0, import_node_fs.chmodSync)(p, mode);
|
|
166
|
+
} catch {
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
function readFdToken() {
|
|
170
|
+
const raw = env("AGENT_GATE_AUTH_TOKEN_FD");
|
|
171
|
+
if (!raw) return "";
|
|
172
|
+
const fd = parseInt(raw, 10);
|
|
173
|
+
if (!Number.isFinite(fd)) return "";
|
|
174
|
+
const cached = fdTokenCache.get(fd);
|
|
175
|
+
if (cached !== void 0) return cached;
|
|
176
|
+
try {
|
|
177
|
+
const buf = Buffer.alloc(8192);
|
|
178
|
+
const n = (0, import_node_fs.readSync)(fd, buf, 0, buf.length, null);
|
|
179
|
+
(0, import_node_fs.closeSync)(fd);
|
|
180
|
+
const tok = buf.subarray(0, n).toString("utf-8").trim();
|
|
181
|
+
fdTokenCache.set(fd, tok);
|
|
182
|
+
return tok;
|
|
183
|
+
} catch {
|
|
184
|
+
fdTokenCache.set(fd, "");
|
|
185
|
+
return "";
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
function readExplicitToken() {
|
|
189
|
+
const t = env("AGENT_GATE_AUTH_TOKEN");
|
|
190
|
+
if (t) return t;
|
|
191
|
+
const fromFd = readFdToken();
|
|
192
|
+
if (fromFd) return fromFd;
|
|
193
|
+
const file = env("AGENT_GATE_AUTH_TOKEN_FILE");
|
|
194
|
+
if (file) {
|
|
195
|
+
try {
|
|
196
|
+
return (0, import_node_fs.readFileSync)(file, "utf-8").trim();
|
|
197
|
+
} catch {
|
|
198
|
+
return "";
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
return "";
|
|
202
|
+
}
|
|
203
|
+
function ensureAutoToken() {
|
|
204
|
+
const p = authTokenPath();
|
|
205
|
+
try {
|
|
206
|
+
try {
|
|
207
|
+
const existing = (0, import_node_fs.readFileSync)(p, "utf-8").trim();
|
|
208
|
+
if (existing) {
|
|
209
|
+
hardenPermissions(p, 384);
|
|
210
|
+
return existing;
|
|
211
|
+
}
|
|
212
|
+
} catch {
|
|
213
|
+
}
|
|
214
|
+
const tok = (0, import_node_crypto.randomBytes)(32).toString("base64url");
|
|
215
|
+
ensurePrivateDir(p.replace(/\/[^/]+$/, ""));
|
|
216
|
+
try {
|
|
217
|
+
(0, import_node_fs.writeFileSync)(p, tok + "\n", { mode: 384, flag: "wx" });
|
|
218
|
+
} catch (e) {
|
|
219
|
+
if (e?.code === "EEXIST") return (0, import_node_fs.readFileSync)(p, "utf-8").trim();
|
|
220
|
+
throw e;
|
|
221
|
+
}
|
|
222
|
+
console.warn(
|
|
223
|
+
`[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`
|
|
224
|
+
);
|
|
225
|
+
return tok;
|
|
226
|
+
} catch (e) {
|
|
227
|
+
console.error(`[AgentGate] \u751F\u6210\u8BBF\u95EE token \u5931\u8D25\uFF08\u672C\u6B21\u8FD0\u884C\u5C06\u4E0D\u9274\u6743\uFF09: ${e?.message ?? e}`);
|
|
228
|
+
return "";
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
function parseAgentTokens(raw) {
|
|
232
|
+
const out = {};
|
|
233
|
+
for (const pair of split(raw)) {
|
|
234
|
+
const i = pair.indexOf("=");
|
|
235
|
+
if (i > 0) {
|
|
236
|
+
const a = pair.slice(0, i).trim();
|
|
237
|
+
const t = pair.slice(i + 1).trim();
|
|
238
|
+
if (a && t) out[a] = t;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return out;
|
|
242
|
+
}
|
|
243
|
+
function resolveAuth() {
|
|
244
|
+
const rawAgents = env("AGENT_GATE_AGENT_TOKENS");
|
|
245
|
+
const key = [
|
|
246
|
+
authMode(),
|
|
247
|
+
env("AGENT_GATE_AUTH_TOKEN"),
|
|
248
|
+
env("AGENT_GATE_AUTH_TOKEN_FILE"),
|
|
249
|
+
env("AGENT_GATE_AUTH_TOKEN_FD"),
|
|
250
|
+
rawAgents,
|
|
251
|
+
env("AGENT_GATE_DATA_DIR"),
|
|
252
|
+
env("XDG_CONFIG_HOME"),
|
|
253
|
+
env("SUDO_USER")
|
|
254
|
+
].join("\0");
|
|
255
|
+
if (tokenCache && tokenCache.key === key) return tokenCache;
|
|
256
|
+
let error = "";
|
|
257
|
+
let token = readExplicitToken();
|
|
258
|
+
if (!token && env("AGENT_GATE_AUTH_TOKEN_FD") && authMode() !== AUTH_MODE_OFF) {
|
|
259
|
+
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";
|
|
260
|
+
console.error(`[AgentGate] ${error}`);
|
|
261
|
+
}
|
|
262
|
+
if (!token && !error && authMode() !== AUTH_MODE_OFF) token = ensureAutoToken();
|
|
263
|
+
const agents = parseAgentTokens(rawAgents);
|
|
264
|
+
tokenCache = { key, token, agents, error };
|
|
265
|
+
return tokenCache;
|
|
266
|
+
}
|
|
267
|
+
function authEnabled() {
|
|
268
|
+
if (authMode() === AUTH_MODE_OFF) return false;
|
|
269
|
+
const { token, agents } = resolveAuth();
|
|
270
|
+
return !!token || Object.keys(agents).length > 0;
|
|
271
|
+
}
|
|
272
|
+
function constEq(a, b) {
|
|
273
|
+
const ba = Buffer.from(a, "utf-8");
|
|
274
|
+
const bb = Buffer.from(b, "utf-8");
|
|
275
|
+
if (ba.length !== bb.length) return false;
|
|
276
|
+
return (0, import_node_crypto.timingSafeEqual)(ba, bb);
|
|
277
|
+
}
|
|
278
|
+
function principalOf(token) {
|
|
279
|
+
if (!token) return "";
|
|
280
|
+
const { agents } = resolveAuth();
|
|
281
|
+
for (const [agent, atok] of Object.entries(agents)) {
|
|
282
|
+
if (constEq(token, atok)) return `agent:${agent}`;
|
|
283
|
+
}
|
|
284
|
+
return "tok:" + (0, import_node_crypto.createHash)("sha256").update(token, "utf-8").digest("hex").slice(0, 12);
|
|
285
|
+
}
|
|
286
|
+
function checkToken(token) {
|
|
287
|
+
if (!token) return false;
|
|
288
|
+
const { token: globalTok, agents } = resolveAuth();
|
|
289
|
+
if (globalTok && constEq(token, globalTok)) return true;
|
|
290
|
+
return Object.values(agents).some((t) => constEq(token, t));
|
|
291
|
+
}
|
|
292
|
+
function isGlobalToken(token) {
|
|
293
|
+
if (!token) return false;
|
|
294
|
+
const { token: globalTok } = resolveAuth();
|
|
295
|
+
return Boolean(globalTok) && constEq(token, globalTok);
|
|
296
|
+
}
|
|
297
|
+
function boundAgentOf(principal) {
|
|
298
|
+
return principal.startsWith("agent:") ? principal.slice("agent:".length) : "";
|
|
299
|
+
}
|
|
300
|
+
function cookiePathAllowed(path) {
|
|
301
|
+
if (path === "/api/v1/analyze" || path.startsWith("/api/v1/analyze/")) return false;
|
|
302
|
+
return path === "/dashboard" || path.startsWith("/dashboard/") || path.startsWith("/ws/") || path.startsWith("/api/");
|
|
303
|
+
}
|
|
304
|
+
function checkRequestAuth(headers, path, cookie = "", requireGlobal = false) {
|
|
305
|
+
if (authMode() === AUTH_MODE_OFF) return { ok: true, principal: "" };
|
|
306
|
+
const isHealth = PUBLIC_PATHS.includes(path.replace(/\/+$/, ""));
|
|
307
|
+
const { token: globalTok, agents, error } = resolveAuth();
|
|
308
|
+
if (error) return { ok: isHealth, principal: "" };
|
|
309
|
+
if (!globalTok && Object.keys(agents).length === 0) return { ok: true, principal: "" };
|
|
310
|
+
if (isHealth) return { ok: true, principal: "" };
|
|
311
|
+
if (cookie && cookiePathAllowed(path) && checkToken(cookie)) {
|
|
312
|
+
const principal = principalOf(cookie);
|
|
313
|
+
if (requireGlobal && principal.startsWith("agent:")) {
|
|
314
|
+
return { ok: false, principal };
|
|
315
|
+
}
|
|
316
|
+
return { ok: true, principal };
|
|
317
|
+
}
|
|
318
|
+
const authHeader = headers["authorization"] || "";
|
|
319
|
+
const tok = authHeader.toLowerCase().startsWith("bearer ") ? authHeader.slice(7).trim() : "";
|
|
320
|
+
if (!tok) return { ok: false, principal: "" };
|
|
321
|
+
if (globalTok && constEq(tok, globalTok)) return { ok: true, principal: principalOf(tok) };
|
|
322
|
+
for (const atok of Object.values(agents)) {
|
|
323
|
+
if (constEq(tok, atok)) {
|
|
324
|
+
const principal = principalOf(tok);
|
|
325
|
+
if (requireGlobal) return { ok: false, principal };
|
|
326
|
+
return { ok: true, principal };
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
return { ok: false, principal: "" };
|
|
330
|
+
}
|
|
331
|
+
function bindAgent(principal, agentType) {
|
|
332
|
+
if (authMode() === AUTH_MODE_OFF) return { ok: true, reason: "" };
|
|
333
|
+
const { agents } = resolveAuth();
|
|
334
|
+
if (Object.keys(agents).length === 0) return { ok: true, reason: "" };
|
|
335
|
+
if (!principal.startsWith("agent:")) return { ok: true, reason: "" };
|
|
336
|
+
const bound = principal.slice("agent:".length);
|
|
337
|
+
const claimed = (agentType || "").trim();
|
|
338
|
+
if (!claimed) {
|
|
339
|
+
return { ok: false, reason: `\u8BE5\u51ED\u8BC1\u7ED1\u5B9A\u5230 agent '${bound}'\uFF0C\u8BF7\u6C42\u5FC5\u987B\u58F0\u660E agent_type` };
|
|
340
|
+
}
|
|
341
|
+
if (claimed.toLowerCase() !== bound.toLowerCase()) {
|
|
342
|
+
return { ok: false, reason: `agent_type '${claimed}' \u4E0E\u51ED\u8BC1\u7ED1\u5B9A\u7684 '${bound}' \u4E0D\u4E00\u81F4` };
|
|
343
|
+
}
|
|
344
|
+
return { ok: true, reason: bound };
|
|
345
|
+
}
|
|
346
|
+
function maxBodyBytes() {
|
|
347
|
+
return envInt("AGENT_GATE_MAX_BODY_BYTES", 16 * 1024 * 1024);
|
|
348
|
+
}
|
|
349
|
+
function rateLimitQps() {
|
|
350
|
+
return envInt("AGENT_GATE_RATE_LIMIT_QPS", 100);
|
|
351
|
+
}
|
|
352
|
+
function poolOf(path) {
|
|
353
|
+
if (path === "/api/v1/analyze" || path.startsWith("/api/v1/analyze/")) return "biz";
|
|
354
|
+
if (path.startsWith("/api/v1/sessions") || path.startsWith("/api/v1/agents") || path.startsWith("/api/v1/tool_calls")) return "read";
|
|
355
|
+
if (path === "/dashboard" || path.startsWith("/dashboard/") || path.startsWith("/ws/")) return "ops";
|
|
356
|
+
if (path === "/api/v1/health") return "health";
|
|
357
|
+
return "other";
|
|
358
|
+
}
|
|
359
|
+
function poolLimit(name) {
|
|
360
|
+
let dflt = POOL_DEFAULTS[name] ?? 4;
|
|
361
|
+
if (name === "biz") dflt = envInt("AGENT_GATE_MAX_INFLIGHT", dflt);
|
|
362
|
+
return envInt(`AGENT_GATE_POOL_${name.toUpperCase()}`, dflt);
|
|
363
|
+
}
|
|
364
|
+
function unauthInflight() {
|
|
365
|
+
return envInt("AGENT_GATE_MAX_UNAUTH_INFLIGHT", 4);
|
|
366
|
+
}
|
|
367
|
+
function unauthPerIp() {
|
|
368
|
+
return envInt("AGENT_GATE_MAX_UNAUTH_PER_IP", 2);
|
|
369
|
+
}
|
|
370
|
+
function agentInflight() {
|
|
371
|
+
return envInt("AGENT_GATE_MAX_AGENT_INFLIGHT", 8);
|
|
372
|
+
}
|
|
373
|
+
function bump(kind, key, windowSec, extra) {
|
|
374
|
+
const now = Date.now() / 1e3;
|
|
375
|
+
const k = `${kind}|${key}`;
|
|
376
|
+
let b = counters.get(k);
|
|
377
|
+
if (!b || now - b.start >= windowSec) {
|
|
378
|
+
b = { start: now, n: 0, seen: /* @__PURE__ */ new Set() };
|
|
379
|
+
counters.set(k, b);
|
|
380
|
+
}
|
|
381
|
+
b.n += 1;
|
|
382
|
+
if (extra !== void 0) b.seen.add(extra);
|
|
383
|
+
if (counters.size > 4096) {
|
|
384
|
+
for (const [kk, v] of counters) {
|
|
385
|
+
if (now - v.start >= windowSec) counters.delete(kk);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
return extra !== void 0 ? b.seen.size : b.n;
|
|
389
|
+
}
|
|
390
|
+
function noteSessionAccess(key, sessionId) {
|
|
391
|
+
const threshold = envInt("AGENT_GATE_SESSION_SWEEP_THRESHOLD", 50);
|
|
392
|
+
if (threshold <= 0) return [0, false];
|
|
393
|
+
const window = envFloat("AGENT_GATE_SESSION_SWEEP_WINDOW", 300);
|
|
394
|
+
const n = bump("sweep", key, window, sessionId || "-");
|
|
395
|
+
return [n, n > threshold];
|
|
396
|
+
}
|
|
397
|
+
function sessionSweepAction() {
|
|
398
|
+
return (env("AGENT_GATE_SESSION_SWEEP_ACTION", "log") || "log").toLowerCase();
|
|
399
|
+
}
|
|
400
|
+
function noteQueueReject(key) {
|
|
401
|
+
const threshold = envInt("AGENT_GATE_QUEUE_ABUSE_THRESHOLD", 10);
|
|
402
|
+
if (threshold <= 0) return [0, false];
|
|
403
|
+
const window = envFloat("AGENT_GATE_QUEUE_ABUSE_WINDOW", 60);
|
|
404
|
+
const n = bump("queue", key, window);
|
|
405
|
+
return [n, n > threshold];
|
|
406
|
+
}
|
|
407
|
+
function queueAbuseAction() {
|
|
408
|
+
return (env("AGENT_GATE_QUEUE_ABUSE_ACTION", "log") || "log").toLowerCase();
|
|
409
|
+
}
|
|
410
|
+
function hardenFilesEnabled() {
|
|
411
|
+
return TRUTHY.includes(env("AGENT_GATE_HARDEN_FILES", "1").toLowerCase());
|
|
412
|
+
}
|
|
413
|
+
function mossTokenPath() {
|
|
414
|
+
const root = env("AGENT_MOSS_DATA_DIR");
|
|
415
|
+
if (root) return (0, import_node_path.join)(root, "auth_token");
|
|
416
|
+
const home = process.env.SUDO_USER && existsDir(`/home/${process.env.SUDO_USER}`) ? `/home/${process.env.SUDO_USER}` : (0, import_node_os.homedir)();
|
|
417
|
+
return (0, import_node_path.join)(home, ".config", "agentmoss", "auth_token");
|
|
418
|
+
}
|
|
419
|
+
function resolveMossToken(force = false) {
|
|
420
|
+
const now = Date.now() / 1e3;
|
|
421
|
+
if (!force && mossTokenCache.expires > now) return mossTokenCache.value;
|
|
422
|
+
let tok = env("AGENT_GATE_MOSS_TOKEN");
|
|
423
|
+
if (!tok) tok = env("AGENT_MOSS_AUTH_TOKEN");
|
|
424
|
+
if (!tok) {
|
|
425
|
+
const f = env("AGENT_MOSS_AUTH_TOKEN_FILE");
|
|
426
|
+
if (f) {
|
|
427
|
+
try {
|
|
428
|
+
tok = (0, import_node_fs.readFileSync)(f, "utf-8").trim();
|
|
429
|
+
} catch {
|
|
430
|
+
tok = "";
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
if (!tok) {
|
|
435
|
+
try {
|
|
436
|
+
tok = (0, import_node_fs.readFileSync)(mossTokenPath(), "utf-8").trim();
|
|
437
|
+
} catch {
|
|
438
|
+
tok = "";
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
mossTokenCache = { value: tok, expires: now + 60 };
|
|
442
|
+
return tok;
|
|
443
|
+
}
|
|
444
|
+
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;
|
|
445
|
+
var init_security = __esm({
|
|
446
|
+
"src/shared/security.ts"() {
|
|
447
|
+
"use strict";
|
|
448
|
+
init_cjs_shims();
|
|
449
|
+
import_node_crypto = require("crypto");
|
|
450
|
+
import_node_fs = require("fs");
|
|
451
|
+
import_node_os = require("os");
|
|
452
|
+
import_node_path = require("path");
|
|
453
|
+
TRUTHY = ["1", "true", "yes", "on"];
|
|
454
|
+
PUBLIC_PATHS = ["/api/v1/health"];
|
|
455
|
+
DASHBOARD_COOKIE = "agent_gate_token";
|
|
456
|
+
AUTH_MODE_AUTO = "auto";
|
|
457
|
+
AUTH_MODE_OFF = "off";
|
|
458
|
+
DASHBOARD_SECURITY_HEADERS = {
|
|
459
|
+
"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'",
|
|
460
|
+
"X-Frame-Options": "DENY",
|
|
461
|
+
"X-Content-Type-Options": "nosniff",
|
|
462
|
+
"Referrer-Policy": "no-referrer"
|
|
463
|
+
};
|
|
464
|
+
tokenCache = null;
|
|
465
|
+
fdTokenCache = /* @__PURE__ */ new Map();
|
|
466
|
+
POOL_DEFAULTS = { biz: 16, read: 8, ops: 4, health: 4, other: 4 };
|
|
467
|
+
counters = /* @__PURE__ */ new Map();
|
|
468
|
+
mossTokenCache = { value: "", expires: 0 };
|
|
469
|
+
RateLimiter = class {
|
|
470
|
+
constructor(qps, burst) {
|
|
471
|
+
this.qps = qps;
|
|
472
|
+
this.burst = burst;
|
|
473
|
+
this.burst = burst ?? Math.max(qps, 1);
|
|
474
|
+
}
|
|
475
|
+
qps;
|
|
476
|
+
burst;
|
|
477
|
+
buckets = /* @__PURE__ */ new Map();
|
|
478
|
+
get enabled() {
|
|
479
|
+
return this.qps > 0;
|
|
480
|
+
}
|
|
481
|
+
allow(key) {
|
|
482
|
+
const now = Date.now() / 1e3;
|
|
483
|
+
const cur = this.buckets.get(key) ?? { tokens: this.burst, last: now };
|
|
484
|
+
const tokens = Math.min(this.burst, cur.tokens + (now - cur.last) * this.qps);
|
|
485
|
+
if (tokens < 1) {
|
|
486
|
+
this.buckets.set(key, { tokens, last: now });
|
|
487
|
+
return false;
|
|
488
|
+
}
|
|
489
|
+
this.buckets.set(key, { tokens: tokens - 1, last: now });
|
|
490
|
+
return true;
|
|
491
|
+
}
|
|
492
|
+
};
|
|
493
|
+
PooledLimiter = class {
|
|
494
|
+
counts = /* @__PURE__ */ new Map();
|
|
495
|
+
tryAcquire(key, limit) {
|
|
496
|
+
if (limit <= 0) return true;
|
|
497
|
+
const cur = this.counts.get(key) || 0;
|
|
498
|
+
if (cur >= limit) return false;
|
|
499
|
+
this.counts.set(key, cur + 1);
|
|
500
|
+
return true;
|
|
501
|
+
}
|
|
502
|
+
release(key) {
|
|
503
|
+
const cur = this.counts.get(key) || 0;
|
|
504
|
+
if (cur <= 1) this.counts.delete(key);
|
|
505
|
+
else this.counts.set(key, cur - 1);
|
|
506
|
+
}
|
|
507
|
+
};
|
|
77
508
|
}
|
|
78
509
|
});
|
|
79
510
|
|
|
80
511
|
// src/shared/moss-client.ts
|
|
81
512
|
var moss_client_exports = {};
|
|
82
513
|
__export(moss_client_exports, {
|
|
514
|
+
authHeaders: () => authHeaders,
|
|
83
515
|
callAgentMoss: () => callAgentMoss,
|
|
84
516
|
callAgentMossReview: () => callAgentMossReview,
|
|
85
517
|
fetchMossHealth: () => fetchMossHealth,
|
|
86
518
|
setMossUrl: () => setMossUrl
|
|
87
519
|
});
|
|
520
|
+
function authHeaders() {
|
|
521
|
+
const h = { "Content-Type": "application/json" };
|
|
522
|
+
const tok = resolveMossToken();
|
|
523
|
+
if (tok) h["Authorization"] = `Bearer ${tok}`;
|
|
524
|
+
return h;
|
|
525
|
+
}
|
|
88
526
|
function setMossUrl(url) {
|
|
89
527
|
mossUrl = url;
|
|
90
528
|
}
|
|
@@ -94,14 +532,23 @@ async function callAgentMoss(request) {
|
|
|
94
532
|
if (isStatefulIncrementalEnabled() && req && typeof req === "object" && req.metadata === void 0) {
|
|
95
533
|
req.metadata = { stateful_incremental: true };
|
|
96
534
|
}
|
|
97
|
-
const
|
|
535
|
+
const body = JSON.stringify(req);
|
|
536
|
+
let resp = await (0, import_node_fetch.default)(`${mossUrl}/api/v1/analyze`, {
|
|
98
537
|
method: "POST",
|
|
99
|
-
headers:
|
|
100
|
-
body
|
|
101
|
-
// 100s:覆盖 AgentMoss 总超时(90s)+ 余量,避免 AgentMoss 还在分析时
|
|
102
|
-
// 被 AgentGate 抢断后 fail-closed 误杀。AgentGate 这层不重试(AgentMoss 内部已重试)。
|
|
538
|
+
headers: authHeaders(),
|
|
539
|
+
body,
|
|
103
540
|
timeout: 1e5
|
|
104
541
|
});
|
|
542
|
+
if (resp.status === 401) {
|
|
543
|
+
console.warn("[AgentGate] AgentMoss \u8FD4\u56DE 401\uFF0C\u5DF2\u91CD\u65B0\u8BFB\u53D6\u8BBF\u95EE token\uFF0C\u91CD\u8BD5\u4E00\u6B21");
|
|
544
|
+
resolveMossToken(true);
|
|
545
|
+
resp = await (0, import_node_fetch.default)(`${mossUrl}/api/v1/analyze`, {
|
|
546
|
+
method: "POST",
|
|
547
|
+
headers: authHeaders(),
|
|
548
|
+
body,
|
|
549
|
+
timeout: 1e5
|
|
550
|
+
});
|
|
551
|
+
}
|
|
105
552
|
if (!resp.ok) {
|
|
106
553
|
console.error(`[AgentGate] AgentMoss HTTP ${resp.status}: ${resp.statusText}`);
|
|
107
554
|
return failClosedResponse(`AgentMoss returned ${resp.status}`);
|
|
@@ -141,7 +588,7 @@ async function callAgentMossReview(options) {
|
|
|
141
588
|
try {
|
|
142
589
|
const resp = await (0, import_node_fetch.default)(`${mossUrl}/api/v1/review`, {
|
|
143
590
|
method: "POST",
|
|
144
|
-
headers:
|
|
591
|
+
headers: authHeaders(),
|
|
145
592
|
body: JSON.stringify({ agent_id: agentId, db_path: dbPath }),
|
|
146
593
|
timeout: 3e4
|
|
147
594
|
});
|
|
@@ -169,8 +616,9 @@ var init_moss_client = __esm({
|
|
|
169
616
|
init_cjs_shims();
|
|
170
617
|
import_node_fetch = __toESM(require("node-fetch"));
|
|
171
618
|
init_multi_session();
|
|
619
|
+
init_security();
|
|
172
620
|
DEFAULT_MOSS_URL = "http://127.0.0.1:9090";
|
|
173
|
-
mossUrl = DEFAULT_MOSS_URL;
|
|
621
|
+
mossUrl = process.env.AGENT_MOSS_URL || process.env.MOSS_URL || DEFAULT_MOSS_URL;
|
|
174
622
|
}
|
|
175
623
|
});
|
|
176
624
|
|
|
@@ -194,6 +642,7 @@ var init_json_storage = __esm({
|
|
|
194
642
|
init_cjs_shims();
|
|
195
643
|
import_fs = require("fs");
|
|
196
644
|
import_path = require("path");
|
|
645
|
+
init_security();
|
|
197
646
|
JsonStorage = class {
|
|
198
647
|
dataDir;
|
|
199
648
|
agentsPath;
|
|
@@ -209,10 +658,39 @@ var init_json_storage = __esm({
|
|
|
209
658
|
this.agentsPath = (0, import_path.join)(this.dataDir, "agents.json");
|
|
210
659
|
this.sessionsPath = (0, import_path.join)(this.dataDir, "sessions.json");
|
|
211
660
|
this.toolCallsDir = (0, import_path.join)(this.dataDir, "tool_calls");
|
|
212
|
-
if (!(0, import_fs.existsSync)(this.dataDir)) (0, import_fs.mkdirSync)(this.dataDir, { recursive: true });
|
|
213
|
-
if (!(0, import_fs.existsSync)(this.toolCallsDir)) (0, import_fs.mkdirSync)(this.toolCallsDir, { recursive: true });
|
|
661
|
+
if (!(0, import_fs.existsSync)(this.dataDir)) (0, import_fs.mkdirSync)(this.dataDir, { recursive: true, mode: 448 });
|
|
662
|
+
if (!(0, import_fs.existsSync)(this.toolCallsDir)) (0, import_fs.mkdirSync)(this.toolCallsDir, { recursive: true, mode: 448 });
|
|
663
|
+
this.hardenStoragePermissions();
|
|
214
664
|
this.nextId = this.recoverNextId();
|
|
215
665
|
}
|
|
666
|
+
/** 把存储目录收紧到 0700、已有 JSON 文件收紧到 0600。
|
|
667
|
+
* 新建文件由 `writeJsonFile` 的 mode 保证;这里处理**存量**文件
|
|
668
|
+
* (旧版本按 umask 创建的 0644)以及 mkdirSync 对已存在目录不生效的问题。 */
|
|
669
|
+
hardenStoragePermissions() {
|
|
670
|
+
if (!hardenFilesEnabled()) return;
|
|
671
|
+
const uid = process.getuid?.();
|
|
672
|
+
const tighten = (p, mode) => {
|
|
673
|
+
try {
|
|
674
|
+
const st = (0, import_fs.statSync)(p);
|
|
675
|
+
if (st.isSymbolicLink()) return;
|
|
676
|
+
if (uid !== void 0 && st.uid !== uid) return;
|
|
677
|
+
if ((st.mode & 511) !== mode) (0, import_fs.chmodSync)(p, mode);
|
|
678
|
+
} catch {
|
|
679
|
+
}
|
|
680
|
+
};
|
|
681
|
+
tighten(this.dataDir, 448);
|
|
682
|
+
tighten(this.toolCallsDir, 448);
|
|
683
|
+
tighten(this.agentsPath, 384);
|
|
684
|
+
tighten(this.sessionsPath, 384);
|
|
685
|
+
try {
|
|
686
|
+
for (const f of (0, import_fs.readdirSync)(this.toolCallsDir)) {
|
|
687
|
+
if (f.endsWith(".json") || f.endsWith(".tmp")) {
|
|
688
|
+
tighten((0, import_path.join)(this.toolCallsDir, f), 384);
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
} catch {
|
|
692
|
+
}
|
|
693
|
+
}
|
|
216
694
|
/** 扫描所有 tool_calls 文件,找到最大 id + 1 */
|
|
217
695
|
recoverNextId() {
|
|
218
696
|
let maxId = 0;
|
|
@@ -236,12 +714,12 @@ var init_json_storage = __esm({
|
|
|
236
714
|
return fallback;
|
|
237
715
|
}
|
|
238
716
|
}
|
|
239
|
-
/** 原子写入:先写 .tmp 再 rename */
|
|
717
|
+
/** 原子写入:先写 .tmp 再 rename(rename 保留 tmp 的 0600 权限) */
|
|
240
718
|
writeJsonFile(path, data) {
|
|
241
719
|
const dir = (0, import_path.dirname)(path);
|
|
242
|
-
if (!(0, import_fs.existsSync)(dir)) (0, import_fs.mkdirSync)(dir, { recursive: true });
|
|
720
|
+
if (!(0, import_fs.existsSync)(dir)) (0, import_fs.mkdirSync)(dir, { recursive: true, mode: 448 });
|
|
243
721
|
const tmp = path + ".tmp";
|
|
244
|
-
(0, import_fs.writeFileSync)(tmp, JSON.stringify(data, null, 2), "utf-8");
|
|
722
|
+
(0, import_fs.writeFileSync)(tmp, JSON.stringify(data, null, 2), { encoding: "utf-8", mode: 384 });
|
|
245
723
|
(0, import_fs.renameSync)(tmp, path);
|
|
246
724
|
}
|
|
247
725
|
loadAgents() {
|
|
@@ -355,6 +833,9 @@ var init_json_storage = __esm({
|
|
|
355
833
|
} catch {
|
|
356
834
|
}
|
|
357
835
|
}
|
|
836
|
+
if (params.agentType) {
|
|
837
|
+
allRecords = allRecords.filter((r) => r.agent_type === params.agentType);
|
|
838
|
+
}
|
|
358
839
|
if (params.decision) {
|
|
359
840
|
allRecords = allRecords.filter((r) => r.decision === params.decision);
|
|
360
841
|
}
|
|
@@ -365,6 +846,7 @@ var init_json_storage = __esm({
|
|
|
365
846
|
}
|
|
366
847
|
countToolCalls(params) {
|
|
367
848
|
const sessions = this.loadSessions();
|
|
849
|
+
const agents = this.loadAgents();
|
|
368
850
|
let allRecords = [];
|
|
369
851
|
try {
|
|
370
852
|
const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
|
|
@@ -374,6 +856,12 @@ var init_json_storage = __esm({
|
|
|
374
856
|
}
|
|
375
857
|
} catch {
|
|
376
858
|
}
|
|
859
|
+
if (params.agentType) {
|
|
860
|
+
const allowed = new Set(
|
|
861
|
+
[...sessions.values()].filter((s) => (agents.get(s.agent_id)?.agent_type || "") === params.agentType).map((s) => s.id)
|
|
862
|
+
);
|
|
863
|
+
allRecords = allRecords.filter((r) => allowed.has(r.session_id));
|
|
864
|
+
}
|
|
377
865
|
if (params.decision) {
|
|
378
866
|
allRecords = allRecords.filter((r) => r.decision === params.decision);
|
|
379
867
|
}
|
|
@@ -419,11 +907,12 @@ var init_json_storage = __esm({
|
|
|
419
907
|
hostname: agent?.hostname || ""
|
|
420
908
|
};
|
|
421
909
|
}
|
|
422
|
-
getAgentsList() {
|
|
910
|
+
getAgentsList(agentType) {
|
|
423
911
|
const agents = this.loadAgents();
|
|
424
912
|
const sessions = this.loadSessions();
|
|
425
913
|
const result = [];
|
|
426
914
|
for (const agent of agents.values()) {
|
|
915
|
+
if (agentType && agent.agent_type !== agentType) continue;
|
|
427
916
|
let sessionCount = 0;
|
|
428
917
|
let callCount = 0;
|
|
429
918
|
for (const session of sessions.values()) {
|
|
@@ -444,6 +933,11 @@ var init_json_storage = __esm({
|
|
|
444
933
|
result.sort((a, b) => b.call_count - a.call_count);
|
|
445
934
|
return result.slice(0, 20);
|
|
446
935
|
}
|
|
936
|
+
getSessionAgentType(sessionId) {
|
|
937
|
+
const session = this.loadSessions().get(sessionId);
|
|
938
|
+
if (!session) return void 0;
|
|
939
|
+
return this.loadAgents().get(session.agent_id)?.agent_type;
|
|
940
|
+
}
|
|
447
941
|
getTimeline(limit = 100) {
|
|
448
942
|
const buckets = /* @__PURE__ */ new Map();
|
|
449
943
|
try {
|
|
@@ -627,6 +1121,10 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
627
1121
|
conditions.push("tc.session_id = ?");
|
|
628
1122
|
values.push(params.sessionId);
|
|
629
1123
|
}
|
|
1124
|
+
if (params.agentType) {
|
|
1125
|
+
conditions.push("a.agent_type = ?");
|
|
1126
|
+
values.push(params.agentType);
|
|
1127
|
+
}
|
|
630
1128
|
if (params.decision) {
|
|
631
1129
|
conditions.push("tc.decision = ?");
|
|
632
1130
|
values.push(params.decision);
|
|
@@ -649,9 +1147,16 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
649
1147
|
conditions.push("tc.decision = ?");
|
|
650
1148
|
values.push(params.decision);
|
|
651
1149
|
}
|
|
1150
|
+
if (params.agentType) {
|
|
1151
|
+
conditions.push("a.agent_type = ?");
|
|
1152
|
+
values.push(params.agentType);
|
|
1153
|
+
}
|
|
652
1154
|
const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
653
1155
|
const row = this.db.prepare(
|
|
654
|
-
`SELECT COUNT(*) as total FROM tool_calls tc
|
|
1156
|
+
`SELECT COUNT(*) as total FROM tool_calls tc
|
|
1157
|
+
LEFT JOIN sessions s ON tc.session_id = s.id
|
|
1158
|
+
LEFT JOIN agents a ON s.agent_id = a.id
|
|
1159
|
+
${where}`
|
|
655
1160
|
).get(...values);
|
|
656
1161
|
return row?.total ?? 0;
|
|
657
1162
|
}
|
|
@@ -659,11 +1164,11 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
659
1164
|
const row = this.db.prepare("SELECT COUNT(*) as total FROM tool_calls").get();
|
|
660
1165
|
let dbBytes = 0;
|
|
661
1166
|
try {
|
|
662
|
-
const { statSync:
|
|
663
|
-
dbBytes =
|
|
1167
|
+
const { statSync: statSync3, existsSync: existsSync3 } = require("fs");
|
|
1168
|
+
dbBytes = statSync3(this.dbPath).size;
|
|
664
1169
|
for (const suffix of ["-wal", "-shm"]) {
|
|
665
1170
|
const p = this.dbPath + suffix;
|
|
666
|
-
if (existsSync3(p)) dbBytes +=
|
|
1171
|
+
if (existsSync3(p)) dbBytes += statSync3(p).size;
|
|
667
1172
|
}
|
|
668
1173
|
} catch {
|
|
669
1174
|
}
|
|
@@ -677,7 +1182,8 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
677
1182
|
})();
|
|
678
1183
|
return result;
|
|
679
1184
|
}
|
|
680
|
-
getAgentsList() {
|
|
1185
|
+
getAgentsList(agentType) {
|
|
1186
|
+
const where = agentType ? "WHERE a.agent_type = ?" : "";
|
|
681
1187
|
return this.db.prepare(`
|
|
682
1188
|
SELECT a.agent_type, a.hostname, a.agent_version as version,
|
|
683
1189
|
COUNT(DISTINCT s.id) as session_count,
|
|
@@ -685,10 +1191,19 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
685
1191
|
FROM agents a
|
|
686
1192
|
LEFT JOIN sessions s ON s.agent_id = a.id
|
|
687
1193
|
LEFT JOIN tool_calls tc ON tc.session_id = s.id
|
|
1194
|
+
${where}
|
|
688
1195
|
GROUP BY a.id
|
|
689
1196
|
ORDER BY call_count DESC
|
|
690
1197
|
LIMIT 20
|
|
691
|
-
`).all();
|
|
1198
|
+
`).all(...agentType ? [agentType] : []);
|
|
1199
|
+
}
|
|
1200
|
+
getSessionAgentType(sessionId) {
|
|
1201
|
+
const row = this.db.prepare(
|
|
1202
|
+
`SELECT a.agent_type as agent_type
|
|
1203
|
+
FROM sessions s JOIN agents a ON s.agent_id = a.id
|
|
1204
|
+
WHERE s.id = ?`
|
|
1205
|
+
).get(sessionId);
|
|
1206
|
+
return row?.agent_type;
|
|
692
1207
|
}
|
|
693
1208
|
getTimeline(limit = 100) {
|
|
694
1209
|
const rows = this.db.prepare(`
|
|
@@ -757,14 +1272,14 @@ function getDb(dbPath) {
|
|
|
757
1272
|
if (rawDb) return rawDb;
|
|
758
1273
|
try {
|
|
759
1274
|
const Database = require("better-sqlite3");
|
|
760
|
-
const { existsSync: existsSync3, mkdirSync:
|
|
761
|
-
const { join:
|
|
1275
|
+
const { existsSync: existsSync3, mkdirSync: mkdirSync4 } = require("fs");
|
|
1276
|
+
const { join: join4, dirname: dirname3 } = require("path");
|
|
762
1277
|
const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
|
|
763
|
-
const xdgData = process.env.XDG_DATA_HOME ||
|
|
764
|
-
const defaultPath =
|
|
1278
|
+
const xdgData = process.env.XDG_DATA_HOME || join4(home, ".local", "share");
|
|
1279
|
+
const defaultPath = join4(xdgData, "agent_gate", "agent_gate_ts.db");
|
|
765
1280
|
const path = dbPath || defaultPath;
|
|
766
1281
|
const dir = dirname3(path);
|
|
767
|
-
if (!existsSync3(dir))
|
|
1282
|
+
if (!existsSync3(dir)) mkdirSync4(dir, { recursive: true });
|
|
768
1283
|
rawDb = new Database(path);
|
|
769
1284
|
rawDb.pragma("journal_mode = WAL");
|
|
770
1285
|
return rawDb;
|
|
@@ -817,6 +1332,7 @@ init_cjs_shims();
|
|
|
817
1332
|
var import_hono = require("hono");
|
|
818
1333
|
var import_cors = require("hono/cors");
|
|
819
1334
|
var import_logger = require("hono/logger");
|
|
1335
|
+
var import_cookie = require("hono/cookie");
|
|
820
1336
|
|
|
821
1337
|
// src/v1/routes.ts
|
|
822
1338
|
init_cjs_shims();
|
|
@@ -827,7 +1343,7 @@ var import_zod = require("zod");
|
|
|
827
1343
|
|
|
828
1344
|
// src/version.ts
|
|
829
1345
|
init_cjs_shims();
|
|
830
|
-
var _version = true ? "0.
|
|
1346
|
+
var _version = true ? "0.8.0" : (() => {
|
|
831
1347
|
try {
|
|
832
1348
|
const require2 = createRequire(importMetaUrl);
|
|
833
1349
|
const pkg = require2("../package.json");
|
|
@@ -902,7 +1418,8 @@ var HealthResponseSchema = import_zod.z.object({
|
|
|
902
1418
|
status: import_zod.z.string().default("healthy"),
|
|
903
1419
|
version: import_zod.z.string().default(version),
|
|
904
1420
|
moss_version: import_zod.z.string().default("N/A"),
|
|
905
|
-
moss_status: import_zod.z.string().default("unknown")
|
|
1421
|
+
moss_status: import_zod.z.string().default("unknown"),
|
|
1422
|
+
instance: import_zod.z.string().default("")
|
|
906
1423
|
});
|
|
907
1424
|
|
|
908
1425
|
// src/shared/normalizer.ts
|
|
@@ -1083,12 +1600,15 @@ function getStorageStats() {
|
|
|
1083
1600
|
function clearToolCalls() {
|
|
1084
1601
|
return store().clearToolCalls();
|
|
1085
1602
|
}
|
|
1086
|
-
function getAgentsList() {
|
|
1087
|
-
return store().getAgentsList();
|
|
1603
|
+
function getAgentsList(agentType) {
|
|
1604
|
+
return store().getAgentsList(agentType);
|
|
1088
1605
|
}
|
|
1089
1606
|
function getTimeline(limit) {
|
|
1090
1607
|
return store().getTimeline(limit);
|
|
1091
1608
|
}
|
|
1609
|
+
function getSessionAgentType(sessionId) {
|
|
1610
|
+
return store().getSessionAgentType(sessionId);
|
|
1611
|
+
}
|
|
1092
1612
|
|
|
1093
1613
|
// src/v1/routes.ts
|
|
1094
1614
|
init_multi_session();
|
|
@@ -1103,6 +1623,7 @@ function resolveAgentIdentity(metadata, collected) {
|
|
|
1103
1623
|
}
|
|
1104
1624
|
|
|
1105
1625
|
// src/v1/routes.ts
|
|
1626
|
+
init_security();
|
|
1106
1627
|
var v1ReviewCounter = 0;
|
|
1107
1628
|
async function healthRoute(c) {
|
|
1108
1629
|
const mossHealth = await fetchMossHealth();
|
|
@@ -1110,7 +1631,11 @@ async function healthRoute(c) {
|
|
|
1110
1631
|
status: "healthy",
|
|
1111
1632
|
version,
|
|
1112
1633
|
moss_version: mossHealth.moss_version,
|
|
1113
|
-
moss_status: mossHealth.moss_status
|
|
1634
|
+
moss_status: mossHealth.moss_status,
|
|
1635
|
+
// 归属标识:由启动方注入 AGENT_GATE_INSTANCE(同机多套 AgentGate 时用于区分是谁起的),
|
|
1636
|
+
// 未注入时为空串。与 agent-moss 的 AGENT_MOSS_INSTANCE 同一套约定,供探测端在
|
|
1637
|
+
// /proc 不可读、无法做 PID↔端口校验时退化为按实例字符串判归属。
|
|
1638
|
+
instance: process.env.AGENT_GATE_INSTANCE || ""
|
|
1114
1639
|
});
|
|
1115
1640
|
}
|
|
1116
1641
|
function storageOversizeInfo() {
|
|
@@ -1124,6 +1649,12 @@ async function analyzeRoute(c) {
|
|
|
1124
1649
|
try {
|
|
1125
1650
|
const body = await c.req.json();
|
|
1126
1651
|
const input = AgentGateInputSchema.parse(body);
|
|
1652
|
+
const principal = c.get("principal") || "";
|
|
1653
|
+
const bind = bindAgent(principal, input.agent_type || "");
|
|
1654
|
+
if (!bind.ok) {
|
|
1655
|
+
console.warn(`[AgentGate] \u62D2\u7EDD\u8EAB\u4EFD\u4E0D\u5339\u914D\u7684\u8BF7\u6C42: principal=${principal} claimed=${input.agent_type}`);
|
|
1656
|
+
return c.json({ detail: bind.reason }, 403);
|
|
1657
|
+
}
|
|
1127
1658
|
const toolName = input.tool_name || input.a_next?.action_type || "unknown";
|
|
1128
1659
|
const command = input.command || input.a_next?.action_detail || "";
|
|
1129
1660
|
const key = cacheKey(input.session_id, input.cwd, command);
|
|
@@ -1204,7 +1735,22 @@ async function analyzeRoute(c) {
|
|
|
1204
1735
|
}
|
|
1205
1736
|
}
|
|
1206
1737
|
async function sessionsRoute(c) {
|
|
1207
|
-
const sessionId = c.req.param("id");
|
|
1738
|
+
const sessionId = c.req.param("id") || "";
|
|
1739
|
+
const principal = c.get("principal") || "ip:unknown";
|
|
1740
|
+
const [n, hit] = noteSessionAccess(principal, sessionId);
|
|
1741
|
+
if (hit) {
|
|
1742
|
+
if (sessionSweepAction() === "deny") {
|
|
1743
|
+
return c.json({ detail: "\u4F1A\u8BDD\u8BBF\u95EE\u8FC7\u4E8E\u96C6\u4E2D\uFF0C\u7591\u4F3C\u6279\u91CF\u626B\u63CF" }, 429);
|
|
1744
|
+
}
|
|
1745
|
+
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`);
|
|
1746
|
+
}
|
|
1747
|
+
const bound = boundAgentOf(c.get("principal") || "");
|
|
1748
|
+
if (bound) {
|
|
1749
|
+
const owner = getSessionAgentType(sessionId);
|
|
1750
|
+
if ((owner || "").toLowerCase() !== bound.toLowerCase()) {
|
|
1751
|
+
return c.json({ detail: "\u8BE5\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u5F53\u524D\u51ED\u8BC1\u7ED1\u5B9A\u7684 agent" }, 403);
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1208
1754
|
const rows = queryToolCalls({ sessionId, limit: 100 });
|
|
1209
1755
|
return c.json({ session_id: sessionId, tool_calls: rows });
|
|
1210
1756
|
}
|
|
@@ -1212,35 +1758,168 @@ async function toolCallsRoute(c) {
|
|
|
1212
1758
|
const decision = c.req.query("decision");
|
|
1213
1759
|
const limit = parseInt(c.req.query("limit") || "50", 10);
|
|
1214
1760
|
const offset = parseInt(c.req.query("offset") || "0", 10);
|
|
1215
|
-
const
|
|
1216
|
-
const
|
|
1761
|
+
const bound = boundAgentOf(c.get("principal") || "");
|
|
1762
|
+
const agentType = bound || void 0;
|
|
1763
|
+
const total = countToolCalls({ decision: decision ?? void 0, agentType });
|
|
1764
|
+
const data = queryToolCalls({ decision: decision ?? void 0, agentType, limit, offset });
|
|
1217
1765
|
return c.json({ total, data });
|
|
1218
1766
|
}
|
|
1219
1767
|
async function agentsRoute(c) {
|
|
1220
|
-
const
|
|
1768
|
+
const bound = boundAgentOf(c.get("principal") || "");
|
|
1769
|
+
const agents = getAgentsList(bound || void 0);
|
|
1221
1770
|
return c.json(agents);
|
|
1222
1771
|
}
|
|
1223
1772
|
async function timelineRoute(c) {
|
|
1773
|
+
if (boundAgentOf(c.get("principal") || "")) {
|
|
1774
|
+
return c.json({ detail: "\u8BE5\u51ED\u8BC1\u7ED1\u5B9A\u5230 agent\uFF0C\u65E0\u6743\u67E5\u770B\u5168\u5C40\u65F6\u95F4\u7EBF" }, 403);
|
|
1775
|
+
}
|
|
1224
1776
|
const limit = parseInt(c.req.query("limit") || "100", 10);
|
|
1225
1777
|
const rows = getTimeline(limit);
|
|
1226
1778
|
return c.json(rows);
|
|
1227
1779
|
}
|
|
1228
1780
|
function storageStatsRoute(c) {
|
|
1781
|
+
if (boundAgentOf(c.get("principal") || "")) {
|
|
1782
|
+
return c.json({ detail: "\u8BE5\u51ED\u8BC1\u7ED1\u5B9A\u5230 agent\uFF0C\u65E0\u6743\u67E5\u770B\u5B58\u50A8\u7EDF\u8BA1" }, 403);
|
|
1783
|
+
}
|
|
1229
1784
|
const storageStats = getStorageStats();
|
|
1230
1785
|
const defaultThreshold = parseFloat(process.env.AGENT_GATE_CLEANUP_THRESHOLD_MB || "100");
|
|
1231
1786
|
const totalMB = (storageStats.dbBytes + storageStats.jsonBytes) / 1024 / 1024;
|
|
1232
1787
|
return c.json({ stats: storageStats, oversize: totalMB > defaultThreshold, thresholdMB: defaultThreshold });
|
|
1233
1788
|
}
|
|
1234
1789
|
function deleteToolCallsRoute(c) {
|
|
1790
|
+
if (boundAgentOf(c.get("principal") || "")) {
|
|
1791
|
+
return c.json({ detail: "\u8BE5\u51ED\u8BC1\u7ED1\u5B9A\u5230 agent\uFF0C\u65E0\u6743\u6E05\u7406\u8BB0\u5F55" }, 403);
|
|
1792
|
+
}
|
|
1235
1793
|
const deleted = clearToolCalls();
|
|
1236
1794
|
return c.json({ deleted });
|
|
1237
1795
|
}
|
|
1238
1796
|
|
|
1239
1797
|
// src/v1/server.ts
|
|
1798
|
+
init_security();
|
|
1799
|
+
var PUBLIC_PAGE_PATHS = ["/dashboard", "/dashboard/"];
|
|
1800
|
+
var UNAUTHORIZED_HTML = `<!DOCTYPE html>
|
|
1801
|
+
<html lang="zh-CN"><head><meta charset="UTF-8"><title>AgentGate Dashboard</title>
|
|
1802
|
+
<style>body{font:14px/1.6 -apple-system,'Segoe UI',sans-serif;background:#FAFAFA;color:#1d1d1f;
|
|
1803
|
+
display:flex;align-items:center;justify-content:center;height:100vh;margin:0}
|
|
1804
|
+
.box{background:#fff;border:1px solid #eee;border-radius:10px;padding:28px 32px;max-width:560px}
|
|
1805
|
+
code{background:#F5F5F7;padding:1px 6px;border-radius:4px;font-size:13px}
|
|
1806
|
+
p{margin:8px 0;color:#555}</style></head><body>
|
|
1807
|
+
<div class="box">
|
|
1808
|
+
<h3 style="margin-top:0">\u9700\u8981\u8BBF\u95EE\u51ED\u8BC1</h3>
|
|
1809
|
+
<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>
|
|
1810
|
+
<p><code>/dashboard/?token=<token></code></p>
|
|
1811
|
+
<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
|
|
1812
|
+
\u6362 Cookie \u540E\u5C31\u53EA\u9700\u6253\u5F00 <code>/dashboard/</code>\u3002</p>
|
|
1813
|
+
<p>\u5982\u9700\u6062\u590D\u65E7\u884C\u4E3A\uFF1A<code>AGENT_GATE_AUTH_MODE=off</code>\u3002</p>
|
|
1814
|
+
</div></body></html>`;
|
|
1815
|
+
var AGENT_FORBIDDEN_HTML = `<!DOCTYPE html>
|
|
1816
|
+
<html lang="zh-CN"><head><meta charset="UTF-8"><title>AgentGate Dashboard</title>
|
|
1817
|
+
<style>body{font:14px/1.6 -apple-system,'Segoe UI',sans-serif;background:#FAFAFA;color:#1d1d1f;
|
|
1818
|
+
display:flex;align-items:center;justify-content:center;height:100vh;margin:0}
|
|
1819
|
+
.box{background:#fff;border:1px solid #eee;border-radius:10px;padding:28px 32px;max-width:560px}
|
|
1820
|
+
code{background:#F5F5F7;padding:1px 6px;border-radius:4px;font-size:13px}
|
|
1821
|
+
p{margin:8px 0;color:#555}</style></head><body>
|
|
1822
|
+
<div class="box">
|
|
1823
|
+
<h3 style="margin-top:0">\u8BE5\u51ED\u8BC1\u65E0\u6743\u8BBF\u95EE\u770B\u677F</h3>
|
|
1824
|
+
<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
|
|
1825
|
+
\u5426\u5219 agent A \u5C31\u80FD\u770B\u5230 agent B \u7684\u5168\u90E8\u547D\u4EE4\u539F\u6587\u548C\u7528\u6237 prompt\u3002</p>
|
|
1826
|
+
<p>agent \u81EA\u67E5\u8BF7\u7528\u8BFB\u63A5\u53E3\uFF08\u6309\u51ED\u8BC1\u7ED1\u5B9A\u7684 agent \u81EA\u52A8\u8FC7\u6EE4\uFF09\uFF1A
|
|
1827
|
+
<code>/api/v1/sessions/<id>/traces</code>\u3001<code>/api/v1/tool_calls</code>\u3002</p>
|
|
1828
|
+
<p>\u8FD0\u7EF4\u8BF7\u4F7F\u7528\u5168\u5C40 token\uFF1A<code>~/.config/agentgate/auth_token</code>\u3002</p>
|
|
1829
|
+
</div></body></html>`;
|
|
1240
1830
|
function createApp() {
|
|
1241
1831
|
const app = new import_hono.Hono();
|
|
1242
|
-
|
|
1832
|
+
const rateLimiter = new RateLimiter(rateLimitQps());
|
|
1833
|
+
const pools = new PooledLimiter();
|
|
1834
|
+
app.use("*", (0, import_cors.cors)({
|
|
1835
|
+
origin: (origin) => allowedOrigins().includes(normalizeOrigin(origin)) ? origin : null,
|
|
1836
|
+
allowMethods: ["GET", "POST", "OPTIONS", "DELETE"],
|
|
1837
|
+
allowHeaders: ["*"]
|
|
1838
|
+
}));
|
|
1243
1839
|
app.use("*", (0, import_logger.logger)());
|
|
1840
|
+
app.use("*", async (c, next) => {
|
|
1841
|
+
const path = new URL(c.req.url).pathname;
|
|
1842
|
+
const method = c.req.method.toUpperCase();
|
|
1843
|
+
if (method === "OPTIONS") return next();
|
|
1844
|
+
const cl = c.req.header("content-length");
|
|
1845
|
+
const maxBody = maxBodyBytes();
|
|
1846
|
+
if (cl && maxBody > 0) {
|
|
1847
|
+
const n = parseInt(cl, 10);
|
|
1848
|
+
if (Number.isFinite(n) && n > maxBody) {
|
|
1849
|
+
return c.json({ detail: `\u8BF7\u6C42\u4F53\u8D85\u8FC7\u4E0A\u9650 ${maxBody} \u5B57\u8282` }, 413);
|
|
1850
|
+
}
|
|
1851
|
+
}
|
|
1852
|
+
if (originCheckEnabled()) {
|
|
1853
|
+
const origin = c.req.header("origin") || "";
|
|
1854
|
+
if (origin && !originAllowed(origin, c.req.header("host") || "")) {
|
|
1855
|
+
console.warn(`[AgentGate] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path}`);
|
|
1856
|
+
return c.json({ detail: `\u8DE8\u6E90\u6765\u6E90\u672A\u88AB\u5141\u8BB8: ${origin}` }, 403);
|
|
1857
|
+
}
|
|
1858
|
+
}
|
|
1859
|
+
const headers = { authorization: c.req.header("authorization") };
|
|
1860
|
+
const cookie = (0, import_cookie.getCookie)(c, DASHBOARD_COOKIE) || "";
|
|
1861
|
+
const requireGlobal = path.startsWith("/dashboard") || path.startsWith("/ws/");
|
|
1862
|
+
const { ok, principal } = checkRequestAuth(headers, path, cookie, requireGlobal);
|
|
1863
|
+
if (!ok && !PUBLIC_PAGE_PATHS.includes(path)) {
|
|
1864
|
+
if (boundAgentOf(principal)) {
|
|
1865
|
+
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);
|
|
1866
|
+
}
|
|
1867
|
+
c.header("WWW-Authenticate", "Bearer");
|
|
1868
|
+
return c.json({ detail: "Unauthorized: invalid or missing Bearer token" }, 401);
|
|
1869
|
+
}
|
|
1870
|
+
c.set("principal", principal);
|
|
1871
|
+
if (rateLimiter.enabled) {
|
|
1872
|
+
const key = principal || `ip:${c.req.header("x-forwarded-for") || "unknown"}`;
|
|
1873
|
+
if (!rateLimiter.allow(key)) {
|
|
1874
|
+
c.header("Retry-After", "1");
|
|
1875
|
+
return c.json({ detail: "\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" }, 429);
|
|
1876
|
+
}
|
|
1877
|
+
}
|
|
1878
|
+
const ip = c.req.header("x-forwarded-for") || "unknown";
|
|
1879
|
+
const keys = [];
|
|
1880
|
+
const take = (key, limit) => {
|
|
1881
|
+
if (pools.tryAcquire(key, limit)) {
|
|
1882
|
+
keys.push(key);
|
|
1883
|
+
return true;
|
|
1884
|
+
}
|
|
1885
|
+
return false;
|
|
1886
|
+
};
|
|
1887
|
+
const busy = (detail, status = 503) => {
|
|
1888
|
+
c.header("Retry-After", "1");
|
|
1889
|
+
c.header("Connection", "close");
|
|
1890
|
+
return c.json({ detail }, status);
|
|
1891
|
+
};
|
|
1892
|
+
try {
|
|
1893
|
+
if (!principal && authEnabled()) {
|
|
1894
|
+
if (!take("unauth:total", unauthInflight())) {
|
|
1895
|
+
return busy("\u672A\u8BA4\u8BC1\u8BF7\u6C42\u5E76\u53D1\u8D85\u9650\uFF0C\u8BF7\u6301\u51ED\u8BC1\u8BBF\u95EE");
|
|
1896
|
+
}
|
|
1897
|
+
if (!take(`unauth:ip:${ip}`, unauthPerIp())) {
|
|
1898
|
+
return busy("\u8BE5\u6765\u6E90\u7684\u672A\u8BA4\u8BC1\u8BF7\u6C42\u5E76\u53D1\u8D85\u9650");
|
|
1899
|
+
}
|
|
1900
|
+
} else {
|
|
1901
|
+
const bound = boundAgentOf(principal);
|
|
1902
|
+
if (bound && !take(`agent:${bound}`, agentInflight())) {
|
|
1903
|
+
return busy(`agent '${bound}' \u7684\u5E76\u53D1\u8D85\u9650\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`, 429);
|
|
1904
|
+
}
|
|
1905
|
+
}
|
|
1906
|
+
const pool = poolOf(path);
|
|
1907
|
+
if (!take(`pool:${pool}`, poolLimit(pool))) {
|
|
1908
|
+
const qkey = principal || `ip:${ip}`;
|
|
1909
|
+
const [n, abusive] = noteQueueReject(qkey);
|
|
1910
|
+
if (abusive && queueAbuseAction() === "deny") {
|
|
1911
|
+
return busy("\u5E76\u53D1\u62D2\u7EDD\u8FC7\u4E8E\u9891\u7E41\uFF0C\u7591\u4F3C\u6076\u610F\u8BF7\u6C42", 429);
|
|
1912
|
+
}
|
|
1913
|
+
if (abusive) {
|
|
1914
|
+
console.warn(`[AgentGate] \u26A0\uFE0F \u7591\u4F3C\u6076\u610F\u5E76\u53D1\u5360\u7528: key=${qkey} \u7A97\u53E3\u5185\u88AB\u62D2 ${n} \u6B21`);
|
|
1915
|
+
}
|
|
1916
|
+
return busy("\u670D\u52A1\u7E41\u5FD9\uFF08\u5E76\u53D1\u5DF2\u6EE1\uFF09\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");
|
|
1917
|
+
}
|
|
1918
|
+
return await next();
|
|
1919
|
+
} finally {
|
|
1920
|
+
while (keys.length) pools.release(keys.pop());
|
|
1921
|
+
}
|
|
1922
|
+
});
|
|
1244
1923
|
app.get("/api/v1/health", healthRoute);
|
|
1245
1924
|
app.post("/api/v1/analyze", analyzeRoute);
|
|
1246
1925
|
app.get("/api/v1/sessions/:id/traces", sessionsRoute);
|
|
@@ -1254,7 +1933,26 @@ function createApp() {
|
|
|
1254
1933
|
return app;
|
|
1255
1934
|
}
|
|
1256
1935
|
async function dashboardRoute(c) {
|
|
1257
|
-
|
|
1936
|
+
if (authEnabled()) {
|
|
1937
|
+
const token = c.req.query("token") || "";
|
|
1938
|
+
if (token && isGlobalToken(token)) {
|
|
1939
|
+
(0, import_cookie.setCookie)(c, DASHBOARD_COOKIE, token, {
|
|
1940
|
+
httpOnly: true,
|
|
1941
|
+
sameSite: "Strict",
|
|
1942
|
+
path: "/"
|
|
1943
|
+
});
|
|
1944
|
+
c.header("Referrer-Policy", "no-referrer");
|
|
1945
|
+
return c.redirect("/dashboard/", 302);
|
|
1946
|
+
}
|
|
1947
|
+
const cookie = (0, import_cookie.getCookie)(c, DASHBOARD_COOKIE) || "";
|
|
1948
|
+
if (!isGlobalToken(cookie)) {
|
|
1949
|
+
if (token && checkToken(token) || cookie && checkToken(cookie)) {
|
|
1950
|
+
return c.html(AGENT_FORBIDDEN_HTML, 403, DASHBOARD_SECURITY_HEADERS);
|
|
1951
|
+
}
|
|
1952
|
+
return c.html(UNAUTHORIZED_HTML, 401, DASHBOARD_SECURITY_HEADERS);
|
|
1953
|
+
}
|
|
1954
|
+
}
|
|
1955
|
+
const { readFileSync: readFileSync3, existsSync: existsSync3 } = await import("fs");
|
|
1258
1956
|
const { resolve, dirname: dirname3 } = await import("path");
|
|
1259
1957
|
const { fileURLToPath } = await import("url");
|
|
1260
1958
|
const __dirname = dirname3(fileURLToPath(importMetaUrl));
|
|
@@ -1264,8 +1962,8 @@ async function dashboardRoute(c) {
|
|
|
1264
1962
|
resolve(__dirname, "../src/v1/dashboard.html")
|
|
1265
1963
|
];
|
|
1266
1964
|
const htmlPath = paths.find((p) => existsSync3(p)) || paths[0];
|
|
1267
|
-
const html =
|
|
1268
|
-
return c.html(html);
|
|
1965
|
+
const html = readFileSync3(htmlPath, "utf-8");
|
|
1966
|
+
return c.html(html, 200, DASHBOARD_SECURITY_HEADERS);
|
|
1269
1967
|
}
|
|
1270
1968
|
// Annotate the CommonJS export names for ESM import in node:
|
|
1271
1969
|
0 && (module.exports = {
|