@astrasyncai/verification-gateway 5.4.0 → 5.4.2

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 (133) hide show
  1. package/dist/adapter-interface/interface.d.mts +2 -3
  2. package/dist/adapter-interface/interface.d.ts +2 -3
  3. package/dist/adapters/express.d.mts +63 -4
  4. package/dist/adapters/express.d.ts +63 -4
  5. package/dist/adapters/express.js +9 -2
  6. package/dist/adapters/express.js.map +1 -1
  7. package/dist/adapters/express.mjs +9 -2
  8. package/dist/adapters/express.mjs.map +1 -1
  9. package/dist/adapters/mcp.d.mts +396 -4
  10. package/dist/adapters/mcp.d.ts +396 -4
  11. package/dist/adapters/mcp.js +9 -2
  12. package/dist/adapters/mcp.js.map +1 -1
  13. package/dist/adapters/mcp.mjs +9 -2
  14. package/dist/adapters/mcp.mjs.map +1 -1
  15. package/dist/adapters/nextjs.d.mts +22 -4
  16. package/dist/adapters/nextjs.d.ts +22 -4
  17. package/dist/adapters/nextjs.js +9 -2
  18. package/dist/adapters/nextjs.js.map +1 -1
  19. package/dist/adapters/nextjs.mjs +9 -2
  20. package/dist/adapters/nextjs.mjs.map +1 -1
  21. package/dist/adapters/sdk.d.mts +157 -3
  22. package/dist/adapters/sdk.d.ts +157 -3
  23. package/dist/adapters/sdk.js +35 -15
  24. package/dist/adapters/sdk.js.map +1 -1
  25. package/dist/adapters/sdk.mjs +35 -15
  26. package/dist/adapters/sdk.mjs.map +1 -1
  27. package/dist/agent/index.d.mts +224 -3
  28. package/dist/agent/index.d.ts +224 -3
  29. package/dist/agent/index.js +1 -1
  30. package/dist/agent/index.js.map +1 -1
  31. package/dist/agent/index.mjs +1 -1
  32. package/dist/agent/index.mjs.map +1 -1
  33. package/dist/bin/astrasync-claude-hook.js +9 -2
  34. package/dist/bin/astrasync-codex-hook.js +9 -2
  35. package/dist/bin/astrasync-guard.js +9 -2
  36. package/dist/bin/astrasync.js +9 -2
  37. package/dist/browser/background.js +9 -2
  38. package/dist/browser/background.js.map +1 -1
  39. package/dist/browser/background.mjs +9 -2
  40. package/dist/browser/background.mjs.map +1 -1
  41. package/dist/browser/browser-adapter.d.mts +1 -5
  42. package/dist/browser/browser-adapter.d.ts +1 -5
  43. package/dist/claude-code/claude-code-adapter.d.mts +1 -5
  44. package/dist/claude-code/claude-code-adapter.d.ts +1 -5
  45. package/dist/cli/index.d.mts +1 -5
  46. package/dist/cli/index.d.ts +1 -5
  47. package/dist/cli/index.js +1 -1
  48. package/dist/cli/index.js.map +1 -1
  49. package/dist/cli/index.mjs +1 -1
  50. package/dist/cli/index.mjs.map +1 -1
  51. package/dist/codex/index.d.mts +1 -5
  52. package/dist/codex/index.d.ts +1 -5
  53. package/dist/codex/index.js +9 -2
  54. package/dist/codex/index.js.map +1 -1
  55. package/dist/codex/index.mjs +9 -2
  56. package/dist/codex/index.mjs.map +1 -1
  57. package/dist/cursor/cursor-adapter.d.mts +1 -5
  58. package/dist/cursor/cursor-adapter.d.ts +1 -5
  59. package/dist/cursor/extension.d.mts +1 -5
  60. package/dist/cursor/extension.d.ts +1 -5
  61. package/dist/cursor/extension.js +9 -2
  62. package/dist/cursor/extension.js.map +1 -1
  63. package/dist/cursor/extension.mjs +9 -2
  64. package/dist/cursor/extension.mjs.map +1 -1
  65. package/dist/edge-config.d.mts +1 -1
  66. package/dist/edge-config.d.ts +1 -1
  67. package/dist/edge-config.js +1 -1
  68. package/dist/edge-config.js.map +1 -1
  69. package/dist/edge-config.mjs +1 -1
  70. package/dist/edge-config.mjs.map +1 -1
  71. package/dist/edge-core/index.d.mts +1 -1
  72. package/dist/edge-core/index.d.ts +1 -1
  73. package/dist/edge-core/index.js +9 -2
  74. package/dist/edge-core/index.js.map +1 -1
  75. package/dist/edge-core/index.mjs +9 -2
  76. package/dist/edge-core/index.mjs.map +1 -1
  77. package/dist/gateway/gateway.d.mts +2 -3
  78. package/dist/gateway/gateway.d.ts +2 -3
  79. package/dist/gateway/gateway.js +9 -2
  80. package/dist/gateway/gateway.js.map +1 -1
  81. package/dist/gateway/gateway.mjs +9 -2
  82. package/dist/gateway/gateway.mjs.map +1 -1
  83. package/dist/git-trigger/git-hooks.d.mts +253 -3
  84. package/dist/git-trigger/git-hooks.d.ts +253 -3
  85. package/dist/index.d.mts +4506 -42
  86. package/dist/index.d.ts +4506 -42
  87. package/dist/index.js +35 -15
  88. package/dist/index.js.map +1 -1
  89. package/dist/index.mjs +35 -15
  90. package/dist/index.mjs.map +1 -1
  91. package/dist/interface-q1WrMsB1.d.mts +365 -0
  92. package/dist/interface-q1WrMsB1.d.ts +365 -0
  93. package/dist/local-evaluator/evaluator.d.mts +2 -3
  94. package/dist/local-evaluator/evaluator.d.ts +2 -3
  95. package/dist/registration/index.js +1 -1
  96. package/dist/registration/index.js.map +1 -1
  97. package/dist/registration/index.mjs +1 -1
  98. package/dist/registration/index.mjs.map +1 -1
  99. package/dist/transport/index.d.mts +1324 -4
  100. package/dist/transport/index.d.ts +1324 -4
  101. package/dist/transport/index.js +1 -1
  102. package/dist/transport/index.js.map +1 -1
  103. package/dist/transport/index.mjs +1 -1
  104. package/dist/transport/index.mjs.map +1 -1
  105. package/dist/{types-DGh2akuh.d.ts → types-BRz2U0Pn.d.ts} +2 -2
  106. package/dist/{types-76TB0fxW.d.ts → types-BU04qAAR.d.mts} +59 -213
  107. package/dist/{types-CD1F9fmp.d.mts → types-BU04qAAR.d.ts} +59 -213
  108. package/dist/types-Bd2O3eX1.d.mts +769 -0
  109. package/dist/types-BfILnheI.d.mts +189 -0
  110. package/dist/types-BfILnheI.d.ts +189 -0
  111. package/dist/{types-z_RNjHWm.d.mts → types-CfBpm3w5.d.mts} +2 -2
  112. package/dist/types-DMChboN_.d.ts +769 -0
  113. package/dist/ui/index.d.mts +1 -2
  114. package/dist/ui/index.d.ts +1 -2
  115. package/dist/verify.d.mts +1 -1
  116. package/dist/verify.d.ts +1 -1
  117. package/dist/verify.js +9 -2
  118. package/dist/verify.js.map +1 -1
  119. package/dist/verify.mjs +9 -2
  120. package/dist/verify.mjs.map +1 -1
  121. package/package.json +1 -1
  122. package/dist/express-BIAT2pe0.d.mts +0 -69
  123. package/dist/express-D3Tf-b23.d.ts +0 -69
  124. package/dist/index-BVJkTyIF.d.mts +0 -248
  125. package/dist/index-By021oSN.d.mts +0 -1469
  126. package/dist/index-DaMXZabg.d.ts +0 -248
  127. package/dist/index-iJ9_DdLk.d.ts +0 -1469
  128. package/dist/mcp-BqfTDZLh.d.mts +0 -397
  129. package/dist/mcp-OrVOrH-s.d.ts +0 -397
  130. package/dist/nextjs-DGJXzWst.d.mts +0 -28
  131. package/dist/nextjs-xM-jdNrX.d.ts +0 -28
  132. package/dist/sdk-C1IOA5LE.d.ts +0 -173
  133. package/dist/sdk-C6_-6D-9.d.mts +0 -173
package/dist/index.d.ts CHANGED
@@ -1,19 +1,1449 @@
1
- import { G as GatewayConfig, s as StepUpApprovalInfo, u as StepUpOutcome, t as StepUpApprovalStatus, E as EnhancedVerificationResult, A as AccessFailure } from './types-76TB0fxW.js';
2
- export { a as AgentCredentials, b as AstraSyncCredentials, c as AttemptOutcome, d as AttemptReport, C as CallerMetadata, e as CommerceArtifactsPayload, f as CommerceShieldProps, g as ConsiderationItem, h as ConsiderationSet, i as CounterpartyType, j as ExpressMiddlewareOptions, F as FiatSettlementBinding, k as GuidanceInfo, N as NextJsMiddlewareOptions, P as PDLSSInfo, l as ProtocolTransport, R as RouteAccessConfig, m as RuntimeChallengeResult, S as SDKOptions, n as SettlementArtifact, o as SettlementArtifactBinding, p as SettlementArtifactBindingBase, q as SettlementOutcomeInfo, r as StablecoinSettlementBinding, T as TokenGuidance, v as TrustLevel, V as VerificationInterstitialProps, w as VerificationRequest, x as VerificationResult, y as VerifiedAgent, z as VerifiedDeveloper, B as VerifiedOrganization } from './types-76TB0fxW.js';
3
- export { T as TRUST_LEVEL_RANGES, g as getTrustLevel, s as sdk } from './sdk-C1IOA5LE.js';
4
- export { VerifyOptions, clearCache, extractCredentials, fetchRoutes, hasCredentials, quickVerify, reportAttempt, reportUnregisteredAttempt, verify } from './verify.js';
5
- export { e as express } from './express-D3Tf-b23.js';
6
- export { n as nextjs } from './nextjs-xM-jdNrX.js';
7
- export { aR as extractMcpCredentials, bg as setMcpMeta, b1 as transport } from './index-iJ9_DdLk.js';
8
- export { M as MCP_VERIFIED_HOP_HEADER, a as MCP_VERIFIED_HOP_MAX_AGE_MS, b as McpMiddlewareOptions, T as ToolGate, c as ToolGateConfig, V as VerifiedHopMarker, d as createMcpMiddleware, i as isVerifiedHopValidFor, f as parseVerifiedHop, s as serializeVerifiedHop } from './mcp-OrVOrH-s.js';
9
- export { AgentProtocol, AgentRecord, AstraSync, AstraSyncConfig, AstraSyncError, AuthenticationError, BuildGuidanceParams, FrameworkConfig, GuidanceEnvelope, HealthResponse, KYDRequiredError, ModelConfig, PDLSSConfig, PDLSSDuration, PDLSSLimits, PDLSSPurpose, PDLSSScope, PDLSSSelfInstantiation, PendingRegistrationResponse, PollRegistrationResult, RegisterOptions, RegisterResult, RegistrationDeniedError, RegistrationExpiredError, RegistrationResponse, RegistrationTimeoutError, VerifyResponse, WaitForApprovalOptions, buildGuidance } from './registration/index.js';
10
- export { A as AgentClient, C as ChallengeHandler, i as agent, r as recordDecision } from './index-DaMXZabg.js';
11
- export { DEFAULT_EDGE_CONFIG, EdgeConfig, EdgeMode, EdgePathRule, EdgeVerificationDepth, FetchEdgeConfigResult, FetchEdgeConfigSuccess, _resetEdgeConfigCache, degradeToObserve, fetchEdgeConfig, getEdgeConfig, isEdgeConfig, matchEdgePathRule } from './edge-config.js';
12
- export { DynamicPlatformFingerprint, PLATFORM_AGENT_SIGNATURES, PlatformAgentVendor, PlatformDetectionInput, PlatformFingerprint, PlatformSignatureDef, detectPlatformFingerprint, matchPlatformSignature } from './platform-signatures.js';
13
- export { CAPTURE_SCHEMA_VERSION, MAX_HEADERS, MAX_HEADER_VALUE_BYTES, MAX_TOTAL_BYTES, ObservedMetadata, SanitizeHeadersResult, buildSdkObservedMetadata, deriveConnectionFromHeaders, extractApiKeyFormat, extractPlatformHeaders, sanitizeHeaders } from './metadata-capture.js';
14
- import 'express';
15
- import 'next/server';
16
- import 'jose';
1
+ import { RequestHandler, Request, Response as Response$1 } from 'express';
2
+ import * as next_server from 'next/server';
3
+ import { NextRequest } from 'next/server';
4
+ import { JWK } from 'jose';
5
+
6
+ /**
7
+ * Maximal metadata capture — the shared, edge-safe sanitiser.
8
+ *
9
+ * AstraSync's thesis is total metadata capture: every header and connection
10
+ * signal an inbound agent presents is a signal we want to keep. This module is
11
+ * the ONE place that decides what is safe to store verbatim, what is a secret
12
+ * to drop, and what credential headers reduce to a safe *format prefix* (a
13
+ * platform signal, never the secret itself).
14
+ *
15
+ * It runs in three places that must agree byte-for-byte:
16
+ * - the edge adapter (`@astrasyncai/adapter-lambda`) — the richest capture
17
+ * point (full CloudFront header arrays),
18
+ * - the SDK adapters (express / nextjs) — for SDK-only merchants with no edge,
19
+ * - (indirectly) the backend, which stores whatever the above forward.
20
+ *
21
+ * Pure — no Node built-ins, no I/O — so it is safe in Lambda@Edge, the browser
22
+ * build, and Deno. Capture is cheap: at the edge and SDK it is local string
23
+ * work, and the backend stores it on a fire-and-forget event insert, so it adds
24
+ * ZERO verify-access decision latency. Detection (which few signals imply which
25
+ * vendor) is a separate, curated concern — see `platform-signatures.ts`.
26
+ */
27
+ /**
28
+ * Version of the capture semantics (what is kept, dropped, reduced, or
29
+ * derived — and under which key names).
30
+ *
31
+ * Capture semantics are FROZEN within a package major version: a given
32
+ * `schemaVersion` always means the same field vocabulary and the same
33
+ * keep/drop/reduce rules. The number bumps only on a SEMANTIC change to
34
+ * capture (a renamed key, a changed reduction rule) — never for additive
35
+ * signals, and never merely because the package version moved. To tell
36
+ * builds apart, use the `sdkVersion` already present on the verify body;
37
+ * `schemaVersion` answers the different question "how do I interpret this
38
+ * stored metadata?".
39
+ */
40
+ declare const CAPTURE_SCHEMA_VERSION = 1;
41
+ /**
42
+ * The captured, sanitised view of an inbound agent's request metadata. Attached
43
+ * to verify-access / beacon payloads as `callerMetadata.observedMetadata`.
44
+ */
45
+ interface ObservedMetadata {
46
+ /** Header name → value, secrets removed, verbatim otherwise. */
47
+ headers: Record<string, string>;
48
+ /**
49
+ * Safe key-format prefix of a credential header (e.g. `sk-ant-api03`,
50
+ * `sk-proj`, `AIza`) — a platform signal, NEVER the secret. Absent if no
51
+ * credential header was present or none matched a known format.
52
+ */
53
+ apiKeyFormat?: string;
54
+ /**
55
+ * The subset of `headers` that are known platform-signal headers
56
+ * (`openai-organization`, `x-goog-user-project`, `anthropic-version`, …),
57
+ * pulled out for convenient detection + display. Values are the same
58
+ * sanitised strings as in `headers`.
59
+ */
60
+ platformHeaders?: Record<string, string>;
61
+ /**
62
+ * Connection-layer signals (IP, ASN, country, TLS version, HTTP version,
63
+ * device class, TLS fingerprint). Edge adapters populate this from the
64
+ * platform's native connection surface — the authoritative source. SDK
65
+ * adapters populate it as a fallback via {@link deriveConnectionFromHeaders}
66
+ * when a CDN in front of the merchant injected the equivalent headers;
67
+ * absent when neither source had anything.
68
+ */
69
+ connection?: Record<string, string>;
70
+ /**
71
+ * Number of cookie pairs the caller sent. The `cookie` header VALUE is a
72
+ * secret and is always dropped; the COUNT is a client-shape signal
73
+ * (browsers carry cookies, most automation carries none) that would
74
+ * otherwise be unobservable downstream. Absent when no cookie header
75
+ * arrived.
76
+ */
77
+ cookieCount?: number;
78
+ /**
79
+ * Query-string parameter NAMES (deduped, lowercased) — values are NEVER
80
+ * captured (they routinely carry OAuth codes, tokens, and PII, and no
81
+ * deny-list is complete). Names alone fingerprint client shape. Populated
82
+ * by the edge path, which sees the raw query string.
83
+ */
84
+ queryKeys?: string[];
85
+ /**
86
+ * Version of the capture semantics this object was produced under — see
87
+ * {@link CAPTURE_SCHEMA_VERSION}. Optional for backward compatibility with
88
+ * metadata captured before the field existed.
89
+ */
90
+ schemaVersion?: number;
91
+ }
92
+ /**
93
+ * Result of sanitising a raw header map. `headers` is always present (possibly
94
+ * empty); `apiKeyFormat` / `platformHeaders` only when a signal was found.
95
+ */
96
+ interface SanitizeHeadersResult {
97
+ headers: Record<string, string>;
98
+ apiKeyFormat?: string;
99
+ platformHeaders?: Record<string, string>;
100
+ /** Cookie-pair count; the cookie value itself is always dropped. */
101
+ cookieCount?: number;
102
+ }
103
+ /** Size caps — the only guard against jsonb bloat from a hostile POST. */
104
+ declare const MAX_HEADERS = 64;
105
+ declare const MAX_HEADER_VALUE_BYTES = 1024;
106
+ declare const MAX_TOTAL_BYTES: number;
107
+ /**
108
+ * Extract the safe key-format prefix from a credential header value. Strips a
109
+ * leading `Bearer ` / `Basic ` scheme, then returns the longest known prefix
110
+ * that the (lowercased) value starts with. Returns undefined for opaque values
111
+ * (e.g. a bare UUID token) so we never guess a format we don't recognise.
112
+ */
113
+ declare function extractApiKeyFormat(rawValue: string): string | undefined;
114
+ /**
115
+ * Sanitise a raw header map for storage. Deny-lists genuine secrets, reduces
116
+ * credential headers to a safe format prefix, keeps everything else verbatim,
117
+ * and enforces the size caps that bound jsonb growth.
118
+ *
119
+ * Accepts any string→(string|string[]|undefined) map (Node's `req.headers`,
120
+ * CloudFront's flattened headers, a plain object). Multi-value headers are
121
+ * joined with `, ` per RFC 7230.
122
+ */
123
+ declare function sanitizeHeaders(raw: Record<string, string | string[] | undefined> | undefined | null): SanitizeHeadersResult;
124
+ /**
125
+ * Pull the known platform-signal headers out of an ALREADY-sanitised header
126
+ * map. `sanitizeHeaders` already computes this as a by-product; this standalone
127
+ * form is exported for call-sites (edge, tests) that hold a sanitised map and
128
+ * want only the platform subset. Never re-run over raw (unsanitised) headers.
129
+ */
130
+ declare function extractPlatformHeaders(sanitized: Record<string, string> | undefined | null): Record<string, string>;
131
+ /**
132
+ * Derive the connection-layer block from CDN-injected request headers.
133
+ *
134
+ * When a merchant's SDK-gated origin sits behind a CDN (Cloudflare, Fastly,
135
+ * Vercel, CloudFront), the CDN has already seen the connection layer and
136
+ * injected it as headers. This promotes those headers to the same
137
+ * `connection` keys the edge adapters populate natively, so SDK-only
138
+ * deployments still get IP / geo / TLS attribution. Precedence per key:
139
+ *
140
+ * - `ip`: `cf-connecting-ip` > `fastly-client-ip` > `true-client-ip` >
141
+ * `x-real-ip` > `cloudfront-viewer-address` (port stripped) > leftmost
142
+ * `x-forwarded-for`
143
+ * - `country`: `cf-ipcountry` > `x-vercel-ip-country` >
144
+ * `cloudfront-viewer-country` > `fastly-geo-country`
145
+ * - `region` / `city` / `timeZone`: Vercel then CloudFront viewer headers
146
+ * - `countryRegionName` / `asn` / `tlsVersion` / `httpVersion` /
147
+ * `metroCode` / `headerOrder` / `headerCount`: `cloudfront-viewer-*`
148
+ * - `tlsFingerprint`: `cf-ja3-hash` > `cloudfront-viewer-ja3-fingerprint`
149
+ * - `ja4`: `cf-ja4` > `cloudfront-viewer-ja4-fingerprint`
150
+ *
151
+ * All keys are additive under `schemaVersion` 1 (the frozen-capture doctrine
152
+ * bumps only for changed semantics, never for additive signals). Values are
153
+ * truncated to MAX_CONNECTION_VALUE_CHARS — the platform's hard bound.
154
+ *
155
+ * Edge adapters keep their richer native collectors — native platform
156
+ * signals are authoritative; this header derivation is the SDK-level
157
+ * fallback. Header names are matched case-insensitively. Returns undefined
158
+ * when no source header is present, so the `connection` key is simply
159
+ * omitted (matching edge behaviour).
160
+ */
161
+ declare function deriveConnectionFromHeaders(headers: Record<string, string> | undefined | null): Record<string, string> | undefined;
162
+ /**
163
+ * The FULL metadata capture for one request at an SDK adapter (express /
164
+ * nextjs / mcp): sanitised headers, the safe credential format prefix, the
165
+ * platform-signal subset, the CDN-derived connection block, and the capture
166
+ * schema version. This is the ONE builder all SDK adapters share, so their
167
+ * verify-access bodies agree byte-for-byte.
168
+ *
169
+ * Connection derivation runs over the RAW header map (pre-cap) — the size
170
+ * caps guard storage growth and must never hide a geo/IP header that
171
+ * happened to arrive late in an oversized map.
172
+ */
173
+ declare function buildSdkObservedMetadata(rawHeaders: Record<string, string | string[] | undefined> | undefined | null): ObservedMetadata;
174
+
175
+ /**
176
+ * AstraSync Universal Verification Gateway Types
177
+ *
178
+ * TypeScript type definitions for agent verification across all counterparty types.
179
+ */
180
+
181
+ /**
182
+ * Trust levels assigned to agents based on their composite trust score
183
+ */
184
+ type TrustLevel = 'BRONZE' | 'SILVER' | 'GOLD' | 'PLATINUM';
185
+ /**
186
+ * Types of counterparties that can integrate the gateway
187
+ */
188
+ type CounterpartyType = 'agent' | 'api' | 'mcp_server' | 'website' | 'other' | 'unknown';
189
+ /**
190
+ * Agent credentials extracted from request
191
+ */
192
+ interface AgentCredentials {
193
+ /** ASTRA-xxx identifier */
194
+ astraId?: string;
195
+ /** API key for authentication */
196
+ apiKey?: string;
197
+ /** JWT token */
198
+ jwt?: string;
199
+ /** Raw authorization header */
200
+ authorizationHeader?: string;
201
+ }
202
+ /**
203
+ * Configuration options for the verification gateway
204
+ */
205
+ interface GatewayConfig {
206
+ /** AstraSync API base URL */
207
+ apiBaseUrl: string;
208
+ /** API key for authenticating with AstraSync. */
209
+ apiKey?: string;
210
+ /**
211
+ * @deprecated Removed in v2.3.0 — server is the single source of truth for
212
+ * access decisions (verified ID + runtime challenge + PDLSS + trust score).
213
+ * Setting this no longer affects access decisions. If you need a higher gate
214
+ * for an endpoint, configure it server-side via the endpoint's
215
+ * `trust_score_requirement`.
216
+ */
217
+ minTrustScore?: number;
218
+ /**
219
+ * @deprecated Removed in v2.3.0 — see `minTrustScore` above.
220
+ */
221
+ minTrustScoreForFull?: number;
222
+ /** Cache verification results (TTL in seconds) */
223
+ cacheTtl?: number;
224
+ /** Enable debug logging */
225
+ debug?: boolean;
226
+ /** Custom headers to send with verification requests */
227
+ customHeaders?: Record<string, string>;
228
+ /** This counterparty's URL (sent with verify-access requests for analytics) */
229
+ counterpartyUrl?: string;
230
+ /** This counterparty's type (sent with verify-access requests for analytics) */
231
+ counterpartyType?: CounterpartyType;
232
+ /**
233
+ * This counterparty's ASTRAE-id (issued at endpoint registration). When set,
234
+ * the SDK forwards it on verify-access calls so the server attributes traffic
235
+ * directly to this endpoint rather than resolving by URL. Useful when:
236
+ * - The merchant has multiple endpoints under the same origin (each running
237
+ * its own SDK instance with its own counterpartyId)
238
+ * - The endpoint URL might be served behind a proxy / different host than
239
+ * the registered origin
240
+ */
241
+ counterpartyId?: string;
242
+ /**
243
+ * Step-up hold-and-poll (3.6.0, opt-in). When set, adapters HOLD a request
244
+ * whose verify() came back step_up_required, poll the approval status, and
245
+ * on 'approved' re-verify the same request once (cache-bypassed) so the
246
+ * backend redeems the single-use approval — the MFA model the Java SDK
247
+ * ships default-on. Values:
248
+ * - undefined (default): feature OFF — adapters fail closed immediately,
249
+ * exactly as 3.5.0 (a minor release must not silently convert instant
250
+ * 403s into multi-minute holds).
251
+ * - 0: hold until the approval's expiresAt (+5s grace); 5-min fallback
252
+ * when expiresAt is missing/unparsable (Java parity).
253
+ * - >0: hold at most this many milliseconds.
254
+ * Next.js edge runtimes enforce ~25s wall-clock budgets — set a small value
255
+ * there (≤20000) or gate in a Node route handler instead.
256
+ */
257
+ stepUpMaxWaitMs?: number;
258
+ /**
259
+ * Poll interval for the step-up hold (3.6.0). Default 3000ms, clamped to a
260
+ * 250ms floor. At the default the backend's 60/min/IP poll rate limit
261
+ * tolerates ~3 concurrent holds per merchant IP; poll errors are treated as
262
+ * transient, so limiter hits degrade the hold to 'timeout', never an error.
263
+ */
264
+ stepUpPollIntervalMs?: number;
265
+ /**
266
+ * Disable the one-time init self-test. The SDK normally fires a HEAD/OPTIONS
267
+ * to `${apiBaseUrl}/agents/verify-access` on first verify() call and warns
268
+ * if the response is HTML (indicating apiBaseUrl is pointing at a marketing
269
+ * site rather than the API). Set true for tests or environments where the
270
+ * extra request is undesirable.
271
+ */
272
+ disableInitChecks?: boolean;
273
+ /**
274
+ * When true, the init self-test runs synchronously on the first verify()
275
+ * call and THROWS on misconfig (apiBaseUrl returning HTML, unreachable,
276
+ * etc.) instead of warning + continuing. Recommended for production
277
+ * deploys where you want a fast-fail startup signal rather than silent
278
+ * verify-access call failures. Default false for backward compatibility.
279
+ */
280
+ strictInit?: boolean;
281
+ /**
282
+ * 4.0.0: hard timeout (ms) on the outbound verify-access call. Without it
283
+ * a hanging backend hangs the merchant's middleware — and every inbound
284
+ * agent request behind it — indefinitely. Timeouts surface as the
285
+ * fail-closed `verify_access.api_error` result. Default 10_000.
286
+ */
287
+ verifyTimeoutMs?: number;
288
+ /**
289
+ * v2.3.8: emit `X-Astra-Gateway-Mode: unenforced` (with
290
+ * `X-Astra-Gateway-Reason: no-policy | no-match`) on responses where the
291
+ * middleware fell through without consulting verify-access. Lets integration
292
+ * tests assert "this endpoint should be gated; if it falls through, fail
293
+ * loudly". Default off; opt-in.
294
+ *
295
+ * The header value was renamed from the ambiguous `pass-through` to
296
+ * `unenforced` so it describes the GATE state only — not whether the
297
+ * request succeeded end-to-end. The config FLAG name
298
+ * (`setPassThroughHeader`) is unchanged for backwards compatibility.
299
+ */
300
+ setPassThroughHeader?: boolean;
301
+ /**
302
+ * v2.3.8: dashboard origin used to construct configuration links in
303
+ * boot-time warnings (e.g. when no per-route policy is configured).
304
+ * Defaults to `https://astrasync.ai/dashboard` (the `app.astrasync.ai`
305
+ * subdomain referenced in older docs does not resolve).
306
+ */
307
+ dashboardUrl?: string;
308
+ /**
309
+ * When true, the middleware calls verify-access for any request that presents
310
+ * AstraSync credentials, even on `observe`-marked routes / tools that would
311
+ * otherwise pass through unevaluated. Populates `req.agentVerification` and
312
+ * records the verification event for the audit trail. Enforcement still
313
+ * respects the gate — an `observe` marker still passes through regardless of
314
+ * the server decision. Default false to preserve existing behaviour.
315
+ *
316
+ * Use this when a single endpoint serves both anonymous and verified
317
+ * traffic with different response shapes (e.g. anonymous catalog vs
318
+ * verified catalog with agent-only SKUs; anonymous MCP tool listing
319
+ * vs verified tool-listing with restricted tools surfaced). Without
320
+ * the flag, anonymous-with-credentials passes are invisible to the
321
+ * merchant handler and to the AstraSync activity feed.
322
+ *
323
+ * Lives on `GatewayConfig` (not adapter-specific) so both express and
324
+ * MCP middlewares inherit it via their `extends GatewayConfig` chain.
325
+ */
326
+ evaluateAlwaysIfCredentialed?: boolean;
327
+ }
328
+ /**
329
+ * Verified agent information
330
+ */
331
+ interface VerifiedAgent {
332
+ /** ASTRA-xxx identifier */
333
+ astraId: string;
334
+ /** Agent display name */
335
+ name: string;
336
+ /** Composite trust score (0-100) */
337
+ trustScore: number;
338
+ /** Trust level tier */
339
+ trustLevel: TrustLevel;
340
+ /** Whether agent is blockchain-verified */
341
+ blockchainVerified: boolean;
342
+ /** Agent status */
343
+ status: 'active' | 'inactive' | 'suspended' | 'migrating' | 'terminated' | 'retired';
344
+ }
345
+ /**
346
+ * Verified developer (KYD) information
347
+ */
348
+ interface VerifiedDeveloper {
349
+ /** ASTRAD-xxx identifier */
350
+ astradId: string;
351
+ /** Developer name */
352
+ name?: string;
353
+ /** Developer trust score */
354
+ trustScore: number;
355
+ /** Whether developer identity is verified */
356
+ verified: boolean;
357
+ }
358
+ /**
359
+ * Verified organization (KYO) information
360
+ */
361
+ interface VerifiedOrganization {
362
+ /** Organization name */
363
+ name: string;
364
+ /** Whether organization is verified */
365
+ verified: boolean;
366
+ /** Organization trust score */
367
+ trustScore: number;
368
+ }
369
+ /**
370
+ * PDLSS policy information returned with verification.
371
+ *
372
+ * @deprecated v2.2.4 — verify-access no longer returns the full PDLSS to the
373
+ * merchant. Read `EnhancedVerificationResult.verificationContext.pdlssCheck`
374
+ * instead for the merchant-facing summary, and `appliedPolicy` (top-level on
375
+ * the verification result) for the boundary name + policy version. The full
376
+ * PDLSS is owner-side only (queryable via `/api/agents/:id` when
377
+ * authenticated as the agent owner).
378
+ */
379
+ interface PDLSSInfo {
380
+ purposeAllowed: boolean;
381
+ withinDuration: boolean;
382
+ withinLimits: boolean;
383
+ scopeAllowed: boolean;
384
+ selfInstantiationAllowed: boolean;
385
+ allowedPurposes?: string[];
386
+ limits?: Record<string, number>;
387
+ scope?: string[];
388
+ /** Applied policy details. Boundary/policy UUIDs deliberately not included. */
389
+ appliedPolicy?: AppliedPolicy;
390
+ }
391
+ /**
392
+ * Applied policy — merchant-facing identifiers only.
393
+ *
394
+ * Boundary and policy UUIDs are deliberately not surfaced; merchants and
395
+ * agent owners are different tenants and internal join keys are a
396
+ * cross-tenant correlation primitive. Internal callers that need UUIDs
397
+ * query the boundary/policy tables directly.
398
+ */
399
+ interface AppliedPolicy {
400
+ boundaryName: string;
401
+ policyVersion: string;
402
+ }
403
+ /**
404
+ * Structured "why" of a verification decision the merchant receives.
405
+ *
406
+ * Tells the merchant whether the agent ID was verified, whether the runtime
407
+ * challenge succeeded, whether the request was within PDLSS, and the agent's
408
+ * actual dynamic trust score — without exposing thresholds, scope lists, or
409
+ * other-tenant counterparty membership.
410
+ *
411
+ * `attestations` is empty unless the calling endpoint's access policy
412
+ * declared `required_attestations`. Each attestation carries a blockchain
413
+ * proof reference (or, in the future, a full ZKP) so the merchant can verify
414
+ * the underlying claim without seeing the raw underlying data (e.g. the
415
+ * Persona/ConnectID transaction).
416
+ */
417
+ interface VerificationContext {
418
+ idVerified: boolean;
419
+ runtimeChallenge: {
420
+ status: 'passed' | 'skipped' | 'failed' | 'timeout' | 'not_supported';
421
+ checkedAt: string | null;
422
+ };
423
+ pdlssCheck: {
424
+ /** Outcome only — no thresholds disclosed. */
425
+ result: 'within' | 'exceeded' | 'denied' | 'not_evaluated';
426
+ /** Category-level only. */
427
+ purpose: 'approved' | 'denied';
428
+ scope: 'approved' | 'denied';
429
+ };
430
+ /** Live composite score at decision time (not the stale snapshot column). */
431
+ dynamicTrustScore: number;
432
+ attestations: Attestation[];
433
+ }
434
+ /**
435
+ * Attestation returned in `VerificationContext.attestations`.
436
+ *
437
+ * `proofType: 'reference'` (interim) means `proof` is a blockchain txn hash
438
+ * the merchant CAN verify against on-chain records but doesn't HAVE to.
439
+ * `proofType: 'zkp'` (future) means `proof` is a zero-knowledge proof.
440
+ * Wire shape is forward-compatible — clients reading 'reference' today won't
441
+ * break when it becomes 'zkp'.
442
+ */
443
+ interface Attestation {
444
+ /** Attestation kind (e.g. `verified_human_party`). */
445
+ type: string;
446
+ status: 'passed' | 'failed';
447
+ /**
448
+ * ISO-8601 timestamp of the underlying check (when KYC/IDV/AML actually ran).
449
+ * Merchants compare this against their `maxAgeDays` requirement on the
450
+ * endpoint to enforce per-attestation freshness. Distinct from `validUntil`:
451
+ * `checkedAt` is when the data was sourced; `validUntil` is when the issuer
452
+ * stops vouching for it.
453
+ */
454
+ checkedAt: string;
455
+ validUntil?: string;
456
+ proofType: 'reference' | 'zkp';
457
+ proof: string;
458
+ }
459
+ /**
460
+ * Guidance information for unverified agents
461
+ */
462
+ interface GuidanceInfo {
463
+ /** Human-readable guidance message */
464
+ message: string;
465
+ /** URL to register for AstraSync */
466
+ registrationUrl: string;
467
+ /** URL to documentation */
468
+ documentationUrl: string;
469
+ /** Steps to get verified */
470
+ steps?: string[];
471
+ /**
472
+ * 5.1.0: hosted AstraSync MCP connector — the keyless, human-approved
473
+ * registration path for agents already operating inside an MCP host.
474
+ */
475
+ mcp?: {
476
+ endpoint: string;
477
+ discoveryUrl?: string;
478
+ message?: string;
479
+ };
480
+ }
481
+ interface StepUpApprovalInfo {
482
+ approvalId: string;
483
+ pollUrl: string;
484
+ expiresAt: string;
485
+ }
486
+ /**
487
+ * Lifecycle states of a step-up approval row (mirrors the backend's
488
+ * step_up_approval_status_check constraint).
489
+ */
490
+ type StepUpApprovalStatus = 'pending' | 'approved' | 'denied' | 'expired' | 'consumed';
491
+ /**
492
+ * Terminal outcome of a hold-and-poll wait: any non-pending status, or
493
+ * 'timeout' when the hold budget ran out while the approval was still pending.
494
+ */
495
+ type StepUpOutcome = Exclude<StepUpApprovalStatus, 'pending'> | 'timeout';
496
+ /** Fields common to every settlement-artifact binding. */
497
+ interface SettlementArtifactBindingBase {
498
+ merchantId: string;
499
+ sessionId: string;
500
+ singleUse: true;
501
+ expiresAt: string;
502
+ }
503
+ /**
504
+ * Fiat/processor artifact binding (Stripe, Skyfire, PayPal) — the processor
505
+ * is the unit authority, so the binding carries the major-unit pricing amount.
506
+ */
507
+ interface FiatSettlementBinding extends SettlementArtifactBindingBase {
508
+ amount: number;
509
+ currency: string;
510
+ }
511
+ /**
512
+ * Stablecoin voucher binding — wire format v2. Money is integer minor units
513
+ * (`amountMinor` scaled by `assetDecimals`, no floats), and the settlement
514
+ * asset is pinned to a chain + token contract (CAIP-19 `asset`).
515
+ */
516
+ interface StablecoinSettlementBinding extends SettlementArtifactBindingBase {
517
+ amountMinor: number;
518
+ assetDecimals: number;
519
+ currency: string;
520
+ chainId: number;
521
+ tokenContract: string;
522
+ asset: string;
523
+ }
524
+ type SettlementArtifactBinding = FiatSettlementBinding | StablecoinSettlementBinding;
525
+ /**
526
+ * Settlement artifact returned on a clean merchant-mediated grant. The JWS
527
+ * `artifact` is the authoritative, signed object — `binding` mirrors its
528
+ * claims for display convenience only. Never settle from `binding`; decide
529
+ * from the server-verified payload at redeem time.
530
+ */
531
+ interface SettlementArtifact {
532
+ type: string;
533
+ artifact: string;
534
+ binding: SettlementArtifactBinding;
535
+ }
536
+ /**
537
+ * Complete verification result
538
+ */
539
+ /**
540
+ * Single failed gate on a verify-access denial. Aggregated into
541
+ * `VerificationResult.failures[]` so partners can see every blocker in one
542
+ * response (v2.9.8+) — previously the response was fail-fast on the
543
+ * first failed gate, forcing a fix-and-retry cascade through PDLSS
544
+ * dimensions, counterparty allowlist, trust score, and attestations.
545
+ *
546
+ * `dimension` is namespaced so receivers can group by gate family:
547
+ * - `agent.<lookup|status>` (hard prereqs)
548
+ * - `pdlss.<purpose|duration|limits|scope|selfInstantiation>`
549
+ * - `counterparty.<allowlist|trust>`
550
+ * - `attestation.<type>` (e.g. `attestation.verified_human_party`)
551
+ * - `endpoint.<deactivated|trust|policy>`
552
+ */
553
+ interface AccessFailure {
554
+ dimension: string;
555
+ message: string;
556
+ guidance?: string;
557
+ }
558
+ interface VerificationResult {
559
+ /**
560
+ * Identity-verification status — was the caller successfully
561
+ * resolved to a registered agent (signature/credential check passed)?
562
+ * Maps to backend `verificationContext.idVerified`. Drives HTTP 401 vs 403
563
+ * mapping in default adapters: `!identityVerified` → 401 (re-authenticate);
564
+ * `identityVerified && !policyAllowed` → 403 (re-auth won't help — update
565
+ * PDLSS scope or step up). Replaces the pre-4.x `verified` field, which
566
+ * collapsed identity and policy into a single boolean and forced merchants
567
+ * writing `verified ? 200 : 401` into the wrong HTTP-status recovery path
568
+ * on PDLSS denials of authenticated agents.
569
+ */
570
+ identityVerified: boolean;
571
+ /**
572
+ * Does the endpoint's PDLSS / access policy permit this
573
+ * specific action? Maps to backend `access.allowed`. Distinct from
574
+ * `identityVerified`: a verified agent can be policy-denied (403); an
575
+ * unverified caller's policy field is `false` by definition.
576
+ */
577
+ policyAllowed: boolean;
578
+ /** Verified agent info (if verified) */
579
+ agent?: VerifiedAgent;
580
+ /** Developer info (if available) */
581
+ developer?: VerifiedDeveloper;
582
+ /** Organization info (if available) */
583
+ organization?: VerifiedOrganization;
584
+ /** PDLSS policy info (if verified) */
585
+ pdlss?: PDLSSInfo;
586
+ /** Guidance for unverified agents */
587
+ guidance?: GuidanceInfo;
588
+ /** Reasons for denial (if not allowed) */
589
+ denialReasons?: string[];
590
+ /**
591
+ * All policy / gate failures detected on this verify-access call.
592
+ * v2.9.8+ — empty when allowed. Iterate this for the full debug picture
593
+ * instead of consuming `denialReasons` (which only carries the headline
594
+ * message of each failure).
595
+ */
596
+ failures?: AccessFailure[];
597
+ /**
598
+ * Correlation handle for tying a partner-visible denial to a server-side
599
+ * log line, surfaced so adapter onDenied handlers can include it on the
600
+ * merchant's response body. Present on anonymous server responses, on
601
+ * synthesised stubs for API-error fallbacks (`createGuidanceResponse`),
602
+ * and on the `verify_access.internal_error` 200-shaped failure shape.
603
+ */
604
+ correlationId?: string;
605
+ /**
606
+ * 3.12.0: attempt-chain handle, server-echoed on
607
+ * every response branch (caller-supplied or server-minted). Disjoint from
608
+ * `correlationId`/`sessionId` — those identify one verification EVENT; an
609
+ * attempt CONTAINS events (the whole catalog → intent → settlement funnel
610
+ * for one shopping attempt). On a cache hit the SDK overwrites this with
611
+ * the current request's own attemptId (or drops it) so a cached verdict
612
+ * never leaks a prior attempt's id.
613
+ */
614
+ attemptId?: string;
615
+ /**
616
+ * 4.0.0: the backend rejected THIS INTEGRATION'S own API key (revoked /
617
+ * expired / rotated) — a deterministic merchant-side misconfig, distinct
618
+ * from both an agent denial and a transient `verify_access.api_error`.
619
+ * Adapters branch on it to answer inbound agents with 503 +
620
+ * `MERCHANT_VERIFICATION_MISCONFIGURED` instead of a misleading 401.
621
+ */
622
+ misconfigured?: boolean;
623
+ /**
624
+ * 4.6.0: a TRANSIENT infrastructure failure (`verify_access.api_error` — a
625
+ * 5xx / timeout / CSRF-403 reaching the verify-access backend), NOT a policy
626
+ * deny and NOT a deterministic misconfig. Consumers should surface it as an
627
+ * error-and-retry (recommendation `'error'`), never as a policy denial. Unset
628
+ * on misconfig (deterministic — retrying will not help) and on real denials.
629
+ */
630
+ retryable?: boolean;
631
+ /** Whether step-up authentication is required */
632
+ requiresStepUp?: boolean;
633
+ /** Whether approval is required */
634
+ requiresApproval?: boolean;
635
+ /** Step-up approval info (present when transaction is in the human-approval band). */
636
+ stepUpApproval?: StepUpApprovalInfo;
637
+ /**
638
+ * Terminal outcome of an opt-in hold-and-poll wait (3.6.0). Set by adapters
639
+ * on the result they deny with when the hold ended in denied / expired /
640
+ * consumed / timeout. Absent when the feature is off or the hold succeeded
641
+ * (an approved hold re-verifies and the fresh grant result replaces this one).
642
+ */
643
+ stepUpOutcome?: StepUpOutcome;
644
+ /** Settlement voucher (present on clean merchant-mediated grants with a verified wallet). */
645
+ settlement?: SettlementArtifact;
646
+ /**
647
+ * 5.3.0 (astra-pay): sanitized first-party settlement outcome. Present
648
+ * INSTEAD of `settlement` when the counterparty is an AstraSync-operated
649
+ * storefront and the request carried `commercePhase: 'confirm'` — the
650
+ * backend redeemed the voucher and executed the charge server-side
651
+ * (charge-at-redeem), so there is no artifact to deliver, only the result.
652
+ * `no_instrument` = policy passed but the owner has no chargeable
653
+ * instrument on file (steer the user to add one via onboarding).
654
+ */
655
+ settlementOutcome?: SettlementOutcomeInfo;
656
+ /** Timestamp of verification */
657
+ verifiedAt: Date;
658
+ /** TTL for this result (seconds) */
659
+ cacheTtl?: number;
660
+ }
661
+ /**
662
+ * 5.3.0 (astra-pay): sanitized outcome of first-party charge-at-redeem
663
+ * settlement. Carries NO voucher/instrument material — the settlement channel
664
+ * stays merchant-only; this is the result the agent plane is allowed to see.
665
+ *
666
+ * 5.4.2: `requires_approval` — the transaction is HELD for human step-up
667
+ * approval. Not a failure: record the order as pending; after the human
668
+ * approves, the platform re-drives the confirm with the SAME
669
+ * checkoutSessionId and that re-drive carries the settling outcome
670
+ * (one order row per session — the re-drive claims the same row).
671
+ */
672
+ interface SettlementOutcomeInfo {
673
+ status: 'settled' | 'failed' | 'requires_action' | 'no_instrument' | 'requires_approval';
674
+ /** First-party order id — the buyer sees the purchase in their AstraSync
675
+ * dashboard orders view (no public receipt page). */
676
+ orderId?: string;
677
+ /** Decline/failure taxonomy code (card_declined, insufficient_funds, …). */
678
+ failureCode?: string;
679
+ }
680
+ /**
681
+ * Request context for verification
682
+ */
683
+ /**
684
+ * Caller metadata forwarded from the agent's original HTTP request so the
685
+ * endpoint owner can see the real agent-side fingerprint in activity views.
686
+ * Without this, IP/UA recorded on platform_events would be the counterparty
687
+ * server's (useless for endpoint-side forensics).
688
+ */
689
+ interface CallerMetadata {
690
+ /** Agent-side source IP (honours X-Forwarded-For if set). */
691
+ sourceIp?: string;
692
+ /** Agent's User-Agent header. */
693
+ userAgent?: string;
694
+ /** Referer header (where the agent navigated from, if applicable). */
695
+ referer?: string;
696
+ /** Host the agent called (this counterparty's public hostname). */
697
+ host?: string;
698
+ /** Raw X-Forwarded-For chain for audit. */
699
+ forwardedFor?: string;
700
+ /** Published agent card URL, if the agent advertised one (future: from agent headers). */
701
+ agentCardUrl?: string;
702
+ /**
703
+ * The full sanitised view of the agent's inbound request headers + connection
704
+ * signals (maximal metadata capture: every signal legitimately visible on
705
+ * the wire is captured). Produced by `sanitizeHeaders` (genuine secrets
706
+ * removed, credential headers reduced to a safe format prefix). Forwarded so
707
+ * the endpoint owner sees every wire signal about the agent, not just IP/UA.
708
+ * Local string work only — kept OUT of the verify cache key so per-request
709
+ * maps don't defeat verdict caching.
710
+ */
711
+ observedMetadata?: ObservedMetadata;
712
+ }
713
+ interface VerificationRequest {
714
+ /** Agent credentials */
715
+ credentials: AgentCredentials;
716
+ /** Purpose of the access request */
717
+ purpose?: string;
718
+ /** Specific action being performed */
719
+ action?: string;
720
+ /** Type of resource being accessed */
721
+ resourceType?: string;
722
+ /** Specific resource identifier */
723
+ resource?: string;
724
+ /** Jurisdiction for the request */
725
+ jurisdiction?: string;
726
+ /**
727
+ * Transaction value in MAJOR units (dollars, euros, native token units —
728
+ * NOT cents/minor units). Diverges from Stripe (minor units). UCP/ACP
729
+ * extractors auto-convert from cents (÷100). x402 uses per-token decimals.
730
+ * See `transport/transaction-value.ts` for per-protocol normalization.
731
+ */
732
+ transactionValue?: number;
733
+ /** ISO-4217 currency code for transactionValue (e.g. 'USD', 'AUD', 'ETH'). Falls back to 'USD' server-side when unset. */
734
+ currency?: string;
735
+ /**
736
+ * 5.3.0 (astra-pay): checkout-leg discriminator. `'confirm'` marks the
737
+ * completing call of a checkout; first-party settlement (charge-at-redeem
738
+ * on the owner's saved instrument) fires ONLY on this leg. Quote/browse
739
+ * legs omit it (or send `'quote'`) — they must never move money.
740
+ */
741
+ commercePhase?: 'quote' | 'confirm';
742
+ /**
743
+ * 5.3.0 (astra-pay): per-cart idempotency key (the checkout session id),
744
+ * forwarded on the confirm leg. Two concurrent confirms carrying the same
745
+ * key charge the owner's card at most once. Omit for raw one-shot confirms.
746
+ */
747
+ checkoutSessionId?: string;
748
+ /**
749
+ * 5.3.0 (astra-pay): the checkout's authoritative line items, forwarded on
750
+ * the confirm leg for the ORDER plane (receipts + digital-goods fulfillment
751
+ * email). Informational — never the money authority (that remains
752
+ * `transactionValue` bound into the settlement voucher).
753
+ */
754
+ checkoutItems?: Array<{
755
+ sku: string;
756
+ quantity: number;
757
+ title?: string;
758
+ unitPrice?: {
759
+ amount: string;
760
+ currency: string;
761
+ };
762
+ }>;
763
+ /** Whether this is a sub-agent request */
764
+ isSubAgentRequest?: boolean;
765
+ /** Parent agent ID for sub-agent requests */
766
+ parentAgentId?: string;
767
+ /** Depth of sub-agent chain */
768
+ subAgentDepth?: number;
769
+ /** Client IP address (deprecated — use callerMetadata.sourceIp) */
770
+ clientIp?: string;
771
+ /** User agent string (deprecated — use callerMetadata.userAgent) */
772
+ userAgent?: string;
773
+ /**
774
+ * Forwarded request metadata from the agent's original call.
775
+ * When the SDK is embedded in a counterparty server, these describe
776
+ * the agent-side fingerprint — not the counterparty server itself.
777
+ * The express/nextjs adapters auto-populate these from `req`.
778
+ */
779
+ callerMetadata?: CallerMetadata;
780
+ /** Enable runtime challenge for this request */
781
+ enableRuntimeChallenge?: boolean;
782
+ /** Create a verification session (returns sessionId) */
783
+ createSession?: boolean;
784
+ /** Counterparty type */
785
+ counterpartyType?: CounterpartyType;
786
+ /** Counterparty URL */
787
+ counterpartyUrl?: string;
788
+ /** Requested session duration in seconds (from agent's X-Astra-Duration header) */
789
+ durationRequired?: number;
790
+ /** Runtime challenge options */
791
+ runtimeChallengeOptions?: {
792
+ timeoutOverride?: number;
793
+ };
794
+ /**
795
+ * Transport protocol marker. Set by the MCP middleware
796
+ * to `'mcp'`; non-MCP callers leave it unset (server treats as `'rest'`).
797
+ * Separates "how did the call arrive" from "what does the agent want"
798
+ * (`purpose`). Stored on platform_events.eventData for activity-feed
799
+ * visibility into transport-vs-intent.
800
+ */
801
+ invocationProtocol?: 'rest' | 'mcp' | 'a2a' | 'acp' | 'ap2' | 'mpp' | 'ucp';
802
+ /**
803
+ * 3.9.0 — raw commerce-protocol artifacts forwarded verbatim
804
+ * to verify-access, whose commerce pipeline runs the full
805
+ * cryptographic verification SERVER-side and persists commerce_context on
806
+ * the session. Adapters forward artifacts, they never verify them locally
807
+ * (verify-access is the sole verification sink, so every decision is
808
+ * recorded once, with events). Shape mirrors the backend's
809
+ * `commerceArtifacts` schema 1:1.
810
+ */
811
+ commerceArtifacts?: CommerceArtifactsPayload;
812
+ /**
813
+ * 3.12.0 — attempt-chain handle correlating the
814
+ * multi-call commerce funnel (catalog → intent → settlement) into ONE
815
+ * attempt. Format `att_` + 32 lowercase hex. Optional: the server mints one
816
+ * when absent and echoes it top-level on every response branch either way.
817
+ * Observational pass-through — never affects the verdict, so it's excluded
818
+ * from the verify cache key.
819
+ */
820
+ attemptId?: string;
821
+ /**
822
+ * 3.12.0 — first-party observational data: the
823
+ * offers the agent evaluated at this checkpoint (catalog browse / intent
824
+ * selection). Forwarded verbatim to verify-access; never affects the
825
+ * verdict (also excluded from the cache key).
826
+ */
827
+ considerationSet?: ConsiderationSet;
828
+ }
829
+ /**
830
+ * One offer the agent evaluated. Mirrors the
831
+ * backend's `considerationItemSchema` 1:1 — first-party observational data
832
+ * reported by the transport (bridge / adapters), never verified locally.
833
+ */
834
+ interface ConsiderationItem {
835
+ /** SKU identifier as the merchant catalog publishes it (1–128 chars). */
836
+ sku: string;
837
+ /** Display title (≤256 chars). */
838
+ name?: string;
839
+ /** Price in MAJOR units (same convention as `transactionValue`), non-negative. */
840
+ price?: number;
841
+ /** ISO-4217 or settlement-asset code (3–6 alphanumeric chars). */
842
+ currency?: string;
843
+ /** Stock state as the catalog declared it; omit when the catalog didn't say. */
844
+ availability?: 'in_stock' | 'out_of_stock' | 'preorder' | 'unknown';
845
+ /** True when the agent selected this offer (intent/settlement checkpoints). */
846
+ chosen?: boolean;
847
+ /** Why an evaluated-but-unchosen offer lost, when the agent can say. */
848
+ notChosenReason?: 'price' | 'policy' | 'trust_threshold' | 'stock' | 'other';
849
+ }
850
+ /**
851
+ * The set of offers evaluated at one funnel checkpoint.
852
+ * Mirrors the backend's `considerationSetSchema` 1:1.
853
+ *
854
+ * `items` is capped at 50 server-side — reporters MUST order chosen items
855
+ * FIRST so purchased counts survive truncation; `totalEvaluated` carries the
856
+ * true pre-cap count and `truncated` flags that the cap was applied.
857
+ */
858
+ interface ConsiderationSet {
859
+ /** Funnel checkpoint this set was observed at. */
860
+ checkpoint?: 'catalog' | 'intent' | 'settlement';
861
+ /** Offers evaluated (max 50; chosen-first ordering under the cap). */
862
+ items: ConsiderationItem[];
863
+ /** True evaluated count — survives the 50-item cap. */
864
+ totalEvaluated?: number;
865
+ /** True when `items` was truncated to the cap. */
866
+ truncated?: boolean;
867
+ }
868
+ /**
869
+ * Terminal (or notable) outcome of an attempt chain, reported post-hoc via
870
+ * `reportAttempt`. Mirrors the backend's `attemptReportSchema.outcome` 1:1.
871
+ */
872
+ interface AttemptOutcome {
873
+ kind: 'settled' | 'blocked_step_up' | 'failed' | 'high_value_action';
874
+ /** Dotted ACTION-axis token for the failure class, e.g. `commerce.catalog.sku_not_found` (≤128 chars). */
875
+ dimension?: string;
876
+ /** Human-readable detail (≤512 chars). */
877
+ reason?: string;
878
+ /** For `high_value_action`: the non-payment conversion type. */
879
+ actionType?: 'lead' | 'signup' | 'application' | 'enquiry';
880
+ /** Value in MAJOR units (settled amount / estimated action value), non-negative. */
881
+ value?: number;
882
+ /** ISO-4217 or settlement-asset code (3–6 alphanumeric chars). */
883
+ currency?: string;
884
+ /** Settlement rail / mandate type, e.g. `ap2.payment_mandate` (≤64 chars). */
885
+ rail?: string;
886
+ }
887
+ /**
888
+ * Body for `POST /agents/verify-access/attempt-report`:
889
+ * post-hoc consideration/outcome data for an attempt chain that a
890
+ * verify-access call couldn't carry (e.g. the catalog was served from a local
891
+ * cache, or the deny happened transport-side). Must carry `considerationSet`
892
+ * and/or `outcome`.
893
+ */
894
+ interface AttemptReport {
895
+ /** Attempt-chain handle — `att_` + 32 lowercase hex. */
896
+ attemptId: string;
897
+ /** Merchant/endpoint the attempt targeted; falls back to `config.counterpartyId`. */
898
+ counterpartyId?: string;
899
+ /** Canonical ASTRA-* id of the acting agent, when known. */
900
+ agentId?: string;
901
+ considerationSet?: ConsiderationSet;
902
+ outcome?: AttemptOutcome;
903
+ }
904
+ /**
905
+ * Raw commerce-protocol artifacts as verify-access accepts them (backend
906
+ * `validation.ts` → `commerceArtifacts`). All optional; send what was
907
+ * detected on the wire.
908
+ */
909
+ interface CommerceArtifactsPayload {
910
+ /** Compact VI SD-JWT. */
911
+ viSdJwt?: string;
912
+ /** AP2 mandate triple as compact SD-JWTs. */
913
+ ap2Mandates?: {
914
+ intent?: string;
915
+ cart?: string;
916
+ payment?: string;
917
+ };
918
+ /** RFC 9421 signed request (Agent Pay / TAP / Web Bot Auth). */
919
+ rfc9421?: {
920
+ headers: Record<string, string | string[]>;
921
+ method: string;
922
+ url: string;
923
+ body?: string;
924
+ tag?: string;
925
+ };
926
+ /** UCP checkout session request. */
927
+ ucpRequest?: {
928
+ method: string;
929
+ url: string;
930
+ body?: unknown;
931
+ };
932
+ /** ACP request (HMAC-signed webhook or checkout body). */
933
+ acpRequest?: {
934
+ method: string;
935
+ url: string;
936
+ headers?: Record<string, string | string[]>;
937
+ body?: unknown;
938
+ rawBody?: string;
939
+ };
940
+ mppRequest?: {
941
+ method: string;
942
+ url: string;
943
+ headers: Record<string, string | string[]>;
944
+ body?: unknown;
945
+ rawBody?: string;
946
+ };
947
+ mppResponse?: {
948
+ status: number;
949
+ headers: Record<string, string | string[]>;
950
+ body?: unknown;
951
+ };
952
+ x402Request?: {
953
+ method?: string;
954
+ url?: string;
955
+ headers?: Record<string, string | string[]>;
956
+ body?: unknown;
957
+ };
958
+ x402Response?: {
959
+ status?: number;
960
+ headers?: Record<string, string | string[]>;
961
+ body?: unknown;
962
+ };
963
+ stripeWebhook?: {
964
+ payload: string;
965
+ signatureHeader: string;
966
+ secret: string;
967
+ };
968
+ }
969
+ /**
970
+ * Route-specific access configuration
971
+ */
972
+ interface RouteAccessConfig {
973
+ /** Route pattern (supports wildcards) */
974
+ pattern: string;
975
+ /** HTTP method (or * for all) */
976
+ method: string | '*';
977
+ /**
978
+ * Pass this route through unenforced (observe). The middleware skips gating
979
+ * on the server decision; with `evaluateAlwaysIfCredentialed` set it still
980
+ * calls verify-access for the audit trail and populates `req.agentVerification`.
981
+ * Replaces the old `minAccessLevel: 'none'` sentinel (SDK 5.0.0).
982
+ */
983
+ observe?: boolean;
984
+ /** Minimum trust score required (optional) */
985
+ minTrustScore?: number;
986
+ /** Required purposes (optional, agent must declare one of these) */
987
+ requiredPurposes?: string[];
988
+ /** Counterparty-defined PDLSS maximums — agent requests exceeding these are rejected before calling AstraSync */
989
+ /** Maximum session duration in seconds the counterparty will allow */
990
+ maxDuration?: number;
991
+ /** Whitelist of allowed purposes — agent's declared purpose must be in this list */
992
+ allowedPurposes?: string[];
993
+ /** Whitelist of allowed jurisdictions */
994
+ allowedJurisdictions?: string[];
995
+ /** Maximum transaction value for this route */
996
+ maxTransactionValue?: number;
997
+ /**
998
+ * Backend-evaluator strict mode: when true AND
999
+ * `allowedPurposes` is non-empty, verify-access denies requests arriving
1000
+ * WITHOUT a purpose. Configured in the dashboard; passed through here.
1001
+ */
1002
+ requirePurpose?: boolean;
1003
+ /**
1004
+ * SEND-mapping — not an allow-list: the PDLSS tokens the
1005
+ * middleware STAMPS on verify-access calls matching this route, replacing
1006
+ * the generic `data`/`data.*` method-table fallback. `purpose` = bare
1007
+ * category noun (`shopping`, `trading`); `action` = dotted verb
1008
+ * (`shopping.search`, `trading.execute`). Authoritative over agent-supplied
1009
+ * headers — the dashboard is merchant policy, the way MCP toolGates are.
1010
+ */
1011
+ purpose?: string;
1012
+ action?: string;
1013
+ }
1014
+ /**
1015
+ * Express middleware options.
1016
+ *
1017
+ * v2.9.7 removed the `routes` field — per-route policy now lives in the
1018
+ * AstraSync dashboard (gated by team.role admin auth + audit + alerts).
1019
+ * The middleware fetches routes from the backend via
1020
+ * `GET /endpoints/:counterpartyId/routes` on init and refreshes
1021
+ * periodically (override interval via `routesRefreshMs`). Set
1022
+ * `counterpartyId` on `GatewayConfig` so the middleware knows which
1023
+ * endpoint to fetch policy for; without it, the middleware logs a warning
1024
+ * and falls through (allows all) — useful for local dev only.
1025
+ */
1026
+ interface ExpressMiddlewareOptions extends GatewayConfig {
1027
+ /** Function to extract credentials from request */
1028
+ extractCredentials?: (req: unknown) => AgentCredentials;
1029
+ /** Function to extract purpose from request */
1030
+ extractPurpose?: (req: unknown) => string | undefined;
1031
+ /**
1032
+ * Function to extract the PDLSS action from a request — symmetric with
1033
+ * `extractPurpose` (previously the action axis had no override and
1034
+ * hardwired the HTTP verb). When configured it masks the
1035
+ * `X-Astra-Action` header step; returning undefined falls through to the
1036
+ * pinned method→action table (GET→data.read, POST/PUT/PATCH→data.write,
1037
+ * DELETE→data.delete). Dashboard route mapping still outranks it.
1038
+ */
1039
+ extractAction?: (req: unknown) => string | undefined;
1040
+ /**
1041
+ * Optional extractor for the transaction value from the incoming request.
1042
+ * Must return the value in MAJOR units (dollars, euros — NOT cents/minor
1043
+ * units). This diverges from Stripe and most payment rails which use minor
1044
+ * units. If your source is in minor units (cents), divide by 100 before
1045
+ * returning.
1046
+ *
1047
+ * When configured, the extracted value and currency are forwarded to
1048
+ * verify-access so PDLSS limit evaluation runs at middleware time.
1049
+ *
1050
+ * NOTE: this is opt-in upfront enforcement. `authorizeSettlement()` remains
1051
+ * the REQUIRED fail-closed settlement gate at settlement time.
1052
+ */
1053
+ extractTransactionValue?: (req: unknown) => {
1054
+ value: number;
1055
+ currency: string;
1056
+ } | undefined;
1057
+ /** Skip verification for certain paths */
1058
+ skipPaths?: string[];
1059
+ /** Custom response for denied requests */
1060
+ onDenied?: (result: VerificationResult, req: unknown, res: unknown) => void;
1061
+ /** Automatically create sessions and record grant/deny decisions (default: true) */
1062
+ recordDecisions?: boolean;
1063
+ /** Enable runtime challenge for all verify-access calls (default: true) */
1064
+ enableRuntimeChallenge?: boolean;
1065
+ /**
1066
+ * Refresh interval (ms) for the remote-fetched route policy. Default:
1067
+ * 5 minutes. Operators can shorten this to test policy edits faster, or
1068
+ * lengthen it to reduce network chatter.
1069
+ */
1070
+ routesRefreshMs?: number;
1071
+ /**
1072
+ * Posture when the middleware itself throws an internal error (header
1073
+ * parsing failure, `fetchRoutes` network error, malformed proxy state,
1074
+ * etc.). Default `'open'` for backward compatibility in SDK 2.4.13 —
1075
+ * legitimate traffic continues to pass through during platform outages.
1076
+ *
1077
+ * In shadow mode (default), the middleware ALWAYS logs a
1078
+ * `[SHADOW] would-have-denied` line on throws including correlationId so
1079
+ * merchants can grep their own logs for impact analysis. The default
1080
+ * flips to `'closed'` in a follow-up release once the shadow logs confirm
1081
+ * legitimate traffic is unaffected.
1082
+ *
1083
+ * Small-value demo merchants can keep `'open'` indefinitely after the
1084
+ * default flip by setting this explicitly.
1085
+ */
1086
+ failOnError?: 'open' | 'closed';
1087
+ /**
1088
+ * When true, route-pattern matching is case-insensitive. Default false in
1089
+ * SDK 2.4.13 for backward compatibility; shadow logs record divergences so
1090
+ * merchants can preview impact before flipping. A follow-up release makes
1091
+ * case-insensitive the default once observation confirms merchants are
1092
+ * unaffected.
1093
+ *
1094
+ * Recommended: set to true if your Express install uses the default
1095
+ * (case-insensitive) routing AND your policy entries don't deliberately
1096
+ * use case distinctions.
1097
+ */
1098
+ caseInsensitiveRouteMatch?: boolean;
1099
+ /**
1100
+ * Emit a fire-and-forget beacon for bot- and agent-shaped traffic that
1101
+ * passes through UNGATED (no dashboard route matches the path, or the
1102
+ * matching route is gated at `none`), so the endpoint's dashboard sees
1103
+ * anonymous agent traffic the gate never evaluates. Human traffic and
1104
+ * static assets are never beaconed; platform-fingerprinted agents always
1105
+ * beacon; other non-browser traffic is sampled at the dashboard-configured
1106
+ * `sampling.anonymousBeaconRate` (set the rate to 0 in the dashboard to
1107
+ * stop sampling). The beacon is never awaited on the request path and adds
1108
+ * no latency. Requires `counterpartyId`. Default true; set false to
1109
+ * disable the beacon and its config fetch entirely.
1110
+ */
1111
+ anonymousBeacon?: boolean;
1112
+ /**
1113
+ * Trust a fresh `X-Astra-Verified-Hop` marker from an upstream AstraSync
1114
+ * hop (edge gateway at authenticate/authorize depth, or an MCP outer hop)
1115
+ * and skip the duplicate verify-access call when the marker matches the
1116
+ * presented `X-Astra-Id` and is within the freshness window. The marker is
1117
+ * an UNSIGNED dedupe advisory — enable only when every network path to
1118
+ * this middleware crosses a stripping gateway or equivalent trusted
1119
+ * boundary. Default false. No `req.agentVerification` is populated on a
1120
+ * hop-skip (same contract as the MCP adapter).
1121
+ */
1122
+ trustVerifiedHop?: boolean;
1123
+ /** Acceptable `X-Astra-Verified-Hop` age in ms (default 60 000). */
1124
+ verifiedHopMaxAgeMs?: number;
1125
+ }
1126
+ /**
1127
+ * Next.js middleware options.
1128
+ *
1129
+ * v2.9.7 removed the `routes` field — see `ExpressMiddlewareOptions` for
1130
+ * the rationale. Same fetch-from-backend model applies here.
1131
+ */
1132
+ interface NextJsMiddlewareOptions extends GatewayConfig {
1133
+ /** Paths to skip verification */
1134
+ skipPaths?: string[];
1135
+ /**
1136
+ * Trust a fresh `X-Astra-Verified-Hop` marker from an upstream AstraSync
1137
+ * hop and skip the duplicate verify-access call — see
1138
+ * `ExpressMiddlewareOptions.trustVerifiedHop` for the trust model.
1139
+ * Default false.
1140
+ */
1141
+ trustVerifiedHop?: boolean;
1142
+ /** Acceptable `X-Astra-Verified-Hop` age in ms (default 60 000). */
1143
+ verifiedHopMaxAgeMs?: number;
1144
+ /** Refresh interval (ms) for the remote-fetched route policy. Default: 5 minutes. */
1145
+ routesRefreshMs?: number;
1146
+ /**
1147
+ * Whether to show the verification interstitial (the HTML overlay served to
1148
+ * unverified web-page traffic). Default true. Takes precedence over the
1149
+ * deprecated `showCommerceShield` when both are set.
1150
+ */
1151
+ showInterstitial?: boolean;
1152
+ /** @deprecated Renamed in 4.1.0 — use `showInterstitial`. Alias removed next major. */
1153
+ showCommerceShield?: boolean;
1154
+ /** Verification interstitial configuration */
1155
+ commerceShield?: {
1156
+ title?: string;
1157
+ message?: string;
1158
+ allowGuestAccess?: boolean;
1159
+ };
1160
+ /** Enable runtime challenge for all verify-access calls (default: true) */
1161
+ enableRuntimeChallenge?: boolean;
1162
+ /**
1163
+ * Emit a fire-and-forget beacon for bot- and agent-shaped traffic that
1164
+ * passes through ungated — same semantics as the express option of the
1165
+ * same name (see `ExpressMiddlewareOptions.anonymousBeacon`). Default
1166
+ * true; set false to disable entirely.
1167
+ */
1168
+ anonymousBeacon?: boolean;
1169
+ }
1170
+ /**
1171
+ * SDK function options
1172
+ */
1173
+ interface SDKOptions extends GatewayConfig {
1174
+ /** Timeout for verification requests (ms) */
1175
+ timeout?: number;
1176
+ /** Retry configuration */
1177
+ retry?: {
1178
+ maxRetries: number;
1179
+ backoffMs: number;
1180
+ };
1181
+ }
1182
+ /**
1183
+ * Token guidance returned from verify-access.
1184
+ *
1185
+ * `recommendedRateLimit` carries `requestsPerMinute` and `currency` only.
1186
+ * `maxTransactionValue` was removed in v2.2.4 — it leaked the agent's
1187
+ * spending headroom to the merchant, which is a price-discrimination signal
1188
+ * (a merchant could see the agent's autonomous threshold and price the
1189
+ * transaction just under it to capture surplus). The agent's SDK receives
1190
+ * its own limits separately for client-side budgeting; the merchant's
1191
+ * decision doesn't need amount info.
1192
+ */
1193
+ interface TokenGuidance {
1194
+ recommendedScopes: string[];
1195
+ recommendedTtlSeconds: number;
1196
+ recommendedRateLimit?: {
1197
+ requestsPerMinute: number;
1198
+ currency?: string;
1199
+ };
1200
+ jurisdictionConstraints?: string[];
1201
+ delegationAllowed: boolean;
1202
+ maxDelegationDepth?: number;
1203
+ safetyDefaults: {
1204
+ writePrivilegesRequested: boolean;
1205
+ shortLivedTokenRecommended: boolean;
1206
+ scopeConvention: 'astrasync-canonical';
1207
+ };
1208
+ }
1209
+ /**
1210
+ * Runtime challenge result
1211
+ */
1212
+ interface RuntimeChallengeResult {
1213
+ status: 'passed' | 'failed' | 'skipped' | 'timeout' | 'not_supported';
1214
+ challengeId?: string;
1215
+ challengeSentAt?: string;
1216
+ responseReceivedAt?: string;
1217
+ latencyMs?: number;
1218
+ reason?: string;
1219
+ }
1220
+ /**
1221
+ * Enhanced verification result (extends existing VerificationResult).
1222
+ *
1223
+ * - `appliedPolicy`: surfaces the boundary name + policy version that drove
1224
+ * the decision (no UUIDs).
1225
+ * - `verificationContext`: structured "why" for the merchant — see
1226
+ * `VerificationContext` for the full shape.
1227
+ */
1228
+ interface EnhancedVerificationResult extends VerificationResult {
1229
+ sessionId?: string;
1230
+ runtimeChallenge?: RuntimeChallengeResult;
1231
+ tokenGuidance?: TokenGuidance;
1232
+ appliedPolicy?: AppliedPolicy;
1233
+ verificationContext?: VerificationContext;
1234
+ recommendation?: 'grant' | 'deny' | 'step_up_required' | 'audit';
1235
+ recommendationReasons?: string[];
1236
+ /**
1237
+ * v2.3.8: when an endpoint's `unverifiedAgentPolicy` is `'audit'`, the
1238
+ * server returns the warning header to relay to the merchant's response.
1239
+ * The Express + MCP middleware lift this into `res.setHeader(name, value)`
1240
+ * before calling `next()`. Distinct vocabulary from the PDLSS-scope
1241
+ * outbound `unverifiedCounterpartyPolicy: 'warn'` so raw JSON config can't
1242
+ * conflate the two.
1243
+ */
1244
+ warningHeader?: {
1245
+ name: string;
1246
+ value: string;
1247
+ };
1248
+ }
1249
+ /**
1250
+ * Cross-protocol credential config
1251
+ */
1252
+ interface AstraSyncCredentials {
1253
+ agentId: string;
1254
+ verifyUrl?: string;
1255
+ challengeUrl?: string;
1256
+ pdlss?: {
1257
+ purpose?: {
1258
+ category: string;
1259
+ action?: string;
1260
+ };
1261
+ duration?: {
1262
+ maxSessionDuration?: number;
1263
+ };
1264
+ scope?: {
1265
+ jurisdiction?: string;
1266
+ };
1267
+ };
1268
+ }
1269
+ /**
1270
+ * Protocol transport type
1271
+ */
1272
+ type ProtocolTransport = 'http' | 'a2a' | 'mcp';
1273
+ /**
1274
+ * Verification interstitial UI props (the React overlay shown to unverified
1275
+ * agents; user-visible title stays "AstraSync Agent Verification").
1276
+ */
1277
+ interface VerificationInterstitialProps {
1278
+ /** Whether the interstitial is visible */
1279
+ visible: boolean;
1280
+ /** Verification result (if any) */
1281
+ result?: VerificationResult;
1282
+ /** Callback when user chooses to register */
1283
+ onRegister?: () => void;
1284
+ /** Callback when user chooses guest access */
1285
+ onGuestAccess?: () => void;
1286
+ /** Callback when user dismisses */
1287
+ onDismiss?: () => void;
1288
+ /** Custom title */
1289
+ title?: string;
1290
+ /** Custom message */
1291
+ message?: string;
1292
+ /** Whether guest access is allowed */
1293
+ allowGuestAccess?: boolean;
1294
+ /** Custom styles */
1295
+ className?: string;
1296
+ }
1297
+ /** @deprecated Renamed VerificationInterstitialProps in 4.1.0; alias removed next major. */
1298
+ type CommerceShieldProps = VerificationInterstitialProps;
1299
+
1300
+ /**
1301
+ * AstraSync Universal Verification Gateway — Trust Level helpers.
1302
+ *
1303
+ * SDK 5.0.0: the `accessLevel` band (`none`/`restricted`/`read-only`/`standard`/
1304
+ * `full`/`internal`) was removed entirely — it never gated the access decision
1305
+ * (the server does, from a verified ID + runtime challenge + PDLSS match + trust
1306
+ * score). What remains here is the coarse trust-level badge derived from the
1307
+ * numeric trust score, used only for display.
1308
+ */
1309
+
1310
+ /**
1311
+ * Trust level score ranges
1312
+ */
1313
+ declare const TRUST_LEVEL_RANGES: Record<TrustLevel, {
1314
+ min: number;
1315
+ max: number;
1316
+ }>;
1317
+ /**
1318
+ * Determine trust level from score
1319
+ */
1320
+ declare function getTrustLevel(score: number): TrustLevel;
1321
+
1322
+ /**
1323
+ * AstraSync Universal Verification Gateway - Core Verification Logic
1324
+ *
1325
+ * This module handles the core verification logic, calling the AstraSync API
1326
+ * and processing the response into a standardized VerificationResult.
1327
+ */
1328
+
1329
+ /**
1330
+ * Clear the verification cache
1331
+ */
1332
+ declare function clearCache(): void;
1333
+ /**
1334
+ * Extract agent credentials from various sources
1335
+ */
1336
+ declare function extractCredentials(headers: Record<string, string | string[] | undefined>, query?: Record<string, string | undefined>): AgentCredentials;
1337
+ /**
1338
+ * Check if credentials are present
1339
+ */
1340
+ declare function hasCredentials(credentials: AgentCredentials): boolean;
1341
+ /**
1342
+ * Options for a single verify() call (as opposed to GatewayConfig, which is
1343
+ * per-gateway). Mirrors the Java SDK's `verify(request, bypassCache)`.
1344
+ */
1345
+ interface VerifyOptions {
1346
+ /**
1347
+ * Skip the cache READ for this call so the request is guaranteed to reach
1348
+ * the backend (the result is still written to the cache if cacheable).
1349
+ * Used by the step-up hold-and-poll retry: the re-verify after an approval
1350
+ * must hit the server to redeem the single-use approval.
1351
+ */
1352
+ bypassCache?: boolean;
1353
+ }
1354
+ /**
1355
+ * Main verification function
1356
+ */
1357
+ declare function verify(config: GatewayConfig, request: VerificationRequest, options?: VerifyOptions): Promise<VerificationResult>;
1358
+ /**
1359
+ * Report post-hoc consideration/outcome data for an attempt chain (Trust
1360
+ * Record). Use when the signal never reached verify-access: a
1361
+ * catalog served from a local cache, a transport-side deny (sku not found,
1362
+ * over budget), or a terminal outcome (settled / blocked on step-up).
1363
+ * Authenticated with the same credentials as verify(); the backend responds
1364
+ * 202 and folds the data into the attempt chain keyed by `attemptId`.
1365
+ *
1366
+ * Fire-and-forget — errors are silently swallowed, never throws.
1367
+ */
1368
+ declare function reportAttempt(config: GatewayConfig, report: AttemptReport): Promise<void>;
1369
+ /**
1370
+ * Fetch the per-route policy for an endpoint from the AstraSync backend.
1371
+ * v2.9.7 moved policy authority into the dashboard — the SDK no longer
1372
+ * accepts `routes` from merchant-side source code, it fetches them from
1373
+ * here on init (and refreshes periodically).
1374
+ *
1375
+ * Returns `null` when the request fails for any reason — the caller decides
1376
+ * how to fall back (the middleware allows-all when no policy is loaded so
1377
+ * a misconfigured init doesn't take down the merchant's API).
1378
+ */
1379
+ declare function fetchRoutes(config: GatewayConfig, counterpartyId: string): Promise<RouteAccessConfigShape[] | null>;
1380
+ /**
1381
+ * Minimal shape of an EndpointRoute as the SDK consumes it. Mirrors the
1382
+ * server's `EndpointRoute` type and the SDK's `RouteAccessConfig` — same
1383
+ * JSON moves between server and SDK unchanged.
1384
+ */
1385
+ interface RouteAccessConfigShape {
1386
+ pattern: string;
1387
+ method: string;
1388
+ /** Pass through unenforced (observe). Replaces `minAccessLevel: 'none'`. */
1389
+ observe?: boolean;
1390
+ minTrustScore?: number;
1391
+ requiredPurposes?: string[];
1392
+ allowedPurposes?: string[];
1393
+ allowedJurisdictions?: string[];
1394
+ maxDuration?: number;
1395
+ maxTransactionValue?: number;
1396
+ requirePurpose?: boolean;
1397
+ /** Send-mapping — see RouteAccessConfig in types.ts. */
1398
+ purpose?: string;
1399
+ action?: string;
1400
+ }
1401
+ /**
1402
+ * Report an unregistered agent attempt (no AstraSync credentials).
1403
+ * Called by SDK adapters when an agent is redirected to /docs/agent-access.
1404
+ * Fire-and-forget — errors are silently swallowed.
1405
+ */
1406
+ declare function reportUnregisteredAttempt(config: GatewayConfig, data: {
1407
+ /**
1408
+ * 3.6.0: optional — the backend attributes by counterpartyId first (sent
1409
+ * from config below) and requires at least ONE of counterpartyId/URL.
1410
+ * A null/undefined URL is omitted from the body, not sent as null.
1411
+ */
1412
+ counterpartyUrl?: string;
1413
+ counterpartyType?: string;
1414
+ sourceIp?: string;
1415
+ userAgent?: string;
1416
+ requestPath?: string;
1417
+ requestMethod?: string;
1418
+ /**
1419
+ * 3.9.0 — edge-adapter evidence fields, persisted into the
1420
+ * event's eventData by the backend: `protocol` = detected transport/
1421
+ * credential protocol; `evidence` = light crypto-free detection detail.
1422
+ */
1423
+ protocol?: string;
1424
+ evidence?: Record<string, unknown>;
1425
+ /**
1426
+ * Maximal metadata capture — the full sanitised metadata for an
1427
+ * unregistered caller (every signal legitimately visible on the wire).
1428
+ * Persisted into eventData; feeds platform attribution and (via
1429
+ * correlationId) registration auto-fill. Fire-and-forget, so free.
1430
+ */
1431
+ observedMetadata?: ObservedMetadata;
1432
+ }): Promise<void>;
1433
+ /**
1434
+ * Quick verification — checks credentials and policy in one call.
1435
+ *
1436
+ * The return shape mirrors `VerificationResult`'s split — partners
1437
+ * writing custom handlers around `quickVerify` get the same identity/policy
1438
+ * distinction as those calling `verify()` directly. Map to HTTP status the
1439
+ * same way: `!identityVerified` → 401; `identityVerified && !policyAllowed`
1440
+ * → 403.
1441
+ */
1442
+ declare function quickVerify(config: GatewayConfig, credentials: AgentCredentials): Promise<{
1443
+ identityVerified: boolean;
1444
+ policyAllowed: boolean;
1445
+ reason?: string;
1446
+ }>;
17
1447
 
18
1448
  /**
19
1449
  * Step-up hold-and-poll (3.6.0) — the synchronous half of the MFA-style gate,
@@ -98,38 +1528,3072 @@ interface SettlementDecision {
98
1528
  declare function authorizeSettlement(config: GatewayConfig, req: SettlementRequest): Promise<SettlementDecision>;
99
1529
 
100
1530
  /**
101
- * SDK-side discovery of canonical platform URLs via `/.well-known/agentic-commerce`.
1531
+ * AstraSync Universal Verification Gateway - Express Middleware
102
1532
  *
103
- * Fire-and-forget pre-fetch at middleware creation; first verify() awaits
104
- * the in-flight promise if it hasn't resolved. 60-minute TTL with
105
- * stale-while-revalidate background refresh.
1533
+ * Express.js middleware for verifying AI agents on API endpoints.
1534
+ *
1535
+ * @example
1536
+ * ```typescript
1537
+ * import express from 'express';
1538
+ * import { createMiddleware } from '@astrasyncai/verification-gateway/express';
1539
+ *
1540
+ * const app = express();
1541
+ *
1542
+ * app.use(createMiddleware({
1543
+ * apiBaseUrl: 'https://astrasync.ai/api',
1544
+ * apiKey: process.env.ASTRASYNC_API_KEY,
1545
+ * counterpartyId: 'ASTRAE-...', // your registered endpoint id
1546
+ * }));
1547
+ * ```
1548
+ *
1549
+ * Per-route policy (which paths are gated, trust floors, PDLSS purposes) is
1550
+ * configured in the AstraSync dashboard, not in code — the middleware
1551
+ * fetches it automatically on init and refreshes periodically. There is no
1552
+ * `routes` option; a `routes` key in the config object is ignored (with a
1553
+ * warning) since v2.9.7.
106
1554
  */
107
- interface WellKnownAgenticCommerce {
108
- registrationUrl: string;
109
- documentationUrl: string;
110
- verifyAccessUrl: string;
111
- /** 5.1.0: hosted AstraSync MCP bridge endpoint (absent on self-hosted backends). */
112
- mcpEndpoint?: string;
113
- /** 5.1.0: bridge connector-discovery doc (absent on self-hosted backends). */
114
- mcpDiscoveryUrl?: string;
1555
+
1556
+ /**
1557
+ * Extend Express Request with verification result
1558
+ */
1559
+ declare global {
1560
+ namespace Express {
1561
+ interface Request {
1562
+ agentVerification?: VerificationResult;
1563
+ }
1564
+ }
115
1565
  }
116
1566
  /**
117
- * Start a background fetch. Returns the promise for callers that need
118
- * to await it (first verify() call).
1567
+ * Extract extended AstraSync credentials (X-Astra-* headers) from Express request.
1568
+ * Returns null if no AstraSync headers are present.
119
1569
  */
120
- declare function prefetchWellKnown(apiBaseUrl: string): Promise<WellKnownAgenticCommerce>;
1570
+ declare function extractAstraSyncCredentials(req: Request): AstraSyncCredentials | null;
121
1571
  /**
122
- * Get cached well-known URLs. If stale, triggers a background refresh
123
- * and returns stale data (stale-while-revalidate). If no cache exists,
124
- * awaits the in-flight fetch or starts a new one.
1572
+ * Create Express middleware for agent verification.
1573
+ *
1574
+ * v2.9.7 moved per-route policy authority out of merchant-side source code
1575
+ * into the AstraSync dashboard. `createMiddleware` no longer accepts a
1576
+ * `routes` array — it fetches the endpoint's stored policy via
1577
+ * `GET /endpoints/:counterpartyId/routes` on init and refreshes
1578
+ * periodically. Policy edits in the dashboard take effect on the next
1579
+ * refresh (or sooner if the operator manually restarts the SDK).
1580
+ *
1581
+ * `counterpartyId` is required: the SDK can't know which endpoint's policy
1582
+ * to fetch without it. Local-development workflows that don't have an
1583
+ * AstraSync endpoint registered can omit it — the middleware logs a
1584
+ * one-time warning and falls through (allows all) until a policy is
1585
+ * fetchable.
125
1586
  */
126
- declare function getWellKnownUrls(apiBaseUrl: string): Promise<WellKnownAgenticCommerce>;
1587
+ declare function createMiddleware$1(options: ExpressMiddlewareOptions): RequestHandler;
1588
+
1589
+ declare const express_extractAstraSyncCredentials: typeof extractAstraSyncCredentials;
1590
+ declare namespace express {
1591
+ export { createMiddleware$1 as createMiddleware, express_extractAstraSyncCredentials as extractAstraSyncCredentials };
1592
+ }
1593
+
127
1594
  /**
128
- * Synchronous cache read — returns cached URLs or undefined.
129
- * Never triggers a fetch. Used by verify() to avoid extra HTTP calls
130
- * in the hot path; adapters are responsible for prefetching.
1595
+ * Create Next.js middleware for agent verification.
1596
+ *
1597
+ * v2.9.7 moved per-route policy out of merchant-side source code into the
1598
+ * AstraSync dashboard. The middleware fetches its routes from the backend
1599
+ * via `GET /endpoints/:counterpartyId/routes` on init and refreshes
1600
+ * periodically — see `ExpressMiddlewareOptions` for the rationale (a dual
1601
+ * config source silently conflicts with dashboard policy).
131
1602
  */
132
- declare function getCachedWellKnownUrls(apiBaseUrl: string): WellKnownAgenticCommerce | undefined;
1603
+ declare function createMiddleware(options: NextJsMiddlewareOptions): (request: NextRequest) => Promise<next_server.NextResponse<unknown>>;
1604
+ /**
1605
+ * Helper to create matcher config
1606
+ */
1607
+ declare function createMatcherConfig(paths: string[]): {
1608
+ matcher: string[];
1609
+ };
1610
+
1611
+ declare const nextjs_createMatcherConfig: typeof createMatcherConfig;
1612
+ declare const nextjs_createMiddleware: typeof createMiddleware;
1613
+ declare namespace nextjs {
1614
+ export { nextjs_createMatcherConfig as createMatcherConfig, nextjs_createMiddleware as createMiddleware };
1615
+ }
1616
+
1617
+ /**
1618
+ * AstraSync Universal Verification Gateway - SDK Adapter
1619
+ *
1620
+ * Direct SDK for verifying agents in any JavaScript/TypeScript environment.
1621
+ * Useful for agent-to-agent verification, serverless functions, or custom integrations.
1622
+ *
1623
+ * @example
1624
+ * ```typescript
1625
+ * import { createClient } from '@astrasyncai/verification-gateway/sdk';
1626
+ *
1627
+ * const gateway = createClient({
1628
+ * apiBaseUrl: 'https://astrasync.ai/api',
1629
+ * });
1630
+ *
1631
+ * // Verify another agent before interacting
1632
+ * const result = await gateway.verify({
1633
+ * astraId: 'ASTRA-abc123',
1634
+ * purpose: 'data-exchange',
1635
+ * });
1636
+ *
1637
+ * if (result.identityVerified && result.policyAllowed) {
1638
+ * // Safe to interact with this agent
1639
+ * }
1640
+ * ```
1641
+ */
1642
+
1643
+ /**
1644
+ * Verification Gateway SDK Client
1645
+ */
1646
+ declare class VerificationGatewayClient {
1647
+ private config;
1648
+ private timeout;
1649
+ private retryConfig;
1650
+ constructor(options: SDKOptions);
1651
+ /**
1652
+ * Full verification with all details
1653
+ */
1654
+ verify(options: {
1655
+ astraId?: string;
1656
+ apiKey?: string;
1657
+ jwt?: string;
1658
+ purpose?: string;
1659
+ action?: string;
1660
+ resourceType?: string;
1661
+ resource?: string;
1662
+ jurisdiction?: string;
1663
+ transactionValue?: number;
1664
+ currency?: string;
1665
+ isSubAgentRequest?: boolean;
1666
+ parentAgentId?: string;
1667
+ subAgentDepth?: number;
1668
+ counterpartyUrl?: string;
1669
+ counterpartyType?: string;
1670
+ }): Promise<VerificationResult>;
1671
+ /**
1672
+ * 5.4.0 (astra-pay): confirm-leg of a checkout — the ONLY call that may fire
1673
+ * first-party charge-at-redeem (server-side settlement on the owner's saved
1674
+ * instrument). This is the supported public surface for the confirm leg;
1675
+ * `verify()` deliberately does not expose the checkout fields, so settlement
1676
+ * can never fire by accident from a generic verify.
1677
+ *
1678
+ * Sends `commercePhase: 'confirm'` plus the checkout session id (per-cart
1679
+ * idempotency) and line items (order/receipt plane), and identifies the
1680
+ * merchant via `counterpartyUrl`/`counterpartyType` (required — the backend
1681
+ * only settles a merchant-mediated grant against a first-party storefront).
1682
+ * `purpose`/`action` default to the canonical shopping pair.
1683
+ *
1684
+ * Returns the full `VerificationResult`: read `.settlementOutcome` for the
1685
+ * settled/failed/requires_action/no_instrument outcome (+ `orderId`), and the
1686
+ * identity/policy/`failures` fields for a denial. On any non-`confirm`/first-
1687
+ * party path `settlementOutcome` is simply absent — no money moves.
1688
+ */
1689
+ confirmCheckout(options: {
1690
+ astraId?: string;
1691
+ apiKey?: string;
1692
+ jwt?: string;
1693
+ purpose?: string;
1694
+ action?: string;
1695
+ transactionValue?: number;
1696
+ currency?: string;
1697
+ checkoutSessionId?: string;
1698
+ checkoutItems?: VerificationRequest['checkoutItems'];
1699
+ counterpartyUrl?: string;
1700
+ counterpartyType?: string;
1701
+ }): Promise<VerificationResult>;
1702
+ /**
1703
+ * Quick verification — checks credentials and policy in one call.
1704
+ *
1705
+ * The return shape mirrors `VerificationResult`'s identity/policy
1706
+ * split. Map to HTTP status the same way: `!identityVerified` → 401,
1707
+ * `identityVerified && !policyAllowed` → 403.
1708
+ */
1709
+ quickVerify(credentials: {
1710
+ astraId?: string;
1711
+ apiKey?: string;
1712
+ jwt?: string;
1713
+ }): Promise<{
1714
+ identityVerified: boolean;
1715
+ policyAllowed: boolean;
1716
+ reason?: string;
1717
+ }>;
1718
+ /**
1719
+ * Verify a specific ASTRA-ID
1720
+ */
1721
+ verifyAstraId(astraId: string, options?: {
1722
+ purpose?: string;
1723
+ action?: string;
1724
+ }): Promise<VerificationResult>;
1725
+ /**
1726
+ * Verify using an API key
1727
+ */
1728
+ verifyApiKey(apiKey: string, options?: {
1729
+ purpose?: string;
1730
+ action?: string;
1731
+ }): Promise<VerificationResult>;
1732
+ /**
1733
+ * Clear the verification cache
1734
+ */
1735
+ clearCache(): void;
1736
+ /**
1737
+ * Execute a function with retry logic
1738
+ */
1739
+ private executeWithRetry;
1740
+ }
1741
+ /**
1742
+ * Create a new SDK client
1743
+ */
1744
+ declare function createClient(options: SDKOptions): VerificationGatewayClient;
1745
+ /**
1746
+ * One-shot verification without creating a client
1747
+ */
1748
+ declare function verifyOnce(options: SDKOptions & {
1749
+ astraId?: string;
1750
+ apiKey?: string;
1751
+ jwt?: string;
1752
+ purpose?: string;
1753
+ action?: string;
1754
+ }): Promise<VerificationResult>;
1755
+
1756
+ type sdk_VerificationGatewayClient = VerificationGatewayClient;
1757
+ declare const sdk_VerificationGatewayClient: typeof VerificationGatewayClient;
1758
+ declare const sdk_createClient: typeof createClient;
1759
+ declare const sdk_getTrustLevel: typeof getTrustLevel;
1760
+ declare const sdk_verifyOnce: typeof verifyOnce;
1761
+ declare namespace sdk {
1762
+ export { sdk_VerificationGatewayClient as VerificationGatewayClient, sdk_createClient as createClient, sdk_getTrustLevel as getTrustLevel, sdk_verifyOnce as verifyOnce };
1763
+ }
1764
+
1765
+ /**
1766
+ * HTTP Transport Adapter
1767
+ *
1768
+ * Maps AstraSync credentials to/from HTTP headers (X-Astra-* convention).
1769
+ */
1770
+
1771
+ /**
1772
+ * Inject AstraSync credentials into HTTP headers.
1773
+ */
1774
+ declare function setHttpHeaders(headers: Record<string, string>, credentials: AstraSyncCredentials): Record<string, string>;
1775
+ /**
1776
+ * Extract AstraSync credentials from HTTP headers.
1777
+ */
1778
+ declare function extractHttpCredentials(headers: Record<string, string | string[] | undefined>): AstraSyncCredentials | null;
1779
+
1780
+ /**
1781
+ * A2A (Agent-to-Agent) Transport Adapter
1782
+ *
1783
+ * Maps AstraSync credentials to/from A2A task metadata.astrasync block.
1784
+ */
1785
+
1786
+ interface A2ATask {
1787
+ metadata?: Record<string, unknown>;
1788
+ [key: string]: unknown;
1789
+ }
1790
+ /**
1791
+ * Add AstraSync credentials to an A2A task's metadata block.
1792
+ */
1793
+ declare function setA2AMetadata(task: A2ATask, credentials: AstraSyncCredentials): A2ATask;
1794
+ /**
1795
+ * Extract AstraSync credentials from an A2A task's metadata block.
1796
+ */
1797
+ declare function extractA2ACredentials(task: A2ATask): AstraSyncCredentials | null;
1798
+
1799
+ /**
1800
+ * MCP (Model Context Protocol) Transport Adapter
1801
+ *
1802
+ * Maps AstraSync credentials to/from MCP params._meta.astrasync block.
1803
+ */
1804
+
1805
+ interface McpParams {
1806
+ _meta?: Record<string, unknown>;
1807
+ [key: string]: unknown;
1808
+ }
1809
+ /**
1810
+ * Add AstraSync credentials to MCP params' _meta block.
1811
+ */
1812
+ declare function setMcpMeta(params: McpParams, credentials: AstraSyncCredentials): McpParams;
1813
+ /**
1814
+ * Extract AstraSync credentials from MCP params' _meta block.
1815
+ */
1816
+ declare function extractMcpCredentials(params: McpParams): AstraSyncCredentials | null;
1817
+
1818
+ /**
1819
+ * Protocol request -> AstraSync PDLSS purpose category mapping.
1820
+ *
1821
+ * Commerce purpose mapping table, extended with MPP + x402
1822
+ * entries (April 2026 protocol landscape).
1823
+ */
1824
+ type CommercePurpose = 'commerce.checkout.create' | 'commerce.checkout.update' | 'commerce.checkout.confirm' | 'commerce.checkout.cancel' | 'commerce.payment.execute' | 'commerce.payment.stream' | 'commerce.delegation.intent' | 'commerce.delegation.checkout' | 'commerce.delegation.payment' | 'commerce.identity_probe' | 'commerce.browsing';
1825
+ declare function mapUCPRequestToPurpose(method: string, path: string): CommercePurpose | null;
1826
+ declare function mapACPRequestToPurpose(method: string, path: string): CommercePurpose | null;
1827
+ type AP2MandateType = 'intent_mandate' | 'cart_mandate' | 'payment_mandate';
1828
+ declare function mapAP2MandateToPurpose(mandateType: AP2MandateType): CommercePurpose;
1829
+ type VIMandateType = 'checkout' | 'payment' | 'checkout.open' | 'payment.open';
1830
+ declare function mapVIMandateToPurpose(mandateType: VIMandateType): CommercePurpose;
1831
+ type RFC9421Tag = 'browse' | 'purchase' | undefined;
1832
+ declare function mapRFC9421TagToPurpose(tag: RFC9421Tag): CommercePurpose;
1833
+ type MPPIntent = 'charge' | 'session';
1834
+ declare function mapMPPRequestToPurpose(intent: MPPIntent | undefined, amount: number | undefined): CommercePurpose;
1835
+ declare function mapX402RequestToPurpose(amount: number | undefined): CommercePurpose;
1836
+ /**
1837
+ * Informational Stripe webhook events surfaced as trust signals on
1838
+ * `CommerceContext.trustSignals` but NOT routed to a PDLSS purpose.
1839
+ */
1840
+ declare const STRIPE_WEBHOOK_INFORMATIONAL_EVENTS: readonly ["payment_intent.succeeded", "payment_intent.payment_failed", "charge.refunded", "checkout.session.completed", "customer.subscription.created"];
1841
+ type StripeWebhookInformationalEvent = (typeof STRIPE_WEBHOOK_INFORMATIONAL_EVENTS)[number];
1842
+ declare function isStripeWebhookInformational(eventType: string): boolean;
1843
+
1844
+ /**
1845
+ * Per-protocol transaction-value normalization.
1846
+ *
1847
+ * Each protocol encodes amount/currency differently. This module produces a
1848
+ * uniform `TransactionValueContext` with `source` recording the extraction
1849
+ * path so trace logs can show where the value came from.
1850
+ *
1851
+ * Amount unit: "major units" (dollars/euros/etc. for fiat; native unit for
1852
+ * tokens — we do NOT convert across currencies). UCP/ACP totals are in
1853
+ * cents, so we divide by 100. MPP/x402/VI pass through as declared.
1854
+ */
1855
+ interface TransactionValueContext {
1856
+ protocol: 'vi' | 'ap2' | 'ucp' | 'acp' | 'mpp' | 'x402' | 'agentpay' | 'tap';
1857
+ amount: number;
1858
+ currency: string;
1859
+ source: string;
1860
+ /** When true, the amount is in raw atomic/minor units and could NOT be
1861
+ * converted to major units (unknown token decimals). The limit engine
1862
+ * must fail-closed — never compare raw units against major-unit limits. */
1863
+ rawUnits?: boolean;
1864
+ }
1865
+ declare function extractUCPTransactionValue(input: {
1866
+ totals?: Array<{
1867
+ type?: string;
1868
+ amount?: number;
1869
+ currency?: string;
1870
+ }>;
1871
+ }): TransactionValueContext | null;
1872
+ declare function extractACPTransactionValue(input: {
1873
+ totals?: Array<{
1874
+ type?: string;
1875
+ amount?: number;
1876
+ currency?: string;
1877
+ }>;
1878
+ }): TransactionValueContext | null;
1879
+ interface VIClaimsForValue {
1880
+ constraints?: {
1881
+ paymentAmount?: {
1882
+ currency?: string;
1883
+ min?: number;
1884
+ max?: number;
1885
+ };
1886
+ };
1887
+ l3aPaymentAmount?: {
1888
+ currency?: string;
1889
+ amount?: number;
1890
+ };
1891
+ }
1892
+ declare function extractVITransactionValue(claims: VIClaimsForValue): TransactionValueContext | null;
1893
+ interface AP2PaymentMandateForValue {
1894
+ payment_details_total?: {
1895
+ amount?: {
1896
+ value?: string | number;
1897
+ currency?: string;
1898
+ };
1899
+ };
1900
+ }
1901
+ declare function extractAP2TransactionValue(mandate: AP2PaymentMandateForValue | undefined): TransactionValueContext | null;
1902
+ interface MPPChallengeForValue {
1903
+ method?: string;
1904
+ request?: {
1905
+ amount?: number;
1906
+ currency?: string;
1907
+ } & Record<string, unknown>;
1908
+ }
1909
+ declare function extractMPPTransactionValue(challenge: MPPChallengeForValue): TransactionValueContext | null;
1910
+ interface X402RequestForValue {
1911
+ maxAmountRequired?: number;
1912
+ amount?: number;
1913
+ asset?: string;
1914
+ currency?: string;
1915
+ }
1916
+ declare function extractX402TransactionValue(req: X402RequestForValue): TransactionValueContext | null;
1917
+
1918
+ /**
1919
+ * RFC 9421 HTTP Message Signatures parser.
1920
+ *
1921
+ * Wraps `structured-headers` (transitive dep of http-message-signatures) to
1922
+ * parse the Signature-Input and Signature Dictionary headers per RFC 9421
1923
+ * Section 2.
1924
+ *
1925
+ * Produces structured metadata (kid, algorithm, covered components, tag,
1926
+ * created/expires/nonce, signature bytes) without verifying the signature —
1927
+ * verification lives in rfc9421-verify.ts.
1928
+ *
1929
+ * Shared by:
1930
+ * - Agent Pay (Mastercard) — kid resolves via Mastercard Agent Registry
1931
+ * - TAP (Visa) — kid resolves via Visa JWKS
1932
+ * - Web Bot Auth (generic transport substrate) — kid resolves via
1933
+ * /.well-known/http-message-signatures-directory
1934
+ */
1935
+ interface RFC9421SignatureParams {
1936
+ /** The label identifying the signature in the Dictionary header (e.g. "sig1"). */
1937
+ label: string;
1938
+ /** Key ID used to look up the verifying key in the relevant registry. */
1939
+ kid: string;
1940
+ /** Algorithm declared in the Signature-Input params (e.g. "ecdsa-p256-sha256", "ed25519"). */
1941
+ alg?: string;
1942
+ /** Covered components, in order, per RFC 9421 Section 2.1. */
1943
+ covered: string[];
1944
+ /** Base64url-encoded signature bytes extracted from the paired Signature header. */
1945
+ signatureBase64: string;
1946
+ /** Unix seconds when the signature was created. */
1947
+ created?: number;
1948
+ /** Unix seconds when the signature expires. */
1949
+ expires?: number;
1950
+ /** Nonce (opaque string) for replay protection. */
1951
+ nonce?: string;
1952
+ /** Tag parameter. For Agent Pay/TAP this is "browse" or "purchase"; undefined otherwise. */
1953
+ tag?: 'browse' | 'purchase' | string;
1954
+ }
1955
+ interface ParsedRFC9421 {
1956
+ signatures: RFC9421SignatureParams[];
1957
+ }
1958
+ /**
1959
+ * Parse the RFC 9421 Signature-Input and Signature headers from a request or response.
1960
+ * Returns all signatures present (a single message may carry multiple labelled signatures).
1961
+ *
1962
+ * Returns null if either header is missing or malformed.
1963
+ */
1964
+ declare function parseRFC9421(headers: Record<string, string | string[] | undefined>): ParsedRFC9421 | null;
1965
+
1966
+ type RegistryName = 'mastercard' | 'visa' | 'web-bot-auth';
1967
+ interface RegistryResolver {
1968
+ readonly name: RegistryName;
1969
+ resolve(kid: string, context?: ResolveContext): Promise<JWK | null>;
1970
+ }
1971
+ interface ResolveContext {
1972
+ origin?: string;
1973
+ algorithm?: string;
1974
+ }
1975
+
1976
+ /**
1977
+ * Shared nonce/signature replay-protection store for transport verifiers.
1978
+ *
1979
+ * Rationale: every transport-signature verifier (RFC9421, VI, AP2, ACP,
1980
+ * MPP) validates a created/expires window, but without a seen-nonce
1981
+ * cache any captured signed request can be replayed within the (default
1982
+ * 300s, now tightened to 60s) tolerance window.
1983
+ *
1984
+ * This module ships a bounded in-memory LRU as the default. Production
1985
+ * deployments with multi-pod horizontal scaling SHOULD pass a shared store
1986
+ * (Redis-backed) via the verifier options to make replay protection global
1987
+ * rather than per-pod.
1988
+ *
1989
+ * The store interface is intentionally minimal: a single `seen(key,
1990
+ * expiresAt)` method that returns true iff the key was already recorded
1991
+ * (i.e. caller should reject as a replay). Callers compose the key from
1992
+ * whichever identifiers are unique to the signature (kid + nonce + sig
1993
+ * digest, typically).
1994
+ */
1995
+ interface NonceStore {
1996
+ /**
1997
+ * Record `key` as seen. Returns true iff the key was ALREADY present —
1998
+ * i.e. caller should reject the request as a replay. Returns false on
1999
+ * first sighting (caller should proceed).
2000
+ *
2001
+ * `expiresAtMs` is a hint for the store to evict entries that can no
2002
+ * longer cause harm (their signature window has elapsed).
2003
+ */
2004
+ seen(key: string, expiresAtMs: number): boolean;
2005
+ }
2006
+
2007
+ /**
2008
+ * RFC 9421 HTTP Message Signatures verification.
2009
+ *
2010
+ * Wraps http-message-signatures (dhensby) verifyMessage() with a RegistryResolver
2011
+ * hook for kid → JWK lookup. Library handles canonicalization + ES256/EdDSA/
2012
+ * HMAC/RSA verification; we supply the key-finding callback and policy around
2013
+ * clock skew.
2014
+ *
2015
+ * Shared by:
2016
+ * - Agent Pay (Mastercard) — resolver = createMastercardRegistry
2017
+ * - TAP (Visa) — resolver = createVisaRegistry
2018
+ * - Web Bot Auth (generic) — resolver = createWebBotAuthRegistry
2019
+ */
2020
+
2021
+ interface RFC9421VerifyRequest {
2022
+ method: string;
2023
+ url: string;
2024
+ headers: Record<string, string | string[]>;
2025
+ body?: string;
2026
+ }
2027
+ interface RFC9421VerifyOptions {
2028
+ resolver: RegistryResolver;
2029
+ /** Seconds of tolerance around created/expires. Default 60 (tightened from 300). */
2030
+ clockSkewSec?: number;
2031
+ /** Injectable for deterministic tests. */
2032
+ now?: () => number;
2033
+ /** Optional replay-protection store. Defaults to in-process LRU. */
2034
+ nonceStore?: NonceStore;
2035
+ }
2036
+ interface RFC9421VerifyResult {
2037
+ ok: boolean;
2038
+ kid?: string;
2039
+ registry?: RegistryResolver['name'];
2040
+ algorithm?: string;
2041
+ error?: string;
2042
+ }
2043
+ declare function verifyRFC9421(request: RFC9421VerifyRequest, options: RFC9421VerifyOptions): Promise<RFC9421VerifyResult>;
2044
+
2045
+ /**
2046
+ * UCP (Universal Commerce Protocol) checkout session extractor.
2047
+ *
2048
+ * Google + Shopify spec (ucp.dev). Extracts checkout session context from
2049
+ * incoming HTTP requests and, at registration time, validates the
2050
+ * `/.well-known/ucp` manifest via AJV against the mirrored JSON schema.
2051
+ */
2052
+
2053
+ interface UCPTotal {
2054
+ type?: string;
2055
+ amount?: number;
2056
+ currency?: string;
2057
+ }
2058
+ interface UCPCheckoutContext {
2059
+ sessionId?: string;
2060
+ endpoint: string;
2061
+ purpose: CommercePurpose | null;
2062
+ merchantDomain?: string;
2063
+ totals?: UCPTotal[];
2064
+ paymentMethod?: string;
2065
+ manifestUrl?: string;
2066
+ }
2067
+ interface UCPRequestLike {
2068
+ method: string;
2069
+ url: string;
2070
+ headers?: Record<string, string | string[] | undefined>;
2071
+ body?: unknown;
2072
+ }
2073
+ declare function extractUCPContext(request: UCPRequestLike): UCPCheckoutContext | null;
2074
+ /**
2075
+ * Fetch and parse a UCP manifest at registration time. Returns parsed JSON
2076
+ * on success, null on any failure (network, parse, timeout). Does NOT throw.
2077
+ *
2078
+ * Schema validation is a separate step — see `validateUCPManifest`.
2079
+ */
2080
+ declare function fetchUCPManifest(manifestUrl: string, options?: {
2081
+ timeoutMs?: number;
2082
+ }): Promise<unknown | null>;
2083
+ /**
2084
+ * Validate a UCP manifest against the minimal shape we care about.
2085
+ *
2086
+ * The full UCP manifest schema lives upstream (ucp.dev) and is out of scope
2087
+ * to mirror here exhaustively. This function checks the structural guarantees
2088
+ * we depend on: required top-level fields (version, capabilities, endpoints).
2089
+ *
2090
+ * For full schema validation, consumers can pass their own AJV compiled
2091
+ * validator via `options.validator`.
2092
+ */
2093
+ interface UCPManifestValidationResult {
2094
+ ok: boolean;
2095
+ errors: string[];
2096
+ }
2097
+ declare function validateUCPManifest(manifest: unknown, options?: {
2098
+ validator?: (m: unknown) => {
2099
+ ok: boolean;
2100
+ errors: string[];
2101
+ };
2102
+ }): UCPManifestValidationResult;
2103
+
2104
+ /**
2105
+ * ACP (Agentic Commerce Protocol) request extractor.
2106
+ *
2107
+ * Co-maintained by OpenAI + Stripe. Spec at agenticcommerce.dev.
2108
+ *
2109
+ * Extracts ACP request context from HTTP requests:
2110
+ * - Multi-header parsing: Signature, Timestamp, Idempotency-Key,
2111
+ * Authorization: Bearer, API-Version
2112
+ * - Endpoint classification: Agentic Checkout (checkout_sessions.*) vs
2113
+ * Delegate Payment (agentic_commerce/delegate_payment)
2114
+ * - Payment token detection: spt_* (Stripe SharedPaymentToken),
2115
+ * vt_* (ACP vault token), unknown
2116
+ * - Totals + merchant extraction from body
2117
+ *
2118
+ * No signature verification here — see acp-verify.ts.
2119
+ */
2120
+
2121
+ type ACPEndpoint = 'checkout_sessions.create' | 'checkout_sessions.update' | 'checkout_sessions.complete' | 'checkout_sessions.cancel' | 'delegate_payment' | 'unknown';
2122
+ type ACPPaymentTokenType = 'stripe-spt' | 'acp-vt' | 'other' | null;
2123
+ interface ACPTotal {
2124
+ type?: string;
2125
+ amount?: number;
2126
+ currency?: string;
2127
+ }
2128
+ interface ACPRequestContext {
2129
+ endpoint: ACPEndpoint;
2130
+ purpose: CommercePurpose | null;
2131
+ sessionId?: string;
2132
+ merchantId?: string;
2133
+ apiVersion?: string;
2134
+ bearer?: string;
2135
+ signatureHeader?: string;
2136
+ timestampHeader?: string;
2137
+ idempotencyKey?: string;
2138
+ paymentToken?: {
2139
+ raw?: string;
2140
+ type: ACPPaymentTokenType;
2141
+ provider?: string;
2142
+ };
2143
+ totals?: ACPTotal[];
2144
+ fulfillmentOption?: string;
2145
+ rawBody?: string;
2146
+ }
2147
+ interface ACPRequestLike {
2148
+ method: string;
2149
+ url: string;
2150
+ headers?: Record<string, string | string[] | undefined>;
2151
+ body?: unknown;
2152
+ rawBody?: string;
2153
+ }
2154
+ declare function extractACPContext(request: ACPRequestLike): ACPRequestContext | null;
2155
+
2156
+ /**
2157
+ * VI (Verifiable Intent) SD-JWT extraction.
2158
+ *
2159
+ * Open-sourced 5 March 2026 by Mastercard + Google (v0.1-draft).
2160
+ * VI is a 3-layer SD-JWT chain:
2161
+ * L1 — issuer → wallet (credential provider)
2162
+ * L2 — user → agent (cnf.jwk binding to L3 agent key)
2163
+ * L3 — agent → merchant (payment or checkout mandate, split into L3a / L3b
2164
+ * cross-referenced via transaction_id)
2165
+ *
2166
+ * This module does EXTRACTION ONLY — it decodes SD-JWT structure and pulls
2167
+ * out the mandate type, kid, executionMode, 8 constraint types, checkoutHash
2168
+ * (constraint type 8), transactionId, and raw layers for later verification.
2169
+ *
2170
+ * Signature verification lives in vi-verify.ts; this module uses @sd-jwt's
2171
+ * sync decoder with a SHA-256 hasher for structural parsing only.
2172
+ */
2173
+
2174
+ type VIExecutionMode = 'Immediate' | 'Autonomous' | 'Both';
2175
+ interface VIAllowedParty {
2176
+ id?: string;
2177
+ name?: string;
2178
+ website?: string;
2179
+ }
2180
+ interface VILineItem {
2181
+ id?: string;
2182
+ acceptableItems?: string[];
2183
+ quantity?: number;
2184
+ }
2185
+ interface VIPaymentAmount {
2186
+ currency?: string;
2187
+ min?: number;
2188
+ max?: number;
2189
+ }
2190
+ interface VIBudgetLimit {
2191
+ currency?: string;
2192
+ max?: number;
2193
+ }
2194
+ interface VIRecurrence {
2195
+ frequency?: string;
2196
+ startDate?: string;
2197
+ endDate?: string;
2198
+ maxOccurrences?: number;
2199
+ }
2200
+ interface VIConstraints {
2201
+ allowedMerchants?: VIAllowedParty[];
2202
+ allowedPayees?: VIAllowedParty[];
2203
+ lineItems?: VILineItem[];
2204
+ paymentAmount?: VIPaymentAmount;
2205
+ budgetLimit?: VIBudgetLimit;
2206
+ recurrence?: VIRecurrence;
2207
+ agentRecurrence?: VIRecurrence;
2208
+ }
2209
+ interface VIExtractedClaims {
2210
+ mandateType: VIMandateType;
2211
+ kid?: string;
2212
+ executionMode?: VIExecutionMode;
2213
+ credentialProvider?: string;
2214
+ constraints: VIConstraints;
2215
+ /** VI constraint type 8 — SHA-256 of the paired L2 checkout disclosure. */
2216
+ checkoutHash?: string;
2217
+ transactionId?: string;
2218
+ rawLayers: {
2219
+ l1?: string;
2220
+ l2?: string;
2221
+ l3?: string;
2222
+ };
2223
+ }
2224
+ /**
2225
+ * Extract VI claims from a compact SD-JWT string.
2226
+ *
2227
+ * Input shape:
2228
+ * <jwt>~<disclosure1>~<disclosure2>~...~<kbJwt?>
2229
+ *
2230
+ * Returns null if parsing fails at any layer. Does not verify signatures.
2231
+ */
2232
+ declare function extractVIClaims(sdJwtCompact: string): VIExtractedClaims | null;
2233
+
2234
+ /**
2235
+ * Stripe webhook HMAC-SHA256 verifier (inline).
2236
+ *
2237
+ * Stripe-Signature header format: "t=TIMESTAMP,v1=HEX_SIGNATURE"
2238
+ * - t: unix seconds when Stripe signed the webhook
2239
+ * - v1: HMAC-SHA256(webhook_secret, `${t}.${payload}`) as hex
2240
+ *
2241
+ * Multiple v1 signatures can coexist during secret rotation; any match wins.
2242
+ * Default tolerance on timestamp age: 300s (matches Stripe's own default).
2243
+ *
2244
+ * Documented at docs.stripe.com — we intentionally inline ~25 LOC rather
2245
+ * than pull in the full stripe npm package (MIT but 600KB+ with deps).
2246
+ */
2247
+ interface VerifyStripeWebhookResult {
2248
+ ok: boolean;
2249
+ timestamp?: number;
2250
+ error?: string;
2251
+ }
2252
+ interface VerifyStripeWebhookOptions {
2253
+ toleranceSec?: number;
2254
+ /** Injectable for deterministic tests. */
2255
+ now?: () => number;
2256
+ }
2257
+ declare function verifyStripeWebhook(payload: string, signatureHeader: string | undefined, secret: string, options?: VerifyStripeWebhookOptions): VerifyStripeWebhookResult;
2258
+
2259
+ /**
2260
+ * PDLSS constraint evaluation.
2261
+ *
2262
+ * Evaluates VI constraint types 1-4 (merchant/payee allowlists, line items,
2263
+ * payment amount) + MPP/x402 payment-method allowlist + spending-limit
2264
+ * against a transaction context.
2265
+ *
2266
+ * Types 5/6/7 (budget, recurrence, agent_recurrence) extract through but
2267
+ * enforcement is deferred to the cross-merchant budget service.
2268
+ * This module returns per-constraint {ok, reason} results
2269
+ * so a policy layer can decide hard-deny vs trust-signal.
2270
+ */
2271
+
2272
+ interface TransactionContext {
2273
+ amount?: number;
2274
+ currency?: string;
2275
+ merchant?: {
2276
+ id?: string;
2277
+ website?: string;
2278
+ };
2279
+ payee?: {
2280
+ id?: string;
2281
+ website?: string;
2282
+ };
2283
+ lineItems?: Array<{
2284
+ id?: string;
2285
+ quantity?: number;
2286
+ }>;
2287
+ /** For MPP / x402 payment-method enforcement. */
2288
+ paymentMethod?: string;
2289
+ }
2290
+ type ConstraintKey = 'merchant' | 'payee' | 'lineItems' | 'amount' | 'paymentMethod';
2291
+ interface ConstraintResult {
2292
+ ok: boolean;
2293
+ reason?: string;
2294
+ }
2295
+ interface ConstraintEvalResult {
2296
+ ok: boolean;
2297
+ results: Record<string, ConstraintResult>;
2298
+ reasons: string[];
2299
+ }
2300
+ interface VIConstraintEvalInput {
2301
+ constraints: VIConstraints;
2302
+ transaction: TransactionContext;
2303
+ }
2304
+ declare function evaluateVIConstraints(input: VIConstraintEvalInput): ConstraintEvalResult;
2305
+ interface PaymentMethodAllowlistInput {
2306
+ allowedMethods?: string[];
2307
+ requestedMethod?: string;
2308
+ }
2309
+ declare function evaluatePaymentMethodAllowlist(input: PaymentMethodAllowlistInput): ConstraintResult;
2310
+ interface SpendingLimitInput {
2311
+ limit?: {
2312
+ amount?: number;
2313
+ currency?: string;
2314
+ };
2315
+ requested?: {
2316
+ amount?: number;
2317
+ currency?: string;
2318
+ };
2319
+ }
2320
+ declare function evaluateSpendingLimit(input: SpendingLimitInput): ConstraintResult;
2321
+
2322
+ /**
2323
+ * Cross-protocol agent identity binding.
2324
+ *
2325
+ * Every commerce layer claims an agent identity differently:
2326
+ * - VI L3 kid (SD-JWT header)
2327
+ * - AP2 agent_id (mandate payload)
2328
+ * - ACP Authorization: Bearer token (merchant-issued pre-shared)
2329
+ * - MPP Credential `source` field (DID or chain-native key)
2330
+ * - x402 client wallet address
2331
+ * - RFC 9421 kid (Agent Pay / TAP / Web Bot Auth)
2332
+ *
2333
+ * This module maps any such claim to a single AstraSync agent via a
2334
+ * caller-supplied resolver (typically delegates to the counterparty service),
2335
+ * then flags whether multiple claims on the same request resolve to different
2336
+ * agents (a trust signal for PDLSS).
2337
+ *
2338
+ * This is AstraSync whitespace — no vendor owns multi-protocol identity
2339
+ * unification.
2340
+ */
2341
+ interface IdentityClaim {
2342
+ /** Originating protocol label: 'vi' | 'ap2' | 'acp' | 'mpp' | 'x402' | 'agentpay' | 'tap' | 'webbotauth' */
2343
+ protocol: string;
2344
+ /** Claim field name, e.g. 'kid', 'agent_id', 'source', 'bearer'. */
2345
+ field: string;
2346
+ /** Claim value as presented on the wire. */
2347
+ value: string;
2348
+ }
2349
+ interface IdentityBindingResult {
2350
+ claims: IdentityClaim[];
2351
+ mappedAstraSyncAgentId?: string;
2352
+ /**
2353
+ * True when two or more claims resolve to different AstraSync agents.
2354
+ * Surfaced as a trust signal rather than an auto-deny — legitimate flows
2355
+ * (e.g. delegate payments) can legitimately carry multiple identities.
2356
+ */
2357
+ mismatchAcrossLayers: boolean;
2358
+ /** Per-claim resolution result for audit / debugging. */
2359
+ resolutions: Array<{
2360
+ claim: IdentityClaim;
2361
+ agentId: string | null;
2362
+ }>;
2363
+ }
2364
+ type IdentityResolver = (claim: IdentityClaim) => Promise<string | null>;
2365
+ declare function bindIdentity(claims: IdentityClaim[], resolver: IdentityResolver): Promise<IdentityBindingResult>;
2366
+ /**
2367
+ * Helper constructors — keep protocol/field strings consistent across the
2368
+ * codebase and make tests readable.
2369
+ */
2370
+ declare const claim: {
2371
+ viKid: (value: string) => IdentityClaim;
2372
+ ap2AgentId: (value: string) => IdentityClaim;
2373
+ acpBearer: (value: string) => IdentityClaim;
2374
+ mppSource: (value: string) => IdentityClaim;
2375
+ x402Wallet: (value: string) => IdentityClaim;
2376
+ agentPayKid: (value: string) => IdentityClaim;
2377
+ tapKid: (value: string) => IdentityClaim;
2378
+ webBotAuthKid: (value: string) => IdentityClaim;
2379
+ };
2380
+
2381
+ /**
2382
+ * AP2 (Agent Payments Protocol) mandate extraction.
2383
+ *
2384
+ * Google-led, launched 3 April 2026 with 60+ partners (Mastercard, PayPal,
2385
+ * Coinbase, AmEx, Revolut, UnionPay, ...). AP2 ships three mandate types as
2386
+ * SD-JWTs in series:
2387
+ * - intent_mandate — user declares intent (amount, merchant category, etc.)
2388
+ * - cart_mandate — user approves a cart (specific items, totals)
2389
+ * - payment_mandate — authorizes the actual payment rail
2390
+ *
2391
+ * Mandates are cross-referenced via ids; each is an SD-JWT over ES256 (or
2392
+ * equivalent). We decode via @sd-jwt/core and extract the AP2-specific
2393
+ * shape — verification lives in ap2-verify.ts.
2394
+ */
2395
+
2396
+ interface AP2PaymentDetailsTotal {
2397
+ amount?: {
2398
+ value?: string | number;
2399
+ currency?: string;
2400
+ };
2401
+ label?: string;
2402
+ }
2403
+ interface AP2IntentMandateClaims {
2404
+ type: 'intent_mandate';
2405
+ agent_id?: string;
2406
+ user_id?: string;
2407
+ merchant_category?: string;
2408
+ allowedMerchantDomains?: string[];
2409
+ paymentMethods?: string[];
2410
+ expires?: string;
2411
+ payment_details_total?: AP2PaymentDetailsTotal;
2412
+ raw: Record<string, unknown>;
2413
+ }
2414
+ interface AP2CartMandateClaims {
2415
+ type: 'cart_mandate';
2416
+ agent_id?: string;
2417
+ intent_mandate_id?: string;
2418
+ merchant_id?: string;
2419
+ line_items?: Array<{
2420
+ id?: string;
2421
+ quantity?: number;
2422
+ price?: {
2423
+ value?: string | number;
2424
+ currency?: string;
2425
+ };
2426
+ }>;
2427
+ payment_details_total?: AP2PaymentDetailsTotal;
2428
+ expires?: string;
2429
+ raw: Record<string, unknown>;
2430
+ }
2431
+ interface AP2PaymentMandateClaims {
2432
+ type: 'payment_mandate';
2433
+ agent_id?: string;
2434
+ cart_mandate_id?: string;
2435
+ payment_method?: string;
2436
+ payment_details_total?: AP2PaymentDetailsTotal;
2437
+ credential_provider?: string;
2438
+ raw: Record<string, unknown>;
2439
+ }
2440
+ type AP2MandateClaims = AP2IntentMandateClaims | AP2CartMandateClaims | AP2PaymentMandateClaims;
2441
+ interface AP2MandateTriple {
2442
+ intent?: AP2IntentMandateClaims;
2443
+ cart?: AP2CartMandateClaims;
2444
+ payment?: AP2PaymentMandateClaims;
2445
+ rawLayers: {
2446
+ intentJwt?: string;
2447
+ cartJwt?: string;
2448
+ paymentJwt?: string;
2449
+ };
2450
+ }
2451
+ /**
2452
+ * Extract a single AP2 mandate from a compact SD-JWT.
2453
+ * Returns null if the SD-JWT is malformed or lacks a recognized type field.
2454
+ */
2455
+ declare function extractAP2Mandate(sdJwtCompact: string): AP2MandateClaims | null;
2456
+ interface AP2MandateTripleInput {
2457
+ intent?: string;
2458
+ cart?: string;
2459
+ payment?: string;
2460
+ }
2461
+ /**
2462
+ * Extract an intent / cart / payment triple, returning whichever are present.
2463
+ * Does NOT enforce cross-reference consistency — that's ap2-verify.ts's job.
2464
+ */
2465
+ declare function extractAP2Mandates(input: AP2MandateTripleInput): AP2MandateTriple;
2466
+
2467
+ /**
2468
+ * AP2 mandate chain verification.
2469
+ *
2470
+ * Checks the cross-reference consistency of an intent → cart → payment
2471
+ * triple. Does NOT verify cryptographic signatures here (that's a call to
2472
+ * @sd-jwt/core which needs the agent's / CP's public key; expose via a
2473
+ * verifier callback so pipeline can plug in the right resolver).
2474
+ *
2475
+ * Rules (per AP2 spec v0.1-draft):
2476
+ * - cart.intent_mandate_id must equal the intent mandate's canonical id (if present)
2477
+ * - payment.cart_mandate_id must equal the cart mandate's canonical id (if present)
2478
+ * - agent_id must match across all three layers
2479
+ * - payment_method in payment mandate must be in intent.paymentMethods (if declared)
2480
+ * - cart totals must not exceed intent totals (if both declared in same currency)
2481
+ * - no mandate may be expired (beyond clock skew)
2482
+ */
2483
+
2484
+ interface AP2VerifyInput {
2485
+ triple: AP2MandateTriple;
2486
+ /**
2487
+ * Clock skew tolerance in seconds for expiry checks. Default 60s
2488
+ * (tightened from the previous 300s default).
2489
+ */
2490
+ clockSkewSec?: number;
2491
+ now?: () => number;
2492
+ /**
2493
+ * Optional replay-protection store. Defaults to in-process LRU. When the
2494
+ * payment mandate carries an id, this verifier registers it as seen so
2495
+ * the same payment mandate replayed within the expiry window is rejected.
2496
+ */
2497
+ nonceStore?: NonceStore;
2498
+ }
2499
+ interface AP2ChainResult {
2500
+ ok: boolean;
2501
+ checks: {
2502
+ intentPresent: boolean;
2503
+ cartRefOk: boolean;
2504
+ paymentRefOk: boolean;
2505
+ agentIdContinuity: boolean;
2506
+ paymentMethodAllowed: boolean;
2507
+ totalsConsistent: boolean;
2508
+ expiryOk: boolean;
2509
+ };
2510
+ agentId?: string;
2511
+ errors: string[];
2512
+ }
2513
+ declare function verifyAP2Chain(input: AP2VerifyInput): AP2ChainResult;
2514
+
2515
+ /**
2516
+ * ACP detached-JSON-signature verifier.
2517
+ *
2518
+ * ACP (Agentic Commerce Protocol, OpenAI + Stripe) uses detached JSON
2519
+ * signatures over request bodies. The public signature algorithm is NOT
2520
+ * specified in open docs as of April 2026 (docs.stripe.com/agentic-commerce/*
2521
+ * is Private Preview). We implement Ed25519 and ES256 candidates against
2522
+ * whichever public key the caller supplies, and report algorithm-unsupported
2523
+ * as a trust signal rather than a hard fail so policy can weight it.
2524
+ *
2525
+ * Timestamp freshness (>300s default) IS a hard fail — prevents replay.
2526
+ *
2527
+ * Bearer-token → AstraSync agent binding is delegated to caller-supplied
2528
+ * resolver (typically the counterparty service).
2529
+ */
2530
+
2531
+ type ACPSignatureAlgorithm = 'ed25519' | 'es256' | 'unsupported';
2532
+ interface ACPVerifyInput {
2533
+ /** Raw request body over which the signature was computed. */
2534
+ rawBody: string;
2535
+ /** Value of the Signature header. Expected to be base64 (either standard or url). */
2536
+ signatureHeader?: string;
2537
+ /** Value of the Timestamp header (unix seconds as string, or ISO 8601). */
2538
+ timestampHeader?: string;
2539
+ /** Candidate public keys to try. First matching algorithm wins. */
2540
+ candidateKeys: Array<{
2541
+ jwk: JWK;
2542
+ alg?: ACPSignatureAlgorithm | string;
2543
+ }>;
2544
+ /** Clock skew tolerance in seconds (default 60, tightened from 300). */
2545
+ clockSkewSec?: number;
2546
+ /** Injectable now for tests. */
2547
+ now?: () => number;
2548
+ /** Optional replay-protection store. Defaults to in-process LRU. */
2549
+ nonceStore?: NonceStore;
2550
+ }
2551
+ interface ACPVerifyResult {
2552
+ ok: boolean;
2553
+ algorithm?: ACPSignatureAlgorithm;
2554
+ error?: string;
2555
+ /** True when timestamp is outside tolerance. */
2556
+ timestampStale?: boolean;
2557
+ }
2558
+ declare function verifyACPSignature(input: ACPVerifyInput): Promise<ACPVerifyResult>;
2559
+
2560
+ /**
2561
+ * MPP (Machine Payments Protocol) extractor.
2562
+ *
2563
+ * Wraps mppx (wevm) — pinned to 0.5.13, wrapped behind this adapter so
2564
+ * upgrades localise here. MPP launched March 18 2026 (Stripe + Tempo +
2565
+ * Paradigm), IETF draft-ryan-httpauth-payment-01.
2566
+ *
2567
+ * Flow:
2568
+ * Client → GET /resource
2569
+ * Server → 402 + WWW-Authenticate: Payment id=..., realm=..., method=tempo|stripe|...
2570
+ * Client → GET /resource with Authorization: Payment <base64url-json credential>
2571
+ * Server → 200 + Payment-Receipt: <base64url-json receipt>
2572
+ *
2573
+ * What we extract:
2574
+ * - Challenge: id, realm, method, intent, request{amount,currency,...}, expires, digest
2575
+ * - Credential: challenge + source (DID/chain-key) + payload (method-specific)
2576
+ * - Receipt: challengeId, method, reference (tx hash / pi_... ID), settlement
2577
+ * - Multi-method 402 offers (may be multiple WWW-Authenticate headers)
2578
+ *
2579
+ * What we do NOT verify here (pass-through):
2580
+ * - HMAC challenge binding (requires merchant's MPP_SECRET_KEY)
2581
+ * - Payment proof cryptography (Tempo tx sig, Stripe SPT, Lightning preimage)
2582
+ * — each requires upstream connectivity
2583
+ *
2584
+ * Verification (expiry + BodyDigest + source extraction) in mpp-verify.ts.
2585
+ */
2586
+ interface MPPChallengeSummary {
2587
+ id: string;
2588
+ realm: string;
2589
+ method: string;
2590
+ intent: string;
2591
+ /** Method-specific request data (amount, currency, recipient, etc.) */
2592
+ request: Record<string, unknown>;
2593
+ expires?: string;
2594
+ digest?: string;
2595
+ description?: string;
2596
+ opaque?: Record<string, string>;
2597
+ }
2598
+ interface MPPCredentialSummary {
2599
+ challenge: MPPChallengeSummary;
2600
+ /** DID or chain-native key identifying the payer. */
2601
+ source?: string;
2602
+ /** Method-specific payment proof (Tempo tx, SPT, Lightning preimage, etc.). */
2603
+ payload: unknown;
2604
+ }
2605
+ interface MPPReceiptSummary {
2606
+ method?: string;
2607
+ reference?: string;
2608
+ externalId?: string;
2609
+ status?: string;
2610
+ timestamp?: string;
2611
+ raw: Record<string, unknown>;
2612
+ }
2613
+ type MPPKind = 'challenge' | 'credential' | 'receipt' | 'error' | 'unknown';
2614
+ interface MPPRequestContext {
2615
+ kind: MPPKind;
2616
+ /** For 402 responses: one or more challenge offers. */
2617
+ challenges?: MPPChallengeSummary[];
2618
+ /** For requests with Authorization: Payment header. */
2619
+ credential?: MPPCredentialSummary;
2620
+ /** For 200 responses with Payment-Receipt header. */
2621
+ receipt?: MPPReceiptSummary;
2622
+ /** For problem+json error responses. */
2623
+ error?: {
2624
+ type?: string;
2625
+ title?: string;
2626
+ detail?: string;
2627
+ };
2628
+ /** Detected payment methods offered (for multi-method 402). */
2629
+ offeredMethods?: string[];
2630
+ /** Raw body captured for BodyDigest verification in mpp-verify.ts. */
2631
+ rawBody?: string;
2632
+ }
2633
+ interface MPPRequestLike {
2634
+ method: string;
2635
+ url: string;
2636
+ headers: Record<string, string | string[] | undefined>;
2637
+ body?: unknown;
2638
+ rawBody?: string;
2639
+ }
2640
+ interface MPPResponseLike {
2641
+ status: number;
2642
+ headers: Record<string, string | string[] | undefined>;
2643
+ body?: unknown;
2644
+ rawBody?: string;
2645
+ }
2646
+ /**
2647
+ * Extract MPP context from an agent → merchant request.
2648
+ * Looks for `Authorization: Payment <credential>` header.
2649
+ */
2650
+ declare function extractMPPFromRequest(request: MPPRequestLike): MPPRequestContext | null;
2651
+ /**
2652
+ * Extract MPP context from a merchant → agent response.
2653
+ * Handles 402 (challenge offers), 200 (receipt), 4xx (problem+json errors).
2654
+ */
2655
+ declare function extractMPPFromResponse(response: MPPResponseLike): MPPRequestContext | null;
2656
+ /**
2657
+ * Extract from either a request OR a response, auto-detecting which has MPP
2658
+ * artifacts. Convenience for pipeline callers.
2659
+ */
2660
+ declare function extractMPPContext(message: {
2661
+ request: MPPRequestLike;
2662
+ } | {
2663
+ response: MPPResponseLike;
2664
+ } | (MPPRequestLike & Partial<MPPResponseLike>)): MPPRequestContext | null;
2665
+
2666
+ /**
2667
+ * MPP verification — expiry + optional BodyDigest + source extraction.
2668
+ *
2669
+ * We do NOT verify the challenge's HMAC binding (needs merchant's secret)
2670
+ * or the cryptographic payment proof (per-method, requires upstream
2671
+ * connectivity). Those are the merchant's / settlement layer's job.
2672
+ *
2673
+ * Our job: structural correctness, expiry policy, tamper detection via
2674
+ * optional BodyDigest, and identity extraction for PDLSS binding.
2675
+ */
2676
+
2677
+ interface MPPVerifyInput {
2678
+ context: MPPRequestContext;
2679
+ /** Raw request body to validate BodyDigest against, if the challenge declares one. */
2680
+ rawBody?: string;
2681
+ /** Seconds of clock-skew tolerance on challenge.expires. Default 60. */
2682
+ clockSkewSec?: number;
2683
+ /** Injectable for deterministic tests. */
2684
+ now?: () => number;
2685
+ /** Optional replay-protection store. Defaults to in-process LRU. */
2686
+ nonceStore?: NonceStore;
2687
+ }
2688
+ interface MPPVerifyResult {
2689
+ ok: boolean;
2690
+ expiryOk: boolean;
2691
+ bodyDigestOk: boolean | null;
2692
+ source?: string;
2693
+ method?: string;
2694
+ error?: string;
2695
+ }
2696
+ declare function verifyMPP(input: MPPVerifyInput): MPPVerifyResult;
2697
+
2698
+ /**
2699
+ * x402 (Coinbase / Linux Foundation x402 Foundation) extractor.
2700
+ *
2701
+ * Wraps @x402/core's schema parsers. x402 Foundation launched April 2 2026
2702
+ * with v2 adding network-agnostic identifiers + multiple facilitators +
2703
+ * Bazaar discovery. MPP (Machine Payments Protocol) is the IETF-formalised
2704
+ * superset of x402; this module normalizes x402 output to MPP-shape so
2705
+ * downstream pipeline code is uniform.
2706
+ *
2707
+ * Where x402 lives on the wire:
2708
+ * - 402 response body (v2) OR `X-PAYMENT-REQUIRED` header (v1) — PaymentRequired
2709
+ * - Request body (v2) OR `X-PAYMENT` header (v1, base64) — PaymentPayload
2710
+ */
2711
+ type X402Kind = 'required' | 'payload' | 'error' | 'unknown';
2712
+ interface X402RequirementsSummary {
2713
+ scheme: string;
2714
+ network: string;
2715
+ asset: string;
2716
+ /** Normalized to string for v1/v2 compat — v1 uses maxAmountRequired, v2 uses amount. */
2717
+ amount: string;
2718
+ payTo: string;
2719
+ maxTimeoutSeconds?: number;
2720
+ resource?: string;
2721
+ description?: string;
2722
+ }
2723
+ interface X402RequestContext {
2724
+ kind: X402Kind;
2725
+ version: 1 | 2 | null;
2726
+ /** For 402 responses: the PaymentRequired body. */
2727
+ paymentRequired?: {
2728
+ resource: string;
2729
+ accepts: X402RequirementsSummary[];
2730
+ extensions?: Record<string, unknown>;
2731
+ error?: string;
2732
+ };
2733
+ /** For request body (v2) or X-PAYMENT header (v1 base64): the PaymentPayload. */
2734
+ paymentPayload?: {
2735
+ scheme: string;
2736
+ network: string;
2737
+ /** Free-form per-scheme payload (e.g. EIP-3009 authorization, Solana tx). */
2738
+ payload: Record<string, unknown>;
2739
+ extensions?: Record<string, unknown>;
2740
+ };
2741
+ error?: {
2742
+ type: string;
2743
+ detail?: string;
2744
+ };
2745
+ /** Whether this was parsed from a header (v1 back-compat) or body (v2). */
2746
+ source: 'header' | 'body' | null;
2747
+ }
2748
+ interface X402RequestLike {
2749
+ method?: string;
2750
+ url?: string;
2751
+ headers?: Record<string, string | string[] | undefined>;
2752
+ body?: unknown;
2753
+ }
2754
+ interface X402ResponseLike {
2755
+ status?: number;
2756
+ headers?: Record<string, string | string[] | undefined>;
2757
+ body?: unknown;
2758
+ }
2759
+ /**
2760
+ * Extract x402 PaymentPayload from an agent → merchant request.
2761
+ * Checks v2 body (if it parses as PaymentPayload) and v1 X-PAYMENT header.
2762
+ */
2763
+ declare function extractX402FromRequest(request: X402RequestLike): X402RequestContext | null;
2764
+ /**
2765
+ * Extract x402 PaymentRequired from a merchant → agent 402 response.
2766
+ */
2767
+ declare function extractX402FromResponse(response: X402ResponseLike): X402RequestContext | null;
2768
+ declare function extractX402Context(message: {
2769
+ request: X402RequestLike;
2770
+ } | {
2771
+ response: X402ResponseLike;
2772
+ } | (X402RequestLike & Partial<X402ResponseLike>)): X402RequestContext | null;
2773
+
2774
+ /**
2775
+ * VI (Verifiable Intent) 3-layer SD-JWT chain verification.
2776
+ *
2777
+ * VI chains: L1 (credential provider → wallet) → L2 (user → agent) → L3
2778
+ * (agent → merchant). L3 itself can split into L3a (payment mandate) + L3b
2779
+ * (checkout mandate) cross-referenced via transaction_id, with L3b carrying
2780
+ * a checkout_hash (VI constraint type 8) that must match SHA-256 of the L2
2781
+ * checkout disclosure.
2782
+ *
2783
+ * Signature primitives are delegated to @sd-jwt/core (via our extractor);
2784
+ * cnf.jwk chain-walking + cross-references + checkout_hash binding is
2785
+ * AstraSync-specific composition logic — that's the whitespace here.
2786
+ *
2787
+ * This module does NOT re-verify selective-disclosure hashes (the extractor
2788
+ * already applied them via @sd-jwt/core). It DOES verify:
2789
+ * - cnf.jwk in L1 payload points to L2's signing key (thumbprint match)
2790
+ * - cnf.jwk in L2 payload points to L3's signing key
2791
+ * - L3a.transaction_id === L3b.transaction_id (when both present)
2792
+ * - L3b.checkout_hash === SHA-256(L2 canonical checkout disclosure) — type 8
2793
+ * - mandate-level `exp` is not in the past (beyond clock skew)
2794
+ *
2795
+ * Cryptographic signature verification on each layer uses the verifier
2796
+ * callback the caller supplies (e.g. resolves via @sd-jwt/core with the
2797
+ * right JWK from the L1 issuer's JWKS).
2798
+ */
2799
+
2800
+ interface VILayer {
2801
+ /** Compact SD-JWT / JWS for this layer. */
2802
+ compact: string;
2803
+ /** Decoded JWT payload (already disclosure-merged). */
2804
+ payload: Record<string, unknown>;
2805
+ /** Decoded JWT header. */
2806
+ header: Record<string, unknown>;
2807
+ }
2808
+ interface VIVerifyInput {
2809
+ /**
2810
+ * Layers in chain order. L1 is REQUIRED by default —
2811
+ * without L1 there is no chain root and L2 can be verified against any
2812
+ * attacker-supplied key. Callers who have resolved L2's signing key by
2813
+ * a trusted out-of-band mechanism (wallet binding, prior protocol step)
2814
+ * MUST set `allowUnboundChain: true` AND supply `expectedL2Key`.
2815
+ */
2816
+ layers: {
2817
+ l1?: VILayer;
2818
+ l2: VILayer;
2819
+ l3a?: VILayer;
2820
+ l3b?: VILayer;
2821
+ };
2822
+ /**
2823
+ * Verifier callback invoked per layer. Should return true iff the layer's
2824
+ * JWS signature verifies against the resolved public key (for L2 this is
2825
+ * L1's cnf.jwk; for L3 this is L2's cnf.jwk; for L1 this is the issuer's
2826
+ * JWKS per `iss` claim).
2827
+ */
2828
+ verifySignature: (layer: VILayer, expectedKey: JWK | null) => Promise<boolean>;
2829
+ /**
2830
+ * Clock skew tolerance in seconds for expiry checks. Default 60s
2831
+ * (tightened from the previous 300s default).
2832
+ */
2833
+ clockSkewSec?: number;
2834
+ now?: () => number;
2835
+ /**
2836
+ * Explicit opt-in to verify a chain with L1 omitted.
2837
+ * Defaults to false. When true, `expectedL2Key` MUST also be supplied
2838
+ * (used as the expected signing key for L2 verification).
2839
+ */
2840
+ allowUnboundChain?: boolean;
2841
+ /** Required when allowUnboundChain === true. */
2842
+ expectedL2Key?: JWK;
2843
+ /** Optional replay-protection store. Defaults to in-process LRU. */
2844
+ nonceStore?: NonceStore;
2845
+ }
2846
+ interface VIVerifyResult {
2847
+ ok: boolean;
2848
+ checks: {
2849
+ l1SigOk: boolean | null;
2850
+ l2SigOk: boolean;
2851
+ l3aSigOk: boolean | null;
2852
+ l3bSigOk: boolean | null;
2853
+ l1BindsL2: boolean;
2854
+ l2BindsL3: boolean;
2855
+ l3aL3bTxnIdMatch: boolean | null;
2856
+ checkoutHashOk: boolean | null;
2857
+ expiryOk: boolean;
2858
+ };
2859
+ errors: string[];
2860
+ }
2861
+ declare function verifyVIChain(input: VIVerifyInput): Promise<VIVerifyResult>;
2862
+
2863
+ /**
2864
+ * Commerce pipeline orchestrator.
2865
+ *
2866
+ * Ties together extractors + verifiers + identity binding + constraint
2867
+ * evaluation + trust signals into a single CommerceContext result.
2868
+ *
2869
+ * This is AstraSync whitespace: the orchestration over the library-backed
2870
+ * primitives. The backend verify-access service is the sole per-request
2871
+ * caller — the edge adapters forward raw artifacts to verify-access and
2872
+ * never call this module directly. The admin transport playground also
2873
+ * calls it ad-hoc.
2874
+ *
2875
+ * Policy:
2876
+ * - Hard-deny (ok=false) on bad signatures, expired mandates, constraint
2877
+ * failures, identity cannot be bound.
2878
+ * - Trust signal (ok remains policy-driven) on ACP algorithm unsupported,
2879
+ * Stripe webhook HMAC fail, payment-token type unknown, cross-layer
2880
+ * identity mismatch.
2881
+ */
2882
+
2883
+ type CommerceProtocol = 'vi' | 'ap2' | 'ucp' | 'acp' | 'agentpay' | 'tap' | 'mpp' | 'x402';
2884
+ interface CommercePipelineInput {
2885
+ protocol: CommerceProtocol;
2886
+ vi?: {
2887
+ claims: VIExtractedClaims;
2888
+ verifyInput?: VIVerifyInput;
2889
+ };
2890
+ ap2?: {
2891
+ triple: AP2MandateTriple;
2892
+ };
2893
+ ucp?: UCPCheckoutContext;
2894
+ acp?: {
2895
+ context: ACPRequestContext;
2896
+ verifyInput?: Parameters<typeof verifyACPSignature>[0];
2897
+ };
2898
+ rfc9421?: {
2899
+ request: RFC9421VerifyRequest;
2900
+ tag?: 'browse' | 'purchase' | string;
2901
+ verifyOptions: Parameters<typeof verifyRFC9421>[1];
2902
+ };
2903
+ mpp?: {
2904
+ context: MPPRequestContext;
2905
+ rawBody?: string;
2906
+ };
2907
+ x402?: X402RequestContext;
2908
+ stripeWebhook?: {
2909
+ payload: string;
2910
+ signatureHeader: string;
2911
+ secret: string;
2912
+ };
2913
+ transaction?: TransactionContext;
2914
+ registeredConstraints?: {
2915
+ allowedPaymentMethods?: string[];
2916
+ spendingLimit?: {
2917
+ amount?: number;
2918
+ currency?: string;
2919
+ };
2920
+ };
2921
+ identityResolver?: IdentityResolver;
2922
+ clockSkewSec?: number;
2923
+ now?: () => number;
2924
+ }
2925
+ interface CommerceSignatureStack {
2926
+ vi?: VIVerifyResult;
2927
+ ap2?: AP2ChainResult;
2928
+ acp?: ACPVerifyResult;
2929
+ rfc9421?: RFC9421VerifyResult;
2930
+ mpp?: MPPVerifyResult;
2931
+ stripeWebhook?: VerifyStripeWebhookResult;
2932
+ }
2933
+ interface CommerceContext {
2934
+ protocol: CommerceProtocol;
2935
+ purpose: CommercePurpose | null;
2936
+ transactionValue?: TransactionValueContext;
2937
+ signatures: CommerceSignatureStack;
2938
+ identity?: {
2939
+ claims: IdentityClaim[];
2940
+ mappedAstraSyncAgentId?: string;
2941
+ mismatchAcrossLayers: boolean;
2942
+ };
2943
+ paymentToken?: {
2944
+ present: boolean;
2945
+ type: 'stripe-spt' | 'acp-vt' | 'tempo-tx' | 'other' | null;
2946
+ };
2947
+ mppMethodsOffered?: string[];
2948
+ constraints?: ConstraintEvalResult;
2949
+ receipt?: {
2950
+ method?: string;
2951
+ reference?: string;
2952
+ status?: string;
2953
+ timestamp?: string;
2954
+ };
2955
+ trustSignals: string[];
2956
+ timings: {
2957
+ extractMs: number;
2958
+ verifyMs: number;
2959
+ evalMs: number;
2960
+ };
2961
+ /** False when any hard-deny rule fires. */
2962
+ ok: boolean;
2963
+ }
2964
+ declare function runCommercePipeline(input: CommercePipelineInput): Promise<CommerceContext>;
2965
+
2966
+ /**
2967
+ * Pluggable extractor registry for the Trusted Agent Gateway edge
2968
+ * adapters and other callers that need a curated extractor set.
2969
+ *
2970
+ * Built-in extractors (VI, UCP, ACP, RFC 9421, MPP, x402, Stripe webhook)
2971
+ * are NOT auto-registered. A caller imports this module, picks the set
2972
+ * it wants, and calls registerTransportExtractor() for each.
2973
+ *
2974
+ * Re-registering by name replaces the prior extractor (idempotent).
2975
+ */
2976
+ interface ExtractorRequestLike {
2977
+ method?: string;
2978
+ url?: string;
2979
+ headers?: Record<string, string | string[] | undefined>;
2980
+ body?: unknown;
2981
+ }
2982
+ interface TransportExtractor<T = unknown> {
2983
+ readonly name: string;
2984
+ match(request: ExtractorRequestLike): boolean;
2985
+ extract(request: ExtractorRequestLike): T | Promise<T> | null;
2986
+ }
2987
+ declare function registerTransportExtractor<T>(extractor: TransportExtractor<T>): void;
2988
+ declare function getTransportExtractors(): ReadonlyArray<TransportExtractor>;
2989
+ declare function getTransportExtractor(name: string): TransportExtractor | undefined;
2990
+ declare function clearTransportExtractors(): void;
2991
+ /**
2992
+ * Helper: run all matching extractors against a request and return their
2993
+ * extracted contexts keyed by extractor name. Skips extractors whose
2994
+ * `match()` returns false.
2995
+ */
2996
+ declare function runMatchingExtractors(request: ExtractorRequestLike): Promise<Record<string, unknown>>;
2997
+
2998
+ /**
2999
+ * Visa JWKS registry resolver.
3000
+ *
3001
+ * Default endpoint: https://mcp.visa.com/.well-known/jwks (per Visa TAP spec).
3002
+ * Wraps jose.createRemoteJWKSet which handles caching + rotation natively.
3003
+ */
3004
+
3005
+ interface VisaRegistryOptions {
3006
+ jwksUrl?: string;
3007
+ cacheMaxAge?: number;
3008
+ cooldownDuration?: number;
3009
+ }
3010
+ declare function createVisaRegistry(options?: VisaRegistryOptions): RegistryResolver;
3011
+
3012
+ /**
3013
+ * Mastercard Agent Registry resolver — STUB.
3014
+ *
3015
+ * Mastercard Agent Pay is behind partnership (pilots Feb 2026, GA Q2 2026).
3016
+ * No public Agent Registry URL or open-source resolver exists as of April
3017
+ * 2026. This resolver accepts an optional `registryUrl` and, when absent,
3018
+ * returns null with a single one-time console.warn so callers can plumb
3019
+ * the flow end-to-end without a live registry.
3020
+ *
3021
+ * When Mastercard ships a public resolver or when a commercial relationship
3022
+ * provides a registry URL, pass it via `MastercardRegistryOptions.registryUrl`.
3023
+ * Response shape expected: { keys: JWK[] } (JWKS-style).
3024
+ */
3025
+
3026
+ interface MastercardRegistryOptions {
3027
+ /** Partnership-provided registry URL. Without it, the resolver is inert. */
3028
+ registryUrl?: string;
3029
+ /** Cache TTL in seconds. Default 3600. */
3030
+ cacheTtlSec?: number;
3031
+ /** Fetch fn override for testing. */
3032
+ fetch?: typeof fetch;
3033
+ /** Silence the one-time warn (testing only). */
3034
+ silent?: boolean;
3035
+ }
3036
+ declare function createMastercardRegistry(options?: MastercardRegistryOptions): RegistryResolver;
3037
+
3038
+ /**
3039
+ * Web Bot Auth registry resolver.
3040
+ *
3041
+ * IETF draft-meunier-web-bot-auth-architecture-05 + draft-meunier-http-
3042
+ * message-signatures-directory-01. Shared transport substrate under TAP,
3043
+ * Agent Pay, and Cloudflare Pay Per Crawl.
3044
+ *
3045
+ * Fetches a Web Bot Auth signature directory
3046
+ * (default: `<origin>/.well-known/http-message-signatures-directory`).
3047
+ * Shape per spec is a JWKS with Ed25519 keys.
3048
+ *
3049
+ * Wraps Cloudflare's `web-bot-auth` npm package where feasible; for raw
3050
+ * directory fetch + kid matching we use fetch + JSON since web-bot-auth's
3051
+ * higher-level API assumes a full request to verify.
3052
+ */
3053
+
3054
+ interface WebBotAuthRegistryOptions {
3055
+ /**
3056
+ * Optional explicit directory URL. When omitted, the resolver derives one
3057
+ * from `ResolveContext.origin` (e.g. the request URL's origin at verify time).
3058
+ */
3059
+ directoryUrl?: string;
3060
+ cacheTtlSec?: number;
3061
+ fetch?: typeof fetch;
3062
+ }
3063
+ declare function createWebBotAuthRegistry(options?: WebBotAuthRegistryOptions): RegistryResolver;
3064
+
3065
+ /**
3066
+ * Cross-Protocol Transport Module
3067
+ *
3068
+ * Provides adapters for injecting/extracting AstraSync credentials
3069
+ * across HTTP, A2A, and MCP protocols.
3070
+ */
3071
+
3072
+ /**
3073
+ * Auto-detect protocol from request/context shape.
3074
+ */
3075
+ declare function detectProtocol(context: Record<string, unknown>): ProtocolTransport;
3076
+ /**
3077
+ * Apply credentials to any protocol target.
3078
+ */
3079
+ declare function applyCredentials(protocol: ProtocolTransport, target: Record<string, unknown>, credentials: AstraSyncCredentials): Record<string, unknown>;
3080
+ /**
3081
+ * Extract credentials from any protocol context.
3082
+ */
3083
+ declare function extractCredentialsFromProtocol(protocol: ProtocolTransport, context: Record<string, unknown>): AstraSyncCredentials | null;
3084
+
3085
+ type index$1_ACPEndpoint = ACPEndpoint;
3086
+ type index$1_ACPPaymentTokenType = ACPPaymentTokenType;
3087
+ type index$1_ACPRequestContext = ACPRequestContext;
3088
+ type index$1_ACPRequestLike = ACPRequestLike;
3089
+ type index$1_ACPSignatureAlgorithm = ACPSignatureAlgorithm;
3090
+ type index$1_ACPTotal = ACPTotal;
3091
+ type index$1_ACPVerifyInput = ACPVerifyInput;
3092
+ type index$1_ACPVerifyResult = ACPVerifyResult;
3093
+ type index$1_AP2CartMandateClaims = AP2CartMandateClaims;
3094
+ type index$1_AP2ChainResult = AP2ChainResult;
3095
+ type index$1_AP2IntentMandateClaims = AP2IntentMandateClaims;
3096
+ type index$1_AP2MandateClaims = AP2MandateClaims;
3097
+ type index$1_AP2MandateTriple = AP2MandateTriple;
3098
+ type index$1_AP2MandateTripleInput = AP2MandateTripleInput;
3099
+ type index$1_AP2MandateType = AP2MandateType;
3100
+ type index$1_AP2PaymentDetailsTotal = AP2PaymentDetailsTotal;
3101
+ type index$1_AP2PaymentMandateClaims = AP2PaymentMandateClaims;
3102
+ type index$1_AP2PaymentMandateForValue = AP2PaymentMandateForValue;
3103
+ type index$1_AP2VerifyInput = AP2VerifyInput;
3104
+ type index$1_CommerceContext = CommerceContext;
3105
+ type index$1_CommercePipelineInput = CommercePipelineInput;
3106
+ type index$1_CommerceProtocol = CommerceProtocol;
3107
+ type index$1_CommercePurpose = CommercePurpose;
3108
+ type index$1_CommerceSignatureStack = CommerceSignatureStack;
3109
+ type index$1_ConstraintEvalResult = ConstraintEvalResult;
3110
+ type index$1_ConstraintKey = ConstraintKey;
3111
+ type index$1_ConstraintResult = ConstraintResult;
3112
+ type index$1_ExtractorRequestLike = ExtractorRequestLike;
3113
+ type index$1_IdentityBindingResult = IdentityBindingResult;
3114
+ type index$1_IdentityClaim = IdentityClaim;
3115
+ type index$1_IdentityResolver = IdentityResolver;
3116
+ type index$1_MPPChallengeForValue = MPPChallengeForValue;
3117
+ type index$1_MPPChallengeSummary = MPPChallengeSummary;
3118
+ type index$1_MPPCredentialSummary = MPPCredentialSummary;
3119
+ type index$1_MPPIntent = MPPIntent;
3120
+ type index$1_MPPKind = MPPKind;
3121
+ type index$1_MPPReceiptSummary = MPPReceiptSummary;
3122
+ type index$1_MPPRequestContext = MPPRequestContext;
3123
+ type index$1_MPPRequestLike = MPPRequestLike;
3124
+ type index$1_MPPResponseLike = MPPResponseLike;
3125
+ type index$1_MPPVerifyInput = MPPVerifyInput;
3126
+ type index$1_MPPVerifyResult = MPPVerifyResult;
3127
+ type index$1_ParsedRFC9421 = ParsedRFC9421;
3128
+ type index$1_PaymentMethodAllowlistInput = PaymentMethodAllowlistInput;
3129
+ type index$1_RFC9421SignatureParams = RFC9421SignatureParams;
3130
+ type index$1_RFC9421Tag = RFC9421Tag;
3131
+ type index$1_RFC9421VerifyOptions = RFC9421VerifyOptions;
3132
+ type index$1_RFC9421VerifyRequest = RFC9421VerifyRequest;
3133
+ type index$1_RFC9421VerifyResult = RFC9421VerifyResult;
3134
+ type index$1_RegistryName = RegistryName;
3135
+ type index$1_RegistryResolver = RegistryResolver;
3136
+ type index$1_ResolveContext = ResolveContext;
3137
+ declare const index$1_STRIPE_WEBHOOK_INFORMATIONAL_EVENTS: typeof STRIPE_WEBHOOK_INFORMATIONAL_EVENTS;
3138
+ type index$1_SpendingLimitInput = SpendingLimitInput;
3139
+ type index$1_StripeWebhookInformationalEvent = StripeWebhookInformationalEvent;
3140
+ type index$1_TransactionContext = TransactionContext;
3141
+ type index$1_TransactionValueContext = TransactionValueContext;
3142
+ type index$1_TransportExtractor<T = unknown> = TransportExtractor<T>;
3143
+ type index$1_UCPCheckoutContext = UCPCheckoutContext;
3144
+ type index$1_UCPManifestValidationResult = UCPManifestValidationResult;
3145
+ type index$1_UCPRequestLike = UCPRequestLike;
3146
+ type index$1_UCPTotal = UCPTotal;
3147
+ type index$1_VIAllowedParty = VIAllowedParty;
3148
+ type index$1_VIBudgetLimit = VIBudgetLimit;
3149
+ type index$1_VIClaimsForValue = VIClaimsForValue;
3150
+ type index$1_VIConstraintEvalInput = VIConstraintEvalInput;
3151
+ type index$1_VIConstraints = VIConstraints;
3152
+ type index$1_VIExecutionMode = VIExecutionMode;
3153
+ type index$1_VIExtractedClaims = VIExtractedClaims;
3154
+ type index$1_VILayer = VILayer;
3155
+ type index$1_VILineItem = VILineItem;
3156
+ type index$1_VIMandateType = VIMandateType;
3157
+ type index$1_VIPaymentAmount = VIPaymentAmount;
3158
+ type index$1_VIRecurrence = VIRecurrence;
3159
+ type index$1_VIVerifyInput = VIVerifyInput;
3160
+ type index$1_VIVerifyResult = VIVerifyResult;
3161
+ type index$1_VerifyStripeWebhookOptions = VerifyStripeWebhookOptions;
3162
+ type index$1_VerifyStripeWebhookResult = VerifyStripeWebhookResult;
3163
+ type index$1_X402Kind = X402Kind;
3164
+ type index$1_X402RequestContext = X402RequestContext;
3165
+ type index$1_X402RequestForValue = X402RequestForValue;
3166
+ type index$1_X402RequestLike = X402RequestLike;
3167
+ type index$1_X402RequirementsSummary = X402RequirementsSummary;
3168
+ type index$1_X402ResponseLike = X402ResponseLike;
3169
+ declare const index$1_applyCredentials: typeof applyCredentials;
3170
+ declare const index$1_bindIdentity: typeof bindIdentity;
3171
+ declare const index$1_claim: typeof claim;
3172
+ declare const index$1_clearTransportExtractors: typeof clearTransportExtractors;
3173
+ declare const index$1_createMastercardRegistry: typeof createMastercardRegistry;
3174
+ declare const index$1_createVisaRegistry: typeof createVisaRegistry;
3175
+ declare const index$1_createWebBotAuthRegistry: typeof createWebBotAuthRegistry;
3176
+ declare const index$1_detectProtocol: typeof detectProtocol;
3177
+ declare const index$1_evaluatePaymentMethodAllowlist: typeof evaluatePaymentMethodAllowlist;
3178
+ declare const index$1_evaluateSpendingLimit: typeof evaluateSpendingLimit;
3179
+ declare const index$1_evaluateVIConstraints: typeof evaluateVIConstraints;
3180
+ declare const index$1_extractA2ACredentials: typeof extractA2ACredentials;
3181
+ declare const index$1_extractACPContext: typeof extractACPContext;
3182
+ declare const index$1_extractACPTransactionValue: typeof extractACPTransactionValue;
3183
+ declare const index$1_extractAP2Mandate: typeof extractAP2Mandate;
3184
+ declare const index$1_extractAP2Mandates: typeof extractAP2Mandates;
3185
+ declare const index$1_extractAP2TransactionValue: typeof extractAP2TransactionValue;
3186
+ declare const index$1_extractCredentialsFromProtocol: typeof extractCredentialsFromProtocol;
3187
+ declare const index$1_extractHttpCredentials: typeof extractHttpCredentials;
3188
+ declare const index$1_extractMPPContext: typeof extractMPPContext;
3189
+ declare const index$1_extractMPPFromRequest: typeof extractMPPFromRequest;
3190
+ declare const index$1_extractMPPFromResponse: typeof extractMPPFromResponse;
3191
+ declare const index$1_extractMPPTransactionValue: typeof extractMPPTransactionValue;
3192
+ declare const index$1_extractMcpCredentials: typeof extractMcpCredentials;
3193
+ declare const index$1_extractUCPContext: typeof extractUCPContext;
3194
+ declare const index$1_extractUCPTransactionValue: typeof extractUCPTransactionValue;
3195
+ declare const index$1_extractVIClaims: typeof extractVIClaims;
3196
+ declare const index$1_extractVITransactionValue: typeof extractVITransactionValue;
3197
+ declare const index$1_extractX402Context: typeof extractX402Context;
3198
+ declare const index$1_extractX402FromRequest: typeof extractX402FromRequest;
3199
+ declare const index$1_extractX402FromResponse: typeof extractX402FromResponse;
3200
+ declare const index$1_extractX402TransactionValue: typeof extractX402TransactionValue;
3201
+ declare const index$1_fetchUCPManifest: typeof fetchUCPManifest;
3202
+ declare const index$1_getTransportExtractor: typeof getTransportExtractor;
3203
+ declare const index$1_getTransportExtractors: typeof getTransportExtractors;
3204
+ declare const index$1_isStripeWebhookInformational: typeof isStripeWebhookInformational;
3205
+ declare const index$1_mapACPRequestToPurpose: typeof mapACPRequestToPurpose;
3206
+ declare const index$1_mapAP2MandateToPurpose: typeof mapAP2MandateToPurpose;
3207
+ declare const index$1_mapMPPRequestToPurpose: typeof mapMPPRequestToPurpose;
3208
+ declare const index$1_mapRFC9421TagToPurpose: typeof mapRFC9421TagToPurpose;
3209
+ declare const index$1_mapUCPRequestToPurpose: typeof mapUCPRequestToPurpose;
3210
+ declare const index$1_mapVIMandateToPurpose: typeof mapVIMandateToPurpose;
3211
+ declare const index$1_mapX402RequestToPurpose: typeof mapX402RequestToPurpose;
3212
+ declare const index$1_parseRFC9421: typeof parseRFC9421;
3213
+ declare const index$1_registerTransportExtractor: typeof registerTransportExtractor;
3214
+ declare const index$1_runCommercePipeline: typeof runCommercePipeline;
3215
+ declare const index$1_runMatchingExtractors: typeof runMatchingExtractors;
3216
+ declare const index$1_setA2AMetadata: typeof setA2AMetadata;
3217
+ declare const index$1_setHttpHeaders: typeof setHttpHeaders;
3218
+ declare const index$1_setMcpMeta: typeof setMcpMeta;
3219
+ declare const index$1_validateUCPManifest: typeof validateUCPManifest;
3220
+ declare const index$1_verifyACPSignature: typeof verifyACPSignature;
3221
+ declare const index$1_verifyAP2Chain: typeof verifyAP2Chain;
3222
+ declare const index$1_verifyMPP: typeof verifyMPP;
3223
+ declare const index$1_verifyRFC9421: typeof verifyRFC9421;
3224
+ declare const index$1_verifyStripeWebhook: typeof verifyStripeWebhook;
3225
+ declare const index$1_verifyVIChain: typeof verifyVIChain;
3226
+ declare namespace index$1 {
3227
+ export { type index$1_ACPEndpoint as ACPEndpoint, type index$1_ACPPaymentTokenType as ACPPaymentTokenType, type index$1_ACPRequestContext as ACPRequestContext, type index$1_ACPRequestLike as ACPRequestLike, type index$1_ACPSignatureAlgorithm as ACPSignatureAlgorithm, type index$1_ACPTotal as ACPTotal, type index$1_ACPVerifyInput as ACPVerifyInput, type index$1_ACPVerifyResult as ACPVerifyResult, type index$1_AP2CartMandateClaims as AP2CartMandateClaims, type index$1_AP2ChainResult as AP2ChainResult, type index$1_AP2IntentMandateClaims as AP2IntentMandateClaims, type index$1_AP2MandateClaims as AP2MandateClaims, type index$1_AP2MandateTriple as AP2MandateTriple, type index$1_AP2MandateTripleInput as AP2MandateTripleInput, type index$1_AP2MandateType as AP2MandateType, type index$1_AP2PaymentDetailsTotal as AP2PaymentDetailsTotal, type index$1_AP2PaymentMandateClaims as AP2PaymentMandateClaims, type index$1_AP2PaymentMandateForValue as AP2PaymentMandateForValue, type index$1_AP2VerifyInput as AP2VerifyInput, type index$1_CommerceContext as CommerceContext, type index$1_CommercePipelineInput as CommercePipelineInput, type index$1_CommerceProtocol as CommerceProtocol, type index$1_CommercePurpose as CommercePurpose, type index$1_CommerceSignatureStack as CommerceSignatureStack, type index$1_ConstraintEvalResult as ConstraintEvalResult, type index$1_ConstraintKey as ConstraintKey, type index$1_ConstraintResult as ConstraintResult, type index$1_ExtractorRequestLike as ExtractorRequestLike, type index$1_IdentityBindingResult as IdentityBindingResult, type index$1_IdentityClaim as IdentityClaim, type index$1_IdentityResolver as IdentityResolver, type index$1_MPPChallengeForValue as MPPChallengeForValue, type index$1_MPPChallengeSummary as MPPChallengeSummary, type index$1_MPPCredentialSummary as MPPCredentialSummary, type index$1_MPPIntent as MPPIntent, type index$1_MPPKind as MPPKind, type index$1_MPPReceiptSummary as MPPReceiptSummary, type index$1_MPPRequestContext as MPPRequestContext, type index$1_MPPRequestLike as MPPRequestLike, type index$1_MPPResponseLike as MPPResponseLike, type index$1_MPPVerifyInput as MPPVerifyInput, type index$1_MPPVerifyResult as MPPVerifyResult, type index$1_ParsedRFC9421 as ParsedRFC9421, type index$1_PaymentMethodAllowlistInput as PaymentMethodAllowlistInput, type index$1_RFC9421SignatureParams as RFC9421SignatureParams, type index$1_RFC9421Tag as RFC9421Tag, type index$1_RFC9421VerifyOptions as RFC9421VerifyOptions, type index$1_RFC9421VerifyRequest as RFC9421VerifyRequest, type index$1_RFC9421VerifyResult as RFC9421VerifyResult, type index$1_RegistryName as RegistryName, type index$1_RegistryResolver as RegistryResolver, type index$1_ResolveContext as ResolveContext, index$1_STRIPE_WEBHOOK_INFORMATIONAL_EVENTS as STRIPE_WEBHOOK_INFORMATIONAL_EVENTS, type index$1_SpendingLimitInput as SpendingLimitInput, type index$1_StripeWebhookInformationalEvent as StripeWebhookInformationalEvent, type index$1_TransactionContext as TransactionContext, type index$1_TransactionValueContext as TransactionValueContext, type index$1_TransportExtractor as TransportExtractor, type index$1_UCPCheckoutContext as UCPCheckoutContext, type index$1_UCPManifestValidationResult as UCPManifestValidationResult, type index$1_UCPRequestLike as UCPRequestLike, type index$1_UCPTotal as UCPTotal, type index$1_VIAllowedParty as VIAllowedParty, type index$1_VIBudgetLimit as VIBudgetLimit, type index$1_VIClaimsForValue as VIClaimsForValue, type index$1_VIConstraintEvalInput as VIConstraintEvalInput, type index$1_VIConstraints as VIConstraints, type index$1_VIExecutionMode as VIExecutionMode, type index$1_VIExtractedClaims as VIExtractedClaims, type index$1_VILayer as VILayer, type index$1_VILineItem as VILineItem, type index$1_VIMandateType as VIMandateType, type index$1_VIPaymentAmount as VIPaymentAmount, type index$1_VIRecurrence as VIRecurrence, type index$1_VIVerifyInput as VIVerifyInput, type index$1_VIVerifyResult as VIVerifyResult, type index$1_VerifyStripeWebhookOptions as VerifyStripeWebhookOptions, type index$1_VerifyStripeWebhookResult as VerifyStripeWebhookResult, type index$1_X402Kind as X402Kind, type index$1_X402RequestContext as X402RequestContext, type index$1_X402RequestForValue as X402RequestForValue, type index$1_X402RequestLike as X402RequestLike, type index$1_X402RequirementsSummary as X402RequirementsSummary, type index$1_X402ResponseLike as X402ResponseLike, index$1_applyCredentials as applyCredentials, index$1_bindIdentity as bindIdentity, index$1_claim as claim, index$1_clearTransportExtractors as clearTransportExtractors, index$1_createMastercardRegistry as createMastercardRegistry, index$1_createVisaRegistry as createVisaRegistry, index$1_createWebBotAuthRegistry as createWebBotAuthRegistry, index$1_detectProtocol as detectProtocol, index$1_evaluatePaymentMethodAllowlist as evaluatePaymentMethodAllowlist, index$1_evaluateSpendingLimit as evaluateSpendingLimit, index$1_evaluateVIConstraints as evaluateVIConstraints, index$1_extractA2ACredentials as extractA2ACredentials, index$1_extractACPContext as extractACPContext, index$1_extractACPTransactionValue as extractACPTransactionValue, index$1_extractAP2Mandate as extractAP2Mandate, index$1_extractAP2Mandates as extractAP2Mandates, index$1_extractAP2TransactionValue as extractAP2TransactionValue, index$1_extractCredentialsFromProtocol as extractCredentialsFromProtocol, index$1_extractHttpCredentials as extractHttpCredentials, index$1_extractMPPContext as extractMPPContext, index$1_extractMPPFromRequest as extractMPPFromRequest, index$1_extractMPPFromResponse as extractMPPFromResponse, index$1_extractMPPTransactionValue as extractMPPTransactionValue, index$1_extractMcpCredentials as extractMcpCredentials, index$1_extractUCPContext as extractUCPContext, index$1_extractUCPTransactionValue as extractUCPTransactionValue, index$1_extractVIClaims as extractVIClaims, index$1_extractVITransactionValue as extractVITransactionValue, index$1_extractX402Context as extractX402Context, index$1_extractX402FromRequest as extractX402FromRequest, index$1_extractX402FromResponse as extractX402FromResponse, index$1_extractX402TransactionValue as extractX402TransactionValue, index$1_fetchUCPManifest as fetchUCPManifest, index$1_getTransportExtractor as getTransportExtractor, index$1_getTransportExtractors as getTransportExtractors, index$1_isStripeWebhookInformational as isStripeWebhookInformational, index$1_mapACPRequestToPurpose as mapACPRequestToPurpose, index$1_mapAP2MandateToPurpose as mapAP2MandateToPurpose, index$1_mapMPPRequestToPurpose as mapMPPRequestToPurpose, index$1_mapRFC9421TagToPurpose as mapRFC9421TagToPurpose, index$1_mapUCPRequestToPurpose as mapUCPRequestToPurpose, index$1_mapVIMandateToPurpose as mapVIMandateToPurpose, index$1_mapX402RequestToPurpose as mapX402RequestToPurpose, index$1_parseRFC9421 as parseRFC9421, index$1_registerTransportExtractor as registerTransportExtractor, index$1_runCommercePipeline as runCommercePipeline, index$1_runMatchingExtractors as runMatchingExtractors, index$1_setA2AMetadata as setA2AMetadata, index$1_setHttpHeaders as setHttpHeaders, index$1_setMcpMeta as setMcpMeta, index$1_validateUCPManifest as validateUCPManifest, index$1_verifyACPSignature as verifyACPSignature, index$1_verifyAP2Chain as verifyAP2Chain, index$1_verifyMPP as verifyMPP, index$1_verifyRFC9421 as verifyRFC9421, index$1_verifyStripeWebhook as verifyStripeWebhook, index$1_verifyVIChain as verifyVIChain };
3228
+ }
3229
+
3230
+ /**
3231
+ * X-Astra-Verified-Hop — cross-hop verify-access dedupe marker.
3232
+ *
3233
+ * Header carrying upstream verify-access proof so an inner-hop endpoint can
3234
+ * dedupe (skip verify-access when the same ASTRA-id was already verified a
3235
+ * few ms earlier). Emitted by the MCP adapter toward tool fetches and by the
3236
+ * edge gateway toward the origin at authenticate/authorize depth. Value
3237
+ * format:
3238
+ *
3239
+ * {astraId};{sessionId};{checkedAt-ms}
3240
+ *
3241
+ * Receivers MUST validate that `checkedAt` is recent (≤ 60s window
3242
+ * recommended) and that `astraId` matches the agent identity claimed on the
3243
+ * inner hop. The header alone is NOT proof-of-identity — it's an UNSIGNED
3244
+ * dedupe advisory: trust it (`trustVerifiedHop`) only where every network
3245
+ * path to the inner hop crosses a stripping gateway or an equivalent trusted
3246
+ * boundary, exactly like the unsigned X-AstraSync-* attestation headers.
3247
+ * Pair with the existing X-Astra-Id auth.
3248
+ */
3249
+ declare const MCP_VERIFIED_HOP_HEADER = "X-Astra-Verified-Hop";
3250
+ /** Default acceptable age (ms) for an X-Astra-Verified-Hop header. */
3251
+ declare const MCP_VERIFIED_HOP_MAX_AGE_MS = 60000;
3252
+ interface VerifiedHopMarker {
3253
+ astraId: string;
3254
+ sessionId?: string;
3255
+ checkedAt: number;
3256
+ }
3257
+ declare function serializeVerifiedHop(marker: VerifiedHopMarker): string;
3258
+ declare function parseVerifiedHop(value: string | undefined | null): VerifiedHopMarker | null;
3259
+ /**
3260
+ * Returns true when `marker.astraId` matches the inner-hop's claimed
3261
+ * ASTRA-id AND the marker is recent enough. Inner-hop middleware uses this
3262
+ * to skip a duplicate verify-access call.
3263
+ */
3264
+ declare function isVerifiedHopValidFor(marker: VerifiedHopMarker | null, expectedAstraId: string, opts?: {
3265
+ maxAgeMs?: number;
3266
+ now?: number;
3267
+ }): boolean;
3268
+
3269
+ /**
3270
+ * MCP server-side helpers — companion to `transport/mcp.ts` (which handles the
3271
+ * agent-side `_meta.astrasync` block).
3272
+ *
3273
+ * Surfaces a body-aware policy hook the existing `createMiddleware` couldn't
3274
+ * provide — MCP traffic is JSON-RPC over a single endpoint (`/mcp`), so the
3275
+ * default route-pattern gating is too coarse: every request looks the same
3276
+ * URL-wise, but `initialize` is low-risk handshake while `tools/call` of a
3277
+ * payment tool is high-risk. Cohort-3 beta merchants flagged this 🟡 in the
3278
+ * v2.9.5 round.
3279
+ *
3280
+ * What lives here:
3281
+ * - `parseMcpJsonRpc(body)` — peels JSON-RPC method + tool name + agent
3282
+ * id without committing to a particular MCP
3283
+ * server framework.
3284
+ * - `mcpToPdlss(parsed)` — canonical mapping JSON-RPC method → PDLSS
3285
+ * purpose / action / resource. Doc-stable
3286
+ * so audits can correlate.
3287
+ * - `mcpDefaultEnforced(parsed)` — whether a method is enforced by default
3288
+ * so a single MCP middleware can split
3289
+ * `initialize` / `tools/list` (pass-through)
3290
+ * from `tools/call` (enforced).
3291
+ * - `MCP_VERIFIED_HOP_HEADER` — header convention for the dedupe pattern
3292
+ * when an MCP tool calls an inner REST hop.
3293
+ * - `serialize/parseVerifiedHop` helpers.
3294
+ *
3295
+ * The Express MCP adapter is in `adapters/mcp.ts` and consumes these.
3296
+ */
3297
+
3298
+ /**
3299
+ * Output of `parseMcpJsonRpc`. Self-describing so the middleware doesn't have
3300
+ * to re-introspect the body to figure out gating.
3301
+ */
3302
+ interface ParsedMcpRequest {
3303
+ /** JSON-RPC method (e.g. `tools/call`, `initialize`, `tools/list`). */
3304
+ method: string;
3305
+ /** Set when method === 'tools/call'; the tool name from `params.name`. */
3306
+ toolName?: string;
3307
+ /** Initialize-specific protocolVersion handshake info, when present. */
3308
+ protocolVersion?: string;
3309
+ /**
3310
+ * Agent id read from the body, in priority order:
3311
+ * 1. `params._meta.astrasync.agentId` (the canonical SDK location, see
3312
+ * `transport/mcp.ts → setMcpMeta`)
3313
+ * 2. `params.arguments.agent_id` (legacy / hand-written tool callers)
3314
+ * Header-supplied id (X-Astra-Id) is read separately by the adapter and
3315
+ * compared to this for the mismatch check.
3316
+ */
3317
+ agentIdFromBody?: string;
3318
+ /**
3319
+ * Purpose extracted from the MCP body
3320
+ * with the symmetric precedence chain. Sourced from `_meta.astrasync.purpose`
3321
+ * (canonical SDK location) OR `params.arguments.purpose` (legacy /
3322
+ * conventional callers). The discriminator is on `purposeSourceFromBody`.
3323
+ * Adapter combines this with the `X-Astra-Purpose` header (header wins)
3324
+ * before mapping; final fallback at `mcpToPdlss` is `undefined`.
3325
+ */
3326
+ purposeFromBody?: string;
3327
+ /** Which body location resolved `purposeFromBody`. */
3328
+ purposeSourceFromBody?: 'meta' | 'tool_argument';
3329
+ /**
3330
+ * Action extracted from the MCP body with the same
3331
+ * symmetric chain as purpose. Sourced from `_meta.astrasync.action`
3332
+ * (canonical) OR `params.arguments.action` (legacy). Adapter combines
3333
+ * with the `X-Astra-Action` header (header wins) before mapping; final
3334
+ * fallback at `mcpToPdlss` is the transport-layer default
3335
+ * (`tools/call:<toolname>` or just `<method>`).
3336
+ */
3337
+ actionFromBody?: string;
3338
+ /** Which body location resolved `actionFromBody`. */
3339
+ actionSourceFromBody?: 'meta' | 'tool_argument';
3340
+ /** True for handshake methods that must succeed before any tool call. */
3341
+ isInitialize: boolean;
3342
+ /** True for `tools/call`. */
3343
+ isToolCall: boolean;
3344
+ /** True for low-risk introspection (`tools/list`, `prompts/list`, etc.). */
3345
+ isIntrospection: boolean;
3346
+ }
3347
+
3348
+ /**
3349
+ * AstraSync Universal Verification Gateway — MCP middleware
3350
+ *
3351
+ * Express-shaped middleware tailored to the JSON-RPC body of an MCP
3352
+ * (Model Context Protocol) endpoint. Closes the cohort-3 gaps the default
3353
+ * `createMiddleware` couldn't:
3354
+ *
3355
+ * (a) **Body-aware gating**. All MCP traffic targets the same `/mcp` URL.
3356
+ * The default route-pattern matcher can't tell `initialize` (low risk)
3357
+ * from `tools/call start_checkout` (high risk). This middleware peels
3358
+ * the JSON-RPC body and applies a per-method risk tier.
3359
+ *
3360
+ * (b) **PDLSS mapping**. Derives purpose, action, and resource from
3361
+ * `toolGates` config and request context. See `transport/mcp-server.ts`
3362
+ * `mcpToPdlss()` for the exact mapping.
3363
+ *
3364
+ * (c) **Inner-hop dedupe**. Outbound responses set
3365
+ * `X-Astra-Verified-Hop` so a downstream REST endpoint that the tool
3366
+ * calls can skip a duplicate verify-access. The receiving REST
3367
+ * middleware checks `parseVerifiedHop` and skips when valid.
3368
+ *
3369
+ * (d) **Header-vs-body identity precedence**. Reads ASTRA-id from
3370
+ * `X-Astra-Id` first, body second. If both are present and disagree,
3371
+ * returns a structured 400 by default (configurable). Pre-fix,
3372
+ * integrators had to re-discover this on their own.
3373
+ *
3374
+ * Usage:
3375
+ *
3376
+ * ```typescript
3377
+ * import express from 'express';
3378
+ * import { createMcpMiddleware } from '@astrasyncai/verification-gateway/mcp';
3379
+ *
3380
+ * const app = express();
3381
+ * app.use(express.json());
3382
+ *
3383
+ * app.post(
3384
+ * '/mcp',
3385
+ * createMcpMiddleware({
3386
+ * apiBaseUrl: 'https://astrasync.ai/api',
3387
+ * apiKey: process.env.ASTRASYNC_API_KEY,
3388
+ * // Per-tool gates — `tools/call` is enforced by default; introspection /
3389
+ * // handshake pass through. A gated tool needs a PDLSS purpose (and ideally
3390
+ * // an action). Set a tool/method to `'observe'` to pass it through
3391
+ * // unenforced (still evaluated when `evaluateAlwaysIfCredentialed`).
3392
+ * toolGates: {
3393
+ * browse_catalog: { purpose: 'shopping', action: 'shopping.search' },
3394
+ * start_checkout: { purpose: 'shopping', action: 'shopping.purchase' },
3395
+ * health_check: 'observe',
3396
+ * },
3397
+ * }),
3398
+ * yourMcpServerHandler,
3399
+ * );
3400
+ * ```
3401
+ */
3402
+
3403
+ declare global {
3404
+ namespace Express {
3405
+ interface Request {
3406
+ mcpRequest?: ParsedMcpRequest;
3407
+ agentVerification?: VerificationResult;
3408
+ }
3409
+ }
3410
+ }
3411
+ /**
3412
+ * Extended per-tool gate with optional PDLSS purpose + action + resource
3413
+ * overrides.
3414
+ *
3415
+ * When `purpose` is set, it is authoritative for that tool — the agent's
3416
+ * `X-Astra-Purpose` header is ignored. This lets the merchant declare what
3417
+ * semantic purpose each tool fulfils rather than trusting agent self-declaration.
3418
+ *
3419
+ * When `action` is set (symmetric with `purpose`), it is
3420
+ * authoritative over `X-Astra-Action` / body declarations, letting the
3421
+ * merchant pin a dotted-verb action (e.g. `shopping.search`) for a tool
3422
+ * whose callers would otherwise leave the action undeclared (purpose-only
3423
+ * evaluation — raw tool names never travel as PDLSS actions).
3424
+ *
3425
+ * When `resource` is set, it overrides the default (`req.path`) for that
3426
+ * tool's verify-access call — e.g. mapping `list_products` to `/api/catalog`.
3427
+ */
3428
+ interface ToolGateConfig {
3429
+ purpose?: string;
3430
+ action?: string;
3431
+ resource?: string;
3432
+ }
3433
+ /**
3434
+ * A tool/method gate is either a {@link ToolGateConfig} (enforced — calls
3435
+ * verify-access and gates on the server decision, using the declared PDLSS
3436
+ * purpose/action) or the literal `'observe'` (passed through unenforced;
3437
+ * still evaluated when `evaluateAlwaysIfCredentialed` is set). SDK 5.0.0
3438
+ * removed the access-level band, so a gate no longer carries a tier — its
3439
+ * only decision is enforce vs observe.
3440
+ */
3441
+ type ToolGate = ToolGateConfig | 'observe';
3442
+ interface McpMiddlewareOptions extends GatewayConfig {
3443
+ /**
3444
+ * Per-tool gating for `tools/call` invocations. Tools not listed are
3445
+ * enforced by default (`tools/call` calls verify-access and gates on the
3446
+ * server decision).
3447
+ *
3448
+ * A gated tool declares its PDLSS `purpose` (required: the backend rejects
3449
+ * gated calls with no resolvable purpose) and ideally a dotted-verb
3450
+ * `action`:
3451
+ * ```typescript
3452
+ * toolGates: {
3453
+ * list_products: { purpose: 'shopping',
3454
+ * action: 'shopping.search',
3455
+ * resource: '/api/catalog' },
3456
+ * start_checkout: { purpose: 'shopping',
3457
+ * action: 'shopping.purchase',
3458
+ * resource: '/api/checkout/*' },
3459
+ * health_check: 'observe', // pass through unenforced
3460
+ * }
3461
+ * ```
3462
+ *
3463
+ * Set a tool to `'observe'` to pass it through without enforcement (it is
3464
+ * still evaluated for the audit trail when `evaluateAlwaysIfCredentialed`
3465
+ * is set). A gated object form with no resolvable purpose fails fast with a
3466
+ * `PDLSS_PURPOSE_REQUIRED` 400 (the SDK never sends the raw tool name as
3467
+ * the PDLSS action).
3468
+ *
3469
+ * The action axis for non-tools/call MCP methods (`tools/list`,
3470
+ * `resources/list`, `prompts/list`, etc.) is the literal JSON-RPC method
3471
+ * name (e.g. `'tools/list'`). Merchants gating MCP traffic by action should
3472
+ * declare per-tool gates in `toolGates`, not endpoint-level `allowedActions`
3473
+ * — the latter applies to REST-style action values, not MCP method strings.
3474
+ */
3475
+ toolGates?: Record<string, ToolGate>;
3476
+ /**
3477
+ * Per-method override. By default introspection / handshake methods
3478
+ * (`tools/list`, `initialize`, `ping`, …) pass through and `tools/call` is
3479
+ * enforced; declare a method here to enforce it (object form, with a PDLSS
3480
+ * purpose) or set it to `'observe'` to pass it through. Matches by exact
3481
+ * JSON-RPC method string.
3482
+ */
3483
+ methodGates?: Record<string, ToolGate>;
3484
+ /**
3485
+ * What to do when the agent id supplied in the X-Astra-Id header
3486
+ * disagrees with the agent id in the JSON-RPC body
3487
+ * (`params._meta.astrasync.agentId` or `params.arguments.agent_id`).
3488
+ *
3489
+ * - `'reject'` (default) — return 400 `AGENT_ID_MISMATCH`. Safest.
3490
+ * - `'prefer-header'` — log + verify against the header value. Keeps
3491
+ * bodies that were authored before X-Astra-Id was the canonical
3492
+ * identity slot working.
3493
+ * - `'prefer-body'` — log + verify against the body value. Useful in
3494
+ * reverse-proxy setups that strip auth headers.
3495
+ */
3496
+ onAgentIdMismatch?: 'reject' | 'prefer-header' | 'prefer-body';
3497
+ /** Skip verification + dedupe entirely. For testing. */
3498
+ skip?: boolean;
3499
+ /** Custom denied handler. Defaults to a structured JSON-RPC error response. */
3500
+ onDenied?: (result: VerificationResult, req: Request, res: Response$1) => void;
3501
+ /**
3502
+ * If `true`, trust an inbound `X-Astra-Verified-Hop` header to skip
3503
+ * verify-access when it carries a recent marker for the resolved agent.
3504
+ *
3505
+ * **DEFAULT FLIPPED TO `false` in SDK 2.4.13.** The marker
3506
+ * is plaintext semicolon-delimited with no HMAC, so any client that sets
3507
+ * the header (with the right format + fresh timestamp + matching ASTRA-id)
3508
+ * skipped verify-access entirely. The per-process verify-access result
3509
+ * cache already dedupes legitimate repeat calls — this optimization
3510
+ * provided no additional savings, only a bypass surface.
3511
+ *
3512
+ * Set this to `true` ONLY if you control every upstream MCP hop that sets
3513
+ * the header AND you trust the network path between hops (mTLS, internal
3514
+ * VPC, etc.). For most installs, leave at the safe default.
3515
+ *
3516
+ * A future SDK release will either remove this option entirely OR add
3517
+ * HMAC signing to the marker.
3518
+ */
3519
+ trustVerifiedHop?: boolean;
3520
+ /** Window for accepting an upstream verified-hop marker. Default 60_000ms. */
3521
+ verifiedHopMaxAgeMs?: number;
3522
+ /**
3523
+ * Automatically record grant/deny decisions for every MCP call. Default
3524
+ * `true` — matches the express adapter.
3525
+ */
3526
+ recordDecisions?: boolean;
3527
+ /** Forward runtime challenge (default `true`). */
3528
+ enableRuntimeChallenge?: boolean;
3529
+ /**
3530
+ * Posture when the MCP middleware itself throws an internal error.
3531
+ * Default `'open'` for backward compatibility in SDK 2.4.13. Shadow logs
3532
+ * record what WOULD be denied with `failOnError: 'closed'` so merchants
3533
+ * can grep correlationId for impact analysis during the observation
3534
+ * window. Default flips to `'closed'` in a follow-up release.
3535
+ */
3536
+ failOnError?: 'open' | 'closed';
3537
+ }
3538
+ /**
3539
+ * Create the MCP middleware. Attach AFTER `express.json()` — the body must
3540
+ * already be a parsed object.
3541
+ */
3542
+ declare function createMcpMiddleware(options: McpMiddlewareOptions): RequestHandler;
3543
+
3544
+ /**
3545
+ * SDK-side discovery of canonical platform URLs via `/.well-known/agentic-commerce`.
3546
+ *
3547
+ * Fire-and-forget pre-fetch at middleware creation; first verify() awaits
3548
+ * the in-flight promise if it hasn't resolved. 60-minute TTL with
3549
+ * stale-while-revalidate background refresh.
3550
+ */
3551
+ interface WellKnownAgenticCommerce {
3552
+ registrationUrl: string;
3553
+ documentationUrl: string;
3554
+ verifyAccessUrl: string;
3555
+ /** 5.1.0: hosted AstraSync MCP bridge endpoint (absent on self-hosted backends). */
3556
+ mcpEndpoint?: string;
3557
+ /** 5.1.0: bridge connector-discovery doc (absent on self-hosted backends). */
3558
+ mcpDiscoveryUrl?: string;
3559
+ }
3560
+ /**
3561
+ * Start a background fetch. Returns the promise for callers that need
3562
+ * to await it (first verify() call).
3563
+ */
3564
+ declare function prefetchWellKnown(apiBaseUrl: string): Promise<WellKnownAgenticCommerce>;
3565
+ /**
3566
+ * Get cached well-known URLs. If stale, triggers a background refresh
3567
+ * and returns stale data (stale-while-revalidate). If no cache exists,
3568
+ * awaits the in-flight fetch or starts a new one.
3569
+ */
3570
+ declare function getWellKnownUrls(apiBaseUrl: string): Promise<WellKnownAgenticCommerce>;
3571
+ /**
3572
+ * Synchronous cache read — returns cached URLs or undefined.
3573
+ * Never triggers a fetch. Used by verify() to avoid extra HTTP calls
3574
+ * in the hot path; adapters are responsible for prefetching.
3575
+ */
3576
+ declare function getCachedWellKnownUrls(apiBaseUrl: string): WellKnownAgenticCommerce | undefined;
3577
+
3578
+ /** Configuration for the AstraSync SDK client. */
3579
+ interface AstraSyncConfig {
3580
+ /** API key (kya_ prefixed). Used as Bearer token. */
3581
+ apiKey?: string;
3582
+ /** Email for email+password authentication. */
3583
+ email?: string;
3584
+ /** Password for email+password authentication. */
3585
+ password?: string;
3586
+ /** secp256k1 private key for crypto signing. Used WITH apiKey or email+password. */
3587
+ privateKey?: string;
3588
+ /**
3589
+ * Base URL for the AstraSync API. Pass the bare ORIGIN — the SDK appends
3590
+ * `/api/agents/...` for each call.
3591
+ *
3592
+ * - Production: `https://astrasync.ai` (default)
3593
+ * - Staging: `https://staging.astrasync.ai`
3594
+ *
3595
+ * A trailing `/api` is tolerated for compatibility with the
3596
+ * `GatewayConfig.apiBaseUrl` convention used by the verification gateway
3597
+ * — if you pass `https://astrasync.ai/api` the SDK strips the suffix and
3598
+ * emits a one-time console.warn so you can fix the source.
3599
+ *
3600
+ * Defaults to the `ASTRASYNC_API_URL` env var, then production.
3601
+ */
3602
+ baseUrl?: string;
3603
+ /**
3604
+ * Suppress the one-time console.warn emitted on baseUrl normalization,
3605
+ * deprecation, or other non-fatal SDK conditions. Default: `false`
3606
+ * (warnings emit). Set `true` in test runners or where logs are
3607
+ * structured.
3608
+ */
3609
+ silent?: boolean;
3610
+ /**
3611
+ * When `true`, the SDK does NOT fall back to `process.env.ASTRASYNC_API_KEY`
3612
+ * if `apiKey` is omitted. Set this when constructing the SDK inside a
3613
+ * per-request handler (MCP tool, gateway adapter) where the host process
3614
+ * has its own platform-attribution `ASTRASYNC_API_KEY` in env that must
3615
+ * not silently substitute for user-supplied credentials. Without this
3616
+ * flag, a no-credentials call from such a wrapper will silently
3617
+ * authenticate as the host process and attribute the request to the
3618
+ * wrong account.
3619
+ *
3620
+ * Default: `false` (backward compat — CLIs and scripts continue to
3621
+ * pick up `ASTRASYNC_API_KEY` from env as before).
3622
+ */
3623
+ disableEnvFallback?: boolean;
3624
+ }
3625
+ /**
3626
+ * Multi-protocol declarations the agent participates in.
3627
+ * Promoted from `metadata.protocols[]` to a first-class field in agent-registration v1.0.0.
3628
+ */
3629
+ type AgentProtocol = 'a2a' | 'acp' | 'ap2' | 'ucp' | 'mpp' | 'x402' | 'erc8004' | 'vi' | 'agentpay' | 'tap' | 'other';
3630
+ /** PDLSS purpose configuration. */
3631
+ interface PDLSSPurpose {
3632
+ categories: string[];
3633
+ allowedActions?: string[];
3634
+ deniedActions?: string[];
3635
+ }
3636
+ /** PDLSS duration configuration. */
3637
+ interface PDLSSDuration {
3638
+ startTime?: string | null;
3639
+ endTime?: string | null;
3640
+ timezone?: string | null;
3641
+ maxSessionDuration?: number | null;
3642
+ ttl?: number | null;
3643
+ allowedDays?: number[] | null;
3644
+ allowedHours?: {
3645
+ start: number;
3646
+ end: number;
3647
+ } | null;
3648
+ }
3649
+ /** PDLSS limits configuration. */
3650
+ interface PDLSSLimits {
3651
+ /** Autonomous Limit — spend up to this without asking; above it → step-up. */
3652
+ autonomousThreshold?: number | null;
3653
+ /** Hard Limit — above it the transaction is denied outright. (Wire key stays
3654
+ * `approvalThreshold` because it is hashed on-chain; see adapter spec F3.) The
3655
+ * old middle `stepUpThreshold` tier was enforcement-dead and has been removed —
3656
+ * there are exactly two limits. */
3657
+ approvalThreshold?: number | null;
3658
+ maxTransactionsPerDay?: number | null;
3659
+ maxTransactionsPerHour?: number | null;
3660
+ maxTotalValue?: number | null;
3661
+ currency?: string;
3662
+ }
3663
+ /** PDLSS scope configuration. */
3664
+ interface PDLSSScope {
3665
+ resources?: string[];
3666
+ resourceTypes?: string[];
3667
+ jurisdictions?: string[];
3668
+ excludedResources?: string[];
3669
+ counterparties?: string[];
3670
+ excludedCounterparties?: string[];
3671
+ }
3672
+ /** PDLSS self-instantiation configuration. */
3673
+ interface PDLSSSelfInstantiation {
3674
+ allowed: boolean;
3675
+ maxSubAgents?: number | null;
3676
+ inheritPermissions?: boolean | null;
3677
+ allowedPurposes?: string[] | null;
3678
+ requireApproval?: boolean | null;
3679
+ maxDepth?: number | null;
3680
+ }
3681
+ /** Full PDLSS configuration. */
3682
+ interface PDLSSConfig$1 {
3683
+ purpose: PDLSSPurpose;
3684
+ duration?: PDLSSDuration;
3685
+ limits?: PDLSSLimits;
3686
+ scope?: PDLSSScope;
3687
+ selfInstantiation?: PDLSSSelfInstantiation;
3688
+ }
3689
+ /** Model metadata for registration. */
3690
+ interface ModelConfig {
3691
+ modelName: string;
3692
+ modelProvider: string;
3693
+ modelType?: 'llm' | 'embedding' | 'image' | 'audio' | 'multimodal' | 'code' | 'other';
3694
+ contextWindow?: number;
3695
+ maxTokens?: number;
3696
+ }
3697
+ /** Framework metadata for registration. */
3698
+ interface FrameworkConfig {
3699
+ frameworkName: string;
3700
+ frameworkVersion: string;
3701
+ }
3702
+ /** Options for agent registration. */
3703
+ interface RegisterOptions {
3704
+ name: string;
3705
+ description?: string;
3706
+ agentType?: string;
3707
+ /**
3708
+ * URL where your agent's verification-gateway SDK is mounted for runtime
3709
+ * challenges. Optional — if omitted, your agent declares no runtime-challenge
3710
+ * support and some counterparties may decline access requests. Mirrors the
3711
+ * webUI "API endpoint" field.
3712
+ */
3713
+ apiEndpoint?: string;
3714
+ model?: ModelConfig;
3715
+ framework?: FrameworkConfig;
3716
+ /** Multi-protocol declarations (e.g. ['acp', 'ap2', 'a2a']). First-class as of v1.0.0. */
3717
+ protocols?: AgentProtocol[];
3718
+ metadata?: Record<string, unknown>;
3719
+ pdlss?: PDLSSConfig$1;
3720
+ }
3721
+ /**
3722
+ * Optional blocking-mode flags for `register()`. When `waitForApproval` is
3723
+ * true and the backend returns 202 pending, the SDK polls until the request
3724
+ * resolves (approved → returns Agent; denied/expired → throws; timeout →
3725
+ * throws). The default is non-blocking: the SDK returns the pending result
3726
+ * immediately and the caller handles polling itself.
3727
+ */
3728
+ interface WaitForApprovalOptions {
3729
+ /** Block until the request resolves. Default: false. */
3730
+ waitForApproval?: boolean;
3731
+ /** How long to wait in blocking mode. Default: 600_000ms (10 min). */
3732
+ timeoutMs?: number;
3733
+ /** Poll cadence in blocking mode. Default: 5000ms. */
3734
+ pollIntervalMs?: number;
3735
+ /** Called once per poll while still pending; useful for progress UX. */
3736
+ onPending?: (event: {
3737
+ requestId: string;
3738
+ ageMs: number;
3739
+ }) => void;
3740
+ }
3741
+ /**
3742
+ * Discriminated registration result.
3743
+ *
3744
+ * - `active`: synchronous path (crypto-keypair signature verified, or
3745
+ * email+password auth). `agent` is the live record.
3746
+ * - `pending_approval`: API-key auth path. The owner has been notified by
3747
+ * email and a dashboard alert. Poll `pollUrl` or call
3748
+ * `sdk.pollRegistration(requestId)` to track progress, or re-call
3749
+ * `register` with `waitForApproval: true` to block.
3750
+ */
3751
+ type RegisterResult = {
3752
+ status: 'active';
3753
+ agent: AgentRecord;
3754
+ /** Backend advisories surfaced verbatim. */
3755
+ warnings?: Array<{
3756
+ code: string;
3757
+ message: string;
3758
+ }>;
3759
+ } | {
3760
+ status: 'pending_approval';
3761
+ requestId: string;
3762
+ expiresAt: string;
3763
+ pollUrl: string;
3764
+ message?: string;
3765
+ /** Backend advisories surfaced verbatim. */
3766
+ warnings?: Array<{
3767
+ code: string;
3768
+ message: string;
3769
+ }>;
3770
+ };
3771
+ /**
3772
+ * Response shape from `pollRegistration(requestId)` and the internal poll
3773
+ * loop. State `pending` means still awaiting owner; the others are terminal.
3774
+ *
3775
+ * On `state: 'approved'`, the response also carries the
3776
+ * canonical `astraId` — the partner-facing public agent identity that all
3777
+ * verify-access / verify/{id} surfaces accept. The `agent` (UUID) field
3778
+ * stays owner-private and is kept for backward compat.
3779
+ */
3780
+ interface PollRegistrationResult {
3781
+ state: 'pending' | 'approved' | 'denied' | 'expired';
3782
+ /**
3783
+ * Canonical `ASTRA-…` id. Populated when `state === 'approved'`; `null`
3784
+ * (or absent) otherwise. This is the identifier to pass to public
3785
+ * verification surfaces — UUIDs from the register response are owner-
3786
+ * private request handles and are rejected by verify-access in v2.4.3+.
3787
+ */
3788
+ astraId?: string | null;
3789
+ agent?: AgentRecord;
3790
+ reason?: string;
3791
+ }
3792
+ /**
3793
+ * Response from agent registration (raw 201 body). Use {@link RegisterResult}
3794
+ * for the consumer-facing shape returned from `sdk.register()`.
3795
+ */
3796
+ interface RegistrationResponse {
3797
+ success: boolean;
3798
+ message: string;
3799
+ data: {
3800
+ agent: AgentRecord;
3801
+ };
3802
+ /**
3803
+ * Backend-emitted advisories (e.g. `no_callback_endpoint`
3804
+ * when apiEndpoint is omitted). Previously the SDK whitelisted five
3805
+ * fields on the way out and dropped this. Surface verbatim on both 201
3806
+ * and 202 register paths.
3807
+ */
3808
+ warnings?: Array<{
3809
+ code: string;
3810
+ message: string;
3811
+ }>;
3812
+ }
3813
+ /** Raw 202 body — internal type, exposed via {@link RegisterResult}. */
3814
+ interface PendingRegistrationResponse {
3815
+ success: true;
3816
+ status: 'pending_approval';
3817
+ requestId: string;
3818
+ expiresAt: string;
3819
+ pollUrl: string;
3820
+ message?: string;
3821
+ /** Same advisories as 201 path. */
3822
+ warnings?: Array<{
3823
+ code: string;
3824
+ message: string;
3825
+ }>;
3826
+ }
3827
+ /** Agent record from the API. */
3828
+ interface AgentRecord {
3829
+ kyaAgentId: string;
3830
+ name: string;
3831
+ description?: string;
3832
+ agentType: string;
3833
+ agentStatus: string;
3834
+ trustScore: number;
3835
+ astrasyncIdLevel1?: string | null;
3836
+ tempId?: string | null;
3837
+ metadata?: Record<string, unknown>;
3838
+ createdAt: string;
3839
+ updatedAt: string;
3840
+ }
3841
+ /** Public agent verification response. */
3842
+ interface VerifyResponse {
3843
+ success: boolean;
3844
+ data: {
3845
+ agentUuid: string;
3846
+ agentName: string;
3847
+ agentDescription: string;
3848
+ agentTrustScore: number;
3849
+ agentStatus: string;
3850
+ ownerName?: string;
3851
+ };
3852
+ }
3853
+ /** Health check response. */
3854
+ interface HealthResponse {
3855
+ status: string;
3856
+ service: string;
3857
+ version: string;
3858
+ }
3859
+ /** Error response from the API. */
3860
+ interface ApiErrorResponse {
3861
+ success: false;
3862
+ error: string;
3863
+ code?: string;
3864
+ kydUrl?: string;
3865
+ ownerNotified?: boolean;
3866
+ }
3867
+
3868
+ /**
3869
+ * AstraSync SDK client for registering and managing AI agents.
3870
+ *
3871
+ * @example
3872
+ * ```typescript
3873
+ * const client = new AstraSync({ apiKey: 'kya_your_api_key' });
3874
+ * const result = await client.register({
3875
+ * name: 'My Agent',
3876
+ * model: { modelName: 'gpt-4o', modelProvider: 'openai', modelType: 'llm' },
3877
+ * });
3878
+ * ```
3879
+ *
3880
+ * For staging, pass `baseUrl: 'https://staging.astrasync.ai'`.
3881
+ */
3882
+ declare class AstraSync {
3883
+ private readonly baseUrl;
3884
+ private readonly apiKey?;
3885
+ private readonly email?;
3886
+ private readonly password?;
3887
+ private readonly privateKey?;
3888
+ private cachedJwt?;
3889
+ private jwtExpiresAt?;
3890
+ constructor(config?: AstraSyncConfig);
3891
+ /**
3892
+ * Register a new AI agent on the AstraSync KYA Platform.
3893
+ *
3894
+ * The backend response depends on auth context:
3895
+ * - **Crypto-keypair signed** (`privateKey` configured): synchronous 201,
3896
+ * returns `{ status: 'active', agent }`.
3897
+ * - **API-key only** (no signature): 202 pending, returns
3898
+ * `{ status: 'pending_approval', requestId, pollUrl, expiresAt }`. The
3899
+ * owner is notified by email and a dashboard alert is emitted; the agent
3900
+ * becomes active only after the owner approves.
3901
+ *
3902
+ * Blocking mode: pass `{ waitForApproval: true }` to have the SDK poll the
3903
+ * request until it resolves, then return the live agent record. The promise
3904
+ * rejects with `RegistrationDeniedError`, `RegistrationExpiredError`, or
3905
+ * `RegistrationTimeoutError` on the corresponding terminal states.
3906
+ *
3907
+ * @example Non-blocking (default — best for serverless / scheduled agents):
3908
+ * ```typescript
3909
+ * const result = await sdk.register({ name, pdlss });
3910
+ * if (result.status === 'pending_approval') {
3911
+ * storeRequestId(result.requestId);
3912
+ * return; // function exits; resume later via pollRegistration()
3913
+ * }
3914
+ * ```
3915
+ *
3916
+ * @example Blocking (best for long-running services + CLI):
3917
+ * ```typescript
3918
+ * const agent = await sdk.register({
3919
+ * name, pdlss, waitForApproval: true, timeoutMs: 600_000,
3920
+ * onPending: ({ ageMs }) => console.log(`waiting ${ageMs}ms`),
3921
+ * });
3922
+ * ```
3923
+ */
3924
+ register(options: RegisterOptions & WaitForApprovalOptions): Promise<RegisterResult | AgentRecord>;
3925
+ /**
3926
+ * Poll the current state of a pending-approval registration request.
3927
+ *
3928
+ * Useful for caller-driven polling when `waitForApproval: false` (the
3929
+ * default). The endpoint is unauthenticated — pass the `requestId` that
3930
+ * was returned from the 202 response.
3931
+ *
3932
+ * @returns `state: 'pending'` while awaiting; `'approved'` carries the
3933
+ * minted agent in `agent`; `'denied'` may carry the owner's
3934
+ * `reason`; `'expired'` is terminal after 14 days.
3935
+ */
3936
+ pollRegistration(requestId: string): Promise<PollRegistrationResult>;
3937
+ /**
3938
+ * Block until a pending registration request resolves to a terminal state.
3939
+ * Resolves to the live `AgentRecord` on approval; rejects with the matching
3940
+ * Registration*Error on deny/expire/timeout. Usually called via
3941
+ * `register({ waitForApproval: true })`, but exposed for callers that want
3942
+ * to fire-and-forget the initial register call and resume waiting later
3943
+ * (e.g. after restoring a stored `requestId` on cold start).
3944
+ */
3945
+ waitForApproval(requestId: string, options?: WaitForApprovalOptions): Promise<AgentRecord>;
3946
+ /**
3947
+ * Look up an agent's public profile by ASTRA ID or UUID.
3948
+ */
3949
+ verify(agentId: string): Promise<VerifyResponse>;
3950
+ /**
3951
+ * Check API health.
3952
+ */
3953
+ health(): Promise<HealthResponse>;
3954
+ private request;
3955
+ /**
3956
+ * Variant of {@link request} that also returns the HTTP status code, so
3957
+ * callers can branch on 201 vs 202 (or other success codes) without losing
3958
+ * type information about the response body.
3959
+ */
3960
+ private requestWithStatus;
3961
+ private getAuthToken;
3962
+ /**
3963
+ * Sign a request using secp256k1 (ethers.js).
3964
+ * Canonical message format: METHOD:ENDPOINT:SORTED_JSON_BODY
3965
+ * Must match apps/backend/src/services/signature-verify.service.ts exactly.
3966
+ */
3967
+ private signRequest;
3968
+ /** Recursively sort object keys for canonical JSON representation. */
3969
+ private sortObjectKeys;
3970
+ }
3971
+
3972
+ /** Base error class for AstraSync SDK errors. */
3973
+ declare class AstraSyncError extends Error {
3974
+ readonly code?: string;
3975
+ readonly statusCode: number;
3976
+ constructor(message: string, statusCode: number, code?: string);
3977
+ }
3978
+ /** Thrown when KYD verification is required before agent registration. */
3979
+ declare class KYDRequiredError extends AstraSyncError {
3980
+ readonly kydUrl: string;
3981
+ readonly ownerNotified: boolean;
3982
+ constructor(response: ApiErrorResponse);
3983
+ }
3984
+ /** Thrown when authentication fails. */
3985
+ declare class AuthenticationError extends AstraSyncError {
3986
+ constructor(message: string);
3987
+ }
3988
+ /**
3989
+ * Thrown by `register({ waitForApproval: true })` when the owner denies the
3990
+ * pending registration request. The `reason` field, when present, mirrors the
3991
+ * deny note the owner left in the dashboard.
3992
+ */
3993
+ declare class RegistrationDeniedError extends AstraSyncError {
3994
+ readonly requestId: string;
3995
+ readonly reason?: string;
3996
+ constructor(requestId: string, reason?: string);
3997
+ }
3998
+ /**
3999
+ * Thrown by `register({ waitForApproval: true })` when the pending request
4000
+ * passes its 14-day TTL with no owner decision. The agent must re-submit.
4001
+ */
4002
+ declare class RegistrationExpiredError extends AstraSyncError {
4003
+ readonly requestId: string;
4004
+ constructor(requestId: string);
4005
+ }
4006
+ /**
4007
+ * Thrown by `register({ waitForApproval: true })` when the caller's local
4008
+ * `timeoutMs` elapses before the owner makes a decision. The request is still
4009
+ * live server-side — poll `pollRegistration(requestId)` to resume waiting, or
4010
+ * call `waitForApproval` again with a longer timeout.
4011
+ */
4012
+ declare class RegistrationTimeoutError extends AstraSyncError {
4013
+ readonly requestId: string;
4014
+ constructor(requestId: string);
4015
+ }
4016
+
4017
+ /**
4018
+ * Guidance envelope for credentials-required cases.
4019
+ *
4020
+ * A single shared source of truth so partners writing their own wrappers
4021
+ * (custom MCP servers, Express middleware around registration, gateway
4022
+ * adapters) consume a single source of truth instead of re-implementing the
4023
+ * five-step boilerplate.
4024
+ *
4025
+ * The envelope is what an agent (or wrapping MCP client) sees when it calls
4026
+ * `register_agent` with no AstraSync credentials. It tells the calling agent
4027
+ * (a) what failed (`status: 'credentials_required'`), (b) the keyless
4028
+ * registration ACTION endpoint (`registrationUrl` — POST-able, not the human
4029
+ * dashboard), (c) where the relevant docs are (`documentationUrl`), and (d) the
4030
+ * ordered next-actions (`steps`).
4031
+ */
4032
+ interface GuidanceEnvelope {
4033
+ /**
4034
+ * Single-literal today. Expand to a union (e.g.
4035
+ * `'credentials_required' | 'kyd_required' | …`) when a second guidance
4036
+ * status emerges. Don't pre-emptively widen — the literal pins the shape.
4037
+ */
4038
+ status: 'credentials_required';
4039
+ message: string;
4040
+ guidance: {
4041
+ message: string;
4042
+ registrationUrl: string;
4043
+ documentationUrl: string;
4044
+ steps: string[];
4045
+ };
4046
+ }
4047
+ interface BuildGuidanceParams {
4048
+ /**
4049
+ * Bare origin of the AstraSync deployment the caller should register at,
4050
+ * e.g. `https://astrasync.ai` or `https://staging.astrasync.ai`. No
4051
+ * trailing slash, no `/api` suffix — registrationUrl and documentationUrl
4052
+ * are templated relative to this origin.
4053
+ */
4054
+ origin: string;
4055
+ /**
4056
+ * Overrides the top-level `message` (the short summary the agent sees).
4057
+ * Defaults to the error message from the SDK's `AuthenticationError`
4058
+ * when present, else a generic "credentials required" line.
4059
+ */
4060
+ message?: string;
4061
+ /**
4062
+ * Overrides the documentation path. Defaults to `/docs/agent-access`.
4063
+ */
4064
+ documentationPath?: string;
4065
+ }
4066
+ /**
4067
+ * Build the credentials-required guidance envelope.
4068
+ *
4069
+ * This is the canonical builder — MCP wrappers (`agent-registration.ts`),
4070
+ * Express middleware in custom integrations, and any other partner-side
4071
+ * wrapper that needs to surface "you need to register" should call this
4072
+ * rather than reconstructing the shape inline. Inline reconstruction
4073
+ * historically led to drift between wrappers; this consolidates it.
4074
+ *
4075
+ * @example
4076
+ * ```ts
4077
+ * import { buildGuidance } from '@astrasyncai/verification-gateway';
4078
+ *
4079
+ * try {
4080
+ * const sdk = new AstraSync({ apiKey: callerApiKey, disableEnvFallback: true });
4081
+ * // ...
4082
+ * } catch (err) {
4083
+ * if (err instanceof AuthenticationError) {
4084
+ * return buildGuidance({ origin: 'https://astrasync.ai', message: err.message });
4085
+ * }
4086
+ * throw err;
4087
+ * }
4088
+ * ```
4089
+ */
4090
+ declare function buildGuidance(params: BuildGuidanceParams): GuidanceEnvelope;
4091
+
4092
+ /**
4093
+ * AgentClient — Credential Presentation
4094
+ *
4095
+ * Agent-side SDK for automatically injecting AstraSync credentials
4096
+ * into outgoing requests across all supported protocols.
4097
+ */
4098
+
4099
+ interface AgentClientConfig {
4100
+ agentId: string;
4101
+ verifyUrl?: string;
4102
+ challengeUrl?: string;
4103
+ pdlss?: AstraSyncCredentials['pdlss'];
4104
+ /** Base URL for AstraSync API (used for ownership check). Defaults to https://astrasync.ai/api */
4105
+ apiBaseUrl?: string;
4106
+ /** API key used to authenticate ownership check + other authenticated calls. */
4107
+ apiKey?: string;
4108
+ }
4109
+ interface FetchOptions extends RequestInit {
4110
+ purpose?: string;
4111
+ action?: string;
4112
+ }
4113
+ declare class AgentClient {
4114
+ private credentials;
4115
+ private apiBaseUrl;
4116
+ private apiKey;
4117
+ constructor(config: AgentClientConfig);
4118
+ /**
4119
+ * Async factory that validates the API key's account owns the configured
4120
+ * ASTRA-id before returning a usable client. Refuses to initialise on
4121
+ * mismatch so a stolen ASTRA-id cannot be paired with a valid (different)
4122
+ * API key.
4123
+ *
4124
+ * Set env `ASTRASYNC_SKIP_OWNERSHIP_CHECK=true` to bypass — intended for
4125
+ * test environments only.
4126
+ */
4127
+ static create(config: AgentClientConfig): Promise<AgentClient>;
4128
+ /**
4129
+ * Calls GET /api/agents/:astraId/ownership with the configured API key.
4130
+ * Returns true only when the backend confirms this API key's account
4131
+ * owns the configured agent.
4132
+ */
4133
+ private verifyOwnership;
4134
+ /**
4135
+ * Make an HTTP request with AstraSync headers automatically injected.
4136
+ */
4137
+ fetch(url: string, options?: FetchOptions): Promise<Response>;
4138
+ /**
4139
+ * Prepare A2A task metadata with AstraSync credentials.
4140
+ */
4141
+ prepareA2AMetadata(task: Record<string, unknown>, overrides?: {
4142
+ purpose?: string;
4143
+ action?: string;
4144
+ }): Record<string, unknown>;
4145
+ /**
4146
+ * Prepare MCP params with AstraSync _meta.
4147
+ */
4148
+ prepareMcpMeta(params: Record<string, unknown>, overrides?: {
4149
+ purpose?: string;
4150
+ action?: string;
4151
+ }): Record<string, unknown>;
4152
+ /**
4153
+ * Generic: apply credentials to any protocol.
4154
+ */
4155
+ applyCredentials(protocol: ProtocolTransport, target: Record<string, unknown>, overrides?: {
4156
+ purpose?: string;
4157
+ action?: string;
4158
+ }): Record<string, unknown>;
4159
+ private buildCredentials;
4160
+ }
4161
+
4162
+ /**
4163
+ * ChallengeHandler — Agent-Side Runtime Challenge Responder
4164
+ *
4165
+ * Handles incoming runtime challenges from AstraSync's verification service.
4166
+ * Agents register pending counterparties before initiating contact,
4167
+ * then this handler validates and responds to challenges.
4168
+ */
4169
+ interface ChallengeResponse {
4170
+ status: number;
4171
+ body: {
4172
+ challengeId: string;
4173
+ acknowledged: boolean;
4174
+ pendingCounterparties: string[];
4175
+ respondedAt: string;
4176
+ error?: string;
4177
+ };
4178
+ }
4179
+ interface ChallengeHandlerConfig {
4180
+ agentId: string;
4181
+ }
4182
+ declare class ChallengeHandler {
4183
+ private agentId;
4184
+ private pendingCounterparties;
4185
+ constructor(config: ChallengeHandlerConfig);
4186
+ /**
4187
+ * Register a counterparty as pending (before initiating contact).
4188
+ */
4189
+ registerPending(counterpartyId: string): void;
4190
+ /**
4191
+ * Remove a counterparty from pending list (after interaction complete).
4192
+ */
4193
+ removePending(counterpartyId: string): void;
4194
+ /**
4195
+ * Get current pending counterparties list.
4196
+ */
4197
+ getPendingList(): string[];
4198
+ /**
4199
+ * Express middleware for the challenge endpoint.
4200
+ * Mount at: app.post('/astrasync/challenge', handler.expressMiddleware())
4201
+ */
4202
+ expressMiddleware(): (req: {
4203
+ body: unknown;
4204
+ }, res: {
4205
+ status: (code: number) => {
4206
+ json: (body: unknown) => void;
4207
+ };
4208
+ }) => void;
4209
+ /**
4210
+ * Generic handler (framework-agnostic).
4211
+ * Returns { status, body } for the caller to send.
4212
+ */
4213
+ handleChallenge(body: unknown): ChallengeResponse;
4214
+ }
4215
+
4216
+ /**
4217
+ * PDLSS Formatter — Transport Format Conversion
4218
+ *
4219
+ * Converts between full PDLSS boundaries and compact transport format
4220
+ * used in HTTP headers, A2A metadata, and MCP _meta blocks.
4221
+ */
4222
+
4223
+ /**
4224
+ * Full PDLSS configuration (as returned by the backend).
4225
+ */
4226
+ interface PDLSSConfig {
4227
+ purpose?: {
4228
+ categories?: string[];
4229
+ allowedActions?: string[];
4230
+ deniedActions?: string[];
4231
+ };
4232
+ duration?: {
4233
+ maxSessionDuration?: number;
4234
+ ttl?: number;
4235
+ allowedDays?: number[];
4236
+ allowedHours?: {
4237
+ start: number;
4238
+ end: number;
4239
+ };
4240
+ };
4241
+ limits?: {
4242
+ autonomousThreshold?: number;
4243
+ approvalThreshold?: number;
4244
+ currency?: string;
4245
+ };
4246
+ scope?: {
4247
+ jurisdictions?: string[];
4248
+ resources?: string[];
4249
+ resourceTypes?: string[];
4250
+ };
4251
+ selfInstantiation?: {
4252
+ allowed: boolean;
4253
+ maxDepth?: number;
4254
+ maxSubAgents?: number;
4255
+ };
4256
+ }
4257
+ /**
4258
+ * Compact transport format (embedded in headers/metadata).
4259
+ */
4260
+ type TransportPDLSS = NonNullable<AstraSyncCredentials['pdlss']>;
4261
+ /**
4262
+ * Convert full PDLSS boundaries into compact transport format.
4263
+ * Used by AgentClient when building credential headers/metadata.
4264
+ */
4265
+ declare function formatPDLSSForTransport(pdlss: PDLSSConfig): TransportPDLSS;
4266
+ /**
4267
+ * Parse transport format back into full PDLSS config.
4268
+ * Used by counterparty-side when receiving credentials.
4269
+ */
4270
+ declare function parsePDLSSFromTransport(transport: TransportPDLSS): PDLSSConfig;
4271
+
4272
+ /**
4273
+ * Decision Client — Counterparty-Side Decision Recording
4274
+ *
4275
+ * Helper for counterparties to record their grant/deny decisions
4276
+ * back to AstraSync after receiving a verification result.
4277
+ */
4278
+
4279
+ interface RecordDecisionParams {
4280
+ sessionId: string;
4281
+ decision: 'granted' | 'denied';
4282
+ reason?: string;
4283
+ tokenIssued?: boolean;
4284
+ auditId?: string;
4285
+ }
4286
+ interface RecordDecisionResult {
4287
+ recorded: boolean;
4288
+ blockchainTxHash?: string;
4289
+ }
4290
+ /**
4291
+ * Record a counterparty's grant/deny decision for a verification session.
4292
+ * POST to /agents/verify-access/:sessionId/decision
4293
+ */
4294
+ declare function recordDecision(config: GatewayConfig, params: RecordDecisionParams): Promise<RecordDecisionResult>;
4295
+
4296
+ /**
4297
+ * Agent-side SDK errors.
4298
+ */
4299
+ declare class AstraSyncSdkError extends Error {
4300
+ readonly code: string;
4301
+ constructor(code: string, message: string);
4302
+ }
4303
+ /**
4304
+ * Thrown when the API key used to initialise AgentClient is not owned by
4305
+ * the same account that registered the configured ASTRA-id. Blocks the
4306
+ * client from doing anything under a mismatched identity.
4307
+ */
4308
+ declare class OwnershipMismatchError extends AstraSyncSdkError {
4309
+ readonly astraId: string;
4310
+ constructor(astraId: string);
4311
+ }
4312
+
4313
+ /**
4314
+ * Agent-Side SDK Module
4315
+ *
4316
+ * Tools for AI agents to present credentials, handle challenges,
4317
+ * and interact with the AstraSync verification protocol.
4318
+ */
4319
+
4320
+ type index_AgentClient = AgentClient;
4321
+ declare const index_AgentClient: typeof AgentClient;
4322
+ type index_AstraSyncSdkError = AstraSyncSdkError;
4323
+ declare const index_AstraSyncSdkError: typeof AstraSyncSdkError;
4324
+ type index_ChallengeHandler = ChallengeHandler;
4325
+ declare const index_ChallengeHandler: typeof ChallengeHandler;
4326
+ type index_OwnershipMismatchError = OwnershipMismatchError;
4327
+ declare const index_OwnershipMismatchError: typeof OwnershipMismatchError;
4328
+ type index_PDLSSConfig = PDLSSConfig;
4329
+ type index_TransportPDLSS = TransportPDLSS;
4330
+ declare const index_formatPDLSSForTransport: typeof formatPDLSSForTransport;
4331
+ declare const index_parsePDLSSFromTransport: typeof parsePDLSSFromTransport;
4332
+ declare const index_recordDecision: typeof recordDecision;
4333
+ declare namespace index {
4334
+ export { index_AgentClient as AgentClient, index_AstraSyncSdkError as AstraSyncSdkError, index_ChallengeHandler as ChallengeHandler, index_OwnershipMismatchError as OwnershipMismatchError, type index_PDLSSConfig as PDLSSConfig, type index_TransportPDLSS as TransportPDLSS, index_formatPDLSSForTransport as formatPDLSSForTransport, index_parsePDLSSFromTransport as parsePDLSSFromTransport, index_recordDecision as recordDecision };
4335
+ }
4336
+
4337
+ /**
4338
+ * Edge verification config — the per-endpoint policy the Trusted Agent
4339
+ * Gateway edge adapters (e.g. `@astrasyncai/adapter-lambda`) fetch from the
4340
+ * AstraSync dashboard to decide how much verification friction to apply
4341
+ * to inbound traffic, and where.
4342
+ *
4343
+ * Fetch pattern mirrors `well-known.ts`: TTL cache + stale-while-revalidate
4344
+ * + in-flight dedupe, with a `_reset*` hook for tests. Fail posture is
4345
+ * deliberately asymmetric: this module can NEVER put a site into enforce
4346
+ * mode on its own — enforce only ever originates from a successfully
4347
+ * fetched config, and a config that has gone stale past `maxStaleMs`
4348
+ * degrades back to observe.
4349
+ *
4350
+ * Which EdgeConfig fields each integration consumes:
4351
+ *
4352
+ * | Field | Edge adapters | SDK adapters (express/nextjs/mcp) |
4353
+ * | ------------------------------ | ------------- | --------------------------------- |
4354
+ * | `mode` (observe/enforce) | yes | — |
4355
+ * | `depth` | yes | — |
4356
+ * | `pathRules` | yes | — |
4357
+ * | `sampling.anonymousBeaconRate` | yes | yes — the SDK anonymous beacon |
4358
+ * | `failurePosture` | yes | — |
4359
+ *
4360
+ * The observe/enforce × depth posture is EDGE-ONLY by design: SDK adapters
4361
+ * enforce via the dashboard route policy (`fetchRoutes`), not via this
4362
+ * config, and consume only the `sampling` block for their anonymous
4363
+ * traffic beacon.
4364
+ */
4365
+
4366
+ /**
4367
+ * Edge posture. Canonical Trusted Agent Gateway vocabulary:
4368
+ * `observe` ≈ the gateway's `passive` posture (verify +
4369
+ * record, enforce nothing), `enforce` ≈ `active`. New value set on a new
4370
+ * field name — do NOT reuse `GatewayPosture`'s `active`/`passive` here
4371
+ * (different field, different meaning: posture governs an agent-side
4372
+ * gateway; mode governs counterparty-side edge interception).
4373
+ */
4374
+ type EdgeMode = 'observe' | 'enforce';
4375
+ /**
4376
+ * How deep the edge checks each request — what is it → who is it → are
4377
+ * they allowed:
4378
+ * - `classify` — UA / platform-fingerprint classification only; no
4379
+ * credential handling.
4380
+ * - `authenticate` — establish who is calling: detect and parse agent
4381
+ * credentials (X-Astra-*, VI SD-JWT, RFC 9421, ACP,
4382
+ * UCP, AP2…) and verify presented AstraSync identities.
4383
+ * - `authorize` — full policy decision: credentials cryptographically
4384
+ * proven and PDLSS-evaluated via a verify-access round
4385
+ * trip. (US spelling on the wire, matching
4386
+ * `authorizeSettlement` and HTTP `Authorization`.)
4387
+ */
4388
+ type EdgeVerificationDepth = 'classify' | 'authenticate' | 'authorize';
4389
+ interface EdgePathRule {
4390
+ /**
4391
+ * `*`-wildcard glob matched against the request path. Matching is
4392
+ * case-INsensitive and all regex metacharacters except `*` are
4393
+ * escaped. (Deliberately diverges from the express adapter's
4394
+ * `matchRoute`, which is historically case-sensitive by default —
4395
+ * new surface ships case-insensitive matching as the default.)
4396
+ */
4397
+ pattern: string;
4398
+ /** Pass the request through untouched (static assets); mode/depth ignored. */
4399
+ skip?: boolean;
4400
+ /** Override the top-level mode for this path. */
4401
+ mode?: EdgeMode;
4402
+ /** Override the top-level depth for this path. */
4403
+ depth?: EdgeVerificationDepth;
4404
+ }
4405
+ interface EdgeConfig {
4406
+ /** Shape version — bump on breaking changes. */
4407
+ version: 1;
4408
+ /** Default posture for paths no rule matches. */
4409
+ mode: EdgeMode;
4410
+ /** Default check depth for paths no rule matches. */
4411
+ depth: EdgeVerificationDepth;
4412
+ /** Ordered, first-match-wins. */
4413
+ pathRules: EdgePathRule[];
4414
+ sampling: {
4415
+ /** Fraction (0..1) of anonymous-bot requests that emit a beacon. */
4416
+ anonymousBeaconRate: number;
4417
+ };
4418
+ /**
4419
+ * 4.5.0: the EFFECTIVE failure posture is derived from the effective
4420
+ * mode — fail posture follows success posture. Observe fails open
4421
+ * (unreachable backend = pass-through, site never breaks); enforce fails
4422
+ * closed on verification-infrastructure failure (503
4423
+ * `VERIFICATION_UNAVAILABLE`, retry-later — see edge-core/pipeline). This
4424
+ * field is retained on the wire for adapter compatibility and as a future
4425
+ * explicit override; it is not consulted by the 4.5.x pipeline. Note the
4426
+ * distinction from CONFIG staleness: a config stale past 24h still has
4427
+ * enforce degraded to observe (`degradeToObserve`) — that is config-trust
4428
+ * hygiene, independent of runtime verification availability.
4429
+ */
4430
+ failurePosture: 'open' | 'closed';
4431
+ }
4432
+ /**
4433
+ * The safe default: observe-only, classification depth, nothing enforced.
4434
+ * Served by the backend when an endpoint has never been configured, and
4435
+ * used by `getEdgeConfig` whenever no config can be fetched.
4436
+ */
4437
+ declare const DEFAULT_EDGE_CONFIG: EdgeConfig;
4438
+ /** Structural guard for configs arriving over the wire. */
4439
+ declare function isEdgeConfig(value: unknown): value is EdgeConfig;
4440
+ interface FetchEdgeConfigSuccess {
4441
+ edgeConfig: EdgeConfig;
4442
+ etag?: string;
4443
+ }
4444
+ type FetchEdgeConfigResult = FetchEdgeConfigSuccess | {
4445
+ notModified: true;
4446
+ } | null;
4447
+ /**
4448
+ * Fetch the edge config for an endpoint from the AstraSync backend.
4449
+ * `GET {apiBaseUrl}/endpoints/:counterpartyId/edge-config` with the same
4450
+ * auth headers as `fetchRoutes`. Pass the cached `etag` to get a cheap
4451
+ * `{ notModified: true }` on 304. Returns `null` on any failure —
4452
+ * the caller decides how to fall back.
4453
+ */
4454
+ declare function fetchEdgeConfig(config: Pick<GatewayConfig, 'apiBaseUrl' | 'apiKey'>, counterpartyId: string, opts?: {
4455
+ etag?: string;
4456
+ timeoutMs?: number;
4457
+ }): Promise<FetchEdgeConfigResult>;
4458
+ /** Copy of `config` with every enforce (top-level and per-rule) degraded to observe. */
4459
+ declare function degradeToObserve(config: EdgeConfig): EdgeConfig;
4460
+ /**
4461
+ * Get the edge config for an endpoint, cached. Never throws, never blocks
4462
+ * longer than one fetch.
4463
+ *
4464
+ * - Fresh cache (within `ttlMs`) → cached config, no network.
4465
+ * - Stale cache → cached config immediately + background revalidate
4466
+ * (stale-while-revalidate). If the last successful fetch is older than
4467
+ * `maxStaleMs` (default 24h), any enforce is degraded to observe — a
4468
+ * long-dead backend can never keep a site enforcing.
4469
+ * - No cache → await one fetch; on failure return `DEFAULT_EDGE_CONFIG`
4470
+ * (observe-only). Defaults never enforce.
4471
+ */
4472
+ declare function getEdgeConfig(config: Pick<GatewayConfig, 'apiBaseUrl' | 'apiKey'>, counterpartyId: string, opts?: {
4473
+ ttlMs?: number;
4474
+ maxStaleMs?: number;
4475
+ }): Promise<EdgeConfig>;
4476
+ /**
4477
+ * First-match-wins path-rule lookup. Case-insensitive `*` globs with all
4478
+ * other regex metacharacters escaped (a literal `.` in a pattern matches
4479
+ * only `.`). Returns `undefined` when no rule matches — the caller applies
4480
+ * the config's top-level mode/depth.
4481
+ */
4482
+ declare function matchEdgePathRule(rules: EdgePathRule[], path: string): EdgePathRule | undefined;
4483
+ /** Reset cache — for testing only. */
4484
+ declare function _resetEdgeConfigCache(): void;
4485
+
4486
+ /**
4487
+ * Platform-agent fingerprint signatures — the shared registry of known
4488
+ * platform-agent UA / agent-card patterns (Claude / ChatGPT / Gemini /
4489
+ * Cursor / Goose).
4490
+ *
4491
+ * Single source of truth, lifted verbatim from the backend's
4492
+ * `platform-agent-detector.service` (which now imports detection from
4493
+ * here): the backend's verify-access anonymous handler and the edge
4494
+ * adapter (`@astrasyncai/adapter-lambda`) must classify identically or
4495
+ * the three-tier visibility numbers drift between capture points.
4496
+ *
4497
+ * Pure regex — no Node built-ins, edge-safe. Detection is regex-only for
4498
+ * v2.9 — TLS fingerprinting / behavioural signatures are deferred.
4499
+ */
4500
+ type PlatformAgentVendor = 'claude' | 'chatgpt' | 'gemini' | 'cursor' | 'goose' | 'perplexity' | 'chatgpt-atlas' | 'perplexity-comet' | 'astrasync-sdk' | 'unknown';
4501
+ interface PlatformFingerprint {
4502
+ vendor: PlatformAgentVendor;
4503
+ /** A stable identifier used as the orphan-agent dedup key. */
4504
+ fingerprintKey: string;
4505
+ /** Human-readable name surfaced in the admin panel. */
4506
+ displayName: string;
4507
+ }
4508
+ interface PlatformDetectionInput {
4509
+ userAgent?: string;
4510
+ agentCardUrl?: string;
4511
+ /**
4512
+ * A safe API-key format prefix observed on the caller's
4513
+ * credential header (e.g. `sk-ant-api03`, `sk-proj`, `aiza`). A strong
4514
+ * platform signal; never the secret. Matched against `apiKeyFormatPatterns`.
4515
+ */
4516
+ apiKeyFormat?: string;
4517
+ /**
4518
+ * The sanitised platform-signal headers (lowercased names →
4519
+ * values), e.g. `openai-organization`, `x-goog-user-project`. Matched
4520
+ * against `headerPatterns` (which test on `name` and `name: value`).
4521
+ */
4522
+ platformHeaders?: Record<string, string>;
4523
+ /**
4524
+ * The caller's JA4 TLS-client fingerprint (from the connection capture).
4525
+ * Matched against `ja4Patterns`. A JA4 identifies the client TLS stack,
4526
+ * so signatures should pair it with other evidence when attributing a
4527
+ * vendor.
4528
+ */
4529
+ ja4?: string;
4530
+ /**
4531
+ * The caller's origin ASN (from the connection capture). Matched against
4532
+ * `asnList` by exact membership. An ASN alone attributes an entire cloud
4533
+ * provider — registry validation rejects ASN-only signatures.
4534
+ */
4535
+ asn?: string;
4536
+ }
4537
+ /**
4538
+ * A signature definition, generic over the vendor key. The seed constant
4539
+ * below uses the closed `PlatformAgentVendor` union; DB-promoted signatures
4540
+ * (backend dynamic registry, console round) carry arbitrary string vendors —
4541
+ * `matchPlatformSignature` accepts both.
4542
+ */
4543
+ interface PlatformSignatureDef<V extends string = string> {
4544
+ vendor: V;
4545
+ displayName: string;
4546
+ uaPatterns?: RegExp[];
4547
+ agentCardPatterns?: RegExp[];
4548
+ /**
4549
+ * Patterns tested against an observed API-key format prefix
4550
+ * (e.g. `/^sk-ant/i` → claude). A credential-header format is a stronger
4551
+ * platform signal than a spoofable User-Agent.
4552
+ */
4553
+ apiKeyFormatPatterns?: RegExp[];
4554
+ /**
4555
+ * Patterns tested against each observed platform-signal
4556
+ * header, as both `name` and `name: value` (so `/openai-organization/i` and
4557
+ * `/x-goog-user-project/i` match on presence).
4558
+ */
4559
+ headerPatterns?: RegExp[];
4560
+ /** Patterns tested against the observed JA4 TLS-client fingerprint. */
4561
+ ja4Patterns?: RegExp[];
4562
+ /** Exact ASN strings this signature matches (never regex). */
4563
+ asnList?: string[];
4564
+ }
4565
+ /**
4566
+ * A fingerprint whose vendor may be a dynamically-promoted (non-seed) key.
4567
+ * Structurally a superset of `PlatformFingerprint`.
4568
+ */
4569
+ interface DynamicPlatformFingerprint {
4570
+ vendor: string;
4571
+ fingerprintKey: string;
4572
+ displayName: string;
4573
+ }
4574
+ /**
4575
+ * Registry of known platform-agent signatures. Order matters — first match wins.
4576
+ *
4577
+ * Patterns are intentionally permissive (case-insensitive substring match) since
4578
+ * platform UA strings drift between versions. False positives are tolerable —
4579
+ * the orphan record is informational, not enforcement.
4580
+ */
4581
+ declare const PLATFORM_AGENT_SIGNATURES: ReadonlyArray<PlatformSignatureDef<PlatformAgentVendor>>;
4582
+ /**
4583
+ * Generic first-match-wins matcher over an arbitrary signature set. The
4584
+ * backend's dynamic registry merges the seed constant with DB-promoted
4585
+ * signatures and calls this — ONE matching implementation everywhere
4586
+ * (fingerprint-key rule included: vendor + lowercased UA basename before
4587
+ * the first space/slash, falling back to the agent-card host).
4588
+ */
4589
+ declare function matchPlatformSignature(signatures: ReadonlyArray<PlatformSignatureDef>, input: PlatformDetectionInput): DynamicPlatformFingerprint | undefined;
4590
+ /**
4591
+ * Inspect caller metadata for a known SEED platform-agent fingerprint.
4592
+ * Returns undefined if no signature matches. (Backends with the dynamic
4593
+ * registry should call `matchPlatformSignature` over their merged set
4594
+ * instead — same semantics, live signature additions included.)
4595
+ */
4596
+ declare function detectPlatformFingerprint(input: PlatformDetectionInput): PlatformFingerprint | undefined;
133
4597
 
134
4598
  /**
135
4599
  * HTTP-client RUNTIME signatures — a display-only vocabulary, disjoint from
@@ -177,7 +4641,7 @@ declare function detectRuntime(userAgent: string | undefined | null): string | u
177
4641
  * silently (never throwing), so this is a no-op there — which is correct:
178
4642
  * in a browser the page's real UA is the honest identity.
179
4643
  */
180
- declare const SDK_USER_AGENT = "astrasync-sdk/5.4.0";
4644
+ declare const SDK_USER_AGENT = "astrasync-sdk/5.4.1";
181
4645
  declare const sdkFetch: typeof fetch;
182
4646
 
183
4647
  /**
@@ -198,6 +4662,6 @@ declare const sdkFetch: typeof fetch;
198
4662
  * is fine — bumping both in the release-ceremony commit keeps them
199
4663
  * lockstep.
200
4664
  */
201
- declare const SDK_VERSION = "5.4.0";
4665
+ declare const SDK_VERSION = "5.4.1";
202
4666
 
203
- export { EnhancedVerificationResult, GatewayConfig, RUNTIME_SIGNATURES, type RuntimeSignature, SDK_USER_AGENT, type SettlementDecision, type SettlementRequest, StepUpApprovalInfo, StepUpApprovalStatus, StepUpOutcome, SDK_VERSION as VERSION, type WellKnownAgenticCommerce, authorizeSettlement, awaitStepUpApproval, detectRuntime, getCachedWellKnownUrls, getWellKnownUrls, pollStepUpStatus, prefetchWellKnown, sdkFetch };
4667
+ export { AgentClient, type AgentCredentials, type AgentProtocol, type AgentRecord, AstraSync, type AstraSyncConfig, type AstraSyncCredentials, AstraSyncError, type AttemptOutcome, type AttemptReport, AuthenticationError, type BuildGuidanceParams, CAPTURE_SCHEMA_VERSION, type CallerMetadata, ChallengeHandler, type CommerceArtifactsPayload, type CommerceContext, type CommercePipelineInput, type CommerceShieldProps, type ConsiderationItem, type ConsiderationSet, type CounterpartyType, DEFAULT_EDGE_CONFIG, type DynamicPlatformFingerprint, type EdgeConfig, type EdgeMode, type EdgePathRule, type EdgeVerificationDepth, type EnhancedVerificationResult, type ExpressMiddlewareOptions, type FetchEdgeConfigResult, type FetchEdgeConfigSuccess, type FiatSettlementBinding, type FrameworkConfig, type GatewayConfig, type GuidanceEnvelope, type GuidanceInfo, type HealthResponse, KYDRequiredError, MAX_HEADERS, MAX_HEADER_VALUE_BYTES, MAX_TOTAL_BYTES, MCP_VERIFIED_HOP_HEADER, MCP_VERIFIED_HOP_MAX_AGE_MS, type McpMiddlewareOptions, type ModelConfig, type NextJsMiddlewareOptions, type ObservedMetadata, type PDLSSConfig$1 as PDLSSConfig, type PDLSSDuration, type PDLSSInfo, type PDLSSLimits, type PDLSSPurpose, type PDLSSScope, type PDLSSSelfInstantiation, PLATFORM_AGENT_SIGNATURES, type PendingRegistrationResponse, type PlatformAgentVendor, type PlatformDetectionInput, type PlatformFingerprint, type PlatformSignatureDef, type PollRegistrationResult, type ProtocolTransport, RUNTIME_SIGNATURES, type RegisterOptions, type RegisterResult, RegistrationDeniedError, RegistrationExpiredError, type RegistrationResponse, RegistrationTimeoutError, type RouteAccessConfig, type RuntimeChallengeResult, type RuntimeSignature, type SDKOptions, SDK_USER_AGENT, type SanitizeHeadersResult, type SettlementArtifact, type SettlementArtifactBinding, type SettlementArtifactBindingBase, type SettlementDecision, type SettlementOutcomeInfo, type SettlementRequest, type StablecoinSettlementBinding, type StepUpApprovalInfo, type StepUpApprovalStatus, type StepUpOutcome, TRUST_LEVEL_RANGES, type TokenGuidance, type ToolGate, type ToolGateConfig, type TrustLevel, SDK_VERSION as VERSION, type VerificationInterstitialProps, type VerificationRequest, type VerificationResult, type VerifiedAgent, type VerifiedDeveloper, type VerifiedHopMarker, type VerifiedOrganization, type VerifyOptions, type VerifyResponse, type WaitForApprovalOptions, type WellKnownAgenticCommerce, _resetEdgeConfigCache, index as agent, authorizeSettlement, awaitStepUpApproval, buildGuidance, buildSdkObservedMetadata, clearCache, createMcpMiddleware, degradeToObserve, deriveConnectionFromHeaders, detectPlatformFingerprint, detectRuntime, express, extractApiKeyFormat, extractCredentials, extractMcpCredentials, extractPlatformHeaders, fetchEdgeConfig, fetchRoutes, getCachedWellKnownUrls, getEdgeConfig, getTrustLevel, getWellKnownUrls, hasCredentials, isEdgeConfig, isVerifiedHopValidFor, matchEdgePathRule, matchPlatformSignature, nextjs, parseVerifiedHop, pollStepUpStatus, prefetchWellKnown, quickVerify, recordDecision, reportAttempt, reportUnregisteredAttempt, sanitizeHeaders, sdk, sdkFetch, serializeVerifiedHop, setMcpMeta, index$1 as transport, verify };