@decionis/agentsafe 0.2.5 → 0.3.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.
Files changed (271) hide show
  1. package/README.md +135 -20
  2. package/dist/Cli.js +19 -0
  3. package/dist/Cli.js.map +1 -1
  4. package/dist/Index.d.ts +10 -4
  5. package/dist/Index.d.ts.map +1 -1
  6. package/dist/Index.js +8 -2
  7. package/dist/Index.js.map +1 -1
  8. package/dist/TrustedExecutor.d.ts.map +1 -1
  9. package/dist/TrustedExecutor.js +1 -0
  10. package/dist/TrustedExecutor.js.map +1 -1
  11. package/dist/adapters/AdapterActionHandler.d.ts.map +1 -1
  12. package/dist/adapters/AdapterActionHandler.js +8 -4
  13. package/dist/adapters/AdapterActionHandler.js.map +1 -1
  14. package/dist/adapters/EffectAdapter.d.ts +6 -1
  15. package/dist/adapters/EffectAdapter.d.ts.map +1 -1
  16. package/dist/adapters/EffectAdapter.js +7 -1
  17. package/dist/adapters/EffectAdapter.js.map +1 -1
  18. package/dist/adapters/banking/CoreBankingHttpAdapter.d.ts.map +1 -1
  19. package/dist/adapters/banking/CoreBankingHttpAdapter.js +4 -4
  20. package/dist/adapters/banking/CoreBankingHttpAdapter.js.map +1 -1
  21. package/dist/adapters/cards/CardAuthorizationMatcher.d.ts +44 -0
  22. package/dist/adapters/cards/CardAuthorizationMatcher.d.ts.map +1 -0
  23. package/dist/adapters/cards/CardAuthorizationMatcher.js +39 -0
  24. package/dist/adapters/cards/CardAuthorizationMatcher.js.map +1 -0
  25. package/dist/adapters/cards/CardEffect.d.ts +52 -0
  26. package/dist/adapters/cards/CardEffect.d.ts.map +1 -0
  27. package/dist/adapters/cards/CardEffect.js +117 -0
  28. package/dist/adapters/cards/CardEffect.js.map +1 -0
  29. package/dist/adapters/cards/CardHandlers.d.ts +15 -0
  30. package/dist/adapters/cards/CardHandlers.d.ts.map +1 -0
  31. package/dist/adapters/cards/CardHandlers.js +26 -0
  32. package/dist/adapters/cards/CardHandlers.js.map +1 -0
  33. package/dist/adapters/cards/CardPurchase.d.ts +61 -0
  34. package/dist/adapters/cards/CardPurchase.d.ts.map +1 -0
  35. package/dist/adapters/cards/CardPurchase.js +116 -0
  36. package/dist/adapters/cards/CardPurchase.js.map +1 -0
  37. package/dist/adapters/cards/HeldCardGrants.d.ts +70 -0
  38. package/dist/adapters/cards/HeldCardGrants.d.ts.map +1 -0
  39. package/dist/adapters/cards/HeldCardGrants.js +79 -0
  40. package/dist/adapters/cards/HeldCardGrants.js.map +1 -0
  41. package/dist/adapters/cards/Pan.d.ts +17 -0
  42. package/dist/adapters/cards/Pan.d.ts.map +1 -0
  43. package/dist/adapters/cards/Pan.js +52 -0
  44. package/dist/adapters/cards/Pan.js.map +1 -0
  45. package/dist/adapters/mcp/McpGuard.d.ts.map +1 -1
  46. package/dist/adapters/mcp/McpGuard.js +9 -4
  47. package/dist/adapters/mcp/McpGuard.js.map +1 -1
  48. package/dist/audit/HashChain.d.ts +8 -2
  49. package/dist/audit/HashChain.d.ts.map +1 -1
  50. package/dist/audit/HashChain.js +14 -2
  51. package/dist/audit/HashChain.js.map +1 -1
  52. package/dist/cli/Commands.d.ts +1 -1
  53. package/dist/cli/Commands.d.ts.map +1 -1
  54. package/dist/cli/Commands.js +5 -0
  55. package/dist/cli/Commands.js.map +1 -1
  56. package/dist/cli/Edge.d.ts +4 -0
  57. package/dist/cli/Edge.d.ts.map +1 -0
  58. package/dist/cli/Edge.js +250 -0
  59. package/dist/cli/Edge.js.map +1 -0
  60. package/dist/cli/Help.d.ts.map +1 -1
  61. package/dist/cli/Help.js +8 -0
  62. package/dist/cli/Help.js.map +1 -1
  63. package/dist/cli/Host.d.ts +36 -0
  64. package/dist/cli/Host.d.ts.map +1 -0
  65. package/dist/cli/Host.js +247 -0
  66. package/dist/cli/Host.js.map +1 -0
  67. package/dist/cli/TcpBrokerCli.d.ts +4 -0
  68. package/dist/cli/TcpBrokerCli.d.ts.map +1 -0
  69. package/dist/cli/TcpBrokerCli.js +93 -0
  70. package/dist/cli/TcpBrokerCli.js.map +1 -0
  71. package/dist/cli/TcpClientCli.d.ts +16 -0
  72. package/dist/cli/TcpClientCli.d.ts.map +1 -0
  73. package/dist/cli/TcpClientCli.js +175 -0
  74. package/dist/cli/TcpClientCli.js.map +1 -0
  75. package/dist/config/ConfigKeys.d.ts +2 -2
  76. package/dist/config/ConfigKeys.d.ts.map +1 -1
  77. package/dist/config/ConfigKeys.js +19 -0
  78. package/dist/config/ConfigKeys.js.map +1 -1
  79. package/dist/config/ExecutorConfig.d.ts +62 -0
  80. package/dist/config/ExecutorConfig.d.ts.map +1 -1
  81. package/dist/config/ExecutorConfig.js +124 -0
  82. package/dist/config/ExecutorConfig.js.map +1 -1
  83. package/dist/edge/EdgeLicence.d.ts +25 -0
  84. package/dist/edge/EdgeLicence.d.ts.map +1 -0
  85. package/dist/edge/EdgeLicence.js +42 -0
  86. package/dist/edge/EdgeLicence.js.map +1 -0
  87. package/dist/edge/EdgeReplay.d.ts +45 -0
  88. package/dist/edge/EdgeReplay.d.ts.map +1 -0
  89. package/dist/edge/EdgeReplay.js +69 -0
  90. package/dist/edge/EdgeReplay.js.map +1 -0
  91. package/dist/edge/Entitlement.d.ts +57 -0
  92. package/dist/edge/Entitlement.d.ts.map +1 -0
  93. package/dist/edge/Entitlement.js +139 -0
  94. package/dist/edge/Entitlement.js.map +1 -0
  95. package/dist/edge/EntitlementEvaluation.d.ts +66 -0
  96. package/dist/edge/EntitlementEvaluation.d.ts.map +1 -0
  97. package/dist/edge/EntitlementEvaluation.js +74 -0
  98. package/dist/edge/EntitlementEvaluation.js.map +1 -0
  99. package/dist/edge/UsageCount.d.ts +40 -0
  100. package/dist/edge/UsageCount.d.ts.map +1 -0
  101. package/dist/edge/UsageCount.js +140 -0
  102. package/dist/edge/UsageCount.js.map +1 -0
  103. package/dist/edge/UsageKeyRegistration.d.ts +34 -0
  104. package/dist/edge/UsageKeyRegistration.d.ts.map +1 -0
  105. package/dist/edge/UsageKeyRegistration.js +74 -0
  106. package/dist/edge/UsageKeyRegistration.js.map +1 -0
  107. package/dist/edge/UsageMeter.d.ts +89 -0
  108. package/dist/edge/UsageMeter.d.ts.map +1 -0
  109. package/dist/edge/UsageMeter.js +275 -0
  110. package/dist/edge/UsageMeter.js.map +1 -0
  111. package/dist/edge/UsagePeriod.d.ts +23 -0
  112. package/dist/edge/UsagePeriod.d.ts.map +1 -0
  113. package/dist/edge/UsagePeriod.js +31 -0
  114. package/dist/edge/UsagePeriod.js.map +1 -0
  115. package/dist/edge/UsageReport.d.ts +92 -0
  116. package/dist/edge/UsageReport.d.ts.map +1 -0
  117. package/dist/edge/UsageReport.js +153 -0
  118. package/dist/edge/UsageReport.js.map +1 -0
  119. package/dist/edge/UsageTally.d.ts +63 -0
  120. package/dist/edge/UsageTally.d.ts.map +1 -0
  121. package/dist/edge/UsageTally.js +89 -0
  122. package/dist/edge/UsageTally.js.map +1 -0
  123. package/dist/egress/EgressError.d.ts +7 -1
  124. package/dist/egress/EgressError.d.ts.map +1 -1
  125. package/dist/egress/EgressError.js.map +1 -1
  126. package/dist/egress/EgressPolicy.d.ts +16 -3
  127. package/dist/egress/EgressPolicy.d.ts.map +1 -1
  128. package/dist/egress/EgressPolicy.js +33 -3
  129. package/dist/egress/EgressPolicy.js.map +1 -1
  130. package/dist/egress/GuardedFetch.d.ts +38 -1
  131. package/dist/egress/GuardedFetch.d.ts.map +1 -1
  132. package/dist/egress/GuardedFetch.js +52 -7
  133. package/dist/egress/GuardedFetch.js.map +1 -1
  134. package/dist/egress/TcpClient.d.ts +103 -0
  135. package/dist/egress/TcpClient.d.ts.map +1 -0
  136. package/dist/egress/TcpClient.js +490 -0
  137. package/dist/egress/TcpClient.js.map +1 -0
  138. package/dist/egress/TcpControlClient.d.ts +49 -0
  139. package/dist/egress/TcpControlClient.d.ts.map +1 -0
  140. package/dist/egress/TcpControlClient.js +186 -0
  141. package/dist/egress/TcpControlClient.js.map +1 -0
  142. package/dist/gateway/ForwardHandler.d.ts.map +1 -1
  143. package/dist/gateway/ForwardHandler.js +7 -4
  144. package/dist/gateway/ForwardHandler.js.map +1 -1
  145. package/dist/gateway/Gateway.d.ts +190 -10
  146. package/dist/gateway/Gateway.d.ts.map +1 -1
  147. package/dist/gateway/Gateway.js +465 -62
  148. package/dist/gateway/Gateway.js.map +1 -1
  149. package/dist/gateway/GatewayConfig.d.ts +67 -0
  150. package/dist/gateway/GatewayConfig.d.ts.map +1 -1
  151. package/dist/gateway/GatewayConfig.js +149 -2
  152. package/dist/gateway/GatewayConfig.js.map +1 -1
  153. package/dist/gateway/InterceptedRequest.d.ts +9 -2
  154. package/dist/gateway/InterceptedRequest.d.ts.map +1 -1
  155. package/dist/gateway/InterceptedRequest.js +41 -9
  156. package/dist/gateway/InterceptedRequest.js.map +1 -1
  157. package/dist/gateway/RateLimit.d.ts +29 -0
  158. package/dist/gateway/RateLimit.d.ts.map +1 -0
  159. package/dist/gateway/RateLimit.js +33 -0
  160. package/dist/gateway/RateLimit.js.map +1 -0
  161. package/dist/gateway/RefusalSampler.d.ts +28 -0
  162. package/dist/gateway/RefusalSampler.d.ts.map +1 -0
  163. package/dist/gateway/RefusalSampler.js +52 -0
  164. package/dist/gateway/RefusalSampler.js.map +1 -0
  165. package/dist/gateway/RouteTable.d.ts +3 -0
  166. package/dist/gateway/RouteTable.d.ts.map +1 -1
  167. package/dist/gateway/RouteTable.js +44 -7
  168. package/dist/gateway/RouteTable.js.map +1 -1
  169. package/dist/gateway/Upstream.d.ts +26 -0
  170. package/dist/gateway/Upstream.d.ts.map +1 -1
  171. package/dist/gateway/Upstream.js +41 -2
  172. package/dist/gateway/Upstream.js.map +1 -1
  173. package/dist/gateway/UpstreamProof.d.ts +235 -0
  174. package/dist/gateway/UpstreamProof.d.ts.map +1 -0
  175. package/dist/gateway/UpstreamProof.js +375 -0
  176. package/dist/gateway/UpstreamProof.js.map +1 -0
  177. package/dist/handlers/ForwardRequestHandler.d.ts +5 -1
  178. package/dist/handlers/ForwardRequestHandler.d.ts.map +1 -1
  179. package/dist/handlers/ForwardRequestHandler.js +12 -2
  180. package/dist/handlers/ForwardRequestHandler.js.map +1 -1
  181. package/dist/hosted/TenantHost.d.ts +180 -0
  182. package/dist/hosted/TenantHost.d.ts.map +1 -0
  183. package/dist/hosted/TenantHost.js +432 -0
  184. package/dist/hosted/TenantHost.js.map +1 -0
  185. package/dist/hosted/TenantRegistry.d.ts +73 -0
  186. package/dist/hosted/TenantRegistry.d.ts.map +1 -0
  187. package/dist/hosted/TenantRegistry.js +123 -0
  188. package/dist/hosted/TenantRegistry.js.map +1 -0
  189. package/dist/http/ExecutorHttpServer.d.ts +7 -0
  190. package/dist/http/ExecutorHttpServer.d.ts.map +1 -1
  191. package/dist/http/ExecutorHttpServer.js +30 -5
  192. package/dist/http/ExecutorHttpServer.js.map +1 -1
  193. package/dist/http/GatewayHttpServer.d.ts +55 -3
  194. package/dist/http/GatewayHttpServer.d.ts.map +1 -1
  195. package/dist/http/GatewayHttpServer.js +157 -17
  196. package/dist/http/GatewayHttpServer.js.map +1 -1
  197. package/dist/http/RedirectServer.d.ts +26 -0
  198. package/dist/http/RedirectServer.d.ts.map +1 -0
  199. package/dist/http/RedirectServer.js +62 -0
  200. package/dist/http/RedirectServer.js.map +1 -0
  201. package/dist/http/Routes.d.ts +17 -0
  202. package/dist/http/Routes.d.ts.map +1 -1
  203. package/dist/http/Routes.js +21 -0
  204. package/dist/http/Routes.js.map +1 -1
  205. package/dist/http/TcpBroker.d.ts +57 -0
  206. package/dist/http/TcpBroker.d.ts.map +1 -0
  207. package/dist/http/TcpBroker.js +299 -0
  208. package/dist/http/TcpBroker.js.map +1 -0
  209. package/dist/http/TcpHostRelay.d.ts +24 -0
  210. package/dist/http/TcpHostRelay.d.ts.map +1 -0
  211. package/dist/http/TcpHostRelay.js +194 -0
  212. package/dist/http/TcpHostRelay.js.map +1 -0
  213. package/dist/http/TcpRelayStreams.d.ts +24 -0
  214. package/dist/http/TcpRelayStreams.d.ts.map +1 -0
  215. package/dist/http/TcpRelayStreams.js +128 -0
  216. package/dist/http/TcpRelayStreams.js.map +1 -0
  217. package/dist/http/TlsListener.d.ts +3 -1
  218. package/dist/http/TlsListener.d.ts.map +1 -1
  219. package/dist/http/TlsListener.js +7 -2
  220. package/dist/http/TlsListener.js.map +1 -1
  221. package/dist/identity/PrincipalsFile.d.ts +3 -1
  222. package/dist/identity/PrincipalsFile.d.ts.map +1 -1
  223. package/dist/identity/PrincipalsFile.js +1 -0
  224. package/dist/identity/PrincipalsFile.js.map +1 -1
  225. package/dist/incident/Metrics.d.ts +2 -0
  226. package/dist/incident/Metrics.d.ts.map +1 -1
  227. package/dist/incident/Metrics.js +10 -0
  228. package/dist/incident/Metrics.js.map +1 -1
  229. package/dist/incident/SecurityEvents.d.ts +89 -0
  230. package/dist/incident/SecurityEvents.d.ts.map +1 -1
  231. package/dist/incident/SecurityEvents.js +93 -2
  232. package/dist/incident/SecurityEvents.js.map +1 -1
  233. package/dist/journal/ExecutionJournal.d.ts +27 -0
  234. package/dist/journal/ExecutionJournal.d.ts.map +1 -1
  235. package/dist/journal/ExecutionJournal.js +28 -0
  236. package/dist/journal/ExecutionJournal.js.map +1 -1
  237. package/dist/journal/FileExecutionJournal.d.ts +2 -1
  238. package/dist/journal/FileExecutionJournal.d.ts.map +1 -1
  239. package/dist/journal/FileExecutionJournal.js +4 -1
  240. package/dist/journal/FileExecutionJournal.js.map +1 -1
  241. package/dist/journal/InMemoryExecutionJournal.d.ts +2 -1
  242. package/dist/journal/InMemoryExecutionJournal.d.ts.map +1 -1
  243. package/dist/journal/InMemoryExecutionJournal.js +4 -1
  244. package/dist/journal/InMemoryExecutionJournal.js.map +1 -1
  245. package/dist/service/AuthorityClients.d.ts +8 -1
  246. package/dist/service/AuthorityClients.d.ts.map +1 -1
  247. package/dist/service/AuthorityClients.js +33 -5
  248. package/dist/service/AuthorityClients.js.map +1 -1
  249. package/dist/service/EdgeRuntime.d.ts +73 -0
  250. package/dist/service/EdgeRuntime.d.ts.map +1 -0
  251. package/dist/service/EdgeRuntime.js +209 -0
  252. package/dist/service/EdgeRuntime.js.map +1 -0
  253. package/dist/service/EscalationResolver.d.ts +82 -2
  254. package/dist/service/EscalationResolver.d.ts.map +1 -1
  255. package/dist/service/EscalationResolver.js +39 -3
  256. package/dist/service/EscalationResolver.js.map +1 -1
  257. package/dist/service/Requests.d.ts +28 -2
  258. package/dist/service/Requests.d.ts.map +1 -1
  259. package/dist/service/TrustedExecutorService.d.ts +71 -1
  260. package/dist/service/TrustedExecutorService.d.ts.map +1 -1
  261. package/dist/service/TrustedExecutorService.js +461 -27
  262. package/dist/service/TrustedExecutorService.js.map +1 -1
  263. package/dist/tcp/TcpWire.d.ts +18 -0
  264. package/dist/tcp/TcpWire.d.ts.map +1 -0
  265. package/dist/tcp/TcpWire.js +114 -0
  266. package/dist/tcp/TcpWire.js.map +1 -0
  267. package/dist/verify/VerifyAuditChain.d.ts +5 -0
  268. package/dist/verify/VerifyAuditChain.d.ts.map +1 -1
  269. package/dist/verify/VerifyAuditChain.js +20 -4
  270. package/dist/verify/VerifyAuditChain.js.map +1 -1
  271. package/package.json +7 -3
@@ -1,4 +1,5 @@
1
- import { randomUUID } from "node:crypto";
1
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
2
+ import { Resolver } from "node:dns/promises";
2
3
  import { appendFileSync, mkdirSync } from "node:fs";
3
4
  import { join } from "node:path";
4
5
  import { ActionRegistry, AuditRecorder, DecionisGate, DecionisGrantVerifier, IntentCapture, SafeExecutor, ShadowPipeline, } from "@decionis/agent-safe-pipeline";
@@ -11,7 +12,8 @@ import { ChainJournal } from "../audit/ChainJournal.js";
11
12
  import { HashChain } from "../audit/HashChain.js";
12
13
  import { EVIDENCE_STREAM, HashChainedAuditSink } from "../audit/HashChainedAuditSink.js";
13
14
  import { EgressPolicy } from "../egress/EgressPolicy.js";
14
- import { GuardedFetch } from "../egress/GuardedFetch.js";
15
+ import { EgressError } from "../egress/EgressError.js";
16
+ import { CLIENT_CERTIFICATE_REFUSED, GuardedFetch, } from "../egress/GuardedFetch.js";
15
17
  import { RequestContext } from "../http/RequestContext.js";
16
18
  import { SECURITY_STREAM, SecurityEvents } from "../incident/SecurityEvents.js";
17
19
  import { LineEmitter } from "../logging/LineEmitter.js";
@@ -21,12 +23,16 @@ import { EscalationResolver } from "../service/EscalationResolver.js";
21
23
  import { ActivationFunnel } from "./Activation.js";
22
24
  import { startDemoAuthority } from "./DemoAuthority.js";
23
25
  import { httpForwardHandler, registerHttpActions, RequestHolder, } from "./ForwardHandler.js";
26
+ import { GatewayConfigLoader } from "./GatewayConfig.js";
24
27
  import { gatewayMetrics } from "./GatewayMetrics.js";
25
28
  import { processSurface } from "./InstallSurface.js";
26
29
  import { renderHuman, renderJson, } from "./GatewayReport.js";
27
30
  import { normalizeRequest } from "./InterceptedRequest.js";
31
+ import { TokenBucket } from "./RateLimit.js";
32
+ import { RefusalSampler } from "./RefusalSampler.js";
28
33
  import { RouteTable } from "./RouteTable.js";
29
34
  import { enforcementSwitch, ShadowLedger } from "./ShadowLedger.js";
35
+ import { PROOF_PENDING_RETRY_MS, sameBinding, UpstreamProofCheck, UpstreamProofMonitor, } from "./UpstreamProof.js";
30
36
  /**
31
37
  * When a shadow gateway prints its report unasked: as the count of settled
32
38
  * observations reaches each of these, and whenever a day has passed since
@@ -47,6 +53,36 @@ export const GATEWAY_RESPONSE_VERSION = "agent-safe.gateway/1";
47
53
  /** The most escalations held at once; beyond it a new hold is refused rather than an old one dropped. */
48
54
  const MAX_HELD = 1_000;
49
55
  const RETRY_AFTER_SECONDS = 5;
56
+ /**
57
+ * The transport codes of a send that ended before a connection to the
58
+ * upstream existed: the name did not resolve, or the connection was refused
59
+ * or never made. Nothing of the request left this process.
60
+ */
61
+ const BEFORE_CONNECTION = new Set([
62
+ "ENOTFOUND",
63
+ "EAI_AGAIN",
64
+ "EAI_FAIL",
65
+ "ECONNREFUSED",
66
+ "UND_ERR_CONNECT_TIMEOUT",
67
+ ]);
68
+ /**
69
+ * A transport's codes for a handshake the upstream refused: its own
70
+ * certificate did not verify here, or it refused the gateway's, which the
71
+ * gateway never presents (`CLIENT_CERTIFICATE_REFUSED`: TLS 1.3's
72
+ * `certificate_required` and the alerts other servers send for it). Either
73
+ * way the handshake never finished and nothing of the request was accepted.
74
+ * The guarded egress says the same with its own codes.
75
+ */
76
+ const CERTIFICATE_UNVERIFIED = /^(?:UNABLE_TO_|SELF_SIGNED|DEPTH_ZERO|CERT_|ERR_TLS_CERT_ALTNAME)/;
77
+ /** How much of a `sha256:` digest a readback shows: enough to tell two apart, never the digest. */
78
+ export function shortDigest(digest) {
79
+ return digest.slice(0, "sha256:".length + 12);
80
+ }
81
+ /**
82
+ * The header a resume token travels in. Never the path or the query: those
83
+ * are what proxies, access logs and this gateway's own report write down.
84
+ */
85
+ export const RESUME_TOKEN_HEADER = "agentsafe-resume-token";
50
86
  /**
51
87
  * The HTTP-interception ingress over the unchanged lifecycle. A request the
52
88
  * route table calls consequential becomes a captured intent; the authority
@@ -63,6 +99,7 @@ export class Gateway {
63
99
  metrics;
64
100
  emitLine;
65
101
  io;
102
+ security;
66
103
  secrets;
67
104
  demo;
68
105
  evidence;
@@ -72,6 +109,7 @@ export class Gateway {
72
109
  surface;
73
110
  boundary;
74
111
  workload;
112
+ proof;
75
113
  held = new Map();
76
114
  holder = new RequestHolder();
77
115
  capture;
@@ -82,14 +120,21 @@ export class Gateway {
82
120
  counts = {};
83
121
  activation;
84
122
  ledger = new ShadowLedger();
123
+ bucket;
124
+ /** The tenant key's refusals on the security stream, bounded per window. */
125
+ refusals;
85
126
  lastShadowReportAt;
86
- constructor(config, upstream, routes, audit, gate, verifier, metrics, emitLine, io, security, secrets, demo, journal, evidence, chain, clock, version, surface, boundary, workload) {
127
+ /** The tenant keys admitted now: the configuration's, until a host replaces them in place. */
128
+ admitted;
129
+ registry = null;
130
+ constructor(config, upstream, routes, audit, gate, verifier, metrics, emitLine, io, security, secrets, demo, journal, evidence, chain, clock, version, surface, boundary, workload, activation, proof) {
87
131
  this.config = config;
88
132
  this.upstream = upstream;
89
133
  this.routes = routes;
90
134
  this.metrics = metrics;
91
135
  this.emitLine = emitLine;
92
136
  this.io = io;
137
+ this.security = security;
93
138
  this.secrets = secrets;
94
139
  this.demo = demo;
95
140
  this.evidence = evidence;
@@ -99,9 +144,17 @@ export class Gateway {
99
144
  this.surface = surface;
100
145
  this.boundary = boundary;
101
146
  this.workload = workload;
147
+ this.proof = proof;
102
148
  this.lastShadowReportAt = clock();
149
+ this.admitted = config.tenantKeys;
103
150
  this.capture = new IntentCapture({ audit, ttlSeconds: config.intentTtlSeconds });
104
- this.activation = new ActivationFunnel((milestone, at) => this.report({ event: "ACTIVATION", milestone, at }), clock);
151
+ this.bucket = config.rateLimit === null ? null : new TokenBucket(config.rateLimit, clock);
152
+ this.refusals = new RefusalSampler((code) => security.emit({ event: "AUTH_FAILED", method: "tenant_key", code }), (code, count) => security.emit({ event: "AUTH_FAILED_SUPPRESSED", method: "tenant_key", code, count }));
153
+ // A funnel handed on keeps reporting through the gateway that made it:
154
+ // the same tenant's output, so a milestone is still reported once.
155
+ this.activation =
156
+ activation ??
157
+ new ActivationFunnel((milestone, at) => this.report({ event: "ACTIVATION", milestone, at }), clock);
105
158
  const registry = registerHttpActions(new ActionRegistry(), routes.actions(), httpForwardHandler(upstream, this.holder));
106
159
  // The executor refuses an intent captured through another boundary: an
107
160
  // authority issued at one door is not presentable at the next.
@@ -129,8 +182,8 @@ export class Gateway {
129
182
  /**
130
183
  * Assembles the gateway: the secrets it needs opened, the demo authority
131
184
  * started when chosen, the guarded egress sealed to the authority, the
132
- * pipeline objects built over it, the evidence chains restored. Nothing
133
- * listens; the listener is the caller's.
185
+ * pipeline objects built over it, the evidence chains restored or
186
+ * continued. Nothing listens; the listener is the caller's.
134
187
  */
135
188
  static async create(config, dependencies = {}) {
136
189
  const env = dependencies.env ?? process.env;
@@ -155,16 +208,24 @@ export class Gateway {
155
208
  mkdirSync(config.evidence.journalDir, { recursive: true });
156
209
  journal = new ChainJournal(config.evidence.journalDir, { checkpointLines: 100 });
157
210
  }
211
+ // Each chain goes on from the gateway this one replaces, else from the
212
+ // head the journal last persisted, else from genesis.
213
+ const continues = dependencies.continues ?? null;
214
+ const takeUp = (stream, handed) => handed ?? new HashChain(stream, journal?.restore(stream) ?? null, config.hostedTenant);
158
215
  const security = new SecurityEvents(emitter.security, {
159
- chain: new HashChain(SECURITY_STREAM, journal?.restore(SECURITY_STREAM) ?? null),
216
+ chain: takeUp(SECURITY_STREAM, continues?.security),
160
217
  });
218
+ const securityHead = security.chain.head.seq;
161
219
  emitter.reportRedactions((patterns) => security.emit({ event: "LEAK_SUSPECTED", patterns: [...patterns] }));
162
220
  if (store === null && config.secrets.required.length > 0) {
163
221
  store = CompositeSecretStore.fromEnvironment(env, config.secrets.required, {
164
222
  events: security,
165
223
  production: config.production,
166
224
  enforcePermissions: config.production,
167
- watch: false,
225
+ // A hosted gateway lives as long as its host, and its tenant's
226
+ // workspace key is rotated under it, in a mounted Secret: it watches
227
+ // the file, so a rotation takes effect without a rebuild or a restart.
228
+ watch: config.hosted,
168
229
  });
169
230
  }
170
231
  const secrets = store;
@@ -218,15 +279,47 @@ export class Gateway {
218
279
  if (toTerminal)
219
280
  emitter.audit(line);
220
281
  };
282
+ // A public-only upstream goes through the guarded egress, sealed to its
283
+ // one origin: every address it resolves to is checked before a socket
284
+ // exists. Its own bounds sit just outside the upstream's, so an answer too
285
+ // large or too slow is still reported the way it always was.
286
+ const upstreamGuard = config.upstream.publicOnly
287
+ ? new GuardedFetch({
288
+ policy: new EgressPolicy([
289
+ {
290
+ origin: new URL(config.upstream.url).origin,
291
+ pathPrefixes: ["/"],
292
+ ca: null,
293
+ pins: [],
294
+ },
295
+ ]),
296
+ events: security,
297
+ maxResponseBytes: config.upstream.maxResponseBytes + 1,
298
+ timeoutMs: config.upstream.timeoutMs + 1_000,
299
+ publicOnly: true,
300
+ // A tenant's TLS is the tenant's to fix: the gateway reports a
301
+ // refused handshake as its own event, which pages no one.
302
+ reportTls: false,
303
+ ...(dependencies.upstreamFetch === undefined
304
+ ? {}
305
+ : { transport: dependencies.upstreamFetch }),
306
+ ...(dependencies.upstreamResolve === undefined
307
+ ? {}
308
+ : { resolve: dependencies.upstreamResolve }),
309
+ })
310
+ : null;
221
311
  const upstream = new Upstream({
222
312
  url: config.upstream.url,
223
313
  timeoutMs: config.upstream.timeoutMs,
224
314
  maxResponseBytes: config.upstream.maxResponseBytes,
225
- fetch: dependencies.upstreamFetch ?? fetch,
315
+ fetch: upstreamGuard?.fetch ?? dependencies.upstreamFetch ?? fetch,
316
+ hostOnlyCookies: config.hosted,
317
+ sandboxed: config.hosted,
318
+ ...(upstreamGuard === null ? {} : { close: () => upstreamGuard.close() }),
226
319
  });
227
320
  const routes = new RouteTable(config.interception.routes, config.interception.unmatched, config.interception.http);
228
- const evidence = new HashChain(EVIDENCE_STREAM, journal?.restore(EVIDENCE_STREAM) ?? null);
229
- const chain = new HashChain(GATEWAY_STREAM, journal?.restore(GATEWAY_STREAM) ?? null);
321
+ const evidence = takeUp(EVIDENCE_STREAM, continues?.evidence);
322
+ const chain = takeUp(GATEWAY_STREAM, continues?.gateway);
230
323
  const audit = new AuditRecorder({
231
324
  sink: new HashChainedAuditSink(emitLine, evidence),
232
325
  failurePolicy: config.evidence.enabled ? "REQUIRE_BEFORE_EXECUTION" : "BEST_EFFORT",
@@ -248,9 +341,60 @@ export class Gateway {
248
341
  new NoneProvenanceProvider(),
249
342
  ];
250
343
  const workload = resolveWorkload(dependencies.provenance ?? providers, { env });
251
- const gateway = new Gateway(config, upstream, routes, audit, gate, verifier, metrics, emitLine, io, security, secrets, demo, journal, evidence, chain, clock, version, surface, boundary, workload);
344
+ const proof = Gateway.upstreamProof(config, dependencies, security, clock, continues !== null);
345
+ // A chain that does not start at genesis says where it was taken up, once
346
+ // nothing is left that can refuse the gateway.
347
+ for (const [stream, head] of [
348
+ [SECURITY_STREAM, securityHead],
349
+ [EVIDENCE_STREAM, evidence.head.seq],
350
+ [GATEWAY_STREAM, chain.head.seq],
351
+ ]) {
352
+ if (head > 0)
353
+ security.emit({ event: "CHAIN_RESUMED", chain: stream, head });
354
+ }
355
+ const gateway = new Gateway(config, upstream, routes, audit, gate, verifier, metrics, emitLine, io, security, secrets, demo, journal, evidence, chain, clock, version, surface, boundary, workload, continues?.activation ?? null, proof);
356
+ // The first look at the proof starts once nothing can refuse the gateway;
357
+ // a gateway built to replace another takes the proof over at the swap.
358
+ if (proof !== null && !proof.takesOver)
359
+ proof.monitor.start();
252
360
  return gateway;
253
361
  }
362
+ /**
363
+ * The upstream's proof, when the configuration requires one: a check of its
364
+ * own and a monitor, pending until it looks or takes over from the gateway
365
+ * this one replaces (`takeOver`).
366
+ */
367
+ static upstreamProof(config, dependencies, security, clock, takesOver) {
368
+ if (!config.upstream.proofRequired || config.hostedTenant === null)
369
+ return null;
370
+ const binding = {
371
+ tenant: config.hostedTenant,
372
+ org: config.authority.tenantId,
373
+ origin: new URL(config.upstream.url).origin,
374
+ };
375
+ const check = new UpstreamProofCheck(binding, {
376
+ resolveTxt: dependencies.upstreamResolveTxt ?? Gateway.systemTxt(),
377
+ ...(dependencies.upstreamFetch === undefined
378
+ ? {}
379
+ : { transport: dependencies.upstreamFetch }),
380
+ ...(dependencies.upstreamResolve === undefined
381
+ ? {}
382
+ : { resolve: dependencies.upstreamResolve }),
383
+ });
384
+ const monitor = new UpstreamProofMonitor({
385
+ origin: binding.origin,
386
+ check: () => check.check(),
387
+ report: (event) => security.emit(event),
388
+ clock,
389
+ random: Math.random,
390
+ });
391
+ return { binding, check, monitor, takesOver };
392
+ }
393
+ /** TXT through the system's resolver, bounded, so a check never waits on DNS for long. */
394
+ static systemTxt() {
395
+ const resolver = new Resolver({ timeout: 2_000, tries: 2 });
396
+ return (name) => resolver.resolveTxt(name);
397
+ }
254
398
  get authorityLabel() {
255
399
  return this.demo !== null
256
400
  ? "local/demo (synthetic policy on loopback; not Decionis)"
@@ -370,8 +514,113 @@ export class Gateway {
370
514
  activation: this.activation.snapshot(),
371
515
  surface: this.surface,
372
516
  shadow: this.shadow === null ? null : this.ledger.summary(),
517
+ hosted: this.config.hosted
518
+ ? {
519
+ tenant: this.config.hostedTenant,
520
+ tenant_keys: this.admitted.map(shortDigest),
521
+ registry: this.registry,
522
+ upstream_proof: this.proof?.monitor.snapshot() ?? null,
523
+ }
524
+ : null,
373
525
  };
374
526
  }
527
+ /** The tenant keys the gateway admits now, as digests. */
528
+ get tenantKeys() {
529
+ return this.admitted;
530
+ }
531
+ /**
532
+ * Replaces the tenant keys the gateway admits, at once and without a
533
+ * rebuild, so a rotation or a revocation changes nothing else: not the
534
+ * chains, the rate, the counts or what is in flight. The digests are held
535
+ * to the configuration's rule; digests that break it are refused whole,
536
+ * and the keys admitted stay as they were.
537
+ */
538
+ admitKeys(digests) {
539
+ this.admitted = GatewayConfigLoader.admittedKeys(digests, this.config.hosted);
540
+ }
541
+ /** The registry a host last loaded, and the entry this gateway was built from, for the status. */
542
+ builtFrom(source) {
543
+ this.registry = source;
544
+ }
545
+ /** What the gateway built to replace this one takes up: its chains and its funnel. */
546
+ continuation() {
547
+ return {
548
+ evidence: this.evidence,
549
+ gateway: this.chain,
550
+ security: this.security.chain,
551
+ activation: this.activation,
552
+ };
553
+ }
554
+ /**
555
+ * The swap: this gateway, built to replace `from` with its continuation,
556
+ * takes over what `from` still did itself. `from` stops persisting the
557
+ * chains' heads and looking at the upstream's proof, a look in flight
558
+ * included, and only finishes what it has in flight. The proof is taken as
559
+ * it stands now, not as it stood when this one was built: a look that ended
560
+ * while the registry was loading counts, and is reported once, by `from`;
561
+ * the last look and the next stay when they were. When `from` was bound to
562
+ * another tenant, organization or origin, this one looks from the start.
563
+ */
564
+ takeOver(from) {
565
+ from.handedOn();
566
+ const proof = this.proof;
567
+ if (proof === null || !proof.takesOver)
568
+ return;
569
+ const kept = from.proof;
570
+ if (kept !== null && sameBinding(kept.binding, proof.binding)) {
571
+ proof.monitor.resume(kept.monitor.standing());
572
+ }
573
+ else {
574
+ proof.monitor.start();
575
+ }
576
+ }
577
+ /**
578
+ * Hands on what the gateway that continues this one now does itself:
579
+ * persisting the chains' heads, and looking at the upstream's proof. This
580
+ * one goes on finishing what it has in flight. Called again, it does nothing.
581
+ */
582
+ handedOn() {
583
+ this.releaseJournal();
584
+ this.proof?.monitor.stop();
585
+ }
586
+ /**
587
+ * What the upstream's proof lets a tenant's request do now: forwarded,
588
+ * forwarded and marked missing, or refused. Always forwarded when the
589
+ * gateway requires no proof.
590
+ */
591
+ upstreamProof() {
592
+ return this.proof?.monitor.admits() ?? "FORWARD";
593
+ }
594
+ /** Whether the first look at the upstream's proof has ended, or there is none to take. */
595
+ get upstreamProofSettled() {
596
+ return this.proof?.monitor.settled ?? true;
597
+ }
598
+ /**
599
+ * The answer to an admitted request while the upstream's proof is not
600
+ * established: nothing forwarded, and the upstream named, since the gateway
601
+ * only observes and calling it directly loses nothing but the observation.
602
+ */
603
+ unverified() {
604
+ this.metrics.requests.inc({ kind: "upstream_unverified" });
605
+ this.count("upstream_unverified");
606
+ return this.own(503, {
607
+ state: "ERROR",
608
+ verdict: null,
609
+ reason_codes: ["UPSTREAM_UNVERIFIED"],
610
+ execution: "NOT_FORWARDED",
611
+ fallback: this.config.upstream.url,
612
+ }, { "retry-after": String(PROOF_PENDING_RETRY_MS / 1_000) });
613
+ }
614
+ /**
615
+ * Stops persisting the chains' heads, once the gateway that continues them
616
+ * persists them itself. A replaced gateway still finishing its requests
617
+ * links on the same chains, so its last checkpoint, at the end of its
618
+ * drain, would otherwise land after the live one's.
619
+ */
620
+ releaseJournal() {
621
+ for (const stop of this.stopFollowing.splice(0))
622
+ stop();
623
+ }
375
624
  /** The switch the shadow report ends with, for whoever renders the status elsewhere. */
376
625
  get enforcementSwitch() {
377
626
  return enforcementSwitch(this.config);
@@ -379,19 +628,13 @@ export class Gateway {
379
628
  metricsText() {
380
629
  return this.metrics.registry.render();
381
630
  }
382
- /** A request that is not consequential: forwarded unchanged, counted, not evaluated. */
631
+ /**
632
+ * A request that is not consequential: forwarded unchanged, counted, not
633
+ * evaluated, and relayed as `PASSTHROUGH`, so a caller can tell an answer
634
+ * that came through the gateway from one that never reached it.
635
+ */
383
636
  async passthrough(request) {
384
- this.metrics.requests.inc({ kind: "passthrough" });
385
- this.count("passthrough");
386
- const startedAt = this.clock();
387
- try {
388
- const result = await this.upstream.send(request.method.toUpperCase(), request.path, request.search, this.upstream.headersFor(request), request.body, this.upstream.signal());
389
- this.metrics.observeForwardLatency(this.clock() - startedAt);
390
- return { status: result.status, headers: result.headers, body: result.body };
391
- }
392
- catch (error) {
393
- return this.upstreamFailure(error);
394
- }
637
+ return await this.forwardUnchanged(request, { "agentsafe-execution": "PASSTHROUGH" });
395
638
  }
396
639
  /** A consequential request, through the whole lifecycle. */
397
640
  async govern(request, action) {
@@ -420,26 +663,70 @@ export class Gateway {
420
663
  return await this.enforce(request, captured, startedAt);
421
664
  });
422
665
  }
423
- /** What a held escalation looks like from outside; null when nothing is held under the id. */
424
- escalation(intentId) {
425
- const entry = this.held.get(intentId);
426
- if (entry === undefined)
666
+ /**
667
+ * Why a request's tenant key refuses it, or null when it admits it: always
668
+ * admitted when the gateway has no keys; otherwise only a key that hashes
669
+ * to one of them. Every configured digest is compared, in constant time,
670
+ * whether or not an earlier one matched. A refusal is counted and put on
671
+ * the security stream with its reason, never with the value presented:
672
+ * one line each up to a bound per window, and a count of the rest, so a
673
+ * flood without the key cannot grow the chained stream with its rate.
674
+ */
675
+ keyRefusal(presented) {
676
+ if (this.admitted.length === 0)
677
+ return null;
678
+ const candidate = presented === undefined || presented === ""
679
+ ? null
680
+ : createHash("sha256").update(presented, "utf8").digest();
681
+ let admitted = false;
682
+ for (const digest of this.admitted) {
683
+ const expected = Buffer.from(digest.slice("sha256:".length), "hex");
684
+ if (candidate !== null && timingSafeEqual(candidate, expected))
685
+ admitted = true;
686
+ }
687
+ if (admitted)
427
688
  return null;
428
- return this.holdBody(entry);
689
+ const refusal = candidate === null ? "TENANT_KEY_MISSING" : "TENANT_KEY_INVALID";
690
+ this.metrics.requests.inc({ kind: "tenant_key_refused" });
691
+ this.refusals.refuse(refusal);
692
+ return refusal;
693
+ }
694
+ /**
695
+ * Whether the gateway's rate admits one more request now. Taken after the
696
+ * tenant key, so only the tenant's own traffic spends the tenant's rate; a
697
+ * refusal is counted, and says when to try again.
698
+ */
699
+ rate() {
700
+ if (this.bucket === null)
701
+ return { admitted: true };
702
+ const decision = this.bucket.take();
703
+ if (!decision.admitted)
704
+ this.metrics.requests.inc({ kind: "rate_limited" });
705
+ return decision;
706
+ }
707
+ /**
708
+ * What a held escalation looks like from outside, to the caller holding its
709
+ * resume token; otherwise why not. The intent id is a correlation id, written
710
+ * to stdout and to evidence, so it is never enough on its own.
711
+ */
712
+ escalation(intentId, resumeToken) {
713
+ const entry = this.heldFor(intentId, resumeToken);
714
+ return typeof entry === "string" ? entry : this.holdBody(entry);
429
715
  }
430
716
  /**
431
717
  * Asks the authority again about a held intent. Only a fresh `ALLOW` with
432
718
  * a grant executes, once; anything else is still held or refused. The
433
719
  * gateway never turns the hold into permission on its own.
434
720
  */
435
- async resume(intentId) {
721
+ async resume(intentId, resumeToken) {
436
722
  this.metrics.requests.inc({ kind: "control" });
437
- const entry = this.held.get(intentId);
438
- if (entry === undefined) {
439
- return this.own(404, {
723
+ const entry = this.heldFor(intentId, resumeToken);
724
+ if (typeof entry === "string") {
725
+ // A wrong token leaves the hold where it is: its owner can still resume.
726
+ return this.own(entry === "ESCALATION_NOT_HELD" ? 404 : 403, {
440
727
  state: "ERROR",
441
728
  verdict: null,
442
- reason_codes: ["ESCALATION_NOT_HELD"],
729
+ reason_codes: [entry],
443
730
  execution: "NOT_FORWARDED",
444
731
  });
445
732
  }
@@ -491,12 +778,14 @@ export class Gateway {
491
778
  return await RequestContext.run({ principal: this.principalOf(entry.captured) }, () => this.execute(entry.request, entry.captured, resolution.decision, startedAt, null));
492
779
  }
493
780
  async close() {
494
- for (const stop of this.stopFollowing)
495
- stop();
781
+ this.refusals.flush();
782
+ this.handedOn();
783
+ this.proof?.check.close();
496
784
  this.held.clear();
497
785
  if (this.demo !== null)
498
786
  await this.demo.stop();
499
787
  this.secrets?.close();
788
+ this.upstream.close();
500
789
  }
501
790
  captureIntent(request, action) {
502
791
  const normalized = normalizeRequest(request, action, {
@@ -538,7 +827,20 @@ export class Gateway {
538
827
  const run = await shadow.observe(captured, () => this.upstream.send(request.method.toUpperCase(), request.path, request.search, this.upstream.headersFor(request, { "x-agent-safe-intent-hash": captured.intentHash }), request.body, this.upstream.signal()));
539
828
  this.metrics.observeForwardLatency(this.clock() - forwardStarted);
540
829
  const production = run.production;
541
- const upstreamStatus = production.status === "COMPLETED" ? production.result.status : null;
830
+ let upstreamStatus = null;
831
+ let failure = null;
832
+ let answer;
833
+ if (production.status === "COMPLETED") {
834
+ upstreamStatus = production.result.status;
835
+ answer = this.relay(production.result, {
836
+ "agentsafe-mode": "SHADOW",
837
+ "agentsafe-execution": "PASSTHROUGH",
838
+ });
839
+ }
840
+ else {
841
+ failure = this.failureOf(production.error);
842
+ answer = this.failed(failure);
843
+ }
542
844
  // The observation settles on its own bound and is reported when it does;
543
845
  // the client's response never waits for the authority.
544
846
  void run.observation.then((observation) => {
@@ -549,10 +851,14 @@ export class Gateway {
549
851
  ...this.interception(request, captured, startedAt),
550
852
  state: "SHADOW",
551
853
  verdict: observation.verdict,
552
- reason_codes: observation.status === "OBSERVED"
553
- ? observation.reasonCodes
554
- : [observation.status, ...observation.reasonCodes],
555
- execution: "PASSTHROUGH",
854
+ // A forward that failed says so after the authority's codes, and
855
+ // whether it can have reached the upstream.
856
+ reason_codes: [
857
+ ...(observation.status === "OBSERVED" ? [] : [observation.status]),
858
+ ...observation.reasonCodes,
859
+ ...(failure === null ? [] : [failure.code]),
860
+ ],
861
+ execution: failure?.execution ?? "PASSTHROUGH",
556
862
  decision_id: observation.decisionId,
557
863
  dossier_id: observation.dossierId,
558
864
  upstream_status: upstreamStatus,
@@ -561,12 +867,7 @@ export class Gateway {
561
867
  });
562
868
  this.shadowReportOnCadence();
563
869
  });
564
- if (production.status === "FAILED")
565
- return this.upstreamFailure(production.error);
566
- return this.relay(production.result, {
567
- "agentsafe-mode": "SHADOW",
568
- "agentsafe-execution": "PASSTHROUGH",
569
- });
870
+ return answer;
570
871
  }
571
872
  async enforce(request, captured, startedAt) {
572
873
  const escalation = this.resolver;
@@ -624,6 +925,9 @@ export class Gateway {
624
925
  ? ["ESCALATION_HANDOFF_UNAVAILABLE"]
625
926
  : []),
626
927
  ];
928
+ // The capability to see and resume this hold: handed to the caller whose
929
+ // request it is, once, in this response, and written nowhere else.
930
+ const resumeToken = randomBytes(32).toString("base64url");
627
931
  const entry = {
628
932
  captured,
629
933
  request,
@@ -631,6 +935,7 @@ export class Gateway {
631
935
  handoff: handoff === null ? null : { ...handoff, intent: captured.intent },
632
936
  heldAt: new Date(this.clock()).toISOString(),
633
937
  expiresAt: Date.parse(captured.intent.expiresAt),
938
+ resumeDigest: Gateway.resumeDigest(resumeToken),
634
939
  };
635
940
  const heldOk = this.hold(captured.intent.intentId, entry);
636
941
  this.link({
@@ -665,6 +970,7 @@ export class Gateway {
665
970
  dossier_id: decision.dossierId,
666
971
  escalation: entry.handoff === null ? null : this.handoffBody(entry.handoff),
667
972
  resume: heldOk ? `${GATEWAY_PREFIX}/v1/escalations/${captured.intent.intentId}` : null,
973
+ resume_token: heldOk ? resumeToken : null,
668
974
  expires_at: captured.intent.expiresAt,
669
975
  });
670
976
  }
@@ -685,7 +991,10 @@ export class Gateway {
685
991
  reason_codes: [...decision.reasonCodes],
686
992
  failure_policy: "FAIL_OPEN",
687
993
  });
688
- const forwarded = await this.passthrough(request);
994
+ const forwarded = await this.forwardUnchanged(request, {
995
+ "agentsafe-state": "AUTHORITY_UNAVAILABLE",
996
+ "agentsafe-execution": "FORWARDED_UNGOVERNED",
997
+ });
689
998
  this.report({
690
999
  ...this.interception(request, captured, startedAt),
691
1000
  state: "AUTHORITY_UNAVAILABLE",
@@ -698,14 +1007,7 @@ export class Gateway {
698
1007
  finalization: null,
699
1008
  authority_ms: authorityMs,
700
1009
  });
701
- return {
702
- ...forwarded,
703
- headers: [
704
- ...forwarded.headers,
705
- ["agentsafe-state", "AUTHORITY_UNAVAILABLE"],
706
- ["agentsafe-execution", "FORWARDED_UNGOVERNED"],
707
- ],
708
- };
1010
+ return forwarded;
709
1011
  }
710
1012
  this.report({
711
1013
  ...this.interception(request, captured, startedAt),
@@ -809,11 +1111,15 @@ export class Gateway {
809
1111
  }
810
1112
  // Blocked at the claim, or failed before anything was sent: nothing reached the upstream.
811
1113
  const reason = "reason" in outcome ? outcome.reason : "EXECUTION_BLOCKED";
1114
+ // A handler's own refusal code follows the category (PAYLOAD_BINDING_MISMATCH).
1115
+ const reasonCodes = outcome.outcome === "FAILED_BEFORE_DISPATCH" && outcome.code !== undefined
1116
+ ? [reason, outcome.code]
1117
+ : [reason];
812
1118
  const state = outcome.outcome === "BLOCKED" ? "ERROR" : "EXECUTION_FAILED";
813
1119
  this.report({
814
1120
  ...base,
815
1121
  state,
816
- reason_codes: [reason],
1122
+ reason_codes: reasonCodes,
817
1123
  execution: "NOT_FORWARDED",
818
1124
  upstream_status: null,
819
1125
  finalization,
@@ -821,7 +1127,7 @@ export class Gateway {
821
1127
  return this.own(outcome.outcome === "BLOCKED" ? 503 : 502, {
822
1128
  state,
823
1129
  verdict: "ALLOW",
824
- reason_codes: [reason],
1130
+ reason_codes: reasonCodes,
825
1131
  execution: "NOT_FORWARDED",
826
1132
  intent_id: intentId,
827
1133
  intent_hash: captured.intentHash,
@@ -838,6 +1144,30 @@ export class Gateway {
838
1144
  this.metrics.held.set(this.held.size);
839
1145
  return true;
840
1146
  }
1147
+ /**
1148
+ * The hold under an id, for the caller presenting its token. A refusal is
1149
+ * linked to the evidence stream, because a wrong token for a live hold is
1150
+ * someone who read an intent id and is not its caller.
1151
+ */
1152
+ heldFor(intentId, resumeToken) {
1153
+ this.expireHeld();
1154
+ const entry = this.held.get(intentId);
1155
+ if (entry === undefined)
1156
+ return "ESCALATION_NOT_HELD";
1157
+ if (resumeToken === null ||
1158
+ !timingSafeEqual(Gateway.resumeDigest(resumeToken), entry.resumeDigest)) {
1159
+ this.link({
1160
+ event: "ESCALATION_RESUME_REFUSED",
1161
+ intent_id: intentId,
1162
+ reason_codes: ["RESUME_TOKEN_INVALID"],
1163
+ });
1164
+ return "RESUME_TOKEN_INVALID";
1165
+ }
1166
+ return entry;
1167
+ }
1168
+ static resumeDigest(resumeToken) {
1169
+ return createHash("sha256").update(resumeToken, "utf8").digest();
1170
+ }
841
1171
  release(intentId) {
842
1172
  this.held.delete(intentId);
843
1173
  this.metrics.held.set(this.held.size);
@@ -887,6 +1217,24 @@ export class Gateway {
887
1217
  latency_ms: Math.max(this.clock() - startedAt, 0),
888
1218
  };
889
1219
  }
1220
+ /**
1221
+ * Forwards a request as it came, counted as a passthrough, and relays the
1222
+ * answer with the gateway's own headers; a failure is the gateway's own
1223
+ * response, which carries its own.
1224
+ */
1225
+ async forwardUnchanged(request, extra) {
1226
+ this.metrics.requests.inc({ kind: "passthrough" });
1227
+ this.count("passthrough");
1228
+ const startedAt = this.clock();
1229
+ try {
1230
+ const result = await this.upstream.send(request.method.toUpperCase(), request.path, request.search, this.upstream.headersFor(request), request.body, this.upstream.signal());
1231
+ this.metrics.observeForwardLatency(this.clock() - startedAt);
1232
+ return this.relay(result, extra);
1233
+ }
1234
+ catch (error) {
1235
+ return this.failed(this.failureOf(error));
1236
+ }
1237
+ }
890
1238
  relay(result, extra) {
891
1239
  return {
892
1240
  status: result.status,
@@ -894,15 +1242,68 @@ export class Gateway {
894
1242
  body: result.body,
895
1243
  };
896
1244
  }
897
- upstreamFailure(error) {
898
- const tooLarge = error instanceof Error && error.name === "UpstreamResponseTooLarge";
1245
+ /**
1246
+ * What a failed forward is. It is `NOT_FORWARDED` only when nothing of the
1247
+ * request can have been accepted: a public-only upstream resolved inward,
1248
+ * the upstream refused the handshake or its certificate did not verify,
1249
+ * or no connection was ever made. Anything else may have come after the
1250
+ * request was written, and the upstream may have acted on it, so it is
1251
+ * never a refusal a caller may retry. A timeout is one wherever the send
1252
+ * was when it ran out: the send cannot say whether it had written the
1253
+ * request. Too large is the relay's own bound or the guarded egress's just
1254
+ * outside it, whichever reader saw it first. A refused handshake is the
1255
+ * tenant's configuration, reported once as `UPSTREAM_TLS_REFUSED`.
1256
+ */
1257
+ failureOf(error) {
1258
+ if (error instanceof EgressError && error.code === "EGRESS_ADDRESS_REFUSED") {
1259
+ return { code: "UPSTREAM_ADDRESS_REFUSED", execution: "NOT_FORWARDED" };
1260
+ }
1261
+ const transport = Gateway.transportCode(error);
1262
+ const tls = transport === "EGRESS_TLS_CLIENT_CERT_REFUSED" || CLIENT_CERTIFICATE_REFUSED.test(transport)
1263
+ ? "UPSTREAM_CLIENT_CERT_REFUSED"
1264
+ : transport === "EGRESS_TLS_REJECTED" || CERTIFICATE_UNVERIFIED.test(transport)
1265
+ ? "UPSTREAM_TLS_REJECTED"
1266
+ : null;
1267
+ if (tls !== null) {
1268
+ this.security.emit({
1269
+ event: "UPSTREAM_TLS_REFUSED",
1270
+ origin: new URL(this.config.upstream.url).origin,
1271
+ code: tls,
1272
+ });
1273
+ return { code: tls, execution: "NOT_FORWARDED" };
1274
+ }
1275
+ if (BEFORE_CONNECTION.has(transport)) {
1276
+ return { code: "UPSTREAM_UNREACHABLE", execution: "NOT_FORWARDED" };
1277
+ }
1278
+ const tooLarge = (error instanceof Error && error.name === "UpstreamResponseTooLarge") ||
1279
+ transport === "EGRESS_BODY_TOO_LARGE";
1280
+ const timedOut = (error instanceof Error && error.name === "TimeoutError") || transport === "EGRESS_TIMEOUT";
1281
+ return {
1282
+ code: tooLarge
1283
+ ? "UPSTREAM_RESPONSE_TOO_LARGE"
1284
+ : timedOut
1285
+ ? "UPSTREAM_TIMEOUT"
1286
+ : "UPSTREAM_TRANSPORT_FAILED",
1287
+ execution: "INDETERMINATE",
1288
+ };
1289
+ }
1290
+ /** The gateway's own answer to a forward that failed. */
1291
+ failed(failure) {
899
1292
  return this.own(502, {
900
1293
  state: "ERROR",
901
1294
  verdict: null,
902
- reason_codes: [tooLarge ? "UPSTREAM_RESPONSE_TOO_LARGE" : "UPSTREAM_UNREACHABLE"],
903
- execution: tooLarge ? "INDETERMINATE" : "NOT_FORWARDED",
1295
+ reason_codes: [failure.code],
1296
+ execution: failure.execution,
904
1297
  });
905
1298
  }
1299
+ /** A failed send's transport code: its own, as `node:http` raises it, or its cause's, as `fetch` wraps it. */
1300
+ static transportCode(error) {
1301
+ const own = error?.code;
1302
+ if (typeof own === "string")
1303
+ return own;
1304
+ const cause = error?.cause?.code;
1305
+ return typeof cause === "string" ? cause : "";
1306
+ }
906
1307
  /** A response the gateway itself makes: JSON, protective headers, the wire version. */
907
1308
  own(status, body, headers = {}) {
908
1309
  return {
@@ -911,6 +1312,8 @@ export class Gateway {
911
1312
  ["content-type", "application/json; charset=utf-8"],
912
1313
  ["cache-control", "no-store"],
913
1314
  ["x-content-type-options", "nosniff"],
1315
+ ["content-security-policy", "default-src 'none'; frame-ancestors 'none'"],
1316
+ ["x-frame-options", "DENY"],
914
1317
  ["agentsafe-state", body.state],
915
1318
  ["agentsafe-execution", body.execution],
916
1319
  ...Object.entries(headers),