@astrasyncai/verification-gateway 5.4.2 → 5.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +74 -21
- package/dist/adapters/express.d.mts +1 -1
- package/dist/adapters/express.d.ts +1 -1
- package/dist/adapters/express.js +12 -3
- package/dist/adapters/express.js.map +1 -1
- package/dist/adapters/express.mjs +12 -3
- package/dist/adapters/express.mjs.map +1 -1
- package/dist/adapters/mcp.d.mts +1 -1
- package/dist/adapters/mcp.d.ts +1 -1
- package/dist/adapters/mcp.js +12 -3
- package/dist/adapters/mcp.js.map +1 -1
- package/dist/adapters/mcp.mjs +12 -3
- package/dist/adapters/mcp.mjs.map +1 -1
- package/dist/adapters/nextjs.d.mts +1 -1
- package/dist/adapters/nextjs.d.ts +1 -1
- package/dist/adapters/nextjs.js +12 -3
- package/dist/adapters/nextjs.js.map +1 -1
- package/dist/adapters/nextjs.mjs +12 -3
- package/dist/adapters/nextjs.mjs.map +1 -1
- package/dist/adapters/sdk.d.mts +41 -1
- package/dist/adapters/sdk.d.ts +41 -1
- package/dist/adapters/sdk.js +54 -3
- package/dist/adapters/sdk.js.map +1 -1
- package/dist/adapters/sdk.mjs +54 -3
- package/dist/adapters/sdk.mjs.map +1 -1
- package/dist/agent/index.js +1 -1
- package/dist/agent/index.js.map +1 -1
- package/dist/agent/index.mjs +1 -1
- package/dist/agent/index.mjs.map +1 -1
- package/dist/bin/astrasync-claude-hook.js +12 -3
- package/dist/bin/astrasync-codex-hook.js +12 -3
- package/dist/bin/astrasync-guard.js +12 -3
- package/dist/bin/astrasync.js +13 -3
- package/dist/browser/background.js +12 -3
- package/dist/browser/background.js.map +1 -1
- package/dist/browser/background.mjs +12 -3
- package/dist/browser/background.mjs.map +1 -1
- package/dist/cli/index.js +1 -1
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/index.mjs +1 -1
- package/dist/cli/index.mjs.map +1 -1
- package/dist/codex/index.js +12 -3
- package/dist/codex/index.js.map +1 -1
- package/dist/codex/index.mjs +12 -3
- package/dist/codex/index.mjs.map +1 -1
- package/dist/cursor/extension.js +12 -3
- package/dist/cursor/extension.js.map +1 -1
- package/dist/cursor/extension.mjs +12 -3
- package/dist/cursor/extension.mjs.map +1 -1
- package/dist/edge-config.d.mts +1 -1
- package/dist/edge-config.d.ts +1 -1
- package/dist/edge-config.js +1 -1
- package/dist/edge-config.js.map +1 -1
- package/dist/edge-config.mjs +1 -1
- package/dist/edge-config.mjs.map +1 -1
- package/dist/edge-core/index.d.mts +1 -1
- package/dist/edge-core/index.d.ts +1 -1
- package/dist/edge-core/index.js +12 -3
- package/dist/edge-core/index.js.map +1 -1
- package/dist/edge-core/index.mjs +12 -3
- package/dist/edge-core/index.mjs.map +1 -1
- package/dist/gateway/gateway.js +12 -3
- package/dist/gateway/gateway.js.map +1 -1
- package/dist/gateway/gateway.mjs +12 -3
- package/dist/gateway/gateway.mjs.map +1 -1
- package/dist/git-trigger/git-hooks.d.mts +1 -1
- package/dist/git-trigger/git-hooks.d.ts +1 -1
- package/dist/index.d.mts +121 -4
- package/dist/index.d.ts +121 -4
- package/dist/index.js +54 -3
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +54 -3
- package/dist/index.mjs.map +1 -1
- package/dist/registration/index.js +1 -1
- package/dist/registration/index.js.map +1 -1
- package/dist/registration/index.mjs +1 -1
- package/dist/registration/index.mjs.map +1 -1
- package/dist/transport/index.js +1 -1
- package/dist/transport/index.js.map +1 -1
- package/dist/transport/index.mjs +1 -1
- package/dist/transport/index.mjs.map +1 -1
- package/dist/{types-Bd2O3eX1.d.mts → types-BCmHFdkJ.d.mts} +78 -1
- package/dist/{types-BU04qAAR.d.mts → types-BK_pRNSs.d.mts} +78 -1
- package/dist/{types-BU04qAAR.d.ts → types-BK_pRNSs.d.ts} +78 -1
- package/dist/{types-DMChboN_.d.ts → types-CwY5IY-0.d.ts} +78 -1
- package/dist/ui/index.d.mts +1 -1
- package/dist/ui/index.d.ts +1 -1
- package/dist/verify.d.mts +1 -1
- package/dist/verify.d.ts +1 -1
- package/dist/verify.js +12 -3
- package/dist/verify.js.map +1 -1
- package/dist/verify.mjs +12 -3
- package/dist/verify.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/edge-core/index.ts","../../src/version.ts","../../src/http.ts","../../src/edge-config.ts","../../src/metadata-capture.ts","../../src/platform-signatures.ts","../../src/trust-levels.ts","../../src/well-known.ts","../../src/verify.ts","../../src/edge-core/request.ts","../../src/edge-core/detect.ts","../../src/edge-core/classify.ts","../../src/edge-core/messaging.ts","../../src/verified-hop.ts","../../src/edge-core/enforce.ts","../../src/adapters/http-pdlss.ts","../../src/edge-core/events.ts","../../src/edge-core/pipeline.ts","../../src/edge-core/evaluate.ts"],"sourcesContent":["/**\n * AstraSync Trusted Agent Gateway — platform-neutral edge core.\n *\n * The shared classification/detection/verification/enforcement pipeline\n * behind the AstraSync edge adapters (`@astrasyncai/adapter-lambda`,\n * `@astrasyncai/adapter-edge`). Platform packages normalize their native\n * request shape into a {@link NormalizedRequest}, call\n * {@link evaluateEdgeRequest}, and apply the returned\n * {@link OutcomeApplication} onto their native primitives.\n */\n\nexport { classify, resolvePolicy, _patterns } from './classify';\nexport { detectCommerce, type DetectedCommerce } from './detect';\nexport { evaluateEdgeRequest, type EdgeEvaluation } from './evaluate';\nexport { applyOutcome, passUntouched, ASAT_HEADERS } from './enforce';\nexport { withBudget, emitBeacon, sampled } from './events';\nexport {\n buildDenyBody,\n buildManualReviewBody,\n type DenyBody,\n type ManualReviewBody,\n} from './messaging';\nexport { runTier, buildVerificationRequest, outcomeFromVerifyResult } from './pipeline';\nexport { headerValue, requestUrl, buildObservedMetadata } from './request';\nexport type {\n NormalizedRequest,\n PlatformIo,\n OutcomeApplication,\n TrafficTier,\n Classification,\n EdgeDecision,\n TierOutcome,\n EffectivePolicy,\n EdgeCoreOptions,\n EdgeLogger,\n} from './types';\n","/**\n * Single source-of-truth for the SDK's\n * package version emitted on verify-access bodies (and any future\n * telemetry). Bumped alongside `package.json#version` on every release.\n *\n * Why a constant rather than `import pkg from '../package.json'`:\n * - `tsconfig.json` sets `rootDir: ./src`; importing the sibling\n * package.json fails the build with \"outside rootDir\".\n * - Build-time string replacement (tsup `define`, esbuild banner, etc.)\n * adds toolchain coupling for a trivial gain.\n * - Embedded readonly constant works in every environment (Node, browser,\n * bundlers, Deno) without runtime fs / network access.\n *\n * Release discipline: a CI lint can grep `package.json#version` against\n * this constant if the two ever diverge in the wild. A manual bump\n * is fine — bumping both in the release-ceremony commit keeps them\n * lockstep.\n */\nexport const SDK_VERSION = '5.4.1';\n","/**\n * Shared outbound-HTTP wrapper — every request the SDK makes to the\n * AstraSync backend (or anywhere else) goes through `sdkFetch` so it\n * carries an identifying User-Agent.\n *\n * Why: Node's global fetch defaults to `user-agent: node`, which is\n * indistinguishable from every other Node client on the wire. Visit\n * Intelligence observed our own SDK/beacon traffic as anonymous \"node\"\n * visits. Self-identification is the platform's own medicine.\n *\n * Browser note: some browsers filter the User-Agent request header\n * silently (never throwing), so this is a no-op there — which is correct:\n * in a browser the page's real UA is the honest identity.\n */\n\nimport { SDK_VERSION } from './version';\n\nexport const SDK_USER_AGENT = `astrasync-sdk/${SDK_VERSION}`;\n\n/**\n * Add the SDK User-Agent without changing the SHAPE of the caller's headers\n * (plain records stay plain records) — interceptors, adapters, and tests\n * read `init.headers` as a record, and `Headers` would also lowercase names.\n */\nfunction withUserAgent(initHeaders: HeadersInit | undefined): HeadersInit {\n if (!initHeaders) return { 'user-agent': SDK_USER_AGENT };\n if (initHeaders instanceof Headers) {\n const copy = new Headers(initHeaders);\n if (!copy.has('user-agent')) copy.set('user-agent', SDK_USER_AGENT);\n return copy;\n }\n if (Array.isArray(initHeaders)) {\n const has = initHeaders.some(([name]) => name.toLowerCase() === 'user-agent');\n return has ? initHeaders : [...initHeaders, ['user-agent', SDK_USER_AGENT]];\n }\n const has = Object.keys(initHeaders).some((name) => name.toLowerCase() === 'user-agent');\n return has ? initHeaders : { 'user-agent': SDK_USER_AGENT, ...initHeaders };\n}\n\nexport const sdkFetch: typeof fetch = (input, init) =>\n fetch(input, { ...init, headers: withUserAgent(init?.headers) });\n","/**\n * Edge verification config — the per-endpoint policy the Trusted Agent\n * Gateway edge adapters (e.g. `@astrasyncai/adapter-lambda`) fetch from the\n * AstraSync dashboard to decide how much verification friction to apply\n * to inbound traffic, and where.\n *\n * Fetch pattern mirrors `well-known.ts`: TTL cache + stale-while-revalidate\n * + in-flight dedupe, with a `_reset*` hook for tests. Fail posture is\n * deliberately asymmetric: this module can NEVER put a site into enforce\n * mode on its own — enforce only ever originates from a successfully\n * fetched config, and a config that has gone stale past `maxStaleMs`\n * degrades back to observe.\n *\n * Which EdgeConfig fields each integration consumes:\n *\n * | Field | Edge adapters | SDK adapters (express/nextjs/mcp) |\n * | ------------------------------ | ------------- | --------------------------------- |\n * | `mode` (observe/enforce) | yes | — |\n * | `depth` | yes | — |\n * | `pathRules` | yes | — |\n * | `sampling.anonymousBeaconRate` | yes | yes — the SDK anonymous beacon |\n * | `failurePosture` | yes | — |\n *\n * The observe/enforce × depth posture is EDGE-ONLY by design: SDK adapters\n * enforce via the dashboard route policy (`fetchRoutes`), not via this\n * config, and consume only the `sampling` block for their anonymous\n * traffic beacon.\n */\n\nimport { sdkFetch } from './http';\nimport type { GatewayConfig } from './types';\n\n/**\n * Edge posture. Canonical Trusted Agent Gateway vocabulary:\n * `observe` ≈ the gateway's `passive` posture (verify +\n * record, enforce nothing), `enforce` ≈ `active`. New value set on a new\n * field name — do NOT reuse `GatewayPosture`'s `active`/`passive` here\n * (different field, different meaning: posture governs an agent-side\n * gateway; mode governs counterparty-side edge interception).\n */\nexport type EdgeMode = 'observe' | 'enforce';\n\n/**\n * How deep the edge checks each request — what is it → who is it → are\n * they allowed:\n * - `classify` — UA / platform-fingerprint classification only; no\n * credential handling.\n * - `authenticate` — establish who is calling: detect and parse agent\n * credentials (X-Astra-*, VI SD-JWT, RFC 9421, ACP,\n * UCP, AP2…) and verify presented AstraSync identities.\n * - `authorize` — full policy decision: credentials cryptographically\n * proven and PDLSS-evaluated via a verify-access round\n * trip. (US spelling on the wire, matching\n * `authorizeSettlement` and HTTP `Authorization`.)\n */\nexport type EdgeVerificationDepth = 'classify' | 'authenticate' | 'authorize';\n\nexport interface EdgePathRule {\n /**\n * `*`-wildcard glob matched against the request path. Matching is\n * case-INsensitive and all regex metacharacters except `*` are\n * escaped. (Deliberately diverges from the express adapter's\n * `matchRoute`, which is historically case-sensitive by default —\n * new surface ships case-insensitive matching as the default.)\n */\n pattern: string;\n /** Pass the request through untouched (static assets); mode/depth ignored. */\n skip?: boolean;\n /** Override the top-level mode for this path. */\n mode?: EdgeMode;\n /** Override the top-level depth for this path. */\n depth?: EdgeVerificationDepth;\n}\n\nexport interface EdgeConfig {\n /** Shape version — bump on breaking changes. */\n version: 1;\n /** Default posture for paths no rule matches. */\n mode: EdgeMode;\n /** Default check depth for paths no rule matches. */\n depth: EdgeVerificationDepth;\n /** Ordered, first-match-wins. */\n pathRules: EdgePathRule[];\n sampling: {\n /** Fraction (0..1) of anonymous-bot requests that emit a beacon. */\n anonymousBeaconRate: number;\n };\n /**\n * 4.5.0: the EFFECTIVE failure posture is derived from the effective\n * mode — fail posture follows success posture. Observe fails open\n * (unreachable backend = pass-through, site never breaks); enforce fails\n * closed on verification-infrastructure failure (503\n * `VERIFICATION_UNAVAILABLE`, retry-later — see edge-core/pipeline). This\n * field is retained on the wire for adapter compatibility and as a future\n * explicit override; it is not consulted by the 4.5.x pipeline. Note the\n * distinction from CONFIG staleness: a config stale past 24h still has\n * enforce degraded to observe (`degradeToObserve`) — that is config-trust\n * hygiene, independent of runtime verification availability.\n */\n failurePosture: 'open' | 'closed';\n}\n\n/**\n * The safe default: observe-only, classification depth, nothing enforced.\n * Served by the backend when an endpoint has never been configured, and\n * used by `getEdgeConfig` whenever no config can be fetched.\n */\nexport const DEFAULT_EDGE_CONFIG: EdgeConfig = Object.freeze({\n version: 1,\n mode: 'observe',\n depth: 'classify',\n pathRules: [],\n sampling: Object.freeze({ anonymousBeaconRate: 0.1 }),\n failurePosture: 'open',\n}) as EdgeConfig;\n\nconst EDGE_MODES: readonly string[] = ['observe', 'enforce'];\nconst EDGE_DEPTHS: readonly string[] = ['classify', 'authenticate', 'authorize'];\n\n/** Structural guard for configs arriving over the wire. */\nexport function isEdgeConfig(value: unknown): value is EdgeConfig {\n if (typeof value !== 'object' || value === null) return false;\n const v = value as Record<string, unknown>;\n if (v.version !== 1) return false;\n if (!EDGE_MODES.includes(v.mode as string)) return false;\n if (!EDGE_DEPTHS.includes(v.depth as string)) return false;\n if (!Array.isArray(v.pathRules)) return false;\n for (const rule of v.pathRules) {\n if (typeof rule !== 'object' || rule === null) return false;\n const r = rule as Record<string, unknown>;\n if (typeof r.pattern !== 'string' || r.pattern.length === 0) return false;\n if (r.mode !== undefined && !EDGE_MODES.includes(r.mode as string)) return false;\n if (r.depth !== undefined && !EDGE_DEPTHS.includes(r.depth as string)) return false;\n }\n const sampling = v.sampling as Record<string, unknown> | undefined;\n if (\n typeof sampling !== 'object' ||\n sampling === null ||\n typeof sampling.anonymousBeaconRate !== 'number' ||\n sampling.anonymousBeaconRate < 0 ||\n sampling.anonymousBeaconRate > 1\n ) {\n return false;\n }\n return v.failurePosture === 'open';\n}\n\nexport interface FetchEdgeConfigSuccess {\n edgeConfig: EdgeConfig;\n etag?: string;\n}\n\nexport type FetchEdgeConfigResult = FetchEdgeConfigSuccess | { notModified: true } | null;\n\n/**\n * Fetch the edge config for an endpoint from the AstraSync backend.\n * `GET {apiBaseUrl}/endpoints/:counterpartyId/edge-config` with the same\n * auth headers as `fetchRoutes`. Pass the cached `etag` to get a cheap\n * `{ notModified: true }` on 304. Returns `null` on any failure —\n * the caller decides how to fall back.\n */\nexport async function fetchEdgeConfig(\n config: Pick<GatewayConfig, 'apiBaseUrl' | 'apiKey'>,\n counterpartyId: string,\n opts?: { etag?: string; timeoutMs?: number }\n): Promise<FetchEdgeConfigResult> {\n if (!counterpartyId) return null;\n const headers: Record<string, string> = { Accept: 'application/json' };\n if (config.apiKey) {\n headers['Authorization'] = `Bearer ${config.apiKey}`;\n headers['X-API-Key'] = config.apiKey;\n }\n if (opts?.etag) headers['If-None-Match'] = opts.etag;\n try {\n const response = await sdkFetch(\n `${config.apiBaseUrl}/endpoints/${encodeURIComponent(counterpartyId)}/edge-config`,\n { method: 'GET', headers, signal: AbortSignal.timeout(opts?.timeoutMs ?? 5000) }\n );\n if (response.status === 304) return { notModified: true };\n if (!response.ok) return null;\n const body = (await response.json()) as { data?: { edgeConfig?: unknown } };\n const edgeConfig = body.data?.edgeConfig;\n if (!isEdgeConfig(edgeConfig)) return null;\n return { edgeConfig, etag: response.headers.get('etag') ?? undefined };\n } catch {\n return null;\n }\n}\n\ninterface CacheEntry {\n config: EdgeConfig;\n etag?: string;\n /** When the entry was last confirmed fresh (fetch or 304). */\n lastSuccessAt: number;\n}\n\nconst DEFAULT_TTL_MS = 60 * 1000;\nconst DEFAULT_MAX_STALE_MS = 24 * 60 * 60 * 1000;\n\nconst cache = new Map<string, CacheEntry>();\nconst inflight = new Map<string, Promise<void>>();\n\nfunction cacheKey(apiBaseUrl: string, counterpartyId: string): string {\n return `${apiBaseUrl}|${counterpartyId}`;\n}\n\n/** Copy of `config` with every enforce (top-level and per-rule) degraded to observe. */\nexport function degradeToObserve(config: EdgeConfig): EdgeConfig {\n if (config.mode !== 'enforce' && !config.pathRules.some((r) => r.mode === 'enforce')) {\n return config;\n }\n return {\n ...config,\n mode: 'observe',\n pathRules: config.pathRules.map((r) => (r.mode === 'enforce' ? { ...r, mode: 'observe' } : r)),\n };\n}\n\nasync function revalidate(\n config: Pick<GatewayConfig, 'apiBaseUrl' | 'apiKey'>,\n counterpartyId: string\n): Promise<void> {\n const key = cacheKey(config.apiBaseUrl, counterpartyId);\n const existing = inflight.get(key);\n if (existing) return existing;\n\n const promise = fetchEdgeConfig(config, counterpartyId, { etag: cache.get(key)?.etag })\n .then((result) => {\n if (result === null) return; // failure — cache untouched, caller falls back\n const now = Date.now();\n if ('notModified' in result) {\n const entry = cache.get(key);\n if (entry) entry.lastSuccessAt = now;\n return;\n }\n cache.set(key, { config: result.edgeConfig, etag: result.etag, lastSuccessAt: now });\n })\n .finally(() => {\n inflight.delete(key);\n });\n\n inflight.set(key, promise);\n return promise;\n}\n\n/**\n * Get the edge config for an endpoint, cached. Never throws, never blocks\n * longer than one fetch.\n *\n * - Fresh cache (within `ttlMs`) → cached config, no network.\n * - Stale cache → cached config immediately + background revalidate\n * (stale-while-revalidate). If the last successful fetch is older than\n * `maxStaleMs` (default 24h), any enforce is degraded to observe — a\n * long-dead backend can never keep a site enforcing.\n * - No cache → await one fetch; on failure return `DEFAULT_EDGE_CONFIG`\n * (observe-only). Defaults never enforce.\n */\nexport async function getEdgeConfig(\n config: Pick<GatewayConfig, 'apiBaseUrl' | 'apiKey'>,\n counterpartyId: string,\n opts?: { ttlMs?: number; maxStaleMs?: number }\n): Promise<EdgeConfig> {\n const ttlMs = opts?.ttlMs ?? DEFAULT_TTL_MS;\n const maxStaleMs = opts?.maxStaleMs ?? DEFAULT_MAX_STALE_MS;\n const key = cacheKey(config.apiBaseUrl, counterpartyId);\n\n const entry = cache.get(key);\n if (entry) {\n const age = Date.now() - entry.lastSuccessAt;\n if (age > ttlMs) {\n revalidate(config, counterpartyId).catch(() => {\n // background refresh failed — stale entry remains until next call\n });\n }\n return age > maxStaleMs ? degradeToObserve(entry.config) : entry.config;\n }\n\n await revalidate(config, counterpartyId).catch(() => {\n // fetch failed — fall through to defaults\n });\n return cache.get(key)?.config ?? DEFAULT_EDGE_CONFIG;\n}\n\n/**\n * First-match-wins path-rule lookup. Case-insensitive `*` globs with all\n * other regex metacharacters escaped (a literal `.` in a pattern matches\n * only `.`). Returns `undefined` when no rule matches — the caller applies\n * the config's top-level mode/depth.\n */\nexport function matchEdgePathRule(rules: EdgePathRule[], path: string): EdgePathRule | undefined {\n for (const rule of rules) {\n if (globToRegExp(rule.pattern).test(path)) return rule;\n }\n return undefined;\n}\n\nfunction globToRegExp(pattern: string): RegExp {\n const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&').replace(/\\*/g, '.*');\n return new RegExp(`^${escaped}$`, 'i');\n}\n\n/** Reset cache — for testing only. */\nexport function _resetEdgeConfigCache(): void {\n cache.clear();\n inflight.clear();\n}\n","/**\n * Maximal metadata capture — the shared, edge-safe sanitiser.\n *\n * AstraSync's thesis is total metadata capture: every header and connection\n * signal an inbound agent presents is a signal we want to keep. This module is\n * the ONE place that decides what is safe to store verbatim, what is a secret\n * to drop, and what credential headers reduce to a safe *format prefix* (a\n * platform signal, never the secret itself).\n *\n * It runs in three places that must agree byte-for-byte:\n * - the edge adapter (`@astrasyncai/adapter-lambda`) — the richest capture\n * point (full CloudFront header arrays),\n * - the SDK adapters (express / nextjs) — for SDK-only merchants with no edge,\n * - (indirectly) the backend, which stores whatever the above forward.\n *\n * Pure — no Node built-ins, no I/O — so it is safe in Lambda@Edge, the browser\n * build, and Deno. Capture is cheap: at the edge and SDK it is local string\n * work, and the backend stores it on a fire-and-forget event insert, so it adds\n * ZERO verify-access decision latency. Detection (which few signals imply which\n * vendor) is a separate, curated concern — see `platform-signatures.ts`.\n */\n\n/**\n * Version of the capture semantics (what is kept, dropped, reduced, or\n * derived — and under which key names).\n *\n * Capture semantics are FROZEN within a package major version: a given\n * `schemaVersion` always means the same field vocabulary and the same\n * keep/drop/reduce rules. The number bumps only on a SEMANTIC change to\n * capture (a renamed key, a changed reduction rule) — never for additive\n * signals, and never merely because the package version moved. To tell\n * builds apart, use the `sdkVersion` already present on the verify body;\n * `schemaVersion` answers the different question \"how do I interpret this\n * stored metadata?\".\n */\nexport const CAPTURE_SCHEMA_VERSION = 1;\n\n/**\n * The captured, sanitised view of an inbound agent's request metadata. Attached\n * to verify-access / beacon payloads as `callerMetadata.observedMetadata`.\n */\nexport interface ObservedMetadata {\n /** Header name → value, secrets removed, verbatim otherwise. */\n headers: Record<string, string>;\n /**\n * Safe key-format prefix of a credential header (e.g. `sk-ant-api03`,\n * `sk-proj`, `AIza`) — a platform signal, NEVER the secret. Absent if no\n * credential header was present or none matched a known format.\n */\n apiKeyFormat?: string;\n /**\n * The subset of `headers` that are known platform-signal headers\n * (`openai-organization`, `x-goog-user-project`, `anthropic-version`, …),\n * pulled out for convenient detection + display. Values are the same\n * sanitised strings as in `headers`.\n */\n platformHeaders?: Record<string, string>;\n /**\n * Connection-layer signals (IP, ASN, country, TLS version, HTTP version,\n * device class, TLS fingerprint). Edge adapters populate this from the\n * platform's native connection surface — the authoritative source. SDK\n * adapters populate it as a fallback via {@link deriveConnectionFromHeaders}\n * when a CDN in front of the merchant injected the equivalent headers;\n * absent when neither source had anything.\n */\n connection?: Record<string, string>;\n /**\n * Number of cookie pairs the caller sent. The `cookie` header VALUE is a\n * secret and is always dropped; the COUNT is a client-shape signal\n * (browsers carry cookies, most automation carries none) that would\n * otherwise be unobservable downstream. Absent when no cookie header\n * arrived.\n */\n cookieCount?: number;\n /**\n * Query-string parameter NAMES (deduped, lowercased) — values are NEVER\n * captured (they routinely carry OAuth codes, tokens, and PII, and no\n * deny-list is complete). Names alone fingerprint client shape. Populated\n * by the edge path, which sees the raw query string.\n */\n queryKeys?: string[];\n /**\n * Version of the capture semantics this object was produced under — see\n * {@link CAPTURE_SCHEMA_VERSION}. Optional for backward compatibility with\n * metadata captured before the field existed.\n */\n schemaVersion?: number;\n}\n\n/**\n * Result of sanitising a raw header map. `headers` is always present (possibly\n * empty); `apiKeyFormat` / `platformHeaders` only when a signal was found.\n */\nexport interface SanitizeHeadersResult {\n headers: Record<string, string>;\n apiKeyFormat?: string;\n platformHeaders?: Record<string, string>;\n /** Cookie-pair count; the cookie value itself is always dropped. */\n cookieCount?: number;\n}\n\n/**\n * Header names dropped entirely — genuine secrets or our own credentials that\n * describe the request's transport, not the agent. Matched case-insensitively\n * on the exact header name.\n */\nconst SECRET_HEADER_NAMES = new Set([\n 'cookie',\n 'set-cookie',\n 'x-csrf-token',\n 'proxy-authorization',\n 'x-astrasync-signature',\n 'x-astrasync-secret',\n 'x-hub-signature',\n 'x-hub-signature-256',\n // Short-lived verify dedupe token — must never persist in stored metadata.\n 'x-astra-verified-hop',\n]);\n\n/**\n * Header-name prefixes dropped entirely — our own credential / signing surface\n * (`x-astrasync-*`, `kya-*`) must never round-trip into stored metadata.\n */\nconst SECRET_HEADER_PREFIXES = ['x-astrasync-', 'kya-', 'kya_'];\n\n/**\n * Credential headers whose VALUE is a secret but whose FORMAT is a signal. We\n * keep the leading format prefix (up to the random tail) and drop the rest.\n */\nconst CREDENTIAL_HEADER_NAMES = new Set([\n 'authorization',\n 'x-api-key',\n 'x-goog-api-key',\n 'api-key',\n]);\n\n/**\n * Header names that carry a raw signature value (drop the value; the presence\n * is not worth a bloat risk). Matched as a suffix so `x-*-signature` variants\n * are covered without an exhaustive list.\n */\nfunction isSignatureHeader(name: string): boolean {\n return name === 'signature' || name.endsWith('-signature') || name.endsWith('-signature-256');\n}\n\n/**\n * Known platform-signal headers — pulled into `platformHeaders` for convenient\n * detection + display. Exact names plus a few prefixes (`x-goog-`,\n * `x-stainless-` — the OpenAI/Anthropic SDK client fingerprint headers).\n */\nconst PLATFORM_HEADER_NAMES = new Set([\n 'openai-organization',\n 'openai-project',\n 'openai-version',\n 'openai-processing-ms',\n 'anthropic-version',\n 'anthropic-beta',\n 'x-goog-user-project',\n 'x-goog-api-client',\n 'user-agent',\n 'x-agent-card-url',\n 'x-agent-provider',\n]);\n// `sec-ch-*` client hints are platform signals: Chromium forks (agentic\n// browsers included) often carry their real brand in `sec-ch-ua` even when\n// the UA string mimics stock Chrome.\nconst PLATFORM_HEADER_PREFIXES = [\n 'x-goog-',\n 'x-stainless-',\n 'x-anthropic-',\n 'x-openai-',\n 'sec-ch-',\n];\n\n/**\n * Known API-key format prefixes, longest-first so `sk-ant-api03` wins over\n * `sk-ant` and `sk-`. Each is the SAFE, non-secret leading token of a\n * credential; the random tail is never captured.\n */\nconst KEY_FORMAT_PREFIXES = [\n 'sk-ant-api03',\n 'sk-ant-api',\n 'sk-ant',\n 'sk-proj',\n 'sk-svcacct',\n 'sk-or-v1',\n 'sk-or',\n 'sk-lf',\n 'sk-',\n 'gsk_',\n 'aiza',\n 'ya29',\n 'ghp_',\n 'gho_',\n 'github_pat_',\n 'xai-',\n 'pplx-',\n 'r8_',\n 'hf_',\n 'astra-',\n 'astrae-',\n];\n\n/** Size caps — the only guard against jsonb bloat from a hostile POST. */\nexport const MAX_HEADERS = 64;\nexport const MAX_HEADER_VALUE_BYTES = 1024;\nexport const MAX_TOTAL_BYTES = 16 * 1024;\n\nfunction byteLength(s: string): number {\n // Edge-safe (no Buffer): count UTF-8 bytes without allocating a Buffer.\n let bytes = 0;\n for (let i = 0; i < s.length; i++) {\n const code = s.charCodeAt(i);\n if (code < 0x80) bytes += 1;\n else if (code < 0x800) bytes += 2;\n else if (code >= 0xd800 && code <= 0xdbff) {\n bytes += 4;\n i++; // surrogate pair\n } else bytes += 3;\n }\n return bytes;\n}\n\n/**\n * Extract the safe key-format prefix from a credential header value. Strips a\n * leading `Bearer ` / `Basic ` scheme, then returns the longest known prefix\n * that the (lowercased) value starts with. Returns undefined for opaque values\n * (e.g. a bare UUID token) so we never guess a format we don't recognise.\n */\nexport function extractApiKeyFormat(rawValue: string): string | undefined {\n if (!rawValue) return undefined;\n let value = rawValue.trim();\n const spaceIdx = value.indexOf(' ');\n if (spaceIdx > 0) {\n const scheme = value.slice(0, spaceIdx).toLowerCase();\n if (scheme === 'bearer' || scheme === 'basic' || scheme === 'token') {\n value = value.slice(spaceIdx + 1).trim();\n }\n }\n const lower = value.toLowerCase();\n for (const prefix of KEY_FORMAT_PREFIXES) {\n if (lower.startsWith(prefix)) {\n // Return the prefix as-declared in the list (canonical casing).\n return prefix;\n }\n }\n return undefined;\n}\n\nfunction isSecretHeader(name: string): boolean {\n if (SECRET_HEADER_NAMES.has(name)) return true;\n if (SECRET_HEADER_PREFIXES.some((p) => name.startsWith(p))) return true;\n if (isSignatureHeader(name)) return true;\n return false;\n}\n\nfunction isPlatformHeader(name: string): boolean {\n if (PLATFORM_HEADER_NAMES.has(name)) return true;\n return PLATFORM_HEADER_PREFIXES.some((p) => name.startsWith(p));\n}\n\n/**\n * Sanitise a raw header map for storage. Deny-lists genuine secrets, reduces\n * credential headers to a safe format prefix, keeps everything else verbatim,\n * and enforces the size caps that bound jsonb growth.\n *\n * Accepts any string→(string|string[]|undefined) map (Node's `req.headers`,\n * CloudFront's flattened headers, a plain object). Multi-value headers are\n * joined with `, ` per RFC 7230.\n */\nexport function sanitizeHeaders(\n raw: Record<string, string | string[] | undefined> | undefined | null\n): SanitizeHeadersResult {\n const headers: Record<string, string> = {};\n const platformHeaders: Record<string, string> = {};\n let apiKeyFormat: string | undefined;\n let cookieCount: number | undefined;\n let totalBytes = 0;\n let count = 0;\n\n if (!raw) return { headers };\n\n for (const rawName of Object.keys(raw)) {\n if (count >= MAX_HEADERS) break;\n const name = rawName.toLowerCase();\n const rawValue = raw[rawName];\n if (rawValue === undefined) continue;\n const joined = Array.isArray(rawValue) ? rawValue.join(', ') : String(rawValue);\n\n // Credential headers: capture the format prefix, drop the secret.\n if (CREDENTIAL_HEADER_NAMES.has(name)) {\n const fmt = extractApiKeyFormat(joined);\n if (fmt && !apiKeyFormat) apiKeyFormat = fmt;\n continue;\n }\n\n // Cookie: the value is a secret (dropped below), but the PAIR COUNT is a\n // client-shape signal worth keeping.\n if (name === 'cookie') {\n cookieCount = joined.split(';').filter((s) => s.trim().length > 0).length;\n }\n\n // Genuine secrets: drop entirely.\n if (isSecretHeader(name)) continue;\n\n // Everything else describing the agent: keep, bounded.\n let value = joined;\n if (byteLength(value) > MAX_HEADER_VALUE_BYTES) {\n value = value.slice(0, MAX_HEADER_VALUE_BYTES);\n }\n const entryBytes = byteLength(name) + byteLength(value);\n if (totalBytes + entryBytes > MAX_TOTAL_BYTES) continue;\n totalBytes += entryBytes;\n count++;\n headers[name] = value;\n if (isPlatformHeader(name)) platformHeaders[name] = value;\n }\n\n const result: SanitizeHeadersResult = { headers };\n if (apiKeyFormat) result.apiKeyFormat = apiKeyFormat;\n if (Object.keys(platformHeaders).length > 0) result.platformHeaders = platformHeaders;\n if (cookieCount !== undefined) result.cookieCount = cookieCount;\n return result;\n}\n\n/**\n * Pull the known platform-signal headers out of an ALREADY-sanitised header\n * map. `sanitizeHeaders` already computes this as a by-product; this standalone\n * form is exported for call-sites (edge, tests) that hold a sanitised map and\n * want only the platform subset. Never re-run over raw (unsanitised) headers.\n */\nexport function extractPlatformHeaders(\n sanitized: Record<string, string> | undefined | null\n): Record<string, string> {\n const out: Record<string, string> = {};\n if (!sanitized) return out;\n for (const name of Object.keys(sanitized)) {\n if (isPlatformHeader(name.toLowerCase())) out[name.toLowerCase()] = sanitized[name];\n }\n return out;\n}\n\n/**\n * Precedence-ordered CDN header sources for each derived `connection` key.\n * First present header wins; the special `x-forwarded-for` source takes the\n * LEFTMOST (client) entry of the comma-separated chain.\n */\nconst CONNECTION_HEADER_SOURCES: ReadonlyArray<readonly [key: string, headers: readonly string[]]> =\n [\n ['ip', ['cf-connecting-ip', 'fastly-client-ip', 'true-client-ip', 'x-real-ip']],\n [\n 'country',\n ['cf-ipcountry', 'x-vercel-ip-country', 'cloudfront-viewer-country', 'fastly-geo-country'],\n ],\n ['region', ['x-vercel-ip-country-region', 'cloudfront-viewer-country-region']],\n ['countryRegionName', ['cloudfront-viewer-country-region-name']],\n ['city', ['x-vercel-ip-city', 'cloudfront-viewer-city']],\n ['latitude', ['x-vercel-ip-latitude', 'cloudfront-viewer-latitude']],\n ['longitude', ['x-vercel-ip-longitude', 'cloudfront-viewer-longitude']],\n ['postalCode', ['x-vercel-ip-postal-code', 'cloudfront-viewer-postal-code']],\n ['asn', ['cloudfront-viewer-asn']],\n ['tlsVersion', ['cloudfront-viewer-tls']],\n ['httpVersion', ['cloudfront-viewer-http-version']],\n ['timeZone', ['x-vercel-ip-timezone', 'cloudfront-viewer-time-zone']],\n ['metroCode', ['cloudfront-viewer-metro-code']],\n // TLS fingerprints can only be computed where TLS terminates. When a CDN\n // terminates TLS in front of the merchant, its fingerprint headers ARE the\n // connection-layer truth — normalising them here is the permanent design.\n // CloudFront delivers JA3/JA4 only via an origin request policy and only\n // for HTTPS viewer connections.\n ['tlsFingerprint', ['cf-ja3-hash', 'cloudfront-viewer-ja3-fingerprint']],\n ['ja4', ['cf-ja4', 'cloudfront-viewer-ja4-fingerprint']],\n // Header-structure fingerprint: browser/SDK-distinctive header ordering.\n ['headerOrder', ['cloudfront-viewer-header-order']],\n ['headerCount', ['cloudfront-viewer-header-count']],\n ];\n\n/**\n * Backend bound: observedMetadata.connection values longer than this fail\n * the platform's zod parse outright (boundedStringRecord(32, 256)), so every\n * emitter truncates — headerOrder routinely exceeds it.\n */\nexport const MAX_CONNECTION_VALUE_CHARS = 256;\n\n/**\n * Derive the connection-layer block from CDN-injected request headers.\n *\n * When a merchant's SDK-gated origin sits behind a CDN (Cloudflare, Fastly,\n * Vercel, CloudFront), the CDN has already seen the connection layer and\n * injected it as headers. This promotes those headers to the same\n * `connection` keys the edge adapters populate natively, so SDK-only\n * deployments still get IP / geo / TLS attribution. Precedence per key:\n *\n * - `ip`: `cf-connecting-ip` > `fastly-client-ip` > `true-client-ip` >\n * `x-real-ip` > `cloudfront-viewer-address` (port stripped) > leftmost\n * `x-forwarded-for`\n * - `country`: `cf-ipcountry` > `x-vercel-ip-country` >\n * `cloudfront-viewer-country` > `fastly-geo-country`\n * - `region` / `city` / `timeZone`: Vercel then CloudFront viewer headers\n * - `countryRegionName` / `asn` / `tlsVersion` / `httpVersion` /\n * `metroCode` / `headerOrder` / `headerCount`: `cloudfront-viewer-*`\n * - `tlsFingerprint`: `cf-ja3-hash` > `cloudfront-viewer-ja3-fingerprint`\n * - `ja4`: `cf-ja4` > `cloudfront-viewer-ja4-fingerprint`\n *\n * All keys are additive under `schemaVersion` 1 (the frozen-capture doctrine\n * bumps only for changed semantics, never for additive signals). Values are\n * truncated to MAX_CONNECTION_VALUE_CHARS — the platform's hard bound.\n *\n * Edge adapters keep their richer native collectors — native platform\n * signals are authoritative; this header derivation is the SDK-level\n * fallback. Header names are matched case-insensitively. Returns undefined\n * when no source header is present, so the `connection` key is simply\n * omitted (matching edge behaviour).\n */\nexport function deriveConnectionFromHeaders(\n headers: Record<string, string> | undefined | null\n): Record<string, string> | undefined {\n if (!headers) return undefined;\n const lower: Record<string, string> = {};\n for (const name of Object.keys(headers)) {\n const value = headers[name];\n if (typeof value === 'string' && value.length > 0) lower[name.toLowerCase()] = value;\n }\n\n const connection: Record<string, string> = {};\n for (const [key, sources] of CONNECTION_HEADER_SOURCES) {\n for (const source of sources) {\n const value = lower[source]?.trim();\n if (value) {\n connection[key] = value.slice(0, MAX_CONNECTION_VALUE_CHARS);\n break;\n }\n }\n }\n // ip fallback 1: cloudfront-viewer-address arrives as ip:port — strip the\n // trailing port only (IPv6-safe), unlike the dedicated client-ip headers.\n // The port itself is kept as its own key: ephemeral-port patterns signal\n // NAT/proxy connection reuse.\n {\n const addr = lower['cloudfront-viewer-address']?.trim();\n const portMatch = addr?.match(/:(\\d+)$/);\n if (portMatch) connection.sourcePort = portMatch[1];\n if (!connection.ip && addr) connection.ip = addr.replace(/:\\d+$/, '');\n }\n // ip fallback 2: leftmost (client) hop of the x-forwarded-for chain.\n if (!connection.ip) {\n const xff = lower['x-forwarded-for'];\n const client = xff?.split(',')[0]?.trim();\n if (client) connection.ip = client;\n }\n // tlsCipher: CloudFront folds the cipher into the viewer-tls string\n // (`TLSv1.3:TLS_AES_128_GCM_SHA256:fullHandshake`). `tlsVersion` stays\n // verbatim (reducing it would be a semantic change → schema v2); the\n // cipher is pulled out additively so it is queryable on its own.\n if (!connection.tlsCipher) {\n const cipher = connection.tlsVersion?.split(':')[1];\n if (cipher) connection.tlsCipher = cipher;\n }\n\n return Object.keys(connection).length > 0 ? connection : undefined;\n}\n\n/**\n * The FULL metadata capture for one request at an SDK adapter (express /\n * nextjs / mcp): sanitised headers, the safe credential format prefix, the\n * platform-signal subset, the CDN-derived connection block, and the capture\n * schema version. This is the ONE builder all SDK adapters share, so their\n * verify-access bodies agree byte-for-byte.\n *\n * Connection derivation runs over the RAW header map (pre-cap) — the size\n * caps guard storage growth and must never hide a geo/IP header that\n * happened to arrive late in an oversized map.\n */\nexport function buildSdkObservedMetadata(\n rawHeaders: Record<string, string | string[] | undefined> | undefined | null\n): ObservedMetadata {\n const { headers, apiKeyFormat, platformHeaders, cookieCount } = sanitizeHeaders(rawHeaders);\n const flat: Record<string, string> = {};\n if (rawHeaders) {\n for (const name of Object.keys(rawHeaders)) {\n const value = rawHeaders[name];\n if (value === undefined) continue;\n flat[name.toLowerCase()] = Array.isArray(value) ? value.join(', ') : String(value);\n }\n }\n const connection = deriveConnectionFromHeaders(flat);\n return {\n headers,\n ...(apiKeyFormat && { apiKeyFormat }),\n ...(platformHeaders && { platformHeaders }),\n ...(connection && { connection }),\n ...(cookieCount !== undefined && { cookieCount }),\n schemaVersion: CAPTURE_SCHEMA_VERSION,\n };\n}\n","/**\n * Platform-agent fingerprint signatures — the shared registry of known\n * platform-agent UA / agent-card patterns (Claude / ChatGPT / Gemini /\n * Cursor / Goose).\n *\n * Single source of truth, lifted verbatim from the backend's\n * `platform-agent-detector.service` (which now imports detection from\n * here): the backend's verify-access anonymous handler and the edge\n * adapter (`@astrasyncai/adapter-lambda`) must classify identically or\n * the three-tier visibility numbers drift between capture points.\n *\n * Pure regex — no Node built-ins, edge-safe. Detection is regex-only for\n * v2.9 — TLS fingerprinting / behavioural signatures are deferred.\n */\n\nexport type PlatformAgentVendor =\n | 'claude'\n | 'chatgpt'\n | 'gemini'\n | 'cursor'\n | 'goose'\n | 'perplexity'\n | 'chatgpt-atlas'\n | 'perplexity-comet'\n | 'astrasync-sdk'\n | 'unknown';\n\nexport interface PlatformFingerprint {\n vendor: PlatformAgentVendor;\n /** A stable identifier used as the orphan-agent dedup key. */\n fingerprintKey: string;\n /** Human-readable name surfaced in the admin panel. */\n displayName: string;\n}\n\nexport interface PlatformDetectionInput {\n userAgent?: string;\n agentCardUrl?: string;\n /**\n * A safe API-key format prefix observed on the caller's\n * credential header (e.g. `sk-ant-api03`, `sk-proj`, `aiza`). A strong\n * platform signal; never the secret. Matched against `apiKeyFormatPatterns`.\n */\n apiKeyFormat?: string;\n /**\n * The sanitised platform-signal headers (lowercased names →\n * values), e.g. `openai-organization`, `x-goog-user-project`. Matched\n * against `headerPatterns` (which test on `name` and `name: value`).\n */\n platformHeaders?: Record<string, string>;\n /**\n * The caller's JA4 TLS-client fingerprint (from the connection capture).\n * Matched against `ja4Patterns`. A JA4 identifies the client TLS stack,\n * so signatures should pair it with other evidence when attributing a\n * vendor.\n */\n ja4?: string;\n /**\n * The caller's origin ASN (from the connection capture). Matched against\n * `asnList` by exact membership. An ASN alone attributes an entire cloud\n * provider — registry validation rejects ASN-only signatures.\n */\n asn?: string;\n}\n\n/**\n * A signature definition, generic over the vendor key. The seed constant\n * below uses the closed `PlatformAgentVendor` union; DB-promoted signatures\n * (backend dynamic registry, console round) carry arbitrary string vendors —\n * `matchPlatformSignature` accepts both.\n */\nexport interface PlatformSignatureDef<V extends string = string> {\n vendor: V;\n displayName: string;\n uaPatterns?: RegExp[];\n agentCardPatterns?: RegExp[];\n /**\n * Patterns tested against an observed API-key format prefix\n * (e.g. `/^sk-ant/i` → claude). A credential-header format is a stronger\n * platform signal than a spoofable User-Agent.\n */\n apiKeyFormatPatterns?: RegExp[];\n /**\n * Patterns tested against each observed platform-signal\n * header, as both `name` and `name: value` (so `/openai-organization/i` and\n * `/x-goog-user-project/i` match on presence).\n */\n headerPatterns?: RegExp[];\n /** Patterns tested against the observed JA4 TLS-client fingerprint. */\n ja4Patterns?: RegExp[];\n /** Exact ASN strings this signature matches (never regex). */\n asnList?: string[];\n}\n\n/**\n * A fingerprint whose vendor may be a dynamically-promoted (non-seed) key.\n * Structurally a superset of `PlatformFingerprint`.\n */\nexport interface DynamicPlatformFingerprint {\n vendor: string;\n fingerprintKey: string;\n displayName: string;\n}\n\n/**\n * Registry of known platform-agent signatures. Order matters — first match wins.\n *\n * Patterns are intentionally permissive (case-insensitive substring match) since\n * platform UA strings drift between versions. False positives are tolerable —\n * the orphan record is informational, not enforcement.\n */\nexport const PLATFORM_AGENT_SIGNATURES: ReadonlyArray<PlatformSignatureDef<PlatformAgentVendor>> = [\n {\n vendor: 'claude',\n displayName: 'Anthropic Claude',\n uaPatterns: [/claude/i, /anthropic/i],\n agentCardPatterns: [/anthropic\\.com/i, /claude\\.ai/i],\n apiKeyFormatPatterns: [/^sk-ant/i],\n headerPatterns: [/^anthropic-version/i, /^anthropic-beta/i, /^x-anthropic-/i],\n },\n {\n vendor: 'chatgpt',\n displayName: 'OpenAI ChatGPT',\n uaPatterns: [/chatgpt/i, /openai/i, /gpt-?\\d/i],\n agentCardPatterns: [/openai\\.com/i, /chatgpt\\.com/i],\n apiKeyFormatPatterns: [/^sk-proj/i, /^sk-svcacct/i],\n headerPatterns: [/^openai-organization/i, /^openai-project/i, /^openai-version/i],\n },\n {\n vendor: 'gemini',\n displayName: 'Google Gemini',\n uaPatterns: [/gemini/i, /google-gemini/i, /bard/i],\n agentCardPatterns: [/gemini\\.google\\.com/i, /ai\\.google\\.dev/i],\n apiKeyFormatPatterns: [/^aiza/i],\n headerPatterns: [/^x-goog-user-project/i, /^x-goog-api-client/i],\n },\n {\n vendor: 'cursor',\n displayName: 'Cursor',\n uaPatterns: [/cursor/i],\n agentCardPatterns: [/cursor\\.sh/i, /cursor\\.com/i],\n },\n {\n vendor: 'goose',\n displayName: 'Block Goose',\n uaPatterns: [/goose/i, /block-goose/i],\n agentCardPatterns: [/block\\.xyz\\/goose/i, /goose\\.tools/i],\n },\n {\n vendor: 'perplexity',\n displayName: 'Perplexity',\n uaPatterns: [/perplexity/i],\n agentCardPatterns: [/perplexity\\.ai/i],\n apiKeyFormatPatterns: [/^pplx-/i],\n },\n // Agentic browsers — versioned-token patterns ONLY (a stock Chrome UA must\n // never match). Distinct vendor keys (not 'chatgpt'/'perplexity'): the\n // browser product is a different surface than the assistant service, and\n // the DB registry mirrors one row per vendor. These sit after the primary\n // vendor entries so a UA carrying an explicit vendor token keeps its\n // primary attribution; a browser-shaped UA with the agentic token is\n // caught here BEFORE classify's human tier, which is what makes these\n // visits observable at all. Token drift is real (some builds mimic Chrome\n // outright) — re-verify against captured events when a new browser ships,\n // and check `sec-ch-ua` platformHeaders for the real brand.\n {\n vendor: 'chatgpt-atlas',\n displayName: 'ChatGPT Atlas browser',\n uaPatterns: [/\\batlas\\/\\d/i],\n headerPatterns: [/^sec-ch-ua: .*atlas/i],\n },\n {\n vendor: 'perplexity-comet',\n displayName: 'Perplexity Comet browser',\n uaPatterns: [/\\bcomet\\/\\d/i],\n headerPatterns: [/^sec-ch-ua: .*comet/i],\n },\n // Our own SDK self-identifies (sdkFetch stamps this UA) — first-party\n // traffic must never pollute the unknown/anonymous pool it exists to audit.\n {\n vendor: 'astrasync-sdk',\n displayName: 'AstraSync SDK',\n uaPatterns: [/^astrasync-sdk\\//i],\n },\n];\n\n/**\n * Generic first-match-wins matcher over an arbitrary signature set. The\n * backend's dynamic registry merges the seed constant with DB-promoted\n * signatures and calls this — ONE matching implementation everywhere\n * (fingerprint-key rule included: vendor + lowercased UA basename before\n * the first space/slash, falling back to the agent-card host).\n */\nexport function matchPlatformSignature(\n signatures: ReadonlyArray<PlatformSignatureDef>,\n input: PlatformDetectionInput\n): DynamicPlatformFingerprint | undefined {\n const ua = input.userAgent ?? '';\n const cardUrl = input.agentCardUrl ?? '';\n const apiKeyFormat = input.apiKeyFormat ?? '';\n const ja4 = input.ja4 ?? '';\n const asn = input.asn ?? '';\n // Flatten platform headers to `name` and `name: value` lines for matching.\n const headerLines: string[] = [];\n if (input.platformHeaders) {\n for (const [name, value] of Object.entries(input.platformHeaders)) {\n headerLines.push(name, `${name}: ${value}`);\n }\n }\n\n for (const sig of signatures) {\n const uaMatch = sig.uaPatterns?.some((p) => p.test(ua));\n const cardMatch = sig.agentCardPatterns?.some((p) => p.test(cardUrl));\n const keyMatch =\n apiKeyFormat.length > 0 && sig.apiKeyFormatPatterns?.some((p) => p.test(apiKeyFormat));\n const headerMatch =\n headerLines.length > 0 &&\n sig.headerPatterns?.some((p) => headerLines.some((line) => p.test(line)));\n const ja4Match = ja4.length > 0 && sig.ja4Patterns?.some((p) => p.test(ja4));\n const asnMatch = asn.length > 0 && sig.asnList?.includes(asn);\n if (uaMatch || cardMatch || keyMatch || headerMatch || ja4Match || asnMatch) {\n const uaBase = ua.split(/[\\s/]/)[0]?.toLowerCase() ?? '';\n const cardHost = (() => {\n try {\n return cardUrl ? new URL(cardUrl).host : '';\n } catch {\n return '';\n }\n })();\n // Prefer a UA/card basename for the dedup key; fall back to the\n // credential format, then the connection fingerprint (still stable\n // per-vendor keys) when only a key/header/ja4/asn matched.\n const keyBasis =\n uaBase || cardHost || apiKeyFormat || ja4 || (asn && `asn${asn}`) || 'unknown';\n return {\n vendor: sig.vendor,\n fingerprintKey: `${sig.vendor}:${keyBasis}`,\n displayName: sig.displayName,\n };\n }\n }\n\n return undefined;\n}\n\n/**\n * Inspect caller metadata for a known SEED platform-agent fingerprint.\n * Returns undefined if no signature matches. (Backends with the dynamic\n * registry should call `matchPlatformSignature` over their merged set\n * instead — same semantics, live signature additions included.)\n */\nexport function detectPlatformFingerprint(\n input: PlatformDetectionInput\n): PlatformFingerprint | undefined {\n // Seed vendors are all members of the PlatformAgentVendor union, so the\n // narrowing cast is sound by construction.\n return matchPlatformSignature(PLATFORM_AGENT_SIGNATURES, input) as\n | PlatformFingerprint\n | undefined;\n}\n","/**\n * AstraSync Universal Verification Gateway — Trust Level helpers.\n *\n * SDK 5.0.0: the `accessLevel` band (`none`/`restricted`/`read-only`/`standard`/\n * `full`/`internal`) was removed entirely — it never gated the access decision\n * (the server does, from a verified ID + runtime challenge + PDLSS match + trust\n * score). What remains here is the coarse trust-level badge derived from the\n * numeric trust score, used only for display.\n */\n\nimport type { TrustLevel } from './types';\n\n/**\n * Trust level score ranges\n */\nexport const TRUST_LEVEL_RANGES: Record<TrustLevel, { min: number; max: number }> = {\n BRONZE: { min: 0, max: 39 },\n SILVER: { min: 40, max: 59 },\n GOLD: { min: 60, max: 79 },\n PLATINUM: { min: 80, max: 100 },\n};\n\n/**\n * Determine trust level from score\n */\nexport function getTrustLevel(score: number): TrustLevel {\n if (score >= 80) return 'PLATINUM';\n if (score >= 60) return 'GOLD';\n if (score >= 40) return 'SILVER';\n return 'BRONZE';\n}\n","import { sdkFetch } from './http';\n/**\n * SDK-side discovery of canonical platform URLs via `/.well-known/agentic-commerce`.\n *\n * Fire-and-forget pre-fetch at middleware creation; first verify() awaits\n * the in-flight promise if it hasn't resolved. 60-minute TTL with\n * stale-while-revalidate background refresh.\n */\n\nexport interface WellKnownAgenticCommerce {\n registrationUrl: string;\n documentationUrl: string;\n verifyAccessUrl: string;\n /** 5.1.0: hosted AstraSync MCP bridge endpoint (absent on self-hosted backends). */\n mcpEndpoint?: string;\n /** 5.1.0: bridge connector-discovery doc (absent on self-hosted backends). */\n mcpDiscoveryUrl?: string;\n}\n\ninterface CacheEntry {\n data: WellKnownAgenticCommerce;\n fetchedAt: number;\n}\n\nconst CACHE_TTL_MS = 60 * 60 * 1000; // 60 minutes\n\nconst cache = new Map<string, CacheEntry>();\nconst inflight = new Map<string, Promise<WellKnownAgenticCommerce>>();\n\nfunction wellKnownUrl(apiBaseUrl: string): string {\n // apiBaseUrl is typically 'https://astrasync.ai/api' — strip the /api suffix\n // to get the platform root, then append /.well-known/agentic-commerce.\n const base = apiBaseUrl.replace(/\\/api\\/?$/, '');\n return `${base}/.well-known/agentic-commerce`;\n}\n\nasync function fetchWellKnown(apiBaseUrl: string): Promise<WellKnownAgenticCommerce> {\n const url = wellKnownUrl(apiBaseUrl);\n const response = await sdkFetch(url, {\n method: 'GET',\n headers: { Accept: 'application/json' },\n signal: AbortSignal.timeout(5000),\n });\n if (!response.ok) {\n throw new Error(\n `AstraSync platform must expose /.well-known/agentic-commerce; ` +\n `got ${response.status} from ${url}. SDK cannot initialise without it.`\n );\n }\n const data = (await response.json()) as Record<string, unknown>;\n if (!data.registrationUrl || !data.documentationUrl || !data.verifyAccessUrl) {\n throw new Error(\n `/.well-known/agentic-commerce response missing required fields ` +\n `(registrationUrl, documentationUrl, verifyAccessUrl).`\n );\n }\n return data as unknown as WellKnownAgenticCommerce;\n}\n\n/**\n * Start a background fetch. Returns the promise for callers that need\n * to await it (first verify() call).\n */\nexport function prefetchWellKnown(apiBaseUrl: string): Promise<WellKnownAgenticCommerce> {\n const existing = inflight.get(apiBaseUrl);\n if (existing) return existing;\n\n const promise = fetchWellKnown(apiBaseUrl)\n .then((data) => {\n cache.set(apiBaseUrl, { data, fetchedAt: Date.now() });\n inflight.delete(apiBaseUrl);\n return data;\n })\n .catch((err) => {\n inflight.delete(apiBaseUrl);\n throw err;\n });\n\n inflight.set(apiBaseUrl, promise);\n return promise;\n}\n\n/**\n * Get cached well-known URLs. If stale, triggers a background refresh\n * and returns stale data (stale-while-revalidate). If no cache exists,\n * awaits the in-flight fetch or starts a new one.\n */\nexport async function getWellKnownUrls(apiBaseUrl: string): Promise<WellKnownAgenticCommerce> {\n const entry = cache.get(apiBaseUrl);\n\n if (entry) {\n if (Date.now() - entry.fetchedAt > CACHE_TTL_MS) {\n // Stale — trigger background refresh, return stale data\n prefetchWellKnown(apiBaseUrl).catch(() => {\n // Background refresh failed — stale data remains until next request\n });\n }\n return entry.data;\n }\n\n // No cache — must await\n const pending = inflight.get(apiBaseUrl);\n if (pending) return pending;\n\n return prefetchWellKnown(apiBaseUrl);\n}\n\n/**\n * Synchronous cache read — returns cached URLs or undefined.\n * Never triggers a fetch. Used by verify() to avoid extra HTTP calls\n * in the hot path; adapters are responsible for prefetching.\n */\nexport function getCachedWellKnownUrls(apiBaseUrl: string): WellKnownAgenticCommerce | undefined {\n return cache.get(apiBaseUrl)?.data;\n}\n\n/** Reset cache — for testing only. */\nexport function _resetWellKnownCache(): void {\n cache.clear();\n inflight.clear();\n}\n","/**\n * AstraSync Universal Verification Gateway - Core Verification Logic\n *\n * This module handles the core verification logic, calling the AstraSync API\n * and processing the response into a standardized VerificationResult.\n */\n\nimport { sdkFetch } from './http';\nimport type {\n GatewayConfig,\n AgentCredentials,\n VerificationRequest,\n VerificationResult,\n VerifiedAgent,\n VerifiedDeveloper,\n VerifiedOrganization,\n GuidanceInfo,\n EnhancedVerificationResult,\n TokenGuidance,\n RuntimeChallengeResult,\n StepUpApprovalInfo,\n SettlementOutcomeInfo,\n SettlementArtifact,\n AttemptReport,\n} from './types';\nimport { getTrustLevel } from './trust-levels';\nimport type { ObservedMetadata } from './metadata-capture';\nimport { SDK_VERSION } from './version';\nimport { getCachedWellKnownUrls, type WellKnownAgenticCommerce } from './well-known';\n\n/**\n * Default configuration values\n *\n * apiBaseUrl matches the OpenAPI authoritative server (https://astrasync.ai/api\n * for prod, https://staging.astrasync.ai/api for staging). Always include the\n * /api path prefix when overriding — registration / docs URLs are derived by\n * stripping it.\n */\nconst DEFAULT_CONFIG: Partial<GatewayConfig> = {\n apiBaseUrl: 'https://astrasync.ai/api',\n // minTrustScore + minTrustScoreForFull deprecated in v2.3.0 — server decides.\n // cacheTtl deliberately unset. When undefined, cacheResult applies the 60s\n // default; the caller's explicit value is honoured for cacheable results.\n // Denials and step-up escalations are NEVER cached (3.6.0) regardless of\n // cacheTtl. Set cacheTtl: 0 to disable caching entirely.\n debug: false,\n};\n\n/**\n * Init self-test state. Fires once per process on first verify() call to warn\n * if apiBaseUrl is pointing at the wrong host (e.g. a marketing site that\n * 200s with text/html instead of the API).\n */\nlet initCheckPerformed = false;\n\n/** Test-only: re-arm the one-time init self-check. */\nexport function _resetInitCheck(): void {\n initCheckPerformed = false;\n}\n\n/** One-shot guard for v2.3.0 deprecation warning. */\nlet deprecationWarningShown = false;\n\nasync function performInitCheck(\n apiBaseUrl: string,\n debug?: boolean,\n strictInit?: boolean,\n apiKey?: string\n): Promise<void> {\n initCheckPerformed = true;\n try {\n const probeUrl = `${apiBaseUrl}/agents/verify-access`;\n // HEAD mirrors GET semantics (running the full request pipeline without a\n // body) so the response carries the same content-type the marketing 404\n // would return. OPTIONS often gets short-circuited by CORS-preflight\n // handlers and returns no content-type, defeating the check.\n const response = await sdkFetch(probeUrl, { method: 'HEAD' });\n const contentType = response.headers.get('content-type') ?? '';\n if (contentType.startsWith('text/html')) {\n const message =\n `[VerificationGateway] apiBaseUrl '${apiBaseUrl}' returned HTML (content-type: ${contentType}). ` +\n `This usually means apiBaseUrl is pointing at a marketing site instead of the API. ` +\n `Expected: 'https://astrasync.ai/api' (prod) or 'https://staging.astrasync.ai/api' (staging).`;\n // Audit F-A6-33: when strictInit is set, throw on misconfig instead\n // of warning + continuing. Recurring footgun per\n // `[[feedback_astrasync_api_url_canonical]]` — silent warn lets\n // misconfigured prod deploys ship with all verify-access calls\n // silently failing.\n if (strictInit) {\n throw new Error(`${message} (strictInit=true)`);\n }\n console.warn(`${message} Set disableInitChecks: true on GatewayConfig to silence.`);\n } else if (debug) {\n console.log(\n `[VerificationGateway] init check passed for ${apiBaseUrl} (content-type: ${contentType})`\n );\n }\n\n // 4.0.0: key liveness probe. A dead API key otherwise surfaces only\n // per-request as inbound agents get turned away — the operator should\n // learn at deploy time. 404 = older backend without self-check: silent.\n if (apiKey) {\n const selfCheck = await sdkFetch(`${apiBaseUrl}/agents/verify-access/self-check`, {\n headers: { Authorization: `Bearer ${apiKey}` },\n });\n if (selfCheck.status === 401) {\n const body = (await selfCheck.json().catch(() => ({}))) as {\n code?: string;\n message?: string;\n remediation?: { manageUrl?: string };\n };\n const message =\n `[VerificationGateway] the configured AstraSync API key was REJECTED at startup ` +\n `(${body.code ?? 'api_key_invalid'}: ${body.message ?? 'invalid key'}). Every inbound agent ` +\n `will be turned away until the key is rotated` +\n (body.remediation?.manageUrl ? ` at ${body.remediation.manageUrl}` : '') +\n `.`;\n if (strictInit) {\n throw new Error(`${message} (strictInit=true)`);\n }\n console.error(message);\n } else if (selfCheck.ok) {\n const body = (await selfCheck.json().catch(() => ({}))) as {\n daysToExpiry?: number | null;\n };\n if (typeof body.daysToExpiry === 'number' && body.daysToExpiry <= 7) {\n console.warn(\n `[VerificationGateway] the configured AstraSync API key expires in ${body.daysToExpiry} day(s) — ` +\n `rotate it at Settings → Developer Tools before integrations start failing.`\n );\n } else if (debug) {\n console.log('[VerificationGateway] API key self-check passed');\n }\n }\n }\n } catch (err) {\n if (strictInit) {\n // strict mode propagates init failures so callers get a clear,\n // synchronous \"your config is broken\" signal at startup.\n throw err;\n }\n if (debug) {\n console.log(`[VerificationGateway] init check failed (non-blocking): ${String(err)}`);\n }\n }\n}\n\n/**\n * Simple in-memory cache for verification results\n */\nconst verificationCache = new Map<string, { result: VerificationResult; expiresAt: number }>();\n\n/**\n * Generate cache key from the full request shape.\n *\n * Historically the key was credentials-only (`astraId-apiKey-jwt`),\n * which silently returned the cached result of a prior call even when the\n * subsequent call's purpose/action/counterparty/etc. differed. That was a\n * security gap — a warm cache could serve an allow verdict for a purpose the\n * agent hadn't actually been authorised for. Key now includes every field\n * that affects the backend verdict.\n *\n * MAINTAIN: when adding a field to VerificationRequest that affects the\n * backend verdict, add it to this key. Fields that don't affect verdict\n * (e.g. requestId, timestamps, sdkVersion) don't belong here — including\n * them would needlessly thrash the cache for repeated identical requests.\n *\n * 3.12.0 (Trust Record): `attemptId` and `considerationSet` are\n * deliberately EXCLUDED — like `callerMetadata.observedMetadata` they are\n * observational pass-through that never affects the verdict, and keying on\n * a per-attempt id would defeat verdict caching entirely. Cache hits get\n * their attemptId rewritten in verify() instead (never leak a prior\n * attempt's id from a cached result).\n */\nfunction getCacheKey(request: VerificationRequest, counterpartyId?: string): string {\n const c = request.credentials;\n return [\n c.astraId || '',\n c.apiKey || '',\n c.jwt || '',\n request.purpose || '',\n request.action || '',\n request.resourceType || '',\n request.resource || '',\n request.jurisdiction || '',\n request.transactionValue ?? '',\n request.currency || '',\n // SECURITY (cross-merchant cache leak): the merchant identity is sent via\n // `config.counterpartyId`, NOT on the request, so it was previously absent\n // from the key — two verifies for the SAME agent/purpose/action/value but\n // DIFFERENT merchants collided, and a grant at a permissive merchant (low\n // trust floor) was served for a stricter one. Same bug class as the\n // duration omission (F-A1-07). counterpartyId affects the backend verdict\n // (trust floor / per-route policy), so it MUST key the cache.\n counterpartyId || '',\n request.counterpartyUrl || '',\n request.counterpartyType || '',\n request.isSubAgentRequest ? '1' : '0',\n request.parentAgentId || '',\n request.subAgentDepth ?? '',\n // Audit F-A1-07: previously-missing dimensions that DO affect the\n // backend verdict. Without these, two requests with different\n // durations (e.g. 60s vs 86400s) collided on the same cache key and\n // the shorter-duration allow served the longer-duration request.\n request.durationRequired ?? '',\n request.invocationProtocol || '',\n request.enableRuntimeChallenge ? '1' : '0',\n // callerMetadata fields contribute to risk model; include the ones\n // backend reads. sourceIp/userAgent/forwardedFor change per-request\n // so their inclusion effectively forces a re-check for any varying\n // client (the right behavior — IP-driven anomaly scoring shouldn't\n // be cached across IPs).\n request.callerMetadata?.sourceIp || '',\n request.callerMetadata?.userAgent || '',\n request.callerMetadata?.forwardedFor || '',\n request.callerMetadata?.agentCardUrl || '',\n // UAT2 Bug B (5.4.1): the commerce phase and cart identity DO affect the\n // backend verdict — the confirm leg is the ONLY leg that may execute\n // first-party settlement. Without these, a confirm within the cache TTL of\n // its start_checkout quote was served the cached quote-leg grant (no\n // settlementOutcome) and never reached the backend. Same F-A1-07 bug class.\n request.commercePhase || '',\n request.checkoutSessionId || '',\n ].join('|');\n}\n\n/**\n * Check if cached result is still valid\n */\nfunction getCachedResult(\n request: VerificationRequest,\n counterpartyId?: string\n): VerificationResult | null {\n const key = getCacheKey(request, counterpartyId);\n const cached = verificationCache.get(key);\n\n if (cached && cached.expiresAt > Date.now()) {\n return cached.result;\n }\n\n if (cached) {\n verificationCache.delete(key);\n }\n\n return null;\n}\n\n/**\n * Cache a verification result.\n *\n * 3.6.0: uniform 60s default. The earlier step-up TTL split (300s for\n * step-up verdicts) is gone — step-up verdicts are no longer cached AT ALL\n * (see the write predicate in verify()): a cached step_up_required result\n * carries a pollUrl that goes stale (consumed/expired) and, worse, keeps\n * denying retries that the owner has already approved. When `configuredTtl`\n * is set (truthy positive number), it's honoured for cacheable results.\n */\nconst DEFAULT_CACHE_TTL_SECONDS = 60;\n\nfunction cacheResult(\n request: VerificationRequest,\n result: VerificationResult,\n configuredTtl: number | undefined,\n counterpartyId?: string\n): void {\n const ttlSeconds = configuredTtl && configuredTtl > 0 ? configuredTtl : DEFAULT_CACHE_TTL_SECONDS;\n const key = getCacheKey(request, counterpartyId);\n verificationCache.set(key, {\n result,\n expiresAt: Date.now() + ttlSeconds * 1000,\n });\n}\n\n/**\n * Clear the verification cache\n */\nexport function clearCache(): void {\n verificationCache.clear();\n}\n\n/**\n * Extract agent credentials from various sources\n */\nexport function extractCredentials(\n headers: Record<string, string | string[] | undefined>,\n query?: Record<string, string | undefined>\n): AgentCredentials {\n const credentials: AgentCredentials = {};\n\n // Audit F-A1-12: ASTRA-ID shape validation. Accept only the canonical\n // pattern (ASTRA-/ASTRAE- prefix + 1-64 url-safe chars) to prevent CRLF\n // header injection or downstream interpolation surprises. Reject otherwise.\n const ASTRA_ID_PATTERN = /^ASTRAE?-[A-Za-z0-9_-]{1,64}$/;\n\n // Check for ASTRA-ID in headers (case-insensitive). Accepts the historical\n // X-Astra-Id name plus the X-Astra-AgentId / x-astra-agent-id alias the\n // partner asked for in #9a — both surface the same field.\n const astraIdHeader =\n headers['x-astra-id'] ||\n headers['X-Astra-Id'] ||\n headers['X-ASTRA-ID'] ||\n headers['x-astra-agentid'] ||\n headers['X-Astra-AgentId'] ||\n headers['x-astra-agent-id'] ||\n headers['X-Astra-Agent-Id'] ||\n headers['X-ASTRA-AGENT-ID'];\n if (astraIdHeader) {\n // Audit F-A1-11: guard array-confusion. If multiple X-Astra-Id headers\n // were sent (Express collapses to comma-joined string on most paths),\n // take only the first canonical-shaped one.\n const raw = Array.isArray(astraIdHeader)\n ? astraIdHeader[0]\n : typeof astraIdHeader === 'string'\n ? astraIdHeader\n : undefined;\n if (typeof raw === 'string' && ASTRA_ID_PATTERN.test(raw)) {\n credentials.astraId = raw;\n }\n }\n\n // Check for API key in headers\n const apiKeyHeader = headers['x-api-key'] || headers['X-Api-Key'] || headers['X-API-KEY'];\n if (apiKeyHeader) {\n credentials.apiKey = Array.isArray(apiKeyHeader) ? apiKeyHeader[0] : apiKeyHeader;\n }\n\n // Check Authorization header for Bearer token.\n // Audit F-A1-11: defensive type guard — Array.isArray gives a non-string,\n // and Express path quirks can produce undefined despite the truthy check.\n const authHeader = headers['authorization'] || headers['Authorization'];\n if (authHeader) {\n const authValue = Array.isArray(authHeader) ? authHeader[0] : authHeader;\n if (typeof authValue === 'string') {\n credentials.authorizationHeader = authValue;\n if (authValue.startsWith('Bearer ')) {\n credentials.jwt = authValue.slice(7);\n }\n }\n }\n\n // Check query parameters as fallback\n if (query) {\n if (query.astraId && !credentials.astraId) {\n credentials.astraId = query.astraId;\n }\n if (query.apiKey && !credentials.apiKey) {\n credentials.apiKey = query.apiKey;\n }\n }\n\n return credentials;\n}\n\n/**\n * Check if credentials are present\n */\nexport function hasCredentials(credentials: AgentCredentials): boolean {\n return !!(credentials.astraId || credentials.apiKey || credentials.jwt);\n}\n\n/**\n * Source of a synthesised guidance response. The sources are split — the\n * `'no_credentials'` shape is the original (caller has no AstraSync\n * credentials, suggest registration). The `'api_error'` shape is for when\n * the verify-access HTTP call itself failed (5xx, network, etc.) — DON'T\n * tell a verified-but-currently-blocked partner to \"register your agent\".\n *\n * 4.0.0 adds `'merchant_misconfig'`: the backend rejected THIS INTEGRATION'S\n * own API key (401 api_key_revoked/expired/invalid). Neither the agent's\n * fault nor a platform outage — retrying won't help, and the inbound agent\n * deserves to know the site operator's integration is broken (the\n * gadget-emporium failure mode: a rotated key silently 401ing every\n * credentialed agent for days).\n */\ntype GuidanceSource = 'no_credentials' | 'api_error' | 'merchant_misconfig';\n\n/**\n * MCP-connector steering (5.1.0). Present only when the backend's well-known\n * doc advertises a hosted bridge. The copy must directly counter the observed\n * model refusal (\"go register manually on the dashboard\"): registration via\n * the connector is the agent's own next action, with the human approval built\n * into the flow.\n */\nfunction mcpGuidance(urls?: WellKnownAgenticCommerce): GuidanceInfo['mcp'] {\n if (!urls?.mcpEndpoint) return undefined;\n return {\n endpoint: urls.mcpEndpoint,\n discoveryUrl: urls.mcpDiscoveryUrl,\n message:\n 'If you are operating inside an MCP-capable host (Claude, ChatGPT, Cursor, or any MCP client), ' +\n 'add the AstraSync MCP connector instead of integrating these URLs by hand: registration through ' +\n 'the connector is KEYLESS and HUMAN-APPROVED — your human approves in an in-chat card, and you ' +\n 'never see, hold, or transmit an API key, password, or private key.',\n };\n}\n\n/**\n * Create guidance response for unverified agents or for API-error fallback.\n *\n * The source is split so the `register your agent` template\n * doesn't fire on transient backend failures. Also threads `correlationId`\n * through so adapter `onDenied` handlers can surface it on the merchant's\n * response body for log correlation.\n */\nfunction createGuidanceResponse(\n _config: GatewayConfig,\n reason?: string,\n options: {\n source?: GuidanceSource;\n correlationId?: string;\n /** 3.12.0 (Trust Record): server-echoed attempt handle, threaded like correlationId. */\n attemptId?: string;\n urls?: WellKnownAgenticCommerce;\n /** 4.0.0: backend-provided remediation URLs for the merchant (misconfig source). */\n remediation?: { docsUrl?: string; manageUrl?: string };\n } = {}\n): VerificationResult {\n const source = options.source ?? 'no_credentials';\n const isApiError = source === 'api_error';\n const isMisconfig = source === 'merchant_misconfig';\n const urls = options.urls;\n\n const guidance: GuidanceInfo = isMisconfig\n ? {\n message:\n \"This site's AstraSync integration is misconfigured (its API key was revoked, expired, or rotated). \" +\n 'Your identity and the AstraSync platform are fine — contact the site operator. Retrying will not help.',\n registrationUrl: urls?.registrationUrl ?? '',\n documentationUrl: options.remediation?.docsUrl ?? urls?.documentationUrl ?? '',\n steps: [\n 'Report the failure to the site operator — their AstraSync API key needs rotating',\n 'Do not retry: the failure is deterministic until the operator updates their key',\n ],\n }\n : isApiError\n ? {\n message:\n 'Verification is temporarily unavailable. Retry with exponential backoff; if the issue persists, contact support with the correlationId.',\n registrationUrl: urls?.registrationUrl ?? '',\n documentationUrl: urls?.documentationUrl ?? '',\n steps: [\n 'Retry the request with exponential backoff',\n 'If failures persist, share the correlationId with support',\n ],\n }\n : {\n message:\n 'This service verifies AI agents before granting access. Please register your agent with AstraSync.',\n registrationUrl: urls?.registrationUrl ?? '',\n documentationUrl: urls?.documentationUrl ?? '',\n steps: [\n // MCP steering leads when the hosted bridge is advertised — the\n // connector is the agent-actionable path (keyless, human-approved).\n ...(urls?.mcpEndpoint\n ? [\n `Fastest path (inside an MCP host): add the AstraSync MCP connector at ${urls.mcpEndpoint} — keyless, human-approved registration`,\n ]\n : []),\n 'Register for an AstraSync account',\n 'Create and register your agent',\n 'Add your ASTRA-ID to request headers',\n 'Retry your request',\n ],\n ...(mcpGuidance(urls) && { mcp: mcpGuidance(urls) }),\n };\n\n return {\n // Round-18 G4: createGuidanceResponse fires for unverified-agent path or\n // API-error fallback. Identity is not verified (no agent resolved);\n // policy is not evaluated (we never reached the gate).\n identityVerified: false,\n policyAllowed: false,\n guidance,\n denialReasons: reason ? [reason] : ['No valid agent credentials provided'],\n // Round-10 (#47, O5): on API-error fallback, surface a typed failure so\n // partners (and their custom onDenied handlers) can branch on\n // dimension. Without this, the synthesised stub was indistinguishable\n // from a real policy deny.\n failures: isMisconfig\n ? [\n {\n dimension: 'verify_access.merchant_misconfigured',\n message: reason ?? 'The integration API key was rejected by AstraSync',\n guidance: guidance.message,\n },\n ]\n : isApiError\n ? [\n {\n dimension: 'verify_access.api_error',\n message: reason ?? 'Verification temporarily unavailable',\n guidance: guidance.message,\n },\n ]\n : undefined,\n // 4.0.0: typed marker so adapters render the misconfig envelope (503 +\n // MERCHANT_VERIFICATION_MISCONFIGURED) without string-matching.\n ...(isMisconfig && { misconfigured: true }),\n // 4.6.0: a transient api_error is retryable — mark it so consumers surface\n // \"temporarily unavailable, retry\" (recommendation 'error') instead of\n // coercing the absent recommendation to a policy 'deny'. Misconfig is\n // deterministic and intentionally NOT marked retryable.\n ...(isApiError && { retryable: true }),\n correlationId: options.correlationId,\n attemptId: options.attemptId,\n verifiedAt: new Date(),\n };\n}\n\n/**\n * Call the AstraSync verify-access API\n */\nasync function callVerifyAccessAPI(\n config: GatewayConfig,\n request: VerificationRequest\n): Promise<{\n success: boolean;\n access?: {\n allowed: boolean;\n reason?: string;\n /**\n * Aggregated denial failures (v2.9.8+). Empty / absent when allowed.\n * Each entry is `{ dimension, message, guidance? }` — see\n * `AccessFailure` for the contract.\n */\n failures?: Array<{ dimension: string; message: string; guidance?: string }>;\n requiresStepUp?: boolean;\n requiresApproval?: boolean;\n appliedPolicy?: {\n boundaryName: string;\n policyVersion: string;\n };\n counterparty?: {\n id: string;\n name: string;\n trustScoreRequirement: number;\n };\n };\n agent?: {\n kyaAgentId: string;\n astraId: string;\n name: string;\n trustScore: number;\n trustLevel: string;\n agentStatus: string;\n blockchainStatus: string;\n };\n developer?: {\n kyaOwnerId: string;\n fullName: string;\n email: string;\n identityVerified: boolean;\n trustScore: number;\n };\n organization?: {\n name: string;\n verified: boolean;\n trustScore: number;\n };\n /**\n * Structured explanation of the verification decision. Tells the merchant\n * WHY (id verified? challenge passed? request within PDLSS? trust score?)\n * without exposing thresholds, scope lists, or other-tenant counterparty\n * membership. Empty `attestations` unless the endpoint's access policy\n * declared `required_attestations`.\n */\n verificationContext?: {\n idVerified: boolean;\n runtimeChallenge: {\n status: 'passed' | 'skipped' | 'failed' | 'timeout' | 'not_supported';\n checkedAt: string | null;\n };\n pdlssCheck: {\n result: 'within' | 'exceeded' | 'denied' | 'not_evaluated';\n purpose: 'approved' | 'denied';\n scope: 'approved' | 'denied';\n };\n dynamicTrustScore: number;\n attestations: Array<{\n type: string;\n status: 'passed' | 'failed';\n /** LMAX-POC C1: underlying check timestamp for merchant freshness gates. */\n checkedAt: string;\n validUntil?: string;\n proofType: 'reference' | 'zkp';\n proof: string;\n }>;\n };\n error?: string;\n /**\n * 4.0.0: the backend 401'd this integration's OWN API key (revoked /\n * expired / invalid) — deterministic merchant-side misconfig, not a\n * transient failure. `misconfigCode` carries the backend's api_key_* code\n * and `remediation` its operator-facing URLs when present.\n */\n misconfig?: boolean;\n misconfigCode?: string;\n remediation?: { docsUrl?: string; manageUrl?: string };\n /**\n * When the verify-access server response carries a\n * correlationId on an error envelope, propagate it so the SDK can thread\n * it through createGuidanceResponse → adapter onDenied → merchant body.\n */\n correlationId?: string;\n /**\n * 3.12.0 (Trust Record): the server echoes the attempt-chain\n * handle top-level on every response branch (error envelopes included).\n */\n attemptId?: string;\n}> {\n const { credentials, ...requestData } = request;\n\n // Build the request body. agentId is omitted when not provided so the\n // server treats it as an anonymous canonical-flow call (Branch A/B/C).\n const body: Record<string, unknown> = {\n ...(credentials.astraId && { agentId: credentials.astraId }),\n ...(requestData.purpose && { purpose: requestData.purpose }),\n };\n\n // Add optional fields\n if (requestData.action) body.action = requestData.action;\n if (requestData.resourceType) body.resourceType = requestData.resourceType;\n if (requestData.resource) body.resource = requestData.resource;\n if (requestData.jurisdiction) body.jurisdiction = requestData.jurisdiction;\n if (requestData.transactionValue) body.transactionValue = requestData.transactionValue;\n if (requestData.currency) body.currency = requestData.currency;\n if (requestData.isSubAgentRequest) body.isSubAgentRequest = requestData.isSubAgentRequest;\n if (requestData.parentAgentId) body.parentAgentId = requestData.parentAgentId;\n if (requestData.subAgentDepth !== undefined) body.subAgentDepth = requestData.subAgentDepth;\n // Handshake Protocol v10 additions\n if (requestData.enableRuntimeChallenge)\n body.enableRuntimeChallenge = requestData.enableRuntimeChallenge;\n if (requestData.createSession) body.createSession = requestData.createSession;\n if (requestData.durationRequired) body.durationRequired = requestData.durationRequired;\n if (requestData.counterpartyType) body.counterpartyType = requestData.counterpartyType;\n if (requestData.counterpartyUrl) body.counterpartyUrl = requestData.counterpartyUrl;\n if (config.counterpartyId) body.counterpartyId = config.counterpartyId;\n if (requestData.runtimeChallengeOptions)\n body.runtimeChallengeOptions = requestData.runtimeChallengeOptions;\n // Round-12 (F19): transport-vs-intent separation. MCP middleware sets\n // this to 'mcp'; non-MCP callers leave it unset.\n if (requestData.invocationProtocol) body.invocationProtocol = requestData.invocationProtocol;\n // 5.3.0 (astra-pay): checkout-leg discriminator — first-party settlement\n // fires only on 'confirm'; absent keeps pre-phase server behavior.\n if (requestData.commercePhase) body.commercePhase = requestData.commercePhase;\n // Per-cart idempotency key (checkout session id) forwarded on the confirm\n // leg so concurrent confirms for one cart charge at most once.\n if (requestData.checkoutSessionId) body.checkoutSessionId = requestData.checkoutSessionId;\n // Order-plane cart lines (receipts + fulfillment email) — informational.\n if (requestData.checkoutItems) body.checkoutItems = requestData.checkoutItems;\n // 3.9.0 (§33.5 #1): raw commerce artifacts forwarded verbatim — the\n // backend's Step 0.5 pipeline does the cryptographic verification\n // server-side (adapters forward, never verify locally).\n if (requestData.commerceArtifacts) body.commerceArtifacts = requestData.commerceArtifacts;\n // 3.12.0 (Trust Record, §33.5 #3): attempt-chain handle + consideration set,\n // forwarded skip-when-undefined (observedMetadata precedent) — pure\n // observational pass-through; the server echoes attemptId on every branch.\n if (requestData.attemptId) body.attemptId = requestData.attemptId;\n if (requestData.considerationSet) body.considerationSet = requestData.considerationSet;\n\n // Round-13 (F14 closure / R13-7): emit the SDK package version on every\n // verify-access body so the backend can auto-populate `kya_counterparty.\n // sdk_version` for the calling endpoint. Body field (not User-Agent\n // header) is the canonical channel — works in Node, browser, behind\n // Cloudflare, and across SDK bundlers without environment-specific\n // header gymnastics. Backend's `validation.ts:verifyAccessSchema`\n // accepts the semver regex; the auto-pop logic is forward-only.\n body.sdkVersion = SDK_VERSION;\n\n // Forward caller metadata when present. Merges the legacy top-level\n // clientIp/userAgent into the nested block for backward compatibility.\n if (requestData.callerMetadata || requestData.clientIp || requestData.userAgent) {\n const meta = {\n ...(requestData.clientIp && { sourceIp: requestData.clientIp }),\n ...(requestData.userAgent && { userAgent: requestData.userAgent }),\n ...requestData.callerMetadata,\n };\n if (Object.keys(meta).length > 0) body.callerMetadata = meta;\n }\n\n // Build headers\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...config.customHeaders,\n };\n\n // verify-access requires authentication. Use ONLY the merchant's\n // configured apiKey for outbound auth. Previously the caller's inbound\n // Authorization header took priority, which pivoted the verify-access\n // call to the caller's identity — letting an attacker who supplied\n // their own Authorization header trigger verify-access calls under\n // THEIR account and observe the resulting verdicts for arbitrary\n // lookups they triggered via the merchant. Audit F-A1-10.\n //\n // The caller-supplied JWT (if any) is already extracted to\n // credentials.jwt and travels in the verify-access request body so\n // backend can evaluate it as the agent's identity claim — separate from\n // the merchant-attribution auth on the outbound HTTPS call.\n if (config.apiKey) {\n headers['Authorization'] = `Bearer ${config.apiKey}`;\n // Legacy header kept for compatibility with any middleware that reads it directly.\n headers['X-API-Key'] = config.apiKey;\n }\n\n try {\n // 4.0.0: hard timeout — without one, a backend that accepts the\n // connection but never answers hangs the merchant's middleware and every\n // inbound agent request behind it (observed live on a partner property).\n // Timeouts land on the catch path below → api_error (fail-closed),\n // NOT misconfig. The edge adapter races its own tighter withBudget.\n const response = await sdkFetch(`${config.apiBaseUrl}/agents/verify-access`, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(config.verifyTimeoutMs ?? 10_000),\n });\n\n const data = await response.json();\n\n // v2.3.8 (defect #29): treat 410 Gone as a deterministic deactivated-endpoint\n // signal. Older SDKs may treat any non-2xx as transient and retry; v2.3.8+\n // surfaces it as a structured denial with `reason: 'endpoint_deactivated'`\n // so callers can distinguish \"endpoint gone\" from \"endpoint denied this\".\n if (response.status === 410) {\n return {\n success: true,\n // 3.12.0 (Trust Record): keep the server-echoed attempt handle even on\n // the synthesised 410 deny shape (echoed on every branch).\n attemptId: typeof data?.attemptId === 'string' ? data.attemptId : undefined,\n access: {\n allowed: false,\n reason: 'endpoint_deactivated',\n failures: [\n {\n dimension: 'endpoint.deactivated',\n message:\n typeof data?.message === 'string' ? data.message : 'Endpoint has been deactivated',\n guidance:\n typeof data?.guidance === 'string'\n ? data.guidance\n : 'Reactivate via POST /api/endpoints/{id}/reactivate, or update the URL on the calling agent.',\n },\n ],\n },\n };\n }\n\n if (!response.ok) {\n // 4.0.0: a 401 from verify-access can ONLY mean the backend rejected\n // THIS INTEGRATION'S own API key — agent denials come back as 200 with\n // access.allowed=false. Surface it as merchant-misconfig, not a\n // transient api_error: it is deterministic until the operator rotates\n // the key, and the \"retry with backoff\" template actively misleads.\n // Backends ≥ this round also send code: api_key_* + remediation URLs.\n if (response.status === 401) {\n return {\n success: false,\n error: data.message || data.error || 'Integration API key rejected',\n misconfig: true,\n misconfigCode: typeof data?.code === 'string' ? data.code : undefined,\n remediation:\n data?.remediation && typeof data.remediation === 'object'\n ? (data.remediation as { docsUrl?: string; manageUrl?: string })\n : undefined,\n correlationId: typeof data?.correlationId === 'string' ? data.correlationId : undefined,\n attemptId: typeof data?.attemptId === 'string' ? data.attemptId : undefined,\n };\n }\n // Round-10 (#47, O5): propagate correlationId on the error path too if\n // the server happened to include one (some 5xx error envelopes carry\n // it). Lets the SDK pass it through to the adapter onDenied handler.\n return {\n success: false,\n error: data.message || data.error || `API returned ${response.status}`,\n correlationId: typeof data?.correlationId === 'string' ? data.correlationId : undefined,\n attemptId: typeof data?.attemptId === 'string' ? data.attemptId : undefined,\n };\n }\n\n return data;\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n return {\n success: false,\n error: `Failed to call verify-access API: ${message}`,\n };\n }\n}\n\n/**\n * Options for a single verify() call (as opposed to GatewayConfig, which is\n * per-gateway). Mirrors the Java SDK's `verify(request, bypassCache)`.\n */\nexport interface VerifyOptions {\n /**\n * Skip the cache READ for this call so the request is guaranteed to reach\n * the backend (the result is still written to the cache if cacheable).\n * Used by the step-up hold-and-poll retry: the re-verify after an approval\n * must hit the server to redeem the single-use approval.\n */\n bypassCache?: boolean;\n}\n\n/**\n * Main verification function\n */\nexport async function verify(\n config: GatewayConfig,\n request: VerificationRequest,\n options?: VerifyOptions\n): Promise<VerificationResult> {\n const mergedConfig = { ...DEFAULT_CONFIG, ...config };\n\n // v2.5.0: read well-known URLs from cache (prefetched by adapter at middleware creation).\n // Synchronous — never triggers a fetch. If cache is empty, guidance URLs are empty strings.\n const urls = mergedConfig.apiBaseUrl\n ? getCachedWellKnownUrls(mergedConfig.apiBaseUrl)\n : undefined;\n\n // One-time init self-test — fire-and-forget by default, never blocks verify().\n // Audit F-A6-33: when GatewayConfig.strictInit is set, the init promise is\n // awaited and any failure throws synchronously so callers learn about\n // misconfigured apiBaseUrl on the first verify() call rather than silently\n // running with broken auth.\n if (!initCheckPerformed && !mergedConfig.disableInitChecks && mergedConfig.apiBaseUrl) {\n if (mergedConfig.strictInit) {\n await performInitCheck(\n mergedConfig.apiBaseUrl,\n mergedConfig.debug,\n true,\n mergedConfig.apiKey\n );\n } else {\n void performInitCheck(\n mergedConfig.apiBaseUrl,\n mergedConfig.debug,\n false,\n mergedConfig.apiKey\n );\n }\n }\n\n // Deprecation warning for v2.3.0 removed config fields. Fires once per process.\n if (\n !deprecationWarningShown &&\n (config.minTrustScore !== undefined || config.minTrustScoreForFull !== undefined)\n ) {\n deprecationWarningShown = true;\n console.warn(\n '[VerificationGateway] minTrustScore / minTrustScoreForFull are deprecated in v2.3.0 ' +\n 'and have no effect. Server is now the single source of truth for access decisions ' +\n '(verified ID + runtime challenge + PDLSS + trust score). To gate access ' +\n \"to an endpoint, configure the endpoint's trust_score_requirement server-side.\"\n );\n }\n\n // v2.3.0: anonymous traffic no longer short-circuits here. We forward the\n // request to the server with no agentId; the server applies the endpoint's\n // unverifiedAgentPolicy and returns advisory. createGuidanceResponse remains\n // as the offline fallback if the API itself fails (handled below).\n\n // Check cache first. Caching on unless caller explicitly sets cacheTtl: 0\n // to disable. Undefined falls through to the 60s default at cacheResult\n // write time. options.bypassCache skips the read only (hold-and-poll retry\n // must reach the backend to redeem its approval).\n if (mergedConfig.cacheTtl !== 0 && !options?.bypassCache) {\n const cached = getCachedResult(request, mergedConfig.counterpartyId);\n if (cached) {\n if (mergedConfig.debug) {\n console.log('[VerificationGateway] Returning cached result');\n }\n // 3.12.0 (Trust Record, §33.5 #3): attemptId is excluded from the cache\n // key, so the stored result may carry a PRIOR attempt's id. Overwrite it\n // with this request's own attemptId — or drop it when this request has\n // none — a cached verdict must never leak another attempt's handle.\n // Shallow clone: never mutate the stored entry (a concurrent holder of\n // the same cached object may still be reading it).\n const hit: VerificationResult = { ...cached };\n if (request.attemptId) {\n hit.attemptId = request.attemptId;\n } else {\n delete hit.attemptId;\n }\n return hit;\n }\n }\n\n // Inject counterparty info from config if not already set in request\n const enrichedRequest = { ...request };\n if (!enrichedRequest.counterpartyUrl && mergedConfig.counterpartyUrl) {\n enrichedRequest.counterpartyUrl = mergedConfig.counterpartyUrl;\n }\n if (!enrichedRequest.counterpartyType && mergedConfig.counterpartyType) {\n enrichedRequest.counterpartyType = mergedConfig.counterpartyType;\n }\n\n // Call the API\n if (mergedConfig.debug) {\n console.log('[VerificationGateway] Calling verify-access API');\n }\n\n const apiResponse = await callVerifyAccessAPI(mergedConfig, enrichedRequest);\n\n // 3.6.0: the server emits a top-level denialReasons array on every deny\n // path (same strings as the failure messages). Non-empty → authoritative;\n // absent/empty → fall back to the client-side reconstructions below.\n const rawServerDenialReasons = (apiResponse as Record<string, unknown>).denialReasons;\n const serverDenialReasons =\n Array.isArray(rawServerDenialReasons) && rawServerDenialReasons.length > 0\n ? (rawServerDenialReasons as string[])\n : undefined;\n\n // Handle API errors\n if (!apiResponse.success) {\n // Round-10 (#47, O5): distinguish API errors from missing-credentials.\n // The previous default tagged any failure with the \"register your\n // agent\" template, which is misleading to a verified partner whose\n // verify-access call hit a 500. The `api_error` source surfaces a\n // typed `verify_access.api_error` failure entry instead.\n // 4.0.0: a rejected merchant key gets its own source — deterministic\n // misconfig must not wear the \"temporarily unavailable, retry\" template.\n return createGuidanceResponse(mergedConfig, apiResponse.error, {\n source: apiResponse.misconfig ? 'merchant_misconfig' : 'api_error',\n correlationId: (apiResponse as { correlationId?: string }).correlationId,\n attemptId: (apiResponse as { attemptId?: string }).attemptId,\n remediation: apiResponse.remediation,\n urls,\n });\n }\n\n // Check access result\n if (!apiResponse.access?.allowed) {\n // v2.9.8 (defect M1): aggregated failures across every gate that\n // denied. Surface them on the result so the integrator can see every\n // blocker in one go instead of the previous fail-fast cascade.\n const aggregatedFailures = (apiResponse.access as Record<string, unknown> | undefined)\n ?.failures as Array<{ dimension: string; message: string; guidance?: string }> | undefined;\n // Round-18 G4: backend denied access (PDLSS or other gate); identity status\n // depends on whether the backend resolved the caller. Read from\n // verificationContext.idVerified; default false if absent (anonymous or\n // identity-fail paths land here too). policyAllowed is false by definition\n // in this branch (apiResponse.access.allowed === false).\n const idVerifiedFromBackend =\n (apiResponse.verificationContext as { idVerified?: boolean } | undefined)?.idVerified ===\n true;\n const result: EnhancedVerificationResult = {\n identityVerified: idVerifiedFromBackend,\n policyAllowed: false,\n // 3.6.0: the server now emits top-level denialReasons on every deny\n // path — prefer it verbatim; the failure-message reconstruction remains\n // as the fallback for older backends.\n denialReasons:\n serverDenialReasons ??\n (aggregatedFailures && aggregatedFailures.length > 0\n ? aggregatedFailures.map((f) => f.message)\n : apiResponse.access?.reason\n ? [apiResponse.access.reason]\n : ['Access denied']),\n failures: aggregatedFailures,\n requiresStepUp: apiResponse.access?.requiresStepUp,\n requiresApproval: apiResponse.access?.requiresApproval,\n guidance: {\n message: apiResponse.access?.reason || 'Access denied by PDLSS policy',\n registrationUrl: urls?.registrationUrl ?? '',\n documentationUrl: urls?.documentationUrl ?? '',\n // 5.1.0: anonymous callers land on this branch — steer MCP-hosted\n // agents to the connector (this is what the edge deny body surfaces).\n ...(mcpGuidance(urls) && { mcp: mcpGuidance(urls) }),\n },\n verifiedAt: new Date(),\n // Extract sessionId so decisions can be recorded for denials too\n sessionId: (apiResponse as Record<string, unknown>).sessionId as string | undefined,\n // Anonymous traffic has no session → correlationId is the per-attempt\n // linking key (the sessionId-equivalent for anonymous callers).\n correlationId: (apiResponse as Record<string, unknown>).correlationId as string | undefined,\n // 3.12.0 (Trust Record): server echoes the attempt-chain handle on\n // every branch — denials included (the funnel outlives one deny).\n attemptId: (apiResponse as Record<string, unknown>).attemptId as string | undefined,\n recommendation: (apiResponse as Record<string, unknown>)\n .recommendation as EnhancedVerificationResult['recommendation'],\n recommendationReasons: (apiResponse as Record<string, unknown>).recommendationReasons as\n | string[]\n | undefined,\n stepUpApproval: (apiResponse as Record<string, unknown>).stepUpApproval as\n | StepUpApprovalInfo\n | undefined,\n settlement: (apiResponse as Record<string, unknown>).settlement as\n | SettlementArtifact\n | undefined,\n settlementOutcome: (apiResponse as Record<string, unknown>).settlementOutcome as\n | SettlementOutcomeInfo\n | undefined,\n };\n\n return result;\n }\n\n // Build successful result\n const agent: VerifiedAgent | undefined = apiResponse.agent\n ? {\n astraId: apiResponse.agent.astraId,\n name: apiResponse.agent.name,\n trustScore: apiResponse.agent.trustScore,\n trustLevel: getTrustLevel(apiResponse.agent.trustScore),\n blockchainVerified: apiResponse.agent.blockchainStatus === 'verified',\n status: apiResponse.agent.agentStatus as VerifiedAgent['status'],\n }\n : undefined;\n\n const developer: VerifiedDeveloper | undefined = apiResponse.developer\n ? {\n astradId: apiResponse.developer.kyaOwnerId,\n name: apiResponse.developer.fullName,\n trustScore: apiResponse.developer.trustScore || 0,\n verified: apiResponse.developer.identityVerified,\n }\n : undefined;\n\n const organization: VerifiedOrganization | undefined = apiResponse.organization\n ? {\n name: apiResponse.organization.name,\n verified: apiResponse.organization.verified,\n trustScore: apiResponse.organization.trustScore,\n }\n : undefined;\n\n // Verification context — structured \"why\" the merchant gets in v2.2.4+.\n // Carries appliedPolicy (no UUIDs), pdlssCheck summary, dynamic trust score,\n // and policy-driven attestations. Replaces the old over-sharing `pdlss` block.\n const verificationContext = apiResponse.verificationContext;\n\n const result: EnhancedVerificationResult = {\n // 4.5.0 (probe F1): read idVerified from verificationContext with the\n // SAME absent⇒false default as the deny branch. The previous `!== false`\n // default manufactured `identityVerified: true` for anonymous\n // allow_full/allow_partial/audit responses (which allow access but omit\n // verificationContext entirely) — the \"anonymous caller labelled\n // verified\" defect. Every authenticated success response has carried\n // `verificationContext.idVerified: true` since v2.2.4, so a truth claim\n // this load-bearing must never be defaulted on.\n identityVerified:\n (apiResponse.verificationContext as { idVerified?: boolean } | undefined)?.idVerified ===\n true,\n policyAllowed: true,\n agent,\n developer,\n organization,\n appliedPolicy: apiResponse.access?.appliedPolicy,\n verificationContext,\n requiresStepUp: apiResponse.access?.requiresStepUp,\n requiresApproval: apiResponse.access?.requiresApproval,\n verifiedAt: new Date(),\n cacheTtl: mergedConfig.cacheTtl,\n // Handshake Protocol v10 enhanced fields (present when backend returns them)\n sessionId: (apiResponse as Record<string, unknown>).sessionId as string | undefined,\n // v2.3.10 (defect #34, round-4): anonymous responses surface correlationId\n // (no session row exists for unverified callers).\n correlationId: (apiResponse as Record<string, unknown>).correlationId as string | undefined,\n // 3.12.0 (Trust Record): server-echoed attempt-chain handle.\n attemptId: (apiResponse as Record<string, unknown>).attemptId as string | undefined,\n runtimeChallenge: (apiResponse as Record<string, unknown>).runtimeChallenge as\n | RuntimeChallengeResult\n | undefined,\n tokenGuidance: (apiResponse as Record<string, unknown>).tokenGuidance as\n | TokenGuidance\n | undefined,\n recommendation: (apiResponse as Record<string, unknown>)\n .recommendation as EnhancedVerificationResult['recommendation'],\n recommendationReasons: (apiResponse as Record<string, unknown>).recommendationReasons as\n | string[]\n | undefined,\n warningHeader: (apiResponse as Record<string, unknown>).warningHeader as\n | { name: string; value: string }\n | undefined,\n stepUpApproval: (apiResponse as Record<string, unknown>).stepUpApproval as\n | StepUpApprovalInfo\n | undefined,\n settlement: (apiResponse as Record<string, unknown>).settlement as\n | SettlementArtifact\n | undefined,\n settlementOutcome: (apiResponse as Record<string, unknown>).settlementOutcome as\n | SettlementOutcomeInfo\n | undefined,\n };\n\n // Enforce AstraSync recommendation\n if (result.recommendation === 'deny') {\n // Round-18 G4: recommendation-driven deny lands on the success-path\n // construction (identity was resolved). Flip policy only — identity stays\n // verified — so adapters return 403 (re-auth won't help; the policy\n // decision is the blocker).\n result.policyAllowed = false;\n // 3.6.0: server-sent top-level denialReasons wins; recommendationReasons\n // reconstruction is the fallback for older backends.\n result.denialReasons = serverDenialReasons ??\n result.recommendationReasons ?? ['Access denied by AstraSync recommendation'];\n result.guidance = result.runtimeChallenge\n ? {\n message: `Verification failed: ${result.runtimeChallenge.reason || 'runtime challenge failed'}`,\n registrationUrl: urls?.registrationUrl ?? '',\n documentationUrl: urls?.documentationUrl ?? '',\n }\n : {\n message: result.recommendationReasons?.[0] || 'Access denied by AstraSync recommendation',\n registrationUrl: urls?.registrationUrl ?? '',\n documentationUrl: urls?.documentationUrl ?? '',\n };\n } else if (result.recommendation === 'step_up_required') {\n // The escalation signal rides on `requiresStepUp` / `stepUpApproval`, not\n // on any masquerade of the (now-removed) access band.\n result.requiresStepUp = true;\n result.denialReasons = serverDenialReasons ??\n result.recommendationReasons ?? ['Step-up verification required'];\n }\n\n // Cache the result. Never cache denials (agent may fix challenge endpoint\n // and retry) NOR step-up escalations (3.6.0 — the same bug the Java SDK\n // had: a cached step_up_required verdict keeps denying retries the owner\n // has already approved, and its pollUrl goes stale once consumed/expired).\n // Escalations stay uncached even when the caller pins an explicit cacheTtl.\n const escalates =\n result.requiresStepUp === true ||\n result.requiresApproval === true ||\n result.recommendation === 'step_up_required';\n if (mergedConfig.cacheTtl !== 0 && result.recommendation !== 'deny' && !escalates) {\n cacheResult(request, result, mergedConfig.cacheTtl, mergedConfig.counterpartyId);\n }\n\n return result;\n}\n\n/**\n * Record a counterparty's grant/deny decision for a verification session.\n * Fire-and-forget — errors are silently swallowed.\n */\nexport async function recordDecision(\n config: GatewayConfig,\n sessionId: string,\n decision: 'granted' | 'denied',\n reason?: string\n): Promise<void> {\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (config.apiKey) {\n headers['Authorization'] = `Bearer ${config.apiKey}`;\n headers['X-API-Key'] = config.apiKey;\n }\n\n await sdkFetch(`${config.apiBaseUrl}/agents/verify-access/${sessionId}/decision`, {\n method: 'POST',\n headers,\n body: JSON.stringify({ decision, reason }),\n }).catch(() => {\n /* fire-and-forget */\n });\n}\n\n/**\n * Report post-hoc consideration/outcome data for an attempt chain (Trust\n * Record). Use when the signal never reached verify-access: a\n * catalog served from a local cache, a transport-side deny (sku not found,\n * over budget), or a terminal outcome (settled / blocked on step-up).\n * Authenticated with the same credentials as verify(); the backend responds\n * 202 and folds the data into the attempt chain keyed by `attemptId`.\n *\n * Fire-and-forget — errors are silently swallowed, never throws.\n */\nexport async function reportAttempt(config: GatewayConfig, report: AttemptReport): Promise<void> {\n const apiBaseUrl = config.apiBaseUrl || DEFAULT_CONFIG.apiBaseUrl!;\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (config.apiKey) {\n headers['Authorization'] = `Bearer ${config.apiKey}`;\n headers['X-API-Key'] = config.apiKey;\n }\n\n // counterpartyId resolution mirrors reportUnregisteredAttempt: an explicit\n // report value wins; otherwise attribute to the configured endpoint.\n const body = {\n ...report,\n ...(!report.counterpartyId &&\n config.counterpartyId && { counterpartyId: config.counterpartyId }),\n };\n\n await sdkFetch(`${apiBaseUrl}/agents/verify-access/attempt-report`, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n }).catch(() => {\n /* fire-and-forget */\n });\n}\n\n/**\n * Fetch the per-route policy for an endpoint from the AstraSync backend.\n * v2.9.7 moved policy authority into the dashboard — the SDK no longer\n * accepts `routes` from merchant-side source code, it fetches them from\n * here on init (and refreshes periodically).\n *\n * Returns `null` when the request fails for any reason — the caller decides\n * how to fall back (the middleware allows-all when no policy is loaded so\n * a misconfigured init doesn't take down the merchant's API).\n */\nexport async function fetchRoutes(\n config: GatewayConfig,\n counterpartyId: string\n): Promise<RouteAccessConfigShape[] | null> {\n if (!counterpartyId) return null;\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (config.apiKey) {\n headers['Authorization'] = `Bearer ${config.apiKey}`;\n headers['X-API-Key'] = config.apiKey;\n }\n try {\n const response = await sdkFetch(\n `${config.apiBaseUrl}/endpoints/${encodeURIComponent(counterpartyId)}/routes`,\n { method: 'GET', headers }\n );\n if (!response.ok) return null;\n const body = (await response.json()) as { data?: { routes?: RouteAccessConfigShape[] } };\n return body.data?.routes ?? [];\n } catch {\n return null;\n }\n}\n\n/**\n * Minimal shape of an EndpointRoute as the SDK consumes it. Mirrors the\n * server's `EndpointRoute` type and the SDK's `RouteAccessConfig` — same\n * JSON moves between server and SDK unchanged.\n */\nexport interface RouteAccessConfigShape {\n pattern: string;\n method: string;\n /** Pass through unenforced (observe). Replaces `minAccessLevel: 'none'`. */\n observe?: boolean;\n minTrustScore?: number;\n requiredPurposes?: string[];\n allowedPurposes?: string[];\n allowedJurisdictions?: string[];\n maxDuration?: number;\n maxTransactionValue?: number;\n requirePurpose?: boolean;\n /** Send-mapping — see RouteAccessConfig in types.ts. */\n purpose?: string;\n action?: string;\n}\n\n/**\n * Verify an agent AND automatically record the grant/deny decision.\n *\n * This is the recommended entry point for counterparties that call verify()\n * directly (e.g. MCP servers) rather than using createMiddleware().\n * It adds createSession: true, then fire-and-forgets the decision.\n */\nexport async function verifyAndRecord(\n config: GatewayConfig,\n request: VerificationRequest,\n options?: VerifyOptions\n): Promise<VerificationResult> {\n const mergedConfig = { ...DEFAULT_CONFIG, ...config };\n const result = await verify(mergedConfig, { ...request, createSession: true }, options);\n const sessionId = (result as EnhancedVerificationResult).sessionId;\n\n if (sessionId) {\n // Round-18 G4: a session is \"granted\" only if identity verified AND\n // policy allowed; either failing is a deny.\n if (result.identityVerified && result.policyAllowed) {\n recordDecision(mergedConfig, sessionId, 'granted').catch(() => {});\n } else {\n recordDecision(mergedConfig, sessionId, 'denied', result.denialReasons?.[0]).catch(() => {});\n }\n }\n\n return result;\n}\n\n/**\n * Report an unregistered agent attempt (no AstraSync credentials).\n * Called by SDK adapters when an agent is redirected to /docs/agent-access.\n * Fire-and-forget — errors are silently swallowed.\n */\nexport async function reportUnregisteredAttempt(\n config: GatewayConfig,\n data: {\n /**\n * 3.6.0: optional — the backend attributes by counterpartyId first (sent\n * from config below) and requires at least ONE of counterpartyId/URL.\n * A null/undefined URL is omitted from the body, not sent as null.\n */\n counterpartyUrl?: string;\n counterpartyType?: string;\n sourceIp?: string;\n userAgent?: string;\n requestPath?: string;\n requestMethod?: string;\n /**\n * 3.9.0 — edge-adapter evidence fields, persisted into the\n * event's eventData by the backend: `protocol` = detected transport/\n * credential protocol; `evidence` = light crypto-free detection detail.\n */\n protocol?: string;\n evidence?: Record<string, unknown>;\n /**\n * Maximal metadata capture — the full sanitised metadata for an\n * unregistered caller (every signal legitimately visible on the wire).\n * Persisted into eventData; feeds platform attribution and (via\n * correlationId) registration auto-fill. Fire-and-forget, so free.\n */\n observedMetadata?: ObservedMetadata;\n }\n): Promise<void> {\n const apiBaseUrl = config.apiBaseUrl || DEFAULT_CONFIG.apiBaseUrl!;\n\n const { counterpartyUrl, ...rest } = data;\n const body = {\n ...rest,\n ...(counterpartyUrl && { counterpartyUrl }),\n ...(config.counterpartyId && { counterpartyId: config.counterpartyId }),\n };\n\n await sdkFetch(`${apiBaseUrl}/verification-activity/unregistered-attempt`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n }).catch(() => {\n /* fire-and-forget */\n });\n}\n\n/**\n * Report a counterparty-side PDLSS pre-check failure.\n * Called by SDK adapters when the agent's requested PDLSS exceeds\n * counterparty-defined maximums BEFORE calling verify-access.\n * Fire-and-forget — errors are silently swallowed.\n */\nexport async function reportCounterpartyPreCheckFailure(\n config: GatewayConfig,\n data: {\n agentId: string;\n counterpartyUrl: string;\n counterpartyType?: string;\n failures: Array<{\n field: string;\n requested: string | number;\n limit: string | number | string[];\n message: string;\n }>;\n requestPath?: string;\n requestMethod?: string;\n }\n): Promise<void> {\n const apiBaseUrl = config.apiBaseUrl || DEFAULT_CONFIG.apiBaseUrl!;\n\n await sdkFetch(`${apiBaseUrl}/verification-activity/counterparty-pre-check-failure`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(data),\n }).catch(() => {\n /* fire-and-forget */\n });\n}\n\n/**\n * Quick verification — checks credentials and policy in one call.\n *\n * The return shape mirrors `VerificationResult`'s split — partners\n * writing custom handlers around `quickVerify` get the same identity/policy\n * distinction as those calling `verify()` directly. Map to HTTP status the\n * same way: `!identityVerified` → 401; `identityVerified && !policyAllowed`\n * → 403.\n */\nexport async function quickVerify(\n config: GatewayConfig,\n credentials: AgentCredentials\n): Promise<{\n identityVerified: boolean;\n policyAllowed: boolean;\n reason?: string;\n}> {\n const result = await verify(config, {\n credentials,\n purpose: 'verification',\n });\n\n return {\n identityVerified: result.identityVerified,\n policyAllowed: result.policyAllowed,\n reason: result.denialReasons?.[0],\n };\n}\n","/**\n * Helpers over {@link NormalizedRequest} — header access, URL\n * reconstruction, and the full sanitized metadata capture.\n */\n\nimport {\n sanitizeHeaders,\n CAPTURE_SCHEMA_VERSION,\n type ObservedMetadata,\n} from '../metadata-capture';\nimport type { NormalizedRequest } from './types';\n\n/** Value of a header (name matched case-insensitively), or undefined. */\nexport function headerValue(req: NormalizedRequest, name: string): string | undefined {\n return req.headers[name.toLowerCase()];\n}\n\n/** Full request URL as the origin will see it (scheme fixed to https). */\nexport function requestUrl(req: NormalizedRequest, host: string): string {\n const qs = req.querystring ? `?${req.querystring}` : '';\n return `https://${host}${req.uri}${qs}`;\n}\n\n/**\n * The FULL sanitized metadata capture for one request: every inbound\n * header (secrets stripped, credential headers reduced to a safe format\n * prefix) plus the connection-layer block the platform collected. The\n * edge is the richest capture point — the headers are already in memory —\n * and this is pure string work, so it adds no page latency. Forwarded on\n * both the verify-access call and the telemetry beacon.\n */\nexport function buildObservedMetadata(req: NormalizedRequest): ObservedMetadata {\n const { headers, apiKeyFormat, platformHeaders, cookieCount } = sanitizeHeaders(req.headers);\n const connection = req.connection ?? {};\n const queryKeys = extractQueryKeys(req.querystring);\n return {\n headers,\n ...(apiKeyFormat && { apiKeyFormat }),\n ...(platformHeaders && { platformHeaders }),\n ...(Object.keys(connection).length > 0 && { connection }),\n ...(cookieCount !== undefined && { cookieCount }),\n ...(queryKeys && { queryKeys }),\n schemaVersion: CAPTURE_SCHEMA_VERSION,\n };\n}\n\n/** Backend bounds on queryKeys (mirrored in observedMetadataSchema). */\nconst MAX_QUERY_KEYS = 32;\nconst MAX_QUERY_KEY_CHARS = 64;\n\n/**\n * Query-string parameter NAMES only — deduped, lowercased, bounded. Values\n * are never captured (OAuth codes, tokens, PII); the name set alone\n * fingerprints client shape. Exported for tests.\n */\nexport function extractQueryKeys(querystring: string | undefined): string[] | undefined {\n if (!querystring) return undefined;\n let params: URLSearchParams;\n try {\n params = new URLSearchParams(querystring);\n } catch {\n return undefined;\n }\n const keys: string[] = [];\n for (const key of params.keys()) {\n const normalized = key.toLowerCase().slice(0, MAX_QUERY_KEY_CHARS);\n if (normalized && !keys.includes(normalized)) {\n keys.push(normalized);\n if (keys.length >= MAX_QUERY_KEYS) break;\n }\n }\n return keys.length > 0 ? keys : undefined;\n}\n","/**\n * Crypto-free commerce-protocol detection.\n *\n * The edge only SNIFFS — header shapes, compact-JWT patterns, body field\n * names — and packages what it saw as raw `CommerceArtifactsPayload` for\n * verify-access, whose server-side pipeline does the authoritative parsing\n * and cryptographic verification. Nothing here imports jose/sd-jwt/\n * signature libraries: detection must stay cheap enough to run on every\n * non-human request, and verification must happen exactly once, in the\n * canonical sink, where it is recorded.\n */\n\nimport type { CommerceArtifactsPayload } from '../types';\nimport { headerValue, requestUrl } from './request';\nimport type { NormalizedRequest } from './types';\n\nexport interface DetectedCommerce {\n /** Detection-order label: rfc9421-agent-pay | rfc9421-tap | rfc9421-web-bot-auth | vi-sd-jwt | ap2 | acp | ucp | mpp | x402 */\n protocol: string;\n artifacts: CommerceArtifactsPayload;\n /** Light detection detail for beacons/audit — never secrets or full credentials. */\n evidence: Record<string, unknown>;\n}\n\n/** Compact SD-JWT: JWT + `~`-separated disclosures. */\nconst SD_JWT_PATTERN = /^eyJ[\\w-]+\\.[\\w-]*\\.[\\w-]+~/;\n\n/** Decode a base64url segment to UTF-8 text (web-standard, no Buffer). */\nfunction decodeBase64Url(seg: string): string {\n const b64 = seg.replace(/-/g, '+').replace(/_/g, '/');\n const padded = b64 + '='.repeat((4 - (b64.length % 4)) % 4);\n const binary = atob(padded);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return new TextDecoder().decode(bytes);\n}\n\n/** Decode a JWT header segment without verifying anything. */\nfunction sniffJwtHeader(compact: string): Record<string, unknown> | undefined {\n try {\n const seg = compact.split('.')[0];\n return JSON.parse(decodeBase64Url(seg)) as Record<string, unknown>;\n } catch {\n return undefined;\n }\n}\n\nfunction parseJsonBody(bodyText: string | undefined): Record<string, unknown> | undefined {\n if (!bodyText) return undefined;\n try {\n const parsed: unknown = JSON.parse(bodyText);\n return typeof parsed === 'object' && parsed !== null\n ? (parsed as Record<string, unknown>)\n : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Detection order (after the native X-Astra check, which classify owns):\n * SD-JWT/VI → RFC 9421 (Agent Pay / TAP / Web Bot Auth by kid namespace or\n * Signature-Agent) → ACP HMAC → UCP session → AP2 body triple → MPP → x402.\n * Returns undefined when nothing commerce-shaped is on the wire.\n *\n * When the platform truncated the body (`bodyTruncated`), body-bound\n * artifacts still forward what arrived but carry a `bodyTruncated`\n * evidence flag — the backend downgrades those signatures rather than\n * hard-failing.\n */\nexport function detectCommerce(req: NormalizedRequest, host: string): DetectedCommerce | undefined {\n const url = requestUrl(req, host);\n const method = req.method;\n const headers = req.headers;\n const jsonBody = parseJsonBody(req.bodyText);\n const truncated = req.bodyTruncated ? { bodyTruncated: true } : {};\n\n // --- VI / SD-JWT credential in a header ------------------------------\n const authHeader = headerValue(req, 'authorization');\n const bearer = authHeader?.replace(/^Bearer\\s+/i, '');\n const mandateHeader =\n headerValue(req, 'x-payment-mandate') ?? headerValue(req, 'payment-mandate');\n const sdJwtCandidate = [mandateHeader, bearer].find((v) => v && SD_JWT_PATTERN.test(v));\n if (sdJwtCandidate) {\n const typ = sniffJwtHeader(sdJwtCandidate)?.typ;\n return {\n protocol: 'vi-sd-jwt',\n artifacts: { viSdJwt: sdJwtCandidate },\n evidence: { typ, ...truncated },\n };\n }\n\n // --- RFC 9421 (Agent Pay / TAP / Web Bot Auth) ------------------------\n const signature = headerValue(req, 'signature');\n const signatureInput = headerValue(req, 'signature-input');\n if (signature && signatureInput) {\n const signatureAgent = headerValue(req, 'signature-agent');\n const registryHint = headerValue(req, 'x-agent-registry');\n const lowerInput = signatureInput.toLowerCase();\n const protocol = signatureAgent\n ? 'rfc9421-web-bot-auth'\n : registryHint?.toLowerCase().includes('visa') || lowerInput.includes('visa')\n ? 'rfc9421-tap'\n : registryHint?.toLowerCase().includes('mastercard') || lowerInput.includes('mastercard')\n ? 'rfc9421-agent-pay'\n : 'rfc9421';\n return {\n protocol,\n artifacts: {\n rfc9421: { headers, method, url, ...(req.bodyText && { body: req.bodyText }) },\n },\n evidence: {\n ...(signatureAgent && { signatureAgent }),\n ...(registryHint && { registryHint }),\n keyid: signatureInput.match(/keyid=\"([^\"]+)\"/)?.[1],\n ...truncated,\n },\n };\n }\n\n // --- ACP (HMAC-signed webhook/checkout: signature WITHOUT signature-input)\n const acpTimestamp = headerValue(req, 'timestamp');\n if (signature && !signatureInput && (acpTimestamp || headerValue(req, 'idempotency-key'))) {\n return {\n protocol: 'acp',\n artifacts: {\n acpRequest: {\n method,\n url,\n headers,\n ...(req.bodyText && { rawBody: req.bodyText }),\n ...(jsonBody && { body: jsonBody }),\n },\n },\n evidence: { hasTimestamp: Boolean(acpTimestamp), ...truncated },\n };\n }\n\n // --- UCP checkout session ---------------------------------------------\n if (/\\/checkout[-_]sessions(\\/|$)/.test(req.uri)) {\n return {\n protocol: 'ucp',\n artifacts: { ucpRequest: { method, url, ...(jsonBody && { body: jsonBody }) } },\n evidence: { path: req.uri, ...truncated },\n };\n }\n\n // --- AP2 mandate triple in the body -----------------------------------\n if (jsonBody) {\n const intent = jsonBody.intent_mandate ?? jsonBody.intentMandate;\n const cart = jsonBody.cart_mandate ?? jsonBody.cartMandate;\n const payment = jsonBody.payment_mandate ?? jsonBody.paymentMandate;\n if (typeof intent === 'string' || typeof cart === 'string' || typeof payment === 'string') {\n return {\n protocol: 'ap2',\n artifacts: {\n ap2Mandates: {\n ...(typeof intent === 'string' && { intent }),\n ...(typeof cart === 'string' && { cart }),\n ...(typeof payment === 'string' && { payment }),\n },\n },\n evidence: {\n mandatesPresent: [\n typeof intent === 'string' && 'intent',\n typeof cart === 'string' && 'cart',\n typeof payment === 'string' && 'payment',\n ].filter(Boolean),\n ...truncated,\n },\n };\n }\n }\n\n // --- MPP (`Authorization: Payment <credential>`) -----------------------\n if (authHeader && /^Payment\\s+/i.test(authHeader)) {\n return {\n protocol: 'mpp',\n artifacts: {\n mppRequest: {\n method,\n url,\n headers,\n ...(req.bodyText && { rawBody: req.bodyText }),\n ...(jsonBody && { body: jsonBody }),\n },\n },\n evidence: truncated,\n };\n }\n\n // --- x402 (X-PAYMENT header) ------------------------------------------\n if (headerValue(req, 'x-payment')) {\n return {\n protocol: 'x402',\n artifacts: {\n x402Request: { method, url, headers, ...(jsonBody && { body: jsonBody }) },\n },\n evidence: truncated,\n };\n }\n\n return undefined;\n}\n","/**\n * Three-tier traffic classification (verified / identified-but-unregistered\n * / anonymous) plus the two non-tiers the gateway touches as little as\n * possible: `human` (zero network calls, zero logging) and `skipped`\n * (static assets / excluded paths).\n *\n * Cheapest checks first — the human path must add microseconds, not\n * milliseconds. Platform signatures are shared with the backend so the\n * edge and verify-access's anonymous handler classify identically.\n */\n\nimport { matchEdgePathRule, type EdgeConfig } from '../edge-config';\nimport { sanitizeHeaders } from '../metadata-capture';\nimport { detectPlatformFingerprint } from '../platform-signatures';\nimport { extractCredentials } from '../verify';\nimport { detectCommerce } from './detect';\nimport { headerValue } from './request';\nimport type { Classification, EffectivePolicy, NormalizedRequest } from './types';\n\n/** Extensions the gateway never classifies — static assets. */\nconst STATIC_EXTENSIONS =\n /\\.(css|js|mjs|map|png|jpe?g|gif|webp|avif|svg|ico|woff2?|ttf|otf|eot|mp4|webm|pdf|txt|xml)$/i;\n\n/**\n * AstraSync's own SDK traffic (`sdkFetch` stamps this UA on every outbound\n * SDK request). Whenever a deployment's API URL transits a gateway-fronted\n * distribution, the SDK's beacon/verify calls re-enter the gateway — and a\n * beacon that gets beaconed is a self-sustaining invocation loop (the 4.4.0\n * staging outage). Self-traffic is therefore a first-class tier: pass\n * through with ZERO beacons, verify calls, or logging, checked BEFORE the\n * credentials step (SDK verify calls carry a Bearer key and would otherwise\n * tier `verified` and re-enter at authenticate/authorize depth).\n *\n * Spoofing: a caller forging this UA gets pass-through — the same treatment\n * anonymous bots already get in both modes (they only dodge the sampled\n * anonymous beacon), and the origin's own auth still applies. No new bypass.\n */\nconst SELF_UA_PATTERN = /^astrasync-sdk\\//i;\n\n/** Non-browser, non-platform CLI/library UA tokens → anonymous bot. */\nconst BOT_UA_PATTERN =\n /curl|wget|python-requests|python-urllib|node-fetch|axios|got|okhttp|go-http-client|libwww|httpie|java\\/|ruby|php|scrapy|headless|phantomjs|selenium|playwright|puppeteer|bot|crawler|spider|slurp/i;\n\n/** Browser-shaped UA. */\nconst BROWSER_UA_PATTERN = /mozilla\\/\\d/i;\n\n/**\n * Resolve the effective mode/depth for a path from the EdgeConfig — ordered\n * first-match-wins rules with case-insensitive globs; no match falls through\n * to the config's top-level defaults. Static extensions are always skipped\n * regardless of rules (a rule can only skip MORE, never un-skip an asset).\n */\nexport function resolvePolicy(config: EdgeConfig, path: string): EffectivePolicy {\n if (STATIC_EXTENSIONS.test(path)) {\n return { mode: config.mode, depth: config.depth, skip: true };\n }\n const rule = matchEdgePathRule(config.pathRules, path);\n if (!rule) return { mode: config.mode, depth: config.depth, skip: false };\n return {\n mode: rule.mode ?? config.mode,\n depth: rule.depth ?? config.depth,\n skip: rule.skip === true,\n };\n}\n\n/**\n * Classify one request. Order (cheapest sufficient evidence wins):\n * 0. AstraSync SDK UA → `self` (own plumbing; never beaconed — loop-proof)\n * 1. X-Astra-* credentials → `verified` candidate\n * 2. commerce-protocol credentials on the wire → `identified`\n * 3. platform UA fingerprint (Claude/ChatGPT/Gemini/…) → `identified`\n * 4. bot-shaped UA / headerless non-browser → `anonymous-bot`\n * 5. everything browser-shaped → `human`\n *\n * `depth: 'classify'` skips step 2 (no body inspection, no header sniffing\n * beyond UA) — that is the zero-friction setting.\n */\nexport function classify(\n req: NormalizedRequest,\n host: string,\n depth: 'classify' | 'authenticate' | 'authorize'\n): Classification {\n const userAgent = headerValue(req, 'user-agent') ?? '';\n\n // 0. Our own SDK's outbound calls (beacons, verify-access, config\n // fetches). MUST precede the credentials check — see SELF_UA_PATTERN.\n if (SELF_UA_PATTERN.test(userAgent)) {\n return { tier: 'self' };\n }\n\n // 1. Native AstraSync credentials.\n const credentials = extractCredentials(req.headers, {});\n if (credentials.astraId || credentials.apiKey || credentials.jwt) {\n return { tier: 'verified', protocol: 'x-astra' };\n }\n\n // The key-format prefix + platform-signal headers are stronger,\n // less-spoofable platform signals than the UA. Compute once (cheap\n // string work) and feed every fingerprint call below.\n const { apiKeyFormat, platformHeaders } = sanitizeHeaders(req.headers);\n const detectionInput = { userAgent, apiKeyFormat, platformHeaders };\n\n // 2. Commerce-protocol credentials (skipped entirely at classify depth).\n if (depth !== 'classify') {\n const commerce = detectCommerce(req, host);\n if (commerce) {\n return {\n tier: 'identified',\n protocol: commerce.protocol,\n artifacts: commerce.artifacts,\n evidence: commerce.evidence,\n fingerprint: detectPlatformFingerprint(detectionInput),\n };\n }\n }\n\n // 3. Platform-agent fingerprint (UA, key-format, or platform header).\n const fingerprint = detectPlatformFingerprint(detectionInput);\n if (fingerprint) {\n return { tier: 'identified', protocol: 'platform-ua', fingerprint };\n }\n\n // 4. Bot-shaped: CLI/library UA, no UA at all, or any non-browser UA —\n // humans arrive with Mozilla-family UAs; everything else is automation.\n if (!userAgent || BOT_UA_PATTERN.test(userAgent) || !BROWSER_UA_PATTERN.test(userAgent)) {\n return { tier: 'anonymous-bot', evidence: { userAgent: userAgent || '(none)' } };\n }\n\n // 4b. Claims to be a browser but is missing every browser fetch-metadata\n // header — headless/spoofed. `sec-fetch-mode` is sent by all evergreen\n // browsers; its absence on a Mozilla UA is a strong bot signal.\n if (!headerValue(req, 'sec-fetch-mode') && !headerValue(req, 'accept-language')) {\n return { tier: 'anonymous-bot', evidence: { userAgent, spoofedBrowser: true } };\n }\n\n // 5. Human traffic — the gateway gets out of the way.\n return { tier: 'human' };\n}\n\n/** Exported for tests. */\nexport const _patterns = { STATIC_EXTENSIONS, BOT_UA_PATTERN, BROWSER_UA_PATTERN, SELF_UA_PATTERN };\n","/**\n * Protocol-specific machine-readable messaging for enforce-mode responses.\n * Agents (not humans) consume these bodies: stable error codes, the\n * failure list, and registration guidance with real URLs.\n */\n\nimport type { TierOutcome } from './types';\n\nconst PROTOCOL_MESSAGES: Record<string, string> = {\n 'vi-sd-jwt':\n 'This request presented Visa Intelligent Commerce credentials, but the agent is not verified with AstraSync. Register the agent to pair your VI credentials with a verified identity and mandate.',\n 'rfc9421-agent-pay':\n 'This request carried a Mastercard Agent Pay signature, but the agent is not verified with AstraSync. Register the agent to pair Agent Pay credentials with a verified identity and mandate.',\n 'rfc9421-tap':\n 'This request carried a Visa TAP signature, but the agent is not verified with AstraSync. Register the agent to pair TAP credentials with a verified identity and mandate.',\n 'rfc9421-web-bot-auth':\n 'This request carried a Web Bot Auth signature, but the agent is not verified with AstraSync. Register the agent to link your signed-agent identity to a verified principal.',\n rfc9421:\n 'This request carried an RFC 9421 HTTP message signature, but the agent is not verified with AstraSync. Register the agent to link the signing identity to a verified principal.',\n acp: 'This request used the Agentic Commerce Protocol, but the agent is not verified with AstraSync. Register the agent to transact on this property.',\n ucp: 'This request used a UCP checkout session, but the agent is not verified with AstraSync. Register the agent to transact on this property.',\n ap2: 'This request presented AP2 mandates, but the agent is not verified with AstraSync. Register the agent to pair your mandates with a verified identity.',\n mpp: 'This request presented MPP payment credentials, but the agent is not verified with AstraSync. Register the agent to transact on this property.',\n x402: 'This request used x402 payment headers, but the agent is not verified with AstraSync. Register the agent to transact on this property.',\n 'platform-ua':\n 'This traffic was identified as a platform AI agent without AstraSync credentials. Register the agent to access this property with a verified identity.',\n 'x-astra':\n 'The presented AstraSync credentials failed verification or were denied by this property’s access policy.',\n};\n\nexport interface DenyBody {\n success: false;\n error: {\n code: 'UNAUTHORIZED' | 'INSUFFICIENT_ACCESS';\n message: string;\n protocol?: string;\n failures: string[];\n correlationId?: string;\n guidance: {\n message?: string;\n registrationUrl?: string;\n documentationUrl?: string;\n /** 5.1.0: MCP-connector steering — the keyless, human-approved path. */\n mcp?: { endpoint: string; discoveryUrl?: string; message: string };\n };\n };\n}\n\n/**\n * Cold-cache fallback for the MCP endpoint, gated to astrasync.ai hosts —\n * the hosted bridge only exists there; a self-hosted deployment must not\n * advertise a dead endpoint.\n */\nfunction fallbackMcpEndpoint(origin: string): string | undefined {\n try {\n const host = new URL(origin).hostname.replace(/^www\\./, '');\n if (host === 'astrasync.ai' || host.endsWith('.astrasync.ai')) return `https://mcp.${host}/mcp`;\n } catch {\n // malformed apiBaseUrl — no fallback\n }\n return undefined;\n}\n\nexport function buildDenyBody(\n outcome: TierOutcome,\n apiBaseUrl: string,\n publicBaseUrl?: string\n): DenyBody {\n // Round-11 two-plane URL doctrine: apiBaseUrl is the VERIFY plane (edge\n // deploys deliberately bake it to the direct origin so verify/beacon calls\n // don't re-enter the CDN Lambda) — but every URL in this body is read by\n // AGENTS, who must only ever see the public host. publicBaseUrl carries it;\n // unset falls back to apiBaseUrl (pre-5.2.0 behavior, correct when the API\n // base IS the public apex). Fixes staging deny bodies steering agents to\n // staging-origin.* hosts incl. the dead mcp.staging-origin fallback.\n const origin = (publicBaseUrl || apiBaseUrl).replace(/\\/api\\/?$/, '');\n const mcpEndpoint = outcome.guidance?.mcp?.endpoint || fallbackMcpEndpoint(origin);\n const protocolMessage =\n (outcome.protocol && PROTOCOL_MESSAGES[outcome.protocol]) ??\n 'This request could not be verified by AstraSync.';\n return {\n success: false,\n error: {\n // UNAUTHORIZED = identity failed (register/re-authenticate helps);\n // INSUFFICIENT_ACCESS = identity fine, policy denied (fix the mandate).\n code: outcome.tier === 'verified' ? 'INSUFFICIENT_ACCESS' : 'UNAUTHORIZED',\n message: protocolMessage,\n ...(outcome.protocol && { protocol: outcome.protocol }),\n failures: outcome.reasons,\n ...(outcome.correlationId && { correlationId: outcome.correlationId }),\n guidance: {\n // `||` not `??`: verify() fills these with EMPTY STRINGS when the\n // well-known cache is cold — empty means \"use the fallback\".\n message:\n outcome.guidance?.message ||\n 'Register this agent with AstraSync to receive verifiable credentials.',\n registrationUrl: outcome.guidance?.registrationUrl || `${origin}/register`,\n documentationUrl: outcome.guidance?.documentationUrl || `${origin}/docs/edge-adapter`,\n ...(mcpEndpoint && {\n mcp: {\n endpoint: mcpEndpoint,\n discoveryUrl:\n outcome.guidance?.mcp?.discoveryUrl ||\n `${mcpEndpoint.replace(/\\/mcp$/, '')}/.well-known/mcp.json`,\n message:\n outcome.guidance?.mcp?.message ||\n 'Inside an MCP host? Add the AstraSync MCP connector at this endpoint instead of the ' +\n 'registration URL — registration through the connector is keyless and human-approved ' +\n '(your human approves in an in-chat card; you never handle credentials).',\n },\n }),\n },\n },\n };\n}\n\nexport interface UnavailableBody {\n success: false;\n error: {\n code: 'VERIFICATION_UNAVAILABLE';\n message: string;\n failures: string[];\n correlationId?: string;\n guidance: { message: string };\n };\n}\n\n/**\n * Enforce-mode 503 for verification-infrastructure failure. Deliberately a\n * different code and status from the 403 deny: a 403 tells the agent to\n * register or fix its mandate (retrying won't help); this tells it the\n * OPPOSITE — identity and policy were never evaluated, retry with backoff.\n */\nexport function buildUnavailableBody(outcome: TierOutcome): UnavailableBody {\n return {\n success: false,\n error: {\n code: 'VERIFICATION_UNAVAILABLE',\n message:\n 'Agent verification is temporarily unavailable and this path enforces verification. ' +\n 'Your identity was not evaluated and no denial was recorded — retry with exponential backoff.',\n failures: outcome.reasons,\n ...(outcome.correlationId && { correlationId: outcome.correlationId }),\n guidance: {\n message: 'Retry the request with exponential backoff; the condition is transient.',\n },\n },\n };\n}\n\nexport interface ManualReviewBody {\n success: false;\n status: 'manual_review';\n message: string;\n stepUpApproval?: { pollUrl?: string; expiresAt?: string };\n correlationId?: string;\n}\n\nexport function buildManualReviewBody(outcome: TierOutcome): ManualReviewBody {\n return {\n success: false,\n status: 'manual_review',\n message:\n 'This action requires human approval. Poll the step-up approval endpoint and retry once approved.',\n ...(outcome.stepUp && { stepUpApproval: outcome.stepUp }),\n ...(outcome.correlationId && { correlationId: outcome.correlationId }),\n };\n}\n","/**\n * X-Astra-Verified-Hop — cross-hop verify-access dedupe marker.\n *\n * Header carrying upstream verify-access proof so an inner-hop endpoint can\n * dedupe (skip verify-access when the same ASTRA-id was already verified a\n * few ms earlier). Emitted by the MCP adapter toward tool fetches and by the\n * edge gateway toward the origin at authenticate/authorize depth. Value\n * format:\n *\n * {astraId};{sessionId};{checkedAt-ms}\n *\n * Receivers MUST validate that `checkedAt` is recent (≤ 60s window\n * recommended) and that `astraId` matches the agent identity claimed on the\n * inner hop. The header alone is NOT proof-of-identity — it's an UNSIGNED\n * dedupe advisory: trust it (`trustVerifiedHop`) only where every network\n * path to the inner hop crosses a stripping gateway or an equivalent trusted\n * boundary, exactly like the unsigned X-AstraSync-* attestation headers.\n * Pair with the existing X-Astra-Id auth.\n */\n\nexport const MCP_VERIFIED_HOP_HEADER = 'X-Astra-Verified-Hop';\n\n/** Default acceptable age (ms) for an X-Astra-Verified-Hop header. */\nexport const MCP_VERIFIED_HOP_MAX_AGE_MS = 60_000;\n\nexport interface VerifiedHopMarker {\n astraId: string;\n sessionId?: string;\n checkedAt: number; // epoch ms\n}\n\nexport function serializeVerifiedHop(marker: VerifiedHopMarker): string {\n return `${marker.astraId};${marker.sessionId ?? ''};${marker.checkedAt}`;\n}\n\nexport function parseVerifiedHop(value: string | undefined | null): VerifiedHopMarker | null {\n if (!value) return null;\n const parts = value.split(';');\n if (parts.length !== 3) return null;\n const [astraId, sessionId, checkedAtRaw] = parts;\n if (!astraId) return null;\n const checkedAt = Number(checkedAtRaw);\n if (!Number.isFinite(checkedAt) || checkedAt <= 0) return null;\n return {\n astraId,\n ...(sessionId ? { sessionId } : {}),\n checkedAt,\n };\n}\n\n/**\n * Returns true when `marker.astraId` matches the inner-hop's claimed\n * ASTRA-id AND the marker is recent enough. Inner-hop middleware uses this\n * to skip a duplicate verify-access call.\n */\nexport function isVerifiedHopValidFor(\n marker: VerifiedHopMarker | null,\n expectedAstraId: string,\n opts: { maxAgeMs?: number; now?: number } = {}\n): boolean {\n if (!marker) return false;\n if (marker.astraId !== expectedAstraId) return false;\n const maxAge = opts.maxAgeMs ?? MCP_VERIFIED_HOP_MAX_AGE_MS;\n const now = opts.now ?? Date.now();\n return now - marker.checkedAt <= maxAge && now >= marker.checkedAt;\n}\n","/**\n * Decision → abstract outcome-application wiring. Executed in BOTH modes\n * so observe mode records exactly what enforce mode would have done — but\n * only enforce mode is allowed to emit anything other than a pass.\n */\n\nimport { buildDenyBody, buildManualReviewBody, buildUnavailableBody } from './messaging';\nimport { MCP_VERIFIED_HOP_HEADER, serializeVerifiedHop } from '../verified-hop';\nimport type { EffectivePolicy, OutcomeApplication, TierOutcome } from './types';\n\n/** Trust-attestation headers injected on allowed requests. */\nexport const ASAT_HEADERS = {\n trustScore: 'X-AstraSync-Trust-Score',\n agentId: 'X-AstraSync-Agent-Id',\n developerId: 'X-AstraSync-Developer-Id',\n observedDecision: 'X-AstraSync-Observed-Decision',\n} as const;\n\n/**\n * Inbound header names an evaluated pass must strip: the gateway's own\n * attestation surface plus the verify-dedupe marker — both are only ever\n * allowed to originate AT the gateway, never from the viewer.\n */\nconst STRIP_HEADER_PREFIXES = ['x-astrasync-', 'x-astra-verified-hop'];\n\n/**\n * A pass that leaves the request completely untouched — used for skipped\n * paths and human traffic, which the gateway must not modify at all.\n */\nexport function passUntouched(): OutcomeApplication {\n return { action: 'pass', injectHeaders: {}, stripHeaderPrefixes: [] };\n}\n\n/**\n * Turn a tier outcome into the abstract application the platform executes.\n * Every evaluated pass strips inbound spoofed `x-astrasync-*` headers\n * (both modes — trust headers must only ever originate at the gateway).\n *\n * Observe mode: always a pass — header hygiene plus an\n * `X-AstraSync-Observed-Decision` stamp for origin-side log correlation.\n *\n * Enforce mode: ALLOW → pass with trust-attestation headers; DENY → 403\n * machine-readable body; MANUAL_REVIEW → 202 with step-up poll info.\n */\nexport function applyOutcome(\n options: { apiBaseUrl: string; publicBaseUrl?: string },\n outcome: TierOutcome,\n policy: EffectivePolicy\n): OutcomeApplication {\n const injectHeaders: Record<string, string> = {};\n\n // Surface a rejected property key in origin logs in BOTH modes — the\n // outcome is allow (fail-open) so the deny stamp below never fires.\n if (outcome.misconfig) {\n injectHeaders[ASAT_HEADERS.observedDecision] = 'misconfig';\n }\n\n if (policy.mode !== 'enforce') {\n // Shadow stamp: what enforce WOULD have done, visible in origin logs.\n if (outcome.decision !== 'allow') {\n injectHeaders[ASAT_HEADERS.observedDecision] = outcome.decision;\n }\n Object.assign(injectHeaders, asatHeaders(outcome), verifiedHopHeader(outcome));\n return { action: 'pass', injectHeaders, stripHeaderPrefixes: STRIP_HEADER_PREFIXES };\n }\n\n switch (outcome.decision) {\n case 'deny':\n // Fail posture follows success posture (4.5.0): an infra-failure deny\n // is a 503 retry-later, never a 403 register-first — the agent's\n // identity was never evaluated.\n if (outcome.unavailable) {\n return {\n action: 'respond',\n status: 503,\n headers: { 'Retry-After': '30' },\n bodyJson: buildUnavailableBody(outcome),\n };\n }\n return {\n action: 'respond',\n status: 403,\n headers: {},\n bodyJson: buildDenyBody(outcome, options.apiBaseUrl, options.publicBaseUrl),\n };\n case 'manual_review':\n return {\n action: 'respond',\n status: 202,\n headers: { 'Retry-After': '30' },\n bodyJson: buildManualReviewBody(outcome),\n };\n default:\n Object.assign(injectHeaders, asatHeaders(outcome), verifiedHopHeader(outcome));\n return { action: 'pass', injectHeaders, stripHeaderPrefixes: STRIP_HEADER_PREFIXES };\n }\n}\n\nfunction asatHeaders(outcome: TierOutcome): Record<string, string> {\n if (!outcome.asat) return {};\n const { trustScore, agentId, developerId } = outcome.asat;\n return {\n ...(trustScore !== undefined && { [ASAT_HEADERS.trustScore]: String(trustScore) }),\n ...(agentId && { [ASAT_HEADERS.agentId]: agentId }),\n ...(developerId && { [ASAT_HEADERS.developerId]: developerId }),\n };\n}\n\n/**\n * Verify-dedupe marker toward the origin. asat is only populated when a\n * verify-access call succeeded (authenticate/authorize depth), so gating on\n * it is the depth gate — classify-depth traffic never carries a marker. An\n * SDK-middleware origin with `trustVerifiedHop` enabled can then skip its\n * duplicate verify-access for the same agent within the freshness window.\n */\nfunction verifiedHopHeader(outcome: TierOutcome): Record<string, string> {\n const agentId = outcome.asat?.agentId;\n if (!agentId) return {};\n return {\n [MCP_VERIFIED_HOP_HEADER]: serializeVerifiedHop({\n astraId: agentId,\n ...(outcome.sessionId && { sessionId: outcome.sessionId }),\n checkedAt: Date.now(),\n }),\n };\n}\n","/**\n * Shared purpose/action resolver for the HTTP adapters (express + nextjs) —\n * the vocabulary-unification layer.\n *\n * The PDLSS two-axis contract: `purpose` = bare category noun (`shopping`,\n * `data`, custom nouns like `trading`); `action` = dotted verb\n * (`shopping.search`) or an enumerated transport token. Transport verbs\n * (GET/POST/...) NEVER travel as PDLSS actions — they map through the pinned\n * method table below.\n *\n * SELF-CONTAINED on purpose: this published package cannot depend on the\n * private @astrasyncai/pdlss-vocab workspace package, so the constants are\n * duplicated here and pinned strictly equal by a monorepo CI test\n * (vocab-equality.test.ts). Change them in BOTH places or that test fails.\n */\n\n/** Pinned method→action derivation table. */\nexport const HTTP_METHOD_ACTION_TABLE: Readonly<Record<string, string>> = {\n GET: 'data.read',\n HEAD: 'data.read',\n OPTIONS: 'data.read',\n POST: 'data.write',\n PUT: 'data.write',\n PATCH: 'data.write',\n DELETE: 'data.delete',\n};\n\n/** Unknown methods are treated as mutating until proven otherwise. */\nexport const DEFAULT_HTTP_ACTION = 'data.write';\n\n/** Generic category emitted when nothing supplies a domain purpose. */\nexport const DEFAULT_HTTP_PURPOSE = 'data';\n\nexport function actionForHttpMethod(method: string): string {\n return HTTP_METHOD_ACTION_TABLE[method.toUpperCase()] ?? DEFAULT_HTTP_ACTION;\n}\n\nexport type HttpPurposeSource =\n | 'route_config'\n | 'custom_extractor'\n | 'header'\n | 'legacy_header'\n | 'query'\n | 'action_derived'\n | 'transport_default';\n\nexport type HttpActionSource =\n | 'route_config'\n | 'custom_extractor'\n | 'header'\n | 'purpose_header_derived'\n | 'method_table';\n\nexport interface HttpPdlssInput {\n method: string;\n /** `X-Astra-Purpose` header value (agent's declaration). */\n astraPurpose?: string;\n /** `X-Astra-Action` header value (agent's declaration, symmetric with MCP). */\n astraAction?: string;\n /** Legacy `x-purpose` header — deprecated, removal scheduled for 4.0.0. */\n legacyPurpose?: string;\n /** Legacy `?purpose` query param (express only) — deprecated, removal 4.0.0. */\n queryPurpose?: string;\n /** Dashboard route config send-mapping (RouteAccessConfig.purpose/.action). */\n routePurpose?: string;\n routeAction?: string;\n /** Results of the merchant's extractPurpose/extractAction options. */\n customPurpose?: string;\n hasCustomPurposeExtractor?: boolean;\n customAction?: string;\n hasCustomActionExtractor?: boolean;\n}\n\nexport interface HttpPdlssResolution {\n purpose: string;\n action: string;\n purposeSource: HttpPurposeSource;\n actionSource: HttpActionSource;\n}\n\n/**\n * Normalize an `X-Astra-Purpose` header value.\n * - colon form `\"category:action\"` (legacy wire shape): take the prefix; the\n * remainder is free-text and exists in no vocabulary — discard it and let\n * the method table supply the action (matches pre-3.1.0 discard behavior).\n * - dotted form `\"shopping.purchase\"` (the shape older docs taught): prefix\n * becomes the purpose, the WHOLE token becomes an action candidate.\n * - bare token: purpose verbatim.\n */\nexport function normalizePurposeHeader(value: string): {\n purpose: string;\n actionCandidate?: string;\n} {\n const colon = value.indexOf(':');\n if (colon >= 0) {\n return { purpose: value.slice(0, colon) };\n }\n const dot = value.indexOf('.');\n if (dot > 0 && dot < value.length - 1) {\n return { purpose: value.slice(0, dot), actionCandidate: value };\n }\n return { purpose: value };\n}\n\n/**\n * Resolve the {purpose, action} pair for one HTTP request.\n *\n * Precedence (both axes):\n * action: route mapping → extractAction option → X-Astra-Action header →\n * candidate from a dotted X-Astra-Purpose → pinned method table\n * purpose: route mapping → extractPurpose option → X-Astra-Purpose →\n * legacy x-purpose / ?purpose → category prefix of the resolved\n * action → 'data'\n *\n * A configured custom extractor masks the header/legacy/query steps of its\n * axis (it replaces the default chain, as extractPurpose always has); when it\n * returns undefined the axis falls through to the table/prefix fallback.\n * The route mapping is merchant policy fetched from the dashboard — it\n * outranks agent-supplied headers the way MCP toolGates do.\n */\nexport function resolveHttpPdlss(input: HttpPdlssInput): HttpPdlssResolution {\n const fromHeader = input.astraPurpose ? normalizePurposeHeader(input.astraPurpose) : undefined;\n\n // ── Action axis ──\n let action: string;\n let actionSource: HttpActionSource;\n if (input.routeAction) {\n action = input.routeAction;\n actionSource = 'route_config';\n } else if (input.hasCustomActionExtractor && input.customAction) {\n action = input.customAction;\n actionSource = 'custom_extractor';\n } else if (!input.hasCustomActionExtractor && input.astraAction) {\n action = input.astraAction;\n actionSource = 'header';\n } else if (!input.hasCustomActionExtractor && fromHeader?.actionCandidate) {\n action = fromHeader.actionCandidate;\n actionSource = 'purpose_header_derived';\n } else {\n action = actionForHttpMethod(input.method);\n actionSource = 'method_table';\n }\n\n // ── Purpose axis ──\n let purpose: string | undefined;\n let purposeSource: HttpPurposeSource | undefined;\n if (input.routePurpose) {\n purpose = input.routePurpose;\n purposeSource = 'route_config';\n } else if (input.hasCustomPurposeExtractor) {\n if (input.customPurpose) {\n purpose = input.customPurpose;\n purposeSource = 'custom_extractor';\n }\n } else if (fromHeader) {\n purpose = fromHeader.purpose;\n purposeSource = 'header';\n } else if (input.legacyPurpose) {\n purpose = input.legacyPurpose;\n purposeSource = 'legacy_header';\n } else if (input.queryPurpose) {\n purpose = input.queryPurpose;\n purposeSource = 'query';\n }\n\n if (!purpose) {\n // Keep the pair coherent: an agent that sent only X-Astra-Action (or a\n // route that mapped only the action) gets that action's own category.\n const dot = action.indexOf('.');\n if (dot > 0) {\n purpose = action.slice(0, dot);\n purposeSource = 'action_derived';\n } else {\n purpose = DEFAULT_HTTP_PURPOSE;\n purposeSource = 'transport_default';\n }\n }\n\n return { purpose, action, purposeSource: purposeSource!, actionSource };\n}\n","/**\n * Time-budgeted event emission.\n *\n * Some edge runtimes (Lambda@Edge) have no background-work scheduler —\n * anything not awaited before the handler returns may never run. So every\n * telemetry call is awaited under an explicit budget and DROPPED on\n * timeout: latency to the customer's traffic is bounded, and a slow\n * AstraSync API costs telemetry, never page loads. Runtimes that provide\n * `waitUntil` (Cloudflare Workers, Vercel Edge, Fastly Compute) can pass\n * it via {@link EdgeCoreOptions.waitUntil} to take beacons off the latency\n * path entirely.\n */\n\nimport { reportUnregisteredAttempt } from '../verify';\nimport { buildObservedMetadata, headerValue } from './request';\nimport type { Classification, EdgeCoreOptions, NormalizedRequest } from './types';\n\n/** Await `promise` for at most `ms`; resolve `undefined` on timeout/error. */\nexport async function withBudget<T>(promise: Promise<T>, ms: number): Promise<T | undefined> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<undefined>((resolve) => {\n timer = setTimeout(() => resolve(undefined), ms);\n }),\n ]);\n } catch {\n return undefined;\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\n/**\n * Emit an unregistered-attempt beacon for `identified` (non-crypto depths)\n * and sampled `anonymous-bot` traffic. Unauthenticated by design; the\n * backend fingerprints the UA and find-or-provisions platform agents\n * server-side.\n */\nexport async function emitBeacon(\n options: EdgeCoreOptions,\n req: NormalizedRequest,\n classification: Classification,\n budgetMs: number\n): Promise<void> {\n const budgeted = withBudget(\n reportUnregisteredAttempt(\n { apiBaseUrl: options.apiBaseUrl, counterpartyId: options.counterpartyId },\n {\n counterpartyUrl: options.counterpartyUrl,\n counterpartyType: 'website',\n sourceIp: req.clientIp,\n userAgent: headerValue(req, 'user-agent'),\n requestPath: req.uri,\n requestMethod: req.method,\n // Evidence fields the backend persists into the event record.\n protocol: classification.protocol,\n evidence: classification.evidence,\n // The full sanitized header + connection capture for the\n // unregistered caller (fire-and-forget, so free).\n observedMetadata: buildObservedMetadata(req),\n }\n ),\n budgetMs\n );\n if (options.waitUntil) {\n options.waitUntil(budgeted);\n return;\n }\n await budgeted;\n}\n\n/** Deterministic-in-tests sampling gate. */\nexport function sampled(rate: number, random: () => number = Math.random): boolean {\n if (rate <= 0) return false;\n if (rate >= 1) return true;\n return random() < rate;\n}\n","/**\n * Depth-controlled verification per tier. The edge never verifies\n * credentials itself — it forwards what it detected to verify-access, the\n * canonical sole verification sink (the backend runs the commerce\n * pipeline, records events, provisions unregistered platform agents,\n * persists sessions). What the depth setting controls is how much the edge\n * LOOKS and how much it FORWARDS:\n *\n * classify — what is it? UA tiers only. Zero verify-access calls;\n * beacons only.\n * authenticate — who is it? + protocol detection. X-Astra agents get a\n * verify-access identity check; commerce/platform traffic\n * is beaconed with protocol + evidence (no signature\n * verification anywhere).\n * authorize — are they allowed? + artifact forwarding. X-Astra verify\n * calls carry commerceArtifacts; identified traffic gets an\n * anonymous verify-access call with artifacts +\n * callerMetadata so the backend cryptographically proves\n * and policy-evaluates once.\n */\n\nimport { resolveHttpPdlss } from '../adapters/http-pdlss';\nimport type { GatewayConfig, VerificationRequest } from '../types';\nimport { verify, extractCredentials } from '../verify';\nimport { withBudget, emitBeacon, sampled } from './events';\nimport { buildObservedMetadata, headerValue } from './request';\nimport type {\n Classification,\n EdgeCoreOptions,\n EffectivePolicy,\n NormalizedRequest,\n TierOutcome,\n} from './types';\n\nfunction baseOutcome(classification: Classification): TierOutcome {\n return {\n tier: classification.tier,\n decision: 'allow',\n reasons: [],\n protocol: classification.protocol,\n };\n}\n\nexport function buildVerificationRequest(\n options: EdgeCoreOptions,\n req: NormalizedRequest,\n classification: Classification,\n includeArtifacts: boolean\n): VerificationRequest {\n // verify-access REQUIRES a purpose. Resolve via the shared chain: the\n // agent's X-Astra-Purpose/-Action declarations, else the pinned method\n // table (GET → data/data.read etc.) — a transport verb never travels as\n // a permission action.\n const pdlss = resolveHttpPdlss({\n method: req.method,\n astraPurpose: headerValue(req, 'x-astra-purpose'),\n astraAction: headerValue(req, 'x-astra-action'),\n });\n // Forward the caller's attempt-chain handle when well-formed\n // (agent-declared, like x-astra-purpose — not a trust header, so no\n // spoof-strip needed). The edge synthesises NO consideration data — it\n // can't see offer semantics; pure pass-through.\n const attemptId = headerValue(req, 'x-astra-attempt-id');\n return {\n ...(attemptId && /^att_[0-9a-f]{32}$/.test(attemptId) && { attemptId }),\n credentials: extractCredentials(req.headers, {}),\n purpose: pdlss.purpose,\n action: pdlss.action,\n resource: req.uri,\n createSession: true,\n counterpartyType: 'website',\n counterpartyUrl: options.counterpartyUrl,\n callerMetadata: {\n sourceIp: req.clientIp,\n userAgent: headerValue(req, 'user-agent'),\n referer: headerValue(req, 'referer'),\n host: headerValue(req, 'host'),\n // The full sanitized header + connection capture. The backend stores\n // it fire-and-forget (zero decision latency) and uses the key-format\n // / platform headers for attribution.\n observedMetadata: buildObservedMetadata(req),\n },\n ...(includeArtifacts &&\n classification.artifacts && { commerceArtifacts: classification.artifacts }),\n };\n}\n\nexport function outcomeFromVerifyResult(\n classification: Classification,\n result: Awaited<ReturnType<typeof verify>>\n): TierOutcome {\n const outcome = baseOutcome(classification);\n outcome.sessionId = (result as { sessionId?: string }).sessionId;\n outcome.correlationId = result.correlationId;\n outcome.guidance = result.guidance;\n\n // The PROPERTY'S own API key was rejected by the backend — neither an\n // agent deny nor an infra failure. Fail OPEN in both modes: agents must\n // not be blocked by the property's dead key. The misconfig flag stamps\n // X-AstraSync-Observed-Decision so origin logs surface it; the owner is\n // alerted server-side on every rejected call.\n if (result.misconfigured) {\n outcome.reasons = ['verification key misconfigured — fail-open (merchant_misconfig)'];\n outcome.misconfig = true;\n return outcome;\n }\n\n if (result.requiresStepUp || result.stepUpApproval) {\n outcome.decision = 'manual_review';\n outcome.reasons = ['step-up approval required'];\n outcome.stepUp = {\n pollUrl: (result.stepUpApproval as { pollUrl?: string } | undefined)?.pollUrl,\n expiresAt: (result.stepUpApproval as { expiresAt?: string } | undefined)?.expiresAt,\n };\n return outcome;\n }\n\n if (!result.identityVerified || !result.policyAllowed) {\n outcome.decision = 'deny';\n outcome.reasons = result.denialReasons?.length\n ? result.denialReasons\n : [!result.identityVerified ? 'identity not verified' : 'denied by access policy'];\n return outcome;\n }\n\n outcome.asat = {\n trustScore: result.agent?.trustScore,\n agentId: result.agent?.astraId,\n developerId: result.developer?.astradId,\n };\n return outcome;\n}\n\n/**\n * Fail posture follows success posture (4.5.0): when verification\n * infrastructure is unreachable, observe mode passes through with the\n * reason recorded, while enforce mode denies with `unavailable: true`\n * (rendered as a 503 retry-later, never a 403 register-first — the backend\n * never evaluated the caller, so no denial semantics may be claimed).\n */\nfunction unavailableOutcome(\n classification: Classification,\n policy: EffectivePolicy,\n reason: string,\n correlationId?: string\n): TierOutcome {\n const outcome = baseOutcome(classification);\n outcome.unavailable = true;\n outcome.reasons = [reason];\n if (correlationId) outcome.correlationId = correlationId;\n if (policy.mode === 'enforce') outcome.decision = 'deny';\n return outcome;\n}\n\n/**\n * A verify() result whose failure is the SDK's typed api_error fallback —\n * infra unavailability that verify() shaped as a deny-like result. Must not\n * match merchant_misconfigured (deterministic, handled fail-open).\n */\nfunction isApiErrorResult(result: Awaited<ReturnType<typeof verify>>): boolean {\n return (\n (result.failures ?? []).some((f) => f.dimension === 'verify_access.api_error') === true &&\n !result.misconfigured\n );\n}\n/**\n * Run the tier-appropriate verification/telemetry for one classified\n * request. NEVER throws. Infra-failure handling is posture-symmetric (see\n * `unavailableOutcome`); a presented credential the BACKEND rejected\n * remains a real deny in both modes, and the property's own rejected key\n * (misconfig) remains fail-open in both modes. Internal pipeline\n * exceptions (the catch below) stay fail-open unconditionally — they are\n * gateway bugs, not verification availability, and must never take a site\n * down.\n */\nexport async function runTier(\n options: EdgeCoreOptions,\n req: NormalizedRequest,\n classification: Classification,\n policy: EffectivePolicy,\n apiKey: string | undefined,\n sampling: { anonymousBeaconRate: number }\n): Promise<TierOutcome> {\n const budgets = options.budgets ?? {};\n const beaconMs = budgets.beaconMs ?? 300;\n const verifyMs =\n policy.mode === 'enforce'\n ? (budgets.verifyEnforceMs ?? 3000)\n : (budgets.verifyObserveMs ?? 1500);\n\n const gatewayConfig: GatewayConfig = {\n apiBaseUrl: options.apiBaseUrl,\n ...(apiKey && { apiKey }),\n counterpartyId: options.counterpartyId,\n // The gateway handles its own error semantics; init self-probes don't\n // belong in a per-request edge function.\n disableInitChecks: true,\n } as GatewayConfig;\n\n try {\n switch (classification.tier) {\n case 'verified': {\n // classify depth = zero API calls, even for credentialed agents.\n if (policy.depth === 'classify') {\n return baseOutcome(classification);\n }\n const result = await withBudget(\n verify(\n gatewayConfig,\n buildVerificationRequest(options, req, classification, policy.depth === 'authorize')\n ),\n verifyMs\n );\n if (!result) {\n return unavailableOutcome(\n classification,\n policy,\n 'verify-access unreachable within budget'\n );\n }\n if (isApiErrorResult(result)) {\n return unavailableOutcome(\n classification,\n policy,\n result.denialReasons?.[0] ?? 'verify-access api error',\n result.correlationId\n );\n }\n return outcomeFromVerifyResult(classification, result);\n }\n\n case 'identified': {\n if (policy.depth === 'authorize' && classification.artifacts) {\n // Anonymous verify-access call WITH artifacts: the backend runs\n // the commerce pipeline, records unverified events, and\n // provisions unregistered platform agents — one sink, recorded\n // once.\n const result = await withBudget(\n verify(gatewayConfig, buildVerificationRequest(options, req, classification, true)),\n verifyMs\n );\n if (!result) {\n return unavailableOutcome(\n classification,\n policy,\n 'verify-access unreachable within budget'\n );\n }\n if (isApiErrorResult(result)) {\n return unavailableOutcome(\n classification,\n policy,\n result.denialReasons?.[0] ?? 'verify-access api error',\n result.correlationId\n );\n }\n return outcomeFromVerifyResult(classification, result);\n }\n // classify/credentials depth (or no artifacts): lightweight beacon.\n await emitBeacon(options, req, classification, beaconMs);\n const outcome = baseOutcome(classification);\n if (policy.mode === 'enforce' && policy.depth !== 'classify') {\n // Unregistered agent on an enforced path: deny with guidance.\n outcome.decision = 'deny';\n outcome.reasons = ['agent is not registered with AstraSync'];\n }\n return outcome;\n }\n\n case 'anonymous-bot': {\n if (sampled(sampling.anonymousBeaconRate, options.random)) {\n await emitBeacon(\n options,\n req,\n { ...classification, protocol: classification.protocol ?? 'ua-heuristic' },\n beaconMs\n );\n }\n // Anonymous bots pass through even in enforce mode — enforce gates\n // AGENT traffic; generic bot management stays the CDN/WAF's job.\n return baseOutcome(classification);\n }\n\n default:\n return baseOutcome(classification);\n }\n } catch (err) {\n const outcome = baseOutcome(classification);\n outcome.reasons = [\n `edge pipeline error — fail-open: ${err instanceof Error ? err.message : String(err)}`,\n ];\n return outcome;\n }\n}\n","/**\n * The platform-neutral evaluation pipeline for one request:\n *\n * path policy → classify → tier pipeline → outcome application\n *\n * Platform adapters own everything around this: config/secret loading,\n * request normalization, and applying the returned application onto their\n * native request/response shapes. `evaluateEdgeRequest` NEVER throws — any\n * internal failure resolves to an untouched pass (the gateway must never\n * take the site down).\n */\n\nimport type { EdgeConfig } from '../edge-config';\nimport { classify, resolvePolicy } from './classify';\nimport { applyOutcome, passUntouched } from './enforce';\nimport { runTier } from './pipeline';\nimport { headerValue } from './request';\nimport type {\n Classification,\n EdgeCoreOptions,\n EffectivePolicy,\n NormalizedRequest,\n OutcomeApplication,\n TierOutcome,\n} from './types';\n\nexport interface EdgeEvaluation {\n application: OutcomeApplication;\n policy: EffectivePolicy;\n /** Absent when the path was skipped before classification. */\n classification?: Classification;\n /** Absent for skipped paths and human/self traffic (no pipeline run). */\n outcome?: TierOutcome;\n}\n\n/**\n * Evaluate one normalized request against the effective EdgeConfig.\n *\n * - Skipped paths (static assets / skip rules): untouched, zero work.\n * - Humans and self (AstraSync SDK) traffic: get out of the way. No calls,\n * no logs, no header changes.\n * - Everything else runs the tier pipeline and yields an application the\n * platform must execute (pass with header hygiene, or an enforce-mode\n * response).\n */\nexport async function evaluateEdgeRequest(\n options: EdgeCoreOptions,\n req: NormalizedRequest,\n config: EdgeConfig,\n apiKey: string | undefined\n): Promise<EdgeEvaluation> {\n const policy = resolvePolicy(config, req.uri);\n try {\n if (policy.skip) return { policy, application: passUntouched() };\n\n const host =\n headerValue(req, 'x-forwarded-host') ??\n headerValue(req, 'host') ??\n new URL(options.counterpartyUrl).host;\n\n const classification = classify(req, host, policy.depth);\n\n // Human and self (own-SDK) traffic: get out of the way. No calls, no\n // logs, no header changes. Self MUST short-circuit here — running it\n // through the tier pipeline would let a beacon spawn a beacon.\n if (classification.tier === 'human' || classification.tier === 'self') {\n return { policy, classification, application: passUntouched() };\n }\n\n const outcome = await runTier(options, req, classification, policy, apiKey, config.sampling);\n\n if (outcome.decision !== 'allow') {\n options.log?.(\n 'info',\n policy.mode === 'enforce'\n ? `${outcome.decision.toUpperCase()}: ${req.method} ${req.uri}`\n : `[OBSERVE] would have been ${outcome.decision.toUpperCase()}: ${req.method} ${req.uri}`,\n { tier: outcome.tier, protocol: outcome.protocol, reasons: outcome.reasons }\n );\n }\n\n return {\n policy,\n classification,\n outcome,\n application: applyOutcome(options, outcome, policy),\n };\n } catch (err) {\n // Fail-open, unconditionally.\n options.log?.('error', 'edge evaluation error — passing request through', {\n error: err instanceof Error ? err.message : String(err),\n });\n return { policy, application: passUntouched() };\n }\n}\n"],"mappings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EAChD;AACF;","names":["has","result"]}
|
|
1
|
+
{"version":3,"sources":["../../src/edge-core/index.ts","../../src/version.ts","../../src/http.ts","../../src/edge-config.ts","../../src/metadata-capture.ts","../../src/platform-signatures.ts","../../src/trust-levels.ts","../../src/well-known.ts","../../src/verify.ts","../../src/edge-core/request.ts","../../src/edge-core/detect.ts","../../src/edge-core/classify.ts","../../src/edge-core/messaging.ts","../../src/verified-hop.ts","../../src/edge-core/enforce.ts","../../src/adapters/http-pdlss.ts","../../src/edge-core/events.ts","../../src/edge-core/pipeline.ts","../../src/edge-core/evaluate.ts"],"sourcesContent":["/**\n * AstraSync Trusted Agent Gateway — platform-neutral edge core.\n *\n * The shared classification/detection/verification/enforcement pipeline\n * behind the AstraSync edge adapters (`@astrasyncai/adapter-lambda`,\n * `@astrasyncai/adapter-edge`). Platform packages normalize their native\n * request shape into a {@link NormalizedRequest}, call\n * {@link evaluateEdgeRequest}, and apply the returned\n * {@link OutcomeApplication} onto their native primitives.\n */\n\nexport { classify, resolvePolicy, _patterns } from './classify';\nexport { detectCommerce, type DetectedCommerce } from './detect';\nexport { evaluateEdgeRequest, type EdgeEvaluation } from './evaluate';\nexport { applyOutcome, passUntouched, ASAT_HEADERS } from './enforce';\nexport { withBudget, emitBeacon, sampled } from './events';\nexport {\n buildDenyBody,\n buildManualReviewBody,\n type DenyBody,\n type ManualReviewBody,\n} from './messaging';\nexport { runTier, buildVerificationRequest, outcomeFromVerifyResult } from './pipeline';\nexport { headerValue, requestUrl, buildObservedMetadata } from './request';\nexport type {\n NormalizedRequest,\n PlatformIo,\n OutcomeApplication,\n TrafficTier,\n Classification,\n EdgeDecision,\n TierOutcome,\n EffectivePolicy,\n EdgeCoreOptions,\n EdgeLogger,\n} from './types';\n","/**\n * Single source-of-truth for the SDK's\n * package version emitted on verify-access bodies (and any future\n * telemetry). Bumped alongside `package.json#version` on every release.\n *\n * Why a constant rather than `import pkg from '../package.json'`:\n * - `tsconfig.json` sets `rootDir: ./src`; importing the sibling\n * package.json fails the build with \"outside rootDir\".\n * - Build-time string replacement (tsup `define`, esbuild banner, etc.)\n * adds toolchain coupling for a trivial gain.\n * - Embedded readonly constant works in every environment (Node, browser,\n * bundlers, Deno) without runtime fs / network access.\n *\n * Release discipline: a CI lint can grep `package.json#version` against\n * this constant if the two ever diverge in the wild. A manual bump\n * is fine — bumping both in the release-ceremony commit keeps them\n * lockstep.\n */\nexport const SDK_VERSION = '5.6.0';\n","/**\n * Shared outbound-HTTP wrapper — every request the SDK makes to the\n * AstraSync backend (or anywhere else) goes through `sdkFetch` so it\n * carries an identifying User-Agent.\n *\n * Why: Node's global fetch defaults to `user-agent: node`, which is\n * indistinguishable from every other Node client on the wire. Visit\n * Intelligence observed our own SDK/beacon traffic as anonymous \"node\"\n * visits. Self-identification is the platform's own medicine.\n *\n * Browser note: some browsers filter the User-Agent request header\n * silently (never throwing), so this is a no-op there — which is correct:\n * in a browser the page's real UA is the honest identity.\n */\n\nimport { SDK_VERSION } from './version';\n\nexport const SDK_USER_AGENT = `astrasync-sdk/${SDK_VERSION}`;\n\n/**\n * Add the SDK User-Agent without changing the SHAPE of the caller's headers\n * (plain records stay plain records) — interceptors, adapters, and tests\n * read `init.headers` as a record, and `Headers` would also lowercase names.\n */\nfunction withUserAgent(initHeaders: HeadersInit | undefined): HeadersInit {\n if (!initHeaders) return { 'user-agent': SDK_USER_AGENT };\n if (initHeaders instanceof Headers) {\n const copy = new Headers(initHeaders);\n if (!copy.has('user-agent')) copy.set('user-agent', SDK_USER_AGENT);\n return copy;\n }\n if (Array.isArray(initHeaders)) {\n const has = initHeaders.some(([name]) => name.toLowerCase() === 'user-agent');\n return has ? initHeaders : [...initHeaders, ['user-agent', SDK_USER_AGENT]];\n }\n const has = Object.keys(initHeaders).some((name) => name.toLowerCase() === 'user-agent');\n return has ? initHeaders : { 'user-agent': SDK_USER_AGENT, ...initHeaders };\n}\n\nexport const sdkFetch: typeof fetch = (input, init) =>\n fetch(input, { ...init, headers: withUserAgent(init?.headers) });\n","/**\n * Edge verification config — the per-endpoint policy the Trusted Agent\n * Gateway edge adapters (e.g. `@astrasyncai/adapter-lambda`) fetch from the\n * AstraSync dashboard to decide how much verification friction to apply\n * to inbound traffic, and where.\n *\n * Fetch pattern mirrors `well-known.ts`: TTL cache + stale-while-revalidate\n * + in-flight dedupe, with a `_reset*` hook for tests. Fail posture is\n * deliberately asymmetric: this module can NEVER put a site into enforce\n * mode on its own — enforce only ever originates from a successfully\n * fetched config, and a config that has gone stale past `maxStaleMs`\n * degrades back to observe.\n *\n * Which EdgeConfig fields each integration consumes:\n *\n * | Field | Edge adapters | SDK adapters (express/nextjs/mcp) |\n * | ------------------------------ | ------------- | --------------------------------- |\n * | `mode` (observe/enforce) | yes | — |\n * | `depth` | yes | — |\n * | `pathRules` | yes | — |\n * | `sampling.anonymousBeaconRate` | yes | yes — the SDK anonymous beacon |\n * | `failurePosture` | yes | — |\n *\n * The observe/enforce × depth posture is EDGE-ONLY by design: SDK adapters\n * enforce via the dashboard route policy (`fetchRoutes`), not via this\n * config, and consume only the `sampling` block for their anonymous\n * traffic beacon.\n */\n\nimport { sdkFetch } from './http';\nimport type { GatewayConfig } from './types';\n\n/**\n * Edge posture. Canonical Trusted Agent Gateway vocabulary:\n * `observe` ≈ the gateway's `passive` posture (verify +\n * record, enforce nothing), `enforce` ≈ `active`. New value set on a new\n * field name — do NOT reuse `GatewayPosture`'s `active`/`passive` here\n * (different field, different meaning: posture governs an agent-side\n * gateway; mode governs counterparty-side edge interception).\n */\nexport type EdgeMode = 'observe' | 'enforce';\n\n/**\n * How deep the edge checks each request — what is it → who is it → are\n * they allowed:\n * - `classify` — UA / platform-fingerprint classification only; no\n * credential handling.\n * - `authenticate` — establish who is calling: detect and parse agent\n * credentials (X-Astra-*, VI SD-JWT, RFC 9421, ACP,\n * UCP, AP2…) and verify presented AstraSync identities.\n * - `authorize` — full policy decision: credentials cryptographically\n * proven and PDLSS-evaluated via a verify-access round\n * trip. (US spelling on the wire, matching\n * `authorizeSettlement` and HTTP `Authorization`.)\n */\nexport type EdgeVerificationDepth = 'classify' | 'authenticate' | 'authorize';\n\nexport interface EdgePathRule {\n /**\n * `*`-wildcard glob matched against the request path. Matching is\n * case-INsensitive and all regex metacharacters except `*` are\n * escaped. (Deliberately diverges from the express adapter's\n * `matchRoute`, which is historically case-sensitive by default —\n * new surface ships case-insensitive matching as the default.)\n */\n pattern: string;\n /** Pass the request through untouched (static assets); mode/depth ignored. */\n skip?: boolean;\n /** Override the top-level mode for this path. */\n mode?: EdgeMode;\n /** Override the top-level depth for this path. */\n depth?: EdgeVerificationDepth;\n}\n\nexport interface EdgeConfig {\n /** Shape version — bump on breaking changes. */\n version: 1;\n /** Default posture for paths no rule matches. */\n mode: EdgeMode;\n /** Default check depth for paths no rule matches. */\n depth: EdgeVerificationDepth;\n /** Ordered, first-match-wins. */\n pathRules: EdgePathRule[];\n sampling: {\n /** Fraction (0..1) of anonymous-bot requests that emit a beacon. */\n anonymousBeaconRate: number;\n };\n /**\n * 4.5.0: the EFFECTIVE failure posture is derived from the effective\n * mode — fail posture follows success posture. Observe fails open\n * (unreachable backend = pass-through, site never breaks); enforce fails\n * closed on verification-infrastructure failure (503\n * `VERIFICATION_UNAVAILABLE`, retry-later — see edge-core/pipeline). This\n * field is retained on the wire for adapter compatibility and as a future\n * explicit override; it is not consulted by the 4.5.x pipeline. Note the\n * distinction from CONFIG staleness: a config stale past 24h still has\n * enforce degraded to observe (`degradeToObserve`) — that is config-trust\n * hygiene, independent of runtime verification availability.\n */\n failurePosture: 'open' | 'closed';\n}\n\n/**\n * The safe default: observe-only, classification depth, nothing enforced.\n * Served by the backend when an endpoint has never been configured, and\n * used by `getEdgeConfig` whenever no config can be fetched.\n */\nexport const DEFAULT_EDGE_CONFIG: EdgeConfig = Object.freeze({\n version: 1,\n mode: 'observe',\n depth: 'classify',\n pathRules: [],\n sampling: Object.freeze({ anonymousBeaconRate: 0.1 }),\n failurePosture: 'open',\n}) as EdgeConfig;\n\nconst EDGE_MODES: readonly string[] = ['observe', 'enforce'];\nconst EDGE_DEPTHS: readonly string[] = ['classify', 'authenticate', 'authorize'];\n\n/** Structural guard for configs arriving over the wire. */\nexport function isEdgeConfig(value: unknown): value is EdgeConfig {\n if (typeof value !== 'object' || value === null) return false;\n const v = value as Record<string, unknown>;\n if (v.version !== 1) return false;\n if (!EDGE_MODES.includes(v.mode as string)) return false;\n if (!EDGE_DEPTHS.includes(v.depth as string)) return false;\n if (!Array.isArray(v.pathRules)) return false;\n for (const rule of v.pathRules) {\n if (typeof rule !== 'object' || rule === null) return false;\n const r = rule as Record<string, unknown>;\n if (typeof r.pattern !== 'string' || r.pattern.length === 0) return false;\n if (r.mode !== undefined && !EDGE_MODES.includes(r.mode as string)) return false;\n if (r.depth !== undefined && !EDGE_DEPTHS.includes(r.depth as string)) return false;\n }\n const sampling = v.sampling as Record<string, unknown> | undefined;\n if (\n typeof sampling !== 'object' ||\n sampling === null ||\n typeof sampling.anonymousBeaconRate !== 'number' ||\n sampling.anonymousBeaconRate < 0 ||\n sampling.anonymousBeaconRate > 1\n ) {\n return false;\n }\n return v.failurePosture === 'open';\n}\n\nexport interface FetchEdgeConfigSuccess {\n edgeConfig: EdgeConfig;\n etag?: string;\n}\n\nexport type FetchEdgeConfigResult = FetchEdgeConfigSuccess | { notModified: true } | null;\n\n/**\n * Fetch the edge config for an endpoint from the AstraSync backend.\n * `GET {apiBaseUrl}/endpoints/:counterpartyId/edge-config` with the same\n * auth headers as `fetchRoutes`. Pass the cached `etag` to get a cheap\n * `{ notModified: true }` on 304. Returns `null` on any failure —\n * the caller decides how to fall back.\n */\nexport async function fetchEdgeConfig(\n config: Pick<GatewayConfig, 'apiBaseUrl' | 'apiKey'>,\n counterpartyId: string,\n opts?: { etag?: string; timeoutMs?: number }\n): Promise<FetchEdgeConfigResult> {\n if (!counterpartyId) return null;\n const headers: Record<string, string> = { Accept: 'application/json' };\n if (config.apiKey) {\n headers['Authorization'] = `Bearer ${config.apiKey}`;\n headers['X-API-Key'] = config.apiKey;\n }\n if (opts?.etag) headers['If-None-Match'] = opts.etag;\n try {\n const response = await sdkFetch(\n `${config.apiBaseUrl}/endpoints/${encodeURIComponent(counterpartyId)}/edge-config`,\n { method: 'GET', headers, signal: AbortSignal.timeout(opts?.timeoutMs ?? 5000) }\n );\n if (response.status === 304) return { notModified: true };\n if (!response.ok) return null;\n const body = (await response.json()) as { data?: { edgeConfig?: unknown } };\n const edgeConfig = body.data?.edgeConfig;\n if (!isEdgeConfig(edgeConfig)) return null;\n return { edgeConfig, etag: response.headers.get('etag') ?? undefined };\n } catch {\n return null;\n }\n}\n\ninterface CacheEntry {\n config: EdgeConfig;\n etag?: string;\n /** When the entry was last confirmed fresh (fetch or 304). */\n lastSuccessAt: number;\n}\n\nconst DEFAULT_TTL_MS = 60 * 1000;\nconst DEFAULT_MAX_STALE_MS = 24 * 60 * 60 * 1000;\n\nconst cache = new Map<string, CacheEntry>();\nconst inflight = new Map<string, Promise<void>>();\n\nfunction cacheKey(apiBaseUrl: string, counterpartyId: string): string {\n return `${apiBaseUrl}|${counterpartyId}`;\n}\n\n/** Copy of `config` with every enforce (top-level and per-rule) degraded to observe. */\nexport function degradeToObserve(config: EdgeConfig): EdgeConfig {\n if (config.mode !== 'enforce' && !config.pathRules.some((r) => r.mode === 'enforce')) {\n return config;\n }\n return {\n ...config,\n mode: 'observe',\n pathRules: config.pathRules.map((r) => (r.mode === 'enforce' ? { ...r, mode: 'observe' } : r)),\n };\n}\n\nasync function revalidate(\n config: Pick<GatewayConfig, 'apiBaseUrl' | 'apiKey'>,\n counterpartyId: string\n): Promise<void> {\n const key = cacheKey(config.apiBaseUrl, counterpartyId);\n const existing = inflight.get(key);\n if (existing) return existing;\n\n const promise = fetchEdgeConfig(config, counterpartyId, { etag: cache.get(key)?.etag })\n .then((result) => {\n if (result === null) return; // failure — cache untouched, caller falls back\n const now = Date.now();\n if ('notModified' in result) {\n const entry = cache.get(key);\n if (entry) entry.lastSuccessAt = now;\n return;\n }\n cache.set(key, { config: result.edgeConfig, etag: result.etag, lastSuccessAt: now });\n })\n .finally(() => {\n inflight.delete(key);\n });\n\n inflight.set(key, promise);\n return promise;\n}\n\n/**\n * Get the edge config for an endpoint, cached. Never throws, never blocks\n * longer than one fetch.\n *\n * - Fresh cache (within `ttlMs`) → cached config, no network.\n * - Stale cache → cached config immediately + background revalidate\n * (stale-while-revalidate). If the last successful fetch is older than\n * `maxStaleMs` (default 24h), any enforce is degraded to observe — a\n * long-dead backend can never keep a site enforcing.\n * - No cache → await one fetch; on failure return `DEFAULT_EDGE_CONFIG`\n * (observe-only). Defaults never enforce.\n */\nexport async function getEdgeConfig(\n config: Pick<GatewayConfig, 'apiBaseUrl' | 'apiKey'>,\n counterpartyId: string,\n opts?: { ttlMs?: number; maxStaleMs?: number }\n): Promise<EdgeConfig> {\n const ttlMs = opts?.ttlMs ?? DEFAULT_TTL_MS;\n const maxStaleMs = opts?.maxStaleMs ?? DEFAULT_MAX_STALE_MS;\n const key = cacheKey(config.apiBaseUrl, counterpartyId);\n\n const entry = cache.get(key);\n if (entry) {\n const age = Date.now() - entry.lastSuccessAt;\n if (age > ttlMs) {\n revalidate(config, counterpartyId).catch(() => {\n // background refresh failed — stale entry remains until next call\n });\n }\n return age > maxStaleMs ? degradeToObserve(entry.config) : entry.config;\n }\n\n await revalidate(config, counterpartyId).catch(() => {\n // fetch failed — fall through to defaults\n });\n return cache.get(key)?.config ?? DEFAULT_EDGE_CONFIG;\n}\n\n/**\n * First-match-wins path-rule lookup. Case-insensitive `*` globs with all\n * other regex metacharacters escaped (a literal `.` in a pattern matches\n * only `.`). Returns `undefined` when no rule matches — the caller applies\n * the config's top-level mode/depth.\n */\nexport function matchEdgePathRule(rules: EdgePathRule[], path: string): EdgePathRule | undefined {\n for (const rule of rules) {\n if (globToRegExp(rule.pattern).test(path)) return rule;\n }\n return undefined;\n}\n\nfunction globToRegExp(pattern: string): RegExp {\n const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&').replace(/\\*/g, '.*');\n return new RegExp(`^${escaped}$`, 'i');\n}\n\n/** Reset cache — for testing only. */\nexport function _resetEdgeConfigCache(): void {\n cache.clear();\n inflight.clear();\n}\n","/**\n * Maximal metadata capture — the shared, edge-safe sanitiser.\n *\n * AstraSync's thesis is total metadata capture: every header and connection\n * signal an inbound agent presents is a signal we want to keep. This module is\n * the ONE place that decides what is safe to store verbatim, what is a secret\n * to drop, and what credential headers reduce to a safe *format prefix* (a\n * platform signal, never the secret itself).\n *\n * It runs in three places that must agree byte-for-byte:\n * - the edge adapter (`@astrasyncai/adapter-lambda`) — the richest capture\n * point (full CloudFront header arrays),\n * - the SDK adapters (express / nextjs) — for SDK-only merchants with no edge,\n * - (indirectly) the backend, which stores whatever the above forward.\n *\n * Pure — no Node built-ins, no I/O — so it is safe in Lambda@Edge, the browser\n * build, and Deno. Capture is cheap: at the edge and SDK it is local string\n * work, and the backend stores it on a fire-and-forget event insert, so it adds\n * ZERO verify-access decision latency. Detection (which few signals imply which\n * vendor) is a separate, curated concern — see `platform-signatures.ts`.\n */\n\n/**\n * Version of the capture semantics (what is kept, dropped, reduced, or\n * derived — and under which key names).\n *\n * Capture semantics are FROZEN within a package major version: a given\n * `schemaVersion` always means the same field vocabulary and the same\n * keep/drop/reduce rules. The number bumps only on a SEMANTIC change to\n * capture (a renamed key, a changed reduction rule) — never for additive\n * signals, and never merely because the package version moved. To tell\n * builds apart, use the `sdkVersion` already present on the verify body;\n * `schemaVersion` answers the different question \"how do I interpret this\n * stored metadata?\".\n */\nexport const CAPTURE_SCHEMA_VERSION = 1;\n\n/**\n * The captured, sanitised view of an inbound agent's request metadata. Attached\n * to verify-access / beacon payloads as `callerMetadata.observedMetadata`.\n */\nexport interface ObservedMetadata {\n /** Header name → value, secrets removed, verbatim otherwise. */\n headers: Record<string, string>;\n /**\n * Safe key-format prefix of a credential header (e.g. `sk-ant-api03`,\n * `sk-proj`, `AIza`) — a platform signal, NEVER the secret. Absent if no\n * credential header was present or none matched a known format.\n */\n apiKeyFormat?: string;\n /**\n * The subset of `headers` that are known platform-signal headers\n * (`openai-organization`, `x-goog-user-project`, `anthropic-version`, …),\n * pulled out for convenient detection + display. Values are the same\n * sanitised strings as in `headers`.\n */\n platformHeaders?: Record<string, string>;\n /**\n * Connection-layer signals (IP, ASN, country, TLS version, HTTP version,\n * device class, TLS fingerprint). Edge adapters populate this from the\n * platform's native connection surface — the authoritative source. SDK\n * adapters populate it as a fallback via {@link deriveConnectionFromHeaders}\n * when a CDN in front of the merchant injected the equivalent headers;\n * absent when neither source had anything.\n */\n connection?: Record<string, string>;\n /**\n * Number of cookie pairs the caller sent. The `cookie` header VALUE is a\n * secret and is always dropped; the COUNT is a client-shape signal\n * (browsers carry cookies, most automation carries none) that would\n * otherwise be unobservable downstream. Absent when no cookie header\n * arrived.\n */\n cookieCount?: number;\n /**\n * Query-string parameter NAMES (deduped, lowercased) — values are NEVER\n * captured (they routinely carry OAuth codes, tokens, and PII, and no\n * deny-list is complete). Names alone fingerprint client shape. Populated\n * by the edge path, which sees the raw query string.\n */\n queryKeys?: string[];\n /**\n * Version of the capture semantics this object was produced under — see\n * {@link CAPTURE_SCHEMA_VERSION}. Optional for backward compatibility with\n * metadata captured before the field existed.\n */\n schemaVersion?: number;\n}\n\n/**\n * Result of sanitising a raw header map. `headers` is always present (possibly\n * empty); `apiKeyFormat` / `platformHeaders` only when a signal was found.\n */\nexport interface SanitizeHeadersResult {\n headers: Record<string, string>;\n apiKeyFormat?: string;\n platformHeaders?: Record<string, string>;\n /** Cookie-pair count; the cookie value itself is always dropped. */\n cookieCount?: number;\n}\n\n/**\n * Header names dropped entirely — genuine secrets or our own credentials that\n * describe the request's transport, not the agent. Matched case-insensitively\n * on the exact header name.\n */\nconst SECRET_HEADER_NAMES = new Set([\n 'cookie',\n 'set-cookie',\n 'x-csrf-token',\n 'proxy-authorization',\n 'x-astrasync-signature',\n 'x-astrasync-secret',\n 'x-hub-signature',\n 'x-hub-signature-256',\n // Short-lived verify dedupe token — must never persist in stored metadata.\n 'x-astra-verified-hop',\n]);\n\n/**\n * Header-name prefixes dropped entirely — our own credential / signing surface\n * (`x-astrasync-*`, `kya-*`) must never round-trip into stored metadata.\n */\nconst SECRET_HEADER_PREFIXES = ['x-astrasync-', 'kya-', 'kya_'];\n\n/**\n * Credential headers whose VALUE is a secret but whose FORMAT is a signal. We\n * keep the leading format prefix (up to the random tail) and drop the rest.\n */\nconst CREDENTIAL_HEADER_NAMES = new Set([\n 'authorization',\n 'x-api-key',\n 'x-goog-api-key',\n 'api-key',\n]);\n\n/**\n * Header names that carry a raw signature value (drop the value; the presence\n * is not worth a bloat risk). Matched as a suffix so `x-*-signature` variants\n * are covered without an exhaustive list.\n */\nfunction isSignatureHeader(name: string): boolean {\n return name === 'signature' || name.endsWith('-signature') || name.endsWith('-signature-256');\n}\n\n/**\n * Known platform-signal headers — pulled into `platformHeaders` for convenient\n * detection + display. Exact names plus a few prefixes (`x-goog-`,\n * `x-stainless-` — the OpenAI/Anthropic SDK client fingerprint headers).\n */\nconst PLATFORM_HEADER_NAMES = new Set([\n 'openai-organization',\n 'openai-project',\n 'openai-version',\n 'openai-processing-ms',\n 'anthropic-version',\n 'anthropic-beta',\n 'x-goog-user-project',\n 'x-goog-api-client',\n 'user-agent',\n 'x-agent-card-url',\n 'x-agent-provider',\n]);\n// `sec-ch-*` client hints are platform signals: Chromium forks (agentic\n// browsers included) often carry their real brand in `sec-ch-ua` even when\n// the UA string mimics stock Chrome.\nconst PLATFORM_HEADER_PREFIXES = [\n 'x-goog-',\n 'x-stainless-',\n 'x-anthropic-',\n 'x-openai-',\n 'sec-ch-',\n];\n\n/**\n * Known API-key format prefixes, longest-first so `sk-ant-api03` wins over\n * `sk-ant` and `sk-`. Each is the SAFE, non-secret leading token of a\n * credential; the random tail is never captured.\n */\nconst KEY_FORMAT_PREFIXES = [\n 'sk-ant-api03',\n 'sk-ant-api',\n 'sk-ant',\n 'sk-proj',\n 'sk-svcacct',\n 'sk-or-v1',\n 'sk-or',\n 'sk-lf',\n 'sk-',\n 'gsk_',\n 'aiza',\n 'ya29',\n 'ghp_',\n 'gho_',\n 'github_pat_',\n 'xai-',\n 'pplx-',\n 'r8_',\n 'hf_',\n 'astra-',\n 'astrae-',\n];\n\n/** Size caps — the only guard against jsonb bloat from a hostile POST. */\nexport const MAX_HEADERS = 64;\nexport const MAX_HEADER_VALUE_BYTES = 1024;\nexport const MAX_TOTAL_BYTES = 16 * 1024;\n\nfunction byteLength(s: string): number {\n // Edge-safe (no Buffer): count UTF-8 bytes without allocating a Buffer.\n let bytes = 0;\n for (let i = 0; i < s.length; i++) {\n const code = s.charCodeAt(i);\n if (code < 0x80) bytes += 1;\n else if (code < 0x800) bytes += 2;\n else if (code >= 0xd800 && code <= 0xdbff) {\n bytes += 4;\n i++; // surrogate pair\n } else bytes += 3;\n }\n return bytes;\n}\n\n/**\n * Extract the safe key-format prefix from a credential header value. Strips a\n * leading `Bearer ` / `Basic ` scheme, then returns the longest known prefix\n * that the (lowercased) value starts with. Returns undefined for opaque values\n * (e.g. a bare UUID token) so we never guess a format we don't recognise.\n */\nexport function extractApiKeyFormat(rawValue: string): string | undefined {\n if (!rawValue) return undefined;\n let value = rawValue.trim();\n const spaceIdx = value.indexOf(' ');\n if (spaceIdx > 0) {\n const scheme = value.slice(0, spaceIdx).toLowerCase();\n if (scheme === 'bearer' || scheme === 'basic' || scheme === 'token') {\n value = value.slice(spaceIdx + 1).trim();\n }\n }\n const lower = value.toLowerCase();\n for (const prefix of KEY_FORMAT_PREFIXES) {\n if (lower.startsWith(prefix)) {\n // Return the prefix as-declared in the list (canonical casing).\n return prefix;\n }\n }\n return undefined;\n}\n\nfunction isSecretHeader(name: string): boolean {\n if (SECRET_HEADER_NAMES.has(name)) return true;\n if (SECRET_HEADER_PREFIXES.some((p) => name.startsWith(p))) return true;\n if (isSignatureHeader(name)) return true;\n return false;\n}\n\nfunction isPlatformHeader(name: string): boolean {\n if (PLATFORM_HEADER_NAMES.has(name)) return true;\n return PLATFORM_HEADER_PREFIXES.some((p) => name.startsWith(p));\n}\n\n/**\n * Sanitise a raw header map for storage. Deny-lists genuine secrets, reduces\n * credential headers to a safe format prefix, keeps everything else verbatim,\n * and enforces the size caps that bound jsonb growth.\n *\n * Accepts any string→(string|string[]|undefined) map (Node's `req.headers`,\n * CloudFront's flattened headers, a plain object). Multi-value headers are\n * joined with `, ` per RFC 7230.\n */\nexport function sanitizeHeaders(\n raw: Record<string, string | string[] | undefined> | undefined | null\n): SanitizeHeadersResult {\n const headers: Record<string, string> = {};\n const platformHeaders: Record<string, string> = {};\n let apiKeyFormat: string | undefined;\n let cookieCount: number | undefined;\n let totalBytes = 0;\n let count = 0;\n\n if (!raw) return { headers };\n\n for (const rawName of Object.keys(raw)) {\n if (count >= MAX_HEADERS) break;\n const name = rawName.toLowerCase();\n const rawValue = raw[rawName];\n if (rawValue === undefined) continue;\n const joined = Array.isArray(rawValue) ? rawValue.join(', ') : String(rawValue);\n\n // Credential headers: capture the format prefix, drop the secret.\n if (CREDENTIAL_HEADER_NAMES.has(name)) {\n const fmt = extractApiKeyFormat(joined);\n if (fmt && !apiKeyFormat) apiKeyFormat = fmt;\n continue;\n }\n\n // Cookie: the value is a secret (dropped below), but the PAIR COUNT is a\n // client-shape signal worth keeping.\n if (name === 'cookie') {\n cookieCount = joined.split(';').filter((s) => s.trim().length > 0).length;\n }\n\n // Genuine secrets: drop entirely.\n if (isSecretHeader(name)) continue;\n\n // Everything else describing the agent: keep, bounded.\n let value = joined;\n if (byteLength(value) > MAX_HEADER_VALUE_BYTES) {\n value = value.slice(0, MAX_HEADER_VALUE_BYTES);\n }\n const entryBytes = byteLength(name) + byteLength(value);\n if (totalBytes + entryBytes > MAX_TOTAL_BYTES) continue;\n totalBytes += entryBytes;\n count++;\n headers[name] = value;\n if (isPlatformHeader(name)) platformHeaders[name] = value;\n }\n\n const result: SanitizeHeadersResult = { headers };\n if (apiKeyFormat) result.apiKeyFormat = apiKeyFormat;\n if (Object.keys(platformHeaders).length > 0) result.platformHeaders = platformHeaders;\n if (cookieCount !== undefined) result.cookieCount = cookieCount;\n return result;\n}\n\n/**\n * Pull the known platform-signal headers out of an ALREADY-sanitised header\n * map. `sanitizeHeaders` already computes this as a by-product; this standalone\n * form is exported for call-sites (edge, tests) that hold a sanitised map and\n * want only the platform subset. Never re-run over raw (unsanitised) headers.\n */\nexport function extractPlatformHeaders(\n sanitized: Record<string, string> | undefined | null\n): Record<string, string> {\n const out: Record<string, string> = {};\n if (!sanitized) return out;\n for (const name of Object.keys(sanitized)) {\n if (isPlatformHeader(name.toLowerCase())) out[name.toLowerCase()] = sanitized[name];\n }\n return out;\n}\n\n/**\n * Precedence-ordered CDN header sources for each derived `connection` key.\n * First present header wins; the special `x-forwarded-for` source takes the\n * LEFTMOST (client) entry of the comma-separated chain.\n */\nconst CONNECTION_HEADER_SOURCES: ReadonlyArray<readonly [key: string, headers: readonly string[]]> =\n [\n ['ip', ['cf-connecting-ip', 'fastly-client-ip', 'true-client-ip', 'x-real-ip']],\n [\n 'country',\n ['cf-ipcountry', 'x-vercel-ip-country', 'cloudfront-viewer-country', 'fastly-geo-country'],\n ],\n ['region', ['x-vercel-ip-country-region', 'cloudfront-viewer-country-region']],\n ['countryRegionName', ['cloudfront-viewer-country-region-name']],\n ['city', ['x-vercel-ip-city', 'cloudfront-viewer-city']],\n ['latitude', ['x-vercel-ip-latitude', 'cloudfront-viewer-latitude']],\n ['longitude', ['x-vercel-ip-longitude', 'cloudfront-viewer-longitude']],\n ['postalCode', ['x-vercel-ip-postal-code', 'cloudfront-viewer-postal-code']],\n ['asn', ['cloudfront-viewer-asn']],\n ['tlsVersion', ['cloudfront-viewer-tls']],\n ['httpVersion', ['cloudfront-viewer-http-version']],\n ['timeZone', ['x-vercel-ip-timezone', 'cloudfront-viewer-time-zone']],\n ['metroCode', ['cloudfront-viewer-metro-code']],\n // TLS fingerprints can only be computed where TLS terminates. When a CDN\n // terminates TLS in front of the merchant, its fingerprint headers ARE the\n // connection-layer truth — normalising them here is the permanent design.\n // CloudFront delivers JA3/JA4 only via an origin request policy and only\n // for HTTPS viewer connections.\n ['tlsFingerprint', ['cf-ja3-hash', 'cloudfront-viewer-ja3-fingerprint']],\n ['ja4', ['cf-ja4', 'cloudfront-viewer-ja4-fingerprint']],\n // Header-structure fingerprint: browser/SDK-distinctive header ordering.\n ['headerOrder', ['cloudfront-viewer-header-order']],\n ['headerCount', ['cloudfront-viewer-header-count']],\n ];\n\n/**\n * Backend bound: observedMetadata.connection values longer than this fail\n * the platform's zod parse outright (boundedStringRecord(32, 256)), so every\n * emitter truncates — headerOrder routinely exceeds it.\n */\nexport const MAX_CONNECTION_VALUE_CHARS = 256;\n\n/**\n * Derive the connection-layer block from CDN-injected request headers.\n *\n * When a merchant's SDK-gated origin sits behind a CDN (Cloudflare, Fastly,\n * Vercel, CloudFront), the CDN has already seen the connection layer and\n * injected it as headers. This promotes those headers to the same\n * `connection` keys the edge adapters populate natively, so SDK-only\n * deployments still get IP / geo / TLS attribution. Precedence per key:\n *\n * - `ip`: `cf-connecting-ip` > `fastly-client-ip` > `true-client-ip` >\n * `x-real-ip` > `cloudfront-viewer-address` (port stripped) > leftmost\n * `x-forwarded-for`\n * - `country`: `cf-ipcountry` > `x-vercel-ip-country` >\n * `cloudfront-viewer-country` > `fastly-geo-country`\n * - `region` / `city` / `timeZone`: Vercel then CloudFront viewer headers\n * - `countryRegionName` / `asn` / `tlsVersion` / `httpVersion` /\n * `metroCode` / `headerOrder` / `headerCount`: `cloudfront-viewer-*`\n * - `tlsFingerprint`: `cf-ja3-hash` > `cloudfront-viewer-ja3-fingerprint`\n * - `ja4`: `cf-ja4` > `cloudfront-viewer-ja4-fingerprint`\n *\n * All keys are additive under `schemaVersion` 1 (the frozen-capture doctrine\n * bumps only for changed semantics, never for additive signals). Values are\n * truncated to MAX_CONNECTION_VALUE_CHARS — the platform's hard bound.\n *\n * Edge adapters keep their richer native collectors — native platform\n * signals are authoritative; this header derivation is the SDK-level\n * fallback. Header names are matched case-insensitively. Returns undefined\n * when no source header is present, so the `connection` key is simply\n * omitted (matching edge behaviour).\n */\nexport function deriveConnectionFromHeaders(\n headers: Record<string, string> | undefined | null\n): Record<string, string> | undefined {\n if (!headers) return undefined;\n const lower: Record<string, string> = {};\n for (const name of Object.keys(headers)) {\n const value = headers[name];\n if (typeof value === 'string' && value.length > 0) lower[name.toLowerCase()] = value;\n }\n\n const connection: Record<string, string> = {};\n for (const [key, sources] of CONNECTION_HEADER_SOURCES) {\n for (const source of sources) {\n const value = lower[source]?.trim();\n if (value) {\n connection[key] = value.slice(0, MAX_CONNECTION_VALUE_CHARS);\n break;\n }\n }\n }\n // ip fallback 1: cloudfront-viewer-address arrives as ip:port — strip the\n // trailing port only (IPv6-safe), unlike the dedicated client-ip headers.\n // The port itself is kept as its own key: ephemeral-port patterns signal\n // NAT/proxy connection reuse.\n {\n const addr = lower['cloudfront-viewer-address']?.trim();\n const portMatch = addr?.match(/:(\\d+)$/);\n if (portMatch) connection.sourcePort = portMatch[1];\n if (!connection.ip && addr) connection.ip = addr.replace(/:\\d+$/, '');\n }\n // ip fallback 2: leftmost (client) hop of the x-forwarded-for chain.\n if (!connection.ip) {\n const xff = lower['x-forwarded-for'];\n const client = xff?.split(',')[0]?.trim();\n if (client) connection.ip = client;\n }\n // tlsCipher: CloudFront folds the cipher into the viewer-tls string\n // (`TLSv1.3:TLS_AES_128_GCM_SHA256:fullHandshake`). `tlsVersion` stays\n // verbatim (reducing it would be a semantic change → schema v2); the\n // cipher is pulled out additively so it is queryable on its own.\n if (!connection.tlsCipher) {\n const cipher = connection.tlsVersion?.split(':')[1];\n if (cipher) connection.tlsCipher = cipher;\n }\n\n return Object.keys(connection).length > 0 ? connection : undefined;\n}\n\n/**\n * The FULL metadata capture for one request at an SDK adapter (express /\n * nextjs / mcp): sanitised headers, the safe credential format prefix, the\n * platform-signal subset, the CDN-derived connection block, and the capture\n * schema version. This is the ONE builder all SDK adapters share, so their\n * verify-access bodies agree byte-for-byte.\n *\n * Connection derivation runs over the RAW header map (pre-cap) — the size\n * caps guard storage growth and must never hide a geo/IP header that\n * happened to arrive late in an oversized map.\n */\nexport function buildSdkObservedMetadata(\n rawHeaders: Record<string, string | string[] | undefined> | undefined | null\n): ObservedMetadata {\n const { headers, apiKeyFormat, platformHeaders, cookieCount } = sanitizeHeaders(rawHeaders);\n const flat: Record<string, string> = {};\n if (rawHeaders) {\n for (const name of Object.keys(rawHeaders)) {\n const value = rawHeaders[name];\n if (value === undefined) continue;\n flat[name.toLowerCase()] = Array.isArray(value) ? value.join(', ') : String(value);\n }\n }\n const connection = deriveConnectionFromHeaders(flat);\n return {\n headers,\n ...(apiKeyFormat && { apiKeyFormat }),\n ...(platformHeaders && { platformHeaders }),\n ...(connection && { connection }),\n ...(cookieCount !== undefined && { cookieCount }),\n schemaVersion: CAPTURE_SCHEMA_VERSION,\n };\n}\n","/**\n * Platform-agent fingerprint signatures — the shared registry of known\n * platform-agent UA / agent-card patterns (Claude / ChatGPT / Gemini /\n * Cursor / Goose).\n *\n * Single source of truth, lifted verbatim from the backend's\n * `platform-agent-detector.service` (which now imports detection from\n * here): the backend's verify-access anonymous handler and the edge\n * adapter (`@astrasyncai/adapter-lambda`) must classify identically or\n * the three-tier visibility numbers drift between capture points.\n *\n * Pure regex — no Node built-ins, edge-safe. Detection is regex-only for\n * v2.9 — TLS fingerprinting / behavioural signatures are deferred.\n */\n\nexport type PlatformAgentVendor =\n | 'claude'\n | 'chatgpt'\n | 'gemini'\n | 'cursor'\n | 'goose'\n | 'perplexity'\n | 'chatgpt-atlas'\n | 'perplexity-comet'\n | 'astrasync-sdk'\n | 'unknown';\n\nexport interface PlatformFingerprint {\n vendor: PlatformAgentVendor;\n /** A stable identifier used as the orphan-agent dedup key. */\n fingerprintKey: string;\n /** Human-readable name surfaced in the admin panel. */\n displayName: string;\n}\n\nexport interface PlatformDetectionInput {\n userAgent?: string;\n agentCardUrl?: string;\n /**\n * A safe API-key format prefix observed on the caller's\n * credential header (e.g. `sk-ant-api03`, `sk-proj`, `aiza`). A strong\n * platform signal; never the secret. Matched against `apiKeyFormatPatterns`.\n */\n apiKeyFormat?: string;\n /**\n * The sanitised platform-signal headers (lowercased names →\n * values), e.g. `openai-organization`, `x-goog-user-project`. Matched\n * against `headerPatterns` (which test on `name` and `name: value`).\n */\n platformHeaders?: Record<string, string>;\n /**\n * The caller's JA4 TLS-client fingerprint (from the connection capture).\n * Matched against `ja4Patterns`. A JA4 identifies the client TLS stack,\n * so signatures should pair it with other evidence when attributing a\n * vendor.\n */\n ja4?: string;\n /**\n * The caller's origin ASN (from the connection capture). Matched against\n * `asnList` by exact membership. An ASN alone attributes an entire cloud\n * provider — registry validation rejects ASN-only signatures.\n */\n asn?: string;\n}\n\n/**\n * A signature definition, generic over the vendor key. The seed constant\n * below uses the closed `PlatformAgentVendor` union; DB-promoted signatures\n * (backend dynamic registry, console round) carry arbitrary string vendors —\n * `matchPlatformSignature` accepts both.\n */\nexport interface PlatformSignatureDef<V extends string = string> {\n vendor: V;\n displayName: string;\n uaPatterns?: RegExp[];\n agentCardPatterns?: RegExp[];\n /**\n * Patterns tested against an observed API-key format prefix\n * (e.g. `/^sk-ant/i` → claude). A credential-header format is a stronger\n * platform signal than a spoofable User-Agent.\n */\n apiKeyFormatPatterns?: RegExp[];\n /**\n * Patterns tested against each observed platform-signal\n * header, as both `name` and `name: value` (so `/openai-organization/i` and\n * `/x-goog-user-project/i` match on presence).\n */\n headerPatterns?: RegExp[];\n /** Patterns tested against the observed JA4 TLS-client fingerprint. */\n ja4Patterns?: RegExp[];\n /** Exact ASN strings this signature matches (never regex). */\n asnList?: string[];\n}\n\n/**\n * A fingerprint whose vendor may be a dynamically-promoted (non-seed) key.\n * Structurally a superset of `PlatformFingerprint`.\n */\nexport interface DynamicPlatformFingerprint {\n vendor: string;\n fingerprintKey: string;\n displayName: string;\n}\n\n/**\n * Registry of known platform-agent signatures. Order matters — first match wins.\n *\n * Patterns are intentionally permissive (case-insensitive substring match) since\n * platform UA strings drift between versions. False positives are tolerable —\n * the orphan record is informational, not enforcement.\n */\nexport const PLATFORM_AGENT_SIGNATURES: ReadonlyArray<PlatformSignatureDef<PlatformAgentVendor>> = [\n {\n vendor: 'claude',\n displayName: 'Anthropic Claude',\n uaPatterns: [/claude/i, /anthropic/i],\n agentCardPatterns: [/anthropic\\.com/i, /claude\\.ai/i],\n apiKeyFormatPatterns: [/^sk-ant/i],\n headerPatterns: [/^anthropic-version/i, /^anthropic-beta/i, /^x-anthropic-/i],\n },\n {\n vendor: 'chatgpt',\n displayName: 'OpenAI ChatGPT',\n uaPatterns: [/chatgpt/i, /openai/i, /gpt-?\\d/i],\n agentCardPatterns: [/openai\\.com/i, /chatgpt\\.com/i],\n apiKeyFormatPatterns: [/^sk-proj/i, /^sk-svcacct/i],\n headerPatterns: [/^openai-organization/i, /^openai-project/i, /^openai-version/i],\n },\n {\n vendor: 'gemini',\n displayName: 'Google Gemini',\n uaPatterns: [/gemini/i, /google-gemini/i, /bard/i],\n agentCardPatterns: [/gemini\\.google\\.com/i, /ai\\.google\\.dev/i],\n apiKeyFormatPatterns: [/^aiza/i],\n headerPatterns: [/^x-goog-user-project/i, /^x-goog-api-client/i],\n },\n {\n vendor: 'cursor',\n displayName: 'Cursor',\n uaPatterns: [/cursor/i],\n agentCardPatterns: [/cursor\\.sh/i, /cursor\\.com/i],\n },\n {\n vendor: 'goose',\n displayName: 'Block Goose',\n uaPatterns: [/goose/i, /block-goose/i],\n agentCardPatterns: [/block\\.xyz\\/goose/i, /goose\\.tools/i],\n },\n {\n vendor: 'perplexity',\n displayName: 'Perplexity',\n uaPatterns: [/perplexity/i],\n agentCardPatterns: [/perplexity\\.ai/i],\n apiKeyFormatPatterns: [/^pplx-/i],\n },\n // Agentic browsers — versioned-token patterns ONLY (a stock Chrome UA must\n // never match). Distinct vendor keys (not 'chatgpt'/'perplexity'): the\n // browser product is a different surface than the assistant service, and\n // the DB registry mirrors one row per vendor. These sit after the primary\n // vendor entries so a UA carrying an explicit vendor token keeps its\n // primary attribution; a browser-shaped UA with the agentic token is\n // caught here BEFORE classify's human tier, which is what makes these\n // visits observable at all. Token drift is real (some builds mimic Chrome\n // outright) — re-verify against captured events when a new browser ships,\n // and check `sec-ch-ua` platformHeaders for the real brand.\n {\n vendor: 'chatgpt-atlas',\n displayName: 'ChatGPT Atlas browser',\n uaPatterns: [/\\batlas\\/\\d/i],\n headerPatterns: [/^sec-ch-ua: .*atlas/i],\n },\n {\n vendor: 'perplexity-comet',\n displayName: 'Perplexity Comet browser',\n uaPatterns: [/\\bcomet\\/\\d/i],\n headerPatterns: [/^sec-ch-ua: .*comet/i],\n },\n // Our own SDK self-identifies (sdkFetch stamps this UA) — first-party\n // traffic must never pollute the unknown/anonymous pool it exists to audit.\n {\n vendor: 'astrasync-sdk',\n displayName: 'AstraSync SDK',\n uaPatterns: [/^astrasync-sdk\\//i],\n },\n];\n\n/**\n * Generic first-match-wins matcher over an arbitrary signature set. The\n * backend's dynamic registry merges the seed constant with DB-promoted\n * signatures and calls this — ONE matching implementation everywhere\n * (fingerprint-key rule included: vendor + lowercased UA basename before\n * the first space/slash, falling back to the agent-card host).\n */\nexport function matchPlatformSignature(\n signatures: ReadonlyArray<PlatformSignatureDef>,\n input: PlatformDetectionInput\n): DynamicPlatformFingerprint | undefined {\n const ua = input.userAgent ?? '';\n const cardUrl = input.agentCardUrl ?? '';\n const apiKeyFormat = input.apiKeyFormat ?? '';\n const ja4 = input.ja4 ?? '';\n const asn = input.asn ?? '';\n // Flatten platform headers to `name` and `name: value` lines for matching.\n const headerLines: string[] = [];\n if (input.platformHeaders) {\n for (const [name, value] of Object.entries(input.platformHeaders)) {\n headerLines.push(name, `${name}: ${value}`);\n }\n }\n\n for (const sig of signatures) {\n const uaMatch = sig.uaPatterns?.some((p) => p.test(ua));\n const cardMatch = sig.agentCardPatterns?.some((p) => p.test(cardUrl));\n const keyMatch =\n apiKeyFormat.length > 0 && sig.apiKeyFormatPatterns?.some((p) => p.test(apiKeyFormat));\n const headerMatch =\n headerLines.length > 0 &&\n sig.headerPatterns?.some((p) => headerLines.some((line) => p.test(line)));\n const ja4Match = ja4.length > 0 && sig.ja4Patterns?.some((p) => p.test(ja4));\n const asnMatch = asn.length > 0 && sig.asnList?.includes(asn);\n if (uaMatch || cardMatch || keyMatch || headerMatch || ja4Match || asnMatch) {\n const uaBase = ua.split(/[\\s/]/)[0]?.toLowerCase() ?? '';\n const cardHost = (() => {\n try {\n return cardUrl ? new URL(cardUrl).host : '';\n } catch {\n return '';\n }\n })();\n // Prefer a UA/card basename for the dedup key; fall back to the\n // credential format, then the connection fingerprint (still stable\n // per-vendor keys) when only a key/header/ja4/asn matched.\n const keyBasis =\n uaBase || cardHost || apiKeyFormat || ja4 || (asn && `asn${asn}`) || 'unknown';\n return {\n vendor: sig.vendor,\n fingerprintKey: `${sig.vendor}:${keyBasis}`,\n displayName: sig.displayName,\n };\n }\n }\n\n return undefined;\n}\n\n/**\n * Inspect caller metadata for a known SEED platform-agent fingerprint.\n * Returns undefined if no signature matches. (Backends with the dynamic\n * registry should call `matchPlatformSignature` over their merged set\n * instead — same semantics, live signature additions included.)\n */\nexport function detectPlatformFingerprint(\n input: PlatformDetectionInput\n): PlatformFingerprint | undefined {\n // Seed vendors are all members of the PlatformAgentVendor union, so the\n // narrowing cast is sound by construction.\n return matchPlatformSignature(PLATFORM_AGENT_SIGNATURES, input) as\n | PlatformFingerprint\n | undefined;\n}\n","/**\n * AstraSync Universal Verification Gateway — Trust Level helpers.\n *\n * SDK 5.0.0: the `accessLevel` band (`none`/`restricted`/`read-only`/`standard`/\n * `full`/`internal`) was removed entirely — it never gated the access decision\n * (the server does, from a verified ID + runtime challenge + PDLSS match + trust\n * score). What remains here is the coarse trust-level badge derived from the\n * numeric trust score, used only for display.\n */\n\nimport type { TrustLevel } from './types';\n\n/**\n * Trust level score ranges\n */\nexport const TRUST_LEVEL_RANGES: Record<TrustLevel, { min: number; max: number }> = {\n BRONZE: { min: 0, max: 39 },\n SILVER: { min: 40, max: 59 },\n GOLD: { min: 60, max: 79 },\n PLATINUM: { min: 80, max: 100 },\n};\n\n/**\n * Determine trust level from score\n */\nexport function getTrustLevel(score: number): TrustLevel {\n if (score >= 80) return 'PLATINUM';\n if (score >= 60) return 'GOLD';\n if (score >= 40) return 'SILVER';\n return 'BRONZE';\n}\n","import { sdkFetch } from './http';\n/**\n * SDK-side discovery of canonical platform URLs via `/.well-known/agentic-commerce`.\n *\n * Fire-and-forget pre-fetch at middleware creation; first verify() awaits\n * the in-flight promise if it hasn't resolved. 60-minute TTL with\n * stale-while-revalidate background refresh.\n */\n\nexport interface WellKnownAgenticCommerce {\n registrationUrl: string;\n documentationUrl: string;\n verifyAccessUrl: string;\n /** 5.1.0: hosted AstraSync MCP bridge endpoint (absent on self-hosted backends). */\n mcpEndpoint?: string;\n /** 5.1.0: bridge connector-discovery doc (absent on self-hosted backends). */\n mcpDiscoveryUrl?: string;\n}\n\ninterface CacheEntry {\n data: WellKnownAgenticCommerce;\n fetchedAt: number;\n}\n\nconst CACHE_TTL_MS = 60 * 60 * 1000; // 60 minutes\n\nconst cache = new Map<string, CacheEntry>();\nconst inflight = new Map<string, Promise<WellKnownAgenticCommerce>>();\n\nfunction wellKnownUrl(apiBaseUrl: string): string {\n // apiBaseUrl is typically 'https://astrasync.ai/api' — strip the /api suffix\n // to get the platform root, then append /.well-known/agentic-commerce.\n const base = apiBaseUrl.replace(/\\/api\\/?$/, '');\n return `${base}/.well-known/agentic-commerce`;\n}\n\nasync function fetchWellKnown(apiBaseUrl: string): Promise<WellKnownAgenticCommerce> {\n const url = wellKnownUrl(apiBaseUrl);\n const response = await sdkFetch(url, {\n method: 'GET',\n headers: { Accept: 'application/json' },\n signal: AbortSignal.timeout(5000),\n });\n if (!response.ok) {\n throw new Error(\n `AstraSync platform must expose /.well-known/agentic-commerce; ` +\n `got ${response.status} from ${url}. SDK cannot initialise without it.`\n );\n }\n const data = (await response.json()) as Record<string, unknown>;\n if (!data.registrationUrl || !data.documentationUrl || !data.verifyAccessUrl) {\n throw new Error(\n `/.well-known/agentic-commerce response missing required fields ` +\n `(registrationUrl, documentationUrl, verifyAccessUrl).`\n );\n }\n return data as unknown as WellKnownAgenticCommerce;\n}\n\n/**\n * Start a background fetch. Returns the promise for callers that need\n * to await it (first verify() call).\n */\nexport function prefetchWellKnown(apiBaseUrl: string): Promise<WellKnownAgenticCommerce> {\n const existing = inflight.get(apiBaseUrl);\n if (existing) return existing;\n\n const promise = fetchWellKnown(apiBaseUrl)\n .then((data) => {\n cache.set(apiBaseUrl, { data, fetchedAt: Date.now() });\n inflight.delete(apiBaseUrl);\n return data;\n })\n .catch((err) => {\n inflight.delete(apiBaseUrl);\n throw err;\n });\n\n inflight.set(apiBaseUrl, promise);\n return promise;\n}\n\n/**\n * Get cached well-known URLs. If stale, triggers a background refresh\n * and returns stale data (stale-while-revalidate). If no cache exists,\n * awaits the in-flight fetch or starts a new one.\n */\nexport async function getWellKnownUrls(apiBaseUrl: string): Promise<WellKnownAgenticCommerce> {\n const entry = cache.get(apiBaseUrl);\n\n if (entry) {\n if (Date.now() - entry.fetchedAt > CACHE_TTL_MS) {\n // Stale — trigger background refresh, return stale data\n prefetchWellKnown(apiBaseUrl).catch(() => {\n // Background refresh failed — stale data remains until next request\n });\n }\n return entry.data;\n }\n\n // No cache — must await\n const pending = inflight.get(apiBaseUrl);\n if (pending) return pending;\n\n return prefetchWellKnown(apiBaseUrl);\n}\n\n/**\n * Synchronous cache read — returns cached URLs or undefined.\n * Never triggers a fetch. Used by verify() to avoid extra HTTP calls\n * in the hot path; adapters are responsible for prefetching.\n */\nexport function getCachedWellKnownUrls(apiBaseUrl: string): WellKnownAgenticCommerce | undefined {\n return cache.get(apiBaseUrl)?.data;\n}\n\n/** Reset cache — for testing only. */\nexport function _resetWellKnownCache(): void {\n cache.clear();\n inflight.clear();\n}\n","/**\n * AstraSync Universal Verification Gateway - Core Verification Logic\n *\n * This module handles the core verification logic, calling the AstraSync API\n * and processing the response into a standardized VerificationResult.\n */\n\nimport { sdkFetch } from './http';\nimport type {\n GatewayConfig,\n AgentCredentials,\n VerificationRequest,\n VerificationResult,\n VerifiedAgent,\n VerifiedDeveloper,\n VerifiedOrganization,\n GuidanceInfo,\n EnhancedVerificationResult,\n TokenGuidance,\n RuntimeChallengeResult,\n StepUpApprovalInfo,\n SettlementOutcomeInfo,\n MerchantSettlementToken,\n FulfilmentInfo,\n SettlementArtifact,\n AttemptReport,\n} from './types';\nimport { getTrustLevel } from './trust-levels';\nimport type { ObservedMetadata } from './metadata-capture';\nimport { SDK_VERSION } from './version';\nimport { getCachedWellKnownUrls, type WellKnownAgenticCommerce } from './well-known';\n\n/**\n * Default configuration values\n *\n * apiBaseUrl matches the OpenAPI authoritative server (https://astrasync.ai/api\n * for prod, https://staging.astrasync.ai/api for staging). Always include the\n * /api path prefix when overriding — registration / docs URLs are derived by\n * stripping it.\n */\nconst DEFAULT_CONFIG: Partial<GatewayConfig> = {\n apiBaseUrl: 'https://astrasync.ai/api',\n // minTrustScore + minTrustScoreForFull deprecated in v2.3.0 — server decides.\n // cacheTtl deliberately unset. When undefined, cacheResult applies the 60s\n // default; the caller's explicit value is honoured for cacheable results.\n // Denials and step-up escalations are NEVER cached (3.6.0) regardless of\n // cacheTtl. Set cacheTtl: 0 to disable caching entirely.\n debug: false,\n};\n\n/**\n * Init self-test state. Fires once per process on first verify() call to warn\n * if apiBaseUrl is pointing at the wrong host (e.g. a marketing site that\n * 200s with text/html instead of the API).\n */\nlet initCheckPerformed = false;\n\n/** Test-only: re-arm the one-time init self-check. */\nexport function _resetInitCheck(): void {\n initCheckPerformed = false;\n}\n\n/** One-shot guard for v2.3.0 deprecation warning. */\nlet deprecationWarningShown = false;\n\nasync function performInitCheck(\n apiBaseUrl: string,\n debug?: boolean,\n strictInit?: boolean,\n apiKey?: string\n): Promise<void> {\n initCheckPerformed = true;\n try {\n const probeUrl = `${apiBaseUrl}/agents/verify-access`;\n // HEAD mirrors GET semantics (running the full request pipeline without a\n // body) so the response carries the same content-type the marketing 404\n // would return. OPTIONS often gets short-circuited by CORS-preflight\n // handlers and returns no content-type, defeating the check.\n const response = await sdkFetch(probeUrl, { method: 'HEAD' });\n const contentType = response.headers.get('content-type') ?? '';\n if (contentType.startsWith('text/html')) {\n const message =\n `[VerificationGateway] apiBaseUrl '${apiBaseUrl}' returned HTML (content-type: ${contentType}). ` +\n `This usually means apiBaseUrl is pointing at a marketing site instead of the API. ` +\n `Expected: 'https://astrasync.ai/api' (prod) or 'https://staging.astrasync.ai/api' (staging).`;\n // Audit F-A6-33: when strictInit is set, throw on misconfig instead\n // of warning + continuing. Recurring footgun per\n // `[[feedback_astrasync_api_url_canonical]]` — silent warn lets\n // misconfigured prod deploys ship with all verify-access calls\n // silently failing.\n if (strictInit) {\n throw new Error(`${message} (strictInit=true)`);\n }\n console.warn(`${message} Set disableInitChecks: true on GatewayConfig to silence.`);\n } else if (debug) {\n console.log(\n `[VerificationGateway] init check passed for ${apiBaseUrl} (content-type: ${contentType})`\n );\n }\n\n // 4.0.0: key liveness probe. A dead API key otherwise surfaces only\n // per-request as inbound agents get turned away — the operator should\n // learn at deploy time. 404 = older backend without self-check: silent.\n if (apiKey) {\n const selfCheck = await sdkFetch(`${apiBaseUrl}/agents/verify-access/self-check`, {\n headers: { Authorization: `Bearer ${apiKey}` },\n });\n if (selfCheck.status === 401) {\n const body = (await selfCheck.json().catch(() => ({}))) as {\n code?: string;\n message?: string;\n remediation?: { manageUrl?: string };\n };\n const message =\n `[VerificationGateway] the configured AstraSync API key was REJECTED at startup ` +\n `(${body.code ?? 'api_key_invalid'}: ${body.message ?? 'invalid key'}). Every inbound agent ` +\n `will be turned away until the key is rotated` +\n (body.remediation?.manageUrl ? ` at ${body.remediation.manageUrl}` : '') +\n `.`;\n if (strictInit) {\n throw new Error(`${message} (strictInit=true)`);\n }\n console.error(message);\n } else if (selfCheck.ok) {\n const body = (await selfCheck.json().catch(() => ({}))) as {\n daysToExpiry?: number | null;\n };\n if (typeof body.daysToExpiry === 'number' && body.daysToExpiry <= 7) {\n console.warn(\n `[VerificationGateway] the configured AstraSync API key expires in ${body.daysToExpiry} day(s) — ` +\n `rotate it at Settings → Developer Tools before integrations start failing.`\n );\n } else if (debug) {\n console.log('[VerificationGateway] API key self-check passed');\n }\n }\n }\n } catch (err) {\n if (strictInit) {\n // strict mode propagates init failures so callers get a clear,\n // synchronous \"your config is broken\" signal at startup.\n throw err;\n }\n if (debug) {\n console.log(`[VerificationGateway] init check failed (non-blocking): ${String(err)}`);\n }\n }\n}\n\n/**\n * Simple in-memory cache for verification results\n */\nconst verificationCache = new Map<string, { result: VerificationResult; expiresAt: number }>();\n\n/**\n * Generate cache key from the full request shape.\n *\n * Historically the key was credentials-only (`astraId-apiKey-jwt`),\n * which silently returned the cached result of a prior call even when the\n * subsequent call's purpose/action/counterparty/etc. differed. That was a\n * security gap — a warm cache could serve an allow verdict for a purpose the\n * agent hadn't actually been authorised for. Key now includes every field\n * that affects the backend verdict.\n *\n * MAINTAIN: when adding a field to VerificationRequest that affects the\n * backend verdict, add it to this key. Fields that don't affect verdict\n * (e.g. requestId, timestamps, sdkVersion) don't belong here — including\n * them would needlessly thrash the cache for repeated identical requests.\n *\n * 3.12.0 (Trust Record): `attemptId` and `considerationSet` are\n * deliberately EXCLUDED — like `callerMetadata.observedMetadata` they are\n * observational pass-through that never affects the verdict, and keying on\n * a per-attempt id would defeat verdict caching entirely. Cache hits get\n * their attemptId rewritten in verify() instead (never leak a prior\n * attempt's id from a cached result).\n */\nfunction getCacheKey(request: VerificationRequest, counterpartyId?: string): string {\n const c = request.credentials;\n return [\n c.astraId || '',\n c.apiKey || '',\n c.jwt || '',\n request.purpose || '',\n request.action || '',\n request.resourceType || '',\n request.resource || '',\n request.jurisdiction || '',\n request.transactionValue ?? '',\n request.currency || '',\n // SECURITY (cross-merchant cache leak): the merchant identity is sent via\n // `config.counterpartyId`, NOT on the request, so it was previously absent\n // from the key — two verifies for the SAME agent/purpose/action/value but\n // DIFFERENT merchants collided, and a grant at a permissive merchant (low\n // trust floor) was served for a stricter one. Same bug class as the\n // duration omission (F-A1-07). counterpartyId affects the backend verdict\n // (trust floor / per-route policy), so it MUST key the cache.\n counterpartyId || '',\n request.counterpartyUrl || '',\n request.counterpartyType || '',\n request.isSubAgentRequest ? '1' : '0',\n request.parentAgentId || '',\n request.subAgentDepth ?? '',\n // Audit F-A1-07: previously-missing dimensions that DO affect the\n // backend verdict. Without these, two requests with different\n // durations (e.g. 60s vs 86400s) collided on the same cache key and\n // the shorter-duration allow served the longer-duration request.\n request.durationRequired ?? '',\n request.invocationProtocol || '',\n request.enableRuntimeChallenge ? '1' : '0',\n // callerMetadata fields contribute to risk model; include the ones\n // backend reads. sourceIp/userAgent/forwardedFor change per-request\n // so their inclusion effectively forces a re-check for any varying\n // client (the right behavior — IP-driven anomaly scoring shouldn't\n // be cached across IPs).\n request.callerMetadata?.sourceIp || '',\n request.callerMetadata?.userAgent || '',\n request.callerMetadata?.forwardedFor || '',\n request.callerMetadata?.agentCardUrl || '',\n // UAT2 Bug B (5.4.1): the commerce phase and cart identity DO affect the\n // backend verdict — the confirm leg is the ONLY leg that may execute\n // first-party settlement. Without these, a confirm within the cache TTL of\n // its start_checkout quote was served the cached quote-leg grant (no\n // settlementOutcome) and never reached the backend. Same F-A1-07 bug class.\n request.commercePhase || '',\n request.checkoutSessionId || '',\n ].join('|');\n}\n\n/**\n * Check if cached result is still valid\n */\nfunction getCachedResult(\n request: VerificationRequest,\n counterpartyId?: string\n): VerificationResult | null {\n const key = getCacheKey(request, counterpartyId);\n const cached = verificationCache.get(key);\n\n if (cached && cached.expiresAt > Date.now()) {\n return cached.result;\n }\n\n if (cached) {\n verificationCache.delete(key);\n }\n\n return null;\n}\n\n/**\n * Cache a verification result.\n *\n * 3.6.0: uniform 60s default. The earlier step-up TTL split (300s for\n * step-up verdicts) is gone — step-up verdicts are no longer cached AT ALL\n * (see the write predicate in verify()): a cached step_up_required result\n * carries a pollUrl that goes stale (consumed/expired) and, worse, keeps\n * denying retries that the owner has already approved. When `configuredTtl`\n * is set (truthy positive number), it's honoured for cacheable results.\n */\nconst DEFAULT_CACHE_TTL_SECONDS = 60;\n\nfunction cacheResult(\n request: VerificationRequest,\n result: VerificationResult,\n configuredTtl: number | undefined,\n counterpartyId?: string\n): void {\n const ttlSeconds = configuredTtl && configuredTtl > 0 ? configuredTtl : DEFAULT_CACHE_TTL_SECONDS;\n const key = getCacheKey(request, counterpartyId);\n verificationCache.set(key, {\n result,\n expiresAt: Date.now() + ttlSeconds * 1000,\n });\n}\n\n/**\n * Clear the verification cache\n */\nexport function clearCache(): void {\n verificationCache.clear();\n}\n\n/**\n * Extract agent credentials from various sources\n */\nexport function extractCredentials(\n headers: Record<string, string | string[] | undefined>,\n query?: Record<string, string | undefined>\n): AgentCredentials {\n const credentials: AgentCredentials = {};\n\n // Audit F-A1-12: ASTRA-ID shape validation. Accept only the canonical\n // pattern (ASTRA-/ASTRAE- prefix + 1-64 url-safe chars) to prevent CRLF\n // header injection or downstream interpolation surprises. Reject otherwise.\n const ASTRA_ID_PATTERN = /^ASTRAE?-[A-Za-z0-9_-]{1,64}$/;\n\n // Check for ASTRA-ID in headers (case-insensitive). Accepts the historical\n // X-Astra-Id name plus the X-Astra-AgentId / x-astra-agent-id alias the\n // partner asked for in #9a — both surface the same field.\n const astraIdHeader =\n headers['x-astra-id'] ||\n headers['X-Astra-Id'] ||\n headers['X-ASTRA-ID'] ||\n headers['x-astra-agentid'] ||\n headers['X-Astra-AgentId'] ||\n headers['x-astra-agent-id'] ||\n headers['X-Astra-Agent-Id'] ||\n headers['X-ASTRA-AGENT-ID'];\n if (astraIdHeader) {\n // Audit F-A1-11: guard array-confusion. If multiple X-Astra-Id headers\n // were sent (Express collapses to comma-joined string on most paths),\n // take only the first canonical-shaped one.\n const raw = Array.isArray(astraIdHeader)\n ? astraIdHeader[0]\n : typeof astraIdHeader === 'string'\n ? astraIdHeader\n : undefined;\n if (typeof raw === 'string' && ASTRA_ID_PATTERN.test(raw)) {\n credentials.astraId = raw;\n }\n }\n\n // Check for API key in headers\n const apiKeyHeader = headers['x-api-key'] || headers['X-Api-Key'] || headers['X-API-KEY'];\n if (apiKeyHeader) {\n credentials.apiKey = Array.isArray(apiKeyHeader) ? apiKeyHeader[0] : apiKeyHeader;\n }\n\n // Check Authorization header for Bearer token.\n // Audit F-A1-11: defensive type guard — Array.isArray gives a non-string,\n // and Express path quirks can produce undefined despite the truthy check.\n const authHeader = headers['authorization'] || headers['Authorization'];\n if (authHeader) {\n const authValue = Array.isArray(authHeader) ? authHeader[0] : authHeader;\n if (typeof authValue === 'string') {\n credentials.authorizationHeader = authValue;\n if (authValue.startsWith('Bearer ')) {\n credentials.jwt = authValue.slice(7);\n }\n }\n }\n\n // Check query parameters as fallback\n if (query) {\n if (query.astraId && !credentials.astraId) {\n credentials.astraId = query.astraId;\n }\n if (query.apiKey && !credentials.apiKey) {\n credentials.apiKey = query.apiKey;\n }\n }\n\n return credentials;\n}\n\n/**\n * Check if credentials are present\n */\nexport function hasCredentials(credentials: AgentCredentials): boolean {\n return !!(credentials.astraId || credentials.apiKey || credentials.jwt);\n}\n\n/**\n * Source of a synthesised guidance response. The sources are split — the\n * `'no_credentials'` shape is the original (caller has no AstraSync\n * credentials, suggest registration). The `'api_error'` shape is for when\n * the verify-access HTTP call itself failed (5xx, network, etc.) — DON'T\n * tell a verified-but-currently-blocked partner to \"register your agent\".\n *\n * 4.0.0 adds `'merchant_misconfig'`: the backend rejected THIS INTEGRATION'S\n * own API key (401 api_key_revoked/expired/invalid). Neither the agent's\n * fault nor a platform outage — retrying won't help, and the inbound agent\n * deserves to know the site operator's integration is broken (the\n * gadget-emporium failure mode: a rotated key silently 401ing every\n * credentialed agent for days).\n */\ntype GuidanceSource = 'no_credentials' | 'api_error' | 'merchant_misconfig';\n\n/**\n * MCP-connector steering (5.1.0). Present only when the backend's well-known\n * doc advertises a hosted bridge. The copy must directly counter the observed\n * model refusal (\"go register manually on the dashboard\"): registration via\n * the connector is the agent's own next action, with the human approval built\n * into the flow.\n */\nfunction mcpGuidance(urls?: WellKnownAgenticCommerce): GuidanceInfo['mcp'] {\n if (!urls?.mcpEndpoint) return undefined;\n return {\n endpoint: urls.mcpEndpoint,\n discoveryUrl: urls.mcpDiscoveryUrl,\n message:\n 'If you are operating inside an MCP-capable host (Claude, ChatGPT, Cursor, or any MCP client), ' +\n 'add the AstraSync MCP connector instead of integrating these URLs by hand: registration through ' +\n 'the connector is KEYLESS and HUMAN-APPROVED — your human approves in an in-chat card, and you ' +\n 'never see, hold, or transmit an API key, password, or private key.',\n };\n}\n\n/**\n * Create guidance response for unverified agents or for API-error fallback.\n *\n * The source is split so the `register your agent` template\n * doesn't fire on transient backend failures. Also threads `correlationId`\n * through so adapter `onDenied` handlers can surface it on the merchant's\n * response body for log correlation.\n */\nfunction createGuidanceResponse(\n _config: GatewayConfig,\n reason?: string,\n options: {\n source?: GuidanceSource;\n correlationId?: string;\n /** 3.12.0 (Trust Record): server-echoed attempt handle, threaded like correlationId. */\n attemptId?: string;\n urls?: WellKnownAgenticCommerce;\n /** 4.0.0: backend-provided remediation URLs for the merchant (misconfig source). */\n remediation?: { docsUrl?: string; manageUrl?: string };\n } = {}\n): VerificationResult {\n const source = options.source ?? 'no_credentials';\n const isApiError = source === 'api_error';\n const isMisconfig = source === 'merchant_misconfig';\n const urls = options.urls;\n\n const guidance: GuidanceInfo = isMisconfig\n ? {\n message:\n \"This site's AstraSync integration is misconfigured (its API key was revoked, expired, or rotated). \" +\n 'Your identity and the AstraSync platform are fine — contact the site operator. Retrying will not help.',\n registrationUrl: urls?.registrationUrl ?? '',\n documentationUrl: options.remediation?.docsUrl ?? urls?.documentationUrl ?? '',\n steps: [\n 'Report the failure to the site operator — their AstraSync API key needs rotating',\n 'Do not retry: the failure is deterministic until the operator updates their key',\n ],\n }\n : isApiError\n ? {\n message:\n 'Verification is temporarily unavailable. Retry with exponential backoff; if the issue persists, contact support with the correlationId.',\n registrationUrl: urls?.registrationUrl ?? '',\n documentationUrl: urls?.documentationUrl ?? '',\n steps: [\n 'Retry the request with exponential backoff',\n 'If failures persist, share the correlationId with support',\n ],\n }\n : {\n message:\n 'This service verifies AI agents before granting access. Please register your agent with AstraSync.',\n registrationUrl: urls?.registrationUrl ?? '',\n documentationUrl: urls?.documentationUrl ?? '',\n steps: [\n // MCP steering leads when the hosted bridge is advertised — the\n // connector is the agent-actionable path (keyless, human-approved).\n ...(urls?.mcpEndpoint\n ? [\n `Fastest path (inside an MCP host): add the AstraSync MCP connector at ${urls.mcpEndpoint} — keyless, human-approved registration`,\n ]\n : []),\n 'Register for an AstraSync account',\n 'Create and register your agent',\n 'Add your ASTRA-ID to request headers',\n 'Retry your request',\n ],\n ...(mcpGuidance(urls) && { mcp: mcpGuidance(urls) }),\n };\n\n return {\n // Round-18 G4: createGuidanceResponse fires for unverified-agent path or\n // API-error fallback. Identity is not verified (no agent resolved);\n // policy is not evaluated (we never reached the gate).\n identityVerified: false,\n policyAllowed: false,\n guidance,\n denialReasons: reason ? [reason] : ['No valid agent credentials provided'],\n // Round-10 (#47, O5): on API-error fallback, surface a typed failure so\n // partners (and their custom onDenied handlers) can branch on\n // dimension. Without this, the synthesised stub was indistinguishable\n // from a real policy deny.\n failures: isMisconfig\n ? [\n {\n dimension: 'verify_access.merchant_misconfigured',\n message: reason ?? 'The integration API key was rejected by AstraSync',\n guidance: guidance.message,\n },\n ]\n : isApiError\n ? [\n {\n dimension: 'verify_access.api_error',\n message: reason ?? 'Verification temporarily unavailable',\n guidance: guidance.message,\n },\n ]\n : undefined,\n // 4.0.0: typed marker so adapters render the misconfig envelope (503 +\n // MERCHANT_VERIFICATION_MISCONFIGURED) without string-matching.\n ...(isMisconfig && { misconfigured: true }),\n // 4.6.0: a transient api_error is retryable — mark it so consumers surface\n // \"temporarily unavailable, retry\" (recommendation 'error') instead of\n // coercing the absent recommendation to a policy 'deny'. Misconfig is\n // deterministic and intentionally NOT marked retryable.\n ...(isApiError && { retryable: true }),\n correlationId: options.correlationId,\n attemptId: options.attemptId,\n verifiedAt: new Date(),\n };\n}\n\n/**\n * Call the AstraSync verify-access API\n */\nasync function callVerifyAccessAPI(\n config: GatewayConfig,\n request: VerificationRequest\n): Promise<{\n success: boolean;\n access?: {\n allowed: boolean;\n reason?: string;\n /**\n * Aggregated denial failures (v2.9.8+). Empty / absent when allowed.\n * Each entry is `{ dimension, message, guidance? }` — see\n * `AccessFailure` for the contract.\n */\n failures?: Array<{ dimension: string; message: string; guidance?: string }>;\n requiresStepUp?: boolean;\n requiresApproval?: boolean;\n appliedPolicy?: {\n boundaryName: string;\n policyVersion: string;\n };\n counterparty?: {\n id: string;\n name: string;\n trustScoreRequirement: number;\n };\n };\n agent?: {\n kyaAgentId: string;\n astraId: string;\n name: string;\n trustScore: number;\n trustLevel: string;\n agentStatus: string;\n blockchainStatus: string;\n };\n developer?: {\n kyaOwnerId: string;\n fullName: string;\n email: string;\n identityVerified: boolean;\n trustScore: number;\n };\n organization?: {\n name: string;\n verified: boolean;\n trustScore: number;\n };\n /**\n * Structured explanation of the verification decision. Tells the merchant\n * WHY (id verified? challenge passed? request within PDLSS? trust score?)\n * without exposing thresholds, scope lists, or other-tenant counterparty\n * membership. Empty `attestations` unless the endpoint's access policy\n * declared `required_attestations`.\n */\n verificationContext?: {\n idVerified: boolean;\n runtimeChallenge: {\n status: 'passed' | 'skipped' | 'failed' | 'timeout' | 'not_supported';\n checkedAt: string | null;\n };\n pdlssCheck: {\n result: 'within' | 'exceeded' | 'denied' | 'not_evaluated';\n purpose: 'approved' | 'denied';\n scope: 'approved' | 'denied';\n };\n dynamicTrustScore: number;\n attestations: Array<{\n type: string;\n status: 'passed' | 'failed';\n /** LMAX-POC C1: underlying check timestamp for merchant freshness gates. */\n checkedAt: string;\n validUntil?: string;\n proofType: 'reference' | 'zkp';\n proof: string;\n }>;\n };\n error?: string;\n /**\n * 4.0.0: the backend 401'd this integration's OWN API key (revoked /\n * expired / invalid) — deterministic merchant-side misconfig, not a\n * transient failure. `misconfigCode` carries the backend's api_key_* code\n * and `remediation` its operator-facing URLs when present.\n */\n misconfig?: boolean;\n misconfigCode?: string;\n remediation?: { docsUrl?: string; manageUrl?: string };\n /**\n * When the verify-access server response carries a\n * correlationId on an error envelope, propagate it so the SDK can thread\n * it through createGuidanceResponse → adapter onDenied → merchant body.\n */\n correlationId?: string;\n /**\n * 3.12.0 (Trust Record): the server echoes the attempt-chain\n * handle top-level on every response branch (error envelopes included).\n */\n attemptId?: string;\n}> {\n const { credentials, ...requestData } = request;\n\n // Build the request body. agentId is omitted when not provided so the\n // server treats it as an anonymous canonical-flow call (Branch A/B/C).\n const body: Record<string, unknown> = {\n ...(credentials.astraId && { agentId: credentials.astraId }),\n ...(requestData.purpose && { purpose: requestData.purpose }),\n };\n\n // Add optional fields\n if (requestData.action) body.action = requestData.action;\n if (requestData.resourceType) body.resourceType = requestData.resourceType;\n if (requestData.resource) body.resource = requestData.resource;\n if (requestData.jurisdiction) body.jurisdiction = requestData.jurisdiction;\n if (requestData.transactionValue) body.transactionValue = requestData.transactionValue;\n if (requestData.currency) body.currency = requestData.currency;\n if (requestData.isSubAgentRequest) body.isSubAgentRequest = requestData.isSubAgentRequest;\n if (requestData.parentAgentId) body.parentAgentId = requestData.parentAgentId;\n if (requestData.subAgentDepth !== undefined) body.subAgentDepth = requestData.subAgentDepth;\n // Handshake Protocol v10 additions\n if (requestData.enableRuntimeChallenge)\n body.enableRuntimeChallenge = requestData.enableRuntimeChallenge;\n if (requestData.createSession) body.createSession = requestData.createSession;\n if (requestData.durationRequired) body.durationRequired = requestData.durationRequired;\n if (requestData.counterpartyType) body.counterpartyType = requestData.counterpartyType;\n if (requestData.counterpartyUrl) body.counterpartyUrl = requestData.counterpartyUrl;\n if (config.counterpartyId) body.counterpartyId = config.counterpartyId;\n if (requestData.runtimeChallengeOptions)\n body.runtimeChallengeOptions = requestData.runtimeChallengeOptions;\n // Round-12 (F19): transport-vs-intent separation. MCP middleware sets\n // this to 'mcp'; non-MCP callers leave it unset.\n if (requestData.invocationProtocol) body.invocationProtocol = requestData.invocationProtocol;\n // 5.3.0 (astra-pay): checkout-leg discriminator — first-party settlement\n // fires only on 'confirm'; absent keeps pre-phase server behavior.\n if (requestData.commercePhase) body.commercePhase = requestData.commercePhase;\n // Per-cart idempotency key (checkout session id) forwarded on the confirm\n // leg so concurrent confirms for one cart charge at most once.\n if (requestData.checkoutSessionId) body.checkoutSessionId = requestData.checkoutSessionId;\n // Order-plane cart lines (receipts + fulfillment email) — informational.\n if (requestData.checkoutItems) body.checkoutItems = requestData.checkoutItems;\n // 5.6.0 (astra-pay): transit-only fulfilment contact — echoed back in\n // result.fulfilment for first-party confirms, never persisted server-side.\n if (requestData.buyerEmail) body.buyerEmail = requestData.buyerEmail;\n // 3.9.0 (§33.5 #1): raw commerce artifacts forwarded verbatim — the\n // backend's Step 0.5 pipeline does the cryptographic verification\n // server-side (adapters forward, never verify locally).\n if (requestData.commerceArtifacts) body.commerceArtifacts = requestData.commerceArtifacts;\n // 3.12.0 (Trust Record, §33.5 #3): attempt-chain handle + consideration set,\n // forwarded skip-when-undefined (observedMetadata precedent) — pure\n // observational pass-through; the server echoes attemptId on every branch.\n if (requestData.attemptId) body.attemptId = requestData.attemptId;\n if (requestData.considerationSet) body.considerationSet = requestData.considerationSet;\n\n // Round-13 (F14 closure / R13-7): emit the SDK package version on every\n // verify-access body so the backend can auto-populate `kya_counterparty.\n // sdk_version` for the calling endpoint. Body field (not User-Agent\n // header) is the canonical channel — works in Node, browser, behind\n // Cloudflare, and across SDK bundlers without environment-specific\n // header gymnastics. Backend's `validation.ts:verifyAccessSchema`\n // accepts the semver regex; the auto-pop logic is forward-only.\n body.sdkVersion = SDK_VERSION;\n\n // Forward caller metadata when present. Merges the legacy top-level\n // clientIp/userAgent into the nested block for backward compatibility.\n if (requestData.callerMetadata || requestData.clientIp || requestData.userAgent) {\n const meta = {\n ...(requestData.clientIp && { sourceIp: requestData.clientIp }),\n ...(requestData.userAgent && { userAgent: requestData.userAgent }),\n ...requestData.callerMetadata,\n };\n if (Object.keys(meta).length > 0) body.callerMetadata = meta;\n }\n\n // Build headers\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...config.customHeaders,\n };\n\n // verify-access requires authentication. Use ONLY the merchant's\n // configured apiKey for outbound auth. Previously the caller's inbound\n // Authorization header took priority, which pivoted the verify-access\n // call to the caller's identity — letting an attacker who supplied\n // their own Authorization header trigger verify-access calls under\n // THEIR account and observe the resulting verdicts for arbitrary\n // lookups they triggered via the merchant. Audit F-A1-10.\n //\n // The caller-supplied JWT (if any) is already extracted to\n // credentials.jwt and travels in the verify-access request body so\n // backend can evaluate it as the agent's identity claim — separate from\n // the merchant-attribution auth on the outbound HTTPS call.\n if (config.apiKey) {\n headers['Authorization'] = `Bearer ${config.apiKey}`;\n // Legacy header kept for compatibility with any middleware that reads it directly.\n headers['X-API-Key'] = config.apiKey;\n }\n\n try {\n // 4.0.0: hard timeout — without one, a backend that accepts the\n // connection but never answers hangs the merchant's middleware and every\n // inbound agent request behind it (observed live on a partner property).\n // Timeouts land on the catch path below → api_error (fail-closed),\n // NOT misconfig. The edge adapter races its own tighter withBudget.\n const response = await sdkFetch(`${config.apiBaseUrl}/agents/verify-access`, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(config.verifyTimeoutMs ?? 10_000),\n });\n\n const data = await response.json();\n\n // v2.3.8 (defect #29): treat 410 Gone as a deterministic deactivated-endpoint\n // signal. Older SDKs may treat any non-2xx as transient and retry; v2.3.8+\n // surfaces it as a structured denial with `reason: 'endpoint_deactivated'`\n // so callers can distinguish \"endpoint gone\" from \"endpoint denied this\".\n if (response.status === 410) {\n return {\n success: true,\n // 3.12.0 (Trust Record): keep the server-echoed attempt handle even on\n // the synthesised 410 deny shape (echoed on every branch).\n attemptId: typeof data?.attemptId === 'string' ? data.attemptId : undefined,\n access: {\n allowed: false,\n reason: 'endpoint_deactivated',\n failures: [\n {\n dimension: 'endpoint.deactivated',\n message:\n typeof data?.message === 'string' ? data.message : 'Endpoint has been deactivated',\n guidance:\n typeof data?.guidance === 'string'\n ? data.guidance\n : 'Reactivate via POST /api/endpoints/{id}/reactivate, or update the URL on the calling agent.',\n },\n ],\n },\n };\n }\n\n if (!response.ok) {\n // 4.0.0: a 401 from verify-access can ONLY mean the backend rejected\n // THIS INTEGRATION'S own API key — agent denials come back as 200 with\n // access.allowed=false. Surface it as merchant-misconfig, not a\n // transient api_error: it is deterministic until the operator rotates\n // the key, and the \"retry with backoff\" template actively misleads.\n // Backends ≥ this round also send code: api_key_* + remediation URLs.\n if (response.status === 401) {\n return {\n success: false,\n error: data.message || data.error || 'Integration API key rejected',\n misconfig: true,\n misconfigCode: typeof data?.code === 'string' ? data.code : undefined,\n remediation:\n data?.remediation && typeof data.remediation === 'object'\n ? (data.remediation as { docsUrl?: string; manageUrl?: string })\n : undefined,\n correlationId: typeof data?.correlationId === 'string' ? data.correlationId : undefined,\n attemptId: typeof data?.attemptId === 'string' ? data.attemptId : undefined,\n };\n }\n // Round-10 (#47, O5): propagate correlationId on the error path too if\n // the server happened to include one (some 5xx error envelopes carry\n // it). Lets the SDK pass it through to the adapter onDenied handler.\n return {\n success: false,\n error: data.message || data.error || `API returned ${response.status}`,\n correlationId: typeof data?.correlationId === 'string' ? data.correlationId : undefined,\n attemptId: typeof data?.attemptId === 'string' ? data.attemptId : undefined,\n };\n }\n\n return data;\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n return {\n success: false,\n error: `Failed to call verify-access API: ${message}`,\n };\n }\n}\n\n/**\n * Options for a single verify() call (as opposed to GatewayConfig, which is\n * per-gateway). Mirrors the Java SDK's `verify(request, bypassCache)`.\n */\nexport interface VerifyOptions {\n /**\n * Skip the cache READ for this call so the request is guaranteed to reach\n * the backend (the result is still written to the cache if cacheable).\n * Used by the step-up hold-and-poll retry: the re-verify after an approval\n * must hit the server to redeem the single-use approval.\n */\n bypassCache?: boolean;\n}\n\n/**\n * Main verification function\n */\nexport async function verify(\n config: GatewayConfig,\n request: VerificationRequest,\n options?: VerifyOptions\n): Promise<VerificationResult> {\n const mergedConfig = { ...DEFAULT_CONFIG, ...config };\n\n // v2.5.0: read well-known URLs from cache (prefetched by adapter at middleware creation).\n // Synchronous — never triggers a fetch. If cache is empty, guidance URLs are empty strings.\n const urls = mergedConfig.apiBaseUrl\n ? getCachedWellKnownUrls(mergedConfig.apiBaseUrl)\n : undefined;\n\n // One-time init self-test — fire-and-forget by default, never blocks verify().\n // Audit F-A6-33: when GatewayConfig.strictInit is set, the init promise is\n // awaited and any failure throws synchronously so callers learn about\n // misconfigured apiBaseUrl on the first verify() call rather than silently\n // running with broken auth.\n if (!initCheckPerformed && !mergedConfig.disableInitChecks && mergedConfig.apiBaseUrl) {\n if (mergedConfig.strictInit) {\n await performInitCheck(\n mergedConfig.apiBaseUrl,\n mergedConfig.debug,\n true,\n mergedConfig.apiKey\n );\n } else {\n void performInitCheck(\n mergedConfig.apiBaseUrl,\n mergedConfig.debug,\n false,\n mergedConfig.apiKey\n );\n }\n }\n\n // Deprecation warning for v2.3.0 removed config fields. Fires once per process.\n if (\n !deprecationWarningShown &&\n (config.minTrustScore !== undefined || config.minTrustScoreForFull !== undefined)\n ) {\n deprecationWarningShown = true;\n console.warn(\n '[VerificationGateway] minTrustScore / minTrustScoreForFull are deprecated in v2.3.0 ' +\n 'and have no effect. Server is now the single source of truth for access decisions ' +\n '(verified ID + runtime challenge + PDLSS + trust score). To gate access ' +\n \"to an endpoint, configure the endpoint's trust_score_requirement server-side.\"\n );\n }\n\n // v2.3.0: anonymous traffic no longer short-circuits here. We forward the\n // request to the server with no agentId; the server applies the endpoint's\n // unverifiedAgentPolicy and returns advisory. createGuidanceResponse remains\n // as the offline fallback if the API itself fails (handled below).\n\n // Check cache first. Caching on unless caller explicitly sets cacheTtl: 0\n // to disable. Undefined falls through to the 60s default at cacheResult\n // write time. options.bypassCache skips the read only (hold-and-poll retry\n // must reach the backend to redeem its approval).\n if (mergedConfig.cacheTtl !== 0 && !options?.bypassCache) {\n const cached = getCachedResult(request, mergedConfig.counterpartyId);\n if (cached) {\n if (mergedConfig.debug) {\n console.log('[VerificationGateway] Returning cached result');\n }\n // 3.12.0 (Trust Record, §33.5 #3): attemptId is excluded from the cache\n // key, so the stored result may carry a PRIOR attempt's id. Overwrite it\n // with this request's own attemptId — or drop it when this request has\n // none — a cached verdict must never leak another attempt's handle.\n // Shallow clone: never mutate the stored entry (a concurrent holder of\n // the same cached object may still be reading it).\n const hit: VerificationResult = { ...cached };\n if (request.attemptId) {\n hit.attemptId = request.attemptId;\n } else {\n delete hit.attemptId;\n }\n return hit;\n }\n }\n\n // Inject counterparty info from config if not already set in request\n const enrichedRequest = { ...request };\n if (!enrichedRequest.counterpartyUrl && mergedConfig.counterpartyUrl) {\n enrichedRequest.counterpartyUrl = mergedConfig.counterpartyUrl;\n }\n if (!enrichedRequest.counterpartyType && mergedConfig.counterpartyType) {\n enrichedRequest.counterpartyType = mergedConfig.counterpartyType;\n }\n\n // Call the API\n if (mergedConfig.debug) {\n console.log('[VerificationGateway] Calling verify-access API');\n }\n\n const apiResponse = await callVerifyAccessAPI(mergedConfig, enrichedRequest);\n\n // 3.6.0: the server emits a top-level denialReasons array on every deny\n // path (same strings as the failure messages). Non-empty → authoritative;\n // absent/empty → fall back to the client-side reconstructions below.\n const rawServerDenialReasons = (apiResponse as Record<string, unknown>).denialReasons;\n const serverDenialReasons =\n Array.isArray(rawServerDenialReasons) && rawServerDenialReasons.length > 0\n ? (rawServerDenialReasons as string[])\n : undefined;\n\n // Handle API errors\n if (!apiResponse.success) {\n // Round-10 (#47, O5): distinguish API errors from missing-credentials.\n // The previous default tagged any failure with the \"register your\n // agent\" template, which is misleading to a verified partner whose\n // verify-access call hit a 500. The `api_error` source surfaces a\n // typed `verify_access.api_error` failure entry instead.\n // 4.0.0: a rejected merchant key gets its own source — deterministic\n // misconfig must not wear the \"temporarily unavailable, retry\" template.\n return createGuidanceResponse(mergedConfig, apiResponse.error, {\n source: apiResponse.misconfig ? 'merchant_misconfig' : 'api_error',\n correlationId: (apiResponse as { correlationId?: string }).correlationId,\n attemptId: (apiResponse as { attemptId?: string }).attemptId,\n remediation: apiResponse.remediation,\n urls,\n });\n }\n\n // Check access result\n if (!apiResponse.access?.allowed) {\n // v2.9.8 (defect M1): aggregated failures across every gate that\n // denied. Surface them on the result so the integrator can see every\n // blocker in one go instead of the previous fail-fast cascade.\n const aggregatedFailures = (apiResponse.access as Record<string, unknown> | undefined)\n ?.failures as Array<{ dimension: string; message: string; guidance?: string }> | undefined;\n // Round-18 G4: backend denied access (PDLSS or other gate); identity status\n // depends on whether the backend resolved the caller. Read from\n // verificationContext.idVerified; default false if absent (anonymous or\n // identity-fail paths land here too). policyAllowed is false by definition\n // in this branch (apiResponse.access.allowed === false).\n const idVerifiedFromBackend =\n (apiResponse.verificationContext as { idVerified?: boolean } | undefined)?.idVerified ===\n true;\n const result: EnhancedVerificationResult = {\n identityVerified: idVerifiedFromBackend,\n policyAllowed: false,\n // 3.6.0: the server now emits top-level denialReasons on every deny\n // path — prefer it verbatim; the failure-message reconstruction remains\n // as the fallback for older backends.\n denialReasons:\n serverDenialReasons ??\n (aggregatedFailures && aggregatedFailures.length > 0\n ? aggregatedFailures.map((f) => f.message)\n : apiResponse.access?.reason\n ? [apiResponse.access.reason]\n : ['Access denied']),\n failures: aggregatedFailures,\n requiresStepUp: apiResponse.access?.requiresStepUp,\n requiresApproval: apiResponse.access?.requiresApproval,\n guidance: {\n message: apiResponse.access?.reason || 'Access denied by PDLSS policy',\n registrationUrl: urls?.registrationUrl ?? '',\n documentationUrl: urls?.documentationUrl ?? '',\n // 5.1.0: anonymous callers land on this branch — steer MCP-hosted\n // agents to the connector (this is what the edge deny body surfaces).\n ...(mcpGuidance(urls) && { mcp: mcpGuidance(urls) }),\n },\n verifiedAt: new Date(),\n // Extract sessionId so decisions can be recorded for denials too\n sessionId: (apiResponse as Record<string, unknown>).sessionId as string | undefined,\n // Anonymous traffic has no session → correlationId is the per-attempt\n // linking key (the sessionId-equivalent for anonymous callers).\n correlationId: (apiResponse as Record<string, unknown>).correlationId as string | undefined,\n // 3.12.0 (Trust Record): server echoes the attempt-chain handle on\n // every branch — denials included (the funnel outlives one deny).\n attemptId: (apiResponse as Record<string, unknown>).attemptId as string | undefined,\n recommendation: (apiResponse as Record<string, unknown>)\n .recommendation as EnhancedVerificationResult['recommendation'],\n recommendationReasons: (apiResponse as Record<string, unknown>).recommendationReasons as\n | string[]\n | undefined,\n stepUpApproval: (apiResponse as Record<string, unknown>).stepUpApproval as\n | StepUpApprovalInfo\n | undefined,\n settlement: (apiResponse as Record<string, unknown>).settlement as\n | SettlementArtifact\n | undefined,\n settlementOutcome: (apiResponse as Record<string, unknown>).settlementOutcome as\n | SettlementOutcomeInfo\n | undefined,\n // 5.5.0 self-settlement: merchant-only material — passes through to the\n // MERCHANT caller only (bridge callers strip it before the agent plane).\n settlementToken: (apiResponse as Record<string, unknown>).settlementToken as\n | MerchantSettlementToken\n | undefined,\n // 5.6.0: fulfilment contact — merchant-only lane, same strip rule.\n fulfilment: (apiResponse as Record<string, unknown>).fulfilment as FulfilmentInfo | undefined,\n };\n\n return result;\n }\n\n // Build successful result\n const agent: VerifiedAgent | undefined = apiResponse.agent\n ? {\n astraId: apiResponse.agent.astraId,\n name: apiResponse.agent.name,\n trustScore: apiResponse.agent.trustScore,\n trustLevel: getTrustLevel(apiResponse.agent.trustScore),\n blockchainVerified: apiResponse.agent.blockchainStatus === 'verified',\n status: apiResponse.agent.agentStatus as VerifiedAgent['status'],\n }\n : undefined;\n\n const developer: VerifiedDeveloper | undefined = apiResponse.developer\n ? {\n astradId: apiResponse.developer.kyaOwnerId,\n name: apiResponse.developer.fullName,\n trustScore: apiResponse.developer.trustScore || 0,\n verified: apiResponse.developer.identityVerified,\n }\n : undefined;\n\n const organization: VerifiedOrganization | undefined = apiResponse.organization\n ? {\n name: apiResponse.organization.name,\n verified: apiResponse.organization.verified,\n trustScore: apiResponse.organization.trustScore,\n }\n : undefined;\n\n // Verification context — structured \"why\" the merchant gets in v2.2.4+.\n // Carries appliedPolicy (no UUIDs), pdlssCheck summary, dynamic trust score,\n // and policy-driven attestations. Replaces the old over-sharing `pdlss` block.\n const verificationContext = apiResponse.verificationContext;\n\n const result: EnhancedVerificationResult = {\n // 4.5.0 (probe F1): read idVerified from verificationContext with the\n // SAME absent⇒false default as the deny branch. The previous `!== false`\n // default manufactured `identityVerified: true` for anonymous\n // allow_full/allow_partial/audit responses (which allow access but omit\n // verificationContext entirely) — the \"anonymous caller labelled\n // verified\" defect. Every authenticated success response has carried\n // `verificationContext.idVerified: true` since v2.2.4, so a truth claim\n // this load-bearing must never be defaulted on.\n identityVerified:\n (apiResponse.verificationContext as { idVerified?: boolean } | undefined)?.idVerified ===\n true,\n policyAllowed: true,\n agent,\n developer,\n organization,\n appliedPolicy: apiResponse.access?.appliedPolicy,\n verificationContext,\n requiresStepUp: apiResponse.access?.requiresStepUp,\n requiresApproval: apiResponse.access?.requiresApproval,\n verifiedAt: new Date(),\n cacheTtl: mergedConfig.cacheTtl,\n // Handshake Protocol v10 enhanced fields (present when backend returns them)\n sessionId: (apiResponse as Record<string, unknown>).sessionId as string | undefined,\n // v2.3.10 (defect #34, round-4): anonymous responses surface correlationId\n // (no session row exists for unverified callers).\n correlationId: (apiResponse as Record<string, unknown>).correlationId as string | undefined,\n // 3.12.0 (Trust Record): server-echoed attempt-chain handle.\n attemptId: (apiResponse as Record<string, unknown>).attemptId as string | undefined,\n runtimeChallenge: (apiResponse as Record<string, unknown>).runtimeChallenge as\n | RuntimeChallengeResult\n | undefined,\n tokenGuidance: (apiResponse as Record<string, unknown>).tokenGuidance as\n | TokenGuidance\n | undefined,\n recommendation: (apiResponse as Record<string, unknown>)\n .recommendation as EnhancedVerificationResult['recommendation'],\n recommendationReasons: (apiResponse as Record<string, unknown>).recommendationReasons as\n | string[]\n | undefined,\n warningHeader: (apiResponse as Record<string, unknown>).warningHeader as\n | { name: string; value: string }\n | undefined,\n stepUpApproval: (apiResponse as Record<string, unknown>).stepUpApproval as\n | StepUpApprovalInfo\n | undefined,\n settlement: (apiResponse as Record<string, unknown>).settlement as\n | SettlementArtifact\n | undefined,\n settlementOutcome: (apiResponse as Record<string, unknown>).settlementOutcome as\n | SettlementOutcomeInfo\n | undefined,\n settlementToken: (apiResponse as Record<string, unknown>).settlementToken as\n | MerchantSettlementToken\n | undefined,\n // 5.6.0: fulfilment contact — merchant-only lane, same strip rule.\n fulfilment: (apiResponse as Record<string, unknown>).fulfilment as FulfilmentInfo | undefined,\n };\n\n // Enforce AstraSync recommendation\n if (result.recommendation === 'deny') {\n // Round-18 G4: recommendation-driven deny lands on the success-path\n // construction (identity was resolved). Flip policy only — identity stays\n // verified — so adapters return 403 (re-auth won't help; the policy\n // decision is the blocker).\n result.policyAllowed = false;\n // 3.6.0: server-sent top-level denialReasons wins; recommendationReasons\n // reconstruction is the fallback for older backends.\n result.denialReasons = serverDenialReasons ??\n result.recommendationReasons ?? ['Access denied by AstraSync recommendation'];\n result.guidance = result.runtimeChallenge\n ? {\n message: `Verification failed: ${result.runtimeChallenge.reason || 'runtime challenge failed'}`,\n registrationUrl: urls?.registrationUrl ?? '',\n documentationUrl: urls?.documentationUrl ?? '',\n }\n : {\n message: result.recommendationReasons?.[0] || 'Access denied by AstraSync recommendation',\n registrationUrl: urls?.registrationUrl ?? '',\n documentationUrl: urls?.documentationUrl ?? '',\n };\n } else if (result.recommendation === 'step_up_required') {\n // The escalation signal rides on `requiresStepUp` / `stepUpApproval`, not\n // on any masquerade of the (now-removed) access band.\n result.requiresStepUp = true;\n result.denialReasons = serverDenialReasons ??\n result.recommendationReasons ?? ['Step-up verification required'];\n }\n\n // Cache the result. Never cache denials (agent may fix challenge endpoint\n // and retry) NOR step-up escalations (3.6.0 — the same bug the Java SDK\n // had: a cached step_up_required verdict keeps denying retries the owner\n // has already approved, and its pollUrl goes stale once consumed/expired).\n // Escalations stay uncached even when the caller pins an explicit cacheTtl.\n const escalates =\n result.requiresStepUp === true ||\n result.requiresApproval === true ||\n result.recommendation === 'step_up_required';\n if (mergedConfig.cacheTtl !== 0 && result.recommendation !== 'deny' && !escalates) {\n cacheResult(request, result, mergedConfig.cacheTtl, mergedConfig.counterpartyId);\n }\n\n return result;\n}\n\n/**\n * Record a counterparty's grant/deny decision for a verification session.\n * Fire-and-forget — errors are silently swallowed.\n */\nexport async function recordDecision(\n config: GatewayConfig,\n sessionId: string,\n decision: 'granted' | 'denied',\n reason?: string\n): Promise<void> {\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (config.apiKey) {\n headers['Authorization'] = `Bearer ${config.apiKey}`;\n headers['X-API-Key'] = config.apiKey;\n }\n\n await sdkFetch(`${config.apiBaseUrl}/agents/verify-access/${sessionId}/decision`, {\n method: 'POST',\n headers,\n body: JSON.stringify({ decision, reason }),\n }).catch(() => {\n /* fire-and-forget */\n });\n}\n\n/**\n * Report post-hoc consideration/outcome data for an attempt chain (Trust\n * Record). Use when the signal never reached verify-access: a\n * catalog served from a local cache, a transport-side deny (sku not found,\n * over budget), or a terminal outcome (settled / blocked on step-up).\n * Authenticated with the same credentials as verify(); the backend responds\n * 202 and folds the data into the attempt chain keyed by `attemptId`.\n *\n * Fire-and-forget — errors are silently swallowed, never throws.\n */\nexport async function reportAttempt(config: GatewayConfig, report: AttemptReport): Promise<void> {\n const apiBaseUrl = config.apiBaseUrl || DEFAULT_CONFIG.apiBaseUrl!;\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (config.apiKey) {\n headers['Authorization'] = `Bearer ${config.apiKey}`;\n headers['X-API-Key'] = config.apiKey;\n }\n\n // counterpartyId resolution mirrors reportUnregisteredAttempt: an explicit\n // report value wins; otherwise attribute to the configured endpoint.\n const body = {\n ...report,\n ...(!report.counterpartyId &&\n config.counterpartyId && { counterpartyId: config.counterpartyId }),\n };\n\n await sdkFetch(`${apiBaseUrl}/agents/verify-access/attempt-report`, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n }).catch(() => {\n /* fire-and-forget */\n });\n}\n\n/**\n * Fetch the per-route policy for an endpoint from the AstraSync backend.\n * v2.9.7 moved policy authority into the dashboard — the SDK no longer\n * accepts `routes` from merchant-side source code, it fetches them from\n * here on init (and refreshes periodically).\n *\n * Returns `null` when the request fails for any reason — the caller decides\n * how to fall back (the middleware allows-all when no policy is loaded so\n * a misconfigured init doesn't take down the merchant's API).\n */\nexport async function fetchRoutes(\n config: GatewayConfig,\n counterpartyId: string\n): Promise<RouteAccessConfigShape[] | null> {\n if (!counterpartyId) return null;\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (config.apiKey) {\n headers['Authorization'] = `Bearer ${config.apiKey}`;\n headers['X-API-Key'] = config.apiKey;\n }\n try {\n const response = await sdkFetch(\n `${config.apiBaseUrl}/endpoints/${encodeURIComponent(counterpartyId)}/routes`,\n { method: 'GET', headers }\n );\n if (!response.ok) return null;\n const body = (await response.json()) as { data?: { routes?: RouteAccessConfigShape[] } };\n return body.data?.routes ?? [];\n } catch {\n return null;\n }\n}\n\n/**\n * Minimal shape of an EndpointRoute as the SDK consumes it. Mirrors the\n * server's `EndpointRoute` type and the SDK's `RouteAccessConfig` — same\n * JSON moves between server and SDK unchanged.\n */\nexport interface RouteAccessConfigShape {\n pattern: string;\n method: string;\n /** Pass through unenforced (observe). Replaces `minAccessLevel: 'none'`. */\n observe?: boolean;\n minTrustScore?: number;\n requiredPurposes?: string[];\n allowedPurposes?: string[];\n allowedJurisdictions?: string[];\n maxDuration?: number;\n maxTransactionValue?: number;\n requirePurpose?: boolean;\n /** Send-mapping — see RouteAccessConfig in types.ts. */\n purpose?: string;\n action?: string;\n}\n\n/**\n * Verify an agent AND automatically record the grant/deny decision.\n *\n * This is the recommended entry point for counterparties that call verify()\n * directly (e.g. MCP servers) rather than using createMiddleware().\n * It adds createSession: true, then fire-and-forgets the decision.\n */\nexport async function verifyAndRecord(\n config: GatewayConfig,\n request: VerificationRequest,\n options?: VerifyOptions\n): Promise<VerificationResult> {\n const mergedConfig = { ...DEFAULT_CONFIG, ...config };\n const result = await verify(mergedConfig, { ...request, createSession: true }, options);\n const sessionId = (result as EnhancedVerificationResult).sessionId;\n\n if (sessionId) {\n // Round-18 G4: a session is \"granted\" only if identity verified AND\n // policy allowed; either failing is a deny.\n if (result.identityVerified && result.policyAllowed) {\n recordDecision(mergedConfig, sessionId, 'granted').catch(() => {});\n } else {\n recordDecision(mergedConfig, sessionId, 'denied', result.denialReasons?.[0]).catch(() => {});\n }\n }\n\n return result;\n}\n\n/**\n * Report an unregistered agent attempt (no AstraSync credentials).\n * Called by SDK adapters when an agent is redirected to /docs/agent-access.\n * Fire-and-forget — errors are silently swallowed.\n */\nexport async function reportUnregisteredAttempt(\n config: GatewayConfig,\n data: {\n /**\n * 3.6.0: optional — the backend attributes by counterpartyId first (sent\n * from config below) and requires at least ONE of counterpartyId/URL.\n * A null/undefined URL is omitted from the body, not sent as null.\n */\n counterpartyUrl?: string;\n counterpartyType?: string;\n sourceIp?: string;\n userAgent?: string;\n requestPath?: string;\n requestMethod?: string;\n /**\n * 3.9.0 — edge-adapter evidence fields, persisted into the\n * event's eventData by the backend: `protocol` = detected transport/\n * credential protocol; `evidence` = light crypto-free detection detail.\n */\n protocol?: string;\n evidence?: Record<string, unknown>;\n /**\n * Maximal metadata capture — the full sanitised metadata for an\n * unregistered caller (every signal legitimately visible on the wire).\n * Persisted into eventData; feeds platform attribution and (via\n * correlationId) registration auto-fill. Fire-and-forget, so free.\n */\n observedMetadata?: ObservedMetadata;\n }\n): Promise<void> {\n const apiBaseUrl = config.apiBaseUrl || DEFAULT_CONFIG.apiBaseUrl!;\n\n const { counterpartyUrl, ...rest } = data;\n const body = {\n ...rest,\n ...(counterpartyUrl && { counterpartyUrl }),\n ...(config.counterpartyId && { counterpartyId: config.counterpartyId }),\n };\n\n await sdkFetch(`${apiBaseUrl}/verification-activity/unregistered-attempt`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n }).catch(() => {\n /* fire-and-forget */\n });\n}\n\n/**\n * Report a counterparty-side PDLSS pre-check failure.\n * Called by SDK adapters when the agent's requested PDLSS exceeds\n * counterparty-defined maximums BEFORE calling verify-access.\n * Fire-and-forget — errors are silently swallowed.\n */\nexport async function reportCounterpartyPreCheckFailure(\n config: GatewayConfig,\n data: {\n agentId: string;\n counterpartyUrl: string;\n counterpartyType?: string;\n failures: Array<{\n field: string;\n requested: string | number;\n limit: string | number | string[];\n message: string;\n }>;\n requestPath?: string;\n requestMethod?: string;\n }\n): Promise<void> {\n const apiBaseUrl = config.apiBaseUrl || DEFAULT_CONFIG.apiBaseUrl!;\n\n await sdkFetch(`${apiBaseUrl}/verification-activity/counterparty-pre-check-failure`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(data),\n }).catch(() => {\n /* fire-and-forget */\n });\n}\n\n/**\n * Quick verification — checks credentials and policy in one call.\n *\n * The return shape mirrors `VerificationResult`'s split — partners\n * writing custom handlers around `quickVerify` get the same identity/policy\n * distinction as those calling `verify()` directly. Map to HTTP status the\n * same way: `!identityVerified` → 401; `identityVerified && !policyAllowed`\n * → 403.\n */\nexport async function quickVerify(\n config: GatewayConfig,\n credentials: AgentCredentials\n): Promise<{\n identityVerified: boolean;\n policyAllowed: boolean;\n reason?: string;\n}> {\n const result = await verify(config, {\n credentials,\n purpose: 'verification',\n });\n\n return {\n identityVerified: result.identityVerified,\n policyAllowed: result.policyAllowed,\n reason: result.denialReasons?.[0],\n };\n}\n","/**\n * Helpers over {@link NormalizedRequest} — header access, URL\n * reconstruction, and the full sanitized metadata capture.\n */\n\nimport {\n sanitizeHeaders,\n CAPTURE_SCHEMA_VERSION,\n type ObservedMetadata,\n} from '../metadata-capture';\nimport type { NormalizedRequest } from './types';\n\n/** Value of a header (name matched case-insensitively), or undefined. */\nexport function headerValue(req: NormalizedRequest, name: string): string | undefined {\n return req.headers[name.toLowerCase()];\n}\n\n/** Full request URL as the origin will see it (scheme fixed to https). */\nexport function requestUrl(req: NormalizedRequest, host: string): string {\n const qs = req.querystring ? `?${req.querystring}` : '';\n return `https://${host}${req.uri}${qs}`;\n}\n\n/**\n * The FULL sanitized metadata capture for one request: every inbound\n * header (secrets stripped, credential headers reduced to a safe format\n * prefix) plus the connection-layer block the platform collected. The\n * edge is the richest capture point — the headers are already in memory —\n * and this is pure string work, so it adds no page latency. Forwarded on\n * both the verify-access call and the telemetry beacon.\n */\nexport function buildObservedMetadata(req: NormalizedRequest): ObservedMetadata {\n const { headers, apiKeyFormat, platformHeaders, cookieCount } = sanitizeHeaders(req.headers);\n const connection = req.connection ?? {};\n const queryKeys = extractQueryKeys(req.querystring);\n return {\n headers,\n ...(apiKeyFormat && { apiKeyFormat }),\n ...(platformHeaders && { platformHeaders }),\n ...(Object.keys(connection).length > 0 && { connection }),\n ...(cookieCount !== undefined && { cookieCount }),\n ...(queryKeys && { queryKeys }),\n schemaVersion: CAPTURE_SCHEMA_VERSION,\n };\n}\n\n/** Backend bounds on queryKeys (mirrored in observedMetadataSchema). */\nconst MAX_QUERY_KEYS = 32;\nconst MAX_QUERY_KEY_CHARS = 64;\n\n/**\n * Query-string parameter NAMES only — deduped, lowercased, bounded. Values\n * are never captured (OAuth codes, tokens, PII); the name set alone\n * fingerprints client shape. Exported for tests.\n */\nexport function extractQueryKeys(querystring: string | undefined): string[] | undefined {\n if (!querystring) return undefined;\n let params: URLSearchParams;\n try {\n params = new URLSearchParams(querystring);\n } catch {\n return undefined;\n }\n const keys: string[] = [];\n for (const key of params.keys()) {\n const normalized = key.toLowerCase().slice(0, MAX_QUERY_KEY_CHARS);\n if (normalized && !keys.includes(normalized)) {\n keys.push(normalized);\n if (keys.length >= MAX_QUERY_KEYS) break;\n }\n }\n return keys.length > 0 ? keys : undefined;\n}\n","/**\n * Crypto-free commerce-protocol detection.\n *\n * The edge only SNIFFS — header shapes, compact-JWT patterns, body field\n * names — and packages what it saw as raw `CommerceArtifactsPayload` for\n * verify-access, whose server-side pipeline does the authoritative parsing\n * and cryptographic verification. Nothing here imports jose/sd-jwt/\n * signature libraries: detection must stay cheap enough to run on every\n * non-human request, and verification must happen exactly once, in the\n * canonical sink, where it is recorded.\n */\n\nimport type { CommerceArtifactsPayload } from '../types';\nimport { headerValue, requestUrl } from './request';\nimport type { NormalizedRequest } from './types';\n\nexport interface DetectedCommerce {\n /** Detection-order label: rfc9421-agent-pay | rfc9421-tap | rfc9421-web-bot-auth | vi-sd-jwt | ap2 | acp | ucp | mpp | x402 */\n protocol: string;\n artifacts: CommerceArtifactsPayload;\n /** Light detection detail for beacons/audit — never secrets or full credentials. */\n evidence: Record<string, unknown>;\n}\n\n/** Compact SD-JWT: JWT + `~`-separated disclosures. */\nconst SD_JWT_PATTERN = /^eyJ[\\w-]+\\.[\\w-]*\\.[\\w-]+~/;\n\n/** Decode a base64url segment to UTF-8 text (web-standard, no Buffer). */\nfunction decodeBase64Url(seg: string): string {\n const b64 = seg.replace(/-/g, '+').replace(/_/g, '/');\n const padded = b64 + '='.repeat((4 - (b64.length % 4)) % 4);\n const binary = atob(padded);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return new TextDecoder().decode(bytes);\n}\n\n/** Decode a JWT header segment without verifying anything. */\nfunction sniffJwtHeader(compact: string): Record<string, unknown> | undefined {\n try {\n const seg = compact.split('.')[0];\n return JSON.parse(decodeBase64Url(seg)) as Record<string, unknown>;\n } catch {\n return undefined;\n }\n}\n\nfunction parseJsonBody(bodyText: string | undefined): Record<string, unknown> | undefined {\n if (!bodyText) return undefined;\n try {\n const parsed: unknown = JSON.parse(bodyText);\n return typeof parsed === 'object' && parsed !== null\n ? (parsed as Record<string, unknown>)\n : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Detection order (after the native X-Astra check, which classify owns):\n * SD-JWT/VI → RFC 9421 (Agent Pay / TAP / Web Bot Auth by kid namespace or\n * Signature-Agent) → ACP HMAC → UCP session → AP2 body triple → MPP → x402.\n * Returns undefined when nothing commerce-shaped is on the wire.\n *\n * When the platform truncated the body (`bodyTruncated`), body-bound\n * artifacts still forward what arrived but carry a `bodyTruncated`\n * evidence flag — the backend downgrades those signatures rather than\n * hard-failing.\n */\nexport function detectCommerce(req: NormalizedRequest, host: string): DetectedCommerce | undefined {\n const url = requestUrl(req, host);\n const method = req.method;\n const headers = req.headers;\n const jsonBody = parseJsonBody(req.bodyText);\n const truncated = req.bodyTruncated ? { bodyTruncated: true } : {};\n\n // --- VI / SD-JWT credential in a header ------------------------------\n const authHeader = headerValue(req, 'authorization');\n const bearer = authHeader?.replace(/^Bearer\\s+/i, '');\n const mandateHeader =\n headerValue(req, 'x-payment-mandate') ?? headerValue(req, 'payment-mandate');\n const sdJwtCandidate = [mandateHeader, bearer].find((v) => v && SD_JWT_PATTERN.test(v));\n if (sdJwtCandidate) {\n const typ = sniffJwtHeader(sdJwtCandidate)?.typ;\n return {\n protocol: 'vi-sd-jwt',\n artifacts: { viSdJwt: sdJwtCandidate },\n evidence: { typ, ...truncated },\n };\n }\n\n // --- RFC 9421 (Agent Pay / TAP / Web Bot Auth) ------------------------\n const signature = headerValue(req, 'signature');\n const signatureInput = headerValue(req, 'signature-input');\n if (signature && signatureInput) {\n const signatureAgent = headerValue(req, 'signature-agent');\n const registryHint = headerValue(req, 'x-agent-registry');\n const lowerInput = signatureInput.toLowerCase();\n const protocol = signatureAgent\n ? 'rfc9421-web-bot-auth'\n : registryHint?.toLowerCase().includes('visa') || lowerInput.includes('visa')\n ? 'rfc9421-tap'\n : registryHint?.toLowerCase().includes('mastercard') || lowerInput.includes('mastercard')\n ? 'rfc9421-agent-pay'\n : 'rfc9421';\n return {\n protocol,\n artifacts: {\n rfc9421: { headers, method, url, ...(req.bodyText && { body: req.bodyText }) },\n },\n evidence: {\n ...(signatureAgent && { signatureAgent }),\n ...(registryHint && { registryHint }),\n keyid: signatureInput.match(/keyid=\"([^\"]+)\"/)?.[1],\n ...truncated,\n },\n };\n }\n\n // --- ACP (HMAC-signed webhook/checkout: signature WITHOUT signature-input)\n const acpTimestamp = headerValue(req, 'timestamp');\n if (signature && !signatureInput && (acpTimestamp || headerValue(req, 'idempotency-key'))) {\n return {\n protocol: 'acp',\n artifacts: {\n acpRequest: {\n method,\n url,\n headers,\n ...(req.bodyText && { rawBody: req.bodyText }),\n ...(jsonBody && { body: jsonBody }),\n },\n },\n evidence: { hasTimestamp: Boolean(acpTimestamp), ...truncated },\n };\n }\n\n // --- UCP checkout session ---------------------------------------------\n if (/\\/checkout[-_]sessions(\\/|$)/.test(req.uri)) {\n return {\n protocol: 'ucp',\n artifacts: { ucpRequest: { method, url, ...(jsonBody && { body: jsonBody }) } },\n evidence: { path: req.uri, ...truncated },\n };\n }\n\n // --- AP2 mandate triple in the body -----------------------------------\n if (jsonBody) {\n const intent = jsonBody.intent_mandate ?? jsonBody.intentMandate;\n const cart = jsonBody.cart_mandate ?? jsonBody.cartMandate;\n const payment = jsonBody.payment_mandate ?? jsonBody.paymentMandate;\n if (typeof intent === 'string' || typeof cart === 'string' || typeof payment === 'string') {\n return {\n protocol: 'ap2',\n artifacts: {\n ap2Mandates: {\n ...(typeof intent === 'string' && { intent }),\n ...(typeof cart === 'string' && { cart }),\n ...(typeof payment === 'string' && { payment }),\n },\n },\n evidence: {\n mandatesPresent: [\n typeof intent === 'string' && 'intent',\n typeof cart === 'string' && 'cart',\n typeof payment === 'string' && 'payment',\n ].filter(Boolean),\n ...truncated,\n },\n };\n }\n }\n\n // --- MPP (`Authorization: Payment <credential>`) -----------------------\n if (authHeader && /^Payment\\s+/i.test(authHeader)) {\n return {\n protocol: 'mpp',\n artifacts: {\n mppRequest: {\n method,\n url,\n headers,\n ...(req.bodyText && { rawBody: req.bodyText }),\n ...(jsonBody && { body: jsonBody }),\n },\n },\n evidence: truncated,\n };\n }\n\n // --- x402 (X-PAYMENT header) ------------------------------------------\n if (headerValue(req, 'x-payment')) {\n return {\n protocol: 'x402',\n artifacts: {\n x402Request: { method, url, headers, ...(jsonBody && { body: jsonBody }) },\n },\n evidence: truncated,\n };\n }\n\n return undefined;\n}\n","/**\n * Three-tier traffic classification (verified / identified-but-unregistered\n * / anonymous) plus the two non-tiers the gateway touches as little as\n * possible: `human` (zero network calls, zero logging) and `skipped`\n * (static assets / excluded paths).\n *\n * Cheapest checks first — the human path must add microseconds, not\n * milliseconds. Platform signatures are shared with the backend so the\n * edge and verify-access's anonymous handler classify identically.\n */\n\nimport { matchEdgePathRule, type EdgeConfig } from '../edge-config';\nimport { sanitizeHeaders } from '../metadata-capture';\nimport { detectPlatformFingerprint } from '../platform-signatures';\nimport { extractCredentials } from '../verify';\nimport { detectCommerce } from './detect';\nimport { headerValue } from './request';\nimport type { Classification, EffectivePolicy, NormalizedRequest } from './types';\n\n/** Extensions the gateway never classifies — static assets. */\nconst STATIC_EXTENSIONS =\n /\\.(css|js|mjs|map|png|jpe?g|gif|webp|avif|svg|ico|woff2?|ttf|otf|eot|mp4|webm|pdf|txt|xml)$/i;\n\n/**\n * AstraSync's own SDK traffic (`sdkFetch` stamps this UA on every outbound\n * SDK request). Whenever a deployment's API URL transits a gateway-fronted\n * distribution, the SDK's beacon/verify calls re-enter the gateway — and a\n * beacon that gets beaconed is a self-sustaining invocation loop (the 4.4.0\n * staging outage). Self-traffic is therefore a first-class tier: pass\n * through with ZERO beacons, verify calls, or logging, checked BEFORE the\n * credentials step (SDK verify calls carry a Bearer key and would otherwise\n * tier `verified` and re-enter at authenticate/authorize depth).\n *\n * Spoofing: a caller forging this UA gets pass-through — the same treatment\n * anonymous bots already get in both modes (they only dodge the sampled\n * anonymous beacon), and the origin's own auth still applies. No new bypass.\n */\nconst SELF_UA_PATTERN = /^astrasync-sdk\\//i;\n\n/** Non-browser, non-platform CLI/library UA tokens → anonymous bot. */\nconst BOT_UA_PATTERN =\n /curl|wget|python-requests|python-urllib|node-fetch|axios|got|okhttp|go-http-client|libwww|httpie|java\\/|ruby|php|scrapy|headless|phantomjs|selenium|playwright|puppeteer|bot|crawler|spider|slurp/i;\n\n/** Browser-shaped UA. */\nconst BROWSER_UA_PATTERN = /mozilla\\/\\d/i;\n\n/**\n * Resolve the effective mode/depth for a path from the EdgeConfig — ordered\n * first-match-wins rules with case-insensitive globs; no match falls through\n * to the config's top-level defaults. Static extensions are always skipped\n * regardless of rules (a rule can only skip MORE, never un-skip an asset).\n */\nexport function resolvePolicy(config: EdgeConfig, path: string): EffectivePolicy {\n if (STATIC_EXTENSIONS.test(path)) {\n return { mode: config.mode, depth: config.depth, skip: true };\n }\n const rule = matchEdgePathRule(config.pathRules, path);\n if (!rule) return { mode: config.mode, depth: config.depth, skip: false };\n return {\n mode: rule.mode ?? config.mode,\n depth: rule.depth ?? config.depth,\n skip: rule.skip === true,\n };\n}\n\n/**\n * Classify one request. Order (cheapest sufficient evidence wins):\n * 0. AstraSync SDK UA → `self` (own plumbing; never beaconed — loop-proof)\n * 1. X-Astra-* credentials → `verified` candidate\n * 2. commerce-protocol credentials on the wire → `identified`\n * 3. platform UA fingerprint (Claude/ChatGPT/Gemini/…) → `identified`\n * 4. bot-shaped UA / headerless non-browser → `anonymous-bot`\n * 5. everything browser-shaped → `human`\n *\n * `depth: 'classify'` skips step 2 (no body inspection, no header sniffing\n * beyond UA) — that is the zero-friction setting.\n */\nexport function classify(\n req: NormalizedRequest,\n host: string,\n depth: 'classify' | 'authenticate' | 'authorize'\n): Classification {\n const userAgent = headerValue(req, 'user-agent') ?? '';\n\n // 0. Our own SDK's outbound calls (beacons, verify-access, config\n // fetches). MUST precede the credentials check — see SELF_UA_PATTERN.\n if (SELF_UA_PATTERN.test(userAgent)) {\n return { tier: 'self' };\n }\n\n // 1. Native AstraSync credentials.\n const credentials = extractCredentials(req.headers, {});\n if (credentials.astraId || credentials.apiKey || credentials.jwt) {\n return { tier: 'verified', protocol: 'x-astra' };\n }\n\n // The key-format prefix + platform-signal headers are stronger,\n // less-spoofable platform signals than the UA. Compute once (cheap\n // string work) and feed every fingerprint call below.\n const { apiKeyFormat, platformHeaders } = sanitizeHeaders(req.headers);\n const detectionInput = { userAgent, apiKeyFormat, platformHeaders };\n\n // 2. Commerce-protocol credentials (skipped entirely at classify depth).\n if (depth !== 'classify') {\n const commerce = detectCommerce(req, host);\n if (commerce) {\n return {\n tier: 'identified',\n protocol: commerce.protocol,\n artifacts: commerce.artifacts,\n evidence: commerce.evidence,\n fingerprint: detectPlatformFingerprint(detectionInput),\n };\n }\n }\n\n // 3. Platform-agent fingerprint (UA, key-format, or platform header).\n const fingerprint = detectPlatformFingerprint(detectionInput);\n if (fingerprint) {\n return { tier: 'identified', protocol: 'platform-ua', fingerprint };\n }\n\n // 4. Bot-shaped: CLI/library UA, no UA at all, or any non-browser UA —\n // humans arrive with Mozilla-family UAs; everything else is automation.\n if (!userAgent || BOT_UA_PATTERN.test(userAgent) || !BROWSER_UA_PATTERN.test(userAgent)) {\n return { tier: 'anonymous-bot', evidence: { userAgent: userAgent || '(none)' } };\n }\n\n // 4b. Claims to be a browser but is missing every browser fetch-metadata\n // header — headless/spoofed. `sec-fetch-mode` is sent by all evergreen\n // browsers; its absence on a Mozilla UA is a strong bot signal.\n if (!headerValue(req, 'sec-fetch-mode') && !headerValue(req, 'accept-language')) {\n return { tier: 'anonymous-bot', evidence: { userAgent, spoofedBrowser: true } };\n }\n\n // 5. Human traffic — the gateway gets out of the way.\n return { tier: 'human' };\n}\n\n/** Exported for tests. */\nexport const _patterns = { STATIC_EXTENSIONS, BOT_UA_PATTERN, BROWSER_UA_PATTERN, SELF_UA_PATTERN };\n","/**\n * Protocol-specific machine-readable messaging for enforce-mode responses.\n * Agents (not humans) consume these bodies: stable error codes, the\n * failure list, and registration guidance with real URLs.\n */\n\nimport type { TierOutcome } from './types';\n\nconst PROTOCOL_MESSAGES: Record<string, string> = {\n 'vi-sd-jwt':\n 'This request presented Visa Intelligent Commerce credentials, but the agent is not verified with AstraSync. Register the agent to pair your VI credentials with a verified identity and mandate.',\n 'rfc9421-agent-pay':\n 'This request carried a Mastercard Agent Pay signature, but the agent is not verified with AstraSync. Register the agent to pair Agent Pay credentials with a verified identity and mandate.',\n 'rfc9421-tap':\n 'This request carried a Visa TAP signature, but the agent is not verified with AstraSync. Register the agent to pair TAP credentials with a verified identity and mandate.',\n 'rfc9421-web-bot-auth':\n 'This request carried a Web Bot Auth signature, but the agent is not verified with AstraSync. Register the agent to link your signed-agent identity to a verified principal.',\n rfc9421:\n 'This request carried an RFC 9421 HTTP message signature, but the agent is not verified with AstraSync. Register the agent to link the signing identity to a verified principal.',\n acp: 'This request used the Agentic Commerce Protocol, but the agent is not verified with AstraSync. Register the agent to transact on this property.',\n ucp: 'This request used a UCP checkout session, but the agent is not verified with AstraSync. Register the agent to transact on this property.',\n ap2: 'This request presented AP2 mandates, but the agent is not verified with AstraSync. Register the agent to pair your mandates with a verified identity.',\n mpp: 'This request presented MPP payment credentials, but the agent is not verified with AstraSync. Register the agent to transact on this property.',\n x402: 'This request used x402 payment headers, but the agent is not verified with AstraSync. Register the agent to transact on this property.',\n 'platform-ua':\n 'This traffic was identified as a platform AI agent without AstraSync credentials. Register the agent to access this property with a verified identity.',\n 'x-astra':\n 'The presented AstraSync credentials failed verification or were denied by this property’s access policy.',\n};\n\nexport interface DenyBody {\n success: false;\n error: {\n code: 'UNAUTHORIZED' | 'INSUFFICIENT_ACCESS';\n message: string;\n protocol?: string;\n failures: string[];\n correlationId?: string;\n guidance: {\n message?: string;\n registrationUrl?: string;\n documentationUrl?: string;\n /** 5.1.0: MCP-connector steering — the keyless, human-approved path. */\n mcp?: { endpoint: string; discoveryUrl?: string; message: string };\n };\n };\n}\n\n/**\n * Cold-cache fallback for the MCP endpoint, gated to astrasync.ai hosts —\n * the hosted bridge only exists there; a self-hosted deployment must not\n * advertise a dead endpoint.\n */\nfunction fallbackMcpEndpoint(origin: string): string | undefined {\n try {\n const host = new URL(origin).hostname.replace(/^www\\./, '');\n if (host === 'astrasync.ai' || host.endsWith('.astrasync.ai')) return `https://mcp.${host}/mcp`;\n } catch {\n // malformed apiBaseUrl — no fallback\n }\n return undefined;\n}\n\nexport function buildDenyBody(\n outcome: TierOutcome,\n apiBaseUrl: string,\n publicBaseUrl?: string\n): DenyBody {\n // Round-11 two-plane URL doctrine: apiBaseUrl is the VERIFY plane (edge\n // deploys deliberately bake it to the direct origin so verify/beacon calls\n // don't re-enter the CDN Lambda) — but every URL in this body is read by\n // AGENTS, who must only ever see the public host. publicBaseUrl carries it;\n // unset falls back to apiBaseUrl (pre-5.2.0 behavior, correct when the API\n // base IS the public apex). Fixes staging deny bodies steering agents to\n // staging-origin.* hosts incl. the dead mcp.staging-origin fallback.\n const origin = (publicBaseUrl || apiBaseUrl).replace(/\\/api\\/?$/, '');\n const mcpEndpoint = outcome.guidance?.mcp?.endpoint || fallbackMcpEndpoint(origin);\n const protocolMessage =\n (outcome.protocol && PROTOCOL_MESSAGES[outcome.protocol]) ??\n 'This request could not be verified by AstraSync.';\n return {\n success: false,\n error: {\n // UNAUTHORIZED = identity failed (register/re-authenticate helps);\n // INSUFFICIENT_ACCESS = identity fine, policy denied (fix the mandate).\n code: outcome.tier === 'verified' ? 'INSUFFICIENT_ACCESS' : 'UNAUTHORIZED',\n message: protocolMessage,\n ...(outcome.protocol && { protocol: outcome.protocol }),\n failures: outcome.reasons,\n ...(outcome.correlationId && { correlationId: outcome.correlationId }),\n guidance: {\n // `||` not `??`: verify() fills these with EMPTY STRINGS when the\n // well-known cache is cold — empty means \"use the fallback\".\n message:\n outcome.guidance?.message ||\n 'Register this agent with AstraSync to receive verifiable credentials.',\n registrationUrl: outcome.guidance?.registrationUrl || `${origin}/register`,\n documentationUrl: outcome.guidance?.documentationUrl || `${origin}/docs/edge-adapter`,\n ...(mcpEndpoint && {\n mcp: {\n endpoint: mcpEndpoint,\n discoveryUrl:\n outcome.guidance?.mcp?.discoveryUrl ||\n `${mcpEndpoint.replace(/\\/mcp$/, '')}/.well-known/mcp.json`,\n message:\n outcome.guidance?.mcp?.message ||\n 'Inside an MCP host? Add the AstraSync MCP connector at this endpoint instead of the ' +\n 'registration URL — registration through the connector is keyless and human-approved ' +\n '(your human approves in an in-chat card; you never handle credentials).',\n },\n }),\n },\n },\n };\n}\n\nexport interface UnavailableBody {\n success: false;\n error: {\n code: 'VERIFICATION_UNAVAILABLE';\n message: string;\n failures: string[];\n correlationId?: string;\n guidance: { message: string };\n };\n}\n\n/**\n * Enforce-mode 503 for verification-infrastructure failure. Deliberately a\n * different code and status from the 403 deny: a 403 tells the agent to\n * register or fix its mandate (retrying won't help); this tells it the\n * OPPOSITE — identity and policy were never evaluated, retry with backoff.\n */\nexport function buildUnavailableBody(outcome: TierOutcome): UnavailableBody {\n return {\n success: false,\n error: {\n code: 'VERIFICATION_UNAVAILABLE',\n message:\n 'Agent verification is temporarily unavailable and this path enforces verification. ' +\n 'Your identity was not evaluated and no denial was recorded — retry with exponential backoff.',\n failures: outcome.reasons,\n ...(outcome.correlationId && { correlationId: outcome.correlationId }),\n guidance: {\n message: 'Retry the request with exponential backoff; the condition is transient.',\n },\n },\n };\n}\n\nexport interface ManualReviewBody {\n success: false;\n status: 'manual_review';\n message: string;\n stepUpApproval?: { pollUrl?: string; expiresAt?: string };\n correlationId?: string;\n}\n\nexport function buildManualReviewBody(outcome: TierOutcome): ManualReviewBody {\n return {\n success: false,\n status: 'manual_review',\n message:\n 'This action requires human approval. Poll the step-up approval endpoint and retry once approved.',\n ...(outcome.stepUp && { stepUpApproval: outcome.stepUp }),\n ...(outcome.correlationId && { correlationId: outcome.correlationId }),\n };\n}\n","/**\n * X-Astra-Verified-Hop — cross-hop verify-access dedupe marker.\n *\n * Header carrying upstream verify-access proof so an inner-hop endpoint can\n * dedupe (skip verify-access when the same ASTRA-id was already verified a\n * few ms earlier). Emitted by the MCP adapter toward tool fetches and by the\n * edge gateway toward the origin at authenticate/authorize depth. Value\n * format:\n *\n * {astraId};{sessionId};{checkedAt-ms}\n *\n * Receivers MUST validate that `checkedAt` is recent (≤ 60s window\n * recommended) and that `astraId` matches the agent identity claimed on the\n * inner hop. The header alone is NOT proof-of-identity — it's an UNSIGNED\n * dedupe advisory: trust it (`trustVerifiedHop`) only where every network\n * path to the inner hop crosses a stripping gateway or an equivalent trusted\n * boundary, exactly like the unsigned X-AstraSync-* attestation headers.\n * Pair with the existing X-Astra-Id auth.\n */\n\nexport const MCP_VERIFIED_HOP_HEADER = 'X-Astra-Verified-Hop';\n\n/** Default acceptable age (ms) for an X-Astra-Verified-Hop header. */\nexport const MCP_VERIFIED_HOP_MAX_AGE_MS = 60_000;\n\nexport interface VerifiedHopMarker {\n astraId: string;\n sessionId?: string;\n checkedAt: number; // epoch ms\n}\n\nexport function serializeVerifiedHop(marker: VerifiedHopMarker): string {\n return `${marker.astraId};${marker.sessionId ?? ''};${marker.checkedAt}`;\n}\n\nexport function parseVerifiedHop(value: string | undefined | null): VerifiedHopMarker | null {\n if (!value) return null;\n const parts = value.split(';');\n if (parts.length !== 3) return null;\n const [astraId, sessionId, checkedAtRaw] = parts;\n if (!astraId) return null;\n const checkedAt = Number(checkedAtRaw);\n if (!Number.isFinite(checkedAt) || checkedAt <= 0) return null;\n return {\n astraId,\n ...(sessionId ? { sessionId } : {}),\n checkedAt,\n };\n}\n\n/**\n * Returns true when `marker.astraId` matches the inner-hop's claimed\n * ASTRA-id AND the marker is recent enough. Inner-hop middleware uses this\n * to skip a duplicate verify-access call.\n */\nexport function isVerifiedHopValidFor(\n marker: VerifiedHopMarker | null,\n expectedAstraId: string,\n opts: { maxAgeMs?: number; now?: number } = {}\n): boolean {\n if (!marker) return false;\n if (marker.astraId !== expectedAstraId) return false;\n const maxAge = opts.maxAgeMs ?? MCP_VERIFIED_HOP_MAX_AGE_MS;\n const now = opts.now ?? Date.now();\n return now - marker.checkedAt <= maxAge && now >= marker.checkedAt;\n}\n","/**\n * Decision → abstract outcome-application wiring. Executed in BOTH modes\n * so observe mode records exactly what enforce mode would have done — but\n * only enforce mode is allowed to emit anything other than a pass.\n */\n\nimport { buildDenyBody, buildManualReviewBody, buildUnavailableBody } from './messaging';\nimport { MCP_VERIFIED_HOP_HEADER, serializeVerifiedHop } from '../verified-hop';\nimport type { EffectivePolicy, OutcomeApplication, TierOutcome } from './types';\n\n/** Trust-attestation headers injected on allowed requests. */\nexport const ASAT_HEADERS = {\n trustScore: 'X-AstraSync-Trust-Score',\n agentId: 'X-AstraSync-Agent-Id',\n developerId: 'X-AstraSync-Developer-Id',\n observedDecision: 'X-AstraSync-Observed-Decision',\n} as const;\n\n/**\n * Inbound header names an evaluated pass must strip: the gateway's own\n * attestation surface plus the verify-dedupe marker — both are only ever\n * allowed to originate AT the gateway, never from the viewer.\n */\nconst STRIP_HEADER_PREFIXES = ['x-astrasync-', 'x-astra-verified-hop'];\n\n/**\n * A pass that leaves the request completely untouched — used for skipped\n * paths and human traffic, which the gateway must not modify at all.\n */\nexport function passUntouched(): OutcomeApplication {\n return { action: 'pass', injectHeaders: {}, stripHeaderPrefixes: [] };\n}\n\n/**\n * Turn a tier outcome into the abstract application the platform executes.\n * Every evaluated pass strips inbound spoofed `x-astrasync-*` headers\n * (both modes — trust headers must only ever originate at the gateway).\n *\n * Observe mode: always a pass — header hygiene plus an\n * `X-AstraSync-Observed-Decision` stamp for origin-side log correlation.\n *\n * Enforce mode: ALLOW → pass with trust-attestation headers; DENY → 403\n * machine-readable body; MANUAL_REVIEW → 202 with step-up poll info.\n */\nexport function applyOutcome(\n options: { apiBaseUrl: string; publicBaseUrl?: string },\n outcome: TierOutcome,\n policy: EffectivePolicy\n): OutcomeApplication {\n const injectHeaders: Record<string, string> = {};\n\n // Surface a rejected property key in origin logs in BOTH modes — the\n // outcome is allow (fail-open) so the deny stamp below never fires.\n if (outcome.misconfig) {\n injectHeaders[ASAT_HEADERS.observedDecision] = 'misconfig';\n }\n\n if (policy.mode !== 'enforce') {\n // Shadow stamp: what enforce WOULD have done, visible in origin logs.\n if (outcome.decision !== 'allow') {\n injectHeaders[ASAT_HEADERS.observedDecision] = outcome.decision;\n }\n Object.assign(injectHeaders, asatHeaders(outcome), verifiedHopHeader(outcome));\n return { action: 'pass', injectHeaders, stripHeaderPrefixes: STRIP_HEADER_PREFIXES };\n }\n\n switch (outcome.decision) {\n case 'deny':\n // Fail posture follows success posture (4.5.0): an infra-failure deny\n // is a 503 retry-later, never a 403 register-first — the agent's\n // identity was never evaluated.\n if (outcome.unavailable) {\n return {\n action: 'respond',\n status: 503,\n headers: { 'Retry-After': '30' },\n bodyJson: buildUnavailableBody(outcome),\n };\n }\n return {\n action: 'respond',\n status: 403,\n headers: {},\n bodyJson: buildDenyBody(outcome, options.apiBaseUrl, options.publicBaseUrl),\n };\n case 'manual_review':\n return {\n action: 'respond',\n status: 202,\n headers: { 'Retry-After': '30' },\n bodyJson: buildManualReviewBody(outcome),\n };\n default:\n Object.assign(injectHeaders, asatHeaders(outcome), verifiedHopHeader(outcome));\n return { action: 'pass', injectHeaders, stripHeaderPrefixes: STRIP_HEADER_PREFIXES };\n }\n}\n\nfunction asatHeaders(outcome: TierOutcome): Record<string, string> {\n if (!outcome.asat) return {};\n const { trustScore, agentId, developerId } = outcome.asat;\n return {\n ...(trustScore !== undefined && { [ASAT_HEADERS.trustScore]: String(trustScore) }),\n ...(agentId && { [ASAT_HEADERS.agentId]: agentId }),\n ...(developerId && { [ASAT_HEADERS.developerId]: developerId }),\n };\n}\n\n/**\n * Verify-dedupe marker toward the origin. asat is only populated when a\n * verify-access call succeeded (authenticate/authorize depth), so gating on\n * it is the depth gate — classify-depth traffic never carries a marker. An\n * SDK-middleware origin with `trustVerifiedHop` enabled can then skip its\n * duplicate verify-access for the same agent within the freshness window.\n */\nfunction verifiedHopHeader(outcome: TierOutcome): Record<string, string> {\n const agentId = outcome.asat?.agentId;\n if (!agentId) return {};\n return {\n [MCP_VERIFIED_HOP_HEADER]: serializeVerifiedHop({\n astraId: agentId,\n ...(outcome.sessionId && { sessionId: outcome.sessionId }),\n checkedAt: Date.now(),\n }),\n };\n}\n","/**\n * Shared purpose/action resolver for the HTTP adapters (express + nextjs) —\n * the vocabulary-unification layer.\n *\n * The PDLSS two-axis contract: `purpose` = bare category noun (`shopping`,\n * `data`, custom nouns like `trading`); `action` = dotted verb\n * (`shopping.search`) or an enumerated transport token. Transport verbs\n * (GET/POST/...) NEVER travel as PDLSS actions — they map through the pinned\n * method table below.\n *\n * SELF-CONTAINED on purpose: this published package cannot depend on the\n * private @astrasyncai/pdlss-vocab workspace package, so the constants are\n * duplicated here and pinned strictly equal by a monorepo CI test\n * (vocab-equality.test.ts). Change them in BOTH places or that test fails.\n */\n\n/** Pinned method→action derivation table. */\nexport const HTTP_METHOD_ACTION_TABLE: Readonly<Record<string, string>> = {\n GET: 'data.read',\n HEAD: 'data.read',\n OPTIONS: 'data.read',\n POST: 'data.write',\n PUT: 'data.write',\n PATCH: 'data.write',\n DELETE: 'data.delete',\n};\n\n/** Unknown methods are treated as mutating until proven otherwise. */\nexport const DEFAULT_HTTP_ACTION = 'data.write';\n\n/** Generic category emitted when nothing supplies a domain purpose. */\nexport const DEFAULT_HTTP_PURPOSE = 'data';\n\nexport function actionForHttpMethod(method: string): string {\n return HTTP_METHOD_ACTION_TABLE[method.toUpperCase()] ?? DEFAULT_HTTP_ACTION;\n}\n\nexport type HttpPurposeSource =\n | 'route_config'\n | 'custom_extractor'\n | 'header'\n | 'legacy_header'\n | 'query'\n | 'action_derived'\n | 'transport_default';\n\nexport type HttpActionSource =\n | 'route_config'\n | 'custom_extractor'\n | 'header'\n | 'purpose_header_derived'\n | 'method_table';\n\nexport interface HttpPdlssInput {\n method: string;\n /** `X-Astra-Purpose` header value (agent's declaration). */\n astraPurpose?: string;\n /** `X-Astra-Action` header value (agent's declaration, symmetric with MCP). */\n astraAction?: string;\n /** Legacy `x-purpose` header — deprecated, removal scheduled for 4.0.0. */\n legacyPurpose?: string;\n /** Legacy `?purpose` query param (express only) — deprecated, removal 4.0.0. */\n queryPurpose?: string;\n /** Dashboard route config send-mapping (RouteAccessConfig.purpose/.action). */\n routePurpose?: string;\n routeAction?: string;\n /** Results of the merchant's extractPurpose/extractAction options. */\n customPurpose?: string;\n hasCustomPurposeExtractor?: boolean;\n customAction?: string;\n hasCustomActionExtractor?: boolean;\n}\n\nexport interface HttpPdlssResolution {\n purpose: string;\n action: string;\n purposeSource: HttpPurposeSource;\n actionSource: HttpActionSource;\n}\n\n/**\n * Normalize an `X-Astra-Purpose` header value.\n * - colon form `\"category:action\"` (legacy wire shape): take the prefix; the\n * remainder is free-text and exists in no vocabulary — discard it and let\n * the method table supply the action (matches pre-3.1.0 discard behavior).\n * - dotted form `\"shopping.purchase\"` (the shape older docs taught): prefix\n * becomes the purpose, the WHOLE token becomes an action candidate.\n * - bare token: purpose verbatim.\n */\nexport function normalizePurposeHeader(value: string): {\n purpose: string;\n actionCandidate?: string;\n} {\n const colon = value.indexOf(':');\n if (colon >= 0) {\n return { purpose: value.slice(0, colon) };\n }\n const dot = value.indexOf('.');\n if (dot > 0 && dot < value.length - 1) {\n return { purpose: value.slice(0, dot), actionCandidate: value };\n }\n return { purpose: value };\n}\n\n/**\n * Resolve the {purpose, action} pair for one HTTP request.\n *\n * Precedence (both axes):\n * action: route mapping → extractAction option → X-Astra-Action header →\n * candidate from a dotted X-Astra-Purpose → pinned method table\n * purpose: route mapping → extractPurpose option → X-Astra-Purpose →\n * legacy x-purpose / ?purpose → category prefix of the resolved\n * action → 'data'\n *\n * A configured custom extractor masks the header/legacy/query steps of its\n * axis (it replaces the default chain, as extractPurpose always has); when it\n * returns undefined the axis falls through to the table/prefix fallback.\n * The route mapping is merchant policy fetched from the dashboard — it\n * outranks agent-supplied headers the way MCP toolGates do.\n */\nexport function resolveHttpPdlss(input: HttpPdlssInput): HttpPdlssResolution {\n const fromHeader = input.astraPurpose ? normalizePurposeHeader(input.astraPurpose) : undefined;\n\n // ── Action axis ──\n let action: string;\n let actionSource: HttpActionSource;\n if (input.routeAction) {\n action = input.routeAction;\n actionSource = 'route_config';\n } else if (input.hasCustomActionExtractor && input.customAction) {\n action = input.customAction;\n actionSource = 'custom_extractor';\n } else if (!input.hasCustomActionExtractor && input.astraAction) {\n action = input.astraAction;\n actionSource = 'header';\n } else if (!input.hasCustomActionExtractor && fromHeader?.actionCandidate) {\n action = fromHeader.actionCandidate;\n actionSource = 'purpose_header_derived';\n } else {\n action = actionForHttpMethod(input.method);\n actionSource = 'method_table';\n }\n\n // ── Purpose axis ──\n let purpose: string | undefined;\n let purposeSource: HttpPurposeSource | undefined;\n if (input.routePurpose) {\n purpose = input.routePurpose;\n purposeSource = 'route_config';\n } else if (input.hasCustomPurposeExtractor) {\n if (input.customPurpose) {\n purpose = input.customPurpose;\n purposeSource = 'custom_extractor';\n }\n } else if (fromHeader) {\n purpose = fromHeader.purpose;\n purposeSource = 'header';\n } else if (input.legacyPurpose) {\n purpose = input.legacyPurpose;\n purposeSource = 'legacy_header';\n } else if (input.queryPurpose) {\n purpose = input.queryPurpose;\n purposeSource = 'query';\n }\n\n if (!purpose) {\n // Keep the pair coherent: an agent that sent only X-Astra-Action (or a\n // route that mapped only the action) gets that action's own category.\n const dot = action.indexOf('.');\n if (dot > 0) {\n purpose = action.slice(0, dot);\n purposeSource = 'action_derived';\n } else {\n purpose = DEFAULT_HTTP_PURPOSE;\n purposeSource = 'transport_default';\n }\n }\n\n return { purpose, action, purposeSource: purposeSource!, actionSource };\n}\n","/**\n * Time-budgeted event emission.\n *\n * Some edge runtimes (Lambda@Edge) have no background-work scheduler —\n * anything not awaited before the handler returns may never run. So every\n * telemetry call is awaited under an explicit budget and DROPPED on\n * timeout: latency to the customer's traffic is bounded, and a slow\n * AstraSync API costs telemetry, never page loads. Runtimes that provide\n * `waitUntil` (Cloudflare Workers, Vercel Edge, Fastly Compute) can pass\n * it via {@link EdgeCoreOptions.waitUntil} to take beacons off the latency\n * path entirely.\n */\n\nimport { reportUnregisteredAttempt } from '../verify';\nimport { buildObservedMetadata, headerValue } from './request';\nimport type { Classification, EdgeCoreOptions, NormalizedRequest } from './types';\n\n/** Await `promise` for at most `ms`; resolve `undefined` on timeout/error. */\nexport async function withBudget<T>(promise: Promise<T>, ms: number): Promise<T | undefined> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<undefined>((resolve) => {\n timer = setTimeout(() => resolve(undefined), ms);\n }),\n ]);\n } catch {\n return undefined;\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\n/**\n * Emit an unregistered-attempt beacon for `identified` (non-crypto depths)\n * and sampled `anonymous-bot` traffic. Unauthenticated by design; the\n * backend fingerprints the UA and find-or-provisions platform agents\n * server-side.\n */\nexport async function emitBeacon(\n options: EdgeCoreOptions,\n req: NormalizedRequest,\n classification: Classification,\n budgetMs: number\n): Promise<void> {\n const budgeted = withBudget(\n reportUnregisteredAttempt(\n { apiBaseUrl: options.apiBaseUrl, counterpartyId: options.counterpartyId },\n {\n counterpartyUrl: options.counterpartyUrl,\n counterpartyType: 'website',\n sourceIp: req.clientIp,\n userAgent: headerValue(req, 'user-agent'),\n requestPath: req.uri,\n requestMethod: req.method,\n // Evidence fields the backend persists into the event record.\n protocol: classification.protocol,\n evidence: classification.evidence,\n // The full sanitized header + connection capture for the\n // unregistered caller (fire-and-forget, so free).\n observedMetadata: buildObservedMetadata(req),\n }\n ),\n budgetMs\n );\n if (options.waitUntil) {\n options.waitUntil(budgeted);\n return;\n }\n await budgeted;\n}\n\n/** Deterministic-in-tests sampling gate. */\nexport function sampled(rate: number, random: () => number = Math.random): boolean {\n if (rate <= 0) return false;\n if (rate >= 1) return true;\n return random() < rate;\n}\n","/**\n * Depth-controlled verification per tier. The edge never verifies\n * credentials itself — it forwards what it detected to verify-access, the\n * canonical sole verification sink (the backend runs the commerce\n * pipeline, records events, provisions unregistered platform agents,\n * persists sessions). What the depth setting controls is how much the edge\n * LOOKS and how much it FORWARDS:\n *\n * classify — what is it? UA tiers only. Zero verify-access calls;\n * beacons only.\n * authenticate — who is it? + protocol detection. X-Astra agents get a\n * verify-access identity check; commerce/platform traffic\n * is beaconed with protocol + evidence (no signature\n * verification anywhere).\n * authorize — are they allowed? + artifact forwarding. X-Astra verify\n * calls carry commerceArtifacts; identified traffic gets an\n * anonymous verify-access call with artifacts +\n * callerMetadata so the backend cryptographically proves\n * and policy-evaluates once.\n */\n\nimport { resolveHttpPdlss } from '../adapters/http-pdlss';\nimport type { GatewayConfig, VerificationRequest } from '../types';\nimport { verify, extractCredentials } from '../verify';\nimport { withBudget, emitBeacon, sampled } from './events';\nimport { buildObservedMetadata, headerValue } from './request';\nimport type {\n Classification,\n EdgeCoreOptions,\n EffectivePolicy,\n NormalizedRequest,\n TierOutcome,\n} from './types';\n\nfunction baseOutcome(classification: Classification): TierOutcome {\n return {\n tier: classification.tier,\n decision: 'allow',\n reasons: [],\n protocol: classification.protocol,\n };\n}\n\nexport function buildVerificationRequest(\n options: EdgeCoreOptions,\n req: NormalizedRequest,\n classification: Classification,\n includeArtifacts: boolean\n): VerificationRequest {\n // verify-access REQUIRES a purpose. Resolve via the shared chain: the\n // agent's X-Astra-Purpose/-Action declarations, else the pinned method\n // table (GET → data/data.read etc.) — a transport verb never travels as\n // a permission action.\n const pdlss = resolveHttpPdlss({\n method: req.method,\n astraPurpose: headerValue(req, 'x-astra-purpose'),\n astraAction: headerValue(req, 'x-astra-action'),\n });\n // Forward the caller's attempt-chain handle when well-formed\n // (agent-declared, like x-astra-purpose — not a trust header, so no\n // spoof-strip needed). The edge synthesises NO consideration data — it\n // can't see offer semantics; pure pass-through.\n const attemptId = headerValue(req, 'x-astra-attempt-id');\n return {\n ...(attemptId && /^att_[0-9a-f]{32}$/.test(attemptId) && { attemptId }),\n credentials: extractCredentials(req.headers, {}),\n purpose: pdlss.purpose,\n action: pdlss.action,\n resource: req.uri,\n createSession: true,\n counterpartyType: 'website',\n counterpartyUrl: options.counterpartyUrl,\n callerMetadata: {\n sourceIp: req.clientIp,\n userAgent: headerValue(req, 'user-agent'),\n referer: headerValue(req, 'referer'),\n host: headerValue(req, 'host'),\n // The full sanitized header + connection capture. The backend stores\n // it fire-and-forget (zero decision latency) and uses the key-format\n // / platform headers for attribution.\n observedMetadata: buildObservedMetadata(req),\n },\n ...(includeArtifacts &&\n classification.artifacts && { commerceArtifacts: classification.artifacts }),\n };\n}\n\nexport function outcomeFromVerifyResult(\n classification: Classification,\n result: Awaited<ReturnType<typeof verify>>\n): TierOutcome {\n const outcome = baseOutcome(classification);\n outcome.sessionId = (result as { sessionId?: string }).sessionId;\n outcome.correlationId = result.correlationId;\n outcome.guidance = result.guidance;\n\n // The PROPERTY'S own API key was rejected by the backend — neither an\n // agent deny nor an infra failure. Fail OPEN in both modes: agents must\n // not be blocked by the property's dead key. The misconfig flag stamps\n // X-AstraSync-Observed-Decision so origin logs surface it; the owner is\n // alerted server-side on every rejected call.\n if (result.misconfigured) {\n outcome.reasons = ['verification key misconfigured — fail-open (merchant_misconfig)'];\n outcome.misconfig = true;\n return outcome;\n }\n\n if (result.requiresStepUp || result.stepUpApproval) {\n outcome.decision = 'manual_review';\n outcome.reasons = ['step-up approval required'];\n outcome.stepUp = {\n pollUrl: (result.stepUpApproval as { pollUrl?: string } | undefined)?.pollUrl,\n expiresAt: (result.stepUpApproval as { expiresAt?: string } | undefined)?.expiresAt,\n };\n return outcome;\n }\n\n if (!result.identityVerified || !result.policyAllowed) {\n outcome.decision = 'deny';\n outcome.reasons = result.denialReasons?.length\n ? result.denialReasons\n : [!result.identityVerified ? 'identity not verified' : 'denied by access policy'];\n return outcome;\n }\n\n outcome.asat = {\n trustScore: result.agent?.trustScore,\n agentId: result.agent?.astraId,\n developerId: result.developer?.astradId,\n };\n return outcome;\n}\n\n/**\n * Fail posture follows success posture (4.5.0): when verification\n * infrastructure is unreachable, observe mode passes through with the\n * reason recorded, while enforce mode denies with `unavailable: true`\n * (rendered as a 503 retry-later, never a 403 register-first — the backend\n * never evaluated the caller, so no denial semantics may be claimed).\n */\nfunction unavailableOutcome(\n classification: Classification,\n policy: EffectivePolicy,\n reason: string,\n correlationId?: string\n): TierOutcome {\n const outcome = baseOutcome(classification);\n outcome.unavailable = true;\n outcome.reasons = [reason];\n if (correlationId) outcome.correlationId = correlationId;\n if (policy.mode === 'enforce') outcome.decision = 'deny';\n return outcome;\n}\n\n/**\n * A verify() result whose failure is the SDK's typed api_error fallback —\n * infra unavailability that verify() shaped as a deny-like result. Must not\n * match merchant_misconfigured (deterministic, handled fail-open).\n */\nfunction isApiErrorResult(result: Awaited<ReturnType<typeof verify>>): boolean {\n return (\n (result.failures ?? []).some((f) => f.dimension === 'verify_access.api_error') === true &&\n !result.misconfigured\n );\n}\n/**\n * Run the tier-appropriate verification/telemetry for one classified\n * request. NEVER throws. Infra-failure handling is posture-symmetric (see\n * `unavailableOutcome`); a presented credential the BACKEND rejected\n * remains a real deny in both modes, and the property's own rejected key\n * (misconfig) remains fail-open in both modes. Internal pipeline\n * exceptions (the catch below) stay fail-open unconditionally — they are\n * gateway bugs, not verification availability, and must never take a site\n * down.\n */\nexport async function runTier(\n options: EdgeCoreOptions,\n req: NormalizedRequest,\n classification: Classification,\n policy: EffectivePolicy,\n apiKey: string | undefined,\n sampling: { anonymousBeaconRate: number }\n): Promise<TierOutcome> {\n const budgets = options.budgets ?? {};\n const beaconMs = budgets.beaconMs ?? 300;\n const verifyMs =\n policy.mode === 'enforce'\n ? (budgets.verifyEnforceMs ?? 3000)\n : (budgets.verifyObserveMs ?? 1500);\n\n const gatewayConfig: GatewayConfig = {\n apiBaseUrl: options.apiBaseUrl,\n ...(apiKey && { apiKey }),\n counterpartyId: options.counterpartyId,\n // The gateway handles its own error semantics; init self-probes don't\n // belong in a per-request edge function.\n disableInitChecks: true,\n } as GatewayConfig;\n\n try {\n switch (classification.tier) {\n case 'verified': {\n // classify depth = zero API calls, even for credentialed agents.\n if (policy.depth === 'classify') {\n return baseOutcome(classification);\n }\n const result = await withBudget(\n verify(\n gatewayConfig,\n buildVerificationRequest(options, req, classification, policy.depth === 'authorize')\n ),\n verifyMs\n );\n if (!result) {\n return unavailableOutcome(\n classification,\n policy,\n 'verify-access unreachable within budget'\n );\n }\n if (isApiErrorResult(result)) {\n return unavailableOutcome(\n classification,\n policy,\n result.denialReasons?.[0] ?? 'verify-access api error',\n result.correlationId\n );\n }\n return outcomeFromVerifyResult(classification, result);\n }\n\n case 'identified': {\n if (policy.depth === 'authorize' && classification.artifacts) {\n // Anonymous verify-access call WITH artifacts: the backend runs\n // the commerce pipeline, records unverified events, and\n // provisions unregistered platform agents — one sink, recorded\n // once.\n const result = await withBudget(\n verify(gatewayConfig, buildVerificationRequest(options, req, classification, true)),\n verifyMs\n );\n if (!result) {\n return unavailableOutcome(\n classification,\n policy,\n 'verify-access unreachable within budget'\n );\n }\n if (isApiErrorResult(result)) {\n return unavailableOutcome(\n classification,\n policy,\n result.denialReasons?.[0] ?? 'verify-access api error',\n result.correlationId\n );\n }\n return outcomeFromVerifyResult(classification, result);\n }\n // classify/credentials depth (or no artifacts): lightweight beacon.\n await emitBeacon(options, req, classification, beaconMs);\n const outcome = baseOutcome(classification);\n if (policy.mode === 'enforce' && policy.depth !== 'classify') {\n // Unregistered agent on an enforced path: deny with guidance.\n outcome.decision = 'deny';\n outcome.reasons = ['agent is not registered with AstraSync'];\n }\n return outcome;\n }\n\n case 'anonymous-bot': {\n if (sampled(sampling.anonymousBeaconRate, options.random)) {\n await emitBeacon(\n options,\n req,\n { ...classification, protocol: classification.protocol ?? 'ua-heuristic' },\n beaconMs\n );\n }\n // Anonymous bots pass through even in enforce mode — enforce gates\n // AGENT traffic; generic bot management stays the CDN/WAF's job.\n return baseOutcome(classification);\n }\n\n default:\n return baseOutcome(classification);\n }\n } catch (err) {\n const outcome = baseOutcome(classification);\n outcome.reasons = [\n `edge pipeline error — fail-open: ${err instanceof Error ? err.message : String(err)}`,\n ];\n return outcome;\n }\n}\n","/**\n * The platform-neutral evaluation pipeline for one request:\n *\n * path policy → classify → tier pipeline → outcome application\n *\n * Platform adapters own everything around this: config/secret loading,\n * request normalization, and applying the returned application onto their\n * native request/response shapes. `evaluateEdgeRequest` NEVER throws — any\n * internal failure resolves to an untouched pass (the gateway must never\n * take the site down).\n */\n\nimport type { EdgeConfig } from '../edge-config';\nimport { classify, resolvePolicy } from './classify';\nimport { applyOutcome, passUntouched } from './enforce';\nimport { runTier } from './pipeline';\nimport { headerValue } from './request';\nimport type {\n Classification,\n EdgeCoreOptions,\n EffectivePolicy,\n NormalizedRequest,\n OutcomeApplication,\n TierOutcome,\n} from './types';\n\nexport interface EdgeEvaluation {\n application: OutcomeApplication;\n policy: EffectivePolicy;\n /** Absent when the path was skipped before classification. */\n classification?: Classification;\n /** Absent for skipped paths and human/self traffic (no pipeline run). */\n outcome?: TierOutcome;\n}\n\n/**\n * Evaluate one normalized request against the effective EdgeConfig.\n *\n * - Skipped paths (static assets / skip rules): untouched, zero work.\n * - Humans and self (AstraSync SDK) traffic: get out of the way. No calls,\n * no logs, no header changes.\n * - Everything else runs the tier pipeline and yields an application the\n * platform must execute (pass with header hygiene, or an enforce-mode\n * response).\n */\nexport async function evaluateEdgeRequest(\n options: EdgeCoreOptions,\n req: NormalizedRequest,\n config: EdgeConfig,\n apiKey: string | undefined\n): Promise<EdgeEvaluation> {\n const policy = resolvePolicy(config, req.uri);\n try {\n if (policy.skip) return { policy, application: passUntouched() };\n\n const host =\n headerValue(req, 'x-forwarded-host') ??\n headerValue(req, 'host') ??\n new URL(options.counterpartyUrl).host;\n\n const classification = classify(req, host, policy.depth);\n\n // Human and self (own-SDK) traffic: get out of the way. No calls, no\n // logs, no header changes. Self MUST short-circuit here — running it\n // through the tier pipeline would let a beacon spawn a beacon.\n if (classification.tier === 'human' || classification.tier === 'self') {\n return { policy, classification, application: passUntouched() };\n }\n\n const outcome = await runTier(options, req, classification, policy, apiKey, config.sampling);\n\n if (outcome.decision !== 'allow') {\n options.log?.(\n 'info',\n policy.mode === 'enforce'\n ? `${outcome.decision.toUpperCase()}: ${req.method} ${req.uri}`\n : `[OBSERVE] would have been ${outcome.decision.toUpperCase()}: ${req.method} ${req.uri}`,\n { tier: outcome.tier, protocol: outcome.protocol, reasons: outcome.reasons }\n );\n }\n\n return {\n policy,\n classification,\n outcome,\n application: applyOutcome(options, outcome, policy),\n };\n } catch (err) {\n // Fail-open, unconditionally.\n options.log?.('error', 'edge evaluation error — passing request through', {\n error: err instanceof Error ? err.message : String(err),\n });\n return { policy, application: passUntouched() };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACkBO,IAAM,cAAc;;;ACDpB,IAAM,iBAAiB,iBAAiB,WAAW;AAO1D,SAAS,cAAc,aAAmD;AACxE,MAAI,CAAC,YAAa,QAAO,EAAE,cAAc,eAAe;AACxD,MAAI,uBAAuB,SAAS;AAClC,UAAM,OAAO,IAAI,QAAQ,WAAW;AACpC,QAAI,CAAC,KAAK,IAAI,YAAY,EAAG,MAAK,IAAI,cAAc,cAAc;AAClE,WAAO;AAAA,EACT;AACA,MAAI,MAAM,QAAQ,WAAW,GAAG;AAC9B,UAAMA,OAAM,YAAY,KAAK,CAAC,CAAC,IAAI,MAAM,KAAK,YAAY,MAAM,YAAY;AAC5E,WAAOA,OAAM,cAAc,CAAC,GAAG,aAAa,CAAC,cAAc,cAAc,CAAC;AAAA,EAC5E;AACA,QAAM,MAAM,OAAO,KAAK,WAAW,EAAE,KAAK,CAAC,SAAS,KAAK,YAAY,MAAM,YAAY;AACvF,SAAO,MAAM,cAAc,EAAE,cAAc,gBAAgB,GAAG,YAAY;AAC5E;AAEO,IAAM,WAAyB,CAAC,OAAO,SAC5C,MAAM,OAAO,EAAE,GAAG,MAAM,SA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