@decionis/agentsafe 0.6.0 → 0.7.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 (169) hide show
  1. package/README.md +62 -19
  2. package/dist/Cli.js +18 -1
  3. package/dist/Cli.js.map +1 -1
  4. package/dist/Index.d.ts +5 -3
  5. package/dist/Index.d.ts.map +1 -1
  6. package/dist/Index.js +3 -1
  7. package/dist/Index.js.map +1 -1
  8. package/dist/TrustedExecutor.d.ts.map +1 -1
  9. package/dist/TrustedExecutor.js +2 -0
  10. package/dist/TrustedExecutor.js.map +1 -1
  11. package/dist/adapters/mcp/McpGuard.d.ts +32 -3
  12. package/dist/adapters/mcp/McpGuard.d.ts.map +1 -1
  13. package/dist/adapters/mcp/McpGuard.js +29 -5
  14. package/dist/adapters/mcp/McpGuard.js.map +1 -1
  15. package/dist/adapters/mcp/McpIntentBinder.d.ts +18 -3
  16. package/dist/adapters/mcp/McpIntentBinder.d.ts.map +1 -1
  17. package/dist/adapters/mcp/McpIntentBinder.js +48 -1
  18. package/dist/adapters/mcp/McpIntentBinder.js.map +1 -1
  19. package/dist/adapters/mcp/McpInvocation.d.ts +9 -2
  20. package/dist/adapters/mcp/McpInvocation.d.ts.map +1 -1
  21. package/dist/adapters/mcp/McpInvocation.js.map +1 -1
  22. package/dist/cli/Actions.d.ts +14 -0
  23. package/dist/cli/Actions.d.ts.map +1 -0
  24. package/dist/cli/Actions.js +168 -0
  25. package/dist/cli/Actions.js.map +1 -0
  26. package/dist/cli/Arguments.d.ts +4 -0
  27. package/dist/cli/Arguments.d.ts.map +1 -1
  28. package/dist/cli/Arguments.js +12 -3
  29. package/dist/cli/Arguments.js.map +1 -1
  30. package/dist/cli/ConfigCommand.d.ts.map +1 -1
  31. package/dist/cli/ConfigCommand.js +5 -0
  32. package/dist/cli/ConfigCommand.js.map +1 -1
  33. package/dist/cli/Help.d.ts.map +1 -1
  34. package/dist/cli/Help.js +13 -1
  35. package/dist/cli/Help.js.map +1 -1
  36. package/dist/cli/Host.d.ts +5 -2
  37. package/dist/cli/Host.d.ts.map +1 -1
  38. package/dist/cli/Host.js +24 -2
  39. package/dist/cli/Host.js.map +1 -1
  40. package/dist/cli/Profile.d.ts +24 -0
  41. package/dist/cli/Profile.d.ts.map +1 -0
  42. package/dist/cli/Profile.js +168 -0
  43. package/dist/cli/Profile.js.map +1 -0
  44. package/dist/cli/Records.d.ts +15 -0
  45. package/dist/cli/Records.d.ts.map +1 -0
  46. package/dist/cli/Records.js +205 -0
  47. package/dist/cli/Records.js.map +1 -0
  48. package/dist/config/ConfigKeys.d.ts +2 -2
  49. package/dist/config/ConfigKeys.d.ts.map +1 -1
  50. package/dist/config/ConfigKeys.js +6 -0
  51. package/dist/config/ConfigKeys.js.map +1 -1
  52. package/dist/config/ExecutorConfig.d.ts +29 -0
  53. package/dist/config/ExecutorConfig.d.ts.map +1 -1
  54. package/dist/config/ExecutorConfig.js +53 -1
  55. package/dist/config/ExecutorConfig.js.map +1 -1
  56. package/dist/gateway/ForwardHandler.d.ts +22 -4
  57. package/dist/gateway/ForwardHandler.d.ts.map +1 -1
  58. package/dist/gateway/ForwardHandler.js +27 -10
  59. package/dist/gateway/ForwardHandler.js.map +1 -1
  60. package/dist/gateway/Gateway.d.ts +123 -3
  61. package/dist/gateway/Gateway.d.ts.map +1 -1
  62. package/dist/gateway/Gateway.js +513 -16
  63. package/dist/gateway/Gateway.js.map +1 -1
  64. package/dist/gateway/GatewayConfig.d.ts +109 -0
  65. package/dist/gateway/GatewayConfig.d.ts.map +1 -1
  66. package/dist/gateway/GatewayConfig.js +267 -9
  67. package/dist/gateway/GatewayConfig.js.map +1 -1
  68. package/dist/gateway/GatewayReport.d.ts +6 -2
  69. package/dist/gateway/GatewayReport.d.ts.map +1 -1
  70. package/dist/gateway/GatewayReport.js +3 -0
  71. package/dist/gateway/GatewayReport.js.map +1 -1
  72. package/dist/gateway/InterceptedRequest.d.ts +45 -1
  73. package/dist/gateway/InterceptedRequest.d.ts.map +1 -1
  74. package/dist/gateway/InterceptedRequest.js +43 -1
  75. package/dist/gateway/InterceptedRequest.js.map +1 -1
  76. package/dist/gateway/PolicySelector.d.ts +5 -0
  77. package/dist/gateway/PolicySelector.d.ts.map +1 -0
  78. package/dist/gateway/PolicySelector.js +9 -0
  79. package/dist/gateway/PolicySelector.js.map +1 -0
  80. package/dist/gateway/RouteTable.d.ts +44 -7
  81. package/dist/gateway/RouteTable.d.ts.map +1 -1
  82. package/dist/gateway/RouteTable.js +58 -9
  83. package/dist/gateway/RouteTable.js.map +1 -1
  84. package/dist/gateway/SubjectSessions.d.ts +113 -0
  85. package/dist/gateway/SubjectSessions.d.ts.map +1 -0
  86. package/dist/gateway/SubjectSessions.js +219 -0
  87. package/dist/gateway/SubjectSessions.js.map +1 -0
  88. package/dist/gateway/Upstream.d.ts +11 -0
  89. package/dist/gateway/Upstream.d.ts.map +1 -1
  90. package/dist/gateway/Upstream.js +19 -2
  91. package/dist/gateway/Upstream.js.map +1 -1
  92. package/dist/hosted/TenantHost.d.ts +24 -5
  93. package/dist/hosted/TenantHost.d.ts.map +1 -1
  94. package/dist/hosted/TenantHost.js +39 -10
  95. package/dist/hosted/TenantHost.js.map +1 -1
  96. package/dist/hosted/TenantRegistry.d.ts +20 -0
  97. package/dist/hosted/TenantRegistry.d.ts.map +1 -1
  98. package/dist/hosted/TenantRegistry.js +47 -1
  99. package/dist/hosted/TenantRegistry.js.map +1 -1
  100. package/dist/http/GatewayHttpServer.d.ts.map +1 -1
  101. package/dist/http/GatewayHttpServer.js +46 -2
  102. package/dist/http/GatewayHttpServer.js.map +1 -1
  103. package/dist/identity/WorkloadJwtVerifier.d.ts +13 -0
  104. package/dist/identity/WorkloadJwtVerifier.d.ts.map +1 -1
  105. package/dist/identity/WorkloadJwtVerifier.js +40 -8
  106. package/dist/identity/WorkloadJwtVerifier.js.map +1 -1
  107. package/dist/incident/HaltSwitch.d.ts +10 -2
  108. package/dist/incident/HaltSwitch.d.ts.map +1 -1
  109. package/dist/incident/HaltSwitch.js +22 -2
  110. package/dist/incident/HaltSwitch.js.map +1 -1
  111. package/dist/incident/SecurityEvents.d.ts +18 -0
  112. package/dist/incident/SecurityEvents.d.ts.map +1 -1
  113. package/dist/incident/SecurityEvents.js +17 -0
  114. package/dist/incident/SecurityEvents.js.map +1 -1
  115. package/dist/limits/HardLimits.d.ts.map +1 -1
  116. package/dist/limits/HardLimits.js.map +1 -1
  117. package/dist/outcomes/CardOutcomeEvidence.d.ts +56 -0
  118. package/dist/outcomes/CardOutcomeEvidence.d.ts.map +1 -0
  119. package/dist/outcomes/CardOutcomeEvidence.js +211 -0
  120. package/dist/outcomes/CardOutcomeEvidence.js.map +1 -0
  121. package/dist/outcomes/CardOutcomeFact.d.ts +90 -0
  122. package/dist/outcomes/CardOutcomeFact.d.ts.map +1 -0
  123. package/dist/outcomes/CardOutcomeFact.js +76 -0
  124. package/dist/outcomes/CardOutcomeFact.js.map +1 -0
  125. package/dist/outcomes/CardOutcomeLedger.d.ts +26 -0
  126. package/dist/outcomes/CardOutcomeLedger.d.ts.map +1 -0
  127. package/dist/outcomes/CardOutcomeLedger.js +31 -0
  128. package/dist/outcomes/CardOutcomeLedger.js.map +1 -0
  129. package/dist/outcomes/CardOutcomeRecorder.d.ts +35 -0
  130. package/dist/outcomes/CardOutcomeRecorder.d.ts.map +1 -0
  131. package/dist/outcomes/CardOutcomeRecorder.js +84 -0
  132. package/dist/outcomes/CardOutcomeRecorder.js.map +1 -0
  133. package/dist/outcomes/CardOutcomes.d.ts +68 -0
  134. package/dist/outcomes/CardOutcomes.d.ts.map +1 -0
  135. package/dist/outcomes/CardOutcomes.js +191 -0
  136. package/dist/outcomes/CardOutcomes.js.map +1 -0
  137. package/dist/outcomes/CoreOutcomeEvidenceClient.d.ts +54 -0
  138. package/dist/outcomes/CoreOutcomeEvidenceClient.d.ts.map +1 -0
  139. package/dist/outcomes/CoreOutcomeEvidenceClient.js +116 -0
  140. package/dist/outcomes/CoreOutcomeEvidenceClient.js.map +1 -0
  141. package/dist/outcomes/FileCardOutcomeLedger.d.ts +36 -0
  142. package/dist/outcomes/FileCardOutcomeLedger.d.ts.map +1 -0
  143. package/dist/outcomes/FileCardOutcomeLedger.js +152 -0
  144. package/dist/outcomes/FileCardOutcomeLedger.js.map +1 -0
  145. package/dist/outcomes/OutcomeEvidence.d.ts +238 -0
  146. package/dist/outcomes/OutcomeEvidence.d.ts.map +1 -0
  147. package/dist/outcomes/OutcomeEvidence.js +130 -0
  148. package/dist/outcomes/OutcomeEvidence.js.map +1 -0
  149. package/dist/outcomes/OutcomeEvidencePublisher.d.ts +81 -0
  150. package/dist/outcomes/OutcomeEvidencePublisher.d.ts.map +1 -0
  151. package/dist/outcomes/OutcomeEvidencePublisher.js +189 -0
  152. package/dist/outcomes/OutcomeEvidencePublisher.js.map +1 -0
  153. package/dist/outcomes/OutcomeEvidenceStore.d.ts +57 -0
  154. package/dist/outcomes/OutcomeEvidenceStore.d.ts.map +1 -0
  155. package/dist/outcomes/OutcomeEvidenceStore.js +191 -0
  156. package/dist/outcomes/OutcomeEvidenceStore.js.map +1 -0
  157. package/dist/service/Requests.d.ts +6 -0
  158. package/dist/service/Requests.d.ts.map +1 -1
  159. package/dist/service/Requests.js +9 -1
  160. package/dist/service/Requests.js.map +1 -1
  161. package/dist/service/TrustedExecutorService.d.ts +21 -1
  162. package/dist/service/TrustedExecutorService.d.ts.map +1 -1
  163. package/dist/service/TrustedExecutorService.js +54 -13
  164. package/dist/service/TrustedExecutorService.js.map +1 -1
  165. package/dist/verify/VerifyingProvider.d.ts +32 -6
  166. package/dist/verify/VerifyingProvider.d.ts.map +1 -1
  167. package/dist/verify/VerifyingProvider.js +16 -2
  168. package/dist/verify/VerifyingProvider.js.map +1 -1
  169. package/package.json +6 -5
@@ -1,8 +1,8 @@
1
1
  import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
2
2
  import { Resolver } from "node:dns/promises";
3
- import { appendFileSync, mkdirSync } from "node:fs";
3
+ import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
4
4
  import { join } from "node:path";
5
- import { ActionRegistry, AuditRecorder, DecionisGate, DecionisGrantVerifier, IntentCapture, SafeExecutor, ShadowPipeline, } from "@decionis/agent-safe-pipeline";
5
+ import { ActionRegistry, ApiProfiles, AuditRecorder, DecionisGate, DecionisGrantVerifier, IntentCapture, SafeExecutor, ShadowPipeline, } from "@decionis/agent-safe-pipeline";
6
6
  import { boundarySignal, resolveBoundary, } from "../boundary/BoundaryIdentity.js";
7
7
  import { DockerProvenanceProvider } from "../provenance/DockerProvenanceProvider.js";
8
8
  import { KubernetesProvenanceProvider } from "../provenance/KubernetesProvenanceProvider.js";
@@ -19,6 +19,7 @@ import { SECURITY_STREAM, SecurityEvents } from "../incident/SecurityEvents.js";
19
19
  import { LineEmitter } from "../logging/LineEmitter.js";
20
20
  import { CompositeSecretStore } from "../secrets/CompositeSecretStore.js";
21
21
  import { Redactor } from "../secrets/Redactor.js";
22
+ import { SecretError } from "../secrets/SecretStore.js";
22
23
  import { EscalationResolver } from "../service/EscalationResolver.js";
23
24
  import { ActivationFunnel } from "./Activation.js";
24
25
  import { startDemoAuthority } from "./DemoAuthority.js";
@@ -27,10 +28,12 @@ import { GatewayConfigLoader } from "./GatewayConfig.js";
27
28
  import { gatewayMetrics } from "./GatewayMetrics.js";
28
29
  import { processSurface } from "./InstallSurface.js";
29
30
  import { renderHuman, renderJson, } from "./GatewayReport.js";
30
- import { normalizeRequest } from "./InterceptedRequest.js";
31
+ import { normalizeFacts, normalizeRequest } from "./InterceptedRequest.js";
31
32
  import { TokenBucket } from "./RateLimit.js";
32
33
  import { RefusalSampler } from "./RefusalSampler.js";
33
34
  import { RouteTable } from "./RouteTable.js";
35
+ import { IssuerSubjectVerifier, MAX_SUBJECT_TOKEN_AGE_SECONDS, SubjectSessions, } from "./SubjectSessions.js";
36
+ import { WorkloadJwtVerifier } from "../identity/WorkloadJwtVerifier.js";
34
37
  import { enforcementSwitch, ShadowLedger } from "./ShadowLedger.js";
35
38
  import { PROOF_PENDING_RETRY_MS, sameBinding, UpstreamProofCheck, UpstreamProofMonitor, } from "./UpstreamProof.js";
36
39
  /**
@@ -110,8 +113,23 @@ export class Gateway {
110
113
  boundary;
111
114
  workload;
112
115
  proof;
116
+ sessions;
117
+ jwks;
113
118
  held = new Map();
119
+ /**
120
+ * For each governed request whose operation names where the subject sits
121
+ * in its answer: the session and operation the answer is checked against,
122
+ * wherever it is relayed (enforced, observed in shadow, forwarded failing
123
+ * open, or after a resumed escalation, which holds the same request).
124
+ */
125
+ answerScopes = new WeakMap();
114
126
  holder = new RequestHolder();
127
+ /**
128
+ * The key of the facts-only request digest: made here, held only here, so
129
+ * the digest an authority receives confirms nothing about the request to
130
+ * anyone else. A held escalation is resumed by this same gateway.
131
+ */
132
+ digestKey = randomBytes(32);
115
133
  capture;
116
134
  executor;
117
135
  shadow;
@@ -127,7 +145,7 @@ export class Gateway {
127
145
  /** The tenant keys admitted now: the configuration's, until a host replaces them in place. */
128
146
  admitted;
129
147
  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) {
148
+ constructor(config, upstream, routes, audit, gate, verifier, metrics, emitLine, io, security, secrets, demo, journal, evidence, chain, clock, version, surface, boundary, workload, activation, proof, sessions, jwks) {
131
149
  this.config = config;
132
150
  this.upstream = upstream;
133
151
  this.routes = routes;
@@ -145,6 +163,8 @@ export class Gateway {
145
163
  this.boundary = boundary;
146
164
  this.workload = workload;
147
165
  this.proof = proof;
166
+ this.sessions = sessions;
167
+ this.jwks = jwks;
148
168
  this.lastShadowReportAt = clock();
149
169
  this.admitted = config.tenantKeys;
150
170
  this.capture = new IntentCapture({ audit, ttlSeconds: config.intentTtlSeconds });
@@ -155,7 +175,7 @@ export class Gateway {
155
175
  this.activation =
156
176
  activation ??
157
177
  new ActivationFunnel((milestone, at) => this.report({ event: "ACTIVATION", milestone, at }), clock);
158
- const registry = registerHttpActions(new ActionRegistry(), routes.actions(), httpForwardHandler(upstream, this.holder));
178
+ const registry = registerHttpActions(new ActionRegistry(), routes.actions(), httpForwardHandler(upstream, this.holder, this.digestKey));
159
179
  // The executor refuses an intent captured through another boundary: an
160
180
  // authority issued at one door is not presentable at the next.
161
181
  this.executor = new SafeExecutor(registry, verifier, audit, {
@@ -218,7 +238,17 @@ export class Gateway {
218
238
  const securityHead = security.chain.head.seq;
219
239
  emitter.reportRedactions((patterns) => security.emit({ event: "LEAK_SUSPECTED", patterns: [...patterns] }));
220
240
  if (store === null && config.secrets.required.length > 0) {
221
- store = CompositeSecretStore.fromEnvironment(env, config.secrets.required, {
241
+ // The upstream credential is opened from the file the configuration
242
+ // names, and from nowhere else: never a value in the environment.
243
+ const credential = config.upstream.credential;
244
+ const secretEnvironment = credential === null
245
+ ? env
246
+ : {
247
+ ...env,
248
+ DOWNSTREAM_CREDENTIAL: undefined,
249
+ DOWNSTREAM_CREDENTIAL_FILE: credential.file,
250
+ };
251
+ store = CompositeSecretStore.fromEnvironment(secretEnvironment, config.secrets.required, {
222
252
  events: security,
223
253
  production: config.production,
224
254
  enforcePermissions: config.production,
@@ -229,6 +259,19 @@ export class Gateway {
229
259
  });
230
260
  }
231
261
  const secrets = store;
262
+ if (config.upstream.credential !== null) {
263
+ // The value travels as one header, so it is checked once here: a
264
+ // gateway that could not send it refuses to start rather than fail
265
+ // each request after its grant was claimed.
266
+ if (secrets === null || !secrets.has("DOWNSTREAM_CREDENTIAL")) {
267
+ throw new SecretError("CONFIG_SECRET_MISSING", "DOWNSTREAM_CREDENTIAL");
268
+ }
269
+ secrets.get("DOWNSTREAM_CREDENTIAL").use((value) => {
270
+ if (!Upstream.isHeaderValue(value.toString("utf8"))) {
271
+ throw new SecretError("CONFIG_SECRET_INVALID", "DOWNSTREAM_CREDENTIAL");
272
+ }
273
+ });
274
+ }
232
275
  const demo = config.authority.kind === "LOCAL"
233
276
  ? await (dependencies.demoAuthority ?? startDemoAuthority)()
234
277
  : null;
@@ -315,9 +358,18 @@ export class Gateway {
315
358
  fetch: upstreamGuard?.fetch ?? dependencies.upstreamFetch ?? fetch,
316
359
  hostOnlyCookies: config.hosted,
317
360
  sandboxed: config.hosted,
361
+ ...(config.upstream.credential === null || secrets === null
362
+ ? {}
363
+ : {
364
+ credential: {
365
+ header: config.upstream.credential.header,
366
+ // Read at the moment of use, so a rotated file takes effect at once.
367
+ value: () => secrets.get("DOWNSTREAM_CREDENTIAL").use((value) => value.toString("utf8")),
368
+ },
369
+ }),
318
370
  ...(upstreamGuard === null ? {} : { close: () => upstreamGuard.close() }),
319
371
  });
320
- const routes = new RouteTable(config.interception.routes, config.interception.unmatched, config.interception.http);
372
+ const routes = new RouteTable(config.interception.routes, config.interception.unmatched, config.interception.http, config.interception.profile === null ? null : ApiProfiles.get(config.interception.profile), config.interception.privacy, Gateway.readPolicy(config));
321
373
  const evidence = takeUp(EVIDENCE_STREAM, continues?.evidence);
322
374
  const chain = takeUp(GATEWAY_STREAM, continues?.gateway);
323
375
  const audit = new AuditRecorder({
@@ -342,6 +394,10 @@ export class Gateway {
342
394
  ];
343
395
  const workload = resolveWorkload(dependencies.provenance ?? providers, { env });
344
396
  const proof = Gateway.upstreamProof(config, dependencies, security, clock, continues !== null);
397
+ const jwks = await Gateway.subjectKeys(config, dependencies, security);
398
+ const sessions = config.subject === null || jwks === null
399
+ ? null
400
+ : new SubjectSessions(new IssuerSubjectVerifier(jwks, config.subject.issuer, config.subject.claim), { ttlSeconds: config.subject.sessionTtlSeconds, clock });
345
401
  // A chain that does not start at genesis says where it was taken up, once
346
402
  // nothing is left that can refuse the gateway.
347
403
  for (const [stream, head] of [
@@ -352,7 +408,8 @@ export class Gateway {
352
408
  if (head > 0)
353
409
  security.emit({ event: "CHAIN_RESUMED", chain: stream, head });
354
410
  }
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);
411
+ 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, sessions, jwks);
412
+ jwks?.start();
356
413
  // The first look at the proof starts once nothing can refuse the gateway;
357
414
  // a gateway built to replace another takes the proof over at the swap.
358
415
  if (proof !== null && !proof.takesOver)
@@ -390,6 +447,69 @@ export class Gateway {
390
447
  });
391
448
  return { binding, check, monitor, takesOver };
392
449
  }
450
+ /** What the gateway does with reads: checked only when it pins subjects. */
451
+ static readPolicy(config) {
452
+ if (config.subject === null)
453
+ return "PASSTHROUGH";
454
+ return config.interception.refuseUnknownReads ? "REFUSE_UNKNOWN" : "CHECK";
455
+ }
456
+ /**
457
+ * The identity provider's key set, when the gateway pins subjects: the file
458
+ * when there is one, else one fetch from the address at start, refused by
459
+ * name when it fails; refreshed from the address through the guarded
460
+ * egress, sealed to its origin, with the last good set kept on a failure.
461
+ */
462
+ static async subjectKeys(config, dependencies, security) {
463
+ const subject = config.subject;
464
+ if (subject === null)
465
+ return null;
466
+ const egress = subject.jwksUrl === null
467
+ ? null
468
+ : new GuardedFetch({
469
+ policy: new EgressPolicy([
470
+ { origin: new URL(subject.jwksUrl).origin, pathPrefixes: ["/"], ca: null, pins: [] },
471
+ ]),
472
+ events: security,
473
+ maxResponseBytes: 256 * 1024,
474
+ ...(dependencies.subjectJwksFetch === undefined
475
+ ? {}
476
+ : { transport: dependencies.subjectJwksFetch }),
477
+ });
478
+ const refresh = egress === null || subject.jwksUrl === null
479
+ ? undefined
480
+ : { url: subject.jwksUrl, fetch: egress.fetch, intervalSeconds: 300, events: security };
481
+ let text = null;
482
+ if (subject.jwksFile !== null) {
483
+ try {
484
+ text = readFileSync(subject.jwksFile, "utf8");
485
+ }
486
+ catch {
487
+ throw new Error("JWKS_UNAVAILABLE: subject.jwksFile");
488
+ }
489
+ }
490
+ else if (refresh !== undefined) {
491
+ try {
492
+ const response = await refresh.fetch(refresh.url, {
493
+ method: "GET",
494
+ headers: { accept: "application/json" },
495
+ signal: AbortSignal.timeout(10_000),
496
+ });
497
+ text = response.status === 200 ? await response.text() : null;
498
+ }
499
+ catch {
500
+ text = null;
501
+ }
502
+ if (text === null)
503
+ throw new Error("JWKS_UNAVAILABLE: subject.jwksUrl");
504
+ }
505
+ return new WorkloadJwtVerifier({
506
+ audiences: [subject.audience],
507
+ keys: WorkloadJwtVerifier.parseJwks(text ?? ""),
508
+ clockToleranceSeconds: 60,
509
+ maxTokenAgeSeconds: MAX_SUBJECT_TOKEN_AGE_SECONDS,
510
+ ...(refresh === undefined ? {} : { refresh }),
511
+ });
512
+ }
393
513
  /** TXT through the system's resolver, bounded, so a check never waits on DNS for long. */
394
514
  static systemTxt() {
395
515
  const resolver = new Resolver({ timeout: 2_000, tries: 2 });
@@ -486,8 +606,22 @@ export class Gateway {
486
606
  this.shadowReport(new Date(now).toISOString());
487
607
  }
488
608
  }
489
- plan(method, path) {
490
- return this.routes.plan(method, path);
609
+ plan(method, path, search = "") {
610
+ return this.routes.plan(method, path, Gateway.queryOf(search));
611
+ }
612
+ /** A query for planning only; a name the intent contract forbids is left out, and refused later. */
613
+ static queryOf(search) {
614
+ const query = {};
615
+ for (const [key, value] of new URLSearchParams(search)) {
616
+ if (key === "__proto__" || key === "constructor" || key === "prototype")
617
+ continue;
618
+ const current = query[key];
619
+ if (current === undefined)
620
+ query[key] = value;
621
+ else
622
+ query[key] = Array.isArray(current) ? [...current, value] : [current, value];
623
+ }
624
+ return query;
491
625
  }
492
626
  readiness() {
493
627
  return {
@@ -520,6 +654,10 @@ export class Gateway {
520
654
  tenant_keys: this.admitted.map(shortDigest),
521
655
  registry: this.registry,
522
656
  upstream_proof: this.proof?.monitor.snapshot() ?? null,
657
+ dedicated: this.config.hostedDedicated,
658
+ upstream_credential: this.config.upstream.credential === null
659
+ ? null
660
+ : { header: this.config.upstream.credential.header },
523
661
  }
524
662
  : null,
525
663
  };
@@ -636,14 +774,34 @@ export class Gateway {
636
774
  async passthrough(request) {
637
775
  return await this.forwardUnchanged(request, { "agentsafe-execution": "PASSTHROUGH" });
638
776
  }
639
- /** A consequential request, through the whole lifecycle. */
777
+ /**
778
+ * A consequential request, through the whole lifecycle. When the gateway
779
+ * pins subjects, a session the request presents is resolved first: one
780
+ * that does not stand is refused before anything else, and the subject of
781
+ * one that does is stated to the authority as `session.subject`, so a
782
+ * write's policy can compare a fact with it.
783
+ */
640
784
  async govern(request, action) {
641
785
  this.metrics.requests.inc({ kind: "governed" });
642
786
  this.count("governed");
643
787
  const startedAt = this.clock();
788
+ const session = await this.sessionOf(request);
789
+ if (typeof session === "string")
790
+ return this.subjectRefused(request, action, null, session, null);
791
+ // A write whose operation names a subject is for one subject: without a
792
+ // session there is nothing to state to policy or to check its answer by.
793
+ const scoped = this.sessions === null ? null : this.scopedOperation(request, action);
794
+ if (scoped !== null) {
795
+ if (session === null) {
796
+ return this.subjectRefused(request, action, scoped.id, "SUBJECT_SESSION_REQUIRED", null);
797
+ }
798
+ if (scoped.subject?.response !== undefined) {
799
+ this.answerScopes.set(request, { session, operation: scoped.id, action });
800
+ }
801
+ }
644
802
  let captured;
645
803
  try {
646
- captured = this.captureIntent(request, action);
804
+ captured = this.captureIntent(request, action, session);
647
805
  }
648
806
  catch (error) {
649
807
  const code = error instanceof Error ? error.message : "INTENT_INVALID";
@@ -781,16 +939,31 @@ export class Gateway {
781
939
  this.refusals.flush();
782
940
  this.handedOn();
783
941
  this.proof?.check.close();
942
+ this.jwks?.stop();
784
943
  this.held.clear();
785
944
  if (this.demo !== null)
786
945
  await this.demo.stop();
787
946
  this.secrets?.close();
788
947
  this.upstream.close();
789
948
  }
790
- captureIntent(request, action) {
949
+ captureIntent(request, action, session) {
950
+ if (this.config.interception.privacy === "FACTS") {
951
+ return this.captureFacts(request, action, session);
952
+ }
953
+ const plan = this.plan(request.method, request.path, request.search);
954
+ const route = plan.kind === "GOVERN" ? plan.route : null;
955
+ // A caller of govern() cannot change the action to evade a route's
956
+ // policy pin. The HTTP listener already uses the route's action.
957
+ if (route !== null &&
958
+ (route.policyId !== undefined || route.policyVersion !== undefined) &&
959
+ route.action !== action) {
960
+ throw new Error("ROUTE_ACTION_MISMATCH");
961
+ }
791
962
  const normalized = normalizeRequest(request, action, {
792
963
  maxEmbeddedBodyBytes: this.config.interception.maxEmbeddedBodyBytes,
793
964
  principalHeader: this.config.interception.principalHeader,
965
+ ...(route?.policyId === undefined ? {} : { policyId: route.policyId }),
966
+ ...(route?.policyVersion === undefined ? {} : { policyVersion: route.policyVersion }),
794
967
  });
795
968
  const trusted = {
796
969
  tenantId: this.config.authority.tenantId,
@@ -805,6 +978,8 @@ export class Gateway {
805
978
  ...normalized.context,
806
979
  ingress: "http",
807
980
  ...(normalized.principal === null ? {} : { claimed_principal: normalized.principal }),
981
+ ...this.profileFacts(request, action),
982
+ ...Gateway.sessionContext(session),
808
983
  },
809
984
  idempotencyKey: normalized.idempotencyKey ?? randomUUID(),
810
985
  ...(normalized.correlationId === null ? {} : { correlationId: normalized.correlationId }),
@@ -815,6 +990,325 @@ export class Gateway {
815
990
  };
816
991
  return this.capture.capture(normalized.proposal, trusted);
817
992
  }
993
+ /**
994
+ * Facts-only privacy: the authority receives the profile operation that
995
+ * named the call, its path template and the facts it names, and the keyed
996
+ * digest that binds the held request. No path, query, header or body byte
997
+ * of the request is in the intent; a call the profile does not describe
998
+ * never reaches here, because the route table refused it.
999
+ */
1000
+ captureFacts(request, action, session) {
1001
+ const matched = this.profileMatch(request);
1002
+ const operation = matched === null ? null : (this.profile()?.operation(matched.operation) ?? null);
1003
+ if (matched === null || operation === null || matched.action !== action) {
1004
+ throw new Error("PROFILE_OPERATION_UNMATCHED");
1005
+ }
1006
+ const normalized = normalizeFacts(request, action, operation, this.digestKey);
1007
+ const trusted = {
1008
+ tenantId: this.config.authority.tenantId,
1009
+ actor: this.config.actor,
1010
+ downstreamTarget: {
1011
+ system: this.config.upstream.system,
1012
+ operation: action,
1013
+ environment: this.config.upstream.environment,
1014
+ endpoint: this.config.upstream.url,
1015
+ },
1016
+ context: {
1017
+ ...normalized.context,
1018
+ ingress: "http",
1019
+ ...matched.facts,
1020
+ api_profile: { id: matched.profile, operation: matched.operation },
1021
+ ...Gateway.sessionContext(session),
1022
+ },
1023
+ idempotencyKey: normalized.idempotencyKey ?? randomUUID(),
1024
+ signals: {
1025
+ boundary: boundarySignal(this.boundary),
1026
+ ...(this.workload === null ? {} : { workload: this.workload }),
1027
+ },
1028
+ };
1029
+ return this.capture.capture(normalized.proposal, trusted);
1030
+ }
1031
+ /**
1032
+ * The pinned subject as the authority reads it: the fact `session.subject`.
1033
+ * A verified claim of the identity provider, never a value of the request;
1034
+ * absent, never null, when the request presented no session.
1035
+ */
1036
+ static sessionContext(session) {
1037
+ return session === null ? {} : { session: { subject: session.subject } };
1038
+ }
1039
+ /** The session a request presents, when the gateway pins subjects; null when it presents none. */
1040
+ async sessionOf(request) {
1041
+ return this.sessions === null ? null : await this.sessions.resolve(request.headers);
1042
+ }
1043
+ /**
1044
+ * A read a profile operation names, checked against the session's subject
1045
+ * and never decided. Before it is sent: the request must present a session
1046
+ * that stands, and when the operation says where the subject sits in the
1047
+ * call, it must be the session's. After: when the operation says where the
1048
+ * subject sits in each item of a successful answer, every item must name
1049
+ * the session's subject, or the whole answer is refused and none of it is
1050
+ * relayed; nothing is filtered, since a partial answer would look complete.
1051
+ * An answer that is not a success is relayed as it came. Every refusal is
1052
+ * a reason code and a line on the gateway's evidence chain.
1053
+ */
1054
+ async check(request, operationId) {
1055
+ this.metrics.requests.inc({ kind: "checked" });
1056
+ this.count("checked");
1057
+ const profile = this.profile();
1058
+ const operation = profile?.operation(operationId) ?? null;
1059
+ if (profile === null || operation === null) {
1060
+ return this.subjectRefused(request, operationId, null, "READ_OPERATION_UNMATCHED", null);
1061
+ }
1062
+ const session = await this.sessionOf(request);
1063
+ if (session === null || typeof session === "string") {
1064
+ return this.subjectRefused(request, operation.action, operationId, session ?? "SUBJECT_SESSION_REQUIRED", null);
1065
+ }
1066
+ const query = Gateway.strictQuery(request.search);
1067
+ if (query === null) {
1068
+ return this.subjectRefused(request, operation.action, operationId, "QUERY_PARAMETER_REFUSED", session);
1069
+ }
1070
+ const matched = profile.match({ method: request.method, path: request.path, query });
1071
+ if (matched === null || matched.operation !== operationId) {
1072
+ return this.subjectRefused(request, operation.action, operationId, "READ_OPERATION_UNMATCHED", session);
1073
+ }
1074
+ const asked = profile.checkRequest(matched, query, session.subject);
1075
+ if (asked !== "MATCH") {
1076
+ return this.subjectRefused(request, operation.action, operationId, asked, session);
1077
+ }
1078
+ let result;
1079
+ try {
1080
+ result = await this.upstream.send(request.method.toUpperCase(), request.path, request.search, this.upstream.headersFor(request), request.body, this.upstream.signal());
1081
+ }
1082
+ catch (error) {
1083
+ return this.failed(this.failureOf(error));
1084
+ }
1085
+ const answered = this.answerRefusal(operationId, session, result);
1086
+ if (answered !== null) {
1087
+ return this.subjectRefused(request, operation.action, operationId, answered, session, result.status);
1088
+ }
1089
+ return this.relay(result, {
1090
+ "agentsafe-execution": "PASSTHROUGH",
1091
+ "agentsafe-subject": "CHECKED",
1092
+ });
1093
+ }
1094
+ /**
1095
+ * Why a successful answer may not be relayed for this session, or null when
1096
+ * it may: every item the operation's response pointer reaches must name the
1097
+ * session's subject, and beside a list only the envelope's keys may stand.
1098
+ * An answer that is not a success is relayed as it came.
1099
+ */
1100
+ answerRefusal(operationId, session, result) {
1101
+ if (result.status < 200 || result.status >= 300)
1102
+ return null;
1103
+ let body;
1104
+ try {
1105
+ body =
1106
+ result.body.length === 0
1107
+ ? undefined
1108
+ : JSON.parse(result.body.toString("utf8"));
1109
+ }
1110
+ catch {
1111
+ body = undefined;
1112
+ }
1113
+ const answered = this.profile()?.checkResponse(operationId, body, session.subject) ?? null;
1114
+ return answered === null || answered === "MATCH" ? null : answered;
1115
+ }
1116
+ /**
1117
+ * A forwarded answer, relayed: as it came, or, when the request's operation
1118
+ * names where the subject sits in its answer and the answer names another
1119
+ * subject, withheld. The effect, if any, has happened; the response says
1120
+ * the call reached the upstream (`WITHHELD`) and with what status, so a
1121
+ * caller never takes it for a call that was not made.
1122
+ */
1123
+ answer(request, result, extra) {
1124
+ const scope = this.answerScopes.get(request);
1125
+ const refused = scope === undefined ? null : this.answerRefusal(scope.operation, scope.session, result);
1126
+ if (scope !== undefined && refused !== null) {
1127
+ return this.subjectRefused(request, scope.action, scope.operation, refused, scope.session, result.status);
1128
+ }
1129
+ return this.relay(result, extra);
1130
+ }
1131
+ /** The profile operation that named a governed call, when it names a subject; else null. */
1132
+ scopedOperation(request, action) {
1133
+ const matched = this.profileMatch(request);
1134
+ if (matched === null || matched.action !== action)
1135
+ return null;
1136
+ const operation = this.profile()?.operation(matched.operation) ?? null;
1137
+ return operation?.subject === undefined ? null : operation;
1138
+ }
1139
+ /**
1140
+ * A checked read's query, decoded as RFC 3986 writes it: each name and
1141
+ * value percent-decoded once, and a `+` refused rather than read as a space
1142
+ * or a plus, since an upstream may read it either way and a subject check
1143
+ * must see what the upstream sees. Null when a component does not decode,
1144
+ * holds a `+`, or is a name the intent contract forbids.
1145
+ */
1146
+ static strictQuery(search) {
1147
+ const query = {};
1148
+ const text = search.startsWith("?") ? search.slice(1) : search;
1149
+ for (const pair of text.split("&")) {
1150
+ if (pair === "")
1151
+ continue;
1152
+ if (pair.includes("+"))
1153
+ return null;
1154
+ const at = pair.indexOf("=");
1155
+ let name;
1156
+ let value;
1157
+ try {
1158
+ name = decodeURIComponent(at === -1 ? pair : pair.slice(0, at));
1159
+ value = at === -1 ? "" : decodeURIComponent(pair.slice(at + 1));
1160
+ }
1161
+ catch {
1162
+ return null;
1163
+ }
1164
+ if (name === "__proto__" || name === "constructor" || name === "prototype")
1165
+ return null;
1166
+ const current = query[name];
1167
+ query[name] =
1168
+ current === undefined
1169
+ ? value
1170
+ : Array.isArray(current)
1171
+ ? [...current, value]
1172
+ : [current, value];
1173
+ }
1174
+ return query;
1175
+ }
1176
+ /**
1177
+ * RFC 8693 token exchange at the gateway: the identity provider's subject
1178
+ * token in, a session token for this gateway out. The answer is the RFC's,
1179
+ * never cached; issuing and refusing are both lines on the evidence chain,
1180
+ * with the session's short digest and never a token or the subject.
1181
+ */
1182
+ async exchange(form) {
1183
+ this.metrics.requests.inc({ kind: "control" });
1184
+ if (this.sessions === null) {
1185
+ return this.oauth(404, {
1186
+ error: "invalid_request",
1187
+ error_description: "SUBJECT_NOT_CONFIGURED",
1188
+ });
1189
+ }
1190
+ const answer = await this.sessions.exchange(form);
1191
+ if (answer.status === 200) {
1192
+ this.link({
1193
+ event: "SUBJECT_SESSION_ISSUED",
1194
+ session: answer.session.id,
1195
+ expires_at: new Date(answer.session.expiresAt).toISOString(),
1196
+ });
1197
+ return this.oauth(200, answer.body);
1198
+ }
1199
+ this.link({
1200
+ event: "SUBJECT_SESSION_REFUSED",
1201
+ reason_codes: [answer.body.error_description],
1202
+ });
1203
+ return this.oauth(answer.status, answer.body);
1204
+ }
1205
+ /** An OAuth token endpoint's answer: JSON, never stored by anything between. */
1206
+ oauth(status, body) {
1207
+ return {
1208
+ status,
1209
+ headers: [
1210
+ ["content-type", "application/json; charset=utf-8"],
1211
+ ["cache-control", "no-store"],
1212
+ ["pragma", "no-cache"],
1213
+ ["x-content-type-options", "nosniff"],
1214
+ ],
1215
+ body: Buffer.from(JSON.stringify(body), "utf8"),
1216
+ };
1217
+ }
1218
+ /**
1219
+ * A subject refusal: the gateway's own answer, a report line and a line on
1220
+ * the evidence chain naming the operation, the reason and the session by
1221
+ * its short digest. `WITHHELD`, with the upstream's status, when the call
1222
+ * reached the upstream and its answer was not relayed; `NOT_FORWARDED`
1223
+ * otherwise.
1224
+ */
1225
+ subjectRefused(request, action, operation, code, session, upstreamStatus = null) {
1226
+ const execution = upstreamStatus === null ? "NOT_FORWARDED" : "WITHHELD";
1227
+ const status = code === "SUBJECT_TOKEN_AMBIGUOUS"
1228
+ ? 400
1229
+ : code === "SUBJECT_SESSION_REQUIRED" ||
1230
+ code === "SUBJECT_SESSION_INVALID" ||
1231
+ code === "SUBJECT_TOKEN_INVALID"
1232
+ ? 401
1233
+ : 403;
1234
+ this.metrics.requests.inc({ kind: "subject_refused" });
1235
+ this.count("subject_refused");
1236
+ this.link({
1237
+ event: "SUBJECT_REFUSED",
1238
+ operation,
1239
+ reason_codes: [code],
1240
+ session: session?.id ?? null,
1241
+ execution,
1242
+ });
1243
+ this.report({
1244
+ event: "INTERCEPTED",
1245
+ at: new Date(this.clock()).toISOString(),
1246
+ method: request.method.toUpperCase(),
1247
+ path: request.path,
1248
+ action,
1249
+ state: "REFUSED",
1250
+ verdict: null,
1251
+ reason_codes: [code],
1252
+ execution,
1253
+ mode: this.config.authority.mode,
1254
+ authority: this.demo === null ? "decionis" : "local/demo",
1255
+ intent_id: null,
1256
+ intent_hash: null,
1257
+ decision_id: null,
1258
+ dossier_id: null,
1259
+ upstream_status: upstreamStatus,
1260
+ finalization: null,
1261
+ latency_ms: 0,
1262
+ authority_ms: null,
1263
+ });
1264
+ return this.own(status, {
1265
+ state: "REFUSED",
1266
+ verdict: null,
1267
+ reason_codes: [code],
1268
+ execution,
1269
+ ...(upstreamStatus === null ? {} : { upstream_status: upstreamStatus }),
1270
+ }, status === 401 ? { "www-authenticate": "AgentSafe-Session" } : {});
1271
+ }
1272
+ /**
1273
+ * The facts the gateway's API profile names for this call, when the profile
1274
+ * named its action: each at the top level of the trusted context, beside the
1275
+ * operation, exactly as a native executor reading the same profile states
1276
+ * them. The body is read for facts whether or not it is embedded.
1277
+ */
1278
+ profileFacts(request, action) {
1279
+ const matched = this.profileMatch(request);
1280
+ if (matched === null || matched.action !== action)
1281
+ return {};
1282
+ return {
1283
+ ...matched.facts,
1284
+ api_profile: { id: matched.profile, operation: matched.operation },
1285
+ };
1286
+ }
1287
+ profile() {
1288
+ const profileId = this.config.interception.profile;
1289
+ return profileId === null ? null : ApiProfiles.get(profileId);
1290
+ }
1291
+ /** What the gateway's API profile says about a call, its JSON body read when there is one. */
1292
+ profileMatch(request) {
1293
+ const profile = this.profile();
1294
+ if (profile === null)
1295
+ return null;
1296
+ let body;
1297
+ if (request.body.length > 0 && /json/i.test(request.headers["content-type"] ?? "")) {
1298
+ try {
1299
+ body = JSON.parse(request.body.toString("utf8"));
1300
+ }
1301
+ catch {
1302
+ body = undefined;
1303
+ }
1304
+ }
1305
+ return profile.match({
1306
+ method: request.method,
1307
+ path: request.path,
1308
+ query: Gateway.queryOf(request.search),
1309
+ ...(body === undefined ? {} : { body }),
1310
+ });
1311
+ }
818
1312
  principalOf(captured) {
819
1313
  const claimed = captured.intent.context["claimed_principal"];
820
1314
  return typeof claimed === "string" ? claimed : this.config.actor.id;
@@ -832,7 +1326,7 @@ export class Gateway {
832
1326
  let answer;
833
1327
  if (production.status === "COMPLETED") {
834
1328
  upstreamStatus = production.result.status;
835
- answer = this.relay(production.result, {
1329
+ answer = this.answer(request, production.result, {
836
1330
  "agentsafe-mode": "SHADOW",
837
1331
  "agentsafe-execution": "PASSTHROUGH",
838
1332
  });
@@ -1066,7 +1560,10 @@ export class Gateway {
1066
1560
  upstream_status: outcome.result.status,
1067
1561
  finalization,
1068
1562
  });
1069
- return this.relay(outcome.result, { ...evidenceHeaders, "agentsafe-execution": "FORWARDED" });
1563
+ return this.answer(request, outcome.result, {
1564
+ ...evidenceHeaders,
1565
+ "agentsafe-execution": "FORWARDED",
1566
+ });
1070
1567
  }
1071
1568
  if (outcome.outcome === "DEFINITELY_NOT_EXECUTED" && forward.response !== null) {
1072
1569
  this.report({
@@ -1229,7 +1726,7 @@ export class Gateway {
1229
1726
  try {
1230
1727
  const result = await this.upstream.send(request.method.toUpperCase(), request.path, request.search, this.upstream.headersFor(request), request.body, this.upstream.signal());
1231
1728
  this.metrics.observeForwardLatency(this.clock() - startedAt);
1232
- return this.relay(result, extra);
1729
+ return this.answer(request, result, extra);
1233
1730
  }
1234
1731
  catch (error) {
1235
1732
  return this.failed(this.failureOf(error));