@kenhkl/agent-gate 0.7.4 → 0.7.6

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.4" : (() => {
817
+ _version = true ? "0.7.6" : (() => {
818
818
  try {
819
819
  const require2 = createRequire(importMetaUrl);
820
820
  const pkg = require2("../package.json");
@@ -898,7 +898,8 @@ var init_models = __esm({
898
898
  status: import_zod.z.string().default("healthy"),
899
899
  version: import_zod.z.string().default(version),
900
900
  moss_version: import_zod.z.string().default("N/A"),
901
- moss_status: import_zod.z.string().default("unknown")
901
+ moss_status: import_zod.z.string().default("unknown"),
902
+ instance: import_zod.z.string().default("")
902
903
  });
903
904
  }
904
905
  });
@@ -1145,7 +1146,11 @@ async function healthRoute(c) {
1145
1146
  status: "healthy",
1146
1147
  version,
1147
1148
  moss_version: mossHealth.moss_version,
1148
- moss_status: mossHealth.moss_status
1149
+ moss_status: mossHealth.moss_status,
1150
+ // 归属标识:由启动方注入 AGENT_GATE_INSTANCE(同机多套 AgentGate 时用于区分是谁起的),
1151
+ // 未注入时为空串。与 agent-moss 的 AGENT_MOSS_INSTANCE 同一套约定,供探测端在
1152
+ // /proc 不可读、无法做 PID↔端口校验时退化为按实例字符串判归属。
1153
+ instance: process.env.AGENT_GATE_INSTANCE || ""
1149
1154
  });
1150
1155
  }
1151
1156
  function storageOversizeInfo() {
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.4" : (() => {
830
+ var _version = true ? "0.7.6" : (() => {
831
831
  try {
832
832
  const require2 = createRequire(importMetaUrl);
833
833
  const pkg = require2("../package.json");
@@ -902,7 +902,8 @@ var HealthResponseSchema = import_zod.z.object({
902
902
  status: import_zod.z.string().default("healthy"),
903
903
  version: import_zod.z.string().default(version),
904
904
  moss_version: import_zod.z.string().default("N/A"),
905
- moss_status: import_zod.z.string().default("unknown")
905
+ moss_status: import_zod.z.string().default("unknown"),
906
+ instance: import_zod.z.string().default("")
906
907
  });
907
908
 
908
909
  // src/shared/normalizer.ts
@@ -1110,7 +1111,11 @@ async function healthRoute(c) {
1110
1111
  status: "healthy",
1111
1112
  version,
1112
1113
  moss_version: mossHealth.moss_version,
1113
- moss_status: mossHealth.moss_status
1114
+ moss_status: mossHealth.moss_status,
1115
+ // 归属标识:由启动方注入 AGENT_GATE_INSTANCE(同机多套 AgentGate 时用于区分是谁起的),
1116
+ // 未注入时为空串。与 agent-moss 的 AGENT_MOSS_INSTANCE 同一套约定,供探测端在
1117
+ // /proc 不可读、无法做 PID↔端口校验时退化为按实例字符串判归属。
1118
+ instance: process.env.AGENT_GATE_INSTANCE || ""
1114
1119
  });
1115
1120
  }
1116
1121
  function storageOversizeInfo() {
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.4" : (() => {
53
+ _version = true ? "0.7.6" : (() => {
54
54
  try {
55
55
  const require2 = createRequire(importMetaUrl);
56
56
  const pkg = require2("../package.json");
@@ -901,7 +901,8 @@ var init_models = __esm({
901
901
  status: import_zod.z.string().default("healthy"),
902
902
  version: import_zod.z.string().default(version),
903
903
  moss_version: import_zod.z.string().default("N/A"),
904
- moss_status: import_zod.z.string().default("unknown")
904
+ moss_status: import_zod.z.string().default("unknown"),
905
+ instance: import_zod.z.string().default("")
905
906
  });
906
907
  }
907
908
  });
@@ -1148,7 +1149,11 @@ async function healthRoute(c) {
1148
1149
  status: "healthy",
1149
1150
  version,
1150
1151
  moss_version: mossHealth.moss_version,
1151
- moss_status: mossHealth.moss_status
1152
+ moss_status: mossHealth.moss_status,
1153
+ // 归属标识:由启动方注入 AGENT_GATE_INSTANCE(同机多套 AgentGate 时用于区分是谁起的),
1154
+ // 未注入时为空串。与 agent-moss 的 AGENT_MOSS_INSTANCE 同一套约定,供探测端在
1155
+ // /proc 不可读、无法做 PID↔端口校验时退化为按实例字符串判归属。
1156
+ instance: process.env.AGENT_GATE_INSTANCE || ""
1152
1157
  });
1153
1158
  }
1154
1159
  function storageOversizeInfo() {
@@ -27497,22 +27502,36 @@ var init_interceptor = __esm({
27497
27502
  const meta = parser.parseRequest(url, headers, body);
27498
27503
  this._requestCache.set(flowId, { meta, headers, url, parser });
27499
27504
  }
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).
27505
+ /** Process an incoming response in observation mode.
27506
+ * Returns the captured proxy events. Deny decisions are only logged
27507
+ * (fire-and-forget); blocking is handled by decideResponse() (block mode).
27505
27508
  */
27506
27509
  async onResponse(flowId, respHeaders, respBody) {
27510
+ const { events } = await this._processResponse(flowId, respHeaders, respBody, false);
27511
+ return events;
27512
+ }
27513
+ /** Process an incoming response and synchronously await the deny decision.
27514
+ * Used by the MITM proxy in block mode: the caller replaces the upstream
27515
+ * response with a 403 when `deny.deny` is true.
27516
+ * Note: in Gateway mode the same decision is produced by gateway/server.ts.
27517
+ */
27518
+ async decideResponse(flowId, respHeaders, respBody) {
27519
+ return this._processResponse(flowId, respHeaders, respBody, true);
27520
+ }
27521
+ /** Shared response processing pipeline.
27522
+ * @param awaitDecision when true, await AgentMoss instead of fire-and-forget.
27523
+ */
27524
+ async _processResponse(flowId, respHeaders, respBody, awaitDecision) {
27507
27525
  const cached = this._requestCache.get(flowId);
27508
- if (!cached) return [];
27526
+ if (!cached) return { events: [], deny: { deny: false } };
27509
27527
  this._requestCache.delete(flowId);
27510
27528
  const { parser, meta, headers, url } = cached;
27511
27529
  const toolCalls = parser.parseResponse(url, respHeaders, respBody, meta);
27512
- if (toolCalls.length === 0) return [];
27530
+ if (toolCalls.length === 0) return { events: [], deny: { deny: false } };
27513
27531
  const agentType = parser.detectAgentType(headers, meta);
27514
27532
  const sessionId = deriveSessionId(meta, headers);
27515
27533
  const events = [];
27534
+ let deny = { deny: false };
27516
27535
  for (const tc of toolCalls) {
27517
27536
  let event = normalizeProxyEvent(tc, null, meta, sessionId, agentType);
27518
27537
  const session = this._sessionAgg.processProxyEvent(event);
@@ -27524,8 +27543,9 @@ var init_interceptor = __esm({
27524
27543
  }
27525
27544
  for (const match of matches) {
27526
27545
  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);
27546
+ if (match.rule.localBlock) {
27547
+ if (this._config.onBlock) this._config.onBlock(session.id, match.rule.name);
27548
+ if (!deny.deny) deny = { deny: true, tool: tc.name, reason: `local-block:${match.rule.name}` };
27529
27549
  }
27530
27550
  }
27531
27551
  if (this._coordinator) {
@@ -27533,23 +27553,30 @@ var init_interceptor = __esm({
27533
27553
  console.error("[PhaseCoordinator] L1 event failed:", err);
27534
27554
  return "Allow";
27535
27555
  });
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
- );
27556
+ if (awaitDecision) {
27557
+ const d = await decision;
27558
+ if (d === "Deny" && !deny.deny) {
27559
+ deny = { deny: true, tool: tc.name, reason: "agentmoss-deny" };
27545
27560
  }
27546
- });
27561
+ } else {
27562
+ decision.then((d) => {
27563
+ if (d === "Deny") {
27564
+ console.warn(
27565
+ `[AgentGate] PhaseCoordinator DENY (MITM: cannot block): tool=${tc.name} session=${sessionId.slice(0, 8)}`
27566
+ );
27567
+ } else if (d === null) {
27568
+ console.info(
27569
+ `[AgentGate] PhaseCoordinator: waiting for L2 (tool=${tc.name} session=${sessionId.slice(0, 8)})`
27570
+ );
27571
+ }
27572
+ });
27573
+ }
27547
27574
  }
27548
27575
  }
27549
27576
  console.log(
27550
27577
  `[AgentGate] Intercepted ${events.length} tool_call(s) from ${url} (session=${sessionId.slice(0, 8)}, agent=${agentType})`
27551
27578
  );
27552
- return events;
27579
+ return { events, deny };
27553
27580
  }
27554
27581
  };
27555
27582
  }
@@ -27811,7 +27838,7 @@ var server_exports2 = {};
27811
27838
  __export(server_exports2, {
27812
27839
  ProxyServer: () => ProxyServer
27813
27840
  });
27814
- var import_node_http, import_node_url, import_node_path, import_node_fs2, import_http_mitm_proxy, DASHBOARD_HTML, ProxyServer;
27841
+ var import_node_http, import_node_url, import_node_path, import_node_fs2, import_node_stream, import_http_mitm_proxy, DASHBOARD_HTML, ProxyServer;
27815
27842
  var init_server2 = __esm({
27816
27843
  "src/v3/proxy/server.ts"() {
27817
27844
  "use strict";
@@ -27820,6 +27847,7 @@ var init_server2 = __esm({
27820
27847
  import_node_url = require("url");
27821
27848
  import_node_path = __toESM(require("path"));
27822
27849
  import_node_fs2 = __toESM(require("fs"));
27850
+ import_node_stream = require("stream");
27823
27851
  import_http_mitm_proxy = __toESM(require_dist());
27824
27852
  init_interceptor();
27825
27853
  init_session();
@@ -27921,6 +27949,12 @@ load();setInterval(load,5000);
27921
27949
  reqChunks.push(chunk);
27922
27950
  return cb(null, chunk);
27923
27951
  });
27952
+ if (this._options.blockDeny) {
27953
+ ctx.onResponse((innerCtx, cb) => {
27954
+ this._handleBlockingResponse(innerCtx, flowId, fullUrl, method, reqChunks, cb);
27955
+ });
27956
+ return callback(null);
27957
+ }
27924
27958
  const respChunks = [];
27925
27959
  ctx.onResponseData((_ctx, chunk, cb) => {
27926
27960
  respChunks.push(chunk);
@@ -27940,10 +27974,9 @@ load();setInterval(load,5000);
27940
27974
  if (v !== void 0) respHeaders[k] = Array.isArray(v) ? v[0] : String(v);
27941
27975
  }
27942
27976
  }
27943
- const result = this._interceptor.onResponse(flowId, respHeaders, respBody);
27944
- if (typeof result === "string") {
27945
- console.warn(`[AgentGate] BLOCKED tool=${result}`);
27946
- }
27977
+ this._interceptor.onResponse(flowId, respHeaders, respBody).catch((err) => {
27978
+ console.error("[AgentGate] onResponse failed:", err);
27979
+ });
27947
27980
  return cb(null);
27948
27981
  });
27949
27982
  return callback(null);
@@ -27992,6 +28025,79 @@ load();setInterval(load,5000);
27992
28025
  get triggerEngine() {
27993
28026
  return this._triggerEngine;
27994
28027
  }
28028
+ // ===== Block mode: response takeover =====
28029
+ /** Called in block mode from ctx.onResponse (upstream paused, not yet flushed).
28030
+ * Reads the full upstream body, awaits the deny decision, then replaces
28031
+ * ctx.serverToProxyResponse — with a 403 JSON on deny, or the original
28032
+ * response otherwise. http-mitm-proxy reads ctx.serverToProxyResponse only
28033
+ * after this callback returns (see node_modules/http-mitm-proxy/lib/proxy.ts
28034
+ * proxyToServerRequestComplete), so the replacement is what reaches the client.
28035
+ */
28036
+ _handleBlockingResponse(ctx, flowId, fullUrl, method, reqChunks, cb) {
28037
+ const resp = ctx.serverToProxyResponse;
28038
+ let settled = false;
28039
+ const finish = (err) => {
28040
+ if (settled) return;
28041
+ settled = true;
28042
+ cb(err ?? null);
28043
+ };
28044
+ if (!resp) {
28045
+ console.warn("[AgentGate] block mode: no upstream response to inspect; passing through");
28046
+ finish(null);
28047
+ return;
28048
+ }
28049
+ const chunks = [];
28050
+ resp.on("data", (c) => chunks.push(Buffer.isBuffer(c) ? c : Buffer.from(c)));
28051
+ resp.on("error", () => finish(null));
28052
+ resp.on("end", () => {
28053
+ const respBody = Buffer.concat(chunks);
28054
+ const originalStatus = resp.statusCode || 200;
28055
+ const respHeaders = {};
28056
+ for (const [k, v] of Object.entries(resp.headers)) {
28057
+ if (v !== void 0) respHeaders[k] = Array.isArray(v) ? v.join(", ") : String(v);
28058
+ }
28059
+ const headers = {};
28060
+ for (const [k, v] of Object.entries(ctx.clientToProxyRequest.headers)) {
28061
+ if (v !== void 0) headers[k] = Array.isArray(v) ? v[0] : String(v);
28062
+ }
28063
+ this._interceptor.onRequest(flowId, fullUrl, method, headers, Buffer.concat(reqChunks));
28064
+ this._interceptor.decideResponse(flowId, respHeaders, respBody).then(({ deny }) => {
28065
+ if (deny.deny) {
28066
+ console.warn(
28067
+ `[AgentGate] BLOCKED (MITM 403): tool=${deny.tool} reason=${deny.reason} url=${fullUrl}`
28068
+ );
28069
+ const body = Buffer.from(
28070
+ JSON.stringify({
28071
+ error: "blocked_by_agentgate",
28072
+ tool: deny.tool,
28073
+ message: `Blocked by AgentGate\uFF08${deny.reason || "denied"}\uFF09`
28074
+ })
28075
+ );
28076
+ this._replaceResponse(ctx, 403, { "content-type": "application/json; charset=utf-8" }, body);
28077
+ } else {
28078
+ this._replaceResponse(ctx, originalStatus, respHeaders, respBody);
28079
+ }
28080
+ finish(null);
28081
+ }).catch((err) => {
28082
+ console.error("[AgentGate] decideResponse failed (fail-open):", err);
28083
+ this._replaceResponse(ctx, originalStatus, respHeaders, respBody);
28084
+ finish(null);
28085
+ });
28086
+ });
28087
+ resp.resume();
28088
+ }
28089
+ /** Replace ctx.serverToProxyResponse with a synthesized stream carrying the
28090
+ * given status/headers/body (the original stream has already been consumed). */
28091
+ _replaceResponse(ctx, statusCode, headers, body) {
28092
+ const ps = new import_node_stream.PassThrough();
28093
+ const h = { ...headers };
28094
+ delete h["transfer-encoding"];
28095
+ h["content-length"] = String(body.length);
28096
+ ps.statusCode = statusCode;
28097
+ ps.headers = h;
28098
+ ctx.serverToProxyResponse = ps;
28099
+ ps.end(body);
28100
+ }
27995
28101
  // ===== Dashboard (separate HTTP server) =====
27996
28102
  _startDashboard() {
27997
28103
  const dashPort = this._options.port + 1;
@@ -33121,6 +33227,7 @@ Start options:
33121
33227
  Log level (default: info)
33122
33228
  --deny-action <inform|block>
33123
33229
  AgentMoss Deny handling: inform=log only (default), block=actually block
33230
+ --security-url <url> AgentMoss service URL (default: $AGENT_MOSS_URL / $MOSS_URL / 9090)
33124
33231
 
33125
33232
  Server options:
33126
33233
  --host <host> Listen host (default: 127.0.0.1)
@@ -33137,6 +33244,7 @@ Proxy options:
33137
33244
  --intercept <hosts> Comma-separated hosts to intercept (default: api.openai.com,api.anthropic.com)
33138
33245
  --level <1|2> Interception level: 1=L1 (proxy only), 2=L1+L2 (proxy+PTY). Default from env or 1
33139
33246
  --deny-action <inform|block> AgentMoss Deny: inform=log only (default), block=actually block
33247
+ --security-url <url> AgentMoss service URL (default: $AGENT_MOSS_URL / $MOSS_URL / 9090)
33140
33248
 
33141
33249
  Gateway options:
33142
33250
  --host <host> Listen host (default: 127.0.0.1)
@@ -33194,6 +33302,7 @@ Run options:
33194
33302
  let interceptHosts = "api.openai.com,api.anthropic.com";
33195
33303
  let level = 1;
33196
33304
  let denyAction = "inform";
33305
+ let securityUrl;
33197
33306
  for (let i = 1; i < args.length; i++) {
33198
33307
  if (args[i] === "--host" && args[i + 1]) host = args[++i];
33199
33308
  else if (args[i] === "--port" && args[i + 1]) port = parseInt(args[++i], 10);
@@ -33202,6 +33311,7 @@ Run options:
33202
33311
  else if (args[i] === "--intercept" && args[i + 1]) interceptHosts = args[++i];
33203
33312
  else if (args[i] === "--level" && args[i + 1]) level = parseInt(args[++i], 10);
33204
33313
  else if (args[i] === "--deny-action" && args[i + 1]) denyAction = args[++i];
33314
+ else if (args[i] === "--security-url" && args[i + 1]) securityUrl = args[++i];
33205
33315
  }
33206
33316
  const envLevel = process.env.AGENT_GATE_LEVEL;
33207
33317
  if (envLevel && !args.includes("--level")) level = parseInt(envLevel, 10);
@@ -33219,6 +33329,8 @@ Run options:
33219
33329
  const { WhitelistEngine: WhitelistEngine2 } = await Promise.resolve().then(() => (init_whitelist(), whitelist_exports));
33220
33330
  const { PrivacyFilter: PrivacyFilter2 } = await Promise.resolve().then(() => (init_privacy(), privacy_exports));
33221
33331
  const { callAgentMoss: callAgentMoss2, setMossUrl: setMossUrl2 } = await Promise.resolve().then(() => (init_moss_client(), moss_client_exports));
33332
+ const effectiveMossUrl = securityUrl || process.env.AGENT_MOSS_URL || process.env.MOSS_URL;
33333
+ if (effectiveMossUrl) setMossUrl2(effectiveMossUrl);
33222
33334
  const aggregator = new ProxySessionAggregator2();
33223
33335
  const triggerEngine = new TriggerEngine2(rulesPath);
33224
33336
  const whitelistEngine = new WhitelistEngine2(rulesPath);
@@ -33251,7 +33363,9 @@ Run options:
33251
33363
  interceptHosts: interceptHosts.split(",").map((h) => h.trim()),
33252
33364
  rulesPath,
33253
33365
  db,
33254
- coordinator
33366
+ coordinator,
33367
+ // deny-action=block → 接管响应,AgentMoss 判 Deny 时回 403(真拦截)
33368
+ blockDeny: denyAction === "block"
33255
33369
  });
33256
33370
  await server.start();
33257
33371
  process.on("SIGINT", () => {
@@ -33757,8 +33871,9 @@ Usage:
33757
33871
  const { PrivacyFilter: PrivacyFilter2 } = await Promise.resolve().then(() => (init_privacy(), privacy_exports));
33758
33872
  const { WhitelistEngine: WhitelistEngine2 } = await Promise.resolve().then(() => (init_whitelist(), whitelist_exports));
33759
33873
  const { callAgentMoss: callAgentMoss2, setMossUrl: setMossUrl2 } = await Promise.resolve().then(() => (init_moss_client(), moss_client_exports));
33874
+ const effectiveMossUrl = securityUrl || process.env.AGENT_MOSS_URL || process.env.MOSS_URL;
33875
+ if (effectiveMossUrl) setMossUrl2(effectiveMossUrl);
33760
33876
  const proxyLevel = hasL2 ? 2 : 1;
33761
- const denyAction2 = "inform";
33762
33877
  const rulesPath = "../config/trigger_rules.yaml";
33763
33878
  const aggregator = new ProxySessionAggregator2();
33764
33879
  const triggerEngine = new TriggerEngine2(rulesPath);
@@ -33774,7 +33889,7 @@ Usage:
33774
33889
  whitelistEngine,
33775
33890
  privacyFilter,
33776
33891
  onBlock: (_sid, _matches) => {
33777
- if (denyAction2 === "block") {
33892
+ if (denyAction === "block") {
33778
33893
  console.warn(`[AgentGate] AgentMoss DENY (blocking)`);
33779
33894
  return true;
33780
33895
  }
@@ -33816,7 +33931,9 @@ Usage:
33816
33931
  port,
33817
33932
  interceptHosts: hasL1 && upstream ? [new URL(upstream).hostname] : [],
33818
33933
  rulesPath,
33819
- coordinator
33934
+ coordinator,
33935
+ // deny-action=block → 接管响应,AgentMoss 判 Deny 时回 403(真拦截)
33936
+ blockDeny: denyAction === "block"
33820
33937
  });
33821
33938
  console.log(`[AgentGate] Starting L${proxyLevel} proxy on :${port}${upstream ? " \u2192 " + upstream : ""}...`);
33822
33939
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kenhkl/agent-gate",
3
- "version": "0.7.4",
3
+ "version": "0.7.6",
4
4
  "description": "AI Agent data collection & security analysis gateway (TypeScript)",
5
5
  "main": "dist/v1/server.js",
6
6
  "bin": {