@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/dashboard.html
CHANGED
|
@@ -52,6 +52,15 @@
|
|
|
52
52
|
var _totalRecords = 0;
|
|
53
53
|
|
|
54
54
|
function setText(id, v){ var el=document.getElementById(id); if(el)el.textContent=v; }
|
|
55
|
+
// HTML 转义。dashboard 展示的 agent_type / session_id / command / reason /
|
|
56
|
+
// hostname 全部来自调用方上报,属不可信内容。引号必须一并转义 —— 它们会被
|
|
57
|
+
// 拼进属性上下文(title="..."),只转 &<> 时可被闭合注入事件处理器。
|
|
58
|
+
// 与 Python 版 dashboard.py 的 escapeHtml 保持同一套字符集。
|
|
59
|
+
function esc(s){
|
|
60
|
+
return String(s == null ? '' : s)
|
|
61
|
+
.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>')
|
|
62
|
+
.replace(/"/g,'"').replace(/'/g,''');
|
|
63
|
+
}
|
|
55
64
|
function updateClock(){ setText('clock', new Date().toLocaleString('zh-CN')); }
|
|
56
65
|
updateClock(); setInterval(updateClock, 1000);
|
|
57
66
|
// Fetch versions from health API
|
|
@@ -148,7 +157,7 @@
|
|
|
148
157
|
if(rb)rb.innerHTML='<div style="width:'+lv.critical/tr*100+'%;background:var(--red)"></div><div style="width:'+lv.high/tr*100+'%;background:var(--orange)"></div><div style="width:'+lv.medium/tr*100+'%;background:var(--yellow)"></div><div style="width:'+lv.low/tr*100+'%;background:var(--muted)"></div>';
|
|
149
158
|
if(rl)rl.innerHTML='<span><span class="risk-dot" style="background:var(--red)"></span>Critical '+lv.critical+'</span><span><span class="risk-dot" style="background:var(--orange)"></span>High '+lv.high+'</span><span><span class="risk-dot" style="background:var(--yellow)"></span>Medium '+lv.medium+'</span><span><span class="risk-dot" style="background:var(--muted)"></span>Low '+lv.low+'</span>';
|
|
150
159
|
var tb=document.getElementById('recent-table');
|
|
151
|
-
if(tb)tb.innerHTML=arr.map(function(x){var t=x.called_at?new Date(x.called_at.replace(' ','T')+'Z'):null;return'<tr><td>'+(t?t.toLocaleTimeString('zh-CN',{hour:'2-digit',minute:'2-digit',second:'2-digit'}):'-')+'</td><td>'+(x.agent_type||'-')+'</td><td>'+(x.session_id||'-')+'</td><td><code>'+(x.command||x.action_detail||'-')+'</code></td><td><span class="badge '+(x.decision==='Allow'?'badge-allow':'badge-deny')+'">'+x.decision+'</span></td><td style="color:'+(x.risk_level==='critical'?'var(--red)':x.risk_level==='high'?'var(--orange)':x.risk_level==='medium'?'var(--yellow)':'var(--muted)')+'">'+(x.risk_level||'-')+'</td><td>'+Math.round(x.analysis_duration_ms||0)+'ms</td><td>'+(x.reason||'-')+'</td></tr>'}).join('');
|
|
160
|
+
if(tb)tb.innerHTML=arr.map(function(x){var t=x.called_at?new Date(x.called_at.replace(' ','T')+'Z'):null;return'<tr><td>'+(t?t.toLocaleTimeString('zh-CN',{hour:'2-digit',minute:'2-digit',second:'2-digit'}):'-')+'</td><td>'+esc(x.agent_type||'-')+'</td><td>'+esc(x.session_id||'-')+'</td><td><code>'+esc(x.command||x.action_detail||'-')+'</code></td><td><span class="badge '+(x.decision==='Allow'?'badge-allow':'badge-deny')+'">'+esc(x.decision)+'</span></td><td style="color:'+(x.risk_level==='critical'?'var(--red)':x.risk_level==='high'?'var(--orange)':x.risk_level==='medium'?'var(--yellow)':'var(--muted)')+'">'+esc(x.risk_level||'-')+'</td><td>'+Math.round(x.analysis_duration_ms||0)+'ms</td><td>'+esc(x.reason||'-')+'</td></tr>'}).join('');
|
|
152
161
|
// Pagination
|
|
153
162
|
var totalPages = Math.max(1, Math.ceil(_totalRecords / _pageSize));
|
|
154
163
|
var pg = document.getElementById('ag-pagination');
|
|
@@ -160,7 +169,7 @@
|
|
|
160
169
|
pg.appendChild(btnP);pg.appendChild(lbl);pg.appendChild(btnN);
|
|
161
170
|
}
|
|
162
171
|
var at=document.getElementById('agents-table');
|
|
163
|
-
if(at)at.innerHTML=agents.map(function(a){return'<tr><td>'+a.agent_type+'</td><td>'+a.hostname+'</td><td>'+a.session_count+'</td><td>'+a.call_count+'</td></tr>'}).join('');
|
|
172
|
+
if(at)at.innerHTML=agents.map(function(a){return'<tr><td>'+esc(a.agent_type)+'</td><td>'+esc(a.hostname)+'</td><td>'+esc(a.session_count)+'</td><td>'+esc(a.call_count)+'</td></tr>'}).join('');
|
|
164
173
|
var tt=document.getElementById('timeline-table');
|
|
165
174
|
if(tt)tt.innerHTML=tl.map(function(t){return'<tr><td>'+t.time+'</td><td style="color:var(--green)">'+t.allow+'</td><td style="color:var(--red)">'+t.deny+'</td></tr>'}).join('');
|
|
166
175
|
}catch(e){console.error(e)}
|
|
@@ -63,17 +63,22 @@ interface StorageAdapter {
|
|
|
63
63
|
getActionHistory(sessionId: string, limit?: number): ActionEntry[];
|
|
64
64
|
queryToolCalls(params: {
|
|
65
65
|
sessionId?: string;
|
|
66
|
+
/** 逐 agent token 的隔离依据(agent_id 是 `<agent_type>:<hostname>`)。 */
|
|
67
|
+
agentType?: string;
|
|
66
68
|
decision?: string;
|
|
67
69
|
limit?: number;
|
|
68
70
|
offset?: number;
|
|
69
71
|
}): ToolCallRich[];
|
|
70
72
|
countToolCalls(params: {
|
|
71
73
|
decision?: string;
|
|
74
|
+
agentType?: string;
|
|
72
75
|
}): number;
|
|
73
76
|
getStorageStats(): StorageStats;
|
|
74
77
|
clearToolCalls(): number;
|
|
75
|
-
getAgentsList(): AgentSummary[];
|
|
78
|
+
getAgentsList(agentType?: string): AgentSummary[];
|
|
76
79
|
getTimeline(limit?: number): TimelineEntry[];
|
|
80
|
+
/** 会话归属哪个 agent_type(跨 agent 读隔离校验用)。不存在返回 undefined。 */
|
|
81
|
+
getSessionAgentType(sessionId: string): string | undefined;
|
|
77
82
|
close(): void;
|
|
78
83
|
}
|
|
79
84
|
|
|
@@ -37,6 +37,26 @@ var init_cjs_shims = __esm({
|
|
|
37
37
|
}
|
|
38
38
|
});
|
|
39
39
|
|
|
40
|
+
// src/shared/security.ts
|
|
41
|
+
function env(name, dflt = "") {
|
|
42
|
+
return (process.env[name] ?? dflt).trim();
|
|
43
|
+
}
|
|
44
|
+
function hardenFilesEnabled() {
|
|
45
|
+
return TRUTHY.includes(env("AGENT_GATE_HARDEN_FILES", "1").toLowerCase());
|
|
46
|
+
}
|
|
47
|
+
var import_node_crypto, import_node_fs, import_node_os, import_node_path, TRUTHY;
|
|
48
|
+
var init_security = __esm({
|
|
49
|
+
"src/shared/security.ts"() {
|
|
50
|
+
"use strict";
|
|
51
|
+
init_cjs_shims();
|
|
52
|
+
import_node_crypto = require("crypto");
|
|
53
|
+
import_node_fs = require("fs");
|
|
54
|
+
import_node_os = require("os");
|
|
55
|
+
import_node_path = require("path");
|
|
56
|
+
TRUTHY = ["1", "true", "yes", "on"];
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
|
|
40
60
|
// src/shared/storage/json-storage.ts
|
|
41
61
|
var json_storage_exports = {};
|
|
42
62
|
__export(json_storage_exports, {
|
|
@@ -57,6 +77,7 @@ var init_json_storage = __esm({
|
|
|
57
77
|
init_cjs_shims();
|
|
58
78
|
import_fs = require("fs");
|
|
59
79
|
import_path = require("path");
|
|
80
|
+
init_security();
|
|
60
81
|
JsonStorage = class {
|
|
61
82
|
dataDir;
|
|
62
83
|
agentsPath;
|
|
@@ -72,10 +93,39 @@ var init_json_storage = __esm({
|
|
|
72
93
|
this.agentsPath = (0, import_path.join)(this.dataDir, "agents.json");
|
|
73
94
|
this.sessionsPath = (0, import_path.join)(this.dataDir, "sessions.json");
|
|
74
95
|
this.toolCallsDir = (0, import_path.join)(this.dataDir, "tool_calls");
|
|
75
|
-
if (!(0, import_fs.existsSync)(this.dataDir)) (0, import_fs.mkdirSync)(this.dataDir, { recursive: true });
|
|
76
|
-
if (!(0, import_fs.existsSync)(this.toolCallsDir)) (0, import_fs.mkdirSync)(this.toolCallsDir, { recursive: true });
|
|
96
|
+
if (!(0, import_fs.existsSync)(this.dataDir)) (0, import_fs.mkdirSync)(this.dataDir, { recursive: true, mode: 448 });
|
|
97
|
+
if (!(0, import_fs.existsSync)(this.toolCallsDir)) (0, import_fs.mkdirSync)(this.toolCallsDir, { recursive: true, mode: 448 });
|
|
98
|
+
this.hardenStoragePermissions();
|
|
77
99
|
this.nextId = this.recoverNextId();
|
|
78
100
|
}
|
|
101
|
+
/** 把存储目录收紧到 0700、已有 JSON 文件收紧到 0600。
|
|
102
|
+
* 新建文件由 `writeJsonFile` 的 mode 保证;这里处理**存量**文件
|
|
103
|
+
* (旧版本按 umask 创建的 0644)以及 mkdirSync 对已存在目录不生效的问题。 */
|
|
104
|
+
hardenStoragePermissions() {
|
|
105
|
+
if (!hardenFilesEnabled()) return;
|
|
106
|
+
const uid = process.getuid?.();
|
|
107
|
+
const tighten = (p, mode) => {
|
|
108
|
+
try {
|
|
109
|
+
const st = (0, import_fs.statSync)(p);
|
|
110
|
+
if (st.isSymbolicLink()) return;
|
|
111
|
+
if (uid !== void 0 && st.uid !== uid) return;
|
|
112
|
+
if ((st.mode & 511) !== mode) (0, import_fs.chmodSync)(p, mode);
|
|
113
|
+
} catch {
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
tighten(this.dataDir, 448);
|
|
117
|
+
tighten(this.toolCallsDir, 448);
|
|
118
|
+
tighten(this.agentsPath, 384);
|
|
119
|
+
tighten(this.sessionsPath, 384);
|
|
120
|
+
try {
|
|
121
|
+
for (const f of (0, import_fs.readdirSync)(this.toolCallsDir)) {
|
|
122
|
+
if (f.endsWith(".json") || f.endsWith(".tmp")) {
|
|
123
|
+
tighten((0, import_path.join)(this.toolCallsDir, f), 384);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
} catch {
|
|
127
|
+
}
|
|
128
|
+
}
|
|
79
129
|
/** 扫描所有 tool_calls 文件,找到最大 id + 1 */
|
|
80
130
|
recoverNextId() {
|
|
81
131
|
let maxId = 0;
|
|
@@ -99,12 +149,12 @@ var init_json_storage = __esm({
|
|
|
99
149
|
return fallback;
|
|
100
150
|
}
|
|
101
151
|
}
|
|
102
|
-
/** 原子写入:先写 .tmp 再 rename */
|
|
152
|
+
/** 原子写入:先写 .tmp 再 rename(rename 保留 tmp 的 0600 权限) */
|
|
103
153
|
writeJsonFile(path, data) {
|
|
104
154
|
const dir = (0, import_path.dirname)(path);
|
|
105
|
-
if (!(0, import_fs.existsSync)(dir)) (0, import_fs.mkdirSync)(dir, { recursive: true });
|
|
155
|
+
if (!(0, import_fs.existsSync)(dir)) (0, import_fs.mkdirSync)(dir, { recursive: true, mode: 448 });
|
|
106
156
|
const tmp = path + ".tmp";
|
|
107
|
-
(0, import_fs.writeFileSync)(tmp, JSON.stringify(data, null, 2), "utf-8");
|
|
157
|
+
(0, import_fs.writeFileSync)(tmp, JSON.stringify(data, null, 2), { encoding: "utf-8", mode: 384 });
|
|
108
158
|
(0, import_fs.renameSync)(tmp, path);
|
|
109
159
|
}
|
|
110
160
|
loadAgents() {
|
|
@@ -218,6 +268,9 @@ var init_json_storage = __esm({
|
|
|
218
268
|
} catch {
|
|
219
269
|
}
|
|
220
270
|
}
|
|
271
|
+
if (params.agentType) {
|
|
272
|
+
allRecords = allRecords.filter((r) => r.agent_type === params.agentType);
|
|
273
|
+
}
|
|
221
274
|
if (params.decision) {
|
|
222
275
|
allRecords = allRecords.filter((r) => r.decision === params.decision);
|
|
223
276
|
}
|
|
@@ -228,6 +281,7 @@ var init_json_storage = __esm({
|
|
|
228
281
|
}
|
|
229
282
|
countToolCalls(params) {
|
|
230
283
|
const sessions = this.loadSessions();
|
|
284
|
+
const agents = this.loadAgents();
|
|
231
285
|
let allRecords = [];
|
|
232
286
|
try {
|
|
233
287
|
const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
|
|
@@ -237,6 +291,12 @@ var init_json_storage = __esm({
|
|
|
237
291
|
}
|
|
238
292
|
} catch {
|
|
239
293
|
}
|
|
294
|
+
if (params.agentType) {
|
|
295
|
+
const allowed = new Set(
|
|
296
|
+
[...sessions.values()].filter((s) => (agents.get(s.agent_id)?.agent_type || "") === params.agentType).map((s) => s.id)
|
|
297
|
+
);
|
|
298
|
+
allRecords = allRecords.filter((r) => allowed.has(r.session_id));
|
|
299
|
+
}
|
|
240
300
|
if (params.decision) {
|
|
241
301
|
allRecords = allRecords.filter((r) => r.decision === params.decision);
|
|
242
302
|
}
|
|
@@ -282,11 +342,12 @@ var init_json_storage = __esm({
|
|
|
282
342
|
hostname: agent?.hostname || ""
|
|
283
343
|
};
|
|
284
344
|
}
|
|
285
|
-
getAgentsList() {
|
|
345
|
+
getAgentsList(agentType) {
|
|
286
346
|
const agents = this.loadAgents();
|
|
287
347
|
const sessions = this.loadSessions();
|
|
288
348
|
const result = [];
|
|
289
349
|
for (const agent of agents.values()) {
|
|
350
|
+
if (agentType && agent.agent_type !== agentType) continue;
|
|
290
351
|
let sessionCount = 0;
|
|
291
352
|
let callCount = 0;
|
|
292
353
|
for (const session of sessions.values()) {
|
|
@@ -307,6 +368,11 @@ var init_json_storage = __esm({
|
|
|
307
368
|
result.sort((a, b) => b.call_count - a.call_count);
|
|
308
369
|
return result.slice(0, 20);
|
|
309
370
|
}
|
|
371
|
+
getSessionAgentType(sessionId) {
|
|
372
|
+
const session = this.loadSessions().get(sessionId);
|
|
373
|
+
if (!session) return void 0;
|
|
374
|
+
return this.loadAgents().get(session.agent_id)?.agent_type;
|
|
375
|
+
}
|
|
310
376
|
getTimeline(limit = 100) {
|
|
311
377
|
const buckets = /* @__PURE__ */ new Map();
|
|
312
378
|
try {
|
|
@@ -490,6 +556,10 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
490
556
|
conditions.push("tc.session_id = ?");
|
|
491
557
|
values.push(params.sessionId);
|
|
492
558
|
}
|
|
559
|
+
if (params.agentType) {
|
|
560
|
+
conditions.push("a.agent_type = ?");
|
|
561
|
+
values.push(params.agentType);
|
|
562
|
+
}
|
|
493
563
|
if (params.decision) {
|
|
494
564
|
conditions.push("tc.decision = ?");
|
|
495
565
|
values.push(params.decision);
|
|
@@ -512,9 +582,16 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
512
582
|
conditions.push("tc.decision = ?");
|
|
513
583
|
values.push(params.decision);
|
|
514
584
|
}
|
|
585
|
+
if (params.agentType) {
|
|
586
|
+
conditions.push("a.agent_type = ?");
|
|
587
|
+
values.push(params.agentType);
|
|
588
|
+
}
|
|
515
589
|
const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
516
590
|
const row = this.db.prepare(
|
|
517
|
-
`SELECT COUNT(*) as total FROM tool_calls tc
|
|
591
|
+
`SELECT COUNT(*) as total FROM tool_calls tc
|
|
592
|
+
LEFT JOIN sessions s ON tc.session_id = s.id
|
|
593
|
+
LEFT JOIN agents a ON s.agent_id = a.id
|
|
594
|
+
${where}`
|
|
518
595
|
).get(...values);
|
|
519
596
|
return row?.total ?? 0;
|
|
520
597
|
}
|
|
@@ -522,11 +599,11 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
522
599
|
const row = this.db.prepare("SELECT COUNT(*) as total FROM tool_calls").get();
|
|
523
600
|
let dbBytes = 0;
|
|
524
601
|
try {
|
|
525
|
-
const { statSync:
|
|
526
|
-
dbBytes =
|
|
602
|
+
const { statSync: statSync3, existsSync: existsSync3 } = require("fs");
|
|
603
|
+
dbBytes = statSync3(this.dbPath).size;
|
|
527
604
|
for (const suffix of ["-wal", "-shm"]) {
|
|
528
605
|
const p = this.dbPath + suffix;
|
|
529
|
-
if (existsSync3(p)) dbBytes +=
|
|
606
|
+
if (existsSync3(p)) dbBytes += statSync3(p).size;
|
|
530
607
|
}
|
|
531
608
|
} catch {
|
|
532
609
|
}
|
|
@@ -540,7 +617,8 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
540
617
|
})();
|
|
541
618
|
return result;
|
|
542
619
|
}
|
|
543
|
-
getAgentsList() {
|
|
620
|
+
getAgentsList(agentType) {
|
|
621
|
+
const where = agentType ? "WHERE a.agent_type = ?" : "";
|
|
544
622
|
return this.db.prepare(`
|
|
545
623
|
SELECT a.agent_type, a.hostname, a.agent_version as version,
|
|
546
624
|
COUNT(DISTINCT s.id) as session_count,
|
|
@@ -548,10 +626,19 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, calle
|
|
|
548
626
|
FROM agents a
|
|
549
627
|
LEFT JOIN sessions s ON s.agent_id = a.id
|
|
550
628
|
LEFT JOIN tool_calls tc ON tc.session_id = s.id
|
|
629
|
+
${where}
|
|
551
630
|
GROUP BY a.id
|
|
552
631
|
ORDER BY call_count DESC
|
|
553
632
|
LIMIT 20
|
|
554
|
-
`).all();
|
|
633
|
+
`).all(...agentType ? [agentType] : []);
|
|
634
|
+
}
|
|
635
|
+
getSessionAgentType(sessionId) {
|
|
636
|
+
const row = this.db.prepare(
|
|
637
|
+
`SELECT a.agent_type as agent_type
|
|
638
|
+
FROM sessions s JOIN agents a ON s.agent_id = a.id
|
|
639
|
+
WHERE s.id = ?`
|
|
640
|
+
).get(sessionId);
|
|
641
|
+
return row?.agent_type;
|
|
555
642
|
}
|
|
556
643
|
getTimeline(limit = 100) {
|
|
557
644
|
const rows = this.db.prepare(`
|
|
@@ -624,14 +711,14 @@ function getDb(dbPath) {
|
|
|
624
711
|
if (rawDb) return rawDb;
|
|
625
712
|
try {
|
|
626
713
|
const Database = require("better-sqlite3");
|
|
627
|
-
const { existsSync: existsSync3, mkdirSync:
|
|
628
|
-
const { join:
|
|
714
|
+
const { existsSync: existsSync3, mkdirSync: mkdirSync4 } = require("fs");
|
|
715
|
+
const { join: join4, dirname: dirname3 } = require("path");
|
|
629
716
|
const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
|
|
630
|
-
const xdgData = process.env.XDG_DATA_HOME ||
|
|
631
|
-
const defaultPath =
|
|
717
|
+
const xdgData = process.env.XDG_DATA_HOME || join4(home, ".local", "share");
|
|
718
|
+
const defaultPath = join4(xdgData, "agent_gate", "agent_gate_ts.db");
|
|
632
719
|
const path = dbPath || defaultPath;
|
|
633
720
|
const dir = dirname3(path);
|
|
634
|
-
if (!existsSync3(dir))
|
|
721
|
+
if (!existsSync3(dir)) mkdirSync4(dir, { recursive: true });
|
|
635
722
|
rawDb = new Database(path);
|
|
636
723
|
rawDb.pragma("journal_mode = WAL");
|
|
637
724
|
return rawDb;
|