@codemem/core 0.47.4 → 0.48.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/admission-budget-adapter-test-fixtures.d.ts +68 -0
- package/dist/admission-budget-adapter-test-fixtures.d.ts.map +1 -0
- package/dist/admission-budget-adapters.d.ts +28 -0
- package/dist/admission-budget-adapters.d.ts.map +1 -0
- package/dist/admission-budget-allocation-schema-test-fixtures.d.ts +23 -0
- package/dist/admission-budget-allocation-schema-test-fixtures.d.ts.map +1 -0
- package/dist/admission-budget-allocation-schema.d.ts +5 -0
- package/dist/admission-budget-allocation-schema.d.ts.map +1 -0
- package/dist/admission-budget-schema.d.ts +3 -0
- package/dist/admission-budget-schema.d.ts.map +1 -0
- package/dist/admission-budget-test-fixtures.d.ts +31 -0
- package/dist/admission-budget-test-fixtures.d.ts.map +1 -0
- package/dist/admission-budget.d.ts +28 -0
- package/dist/admission-budget.d.ts.map +1 -0
- package/dist/better-sqlite-coordinator-runtime.d.ts +9 -0
- package/dist/better-sqlite-coordinator-runtime.d.ts.map +1 -1
- package/dist/better-sqlite-coordinator-store.d.ts +13 -11
- package/dist/better-sqlite-coordinator-store.d.ts.map +1 -1
- package/dist/coordinator-account-link-headless-runtime.d.ts +38 -0
- package/dist/coordinator-account-link-headless-runtime.d.ts.map +1 -0
- package/dist/coordinator-account-link-headless-test-fixtures.d.ts +60 -0
- package/dist/coordinator-account-link-headless-test-fixtures.d.ts.map +1 -0
- package/dist/coordinator-account-link-runtime.d.ts +70 -2
- package/dist/coordinator-account-link-runtime.d.ts.map +1 -1
- package/dist/coordinator-api.d.ts +6 -0
- package/dist/coordinator-api.d.ts.map +1 -1
- package/dist/coordinator-auth-browser-style.d.ts +1 -1
- package/dist/coordinator-auth-browser-style.d.ts.map +1 -1
- package/dist/coordinator-auth-browser-transaction.d.ts +4 -0
- package/dist/coordinator-auth-browser-transaction.d.ts.map +1 -1
- package/dist/coordinator-auth-browser-view.d.ts +7 -0
- package/dist/coordinator-auth-browser-view.d.ts.map +1 -1
- package/dist/coordinator-auth-headless-code-limits.d.ts +42 -0
- package/dist/coordinator-auth-headless-code-limits.d.ts.map +1 -0
- package/dist/coordinator-auth-headless-provenance.d.ts +46 -0
- package/dist/coordinator-auth-headless-provenance.d.ts.map +1 -0
- package/dist/coordinator-auth-headless-schema.d.ts +23 -0
- package/dist/coordinator-auth-headless-schema.d.ts.map +1 -0
- package/dist/coordinator-auth-headless-view.d.ts +33 -0
- package/dist/coordinator-auth-headless-view.d.ts.map +1 -0
- package/dist/coordinator-auth-historical-store-test-fixture.d.ts.map +1 -1
- package/dist/coordinator-auth-key-fingerprint.d.ts +8 -0
- package/dist/coordinator-auth-key-fingerprint.d.ts.map +1 -0
- package/dist/coordinator-auth-link-contract.d.ts +6 -0
- package/dist/coordinator-auth-link-contract.d.ts.map +1 -1
- package/dist/coordinator-auth-link-headless-test-fixtures.d.ts +105 -0
- package/dist/coordinator-auth-link-headless-test-fixtures.d.ts.map +1 -0
- package/dist/coordinator-auth-link-headless.d.ts +78 -0
- package/dist/coordinator-auth-link-headless.d.ts.map +1 -0
- package/dist/coordinator-auth-link.d.ts +25 -0
- package/dist/coordinator-auth-link.d.ts.map +1 -1
- package/dist/coordinator-auth-session.d.ts.map +1 -1
- package/dist/coordinator-browser-auth-app.d.ts +9 -1
- package/dist/coordinator-browser-auth-app.d.ts.map +1 -1
- package/dist/coordinator-browser-csrf.d.ts +8 -0
- package/dist/coordinator-browser-csrf.d.ts.map +1 -1
- package/dist/coordinator-browser-form-body.d.ts +6 -1
- package/dist/coordinator-browser-form-body.d.ts.map +1 -1
- package/dist/coordinator-browser-form-guard.d.ts +5 -0
- package/dist/coordinator-browser-form-guard.d.ts.map +1 -1
- package/dist/coordinator-browser-headless-link.d.ts +33 -0
- package/dist/coordinator-browser-headless-link.d.ts.map +1 -0
- package/dist/coordinator-browser-link-completion.d.ts +2 -1
- package/dist/coordinator-browser-link-completion.d.ts.map +1 -1
- package/dist/coordinator-browser-link.d.ts +4 -1
- package/dist/coordinator-browser-link.d.ts.map +1 -1
- package/dist/coordinator-device-auth-link.d.ts +46 -3
- package/dist/coordinator-device-auth-link.d.ts.map +1 -1
- package/dist/coordinator-device-headless-link-test-fixtures.d.ts +117 -0
- package/dist/coordinator-device-headless-link-test-fixtures.d.ts.map +1 -0
- package/dist/coordinator-device-headless-link.d.ts +23 -0
- package/dist/coordinator-device-headless-link.d.ts.map +1 -0
- package/dist/coordinator-device-rebind-ceremony.d.ts +9 -1
- package/dist/coordinator-device-rebind-ceremony.d.ts.map +1 -1
- package/dist/coordinator-device-rebind-commit.d.ts.map +1 -1
- package/dist/coordinator-device-rebind-http.d.ts.map +1 -1
- package/dist/coordinator-device-rebind-view.d.ts +1 -1
- package/dist/coordinator-device-rebind-view.d.ts.map +1 -1
- package/dist/coordinator-owner-enrollment-commit.d.ts.map +1 -1
- package/dist/coordinator-owner-enrollment-http.d.ts.map +1 -1
- package/dist/coordinator-owner-enrollment-start-test-fixtures.d.ts.map +1 -1
- package/dist/coordinator-relay-admission-route-test-fixtures.d.ts +52 -0
- package/dist/coordinator-relay-admission-route-test-fixtures.d.ts.map +1 -0
- package/dist/coordinator-relay-admission-route.d.ts +47 -0
- package/dist/coordinator-relay-admission-route.d.ts.map +1 -0
- package/dist/coordinator-relay-info.d.ts +16 -0
- package/dist/coordinator-relay-info.d.ts.map +1 -0
- package/dist/coordinator-runtime-ZLZ8uDtd.js +593 -0
- package/dist/coordinator-runtime-ZLZ8uDtd.js.map +1 -0
- package/dist/coordinator-runtime.d.ts +26 -0
- package/dist/coordinator-runtime.d.ts.map +1 -1
- package/dist/coordinator-sync-config.d.ts +8 -0
- package/dist/coordinator-sync-config.d.ts.map +1 -1
- package/dist/d1-coordinator-runtime.d.ts +9 -0
- package/dist/d1-coordinator-runtime.d.ts.map +1 -1
- package/dist/d1-coordinator-store.d.ts +13 -0
- package/dist/d1-coordinator-store.d.ts.map +1 -1
- package/dist/db.d.ts.map +1 -1
- package/dist/embeddings.d.ts.map +1 -1
- package/dist/index.d.ts +10 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +11596 -19341
- package/dist/index.js.map +1 -1
- package/dist/ingest-pipeline.d.ts +3 -0
- package/dist/ingest-pipeline.d.ts.map +1 -1
- package/dist/internal/cloudflare-coordinator.d.ts +4 -0
- package/dist/internal/cloudflare-coordinator.d.ts.map +1 -1
- package/dist/internal/cloudflare-coordinator.js +1521 -1164
- package/dist/internal/cloudflare-coordinator.js.map +1 -1
- package/dist/internal/relay-host.d.ts +7 -0
- package/dist/internal/relay-host.d.ts.map +1 -0
- package/dist/internal/relay-host.js +4 -0
- package/dist/internal/relay-runtime.d.ts +13 -0
- package/dist/internal/relay-runtime.d.ts.map +1 -0
- package/dist/internal/relay-runtime.js +339 -0
- package/dist/internal/relay-runtime.js.map +1 -0
- package/dist/maintenance/init-vacuum.d.ts.map +1 -1
- package/dist/maintenance-jobs.d.ts.map +1 -1
- package/dist/memory-reference-schema.d.ts +3 -0
- package/dist/memory-reference-schema.d.ts.map +1 -0
- package/dist/observer-config.d.ts.map +1 -1
- package/dist/{owner-enrollment-start-DHh8A5hh.js → owner-enrollment-start-DFVkODlJ.js} +3658 -2339
- package/dist/owner-enrollment-start-DFVkODlJ.js.map +1 -0
- package/dist/owner-enrollment-start.d.ts +6 -0
- package/dist/owner-enrollment-start.d.ts.map +1 -1
- package/dist/owner-qualified-headless-test-harness.d.ts +4 -0
- package/dist/owner-qualified-headless-test-harness.d.ts.map +1 -0
- package/dist/peer-http-client-lifecycle.d.ts +30 -0
- package/dist/peer-http-client-lifecycle.d.ts.map +1 -0
- package/dist/peer-http-client.d.ts +24 -0
- package/dist/peer-http-client.d.ts.map +1 -0
- package/dist/peer-http-headers.d.ts +19 -0
- package/dist/peer-http-headers.d.ts.map +1 -0
- package/dist/peer-http-policy.d.ts +13 -0
- package/dist/peer-http-policy.d.ts.map +1 -0
- package/dist/peer-http-server-response.d.ts +9 -0
- package/dist/peer-http-server-response.d.ts.map +1 -0
- package/dist/peer-http-server-test-fixtures.d.ts +34 -0
- package/dist/peer-http-server-test-fixtures.d.ts.map +1 -0
- package/dist/peer-http-server.d.ts +24 -0
- package/dist/peer-http-server.d.ts.map +1 -0
- package/dist/peer-http-test-fixtures.d.ts +40 -0
- package/dist/peer-http-test-fixtures.d.ts.map +1 -0
- package/dist/peer-http-wire-audit.d.ts +33 -0
- package/dist/peer-http-wire-audit.d.ts.map +1 -0
- package/dist/peer-traversal-carrier.d.ts +21 -0
- package/dist/peer-traversal-carrier.d.ts.map +1 -0
- package/dist/peer-traversal-coordinator-attempt-schema.d.ts +3 -0
- package/dist/peer-traversal-coordinator-attempt-schema.d.ts.map +1 -0
- package/dist/peer-traversal-coordinator-attempt-write-test-fixtures.d.ts +53 -0
- package/dist/peer-traversal-coordinator-attempt-write-test-fixtures.d.ts.map +1 -0
- package/dist/peer-traversal-coordinator-attempt-write.d.ts +37 -0
- package/dist/peer-traversal-coordinator-attempt-write.d.ts.map +1 -0
- package/dist/peer-traversal-coordinator-client-test-fixtures.d.ts +37 -0
- package/dist/peer-traversal-coordinator-client-test-fixtures.d.ts.map +1 -0
- package/dist/peer-traversal-coordinator-client.d.ts +48 -0
- package/dist/peer-traversal-coordinator-client.d.ts.map +1 -0
- package/dist/peer-traversal-coordinator-decision-test-fixtures.d.ts +30 -0
- package/dist/peer-traversal-coordinator-decision-test-fixtures.d.ts.map +1 -0
- package/dist/peer-traversal-coordinator-decision.d.ts +58 -0
- package/dist/peer-traversal-coordinator-decision.d.ts.map +1 -0
- package/dist/peer-traversal-coordinator-metadata-schema-test-fixtures.d.ts +3 -0
- package/dist/peer-traversal-coordinator-metadata-schema-test-fixtures.d.ts.map +1 -0
- package/dist/peer-traversal-coordinator-metadata-schema.d.ts +9 -0
- package/dist/peer-traversal-coordinator-metadata-schema.d.ts.map +1 -0
- package/dist/peer-traversal-coordinator-phase-write-test-fixtures.d.ts +24 -0
- package/dist/peer-traversal-coordinator-phase-write-test-fixtures.d.ts.map +1 -0
- package/dist/peer-traversal-coordinator-schema-common-test-fixtures.d.ts +21 -0
- package/dist/peer-traversal-coordinator-schema-common-test-fixtures.d.ts.map +1 -0
- package/dist/peer-traversal-coordinator-schema-test-fixtures.d.ts +12 -0
- package/dist/peer-traversal-coordinator-schema-test-fixtures.d.ts.map +1 -0
- package/dist/peer-traversal-coordinator-schema.d.ts +3 -0
- package/dist/peer-traversal-coordinator-schema.d.ts.map +1 -0
- package/dist/peer-traversal-coordinator-write-sql.d.ts +30 -0
- package/dist/peer-traversal-coordinator-write-sql.d.ts.map +1 -0
- package/dist/peer-traversal-frame.d.ts +32 -0
- package/dist/peer-traversal-frame.d.ts.map +1 -0
- package/dist/peer-traversal-noise-transport.d.ts +29 -0
- package/dist/peer-traversal-noise-transport.d.ts.map +1 -0
- package/dist/peer-traversal-noise.d.ts +30 -0
- package/dist/peer-traversal-noise.d.ts.map +1 -0
- package/dist/peer-traversal-rendezvous-test-fixtures.d.ts +105 -0
- package/dist/peer-traversal-rendezvous-test-fixtures.d.ts.map +1 -0
- package/dist/peer-traversal-signal-chain.d.ts +26 -0
- package/dist/peer-traversal-signal-chain.d.ts.map +1 -0
- package/dist/peer-traversal-signal-codec.d.ts +67 -0
- package/dist/peer-traversal-signal-codec.d.ts.map +1 -0
- package/dist/peer-traversal-signal-proof.d.ts +22 -0
- package/dist/peer-traversal-signal-proof.d.ts.map +1 -0
- package/dist/peer-traversal-stream-test-fixtures.d.ts +44 -0
- package/dist/peer-traversal-stream-test-fixtures.d.ts.map +1 -0
- package/dist/peer-traversal-stream.d.ts +91 -0
- package/dist/peer-traversal-stream.d.ts.map +1 -0
- package/dist/raw-event-flush-claim-schema.d.ts +5 -0
- package/dist/raw-event-flush-claim-schema.d.ts.map +1 -0
- package/dist/raw-event-flush-claim.d.ts +40 -0
- package/dist/raw-event-flush-claim.d.ts.map +1 -0
- package/dist/raw-event-flush-cursor.d.ts +14 -0
- package/dist/raw-event-flush-cursor.d.ts.map +1 -0
- package/dist/raw-event-flush.d.ts +2 -0
- package/dist/raw-event-flush.d.ts.map +1 -1
- package/dist/raw-event-sweeper.d.ts +0 -1
- package/dist/raw-event-sweeper.d.ts.map +1 -1
- package/dist/relay-address-allowance.d.ts +29 -0
- package/dist/relay-address-allowance.d.ts.map +1 -0
- package/dist/relay-admission-clock-C4rCAFdM.js +31 -0
- package/dist/relay-admission-clock-C4rCAFdM.js.map +1 -0
- package/dist/relay-admission-clock-test-fixtures.d.ts +5 -0
- package/dist/relay-admission-clock-test-fixtures.d.ts.map +1 -0
- package/dist/relay-admission-clock.d.ts +28 -0
- package/dist/relay-admission-clock.d.ts.map +1 -0
- package/dist/relay-admission-codec.d.ts +69 -0
- package/dist/relay-admission-codec.d.ts.map +1 -0
- package/dist/relay-admission-decision-test-fixtures.d.ts +52 -0
- package/dist/relay-admission-decision-test-fixtures.d.ts.map +1 -0
- package/dist/relay-admission-decision.d.ts +60 -0
- package/dist/relay-admission-decision.d.ts.map +1 -0
- package/dist/relay-admission-metadata-schema.d.ts +25 -0
- package/dist/relay-admission-metadata-schema.d.ts.map +1 -0
- package/dist/relay-admission-metadata-test-fixtures.d.ts +42 -0
- package/dist/relay-admission-metadata-test-fixtures.d.ts.map +1 -0
- package/dist/relay-admission-participant-nonce-test-fixtures.d.ts +70 -0
- package/dist/relay-admission-participant-nonce-test-fixtures.d.ts.map +1 -0
- package/dist/relay-admission-participant-nonce.d.ts +44 -0
- package/dist/relay-admission-participant-nonce.d.ts.map +1 -0
- package/dist/relay-admission-proof-DjvC-e6G.js +78 -0
- package/dist/relay-admission-proof-DjvC-e6G.js.map +1 -0
- package/dist/relay-admission-proof.d.ts +31 -0
- package/dist/relay-admission-proof.d.ts.map +1 -0
- package/dist/relay-admission-readiness.d.ts +23 -0
- package/dist/relay-admission-readiness.d.ts.map +1 -0
- package/dist/relay-admission-reply-CHCEakzd.js +503 -0
- package/dist/relay-admission-reply-CHCEakzd.js.map +1 -0
- package/dist/relay-admission-reply.d.ts +12 -0
- package/dist/relay-admission-reply.d.ts.map +1 -0
- package/dist/relay-admission-storage-test-fixtures.d.ts +16 -0
- package/dist/relay-admission-storage-test-fixtures.d.ts.map +1 -0
- package/dist/relay-admission-table-keys-test-fixtures.d.ts +12 -0
- package/dist/relay-admission-table-keys-test-fixtures.d.ts.map +1 -0
- package/dist/relay-client-config.d.ts +87 -0
- package/dist/relay-client-config.d.ts.map +1 -0
- package/dist/relay-control-codec.d.ts +53 -0
- package/dist/relay-control-codec.d.ts.map +1 -0
- package/dist/relay-coordinator-client.d.ts +17 -0
- package/dist/relay-coordinator-client.d.ts.map +1 -0
- package/dist/relay-data-frame-CkrBuBf6.js +38 -0
- package/dist/relay-data-frame-CkrBuBf6.js.map +1 -0
- package/dist/relay-data-frame.d.ts +15 -0
- package/dist/relay-data-frame.d.ts.map +1 -0
- package/dist/relay-ed25519-BNMhPehl.js +49 -0
- package/dist/relay-ed25519-BNMhPehl.js.map +1 -0
- package/dist/relay-ed25519.d.ts +12 -0
- package/dist/relay-ed25519.d.ts.map +1 -0
- package/dist/relay-failure-reason.d.ts +25 -0
- package/dist/relay-failure-reason.d.ts.map +1 -0
- package/dist/relay-fault-proxy-test-fixtures.d.ts +75 -0
- package/dist/relay-fault-proxy-test-fixtures.d.ts.map +1 -0
- package/dist/relay-health-DhxMrW_S.js +495 -0
- package/dist/relay-health-DhxMrW_S.js.map +1 -0
- package/dist/relay-health-probe.d.ts +32 -0
- package/dist/relay-health-probe.d.ts.map +1 -0
- package/dist/relay-health-storage.d.ts +38 -0
- package/dist/relay-health-storage.d.ts.map +1 -0
- package/dist/relay-health-test-fixtures.d.ts +20 -0
- package/dist/relay-health-test-fixtures.d.ts.map +1 -0
- package/dist/relay-health.d.ts +168 -0
- package/dist/relay-health.d.ts.map +1 -0
- package/dist/relay-noise-identity.d.ts +22 -0
- package/dist/relay-noise-identity.d.ts.map +1 -0
- package/dist/relay-noise-opening.d.ts +13 -0
- package/dist/relay-noise-opening.d.ts.map +1 -0
- package/dist/relay-noise-stream.d.ts +82 -0
- package/dist/relay-noise-stream.d.ts.map +1 -0
- package/dist/relay-noise-test-fixtures.d.ts +15 -0
- package/dist/relay-noise-test-fixtures.d.ts.map +1 -0
- package/dist/relay-noise.d.ts +49 -0
- package/dist/relay-noise.d.ts.map +1 -0
- package/dist/relay-pair-pacing-test-fixtures.d.ts +16 -0
- package/dist/relay-pair-pacing-test-fixtures.d.ts.map +1 -0
- package/dist/relay-peer-client-Dkoe1TXa.js +8558 -0
- package/dist/relay-peer-client-Dkoe1TXa.js.map +1 -0
- package/dist/relay-peer-client-test-fixtures.d.ts +55 -0
- package/dist/relay-peer-client-test-fixtures.d.ts.map +1 -0
- package/dist/relay-peer-client.d.ts +68 -0
- package/dist/relay-peer-client.d.ts.map +1 -0
- package/dist/relay-peer-reachability.d.ts +28 -0
- package/dist/relay-peer-reachability.d.ts.map +1 -0
- package/dist/relay-peer-transport.d.ts +76 -0
- package/dist/relay-peer-transport.d.ts.map +1 -0
- package/dist/relay-quota-contract-test-fixtures.d.ts +32 -0
- package/dist/relay-quota-contract-test-fixtures.d.ts.map +1 -0
- package/dist/relay-quota-sqlite-C1th1yVy.js +246 -0
- package/dist/relay-quota-sqlite-C1th1yVy.js.map +1 -0
- package/dist/relay-quota-sqlite.d.ts +77 -0
- package/dist/relay-quota-sqlite.d.ts.map +1 -0
- package/dist/relay-runtime.integration-test-fixtures.d.ts +17 -0
- package/dist/relay-runtime.integration-test-fixtures.d.ts.map +1 -0
- package/dist/relay-server-CLNJrfOV.js +831 -0
- package/dist/relay-server-CLNJrfOV.js.map +1 -0
- package/dist/relay-server-restore.d.ts +56 -0
- package/dist/relay-server-restore.d.ts.map +1 -0
- package/dist/relay-server-test-fixtures.d.ts +148 -0
- package/dist/relay-server-test-fixtures.d.ts.map +1 -0
- package/dist/relay-server.d.ts +91 -0
- package/dist/relay-server.d.ts.map +1 -0
- package/dist/relay-service-pin-store.d.ts +59 -0
- package/dist/relay-service-pin-store.d.ts.map +1 -0
- package/dist/relay-service-proof.d.ts +27 -0
- package/dist/relay-service-proof.d.ts.map +1 -0
- package/dist/relay-websocket-runtime-test-fixtures.d.ts +63 -0
- package/dist/relay-websocket-runtime-test-fixtures.d.ts.map +1 -0
- package/dist/relay-websocket-runtime.d.ts +34 -0
- package/dist/relay-websocket-runtime.d.ts.map +1 -0
- package/dist/schema-bootstrap.d.ts.map +1 -1
- package/dist/schema.d.ts +182 -0
- package/dist/schema.d.ts.map +1 -1
- package/dist/{semantic-worker-ranking-DEOx8Xbb.js → scope-membership-cache-D5caGR57.js} +2361 -3566
- package/dist/scope-membership-cache-D5caGR57.js.map +1 -0
- package/dist/semantic-worker-entry.js +1 -1
- package/dist/{semantic-worker-job-D1qI9vRV.js → semantic-worker-job-CjYS3nT_.js} +3 -2
- package/dist/{semantic-worker-job-D1qI9vRV.js.map → semantic-worker-job-CjYS3nT_.js.map} +1 -1
- package/dist/semantic-worker-ranking-BuO9lch_.js +165 -0
- package/dist/semantic-worker-ranking-BuO9lch_.js.map +1 -0
- package/dist/store.d.ts +1 -0
- package/dist/store.d.ts.map +1 -1
- package/dist/{workspace-identity-nF_U-y6A.js → sync-auth-constants-Cb8-a8lE.js} +2644 -2341
- package/dist/sync-auth-constants-Cb8-a8lE.js.map +1 -0
- package/dist/sync-capability.d.ts +8 -2
- package/dist/sync-capability.d.ts.map +1 -1
- package/dist/sync-channel-pass.d.ts +24 -0
- package/dist/sync-channel-pass.d.ts.map +1 -0
- package/dist/sync-channel-progress.d.ts +25 -0
- package/dist/sync-channel-progress.d.ts.map +1 -0
- package/dist/sync-daemon.d.ts +12 -2
- package/dist/sync-daemon.d.ts.map +1 -1
- package/dist/sync-http-client.d.ts +1 -0
- package/dist/sync-http-client.d.ts.map +1 -1
- package/dist/sync-orchestration.d.ts +9 -0
- package/dist/sync-orchestration.d.ts.map +1 -0
- package/dist/sync-pass.d.ts +83 -6
- package/dist/sync-pass.d.ts.map +1 -1
- package/dist/sync-reachability-pass-B6ukEh3U.js +2 -0
- package/dist/sync-reachability-pass-CXHfKTMy.js +8454 -0
- package/dist/sync-reachability-pass-CXHfKTMy.js.map +1 -0
- package/dist/sync-reachability-pass.d.ts +29 -0
- package/dist/sync-reachability-pass.d.ts.map +1 -0
- package/dist/sync-replication.d.ts +12 -0
- package/dist/sync-replication.d.ts.map +1 -1
- package/dist/sync-scope-protocol.d.ts +7 -0
- package/dist/sync-scope-protocol.d.ts.map +1 -1
- package/dist/sync-transfer-activity.d.ts +5 -0
- package/dist/sync-transfer-activity.d.ts.map +1 -1
- package/dist/test-schema.generated.d.ts +1 -1
- package/dist/test-schema.generated.d.ts.map +1 -1
- package/dist/validated-vector-index-audit-BosLXii5.js +1241 -0
- package/dist/validated-vector-index-audit-BosLXii5.js.map +1 -0
- package/dist/vector-metadata-rows.d.ts +43 -0
- package/dist/vector-metadata-rows.d.ts.map +1 -0
- package/dist/vector-metadata-snapshot.d.ts +4 -5
- package/dist/vector-metadata-snapshot.d.ts.map +1 -1
- package/dist/vector-migration.d.ts +30 -0
- package/dist/vector-migration.d.ts.map +1 -1
- package/dist/vector-writes.d.ts.map +1 -1
- package/dist/vectors.d.ts.map +1 -1
- package/dist/workspace-identity-DI8bBR0Y.js +76 -0
- package/dist/workspace-identity-DI8bBR0Y.js.map +1 -0
- package/package.json +20 -3
- package/dist/owner-enrollment-start-DHh8A5hh.js.map +0 -1
- package/dist/semantic-worker-ranking-DEOx8Xbb.js.map +0 -1
- package/dist/workspace-identity-nF_U-y6A.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"owner-enrollment-start-DHh8A5hh.js","names":["errorHandler","Hono","Node","Node","HonoBase","USER_AGENT","ERR_INVALID_ARG_VALUE","ERR_INVALID_ARG_TYPE","CodedTypeError","allowInsecureRequests","clockTolerance","customFetch","decoder","signal","performDiscovery","assertString","randomBytes","calculatePKCECodeChallenge","ClientSecretPost","None","oauth.ClientSecretPost","oauth.None","oauth.customFetch","oauth.clockTolerance","oauth.calculatePKCECodeChallenge","oauth.generateRandomCodeVerifier","oauth.generateRandomNonce","oauth.generateRandomState","oauth.ResponseBodyError","oauth.AuthorizationResponseError","oauth.WWWAuthenticateChallengeError","oauth.OperationProcessingError","oauth.HTTP_REQUEST_FORBIDDEN","oauth.REQUEST_PROTOCOL_FORBIDDEN","oauth.RESPONSE_IS_NOT_CONFORM","oauth.RESPONSE_IS_NOT_JSON","oauth.PARSE_ERROR","oauth.INVALID_RESPONSE","oauth.JWT_CLAIM_COMPARISON","oauth.JSON_ATTRIBUTE_COMPARISON","oauth.JWT_TIMESTAMP_CHECK","oauth.UnsupportedOperationError","oauth.UNSUPPORTED_OPERATION","oauth.discoveryRequest","oauth.allowInsecureRequests","oauth.processDiscoveryResponse","oauth._nodiscoverycheck","oauth.clockSkew","oauth._expectedIssuer","oauth.getValidatedIdTokenClaims","oauth\n .validateApplicationLevelSignature","oauth.jwksCache","jwksCache","oauth.formPostResponse","oauth.validateAuthResponse","oauth\n .authorizationCodeGrantRequest","oauth.nopkce","oauth.processAuthorizationCodeResponse","oauth.jweDecrypt","oauth.resolveEndpoint","oauth\n .userInfoRequest","oauth.processUserInfoResponse","oauth.isDPoPNonceError"],"sources":["../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/compose.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/request/constants.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/utils/buffer.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/utils/body.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/utils/url.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/request.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/utils/html.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/context.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/router.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/utils/constants.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/hono-base.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/router/utils.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/router/reg-exp-router/matcher.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/router/reg-exp-router/node.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/router/reg-exp-router/trie.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/router/reg-exp-router/router.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/router/smart-router/router.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/router/trie-router/node.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/router/trie-router/router.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/hono.js","../src/coordinator-auth-controller-owner-review.ts","../src/coordinator-auth-controller-review-route.ts","../src/coordinator-account-change-contract.ts","../src/coordinator-device-account-change.ts","../src/coordinator-device-auth-link.ts","../src/coordinator-browser-form-body.ts","../src/coordinator-browser-form-guard.ts","../src/coordinator-browser-request.ts","../src/coordinator-browser-start-transaction.ts","../src/coordinator-owner-enrollment-proof.ts","../src/coordinator-device-rebind-proof.ts","../src/coordinator-device-rebind-commit.ts","../src/coordinator-device-rebind-ceremony.ts","../../../node_modules/.pnpm/limiter@3.0.0/node_modules/limiter/dist/esm/clock.js","../../../node_modules/.pnpm/limiter@3.0.0/node_modules/limiter/dist/esm/TokenBucket.js","../../../node_modules/.pnpm/limiter@3.0.0/node_modules/limiter/dist/esm/RateLimiter.js","../src/request-rate-limit.ts","../src/coordinator-device-rebind-http.ts","../src/coordinator-device-revocation-handler.ts","../src/coordinator-device-revocation-route.ts","../src/coordinator-invites.ts","../src/coordinator-scope-authorization-response.ts","../src/project-invite-acceptance.ts","../src/project-share-intent.ts","../src/coordinator-api.ts","../src/coordinator-identity-group-grant-client.ts","../src/coordinator-browser-auth-config.ts","../../../node_modules/.pnpm/oauth4webapi@3.8.8/node_modules/oauth4webapi/build/index.js","../../../node_modules/.pnpm/openid-client@6.8.8/node_modules/openid-client/build/index.js","../src/coordinator-oidc.ts","../src/coordinator-auth-link-liveness.ts","../src/coordinator-owner-enrollment-qualification-schema.ts","../src/owner-enrollment-link-authority.ts","../src/owner-enrollment-admission.ts","../src/owner-enrollment-owner-pin.ts","../src/coordinator-owner-enrollment-commit.ts","../src/owner-browser-admission-authority.ts","../src/owner-enrollment-start.ts"],"sourcesContent":["// src/compose.ts\nvar compose = (middleware, onError, onNotFound) => {\n return (context, next) => {\n let index = -1;\n return dispatch(0);\n async function dispatch(i) {\n if (i <= index) {\n throw new Error(\"next() called multiple times\");\n }\n index = i;\n let res;\n let isError = false;\n let handler;\n if (middleware[i]) {\n handler = middleware[i][0][0];\n context.req.routeIndex = i;\n } else {\n handler = i === middleware.length && next || void 0;\n }\n if (handler) {\n try {\n res = await handler(context, () => dispatch(i + 1));\n } catch (err) {\n if (err instanceof Error && onError) {\n context.error = err;\n res = await onError(err, context);\n isError = true;\n } else {\n throw err;\n }\n }\n } else {\n if (context.finalized === false && onNotFound) {\n res = await onNotFound(context);\n }\n }\n if (res && (context.finalized === false || isError)) {\n context.res = res;\n }\n return context;\n }\n };\n};\nexport {\n compose\n};\n","// src/request/constants.ts\nvar GET_MATCH_RESULT = /* @__PURE__ */ Symbol();\nexport {\n GET_MATCH_RESULT\n};\n","// src/utils/buffer.ts\nimport { sha256 } from \"./crypto.js\";\nvar equal = (a, b) => {\n if (a === b) {\n return true;\n }\n if (a.byteLength !== b.byteLength) {\n return false;\n }\n const va = new DataView(a);\n const vb = new DataView(b);\n let i = va.byteLength;\n while (i--) {\n if (va.getUint8(i) !== vb.getUint8(i)) {\n return false;\n }\n }\n return true;\n};\nvar constantTimeEqualString = (a, b) => {\n const aLen = a.length;\n const bLen = b.length;\n const maxLen = Math.max(aLen, bLen);\n let out = aLen ^ bLen;\n for (let i = 0; i < maxLen; i++) {\n const aChar = i < aLen ? a.charCodeAt(i) : 0;\n const bChar = i < bLen ? b.charCodeAt(i) : 0;\n out |= aChar ^ bChar;\n }\n return out === 0;\n};\nvar timingSafeEqualString = async (a, b, hashFunction) => {\n if (!hashFunction) {\n hashFunction = sha256;\n }\n const [sa, sb] = await Promise.all([hashFunction(a), hashFunction(b)]);\n if (sa == null || sb == null || typeof sa !== \"string\" || typeof sb !== \"string\") {\n return false;\n }\n const hashEqual = constantTimeEqualString(sa, sb);\n const originalEqual = constantTimeEqualString(a, b);\n return hashEqual && originalEqual;\n};\nvar timingSafeEqual = async (a, b, hashFunction) => {\n if (typeof a === \"string\" && typeof b === \"string\") {\n return timingSafeEqualString(a, b, hashFunction);\n }\n if (!hashFunction) {\n hashFunction = sha256;\n }\n const [sa, sb] = await Promise.all([hashFunction(a), hashFunction(b)]);\n if (!sa || !sb || typeof sa !== \"string\" || typeof sb !== \"string\") {\n return false;\n }\n return timingSafeEqualString(sa, sb);\n};\nvar bufferToString = (buffer) => {\n if (buffer instanceof ArrayBuffer) {\n const enc = new TextDecoder(\"utf-8\");\n return enc.decode(buffer);\n }\n return buffer;\n};\nvar bufferToFormData = (arrayBuffer, contentType) => {\n const response = new Response(arrayBuffer, {\n headers: {\n // Normalize the media type (case-insensitive) while keeping parameters like the boundary\n \"Content-Type\": contentType.replace(/^[^;]+/, (mediaType) => mediaType.toLowerCase())\n }\n });\n return response.formData();\n};\nexport {\n bufferToFormData,\n bufferToString,\n equal,\n timingSafeEqual\n};\n","// src/utils/body.ts\nimport { bufferToFormData } from \"./buffer.js\";\nvar MAX_NESTING_DEPTH = 32;\nvar MAX_NESTED_OBJECTS = 1e4;\nvar isRawRequest = (request) => \"headers\" in request;\nvar parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {\n const { all = false, dot = false } = options;\n const headers = isRawRequest(request) ? request.headers : request.raw.headers;\n const contentType = headers.get(\"Content-Type\");\n const mediaType = contentType?.split(\";\")[0].trim().toLowerCase();\n if (mediaType === \"multipart/form-data\" || mediaType === \"application/x-www-form-urlencoded\") {\n return parseFormData(request, { all, dot });\n }\n return {};\n};\nasync function parseFormData(request, options) {\n if (!isRawRequest(request) && request.bodyCache.formData) {\n return convertFormDataToBodyData(\n await request.bodyCache.formData,\n options\n );\n }\n const headers = isRawRequest(request) ? request.headers : request.raw.headers;\n const arrayBuffer = await request.arrayBuffer();\n const formDataPromise = bufferToFormData(arrayBuffer, headers.get(\"Content-Type\") || \"\");\n if (!isRawRequest(request)) {\n request.bodyCache.formData = formDataPromise;\n }\n const formData = await formDataPromise;\n if (formData) {\n return convertFormDataToBodyData(formData, options);\n }\n return {};\n}\nfunction convertFormDataToBodyData(formData, options) {\n const form = /* @__PURE__ */ Object.create(null);\n const nestingState = { count: 0 };\n formData.forEach((value, key) => {\n const shouldParseAllValues = options.all || key.endsWith(\"[]\");\n if (!shouldParseAllValues) {\n form[key] = value;\n } else {\n handleParsingAllValues(form, key, value);\n }\n });\n if (options.dot) {\n Object.entries(form).forEach(([key, value]) => {\n const shouldParseDotValues = key.includes(\".\");\n if (shouldParseDotValues) {\n handleParsingNestedValues(form, key, value, nestingState);\n delete form[key];\n }\n });\n }\n return form;\n}\nvar handleParsingAllValues = (form, key, value) => {\n if (form[key] !== void 0) {\n if (Array.isArray(form[key])) {\n ;\n form[key].push(value);\n } else {\n form[key] = [form[key], value];\n }\n } else {\n if (!key.endsWith(\"[]\")) {\n form[key] = value;\n } else {\n form[key] = [value];\n }\n }\n};\nvar handleParsingNestedValues = (form, key, value, state) => {\n if (/(?:^|\\.)__proto__\\./.test(key)) {\n return;\n }\n let nestedForm = form;\n const keys = key.split(\".\", MAX_NESTING_DEPTH + 2);\n if (keys.length > MAX_NESTING_DEPTH + 1) {\n throwNestingLimitExceeded();\n }\n keys.forEach((key2, index) => {\n if (index === keys.length - 1) {\n nestedForm[key2] = value;\n } else {\n if (!nestedForm[key2] || typeof nestedForm[key2] !== \"object\" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {\n if (state.count++ >= MAX_NESTED_OBJECTS) {\n throwNestingLimitExceeded();\n }\n nestedForm[key2] = /* @__PURE__ */ Object.create(null);\n }\n nestedForm = nestedForm[key2];\n }\n });\n};\nvar throwNestingLimitExceeded = () => {\n throw new Error(\"Nesting limit exceeded\");\n};\nexport {\n parseBody\n};\n","// src/utils/url.ts\nvar splitPath = (path) => {\n const paths = path.split(\"/\");\n if (paths[0] === \"\") {\n paths.shift();\n }\n return paths;\n};\nvar splitRoutingPath = (routePath) => {\n const { groups, path } = extractGroupsFromPath(routePath);\n const paths = splitPath(path);\n return replaceGroupMarks(paths, groups);\n};\nvar extractGroupsFromPath = (path) => {\n const groups = [];\n path = path.replace(/\\{[^}]+\\}/g, (match, index) => {\n const mark = `@${index}`;\n groups.push([mark, match]);\n return mark;\n });\n return { groups, path };\n};\nvar replaceGroupMarks = (paths, groups) => {\n for (let i = groups.length - 1; i >= 0; i--) {\n const [mark] = groups[i];\n for (let j = paths.length - 1; j >= 0; j--) {\n if (paths[j].includes(mark)) {\n paths[j] = paths[j].replace(mark, groups[i][1]);\n break;\n }\n }\n }\n return paths;\n};\nvar patternCache = {};\nvar getPattern = (label, next) => {\n if (label === \"*\") {\n return \"*\";\n }\n const match = label.match(/^\\:([^\\{\\}]+)(?:\\{(.+)\\})?$/);\n if (match) {\n const cacheKey = `${label}#${next}`;\n if (!patternCache[cacheKey]) {\n if (match[2]) {\n patternCache[cacheKey] = next && next[0] !== \":\" && next[0] !== \"*\" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];\n } else {\n patternCache[cacheKey] = [label, match[1], true];\n }\n }\n return patternCache[cacheKey];\n }\n return null;\n};\nvar tryDecode = (str, decoder) => {\n try {\n return decoder(str);\n } catch {\n return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {\n try {\n return decoder(match);\n } catch {\n return match;\n }\n });\n }\n};\nvar tryDecodeURI = (str) => tryDecode(str, decodeURI);\nvar getPath = (request) => {\n const url = request.url;\n const start = url.indexOf(\"/\", url.indexOf(\":\") + 4);\n let i = start;\n for (; i < url.length; i++) {\n const charCode = url.charCodeAt(i);\n if (charCode === 37) {\n const queryIndex = url.indexOf(\"?\", i);\n const hashIndex = url.indexOf(\"#\", i);\n const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);\n const path = url.slice(start, end);\n return tryDecodeURI(path.includes(\"%25\") ? path.replace(/%25/g, \"%2525\") : path);\n } else if (charCode === 63 || charCode === 35) {\n break;\n }\n }\n return url.slice(start, i);\n};\nvar getQueryStrings = (url) => {\n const queryIndex = url.indexOf(\"?\", 8);\n if (queryIndex === -1) {\n return \"\";\n }\n const hashIndex = url.indexOf(\"#\", 8);\n return hashIndex === -1 ? url.slice(queryIndex) : queryIndex < hashIndex ? url.slice(queryIndex, hashIndex) : \"\";\n};\nvar getPathNoStrict = (request) => {\n const result = getPath(request);\n return result.length > 1 && result.at(-1) === \"/\" ? result.slice(0, -1) : result;\n};\nvar mergePath = (base, sub, ...rest) => {\n if (rest.length) {\n sub = mergePath(sub, ...rest);\n }\n return `${base?.[0] === \"/\" ? \"\" : \"/\"}${base}${sub === \"/\" ? \"\" : `${base?.at(-1) === \"/\" ? \"\" : \"/\"}${sub?.[0] === \"/\" ? sub.slice(1) : sub}`}`;\n};\nvar checkOptionalParameter = (path) => {\n if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(\":\")) {\n return null;\n }\n const segments = path.split(\"/\");\n const results = [];\n let basePath = \"\";\n segments.forEach((segment) => {\n if (segment !== \"\" && !/\\:/.test(segment)) {\n basePath += \"/\" + segment;\n } else if (/\\:/.test(segment)) {\n if (segment.charCodeAt(segment.length - 1) === 63) {\n if (results.length === 0 && basePath === \"\") {\n results.push(\"/\");\n } else {\n results.push(basePath);\n }\n const optionalSegment = segment.slice(0, -1);\n basePath += \"/\" + optionalSegment;\n results.push(basePath);\n } else {\n basePath += \"/\" + segment;\n }\n }\n });\n return results.filter((v, i, a) => a.indexOf(v) === i);\n};\nvar tryDecodeURIComponent = (str) => str.indexOf(\"%\") !== -1 ? tryDecode(str, decodeURIComponent_) : str;\nvar _decodeURI = (value) => {\n if (value.indexOf(\"+\") !== -1) {\n value = value.replace(/\\+/g, \" \");\n }\n return tryDecodeURIComponent(value);\n};\nvar _getQueryParam = (url, key, multiple) => {\n const hashIndex = url.indexOf(\"#\", 8);\n if (hashIndex !== -1) {\n url = url.slice(0, hashIndex);\n }\n let encoded;\n if (!multiple && key && key.indexOf(\"%\") === -1 && key.indexOf(\"+\") === -1) {\n let keyIndex2 = url.indexOf(\"?\", 8);\n if (keyIndex2 === -1) {\n return void 0;\n }\n if (!url.startsWith(key, keyIndex2 + 1)) {\n keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);\n }\n while (keyIndex2 !== -1) {\n const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);\n if (trailingKeyCode === 61) {\n const valueIndex = keyIndex2 + key.length + 2;\n const endIndex = url.indexOf(\"&\", valueIndex);\n return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));\n } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {\n return \"\";\n }\n keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);\n }\n encoded = /[%+]/.test(url);\n if (!encoded) {\n return void 0;\n }\n }\n const results = /* @__PURE__ */ Object.create(null);\n encoded ??= /[%+]/.test(url);\n let keyIndex = url.indexOf(\"?\", 8);\n while (keyIndex !== -1) {\n const nextKeyIndex = url.indexOf(\"&\", keyIndex + 1);\n let valueIndex = url.indexOf(\"=\", keyIndex);\n if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {\n valueIndex = -1;\n }\n let name = url.slice(\n keyIndex + 1,\n valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex\n );\n if (encoded) {\n name = _decodeURI(name);\n }\n keyIndex = nextKeyIndex;\n if (name === \"\") {\n continue;\n }\n let value;\n if (valueIndex === -1) {\n value = \"\";\n } else {\n value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);\n if (encoded) {\n value = _decodeURI(value);\n }\n }\n if (multiple) {\n if (!(results[name] && Array.isArray(results[name]))) {\n results[name] = [];\n }\n ;\n results[name].push(value);\n } else {\n results[name] ??= value;\n }\n }\n return key ? results[key] : results;\n};\nvar getQueryParam = _getQueryParam;\nvar getQueryParams = (url, key) => {\n return _getQueryParam(url, key, true);\n};\nvar decodeURIComponent_ = decodeURIComponent;\nexport {\n checkOptionalParameter,\n decodeURIComponent_,\n getPath,\n getPathNoStrict,\n getPattern,\n getQueryParam,\n getQueryParams,\n getQueryStrings,\n mergePath,\n splitPath,\n splitRoutingPath,\n tryDecode,\n tryDecodeURI,\n tryDecodeURIComponent\n};\n","// src/request.ts\nimport { HTTPException } from \"./http-exception.js\";\nimport { GET_MATCH_RESULT } from \"./request/constants.js\";\nimport { parseBody } from \"./utils/body.js\";\nimport { getQueryParam, getQueryParams, tryDecodeURIComponent } from \"./utils/url.js\";\nvar HonoRequest = class {\n /**\n * `.raw` can get the raw Request object.\n *\n * @see {@link https://hono.dev/docs/api/request#raw}\n *\n * @example\n * ```ts\n * // For Cloudflare Workers\n * app.post('/', async (c) => {\n * const metadata = c.req.raw.cf?.hostMetadata?\n * ...\n * })\n * ```\n */\n raw;\n #validatedData;\n // Short name of validatedData\n #matchResult;\n routeIndex = 0;\n /**\n * `.path` can get the pathname of the request.\n *\n * @see {@link https://hono.dev/docs/api/request#path}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const pathname = c.req.path // `/about/me`\n * })\n * ```\n */\n path;\n bodyCache = {};\n constructor(request, path = \"/\", matchResult = [[]]) {\n this.raw = request;\n this.path = path;\n this.#matchResult = matchResult;\n }\n param(key) {\n return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();\n }\n #getDecodedParam(key) {\n const paramKey = this.#matchResult[0][this.routeIndex]?.[1][key];\n const param = this.#getParamValue(paramKey);\n return param && tryDecodeURIComponent(param);\n }\n #getAllDecodedParams() {\n const decoded = {};\n const keys = Object.keys(this.#matchResult[0][this.routeIndex]?.[1] ?? {});\n for (const key of keys) {\n const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);\n if (value !== void 0) {\n decoded[key] = tryDecodeURIComponent(value);\n }\n }\n return decoded;\n }\n #getParamValue(paramKey) {\n return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;\n }\n query(key) {\n return getQueryParam(this.url, key);\n }\n queries(key) {\n return getQueryParams(this.url, key);\n }\n header(name) {\n if (name) {\n return this.raw.headers.get(name) ?? void 0;\n }\n const headerData = /* @__PURE__ */ Object.create(null);\n this.raw.headers.forEach((value, key) => {\n headerData[key] = value;\n });\n return headerData;\n }\n async parseBody(options) {\n return parseBody(this, options);\n }\n #cachedBody = (key) => {\n const { bodyCache, raw } = this;\n const cachedBody = bodyCache[key];\n if (cachedBody) {\n return cachedBody;\n }\n for (const anyCachedKey in bodyCache) {\n return bodyCache[anyCachedKey].then((body) => {\n if (anyCachedKey === \"json\") {\n body = JSON.stringify(body);\n }\n return new Response(body)[key]();\n });\n }\n return bodyCache[key] = raw[key]();\n };\n /**\n * `.json()` can parse Request body of type `application/json`\n *\n * @see {@link https://hono.dev/docs/api/request#json}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.json()\n * })\n * ```\n */\n json() {\n return this.#cachedBody(\"text\").then((text) => JSON.parse(text));\n }\n /**\n * `.text()` can parse Request body of type `text/plain`\n *\n * @see {@link https://hono.dev/docs/api/request#text}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.text()\n * })\n * ```\n */\n text() {\n return this.#cachedBody(\"text\");\n }\n /**\n * `.arrayBuffer()` parse Request body as an `ArrayBuffer`\n *\n * @see {@link https://hono.dev/docs/api/request#arraybuffer}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.arrayBuffer()\n * })\n * ```\n */\n arrayBuffer() {\n return this.#cachedBody(\"arrayBuffer\");\n }\n /**\n * `.bytes()` parses the request body as a `Uint8Array`.\n *\n * @see {@link https://hono.dev/docs/api/request#bytes}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.bytes()\n * })\n * ```\n */\n bytes() {\n return this.#cachedBody(\"arrayBuffer\").then((buffer) => new Uint8Array(buffer));\n }\n /**\n * Parses the request body as a `Blob`.\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.blob();\n * });\n * ```\n * @see https://hono.dev/docs/api/request#blob\n */\n blob() {\n return this.#cachedBody(\"blob\");\n }\n /**\n * Parses the request body as `FormData`.\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.formData();\n * });\n * ```\n * @see https://hono.dev/docs/api/request#formdata\n */\n formData() {\n return this.#cachedBody(\"formData\");\n }\n /**\n * Adds validated data to the request.\n *\n * @param target - The target of the validation.\n * @param data - The validated data to add.\n */\n addValidatedData(target, data) {\n ;\n (this.#validatedData ??= {})[target] = data;\n }\n valid(target) {\n return this.#validatedData?.[target];\n }\n /**\n * `.url()` can get the request url strings.\n *\n * @see {@link https://hono.dev/docs/api/request#url}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const url = c.req.url // `http://localhost:8787/about/me`\n * ...\n * })\n * ```\n */\n get url() {\n return this.raw.url;\n }\n /**\n * `.method()` can get the method name of the request.\n *\n * @see {@link https://hono.dev/docs/api/request#method}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const method = c.req.method // `GET`\n * })\n * ```\n */\n get method() {\n return this.raw.method;\n }\n get [GET_MATCH_RESULT]() {\n return this.#matchResult;\n }\n /**\n * `.matchedRoutes()` can return a matched route in the handler\n *\n * @deprecated\n *\n * Use matchedRoutes helper defined in \"hono/route\" instead.\n *\n * @see {@link https://hono.dev/docs/api/request#matchedroutes}\n *\n * @example\n * ```ts\n * app.use('*', async function logger(c, next) {\n * await next()\n * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {\n * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')\n * console.log(\n * method,\n * ' ',\n * path,\n * ' '.repeat(Math.max(10 - path.length, 0)),\n * name,\n * i === c.req.routeIndex ? '<- respond from here' : ''\n * )\n * })\n * })\n * ```\n */\n get matchedRoutes() {\n return this.#matchResult[0].map(([[, route]]) => route);\n }\n /**\n * `routePath()` can retrieve the path registered within the handler\n *\n * @deprecated\n *\n * Use routePath helper defined in \"hono/route\" instead.\n *\n * @see {@link https://hono.dev/docs/api/request#routepath}\n *\n * @example\n * ```ts\n * app.get('/posts/:id', (c) => {\n * return c.json({ path: c.req.routePath })\n * })\n * ```\n */\n get routePath() {\n return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;\n }\n};\nvar cloneRawRequest = async (req) => {\n if (!req.raw.bodyUsed) {\n return req.raw.clone();\n }\n const cacheKey = Object.keys(req.bodyCache)[0];\n if (!cacheKey) {\n throw new HTTPException(500, {\n message: \"Cannot clone request: body was already consumed and not cached. Please use HonoRequest methods (e.g., req.json(), req.text()) instead of consuming req.raw directly.\"\n });\n }\n let body = await req[cacheKey]();\n const headers = req.header();\n if (cacheKey === \"json\") {\n body = JSON.stringify(body);\n delete headers[\"content-length\"];\n } else if (body instanceof FormData) {\n delete headers[\"content-type\"];\n delete headers[\"content-length\"];\n }\n const requestInit = {\n body,\n cache: req.raw.cache,\n credentials: req.raw.credentials,\n headers,\n integrity: req.raw.integrity,\n keepalive: req.raw.keepalive,\n method: req.method,\n mode: req.raw.mode,\n redirect: req.raw.redirect,\n referrer: req.raw.referrer,\n referrerPolicy: req.raw.referrerPolicy,\n signal: req.raw.signal\n };\n return new Request(req.url, requestInit);\n};\nexport {\n HonoRequest,\n cloneRawRequest\n};\n","// src/utils/html.ts\nvar HtmlEscapedCallbackPhase = {\n Stringify: 1,\n BeforeStream: 2,\n Stream: 3\n};\nvar raw = (value, callbacks) => {\n const escapedString = new String(value);\n escapedString.isEscaped = true;\n escapedString.callbacks = callbacks;\n return escapedString;\n};\nvar escapeRe = /[&<>'\"]/;\nvar stringBufferToString = async (buffer, callbacks) => {\n let str = \"\";\n callbacks ||= [];\n const resolvedBuffer = await Promise.all(buffer);\n for (let i = resolvedBuffer.length - 1; ; i--) {\n str += resolvedBuffer[i];\n i--;\n if (i < 0) {\n break;\n }\n let r = resolvedBuffer[i];\n if (typeof r === \"object\") {\n callbacks.push(...r.callbacks || []);\n }\n const isEscaped = r.isEscaped;\n r = await (typeof r === \"object\" ? r.toString() : r);\n if (typeof r === \"object\") {\n callbacks.push(...r.callbacks || []);\n }\n if (r.isEscaped ?? isEscaped) {\n str += r;\n } else {\n const buf = [str];\n escapeToBuffer(r, buf);\n str = buf[0];\n }\n }\n return raw(str, callbacks);\n};\nvar escapeToBuffer = (str, buffer) => {\n const match = str.search(escapeRe);\n if (match === -1) {\n buffer[0] += str;\n return;\n }\n let escape;\n let index;\n let lastIndex = 0;\n for (index = match; index < str.length; index++) {\n switch (str.charCodeAt(index)) {\n case 34:\n escape = \""\";\n break;\n case 39:\n escape = \"'\";\n break;\n case 38:\n escape = \"&\";\n break;\n case 60:\n escape = \"<\";\n break;\n case 62:\n escape = \">\";\n break;\n default:\n continue;\n }\n buffer[0] += str.substring(lastIndex, index) + escape;\n lastIndex = index + 1;\n }\n buffer[0] += str.substring(lastIndex, index);\n};\nvar resolveCallbackSync = (str) => {\n const callbacks = str.callbacks;\n if (!callbacks?.length) {\n return str;\n }\n const buffer = [str];\n const context = {};\n callbacks.forEach((c) => c({ phase: HtmlEscapedCallbackPhase.Stringify, buffer, context }));\n return buffer[0];\n};\nvar resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {\n if (typeof str === \"object\" && !(str instanceof String)) {\n if (!(str instanceof Promise)) {\n str = str.toString();\n }\n if (str instanceof Promise) {\n str = await str;\n }\n }\n const callbacks = str.callbacks;\n if (!callbacks?.length) {\n return Promise.resolve(str);\n }\n if (buffer) {\n buffer[0] += str;\n } else {\n buffer = [str];\n }\n const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(\n (res) => Promise.all(\n res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))\n ).then(() => buffer[0])\n );\n if (preserveCallbacks) {\n return raw(await resStr, callbacks);\n } else {\n return resStr;\n }\n};\nexport {\n HtmlEscapedCallbackPhase,\n escapeToBuffer,\n raw,\n resolveCallback,\n resolveCallbackSync,\n stringBufferToString\n};\n","// src/context.ts\nimport { HonoRequest } from \"./request.js\";\nimport { HtmlEscapedCallbackPhase, resolveCallback } from \"./utils/html.js\";\nvar TEXT_PLAIN = \"text/plain; charset=UTF-8\";\nvar setDefaultContentType = (contentType, headers) => {\n return {\n \"Content-Type\": contentType,\n ...headers\n };\n};\nvar createResponseInstance = (body, init) => new Response(body, init);\nvar Context = class {\n #rawRequest;\n #req;\n /**\n * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.\n *\n * @see {@link https://hono.dev/docs/api/context#env}\n *\n * @example\n * ```ts\n * // Environment object for Cloudflare Workers\n * app.get('*', async c => {\n * const counter = c.env.COUNTER\n * })\n * ```\n */\n env = {};\n #var;\n finalized = false;\n /**\n * `.error` can get the error object from the middleware if the Handler throws an error.\n *\n * @see {@link https://hono.dev/docs/api/context#error}\n *\n * @example\n * ```ts\n * app.use('*', async (c, next) => {\n * await next()\n * if (c.error) {\n * // do something...\n * }\n * })\n * ```\n */\n error;\n #status;\n #executionCtx;\n #res;\n #layout;\n #renderer;\n #notFoundHandler;\n #preparedHeaders;\n #matchResult;\n #path;\n /**\n * Creates an instance of the Context class.\n *\n * @param req - The Request object.\n * @param options - Optional configuration options for the context.\n */\n constructor(req, options) {\n this.#rawRequest = req;\n if (options) {\n this.#executionCtx = options.executionCtx;\n this.env = options.env;\n this.#notFoundHandler = options.notFoundHandler;\n this.#path = options.path;\n this.#matchResult = options.matchResult;\n }\n }\n /**\n * `.req` is the instance of {@link HonoRequest}.\n */\n get req() {\n this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);\n return this.#req;\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#event}\n * The FetchEvent associated with the current request.\n *\n * @throws Will throw an error if the context does not have a FetchEvent.\n */\n get event() {\n if (this.#executionCtx && \"respondWith\" in this.#executionCtx) {\n return this.#executionCtx;\n } else {\n throw Error(\"This context has no FetchEvent\");\n }\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#executionctx}\n * The ExecutionContext associated with the current request.\n *\n * @throws Will throw an error if the context does not have an ExecutionContext.\n */\n get executionCtx() {\n if (this.#executionCtx) {\n return this.#executionCtx;\n } else {\n throw Error(\"This context has no ExecutionContext\");\n }\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#res}\n * The Response object for the current request.\n */\n get res() {\n return this.#res ||= createResponseInstance(null, {\n headers: this.#preparedHeaders ??= new Headers()\n });\n }\n /**\n * Sets the Response object for the current request.\n *\n * @param _res - The Response object to set.\n */\n set res(_res) {\n if (this.#res && _res) {\n _res = createResponseInstance(_res.body, _res);\n for (const [k, v] of this.#res.headers.entries()) {\n if (k === \"content-type\") {\n continue;\n }\n if (k === \"set-cookie\") {\n const cookies = this.#res.headers.getSetCookie();\n _res.headers.delete(\"set-cookie\");\n for (const cookie of cookies) {\n _res.headers.append(\"set-cookie\", cookie);\n }\n } else {\n _res.headers.set(k, v);\n }\n }\n }\n this.#res = _res;\n this.finalized = true;\n }\n /**\n * `.render()` can create a response within a layout.\n *\n * @see {@link https://hono.dev/docs/api/context#render-setrenderer}\n *\n * @example\n * ```ts\n * app.get('/', (c) => {\n * return c.render('Hello!')\n * })\n * ```\n */\n render = (...args) => {\n this.#renderer ??= (content) => this.html(content);\n return this.#renderer(...args);\n };\n /**\n * Sets the layout for the response.\n *\n * @param layout - The layout to set.\n * @returns The layout function.\n */\n setLayout = (layout) => this.#layout = layout;\n /**\n * Gets the current layout for the response.\n *\n * @returns The current layout function.\n */\n getLayout = () => this.#layout;\n /**\n * `.setRenderer()` can set the layout in the custom middleware.\n *\n * @see {@link https://hono.dev/docs/api/context#render-setrenderer}\n *\n * @example\n * ```tsx\n * app.use('*', async (c, next) => {\n * c.setRenderer((content) => {\n * return c.html(\n * <html>\n * <body>\n * <p>{content}</p>\n * </body>\n * </html>\n * )\n * })\n * await next()\n * })\n * ```\n */\n setRenderer = (renderer) => {\n this.#renderer = renderer;\n };\n /**\n * `.header()` can set headers.\n *\n * @see {@link https://hono.dev/docs/api/context#header}\n *\n * @example\n * ```ts\n * app.get('/welcome', (c) => {\n * // Set headers\n * c.header('X-Message', 'Hello!')\n * c.header('Content-Type', 'text/plain')\n *\n * // Append multiple headers using the append option (e.g. Vary)\n * c.header('Vary', 'Accept-Encoding', { append: true })\n * c.header('Vary', 'User-Agent', { append: true })\n *\n * return c.body('Thank you for coming')\n * })\n * ```\n */\n header = (name, value, options) => {\n if (this.finalized) {\n this.#res = createResponseInstance(this.#res.body, this.#res);\n }\n const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();\n if (value === void 0) {\n headers.delete(name);\n } else if (options?.append) {\n headers.append(name, value);\n } else {\n headers.set(name, value);\n }\n };\n status = (status) => {\n this.#status = status;\n };\n /**\n * `.set()` can set the value specified by the key.\n *\n * @see {@link https://hono.dev/docs/api/context#set-get}\n *\n * @example\n * ```ts\n * app.use('*', async (c, next) => {\n * c.set('message', 'Hono is hot!!')\n * await next()\n * })\n * ```\n */\n set = (key, value) => {\n this.#var ??= /* @__PURE__ */ new Map();\n this.#var.set(key, value);\n };\n /**\n * `.get()` can use the value specified by the key.\n *\n * @see {@link https://hono.dev/docs/api/context#set-get}\n *\n * @example\n * ```ts\n * app.get('/', (c) => {\n * const message = c.get('message')\n * return c.text(`The message is \"${message}\"`)\n * })\n * ```\n */\n get = (key) => {\n return this.#var ? this.#var.get(key) : void 0;\n };\n /**\n * `.var` can access the value of a variable.\n *\n * @see {@link https://hono.dev/docs/api/context#var}\n *\n * @example\n * ```ts\n * const result = c.var.client.oneMethod()\n * ```\n */\n // c.var.propName is a read-only\n get var() {\n if (!this.#var) {\n return {};\n }\n return Object.fromEntries(this.#var);\n }\n #newResponse(data, arg, headers) {\n let responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders;\n if (typeof arg === \"object\" && arg.headers) {\n responseHeaders ??= new Headers();\n for (const [key, value] of new Headers(arg.headers)) {\n if (key === \"set-cookie\") {\n responseHeaders.append(key, value);\n } else {\n responseHeaders.set(key, value);\n }\n }\n }\n if (headers) {\n if (!responseHeaders) {\n let count = 0;\n for (const k in headers) {\n if (++count > 1 || typeof headers[k] !== \"string\") {\n responseHeaders = new Headers();\n break;\n }\n }\n }\n if (responseHeaders) {\n for (const k in headers) {\n const v = headers[k];\n if (typeof v === \"string\") {\n responseHeaders.set(k, v);\n } else {\n responseHeaders.delete(k);\n for (const v2 of v) {\n responseHeaders.append(k, v2);\n }\n }\n }\n }\n }\n const status = typeof arg === \"number\" ? arg : arg?.status ?? this.#status;\n return createResponseInstance(data, {\n status,\n headers: responseHeaders ?? headers\n });\n }\n newResponse = (...args) => this.#newResponse(...args);\n /**\n * `.body()` can return the HTTP response.\n * You can set headers with `.header()` and set HTTP status code with `.status`.\n * This can also be set in `.text()`, `.json()` and so on.\n *\n * @see {@link https://hono.dev/docs/api/context#body}\n *\n * @example\n * ```ts\n * app.get('/welcome', (c) => {\n * // Set headers\n * c.header('X-Message', 'Hello!')\n * c.header('Content-Type', 'text/plain')\n * // Set HTTP status code\n * c.status(201)\n *\n * // Return the response body\n * return c.body('Thank you for coming')\n * })\n * ```\n */\n body = (data, arg, headers) => this.#newResponse(data, arg, headers);\n /**\n * `.text()` can render text as `Content-Type:text/plain`.\n *\n * @see {@link https://hono.dev/docs/api/context#text}\n *\n * @example\n * ```ts\n * app.get('/say', (c) => {\n * return c.text('Hello!')\n * })\n * ```\n */\n text = (text, arg, headers) => {\n return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(\n text,\n arg,\n setDefaultContentType(TEXT_PLAIN, headers)\n );\n };\n /**\n * `.json()` can render JSON as `Content-Type:application/json`.\n *\n * @see {@link https://hono.dev/docs/api/context#json}\n *\n * @example\n * ```ts\n * app.get('/api', (c) => {\n * return c.json({ message: 'Hello!' })\n * })\n * ```\n */\n json = (object, arg, headers) => {\n return this.#newResponse(\n JSON.stringify(object),\n arg,\n setDefaultContentType(\"application/json\", headers)\n );\n };\n html = (html, arg, headers) => {\n const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType(\"text/html; charset=UTF-8\", headers));\n return typeof html === \"object\" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);\n };\n /**\n * `.redirect()` can Redirect, default status code is 302.\n *\n * @see {@link https://hono.dev/docs/api/context#redirect}\n *\n * @example\n * ```ts\n * app.get('/redirect', (c) => {\n * return c.redirect('/')\n * })\n * app.get('/redirect-permanently', (c) => {\n * return c.redirect('/', 301)\n * })\n * ```\n */\n redirect = (location, status) => {\n const locationString = String(location);\n this.header(\n \"Location\",\n // Multibyes should be encoded\n // eslint-disable-next-line no-control-regex\n !/[^\\x00-\\xFF]/.test(locationString) ? locationString : encodeURI(locationString)\n );\n return this.newResponse(null, status ?? 302);\n };\n /**\n * `.notFound()` can return the Not Found Response.\n *\n * @see {@link https://hono.dev/docs/api/context#notfound}\n *\n * @example\n * ```ts\n * app.get('/notfound', (c) => {\n * return c.notFound()\n * })\n * ```\n */\n notFound = () => {\n this.#notFoundHandler ??= () => createResponseInstance();\n return this.#notFoundHandler(this);\n };\n};\nexport {\n Context,\n TEXT_PLAIN\n};\n","// src/router.ts\nvar METHOD_NAME_ALL = \"ALL\";\nvar METHOD_NAME_ALL_LOWERCASE = \"all\";\nvar METHODS = [\"get\", \"post\", \"put\", \"delete\", \"options\", \"patch\", \"query\"];\nvar MESSAGE_MATCHER_IS_ALREADY_BUILT = \"Can not add a route since the matcher is already built.\";\nvar UnsupportedPathError = class extends Error {\n};\nexport {\n MESSAGE_MATCHER_IS_ALREADY_BUILT,\n METHODS,\n METHOD_NAME_ALL,\n METHOD_NAME_ALL_LOWERCASE,\n UnsupportedPathError\n};\n","// src/utils/constants.ts\nvar COMPOSED_HANDLER = \"__COMPOSED_HANDLER\";\nexport {\n COMPOSED_HANDLER\n};\n","// src/hono-base.ts\nimport { compose } from \"./compose.js\";\nimport { Context } from \"./context.js\";\nimport { METHODS, METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE } from \"./router.js\";\nimport { COMPOSED_HANDLER } from \"./utils/constants.js\";\nimport { getPath, getPathNoStrict, mergePath } from \"./utils/url.js\";\nvar notFoundHandler = (c) => {\n return c.text(\"404 Not Found\", 404);\n};\nvar errorHandler = (err, c) => {\n if (\"getResponse\" in err) {\n const res = err.getResponse();\n return c.newResponse(res.body, res);\n }\n console.error(err);\n return c.text(\"Internal Server Error\", 500);\n};\nvar Hono = class _Hono {\n get;\n post;\n put;\n delete;\n options;\n patch;\n query;\n all;\n on;\n use;\n /*\n This class is like an abstract class and does not have a router.\n To use it, inherit the class and implement router in the constructor.\n */\n router;\n getPath;\n // Cannot use `#` because it requires visibility at JavaScript runtime.\n _basePath = \"/\";\n #path = \"/\";\n routes = [];\n constructor(options = {}) {\n const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];\n allMethods.forEach((method) => {\n this[method] = (args1, ...args) => {\n if (typeof args1 === \"string\") {\n this.#path = args1;\n } else {\n this.#addRoute(method, this.#path, args1);\n }\n args.forEach((handler) => {\n this.#addRoute(method, this.#path, handler);\n });\n return this;\n };\n });\n this.on = (method, path, ...handlers) => {\n for (const p of [path].flat()) {\n this.#path = p;\n for (const m of [method].flat()) {\n handlers.map((handler) => {\n this.#addRoute(m.toUpperCase(), this.#path, handler);\n });\n }\n }\n return this;\n };\n this.use = (arg1, ...handlers) => {\n if (typeof arg1 === \"string\") {\n this.#path = arg1;\n } else {\n this.#path = \"*\";\n handlers.unshift(arg1);\n }\n handlers.forEach((handler) => {\n this.#addRoute(METHOD_NAME_ALL, this.#path, handler);\n });\n return this;\n };\n const { strict, ...optionsWithoutStrict } = options;\n Object.assign(this, optionsWithoutStrict);\n this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;\n }\n #clone() {\n const clone = new _Hono({\n router: this.router,\n getPath: this.getPath\n });\n clone.errorHandler = this.errorHandler;\n clone.#notFoundHandler = this.#notFoundHandler;\n clone.routes = this.routes;\n return clone;\n }\n #notFoundHandler = notFoundHandler;\n // Cannot use `#` because it requires visibility at JavaScript runtime.\n errorHandler = errorHandler;\n /**\n * `.route()` allows grouping other Hono instance in routes.\n *\n * @see {@link https://hono.dev/docs/api/routing#grouping}\n *\n * @param {string} path - base Path\n * @param {Hono} app - other Hono instance\n * @returns {Hono} routed Hono instance\n *\n * @example\n * ```ts\n * const app = new Hono()\n * const app2 = new Hono()\n *\n * app2.get(\"/user\", (c) => c.text(\"user\"))\n * app.route(\"/api\", app2) // GET /api/user\n * ```\n */\n route(path, app) {\n const subApp = this.basePath(path);\n app.routes.map((r) => {\n let handler;\n if (app.errorHandler === errorHandler) {\n handler = r.handler;\n } else {\n handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;\n handler[COMPOSED_HANDLER] = r.handler;\n }\n subApp.#addRoute(r.method, r.path, handler, r.basePath);\n });\n return this;\n }\n /**\n * `.basePath()` allows base paths to be specified.\n *\n * @see {@link https://hono.dev/docs/api/routing#base-path}\n *\n * @param {string} path - base Path\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * const api = new Hono().basePath('/api')\n * ```\n */\n basePath(path) {\n const subApp = this.#clone();\n subApp._basePath = mergePath(this._basePath, path);\n return subApp;\n }\n /**\n * `.onError()` handles an error and returns a customized Response.\n *\n * @see {@link https://hono.dev/docs/api/hono#error-handling}\n *\n * @param {ErrorHandler} handler - request Handler for error\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * app.onError((err, c) => {\n * console.error(`${err}`)\n * return c.text('Custom Error Message', 500)\n * })\n * ```\n */\n onError = (handler) => {\n this.errorHandler = handler;\n return this;\n };\n /**\n * `.notFound()` allows you to customize a Not Found Response.\n *\n * @see {@link https://hono.dev/docs/api/hono#not-found}\n *\n * @param {NotFoundHandler} handler - request handler for not-found\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * app.notFound((c) => {\n * return c.text('Custom 404 Message', 404)\n * })\n * ```\n */\n notFound = (handler) => {\n this.#notFoundHandler = handler;\n return this;\n };\n /**\n * `.mount()` allows you to mount applications built with other frameworks into your Hono application.\n *\n * @see {@link https://hono.dev/docs/api/hono#mount}\n *\n * @param {string} path - base Path\n * @param {Function} applicationHandler - other Request Handler\n * @param {MountOptions} [options] - options of `.mount()`\n * @returns {Hono} mounted Hono instance\n *\n * @example\n * ```ts\n * import { Router as IttyRouter } from 'itty-router'\n * import { Hono } from 'hono'\n * // Create itty-router application\n * const ittyRouter = IttyRouter()\n * // GET /itty-router/hello\n * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))\n *\n * const app = new Hono()\n * app.mount('/itty-router', ittyRouter.handle)\n * ```\n *\n * @example\n * ```ts\n * const app = new Hono()\n * // Send the request to another application without modification.\n * app.mount('/app', anotherApp, {\n * replaceRequest: (req) => req,\n * })\n * ```\n */\n mount(path, applicationHandler, options) {\n let replaceRequest;\n let optionHandler;\n if (options) {\n if (typeof options === \"function\") {\n optionHandler = options;\n } else {\n optionHandler = options.optionHandler;\n if (options.replaceRequest === false) {\n replaceRequest = (request) => request;\n } else {\n replaceRequest = options.replaceRequest;\n }\n }\n }\n const getOptions = optionHandler ? (c) => {\n const options2 = optionHandler(c);\n return Array.isArray(options2) ? options2 : [options2];\n } : (c) => {\n let executionContext = void 0;\n try {\n executionContext = c.executionCtx;\n } catch {\n }\n return [c.env, executionContext];\n };\n replaceRequest ||= (() => {\n const mergedPath = mergePath(this._basePath, path);\n const pathPrefixLength = mergedPath === \"/\" ? 0 : mergedPath.length;\n return (request) => {\n const url = new URL(request.url);\n url.pathname = this.getPath(request).slice(pathPrefixLength) || \"/\";\n return new Request(url, request);\n };\n })();\n const handler = async (c, next) => {\n const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));\n if (res) {\n return res;\n }\n await next();\n };\n this.#addRoute(METHOD_NAME_ALL, mergePath(path, \"*\"), handler);\n return this;\n }\n #addRoute(method, path, handler, baseRoutePath) {\n method = method.toUpperCase();\n path = mergePath(this._basePath, path);\n const r = {\n basePath: baseRoutePath !== void 0 ? mergePath(this._basePath, baseRoutePath) : this._basePath,\n path,\n method,\n handler\n };\n this.router.add(method, path, [handler, r]);\n this.routes.push(r);\n }\n #handleError(err, c) {\n if (err instanceof Error) {\n return this.errorHandler(err, c);\n }\n throw err;\n }\n #dispatch(request, executionCtx, env, method) {\n if (method === \"HEAD\") {\n return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, \"GET\")))();\n }\n const path = this.getPath(request, { env });\n const matchResult = this.router.match(method, path);\n const c = new Context(request, {\n path,\n matchResult,\n env,\n executionCtx,\n notFoundHandler: this.#notFoundHandler\n });\n if (matchResult[0].length === 1) {\n let res;\n try {\n res = matchResult[0][0][0][0](c, async () => {\n c.res = await this.#notFoundHandler(c);\n });\n } catch (err) {\n return this.#handleError(err, c);\n }\n return res instanceof Promise ? res.then(\n (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))\n ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);\n }\n const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);\n return (async () => {\n try {\n const context = await composed(c);\n if (!context.finalized) {\n throw new Error(\n \"Context is not finalized. Did you forget to return a Response object or `await next()`?\"\n );\n }\n return context.res;\n } catch (err) {\n return this.#handleError(err, c);\n }\n })();\n }\n /**\n * `.fetch()` will be entry point of your app.\n *\n * @see {@link https://hono.dev/docs/api/hono#fetch}\n *\n * @param {Request} request - request Object of request\n * @param {Env} env - env Object\n * @param {ExecutionContext} executionCtx - context of execution\n * @returns {Response | Promise<Response>} response of request\n *\n */\n fetch = (request, ...rest) => {\n return this.#dispatch(request, rest[1], rest[0], request.method);\n };\n /**\n * `.request()` is a useful method for testing.\n * You can pass a URL or pathname to send a GET request.\n * app will return a Response object.\n * ```ts\n * test('GET /hello is ok', async () => {\n * const res = await app.request('/hello')\n * expect(res.status).toBe(200)\n * })\n * ```\n * @see https://hono.dev/docs/api/hono#request\n */\n request = (input, requestInit, Env, executionCtx) => {\n if (input instanceof Request) {\n return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);\n }\n input = input.toString();\n return this.fetch(\n new Request(\n /^https?:\\/\\//.test(input) ? input : `http://localhost${mergePath(\"/\", input)}`,\n requestInit\n ),\n Env,\n executionCtx\n );\n };\n /**\n * `.fire()` automatically adds a global fetch event listener.\n * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.\n * @deprecated\n * Use `fire` from `hono/service-worker` instead.\n * ```ts\n * import { Hono } from 'hono'\n * import { fire } from 'hono/service-worker'\n *\n * const app = new Hono()\n * // ...\n * fire(app)\n * ```\n * @see https://hono.dev/docs/api/hono#fire\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API\n * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/\n */\n fire = () => {\n addEventListener(\"fetch\", (event) => {\n event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));\n });\n };\n};\nexport {\n Hono as HonoBase\n};\n","// src/router/utils.ts\nvar createNullObject = () => /* @__PURE__ */ Object.create(null);\nexport {\n createNullObject\n};\n","// src/router/reg-exp-router/matcher.ts\nimport { METHOD_NAME_ALL } from \"../../router.js\";\nvar emptyParam = [];\nfunction match(method, path) {\n const matchers = this.buildAllMatchers();\n const match2 = ((method2, path2) => {\n const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];\n const staticMatch = matcher[2][path2];\n if (staticMatch) {\n return staticMatch;\n }\n const match3 = path2.match(matcher[0]);\n if (!match3) {\n return [[], emptyParam];\n }\n const index = match3.indexOf(\"\", 1);\n return [matcher[1][index], match3];\n });\n this.match = match2;\n return match2(method, path);\n}\nexport {\n emptyParam,\n match\n};\n","// src/router/reg-exp-router/node.ts\nimport { createNullObject } from \"../utils.js\";\nvar LABEL_REG_EXP_STR = \"[^/]+\";\nvar ONLY_WILDCARD_REG_EXP_STR = \".*\";\nvar TAIL_WILDCARD_REG_EXP_STR = \"(?:|/.*)\";\nvar PATH_ERROR = /* @__PURE__ */ Symbol();\nvar regExpMetaChars = new Set(\".\\\\+*[^]$()\");\nfunction compareKey(a, b) {\n if (a.length === 1) {\n return b.length === 1 ? a < b ? -1 : 1 : -1;\n }\n if (b.length === 1) {\n return 1;\n }\n if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {\n return b === TAIL_WILDCARD_REG_EXP_STR ? -1 : 1;\n } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {\n return -1;\n }\n if (a === LABEL_REG_EXP_STR) {\n return 1;\n } else if (b === LABEL_REG_EXP_STR) {\n return -1;\n }\n return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;\n}\nvar Node = class _Node {\n // handler index of a dynamic path, or -1 for a static path terminal\n #index;\n #varIndex;\n #children = createNullObject();\n insert(tokens, index, paramMap, context, isStatic) {\n let node = this;\n for (let i = 0, len = tokens.length; i < len; i++) {\n const token = tokens[i];\n const pattern = token.length === 1 ? token === \"*\" ? i === len - 1 ? [\"\", \"\", ONLY_WILDCARD_REG_EXP_STR] : [\"\", \"\", LABEL_REG_EXP_STR] : null : token === \"/*\" ? [\"\", \"\", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\\:([^\\{\\}]+)(?:\\{(.+)\\})?$/);\n let nextNode;\n if (pattern) {\n const name = pattern[1];\n let regexpStr = pattern[2] || LABEL_REG_EXP_STR;\n if (name && pattern[2]) {\n if (regexpStr === \".*\") {\n throw PATH_ERROR;\n }\n regexpStr = regexpStr.replace(/^\\((?!\\?:)(?=[^)]+\\)$)/, \"(?:\");\n if (/\\((?!\\?:)/.test(regexpStr)) {\n throw PATH_ERROR;\n }\n if (regexpStr.length === 1 && regExpMetaChars.has(regexpStr)) {\n throw PATH_ERROR;\n }\n }\n nextNode = node.#children[regexpStr];\n if (!nextNode) {\n if (regexpStr !== ONLY_WILDCARD_REG_EXP_STR && regexpStr !== TAIL_WILDCARD_REG_EXP_STR) {\n for (const k in node.#children) {\n if (\n // a single-char pattern coexists with single-char literals as a literal does\n (regexpStr.length > 1 || k.length > 1) && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR\n ) {\n throw PATH_ERROR;\n }\n }\n }\n nextNode = node.#children[regexpStr] = new _Node();\n }\n if (name !== \"\") {\n nextNode.#varIndex ??= context.varIndex++;\n paramMap.push([name, nextNode.#varIndex]);\n }\n } else {\n nextNode = node.#children[token];\n if (!nextNode) {\n for (const k in node.#children) {\n if (k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR) {\n throw PATH_ERROR;\n }\n }\n nextNode = node.#children[token] = new _Node();\n }\n }\n node = nextNode;\n }\n if (node.#index !== void 0) {\n throw PATH_ERROR;\n }\n node.#index = isStatic ? -1 : index;\n }\n buildRegExpStr() {\n const childKeys = Object.keys(this.#children).sort(compareKey);\n const strList = childKeys.map((k) => {\n const c = this.#children[k];\n const childStr = c.buildRegExpStr();\n return childStr === \"\" ? \"\" : (typeof c.#varIndex === \"number\" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\\\${k}` : k) + childStr;\n }).filter(Boolean);\n if (typeof this.#index === \"number\" && this.#index !== -1) {\n strList.unshift(`#${this.#index}`);\n }\n if (strList.length === 0) {\n return \"\";\n }\n if (strList.length === 1) {\n return strList[0];\n }\n return \"(?:\" + strList.join(\"|\") + \")\";\n }\n};\nexport {\n LABEL_REG_EXP_STR,\n Node,\n ONLY_WILDCARD_REG_EXP_STR,\n PATH_ERROR,\n TAIL_WILDCARD_REG_EXP_STR\n};\n","// src/router/reg-exp-router/trie.ts\nimport { createNullObject } from \"../utils.js\";\nimport { Node } from \"./node.js\";\nvar Trie = class {\n #context = { varIndex: 0 };\n #root = new Node();\n #index = 0;\n // dynamic path -> [handler index, param assoc]; static paths are not registered\n paths = createNullObject();\n insert(path, isStatic) {\n if (isStatic) {\n this.#root.insert(path.split(\"\"), 0, [], this.#context, true);\n return;\n }\n const paramAssoc = [];\n const groups = [];\n let markedPath = path;\n for (let i = 0; ; ) {\n let replaced = false;\n markedPath = markedPath.replace(/\\{[^}]+\\}/g, (m) => {\n const mark = `@\\\\${i}`;\n groups[i] = [mark, m];\n i++;\n replaced = true;\n return mark;\n });\n if (!replaced) {\n break;\n }\n }\n const tokens = markedPath.match(/(?::[^\\/]+)|(?:\\/\\*$)|./g) || [];\n for (let i = groups.length - 1; i >= 0; i--) {\n const [mark] = groups[i];\n for (let j = tokens.length - 1; j >= 0; j--) {\n if (tokens[j].indexOf(mark) !== -1) {\n tokens[j] = tokens[j].replace(mark, groups[i][1]);\n break;\n }\n }\n }\n this.#root.insert(tokens, this.#index, paramAssoc, this.#context, false);\n this.paths[path] = [this.#index++, paramAssoc];\n }\n buildRegExp() {\n let regexp = this.#root.buildRegExpStr();\n if (regexp === \"\") {\n return [/^$/, [], []];\n }\n let captureIndex = 0;\n const indexReplacementMap = [];\n const paramReplacementMap = [];\n regexp = regexp.replace(/#(\\d+)|@(\\d+)|\\.\\*\\$/g, (_, handlerIndex, paramIndex) => {\n if (handlerIndex !== void 0) {\n indexReplacementMap[++captureIndex] = Number(handlerIndex);\n return \"$()\";\n }\n if (paramIndex !== void 0) {\n paramReplacementMap[Number(paramIndex)] = ++captureIndex;\n return \"\";\n }\n return \"\";\n });\n return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];\n }\n};\nexport {\n Trie\n};\n","// src/router/reg-exp-router/router.ts\nimport {\n MESSAGE_MATCHER_IS_ALREADY_BUILT,\n METHOD_NAME_ALL,\n UnsupportedPathError\n} from \"../../router.js\";\nimport { checkOptionalParameter } from \"../../utils/url.js\";\nimport { createNullObject } from \"../utils.js\";\nimport { match, emptyParam } from \"./matcher.js\";\nimport {\n LABEL_REG_EXP_STR,\n ONLY_WILDCARD_REG_EXP_STR,\n PATH_ERROR,\n TAIL_WILDCARD_REG_EXP_STR\n} from \"./node.js\";\nimport { Trie } from \"./trie.js\";\nvar wildcardRegExpCache = createNullObject();\nfunction buildWildcardRegExp(path) {\n return wildcardRegExpCache[path] ??= new RegExp(\n `^${path.replace(\n /\\/:[^/{}]+(?:\\{\\[\\^\\/]\\+})?(?=[/{]|$)|\\/?\\*$|([.\\\\+*[^\\]$()?{}|])/g,\n (match2, metaChar) => metaChar ? `\\\\${metaChar}` : match2 === \"/*\" ? TAIL_WILDCARD_REG_EXP_STR : match2 === \"*\" ? ONLY_WILDCARD_REG_EXP_STR : `/:${LABEL_REG_EXP_STR}`\n )}$`\n );\n}\nfunction findMiddleware(middleware, path) {\n for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {\n if (buildWildcardRegExp(k).test(path)) {\n return [...middleware[k]];\n }\n }\n return void 0;\n}\nvar RegExpRouter = class {\n name = \"RegExpRouter\";\n #middleware;\n #routes;\n #tries;\n constructor() {\n this.#middleware = { [METHOD_NAME_ALL]: createNullObject() };\n this.#routes = { [METHOD_NAME_ALL]: createNullObject() };\n this.#tries = { [METHOD_NAME_ALL]: new Trie() };\n }\n #insertPath(method, path) {\n try {\n this.#tries[method].insert(path, !/\\*|\\/:/.test(path));\n } catch (e) {\n throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;\n }\n }\n add(method, path, handler) {\n const middleware = this.#middleware;\n const routes = this.#routes;\n if (!middleware) {\n throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);\n }\n if (!middleware[method]) {\n this.#tries[method] = new Trie();\n for (const handlerMap of [middleware, routes]) {\n handlerMap[method] = createNullObject();\n for (const p in handlerMap[METHOD_NAME_ALL]) {\n handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];\n this.#insertPath(method, p);\n }\n }\n }\n if (path === \"/*\") {\n path = \"*\";\n }\n const methods = method === METHOD_NAME_ALL ? Object.keys(middleware) : [method];\n if (/\\*$/.test(path)) {\n const re = buildWildcardRegExp(path);\n for (const m of methods) {\n if (!middleware[m][path]) {\n this.#insertPath(m, path);\n middleware[m][path] = findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];\n }\n }\n for (const handlerMap of [middleware, routes]) {\n for (const m of methods) {\n for (const p in handlerMap[m]) {\n re.test(p) && handlerMap[m][p].push([handler, path]);\n }\n }\n }\n return;\n }\n const paths = checkOptionalParameter(path) || [path];\n for (const path2 of paths) {\n for (const m of methods) {\n if (!routes[m][path2]) {\n this.#insertPath(m, path2);\n routes[m][path2] = findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || [];\n }\n routes[m][path2].push([handler, path2]);\n }\n }\n }\n match = match;\n buildAllMatchers() {\n const matchers = createNullObject();\n for (const method of Object.keys(this.#routes)) {\n matchers[method] = this.#buildMatcher(method);\n }\n this.#middleware = this.#routes = this.#tries = void 0;\n wildcardRegExpCache = createNullObject();\n return matchers;\n }\n #buildMatcher(method) {\n const middleware = this.#middleware[method];\n const routes = this.#routes[method];\n const trie = this.#tries[method];\n const staticMap = createNullObject();\n const handlerData = [];\n const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();\n for (const r of [middleware, routes]) {\n for (const path in r) {\n const handlers = r[path];\n const pathData = trie.paths[path];\n if (!pathData) {\n staticMap[path] = [handlers.map(([h]) => [h, createNullObject()]), emptyParam];\n continue;\n }\n handlerData[pathData[0]] = handlers.map(([h, handlerPath]) => [\n h,\n trie.paths[handlerPath][1].reduceRight((map, [key], i) => {\n map[key] = paramReplacementMap[pathData[1][i][1]];\n return map;\n }, createNullObject())\n ]);\n }\n }\n return [regexp, indexReplacementMap.map((i) => handlerData[i]), staticMap];\n }\n};\nexport {\n RegExpRouter\n};\n","// src/router/smart-router/router.ts\nimport { MESSAGE_MATCHER_IS_ALREADY_BUILT, UnsupportedPathError } from \"../../router.js\";\nvar SmartRouter = class {\n name = \"SmartRouter\";\n #routers = [];\n #routes = [];\n constructor(init) {\n this.#routers = init.routers;\n }\n add(method, path, handler) {\n if (!this.#routes) {\n throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);\n }\n this.#routes.push([method, path, handler]);\n }\n match(method, path) {\n if (!this.#routes) {\n throw new Error(\"Fatal error\");\n }\n const routers = this.#routers;\n const routes = this.#routes;\n const len = routers.length;\n let i = 0;\n let res;\n for (; i < len; i++) {\n const router = routers[i];\n try {\n for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {\n router.add(...routes[i2]);\n }\n res = router.match(method, path);\n } catch (e) {\n if (e instanceof UnsupportedPathError) {\n continue;\n }\n throw e;\n }\n this.match = router.match.bind(router);\n this.#routers = [router];\n this.#routes = void 0;\n break;\n }\n if (i === len) {\n throw new Error(\"Fatal error\");\n }\n this.name = `SmartRouter + ${this.activeRouter.name}`;\n return res;\n }\n get activeRouter() {\n if (this.#routes || this.#routers.length !== 1) {\n throw new Error(\"No active router has been determined yet.\");\n }\n return this.#routers[0];\n }\n};\nexport {\n SmartRouter\n};\n","// src/router/trie-router/node.ts\nimport { METHOD_NAME_ALL } from \"../../router.js\";\nimport { getPattern, splitPath, splitRoutingPath } from \"../../utils/url.js\";\nimport { createNullObject } from \"../utils.js\";\nvar emptyParams = createNullObject();\nvar order = 0;\nvar Node = class _Node {\n #methods = [];\n #children = createNullObject();\n #patterns = [];\n #pattern;\n #params = emptyParams;\n insert(method, path, handler) {\n let curNode = this;\n const parts = splitRoutingPath(path);\n const possibleKeys = /* @__PURE__ */ new Set();\n let i = 0;\n for (const p of parts) {\n const nextP = parts[++i];\n const pattern = getPattern(p, nextP) || (nextP === void 0 && p && p.indexOf(\"*\") === p.length - 1 ? p : null);\n const isParam = Array.isArray(pattern);\n const key = isParam ? pattern[0] : pattern || p;\n const child = curNode.#children[key] ||= new _Node();\n if (pattern && !child.#pattern) {\n child.#pattern = pattern;\n curNode.#patterns.push(child);\n }\n curNode = child;\n if (isParam) {\n possibleKeys.add(pattern[1]);\n }\n }\n curNode.#methods.push({\n [method]: {\n handler,\n possibleKeys: [...possibleKeys],\n score: ++order\n }\n });\n }\n #pushHandlerSets(handlerSets, node, method, nodeParams, params) {\n for (let i = 0, len = node.#methods.length; i < len; i++) {\n const m = node.#methods[i];\n const handlerSet = m[method] || m[METHOD_NAME_ALL];\n if (handlerSet) {\n handlerSet.params = createNullObject();\n handlerSets.push(handlerSet);\n for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {\n const key = handlerSet.possibleKeys[i2];\n handlerSet.params[key] = params?.[key] && !i2 ? params[key] : nodeParams[key] ?? params?.[key];\n }\n }\n }\n }\n search(method, path) {\n const handlerSets = [];\n this.#params = emptyParams;\n const curNode = this;\n let curNodes = [curNode];\n const parts = splitPath(path);\n const curNodesQueue = [];\n const len = parts.length;\n let partOffsets = null;\n for (let i = 0; i < len; i++) {\n const part = parts[i];\n const isLast = i === len - 1;\n const tempNodes = [];\n for (let j = 0, len2 = curNodes.length; j < len2; j++) {\n const node = curNodes[j];\n const nextNode = node.#children[part];\n if (nextNode) {\n nextNode.#params = node.#params;\n if (isLast) {\n if (nextNode.#children[\"*\"]) {\n this.#pushHandlerSets(handlerSets, nextNode.#children[\"*\"], method, node.#params);\n }\n this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);\n } else {\n tempNodes.push(nextNode);\n }\n }\n for (const child of node.#patterns) {\n const pattern = child.#pattern;\n const params = node.#params === emptyParams ? {} : { ...node.#params };\n if (typeof pattern === \"string\") {\n if (pattern === \"*\" || part.startsWith(pattern.slice(0, -1))) {\n this.#pushHandlerSets(handlerSets, child, method, node.#params);\n if (pattern === \"*\") {\n child.#params = params;\n tempNodes.push(child);\n }\n }\n continue;\n }\n const [, name, matcher] = pattern;\n if (!part && matcher === true) {\n continue;\n }\n if (matcher !== true) {\n if (!partOffsets) {\n partOffsets = [];\n let offset = path[0] === \"/\" ? 1 : 0;\n for (let p = 0; p < len; p++) {\n partOffsets[p] = offset;\n offset += parts[p].length + 1;\n }\n }\n const restPathString = path.slice(partOffsets[i]);\n const m = matcher.exec(restPathString);\n if (m) {\n params[name] = m[0];\n this.#pushHandlerSets(handlerSets, child, method, node.#params, params);\n if (m[0].length === restPathString.length && child.#children[\"*\"]) {\n this.#pushHandlerSets(\n handlerSets,\n child.#children[\"*\"],\n method,\n node.#params,\n params\n );\n }\n for (const _ in child.#children) {\n child.#params = params;\n const componentCount = m[0].match(/\\//g)?.length ?? 0;\n const targetCurNodes = curNodesQueue[componentCount] ||= [];\n targetCurNodes.push(child);\n break;\n }\n continue;\n }\n }\n if (matcher === true || matcher.test(part)) {\n params[name] = part;\n if (isLast) {\n this.#pushHandlerSets(handlerSets, child, method, params, node.#params);\n if (child.#children[\"*\"]) {\n this.#pushHandlerSets(\n handlerSets,\n child.#children[\"*\"],\n method,\n params,\n node.#params\n );\n }\n } else {\n child.#params = params;\n tempNodes.push(child);\n }\n }\n }\n }\n const shifted = curNodesQueue.shift();\n curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;\n }\n if (handlerSets[1]) {\n handlerSets.sort((a, b) => {\n return a.score - b.score;\n });\n }\n return [handlerSets.map(({ handler, params }) => [handler, params])];\n }\n};\nexport {\n Node\n};\n","// src/router/trie-router/router.ts\nimport { checkOptionalParameter } from \"../../utils/url.js\";\nimport { Node } from \"./node.js\";\nvar TrieRouter = class {\n name = \"TrieRouter\";\n #node = new Node();\n add(method, path, handler) {\n for (const result of checkOptionalParameter(path) || [path]) {\n this.#node.insert(method, result, handler);\n }\n }\n match(method, path) {\n return this.#node.search(method, path);\n }\n};\nexport {\n TrieRouter\n};\n","// src/hono.ts\nimport { HonoBase } from \"./hono-base.js\";\nimport { RegExpRouter } from \"./router/reg-exp-router/index.js\";\nimport { SmartRouter } from \"./router/smart-router/index.js\";\nimport { TrieRouter } from \"./router/trie-router/index.js\";\nvar Hono = class extends HonoBase {\n /**\n * Creates an instance of the Hono class.\n *\n * @param options - Optional configuration options for the Hono instance.\n */\n constructor(options = {}) {\n super(options);\n this.router = options.router ?? new SmartRouter({\n routers: [new RegExpRouter(), new TrieRouter()]\n });\n }\n};\nexport {\n Hono\n};\n","import type { CoordinatorAccountLinkStatusStore } from \"./coordinator-account-link-status.js\";\nimport type {\n\tCoordinatorAccountOwnerTarget,\n\tCoordinatorAccountOwnerTargetStore,\n} from \"./coordinator-account-owner-target.js\";\nimport type {\n\tCoordinatorAuthControllerStore,\n\tCoordinatorAuthControllerVerifiedSnapshot,\n} from \"./coordinator-auth-controller.js\";\nimport type { ControllerHistoryEvidence } from \"./coordinator-auth-controller-history.js\";\nimport type { CoordinatorAuthLinkConfig } from \"./coordinator-auth-link-contract.js\";\nimport { legacyDecisionCountsAsOwner } from \"./coordinator-legacy-team-completion.js\";\nimport type { CoordinatorEnrollment } from \"./coordinator-store-contract.js\";\n\nexport type ExistingOwnerReviewCapabilities = Partial<\n\tCoordinatorAccountOwnerTargetStore &\n\t\tCoordinatorAccountLinkStatusStore &\n\t\tPick<CoordinatorAuthControllerStore, \"hasAuthControllerSubjectOwnerConflict\">\n>;\nexport interface CoordinatorControllerOwnerAdvisory {\n\tidentity_id: string;\n\tlink_id: string;\n\tauth_config_revision: string;\n\tcreated_at_ms: number;\n\tactive_review: {\n\t\tattestation_id: string;\n\t\treview_receipt_id: string;\n\t\tevidence_digest: string;\n\t} | null;\n}\n\n/** No account profile or issuer data crosses this advisory boundary. */\nexport async function prepareExistingOwnerReview(options: {\n\tstore: ExistingOwnerReviewCapabilities;\n\tenrollment: CoordinatorEnrollment | null;\n\tidentityId: string;\n\tconfig: CoordinatorAuthLinkConfig;\n\tsnapshot: CoordinatorAuthControllerVerifiedSnapshot;\n}): Promise<{\n\ttarget?: CoordinatorControllerOwnerAdvisory;\n\treason?: \"account_owner_target_unavailable\" | \"account_owner_conflict\";\n}> {\n\tconst { store, enrollment, identityId, config, snapshot } = options;\n\tif (\n\t\t!enrollment ||\n\t\t!store.readAccountOwnerTarget ||\n\t\t!store.readAccountLinkStatus ||\n\t\t!store.hasAuthControllerSubjectOwnerConflict ||\n\t\t!snapshot.legacyHistory\n\t)\n\t\treturn { reason: \"account_owner_target_unavailable\" };\n\tconst signer = {\n\t\tgroupId: enrollment.group_id,\n\t\tdeviceId: enrollment.device_id,\n\t\tpublicKey: enrollment.public_key,\n\t\tfingerprint: enrollment.fingerprint,\n\t};\n\ttry {\n\t\tconst target = await store.readAccountOwnerTarget(\n\t\t\t{ targetIdentityId: identityId, signer },\n\t\t\tconfig,\n\t\t);\n\t\tif (target.kind !== \"ready\") return { reason: \"account_owner_target_unavailable\" };\n\t\tif (\n\t\t\tawait store.hasAuthControllerSubjectOwnerConflict({\n\t\t\t\tidentityId,\n\t\t\t\thistory: snapshot.legacyHistory,\n\t\t\t})\n\t\t)\n\t\t\treturn { reason: \"account_owner_conflict\" };\n\t\tconst status = await store.readAccountLinkStatus(signer, config, { identityId });\n\t\tif (\n\t\t\tstatus.state === \"conflict\" ||\n\t\t\tstatus.state === \"revoked\" ||\n\t\t\t(status.identityId !== null && status.identityId !== identityId)\n\t\t)\n\t\t\treturn { reason: \"account_owner_conflict\" };\n\t\tsnapshot.accountOwnerTarget = {\n\t\t\tpurpose: \"existing_account_owner\",\n\t\t\tcoordinatorId: config.coordinatorId,\n\t\t\ttargetIdentityId: identityId,\n\t\t\tissuer: config.issuer,\n\t\t\tlinkId: target.linkId,\n\t\t\tauthConfigRevision: target.currentGeneration.authConfigRevision,\n\t\t\tcreatedAtMs: target.currentGeneration.createdAtMs,\n\t\t};\n\t\treturn { target: projectTarget(target) };\n\t} catch {\n\t\treturn { reason: \"account_owner_target_unavailable\" };\n\t}\n}\n\nfunction projectTarget(\n\ttarget: Extract<CoordinatorAccountOwnerTarget, { kind: \"ready\" }>,\n): CoordinatorControllerOwnerAdvisory {\n\treturn {\n\t\tidentity_id: target.targetIdentityId,\n\t\tlink_id: target.linkId,\n\t\tauth_config_revision: target.currentGeneration.authConfigRevision,\n\t\tcreated_at_ms: target.currentGeneration.createdAtMs,\n\t\tactive_review: target.review\n\t\t\t? {\n\t\t\t\t\tattestation_id: target.review.attestationId,\n\t\t\t\t\treview_receipt_id: target.review.reviewReceiptId,\n\t\t\t\t\tevidence_digest: target.review.evidenceDigest,\n\t\t\t\t}\n\t\t\t: null,\n\t};\n}\n\n/**\n * Hints are only subject assignments, never the other people in the retained\n * manifests, and never another device's guessed label.\n */\nexport function historicalOwnerHints(\n\thistory: ControllerHistoryEvidence[],\n\tsnapshot: CoordinatorAuthControllerVerifiedSnapshot,\n): string[] {\n\tconst subject = snapshot.legacyHistory;\n\tif (!subject) return [];\n\tconst fingerprints = new Set([\n\t\tsubject.fingerprint,\n\t\t...subject.keys.map((key) => key.fingerprint),\n\t]);\n\tconst identities = history.flatMap((row) =>\n\t\trow.manifest.device_decisions\n\t\t\t.filter(\n\t\t\t\t(decision) =>\n\t\t\t\t\tlegacyDecisionCountsAsOwner(decision) &&\n\t\t\t\t\t(decision.device_id === subject.deviceId || fingerprints.has(decision.key_fingerprint)),\n\t\t\t)\n\t\t\t.flatMap((decision) => (decision.identity_id ? [decision.identity_id] : [])),\n\t);\n\treturn [...new Set(identities)].sort();\n}\n","import type { Context } from \"hono\";\nimport type { CoordinatorAuthBrowserConfig } from \"./coordinator-auth-browser-transaction-contract.js\";\nimport {\n\ttype CoordinatorAuthControllerAttestation,\n\ttype CoordinatorAuthControllerReviewInput,\n\ttype CoordinatorAuthControllerStore,\n\ttype CoordinatorAuthControllerVerifiedSnapshot,\n\tcaptureVerifiedSnapshot,\n\tisAuthControllerId,\n} from \"./coordinator-auth-controller.js\";\nimport {\n\ttype ControllerHistoryEvidence,\n\tcontrollerHistoryDigestEvidence,\n\tparseControllerHistoryRecord,\n} from \"./coordinator-auth-controller-history.js\";\nimport {\n\ttype CoordinatorControllerOwnerAdvisory,\n\ttype ExistingOwnerReviewCapabilities,\n\thistoricalOwnerHints,\n\tprepareExistingOwnerReview,\n} from \"./coordinator-auth-controller-owner-review.js\";\nimport type { CoordinatorAuthLinkConfig } from \"./coordinator-auth-link-contract.js\";\nimport {\n\tassertConfiguredAuthSchema,\n\tauthSchemaUpgradeResponse,\n\tCoordinatorAuthSchemaUpgradeRequiredError,\n} from \"./coordinator-auth-schema.js\";\nimport {\n\ttype CoordinatorOwnerResolutionReviewStore,\n\tOwnerResolutionReviewError,\n} from \"./coordinator-owner-resolution-review.js\";\nimport type {\n\tCoordinatorEnrollment,\n\tCoordinatorInvite,\n\tCoordinatorStore,\n} from \"./coordinator-store-contract.js\";\n\nexport type CoordinatorControllerReviewStore = CoordinatorStore &\n\tPartial<CoordinatorOwnerResolutionReviewStore> &\n\tExistingOwnerReviewCapabilities &\n\tPartial<Pick<CoordinatorAuthControllerStore, \"readAuthControllerAttestationForSnapshot\">> &\n\tPick<\n\t\tCoordinatorAuthControllerStore,\n\t\t\"createAuthControllerAttestation\" | \"captureAuthControllerLegacyHistory\"\n\t>;\nexport interface CoordinatorControllerReviewDeps {\n\tconfig: CoordinatorAuthBrowserConfig;\n\tstoreFactory: () => CoordinatorControllerReviewStore;\n\tadminSecret: () => string | null;\n\treadRequestBytes: (c: Context, maxBytes: number) => Promise<Uint8Array | null>;\n\tparseJsonObject: (raw: Uint8Array) => Record<string, unknown> | null;\n\trateLimitedResponse: (\n\t\tc: Context,\n\t\tkey: string,\n\t\toptions: { authenticated: boolean },\n\t) => Response | null;\n}\ninterface ReviewInput {\n\tpurpose?: \"existing_account_owner\";\n\tresolution_scope?: \"historical_included_owner_labels_only\";\n\tconfirm_owner_resolution_digest?: string;\n\tgroup_id: string;\n\tdevice_id: string;\n\tidentity_id: string;\n\tfingerprint: string;\n\tconfirm_evidence_digest?: string;\n}\nexport type CoordinatorControllerReviewReason =\n\t| \"group_unavailable\"\n\t| \"enrollment_unavailable\"\n\t| \"key_mismatch\"\n\t| \"enrollment_identity_mismatch\"\n\t| \"invite_identity_mismatch\"\n\t| \"invite_evidence_invalid\"\n\t| \"legacy_history_invalid\"\n\t| \"account_owner_target_unavailable\"\n\t| \"account_owner_conflict\";\nexport interface CoordinatorControllerReviewPreview {\n\tpurpose?: \"existing_account_owner\";\n\taccount_owner_target?: CoordinatorControllerOwnerAdvisory;\n\thistorical_owner_hints?: string[];\n\tstate: \"ready\" | \"needs_review\";\n\treasons: CoordinatorControllerReviewReason[];\n\tcoordinator_id: string;\n\tevidence_digest?: string;\n\tenrollment: {\n\t\tdevice_id: string;\n\t\tdisplay_name: string | null;\n\t\tfingerprint: string;\n\t\tidentity_label: \"none\" | \"matches\";\n\t} | null;\n\treviewed_invites: { invite_id: string; kind: \"team_member\" | \"add_device\" }[];\n\treviewed_invite_count: number;\n\t/** Historical sharing assignments, not a change of account owner or Team access. */\n\tlegacy_history: ControllerHistoryEvidence[];\n}\nexport interface CoordinatorControllerRecoveryReceipt {\n\tdisposition: \"created\" | \"reused\";\n\treview_receipt_id: string;\n\t/** Original immutable remote review digest, not the fresh confirmation digest. */\n\tevidence_digest: string;\n}\nconst PATH = \"/v1/admin/auth-controller-reviews\";\nconst FIELDS = [\"group_id\", \"device_id\", \"identity_id\", \"fingerprint\"] as const;\nconst ALLOWED_FIELDS: readonly string[] = [...FIELDS, \"confirm_evidence_digest\", \"purpose\"];\nfunction isHash(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length === 64 && /^[a-f0-9]{64}$/.test(value);\n}\nfunction captureInput(data: Record<string, unknown> | null): ReviewInput | null {\n\tif (data && Object.hasOwn(data, \"resolution_scope\")) return captureResolutionInput(data);\n\tconst copy = captureInputFields(data);\n\tif (!copy || !FIELDS.every((key) => Object.hasOwn(copy, key))) return null;\n\tconst { group_id, device_id, identity_id, fingerprint } = copy;\n\tif (\n\t\t!isAuthControllerId(group_id) ||\n\t\t!isAuthControllerId(device_id) ||\n\t\t!isAuthControllerId(identity_id) ||\n\t\t!isHash(fingerprint)\n\t)\n\t\treturn null;\n\tif (Object.hasOwn(copy, \"confirm_evidence_digest\") && !isHash(copy.confirm_evidence_digest))\n\t\treturn null;\n\tif (Object.hasOwn(copy, \"purpose\") && copy.purpose !== \"existing_account_owner\") return null;\n\tconst input: ReviewInput = { group_id, device_id, identity_id, fingerprint };\n\tif (Object.hasOwn(copy, \"confirm_evidence_digest\"))\n\t\tinput.confirm_evidence_digest = copy.confirm_evidence_digest;\n\tif (copy.purpose === \"existing_account_owner\") input.purpose = copy.purpose;\n\treturn input;\n}\nfunction captureResolutionInput(data: Record<string, unknown>): ReviewInput | null {\n\tconst allowed = [...FIELDS, \"purpose\", \"resolution_scope\", \"confirm_owner_resolution_digest\"];\n\tif (Object.keys(data).some((key) => !allowed.includes(key))) return null;\n\tif (\n\t\tdata.purpose !== \"existing_account_owner\" ||\n\t\tdata.resolution_scope !== \"historical_included_owner_labels_only\"\n\t)\n\t\treturn null;\n\tconst { resolution_scope, confirm_owner_resolution_digest, ...ordinary } = data;\n\tconst input = captureInput(ordinary);\n\tif (!input) return null;\n\tif (Object.hasOwn(data, \"confirm_owner_resolution_digest\")) {\n\t\tif (!isHash(confirm_owner_resolution_digest)) return null;\n\t\tinput.confirm_owner_resolution_digest = confirm_owner_resolution_digest;\n\t}\n\treturn { ...input, resolution_scope };\n}\nfunction captureInputFields(data: Record<string, unknown> | null): Record<string, string> | null {\n\tif (!data || Array.isArray(data)) return null;\n\tconst keys = Reflect.ownKeys(data);\n\tif (keys.some((key) => typeof key !== \"string\" || !ALLOWED_FIELDS.includes(key))) return null;\n\tconst copy: Record<string, string> = {};\n\tfor (const key of keys) {\n\t\tif (typeof key !== \"string\") return null;\n\t\tconst field = Object.getOwnPropertyDescriptor(data, key);\n\t\tif (!field || !Object.hasOwn(field, \"value\") || typeof field.value !== \"string\") return null;\n\t\tcopy[key] = field.value;\n\t}\n\treturn copy;\n}\nasync function digestBytes(value: string): Promise<ArrayBuffer> {\n\treturn globalThis.crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(value));\n}\nasync function hash(value: unknown): Promise<string> {\n\tconst bytes = await digestBytes(JSON.stringify(value));\n\treturn Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\nasync function authenticate(\n\tprovided: string | undefined,\n\tconfigured: string | null,\n): Promise<boolean> {\n\tif (!configured || !provided || provided.length > 8192) return false;\n\t// Native verification compares fixed-length MACs; no JS secret-string comparison.\n\tconst [expected, actual] = await Promise.all([digestBytes(configured), digestBytes(provided)]);\n\tconst key = await globalThis.crypto.subtle.importKey(\n\t\t\"raw\",\n\t\texpected,\n\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n\t\tfalse,\n\t\t[\"sign\", \"verify\"],\n\t);\n\tconst signature = await globalThis.crypto.subtle.sign(\"HMAC\", key, expected);\n\treturn globalThis.crypto.subtle.verify(\"HMAC\", key, signature, actual);\n}\nfunction boundInvites(\n\tinvites: CoordinatorInvite[],\n\tenrollment: CoordinatorEnrollment,\n): CoordinatorInvite[] {\n\treturn invites\n\t\t.filter(\n\t\t\t(invite) =>\n\t\t\t\tinvite.group_id === enrollment.group_id &&\n\t\t\t\tinvite.revoked_at === null &&\n\t\t\t\t!!invite.consumed_at &&\n\t\t\t\t(invite.invite_kind === \"team_member\" || invite.invite_kind === \"add_device\") &&\n\t\t\t\tinvite.bound_device_id === enrollment.device_id &&\n\t\t\t\tinvite.bound_public_key === enrollment.public_key &&\n\t\t\t\tinvite.bound_fingerprint === enrollment.fingerprint,\n\t\t)\n\t\t.map((invite) => ({ ...invite }))\n\t\t.sort((a, b) => (a.invite_id < b.invite_id ? -1 : Number(a.invite_id > b.invite_id)));\n}\nfunction inviteIdentityMatches(invite: CoordinatorInvite, identityId: string): boolean {\n\tconst authoritative =\n\t\tinvite.invite_kind === \"team_member\" ? invite.assigned_identity_id : invite.target_identity_id;\n\treturn authoritative === identityId && invite.recipient_actor_id === identityId;\n}\nfunction enrollmentReasons(\n\tenrollment: CoordinatorEnrollment | null,\n\tinput: ReviewInput,\n): CoordinatorControllerReviewReason[] {\n\tif (enrollment?.enabled !== 1) return [\"enrollment_unavailable\"];\n\tconst reasons: CoordinatorControllerReviewReason[] = [];\n\tif (enrollment.fingerprint !== input.fingerprint) reasons.push(\"key_mismatch\");\n\tif (enrollment.identity_id !== null && enrollment.identity_id !== input.identity_id)\n\t\treasons.push(\"enrollment_identity_mismatch\");\n\treturn reasons;\n}\nasync function preview(\n\tstore: CoordinatorControllerReviewStore,\n\tinput: ReviewInput,\n\tcoordinatorId: string,\n\tconfig: CoordinatorAuthLinkConfig,\n) {\n\tconst groupResult = await store.getGroup(input.group_id);\n\tconst group = groupResult ? { ...groupResult } : null;\n\tconst enrollmentResult = await store.getEnrollment(input.group_id, input.device_id);\n\tconst enrollment = enrollmentResult ? { ...enrollmentResult } : null;\n\tconst reasons = enrollmentReasons(enrollment, input);\n\tif (!group || group.archived_at !== null) reasons.push(\"group_unavailable\");\n\tconst bound = enrollment ? boundInvites(await store.listInvites(input.group_id), enrollment) : [];\n\tif (bound.some((invite) => !inviteIdentityMatches(invite, input.identity_id)))\n\t\treasons.push(\"invite_identity_mismatch\");\n\tif (bound.some((invite) => !isHash(invite.reviewed_preview_digest)))\n\t\treasons.push(\"invite_evidence_invalid\");\n\tconst invites = bound.filter((invite) => isHash(invite.reviewed_preview_digest));\n\tconst verifiedSnapshot = verifiedInviteSnapshot(enrollment, invites);\n\tconst legacyHistory = await addHistorySnapshot({\n\t\tstore,\n\t\tenrollment,\n\t\tcoordinatorId,\n\t\tverifiedSnapshot,\n\t\treasons,\n\t});\n\tconst ownerTarget = await addOwnerSnapshot({\n\t\tstore,\n\t\tinput,\n\t\tenrollment,\n\t\tconfig,\n\t\tsnapshot: verifiedSnapshot,\n\t\treasons,\n\t});\n\taddSnapshotReasons(verifiedSnapshot, reasons);\n\tconst result = previewResult({\n\t\tinput,\n\t\tcoordinatorId,\n\t\tenrollment,\n\t\tinvites,\n\t\treasons,\n\t\tlegacyHistory,\n\t\tverifiedSnapshot,\n\t\townerTarget,\n\t});\n\tif (result.state === \"ready\" && enrollment)\n\t\tresult.evidence_digest = await hash([\n\t\t\t\"codemem-controller-review-v2\",\n\t\t\tcoordinatorId,\n\t\t\tinput.group_id,\n\t\t\tenrollment.device_id,\n\t\t\tenrollment.public_key,\n\t\t\tenrollment.fingerprint,\n\t\t\tinput.identity_id,\n\t\t\t{\n\t\t\t\t...verifiedSnapshot,\n\t\t\t\tlegacyHistory: controllerHistoryDigestEvidence(verifiedSnapshot.legacyHistory),\n\t\t\t},\n\t\t]);\n\treturn { result, enrollment, verifiedSnapshot };\n}\n\nasync function addOwnerSnapshot(options: {\n\tstore: CoordinatorControllerReviewStore;\n\tinput: ReviewInput;\n\tenrollment: CoordinatorEnrollment | null;\n\tconfig: CoordinatorAuthLinkConfig;\n\tsnapshot: CoordinatorAuthControllerVerifiedSnapshot;\n\treasons: CoordinatorControllerReviewReason[];\n}): Promise<CoordinatorControllerOwnerAdvisory | undefined> {\n\tif (!options.input.purpose) return undefined;\n\tconst owner = await prepareExistingOwnerReview({\n\t\t...options,\n\t\tidentityId: options.input.identity_id,\n\t});\n\tif (owner.reason) options.reasons.push(owner.reason);\n\treturn owner.target;\n}\n\nfunction previewResult(options: {\n\tinput: ReviewInput;\n\tcoordinatorId: string;\n\tenrollment: CoordinatorEnrollment | null;\n\tinvites: CoordinatorInvite[];\n\treasons: CoordinatorControllerReviewReason[];\n\tlegacyHistory: ControllerHistoryEvidence[];\n\tverifiedSnapshot: CoordinatorAuthControllerVerifiedSnapshot;\n\townerTarget: CoordinatorControllerOwnerAdvisory | undefined;\n}): CoordinatorControllerReviewPreview {\n\tconst {\n\t\tinput,\n\t\tcoordinatorId,\n\t\tenrollment,\n\t\tinvites,\n\t\treasons,\n\t\tlegacyHistory,\n\t\tverifiedSnapshot,\n\t\townerTarget,\n\t} = options;\n\tconst result: CoordinatorControllerReviewPreview = {\n\t\tstate: reasons.length ? \"needs_review\" : \"ready\",\n\t\treasons,\n\t\tcoordinator_id: coordinatorId,\n\t\tlegacy_history: legacyHistory,\n\t\tenrollment: null,\n\t\treviewed_invite_count: invites.length,\n\t\t// Invite references remain short; retained manifests are presented in full separately.\n\t\treviewed_invites: invites.slice(0, 10).map((invite) => ({\n\t\t\tinvite_id: invite.invite_id,\n\t\t\tkind: invite.invite_kind as \"team_member\" | \"add_device\",\n\t\t})),\n\t};\n\tif (input.purpose) {\n\t\tresult.purpose = input.purpose;\n\t\tresult.account_owner_target = ownerTarget;\n\t\tresult.historical_owner_hints = historicalOwnerHints(legacyHistory, verifiedSnapshot);\n\t}\n\tif (enrollment && !reasons.includes(\"enrollment_identity_mismatch\"))\n\t\tresult.enrollment = {\n\t\t\tdevice_id: enrollment.device_id,\n\t\t\tdisplay_name: enrollment.display_name?.slice(0, 256) ?? null,\n\t\t\tfingerprint: enrollment.fingerprint,\n\t\t\tidentity_label: enrollment.identity_id === null ? \"none\" : \"matches\",\n\t\t};\n\treturn result;\n}\nasync function addHistorySnapshot(options: {\n\tstore: CoordinatorControllerReviewStore;\n\tenrollment: CoordinatorEnrollment | null;\n\tcoordinatorId: string;\n\tverifiedSnapshot: CoordinatorAuthControllerVerifiedSnapshot;\n\treasons: CoordinatorControllerReviewReason[];\n}): Promise<ControllerHistoryEvidence[]> {\n\tconst { store, enrollment, coordinatorId, verifiedSnapshot, reasons } = options;\n\tif (!enrollment) return [];\n\ttry {\n\t\tverifiedSnapshot.legacyHistory = await store.captureAuthControllerLegacyHistory({\n\t\t\tcoordinatorId,\n\t\t\tdeviceId: enrollment.device_id,\n\t\t\tpublicKey: enrollment.public_key,\n\t\t\tfingerprint: enrollment.fingerprint,\n\t\t});\n\t\treturn verifiedSnapshot.legacyHistory.records.map((row) =>\n\t\t\tparseControllerHistoryRecord(row, coordinatorId),\n\t\t);\n\t} catch {\n\t\treasons.push(\"legacy_history_invalid\");\n\t\treturn [];\n\t}\n}\nfunction addSnapshotReasons(\n\tsnapshot: CoordinatorAuthControllerVerifiedSnapshot,\n\treasons: CoordinatorControllerReviewReason[],\n): void {\n\tif (!captureVerifiedSnapshot(snapshot)) reasons.push(\"invite_evidence_invalid\");\n}\nfunction verifiedInviteSnapshot(\n\tenrollment: CoordinatorEnrollment | null,\n\tinvites: CoordinatorInvite[],\n): CoordinatorAuthControllerVerifiedSnapshot {\n\treturn {\n\t\tenrollmentIdentityId: enrollment?.identity_id ?? null,\n\t\tinvites: invites.map((invite) => ({\n\t\t\tinviteId: invite.invite_id,\n\t\t\tkind: invite.invite_kind as \"team_member\" | \"add_device\",\n\t\t\tactorId: invite.recipient_actor_id as string,\n\t\t\tassignedIdentityId: invite.assigned_identity_id ?? null,\n\t\t\ttargetIdentityId: invite.target_identity_id ?? null,\n\t\t\tdigest: invite.reviewed_preview_digest as string,\n\t\t})),\n\t};\n}\nasync function applyReview(\n\tc: Context,\n\tstore: CoordinatorControllerReviewStore,\n\tinput: ReviewInput,\n\tcoordinatorId: string,\n\tconfig: CoordinatorAuthLinkConfig,\n): Promise<Response> {\n\tconst { result, enrollment, verifiedSnapshot } = await preview(\n\t\tstore,\n\t\tinput,\n\t\tcoordinatorId,\n\t\tconfig,\n\t);\n\tif (input.confirm_evidence_digest === undefined) return c.json(result);\n\tif (result.state !== \"ready\" || !enrollment || !result.evidence_digest)\n\t\treturn c.json({ error: \"needs_review\", ...result }, 409);\n\tif (input.confirm_evidence_digest !== result.evidence_digest)\n\t\treturn c.json({ error: \"review_stale\" }, 409);\n\tconst attestationId = `controller-v1:${await hash([coordinatorId, input.group_id, input.device_id, input.fingerprint])}`;\n\tconst reviewReceiptId = `review-v1:${await hash([attestationId, input.identity_id, result.evidence_digest])}`;\n\tconst review = {\n\t\tattestationId,\n\t\tcoordinatorId,\n\t\tidentityId: input.identity_id,\n\t\tgroupId: input.group_id,\n\t\tdeviceId: input.device_id,\n\t\tpublicKey: enrollment.public_key,\n\t\tfingerprint: enrollment.fingerprint,\n\t\treviewReceiptId,\n\t\tevidenceDigest: result.evidence_digest,\n\t\tverifiedSnapshot,\n\t};\n\tconst activeReview = result.account_owner_target?.active_review;\n\tif (input.purpose && activeReview) {\n\t\treturn restoreReview(c, store, review, activeReview);\n\t}\n\tconst created = await store.createAuthControllerAttestation(review);\n\tif (created.kind === \"rejected\") {\n\t\tif (created.error === \"enrollment_mismatch\" || created.error === \"review_stale\")\n\t\t\treturn c.json({ error: \"review_stale\" }, 409);\n\t\tif (created.error === \"attestation_conflict\" || created.error === \"attestation_revoked\")\n\t\t\treturn c.json({ error: \"already_reviewed_or_needs_review\" }, 409);\n\t\treturn c.json({ error: \"review_unavailable\" }, 403);\n\t}\n\treturn appliedReviewResponse(c, created.attestation, created.kind, input.purpose);\n}\n\nasync function restoreReview(\n\tc: Context,\n\tstore: CoordinatorControllerReviewStore,\n\treview: CoordinatorAuthControllerReviewInput,\n\tactive: NonNullable<CoordinatorControllerOwnerAdvisory[\"active_review\"]>,\n): Promise<Response> {\n\tconst row = await store.readAuthControllerAttestationForSnapshot?.({\n\t\t...review,\n\t\tattestationId: active.attestation_id,\n\t});\n\tif (\n\t\t!row ||\n\t\trow.identity_id !== review.identityId ||\n\t\trow.review_receipt_id !== active.review_receipt_id ||\n\t\trow.evidence_digest !== active.evidence_digest\n\t)\n\t\treturn c.json({ error: \"review_stale\" }, 409);\n\treturn appliedReviewResponse(c, row, \"existing\", \"existing_account_owner\");\n}\n\nfunction appliedReviewResponse(\n\tc: Context,\n\trow: CoordinatorAuthControllerAttestation,\n\tstate: \"created\" | \"existing\",\n\tpurpose: ReviewInput[\"purpose\"],\n): Response {\n\tconst result = {\n\t\tstate,\n\t\tattestation_id: row.attestation_id,\n\t\tcoordinator_id: row.coordinator_id,\n\t\tgroup_id: row.group_id,\n\t\tdevice_id: row.device_id,\n\t\tfingerprint: row.fingerprint,\n\t\tidentity_id: row.identity_id,\n\t\tcreated_at: row.created_at,\n\t};\n\tif (!purpose) return c.json(result, state === \"created\" ? 201 : 200);\n\treturn c.json(\n\t\t{\n\t\t\t...result,\n\t\t\tpurpose,\n\t\t\trecovery_receipt: {\n\t\t\t\tdisposition: state === \"created\" ? \"created\" : \"reused\",\n\t\t\t\treview_receipt_id: row.review_receipt_id,\n\t\t\t\tevidence_digest: row.evidence_digest,\n\t\t\t},\n\t\t},\n\t\tstate === \"created\" ? 201 : 200,\n\t);\n}\nasync function handleReview(c: Context, deps: CoordinatorControllerReviewDeps): Promise<Response> {\n\tc.header(\"Cache-Control\", \"no-store\");\n\tc.header(\"Referrer-Policy\", \"no-referrer\");\n\tc.header(\"X-Content-Type-Options\", \"nosniff\");\n\tlet store: CoordinatorControllerReviewStore | undefined;\n\ttry {\n\t\ttry {\n\t\t\tconst provided = c.req.header(\"X-Codemem-Coordinator-Admin\");\n\t\t\tconst configured = deps.adminSecret();\n\t\t\tif (!(await authenticate(provided, configured))) {\n\t\t\t\treturn (\n\t\t\t\t\tdeps.rateLimitedResponse(c, \"controller-review:anonymous\", { authenticated: false }) ??\n\t\t\t\t\tc.json({ error: \"unauthorized\" }, 401)\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst limited = deps.rateLimitedResponse(c, \"controller-review:admin\", {\n\t\t\t\tauthenticated: true,\n\t\t\t});\n\t\t\tif (limited) return limited;\n\t\t\tconst raw = await deps.readRequestBytes(c, 4096);\n\t\t\tif (!raw) return c.json({ error: \"body_too_large\" }, 413);\n\t\t\tconst input = captureInput(deps.parseJsonObject(raw));\n\t\t\tif (!input) return c.json({ error: \"review_invalid_input\" }, 400);\n\t\t\tstore = deps.storeFactory();\n\t\t\tawait assertConfiguredAuthSchema(store);\n\t\t\tif (input.resolution_scope) return await applyResolutionReview(c, store, input, deps.config);\n\t\t\treturn await applyReview(c, store, input, deps.config.coordinatorId, deps.config);\n\t\t} finally {\n\t\t\tawait store?.close();\n\t\t}\n\t} catch (error) {\n\t\tif (error instanceof OwnerResolutionReviewError) {\n\t\t\tif (error.code === \"review_stale\") return c.json({ error: error.code }, 409);\n\t\t\treturn c.json({ error: error.code, action: \"Preview status before confirming again\" }, 503);\n\t\t}\n\t\tif (error instanceof CoordinatorAuthSchemaUpgradeRequiredError)\n\t\t\treturn authSchemaUpgradeResponse();\n\t\treturn c.json({ error: \"review_unavailable\" }, 503);\n\t}\n}\nasync function applyResolutionReview(\n\tc: Context,\n\tstore: CoordinatorControllerReviewStore,\n\tinput: ReviewInput,\n\tconfig: CoordinatorAuthLinkConfig,\n): Promise<Response> {\n\tif (\n\t\ttypeof store.previewOwnerResolutionReview !== \"function\" ||\n\t\ttypeof store.confirmOwnerResolutionReview !== \"function\"\n\t)\n\t\treturn c.json(\n\t\t\t{ error: \"owner_resolution_review_unsupported\", action: \"Upgrade the coordinator\" },\n\t\t\t503,\n\t\t);\n\tconst selection = {\n\t\tgroupId: input.group_id,\n\t\tdeviceId: input.device_id,\n\t\tidentityId: input.identity_id,\n\t\tfingerprint: input.fingerprint,\n\t};\n\tif (input.confirm_owner_resolution_digest === undefined)\n\t\treturn c.json(await store.previewOwnerResolutionReview(selection, config));\n\tconst result = await confirmResolutionReview(\n\t\t{ confirmOwnerResolutionReview: store.confirmOwnerResolutionReview.bind(store) },\n\t\t{\n\t\t\t...selection,\n\t\t\tconfirmOwnerResolutionDigest: input.confirm_owner_resolution_digest,\n\t\t},\n\t\tconfig,\n\t);\n\tconst created =\n\t\tresult.recovery_receipt?.disposition === \"created\" ||\n\t\tresult.owner_resolution?.disposition === \"created\";\n\treturn c.json(result, created ? 201 : 200);\n}\nasync function confirmResolutionReview(\n\tstore: Pick<CoordinatorOwnerResolutionReviewStore, \"confirmOwnerResolutionReview\">,\n\tselection: Parameters<CoordinatorOwnerResolutionReviewStore[\"confirmOwnerResolutionReview\"]>[0],\n\tconfig: CoordinatorAuthLinkConfig,\n) {\n\ttry {\n\t\treturn await store.confirmOwnerResolutionReview(selection, config);\n\t} catch (error) {\n\t\tif (\n\t\t\terror instanceof OwnerResolutionReviewError ||\n\t\t\terror instanceof CoordinatorAuthSchemaUpgradeRequiredError\n\t\t)\n\t\t\tthrow error;\n\t\tthrow new OwnerResolutionReviewError(\"owner_resolution_outcome_unknown\");\n\t}\n}\n/** Existing configured admin authority only; local evidence is not an authentication proof. */\nexport function registerCoordinatorAuthControllerReviewRoutes(\n\tapp: { post(path: string, handler: (c: Context) => Promise<Response>): unknown },\n\tdeps: CoordinatorControllerReviewDeps,\n): void {\n\tif (!deps.config.enabled) return;\n\tconst { enabled, coordinatorId, issuer, revision, redirectUri } = deps.config;\n\tconst captured = {\n\t\t...deps,\n\t\tconfig: Object.freeze({ enabled, coordinatorId, issuer, revision, redirectUri }),\n\t};\n\tapp.post(PATH, (c) => handleReview(c, captured));\n}\n","/** Separate proof domain from initial account linking. Safe for runtime clients. */\nexport const AUTH_ACCOUNT_CHANGE_PURPOSE = \"coordinator-account-change-v1\";\nexport type CoordinatorAccountChangeIntent = \"refresh\" | \"disconnect\";\n","import type { Context, Hono } from \"hono\";\nimport type { AccountChangeOperations } from \"./coordinator-account-change.js\";\nimport { AUTH_ACCOUNT_CHANGE_PURPOSE } from \"./coordinator-account-change-contract.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { CoordinatorAuthLinkSigner } from \"./coordinator-auth-link-contract.js\";\nimport { parseCoordinatorAuthLoopback } from \"./coordinator-auth-loopback.js\";\nimport {\n\tdecodeCoordinatorAuthProof32,\n\thashCoordinatorAuthProofBytes32,\n} from \"./coordinator-auth-proof.js\";\nimport type { registerCoordinatorDeviceAuthLinkRoutes } from \"./coordinator-device-auth-link.js\";\n\ntype LinkDeps = Parameters<typeof registerCoordinatorDeviceAuthLinkRoutes>[1];\ntype ChangeOperations = Pick<\n\tAccountChangeOperations,\n\t\"create\" | \"readStatus\" | \"finalize\" | \"cancel\" | \"readCapabilities\" | \"unlink\"\n>;\nexport interface CoordinatorDeviceAccountChangeOptions {\n\tconfig: LinkDeps[\"config\"];\n\tstoreFactory: LinkDeps[\"storeFactory\"];\n\t/** Must check the account-change schema, not only the older link schema. */\n\tassertReady: (store: ReturnType<LinkDeps[\"storeFactory\"]>) => Promise<void>;\n\toperationsFactory: (\n\t\tstore: ReturnType<LinkDeps[\"storeFactory\"]>,\n\t) => ChangeOperations | null | Promise<ChangeOperations | null>;\n}\ntype Deps = Omit<LinkDeps, \"config\" | \"storeFactory\"> & CoordinatorDeviceAccountChangeOptions;\ntype Action = \"create\" | \"status\" | \"finalize\" | \"cancel\" | \"capabilities\" | \"unlink\";\nconst pins = [\"group_id\", \"identity_id\", \"runtime_verifier_hash\"] as const;\nconst fields = {\n\tunlink: [\"group_id\", \"identity_id\", \"attempt_id\", \"target_link_id\"],\n\tcapabilities: [\"group_id\", \"identity_id\"],\n\tcreate: [...pins, \"intent\", \"attempt_id\", \"browser_start_hash\", \"loopback_redirect\"],\n\tstatus: pins,\n\tcancel: pins,\n\tfinalize: [\n\t\t\"purpose\",\n\t\t\"coordinator_id\",\n\t\t\"attempt_id\",\n\t\t\"group_id\",\n\t\t\"identity_id\",\n\t\t\"device_id\",\n\t\t\"fingerprint\",\n\t\t\"runtime_verifier\",\n\t\t\"completion\",\n\t],\n} as const;\ntype Input = Record<(typeof fields)[Action][number], string>;\nconst isHash = (value: string) => /^[a-f0-9]{64}$/.test(value);\nfunction exactInput(value: Record<string, unknown> | null, action: Action): value is Input {\n\treturn (\n\t\tvalue !== null &&\n\t\tObject.keys(value).length === fields[action].length &&\n\t\tfields[action].every((key) => Object.hasOwn(value, key) && typeof value[key] === \"string\")\n\t);\n}\nfunction unavailable(c: Context): Response {\n\treturn c.json({ error: \"authentication_unavailable\" }, 503);\n}\nfunction denied(c: Context): Response {\n\treturn c.json({ error: \"account_change_unavailable\" }, 403);\n}\nfunction invalid(c: Context): Response {\n\treturn c.json({ error: \"account_change_invalid_input\" }, 400);\n}\n\nasync function readInput(c: Context, action: Action, deps: Deps) {\n\tconst url = new URL(c.req.url);\n\tif (url.origin !== new URL(deps.config.redirectUri).origin) return denied(c);\n\tif (action === \"status\" || action === \"capabilities\") {\n\t\tconst entries = [...url.searchParams.entries()];\n\t\tif (c.req.raw.body !== null || entries.length !== fields[action].length) return invalid(c);\n\t\tconst data = Object.fromEntries(entries);\n\t\tif (!exactInput(data, action)) return invalid(c);\n\t\treturn { data, raw: new Uint8Array() };\n\t}\n\tif (url.search) return invalid(c);\n\tconst raw = await deps.readRequestBytes(c, 4096);\n\tif (!raw) return c.json({ error: \"body_too_large\" }, 413);\n\tconst data = deps.parseJsonObject(raw);\n\tif (!exactInput(data, action)) return invalid(c);\n\treturn { data, raw };\n}\nfunction validPins(data: Input, attemptId: string): boolean {\n\treturn (\n\t\tisAuthControllerId(attemptId) &&\n\t\tisAuthControllerId(data.group_id) &&\n\t\tisAuthControllerId(data.identity_id)\n\t);\n}\nfunction validInput(data: Input, action: Action, attemptId: string, deps: Deps): boolean {\n\tif (action === \"capabilities\")\n\t\treturn isAuthControllerId(data.group_id) && isAuthControllerId(data.identity_id);\n\tif (!validPins(data, attemptId)) return false;\n\tif (action === \"unlink\") return isAuthControllerId(data.target_link_id);\n\tif (action === \"finalize\") {\n\t\treturn (\n\t\t\tdata.purpose === AUTH_ACCOUNT_CHANGE_PURPOSE &&\n\t\t\tdata.coordinator_id === deps.config.coordinatorId &&\n\t\t\tdata.attempt_id === attemptId &&\n\t\t\tisAuthControllerId(data.device_id) &&\n\t\t\tisHash(data.fingerprint) &&\n\t\t\tdecodeCoordinatorAuthProof32(data.runtime_verifier) !== null &&\n\t\t\tdecodeCoordinatorAuthProof32(data.completion) !== null\n\t\t);\n\t}\n\tif (!isHash(data.runtime_verifier_hash)) return false;\n\tif (action !== \"create\") return true;\n\treturn (\n\t\t(data.intent === \"refresh\" || data.intent === \"disconnect\") &&\n\t\tisHash(data.browser_start_hash) &&\n\t\tparseCoordinatorAuthLoopback(data.loopback_redirect).ok\n\t);\n}\nasync function finalizeProof(\n\tc: Context,\n\tdata: Input,\n\tinput: {\n\t\tattemptId: string;\n\t\tsigner: CoordinatorAuthLinkSigner;\n\t\texpectedIdentityId: string;\n\t\truntimeVerifierHash: string;\n\t},\n\toperations: ChangeOperations,\n\tdeps: Deps,\n): Promise<string | Response> {\n\tif (data.device_id !== input.signer.deviceId || data.fingerprint !== input.signer.fingerprint)\n\t\treturn denied(c);\n\tconst verifier = decodeCoordinatorAuthProof32(data.runtime_verifier);\n\tconst completion = decodeCoordinatorAuthProof32(data.completion);\n\tif (!verifier || !completion) return invalid(c);\n\tconst runtimeVerifierHash = await hashCoordinatorAuthProofBytes32(verifier);\n\tconst result = await operations.finalize(\n\t\t{\n\t\t\t...input,\n\t\t\truntimeVerifierHash,\n\t\t\tcompletionSecretHash: await hashCoordinatorAuthProofBytes32(completion),\n\t\t},\n\t\tdeps.config,\n\t);\n\treturn result ? runtimeVerifierHash : denied(c);\n}\nasync function applyAction(\n\tc: Context,\n\taction: Action,\n\tdata: Input,\n\tattemptId: string,\n\tsigner: CoordinatorAuthLinkSigner,\n\toperations: ChangeOperations,\n\tdeps: Deps,\n): Promise<Response> {\n\tif (action === \"unlink\") return applyUnlink(c, data, attemptId, signer, operations, deps);\n\tif (action === \"capabilities\") {\n\t\tconst { unlinkTarget, ...actions } = await operations.readCapabilities(\n\t\t\t{ signer, expectedIdentityId: data.identity_id },\n\t\t\tdeps.config,\n\t\t);\n\t\treturn c.json({\n\t\t\tcoordinator_id: deps.config.coordinatorId,\n\t\t\tidentity_id: data.identity_id,\n\t\t\tactions,\n\t\t\t...(unlinkTarget ? { unlink_target: unlinkTarget } : {}),\n\t\t});\n\t}\n\treturn applyBrowserAction(c, action, data, attemptId, signer, operations, deps);\n}\nasync function applyUnlink(\n\tc: Context,\n\tdata: Input,\n\tattemptId: string,\n\tsigner: CoordinatorAuthLinkSigner,\n\toperations: ChangeOperations,\n\tdeps: Deps,\n): Promise<Response> {\n\tconst digest = await crypto.subtle.digest(\n\t\t\"SHA-256\",\n\t\tnew TextEncoder().encode(JSON.stringify(fields.unlink.map((key) => data[key]))),\n\t);\n\tconst requestHash = Array.from(new Uint8Array(digest), (byte) =>\n\t\tbyte.toString(16).padStart(2, \"0\"),\n\t).join(\"\");\n\tconst result = await operations.unlink(\n\t\t{\n\t\t\tattemptId,\n\t\t\tsigner,\n\t\t\texpectedIdentityId: data.identity_id,\n\t\t\texpectedLinkId: data.target_link_id,\n\t\t\trequestHash,\n\t\t},\n\t\tdeps.config,\n\t);\n\treturn result\n\t\t? c.json({\n\t\t\t\tstate: \"completed\",\n\t\t\t\tattemptId,\n\t\t\t\tidentityId: data.identity_id,\n\t\t\t\tcoordinatorId: deps.config.coordinatorId,\n\t\t\t\ttargetLinkId: result.targetLinkId,\n\t\t\t})\n\t\t: denied(c);\n}\nasync function applyBrowserAction(\n\tc: Context,\n\taction: Action,\n\tdata: Input,\n\tattemptId: string,\n\tsigner: CoordinatorAuthLinkSigner,\n\toperations: ChangeOperations,\n\tdeps: Deps,\n): Promise<Response> {\n\tconst input = {\n\t\tattemptId,\n\t\tsigner,\n\t\texpectedIdentityId: data.identity_id,\n\t\truntimeVerifierHash: data.runtime_verifier_hash,\n\t};\n\tif (action === \"finalize\") {\n\t\tconst proof = await finalizeProof(c, data, input, operations, deps);\n\t\tif (proof instanceof Response) return proof;\n\t\tinput.runtimeVerifierHash = proof;\n\t}\n\tif (action === \"create\") {\n\t\tconst created = await operations.create(\n\t\t\t{\n\t\t\t\t...input,\n\t\t\t\tintent: data.intent,\n\t\t\t\tbrowserStartHash: data.browser_start_hash,\n\t\t\t\tloopbackRedirect: data.loopback_redirect,\n\t\t\t},\n\t\t\tdeps.config,\n\t\t);\n\t\tif (!created) return denied(c);\n\t}\n\tif (action === \"cancel\" && !(await operations.cancel(input, deps.config))) return denied(c);\n\tconst status = await operations.readStatus(input, deps.config);\n\tif (!status) return denied(c);\n\t// Explicit allowlist: private browser state and provider data never cross HTTP.\n\tconst publicStatus = {\n\t\tattemptId: status.attemptId,\n\t\tintent: status.intent,\n\t\tstate: status.state,\n\t\texpiresAtMs: status.expiresAtMs,\n\t\tidentityId: status.identityId,\n\t};\n\tif (action === \"finalize\" && status.state !== \"completed\") return unavailable(c);\n\tif (action === \"create\")\n\t\treturn c.json({\n\t\t\tcoordinator_id: deps.config.coordinatorId,\n\t\t\tidentity_id: status.identityId,\n\t\t\tstatus: publicStatus,\n\t\t});\n\treturn c.json({ status: publicStatus });\n}\nasync function handle(c: Context, action: Action, deps: Deps): Promise<Response> {\n\tc.header(\"Cache-Control\", \"no-store\");\n\tc.header(\"Referrer-Policy\", \"no-referrer\");\n\tlet store: ReturnType<Deps[\"storeFactory\"]> | undefined;\n\ttry {\n\t\ttry {\n\t\t\tconst input = await readInput(c, action, deps);\n\t\t\tif (input instanceof Response) return input;\n\t\t\tconst attemptId = [\"create\", \"unlink\"].includes(action)\n\t\t\t\t? input.data.attempt_id\n\t\t\t\t: (c.req.param(\"attemptId\") ?? \"\");\n\t\t\tif (!validInput(input.data, action, attemptId, deps)) return invalid(c);\n\t\t\tstore = deps.storeFactory();\n\t\t\tconst auth = await deps.authorizeRequest(store, {\n\t\t\t\tmethod: c.req.method,\n\t\t\t\turl: c.req.url,\n\t\t\t\tgroupId: input.data.group_id,\n\t\t\t\tbody: input.raw,\n\t\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t\t});\n\t\t\tif (!auth.ok || !auth.enrollment)\n\t\t\t\treturn (\n\t\t\t\t\tdeps.rateLimitedResponse(c, `account-change:${action}`, { authenticated: false }) ??\n\t\t\t\t\tc.json({ error: \"account_change_unavailable\" }, deps.authErrorStatus(auth.error))\n\t\t\t\t);\n\t\t\tconst enrollment = auth.enrollment;\n\t\t\tconst limited = deps.rateLimitedResponse(\n\t\t\t\tc,\n\t\t\t\t`${deps.config.coordinatorId}:${enrollment.device_id}`,\n\t\t\t\t{ authenticated: true },\n\t\t\t);\n\t\t\tif (limited) return limited;\n\t\t\tawait deps.assertReady(store);\n\t\t\tconst operations = await deps.operationsFactory(store);\n\t\t\tif (!operations) return c.json({ error: \"not_found\" }, 404);\n\t\t\treturn await applyAction(\n\t\t\t\tc,\n\t\t\t\taction,\n\t\t\t\tinput.data,\n\t\t\t\tattemptId,\n\t\t\t\t{\n\t\t\t\t\tgroupId: enrollment.group_id,\n\t\t\t\t\tdeviceId: enrollment.device_id,\n\t\t\t\t\tpublicKey: enrollment.public_key,\n\t\t\t\t\tfingerprint: enrollment.fingerprint,\n\t\t\t\t},\n\t\t\t\toperations,\n\t\t\t\tdeps,\n\t\t\t);\n\t\t} finally {\n\t\t\tawait store?.close();\n\t\t}\n\t} catch {\n\t\treturn unavailable(c);\n\t}\n}\n\n/** Explicit capability only; signed admission precedes account-change schema checks. */\nexport function registerCoordinatorDeviceAccountChangeRoutes(app: Hono, deps: Deps): void {\n\tif (!deps.config.enabled) return;\n\tconst { coordinatorId, issuer, revision, enabled, redirectUri } = deps.config;\n\tconst captured = {\n\t\t...deps,\n\t\tconfig: Object.freeze({ coordinatorId, issuer, revision, enabled, redirectUri }),\n\t};\n\tapp.post(\"/v1/auth/account-changes\", (c) => handle(c, \"create\", captured));\n\tapp.post(\"/v1/auth/account-unlinks\", (c) => handle(c, \"unlink\", captured));\n\tapp.get(\"/v1/auth/account-changes\", (c) => handle(c, \"capabilities\", captured));\n\tapp.get(\"/v1/auth/account-changes/:attemptId\", (c) => handle(c, \"status\", captured));\n\tapp.post(\"/v1/auth/account-changes/:attemptId/finalize\", (c) => handle(c, \"finalize\", captured));\n\tapp.post(\"/v1/auth/account-changes/:attemptId/cancel\", (c) => handle(c, \"cancel\", captured));\n}\n","import type { Context } from \"hono\";\nimport type { CoordinatorAccountLinkStatusStore } from \"./coordinator-account-link-status.js\";\nimport type {\n\tCoordinatorAuthBrowserConfig,\n\tCoordinatorAuthBrowserTransactionStore,\n} from \"./coordinator-auth-browser-transaction-contract.js\";\nimport type { CoordinatorAuthControllerStore } from \"./coordinator-auth-controller.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { AuthLinkBackend } from \"./coordinator-auth-link.js\";\nimport {\n\tAUTH_LINK_PURPOSE,\n\ttype CoordinatorAuthLinkRejected,\n\ttype CoordinatorAuthLinkSigner,\n\ttype CoordinatorAuthLinkStore,\n} from \"./coordinator-auth-link-contract.js\";\nimport { parseCoordinatorAuthLoopback } from \"./coordinator-auth-loopback.js\";\nimport {\n\tdecodeCoordinatorAuthProof32,\n\thashCoordinatorAuthProofBytes32,\n} from \"./coordinator-auth-proof.js\";\nimport {\n\tassertConfiguredAuthSchema,\n\tauthSchemaUpgradeResponse,\n\tCoordinatorAuthSchemaUpgradeRequiredError,\n} from \"./coordinator-auth-schema.js\";\nimport {\n\tcaptureResolvedAccountOwnerReceiptReference,\n\ttype ResolvedAccountOwnerStatusOperations,\n} from \"./coordinator-resolved-account-owner-status.js\";\nimport type { CoordinatorEnrollment, CoordinatorStore } from \"./coordinator-store-contract.js\";\n\nexport type CoordinatorDeviceAuthLinkStore = CoordinatorStore &\n\tPartial<CoordinatorAccountLinkStatusStore> &\n\tPartial<Pick<ResolvedAccountOwnerStatusOperations, \"readResolvedAccountOwnerStatus\">> &\n\tPick<\n\t\tCoordinatorAuthControllerStore,\n\t\t\"createAuthControllerAttestation\" | \"captureAuthControllerLegacyHistory\"\n\t> &\n\tPick<\n\t\tCoordinatorAuthLinkStore,\n\t\t| \"createAuthLinkAttempt\"\n\t\t| \"getAuthLinkAttemptStatus\"\n\t\t| \"finalizeAuthLinkAttempt\"\n\t\t| \"failAuthLinkAttempt\"\n\t> &\n\tPick<CoordinatorAuthBrowserTransactionStore, \"retireAuthBrowserTransactions\"> & {\n\t\t/** Rebind storage (ADR 0005 Section 8), or null before its tables exist. */\n\t\treadDeviceRebindBackend?(): Promise<AuthLinkBackend | null>;\n\t};\n\nexport interface CoordinatorDeviceAuthLinkOptions {\n\tconfig: CoordinatorAuthBrowserConfig;\n\tstoreFactory: () => CoordinatorDeviceAuthLinkStore;\n}\n\ninterface SignedRequest {\n\tmethod: string;\n\turl: string;\n\tgroupId: string;\n\tbody: Uint8Array;\n\tdeviceId: string | null;\n\tsignature: string | null;\n\ttimestamp: string | null;\n\tnonce: string | null;\n}\ninterface DeviceAuthLinkDeps extends CoordinatorDeviceAuthLinkOptions {\n\tauthorizeRequest: (\n\t\tstore: CoordinatorDeviceAuthLinkStore,\n\t\trequest: SignedRequest,\n\t) => Promise<{ ok: boolean; error: string; enrollment: CoordinatorEnrollment | null }>;\n\tauthErrorStatus: (error: string) => 401 | 403 | 409;\n\treadRequestBytes: (c: Context, maxBytes: number) => Promise<Uint8Array | null>;\n\tparseJsonObject: (raw: Uint8Array) => Record<string, unknown> | null;\n\trateLimitedResponse: (\n\t\tc: Context,\n\t\tkey: string,\n\t\toptions: { authenticated: boolean },\n\t) => Response | null;\n}\ninterface DeviceAuthLinkApp {\n\tget(path: string, handler: (c: Context) => Promise<Response>): unknown;\n\tpost(path: string, handler: (c: Context) => Promise<Response>): unknown;\n}\ntype Action =\n\t| \"create\"\n\t| \"status\"\n\t| \"finalize\"\n\t| \"cancel\"\n\t| \"account_status\"\n\t| \"resolved_owner_status\"\n\t| \"resolved_owner_receipt_status\";\nconst RECEIPT_QUERY_FIELDS = [\n\t\"attestation_id\",\n\t\"review_receipt_id\",\n\t\"review_evidence_digest\",\n\t\"resolution_id\",\n\t\"resolution_evidence_digest\",\n] as const;\n\nfunction receiptFromData(data: Record<string, unknown>) {\n\treturn captureResolvedAccountOwnerReceiptReference({\n\t\tattestationId: data.attestation_id,\n\t\treviewReceiptId: data.review_receipt_id,\n\t\treviewEvidenceDigest: data.review_evidence_digest,\n\t\tresolutionId: data.resolution_id,\n\t\tresolutionEvidenceDigest: data.resolution_evidence_digest,\n\t});\n}\nconst FIELDS = {\n\tcreate: [\n\t\t\"group_id\",\n\t\t\"identity_id\",\n\t\t\"authority\",\n\t\t\"attempt_id\",\n\t\t\"runtime_verifier_hash\",\n\t\t\"browser_start_hash\",\n\t\t\"loopback_redirect\",\n\t],\n\tfinalize: [\n\t\t\"purpose\",\n\t\t\"coordinator_id\",\n\t\t\"attempt_id\",\n\t\t\"group_id\",\n\t\t\"identity_id\",\n\t\t\"device_id\",\n\t\t\"fingerprint\",\n\t\t\"runtime_verifier\",\n\t\t\"completion\",\n\t],\n\tcancel: [\"group_id\"],\n} as const;\n\nfunction exactStrings<T extends string>(\n\tdata: Record<string, unknown> | null,\n\tfields: readonly T[],\n): data is Record<T, string> {\n\treturn (\n\t\tdata !== null &&\n\t\tObject.keys(data).length === fields.length &&\n\t\tfields.every((field) => Object.hasOwn(data, field) && typeof data[field] === \"string\")\n\t);\n}\nfunction isHash(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length === 64 && /^[a-f0-9]{64}$/.test(value);\n}\nfunction validInput(\n\taction: Action,\n\tdata: Record<string, unknown>,\n\tattemptId: string,\n\tconfig: CoordinatorAuthBrowserConfig,\n): data is Record<string, unknown> & { group_id: string } {\n\tif (!isAuthControllerId(data.group_id) || !isAuthControllerId(attemptId)) return false;\n\tif (action === \"create\") {\n\t\treturn (\n\t\t\texactStrings(data, FIELDS.create) &&\n\t\t\tisAuthControllerId(data.identity_id) &&\n\t\t\t(data.authority === \"device_claim\" || data.authority === \"controller_attestation\") &&\n\t\t\tisHash(data.runtime_verifier_hash) &&\n\t\t\tisHash(data.browser_start_hash) &&\n\t\t\tparseCoordinatorAuthLoopback(data.loopback_redirect).ok\n\t\t);\n\t}\n\tif (action !== \"finalize\") return true;\n\treturn (\n\t\texactStrings(data, FIELDS.finalize) &&\n\t\tdata.purpose === AUTH_LINK_PURPOSE &&\n\t\tdata.coordinator_id === config.coordinatorId &&\n\t\tdata.attempt_id === attemptId &&\n\t\tisAuthControllerId(data.identity_id) &&\n\t\tisAuthControllerId(data.device_id) &&\n\t\tisHash(data.fingerprint) &&\n\t\tdecodeCoordinatorAuthProof32(data.runtime_verifier) !== null &&\n\t\tdecodeCoordinatorAuthProof32(data.completion) !== null\n\t);\n}\nfunction rejectedResponse(\n\tc: Context,\n\tresult: CoordinatorAuthLinkRejected,\n\toptions: { reviewRequired?: boolean } = {},\n): Response {\n\tif (result.error === \"attempt_limited\") return c.json({ error: \"auth_link_limited\" }, 429);\n\tif (result.error === \"attempt_conflict\" || result.error === \"link_conflict\") {\n\t\treturn c.json({ error: \"auth_link_conflict\" }, 409);\n\t}\n\tif (options.reviewRequired && result.error === \"controller_not_active\") {\n\t\treturn c.json({ error: \"auth_link_review_required\" }, 403);\n\t}\n\treturn c.json({ error: \"auth_link_unavailable\" }, 403);\n}\n\nasync function readResolvedOwnerStatus(\n\tc: Context,\n\taction: \"resolved_owner_status\" | \"resolved_owner_receipt_status\",\n\tstore: CoordinatorDeviceAuthLinkStore,\n\tdata: Record<string, unknown>,\n\tsigner: CoordinatorAuthLinkSigner,\n\tconfig: CoordinatorAuthBrowserConfig,\n): Promise<Response> {\n\tif (!store.readResolvedAccountOwnerStatus) return c.json({ error: \"auth_link_unavailable\" }, 503);\n\tconst options = { ownerIdentityId: String(data.owner_identity_id) };\n\tif (action === \"resolved_owner_receipt_status\") {\n\t\tconst expectedReceipt = receiptFromData(data);\n\t\tif (!expectedReceipt) return c.json({ error: \"auth_link_invalid_input\" }, 400);\n\t\treturn c.json(\n\t\t\tawait store.readResolvedAccountOwnerStatus(signer, config, { ...options, expectedReceipt }),\n\t\t);\n\t}\n\treturn c.json(await store.readResolvedAccountOwnerStatus(signer, config, options));\n}\n\nasync function applyDeviceAction(\n\tc: Context,\n\taction: Action,\n\tstore: CoordinatorDeviceAuthLinkStore,\n\tdata: Record<string, unknown> & { group_id: string },\n\tattemptId: string,\n\tsigner: CoordinatorAuthLinkSigner,\n\tconfig: CoordinatorAuthBrowserConfig,\n): Promise<Response> {\n\tif (action === \"resolved_owner_status\" || action === \"resolved_owner_receipt_status\") {\n\t\treturn readResolvedOwnerStatus(c, action, store, data, signer, config);\n\t}\n\tif (action === \"account_status\") {\n\t\tif (!store.readAccountLinkStatus) return c.json({ error: \"auth_link_unavailable\" }, 503);\n\t\treturn c.json(\n\t\t\tawait store.readAccountLinkStatus(signer, config, { identityId: String(data.identity_id) }),\n\t\t);\n\t}\n\tif (action === \"status\") {\n\t\tconst status = await store.getAuthLinkAttemptStatus(\n\t\t\tattemptId,\n\t\t\t{ kind: \"device\", signer },\n\t\t\tconfig,\n\t\t);\n\t\tif (!status) return c.json({ error: \"auth_link_unavailable\" }, 404);\n\t\treturn c.json({ status });\n\t}\n\tif (action === \"create\") {\n\t\treturn createDeviceAttempt(c, store, data, attemptId, signer, config);\n\t}\n\tif (action === \"cancel\") {\n\t\treturn cancelDeviceAttempt(c, store, attemptId, signer, config);\n\t}\n\tif (!exactStrings(data, FIELDS.finalize))\n\t\treturn c.json({ error: \"auth_link_invalid_input\" }, 400);\n\treturn finalizeDeviceAttempt(c, store, data, attemptId, signer, config);\n}\n\nasync function createDeviceAttempt(\n\tc: Context,\n\tstore: CoordinatorDeviceAuthLinkStore,\n\tdata: Record<string, unknown>,\n\tattemptId: string,\n\tsigner: CoordinatorAuthLinkSigner,\n\tconfig: CoordinatorAuthBrowserConfig,\n): Promise<Response> {\n\tif (!exactStrings(data, FIELDS.create)) return c.json({ error: \"auth_link_invalid_input\" }, 400);\n\tif (!store.readAccountLinkStatus) return c.json({ error: \"auth_link_unavailable\" }, 503);\n\tconst current = await store.readAccountLinkStatus(signer, config, {\n\t\tidentityId: data.identity_id,\n\t});\n\tif (\n\t\t(current.state !== \"unlinked\" && current.state !== \"linked\") ||\n\t\tcurrent.identityId !== data.identity_id ||\n\t\tcurrent.authority !== data.authority\n\t)\n\t\treturn c.json({ error: \"auth_link_review_required\" }, 403);\n\tconst authority =\n\t\tcurrent.authority === \"device_claim\"\n\t\t\t? { kind: \"device_claim\" as const, identityId: data.identity_id }\n\t\t\t: { kind: \"controller_attestation\" as const };\n\tconst result = await store.createAuthLinkAttempt(\n\t\t{\n\t\t\tauthority,\n\t\t\texpectedIdentityId: data.identity_id,\n\t\t\tattemptId,\n\t\t\tsigner,\n\t\t\truntimeVerifierHash: data.runtime_verifier_hash,\n\t\t\tbrowserStartHash: data.browser_start_hash,\n\t\t\tloopbackRedirect: data.loopback_redirect,\n\t\t},\n\t\tconfig,\n\t);\n\tif (result.kind === \"rejected\") {\n\t\tif (result.error === \"attempt_unavailable\")\n\t\t\treturn c.json({ error: \"auth_link_review_required\" }, 403);\n\t\treturn rejectedResponse(c, result, { reviewRequired: true });\n\t}\n\treturn c.json(\n\t\t{\n\t\t\tstatus: result.status,\n\t\t\tidentity_id: result.identityId,\n\t\t\tauthority: current.authority,\n\t\t\tcoordinator_id: config.coordinatorId,\n\t\t},\n\t\tresult.kind === \"created\" ? 201 : 200,\n\t);\n}\n\nasync function cancelDeviceAttempt(\n\tc: Context,\n\tstore: CoordinatorDeviceAuthLinkStore,\n\tattemptId: string,\n\tsigner: CoordinatorAuthLinkSigner,\n\tconfig: CoordinatorAuthBrowserConfig,\n): Promise<Response> {\n\tconst result = await store.failAuthLinkAttempt(\n\t\t{\n\t\t\tattemptId,\n\t\t\trequester: { kind: \"device\", signer },\n\t\t\treason: \"cancelled\",\n\t\t},\n\t\tconfig,\n\t);\n\tif (result.kind === \"rejected\") return rejectedResponse(c, result);\n\tif (result.status.state !== \"failed\") return c.json({ error: \"auth_link_unavailable\" }, 503);\n\t// Failure is already committed: cleanup faults must never report success.\n\tconst retired = await store.retireAuthBrowserTransactions(config, { attemptId });\n\tif (retired.kind !== \"retired\" || retired.more)\n\t\treturn c.json({ error: \"auth_link_unavailable\" }, 503);\n\treturn c.json({ status: result.status });\n}\n\nasync function finalizeDeviceAttempt(\n\tc: Context,\n\tstore: CoordinatorDeviceAuthLinkStore,\n\tdata: Record<(typeof FIELDS.finalize)[number], string>,\n\tattemptId: string,\n\tsigner: CoordinatorAuthLinkSigner,\n\tconfig: CoordinatorAuthBrowserConfig,\n): Promise<Response> {\n\tconst runtimeVerifier = decodeCoordinatorAuthProof32(data.runtime_verifier);\n\tconst completion = decodeCoordinatorAuthProof32(data.completion);\n\tif (!runtimeVerifier || !completion) return c.json({ error: \"auth_link_invalid_input\" }, 400);\n\tconst runtimeVerifierHash = await hashCoordinatorAuthProofBytes32(runtimeVerifier);\n\tconst completionSecretHash = await hashCoordinatorAuthProofBytes32(completion);\n\tconst result = await store.finalizeAuthLinkAttempt(\n\t\t{\n\t\t\tpurpose: AUTH_LINK_PURPOSE,\n\t\t\tcoordinatorId: config.coordinatorId,\n\t\t\tattemptId,\n\t\t\tgroupId: data.group_id,\n\t\t\tidentityId: data.identity_id,\n\t\t\tdeviceId: data.device_id,\n\t\t\tfingerprint: data.fingerprint,\n\t\t\truntimeVerifierHash,\n\t\t\tcompletionSecretHash,\n\t\t\tsigner,\n\t\t},\n\t\tconfig,\n\t);\n\tif (result.kind === \"rejected\") return rejectedResponse(c, result, { reviewRequired: true });\n\treturn c.json({ status: result.status });\n}\n\nfunction readAccountStatusInput(\n\tc: Context,\n\turl: string,\n\tdeps: DeviceAuthLinkDeps,\n\toptions: { identityField?: \"identity_id\" | \"owner_identity_id\"; receipt?: true } = {},\n): { raw: Uint8Array; data: Record<string, unknown> } | Response {\n\tconst identityField = options.identityField ?? \"identity_id\";\n\tconst fields = [\n\t\t\"group_id\",\n\t\tidentityField,\n\t\t\"coordinator_origin\",\n\t\t...(options.receipt ? RECEIPT_QUERY_FIELDS : []),\n\t];\n\tconst parsed = new URL(url);\n\tconst origin = new URL(deps.config.redirectUri).origin;\n\tif (parsed.origin !== origin) return c.json({ error: \"auth_link_unavailable\" }, 403);\n\tconst entries = [...parsed.searchParams.entries()];\n\tif (\n\t\tc.req.raw.body !== null ||\n\t\tentries.length !== fields.length ||\n\t\tfields.some((field) => parsed.searchParams.getAll(field).length !== 1)\n\t) {\n\t\treturn c.json({ error: \"auth_link_invalid_input\" }, 400);\n\t}\n\tif (parsed.searchParams.get(\"coordinator_origin\") !== origin)\n\t\treturn c.json({ error: \"auth_link_unavailable\" }, 403);\n\treturn {\n\t\traw: new Uint8Array(),\n\t\tdata: Object.fromEntries(entries.filter(([field]) => field !== \"coordinator_origin\")),\n\t};\n}\n\nasync function readDeviceInput(\n\tc: Context,\n\taction: Action,\n\turl: string,\n\tdeps: DeviceAuthLinkDeps,\n): Promise<{ raw: Uint8Array; data: Record<string, unknown> } | Response> {\n\tif (action === \"account_status\") return readAccountStatusInput(c, url, deps);\n\tif (action === \"resolved_owner_status\")\n\t\treturn readAccountStatusInput(c, url, deps, { identityField: \"owner_identity_id\" });\n\tif (action === \"resolved_owner_receipt_status\")\n\t\treturn readAccountStatusInput(c, url, deps, {\n\t\t\tidentityField: \"owner_identity_id\",\n\t\t\treceipt: true,\n\t\t});\n\tif (action === \"status\") {\n\t\tconst entries = [...new URL(url).searchParams.entries()];\n\t\tconst entry = entries[0];\n\t\tif (entries.length !== 1 || !entry || entry[0] !== \"group_id\") {\n\t\t\treturn c.json({ error: \"auth_link_invalid_input\" }, 400);\n\t\t}\n\t\treturn { raw: new Uint8Array(), data: { group_id: entry[1] } };\n\t}\n\tconst raw = await deps.readRequestBytes(c, 4096);\n\tif (!raw) return c.json({ error: \"body_too_large\" }, 413);\n\tconst data = deps.parseJsonObject(raw);\n\tif (!exactStrings(data, FIELDS[action])) return c.json({ error: \"auth_link_invalid_input\" }, 400);\n\treturn { raw, data };\n}\n\nfunction validDeviceInput(\n\taction: Action,\n\tdata: Record<string, unknown>,\n\tattemptId: unknown,\n\tconfig: CoordinatorAuthBrowserConfig,\n): data is Record<string, unknown> & { group_id: string } {\n\tif (action === \"resolved_owner_status\")\n\t\treturn isAuthControllerId(data.group_id) && isAuthControllerId(data.owner_identity_id);\n\tif (action === \"resolved_owner_receipt_status\")\n\t\treturn (\n\t\t\tisAuthControllerId(data.group_id) &&\n\t\t\tisAuthControllerId(data.owner_identity_id) &&\n\t\t\treceiptFromData(data) !== null\n\t\t);\n\tif (action === \"account_status\")\n\t\treturn isAuthControllerId(data.group_id) && isAuthControllerId(data.identity_id);\n\treturn isAuthControllerId(attemptId) && validInput(action, data, attemptId, config);\n}\n\nasync function handleDeviceRequest(\n\tc: Context,\n\taction: Action,\n\tdeps: DeviceAuthLinkDeps,\n): Promise<Response> {\n\tc.header(\"Cache-Control\", \"no-store\");\n\tconst { config, storeFactory, authorizeRequest, rateLimitedResponse, authErrorStatus } = deps;\n\tlet store: CoordinatorDeviceAuthLinkStore | undefined;\n\ttry {\n\t\ttry {\n\t\t\tconst request = {\n\t\t\t\tmethod: c.req.method,\n\t\t\t\turl: c.req.url,\n\t\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t\t};\n\t\t\tconst pathAttemptId = c.req.param(\"attemptId\") ?? \"\";\n\t\t\tconst input = await readDeviceInput(c, action, request.url, deps);\n\t\t\tif (input instanceof Response) return input;\n\t\t\tconst { raw, data } = input;\n\t\t\tconst attemptId = action === \"create\" ? data.attempt_id : pathAttemptId;\n\t\t\tif (!validDeviceInput(action, data, attemptId, config))\n\t\t\t\treturn c.json({ error: \"auth_link_invalid_input\" }, 400);\n\t\t\tstore = storeFactory();\n\t\t\tconst auth = await authorizeRequest(store, {\n\t\t\t\t...request,\n\t\t\t\tgroupId: data.group_id,\n\t\t\t\tbody: raw,\n\t\t\t});\n\t\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\t\treturn (\n\t\t\t\t\trateLimitedResponse(c, `link:${action}`, { authenticated: false }) ??\n\t\t\t\t\tc.json({ error: \"auth_link_unavailable\" }, authErrorStatus(auth.error))\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst enrollment = auth.enrollment;\n\t\t\tconst limited = rateLimitedResponse(c, `${config.coordinatorId}:${enrollment.device_id}`, {\n\t\t\t\tauthenticated: true,\n\t\t\t});\n\t\t\tif (limited) return limited;\n\t\t\tawait assertConfiguredAuthSchema(store);\n\t\t\tconst signer = {\n\t\t\t\tgroupId: enrollment.group_id,\n\t\t\t\tdeviceId: enrollment.device_id,\n\t\t\t\tpublicKey: enrollment.public_key,\n\t\t\t\tfingerprint: enrollment.fingerprint,\n\t\t\t};\n\t\t\treturn await applyDeviceAction(c, action, store, data, String(attemptId), signer, config);\n\t\t} finally {\n\t\t\tawait store?.close();\n\t\t}\n\t} catch (error) {\n\t\treturn deviceAuthFailure(c, error);\n\t}\n}\n\nfunction deviceAuthFailure(c: Context, error: unknown): Response {\n\tif (error instanceof CoordinatorAuthSchemaUpgradeRequiredError)\n\t\treturn authSchemaUpgradeResponse();\n\treturn c.json({ error: \"auth_link_unavailable\" }, 503);\n}\n\n/** Mount only for the actual ready browser-auth adapter, never the legacy link option. */\nexport function registerCoordinatorAccountLinkStatusRoute(\n\tapp: DeviceAuthLinkApp,\n\tdeps: DeviceAuthLinkDeps,\n): void {\n\tif (!deps.config.enabled) return;\n\tconst { coordinatorId, issuer, revision, enabled, redirectUri } = deps.config;\n\tconst config = Object.freeze({ coordinatorId, issuer, revision, enabled, redirectUri });\n\tapp.get(\"/v1/auth/account-link-status\", (c) =>\n\t\thandleDeviceRequest(c, \"account_status\", { ...deps, config }),\n\t);\n\tapp.get(\"/v1/auth/resolved-account-owner-status\", (c) =>\n\t\thandleDeviceRequest(c, \"resolved_owner_status\", { ...deps, config }),\n\t);\n\tapp.get(\"/v1/auth/resolved-account-owner-receipt-status\", (c) =>\n\t\thandleDeviceRequest(c, \"resolved_owner_receipt_status\", { ...deps, config }),\n\t);\n}\n\nexport function registerCoordinatorDeviceAuthLinkRoutes(\n\tapp: DeviceAuthLinkApp,\n\tdeps: DeviceAuthLinkDeps,\n): void {\n\tconst { coordinatorId, issuer, revision, enabled, redirectUri } = deps.config;\n\tif (!enabled) return;\n\t// Retain only the reviewed configuration snapshot, never SDK secrets.\n\tconst config = Object.freeze({ coordinatorId, issuer, revision, enabled, redirectUri });\n\tconst {\n\t\tstoreFactory,\n\t\tauthorizeRequest,\n\t\tauthErrorStatus,\n\t\treadRequestBytes,\n\t\tparseJsonObject,\n\t\trateLimitedResponse,\n\t} = deps;\n\tconst captured = {\n\t\tconfig,\n\t\tstoreFactory,\n\t\tauthorizeRequest,\n\t\tauthErrorStatus,\n\t\treadRequestBytes,\n\t\tparseJsonObject,\n\t\trateLimitedResponse,\n\t};\n\tapp.post(\"/v1/auth/link-attempts\", (c) => handleDeviceRequest(c, \"create\", captured));\n\tapp.get(\"/v1/auth/link-attempts/:attemptId\", (c) => handleDeviceRequest(c, \"status\", captured));\n\tapp.post(\"/v1/auth/link-attempts/:attemptId/finalize\", (c) =>\n\t\thandleDeviceRequest(c, \"finalize\", captured),\n\t);\n\tapp.post(\"/v1/auth/link-attempts/:attemptId/cancel\", (c) =>\n\t\thandleDeviceRequest(c, \"cancel\", captured),\n\t);\n}\n","import { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport { decodeCoordinatorAuthProof32 } from \"./coordinator-auth-proof.js\";\n\nexport const BROWSER_FORM_BODY_MAX_BYTES = 4096;\nexport type BrowserFormAction =\n\t| \"transaction_attempt\"\n\t| \"session_logout\"\n\t| \"signin_start\"\n\t| \"link_start\";\ntype FormInvalid = Readonly<{ ok: false; error: \"form_invalid\" }>;\ntype ReadResult =\n\t| Readonly<{ ok: true; bytes: Uint8Array<ArrayBuffer> }>\n\t| FormInvalid\n\t| Readonly<{ ok: false; error: \"body_too_large\" }>;\ntype ParseResult =\n\t| FormInvalid\n\t| Readonly<{ ok: true; action: \"session_logout\"; csrf: string }>\n\t| Readonly<{ ok: true; action: \"signin_start\"; csrf: string }>\n\t| Readonly<{ ok: true; action: \"link_start\"; csrf: string; attemptId: string; startCode: string }>\n\t| Readonly<{ ok: true; action: \"transaction_attempt\"; csrf: string; attemptId: string }>;\nconst FORM_INVALID: FormInvalid = Object.freeze({ ok: false, error: \"form_invalid\" });\nconst BODY_TOO_LARGE = Object.freeze({ ok: false, error: \"body_too_large\" } as const);\nconst typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);\nconst typedArrayTag = Object.getOwnPropertyDescriptor(typedArrayPrototype, Symbol.toStringTag)?.get;\nconst typedArrayLength = Object.getOwnPropertyDescriptor(typedArrayPrototype, \"byteLength\")?.get;\nconst streamLocked = Object.getOwnPropertyDescriptor(ReadableStream.prototype, \"locked\")?.get;\n\nfunction ownData(input: unknown, key: string): unknown {\n\tif (typeof input !== \"object\" || input === null || Array.isArray(input)) throw FORM_INVALID;\n\tconst descriptor = Object.getOwnPropertyDescriptor(input, key);\n\tif (!descriptor || !Object.hasOwn(descriptor, \"value\")) throw FORM_INVALID;\n\treturn descriptor.value;\n}\n\nfunction declaredLengthError(value: unknown): FormInvalid | typeof BODY_TOO_LARGE | null {\n\tif (value === null || value === undefined) return null;\n\tif (typeof value !== \"string\" || value.length < 1 || value.length > 10) return FORM_INVALID;\n\t// Keep the final character explicitly within the declared-length grammar.\n\tif (!/^[0-9]+$/.test(value) || !/^[0-9]$/.test(value.slice(-1))) return FORM_INVALID;\n\tif (Number(value) > BROWSER_FORM_BODY_MAX_BYTES) return BODY_TOO_LARGE;\n\treturn null;\n}\n\nfunction nativeByteLength(value: unknown): number {\n\tif (typedArrayTag?.call(value) !== \"Uint8Array\") throw FORM_INVALID;\n\tconst length: unknown = typedArrayLength?.call(value);\n\tif (typeof length !== \"number\") throw FORM_INVALID;\n\treturn length;\n}\n\nfunction cancelReader(reader: ReadableStreamDefaultReader<Uint8Array>): void {\n\ttry {\n\t\t// Untrusted teardown can outlive this call; never wait for its completion.\n\t\tvoid ReadableStreamDefaultReader.prototype.cancel.call(reader).catch(() => {});\n\t} catch {\n\t\t// Cleanup cannot replace the fixed public error.\n\t}\n}\n\nasync function collectBytes(reader: ReadableStreamDefaultReader<Uint8Array>): Promise<ReadResult> {\n\ttry {\n\t\t// One owned allocation bounds storage, even with thousands of tiny chunks.\n\t\tconst bytes = new Uint8Array(BROWSER_FORM_BODY_MAX_BYTES);\n\t\tlet total = 0;\n\t\tfor (;;) {\n\t\t\tconst chunk = await ReadableStreamDefaultReader.prototype.read.call(reader);\n\t\t\tif (chunk.done) return Object.freeze({ ok: true, bytes: bytes.subarray(0, total) });\n\t\t\tconst length = nativeByteLength(chunk.value);\n\t\t\tif (length > BROWSER_FORM_BODY_MAX_BYTES - total) {\n\t\t\t\tcancelReader(reader);\n\t\t\t\treturn BODY_TOO_LARGE;\n\t\t\t}\n\t\t\t// Copy before the next read can let a producer reuse or mutate its buffer.\n\t\t\tUint8Array.prototype.set.call(bytes, chunk.value, total);\n\t\t\ttotal += length;\n\t\t}\n\t} catch {\n\t\tcancelReader(reader);\n\t\treturn FORM_INVALID;\n\t} finally {\n\t\ttry {\n\t\t\tReadableStreamDefaultReader.prototype.releaseLock.call(reader);\n\t\t} catch {\n\t\t\t// A failed release must not reject the caller's promise.\n\t\t}\n\t}\n}\n\n/** Byte limits only. Slow-sender deadlines must be enforced by the transport. */\nexport async function readBrowserFormBody(input: {\n\tbody: ReadableStream<Uint8Array> | null;\n\tcontentLength: unknown;\n}): Promise<ReadResult> {\n\ttry {\n\t\tconst body = ownData(input, \"body\");\n\t\tconst error = declaredLengthError(ownData(input, \"contentLength\"));\n\t\tif (error) return error;\n\t\tif (body === null || streamLocked?.call(body) !== false) return FORM_INVALID;\n\t\t// Fetch body extraction rejects disturbed streams without reading them.\n\t\tnew Response(body as ReadableStream<Uint8Array>);\n\t\tconst reader = ReadableStream.prototype.getReader.call(\n\t\t\tbody,\n\t\t) as ReadableStreamDefaultReader<Uint8Array>;\n\t\treturn await collectBytes(reader);\n\t} catch {\n\t\treturn FORM_INVALID;\n\t}\n}\n\nfunction decodeRawBody(bytes: Uint8Array): string {\n\tconst length = nativeByteLength(bytes);\n\tif (length === 0 || length > BROWSER_FORM_BODY_MAX_BYTES) throw FORM_INVALID;\n\t// Preserve BOM so the ASCII grammar rejects it instead of silently stripping it.\n\tconst raw = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(bytes);\n\tif (\n\t\traw.length > BROWSER_FORM_BODY_MAX_BYTES ||\n\t\t!/^[A-Za-z0-9*._%+=&-]+$/.test(raw) ||\n\t\t!/^[A-Za-z0-9*._%+=&-]+$/.test(raw.slice(-1))\n\t) {\n\t\tthrow FORM_INVALID;\n\t}\n\treturn raw;\n}\n\nfunction decodeFields(raw: string, action: BrowserFormAction): Readonly<Record<string, string>> {\n\tconst fields: Record<string, string> = Object.create(null);\n\tfor (const segment of raw.split(\"&\")) {\n\t\tconst equals = segment.indexOf(\"=\");\n\t\tif (equals < 1 || equals !== segment.lastIndexOf(\"=\")) throw FORM_INVALID;\n\t\tconst key = decodeURIComponent(segment.slice(0, equals).replaceAll(\"+\", \" \"));\n\t\tconst attemptField =\n\t\t\tkey === \"attempt_id\" && (action === \"transaction_attempt\" || action === \"link_start\");\n\t\tconst startField = key === \"start_code\" && action === \"link_start\";\n\t\tif (key !== \"csrf\" && !attemptField && !startField) {\n\t\t\tthrow FORM_INVALID;\n\t\t}\n\t\tif (Object.hasOwn(fields, key)) throw FORM_INVALID;\n\t\tfields[key] = decodeURIComponent(segment.slice(equals + 1).replaceAll(\"+\", \" \"));\n\t}\n\treturn Object.freeze(fields);\n}\n\n/** Grammar and field checks only; this does not authenticate CSRF or an attempt. */\nexport function parseBrowserFormBody(bytes: Uint8Array, action: BrowserFormAction): ParseResult {\n\ttry {\n\t\tif (\n\t\t\taction !== \"session_logout\" &&\n\t\t\taction !== \"transaction_attempt\" &&\n\t\t\taction !== \"signin_start\" &&\n\t\t\taction !== \"link_start\"\n\t\t)\n\t\t\treturn FORM_INVALID;\n\t\tconst fields = decodeFields(decodeRawBody(bytes), action);\n\t\tif (!Object.hasOwn(fields, \"csrf\")) return FORM_INVALID;\n\t\tconst csrf = fields.csrf;\n\t\tif (typeof csrf !== \"string\") return FORM_INVALID;\n\t\tif (action === \"session_logout\" || action === \"signin_start\") {\n\t\t\treturn Object.freeze({ ok: true, action, csrf });\n\t\t}\n\t\tconst attemptId = fields.attempt_id;\n\t\tif (!isAuthControllerId(attemptId)) return FORM_INVALID;\n\t\tif (action === \"link_start\") {\n\t\t\tconst startCode = fields.start_code;\n\t\t\tif (typeof startCode !== \"string\" || !decodeCoordinatorAuthProof32(startCode))\n\t\t\t\treturn FORM_INVALID;\n\t\t\treturn Object.freeze({ ok: true, action, csrf, attemptId, startCode });\n\t\t}\n\t\treturn Object.freeze({ ok: true, action, csrf, attemptId });\n\t} catch {\n\t\treturn FORM_INVALID;\n\t}\n}\n","import { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport { type CookieKind, readBrowserCookie } from \"./coordinator-browser-credential.js\";\nimport {\n\ttype BrowserCsrfKey,\n\ttype BrowserCsrfScope,\n\tisBrowserCsrfToken,\n\tverifyBrowserCsrfToken,\n} from \"./coordinator-browser-csrf.js\";\nimport {\n\tBROWSER_FORM_BODY_MAX_BYTES,\n\ttype BrowserFormAction,\n\tparseBrowserFormBody,\n\treadBrowserFormBody,\n} from \"./coordinator-browser-form-body.js\";\nimport type { InMemoryRequestRateLimiter } from \"./request-rate-limit.js\";\n\nexport const BROWSER_FORM_REJECTIONS = Object.freeze([\n\t\"invalid_input\",\n\t\"method_not_allowed\",\n\t\"client_unidentified\",\n\t\"rate_limited\",\n\t\"origin_rejected\",\n\t\"unsupported_media_type\",\n\t\"body_too_large\",\n\t\"form_invalid\",\n\t\"cookie_missing\",\n\t\"cookie_invalid\",\n\t\"csrf_invalid\",\n] as const);\ntype Rejection = (typeof BROWSER_FORM_REJECTIONS)[number];\ntype Failure = Readonly<{ ok: false; error: Rejection; retryAfterS?: number }>;\nexport type BrowserFormGuardResult =\n\t| Readonly<{ ok: true; action: \"session_logout\"; cookieHash: string }>\n\t| Readonly<{ ok: true; action: \"signin_start\"; cookieHash: string }>\n\t| Readonly<{\n\t\t\tok: true;\n\t\t\taction: \"link_start\";\n\t\t\tcookieHash: string;\n\t\t\tattemptId: string;\n\t\t\tstartCode: string;\n\t }>\n\t| Readonly<{ ok: true; action: \"transaction_attempt\"; cookieHash: string; attemptId: string }>\n\t| Failure;\nexport interface BrowserFormGuardInput {\n\trequest: Request;\n\tscope: BrowserCsrfScope;\n\tcsrfKey: BrowserCsrfKey;\n\taction: BrowserFormAction;\n\tlimiter: InMemoryRequestRateLimiter;\n\tclientKey: string;\n\tlimit?: number;\n}\nconst INVALID_INPUT: Failure = Object.freeze({ ok: false, error: \"invalid_input\" });\nconst ACTION_COOKIE_KINDS: Readonly<Record<BrowserFormAction, CookieKind>> = Object.freeze({\n\ttransaction_attempt: \"transaction\",\n\tsession_logout: \"session\",\n\tsignin_start: \"start\",\n\tlink_start: \"start\",\n});\nconst ratePolicies = new WeakMap<InMemoryRequestRateLimiter, Map<string, number>>();\nconst setupAdmission = Symbol(\"browser-auth-setup-admission\");\n/** Setup may spend the handler's token, but only this exact Request can redeem it once. */\nexport function checkBrowserAuthRequestRate(\n\trequest: Request,\n\tlimiter: InMemoryRequestRateLimiter,\n\tkey: string,\n\tlimit: number,\n\toptions: { admitSetup?: boolean; check?: InMemoryRequestRateLimiter[\"check\"] } = {},\n) {\n\tconst admission = Object.getOwnPropertyDescriptor(request, setupAdmission)?.value;\n\tif (\n\t\t!options.admitSetup &&\n\t\tadmission?.limiter === limiter &&\n\t\tadmission.key === key &&\n\t\tadmission.limit === limit\n\t) {\n\t\tReflect.deleteProperty(request, setupAdmission);\n\t\treturn { allowed: true, retryAfterS: 0 };\n\t}\n\tconst result = (options.check ?? limiter.check).call(limiter, key, limit);\n\tif (options.admitSetup && result.allowed)\n\t\tObject.defineProperty(request, setupAdmission, {\n\t\t\tvalue: { limiter, key, limit },\n\t\t\tconfigurable: true,\n\t\t});\n\treturn result;\n}\n\nexport function admitBrowserFormSetup(input: BrowserFormGuardInput): Failure | null {\n\ttry {\n\t\tconst snapshot = captureInput(input);\n\t\treturn checkOrigin(snapshot) ?? checkRate(snapshot, { admitSetup: true });\n\t} catch {\n\t\treturn INVALID_INPUT;\n\t}\n}\nconst headersGet = Headers.prototype.get;\nfunction nativeRequestGetter(name: string): ((this: Request) => unknown) | undefined {\n\tlet prototype: object | null = Request.prototype;\n\twhile (prototype !== null) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(prototype, name);\n\t\tif (descriptor) return descriptor.get;\n\t\tprototype = Object.getPrototypeOf(prototype);\n\t}\n\treturn undefined;\n}\nconst requestGetters = Object.freeze({\n\tmethod: nativeRequestGetter(\"method\"),\n\turl: nativeRequestGetter(\"url\"),\n\theaders: nativeRequestGetter(\"headers\"),\n\tbody: nativeRequestGetter(\"body\"),\n});\ntype Snapshot = Readonly<{\n\trequest: Request;\n\tscope: BrowserCsrfScope;\n\tcsrfKey: BrowserCsrfKey;\n\taction: BrowserFormAction;\n\tkind: CookieKind;\n\tlimiter: InMemoryRequestRateLimiter;\n\tcheck: InMemoryRequestRateLimiter[\"check\"];\n\tclientKey: unknown;\n\tlimit: unknown;\n\tmethod: string;\n\turl: string;\n\torigin: string | null;\n\tmediaType: string | null;\n\tcontentLength: string | null;\n\tcookie: string | null;\n\tbody: ReadableStream<Uint8Array> | null;\n}>;\n\nfunction reject(error: Rejection): Failure {\n\treturn Object.freeze({ ok: false, error });\n}\n\nfunction ownData(value: unknown, name: string): unknown {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) throw INVALID_INPUT;\n\tconst descriptor = Object.getOwnPropertyDescriptor(value, name);\n\tif (!descriptor || !Object.hasOwn(descriptor, \"value\")) throw INVALID_INPUT;\n\treturn descriptor.value;\n}\n\nfunction captureScope(value: unknown): BrowserCsrfScope {\n\tconst publicOrigin = ownData(value, \"publicOrigin\");\n\tconst store = ownData(value, \"store\");\n\tconst coordinatorId = ownData(store, \"coordinatorId\");\n\tconst revision = ownData(store, \"revision\");\n\tif (typeof publicOrigin !== \"string\" || /[\\\\\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(publicOrigin)) {\n\t\tthrow INVALID_INPUT;\n\t}\n\tconst url = new URL(publicOrigin);\n\tif (url.protocol !== \"https:\" || url.origin !== publicOrigin || url.username || url.password) {\n\t\tthrow INVALID_INPUT;\n\t}\n\tif (\n\t\t!isAuthControllerId(coordinatorId) ||\n\t\ttypeof revision !== \"string\" ||\n\t\trevision.length !== 64 ||\n\t\t!/^[a-f0-9]{64}$/.test(revision)\n\t)\n\t\tthrow INVALID_INPUT;\n\treturn Object.freeze({ publicOrigin, store: Object.freeze({ coordinatorId, revision }) });\n}\n\nfunction captureCheck(value: unknown): InMemoryRequestRateLimiter[\"check\"] {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) throw INVALID_INPUT;\n\tconst seen = new Set<object>();\n\tlet cursor: object | null = value;\n\twhile (cursor !== null) {\n\t\tif (seen.has(cursor)) throw INVALID_INPUT;\n\t\tseen.add(cursor);\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(cursor, \"check\");\n\t\tif (descriptor) {\n\t\t\tif (!Object.hasOwn(descriptor, \"value\") || typeof descriptor.value !== \"function\") {\n\t\t\t\tthrow INVALID_INPUT;\n\t\t\t}\n\t\t\treturn descriptor.value;\n\t\t}\n\t\tcursor = Object.getPrototypeOf(cursor);\n\t}\n\tthrow INVALID_INPUT;\n}\n\nfunction captureInput(input: BrowserFormGuardInput): Snapshot {\n\tconst request = ownData(input, \"request\");\n\tconst scope = captureScope(ownData(input, \"scope\"));\n\tconst csrfKey = ownData(input, \"csrfKey\") as BrowserCsrfKey;\n\tconst action = ownData(input, \"action\");\n\tconst limiter = ownData(input, \"limiter\");\n\tconst check = captureCheck(limiter);\n\tconst clientKey = ownData(input, \"clientKey\");\n\tconst limitDescriptor = Object.getOwnPropertyDescriptor(input, \"limit\");\n\tif (limitDescriptor && !Object.hasOwn(limitDescriptor, \"value\")) throw INVALID_INPUT;\n\tconst suppliedLimit: unknown = limitDescriptor?.value;\n\tconst limit = suppliedLimit === undefined ? 20 : suppliedLimit;\n\tif (\n\t\t!(request instanceof Request) ||\n\t\t(action !== \"session_logout\" &&\n\t\t\taction !== \"transaction_attempt\" &&\n\t\t\taction !== \"signin_start\" &&\n\t\t\taction !== \"link_start\")\n\t) {\n\t\tthrow INVALID_INPUT;\n\t}\n\t// Native getters enforce the Request brand and ignore caller-owned overrides.\n\tconst method: unknown = requestGetters.method?.call(request);\n\tconst url: unknown = requestGetters.url?.call(request);\n\tconst headers = requestGetters.headers?.call(request) as Headers;\n\tconst body = requestGetters.body?.call(request) as ReadableStream<Uint8Array> | null;\n\tif (typeof method !== \"string\" || typeof url !== \"string\") throw INVALID_INPUT;\n\treturn Object.freeze({\n\t\trequest,\n\t\tscope,\n\t\tcsrfKey,\n\t\taction,\n\t\tkind: ACTION_COOKIE_KINDS[action],\n\t\tlimiter: limiter as InMemoryRequestRateLimiter,\n\t\tcheck,\n\t\tclientKey,\n\t\tlimit,\n\t\tmethod,\n\t\turl,\n\t\tbody,\n\t\torigin: headersGet.call(headers, \"origin\"),\n\t\tmediaType: headersGet.call(headers, \"content-type\"),\n\t\tcontentLength: headersGet.call(headers, \"content-length\"),\n\t\tcookie: headersGet.call(headers, \"cookie\"),\n\t});\n}\n\nfunction pinRatePolicy(snapshot: Snapshot, limit: number): boolean {\n\tlet policies = ratePolicies.get(snapshot.limiter);\n\tif (!policies) {\n\t\tpolicies = new Map();\n\t\tratePolicies.set(snapshot.limiter, policies);\n\t}\n\tconst coordinatorId = snapshot.scope.store.coordinatorId;\n\tconst existing = policies.get(coordinatorId);\n\tif (existing !== undefined) return existing === limit;\n\tpolicies.set(coordinatorId, limit);\n\treturn true;\n}\n\nfunction checkRate(snapshot: Snapshot, options: { admitSetup?: boolean } = {}): Failure | null {\n\tconst { clientKey, limit } = snapshot;\n\tif (!isAuthControllerId(clientKey) || clientKey.length > 128) {\n\t\treturn reject(\"client_unidentified\");\n\t}\n\tif (typeof limit !== \"number\" || !Number.isSafeInteger(limit) || limit < 1 || limit > 1000) {\n\t\treturn INVALID_INPUT;\n\t}\n\t// The injected limiter includes the limit in its internal bucket key.\n\tif (!pinRatePolicy(snapshot, limit)) return INVALID_INPUT;\n\tconst result: unknown = checkBrowserAuthRequestRate(\n\t\tsnapshot.request,\n\t\tsnapshot.limiter,\n\t\tJSON.stringify([\"browser-form\", snapshot.scope.store.coordinatorId, clientKey]),\n\t\tlimit,\n\t\t{ ...options, check: snapshot.check },\n\t);\n\tconst allowed = ownData(result, \"allowed\");\n\tconst retryAfterS = ownData(result, \"retryAfterS\");\n\tif (\n\t\ttypeof allowed !== \"boolean\" ||\n\t\ttypeof retryAfterS !== \"number\" ||\n\t\t!Number.isFinite(retryAfterS)\n\t)\n\t\treturn INVALID_INPUT;\n\tif (allowed === true) {\n\t\treturn Number.isSafeInteger(retryAfterS) && retryAfterS >= 0 ? null : INVALID_INPUT;\n\t}\n\treturn Object.freeze({\n\t\tok: false,\n\t\terror: \"rate_limited\",\n\t\tretryAfterS: Math.max(1, Math.min(3600, Math.ceil(retryAfterS))),\n\t});\n}\n\nfunction validMediaType(value: string | null): boolean {\n\tif (value === null || /[^\\x20-\\x7e\\t]/.test(value)) return false;\n\tconst parts = value.toLowerCase().split(\";\");\n\tif (parts.length > 2 || parts[0]?.trim() !== \"application/x-www-form-urlencoded\") return false;\n\tif (parts.length === 1) return true;\n\tconst charset = parts[1]?.split(\"=\");\n\treturn (\n\t\tcharset?.length === 2 && charset[0]?.trim() === \"charset\" && charset[1]?.trim() === \"utf-8\"\n\t);\n}\n\nfunction checkOrigin(snapshot: Snapshot): Failure | null {\n\tif (\n\t\tnew URL(snapshot.url).origin !== snapshot.scope.publicOrigin ||\n\t\tsnapshot.origin !== snapshot.scope.publicOrigin\n\t)\n\t\treturn reject(\"origin_rejected\");\n\treturn null;\n}\n\nfunction checkMediaAndLength(snapshot: Snapshot): Failure | null {\n\tif (!validMediaType(snapshot.mediaType)) return reject(\"unsupported_media_type\");\n\tconst length = snapshot.contentLength;\n\tif (length === null) return null;\n\tif (\n\t\tlength.length < 1 ||\n\t\tlength.length > 10 ||\n\t\t!/^[0-9]+$/.test(length) ||\n\t\t!/^[0-9]$/.test(length.slice(-1))\n\t)\n\t\treturn reject(\"form_invalid\");\n\tif (Number(length) > BROWSER_FORM_BODY_MAX_BYTES) return reject(\"body_too_large\");\n\treturn null;\n}\n\nasync function verifyForm(snapshot: Snapshot): Promise<BrowserFormGuardResult> {\n\tlet cookie: Awaited<ReturnType<typeof readBrowserCookie>>;\n\ttry {\n\t\tcookie = await readBrowserCookie(snapshot.cookie, snapshot.kind);\n\t} catch {\n\t\treturn reject(\"cookie_invalid\");\n\t}\n\tif (cookie.kind === \"absent\") return reject(\"cookie_missing\");\n\tif (cookie.kind !== \"present\") return reject(\"cookie_invalid\");\n\tconst body = await readBrowserFormBody({\n\t\tbody: snapshot.body,\n\t\tcontentLength: snapshot.contentLength,\n\t});\n\tif (!body.ok) return reject(body.error);\n\tconst form = parseBrowserFormBody(body.bytes, snapshot.action);\n\tif (!form.ok) return reject(form.error);\n\tif (\n\t\t!isBrowserCsrfToken(form.csrf) ||\n\t\t!(await verifyBrowserCsrfToken(\n\t\t\tsnapshot.csrfKey,\n\t\t\tcookie.secret,\n\t\t\tsnapshot.kind,\n\t\t\tsnapshot.scope,\n\t\t\tform.csrf,\n\t\t))\n\t)\n\t\treturn reject(\"csrf_invalid\");\n\tif (form.action === \"session_logout\" || form.action === \"signin_start\") {\n\t\treturn Object.freeze({ ok: true, action: form.action, cookieHash: cookie.cookieHash });\n\t}\n\tif (form.action === \"link_start\") {\n\t\treturn Object.freeze({\n\t\t\tok: true,\n\t\t\taction: form.action,\n\t\t\tcookieHash: cookie.cookieHash,\n\t\t\tattemptId: form.attemptId,\n\t\t\tstartCode: form.startCode,\n\t\t});\n\t}\n\treturn Object.freeze({\n\t\tok: true,\n\t\taction: form.action,\n\t\tcookieHash: cookie.cookieHash,\n\t\tattemptId: form.attemptId,\n\t});\n}\n\n/** Unmounted transport guard, not authentication. Require a live store lookup afterwards.\n * cookieHash is sensitive internal data, never an HTTP response or log DTO.\n * Supply server-owned scope, an imported CSRF key, and trusted platform client identity.\n */\nexport async function guardBrowserForm(\n\tinput: BrowserFormGuardInput,\n): Promise<BrowserFormGuardResult> {\n\ttry {\n\t\tconst snapshot = captureInput(input);\n\t\tif (snapshot.method !== \"POST\") return reject(\"method_not_allowed\");\n\t\tconst originError = checkOrigin(snapshot);\n\t\tif (originError) return originError;\n\t\tconst rateError = checkRate(snapshot);\n\t\tif (rateError) return rateError;\n\t\tconst headerError = checkMediaAndLength(snapshot);\n\t\tif (headerError) return headerError;\n\t\treturn await verifyForm(snapshot);\n\t} catch {\n\t\treturn INVALID_INPUT;\n\t}\n}\n","function nativeRequestGetter(name: string): ((this: Request) => unknown) | undefined {\n\tlet prototype: object | null = Request.prototype;\n\twhile (prototype !== null) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(prototype, name);\n\t\tif (descriptor) return descriptor.get;\n\t\tprototype = Object.getPrototypeOf(prototype);\n\t}\n\treturn undefined;\n}\nconst requestGetters = Object.freeze({\n\tmethod: nativeRequestGetter(\"method\"),\n\turl: nativeRequestGetter(\"url\"),\n\theaders: nativeRequestGetter(\"headers\"),\n});\nconst headersGet = Headers.prototype.get;\nexport function snapshotBrowserRoute(request: Request) {\n\tconst method = requestGetters.method?.call(request);\n\tconst url = requestGetters.url?.call(request);\n\tif (typeof method !== \"string\" || typeof url !== \"string\") throw new Error();\n\treturn Object.freeze({ method, url });\n}\n\nexport function snapshotBrowserRequest(request: Request) {\n\tconst route = snapshotBrowserRoute(request);\n\tconst headers = requestGetters.headers?.call(request) as Headers;\n\treturn Object.freeze({ ...route, cookie: headersGet.call(headers, \"cookie\") });\n}\n","import type {\n\tCoordinatorAuthBrowserConfig,\n\tCoordinatorAuthBrowserTransactionStore,\n} from \"./coordinator-auth-browser-transaction-contract.js\";\nimport { readBrowserCookie } from \"./coordinator-browser-credential.js\";\n\ntype ActivityStore = Pick<\n\tCoordinatorAuthBrowserTransactionStore,\n\t\"readAuthBrowserTransactionActivity\"\n>;\n\n/** Invalid credentials and config drift deny restart; lookup faults reach the handler's catch. */\nexport async function readBrowserStartTransaction(\n\tcookie: unknown,\n\tstore: ActivityStore,\n\tconfig: CoordinatorAuthBrowserConfig,\n): Promise<\"absent\" | \"invalid\" | \"active\" | \"inactive\"> {\n\tconst transaction = await readBrowserCookie(cookie, \"transaction\");\n\tif (transaction.kind !== \"present\") return transaction.kind;\n\tconst activity = await store.readAuthBrowserTransactionActivity(\n\t\t{ binderHash: transaction.cookieHash },\n\t\tconfig,\n\t);\n\tif (activity.kind === \"rejected\") return \"invalid\";\n\treturn activity.kind;\n}\n","import {\n\tdecodeCoordinatorAuthProof32,\n\thashCoordinatorAuthProofBytes32,\n} from \"./coordinator-auth-proof.js\";\nimport { ed25519KeyId, parseSshEd25519PublicKey } from \"./coordinator-ed25519-key-id.js\";\n\n/** Private ceremony metadata and pending-key proof, never current account/group authority. */\nexport interface OwnerAttempt {\n\tcoordinator_id: string;\n\tattempt_id: string;\n\tpurpose: \"owner_enroll\";\n\torigin: string;\n\tdevice_id: string;\n\tpublic_key: string;\n\tkey_id: string;\n\tfingerprint: string;\n\tissuer: string;\n\tauth_config_revision: string;\n\tadmission_owner_hash: string | null;\n\tloopback_redirect: string | null;\n\tbrowser_start_hash: string;\n\tbrowser_transaction_hash: string | null;\n\tbrowser_binder_hash: string | null;\n\taccount_subject: string | null;\n\tidentity_id: string | null;\n\tlink_id: string | null;\n\tlink_attempt_id: string | null;\n\tlink_controller_attestation_id: string | null;\n\tlink_auth_config_revision: string | null;\n\tgrant_revisions_json: string | null;\n\tconfirmation_hash: string | null;\n\tcompletion_secret_hash: string | null;\n\tfinal_key_proof_hash: string | null;\n\tstate: string;\n\tcreated_at_ms: number;\n\texpires_at_ms: number;\n\tfinalized_at_ms: number | null;\n\tbinding_id: string | null;\n\taudit_event_id: string | null;\n\tfinal_outcome_json: string | null;\n}\n\n/** The optional column exists only after explicit schema installation. */\nexport interface OwnerAuthorityAttempt extends OwnerAttempt {\n\towner_qualification_id?: string | null;\n}\n\nexport interface GrantPin {\n\tgroupId: string;\n\trevision: number;\n}\nexport function readGrantPins(value: string | null): GrantPin[] | null {\n\ttry {\n\t\tconst pins: unknown = JSON.parse(value ?? \"null\");\n\t\tif (!Array.isArray(pins) || pins.length < 1 || pins.length > 50) return null;\n\t\tif (\n\t\t\t!pins.every(\n\t\t\t\t(p) =>\n\t\t\t\t\tp &&\n\t\t\t\t\ttypeof p === \"object\" &&\n\t\t\t\t\ttypeof p.groupId === \"string\" &&\n\t\t\t\t\tp.groupId.trim().length > 0 &&\n\t\t\t\t\tp.groupId === p.groupId.trim() &&\n\t\t\t\t\t!p.groupId.includes(\"\\0\") &&\n\t\t\t\t\tNumber.isSafeInteger(p.revision) &&\n\t\t\t\t\tp.revision > 0,\n\t\t\t)\n\t\t)\n\t\t\treturn null;\n\t\tif (new Set(pins.map((p) => p.groupId)).size !== pins.length) return null;\n\t\treturn pins.map(({ groupId, revision }) => ({ groupId, revision }));\n\t} catch {\n\t\treturn null;\n\t}\n}\nexport function validAttemptTime(row: OwnerAttempt): boolean {\n\treturn (\n\t\tNumber.isSafeInteger(row.created_at_ms) &&\n\t\trow.created_at_ms >= 0 &&\n\t\trow.created_at_ms <= 9007199254140991 &&\n\t\trow.expires_at_ms === row.created_at_ms + 600000\n\t);\n}\nexport function validWriteTime(value: unknown): value is number {\n\treturn (\n\t\tNumber.isSafeInteger(value) &&\n\t\ttypeof value === \"number\" &&\n\t\tvalue >= 0 &&\n\t\tvalue <= 8640000000000000\n\t);\n}\n\ntype OwnerFinalPins = Pick<\n\tOwnerAttempt,\n\t| \"coordinator_id\"\n\t| \"origin\"\n\t| \"auth_config_revision\"\n\t| \"attempt_id\"\n\t| \"device_id\"\n\t| \"public_key\"\n\t| \"key_id\"\n\t| \"fingerprint\"\n\t| \"issuer\"\n\t| \"confirmation_hash\"\n>;\n\n/** The pending device can sign these pins from its start and the owner-only loopback delivery. */\nexport function ownerEnrollmentFinalMessage(a: OwnerFinalPins, completionSecret: string): string {\n\treturn JSON.stringify([\n\t\t\"codemem-owner-enrollment-finalize-v2\",\n\t\t\"owner_enroll\",\n\t\ta.coordinator_id,\n\t\ta.origin,\n\t\ta.auth_config_revision,\n\t\ta.attempt_id,\n\t\ta.device_id,\n\t\ta.public_key,\n\t\ta.key_id,\n\t\ta.fingerprint,\n\t\ta.issuer,\n\t\ta.confirmation_hash,\n\t\tcompletionSecret,\n\t]);\n}\n/** Commitment shown to the original browser, including the exact linked account and grants. */\nexport async function ownerEnrollmentConfirmationHash(a: OwnerAuthorityAttempt): Promise<string> {\n\tconst fields = `coordinator_id attempt_id origin device_id public_key key_id fingerprint\n issuer account_subject identity_id link_id link_attempt_id link_controller_attestation_id\n link_auth_config_revision auth_config_revision browser_start_hash browser_transaction_hash\n browser_binder_hash grant_revisions_json created_at_ms expires_at_ms`.split(/\\s+/);\n\tconst message = JSON.stringify([\n\t\t\"owner_enroll\",\n\t\t...fields.map((field) => a[field as keyof OwnerAttempt]),\n\t\t// Keep existing operator confirmation/proof commitments byte-for-byte unchanged.\n\t\t...(a.admission_owner_hash === null ? [] : [a.admission_owner_hash]),\n\t\t...(a.owner_qualification_id == null\n\t\t\t? []\n\t\t\t: [\"codemem.owner-enrollment.qualification.v1\", a.owner_qualification_id]),\n\t]);\n\tconst digest = await globalThis.crypto.subtle.digest(\n\t\t\"SHA-256\",\n\t\tnew TextEncoder().encode(message),\n\t);\n\treturn Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n/** Verifies the pending-key signature and hashes proof bytes, not the stored completion hash or current authority. */\nexport async function verifyPendingKeySignatureAndHashes(\n\ta: OwnerAttempt,\n\tcompletionSecret: string,\n\tsignature: string,\n) {\n\tconst bytes = decodeCoordinatorAuthProof32(completionSecret);\n\tif (!bytes || (await ed25519KeyId(a.public_key)) !== a.key_id) return null;\n\t// Legacy fingerprints hash the exact key text, unlike the canonical SSH key ID.\n\tconst fingerprintDigest = await globalThis.crypto.subtle.digest(\n\t\t\"SHA-256\",\n\t\tnew TextEncoder().encode(a.public_key),\n\t);\n\tconst fingerprint = Array.from(new Uint8Array(fingerprintDigest), (b) =>\n\t\tb.toString(16).padStart(2, \"0\"),\n\t).join(\"\");\n\tif (fingerprint !== a.fingerprint) return null;\n\tconst completionHash = await hashCoordinatorAuthProofBytes32(bytes);\n\tconst message = ownerEnrollmentFinalMessage(a, completionSecret);\n\tif (!(await verifyOwnerEnrollmentSignature(a.public_key, message, signature))) return null;\n\tconst digest = await globalThis.crypto.subtle.digest(\n\t\t\"SHA-256\",\n\t\tnew TextEncoder().encode(signature),\n\t);\n\tconst keyProofHash = Array.from(new Uint8Array(digest), (b) =>\n\t\tb.toString(16).padStart(2, \"0\"),\n\t).join(\"\");\n\treturn { completionHash, keyProofHash };\n}\nexport async function verifyOwnerEnrollmentSignature(\n\tpublicKey: string,\n\tmessage: string,\n\tsignature: string,\n): Promise<boolean> {\n\ttry {\n\t\tif (typeof signature !== \"string\" || !/^[A-Za-z0-9_-]{85}[AQgw]$/.test(signature)) return false;\n\t\tconst binary = atob(`${signature.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\")}==`);\n\t\tconst bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));\n\t\tconst parsed = parseSshEd25519PublicKey(publicKey);\n\t\tif (parsed.kind !== \"ed25519\" || bytes.length !== 64) return false;\n\t\tconst key = await globalThis.crypto.subtle.importKey(\n\t\t\t\"raw\",\n\t\t\tnew Uint8Array(parsed.blob.slice(19)),\n\t\t\t{ name: \"Ed25519\" },\n\t\t\tfalse,\n\t\t\t[\"verify\"],\n\t\t);\n\t\treturn await globalThis.crypto.subtle.verify(\n\t\t\t\"Ed25519\",\n\t\t\tkey,\n\t\t\tbytes,\n\t\t\tnew TextEncoder().encode(message),\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** Validates proof and metadata only; the atomic writer must still check live authority in SQL. */\nexport async function verifyOwnerEnrollmentCompletion(\n\ta: OwnerAttempt,\n\trevision: string,\n\tnow: number,\n\tcompletionSecret: string,\n\tsignature: string,\n) {\n\tconst grants = readGrantPins(a.grant_revisions_json);\n\tif (\n\t\t!grants ||\n\t\ta.purpose !== \"owner_enroll\" ||\n\t\ta.state !== \"confirmed\" ||\n\t\t![a.account_subject, a.identity_id, a.link_id, a.confirmation_hash].every(isNonemptyText) ||\n\t\t!validAttemptTime(a) ||\n\t\t!validWriteTime(now) ||\n\t\tnow < a.created_at_ms ||\n\t\tnow >= a.expires_at_ms ||\n\t\trevision !== a.auth_config_revision\n\t)\n\t\treturn null;\n\tif ((await ownerEnrollmentConfirmationHash(a)) !== a.confirmation_hash) return null;\n\tconst proof = await verifyPendingKeySignatureAndHashes(a, completionSecret, signature);\n\tif (!proof || proof.completionHash !== a.completion_secret_hash) return null;\n\treturn { grants, ...proof };\n}\nfunction isNonemptyText(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.trim().length > 0;\n}\nfunction receiptOutcomeMatches(row: OwnerAttempt): boolean {\n\tconst grants = readGrantPins(row.grant_revisions_json);\n\ttry {\n\t\tconst outcome = JSON.parse(row.final_outcome_json ?? \"null\");\n\t\treturn (\n\t\t\t!!grants &&\n\t\t\toutcome?.kind === \"finalized\" &&\n\t\t\toutcome.bindingId === row.binding_id &&\n\t\t\tJSON.stringify(outcome.groups) === JSON.stringify(grants.map((g) => g.groupId))\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Receipt shape is not evidence that a database commit occurred or permission remains active. */\nexport function validOwnerEnrollmentReceiptMetadata(a: OwnerAttempt): boolean {\n\treturn (\n\t\ta.purpose === \"owner_enroll\" &&\n\t\ta.state === \"finalized\" &&\n\t\t!!a.binding_id &&\n\t\t!!a.audit_event_id &&\n\t\tisNonemptyText(a.final_key_proof_hash) &&\n\t\tisNonemptyText(a.completion_secret_hash) &&\n\t\treceiptOutcomeMatches(a) &&\n\t\tvalidAttemptTime(a) &&\n\t\tvalidWriteTime(a.finalized_at_ms) &&\n\t\ta.finalized_at_ms >= a.created_at_ms &&\n\t\ta.finalized_at_ms < a.expires_at_ms\n\t);\n}\n","import {\n\tdecodeCoordinatorAuthProof32,\n\thashCoordinatorAuthProofBytes32,\n} from \"./coordinator-auth-proof.js\";\nimport { ed25519KeyId } from \"./coordinator-ed25519-key-id.js\";\nimport { verifyOwnerEnrollmentSignature } from \"./coordinator-owner-enrollment-proof.js\";\n\n/** One stored rebinding attempt. Private ceremony state, never current authority. */\nexport interface DeviceRebindAttempt {\n\tcoordinator_id: string;\n\tattempt_id: string;\n\torigin: string;\n\tdevice_id: string;\n\tpublic_key: string;\n\tkey_id: string;\n\tfingerprint: string;\n\tcurrent_identity_id: string;\n\tissuer: string;\n\tauth_config_revision: string;\n\tloopback_redirect: string | null;\n\tbrowser_start_hash: string;\n\tbrowser_transaction_hash: string | null;\n\tbrowser_binder_hash: string | null;\n\taccount_subject: string | null;\n\ttarget_identity_id: string | null;\n\tlink_id: string | null;\n\tlink_authority_kind: \"controller_attestation\" | \"device_claim\" | null;\n\treview_digest: string | null;\n\tteam_effects_json: string | null;\n\tenrollment_count: number | null;\n\tconfirmation_hash: string | null;\n\tcompletion_secret_hash: string | null;\n\tfinal_key_proof_hash: string | null;\n\tstate: string;\n\tcreated_at_ms: number;\n\texpires_at_ms: number;\n\tfinalized_at_ms: number | null;\n\tbinding_id: string | null;\n\taudit_event_id: string | null;\n\tfinal_outcome_json: string | null;\n}\n\n// Domain strings differ from owner enrollment so no proof can cross ceremonies.\nconst CONFIRM_DOMAIN = \"codemem-device-rebind-confirm-v1\";\nconst FINAL_DOMAIN = \"codemem-device-rebind-finalize-v1\";\n\nconst CONFIRMED_FIELDS = [\n\t\"coordinator_id\",\n\t\"attempt_id\",\n\t\"origin\",\n\t\"device_id\",\n\t\"public_key\",\n\t\"key_id\",\n\t\"fingerprint\",\n\t\"current_identity_id\",\n\t\"issuer\",\n\t\"auth_config_revision\",\n\t\"browser_start_hash\",\n\t\"browser_transaction_hash\",\n\t\"browser_binder_hash\",\n\t\"account_subject\",\n\t\"target_identity_id\",\n\t\"link_id\",\n\t\"link_authority_kind\",\n\t\"review_digest\",\n\t\"team_effects_json\",\n\t\"enrollment_count\",\n\t\"created_at_ms\",\n\t\"expires_at_ms\",\n] as const satisfies readonly (keyof DeviceRebindAttempt)[];\n\nasync function sha256Hex(text: string): Promise<string> {\n\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(text));\n\treturn Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * What the browser confirms: the Google account, both Identities, the device,\n * the local review digest, and the Team effects shown to the person.\n */\nexport function deviceRebindConfirmationHash(a: DeviceRebindAttempt): Promise<string> {\n\treturn sha256Hex(JSON.stringify([CONFIRM_DOMAIN, ...CONFIRMED_FIELDS.map((field) => a[field])]));\n}\n\n/** What the device key signs after the loopback delivers the completion secret. */\nexport function deviceRebindFinalMessage(a: DeviceRebindAttempt, completionSecret: string): string {\n\treturn JSON.stringify([\n\t\tFINAL_DOMAIN,\n\t\ta.coordinator_id,\n\t\ta.origin,\n\t\ta.auth_config_revision,\n\t\ta.attempt_id,\n\t\ta.device_id,\n\t\ta.public_key,\n\t\ta.key_id,\n\t\ta.fingerprint,\n\t\ta.issuer,\n\t\ta.current_identity_id,\n\t\ta.target_identity_id,\n\t\ta.review_digest,\n\t\ta.confirmation_hash,\n\t\tcompletionSecret,\n\t]);\n}\n\nfunction confirmedAndCurrent(a: DeviceRebindAttempt, revision: string, now: number): boolean {\n\treturn (\n\t\ta.state === \"confirmed\" &&\n\t\t[\n\t\t\ta.account_subject,\n\t\t\ta.target_identity_id,\n\t\t\ta.link_id,\n\t\t\ta.review_digest,\n\t\t\ta.confirmation_hash,\n\t\t].every((value) => typeof value === \"string\" && value.length > 0) &&\n\t\tNumber.isSafeInteger(now) &&\n\t\tnow >= a.created_at_ms &&\n\t\tnow < a.expires_at_ms &&\n\t\trevision === a.auth_config_revision\n\t);\n}\n\n/**\n * Checks the three proofs this attempt binds: the confirmed browser commitment,\n * the completion secret delivered to this device, and its enrolled key's\n * signature. It does not check current authority; the commit SQL does that.\n */\nexport async function verifyDeviceRebindCompletion(\n\ta: DeviceRebindAttempt,\n\tinput: { revision: string; now: number; completionSecret: string; signature: string },\n): Promise<{ keyProofHash: string } | null> {\n\tif (!confirmedAndCurrent(a, input.revision, input.now)) return null;\n\tif ((await deviceRebindConfirmationHash(a)) !== a.confirmation_hash) return null;\n\tconst secret = decodeCoordinatorAuthProof32(input.completionSecret);\n\tif (!secret || (await hashCoordinatorAuthProofBytes32(secret)) !== a.completion_secret_hash)\n\t\treturn null;\n\tif ((await ed25519KeyId(a.public_key)) !== a.key_id) return null;\n\tif ((await sha256Hex(a.public_key)) !== a.fingerprint) return null;\n\tconst message = deviceRebindFinalMessage(a, input.completionSecret);\n\tif (!(await verifyOwnerEnrollmentSignature(a.public_key, message, input.signature))) return null;\n\treturn { keyProofHash: await sha256Hex(input.signature) };\n}\n","import type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport {\n\tdecodeCoordinatorAuthProof32,\n\thashCoordinatorAuthProofBytes32,\n} from \"./coordinator-auth-proof.js\";\nimport {\n\ttype DeviceRebindAttempt,\n\tverifyDeviceRebindCompletion,\n} from \"./coordinator-device-rebind-proof.js\";\nimport {\n\ted25519KeyIdForRevocation,\n\tparseSshEd25519PublicKeyForRevocation,\n} from \"./coordinator-ed25519-key-id-compat.js\";\n\n/** Finalized rebinds allowed per target Identity in any 24 hours (ADR 0005 Section 8). */\nexport const DEVICE_REBIND_DAILY_LIMIT = 3;\nconst DAY_MS = 86_400_000;\n\nexport type DeviceRebindReceipt = {\n\tkind: \"finalized\";\n\tattemptId: string;\n\tbindingId: string;\n\tdeviceId: string;\n\tpreviousIdentityId: string;\n\ttargetIdentityId: string;\n\tenrollmentCount: number;\n\tfinalizedAtMs: number;\n};\n\nexport type DeviceRebindCommitResult =\n\t| { kind: \"committed\"; receipt: DeviceRebindReceipt }\n\t| { kind: \"prior_commit\"; receipt: DeviceRebindReceipt }\n\t| { kind: \"refused\" };\n\nconst ATTEMPT = \"coordinator_device_rebind_attempts\";\n\n/** A guard predicate on the live attempt `a`, with its own bound values. */\ninterface Guard {\n\tsql: string;\n\tvalues: readonly (string | number | null)[];\n}\n\n// Enrollment and attestation reads are bounded; above this the commit refuses.\nconst MAX_SCANNED_ROWS = 500;\n\n/**\n * Text forms of one SSH key differ (comments, whitespace), so the same key can\n * hide under another public_key and fingerprint. This scan finds every\n * enrollment and attestation whose canonical key is the device's key. It\n * refuses when one belongs to another device or names another Identity, and\n * returns the exact row set so the commit can pin it.\n */\nasync function keyAliasScan(\n\tbackend: AuthLinkBackend,\n\ta: DeviceRebindAttempt,\n): Promise<{ enrollments: string; attestations: string } | null> {\n\tconst enrollments = await backend.first<{ rows: string }>({\n\t\tsql: `SELECT json_group_array(json_object('groupId', group_id, 'deviceId', device_id,\n 'publicKey', public_key, 'identityId', identity_id)) AS rows\n FROM (SELECT group_id, device_id, public_key, identity_id FROM enrolled_devices LIMIT ?)`,\n\t\tvalues: [MAX_SCANNED_ROWS + 1],\n\t});\n\tconst attestations = await backend.first<{ rows: string }>({\n\t\tsql: `SELECT json_group_array(json_object('coordinatorId', coordinator_id,\n 'attestationId', attestation_id, 'deviceId', device_id, 'publicKey', public_key,\n 'identityId', identity_id)) AS rows\n FROM (SELECT coordinator_id, attestation_id, device_id, public_key, identity_id\n FROM coordinator_auth_controller_attestations WHERE revoked_at IS NULL LIMIT ?)`,\n\t\tvalues: [MAX_SCANNED_ROWS + 1],\n\t});\n\tif (!enrollments || !attestations) return null;\n\tconst enrolled = JSON.parse(enrollments.rows) as KeyRow[];\n\tconst attested = JSON.parse(attestations.rows) as KeyRow[];\n\tif (enrolled.length > MAX_SCANNED_ROWS || attested.length > MAX_SCANNED_ROWS) return null;\n\tif (!(await enrollmentsUseOnlyThisDevice(enrolled, a))) return null;\n\tif (!(await attestationsAgree(attested, a))) return null;\n\treturn { enrollments: enrollments.rows, attestations: attestations.rows };\n}\n\ninterface KeyRow {\n\tdeviceId: string;\n\tpublicKey: string;\n\tidentityId: string | null;\n}\n\n/** Only this device's enrollments may use its key, and only in its exact text. */\nasync function enrollmentsUseOnlyThisDevice(\n\trows: readonly KeyRow[],\n\ta: DeviceRebindAttempt,\n): Promise<boolean> {\n\tfor (const row of rows) {\n\t\tconst sameKey = await sameCanonicalKey(row.publicKey, a.key_id);\n\t\tif (sameKey === null) return false;\n\t\tconst thisDevice = row.deviceId === a.device_id;\n\t\tif (sameKey !== thisDevice || (sameKey && row.publicKey !== a.public_key)) return false;\n\t}\n\treturn true;\n}\n\n/** No active attestation of this device or its key names any Identity but the target. */\nasync function attestationsAgree(\n\trows: readonly KeyRow[],\n\ta: DeviceRebindAttempt,\n): Promise<boolean> {\n\tfor (const row of rows) {\n\t\tconst sameKey = await sameCanonicalKey(row.publicKey, a.key_id);\n\t\tif (sameKey === null) return false;\n\t\tif ((sameKey || row.deviceId === a.device_id) && row.identityId !== a.target_identity_id)\n\t\t\treturn false;\n\t}\n\treturn true;\n}\n\n/** True or false for a parsable key; null (refuse) for a malformed Ed25519 key. */\nasync function sameCanonicalKey(publicKey: string, keyId: string): Promise<boolean | null> {\n\tif (parseSshEd25519PublicKeyForRevocation(publicKey).kind === \"malformed_ed25519\") return null;\n\treturn (await ed25519KeyIdForRevocation(publicKey)) === keyId;\n}\n\n/**\n * This device has no proof of its own for its current Identity, as account\n * changes select it: no claim for this device and key in a live Team, and no\n * active attestation for this key in a live Team it is still enrolled in (a binding\n * already blocks every attempt). Only such a device may self-bind, getting a\n * binding for the Identity it already uses.\n */\nexport const NO_OWN_PROOF_SQL = `NOT EXISTS (SELECT 1 FROM coordinator_auth_device_claims d\n WHERE d.coordinator_id = a.coordinator_id AND d.identity_id = a.current_identity_id\n AND d.device_id = a.device_id AND d.key_id = a.key_id\n AND EXISTS (SELECT 1 FROM groups g WHERE g.group_id = d.group_id AND g.archived_at IS NULL))\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_controller_attestations t\n JOIN enrolled_devices e ON e.group_id = t.group_id AND e.device_id = t.device_id\n AND e.public_key = t.public_key AND e.fingerprint = t.fingerprint AND e.enabled = 1\n AND (e.identity_id IS NULL OR e.identity_id = t.identity_id)\n JOIN groups g ON g.group_id = t.group_id AND g.archived_at IS NULL\n WHERE t.coordinator_id = a.coordinator_id AND t.identity_id = a.current_identity_id\n AND t.device_id = a.device_id AND t.public_key = a.public_key AND t.fingerprint = a.fingerprint\n AND t.revoked_at IS NULL)`;\n\nfunction guards(\n\ta: DeviceRebindAttempt,\n\tnow: number,\n\trevision: string,\n\tscan: { enrollments: string; attestations: string },\n): Guard[] {\n\treturn [\n\t\t{\n\t\t\tsql: `a.state = 'confirmed' AND a.expires_at_ms > ? AND a.auth_config_revision = ?\n AND a.confirmation_hash = ? AND a.completion_secret_hash = ?`,\n\t\t\tvalues: [now, revision, a.confirmation_hash, a.completion_secret_hash],\n\t\t},\n\t\t{\n\t\t\tsql: `EXISTS (SELECT 1 FROM coordinator_auth_account_links l\n WHERE l.coordinator_id = a.coordinator_id AND l.link_id = a.link_id\n AND l.identity_id = a.target_identity_id AND l.issuer = a.issuer AND l.subject = a.account_subject\n AND l.authority_kind = a.link_authority_kind AND l.revoked_at_ms IS NULL)`,\n\t\t\tvalues: [],\n\t\t},\n\t\t// Accounts are never merged: switching needs a current Identity with no\n\t\t// active link. A self-bind (target = current) keeps the Identity, so its\n\t\t// link is the target link checked above, and the device must still have\n\t\t// no proof of its own.\n\t\t{\n\t\t\tsql: `((a.target_identity_id = a.current_identity_id AND ${NO_OWN_PROOF_SQL})\n OR (a.target_identity_id <> a.current_identity_id AND NOT EXISTS (SELECT 1\n FROM coordinator_auth_account_links l WHERE l.coordinator_id = a.coordinator_id\n AND l.identity_id = a.current_identity_id AND l.revoked_at_ms IS NULL)))`,\n\t\t\tvalues: [],\n\t\t},\n\t\t// Bindings are immutable, so a device is bound at most once.\n\t\t{\n\t\t\tsql: `NOT EXISTS (SELECT 1 FROM coordinator_device_ownership_bindings b\n WHERE b.device_id = a.device_id OR b.key_id = a.key_id)`,\n\t\t\tvalues: [],\n\t\t},\n\t\t{\n\t\t\tsql: `NOT EXISTS (SELECT 1 FROM coordinator_device_revocations r\n WHERE (r.subject_kind = 'device_id' AND r.subject_value = a.device_id)\n OR (r.subject_kind = 'ed25519_key' AND r.subject_value = a.key_id))`,\n\t\t\tvalues: [],\n\t\t},\n\t\t// This device's enrollments: exactly the confirmed count, this key, and no\n\t\t// third Identity. Rows already naming the target are left as they are.\n\t\t{\n\t\t\tsql: `(SELECT count(*) FROM enrolled_devices e WHERE e.device_id = a.device_id) = a.enrollment_count\n AND NOT EXISTS (SELECT 1 FROM enrolled_devices e WHERE e.device_id = a.device_id\n AND (e.public_key <> a.public_key OR e.fingerprint <> a.fingerprint\n OR (e.identity_id IS NOT NULL AND e.identity_id NOT IN (a.current_identity_id, a.target_identity_id))))`,\n\t\t\tvalues: [],\n\t\t},\n\t\t// The key-alias scan above still describes every enrollment and active\n\t\t// attestation, field for field: rows may be edited in place, not just added.\n\t\t{\n\t\t\tsql: `(SELECT count(*) FROM enrolled_devices) = json_array_length(?)\n AND NOT EXISTS (SELECT 1 FROM enrolled_devices e WHERE NOT EXISTS (SELECT 1 FROM json_each(?) k\n WHERE e.group_id = json_extract(k.value, '$.groupId') AND e.device_id = json_extract(k.value, '$.deviceId')\n AND e.public_key = json_extract(k.value, '$.publicKey')\n AND e.identity_id IS json_extract(k.value, '$.identityId')))\n AND (SELECT count(*) FROM coordinator_auth_controller_attestations WHERE revoked_at IS NULL)\n = json_array_length(?)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_controller_attestations t WHERE t.revoked_at IS NULL\n AND NOT EXISTS (SELECT 1 FROM json_each(?) k\n WHERE t.coordinator_id = json_extract(k.value, '$.coordinatorId')\n AND t.attestation_id = json_extract(k.value, '$.attestationId')\n AND t.device_id = json_extract(k.value, '$.deviceId')\n AND t.public_key = json_extract(k.value, '$.publicKey')\n AND t.identity_id = json_extract(k.value, '$.identityId')))`,\n\t\t\tvalues: [scan.enrollments, scan.enrollments, scan.attestations, scan.attestations],\n\t\t},\n\t\t{\n\t\t\tsql: `NOT EXISTS (SELECT 1 FROM coordinator_auth_controller_attestations t\n WHERE t.coordinator_id = a.coordinator_id AND (t.device_id = a.device_id OR t.public_key = a.public_key)\n AND t.revoked_at IS NULL AND t.identity_id <> a.target_identity_id)`,\n\t\t\tvalues: [],\n\t\t},\n\t\t{\n\t\t\tsql: `(SELECT count(*) FROM coordinator_device_rebind_audit_log r\n WHERE r.coordinator_id = a.coordinator_id AND r.target_identity_id = a.target_identity_id\n AND r.created_at_ms > ?) < ${DEVICE_REBIND_DAILY_LIMIT}`,\n\t\t\tvalues: [now - DAY_MS],\n\t\t},\n\t];\n}\n\n// Only coordinators that ran migration 0037 have legacy owner resolutions.\nconst NO_OTHER_LEGACY_OWNER: Guard = {\n\tsql: `NOT EXISTS (SELECT 1 FROM coordinator_legacy_owner_resolutions o\n WHERE o.coordinator_id = a.coordinator_id AND (o.device_id = a.device_id OR o.key_id = a.key_id)\n AND o.owner_identity_id <> a.target_identity_id)`,\n\tvalues: [],\n};\n\nasync function hasTable(backend: AuthLinkBackend, name: string): Promise<boolean> {\n\treturn (\n\t\t(await backend.first({\n\t\t\tsql: \"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?\",\n\t\t\tvalues: [name],\n\t\t})) !== null\n\t);\n}\n\n/**\n * Each guard is its own column, so the winning UPDATE stays shallow on D1\n * (expression depth limit 100).\n */\nasync function guardStatement(\n\tbackend: AuthLinkBackend,\n\ta: DeviceRebindAttempt,\n\tchecks: Guard[],\n): Promise<AuthLinkStatement> {\n\tconst all = [...checks];\n\tif (await hasTable(backend, \"coordinator_legacy_owner_resolutions\"))\n\t\tall.push(NO_OTHER_LEGACY_OWNER);\n\treturn {\n\t\tsql: `WITH rebind_guards AS MATERIALIZED (SELECT ${all\n\t\t\t.map((guard, index) => `(${guard.sql}) AS g${index}`)\n\t\t\t.join(\",\\n \")}\n FROM ${ATTEMPT} a WHERE a.coordinator_id = ? AND a.attempt_id = ?),\n rebind_ok AS MATERIALIZED (SELECT ${all.map((_, index) => `g${index}`).join(\" AND \")} AS ok\n FROM rebind_guards)`,\n\t\tvalues: [...all.flatMap((guard) => guard.values), a.coordinator_id, a.attempt_id],\n\t};\n}\n\nconst WINNER = \"coordinator_id = ? AND attempt_id = ? AND state = 'finalized' AND binding_id = ?\";\n\n/** A row-count mismatch updates the finalized row, which its trigger aborts with the batch. */\nfunction assertWrite(winner: readonly string[], expected: number): AuthLinkStatement {\n\treturn {\n\t\tsql: `UPDATE ${ATTEMPT} SET state = 'failed' WHERE ${WINNER} AND changes() <> ?`,\n\t\tvalues: [...winner, expected],\n\t};\n}\n\nfunction statements(\n\ta: DeviceRebindAttempt,\n\tguard: AuthLinkStatement,\n\tfields: { now: number; bindingId: string; eventId: string; keyProofHash: string },\n): AuthLinkStatement[] {\n\tconst { now, bindingId, eventId, keyProofHash } = fields;\n\tconst winner = [a.coordinator_id, a.attempt_id, bindingId];\n\tconst count = a.enrollment_count ?? 0;\n\tconst outcome = JSON.stringify({ kind: \"finalized\", bindingId, enrollmentCount: count });\n\treturn [\n\t\t{\n\t\t\tsql: `${guard.sql} UPDATE ${ATTEMPT} SET state = 'finalized', finalized_at_ms = ?,\n binding_id = ?, audit_event_id = ?, final_key_proof_hash = ?, final_outcome_json = ?,\n loopback_redirect = NULL\n WHERE coordinator_id = ? AND attempt_id = ? AND (SELECT ok FROM rebind_ok) = 1`,\n\t\t\tvalues: [\n\t\t\t\t...guard.values,\n\t\t\t\tnow,\n\t\t\t\tbindingId,\n\t\t\t\teventId,\n\t\t\t\tkeyProofHash,\n\t\t\t\toutcome,\n\t\t\t\ta.coordinator_id,\n\t\t\t\ta.attempt_id,\n\t\t\t],\n\t\t},\n\t\tassertWrite(winner, 1),\n\t\t{\n\t\t\tsql: `INSERT INTO coordinator_device_ownership_bindings\n (device_id, key_id, identity_id, coordinator_id, binding_id, provenance, source_ref, bound_at)\n SELECT device_id, key_id, target_identity_id, coordinator_id, binding_id, 'owner_enrollment',\n 'rebind:' || attempt_id, ? FROM ${ATTEMPT} WHERE ${WINNER}`,\n\t\t\tvalues: [new Date(now).toISOString(), ...winner],\n\t\t},\n\t\tassertWrite(winner, 1),\n\t\t{\n\t\t\tsql: `UPDATE enrolled_devices SET identity_id = ?\n WHERE device_id = ? AND EXISTS (SELECT 1 FROM ${ATTEMPT} WHERE ${WINNER})`,\n\t\t\tvalues: [a.target_identity_id, a.device_id, ...winner],\n\t\t},\n\t\tassertWrite(winner, count),\n\t\t{\n\t\t\tsql: `INSERT INTO coordinator_device_rebind_audit_log\n (coordinator_id, event_id, attempt_id, action, binding_id, device_id, previous_identity_id,\n target_identity_id, enrollment_count, created_at_ms)\n SELECT coordinator_id, audit_event_id, attempt_id, 'owner_device_rebound', binding_id, device_id,\n current_identity_id, target_identity_id, enrollment_count, finalized_at_ms\n FROM ${ATTEMPT} WHERE ${WINNER}`,\n\t\t\tvalues: winner,\n\t\t},\n\t\tassertWrite(winner, 1),\n\t];\n}\n\nasync function readAttempt(\n\tbackend: AuthLinkBackend,\n\tcoordinatorId: string,\n\tattemptId: string,\n): Promise<DeviceRebindAttempt | null> {\n\treturn backend.first<DeviceRebindAttempt>({\n\t\tsql: `SELECT * FROM ${ATTEMPT} WHERE coordinator_id = ? AND attempt_id = ?`,\n\t\tvalues: [coordinatorId, attemptId],\n\t});\n}\n\n/**\n * Reads a finalized rebind from records that never change: the finalized\n * attempt, its binding, and its audit event. Enrollments are not consulted,\n * because an admin may change them after the commit. Resolves an unknown commit outcome\n * without retrying the write. Null means \"not committed as recorded\".\n */\nexport async function readDeviceRebindReceipt(\n\tbackend: AuthLinkBackend,\n\tcoordinatorId: string,\n\tattemptId: string,\n): Promise<DeviceRebindReceipt | null> {\n\tconst row = await backend.first<DeviceRebindAttempt & { binding_ok: number; audit_ok: number }>({\n\t\tsql: `SELECT a.*,\n EXISTS (SELECT 1 FROM coordinator_device_ownership_bindings b WHERE b.binding_id = a.binding_id\n AND b.device_id = a.device_id AND b.key_id = a.key_id AND b.identity_id = a.target_identity_id\n AND b.coordinator_id = a.coordinator_id AND b.source_ref = 'rebind:' || a.attempt_id) AS binding_ok,\n EXISTS (SELECT 1 FROM coordinator_device_rebind_audit_log l WHERE l.coordinator_id = a.coordinator_id\n AND l.event_id = a.audit_event_id AND l.attempt_id = a.attempt_id AND l.binding_id = a.binding_id\n AND l.device_id = a.device_id AND l.previous_identity_id = a.current_identity_id\n AND l.target_identity_id = a.target_identity_id AND l.enrollment_count = a.enrollment_count\n AND l.created_at_ms = a.finalized_at_ms) AS audit_ok\n FROM ${ATTEMPT} a WHERE a.coordinator_id = ? AND a.attempt_id = ? AND a.state = 'finalized'`,\n\t\tvalues: [coordinatorId, attemptId],\n\t});\n\tif (row?.binding_ok !== 1 || row.audit_ok !== 1) return null;\n\treturn {\n\t\tkind: \"finalized\",\n\t\tattemptId: row.attempt_id,\n\t\tbindingId: row.binding_id as string,\n\t\tdeviceId: row.device_id,\n\t\tpreviousIdentityId: row.current_identity_id,\n\t\ttargetIdentityId: row.target_identity_id as string,\n\t\tenrollmentCount: row.enrollment_count as number,\n\t\tfinalizedAtMs: row.finalized_at_ms as number,\n\t};\n}\n\ninterface DeviceRebindCommitInput {\n\tbackend: AuthLinkBackend;\n\tcoordinatorId: string;\n\tattemptId: string;\n\t/** Trusted current auth config revision, never a client value. */\n\trevision: string;\n\tnow: number;\n\tcompletionSecret: string;\n\tsignature: string;\n}\n\n/**\n * One atomic commit: finalize the attempt, write the immutable ownership\n * binding, move every enrollment of the device key to the target Identity, and\n * record the audit event. Team memberships and grants are untouched. An exact\n * retry of an already finalized attempt returns its receipt; anything else\n * writes nothing. SQL errors propagate so an unknown outcome is never reported\n * as a refusal; callers resolve it with readDeviceRebindReceipt.\n */\nexport async function commitDeviceRebind(\n\tinput: DeviceRebindCommitInput,\n): Promise<DeviceRebindCommitResult> {\n\tconst { backend, now, revision } = input;\n\tconst row = await readAttempt(backend, input.coordinatorId, input.attemptId);\n\tif (!row) return { kind: \"refused\" };\n\tif (row.state === \"finalized\") return priorCommit(backend, row, input);\n\tconst proof = await verifyDeviceRebindCompletion(row, input);\n\tif (!proof) return { kind: \"refused\" };\n\tconst scan = await keyAliasScan(backend, row);\n\tif (!scan) return { kind: \"refused\" };\n\tconst guard = await guardStatement(backend, row, guards(row, now, revision, scan));\n\tconst bindingId = globalThis.crypto.randomUUID();\n\tawait backend.batch(\n\t\tstatements(row, guard, {\n\t\t\tnow,\n\t\t\tbindingId,\n\t\t\teventId: globalThis.crypto.randomUUID(),\n\t\t\tkeyProofHash: proof.keyProofHash,\n\t\t}),\n\t);\n\tconst receipt = await readDeviceRebindReceipt(backend, row.coordinator_id, row.attempt_id);\n\tif (!receipt) return { kind: \"refused\" };\n\t// A concurrent exact retry may have won; this call then wrote nothing itself.\n\treturn receipt.bindingId === bindingId\n\t\t? { kind: \"committed\", receipt }\n\t\t: { kind: \"prior_commit\", receipt };\n}\n\n/** An exact retry carries the same completion secret and the same signature. */\nasync function priorCommit(\n\tbackend: AuthLinkBackend,\n\trow: DeviceRebindAttempt,\n\tinput: { completionSecret: string; signature: string },\n): Promise<DeviceRebindCommitResult> {\n\tconst secret = decodeCoordinatorAuthProof32(input.completionSecret);\n\tif (!secret || (await hashCoordinatorAuthProofBytes32(secret)) !== row.completion_secret_hash)\n\t\treturn { kind: \"refused\" };\n\tconst digest = await globalThis.crypto.subtle.digest(\n\t\t\"SHA-256\",\n\t\tnew TextEncoder().encode(input.signature),\n\t);\n\tconst keyProofHash = Array.from(new Uint8Array(digest), (byte) =>\n\t\tbyte.toString(16).padStart(2, \"0\"),\n\t).join(\"\");\n\tif (keyProofHash !== row.final_key_proof_hash) return { kind: \"refused\" };\n\tconst receipt = await readDeviceRebindReceipt(backend, row.coordinator_id, row.attempt_id);\n\treturn receipt ? { kind: \"prior_commit\", receipt } : { kind: \"refused\" };\n}\n","import { CoordinatorAuthBrowserTransactions } from \"./coordinator-auth-browser-transaction.js\";\nimport type { CoordinatorAuthBrowserConfig } from \"./coordinator-auth-browser-transaction-contract.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport {\n\tAUTH_LINK_CREATE_WINDOW_MS,\n\tAUTH_LINK_MAX_ACTIVE_PER_DEVICE,\n\tAUTH_LINK_MAX_CREATES_PER_DEVICE_WINDOW,\n} from \"./coordinator-auth-link-contract.js\";\nimport { parseCoordinatorAuthLoopback } from \"./coordinator-auth-loopback.js\";\nimport {\n\tdecodeCoordinatorAuthProof32,\n\thashCoordinatorAuthProofBytes32,\n} from \"./coordinator-auth-proof.js\";\nimport {\n\tclearBrowserCookie,\n\treadBrowserCookie,\n\treissueStartCookieAsTransaction,\n} from \"./coordinator-browser-credential.js\";\nimport {\n\ttype BrowserCsrfKey,\n\ttype BrowserCsrfScope,\n\tissueBrowserCsrfToken,\n} from \"./coordinator-browser-csrf.js\";\nimport { guardBrowserForm } from \"./coordinator-browser-form-guard.js\";\nimport { snapshotBrowserRequest } from \"./coordinator-browser-request.js\";\nimport { readBrowserStartTransaction } from \"./coordinator-browser-start-transaction.js\";\nimport {\n\tcommitDeviceRebind,\n\tDEVICE_REBIND_DAILY_LIMIT,\n\ttype DeviceRebindReceipt,\n\tNO_OWN_PROOF_SQL,\n\treadDeviceRebindReceipt,\n} from \"./coordinator-device-rebind-commit.js\";\nimport {\n\ttype DeviceRebindAttempt,\n\tdeviceRebindConfirmationHash,\n\tverifyDeviceRebindCompletion,\n} from \"./coordinator-device-rebind-proof.js\";\nimport { ed25519KeyId } from \"./coordinator-ed25519-key-id.js\";\nimport type { CoordinatorOidcClient } from \"./coordinator-oidc.js\";\nimport type { InMemoryRequestRateLimiter } from \"./request-rate-limit.js\";\n\n/** The signed device request's verified enrollment; the route authenticates it. */\nexport interface DeviceRebindSigner {\n\tgroupId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n}\n\nexport interface DeviceRebindStart {\n\tattemptId: string;\n\tsigner: DeviceRebindSigner;\n\t/** The device's current Identity (its local actor), checked against its enrollments. */\n\tcurrentIdentityId: string;\n\tloopbackRedirect: string;\n\t/** SHA-256 hex of the browser start code; the device keeps the code itself. */\n\tbrowserStartHash: string;\n\t/** SHA-256 hex of the device's local review; any local change aborts the switch. */\n\treviewDigest: string;\n}\n\n/** Why a step refused; the Viewer turns these into the next action for the person. */\nexport type DeviceRebindRefusal =\n\t| \"unavailable\"\n\t| \"current_identity_linked\"\n\t| \"device_already_bound\"\n\t| \"account_not_linked\"\n\t| \"already_this_identity\"\n\t| \"daily_limit\"\n\t| \"retry\";\n\nexport interface DeviceRebindConfirmation {\n\tattemptId: string;\n\tdeviceId: string;\n\tfingerprint: string;\n\tissuer: string;\n\tsubject: string;\n\tcurrentIdentityId: string;\n\ttargetIdentityId: string;\n\t/** Groups where the device stays enrolled but the target Identity has no access yet. */\n\tgroupsWithoutAccess: readonly string[];\n\tconfirmationHash: string;\n}\n\nexport type DeviceRebindResult =\n\t| {\n\t\t\tkind: \"refused\";\n\t\t\treason: DeviceRebindRefusal;\n\t\t\t/** This step burned the browser's transaction; its cookie can be cleared. */\n\t\t\tretired?: true;\n\t\t\t/** Where the browser tells the device the attempt ended, so it stops waiting. */\n\t\t\treturnTo?: { loopbackRedirect: string; attemptId: string };\n\t }\n\t| { kind: \"unknown\" }\n\t| { kind: \"started\"; attemptId: string; expiresAtMs: number }\n\t| { kind: \"browser_claimed\"; authorizationUrl: string; setCookies: string[] }\n\t| { kind: \"verified\"; confirmation: DeviceRebindConfirmation; csrf: string }\n\t| { kind: \"confirmed\"; completionSecret: string; loopbackRedirect: string }\n\t| { kind: \"finalized\" | \"prior_commit\"; receipt: DeviceRebindReceipt }\n\t| {\n\t\t\tkind: \"status\";\n\t\t\tstate: string;\n\t\t\texpiresAtMs: number;\n\t\t\t/** Shown once the person confirmed; the device signs it at finalize. */\n\t\t\ttargetIdentityId: string | null;\n\t\t\treceipt: DeviceRebindReceipt | null;\n\t };\n\n/** What the signed device steps need: no OIDC client or browser CSRF key. */\nexport interface DeviceRebindDeviceDependencies {\n\tbackend: AuthLinkBackend;\n\t/** Store settings of the enabled browser-auth configuration. */\n\tconfig: CoordinatorAuthBrowserConfig;\n\tpublicOrigin: string;\n\tlimiter: InMemoryRequestRateLimiter;\n\tnow(): number;\n}\n\nexport interface DeviceRebindDependencies extends DeviceRebindDeviceDependencies {\n\tcsrfKey: BrowserCsrfKey;\n\tclient: Pick<CoordinatorOidcClient, \"createAuthorizationRequest\" | \"verifyCallback\">;\n}\n\nconst ATTEMPT = \"coordinator_device_rebind_attempts\";\nconst TTL_MS = 600_000;\nconst START_CLIENT_LIMIT = 20;\nconst refused = (reason: DeviceRebindRefusal): DeviceRebindResult => ({ kind: \"refused\", reason });\n\nasync function sha256Hex(value: string): Promise<string> {\n\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(value));\n\treturn Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nasync function proofHash(value: string): Promise<string | null> {\n\tconst bytes = decodeCoordinatorAuthProof32(value);\n\treturn bytes ? hashCoordinatorAuthProofBytes32(bytes) : null;\n}\n\nfunction mintCompletionSecret(): string {\n\tconst bytes = globalThis.crypto.getRandomValues(new Uint8Array(32));\n\treturn btoa(String.fromCharCode(...bytes))\n\t\t.replaceAll(\"+\", \"-\")\n\t\t.replaceAll(\"/\", \"_\")\n\t\t.replace(/=+$/, \"\");\n}\n\n// Live conditions shared by every step; each winning statement repeats them.\nconst UNBOUND_SQL = `NOT EXISTS (SELECT 1 FROM coordinator_device_ownership_bindings b\n WHERE b.device_id = a.device_id OR b.key_id = a.key_id)`;\nconst UNREVOKED_SQL = `NOT EXISTS (SELECT 1 FROM coordinator_device_revocations r\n WHERE (r.subject_kind = 'device_id' AND r.subject_value = a.device_id)\n OR (r.subject_kind = 'ed25519_key' AND r.subject_value = a.key_id))`;\nconst CURRENT_UNLINKED_SQL = `NOT EXISTS (SELECT 1 FROM coordinator_auth_account_links l\n WHERE l.coordinator_id = a.coordinator_id AND l.identity_id = a.current_identity_id\n AND l.revoked_at_ms IS NULL)`;\nconst TARGET_LINK_SQL = `EXISTS (SELECT 1 FROM coordinator_auth_account_links l\n WHERE l.coordinator_id = a.coordinator_id AND l.link_id = a.link_id\n AND l.identity_id = a.target_identity_id AND l.issuer = a.issuer AND l.subject = a.account_subject\n AND l.authority_kind = a.link_authority_kind AND l.revoked_at_ms IS NULL)`;\n/**\n * Switching Identities needs a current Identity without an account link\n * (accounts are never merged). A self-bind (target = current) instead needs a\n * device without its own proof. Before sign-in the target is unknown, so\n * either may hold.\n */\nconst CURRENT_ACCOUNT_SQL = `(${CURRENT_UNLINKED_SQL}\n OR ((a.target_identity_id IS NULL OR a.target_identity_id = a.current_identity_id) AND ${NO_OWN_PROOF_SQL}))`;\nconst LIVE_SQL = `a.coordinator_id = ? AND a.attempt_id = ? AND a.origin = ? AND a.issuer = ?\n AND a.auth_config_revision = ? AND a.created_at_ms <= ? AND a.expires_at_ms > ?\n AND ${UNBOUND_SQL} AND ${UNREVOKED_SQL} AND ${CURRENT_ACCOUNT_SQL}`;\n// Every enrollment of the device names no Identity or the current one.\nconst ENROLLMENTS_CURRENT_SQL = `NOT EXISTS (SELECT 1 FROM enrolled_devices e WHERE e.device_id = a.device_id\n AND e.identity_id IS NOT NULL AND e.identity_id <> a.current_identity_id)`;\n// The current Identity is one an enrollment names, or the device's default local Identity.\nconst CURRENT_IS_DEVICES_SQL = `(a.current_identity_id = 'local:' || a.device_id\n OR EXISTS (SELECT 1 FROM enrolled_devices e WHERE e.device_id = a.device_id\n AND e.identity_id = a.current_identity_id))`;\nconst groupsWithoutAccessSql = (\n\ttarget: string,\n) => `SELECT coalesce(json_group_array(group_id), '[]') FROM (\n SELECT DISTINCT e.group_id FROM enrolled_devices e WHERE e.device_id = a.device_id\n AND NOT EXISTS (SELECT 1 FROM coordinator_identity_group_grants r WHERE r.coordinator_id = a.coordinator_id\n AND r.identity_id = ${target} AND r.group_id = e.group_id AND r.status = 'active' AND r.revoked_at IS NULL)\n ORDER BY e.group_id)`;\nconst GROUPS_WITHOUT_ACCESS_SQL = groupsWithoutAccessSql(\"?\");\n// The Team effects and enrollments shown in the browser are still the live ones.\nconst EFFECTS_CURRENT_SQL = `json((${groupsWithoutAccessSql(\"a.target_identity_id\")}))\n = json_extract(a.team_effects_json, '$.groupsWithoutAccess')\n AND (SELECT count(*) FROM enrolled_devices e WHERE e.device_id = a.device_id) = a.enrollment_count`;\n\ninterface Ctx<D extends DeviceRebindDeviceDependencies = DeviceRebindDependencies> {\n\tdeps: D;\n\tc: CoordinatorAuthBrowserConfig;\n\tscope: BrowserCsrfScope;\n}\n/** Device steps and their helpers run with either dependency set. */\ntype DeviceCtx = Ctx<DeviceRebindDeviceDependencies>;\n\nfunction live(ctx: DeviceCtx, time: number, attemptId: string) {\n\tconst { c, deps } = ctx;\n\treturn [c.coordinatorId, attemptId, deps.publicOrigin, c.issuer, c.revision, time, time];\n}\n\nfunction readAttempt(ctx: DeviceCtx, attemptId: string) {\n\treturn ctx.deps.backend.first<DeviceRebindAttempt>({\n\t\tsql: `SELECT * FROM ${ATTEMPT} WHERE coordinator_id = ? AND attempt_id = ?`,\n\t\tvalues: [ctx.c.coordinatorId, attemptId],\n\t});\n}\n\n/** Unexpected errors report an unknown outcome, never a failure. */\nfunction boundary<C extends DeviceCtx, A extends unknown[]>(\n\tctx: C,\n\tstep: (ctx: C, ...args: A) => Promise<DeviceRebindResult | null>,\n) {\n\treturn async (...args: A): Promise<DeviceRebindResult | null> => {\n\t\ttry {\n\t\t\treturn await step(ctx, ...args);\n\t\t} catch {\n\t\t\treturn { kind: \"unknown\" };\n\t\t}\n\t};\n}\n\n/**\n * The browser and device ceremony for ADR 0005 Section 8 rebinding. Every\n * step re-checks live authority in its winning statement; pre-reads only pick\n * the refusal reason shown to the person.\n */\nexport function createDeviceRebindCeremony(deps: DeviceRebindDependencies) {\n\tconst ctx = context(deps);\n\treturn Object.freeze({\n\t\t...deviceSteps(ctx),\n\t\tclaimBrowser: boundary(ctx, claimBrowser),\n\t\tverifyCallback: (request: Request) => verifyCallback(ctx, request),\n\t\tconfirm: boundary(ctx, confirm),\n\t});\n}\n\n/** The steps a signed device request drives: start, status, and finalize. */\nexport function createDeviceRebindDeviceSteps(deps: DeviceRebindDeviceDependencies) {\n\treturn Object.freeze(deviceSteps(context(deps)));\n}\n\nfunction context<D extends DeviceRebindDeviceDependencies>(deps: D): Ctx<D> {\n\tconst c = deps.config;\n\treturn { deps, c, scope: Object.freeze({ publicOrigin: deps.publicOrigin, store: c }) };\n}\n\nfunction deviceSteps(ctx: DeviceCtx) {\n\treturn {\n\t\tstart: boundary(ctx, start),\n\t\tfinalize: boundary(ctx, finalize),\n\t\tstatus: boundary(ctx, status),\n\t};\n}\n\nasync function startRefusal(\n\tctx: DeviceCtx,\n\tinput: DeviceRebindStart,\n\tkeyId: string,\n): Promise<DeviceRebindRefusal | null> {\n\tconst facts = await ctx.deps.backend.first<{\n\t\tbound: number;\n\t\tlinked: number;\n\t\tproof: number;\n\t\tenrolled: number;\n\t}>({\n\t\tsql: `SELECT\n EXISTS (SELECT 1 FROM coordinator_device_ownership_bindings WHERE device_id = ? OR key_id = ?) AS bound,\n EXISTS (SELECT 1 FROM coordinator_auth_account_links WHERE coordinator_id = ? AND identity_id = ?\n AND revoked_at_ms IS NULL) AS linked,\n NOT (${NO_OWN_PROOF_SQL}) AS proof,\n EXISTS (SELECT 1 FROM enrolled_devices e JOIN groups g ON g.group_id = e.group_id\n WHERE e.group_id = ? AND e.device_id = ? AND e.public_key = ? AND e.fingerprint = ? AND e.enabled = 1\n AND g.archived_at IS NULL) AS enrolled\n FROM (SELECT ? AS coordinator_id, ? AS current_identity_id, ? AS device_id, ? AS key_id,\n ? AS public_key, ? AS fingerprint) a`,\n\t\tvalues: [\n\t\t\tinput.signer.deviceId,\n\t\t\tkeyId,\n\t\t\tctx.c.coordinatorId,\n\t\t\tinput.currentIdentityId,\n\t\t\tinput.signer.groupId,\n\t\t\tinput.signer.deviceId,\n\t\t\tinput.signer.publicKey,\n\t\t\tinput.signer.fingerprint,\n\t\t\tctx.c.coordinatorId,\n\t\t\tinput.currentIdentityId,\n\t\t\tinput.signer.deviceId,\n\t\t\tkeyId,\n\t\t\tinput.signer.publicKey,\n\t\t\tinput.signer.fingerprint,\n\t\t],\n\t});\n\tif (facts?.enrolled !== 1) return \"unavailable\";\n\tif (facts.bound === 1) return \"device_already_bound\";\n\t// A linked current Identity still allows a self-bind for a device without its own proof.\n\tif (facts.linked === 1 && facts.proof === 1) return \"current_identity_linked\";\n\treturn null;\n}\n\nasync function start(ctx: DeviceCtx, input: DeviceRebindStart, clientKey: string) {\n\tconst limit = ctx.deps.limiter.check(\n\t\tJSON.stringify([\"device-rebind-start\", ctx.c.coordinatorId, clientKey]),\n\t\tSTART_CLIENT_LIMIT,\n\t);\n\tif (!limit.allowed) return refused(\"retry\");\n\tif (\n\t\t!isAuthControllerId(input.attemptId) ||\n\t\t!isAuthControllerId(input.currentIdentityId) ||\n\t\t!/^[0-9a-f]{64}$/.test(input.reviewDigest) ||\n\t\t!/^[0-9a-f]{64}$/.test(input.browserStartHash) ||\n\t\t!parseCoordinatorAuthLoopback(input.loopbackRedirect).ok\n\t)\n\t\treturn refused(\"unavailable\");\n\tconst startHash = input.browserStartHash;\n\tconst keyId = await ed25519KeyId(input.signer.publicKey);\n\tif (!keyId) return refused(\"unavailable\");\n\tconst reason = await startRefusal(ctx, input, keyId);\n\tif (reason) return refused(reason);\n\tconst time = ctx.deps.now();\n\tconst s = input.signer;\n\tconst wrote = await ctx.deps.backend.run({\n\t\tsql: `INSERT INTO ${ATTEMPT} (coordinator_id, attempt_id, origin, device_id, public_key, key_id,\n fingerprint, current_identity_id, issuer, auth_config_revision, loopback_redirect, browser_start_hash,\n review_digest, state, created_at_ms, expires_at_ms)\n SELECT a.* FROM (SELECT ? AS coordinator_id, ? AS attempt_id, ? AS origin, ? AS device_id,\n ? AS public_key, ? AS key_id, ? AS fingerprint, ? AS current_identity_id, ? AS issuer,\n ? AS auth_config_revision, ? AS loopback_redirect, ? AS browser_start_hash, ? AS review_digest,\n 'pending' AS state, ? AS created_at_ms, ? AS expires_at_ms) a\n WHERE EXISTS (SELECT 1 FROM enrolled_devices e JOIN groups g ON g.group_id = e.group_id\n WHERE e.group_id = ? AND e.device_id = a.device_id AND e.public_key = a.public_key\n AND e.fingerprint = a.fingerprint AND e.enabled = 1 AND g.archived_at IS NULL)\n AND ${ENROLLMENTS_CURRENT_SQL} AND ${CURRENT_IS_DEVICES_SQL}\n AND ${UNBOUND_SQL} AND ${UNREVOKED_SQL} AND (${CURRENT_UNLINKED_SQL} OR ${NO_OWN_PROOF_SQL})\n AND NOT EXISTS (SELECT 1 FROM coordinator_owner_enrollment_attempts o\n WHERE o.coordinator_id = a.coordinator_id AND o.attempt_id = a.attempt_id)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_link_attempts o\n WHERE o.coordinator_id = a.coordinator_id AND o.attempt_id = a.attempt_id)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_browser_transactions o\n WHERE o.coordinator_id = a.coordinator_id AND o.attempt_id = a.attempt_id)\n AND (SELECT count(*) FROM ${ATTEMPT} o WHERE o.coordinator_id = a.coordinator_id AND o.device_id = a.device_id\n AND o.state IN ('pending', 'browser_claimed', 'oidc_verified', 'confirmed') AND o.expires_at_ms > ?) < ?\n AND (SELECT count(*) FROM ${ATTEMPT} o WHERE o.coordinator_id = a.coordinator_id AND o.device_id = a.device_id\n AND o.created_at_ms > ?) < ?`,\n\t\tvalues: [\n\t\t\tctx.c.coordinatorId,\n\t\t\tinput.attemptId,\n\t\t\tctx.deps.publicOrigin,\n\t\t\ts.deviceId,\n\t\t\ts.publicKey,\n\t\t\tkeyId,\n\t\t\ts.fingerprint,\n\t\t\tinput.currentIdentityId,\n\t\t\tctx.c.issuer,\n\t\t\tctx.c.revision,\n\t\t\tinput.loopbackRedirect,\n\t\t\tstartHash,\n\t\t\tinput.reviewDigest,\n\t\t\ttime,\n\t\t\ttime + TTL_MS,\n\t\t\ts.groupId,\n\t\t\ttime,\n\t\t\tAUTH_LINK_MAX_ACTIVE_PER_DEVICE,\n\t\t\ttime - AUTH_LINK_CREATE_WINDOW_MS,\n\t\t\tAUTH_LINK_MAX_CREATES_PER_DEVICE_WINDOW,\n\t\t],\n\t});\n\tif (wrote !== 1) return refused(\"unavailable\");\n\treturn { kind: \"started\" as const, attemptId: input.attemptId, expiresAtMs: time + TTL_MS };\n}\n\nasync function claimBrowser(ctx: Ctx, request: Request, clientKey: string) {\n\tconst snapshot = snapshotBrowserRequest(request);\n\tconst transaction = await readBrowserStartTransaction(\n\t\tsnapshot.cookie,\n\t\tnew CoordinatorAuthBrowserTransactions(ctx.deps.backend, ctx.deps.now),\n\t\tctx.c,\n\t);\n\tif (transaction === \"active\" || transaction === \"invalid\") return refused(\"unavailable\");\n\tconst checked = await guardBrowserForm({\n\t\trequest,\n\t\tclientKey,\n\t\taction: \"link_start\",\n\t\tscope: ctx.scope,\n\t\tcsrfKey: ctx.deps.csrfKey,\n\t\tlimiter: ctx.deps.limiter,\n\t});\n\tif (!checked.ok || checked.action !== \"link_start\") return refused(\"unavailable\");\n\tconst cookie = await readBrowserCookie(snapshot.cookie, \"start\");\n\tif (cookie.kind !== \"present\" || cookie.cookieHash !== checked.cookieHash)\n\t\treturn refused(\"unavailable\");\n\tconst row = await readAttempt(ctx, checked.attemptId);\n\tif (\n\t\trow?.state !== \"pending\" ||\n\t\trow.expires_at_ms <= ctx.deps.now() ||\n\t\trow.browser_start_hash !== (await proofHash(checked.startCode))\n\t)\n\t\treturn refused(\"unavailable\");\n\tconst authorization = await ctx.deps.client.createAuthorizationRequest();\n\tconst url = new URL(authorization.authorizationUrl);\n\turl.searchParams.set(\"prompt\", \"select_account\");\n\tconst time = ctx.deps.now();\n\tconst transactionHash = await hashCoordinatorAuthProofBytes32(\n\t\tglobalThis.crypto.getRandomValues(new Uint8Array(32)),\n\t);\n\tconst stateHash = await sha256Hex(authorization.material.state);\n\tawait ctx.deps.backend.batch(\n\t\tclaimStatements(ctx, row, authorization.material, {\n\t\t\ttime,\n\t\t\ttransactionHash,\n\t\t\tstateHash,\n\t\t\tbinderHash: checked.cookieHash,\n\t\t}),\n\t);\n\tconst claimed = await readAttempt(ctx, row.attempt_id);\n\tif (claimed?.state !== \"browser_claimed\" || claimed.browser_transaction_hash !== transactionHash)\n\t\tthrow new Error(\"device_rebind_claim_unconfirmed\");\n\treturn {\n\t\tkind: \"browser_claimed\" as const,\n\t\tauthorizationUrl: url.href,\n\t\tsetCookies: [reissueStartCookieAsTransaction(cookie.secret), clearBrowserCookie(\"start\")],\n\t};\n}\n\n/** Browser transaction insert and attempt claim; each asserts it changed exactly one row. */\nfunction claimStatements(\n\tctx: Ctx,\n\trow: DeviceRebindAttempt,\n\tmaterial: { nonce: string; pkceVerifier: string },\n\tp: { time: number; transactionHash: string; stateHash: string; binderHash: string },\n): AuthLinkStatement[] {\n\tconst pending = `${LIVE_SQL} AND a.state = 'pending' AND a.browser_start_hash = ?\n AND a.browser_transaction_hash IS NULL AND a.browser_binder_hash IS NULL`;\n\tconst pendingValues = [...live(ctx, p.time, row.attempt_id), row.browser_start_hash];\n\t// A standalone INSERT fails the batch when the previous write changed nothing.\n\tconst assertOne = {\n\t\tsql: \"INSERT INTO coordinator_auth_browser_transactions (purpose) SELECT 'owner_enroll' WHERE changes() <> 1\",\n\t\tvalues: [],\n\t};\n\treturn [\n\t\t{\n\t\t\tsql: `INSERT INTO coordinator_auth_browser_transactions (coordinator_id, browser_transaction_hash,\n purpose, attempt_id, state_hash, binder_hash, issuer, auth_config_revision, redirect_uri, state, nonce,\n pkce_verifier, created_at_ms, expires_at_ms)\n SELECT a.coordinator_id, ?, 'owner_enroll', a.attempt_id, ?, ?, a.issuer, a.auth_config_revision, ?,\n 'pending', ?, ?, ?, a.expires_at_ms FROM ${ATTEMPT} a WHERE ${pending}`,\n\t\t\tvalues: [\n\t\t\t\tp.transactionHash,\n\t\t\t\tp.stateHash,\n\t\t\t\tp.binderHash,\n\t\t\t\tctx.c.redirectUri,\n\t\t\t\tmaterial.nonce,\n\t\t\t\tmaterial.pkceVerifier,\n\t\t\t\tp.time,\n\t\t\t\t...pendingValues,\n\t\t\t],\n\t\t},\n\t\tassertOne,\n\t\t{\n\t\t\tsql: `UPDATE ${ATTEMPT} AS a SET state = 'browser_claimed', browser_transaction_hash = ?,\n browser_binder_hash = ? WHERE ${pending}`,\n\t\t\tvalues: [p.transactionHash, p.binderHash, ...pendingValues],\n\t\t},\n\t\tassertOne,\n\t];\n}\n\n/** The single OIDC state of a well-formed callback to the configured URL, checked before any burn. */\nfunction callbackState(\n\tctx: Ctx,\n\tsnapshot: ReturnType<typeof snapshotBrowserRequest>,\n): string | null {\n\tif (snapshot.method !== \"GET\" || snapshot.url.length > 8192 || snapshot.url.includes(\"#\"))\n\t\treturn null;\n\tconst url = new URL(snapshot.url);\n\tconst redirect = new URL(ctx.c.redirectUri);\n\tif (\n\t\turl.origin !== redirect.origin ||\n\t\turl.pathname !== redirect.pathname ||\n\t\turl.username ||\n\t\turl.password\n\t)\n\t\treturn null;\n\tconst states = url.searchParams.getAll(\"state\");\n\tif (states.length !== 1 || !/^[A-Za-z0-9._~-]{43,128}$/.test(states[0] ?? \"\")) return null;\n\treturn states[0] ?? null;\n}\n\n/**\n * Returns null when the callback belongs to another ceremony; the shared OIDC\n * callback then offers it to the next handler. Only this step may fall\n * through: rebind start and confirm forms have their own URLs. Until the\n * transaction is burned, any error also means \"not mine\", so a storage fault\n * never takes another ceremony's callback; after the burn it is unknown.\n */\nasync function verifyCallback(ctx: Ctx, request: Request): Promise<DeviceRebindResult | null> {\n\tlet match: Awaited<ReturnType<typeof matchCallback>>;\n\ttry {\n\t\tmatch = await matchCallback(ctx, request);\n\t} catch {\n\t\treturn null;\n\t}\n\tif (!match) return null;\n\ttry {\n\t\treturn await verifyMatched(ctx, match);\n\t} catch {\n\t\treturn { kind: \"unknown\" };\n\t}\n}\n\nasync function matchCallback(ctx: Ctx, request: Request) {\n\tconst snapshot = snapshotBrowserRequest(request);\n\tconst state = callbackState(ctx, snapshot);\n\tif (!state) return null;\n\tconst cookie = await readBrowserCookie(snapshot.cookie, \"transaction\");\n\tif (cookie.kind !== \"present\") return null;\n\tconst time = ctx.deps.now();\n\tconst txn = await ctx.deps.backend.first<{\n\t\tbrowser_transaction_hash: string;\n\t\tattempt_id: string;\n\t\tnonce: string;\n\t\tpkce_verifier: string;\n\t}>({\n\t\tsql: `SELECT b.* FROM coordinator_auth_browser_transactions b JOIN ${ATTEMPT} a\n ON a.coordinator_id = b.coordinator_id AND a.attempt_id = b.attempt_id\n AND a.browser_transaction_hash = b.browser_transaction_hash AND a.browser_binder_hash = b.binder_hash\n WHERE b.coordinator_id = ? AND b.purpose = 'owner_enroll' AND b.state_hash = ? AND b.binder_hash = ?\n AND b.state = 'pending' AND b.issuer = ? AND b.auth_config_revision = ? AND b.redirect_uri = ?\n AND b.created_at_ms <= ? AND b.expires_at_ms > ? AND a.state = 'browser_claimed'`,\n\t\tvalues: [\n\t\t\tctx.c.coordinatorId,\n\t\t\tawait sha256Hex(state),\n\t\t\tcookie.cookieHash,\n\t\t\tctx.c.issuer,\n\t\t\tctx.c.revision,\n\t\t\tctx.c.redirectUri,\n\t\t\ttime,\n\t\t\ttime,\n\t\t],\n\t});\n\treturn txn ? { snapshot, state, cookie, txn, time } : null;\n}\n\nasync function verifyMatched(\n\tctx: Ctx,\n\t{ snapshot, state, cookie, txn, time }: NonNullable<Awaited<ReturnType<typeof matchCallback>>>,\n): Promise<DeviceRebindResult> {\n\t// Burn the transaction before provider verification, as every other ceremony does.\n\tconst claimToken = globalThis.crypto.randomUUID();\n\tconst burned = await ctx.deps.backend.run({\n\t\tsql: `UPDATE coordinator_auth_browser_transactions SET state = 'consumed', consumed_at_ms = ?,\n claim_token = ?, nonce = NULL, pkce_verifier = NULL\n WHERE coordinator_id = ? AND browser_transaction_hash = ? AND state = 'pending'`,\n\t\tvalues: [time, claimToken, ctx.c.coordinatorId, txn.browser_transaction_hash],\n\t});\n\tif (burned !== 1) return refused(\"unavailable\");\n\tconst verified = await ctx.deps.client.verifyCallback(\n\t\t{\n\t\t\tcallbackUrl: snapshot.url,\n\t\t\tmaterial: { state, nonce: txn.nonce, pkceVerifier: txn.pkce_verifier },\n\t\t},\n\t\t{ fetchUserInfo: false },\n\t);\n\t// This request burned the transaction, so a refusal from here on retires it.\n\tif (!verified.ok || verified.account.issuer !== ctx.c.issuer)\n\t\treturn retiredRefusal(ctx, txn.attempt_id, \"unavailable\");\n\tconst outcome = await persistVerified(ctx, txn.attempt_id, verified.account, claimToken);\n\tif (outcome.kind === \"refused\") return retiredRefusal(ctx, txn.attempt_id, outcome.reason);\n\tif (outcome.kind !== \"verified\") return outcome;\n\tconst csrf = await issueBrowserCsrfToken(\n\t\tctx.deps.csrfKey,\n\t\tcookie.secret,\n\t\t\"transaction\",\n\t\tctx.scope,\n\t);\n\treturn { kind: \"verified\" as const, confirmation: outcome.confirmation, csrf };\n}\n\n/** The attempt can't continue; the browser hands the reason back to the waiting device. */\nasync function retiredRefusal(\n\tctx: Ctx,\n\tattemptId: string,\n\treason: DeviceRebindRefusal,\n): Promise<DeviceRebindResult> {\n\tconst row = await readAttempt(ctx, attemptId);\n\tconst returnTo = row?.loopback_redirect\n\t\t? { loopbackRedirect: row.loopback_redirect, attemptId: row.attempt_id }\n\t\t: undefined;\n\treturn { kind: \"refused\", reason, retired: true, ...(returnTo ? { returnTo } : {}) };\n}\n\nasync function persistVerified(\n\tctx: Ctx,\n\tattemptId: string,\n\taccount: { issuer: string; subject: string },\n\tclaimToken: string,\n): Promise<DeviceRebindResult> {\n\tconst row = await readAttempt(ctx, attemptId);\n\tconst link = await ctx.deps.backend.first<{\n\t\tlink_id: string;\n\t\tidentity_id: string;\n\t\tauthority_kind: \"controller_attestation\" | \"device_claim\";\n\t}>({\n\t\tsql: `SELECT link_id, identity_id, authority_kind FROM coordinator_auth_account_links\n WHERE coordinator_id = ? AND issuer = ? AND subject = ? AND revoked_at_ms IS NULL`,\n\t\tvalues: [ctx.c.coordinatorId, account.issuer, account.subject],\n\t});\n\tif (!row) return refused(\"unavailable\");\n\tif (!link) return refused(\"account_not_linked\");\n\tconst time = ctx.deps.now();\n\tconst wrote = await ctx.deps.backend.run({\n\t\tsql: `UPDATE ${ATTEMPT} AS a SET state = 'oidc_verified', account_subject = ?, target_identity_id = ?,\n link_id = ?, link_authority_kind = ?,\n enrollment_count = (SELECT count(*) FROM enrolled_devices e WHERE e.device_id = a.device_id),\n team_effects_json = json_object('groupsWithoutAccess', json((${GROUPS_WITHOUT_ACCESS_SQL})))\n WHERE ${LIVE_SQL} AND a.state = 'browser_claimed' AND ${ENROLLMENTS_CURRENT_SQL}\n AND (SELECT count(*) FROM enrolled_devices e WHERE e.device_id = a.device_id) BETWEEN 1 AND 50\n AND EXISTS (SELECT 1 FROM coordinator_auth_account_links l WHERE l.coordinator_id = a.coordinator_id\n AND l.link_id = ? AND l.identity_id = ? AND l.issuer = a.issuer AND l.subject = ? AND l.revoked_at_ms IS NULL)\n AND EXISTS (SELECT 1 FROM coordinator_auth_browser_transactions b WHERE b.coordinator_id = a.coordinator_id\n AND b.browser_transaction_hash = a.browser_transaction_hash AND b.state = 'consumed' AND b.claim_token = ?)\n AND (? = a.current_identity_id OR ${CURRENT_UNLINKED_SQL})`,\n\t\tvalues: [\n\t\t\taccount.subject,\n\t\t\tlink.identity_id,\n\t\t\tlink.link_id,\n\t\t\tlink.authority_kind,\n\t\t\tlink.identity_id,\n\t\t\t...live(ctx, time, attemptId),\n\t\t\tlink.link_id,\n\t\t\tlink.identity_id,\n\t\t\taccount.subject,\n\t\t\tclaimToken,\n\t\t\t// A switch needs an unlinked current Identity; a self-bind's no-own-proof rule is in LIVE_SQL.\n\t\t\tlink.identity_id,\n\t\t],\n\t});\n\tif (wrote !== 1) return refused(await currentRefusal(ctx, row, link.identity_id));\n\tconst verified = await readAttempt(ctx, attemptId);\n\tif (verified?.state !== \"oidc_verified\" || verified.link_id !== link.link_id)\n\t\tthrow new Error(\"device_rebind_verify_unconfirmed\");\n\treturn { kind: \"verified\", confirmation: await confirmationView(verified), csrf: \"\" };\n}\n\n/** Explains why a guarded write matched nothing; never authorizes anything. */\nasync function currentRefusal(\n\tctx: DeviceCtx,\n\trow: DeviceRebindAttempt,\n\ttarget: string | null = row.target_identity_id,\n): Promise<DeviceRebindRefusal> {\n\tconst facts = await ctx.deps.backend.first<{ bound: number; linked: number; proof: number }>({\n\t\tsql: `SELECT\n EXISTS (SELECT 1 FROM coordinator_device_ownership_bindings WHERE device_id = a.device_id\n OR key_id = a.key_id) AS bound,\n EXISTS (SELECT 1 FROM coordinator_auth_account_links WHERE coordinator_id = a.coordinator_id\n AND identity_id = a.current_identity_id AND revoked_at_ms IS NULL) AS linked,\n NOT (${NO_OWN_PROOF_SQL}) AS proof\n FROM ${ATTEMPT} a WHERE a.coordinator_id = ? AND a.attempt_id = ?`,\n\t\tvalues: [ctx.c.coordinatorId, row.attempt_id],\n\t});\n\tif (facts?.bound === 1) return \"device_already_bound\";\n\t// A self-bind is only for a device without its own proof; switching needs an unlinked Identity.\n\tif (target === row.current_identity_id)\n\t\treturn facts?.proof === 1 ? \"already_this_identity\" : \"unavailable\";\n\tif (facts?.linked === 1) return \"current_identity_linked\";\n\treturn \"unavailable\";\n}\n\nasync function confirmationView(row: DeviceRebindAttempt): Promise<DeviceRebindConfirmation> {\n\tconst effects = JSON.parse(row.team_effects_json ?? \"null\") as {\n\t\tgroupsWithoutAccess?: unknown;\n\t};\n\tconst groups = Array.isArray(effects?.groupsWithoutAccess) ? effects.groupsWithoutAccess : null;\n\tif (!groups?.every((group) => typeof group === \"string\") || !row.account_subject)\n\t\tthrow new Error(\"device_rebind_confirmation_invalid\");\n\treturn Object.freeze({\n\t\tattemptId: row.attempt_id,\n\t\tdeviceId: row.device_id,\n\t\tfingerprint: row.fingerprint,\n\t\tissuer: row.issuer,\n\t\tsubject: row.account_subject,\n\t\tcurrentIdentityId: row.current_identity_id,\n\t\ttargetIdentityId: row.target_identity_id as string,\n\t\tgroupsWithoutAccess: Object.freeze([...groups]),\n\t\t// confirm(ctx, ) persists this exact commitment with the completion-secret hash.\n\t\tconfirmationHash: await deviceRebindConfirmationHash(row),\n\t});\n}\n\nasync function confirm(ctx: Ctx, request: Request, clientKey: string, commitment: string) {\n\tconst snapshot = snapshotBrowserRequest(request);\n\tconst checked = await guardBrowserForm({\n\t\trequest,\n\t\tclientKey,\n\t\taction: \"transaction_attempt\",\n\t\tscope: ctx.scope,\n\t\tcsrfKey: ctx.deps.csrfKey,\n\t\tlimiter: ctx.deps.limiter,\n\t});\n\tif (!checked.ok || checked.action !== \"transaction_attempt\") return refused(\"unavailable\");\n\tconst cookie = await readBrowserCookie(snapshot.cookie, \"transaction\");\n\tif (cookie.kind !== \"present\" || cookie.cookieHash !== checked.cookieHash)\n\t\treturn refused(\"unavailable\");\n\tconst row = await readAttempt(ctx, checked.attemptId);\n\tif (row?.state !== \"oidc_verified\" || row.browser_binder_hash !== cookie.cookieHash)\n\t\treturn refused(\"unavailable\");\n\tconst view = await confirmationView(row);\n\tif (commitment !== view.confirmationHash || !row.loopback_redirect) return refused(\"unavailable\");\n\tconst completionSecret = mintCompletionSecret();\n\tconst time = ctx.deps.now();\n\tconst wrote = await ctx.deps.backend.run({\n\t\tsql: `UPDATE ${ATTEMPT} AS a SET state = 'confirmed', confirmation_hash = ?, completion_secret_hash = ?\n WHERE ${LIVE_SQL} AND a.state = 'oidc_verified' AND a.browser_binder_hash = ?\n AND a.account_subject = ? AND a.target_identity_id = ? AND a.link_id = ? AND a.team_effects_json = ?\n AND a.enrollment_count = ? AND ${TARGET_LINK_SQL} AND ${ENROLLMENTS_CURRENT_SQL}\n AND ${EFFECTS_CURRENT_SQL}\n AND EXISTS (SELECT 1 FROM coordinator_auth_browser_transactions b WHERE b.coordinator_id = a.coordinator_id\n AND b.browser_transaction_hash = a.browser_transaction_hash AND b.state = 'consumed')`,\n\t\tvalues: [\n\t\t\tview.confirmationHash,\n\t\t\tawait proofHash(completionSecret),\n\t\t\t...live(ctx, time, row.attempt_id),\n\t\t\tcookie.cookieHash,\n\t\t\trow.account_subject,\n\t\t\trow.target_identity_id,\n\t\t\trow.link_id,\n\t\t\trow.team_effects_json,\n\t\t\trow.enrollment_count,\n\t\t],\n\t});\n\tif (wrote !== 1) return refused(await currentRefusal(ctx, row));\n\treturn {\n\t\tkind: \"confirmed\" as const,\n\t\tcompletionSecret,\n\t\tloopbackRedirect: row.loopback_redirect,\n\t};\n}\n\nasync function finalize(\n\tctx: DeviceCtx,\n\tinput: {\n\t\tattemptId: string;\n\t\tsigner: DeviceRebindSigner;\n\t\tcompletionSecret: string;\n\t\tsignature: string;\n\t},\n): Promise<DeviceRebindResult> {\n\tconst row = await readAttempt(ctx, input.attemptId);\n\tif (!row || !sameDevice(row, input.signer)) return refused(\"unavailable\");\n\tconst result = await commitDeviceRebind({\n\t\tbackend: ctx.deps.backend,\n\t\tcoordinatorId: ctx.c.coordinatorId,\n\t\tattemptId: input.attemptId,\n\t\trevision: ctx.c.revision,\n\t\tnow: ctx.deps.now(),\n\t\tcompletionSecret: input.completionSecret,\n\t\tsignature: input.signature,\n\t});\n\tif (result.kind === \"committed\") return { kind: \"finalized\", receipt: result.receipt };\n\tif (result.kind === \"prior_commit\") return { kind: \"prior_commit\", receipt: result.receipt };\n\treturn refused(await finalizeRefusal(ctx, input, row));\n}\n\n/**\n * A refused commit is retryable only when its proofs are valid, the attempt is\n * still confirmed, and the target has not reached its daily limit: then a\n * concurrent enrollment change elsewhere made the pinned scan refuse.\n */\nasync function finalizeRefusal(\n\tctx: DeviceCtx,\n\tinput: { attemptId: string; completionSecret: string; signature: string },\n\trow: DeviceRebindAttempt,\n): Promise<DeviceRebindRefusal> {\n\tconst after = await readAttempt(ctx, input.attemptId);\n\tconst now = ctx.deps.now();\n\tif (after?.state !== \"confirmed\" || after.expires_at_ms <= now) return currentRefusal(ctx, row);\n\tconst proof = await verifyDeviceRebindCompletion(after, {\n\t\trevision: ctx.c.revision,\n\t\tnow,\n\t\tcompletionSecret: input.completionSecret,\n\t\tsignature: input.signature,\n\t});\n\tif (!proof) return \"unavailable\";\n\tconst recent = await ctx.deps.backend.first<{ n: number }>({\n\t\tsql: `SELECT count(*) AS n FROM coordinator_device_rebind_audit_log\n WHERE coordinator_id = ? AND target_identity_id = ? AND created_at_ms > ?`,\n\t\tvalues: [ctx.c.coordinatorId, after.target_identity_id, now - 86_400_000],\n\t});\n\tif ((recent?.n ?? 0) >= DEVICE_REBIND_DAILY_LIMIT) return \"daily_limit\";\n\tconst reason = await currentRefusal(ctx, row);\n\tif (reason !== \"unavailable\") return reason;\n\treturn pinnedFactsHold(ctx, after);\n}\n\n/** The attempt pins its link and enrollments; once those change, retrying cannot succeed. */\nasync function pinnedFactsHold(\n\tctx: DeviceCtx,\n\ta: DeviceRebindAttempt,\n): Promise<DeviceRebindRefusal> {\n\tconst facts = await ctx.deps.backend.first<{ linked: number; enrollments: number }>({\n\t\tsql: `SELECT ${TARGET_LINK_SQL} AS linked,\n ((SELECT count(*) FROM enrolled_devices e WHERE e.device_id = a.device_id) = a.enrollment_count\n AND ${ENROLLMENTS_CURRENT_SQL}) AS enrollments\n FROM ${ATTEMPT} a WHERE a.coordinator_id = ? AND a.attempt_id = ?`,\n\t\tvalues: [ctx.c.coordinatorId, a.attempt_id],\n\t});\n\tif (facts?.linked !== 1) return \"account_not_linked\";\n\tif (facts.enrollments !== 1) return \"unavailable\";\n\treturn \"retry\";\n}\n\n/** Signed read by the attempt's own device; resolves unknown outcomes without writing. */\nasync function status(ctx: DeviceCtx, input: { attemptId: string; signer: DeviceRebindSigner }) {\n\tconst row = await readAttempt(ctx, input.attemptId);\n\tif (!row || !sameDevice(row, input.signer)) return refused(\"unavailable\");\n\treturn {\n\t\tkind: \"status\" as const,\n\t\tstate: row.state,\n\t\texpiresAtMs: row.expires_at_ms,\n\t\ttargetIdentityId: [\"confirmed\", \"finalized\"].includes(row.state)\n\t\t\t? row.target_identity_id\n\t\t\t: null,\n\t\treceipt:\n\t\t\trow.state === \"finalized\"\n\t\t\t\t? await readDeviceRebindReceipt(ctx.deps.backend, ctx.c.coordinatorId, row.attempt_id)\n\t\t\t\t: null,\n\t};\n}\n\nfunction sameDevice(row: DeviceRebindAttempt, signer: DeviceRebindSigner): boolean {\n\treturn (\n\t\trow.device_id === signer.deviceId &&\n\t\trow.public_key === signer.publicKey &&\n\t\trow.fingerprint === signer.fingerprint\n\t);\n}\n","// generate timestamp or delta\n// see http://nodejs.org/api/process.html#process_process_hrtime\nfunction hrtime(previousTimestamp) {\n const clocktime = performance.now() * 1e-3;\n let seconds = Math.floor(clocktime);\n let nanoseconds = Math.floor((clocktime % 1) * 1e9);\n if (previousTimestamp != undefined) {\n seconds = seconds - previousTimestamp[0];\n nanoseconds = nanoseconds - previousTimestamp[1];\n if (nanoseconds < 0) {\n seconds--;\n nanoseconds += 1e9;\n }\n }\n return [seconds, nanoseconds];\n}\n// The current timestamp in whole milliseconds\nexport function getMilliseconds() {\n const [seconds, nanoseconds] = hrtime();\n return seconds * 1e3 + Math.floor(nanoseconds / 1e6);\n}\n// Wait for a specified number of milliseconds before fulfilling the returned promise.\nexport function wait(ms) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n//# sourceMappingURL=clock.js.map","import { getMilliseconds, wait } from \"./clock.js\";\n/**\n * A hierarchical token bucket for rate limiting. See\n * http://en.wikipedia.org/wiki/Token_bucket for more information.\n *\n * @param options\n * @param options.bucketSize Maximum number of tokens to hold in the bucket.\n * Also known as the burst rate.\n * @param options.tokensPerInterval Number of tokens to drip into the bucket\n * over the course of one interval.\n * @param options.interval The interval length in milliseconds, or as\n * one of the following strings: 'second', 'minute', 'hour', day'.\n * @param options.parentBucket Optional. A token bucket that will act as\n * the parent of this bucket.\n */\nexport class TokenBucket {\n bucketSize;\n tokensPerInterval;\n interval;\n parentBucket;\n content;\n lastDrip;\n constructor({ bucketSize, tokensPerInterval, interval, parentBucket }) {\n this.bucketSize = bucketSize;\n this.tokensPerInterval = tokensPerInterval;\n if (typeof interval === \"string\") {\n switch (interval) {\n case \"sec\":\n case \"second\":\n this.interval = 1000;\n break;\n case \"min\":\n case \"minute\":\n this.interval = 1000 * 60;\n break;\n case \"hr\":\n case \"hour\":\n this.interval = 1000 * 60 * 60;\n break;\n case \"day\":\n this.interval = 1000 * 60 * 60 * 24;\n break;\n default:\n throw new Error(\"Invalid interval \" + interval);\n }\n }\n else {\n this.interval = interval;\n }\n this.parentBucket = parentBucket;\n this.content = 0;\n this.lastDrip = getMilliseconds();\n }\n /**\n * Remove the requested number of tokens. If the bucket (and any parent\n * buckets) contains enough tokens this will happen immediately. Otherwise,\n * the removal will happen when enough tokens become available.\n * @param count The number of tokens to remove.\n * @returns A promise for the remainingTokens count.\n */\n async removeTokens(count) {\n // Is this an infinite size bucket?\n if (this.bucketSize === 0) {\n return Number.POSITIVE_INFINITY;\n }\n // Make sure the bucket can hold the requested number of tokens\n if (count > this.bucketSize) {\n throw new Error(`Requested tokens ${count} exceeds bucket size ${this.bucketSize}`);\n }\n // Drip new tokens into this bucket\n this.drip();\n const comeBackLater = async () => {\n // How long do we need to wait to make up the difference in tokens?\n const waitMs = Math.ceil((count - this.content) * (this.interval / this.tokensPerInterval));\n await wait(waitMs);\n return this.removeTokens(count);\n };\n // If we don't have enough tokens in this bucket, come back later\n if (count > this.content)\n return comeBackLater();\n if (this.parentBucket != undefined) {\n // Remove the requested from the parent bucket first\n const remainingTokens = await this.parentBucket.removeTokens(count);\n // Check that we still have enough tokens in this bucket\n if (count > this.content)\n return comeBackLater();\n // Tokens were removed from the parent bucket, now remove them from\n // this bucket. Note that we look at the current bucket and parent\n // bucket's remaining tokens and return the smaller of the two values\n this.content -= count;\n return Math.min(remainingTokens, this.content);\n }\n else {\n // Remove the requested tokens from this bucket\n this.content -= count;\n return this.content;\n }\n }\n /**\n * Attempt to remove the requested number of tokens and return immediately.\n * If the bucket (and any parent buckets) contains enough tokens this will\n * return true, otherwise false is returned.\n * @param {Number} count The number of tokens to remove.\n * @param {Boolean} True if the tokens were successfully removed, otherwise\n * false.\n */\n tryRemoveTokens(count) {\n // Is this an infinite size bucket?\n if (!this.bucketSize)\n return true;\n // Make sure the bucket can hold the requested number of tokens\n if (count > this.bucketSize)\n return false;\n // Drip new tokens into this bucket\n this.drip();\n // If we don't have enough tokens in this bucket, return false\n if (count > this.content)\n return false;\n // Try to remove the requested tokens from the parent bucket\n if (this.parentBucket && !this.parentBucket.tryRemoveTokens(count))\n return false;\n // Remove the requested tokens from this bucket and return\n this.content -= count;\n return true;\n }\n /**\n * Add any new tokens to the bucket since the last drip.\n * @returns {Boolean} True if new tokens were added, otherwise false.\n */\n drip() {\n if (this.tokensPerInterval === 0) {\n const prevContent = this.content;\n this.content = this.bucketSize;\n return this.content > prevContent;\n }\n const now = getMilliseconds();\n const deltaMS = Math.max(now - this.lastDrip, 0);\n this.lastDrip = now;\n const dripAmount = deltaMS * (this.tokensPerInterval / this.interval);\n const prevContent = this.content;\n this.content = Math.min(this.content + dripAmount, this.bucketSize);\n return Math.floor(this.content) > Math.floor(prevContent);\n }\n}\n//# sourceMappingURL=TokenBucket.js.map","import { TokenBucket } from \"./TokenBucket.js\";\nimport { getMilliseconds, wait } from \"./clock.js\";\n/**\n * A generic rate limiter. Underneath the hood, this uses a token bucket plus\n * an additional check to limit how many tokens we can remove each interval.\n *\n * @param options\n * @param options.tokensPerInterval Maximum number of tokens that can be\n * removed at any given moment and over the course of one interval.\n * @param options.interval The interval length in milliseconds, or as\n * one of the following strings: 'second', 'minute', 'hour', day'.\n * @param options.fireImmediately Whether or not the promise will resolve\n * immediately when rate limiting is in effect (default is false).\n */\nexport class RateLimiter {\n tokenBucket;\n curIntervalStart;\n tokensThisInterval;\n fireImmediately;\n constructor({ tokensPerInterval, interval, fireImmediately }) {\n this.tokenBucket = new TokenBucket({\n bucketSize: tokensPerInterval,\n tokensPerInterval,\n interval,\n });\n // Fill the token bucket to start\n this.tokenBucket.content = tokensPerInterval;\n this.curIntervalStart = getMilliseconds();\n this.tokensThisInterval = 0;\n this.fireImmediately = fireImmediately ?? false;\n }\n /**\n * Remove the requested number of tokens. If the rate limiter contains enough\n * tokens and we haven't spent too many tokens in this interval already, this\n * will happen immediately. Otherwise, the removal will happen when enough\n * tokens become available.\n * @param count The number of tokens to remove.\n * @returns A promise for the remainingTokens count.\n */\n async removeTokens(count) {\n // Make sure the request isn't for more than we can handle\n if (count > this.tokenBucket.bucketSize) {\n throw new Error(`Requested tokens ${count} exceeds maximum tokens per interval ${this.tokenBucket.bucketSize}`);\n }\n const now = getMilliseconds();\n // Advance the current interval and reset the current interval token count\n // if needed\n if (now < this.curIntervalStart || now - this.curIntervalStart >= this.tokenBucket.interval) {\n this.curIntervalStart = now;\n this.tokensThisInterval = 0;\n }\n // If we don't have enough tokens left in this interval, wait until the\n // next interval\n if (count > this.tokenBucket.tokensPerInterval - this.tokensThisInterval) {\n if (this.fireImmediately) {\n return -1;\n }\n else {\n const waitMs = Math.ceil(this.curIntervalStart + this.tokenBucket.interval - now);\n await wait(waitMs);\n const remainingTokens = await this.tokenBucket.removeTokens(count);\n this.tokensThisInterval += count;\n return remainingTokens;\n }\n }\n // Remove the requested number of tokens from the token bucket\n const remainingTokens = await this.tokenBucket.removeTokens(count);\n this.tokensThisInterval += count;\n return remainingTokens;\n }\n /**\n * Attempt to remove the requested number of tokens and return immediately.\n * If the bucket (and any parent buckets) contains enough tokens and we\n * haven't spent too many tokens in this interval already, this will return\n * true. Otherwise, false is returned.\n * @param {Number} count The number of tokens to remove.\n * @param {Boolean} True if the tokens were successfully removed, otherwise\n * false.\n */\n tryRemoveTokens(count) {\n // Make sure the request isn't for more than we can handle\n if (count > this.tokenBucket.bucketSize)\n return false;\n const now = getMilliseconds();\n // Advance the current interval and reset the current interval token count\n // if needed\n if (now < this.curIntervalStart || now - this.curIntervalStart >= this.tokenBucket.interval) {\n this.curIntervalStart = now;\n this.tokensThisInterval = 0;\n }\n // If we don't have enough tokens left in this interval, return false\n if (count > this.tokenBucket.tokensPerInterval - this.tokensThisInterval)\n return false;\n // Try to remove the requested number of tokens from the token bucket\n const removed = this.tokenBucket.tryRemoveTokens(count);\n if (removed) {\n this.tokensThisInterval += count;\n }\n return removed;\n }\n /**\n * Returns the number of tokens remaining in the TokenBucket.\n * @returns {Number} The number of tokens remaining.\n */\n getTokensRemaining() {\n this.tokenBucket.drip();\n return this.tokenBucket.content;\n }\n}\n//# sourceMappingURL=RateLimiter.js.map","import { RateLimiter } from \"limiter\";\n\nexport interface InMemoryRequestRateLimiter {\n\tcheck(key: string, limit: number): { allowed: boolean; retryAfterS: number };\n}\n\nexport interface CreateInMemoryRequestRateLimiterOptions {\n\twindowMs?: number;\n\tnow?: () => number;\n}\n\n/**\n * Best-effort, per-isolate request rate limiter.\n *\n * Buckets live in a module-local Map, so on Cloudflare Workers the limits are\n * enforced per isolate, not fleet-wide: the effective ceiling is multiplied by\n * the number of live isolates and resets whenever an isolate is evicted. This\n * is acceptable as a coarse abuse brake but is NOT a hard global limit. The\n * unauthenticated /v1/join surface is the most exposed to this gap. Real\n * fleet-wide enforcement needs a shared counter backed by a Durable Object or\n * D1/KV.\n */\nexport function createInMemoryRequestRateLimiter(\n\toptions: CreateInMemoryRequestRateLimiterOptions = {},\n): InMemoryRequestRateLimiter {\n\tconst windowMs = Math.max(1000, Math.trunc(options.windowMs ?? 60_000));\n\tconst now = options.now ?? (() => Date.now());\n\tconst buckets = new Map<string, { limiter: RateLimiter; lastUsedAt: number }>();\n\tlet checks = 0;\n\n\tfunction estimatedRetryAfterS(limit: number): number {\n\t\treturn Math.max(1, Math.ceil(windowMs / Math.max(1, limit) / 1000));\n\t}\n\n\tfunction cleanupExpiredBuckets(currentNow: number): void {\n\t\tif (buckets.size < 64 || checks % 64 !== 0) return;\n\t\tconst staleBefore = currentNow - windowMs * 10;\n\t\tfor (const [key, bucket] of buckets) {\n\t\t\tif (bucket.lastUsedAt < staleBefore) buckets.delete(key);\n\t\t}\n\t}\n\n\treturn {\n\t\tcheck(key: string, limit: number) {\n\t\t\tconst safeLimit = Math.max(1, Math.trunc(limit));\n\t\t\tchecks += 1;\n\t\t\tconst currentNow = now();\n\t\t\tcleanupExpiredBuckets(currentNow);\n\t\t\tconst bucketKey = `${safeLimit}:${key}`;\n\t\t\tlet bucket = buckets.get(bucketKey);\n\t\t\tif (!bucket) {\n\t\t\t\tbucket = {\n\t\t\t\t\tlimiter: new RateLimiter({\n\t\t\t\t\t\ttokensPerInterval: safeLimit,\n\t\t\t\t\t\tinterval: windowMs,\n\t\t\t\t\t\tfireImmediately: true,\n\t\t\t\t\t}),\n\t\t\t\t\tlastUsedAt: currentNow,\n\t\t\t\t};\n\t\t\t\tbuckets.set(bucketKey, bucket);\n\t\t\t}\n\t\t\tbucket.lastUsedAt = currentNow;\n\t\t\tif (bucket.limiter.tryRemoveTokens(1)) {\n\t\t\t\treturn { allowed: true, retryAfterS: 0 };\n\t\t\t}\n\t\t\treturn { allowed: false, retryAfterS: estimatedRetryAfterS(safeLimit) };\n\t\t},\n\t};\n}\n","/** Signed device routes for ADR 0005 Section 8 rebinding: start, status, finalize. */\nimport type { Context, Hono } from \"hono\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport { decodeCoordinatorAuthProof32 } from \"./coordinator-auth-proof.js\";\nimport type { registerCoordinatorDeviceAuthLinkRoutes } from \"./coordinator-device-auth-link.js\";\nimport {\n\tcreateDeviceRebindDeviceSteps,\n\ttype DeviceRebindResult,\n\ttype DeviceRebindSigner,\n} from \"./coordinator-device-rebind-ceremony.js\";\nimport type { DeviceRebindReceipt } from \"./coordinator-device-rebind-commit.js\";\nimport {\n\tcreateInMemoryRequestRateLimiter,\n\ttype InMemoryRequestRateLimiter,\n} from \"./request-rate-limit.js\";\n\ntype LinkDeps = Parameters<typeof registerCoordinatorDeviceAuthLinkRoutes>[1];\ntype Store = ReturnType<LinkDeps[\"storeFactory\"]>;\ntype Deps = LinkDeps & { limiter: InMemoryRequestRateLimiter; now: () => number };\ntype Steps = ReturnType<typeof createDeviceRebindDeviceSteps>;\ntype Action = \"start\" | \"status\" | \"finalize\";\n\nexport const DEVICE_REBIND_ATTEMPTS_PATH = \"/v1/auth/rebind-attempts\";\n\nconst fields = {\n\tstart: [\n\t\t\"group_id\",\n\t\t\"identity_id\",\n\t\t\"attempt_id\",\n\t\t\"browser_start_hash\",\n\t\t\"loopback_redirect\",\n\t\t\"review_digest\",\n\t],\n\tstatus: [\"group_id\"],\n\tfinalize: [\"group_id\", \"completion\", \"signature\"],\n} as const;\ntype Input = Record<(typeof fields)[Action][number], string>;\nconst isHash = (value: string) => /^[a-f0-9]{64}$/.test(value);\n\nfunction exactInput(value: Record<string, unknown> | null, action: Action): value is Input {\n\treturn (\n\t\tvalue !== null &&\n\t\tObject.keys(value).length === fields[action].length &&\n\t\tfields[action].every((key) => Object.hasOwn(value, key) && typeof value[key] === \"string\")\n\t);\n}\n\nconst unknownOutcome = (c: Context) => c.json({ error: \"device_rebind_unknown\" }, 503);\nconst invalid = (c: Context) => c.json({ error: \"device_rebind_invalid_input\" }, 400);\n\nasync function readInput(c: Context, action: Action, deps: Deps) {\n\tconst url = new URL(c.req.url);\n\tif (url.origin !== new URL(deps.config.redirectUri).origin)\n\t\treturn c.json({ error: \"device_rebind_unavailable\" }, 403);\n\tif (action === \"status\") {\n\t\tconst entries = [...url.searchParams.entries()];\n\t\tif (c.req.raw.body !== null || entries.length !== fields.status.length) return invalid(c);\n\t\tconst data = Object.fromEntries(entries);\n\t\treturn exactInput(data, action) ? { data, raw: new Uint8Array() } : invalid(c);\n\t}\n\tif (url.search) return invalid(c);\n\tconst raw = await deps.readRequestBytes(c, 4096);\n\tif (!raw) return c.json({ error: \"body_too_large\" }, 413);\n\tconst data = deps.parseJsonObject(raw);\n\treturn exactInput(data, action) ? { data, raw } : invalid(c);\n}\n\nfunction validInput(data: Input, action: Action, attemptId: string): boolean {\n\tif (!isAuthControllerId(attemptId) || !isAuthControllerId(data.group_id)) return false;\n\tif (action === \"finalize\")\n\t\treturn decodeCoordinatorAuthProof32(data.completion) !== null && data.signature.length <= 512;\n\tif (action === \"status\") return true;\n\treturn (\n\t\tisAuthControllerId(data.identity_id) &&\n\t\tisHash(data.browser_start_hash) &&\n\t\tisHash(data.review_digest)\n\t);\n}\n\n/** Explicit allowlist: the receipt is the device's own durable record. */\nfunction receiptJson(receipt: DeviceRebindReceipt) {\n\treturn {\n\t\tattempt_id: receipt.attemptId,\n\t\tbinding_id: receipt.bindingId,\n\t\tdevice_id: receipt.deviceId,\n\t\tprevious_identity_id: receipt.previousIdentityId,\n\t\ttarget_identity_id: receipt.targetIdentityId,\n\t\tenrollment_count: receipt.enrollmentCount,\n\t\tfinalized_at_ms: receipt.finalizedAtMs,\n\t};\n}\n\n/**\n * `retry` is the only refusal worth repeating as is; every other refusal needs\n * the person to act. An unknown outcome is 503: read status before retrying.\n */\nfunction respond(c: Context, result: DeviceRebindResult | null, deps: Deps): Response {\n\tif (!result || result.kind === \"unknown\") return unknownOutcome(c);\n\tif (result.kind === \"refused\")\n\t\treturn c.json(\n\t\t\t{ error: \"device_rebind_refused\", reason: result.reason },\n\t\t\tresult.reason === \"retry\" ? 409 : 403,\n\t\t);\n\tif (result.kind === \"started\")\n\t\treturn c.json({\n\t\t\tattempt_id: result.attemptId,\n\t\t\texpires_at_ms: result.expiresAtMs,\n\t\t\tcoordinator_id: deps.config.coordinatorId,\n\t\t\torigin: new URL(deps.config.redirectUri).origin,\n\t\t\tissuer: deps.config.issuer,\n\t\t\tauth_config_revision: deps.config.revision,\n\t\t});\n\tif (result.kind === \"status\")\n\t\treturn c.json({\n\t\t\tstate: result.state,\n\t\t\texpires_at_ms: result.expiresAtMs,\n\t\t\ttarget_identity_id: result.targetIdentityId,\n\t\t\treceipt: result.receipt ? receiptJson(result.receipt) : null,\n\t\t});\n\tif (result.kind === \"finalized\" || result.kind === \"prior_commit\")\n\t\treturn c.json({ state: result.kind, receipt: receiptJson(result.receipt) });\n\treturn unknownOutcome(c);\n}\n\nfunction runAction(\n\tsteps: Steps,\n\taction: Action,\n\tdata: Input,\n\tattemptId: string,\n\tsigner: DeviceRebindSigner,\n) {\n\tif (action === \"status\") return steps.status({ attemptId, signer });\n\tif (action === \"finalize\")\n\t\treturn steps.finalize({\n\t\t\tattemptId,\n\t\t\tsigner,\n\t\t\tcompletionSecret: data.completion,\n\t\t\tsignature: data.signature,\n\t\t});\n\treturn steps.start(\n\t\t{\n\t\t\tattemptId,\n\t\t\tsigner,\n\t\t\tcurrentIdentityId: data.identity_id,\n\t\t\tloopbackRedirect: data.loopback_redirect,\n\t\t\tbrowserStartHash: data.browser_start_hash,\n\t\t\treviewDigest: data.review_digest,\n\t\t},\n\t\tsigner.deviceId,\n\t);\n}\n\nasync function authorize(\n\tc: Context,\n\taction: Action,\n\tdata: Input,\n\traw: Uint8Array,\n\tstore: Store,\n\tdeps: Deps,\n) {\n\tconst auth = await deps.authorizeRequest(store, {\n\t\tmethod: c.req.method,\n\t\turl: c.req.url,\n\t\tgroupId: data.group_id,\n\t\tbody: raw,\n\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t});\n\tif (!auth.ok || !auth.enrollment)\n\t\treturn (\n\t\t\tdeps.rateLimitedResponse(c, `device-rebind:${action}`, { authenticated: false }) ??\n\t\t\tc.json({ error: \"device_rebind_unavailable\" }, deps.authErrorStatus(auth.error))\n\t\t);\n\tconst e = auth.enrollment;\n\treturn (\n\t\tdeps.rateLimitedResponse(c, `${deps.config.coordinatorId}:${e.device_id}`, {\n\t\t\tauthenticated: true,\n\t\t}) ?? {\n\t\t\tgroupId: e.group_id,\n\t\t\tdeviceId: e.device_id,\n\t\t\tpublicKey: e.public_key,\n\t\t\tfingerprint: e.fingerprint,\n\t\t}\n\t);\n}\n\nasync function handle(c: Context, action: Action, deps: Deps): Promise<Response> {\n\tc.header(\"Cache-Control\", \"no-store\");\n\tc.header(\"Referrer-Policy\", \"no-referrer\");\n\tlet store: Store | undefined;\n\ttry {\n\t\ttry {\n\t\t\tconst input = await readInput(c, action, deps);\n\t\t\tif (input instanceof Response) return input;\n\t\t\tconst attemptId =\n\t\t\t\taction === \"start\" ? input.data.attempt_id : (c.req.param(\"attemptId\") ?? \"\");\n\t\t\tif (!validInput(input.data, action, attemptId)) return invalid(c);\n\t\t\tstore = deps.storeFactory();\n\t\t\tconst signer = await authorize(c, action, input.data, input.raw, store, deps);\n\t\t\tif (signer instanceof Response) return signer;\n\t\t\tconst steps = await deviceSteps(store, deps);\n\t\t\tif (!steps) return c.json({ error: \"not_found\" }, 404);\n\t\t\treturn respond(c, await runAction(steps, action, input.data, attemptId, signer), deps);\n\t\t} finally {\n\t\t\tawait store?.close();\n\t\t}\n\t} catch {\n\t\treturn unknownOutcome(c);\n\t}\n}\n\nasync function deviceSteps(store: Store, deps: Deps): Promise<Steps | null> {\n\tconst backend = (await store.readDeviceRebindBackend?.()) ?? null;\n\tif (!backend) return null;\n\treturn createDeviceRebindDeviceSteps({\n\t\tbackend,\n\t\tconfig: deps.config,\n\t\tpublicOrigin: new URL(deps.config.redirectUri).origin,\n\t\tlimiter: deps.limiter,\n\t\tnow: deps.now,\n\t});\n}\n\n/** Signed admission runs before any rebind storage is touched. */\nexport function registerCoordinatorDeviceRebindRoutes(\n\tapp: Hono,\n\tdeps: LinkDeps & { now?: () => number },\n): void {\n\tif (!deps.config.enabled) return;\n\tconst now = deps.now ?? (() => Date.now());\n\tconst captured: Deps = { ...deps, now, limiter: createInMemoryRequestRateLimiter({ now }) };\n\tapp.post(DEVICE_REBIND_ATTEMPTS_PATH, (c) => handle(c, \"start\", captured));\n\tapp.get(`${DEVICE_REBIND_ATTEMPTS_PATH}/:attemptId`, (c) => handle(c, \"status\", captured));\n\tapp.post(`${DEVICE_REBIND_ATTEMPTS_PATH}/:attemptId/finalize`, (c) =>\n\t\thandle(c, \"finalize\", captured),\n\t);\n}\n","import { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type {\n\tCoordinatorCreateDeviceRevocationInput,\n\tCoordinatorCreateDeviceRevocationResult,\n\tCoordinatorDeviceRevocationRecord,\n} from \"./coordinator-device-revocation.js\";\nimport { ed25519KeyId } from \"./coordinator-ed25519-key-id.js\";\nimport type { CoordinatorStore } from \"./coordinator-store-contract.js\";\n\nexport type CoordinatorDeviceRevocationAction = \"preview\" | \"commit\";\nfunction isAction(action: unknown): action is CoordinatorDeviceRevocationAction {\n\treturn action === \"preview\" || action === \"commit\";\n}\nexport interface CoordinatorDeviceRevocationHandlerOptions {\n\tstore: Pick<CoordinatorStore, \"getEnrollment\" | \"createDeviceRevocation\">;\n\t/** Server composition only: never derive this from a request or enrollment. */\n\ttrustedCoordinatorId: string | null;\n\tadminSecret?: string | null;\n\t/** Transport admission only, called after native admin authentication and context checks. */\n\tbeforeBody?: (request: Request) => Response | null;\n}\ninterface RevocationInput {\n\tgroup_id: string;\n\tdevice_id: string;\n\texpected_digest?: string;\n}\nexport const COORDINATOR_DEVICE_REVOCATION_MAX_BODY_BYTES = 4096;\nconst MAX_BODY_BYTES = COORDINATOR_DEVICE_REVOCATION_MAX_BODY_BYTES;\nconst SCOPE = \"whole_database_device_id_any_key_and_canonical_key_any_device_all_groups\";\nfunction response(body: unknown, status = 200): Response {\n\treturn Response.json(body, {\n\t\tstatus,\n\t\theaders: {\n\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t},\n\t});\n}\nfunction failure(error: string, status: number): Response {\n\treturn response({ error }, status);\n}\nfunction isDigest(value: unknown): value is string {\n\treturn typeof value === \"string\" && /^[a-f0-9]{64}$/.test(value);\n}\nasync function digestBytes(value: string): Promise<ArrayBuffer> {\n\treturn globalThis.crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(value));\n}\nasync function authenticate(provided: string | null, configured: string | null): Promise<boolean> {\n\tif (typeof configured !== \"string\" || !configured || !provided || provided.length > 8192)\n\t\treturn false;\n\t// Match the controller-review native fixed-length MAC verification pattern.\n\tconst [expected, actual] = await Promise.all([digestBytes(configured), digestBytes(provided)]);\n\tconst key = await globalThis.crypto.subtle.importKey(\n\t\t\"raw\",\n\t\texpected,\n\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n\t\tfalse,\n\t\t[\"sign\", \"verify\"],\n\t);\n\tconst signature = await globalThis.crypto.subtle.sign(\"HMAC\", key, expected);\n\treturn globalThis.crypto.subtle.verify(\"HMAC\", key, signature, actual);\n}\nfunction matchesDeclaredBodyLength(declared: string | null, size: number): boolean {\n\tif (declared === null) return true;\n\treturn /^[0-9]{1,10}$/.test(declared) && Number(declared) === size;\n}\nasync function readBody(request: Request): Promise<Uint8Array | null> {\n\tconst declaredLength = request.headers.get(\"Content-Length\");\n\tif (!request.body) return new Uint8Array();\n\tconst reader = request.body.getReader();\n\tconst signal = AbortSignal.any([request.signal, AbortSignal.timeout(10_000)]);\n\tconst bytes = new Uint8Array(MAX_BODY_BYTES);\n\tlet size = 0;\n\tlet onAbort = () => {};\n\ttry {\n\t\t// Resolve interruption so an abort before the first read cannot orphan a rejection.\n\t\tconst aborted = new Promise<null>((resolve) => {\n\t\t\tonAbort = () => resolve(null);\n\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tif (signal.aborted) onAbort();\n\t\t});\n\t\twhile (true) {\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst chunk = await Promise.race([reader.read(), aborted]);\n\t\t\tif (chunk === null) throw new Error(\"revocation_body_stopped\");\n\t\t\tconst { done, value } = chunk;\n\t\t\tif (done) {\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t\t// Empty input follows the existing invalid-input 400 path before store access.\n\t\t\t\tif (!matchesDeclaredBodyLength(declaredLength, size)) return new Uint8Array();\n\t\t\t\treturn bytes.subarray(0, size);\n\t\t\t}\n\t\t\tif (value.byteLength > MAX_BODY_BYTES - size) return null;\n\t\t\tbytes.set(value, size);\n\t\t\tsize += value.byteLength;\n\t\t}\n\t} finally {\n\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t// Stream teardown must not extend a deadline or delay an oversized-body refusal.\n\t\tvoid reader.cancel().catch(() => {});\n\t\treader.releaseLock();\n\t}\n}\nfunction parseInput(\n\traw: Uint8Array,\n\taction: CoordinatorDeviceRevocationAction,\n): RevocationInput | null {\n\ttry {\n\t\tconst data: unknown = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(raw));\n\t\tif (!data || typeof data !== \"object\" || Array.isArray(data)) return null;\n\t\tconst fields =\n\t\t\taction === \"commit\"\n\t\t\t\t? [\"group_id\", \"device_id\", \"expected_digest\"]\n\t\t\t\t: [\"group_id\", \"device_id\"];\n\t\tconst keys = Object.keys(data);\n\t\tif (keys.length !== fields.length || keys.some((key) => !fields.includes(key))) return null;\n\t\tif (!(\"group_id\" in data) || !(\"device_id\" in data)) return null;\n\t\tif (!isAuthControllerId(data.group_id) || !isAuthControllerId(data.device_id)) return null;\n\t\tconst input: RevocationInput = { group_id: data.group_id, device_id: data.device_id };\n\t\tif (action === \"commit\") {\n\t\t\tif (!(\"expected_digest\" in data) || !isDigest(data.expected_digest)) return null;\n\t\t\tinput.expected_digest = data.expected_digest;\n\t\t}\n\t\treturn input;\n\t} catch {\n\t\treturn null;\n\t}\n}\n/** Existing canonical parsers intentionally accept invalid inner types/trailing bytes. */\nfunction isStrictEd25519Key(publicKey: string): boolean {\n\tif (publicKey.length > 16384 || /[\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(publicKey.replaceAll(\"\\t\", \"\")))\n\t\treturn false;\n\tconst [type, encoded] = publicKey.trim().split(/\\s+/);\n\tif (type !== \"ssh-ed25519\" || !encoded || !/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)) return false;\n\ttry {\n\t\tconst wire = Uint8Array.from(atob(encoded), (character) => character.charCodeAt(0));\n\t\tif (wire.length !== 51) return false;\n\t\tconst view = new DataView(wire.buffer);\n\t\treturn (\n\t\t\tview.getUint32(0) === 11 &&\n\t\t\tnew TextDecoder().decode(wire.subarray(4, 15)) === \"ssh-ed25519\" &&\n\t\t\tview.getUint32(15) === 32\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\nasync function evidenceDigest(\n\tcoordinatorId: string,\n\ttuple: CoordinatorCreateDeviceRevocationInput,\n\tkeyId: string,\n): Promise<string> {\n\tconst bytes = await digestBytes(\n\t\tJSON.stringify([\n\t\t\t\"codemem-global-device-revocation\",\n\t\t\t1,\n\t\t\t\"revoke\",\n\t\t\tcoordinatorId,\n\t\t\ttuple.groupId,\n\t\t\ttuple.deviceId,\n\t\t\ttuple.publicKey,\n\t\t\ttuple.fingerprint,\n\t\t\tkeyId,\n\t\t]),\n\t);\n\treturn Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\ntype RevocationReference = Pick<\n\tCoordinatorDeviceRevocationRecord,\n\t\"subject_kind\" | \"subject_value\" | \"revocation_id\" | \"created_at\"\n>;\nfunction isReceiptText(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length > 0 && !value.includes(\"\\0\");\n}\nfunction captureRevocationReferences(\n\tresult: CoordinatorCreateDeviceRevocationResult,\n\tdeviceId: string,\n\tkeyId: string,\n): RevocationReference[] | null {\n\tif (result?.kind !== \"revoked\" || !Array.isArray(result.records)) return null;\n\t// First retained subjects may have different revocation IDs and historical metadata.\n\tconst references: RevocationReference[] = [];\n\tfor (const [kind, value] of [\n\t\t[\"device_id\", deviceId],\n\t\t[\"ed25519_key\", keyId],\n\t] as const) {\n\t\tconst matching = result.records.filter(\n\t\t\t(row) => row?.subject_kind === kind && row.subject_value === value,\n\t\t);\n\t\tif (matching.length !== 1) return null;\n\t\tconst row = matching[0];\n\t\tif (!row) return null;\n\t\tconst reference = {\n\t\t\tsubject_kind: kind,\n\t\t\tsubject_value: value,\n\t\t\trevocation_id: row.revocation_id,\n\t\t\tcreated_at: row.created_at,\n\t\t};\n\t\tif (!isReceiptText(reference.revocation_id) || !isReceiptText(reference.created_at))\n\t\t\treturn null;\n\t\treferences.push(reference);\n\t}\n\treturn references;\n}\nasync function applyAction(\n\taction: CoordinatorDeviceRevocationAction,\n\tstore: CoordinatorDeviceRevocationHandlerOptions[\"store\"],\n\tcoordinatorId: string,\n\tinput: RevocationInput,\n): Promise<Response> {\n\tconst includeDisabled = true;\n\tconst enrollment = await store.getEnrollment(input.group_id, input.device_id, includeDisabled);\n\tif (!enrollment) return failure(\"revocation_target_unavailable\", 409);\n\t// Copy the exact tuple before any crypto await; never refresh it during commit.\n\tconst tuple = Object.freeze({\n\t\tgroupId: enrollment.group_id,\n\t\tdeviceId: enrollment.device_id,\n\t\tpublicKey: enrollment.public_key,\n\t\tfingerprint: enrollment.fingerprint,\n\t});\n\tif (\n\t\ttuple.groupId !== input.group_id ||\n\t\ttuple.deviceId !== input.device_id ||\n\t\ttypeof tuple.publicKey !== \"string\" ||\n\t\t!isStrictEd25519Key(tuple.publicKey) ||\n\t\ttypeof tuple.fingerprint !== \"string\" ||\n\t\t!tuple.fingerprint ||\n\t\ttuple.fingerprint.includes(\"\\0\")\n\t)\n\t\treturn failure(\"revocation_target_unavailable\", 409);\n\tconst keyId = await ed25519KeyId(tuple.publicKey);\n\tif (!keyId) return failure(\"revocation_target_unavailable\", 409);\n\tconst digest = await evidenceDigest(coordinatorId, tuple, keyId);\n\tconst subjects = {\n\t\tversion: 1,\n\t\tcoordinator_id: coordinatorId,\n\t\tgroup_id: tuple.groupId,\n\t\tdevice_id: tuple.deviceId,\n\t\tkey_id: keyId,\n\t\tscope: SCOPE,\n\t};\n\tif (action === \"preview\")\n\t\treturn response({ state: \"ready\", ...subjects, expected_digest: digest });\n\tif (input.expected_digest !== digest) return failure(\"revocation_preview_stale\", 409);\n\tconst result = await store.createDeviceRevocation(tuple);\n\tif (result?.kind === \"rejected\" && result.error === \"enrollment_mismatch\")\n\t\treturn failure(\"revocation_preview_stale\", 409);\n\tconst revocations = captureRevocationReferences(result, tuple.deviceId, keyId);\n\tif (!revocations) return failure(\"device_revocation_incomplete\", 503);\n\treturn response({ state: \"revoked\", ...subjects, revocations });\n}\n\n/**\n * Internal capability. Transport registration and per-request store ownership live\n * in the runtime route adapter; direct callers retain ownership of their store.\n */\nexport function createCoordinatorDeviceRevocationHandler(\n\toptions: CoordinatorDeviceRevocationHandlerOptions,\n): (action: CoordinatorDeviceRevocationAction, request: Request) => Promise<Response> {\n\tconst fixed = Object.freeze({\n\t\tstore: options.store,\n\t\ttrustedCoordinatorId: options.trustedCoordinatorId,\n\t\tadminSecret: options.adminSecret ?? null,\n\t\tbeforeBody: options.beforeBody,\n\t});\n\treturn async (action: CoordinatorDeviceRevocationAction, request: Request): Promise<Response> => {\n\t\tconst { store, trustedCoordinatorId, adminSecret } = fixed;\n\t\ttry {\n\t\t\tif (!(await authenticate(request.headers.get(\"X-Codemem-Coordinator-Admin\"), adminSecret)))\n\t\t\t\treturn failure(\"unauthorized\", 401);\n\t\t\tif (!isAuthControllerId(trustedCoordinatorId) || !store)\n\t\t\t\treturn failure(\"revocation_unavailable\", 503);\n\t\t\tif (!isAction(action)) return failure(\"revocation_invalid_input\", 400);\n\t\t\tconst admission = fixed.beforeBody?.(request);\n\t\t\tif (admission) return admission;\n\t\t\tconst raw = await readBody(request);\n\t\t\tif (!raw) return failure(\"body_too_large\", 413);\n\t\t\tconst input = parseInput(raw, action);\n\t\t\tif (!input) return failure(\"revocation_invalid_input\", 400);\n\t\t\treturn await applyAction(action, store, trustedCoordinatorId, input);\n\t\t} catch {\n\t\t\t// A lost receipt can follow a committed write: no rollback or compensation claim.\n\t\t\treturn failure(\"device_revocation_incomplete\", 503);\n\t\t}\n\t};\n}\n","import type { Context, Hono } from \"hono\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport {\n\tCOORDINATOR_DEVICE_REVOCATION_MAX_BODY_BYTES,\n\tcreateCoordinatorDeviceRevocationHandler,\n} from \"./coordinator-device-revocation-handler.js\";\nimport type { CoordinatorStore } from \"./coordinator-store-contract.js\";\n\n/** Server composition only. The route always uses the runtime's concrete DB factory. */\nexport interface CoordinatorDeviceRevocationContext {\n\tcoordinatorId: string;\n}\n\nfunction failure(error: string, status: number): Response {\n\treturn Response.json(\n\t\t{ error },\n\t\t{\n\t\t\tstatus,\n\t\t\theaders: {\n\t\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\t},\n\t\t},\n\t);\n}\n\nfunction transportAdmission(request: Request): Response | null {\n\tif (request.method !== \"POST\") return failure(\"method_not_allowed\", 405);\n\tconst url = new URL(request.url);\n\tif (url.search || url.username || url.password) return failure(\"revocation_invalid_input\", 400);\n\tif (\n\t\t!/^application\\/json(?:\\s*;\\s*charset=utf-8)?$/i.test(request.headers.get(\"Content-Type\") ?? \"\")\n\t)\n\t\treturn failure(\"unsupported_media_type\", 415);\n\tif (request.headers.has(\"Content-Encoding\")) return failure(\"unsupported_media_type\", 415);\n\tconst length = request.headers.get(\"Content-Length\");\n\tif (length !== null) {\n\t\tif (request.headers.has(\"Transfer-Encoding\")) return failure(\"revocation_invalid_input\", 400);\n\t\tif (!/^[0-9]{1,10}$/.test(length)) return failure(\"revocation_invalid_input\", 400);\n\t\tif (Number(length) > COORDINATOR_DEVICE_REVOCATION_MAX_BODY_BYTES)\n\t\t\treturn failure(\"body_too_large\", 413);\n\t}\n\treturn null;\n}\n\nexport function registerCoordinatorDeviceRevocationRoutes(\n\tapp: Hono,\n\toptions: {\n\t\tcontext?: CoordinatorDeviceRevocationContext;\n\t\tconfiguredCoordinatorIds: readonly unknown[];\n\t\tstoreFactory: () => CoordinatorStore;\n\t\tadminSecret: () => string | null;\n\t\trateLimitedResponse: (c: Context, key: string, authenticated: boolean) => Response | null;\n\t},\n): void {\n\tconst selectedId = options.context?.coordinatorId;\n\tconst trustedCoordinatorId =\n\t\tisAuthControllerId(selectedId) &&\n\t\toptions.configuredCoordinatorIds.every((id) => id === selectedId)\n\t\t\t? selectedId\n\t\t\t: null;\n\tconst storeFactory = options.storeFactory;\n\tconst adminSecret = options.adminSecret;\n\tconst rateLimitedResponse = options.rateLimitedResponse;\n\tfor (const [path, action] of [\n\t\t[\"/v1/admin/devices/revoke-preview\", \"preview\"],\n\t\t[\"/v1/admin/devices/revoke\", \"commit\"],\n\t] as const) {\n\t\tapp.all(path, async (c) => {\n\t\t\tlet selectedStore: CoordinatorStore | undefined;\n\t\t\ttry {\n\t\t\t\t// Capture credentials before crypto/body awaits. The factory and ID were pinned\n\t\t\t\t// at composition; opening the DB is deferred until authenticated input is valid.\n\t\t\t\tconst secret = adminSecret();\n\t\t\t\tconst limited = rateLimitedResponse(c, c.req.path, false);\n\t\t\t\tif (limited) return limited;\n\t\t\t\tconst selected = () => (selectedStore ??= storeFactory());\n\t\t\t\tconst handler = createCoordinatorDeviceRevocationHandler({\n\t\t\t\t\ttrustedCoordinatorId,\n\t\t\t\t\tadminSecret: secret,\n\t\t\t\t\tstore: {\n\t\t\t\t\t\tgetEnrollment: (...args) => selected().getEnrollment(...args),\n\t\t\t\t\t\tcreateDeviceRevocation: (...args) => selected().createDeviceRevocation(...args),\n\t\t\t\t\t},\n\t\t\t\t\tbeforeBody: (request) =>\n\t\t\t\t\t\trateLimitedResponse(c, \"admin\", true) ?? transportAdmission(request),\n\t\t\t\t});\n\t\t\t\treturn await handler(action, c.req.raw);\n\t\t\t} catch {\n\t\t\t\treturn failure(\"device_revocation_incomplete\", 503);\n\t\t\t} finally {\n\t\t\t\t// Only the per-request selected store is owned here, never browser/runtime stores.\n\t\t\t\tif (selectedStore) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait selectedStore.close();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t/* No backend details in responses. */\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n}\n","/**\n * Invite link encoding/decoding for the coordinator join flow.\n *\n * Ported from codemem/coordinator_invites.py.\n */\n\nexport interface InvitePayload {\n\tv: number;\n\tkind: \"coordinator_team_invite\" | \"team_member\" | \"add_device\" | string;\n\tcoordinator_url: string;\n\tgroup_id: string;\n\tpolicy: string;\n\ttoken: string;\n\texpires_at: string;\n\tteam_name: string | null;\n\t/** Present only for project-first invites. All values are display-only; access intent stays coordinator-owned. */\n\toperation_id?: string;\n\tinviter_name?: string | null;\n\tinviter_device_id?: string;\n\tproject_summaries?: Array<{ display_name: string; existing_memory_count: number }>;\n\t/** Policy metadata for recipient-aware invites. It is preview-only and never grants scope access. */\n\tpolicy_team_id?: string;\n\ttarget_identity_id?: string;\n\tassigned_identity_id?: string;\n\treviewed_preview_digest?: string;\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n\tlet binary = \"\";\n\tfor (const byte of bytes) binary += String.fromCharCode(byte);\n\treturn btoa(binary);\n}\n\nfunction base64ToBytes(base64: string): Uint8Array {\n\tconst binary = atob(base64);\n\tconst bytes = new Uint8Array(binary.length);\n\tfor (let index = 0; index < binary.length; index += 1) {\n\t\tbytes[index] = binary.charCodeAt(index);\n\t}\n\treturn bytes;\n}\n\nfunction toBase64Url(base64: string): string {\n\treturn base64.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nfunction fromBase64Url(value: string): string {\n\tconst padded = value.replace(/-/g, \"+\").replace(/_/g, \"/\");\n\treturn padded + \"=\".repeat((4 - (padded.length % 4)) % 4);\n}\n\n/** Encode an invite payload as a compact base64url string (no padding). */\nexport function encodeInvitePayload(payload: InvitePayload): string {\n\tconst json = JSON.stringify(payload);\n\tconst bytes = new TextEncoder().encode(json);\n\treturn toBase64Url(bytesToBase64(bytes));\n}\n\n/** Decode a base64url invite payload string back to an InvitePayload. */\nexport function decodeInvitePayload(value: string): InvitePayload {\n\tconst json = new TextDecoder().decode(base64ToBytes(fromBase64Url(value)));\n\tconst data: unknown = JSON.parse(json);\n\tif (typeof data !== \"object\" || data === null) {\n\t\tthrow new Error(\"invalid invite payload\");\n\t}\n\treturn data as InvitePayload;\n}\n\n/** Build a `codemem://join?invite=...` link from an encoded payload. */\nexport function inviteLink(encodedPayload: string): string {\n\treturn `codemem://join?invite=${encodeURIComponent(encodedPayload)}`;\n}\n\n/**\n * Extract the raw encoded payload from either a `codemem://` link or a raw value.\n *\n * Throws if a `codemem://` link is provided but has no `invite` query parameter.\n */\nexport function extractInvitePayload(value: string): string {\n\tconst raw = value.trim();\n\tif (raw.startsWith(\"codemem://\")) {\n\t\tconst url = new URL(raw);\n\t\tconst invite = url.searchParams.get(\"invite\") ?? \"\";\n\t\tif (!invite) {\n\t\t\tthrow new Error(\"invite payload missing from link\");\n\t\t}\n\t\treturn invite;\n\t}\n\treturn raw;\n}\n","import type { Context } from \"hono\";\nimport type { CoordinatorEnrollment, CoordinatorStore } from \"./coordinator-store-contract.js\";\n\n/** Only this current member/key snapshot can supply remote cache authority.\n * Catalogue version 1 is discovery metadata, not permission or an account login. */\nexport async function scopeAuthorizationResponse(\n\tc: Context,\n\tstore: CoordinatorStore,\n\tinput: { groupId: string; scopeId: string; requester: CoordinatorEnrollment },\n): Promise<Response> {\n\ttry {\n\t\tconst result = await store.getScopeAuthorization({\n\t\t\tgroupId: input.groupId,\n\t\t\tscopeId: input.scopeId,\n\t\t});\n\t\tif (result.kind === \"rejected\") {\n\t\t\tswitch (result.error) {\n\t\t\t\tcase \"scope_not_found\":\n\t\t\t\tcase \"scope_inactive\":\n\t\t\t\tcase \"scope_source_mismatch\":\n\t\t\t\tcase \"group_archived\":\n\t\t\t\t\treturn c.json({ error: \"scope_not_found\" }, 404);\n\t\t\t\tdefault:\n\t\t\t\t\treturn c.json({ error: \"scope_authorization_unavailable\" }, 503);\n\t\t\t}\n\t\t}\n\t\tif (\n\t\t\tresult.kind !== \"authorized\" ||\n\t\t\tresult.authorizationVersion !== 1 ||\n\t\t\tresult.scope.scope_id !== input.scopeId ||\n\t\t\tresult.scope.group_id !== input.groupId\n\t\t) {\n\t\t\treturn c.json({ error: \"scope_authorization_unavailable\" }, 503);\n\t\t}\n\t\t// Match the principal copied before signature verification, not a newly\n\t\t// read enrollment: rotation after admission must not grant an unchecked key.\n\t\tconst requester = input.requester;\n\t\tconst authorized = result.members.some(\n\t\t\t({ membership, enrollment }) =>\n\t\t\t\tmembership.device_id === requester.device_id &&\n\t\t\t\tenrollment.device_id === requester.device_id &&\n\t\t\t\tenrollment.group_id === input.groupId &&\n\t\t\t\trequester.group_id === input.groupId &&\n\t\t\t\tenrollment.public_key === requester.public_key &&\n\t\t\t\tenrollment.fingerprint === requester.fingerprint &&\n\t\t\t\tenrollment.identity_id === requester.identity_id,\n\t\t);\n\t\tif (!authorized) return c.json({ error: \"scope_membership_required\" }, 403);\n\t\treturn c.json({\n\t\t\tauthorization_version: 1,\n\t\t\tscope: result.scope,\n\t\t\titems: result.members.map(({ membership, enrollment, keyId }) => ({\n\t\t\t\tmembership,\n\t\t\t\tenrollment,\n\t\t\t\tkey_id: keyId,\n\t\t\t})),\n\t\t});\n\t} catch {\n\t\treturn c.json({ error: \"scope_authorization_unavailable\" }, 503);\n\t}\n}\n","export const PROJECT_INVITE_PENDING_STATUS = \"pending_setup\" as const;\n\nexport const PROJECT_SYNC_ENABLEMENT_FAILED = \"project_sync_enablement_failed\" as const;\n\nexport const PROJECT_SYNC_ENABLEMENT_FAILURE_DETAIL =\n\t\"Invitation was accepted, but sync could not be enabled. Make the codemem config writable, then retry.\";\n\nexport class ProjectSyncEnablementError extends Error {\n\treadonly code = PROJECT_SYNC_ENABLEMENT_FAILED;\n\treadonly detail = PROJECT_SYNC_ENABLEMENT_FAILURE_DETAIL;\n\n\tconstructor(options?: ErrorOptions) {\n\t\tsuper(PROJECT_SYNC_ENABLEMENT_FAILURE_DETAIL, options);\n\t\tthis.name = \"ProjectSyncEnablementError\";\n\t}\n}\n\nexport function isProjectSyncEnablementError(error: unknown): error is ProjectSyncEnablementError {\n\treturn (\n\t\ttypeof error === \"object\" &&\n\t\terror !== null &&\n\t\t\"code\" in error &&\n\t\terror.code === PROJECT_SYNC_ENABLEMENT_FAILED &&\n\t\t\"detail\" in error &&\n\t\terror.detail === PROJECT_SYNC_ENABLEMENT_FAILURE_DETAIL\n\t);\n}\n","import { createHash } from \"node:crypto\";\nimport { normalizeIdentityDisplayName } from \"./project-invite-identity.js\";\nimport { canonicalWorkspaceIdentity } from \"./workspace-identity.js\";\n\nexport const SHARE_HISTORY_POLICY = \"existing_and_future\" as const;\n\nexport interface ShareProjectIntent {\n\tcanonicalIdentity: string;\n\tdisplayName: string;\n\tidentitySource: string;\n\texistingMemoryCount: number;\n}\n\nexport interface AcceptedProjectIntent {\n\tcanonical_identity: string;\n\tdisplay_name: string;\n\texisting_memory_count: number;\n}\n\nfunction digest(value: unknown): string {\n\treturn createHash(\"sha256\").update(JSON.stringify(value)).digest(\"hex\");\n}\n\nexport function shareProjectSetDigest(projects: ShareProjectIntent[]): string {\n\tconst reviewedProjects = projects\n\t\t.map((project) => ({\n\t\t\tcanonicalIdentity: project.canonicalIdentity,\n\t\t\texistingMemoryCount: project.existingMemoryCount,\n\t\t}))\n\t\t.toSorted((left, right) => left.canonicalIdentity.localeCompare(right.canonicalIdentity));\n\treturn digest({ v: 1, historyPolicy: SHARE_HISTORY_POLICY, projects: reviewedProjects });\n}\n\nexport function acceptedProjectIntentDigest(projects: AcceptedProjectIntent[]): string {\n\treturn shareProjectSetDigest(\n\t\tprojects.map((project) => ({\n\t\t\tcanonicalIdentity: project.canonical_identity,\n\t\t\tdisplayName: project.display_name,\n\t\t\tidentitySource: \"coordinator_acceptance\",\n\t\t\texistingMemoryCount: project.existing_memory_count,\n\t\t})),\n\t);\n}\n\nexport function parseAcceptedProjectIntent(value: unknown): AcceptedProjectIntent[] {\n\tif (!Array.isArray(value) || value.length === 0 || value.length > 100) {\n\t\tthrow new Error(\"operation_intent_invalid\");\n\t}\n\tconst projects = value.map((item) => {\n\t\tif (!item || typeof item !== \"object\" || Array.isArray(item)) {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t\tconst record = item as Record<string, unknown>;\n\t\tif (typeof record.canonical_identity !== \"string\" || typeof record.display_name !== \"string\") {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t\tconst canonicalIdentityRaw = record.canonical_identity;\n\t\tconst canonicalIdentity = canonicalIdentityRaw.trim();\n\t\tconst displayNameRaw = record.display_name;\n\t\tlet displayName: string;\n\t\ttry {\n\t\t\tdisplayName = normalizeIdentityDisplayName(displayNameRaw, \"project_name\");\n\t\t} catch {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t\tconst count = record.existing_memory_count;\n\t\tconst canonicalIdentityRoundTrip = canonicalWorkspaceIdentity({\n\t\t\tgitRemote: canonicalIdentity,\n\t\t}).value;\n\t\tif (\n\t\t\t!canonicalIdentity ||\n\t\t\tcanonicalIdentity !== canonicalIdentityRaw ||\n\t\t\tcanonicalIdentity.length > 2048 ||\n\t\t\tcanonicalIdentity.startsWith(\"unmapped:\") ||\n\t\t\tcanonicalIdentityRoundTrip !== canonicalIdentity ||\n\t\t\tdisplayName !== displayNameRaw ||\n\t\t\t!Number.isSafeInteger(count) ||\n\t\t\tNumber(count) < 0 ||\n\t\t\t/[\\p{Cc}\\p{Cf}]/u.test(canonicalIdentity) ||\n\t\t\t/[\\p{Cc}\\p{Cf}]/u.test(displayName)\n\t\t) {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t\treturn {\n\t\t\tcanonical_identity: canonicalIdentity,\n\t\t\tdisplay_name: displayName,\n\t\t\texisting_memory_count: Number(count),\n\t\t};\n\t});\n\tif (new Set(projects.map((project) => project.canonical_identity)).size !== projects.length) {\n\t\tthrow new Error(\"operation_intent_invalid\");\n\t}\n\treturn projects.toSorted((left, right) =>\n\t\tleft.canonical_identity.localeCompare(right.canonical_identity),\n\t);\n}\n","/**\n * Coordinator API — Hono-based HTTP server for the coordinator relay.\n *\n * Manages device enrollment, presence, invites, and join requests.\n * Ported from codemem/coordinator_api.py.\n */\n\nimport type { Context } from \"hono\";\nimport { Hono } from \"hono\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport { registerCoordinatorAuthControllerReviewRoutes } from \"./coordinator-auth-controller-review-route.js\";\nimport {\n\tAUTH_SCHEMA_UPGRADE_REQUIRED,\n\tassertConfiguredAuthSchema,\n\tauthSchemaUpgradeResponse,\n} from \"./coordinator-auth-schema.js\";\nimport type {\n\tCoordinatorBrowserAuth,\n\tCoordinatorBrowserAuthClientKey,\n} from \"./coordinator-browser-auth-app.js\";\nimport {\n\ttype CoordinatorDeviceAccountChangeOptions,\n\tregisterCoordinatorDeviceAccountChangeRoutes,\n} from \"./coordinator-device-account-change.js\";\nimport {\n\ttype CoordinatorDeviceAuthLinkOptions,\n\ttype CoordinatorDeviceAuthLinkStore,\n\tregisterCoordinatorAccountLinkStatusRoute,\n\tregisterCoordinatorDeviceAuthLinkRoutes,\n} from \"./coordinator-device-auth-link.js\";\nimport {\n\tDEVICE_REBIND_ATTEMPTS_PATH,\n\tregisterCoordinatorDeviceRebindRoutes,\n} from \"./coordinator-device-rebind-http.js\";\nimport {\n\ttype CoordinatorDeviceRevocationContext,\n\tregisterCoordinatorDeviceRevocationRoutes,\n} from \"./coordinator-device-revocation-route.js\";\nimport type { InvitePayload } from \"./coordinator-invites.js\";\nimport { encodeInvitePayload, inviteLink } from \"./coordinator-invites.js\";\nimport type { CoordinatorLegacyTeamCompletionManifestV1 } from \"./coordinator-legacy-team-completion.js\";\nimport {\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES,\n\tCoordinatorLegacyTeamCompletionConflictError,\n\tnormalizeCoordinatorLegacyTeamCompletionCandidateRef,\n\tnormalizeCoordinatorLegacyTeamCompletionGroupIds,\n\tnormalizeCoordinatorLegacyTeamCompletionManifest,\n\trequireCoordinatorLegacyTeamCompletionTeamBinding,\n} from \"./coordinator-legacy-team-completion.js\";\nimport {\n\tCoordinatorMembershipError,\n\tSCOPE_MEMBERSHIP_EFFECT_CONFLICT,\n} from \"./coordinator-membership-effects.js\";\nimport { scopeAuthorizationResponse } from \"./coordinator-scope-authorization-response.js\";\nimport type {\n\tCoordinatorBootstrapGrantAuthorizationError,\n\tCoordinatorBootstrapGrantAuthorizationInput,\n\tCoordinatorBootstrapGrantVerification,\n\tCoordinatorEnrollment,\n\tCoordinatorInviteKind,\n\tCoordinatorScope,\n\tCoordinatorScopeMembership,\n\tCoordinatorStore,\n} from \"./coordinator-store-contract.js\";\nimport { CoordinatorReciprocalApprovalRequestChangedError } from \"./coordinator-store-contract.js\";\nimport { PROJECT_INVITE_PENDING_STATUS } from \"./project-invite-acceptance.js\";\nimport {\n\tnormalizeDeviceDisplayName,\n\tnormalizeHumanPresentationName,\n\tnormalizeProjectInviteSummaries,\n} from \"./project-invite-identity.js\";\nimport { acceptedProjectIntentDigest, parseAcceptedProjectIntent } from \"./project-share-intent.js\";\nimport {\n\tRecipientReviewedIntentError,\n\ttype RecipientReviewedIntentV1,\n\tverifyRecipientReviewedIntent,\n} from \"./recipient-reviewed-intent.js\";\nimport {\n\tcreateInMemoryRequestRateLimiter,\n\ttype InMemoryRequestRateLimiter,\n} from \"./request-rate-limit.js\";\nimport { explainScopeMembershipRevocation } from \"./scope-membership-semantics.js\";\nimport { DEFAULT_TIME_WINDOW_S } from \"./sync-auth-constants.js\";\nimport { fingerprintPublicKey } from \"./sync-fingerprint.js\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst MAX_BODY_BYTES = 64 * 1024;\nconst MAX_LEGACY_TEAM_COMPLETION_BODY_BYTES = COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES + 1024;\nconst ADMIN_HEADER = \"X-Codemem-Coordinator-Admin\";\nconst ADMIN_ACTOR_HEADER = \"X-Codemem-Coordinator-Admin-Actor\";\nconst DEFAULT_COORDINATOR_READ_LIMIT = 120;\nconst DEFAULT_COORDINATOR_MUTATION_LIMIT = 30;\n\nexport interface CoordinatorRequestRateLimitOptions {\n\tlimiter?: InMemoryRequestRateLimiter;\n\treadLimit?: number;\n\tmutationLimit?: number;\n\tunauthenticatedReadLimit?: number;\n\tunauthenticatedMutationLimit?: number;\n}\n\nexport interface CoordinatorRuntimeDeps {\n\tadminSecret(): string | null;\n\tnow(): string;\n}\n\nexport interface CreateCoordinatorAppOptions {\n\tstoreFactory: (options?: { existingOnly: true }) => CoordinatorStore;\n\truntime: CoordinatorRuntimeDeps;\n\trequestVerifier: CoordinatorRequestVerifier;\n\trequestRateLimit?: CoordinatorRequestRateLimitOptions;\n\tauthLink?: CoordinatorDeviceAuthLinkOptions;\n\tbrowserAuth?: CoordinatorAppBrowserAuthOptions;\n\t/** Server-owned recipient namespace only; does not enable authentication or grant authority. */\n\trecipientInviteCoordinatorId?: string;\n\taccountChanges?: CoordinatorDeviceAccountChangeOptions;\n\tdeviceRevocation?: CoordinatorDeviceRevocationContext;\n}\nexport type CoordinatorAppBrowserAuthOptions =\n\t| {\n\t\t\tkind: \"ready\";\n\t\t\tauth: CoordinatorBrowserAuth;\n\t\t\tstoreFactory: () => CoordinatorDeviceAuthLinkStore;\n\t\t\tclientKey: CoordinatorBrowserAuthClientKey;\n\t }\n\t| { kind: \"unavailable\"; error?: typeof AUTH_SCHEMA_UPGRADE_REQUIRED };\n\nfunction recipientInviteErrorStatus(code: string): 403 | 404 | 409 | 410 {\n\tif (code === \"device_revoked\") return 403;\n\tif (code === \"invite_expired\") return 410;\n\tif (code === \"invite_invalid\") return 404;\n\treturn 409;\n}\n\nfunction authenticationUnavailableResponse(): Response {\n\treturn new Response(\"Authentication unavailable. Try again.\", {\n\t\tstatus: 503,\n\t\theaders: {\n\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\t\"Content-Type\": \"text/plain;charset=utf-8\",\n\t\t},\n\t});\n}\n\nfunction recipientInviteContext(\n\topts: CreateCoordinatorAppOptions,\n\ttoken: string,\n): { token: string; coordinatorId?: string } {\n\tconst ready = opts.browserAuth?.kind === \"ready\" ? opts.browserAuth : undefined;\n\tconst config = ready?.auth.storeConfig ?? opts.authLink?.config;\n\tconst coordinatorId = opts.recipientInviteCoordinatorId;\n\tif (coordinatorId !== undefined) {\n\t\tif (\n\t\t\t!isAuthControllerId(coordinatorId) ||\n\t\t\t[ready?.auth.storeConfig, opts.authLink?.config].some(\n\t\t\t\t(metadata) => metadata && metadata.coordinatorId !== coordinatorId,\n\t\t\t)\n\t\t)\n\t\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t\treturn { token, coordinatorId };\n\t}\n\treturn config ? { token, coordinatorId: config.coordinatorId } : { token };\n}\n\nfunction accountChangeOptions(\n\topts: CreateCoordinatorAppOptions,\n): CoordinatorDeviceAccountChangeOptions | undefined {\n\tconst ready = opts.browserAuth?.kind === \"ready\" ? opts.browserAuth : undefined;\n\tconst configured = ready?.auth.storeConfig ?? opts.authLink?.config;\n\tif (\n\t\topts.accountChanges &&\n\t\tconfigured &&\n\t\t[\"coordinatorId\", \"issuer\", \"revision\", \"redirectUri\", \"enabled\"].some(\n\t\t\t(key) => Reflect.get(configured, key) !== Reflect.get(opts.accountChanges?.config ?? {}, key),\n\t\t)\n\t)\n\t\tthrow new Error(\"coordinator_auth_configuration_conflict\");\n\tif (opts.accountChanges) return opts.accountChanges;\n\tif (!ready?.auth.resolveAccountChanges) return undefined;\n\treturn {\n\t\tconfig: ready.auth.storeConfig,\n\t\tstoreFactory: ready.storeFactory,\n\t\tassertReady: assertConfiguredAuthSchema,\n\t\toperationsFactory: ready.auth.resolveAccountChanges,\n\t};\n}\nfunction registerOptionalCoordinatorAuth(\n\tapp: Hono,\n\topts: CreateCoordinatorAppOptions,\n\tdeps: Omit<\n\t\tParameters<typeof registerCoordinatorDeviceAuthLinkRoutes>[1],\n\t\t\"config\" | \"storeFactory\"\n\t>,\n): void {\n\tif (opts.authLink && opts.browserAuth) throw new Error(\"coordinator_auth_configuration_conflict\");\n\tconst accountChanges = accountChangeOptions(opts);\n\tconst unavailable =\n\t\topts.browserAuth?.kind === \"unavailable\" &&\n\t\topts.browserAuth.error === AUTH_SCHEMA_UPGRADE_REQUIRED\n\t\t\t? authSchemaUpgradeResponse\n\t\t\t: authenticationUnavailableResponse;\n\tif (opts.browserAuth?.kind !== \"ready\") {\n\t\tapp.all(\"/v1/auth/account-link-status\", unavailable);\n\t\tapp.all(\"/v1/auth/resolved-account-owner-status\", unavailable);\n\t\tapp.all(\"/v1/auth/resolved-account-owner-receipt-status\", unavailable);\n\t}\n\tif (opts.browserAuth?.kind === \"unavailable\") {\n\t\tfor (const path of [\n\t\t\t\"/auth/*\",\n\t\t\t\"/v1/auth/link-attempts\",\n\t\t\t\"/v1/auth/link-attempts/*\",\n\t\t\t\"/v1/auth/account-changes\",\n\t\t\t\"/v1/auth/account-changes/*\",\n\t\t\t\"/v1/auth/owner-config\",\n\t\t\t\"/v1/auth/owner-attempts\",\n\t\t\t\"/v1/auth/owner-attempts/*\",\n\t\t\tDEVICE_REBIND_ATTEMPTS_PATH,\n\t\t\t`${DEVICE_REBIND_ATTEMPTS_PATH}/*`,\n\t\t\t\"/v1/admin/auth-controller-reviews\",\n\t\t]) {\n\t\t\tapp.all(path, unavailable);\n\t\t}\n\t\treturn;\n\t}\n\tif (accountChanges)\n\t\tregisterCoordinatorDeviceAccountChangeRoutes(app, { ...deps, ...accountChanges });\n\tconst ready = opts.browserAuth;\n\tconst authLink =\n\t\tready?.kind === \"ready\"\n\t\t\t? { config: ready.auth.storeConfig, storeFactory: ready.storeFactory }\n\t\t\t: opts.authLink;\n\tif (authLink?.config.enabled) {\n\t\tregisterCoordinatorDeviceAuthLinkRoutes(app, { ...deps, ...authLink });\n\t\tregisterCoordinatorAuthControllerReviewRoutes(app, {\n\t\t\t...deps,\n\t\t\t...authLink,\n\t\t\tadminSecret: () => opts.runtime.adminSecret(),\n\t\t});\n\t}\n\tif (ready?.kind === \"ready\") {\n\t\tregisterCoordinatorAccountLinkStatusRoute(app, {\n\t\t\t...deps,\n\t\t\tconfig: ready.auth.storeConfig,\n\t\t\tstoreFactory: ready.storeFactory,\n\t\t});\n\t\t// Only with the browser half; a legacy link option has no rebind pages.\n\t\tregisterCoordinatorDeviceRebindRoutes(app, {\n\t\t\t...deps,\n\t\t\tconfig: ready.auth.storeConfig,\n\t\t\tstoreFactory: ready.storeFactory,\n\t\t});\n\t\tready.auth.register(app, ready.clientKey);\n\t}\n}\n\nexport interface CoordinatorVerifyRequestInput {\n\tmethod: string;\n\tpathWithQuery: string;\n\tbodyBytes: Uint8Array;\n\ttimestamp: string;\n\tnonce: string;\n\tsignature: string;\n\tpublicKey: string;\n\tdeviceId: string;\n}\n\nfunction registerCoordinatorRuntimeRoutes(\n\tapp: Hono,\n\topts: CreateCoordinatorAppOptions,\n\tdeps: Parameters<typeof registerOptionalCoordinatorAuth>[2],\n): void {\n\tconst createStore = opts.storeFactory;\n\tregisterCoordinatorDeviceRevocationRoutes(app, {\n\t\tcontext: opts.deviceRevocation,\n\t\tconfiguredCoordinatorIds: [\n\t\t\topts.authLink?.config,\n\t\t\topts.browserAuth?.kind === \"ready\" ? opts.browserAuth.auth.storeConfig : undefined,\n\t\t\topts.accountChanges?.config,\n\t\t]\n\t\t\t.filter((config) => config !== undefined)\n\t\t\t.map((config) => config?.coordinatorId),\n\t\tstoreFactory: () => createStore({ existingOnly: true }),\n\t\tadminSecret: opts.runtime.adminSecret.bind(opts.runtime),\n\t\trateLimitedResponse: (c, key, authenticated) =>\n\t\t\tdeps.rateLimitedResponse(c, key, { authenticated }),\n\t});\n\tregisterOptionalCoordinatorAuth(app, opts, deps);\n}\n\nexport type CoordinatorRequestVerifier = (\n\tinput: CoordinatorVerifyRequestInput,\n) => Promise<boolean> | boolean;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction authorizeAdmin(\n\theaderValue: string | null | undefined,\n\truntime: CoordinatorRuntimeDeps,\n): { ok: boolean; error: string } {\n\tconst expected = runtime.adminSecret();\n\tif (!expected) return { ok: false, error: \"admin_not_configured\" };\n\tconst provided = (headerValue ?? \"\").trim();\n\tif (!provided) return { ok: false, error: \"missing_admin_header\" };\n\tif (provided !== expected) return { ok: false, error: \"invalid_admin_secret\" };\n\treturn { ok: true, error: \"ok\" };\n}\n\n/** Extract path + query string from a full URL for signature verification. */\nfunction pathWithQuery(url: string): string {\n\tconst parsed = new URL(url);\n\treturn parsed.search ? `${parsed.pathname}${parsed.search}` : parsed.pathname;\n}\n\nasync function cleanupNonces(store: CoordinatorStore, cutoff: string): Promise<void> {\n\tawait store.cleanupNonces(cutoff);\n}\n\ninterface AuthResult {\n\tok: boolean;\n\terror: string;\n\tenrollment: CoordinatorEnrollment | null;\n}\n\nasync function authorizeRequest(\n\tstore: CoordinatorStore,\n\truntime: CoordinatorRuntimeDeps,\n\trequestVerifier: CoordinatorRequestVerifier,\n\topts: {\n\t\tmethod: string;\n\t\turl: string;\n\t\tgroupId: string;\n\t\tbody: Uint8Array;\n\t\tdeviceId: string | null;\n\t\tsignature: string | null;\n\t\ttimestamp: string | null;\n\t\tnonce: string | null;\n\t},\n): Promise<AuthResult> {\n\tconst { deviceId, signature, timestamp, nonce } = opts;\n\tif (!deviceId || !signature || !timestamp || !nonce) {\n\t\treturn { ok: false, error: \"missing_headers\", enrollment: null };\n\t}\n\n\tconst sourceEnrollment = await store.getEnrollment(opts.groupId, deviceId, true);\n\tif (!sourceEnrollment) {\n\t\treturn { ok: false, error: \"unknown_device\", enrollment: null };\n\t}\n\tconst enrollment = { ...sourceEnrollment };\n\tif (enrollment.enabled !== 1) {\n\t\treturn { ok: false, error: \"device_disabled\", enrollment: null };\n\t}\n\tconst group = await store.getGroup(opts.groupId);\n\tif (!group) {\n\t\treturn { ok: false, error: \"group_not_found\", enrollment: null };\n\t}\n\tif (group.archived_at) {\n\t\treturn { ok: false, error: \"group_archived\", enrollment: null };\n\t}\n\n\tconst publicKey = enrollment.public_key;\n\tif (typeof publicKey !== \"string\")\n\t\treturn { ok: false, error: \"unknown_device\", enrollment: null };\n\tlet valid: boolean;\n\ttry {\n\t\tvalid = await requestVerifier({\n\t\t\tmethod: opts.method,\n\t\t\tpathWithQuery: pathWithQuery(opts.url),\n\t\t\tbodyBytes: opts.body,\n\t\t\ttimestamp,\n\t\t\tnonce,\n\t\t\tsignature,\n\t\t\tpublicKey: String(publicKey),\n\t\t\tdeviceId,\n\t\t});\n\t} catch {\n\t\treturn { ok: false, error: \"signature_verification_error\", enrollment: null };\n\t}\n\n\tif (!valid) {\n\t\treturn { ok: false, error: \"invalid_signature\", enrollment: null };\n\t}\n\n\tconst createdAt = runtime.now();\n\tconst admission = await store.recordAuthorizedNonce({\n\t\tgroupId: opts.groupId,\n\t\tdeviceId,\n\t\tpublicKey,\n\t\tnonce,\n\t\tcreatedAt,\n\t});\n\tif (admission !== \"recorded\") {\n\t\treturn { ok: false, error: admission, enrollment: null };\n\t}\n\n\t// Clock-source note: the nonce timestamp/cutoff below is driven by the\n\t// injected runtime.now(), while the request freshness window is enforced\n\t// inside requestVerifier using real Date.now() (see the worker's\n\t// request-verifier). In production both are wall-clock so they agree. Under\n\t// an injected/frozen clock they can diverge; the freshness check is not\n\t// reachable from runtime.now(), so tests that freeze runtime.now() must keep\n\t// timestamps within DEFAULT_TIME_WINDOW_S of real time for the verifier to\n\t// accept them. Unifying the two would require threading the clock into the\n\t// verifier signature across the core/worker boundary.\n\tconst cutoff = new Date(\n\t\tnew Date(createdAt).getTime() - DEFAULT_TIME_WINDOW_S * 2 * 1000,\n\t).toISOString();\n\tawait cleanupNonces(store, cutoff);\n\n\treturn { ok: true, error: \"ok\", enrollment };\n}\n\nfunction authErrorStatus(error: string): 401 | 403 | 409 {\n\tif (error === \"device_disabled\" || error === \"device_revoked\") return 403;\n\tif (error === \"group_archived\") return 409;\n\treturn 401;\n}\n\nfunction bootstrapAuthorizationErrorStatus(\n\terror: CoordinatorBootstrapGrantAuthorizationError,\n): 403 | 404 | 409 | 503 {\n\tswitch (error) {\n\t\tcase \"grant_not_found\":\n\t\tcase \"seed_enrollment_not_found\":\n\t\tcase \"worker_enrollment_not_found\":\n\t\t\treturn 404;\n\t\tcase \"grant_revoked\":\n\t\tcase \"grant_expired\":\n\t\tcase \"device_revoked\":\n\t\t\treturn 403;\n\t\tcase \"group_archived\":\n\t\t\treturn 409;\n\t\tdefault:\n\t\t\treturn 503;\n\t}\n}\n\nasync function bootstrapAuthorizationResponse(\n\tc: Context,\n\tstore: CoordinatorStore,\n\tinput: CoordinatorBootstrapGrantAuthorizationInput,\n) {\n\ttry {\n\t\tconst result = await store.getBootstrapGrantAuthorization(input);\n\t\tif (result.kind === \"rejected\") {\n\t\t\treturn c.json({ error: result.error }, bootstrapAuthorizationErrorStatus(result.error));\n\t\t}\n\t\tconst payload: CoordinatorBootstrapGrantVerification = {\n\t\t\tauthorization_version: result.authorizationVersion,\n\t\t\tgrant: result.grant,\n\t\t\tseed_enrollment: result.seedEnrollment,\n\t\t\tworker_enrollment: result.workerEnrollment,\n\t\t};\n\t\treturn c.json(payload);\n\t} catch {\n\t\treturn c.json({ error: \"bootstrap_authorization_unavailable\" }, 503);\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// App factory\n// ---------------------------------------------------------------------------\n\nasync function readRequestBytes(c: Context, maxBytes = MAX_BODY_BYTES): Promise<Uint8Array | null> {\n\tconst contentLength = Number.parseInt(c.req.header(\"content-length\") ?? \"\", 10);\n\tif (Number.isFinite(contentLength) && contentLength > maxBytes) {\n\t\treturn null;\n\t}\n\tconst stream = c.req.raw.body;\n\tif (!stream) return new Uint8Array();\n\tconst reader = stream.getReader();\n\tconst chunks: Uint8Array[] = [];\n\tlet total = 0;\n\ttry {\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) break;\n\t\t\tif (!value) continue;\n\t\t\ttotal += value.byteLength;\n\t\t\tif (total > maxBytes) {\n\t\t\t\tawait reader.cancel();\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tchunks.push(value);\n\t\t}\n\t} finally {\n\t\treader.releaseLock();\n\t}\n\tconst combined = new Uint8Array(total);\n\tlet offset = 0;\n\tfor (const chunk of chunks) {\n\t\tcombined.set(chunk, offset);\n\t\toffset += chunk.byteLength;\n\t}\n\treturn combined;\n}\n\nfunction deviceRevokedResponse(c: Context, error: unknown): Response {\n\tconst ownership = deviceOwnershipErrorResponse(c, error);\n\tif (ownership) return ownership;\n\tif (error instanceof Error && error.message === \"device_revoked\") {\n\t\treturn c.json({ error: \"device_revoked\" }, 403);\n\t}\n\tthrow error;\n}\n\nfunction deviceOwnershipErrorResponse(c: Context, error: unknown): Response | null {\n\tif (!(error instanceof Error)) return null;\n\tif (error.message === \"device_ownership_requires_verified_identity\") {\n\t\treturn c.json({ error: \"device_ownership_requires_verified_identity\" }, 403);\n\t}\n\tif (error.message === \"device_ownership_authorization_unavailable\") {\n\t\treturn c.json({ error: \"device_ownership_authorization_unavailable\" }, 503);\n\t}\n\treturn null;\n}\n\nfunction recipientInviteAcceptanceErrorResponse(c: Context, error: unknown): Response {\n\tconst ownership = deviceOwnershipErrorResponse(c, error);\n\tif (ownership) return ownership;\n\tconst code = error instanceof Error ? error.message : \"invite_invalid\";\n\treturn c.json({ error: code }, recipientInviteErrorStatus(code));\n}\n\nfunction projectInviteAcceptanceErrorResponse(c: Context, error: unknown): Response {\n\tconst ownership = deviceOwnershipErrorResponse(c, error);\n\tif (ownership) return ownership;\n\tconst code = error instanceof Error ? error.message : \"invite_invalid\";\n\tif (code === \"device_revoked\") return c.json({ error: \"device_revoked\" }, 403);\n\tif (code === \"invite_expired\") return c.json({ error: code }, 410);\n\tif (code === \"invite_invalid\") return c.json({ error: code }, 404);\n\treturn c.json({ error: code }, 409);\n}\n\nasync function enrollAdminDevice(\n\tc: Context,\n\tstore: CoordinatorStore,\n\tgroupId: string,\n\tinput: Parameters<CoordinatorStore[\"enrollDevice\"]>[1],\n): Promise<Response> {\n\ttry {\n\t\tawait store.createGroup(groupId);\n\t\tawait store.enrollDevice(groupId, input);\n\t\treturn c.json({ ok: true });\n\t} catch (error) {\n\t\treturn deviceRevokedResponse(c, error);\n\t} finally {\n\t\tawait store.close();\n\t}\n}\n\nasync function reviewJoinRequestWithRevocationDenial(\n\t...args: Parameters<typeof handleJoinRequestReview>\n): Promise<Response> {\n\ttry {\n\t\treturn await handleJoinRequestReview(...args);\n\t} catch (error) {\n\t\tif (\n\t\t\terror instanceof Error &&\n\t\t\t(error.message === \"join_review_unavailable\" || error.message === \"join_review_incomplete\")\n\t\t) {\n\t\t\treturn args[0].json({ error: error.message }, 503);\n\t\t}\n\t\treturn deviceRevokedResponse(args[0], error);\n\t}\n}\n\nasync function enableAdminDevice(\n\tc: Context,\n\tstore: CoordinatorStore,\n\tgroupId: string,\n\tdeviceId: string,\n): Promise<Response> {\n\ttry {\n\t\tconst ok = await store.setDeviceEnabled(groupId, deviceId, true);\n\t\tif (!ok) return c.json({ error: \"device_not_found\" }, 404);\n\t\treturn c.json({ ok: true });\n\t} catch (error) {\n\t\treturn deviceRevokedResponse(c, error);\n\t} finally {\n\t\tawait store.close();\n\t}\n}\n\nasync function peerDiscoveryResponse(\n\tc: Context,\n\tstore: CoordinatorStore,\n\tgroupId: string,\n\trequestingDeviceId: string,\n): Promise<Response> {\n\ttry {\n\t\tconst items = await store.listGroupPeers(groupId, requestingDeviceId);\n\t\treturn c.json({ items });\n\t} catch {\n\t\treturn c.json({ error: \"peer_discovery_unavailable\" }, 503);\n\t}\n}\n\nexport function createCoordinatorApp(\n\topts?: CreateCoordinatorAppOptions,\n): InstanceType<typeof Hono> {\n\tif (!opts?.storeFactory || !opts.runtime || !opts.requestVerifier) {\n\t\tthrow new Error(\"createCoordinatorApp requires storeFactory, runtime, and requestVerifier.\");\n\t}\n\tconst runtime = opts.runtime;\n\tconst createStore = opts.storeFactory;\n\tconst requestVerifier = opts.requestVerifier;\n\tconst requestRateLimit = opts.requestRateLimit ?? {};\n\tconst rateLimiter = requestRateLimit.limiter ?? createInMemoryRequestRateLimiter();\n\tconst readLimit = Math.max(\n\t\t1,\n\t\tMath.trunc(requestRateLimit.readLimit ?? DEFAULT_COORDINATOR_READ_LIMIT),\n\t);\n\tconst mutationLimit = Math.max(\n\t\t1,\n\t\tMath.trunc(requestRateLimit.mutationLimit ?? DEFAULT_COORDINATOR_MUTATION_LIMIT),\n\t);\n\tconst unauthenticatedReadLimit = Math.max(\n\t\t1,\n\t\tMath.trunc(requestRateLimit.unauthenticatedReadLimit ?? Math.min(20, readLimit)),\n\t);\n\tconst unauthenticatedMutationLimit = Math.max(\n\t\t1,\n\t\tMath.trunc(requestRateLimit.unauthenticatedMutationLimit ?? Math.min(10, mutationLimit)),\n\t);\n\tconst app = new Hono();\n\tconst textDecoder = new TextDecoder();\n\n\tfunction rateLimitedResponse(c: Context, key: string, authenticated: boolean) {\n\t\tconst isRead = c.req.method === \"GET\" || c.req.method === \"HEAD\" || c.req.method === \"OPTIONS\";\n\t\tconst result = rateLimiter.check(\n\t\t\t`${c.req.method}:${authenticated ? \"auth\" : \"anon\"}:${key}`,\n\t\t\tauthenticated\n\t\t\t\t? isRead\n\t\t\t\t\t? readLimit\n\t\t\t\t\t: mutationLimit\n\t\t\t\t: isRead\n\t\t\t\t\t? unauthenticatedReadLimit\n\t\t\t\t\t: unauthenticatedMutationLimit,\n\t\t);\n\t\tif (result.allowed) return null;\n\t\tc.header(\"Retry-After\", String(result.retryAfterS));\n\t\treturn c.json({ error: \"rate_limited\", retry_after_s: result.retryAfterS }, 429);\n\t}\n\n\tfunction parseJsonObject(raw: Uint8Array): Record<string, unknown> | null {\n\t\ttry {\n\t\t\tconst data: unknown = JSON.parse(textDecoder.decode(raw));\n\t\t\tif (typeof data !== \"object\" || data === null || Array.isArray(data)) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn data as Record<string, unknown>;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tregisterCoordinatorRuntimeRoutes(app, opts, {\n\t\tauthorizeRequest: (store, request) =>\n\t\t\tauthorizeRequest(store, runtime, requestVerifier, request),\n\t\tauthErrorStatus,\n\t\treadRequestBytes,\n\t\tparseJsonObject,\n\t\trateLimitedResponse: (c, key, options) => rateLimitedResponse(c, key, options.authenticated),\n\t});\n\n\tfunction optionalString(data: Record<string, unknown>, key: string): string | null {\n\t\tconst value = data[key];\n\t\tif (value == null) return null;\n\t\treturn String(value).trim() || null;\n\t}\n\n\tfunction optionalHeaderString(value: string | null | undefined): string | null {\n\t\treturn value?.trim() || null;\n\t}\n\n\tfunction optionalNumber(data: Record<string, unknown>, key: string): number | null {\n\t\tconst value = data[key];\n\t\tif (value == null || value === \"\") return null;\n\t\tif (typeof value !== \"number\" && typeof value !== \"string\") return Number.NaN;\n\t\tif (typeof value === \"string\") {\n\t\t\tconst trimmed = value.trim();\n\t\t\tif (!trimmed) return Number.NaN;\n\t\t\tconst number = Number(trimmed);\n\t\t\treturn Number.isFinite(number) ? Math.trunc(number) : Number.NaN;\n\t\t}\n\t\tconst number = value;\n\t\treturn Number.isFinite(number) ? Math.trunc(number) : Number.NaN;\n\t}\n\n\tfunction queryFlag(value: string | undefined | null): boolean {\n\t\treturn [\"1\", \"true\", \"yes\"].includes(\n\t\t\tString(value ?? \"\")\n\t\t\t\t.trim()\n\t\t\t\t.toLowerCase(),\n\t\t);\n\t}\n\n\tfunction storedProjectIntent(value: string | null | undefined) {\n\t\ttry {\n\t\t\treturn parseAcceptedProjectIntent(JSON.parse(value ?? \"\"));\n\t\t} catch {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t}\n\n\tfunction buildAcceptedProjectIntent(invite: {\n\t\toperation_id?: string | null;\n\t\treviewed_project_set_digest?: string | null;\n\t\tproject_intent_json?: string | null;\n\t}) {\n\t\tconst operationId = String(invite.operation_id ?? \"\").trim();\n\t\tconst reviewedProjectSetDigest = String(invite.reviewed_project_set_digest ?? \"\").trim();\n\t\tif (\n\t\t\t!/^share_[a-f0-9]{40}$/u.test(operationId) ||\n\t\t\t!/^[a-f0-9]{64}$/u.test(reviewedProjectSetDigest)\n\t\t) {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t\tconst projects = storedProjectIntent(invite.project_intent_json);\n\t\tconst computedDigest = acceptedProjectIntentDigest(projects);\n\t\tif (computedDigest !== reviewedProjectSetDigest) {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t\treturn {\n\t\t\toperation_id: operationId,\n\t\t\treviewed_project_set_digest: reviewedProjectSetDigest,\n\t\t\tprojects,\n\t\t};\n\t}\n\n\tfunction storedProjectSummaries(\n\t\tvalue: string | null | undefined,\n\t): ReturnType<typeof normalizeProjectInviteSummaries> {\n\t\ttry {\n\t\t\treturn normalizeProjectInviteSummaries(JSON.parse(value ?? \"\"));\n\t\t} catch {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t}\n\n\tasync function requireActiveAdminGroup(store: CoordinatorStore, groupId: string, c: Context) {\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\t\tconst group = await store.getGroup(groupId);\n\t\tif (!group) return c.json({ error: \"group_not_found\" }, 404);\n\t\tif (group.archived_at) return c.json({ error: \"group_archived\" }, 409);\n\t\treturn null;\n\t}\n\n\tasync function findAdminScope(\n\t\tstore: CoordinatorStore,\n\t\tgroupId: string,\n\t\tscopeId: string,\n\t\tc: Context,\n\t): Promise<{ scope: CoordinatorScope | null; response: Response | null }> {\n\t\tconst groupError = await requireActiveAdminGroup(store, groupId, c);\n\t\tif (groupError) return { scope: null, response: groupError };\n\t\tif (!scopeId) return { scope: null, response: c.json({ error: \"scope_id_required\" }, 400) };\n\t\tconst matching = await store.listScopes({ groupId, includeInactive: true });\n\t\tconst scope = matching.find((item) => item.scope_id === scopeId) ?? null;\n\t\tif (!scope) return { scope: null, response: c.json({ error: \"scope_not_found\" }, 404) };\n\t\treturn { scope, response: null };\n\t}\n\n\tasync function authorizeGroupMember(store: CoordinatorStore, groupId: string, c: Context) {\n\t\tconst auth = await authorizeRequest(store, runtime, requestVerifier, {\n\t\t\tmethod: c.req.method,\n\t\t\turl: c.req.url,\n\t\t\tgroupId,\n\t\t\tbody: new Uint8Array(0),\n\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t});\n\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\treturn {\n\t\t\t\tauth,\n\t\t\t\tresponse:\n\t\t\t\t\trateLimitedResponse(c, c.req.path, false) ??\n\t\t\t\t\tc.json({ error: auth.error }, authErrorStatus(auth.error)),\n\t\t\t};\n\t\t}\n\t\tconst limited = rateLimitedResponse(c, String(auth.enrollment.device_id), true);\n\t\treturn { auth, response: limited };\n\t}\n\n\tfunction activeCurrentMembership(\n\t\tmembership: CoordinatorScopeMembership,\n\t\tscope: CoordinatorScope,\n\t): boolean {\n\t\treturn membership.status === \"active\" && membership.membership_epoch >= scope.membership_epoch;\n\t}\n\n\t// -----------------------------------------------------------------------\n\t// POST /v1/presence — upsert device presence (authenticated)\n\t// -----------------------------------------------------------------------\n\n\tapp.post(\"/v1/presence\", async (c) => {\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) {\n\t\t\treturn c.json({ error: \"body_too_large\" }, 413);\n\t\t}\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tif (!groupId) {\n\t\t\treturn c.json({ error: \"group_id_required\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst auth = await authorizeRequest(store, runtime, requestVerifier, {\n\t\t\t\tmethod: c.req.method,\n\t\t\t\turl: c.req.url,\n\t\t\t\tgroupId,\n\t\t\t\tbody: raw,\n\t\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t\t});\n\t\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\t\tconst limited = rateLimitedResponse(c, c.req.path, false);\n\t\t\t\tif (limited) return limited;\n\t\t\t\treturn c.json({ error: auth.error }, authErrorStatus(auth.error));\n\t\t\t}\n\t\t\tconst limited = rateLimitedResponse(c, String(auth.enrollment.device_id), true);\n\t\t\tif (limited) return limited;\n\n\t\t\tif (data.fingerprint && String(data.fingerprint) !== String(auth.enrollment.fingerprint)) {\n\t\t\t\treturn c.json({ error: \"fingerprint_mismatch\" }, 401);\n\t\t\t}\n\n\t\t\tconst rawAddresses = data.addresses ?? [];\n\t\t\tif (!Array.isArray(rawAddresses) || !rawAddresses.every((item) => typeof item === \"string\")) {\n\t\t\t\treturn c.json({ error: \"addresses_must_be_list_of_strings\" }, 400);\n\t\t\t}\n\n\t\t\tlet ttlS: number;\n\t\t\ttry {\n\t\t\t\tttlS = Math.max(1, Number.parseInt(String(data.ttl_s ?? 180), 10));\n\t\t\t\tif (Number.isNaN(ttlS)) {\n\t\t\t\t\treturn c.json({ error: \"ttl_s_must_be_int\" }, 400);\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\treturn c.json({ error: \"ttl_s_must_be_int\" }, 400);\n\t\t\t}\n\n\t\t\tconst response = await store.upsertPresence({\n\t\t\t\tgroupId,\n\t\t\t\tdeviceId: String(auth.enrollment.device_id),\n\t\t\t\taddresses: rawAddresses as string[],\n\t\t\t\tttlS,\n\t\t\t\tcapabilities:\n\t\t\t\t\ttypeof data.capabilities === \"object\" &&\n\t\t\t\t\tdata.capabilities !== null &&\n\t\t\t\t\t!Array.isArray(data.capabilities)\n\t\t\t\t\t\t? (data.capabilities as Record<string, unknown>)\n\t\t\t\t\t\t: undefined,\n\t\t\t});\n\n\t\t\treturn c.json({ ok: true, ...response });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// GET /v1/peers — list group peers (authenticated)\n\t// -----------------------------------------------------------------------\n\n\tapp.get(\"/v1/peers\", async (c) => {\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) {\n\t\t\treturn c.json({ error: \"group_id_required\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst auth = await authorizeRequest(store, runtime, requestVerifier, {\n\t\t\t\tmethod: c.req.method,\n\t\t\t\turl: c.req.url,\n\t\t\t\tgroupId,\n\t\t\t\tbody: new Uint8Array(0),\n\t\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t\t});\n\t\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\t\tconst limited = rateLimitedResponse(c, c.req.path, false);\n\t\t\t\tif (limited) return limited;\n\t\t\t\treturn c.json({ error: auth.error }, authErrorStatus(auth.error));\n\t\t\t}\n\t\t\tconst limited = rateLimitedResponse(c, String(auth.enrollment.device_id), true);\n\t\t\tif (limited) return limited;\n\n\t\t\treturn await peerDiscoveryResponse(c, store, groupId, String(auth.enrollment.device_id));\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// GET /v1/scopes — discovery catalogue, never member/key authority\n\t// -----------------------------------------------------------------------\n\n\tapp.get(\"/v1/scopes\", async (c) => {\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst { auth, response } = await authorizeGroupMember(store, groupId, c);\n\t\t\tif (response) return response;\n\t\t\tif (!auth.enrollment) return c.json({ error: \"unknown_device\" }, 401);\n\t\t\tconst scopes = await store.listScopes({ groupId, includeInactive: false });\n\t\t\t// One indexed lookup of the requester's own memberships, rather than\n\t\t\t// reading every member of every scope to answer a question about one\n\t\t\t// device. (scope_id, device_id) is unique, so the map is 1:1.\n\t\t\tconst memberships = await store.listDeviceScopeMemberships(\n\t\t\t\tString(auth.enrollment.device_id),\n\t\t\t\tfalse,\n\t\t\t);\n\t\t\tconst membershipByScope = new Map(\n\t\t\t\tmemberships.map((membership) => [membership.scope_id, membership]),\n\t\t\t);\n\t\t\tconst items: CoordinatorScope[] = scopes.filter((scope) => {\n\t\t\t\tif (scope.status !== \"active\") return false;\n\t\t\t\tconst membership = membershipByScope.get(scope.scope_id);\n\t\t\t\treturn Boolean(membership && activeCurrentMembership(membership, scope));\n\t\t\t});\n\t\t\t// Version describes the catalogue format only. Consumers must fetch each\n\t\t\t// actual scope's current member snapshot before granting cache authority.\n\t\t\treturn c.json({ version: 1, items });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// GET /v1/scopes/:scope_id/members — list members of an authorized scope\n\t// -----------------------------------------------------------------------\n\n\tapp.get(\"/v1/scopes/:scope_id/members\", async (c) => {\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = String(c.req.param(\"scope_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\t\tif (!scopeId) return c.json({ error: \"scope_id_required\" }, 400);\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst { auth, response } = await authorizeGroupMember(store, groupId, c);\n\t\t\tif (response) return response;\n\t\t\tif (!auth.enrollment) return c.json({ error: \"unknown_device\" }, 401);\n\t\t\treturn await scopeAuthorizationResponse(c, store, {\n\t\t\t\tgroupId,\n\t\t\t\tscopeId,\n\t\t\t\trequester: auth.enrollment,\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// GET /v1/reciprocal-approvals — list pending local approval state\n\t// -----------------------------------------------------------------------\n\n\tapp.get(\"/v1/reciprocal-approvals\", async (c) => {\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tconst direction = (c.req.query(\"direction\") ?? \"incoming\").trim();\n\t\tconst status = (c.req.query(\"status\") ?? \"pending\").trim() || \"pending\";\n\t\tif (!groupId) {\n\t\t\treturn c.json({ error: \"group_id_required\" }, 400);\n\t\t}\n\t\tif (![\"incoming\", \"outgoing\"].includes(direction)) {\n\t\t\treturn c.json({ error: \"direction_must_be_incoming_or_outgoing\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst auth = await authorizeRequest(store, runtime, requestVerifier, {\n\t\t\t\tmethod: c.req.method,\n\t\t\t\turl: c.req.url,\n\t\t\t\tgroupId,\n\t\t\t\tbody: new Uint8Array(0),\n\t\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t\t});\n\t\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\t\treturn (\n\t\t\t\t\trateLimitedResponse(c, c.req.path, false) ??\n\t\t\t\t\tc.json({ error: auth.error }, authErrorStatus(auth.error))\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst limited = rateLimitedResponse(c, String(auth.enrollment.device_id), true);\n\t\t\tif (limited) return limited;\n\t\t\tconst items = await store.listReciprocalApprovals({\n\t\t\t\tgroupId,\n\t\t\t\tdeviceId: String(auth.enrollment.device_id),\n\t\t\t\tdirection: direction as \"incoming\" | \"outgoing\",\n\t\t\t\tstatus,\n\t\t\t});\n\t\t\treturn c.json({ items });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// POST /v1/reciprocal-approvals — register a local trust action\n\t// -----------------------------------------------------------------------\n\n\tapp.post(\"/v1/reciprocal-approvals\", async (c) => {\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) {\n\t\t\treturn c.json({ error: \"body_too_large\" }, 413);\n\t\t}\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst requestedDeviceId = String(data.requested_device_id ?? \"\").trim();\n\t\tconst expectedIncomingRequestId = Object.hasOwn(data, \"expected_incoming_request_id\")\n\t\t\t? String(data.expected_incoming_request_id ?? \"\").trim()\n\t\t\t: undefined;\n\t\tif (!groupId || !requestedDeviceId) {\n\t\t\treturn c.json({ error: \"group_id_and_requested_device_id_required\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst auth = await authorizeRequest(store, runtime, requestVerifier, {\n\t\t\t\tmethod: c.req.method,\n\t\t\t\turl: c.req.url,\n\t\t\t\tgroupId,\n\t\t\t\tbody: raw,\n\t\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t\t});\n\t\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\t\treturn (\n\t\t\t\t\trateLimitedResponse(c, c.req.path, false) ??\n\t\t\t\t\tc.json({ error: auth.error }, authErrorStatus(auth.error))\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst limited = rateLimitedResponse(c, String(auth.enrollment.device_id), true);\n\t\t\tif (limited) return limited;\n\t\t\tif (requestedDeviceId === String(auth.enrollment.device_id)) {\n\t\t\t\treturn c.json({ error: \"requested_device_must_differ\" }, 400);\n\t\t\t}\n\t\t\tconst targetEnrollment = await store.getEnrollment(groupId, requestedDeviceId);\n\t\t\tif (!targetEnrollment) {\n\t\t\t\treturn c.json({ error: \"requested_device_not_found\" }, 404);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst request = await store.createReciprocalApproval({\n\t\t\t\t\tgroupId,\n\t\t\t\t\trequestingDeviceId: String(auth.enrollment.device_id),\n\t\t\t\t\trequestedDeviceId,\n\t\t\t\t\t...(expectedIncomingRequestId !== undefined ? { expectedIncomingRequestId } : {}),\n\t\t\t\t});\n\t\t\t\treturn c.json({ ok: true, request });\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof CoordinatorReciprocalApprovalRequestChangedError) {\n\t\t\t\t\treturn c.json({ error: error.code }, 409);\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// POST /v1/invites/add-device — create an Identity-owned device invite\n\t// -----------------------------------------------------------------------\n\n\tapp.post(\"/v1/invites/add-device\", async (c) => {\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst allowedFields = new Set([\n\t\t\t\"group_id\",\n\t\t\t\"expires_at\",\n\t\t\t\"reviewed_preview_digest\",\n\t\t\t\"reviewed_intent\",\n\t\t]);\n\t\tif (Object.keys(data).some((key) => !allowedFields.has(key))) {\n\t\t\treturn c.json({ error: \"unexpected_add_device_invite_fields\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst expiresAt = String(data.expires_at ?? \"\").trim();\n\t\tconst reviewedPreviewDigest = String(data.reviewed_preview_digest ?? \"\").trim();\n\t\tif (!groupId || !expiresAt) {\n\t\t\treturn c.json({ error: \"group_id_and_expires_at_required\" }, 400);\n\t\t}\n\t\tif (Number.isNaN(new Date(expiresAt).getTime())) {\n\t\t\treturn c.json({ error: \"invalid_expires_at\" }, 400);\n\t\t}\n\t\tif (!/^[a-f0-9]{64}$/u.test(reviewedPreviewDigest)) {\n\t\t\treturn c.json({ error: \"reviewed_preview_digest_invalid\" }, 400);\n\t\t}\n\t\tif (data.reviewed_intent == null) {\n\t\t\treturn c.json({ error: \"recipient_invite_review_unavailable\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst auth = await authorizeRequest(store, runtime, requestVerifier, {\n\t\t\t\tmethod: c.req.method,\n\t\t\t\turl: c.req.url,\n\t\t\t\tgroupId,\n\t\t\t\tbody: raw,\n\t\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t\t});\n\t\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\t\treturn (\n\t\t\t\t\trateLimitedResponse(c, c.req.path, false) ??\n\t\t\t\t\tc.json({ error: auth.error }, authErrorStatus(auth.error))\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst limited = rateLimitedResponse(c, String(auth.enrollment.device_id), true);\n\t\t\tif (limited) return limited;\n\n\t\t\tconst targetIdentityId = auth.enrollment.identity_id;\n\t\t\tif (\n\t\t\t\t!targetIdentityId ||\n\t\t\t\ttargetIdentityId !== targetIdentityId.trim() ||\n\t\t\t\ttargetIdentityId.length > 256 ||\n\t\t\t\t/[\\p{Cc}\\p{Cf}]/u.test(targetIdentityId)\n\t\t\t) {\n\t\t\t\treturn c.json({ error: \"identity_binding_required\" }, 403);\n\t\t\t}\n\n\t\t\tlet reviewedIntent: RecipientReviewedIntentV1;\n\t\t\ttry {\n\t\t\t\treviewedIntent = await verifyRecipientReviewedIntent(data.reviewed_intent, {\n\t\t\t\t\ttarget: { kind: \"add_device\", targetIdentityId },\n\t\t\t\t\tdigest: reviewedPreviewDigest,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (\n\t\t\t\t\terror instanceof RecipientReviewedIntentError &&\n\t\t\t\t\terror.code === \"recipient_invite_intent_mismatch\"\n\t\t\t\t) {\n\t\t\t\t\treturn c.json({ error: error.code }, 409);\n\t\t\t\t}\n\t\t\t\treturn c.json({ error: \"recipient_invite_review_unavailable\" }, 400);\n\t\t\t}\n\n\t\t\tconst invite = await store.createInvite({\n\t\t\t\tgroupId,\n\t\t\t\tpolicy: \"auto_admit\",\n\t\t\t\texpiresAt,\n\t\t\t\tcreatedBy: targetIdentityId,\n\t\t\t\tinviterDeviceId: String(auth.enrollment.device_id),\n\t\t\t\tinviteKind: \"add_device\",\n\t\t\t\ttargetIdentityId,\n\t\t\t\treviewedPreviewDigest,\n\t\t\t\treviewedIntent,\n\t\t\t});\n\t\t\tconst payload: InvitePayload = {\n\t\t\t\tv: 1,\n\t\t\t\tkind: \"add_device\",\n\t\t\t\tcoordinator_url: new URL(c.req.url).origin,\n\t\t\t\tgroup_id: groupId,\n\t\t\t\tpolicy: invite.policy,\n\t\t\t\ttoken: String(invite.token ?? \"\"),\n\t\t\t\texpires_at: invite.expires_at,\n\t\t\t\tteam_name: (invite.team_name_snapshot as string) ?? null,\n\t\t\t\ttarget_identity_id: invite.target_identity_id ?? undefined,\n\t\t\t\tinviter_device_id: invite.inviter_device_id ?? undefined,\n\t\t\t\treviewed_preview_digest: invite.reviewed_preview_digest ?? undefined,\n\t\t\t};\n\t\t\tconst encoded = encodeInvitePayload(payload);\n\t\t\tconst { token: _token, ...inviteWithoutToken } = invite;\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\tinvite: inviteWithoutToken,\n\t\t\t\tpayload,\n\t\t\t\tencoded,\n\t\t\t\tlink: inviteLink(encoded),\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// Admin routes\n\t// -----------------------------------------------------------------------\n\n\t// POST /v1/admin/devices — enroll a device\n\tapp.post(\"/v1/admin/devices\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst deviceId = String(data.device_id ?? \"\").trim();\n\t\tconst fingerprint = String(data.fingerprint ?? \"\").trim();\n\t\tconst publicKey = String(data.public_key ?? \"\").trim();\n\t\tconst displayName = String(data.display_name ?? \"\").trim() || null;\n\n\t\tif (!groupId || !deviceId || !fingerprint || !publicKey) {\n\t\t\treturn c.json({ error: \"group_id_device_id_fingerprint_public_key_required\" }, 400);\n\t\t}\n\t\tif (fingerprintPublicKey(publicKey) !== fingerprint) {\n\t\t\treturn c.json({ error: \"fingerprint_mismatch\" }, 400);\n\t\t}\n\n\t\treturn enrollAdminDevice(c, createStore(), groupId, {\n\t\t\tdeviceId,\n\t\t\tfingerprint,\n\t\t\tpublicKey,\n\t\t\tdisplayName,\n\t\t});\n\t});\n\n\t// GET /v1/admin/groups — list coordinator groups\n\tapp.get(\"/v1/admin/groups\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst includeArchived = [\"1\", \"true\", \"yes\"].includes(\n\t\t\t(c.req.query(\"include_archived\") ?? \"0\").trim().toLowerCase(),\n\t\t);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\treturn c.json({ items: await store.listGroups(includeArchived) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/admin/groups\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst displayName = String(data.display_name ?? \"\").trim() || null;\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tawait store.createGroup(groupId, displayName);\n\t\t\treturn c.json({ ok: true, group: await store.getGroup(groupId) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/admin/groups/rename\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst displayName = String(data.display_name ?? \"\").trim();\n\t\tif (!groupId || !displayName) {\n\t\t\treturn c.json({ error: \"group_id_and_display_name_required\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.renameGroup(groupId, displayName);\n\t\t\tif (!ok) return c.json({ error: \"group_not_found\" }, 404);\n\t\t\treturn c.json({ ok: true, group: await store.getGroup(groupId) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/admin/groups/archive\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.archiveGroup(groupId, runtime.now());\n\t\t\tif (!ok) return c.json({ error: \"group_not_found_or_already_archived\" }, 404);\n\t\t\treturn c.json({ ok: true, group: await store.getGroup(groupId) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/admin/groups/unarchive\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.unarchiveGroup(groupId);\n\t\t\tif (!ok) return c.json({ error: \"group_not_found_or_not_archived\" }, 404);\n\t\t\treturn c.json({ ok: true, group: await store.getGroup(groupId) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// GET /v1/admin/groups/:group_id/scopes — list Sharing domains for a group\n\tapp.get(\"/v1/admin/groups/:group_id/scopes\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst groupError = await requireActiveAdminGroup(store, groupId, c);\n\t\t\tif (groupError) return groupError;\n\t\t\tconst includeInactive = queryFlag(c.req.query(\"include_inactive\"));\n\t\t\treturn c.json({\n\t\t\t\titems: await store.listScopes({ groupId, includeInactive }),\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/groups/:group_id/scopes — create a Sharing domain\n\tapp.post(\"/v1/admin/groups/:group_id/scopes\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = optionalString(data, \"scope_id\");\n\t\tconst label = optionalString(data, \"label\");\n\t\tconst membershipEpoch = optionalNumber(data, \"membership_epoch\");\n\t\tif (!scopeId || !label) return c.json({ error: \"scope_id_and_label_required\" }, 400);\n\t\tif (Number.isNaN(membershipEpoch)) {\n\t\t\treturn c.json({ error: \"membership_epoch_must_be_number\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst groupError = await requireActiveAdminGroup(store, groupId, c);\n\t\t\tif (groupError) return groupError;\n\t\t\tconst scope = await store.createScope({\n\t\t\t\tscopeId,\n\t\t\t\tlabel,\n\t\t\t\tkind: optionalString(data, \"kind\"),\n\t\t\t\tauthorityType: optionalString(data, \"authority_type\"),\n\t\t\t\tcoordinatorId: optionalString(data, \"coordinator_id\"),\n\t\t\t\tgroupId,\n\t\t\t\tmanifestIssuerDeviceId: optionalString(data, \"manifest_issuer_device_id\"),\n\t\t\t\tmembershipEpoch,\n\t\t\t\tmanifestHash: optionalString(data, \"manifest_hash\"),\n\t\t\t\tstatus: optionalString(data, \"status\"),\n\t\t\t});\n\t\t\treturn c.json({ ok: true, scope }, 201);\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error) }, 400);\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// PATCH /v1/admin/groups/:group_id/scopes/:scope_id — update Sharing domain metadata\n\tapp.patch(\"/v1/admin/groups/:group_id/scopes/:scope_id\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = String(c.req.param(\"scope_id\") ?? \"\").trim();\n\t\tconst membershipEpoch = optionalNumber(data, \"membership_epoch\");\n\t\tif (!scopeId) return c.json({ error: \"scope_id_required\" }, 400);\n\t\tif (Number.isNaN(membershipEpoch)) {\n\t\t\treturn c.json({ error: \"membership_epoch_must_be_number\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst lookup = await findAdminScope(store, groupId, scopeId, c);\n\t\t\tif (lookup.response) return lookup.response;\n\t\t\tconst scope = await store.updateScope({\n\t\t\t\tscopeId,\n\t\t\t\tlabel: data.label === undefined ? undefined : optionalString(data, \"label\"),\n\t\t\t\tkind: data.kind === undefined ? undefined : optionalString(data, \"kind\"),\n\t\t\t\tauthorityType:\n\t\t\t\t\tdata.authority_type === undefined ? undefined : optionalString(data, \"authority_type\"),\n\t\t\t\tcoordinatorId:\n\t\t\t\t\tdata.coordinator_id === undefined ? undefined : optionalString(data, \"coordinator_id\"),\n\t\t\t\tgroupId,\n\t\t\t\tmanifestIssuerDeviceId:\n\t\t\t\t\tdata.manifest_issuer_device_id === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: optionalString(data, \"manifest_issuer_device_id\"),\n\t\t\t\tmembershipEpoch,\n\t\t\t\tmanifestHash:\n\t\t\t\t\tdata.manifest_hash === undefined ? undefined : optionalString(data, \"manifest_hash\"),\n\t\t\t\tstatus: data.status === undefined ? undefined : optionalString(data, \"status\"),\n\t\t\t});\n\t\t\tif (!scope) return c.json({ error: \"scope_not_found\" }, 404);\n\t\t\treturn c.json({ ok: true, scope });\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error) }, 400);\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// GET /v1/admin/groups/:group_id/scopes/:scope_id/members — list explicit grants\n\tapp.get(\"/v1/admin/groups/:group_id/scopes/:scope_id/members\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = String(c.req.param(\"scope_id\") ?? \"\").trim();\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst lookup = await findAdminScope(store, groupId, scopeId, c);\n\t\t\tif (lookup.response) return lookup.response;\n\t\t\treturn c.json({\n\t\t\t\titems: await store.listScopeMemberships(scopeId, queryFlag(c.req.query(\"include_revoked\"))),\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/groups/:group_id/scopes/:scope_id/members — grant device access\n\tapp.post(\"/v1/admin/groups/:group_id/scopes/:scope_id/members\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = String(c.req.param(\"scope_id\") ?? \"\").trim();\n\t\tconst effectId = optionalString(data, \"effect_id\");\n\t\tconst deviceId = optionalString(data, \"device_id\");\n\t\tconst membershipEpoch = optionalNumber(data, \"membership_epoch\");\n\t\tif (!effectId) return c.json({ error: \"effect_id_required\" }, 400);\n\t\tif (!deviceId) return c.json({ error: \"device_id_required\" }, 400);\n\t\tif (Number.isNaN(membershipEpoch)) {\n\t\t\treturn c.json({ error: \"membership_epoch_must_be_number\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst lookup = await findAdminScope(store, groupId, scopeId, c);\n\t\t\tif (lookup.response) return lookup.response;\n\t\t\tconst membership = await store.grantScopeMembership({\n\t\t\t\teffectId,\n\t\t\t\tscopeId,\n\t\t\t\tdeviceId,\n\t\t\t\trole: optionalString(data, \"role\"),\n\t\t\t\tmembershipEpoch,\n\t\t\t\tcoordinatorId: optionalString(data, \"coordinator_id\"),\n\t\t\t\tgroupId,\n\t\t\t\tmanifestIssuerDeviceId: optionalString(data, \"manifest_issuer_device_id\"),\n\t\t\t\tmanifestHash: optionalString(data, \"manifest_hash\"),\n\t\t\t\tsignedManifestJson: optionalString(data, \"signed_manifest_json\"),\n\t\t\t\tactorType: \"admin\",\n\t\t\t\tactorId: optionalHeaderString(c.req.header(ADMIN_ACTOR_HEADER)),\n\t\t\t});\n\t\t\treturn c.json({ ok: true, membership }, 201);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tif (\n\t\t\t\terror instanceof CoordinatorMembershipError &&\n\t\t\t\t(error.code === \"scope_not_found\" || error.code === \"scope_group_mismatch\")\n\t\t\t) {\n\t\t\t\treturn c.json({ error: \"scope_not_found\" }, 404);\n\t\t\t}\n\t\t\tif (error instanceof CoordinatorMembershipError && error.code === \"device_not_enrolled\") {\n\t\t\t\treturn c.json({ error: \"device_not_enrolled_for_scope_group\" }, 404);\n\t\t\t}\n\t\t\tconst scopeInactive =\n\t\t\t\terror instanceof CoordinatorMembershipError && error.code === \"scope_inactive\";\n\t\t\treturn c.json(\n\t\t\t\t{ error: scopeInactive ? \"scope_not_active\" : message },\n\t\t\t\tmessage === SCOPE_MEMBERSHIP_EFFECT_CONFLICT || scopeInactive ? 409 : 400,\n\t\t\t);\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/groups/:group_id/scopes/:scope_id/members/:device_id/revoke\n\tapp.post(\"/v1/admin/groups/:group_id/scopes/:scope_id/members/:device_id/revoke\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = raw.byteLength > 0 ? parseJsonObject(raw) : {};\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = String(c.req.param(\"scope_id\") ?? \"\").trim();\n\t\tconst deviceId = String(c.req.param(\"device_id\") ?? \"\").trim();\n\t\tconst effectId = optionalString(data, \"effect_id\");\n\t\tconst membershipEpoch = optionalNumber(data, \"membership_epoch\");\n\t\tif (!effectId) return c.json({ error: \"effect_id_required\" }, 400);\n\t\tif (!deviceId) return c.json({ error: \"device_id_required\" }, 400);\n\t\tif (Number.isNaN(membershipEpoch)) {\n\t\t\treturn c.json({ error: \"membership_epoch_must_be_number\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst lookup = await findAdminScope(store, groupId, scopeId, c);\n\t\t\tif (lookup.response) return lookup.response;\n\t\t\tconst ok = await store.revokeScopeMembership({\n\t\t\t\teffectId,\n\t\t\t\tscopeId,\n\t\t\t\tdeviceId,\n\t\t\t\tgroupId,\n\t\t\t\tmembershipEpoch,\n\t\t\t\tmanifestHash: optionalString(data, \"manifest_hash\"),\n\t\t\t\tsignedManifestJson: optionalString(data, \"signed_manifest_json\"),\n\t\t\t\tactorType: \"admin\",\n\t\t\t\tactorId: optionalHeaderString(c.req.header(ADMIN_ACTOR_HEADER)),\n\t\t\t});\n\t\t\tif (!ok) return c.json({ error: \"membership_not_found\" }, 404);\n\t\t\tlet revokedMembership: CoordinatorScopeMembership | undefined;\n\t\t\ttry {\n\t\t\t\trevokedMembership = (await store.listScopeMemberships(scopeId, true)).find(\n\t\t\t\t\t(membership) => membership.device_id === deviceId,\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\trevokedMembership = undefined;\n\t\t\t}\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tdevice_id: deviceId,\n\t\t\t\trevocation: explainScopeMembershipRevocation({\n\t\t\t\t\tscopeId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tmembershipEpoch: revokedMembership?.membership_epoch ?? membershipEpoch,\n\t\t\t\t}),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tif (error instanceof CoordinatorMembershipError && error.code === \"scope_group_mismatch\") {\n\t\t\t\treturn c.json({ error: \"scope_not_found\" }, 404);\n\t\t\t}\n\t\t\treturn c.json({ error: message }, message === SCOPE_MEMBERSHIP_EFFECT_CONFLICT ? 409 : 400);\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// GET /v1/admin/devices — list enrolled devices\n\tapp.get(\"/v1/admin/devices\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\n\t\tconst includeDisabled = [\"1\", \"true\", \"yes\"].includes(\n\t\t\t(c.req.query(\"include_disabled\") ?? \"0\").trim().toLowerCase(),\n\t\t);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\treturn c.json({ items: await store.listEnrolledDevices(groupId, includeDisabled) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/devices/rename\n\tapp.post(\"/v1/admin/devices/rename\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst deviceId = String(data.device_id ?? \"\").trim();\n\t\tconst displayName = String(data.display_name ?? \"\").trim();\n\n\t\tif (!groupId || !deviceId) {\n\t\t\treturn c.json({ error: \"group_id_and_device_id_required\" }, 400);\n\t\t}\n\t\tif (!displayName) {\n\t\t\treturn c.json({ error: \"display_name_required\" }, 400);\n\t\t}\n\t\tlet normalizedDisplayName: string;\n\t\ttry {\n\t\t\tnormalizedDisplayName = normalizeHumanPresentationName(displayName, \"display_name\");\n\t\t} catch (error) {\n\t\t\treturn c.json(\n\t\t\t\t{ error: error instanceof Error ? error.message : \"display_name_invalid\" },\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.renameDevice(groupId, deviceId, normalizedDisplayName);\n\t\t\tif (!ok) return c.json({ error: \"device_not_found\" }, 404);\n\t\t\tconst device = await store.getEnrollment(groupId, deviceId);\n\t\t\treturn c.json({ ok: true, device });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/devices/disable\n\tapp.post(\"/v1/admin/devices/disable\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst deviceId = String(data.device_id ?? \"\").trim();\n\n\t\tif (!groupId || !deviceId) {\n\t\t\treturn c.json({ error: \"group_id_and_device_id_required\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.setDeviceEnabled(groupId, deviceId, false);\n\t\t\tif (!ok) return c.json({ error: \"device_not_found\" }, 404);\n\t\t\treturn c.json({ ok: true });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/devices/enable\n\tapp.post(\"/v1/admin/devices/enable\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst deviceId = String(data.device_id ?? \"\").trim();\n\n\t\tif (!groupId || !deviceId) {\n\t\t\treturn c.json({ error: \"group_id_and_device_id_required\" }, 400);\n\t\t}\n\n\t\treturn enableAdminDevice(c, createStore(), groupId, deviceId);\n\t});\n\n\t// POST /v1/admin/devices/remove\n\tapp.post(\"/v1/admin/devices/remove\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst deviceId = String(data.device_id ?? \"\").trim();\n\n\t\tif (!groupId || !deviceId) {\n\t\t\treturn c.json({ error: \"group_id_and_device_id_required\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.removeDevice(groupId, deviceId);\n\t\t\tif (!ok) return c.json({ error: \"device_not_found\" }, 404);\n\t\t\treturn c.json({ ok: true });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/admin/legacy-team-completions\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\t\tconst raw = await readRequestBytes(c, MAX_LEGACY_TEAM_COMPLETION_BODY_BYTES);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\t\tif (Object.keys(data).some((key) => key !== \"group_id\" && key !== \"manifest\")) {\n\t\t\treturn c.json({ error: \"completion_manifest_invalid\" }, 400);\n\t\t}\n\t\tlet groupId: string;\n\t\tlet manifest: CoordinatorLegacyTeamCompletionManifestV1;\n\t\ttry {\n\t\t\tconst groupIds = normalizeCoordinatorLegacyTeamCompletionGroupIds([data.group_id]);\n\t\t\tconst normalizedGroupId = groupIds[0];\n\t\t\tif (!normalizedGroupId) throw new Error(\"completion_manifest_invalid\");\n\t\t\tgroupId = normalizedGroupId;\n\t\t\tmanifest = normalizeCoordinatorLegacyTeamCompletionManifest(data.manifest);\n\t\t\trequireCoordinatorLegacyTeamCompletionTeamBinding(manifest);\n\t\t} catch {\n\t\t\treturn c.json({ error: \"completion_manifest_invalid\" }, 400);\n\t\t}\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst result = await store.createLegacyTeamCompletion(groupId, manifest);\n\t\t\treturn c.json({ ok: true, ...result }, result.status === \"created\" ? 201 : 200);\n\t\t} catch (error) {\n\t\t\tif (error instanceof CoordinatorLegacyTeamCompletionConflictError) {\n\t\t\t\treturn c.json({ error: error.code }, 409);\n\t\t\t}\n\t\t\tconst code = error instanceof Error ? error.message : \"completion_manifest_invalid\";\n\t\t\tif (code === \"group_not_found\") return c.json({ error: code }, 404);\n\t\t\tif (code === \"group_archived\") return c.json({ error: code }, 409);\n\t\t\tif (code === \"completion_manifest_unavailable\") {\n\t\t\t\treturn c.json({ error: code }, 409);\n\t\t\t}\n\t\t\tif (code === \"completion_manifest_invalid\") return c.json({ error: code }, 400);\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.get(\"/v1/admin/legacy-team-completions\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\t\tconst groupId = String(c.req.query(\"group_id\") ?? \"\").trim();\n\t\tlet candidateRef: string;\n\t\ttry {\n\t\t\tif (normalizeCoordinatorLegacyTeamCompletionGroupIds([groupId]).length !== 1) {\n\t\t\t\tthrow new Error(\"completion_manifest_invalid\");\n\t\t\t}\n\t\t\tcandidateRef = normalizeCoordinatorLegacyTeamCompletionCandidateRef(\n\t\t\t\tc.req.query(\"candidate_ref\"),\n\t\t\t);\n\t\t} catch {\n\t\t\treturn c.json({ error: \"group_id_and_candidate_ref_required\" }, 400);\n\t\t}\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst manifest = await store.getLegacyTeamCompletion(groupId, candidateRef);\n\t\t\treturn manifest ? c.json({ manifest }) : c.json({ error: \"completion_not_found\" }, 404);\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/admin/legacy-team-completions/query\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data || Object.keys(data).some((key) => key !== \"group_ids\")) {\n\t\t\treturn c.json({ error: \"completion_query_invalid\" }, 400);\n\t\t}\n\t\tlet groupIds: string[];\n\t\ttry {\n\t\t\tgroupIds = normalizeCoordinatorLegacyTeamCompletionGroupIds(data.group_ids);\n\t\t\tif (groupIds.length === 0) throw new Error(\"completion_query_invalid\");\n\t\t} catch {\n\t\t\treturn c.json({ error: \"completion_query_invalid\" }, 400);\n\t\t}\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\treturn c.json({ items: await store.listLegacyTeamCompletions(groupIds) });\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"completion_results_too_large\") {\n\t\t\t\treturn c.json({ error: error.message }, 413);\n\t\t\t}\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/invites — create an invite\n\tapp.post(\"/v1/admin/invites\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst policy = String(data.policy ?? \"auto_admit\").trim();\n\t\tconst expiresAt = String(data.expires_at ?? \"\").trim();\n\t\tconst createdBy = String(data.created_by ?? \"\").trim() || null;\n\t\tconst operationId = String(data.operation_id ?? \"\").trim() || null;\n\t\tconst reviewedProjectSetDigest = String(data.reviewed_project_set_digest ?? \"\").trim() || null;\n\t\tconst inviterActorId = String(data.inviter_actor_id ?? \"\").trim() || null;\n\t\tconst inviterDisplayName = String(data.inviter_display_name ?? \"\").trim() || null;\n\t\tconst inviterDeviceId = String(data.inviter_device_id ?? \"\").trim() || null;\n\t\tconst pendingPersonId = String(data.pending_person_id ?? \"\").trim() || null;\n\t\tconst requestedInviteKind = String(data.invite_kind ?? data.kind ?? \"\").trim();\n\t\tconst policyTeamId = String(data.policy_team_id ?? \"\").trim() || null;\n\t\tconst targetIdentityId = String(data.target_identity_id ?? \"\").trim() || null;\n\t\tconst reviewedPreviewDigest = String(data.reviewed_preview_digest ?? \"\").trim() || null;\n\t\tlet reviewedIntent: RecipientReviewedIntentV1 | undefined;\n\t\tlet projectSummaries: ReturnType<typeof normalizeProjectInviteSummaries> | null = null;\n\t\tlet projectIntent: Array<{\n\t\t\tcanonical_identity: string;\n\t\t\tdisplay_name: string;\n\t\t\texisting_memory_count: number;\n\t\t}> | null = null;\n\n\t\tif (!groupId || ![\"auto_admit\", \"approval_required\"].includes(policy) || !expiresAt) {\n\t\t\treturn c.json({ error: \"group_id_policy_and_expires_at_required\" }, 400);\n\t\t}\n\t\tif (Object.hasOwn(data, \"assigned_identity_id\")) {\n\t\t\treturn c.json({ error: \"assigned_identity_id_forbidden\" }, 400);\n\t\t}\n\t\t// Validate the date at the boundary so store.createInvite's\n\t\t// normalizeInviteExpiresAt throw can't escape as an unhandled 500.\n\t\tif (Number.isNaN(new Date(expiresAt).getTime())) {\n\t\t\treturn c.json({ error: \"invalid_expires_at\" }, 400);\n\t\t}\n\t\tif (Boolean(operationId) !== Boolean(reviewedProjectSetDigest)) {\n\t\t\treturn c.json({ error: \"operation_intent_reference_incomplete\" }, 400);\n\t\t}\n\t\tconst inviteKind = (requestedInviteKind ||\n\t\t\t(operationId ? \"project_share\" : \"legacy_enrollment\")) as CoordinatorInviteKind;\n\t\tif (\n\t\t\t!([\"legacy_enrollment\", \"project_share\", \"team_member\", \"add_device\"] as const).includes(\n\t\t\t\tinviteKind,\n\t\t\t)\n\t\t) {\n\t\t\treturn c.json({ error: \"invite_kind_invalid\" }, 400);\n\t\t}\n\t\tif (inviteKind === \"project_share\" ? !operationId : Boolean(operationId)) {\n\t\t\treturn c.json({ error: \"invite_kind_intent_mismatch\" }, 400);\n\t\t}\n\t\tif (reviewedPreviewDigest && !/^[a-f0-9]{64}$/u.test(reviewedPreviewDigest)) {\n\t\t\treturn c.json({ error: \"reviewed_preview_digest_invalid\" }, 400);\n\t\t}\n\t\tif (\n\t\t\t(inviteKind === \"team_member\" &&\n\t\t\t\t(!policyTeamId || !reviewedPreviewDigest || Boolean(targetIdentityId))) ||\n\t\t\t(inviteKind === \"add_device\" &&\n\t\t\t\t(!targetIdentityId || !reviewedPreviewDigest || Boolean(policyTeamId))) ||\n\t\t\t(![\"team_member\", \"add_device\"].includes(inviteKind) &&\n\t\t\t\tBoolean(policyTeamId || targetIdentityId || reviewedPreviewDigest))\n\t\t) {\n\t\t\treturn c.json({ error: \"recipient_invite_metadata_invalid\" }, 400);\n\t\t}\n\t\tif (\n\t\t\t[policyTeamId, targetIdentityId]\n\t\t\t\t.filter((value): value is string => Boolean(value))\n\t\t\t\t.some((value) => value.length > 256 || /[\\p{Cc}\\p{Cf}]/u.test(value))\n\t\t) {\n\t\t\treturn c.json({ error: \"recipient_invite_identifier_invalid\" }, 400);\n\t\t}\n\t\tif (inviteKind === \"team_member\" || inviteKind === \"add_device\") {\n\t\t\tif (data.reviewed_intent == null) {\n\t\t\t\treturn c.json({ error: \"recipient_invite_review_unavailable\" }, 400);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treviewedIntent = await verifyRecipientReviewedIntent(data.reviewed_intent, {\n\t\t\t\t\ttarget:\n\t\t\t\t\t\tinviteKind === \"team_member\"\n\t\t\t\t\t\t\t? { kind: \"team_member\", policyTeamId: String(policyTeamId) }\n\t\t\t\t\t\t\t: { kind: \"add_device\", targetIdentityId: String(targetIdentityId) },\n\t\t\t\t\tdigest: String(reviewedPreviewDigest),\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (\n\t\t\t\t\terror instanceof RecipientReviewedIntentError &&\n\t\t\t\t\terror.code === \"recipient_invite_intent_mismatch\"\n\t\t\t\t) {\n\t\t\t\t\treturn c.json({ error: error.code }, 409);\n\t\t\t\t}\n\t\t\t\treturn c.json({ error: \"recipient_invite_review_unavailable\" }, 400);\n\t\t\t}\n\t\t} else if (data.reviewed_intent != null) {\n\t\t\treturn c.json({ error: \"recipient_invite_metadata_invalid\" }, 400);\n\t\t}\n\t\tif (\n\t\t\t(operationId && !/^share_[a-f0-9]{40}$/u.test(operationId)) ||\n\t\t\t(reviewedProjectSetDigest && !/^[a-f0-9]{64}$/u.test(reviewedProjectSetDigest))\n\t\t) {\n\t\t\treturn c.json({ error: \"operation_intent_reference_invalid\" }, 400);\n\t\t}\n\t\tif (operationId) {\n\t\t\tif (!inviterActorId || !inviterDisplayName || !inviterDeviceId || !pendingPersonId) {\n\t\t\t\treturn c.json({ error: \"project_invite_identity_context_required\" }, 400);\n\t\t\t}\n\t\t\tif (\n\t\t\t\t[inviterActorId, inviterDeviceId, pendingPersonId].some(\n\t\t\t\t\t(value) => value.length > 256 || /[\\p{Cc}\\p{Cf}]/u.test(value),\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\treturn c.json({ error: \"project_invite_identity_context_invalid\" }, 400);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tnormalizeHumanPresentationName(inviterDisplayName, \"inviter_display_name\");\n\t\t\t\tprojectSummaries = normalizeProjectInviteSummaries(data.project_summaries);\n\t\t\t\tif (\n\t\t\t\t\t!Array.isArray(data.project_intent) ||\n\t\t\t\t\tdata.project_intent.length !== projectSummaries.length\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"project_intent_invalid\");\n\t\t\t\t}\n\t\t\t\tprojectIntent = data.project_intent.map((item, index) => {\n\t\t\t\t\tlet parsed: ReturnType<typeof parseAcceptedProjectIntent>[number] | undefined;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tparsed = parseAcceptedProjectIntent([item])[0];\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tthrow new Error(\"project_intent_invalid\");\n\t\t\t\t\t}\n\t\t\t\t\tconst summary = projectSummaries?.[index];\n\t\t\t\t\tif (\n\t\t\t\t\t\t!parsed ||\n\t\t\t\t\t\t!summary ||\n\t\t\t\t\t\tparsed.display_name !== summary.display_name ||\n\t\t\t\t\t\tparsed.existing_memory_count !== summary.existing_memory_count\n\t\t\t\t\t) {\n\t\t\t\t\t\tthrow new Error(\"project_intent_invalid\");\n\t\t\t\t\t}\n\t\t\t\t\treturn parsed;\n\t\t\t\t});\n\t\t\t\tif (\n\t\t\t\t\tnew Set(projectIntent.map((item) => item.canonical_identity)).size !==\n\t\t\t\t\tprojectIntent.length\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"project_intent_invalid\");\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{ error: error instanceof Error ? error.message : \"project_invite_invalid\" },\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst group = await store.getGroup(groupId);\n\t\t\tif (!group) return c.json({ error: \"group_not_found\" }, 404);\n\t\t\tif (group.archived_at) return c.json({ error: \"group_archived\" }, 409);\n\n\t\t\tconst invite = await store.createInvite({\n\t\t\t\tgroupId,\n\t\t\t\tpolicy,\n\t\t\t\texpiresAt,\n\t\t\t\tcreatedBy,\n\t\t\t\toperationId,\n\t\t\t\treviewedProjectSetDigest,\n\t\t\t\tinviterActorId,\n\t\t\t\tinviterDisplayName,\n\t\t\t\tinviterDeviceId,\n\t\t\t\tpendingPersonId,\n\t\t\t\tprojectSummaries,\n\t\t\t\tprojectIntent,\n\t\t\t\tinviteKind,\n\t\t\t\tpolicyTeamId,\n\t\t\t\ttargetIdentityId,\n\t\t\t\treviewedPreviewDigest,\n\t\t\t\treviewedIntent,\n\t\t\t});\n\n\t\t\tconst payload: InvitePayload = {\n\t\t\t\tv: 1,\n\t\t\t\tkind:\n\t\t\t\t\tinvite.invite_kind === \"team_member\" || invite.invite_kind === \"add_device\"\n\t\t\t\t\t\t? invite.invite_kind\n\t\t\t\t\t\t: \"coordinator_team_invite\",\n\t\t\t\tcoordinator_url: String(data.coordinator_url ?? \"\").trim(),\n\t\t\t\tgroup_id: groupId,\n\t\t\t\tpolicy: invite.policy,\n\t\t\t\ttoken: String(invite.token ?? \"\"),\n\t\t\t\texpires_at: invite.expires_at,\n\t\t\t\tteam_name: (invite.team_name_snapshot as string) ?? null,\n\t\t\t\t...(invite.operation_id\n\t\t\t\t\t? {\n\t\t\t\t\t\t\toperation_id: invite.operation_id,\n\t\t\t\t\t\t\tinviter_name: invite.inviter_display_name ?? null,\n\t\t\t\t\t\t\tproject_summaries: projectSummaries ?? [],\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t...(invite.invite_kind === \"team_member\"\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tpolicy_team_id: invite.policy_team_id ?? undefined,\n\t\t\t\t\t\t\tassigned_identity_id: invite.assigned_identity_id ?? undefined,\n\t\t\t\t\t\t\treviewed_preview_digest: invite.reviewed_preview_digest ?? undefined,\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t...(invite.invite_kind === \"add_device\"\n\t\t\t\t\t? {\n\t\t\t\t\t\t\ttarget_identity_id: invite.target_identity_id ?? undefined,\n\t\t\t\t\t\t\tinviter_device_id: invite.inviter_device_id ?? undefined,\n\t\t\t\t\t\t\treviewed_preview_digest: invite.reviewed_preview_digest ?? undefined,\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t};\n\t\t\tconst encoded = encodeInvitePayload(payload);\n\n\t\t\t// Omit token from the returned invite object (matches Python)\n\t\t\tconst { token: _token, ...inviteWithoutToken } = invite;\n\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\tinvite: inviteWithoutToken,\n\t\t\t\tpayload,\n\t\t\t\tencoded,\n\t\t\t\tlink: inviteLink(encoded),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"invite_operation_intent_conflict\") {\n\t\t\t\treturn c.json({ error: \"invite_operation_intent_conflict\" }, 409);\n\t\t\t}\n\t\t\tif (error instanceof Error && error.message === \"invite_already_bound\") {\n\t\t\t\treturn c.json({ error: \"invite_already_bound\" }, 409);\n\t\t\t}\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/invites/inspect\", async (c) => {\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\t\tconst token = String(data.token ?? \"\").trim();\n\t\tif (!token) return c.json({ error: \"invite_invalid\" }, 404);\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst invite = await store.getInviteByTokenForInspection(token);\n\t\t\tif (!invite || invite.revoked_at) return c.json({ error: \"invite_invalid\" }, 404);\n\t\t\tif (invite.invite_kind === \"team_member\" || invite.invite_kind === \"add_device\") {\n\t\t\t\ttry {\n\t\t\t\t\tconst inspection = await store.inspectRecipientInvite({ token, now: runtime.now() });\n\t\t\t\t\tif (!inspection) return c.json({ error: \"invite_invalid\" }, 404);\n\t\t\t\t\treturn c.json(\n\t\t\t\t\t\tinspection.kind === \"team_member\"\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tkind: inspection.kind,\n\t\t\t\t\t\t\t\t\tpolicy_team_id: inspection.policy_team_id,\n\t\t\t\t\t\t\t\t\tassigned_identity_id: inspection.assigned_identity_id,\n\t\t\t\t\t\t\t\t\treviewed_preview_digest: inspection.reviewed_preview_digest,\n\t\t\t\t\t\t\t\t\treviewed_intent: inspection.reviewed_intent,\n\t\t\t\t\t\t\t\t\tbound: inspection.bound,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\tkind: inspection.kind,\n\t\t\t\t\t\t\t\t\ttarget_identity_id: inspection.target_identity_id,\n\t\t\t\t\t\t\t\t\treviewed_preview_digest: inspection.reviewed_preview_digest,\n\t\t\t\t\t\t\t\t\treviewed_intent: inspection.reviewed_intent,\n\t\t\t\t\t\t\t\t\tbound: inspection.bound,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst code = error instanceof Error ? error.message : \"invite_invalid\";\n\t\t\t\t\tconst status = code === \"invite_expired\" ? 410 : code === \"invite_invalid\" ? 404 : 409;\n\t\t\t\t\treturn c.json({ error: code }, status);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst projectInvite = Boolean(invite.operation_id || invite.reviewed_project_set_digest);\n\t\t\tif (\n\t\t\t\tnew Date(invite.expires_at) <= new Date(runtime.now()) &&\n\t\t\t\t(!projectInvite || !invite.consumed_at)\n\t\t\t) {\n\t\t\t\treturn c.json({ error: \"invite_expired\" }, 410);\n\t\t\t}\n\t\t\tif (!invite.operation_id) {\n\t\t\t\treturn c.json({ kind: \"legacy_team_invite\", team_name: invite.team_name_snapshot });\n\t\t\t}\n\t\t\tif (!invite.project_intent_json || !invite.project_summaries_json) {\n\t\t\t\treturn c.json({ error: \"invite_invalid\" }, 404);\n\t\t\t}\n\t\t\tlet projects: ReturnType<typeof normalizeProjectInviteSummaries>;\n\t\t\ttry {\n\t\t\t\tprojects = storedProjectSummaries(invite.project_summaries_json);\n\t\t\t} catch {\n\t\t\t\treturn c.json({ error: \"invite_invalid\" }, 409);\n\t\t\t}\n\t\t\treturn c.json({\n\t\t\t\tkind: \"project_share_invite\",\n\t\t\t\toperation_id: invite.operation_id,\n\t\t\t\tinviter_name: invite.inviter_display_name,\n\t\t\t\tteam_name: invite.team_name_snapshot,\n\t\t\t\tprojects,\n\t\t\t\tbound: Boolean(invite.consumed_at),\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// GET /v1/admin/invites — list invites\n\tapp.get(\"/v1/admin/invites\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst rows = (await store.listInvites(groupId)).map(\n\t\t\t\t({ token: _token, ...inviteWithoutToken }) => inviteWithoutToken,\n\t\t\t);\n\t\t\treturn c.json({ items: rows });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.get(\"/v1/admin/project-invites/:operationId\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok) return c.json({ error: adminAuth.error }, 401);\n\t\tconst operationId = String(c.req.param(\"operationId\") ?? \"\").trim();\n\t\tconst groupId = String(c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!operationId || !groupId)\n\t\t\treturn c.json({ error: \"operation_id_and_group_id_required\" }, 400);\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst invite = await store.getInviteByOperationId(groupId, operationId);\n\t\t\tif (!invite) return c.json({ error: \"operation_not_found\" }, 404);\n\t\t\tlet projects: ReturnType<typeof storedProjectIntent>;\n\t\t\ttry {\n\t\t\t\tprojects = storedProjectIntent(invite.project_intent_json);\n\t\t\t} catch {\n\t\t\t\treturn c.json({ error: \"operation_intent_invalid\" }, 409);\n\t\t\t}\n\t\t\tlet inviteLinkValue: string | null = null;\n\t\t\tif (\n\t\t\t\t!invite.consumed_at &&\n\t\t\t\t!invite.revoked_at &&\n\t\t\t\tnew Date(invite.expires_at) > new Date(runtime.now()) &&\n\t\t\t\tinvite.token &&\n\t\t\t\t!invite.token.startsWith(\"consumed:\")\n\t\t\t) {\n\t\t\t\tconst summaries = projects.map((project) => ({\n\t\t\t\t\tdisplay_name: String(project.display_name ?? \"\"),\n\t\t\t\t\texisting_memory_count: Number(project.existing_memory_count ?? 0),\n\t\t\t\t}));\n\t\t\t\tconst payload: InvitePayload = {\n\t\t\t\t\tv: 1,\n\t\t\t\t\tkind: \"coordinator_team_invite\",\n\t\t\t\t\tcoordinator_url: new URL(c.req.url).origin,\n\t\t\t\t\tgroup_id: invite.group_id,\n\t\t\t\t\tpolicy: invite.policy,\n\t\t\t\t\ttoken: invite.token,\n\t\t\t\t\texpires_at: invite.expires_at,\n\t\t\t\t\tteam_name: invite.team_name_snapshot,\n\t\t\t\t\toperation_id: operationId,\n\t\t\t\t\tinviter_name: invite.inviter_display_name ?? null,\n\t\t\t\t\tproject_summaries: summaries,\n\t\t\t\t};\n\t\t\t\tinviteLinkValue = inviteLink(encodeInvitePayload(payload));\n\t\t\t}\n\t\t\treturn c.json({\n\t\t\t\toperation_id: invite.operation_id,\n\t\t\t\tgroup_id: invite.group_id,\n\t\t\t\treviewed_project_set_digest: invite.reviewed_project_set_digest,\n\t\t\t\tstate: invite.consumed_at ? \"accepted\" : \"waiting_for_acceptance\",\n\t\t\t\tpending_person_id: invite.pending_person_id,\n\t\t\t\trecipient_actor_id: invite.recipient_actor_id,\n\t\t\t\trecipient_display_name: invite.recipient_display_name,\n\t\t\t\trecipient_device_id: invite.bound_device_id,\n\t\t\t\trecipient_device_display_name: invite.recipient_device_display_name,\n\t\t\t\trecipient_public_key: invite.bound_public_key,\n\t\t\t\trecipient_fingerprint: invite.bound_fingerprint,\n\t\t\t\tconsumed_at: invite.consumed_at,\n\t\t\t\tbootstrap_grant_id: invite.bootstrap_grant_id,\n\t\t\t\ttrust_state: invite.trust_state,\n\t\t\t\tprojects,\n\t\t\t\tinvite_link: inviteLinkValue,\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.get(\"/v1/admin/bootstrap-grants/:grantId\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst grantId = String(c.req.param(\"grantId\") ?? \"\").trim();\n\t\tif (!grantId) return c.json({ error: \"grant_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\treturn await bootstrapAuthorizationResponse(c, store, {\n\t\t\t\tgrantId,\n\t\t\t\tnowMs: Date.parse(runtime.now()),\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.get(\"/v1/bootstrap-grants/:grantId\", async (c) => {\n\t\tconst grantId = String(c.req.param(\"grantId\") ?? \"\").trim();\n\t\tconst groupId = String(c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!grantId || !groupId) return c.json({ error: \"grant_id_and_group_id_required\" }, 400);\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst auth = await authorizeRequest(store, runtime, requestVerifier, {\n\t\t\t\tmethod: c.req.method,\n\t\t\t\turl: c.req.url,\n\t\t\t\tgroupId,\n\t\t\t\tbody: new Uint8Array(0),\n\t\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t\t});\n\t\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\t\treturn (\n\t\t\t\t\trateLimitedResponse(c, c.req.path, false) ??\n\t\t\t\t\tc.json({ error: auth.error }, authErrorStatus(auth.error))\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst limited = rateLimitedResponse(c, String(auth.enrollment.device_id), true);\n\t\t\tif (limited) return limited;\n\t\t\treturn await bootstrapAuthorizationResponse(c, store, {\n\t\t\t\tgrantId,\n\t\t\t\tnowMs: Date.parse(runtime.now()),\n\t\t\t\texpectedSeed: {\n\t\t\t\t\tgroupId: auth.enrollment.group_id,\n\t\t\t\t\tdeviceId: auth.enrollment.device_id,\n\t\t\t\t\tpublicKey: auth.enrollment.public_key,\n\t\t\t\t\tfingerprint: auth.enrollment.fingerprint,\n\t\t\t\t},\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.get(\"/v1/admin/bootstrap-grants\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\treturn c.json({ items: await store.listBootstrapGrants(groupId) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/admin/bootstrap-grants/revoke\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst grantId = String(data.grant_id ?? \"\").trim();\n\t\tif (!grantId) return c.json({ error: \"grant_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.revokeBootstrapGrant(grantId, runtime.now());\n\t\t\tif (!ok) return c.json({ error: \"grant_not_found\" }, 404);\n\t\t\treturn c.json({ ok: true, grant_id: grantId });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/join-requests/approve\n\tapp.post(\"/v1/admin/join-requests/approve\", async (c) => {\n\t\treturn reviewJoinRequestWithRevocationDenial(c, true, {\n\t\t\tcreateStore,\n\t\t\truntime,\n\t\t\trateLimitedResponse,\n\t\t});\n\t});\n\n\t// POST /v1/admin/join-requests/deny\n\tapp.post(\"/v1/admin/join-requests/deny\", async (c) => {\n\t\treturn reviewJoinRequestWithRevocationDenial(c, false, {\n\t\t\tcreateStore,\n\t\t\truntime,\n\t\t\trateLimitedResponse,\n\t\t});\n\t});\n\n\t// GET /v1/admin/join-requests — list join requests\n\tapp.get(\"/v1/admin/join-requests\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\treturn c.json({ items: await store.listJoinRequests(groupId) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// POST /v1/join — join via invite token (unauthenticated)\n\t// -----------------------------------------------------------------------\n\n\tapp.post(\"/v1/join\", async (c) => {\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst token = String(data.token ?? \"\").trim();\n\t\tconst deviceId = String(data.device_id ?? \"\").trim();\n\t\tconst fingerprint = String(data.fingerprint ?? \"\").trim();\n\t\tconst publicKey = String(data.public_key ?? \"\").trim();\n\t\tconst displayName = String(data.display_name ?? \"\").trim() || null;\n\t\tconst operationId = String(data.operation_id ?? \"\").trim();\n\t\tconst recipientActorId = String(data.recipient_actor_id ?? \"\").trim();\n\t\tconst recipientDisplayName = String(data.recipient_display_name ?? \"\").trim();\n\t\tconst deviceDisplayName = String(data.device_display_name ?? \"\").trim();\n\n\t\tif (!token || !deviceId || !fingerprint || !publicKey) {\n\t\t\treturn c.json({ error: \"token_device_id_fingerprint_public_key_required\" }, 400);\n\t\t}\n\t\tif (fingerprintPublicKey(publicKey) !== fingerprint) {\n\t\t\treturn c.json({ error: \"fingerprint_mismatch\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst invite = await store.getInviteByTokenForInspection(token);\n\t\t\tif (!invite) return c.json({ error: \"invite_invalid\" }, 404);\n\t\t\tconst projectInvite = Boolean(invite.operation_id || invite.reviewed_project_set_digest);\n\t\t\tconst recipientInvite =\n\t\t\t\tinvite.invite_kind === \"team_member\" || invite.invite_kind === \"add_device\";\n\t\t\tif (invite.revoked_at) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{ error: projectInvite || recipientInvite ? \"invite_invalid\" : \"revoked_token\" },\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!invite.consumed_at && new Date(invite.expires_at) <= new Date(runtime.now())) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{ error: projectInvite || recipientInvite ? \"invite_expired\" : \"expired_token\" },\n\t\t\t\t\t410,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (recipientInvite) {\n\t\t\t\tconst allowedRecipientAcceptanceFields = new Set([\n\t\t\t\t\t\"token\",\n\t\t\t\t\t\"invite_kind\",\n\t\t\t\t\t\"kind\",\n\t\t\t\t\t\"identity_id\",\n\t\t\t\t\t\"device_id\",\n\t\t\t\t\t\"public_key\",\n\t\t\t\t\t\"fingerprint\",\n\t\t\t\t\t\"recipient_display_name\",\n\t\t\t\t\t\"device_display_name\",\n\t\t\t\t]);\n\t\t\t\tif (Object.keys(data).some((key) => !allowedRecipientAcceptanceFields.has(key))) {\n\t\t\t\t\treturn c.json({ error: \"unexpected_recipient_invite_fields\" }, 400);\n\t\t\t\t}\n\t\t\t\tconst requestedKind = String(data.invite_kind ?? data.kind ?? \"\").trim();\n\t\t\t\tconst identityId = String(data.identity_id ?? \"\").trim();\n\t\t\t\tif (!identityId || requestedKind !== invite.invite_kind) {\n\t\t\t\t\treturn c.json({ error: \"recipient_invite_binding_required\" }, 400);\n\t\t\t\t}\n\t\t\t\tif (identityId.length > 256 || /[\\p{Cc}\\p{Cf}]/u.test(identityId)) {\n\t\t\t\t\treturn c.json({ error: \"identity_id_invalid\" }, 400);\n\t\t\t\t}\n\t\t\t\tlet normalizedRecipientDisplayName: string | null = null;\n\t\t\t\tlet normalizedDeviceDisplayName: string | null = null;\n\t\t\t\ttry {\n\t\t\t\t\tif (data.recipient_display_name != null) {\n\t\t\t\t\t\tif (typeof data.recipient_display_name !== \"string\") {\n\t\t\t\t\t\t\tthrow new Error(\"recipient_display_name_invalid\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tnormalizedRecipientDisplayName = normalizeHumanPresentationName(\n\t\t\t\t\t\t\tdata.recipient_display_name,\n\t\t\t\t\t\t\t\"recipient_display_name\",\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (data.device_display_name != null) {\n\t\t\t\t\t\tif (typeof data.device_display_name !== \"string\") {\n\t\t\t\t\t\t\tthrow new Error(\"device_display_name_invalid\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tnormalizedDeviceDisplayName = normalizeDeviceDisplayName(\n\t\t\t\t\t\t\tdata.device_display_name,\n\t\t\t\t\t\t\t\"device_display_name\",\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn c.json(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\terror: error instanceof Error ? error.message : \"recipient_invite_identity_invalid\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t400,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\tinvite.invite_kind === \"add_device\" &&\n\t\t\t\t\tString(invite.inviter_device_id ?? \"\").trim() === deviceId\n\t\t\t\t) {\n\t\t\t\t\treturn c.json({ error: \"add_device_invite_self_acceptance_forbidden\" }, 409);\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst acceptance = await store.consumeRecipientInvite({\n\t\t\t\t\t\t...recipientInviteContext(opts, token),\n\t\t\t\t\t\tinviteKind: invite.invite_kind as \"team_member\" | \"add_device\",\n\t\t\t\t\t\tidentityId,\n\t\t\t\t\t\tdeviceId,\n\t\t\t\t\t\tpublicKey,\n\t\t\t\t\t\tfingerprint,\n\t\t\t\t\t\trecipientDisplayName: normalizedRecipientDisplayName,\n\t\t\t\t\t\tdeviceDisplayName: normalizedDeviceDisplayName,\n\t\t\t\t\t\tnow: runtime.now(),\n\t\t\t\t\t});\n\t\t\t\t\treturn c.json({\n\t\t\t\t\t\tok: true,\n\t\t\t\t\t\tstatus: acceptance.status,\n\t\t\t\t\t\tkind: acceptance.invite.invite_kind,\n\t\t\t\t\t\tgroup_id: acceptance.invite.group_id,\n\t\t\t\t\t\tidentity_id: acceptance.invite.recipient_actor_id,\n\t\t\t\t\t\tpolicy_team_id: acceptance.invite.policy_team_id ?? null,\n\t\t\t\t\t\ttarget_identity_id: acceptance.invite.target_identity_id ?? null,\n\t\t\t\t\t\tassigned_identity_id: acceptance.invite.assigned_identity_id ?? null,\n\t\t\t\t\t\tbootstrap_grant_id: acceptance.bootstrap_grant?.grant_id ?? null,\n\t\t\t\t\t\tinviter_device: acceptance.bootstrap_grant\n\t\t\t\t\t\t\t? await store.getEnrollment(\n\t\t\t\t\t\t\t\t\tacceptance.invite.group_id,\n\t\t\t\t\t\t\t\t\tacceptance.bootstrap_grant.seed_device_id,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\t\treviewed_preview_digest: acceptance.invite.reviewed_preview_digest,\n\t\t\t\t\t\treviewed_intent: acceptance.reviewed_intent,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn recipientInviteAcceptanceErrorResponse(c, error);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (invite.operation_id || invite.reviewed_project_set_digest) {\n\t\t\t\tconst allowedProjectAcceptanceFields = new Set([\n\t\t\t\t\t\"token\",\n\t\t\t\t\t\"operation_id\",\n\t\t\t\t\t\"device_id\",\n\t\t\t\t\t\"public_key\",\n\t\t\t\t\t\"fingerprint\",\n\t\t\t\t\t\"display_name\",\n\t\t\t\t\t\"recipient_actor_id\",\n\t\t\t\t\t\"recipient_display_name\",\n\t\t\t\t\t\"device_display_name\",\n\t\t\t\t]);\n\t\t\t\tif (Object.keys(data).some((key) => !allowedProjectAcceptanceFields.has(key))) {\n\t\t\t\t\treturn c.json({ error: \"unexpected_project_invite_fields\" }, 400);\n\t\t\t\t}\n\t\t\t\tif (!operationId || !recipientActorId || !recipientDisplayName || !deviceDisplayName) {\n\t\t\t\t\treturn c.json({ error: \"project_invite_identity_required\" }, 400);\n\t\t\t\t}\n\t\t\t\tif (String(invite.inviter_device_id ?? \"\").trim() === deviceId) {\n\t\t\t\t\treturn c.json({ error: \"project_invite_self_acceptance_forbidden\" }, 409);\n\t\t\t\t}\n\t\t\t\tif (recipientActorId.length > 256 || /[\\p{Cc}\\p{Cf}]/u.test(recipientActorId)) {\n\t\t\t\t\treturn c.json({ error: \"recipient_actor_id_invalid\" }, 400);\n\t\t\t\t}\n\t\t\t\tlet normalizedRecipientName: string;\n\t\t\t\tlet normalizedDeviceName: string;\n\t\t\t\ttry {\n\t\t\t\t\tnormalizedRecipientName = normalizeHumanPresentationName(\n\t\t\t\t\t\trecipientDisplayName,\n\t\t\t\t\t\t\"recipient_display_name\",\n\t\t\t\t\t);\n\t\t\t\t\tnormalizedDeviceName = normalizeDeviceDisplayName(\n\t\t\t\t\t\tdeviceDisplayName,\n\t\t\t\t\t\t\"device_display_name\",\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn c.json(\n\t\t\t\t\t\t{ error: error instanceof Error ? error.message : \"project_invite_identity_invalid\" },\n\t\t\t\t\t\t400,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tlet acceptedIntent: ReturnType<typeof buildAcceptedProjectIntent>;\n\t\t\t\ttry {\n\t\t\t\t\tacceptedIntent = buildAcceptedProjectIntent(invite);\n\t\t\t\t} catch {\n\t\t\t\t\treturn c.json({ error: \"operation_intent_invalid\" }, 409);\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst acceptance = await store.consumeProjectInvite({\n\t\t\t\t\t\ttoken,\n\t\t\t\t\t\toperationId,\n\t\t\t\t\t\tdeviceId,\n\t\t\t\t\t\tpublicKey,\n\t\t\t\t\t\tfingerprint,\n\t\t\t\t\t\trecipientActorId,\n\t\t\t\t\t\trecipientDisplayName: normalizedRecipientName,\n\t\t\t\t\t\tdeviceDisplayName: normalizedDeviceName,\n\t\t\t\t\t\tnow: runtime.now(),\n\t\t\t\t\t});\n\t\t\t\t\treturn c.json({\n\t\t\t\t\t\tok: true,\n\t\t\t\t\t\tstatus: PROJECT_INVITE_PENDING_STATUS,\n\t\t\t\t\t\tgroup_id: acceptance.invite.group_id,\n\t\t\t\t\t\toperation_id: acceptance.invite.operation_id,\n\t\t\t\t\t\ttrust_state: acceptance.invite.trust_state,\n\t\t\t\t\t\tbootstrap_grant_id: acceptance.bootstrap_grant?.grant_id ?? null,\n\t\t\t\t\t\tinviter_device: acceptance.seed_enrollment\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tdevice_id: acceptance.seed_enrollment.device_id,\n\t\t\t\t\t\t\t\t\tpublic_key: acceptance.seed_enrollment.public_key,\n\t\t\t\t\t\t\t\t\tfingerprint: acceptance.seed_enrollment.fingerprint,\n\t\t\t\t\t\t\t\t\tdisplay_name: acceptance.seed_enrollment.display_name,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\t\taccepted_project_intent: acceptedIntent,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn projectInviteAcceptanceErrorResponse(c, error);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst projectAcceptanceFields = [\n\t\t\t\t\"operation_id\",\n\t\t\t\t\"recipient_actor_id\",\n\t\t\t\t\"recipient_display_name\",\n\t\t\t\t\"device_display_name\",\n\t\t\t];\n\t\t\tif (projectAcceptanceFields.some((field) => Object.hasOwn(data, field))) {\n\t\t\t\treturn c.json({ error: \"unexpected_project_invite_fields\" }, 400);\n\t\t\t}\n\t\t\tconst group = await store.getGroup(String(invite.group_id));\n\t\t\tif (!group) return c.json({ error: \"group_not_found\" }, 404);\n\t\t\tif (group.archived_at) return c.json({ error: \"group_archived\" }, 409);\n\n\t\t\tconst inviteGroupId = String(invite.group_id);\n\t\t\tconst existing = await store.getEnrollment(inviteGroupId, deviceId);\n\t\t\tif (existing) {\n\t\t\t\treturn c.json({\n\t\t\t\t\tok: true,\n\t\t\t\t\tstatus: \"already_enrolled\",\n\t\t\t\t\tgroup_id: invite.group_id,\n\t\t\t\t\tpolicy: invite.policy,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst invitePolicy = String(invite.policy);\n\t\t\tif (![\"auto_admit\", \"approval_required\"].includes(invitePolicy)) {\n\t\t\t\treturn c.json({ error: `unknown invite policy: ${invitePolicy}` }, 400);\n\t\t\t}\n\n\t\t\tif (invitePolicy === \"approval_required\") {\n\t\t\t\tconst request = await store.createJoinRequest({\n\t\t\t\t\tgroupId: inviteGroupId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tpublicKey,\n\t\t\t\t\tfingerprint,\n\t\t\t\t\tdisplayName,\n\t\t\t\t\ttoken,\n\t\t\t\t});\n\t\t\t\treturn c.json({\n\t\t\t\t\tok: true,\n\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\tgroup_id: invite.group_id,\n\t\t\t\t\tpolicy: invite.policy,\n\t\t\t\t\trequest_id: request.request_id,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tawait store.enrollDevice(inviteGroupId, {\n\t\t\t\tdeviceId,\n\t\t\t\tfingerprint,\n\t\t\t\tpublicKey,\n\t\t\t\tdisplayName,\n\t\t\t});\n\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\tstatus: \"enrolled\",\n\t\t\t\tgroup_id: invite.group_id,\n\t\t\t\tpolicy: invite.policy,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\treturn deviceRevokedResponse(c, error);\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\treturn app;\n}\n\n// ---------------------------------------------------------------------------\n// Shared handler for approve/deny\n// ---------------------------------------------------------------------------\n\nasync function handleJoinRequestReview(\n\tc: Context,\n\tapproved: boolean,\n\tdeps: {\n\t\tcreateStore: () => CoordinatorStore;\n\t\truntime: CoordinatorRuntimeDeps;\n\t\trateLimitedResponse: (c: Context, key: string, authenticated: boolean) => Response | null;\n\t},\n) {\n\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), deps.runtime);\n\tif (!adminAuth.ok)\n\t\treturn (\n\t\t\tdeps.rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401)\n\t\t);\n\tconst limited = deps.rateLimitedResponse(c, \"admin\", true);\n\tif (limited) return limited;\n\n\tconst raw = await (async () => {\n\t\tconst contentLength = Number.parseInt(c.req.header(\"content-length\") ?? \"\", 10);\n\t\tif (Number.isFinite(contentLength) && contentLength > MAX_BODY_BYTES) {\n\t\t\treturn null;\n\t\t}\n\t\tconst stream = c.req.raw.body;\n\t\tif (!stream) return new Uint8Array();\n\t\tconst reader = stream.getReader();\n\t\tconst chunks: Uint8Array[] = [];\n\t\tlet total = 0;\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\t\t\t\tif (!value) continue;\n\t\t\t\ttotal += value.byteLength;\n\t\t\t\tif (total > MAX_BODY_BYTES) {\n\t\t\t\t\tawait reader.cancel();\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tchunks.push(value);\n\t\t\t}\n\t\t} finally {\n\t\t\treader.releaseLock();\n\t\t}\n\t\tconst combined = new Uint8Array(total);\n\t\tlet offset = 0;\n\t\tfor (const chunk of chunks) {\n\t\t\tcombined.set(chunk, offset);\n\t\t\toffset += chunk.byteLength;\n\t\t}\n\t\treturn combined;\n\t})();\n\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\tlet data: Record<string, unknown> | null;\n\ttry {\n\t\tconst textDecoder = new TextDecoder();\n\t\tconst parsed: unknown = JSON.parse(textDecoder.decode(raw));\n\t\tdata =\n\t\t\ttypeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed)\n\t\t\t\t? (parsed as Record<string, unknown>)\n\t\t\t\t: null;\n\t} catch {\n\t\tdata = null;\n\t}\n\tif (!data) {\n\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t}\n\n\tconst requestId = String(data.request_id ?? \"\").trim();\n\tconst reviewedBy = String(data.reviewed_by ?? \"\").trim() || null;\n\tconst bootstrapGrantSeedDeviceId = String(data.bootstrap_grant_seed_device_id ?? \"\").trim();\n\tconst bootstrapGrantExpiresAt = String(data.bootstrap_grant_expires_at ?? \"\").trim();\n\n\tif (!requestId) return c.json({ error: \"request_id_required\" }, 400);\n\tconst bootstrapGrantFields = [bootstrapGrantSeedDeviceId, bootstrapGrantExpiresAt].filter(\n\t\tBoolean,\n\t).length;\n\tif (bootstrapGrantFields > 0 && bootstrapGrantFields < 2) {\n\t\treturn c.json(\n\t\t\t{ error: \"bootstrap_grant_seed_device_id_and_expires_at_required_together\" },\n\t\t\t400,\n\t\t);\n\t}\n\n\tconst store = deps.createStore();\n\ttry {\n\t\tconst request = await store.reviewJoinRequest({\n\t\t\trequestId,\n\t\t\tapproved,\n\t\t\treviewedBy,\n\t\t\tbootstrapGrant:\n\t\t\t\tapproved && bootstrapGrantSeedDeviceId && bootstrapGrantExpiresAt\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tseedDeviceId: bootstrapGrantSeedDeviceId,\n\t\t\t\t\t\t\texpiresAt: bootstrapGrantExpiresAt,\n\t\t\t\t\t\t\tcreatedBy: reviewedBy,\n\t\t\t\t\t\t}\n\t\t\t\t\t: null,\n\t\t});\n\n\t\tif (!request) return c.json({ error: \"request_not_found\" }, 404);\n\n\t\tif (request._no_transition) {\n\t\t\treturn c.json({ error: \"request_not_pending\", status: request.status }, 409);\n\t\t}\n\n\t\treturn c.json({ ok: true, request });\n\t} finally {\n\t\tawait store.close();\n\t}\n}\n","import { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { CoordinatorIdentityGroupGrant } from \"./coordinator-identity-group-grant.js\";\n\nexport function isCoordinatorControllerAttestationReference(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" && value.length === 78 && /^controller-v1:[a-f0-9]{64}$/.test(value)\n\t);\n}\n\nexport interface CoordinatorIdentityGroupGrantActionResult {\n\tkind: \"created\" | \"existing\";\n\tgrant: CoordinatorIdentityGroupGrant;\n}\n\n/** Return only validated transport-grant fields, never arbitrary server output. */\nexport function parseCoordinatorIdentityGroupGrantResponse(\n\tpayload: Record<string, unknown> | null,\n): CoordinatorIdentityGroupGrantActionResult {\n\tconst value = payload?.grant;\n\tif (!value || typeof value !== \"object\" || Array.isArray(value))\n\t\tthrow new Error(\"identity_group_grant_response_invalid\");\n\tconst grant = value as Record<string, unknown>;\n\tif (\n\t\t(payload?.kind !== \"created\" && payload?.kind !== \"existing\") ||\n\t\t!isAuthControllerId(grant.coordinator_id) ||\n\t\t!isAuthControllerId(grant.identity_id) ||\n\t\t!isAuthControllerId(grant.group_id) ||\n\t\t!isAuthControllerId(grant.source_receipt_id) ||\n\t\tgrant.status !== \"active\" ||\n\t\tgrant.source_kind !== \"controller_attestation\" ||\n\t\ttypeof grant.revision !== \"number\" ||\n\t\t!Number.isSafeInteger(grant.revision) ||\n\t\tgrant.revision < 1 ||\n\t\t!isAuthControllerId(grant.created_at) ||\n\t\t!Number.isFinite(Date.parse(grant.created_at)) ||\n\t\tgrant.revoked_at !== null\n\t)\n\t\tthrow new Error(\"identity_group_grant_response_invalid\");\n\treturn {\n\t\tkind: payload.kind,\n\t\tgrant: {\n\t\t\tcoordinator_id: grant.coordinator_id,\n\t\t\tidentity_id: grant.identity_id,\n\t\t\tgroup_id: grant.group_id,\n\t\t\tstatus: grant.status,\n\t\t\trevision: grant.revision,\n\t\t\tsource_kind: grant.source_kind,\n\t\t\tsource_receipt_id: grant.source_receipt_id,\n\t\t\tcreated_at: grant.created_at,\n\t\t\trevoked_at: grant.revoked_at,\n\t\t},\n\t};\n}\n","/** Trusted server-side data only, never request JSON or an environment loader.\n * Enabled settings contain SDK secrets: never use them as an HTTP or logging DTO.\n */\nimport type { CoordinatorAuthBrowserConfig } from \"./coordinator-auth-browser-transaction-contract.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { CoordinatorOidcProviderConfig } from \"./coordinator-oidc.js\";\n\nexport const COORDINATOR_BROWSER_AUTH_ISSUER = \"https://accounts.google.com\";\n\nexport interface CoordinatorBrowserAuthConfig {\n\tenabled: boolean;\n\tcoordinatorId: string;\n\tissuer: string;\n\tclientId: string;\n\tclientSecret: string;\n\tredirectUri: string;\n\trevision: string;\n}\n\nexport type CoordinatorBrowserAuthConfigField =\n\t| \"config\"\n\t| \"enabled\"\n\t| \"unknown_field\"\n\t| \"coordinatorId\"\n\t| \"issuer\"\n\t| \"clientId\"\n\t| \"clientSecret\"\n\t| \"redirectUri\"\n\t| \"revision\";\n\nexport type CoordinatorBrowserAuthSettings =\n\t| Readonly<{ kind: \"disabled\" }>\n\t| Readonly<{ kind: \"invalid\"; field: CoordinatorBrowserAuthConfigField }>\n\t| Readonly<{\n\t\t\tkind: \"enabled\";\n\t\t\tpublicOrigin: string;\n\t\t\tstore: Readonly<CoordinatorAuthBrowserConfig>;\n\t\t\toidc: Readonly<CoordinatorOidcProviderConfig>;\n\t }>;\n\nconst CONFIG_KEYS = [\n\t\"enabled\",\n\t\"coordinatorId\",\n\t\"issuer\",\n\t\"clientId\",\n\t\"clientSecret\",\n\t\"redirectUri\",\n\t\"revision\",\n] as const;\n\nfunction invalid(field: CoordinatorBrowserAuthConfigField): CoordinatorBrowserAuthSettings {\n\treturn Object.freeze({ kind: \"invalid\", field });\n}\n\nfunction ownDataValue(value: object, key: keyof CoordinatorBrowserAuthConfig): unknown {\n\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\tif (!descriptor || !Object.hasOwn(descriptor, \"value\")) return undefined;\n\treturn descriptor.value;\n}\n\nfunction isCredential(value: unknown, maxLength: number): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length > 0 &&\n\t\tvalue.length <= maxLength &&\n\t\tvalue.trim() === value &&\n\t\t!/[\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(value)\n\t);\n}\n\nfunction redirectOrigin(value: unknown): string | null {\n\tif (typeof value !== \"string\" || value.trim() !== value) return null;\n\tif (/[\\p{Cc}\\p{Cf}\\p{Cs}\\\\?#]/u.test(value)) return null;\n\ttry {\n\t\tconst url = new URL(value);\n\t\tif (url.protocol !== \"https:\" || url.href !== value) return null;\n\t\tif (url.username || url.password || url.search || url.hash) return null;\n\t\treturn url.origin;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction captureEnabled(value: object): CoordinatorBrowserAuthSettings {\n\tconst keys = Reflect.ownKeys(value);\n\tif (keys.some((key) => typeof key !== \"string\" || !CONFIG_KEYS.some((known) => known === key)))\n\t\treturn invalid(\"unknown_field\");\n\tconst coordinatorId = ownDataValue(value, \"coordinatorId\");\n\tconst issuer = ownDataValue(value, \"issuer\");\n\tconst clientId = ownDataValue(value, \"clientId\");\n\tconst clientSecret = ownDataValue(value, \"clientSecret\");\n\tconst redirectUri = ownDataValue(value, \"redirectUri\");\n\tconst revision = ownDataValue(value, \"revision\");\n\tif (!isAuthControllerId(coordinatorId)) return invalid(\"coordinatorId\");\n\tif (issuer !== COORDINATOR_BROWSER_AUTH_ISSUER) return invalid(\"issuer\");\n\tif (!isCredential(clientId, 256)) return invalid(\"clientId\");\n\tif (!isCredential(clientSecret, 4096)) return invalid(\"clientSecret\");\n\tconst publicOrigin = redirectOrigin(redirectUri);\n\tif (typeof redirectUri !== \"string\" || publicOrigin === null) return invalid(\"redirectUri\");\n\tif (typeof revision !== \"string\" || revision.length !== 64 || !/^[a-f0-9]{64}$/.test(revision))\n\t\treturn invalid(\"revision\");\n\treturn Object.freeze({\n\t\tkind: \"enabled\",\n\t\tpublicOrigin,\n\t\tstore: Object.freeze({ enabled: true, coordinatorId, issuer, redirectUri, revision }),\n\t\toidc: Object.freeze({ issuer, clientId, clientSecret, redirectUri }),\n\t});\n}\n\n/** Capture own data descriptors once; getters are never evaluated. Reflection\n * may execute proxy traps, whose exceptions are returned without input details.\n */\nexport function captureCoordinatorBrowserAuthConfig(\n\tvalue: unknown,\n): CoordinatorBrowserAuthSettings {\n\ttry {\n\t\tif (value === undefined) return Object.freeze({ kind: \"disabled\" });\n\t\tif (value === null || typeof value !== \"object\" || Array.isArray(value))\n\t\t\treturn invalid(\"config\");\n\t\tconst prototype = Object.getPrototypeOf(value);\n\t\tif (prototype !== Object.prototype && prototype !== null) return invalid(\"config\");\n\t\tconst enabled = ownDataValue(value, \"enabled\");\n\t\tif (enabled === false) return Object.freeze({ kind: \"disabled\" });\n\t\tif (enabled !== true) return invalid(\"enabled\");\n\t\treturn captureEnabled(value);\n\t} catch {\n\t\treturn invalid(\"config\");\n\t}\n}\n","let USER_AGENT;\nif (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {\n const NAME = 'oauth4webapi';\n const VERSION = 'v3.8.8';\n USER_AGENT = `${NAME}/${VERSION}`;\n}\nfunction looseInstanceOf(input, expected) {\n if (input == null) {\n return false;\n }\n try {\n return (input instanceof expected ||\n Object.getPrototypeOf(input)[Symbol.toStringTag] === expected.prototype[Symbol.toStringTag]);\n }\n catch {\n return false;\n }\n}\nconst ERR_INVALID_ARG_VALUE = 'ERR_INVALID_ARG_VALUE';\nconst ERR_INVALID_ARG_TYPE = 'ERR_INVALID_ARG_TYPE';\nfunction CodedTypeError(message, code, cause) {\n const err = new TypeError(message, { cause });\n Object.assign(err, { code });\n return err;\n}\nexport const allowInsecureRequests = Symbol();\nexport const clockSkew = Symbol();\nexport const clockTolerance = Symbol();\nexport const customFetch = Symbol();\nexport const modifyAssertion = Symbol();\nexport const jweDecrypt = Symbol();\nexport const jwksCache = Symbol();\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\nfunction buf(input) {\n if (typeof input === 'string') {\n return encoder.encode(input);\n }\n return decoder.decode(input);\n}\nlet encodeBase64Url;\nif (Uint8Array.prototype.toBase64) {\n encodeBase64Url = (input) => {\n if (input instanceof ArrayBuffer) {\n input = new Uint8Array(input);\n }\n return input.toBase64({ alphabet: 'base64url', omitPadding: true });\n };\n}\nelse {\n const CHUNK_SIZE = 0x8000;\n encodeBase64Url = (input) => {\n if (input instanceof ArrayBuffer) {\n input = new Uint8Array(input);\n }\n const arr = [];\n for (let i = 0; i < input.byteLength; i += CHUNK_SIZE) {\n arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));\n }\n return btoa(arr.join('')).replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\n };\n}\nlet decodeBase64Url;\nif (Uint8Array.fromBase64) {\n decodeBase64Url = (input) => {\n try {\n return Uint8Array.fromBase64(input, { alphabet: 'base64url' });\n }\n catch (cause) {\n throw CodedTypeError('The input to be decoded is not correctly encoded.', ERR_INVALID_ARG_VALUE, cause);\n }\n };\n}\nelse {\n decodeBase64Url = (input) => {\n try {\n const binary = atob(input.replace(/-/g, '+').replace(/_/g, '/').replace(/\\s/g, ''));\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n }\n catch (cause) {\n throw CodedTypeError('The input to be decoded is not correctly encoded.', ERR_INVALID_ARG_VALUE, cause);\n }\n };\n}\nfunction b64u(input) {\n if (typeof input === 'string') {\n return decodeBase64Url(input);\n }\n return encodeBase64Url(input);\n}\nexport class UnsupportedOperationError extends Error {\n code;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n this.code = UNSUPPORTED_OPERATION;\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nexport class OperationProcessingError extends Error {\n code;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n if (options?.code) {\n this.code = options?.code;\n }\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nfunction OPE(message, code, cause) {\n return new OperationProcessingError(message, { code, cause });\n}\nasync function calculateJwkThumbprint(jwk) {\n let components;\n switch (jwk.kty) {\n case 'EC':\n components = {\n crv: jwk.crv,\n kty: jwk.kty,\n x: jwk.x,\n y: jwk.y,\n };\n break;\n case 'OKP':\n components = {\n crv: jwk.crv,\n kty: jwk.kty,\n x: jwk.x,\n };\n break;\n case 'AKP':\n components = {\n alg: jwk.alg,\n kty: jwk.kty,\n pub: jwk.pub,\n };\n break;\n case 'RSA':\n components = {\n e: jwk.e,\n kty: jwk.kty,\n n: jwk.n,\n };\n break;\n default:\n throw new UnsupportedOperationError('unsupported JWK key type', { cause: jwk });\n }\n return b64u(await crypto.subtle.digest('SHA-256', buf(JSON.stringify(components))));\n}\nfunction assertCryptoKey(key, it) {\n if (!(key instanceof CryptoKey)) {\n throw CodedTypeError(`${it} must be a CryptoKey`, ERR_INVALID_ARG_TYPE);\n }\n}\nfunction assertPrivateKey(key, it) {\n assertCryptoKey(key, it);\n if (key.type !== 'private') {\n throw CodedTypeError(`${it} must be a private CryptoKey`, ERR_INVALID_ARG_VALUE);\n }\n}\nfunction assertPublicKey(key, it) {\n assertCryptoKey(key, it);\n if (key.type !== 'public') {\n throw CodedTypeError(`${it} must be a public CryptoKey`, ERR_INVALID_ARG_VALUE);\n }\n}\nfunction normalizeTyp(value) {\n return value.toLowerCase().replace(/^application\\//, '');\n}\nfunction isJsonObject(input) {\n if (input === null || typeof input !== 'object' || Array.isArray(input)) {\n return false;\n }\n return true;\n}\nfunction prepareHeaders(input) {\n if (looseInstanceOf(input, Headers)) {\n input = Object.fromEntries(input.entries());\n }\n const headers = new Headers(input ?? {});\n if (USER_AGENT && !headers.has('user-agent')) {\n headers.set('user-agent', USER_AGENT);\n }\n if (headers.has('authorization')) {\n throw CodedTypeError('\"options.headers\" must not include the \"authorization\" header name', ERR_INVALID_ARG_VALUE);\n }\n return headers;\n}\nfunction signal(url, value) {\n if (value !== undefined) {\n if (typeof value === 'function') {\n value = value(url.href);\n }\n if (!(value instanceof AbortSignal)) {\n throw CodedTypeError('\"options.signal\" must return or be an instance of AbortSignal', ERR_INVALID_ARG_TYPE);\n }\n return value;\n }\n return undefined;\n}\nfunction replaceDoubleSlash(pathname) {\n if (pathname.includes('//')) {\n return pathname.replace('//', '/');\n }\n return pathname;\n}\nfunction prependWellKnown(url, wellKnown, allowTerminatingSlash = false) {\n if (url.pathname === '/') {\n url.pathname = wellKnown;\n }\n else {\n url.pathname = replaceDoubleSlash(`${wellKnown}/${allowTerminatingSlash ? url.pathname : url.pathname.replace(/(\\/)$/, '')}`);\n }\n return url;\n}\nfunction appendWellKnown(url, wellKnown) {\n url.pathname = replaceDoubleSlash(`${url.pathname}/${wellKnown}`);\n return url;\n}\nasync function performDiscovery(input, urlName, transform, options) {\n if (!(input instanceof URL)) {\n throw CodedTypeError(`\"${urlName}\" must be an instance of URL`, ERR_INVALID_ARG_TYPE);\n }\n checkProtocol(input, options?.[allowInsecureRequests] !== true);\n const url = transform(new URL(input.href));\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n return (options?.[customFetch] || fetch)(url.href, {\n body: undefined,\n headers: Object.fromEntries(headers.entries()),\n method: 'GET',\n redirect: 'manual',\n signal: signal(url, options?.signal),\n });\n}\nexport async function discoveryRequest(issuerIdentifier, options) {\n return performDiscovery(issuerIdentifier, 'issuerIdentifier', (url) => {\n switch (options?.algorithm) {\n case undefined:\n case 'oidc':\n appendWellKnown(url, '.well-known/openid-configuration');\n break;\n case 'oauth2':\n prependWellKnown(url, '.well-known/oauth-authorization-server');\n break;\n default:\n throw CodedTypeError('\"options.algorithm\" must be \"oidc\" (default), or \"oauth2\"', ERR_INVALID_ARG_VALUE);\n }\n return url;\n }, options);\n}\nfunction assertNumber(input, allow0, it, code, cause) {\n try {\n if (typeof input !== 'number' || !Number.isFinite(input)) {\n throw CodedTypeError(`${it} must be a number`, ERR_INVALID_ARG_TYPE, cause);\n }\n if (input > 0)\n return;\n if (allow0) {\n if (input !== 0) {\n throw CodedTypeError(`${it} must be a non-negative number`, ERR_INVALID_ARG_VALUE, cause);\n }\n return;\n }\n throw CodedTypeError(`${it} must be a positive number`, ERR_INVALID_ARG_VALUE, cause);\n }\n catch (err) {\n if (code) {\n throw OPE(err.message, code, cause);\n }\n throw err;\n }\n}\nfunction assertString(input, it, code, cause) {\n try {\n if (typeof input !== 'string') {\n throw CodedTypeError(`${it} must be a string`, ERR_INVALID_ARG_TYPE, cause);\n }\n if (input.length === 0) {\n throw CodedTypeError(`${it} must not be empty`, ERR_INVALID_ARG_VALUE, cause);\n }\n }\n catch (err) {\n if (code) {\n throw OPE(err.message, code, cause);\n }\n throw err;\n }\n}\nexport async function processDiscoveryResponse(expectedIssuerIdentifier, response) {\n const expected = expectedIssuerIdentifier;\n if (!(expected instanceof URL) && expected !== _nodiscoverycheck) {\n throw CodedTypeError('\"expectedIssuerIdentifier\" must be an instance of URL', ERR_INVALID_ARG_TYPE);\n }\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n if (response.status !== 200) {\n throw OPE('\"response\" is not a conform Authorization Server Metadata response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);\n }\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.issuer, '\"response\" body \"issuer\" property', INVALID_RESPONSE, { body: json });\n if (expected !== _nodiscoverycheck && new URL(json.issuer).href !== expected.href) {\n throw OPE('\"response\" body \"issuer\" property does not match the expected value', JSON_ATTRIBUTE_COMPARISON, { expected: expected.href, body: json, attribute: 'issuer' });\n }\n return json;\n}\nfunction assertApplicationJson(response) {\n assertContentType(response, 'application/json');\n}\nfunction notJson(response, ...types) {\n let msg = '\"response\" content-type must be ';\n if (types.length > 2) {\n const last = types.pop();\n msg += `${types.join(', ')}, or ${last}`;\n }\n else if (types.length === 2) {\n msg += `${types[0]} or ${types[1]}`;\n }\n else {\n msg += types[0];\n }\n return OPE(msg, RESPONSE_IS_NOT_JSON, response);\n}\nfunction assertContentTypes(response, ...types) {\n if (!types.includes(getContentType(response))) {\n throw notJson(response, ...types);\n }\n}\nfunction assertContentType(response, contentType) {\n if (getContentType(response) !== contentType) {\n throw notJson(response, contentType);\n }\n}\nfunction randomBytes() {\n return b64u(crypto.getRandomValues(new Uint8Array(32)));\n}\nexport function generateRandomCodeVerifier() {\n return randomBytes();\n}\nexport function generateRandomState() {\n return randomBytes();\n}\nexport function generateRandomNonce() {\n return randomBytes();\n}\nexport async function calculatePKCECodeChallenge(codeVerifier) {\n assertString(codeVerifier, 'codeVerifier');\n return b64u(await crypto.subtle.digest('SHA-256', buf(codeVerifier)));\n}\nfunction getKeyAndKid(input) {\n if (input instanceof CryptoKey) {\n return { key: input };\n }\n if (!(input?.key instanceof CryptoKey)) {\n return {};\n }\n if (input.kid !== undefined) {\n assertString(input.kid, '\"kid\"');\n }\n return {\n key: input.key,\n kid: input.kid,\n };\n}\nfunction psAlg(key) {\n switch (key.algorithm.hash.name) {\n case 'SHA-256':\n return 'PS256';\n case 'SHA-384':\n return 'PS384';\n case 'SHA-512':\n return 'PS512';\n default:\n throw new UnsupportedOperationError('unsupported RsaHashedKeyAlgorithm hash name', {\n cause: key,\n });\n }\n}\nfunction rsAlg(key) {\n switch (key.algorithm.hash.name) {\n case 'SHA-256':\n return 'RS256';\n case 'SHA-384':\n return 'RS384';\n case 'SHA-512':\n return 'RS512';\n default:\n throw new UnsupportedOperationError('unsupported RsaHashedKeyAlgorithm hash name', {\n cause: key,\n });\n }\n}\nfunction esAlg(key) {\n switch (key.algorithm.namedCurve) {\n case 'P-256':\n return 'ES256';\n case 'P-384':\n return 'ES384';\n case 'P-521':\n return 'ES512';\n default:\n throw new UnsupportedOperationError('unsupported EcKeyAlgorithm namedCurve', { cause: key });\n }\n}\nfunction keyToJws(key) {\n switch (key.algorithm.name) {\n case 'RSA-PSS':\n return psAlg(key);\n case 'RSASSA-PKCS1-v1_5':\n return rsAlg(key);\n case 'ECDSA':\n return esAlg(key);\n case 'Ed25519':\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n return key.algorithm.name;\n case 'EdDSA':\n return 'Ed25519';\n default:\n throw new UnsupportedOperationError('unsupported CryptoKey algorithm name', { cause: key });\n }\n}\nfunction getClockSkew(client) {\n const skew = client?.[clockSkew];\n return typeof skew === 'number' && Number.isFinite(skew) ? skew : 0;\n}\nfunction getClockTolerance(client) {\n const tolerance = client?.[clockTolerance];\n return typeof tolerance === 'number' && Number.isFinite(tolerance) && Math.sign(tolerance) !== -1\n ? tolerance\n : 30;\n}\nfunction epochTime() {\n return Math.floor(Date.now() / 1000);\n}\nfunction assertAs(as) {\n if (typeof as !== 'object' || as === null) {\n throw CodedTypeError('\"as\" must be an object', ERR_INVALID_ARG_TYPE);\n }\n assertString(as.issuer, '\"as.issuer\"');\n}\nfunction assertClient(client) {\n if (typeof client !== 'object' || client === null) {\n throw CodedTypeError('\"client\" must be an object', ERR_INVALID_ARG_TYPE);\n }\n assertString(client.client_id, '\"client.client_id\"');\n}\nfunction formUrlEncode(token) {\n return encodeURIComponent(token).replace(/(?:[-_.!~*'()]|%20)/g, (substring) => {\n switch (substring) {\n case '-':\n case '_':\n case '.':\n case '!':\n case '~':\n case '*':\n case \"'\":\n case '(':\n case ')':\n return `%${substring.charCodeAt(0).toString(16).toUpperCase()}`;\n case '%20':\n return '+';\n default:\n throw new Error();\n }\n });\n}\nexport function ClientSecretPost(clientSecret) {\n assertString(clientSecret, '\"clientSecret\"');\n return (_as, client, body, _headers) => {\n body.set('client_id', client.client_id);\n body.set('client_secret', clientSecret);\n };\n}\nexport function ClientSecretBasic(clientSecret) {\n assertString(clientSecret, '\"clientSecret\"');\n return (_as, client, _body, headers) => {\n const username = formUrlEncode(client.client_id);\n const password = formUrlEncode(clientSecret);\n const credentials = btoa(`${username}:${password}`);\n headers.set('authorization', `Basic ${credentials}`);\n };\n}\nfunction clientAssertionPayload(as, client) {\n const now = epochTime() + getClockSkew(client);\n return {\n jti: randomBytes(),\n aud: as.issuer,\n exp: now + 60,\n iat: now,\n nbf: now,\n iss: client.client_id,\n sub: client.client_id,\n };\n}\nexport function PrivateKeyJwt(clientPrivateKey, options) {\n const { key, kid } = getKeyAndKid(clientPrivateKey);\n assertPrivateKey(key, '\"clientPrivateKey.key\"');\n return async (as, client, body, _headers) => {\n const header = { alg: keyToJws(key), kid };\n const payload = clientAssertionPayload(as, client);\n options?.[modifyAssertion]?.(header, payload);\n body.set('client_id', client.client_id);\n body.set('client_assertion_type', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer');\n body.set('client_assertion', await signJwt(header, payload, key));\n };\n}\nexport function ClientSecretJwt(clientSecret, options) {\n assertString(clientSecret, '\"clientSecret\"');\n const modify = options?.[modifyAssertion];\n let key;\n return async (as, client, body, _headers) => {\n key ||= await crypto.subtle.importKey('raw', buf(clientSecret), { hash: 'SHA-256', name: 'HMAC' }, false, ['sign']);\n const header = { alg: 'HS256' };\n const payload = clientAssertionPayload(as, client);\n modify?.(header, payload);\n const data = `${b64u(buf(JSON.stringify(header)))}.${b64u(buf(JSON.stringify(payload)))}`;\n const hmac = await crypto.subtle.sign(key.algorithm, key, buf(data));\n body.set('client_id', client.client_id);\n body.set('client_assertion_type', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer');\n body.set('client_assertion', `${data}.${b64u(new Uint8Array(hmac))}`);\n };\n}\nexport function None() {\n return (_as, client, body, _headers) => {\n body.set('client_id', client.client_id);\n };\n}\nexport function TlsClientAuth() {\n return None();\n}\nasync function signJwt(header, payload, key) {\n if (!key.usages.includes('sign')) {\n throw CodedTypeError('CryptoKey instances used for signing assertions must include \"sign\" in their \"usages\"', ERR_INVALID_ARG_VALUE);\n }\n const input = `${b64u(buf(JSON.stringify(header)))}.${b64u(buf(JSON.stringify(payload)))}`;\n const signature = b64u(await crypto.subtle.sign(keyToSubtle(key), key, buf(input)));\n return `${input}.${signature}`;\n}\nexport async function issueRequestObject(as, client, parameters, privateKey, options) {\n assertAs(as);\n assertClient(client);\n parameters = new URLSearchParams(parameters);\n const { key, kid } = getKeyAndKid(privateKey);\n assertPrivateKey(key, '\"privateKey.key\"');\n parameters.set('client_id', client.client_id);\n const now = epochTime() + getClockSkew(client);\n const claims = {\n ...Object.fromEntries(parameters.entries()),\n jti: randomBytes(),\n aud: as.issuer,\n exp: now + 60,\n iat: now,\n nbf: now,\n iss: client.client_id,\n };\n let resource;\n if (parameters.has('resource') &&\n (resource = parameters.getAll('resource')) &&\n resource.length > 1) {\n claims.resource = resource;\n }\n {\n let value = parameters.get('max_age');\n if (value !== null) {\n claims.max_age = parseInt(value, 10);\n assertNumber(claims.max_age, true, '\"max_age\" parameter');\n }\n }\n {\n let value = parameters.get('claims');\n if (value !== null) {\n try {\n claims.claims = JSON.parse(value);\n }\n catch (cause) {\n throw OPE('failed to parse the \"claims\" parameter as JSON', PARSE_ERROR, cause);\n }\n if (!isJsonObject(claims.claims)) {\n throw CodedTypeError('\"claims\" parameter must be a JSON with a top level object', ERR_INVALID_ARG_VALUE);\n }\n }\n }\n {\n let value = parameters.get('authorization_details');\n if (value !== null) {\n try {\n claims.authorization_details = JSON.parse(value);\n }\n catch (cause) {\n throw OPE('failed to parse the \"authorization_details\" parameter as JSON', PARSE_ERROR, cause);\n }\n if (!Array.isArray(claims.authorization_details)) {\n throw CodedTypeError('\"authorization_details\" parameter must be a JSON with a top level array', ERR_INVALID_ARG_VALUE);\n }\n }\n }\n const header = {\n alg: keyToJws(key),\n typ: 'oauth-authz-req+jwt',\n kid,\n };\n options?.[modifyAssertion]?.(header, claims);\n return signJwt(header, claims, key);\n}\nlet jwkCache;\nasync function getSetPublicJwkCache(key, alg) {\n const { kty, e, n, x, y, crv, pub } = await crypto.subtle.exportKey('jwk', key);\n const jwk = { kty, e, n, x, y, crv, pub };\n if (kty === 'AKP')\n jwk.alg = alg;\n jwkCache.set(key, jwk);\n return jwk;\n}\nasync function publicJwk(key, alg) {\n jwkCache ||= new WeakMap();\n return jwkCache.get(key) || getSetPublicJwkCache(key, alg);\n}\nconst URLParse = URL.parse\n ?\n (url, base) => URL.parse(url, base)\n : (url, base) => {\n try {\n return new URL(url, base);\n }\n catch {\n return null;\n }\n };\nexport function checkProtocol(url, enforceHttps) {\n if (enforceHttps && url.protocol !== 'https:') {\n throw OPE('only requests to HTTPS are allowed', HTTP_REQUEST_FORBIDDEN, url);\n }\n if (url.protocol !== 'https:' && url.protocol !== 'http:') {\n throw OPE('only HTTP and HTTPS requests are allowed', REQUEST_PROTOCOL_FORBIDDEN, url);\n }\n}\nfunction validateEndpoint(value, endpoint, useMtlsAlias, enforceHttps) {\n let url;\n if (typeof value !== 'string' || !(url = URLParse(value))) {\n throw OPE(`authorization server metadata does not contain a valid ${useMtlsAlias ? `\"as.mtls_endpoint_aliases.${endpoint}\"` : `\"as.${endpoint}\"`}`, value === undefined ? MISSING_SERVER_METADATA : INVALID_SERVER_METADATA, { attribute: useMtlsAlias ? `mtls_endpoint_aliases.${endpoint}` : endpoint });\n }\n checkProtocol(url, enforceHttps);\n return url;\n}\nexport function resolveEndpoint(as, endpoint, useMtlsAlias, enforceHttps) {\n if (useMtlsAlias && as.mtls_endpoint_aliases && endpoint in as.mtls_endpoint_aliases) {\n return validateEndpoint(as.mtls_endpoint_aliases[endpoint], endpoint, useMtlsAlias, enforceHttps);\n }\n return validateEndpoint(as[endpoint], endpoint, useMtlsAlias, enforceHttps);\n}\nexport async function pushedAuthorizationRequest(as, client, clientAuthentication, parameters, options) {\n assertAs(as);\n assertClient(client);\n const url = resolveEndpoint(as, 'pushed_authorization_request_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const body = new URLSearchParams(parameters);\n body.set('client_id', client.client_id);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n if (options?.DPoP !== undefined) {\n assertDPoP(options.DPoP);\n await options.DPoP.addProof(url, headers, 'POST');\n }\n const response = await authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);\n options?.DPoP?.cacheNonce(response, url);\n return response;\n}\nclass DPoPHandler {\n #header;\n #privateKey;\n #publicKey;\n #clockSkew;\n #modifyAssertion;\n #map;\n #jkt;\n constructor(client, keyPair, options) {\n assertPrivateKey(keyPair?.privateKey, '\"DPoP.privateKey\"');\n assertPublicKey(keyPair?.publicKey, '\"DPoP.publicKey\"');\n if (!keyPair.publicKey.extractable) {\n throw CodedTypeError('\"DPoP.publicKey.extractable\" must be true', ERR_INVALID_ARG_VALUE);\n }\n this.#modifyAssertion = options?.[modifyAssertion];\n this.#clockSkew = getClockSkew(client);\n this.#privateKey = keyPair.privateKey;\n this.#publicKey = keyPair.publicKey;\n branded.add(this);\n }\n #get(key) {\n this.#map ||= new Map();\n let item = this.#map.get(key);\n if (item) {\n this.#map.delete(key);\n this.#map.set(key, item);\n }\n return item;\n }\n #set(key, val) {\n this.#map ||= new Map();\n this.#map.delete(key);\n if (this.#map.size === 100) {\n this.#map.delete(this.#map.keys().next().value);\n }\n this.#map.set(key, val);\n }\n async calculateThumbprint() {\n if (!this.#jkt) {\n const jwk = await crypto.subtle.exportKey('jwk', this.#publicKey);\n this.#jkt ||= await calculateJwkThumbprint(jwk);\n }\n return this.#jkt;\n }\n async addProof(url, headers, htm, accessToken) {\n const alg = keyToJws(this.#privateKey);\n this.#header ||= {\n alg,\n typ: 'dpop+jwt',\n jwk: await publicJwk(this.#publicKey, alg),\n };\n const nonce = this.#get(url.origin);\n const now = epochTime() + this.#clockSkew;\n const payload = {\n iat: now,\n jti: randomBytes(),\n htm,\n nonce,\n htu: `${url.origin}${url.pathname}`,\n ath: accessToken\n ? b64u(await crypto.subtle.digest('SHA-256', buf(accessToken)))\n : undefined,\n };\n this.#modifyAssertion?.(this.#header, payload);\n headers.set('dpop', await signJwt(this.#header, payload, this.#privateKey));\n }\n cacheNonce(response, url) {\n try {\n const nonce = response.headers.get('dpop-nonce');\n if (nonce) {\n this.#set(url.origin, nonce);\n }\n }\n catch { }\n }\n}\nexport function isDPoPNonceError(err) {\n if (err instanceof WWWAuthenticateChallengeError) {\n return err.cause.some((challenge) => challenge.scheme === 'dpop' && challenge.parameters.error === 'use_dpop_nonce');\n }\n if (err instanceof ResponseBodyError) {\n return err.error === 'use_dpop_nonce';\n }\n return false;\n}\nexport function DPoP(client, keyPair, options) {\n return new DPoPHandler(client, keyPair, options);\n}\nexport class ResponseBodyError extends Error {\n cause;\n code;\n error;\n status;\n error_description;\n response;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n this.code = RESPONSE_BODY_ERROR;\n this.cause = options.cause;\n this.error = options.cause.error;\n this.status = options.response.status;\n this.error_description = options.cause.error_description;\n Object.defineProperty(this, 'response', { enumerable: false, value: options.response });\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nexport class AuthorizationResponseError extends Error {\n cause;\n code;\n error;\n error_description;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n this.code = AUTHORIZATION_RESPONSE_ERROR;\n this.cause = options.cause;\n this.error = options.cause.get('error');\n this.error_description = options.cause.get('error_description') ?? undefined;\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nexport class WWWAuthenticateChallengeError extends Error {\n cause;\n code;\n response;\n status;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n this.code = WWW_AUTHENTICATE_CHALLENGE;\n this.cause = options.cause;\n this.status = options.response.status;\n this.response = options.response;\n Object.defineProperty(this, 'response', { enumerable: false });\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nconst tokenMatch = \"[a-zA-Z0-9!#$%&\\\\'\\\\*\\\\+\\\\-\\\\.\\\\^_`\\\\|~]+\";\nconst token68Match = '[a-zA-Z0-9\\\\-\\\\._\\\\~\\\\+\\\\/]+={0,2}';\nconst quotedMatch = '\"((?:[^\"\\\\\\\\]|\\\\\\\\[\\\\s\\\\S])*)\"';\nconst quotedParamMatcher = '(' + tokenMatch + ')\\\\s*=\\\\s*' + quotedMatch;\nconst paramMatcher = '(' + tokenMatch + ')\\\\s*=\\\\s*(' + tokenMatch + ')';\nconst schemeRE = new RegExp('^[,\\\\s]*(' + tokenMatch + ')');\nconst quotedParamRE = new RegExp('^[,\\\\s]*' + quotedParamMatcher + '[,\\\\s]*(.*)');\nconst unquotedParamRE = new RegExp('^[,\\\\s]*' + paramMatcher + '[,\\\\s]*(.*)');\nconst token68ParamRE = new RegExp('^(' + token68Match + ')(?:$|[,\\\\s])(.*)');\nfunction parseWwwAuthenticateChallenges(response) {\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n const header = response.headers.get('www-authenticate');\n if (header === null) {\n return undefined;\n }\n const challenges = [];\n let rest = header;\n while (rest) {\n let match = rest.match(schemeRE);\n const scheme = match?.['1'].toLowerCase();\n if (!scheme) {\n return undefined;\n }\n const afterScheme = rest.substring(match[0].length);\n if (afterScheme && !afterScheme.match(/^[\\s,]/)) {\n return undefined;\n }\n const spaceMatch = afterScheme.match(/^\\s+(.*)$/);\n const hasParameters = !!spaceMatch;\n rest = spaceMatch ? spaceMatch[1] : undefined;\n const parameters = {};\n let token68;\n if (hasParameters) {\n while (rest) {\n let key;\n let value;\n if ((match = rest.match(quotedParamRE))) {\n ;\n [, key, value, rest] = match;\n if (value.includes('\\\\')) {\n value = value.replace(/\\\\([\\s\\S])/g, '$1');\n }\n parameters[key.toLowerCase()] = value;\n continue;\n }\n if ((match = rest.match(unquotedParamRE))) {\n ;\n [, key, value, rest] = match;\n parameters[key.toLowerCase()] = value;\n continue;\n }\n if ((match = rest.match(token68ParamRE))) {\n if (Object.keys(parameters).length) {\n break;\n }\n ;\n [, token68, rest] = match;\n break;\n }\n return undefined;\n }\n }\n else {\n rest = afterScheme || undefined;\n }\n const challenge = { scheme, parameters };\n if (token68) {\n challenge.token68 = token68;\n }\n challenges.push(challenge);\n }\n if (!challenges.length) {\n return undefined;\n }\n return challenges;\n}\nexport async function processPushedAuthorizationResponse(as, client, response) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 201, 'Pushed Authorization Request Endpoint');\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.request_uri, '\"response\" body \"request_uri\" property', INVALID_RESPONSE, {\n body: json,\n });\n let expiresIn = typeof json.expires_in !== 'number' ? parseFloat(json.expires_in) : json.expires_in;\n assertNumber(expiresIn, true, '\"response\" body \"expires_in\" property', INVALID_RESPONSE, {\n body: json,\n });\n json.expires_in = expiresIn;\n return json;\n}\nasync function parseOAuthResponseErrorBody(response) {\n if (response.status > 399 && response.status < 500) {\n assertReadableResponse(response);\n assertApplicationJson(response);\n try {\n const json = await response.clone().json();\n if (isJsonObject(json) && typeof json.error === 'string' && json.error.length) {\n return json;\n }\n }\n catch { }\n }\n return undefined;\n}\nasync function checkOAuthBodyError(response, expected, label) {\n if (response.status !== expected) {\n checkAuthenticationChallenges(response);\n let err;\n if ((err = await parseOAuthResponseErrorBody(response))) {\n await response.body?.cancel();\n throw new ResponseBodyError('server responded with an error in the response body', {\n cause: err,\n response,\n });\n }\n throw OPE(`\"response\" is not a conform ${label} response (unexpected HTTP status code)`, RESPONSE_IS_NOT_CONFORM, response);\n }\n}\nfunction assertDPoP(option) {\n if (!branded.has(option)) {\n throw CodedTypeError('\"options.DPoP\" is not a valid DPoPHandle', ERR_INVALID_ARG_VALUE);\n }\n}\nasync function resourceRequest(accessToken, method, url, headers, body, options) {\n assertString(accessToken, '\"accessToken\"');\n if (!(url instanceof URL)) {\n throw CodedTypeError('\"url\" must be an instance of URL', ERR_INVALID_ARG_TYPE);\n }\n checkProtocol(url, options?.[allowInsecureRequests] !== true);\n headers = prepareHeaders(headers);\n if (options?.DPoP) {\n assertDPoP(options.DPoP);\n await options.DPoP.addProof(url, headers, method.toUpperCase(), accessToken);\n }\n headers.set('authorization', `${headers.has('dpop') ? 'DPoP' : 'Bearer'} ${accessToken}`);\n const response = await (options?.[customFetch] || fetch)(url.href, {\n duplex: looseInstanceOf(body, ReadableStream) ? 'half' : undefined,\n body,\n headers: Object.fromEntries(headers.entries()),\n method,\n redirect: 'manual',\n signal: signal(url, options?.signal),\n });\n options?.DPoP?.cacheNonce(response, url);\n return response;\n}\nexport async function protectedResourceRequest(accessToken, method, url, headers, body, options) {\n const response = await resourceRequest(accessToken, method, url, headers, body, options);\n checkAuthenticationChallenges(response);\n return response;\n}\nexport async function userInfoRequest(as, client, accessToken, options) {\n assertAs(as);\n assertClient(client);\n const url = resolveEndpoint(as, 'userinfo_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const headers = prepareHeaders(options?.headers);\n if (client.userinfo_signed_response_alg) {\n headers.set('accept', 'application/jwt');\n }\n else {\n headers.set('accept', 'application/json');\n headers.append('accept', 'application/jwt');\n }\n return resourceRequest(accessToken, 'GET', url, headers, null, {\n ...options,\n [clockSkew]: getClockSkew(client),\n });\n}\nlet jwksMap;\nlet jwksRequests;\nlet jwksKeys;\nfunction setJwksCache(as, jwks, uat, cache) {\n jwksMap ||= new WeakMap();\n jwksMap.set(as, {\n jwks,\n uat,\n get age() {\n return epochTime() - this.uat;\n },\n });\n if (cache) {\n Object.assign(cache, { jwks: structuredClone(jwks), uat });\n }\n}\nfunction isFreshJwksCache(input) {\n if (typeof input !== 'object' || input === null) {\n return false;\n }\n if (!('uat' in input) || typeof input.uat !== 'number' || epochTime() - input.uat >= 300) {\n return false;\n }\n if (!('jwks' in input) ||\n !isJsonObject(input.jwks) ||\n !Array.isArray(input.jwks.keys) ||\n !Array.prototype.every.call(input.jwks.keys, isJsonObject)) {\n return false;\n }\n return true;\n}\nfunction clearJwksCache(as, cache) {\n jwksMap?.delete(as);\n delete cache?.jwks;\n delete cache?.uat;\n}\nasync function getPublicSigKeyFromIssuerJwksUri(as, options, header) {\n const { alg, kid } = header;\n checkSupportedJwsAlg(header);\n if (!jwksMap?.has(as) && isFreshJwksCache(options?.[jwksCache])) {\n setJwksCache(as, options?.[jwksCache].jwks, options?.[jwksCache].uat);\n }\n let jwks;\n let age;\n if (jwksMap?.has(as)) {\n ;\n ({ jwks, age } = jwksMap.get(as));\n if (age >= 300) {\n clearJwksCache(as, options?.[jwksCache]);\n return getPublicSigKeyFromIssuerJwksUri(as, options, header);\n }\n }\n else {\n const downloaded = await jwksRequest(as, options);\n jwks = downloaded.jwks;\n age = epochTime() - downloaded.uat;\n setJwksCache(as, jwks, downloaded.uat, options?.[jwksCache]);\n }\n let kty;\n switch (alg.slice(0, 2)) {\n case 'RS':\n case 'PS':\n kty = 'RSA';\n break;\n case 'ES':\n kty = 'EC';\n break;\n case 'Ed':\n kty = 'OKP';\n break;\n case 'ML':\n kty = 'AKP';\n break;\n default:\n throw new UnsupportedOperationError('unsupported JWS algorithm', { cause: { alg } });\n }\n const candidates = jwks.keys.filter((jwk) => {\n if (jwk.kty !== kty) {\n return false;\n }\n if (kid !== undefined && kid !== jwk.kid) {\n return false;\n }\n if (jwk.alg !== undefined && alg !== jwk.alg) {\n return false;\n }\n if (jwk.use !== undefined && jwk.use !== 'sig') {\n return false;\n }\n if (jwk.key_ops?.includes('verify') === false) {\n return false;\n }\n switch (true) {\n case alg === 'ES256' && jwk.crv !== 'P-256':\n case alg === 'ES384' && jwk.crv !== 'P-384':\n case alg === 'ES512' && jwk.crv !== 'P-521':\n case alg === 'Ed25519' && jwk.crv !== 'Ed25519':\n case alg === 'EdDSA' && jwk.crv !== 'Ed25519':\n return false;\n }\n return true;\n });\n const { 0: jwk, length } = candidates;\n if (!length) {\n if (age >= 60) {\n clearJwksCache(as, options?.[jwksCache]);\n return getPublicSigKeyFromIssuerJwksUri(as, options, header);\n }\n throw OPE('error when selecting a JWT verification key, no applicable keys found', KEY_SELECTION, { header, candidates, jwks_uri: new URL(as.jwks_uri) });\n }\n if (length !== 1) {\n throw OPE('error when selecting a JWT verification key, multiple applicable keys found, a \"kid\" JWT Header Parameter is required', KEY_SELECTION, { header, candidates, jwks_uri: new URL(as.jwks_uri) });\n }\n jwksKeys ||= new WeakMap();\n let keys = jwksKeys.get(jwk);\n if (!keys) {\n keys = new Map();\n jwksKeys.set(jwk, keys);\n }\n let key = keys.get(alg);\n if (!key) {\n key = importJwk(alg, jwk).catch((cause) => {\n keys.delete(alg);\n throw cause;\n });\n keys.set(alg, key);\n }\n return key;\n}\nexport const skipSubjectCheck = Symbol();\nexport function getContentType(input) {\n return input.headers.get('content-type')?.split(';')[0];\n}\nexport async function processUserInfoResponse(as, client, expectedSubject, response, options) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n checkAuthenticationChallenges(response);\n if (response.status !== 200) {\n throw OPE('\"response\" is not a conform UserInfo Endpoint response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);\n }\n assertReadableResponse(response);\n let json;\n if (getContentType(response) === 'application/jwt') {\n const { claims, jwt } = await validateJwt(await response.text(), checkSigningAlgorithm.bind(undefined, client.userinfo_signed_response_alg, as.userinfo_signing_alg_values_supported, undefined), getClockSkew(client), getClockTolerance(client), options?.[jweDecrypt])\n .then(validateOptionalAudience.bind(undefined, client.client_id))\n .then(validateOptionalIssuer.bind(undefined, as));\n jwtRefs.set(response, jwt);\n json = claims;\n }\n else {\n if (client.userinfo_signed_response_alg) {\n throw OPE('JWT UserInfo Response expected', JWT_USERINFO_EXPECTED, response);\n }\n json = await getResponseJsonBody(response);\n }\n assertString(json.sub, '\"response\" body \"sub\" property', INVALID_RESPONSE, { body: json });\n switch (expectedSubject) {\n case skipSubjectCheck:\n break;\n default:\n assertString(expectedSubject, '\"expectedSubject\"');\n if (json.sub !== expectedSubject) {\n throw OPE('unexpected \"response\" body \"sub\" property value', JSON_ATTRIBUTE_COMPARISON, {\n expected: expectedSubject,\n body: json,\n attribute: 'sub',\n });\n }\n }\n return json;\n}\nasync function authenticatedRequest(as, client, clientAuthentication, url, body, headers, options) {\n await clientAuthentication(as, client, body, headers);\n headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');\n return (options?.[customFetch] || fetch)(url.href, {\n body,\n headers: Object.fromEntries(headers.entries()),\n method: 'POST',\n redirect: 'manual',\n signal: signal(url, options?.signal),\n });\n}\nasync function tokenEndpointRequest(as, client, clientAuthentication, grantType, parameters, options) {\n const url = resolveEndpoint(as, 'token_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n parameters.set('grant_type', grantType);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n if (options?.DPoP !== undefined) {\n assertDPoP(options.DPoP);\n await options.DPoP.addProof(url, headers, 'POST');\n }\n const response = await authenticatedRequest(as, client, clientAuthentication, url, parameters, headers, options);\n options?.DPoP?.cacheNonce(response, url);\n return response;\n}\nexport async function refreshTokenGrantRequest(as, client, clientAuthentication, refreshToken, options) {\n assertAs(as);\n assertClient(client);\n assertString(refreshToken, '\"refreshToken\"');\n const parameters = new URLSearchParams(options?.additionalParameters);\n parameters.set('refresh_token', refreshToken);\n return tokenEndpointRequest(as, client, clientAuthentication, 'refresh_token', parameters, options);\n}\nconst idTokenClaims = new WeakMap();\nconst jwtRefs = new WeakMap();\nexport function getValidatedIdTokenClaims(ref) {\n if (!ref.id_token) {\n return undefined;\n }\n const claims = idTokenClaims.get(ref);\n if (!claims) {\n throw CodedTypeError('\"ref\" was already garbage collected or did not resolve from the proper sources', ERR_INVALID_ARG_VALUE);\n }\n return claims;\n}\nexport async function validateApplicationLevelSignature(as, ref, options) {\n assertAs(as);\n if (!jwtRefs.has(ref)) {\n throw CodedTypeError('\"ref\" does not contain a processed JWT Response to verify the signature of', ERR_INVALID_ARG_VALUE);\n }\n const { 0: protectedHeader, 1: payload, 2: encodedSignature } = jwtRefs.get(ref).split('.');\n const header = JSON.parse(buf(b64u(protectedHeader)));\n if (header.alg.startsWith('HS')) {\n throw new UnsupportedOperationError('unsupported JWS algorithm', { cause: { alg: header.alg } });\n }\n let key;\n key = await getPublicSigKeyFromIssuerJwksUri(as, options, header);\n await validateJwsSignature(protectedHeader, payload, key, b64u(encodedSignature));\n}\nasync function processGenericAccessTokenResponse(as, client, response, additionalRequiredIdTokenClaims, decryptFn, recognizedTokenTypes) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 200, 'Token Endpoint');\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.access_token, '\"response\" body \"access_token\" property', INVALID_RESPONSE, {\n body: json,\n });\n assertString(json.token_type, '\"response\" body \"token_type\" property', INVALID_RESPONSE, {\n body: json,\n });\n json.token_type = json.token_type.toLowerCase();\n if (json.expires_in !== undefined) {\n let expiresIn = typeof json.expires_in !== 'number' ? parseFloat(json.expires_in) : json.expires_in;\n assertNumber(expiresIn, true, '\"response\" body \"expires_in\" property', INVALID_RESPONSE, {\n body: json,\n });\n json.expires_in = expiresIn;\n }\n if (json.refresh_token !== undefined) {\n assertString(json.refresh_token, '\"response\" body \"refresh_token\" property', INVALID_RESPONSE, {\n body: json,\n });\n }\n if (json.scope !== undefined && typeof json.scope !== 'string') {\n throw OPE('\"response\" body \"scope\" property must be a string', INVALID_RESPONSE, { body: json });\n }\n if (json.id_token !== undefined) {\n assertString(json.id_token, '\"response\" body \"id_token\" property', INVALID_RESPONSE, {\n body: json,\n });\n const requiredClaims = [];\n if (client.require_auth_time === true) {\n requiredClaims.push('auth_time');\n }\n if (client.default_max_age !== undefined) {\n assertNumber(client.default_max_age, true, '\"client.default_max_age\"');\n requiredClaims.push('auth_time');\n }\n if (additionalRequiredIdTokenClaims?.length) {\n requiredClaims.push(...additionalRequiredIdTokenClaims);\n }\n const { claims, jwt } = await validateIdTokenClaims(as, client, json.id_token, requiredClaims, decryptFn);\n validateIdTokenAuthorizedParty(client, claims);\n validateIdTokenAuthTimeClaim(claims);\n jwtRefs.set(response, jwt);\n idTokenClaims.set(json, claims);\n }\n if (recognizedTokenTypes?.[json.token_type] !== undefined) {\n recognizedTokenTypes[json.token_type](response, json);\n }\n else if (json.token_type !== 'dpop' && json.token_type !== 'bearer') {\n throw new UnsupportedOperationError('unsupported `token_type` value', { cause: { body: json } });\n }\n return json;\n}\nfunction checkAuthenticationChallenges(response) {\n let challenges;\n if ((challenges = parseWwwAuthenticateChallenges(response))) {\n throw new WWWAuthenticateChallengeError('server responded with a challenge in the WWW-Authenticate HTTP Header', { cause: challenges, response });\n }\n}\nexport async function processRefreshTokenResponse(as, client, response, options) {\n return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nfunction validateOptionalAudience(expected, result) {\n if (result.claims.aud !== undefined) {\n return validateAudience(expected, result);\n }\n return result;\n}\nfunction validateAudience(expected, result) {\n if (Array.isArray(result.claims.aud)) {\n if (!result.claims.aud.includes(expected)) {\n throw OPE('unexpected JWT \"aud\" (audience) claim value', JWT_CLAIM_COMPARISON, {\n expected,\n claims: result.claims,\n claim: 'aud',\n });\n }\n }\n else if (result.claims.aud !== expected) {\n throw OPE('unexpected JWT \"aud\" (audience) claim value', JWT_CLAIM_COMPARISON, {\n expected,\n claims: result.claims,\n claim: 'aud',\n });\n }\n return result;\n}\nfunction validateOptionalIssuer(as, result) {\n if (result.claims.iss !== undefined) {\n return validateIssuer(as, result);\n }\n return result;\n}\nfunction validateIssuer(as, result) {\n const expected = as[_expectedIssuer]?.(result) ?? as.issuer;\n if (result.claims.iss !== expected) {\n throw OPE('unexpected JWT \"iss\" (issuer) claim value', JWT_CLAIM_COMPARISON, {\n expected,\n claims: result.claims,\n claim: 'iss',\n });\n }\n return result;\n}\nconst branded = new WeakSet();\nfunction brand(searchParams) {\n branded.add(searchParams);\n return searchParams;\n}\nexport const nopkce = Symbol();\nexport async function authorizationCodeGrantRequest(as, client, clientAuthentication, callbackParameters, redirectUri, codeVerifier, options) {\n assertAs(as);\n assertClient(client);\n if (!branded.has(callbackParameters)) {\n throw CodedTypeError('\"callbackParameters\" must be an instance of URLSearchParams obtained from \"validateAuthResponse()\", or \"validateJwtAuthResponse()', ERR_INVALID_ARG_VALUE);\n }\n assertString(redirectUri, '\"redirectUri\"');\n const code = getURLSearchParameter(callbackParameters, 'code');\n if (!code) {\n throw OPE('no authorization code in \"callbackParameters\"', INVALID_RESPONSE);\n }\n const parameters = new URLSearchParams(options?.additionalParameters);\n parameters.set('redirect_uri', redirectUri);\n parameters.set('code', code);\n if (codeVerifier !== nopkce) {\n assertString(codeVerifier, '\"codeVerifier\"');\n parameters.set('code_verifier', codeVerifier);\n }\n return tokenEndpointRequest(as, client, clientAuthentication, 'authorization_code', parameters, options);\n}\nconst jwtClaimNames = {\n aud: 'audience',\n c_hash: 'code hash',\n client_id: 'client id',\n exp: 'expiration time',\n iat: 'issued at',\n iss: 'issuer',\n jti: 'jwt id',\n nonce: 'nonce',\n s_hash: 'state hash',\n sub: 'subject',\n ath: 'access token hash',\n htm: 'http method',\n htu: 'http uri',\n cnf: 'confirmation',\n auth_time: 'authentication time',\n};\nfunction validatePresence(required, result) {\n for (const claim of required) {\n if (result.claims[claim] === undefined) {\n throw OPE(`JWT \"${claim}\" (${jwtClaimNames[claim]}) claim missing`, INVALID_RESPONSE, {\n claims: result.claims,\n });\n }\n }\n return result;\n}\nfunction validateStringClaim(claim, result) {\n if (typeof result.claims[claim] !== 'string') {\n throw OPE(`unexpected JWT \"${claim}\" (${jwtClaimNames[claim]}) claim type`, INVALID_RESPONSE, {\n claims: result.claims,\n });\n }\n return result;\n}\nfunction validateIdTokenClaims(as, client, idToken, requiredClaims, decryptFn) {\n return validateJwt(idToken, checkSigningAlgorithm.bind(undefined, client.id_token_signed_response_alg, as.id_token_signing_alg_values_supported, 'RS256'), getClockSkew(client), getClockTolerance(client), decryptFn)\n .then(validatePresence.bind(undefined, ['aud', 'exp', 'iat', 'iss', 'sub', ...requiredClaims]))\n .then(validateIssuer.bind(undefined, as))\n .then(validateAudience.bind(undefined, client.client_id))\n .then(validateStringClaim.bind(undefined, 'sub'));\n}\nfunction resolveIdTokenMaxAge(client, maxAge) {\n if (maxAge === skipAuthTimeCheck) {\n return maxAge;\n }\n const fromClient = maxAge === undefined;\n if (fromClient) {\n maxAge = client.default_max_age;\n }\n if (maxAge === undefined) {\n return skipAuthTimeCheck;\n }\n assertNumber(maxAge, true, fromClient ? '\"client.default_max_age\"' : '\"maxAge\" argument');\n return maxAge;\n}\nfunction validateIdTokenAuthTimeClaim(claims) {\n if (claims.auth_time !== undefined) {\n assertNumber(claims.auth_time, true, 'ID Token \"auth_time\" (authentication time)', INVALID_RESPONSE, { claims });\n }\n}\nfunction validateIdTokenAuthTime(client, claims, maxAge) {\n if (maxAge === skipAuthTimeCheck) {\n return;\n }\n const now = epochTime() + getClockSkew(client);\n const tolerance = getClockTolerance(client);\n if (claims.auth_time + maxAge < now - tolerance) {\n throw OPE('too much time has elapsed since the last End-User authentication', JWT_TIMESTAMP_CHECK, { claims, now, tolerance, claim: 'auth_time' });\n }\n}\nfunction validateIdTokenNonce(claims, expectedNonce) {\n const expected = expectedNonce === expectNoNonce ? undefined : expectedNonce;\n if (claims.nonce !== expected) {\n throw OPE('unexpected ID Token \"nonce\" claim value', JWT_CLAIM_COMPARISON, {\n expected,\n claims,\n claim: 'nonce',\n });\n }\n}\nfunction validateIdTokenAuthorizedParty(client, claims) {\n if (Array.isArray(claims.aud) && claims.aud.length !== 1) {\n if (claims.azp === undefined) {\n throw OPE('ID Token \"aud\" (audience) claim includes additional untrusted audiences', JWT_CLAIM_COMPARISON, { claims, claim: 'aud' });\n }\n if (claims.azp !== client.client_id) {\n throw OPE('unexpected ID Token \"azp\" (authorized party) claim value', JWT_CLAIM_COMPARISON, {\n expected: client.client_id,\n claims,\n claim: 'azp',\n });\n }\n }\n}\nexport const expectNoNonce = Symbol();\nexport const skipAuthTimeCheck = Symbol();\nexport async function processAuthorizationCodeResponse(as, client, response, options) {\n if (typeof options?.expectedNonce === 'string' ||\n typeof options?.maxAge === 'number' ||\n options?.requireIdToken) {\n return processAuthorizationCodeOpenIDResponse(as, client, response, options.expectedNonce, options.maxAge, options[jweDecrypt], options.recognizedTokenTypes);\n }\n return processAuthorizationCodeOAuth2Response(as, client, response, options?.maxAge, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nasync function processAuthorizationCodeOpenIDResponse(as, client, response, expectedNonce, maxAge, decryptFn, recognizedTokenTypes) {\n const additionalRequiredClaims = [];\n switch (expectedNonce) {\n case undefined:\n expectedNonce = expectNoNonce;\n break;\n case expectNoNonce:\n break;\n default:\n assertString(expectedNonce, '\"expectedNonce\" argument');\n additionalRequiredClaims.push('nonce');\n }\n maxAge = resolveIdTokenMaxAge(client, maxAge);\n if (maxAge !== skipAuthTimeCheck) {\n additionalRequiredClaims.push('auth_time');\n }\n const result = await processGenericAccessTokenResponse(as, client, response, additionalRequiredClaims, decryptFn, recognizedTokenTypes);\n assertString(result.id_token, '\"response\" body \"id_token\" property', INVALID_RESPONSE, {\n body: result,\n });\n const claims = getValidatedIdTokenClaims(result);\n validateIdTokenAuthTime(client, claims, maxAge);\n validateIdTokenNonce(claims, expectedNonce);\n return result;\n}\nasync function processAuthorizationCodeOAuth2Response(as, client, response, maxAge, decryptFn, recognizedTokenTypes) {\n const result = await processGenericAccessTokenResponse(as, client, response, undefined, decryptFn, recognizedTokenTypes);\n const claims = getValidatedIdTokenClaims(result);\n if (claims) {\n validateIdTokenAuthTime(client, claims, resolveIdTokenMaxAge(client, maxAge));\n validateIdTokenNonce(claims, expectNoNonce);\n }\n return result;\n}\nexport const WWW_AUTHENTICATE_CHALLENGE = 'OAUTH_WWW_AUTHENTICATE_CHALLENGE';\nexport const RESPONSE_BODY_ERROR = 'OAUTH_RESPONSE_BODY_ERROR';\nexport const UNSUPPORTED_OPERATION = 'OAUTH_UNSUPPORTED_OPERATION';\nexport const AUTHORIZATION_RESPONSE_ERROR = 'OAUTH_AUTHORIZATION_RESPONSE_ERROR';\nexport const JWT_USERINFO_EXPECTED = 'OAUTH_JWT_USERINFO_EXPECTED';\nexport const PARSE_ERROR = 'OAUTH_PARSE_ERROR';\nexport const INVALID_RESPONSE = 'OAUTH_INVALID_RESPONSE';\nexport const INVALID_REQUEST = 'OAUTH_INVALID_REQUEST';\nexport const RESPONSE_IS_NOT_JSON = 'OAUTH_RESPONSE_IS_NOT_JSON';\nexport const RESPONSE_IS_NOT_CONFORM = 'OAUTH_RESPONSE_IS_NOT_CONFORM';\nexport const HTTP_REQUEST_FORBIDDEN = 'OAUTH_HTTP_REQUEST_FORBIDDEN';\nexport const REQUEST_PROTOCOL_FORBIDDEN = 'OAUTH_REQUEST_PROTOCOL_FORBIDDEN';\nexport const JWT_TIMESTAMP_CHECK = 'OAUTH_JWT_TIMESTAMP_CHECK_FAILED';\nexport const JWT_CLAIM_COMPARISON = 'OAUTH_JWT_CLAIM_COMPARISON_FAILED';\nexport const JSON_ATTRIBUTE_COMPARISON = 'OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED';\nexport const KEY_SELECTION = 'OAUTH_KEY_SELECTION_FAILED';\nexport const MISSING_SERVER_METADATA = 'OAUTH_MISSING_SERVER_METADATA';\nexport const INVALID_SERVER_METADATA = 'OAUTH_INVALID_SERVER_METADATA';\nfunction checkJwtType(expected, result) {\n if (typeof result.header.typ !== 'string' || normalizeTyp(result.header.typ) !== expected) {\n throw OPE('unexpected JWT \"typ\" header parameter value', INVALID_RESPONSE, {\n header: result.header,\n });\n }\n return result;\n}\nexport async function clientCredentialsGrantRequest(as, client, clientAuthentication, parameters, options) {\n assertAs(as);\n assertClient(client);\n return tokenEndpointRequest(as, client, clientAuthentication, 'client_credentials', new URLSearchParams(parameters), options);\n}\nexport async function genericTokenEndpointRequest(as, client, clientAuthentication, grantType, parameters, options) {\n assertAs(as);\n assertClient(client);\n assertString(grantType, '\"grantType\"');\n return tokenEndpointRequest(as, client, clientAuthentication, grantType, new URLSearchParams(parameters), options);\n}\nexport async function processGenericTokenEndpointResponse(as, client, response, options) {\n return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nexport async function processClientCredentialsResponse(as, client, response, options) {\n return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nexport async function revocationRequest(as, client, clientAuthentication, token, options) {\n assertAs(as);\n assertClient(client);\n assertString(token, '\"token\"');\n const url = resolveEndpoint(as, 'revocation_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const body = new URLSearchParams(options?.additionalParameters);\n body.set('token', token);\n const headers = prepareHeaders(options?.headers);\n headers.delete('accept');\n return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);\n}\nexport async function processRevocationResponse(response) {\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 200, 'Revocation Endpoint');\n return undefined;\n}\nfunction assertReadableResponse(response) {\n if (response.bodyUsed) {\n throw CodedTypeError('\"response\" body has been used already', ERR_INVALID_ARG_VALUE);\n }\n}\nexport async function introspectionRequest(as, client, clientAuthentication, token, options) {\n assertAs(as);\n assertClient(client);\n assertString(token, '\"token\"');\n const url = resolveEndpoint(as, 'introspection_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const body = new URLSearchParams(options?.additionalParameters);\n body.set('token', token);\n const headers = prepareHeaders(options?.headers);\n if (options?.requestJwtResponse ?? client.introspection_signed_response_alg) {\n headers.set('accept', 'application/token-introspection+jwt');\n }\n else {\n headers.set('accept', 'application/json');\n }\n return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);\n}\nexport async function processIntrospectionResponse(as, client, response, options) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 200, 'Introspection Endpoint');\n let json;\n if (getContentType(response) === 'application/token-introspection+jwt') {\n assertReadableResponse(response);\n const { claims, jwt } = await validateJwt(await response.text(), checkSigningAlgorithm.bind(undefined, client.introspection_signed_response_alg, as.introspection_signing_alg_values_supported, 'RS256'), getClockSkew(client), getClockTolerance(client), options?.[jweDecrypt])\n .then(checkJwtType.bind(undefined, 'token-introspection+jwt'))\n .then(validatePresence.bind(undefined, ['aud', 'iat', 'iss']))\n .then(validateIssuer.bind(undefined, as))\n .then(validateAudience.bind(undefined, client.client_id));\n jwtRefs.set(response, jwt);\n if (!isJsonObject(claims.token_introspection)) {\n throw OPE('JWT \"token_introspection\" claim must be a JSON object', INVALID_RESPONSE, {\n claims,\n });\n }\n json = claims.token_introspection;\n }\n else {\n assertReadableResponse(response);\n json = await getResponseJsonBody(response);\n }\n if (typeof json.active !== 'boolean') {\n throw OPE('\"response\" body \"active\" property must be a boolean', INVALID_RESPONSE, {\n body: json,\n });\n }\n return json;\n}\nasync function jwksRequest(as, options) {\n assertAs(as);\n const url = resolveEndpoint(as, 'jwks_uri', false, options?.[allowInsecureRequests] !== true);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n headers.append('accept', 'application/jwk-set+json');\n const requestHeaders = Object.fromEntries(headers.entries());\n const headersKey = JSON.stringify(requestHeaders);\n const fetcher = options?.[customFetch] || fetch;\n const requestSignal = signal(url, options?.signal);\n jwksRequests ||= new WeakMap();\n const requests = jwksRequests.get(as) ?? new Set();\n for (const pending of requests) {\n if (pending.url === url.href &&\n pending.headers === headersKey &&\n pending.fetch === fetcher &&\n pending.signal === requestSignal) {\n return pending.promise;\n }\n }\n const pending = {\n url: url.href,\n headers: headersKey,\n fetch: fetcher,\n signal: requestSignal,\n promise: Promise.resolve()\n .then(() => fetcher(url.href, {\n body: undefined,\n headers: requestHeaders,\n method: 'GET',\n redirect: 'manual',\n signal: requestSignal,\n }))\n .then(processJwksResponse)\n .then((jwks) => {\n const uat = epochTime();\n setJwksCache(as, jwks, uat);\n return { jwks, uat };\n })\n .finally(() => {\n requests.delete(pending);\n if (!requests.size) {\n jwksRequests.delete(as);\n }\n }),\n };\n requests.add(pending);\n jwksRequests.set(as, requests);\n return pending.promise;\n}\nasync function processJwksResponse(response) {\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n if (response.status !== 200) {\n throw OPE('\"response\" is not a conform JSON Web Key Set response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);\n }\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response, (response) => assertContentTypes(response, 'application/json', 'application/jwk-set+json'));\n if (!Array.isArray(json.keys)) {\n throw OPE('\"response\" body \"keys\" property must be an array', INVALID_RESPONSE, { body: json });\n }\n if (!Array.prototype.every.call(json.keys, isJsonObject)) {\n throw OPE('\"response\" body \"keys\" property members must be JWK formatted objects', INVALID_RESPONSE, { body: json });\n }\n return json;\n}\nfunction supported(alg) {\n switch (alg) {\n case 'PS256':\n case 'ES256':\n case 'RS256':\n case 'PS384':\n case 'ES384':\n case 'RS384':\n case 'PS512':\n case 'ES512':\n case 'RS512':\n case 'Ed25519':\n case 'EdDSA':\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n return true;\n default:\n return false;\n }\n}\nfunction checkSupportedJwsAlg(header) {\n if (!supported(header.alg)) {\n throw new UnsupportedOperationError('unsupported JWS \"alg\" identifier', {\n cause: { alg: header.alg },\n });\n }\n}\nfunction checkRsaKeyAlgorithm(key) {\n const { algorithm } = key;\n if (typeof algorithm.modulusLength !== 'number' || algorithm.modulusLength < 2048) {\n throw new UnsupportedOperationError(`unsupported ${algorithm.name} modulusLength`, {\n cause: key,\n });\n }\n}\nfunction ecdsaHashName(key) {\n const { algorithm } = key;\n switch (algorithm.namedCurve) {\n case 'P-256':\n return 'SHA-256';\n case 'P-384':\n return 'SHA-384';\n case 'P-521':\n return 'SHA-512';\n default:\n throw new UnsupportedOperationError('unsupported ECDSA namedCurve', { cause: key });\n }\n}\nfunction keyToSubtle(key) {\n switch (key.algorithm.name) {\n case 'ECDSA':\n return {\n name: key.algorithm.name,\n hash: ecdsaHashName(key),\n };\n case 'RSA-PSS': {\n checkRsaKeyAlgorithm(key);\n switch (key.algorithm.hash.name) {\n case 'SHA-256':\n case 'SHA-384':\n case 'SHA-512':\n return {\n name: key.algorithm.name,\n saltLength: parseInt(key.algorithm.hash.name.slice(-3), 10) >> 3,\n };\n default:\n throw new UnsupportedOperationError('unsupported RSA-PSS hash name', { cause: key });\n }\n }\n case 'RSASSA-PKCS1-v1_5':\n checkRsaKeyAlgorithm(key);\n return key.algorithm.name;\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n case 'Ed25519':\n return key.algorithm.name;\n }\n throw new UnsupportedOperationError('unsupported CryptoKey algorithm name', { cause: key });\n}\nasync function validateJwsSignature(protectedHeader, payload, key, signature) {\n const data = buf(`${protectedHeader}.${payload}`);\n const algorithm = keyToSubtle(key);\n const verified = await crypto.subtle.verify(algorithm, key, signature, data);\n if (!verified) {\n throw OPE('JWT signature verification failed', INVALID_RESPONSE, {\n key,\n data,\n signature,\n algorithm,\n });\n }\n}\nasync function validateJwt(jws, checkAlg, clockSkew, clockTolerance, decryptJwt) {\n let { 0: protectedHeader, 1: payload, length } = jws.split('.');\n if (length === 5) {\n if (decryptJwt !== undefined) {\n jws = await decryptJwt(jws);\n ({ 0: protectedHeader, 1: payload, length } = jws.split('.'));\n }\n else {\n throw new UnsupportedOperationError('JWE decryption is not configured', { cause: jws });\n }\n }\n if (length !== 3) {\n throw OPE('Invalid JWT', INVALID_RESPONSE, jws);\n }\n let header;\n try {\n header = JSON.parse(buf(b64u(protectedHeader)));\n }\n catch (cause) {\n throw OPE('failed to parse JWT Header body as base64url encoded JSON', PARSE_ERROR, cause);\n }\n if (!isJsonObject(header)) {\n throw OPE('JWT Header must be a top level object', INVALID_RESPONSE, jws);\n }\n checkAlg(header);\n if (header.crit !== undefined) {\n throw new UnsupportedOperationError('no JWT \"crit\" header parameter extensions are supported', {\n cause: { header },\n });\n }\n let claims;\n try {\n claims = JSON.parse(buf(b64u(payload)));\n }\n catch (cause) {\n throw OPE('failed to parse JWT Payload body as base64url encoded JSON', PARSE_ERROR, cause);\n }\n if (!isJsonObject(claims)) {\n throw OPE('JWT Payload must be a top level object', INVALID_RESPONSE, jws);\n }\n const now = epochTime() + clockSkew;\n if (claims.exp !== undefined) {\n if (typeof claims.exp !== 'number') {\n throw OPE('unexpected JWT \"exp\" (expiration time) claim type', INVALID_RESPONSE, { claims });\n }\n if (claims.exp <= now - clockTolerance) {\n throw OPE('unexpected JWT \"exp\" (expiration time) claim value, expiration is past current timestamp', JWT_TIMESTAMP_CHECK, { claims, now, tolerance: clockTolerance, claim: 'exp' });\n }\n }\n if (claims.iat !== undefined) {\n if (typeof claims.iat !== 'number') {\n throw OPE('unexpected JWT \"iat\" (issued at) claim type', INVALID_RESPONSE, { claims });\n }\n }\n if (claims.iss !== undefined) {\n if (typeof claims.iss !== 'string') {\n throw OPE('unexpected JWT \"iss\" (issuer) claim type', INVALID_RESPONSE, { claims });\n }\n }\n if (claims.nbf !== undefined) {\n if (typeof claims.nbf !== 'number') {\n throw OPE('unexpected JWT \"nbf\" (not before) claim type', INVALID_RESPONSE, { claims });\n }\n if (claims.nbf > now + clockTolerance) {\n throw OPE('unexpected JWT \"nbf\" (not before) claim value', JWT_TIMESTAMP_CHECK, {\n claims,\n now,\n tolerance: clockTolerance,\n claim: 'nbf',\n });\n }\n }\n if (claims.aud !== undefined) {\n if (typeof claims.aud !== 'string' && !Array.isArray(claims.aud)) {\n throw OPE('unexpected JWT \"aud\" (audience) claim type', INVALID_RESPONSE, { claims });\n }\n }\n return { header, claims, jwt: jws };\n}\nexport async function validateJwtAuthResponse(as, client, parameters, expectedState, options) {\n assertAs(as);\n assertClient(client);\n if (parameters instanceof URL) {\n parameters = parameters.searchParams;\n }\n if (!(parameters instanceof URLSearchParams)) {\n throw CodedTypeError('\"parameters\" must be an instance of URLSearchParams, or URL', ERR_INVALID_ARG_TYPE);\n }\n const response = getURLSearchParameter(parameters, 'response');\n if (!response) {\n throw OPE('\"parameters\" does not contain a JARM response', INVALID_RESPONSE);\n }\n const { claims, header, jwt } = await validateJwt(response, checkSigningAlgorithm.bind(undefined, client.authorization_signed_response_alg, as.authorization_signing_alg_values_supported, 'RS256'), getClockSkew(client), getClockTolerance(client), options?.[jweDecrypt])\n .then(validatePresence.bind(undefined, ['aud', 'exp', 'iss']))\n .then(validateIssuer.bind(undefined, as))\n .then(validateAudience.bind(undefined, client.client_id));\n const { 0: protectedHeader, 1: payload, 2: encodedSignature } = jwt.split('.');\n const signature = b64u(encodedSignature);\n const key = await getPublicSigKeyFromIssuerJwksUri(as, options, header);\n await validateJwsSignature(protectedHeader, payload, key, signature);\n const result = new URLSearchParams();\n for (const [key, value] of Object.entries(claims)) {\n if (typeof value === 'string' && key !== 'aud') {\n result.set(key, value);\n }\n }\n return validateAuthResponse(as, client, result, expectedState);\n}\nasync function idTokenHash(data, header, claimName) {\n let algorithm;\n switch (header.alg) {\n case 'RS256':\n case 'PS256':\n case 'ES256':\n algorithm = 'SHA-256';\n break;\n case 'RS384':\n case 'PS384':\n case 'ES384':\n algorithm = 'SHA-384';\n break;\n case 'RS512':\n case 'PS512':\n case 'ES512':\n case 'Ed25519':\n case 'EdDSA':\n algorithm = 'SHA-512';\n break;\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n algorithm = { name: 'cSHAKE256', length: 512, outputLength: 512 };\n break;\n default:\n throw new UnsupportedOperationError(`unsupported JWS algorithm for ${claimName} calculation`, { cause: { alg: header.alg } });\n }\n const digest = await crypto.subtle.digest(algorithm, buf(data));\n return b64u(digest.slice(0, digest.byteLength / 2));\n}\nasync function idTokenHashMatches(data, actual, header, claimName) {\n const expected = await idTokenHash(data, header, claimName);\n return actual === expected;\n}\nexport async function validateDetachedSignatureResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options) {\n return validateHybridResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options, true);\n}\nexport async function validateCodeIdTokenResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options) {\n return validateHybridResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options, false);\n}\nasync function consumeStream(request) {\n if (request.bodyUsed) {\n throw CodedTypeError('form_post Request instances must contain a readable body', ERR_INVALID_ARG_VALUE, { cause: request });\n }\n return request.text();\n}\nexport async function formPostResponse(request) {\n if (request.method !== 'POST') {\n throw CodedTypeError('form_post responses are expected to use the POST method', ERR_INVALID_ARG_VALUE, { cause: request });\n }\n if (getContentType(request) !== 'application/x-www-form-urlencoded') {\n throw CodedTypeError('form_post responses are expected to use the application/x-www-form-urlencoded content-type', ERR_INVALID_ARG_VALUE, { cause: request });\n }\n return consumeStream(request);\n}\nasync function validateHybridResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options, fapi) {\n assertAs(as);\n assertClient(client);\n if (parameters instanceof URL) {\n if (!parameters.hash.length) {\n throw CodedTypeError('\"parameters\" as an instance of URL must contain a hash (fragment) with the Authorization Response parameters', ERR_INVALID_ARG_VALUE);\n }\n parameters = new URLSearchParams(parameters.hash.slice(1));\n }\n else if (looseInstanceOf(parameters, Request)) {\n parameters = new URLSearchParams(await formPostResponse(parameters));\n }\n else if (parameters instanceof URLSearchParams) {\n parameters = new URLSearchParams(parameters);\n }\n else {\n throw CodedTypeError('\"parameters\" must be an instance of URLSearchParams, URL, or Response', ERR_INVALID_ARG_TYPE);\n }\n const id_token = getURLSearchParameter(parameters, 'id_token');\n parameters.delete('id_token');\n switch (expectedState) {\n case undefined:\n case expectNoState:\n break;\n default:\n assertString(expectedState, '\"expectedState\" argument');\n }\n const result = validateAuthResponse({\n ...as,\n authorization_response_iss_parameter_supported: false,\n }, client, parameters, expectedState);\n if (!id_token) {\n throw OPE('\"parameters\" does not contain an ID Token', INVALID_RESPONSE);\n }\n const code = getURLSearchParameter(parameters, 'code');\n if (!code) {\n throw OPE('\"parameters\" does not contain an Authorization Code', INVALID_RESPONSE);\n }\n const requiredClaims = ['nonce', 'c_hash'];\n const state = parameters.get('state');\n if (fapi && (typeof expectedState === 'string' || state !== null)) {\n requiredClaims.push('s_hash');\n }\n maxAge = resolveIdTokenMaxAge(client, maxAge);\n if (client.require_auth_time || maxAge !== skipAuthTimeCheck) {\n requiredClaims.push('auth_time');\n }\n const { claims, header, jwt } = await validateIdTokenClaims(as, client, id_token, requiredClaims, options?.[jweDecrypt]);\n const clockSkew = getClockSkew(client);\n const now = epochTime() + clockSkew;\n if (claims.iat < now - 3600) {\n throw OPE('unexpected JWT \"iat\" (issued at) claim value, it is too far in the past', JWT_TIMESTAMP_CHECK, { now, claims, claim: 'iat' });\n }\n assertString(claims.c_hash, 'ID Token \"c_hash\" (code hash) claim value', INVALID_RESPONSE, {\n claims,\n });\n validateIdTokenAuthTimeClaim(claims);\n validateIdTokenAuthTime(client, claims, maxAge);\n assertString(expectedNonce, '\"expectedNonce\" argument');\n validateIdTokenNonce(claims, expectedNonce);\n validateIdTokenAuthorizedParty(client, claims);\n const { 0: protectedHeader, 1: payload, 2: encodedSignature } = jwt.split('.');\n const signature = b64u(encodedSignature);\n const key = await getPublicSigKeyFromIssuerJwksUri(as, options, header);\n await validateJwsSignature(protectedHeader, payload, key, signature);\n if ((await idTokenHashMatches(code, claims.c_hash, header, 'c_hash')) !== true) {\n throw OPE('invalid ID Token \"c_hash\" (code hash) claim value', JWT_CLAIM_COMPARISON, {\n code,\n alg: header.alg,\n claim: 'c_hash',\n claims,\n });\n }\n if ((fapi && state !== null) || claims.s_hash !== undefined) {\n assertString(claims.s_hash, 'ID Token \"s_hash\" (state hash) claim value', INVALID_RESPONSE, {\n claims,\n });\n assertString(state, '\"state\" response parameter', INVALID_RESPONSE, { parameters });\n if ((await idTokenHashMatches(state, claims.s_hash, header, 's_hash')) !== true) {\n throw OPE('invalid ID Token \"s_hash\" (state hash) claim value', JWT_CLAIM_COMPARISON, {\n state,\n alg: header.alg,\n claim: 's_hash',\n claims,\n });\n }\n }\n return result;\n}\nfunction checkSigningAlgorithm(client, issuer, fallback, header) {\n if (client !== undefined) {\n if (typeof client === 'string' ? header.alg !== client : !client.includes(header.alg)) {\n throw OPE('unexpected JWT \"alg\" header parameter', INVALID_RESPONSE, {\n header,\n expected: client,\n reason: 'client configuration',\n });\n }\n return;\n }\n if (Array.isArray(issuer)) {\n if (!issuer.includes(header.alg)) {\n throw OPE('unexpected JWT \"alg\" header parameter', INVALID_RESPONSE, {\n header,\n expected: issuer,\n reason: 'authorization server metadata',\n });\n }\n return;\n }\n if (fallback !== undefined) {\n if (typeof fallback === 'string'\n ? header.alg !== fallback\n : typeof fallback === 'function'\n ? !fallback(header.alg)\n : !fallback.includes(header.alg)) {\n throw OPE('unexpected JWT \"alg\" header parameter', INVALID_RESPONSE, {\n header,\n expected: fallback,\n reason: 'default value',\n });\n }\n return;\n }\n throw OPE('missing client or server configuration to verify used JWT \"alg\" header parameter', undefined, { client, issuer, fallback });\n}\nfunction getURLSearchParameter(parameters, name) {\n const { 0: value, length } = parameters.getAll(name);\n if (length > 1) {\n throw OPE(`\"${name}\" parameter must be provided only once`, INVALID_RESPONSE);\n }\n return value;\n}\nexport const skipStateCheck = Symbol();\nexport const expectNoState = Symbol();\nexport function validateAuthResponse(as, client, parameters, expectedState) {\n assertAs(as);\n assertClient(client);\n if (parameters instanceof URL) {\n parameters = parameters.searchParams;\n }\n if (!(parameters instanceof URLSearchParams)) {\n throw CodedTypeError('\"parameters\" must be an instance of URLSearchParams, or URL', ERR_INVALID_ARG_TYPE);\n }\n if (getURLSearchParameter(parameters, 'response')) {\n throw OPE('\"parameters\" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()', INVALID_RESPONSE, { parameters });\n }\n const iss = getURLSearchParameter(parameters, 'iss');\n const state = getURLSearchParameter(parameters, 'state');\n if (!iss && as.authorization_response_iss_parameter_supported) {\n throw OPE('response parameter \"iss\" (issuer) missing', INVALID_RESPONSE, { parameters });\n }\n if (iss && iss !== as.issuer) {\n throw OPE('unexpected \"iss\" (issuer) response parameter value', INVALID_RESPONSE, {\n expected: as.issuer,\n parameters,\n });\n }\n switch (expectedState) {\n case undefined:\n case expectNoState:\n if (state !== undefined) {\n throw OPE('unexpected \"state\" response parameter encountered', INVALID_RESPONSE, {\n expected: undefined,\n parameters,\n });\n }\n break;\n case skipStateCheck:\n break;\n default:\n assertString(expectedState, '\"expectedState\" argument');\n if (state !== expectedState) {\n throw OPE(state === undefined\n ? 'response parameter \"state\" missing'\n : 'unexpected \"state\" response parameter value', INVALID_RESPONSE, { expected: expectedState, parameters });\n }\n }\n const error = getURLSearchParameter(parameters, 'error');\n if (error) {\n throw new AuthorizationResponseError('authorization response from the server is an error', {\n cause: parameters,\n });\n }\n const id_token = getURLSearchParameter(parameters, 'id_token');\n const token = getURLSearchParameter(parameters, 'token');\n if (id_token !== undefined || token !== undefined) {\n throw new UnsupportedOperationError('implicit and hybrid flows are not supported');\n }\n return brand(new URLSearchParams(parameters));\n}\nfunction algToSubtle(alg) {\n switch (alg) {\n case 'PS256':\n case 'PS384':\n case 'PS512':\n return { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` };\n case 'RS256':\n case 'RS384':\n case 'RS512':\n return { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` };\n case 'ES256':\n case 'ES384':\n return { name: 'ECDSA', namedCurve: `P-${alg.slice(-3)}` };\n case 'ES512':\n return { name: 'ECDSA', namedCurve: 'P-521' };\n case 'EdDSA':\n return 'Ed25519';\n case 'Ed25519':\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n return alg;\n default:\n throw new UnsupportedOperationError('unsupported JWS algorithm', { cause: { alg } });\n }\n}\nasync function importJwk(alg, jwk) {\n const { ext, key_ops, use, ...key } = jwk;\n return crypto.subtle.importKey('jwk', key, algToSubtle(alg), true, ['verify']);\n}\nexport async function deviceAuthorizationRequest(as, client, clientAuthentication, parameters, options) {\n assertAs(as);\n assertClient(client);\n const url = resolveEndpoint(as, 'device_authorization_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const body = new URLSearchParams(parameters);\n body.set('client_id', client.client_id);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);\n}\nexport async function processDeviceAuthorizationResponse(as, client, response) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 200, 'Device Authorization Endpoint');\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.device_code, '\"response\" body \"device_code\" property', INVALID_RESPONSE, {\n body: json,\n });\n assertString(json.user_code, '\"response\" body \"user_code\" property', INVALID_RESPONSE, {\n body: json,\n });\n assertString(json.verification_uri, '\"response\" body \"verification_uri\" property', INVALID_RESPONSE, { body: json });\n let expiresIn = typeof json.expires_in !== 'number' ? parseFloat(json.expires_in) : json.expires_in;\n assertNumber(expiresIn, true, '\"response\" body \"expires_in\" property', INVALID_RESPONSE, {\n body: json,\n });\n json.expires_in = expiresIn;\n if (json.verification_uri_complete !== undefined) {\n assertString(json.verification_uri_complete, '\"response\" body \"verification_uri_complete\" property', INVALID_RESPONSE, { body: json });\n }\n if (json.interval !== undefined) {\n assertNumber(json.interval, false, '\"response\" body \"interval\" property', INVALID_RESPONSE, {\n body: json,\n });\n }\n return json;\n}\nexport async function deviceCodeGrantRequest(as, client, clientAuthentication, deviceCode, options) {\n assertAs(as);\n assertClient(client);\n assertString(deviceCode, '\"deviceCode\"');\n const parameters = new URLSearchParams(options?.additionalParameters);\n parameters.set('device_code', deviceCode);\n return tokenEndpointRequest(as, client, clientAuthentication, 'urn:ietf:params:oauth:grant-type:device_code', parameters, options);\n}\nexport async function processDeviceCodeResponse(as, client, response, options) {\n return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nexport async function generateKeyPair(alg, options) {\n assertString(alg, '\"alg\"');\n const algorithm = algToSubtle(alg);\n if (alg.startsWith('PS') || alg.startsWith('RS')) {\n Object.assign(algorithm, {\n modulusLength: options?.modulusLength ?? 2048,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n });\n }\n return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, [\n 'sign',\n 'verify',\n ]);\n}\nfunction normalizeHtu(htu) {\n const url = new URL(htu);\n url.search = '';\n url.hash = '';\n return url.href;\n}\nasync function validateDPoP(request, accessToken, accessTokenClaims, options) {\n const headerValue = request.headers.get('dpop');\n if (headerValue === null) {\n throw OPE('operation indicated DPoP use but the request has no DPoP HTTP Header', INVALID_REQUEST, { headers: request.headers });\n }\n if (request.headers.get('authorization')?.toLowerCase().startsWith('dpop ') === false) {\n throw OPE(`operation indicated DPoP use but the request's Authorization HTTP Header scheme is not DPoP`, INVALID_REQUEST, { headers: request.headers });\n }\n if (typeof accessTokenClaims.cnf?.jkt !== 'string') {\n throw OPE('operation indicated DPoP use but the JWT Access Token has no jkt confirmation claim', INVALID_REQUEST, { claims: accessTokenClaims });\n }\n const clockSkew = getClockSkew(options);\n const proof = await validateJwt(headerValue, checkSigningAlgorithm.bind(undefined, options?.signingAlgorithms, undefined, supported), clockSkew, getClockTolerance(options), undefined)\n .then(checkJwtType.bind(undefined, 'dpop+jwt'))\n .then(validatePresence.bind(undefined, ['iat', 'jti', 'ath', 'htm', 'htu']))\n .then(validateStringClaim.bind(undefined, 'jti'));\n const now = epochTime() + clockSkew;\n const diff = Math.abs(now - proof.claims.iat);\n if (diff > 300) {\n throw OPE('DPoP Proof iat is not recent enough', JWT_TIMESTAMP_CHECK, {\n now,\n claims: proof.claims,\n claim: 'iat',\n });\n }\n if (proof.claims.htm !== request.method) {\n throw OPE('DPoP Proof htm mismatch', JWT_CLAIM_COMPARISON, {\n expected: request.method,\n claims: proof.claims,\n claim: 'htm',\n });\n }\n if (typeof proof.claims.htu !== 'string' ||\n normalizeHtu(proof.claims.htu) !== normalizeHtu(request.url)) {\n throw OPE('DPoP Proof htu mismatch', JWT_CLAIM_COMPARISON, {\n expected: normalizeHtu(request.url),\n claims: proof.claims,\n claim: 'htu',\n });\n }\n {\n const expected = b64u(await crypto.subtle.digest('SHA-256', buf(accessToken)));\n if (proof.claims.ath !== expected) {\n throw OPE('DPoP Proof ath mismatch', JWT_CLAIM_COMPARISON, {\n expected,\n claims: proof.claims,\n claim: 'ath',\n });\n }\n }\n const { jwk, alg } = proof.header;\n if (!isJsonObject(jwk)) {\n throw OPE('DPoP Proof jwk header parameter must be a JSON object', INVALID_REQUEST, {\n header: proof.header,\n });\n }\n {\n const expected = await calculateJwkThumbprint(jwk);\n if (accessTokenClaims.cnf.jkt !== expected) {\n throw OPE('JWT Access Token confirmation mismatch', JWT_CLAIM_COMPARISON, {\n expected,\n claims: accessTokenClaims,\n claim: 'cnf.jkt',\n });\n }\n }\n const { 0: protectedHeader, 1: payload, 2: encodedSignature } = headerValue.split('.');\n const signature = b64u(encodedSignature);\n const key = await importJwk(alg, jwk);\n if (key.type !== 'public') {\n throw OPE('DPoP Proof jwk header parameter must contain a public key', INVALID_REQUEST, {\n header: proof.header,\n });\n }\n await validateJwsSignature(protectedHeader, payload, key, signature);\n}\nexport async function validateJwtAccessToken(as, request, expectedAudience, options) {\n assertAs(as);\n if (!looseInstanceOf(request, Request)) {\n throw CodedTypeError('\"request\" must be an instance of Request', ERR_INVALID_ARG_TYPE);\n }\n assertString(expectedAudience, '\"expectedAudience\"');\n const authorization = request.headers.get('authorization');\n if (authorization === null) {\n throw OPE('\"request\" is missing an Authorization HTTP Header', INVALID_REQUEST, {\n headers: request.headers,\n });\n }\n let { 0: scheme, 1: accessToken, length } = authorization.split(/ +/);\n scheme = scheme.toLowerCase();\n switch (scheme) {\n case 'dpop':\n case 'bearer':\n break;\n default:\n throw new UnsupportedOperationError('unsupported Authorization HTTP Header scheme', {\n cause: { headers: request.headers },\n });\n }\n if (length !== 2) {\n throw OPE('invalid Authorization HTTP Header format', INVALID_REQUEST, {\n headers: request.headers,\n });\n }\n const requiredClaims = [\n 'iss',\n 'exp',\n 'aud',\n 'sub',\n 'iat',\n 'jti',\n 'client_id',\n ];\n if (options?.requireDPoP || scheme === 'dpop' || request.headers.has('dpop')) {\n requiredClaims.push('cnf');\n }\n const { claims, header } = await validateJwt(accessToken, checkSigningAlgorithm.bind(undefined, options?.signingAlgorithms, undefined, supported), getClockSkew(options), getClockTolerance(options), undefined)\n .then(checkJwtType.bind(undefined, 'at+jwt'))\n .then(validatePresence.bind(undefined, requiredClaims))\n .then(validateIssuer.bind(undefined, as))\n .then(validateAudience.bind(undefined, expectedAudience))\n .catch(reassignRSCode);\n for (const claim of ['client_id', 'jti', 'sub']) {\n if (typeof claims[claim] !== 'string') {\n throw OPE(`unexpected JWT \"${claim}\" claim type`, INVALID_REQUEST, { claims });\n }\n }\n if ('cnf' in claims) {\n if (!isJsonObject(claims.cnf)) {\n throw OPE('unexpected JWT \"cnf\" (confirmation) claim value', INVALID_REQUEST, { claims });\n }\n const { 0: cnf, length } = Object.keys(claims.cnf);\n if (length) {\n if (length !== 1) {\n throw new UnsupportedOperationError('multiple confirmation claims are not supported', {\n cause: { claims },\n });\n }\n if (cnf !== 'jkt') {\n throw new UnsupportedOperationError('unsupported JWT Confirmation method', {\n cause: { claims },\n });\n }\n }\n }\n const { 0: protectedHeader, 1: payload, 2: encodedSignature } = accessToken.split('.');\n const signature = b64u(encodedSignature);\n const key = await getPublicSigKeyFromIssuerJwksUri(as, options, header);\n await validateJwsSignature(protectedHeader, payload, key, signature);\n if (options?.requireDPoP ||\n scheme === 'dpop' ||\n claims.cnf?.jkt !== undefined ||\n request.headers.has('dpop')) {\n await validateDPoP(request, accessToken, claims, options).catch(reassignRSCode);\n }\n return claims;\n}\nfunction reassignRSCode(err) {\n if (err instanceof OperationProcessingError && err?.code === INVALID_REQUEST) {\n err.code = INVALID_RESPONSE;\n }\n throw err;\n}\nexport async function backchannelAuthenticationRequest(as, client, clientAuthentication, parameters, options) {\n assertAs(as);\n assertClient(client);\n const url = resolveEndpoint(as, 'backchannel_authentication_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const body = new URLSearchParams(parameters);\n body.set('client_id', client.client_id);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);\n}\nexport async function processBackchannelAuthenticationResponse(as, client, response) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 200, 'Backchannel Authentication Endpoint');\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.auth_req_id, '\"response\" body \"auth_req_id\" property', INVALID_RESPONSE, {\n body: json,\n });\n let expiresIn = typeof json.expires_in !== 'number' ? parseFloat(json.expires_in) : json.expires_in;\n assertNumber(expiresIn, true, '\"response\" body \"expires_in\" property', INVALID_RESPONSE, {\n body: json,\n });\n json.expires_in = expiresIn;\n if (json.interval !== undefined) {\n assertNumber(json.interval, false, '\"response\" body \"interval\" property', INVALID_RESPONSE, {\n body: json,\n });\n }\n return json;\n}\nexport async function backchannelAuthenticationGrantRequest(as, client, clientAuthentication, authReqId, options) {\n assertAs(as);\n assertClient(client);\n assertString(authReqId, '\"authReqId\"');\n const parameters = new URLSearchParams(options?.additionalParameters);\n parameters.set('auth_req_id', authReqId);\n return tokenEndpointRequest(as, client, clientAuthentication, 'urn:openid:params:grant-type:ciba', parameters, options);\n}\nexport async function processBackchannelAuthenticationGrantResponse(as, client, response, options) {\n return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nexport async function dynamicClientRegistrationRequest(as, metadata, options) {\n assertAs(as);\n const url = resolveEndpoint(as, 'registration_endpoint', metadata.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n headers.set('content-type', 'application/json');\n const method = 'POST';\n if (options?.DPoP) {\n assertDPoP(options.DPoP);\n await options.DPoP.addProof(url, headers, method, options.initialAccessToken);\n }\n if (options?.initialAccessToken) {\n headers.set('authorization', `${headers.has('dpop') ? 'DPoP' : 'Bearer'} ${options.initialAccessToken}`);\n }\n const response = await (options?.[customFetch] || fetch)(url.href, {\n body: JSON.stringify(metadata),\n headers: Object.fromEntries(headers.entries()),\n method,\n redirect: 'manual',\n signal: signal(url, options?.signal),\n });\n options?.DPoP?.cacheNonce(response, url);\n return response;\n}\nexport async function processDynamicClientRegistrationResponse(response) {\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 201, 'Dynamic Client Registration Endpoint');\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.client_id, '\"response\" body \"client_id\" property', INVALID_RESPONSE, {\n body: json,\n });\n if (json.client_secret !== undefined) {\n assertString(json.client_secret, '\"response\" body \"client_secret\" property', INVALID_RESPONSE, {\n body: json,\n });\n }\n if (json.client_secret) {\n assertNumber(json.client_secret_expires_at, true, '\"response\" body \"client_secret_expires_at\" property', INVALID_RESPONSE, {\n body: json,\n });\n }\n return json;\n}\nexport async function resourceDiscoveryRequest(resourceIdentifier, options) {\n return performDiscovery(resourceIdentifier, 'resourceIdentifier', (url) => {\n prependWellKnown(url, '.well-known/oauth-protected-resource', true);\n return url;\n }, options);\n}\nexport async function processResourceDiscoveryResponse(expectedResourceIdentifier, response) {\n const expected = expectedResourceIdentifier;\n if (!(expected instanceof URL) && expected !== _nodiscoverycheck) {\n throw CodedTypeError('\"expectedResourceIdentifier\" must be an instance of URL', ERR_INVALID_ARG_TYPE);\n }\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n if (response.status !== 200) {\n throw OPE('\"response\" is not a conform Resource Server Metadata response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);\n }\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.resource, '\"response\" body \"resource\" property', INVALID_RESPONSE, {\n body: json,\n });\n if (expected !== _nodiscoverycheck && new URL(json.resource).href !== expected.href) {\n throw OPE('\"response\" body \"resource\" property does not match the expected value', JSON_ATTRIBUTE_COMPARISON, { expected: expected.href, body: json, attribute: 'resource' });\n }\n return json;\n}\nasync function getResponseJsonBody(response, check = assertApplicationJson) {\n let json;\n try {\n json = await response.json();\n }\n catch (cause) {\n check(response);\n throw OPE('failed to parse \"response\" body as JSON', PARSE_ERROR, cause);\n }\n if (!isJsonObject(json)) {\n throw OPE('\"response\" body must be a top level object', INVALID_RESPONSE, { body: json });\n }\n return json;\n}\nexport const _nopkce = nopkce;\nexport const _nodiscoverycheck = Symbol();\nexport const _expectedIssuer = Symbol();\n//# sourceMappingURL=index.js.map","import * as oauth from 'oauth4webapi';\nimport { compactDecrypt } from 'jose/jwe/compact/decrypt';\nimport { JOSEError } from 'jose/errors';\nlet headers;\nlet USER_AGENT;\nif (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {\n const NAME = 'openid-client';\n const VERSION = 'v6.8.8';\n USER_AGENT = `${NAME}/${VERSION}`;\n headers = { 'user-agent': USER_AGENT };\n}\nconst int = (config) => {\n return props.get(config);\n};\nlet props;\nexport { AuthorizationResponseError, ResponseBodyError, WWWAuthenticateChallengeError, } from 'oauth4webapi';\nexport function ClientSecretPost(clientSecret) {\n if (clientSecret !== undefined) {\n return oauth.ClientSecretPost(clientSecret);\n }\n const cache = new WeakMap();\n return (as, client, body, headers) => {\n let auth;\n if (!(auth = cache.get(client))) {\n assertString(client.client_secret, '\"metadata.client_secret\"');\n auth = oauth.ClientSecretPost(client.client_secret);\n cache.set(client, auth);\n }\n return auth(as, client, body, headers);\n };\n}\nfunction assertString(input, it) {\n if (typeof input !== 'string') {\n throw CodedTypeError(`${it} must be a string`, ERR_INVALID_ARG_TYPE);\n }\n if (input.length === 0) {\n throw CodedTypeError(`${it} must not be empty`, ERR_INVALID_ARG_VALUE);\n }\n}\nexport function ClientSecretBasic(clientSecret) {\n if (clientSecret !== undefined) {\n return oauth.ClientSecretBasic(clientSecret);\n }\n const cache = new WeakMap();\n return (as, client, body, headers) => {\n let auth;\n if (!(auth = cache.get(client))) {\n assertString(client.client_secret, '\"metadata.client_secret\"');\n auth = oauth.ClientSecretBasic(client.client_secret);\n cache.set(client, auth);\n }\n return auth(as, client, body, headers);\n };\n}\nexport function ClientSecretJwt(clientSecret, options) {\n if (clientSecret !== undefined) {\n return oauth.ClientSecretJwt(clientSecret, options);\n }\n const cache = new WeakMap();\n return (as, client, body, headers) => {\n let auth;\n if (!(auth = cache.get(client))) {\n assertString(client.client_secret, '\"metadata.client_secret\"');\n auth = oauth.ClientSecretJwt(client.client_secret, options);\n cache.set(client, auth);\n }\n return auth(as, client, body, headers);\n };\n}\nexport function None() {\n return oauth.None();\n}\nexport function PrivateKeyJwt(clientPrivateKey, options) {\n return oauth.PrivateKeyJwt(clientPrivateKey, options);\n}\nexport function TlsClientAuth() {\n return oauth.TlsClientAuth();\n}\nexport const skipStateCheck = oauth.skipStateCheck;\nexport const skipSubjectCheck = oauth.skipSubjectCheck;\nexport const customFetch = oauth.customFetch;\nexport const modifyAssertion = oauth.modifyAssertion;\nexport const clockSkew = oauth.clockSkew;\nexport const clockTolerance = oauth.clockTolerance;\nconst ERR_INVALID_ARG_VALUE = 'ERR_INVALID_ARG_VALUE';\nconst ERR_INVALID_ARG_TYPE = 'ERR_INVALID_ARG_TYPE';\nfunction CodedTypeError(message, code, cause) {\n const err = new TypeError(message, { cause });\n Object.assign(err, { code });\n return err;\n}\nexport function calculatePKCECodeChallenge(codeVerifier) {\n return oauth.calculatePKCECodeChallenge(codeVerifier);\n}\nexport function randomPKCECodeVerifier() {\n return oauth.generateRandomCodeVerifier();\n}\nexport function randomNonce() {\n return oauth.generateRandomNonce();\n}\nexport function randomState() {\n return oauth.generateRandomState();\n}\nexport class ClientError extends Error {\n code;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n this.code = options?.code;\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nconst decoder = new TextDecoder();\nfunction e(msg, cause, code) {\n return new ClientError(msg, { cause, code });\n}\nfunction errorHandler(err) {\n if (err instanceof TypeError ||\n err instanceof ClientError ||\n err instanceof oauth.ResponseBodyError ||\n err instanceof oauth.AuthorizationResponseError ||\n err instanceof oauth.WWWAuthenticateChallengeError) {\n throw err;\n }\n if (err instanceof oauth.OperationProcessingError) {\n switch (err.code) {\n case oauth.HTTP_REQUEST_FORBIDDEN:\n throw e('only requests to HTTPS are allowed', err, err.code);\n case oauth.REQUEST_PROTOCOL_FORBIDDEN:\n throw e('only requests to HTTP or HTTPS are allowed', err, err.code);\n case oauth.RESPONSE_IS_NOT_CONFORM:\n throw e('unexpected HTTP response status code', err.cause, err.code);\n case oauth.RESPONSE_IS_NOT_JSON:\n throw e('unexpected response content-type', err.cause, err.code);\n case oauth.PARSE_ERROR:\n throw e('parsing error occured', err, err.code);\n case oauth.INVALID_RESPONSE:\n throw e('invalid response encountered', err, err.code);\n case oauth.JWT_CLAIM_COMPARISON:\n throw e('unexpected JWT claim value encountered', err, err.code);\n case oauth.JSON_ATTRIBUTE_COMPARISON:\n throw e('unexpected JSON attribute value encountered', err, err.code);\n case oauth.JWT_TIMESTAMP_CHECK:\n throw e('JWT timestamp claim value failed validation', err, err.code);\n default:\n throw e(err.message, err, err.code);\n }\n }\n if (err instanceof oauth.UnsupportedOperationError) {\n throw e('unsupported operation', err, err.code);\n }\n if (err instanceof DOMException) {\n switch (err.name) {\n case 'OperationError':\n throw e('runtime operation error', err, oauth.UNSUPPORTED_OPERATION);\n case 'NotSupportedError':\n throw e('runtime unsupported operation', err, oauth.UNSUPPORTED_OPERATION);\n case 'TimeoutError':\n throw e('operation timed out', err, 'OAUTH_TIMEOUT');\n case 'AbortError':\n throw e('operation aborted', err, 'OAUTH_ABORT');\n }\n }\n throw new ClientError('something went wrong', { cause: err });\n}\nexport function randomDPoPKeyPair(alg, options) {\n return oauth\n .generateKeyPair(alg ?? 'ES256', {\n extractable: options?.extractable,\n })\n .catch(errorHandler);\n}\nfunction handleEntraId(server, as, options) {\n if (server.origin === 'https://login.microsoftonline.com' &&\n (!options?.algorithm || options.algorithm === 'oidc')) {\n as[kEntraId] = true;\n return true;\n }\n return false;\n}\nfunction handleB2Clogin(server, options) {\n if (server.hostname.endsWith('.b2clogin.com') &&\n (!options?.algorithm || options.algorithm === 'oidc')) {\n return true;\n }\n return false;\n}\nexport async function dynamicClientRegistration(server, metadata, clientAuthentication, options) {\n let as;\n if (options?.flag === retry) {\n as = options.as;\n }\n else {\n as = await performDiscovery(server, options);\n }\n const clockSkew = metadata[oauth.clockSkew] ?? 0;\n const clockTolerance = metadata[oauth.clockTolerance] ?? 30;\n metadata = structuredClone(metadata);\n metadata[oauth.clockSkew] = clockSkew;\n metadata[oauth.clockTolerance] = clockTolerance;\n const timeout = options?.timeout ?? 30;\n const signal = AbortSignal.timeout(timeout * 1000);\n let registered;\n try {\n registered = await oauth\n .dynamicClientRegistrationRequest(as, metadata, {\n initialAccessToken: options?.initialAccessToken,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n [oauth.customFetch]: options?.[customFetch],\n [oauth.allowInsecureRequests]: options?.execute?.includes(allowInsecureRequests),\n signal,\n })\n .then(oauth.processDynamicClientRegistrationResponse);\n }\n catch (err) {\n if (retryable(err, options)) {\n return dynamicClientRegistration(server, metadata, clientAuthentication, {\n ...options,\n flag: retry,\n as,\n });\n }\n errorHandler(err);\n }\n registered[oauth.clockSkew] = clockSkew;\n registered[oauth.clockTolerance] = clockTolerance;\n const instance = new Configuration(as, registered.client_id, registered, clientAuthentication);\n let internals = int(instance);\n if (options?.[customFetch]) {\n internals.fetch = options[customFetch];\n }\n if (options?.timeout !== undefined) {\n internals.timeout = options.timeout;\n }\n if (options?.execute) {\n for (const extension of options.execute) {\n extension(instance);\n }\n }\n return instance;\n}\nexport async function discovery(server, clientId, metadata, clientAuthentication, options) {\n const as = await performDiscovery(server, options);\n const instance = new Configuration(as, clientId, metadata, clientAuthentication);\n let internals = int(instance);\n if (options?.[customFetch]) {\n internals.fetch = options[customFetch];\n }\n if (options?.timeout !== undefined) {\n internals.timeout = options.timeout;\n }\n if (options?.execute) {\n for (const extension of options.execute) {\n extension(instance);\n }\n }\n return instance;\n}\nasync function performDiscovery(server, options) {\n if (!(server instanceof URL)) {\n throw CodedTypeError('\"server\" must be an instance of URL', ERR_INVALID_ARG_TYPE);\n }\n const resolve = !server.href.includes('/.well-known/');\n const timeout = options?.timeout ?? 30;\n const signal = AbortSignal.timeout(timeout * 1000);\n const as = await (resolve\n ? oauth.discoveryRequest(server, {\n algorithm: options?.algorithm,\n [oauth.customFetch]: options?.[customFetch],\n [oauth.allowInsecureRequests]: options?.execute?.includes(allowInsecureRequests),\n signal,\n headers: new Headers(headers),\n })\n : (options?.[customFetch] || fetch)((() => {\n oauth.checkProtocol(server, options?.execute?.includes(allowInsecureRequests) ? false : true);\n return server.href;\n })(), {\n headers: Object.fromEntries(new Headers({ accept: 'application/json', ...headers }).entries()),\n body: undefined,\n method: 'GET',\n redirect: 'manual',\n signal,\n }))\n .then((response) => oauth.processDiscoveryResponse(oauth._nodiscoverycheck, response))\n .catch(errorHandler);\n if (resolve && new URL(as.issuer).href !== server.href) {\n handleEntraId(server, as, options) ||\n handleB2Clogin(server, options) ||\n (() => {\n throw new ClientError('discovered metadata issuer does not match the expected issuer', {\n code: oauth.JSON_ATTRIBUTE_COMPARISON,\n cause: {\n expected: server.href,\n body: as,\n attribute: 'issuer',\n },\n });\n })();\n }\n return as;\n}\nfunction isRsaOaep(input) {\n return input.name === 'RSA-OAEP';\n}\nfunction isEcdh(input) {\n return input.name === 'ECDH';\n}\nconst ecdhEs = 'ECDH-ES';\nconst ecdhEsA128Kw = 'ECDH-ES+A128KW';\nconst ecdhEsA192Kw = 'ECDH-ES+A192KW';\nconst ecdhEsA256Kw = 'ECDH-ES+A256KW';\nfunction checkEcdhAlg(algs, alg, pk) {\n switch (alg) {\n case undefined:\n algs.add(ecdhEs);\n algs.add(ecdhEsA128Kw);\n algs.add(ecdhEsA192Kw);\n algs.add(ecdhEsA256Kw);\n break;\n case ecdhEs:\n case ecdhEsA128Kw:\n case ecdhEsA192Kw:\n case ecdhEsA256Kw:\n algs.add(alg);\n break;\n default:\n throw CodedTypeError('invalid key alg', ERR_INVALID_ARG_VALUE, { pk });\n }\n}\nexport function enableDecryptingResponses(config, contentEncryptionAlgorithms = [\n 'A128GCM',\n 'A192GCM',\n 'A256GCM',\n 'A128CBC-HS256',\n 'A192CBC-HS384',\n 'A256CBC-HS512',\n], ...keys) {\n if (int(config).decrypt !== undefined) {\n throw new TypeError('enableDecryptingResponses can only be called on a given Configuration instance once');\n }\n if (keys.length === 0) {\n throw CodedTypeError('no keys were provided', ERR_INVALID_ARG_VALUE);\n }\n const algs = new Set();\n const normalized = [];\n for (const pk of keys) {\n let key;\n if ('key' in pk) {\n key = { key: pk.key };\n if (typeof pk.alg === 'string')\n key.alg = pk.alg;\n if (typeof pk.kid === 'string')\n key.kid = pk.kid;\n }\n else {\n key = { key: pk };\n }\n if (key.key.type !== 'private') {\n throw CodedTypeError('only private keys must be provided', ERR_INVALID_ARG_VALUE);\n }\n if (isRsaOaep(key.key.algorithm)) {\n switch (key.key.algorithm.hash.name) {\n case 'SHA-1':\n case 'SHA-256':\n case 'SHA-384':\n case 'SHA-512': {\n let alg = 'RSA-OAEP';\n let sha;\n if ((sha = parseInt(key.key.algorithm.hash.name.slice(-3), 10))) {\n alg = `${alg}-${sha}`;\n }\n key.alg ||= alg;\n if (alg !== key.alg)\n throw CodedTypeError('invalid key alg', ERR_INVALID_ARG_VALUE, {\n pk,\n });\n algs.add(key.alg);\n break;\n }\n default:\n throw CodedTypeError('only SHA-512, SHA-384, SHA-256, and SHA-1 RSA-OAEP keys are supported', ERR_INVALID_ARG_VALUE);\n }\n }\n else if (isEcdh(key.key.algorithm)) {\n if (key.key.algorithm.namedCurve !== 'P-256') {\n throw CodedTypeError('Only P-256 ECDH keys are supported', ERR_INVALID_ARG_VALUE);\n }\n checkEcdhAlg(algs, key.alg, pk);\n }\n else if (key.key.algorithm.name === 'X25519') {\n checkEcdhAlg(algs, key.alg, pk);\n }\n else {\n throw CodedTypeError('only RSA-OAEP, ECDH, or X25519 keys are supported', ERR_INVALID_ARG_VALUE);\n }\n normalized.push(key);\n }\n int(config).decrypt = async (jwe) => decrypt(normalized, jwe, contentEncryptionAlgorithms, [...algs]).catch(errorHandler);\n}\nfunction checkCryptoKey(key, alg, epk) {\n if (alg.startsWith('RSA-OAEP')) {\n return key.algorithm.name === 'RSA-OAEP';\n }\n if (alg.startsWith('ECDH-ES')) {\n if (key.algorithm.name !== 'ECDH' && key.algorithm.name !== 'X25519') {\n return false;\n }\n if (key.algorithm.name === 'ECDH') {\n return epk?.crv === key.algorithm.namedCurve;\n }\n if (key.algorithm.name === 'X25519') {\n return epk?.crv === 'X25519';\n }\n }\n return false;\n}\nfunction selectCryptoKeyForDecryption(keys, alg, kid, epk) {\n const { 0: key, length } = keys.filter((key) => {\n if (kid !== undefined && kid !== key.kid) {\n return false;\n }\n if (key.alg && alg !== key.alg) {\n return false;\n }\n return checkCryptoKey(key.key, alg, epk);\n });\n if (!key) {\n throw e('no applicable decryption key selected', undefined, 'OAUTH_DECRYPTION_FAILED');\n }\n if (length !== 1) {\n throw e('multiple applicable decryption keys selected', undefined, 'OAUTH_DECRYPTION_FAILED');\n }\n return key.key;\n}\nasync function decrypt(keys, jwe, contentEncryptionAlgorithms, keyManagementAlgorithms) {\n return decoder.decode((await compactDecrypt(jwe, (header) => {\n const { kid, alg, epk } = header;\n return selectCryptoKeyForDecryption(keys, alg, kid, epk);\n }, { keyManagementAlgorithms, contentEncryptionAlgorithms }).catch((err) => {\n if (err instanceof JOSEError) {\n throw e('decryption failed', err, 'OAUTH_DECRYPTION_FAILED');\n }\n errorHandler(err);\n })).plaintext);\n}\nfunction getServerHelpers(metadata) {\n return {\n supportsPKCE: {\n __proto__: null,\n value(method = 'S256') {\n return (metadata.code_challenge_methods_supported?.includes(method) === true);\n },\n },\n };\n}\nfunction addServerHelpers(metadata) {\n Object.defineProperties(metadata, getServerHelpers(metadata));\n}\nconst kEntraId = Symbol();\nexport class Configuration {\n constructor(server, clientId, metadata, clientAuthentication) {\n if (typeof clientId !== 'string' || !clientId.length) {\n throw CodedTypeError('\"clientId\" must be a non-empty string', ERR_INVALID_ARG_TYPE);\n }\n if (typeof metadata === 'string') {\n metadata = { client_secret: metadata };\n }\n if (metadata?.client_id !== undefined && clientId !== metadata.client_id) {\n throw CodedTypeError('\"clientId\" and \"metadata.client_id\" must be the same', ERR_INVALID_ARG_VALUE);\n }\n const client = {\n ...structuredClone(metadata),\n client_id: clientId,\n };\n client[oauth.clockSkew] = metadata?.[oauth.clockSkew] ?? 0;\n client[oauth.clockTolerance] = metadata?.[oauth.clockTolerance] ?? 30;\n let auth;\n if (clientAuthentication) {\n auth = clientAuthentication;\n }\n else {\n if (typeof client.client_secret === 'string' &&\n client.client_secret.length) {\n auth = ClientSecretPost(client.client_secret);\n }\n else {\n auth = None();\n }\n }\n let c = Object.freeze(client);\n const clone = structuredClone(server);\n if (kEntraId in server) {\n clone[oauth._expectedIssuer] = ({ claims: { tid } }) => server.issuer.replace('{tenantid}', tid);\n }\n let as = Object.freeze(clone);\n props ||= new WeakMap();\n props.set(this, {\n __proto__: null,\n as,\n c,\n auth,\n tlsOnly: true,\n timeout: 30,\n jwksCache: {},\n });\n }\n serverMetadata() {\n const metadata = structuredClone(int(this).as);\n addServerHelpers(metadata);\n return metadata;\n }\n clientMetadata() {\n const metadata = structuredClone(int(this).c);\n return metadata;\n }\n get timeout() {\n return int(this).timeout;\n }\n set timeout(value) {\n int(this).timeout = value;\n }\n get [customFetch]() {\n return int(this).fetch;\n }\n set [customFetch](value) {\n int(this).fetch = value;\n }\n}\nObject.freeze(Configuration.prototype);\nfunction getHelpers(response) {\n let exp = undefined;\n if (response.expires_in !== undefined) {\n exp = Date.now() + response.expires_in * 1000;\n }\n return {\n expiresIn: {\n __proto__: null,\n value() {\n if (exp) {\n const now = Date.now();\n if (exp > now) {\n return Math.floor((exp - now) / 1000);\n }\n return 0;\n }\n return undefined;\n },\n },\n claims: {\n __proto__: null,\n value() {\n return oauth.getValidatedIdTokenClaims(response);\n },\n },\n };\n}\nfunction addHelpers(response) {\n Object.defineProperties(response, getHelpers(response));\n}\nexport function getDPoPHandle(config, keyPair, options) {\n checkConfig(config);\n return oauth.DPoP(int(config).c, keyPair, options);\n}\nasync function handleRetryAfter(response, currentInterval, signal, throwIfInvalid = false) {\n const retryAfter = response.headers.get('retry-after')?.trim();\n if (retryAfter === undefined)\n return;\n let delaySeconds;\n if (/^\\d+$/.test(retryAfter)) {\n delaySeconds = parseInt(retryAfter, 10);\n }\n else {\n const retryDate = new Date(retryAfter);\n if (Number.isFinite(retryDate.getTime())) {\n const now = new Date();\n const delayMs = retryDate.getTime() - now.getTime();\n if (delayMs > 0) {\n delaySeconds = Math.ceil(delayMs / 1000);\n }\n }\n }\n if (throwIfInvalid && !Number.isFinite(delaySeconds)) {\n throw new oauth.OperationProcessingError('invalid Retry-After header value', { cause: response });\n }\n if (delaySeconds > currentInterval) {\n await wait(delaySeconds - currentInterval, signal);\n }\n}\nfunction wait(duration, signal) {\n return new Promise((resolve, reject) => {\n const waitStep = (remaining) => {\n try {\n signal.throwIfAborted();\n }\n catch (err) {\n reject(err);\n return;\n }\n if (remaining <= 0) {\n resolve();\n return;\n }\n const currentWait = Math.min(remaining, 5);\n setTimeout(() => waitStep(remaining - currentWait), currentWait * 1000);\n };\n waitStep(duration);\n });\n}\nfunction pollRequestSignal(pollingSignal, timeout) {\n const timeoutSignal = signal(timeout);\n if (!timeoutSignal) {\n return {\n signal: pollingSignal,\n cleanup() { },\n };\n }\n const controller = new AbortController();\n const abort = (event) => {\n const source = event.target;\n controller.abort(source.reason);\n };\n if (pollingSignal.aborted) {\n controller.abort(pollingSignal.reason);\n }\n else if (timeoutSignal.aborted) {\n controller.abort(timeoutSignal.reason);\n }\n else {\n pollingSignal.addEventListener('abort', abort, { once: true });\n timeoutSignal.addEventListener('abort', abort, { once: true });\n }\n return {\n signal: controller.signal,\n cleanup() {\n pollingSignal.removeEventListener('abort', abort);\n timeoutSignal.removeEventListener('abort', abort);\n },\n };\n}\nasync function pollGrant(config, authorizationResponse, grantCode, request, processResponse, parameters, options) {\n const requestParameters = new URLSearchParams(parameters);\n let interval = authorizationResponse.interval ?? 5;\n const pollingSignal = options?.signal ??\n AbortSignal.timeout(authorizationResponse.expires_in * 1000);\n for (;;) {\n try {\n await wait(interval, pollingSignal);\n }\n catch (error) {\n errorHandler(error);\n }\n const { as, c, auth, fetch, tlsOnly, nonRepudiation, timeout, decrypt } = int(config);\n const requestSignal = pollRequestSignal(pollingSignal, timeout);\n try {\n const response = await request(as, c, auth, grantCode, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n additionalParameters: requestParameters,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: requestSignal.signal,\n }).catch(errorHandler);\n if (response.status === 503 && response.headers.has('retry-after')) {\n await response.body?.cancel();\n await handleRetryAfter(response, interval, pollingSignal, true);\n options = { ...options, flag: undefined };\n continue;\n }\n let result;\n try {\n result = await processResponse(as, c, response, {\n [oauth.jweDecrypt]: decrypt,\n });\n }\n catch (error) {\n if (retryable(error, options)) {\n options = { ...options, flag: retry };\n continue;\n }\n if (error instanceof oauth.ResponseBodyError &&\n (error.error === 'slow_down' ||\n error.error === 'authorization_pending')) {\n if (error.error === 'slow_down')\n interval += 5;\n await handleRetryAfter(error.response, interval, pollingSignal);\n options = { ...options, flag: undefined };\n continue;\n }\n errorHandler(error);\n }\n result.id_token && (await nonRepudiation?.(response));\n addHelpers(result);\n return result;\n }\n finally {\n requestSignal.cleanup();\n }\n }\n}\nexport async function pollDeviceAuthorizationGrant(config, deviceAuthorizationResponse, parameters, options) {\n checkConfig(config);\n return pollGrant(config, deviceAuthorizationResponse, deviceAuthorizationResponse.device_code, oauth.deviceCodeGrantRequest, oauth.processDeviceCodeResponse, parameters, options);\n}\nexport async function initiateDeviceAuthorization(config, parameters) {\n checkConfig(config);\n const { as, c, auth, fetch, tlsOnly, timeout } = int(config);\n return oauth\n .deviceAuthorizationRequest(as, c, auth, parameters, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .then((response) => oauth.processDeviceAuthorizationResponse(as, c, response))\n .catch(errorHandler);\n}\nexport async function initiateBackchannelAuthentication(config, parameters) {\n checkConfig(config);\n const { as, c, auth, fetch, tlsOnly, timeout } = int(config);\n return oauth\n .backchannelAuthenticationRequest(as, c, auth, parameters, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .then((response) => oauth.processBackchannelAuthenticationResponse(as, c, response))\n .catch(errorHandler);\n}\nexport async function pollBackchannelAuthenticationGrant(config, backchannelAuthenticationResponse, parameters, options) {\n checkConfig(config);\n return pollGrant(config, backchannelAuthenticationResponse, backchannelAuthenticationResponse.auth_req_id, oauth.backchannelAuthenticationGrantRequest, oauth.processBackchannelAuthenticationGrantResponse, parameters, options);\n}\nexport function allowInsecureRequests(config) {\n int(config).tlsOnly = false;\n}\nexport function setJwksCache(config, jwksCache) {\n int(config).jwksCache = structuredClone(jwksCache);\n}\nexport function getJwksCache(config) {\n const cache = int(config).jwksCache;\n if (cache.uat) {\n return cache;\n }\n return undefined;\n}\nexport function enableNonRepudiationChecks(config) {\n checkConfig(config);\n int(config).nonRepudiation = (response) => {\n const { as, fetch, tlsOnly, timeout, jwksCache } = int(config);\n return oauth\n .validateApplicationLevelSignature(as, response, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n headers: new Headers(headers),\n signal: signal(timeout),\n [oauth.jwksCache]: jwksCache,\n })\n .catch(errorHandler);\n };\n}\nexport function useJwtResponseMode(config) {\n checkConfig(config);\n const { hybrid, implicit } = int(config);\n if (hybrid || implicit) {\n throw e('JARM cannot be combined with a hybrid or implicit response types', undefined, oauth.UNSUPPORTED_OPERATION);\n }\n int(config).jarm = (authorizationResponse, expectedState) => validateJARMResponse(config, authorizationResponse, expectedState);\n}\nexport function enableDetachedSignatureResponseChecks(config) {\n if (!int(config).hybrid) {\n throw e('\"code id_token\" response type must be configured to be used first', undefined, oauth.UNSUPPORTED_OPERATION);\n }\n int(config).hybrid = (authorizationResponse, expectedNonce, expectedState, maxAge) => validateCodeIdTokenResponse(config, authorizationResponse, expectedNonce, expectedState, maxAge, true);\n}\nexport async function implicitAuthentication(config, currentUrl, expectedNonce, checks) {\n checkConfig(config);\n if (!(currentUrl instanceof URL) &&\n !webInstanceOf(currentUrl, 'Request')) {\n throw CodedTypeError('\"currentUrl\" must be an instance of URL, or Request', ERR_INVALID_ARG_TYPE);\n }\n if (typeof expectedNonce !== 'string') {\n throw CodedTypeError('\"expectedNonce\" must be a string', ERR_INVALID_ARG_TYPE);\n }\n const { as, c, fetch, tlsOnly, timeout, decrypt, implicit, jwksCache } = int(config);\n if (!implicit) {\n throw new TypeError('implicitAuthentication() cannot be used by clients using flows other than response_type=id_token');\n }\n let params;\n if (!(currentUrl instanceof URL)) {\n const request = currentUrl;\n switch (request.method) {\n case 'GET':\n params = new URLSearchParams(new URL(request.url).hash.slice(1));\n break;\n case 'POST':\n params = new URLSearchParams(await oauth.formPostResponse(request));\n break;\n default:\n throw CodedTypeError('unexpected Request HTTP method', ERR_INVALID_ARG_VALUE);\n }\n }\n else {\n params = new URLSearchParams(currentUrl.hash.slice(1));\n }\n try {\n {\n const decoy = new URLSearchParams(params);\n decoy.delete('id_token');\n oauth.validateAuthResponse({\n ...as,\n authorization_response_iss_parameter_supported: undefined,\n }, c, decoy, checks?.expectedState);\n }\n {\n const decoy = new Response(JSON.stringify({\n access_token: 'decoy',\n token_type: 'bearer',\n id_token: params.get('id_token'),\n }), {\n headers: new Headers({ 'content-type': 'application/json' }),\n });\n const ref = await oauth.processAuthorizationCodeResponse(as, c, decoy, {\n expectedNonce,\n maxAge: checks?.maxAge,\n [oauth.jweDecrypt]: decrypt,\n });\n await oauth.validateApplicationLevelSignature(as, decoy, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n headers: new Headers(headers),\n signal: signal(timeout),\n [oauth.jwksCache]: jwksCache,\n });\n return oauth.getValidatedIdTokenClaims(ref);\n }\n }\n catch (err) {\n errorHandler(err);\n }\n}\nexport function useCodeIdTokenResponseType(config) {\n checkConfig(config);\n const { jarm, implicit } = int(config);\n if (jarm || implicit) {\n throw e('\"code id_token\" response type cannot be combined with JARM or implicit response type', undefined, oauth.UNSUPPORTED_OPERATION);\n }\n int(config).hybrid = (authorizationResponse, expectedNonce, expectedState, maxAge) => validateCodeIdTokenResponse(config, authorizationResponse, expectedNonce, expectedState, maxAge, false);\n}\nexport function useIdTokenResponseType(config) {\n checkConfig(config);\n const { jarm, hybrid } = int(config);\n if (jarm || hybrid) {\n throw e('\"id_token\" response type cannot be combined with JARM or hybrid response type', undefined, oauth.UNSUPPORTED_OPERATION);\n }\n int(config).implicit = true;\n}\nfunction stripParams(url) {\n url = new URL(url);\n url.search = '';\n url.hash = '';\n return url.href;\n}\nfunction webInstanceOf(input, toStringTag) {\n try {\n return Object.getPrototypeOf(input)[Symbol.toStringTag] === toStringTag;\n }\n catch {\n return false;\n }\n}\nexport async function authorizationCodeGrant(config, currentUrl, checks, tokenEndpointParameters, options) {\n checkConfig(config);\n if (options?.flag !== retry &&\n !(currentUrl instanceof URL) &&\n !webInstanceOf(currentUrl, 'Request')) {\n throw CodedTypeError('\"currentUrl\" must be an instance of URL, or Request', ERR_INVALID_ARG_TYPE);\n }\n let authResponse;\n let redirectUri;\n const { as, c, auth, fetch, tlsOnly, jarm, hybrid, nonRepudiation, timeout, decrypt, implicit } = int(config);\n if (options?.flag === retry) {\n authResponse = options.authResponse;\n redirectUri = options.redirectUri;\n }\n else {\n if (!(currentUrl instanceof URL)) {\n const request = currentUrl;\n currentUrl = new URL(currentUrl.url);\n switch (request.method) {\n case 'GET':\n break;\n case 'POST':\n const params = new URLSearchParams(await oauth.formPostResponse(request));\n if (hybrid) {\n currentUrl.hash = params.toString();\n }\n else {\n for (const [k, v] of params.entries()) {\n currentUrl.searchParams.append(k, v);\n }\n }\n break;\n default:\n throw CodedTypeError('unexpected Request HTTP method', ERR_INVALID_ARG_VALUE);\n }\n }\n redirectUri = stripParams(currentUrl);\n switch (true) {\n case !!jarm:\n authResponse = await jarm(currentUrl, checks?.expectedState);\n break;\n case !!hybrid:\n authResponse = await hybrid(currentUrl, checks?.expectedNonce, checks?.expectedState, checks?.maxAge);\n break;\n case !!implicit:\n throw new TypeError('authorizationCodeGrant() cannot be used by response_type=id_token clients');\n default:\n try {\n authResponse = oauth.validateAuthResponse(as, c, currentUrl.searchParams, checks?.expectedState);\n }\n catch (err) {\n errorHandler(err);\n }\n }\n }\n const response = await oauth\n .authorizationCodeGrantRequest(as, c, auth, authResponse, redirectUri, checks?.pkceCodeVerifier || oauth.nopkce, {\n additionalParameters: tokenEndpointParameters,\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .catch(errorHandler);\n if (typeof checks?.expectedNonce === 'string' ||\n typeof checks?.maxAge === 'number') {\n checks.idTokenExpected = true;\n }\n const p = oauth.processAuthorizationCodeResponse(as, c, response, {\n expectedNonce: checks?.expectedNonce,\n maxAge: checks?.maxAge,\n requireIdToken: checks?.idTokenExpected,\n [oauth.jweDecrypt]: decrypt,\n });\n let result;\n try {\n result = await p;\n }\n catch (err) {\n if (retryable(err, options)) {\n return authorizationCodeGrant(config, undefined, checks, tokenEndpointParameters, {\n ...options,\n flag: retry,\n authResponse: authResponse,\n redirectUri: redirectUri,\n });\n }\n errorHandler(err);\n }\n result.id_token && (await nonRepudiation?.(response));\n addHelpers(result);\n return result;\n}\nasync function validateJARMResponse(config, authorizationResponse, expectedState) {\n const { as, c, fetch, tlsOnly, timeout, decrypt, jwksCache } = int(config);\n return oauth\n .validateJwtAuthResponse(as, c, authorizationResponse, expectedState, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n headers: new Headers(headers),\n signal: signal(timeout),\n [oauth.jweDecrypt]: decrypt,\n [oauth.jwksCache]: jwksCache,\n })\n .catch(errorHandler);\n}\nasync function validateCodeIdTokenResponse(config, authorizationResponse, expectedNonce, expectedState, maxAge, fapi) {\n if (typeof expectedNonce !== 'string') {\n throw CodedTypeError('\"expectedNonce\" must be a string', ERR_INVALID_ARG_TYPE);\n }\n if (expectedState !== undefined && typeof expectedState !== 'string') {\n throw CodedTypeError('\"expectedState\" must be a string', ERR_INVALID_ARG_TYPE);\n }\n const { as, c, fetch, tlsOnly, timeout, decrypt, jwksCache } = int(config);\n return (fapi\n ? oauth.validateDetachedSignatureResponse\n : oauth.validateCodeIdTokenResponse)(as, c, authorizationResponse, expectedNonce, expectedState, maxAge, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n headers: new Headers(headers),\n signal: signal(timeout),\n [oauth.jweDecrypt]: decrypt,\n [oauth.jwksCache]: jwksCache,\n }).catch(errorHandler);\n}\nexport async function refreshTokenGrant(config, refreshToken, parameters, options) {\n checkConfig(config);\n parameters = new URLSearchParams(parameters);\n const { as, c, auth, fetch, tlsOnly, nonRepudiation, timeout, decrypt } = int(config);\n const response = await oauth\n .refreshTokenGrantRequest(as, c, auth, refreshToken, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n additionalParameters: parameters,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .catch(errorHandler);\n const p = oauth.processRefreshTokenResponse(as, c, response, {\n [oauth.jweDecrypt]: decrypt,\n });\n let result;\n try {\n result = await p;\n }\n catch (err) {\n if (retryable(err, options)) {\n return refreshTokenGrant(config, refreshToken, parameters, {\n ...options,\n flag: retry,\n });\n }\n errorHandler(err);\n }\n result.id_token && (await nonRepudiation?.(response));\n addHelpers(result);\n return result;\n}\nexport async function clientCredentialsGrant(config, parameters, options) {\n checkConfig(config);\n parameters = new URLSearchParams(parameters);\n const { as, c, auth, fetch, tlsOnly, timeout } = int(config);\n const response = await oauth\n .clientCredentialsGrantRequest(as, c, auth, parameters, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .catch(errorHandler);\n const p = oauth.processClientCredentialsResponse(as, c, response);\n let result;\n try {\n result = await p;\n }\n catch (err) {\n if (retryable(err, options)) {\n return clientCredentialsGrant(config, parameters, {\n ...options,\n flag: retry,\n });\n }\n errorHandler(err);\n }\n addHelpers(result);\n return result;\n}\nexport function buildAuthorizationUrl(config, parameters) {\n checkConfig(config);\n const { as, c, tlsOnly, hybrid, jarm, implicit } = int(config);\n const authorizationEndpoint = oauth.resolveEndpoint(as, 'authorization_endpoint', false, tlsOnly);\n parameters = new URLSearchParams(parameters);\n if (!parameters.has('client_id')) {\n parameters.set('client_id', c.client_id);\n }\n if (!parameters.has('request_uri') && !parameters.has('request')) {\n if (!parameters.has('response_type')) {\n parameters.set('response_type', hybrid ? 'code id_token' : implicit ? 'id_token' : 'code');\n }\n if (implicit && !parameters.has('nonce')) {\n throw CodedTypeError('response_type=id_token clients must provide a nonce parameter in their authorization request parameters', ERR_INVALID_ARG_VALUE);\n }\n if (jarm) {\n parameters.set('response_mode', 'jwt');\n }\n }\n for (const [k, v] of parameters.entries()) {\n authorizationEndpoint.searchParams.append(k, v);\n }\n return authorizationEndpoint;\n}\nexport async function buildAuthorizationUrlWithJAR(config, parameters, signingKey, options) {\n checkConfig(config);\n const authorizationEndpoint = buildAuthorizationUrl(config, parameters);\n parameters = authorizationEndpoint.searchParams;\n if (!signingKey) {\n throw CodedTypeError('\"signingKey\" must be provided', ERR_INVALID_ARG_VALUE);\n }\n const { as, c } = int(config);\n const request = await oauth\n .issueRequestObject(as, c, parameters, signingKey, options)\n .catch(errorHandler);\n return buildAuthorizationUrl(config, { request });\n}\nexport async function buildAuthorizationUrlWithPAR(config, parameters, options) {\n checkConfig(config);\n const authorizationEndpoint = buildAuthorizationUrl(config, parameters);\n const { as, c, auth, fetch, tlsOnly, timeout } = int(config);\n const response = await oauth\n .pushedAuthorizationRequest(as, c, auth, authorizationEndpoint.searchParams, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .catch(errorHandler);\n const p = oauth.processPushedAuthorizationResponse(as, c, response);\n let result;\n try {\n result = await p;\n }\n catch (err) {\n if (retryable(err, options)) {\n return buildAuthorizationUrlWithPAR(config, parameters, {\n ...options,\n flag: retry,\n });\n }\n errorHandler(err);\n }\n return buildAuthorizationUrl(config, { request_uri: result.request_uri });\n}\nexport function buildEndSessionUrl(config, parameters) {\n checkConfig(config);\n const { as, c, tlsOnly } = int(config);\n const endSessionEndpoint = oauth.resolveEndpoint(as, 'end_session_endpoint', false, tlsOnly);\n parameters = new URLSearchParams(parameters);\n if (!parameters.has('client_id')) {\n parameters.set('client_id', c.client_id);\n }\n for (const [k, v] of parameters.entries()) {\n endSessionEndpoint.searchParams.append(k, v);\n }\n return endSessionEndpoint;\n}\nfunction checkConfig(input) {\n if (!(input instanceof Configuration)) {\n throw CodedTypeError('\"config\" must be an instance of Configuration', ERR_INVALID_ARG_TYPE);\n }\n if (Object.getPrototypeOf(input) !== Configuration.prototype) {\n throw CodedTypeError('subclassing Configuration is not allowed', ERR_INVALID_ARG_VALUE);\n }\n}\nfunction signal(timeout) {\n return timeout ? AbortSignal.timeout(timeout * 1000) : undefined;\n}\nexport async function fetchUserInfo(config, accessToken, expectedSubject, options) {\n checkConfig(config);\n const { as, c, fetch, tlsOnly, nonRepudiation, timeout, decrypt } = int(config);\n const response = await oauth\n .userInfoRequest(as, c, accessToken, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .catch(errorHandler);\n let exec = oauth.processUserInfoResponse(as, c, expectedSubject, response, {\n [oauth.jweDecrypt]: decrypt,\n });\n let result;\n try {\n result = await exec;\n }\n catch (err) {\n if (retryable(err, options)) {\n return fetchUserInfo(config, accessToken, expectedSubject, {\n ...options,\n flag: retry,\n });\n }\n errorHandler(err);\n }\n oauth.getContentType(response) === 'application/jwt' &&\n (await nonRepudiation?.(response));\n return result;\n}\nfunction retryable(err, options) {\n if (options?.DPoP && options.flag !== retry) {\n return oauth.isDPoPNonceError(err);\n }\n return false;\n}\nexport async function tokenIntrospection(config, token, parameters) {\n checkConfig(config);\n const { as, c, auth, fetch, tlsOnly, nonRepudiation, timeout, decrypt } = int(config);\n const response = await oauth\n .introspectionRequest(as, c, auth, token, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n additionalParameters: new URLSearchParams(parameters),\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .catch(errorHandler);\n const result = await oauth\n .processIntrospectionResponse(as, c, response, {\n [oauth.jweDecrypt]: decrypt,\n })\n .catch(errorHandler);\n oauth.getContentType(response) === 'application/token-introspection+jwt' &&\n (await nonRepudiation?.(response));\n return result;\n}\nconst retry = Symbol();\nexport async function genericGrantRequest(config, grantType, parameters, options) {\n checkConfig(config);\n const { as, c, auth, fetch, tlsOnly, timeout, decrypt, nonRepudiation } = int(config);\n const response = await oauth\n .genericTokenEndpointRequest(as, c, auth, grantType, new URLSearchParams(parameters), {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .catch(errorHandler);\n let recognizedTokenTypes;\n if (grantType === 'urn:ietf:params:oauth:grant-type:token-exchange') {\n recognizedTokenTypes = { n_a: () => { } };\n }\n const p = oauth.processGenericTokenEndpointResponse(as, c, response, {\n [oauth.jweDecrypt]: decrypt,\n recognizedTokenTypes,\n });\n let result;\n try {\n result = await p;\n }\n catch (err) {\n if (retryable(err, options)) {\n return genericGrantRequest(config, grantType, parameters, {\n ...options,\n flag: retry,\n });\n }\n errorHandler(err);\n }\n result.id_token && (await nonRepudiation?.(response));\n addHelpers(result);\n return result;\n}\nexport async function tokenRevocation(config, token, parameters) {\n checkConfig(config);\n const { as, c, auth, fetch, tlsOnly, timeout } = int(config);\n return oauth\n .revocationRequest(as, c, auth, token, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n additionalParameters: new URLSearchParams(parameters),\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .then(oauth.processRevocationResponse)\n .catch(errorHandler);\n}\nexport async function fetchProtectedResource(config, accessToken, url, method, body, headers, options) {\n checkConfig(config);\n headers ||= new Headers();\n if (USER_AGENT && !headers.has('user-agent')) {\n headers.set('user-agent', USER_AGENT);\n }\n const { fetch, tlsOnly, timeout } = int(config);\n const exec = oauth.protectedResourceRequest(accessToken, method, url, headers, body, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n DPoP: options?.DPoP,\n signal: signal(timeout),\n });\n let result;\n try {\n result = await exec;\n }\n catch (err) {\n if (retryable(err, options)) {\n return fetchProtectedResource(config, accessToken, url, method, body, headers, {\n ...options,\n flag: retry,\n });\n }\n errorHandler(err);\n }\n return result;\n}\n//# sourceMappingURL=index.js.map","import * as oidc from \"openid-client\";\nimport {\n\ttype CoordinatorAccountReference,\n\tisCoordinatorAccountIssuer,\n\tparseCoordinatorAccountReference,\n} from \"./coordinator-auth-contract.js\";\n\nexport interface CoordinatorOidcProviderConfig {\n\tissuer: string;\n\tclientId: string;\n\tclientSecret: string;\n\tredirectUri: string;\n}\n\n/** Trusted transport options, not a JSON configuration surface. */\nexport interface CoordinatorOidcOptions {\n\tfetch?: oidc.CustomFetch;\n\ttimeoutSeconds?: number;\n}\n\n/** Secret transaction material: keep server-side, never in browser JSON. */\nexport type CoordinatorOidcMaterial = { state: string; nonce: string; pkceVerifier: string };\n\n/** Display metadata only; these fields never grant permissions. */\nexport interface CoordinatorOidcProfile {\n\tdisplayName?: string;\n\temail?: string;\n\temailVerified?: boolean;\n\tpictureUrl?: string;\n}\n\ntype CallbackResult =\n\t| { ok: true; account: CoordinatorAccountReference; profile: CoordinatorOidcProfile }\n\t| { ok: false; error: \"invalid_callback\" | \"oidc_verification_failed\" };\n\nexport interface CoordinatorOidcClient {\n\tcreateAuthorizationRequest(): Promise<{\n\t\tauthorizationUrl: string;\n\t\tmaterial: CoordinatorOidcMaterial;\n\t}>;\n\tverifyCallback(\n\t\tinput: { callbackUrl: string; material: CoordinatorOidcMaterial },\n\t\toptions?: { fetchUserInfo?: boolean },\n\t): Promise<CallbackResult>;\n}\n\nconst CONTROL = /[\\p{Cc}\\p{Cf}\\p{Cs}]/u;\nconst MATERIAL = /^[A-Za-z0-9._~-]{43,128}$/;\n\nfunction capture(value: unknown, keys: string[]): Record<string, unknown> {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) throw new Error();\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (prototype !== Object.prototype && prototype !== null) throw new Error();\n\tconst result: Record<string, unknown> = {};\n\tfor (const key of keys) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\tif (descriptor && !Object.hasOwn(descriptor, \"value\")) throw new Error();\n\t\tresult[key] = descriptor?.value;\n\t}\n\treturn result;\n}\n\nfunction httpsUrl(value: unknown, options: { allowQuery: boolean }): URL | undefined {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\tvalue !== value.trim() ||\n\t\tCONTROL.test(value) ||\n\t\tvalue.includes(\"\\\\\") ||\n\t\tvalue.includes(\"#\") ||\n\t\t(!options.allowQuery && value.includes(\"?\")) ||\n\t\t!/^https:\\/\\//i.test(value)\n\t)\n\t\treturn undefined;\n\ttry {\n\t\tconst url = new URL(value);\n\t\tif (url.protocol !== \"https:\" || !url.hostname || url.username || url.password || url.hash) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn url;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction credential(value: unknown, maximum: number): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length <= maximum &&\n\t\tvalue.trim().length > 0 &&\n\t\tvalue.trim() === value &&\n\t\t!CONTROL.test(value)\n\t);\n}\n\nfunction captureConfiguration(config: unknown, options: unknown) {\n\tconst c = capture(config, [\"issuer\", \"clientId\", \"clientSecret\", \"redirectUri\"]);\n\tconst o = capture(options === undefined ? {} : options, [\"fetch\", \"timeoutSeconds\"]);\n\tconst redirect = httpsUrl(c.redirectUri, { allowQuery: false });\n\tif (\n\t\t!isCoordinatorAccountIssuer(c.issuer) ||\n\t\t!httpsUrl(c.issuer, { allowQuery: false }) ||\n\t\t!credential(c.clientId, 256) ||\n\t\t!credential(c.clientSecret, 4096) ||\n\t\ttypeof c.redirectUri !== \"string\" ||\n\t\t!redirect ||\n\t\tredirect.href !== c.redirectUri ||\n\t\t(o.fetch !== undefined && typeof o.fetch !== \"function\")\n\t)\n\t\tthrow new Error();\n\tconst timeout = o.timeoutSeconds === undefined ? 10 : o.timeoutSeconds;\n\tif (typeof timeout !== \"number\" || !Number.isFinite(timeout) || timeout < 1 || timeout > 30) {\n\t\tthrow new Error();\n\t}\n\treturn {\n\t\tissuer: c.issuer,\n\t\tclientId: c.clientId,\n\t\tclientSecret: c.clientSecret,\n\t\tredirectUri: c.redirectUri,\n\t\tfetch: o.fetch as oidc.CustomFetch | undefined,\n\t\ttimeout,\n\t};\n}\n\nfunction validateMetadata(config: oidc.Configuration, issuer: string): void {\n\tconst metadata = config.serverMetadata();\n\tif (metadata.issuer !== issuer) throw new Error();\n\tfor (const endpoint of [\n\t\tmetadata.authorization_endpoint,\n\t\tmetadata.token_endpoint,\n\t\tmetadata.jwks_uri,\n\t]) {\n\t\tif (!httpsUrl(endpoint, { allowQuery: true })) throw new Error();\n\t}\n\tif (\n\t\tmetadata.userinfo_endpoint !== undefined &&\n\t\t!httpsUrl(metadata.userinfo_endpoint, { allowQuery: true })\n\t)\n\t\tthrow new Error();\n}\n\nfunction captureCallback(input: unknown, options: unknown, redirectUri: string) {\n\tconst i = capture(input, [\"callbackUrl\", \"material\"]);\n\tconst m = capture(i.material, [\"state\", \"nonce\", \"pkceVerifier\"]);\n\tconst o = capture(options === undefined ? {} : options, [\"fetchUserInfo\"]);\n\tif (o.fetchUserInfo !== undefined && typeof o.fetchUserInfo !== \"boolean\") throw new Error();\n\tif (\n\t\ttypeof m.state !== \"string\" ||\n\t\t!MATERIAL.test(m.state) ||\n\t\ttypeof m.nonce !== \"string\" ||\n\t\t!MATERIAL.test(m.nonce) ||\n\t\ttypeof m.pkceVerifier !== \"string\" ||\n\t\t!MATERIAL.test(m.pkceVerifier)\n\t)\n\t\tthrow new Error();\n\tconst url = httpsUrl(i.callbackUrl, { allowQuery: true });\n\tconst redirect = new URL(redirectUri);\n\tif (!url || url.origin !== redirect.origin || url.pathname !== redirect.pathname)\n\t\tthrow new Error();\n\treturn {\n\t\turl,\n\t\tstate: m.state,\n\t\tnonce: m.nonce,\n\t\tpkceVerifier: m.pkceVerifier,\n\t\tfetchUserInfo: o.fetchUserInfo === true,\n\t};\n}\n\nfunction displayString(value: unknown, maximum: number): value is string {\n\treturn (\n\t\ttypeof value === \"string\" && value.length > 0 && value.length <= maximum && !CONTROL.test(value)\n\t);\n}\n\nfunction projectProfile(claims: unknown): CoordinatorOidcProfile {\n\tconst c = capture(claims, [\"name\", \"email\", \"email_verified\", \"picture\"]);\n\tconst profile: CoordinatorOidcProfile = {};\n\tif (displayString(c.name, 256)) profile.displayName = c.name;\n\tif (displayString(c.email, 320)) profile.email = c.email;\n\tif (profile.email !== undefined && typeof c.email_verified === \"boolean\") {\n\t\tprofile.emailVerified = c.email_verified;\n\t}\n\t// Rendering needs its own image policy; this adapter never fetches pictures.\n\tif (displayString(c.picture, 2048) && httpsUrl(c.picture, { allowQuery: true })) {\n\t\tprofile.pictureUrl = c.picture;\n\t}\n\treturn profile;\n}\n\nfunction mergeProfile(\n\tprofile: CoordinatorOidcProfile,\n\textra: CoordinatorOidcProfile,\n): CoordinatorOidcProfile {\n\tconst merged = { ...profile, ...extra };\n\tif (extra.email !== undefined && extra.emailVerified === undefined) delete merged.emailVerified;\n\treturn merged;\n}\n\nasync function authorizationRequest(config: oidc.Configuration, redirectUri: string) {\n\ttry {\n\t\tconst material = {\n\t\t\tstate: oidc.randomState(),\n\t\t\tnonce: oidc.randomNonce(),\n\t\t\tpkceVerifier: oidc.randomPKCECodeVerifier(),\n\t\t};\n\t\tconst challenge = await oidc.calculatePKCECodeChallenge(material.pkceVerifier);\n\t\tconst url = oidc.buildAuthorizationUrl(config, {\n\t\t\tredirect_uri: redirectUri,\n\t\t\tresponse_type: \"code\",\n\t\t\tscope: \"openid email profile\",\n\t\t\tstate: material.state,\n\t\t\tnonce: material.nonce,\n\t\t\tcode_challenge: challenge,\n\t\t\tcode_challenge_method: \"S256\",\n\t\t\tresponse_mode: \"query\",\n\t\t\taccess_type: \"online\",\n\t\t});\n\t\treturn { authorizationUrl: url.href, material };\n\t} catch {\n\t\tthrow new Error(\"oidc_request_failed\");\n\t}\n}\n\nfunction adapter(\n\tconfig: oidc.Configuration,\n\tissuer: string,\n\tredirectUri: string,\n): CoordinatorOidcClient {\n\treturn {\n\t\tcreateAuthorizationRequest: () => authorizationRequest(config, redirectUri),\n\t\tasync verifyCallback(input, options): Promise<CallbackResult> {\n\t\t\tlet callback: ReturnType<typeof captureCallback>;\n\t\t\ttry {\n\t\t\t\tcallback = captureCallback(input, options, redirectUri);\n\t\t\t} catch {\n\t\t\t\treturn { ok: false, error: \"invalid_callback\" };\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst tokens = await oidc.authorizationCodeGrant(config, callback.url, {\n\t\t\t\t\tpkceCodeVerifier: callback.pkceVerifier,\n\t\t\t\t\texpectedState: callback.state,\n\t\t\t\t\texpectedNonce: callback.nonce,\n\t\t\t\t\tidTokenExpected: true,\n\t\t\t\t});\n\t\t\t\tconst claims = tokens.claims();\n\t\t\t\tif (!claims || claims.iss !== issuer) throw new Error();\n\t\t\t\tconst reference = parseCoordinatorAccountReference(\n\t\t\t\t\t{ issuer: claims.iss, subject: claims.sub },\n\t\t\t\t\t{ issuer },\n\t\t\t\t);\n\t\t\t\tif (!reference.ok) throw new Error();\n\t\t\t\tlet profile = projectProfile(claims);\n\t\t\t\tif (callback.fetchUserInfo) {\n\t\t\t\t\tconst userInfo = await oidc.fetchUserInfo(\n\t\t\t\t\t\tconfig,\n\t\t\t\t\t\ttokens.access_token,\n\t\t\t\t\t\treference.account.subject,\n\t\t\t\t\t);\n\t\t\t\t\tprofile = mergeProfile(profile, projectProfile(userInfo));\n\t\t\t\t}\n\t\t\t\treturn { ok: true, account: { ...reference.account }, profile };\n\t\t\t} catch {\n\t\t\t\treturn { ok: false, error: \"oidc_verification_failed\" };\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * Proof verification only. Durable transaction consumption and browser binding\n * belong to the caller; an in-memory replay set cannot replace those checks.\n */\nexport async function createCoordinatorOidcClient(\n\tconfig: CoordinatorOidcProviderConfig,\n\toptions?: CoordinatorOidcOptions,\n): Promise<\n\t| { ok: true; client: CoordinatorOidcClient }\n\t| { ok: false; error: \"invalid_provider_configuration\" | \"oidc_discovery_failed\" }\n> {\n\tlet captured: ReturnType<typeof captureConfiguration>;\n\ttry {\n\t\tcaptured = captureConfiguration(config, options);\n\t} catch {\n\t\treturn { ok: false, error: \"invalid_provider_configuration\" };\n\t}\n\ttry {\n\t\tconst privateConfig = await oidc.discovery(\n\t\t\tnew URL(captured.issuer),\n\t\t\tcaptured.clientId,\n\t\t\t{\n\t\t\t\tclient_secret: captured.clientSecret,\n\t\t\t\tid_token_signed_response_alg: \"RS256\",\n\t\t\t\t[oidc.clockTolerance]: 0,\n\t\t\t},\n\t\t\toidc.ClientSecretPost(captured.clientSecret),\n\t\t\t{\n\t\t\t\t[oidc.customFetch]: captured.fetch,\n\t\t\t\ttimeout: captured.timeout,\n\t\t\t\texecute: [oidc.enableNonRepudiationChecks],\n\t\t\t},\n\t\t);\n\t\tvalidateMetadata(privateConfig, captured.issuer);\n\t\treturn { ok: true, client: adapter(privateConfig, captured.issuer, captured.redirectUri) };\n\t} catch {\n\t\treturn { ok: false, error: \"oidc_discovery_failed\" };\n\t}\n}\n","/** Lifecycle state only, not historical provenance or current device authority.\n * Callers must also validate the link's full authority-specific proof.\n */\nexport function authLinkLiveGenerationSql(options: {\n\tlink: \"l\" | \"cl\";\n\tconnections?: true;\n}): string {\n\tconst link = options.link;\n\tif (link !== \"l\" && link !== \"cl\") throw new Error(\"auth_link_alias_invalid\");\n\t// The complete connection schema retains disconnected generations in history,\n\t// not as ended rows in the current table. Callers must check full readiness;\n\t// this is an explicit storage representation, never a partial-schema fallback.\n\tif (options.connections)\n\t\treturn `(${link}.revoked_at_ms IS NULL\n AND EXISTS (SELECT 1 FROM coordinator_auth_account_links current_generation\n WHERE current_generation.coordinator_id=${link}.coordinator_id AND current_generation.link_id=${link}.link_id\n AND current_generation.identity_id=${link}.identity_id AND current_generation.issuer=${link}.issuer\n AND current_generation.subject=${link}.subject AND current_generation.revoked_at_ms IS NULL)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history barrier\n WHERE barrier.coordinator_id=${link}.coordinator_id AND barrier.identity_id=${link}.identity_id AND barrier.revoked_at_ms IS NOT NULL))`;\n\treturn `(${link}.revoked_at_ms IS NULL AND ${link}.ended_at_ms IS NULL\n AND EXISTS (SELECT 1 FROM coordinator_auth_account_associations live_association\n WHERE live_association.coordinator_id = ${link}.coordinator_id\n AND live_association.issuer = ${link}.issuer AND live_association.subject = ${link}.subject\n AND live_association.identity_id = ${link}.identity_id)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_links security_barrier\n WHERE security_barrier.coordinator_id = ${link}.coordinator_id\n AND security_barrier.identity_id = ${link}.identity_id\n AND security_barrier.revoked_at_ms IS NOT NULL))`;\n}\n","/**\n * Inert storage only, not an issuer or proof of authority. Future issuance must\n * resolve every fact server-side from the exact link, claim and genuine review.\n * No subject/email copy or cascading references: historical evidence survives\n * removal or revocation of the original device. Nothing installs this on open.\n */\nexport interface CoordinatorOwnerEnrollmentQualificationRow {\n\treadonly qualification_id: string;\n\treadonly coordinator_id: string;\n\treadonly link_id: string;\n\treadonly device_claim_id: string;\n\treadonly identity_id: string;\n\treadonly source_group_id: string;\n\treadonly device_id: string;\n\treadonly public_key: string;\n\treadonly fingerprint: string;\n\treadonly key_id: string;\n\treadonly controller_attestation_id: string;\n\treadonly controller_attestation_revision: number;\n\treadonly controller_attestation_created_at: string;\n\treadonly review_receipt_id: string;\n\treadonly evidence_digest: string;\n\treadonly enrollment_identity_id: string | null;\n\treadonly link_attempt_id: string;\n\treadonly link_auth_config_revision: string;\n\treadonly link_created_at_ms: number;\n\treadonly created_at_ms: number;\n\treadonly revoked_at_ms: number | null;\n}\n\n// Separate complete statements allow native D1 batches without splitting triggers.\nexport const COORDINATOR_OWNER_ENROLLMENT_QUALIFICATION_SCHEMA_STATEMENTS = [\n\t`\nCREATE TABLE IF NOT EXISTS coordinator_owner_enrollment_qualifications (\n qualification_id TEXT PRIMARY KEY NOT NULL CHECK (typeof(qualification_id) = 'text' AND length(qualification_id) BETWEEN 1 AND 256 AND qualification_id = trim(qualification_id) AND length(trim(qualification_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(qualification_id, char(0)) = 0),\n coordinator_id TEXT NOT NULL CHECK (typeof(coordinator_id) = 'text' AND length(coordinator_id) BETWEEN 1 AND 256 AND coordinator_id = trim(coordinator_id) AND length(trim(coordinator_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(coordinator_id, char(0)) = 0),\n link_id TEXT NOT NULL CHECK (typeof(link_id) = 'text' AND length(link_id) BETWEEN 1 AND 256 AND link_id = trim(link_id) AND length(trim(link_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(link_id, char(0)) = 0),\n device_claim_id TEXT NOT NULL CHECK (typeof(device_claim_id) = 'text' AND length(device_claim_id) BETWEEN 1 AND 256 AND device_claim_id = trim(device_claim_id) AND length(trim(device_claim_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(device_claim_id, char(0)) = 0),\n identity_id TEXT NOT NULL CHECK (typeof(identity_id) = 'text' AND length(identity_id) BETWEEN 1 AND 256 AND identity_id = trim(identity_id) AND length(trim(identity_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(identity_id, char(0)) = 0),\n source_group_id TEXT NOT NULL CHECK (typeof(source_group_id) = 'text' AND length(source_group_id) BETWEEN 1 AND 256 AND source_group_id = trim(source_group_id) AND length(trim(source_group_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(source_group_id, char(0)) = 0),\n device_id TEXT NOT NULL CHECK (typeof(device_id) = 'text' AND length(device_id) BETWEEN 1 AND 256 AND device_id = trim(device_id) AND length(trim(device_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(device_id, char(0)) = 0),\n public_key TEXT NOT NULL CHECK (typeof(public_key) = 'text' AND length(public_key) BETWEEN 1 AND 4096 AND length(trim(public_key, char(9)||char(10)||char(13)||' ')) > 0 AND instr(public_key, char(0)) = 0),\n fingerprint TEXT NOT NULL CHECK (typeof(fingerprint) = 'text' AND length(fingerprint) = 64 AND fingerprint NOT GLOB '*[^0-9a-f]*' AND instr(fingerprint, char(0)) = 0),\n key_id TEXT NOT NULL CHECK (typeof(key_id) = 'text' AND length(key_id) = 64 AND key_id NOT GLOB '*[^0-9a-f]*' AND instr(key_id, char(0)) = 0),\n controller_attestation_id TEXT NOT NULL CHECK (typeof(controller_attestation_id) = 'text' AND length(controller_attestation_id) BETWEEN 1 AND 256 AND controller_attestation_id = trim(controller_attestation_id) AND length(trim(controller_attestation_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(controller_attestation_id, char(0)) = 0),\n controller_attestation_revision INTEGER NOT NULL CHECK (typeof(controller_attestation_revision) = 'integer' AND controller_attestation_revision = 1),\n controller_attestation_created_at TEXT NOT NULL CHECK (typeof(controller_attestation_created_at) = 'text' AND length(trim(controller_attestation_created_at, char(9)||char(10)||char(13)||' ')) > 0 AND instr(controller_attestation_created_at, char(0)) = 0),\n review_receipt_id TEXT NOT NULL CHECK (typeof(review_receipt_id) = 'text' AND length(review_receipt_id) BETWEEN 1 AND 256 AND review_receipt_id = trim(review_receipt_id) AND length(trim(review_receipt_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(review_receipt_id, char(0)) = 0),\n evidence_digest TEXT NOT NULL CHECK (typeof(evidence_digest) = 'text' AND length(evidence_digest) = 64 AND evidence_digest NOT GLOB '*[^0-9a-f]*' AND instr(evidence_digest, char(0)) = 0),\n enrollment_identity_id TEXT CHECK (enrollment_identity_id IS NULL OR (typeof(enrollment_identity_id) = 'text' AND length(enrollment_identity_id) BETWEEN 1 AND 256 AND enrollment_identity_id = trim(enrollment_identity_id) AND length(trim(enrollment_identity_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(enrollment_identity_id, char(0)) = 0)),\n link_attempt_id TEXT NOT NULL CHECK (typeof(link_attempt_id) = 'text' AND length(link_attempt_id) BETWEEN 1 AND 256 AND link_attempt_id = trim(link_attempt_id) AND length(trim(link_attempt_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(link_attempt_id, char(0)) = 0),\n link_auth_config_revision TEXT NOT NULL CHECK (typeof(link_auth_config_revision) = 'text' AND length(link_auth_config_revision) = 64 AND link_auth_config_revision NOT GLOB '*[^0-9a-f]*' AND instr(link_auth_config_revision, char(0)) = 0),\n link_created_at_ms INTEGER NOT NULL CHECK (typeof(link_created_at_ms) = 'integer' AND link_created_at_ms BETWEEN 0 AND 9007199254740991),\n created_at_ms INTEGER NOT NULL CHECK (typeof(created_at_ms) = 'integer' AND created_at_ms BETWEEN link_created_at_ms AND 9007199254740991),\n revoked_at_ms INTEGER CHECK (revoked_at_ms IS NULL OR (typeof(revoked_at_ms) = 'integer' AND revoked_at_ms BETWEEN created_at_ms AND 9007199254740991)),\n UNIQUE (coordinator_id, link_id)\n) WITHOUT ROWID;\n`,\n\t`\n-- Qualifications are born active; revocation requires an explicit UPDATE.\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_qualification_insert_active\nBEFORE INSERT ON coordinator_owner_enrollment_qualifications\nWHEN NEW.revoked_at_ms IS NOT NULL\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_qualification_birth_revoked'); END;\n`,\n\t`\n-- Each collision probe uses a unique index, never a coordinator-wide OR scan.\n-- Reject even same-value UPSERT/REPLACE: revocation must use explicit UPDATE.\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_qualification_insert_collision\nBEFORE INSERT ON coordinator_owner_enrollment_qualifications\nWHEN EXISTS (SELECT 1 FROM coordinator_owner_enrollment_qualifications WHERE qualification_id = NEW.qualification_id)\n OR EXISTS (SELECT 1 FROM coordinator_owner_enrollment_qualifications WHERE coordinator_id = NEW.coordinator_id AND link_id = NEW.link_id)\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_qualification_collision'); END;\n`,\n\t`\n-- Compare storage classes explicitly, including the nullable enrollment snapshot.\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_qualification_immutable_update\nBEFORE UPDATE ON coordinator_owner_enrollment_qualifications\nWHEN OLD.qualification_id IS NOT NEW.qualification_id OR typeof(NEW.qualification_id) <> 'text'\n OR OLD.coordinator_id IS NOT NEW.coordinator_id OR typeof(NEW.coordinator_id) <> 'text'\n OR OLD.link_id IS NOT NEW.link_id OR typeof(NEW.link_id) <> 'text'\n OR OLD.device_claim_id IS NOT NEW.device_claim_id OR typeof(NEW.device_claim_id) <> 'text'\n OR OLD.identity_id IS NOT NEW.identity_id OR typeof(NEW.identity_id) <> 'text'\n OR OLD.source_group_id IS NOT NEW.source_group_id OR typeof(NEW.source_group_id) <> 'text'\n OR OLD.device_id IS NOT NEW.device_id OR typeof(NEW.device_id) <> 'text'\n OR OLD.public_key IS NOT NEW.public_key OR typeof(NEW.public_key) <> 'text'\n OR OLD.fingerprint IS NOT NEW.fingerprint OR typeof(NEW.fingerprint) <> 'text'\n OR OLD.key_id IS NOT NEW.key_id OR typeof(NEW.key_id) <> 'text'\n OR OLD.controller_attestation_id IS NOT NEW.controller_attestation_id OR typeof(NEW.controller_attestation_id) <> 'text'\n OR OLD.controller_attestation_revision IS NOT NEW.controller_attestation_revision OR typeof(NEW.controller_attestation_revision) <> 'integer'\n OR OLD.controller_attestation_created_at IS NOT NEW.controller_attestation_created_at OR typeof(NEW.controller_attestation_created_at) <> 'text'\n OR OLD.review_receipt_id IS NOT NEW.review_receipt_id OR typeof(NEW.review_receipt_id) <> 'text'\n OR OLD.evidence_digest IS NOT NEW.evidence_digest OR typeof(NEW.evidence_digest) <> 'text'\n OR OLD.enrollment_identity_id IS NOT NEW.enrollment_identity_id OR typeof(OLD.enrollment_identity_id) <> typeof(NEW.enrollment_identity_id)\n OR OLD.link_attempt_id IS NOT NEW.link_attempt_id OR typeof(NEW.link_attempt_id) <> 'text'\n OR OLD.link_auth_config_revision IS NOT NEW.link_auth_config_revision OR typeof(NEW.link_auth_config_revision) <> 'text'\n OR OLD.link_created_at_ms IS NOT NEW.link_created_at_ms OR typeof(NEW.link_created_at_ms) <> 'integer'\n OR OLD.created_at_ms IS NOT NEW.created_at_ms OR typeof(NEW.created_at_ms) <> 'integer'\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_qualification_immutable'); END;\n`,\n\t`\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_qualification_revocation_update\nBEFORE UPDATE ON coordinator_owner_enrollment_qualifications\nWHEN (OLD.revoked_at_ms IS NOT NULL AND OLD.revoked_at_ms IS NOT NEW.revoked_at_ms)\n OR (NEW.revoked_at_ms IS NOT NULL AND (typeof(NEW.revoked_at_ms) <> 'integer'\n OR NEW.revoked_at_ms < OLD.created_at_ms OR NEW.revoked_at_ms > 9007199254740991))\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_qualification_revocation_monotonic'); END;\n`,\n\t`\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_qualification_immutable_delete\nBEFORE DELETE ON coordinator_owner_enrollment_qualifications\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_qualification_immutable'); END;\n`,\n] as const;\n\nexport const COORDINATOR_OWNER_ENROLLMENT_QUALIFICATION_SCHEMA_SQL =\n\tCOORDINATOR_OWNER_ENROLLMENT_QUALIFICATION_SCHEMA_STATEMENTS.join(\"\\n\");\n","import { hasConnectionSessionSchema } from \"./coordinator-account-connection-session.js\";\nimport { authSchemaDefinitionCheck } from \"./coordinator-auth-device-claim-schema.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport { authLinkLiveGenerationSql } from \"./coordinator-auth-link-liveness.js\";\nimport { authDeviceClaimProvenanceSql } from \"./coordinator-auth-link-provenance.js\";\nimport type { OwnerAuthorityAttempt } from \"./coordinator-owner-enrollment-proof.js\";\nimport { COORDINATOR_OWNER_ENROLLMENT_QUALIFICATION_SCHEMA_STATEMENTS } from \"./coordinator-owner-enrollment-qualification-schema.js\";\nimport { COORDINATOR_OWNER_ENROLLMENT_SCHEMA_SQL } from \"./coordinator-owner-enrollment-schema.js\";\n\n// Only the frozen 0036 table/authority guards and canonical 0035 ledger enable claims.\n// Absence preserves legacy controller SQL; partial storage never enables a claim.\nconst attemptDefinitions =\n\tCOORDINATOR_OWNER_ENROLLMENT_SCHEMA_SQL.match(\n\t\t/CREATE (?:TABLE|TRIGGER|INDEX)[\\s\\S]*?;(?=\\s*(?:--|CREATE|$))/gu,\n\t) ?? [];\nconst requiredAttempts = attemptDefinitions.filter(\n\t(sql) =>\n\t\t/^CREATE TABLE/u.test(sql) ||\n\t\t/CREATE TRIGGER IF NOT EXISTS owner_enrollment_authority_/u.test(sql),\n);\nconst readiness = [\n\t...requiredAttempts,\n\t...COORDINATOR_OWNER_ENROLLMENT_QUALIFICATION_SCHEMA_STATEMENTS,\n]\n\t.map((sql) => {\n\t\tconst check = authSchemaDefinitionCheck(sql).matches;\n\t\tif (!sql.startsWith(\"CREATE TABLE IF NOT EXISTS coordinator_owner_enrollment_attempts\"))\n\t\t\treturn check;\n\t\t// ALTER RENAME in official 0036 quotes this header only. Retain every body byte\n\t\t// for the full definition comparison, including quoted literals and CHECKs.\n\t\tconst header = 'CREATE TABLE \"coordinator_owner_enrollment_attempts\"';\n\t\treturn check.replace(\n\t\t\t\"FROM sqlite_master WHERE\",\n\t\t\t`FROM (SELECT type,name,CASE WHEN substr(sql,1,${header.length}) = '${header}'\n THEN 'CREATE TABLE coordinator_owner_enrollment_attempts' || substr(sql,${header.length + 1})\n ELSE sql END AS sql FROM sqlite_master) WHERE`,\n\t\t);\n\t})\n\t.join(\" AND \");\n\n/** Historical review birth, not current controller authority or old-device liveness. */\nconst QUALIFIED_LINKS = `SELECT l.coordinator_id,l.link_id,q.qualification_id\n FROM owner_claim_proven_links l\n JOIN coordinator_owner_enrollment_qualifications q ON q.coordinator_id=l.coordinator_id AND q.link_id=l.link_id\n JOIN coordinator_auth_device_claims d ON d.coordinator_id=l.coordinator_id AND d.claim_id=l.device_claim_id\n JOIN coordinator_auth_controller_attestations origin ON origin.coordinator_id=q.coordinator_id AND origin.attestation_id=q.controller_attestation_id\n WHERE l.authority_kind='device_claim' AND l.controller_attestation_id IS NULL\n AND q.revoked_at_ms IS NULL AND q.device_claim_id=d.claim_id AND q.identity_id=l.identity_id\n AND q.link_attempt_id=l.attempt_id AND q.link_auth_config_revision=l.auth_config_revision AND q.link_created_at_ms=l.created_at_ms\n AND q.source_group_id=d.group_id AND q.device_id=d.device_id AND q.public_key=d.public_key\n AND q.fingerprint=d.fingerprint AND q.key_id=d.key_id AND q.identity_id=d.identity_id\n AND origin.identity_id=q.identity_id AND origin.group_id=q.source_group_id AND origin.device_id=q.device_id\n AND origin.public_key=q.public_key AND origin.fingerprint=q.fingerprint\n AND origin.revision=q.controller_attestation_revision AND origin.revision=1\n AND origin.created_at=q.controller_attestation_created_at AND origin.review_receipt_id=q.review_receipt_id\n AND origin.evidence_digest=q.evidence_digest AND origin.enrollment_identity_id IS q.enrollment_identity_id\n AND (q.enrollment_identity_id IS NULL OR q.enrollment_identity_id=q.identity_id)\n AND (${authLinkLiveGenerationSql({ link: \"l\", connections: true })})`;\n\n/** Scope SQL is private composition, with values from a session or stored attempt.\n * No scope means no rows, never a coordinator-wide authority scan.\n */\nexport async function readOwnerLinkAuthority(\n\tbackend: AuthLinkBackend,\n\ttime = Date.now(),\n\tscope: AuthLinkStatement = { sql: \"0\", values: [] },\n) {\n\tconst capturedScope = { sql: scope.sql, values: [...scope.values] };\n\tif (!Number.isSafeInteger(time) || time < 0) throw new Error(\"owner_authority_invalid_time\");\n\tconst column = await backend.first<{ present: number }>({\n\t\tsql: \"SELECT EXISTS (SELECT 1 FROM pragma_table_info('coordinator_owner_enrollment_attempts') WHERE name='owner_qualification_id') AS present\",\n\t\tvalues: [],\n\t});\n\tconst hasPin = column?.present === 1;\n\tlet qualified = false;\n\tif (hasPin && (await hasConnectionSessionSchema(backend))) {\n\t\tconst result = await backend.first<{ ready: number }>({\n\t\t\tsql: `SELECT (${readiness}) AS ready`,\n\t\t\tvalues: [],\n\t\t});\n\t\tqualified = result?.ready === 1 && requiredAttempts.length === 3;\n\t}\n\treturn ownerLinkAuthoritySql({ hasPin, qualified, time, scope: capturedScope });\n}\n\n/** Controller-only SQL: cannot admit a claim or use qualification evidence.\n * The attempt is the operation's SELECT * snapshot, never request JSON.\n * Optional qualification-schema reads add no authority to this legacy branch.\n */\nexport function controllerOwnerLinkAuthority(\n\tattempt: OwnerAuthorityAttempt,\n\tscope: AuthLinkStatement,\n) {\n\treturn ownerLinkAuthoritySql({\n\t\thasPin: Object.hasOwn(attempt, \"owner_qualification_id\"),\n\t\tqualified: false,\n\t\ttime: 0,\n\t\tscope: { sql: scope.sql, values: [...scope.values] },\n\t});\n}\n\nfunction ownerLinkAuthoritySql({\n\thasPin,\n\tqualified,\n\ttime,\n\tscope,\n}: {\n\thasPin: boolean;\n\tqualified: boolean;\n\ttime: number;\n\tscope: AuthLinkStatement;\n}) {\n\tconst qualification = qualified\n\t\t? \"(SELECT q.qualification_id FROM owner_qualified_links q WHERE q.coordinator_id=l.coordinator_id AND q.link_id=l.link_id)\"\n\t\t: \"NULL\";\n\tconst controller =\n\t\t\"l.authority_kind='controller_attestation' AND l.controller_attestation_id IS NOT NULL AND l.device_claim_id IS NULL\";\n\tconst controllerPin = hasPin\n\t\t? `(${controller}) AND a.owner_qualification_id IS NULL`\n\t\t: `(${controller})`;\n\tconst authorityPin = qualified\n\t\t? \"l.owner_qualification_id IS a.owner_qualification_id\"\n\t\t: controllerPin;\n\t// Materialize retained claim proof before adding qualification and attempt equality;\n\t// nesting all three in one predicate exceeds native D1's expression depth of 100.\n\tlet withSql = \"\";\n\tif (qualified || scope.sql !== \"0\") {\n\t\twithSql = `WITH owner_scope_links AS MATERIALIZED (\n SELECT l.* FROM coordinator_auth_account_links l WHERE ${scope.sql})${\n\t\tqualified\n\t\t\t? `, owner_claim_proven_links AS MATERIALIZED (\n SELECT l.* FROM owner_scope_links l\n WHERE ${authDeviceClaimProvenanceSql({ link: \"l\", connections: true })}),\n owner_qualified_links AS MATERIALIZED (${QUALIFIED_LINKS} AND q.created_at_ms <= ${time}),\n owner_authorized_links AS MATERIALIZED (\n SELECT l.*,${qualification} AS owner_qualification_id FROM owner_scope_links l\n WHERE (${controller}) OR ${qualification} IS NOT NULL) `\n\t\t\t: \"\"\n} `;\n\t}\n\treturn {\n\t\thasPin,\n\t\tvalues: scope.values,\n\t\twith: withSql,\n\t\tqualification,\n\t\tlink: `((${controller}) OR ${qualification} IS NOT NULL)`,\n\t\tactive: `EXISTS (SELECT 1 FROM ${qualified ? \"owner_authorized_links\" : \"owner_scope_links\"} l\n WHERE l.coordinator_id=a.coordinator_id AND l.link_id=a.link_id\n AND l.issuer=a.issuer AND l.subject=a.account_subject AND l.identity_id=a.identity_id\n AND l.attempt_id=a.link_attempt_id AND l.auth_config_revision=a.link_auth_config_revision AND l.revoked_at_ms IS NULL\n AND l.controller_attestation_id IS a.link_controller_attestation_id\n AND ${authorityPin})`,\n\t};\n}\n","import { parseCoordinatorAccountReference } from \"./coordinator-auth-contract.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport { parseCoordinatorAuthLoopback } from \"./coordinator-auth-loopback.js\";\nimport {\n\tdecodeCoordinatorAuthProof32,\n\tencodeCoordinatorAuthProof32,\n} from \"./coordinator-auth-proof.js\";\nimport { parseSshEd25519PublicKey } from \"./coordinator-ed25519-key-id.js\";\nimport { verifyOwnerEnrollmentSignature } from \"./coordinator-owner-enrollment-proof.js\";\nimport type { OwnerEnrollmentStart } from \"./owner-enrollment-start.js\";\n\nexport interface OwnerEnrollmentAdmissionPin {\n\tcoordinatorId: string;\n\torigin: string;\n\tissuer: string;\n\trevision: string;\n}\ndeclare const admissionKeyBrand: unique symbol;\nexport type OwnerEnrollmentAdmissionKey = Readonly<{ [admissionKeyBrand]: true }>;\ntype CryptoKey = Awaited<ReturnType<typeof globalThis.crypto.subtle.importKey>>;\nconst keys = new WeakMap<OwnerEnrollmentAdmissionKey, CryptoKey>();\nconst MAX_TTL_MS = 15 * 60 * 1000;\n\nexport function isOwnerEnrollmentAdmissionKey(\n\tvalue: unknown,\n): value is OwnerEnrollmentAdmissionKey {\n\treturn (\n\t\ttypeof value === \"object\" && value !== null && keys.has(value as OwnerEnrollmentAdmissionKey)\n\t);\n}\n\n/** Server-only key import. Sharing raw CSRF bytes is safe because the MAC domain differs. */\nexport async function importOwnerEnrollmentAdmissionKey(\n\traw: Uint8Array,\n): Promise<OwnerEnrollmentAdmissionKey> {\n\tif (!(raw instanceof Uint8Array) || raw.byteLength !== 32)\n\t\tthrow new Error(\"owner_admission_invalid_key\");\n\tconst cryptoKey = await globalThis.crypto.subtle.importKey(\n\t\t\"raw\",\n\t\tnew Uint8Array(raw),\n\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n\t\tfalse,\n\t\t[\"sign\", \"verify\"],\n\t);\n\tconst key = Object.freeze({}) as OwnerEnrollmentAdmissionKey;\n\tkeys.set(key, cryptoKey);\n\treturn key;\n}\n\nfunction text(value: unknown, maximum: number): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length > 0 &&\n\t\tvalue.length <= maximum &&\n\t\t!/[\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(value)\n\t);\n}\n\nfunction startTuple(pin: OwnerEnrollmentAdmissionPin, start: OwnerEnrollmentStart): string {\n\tconst parsed = parseSshEd25519PublicKey(start.publicKey);\n\tconst origin = new URL(pin.origin);\n\tif (\n\t\t!isAuthControllerId(pin.coordinatorId) ||\n\t\t!text(pin.revision, 64) ||\n\t\t!/^[a-f0-9]{64}$/.test(pin.revision) ||\n\t\torigin.protocol !== \"https:\" ||\n\t\torigin.origin !== pin.origin ||\n\t\t!text(pin.issuer, 4096) ||\n\t\t!isAuthControllerId(start.attemptId) ||\n\t\t!isAuthControllerId(start.deviceId) ||\n\t\t!text(start.publicKey, 80) ||\n\t\tparsed.kind !== \"ed25519\" ||\n\t\tstart.publicKey !== `ssh-ed25519 ${btoa(String.fromCharCode(...parsed.blob))}` ||\n\t\t!text(start.loopbackRedirect, 4096) ||\n\t\t!parseCoordinatorAuthLoopback(start.loopbackRedirect).ok ||\n\t\t!decodeCoordinatorAuthProof32(start.browserStartCode) ||\n\t\t!text(start.signature, 86)\n\t)\n\t\tthrow new Error(\"owner_admission_invalid_start\");\n\treturn JSON.stringify([\n\t\t\"codemem-owner-enrollment-start-v1\",\n\t\t\"owner_enroll\",\n\t\tpin.coordinatorId,\n\t\tpin.origin,\n\t\tpin.issuer,\n\t\tpin.revision,\n\t\tstart.attemptId,\n\t\tstart.deviceId,\n\t\tstart.publicKey,\n\t\tstart.loopbackRedirect,\n\t\tstart.browserStartCode,\n\t]);\n}\n\nfunction validTimes(issued: number, expires: number, now: number): boolean {\n\treturn (\n\t\t[issued, expires, now].every((n) => Number.isSafeInteger(n) && n >= 0) &&\n\t\tissued <= now &&\n\t\tnow < expires &&\n\t\texpires > issued &&\n\t\texpires - issued <= MAX_TTL_MS\n\t);\n}\n\nfunction message(\n\ttuple: string,\n\tsignature: string,\n\tissued: number,\n\texpires: number,\n): Uint8Array<ArrayBuffer> {\n\treturn new TextEncoder().encode(\n\t\tJSON.stringify([\"codemem-owner-enrollment-admission-v1\", issued, expires, tuple, signature]),\n\t);\n}\n\n/** Admin-only issuer: call only after reviewing this exact signed start. No durable state is created. */\nexport async function issueOwnerEnrollmentAdmission(\n\tkey: OwnerEnrollmentAdmissionKey,\n\tpin: OwnerEnrollmentAdmissionPin,\n\tstart: OwnerEnrollmentStart,\n\toptions: { nowMs: number; ttlMs: number },\n): Promise<string> {\n\tconst cryptoKey = keys.get(key);\n\tconst tuple = startTuple(pin, start);\n\tconst issued = options.nowMs;\n\tconst expires = issued + options.ttlMs;\n\tconst signature = start.signature;\n\tif (\n\t\t!cryptoKey ||\n\t\t!validTimes(issued, expires, issued) ||\n\t\t!(await verifyOwnerEnrollmentSignature(start.publicKey, tuple, signature))\n\t) {\n\t\tthrow new Error(\"owner_admission_invalid_start\");\n\t}\n\tconst mac = await globalThis.crypto.subtle.sign(\n\t\t\"HMAC\",\n\t\tcryptoKey,\n\t\tmessage(tuple, signature, issued, expires),\n\t);\n\treturn `v1.${issued}.${expires}.${encodeCoordinatorAuthProof32(new Uint8Array(mac))}`;\n}\n\n/** Exact retries still reach the retained-attempt uniqueness and capacity checks; this is not a replay store. */\nexport async function verifyOwnerEnrollmentAdmission(\n\tkey: OwnerEnrollmentAdmissionKey,\n\ttoken: unknown,\n\tpin: OwnerEnrollmentAdmissionPin,\n\tstart: OwnerEnrollmentStart,\n\tnowMs: number,\n): Promise<boolean> {\n\ttry {\n\t\tconst cryptoKey = keys.get(key);\n\t\tif (!cryptoKey || typeof token !== \"string\" || token.length > 81) return false;\n\t\tconst parts = /^v1\\.(0|[1-9][0-9]{0,15})\\.(0|[1-9][0-9]{0,15})\\.([A-Za-z0-9_-]{43})$/.exec(\n\t\t\ttoken,\n\t\t);\n\t\tif (!parts) return false;\n\t\tconst issued = Number(parts[1]);\n\t\tconst expires = Number(parts[2]);\n\t\tconst mac = decodeCoordinatorAuthProof32(parts[3]);\n\t\tif (!mac || !validTimes(issued, expires, nowMs)) return false;\n\t\treturn await globalThis.crypto.subtle.verify(\n\t\t\t\"HMAC\",\n\t\t\tcryptoKey,\n\t\t\tmac,\n\t\t\tmessage(startTuple(pin, start), start.signature, issued, expires),\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** Server-resolved account/link only. This structural type confers no authorization. */\nexport interface OwnerEnrollmentResolvedOwner {\n\treadonly coordinatorId: string;\n\treadonly issuer: string;\n\treadonly subject: string;\n\treadonly identityId: string;\n\treadonly linkId: string;\n}\n\nexport interface OwnerEnrollmentAdmissionV2Options {\n\treadonly resolvedOwner: OwnerEnrollmentResolvedOwner;\n\treadonly nowMs: number;\n\treadonly ttlMs: number;\n}\n\nexport interface OwnerEnrollmentAdmissionV2VerificationOptions {\n\treadonly resolvedOwner: OwnerEnrollmentResolvedOwner;\n\treadonly nowMs: number;\n}\n\nfunction ownerTuple(owner: OwnerEnrollmentResolvedOwner): string {\n\tconst { coordinatorId, issuer, subject, identityId, linkId } = owner;\n\tif (\n\t\t!isAuthControllerId(coordinatorId) ||\n\t\t!text(issuer, 4096) ||\n\t\t!parseCoordinatorAccountReference({ issuer, subject }, { issuer }).ok ||\n\t\t!isAuthControllerId(identityId) ||\n\t\t!isAuthControllerId(linkId)\n\t)\n\t\tthrow new Error(\"owner_admission_invalid_owner\");\n\treturn JSON.stringify([\n\t\t\"codemem-owner-enrollment-owner-commitment-v1\",\n\t\tcoordinatorId,\n\t\tissuer,\n\t\tsubject,\n\t\tidentityId,\n\t\tlinkId,\n\t]);\n}\n\nasync function hashOwnerTuple(tuple: string): Promise<string> {\n\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(tuple));\n\treturn Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Unmounted primitive: hashes canonical JSON [domain, coordinator, issuer, subject, Identity, link].\n * Returns lowercase SHA-256 hex, not authority or anonymization of guessable account data.\n */\nexport async function ownerEnrollmentOwnerCommitment(\n\towner: OwnerEnrollmentResolvedOwner,\n): Promise<string> {\n\treturn hashOwnerTuple(ownerTuple(owner));\n}\n\nfunction admissionV2Input(\n\tpin: OwnerEnrollmentAdmissionPin,\n\tstart: OwnerEnrollmentStart,\n\towner: OwnerEnrollmentResolvedOwner,\n) {\n\t// Copy every caller-owned field before crypto can yield. No later reads from inputs.\n\tconst pinned = {\n\t\tcoordinatorId: pin.coordinatorId,\n\t\torigin: pin.origin,\n\t\tissuer: pin.issuer,\n\t\trevision: pin.revision,\n\t};\n\tconst pending = {\n\t\tattemptId: start.attemptId,\n\t\tdeviceId: start.deviceId,\n\t\tpublicKey: start.publicKey,\n\t\tloopbackRedirect: start.loopbackRedirect,\n\t\tbrowserStartCode: start.browserStartCode,\n\t\tsignature: start.signature,\n\t};\n\tconst resolved = {\n\t\tcoordinatorId: owner.coordinatorId,\n\t\tissuer: owner.issuer,\n\t\tsubject: owner.subject,\n\t\tidentityId: owner.identityId,\n\t\tlinkId: owner.linkId,\n\t};\n\tconst ownerMessage = ownerTuple(resolved);\n\tif (\n\t\tresolved.coordinatorId !== pinned.coordinatorId ||\n\t\tresolved.issuer !== pinned.issuer ||\n\t\t!text(pinned.origin, 4096) ||\n\t\t!text(pending.browserStartCode, 43)\n\t)\n\t\tthrow new Error(\"owner_admission_invalid_start\");\n\treturn {\n\t\ttuple: startTuple(pinned, pending),\n\t\tpublicKey: pending.publicKey,\n\t\tsignature: pending.signature,\n\t\townerMessage,\n\t};\n}\n\nfunction messageV2(\n\ttuple: string,\n\tsignature: string,\n\tissued: number,\n\texpires: number,\n\townerCommitment: string,\n): Uint8Array<ArrayBuffer> {\n\treturn new TextEncoder().encode(\n\t\tJSON.stringify([\n\t\t\t\"codemem-owner-enrollment-admission-v2\",\n\t\t\tissued,\n\t\t\texpires,\n\t\t\ttuple,\n\t\t\tsignature,\n\t\t\townerCommitment,\n\t\t]),\n\t);\n}\n\n/**\n * Unmounted server-only issuer, NOT a self-service endpoint. Before calling, authenticate the\n * session and resolve its active account link, Identity and grants server-side. Never accept\n * resolvedOwner from request JSON. A type or commitment alone does not authorize issuance.\n * Uses the existing private admission key; v1 operator issuance/verification stays unchanged.\n */\nexport async function issueOwnerEnrollmentAdmissionV2(\n\tkey: OwnerEnrollmentAdmissionKey,\n\tpin: OwnerEnrollmentAdmissionPin,\n\tstart: OwnerEnrollmentStart,\n\toptions: OwnerEnrollmentAdmissionV2Options,\n): Promise<string> {\n\tconst cryptoKey = keys.get(key);\n\tconst input = admissionV2Input(pin, start, options.resolvedOwner);\n\tconst issued = options.nowMs;\n\tconst ttl = options.ttlMs;\n\tconst expires = issued + ttl;\n\tif (!cryptoKey || !Number.isSafeInteger(ttl) || !validTimes(issued, expires, issued))\n\t\tthrow new Error(\"owner_admission_invalid_start\");\n\tif (!(await verifyOwnerEnrollmentSignature(input.publicKey, input.tuple, input.signature)))\n\t\tthrow new Error(\"owner_admission_invalid_start\");\n\tconst commitment = await hashOwnerTuple(input.ownerMessage);\n\tconst mac = await globalThis.crypto.subtle.sign(\n\t\t\"HMAC\",\n\t\tcryptoKey,\n\t\tmessageV2(input.tuple, input.signature, issued, expires, commitment),\n\t);\n\treturn `v2.${issued}.${expires}.${commitment}.${encodeCoordinatorAuthProof32(new Uint8Array(mac))}`;\n}\n\n/**\n * Unmounted v2-only verifier; no v1 fallback. The hash companion is authenticated, not raw owner data.\n * Callers must separately retain an immutable attempt owner pin, compare it at callback/finalize,\n * and recheck live session/link/grant authority. This primitive creates no attempt or replay state.\n */\nexport async function verifyOwnerEnrollmentAdmissionV2(\n\tkey: OwnerEnrollmentAdmissionKey,\n\ttoken: unknown,\n\tpin: OwnerEnrollmentAdmissionPin,\n\tstart: OwnerEnrollmentStart,\n\toptions: OwnerEnrollmentAdmissionV2VerificationOptions,\n): Promise<boolean> {\n\ttry {\n\t\tconst cryptoKey = keys.get(key);\n\t\tif (!cryptoKey || typeof token !== \"string\" || token.length > 146) return false;\n\t\tconst parts =\n\t\t\t/^v2\\.(0|[1-9][0-9]{0,15})\\.(0|[1-9][0-9]{0,15})\\.([a-f0-9]{64})\\.([A-Za-z0-9_-]{43})$/.exec(\n\t\t\t\ttoken,\n\t\t\t);\n\t\tif (!parts) return false;\n\t\tconst issued = Number(parts[1]);\n\t\tconst expires = Number(parts[2]);\n\t\tconst commitment = parts[3];\n\t\tconst mac = decodeCoordinatorAuthProof32(parts[4]);\n\t\tconst now = options.nowMs;\n\t\tif (!mac || !commitment || !validTimes(issued, expires, now)) return false;\n\t\tconst input = admissionV2Input(pin, start, options.resolvedOwner);\n\t\tif ((await hashOwnerTuple(input.ownerMessage)) !== commitment) return false;\n\t\treturn await globalThis.crypto.subtle.verify(\n\t\t\t\"HMAC\",\n\t\t\tcryptoKey,\n\t\t\tmac,\n\t\t\tmessageV2(input.tuple, input.signature, issued, expires, commitment),\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n","import { ownerEnrollmentOwnerCommitment } from \"./owner-enrollment-admission.js\";\n\n/** NULL denotes the existing operator path, never an owner inferred from a device. */\nexport function validAdmissionOwnerHash(value: unknown): value is string | null {\n\treturn value === null || (typeof value === \"string\" && /^[a-f0-9]{64}$/.test(value));\n}\n\ninterface OwnerPin {\n\tadmission_owner_hash: string | null;\n\tcoordinator_id: string;\n\tissuer: string;\n\taccount_subject: string | null;\n\tidentity_id: string | null;\n\tlink_id: string | null;\n}\n\n/** Recompute from independently verified, exact account/link facts, not the token companion. */\nexport async function matchesAdmissionOwner(row: OwnerPin): Promise<boolean> {\n\tif (!validAdmissionOwnerHash(row.admission_owner_hash)) return false;\n\tif (row.admission_owner_hash === null) return true;\n\tif (!row.account_subject || !row.identity_id || !row.link_id) return false;\n\ttry {\n\t\treturn (\n\t\t\trow.admission_owner_hash ===\n\t\t\t(await ownerEnrollmentOwnerCommitment({\n\t\t\t\tcoordinatorId: row.coordinator_id,\n\t\t\t\tissuer: row.issuer,\n\t\t\t\tsubject: row.account_subject,\n\t\t\t\tidentityId: row.identity_id,\n\t\t\t\tlinkId: row.link_id,\n\t\t\t}))\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n","import type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport {\n\ted25519KeyIdForRevocation,\n\tparseSshEd25519PublicKeyForRevocation,\n} from \"./coordinator-ed25519-key-id-compat.js\";\nimport { COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS } from \"./coordinator-legacy-team-completion.js\";\nimport {\n\ttype OwnerAuthorityAttempt as OwnerAttempt,\n\townerEnrollmentConfirmationHash,\n\tvalidOwnerEnrollmentReceiptMetadata,\n\tverifyOwnerEnrollmentCompletion,\n} from \"./coordinator-owner-enrollment-proof.js\";\nimport {\n\tprepareNegativeOwnerConsistency,\n\twithNegativeOwnerWrite,\n} from \"./coordinator-owner-negative-consistency.js\";\nimport { readOwnerLinkAuthority } from \"./owner-enrollment-link-authority.js\";\nimport { matchesAdmissionOwner } from \"./owner-enrollment-owner-pin.js\";\n\nexport {\n\ttype OwnerAttempt,\n\tverifyOwnerEnrollmentSignature,\n} from \"./coordinator-owner-enrollment-proof.js\";\n\n/** Matches the optional Worker owner-enrollment audit migration. */\nexport const COORDINATOR_OWNER_ENROLLMENT_AUDIT_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS coordinator_owner_enrollment_audit_log (\n coordinator_id TEXT NOT NULL, event_id TEXT NOT NULL, attempt_id TEXT NOT NULL,\n action TEXT NOT NULL CHECK (action = 'owner_device_enrolled'),\n binding_id TEXT NOT NULL, device_id TEXT NOT NULL, created_at_ms INTEGER NOT NULL,\n PRIMARY KEY (coordinator_id, event_id), UNIQUE (coordinator_id, attempt_id)\n);`;\n\n/** Historical link provenance is equality only: never consult the old controller/device. */\nexport const OWNER_ACTIVE_LINK_SQL = `EXISTS (SELECT 1 FROM coordinator_auth_account_links l\n WHERE l.coordinator_id = a.coordinator_id AND l.link_id = a.link_id\n AND l.authority_kind = 'controller_attestation' AND l.controller_attestation_id IS NOT NULL AND l.device_claim_id IS NULL\n AND l.issuer = a.issuer AND l.subject = a.account_subject AND l.identity_id = a.identity_id\n AND l.attempt_id = a.link_attempt_id AND l.controller_attestation_id = a.link_controller_attestation_id\n AND l.auth_config_revision = a.link_auth_config_revision AND l.revoked_at_ms IS NULL)`;\n\n// Private SQL expressions only: a is the stored attempt in both callers.\nexport function ownerExcludedLegacyDecisionSql(\n\tgroupExpression: \"r.group_id\" | \"json_extract(p.value,'$.groupId')\",\n): string {\n\treturn `EXISTS (SELECT 1 FROM coordinator_legacy_team_completions c, json_each(c.manifest_json,'$.device_decisions') d\n WHERE c.group_id = ${groupExpression} AND json_extract(c.manifest_json,'$.coordinator_id') = a.coordinator_id\n AND json_extract(d.value,'$.decision') = 'excluded'\n AND (json_extract(d.value,'$.device_id') = a.device_id OR json_extract(d.value,'$.key_fingerprint') = a.fingerprint\n OR NOT EXISTS (SELECT 1 FROM enrolled_devices e WHERE e.group_id = c.group_id\n AND e.device_id = json_extract(d.value,'$.device_id') AND e.fingerprint = json_extract(d.value,'$.key_fingerprint'))))`;\n}\n\nconst LIVE_GRANTS = `json_array_length(a.grant_revisions_json) BETWEEN 1 AND 50\n AND NOT EXISTS (SELECT 1 FROM json_each(a.grant_revisions_json) p\n WHERE NOT EXISTS (SELECT 1 FROM coordinator_identity_group_grants r JOIN groups g ON g.group_id = r.group_id\n WHERE r.coordinator_id = a.coordinator_id AND r.identity_id = a.identity_id\n AND r.group_id = json_extract(p.value,'$.groupId') AND r.revision = json_extract(p.value,'$.revision')\n AND r.status = 'active' AND r.revoked_at IS NULL AND g.archived_at IS NULL)\n OR ${ownerExcludedLegacyDecisionSql(\"json_extract(p.value,'$.groupId')\")})`;\n\nconst NO_REVOCATION = `NOT EXISTS (SELECT 1 FROM coordinator_device_revocations\n WHERE (subject_kind = 'device_id' AND subject_value = a.device_id)\n OR (subject_kind = 'ed25519_key' AND subject_value = a.key_id))`;\n\ninterface EnrollmentKey {\n\tgroupId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n}\nasync function collisionSnapshot(\n\tbackend: AuthLinkBackend,\n\trow: OwnerAttempt,\n): Promise<string | null> {\n\t// This bounded scan fails closed above 500 enrollments; it is not an enrollment quota.\n\tconst source = await backend.first<{ rows: string }>({\n\t\tsql: `SELECT json_group_array(json_object('groupId',group_id,'deviceId',device_id,'publicKey',public_key)) AS rows FROM\n (SELECT group_id,device_id,public_key FROM enrolled_devices LIMIT ?)`,\n\t\tvalues: [COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS + 1],\n\t});\n\tif (!source) return null;\n\tconst rows = JSON.parse(source.rows) as EnrollmentKey[];\n\tif (rows.length > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS) return null;\n\tfor (const existing of rows) {\n\t\tif (existing.deviceId === row.device_id) return null;\n\t\tconst parsed = parseSshEd25519PublicKeyForRevocation(existing.publicKey);\n\t\tif (parsed.kind === \"malformed_ed25519\") return null;\n\t\tif ((await ed25519KeyIdForRevocation(existing.publicKey)) === row.key_id) return null;\n\t}\n\treturn source.rows;\n}\n\n// Every stored key must still belong to the scanned set inside the winning SQL update.\n// Concurrent unrelated enrollment changes deliberately deny this attempt.\nconst SAME_KEYS = `(SELECT count(*) FROM enrolled_devices) = json_array_length(?)\n AND NOT EXISTS (SELECT 1 FROM enrolled_devices e WHERE NOT EXISTS (SELECT 1 FROM json_each(?) k\n WHERE e.group_id = json_extract(k.value,'$.groupId') AND e.device_id = json_extract(k.value,'$.deviceId')\n AND e.public_key = json_extract(k.value,'$.publicKey')))`;\nconst WINNER = `coordinator_id = ? AND attempt_id = ? AND state = 'finalized' AND binding_id = ?`;\nfunction assertWrite(winner: string[], expected: number): AuthLinkStatement {\n\t// The finalized-row trigger (and invalid-state CHECK) aborts the native batch on a count mismatch.\n\treturn {\n\t\tsql: `UPDATE coordinator_owner_enrollment_attempts SET state = 'invalid' WHERE ${WINNER} AND changes() <> ?`,\n\t\tvalues: [...winner, expected],\n\t};\n}\n\ninterface OwnerEnrollmentCommitInput {\n\tbackend: AuthLinkBackend;\n\trow: OwnerAttempt;\n\trevision: string;\n\tnow: number;\n\tcompletionSecret: string;\n\tsignature: string;\n}\n\n/** Internal atomic finalization, not a package export or standalone ownership writer.\n * The later ceremony caller must supply trusted current config and a stored confirmed attempt.\n * SQL failures propagate: a failed post-commit read must not claim nothing changed.\n */\nexport async function commitOwnerEnrollment(input: OwnerEnrollmentCommitInput): Promise<boolean> {\n\tconst { backend, revision, now, completionSecret, signature } = input;\n\tconst a = Object.freeze({ ...input.row });\n\tconst proof = await verifyOwnerEnrollmentCompletion(\n\t\ta,\n\t\trevision,\n\t\tnow,\n\t\tcompletionSecret,\n\t\tsignature,\n\t);\n\tif (!proof || !(await matchesAdmissionOwner(a))) return false;\n\tconst { grants } = proof;\n\tconst snapshot = await collisionSnapshot(backend, a);\n\tif (snapshot === null) return false;\n\tconst consistency = await prepareEnrollmentNegativeConsistency(backend, a);\n\tif (!consistency) return false;\n\tconst bindingId = globalThis.crypto.randomUUID();\n\tconst eventId = globalThis.crypto.randomUUID();\n\tconst outcome = JSON.stringify({\n\t\tkind: \"finalized\",\n\t\tbindingId,\n\t\tgroups: grants.map((g) => g.groupId),\n\t});\n\tconst winner = [a.coordinator_id, a.attempt_id, bindingId];\n\tconst authority = await readOwnerLinkAuthority(backend, now, {\n\t\tsql: \"l.coordinator_id=? AND l.link_id=?\",\n\t\tvalues: [a.coordinator_id, a.link_id],\n\t});\n\tif (!authority.hasPin && a.owner_qualification_id != null) return false;\n\tconst update = winningUpdate(a, {\n\t\trevision,\n\t\tnow,\n\t\tbindingId,\n\t\teventId,\n\t\toutcome,\n\t\tsnapshot,\n\t\t...proof,\n\t});\n\t// UPDATE FROM keeps the full live-link proof separate from final pins and grants.\n\t// Both stages still evaluate inside this one winning statement in the atomic batch.\n\t// Scope the retained attempt before materialization, not just in the final UPDATE.\n\tupdate.sql = `${authority.with ? `${authority.with},` : \"WITH\"} owner_commit_links AS MATERIALIZED (\n SELECT a.coordinator_id,a.attempt_id FROM coordinator_owner_enrollment_attempts a\n WHERE a.coordinator_id=? AND a.attempt_id=? AND ${authority.active}) ${update.sql\n\t\t.replace(\"loopback_redirect = NULL\", \"loopback_redirect = NULL FROM owner_commit_links p\")\n\t\t.replace(\n\t\t\tOWNER_ACTIVE_LINK_SQL,\n\t\t\t\"p.coordinator_id=a.coordinator_id AND p.attempt_id=a.attempt_id\",\n\t\t)}`;\n\tupdate.values.unshift(...authority.values, a.coordinator_id, a.attempt_id);\n\tif (authority.hasPin) {\n\t\tupdate.sql += \" AND a.owner_qualification_id IS ?\";\n\t\tupdate.values.push(a.owner_qualification_id ?? null);\n\t}\n\tawait backend.batch([\n\t\twithEnrollmentNegativeOwner(update, consistency),\n\t\t...dependentWrites(winner, now, grants.length, consistency),\n\t]);\n\treturn readCommittedOwnerEnrollment(backend, winner);\n}\n\n/** Join the already materialized negative result rather than adding its SELECT\n * tree beneath the UPDATE's long chain of ordinary pins (native D1 depth 100).\n * These markers belong only to this module's trusted winning UPDATE template.\n */\nfunction withEnrollmentNegativeOwner(\n\tupdate: AuthLinkStatement,\n\tconsistency: AuthLinkStatement,\n): AuthLinkStatement {\n\tconst checked = withNegativeOwnerWrite(update, consistency);\n\tconst source = \"FROM owner_commit_links p\";\n\tconst guard = \"AND (SELECT matches FROM negative_owner_consistency)\";\n\tif (!checked.sql.includes(source) || !checked.sql.includes(guard))\n\t\tthrow new Error(\"owner_enrollment_statement_invalid\");\n\treturn {\n\t\tsql: checked.sql\n\t\t\t.replace(source, `${source} CROSS JOIN negative_owner_consistency negative`)\n\t\t\t.replace(guard, \"AND negative.matches\"),\n\t\tvalues: checked.values,\n\t};\n}\n\nasync function readCommittedOwnerEnrollment(backend: AuthLinkBackend, winner: string[]) {\n\tconst committed = await backend.first({\n\t\tsql: `SELECT 1 FROM coordinator_owner_enrollment_attempts WHERE ${WINNER}`,\n\t\tvalues: winner,\n\t});\n\treturn committed !== null;\n}\n\nfunction prepareEnrollmentNegativeConsistency(backend: AuthLinkBackend, a: OwnerAttempt) {\n\treturn prepareNegativeOwnerConsistency(backend, {\n\t\tcoordinatorId: a.coordinator_id,\n\t\townerIdentityId: a.identity_id ?? \"\",\n\t\tdeviceId: a.device_id,\n\t\tpublicKey: a.public_key,\n\t\tfingerprint: a.fingerprint,\n\t});\n}\n\nconst WINNING_UPDATE_SQL = `UPDATE coordinator_owner_enrollment_attempts AS a SET state = 'finalized',\n finalized_at_ms = ?, binding_id = ?, audit_event_id = ?, final_outcome_json = ?,\n final_key_proof_hash = ?, loopback_redirect = NULL\n WHERE a.coordinator_id = ? AND a.attempt_id = ? AND a.purpose = 'owner_enroll'\n AND a.state = 'confirmed' AND a.created_at_ms <= ? AND a.expires_at_ms > ?\n AND a.auth_config_revision = ? AND a.origin = ? AND a.issuer = ?\n AND a.admission_owner_hash IS ?\n AND a.device_id = ? AND a.public_key = ? AND a.key_id = ? AND a.fingerprint = ?\n AND a.browser_start_hash = ? AND a.browser_transaction_hash = ? AND a.browser_binder_hash = ?\n AND a.account_subject = ? AND a.identity_id = ? AND a.link_id = ?\n AND a.link_attempt_id = ? AND a.link_controller_attestation_id IS ? AND a.link_auth_config_revision = ?\n AND a.grant_revisions_json = ? AND a.confirmation_hash = ? AND a.completion_secret_hash = ?\n AND a.loopback_redirect = ? AND a.created_at_ms = ? AND a.expires_at_ms = ?\n AND ${OWNER_ACTIVE_LINK_SQL} AND ${LIVE_GRANTS} AND ${NO_REVOCATION}\n AND NOT EXISTS (SELECT 1 FROM coordinator_device_ownership_bindings b WHERE b.device_id = a.device_id OR b.key_id = a.key_id)\n AND ${SAME_KEYS}`;\nfunction winningPins(a: OwnerAttempt): AuthLinkStatement[\"values\"] {\n\treturn [\n\t\ta.origin,\n\t\ta.issuer,\n\t\ta.admission_owner_hash,\n\t\ta.device_id,\n\t\ta.public_key,\n\t\ta.key_id,\n\t\ta.fingerprint,\n\t\ta.browser_start_hash,\n\t\ta.browser_transaction_hash,\n\t\ta.browser_binder_hash,\n\t\ta.account_subject,\n\t\ta.identity_id,\n\t\ta.link_id,\n\t\ta.link_attempt_id,\n\t\ta.link_controller_attestation_id,\n\t\ta.link_auth_config_revision,\n\t\ta.grant_revisions_json,\n\t\ta.confirmation_hash,\n\t];\n}\nfunction winningUpdate(\n\ta: OwnerAttempt,\n\toptions: {\n\t\trevision: string;\n\t\tnow: number;\n\t\tbindingId: string;\n\t\teventId: string;\n\t\toutcome: string;\n\t\tsnapshot: string;\n\t\tcompletionHash: string;\n\t\tkeyProofHash: string;\n\t},\n): AuthLinkStatement {\n\tconst { revision, now, bindingId, eventId, outcome, snapshot, completionHash, keyProofHash } =\n\t\toptions;\n\treturn {\n\t\tsql: WINNING_UPDATE_SQL,\n\t\tvalues: [\n\t\t\tnow,\n\t\t\tbindingId,\n\t\t\teventId,\n\t\t\toutcome,\n\t\t\tkeyProofHash,\n\t\t\ta.coordinator_id,\n\t\t\ta.attempt_id,\n\t\t\tnow,\n\t\t\tnow,\n\t\t\trevision,\n\t\t\t...winningPins(a),\n\t\t\tcompletionHash,\n\t\t\ta.loopback_redirect,\n\t\t\ta.created_at_ms,\n\t\t\ta.expires_at_ms,\n\t\t\tsnapshot,\n\t\t\tsnapshot,\n\t\t],\n\t};\n}\nfunction dependentWrites(\n\twinner: string[],\n\tnow: number,\n\tgrantCount: number,\n\tconsistency: AuthLinkStatement,\n): AuthLinkStatement[] {\n\tconst binding: AuthLinkStatement = {\n\t\tsql: `INSERT INTO coordinator_device_ownership_bindings\n (device_id,key_id,identity_id,coordinator_id,binding_id,provenance,source_ref,bound_at)\n SELECT device_id,key_id,identity_id,coordinator_id,binding_id,'owner_enrollment',attempt_id,?\n FROM coordinator_owner_enrollment_attempts WHERE ${WINNER} AND changes() = 1`,\n\t\tvalues: [new Date(now).toISOString(), ...winner],\n\t};\n\tconst enrollment: AuthLinkStatement = {\n\t\tsql: `INSERT INTO enrolled_devices (group_id,device_id,public_key,fingerprint,identity_id,enabled,created_at)\n SELECT r.group_id,a.device_id,a.public_key,a.fingerprint,a.identity_id,1,?\n FROM coordinator_owner_enrollment_attempts a JOIN json_each(a.grant_revisions_json) p\n JOIN coordinator_identity_group_grants r ON r.coordinator_id = a.coordinator_id AND r.identity_id = a.identity_id\n AND r.group_id = json_extract(p.value,'$.groupId') AND r.revision = json_extract(p.value,'$.revision')\n JOIN groups g ON g.group_id = r.group_id\n WHERE a.coordinator_id = ? AND a.attempt_id = ? AND a.state = 'finalized' AND a.binding_id = ?\n AND r.status = 'active' AND r.revoked_at IS NULL AND g.archived_at IS NULL`,\n\t\tvalues: [new Date(now).toISOString(), ...winner],\n\t};\n\tconst audit: AuthLinkStatement = {\n\t\tsql: `INSERT INTO coordinator_owner_enrollment_audit_log\n (coordinator_id,event_id,attempt_id,action,binding_id,device_id,created_at_ms)\n SELECT coordinator_id,audit_event_id,attempt_id,'owner_device_enrolled',binding_id,device_id,finalized_at_ms\n FROM coordinator_owner_enrollment_attempts WHERE ${WINNER}`,\n\t\tvalues: winner,\n\t};\n\treturn [\n\t\twithNegativeOwnerWrite(binding, consistency),\n\t\tassertWrite(winner, 1),\n\t\tenrollment,\n\t\tassertWrite(winner, grantCount),\n\t\taudit,\n\t\tassertWrite(winner, 1),\n\t];\n}\n\nconst RECEIPT_SQL = `SELECT 1 FROM coordinator_device_ownership_bindings b\n WHERE b.device_id = ? AND b.key_id = ? AND b.identity_id = ? AND b.coordinator_id = ?\n AND b.binding_id = ? AND b.provenance = 'owner_enrollment' AND b.source_ref = ? AND b.bound_at = ?\n AND EXISTS (SELECT 1 FROM coordinator_owner_enrollment_attempts a\n WHERE a.coordinator_id = b.coordinator_id AND a.attempt_id = b.source_ref AND a.state = 'finalized'\n AND a.binding_id = b.binding_id AND a.device_id = b.device_id AND a.key_id = b.key_id AND a.identity_id = b.identity_id\n AND a.final_outcome_json = ? AND a.finalized_at_ms = ? AND a.audit_event_id = ?\n AND a.grant_revisions_json = ? AND a.public_key = ? AND a.fingerprint = ?\n AND a.purpose = ? AND a.origin = ? AND a.issuer = ? AND a.auth_config_revision = ?\n AND a.admission_owner_hash IS ?\n AND a.account_subject = ? AND a.link_id = ? AND a.link_attempt_id IS ?\n AND a.link_controller_attestation_id IS ? AND a.link_auth_config_revision IS ?\n AND a.browser_start_hash = ? AND a.browser_transaction_hash IS ? AND a.browser_binder_hash IS ?\n AND a.confirmation_hash IS ? AND a.completion_secret_hash IS ? AND a.final_key_proof_hash IS ?\n AND a.created_at_ms = ? AND a.expires_at_ms = ? AND a.loopback_redirect IS ?)\n AND NOT EXISTS (SELECT 1 FROM coordinator_owner_enrollment_audit_log e\n WHERE e.coordinator_id = ? AND (e.attempt_id = ? OR e.event_id = ?) AND\n (e.event_id <> ? OR e.attempt_id <> ? OR e.action <> 'owner_device_enrolled' OR e.binding_id <> ? OR e.device_id <> ? OR e.created_at_ms <> ?))\n AND NOT EXISTS (SELECT 1 FROM enrolled_devices e, json_each(?) g\n WHERE e.group_id = json_extract(g.value,'$.groupId') AND e.device_id = ?\n AND (e.public_key <> ? OR e.fingerprint <> ? OR e.identity_id IS NOT ? OR e.created_at <> ?))`;\nfunction receiptValues(row: OwnerAttempt): AuthLinkStatement[\"values\"] {\n\tconst timestamp = new Date(row.finalized_at_ms as number).toISOString();\n\treturn [\n\t\trow.device_id,\n\t\trow.key_id,\n\t\trow.identity_id,\n\t\trow.coordinator_id,\n\t\trow.binding_id,\n\t\trow.attempt_id,\n\t\ttimestamp,\n\t\trow.final_outcome_json,\n\t\trow.finalized_at_ms,\n\t\trow.audit_event_id,\n\t\trow.grant_revisions_json,\n\t\trow.public_key,\n\t\trow.fingerprint,\n\t\trow.purpose,\n\t\trow.origin,\n\t\trow.issuer,\n\t\trow.auth_config_revision,\n\t\trow.admission_owner_hash,\n\t\trow.account_subject,\n\t\trow.link_id,\n\t\trow.link_attempt_id,\n\t\trow.link_controller_attestation_id,\n\t\trow.link_auth_config_revision,\n\t\trow.browser_start_hash,\n\t\trow.browser_transaction_hash,\n\t\trow.browser_binder_hash,\n\t\trow.confirmation_hash,\n\t\trow.completion_secret_hash,\n\t\trow.final_key_proof_hash,\n\t\trow.created_at_ms,\n\t\trow.expires_at_ms,\n\t\trow.loopback_redirect,\n\t\trow.coordinator_id,\n\t\trow.attempt_id,\n\t\trow.audit_event_id,\n\t\trow.audit_event_id,\n\t\trow.attempt_id,\n\t\trow.binding_id,\n\t\trow.device_id,\n\t\trow.finalized_at_ms,\n\t\trow.grant_revisions_json,\n\t\trow.device_id,\n\t\trow.public_key,\n\t\trow.fingerprint,\n\t\trow.identity_id,\n\t\ttimestamp,\n\t];\n}\n/** Prior writes only; missing enrollment/audit rows are never repaired and revocations are never undone. */\nexport async function readOwnerEnrollmentReceipt(\n\tbackend: AuthLinkBackend,\n\trow: OwnerAttempt,\n): Promise<boolean> {\n\tconst a = Object.freeze({ ...row });\n\tif (!validOwnerEnrollmentReceiptMetadata(a) || !(await matchesAdmissionOwner(a))) return false;\n\tif ((await ownerEnrollmentConfirmationHash(a)) !== a.confirmation_hash) return false;\n\tconst authority = await readOwnerLinkAuthority(backend);\n\tif (!authority.hasPin && a.owner_qualification_id != null) return false;\n\tlet sql = RECEIPT_SQL;\n\tconst values = receiptValues(a);\n\tif (authority.hasPin) {\n\t\tsql += ` AND EXISTS (SELECT 1 FROM coordinator_owner_enrollment_attempts a\n WHERE a.coordinator_id=b.coordinator_id AND a.attempt_id=b.source_ref AND a.owner_qualification_id IS ?)`;\n\t\tvalues.push(a.owner_qualification_id ?? null);\n\t}\n\tconst found = await backend.first({ sql, values });\n\treturn found !== null;\n}\n","import { hasConnectionSessionSchema } from \"./coordinator-account-connection-session.js\";\nimport { CONNECTION_NOT_REVOKED_SQL } from \"./coordinator-account-connection-storage.js\";\nimport type { CoordinatorAuthBrowserConfig } from \"./coordinator-auth-browser-transaction-contract.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport { authAccountLinkProvenanceSql } from \"./coordinator-auth-link-provenance.js\";\nimport { AUTH_SESSION_LIVE_GUARD_SQL } from \"./coordinator-auth-session.js\";\nimport { ownerExcludedLegacyDecisionSql } from \"./coordinator-owner-enrollment-commit.js\";\nimport type { OwnerEnrollmentResolvedOwner } from \"./owner-enrollment-admission.js\";\nimport { readOwnerLinkAuthority } from \"./owner-enrollment-link-authority.js\";\n\nexport const OWNER_ADMISSION_SCHEMA_READY_SQL = `EXISTS (SELECT 1 FROM pragma_table_info('coordinator_owner_enrollment_attempts')\n WHERE name = 'admission_owner_hash') AND (SELECT count(*) FROM sqlite_master\n WHERE type = 'trigger' AND tbl_name = 'coordinator_owner_enrollment_attempts'\n AND name IN ('owner_enrollment_admission_insert','owner_enrollment_admission_update')) = 2`;\n\nexport async function ownerAdmissionSchemaReady(backend: AuthLinkBackend): Promise<boolean> {\n\tconst row = await backend.first<{ ready: number }>({\n\t\tsql: `SELECT (${OWNER_ADMISSION_SCHEMA_READY_SQL}) AS ready`,\n\t\tvalues: [],\n\t});\n\treturn row?.ready === 1;\n}\n\n/** Uses the management session's full database-derived provenance, not a new login shortcut.\n * Alias a supplies the pending device so exclusions are identical to callback/commit.\n * Controller enrollment is historical evidence: its old device need not remain active.\n */\nasync function authoritySql(\n\tbackend: AuthLinkBackend,\n\ttime: number,\n\tcoordinatorId: string,\n\tsessionCookieHash: string,\n) {\n\t// The credential's unique session selects at most one link before any proof work.\n\t// This is only a work scope: the live session and all authority guards still win below.\n\tconst scope = {\n\t\tsql: `l.coordinator_id=? AND l.link_id=(SELECT link_id FROM coordinator_auth_sessions\n WHERE coordinator_id=? AND credential_hash=?)`,\n\t\tvalues: [coordinatorId, coordinatorId, sessionCookieHash],\n\t};\n\tconst connections = await hasConnectionSessionSchema(backend);\n\tconst authority = await readOwnerLinkAuthority(backend, time, scope);\n\treturn {\n\t\tvalues: authority.values,\n\t\t// Isolate the full session provenance from grant/exact-owner/INSERT predicates.\n\t\t// Native D1 counts nested provenance toward its expression-depth limit of 100.\n\t\twith: `${authority.with ? `${authority.with},` : \"WITH\"} owner_admission_proven_links AS MATERIALIZED (\n SELECT l.* FROM owner_scope_links l WHERE ${authAccountLinkProvenanceSql(\"l\", { connections })}),\n owner_admission_links AS MATERIALIZED (\n SELECT l.* FROM owner_admission_proven_links l WHERE ${authority.link}\n ${connections ? `AND (${CONNECTION_NOT_REVOKED_SQL})` : \"\"}),\n owner_admission_sessions AS MATERIALIZED (\n SELECT s.coordinator_id,s.identity_id,s.link_id,s.issuer,s.subject,l.authority_kind,l.controller_attestation_id\n FROM coordinator_auth_sessions s JOIN owner_admission_links l\n ON l.coordinator_id=s.coordinator_id AND l.link_id=s.link_id AND l.identity_id=s.identity_id\n AND l.issuer=s.issuer AND l.subject=s.subject WHERE (${AUTH_SESSION_LIVE_GUARD_SQL}))`,\n\t\tfrom: `FROM (SELECT ? AS coordinator_id,? AS device_id,? AS fingerprint) a\n JOIN owner_admission_sessions s ON s.coordinator_id = a.coordinator_id\n WHERE EXISTS (SELECT 1 FROM coordinator_identity_group_grants r JOIN groups g ON g.group_id = r.group_id\n WHERE r.coordinator_id = s.coordinator_id AND r.identity_id = s.identity_id\n AND r.status = 'active' AND r.revoked_at IS NULL AND g.archived_at IS NULL\n AND NOT ${ownerExcludedLegacyDecisionSql(\"r.group_id\")})`,\n\t};\n}\nfunction sessionValues(config: CoordinatorAuthBrowserConfig, hash: string, time: number) {\n\treturn [config.coordinatorId, hash, config.issuer, config.revision, time, time];\n}\n\nexport async function readOwnerAdmissionAuthority(input: {\n\tbackend: AuthLinkBackend;\n\tconfig: CoordinatorAuthBrowserConfig;\n\tsessionCookieHash: string;\n\ttime: number;\n\tdeviceId: string;\n\tfingerprint: string;\n}): Promise<OwnerEnrollmentResolvedOwner | null> {\n\tconst { backend, config, sessionCookieHash, time, deviceId, fingerprint } = input;\n\tconst authority = await authoritySql(backend, time, config.coordinatorId, sessionCookieHash);\n\tconst row = await backend.first<{\n\t\tidentity_id: string;\n\t\tlink_id: string;\n\t\tissuer: string;\n\t\tsubject: string;\n\t}>({\n\t\tsql: `${authority.with} SELECT s.identity_id,s.link_id,s.issuer,s.subject ${authority.from}`,\n\t\tvalues: [\n\t\t\t...authority.values,\n\t\t\t...sessionValues(config, sessionCookieHash, time),\n\t\t\tconfig.coordinatorId,\n\t\t\tdeviceId,\n\t\t\tfingerprint,\n\t\t],\n\t});\n\treturn row\n\t\t? {\n\t\t\t\tcoordinatorId: config.coordinatorId,\n\t\t\t\tissuer: row.issuer,\n\t\t\t\tsubject: row.subject,\n\t\t\t\tidentityId: row.identity_id,\n\t\t\t\tlinkId: row.link_id,\n\t\t\t}\n\t\t: null;\n}\n\n/** Materialized by the winning INSERT; revocation/config/grant races cannot create a new attempt. */\nexport async function ownerAdmissionSessionGuard(input: {\n\tbackend: AuthLinkBackend;\n\tconfig: CoordinatorAuthBrowserConfig;\n\tsessionCookieHash: string;\n\towner: OwnerEnrollmentResolvedOwner;\n\tdeviceId: string;\n\tfingerprint: string;\n\ttime: number;\n}): Promise<AuthLinkStatement> {\n\tconst { backend, config, sessionCookieHash, owner, deviceId, fingerprint, time } = input;\n\tconst authority = await authoritySql(backend, time, config.coordinatorId, sessionCookieHash);\n\treturn {\n\t\tsql: `${authority.with} SELECT 1 ${authority.from}\n AND s.link_id = ? AND s.identity_id = ? AND s.issuer = ? AND s.subject = ?`,\n\t\tvalues: [\n\t\t\t...authority.values,\n\t\t\t...sessionValues(config, sessionCookieHash, time),\n\t\t\tconfig.coordinatorId,\n\t\t\tdeviceId,\n\t\t\tfingerprint,\n\t\t\towner.linkId,\n\t\t\towner.identityId,\n\t\t\towner.issuer,\n\t\t\towner.subject,\n\t\t],\n\t};\n}\n","import { CoordinatorAuthBrowserTransactions } from \"./coordinator-auth-browser-transaction.js\";\nimport type { CoordinatorAuthBrowserConfig } from \"./coordinator-auth-browser-transaction-contract.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport {\n\ttype AuthLinkBackend,\n\ttype AuthLinkStatement,\n\tauthLinkNow,\n} from \"./coordinator-auth-link.js\";\nimport {\n\tAUTH_LINK_CREATE_WINDOW_MS,\n\tAUTH_LINK_MAX_ACTIVE_PER_DEVICE,\n\tAUTH_LINK_MAX_CREATES_PER_DEVICE_WINDOW,\n\tAUTH_LINK_MAX_UNFINISHED_PER_COORDINATOR,\n} from \"./coordinator-auth-link-contract.js\";\nimport { parseCoordinatorAuthLoopback } from \"./coordinator-auth-loopback.js\";\nimport {\n\tdecodeCoordinatorAuthProof32,\n\thashCoordinatorAuthProofBytes32,\n} from \"./coordinator-auth-proof.js\";\nimport { captureCoordinatorBrowserAuthConfig } from \"./coordinator-browser-auth-config.js\";\nimport {\n\tclearBrowserCookie,\n\treadBrowserCookie,\n\treissueStartCookieAsTransaction,\n} from \"./coordinator-browser-credential.js\";\nimport {\n\ttype BrowserCsrfKey,\n\ttype BrowserCsrfScope,\n\tisBrowserCsrfKey,\n\tissueBrowserCsrfToken,\n} from \"./coordinator-browser-csrf.js\";\nimport { guardBrowserForm } from \"./coordinator-browser-form-guard.js\";\nimport { snapshotBrowserRequest } from \"./coordinator-browser-request.js\";\nimport { readBrowserStartTransaction } from \"./coordinator-browser-start-transaction.js\";\nimport { ed25519KeyId } from \"./coordinator-ed25519-key-id.js\";\nimport {\n\ttype CoordinatorOidcClient,\n\ttype CoordinatorOidcOptions,\n\tcreateCoordinatorOidcClient,\n} from \"./coordinator-oidc.js\";\nimport {\n\tcommitOwnerEnrollment,\n\tOWNER_ACTIVE_LINK_SQL,\n\townerExcludedLegacyDecisionSql,\n\treadOwnerEnrollmentReceipt,\n} from \"./coordinator-owner-enrollment-commit.js\";\nimport {\n\ttype OwnerAuthorityAttempt as OwnerAttempt,\n\townerEnrollmentConfirmationHash,\n\treadGrantPins,\n\tvalidAttemptTime,\n\tverifyOwnerEnrollmentSignature,\n\tverifyPendingKeySignatureAndHashes,\n} from \"./coordinator-owner-enrollment-proof.js\";\nimport {\n\tOWNER_ADMISSION_SCHEMA_READY_SQL,\n\townerAdmissionSessionGuard,\n} from \"./owner-browser-admission-authority.js\";\nimport {\n\tisOwnerEnrollmentAdmissionKey,\n\ttype OwnerEnrollmentAdmissionKey,\n\ttype OwnerEnrollmentResolvedOwner,\n\townerEnrollmentOwnerCommitment,\n\tverifyOwnerEnrollmentAdmission,\n\tverifyOwnerEnrollmentAdmissionV2,\n} from \"./owner-enrollment-admission.js\";\nimport {\n\tcontrollerOwnerLinkAuthority,\n\treadOwnerLinkAuthority,\n} from \"./owner-enrollment-link-authority.js\";\nimport { matchesAdmissionOwner, validAdmissionOwnerHash } from \"./owner-enrollment-owner-pin.js\";\nimport type { InMemoryRequestRateLimiter } from \"./request-rate-limit.js\";\n\nexport interface OwnerEnrollmentStart {\n\tattemptId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tloopbackRedirect: string;\n\tbrowserStartCode: string;\n\tsignature: string;\n}\n/** Trusted internal composition only. Never deserialize resolvedOwner from public request JSON. */\nexport interface OwnerEnrollmentOwnerBoundStartOptions {\n\tadmissionToken: string;\n\tresolvedOwner: OwnerEnrollmentResolvedOwner;\n\t/** Trusted browser composition only; never accepted from signed-start JSON. */\n\tsessionCookieHash?: string;\n}\ninterface OwnerEnrollmentFinalize {\n\tattemptId: string;\n\tcompletionSecret: string;\n\tsignature: string;\n}\nexport type OwnerEnrollmentReceipt = {\n\tkind: \"finalized\" | \"prior_commit\";\n\tbindingId: string;\n\tidentityId: string;\n\tgroups: string[];\n};\nexport type OwnerEnrollmentStartResult =\n\t| { kind: \"rejected\"; error: \"owner_enrollment_unavailable\" | \"owner_enrollment_unknown\" }\n\t| { kind: \"started\"; attemptId: string; expiresAtMs: number }\n\t| { kind: \"browser_claimed\"; authorizationUrl: string; setCookies: string[] }\n\t| { kind: \"verified\"; confirmation: OwnerEnrollmentConfirmation; csrf: string }\n\t| {\n\t\t\tkind: \"confirmed\";\n\t\t\tcompletionSecret: string;\n\t\t\tloopbackRedirect: string;\n\t\t\tconfirmation: OwnerEnrollmentConfirmation;\n\t }\n\t| OwnerEnrollmentReceipt;\ninterface OwnerEnrollmentConfirmation {\n\tattemptId: string;\n\tcoordinatorId: string;\n\torigin: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tkeyId: string;\n\tfingerprint: string;\n\tissuer: string;\n\tsubject: string;\n\tidentityId: string;\n\tlinkId: string;\n\trevision: string;\n\tconfirmationHash: string;\n\tgroups: readonly string[];\n}\ntype StartPin = { coordinatorId: string; origin: string; issuer: string; revision: string };\ninterface OwnerEnrollmentCompositionBase {\n\tpurpose: \"owner_enroll\";\n\tconfig: unknown;\n\tbackend: AuthLinkBackend;\n\tcsrfKey: BrowserCsrfKey;\n\tlimiter: InMemoryRequestRateLimiter;\n\toidcOptions: CoordinatorOidcOptions;\n\tclock?: () => number;\n}\nexport type OwnerEnrollmentComposition = OwnerEnrollmentCompositionBase &\n\t(\n\t\t| { mode: \"local_test\"; admissionKey?: never }\n\t\t| { mode: \"production\"; admissionKey: OwnerEnrollmentAdmissionKey }\n\t);\ntype Context = {\n\tbackend: AuthLinkBackend;\n\tc: CoordinatorAuthBrowserConfig;\n\tpin: StartPin;\n\tcsrfKey: BrowserCsrfKey;\n\tscope: BrowserCsrfScope;\n\tlimiter: InMemoryRequestRateLimiter;\n\tclient: CoordinatorOidcClient;\n\tnow: () => number;\n\tadmissionKey?: OwnerEnrollmentAdmissionKey;\n};\nconst unavailable: OwnerEnrollmentStartResult = Object.freeze({\n\tkind: \"rejected\",\n\terror: \"owner_enrollment_unavailable\",\n});\nconst OWNER_START_CLIENT_LIMIT = 20;\nconst OWNER_MAX_ACTIVE_PER_COORDINATOR = 1000;\nfunction own(value: unknown, name: string): unknown {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error();\n\tconst descriptor = Object.getOwnPropertyDescriptor(value, name);\n\tif (!descriptor || !Object.hasOwn(descriptor, \"value\")) throw new Error();\n\treturn descriptor.value;\n}\nfunction text(value: unknown, maximum: number): string {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\t!value ||\n\t\tvalue.length > maximum ||\n\t\t/[\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(value)\n\t)\n\t\tthrow new Error();\n\treturn value;\n}\nfunction id(value: unknown): string {\n\tif (!isAuthControllerId(value)) throw new Error();\n\treturn value;\n}\nfunction captureStart(value: unknown): OwnerEnrollmentStart {\n\treturn Object.freeze({\n\t\tattemptId: id(own(value, \"attemptId\")),\n\t\tdeviceId: id(own(value, \"deviceId\")),\n\t\tpublicKey: text(own(value, \"publicKey\"), 4096),\n\t\tloopbackRedirect: text(own(value, \"loopbackRedirect\"), 4096),\n\t\tbrowserStartCode: text(own(value, \"browserStartCode\"), 43),\n\t\tsignature: text(own(value, \"signature\"), 86),\n\t});\n}\nfunction captureResolvedOwner(value: unknown): OwnerEnrollmentResolvedOwner {\n\treturn Object.freeze({\n\t\tcoordinatorId: id(own(value, \"coordinatorId\")),\n\t\tissuer: text(own(value, \"issuer\"), 4096),\n\t\tsubject: text(own(value, \"subject\"), 255),\n\t\tidentityId: id(own(value, \"identityId\")),\n\t\tlinkId: id(own(value, \"linkId\")),\n\t});\n}\nexport async function ownerEnrollmentHash(value: string): Promise<string> {\n\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(value));\n\treturn Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\nasync function proofHash(value: string): Promise<string> {\n\tconst bytes = decodeCoordinatorAuthProof32(value);\n\tif (!bytes) throw new Error();\n\treturn hashCoordinatorAuthProofBytes32(bytes);\n}\n/** Pending-key proof only; no account or ownership authority. */\nexport function ownerEnrollmentStartMessage(input: OwnerEnrollmentStart, config: StartPin): string {\n\treturn JSON.stringify([\n\t\t\"codemem-owner-enrollment-start-v1\",\n\t\t\"owner_enroll\",\n\t\tconfig.coordinatorId,\n\t\tconfig.origin,\n\t\tconfig.issuer,\n\t\tconfig.revision,\n\t\tinput.attemptId,\n\t\tinput.deviceId,\n\t\tinput.publicKey,\n\t\tinput.loopbackRedirect,\n\t\tinput.browserStartCode,\n\t]);\n}\nasync function boundary(\n\taction: () => Promise<OwnerEnrollmentStartResult>,\n): Promise<OwnerEnrollmentStartResult> {\n\ttry {\n\t\treturn await action();\n\t} catch {\n\t\treturn { kind: \"rejected\", error: \"owner_enrollment_unknown\" };\n\t}\n}\n\n/** Opt-in server composition. Production requires exact-start admission; local fixtures require custom fetch.\n * Native SQLite atomic batch semantics and schema constraints are required; errors\n * report unknown, never a claim that an attempted commit made no changes.\n */\nfunction captureComposition(input: OwnerEnrollmentComposition) {\n\tconst mode = own(input, \"mode\");\n\tif (\n\t\town(input, \"purpose\") !== \"owner_enroll\" ||\n\t\t![\"local_test\", \"production\"].includes(mode as string)\n\t)\n\t\tthrow new Error();\n\tconst settings = captureCoordinatorBrowserAuthConfig(own(input, \"config\"));\n\tif (settings.kind !== \"enabled\") throw new Error();\n\tconst oidcOptions = captureOwnerOidcOptions(mode, own(input, \"oidcOptions\"));\n\tconst admissionKey = mode === \"production\" ? own(input, \"admissionKey\") : undefined;\n\tif (mode === \"production\" && !isOwnerEnrollmentAdmissionKey(admissionKey)) throw new Error();\n\tconst csrfKey = own(input, \"csrfKey\");\n\tconst limiter = own(input, \"limiter\") as InMemoryRequestRateLimiter;\n\tif (!isBrowserCsrfKey(csrfKey) || typeof limiter?.check !== \"function\") throw new Error();\n\tconst backend = own(input, \"backend\") as AuthLinkBackend;\n\tif (\n\t\t!backend ||\n\t\t![backend.first, backend.run, backend.batch].every((f) => typeof f === \"function\")\n\t)\n\t\tthrow new Error();\n\treturn {\n\t\tmode,\n\t\tsettings,\n\t\tbackend,\n\t\tcsrfKey,\n\t\tlimiter,\n\t\toidcOptions,\n\t\tadmissionKey: admissionKey as OwnerEnrollmentAdmissionKey | undefined,\n\t};\n}\n\nfunction captureOwnerOidcOptions(mode: unknown, value: unknown): CoordinatorOidcOptions {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error();\n\tconst captured: Record<string, unknown> = {};\n\tfor (const name of [\"fetch\", \"timeoutSeconds\"]) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, name);\n\t\tif (descriptor && !Object.hasOwn(descriptor, \"value\")) throw new Error();\n\t\tcaptured[name] = descriptor?.value;\n\t}\n\tconst { fetch, timeoutSeconds } = captured;\n\tif (fetch !== undefined && typeof fetch !== \"function\") throw new Error();\n\tif (mode === \"local_test\" && typeof fetch !== \"function\") throw new Error();\n\tif (\n\t\ttimeoutSeconds !== undefined &&\n\t\t(typeof timeoutSeconds !== \"number\" ||\n\t\t\t!Number.isFinite(timeoutSeconds) ||\n\t\t\ttimeoutSeconds < 1 ||\n\t\t\ttimeoutSeconds > 30)\n\t)\n\t\tthrow new Error();\n\treturn {\n\t\tfetch: fetch as CoordinatorOidcOptions[\"fetch\"],\n\t\ttimeoutSeconds: timeoutSeconds as number | undefined,\n\t};\n}\n\nexport async function createCoordinatorOwnerEnrollment(input: OwnerEnrollmentComposition) {\n\ttry {\n\t\tconst { mode, settings, backend, csrfKey, limiter, oidcOptions, admissionKey } =\n\t\t\tcaptureComposition(input);\n\t\tconst client = await composeOidcClient(mode, settings.oidc, oidcOptions);\n\t\tconst c = settings.store;\n\t\tconst clock = input.clock ?? Date.now;\n\t\tconst context: Context = {\n\t\t\tbackend,\n\t\t\tc,\n\t\t\tclient,\n\t\t\tadmissionKey,\n\t\t\tnow: () => authLinkNow(clock),\n\t\t\tpin: Object.freeze({\n\t\t\t\tcoordinatorId: c.coordinatorId,\n\t\t\t\torigin: settings.publicOrigin,\n\t\t\t\tissuer: c.issuer,\n\t\t\t\trevision: c.revision,\n\t\t\t}),\n\t\t\tscope: Object.freeze({ publicOrigin: settings.publicOrigin, store: c }),\n\t\t\tcsrfKey,\n\t\t\tlimiter,\n\t\t};\n\t\treturn {\n\t\t\tok: true as const,\n\t\t\tenrollment: Object.freeze({\n\t\t\t\t// clientKey must come from the trusted transport, never the signed request body.\n\t\t\t\tstart: (value: OwnerEnrollmentStart, clientKey: string, admissionToken?: string) =>\n\t\t\t\t\tboundary(() =>\n\t\t\t\t\t\tstart(context, value, clientKey, { kind: \"operator\", token: admissionToken }),\n\t\t\t\t\t),\n\t\t\t\t// Unmounted until a separately reviewed authenticated browser issuer exists.\n\t\t\t\tstartOwnerBound: (\n\t\t\t\t\tvalue: OwnerEnrollmentStart,\n\t\t\t\t\tclientKey: string,\n\t\t\t\t\toptions: OwnerEnrollmentOwnerBoundStartOptions,\n\t\t\t\t) => boundary(() => start(context, value, clientKey, { kind: \"owner\", options })),\n\t\t\t\tclaimBrowser: (request: Request, clientKey: string) =>\n\t\t\t\t\tboundary(() => claimBrowser(context, request, clientKey)),\n\t\t\t\tverifyCallback: (request: Request) => boundary(() => verifyCallback(context, request)),\n\t\t\t\tconfirm: (request: Request, clientKey: string, confirmationCommitment: string) =>\n\t\t\t\t\tboundary(() => confirm(context, request, clientKey, confirmationCommitment)),\n\t\t\t\tfinalize: (value: OwnerEnrollmentFinalize) => boundary(() => finalize(context, value)),\n\t\t\t}),\n\t\t};\n\t} catch {\n\t\treturn { ok: false as const };\n\t}\n}\n\nasync function composeOidcClient(\n\tmode: unknown,\n\tconfig: Parameters<typeof createCoordinatorOidcClient>[0],\n\toptions: CoordinatorOidcOptions,\n): Promise<CoordinatorOidcClient> {\n\tif (mode === \"production\") return deferredOidcClient(config, options);\n\tconst result = await createCoordinatorOidcClient(config, options);\n\tif (!result.ok) throw new Error(\"owner_enrollment_oidc_unavailable\");\n\treturn result.client;\n}\n\n/** Discovery is deferred until an eligible browser claim or consumed callback. */\nfunction deferredOidcClient(\n\tconfig: Parameters<typeof createCoordinatorOidcClient>[0],\n\toptions: CoordinatorOidcOptions,\n): CoordinatorOidcClient {\n\tlet settled: CoordinatorOidcClient | undefined;\n\tasync function getClient() {\n\t\tif (settled) return settled;\n\t\tconst result = await createCoordinatorOidcClient(config, options);\n\t\tif (!result.ok) throw new Error(\"owner_enrollment_oidc_unavailable\");\n\t\tsettled ??= result.client;\n\t\treturn settled;\n\t}\n\treturn {\n\t\tcreateAuthorizationRequest: async () => (await getClient()).createAuthorizationRequest(),\n\t\tverifyCallback: async (input, callbackOptions) =>\n\t\t\t(await getClient()).verifyCallback(input, callbackOptions),\n\t};\n}\n\ninterface OwnerBrowserTransaction {\n\tbrowser_transaction_hash: string;\n\tattempt_id: string;\n\tstate_hash: string;\n\tbinder_hash: string;\n\tnonce: string;\n\tpkce_verifier: string;\n\tcreated_at_ms: number;\n\texpires_at_ms: number;\n}\ninterface ConsumedOwnerBrowser {\n\ttxn: OwnerBrowserTransaction;\n\trow: OwnerAttempt;\n\tclaimToken: string;\n}\nasync function verifyCallback(\n\tcontext: Context,\n\trequest: Request,\n): Promise<OwnerEnrollmentStartResult> {\n\tconst snapshot = snapshotBrowserRequest(request);\n\tif (snapshot.method !== \"GET\" || snapshot.url.length > 8192 || snapshot.url.includes(\"#\"))\n\t\treturn unavailable;\n\tconst url = new URL(snapshot.url);\n\tconst redirect = new URL(context.c.redirectUri);\n\tconst states = url.searchParams.getAll(\"state\");\n\tif (\n\t\turl.origin !== redirect.origin ||\n\t\turl.pathname !== redirect.pathname ||\n\t\turl.username ||\n\t\turl.password ||\n\t\tstates.length !== 1 ||\n\t\t!/^[A-Za-z0-9._~-]{43,128}$/.test(states[0] ?? \"\")\n\t)\n\t\treturn unavailable;\n\tconst state = states[0] as string;\n\tconst cookie = await readBrowserCookie(snapshot.cookie, \"transaction\");\n\tif (cookie.kind !== \"present\") return unavailable;\n\tconst consumed = await consumeOwnerBrowser(context, state, cookie.cookieHash);\n\tif (!consumed) return unavailable;\n\t// Capture the original material before burning it; the maintained client verifies\n\t// ID-token signatures, issuer, nonce and PKCE. No browser session supplies identity.\n\tconst verified = await context.client.verifyCallback(\n\t\t{\n\t\t\tcallbackUrl: snapshot.url,\n\t\t\tmaterial: { state, nonce: consumed.txn.nonce, pkceVerifier: consumed.txn.pkce_verifier },\n\t\t},\n\t\t{ fetchUserInfo: false },\n\t);\n\tif (!verified.ok || verified.account.issuer !== context.c.issuer) return unavailable;\n\tconst row = await persistVerified(context, consumed, verified.account);\n\tif (!row) return unavailable;\n\tconst confirmation = await confirmationView(row);\n\tconst csrf = await issueBrowserCsrfToken(\n\t\tcontext.csrfKey,\n\t\tcookie.secret,\n\t\t\"transaction\",\n\t\tcontext.scope,\n\t);\n\treturn { kind: \"verified\", confirmation, csrf };\n}\nfunction ownerAttemptSql(state: \"browser_claimed\" | \"oidc_verified\"): string {\n\treturn `a.coordinator_id = ? AND a.attempt_id = ? AND a.purpose = 'owner_enroll'\n AND a.state = '${state}' AND a.origin = ? AND a.issuer = ? AND a.auth_config_revision = ?\n AND a.browser_transaction_hash = ? AND a.browser_binder_hash = ?\n AND a.device_id = ? AND a.public_key = ? AND a.key_id = ? AND a.fingerprint = ?\n AND a.browser_start_hash = ? AND a.loopback_redirect = ? AND a.created_at_ms = ? AND a.expires_at_ms = ?\n AND a.admission_owner_hash IS ?\n AND ${OWNER_ADMISSION_SCHEMA_READY_SQL}\n AND a.created_at_ms <= ? AND a.expires_at_ms > ?`;\n}\nfunction callbackAttemptValues(\n\tcontext: Context,\n\ta: OwnerAttempt,\n\ttime: number,\n): AuthLinkStatement[\"values\"] {\n\treturn [\n\t\tcontext.c.coordinatorId,\n\t\ta.attempt_id,\n\t\tcontext.pin.origin,\n\t\tcontext.c.issuer,\n\t\tcontext.c.revision,\n\t\ta.browser_transaction_hash,\n\t\ta.browser_binder_hash,\n\t\ta.device_id,\n\t\ta.public_key,\n\t\ta.key_id,\n\t\ta.fingerprint,\n\t\ta.browser_start_hash,\n\t\ta.loopback_redirect,\n\t\ta.created_at_ms,\n\t\ta.expires_at_ms,\n\t\ta.admission_owner_hash,\n\t\ttime,\n\t\ttime,\n\t];\n}\nconst CALLBACK_TXN_SQL = `b.coordinator_id = ? AND b.browser_transaction_hash = ? AND b.purpose = 'owner_enroll'\n AND b.attempt_id = ? AND b.state_hash = ? AND b.binder_hash = ? AND b.issuer = ?\n AND b.auth_config_revision = ? AND b.redirect_uri = ? AND b.created_at_ms = ? AND b.expires_at_ms = ?\n AND b.created_at_ms <= ? AND b.expires_at_ms > ?`;\nfunction callbackTxnValues(\n\tcontext: Context,\n\tb: OwnerBrowserTransaction,\n\ttime: number,\n): AuthLinkStatement[\"values\"] {\n\treturn [\n\t\tcontext.c.coordinatorId,\n\t\tb.browser_transaction_hash,\n\t\tb.attempt_id,\n\t\tb.state_hash,\n\t\tb.binder_hash,\n\t\tcontext.c.issuer,\n\t\tcontext.c.revision,\n\t\tcontext.c.redirectUri,\n\t\tb.created_at_ms,\n\t\tb.expires_at_ms,\n\t\ttime,\n\t\ttime,\n\t];\n}\nasync function consumeOwnerBrowser(\n\tcontext: Context,\n\tstate: string,\n\tbinderHash: string,\n): Promise<ConsumedOwnerBrowser | null> {\n\tconst time = context.now();\n\tconst txn = await context.backend.first<OwnerBrowserTransaction>({\n\t\tsql: `SELECT * FROM coordinator_auth_browser_transactions WHERE coordinator_id = ?\n AND purpose = 'owner_enroll' AND state_hash = ? AND binder_hash = ? AND state = 'pending'\n AND issuer = ? AND auth_config_revision = ? AND redirect_uri = ? AND created_at_ms <= ? AND expires_at_ms > ?`,\n\t\tvalues: [\n\t\t\tcontext.c.coordinatorId,\n\t\t\tawait ownerEnrollmentHash(state),\n\t\t\tbinderHash,\n\t\t\tcontext.c.issuer,\n\t\t\tcontext.c.revision,\n\t\t\tcontext.c.redirectUri,\n\t\t\ttime,\n\t\t\ttime,\n\t\t],\n\t});\n\tif (!txn) return null;\n\tconst row = await readAttempt(context, txn.attempt_id);\n\tif (\n\t\t!live(context, row, time) ||\n\t\trow.state !== \"browser_claimed\" ||\n\t\trow.browser_transaction_hash !== txn.browser_transaction_hash ||\n\t\trow.browser_binder_hash !== binderHash ||\n\t\trow.expires_at_ms !== txn.expires_at_ms ||\n\t\ttxn.created_at_ms < row.created_at_ms\n\t)\n\t\treturn null;\n\tconst claimToken = globalThis.crypto.randomUUID();\n\tconst burnTime = context.now();\n\tconst wrote = await context.backend.run({\n\t\tsql: `UPDATE coordinator_auth_browser_transactions AS b SET state = 'consumed',claim_token = ?,\n consumed_at_ms = ?,nonce = NULL,pkce_verifier = NULL WHERE ${CALLBACK_TXN_SQL}\n AND b.state = 'pending' AND b.nonce = ? AND b.pkce_verifier = ?\n AND EXISTS (SELECT 1 FROM coordinator_owner_enrollment_attempts a WHERE ${ownerAttemptSql(\"browser_claimed\")})`,\n\t\tvalues: [\n\t\t\tclaimToken,\n\t\t\tburnTime,\n\t\t\t...callbackTxnValues(context, txn, burnTime),\n\t\t\ttxn.nonce,\n\t\t\ttxn.pkce_verifier,\n\t\t\t...callbackAttemptValues(context, row, burnTime),\n\t\t],\n\t});\n\treturn wrote === 1 ? { txn, row, claimToken } : null;\n}\ninterface OwnerAccountLink {\n\tlink_id: string;\n\tidentity_id: string;\n\tattempt_id: string;\n\tcontroller_attestation_id: string | null;\n\towner_qualification_id: string | null;\n\tauth_config_revision: string;\n\tcreated_at_ms: number;\n\tauthority_kind: string;\n\tdevice_claim_id: string | null;\n}\n// Filter each Team before pinning; the winning update repeats this exact snapshot.\nconst CALLBACK_GRANTS_SQL = `SELECT json_group_array(json_object('groupId',groupId,'revision',revision)) FROM\n (SELECT r.group_id AS groupId,r.revision AS revision FROM coordinator_identity_group_grants r\n JOIN groups g ON g.group_id = r.group_id WHERE r.coordinator_id = a.coordinator_id AND r.identity_id = ?\n AND r.status = 'active' AND r.revoked_at IS NULL AND g.archived_at IS NULL\n AND NOT ${ownerExcludedLegacyDecisionSql(\"r.group_id\")} ORDER BY r.group_id LIMIT 51)`;\nasync function persistVerified(\n\tcontext: Context,\n\tconsumed: ConsumedOwnerBrowser,\n\taccount: { issuer: string; subject: string },\n): Promise<OwnerAttempt | null> {\n\tconst candidate = await context.backend.first<OwnerAccountLink>({\n\t\tsql: `SELECT l.*,NULL AS owner_qualification_id FROM coordinator_auth_account_links l WHERE l.coordinator_id = ? AND l.issuer = ? AND l.subject = ? AND l.revoked_at_ms IS NULL`,\n\t\tvalues: [context.c.coordinatorId, account.issuer, account.subject],\n\t});\n\tif (!candidate) return null;\n\tconst resolved = await callbackLinkAuthority(context, consumed.row, candidate);\n\tif (!resolved) return null;\n\tconst { link, authority } = resolved;\n\tif (\n\t\t!(await matchesAdmissionOwner({\n\t\t\t...consumed.row,\n\t\t\tissuer: account.issuer,\n\t\t\taccount_subject: account.subject,\n\t\t\tidentity_id: link.identity_id,\n\t\t\tlink_id: link.link_id,\n\t\t}))\n\t)\n\t\treturn null;\n\tconst grants = await context.backend.first<{ rows: string }>({\n\t\tsql: `SELECT (${CALLBACK_GRANTS_SQL}) AS rows FROM coordinator_owner_enrollment_attempts a\n WHERE ${ownerAttemptSql(\"browser_claimed\")}`,\n\t\tvalues: [link.identity_id, ...callbackAttemptValues(context, consumed.row, context.now())],\n\t});\n\tif (!grants || !readGrantPins(grants.rows)) return null;\n\tconst time = context.now();\n\tconst wrote = await context.backend.run(\n\t\tverifiedStatement(context, consumed, account, link, grants.rows, time, authority),\n\t);\n\tif (wrote !== 1) return null;\n\tconst row = await readAttempt(context, consumed.row.attempt_id);\n\t// A missing or changed post-write read is unknown, not evidence the write failed.\n\tif (\n\t\trow?.state !== \"oidc_verified\" ||\n\t\trow.admission_owner_hash !== consumed.row.admission_owner_hash ||\n\t\trow.link_id !== link.link_id ||\n\t\t(row.owner_qualification_id ?? null) !== link.owner_qualification_id ||\n\t\trow.link_controller_attestation_id !== link.controller_attestation_id ||\n\t\trow.account_subject !== account.subject ||\n\t\trow.grant_revisions_json !== grants.rows ||\n\t\trow.browser_transaction_hash !== consumed.txn.browser_transaction_hash ||\n\t\trow.browser_binder_hash !== consumed.txn.binder_hash\n\t)\n\t\tthrow new Error();\n\treturn row;\n}\nasync function callbackLinkAuthority(\n\tcontext: Context,\n\tattempt: OwnerAttempt,\n\tlink: OwnerAccountLink,\n) {\n\tconst scope = {\n\t\tsql: \"l.coordinator_id=? AND l.link_id=?\",\n\t\tvalues: [context.c.coordinatorId, link.link_id],\n\t};\n\tif (\n\t\tlink.authority_kind === \"controller_attestation\" &&\n\t\tisAuthControllerId(link.controller_attestation_id) &&\n\t\tlink.device_claim_id === null\n\t)\n\t\treturn { authority: controllerOwnerLinkAuthority(attempt, scope), link };\n\tif (\n\t\tlink.authority_kind !== \"device_claim\" ||\n\t\tlink.controller_attestation_id !== null ||\n\t\t!isAuthControllerId(link.device_claim_id)\n\t)\n\t\treturn null;\n\tconst authority = await readOwnerLinkAuthority(context.backend, context.now(), scope);\n\tconst qualified = await context.backend.first<{ owner_qualification_id: string | null }>({\n\t\tsql: `${authority.with}SELECT ${authority.qualification} AS owner_qualification_id\n FROM owner_scope_links l WHERE l.coordinator_id=? AND l.link_id=?\n AND l.revoked_at_ms IS NULL AND ${authority.link}`,\n\t\tvalues: [...authority.values, context.c.coordinatorId, link.link_id],\n\t});\n\tif (!qualified?.owner_qualification_id) return null;\n\treturn { authority, link: { ...link, owner_qualification_id: qualified.owner_qualification_id } };\n}\nfunction verifiedStatement(\n\tcontext: Context,\n\tconsumed: ConsumedOwnerBrowser,\n\taccount: { issuer: string; subject: string },\n\tlink: OwnerAccountLink,\n\tgrants: string,\n\ttime: number,\n\tauthority: Awaited<ReturnType<typeof readOwnerLinkAuthority>>,\n): AuthLinkStatement {\n\t// Keep consumed-browser proof and link provenance in separate native D1 depth trees.\n\treturn {\n\t\tsql: `${authority.with ? `${authority.with},` : \"WITH\"} owner_callback_attempts AS MATERIALIZED (\n SELECT a.coordinator_id,a.attempt_id FROM coordinator_owner_enrollment_attempts a\n WHERE ${ownerAttemptSql(\"browser_claimed\")}\n AND EXISTS (SELECT 1 FROM coordinator_auth_browser_transactions b WHERE ${CALLBACK_TXN_SQL}\n AND b.state = 'consumed' AND b.claim_token = ? AND b.nonce IS NULL AND b.pkce_verifier IS NULL)),\n owner_callback_links AS MATERIALIZED (\n SELECT l.*,${authority.qualification} AS owner_qualification_id FROM owner_scope_links l\n WHERE ${authority.link})\n UPDATE coordinator_owner_enrollment_attempts AS a SET state = 'oidc_verified',\n account_subject = ?,identity_id = ?,link_id = ?,link_attempt_id = ?,link_controller_attestation_id = ?,\n ${authority.hasPin ? \"owner_qualification_id = ?,\" : \"\"}link_auth_config_revision = ?,grant_revisions_json = ?\n WHERE a.coordinator_id=? AND a.attempt_id=?\n AND EXISTS (SELECT 1 FROM owner_callback_attempts p WHERE p.coordinator_id=a.coordinator_id AND p.attempt_id=a.attempt_id)\n AND EXISTS (SELECT 1 FROM owner_callback_links l WHERE l.coordinator_id = a.coordinator_id\n AND l.link_id = ? AND l.issuer = a.issuer AND l.subject = ? AND l.identity_id = ? AND l.attempt_id = ?\n AND l.controller_attestation_id IS ? AND l.owner_qualification_id IS ? AND l.auth_config_revision = ? AND l.created_at_ms = ? AND l.revoked_at_ms IS NULL)\n AND (${CALLBACK_GRANTS_SQL}) = ?\n AND ${NO_COLLISION_SQL}`,\n\t\tvalues: [\n\t\t\t...authority.values,\n\t\t\t...callbackAttemptValues(context, consumed.row, time),\n\t\t\t...callbackTxnValues(context, consumed.txn, time),\n\t\t\tconsumed.claimToken,\n\t\t\taccount.subject,\n\t\t\tlink.identity_id,\n\t\t\tlink.link_id,\n\t\t\tlink.attempt_id,\n\t\t\tlink.controller_attestation_id,\n\t\t\t...(authority.hasPin ? [link.owner_qualification_id] : []),\n\t\t\tlink.auth_config_revision,\n\t\t\tgrants,\n\t\t\tconsumed.row.coordinator_id,\n\t\t\tconsumed.row.attempt_id,\n\t\t\tlink.link_id,\n\t\t\taccount.subject,\n\t\t\tlink.identity_id,\n\t\t\tlink.attempt_id,\n\t\t\tlink.controller_attestation_id,\n\t\t\tlink.owner_qualification_id,\n\t\t\tlink.auth_config_revision,\n\t\t\tlink.created_at_ms,\n\t\t\tlink.identity_id,\n\t\t\tgrants,\n\t\t\tconsumed.row.device_id,\n\t\t\tconsumed.row.key_id,\n\t\t\tconsumed.row.device_id,\n\t\t\tconsumed.row.key_id,\n\t\t],\n\t};\n}\nasync function confirmationView(row: OwnerAttempt): Promise<OwnerEnrollmentConfirmation> {\n\tif (!row.account_subject || !row.identity_id || !row.link_id) throw new Error();\n\tif (!(await matchesAdmissionOwner(row))) throw new Error();\n\tconst grants = readGrantPins(row.grant_revisions_json);\n\tif (!grants) throw new Error();\n\t// Display commitment; confirm() persists it with the completion-secret hash.\n\tconst confirmationHash = await ownerEnrollmentConfirmationHash(row);\n\treturn Object.freeze({\n\t\tattemptId: row.attempt_id,\n\t\tcoordinatorId: row.coordinator_id,\n\t\torigin: row.origin,\n\t\tdeviceId: row.device_id,\n\t\tpublicKey: row.public_key,\n\t\tkeyId: row.key_id,\n\t\tfingerprint: row.fingerprint,\n\t\tissuer: row.issuer,\n\t\tsubject: row.account_subject,\n\t\tidentityId: row.identity_id,\n\t\tlinkId: row.link_id,\n\t\trevision: row.auth_config_revision,\n\t\tconfirmationHash,\n\t\tgroups: Object.freeze(grants.map((grant) => grant.groupId)),\n\t});\n}\n\n// Both the preflight read and winning update require the consumed transaction,\n// exact linked account provenance, and the same active grant snapshot shown to the user.\nconst CONFIRM_AUTHORITY_SQL = `${OWNER_ACTIVE_LINK_SQL}\n AND (${CALLBACK_GRANTS_SQL}) = a.grant_revisions_json\n AND NOT EXISTS (SELECT 1 FROM json_each(a.grant_revisions_json) p WHERE ${ownerExcludedLegacyDecisionSql(\"json_extract(p.value,'$.groupId')\")})\n AND EXISTS (SELECT 1 FROM coordinator_auth_browser_transactions b\n WHERE b.coordinator_id = a.coordinator_id AND b.attempt_id = a.attempt_id AND b.purpose = 'owner_enroll'\n AND b.browser_transaction_hash = a.browser_transaction_hash AND b.binder_hash = a.browser_binder_hash\n AND b.issuer = a.issuer AND b.auth_config_revision = a.auth_config_revision AND b.redirect_uri = ?\n AND b.state = 'consumed' AND b.claim_token IS NOT NULL AND b.nonce IS NULL AND b.pkce_verifier IS NULL\n AND b.created_at_ms >= a.created_at_ms AND b.created_at_ms <= ?\n AND b.expires_at_ms = a.expires_at_ms)`;\nfunction confirmAuthorityValues(context: Context, row: OwnerAttempt, time: number) {\n\treturn [row.coordinator_id, row.attempt_id, row.identity_id, context.c.redirectUri, time];\n}\nfunction confirmAuthorityCte(authority: Awaited<ReturnType<typeof readOwnerLinkAuthority>>) {\n\t// JOIN/UPDATE FROM consumes this stage without nesting its proof under attempt pins.\n\treturn `${authority.with ? `${authority.with},` : \"WITH\"} owner_confirm_authority AS MATERIALIZED (\n SELECT a.coordinator_id,a.attempt_id FROM coordinator_owner_enrollment_attempts a\n WHERE a.coordinator_id=? AND a.attempt_id=?\n AND ${CONFIRM_AUTHORITY_SQL.replace(OWNER_ACTIVE_LINK_SQL, authority.active)}) `;\n}\nconst CONFIRM_AUTHORITY_MATCH_SQL = `p.coordinator_id=a.coordinator_id AND p.attempt_id=a.attempt_id`;\nasync function confirmationLinkAuthority(context: Context, row: OwnerAttempt, time: number) {\n\tconst scope = {\n\t\tsql: \"l.coordinator_id=? AND l.link_id=?\",\n\t\tvalues: [row.coordinator_id, row.link_id],\n\t};\n\tconst hasQualificationPin = Object.hasOwn(row, \"owner_qualification_id\");\n\tif (isAuthControllerId(row.link_controller_attestation_id)) {\n\t\tif (hasQualificationPin && row.owner_qualification_id !== null) throw new Error();\n\t\tconst authority = controllerOwnerLinkAuthority(row, scope);\n\t\tif (hasQualificationPin) return authority;\n\t\t// A legacy snapshot cannot skip qualification pins added before either SQL executes.\n\t\treturn {\n\t\t\t...authority,\n\t\t\tactive: `(${authority.active} AND NOT EXISTS (SELECT 1 FROM pragma_table_info('coordinator_owner_enrollment_attempts') WHERE name='owner_qualification_id'))`,\n\t\t};\n\t}\n\tif (\n\t\trow.link_controller_attestation_id !== null ||\n\t\t!hasQualificationPin ||\n\t\ttypeof row.owner_qualification_id !== \"string\"\n\t)\n\t\tthrow new Error();\n\tconst authority = await readOwnerLinkAuthority(context.backend, time, scope);\n\tif (!authority.hasPin) throw new Error();\n\treturn authority;\n}\nasync function readConfirmableAttempt(\n\tcontext: Context,\n\tattemptId: string,\n\tbinderHash: string,\n): Promise<OwnerAttempt | null> {\n\tconst row = await context.backend.first<OwnerAttempt>({\n\t\tsql: `SELECT * FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = ?\n AND attempt_id = ? AND purpose = 'owner_enroll' AND state = 'oidc_verified' AND browser_binder_hash = ?\n AND ${OWNER_ADMISSION_SCHEMA_READY_SQL}`,\n\t\tvalues: [context.c.coordinatorId, attemptId, binderHash],\n\t});\n\tconst time = context.now();\n\tif (!live(context, row, time) || !row.browser_transaction_hash || !row.loopback_redirect)\n\t\treturn null;\n\tif (!parseCoordinatorAuthLoopback(row.loopback_redirect).ok) return null;\n\tconst authority = await confirmationLinkAuthority(context, row, time);\n\tconst current = await context.backend.first({\n\t\tsql: `${confirmAuthorityCte(authority)}SELECT 1 FROM coordinator_owner_enrollment_attempts a\n JOIN owner_confirm_authority p ON ${CONFIRM_AUTHORITY_MATCH_SQL} WHERE\n ${ownerAttemptSql(\"oidc_verified\")}`,\n\t\tvalues: [\n\t\t\t...authority.values,\n\t\t\t...confirmAuthorityValues(context, row, time),\n\t\t\t...callbackAttemptValues(context, row, time),\n\t\t],\n\t});\n\treturn current ? row : null;\n}\nasync function confirm(\n\tcontext: Context,\n\trequest: Request,\n\tclientKey: string,\n\tconfirmationCommitment: string,\n): Promise<OwnerEnrollmentStartResult> {\n\tconst snapshot = snapshotBrowserRequest(request);\n\tconst checked = await guardBrowserForm({\n\t\trequest,\n\t\tclientKey,\n\t\taction: \"transaction_attempt\",\n\t\tscope: context.scope,\n\t\tcsrfKey: context.csrfKey,\n\t\tlimiter: context.limiter,\n\t});\n\tif (!checked.ok || checked.action !== \"transaction_attempt\") return unavailable;\n\tconst cookie = await readBrowserCookie(snapshot.cookie, \"transaction\");\n\tif (cookie.kind !== \"present\" || cookie.cookieHash !== checked.cookieHash) return unavailable;\n\tconst row = await readConfirmableAttempt(context, checked.attemptId, cookie.cookieHash);\n\tif (!row?.loopback_redirect) return unavailable;\n\tconst confirmation = await confirmationView(row);\n\tif (confirmationCommitment !== confirmation.confirmationHash) return unavailable;\n\tconst completionSecret = mintCompletionSecret();\n\tconst completionHash = await proofHash(completionSecret);\n\tconst time = context.now();\n\tconst wrote = await context.backend.run(\n\t\tawait confirmStatement(context, row, {\n\t\t\tconfirmationHash: confirmation.confirmationHash,\n\t\t\tcompletionHash,\n\t\t\ttime,\n\t\t}),\n\t);\n\tif (wrote !== 1) return unavailable;\n\treturn {\n\t\tkind: \"confirmed\",\n\t\tcompletionSecret,\n\t\tloopbackRedirect: row.loopback_redirect,\n\t\tconfirmation,\n\t};\n}\nfunction mintCompletionSecret(): string {\n\tconst bytes = globalThis.crypto.getRandomValues(new Uint8Array(32));\n\treturn btoa(String.fromCharCode(...bytes))\n\t\t.replaceAll(\"+\", \"-\")\n\t\t.replaceAll(\"/\", \"_\")\n\t\t.replace(/=+$/, \"\");\n}\nasync function confirmStatement(\n\tcontext: Context,\n\ta: OwnerAttempt,\n\tp: { confirmationHash: string; completionHash: string; time: number },\n): Promise<AuthLinkStatement> {\n\tconst authority = await confirmationLinkAuthority(context, a, p.time);\n\treturn {\n\t\tsql: `${confirmAuthorityCte(authority)}UPDATE coordinator_owner_enrollment_attempts AS a SET state = 'confirmed',\n confirmation_hash = ?,completion_secret_hash = ? FROM owner_confirm_authority p WHERE\n ${ownerAttemptSql(\"oidc_verified\")}\n AND a.account_subject = ? AND a.identity_id = ? AND a.link_id = ? AND a.link_attempt_id = ?\n AND a.link_controller_attestation_id IS ? ${authority.hasPin ? \"AND a.owner_qualification_id IS ?\" : \"\"} AND a.link_auth_config_revision = ? AND a.grant_revisions_json = ?\n AND a.confirmation_hash IS NULL AND a.completion_secret_hash IS NULL\n AND ${CONFIRM_AUTHORITY_MATCH_SQL} AND ${NO_COLLISION_SQL}`,\n\t\tvalues: [\n\t\t\t...authority.values,\n\t\t\t...confirmAuthorityValues(context, a, p.time),\n\t\t\tp.confirmationHash,\n\t\t\tp.completionHash,\n\t\t\t...callbackAttemptValues(context, a, p.time),\n\t\t\ta.account_subject,\n\t\t\ta.identity_id,\n\t\t\ta.link_id,\n\t\t\ta.link_attempt_id,\n\t\t\ta.link_controller_attestation_id,\n\t\t\t...(authority.hasPin ? [a.owner_qualification_id ?? null] : []),\n\t\t\ta.link_auth_config_revision,\n\t\t\ta.grant_revisions_json,\n\t\t\ta.device_id,\n\t\t\ta.key_id,\n\t\t\ta.device_id,\n\t\t\ta.key_id,\n\t\t],\n\t};\n}\nfunction captureFinalize(value: unknown): OwnerEnrollmentFinalize {\n\treturn Object.freeze({\n\t\tattemptId: id(own(value, \"attemptId\")),\n\t\tcompletionSecret: text(own(value, \"completionSecret\"), 43),\n\t\tsignature: text(own(value, \"signature\"), 86),\n\t});\n}\nfunction matchesFinalScope(context: Context, row: OwnerAttempt | null): row is OwnerAttempt {\n\treturn (\n\t\t!!row &&\n\t\trow.purpose === \"owner_enroll\" &&\n\t\trow.coordinator_id === context.c.coordinatorId &&\n\t\trow.origin === context.pin.origin &&\n\t\trow.issuer === context.c.issuer &&\n\t\tvalidAdmissionOwnerHash(row.admission_owner_hash) &&\n\t\t// A committed receipt is historical evidence; only a new commit needs the live revision.\n\t\t(row.state === \"finalized\" || row.auth_config_revision === context.c.revision) &&\n\t\t!!row.confirmation_hash\n\t);\n}\nasync function finalize(\n\tcontext: Context,\n\tvalue: OwnerEnrollmentFinalize,\n): Promise<OwnerEnrollmentStartResult> {\n\tlet i: OwnerEnrollmentFinalize;\n\ttry {\n\t\ti = captureFinalize(value);\n\t} catch {\n\t\treturn unavailable;\n\t}\n\tconst row = await readAttempt(context, i.attemptId);\n\tif (!matchesFinalScope(context, row)) return unavailable;\n\tconst proof = await verifyPendingKeySignatureAndHashes(row, i.completionSecret, i.signature);\n\tif (!proof || proof.completionHash !== row.completion_secret_hash) return unavailable;\n\tif (row.state === \"finalized\") return priorCommit(context, row, proof);\n\tconst time = context.now();\n\tif (!live(context, row, time) || row.state !== \"confirmed\") return unavailable;\n\tif ((await confirmationView(row)).confirmationHash !== row.confirmation_hash) return unavailable;\n\tconst committed = await commitOwnerEnrollment({\n\t\tbackend: context.backend,\n\t\trow,\n\t\trevision: context.c.revision,\n\t\tnow: time,\n\t\tcompletionSecret: i.completionSecret,\n\t\tsignature: i.signature,\n\t});\n\treturn readFinalOutcome(context, i, { committed });\n}\nasync function readFinalOutcome(\n\tcontext: Context,\n\ti: OwnerEnrollmentFinalize,\n\toptions: { committed: boolean },\n): Promise<OwnerEnrollmentStartResult> {\n\tconst fresh = await readAttempt(context, i.attemptId);\n\t// A failed/missing post-commit read never proves rollback or successful completion.\n\tif (!fresh) throw new Error();\n\tif (!matchesFinalScope(context, fresh) || fresh.state !== \"finalized\") {\n\t\tif (options.committed) throw new Error();\n\t\treturn unavailable;\n\t}\n\tconst proof = await verifyPendingKeySignatureAndHashes(fresh, i.completionSecret, i.signature);\n\tif (!proof || !(await matchesReceipt(context, fresh, proof))) throw new Error();\n\tif (!options.committed) return receipt(fresh, \"prior_commit\");\n\treturn receipt(fresh, \"finalized\");\n}\ntype FinalProof = { completionHash: string; keyProofHash: string };\nasync function matchesReceipt(context: Context, row: OwnerAttempt, proof: FinalProof) {\n\treturn (\n\t\trow.completion_secret_hash === proof.completionHash &&\n\t\trow.final_key_proof_hash === proof.keyProofHash &&\n\t\t(await readOwnerEnrollmentReceipt(context.backend, row))\n\t);\n}\nasync function priorCommit(\n\tcontext: Context,\n\trow: OwnerAttempt,\n\tproof: FinalProof,\n): Promise<OwnerEnrollmentStartResult> {\n\tif (!(await matchesReceipt(context, row, proof))) return unavailable;\n\treturn receipt(row, \"prior_commit\");\n}\nfunction receipt(row: OwnerAttempt, kind: \"finalized\" | \"prior_commit\"): OwnerEnrollmentReceipt {\n\tconst grants = readGrantPins(row.grant_revisions_json);\n\tif (!grants || !row.binding_id || !isAuthControllerId(row.identity_id)) throw new Error();\n\treturn {\n\t\tkind,\n\t\tbindingId: row.binding_id,\n\t\tidentityId: row.identity_id,\n\t\tgroups: grants.map((grant) => grant.groupId),\n\t};\n}\nconst NO_COLLISION_SQL = `NOT EXISTS (SELECT 1 FROM coordinator_device_ownership_bindings WHERE device_id = ? OR key_id = ?)\n AND NOT EXISTS (SELECT 1 FROM coordinator_device_revocations WHERE (subject_kind = 'device_id' AND subject_value = ?)\n OR (subject_kind = 'ed25519_key' AND subject_value = ?))`;\nasync function start(\n\tcontext: Context,\n\tvalue: OwnerEnrollmentStart,\n\tclientKey: string,\n\tadmissionInput:\n\t\t| { kind: \"operator\"; token?: string }\n\t\t| { kind: \"owner\"; options: OwnerEnrollmentOwnerBoundStartOptions },\n): Promise<OwnerEnrollmentStartResult> {\n\t// Capture both the signed start and server-resolved owner before any async work.\n\tconst captured = captureStartInputs(value, admissionInput);\n\tif (!isAuthControllerId(clientKey) || clientKey.length > 128) return unavailable;\n\tconst admission = context.limiter.check(\n\t\tJSON.stringify([\"owner-enrollment-start\", context.c.coordinatorId, clientKey]),\n\t\tOWNER_START_CLIENT_LIMIT,\n\t);\n\tif (own(admission, \"allowed\") !== true) return unavailable;\n\tif (!captured) return unavailable;\n\tconst { i } = captured;\n\tlet browserStartHash: string;\n\ttry {\n\t\tbrowserStartHash = await proofHash(i.browserStartCode);\n\t} catch {\n\t\treturn unavailable;\n\t}\n\tconst verifiedAdmission = await verifyStartAdmission(context, captured);\n\tif (!verifiedAdmission) return unavailable;\n\tconst { admissionOwnerHash } = verifiedAdmission;\n\tif (!parseCoordinatorAuthLoopback(i.loopbackRedirect).ok) return unavailable;\n\tconst keyId = await ed25519KeyId(i.publicKey);\n\tif (\n\t\t!keyId ||\n\t\t!(await verifyOwnerEnrollmentSignature(\n\t\t\ti.publicKey,\n\t\t\townerEnrollmentStartMessage(i, context.pin),\n\t\t\ti.signature,\n\t\t))\n\t)\n\t\treturn unavailable;\n\tconst fingerprint = await ownerEnrollmentHash(i.publicKey);\n\tconst time = context.now();\n\tconst statement = startStatement(context, i, {\n\t\tkeyId,\n\t\tfingerprint,\n\t\tbrowserStartHash,\n\t\ttime,\n\t\tadmissionOwnerHash,\n\t});\n\tif (captured.owner && captured.sessionCookieHash !== undefined) {\n\t\tconst guard = await ownerAdmissionSessionGuard({\n\t\t\tbackend: context.backend,\n\t\t\tconfig: context.c,\n\t\t\tsessionCookieHash: captured.sessionCookieHash,\n\t\t\towner: captured.owner,\n\t\t\tdeviceId: i.deviceId,\n\t\t\tfingerprint,\n\t\t\ttime,\n\t\t});\n\t\t// Keep connection provenance out of the INSERT's expression tree (D1 depth 100).\n\t\t// Materialization is inside this same winning statement, not an earlier read.\n\t\tstatement.sql = `WITH owner_admission_authority AS MATERIALIZED (${guard.sql})\n ${statement.sql} AND EXISTS (SELECT 1 FROM owner_admission_authority)`;\n\t\tstatement.values.unshift(...guard.values);\n\t}\n\tconst wrote = await context.backend.run(statement);\n\tif (wrote !== 1) return unavailable;\n\treturn { kind: \"started\", attemptId: i.attemptId, expiresAtMs: time + 600000 };\n}\nfunction captureStartInputs(value: OwnerEnrollmentStart, admission: Parameters<typeof start>[3]) {\n\ttry {\n\t\tconst i = captureStart(value);\n\t\tif (admission.kind === \"operator\") return { i, token: admission.token, owner: null };\n\t\treturn {\n\t\t\ti,\n\t\t\ttoken: own(admission.options, \"admissionToken\"),\n\t\t\towner: captureResolvedOwner(own(admission.options, \"resolvedOwner\")),\n\t\t\tsessionCookieHash: captureSessionCookieHash(admission.options),\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction captureSessionCookieHash(\n\toptions: OwnerEnrollmentOwnerBoundStartOptions,\n): string | undefined {\n\tconst descriptor = Object.getOwnPropertyDescriptor(options, \"sessionCookieHash\");\n\tif (!descriptor) return undefined;\n\tif (\n\t\t!Object.hasOwn(descriptor, \"value\") ||\n\t\ttypeof descriptor.value !== \"string\" ||\n\t\t!/^[a-f0-9]{64}$/.test(descriptor.value)\n\t)\n\t\tthrow new Error();\n\treturn descriptor.value;\n}\nasync function verifyStartAdmission(\n\tcontext: Context,\n\tcaptured: NonNullable<ReturnType<typeof captureStartInputs>>,\n) {\n\tconst { i, token, owner } = captured;\n\tif (owner) {\n\t\tif (\n\t\t\t!context.admissionKey ||\n\t\t\t!(await verifyOwnerEnrollmentAdmissionV2(context.admissionKey, token, context.pin, i, {\n\t\t\t\tresolvedOwner: owner,\n\t\t\t\tnowMs: context.now(),\n\t\t\t}))\n\t\t)\n\t\t\treturn null;\n\t\treturn { admissionOwnerHash: await ownerEnrollmentOwnerCommitment(owner) };\n\t}\n\tif (\n\t\tcontext.admissionKey &&\n\t\t!(await verifyOwnerEnrollmentAdmission(\n\t\t\tcontext.admissionKey,\n\t\t\ttoken,\n\t\t\tcontext.pin,\n\t\t\ti,\n\t\t\tcontext.now(),\n\t\t))\n\t)\n\t\treturn null;\n\treturn { admissionOwnerHash: null };\n}\nfunction startStatement(\n\tcontext: Context,\n\ti: OwnerEnrollmentStart,\n\tp: {\n\t\tkeyId: string;\n\t\tfingerprint: string;\n\t\tbrowserStartHash: string;\n\t\ttime: number;\n\t\tadmissionOwnerHash: string | null;\n\t},\n): AuthLinkStatement {\n\tconst { c, pin } = context;\n\t// Signed starts have no issued-at: retain every attempt ID as a replay tombstone.\n\t// Expiry frees active slots only; no purge is supported, and storage fails closed.\n\treturn {\n\t\tsql: `INSERT INTO coordinator_owner_enrollment_attempts\n (coordinator_id,attempt_id,purpose,origin,device_id,public_key,key_id,fingerprint,issuer,auth_config_revision,\n loopback_redirect,browser_start_hash,state,created_at_ms,expires_at_ms,admission_owner_hash)\n SELECT ?,?,'owner_enroll',?,?,?,?,?,?,?,?,?,'pending',?,?,?\n WHERE ${OWNER_ADMISSION_SCHEMA_READY_SQL} AND ${NO_COLLISION_SQL}\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_link_attempts WHERE coordinator_id = ? AND attempt_id = ?)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_browser_transactions WHERE coordinator_id = ?\n AND attempt_id = ? AND purpose <> 'signin')\n AND (SELECT count(*) FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = ? AND device_id = ?\n AND state IN ('pending','browser_claimed','oidc_verified','confirmed') AND expires_at_ms > ?) < ?\n AND (SELECT count(*) FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = ? AND device_id = ? AND created_at_ms > ?) < ?\n AND (SELECT count(*) FROM (SELECT 1 FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = ?\n AND state IN ('pending','browser_claimed','oidc_verified','confirmed') AND expires_at_ms > ? LIMIT ?)) < ?\n AND (SELECT count(*) FROM (SELECT 1 FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = ?\n AND state <> 'finalized' LIMIT ?)) < ?`,\n\t\tvalues: [\n\t\t\tc.coordinatorId,\n\t\t\ti.attemptId,\n\t\t\tpin.origin,\n\t\t\ti.deviceId,\n\t\t\ti.publicKey,\n\t\t\tp.keyId,\n\t\t\tp.fingerprint,\n\t\t\tc.issuer,\n\t\t\tc.revision,\n\t\t\ti.loopbackRedirect,\n\t\t\tp.browserStartHash,\n\t\t\tp.time,\n\t\t\tp.time + 600000,\n\t\t\tp.admissionOwnerHash,\n\t\t\ti.deviceId,\n\t\t\tp.keyId,\n\t\t\ti.deviceId,\n\t\t\tp.keyId,\n\t\t\tc.coordinatorId,\n\t\t\ti.attemptId,\n\t\t\tc.coordinatorId,\n\t\t\ti.attemptId,\n\t\t\tc.coordinatorId,\n\t\t\ti.deviceId,\n\t\t\tp.time,\n\t\t\tAUTH_LINK_MAX_ACTIVE_PER_DEVICE,\n\t\t\tc.coordinatorId,\n\t\t\ti.deviceId,\n\t\t\tp.time - AUTH_LINK_CREATE_WINDOW_MS,\n\t\t\tAUTH_LINK_MAX_CREATES_PER_DEVICE_WINDOW,\n\t\t\tc.coordinatorId,\n\t\t\tp.time,\n\t\t\tOWNER_MAX_ACTIVE_PER_COORDINATOR,\n\t\t\tOWNER_MAX_ACTIVE_PER_COORDINATOR,\n\t\t\tc.coordinatorId,\n\t\t\tAUTH_LINK_MAX_UNFINISHED_PER_COORDINATOR,\n\t\t\tAUTH_LINK_MAX_UNFINISHED_PER_COORDINATOR,\n\t\t],\n\t};\n}\nasync function readAttempt(context: Context, attemptId: string): Promise<OwnerAttempt | null> {\n\treturn context.backend.first<OwnerAttempt>({\n\t\tsql: `SELECT * FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = ? AND attempt_id = ?\n AND ${OWNER_ADMISSION_SCHEMA_READY_SQL}`,\n\t\tvalues: [context.c.coordinatorId, attemptId],\n\t});\n}\nfunction live(context: Context, row: OwnerAttempt | null, time: number): row is OwnerAttempt {\n\treturn (\n\t\t!!row &&\n\t\trow.coordinator_id === context.c.coordinatorId &&\n\t\trow.purpose === \"owner_enroll\" &&\n\t\trow.origin === context.pin.origin &&\n\t\trow.issuer === context.c.issuer &&\n\t\trow.auth_config_revision === context.c.revision &&\n\t\tvalidAdmissionOwnerHash(row.admission_owner_hash) &&\n\t\tvalidAttemptTime(row) &&\n\t\trow.created_at_ms <= time &&\n\t\trow.expires_at_ms > time\n\t);\n}\nasync function claimBrowser(\n\tcontext: Context,\n\trequest: Request,\n\tclientKey: string,\n): Promise<OwnerEnrollmentStartResult> {\n\tconst snapshot = snapshotBrowserRequest(request);\n\tconst transaction = await readBrowserStartTransaction(\n\t\tsnapshot.cookie,\n\t\tnew CoordinatorAuthBrowserTransactions(context.backend, context.now),\n\t\tcontext.c,\n\t);\n\tif (transaction === \"active\" || transaction === \"invalid\") return unavailable;\n\tconst checked = await guardBrowserForm({\n\t\trequest,\n\t\tclientKey,\n\t\taction: \"link_start\",\n\t\tscope: context.scope,\n\t\tcsrfKey: context.csrfKey,\n\t\tlimiter: context.limiter,\n\t});\n\tif (!checked.ok || checked.action !== \"link_start\") return unavailable;\n\tconst cookie = await readBrowserCookie(snapshot.cookie, \"start\");\n\tif (cookie.kind !== \"present\" || cookie.cookieHash !== checked.cookieHash) return unavailable;\n\tconst row = await readAttempt(context, checked.attemptId);\n\tconst startHash = await proofHash(checked.startCode);\n\tif (\n\t\t!live(context, row, context.now()) ||\n\t\trow.state !== \"pending\" ||\n\t\trow.browser_start_hash !== startHash\n\t)\n\t\treturn unavailable;\n\tconst authorization = await context.client.createAuthorizationRequest();\n\tconst authorizationUrl = new URL(authorization.authorizationUrl);\n\tauthorizationUrl.searchParams.set(\"prompt\", \"select_account\");\n\tconst time = context.now();\n\tif (!live(context, row, time)) return unavailable;\n\tconst hash = await hashCoordinatorAuthProofBytes32(\n\t\tglobalThis.crypto.getRandomValues(new Uint8Array(32)),\n\t);\n\tconst stateHash = await ownerEnrollmentHash(authorization.material.state);\n\tconst setCookies = [reissueStartCookieAsTransaction(cookie.secret), clearBrowserCookie(\"start\")];\n\tawait context.backend.batch(\n\t\tclaimStatements(context, row, authorization, {\n\t\t\ttime,\n\t\t\thash,\n\t\t\tstateHash,\n\t\t\tbinder: checked.cookieHash,\n\t\t}),\n\t);\n\tconst claimed = await readAttempt(context, row.attempt_id);\n\tif (\n\t\tclaimed?.state !== \"browser_claimed\" ||\n\t\tclaimed.browser_transaction_hash !== hash ||\n\t\tclaimed.browser_binder_hash !== checked.cookieHash\n\t) {\n\t\tthrow new Error();\n\t}\n\treturn { kind: \"browser_claimed\", authorizationUrl: authorizationUrl.href, setCookies };\n}\n// A standalone INSERT must fail even if the raced attempt was deleted. UPDATE-based\n// assertions could affect zero rows and silently leave an orphan transaction.\nfunction assertOneWrite(): AuthLinkStatement {\n\treturn {\n\t\tsql: \"INSERT INTO coordinator_auth_browser_transactions (purpose) SELECT 'owner_enroll' WHERE changes() <> 1\",\n\t\tvalues: [],\n\t};\n}\ntype ClaimPin = { time: number; hash: string; stateHash: string; binder: string };\nfunction claimStatements(\n\tcontext: Context,\n\trow: OwnerAttempt,\n\tauthorization: Awaited<ReturnType<CoordinatorOidcClient[\"createAuthorizationRequest\"]>>,\n\tp: ClaimPin,\n): AuthLinkStatement[] {\n\treturn [\n\t\tinsertBrowser(context, row, authorization, p),\n\t\tassertOneWrite(),\n\t\tupdateAttempt(context, row, authorization, p),\n\t\tassertOneWrite(),\n\t];\n}\nconst PENDING_SQL = `coordinator_id = ? AND attempt_id = ? AND purpose = 'owner_enroll' AND state = 'pending'\n AND origin = ? AND issuer = ? AND auth_config_revision = ? AND browser_start_hash = ?\n AND created_at_ms = ? AND expires_at_ms = ? AND created_at_ms <= ? AND expires_at_ms > ?\n AND admission_owner_hash IS ?\n AND ${OWNER_ADMISSION_SCHEMA_READY_SQL}\n AND browser_transaction_hash IS NULL AND browser_binder_hash IS NULL`;\nfunction pendingValues(\n\tcontext: Context,\n\trow: OwnerAttempt,\n\tp: ClaimPin,\n): (string | number | null)[] {\n\treturn [\n\t\tcontext.c.coordinatorId,\n\t\trow.attempt_id,\n\t\tcontext.pin.origin,\n\t\tcontext.c.issuer,\n\t\tcontext.c.revision,\n\t\trow.browser_start_hash,\n\t\trow.created_at_ms,\n\t\trow.expires_at_ms,\n\t\tp.time,\n\t\tp.time,\n\t\trow.admission_owner_hash,\n\t];\n}\nfunction insertBrowser(\n\tcontext: Context,\n\trow: OwnerAttempt,\n\tauthorization: Awaited<ReturnType<CoordinatorOidcClient[\"createAuthorizationRequest\"]>>,\n\tp: ClaimPin,\n): AuthLinkStatement {\n\treturn {\n\t\tsql: `INSERT INTO coordinator_auth_browser_transactions\n (coordinator_id,browser_transaction_hash,purpose,attempt_id,state_hash,binder_hash,issuer,auth_config_revision,redirect_uri,\n state,nonce,pkce_verifier,created_at_ms,expires_at_ms)\n SELECT coordinator_id,?,'owner_enroll',attempt_id,?,?,issuer,auth_config_revision,?,'pending',?,?,?,expires_at_ms\n FROM coordinator_owner_enrollment_attempts WHERE ${PENDING_SQL} AND ${NO_COLLISION_SQL}`,\n\t\tvalues: [\n\t\t\tp.hash,\n\t\t\tp.stateHash,\n\t\t\tp.binder,\n\t\t\tcontext.c.redirectUri,\n\t\t\tauthorization.material.nonce,\n\t\t\tauthorization.material.pkceVerifier,\n\t\t\tp.time,\n\t\t\t...pendingValues(context, row, p),\n\t\t\trow.device_id,\n\t\t\trow.key_id,\n\t\t\trow.device_id,\n\t\t\trow.key_id,\n\t\t],\n\t};\n}\nfunction updateAttempt(\n\tcontext: Context,\n\trow: OwnerAttempt,\n\tauthorization: Awaited<ReturnType<CoordinatorOidcClient[\"createAuthorizationRequest\"]>>,\n\tp: ClaimPin,\n): AuthLinkStatement {\n\treturn {\n\t\tsql: `UPDATE coordinator_owner_enrollment_attempts AS a SET state = 'browser_claimed',browser_transaction_hash = ?,browser_binder_hash = ?\n WHERE ${PENDING_SQL} AND ${NO_COLLISION_SQL}\n AND EXISTS (SELECT 1 FROM coordinator_auth_browser_transactions b WHERE b.coordinator_id = a.coordinator_id\n AND b.attempt_id = a.attempt_id AND b.browser_transaction_hash = ? AND b.purpose = 'owner_enroll'\n AND b.binder_hash = ? AND b.state_hash = ? AND b.issuer = a.issuer AND b.auth_config_revision = a.auth_config_revision\n AND b.redirect_uri = ? AND b.state = 'pending' AND b.nonce = ? AND b.pkce_verifier = ?\n AND b.created_at_ms = ? AND b.expires_at_ms = a.expires_at_ms)`,\n\t\tvalues: [\n\t\t\tp.hash,\n\t\t\tp.binder,\n\t\t\t...pendingValues(context, row, p),\n\t\t\trow.device_id,\n\t\t\trow.key_id,\n\t\t\trow.device_id,\n\t\t\trow.key_id,\n\t\t\tp.hash,\n\t\t\tp.binder,\n\t\t\tp.stateHash,\n\t\t\tcontext.c.redirectUri,\n\t\t\tauthorization.material.nonce,\n\t\t\tauthorization.material.pkceVerifier,\n\t\t\tp.time,\n\t\t],\n\t};\n}\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,33,34,35,47,48],"mappings":";;;AACA,IAAI,MAAW,GAAY,GAAS,OAC1B,GAAS,MAAS;CACxB,IAAI,IAAQ;CACZ,OAAO,EAAS,CAAC;CACjB,eAAe,EAAS,GAAG;EACzB,IAAI,KAAK,GACP,MAAU,MAAM,8BAA8B;EAEhD,IAAQ;EACR,IAAI,GACA,IAAU,IACV;EAOJ,IANI,EAAW,MACb,IAAU,EAAW,EAAE,CAAC,EAAE,CAAC,IAC3B,EAAQ,IAAI,aAAa,KAEzB,IAAU,MAA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