{"version":3,"file":"presented-credential-pqNquw3n.mjs","names":[],"sources":["../src/engine/orchestrator/presented-credential.ts"],"sourcesContent":["/**\n * What the orchestrators read from the engine's verdict on a presented\n * credential, and the carriages they refuse before calling it.\n *\n * draft-kya-http-02's downgrade-attack defense, \"absent demotes, invalid\n * rejects\", is the engine's: it blocks a presented KYA credential it cannot\n * verify, with the precise `kyaos/*` code on `metadata.kya_error_code`, and\n * never demotes one to an anonymous Permit. The presented-credential parity\n * vectors (tests/cross-runtime-parity/presented-credential/) pin that in every\n * runtime, so the orchestrators return the engine's decision as it is.\n */\n\nimport {\n  KYA_HTTP_ERROR,\n  KYA_HTTP_ERROR_STATUS,\n  REGISTERED_SID_MAX_LENGTH,\n  type KyaHttpErrorCode,\n} from '@kya-os/checkpoint-shared/kya-http';\n\nimport type { AgentRequest, BearerDelegationIdentity, VerifyResult } from '../types';\n\nimport type { BearerDelegationCredentialRef } from './build-agent-request';\nimport type { IncomingHttpLike } from './types';\n\n/**\n * #3388 — the identity-pending reject code: a presented kya credential whose\n * trusted roots are not yet warm. Retryable (renders 503 + Retry-After); distinct\n * from a confirmed §9 verify failure.\n */\nexport const KYA_IDENTITY_PENDING = 'kyaos/identity-pending';\n\n/**\n * Whether the engine refuses this request as an unsupported carriage\n * (`kyaos/unsupported-carriage`) without resolving anything: an MCP-I\n * envelope, or a request carrying `KYA-OS-Delegation-Credential` or\n * `KYA-OS-Delegation-Proof`, which only the engine's native propagation lane\n * verifies, and these orchestrators do not configure that lane. They fetch\n * nothing such a request names. Header presence alone counts, as in the\n * engine. A host that configures the native lane must narrow this, or its\n * requests reach the engine without their documents and fail closed.\n */\nexport function isRefusedDelegationCarriage(\n  req: IncomingHttpLike,\n  agentRequest: AgentRequest\n): boolean {\n  if (agentRequest.protocol === 'McpI') return true;\n  return Object.keys(req.headers).some((name) =>\n    PROPAGATION_ARTIFACT_HEADERS.has(name.toLowerCase())\n  );\n}\n\nconst PROPAGATION_ARTIFACT_HEADERS: ReadonlySet<string> = new Set([\n  'kya-os-delegation-credential',\n  'kya-os-delegation-proof',\n]);\n\n/**\n * Read the engine's `metadata.kya_error_code` ONLY when it's a well-formed §9\n * registry code — an arbitrary string is never trusted onto the wire.\n */\nexport function readKyaErrorCode(\n  metadata: Record<string, unknown> | undefined\n): KyaHttpErrorCode | undefined {\n  const raw = metadata?.['kya_error_code'];\n  if (typeof raw !== 'string') return undefined;\n  return KYA_ERROR_CODES.has(raw) ? (raw as KyaHttpErrorCode) : undefined;\n}\n\n/**\n * Read the engine's `metadata.kya_session_id`: the draft-kya-http-02 registered\n * session anchor (the presented credential's `sid` claim), passthrough from\n * `detection_detail.metadata` on the Rust side\n * (`rust/crates/kya-os-engine/src/api.rs`, `bearer_delegation_verified_detail` and the\n * Tier-1 kya-http/2-signed success path). The engine stamps this ONLY on a\n * successfully verified presentation; never on a reject, and never on a demotion\n * (D15 of the flow-lab-customer-delegation-timeline plan). A non-string or empty value\n * is treated as absent, mirroring `readKyaErrorCode`'s refusal to trust an\n * unrecognised shape onto the wire. The trim + `REGISTERED_SID_MAX_LENGTH` bound also\n * guards the wire schema's own constraint (`ReportedDelegationSchema.sid` is\n * `NonEmptyTrimmed.max(REGISTERED_SID_MAX_LENGTH)`): the Rust extraction only checks\n * `is_empty()`, so a malformed-but-validly-signed credential could otherwise produce a\n * whitespace-only or over-length sid that reaches the wire and 400s the whole\n * detection at `LogDetectionRequestSchema.parse()`, the same hazard `sanitizeEngineInfo`\n * guards against for `rulesetHash`.\n */\nexport function readVerifiedDelegationSid(\n  metadata: Record<string, unknown> | undefined\n): string | undefined {\n  const raw = metadata?.['kya_session_id'];\n  if (typeof raw !== 'string') return undefined;\n  const trimmed = raw.trim();\n  return trimmed.length > 0 && trimmed.length <= REGISTERED_SID_MAX_LENGTH ? trimmed : undefined;\n}\n\n/**\n * Read the engine's `metadata.agent_did`: the leaf agent DID the engine attributes a\n * Tier-1 cryptographically verified presentation to (kya-http/2-signed OR standalone\n * bearer delegation; both write this key on their verified path, see\n * `rust/crates/kya-os-engine/src/api.rs` lines ~1868 and ~2010-2019). Same passthrough\n * + guard shape as {@link readVerifiedDelegationSid}. Independent of whether a sid is\n * also present: a verified identity signature can exist without a delegation-bearing\n * sid. Also enforces the wire schema's `did:` prefix shape (`DidStringSchema`): the\n * Rust extraction has no DID-shape check on `agent_did`/`sub` at all, so a\n * non-`did:`-prefixed value is dropped here rather than sent onto the wire, avoiding\n * the same 400-the-whole-detection hazard as above.\n */\nexport function readVerifiedAgentDid(\n  metadata: Record<string, unknown> | undefined\n): string | undefined {\n  const raw = metadata?.['agent_did'];\n  if (typeof raw !== 'string') return undefined;\n  const trimmed = raw.trim();\n  return isDidShaped(trimmed) ? trimmed : undefined;\n}\n\n/**\n * Guard for wire fields typed `DidStringSchema` (`ReportedIdentitySchema` in\n * `@kya-os/checkpoint-shared`, requires a `did:`-prefixed string). Shared by\n * `readVerifiedAgentDid` above (an engine-metadata value) and, via export,\n * `reporter/index.ts`'s bearer-delegation identity merge (a decoded-but-not-\n * re-verified credential claim) — one DID-shape rule for the wire, not two\n * independently-maintained copies.\n */\nexport function isDidShaped(value: string): boolean {\n  return /^did:/.test(value);\n}\n\n/**\n * The §9 HTTP status for a `kyaos/*` code, read from the registry\n * (`KYA_HTTP_ERROR_STATUS`, pinned to error-codes.json). The retryable 503\n * codes (e.g. kyaos/status-pending, #3345) and the 429 replay-capacity code\n * tell a client to back off and retry, not to treat the reject as terminal.\n * The engine renders from the same table (`render/kya_error.rs`).\n */\nexport function statusForKyaError(code: KyaHttpErrorCode): number {\n  return KYA_HTTP_ERROR_STATUS[code];\n}\n\n/** True for the statuses that carry `Retry-After`: 503 and 429. */\nexport function isRetryableKyaStatus(status: number): boolean {\n  return status === 503 || status === 429;\n}\n\n/**\n * KYA-1099 W1 — attach the observed bearer delegation's `agentDid` / `jti` /\n * `iss` plus a `verified` flag (from the decision the orchestrator returns)\n * onto the result an orchestrator is about to return. No-op (returns\n * `result` unchanged, same reference) when the request never carried a\n * bearer delegation — every existing caller is unaffected. Shared by BOTH\n * orchestrators (edge and node) so a request\n * presenting a standalone bearer delegation resolves to the same identity\n * regardless of which runtime handled it — see the module header's sync\n * requirement between `verify-request.ts` and `verify-request-edge.ts`.\n */\nexport function withBearerDelegationIdentity(\n  result: VerifyResult,\n  bearerDelegation: BearerDelegationCredentialRef | null\n): VerifyResult {\n  if (!bearerDelegation) return result;\n  const handle = credentialHandle(bearerDelegation.claims);\n  const bearerDelegationIdentity: BearerDelegationIdentity = {\n    ...(bearerDelegation.agentDid ? { agentDid: bearerDelegation.agentDid } : {}),\n    ...(handle ? { jti: handle } : {}),\n    ...(bearerDelegation.issuer ? { iss: bearerDelegation.issuer } : {}),\n    verified: result.decision.kind === 'Permit',\n  };\n  return { ...result, bearerDelegationIdentity };\n}\n\n// -----------------------------------------------------------------------------\n// Internals.\n// -----------------------------------------------------------------------------\n\n/**\n * The credential handle a verifier keys budgets, blocks and revocations on:\n * `vc.id`, else the JWT `jti`. An org-issued delegation carries one\n * credential id per delegation as `vc.id` and no `jti`.\n */\nfunction credentialHandle(claims: Record<string, unknown>): string | undefined {\n  const vc = claims['vc'];\n  const vcId =\n    typeof vc === 'object' && vc !== null ? (vc as Record<string, unknown>)['id'] : undefined;\n  if (typeof vcId === 'string' && vcId.length > 0) return vcId;\n  const jti = claims['jti'];\n  return typeof jti === 'string' && jti.length > 0 ? jti : undefined;\n}\n\nconst KYA_ERROR_CODES: ReadonlySet<string> = new Set(Object.values(KYA_HTTP_ERROR));\n"],"mappings":";;;;;;;;;;;;;;;;;;AA6BA,MAAa,uBAAuB;;;;;;;;;;;AAYpC,SAAgB,4BACd,KACA,cACS;CACT,IAAI,aAAa,aAAa,QAAQ,OAAO;CAC7C,OAAO,OAAO,KAAK,IAAI,OAAO,CAAC,CAAC,MAAM,SACpC,6BAA6B,IAAI,KAAK,YAAY,CAAC,CACrD;AACF;AAEA,MAAM,+CAAoD,IAAI,IAAI,CAChE,gCACA,yBACF,CAAC;;;;;AAMD,S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