@kenhkl/agent-gate 0.7.3 → 0.7.5

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/README.md CHANGED
@@ -204,6 +204,12 @@ curl http://127.0.0.1:9100/api/v1/health
204
204
 
205
205
  `--moss-url` 也支持通过环境变量 `MOSS_URL` 设置(CLI 参数优先)。
206
206
 
207
+ V3 代理模式(`proxy` / `start` / `gateway`)用 `--security-url` 指定 AgentMoss 地址,解析顺序为:
208
+ `--security-url` > 环境变量 `AGENT_MOSS_URL` > 环境变量 `MOSS_URL` > 默认 `http://127.0.0.1:9090`。
209
+
210
+ `--deny-action block` 时,MITM 代理会在 `onResponse` 阶段接管上游响应:AgentMoss 判 Deny 直接回 **403**(真拦截,
211
+ 响应体为 `{"error":"blocked_by_agentgate",...}`);`inform`(默认)保持响应字节级透传,仅记录。
212
+
207
213
  ### 2.4 数据清理
208
214
 
209
215
  ```bash
package/dist/v1/cli.js CHANGED
@@ -814,7 +814,7 @@ var init_version = __esm({
814
814
  "src/version.ts"() {
815
815
  "use strict";
816
816
  init_cjs_shims();
817
- _version = true ? "0.7.3" : (() => {
817
+ _version = true ? "0.7.5" : (() => {
818
818
  try {
819
819
  const require2 = createRequire(importMetaUrl);
820
820
  const pkg = require2("../package.json");
package/dist/v1/server.js CHANGED
@@ -827,7 +827,7 @@ var import_zod = require("zod");
827
827
 
828
828
  // src/version.ts
829
829
  init_cjs_shims();
830
- var _version = true ? "0.7.3" : (() => {
830
+ var _version = true ? "0.7.5" : (() => {
831
831
  try {
832
832
  const require2 = createRequire(importMetaUrl);
833
833
  const pkg = require2("../package.json");
package/dist/v3/cli.js CHANGED
@@ -50,7 +50,7 @@ var init_version = __esm({
50
50
  "src/version.ts"() {
51
51
  "use strict";
52
52
  init_cjs_shims();
53
- _version = true ? "0.7.3" : (() => {
53
+ _version = true ? "0.7.5" : (() => {
54
54
  try {
55
55
  const require2 = createRequire(importMetaUrl);
56
56
  const pkg = require2("../package.json");
@@ -27497,22 +27497,36 @@ var init_interceptor = __esm({
27497
27497
  const meta = parser.parseRequest(url, headers, body);
27498
27498
  this._requestCache.set(flowId, { meta, headers, url, parser });
27499
27499
  }
27500
- /** Process an incoming response (called after receiving response).
27501
- * Returns the list of captured proxy events.
27502
- * Note: In MITM proxy mode, the response has already been forwarded,
27503
- * so blocking is not possible. Deny decisions are only logged.
27504
- * Blocking works in Gateway mode (see gateway/server.ts).
27500
+ /** Process an incoming response in observation mode.
27501
+ * Returns the captured proxy events. Deny decisions are only logged
27502
+ * (fire-and-forget); blocking is handled by decideResponse() (block mode).
27505
27503
  */
27506
27504
  async onResponse(flowId, respHeaders, respBody) {
27505
+ const { events } = await this._processResponse(flowId, respHeaders, respBody, false);
27506
+ return events;
27507
+ }
27508
+ /** Process an incoming response and synchronously await the deny decision.
27509
+ * Used by the MITM proxy in block mode: the caller replaces the upstream
27510
+ * response with a 403 when `deny.deny` is true.
27511
+ * Note: in Gateway mode the same decision is produced by gateway/server.ts.
27512
+ */
27513
+ async decideResponse(flowId, respHeaders, respBody) {
27514
+ return this._processResponse(flowId, respHeaders, respBody, true);
27515
+ }
27516
+ /** Shared response processing pipeline.
27517
+ * @param awaitDecision when true, await AgentMoss instead of fire-and-forget.
27518
+ */
27519
+ async _processResponse(flowId, respHeaders, respBody, awaitDecision) {
27507
27520
  const cached = this._requestCache.get(flowId);
27508
- if (!cached) return [];
27521
+ if (!cached) return { events: [], deny: { deny: false } };
27509
27522
  this._requestCache.delete(flowId);
27510
27523
  const { parser, meta, headers, url } = cached;
27511
27524
  const toolCalls = parser.parseResponse(url, respHeaders, respBody, meta);
27512
- if (toolCalls.length === 0) return [];
27525
+ if (toolCalls.length === 0) return { events: [], deny: { deny: false } };
27513
27526
  const agentType = parser.detectAgentType(headers, meta);
27514
27527
  const sessionId = deriveSessionId(meta, headers);
27515
27528
  const events = [];
27529
+ let deny = { deny: false };
27516
27530
  for (const tc of toolCalls) {
27517
27531
  let event = normalizeProxyEvent(tc, null, meta, sessionId, agentType);
27518
27532
  const session = this._sessionAgg.processProxyEvent(event);
@@ -27524,8 +27538,9 @@ var init_interceptor = __esm({
27524
27538
  }
27525
27539
  for (const match of matches) {
27526
27540
  if (this._config.onTriggerMatch) this._config.onTriggerMatch(match);
27527
- if (match.rule.localBlock && this._config.onBlock) {
27528
- this._config.onBlock(session.id, match.rule.name);
27541
+ if (match.rule.localBlock) {
27542
+ if (this._config.onBlock) this._config.onBlock(session.id, match.rule.name);
27543
+ if (!deny.deny) deny = { deny: true, tool: tc.name, reason: `local-block:${match.rule.name}` };
27529
27544
  }
27530
27545
  }
27531
27546
  if (this._coordinator) {
@@ -27533,23 +27548,30 @@ var init_interceptor = __esm({
27533
27548
  console.error("[PhaseCoordinator] L1 event failed:", err);
27534
27549
  return "Allow";
27535
27550
  });
27536
- decision.then((d) => {
27537
- if (d === "Deny") {
27538
- console.warn(
27539
- `[AgentGate] PhaseCoordinator DENY (MITM: cannot block): tool=${tc.name} session=${sessionId.slice(0, 8)}`
27540
- );
27541
- } else if (d === null) {
27542
- console.info(
27543
- `[AgentGate] PhaseCoordinator: waiting for L2 (tool=${tc.name} session=${sessionId.slice(0, 8)})`
27544
- );
27551
+ if (awaitDecision) {
27552
+ const d = await decision;
27553
+ if (d === "Deny" && !deny.deny) {
27554
+ deny = { deny: true, tool: tc.name, reason: "agentmoss-deny" };
27545
27555
  }
27546
- });
27556
+ } else {
27557
+ decision.then((d) => {
27558
+ if (d === "Deny") {
27559
+ console.warn(
27560
+ `[AgentGate] PhaseCoordinator DENY (MITM: cannot block): tool=${tc.name} session=${sessionId.slice(0, 8)}`
27561
+ );
27562
+ } else if (d === null) {
27563
+ console.info(
27564
+ `[AgentGate] PhaseCoordinator: waiting for L2 (tool=${tc.name} session=${sessionId.slice(0, 8)})`
27565
+ );
27566
+ }
27567
+ });
27568
+ }
27547
27569
  }
27548
27570
  }
27549
27571
  console.log(
27550
27572
  `[AgentGate] Intercepted ${events.length} tool_call(s) from ${url} (session=${sessionId.slice(0, 8)}, agent=${agentType})`
27551
27573
  );
27552
- return events;
27574
+ return { events, deny };
27553
27575
  }
27554
27576
  };
27555
27577
  }
@@ -27811,7 +27833,7 @@ var server_exports2 = {};
27811
27833
  __export(server_exports2, {
27812
27834
  ProxyServer: () => ProxyServer
27813
27835
  });
27814
- var import_node_http, import_node_url, import_node_path, import_node_fs2, import_http_mitm_proxy, DASHBOARD_HTML, ProxyServer;
27836
+ var import_node_http, import_node_url, import_node_path, import_node_fs2, import_node_stream, import_http_mitm_proxy, DASHBOARD_HTML, ProxyServer;
27815
27837
  var init_server2 = __esm({
27816
27838
  "src/v3/proxy/server.ts"() {
27817
27839
  "use strict";
@@ -27820,6 +27842,7 @@ var init_server2 = __esm({
27820
27842
  import_node_url = require("url");
27821
27843
  import_node_path = __toESM(require("path"));
27822
27844
  import_node_fs2 = __toESM(require("fs"));
27845
+ import_node_stream = require("stream");
27823
27846
  import_http_mitm_proxy = __toESM(require_dist());
27824
27847
  init_interceptor();
27825
27848
  init_session();
@@ -27921,6 +27944,12 @@ load();setInterval(load,5000);
27921
27944
  reqChunks.push(chunk);
27922
27945
  return cb(null, chunk);
27923
27946
  });
27947
+ if (this._options.blockDeny) {
27948
+ ctx.onResponse((innerCtx, cb) => {
27949
+ this._handleBlockingResponse(innerCtx, flowId, fullUrl, method, reqChunks, cb);
27950
+ });
27951
+ return callback(null);
27952
+ }
27924
27953
  const respChunks = [];
27925
27954
  ctx.onResponseData((_ctx, chunk, cb) => {
27926
27955
  respChunks.push(chunk);
@@ -27940,10 +27969,9 @@ load();setInterval(load,5000);
27940
27969
  if (v !== void 0) respHeaders[k] = Array.isArray(v) ? v[0] : String(v);
27941
27970
  }
27942
27971
  }
27943
- const result = this._interceptor.onResponse(flowId, respHeaders, respBody);
27944
- if (typeof result === "string") {
27945
- console.warn(`[AgentGate] BLOCKED tool=${result}`);
27946
- }
27972
+ this._interceptor.onResponse(flowId, respHeaders, respBody).catch((err) => {
27973
+ console.error("[AgentGate] onResponse failed:", err);
27974
+ });
27947
27975
  return cb(null);
27948
27976
  });
27949
27977
  return callback(null);
@@ -27992,6 +28020,79 @@ load();setInterval(load,5000);
27992
28020
  get triggerEngine() {
27993
28021
  return this._triggerEngine;
27994
28022
  }
28023
+ // ===== Block mode: response takeover =====
28024
+ /** Called in block mode from ctx.onResponse (upstream paused, not yet flushed).
28025
+ * Reads the full upstream body, awaits the deny decision, then replaces
28026
+ * ctx.serverToProxyResponse — with a 403 JSON on deny, or the original
28027
+ * response otherwise. http-mitm-proxy reads ctx.serverToProxyResponse only
28028
+ * after this callback returns (see node_modules/http-mitm-proxy/lib/proxy.ts
28029
+ * proxyToServerRequestComplete), so the replacement is what reaches the client.
28030
+ */
28031
+ _handleBlockingResponse(ctx, flowId, fullUrl, method, reqChunks, cb) {
28032
+ const resp = ctx.serverToProxyResponse;
28033
+ let settled = false;
28034
+ const finish = (err) => {
28035
+ if (settled) return;
28036
+ settled = true;
28037
+ cb(err ?? null);
28038
+ };
28039
+ if (!resp) {
28040
+ console.warn("[AgentGate] block mode: no upstream response to inspect; passing through");
28041
+ finish(null);
28042
+ return;
28043
+ }
28044
+ const chunks = [];
28045
+ resp.on("data", (c) => chunks.push(Buffer.isBuffer(c) ? c : Buffer.from(c)));
28046
+ resp.on("error", () => finish(null));
28047
+ resp.on("end", () => {
28048
+ const respBody = Buffer.concat(chunks);
28049
+ const originalStatus = resp.statusCode || 200;
28050
+ const respHeaders = {};
28051
+ for (const [k, v] of Object.entries(resp.headers)) {
28052
+ if (v !== void 0) respHeaders[k] = Array.isArray(v) ? v.join(", ") : String(v);
28053
+ }
28054
+ const headers = {};
28055
+ for (const [k, v] of Object.entries(ctx.clientToProxyRequest.headers)) {
28056
+ if (v !== void 0) headers[k] = Array.isArray(v) ? v[0] : String(v);
28057
+ }
28058
+ this._interceptor.onRequest(flowId, fullUrl, method, headers, Buffer.concat(reqChunks));
28059
+ this._interceptor.decideResponse(flowId, respHeaders, respBody).then(({ deny }) => {
28060
+ if (deny.deny) {
28061
+ console.warn(
28062
+ `[AgentGate] BLOCKED (MITM 403): tool=${deny.tool} reason=${deny.reason} url=${fullUrl}`
28063
+ );
28064
+ const body = Buffer.from(
28065
+ JSON.stringify({
28066
+ error: "blocked_by_agentgate",
28067
+ tool: deny.tool,
28068
+ message: `Blocked by AgentGate\uFF08${deny.reason || "denied"}\uFF09`
28069
+ })
28070
+ );
28071
+ this._replaceResponse(ctx, 403, { "content-type": "application/json; charset=utf-8" }, body);
28072
+ } else {
28073
+ this._replaceResponse(ctx, originalStatus, respHeaders, respBody);
28074
+ }
28075
+ finish(null);
28076
+ }).catch((err) => {
28077
+ console.error("[AgentGate] decideResponse failed (fail-open):", err);
28078
+ this._replaceResponse(ctx, originalStatus, respHeaders, respBody);
28079
+ finish(null);
28080
+ });
28081
+ });
28082
+ resp.resume();
28083
+ }
28084
+ /** Replace ctx.serverToProxyResponse with a synthesized stream carrying the
28085
+ * given status/headers/body (the original stream has already been consumed). */
28086
+ _replaceResponse(ctx, statusCode, headers, body) {
28087
+ const ps = new import_node_stream.PassThrough();
28088
+ const h = { ...headers };
28089
+ delete h["transfer-encoding"];
28090
+ h["content-length"] = String(body.length);
28091
+ ps.statusCode = statusCode;
28092
+ ps.headers = h;
28093
+ ctx.serverToProxyResponse = ps;
28094
+ ps.end(body);
28095
+ }
27995
28096
  // ===== Dashboard (separate HTTP server) =====
27996
28097
  _startDashboard() {
27997
28098
  const dashPort = this._options.port + 1;
@@ -33121,6 +33222,7 @@ Start options:
33121
33222
  Log level (default: info)
33122
33223
  --deny-action <inform|block>
33123
33224
  AgentMoss Deny handling: inform=log only (default), block=actually block
33225
+ --security-url <url> AgentMoss service URL (default: $AGENT_MOSS_URL / $MOSS_URL / 9090)
33124
33226
 
33125
33227
  Server options:
33126
33228
  --host <host> Listen host (default: 127.0.0.1)
@@ -33137,6 +33239,7 @@ Proxy options:
33137
33239
  --intercept <hosts> Comma-separated hosts to intercept (default: api.openai.com,api.anthropic.com)
33138
33240
  --level <1|2> Interception level: 1=L1 (proxy only), 2=L1+L2 (proxy+PTY). Default from env or 1
33139
33241
  --deny-action <inform|block> AgentMoss Deny: inform=log only (default), block=actually block
33242
+ --security-url <url> AgentMoss service URL (default: $AGENT_MOSS_URL / $MOSS_URL / 9090)
33140
33243
 
33141
33244
  Gateway options:
33142
33245
  --host <host> Listen host (default: 127.0.0.1)
@@ -33194,6 +33297,7 @@ Run options:
33194
33297
  let interceptHosts = "api.openai.com,api.anthropic.com";
33195
33298
  let level = 1;
33196
33299
  let denyAction = "inform";
33300
+ let securityUrl;
33197
33301
  for (let i = 1; i < args.length; i++) {
33198
33302
  if (args[i] === "--host" && args[i + 1]) host = args[++i];
33199
33303
  else if (args[i] === "--port" && args[i + 1]) port = parseInt(args[++i], 10);
@@ -33202,6 +33306,7 @@ Run options:
33202
33306
  else if (args[i] === "--intercept" && args[i + 1]) interceptHosts = args[++i];
33203
33307
  else if (args[i] === "--level" && args[i + 1]) level = parseInt(args[++i], 10);
33204
33308
  else if (args[i] === "--deny-action" && args[i + 1]) denyAction = args[++i];
33309
+ else if (args[i] === "--security-url" && args[i + 1]) securityUrl = args[++i];
33205
33310
  }
33206
33311
  const envLevel = process.env.AGENT_GATE_LEVEL;
33207
33312
  if (envLevel && !args.includes("--level")) level = parseInt(envLevel, 10);
@@ -33219,6 +33324,8 @@ Run options:
33219
33324
  const { WhitelistEngine: WhitelistEngine2 } = await Promise.resolve().then(() => (init_whitelist(), whitelist_exports));
33220
33325
  const { PrivacyFilter: PrivacyFilter2 } = await Promise.resolve().then(() => (init_privacy(), privacy_exports));
33221
33326
  const { callAgentMoss: callAgentMoss2, setMossUrl: setMossUrl2 } = await Promise.resolve().then(() => (init_moss_client(), moss_client_exports));
33327
+ const effectiveMossUrl = securityUrl || process.env.AGENT_MOSS_URL || process.env.MOSS_URL;
33328
+ if (effectiveMossUrl) setMossUrl2(effectiveMossUrl);
33222
33329
  const aggregator = new ProxySessionAggregator2();
33223
33330
  const triggerEngine = new TriggerEngine2(rulesPath);
33224
33331
  const whitelistEngine = new WhitelistEngine2(rulesPath);
@@ -33251,7 +33358,9 @@ Run options:
33251
33358
  interceptHosts: interceptHosts.split(",").map((h) => h.trim()),
33252
33359
  rulesPath,
33253
33360
  db,
33254
- coordinator
33361
+ coordinator,
33362
+ // deny-action=block → 接管响应,AgentMoss 判 Deny 时回 403(真拦截)
33363
+ blockDeny: denyAction === "block"
33255
33364
  });
33256
33365
  await server.start();
33257
33366
  process.on("SIGINT", () => {
@@ -33757,8 +33866,9 @@ Usage:
33757
33866
  const { PrivacyFilter: PrivacyFilter2 } = await Promise.resolve().then(() => (init_privacy(), privacy_exports));
33758
33867
  const { WhitelistEngine: WhitelistEngine2 } = await Promise.resolve().then(() => (init_whitelist(), whitelist_exports));
33759
33868
  const { callAgentMoss: callAgentMoss2, setMossUrl: setMossUrl2 } = await Promise.resolve().then(() => (init_moss_client(), moss_client_exports));
33869
+ const effectiveMossUrl = securityUrl || process.env.AGENT_MOSS_URL || process.env.MOSS_URL;
33870
+ if (effectiveMossUrl) setMossUrl2(effectiveMossUrl);
33760
33871
  const proxyLevel = hasL2 ? 2 : 1;
33761
- const denyAction2 = "inform";
33762
33872
  const rulesPath = "../config/trigger_rules.yaml";
33763
33873
  const aggregator = new ProxySessionAggregator2();
33764
33874
  const triggerEngine = new TriggerEngine2(rulesPath);
@@ -33774,7 +33884,7 @@ Usage:
33774
33884
  whitelistEngine,
33775
33885
  privacyFilter,
33776
33886
  onBlock: (_sid, _matches) => {
33777
- if (denyAction2 === "block") {
33887
+ if (denyAction === "block") {
33778
33888
  console.warn(`[AgentGate] AgentMoss DENY (blocking)`);
33779
33889
  return true;
33780
33890
  }
@@ -33816,7 +33926,9 @@ Usage:
33816
33926
  port,
33817
33927
  interceptHosts: hasL1 && upstream ? [new URL(upstream).hostname] : [],
33818
33928
  rulesPath,
33819
- coordinator
33929
+ coordinator,
33930
+ // deny-action=block → 接管响应,AgentMoss 判 Deny 时回 403(真拦截)
33931
+ blockDeny: denyAction === "block"
33820
33932
  });
33821
33933
  console.log(`[AgentGate] Starting L${proxyLevel} proxy on :${port}${upstream ? " \u2192 " + upstream : ""}...`);
33822
33934
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kenhkl/agent-gate",
3
- "version": "0.7.3",
3
+ "version": "0.7.5",
4
4
  "description": "AI Agent data collection & security analysis gateway (TypeScript)",
5
5
  "main": "dist/v1/server.js",
6
6
  "bin": {