@astrasyncai/verification-gateway 5.13.0 → 5.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/dist/adapters/express.js +28 -10
  2. package/dist/adapters/express.js.map +1 -1
  3. package/dist/adapters/express.mjs +28 -10
  4. package/dist/adapters/express.mjs.map +1 -1
  5. package/dist/adapters/mcp.js +1 -1
  6. package/dist/adapters/mcp.js.map +1 -1
  7. package/dist/adapters/mcp.mjs +1 -1
  8. package/dist/adapters/mcp.mjs.map +1 -1
  9. package/dist/adapters/nextjs.js +28 -10
  10. package/dist/adapters/nextjs.js.map +1 -1
  11. package/dist/adapters/nextjs.mjs +28 -10
  12. package/dist/adapters/nextjs.mjs.map +1 -1
  13. package/dist/adapters/sdk.js +1 -1
  14. package/dist/adapters/sdk.js.map +1 -1
  15. package/dist/adapters/sdk.mjs +1 -1
  16. package/dist/adapters/sdk.mjs.map +1 -1
  17. package/dist/agent/index.js +1 -1
  18. package/dist/agent/index.js.map +1 -1
  19. package/dist/agent/index.mjs +1 -1
  20. package/dist/agent/index.mjs.map +1 -1
  21. package/dist/bin/astrasync-claude-hook.js +28 -10
  22. package/dist/bin/astrasync-codex-hook.js +28 -10
  23. package/dist/bin/astrasync-guard.js +28 -10
  24. package/dist/bin/astrasync.js +29 -11
  25. package/dist/browser/background.js +28 -10
  26. package/dist/browser/background.js.map +1 -1
  27. package/dist/browser/background.mjs +28 -10
  28. package/dist/browser/background.mjs.map +1 -1
  29. package/dist/cli/index.js +1 -1
  30. package/dist/cli/index.js.map +1 -1
  31. package/dist/cli/index.mjs +1 -1
  32. package/dist/cli/index.mjs.map +1 -1
  33. package/dist/codex/index.js +28 -10
  34. package/dist/codex/index.js.map +1 -1
  35. package/dist/codex/index.mjs +28 -10
  36. package/dist/codex/index.mjs.map +1 -1
  37. package/dist/cursor/extension.js +28 -10
  38. package/dist/cursor/extension.js.map +1 -1
  39. package/dist/cursor/extension.mjs +28 -10
  40. package/dist/cursor/extension.mjs.map +1 -1
  41. package/dist/edge-config.js +1 -1
  42. package/dist/edge-config.js.map +1 -1
  43. package/dist/edge-config.mjs +1 -1
  44. package/dist/edge-config.mjs.map +1 -1
  45. package/dist/edge-core/index.d.mts +32 -4
  46. package/dist/edge-core/index.d.ts +32 -4
  47. package/dist/edge-core/index.js +28 -10
  48. package/dist/edge-core/index.js.map +1 -1
  49. package/dist/edge-core/index.mjs +28 -10
  50. package/dist/edge-core/index.mjs.map +1 -1
  51. package/dist/gateway/gateway.js +28 -10
  52. package/dist/gateway/gateway.js.map +1 -1
  53. package/dist/gateway/gateway.mjs +28 -10
  54. package/dist/gateway/gateway.mjs.map +1 -1
  55. package/dist/index.d.mts +2 -2
  56. package/dist/index.d.ts +2 -2
  57. package/dist/index.js +28 -10
  58. package/dist/index.js.map +1 -1
  59. package/dist/index.mjs +28 -10
  60. package/dist/index.mjs.map +1 -1
  61. package/dist/registration/index.js +1 -1
  62. package/dist/registration/index.js.map +1 -1
  63. package/dist/registration/index.mjs +1 -1
  64. package/dist/registration/index.mjs.map +1 -1
  65. package/dist/transport/index.js +1 -1
  66. package/dist/transport/index.js.map +1 -1
  67. package/dist/transport/index.mjs +1 -1
  68. package/dist/transport/index.mjs.map +1 -1
  69. package/dist/verify.js +1 -1
  70. package/dist/verify.js.map +1 -1
  71. package/dist/verify.mjs +1 -1
  72. package/dist/verify.mjs.map +1 -1
  73. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/version.ts","../../src/http.ts","../../src/adapters/stepup-poll.ts","../../src/trust-levels.ts","../../src/well-known.ts","../../src/failure-posture.ts","../../src/verify.ts","../../src/transport/http.ts","../../src/verified-hop.ts","../../src/adapters/http-pdlss.ts","../../src/adapters/approval-gate.ts","../../src/pdlss-pre-check.ts","../../src/metadata-capture.ts","../../src/edge-config.ts","../../src/platform-signatures.ts","../../src/edge-core/classify.ts","../../src/edge-core/events.ts","../../src/adapters/anonymous-beacon.ts","../../src/adapters/express.ts"],"sourcesContent":["/**\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.13.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 * Step-up hold-and-poll (3.6.0) — the synchronous half of the MFA-style gate,\n * mirroring the Java SDK's `awaitStepUpApproval` / `pollStepUpStatus`.\n *\n * A verify() that comes back step_up_required carries a `stepUpApproval`\n * handle: `{ approvalId, pollUrl, expiresAt }`. The adapter HOLDS the original\n * request, polls the approval status, and on 'approved' re-verifies the same\n * request once (cache-bypassed) so the backend redeems the single-use approval\n * and returns a grant. Any other terminal outcome falls into the adapter's\n * normal fail-closed deny path.\n *\n * The poll endpoint is deliberately unauthenticated (it sits above the\n * backend router's `authenticate` middleware): the unguessable UUIDv4\n * approvalId is the capability token, and the route is rate-limited\n * (60/min/IP). No Authorization header is sent.\n */\n\nimport { sdkFetch } from '../http';\nimport { GatewayConfig, StepUpApprovalInfo, StepUpApprovalStatus, StepUpOutcome } from '../types';\n\nconst DEFAULT_POLL_INTERVAL_MS = 3000;\nconst MIN_POLL_INTERVAL_MS = 250;\nconst FALLBACK_MAX_WAIT_MS = 5 * 60 * 1000;\nconst EXPIRY_GRACE_MS = 5000;\nconst POLL_REQUEST_TIMEOUT_MS = 10_000;\n\n/** Resolve the absolute poll URL. pollUrl is server-relative\n * (`/api/step-up-approvals/poll/:id`), so join it to apiBaseUrl minus its\n * `/api` suffix (the origin) — same idiom as well-known.ts. Absolute URLs\n * pass through untouched. */\nfunction resolvePollUrl(config: GatewayConfig, pollUrl: string): string {\n if (pollUrl.startsWith('http')) return pollUrl;\n const origin = (config.apiBaseUrl ?? '').replace(/\\/api\\/?$/, '');\n return origin + pollUrl;\n}\n\n/**\n * One GET of the approval's poll endpoint. Returns the status string, or\n * null on any error / non-2xx / unparsable body — the hold loop treats null\n * as transient and just polls again.\n */\nexport async function pollStepUpStatus(\n config: GatewayConfig,\n approval: StepUpApprovalInfo\n): Promise<StepUpApprovalStatus | null> {\n if (!approval.pollUrl) return null;\n try {\n const res = await sdkFetch(resolvePollUrl(config, approval.pollUrl), {\n method: 'GET',\n signal: AbortSignal.timeout(POLL_REQUEST_TIMEOUT_MS),\n });\n if (!res.ok) return null;\n const body = (await res.json()) as Record<string, unknown>;\n // Envelope shape: { success, data: { status, resolvedAt } } — a flat\n // `status` read hangs every hold (live-UAT catch). Envelope-first with a\n // flat fallback for forward compatibility, exactly like the Java SDK.\n const data = body?.data;\n const status =\n data && typeof data === 'object' ? (data as Record<string, unknown>).status : body?.status;\n return typeof status === 'string' ? (status as StepUpApprovalStatus) : null;\n } catch {\n return null; // transient poll failure — the loop just polls again\n }\n}\n\nfunction resolveDeadline(config: GatewayConfig, approval: StepUpApprovalInfo): number {\n const now = Date.now();\n const maxWait = config.stepUpMaxWaitMs ?? 0;\n if (maxWait > 0) return now + maxWait;\n // stepUpMaxWaitMs === 0: hold until the approval itself expires (+ a small\n // grace so an approval landing at the buzzer still resolves on the next\n // poll). Missing/unparsable expiresAt → fixed 5-min fallback (Java parity).\n if (approval.expiresAt) {\n const expiry = Date.parse(approval.expiresAt);\n if (!Number.isNaN(expiry)) return Math.max(now, expiry) + EXPIRY_GRACE_MS;\n }\n return now + FALLBACK_MAX_WAIT_MS;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Block until a pending step-up approval reaches a terminal state or the wait\n * budget runs out. Returns the terminal status, or 'timeout'.\n *\n * Unknown non-pending statuses (a future backend state) still terminate the\n * hold — they are returned as-is and land in the deny path, which is the safe\n * reading of \"not approved\".\n */\nexport async function awaitStepUpApproval(\n config: GatewayConfig,\n approval: StepUpApprovalInfo\n): Promise<StepUpOutcome> {\n const deadline = resolveDeadline(config, approval);\n const pollInterval = Math.max(\n MIN_POLL_INTERVAL_MS,\n config.stepUpPollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS\n );\n\n while (Date.now() < deadline) {\n const status = await pollStepUpStatus(config, approval);\n if (status && status !== 'pending') {\n return status as StepUpOutcome;\n }\n const remaining = deadline - Date.now();\n if (remaining <= 0) break;\n await sleep(Math.min(pollInterval, remaining));\n }\n return 'timeout';\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 * 5.12.0 — HTTP adapter failure posture, lifted from edge-core\n * (`pipeline.ts` isApiErrorResult/unavailableOutcome, `enforce.ts` 503 +\n * Retry-After + buildUnavailableBody) so the Express and Next.js adapters\n * and `quickVerify` answer an AstraSync outage the way the edge does.\n *\n * The 1 Oct load test: the platform rate-limited a merchant's verify-access\n * calls (429), the SDK mapped that to `UNAUTHORIZED` 401 and failed closed\n * — even for anonymous catalogue reads — so the merchant was down for 11\n * minutes. Fail posture follows success posture:\n *\n * - observe routes and anonymous reads (GET/HEAD, no credentials) pass\n * through, stamped `X-Astra-Verification: unavailable`;\n * - enforced routes answer 503 + `Retry-After` (the backend's value, else\n * 30s) + `VERIFICATION_UNAVAILABLE`. Never 401 — the caller's identity\n * was never evaluated.\n *\n * Identity status mapping (contract correction, not a break): credentials\n * missing → 401; a presented id that is malformed or unknown → 403 with\n * registration guidance (re-authenticating with the same id cannot help).\n */\nimport type { AgentCredentials, VerificationResult } from './types';\n\n/** Response header stamped on a fail-open pass-through during an outage. */\nexport const VERIFICATION_STATUS_HEADER = 'X-Astra-Verification';\n\n/** Default Retry-After (seconds) when the backend sent none — edge parity. */\nexport const DEFAULT_UNAVAILABLE_RETRY_AFTER_S = 30;\n\n/**\n * Failure dimensions for a presented-but-rejected agent identifier.\n * `agent.lookup` is the backend's 200-with-deny shape for a well-formed id\n * that matches no registered agent (round-27.4 D4 — the same verdict as the\n * 404 → `identity.unknown_agent` mapping, delivered on a different wire).\n */\nexport const REJECTED_IDENTITY_DIMENSIONS: ReadonlySet<string> = new Set([\n 'identity.invalid_agent_id',\n 'identity.unknown_agent',\n 'agent.lookup',\n]);\n\n/** Registration guidance for a presented id that matches no registered agent. */\nexport const UNKNOWN_AGENT_GUIDANCE =\n 'Register your agent with AstraSync (or, inside an MCP host, add the AstraSync MCP connector for keyless, human-approved registration), then present the canonical ASTRA-* id issued after owner approval.';\n\n/**\n * Failure dimensions that mean \"verification could not be evaluated\" rather\n * than \"the agent was denied\":\n * - `verify_access.api_error` — the SDK's typed, retryable fallback for an\n * AstraSync outage (timeout, 5xx, the platform's 429);\n * - `middleware.internal_error` — an adapter's own `failOnError: 'closed'`\n * catch path (an exception inside the gateway middleware). Failing closed\n * there is a 503, never an identity-shaped 401.\n */\nexport const UNAVAILABLE_DIMENSIONS: ReadonlySet<string> = new Set([\n 'verify_access.api_error',\n 'middleware.internal_error',\n]);\n\n/**\n * A verify() result that is the SDK's typed, retryable api_error fallback —\n * infrastructure unavailability (timeout, 5xx, 429), not a policy deny and\n * not the deterministic merchant misconfig — or an adapter's internal-error\n * fail-closed result.\n */\nexport function isVerificationUnavailable(result: VerificationResult): boolean {\n if (result.misconfigured) return false;\n return (result.failures ?? []).some((f) => UNAVAILABLE_DIMENSIONS.has(f.dimension));\n}\n\n/** Retry-After seconds to relay: the backend's value (≥1s), else 30. */\nexport function unavailableRetryAfterSeconds(result: VerificationResult): number {\n if (typeof result.retryAfterMs === 'number' && Number.isFinite(result.retryAfterMs)) {\n return Math.max(1, Math.ceil(result.retryAfterMs / 1000));\n }\n return DEFAULT_UNAVAILABLE_RETRY_AFTER_S;\n}\n\n/** An anonymous read: GET/HEAD carrying no agent credential. */\nexport function isAnonymousRead(\n method: string | undefined,\n credentials: AgentCredentials\n): boolean {\n const m = (method ?? '').toUpperCase();\n if (m !== 'GET' && m !== 'HEAD') return false;\n return !credentials.astraId && !credentials.jwt;\n}\n\n/** Machine-readable 503 body — same shape as edge-core's buildUnavailableBody. */\nexport function buildVerificationUnavailableBody(result: VerificationResult): {\n success: false;\n error: {\n code: 'VERIFICATION_UNAVAILABLE';\n message: string;\n retryable: true;\n retryAfterSeconds: number;\n failures?: VerificationResult['failures'];\n correlationId?: string;\n guidance: { message: string };\n };\n} {\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 after the Retry-After interval.',\n retryable: true,\n retryAfterSeconds: unavailableRetryAfterSeconds(result),\n ...(result.failures && { failures: result.failures }),\n ...(result.correlationId && { correlationId: result.correlationId }),\n guidance: {\n message:\n 'Retry the request after the Retry-After interval, with exponential backoff; the condition is transient.',\n },\n },\n };\n}\n\n/** True when the deny is about a presented-but-malformed/unknown agent id. */\nexport function isRejectedIdentityClaim(result: VerificationResult): boolean {\n return (result.failures ?? []).some((f) => REJECTED_IDENTITY_DIMENSIONS.has(f.dimension));\n}\n\n/**\n * HTTP status + code for an ordinary (non-outage, non-misconfig) deny:\n * missing identity → 401 UNAUTHORIZED; presented-but-rejected id → 403\n * AGENT_IDENTITY_REJECTED; identity fine but policy denied → 403 with the\n * adapter's policy code.\n */\nexport function denyStatusFor(\n result: VerificationResult,\n policyDeniedCode: string\n): { status: 401 | 403; code: string } {\n // Checked first: older backends stamp idVerified:true on the agent.lookup\n // (unknown id) deny, which would otherwise read as a policy deny.\n if (isRejectedIdentityClaim(result)) return { status: 403, code: 'AGENT_IDENTITY_REJECTED' };\n if (result.identityVerified) return { status: 403, code: policyDeniedCode };\n return { status: 401, code: 'UNAUTHORIZED' };\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';\nimport {\n REJECTED_IDENTITY_DIMENSIONS,\n UNKNOWN_AGENT_GUIDANCE,\n isVerificationUnavailable,\n unavailableRetryAfterSeconds,\n} from './failure-posture';\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 counterparty?: { id?: string; url?: 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 // 5.13.0: name the endpoint this SDK is installed on, so the backend\n // can say whether this key may verify for it (keys are bound to the\n // endpoint's owner — a key from another account is refused on every\n // request with COUNTERPARTY_KEY_MISMATCH).\n const q = counterparty?.id\n ? `?counterpartyId=${encodeURIComponent(counterparty.id)}`\n : counterparty?.url\n ? `?counterpartyUrl=${encodeURIComponent(counterparty.url)}`\n : '';\n const selfCheck = await sdkFetch(`${apiBaseUrl}/agents/verify-access/self-check${q}`, {\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 counterparty?: { found?: boolean; canVerify?: boolean; message?: string };\n };\n if (body.counterparty && body.counterparty.canVerify === false) {\n const message =\n `[VerificationGateway] the configured AstraSync API key cannot verify for this endpoint ` +\n `(${body.counterparty.message ?? 'endpoint not found or owned by another account'}). ` +\n `Every inbound agent will be turned away until the key or counterparty is corrected.`;\n if (strictInit) {\n throw new Error(`${message} (strictInit=true)`);\n }\n console.error(message);\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 /** 5.12.0: backend non-2xx status + Retry-After (api_error source). */\n httpStatus?: number;\n retryAfterMs?: number;\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, rotated, or belongs to another account). \" +\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 replacing',\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 ...(options.httpStatus !== undefined && { httpStatus: options.httpStatus }),\n ...(options.retryAfterMs !== undefined && { retryAfterMs: options.retryAfterMs }),\n correlationId: options.correlationId,\n attemptId: options.attemptId,\n verifiedAt: new Date(),\n };\n}\n\n/**\n * 5.12.0: parse a response body as JSON without throwing — a non-JSON body\n * (HTML error page, plain-text 429) yields `{}` so the status survives.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nasync function readJsonSafe(response: Response): Promise<any> {\n try {\n const parsed = await response.json();\n return parsed && typeof parsed === 'object' ? parsed : {};\n } catch {\n return {};\n }\n}\n\n/** 5.12.0: human guidance for a presented-but-malformed/unknown agent id deny. */\nfunction rejectedIdentityGuidance(\n failures: Array<{ dimension: string; message: string; guidance?: string }> | undefined\n): string | undefined {\n const f = failures?.find((x) => REJECTED_IDENTITY_DIMENSIONS.has(x.dimension));\n if (!f) return undefined;\n // The backend's agent.lookup guidance only says \"check the id format\";\n // an unknown id needs the registration path (404 parity).\n if (f.dimension === 'agent.lookup') {\n return `The presented agent identifier is not registered with AstraSync. ${UNKNOWN_AGENT_GUIDANCE}`;\n }\n return f.guidance ? `${f.message} ${f.guidance}` : f.message;\n}\n\n/** Upper bound on a relayed Retry-After (a hostile/buggy value can't park callers for hours). */\nconst MAX_RETRY_AFTER_MS = 15 * 60 * 1000;\n\n/**\n * 5.12.0: `Retry-After` (delta-seconds or HTTP-date) → milliseconds, or\n * undefined when absent/unparseable. Clamped to [0, 15 min].\n */\nexport function parseRetryAfterMs(response: {\n headers?: { get?(name: string): string | null };\n}): number | undefined {\n const raw = response.headers?.get?.('retry-after');\n if (!raw) return undefined;\n const trimmed = raw.trim();\n let ms: number;\n if (/^\\d+(\\.\\d+)?$/.test(trimmed)) {\n ms = Number(trimmed) * 1000;\n } else {\n const at = Date.parse(trimmed);\n if (Number.isNaN(at)) return undefined;\n ms = at - Date.now();\n }\n return Math.min(MAX_RETRY_AFTER_MS, Math.max(0, Math.round(ms)));\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_configured';\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 /** 5.12.0: backend HTTP status on a non-2xx (429/5xx) — see VerificationResult.httpStatus. */\n httpStatus?: number;\n /** 5.12.0: backend Retry-After in ms, when sent. */\n retryAfterMs?: number;\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 // 5.12.0: a non-JSON body (an HTML 502 from a load balancer, a plain-text\n // 429) used to throw here and lose the status; parse defensively.\n const data = await readJsonSafe(response);\n const retryAfterMs = parseRetryAfterMs(response);\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 // 5.10.0: a caller-supplied agent id that isn't a canonical ASTRA-id\n // (e.g. `ASTRA-bogus123`) is a deterministic failed identity claim, not\n // an outage. Previously it fell through to the transient api_error path,\n // so the edge answered 503 \"verification unavailable — retry\" under\n // enforce; it is now an identity deny (403 + registration guidance).\n if (response.status === 400 && data?.error === 'INVALID_AGENT_ID') {\n const message =\n typeof data?.message === 'string'\n ? data.message\n : 'Agent identifier must be a canonical ASTRA-* id.';\n return {\n success: true,\n attemptId: typeof data?.attemptId === 'string' ? data.attemptId : undefined,\n access: {\n allowed: false,\n reason: 'invalid_agent_id',\n failures: [\n {\n dimension: 'identity.invalid_agent_id',\n message,\n guidance:\n typeof data?.guidance === 'string'\n ? data.guidance\n : 'Present your canonical ASTRA-* id (discover it via GET /api/agents/request-registration/{requestId} after owner approval).',\n },\n ],\n },\n };\n }\n\n // 5.12.0: a presented agent id the backend doesn't know (404 \"Agent not\n // found\") is a deterministic failed identity claim — like the malformed\n // id above — not an outage. It used to fall through to api_error, so\n // merchants answered \"temporarily unavailable, retry\" to an agent that\n // simply isn't registered. A 404 without an agent id in the request (or\n // a non-JSON 404, i.e. a wrong apiBaseUrl) stays on the api_error path.\n if (\n response.status === 404 &&\n credentials.astraId &&\n (data?.error === 'AGENT_NOT_FOUND' ||\n (typeof data?.message === 'string' && /agent/i.test(data.message)))\n ) {\n return {\n success: true,\n attemptId: typeof data?.attemptId === 'string' ? data.attemptId : undefined,\n access: {\n allowed: false,\n reason: 'unknown_agent',\n failures: [\n {\n dimension: 'identity.unknown_agent',\n message: 'The presented agent identifier is not registered with AstraSync.',\n guidance: UNKNOWN_AGENT_GUIDANCE,\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 // 5.13.0: a 403 COUNTERPARTY_KEY_MISMATCH is the same class — this\n // integration's key belongs to an account that doesn't own the endpoint.\n const keyMismatch = response.status === 403 && data?.error === 'COUNTERPARTY_KEY_MISMATCH';\n if (response.status === 401 || keyMismatch) {\n return {\n success: false,\n error: data.message || data.error || 'Integration API key rejected',\n misconfig: true,\n misconfigCode: keyMismatch\n ? 'counterparty_key_mismatch'\n : typeof data?.code === 'string'\n ? data.code\n : 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 // 5.12.0: keep the status + Retry-After so adapters can relay the\n // platform's back-off (429 rate limit vs 5xx outage).\n return {\n success: false,\n error:\n (typeof data?.message === 'string' && data.message) ||\n (typeof data?.error === 'string' && data.error) ||\n `API returned ${response.status}`,\n correlationId: typeof data?.correlationId === 'string' ? data.correlationId : undefined,\n attemptId: typeof data?.attemptId === 'string' ? data.attemptId : undefined,\n httpStatus: response.status,\n ...(retryAfterMs !== undefined && { retryAfterMs }),\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 id: mergedConfig.counterpartyId,\n url: mergedConfig.counterpartyUrl ?? request.counterpartyUrl,\n }\n );\n } else {\n void performInitCheck(\n mergedConfig.apiBaseUrl,\n mergedConfig.debug,\n false,\n mergedConfig.apiKey,\n {\n id: mergedConfig.counterpartyId,\n url: mergedConfig.counterpartyUrl ?? request.counterpartyUrl,\n }\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 httpStatus: apiResponse.httpStatus,\n retryAfterMs: apiResponse.retryAfterMs,\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 // 5.12.0 (round-27.4 D4): a presented id that matches no registered\n // agent is never \"identity verified\", whatever an older backend stamped.\n const idVerifiedFromBackend =\n (apiResponse.verificationContext as { idVerified?: boolean } | undefined)?.idVerified ===\n true && !aggregatedFailures?.some((f) => REJECTED_IDENTITY_DIMENSIONS.has(f.dimension));\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 // 5.12.0: a presented-but-rejected id (malformed / unknown) carries\n // actionable registration guidance on its failure — surface it\n // instead of the bare machine reason ('unknown_agent').\n message:\n rejectedIdentityGuidance(aggregatedFailures) ??\n (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 blockchainAnchored: apiResponse.agent.blockchainStatus === 'anchored',\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' && result.identityVerified) {\n // The escalation signal rides on `requiresStepUp` / `stepUpApproval`, not\n // on any masquerade of the (now-removed) access band.\n //\n // 5.12.0 (round-27.4 D1): step-up is \"allowed-but-escalate\" — the\n // registered agent's OWNER approves a valued action. An unidentified\n // caller has no owner to escalate to, so an allowed response for one is\n // a grant: older backends labelled recognised-but-unregistered agents\n // (Claude-User, the AstraSync bridge) step_up_required on plain reads,\n // and the adapters 401'd an anonymous catalog GET as \"requires human\n // approval\". The backend no longer emits that; this keeps merchants on\n // 5.12.0 correct against an older backend too. Denies are untouched —\n // they take the !allowed branch above.\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 — never throws. 5.12.0: a 429/5xx is retried once\n * (Retry-After honoured, capped at 2s) off the caller's path; a lost report\n * is surfaced via `options.onFailure`.\n */\nexport async function reportAttempt(\n config: GatewayConfig,\n report: AttemptReport,\n options: ReportAttemptOptions = {}\n): 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 const url = `${apiBaseUrl}/agents/verify-access/attempt-report`;\n const init = { method: 'POST', headers, body: JSON.stringify(body) };\n // 5.12.0: check the status — a 429/5xx used to vanish silently (the 1 Oct\n // load test lost attempt reports this way). One bounded retry honouring\n // Retry-After (capped at 2s), scheduled OFF the caller's path; never throws.\n const fail = (failure: { status?: number; error?: string; retried: boolean }): void => {\n try {\n options.onFailure?.(failure);\n } catch {\n /* a reporter callback must never break the caller */\n }\n };\n let response: Response | undefined;\n try {\n response = await sdkFetch(url, init);\n } catch (err) {\n fail({ error: err instanceof Error ? err.message : String(err), retried: false });\n return;\n }\n if (response.ok) return;\n if (response.status !== 429 && response.status < 500) {\n fail({ status: response.status, retried: false });\n return;\n }\n const delayMs = Math.min(ATTEMPT_REPORT_MAX_RETRY_DELAY_MS, parseRetryAfterMs(response) ?? 500);\n const timer = setTimeout(() => {\n sdkFetch(url, init)\n .then((retry) => {\n if (!retry.ok) fail({ status: retry.status, retried: true });\n })\n .catch((err) => {\n fail({ error: err instanceof Error ? err.message : String(err), retried: true });\n });\n }, delayMs);\n (timer as { unref?: () => void }).unref?.();\n}\n\n/** 5.12.0: options for {@link reportAttempt}. */\nexport interface ReportAttemptOptions {\n /**\n * Called once when the report is finally lost (non-retryable status,\n * network error, or the single retry failed). For counters/telemetry;\n * exceptions it throws are swallowed.\n */\n onFailure?: (failure: { status?: number; error?: string; retried: boolean }) => void;\n}\n\n/** 5.12.0: upper bound on reportAttempt's single retry delay. */\nconst ATTEMPT_REPORT_MAX_RETRY_DELAY_MS = 2000;\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 */\n/** 5.13.0: endpoints whose policy read was refused (log once each). */\nconst refusedPolicyReads = new Set<string>();\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) {\n // 5.13.0: a refused policy read is not \"no policy configured\". The key\n // can't see this endpoint (another account's key, or a wrong id), so\n // the middleware is passing EVERY request through unverified. Say so,\n // loudly, once per endpoint.\n if (\n (response.status === 401 || response.status === 403 || response.status === 404) &&\n !refusedPolicyReads.has(counterpartyId)\n ) {\n refusedPolicyReads.add(counterpartyId);\n // eslint-disable-next-line no-console\n console.error(\n `[VerificationGateway] the configured API key cannot read the route policy for ${counterpartyId} ` +\n `(HTTP ${response.status}). The key belongs to an account that does not own this endpoint, ` +\n `or the counterpartyId is wrong. The gateway is in PASS-THROUGH mode: no agent is being verified.`\n );\n }\n return null;\n }\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 * VI uplift Part 3 — attempt-chain handle (`att_<32hex>`, from the\n * X-Astra-Attempt-Id header or an `?astra_attempt=` deep link). Joins\n * the beacon into the agent's research chain. Attribution only.\n */\n attemptId?: string;\n /** First-class referer (traffic-source reporting). */\n referer?: string;\n /** The caller's Accept header (surface-classifier input). */\n accept?: string;\n /** Self-declared platform from X-Astra-Source (attribution, never trust). */\n declaredSource?: 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 // 5.12.0: send the merchant's API key when configured — the backend then\n // stamps the row `attributionVerified: true` (it checks the key owns the\n // counterparty). Without a key the beacon is still accepted, but flagged\n // as unverified attribution in Visit Intelligence.\n await sdkFetch(`${apiBaseUrl}/verification-activity/unregistered-attempt`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(config.apiKey && { Authorization: `Bearer ${config.apiKey}` }),\n },\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 * 5.12.0: verification infrastructure was unavailable (timeout / 5xx /\n * the platform's 429) — NOT a denial. Callers should fail open on reads\n * or answer 503 + Retry-After (`retryAfterMs`, else 30s), never 401.\n */\n unavailable?: true;\n retryAfterMs?: number;\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 ...(isVerificationUnavailable(result) && {\n unavailable: true as const,\n retryAfterMs: unavailableRetryAfterSeconds(result) * 1000,\n }),\n };\n}\n","/**\n * HTTP Transport Adapter\n *\n * Maps AstraSync credentials to/from HTTP headers (X-Astra-* convention).\n */\n\nimport type { AstraSyncCredentials } from '../types';\n\nconst HEADER_PREFIX = 'X-Astra-';\n\n/**\n * Inject AstraSync credentials into HTTP headers.\n */\nexport function setHttpHeaders(\n headers: Record<string, string>,\n credentials: AstraSyncCredentials\n): Record<string, string> {\n const result = { ...headers };\n\n result[`${HEADER_PREFIX}ID`] = credentials.agentId;\n\n if (credentials.verifyUrl) {\n result[`${HEADER_PREFIX}Verify`] = credentials.verifyUrl;\n }\n\n if (credentials.challengeUrl) {\n result[`${HEADER_PREFIX}Challenge`] = credentials.challengeUrl;\n }\n\n if (credentials.pdlss?.purpose) {\n // 3.1.0 (Bug 14, §4.6): the action ALSO travels on its own dedicated\n // header so new-SDK receivers get the clean two-axis pair. The colon\n // form below is kept as the back-compat channel — pre-3.1.0 receivers\n // split on ':' and take the category prefix.\n const purposeValue = credentials.pdlss.purpose.action\n ? `${credentials.pdlss.purpose.category}:${credentials.pdlss.purpose.action}`\n : credentials.pdlss.purpose.category;\n result[`${HEADER_PREFIX}Purpose`] = purposeValue;\n if (credentials.pdlss.purpose.action) {\n result[`${HEADER_PREFIX}Action`] = credentials.pdlss.purpose.action;\n }\n }\n\n if (credentials.pdlss?.duration?.maxSessionDuration) {\n result[`${HEADER_PREFIX}Duration`] = String(credentials.pdlss.duration.maxSessionDuration);\n }\n\n if (credentials.pdlss?.scope?.jurisdiction) {\n result[`${HEADER_PREFIX}Scope`] = credentials.pdlss.scope.jurisdiction;\n }\n\n return result;\n}\n\n/**\n * Extract AstraSync credentials from HTTP headers.\n */\nexport function extractHttpCredentials(\n headers: Record<string, string | string[] | undefined>\n): AstraSyncCredentials | null {\n const getValue = (key: string): string | undefined => {\n const v = headers[key] ?? headers[key.toLowerCase()];\n return Array.isArray(v) ? v[0] : v;\n };\n\n const agentId = getValue(`${HEADER_PREFIX}ID`) ?? getValue('x-astra-id');\n if (!agentId) return null;\n\n const credentials: AstraSyncCredentials = { agentId };\n\n const verifyUrl = getValue(`${HEADER_PREFIX}Verify`) ?? getValue('x-astra-verify');\n if (verifyUrl) credentials.verifyUrl = verifyUrl;\n\n const challengeUrl = getValue(`${HEADER_PREFIX}Challenge`) ?? getValue('x-astra-challenge');\n if (challengeUrl) credentials.challengeUrl = challengeUrl;\n\n const purpose = getValue(`${HEADER_PREFIX}Purpose`) ?? getValue('x-astra-purpose');\n if (purpose) {\n const [category, action] = purpose.split(':');\n credentials.pdlss = {\n ...credentials.pdlss,\n purpose: { category, action },\n };\n }\n\n // 3.1.0 (Bug 14, §4.6): dedicated action header — overrides any colon-form\n // remainder parsed above (the dedicated header is the canonical channel).\n const astraAction = getValue(`${HEADER_PREFIX}Action`) ?? getValue('x-astra-action');\n if (astraAction) {\n credentials.pdlss = {\n ...credentials.pdlss,\n purpose: { category: credentials.pdlss?.purpose?.category ?? '', action: astraAction },\n };\n }\n\n const duration = getValue(`${HEADER_PREFIX}Duration`) ?? getValue('x-astra-duration');\n if (duration) {\n credentials.pdlss = {\n ...credentials.pdlss,\n duration: { maxSessionDuration: parseInt(duration, 10) },\n };\n }\n\n const scope = getValue(`${HEADER_PREFIX}Scope`) ?? getValue('x-astra-scope');\n if (scope) {\n credentials.pdlss = {\n ...credentials.pdlss,\n scope: { jurisdiction: scope },\n };\n }\n\n return credentials;\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 * 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 * Direct-path step-up approval gate (post-3.1.0 F2 follow-up).\n *\n * The verify-access spending-Limit ladder returns an \"allowed-but-escalate\"\n * outcome for a transaction value in the human-in-the-loop band\n * `[autonomousThreshold, hardLimit)`: `policyAllowed: true` (it is NOT a deny)\n * plus `requiresStepUp` / `requiresApproval`. The bridge blocks these; the\n * direct-path adapters historically gated on `identityVerified && policyAllowed`\n * alone and would therefore ADMIT (and let the merchant settle) the very\n * purchase the bridge blocks - a cross-path bypass.\n *\n * The backend now creates a pending step-up approval record and returns a\n * `stepUpApproval` object with `{ approvalId, pollUrl, expiresAt }` in the\n * verify-access response. The owner can approve/deny from the dashboard\n * (Activity → Pending Verifications). Future channels: mobile push, browser\n * extension.\n *\n * Direct-path adapters (Express/MCP/Next.js) fail closed BY DEFAULT. The\n * `stepUpApproval` info is included in the deny response so integrations can\n * surface it (\"your agent owner needs to approve this\") or poll it themselves.\n * 3.6.0 adds an opt-in hold-and-poll (`stepUpMaxWaitMs` on GatewayConfig, see\n * ./stepup-poll.ts): the adapter holds the request, polls the approval, and on\n * 'approved' re-verifies once (cache-bypassed) so the backend redeems the\n * single-use approval — the MFA model the Java SDK ships default-on. Opt-in\n * here because a minor release must not silently convert instant 403s into\n * multi-minute holds (client timeouts, connection pools, edge wall-clocks).\n *\n * Detection keys on the granular Limit flags (`requiresStepUp` /\n * `requiresApproval`, set from the verify-access `access` block) rather than\n * the `recommendation` umbrella - both because those flags ARE what drive a\n * `step_up_required` recommendation server-side, and because it keeps the\n * unverified-agent-policy `audit` outcome (a deliberate allow-and-log) from\n * being caught here.\n */\nimport type { VerificationResult, StepUpApprovalInfo } from '../types';\n\nconst APPROVAL_REASON =\n 'Transaction is above the autonomous limit and requires human approval. The agent owner can approve or deny this transaction in the AstraSync dashboard.';\n\n/** True when the outcome needs human step-up/approval. */\nexport function requiresHumanApproval(result: VerificationResult): boolean {\n return result.requiresStepUp === true || result.requiresApproval === true;\n}\n\n/**\n * Annotate a result in place with the structured approval-required failure +\n * denial reason, so the adapters' existing deny renderers surface it like any\n * other failure. Mirrors the bridge's `commerce.intent.approval_required`.\n */\nexport function annotateApprovalRequired(result: VerificationResult): void {\n result.failures = [\n ...(result.failures ?? []),\n { dimension: 'commerce.intent.approval_required', message: APPROVAL_REASON },\n ];\n result.denialReasons = [APPROVAL_REASON, ...(result.denialReasons ?? [])];\n}\n\n/**\n * Extract step-up approval polling info from the verification result, if\n * present. Returns undefined when no approval was created (e.g. transaction\n * below the autonomous threshold, or the backend couldn't create one).\n */\nexport function getApprovalPollingInfo(result: VerificationResult): StepUpApprovalInfo | undefined {\n return result.stepUpApproval;\n}\n","/**\n * Counterparty-side PDLSS pre-check.\n *\n * Compares the agent's requested PDLSS dimensions (from X-Astra-* headers)\n * against the counterparty-defined maximums on the route config.\n * Returns an array of failures — empty means all checks passed.\n *\n * This runs BEFORE calling verify-access on AstraSync. If it fails,\n * the request is rejected immediately without calling the platform.\n */\n\nimport type { RouteAccessConfig, AstraSyncCredentials, CounterpartyPreCheckFailure } from './types';\n\nexport function performCounterpartyPreCheck(\n routeConfig: RouteAccessConfig,\n astraCreds: AstraSyncCredentials | null,\n purpose: string | undefined\n): CounterpartyPreCheckFailure[] {\n const failures: CounterpartyPreCheckFailure[] = [];\n\n // Check purpose against allowedPurposes whitelist. Route allow-lists are an\n // OPTIONAL per-route refinement — undefined/empty = \"skip, let the backend\n // evaluator be the authoritative gate\". The backend's PDLSS evaluator\n // enforces the agent's own declared policy (round-18.5 F3 fail-closed there\n // is correct: the agent declared its allowlist or didn't). Treating an\n // undefined route allow-list as fail-closed breaks every partner that hasn't\n // enumerated allowedPurposes (which is most of them — round-18.5 originally\n // shipped this and was reverted in 2.4.11 after partner-wide auth break).\n if (routeConfig.allowedPurposes && routeConfig.allowedPurposes.length > 0 && purpose) {\n if (!routeConfig.allowedPurposes.includes(purpose)) {\n failures.push({\n field: 'purpose',\n requested: purpose,\n limit: routeConfig.allowedPurposes,\n message: `Purpose \"${purpose}\" is not in the allowed list: [${routeConfig.allowedPurposes.join(', ')}]`,\n });\n }\n }\n\n // Check purpose against requiredPurposes (legacy field — agent must declare one of these)\n if (routeConfig.requiredPurposes && routeConfig.requiredPurposes.length > 0 && purpose) {\n if (!routeConfig.requiredPurposes.includes(purpose)) {\n failures.push({\n field: 'purpose',\n requested: purpose,\n limit: routeConfig.requiredPurposes,\n message: `Purpose \"${purpose}\" is not in the required list: [${routeConfig.requiredPurposes.join(', ')}]`,\n });\n }\n }\n\n // Check duration against maxDuration — range-check (unchanged; undefined =\n // no upper bound is conventional for opt-in range fields, not a request-\n // driven allow-list).\n if (routeConfig.maxDuration && astraCreds?.pdlss?.duration?.maxSessionDuration) {\n const requested = astraCreds.pdlss.duration.maxSessionDuration;\n if (requested > routeConfig.maxDuration) {\n failures.push({\n field: 'duration',\n requested,\n limit: routeConfig.maxDuration,\n message: `Requested duration ${requested}s exceeds maximum ${routeConfig.maxDuration}s`,\n });\n }\n }\n\n // Check jurisdiction against allowedJurisdictions. Same reasoning as\n // allowedPurposes above — route allow-lists are an optional per-route\n // refinement; undefined/empty = skip and defer to the backend evaluator.\n if (\n routeConfig.allowedJurisdictions &&\n routeConfig.allowedJurisdictions.length > 0 &&\n astraCreds?.pdlss?.scope?.jurisdiction\n ) {\n const requested = astraCreds.pdlss.scope.jurisdiction;\n if (!routeConfig.allowedJurisdictions.includes(requested)) {\n failures.push({\n field: 'jurisdiction',\n requested,\n limit: routeConfig.allowedJurisdictions,\n message: `Jurisdiction \"${requested}\" is not in the allowed list: [${routeConfig.allowedJurisdictions.join(', ')}]`,\n });\n }\n }\n\n return failures;\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 * Query-string VALUES for parameter names the endpoint owner explicitly\n * allow-listed (`EdgeConfig.queryValueAllowlist`, seeded `utm_*` — VI\n * uplift Part 4). The default remains NO value capture; this exists so\n * campaign attribution (utm_source/medium/campaign) can be reported\n * without widening the privacy stance. Bounded 16 entries × 256 chars.\n */\n queryParams?: Record<string, 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\n/**\n * `X-Astra-Source` declared-source protocol (VI uplift Part 2). The header is\n * SELF-ASSERTED and spoofable — it buys attribution, never trust: it is never\n * read by any access decision and never conflated with fingerprint-matched\n * (`platformVendor`) or ASTRA-verified evidence. One shared validator so the\n * edge, backend, and bridge accept byte-identical values.\n */\nexport const DECLARED_SOURCE_MAX = 64;\nconst DECLARED_SOURCE_PATTERN = /^[a-z0-9][a-z0-9 ._/-]{0,63}$/;\n\nexport function normalizeDeclaredSource(value: string | undefined | null): string | undefined {\n const trimmed = value?.trim().slice(0, DECLARED_SOURCE_MAX).toLowerCase();\n return trimmed && DECLARED_SOURCE_PATTERN.test(trimmed) ? trimmed : undefined;\n}\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 * 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 * Per-path beacon sampling opt-DOWN (VI uplift 1.2). The default is full\n * capture; put a fractional rate on explicitly high-volume/low-value paths\n * (static mirrors, health checks) instead of sampling commerce traffic.\n */\n sampling?: {\n /** Fraction (0..1) of anonymous-bot requests that emit a beacon. */\n anonymousBeaconRate: number;\n };\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 * Query-string parameter names whose VALUES may be captured into\n * `observedMetadata.queryParams` (VI uplift Part 4 — campaign/UTM\n * attribution). Lowercase exact names or a single trailing-`*` glob\n * (`utm_*`); ≤16 entries × ≤64 chars. ABSENT by default — the privacy\n * stance (query values dropped at capture) is unchanged unless the\n * endpoint owner explicitly configures this.\n */\n queryValueAllowlist?: string[];\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 *\n * Beacon rate 1.0 (VI uplift 1.2): every anonymous hit beacons by default —\n * a sampled denominator understates anonymous traffic in every dashboard\n * tile and no toggle can reveal the dropped rows. Sampling is a deliberate\n * per-path opt-down (`EdgePathRule.sampling`) for static/high-volume paths.\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: 1.0 }),\n failurePosture: 'open',\n}) as EdgeConfig;\n\nconst EDGE_MODES: readonly string[] = ['observe', 'enforce'];\nconst EDGE_DEPTHS: readonly string[] = ['classify', 'authenticate', 'authorize'];\n\nfunction isSamplingShape(value: unknown): value is { anonymousBeaconRate: number } {\n if (typeof value !== 'object' || value === null) return false;\n const rate = (value as Record<string, unknown>).anonymousBeaconRate;\n return typeof rate === 'number' && rate >= 0 && rate <= 1;\n}\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 if (r.sampling !== undefined && !isSamplingShape(r.sampling)) return false;\n }\n if (!isSamplingShape(v.sampling)) return false;\n if (v.queryValueAllowlist !== undefined) {\n if (\n !Array.isArray(v.queryValueAllowlist) ||\n v.queryValueAllowlist.length > 16 ||\n !v.queryValueAllowlist.every((e) => typeof e === 'string' && e.length > 0 && e.length <= 64)\n ) {\n return false;\n }\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 * 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-bridge'\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 // GPTBot (training crawler) and OAI-SearchBot (ChatGPT search) are\n // OpenAI's declared crawler UAs — `gpt-?\\d` never matched them, so they\n // classified as unattributed crawlers (round-27.4 W5).\n uaPatterns: [/chatgpt/i, /openai/i, /gpt-?\\d/i, /\\bGPTBot\\b/i, /\\bOAI-SearchBot\\b/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: [\n /gemini/i,\n /google-gemini/i,\n /bard/i,\n // Google's AI/agent fetcher tokens (VI uplift 1.3). These are the\n // AI-training/agent crawlers, NOT the Search crawler — googlebot IP\n // ranges attribute Search and are deliberately absent from\n // vendor-ip-ranges. Anchored tokens: none appears in stock browser\n // UAs, and `-` counts as a \\b boundary so GoogleOther-Image/-Video\n // match too.\n /\\bGoogle-Extended\\b/i,\n /\\bGoogleOther\\b/i,\n /\\bGoogle-CloudVertexBot\\b/i,\n ],\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 // The MCP bridge's own catalog fetches (VI uplift 1.5). Deliberately a\n // DISTINCT UA from `astrasync-sdk/`: bridge fetches are buyer-agent\n // traffic merchants should see (identified · unregistered), so this\n // vendor is kept OUT of the self-traffic filter and the edge's SELF\n // short-circuit.\n {\n vendor: 'astrasync-bridge',\n displayName: 'AstraSync MCP bridge (buyer-agent catalog fetch)',\n uaPatterns: [/^astrasync-bridge\\//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 * 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 * AstraSync ACCOUNT API key shape (`kya_` + key material) — the platform's\n * own origin-auth credential (api-key.service `API_KEY_PREFIX`), NOT an\n * agent identity. See the round-17 first-party branch in classify().\n */\nconst ACCOUNT_API_KEY_PATTERN = /^kya_[A-Za-z0-9_-]+$/;\n\nfunction isAccountApiKey(value: string | undefined): boolean {\n return typeof value === 'string' && ACCOUNT_API_KEY_PATTERN.test(value);\n}\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 ...(rule.sampling && { sampling: rule.sampling }),\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 // Round-17 (staging finding, cost hours of masked key-validity debugging):\n // an ACCOUNT API key (`kya_…`) in Authorization/x-api-key is FIRST-PARTY\n // origin auth — curl/Postman/non-SDK backend clients calling the property's\n // own API — not an agent identity claim. Tiering it `verified` sent it into\n // verify-access, which can never verify an account key as an agent, so\n // enforce mode 403'd every plain API client (\"Endpoint policy denies\n // unverified agents\") even with a VALID key — also a self-DoS vector.\n // Treat it like self-traffic: pass through untouched, zero beacons; the\n // origin's own auth stays authoritative. An explicit X-Astra-Id alongside\n // still classifies as an agent claim below. (`kya_` is the only account-key\n // prefix the platform issues — api-key.service API_KEY_PREFIX.)\n if (\n !credentials.astraId &&\n (isAccountApiKey(credentials.jwt) || isAccountApiKey(credentials.apiKey))\n ) {\n return { tier: 'self', evidence: { firstPartyApiKey: true } };\n }\n // Only an ASTRA id is an agent identity claim: verify-access is sent the\n // ASTRA id and nothing else (verify.ts builds the body from\n // credentials.astraId only), so a bare Bearer JWT or a non-kya_ x-api-key\n // could never verify — tiering it `verified` just denied it under enforce.\n // Round-26 staging finding: that self-DoS'd first-party sessions (the\n // property's own chat/OAuth Bearer tokens — our BYOAI widget and passkey\n // ceremony page) and would do the same to any merchant SPA whose signed-in\n // users call its API with Bearer tokens. Such requests fall through to the\n // normal classification below (UA / commerce protocol / fingerprint), so a\n // made-up token earns nothing — it neither verifies nor bypasses the edge.\n if (credentials.astraId) {\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 * Time-budgeted event emission + the edge beacon buffer.\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: latency to the\n * customer's traffic is bounded, and a slow AstraSync API costs telemetry\n * time, never page loads. Runtimes that provide `waitUntil` (Cloudflare\n * Workers, Vercel Edge, Fastly Compute) pass it via\n * {@link EdgeCoreOptions.waitUntil} to take beacons off the latency path.\n *\n * 5.12.0 (round 27.4): beacons go through a module-scope\n * {@link BeaconBuffer} instead of one awaited POST each. Measured on\n * staging, one-POST-per-request under a 300ms budget delivered only ~38%\n * of beacons (origin RTT ~230ms, cold TLS ~700ms, so most POSTs were\n * abandoned at the budget). The buffer:\n * - is bounded (1000 items, drop-oldest, counted);\n * - flushes batches of ≤100 same-destination items to\n * `/verification-activity/edge-events`, authenticated with the API key\n * when one is configured (unauthenticated batches are still accepted,\n * flagged as unverified attribution);\n * - keeps its in-flight flush across invocations — a POST abandoned at the\n * budget keeps running, and a frozen Lambda resumes it on thaw; items in\n * flight are never re-sent while it is pending;\n * - re-queues failed items (max 3 attempts; 429 honours Retry-After\n * without spending an attempt; a 401 on the key falls back to\n * unauthenticated delivery);\n * - collapses identical requests (same counterparty, IP, UA, method, path,\n * attempt id) inside a 60s window into one item carrying `repeatCount`;\n * - stamps each batch with `meta { droppedSinceLast, queueDepth, adapter,\n * version }` so the backend can report delivery loss.\n * Delivery is at-least-once: a POST that times out after the backend\n * recorded it is retried.\n */\n\nimport { sdkFetch } from '../http';\nimport { normalizeDeclaredSource } from '../metadata-capture';\nimport { SDK_VERSION } from '../version';\nimport { buildObservedMetadata, extractAttemptId, 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/** One beacon item — the backend `unregisteredAttemptSchema` shape + observedAt. */\nexport type BeaconItem = Record<string, unknown> & { repeatCount?: number };\n\n/** Where a beacon goes. Items batch together only when every field matches. */\nexport interface BeaconDestination {\n apiBaseUrl: string;\n /** Sent as `Authorization: Bearer` when set (verified attribution). */\n apiKey?: string;\n /** The counterparty the item names — one batch never mixes counterparties. */\n counterparty: string;\n /** Adapter name reported in batch meta (e.g. `lambda-edge`). */\n adapter?: string;\n}\n\n/** Batch metadata the backend records for delivery monitoring. */\nexport interface BeaconBatchMeta {\n droppedSinceLast: number;\n queueDepth: number;\n adapter: string;\n version: string;\n}\n\nexport interface BeaconBufferOptions {\n /** Max queued items; the oldest is dropped (and counted) beyond it. Default 1000. */\n maxItems?: number;\n /** Max items per POST (backend cap). Default 100. */\n maxBatch?: number;\n /** Delivery attempts per item before it is dropped. Default 3. */\n maxAttempts?: number;\n /** Repeat-collapse window. Default 60s. */\n collapseWindowMs?: number;\n /** Max distinct repeat keys remembered (LRU). Default 1000. */\n collapseMaxKeys?: number;\n /** Per-POST timeout (the budget is the caller's; this bounds a hung POST). Default 10s. */\n requestTimeoutMs?: number;\n /** Pause after a failed POST before the next attempt. Default 1s. */\n retryBackoffMs?: number;\n /** Clock — injectable for tests. */\n now?: () => number;\n}\n\ninterface QueuedBeacon {\n dest: BeaconDestination;\n destKey: string;\n item: BeaconItem;\n attempts: number;\n /** Held repeat aggregates aren't sent until their collapse window closes. */\n eligibleAt: number;\n inFlight: boolean;\n}\n\ninterface CollapseEntry {\n firstSeenAt: number;\n /** The window's first item — repeats merge into it while it is still queued. */\n first?: QueuedBeacon;\n /** The held aggregate absorbing repeats once the first item has left. */\n held?: QueuedBeacon;\n}\n\nconst destKeyOf = (d: BeaconDestination) =>\n `${d.apiBaseUrl}\\u0000${d.apiKey ?? ''}\\u0000${d.counterparty}\\u0000${d.adapter ?? ''}`;\n\nexport class BeaconBuffer {\n private queue: QueuedBeacon[] = [];\n private droppedSinceLast = 0;\n private droppedTotal = 0;\n private deliveredTotal = 0;\n private inFlight: Promise<void> | undefined;\n private backoffUntil = 0;\n private readonly collapse = new Map<string, CollapseEntry>();\n /** Keys the backend answered 401 for — later batches go unauthenticated. */\n private readonly rejectedKeys = new Set<string>();\n private readonly opts: Required<BeaconBufferOptions>;\n\n constructor(options: BeaconBufferOptions = {}) {\n this.opts = {\n maxItems: options.maxItems ?? 1000,\n maxBatch: options.maxBatch ?? 100,\n maxAttempts: options.maxAttempts ?? 3,\n collapseWindowMs: options.collapseWindowMs ?? 60_000,\n collapseMaxKeys: options.collapseMaxKeys ?? 1000,\n requestTimeoutMs: options.requestTimeoutMs ?? 10_000,\n retryBackoffMs: options.retryBackoffMs ?? 1_000,\n now: options.now ?? Date.now,\n };\n }\n\n /**\n * Queue one beacon. With a `collapseKey`, a repeat inside the window is\n * merged into a held aggregate (sent when the window closes) instead of\n * becoming its own item.\n */\n enqueue(dest: BeaconDestination, item: BeaconItem, collapseKey?: string): void {\n const now = this.opts.now();\n if (collapseKey) {\n const entry = this.collapse.get(collapseKey);\n if (entry && now - entry.firstSeenAt < this.opts.collapseWindowMs) {\n for (const target of [entry.first, entry.held]) {\n if (target && !target.inFlight && this.queue.includes(target)) {\n target.item.repeatCount = (target.item.repeatCount ?? 1) + 1;\n return;\n }\n }\n const held = this.push(\n dest,\n { ...item, repeatCount: 1 },\n entry.firstSeenAt + this.opts.collapseWindowMs\n );\n entry.held = held;\n return;\n }\n // New (or expired) key: refresh LRU position, evict the oldest.\n this.collapse.delete(collapseKey);\n if (this.collapse.size >= this.opts.collapseMaxKeys) {\n const oldest = this.collapse.keys().next().value;\n if (oldest !== undefined) this.collapse.delete(oldest);\n }\n const fresh: CollapseEntry = { firstSeenAt: now };\n this.collapse.set(collapseKey, fresh);\n fresh.first = this.push(dest, item, now);\n return;\n }\n this.push(dest, item, now);\n }\n\n /**\n * Deliver every eligible queued item. Concurrent callers share ONE\n * in-flight drain (it survives the caller's budget and a Lambda freeze),\n * so nothing in flight is ever sent twice; items queued while it runs are\n * picked up by the same drain.\n */\n flush(): Promise<void> {\n if (!this.inFlight) {\n this.inFlight = this.drain().finally(() => {\n this.inFlight = undefined;\n });\n }\n return this.inFlight;\n }\n\n /** Counters for tests and diagnostics. */\n stats(): {\n queueDepth: number;\n droppedSinceLast: number;\n droppedTotal: number;\n deliveredTotal: number;\n flushing: boolean;\n } {\n return {\n queueDepth: this.queue.length,\n droppedSinceLast: this.droppedSinceLast,\n droppedTotal: this.droppedTotal,\n deliveredTotal: this.deliveredTotal,\n flushing: this.inFlight !== undefined,\n };\n }\n\n private push(dest: BeaconDestination, item: BeaconItem, eligibleAt: number): QueuedBeacon {\n while (this.queue.length >= this.opts.maxItems) this.dropOldest();\n const entry: QueuedBeacon = {\n dest,\n destKey: destKeyOf(dest),\n item,\n attempts: 0,\n eligibleAt,\n inFlight: false,\n };\n this.queue.push(entry);\n return entry;\n }\n\n private dropOldest(): void {\n if (this.queue.shift()) this.countDropped(1);\n }\n\n private countDropped(n: number): void {\n this.droppedSinceLast += n;\n this.droppedTotal += n;\n }\n\n private async drain(): Promise<void> {\n for (;;) {\n const now = this.opts.now();\n if (now < this.backoffUntil) return;\n const batch = this.takeBatch(now);\n if (batch.length === 0) return;\n const ok = await this.send(batch);\n if (!ok) return; // backoff set; the next flush() resumes\n }\n }\n\n /** Oldest eligible item + up to maxBatch-1 more for the same destination. */\n private takeBatch(now: number): QueuedBeacon[] {\n const first = this.queue.find((q) => q.eligibleAt <= now);\n if (!first) return [];\n const batch: QueuedBeacon[] = [];\n const rest: QueuedBeacon[] = [];\n for (const q of this.queue) {\n if (batch.length < this.opts.maxBatch && q.destKey === first.destKey && q.eligibleAt <= now) {\n q.inFlight = true;\n batch.push(q);\n } else {\n rest.push(q);\n }\n }\n this.queue = rest;\n return batch;\n }\n\n /** POST one batch. Returns false when the drain should pause (backoff). */\n private async send(batch: QueuedBeacon[]): Promise<boolean> {\n const dest = batch[0].dest;\n const useKey = dest.apiKey && !this.rejectedKeys.has(dest.apiKey) ? dest.apiKey : undefined;\n const reportedDropped = this.droppedSinceLast;\n const meta: BeaconBatchMeta = {\n droppedSinceLast: reportedDropped,\n queueDepth: this.queue.length,\n adapter: dest.adapter ?? 'edge-core',\n version: SDK_VERSION,\n };\n const controller = typeof AbortController !== 'undefined' ? new AbortController() : undefined;\n const response = await withBudget(\n sdkFetch(`${dest.apiBaseUrl}/verification-activity/edge-events`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(useKey && { Authorization: `Bearer ${useKey}` }),\n },\n body: JSON.stringify({ events: batch.map((q) => q.item), meta }),\n ...(controller && { signal: controller.signal }),\n }),\n this.opts.requestTimeoutMs\n );\n if (!response) controller?.abort();\n const status = response?.status;\n\n for (const q of batch) q.inFlight = false;\n\n if (status !== undefined && status >= 200 && status < 300) {\n // The backend now knows about the drops it was told of.\n this.droppedSinceLast = Math.max(0, this.droppedSinceLast - reportedDropped);\n this.deliveredTotal += batch.length;\n return true;\n }\n if (status === 401 && useKey) {\n // Dead key: keep delivering, unauthenticated (accepted, flagged).\n this.rejectedKeys.add(useKey);\n this.requeue(batch, false);\n return true;\n }\n if (status === 429) {\n const retryAfter = Number(response?.headers.get('retry-after'));\n const waitMs =\n Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter, 120) * 1000 : 30_000;\n this.backoffUntil = this.opts.now() + waitMs;\n this.requeue(batch, false);\n return false;\n }\n if (status !== undefined && status >= 400 && status < 500) {\n // The backend refused the batch itself — retrying can't help.\n this.countDropped(batch.length);\n return true;\n }\n // Network error, timeout, or 5xx: retry later.\n this.backoffUntil = this.opts.now() + this.opts.retryBackoffMs;\n this.requeue(batch, true);\n return false;\n }\n\n /** Put a failed batch back at the head of the queue (order preserved). */\n private requeue(batch: QueuedBeacon[], countAttempt: boolean): void {\n const keep: QueuedBeacon[] = [];\n for (const q of batch) {\n if (countAttempt) q.attempts += 1;\n if (q.attempts >= this.opts.maxAttempts) this.countDropped(1);\n else keep.push(q);\n }\n this.queue = [...keep, ...this.queue];\n while (this.queue.length > this.opts.maxItems) this.dropOldest();\n }\n}\n\nlet beaconBuffer = new BeaconBuffer();\n\n/** The process-wide buffer every {@link emitBeacon} call feeds. */\nexport function getBeaconBuffer(): BeaconBuffer {\n return beaconBuffer;\n}\n\n/** Replace the process-wide buffer (tests; or custom limits at cold start). */\nexport function resetBeaconBuffer(options?: BeaconBufferOptions): BeaconBuffer {\n beaconBuffer = new BeaconBuffer(options);\n return beaconBuffer;\n}\n\n/**\n * Emit an unregistered-attempt beacon for `identified` (non-crypto depths)\n * and sampled `anonymous-bot` traffic: enqueue it, then give the shared\n * flush up to `budgetMs` (or hand the flush to `waitUntil` when the runtime\n * has one). Authenticated with `apiKey` when given; the backend\n * fingerprints the UA and find-or-provisions platform agents server-side.\n */\nexport async function emitBeacon(\n options: EdgeCoreOptions,\n req: NormalizedRequest,\n classification: Classification,\n budgetMs: number,\n queryValueAllowlist?: string[],\n apiKey?: string\n): Promise<void> {\n // VI uplift Parts 2/3 — stitching + attribution fields, all optional so\n // old backends simply ignore them.\n const attemptId = extractAttemptId(req);\n const declaredSource = normalizeDeclaredSource(headerValue(req, 'x-astra-source'));\n const userAgent = headerValue(req, 'user-agent');\n const item: BeaconItem = {\n ...(options.counterpartyId && { counterpartyId: options.counterpartyId }),\n ...(options.counterpartyUrl && { counterpartyUrl: options.counterpartyUrl }),\n counterpartyType: 'website',\n sourceIp: req.clientIp,\n userAgent,\n requestPath: req.uri,\n requestMethod: req.method,\n // Attempt-chain handle (header or ?astra_attempt= deep link) — joins\n // this beacon into the agent's research chain via pe_attempt_idx.\n ...(attemptId && { attemptId }),\n // First-class referer + accept: traffic-source and surface-classifier\n // inputs (previously buried inside observedMetadata.headers).\n referer: headerValue(req, 'referer'),\n accept: headerValue(req, 'accept'),\n ...(declaredSource && { declaredSource }),\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 unregistered\n // caller.\n observedMetadata: buildObservedMetadata(req, queryValueAllowlist),\n // Capture time — batched delivery skews createdAt by the flush delay.\n observedAt: new Date().toISOString(),\n };\n // Drop undefined values so the JSON matches the old body shape.\n for (const k of Object.keys(item)) if (item[k] === undefined) delete item[k];\n\n const buffer = getBeaconBuffer();\n buffer.enqueue(\n {\n apiBaseUrl: options.apiBaseUrl,\n ...(apiKey && { apiKey }),\n counterparty: options.counterpartyId || options.counterpartyUrl,\n ...(options.adapter && { adapter: options.adapter }),\n },\n item,\n // Repeat collapse needs a client identity; without an IP, distinct\n // callers sharing a UA would merge, so don't collapse.\n req.clientIp\n ? [\n options.counterpartyId || options.counterpartyUrl,\n req.clientIp,\n userAgent ?? '',\n req.method,\n req.uri,\n attemptId ?? '',\n ].join('\\u0000')\n : undefined\n );\n const flushing = buffer.flush();\n if (options.waitUntil) {\n options.waitUntil(flushing);\n return;\n }\n await withBudget(flushing, budgetMs);\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 * Anonymous-traffic beacon for the SDK middleware pass-through paths.\n *\n * When a request passes through UNGATED (no dashboard route matches it, or\n * the matching route is gated at `none`), no verify-access call happens and\n * the endpoint's dashboard is blind to that traffic. This module gives the\n * express/nextjs adapters the same lightweight visibility the edge adapters\n * already have: bot- and agent-shaped pass-through traffic emits a\n * fire-and-forget unregistered-attempt beacon, while human traffic and\n * static assets are never beaconed and credentialed agents are handled by\n * verify-access, not this beacon.\n *\n * Sampling is dashboard-driven: the endpoint's edge verification config\n * supplies `sampling.anonymousBeaconRate` (0 turns anonymous-bot sampling\n * off; platform-fingerprinted agents always beacon). Nothing here ever\n * waits on the request path — the beacon is never awaited, and the config\n * fetch runs in the background: until a config has arrived, no beacons are\n * sent. Merchants who must not emit any extra outbound calls can set\n * `anonymousBeacon: false` on the middleware options, which disables the\n * beacon (and its config fetch) entirely.\n */\n\nimport { _patterns } from '../edge-core/classify';\nimport { sampled } from '../edge-core/events';\nimport { getEdgeConfig, type EdgeConfig } from '../edge-config';\nimport { buildSdkObservedMetadata, sanitizeHeaders } from '../metadata-capture';\nimport { detectPlatformFingerprint } from '../platform-signatures';\nimport { extractCredentials, reportUnregisteredAttempt } from '../verify';\nimport type { GatewayConfig } from '../types';\n\n/** Raw (pre-sanitisation) header map as Node/Web adapters hold it. */\ntype RawHeaders = Record<string, string | string[] | undefined>;\n\nfunction readHeader(raw: RawHeaders, name: string): string | undefined {\n const value = raw[name];\n if (typeof value === 'string') return value;\n if (Array.isArray(value)) return value[0];\n return undefined;\n}\n\n/**\n * How a pass-through request should be treated by the anonymous beacon:\n * - `never` — humans, static assets, and credentialed agents: no beacon.\n * - `platform` — a platform-fingerprinted agent (Claude/ChatGPT/Gemini/…):\n * beacon every time (unsampled) — these are exactly the\n * agents the dashboard's platform attribution exists for.\n * - `anonymous-bot` — non-browser automation with no platform signal:\n * beacon at the dashboard-configured sampling rate.\n */\nexport interface PassThroughTrafficClass {\n kind: 'never' | 'platform' | 'anonymous-bot';\n /** Detection protocol persisted with the beacon event. */\n protocol?: string;\n /** Light detection detail persisted with the beacon event. */\n evidence?: Record<string, unknown>;\n}\n\n/**\n * Classify one pass-through request for the anonymous beacon. Reuses the\n * edge classifier's heuristics (static-asset extensions, platform\n * fingerprints, browser-vs-bot UA shape) so the SDK and edge tiers agree on\n * what counts as agent traffic.\n */\nexport function classifyPassThroughTraffic(\n path: string,\n rawHeaders: RawHeaders\n): PassThroughTrafficClass {\n // Static assets: the beacon (like the gateway) gets out of the way.\n if (_patterns.STATIC_EXTENSIONS.test(path)) return { kind: 'never' };\n\n // Credentialed traffic is not anonymous — when a gated route sees these\n // credentials, verify-access records the caller; an unregistered-attempt\n // beacon would misfile it.\n const credentials = extractCredentials(rawHeaders, {});\n if (credentials.astraId || credentials.apiKey || credentials.jwt) {\n return { kind: 'never' };\n }\n\n const userAgent = readHeader(rawHeaders, 'user-agent') ?? '';\n\n // Platform-agent fingerprint (UA, credential key format, or a\n // platform-signal header) — a stronger, less-spoofable signal than the\n // UA alone, and it fires before the browser-shape check because several\n // platform agents present Mozilla-prefixed UAs.\n const { apiKeyFormat, platformHeaders } = sanitizeHeaders(rawHeaders);\n const fingerprint = detectPlatformFingerprint({ userAgent, apiKeyFormat, platformHeaders });\n if (fingerprint) {\n return {\n kind: 'platform',\n protocol: 'platform-ua',\n evidence: { vendor: fingerprint.vendor, userAgent: userAgent || '(none)' },\n };\n }\n\n // 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 (\n !userAgent ||\n _patterns.BOT_UA_PATTERN.test(userAgent) ||\n !_patterns.BROWSER_UA_PATTERN.test(userAgent)\n ) {\n return {\n kind: 'anonymous-bot',\n protocol: 'ua-heuristic',\n evidence: { userAgent: userAgent || '(none)' },\n };\n }\n\n // Claims to be a browser but sends none of the headers every evergreen\n // browser sends — headless/spoofed automation.\n if (!readHeader(rawHeaders, 'sec-fetch-mode') && !readHeader(rawHeaders, 'accept-language')) {\n return {\n kind: 'anonymous-bot',\n protocol: 'ua-heuristic',\n evidence: { userAgent, spoofedBrowser: true },\n };\n }\n\n // Human traffic — never beaconed, never logged.\n return { kind: 'never' };\n}\n\n/** Per-request input the middleware hands the beacon on a pass-through. */\nexport interface AnonymousBeaconInput {\n requestPath: string;\n requestMethod: string;\n /** Origin the SDK is protecting (auto-detected by the adapters). */\n counterpartyUrl?: string;\n /** Client IP as the adapter resolves it; falls back to X-Forwarded-For. */\n sourceIp?: string;\n rawHeaders: RawHeaders;\n}\n\n/** Fire-and-forget emitter — returns immediately, never throws. */\nexport type AnonymousBeaconEmitter = (input: AnonymousBeaconInput) => void;\n\n/**\n * Create the per-middleware-instance anonymous beacon.\n *\n * Requires a configured `counterpartyId` — sampling is a per-endpoint\n * dashboard setting and beacon events attribute to the endpoint; without\n * one, the returned emitter is a no-op.\n *\n * The emitter itself is synchronous: it classifies the request locally and\n * fire-and-forgets the report. The dashboard config is fetched in the\n * background (cached, stale-while-revalidate) and never awaited on the\n * request path; until the first config resolves, no beacons are emitted.\n */\nexport function createAnonymousBeacon(\n config: GatewayConfig,\n options?: {\n /** Counterparty type stamped on beacon events (adapter-specific default). */\n counterpartyType?: string;\n /** Injectable RNG for deterministic sampling in tests. */\n random?: () => number;\n }\n): AnonymousBeaconEmitter {\n const counterpartyId = config.counterpartyId;\n if (!counterpartyId) return () => {};\n\n const random = options?.random ?? Math.random;\n let edgeConfig: EdgeConfig | undefined;\n let refreshing = false;\n\n const refreshConfig = (): void => {\n if (refreshing) return;\n refreshing = true;\n getEdgeConfig(config, counterpartyId)\n .then((cfg) => {\n edgeConfig = cfg;\n })\n .catch(() => {})\n .finally(() => {\n refreshing = false;\n });\n };\n // Eager background fetch so early pass-through traffic already has a\n // sampling rate; requests arriving before it lands are simply not\n // beaconed (visibility is best-effort, latency is not negotiable).\n refreshConfig();\n\n return (input) => {\n try {\n // Keep the config fresh — getEdgeConfig serves its TTL cache and\n // revalidates in the background; this call is never awaited.\n refreshConfig();\n const cfg = edgeConfig;\n if (!cfg) return;\n\n const traffic = classifyPassThroughTraffic(input.requestPath, input.rawHeaders);\n if (traffic.kind === 'never') return;\n if (traffic.kind === 'anonymous-bot' && !sampled(cfg.sampling.anonymousBeaconRate, random)) {\n return;\n }\n\n const userAgent = readHeader(input.rawHeaders, 'user-agent');\n const xff = input.rawHeaders['x-forwarded-for'];\n const xffStr = Array.isArray(xff) ? xff.join(', ') : xff;\n const sourceIp = input.sourceIp ?? xffStr?.split(',')[0]?.trim();\n\n reportUnregisteredAttempt(config, {\n ...(input.counterpartyUrl && { counterpartyUrl: input.counterpartyUrl }),\n counterpartyType: options?.counterpartyType ?? config.counterpartyType ?? 'api',\n ...(sourceIp && { sourceIp }),\n ...(userAgent && { userAgent }),\n requestPath: input.requestPath,\n requestMethod: input.requestMethod,\n ...(traffic.protocol && { protocol: traffic.protocol }),\n ...(traffic.evidence && { evidence: traffic.evidence }),\n observedMetadata: buildSdkObservedMetadata(input.rawHeaders),\n }).catch(() => {});\n } catch {\n // The beacon must never break — or delay — the merchant's request.\n }\n };\n}\n","/**\n * AstraSync Universal Verification Gateway - Express Middleware\n *\n * Express.js middleware for verifying AI agents on API endpoints.\n *\n * @example\n * ```typescript\n * import express from 'express';\n * import { createMiddleware } from '@astrasyncai/verification-gateway/express';\n *\n * const app = express();\n *\n * app.use(createMiddleware({\n * apiBaseUrl: 'https://astrasync.ai/api',\n * apiKey: process.env.ASTRASYNC_API_KEY,\n * counterpartyId: 'ASTRAE-...', // your registered endpoint id\n * }));\n * ```\n *\n * Per-route policy (which paths are gated, trust floors, PDLSS purposes) is\n * configured in the AstraSync dashboard, not in code — the middleware\n * fetches it automatically on init and refreshes periodically. There is no\n * `routes` option; a `routes` key in the config object is ignored (with a\n * warning) since v2.9.7.\n */\n\nimport type { Request, Response, NextFunction, RequestHandler } from 'express';\nimport type {\n ExpressMiddlewareOptions,\n AgentCredentials,\n VerificationResult,\n EnhancedVerificationResult,\n RouteAccessConfig,\n AstraSyncCredentials,\n VerificationRequest,\n} from '../types';\nimport { awaitStepUpApproval } from './stepup-poll';\nimport {\n verify,\n extractCredentials,\n recordDecision,\n reportCounterpartyPreCheckFailure,\n fetchRoutes,\n} from '../verify';\nimport { extractHttpCredentials } from '../transport/http';\nimport { MCP_VERIFIED_HOP_HEADER, parseVerifiedHop, isVerifiedHopValidFor } from '../verified-hop';\nimport { resolveHttpPdlss, type HttpPdlssResolution } from './http-pdlss';\nimport { requiresHumanApproval, annotateApprovalRequired } from './approval-gate';\nimport { performCounterpartyPreCheck } from '../pdlss-pre-check';\nimport { prefetchWellKnown, getWellKnownUrls } from '../well-known';\nimport { buildSdkObservedMetadata } from '../metadata-capture';\nimport { createAnonymousBeacon } from './anonymous-beacon';\nimport {\n VERIFICATION_STATUS_HEADER,\n buildVerificationUnavailableBody,\n denyStatusFor,\n isAnonymousRead,\n isVerificationUnavailable,\n unavailableRetryAfterSeconds,\n} from '../failure-posture';\n\n/**\n * Extend Express Request with verification result\n */\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace Express {\n interface Request {\n agentVerification?: VerificationResult;\n }\n }\n}\n\n/**\n * Default credential extractor\n */\nfunction defaultExtractCredentials(req: Request): AgentCredentials {\n return extractCredentials(\n req.headers as Record<string, string | string[] | undefined>,\n req.query as Record<string, string | undefined>\n );\n}\n\n/**\n * Extract extended AstraSync credentials (X-Astra-* headers) from Express request.\n * Returns null if no AstraSync headers are present.\n */\nexport function extractAstraSyncCredentials(req: Request): AstraSyncCredentials | null {\n return extractHttpCredentials(req.headers as Record<string, string | string[] | undefined>);\n}\n\n/** Read a possibly-array header value as a single string. */\nfunction headerValue(value: string | string[] | undefined): string | undefined {\n if (typeof value === 'string') return value;\n if (Array.isArray(value)) return value[0];\n return undefined;\n}\n\n/**\n * Resolve the canonical {purpose, action} pair for a request.\n * Replaces the gen-1 `defaultExtractPurpose` method-inference (`read_data`/\n * `write_data`) and the hardwired `action: req.method.toUpperCase()` — the\n * transport verb never travels as a PDLSS action. Full precedence chains\n * live in http-pdlss.ts.\n */\nfunction resolveRequestPdlss(\n req: Request,\n routeConfig: { purpose?: string; action?: string } | null,\n customExtractPurpose: ((req: Request) => string | undefined) | undefined,\n customExtractAction: ((req: Request) => string | undefined) | undefined\n): HttpPdlssResolution {\n return resolveHttpPdlss({\n method: req.method,\n astraPurpose: headerValue(req.headers['x-astra-purpose']),\n astraAction: headerValue(req.headers['x-astra-action']),\n legacyPurpose: headerValue(req.headers['x-purpose'] ?? req.headers['X-Purpose']),\n queryPurpose: typeof req.query.purpose === 'string' ? req.query.purpose : undefined,\n routePurpose: routeConfig?.purpose,\n routeAction: routeConfig?.action,\n hasCustomPurposeExtractor: !!customExtractPurpose,\n customPurpose: customExtractPurpose?.(req),\n hasCustomActionExtractor: !!customExtractAction,\n customAction: customExtractAction?.(req),\n });\n}\n\n/**\n * Match a route pattern against a path.\n *\n * Historically the SDK's\n * matchRoute was case-sensitive while Express's default `case sensitive\n * routing` is FALSE. A customer policy `/api/admin/*` did NOT match\n * `/api/ADMIN/users` → SDK returned `no-match` → request passed ungated →\n * Express routed it to the admin handler. The case-insensitive codepath\n * below closes the bypass.\n *\n * Ships in SHADOW MODE in SDK 2.4.13: by default the case-sensitive\n * regex is still authoritative; the case-insensitive variant is\n * computed in parallel and logged when results diverge. Follow-up\n * release flips the default to case-insensitive after 1-week\n * observation. Customers can flip early by setting\n * `caseInsensitiveRouteMatch: true` on the middleware options.\n */\nfunction matchRoute(\n pattern: string,\n path: string,\n opts?: { caseInsensitive?: boolean; correlationId?: string; logShadowDivergence?: boolean }\n): boolean {\n // Convert pattern to regex\n const regexPattern = pattern.replace(/\\*/g, '.*').replace(/\\//g, '\\\\/');\n\n const caseSensitiveRegex = new RegExp(`^${regexPattern}$`);\n const caseSensitiveResult = caseSensitiveRegex.test(path);\n\n if (!opts?.caseInsensitive && !opts?.logShadowDivergence) {\n return caseSensitiveResult;\n }\n\n const caseInsensitiveRegex = new RegExp(`^${regexPattern}$`, 'i');\n const caseInsensitiveResult = caseInsensitiveRegex.test(path);\n\n // Shadow logging: emit only when results diverge so operators can grep\n // their own logs for the bypass class without log volume spam.\n if (opts?.logShadowDivergence && caseSensitiveResult !== caseInsensitiveResult) {\n // eslint-disable-next-line no-console\n console.warn(\n `[SHADOW] matchRoute case-insensitive would change result: pattern=${pattern} path=${path} ` +\n `caseSensitive=${caseSensitiveResult} caseInsensitive=${caseInsensitiveResult} correlationId=${opts.correlationId ?? 'unknown'}`\n );\n }\n\n return opts?.caseInsensitive ? caseInsensitiveResult : caseSensitiveResult;\n}\n\n/**\n * Find the route configuration for a request\n */\nfunction findRouteConfig(\n routes: RouteAccessConfig[],\n path: string,\n method: string,\n opts?: { caseInsensitive?: boolean; correlationId?: string; logShadowDivergence?: boolean }\n): RouteAccessConfig | undefined {\n return routes.find((route) => {\n const methodMatches =\n route.method === '*' || route.method.toUpperCase() === method.toUpperCase();\n const pathMatches = matchRoute(route.pattern, path, opts);\n return methodMatches && pathMatches;\n });\n}\n\n/**\n * Default denied handler\n *\n * The response body carries the full `failures[]`\n * array and the `correlationId` so partners can render per-dimension UX\n * and tie a denial back to a server log line. Previously the merchant only\n * got the first denialReason — meaningful detail was thrown away before\n * the response left the SDK. Also stamps `X-Astra-Gateway-Mode: enforced`\n * so partners can tell a gate-evaluated denial apart from a gate-skipped\n * pass-through (the `unenforced` complement).\n */\nfunction dedupeFailures(result: VerificationResult): void {\n if (result.failures && result.failures.length > 1) {\n const seen = new Set<string>();\n result.failures = result.failures.filter((f) => {\n const key = `${f.dimension}|${f.message}|${(f as { guidance?: string }).guidance ?? ''}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n }\n if (result.denialReasons && result.denialReasons.length > 1) {\n result.denialReasons = [...new Set(result.denialReasons)];\n }\n}\n\nfunction defaultOnDenied(result: VerificationResult, _req: Request, res: Response): void {\n // 4.0.0 BREAKING: when this integration's OWN API key was rejected by the\n // backend (misconfigured marker), the inbound agent did nothing wrong and\n // re-authenticating won't help — a 401 both blames the agent and invites\n // re-auth loops. Answer 503: this site's verification layer is down, by\n // the operator's own configuration. No Retry-After — retrying is futile\n // until the operator rotates the key.\n if (result.misconfigured) {\n res.setHeader('X-Astra-Gateway-Mode', 'enforced');\n res.status(503).json({\n success: false,\n error: {\n code: 'MERCHANT_VERIFICATION_MISCONFIGURED',\n message: result.denialReasons?.[0] || \"This site's AstraSync integration is misconfigured\",\n guidance: result.guidance,\n failures: result.failures,\n correlationId: result.correlationId,\n },\n });\n return;\n }\n\n // 5.12.0: verification infrastructure unavailable (timeout / 5xx / the\n // platform's 429) on an enforced route → 503 + Retry-After, edge parity.\n // Never 401: the agent's identity was never evaluated. (Observe routes and\n // anonymous reads never reach here — the gate passes them through.)\n if (isVerificationUnavailable(result)) {\n res.setHeader('X-Astra-Gateway-Mode', 'enforced');\n res.setHeader(VERIFICATION_STATUS_HEADER, 'unavailable');\n res.setHeader('Retry-After', String(unavailableRetryAfterSeconds(result)));\n res.status(503).json(buildVerificationUnavailableBody(result));\n return;\n }\n\n // Round-18 G4: identity-verification failures → 401 (re-authenticate);\n // identity-verified-but-policy-denied → 403 (re-auth won't help; update\n // PDLSS scope or escalate to step-up). Maps to the two distinct recovery\n // actions that HTTP middleware acts on without parsing bodies. The\n // impossible state `!identityVerified && policyAllowed` falls into the\n // `!identityVerified` branch — identity is the more-fundamental missing\n // precondition. 5.12.0: a PRESENTED id that is malformed or unknown is a\n // 403 AGENT_IDENTITY_REJECTED with registration guidance — 401 is reserved\n // for missing credentials (re-presenting the same id cannot help).\n const { status: statusCode, code } = denyStatusFor(result, 'INSUFFICIENT_ACCESS');\n\n res.setHeader('X-Astra-Gateway-Mode', 'enforced');\n\n res.status(statusCode).json({\n success: false,\n error: {\n code,\n message: result.denialReasons?.[0] || 'Access denied',\n guidance: result.guidance,\n // Round-10: aggregated per-dimension detail + correlation handle.\n failures: result.failures,\n correlationId: result.correlationId,\n stepUpApproval: result.stepUpApproval,\n // 3.6.0: terminal outcome of an opt-in hold-and-poll wait (denied /\n // expired / consumed / timeout). Absent when the feature is off.\n ...(result.stepUpOutcome && { stepUpOutcome: result.stepUpOutcome }),\n },\n });\n}\n\n/**\n * Refresh interval for the remote-fetched route policy. Default: every 5\n * minutes. Override via `routesRefreshMs` on the middleware options. Each\n * middleware instance keeps its own cache; multiple instances pointing at the\n * same endpoint will each fetch independently.\n */\nconst DEFAULT_ROUTES_REFRESH_MS = 5 * 60 * 1000;\n\n/**\n * Create Express middleware for agent verification.\n *\n * v2.9.7 moved per-route policy authority out of merchant-side source code\n * into the AstraSync dashboard. `createMiddleware` no longer accepts a\n * `routes` array — it fetches the endpoint's stored policy via\n * `GET /endpoints/:counterpartyId/routes` on init and refreshes\n * periodically. Policy edits in the dashboard take effect on the next\n * refresh (or sooner if the operator manually restarts the SDK).\n *\n * `counterpartyId` is required: the SDK can't know which endpoint's policy\n * to fetch without it. Local-development workflows that don't have an\n * AstraSync endpoint registered can omit it — the middleware logs a\n * one-time warning and falls through (allows all) until a policy is\n * fetchable.\n */\nexport function createMiddleware(options: ExpressMiddlewareOptions): RequestHandler {\n // Guard against configs authored for pre-2.9.7 SDKs: a `routes` array in\n // merchant source is silently dead config (the type contract rejects it at\n // literal call sites, but variable-typed configs slip through) — and dead\n // route config means the author believes paths are gated that aren't.\n if ('routes' in options) {\n // eslint-disable-next-line no-console\n console.warn(\n '[VerificationGateway] `routes` is dashboard-managed since v2.9.7; this option is ignored — ' +\n 'configure route policy in your AstraSync dashboard.'\n );\n }\n const {\n extractCredentials: customExtractCredentials,\n extractPurpose: customExtractPurpose,\n extractAction: customExtractAction,\n skipPaths = [],\n onDenied = defaultOnDenied,\n recordDecisions,\n enableRuntimeChallenge = true,\n routesRefreshMs = DEFAULT_ROUTES_REFRESH_MS,\n failOnError = 'open',\n caseInsensitiveRouteMatch = false,\n anonymousBeacon = true,\n trustVerifiedHop = false,\n verifiedHopMaxAgeMs,\n ...config\n } = options;\n\n // v2.5.0: fire-and-forget pre-fetch of well-known URLs\n if (config.apiBaseUrl) {\n prefetchWellKnown(config.apiBaseUrl).catch(() => {});\n }\n\n // Dashboard-driven anonymous-traffic beacon for the pass-through paths\n // (no matching route / route gated at `none`). Fire-and-forget: never\n // awaited, never delays next(). See ./anonymous-beacon.ts.\n const emitAnonymousBeacon = anonymousBeacon\n ? createAnonymousBeacon(config, { counterpartyType: config.counterpartyType ?? 'api' })\n : undefined;\n const beaconPassThrough = emitAnonymousBeacon\n ? (req: Request): void => {\n const xff = req.headers['x-forwarded-for'];\n const xffStr = Array.isArray(xff) ? xff.join(', ') : xff;\n emitAnonymousBeacon({\n requestPath: req.path,\n requestMethod: req.method,\n counterpartyUrl: config.counterpartyUrl || `${req.protocol}://${req.get('host')}`,\n sourceIp: req.ip ?? (xffStr ? xffStr.split(',')[0].trim() : undefined),\n rawHeaders: req.headers as Record<string, string | string[] | undefined>,\n });\n }\n : undefined;\n\n // Per-middleware-instance route cache. Populated on first fetch; refreshed\n // every `routesRefreshMs`. Until first successful fetch we hold an empty\n // array which means \"no per-route gating active\" — the middleware falls\n // through. Pre-fix the array came from merchant source, which both broke\n // the auth-boundary story (defect 24) and silently disagreed with the\n // dashboard.\n let cachedRoutes: RouteAccessConfig[] = [];\n let lastFetchAt = 0;\n let refreshing: Promise<void> | null = null;\n let warnedNoCounterparty = false;\n let warnedEmptyRoutes = false;\n\n async function refreshRoutes(): Promise<void> {\n if (!config.counterpartyId) {\n if (!warnedNoCounterparty) {\n // eslint-disable-next-line no-console\n console.warn(\n '[VerificationGateway] No counterpartyId configured — falling through (allow all). ' +\n 'Per-route policy lives in the AstraSync dashboard now; register the endpoint and ' +\n 'set counterpartyId in your middleware config to enforce policy.'\n );\n warnedNoCounterparty = true;\n }\n return;\n }\n const fetched = await fetchRoutes(config, config.counterpartyId);\n if (fetched) {\n cachedRoutes = fetched;\n lastFetchAt = Date.now();\n // v2.3.8 (defect #25): if the fetch succeeded but returned an empty\n // policy, the endpoint is registered correctly but the operator hasn't\n // configured any routes yet — every request will fall through ungated.\n // Surface this loudly once so silent pass-through can't go unnoticed.\n if (cachedRoutes.length === 0 && !warnedEmptyRoutes) {\n // Audit F-PROBE-01: app.astrasync.ai doesn't resolve in DNS today;\n // dashboard actually lives at astrasync.ai/dashboard. Use that as\n // the fallback. If DevOps provisions app.astrasync.ai later, the\n // dashboardUrl config option lets merchants override.\n const dashboard = config.dashboardUrl ?? 'https://astrasync.ai/dashboard';\n // eslint-disable-next-line no-console\n console.warn(\n `[VerificationGateway] No route policy configured for ${config.counterpartyId}. ` +\n `Gateway is in pass-through mode for ALL traffic until you add at least one route. ` +\n `Configure at ${dashboard}/dashboard/endpoints/${config.counterpartyId}/routes`\n );\n warnedEmptyRoutes = true;\n }\n }\n }\n\n // Eager first fetch so the first request after init has policy loaded.\n // Errors are swallowed (handled by fetchRoutes returning null).\n refreshing = refreshRoutes().finally(() => {\n refreshing = null;\n });\n\n return async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n // Check if path should be skipped\n const shouldSkip = skipPaths.some((pattern) => matchRoute(pattern, req.path));\n if (shouldSkip) {\n return next();\n }\n\n // Wait for in-flight init fetch (only on the very first request) so we\n // don't admit traffic with no policy loaded.\n if (refreshing) {\n await refreshing.catch(() => {});\n }\n // Time-based refresh: kick off a background refresh if the cache is\n // stale. Doesn't block the current request — readers see whatever is\n // cached at this moment; the next request will see the refreshed copy.\n if (config.counterpartyId && Date.now() - lastFetchAt > routesRefreshMs) {\n refreshing = refreshRoutes().finally(() => {\n refreshing = null;\n });\n }\n\n // Find route configuration\n // Audit F-A6-31 shadow-mode wiring: pass caseInsensitive flag (default\n // false in 2.4.13) + always log divergences so merchants can grep for\n // would-have-matched results during the 1-week observation window.\n const correlationId =\n (req.headers['x-request-id'] as string | undefined) ||\n (req.headers['x-correlation-id'] as string | undefined);\n const routeConfig = findRouteConfig(cachedRoutes, req.path, req.method, {\n caseInsensitive: caseInsensitiveRouteMatch,\n logShadowDivergence: true,\n correlationId,\n });\n\n // If no route config, skip verification (allow through)\n if (!routeConfig) {\n if (config.setPassThroughHeader) {\n // Round-10 (#49, O10): `unenforced` replaces the previous\n // `pass-through` label. The previous name conflated \"gateway\n // didn't evaluate policy\" with \"request succeeded end-to-end\" —\n // the downstream handler may still return any status. The new\n // semantic describes the GATE state only.\n res.setHeader('X-Astra-Gateway-Mode', 'unenforced');\n res.setHeader(\n 'X-Astra-Gateway-Reason',\n cachedRoutes.length === 0 ? 'no-policy' : 'no-match'\n );\n }\n // Anonymous-traffic beacon: this request never reaches verify-access,\n // so bot/agent-shaped callers would otherwise be invisible to the\n // dashboard. Fire-and-forget — does not delay next().\n beaconPassThrough?.(req);\n return next();\n }\n\n // v2.5.0: resolve well-known URLs (cached; prefetched at middleware creation)\n const wellKnownUrls = config.apiBaseUrl\n ? await getWellKnownUrls(config.apiBaseUrl).catch(() => undefined)\n : undefined;\n\n // Extract credentials (hoisted from below the route-none check so the\n // round-12 F9 evaluateAlwaysIfCredentialed flag can decide whether to\n // evaluate vs short-circuit).\n const credentials = customExtractCredentials\n ? customExtractCredentials(req)\n : defaultExtractCredentials(req);\n\n // Round-12 (F9): route-none short-circuit unless the caller wants\n // evaluation-without-enforcement. With evaluateAlwaysIfCredentialed\n // set to true AND credentials present, the middleware calls\n // verify-access for audit + req.agentVerification population, then\n // proceeds without gating. Default behaviour (flag off) preserves\n // pre-F9 short-circuit semantics.\n const shouldEnforce = !routeConfig.observe;\n if (routeConfig.observe && (!config.evaluateAlwaysIfCredentialed || !credentials.astraId)) {\n if (config.setPassThroughHeader) {\n res.setHeader('X-Astra-Gateway-Mode', 'unenforced');\n res.setHeader('X-Astra-Gateway-Reason', 'route-observe');\n }\n // Anonymous-traffic beacon (see the no-route-match branch above).\n beaconPassThrough?.(req);\n return next();\n }\n\n // Inner-hop dedupe: a trusted upstream AstraSync hop (edge gateway or\n // MCP outer hop) already verified this exact ASTRA-id moments ago —\n // accept the fresh marker and skip the duplicate verify-access call.\n // Mirrors the MCP adapter contract: no req.agentVerification on a\n // hop-skip. The marker must match the request's own X-Astra-Id.\n if (trustVerifiedHop && credentials.astraId) {\n const hopRaw = req.headers[MCP_VERIFIED_HOP_HEADER.toLowerCase()];\n const hopValue =\n typeof hopRaw === 'string' ? hopRaw : Array.isArray(hopRaw) ? hopRaw[0] : undefined;\n const marker = parseVerifiedHop(hopValue);\n if (\n isVerifiedHopValidFor(marker, credentials.astraId, {\n ...(verifiedHopMaxAgeMs !== undefined ? { maxAgeMs: verifiedHopMaxAgeMs } : {}),\n })\n ) {\n return next();\n }\n }\n\n // v2.3.0: anonymous traffic no longer short-circuits client-side.\n // The server applies the endpoint's `unverifiedAgentPolicy` (deny /\n // allow_partial / allow_full) and emits the verification event +\n // blockchain record per the canonical flow. SDK forwards verbatim.\n\n // Resolve the canonical {purpose, action} pair (Bug 14, §4.6): dashboard\n // route mapping → custom extractors → agent X-Astra-* headers →\n // method-table fallback. The transport verb never travels as the action.\n const pdlssPair = resolveRequestPdlss(\n req,\n routeConfig,\n customExtractPurpose,\n customExtractAction\n );\n const purpose = pdlssPair.purpose;\n if (config.debug) {\n // Same telemetry shape as the MCP adapter — adoption tracking and\n // support triage read the *_source fields to see which integration\n // path each partner uses (route mapping vs headers vs fallback).\n // eslint-disable-next-line no-console\n console.debug('[express-middleware] pdlss resolved', {\n purpose_source: pdlssPair.purposeSource,\n resolved_purpose: pdlssPair.purpose,\n action_source: pdlssPair.actionSource,\n resolved_action: pdlssPair.action,\n });\n }\n\n // Extract full AstraSync credentials (includes PDLSS from X-Astra-* headers)\n const astraCreds = extractAstraSyncCredentials(req);\n\n // Auto-detect counterparty URL from the request if not explicitly configured.\n // Since the SDK is installed at this endpoint, we always know the origin.\n const counterpartyUrl = config.counterpartyUrl || `${req.protocol}://${req.get('host')}`;\n\n // Step 2: Counterparty-side PDLSS pre-check — compare agent's requested PDLSS\n // against counterparty-defined maximums on the route config.\n // Rejects immediately if outside limits, BEFORE calling verify-access.\n const preCheckFailures = performCounterpartyPreCheck(routeConfig, astraCreds, purpose);\n if (preCheckFailures.length > 0) {\n // Round-18 G4: counterparty pre-check failure — request rejected\n // before reaching verify-access. Neither identity nor policy was\n // remotely verified; both axes truthfully false.\n const result: VerificationResult = {\n identityVerified: false,\n policyAllowed: false,\n denialReasons: preCheckFailures.map((f) => f.message),\n guidance: {\n message: 'Request exceeds counterparty-defined PDLSS limits.',\n registrationUrl: wellKnownUrls?.registrationUrl ?? '',\n documentationUrl: wellKnownUrls?.documentationUrl ?? '',\n },\n verifiedAt: new Date(),\n };\n\n req.agentVerification = result;\n\n // Fire-and-forget: notify AstraSync of the pre-check failure\n reportCounterpartyPreCheckFailure(config, {\n agentId: astraCreds?.agentId || credentials.astraId || 'unknown',\n counterpartyUrl,\n counterpartyType: config.counterpartyType || 'api',\n failures: preCheckFailures,\n requestPath: req.path,\n requestMethod: req.method,\n }).catch(() => {});\n\n dedupeFailures(result);\n onDenied(result, req, res);\n return;\n }\n\n // Step 3: Call AstraSync verify-access with runtime challenge enabled\n const shouldRecordDecisions = recordDecisions !== false;\n const forwardedFor = req.headers['x-forwarded-for'];\n const forwardedForStr = Array.isArray(forwardedFor) ? forwardedFor.join(', ') : forwardedFor;\n // Audit F-A6-34: previously the LEFTMOST X-Forwarded-For entry was\n // taken as the original client IP. That value is attacker-controlled\n // whenever the customer's reverse proxy doesn't strip\n // client-supplied X-Forwarded-For — an attacker prepends\n // `X-Forwarded-For: 1.1.1.1` and we audit the spoofed IP. Now we\n // prefer req.ip (which Express resolves via configured `trust proxy`\n // hop count — the customer's responsibility to set correctly per\n // their actual hop chain). XFF still provides a fallback for\n // customers without `trust proxy` configured, but emits a one-time\n // warning when used so they know to fix.\n const originalClientIp =\n req.ip ?? (forwardedForStr ? forwardedForStr.split(',')[0].trim() : undefined);\n if (!req.ip && forwardedForStr) {\n // eslint-disable-next-line no-console\n console.warn(\n '[VerificationGateway] req.ip unset — falling back to leftmost X-Forwarded-For. ' +\n 'Configure Express trust proxy correctly to avoid spoofable client IPs in audit logs.'\n );\n }\n const agentCardUrl =\n typeof req.headers['x-astrasync-agent-card'] === 'string'\n ? (req.headers['x-astrasync-agent-card'] as string)\n : undefined;\n\n // P1 (SDK 3.5.0): when extractTransactionValue is configured, include\n // the value in verify-access so PDLSS limit evaluation runs at\n // middleware time. Must return major units (dollars, not cents).\n let txValue: number | undefined;\n let txCurrency: string | undefined;\n if (config.extractTransactionValue) {\n try {\n const extracted = config.extractTransactionValue(req);\n if (extracted) {\n txValue = extracted.value;\n txCurrency = extracted.currency;\n }\n } catch (e) {\n if (config.debug) {\n // eslint-disable-next-line no-console\n console.warn('[VerificationGateway] extractTransactionValue threw:', e);\n }\n }\n }\n\n // 5.8.0 attempt-chain (X-Astra-Attempt-Id): the bridge stamps the\n // interaction-chain id on every venue call (the edge pipeline already\n // reads it). Threading it into verify-access makes this hop part of the\n // SAME chain server-side, so a step-up the human already approved for\n // the chain passes here instead of minting a second approval — the\n // two-hop approval-loop fix. Invalid values are dropped, never sent.\n const attemptHeader = req.headers['x-astra-attempt-id'];\n const inboundAttemptId =\n typeof attemptHeader === 'string' && /^att_[0-9a-f]{32}$/.test(attemptHeader)\n ? attemptHeader\n : undefined;\n\n const verificationRequest: VerificationRequest = {\n credentials,\n purpose,\n action: pdlssPair.action,\n resource: req.path,\n createSession: shouldRecordDecisions,\n counterpartyUrl,\n counterpartyType: config.counterpartyType || 'api',\n enableRuntimeChallenge,\n durationRequired: astraCreds?.pdlss?.duration?.maxSessionDuration,\n ...(txValue !== undefined && { transactionValue: txValue }),\n ...(txCurrency && { currency: txCurrency }),\n ...(inboundAttemptId && { attemptId: inboundAttemptId }),\n callerMetadata: {\n sourceIp: originalClientIp,\n userAgent: req.headers['user-agent'] as string | undefined,\n referer: req.headers.referer as string | undefined,\n host: req.headers.host as string | undefined,\n forwardedFor: forwardedForStr,\n agentCardUrl,\n // Workstream D — capture EVERY inbound header (SDK-only merchants\n // have no edge to do it upstream) plus the CDN-derived connection\n // block. Local string work, secrets stripped; out of the verify\n // cache key so it doesn't defeat caching.\n observedMetadata: buildSdkObservedMetadata(req.headers),\n },\n };\n let result = await verify(config, verificationRequest);\n\n // Attach result to request\n req.agentVerification = result;\n let sessionId = (result as EnhancedVerificationResult).sessionId;\n\n // 3.6.0 hold-and-poll (opt-in via stepUpMaxWaitMs): HOLD a step-up\n // outcome, poll the approval, and on 'approved' re-verify the same\n // request once (cache-bypassed — the retry must reach the backend to\n // redeem the single-use approval). Every non-approved outcome falls\n // through to the existing fail-closed branches below with\n // result.stepUpOutcome stamped for the deny body.\n if (\n config.stepUpMaxWaitMs !== undefined &&\n result.policyAllowed &&\n requiresHumanApproval(result) &&\n result.stepUpApproval?.pollUrl\n ) {\n const outcome = await awaitStepUpApproval(config, result.stepUpApproval);\n res.setHeader('X-Astra-Step-Up', outcome);\n if (outcome === 'approved') {\n result = await verify(config, verificationRequest, { bypassCache: true });\n req.agentVerification = result;\n sessionId = (result as EnhancedVerificationResult).sessionId;\n } else {\n result.stepUpOutcome = outcome;\n }\n }\n\n // Denied verifications short-circuit here: failing either identity OR\n // policy already means \"deny.\" We check that first.\n // 4.5.0 (probe F1 follow-through): the gate is the SERVER's decision —\n // `policyAllowed` is true exactly when the backend allowed the call\n // (every deny/guidance/api-error shape sets it false), so gating on it\n // alone preserves the endpoint policy verbatim. `identityVerified` no\n // longer gates here: anonymous callers granted by an\n // audit/allow_partial/allow_full endpoint policy are honestly\n // identity-unverified yet server-allowed, and re-deriving a deny from\n // identity would override the backend evaluator (the SDK-pre-check\n // asymmetry antipattern). Identity still picks 401-vs-403 in the deny\n // body builder.\n // 5.12.0: fail posture follows success posture (edge-core parity). A\n // transient verification outage on an observe route, or on an\n // anonymous read (GET/HEAD, no credentials), passes through stamped\n // `X-Astra-Verification: unavailable`; enforced routes fall to\n // onDenied, whose default renders 503 + Retry-After (never 401).\n if (\n !result.policyAllowed &&\n isVerificationUnavailable(result) &&\n (!shouldEnforce || isAnonymousRead(req.method, credentials))\n ) {\n res.setHeader(VERIFICATION_STATUS_HEADER, 'unavailable');\n return next();\n }\n\n // Round-12 (F9): evaluation-without-enforcement. When the route is\n // observe but we ran verify-access for audit, skip the gates and call\n // next() — the result is on req.agentVerification for the handler\n // to render tier-aware responses (e.g. anonymous vs verified\n // catalog view on the same path).\n // 5.12.0 (round-27.4 D5, MCP parity): runs BEFORE the deny and step-up\n // branches — an observe route passes through regardless of the server\n // decision, as RouteAccessConfig.observe and evaluateAlwaysIfCredentialed\n // document. It used to run after them, so a credentialed request on an\n // observe route was vetoed.\n if (!shouldEnforce) {\n if (config.setPassThroughHeader) {\n res.setHeader('X-Astra-Gateway-Mode', 'enforced');\n res.setHeader('X-Astra-Gateway-Reason', 'evaluated-not-enforced');\n }\n if (shouldRecordDecisions && sessionId) {\n recordDecision(config, sessionId, 'granted').catch(() => {});\n }\n return next();\n }\n\n if (!result.policyAllowed) {\n if (shouldRecordDecisions && sessionId) {\n recordDecision(config, sessionId, 'denied', result.denialReasons?.[0]).catch(() => {});\n }\n dedupeFailures(result);\n onDenied(result, req, res);\n return;\n }\n\n // F2 direct-path fail-closed: an \"allowed-but-escalate\" outcome\n // (step-up / requires-approval, policyAllowed:true) cannot be completed\n // autonomously. The backend creates a step-up approval record and returns\n // it on `result.stepUpApproval`; deny here — symmetric with the bridge —\n // and surface the polling info in the deny response body.\n if (requiresHumanApproval(result)) {\n annotateApprovalRequired(result);\n if (shouldRecordDecisions && sessionId) {\n recordDecision(config, sessionId, 'denied', result.denialReasons?.[0]).catch(() => {});\n }\n dedupeFailures(result);\n onDenied(result, req, res);\n return;\n }\n\n // The access decision is the server's (identityVerified / policyAllowed,\n // above) — resting on a verified ID + runtime challenge + PDLSS match +\n // trust score. The only client-side refinement is the per-route trust\n // floor below; there is no access-level band (removed in SDK 5.0.0).\n\n // Per-route trust tightening (only refinement that still gates).\n if (routeConfig.minTrustScore && result.agent) {\n if (result.agent.trustScore < routeConfig.minTrustScore) {\n // 3.2.0: qualitative — never embed the score or the threshold in an\n // agent-visible message (trust is a system-internal signal; exposing\n // the number is a gaming vector — post-3.1.0 feedback #2).\n const trustFailure = {\n dimension: 'endpoint.trust',\n message: 'Trust below the route requirement for this endpoint.',\n guidance:\n \"Trust is below this route's floor. Trust is not overridable — the agent either meets the endpoint's trust policy or it doesn't. Raise the agent's trust via real signals (KYD, blockchain registration, agent-card), or have the operator lower the route's minTrustScore.\",\n };\n result.failures = [...(result.failures ?? []), trustFailure];\n result.denialReasons = [trustFailure.message];\n if (!result.guidance && wellKnownUrls) {\n result.guidance = {\n message: trustFailure.message,\n registrationUrl: wellKnownUrls.registrationUrl,\n documentationUrl: wellKnownUrls.documentationUrl,\n };\n }\n if (shouldRecordDecisions && sessionId) {\n recordDecision(config, sessionId, 'denied', trustFailure.message).catch(() => {});\n }\n dedupeFailures(result);\n onDenied(result, req, res);\n return;\n }\n }\n\n // All checks passed — record grant decision\n if (shouldRecordDecisions && sessionId) {\n recordDecision(config, sessionId, 'granted').catch(() => {});\n }\n // v2.3.8 (defect #26): if the endpoint's `unverifiedAgentPolicy` is\n // `'audit'` (allow + soft-launch warning), the server returns the\n // header to relay. Lift it onto the merchant's response BEFORE\n // calling next() so downstream handlers and the eventual response\n // back to the agent both carry it.\n const enhancedResult = result as EnhancedVerificationResult;\n if (enhancedResult.warningHeader) {\n res.setHeader(enhancedResult.warningHeader.name, enhancedResult.warningHeader.value);\n }\n next();\n } catch (error) {\n // Audit F-A1-06: shadow-mode logging for fail-closed default migration.\n // Always log `[SHADOW] would-have-denied` so merchants can grep their\n // own application logs for would-have-been-denied impact during the\n // observation window. Actual deny/admit behavior controlled by\n // failOnError option (default 'open' for backward compatibility).\n const errorClass = error instanceof Error ? error.constructor.name : typeof error;\n const correlationId =\n (req.headers['x-request-id'] as string | undefined) ||\n (req.headers['x-correlation-id'] as string | undefined) ||\n `gen-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n // eslint-disable-next-line no-console\n console.error('[VerificationGateway] Middleware error:', error);\n // eslint-disable-next-line no-console\n console.warn(\n `[SHADOW] would-have-denied: errorClass=${errorClass} route=${req.method}:${req.path} merchantId=${config.counterpartyId ?? 'unknown'} correlationId=${correlationId}`\n );\n\n if (failOnError === 'closed') {\n // 5.12.0: an internal exception is a verification outage, not an\n // identity verdict — the agent was never evaluated. The\n // `middleware.internal_error` dimension is one of the failure-posture\n // UNAVAILABLE_DIMENSIONS, so the default onDenied answers 503 +\n // Retry-After + VERIFICATION_UNAVAILABLE (previously an\n // identity-shaped 401 UNAUTHORIZED with registration guidance).\n // Custom onDenied handlers can detect it via isVerificationUnavailable.\n const result: VerificationResult = {\n identityVerified: false,\n policyAllowed: false,\n denialReasons: [`Verification middleware internal error: ${errorClass}`],\n failures: [\n {\n dimension: 'middleware.internal_error',\n message: `Middleware threw ${errorClass} — failing closed`,\n },\n ],\n verifiedAt: new Date(),\n correlationId,\n };\n dedupeFailures(result);\n return onDenied(result, req, res);\n }\n\n next();\n }\n };\n}\n\n// `requireAccess` and `verifyOnly` were removed in v2.9.7. Both injected a\n// local `routes` array into the merchant's source code, which is the exact\n// dual-config attack vector defect 24 closed. Per-route policy now lives in\n// the AstraSync dashboard (gated by team.role admin auth + audit + alerts).\n// To tighten a route, set its `minTrustScore` (+ purpose/jurisdiction/value\n// gates) in the dashboard. For \"verify but don't block,\" set the route to\n// `observe` (or run the endpoint in an audit `unverifiedAgentPolicy`).\n"],"mappings":";AAkBO,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,cAA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AAE,EAAE,MAAM,GAAG,CAAC,CAAC;AAE1E,cAAQ,MAAM,2CAA2C,KAAK;AAE9D,cAAQ;AAAA,QACN,0CAA0C,UAAU,UAAU,IAAI,MAAM,IAAI,IAAI,IAAI,eAAe,OAAO,kBAAkB,SAAS,kBAAkB,aAAa;AAAA,MACtK;AAEA,UAAI,gBAAgB,UAAU;AAQ5B,cAAM,SAA6B;AAAA,UACjC,kBAAkB;AAAA,UAClB,eAAe;AAAA,UACf,eAAe,CAAC,2CAA2C,UAAU,EAAE;AAAA,UACvE,UAAU;AAAA,YACR;AAAA,cACE,WAAW;AAAA,cACX,SAAS,oBAAoB,UAAU;AAAA,YACzC;AAAA,UACF;AAAA,UACA,YAAY,oBAAI,KAAK;AAAA,UACrB;AAAA,QACF;AACA,uBAAe,MAAM;AACrB,eAAO,SAAS,QAAQ,KAAK,GAAG;AAAA,MAClC;AAEA,WAAK;AAAA,IACP;AAAA,EACF;AACF;","names":["has","result","cache","inflight","headerValue","result"]}
1
+ {"version":3,"sources":["../../src/version.ts","../../src/http.ts","../../src/adapters/stepup-poll.ts","../../src/trust-levels.ts","../../src/well-known.ts","../../src/failure-posture.ts","../../src/verify.ts","../../src/transport/http.ts","../../src/verified-hop.ts","../../src/adapters/http-pdlss.ts","../../src/adapters/approval-gate.ts","../../src/pdlss-pre-check.ts","../../src/metadata-capture.ts","../../src/edge-config.ts","../../src/platform-signatures.ts","../../src/edge-core/classify.ts","../../src/edge-core/events.ts","../../src/adapters/anonymous-beacon.ts","../../src/adapters/express.ts"],"sourcesContent":["/**\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.14.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 * Step-up hold-and-poll (3.6.0) — the synchronous half of the MFA-style gate,\n * mirroring the Java SDK's `awaitStepUpApproval` / `pollStepUpStatus`.\n *\n * A verify() that comes back step_up_required carries a `stepUpApproval`\n * handle: `{ approvalId, pollUrl, expiresAt }`. The adapter HOLDS the original\n * request, polls the approval status, and on 'approved' re-verifies the same\n * request once (cache-bypassed) so the backend redeems the single-use approval\n * and returns a grant. Any other terminal outcome falls into the adapter's\n * normal fail-closed deny path.\n *\n * The poll endpoint is deliberately unauthenticated (it sits above the\n * backend router's `authenticate` middleware): the unguessable UUIDv4\n * approvalId is the capability token, and the route is rate-limited\n * (60/min/IP). No Authorization header is sent.\n */\n\nimport { sdkFetch } from '../http';\nimport { GatewayConfig, StepUpApprovalInfo, StepUpApprovalStatus, StepUpOutcome } from '../types';\n\nconst DEFAULT_POLL_INTERVAL_MS = 3000;\nconst MIN_POLL_INTERVAL_MS = 250;\nconst FALLBACK_MAX_WAIT_MS = 5 * 60 * 1000;\nconst EXPIRY_GRACE_MS = 5000;\nconst POLL_REQUEST_TIMEOUT_MS = 10_000;\n\n/** Resolve the absolute poll URL. pollUrl is server-relative\n * (`/api/step-up-approvals/poll/:id`), so join it to apiBaseUrl minus its\n * `/api` suffix (the origin) — same idiom as well-known.ts. Absolute URLs\n * pass through untouched. */\nfunction resolvePollUrl(config: GatewayConfig, pollUrl: string): string {\n if (pollUrl.startsWith('http')) return pollUrl;\n const origin = (config.apiBaseUrl ?? '').replace(/\\/api\\/?$/, '');\n return origin + pollUrl;\n}\n\n/**\n * One GET of the approval's poll endpoint. Returns the status string, or\n * null on any error / non-2xx / unparsable body — the hold loop treats null\n * as transient and just polls again.\n */\nexport async function pollStepUpStatus(\n config: GatewayConfig,\n approval: StepUpApprovalInfo\n): Promise<StepUpApprovalStatus | null> {\n if (!approval.pollUrl) return null;\n try {\n const res = await sdkFetch(resolvePollUrl(config, approval.pollUrl), {\n method: 'GET',\n signal: AbortSignal.timeout(POLL_REQUEST_TIMEOUT_MS),\n });\n if (!res.ok) return null;\n const body = (await res.json()) as Record<string, unknown>;\n // Envelope shape: { success, data: { status, resolvedAt } } — a flat\n // `status` read hangs every hold (live-UAT catch). Envelope-first with a\n // flat fallback for forward compatibility, exactly like the Java SDK.\n const data = body?.data;\n const status =\n data && typeof data === 'object' ? (data as Record<string, unknown>).status : body?.status;\n return typeof status === 'string' ? (status as StepUpApprovalStatus) : null;\n } catch {\n return null; // transient poll failure — the loop just polls again\n }\n}\n\nfunction resolveDeadline(config: GatewayConfig, approval: StepUpApprovalInfo): number {\n const now = Date.now();\n const maxWait = config.stepUpMaxWaitMs ?? 0;\n if (maxWait > 0) return now + maxWait;\n // stepUpMaxWaitMs === 0: hold until the approval itself expires (+ a small\n // grace so an approval landing at the buzzer still resolves on the next\n // poll). Missing/unparsable expiresAt → fixed 5-min fallback (Java parity).\n if (approval.expiresAt) {\n const expiry = Date.parse(approval.expiresAt);\n if (!Number.isNaN(expiry)) return Math.max(now, expiry) + EXPIRY_GRACE_MS;\n }\n return now + FALLBACK_MAX_WAIT_MS;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Block until a pending step-up approval reaches a terminal state or the wait\n * budget runs out. Returns the terminal status, or 'timeout'.\n *\n * Unknown non-pending statuses (a future backend state) still terminate the\n * hold — they are returned as-is and land in the deny path, which is the safe\n * reading of \"not approved\".\n */\nexport async function awaitStepUpApproval(\n config: GatewayConfig,\n approval: StepUpApprovalInfo\n): Promise<StepUpOutcome> {\n const deadline = resolveDeadline(config, approval);\n const pollInterval = Math.max(\n MIN_POLL_INTERVAL_MS,\n config.stepUpPollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS\n );\n\n while (Date.now() < deadline) {\n const status = await pollStepUpStatus(config, approval);\n if (status && status !== 'pending') {\n return status as StepUpOutcome;\n }\n const remaining = deadline - Date.now();\n if (remaining <= 0) break;\n await sleep(Math.min(pollInterval, remaining));\n }\n return 'timeout';\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 * 5.12.0 — HTTP adapter failure posture, lifted from edge-core\n * (`pipeline.ts` isApiErrorResult/unavailableOutcome, `enforce.ts` 503 +\n * Retry-After + buildUnavailableBody) so the Express and Next.js adapters\n * and `quickVerify` answer an AstraSync outage the way the edge does.\n *\n * The 1 Oct load test: the platform rate-limited a merchant's verify-access\n * calls (429), the SDK mapped that to `UNAUTHORIZED` 401 and failed closed\n * — even for anonymous catalogue reads — so the merchant was down for 11\n * minutes. Fail posture follows success posture:\n *\n * - observe routes and anonymous reads (GET/HEAD, no credentials) pass\n * through, stamped `X-Astra-Verification: unavailable`;\n * - enforced routes answer 503 + `Retry-After` (the backend's value, else\n * 30s) + `VERIFICATION_UNAVAILABLE`. Never 401 — the caller's identity\n * was never evaluated.\n *\n * Identity status mapping (contract correction, not a break): credentials\n * missing → 401; a presented id that is malformed or unknown → 403 with\n * registration guidance (re-authenticating with the same id cannot help).\n */\nimport type { AgentCredentials, VerificationResult } from './types';\n\n/** Response header stamped on a fail-open pass-through during an outage. */\nexport const VERIFICATION_STATUS_HEADER = 'X-Astra-Verification';\n\n/** Default Retry-After (seconds) when the backend sent none — edge parity. */\nexport const DEFAULT_UNAVAILABLE_RETRY_AFTER_S = 30;\n\n/**\n * Failure dimensions for a presented-but-rejected agent identifier.\n * `agent.lookup` is the backend's 200-with-deny shape for a well-formed id\n * that matches no registered agent (round-27.4 D4 — the same verdict as the\n * 404 → `identity.unknown_agent` mapping, delivered on a different wire).\n */\nexport const REJECTED_IDENTITY_DIMENSIONS: ReadonlySet<string> = new Set([\n 'identity.invalid_agent_id',\n 'identity.unknown_agent',\n 'agent.lookup',\n]);\n\n/** Registration guidance for a presented id that matches no registered agent. */\nexport const UNKNOWN_AGENT_GUIDANCE =\n 'Register your agent with AstraSync (or, inside an MCP host, add the AstraSync MCP connector for keyless, human-approved registration), then present the canonical ASTRA-* id issued after owner approval.';\n\n/**\n * Failure dimensions that mean \"verification could not be evaluated\" rather\n * than \"the agent was denied\":\n * - `verify_access.api_error` — the SDK's typed, retryable fallback for an\n * AstraSync outage (timeout, 5xx, the platform's 429);\n * - `middleware.internal_error` — an adapter's own `failOnError: 'closed'`\n * catch path (an exception inside the gateway middleware). Failing closed\n * there is a 503, never an identity-shaped 401.\n */\nexport const UNAVAILABLE_DIMENSIONS: ReadonlySet<string> = new Set([\n 'verify_access.api_error',\n 'middleware.internal_error',\n]);\n\n/**\n * A verify() result that is the SDK's typed, retryable api_error fallback —\n * infrastructure unavailability (timeout, 5xx, 429), not a policy deny and\n * not the deterministic merchant misconfig — or an adapter's internal-error\n * fail-closed result.\n */\nexport function isVerificationUnavailable(result: VerificationResult): boolean {\n if (result.misconfigured) return false;\n return (result.failures ?? []).some((f) => UNAVAILABLE_DIMENSIONS.has(f.dimension));\n}\n\n/** Retry-After seconds to relay: the backend's value (≥1s), else 30. */\nexport function unavailableRetryAfterSeconds(result: VerificationResult): number {\n if (typeof result.retryAfterMs === 'number' && Number.isFinite(result.retryAfterMs)) {\n return Math.max(1, Math.ceil(result.retryAfterMs / 1000));\n }\n return DEFAULT_UNAVAILABLE_RETRY_AFTER_S;\n}\n\n/** An anonymous read: GET/HEAD carrying no agent credential. */\nexport function isAnonymousRead(\n method: string | undefined,\n credentials: AgentCredentials\n): boolean {\n const m = (method ?? '').toUpperCase();\n if (m !== 'GET' && m !== 'HEAD') return false;\n return !credentials.astraId && !credentials.jwt;\n}\n\n/** Machine-readable 503 body — same shape as edge-core's buildUnavailableBody. */\nexport function buildVerificationUnavailableBody(result: VerificationResult): {\n success: false;\n error: {\n code: 'VERIFICATION_UNAVAILABLE';\n message: string;\n retryable: true;\n retryAfterSeconds: number;\n failures?: VerificationResult['failures'];\n correlationId?: string;\n guidance: { message: string };\n };\n} {\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 after the Retry-After interval.',\n retryable: true,\n retryAfterSeconds: unavailableRetryAfterSeconds(result),\n ...(result.failures && { failures: result.failures }),\n ...(result.correlationId && { correlationId: result.correlationId }),\n guidance: {\n message:\n 'Retry the request after the Retry-After interval, with exponential backoff; the condition is transient.',\n },\n },\n };\n}\n\n/** True when the deny is about a presented-but-malformed/unknown agent id. */\nexport function isRejectedIdentityClaim(result: VerificationResult): boolean {\n return (result.failures ?? []).some((f) => REJECTED_IDENTITY_DIMENSIONS.has(f.dimension));\n}\n\n/**\n * HTTP status + code for an ordinary (non-outage, non-misconfig) deny:\n * missing identity → 401 UNAUTHORIZED; presented-but-rejected id → 403\n * AGENT_IDENTITY_REJECTED; identity fine but policy denied → 403 with the\n * adapter's policy code.\n */\nexport function denyStatusFor(\n result: VerificationResult,\n policyDeniedCode: string\n): { status: 401 | 403; code: string } {\n // Checked first: older backends stamp idVerified:true on the agent.lookup\n // (unknown id) deny, which would otherwise read as a policy deny.\n if (isRejectedIdentityClaim(result)) return { status: 403, code: 'AGENT_IDENTITY_REJECTED' };\n if (result.identityVerified) return { status: 403, code: policyDeniedCode };\n return { status: 401, code: 'UNAUTHORIZED' };\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';\nimport {\n REJECTED_IDENTITY_DIMENSIONS,\n UNKNOWN_AGENT_GUIDANCE,\n isVerificationUnavailable,\n unavailableRetryAfterSeconds,\n} from './failure-posture';\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 counterparty?: { id?: string; url?: 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 // 5.13.0: name the endpoint this SDK is installed on, so the backend\n // can say whether this key may verify for it (keys are bound to the\n // endpoint's owner — a key from another account is refused on every\n // request with COUNTERPARTY_KEY_MISMATCH).\n const q = counterparty?.id\n ? `?counterpartyId=${encodeURIComponent(counterparty.id)}`\n : counterparty?.url\n ? `?counterpartyUrl=${encodeURIComponent(counterparty.url)}`\n : '';\n const selfCheck = await sdkFetch(`${apiBaseUrl}/agents/verify-access/self-check${q}`, {\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 counterparty?: { found?: boolean; canVerify?: boolean; message?: string };\n };\n if (body.counterparty && body.counterparty.canVerify === false) {\n const message =\n `[VerificationGateway] the configured AstraSync API key cannot verify for this endpoint ` +\n `(${body.counterparty.message ?? 'endpoint not found or owned by another account'}). ` +\n `Every inbound agent will be turned away until the key or counterparty is corrected.`;\n if (strictInit) {\n throw new Error(`${message} (strictInit=true)`);\n }\n console.error(message);\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 /** 5.12.0: backend non-2xx status + Retry-After (api_error source). */\n httpStatus?: number;\n retryAfterMs?: number;\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, rotated, or belongs to another account). \" +\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 replacing',\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 ...(options.httpStatus !== undefined && { httpStatus: options.httpStatus }),\n ...(options.retryAfterMs !== undefined && { retryAfterMs: options.retryAfterMs }),\n correlationId: options.correlationId,\n attemptId: options.attemptId,\n verifiedAt: new Date(),\n };\n}\n\n/**\n * 5.12.0: parse a response body as JSON without throwing — a non-JSON body\n * (HTML error page, plain-text 429) yields `{}` so the status survives.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nasync function readJsonSafe(response: Response): Promise<any> {\n try {\n const parsed = await response.json();\n return parsed && typeof parsed === 'object' ? parsed : {};\n } catch {\n return {};\n }\n}\n\n/** 5.12.0: human guidance for a presented-but-malformed/unknown agent id deny. */\nfunction rejectedIdentityGuidance(\n failures: Array<{ dimension: string; message: string; guidance?: string }> | undefined\n): string | undefined {\n const f = failures?.find((x) => REJECTED_IDENTITY_DIMENSIONS.has(x.dimension));\n if (!f) return undefined;\n // The backend's agent.lookup guidance only says \"check the id format\";\n // an unknown id needs the registration path (404 parity).\n if (f.dimension === 'agent.lookup') {\n return `The presented agent identifier is not registered with AstraSync. ${UNKNOWN_AGENT_GUIDANCE}`;\n }\n return f.guidance ? `${f.message} ${f.guidance}` : f.message;\n}\n\n/** Upper bound on a relayed Retry-After (a hostile/buggy value can't park callers for hours). */\nconst MAX_RETRY_AFTER_MS = 15 * 60 * 1000;\n\n/**\n * 5.12.0: `Retry-After` (delta-seconds or HTTP-date) → milliseconds, or\n * undefined when absent/unparseable. Clamped to [0, 15 min].\n */\nexport function parseRetryAfterMs(response: {\n headers?: { get?(name: string): string | null };\n}): number | undefined {\n const raw = response.headers?.get?.('retry-after');\n if (!raw) return undefined;\n const trimmed = raw.trim();\n let ms: number;\n if (/^\\d+(\\.\\d+)?$/.test(trimmed)) {\n ms = Number(trimmed) * 1000;\n } else {\n const at = Date.parse(trimmed);\n if (Number.isNaN(at)) return undefined;\n ms = at - Date.now();\n }\n return Math.min(MAX_RETRY_AFTER_MS, Math.max(0, Math.round(ms)));\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_configured';\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 /** 5.12.0: backend HTTP status on a non-2xx (429/5xx) — see VerificationResult.httpStatus. */\n httpStatus?: number;\n /** 5.12.0: backend Retry-After in ms, when sent. */\n retryAfterMs?: number;\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 // 5.12.0: a non-JSON body (an HTML 502 from a load balancer, a plain-text\n // 429) used to throw here and lose the status; parse defensively.\n const data = await readJsonSafe(response);\n const retryAfterMs = parseRetryAfterMs(response);\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 // 5.10.0: a caller-supplied agent id that isn't a canonical ASTRA-id\n // (e.g. `ASTRA-bogus123`) is a deterministic failed identity claim, not\n // an outage. Previously it fell through to the transient api_error path,\n // so the edge answered 503 \"verification unavailable — retry\" under\n // enforce; it is now an identity deny (403 + registration guidance).\n if (response.status === 400 && data?.error === 'INVALID_AGENT_ID') {\n const message =\n typeof data?.message === 'string'\n ? data.message\n : 'Agent identifier must be a canonical ASTRA-* id.';\n return {\n success: true,\n attemptId: typeof data?.attemptId === 'string' ? data.attemptId : undefined,\n access: {\n allowed: false,\n reason: 'invalid_agent_id',\n failures: [\n {\n dimension: 'identity.invalid_agent_id',\n message,\n guidance:\n typeof data?.guidance === 'string'\n ? data.guidance\n : 'Present your canonical ASTRA-* id (discover it via GET /api/agents/request-registration/{requestId} after owner approval).',\n },\n ],\n },\n };\n }\n\n // 5.12.0: a presented agent id the backend doesn't know (404 \"Agent not\n // found\") is a deterministic failed identity claim — like the malformed\n // id above — not an outage. It used to fall through to api_error, so\n // merchants answered \"temporarily unavailable, retry\" to an agent that\n // simply isn't registered. A 404 without an agent id in the request (or\n // a non-JSON 404, i.e. a wrong apiBaseUrl) stays on the api_error path.\n if (\n response.status === 404 &&\n credentials.astraId &&\n (data?.error === 'AGENT_NOT_FOUND' ||\n (typeof data?.message === 'string' && /agent/i.test(data.message)))\n ) {\n return {\n success: true,\n attemptId: typeof data?.attemptId === 'string' ? data.attemptId : undefined,\n access: {\n allowed: false,\n reason: 'unknown_agent',\n failures: [\n {\n dimension: 'identity.unknown_agent',\n message: 'The presented agent identifier is not registered with AstraSync.',\n guidance: UNKNOWN_AGENT_GUIDANCE,\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 // 5.13.0: a 403 COUNTERPARTY_KEY_MISMATCH is the same class — this\n // integration's key belongs to an account that doesn't own the endpoint.\n const keyMismatch = response.status === 403 && data?.error === 'COUNTERPARTY_KEY_MISMATCH';\n if (response.status === 401 || keyMismatch) {\n return {\n success: false,\n error: data.message || data.error || 'Integration API key rejected',\n misconfig: true,\n misconfigCode: keyMismatch\n ? 'counterparty_key_mismatch'\n : typeof data?.code === 'string'\n ? data.code\n : 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 // 5.12.0: keep the status + Retry-After so adapters can relay the\n // platform's back-off (429 rate limit vs 5xx outage).\n return {\n success: false,\n error:\n (typeof data?.message === 'string' && data.message) ||\n (typeof data?.error === 'string' && data.error) ||\n `API returned ${response.status}`,\n correlationId: typeof data?.correlationId === 'string' ? data.correlationId : undefined,\n attemptId: typeof data?.attemptId === 'string' ? data.attemptId : undefined,\n httpStatus: response.status,\n ...(retryAfterMs !== undefined && { retryAfterMs }),\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 id: mergedConfig.counterpartyId,\n url: mergedConfig.counterpartyUrl ?? request.counterpartyUrl,\n }\n );\n } else {\n void performInitCheck(\n mergedConfig.apiBaseUrl,\n mergedConfig.debug,\n false,\n mergedConfig.apiKey,\n {\n id: mergedConfig.counterpartyId,\n url: mergedConfig.counterpartyUrl ?? request.counterpartyUrl,\n }\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 httpStatus: apiResponse.httpStatus,\n retryAfterMs: apiResponse.retryAfterMs,\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 // 5.12.0 (round-27.4 D4): a presented id that matches no registered\n // agent is never \"identity verified\", whatever an older backend stamped.\n const idVerifiedFromBackend =\n (apiResponse.verificationContext as { idVerified?: boolean } | undefined)?.idVerified ===\n true && !aggregatedFailures?.some((f) => REJECTED_IDENTITY_DIMENSIONS.has(f.dimension));\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 // 5.12.0: a presented-but-rejected id (malformed / unknown) carries\n // actionable registration guidance on its failure — surface it\n // instead of the bare machine reason ('unknown_agent').\n message:\n rejectedIdentityGuidance(aggregatedFailures) ??\n (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 blockchainAnchored: apiResponse.agent.blockchainStatus === 'anchored',\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' && result.identityVerified) {\n // The escalation signal rides on `requiresStepUp` / `stepUpApproval`, not\n // on any masquerade of the (now-removed) access band.\n //\n // 5.12.0 (round-27.4 D1): step-up is \"allowed-but-escalate\" — the\n // registered agent's OWNER approves a valued action. An unidentified\n // caller has no owner to escalate to, so an allowed response for one is\n // a grant: older backends labelled recognised-but-unregistered agents\n // (Claude-User, the AstraSync bridge) step_up_required on plain reads,\n // and the adapters 401'd an anonymous catalog GET as \"requires human\n // approval\". The backend no longer emits that; this keeps merchants on\n // 5.12.0 correct against an older backend too. Denies are untouched —\n // they take the !allowed branch above.\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 — never throws. 5.12.0: a 429/5xx is retried once\n * (Retry-After honoured, capped at 2s) off the caller's path; a lost report\n * is surfaced via `options.onFailure`.\n */\nexport async function reportAttempt(\n config: GatewayConfig,\n report: AttemptReport,\n options: ReportAttemptOptions = {}\n): 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 const url = `${apiBaseUrl}/agents/verify-access/attempt-report`;\n const init = { method: 'POST', headers, body: JSON.stringify(body) };\n // 5.12.0: check the status — a 429/5xx used to vanish silently (the 1 Oct\n // load test lost attempt reports this way). One bounded retry honouring\n // Retry-After (capped at 2s), scheduled OFF the caller's path; never throws.\n const fail = (failure: { status?: number; error?: string; retried: boolean }): void => {\n try {\n options.onFailure?.(failure);\n } catch {\n /* a reporter callback must never break the caller */\n }\n };\n let response: Response | undefined;\n try {\n response = await sdkFetch(url, init);\n } catch (err) {\n fail({ error: err instanceof Error ? err.message : String(err), retried: false });\n return;\n }\n if (response.ok) return;\n if (response.status !== 429 && response.status < 500) {\n fail({ status: response.status, retried: false });\n return;\n }\n const delayMs = Math.min(ATTEMPT_REPORT_MAX_RETRY_DELAY_MS, parseRetryAfterMs(response) ?? 500);\n const timer = setTimeout(() => {\n sdkFetch(url, init)\n .then((retry) => {\n if (!retry.ok) fail({ status: retry.status, retried: true });\n })\n .catch((err) => {\n fail({ error: err instanceof Error ? err.message : String(err), retried: true });\n });\n }, delayMs);\n (timer as { unref?: () => void }).unref?.();\n}\n\n/** 5.12.0: options for {@link reportAttempt}. */\nexport interface ReportAttemptOptions {\n /**\n * Called once when the report is finally lost (non-retryable status,\n * network error, or the single retry failed). For counters/telemetry;\n * exceptions it throws are swallowed.\n */\n onFailure?: (failure: { status?: number; error?: string; retried: boolean }) => void;\n}\n\n/** 5.12.0: upper bound on reportAttempt's single retry delay. */\nconst ATTEMPT_REPORT_MAX_RETRY_DELAY_MS = 2000;\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 */\n/** 5.13.0: endpoints whose policy read was refused (log once each). */\nconst refusedPolicyReads = new Set<string>();\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) {\n // 5.13.0: a refused policy read is not \"no policy configured\". The key\n // can't see this endpoint (another account's key, or a wrong id), so\n // the middleware is passing EVERY request through unverified. Say so,\n // loudly, once per endpoint.\n if (\n (response.status === 401 || response.status === 403 || response.status === 404) &&\n !refusedPolicyReads.has(counterpartyId)\n ) {\n refusedPolicyReads.add(counterpartyId);\n // eslint-disable-next-line no-console\n console.error(\n `[VerificationGateway] the configured API key cannot read the route policy for ${counterpartyId} ` +\n `(HTTP ${response.status}). The key belongs to an account that does not own this endpoint, ` +\n `or the counterpartyId is wrong. The gateway is in PASS-THROUGH mode: no agent is being verified.`\n );\n }\n return null;\n }\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 * VI uplift Part 3 — attempt-chain handle (`att_<32hex>`, from the\n * X-Astra-Attempt-Id header or an `?astra_attempt=` deep link). Joins\n * the beacon into the agent's research chain. Attribution only.\n */\n attemptId?: string;\n /** First-class referer (traffic-source reporting). */\n referer?: string;\n /** The caller's Accept header (surface-classifier input). */\n accept?: string;\n /** Self-declared platform from X-Astra-Source (attribution, never trust). */\n declaredSource?: 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 // 5.12.0: send the merchant's API key when configured — the backend then\n // stamps the row `attributionVerified: true` (it checks the key owns the\n // counterparty). Without a key the beacon is still accepted, but flagged\n // as unverified attribution in Visit Intelligence.\n await sdkFetch(`${apiBaseUrl}/verification-activity/unregistered-attempt`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(config.apiKey && { Authorization: `Bearer ${config.apiKey}` }),\n },\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 * 5.12.0: verification infrastructure was unavailable (timeout / 5xx /\n * the platform's 429) — NOT a denial. Callers should fail open on reads\n * or answer 503 + Retry-After (`retryAfterMs`, else 30s), never 401.\n */\n unavailable?: true;\n retryAfterMs?: number;\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 ...(isVerificationUnavailable(result) && {\n unavailable: true as const,\n retryAfterMs: unavailableRetryAfterSeconds(result) * 1000,\n }),\n };\n}\n","/**\n * HTTP Transport Adapter\n *\n * Maps AstraSync credentials to/from HTTP headers (X-Astra-* convention).\n */\n\nimport type { AstraSyncCredentials } from '../types';\n\nconst HEADER_PREFIX = 'X-Astra-';\n\n/**\n * Inject AstraSync credentials into HTTP headers.\n */\nexport function setHttpHeaders(\n headers: Record<string, string>,\n credentials: AstraSyncCredentials\n): Record<string, string> {\n const result = { ...headers };\n\n result[`${HEADER_PREFIX}ID`] = credentials.agentId;\n\n if (credentials.verifyUrl) {\n result[`${HEADER_PREFIX}Verify`] = credentials.verifyUrl;\n }\n\n if (credentials.challengeUrl) {\n result[`${HEADER_PREFIX}Challenge`] = credentials.challengeUrl;\n }\n\n if (credentials.pdlss?.purpose) {\n // 3.1.0 (Bug 14, §4.6): the action ALSO travels on its own dedicated\n // header so new-SDK receivers get the clean two-axis pair. The colon\n // form below is kept as the back-compat channel — pre-3.1.0 receivers\n // split on ':' and take the category prefix.\n const purposeValue = credentials.pdlss.purpose.action\n ? `${credentials.pdlss.purpose.category}:${credentials.pdlss.purpose.action}`\n : credentials.pdlss.purpose.category;\n result[`${HEADER_PREFIX}Purpose`] = purposeValue;\n if (credentials.pdlss.purpose.action) {\n result[`${HEADER_PREFIX}Action`] = credentials.pdlss.purpose.action;\n }\n }\n\n if (credentials.pdlss?.duration?.maxSessionDuration) {\n result[`${HEADER_PREFIX}Duration`] = String(credentials.pdlss.duration.maxSessionDuration);\n }\n\n if (credentials.pdlss?.scope?.jurisdiction) {\n result[`${HEADER_PREFIX}Scope`] = credentials.pdlss.scope.jurisdiction;\n }\n\n return result;\n}\n\n/**\n * Extract AstraSync credentials from HTTP headers.\n */\nexport function extractHttpCredentials(\n headers: Record<string, string | string[] | undefined>\n): AstraSyncCredentials | null {\n const getValue = (key: string): string | undefined => {\n const v = headers[key] ?? headers[key.toLowerCase()];\n return Array.isArray(v) ? v[0] : v;\n };\n\n const agentId = getValue(`${HEADER_PREFIX}ID`) ?? getValue('x-astra-id');\n if (!agentId) return null;\n\n const credentials: AstraSyncCredentials = { agentId };\n\n const verifyUrl = getValue(`${HEADER_PREFIX}Verify`) ?? getValue('x-astra-verify');\n if (verifyUrl) credentials.verifyUrl = verifyUrl;\n\n const challengeUrl = getValue(`${HEADER_PREFIX}Challenge`) ?? getValue('x-astra-challenge');\n if (challengeUrl) credentials.challengeUrl = challengeUrl;\n\n const purpose = getValue(`${HEADER_PREFIX}Purpose`) ?? getValue('x-astra-purpose');\n if (purpose) {\n const [category, action] = purpose.split(':');\n credentials.pdlss = {\n ...credentials.pdlss,\n purpose: { category, action },\n };\n }\n\n // 3.1.0 (Bug 14, §4.6): dedicated action header — overrides any colon-form\n // remainder parsed above (the dedicated header is the canonical channel).\n const astraAction = getValue(`${HEADER_PREFIX}Action`) ?? getValue('x-astra-action');\n if (astraAction) {\n credentials.pdlss = {\n ...credentials.pdlss,\n purpose: { category: credentials.pdlss?.purpose?.category ?? '', action: astraAction },\n };\n }\n\n const duration = getValue(`${HEADER_PREFIX}Duration`) ?? getValue('x-astra-duration');\n if (duration) {\n credentials.pdlss = {\n ...credentials.pdlss,\n duration: { maxSessionDuration: parseInt(duration, 10) },\n };\n }\n\n const scope = getValue(`${HEADER_PREFIX}Scope`) ?? getValue('x-astra-scope');\n if (scope) {\n credentials.pdlss = {\n ...credentials.pdlss,\n scope: { jurisdiction: scope },\n };\n }\n\n return credentials;\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 * 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 * Direct-path step-up approval gate (post-3.1.0 F2 follow-up).\n *\n * The verify-access spending-Limit ladder returns an \"allowed-but-escalate\"\n * outcome for a transaction value in the human-in-the-loop band\n * `[autonomousThreshold, hardLimit)`: `policyAllowed: true` (it is NOT a deny)\n * plus `requiresStepUp` / `requiresApproval`. The bridge blocks these; the\n * direct-path adapters historically gated on `identityVerified && policyAllowed`\n * alone and would therefore ADMIT (and let the merchant settle) the very\n * purchase the bridge blocks - a cross-path bypass.\n *\n * The backend now creates a pending step-up approval record and returns a\n * `stepUpApproval` object with `{ approvalId, pollUrl, expiresAt }` in the\n * verify-access response. The owner can approve/deny from the dashboard\n * (Activity → Pending Verifications). Future channels: mobile push, browser\n * extension.\n *\n * Direct-path adapters (Express/MCP/Next.js) fail closed BY DEFAULT. The\n * `stepUpApproval` info is included in the deny response so integrations can\n * surface it (\"your agent owner needs to approve this\") or poll it themselves.\n * 3.6.0 adds an opt-in hold-and-poll (`stepUpMaxWaitMs` on GatewayConfig, see\n * ./stepup-poll.ts): the adapter holds the request, polls the approval, and on\n * 'approved' re-verifies once (cache-bypassed) so the backend redeems the\n * single-use approval — the MFA model the Java SDK ships default-on. Opt-in\n * here because a minor release must not silently convert instant 403s into\n * multi-minute holds (client timeouts, connection pools, edge wall-clocks).\n *\n * Detection keys on the granular Limit flags (`requiresStepUp` /\n * `requiresApproval`, set from the verify-access `access` block) rather than\n * the `recommendation` umbrella - both because those flags ARE what drive a\n * `step_up_required` recommendation server-side, and because it keeps the\n * unverified-agent-policy `audit` outcome (a deliberate allow-and-log) from\n * being caught here.\n */\nimport type { VerificationResult, StepUpApprovalInfo } from '../types';\n\nconst APPROVAL_REASON =\n 'Transaction is above the autonomous limit and requires human approval. The agent owner can approve or deny this transaction in the AstraSync dashboard.';\n\n/** True when the outcome needs human step-up/approval. */\nexport function requiresHumanApproval(result: VerificationResult): boolean {\n return result.requiresStepUp === true || result.requiresApproval === true;\n}\n\n/**\n * Annotate a result in place with the structured approval-required failure +\n * denial reason, so the adapters' existing deny renderers surface it like any\n * other failure. Mirrors the bridge's `commerce.intent.approval_required`.\n */\nexport function annotateApprovalRequired(result: VerificationResult): void {\n result.failures = [\n ...(result.failures ?? []),\n { dimension: 'commerce.intent.approval_required', message: APPROVAL_REASON },\n ];\n result.denialReasons = [APPROVAL_REASON, ...(result.denialReasons ?? [])];\n}\n\n/**\n * Extract step-up approval polling info from the verification result, if\n * present. Returns undefined when no approval was created (e.g. transaction\n * below the autonomous threshold, or the backend couldn't create one).\n */\nexport function getApprovalPollingInfo(result: VerificationResult): StepUpApprovalInfo | undefined {\n return result.stepUpApproval;\n}\n","/**\n * Counterparty-side PDLSS pre-check.\n *\n * Compares the agent's requested PDLSS dimensions (from X-Astra-* headers)\n * against the counterparty-defined maximums on the route config.\n * Returns an array of failures — empty means all checks passed.\n *\n * This runs BEFORE calling verify-access on AstraSync. If it fails,\n * the request is rejected immediately without calling the platform.\n */\n\nimport type { RouteAccessConfig, AstraSyncCredentials, CounterpartyPreCheckFailure } from './types';\n\nexport function performCounterpartyPreCheck(\n routeConfig: RouteAccessConfig,\n astraCreds: AstraSyncCredentials | null,\n purpose: string | undefined\n): CounterpartyPreCheckFailure[] {\n const failures: CounterpartyPreCheckFailure[] = [];\n\n // Check purpose against allowedPurposes whitelist. Route allow-lists are an\n // OPTIONAL per-route refinement — undefined/empty = \"skip, let the backend\n // evaluator be the authoritative gate\". The backend's PDLSS evaluator\n // enforces the agent's own declared policy (round-18.5 F3 fail-closed there\n // is correct: the agent declared its allowlist or didn't). Treating an\n // undefined route allow-list as fail-closed breaks every partner that hasn't\n // enumerated allowedPurposes (which is most of them — round-18.5 originally\n // shipped this and was reverted in 2.4.11 after partner-wide auth break).\n if (routeConfig.allowedPurposes && routeConfig.allowedPurposes.length > 0 && purpose) {\n if (!routeConfig.allowedPurposes.includes(purpose)) {\n failures.push({\n field: 'purpose',\n requested: purpose,\n limit: routeConfig.allowedPurposes,\n message: `Purpose \"${purpose}\" is not in the allowed list: [${routeConfig.allowedPurposes.join(', ')}]`,\n });\n }\n }\n\n // Check purpose against requiredPurposes (legacy field — agent must declare one of these)\n if (routeConfig.requiredPurposes && routeConfig.requiredPurposes.length > 0 && purpose) {\n if (!routeConfig.requiredPurposes.includes(purpose)) {\n failures.push({\n field: 'purpose',\n requested: purpose,\n limit: routeConfig.requiredPurposes,\n message: `Purpose \"${purpose}\" is not in the required list: [${routeConfig.requiredPurposes.join(', ')}]`,\n });\n }\n }\n\n // Check duration against maxDuration — range-check (unchanged; undefined =\n // no upper bound is conventional for opt-in range fields, not a request-\n // driven allow-list).\n if (routeConfig.maxDuration && astraCreds?.pdlss?.duration?.maxSessionDuration) {\n const requested = astraCreds.pdlss.duration.maxSessionDuration;\n if (requested > routeConfig.maxDuration) {\n failures.push({\n field: 'duration',\n requested,\n limit: routeConfig.maxDuration,\n message: `Requested duration ${requested}s exceeds maximum ${routeConfig.maxDuration}s`,\n });\n }\n }\n\n // Check jurisdiction against allowedJurisdictions. Same reasoning as\n // allowedPurposes above — route allow-lists are an optional per-route\n // refinement; undefined/empty = skip and defer to the backend evaluator.\n if (\n routeConfig.allowedJurisdictions &&\n routeConfig.allowedJurisdictions.length > 0 &&\n astraCreds?.pdlss?.scope?.jurisdiction\n ) {\n const requested = astraCreds.pdlss.scope.jurisdiction;\n if (!routeConfig.allowedJurisdictions.includes(requested)) {\n failures.push({\n field: 'jurisdiction',\n requested,\n limit: routeConfig.allowedJurisdictions,\n message: `Jurisdiction \"${requested}\" is not in the allowed list: [${routeConfig.allowedJurisdictions.join(', ')}]`,\n });\n }\n }\n\n return failures;\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 * Query-string VALUES for parameter names the endpoint owner explicitly\n * allow-listed (`EdgeConfig.queryValueAllowlist`, seeded `utm_*` — VI\n * uplift Part 4). The default remains NO value capture; this exists so\n * campaign attribution (utm_source/medium/campaign) can be reported\n * without widening the privacy stance. Bounded 16 entries × 256 chars.\n */\n queryParams?: Record<string, 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\n/**\n * `X-Astra-Source` declared-source protocol (VI uplift Part 2). The header is\n * SELF-ASSERTED and spoofable — it buys attribution, never trust: it is never\n * read by any access decision and never conflated with fingerprint-matched\n * (`platformVendor`) or ASTRA-verified evidence. One shared validator so the\n * edge, backend, and bridge accept byte-identical values.\n */\nexport const DECLARED_SOURCE_MAX = 64;\nconst DECLARED_SOURCE_PATTERN = /^[a-z0-9][a-z0-9 ._/-]{0,63}$/;\n\nexport function normalizeDeclaredSource(value: string | undefined | null): string | undefined {\n const trimmed = value?.trim().slice(0, DECLARED_SOURCE_MAX).toLowerCase();\n return trimmed && DECLARED_SOURCE_PATTERN.test(trimmed) ? trimmed : undefined;\n}\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 * 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 * Per-path beacon sampling opt-DOWN (VI uplift 1.2). The default is full\n * capture; put a fractional rate on explicitly high-volume/low-value paths\n * (static mirrors, health checks) instead of sampling commerce traffic.\n */\n sampling?: {\n /** Fraction (0..1) of anonymous-bot requests that emit a beacon. */\n anonymousBeaconRate: number;\n };\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 * Query-string parameter names whose VALUES may be captured into\n * `observedMetadata.queryParams` (VI uplift Part 4 — campaign/UTM\n * attribution). Lowercase exact names or a single trailing-`*` glob\n * (`utm_*`); ≤16 entries × ≤64 chars. ABSENT by default — the privacy\n * stance (query values dropped at capture) is unchanged unless the\n * endpoint owner explicitly configures this.\n */\n queryValueAllowlist?: string[];\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 *\n * Beacon rate 1.0 (VI uplift 1.2): every anonymous hit beacons by default —\n * a sampled denominator understates anonymous traffic in every dashboard\n * tile and no toggle can reveal the dropped rows. Sampling is a deliberate\n * per-path opt-down (`EdgePathRule.sampling`) for static/high-volume paths.\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: 1.0 }),\n failurePosture: 'open',\n}) as EdgeConfig;\n\nconst EDGE_MODES: readonly string[] = ['observe', 'enforce'];\nconst EDGE_DEPTHS: readonly string[] = ['classify', 'authenticate', 'authorize'];\n\nfunction isSamplingShape(value: unknown): value is { anonymousBeaconRate: number } {\n if (typeof value !== 'object' || value === null) return false;\n const rate = (value as Record<string, unknown>).anonymousBeaconRate;\n return typeof rate === 'number' && rate >= 0 && rate <= 1;\n}\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 if (r.sampling !== undefined && !isSamplingShape(r.sampling)) return false;\n }\n if (!isSamplingShape(v.sampling)) return false;\n if (v.queryValueAllowlist !== undefined) {\n if (\n !Array.isArray(v.queryValueAllowlist) ||\n v.queryValueAllowlist.length > 16 ||\n !v.queryValueAllowlist.every((e) => typeof e === 'string' && e.length > 0 && e.length <= 64)\n ) {\n return false;\n }\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 * 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-bridge'\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 // GPTBot (training crawler) and OAI-SearchBot (ChatGPT search) are\n // OpenAI's declared crawler UAs — `gpt-?\\d` never matched them, so they\n // classified as unattributed crawlers (round-27.4 W5).\n uaPatterns: [/chatgpt/i, /openai/i, /gpt-?\\d/i, /\\bGPTBot\\b/i, /\\bOAI-SearchBot\\b/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: [\n /gemini/i,\n /google-gemini/i,\n /bard/i,\n // Google's AI/agent fetcher tokens (VI uplift 1.3). These are the\n // AI-training/agent crawlers, NOT the Search crawler — googlebot IP\n // ranges attribute Search and are deliberately absent from\n // vendor-ip-ranges. Anchored tokens: none appears in stock browser\n // UAs, and `-` counts as a \\b boundary so GoogleOther-Image/-Video\n // match too.\n /\\bGoogle-Extended\\b/i,\n /\\bGoogleOther\\b/i,\n /\\bGoogle-CloudVertexBot\\b/i,\n ],\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 // The MCP bridge's own catalog fetches (VI uplift 1.5). Deliberately a\n // DISTINCT UA from `astrasync-sdk/`: bridge fetches are buyer-agent\n // traffic merchants should see (identified · unregistered), so this\n // vendor is kept OUT of the self-traffic filter and the edge's SELF\n // short-circuit.\n {\n vendor: 'astrasync-bridge',\n displayName: 'AstraSync MCP bridge (buyer-agent catalog fetch)',\n uaPatterns: [/^astrasync-bridge\\//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 * 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 * AstraSync ACCOUNT API key shape (`kya_` + key material) — the platform's\n * own origin-auth credential (api-key.service `API_KEY_PREFIX`), NOT an\n * agent identity. See the round-17 first-party branch in classify().\n */\nconst ACCOUNT_API_KEY_PATTERN = /^kya_[A-Za-z0-9_-]+$/;\n\nfunction isAccountApiKey(value: string | undefined): boolean {\n return typeof value === 'string' && ACCOUNT_API_KEY_PATTERN.test(value);\n}\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 ...(rule.sampling && { sampling: rule.sampling }),\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 // Round-17 (staging finding, cost hours of masked key-validity debugging):\n // an ACCOUNT API key (`kya_…`) in Authorization/x-api-key is FIRST-PARTY\n // origin auth — curl/Postman/non-SDK backend clients calling the property's\n // own API — not an agent identity claim. Tiering it `verified` sent it into\n // verify-access, which can never verify an account key as an agent, so\n // enforce mode 403'd every plain API client (\"Endpoint policy denies\n // unverified agents\") even with a VALID key — also a self-DoS vector.\n // Treat it like self-traffic: pass through untouched, zero beacons; the\n // origin's own auth stays authoritative. An explicit X-Astra-Id alongside\n // still classifies as an agent claim below. (`kya_` is the only account-key\n // prefix the platform issues — api-key.service API_KEY_PREFIX.)\n if (\n !credentials.astraId &&\n (isAccountApiKey(credentials.jwt) || isAccountApiKey(credentials.apiKey))\n ) {\n return { tier: 'self', evidence: { firstPartyApiKey: true } };\n }\n // Only an ASTRA id is an agent identity claim: verify-access is sent the\n // ASTRA id and nothing else (verify.ts builds the body from\n // credentials.astraId only), so a bare Bearer JWT or a non-kya_ x-api-key\n // could never verify — tiering it `verified` just denied it under enforce.\n // Round-26 staging finding: that self-DoS'd first-party sessions (the\n // property's own chat/OAuth Bearer tokens — our BYOAI widget and passkey\n // ceremony page) and would do the same to any merchant SPA whose signed-in\n // users call its API with Bearer tokens. Such requests fall through to the\n // normal classification below (UA / commerce protocol / fingerprint), so a\n // made-up token earns nothing — it neither verifies nor bypasses the edge.\n if (credentials.astraId) {\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 * Time-budgeted event emission + the edge beacon buffer.\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: latency to the\n * customer's traffic is bounded, and a slow AstraSync API costs telemetry\n * time, never page loads. Runtimes that provide `waitUntil` (Cloudflare\n * Workers, Vercel Edge, Fastly Compute) pass it via\n * {@link EdgeCoreOptions.waitUntil} to take beacons off the latency path.\n *\n * 5.12.0 (round 27.4): beacons go through a module-scope\n * {@link BeaconBuffer} instead of one awaited POST each. Measured on\n * staging, one-POST-per-request under a 300ms budget delivered only ~38%\n * of beacons (origin RTT ~230ms, cold TLS ~700ms, so most POSTs were\n * abandoned at the budget). The buffer:\n * - is bounded (1000 items, drop-oldest, counted);\n * - flushes batches of ≤100 same-destination items to\n * `/verification-activity/edge-events`, authenticated with the API key\n * when one is configured (unauthenticated batches are still accepted,\n * flagged as unverified attribution);\n * - keeps its in-flight flush across invocations — a POST abandoned at the\n * budget keeps running, and a frozen Lambda resumes it on thaw; items in\n * flight are never re-sent while it is pending;\n * - re-queues failed items (max 3 attempts; 429 honours Retry-After\n * without spending an attempt; a 401 on the key falls back to\n * unauthenticated delivery);\n * - collapses identical requests (same counterparty, IP, UA, method, path,\n * attempt id) inside a 60s window into one item carrying `repeatCount`\n * — but only while that item is still queued (5.14.0, round 27.6: the\n * old 60s held aggregate waited for a later invocation that a reclaimed\n * Lambda container never gets; S1003 measured ~68% delivery);\n * - stamps each batch with `meta { droppedSinceLast, queueDepth, adapter,\n * version, containerId, enqueuedTotal, deliveredTotal, droppedTotal }`\n * so the backend can report delivery loss — including what a container\n * that stops reporting left behind (5.14.0).\n * Delivery is at-least-once: a POST that times out after the backend\n * recorded it is retried.\n */\n\nimport { sdkFetch } from '../http';\nimport { normalizeDeclaredSource } from '../metadata-capture';\nimport { SDK_VERSION } from '../version';\nimport { buildObservedMetadata, extractAttemptId, 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/** One beacon item — the backend `unregisteredAttemptSchema` shape + observedAt. */\nexport type BeaconItem = Record<string, unknown> & { repeatCount?: number };\n\n/** Where a beacon goes. Items batch together only when every field matches. */\nexport interface BeaconDestination {\n apiBaseUrl: string;\n /** Sent as `Authorization: Bearer` when set (verified attribution). */\n apiKey?: string;\n /** The counterparty the item names — one batch never mixes counterparties. */\n counterparty: string;\n /** Adapter name reported in batch meta (e.g. `lambda-edge`). */\n adapter?: string;\n}\n\n/** Batch metadata the backend records for delivery monitoring. */\nexport interface BeaconBatchMeta {\n droppedSinceLast: number;\n queueDepth: number;\n adapter: string;\n version: string;\n /**\n * 5.14.0 (round 27.6): this container's id (one per cold start) and its\n * cumulative item counters. The backend keeps the last report per\n * container, so items stranded in a container that stops reporting (a\n * reclaimed Lambda) are counted instead of silently vanishing.\n */\n containerId: string;\n enqueuedTotal: number;\n deliveredTotal: number;\n droppedTotal: number;\n}\n\n/** One id per module load — a Lambda container / isolate cold start. */\nconst CONTAINER_ID: string = (() => {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) return c.randomUUID();\n return `c-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;\n})();\n\nexport interface BeaconBufferOptions {\n /** Max queued items; the oldest is dropped (and counted) beyond it. Default 1000. */\n maxItems?: number;\n /** Max items per POST (backend cap). Default 100. */\n maxBatch?: number;\n /** Delivery attempts per item before it is dropped. Default 3. */\n maxAttempts?: number;\n /** Repeat-collapse window. Default 60s. */\n collapseWindowMs?: number;\n /**\n * Pre-5.14 behaviour: hold a repeat aggregate until its collapse window\n * closes. Off by default — a held item waits up to 60s for a later\n * invocation of the same container, and a container that is never\n * invoked again loses it (round 27.6, S1003: ~32% loss on staging). Kept\n * only so the delivery simulator can compare the two.\n */\n holdRepeats?: boolean;\n /** Container id stamped on batch meta. Default: one per module load. */\n containerId?: string;\n /** Max distinct repeat keys remembered (LRU). Default 1000. */\n collapseMaxKeys?: number;\n /** Per-POST timeout (the budget is the caller's; this bounds a hung POST). Default 10s. */\n requestTimeoutMs?: number;\n /** Pause after a failed POST before the next attempt. Default 1s. */\n retryBackoffMs?: number;\n /** Clock — injectable for tests. */\n now?: () => number;\n}\n\ninterface QueuedBeacon {\n dest: BeaconDestination;\n destKey: string;\n item: BeaconItem;\n attempts: number;\n /** holdRepeats only: a held aggregate isn't sent until its collapse window closes. */\n eligibleAt: number;\n inFlight: boolean;\n}\n\ninterface CollapseEntry {\n firstSeenAt: number;\n /** The newest item for this key — repeats merge into it while it is still queued. */\n first?: QueuedBeacon;\n /** holdRepeats only: the held aggregate absorbing repeats once the first item has left. */\n held?: QueuedBeacon;\n}\n\nconst destKeyOf = (d: BeaconDestination) =>\n `${d.apiBaseUrl}\\u0000${d.apiKey ?? ''}\\u0000${d.counterparty}\\u0000${d.adapter ?? ''}`;\n\nexport class BeaconBuffer {\n private queue: QueuedBeacon[] = [];\n private droppedSinceLast = 0;\n private droppedTotal = 0;\n private deliveredTotal = 0;\n private enqueuedTotal = 0;\n private inFlight: Promise<void> | undefined;\n private backoffUntil = 0;\n private readonly collapse = new Map<string, CollapseEntry>();\n /** Keys the backend answered 401 for — later batches go unauthenticated. */\n private readonly rejectedKeys = new Set<string>();\n private readonly opts: Required<BeaconBufferOptions>;\n\n constructor(options: BeaconBufferOptions = {}) {\n this.opts = {\n maxItems: options.maxItems ?? 1000,\n maxBatch: options.maxBatch ?? 100,\n maxAttempts: options.maxAttempts ?? 3,\n collapseWindowMs: options.collapseWindowMs ?? 60_000,\n collapseMaxKeys: options.collapseMaxKeys ?? 1000,\n requestTimeoutMs: options.requestTimeoutMs ?? 10_000,\n retryBackoffMs: options.retryBackoffMs ?? 1_000,\n holdRepeats: options.holdRepeats ?? false,\n containerId: options.containerId ?? CONTAINER_ID,\n now: options.now ?? Date.now,\n };\n }\n\n /**\n * Queue one beacon. With a `collapseKey`, a repeat inside the window is\n * merged into this key's item while that item is still queued (not yet in\n * flight). Once it has left, the repeat becomes a new item, sendable on\n * this flush — nothing waits for a later invocation (round 27.6).\n */\n enqueue(dest: BeaconDestination, item: BeaconItem, collapseKey?: string): void {\n const now = this.opts.now();\n if (collapseKey) {\n const entry = this.collapse.get(collapseKey);\n if (entry && now - entry.firstSeenAt < this.opts.collapseWindowMs) {\n for (const target of [entry.first, entry.held]) {\n if (target && !target.inFlight && this.queue.includes(target)) {\n target.item.repeatCount = (target.item.repeatCount ?? 1) + 1;\n return;\n }\n }\n if (this.opts.holdRepeats) {\n entry.held = this.push(\n dest,\n { ...item, repeatCount: 1 },\n entry.firstSeenAt + this.opts.collapseWindowMs\n );\n return;\n }\n entry.first = this.push(dest, { ...item, repeatCount: 1 }, now);\n return;\n }\n // New (or expired) key: refresh LRU position, evict the oldest.\n this.collapse.delete(collapseKey);\n if (this.collapse.size >= this.opts.collapseMaxKeys) {\n const oldest = this.collapse.keys().next().value;\n if (oldest !== undefined) this.collapse.delete(oldest);\n }\n const fresh: CollapseEntry = { firstSeenAt: now };\n this.collapse.set(collapseKey, fresh);\n fresh.first = this.push(dest, item, now);\n return;\n }\n this.push(dest, item, now);\n }\n\n /**\n * Deliver every eligible queued item. Concurrent callers share ONE\n * in-flight drain (it survives the caller's budget and a Lambda freeze),\n * so nothing in flight is ever sent twice; items queued while it runs are\n * picked up by the same drain.\n */\n flush(): Promise<void> {\n if (!this.inFlight) {\n this.inFlight = this.drain().finally(() => {\n this.inFlight = undefined;\n });\n }\n return this.inFlight;\n }\n\n /** Counters for tests and diagnostics. */\n stats(): {\n queueDepth: number;\n droppedSinceLast: number;\n droppedTotal: number;\n deliveredTotal: number;\n enqueuedTotal: number;\n flushing: boolean;\n } {\n return {\n queueDepth: this.queue.length,\n droppedSinceLast: this.droppedSinceLast,\n droppedTotal: this.droppedTotal,\n deliveredTotal: this.deliveredTotal,\n enqueuedTotal: this.enqueuedTotal,\n flushing: this.inFlight !== undefined,\n };\n }\n\n private push(dest: BeaconDestination, item: BeaconItem, eligibleAt: number): QueuedBeacon {\n while (this.queue.length >= this.opts.maxItems) this.dropOldest();\n const entry: QueuedBeacon = {\n dest,\n destKey: destKeyOf(dest),\n item,\n attempts: 0,\n eligibleAt,\n inFlight: false,\n };\n this.queue.push(entry);\n this.enqueuedTotal += 1;\n return entry;\n }\n\n private dropOldest(): void {\n if (this.queue.shift()) this.countDropped(1);\n }\n\n private countDropped(n: number): void {\n this.droppedSinceLast += n;\n this.droppedTotal += n;\n }\n\n private async drain(): Promise<void> {\n for (;;) {\n const now = this.opts.now();\n if (now < this.backoffUntil) return;\n const batch = this.takeBatch(now);\n if (batch.length === 0) return;\n const ok = await this.send(batch);\n if (!ok) return; // backoff set; the next flush() resumes\n }\n }\n\n /** Oldest eligible item + up to maxBatch-1 more for the same destination. */\n private takeBatch(now: number): QueuedBeacon[] {\n const first = this.queue.find((q) => q.eligibleAt <= now);\n if (!first) return [];\n const batch: QueuedBeacon[] = [];\n const rest: QueuedBeacon[] = [];\n for (const q of this.queue) {\n if (batch.length < this.opts.maxBatch && q.destKey === first.destKey && q.eligibleAt <= now) {\n q.inFlight = true;\n batch.push(q);\n } else {\n rest.push(q);\n }\n }\n this.queue = rest;\n return batch;\n }\n\n /** POST one batch. Returns false when the drain should pause (backoff). */\n private async send(batch: QueuedBeacon[]): Promise<boolean> {\n const dest = batch[0].dest;\n const useKey = dest.apiKey && !this.rejectedKeys.has(dest.apiKey) ? dest.apiKey : undefined;\n const reportedDropped = this.droppedSinceLast;\n const meta: BeaconBatchMeta = {\n droppedSinceLast: reportedDropped,\n queueDepth: this.queue.length,\n adapter: dest.adapter ?? 'edge-core',\n version: SDK_VERSION,\n containerId: this.opts.containerId,\n enqueuedTotal: this.enqueuedTotal,\n deliveredTotal: this.deliveredTotal,\n droppedTotal: this.droppedTotal,\n };\n const controller = typeof AbortController !== 'undefined' ? new AbortController() : undefined;\n const response = await withBudget(\n sdkFetch(`${dest.apiBaseUrl}/verification-activity/edge-events`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(useKey && { Authorization: `Bearer ${useKey}` }),\n },\n body: JSON.stringify({ events: batch.map((q) => q.item), meta }),\n ...(controller && { signal: controller.signal }),\n }),\n this.opts.requestTimeoutMs\n );\n if (!response) controller?.abort();\n const status = response?.status;\n\n for (const q of batch) q.inFlight = false;\n\n if (status !== undefined && status >= 200 && status < 300) {\n // The backend now knows about the drops it was told of.\n this.droppedSinceLast = Math.max(0, this.droppedSinceLast - reportedDropped);\n this.deliveredTotal += batch.length;\n return true;\n }\n if (status === 401 && useKey) {\n // Dead key: keep delivering, unauthenticated (accepted, flagged).\n this.rejectedKeys.add(useKey);\n this.requeue(batch, false);\n return true;\n }\n if (status === 429) {\n const retryAfter = Number(response?.headers.get('retry-after'));\n const waitMs =\n Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter, 120) * 1000 : 30_000;\n this.backoffUntil = this.opts.now() + waitMs;\n this.requeue(batch, false);\n return false;\n }\n if (status !== undefined && status >= 400 && status < 500) {\n // The backend refused the batch itself — retrying can't help.\n this.countDropped(batch.length);\n return true;\n }\n // Network error, timeout, or 5xx: retry later.\n this.backoffUntil = this.opts.now() + this.opts.retryBackoffMs;\n this.requeue(batch, true);\n return false;\n }\n\n /** Put a failed batch back at the head of the queue (order preserved). */\n private requeue(batch: QueuedBeacon[], countAttempt: boolean): void {\n const keep: QueuedBeacon[] = [];\n for (const q of batch) {\n if (countAttempt) q.attempts += 1;\n if (q.attempts >= this.opts.maxAttempts) this.countDropped(1);\n else keep.push(q);\n }\n this.queue = [...keep, ...this.queue];\n while (this.queue.length > this.opts.maxItems) this.dropOldest();\n }\n}\n\nlet beaconBuffer = new BeaconBuffer();\n\n/** The process-wide buffer every {@link emitBeacon} call feeds. */\nexport function getBeaconBuffer(): BeaconBuffer {\n return beaconBuffer;\n}\n\n/** Replace the process-wide buffer (tests; or custom limits at cold start). */\nexport function resetBeaconBuffer(options?: BeaconBufferOptions): BeaconBuffer {\n beaconBuffer = new BeaconBuffer(options);\n return beaconBuffer;\n}\n\n/**\n * Emit an unregistered-attempt beacon for `identified` (non-crypto depths)\n * and sampled `anonymous-bot` traffic: enqueue it, then give the shared\n * flush up to `budgetMs` (or hand the flush to `waitUntil` when the runtime\n * has one). Authenticated with `apiKey` when given; the backend\n * fingerprints the UA and find-or-provisions platform agents server-side.\n */\nexport async function emitBeacon(\n options: EdgeCoreOptions,\n req: NormalizedRequest,\n classification: Classification,\n budgetMs: number,\n queryValueAllowlist?: string[],\n apiKey?: string\n): Promise<void> {\n // VI uplift Parts 2/3 — stitching + attribution fields, all optional so\n // old backends simply ignore them.\n const attemptId = extractAttemptId(req);\n const declaredSource = normalizeDeclaredSource(headerValue(req, 'x-astra-source'));\n const userAgent = headerValue(req, 'user-agent');\n const item: BeaconItem = {\n ...(options.counterpartyId && { counterpartyId: options.counterpartyId }),\n ...(options.counterpartyUrl && { counterpartyUrl: options.counterpartyUrl }),\n counterpartyType: 'website',\n sourceIp: req.clientIp,\n userAgent,\n requestPath: req.uri,\n requestMethod: req.method,\n // Attempt-chain handle (header or ?astra_attempt= deep link) — joins\n // this beacon into the agent's research chain via pe_attempt_idx.\n ...(attemptId && { attemptId }),\n // First-class referer + accept: traffic-source and surface-classifier\n // inputs (previously buried inside observedMetadata.headers).\n referer: headerValue(req, 'referer'),\n accept: headerValue(req, 'accept'),\n ...(declaredSource && { declaredSource }),\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 unregistered\n // caller.\n observedMetadata: buildObservedMetadata(req, queryValueAllowlist),\n // Capture time — batched delivery skews createdAt by the flush delay.\n observedAt: new Date().toISOString(),\n };\n // Drop undefined values so the JSON matches the old body shape.\n for (const k of Object.keys(item)) if (item[k] === undefined) delete item[k];\n\n const buffer = getBeaconBuffer();\n buffer.enqueue(\n {\n apiBaseUrl: options.apiBaseUrl,\n ...(apiKey && { apiKey }),\n counterparty: options.counterpartyId || options.counterpartyUrl,\n ...(options.adapter && { adapter: options.adapter }),\n },\n item,\n // Repeat collapse needs a client identity; without an IP, distinct\n // callers sharing a UA would merge, so don't collapse.\n req.clientIp\n ? [\n options.counterpartyId || options.counterpartyUrl,\n req.clientIp,\n userAgent ?? '',\n req.method,\n req.uri,\n attemptId ?? '',\n ].join('\\u0000')\n : undefined\n );\n const flushing = buffer.flush();\n if (options.waitUntil) {\n options.waitUntil(flushing);\n return;\n }\n await withBudget(flushing, budgetMs);\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 * Anonymous-traffic beacon for the SDK middleware pass-through paths.\n *\n * When a request passes through UNGATED (no dashboard route matches it, or\n * the matching route is gated at `none`), no verify-access call happens and\n * the endpoint's dashboard is blind to that traffic. This module gives the\n * express/nextjs adapters the same lightweight visibility the edge adapters\n * already have: bot- and agent-shaped pass-through traffic emits a\n * fire-and-forget unregistered-attempt beacon, while human traffic and\n * static assets are never beaconed and credentialed agents are handled by\n * verify-access, not this beacon.\n *\n * Sampling is dashboard-driven: the endpoint's edge verification config\n * supplies `sampling.anonymousBeaconRate` (0 turns anonymous-bot sampling\n * off; platform-fingerprinted agents always beacon). Nothing here ever\n * waits on the request path — the beacon is never awaited, and the config\n * fetch runs in the background: until a config has arrived, no beacons are\n * sent. Merchants who must not emit any extra outbound calls can set\n * `anonymousBeacon: false` on the middleware options, which disables the\n * beacon (and its config fetch) entirely.\n */\n\nimport { _patterns } from '../edge-core/classify';\nimport { sampled } from '../edge-core/events';\nimport { getEdgeConfig, type EdgeConfig } from '../edge-config';\nimport { buildSdkObservedMetadata, sanitizeHeaders } from '../metadata-capture';\nimport { detectPlatformFingerprint } from '../platform-signatures';\nimport { extractCredentials, reportUnregisteredAttempt } from '../verify';\nimport type { GatewayConfig } from '../types';\n\n/** Raw (pre-sanitisation) header map as Node/Web adapters hold it. */\ntype RawHeaders = Record<string, string | string[] | undefined>;\n\nfunction readHeader(raw: RawHeaders, name: string): string | undefined {\n const value = raw[name];\n if (typeof value === 'string') return value;\n if (Array.isArray(value)) return value[0];\n return undefined;\n}\n\n/**\n * How a pass-through request should be treated by the anonymous beacon:\n * - `never` — humans, static assets, and credentialed agents: no beacon.\n * - `platform` — a platform-fingerprinted agent (Claude/ChatGPT/Gemini/…):\n * beacon every time (unsampled) — these are exactly the\n * agents the dashboard's platform attribution exists for.\n * - `anonymous-bot` — non-browser automation with no platform signal:\n * beacon at the dashboard-configured sampling rate.\n */\nexport interface PassThroughTrafficClass {\n kind: 'never' | 'platform' | 'anonymous-bot';\n /** Detection protocol persisted with the beacon event. */\n protocol?: string;\n /** Light detection detail persisted with the beacon event. */\n evidence?: Record<string, unknown>;\n}\n\n/**\n * Classify one pass-through request for the anonymous beacon. Reuses the\n * edge classifier's heuristics (static-asset extensions, platform\n * fingerprints, browser-vs-bot UA shape) so the SDK and edge tiers agree on\n * what counts as agent traffic.\n */\nexport function classifyPassThroughTraffic(\n path: string,\n rawHeaders: RawHeaders\n): PassThroughTrafficClass {\n // Static assets: the beacon (like the gateway) gets out of the way.\n if (_patterns.STATIC_EXTENSIONS.test(path)) return { kind: 'never' };\n\n // Credentialed traffic is not anonymous — when a gated route sees these\n // credentials, verify-access records the caller; an unregistered-attempt\n // beacon would misfile it.\n const credentials = extractCredentials(rawHeaders, {});\n if (credentials.astraId || credentials.apiKey || credentials.jwt) {\n return { kind: 'never' };\n }\n\n const userAgent = readHeader(rawHeaders, 'user-agent') ?? '';\n\n // Platform-agent fingerprint (UA, credential key format, or a\n // platform-signal header) — a stronger, less-spoofable signal than the\n // UA alone, and it fires before the browser-shape check because several\n // platform agents present Mozilla-prefixed UAs.\n const { apiKeyFormat, platformHeaders } = sanitizeHeaders(rawHeaders);\n const fingerprint = detectPlatformFingerprint({ userAgent, apiKeyFormat, platformHeaders });\n if (fingerprint) {\n return {\n kind: 'platform',\n protocol: 'platform-ua',\n evidence: { vendor: fingerprint.vendor, userAgent: userAgent || '(none)' },\n };\n }\n\n // 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 (\n !userAgent ||\n _patterns.BOT_UA_PATTERN.test(userAgent) ||\n !_patterns.BROWSER_UA_PATTERN.test(userAgent)\n ) {\n return {\n kind: 'anonymous-bot',\n protocol: 'ua-heuristic',\n evidence: { userAgent: userAgent || '(none)' },\n };\n }\n\n // Claims to be a browser but sends none of the headers every evergreen\n // browser sends — headless/spoofed automation.\n if (!readHeader(rawHeaders, 'sec-fetch-mode') && !readHeader(rawHeaders, 'accept-language')) {\n return {\n kind: 'anonymous-bot',\n protocol: 'ua-heuristic',\n evidence: { userAgent, spoofedBrowser: true },\n };\n }\n\n // Human traffic — never beaconed, never logged.\n return { kind: 'never' };\n}\n\n/** Per-request input the middleware hands the beacon on a pass-through. */\nexport interface AnonymousBeaconInput {\n requestPath: string;\n requestMethod: string;\n /** Origin the SDK is protecting (auto-detected by the adapters). */\n counterpartyUrl?: string;\n /** Client IP as the adapter resolves it; falls back to X-Forwarded-For. */\n sourceIp?: string;\n rawHeaders: RawHeaders;\n}\n\n/** Fire-and-forget emitter — returns immediately, never throws. */\nexport type AnonymousBeaconEmitter = (input: AnonymousBeaconInput) => void;\n\n/**\n * Create the per-middleware-instance anonymous beacon.\n *\n * Requires a configured `counterpartyId` — sampling is a per-endpoint\n * dashboard setting and beacon events attribute to the endpoint; without\n * one, the returned emitter is a no-op.\n *\n * The emitter itself is synchronous: it classifies the request locally and\n * fire-and-forgets the report. The dashboard config is fetched in the\n * background (cached, stale-while-revalidate) and never awaited on the\n * request path; until the first config resolves, no beacons are emitted.\n */\nexport function createAnonymousBeacon(\n config: GatewayConfig,\n options?: {\n /** Counterparty type stamped on beacon events (adapter-specific default). */\n counterpartyType?: string;\n /** Injectable RNG for deterministic sampling in tests. */\n random?: () => number;\n }\n): AnonymousBeaconEmitter {\n const counterpartyId = config.counterpartyId;\n if (!counterpartyId) return () => {};\n\n const random = options?.random ?? Math.random;\n let edgeConfig: EdgeConfig | undefined;\n let refreshing = false;\n\n const refreshConfig = (): void => {\n if (refreshing) return;\n refreshing = true;\n getEdgeConfig(config, counterpartyId)\n .then((cfg) => {\n edgeConfig = cfg;\n })\n .catch(() => {})\n .finally(() => {\n refreshing = false;\n });\n };\n // Eager background fetch so early pass-through traffic already has a\n // sampling rate; requests arriving before it lands are simply not\n // beaconed (visibility is best-effort, latency is not negotiable).\n refreshConfig();\n\n return (input) => {\n try {\n // Keep the config fresh — getEdgeConfig serves its TTL cache and\n // revalidates in the background; this call is never awaited.\n refreshConfig();\n const cfg = edgeConfig;\n if (!cfg) return;\n\n const traffic = classifyPassThroughTraffic(input.requestPath, input.rawHeaders);\n if (traffic.kind === 'never') return;\n if (traffic.kind === 'anonymous-bot' && !sampled(cfg.sampling.anonymousBeaconRate, random)) {\n return;\n }\n\n const userAgent = readHeader(input.rawHeaders, 'user-agent');\n const xff = input.rawHeaders['x-forwarded-for'];\n const xffStr = Array.isArray(xff) ? xff.join(', ') : xff;\n const sourceIp = input.sourceIp ?? xffStr?.split(',')[0]?.trim();\n\n reportUnregisteredAttempt(config, {\n ...(input.counterpartyUrl && { counterpartyUrl: input.counterpartyUrl }),\n counterpartyType: options?.counterpartyType ?? config.counterpartyType ?? 'api',\n ...(sourceIp && { sourceIp }),\n ...(userAgent && { userAgent }),\n requestPath: input.requestPath,\n requestMethod: input.requestMethod,\n ...(traffic.protocol && { protocol: traffic.protocol }),\n ...(traffic.evidence && { evidence: traffic.evidence }),\n observedMetadata: buildSdkObservedMetadata(input.rawHeaders),\n }).catch(() => {});\n } catch {\n // The beacon must never break — or delay — the merchant's request.\n }\n };\n}\n","/**\n * AstraSync Universal Verification Gateway - Express Middleware\n *\n * Express.js middleware for verifying AI agents on API endpoints.\n *\n * @example\n * ```typescript\n * import express from 'express';\n * import { createMiddleware } from '@astrasyncai/verification-gateway/express';\n *\n * const app = express();\n *\n * app.use(createMiddleware({\n * apiBaseUrl: 'https://astrasync.ai/api',\n * apiKey: process.env.ASTRASYNC_API_KEY,\n * counterpartyId: 'ASTRAE-...', // your registered endpoint id\n * }));\n * ```\n *\n * Per-route policy (which paths are gated, trust floors, PDLSS purposes) is\n * configured in the AstraSync dashboard, not in code — the middleware\n * fetches it automatically on init and refreshes periodically. There is no\n * `routes` option; a `routes` key in the config object is ignored (with a\n * warning) since v2.9.7.\n */\n\nimport type { Request, Response, NextFunction, RequestHandler } from 'express';\nimport type {\n ExpressMiddlewareOptions,\n AgentCredentials,\n VerificationResult,\n EnhancedVerificationResult,\n RouteAccessConfig,\n AstraSyncCredentials,\n VerificationRequest,\n} from '../types';\nimport { awaitStepUpApproval } from './stepup-poll';\nimport {\n verify,\n extractCredentials,\n recordDecision,\n reportCounterpartyPreCheckFailure,\n fetchRoutes,\n} from '../verify';\nimport { extractHttpCredentials } from '../transport/http';\nimport { MCP_VERIFIED_HOP_HEADER, parseVerifiedHop, isVerifiedHopValidFor } from '../verified-hop';\nimport { resolveHttpPdlss, type HttpPdlssResolution } from './http-pdlss';\nimport { requiresHumanApproval, annotateApprovalRequired } from './approval-gate';\nimport { performCounterpartyPreCheck } from '../pdlss-pre-check';\nimport { prefetchWellKnown, getWellKnownUrls } from '../well-known';\nimport { buildSdkObservedMetadata } from '../metadata-capture';\nimport { createAnonymousBeacon } from './anonymous-beacon';\nimport {\n VERIFICATION_STATUS_HEADER,\n buildVerificationUnavailableBody,\n denyStatusFor,\n isAnonymousRead,\n isVerificationUnavailable,\n unavailableRetryAfterSeconds,\n} from '../failure-posture';\n\n/**\n * Extend Express Request with verification result\n */\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace Express {\n interface Request {\n agentVerification?: VerificationResult;\n }\n }\n}\n\n/**\n * Default credential extractor\n */\nfunction defaultExtractCredentials(req: Request): AgentCredentials {\n return extractCredentials(\n req.headers as Record<string, string | string[] | undefined>,\n req.query as Record<string, string | undefined>\n );\n}\n\n/**\n * Extract extended AstraSync credentials (X-Astra-* headers) from Express request.\n * Returns null if no AstraSync headers are present.\n */\nexport function extractAstraSyncCredentials(req: Request): AstraSyncCredentials | null {\n return extractHttpCredentials(req.headers as Record<string, string | string[] | undefined>);\n}\n\n/** Read a possibly-array header value as a single string. */\nfunction headerValue(value: string | string[] | undefined): string | undefined {\n if (typeof value === 'string') return value;\n if (Array.isArray(value)) return value[0];\n return undefined;\n}\n\n/**\n * Resolve the canonical {purpose, action} pair for a request.\n * Replaces the gen-1 `defaultExtractPurpose` method-inference (`read_data`/\n * `write_data`) and the hardwired `action: req.method.toUpperCase()` — the\n * transport verb never travels as a PDLSS action. Full precedence chains\n * live in http-pdlss.ts.\n */\nfunction resolveRequestPdlss(\n req: Request,\n routeConfig: { purpose?: string; action?: string } | null,\n customExtractPurpose: ((req: Request) => string | undefined) | undefined,\n customExtractAction: ((req: Request) => string | undefined) | undefined\n): HttpPdlssResolution {\n return resolveHttpPdlss({\n method: req.method,\n astraPurpose: headerValue(req.headers['x-astra-purpose']),\n astraAction: headerValue(req.headers['x-astra-action']),\n legacyPurpose: headerValue(req.headers['x-purpose'] ?? req.headers['X-Purpose']),\n queryPurpose: typeof req.query.purpose === 'string' ? req.query.purpose : undefined,\n routePurpose: routeConfig?.purpose,\n routeAction: routeConfig?.action,\n hasCustomPurposeExtractor: !!customExtractPurpose,\n customPurpose: customExtractPurpose?.(req),\n hasCustomActionExtractor: !!customExtractAction,\n customAction: customExtractAction?.(req),\n });\n}\n\n/**\n * Match a route pattern against a path.\n *\n * Historically the SDK's\n * matchRoute was case-sensitive while Express's default `case sensitive\n * routing` is FALSE. A customer policy `/api/admin/*` did NOT match\n * `/api/ADMIN/users` → SDK returned `no-match` → request passed ungated →\n * Express routed it to the admin handler. The case-insensitive codepath\n * below closes the bypass.\n *\n * Ships in SHADOW MODE in SDK 2.4.13: by default the case-sensitive\n * regex is still authoritative; the case-insensitive variant is\n * computed in parallel and logged when results diverge. Follow-up\n * release flips the default to case-insensitive after 1-week\n * observation. Customers can flip early by setting\n * `caseInsensitiveRouteMatch: true` on the middleware options.\n */\nfunction matchRoute(\n pattern: string,\n path: string,\n opts?: { caseInsensitive?: boolean; correlationId?: string; logShadowDivergence?: boolean }\n): boolean {\n // Convert pattern to regex\n const regexPattern = pattern.replace(/\\*/g, '.*').replace(/\\//g, '\\\\/');\n\n const caseSensitiveRegex = new RegExp(`^${regexPattern}$`);\n const caseSensitiveResult = caseSensitiveRegex.test(path);\n\n if (!opts?.caseInsensitive && !opts?.logShadowDivergence) {\n return caseSensitiveResult;\n }\n\n const caseInsensitiveRegex = new RegExp(`^${regexPattern}$`, 'i');\n const caseInsensitiveResult = caseInsensitiveRegex.test(path);\n\n // Shadow logging: emit only when results diverge so operators can grep\n // their own logs for the bypass class without log volume spam.\n if (opts?.logShadowDivergence && caseSensitiveResult !== caseInsensitiveResult) {\n // eslint-disable-next-line no-console\n console.warn(\n `[SHADOW] matchRoute case-insensitive would change result: pattern=${pattern} path=${path} ` +\n `caseSensitive=${caseSensitiveResult} caseInsensitive=${caseInsensitiveResult} correlationId=${opts.correlationId ?? 'unknown'}`\n );\n }\n\n return opts?.caseInsensitive ? caseInsensitiveResult : caseSensitiveResult;\n}\n\n/**\n * Find the route configuration for a request\n */\nfunction findRouteConfig(\n routes: RouteAccessConfig[],\n path: string,\n method: string,\n opts?: { caseInsensitive?: boolean; correlationId?: string; logShadowDivergence?: boolean }\n): RouteAccessConfig | undefined {\n return routes.find((route) => {\n const methodMatches =\n route.method === '*' || route.method.toUpperCase() === method.toUpperCase();\n const pathMatches = matchRoute(route.pattern, path, opts);\n return methodMatches && pathMatches;\n });\n}\n\n/**\n * Default denied handler\n *\n * The response body carries the full `failures[]`\n * array and the `correlationId` so partners can render per-dimension UX\n * and tie a denial back to a server log line. Previously the merchant only\n * got the first denialReason — meaningful detail was thrown away before\n * the response left the SDK. Also stamps `X-Astra-Gateway-Mode: enforced`\n * so partners can tell a gate-evaluated denial apart from a gate-skipped\n * pass-through (the `unenforced` complement).\n */\nfunction dedupeFailures(result: VerificationResult): void {\n if (result.failures && result.failures.length > 1) {\n const seen = new Set<string>();\n result.failures = result.failures.filter((f) => {\n const key = `${f.dimension}|${f.message}|${(f as { guidance?: string }).guidance ?? ''}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n }\n if (result.denialReasons && result.denialReasons.length > 1) {\n result.denialReasons = [...new Set(result.denialReasons)];\n }\n}\n\nfunction defaultOnDenied(result: VerificationResult, _req: Request, res: Response): void {\n // 4.0.0 BREAKING: when this integration's OWN API key was rejected by the\n // backend (misconfigured marker), the inbound agent did nothing wrong and\n // re-authenticating won't help — a 401 both blames the agent and invites\n // re-auth loops. Answer 503: this site's verification layer is down, by\n // the operator's own configuration. No Retry-After — retrying is futile\n // until the operator rotates the key.\n if (result.misconfigured) {\n res.setHeader('X-Astra-Gateway-Mode', 'enforced');\n res.status(503).json({\n success: false,\n error: {\n code: 'MERCHANT_VERIFICATION_MISCONFIGURED',\n message: result.denialReasons?.[0] || \"This site's AstraSync integration is misconfigured\",\n guidance: result.guidance,\n failures: result.failures,\n correlationId: result.correlationId,\n },\n });\n return;\n }\n\n // 5.12.0: verification infrastructure unavailable (timeout / 5xx / the\n // platform's 429) on an enforced route → 503 + Retry-After, edge parity.\n // Never 401: the agent's identity was never evaluated. (Observe routes and\n // anonymous reads never reach here — the gate passes them through.)\n if (isVerificationUnavailable(result)) {\n res.setHeader('X-Astra-Gateway-Mode', 'enforced');\n res.setHeader(VERIFICATION_STATUS_HEADER, 'unavailable');\n res.setHeader('Retry-After', String(unavailableRetryAfterSeconds(result)));\n res.status(503).json(buildVerificationUnavailableBody(result));\n return;\n }\n\n // Round-18 G4: identity-verification failures → 401 (re-authenticate);\n // identity-verified-but-policy-denied → 403 (re-auth won't help; update\n // PDLSS scope or escalate to step-up). Maps to the two distinct recovery\n // actions that HTTP middleware acts on without parsing bodies. The\n // impossible state `!identityVerified && policyAllowed` falls into the\n // `!identityVerified` branch — identity is the more-fundamental missing\n // precondition. 5.12.0: a PRESENTED id that is malformed or unknown is a\n // 403 AGENT_IDENTITY_REJECTED with registration guidance — 401 is reserved\n // for missing credentials (re-presenting the same id cannot help).\n const { status: statusCode, code } = denyStatusFor(result, 'INSUFFICIENT_ACCESS');\n\n res.setHeader('X-Astra-Gateway-Mode', 'enforced');\n\n res.status(statusCode).json({\n success: false,\n error: {\n code,\n message: result.denialReasons?.[0] || 'Access denied',\n guidance: result.guidance,\n // Round-10: aggregated per-dimension detail + correlation handle.\n failures: result.failures,\n correlationId: result.correlationId,\n stepUpApproval: result.stepUpApproval,\n // 3.6.0: terminal outcome of an opt-in hold-and-poll wait (denied /\n // expired / consumed / timeout). Absent when the feature is off.\n ...(result.stepUpOutcome && { stepUpOutcome: result.stepUpOutcome }),\n },\n });\n}\n\n/**\n * Refresh interval for the remote-fetched route policy. Default: every 5\n * minutes. Override via `routesRefreshMs` on the middleware options. Each\n * middleware instance keeps its own cache; multiple instances pointing at the\n * same endpoint will each fetch independently.\n */\nconst DEFAULT_ROUTES_REFRESH_MS = 5 * 60 * 1000;\n\n/**\n * Create Express middleware for agent verification.\n *\n * v2.9.7 moved per-route policy authority out of merchant-side source code\n * into the AstraSync dashboard. `createMiddleware` no longer accepts a\n * `routes` array — it fetches the endpoint's stored policy via\n * `GET /endpoints/:counterpartyId/routes` on init and refreshes\n * periodically. Policy edits in the dashboard take effect on the next\n * refresh (or sooner if the operator manually restarts the SDK).\n *\n * `counterpartyId` is required: the SDK can't know which endpoint's policy\n * to fetch without it. Local-development workflows that don't have an\n * AstraSync endpoint registered can omit it — the middleware logs a\n * one-time warning and falls through (allows all) until a policy is\n * fetchable.\n */\nexport function createMiddleware(options: ExpressMiddlewareOptions): RequestHandler {\n // Guard against configs authored for pre-2.9.7 SDKs: a `routes` array in\n // merchant source is silently dead config (the type contract rejects it at\n // literal call sites, but variable-typed configs slip through) — and dead\n // route config means the author believes paths are gated that aren't.\n if ('routes' in options) {\n // eslint-disable-next-line no-console\n console.warn(\n '[VerificationGateway] `routes` is dashboard-managed since v2.9.7; this option is ignored — ' +\n 'configure route policy in your AstraSync dashboard.'\n );\n }\n const {\n extractCredentials: customExtractCredentials,\n extractPurpose: customExtractPurpose,\n extractAction: customExtractAction,\n skipPaths = [],\n onDenied = defaultOnDenied,\n recordDecisions,\n enableRuntimeChallenge = true,\n routesRefreshMs = DEFAULT_ROUTES_REFRESH_MS,\n failOnError = 'open',\n caseInsensitiveRouteMatch = false,\n anonymousBeacon = true,\n trustVerifiedHop = false,\n verifiedHopMaxAgeMs,\n ...config\n } = options;\n\n // v2.5.0: fire-and-forget pre-fetch of well-known URLs\n if (config.apiBaseUrl) {\n prefetchWellKnown(config.apiBaseUrl).catch(() => {});\n }\n\n // Dashboard-driven anonymous-traffic beacon for the pass-through paths\n // (no matching route / route gated at `none`). Fire-and-forget: never\n // awaited, never delays next(). See ./anonymous-beacon.ts.\n const emitAnonymousBeacon = anonymousBeacon\n ? createAnonymousBeacon(config, { counterpartyType: config.counterpartyType ?? 'api' })\n : undefined;\n const beaconPassThrough = emitAnonymousBeacon\n ? (req: Request): void => {\n const xff = req.headers['x-forwarded-for'];\n const xffStr = Array.isArray(xff) ? xff.join(', ') : xff;\n emitAnonymousBeacon({\n requestPath: req.path,\n requestMethod: req.method,\n counterpartyUrl: config.counterpartyUrl || `${req.protocol}://${req.get('host')}`,\n sourceIp: req.ip ?? (xffStr ? xffStr.split(',')[0].trim() : undefined),\n rawHeaders: req.headers as Record<string, string | string[] | undefined>,\n });\n }\n : undefined;\n\n // Per-middleware-instance route cache. Populated on first fetch; refreshed\n // every `routesRefreshMs`. Until first successful fetch we hold an empty\n // array which means \"no per-route gating active\" — the middleware falls\n // through. Pre-fix the array came from merchant source, which both broke\n // the auth-boundary story (defect 24) and silently disagreed with the\n // dashboard.\n let cachedRoutes: RouteAccessConfig[] = [];\n let lastFetchAt = 0;\n let refreshing: Promise<void> | null = null;\n let warnedNoCounterparty = false;\n let warnedEmptyRoutes = false;\n\n async function refreshRoutes(): Promise<void> {\n if (!config.counterpartyId) {\n if (!warnedNoCounterparty) {\n // eslint-disable-next-line no-console\n console.warn(\n '[VerificationGateway] No counterpartyId configured — falling through (allow all). ' +\n 'Per-route policy lives in the AstraSync dashboard now; register the endpoint and ' +\n 'set counterpartyId in your middleware config to enforce policy.'\n );\n warnedNoCounterparty = true;\n }\n return;\n }\n const fetched = await fetchRoutes(config, config.counterpartyId);\n if (fetched) {\n cachedRoutes = fetched;\n lastFetchAt = Date.now();\n // v2.3.8 (defect #25): if the fetch succeeded but returned an empty\n // policy, the endpoint is registered correctly but the operator hasn't\n // configured any routes yet — every request will fall through ungated.\n // Surface this loudly once so silent pass-through can't go unnoticed.\n if (cachedRoutes.length === 0 && !warnedEmptyRoutes) {\n // Audit F-PROBE-01: app.astrasync.ai doesn't resolve in DNS today;\n // dashboard actually lives at astrasync.ai/dashboard. Use that as\n // the fallback. If DevOps provisions app.astrasync.ai later, the\n // dashboardUrl config option lets merchants override.\n const dashboard = config.dashboardUrl ?? 'https://astrasync.ai/dashboard';\n // eslint-disable-next-line no-console\n console.warn(\n `[VerificationGateway] No route policy configured for ${config.counterpartyId}. ` +\n `Gateway is in pass-through mode for ALL traffic until you add at least one route. ` +\n `Configure at ${dashboard}/dashboard/endpoints/${config.counterpartyId}/routes`\n );\n warnedEmptyRoutes = true;\n }\n }\n }\n\n // Eager first fetch so the first request after init has policy loaded.\n // Errors are swallowed (handled by fetchRoutes returning null).\n refreshing = refreshRoutes().finally(() => {\n refreshing = null;\n });\n\n return async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n // Check if path should be skipped\n const shouldSkip = skipPaths.some((pattern) => matchRoute(pattern, req.path));\n if (shouldSkip) {\n return next();\n }\n\n // Wait for in-flight init fetch (only on the very first request) so we\n // don't admit traffic with no policy loaded.\n if (refreshing) {\n await refreshing.catch(() => {});\n }\n // Time-based refresh: kick off a background refresh if the cache is\n // stale. Doesn't block the current request — readers see whatever is\n // cached at this moment; the next request will see the refreshed copy.\n if (config.counterpartyId && Date.now() - lastFetchAt > routesRefreshMs) {\n refreshing = refreshRoutes().finally(() => {\n refreshing = null;\n });\n }\n\n // Find route configuration\n // Audit F-A6-31 shadow-mode wiring: pass caseInsensitive flag (default\n // false in 2.4.13) + always log divergences so merchants can grep for\n // would-have-matched results during the 1-week observation window.\n const correlationId =\n (req.headers['x-request-id'] as string | undefined) ||\n (req.headers['x-correlation-id'] as string | undefined);\n const routeConfig = findRouteConfig(cachedRoutes, req.path, req.method, {\n caseInsensitive: caseInsensitiveRouteMatch,\n logShadowDivergence: true,\n correlationId,\n });\n\n // If no route config, skip verification (allow through)\n if (!routeConfig) {\n if (config.setPassThroughHeader) {\n // Round-10 (#49, O10): `unenforced` replaces the previous\n // `pass-through` label. The previous name conflated \"gateway\n // didn't evaluate policy\" with \"request succeeded end-to-end\" —\n // the downstream handler may still return any status. The new\n // semantic describes the GATE state only.\n res.setHeader('X-Astra-Gateway-Mode', 'unenforced');\n res.setHeader(\n 'X-Astra-Gateway-Reason',\n cachedRoutes.length === 0 ? 'no-policy' : 'no-match'\n );\n }\n // Anonymous-traffic beacon: this request never reaches verify-access,\n // so bot/agent-shaped callers would otherwise be invisible to the\n // dashboard. Fire-and-forget — does not delay next().\n beaconPassThrough?.(req);\n return next();\n }\n\n // v2.5.0: resolve well-known URLs (cached; prefetched at middleware creation)\n const wellKnownUrls = config.apiBaseUrl\n ? await getWellKnownUrls(config.apiBaseUrl).catch(() => undefined)\n : undefined;\n\n // Extract credentials (hoisted from below the route-none check so the\n // round-12 F9 evaluateAlwaysIfCredentialed flag can decide whether to\n // evaluate vs short-circuit).\n const credentials = customExtractCredentials\n ? customExtractCredentials(req)\n : defaultExtractCredentials(req);\n\n // Round-12 (F9): route-none short-circuit unless the caller wants\n // evaluation-without-enforcement. With evaluateAlwaysIfCredentialed\n // set to true AND credentials present, the middleware calls\n // verify-access for audit + req.agentVerification population, then\n // proceeds without gating. Default behaviour (flag off) preserves\n // pre-F9 short-circuit semantics.\n const shouldEnforce = !routeConfig.observe;\n if (routeConfig.observe && (!config.evaluateAlwaysIfCredentialed || !credentials.astraId)) {\n if (config.setPassThroughHeader) {\n res.setHeader('X-Astra-Gateway-Mode', 'unenforced');\n res.setHeader('X-Astra-Gateway-Reason', 'route-observe');\n }\n // Anonymous-traffic beacon (see the no-route-match branch above).\n beaconPassThrough?.(req);\n return next();\n }\n\n // Inner-hop dedupe: a trusted upstream AstraSync hop (edge gateway or\n // MCP outer hop) already verified this exact ASTRA-id moments ago —\n // accept the fresh marker and skip the duplicate verify-access call.\n // Mirrors the MCP adapter contract: no req.agentVerification on a\n // hop-skip. The marker must match the request's own X-Astra-Id.\n if (trustVerifiedHop && credentials.astraId) {\n const hopRaw = req.headers[MCP_VERIFIED_HOP_HEADER.toLowerCase()];\n const hopValue =\n typeof hopRaw === 'string' ? hopRaw : Array.isArray(hopRaw) ? hopRaw[0] : undefined;\n const marker = parseVerifiedHop(hopValue);\n if (\n isVerifiedHopValidFor(marker, credentials.astraId, {\n ...(verifiedHopMaxAgeMs !== undefined ? { maxAgeMs: verifiedHopMaxAgeMs } : {}),\n })\n ) {\n return next();\n }\n }\n\n // v2.3.0: anonymous traffic no longer short-circuits client-side.\n // The server applies the endpoint's `unverifiedAgentPolicy` (deny /\n // allow_partial / allow_full) and emits the verification event +\n // blockchain record per the canonical flow. SDK forwards verbatim.\n\n // Resolve the canonical {purpose, action} pair (Bug 14, §4.6): dashboard\n // route mapping → custom extractors → agent X-Astra-* headers →\n // method-table fallback. The transport verb never travels as the action.\n const pdlssPair = resolveRequestPdlss(\n req,\n routeConfig,\n customExtractPurpose,\n customExtractAction\n );\n const purpose = pdlssPair.purpose;\n if (config.debug) {\n // Same telemetry shape as the MCP adapter — adoption tracking and\n // support triage read the *_source fields to see which integration\n // path each partner uses (route mapping vs headers vs fallback).\n // eslint-disable-next-line no-console\n console.debug('[express-middleware] pdlss resolved', {\n purpose_source: pdlssPair.purposeSource,\n resolved_purpose: pdlssPair.purpose,\n action_source: pdlssPair.actionSource,\n resolved_action: pdlssPair.action,\n });\n }\n\n // Extract full AstraSync credentials (includes PDLSS from X-Astra-* headers)\n const astraCreds = extractAstraSyncCredentials(req);\n\n // Auto-detect counterparty URL from the request if not explicitly configured.\n // Since the SDK is installed at this endpoint, we always know the origin.\n const counterpartyUrl = config.counterpartyUrl || `${req.protocol}://${req.get('host')}`;\n\n // Step 2: Counterparty-side PDLSS pre-check — compare agent's requested PDLSS\n // against counterparty-defined maximums on the route config.\n // Rejects immediately if outside limits, BEFORE calling verify-access.\n const preCheckFailures = performCounterpartyPreCheck(routeConfig, astraCreds, purpose);\n if (preCheckFailures.length > 0) {\n // Round-18 G4: counterparty pre-check failure — request rejected\n // before reaching verify-access. Neither identity nor policy was\n // remotely verified; both axes truthfully false.\n const result: VerificationResult = {\n identityVerified: false,\n policyAllowed: false,\n denialReasons: preCheckFailures.map((f) => f.message),\n guidance: {\n message: 'Request exceeds counterparty-defined PDLSS limits.',\n registrationUrl: wellKnownUrls?.registrationUrl ?? '',\n documentationUrl: wellKnownUrls?.documentationUrl ?? '',\n },\n verifiedAt: new Date(),\n };\n\n req.agentVerification = result;\n\n // Fire-and-forget: notify AstraSync of the pre-check failure\n reportCounterpartyPreCheckFailure(config, {\n agentId: astraCreds?.agentId || credentials.astraId || 'unknown',\n counterpartyUrl,\n counterpartyType: config.counterpartyType || 'api',\n failures: preCheckFailures,\n requestPath: req.path,\n requestMethod: req.method,\n }).catch(() => {});\n\n dedupeFailures(result);\n onDenied(result, req, res);\n return;\n }\n\n // Step 3: Call AstraSync verify-access with runtime challenge enabled\n const shouldRecordDecisions = recordDecisions !== false;\n const forwardedFor = req.headers['x-forwarded-for'];\n const forwardedForStr = Array.isArray(forwardedFor) ? forwardedFor.join(', ') : forwardedFor;\n // Audit F-A6-34: previously the LEFTMOST X-Forwarded-For entry was\n // taken as the original client IP. That value is attacker-controlled\n // whenever the customer's reverse proxy doesn't strip\n // client-supplied X-Forwarded-For — an attacker prepends\n // `X-Forwarded-For: 1.1.1.1` and we audit the spoofed IP. Now we\n // prefer req.ip (which Express resolves via configured `trust proxy`\n // hop count — the customer's responsibility to set correctly per\n // their actual hop chain). XFF still provides a fallback for\n // customers without `trust proxy` configured, but emits a one-time\n // warning when used so they know to fix.\n const originalClientIp =\n req.ip ?? (forwardedForStr ? forwardedForStr.split(',')[0].trim() : undefined);\n if (!req.ip && forwardedForStr) {\n // eslint-disable-next-line no-console\n console.warn(\n '[VerificationGateway] req.ip unset — falling back to leftmost X-Forwarded-For. ' +\n 'Configure Express trust proxy correctly to avoid spoofable client IPs in audit logs.'\n );\n }\n const agentCardUrl =\n typeof req.headers['x-astrasync-agent-card'] === 'string'\n ? (req.headers['x-astrasync-agent-card'] as string)\n : undefined;\n\n // P1 (SDK 3.5.0): when extractTransactionValue is configured, include\n // the value in verify-access so PDLSS limit evaluation runs at\n // middleware time. Must return major units (dollars, not cents).\n let txValue: number | undefined;\n let txCurrency: string | undefined;\n if (config.extractTransactionValue) {\n try {\n const extracted = config.extractTransactionValue(req);\n if (extracted) {\n txValue = extracted.value;\n txCurrency = extracted.currency;\n }\n } catch (e) {\n if (config.debug) {\n // eslint-disable-next-line no-console\n console.warn('[VerificationGateway] extractTransactionValue threw:', e);\n }\n }\n }\n\n // 5.8.0 attempt-chain (X-Astra-Attempt-Id): the bridge stamps the\n // interaction-chain id on every venue call (the edge pipeline already\n // reads it). Threading it into verify-access makes this hop part of the\n // SAME chain server-side, so a step-up the human already approved for\n // the chain passes here instead of minting a second approval — the\n // two-hop approval-loop fix. Invalid values are dropped, never sent.\n const attemptHeader = req.headers['x-astra-attempt-id'];\n const inboundAttemptId =\n typeof attemptHeader === 'string' && /^att_[0-9a-f]{32}$/.test(attemptHeader)\n ? attemptHeader\n : undefined;\n\n const verificationRequest: VerificationRequest = {\n credentials,\n purpose,\n action: pdlssPair.action,\n resource: req.path,\n createSession: shouldRecordDecisions,\n counterpartyUrl,\n counterpartyType: config.counterpartyType || 'api',\n enableRuntimeChallenge,\n durationRequired: astraCreds?.pdlss?.duration?.maxSessionDuration,\n ...(txValue !== undefined && { transactionValue: txValue }),\n ...(txCurrency && { currency: txCurrency }),\n ...(inboundAttemptId && { attemptId: inboundAttemptId }),\n callerMetadata: {\n sourceIp: originalClientIp,\n userAgent: req.headers['user-agent'] as string | undefined,\n referer: req.headers.referer as string | undefined,\n host: req.headers.host as string | undefined,\n forwardedFor: forwardedForStr,\n agentCardUrl,\n // Workstream D — capture EVERY inbound header (SDK-only merchants\n // have no edge to do it upstream) plus the CDN-derived connection\n // block. Local string work, secrets stripped; out of the verify\n // cache key so it doesn't defeat caching.\n observedMetadata: buildSdkObservedMetadata(req.headers),\n },\n };\n let result = await verify(config, verificationRequest);\n\n // Attach result to request\n req.agentVerification = result;\n let sessionId = (result as EnhancedVerificationResult).sessionId;\n\n // 3.6.0 hold-and-poll (opt-in via stepUpMaxWaitMs): HOLD a step-up\n // outcome, poll the approval, and on 'approved' re-verify the same\n // request once (cache-bypassed — the retry must reach the backend to\n // redeem the single-use approval). Every non-approved outcome falls\n // through to the existing fail-closed branches below with\n // result.stepUpOutcome stamped for the deny body.\n if (\n config.stepUpMaxWaitMs !== undefined &&\n result.policyAllowed &&\n requiresHumanApproval(result) &&\n result.stepUpApproval?.pollUrl\n ) {\n const outcome = await awaitStepUpApproval(config, result.stepUpApproval);\n res.setHeader('X-Astra-Step-Up', outcome);\n if (outcome === 'approved') {\n result = await verify(config, verificationRequest, { bypassCache: true });\n req.agentVerification = result;\n sessionId = (result as EnhancedVerificationResult).sessionId;\n } else {\n result.stepUpOutcome = outcome;\n }\n }\n\n // Denied verifications short-circuit here: failing either identity OR\n // policy already means \"deny.\" We check that first.\n // 4.5.0 (probe F1 follow-through): the gate is the SERVER's decision —\n // `policyAllowed` is true exactly when the backend allowed the call\n // (every deny/guidance/api-error shape sets it false), so gating on it\n // alone preserves the endpoint policy verbatim. `identityVerified` no\n // longer gates here: anonymous callers granted by an\n // audit/allow_partial/allow_full endpoint policy are honestly\n // identity-unverified yet server-allowed, and re-deriving a deny from\n // identity would override the backend evaluator (the SDK-pre-check\n // asymmetry antipattern). Identity still picks 401-vs-403 in the deny\n // body builder.\n // 5.12.0: fail posture follows success posture (edge-core parity). A\n // transient verification outage on an observe route, or on an\n // anonymous read (GET/HEAD, no credentials), passes through stamped\n // `X-Astra-Verification: unavailable`; enforced routes fall to\n // onDenied, whose default renders 503 + Retry-After (never 401).\n if (\n !result.policyAllowed &&\n isVerificationUnavailable(result) &&\n (!shouldEnforce || isAnonymousRead(req.method, credentials))\n ) {\n res.setHeader(VERIFICATION_STATUS_HEADER, 'unavailable');\n return next();\n }\n\n // Round-12 (F9): evaluation-without-enforcement. When the route is\n // observe but we ran verify-access for audit, skip the gates and call\n // next() — the result is on req.agentVerification for the handler\n // to render tier-aware responses (e.g. anonymous vs verified\n // catalog view on the same path).\n // 5.12.0 (round-27.4 D5, MCP parity): runs BEFORE the deny and step-up\n // branches — an observe route passes through regardless of the server\n // decision, as RouteAccessConfig.observe and evaluateAlwaysIfCredentialed\n // document. It used to run after them, so a credentialed request on an\n // observe route was vetoed.\n if (!shouldEnforce) {\n if (config.setPassThroughHeader) {\n res.setHeader('X-Astra-Gateway-Mode', 'enforced');\n res.setHeader('X-Astra-Gateway-Reason', 'evaluated-not-enforced');\n }\n if (shouldRecordDecisions && sessionId) {\n recordDecision(config, sessionId, 'granted').catch(() => {});\n }\n return next();\n }\n\n if (!result.policyAllowed) {\n if (shouldRecordDecisions && sessionId) {\n recordDecision(config, sessionId, 'denied', result.denialReasons?.[0]).catch(() => {});\n }\n dedupeFailures(result);\n onDenied(result, req, res);\n return;\n }\n\n // F2 direct-path fail-closed: an \"allowed-but-escalate\" outcome\n // (step-up / requires-approval, policyAllowed:true) cannot be completed\n // autonomously. The backend creates a step-up approval record and returns\n // it on `result.stepUpApproval`; deny here — symmetric with the bridge —\n // and surface the polling info in the deny response body.\n if (requiresHumanApproval(result)) {\n annotateApprovalRequired(result);\n if (shouldRecordDecisions && sessionId) {\n recordDecision(config, sessionId, 'denied', result.denialReasons?.[0]).catch(() => {});\n }\n dedupeFailures(result);\n onDenied(result, req, res);\n return;\n }\n\n // The access decision is the server's (identityVerified / policyAllowed,\n // above) — resting on a verified ID + runtime challenge + PDLSS match +\n // trust score. The only client-side refinement is the per-route trust\n // floor below; there is no access-level band (removed in SDK 5.0.0).\n\n // Per-route trust tightening (only refinement that still gates).\n if (routeConfig.minTrustScore && result.agent) {\n if (result.agent.trustScore < routeConfig.minTrustScore) {\n // 3.2.0: qualitative — never embed the score or the threshold in an\n // agent-visible message (trust is a system-internal signal; exposing\n // the number is a gaming vector — post-3.1.0 feedback #2).\n const trustFailure = {\n dimension: 'endpoint.trust',\n message: 'Trust below the route requirement for this endpoint.',\n guidance:\n \"Trust is below this route's floor. Trust is not overridable — the agent either meets the endpoint's trust policy or it doesn't. Raise the agent's trust via real signals (KYD, blockchain registration, agent-card), or have the operator lower the route's minTrustScore.\",\n };\n result.failures = [...(result.failures ?? []), trustFailure];\n result.denialReasons = [trustFailure.message];\n if (!result.guidance && wellKnownUrls) {\n result.guidance = {\n message: trustFailure.message,\n registrationUrl: wellKnownUrls.registrationUrl,\n documentationUrl: wellKnownUrls.documentationUrl,\n };\n }\n if (shouldRecordDecisions && sessionId) {\n recordDecision(config, sessionId, 'denied', trustFailure.message).catch(() => {});\n }\n dedupeFailures(result);\n onDenied(result, req, res);\n return;\n }\n }\n\n // All checks passed — record grant decision\n if (shouldRecordDecisions && sessionId) {\n recordDecision(config, sessionId, 'granted').catch(() => {});\n }\n // v2.3.8 (defect #26): if the endpoint's `unverifiedAgentPolicy` is\n // `'audit'` (allow + soft-launch warning), the server returns the\n // header to relay. Lift it onto the merchant's response BEFORE\n // calling next() so downstream handlers and the eventual response\n // back to the agent both carry it.\n const enhancedResult = result as EnhancedVerificationResult;\n if (enhancedResult.warningHeader) {\n res.setHeader(enhancedResult.warningHeader.name, enhancedResult.warningHeader.value);\n }\n next();\n } catch (error) {\n // Audit F-A1-06: shadow-mode logging for fail-closed default migration.\n // Always log `[SHADOW] would-have-denied` so merchants can grep their\n // own application logs for would-have-been-denied impact during the\n // observation window. Actual deny/admit behavior controlled by\n // failOnError option (default 'open' for backward compatibility).\n const errorClass = error instanceof Error ? error.constructor.name : typeof error;\n const correlationId =\n (req.headers['x-request-id'] as string | undefined) ||\n (req.headers['x-correlation-id'] as string | undefined) ||\n `gen-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n // eslint-disable-next-line no-console\n console.error('[VerificationGateway] Middleware error:', error);\n // eslint-disable-next-line no-console\n console.warn(\n `[SHADOW] would-have-denied: errorClass=${errorClass} route=${req.method}:${req.path} merchantId=${config.counterpartyId ?? 'unknown'} correlationId=${correlationId}`\n );\n\n if (failOnError === 'closed') {\n // 5.12.0: an internal exception is a verification outage, not an\n // identity verdict — the agent was never evaluated. The\n // `middleware.internal_error` dimension is one of the failure-posture\n // UNAVAILABLE_DIMENSIONS, so the default onDenied answers 503 +\n // Retry-After + VERIFICATION_UNAVAILABLE (previously an\n // identity-shaped 401 UNAUTHORIZED with registration guidance).\n // Custom onDenied handlers can detect it via isVerificationUnavailable.\n const result: VerificationResult = {\n identityVerified: false,\n policyAllowed: false,\n denialReasons: [`Verification middleware internal error: ${errorClass}`],\n failures: [\n {\n dimension: 'middleware.internal_error',\n message: `Middleware threw ${errorClass} — failing closed`,\n },\n ],\n verifiedAt: new Date(),\n correlationId,\n };\n dedupeFailures(result);\n return onDenied(result, req, res);\n }\n\n next();\n }\n };\n}\n\n// `requireAccess` and `verifyOnly` were removed in v2.9.7. Both injected a\n// local `routes` array into the merchant's source code, which is the exact\n// dual-config attack vector defect 24 closed. Per-route policy now lives in\n// the AstraSync dashboard (gated by team.role admin auth + audit + alerts).\n// To tighten a route, set its `minTrustScore` (+ purpose/jurisdiction/value\n// gates) in the dashboard. For \"verify but don't block,\" set the route to\n// `observe` (or run the endpoint in an audit `unverifiedAgentPolicy`).\n"],"mappings":";AAkBO,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,SAAS,cAAc,MAAM,OAAO,EAAE,CAAC;;;ACpBjE,IAAM,2BAA2B;AACjC,IAAM,uBAAuB;AAC7B,IAAM,uBAAuB,IAAI,KAAK;AACtC,IAAM,kBAAkB;AACxB,IAAM,0BAA0B;AAMhC,SAAS,eAAe,QAAuB,SAAyB;AACtE,MAAI,QAAQ,WAAW,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