{"version":3,"file":"browser-posture-B0XCcAMO.mjs","names":[],"sources":["../src/browser-posture.ts"],"sourcesContent":["import {\n  postureOutcomeFromRequest,\n  postureOutcomeReport,\n  postureRequiredScopes,\n  postureUpgrade,\n  type BrowserPosture,\n  type BrowserPostureConfig,\n  type BrowserPostureOutcome,\n  type PostureRequest,\n  type PostureVerification,\n} from '@kya-os/checkpoint-shared/browser-posture';\nimport type { ChallengeWireInput } from '@kya-os/checkpoint-shared';\nimport type { VerifyResult } from './engine/types';\n\n// Host-only facts, outside the engine ABI. A JSON/header payload cannot set a\n// symbol property. Symbol.for also shares the fact across bundled subpaths.\nconst POSTURE = Symbol.for('checkpoint.verified-browser-posture.v1');\nconst OUTCOME = Symbol.for('checkpoint.browser-posture-outcome.v1');\nconst STEP_UP = Symbol.for('checkpoint.browser-integrity-step-up.v1');\ntype PostureResult = VerifyResult & {\n  [POSTURE]?: BrowserPosture;\n  [OUTCOME]?: BrowserPostureOutcome;\n  [STEP_UP]?: string[];\n};\nexport const BROWSER_INTEGRITY_POLICY = 'browser-integrity-step-up';\n\nexport function verifiedBrowserPosture(result: VerifyResult): BrowserPosture | undefined {\n  return (result as PostureResult)[POSTURE];\n}\n\nexport function browserPostureOutcome(result: VerifyResult): BrowserPostureOutcome | undefined {\n  return (result as PostureResult)[OUTCOME];\n}\n\nexport type PostureHandlerView = BrowserPostureOutcome & { posture?: BrowserPosture };\n\nexport function postureHandlerView(result: VerifyResult): PostureHandlerView | undefined {\n  const outcome = browserPostureOutcome(result);\n  if (!outcome) return undefined;\n  const posture = verifiedBrowserPosture(result);\n  return postureOutcomeView(\n    posture\n      ? { status: 'verified', posture }\n      : (outcome as Exclude<PostureVerification, { status: 'verified' }>)\n  );\n}\n\nexport function postureOutcomeView(outcome: PostureVerification): PostureHandlerView {\n  return Object.freeze(\n    outcome.status === 'verified'\n      ? { status: 'verified' as const, posture: deepFreeze(structuredClone(outcome.posture)) }\n      : { ...postureOutcomeReport(outcome) }\n  );\n}\n\nfunction deepFreeze<T extends object>(value: T): T {\n  for (const child of Object.values(value)) {\n    if (child !== null && typeof child === 'object') deepFreeze(child);\n  }\n  return Object.freeze(value);\n}\n\n/**\n * Verify risk locally before projecting facts into Cedar. Never supplies\n * identity. `request` is the request's `KYA-Posture` headers and cookies\n * (`postureRequestFromHeaders`), or a bare `Cookie` header value.\n */\nexport async function applyBrowserPosture(\n  result: VerifyResult,\n  request: PostureRequest | string | undefined | null,\n  config: BrowserPostureConfig | undefined,\n  projectId: string | undefined\n): Promise<void> {\n  if (!config || !projectId) return;\n  const outcome = await postureOutcomeFromRequest(\n    typeof request === 'object' && request !== null ? request : { cookie: request },\n    config,\n    projectId\n  );\n  (result as PostureResult)[OUTCOME] = postureOutcomeReport(outcome);\n  if (outcome.status !== 'verified') return;\n  (result as PostureResult)[POSTURE] = outcome.posture;\n  classifyBrowserPosture(result, outcome.posture);\n}\n\nconst ENGINE_CLASS = {\n  ai_agent: { type: 'AiAgent' },\n  bot: { type: 'Bot' },\n  incomplete_data: { type: 'IncompleteData' },\n} as const;\n\nfunction classifyBrowserPosture(result: VerifyResult, posture: BrowserPosture): void {\n  const detail = result.detectionDetail;\n  const upgrade = postureUpgrade(posture);\n  if (\n    !upgrade ||\n    result.decision.kind === 'Block' ||\n    detail.isAgent ||\n    !['Human', 'IncompleteData'].includes(detail.detectionClass.type)\n  )\n    return;\n  result.detectionDetail = {\n    ...detail,\n    isAgent: upgrade.isAgent,\n    detectionClass: ENGINE_CLASS[upgrade.detectionClass],\n    ...(upgrade.agentName\n      ? {\n          agentType: upgrade.agentName,\n          detectedAgent: { type: upgrade.detectionClass, name: upgrade.agentName },\n        }\n      : {}),\n    confidence: upgrade.confidence,\n    verificationMethod: upgrade.verificationMethod,\n    reasons: [...detail.reasons, ...upgrade.reasons],\n    ...(detail.metadata?.detection_basis === 'no_evidence'\n      ? { metadata: { ...detail.metadata, detection_basis: 'posture_evidence' } }\n      : {}),\n  };\n}\n\n/** Restrictive default after tenant policy: existing denials/challenges survive.\n * Only a verified signed delegation covering the designated scopes satisfies consent.\n * The consent mint is attested-bearer; a tenant may require a higher floor.\n * Missing/invalid risk evidence never creates a Permit decision.\n */\nexport function applyBrowserIntegrityStepUp(\n  result: VerifyResult,\n  config: BrowserPostureConfig | undefined,\n  path: string\n): void {\n  const posture = verifiedBrowserPosture(result);\n  if (\n    !config ||\n    !posture ||\n    posture.verdict !== 'agent-driven' ||\n    result.decision.kind !== 'Permit'\n  )\n    return;\n  const scopes = postureRequiredScopes(config, path);\n  if (!scopes) return;\n  const detail = result.detectionDetail;\n  if (\n    ['delegated', 'attested-bearer'].includes(detail.assurance ?? '') &&\n    scopes.every((scope) => detail.grantedScopes?.includes(scope))\n  )\n    return;\n  (result as PostureResult)[STEP_UP] = [...scopes];\n  result.decision = {\n    kind: 'Challenge',\n    params: {\n      nonce: crypto.randomUUID(),\n      // A loopback-only config has no origin: the audience is then the page\n      // origin the posture token was verified for.\n      audience: config.origin ?? posture.origin,\n      expiresAt: Math.floor(Date.now() / 1000) + 120,\n      algorithmsAccepted: ['ES256', 'EdDSA'],\n      minAssurance: 'attested-bearer',\n      policyId: BROWSER_INTEGRITY_POLICY,\n    },\n  };\n}\n\nexport function browserIntegrityChallengeScopes(\n  result: VerifyResult\n): readonly string[] | undefined {\n  return (result as PostureResult)[STEP_UP];\n}\n\n/** Registration must demand the same scopes; never fabricate a consent URL\n * or mutate a signed challenge after registration. Absent context renders 503.\n */\nexport function validateBrowserIntegrityChallenge(\n  result: VerifyResult,\n  context: ChallengeWireInput | undefined\n): ChallengeWireInput | undefined {\n  const scopes = browserIntegrityChallengeScopes(result);\n  if (!scopes) return context;\n  return context && scopes.every((s) => context.requiredScopes?.includes(s)) ? context : undefined;\n}\n"],"mappings":";;AAgBA,MAAM,UAAU,OAAO,IAAI,wCAAwC;AACnE,MAAM,UAAU,OAAO,IAAI,uCAAuC;AAClE,MAAM,UAAU,OAAO,IAAI,yCAAyC;AAMpE,MAAa,2BAA2B;AAExC,SAAg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