@codemem/core 0.49.1 → 0.50.0-beta.1
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/api-types.d.ts +7 -0
- package/dist/api-types.d.ts.map +1 -1
- package/dist/better-sqlite-coordinator-runtime.d.ts.map +1 -1
- package/dist/better-sqlite-coordinator-store.d.ts +56 -3
- package/dist/better-sqlite-coordinator-store.d.ts.map +1 -1
- package/dist/boundary-readiness-inventory.d.ts +27 -0
- package/dist/boundary-readiness-inventory.d.ts.map +1 -0
- package/dist/coordinator-account-link-receiver.d.ts +15 -0
- package/dist/coordinator-account-link-receiver.d.ts.map +1 -1
- package/dist/coordinator-account-link-status-client.d.ts +1 -1
- package/dist/coordinator-account-link-status-client.d.ts.map +1 -1
- package/dist/coordinator-actions.d.ts +12 -0
- package/dist/coordinator-actions.d.ts.map +1 -1
- package/dist/coordinator-api.d.ts +7 -0
- package/dist/coordinator-api.d.ts.map +1 -1
- package/dist/coordinator-auth-historical-store-test-fixture.d.ts.map +1 -1
- package/dist/coordinator-auth-link-revocation-test-harness.d.ts.map +1 -1
- package/dist/coordinator-auth-schema-stage.d.ts +14 -2
- package/dist/coordinator-auth-schema-stage.d.ts.map +1 -1
- package/dist/coordinator-block-tombstone-test-harness.d.ts +3 -0
- package/dist/coordinator-block-tombstone-test-harness.d.ts.map +1 -0
- package/dist/coordinator-bootstrap-authorization-api-test-harness.d.ts.map +1 -1
- package/dist/coordinator-bootstrap-authorization-test-harness.d.ts.map +1 -1
- package/dist/coordinator-bootstrap-revocation-test-harness.d.ts.map +1 -1
- package/dist/coordinator-boundary-readiness-client.d.ts +35 -0
- package/dist/coordinator-boundary-readiness-client.d.ts.map +1 -0
- package/dist/coordinator-boundary-readiness-route.d.ts +52 -0
- package/dist/coordinator-boundary-readiness-route.d.ts.map +1 -0
- package/dist/coordinator-boundary-readiness-test-harness.d.ts +15 -0
- package/dist/coordinator-boundary-readiness-test-harness.d.ts.map +1 -0
- package/dist/coordinator-boundary-readiness.d.ts +161 -0
- package/dist/coordinator-boundary-readiness.d.ts.map +1 -0
- package/dist/coordinator-browser-auth-app.d.ts +1 -1
- package/dist/coordinator-browser-auth-app.d.ts.map +1 -1
- package/dist/coordinator-browser-auth-callback.d.ts +2 -1
- package/dist/coordinator-browser-auth-callback.d.ts.map +1 -1
- package/dist/coordinator-controller-revocation-test-harness.d.ts.map +1 -1
- package/dist/coordinator-d1-schema-inventory.d.ts +2 -0
- package/dist/coordinator-d1-schema-inventory.d.ts.map +1 -1
- package/dist/coordinator-d1-scope-authorization-test-harness.d.ts.map +1 -1
- package/dist/coordinator-device-auth-link.d.ts +1 -0
- package/dist/coordinator-device-auth-link.d.ts.map +1 -1
- package/dist/coordinator-device-rejoin-browser-evidence.d.ts +28 -0
- package/dist/coordinator-device-rejoin-browser-evidence.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-browser-transaction-test-harness.d.ts +8 -0
- package/dist/coordinator-device-rejoin-browser-transaction-test-harness.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-browser-transaction.d.ts +43 -0
- package/dist/coordinator-device-rejoin-browser-transaction.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-browser-view.d.ts +30 -0
- package/dist/coordinator-device-rejoin-browser-view.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-browser.d.ts +26 -0
- package/dist/coordinator-device-rejoin-browser.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-client-requests.d.ts +70 -0
- package/dist/coordinator-device-rejoin-client-requests.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-client.d.ts +15 -0
- package/dist/coordinator-device-rejoin-client.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-confirmation-test-harness.d.ts +22 -0
- package/dist/coordinator-device-rejoin-confirmation-test-harness.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-confirmation.d.ts +18 -0
- package/dist/coordinator-device-rejoin-confirmation.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-destinations-test-harness.d.ts +7 -0
- package/dist/coordinator-device-rejoin-destinations-test-harness.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-destinations.d.ts +25 -0
- package/dist/coordinator-device-rejoin-destinations.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-display.d.ts +14 -0
- package/dist/coordinator-device-rejoin-display.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-event-client.d.ts +30 -0
- package/dist/coordinator-device-rejoin-event-client.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-events.d.ts +7 -0
- package/dist/coordinator-device-rejoin-events.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-finalize-test-harness.d.ts +14 -0
- package/dist/coordinator-device-rejoin-finalize-test-harness.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-finalize.d.ts +36 -0
- package/dist/coordinator-device-rejoin-finalize.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-http.d.ts +11 -0
- package/dist/coordinator-device-rejoin-http.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-link-evidence-test-harness.d.ts +17 -0
- package/dist/coordinator-device-rejoin-link-evidence-test-harness.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-link-evidence.d.ts +29 -0
- package/dist/coordinator-device-rejoin-link-evidence.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-link-lineage.d.ts +7 -0
- package/dist/coordinator-device-rejoin-link-lineage.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-oidc-pins.d.ts +14 -0
- package/dist/coordinator-device-rejoin-oidc-pins.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-proof.d.ts +41 -0
- package/dist/coordinator-device-rejoin-proof.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-schema-test-harness.d.ts +8 -0
- package/dist/coordinator-device-rejoin-schema-test-harness.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-schema.d.ts +9 -0
- package/dist/coordinator-device-rejoin-schema.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-start-evidence-test-harness.d.ts +40 -0
- package/dist/coordinator-device-rejoin-start-evidence-test-harness.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-start-evidence.d.ts +25 -0
- package/dist/coordinator-device-rejoin-start-evidence.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-start-http.d.ts +12 -0
- package/dist/coordinator-device-rejoin-start-http.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-start-input.d.ts +23 -0
- package/dist/coordinator-device-rejoin-start-input.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-start-write.d.ts +38 -0
- package/dist/coordinator-device-rejoin-start-write.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-status-http.d.ts +10 -0
- package/dist/coordinator-device-rejoin-status-http.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-status-live-test-harness.d.ts +33 -0
- package/dist/coordinator-device-rejoin-status-live-test-harness.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-status-projection.d.ts +28 -0
- package/dist/coordinator-device-rejoin-status-projection.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-status-test-harness.d.ts +8 -0
- package/dist/coordinator-device-rejoin-status-test-harness.d.ts.map +1 -0
- package/dist/coordinator-device-rejoin-status.d.ts +39 -0
- package/dist/coordinator-device-rejoin-status.d.ts.map +1 -0
- package/dist/coordinator-device-removal-commands.d.ts +13 -0
- package/dist/coordinator-device-removal-commands.d.ts.map +1 -0
- package/dist/coordinator-device-removal-commit-test-harness.d.ts +3 -0
- package/dist/coordinator-device-removal-commit-test-harness.d.ts.map +1 -0
- package/dist/coordinator-device-removal-commit.d.ts +44 -0
- package/dist/coordinator-device-removal-commit.d.ts.map +1 -0
- package/dist/coordinator-device-removal-dependents-test-harness.d.ts +9 -0
- package/dist/coordinator-device-removal-dependents-test-harness.d.ts.map +1 -0
- package/dist/coordinator-device-removal-dependents.d.ts +34 -0
- package/dist/coordinator-device-removal-dependents.d.ts.map +1 -0
- package/dist/coordinator-device-removal-list-test-harness.d.ts +4 -0
- package/dist/coordinator-device-removal-list-test-harness.d.ts.map +1 -0
- package/dist/coordinator-device-removal-list.d.ts +40 -0
- package/dist/coordinator-device-removal-list.d.ts.map +1 -0
- package/dist/coordinator-device-removal-preview-test-harness.d.ts +9 -0
- package/dist/coordinator-device-removal-preview-test-harness.d.ts.map +1 -0
- package/dist/coordinator-device-removal-routes.d.ts +13 -0
- package/dist/coordinator-device-removal-routes.d.ts.map +1 -0
- package/dist/coordinator-device-removal-target.d.ts +98 -0
- package/dist/coordinator-device-removal-target.d.ts.map +1 -0
- package/dist/coordinator-device-removal-test-harness.d.ts +70 -0
- package/dist/coordinator-device-removal-test-harness.d.ts.map +1 -0
- package/dist/coordinator-device-removal-writer-test-harness.d.ts +8 -0
- package/dist/coordinator-device-removal-writer-test-harness.d.ts.map +1 -0
- package/dist/coordinator-device-removal.d.ts +233 -0
- package/dist/coordinator-device-removal.d.ts.map +1 -0
- package/dist/coordinator-device-revocation-client.d.ts +2 -0
- package/dist/coordinator-device-revocation-client.d.ts.map +1 -1
- package/dist/coordinator-device-revocation-handler-test-harness.d.ts.map +1 -1
- package/dist/coordinator-device-revocation-handler.d.ts +1 -1
- package/dist/coordinator-device-revocation-handler.d.ts.map +1 -1
- package/dist/coordinator-device-revocation-route.d.ts.map +1 -1
- package/dist/coordinator-device-revocation-test-harness.d.ts.map +1 -1
- package/dist/coordinator-device-revocation.d.ts +20 -2
- package/dist/coordinator-device-revocation.d.ts.map +1 -1
- package/dist/coordinator-enrollment-reconciler.d.ts.map +1 -1
- package/dist/coordinator-enrollment-test-fixtures.d.ts +126 -0
- package/dist/coordinator-enrollment-test-fixtures.d.ts.map +1 -0
- package/dist/coordinator-history-sql-equivalence-test-fixtures.d.ts +1 -1
- package/dist/coordinator-history-sql-equivalence-test-fixtures.d.ts.map +1 -1
- package/dist/coordinator-identity-grant-revocation-test-harness.d.ts.map +1 -1
- package/dist/coordinator-identity-group-grant-test-harness.d.ts.map +1 -1
- package/dist/coordinator-invitation-lift-test-harness.d.ts +6 -0
- package/dist/coordinator-invitation-lift-test-harness.d.ts.map +1 -0
- package/dist/coordinator-invitation-removal.d.ts +71 -0
- package/dist/coordinator-invitation-removal.d.ts.map +1 -0
- package/dist/coordinator-join-review-guards.d.ts +2 -0
- package/dist/coordinator-join-review-guards.d.ts.map +1 -1
- package/dist/coordinator-join-revocation-test-harness.d.ts.map +1 -1
- package/dist/coordinator-key-id-fill-api-test-harness.d.ts +12 -0
- package/dist/coordinator-key-id-fill-api-test-harness.d.ts.map +1 -0
- package/dist/coordinator-key-id-fill-api.d.ts +19 -0
- package/dist/coordinator-key-id-fill-api.d.ts.map +1 -0
- package/dist/coordinator-legacy-device-ownership.d.ts +66 -5
- package/dist/coordinator-legacy-device-ownership.d.ts.map +1 -1
- package/dist/coordinator-legacy-owner-compatibility.d.ts +3 -0
- package/dist/coordinator-legacy-owner-compatibility.d.ts.map +1 -1
- package/dist/coordinator-membership-enrollment-test-harness.d.ts +4 -0
- package/dist/coordinator-membership-enrollment-test-harness.d.ts.map +1 -0
- package/dist/coordinator-membership-enrollment.d.ts +15 -0
- package/dist/coordinator-membership-enrollment.d.ts.map +1 -0
- package/dist/coordinator-owner-enrollment-commit.d.ts +1 -1
- package/dist/coordinator-owner-enrollment-commit.d.ts.map +1 -1
- package/dist/coordinator-owner-enrollment-qualification-test-harness.d.ts.map +1 -1
- package/dist/coordinator-owner-enrollment-qualification.d.ts +1 -0
- package/dist/coordinator-owner-enrollment-qualification.d.ts.map +1 -1
- package/dist/coordinator-owner-resolution-review-test-fixtures.d.ts.map +1 -1
- package/dist/coordinator-peer-discovery-revocation-test-harness.d.ts.map +1 -1
- package/dist/coordinator-peer-removal-api-test-harness.d.ts +29 -0
- package/dist/coordinator-peer-removal-api-test-harness.d.ts.map +1 -0
- package/dist/coordinator-peer-removal-query-test-harness.d.ts +4 -0
- package/dist/coordinator-peer-removal-query-test-harness.d.ts.map +1 -0
- package/dist/coordinator-peer-removal-query.d.ts +32 -0
- package/dist/coordinator-peer-removal-query.d.ts.map +1 -0
- package/dist/coordinator-peer-revocation-route.d.ts +45 -0
- package/dist/coordinator-peer-revocation-route.d.ts.map +1 -0
- package/dist/coordinator-peer-revocation.d.ts +61 -0
- package/dist/coordinator-peer-revocation.d.ts.map +1 -0
- package/dist/coordinator-presence-capabilities.d.ts +10 -0
- package/dist/coordinator-presence-capabilities.d.ts.map +1 -0
- package/dist/coordinator-project-revocation-test-harness.d.ts +1 -1
- package/dist/coordinator-project-revocation-test-harness.d.ts.map +1 -1
- package/dist/coordinator-recipient-revocation-test-harness.d.ts.map +1 -1
- package/dist/coordinator-refresh-lifecycle.d.ts +11 -0
- package/dist/coordinator-refresh-lifecycle.d.ts.map +1 -0
- package/dist/coordinator-rejoin-discovery.d.ts +16 -0
- package/dist/coordinator-rejoin-discovery.d.ts.map +1 -0
- package/dist/coordinator-rejoin-timestamp.d.ts +3 -0
- package/dist/coordinator-rejoin-timestamp.d.ts.map +1 -0
- package/dist/coordinator-removal-notice.d.ts +21 -0
- package/dist/coordinator-removal-notice.d.ts.map +1 -0
- package/dist/coordinator-removal-progress-listing-test-harness.d.ts +3 -0
- package/dist/coordinator-removal-progress-listing-test-harness.d.ts.map +1 -0
- package/dist/coordinator-runtime-ynLTJI6d.js +1712 -0
- package/dist/coordinator-runtime-ynLTJI6d.js.map +1 -0
- package/dist/coordinator-runtime.d.ts +20 -1
- package/dist/coordinator-runtime.d.ts.map +1 -1
- package/dist/coordinator-scope-authorization-api-test-harness.d.ts.map +1 -1
- package/dist/coordinator-store-contract.d.ts +21 -3
- package/dist/coordinator-store-contract.d.ts.map +1 -1
- package/dist/coordinator-store-test-harness.d.ts.map +1 -1
- package/dist/coordinator-sync-config.d.ts +14 -0
- package/dist/coordinator-sync-config.d.ts.map +1 -1
- package/dist/d1-coordinator-runtime.d.ts +3 -1
- package/dist/d1-coordinator-runtime.d.ts.map +1 -1
- package/dist/d1-coordinator-store.d.ts +63 -3
- package/dist/d1-coordinator-store.d.ts.map +1 -1
- package/dist/database-runtime-primitives.d.ts +1 -1
- package/dist/db.d.ts.map +1 -1
- package/dist/device-identity-binding.d.ts +24 -0
- package/dist/device-identity-binding.d.ts.map +1 -1
- package/dist/device-identity-inventory.d.ts +19 -1
- package/dist/device-identity-inventory.d.ts.map +1 -1
- package/dist/device-retirement.d.ts +43 -0
- package/dist/device-retirement.d.ts.map +1 -0
- package/dist/identity-device-assignment.d.ts +8 -0
- package/dist/identity-device-assignment.d.ts.map +1 -1
- package/dist/index.d.ts +34 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +11649 -10631
- package/dist/index.js.map +1 -1
- package/dist/internal/cloudflare-coordinator.js +2317 -1542
- package/dist/internal/cloudflare-coordinator.js.map +1 -1
- package/dist/internal/relay-runtime.js +28 -28
- package/dist/legacy-pairing-assignment-conversion.d.ts +46 -0
- package/dist/legacy-pairing-assignment-conversion.d.ts.map +1 -0
- package/dist/legacy-pairing-assignment-state.d.ts +11 -0
- package/dist/legacy-pairing-assignment-state.d.ts.map +1 -0
- package/dist/legacy-team-setup-errors.d.ts +2 -1
- package/dist/legacy-team-setup-errors.d.ts.map +1 -1
- package/dist/local-origin-claim.d.ts +48 -0
- package/dist/local-origin-claim.d.ts.map +1 -0
- package/dist/maintenance/ai-structured.d.ts +2 -0
- package/dist/maintenance/ai-structured.d.ts.map +1 -1
- package/dist/observer-config.d.ts.map +1 -1
- package/dist/owned-recipient-d1-test-harness.d.ts.map +1 -1
- package/dist/owner-enrollment-link-authority.d.ts +1 -0
- package/dist/owner-enrollment-link-authority.d.ts.map +1 -1
- package/dist/{owner-enrollment-start-BsDwgxAh.js → owner-enrollment-start-D8QzF1Ar.js} +5548 -3637
- package/dist/owner-enrollment-start-D8QzF1Ar.js.map +1 -0
- package/dist/pairing-removal.d.ts +57 -0
- package/dist/pairing-removal.d.ts.map +1 -0
- package/dist/peer-project-filter-change.d.ts +33 -0
- package/dist/peer-project-filter-change.d.ts.map +1 -0
- package/dist/peer-project-filter-management.d.ts +7 -0
- package/dist/peer-project-filter-management.d.ts.map +1 -0
- package/dist/peer-project-filter-retention.d.ts +17 -0
- package/dist/peer-project-filter-retention.d.ts.map +1 -0
- package/dist/peer-removal-check-state.d.ts +24 -0
- package/dist/peer-removal-check-state.d.ts.map +1 -0
- package/dist/peer-removal.d.ts +34 -0
- package/dist/peer-removal.d.ts.map +1 -0
- package/dist/peer-traversal-coordinator-attempt-write-test-fixtures.d.ts.map +1 -1
- package/dist/peer-traversal-coordinator-decision-test-fixtures.d.ts.map +1 -1
- package/dist/policy-team-device-eligibility.d.ts +10 -0
- package/dist/policy-team-device-eligibility.d.ts.map +1 -1
- package/dist/project-boundary-migration-hold.d.ts +50 -0
- package/dist/project-boundary-migration-hold.d.ts.map +1 -0
- package/dist/project-boundary-migration-records.d.ts +46 -0
- package/dist/project-boundary-migration-records.d.ts.map +1 -0
- package/dist/project-filters-narrowing.d.ts +11 -0
- package/dist/project-filters-narrowing.d.ts.map +1 -0
- package/dist/project-scope-resume.d.ts +26 -0
- package/dist/project-scope-resume.d.ts.map +1 -0
- package/dist/project-scope-settings.d.ts +7 -0
- package/dist/project-scope-settings.d.ts.map +1 -1
- package/dist/project-scope-withdrawal.d.ts +48 -0
- package/dist/project-scope-withdrawal.d.ts.map +1 -0
- package/dist/project-withdrawal-state.d.ts +36 -0
- package/dist/project-withdrawal-state.d.ts.map +1 -0
- package/dist/{recipient-policy-contract-Ca40IBUh.js → recipient-policy-contract-BHxfaQZ2.js} +12 -5
- package/dist/recipient-policy-contract-BHxfaQZ2.js.map +1 -0
- package/dist/recipient-policy-contract.d.ts +7 -0
- package/dist/recipient-policy-contract.d.ts.map +1 -1
- package/dist/recipient-policy-contract.js +2 -2
- package/dist/recipient-policy-edges.d.ts.map +1 -1
- package/dist/recipient-policy-intent.d.ts +1 -0
- package/dist/recipient-policy-intent.d.ts.map +1 -1
- package/dist/recipient-policy-onboarding.d.ts.map +1 -1
- package/dist/recipient-policy-reconciler.d.ts.map +1 -1
- package/dist/recipient-policy-reconciliation.d.ts.map +1 -1
- package/dist/recipient-policy-team-create.d.ts +22 -0
- package/dist/recipient-policy-team-create.d.ts.map +1 -0
- package/dist/{relay-health-CeyhVeuq.js → relay-health-B8BpHFaE.js} +14 -14
- package/dist/{relay-health-CeyhVeuq.js.map → relay-health-B8BpHFaE.js.map} +1 -1
- package/dist/{relay-peer-client-DmZfZebO.js → relay-peer-client-w7WdS1AP.js} +3083 -2634
- package/dist/relay-peer-client-w7WdS1AP.js.map +1 -0
- package/dist/relay-server-test-fixtures.d.ts.map +1 -1
- package/dist/replication-cursor-orphan-cleanup.d.ts +14 -0
- package/dist/replication-cursor-orphan-cleanup.d.ts.map +1 -0
- package/dist/retired-device-aliases.d.ts +28 -0
- package/dist/retired-device-aliases.d.ts.map +1 -0
- package/dist/same-actor-peers.d.ts +5 -1
- package/dist/same-actor-peers.d.ts.map +1 -1
- package/dist/schema-bootstrap.d.ts +1 -0
- package/dist/schema-bootstrap.d.ts.map +1 -1
- package/dist/schema.d.ts +4456 -3623
- package/dist/schema.d.ts.map +1 -1
- package/dist/{scope-membership-cache-read-B6z47l2W.js → scope-resolution-B7FK15hx.js} +2242 -1608
- package/dist/scope-resolution-B7FK15hx.js.map +1 -0
- package/dist/semantic-worker-entry.js +1 -1
- package/dist/{semantic-worker-job-BLaC4xRY.js → semantic-worker-job-BjujlM4-.js} +3 -3
- package/dist/{semantic-worker-job-BLaC4xRY.js.map → semantic-worker-job-BjujlM4-.js.map} +1 -1
- package/dist/{semantic-worker-ranking-5-VSzEmx.js → semantic-worker-ranking-WaUCapnY.js} +66 -60
- package/dist/semantic-worker-ranking-WaUCapnY.js.map +1 -0
- package/dist/share-provisioning.d.ts +4 -0
- package/dist/share-provisioning.d.ts.map +1 -1
- package/dist/shared-owned-device-enrollment-test-harness.d.ts.map +1 -1
- package/dist/shared-owned-project-invites-test-harness.d.ts.map +1 -1
- package/dist/shared-owned-recipient-invites-test-harness.d.ts.map +1 -1
- package/dist/shared-ownership-writer-lifecycle-test-harness.d.ts.map +1 -1
- package/dist/snapshot-cross-scope-reconcile.d.ts +25 -0
- package/dist/snapshot-cross-scope-reconcile.d.ts.map +1 -0
- package/dist/{sync-auth-constants-BVzVfSmn.js → sync-auth-constants-DNUSV-Tn.js} +4482 -2842
- package/dist/sync-auth-constants-DNUSV-Tn.js.map +1 -0
- package/dist/sync-bootstrap.d.ts +2 -0
- package/dist/sync-bootstrap.d.ts.map +1 -1
- package/dist/sync-capability.d.ts +1 -1
- package/dist/sync-capability.d.ts.map +1 -1
- package/dist/sync-channel-progress.d.ts +7 -0
- package/dist/sync-channel-progress.d.ts.map +1 -1
- package/dist/sync-daemon.d.ts +4 -1
- package/dist/sync-daemon.d.ts.map +1 -1
- package/dist/sync-pass.d.ts.map +1 -1
- package/dist/sync-peer-addresses.d.ts +4 -2
- package/dist/sync-peer-addresses.d.ts.map +1 -1
- package/dist/sync-reachability-pass-BpTtRqcV.js +2 -0
- package/dist/{sync-reachability-pass-Dhn4N2hr.js → sync-reachability-pass-DKEORTbs.js} +2638 -2591
- package/dist/sync-reachability-pass-DKEORTbs.js.map +1 -0
- package/dist/sync-replication.d.ts +21 -3
- package/dist/sync-replication.d.ts.map +1 -1
- package/dist/sync-scope-protocol.d.ts.map +1 -1
- package/dist/test-environment-isolation.d.ts +2 -0
- package/dist/test-environment-isolation.d.ts.map +1 -0
- package/dist/test-schema.generated.d.ts +1 -1
- package/dist/test-schema.generated.d.ts.map +1 -1
- package/dist/test-utils.d.ts +4 -0
- package/dist/test-utils.d.ts.map +1 -1
- package/dist/{validated-vector-index-audit-B64yhEBF.js → validated-vector-index-audit-BtUovYuM.js} +269 -637
- package/dist/validated-vector-index-audit-BtUovYuM.js.map +1 -0
- package/dist/viewer-device-removal-commit.d.ts +56 -0
- package/dist/viewer-device-removal-commit.d.ts.map +1 -0
- package/dist/viewer-device-removal-evidence.d.ts +17 -0
- package/dist/viewer-device-removal-evidence.d.ts.map +1 -0
- package/dist/{scope-membership-semantics-B8qXaMqx.js → workspace-identity-C7EPmSZe.js} +121 -49
- package/dist/workspace-identity-C7EPmSZe.js.map +1 -0
- package/package.json +3 -3
- package/dist/coordinator-runtime-CEc6KhBE.js +0 -594
- package/dist/coordinator-runtime-CEc6KhBE.js.map +0 -1
- package/dist/owner-enrollment-start-BsDwgxAh.js.map +0 -1
- package/dist/recipient-policy-contract-Ca40IBUh.js.map +0 -1
- package/dist/relay-peer-client-DmZfZebO.js.map +0 -1
- package/dist/scope-membership-cache-read-B6z47l2W.js.map +0 -1
- package/dist/scope-membership-semantics-B8qXaMqx.js.map +0 -1
- package/dist/semantic-worker-ranking-5-VSzEmx.js.map +0 -1
- package/dist/sync-auth-constants-BVzVfSmn.js.map +0 -1
- package/dist/sync-reachability-pass-C_-w0t6b.js +0 -2
- package/dist/sync-reachability-pass-Dhn4N2hr.js.map +0 -1
- package/dist/validated-vector-index-audit-B64yhEBF.js.map +0 -1
- package/dist/workspace-identity-DI8bBR0Y.js +0 -76
- package/dist/workspace-identity-DI8bBR0Y.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sync-auth-constants-BVzVfSmn.js","names":[],"sources":["../src/legacy-team-setup-limits.ts","../src/recipient-policy-identifiers.ts","../src/coordinator-legacy-team-completion.ts","../src/coordinator-auth-controller-history.ts","../src/coordinator-auth-controller.ts","../src/coordinator-auth-browser-style.ts","../src/coordinator-auth-proof.ts","../src/coordinator-sql-compare.ts","../src/coordinator-account-change-decision.ts","../src/coordinator-auth-legacy-assignment.ts","../src/coordinator-auth-contract.ts","../src/coordinator-auth-link-input.ts","../src/coordinator-auth-device-claim-eligibility.ts","../src/coordinator-account-connection-storage.ts","../src/coordinator-auth-link-provenance.ts","../src/coordinator-auth-read-set.ts","../src/coordinator-account-change-authority.ts","../src/coordinator-account-change-schema.ts","../src/coordinator-account-unlink-schema.ts","../src/coordinator-auth-device-claim-schema.ts","../src/coordinator-auth-link-contract.ts","../src/coordinator-account-connection-schema.ts","../src/coordinator-account-connection-session.ts","../src/coordinator-auth-account-profile-contract.ts","../src/coordinator-account-connection-link.ts","../src/coordinator-auth-link-authority.ts","../src/coordinator-auth-link-source.ts","../src/coordinator-auth-schema.ts","../src/coordinator-account-historical-revoke.ts","../src/coordinator-auth-link-headless.ts","../src/coordinator-auth-session-contract.ts","../src/coordinator-auth-session.ts","../src/coordinator-auth-account-profile.ts","../src/coordinator-auth-headless-schema.ts","../src/coordinator-auth-headless-provenance.ts","../src/coordinator-auth-link-profile.ts","../src/coordinator-auth-loopback.ts","../src/coordinator-device-claim-binding-contract.ts","../src/coordinator-device-claim-binding-reuse.ts","../src/coordinator-device-ownership-evidence-queries.ts","../src/coordinator-legacy-owner-resolution-schema.ts","../src/coordinator-legacy-owner-resolution-metadata.ts","../src/coordinator-device-ownership-evidence-classify.ts","../src/coordinator-owner-negative-consistency.ts","../src/coordinator-owner-negative-reads.ts","../src/coordinator-owner-negative-read-set.ts","../src/coordinator-device-claim-binding-sql.ts","../src/coordinator-device-claim-binding.ts","../src/coordinator-auth-link.ts","../src/coordinator-account-change.ts","../src/coordinator-auth-browser-transaction-contract.ts","../src/coordinator-browser-credential.ts","../src/coordinator-browser-csrf.ts","../src/coordinator-auth-browser-view.ts","../src/coordinator-account-link-status.ts","../src/coordinator-account-owner-target.ts","../src/coordinator-auth-browser-transaction.ts","../src/coordinator-auth-controller-owner.ts","../src/coordinator-auth-controller-read-set.ts","../src/coordinator-device-revocation.ts","../src/coordinator-bootstrap-grant-authorization.ts","../src/coordinator-bootstrap-grant-issuance.ts","../src/coordinator-device-rebind-schema.ts","../src/coordinator-enrollment-ownership.ts","../src/coordinator-identity-group-grant.ts","../src/coordinator-legacy-device-ownership.ts","../src/coordinator-join-review-guards.ts","../src/coordinator-legacy-owner-compatibility.ts","../src/coordinator-legacy-completion-owner-proof.ts","../src/coordinator-membership-effects.ts","../src/coordinator-owner-enrollment-schema.ts","../src/coordinator-device-ownership-evidence-digest.ts","../src/coordinator-device-ownership-evidence.ts","../src/coordinator-legacy-owner-resolution-commit.ts","../src/coordinator-owner-resolution-review-read.ts","../src/coordinator-owner-resolution-review.ts","../src/coordinator-peer-discovery.ts","../src/coordinator-project-invite-guards.ts","../src/coordinator-recipient-owner-consistency.ts","../src/coordinator-resolved-account-owner-status-query.ts","../src/coordinator-resolved-account-owner-status.ts","../src/coordinator-store-contract.ts","../src/project-invite-identity.ts","../src/recipient-reviewed-intent.ts","../src/coordinator-store-input-rules.ts","../src/relay-admission-proof.ts","../src/sync-auth-constants.ts"],"sourcesContent":["import type { Database } from \"./db.js\";\n\nexport const LEGACY_TEAM_SETUP_MAX_DEVICES = 500;\nexport const LEGACY_TEAM_SETUP_MAX_PROJECTS = 500;\nexport const LEGACY_TEAM_SETUP_MAX_PROJECT_DEVICE_PAIRS = 10_000;\n\nexport function requireLegacyTeamSetupSnapshotWithinLimits(input: {\n\tdevices: readonly unknown[];\n\tprojects: readonly unknown[];\n}): void {\n\tif (\n\t\tinput.devices.length > LEGACY_TEAM_SETUP_MAX_DEVICES ||\n\t\tinput.projects.length > LEGACY_TEAM_SETUP_MAX_PROJECTS ||\n\t\tinput.devices.length * input.projects.length > LEGACY_TEAM_SETUP_MAX_PROJECT_DEVICE_PAIRS\n\t) {\n\t\tthrow new Error(\"legacy_team_setup_roster_too_large\");\n\t}\n}\n\n/**\n * Bounds the access-delta derivation itself. Activation recomputes effective\n * devices for every Project the Team touches plus every Project with an\n * active recipient edge, across every assigned device, so a tiny draft can\n * still fan out past the pair budget when the installation already holds many\n * recipients or assignments.\n */\nexport function requireLegacyTeamSetupAccessDeltaTraversalWithinLimit(input: {\n\tprojectIdentities: ReadonlySet<string>;\n\tdeviceCount: number;\n}): void {\n\tif (\n\t\tinput.projectIdentities.size * input.deviceCount >\n\t\tLEGACY_TEAM_SETUP_MAX_PROJECT_DEVICE_PAIRS\n\t) {\n\t\tthrow new Error(\"legacy_team_setup_roster_too_large\");\n\t}\n}\n\n/**\n * Readiness checks re-derive effective devices for every completed Project,\n * and that derivation walks every persisted assignment row. Bound that fan-out\n * so a small roster cannot hide an unbounded Project-by-assignment traversal.\n */\nexport function requireLegacyTeamSetupReachableDevicesWithinLimit(\n\tdb: Database,\n\tdevices: readonly { deviceId: string }[],\n\tprojects: readonly unknown[],\n): void {\n\tif (projects.length === 0) return;\n\tconst deviceIds = [...new Set(devices.map((device) => device.deviceId))];\n\tconst excludeRoster =\n\t\tdeviceIds.length > 0 ? `WHERE device_id NOT IN (${deviceIds.map(() => \"?\").join(\", \")})` : \"\";\n\tconst assignmentRows = Number(\n\t\tdb\n\t\t\t.prepare(`SELECT COUNT(*) FROM identity_devices ${excludeRoster}`)\n\t\t\t.pluck()\n\t\t\t.get(...deviceIds) ?? 0,\n\t);\n\tif (\n\t\t(deviceIds.length + assignmentRows) * projects.length >\n\t\tLEGACY_TEAM_SETUP_MAX_PROJECT_DEVICE_PAIRS\n\t) {\n\t\tthrow new Error(\"legacy_team_setup_roster_too_large\");\n\t}\n}\n\nexport function requireLegacyTeamSetupEffectiveDevicesWithinLimit(\n\tdb: Database,\n\tdevices: readonly { deviceId: string }[],\n\tprojects: readonly unknown[],\n\tpreviousAttemptId: string | null,\n): void {\n\tif (!previousAttemptId) return;\n\tconst currentDeviceIds = [...new Set(devices.map((device) => device.deviceId))];\n\tconst placeholders = currentDeviceIds.map(() => \"?\").join(\", \");\n\tconst excludeCurrent = placeholders ? `AND device_id NOT IN (${placeholders})` : \"\";\n\tconst carriedDeviceCount = Number(\n\t\tdb\n\t\t\t.prepare(\n\t\t\t\t`SELECT COUNT(*) FROM legacy_team_setup_draft_devices\n\t\t\t\t WHERE attempt_id = ? ${excludeCurrent}`,\n\t\t\t)\n\t\t\t.pluck()\n\t\t\t.get(previousAttemptId, ...currentDeviceIds) ?? 0,\n\t);\n\tconst effectiveDeviceCount = devices.length + carriedDeviceCount;\n\tif (\n\t\teffectiveDeviceCount > LEGACY_TEAM_SETUP_MAX_DEVICES ||\n\t\teffectiveDeviceCount * projects.length > LEGACY_TEAM_SETUP_MAX_PROJECT_DEVICE_PAIRS\n\t) {\n\t\tthrow new Error(\"legacy_team_setup_roster_too_large\");\n\t}\n}\n","import { createHash } from \"node:crypto\";\n\n/**\n * Locale-independent UTF-16 code-unit comparison. Every fingerprint and digest\n * in the recipient-policy feature relies on byte-identical ordering across\n * machines, so `localeCompare` (ICU-collation dependent) must never feed a\n * digest.\n */\nexport function compareCodepoints(left: string, right: string): number {\n\treturn left < right ? -1 : left > right ? 1 : 0;\n}\n\nconst RECIPIENT_POLICY_ID_CONTROL_OR_FORMAT_CHARACTER = /[\\p{Cc}\\p{Cf}]/u;\n\nfunction isStrictRecipientPolicyText(value: unknown, maxUtf16Units: number): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length > 0 &&\n\t\tvalue === value.trim() &&\n\t\tvalue.length <= maxUtf16Units &&\n\t\t!RECIPIENT_POLICY_ID_CONTROL_OR_FORMAT_CHARACTER.test(value)\n\t);\n}\n\nexport function isStrictRecipientPolicyId(value: unknown): value is string {\n\treturn isStrictRecipientPolicyText(value, 256);\n}\n\nexport function isStrictRecipientPolicyProjectIdentity(value: unknown): value is string {\n\treturn isStrictRecipientPolicyText(value, 2_048);\n}\n\nconst INVALID_CANONICAL_JSON_MESSAGE = \"Recipient policy value must be strict JSON data\";\n\nfunction invalidCanonicalJson(): never {\n\tthrow new TypeError(INVALID_CANONICAL_JSON_MESSAGE);\n}\n\nfunction serializeJsonString(value: string): string {\n\tconst serialized = JSON.stringify(value);\n\tif (serialized === undefined) return invalidCanonicalJson();\n\treturn serialized;\n}\n\nfunction canonicalJson(value: unknown, ancestors: WeakSet<object>): string {\n\tif (value === null) return \"null\";\n\tif (typeof value === \"boolean\") return value ? \"true\" : \"false\";\n\tif (typeof value === \"string\") return serializeJsonString(value);\n\tif (typeof value === \"number\") {\n\t\tif (!Number.isFinite(value) || Object.is(value, -0)) return invalidCanonicalJson();\n\t\treturn String(value);\n\t}\n\tif (typeof value !== \"object\") return invalidCanonicalJson();\n\tif (ancestors.has(value)) return invalidCanonicalJson();\n\n\tancestors.add(value);\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tif (Object.getPrototypeOf(value) !== Array.prototype) return invalidCanonicalJson();\n\t\t\tconst keys = Reflect.ownKeys(value);\n\t\t\tif (keys.length !== value.length + 1 || keys.some((key) => typeof key !== \"string\")) {\n\t\t\t\treturn invalidCanonicalJson();\n\t\t\t}\n\t\t\tconst children: string[] = [];\n\t\t\tfor (let index = 0; index < value.length; index += 1) {\n\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, String(index));\n\t\t\t\tif (!descriptor?.enumerable || !(\"value\" in descriptor)) return invalidCanonicalJson();\n\t\t\t\tchildren.push(canonicalJson(descriptor.value, ancestors));\n\t\t\t}\n\t\t\treturn `[${children.join(\",\")}]`;\n\t\t}\n\n\t\tconst prototype = Object.getPrototypeOf(value);\n\t\tif (prototype !== Object.prototype && prototype !== null) return invalidCanonicalJson();\n\t\tconst entries = Reflect.ownKeys(value).map((key): [string, unknown] => {\n\t\t\tif (typeof key !== \"string\") return invalidCanonicalJson();\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\t\tif (!descriptor?.enumerable || !(\"value\" in descriptor)) return invalidCanonicalJson();\n\t\t\treturn [key, descriptor.value];\n\t\t});\n\t\treturn `{${entries\n\t\t\t.toSorted(([left], [right]) => compareCodepoints(left, right))\n\t\t\t.map(([key, child]) => `${serializeJsonString(key)}:${canonicalJson(child, ancestors)}`)\n\t\t\t.join(\",\")}}`;\n\t} finally {\n\t\tancestors.delete(value);\n\t}\n}\n\nexport function canonicalRecipientPolicyJson(value: unknown): string {\n\treturn canonicalJson(value, new WeakSet());\n}\n\nexport function recipientPolicyDigest(prefix: string, value: unknown): string {\n\t// Node replaces unpaired UTF-16 surrogates with U+FFFD during UTF-8\n\t// encoding, so accepting them would make distinct domains hash identically.\n\tif (prefix.includes(\"\\0\") || !prefix.isWellFormed()) {\n\t\tthrow new TypeError(\"Recipient policy digest prefix must be well-formed without NUL\");\n\t}\n\treturn `${prefix}:${createHash(\"sha256\")\n\t\t.update(prefix, \"utf8\")\n\t\t.update(\"\\0\", \"utf8\")\n\t\t.update(canonicalRecipientPolicyJson(value), \"utf8\")\n\t\t.digest(\"hex\")}`;\n}\n\n/**\n * Compatibility digest for identifiers persisted by released recipient-policy\n * flows before domain separation was introduced. New digest domains must use\n * `recipientPolicyDigest`; changing these bytes requires an explicit DB rekey.\n */\nexport function legacyRecipientPolicyDigest(prefix: string, value: unknown): string {\n\treturn `${prefix}:${createHash(\"sha256\")\n\t\t.update(canonicalRecipientPolicyJson(value), \"utf8\")\n\t\t.digest(\"hex\")}`;\n}\n\n/**\n * Decision and membership provenances owned by the invite flows. Activation\n * deliberately preserves these rows and readiness must tolerate them; every\n * layer that classifies invite ownership must use this single set —\n * hand-repeated literals with opposite polarity (allowlist vs denylist) are\n * how the two sides drift apart.\n */\nexport const INVITE_DECISION_PROVENANCES = [\"team_invite\", \"coordinator_invite\"] as const;\n\n/**\n * Frozen compatibility identifier persisted by released legacy Team drafts.\n * Changing the JSON tuple bytes or truncation requires an explicit DB rekey.\n */\nexport function legacyTeamCandidateId(coordinatorId: string, groupId: string): string {\n\tconst digest = createHash(\"sha256\")\n\t\t.update(JSON.stringify([coordinatorId, groupId]))\n\t\t.digest(\"hex\")\n\t\t.slice(0, 32);\n\treturn `legacy-team-candidate:${digest}`;\n}\n\nexport function legacyTeamProjectRef(candidateId: string, sourceProjectIdentity: string): string {\n\treturn recipientPolicyDigest(\"legacy-team-project-ref-v1\", [candidateId, sourceProjectIdentity]);\n}\n\nexport function legacyTeamCanonicalProjectRef(\n\tcandidateId: string,\n\tcanonicalProjectIdentity: string,\n): string {\n\treturn recipientPolicyDigest(\"legacy-team-canonical-project-ref-v1\", [\n\t\tcandidateId,\n\t\tcanonicalProjectIdentity,\n\t]);\n}\n\nexport function legacyTeamDeviceRef(candidateId: string, deviceId: string): string {\n\treturn recipientPolicyDigest(\"legacy-team-device-ref-v1\", [candidateId, deviceId]);\n}\n\nexport function deterministicPolicyTeamId(teamCandidateId: string): string {\n\treturn legacyRecipientPolicyDigest(\"policy-team-v1\", teamCandidateId);\n}\n\nexport function legacyTeamRosterFingerprint(\n\tdevices: ReadonlyArray<{\n\t\tdeviceId: string;\n\t\tfingerprint: string;\n\t\tenabled: boolean;\n\t\tidentityId: string | null;\n\t}>,\n): string {\n\treturn recipientPolicyDigest(\n\t\t\"legacy-team-roster-v1\",\n\t\tdevices\n\t\t\t.map((device) => ({\n\t\t\t\tdeviceId: device.deviceId,\n\t\t\t\tfingerprint: device.fingerprint,\n\t\t\t\tenabled: device.enabled,\n\t\t\t\tidentityId: device.identityId,\n\t\t\t}))\n\t\t\t.toSorted((left, right) => compareCodepoints(left.deviceId, right.deviceId)),\n\t);\n}\n","import {\n\tLEGACY_TEAM_SETUP_MAX_DEVICES,\n\tLEGACY_TEAM_SETUP_MAX_PROJECTS,\n} from \"./legacy-team-setup-limits.js\";\nimport {\n\tcompareCodepoints,\n\tdeterministicPolicyTeamId,\n\tlegacyTeamCandidateId,\n} from \"./recipient-policy-identifiers.js\";\n\nexport const COORDINATOR_LEGACY_TEAM_COMPLETION_VERSION = 1 as const;\nexport const COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_GROUPS = 50;\nexport const COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS = 500;\nexport const COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES = 1_500_000;\nexport const COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES =\n\t25 * COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES;\nconst COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_IDENTIFIER_CHARS = 256;\nconst COORDINATOR_LEGACY_TEAM_COMPLETION_RECORD_ENVELOPE_BYTES = 64;\nexport const COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_RESPONSE_BYTES =\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES +\n\t(COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_IDENTIFIER_CHARS +\n\t\tCOORDINATOR_LEGACY_TEAM_COMPLETION_RECORD_ENVELOPE_BYTES) *\n\t\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS +\n\t1024;\nexport const COORDINATOR_LEGACY_TEAM_COMPLETION_CONFLICT = \"completion_conflict\" as const;\n\nexport interface CoordinatorLegacyTeamCompletionMembershipV1 {\n\tidentity_id: string;\n\trole: \"member\";\n}\n\n/**\n * Who asserted an included device's Identity. `self` is the uploading device's\n * own assignment. `label` is that device's guess about another device. It keeps\n * Team access but never counts as ownership evidence. Manifests written before\n * this field existed omit it, and their rows keep the old meaning.\n */\nexport type CoordinatorLegacyTeamCompletionIdentityEvidence = \"self\" | \"label\";\n\nexport interface CoordinatorLegacyTeamCompletionDeviceDecisionV1 {\n\tdevice_id: string;\n\tkey_fingerprint: string;\n\tenabled: boolean;\n\tidentity_id: string | null;\n\tdecision: \"included\" | \"excluded\";\n\tidentity_evidence?: CoordinatorLegacyTeamCompletionIdentityEvidence;\n}\n\n/** False only for a decision another device guessed; such rows never prove ownership. */\nexport function legacyDecisionCountsAsOwner(\n\tdecision: Pick<CoordinatorLegacyTeamCompletionDeviceDecisionV1, \"identity_evidence\">,\n): boolean {\n\treturn decision.identity_evidence !== \"label\";\n}\n\n/**\n * SQL form of {@link legacyDecisionCountsAsOwner} for one `json_each` element,\n * e.g. `legacyDecisionCountsAsOwnerSql(\"d.value\")`. Stored rows are canonical,\n * but an unexpected value must still fail closed: a grant counts only `self` or\n * an absent mark, and a denial counts everything except an explicit label.\n */\nexport function legacyDecisionCountsAsOwnerSql(\n\telement: string,\n\tuse: \"grant\" | \"deny\" = \"grant\",\n): string {\n\tif (use === \"deny\") return `json_extract(${element}, '$.identity_evidence') IS NOT 'label'`;\n\treturn `coalesce(json_extract(${element}, '$.identity_evidence'), 'self') = 'self'`;\n}\n\nexport interface CoordinatorLegacyTeamCompletionProjectMappingV1 {\n\tproject_ref: string;\n\tresolved_project_ref: string;\n\tscope_id: string;\n}\n\nexport interface CoordinatorLegacyTeamCompletionRecipientV1 {\n\tresolved_project_ref: string;\n\tteam_id: string;\n}\n\nexport interface CoordinatorLegacyTeamCompletionManifestV1 {\n\tversion: typeof COORDINATOR_LEGACY_TEAM_COMPLETION_VERSION;\n\tcoordinator_id: string;\n\tcandidate_ref: string;\n\tcandidate_digest: string;\n\tteam_id: string;\n\tteam_digest: string;\n\tsource_digest: string;\n\tfinish_digest: string;\n\taccess_delta_digest: string;\n\tteam: {\n\t\tdisplay_name: string;\n\t\tpolicy_revision: string;\n\t\tdevice_eligibility_mode: \"reviewed_allowlist\";\n\t};\n\tmemberships: CoordinatorLegacyTeamCompletionMembershipV1[];\n\tdevice_decisions: CoordinatorLegacyTeamCompletionDeviceDecisionV1[];\n\tproject_mappings: CoordinatorLegacyTeamCompletionProjectMappingV1[];\n\tproject_recipients: CoordinatorLegacyTeamCompletionRecipientV1[];\n\tcompleted_at: string;\n}\n\nexport interface CoordinatorLegacyTeamCompletionWriteResult {\n\tstatus: \"created\" | \"existing\";\n\tmanifest: CoordinatorLegacyTeamCompletionManifestV1;\n}\n\nexport interface CoordinatorLegacyTeamCompletionRecord {\n\tgroup_id: string;\n\tmanifest: CoordinatorLegacyTeamCompletionManifestV1;\n}\n\nexport interface CoordinatorLegacyTeamCompletionScopeBinding {\n\tscope_id: string | null;\n\tauthority_type: string | null;\n\tcoordinator_id: string | null;\n\tgroup_id: string | null;\n\tstatus: string | null;\n}\n\nexport class CoordinatorLegacyTeamCompletionConflictError extends Error {\n\treadonly code = COORDINATOR_LEGACY_TEAM_COMPLETION_CONFLICT;\n\n\tconstructor() {\n\t\tsuper(COORDINATOR_LEGACY_TEAM_COMPLETION_CONFLICT);\n\t\tthis.name = \"CoordinatorLegacyTeamCompletionConflictError\";\n\t}\n}\n\nfunction invalid(): never {\n\tthrow new Error(\"completion_manifest_invalid\");\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) invalid();\n\treturn value as Record<string, unknown>;\n}\n\nfunction exactFields(value: Record<string, unknown>, fields: readonly string[]): void {\n\tconst allowed = new Set(fields);\n\tif (Object.keys(value).some((field) => !allowed.has(field))) invalid();\n}\n\nfunction isLocalArtifactPath(value: string): boolean {\n\treturn /^(?:[\\\\/]{2}|\\.{1,2}[\\\\/]|\\/|~[\\\\/]|[a-z]:[\\\\/]|file:)/iu.test(value);\n}\n\nfunction identifier(value: unknown): string {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\t!value ||\n\t\tvalue !== value.trim() ||\n\t\tvalue.length > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_IDENTIFIER_CHARS ||\n\t\t/[\\p{Cc}\\p{Cf}]/u.test(value) ||\n\t\tisLocalArtifactPath(value)\n\t) {\n\t\tinvalid();\n\t}\n\treturn value;\n}\n\nfunction digest(value: unknown): string {\n\tconst normalized = identifier(value);\n\tif (!/^[a-f0-9]{64}$/u.test(normalized)) invalid();\n\treturn normalized;\n}\n\nfunction displayName(value: unknown): string {\n\tif (typeof value !== \"string\") invalid();\n\tconst normalized = value.normalize(\"NFC\").trim();\n\tif (\n\t\t!normalized ||\n\t\t[...normalized].length > 120 ||\n\t\t/[\\p{Cc}\\p{Cf}]/u.test(normalized) ||\n\t\tisLocalArtifactPath(normalized)\n\t) {\n\t\tinvalid();\n\t}\n\treturn normalized;\n}\n\nfunction timestamp(value: unknown): string {\n\tif (typeof value !== \"string\" || !value) invalid();\n\tconst parsed = new Date(value);\n\tif (Number.isNaN(parsed.getTime()) || parsed.toISOString() !== value) invalid();\n\treturn value;\n}\n\nfunction array(value: unknown, max: number): unknown[] {\n\tif (!Array.isArray(value) || value.length > max) invalid();\n\treturn value;\n}\n\nfunction uniqueSorted<T>(items: T[], key: (item: T) => string): T[] {\n\tconst sorted = items.toSorted((left, right) => compareCodepoints(key(left), key(right)));\n\tif (sorted.some((item, index) => index > 0 && key(sorted[index - 1] as T) === key(item)))\n\t\tinvalid();\n\treturn sorted;\n}\n\nexport function normalizeCoordinatorLegacyTeamCompletionGroupIds(value: unknown): string[] {\n\treturn uniqueSorted(\n\t\tarray(value, COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_GROUPS).map(identifier),\n\t\t(item) => item,\n\t);\n}\n\nexport function normalizeCoordinatorLegacyTeamCompletionCandidateRef(value: unknown): string {\n\tconst normalized = identifier(value);\n\tif (!/^legacy-team-candidate:[a-f0-9]{32}$/u.test(normalized)) invalid();\n\treturn normalized;\n}\n\nfunction normalizeDeviceDecision(value: unknown): CoordinatorLegacyTeamCompletionDeviceDecisionV1 {\n\tconst item = record(value);\n\texactFields(item, [\n\t\t\"device_id\",\n\t\t\"key_fingerprint\",\n\t\t\"enabled\",\n\t\t\"identity_id\",\n\t\t\"decision\",\n\t\t\"identity_evidence\",\n\t]);\n\tif (item.decision !== \"included\" && item.decision !== \"excluded\") invalid();\n\tif (typeof item.enabled !== \"boolean\") invalid();\n\tconst identityId = item.identity_id == null ? null : identifier(item.identity_id);\n\tif ((item.decision === \"included\") !== Boolean(identityId)) invalid();\n\tif (item.decision === \"included\" && !item.enabled) invalid();\n\tconst decision: CoordinatorLegacyTeamCompletionDeviceDecisionV1[\"decision\"] = item.decision;\n\tconst normalized: CoordinatorLegacyTeamCompletionDeviceDecisionV1 = {\n\t\tdevice_id: identifier(item.device_id),\n\t\tkey_fingerprint: digest(item.key_fingerprint),\n\t\tenabled: item.enabled,\n\t\tidentity_id: identityId,\n\t\tdecision,\n\t};\n\t// Absent stays absent, so manifests written before the field keep their exact bytes.\n\tif (!Object.hasOwn(item, \"identity_evidence\")) return normalized;\n\tif (decision !== \"included\") invalid();\n\tif (item.identity_evidence !== \"self\" && item.identity_evidence !== \"label\") invalid();\n\treturn { ...normalized, identity_evidence: item.identity_evidence };\n}\n\n/**\n * A manifest either predates evidence or marks every included device, and at\n * most one device (the uploader) can speak for itself.\n */\nfunction requireConsistentIdentityEvidence(\n\tdecisions: readonly CoordinatorLegacyTeamCompletionDeviceDecisionV1[],\n): void {\n\tconst included = decisions.filter((decision) => decision.decision === \"included\");\n\tconst marked = included.filter((decision) => decision.identity_evidence !== undefined);\n\tif (marked.length === 0) return;\n\tif (marked.length !== included.length) invalid();\n\tif (marked.filter((decision) => decision.identity_evidence === \"self\").length > 1) invalid();\n}\n\nexport function normalizeCoordinatorLegacyTeamCompletionManifest(\n\tvalue: unknown,\n): CoordinatorLegacyTeamCompletionManifestV1 {\n\tconst input = record(value);\n\texactFields(input, [\n\t\t\"version\",\n\t\t\"coordinator_id\",\n\t\t\"candidate_ref\",\n\t\t\"candidate_digest\",\n\t\t\"team_id\",\n\t\t\"team_digest\",\n\t\t\"source_digest\",\n\t\t\"finish_digest\",\n\t\t\"access_delta_digest\",\n\t\t\"team\",\n\t\t\"memberships\",\n\t\t\"device_decisions\",\n\t\t\"project_mappings\",\n\t\t\"project_recipients\",\n\t\t\"completed_at\",\n\t]);\n\tif (input.version !== COORDINATOR_LEGACY_TEAM_COMPLETION_VERSION) invalid();\n\tconst team = record(input.team);\n\texactFields(team, [\"display_name\", \"policy_revision\", \"device_eligibility_mode\"]);\n\tif (team.device_eligibility_mode !== \"reviewed_allowlist\") invalid();\n\tconst teamId = identifier(input.team_id);\n\tconst memberships = uniqueSorted(\n\t\tarray(input.memberships, LEGACY_TEAM_SETUP_MAX_DEVICES).map((value) => {\n\t\t\tconst item = record(value);\n\t\t\texactFields(item, [\"identity_id\", \"role\"]);\n\t\t\tif (item.role !== \"member\") invalid();\n\t\t\treturn { identity_id: identifier(item.identity_id), role: \"member\" as const };\n\t\t}),\n\t\t(item) => item.identity_id,\n\t);\n\tconst deviceDecisions = uniqueSorted(\n\t\tarray(input.device_decisions, LEGACY_TEAM_SETUP_MAX_DEVICES).map(normalizeDeviceDecision),\n\t\t(item) => item.device_id,\n\t);\n\tif (deviceDecisions.length === 0) invalid();\n\trequireConsistentIdentityEvidence(deviceDecisions);\n\tconst membershipIds = new Set(memberships.map((membership) => membership.identity_id));\n\tconst includedIdentityIds = new Set(\n\t\tdeviceDecisions.flatMap((decision) => (decision.identity_id ? [decision.identity_id] : [])),\n\t);\n\tif (\n\t\tmembershipIds.size !== includedIdentityIds.size ||\n\t\t[...includedIdentityIds].some((identityId) => !membershipIds.has(identityId))\n\t) {\n\t\tinvalid();\n\t}\n\tconst projectMappings = uniqueSorted(\n\t\tarray(input.project_mappings, LEGACY_TEAM_SETUP_MAX_PROJECTS).map((value) => {\n\t\t\tconst item = record(value);\n\t\t\texactFields(item, [\"project_ref\", \"resolved_project_ref\", \"scope_id\"]);\n\t\t\tconst projectRef = identifier(item.project_ref);\n\t\t\tconst resolvedProjectRef = identifier(item.resolved_project_ref);\n\t\t\tif (!/^legacy-team-project-ref-v1:[0-9a-f]{64}$/u.test(projectRef)) invalid();\n\t\t\tif (!/^legacy-team-resolved-project-ref-v1:[0-9a-f]{64}$/u.test(resolvedProjectRef)) {\n\t\t\t\tinvalid();\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tproject_ref: projectRef,\n\t\t\t\tresolved_project_ref: resolvedProjectRef,\n\t\t\t\tscope_id: identifier(item.scope_id),\n\t\t\t};\n\t\t}),\n\t\t(item) => item.project_ref,\n\t);\n\tconst resolvedScopes = new Map<string, string>();\n\tfor (const mapping of projectMappings) {\n\t\tconst priorScopeId = resolvedScopes.get(mapping.resolved_project_ref);\n\t\tif (priorScopeId && priorScopeId !== mapping.scope_id) invalid();\n\t\tresolvedScopes.set(mapping.resolved_project_ref, mapping.scope_id);\n\t}\n\tconst projectRecipients = uniqueSorted(\n\t\tarray(input.project_recipients, LEGACY_TEAM_SETUP_MAX_PROJECTS).map((value) => {\n\t\t\tconst item = record(value);\n\t\t\texactFields(item, [\"resolved_project_ref\", \"team_id\"]);\n\t\t\tconst recipientTeamId = identifier(item.team_id);\n\t\t\tif (recipientTeamId !== teamId) invalid();\n\t\t\tconst resolvedProjectRef = identifier(item.resolved_project_ref);\n\t\t\tif (!/^legacy-team-resolved-project-ref-v1:[0-9a-f]{64}$/u.test(resolvedProjectRef)) {\n\t\t\t\tinvalid();\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tresolved_project_ref: resolvedProjectRef,\n\t\t\t\tteam_id: recipientTeamId,\n\t\t\t};\n\t\t}),\n\t\t(item) => item.resolved_project_ref,\n\t);\n\tconst mappedRecipientRefs = [\n\t\t...new Set(projectMappings.map((mapping) => mapping.resolved_project_ref)),\n\t].toSorted(compareCodepoints);\n\tconst recipientRefs = projectRecipients.map((recipient) => recipient.resolved_project_ref);\n\tif (JSON.stringify(recipientRefs) !== JSON.stringify(mappedRecipientRefs)) {\n\t\tinvalid();\n\t}\n\tconst manifest: CoordinatorLegacyTeamCompletionManifestV1 = {\n\t\tversion: COORDINATOR_LEGACY_TEAM_COMPLETION_VERSION,\n\t\tcoordinator_id: identifier(input.coordinator_id),\n\t\tcandidate_ref: normalizeCoordinatorLegacyTeamCompletionCandidateRef(input.candidate_ref),\n\t\tcandidate_digest: digest(input.candidate_digest),\n\t\tteam_id: teamId,\n\t\tteam_digest: digest(input.team_digest),\n\t\tsource_digest: digest(input.source_digest),\n\t\tfinish_digest: digest(input.finish_digest),\n\t\taccess_delta_digest: digest(input.access_delta_digest),\n\t\tteam: {\n\t\t\tdisplay_name: displayName(team.display_name),\n\t\t\tpolicy_revision: digest(team.policy_revision),\n\t\t\tdevice_eligibility_mode: \"reviewed_allowlist\",\n\t\t},\n\t\tmemberships,\n\t\tdevice_decisions: deviceDecisions,\n\t\tproject_mappings: projectMappings,\n\t\tproject_recipients: projectRecipients,\n\t\tcompleted_at: timestamp(input.completed_at),\n\t};\n\tif (\n\t\tnew TextEncoder().encode(JSON.stringify(manifest)).byteLength >\n\t\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES\n\t) {\n\t\tinvalid();\n\t}\n\treturn manifest;\n}\n\nexport function canonicalCoordinatorLegacyTeamCompletionManifestJson(value: unknown): string {\n\treturn JSON.stringify(normalizeCoordinatorLegacyTeamCompletionManifest(value));\n}\n\nexport function requireCoordinatorLegacyTeamCompletionTeamBinding(\n\tmanifest: CoordinatorLegacyTeamCompletionManifestV1,\n): void {\n\tif (manifest.team_id !== deterministicPolicyTeamId(manifest.candidate_ref)) invalid();\n}\n\nexport function requireCoordinatorLegacyTeamCompletionCandidateBinding(\n\tmanifest: CoordinatorLegacyTeamCompletionManifestV1,\n\tgroupId: string,\n): void {\n\tif (legacyTeamCandidateId(manifest.coordinator_id, groupId) !== manifest.candidate_ref) invalid();\n}\n\nexport function requireCoordinatorLegacyTeamCompletionScopeBindings(\n\tmanifest: CoordinatorLegacyTeamCompletionManifestV1,\n\tgroupId: string,\n\tbindings: CoordinatorLegacyTeamCompletionScopeBinding[],\n): string | null {\n\trequireCoordinatorLegacyTeamCompletionCandidateBinding(manifest, groupId);\n\tconst requestedScopeIds = new Set(manifest.project_mappings.map((mapping) => mapping.scope_id));\n\tif (bindings.length !== requestedScopeIds.size) invalid();\n\tconst coordinatorId = manifest.coordinator_id;\n\tfor (const binding of bindings) {\n\t\tif (\n\t\t\t!binding.scope_id ||\n\t\t\t!requestedScopeIds.has(binding.scope_id) ||\n\t\t\tbinding.authority_type !== \"coordinator\" ||\n\t\t\t!binding.coordinator_id ||\n\t\t\tbinding.group_id !== groupId ||\n\t\t\tbinding.status !== \"active\" ||\n\t\t\tbinding.coordinator_id !== coordinatorId\n\t\t) {\n\t\t\tinvalid();\n\t\t}\n\t}\n\treturn coordinatorId;\n}\n","import { parseSshEd25519PublicKeyForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport {\n\ttype CoordinatorLegacyTeamCompletionManifestV1,\n\tcanonicalCoordinatorLegacyTeamCompletionManifestJson,\n\tnormalizeCoordinatorLegacyTeamCompletionManifest,\n\trequireCoordinatorLegacyTeamCompletionCandidateBinding,\n} from \"./coordinator-legacy-team-completion.js\";\n\nexport interface ControllerHistoryRecord {\n\tgroup_id: string;\n\tcandidate_ref: string;\n\tmanifest_version: number;\n\tcompleted_at: string;\n\tcreated_at: string;\n\tmanifest_json: string;\n}\ninterface HistoryKey {\n\tpublic_key: string;\n\tfingerprint: string;\n}\nexport interface ControllerHistorySnapshot {\n\tcoordinatorId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n\t/** Actual canonical subject aliases, not discovery-filter matches. */\n\tkeys: HistoryKey[];\n\t/** Private race-check inputs; never part of the operator's evidence digest. */\n\tdiscoveryKeys: string[];\n\tdiscoveryFragments: string[];\n\tfingerprints: string[];\n\trecords: ControllerHistoryRecord[];\n}\nexport interface ControllerHistoryEvidence extends ControllerHistoryRecord {\n\tmanifest: CoordinatorLegacyTeamCompletionManifestV1;\n}\nexport interface ControllerHistoryInput {\n\tcoordinatorId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n}\n\nconst MAX_BYTES = 750_000;\n// The encoded snapshot already caps record metadata and JSON-escaped manifest_json\n// at MAX_BYTES. Its parsed manifests add at most MAX_BYTES more; reserve the old\n// response envelope budget for enrollment, invitations, reasons and digest fields.\nexport const CONTROLLER_REVIEW_MAX_RESPONSE_BYTES = 2 * MAX_BYTES + 16_384;\nconst MAX_KEYS = 4096;\nconst MAX_DISCOVERY_KEYS = 8192;\nconst MAX_RECORDS = 500;\n\n// This same predicate selects preview evidence and detects newly relevant rows in\n// the winning write. Malformed unrelated records are not a reason to deny review.\n// Unparseable rows containing a target reference require operator investigation.\n// Enrollment removal must not erase an attested key/fingerprint binding. UNION\n// deduplicates the ordinary new review's existing enrollment pair, while the\n// coordinator filter prevents another namespace's retained keys entering proof.\n// Only canonical parsing below selects aliases; manifest fingerprints add no keys.\nexport const CONTROLLER_HISTORY_CTE = `history_input AS MATERIALIZED (\n SELECT json_extract(value, '$.legacyHistory') AS value FROM snapshot\n), history_key_sources AS NOT MATERIALIZED (\n SELECT public_key, fingerprint FROM enrolled_devices\n UNION\n SELECT a.public_key, a.fingerprint FROM coordinator_auth_controller_attestations a\n CROSS JOIN history_input h\n WHERE a.coordinator_id = json_extract(h.value, '$.coordinatorId')\n), history_rows AS NOT MATERIALIZED (\n SELECT c.*, CASE WHEN json_valid(c.manifest_json) THEN c.manifest_json ELSE '{}' END AS parsed\n FROM coordinator_legacy_team_completions c\n), live_history AS MATERIALIZED (\n SELECT c.group_id, c.candidate_ref, c.manifest_version, c.completed_at, c.created_at,\n CASE WHEN length(CAST(c.manifest_json AS BLOB)) <= ${MAX_BYTES} THEN c.manifest_json ELSE NULL END AS manifest_json\n FROM history_rows c CROSS JOIN history_input h\n WHERE h.value IS NOT NULL\n AND (json_extract(c.parsed, '$.coordinator_id') = json_extract(h.value, '$.coordinatorId')\n OR json_extract(c.parsed, '$.coordinator_id') IS NULL)\n AND (EXISTS (\n SELECT 1 FROM json_each(c.parsed, '$.device_decisions') d\n WHERE json_extract(CASE WHEN d.type = 'object' THEN d.value ELSE '{}' END, '$.device_id') = json_extract(h.value, '$.deviceId')\n OR json_extract(CASE WHEN d.type = 'object' THEN d.value ELSE '{}' END, '$.key_fingerprint')\n IN (SELECT value FROM json_each(h.value, '$.fingerprints'))\n OR ((d.type <> 'object'\n OR json_type(CASE WHEN d.type = 'object' THEN d.value ELSE '{}' END, '$.device_id') IS NOT 'text'\n OR json_type(CASE WHEN d.type = 'object' THEN d.value ELSE '{}' END, '$.key_fingerprint') IS NOT 'text')\n AND (instr(CASE WHEN d.type = 'text' THEN json_quote(d.value) ELSE d.value END,\n json_quote(json_extract(h.value, '$.deviceId'))) > 0\n OR EXISTS (SELECT 1 FROM json_each(h.value, '$.fingerprints') f\n WHERE instr(d.value, f.value) > 0)))\n ) OR ((json_valid(c.manifest_json) = 0 OR json_type(c.parsed, '$.device_decisions') IS NOT 'array') AND (\n instr(c.manifest_json, json_quote(json_extract(h.value, '$.deviceId'))) > 0\n OR EXISTS (SELECT 1 FROM json_each(h.value, '$.fingerprints') f\n WHERE instr(c.manifest_json, f.value) > 0)\n ))) LIMIT ${MAX_RECORDS + 1}\n), snapshot_history AS MATERIALIZED (\n SELECT json_extract(j.value, '$.group_id') AS group_id,\n json_extract(j.value, '$.candidate_ref') AS candidate_ref,\n json_extract(j.value, '$.manifest_version') AS manifest_version,\n json_extract(j.value, '$.completed_at') AS completed_at,\n json_extract(j.value, '$.created_at') AS created_at,\n json_extract(j.value, '$.manifest_json') AS manifest_json\n FROM history_input h, json_each(h.value, '$.records') j\n), snapshot_history_keys AS MATERIALIZED (\n SELECT json_extract(j.value, '$.public_key') AS public_key,\n json_extract(j.value, '$.fingerprint') AS fingerprint\n FROM history_input h, json_each(h.value, '$.keys') j\n), snapshot_discovery_keys AS MATERIALIZED (\n SELECT j.value AS public_key FROM history_input h, json_each(h.value, '$.discoveryKeys') j\n), discovery_lines AS NOT MATERIALIZED (\n SELECT public_key,\n ltrim(replace(replace(replace(replace(replace(public_key,\n char(9), ' '), char(10), ' '), char(11), ' '), char(12), ' '), char(13), ' '), ' ') AS line\n FROM history_key_sources\n), discovery_tails AS NOT MATERIALIZED (\n SELECT public_key, CASE WHEN substr(line, 1, 12) = 'ssh-ed25519 '\n THEN ltrim(substr(line, 13), ' ') ELSE NULL END AS tail FROM discovery_lines\n), discovery_tokens AS NOT MATERIALIZED (\n SELECT public_key, CASE WHEN tail IS NOT NULL\n THEN substr(tail, 1, instr(tail || ' ', ' ') - 1) ELSE NULL END AS token\n FROM discovery_tails\n), live_discovery_keys AS MATERIALIZED (\n SELECT DISTINCT e.public_key FROM discovery_tokens e CROSS JOIN history_input h\n WHERE e.public_key = json_extract(h.value, '$.publicKey')\n OR instr(e.public_key, char(0)) > 0\n OR e.token IS NULL\n OR EXISTS (SELECT 1 FROM json_each(h.value, '$.discoveryFragments') f\n WHERE instr(replace(replace(e.token, '-', '+'), '_', '/'), f.value) > 0)\n OR e.token GLOB '*[^A-Za-z0-9+/=_-]*'\n LIMIT ${MAX_DISCOVERY_KEYS + 1}\n), live_history_keys AS MATERIALIZED (\n SELECT DISTINCT e.public_key, e.fingerprint FROM history_key_sources e\n WHERE e.public_key IN (SELECT public_key FROM snapshot_history_keys)\n LIMIT ${MAX_KEYS + 1}\n)`;\n\nexport const CONTROLLER_HISTORY_KEYS_SQL = `WITH snapshot(value) AS (SELECT ?),\n ${CONTROLLER_HISTORY_CTE}\n SELECT public_key FROM live_discovery_keys ORDER BY public_key`;\n\nconst CONTROLLER_HISTORY_SUBJECT_KEYS_SQL = `WITH snapshot(value) AS (SELECT ?),\n ${CONTROLLER_HISTORY_CTE}\n SELECT public_key, fingerprint FROM live_history_keys ORDER BY public_key, fingerprint`;\n\nexport const CONTROLLER_HISTORY_SELECT_SQL = `WITH snapshot(value) AS (SELECT ?),\n ${CONTROLLER_HISTORY_CTE}\n SELECT group_id, candidate_ref, manifest_version, completed_at, created_at,\n CASE WHEN SUM(length(CAST(manifest_json AS BLOB))) OVER () <= ${MAX_BYTES}\n THEN manifest_json ELSE NULL END AS manifest_json\n FROM live_history ORDER BY group_id, candidate_ref LIMIT ${MAX_RECORDS + 1}`;\n\nexport function parseControllerHistoryRecord(\n\trow: ControllerHistoryRecord,\n\tcoordinatorId: string,\n): ControllerHistoryEvidence {\n\tif (typeof row.group_id !== \"string\" || typeof row.manifest_json !== \"string\")\n\t\tthrow new Error(\"legacy_history_invalid\");\n\tconst manifest = normalizeCoordinatorLegacyTeamCompletionManifest(JSON.parse(row.manifest_json));\n\trequireCoordinatorLegacyTeamCompletionCandidateBinding(manifest, row.group_id);\n\t// Historical Team IDs are retained as evidence, not reinterpreted as owner authority.\n\tif (\n\t\tmanifest.coordinator_id !== coordinatorId ||\n\t\tmanifest.candidate_ref !== row.candidate_ref ||\n\t\tmanifest.version !== row.manifest_version ||\n\t\tmanifest.completed_at !== row.completed_at ||\n\t\ttypeof row.created_at !== \"string\" ||\n\t\t!Number.isFinite(Date.parse(row.created_at)) ||\n\t\tcanonicalCoordinatorLegacyTeamCompletionManifestJson(manifest) !== row.manifest_json\n\t)\n\t\tthrow new Error(\"legacy_history_invalid\");\n\treturn { ...row, manifest };\n}\n\nfunction matchingSubjectKeys(publicKey: string, candidates: string[]): string[] {\n\tconst subject = parseSshEd25519PublicKeyForRevocation(publicKey);\n\treturn candidates.filter((candidate) => {\n\t\tif (candidate === publicKey) return true;\n\t\tif (subject.kind !== \"ed25519\") return false;\n\t\tconst parsed = parseSshEd25519PublicKeyForRevocation(candidate);\n\t\treturn (\n\t\t\tparsed.kind === \"ed25519\" && subject.blob.every((byte, index) => byte === parsed.blob[index])\n\t\t);\n\t});\n}\n\n/** Discovery only: canonical parsing above, never a fragment match, decides alias identity.\n * For any wire offset, one raw-key offset in 0..2 starts on a base64 triplet\n * boundary. Its 27 bytes end before padding and encode to 36 contiguous chars.\n * SQL normalizes URL-safe characters. Any other non-base64 token character\n * (including Buffer-ignored junk or Unicode) takes the conservative GLOB path.\n * ASCII whitespace separates the key type, encoded token and ignored comments;\n * only that token is inspected, never comment punctuation or names. Prefixes\n * outside this ordinary syntax (such as Unicode separators) remain candidates.\n * Embedded NUL also remains a candidate: SQLite token functions stop there,\n * whereas the compatibility base64 decoder can ignore it inside the token.\n */\nexport function controllerHistoryDiscoveryFragments(publicKey: string): string[] {\n\tconst subject = parseSshEd25519PublicKeyForRevocation(publicKey);\n\tif (subject.kind !== \"ed25519\") return [];\n\tconst raw = subject.blob.subarray(19);\n\treturn [0, 1, 2].map((offset) => btoa(String.fromCharCode(...raw.subarray(offset, offset + 27))));\n}\n\nfunction subjectFingerprints(fingerprint: string, keys: HistoryKey[]): string[] {\n\treturn [...new Set([fingerprint, ...keys.map((key) => key.fingerprint)])].sort();\n}\n\n/** Discovery false positives pin classification races, but are not reviewed ownership evidence. */\nexport function controllerHistoryDigestEvidence(history: ControllerHistorySnapshot | undefined) {\n\tif (!history) return undefined;\n\tconst { discoveryKeys: _keys, discoveryFragments: _fragments, ...evidence } = history;\n\treturn evidence;\n}\n\n/** Both backends use the same targeted SELECT, limits and canonical parser. */\nexport async function captureControllerHistory(\n\tinput: ControllerHistoryInput,\n\tall: <T>(sql: string, values: string[]) => Promise<T[]>,\n): Promise<ControllerHistorySnapshot> {\n\tconst discoveryFragments = controllerHistoryDiscoveryFragments(input.publicKey);\n\tconst candidates = await all<{ public_key: string }>(CONTROLLER_HISTORY_KEYS_SQL, [\n\t\tJSON.stringify({ legacyHistory: { ...input, discoveryFragments } }),\n\t]);\n\tif (candidates.length > MAX_DISCOVERY_KEYS) throw new Error(\"legacy_history_too_large\");\n\tconst discoveryKeys = candidates.map((key) => key.public_key);\n\tconst subjectKeys = matchingSubjectKeys(input.publicKey, discoveryKeys);\n\tconst keys = await all<HistoryKey>(CONTROLLER_HISTORY_SUBJECT_KEYS_SQL, [\n\t\tJSON.stringify({\n\t\t\tlegacyHistory: {\n\t\t\t\tcoordinatorId: input.coordinatorId,\n\t\t\t\tkeys: subjectKeys.map((public_key) => ({ public_key })),\n\t\t\t},\n\t\t}),\n\t]);\n\tif (keys.length > MAX_KEYS) throw new Error(\"legacy_history_too_large\");\n\tconst history: ControllerHistorySnapshot = {\n\t\t...input,\n\t\tkeys,\n\t\tdiscoveryKeys,\n\t\tdiscoveryFragments,\n\t\tfingerprints: subjectFingerprints(input.fingerprint, keys),\n\t\trecords: [],\n\t};\n\tconst rows = await all<ControllerHistoryRecord>(CONTROLLER_HISTORY_SELECT_SQL, [\n\t\tJSON.stringify({ legacyHistory: history }),\n\t]);\n\tif (rows.length > MAX_RECORDS) throw new Error(\"legacy_history_too_large\");\n\thistory.records = rows.map((row) => {\n\t\tconst { manifest: _manifest, ...record } = parseControllerHistoryRecord(\n\t\t\trow,\n\t\t\tinput.coordinatorId,\n\t\t);\n\t\treturn record;\n\t});\n\tconst captured = captureControllerHistorySnapshot(history);\n\tif (!captured) throw new Error(\"legacy_history_invalid\");\n\treturn captured;\n}\n\nfunction captureData(value: unknown, budget: { remaining: number }, depth = 0): unknown {\n\tif (--budget.remaining < 0 || depth > 12) throw new Error(\"legacy_history_invalid\");\n\tif (typeof value === \"string\") {\n\t\tbudget.remaining -= value.length;\n\t\tif (budget.remaining < 0) throw new Error(\"legacy_history_too_large\");\n\t\treturn value;\n\t}\n\tif (value === null || typeof value === \"boolean\" || typeof value === \"number\") return value;\n\tif (!value || typeof value !== \"object\") throw new Error(\"legacy_history_invalid\");\n\tconst copy = captureProperties(value, budget, depth);\n\tif (!Array.isArray(value)) return copy;\n\tconst length = Object.getOwnPropertyDescriptor(value, \"length\")?.value;\n\tif (\n\t\t!Number.isSafeInteger(length) ||\n\t\tlength > MAX_DISCOVERY_KEYS ||\n\t\tObject.keys(copy).length !== length\n\t)\n\t\tthrow new Error(\"legacy_history_invalid\");\n\treturn Array.from({ length }, (_, index) => {\n\t\tif (!Object.hasOwn(copy, index)) throw new Error(\"legacy_history_invalid\");\n\t\treturn copy[String(index)];\n\t});\n}\n\nfunction captureProperties(\n\tvalue: object,\n\tbudget: { remaining: number },\n\tdepth: number,\n): Record<string, unknown> {\n\tconst copy: Record<string, unknown> = Object.create(null);\n\tfor (const key of Reflect.ownKeys(value)) {\n\t\tif (Array.isArray(value) && key === \"length\") continue;\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\tif (typeof key !== \"string\" || !descriptor || !Object.hasOwn(descriptor, \"value\"))\n\t\t\tthrow new Error(\"legacy_history_invalid\");\n\t\tcopy[key] = captureData(descriptor.value, budget, depth + 1);\n\t}\n\treturn copy;\n}\n\nfunction stringList(value: unknown): value is string[] {\n\treturn Array.isArray(value) && value.every((item) => typeof item === \"string\" && item.length > 0);\n}\n\nfunction sameStringSet(left: string[], right: string[]): boolean {\n\tconst expected = new Set(left);\n\treturn (\n\t\texpected.size === left.length &&\n\t\tright.length === expected.size &&\n\t\tright.every((item) => expected.delete(item))\n\t);\n}\n\nfunction validSubjectDiscovery(snapshot: ControllerHistorySnapshot): boolean {\n\tif (\n\t\t!stringList(snapshot.discoveryKeys) ||\n\t\tsnapshot.discoveryKeys.length > MAX_DISCOVERY_KEYS ||\n\t\t!Array.isArray(snapshot.discoveryFragments) ||\n\t\tJSON.stringify(snapshot.discoveryFragments) !==\n\t\t\tJSON.stringify(controllerHistoryDiscoveryFragments(snapshot.publicKey)) ||\n\t\t!sameStringSet(snapshot.discoveryKeys, snapshot.discoveryKeys)\n\t)\n\t\treturn false;\n\tconst expected = matchingSubjectKeys(snapshot.publicKey, snapshot.discoveryKeys);\n\tconst actual = [...new Set(snapshot.keys.map((key) => key.public_key))];\n\tif (!sameStringSet(expected, actual)) return false;\n\tif (\n\t\tnew Set(snapshot.keys.map((key) => JSON.stringify([key.public_key, key.fingerprint]))).size !==\n\t\tsnapshot.keys.length\n\t)\n\t\treturn false;\n\treturn (\n\t\tJSON.stringify(snapshot.fingerprints) ===\n\t\tJSON.stringify(subjectFingerprints(snapshot.fingerprint, snapshot.keys))\n\t);\n}\n\n/** Capture JSON data without invoking getters or toJSON on store capability inputs. */\nexport function captureControllerHistorySnapshot(value: unknown): ControllerHistorySnapshot | null {\n\ttry {\n\t\tconst encoded = JSON.stringify(captureData(value, { remaining: MAX_BYTES }));\n\t\tif (!encoded || new TextEncoder().encode(encoded).byteLength > MAX_BYTES) return null;\n\t\tconst snapshot = JSON.parse(encoded) as ControllerHistorySnapshot;\n\t\tif (\n\t\t\t!snapshot ||\n\t\t\t!Array.isArray(snapshot.keys) ||\n\t\t\tsnapshot.keys.length > MAX_KEYS ||\n\t\t\t!Array.isArray(snapshot.fingerprints) ||\n\t\t\t!Array.isArray(snapshot.records) ||\n\t\t\tsnapshot.records.length > MAX_RECORDS ||\n\t\t\t![\n\t\t\t\tsnapshot.coordinatorId,\n\t\t\t\tsnapshot.deviceId,\n\t\t\t\tsnapshot.publicKey,\n\t\t\t\tsnapshot.fingerprint,\n\t\t\t\t...snapshot.fingerprints,\n\t\t\t].every((field) => typeof field === \"string\" && field.length > 0) ||\n\t\t\t!snapshot.keys.every(\n\t\t\t\t(key) => typeof key.public_key === \"string\" && typeof key.fingerprint === \"string\",\n\t\t\t)\n\t\t)\n\t\t\treturn null;\n\t\tif (!validSubjectDiscovery(snapshot)) return null;\n\t\tconst ids = new Set<string>();\n\t\tfor (const row of snapshot.records) {\n\t\t\tparseControllerHistoryRecord(row, snapshot.coordinatorId);\n\t\t\tconst id = JSON.stringify([row.group_id, row.candidate_ref]);\n\t\t\tif (ids.has(id)) return null;\n\t\t\tids.add(id);\n\t\t}\n\t\treturn snapshot;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function parseControllerHistoryEvidence(\n\tvalue: unknown,\n\tcoordinatorId: string,\n): ControllerHistoryEvidence[] {\n\tconst copy = captureData(value, { remaining: MAX_BYTES * 3 });\n\tif (!Array.isArray(copy) || copy.length > MAX_RECORDS) throw new Error(\"legacy_history_invalid\");\n\treturn copy.map((row: ControllerHistoryEvidence) => {\n\t\tconst evidence = parseControllerHistoryRecord(row, coordinatorId);\n\t\tif (\n\t\t\tJSON.stringify(evidence.manifest) !==\n\t\t\tcanonicalCoordinatorLegacyTeamCompletionManifestJson(row.manifest)\n\t\t)\n\t\t\tthrow new Error(\"legacy_history_invalid\");\n\t\treturn evidence;\n\t});\n}\n","import {\n\ttype ControllerHistoryInput,\n\ttype ControllerHistorySnapshot,\n\tcaptureControllerHistorySnapshot,\n} from \"./coordinator-auth-controller-history.js\";\nimport type { CoordinatorAuthControllerOwnerSnapshot } from \"./coordinator-auth-controller-owner.js\";\n\n/** Persistence of completed, trusted admin reviews, not authentication of request JSON.\n * Future routes must authenticate the configured admin before invoking this capability.\n * Enrollment identity labels alone never create controller authority.\n */\nexport interface CoordinatorAuthControllerReviewInput {\n\tattestationId: string;\n\tcoordinatorId: string;\n\tidentityId: string;\n\tgroupId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n\treviewReceiptId: string;\n\tevidenceDigest: string;\n\t/** Optional for legacy trusted seed callers; operator routes always supply it. */\n\tverifiedSnapshot?: CoordinatorAuthControllerVerifiedSnapshot;\n}\n\nexport interface CoordinatorAuthControllerVerifiedSnapshot {\n\tenrollmentIdentityId: string | null;\n\taccountOwnerTarget?: CoordinatorAuthControllerOwnerSnapshot;\n\t/** Captured by the trusted history reader when supplied. */\n\tlegacyHistory?: ControllerHistorySnapshot;\n\tinvites: {\n\t\tinviteId: string;\n\t\tkind: \"team_member\" | \"add_device\";\n\t\tactorId: string;\n\t\tassignedIdentityId: string | null;\n\t\ttargetIdentityId: string | null;\n\t\tdigest: string;\n\t}[];\n}\n\nexport interface CoordinatorAuthControllerAttestation {\n\treadonly attestation_id: string;\n\treadonly coordinator_id: string;\n\treadonly identity_id: string;\n\treadonly group_id: string;\n\treadonly device_id: string;\n\treadonly public_key: string;\n\treadonly fingerprint: string;\n\treadonly review_receipt_id: string;\n\treadonly evidence_digest: string;\n\treadonly enrollment_identity_id: string | null;\n\treadonly revision: 1;\n\treadonly created_at: string;\n\treadonly revoked_at: string | null;\n}\n\nexport type CoordinatorAuthControllerCreateResult =\n\t| { kind: \"created\" | \"existing\"; attestation: CoordinatorAuthControllerAttestation }\n\t| {\n\t\t\tkind: \"rejected\";\n\t\t\terror:\n\t\t\t\t| \"invalid_review_input\"\n\t\t\t\t| \"enrollment_mismatch\"\n\t\t\t\t| \"review_stale\"\n\t\t\t\t| \"attestation_conflict\"\n\t\t\t\t| \"attestation_revoked\";\n\t };\n\nexport interface CoordinatorAuthControllerStore {\n\thasAuthControllerSubjectOwnerConflict(\n\t\tinput: CoordinatorAuthControllerSubjectOwnerInput,\n\t): Promise<boolean>;\n\t/** Read-only restore: checks fresh evidence without comparing or rewriting the stored digest. */\n\treadAuthControllerAttestationForSnapshot(\n\t\tinput: CoordinatorAuthControllerReviewInput,\n\t): Promise<CoordinatorAuthControllerAttestation | null>;\n\tcaptureAuthControllerLegacyHistory(\n\t\tinput: ControllerHistoryInput,\n\t): Promise<ControllerHistorySnapshot>;\n\tcreateAuthControllerAttestation(\n\t\tinput: CoordinatorAuthControllerReviewInput,\n\t): Promise<CoordinatorAuthControllerCreateResult>;\n\tgetActiveAuthControllerAttestation(\n\t\tcoordinatorId: string,\n\t\tattestationId: string,\n\t): Promise<CoordinatorAuthControllerAttestation | null>;\n\trevokeAuthControllerAttestation(coordinatorId: string, attestationId: string): Promise<boolean>;\n}\n\nexport interface CoordinatorAuthControllerSubjectOwnerInput {\n\tidentityId: string;\n\t/** Captured by the trusted history reader, never accepted from browser JSON. */\n\thistory: ControllerHistorySnapshot;\n}\n\nexport function authControllerSubjectOwnerConflictValues(\n\tinput: CoordinatorAuthControllerSubjectOwnerInput,\n): string[] {\n\ttry {\n\t\tconst identity = Object.getOwnPropertyDescriptor(input, \"identityId\");\n\t\tconst history = Object.getOwnPropertyDescriptor(input, \"history\");\n\t\tif (\n\t\t\t!identity ||\n\t\t\t!Object.hasOwn(identity, \"value\") ||\n\t\t\t!isAuthControllerId(identity.value) ||\n\t\t\t!history ||\n\t\t\t!Object.hasOwn(history, \"value\")\n\t\t)\n\t\t\tthrow new Error(\"account_owner_subject_invalid\");\n\t\tconst captured = captureControllerHistorySnapshot(history.value);\n\t\tif (\n\t\t\t!captured ||\n\t\t\t!isAuthControllerId(captured.coordinatorId) ||\n\t\t\t!isAuthControllerId(captured.deviceId)\n\t\t)\n\t\t\tthrow new Error(\"account_owner_subject_invalid\");\n\t\treturn [JSON.stringify(captured), identity.value];\n\t} catch {\n\t\tthrow new Error(\"account_owner_subject_invalid\");\n\t}\n}\n\nconst REVIEW_FIELDS = {\n\tattestationId: \"attestation_id\",\n\tcoordinatorId: \"coordinator_id\",\n\tidentityId: \"identity_id\",\n\tgroupId: \"group_id\",\n\tdeviceId: \"device_id\",\n\tpublicKey: \"public_key\",\n\tfingerprint: \"fingerprint\",\n\treviewReceiptId: \"review_receipt_id\",\n\tevidenceDigest: \"evidence_digest\",\n} as const;\n\nexport function isAuthControllerId(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length > 0 &&\n\t\tvalue.length <= 256 &&\n\t\tvalue.trim() === value &&\n\t\t!/[\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(value)\n\t);\n}\n\nfunction isReviewFieldValid(field: string, value: unknown): value is string {\n\tif (typeof value !== \"string\") return false;\n\tif (field === \"fingerprint\" || field === \"evidenceDigest\") {\n\t\treturn value.length === 64 && /^[a-f0-9]{64}$/.test(value);\n\t}\n\tif (field !== \"publicKey\") return isAuthControllerId(value);\n\t// PEM exports include a final line ending. Validate without line endings, but\n\t// retain the original bytes for the authoritative enrollment comparison.\n\tconst withoutLineEndings = value.replace(/[\\r\\n]/g, \"\");\n\treturn (\n\t\twithoutLineEndings.length > 0 &&\n\t\tvalue.length <= 4096 &&\n\t\twithoutLineEndings.trim() === withoutLineEndings &&\n\t\t!/[\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(withoutLineEndings)\n\t);\n}\n\ntype VerifiedInvite = CoordinatorAuthControllerVerifiedSnapshot[\"invites\"][number];\nfunction validSnapshotField(field: keyof VerifiedInvite, value: unknown): boolean {\n\tif (field === \"kind\") return value === \"team_member\" || value === \"add_device\";\n\tif (field === \"digest\") return isReviewFieldValid(\"evidenceDigest\", value);\n\tif (field === \"assignedIdentityId\" || field === \"targetIdentityId\")\n\t\treturn value === null || isAuthControllerId(value);\n\treturn isAuthControllerId(value);\n}\nfunction captureVerifiedInvite(value: unknown): VerifiedInvite | null {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n\tconst fields = [\n\t\t\"inviteId\",\n\t\t\"kind\",\n\t\t\"actorId\",\n\t\t\"assignedIdentityId\",\n\t\t\"targetIdentityId\",\n\t\t\"digest\",\n\t] as const;\n\tconst copy: Record<string, string | null> = {};\n\tfor (const field of fields) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, field);\n\t\tif (!descriptor || !Object.hasOwn(descriptor, \"value\")) return null;\n\t\tif (!validSnapshotField(field, descriptor.value)) return null;\n\t\tcopy[field] = descriptor.value;\n\t}\n\treturn copy as VerifiedInvite;\n}\nfunction captureVerifiedInvites(value: unknown): VerifiedInvite[] | null {\n\tif (!Array.isArray(value)) return null;\n\tconst length = Object.getOwnPropertyDescriptor(value, \"length\");\n\tif (\n\t\t!length ||\n\t\t!Object.hasOwn(length, \"value\") ||\n\t\t!Number.isSafeInteger(length.value) ||\n\t\tlength.value > 4096\n\t)\n\t\treturn null;\n\tconst invites: VerifiedInvite[] = [];\n\tconst ids = new Set<string>();\n\tfor (let index = 0; index < length.value; index++) {\n\t\tconst item = Object.getOwnPropertyDescriptor(value, String(index));\n\t\tif (!item || !Object.hasOwn(item, \"value\")) return null;\n\t\tconst invite = captureVerifiedInvite(item.value);\n\t\tif (!invite || ids.has(invite.inviteId)) return null;\n\t\tids.add(invite.inviteId);\n\t\tinvites.push(invite);\n\t}\n\treturn invites;\n}\nexport function captureVerifiedSnapshot(\n\tvalue: unknown,\n): CoordinatorAuthControllerVerifiedSnapshot | null {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n\tconst identity = Object.getOwnPropertyDescriptor(value, \"enrollmentIdentityId\");\n\tconst list = Object.getOwnPropertyDescriptor(value, \"invites\");\n\tif (!identity || !Object.hasOwn(identity, \"value\") || !list || !Object.hasOwn(list, \"value\"))\n\t\treturn null;\n\tif (identity.value !== null && !isAuthControllerId(identity.value)) return null;\n\tconst invites = captureVerifiedInvites(list.value);\n\tif (!invites) return null;\n\tconst snapshot: CoordinatorAuthControllerVerifiedSnapshot = {\n\t\tenrollmentIdentityId: identity.value as string | null,\n\t\tinvites,\n\t};\n\tconst history = captureOptionalField(value, \"legacyHistory\", captureControllerHistorySnapshot);\n\tconst target = captureOptionalField(value, \"accountOwnerTarget\", captureOwnerTarget);\n\tif (history === null || target === null) return null;\n\tif (history !== undefined) snapshot.legacyHistory = history;\n\tif (target !== undefined) snapshot.accountOwnerTarget = target;\n\tif (new TextEncoder().encode(JSON.stringify(snapshot)).byteLength > 1_000_000) return null;\n\treturn snapshot;\n}\n\nfunction captureOptionalField<T>(\n\tvalue: object,\n\tfield: string,\n\tcapture: (value: unknown) => T | null,\n): T | null | undefined {\n\tconst descriptor = Object.getOwnPropertyDescriptor(value, field);\n\tif (!descriptor) return field in value ? null : undefined;\n\tif (!Object.hasOwn(descriptor, \"value\")) return null;\n\treturn capture(descriptor.value);\n}\n\nfunction captureOwnerTarget(value: unknown): CoordinatorAuthControllerOwnerSnapshot | null {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n\tconst fields = [\n\t\t\"purpose\",\n\t\t\"coordinatorId\",\n\t\t\"targetIdentityId\",\n\t\t\"issuer\",\n\t\t\"linkId\",\n\t\t\"authConfigRevision\",\n\t\t\"createdAtMs\",\n\t] as const;\n\tif (Reflect.ownKeys(value).length !== fields.length) return null;\n\tconst copy: Record<string, unknown> = {};\n\tfor (const field of fields) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, field);\n\t\tif (!descriptor || !Object.hasOwn(descriptor, \"value\")) return null;\n\t\tcopy[field] = descriptor.value;\n\t}\n\tif (\n\t\tcopy.purpose !== \"existing_account_owner\" ||\n\t\t!Number.isSafeInteger(copy.createdAtMs) ||\n\t\t(copy.createdAtMs as number) < 0\n\t)\n\t\treturn null;\n\tif (\n\t\t![\"coordinatorId\", \"targetIdentityId\", \"issuer\", \"linkId\"].every((field) =>\n\t\t\tisAuthControllerId(copy[field]),\n\t\t) ||\n\t\t!isReviewFieldValid(\"evidenceDigest\", copy.authConfigRevision)\n\t)\n\t\treturn null;\n\treturn copy as unknown as CoordinatorAuthControllerOwnerSnapshot;\n}\n\nfunction captureOptionalSnapshot(\n\tinput: object,\n): CoordinatorAuthControllerVerifiedSnapshot | null | undefined {\n\tconst snapshot = Object.getOwnPropertyDescriptor(input, \"verifiedSnapshot\");\n\tif (!snapshot) return \"verifiedSnapshot\" in input ? null : undefined;\n\tif (!Object.hasOwn(snapshot, \"value\")) return null;\n\treturn captureVerifiedSnapshot(snapshot.value);\n}\n\n/** Capture own data properties once, without coercion, inherited fields or getters. */\nexport function captureAuthControllerReview(\n\tinput: unknown,\n): CoordinatorAuthControllerReviewInput | null {\n\tif (!input || typeof input !== \"object\") return null;\n\tconst captured: Partial<CoordinatorAuthControllerReviewInput> = {};\n\ttry {\n\t\tif (Array.isArray(input)) return null;\n\t\tconst fields = Object.keys(REVIEW_FIELDS) as (keyof typeof REVIEW_FIELDS)[];\n\t\tfor (const field of fields) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(input, field);\n\t\t\tif (!descriptor || !Object.hasOwn(descriptor, \"value\")) return null;\n\t\t\tif (!isReviewFieldValid(field, descriptor.value)) return null;\n\t\t\tcaptured[field] = descriptor.value;\n\t\t}\n\t\tconst snapshot = captureOptionalSnapshot(input);\n\t\tif (snapshot === null) return null;\n\t\tif (!historyMatchesReview(snapshot?.legacyHistory, captured)) return null;\n\t\tif (!ownerTargetMatchesReview(snapshot, captured)) return null;\n\t\tif (snapshot !== undefined) captured.verifiedSnapshot = snapshot;\n\t} catch {\n\t\treturn null;\n\t}\n\treturn captured as CoordinatorAuthControllerReviewInput;\n}\n\nfunction historyMatchesReview(\n\thistory: ControllerHistorySnapshot | undefined,\n\tinput: Partial<CoordinatorAuthControllerReviewInput>,\n): boolean {\n\tif (!history) return true;\n\treturn (\n\t\thistory.coordinatorId === input.coordinatorId &&\n\t\thistory.deviceId === input.deviceId &&\n\t\thistory.publicKey === input.publicKey &&\n\t\thistory.fingerprint === input.fingerprint\n\t);\n}\n\nfunction ownerTargetMatchesReview(\n\tsnapshot: CoordinatorAuthControllerVerifiedSnapshot | undefined,\n\tinput: Partial<CoordinatorAuthControllerReviewInput>,\n): boolean {\n\tconst target = snapshot?.accountOwnerTarget;\n\tif (!target) return true;\n\treturn (\n\t\t!!snapshot?.legacyHistory &&\n\t\ttarget.coordinatorId === input.coordinatorId &&\n\t\ttarget.targetIdentityId === input.identityId\n\t);\n}\n\nexport function authControllerRetryResult(\n\tinput: CoordinatorAuthControllerReviewInput,\n\trow: CoordinatorAuthControllerAttestation | null,\n): CoordinatorAuthControllerCreateResult {\n\tif (\n\t\t!row ||\n\t\tObject.entries(REVIEW_FIELDS).some(\n\t\t\t([field, column]) =>\n\t\t\t\tinput[field as keyof CoordinatorAuthControllerReviewInput] !== row[column],\n\t\t)\n\t) {\n\t\treturn { kind: \"rejected\", error: \"attestation_conflict\" };\n\t}\n\tif (row.revoked_at !== null) return { kind: \"rejected\", error: \"attestation_revoked\" };\n\treturn { kind: \"existing\", attestation: row };\n}\n\nexport function authControllerUnavailableResult(\n\tinput: CoordinatorAuthControllerReviewInput,\n): CoordinatorAuthControllerCreateResult {\n\treturn {\n\t\tkind: \"rejected\",\n\t\terror: input.verifiedSnapshot ? \"review_stale\" : \"enrollment_mismatch\",\n\t};\n}\n\n/** Only uniqueness violations are domain conflicts; other backend failures propagate. */\nexport function isAuthControllerUniqueError(error: unknown): boolean {\n\tif (!(error instanceof Error)) return false;\n\tconst code = Object.getOwnPropertyDescriptor(error, \"code\")?.value;\n\treturn (\n\t\tcode === \"SQLITE_CONSTRAINT_UNIQUE\" ||\n\t\tcode === \"SQLITE_CONSTRAINT_PRIMARYKEY\" ||\n\t\t/\\bUNIQUE constraint failed\\b/i.test(error.message)\n\t);\n}\n\nexport const AUTH_CONTROLLER_SCHEMA_SQL = `\n\tCREATE TABLE IF NOT EXISTS coordinator_auth_controller_attestations (\n\t\tattestation_id TEXT NOT NULL,\n\t\tcoordinator_id TEXT NOT NULL,\n\t\tidentity_id TEXT NOT NULL,\n\t\tgroup_id TEXT NOT NULL,\n\t\tdevice_id TEXT NOT NULL,\n\t\tpublic_key TEXT NOT NULL,\n\t\tfingerprint TEXT NOT NULL CHECK (length(fingerprint) = 64 AND fingerprint NOT GLOB '*[^0-9a-f]*'),\n\t\treview_receipt_id TEXT NOT NULL,\n\t\tevidence_digest TEXT NOT NULL CHECK (length(evidence_digest) = 64 AND evidence_digest NOT GLOB '*[^0-9a-f]*'),\n\t\tenrollment_identity_id TEXT,\n\t\trevision INTEGER NOT NULL DEFAULT 1 CHECK (revision = 1),\n\t\tcreated_at TEXT NOT NULL,\n\t\trevoked_at TEXT,\n\t\tPRIMARY KEY (coordinator_id, attestation_id),\n\t\tUNIQUE (coordinator_id, group_id, device_id, fingerprint),\n\t\tUNIQUE (coordinator_id, review_receipt_id)\n\t);`;\n\n/** Pin the actual enrollment used to derive the revocation key across async reads. */\nexport function authControllerAuthorityValues(\n\tsource: {\n\t\tgroup_id: string;\n\t\tdevice_id: string;\n\t\tpublic_key: string;\n\t\tfingerprint: string;\n\t\tidentity_id: string | null;\n\t},\n\tkeyId: string | null,\n): (string | null)[] {\n\treturn [\n\t\tsource.group_id,\n\t\tsource.device_id,\n\t\tsource.public_key,\n\t\tsource.fingerprint,\n\t\tsource.identity_id,\n\t\tsource.device_id,\n\t\tkeyId,\n\t];\n}\n\nconst AUTH_CONTROLLER_AUTHORITY_GUARD = `\n\tAND e.group_id = ? AND e.device_id = ? AND e.public_key = ?\n\tAND e.fingerprint = ? AND e.identity_id IS ?\n\tAND NOT EXISTS (SELECT 1 FROM coordinator_device_revocations WHERE\n\t\t(subject_kind = 'device_id' AND subject_value = ?) OR\n\t\t(subject_kind = 'ed25519_key' AND subject_value = ?))`;\n\nexport const AUTH_CONTROLLER_ENROLLMENT_SQL = `\n\tSELECT e.* FROM enrolled_devices e WHERE e.group_id = ? AND e.device_id = ?`;\n\nconst AUTH_CONTROLLER_CURRENT_SQL = `\n\tSELECT a.* FROM coordinator_auth_controller_attestations a\n\tJOIN enrolled_devices e ON e.group_id = a.group_id AND e.device_id = a.device_id\n\tJOIN groups g ON g.group_id = a.group_id\n\tWHERE a.coordinator_id = ? AND a.attestation_id = ? AND a.revoked_at IS NULL\n\t\tAND e.enabled = 1 AND g.archived_at IS NULL AND e.public_key = a.public_key\n\t\tAND e.fingerprint = a.fingerprint\n\t\tAND (e.identity_id IS NULL OR e.identity_id = a.identity_id)`;\n\nexport const AUTH_CONTROLLER_CURRENT_ENROLLMENT_SQL = AUTH_CONTROLLER_CURRENT_SQL.replace(\n\t\"SELECT a.*\",\n\t\"SELECT e.*\",\n);\n\nexport const AUTH_CONTROLLER_ACTIVE_SQL = `\n\t${AUTH_CONTROLLER_CURRENT_SQL} ${AUTH_CONTROLLER_AUTHORITY_GUARD}`;\n\nexport const AUTH_CONTROLLER_CONFLICT_SQL = `\n\tSELECT * FROM coordinator_auth_controller_attestations\n\tWHERE coordinator_id = ? AND (attestation_id = ? OR review_receipt_id = ?\n\t\tOR (group_id = ? AND device_id = ? AND fingerprint = ?))\n\tORDER BY CASE WHEN attestation_id = ? THEN 0 ELSE 1 END LIMIT 1`;\n\nexport function authControllerConflictValues(\n\tinput: CoordinatorAuthControllerReviewInput,\n): string[] {\n\treturn [\n\t\tinput.coordinatorId,\n\t\tinput.attestationId,\n\t\tinput.reviewReceiptId,\n\t\tinput.groupId,\n\t\tinput.deviceId,\n\t\tinput.fingerprint,\n\t\tinput.attestationId,\n\t];\n}\n\nexport const AUTH_CONTROLLER_REVOKE_SQL = `\n\tUPDATE coordinator_auth_controller_attestations SET revoked_at = COALESCE(revoked_at, ?)\n\tWHERE coordinator_id = ? AND attestation_id = ?`;\n","/** Standalone auth pages mirror the Viewer's tokens without loading remote assets.\n * Keep these palette values aligned with ui/static/{tokens,themes}.css.\n * Separate origins cannot read the Viewer's saved theme; use the OS preference.\n */\nexport const COORDINATOR_AUTH_STYLE = `\n:root{color-scheme:dark;--surface-0:#0b1016;--surface-1:#0f1720;--surface-2:#111c27;--text-primary:#e7f0f7;--text-secondary:#b7c5d3;--accent:#7ef0c2;--accent-hover:#9eff87;--border:rgba(126,240,194,.12);--border-strong:rgba(126,240,194,.28);--font-sans:\"Geist\",system-ui,-apple-system,sans-serif;--font-mono:\"JetBrains Mono\",ui-monospace,monospace;font-family:var(--font-sans);color:var(--text-primary);background:var(--surface-0)}\n*{box-sizing:border-box}body{margin:0;padding:clamp(1rem,5vw,4rem) 1rem;line-height:1.6}main{max-width:34rem;margin:0 auto;padding:clamp(1.25rem,4vw,2rem);border:1px solid var(--border-strong);border-radius:20px;background:var(--surface-1)}\n.brand{display:flex;align-items:center;gap:.6rem;margin:0 0 1.5rem;color:var(--accent);font-size:.875rem;font-weight:700;letter-spacing:.02em}.brand::before{content:\"\";width:.65rem;height:.65rem;border-radius:3px;background:var(--accent)}\nh1,h2{font-family:inherit;font-weight:600;line-height:1.25;letter-spacing:-.025em}h1{font-size:1.6rem;margin:0 0 1rem}h2{font-size:1.05rem;margin:0 0 .5rem}p{margin:.5rem 0}section{padding:1.25rem 0;border-bottom:1px solid var(--border)}.eyebrow{font-size:.75rem;letter-spacing:.08em;text-transform:uppercase;color:var(--text-secondary)}\n.profile{display:flex;align-items:center;gap:1rem}.profile-text{min-width:0;overflow-wrap:anywhere}.avatar{position:relative;display:inline-flex;align-items:center;justify-content:center;flex:0 0 3rem;width:3rem;height:3rem;border-radius:50%;background:var(--surface-2);color:var(--accent);overflow:hidden}.initials{font-weight:700}.avatar img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}.note{font-size:.875rem;color:var(--text-secondary)}\ndl{margin:0}dt{font-size:.8rem;font-weight:600;color:var(--text-secondary);margin-top:1rem}dd{margin:.25rem 0 0}code{font-family:var(--font-mono);font-size:.8rem;overflow-wrap:anywhere;white-space:pre-wrap}code.command{white-space:nowrap;overflow-wrap:normal}\nlabel{display:block;font-weight:600;margin:1rem 0 .35rem}input[type=text]{font:inherit;font-family:var(--font-mono);font-size:1.1rem;letter-spacing:.12em;text-transform:uppercase;width:100%;min-height:44px;padding:.6rem .8rem;border:1px solid var(--border-strong);border-radius:10px;background:var(--surface-2);color:var(--text-primary)}\n.actions{display:flex;flex-wrap:wrap;gap:.75rem;margin:1.5rem 0 0}form{margin:0}button,.link{font:inherit;font-size:.875rem;font-weight:600;display:inline-flex;align-items:center;justify-content:center;min-height:44px;padding:.65rem 1rem;border:1px solid var(--border-strong);border-radius:10px;background:var(--accent);color:var(--surface-0);cursor:pointer;text-decoration:none}button.secondary{background:transparent;color:var(--accent)}a{color:var(--accent)}button:hover,.link:hover{background:var(--accent-hover);color:var(--surface-0)}:focus-visible{outline:3px solid var(--accent);outline-offset:4px}\n@media(prefers-color-scheme:light){:root{color-scheme:light;--surface-0:#f7faf8;--surface-1:#fff;--surface-2:#eef5f1;--text-primary:#0b1016;--text-secondary:#3f4d5c;--accent:#0f8a68;--accent-hover:#0a6f53;--border:rgba(15,138,104,.16);--border-strong:rgba(15,138,104,.3)}button,.link,button:hover,.link:hover{color:#fff}button.secondary{color:var(--accent)}button.secondary:hover{color:#fff}}\n@media(max-width:30rem){body{padding:1rem}.actions{flex-direction:column}.actions form,.actions button,.actions .link{width:100%}h1{font-size:1.4rem}}\n`;\n","const CANONICAL_PROOF = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;\n\nexport function encodeCoordinatorAuthProof32(bytes: Uint8Array): string {\n\tif (!(bytes instanceof Uint8Array) || bytes.byteLength !== 32) {\n\t\tthrow new Error(\"auth_proof_invalid_input\");\n\t}\n\treturn btoa(String.fromCharCode(...bytes))\n\t\t.replaceAll(\"+\", \"-\")\n\t\t.replaceAll(\"/\", \"_\")\n\t\t.replace(/=+$/, \"\");\n}\n\nexport function decodeCoordinatorAuthProof32(value: unknown): Uint8Array<ArrayBuffer> | null {\n\tif (typeof value !== \"string\" || value.length !== 43 || !CANONICAL_PROOF.test(value)) {\n\t\treturn null;\n\t}\n\ttry {\n\t\tconst binary = atob(`${value.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\")}=`);\n\t\tconst bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));\n\t\tif (bytes.length !== 32 || encodeCoordinatorAuthProof32(bytes) !== value) return null;\n\t\treturn bytes;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport async function hashCoordinatorAuthProofBytes32(bytes: Uint8Array): Promise<string> {\n\tif (!(bytes instanceof Uint8Array) || bytes.byteLength !== 32) {\n\t\tthrow new Error(\"auth_proof_invalid_input\");\n\t}\n\t// Own the input before the digest yields, including callers with shared memory.\n\tconst owned = new Uint8Array(bytes);\n\ttry {\n\t\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", owned);\n\t\treturn Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\n\t\t\t\"\",\n\t\t);\n\t} catch {\n\t\tthrow new Error(\"auth_proof_crypto_failed\");\n\t}\n}\n","/**\n * SQL comparison rules for TypeScript decisions over rows read from SQLite.\n *\n * In SQL a comparison with NULL is neither true nor false, and WHERE keeps a row only\n * when its condition is true. So `a <> b` does not select a row whose `a` is NULL, while\n * JavaScript's `a !== b` would. Each helper answers \"is this SQL comparison true?\".\n *\n * Operands must already have the same storage class. SQLite can also convert between\n * text and numbers by column affinity; these helpers never do, so text never equals a\n * number.\n */\n\n/** A value as SQLite returns it through JSON: text, a number, or NULL. */\nexport type SqlValue = string | number | null;\n\n/** SQL `a = b`. */\nexport function sqlEq(a: SqlValue, b: SqlValue): boolean {\n\treturn a !== null && b !== null && a === b;\n}\n\n/** SQL `a <> b`. */\nexport function sqlNe(a: SqlValue, b: SqlValue): boolean {\n\treturn a !== null && b !== null && a !== b;\n}\n\n/** SQL `a IN (list)` for a list without NULL. */\nexport function sqlIn(a: SqlValue, list: readonly (string | number)[]): boolean {\n\treturn a !== null && list.includes(a);\n}\n\n/** SQL `a IS b`: true when both are NULL or both are the same value. */\nexport function sqlIs(a: SqlValue, b: SqlValue): boolean {\n\treturn a === b;\n}\n","import { type SqlValue, sqlEq, sqlIn, sqlNe } from \"./coordinator-sql-compare.js\";\n\n/** Trusted server values: the signed enrollment, the configuration, and derived key facts. */\nexport interface AccountChangeSubject {\n\tcoordinatorId: string;\n\t/** The Identity of the target link, never a caller-selected one. */\n\tidentityId: string;\n\tgroupId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n\tkeyId: string;\n\tissuer: string;\n\tenabled: boolean;\n\t/** Whether the claim proofs use the connection-session schema. */\n\tconnections: boolean;\n}\n\nexport interface AccountChangeEnrollment {\n\tgroup_id: string;\n\tdevice_id: string;\n\tpublic_key: SqlValue;\n\tfingerprint: SqlValue;\n\tidentity_id: SqlValue;\n\tenabled: SqlValue;\n\t/** For an enrollment in the signed group: 1 when that group exists and is not archived. */\n\tgroup_live: SqlValue;\n}\n\nexport interface AccountChangeBinding {\n\tcoordinator_id: SqlValue;\n\tdevice_id: string;\n\tkey_id: SqlValue;\n\tidentity_id: SqlValue;\n}\n\nexport interface AccountChangeAttestation {\n\tattestation_id: string;\n\tidentity_id: SqlValue;\n\tgroup_id: SqlValue;\n\tdevice_id: SqlValue;\n\tpublic_key: SqlValue;\n\tfingerprint: SqlValue;\n\trevision: SqlValue;\n\trevoked_at: SqlValue;\n}\n\nexport interface AccountChangeClaim {\n\tclaim_id: string;\n\tidentity_id: SqlValue;\n\tgroup_id: SqlValue;\n\tdevice_id: SqlValue;\n\tpublic_key: SqlValue;\n\tfingerprint: SqlValue;\n\tkey_id: SqlValue;\n\t/** SQL verdict: the claim's Identity has an active account link. */\n\tactive_link: SqlValue;\n\t/** SQL verdict: the claim's immutable genesis verifies (always 1 without connections). */\n\tgenesis: SqlValue;\n}\n\n/** The creation attempt a link names, in the columns the check compares. */\nexport interface AccountChangeLinkAttempt {\n\tidentity_id: SqlValue;\n\tissuer: SqlValue;\n\taccount_subject: SqlValue;\n\tauth_config_revision: SqlValue;\n\tstate: SqlValue;\n}\n\nexport interface AccountChangeLink {\n\tcoordinator_id: string;\n\tlink_id: string;\n\tidentity_id: SqlValue;\n\tissuer: SqlValue;\n\tsubject: SqlValue;\n\tauth_config_revision: SqlValue;\n\trevoked_at_ms: SqlValue;\n\tdevice_claim_id: SqlValue;\n\tattempts: AccountChangeLinkAttempt[];\n\t/** SQL verdict: a controller-reviewed link has its complete creation records. */\n\tcontroller_birth: SqlValue;\n\t/** SQL verdict: a device-claim link's immutable creation records verify. */\n\tdevice_birth: SqlValue;\n}\n\n/** SQL verdicts over legacy Team manifests, evaluated for this subject. */\nexport interface AccountChangeLegacy {\n\t/** The legacy assignment the device relies on is still current, or it relies on none. */\n\tassignment_current: SqlValue;\n\t/** No legacy decision that an ownership binding cannot waive contradicts the device. */\n\tunwaivable_clear: SqlValue;\n\t/** No legacy decision contradicts the device at all. */\n\tcompatible_clear: SqlValue;\n}\n\n/** Everything the decision looks at. A list named `...Conflicts` must be empty. */\nexport type AccountChangeFacts = {\n\t/** Enrollments of this device or of any text form of its key. */\n\tenrollments: AccountChangeEnrollment[];\n\t/** Ownership bindings of this device or key. */\n\tbindings: AccountChangeBinding[];\n\t/** Controller reviews of this device or of any text form of its key. */\n\tattestations: AccountChangeAttestation[];\n\t/** Device claims of this device or key. */\n\tclaims: AccountChangeClaim[];\n\t/** The target link, when it exists. */\n\tlink: AccountChangeLink[];\n\t/** Ended links of the subject Identity that record a revocation. */\n\trevokedHistory: unknown[];\n\t/** One row of legacy verdicts. */\n\tlegacy: AccountChangeLegacy[];\n\trevocationConflicts: unknown[];\n\tinviteConflicts: unknown[];\n\totherIdentityLinkAttemptConflicts: unknown[];\n\totherIdentityLinkAuditConflicts: unknown[];\n};\n\nconst CONFLICTS = [\n\t\"revocationConflicts\",\n\t\"inviteConflicts\",\n\t\"otherIdentityLinkAttemptConflicts\",\n\t\"otherIdentityLinkAuditConflicts\",\n] as const satisfies readonly (keyof AccountChangeFacts)[];\n\n/** The link that the device may refresh or disconnect, with the values the write records. */\nexport interface AccountChangeGrant {\n\tcoordinatorId: string;\n\tlinkId: string;\n\tidentityId: SqlValue;\n\tissuer: SqlValue;\n\tsubject: SqlValue;\n\tenrollmentIdentityId: SqlValue;\n}\n\nconst isSigned = (p: AccountChangeSubject, row: { group_id: SqlValue; device_id: SqlValue }) =>\n\tsqlEq(row.group_id, p.groupId) && sqlEq(row.device_id, p.deviceId);\n\n/** The exact signed enrollment, when it is live under the given Identity or none. */\nfunction liveSignedEnrollment(\n\tp: AccountChangeSubject,\n\tfacts: AccountChangeFacts,\n\tidentityId: SqlValue,\n): AccountChangeEnrollment | undefined {\n\treturn facts.enrollments.find(\n\t\t(e) =>\n\t\t\tisSigned(p, e) &&\n\t\t\tsqlEq(e.public_key, p.publicKey) &&\n\t\t\tsqlEq(e.fingerprint, p.fingerprint) &&\n\t\t\tsqlEq(e.enabled, 1) &&\n\t\t\tsqlEq(e.group_live, 1) &&\n\t\t\t(e.identity_id === null || sqlEq(e.identity_id, identityId)),\n\t);\n}\n\n/** The exact active first-revision review of the signed enrollment, as the link reader sees it. */\nfunction currentControllers(p: AccountChangeSubject, facts: AccountChangeFacts) {\n\tif (!p.enabled) return [];\n\treturn facts.attestations.filter(\n\t\t(a) =>\n\t\t\tisSigned(p, a) &&\n\t\t\tsqlEq(a.public_key, p.publicKey) &&\n\t\t\tsqlEq(a.fingerprint, p.fingerprint) &&\n\t\t\ta.revoked_at === null &&\n\t\t\tsqlEq(a.revision, 1) &&\n\t\t\tliveSignedEnrollment(p, facts, a.identity_id) !== undefined,\n\t);\n}\n\n/** This exact device key's own ownership binding for the subject Identity. */\nconst hasRequesterBinding = (p: AccountChangeSubject, facts: AccountChangeFacts) =>\n\tfacts.bindings.some(\n\t\t(b) =>\n\t\t\tsqlEq(b.coordinator_id, p.coordinatorId) &&\n\t\t\tsqlEq(b.device_id, p.deviceId) &&\n\t\t\tsqlEq(b.key_id, p.keyId) &&\n\t\t\tsqlEq(b.identity_id, p.identityId),\n\t);\n\n/** Nothing stored about this device or key names another Identity. */\nfunction noOtherIdentity(p: AccountChangeSubject, facts: AccountChangeFacts): boolean {\n\treturn (\n\t\t!facts.enrollments.some((e) => sqlNe(e.identity_id, p.identityId)) &&\n\t\t!facts.bindings.some((b) => sqlNe(b.identity_id, p.identityId)) &&\n\t\t!facts.attestations.some((a) => sqlNe(a.identity_id, p.identityId))\n\t);\n}\n\n/** Another Identity's claim of this device or key is superseded only by this key's binding. */\nfunction claimsAllow(p: AccountChangeSubject, facts: AccountChangeFacts, binding: boolean) {\n\tconst others = facts.claims.filter((d) => sqlNe(d.identity_id, p.identityId));\n\tif (others.length === 0) return true;\n\treturn binding && !others.some((d) => sqlEq(d.active_link, 1));\n}\n\n/** Every review of the device or key is active and of this Identity, or a current one is. */\nfunction attestationsAllow(p: AccountChangeSubject, facts: AccountChangeFacts): boolean {\n\tconst contradicted = facts.attestations.some(\n\t\t(a) => a.revoked_at !== null || sqlNe(a.identity_id, p.identityId),\n\t);\n\treturn (\n\t\t!contradicted || currentControllers(p, facts).some((c) => sqlEq(c.identity_id, p.identityId))\n\t);\n}\n\n/** The requester checks: this device may speak for the subject Identity at all. */\nfunction requesterAllowed(p: AccountChangeSubject, facts: AccountChangeFacts): boolean {\n\tconst [legacy, ...extra] = facts.legacy;\n\tif (!legacy || extra.length > 0) return false;\n\tif (CONFLICTS.some((name) => facts[name].length > 0)) return false;\n\tconst binding = hasRequesterBinding(p, facts);\n\treturn (\n\t\tsqlEq(legacy.assignment_current, 1) &&\n\t\tnoOtherIdentity(p, facts) &&\n\t\tclaimsAllow(p, facts, binding) &&\n\t\tattestationsAllow(p, facts) &&\n\t\tsqlEq(legacy.unwaivable_clear, 1) &&\n\t\t(sqlEq(legacy.compatible_clear, 1) || binding)\n\t);\n}\n\n/** The target link's creation attempt agrees with it and finished. */\nconst birthAttemptMatches = (link: AccountChangeLink) =>\n\tlink.attempts.some(\n\t\t(b) =>\n\t\t\tsqlEq(b.identity_id, link.identity_id) &&\n\t\t\tsqlEq(b.issuer, link.issuer) &&\n\t\t\tsqlEq(b.account_subject, link.subject) &&\n\t\t\tsqlEq(b.auth_config_revision, link.auth_config_revision) &&\n\t\t\tsqlIn(b.state, [\"finalized\", \"session_redeemed\"]),\n\t);\n\n/** This device's own claim under the link's Identity: the link's claim, or with connections any. */\nfunction hasOwnClaim(p: AccountChangeSubject, facts: AccountChangeFacts, link: AccountChangeLink) {\n\treturn facts.claims.some(\n\t\t(d) =>\n\t\t\tsqlEq(d.identity_id, p.identityId) &&\n\t\t\tsqlEq(d.genesis, 1) &&\n\t\t\t(p.connections\n\t\t\t\t? sqlEq(d.identity_id, link.identity_id)\n\t\t\t\t: sqlEq(d.claim_id, link.device_claim_id)) &&\n\t\t\tisSigned(p, d) &&\n\t\t\tsqlEq(d.public_key, p.publicKey) &&\n\t\t\tsqlEq(d.fingerprint, p.fingerprint) &&\n\t\t\tsqlEq(d.key_id, p.keyId),\n\t);\n}\n\n/** The link is active, and its own records and this device's proof support managing it. */\nfunction linkAllowed(p: AccountChangeSubject, facts: AccountChangeFacts, link: AccountChangeLink) {\n\tconst live = link.revoked_at_ms === null && facts.revokedHistory.length === 0;\n\tconst born = sqlEq(link.controller_birth, 1) || sqlEq(link.device_birth, 1);\n\tconst proof =\n\t\tcurrentControllers(p, facts).some((c) => sqlEq(c.identity_id, link.identity_id)) ||\n\t\thasOwnClaim(p, facts, link) ||\n\t\thasRequesterBinding(p, facts);\n\treturn (\n\t\tsqlEq(link.identity_id, p.identityId) &&\n\t\tsqlEq(link.issuer, p.issuer) &&\n\t\tbirthAttemptMatches(link) &&\n\t\tlive &&\n\t\tborn &&\n\t\tproof\n\t);\n}\n\n/**\n * Pure decision over the facts read. Returns the target link that this device may\n * refresh or disconnect, or null. The primary and unique keys of the tables read allow\n * at most one row per joined fact, so the original statement selected at most one row.\n */\nexport function decideAccountChange(\n\tp: AccountChangeSubject,\n\tfacts: AccountChangeFacts,\n): AccountChangeGrant | null {\n\tconst [link, ...others] = facts.link;\n\tif (!link || others.length > 0) return null;\n\tif (!requesterAllowed(p, facts) || !linkAllowed(p, facts, link)) return null;\n\tconst enrollment = liveSignedEnrollment(p, facts, link.identity_id);\n\tif (!enrollment) return null;\n\treturn {\n\t\tcoordinatorId: link.coordinator_id,\n\t\tlinkId: link.link_id,\n\t\tidentityId: link.identity_id,\n\t\tissuer: link.issuer,\n\t\tsubject: link.subject,\n\t\tenrollmentIdentityId: enrollment.identity_id,\n\t};\n}\n\n/** One candidate link that names this device by claim, review or binding. */\nexport interface AccountChangeTargetCandidate {\n\tlink_id: string;\n\tidentity_id: string;\n\t/** SQL `ob.device_id = ? AND ob.key_id = ?` for one joined binding row: 1, 0 or NULL. */\n\tbound: SqlValue;\n}\n\nexport interface AccountChangeTarget {\n\tidentity_id: string;\n\ttarget_link_id: string;\n}\n\n/** SQL `ORDER BY bound DESC`: 1, then 0, then NULL. */\nconst boundRank = (bound: SqlValue) => {\n\tif (bound === null) return 0;\n\treturn Number(bound) + 1;\n};\n\n/**\n * The target link, as `ORDER BY bound DESC, link_id` picked its first row: this device's\n * binding wins a tie, and the lowest link ID breaks the rest. The candidates must arrive\n * in SQL `link_id` order, so SQLite's collation, not JavaScript's, decides that tie.\n */\nexport function pickAccountChangeTarget(\n\tcandidatesByLinkId: readonly AccountChangeTargetCandidate[],\n): AccountChangeTarget | null {\n\tlet best: AccountChangeTargetCandidate | undefined;\n\tfor (const candidate of candidatesByLinkId)\n\t\tif (!best || boundRank(candidate.bound) > boundRank(best.bound)) best = candidate;\n\treturn best ? { identity_id: best.identity_id, target_link_id: best.link_id } : null;\n}\n","import type { CoordinatorAuthLinkSigner } from \"./coordinator-auth-link-contract.js\";\nimport {\n\tcanonicalCoordinatorLegacyTeamCompletionManifestJson,\n\tlegacyDecisionCountsAsOwner,\n\tlegacyDecisionCountsAsOwnerSql,\n\tnormalizeCoordinatorLegacyTeamCompletionManifest,\n} from \"./coordinator-legacy-team-completion.js\";\nimport { legacyTeamCandidateId } from \"./recipient-policy-identifiers.js\";\n\ninterface AssignmentRecord {\n\tgroup_id: string;\n\tcandidate_ref: string;\n\tmanifest_version: number;\n\tcompleted_at: string;\n\tmanifest_json: string;\n}\n\n// The canonical reference scopes one record to this coordinator and group, without fallback.\nexport const AUTH_LEGACY_ASSIGNMENT_CAPTURE_SQL = `SELECT json_object(\n 'group_id', group_id, 'candidate_ref', candidate_ref, 'manifest_version', manifest_version,\n 'completed_at', completed_at, 'manifest_json',\n CASE WHEN length(CAST(manifest_json AS BLOB)) <= ? THEN manifest_json ELSE NULL END)\n FROM coordinator_legacy_team_completions WHERE group_id = ? AND candidate_ref = ?`;\n\n/** Read-set form of the capture: the same object as one `row`, with the same three inputs. */\nexport const AUTH_LEGACY_ASSIGNMENT_READ_SQL = `SELECT row FROM (SELECT (${AUTH_LEGACY_ASSIGNMENT_CAPTURE_SQL}) AS row)\n WHERE row IS NOT NULL`;\n\n/** A capture is not authority: every consumer must recheck it inside its statement. */\nexport function captureCurrentLegacyAssignment(\n\tsnapshot: string | null | undefined,\n\tinput: {\n\t\tcoordinatorId: string;\n\t\tidentityId: string;\n\t\tsigner: CoordinatorAuthLinkSigner;\n\t\tdistinctKeys: string[];\n\t},\n): string | null {\n\ttry {\n\t\tif (typeof snapshot !== \"string\") return null;\n\t\tconst row: AssignmentRecord | null = JSON.parse(snapshot);\n\t\tif (!row || typeof row.manifest_json !== \"string\") return null;\n\t\tconst manifest = normalizeCoordinatorLegacyTeamCompletionManifest(\n\t\t\tJSON.parse(row.manifest_json),\n\t\t);\n\t\tif (\n\t\t\tcanonicalCoordinatorLegacyTeamCompletionManifestJson(manifest) !== row.manifest_json ||\n\t\t\trow.group_id !== input.signer.groupId ||\n\t\t\trow.candidate_ref !== legacyTeamCandidateId(input.coordinatorId, input.signer.groupId) ||\n\t\t\trow.candidate_ref !== manifest.candidate_ref ||\n\t\t\trow.manifest_version !== manifest.version ||\n\t\t\trow.completed_at !== manifest.completed_at ||\n\t\t\tmanifest.coordinator_id !== input.coordinatorId\n\t\t)\n\t\t\treturn null;\n\t\tconst assigned = manifest.device_decisions.some(\n\t\t\t(d) =>\n\t\t\t\td.device_id === input.signer.deviceId &&\n\t\t\t\td.key_fingerprint === input.signer.fingerprint &&\n\t\t\t\td.identity_id === input.identityId &&\n\t\t\t\td.decision === \"included\" &&\n\t\t\t\td.enabled &&\n\t\t\t\tlegacyDecisionCountsAsOwner(d),\n\t\t);\n\t\treturn assigned ? JSON.stringify({ ...row, distinct_keys: input.distinctKeys }) : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n// A label row (another device's guess) never makes a current assignment. Grouped\n// terms keep D1's expression depth (max 100) unchanged for embedding queries.\n// Exact bytes and row metadata pin normalization to the record used by the writer.\n// This is a FROM subquery correlated to the embedding statement's claim_input row p,\n// never a WITH name: SQLite 3.54.0 and 3.54.1 (production D1) refuse a statement that\n// resolves a WITH name after about 100 table references.\nexport const AUTH_CURRENT_LEGACY_ASSIGNMENT_ROWS_SQL = `(\n SELECT c.* FROM coordinator_legacy_team_completions c\n WHERE c.group_id = p.group_id AND c.group_id = json_extract(p.assignment_snapshot, '$.group_id')\n AND c.candidate_ref = json_extract(p.assignment_snapshot, '$.candidate_ref')\n AND c.manifest_version = json_extract(p.assignment_snapshot, '$.manifest_version')\n AND c.completed_at = json_extract(p.assignment_snapshot, '$.completed_at')\n AND c.manifest_json = json_extract(p.assignment_snapshot, '$.manifest_json')\n AND json_extract(json_extract(p.assignment_snapshot, '$.manifest_json'), '$.coordinator_id') = p.coordinator_id\n AND EXISTS (SELECT 1 FROM json_each(json_extract(p.assignment_snapshot, '$.manifest_json'), '$.device_decisions') d\n WHERE json_extract(d.value, '$.device_id') = p.device_id\n AND json_extract(d.value, '$.key_fingerprint') = p.fingerprint\n AND json_extract(d.value, '$.identity_id') = p.identity_id\n AND (json_extract(d.value, '$.decision') = 'included' AND json_extract(d.value, '$.enabled') = 1\n AND ${legacyDecisionCountsAsOwnerSql(\"d.value\")}))\n AND EXISTS (SELECT 1 FROM enrolled_devices e JOIN groups g ON g.group_id = e.group_id\n WHERE e.group_id = p.group_id AND e.device_id = p.device_id AND e.public_key = p.public_key\n AND e.fingerprint = p.fingerprint AND e.enabled = 1 AND g.archived_at IS NULL\n AND (e.identity_id IS NULL OR e.identity_id = p.identity_id))\n AND NOT EXISTS (SELECT 1 FROM coordinator_device_revocations r\n WHERE (r.subject_kind = 'device_id' AND r.subject_value = p.device_id)\n OR (r.subject_kind = 'ed25519_key' AND r.subject_value = p.key_id)))`;\n\nexport const AUTH_CURRENT_LEGACY_ASSIGNMENT_SQL = `EXISTS (SELECT 1 FROM ${AUTH_CURRENT_LEGACY_ASSIGNMENT_ROWS_SQL} ca)`;\n","/**\n * Inert coordinator account-link policy. These results authenticate no claims,\n * grant no access, and must not be used as a runtime authorization gate.\n */\nexport interface CoordinatorAccountReference {\n\treadonly issuer: string;\n\treadonly subject: string;\n}\n\nexport type CoordinatorAccountReferenceResult =\n\t| { ok: true; account: CoordinatorAccountReference }\n\t| {\n\t\t\tok: false;\n\t\t\terror: \"invalid_account_reference\" | \"invalid_issuer\" | \"issuer_mismatch\" | \"invalid_subject\";\n\t };\n\nconst CONTROL_OR_FORMAT = /[\\p{Cc}\\p{Cf}\\p{Cs}]/u;\nconst FINGERPRINT = /^[0-9a-f]{64}$/;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nfunction field(value: Record<string, unknown>, key: string): unknown {\n\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\treturn descriptor && Object.hasOwn(descriptor, \"value\") ? descriptor.value : undefined;\n}\n\nfunction isIssuer(value: unknown): value is string {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\t!/^https:\\/\\//i.test(value) ||\n\t\tvalue !== value.trim() ||\n\t\tCONTROL_OR_FORMAT.test(value) ||\n\t\tvalue.includes(\"\\\\\") ||\n\t\tvalue.includes(\"?\") ||\n\t\tvalue.includes(\"#\")\n\t) {\n\t\treturn false;\n\t}\n\ttry {\n\t\tconst url = new URL(value);\n\t\treturn (\n\t\t\turl.protocol === \"https:\" &&\n\t\t\turl.hostname.length > 0 &&\n\t\t\turl.username === \"\" &&\n\t\t\turl.password === \"\" &&\n\t\t\turl.search === \"\" &&\n\t\t\turl.hash === \"\"\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport { isIssuer as isCoordinatorAccountIssuer };\n\nfunction isSubject(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length <= 255 &&\n\t\tvalue.trim().length > 0 &&\n\t\t!CONTROL_OR_FORMAT.test(value)\n\t);\n}\n\nfunction readAccountReference(value: unknown): CoordinatorAccountReferenceResult {\n\tif (!isRecord(value)) return { ok: false, error: \"invalid_account_reference\" };\n\tconst issuer = field(value, \"issuer\");\n\tconst subject = field(value, \"subject\");\n\tif (!isIssuer(issuer)) return { ok: false, error: \"invalid_issuer\" };\n\tif (!isSubject(subject)) return { ok: false, error: \"invalid_subject\" };\n\treturn { ok: true, account: { issuer, subject } };\n}\n\n/** Shape validation only; the caller must authenticate the issuer and subject independently. */\nexport function parseCoordinatorAccountReference(\n\tvalue: unknown,\n\toptions: { issuer: string },\n): CoordinatorAccountReferenceResult {\n\tconst configuredIssuer = isRecord(options) ? field(options, \"issuer\") : undefined;\n\tif (!isIssuer(configuredIssuer)) return { ok: false, error: \"invalid_issuer\" };\n\tconst reference = readAccountReference(value);\n\tif (!reference.ok) return reference;\n\tif (reference.account.issuer !== configuredIssuer) {\n\t\treturn { ok: false, error: \"issuer_mismatch\" };\n\t}\n\treturn reference;\n}\n\nexport interface CoordinatorAccountLink {\n\treadonly coordinatorId: string;\n\treadonly account: CoordinatorAccountReference;\n\treadonly identityId: string;\n\treadonly status: \"active\" | \"revoked\";\n}\n\n/**\n * Kind labels do not verify ownership. The caller must verify proofs first;\n * controller_verified means an existing trusted Identity-controlling device.\n */\nexport type CoordinatorIdentityOwnershipEvidence =\n\t| {\n\t\t\treadonly kind: \"controller_verified\" | \"admin_verified\";\n\t\t\treadonly coordinatorId: string;\n\t\t\treadonly identityId: string;\n\t\t\treadonly deviceId: string;\n\t\t\treadonly fingerprint: string;\n\t }\n\t| { readonly kind: \"invitation_claim\" | \"unavailable\" };\n\nexport interface CoordinatorAccountLinkInput {\n\treadonly coordinatorId: string;\n\treadonly account: CoordinatorAccountReference;\n\treadonly identityId: string;\n\treadonly device: { readonly deviceId: string; readonly fingerprint: string };\n\treadonly ownership: CoordinatorIdentityOwnershipEvidence;\n\treadonly accountLink: CoordinatorAccountLink | null;\n\treadonly identityLink: CoordinatorAccountLink | null;\n}\n\nexport type CoordinatorAccountLinkDecision =\n\t| {\n\t\t\tkind: \"eligible\";\n\t\t\tdisposition: \"create\" | \"existing\";\n\t\t\tcoordinatorId: string;\n\t\t\tidentityId: string;\n\t\t\taccount: CoordinatorAccountReference;\n\t }\n\t| {\n\t\t\tkind: \"rejected\";\n\t\t\terror:\n\t\t\t\t| \"invalid_link_input\"\n\t\t\t\t| \"ownership_review_required\"\n\t\t\t\t| \"ownership_mismatch\"\n\t\t\t\t| \"invalid_link_snapshot\"\n\t\t\t\t| \"account_link_conflict\"\n\t\t\t\t| \"identity_link_conflict\"\n\t\t\t\t| \"link_revoked\";\n\t };\n\nfunction isId(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length > 0 &&\n\t\tvalue.length <= 256 &&\n\t\tvalue === value.trim() &&\n\t\t!CONTROL_OR_FORMAT.test(value)\n\t);\n}\n\nfunction sameAccount(\n\tleft: CoordinatorAccountReference,\n\tright: CoordinatorAccountReference,\n): boolean {\n\treturn left.issuer === right.issuer && left.subject === right.subject;\n}\n\nfunction isFingerprint(value: unknown): value is string {\n\treturn typeof value === \"string\" && FINGERPRINT.test(value);\n}\n\ninterface ValidatedLinkInput {\n\treadonly coordinatorId: string;\n\treadonly identityId: string;\n\treadonly account: CoordinatorAccountReference;\n\treadonly deviceId: string;\n\treadonly fingerprint: string;\n\treadonly ownership: unknown;\n\treadonly accountLink: unknown;\n\treadonly identityLink: unknown;\n}\n\nfunction readLinkInput(input: unknown, options: { issuer: string }): ValidatedLinkInput | null {\n\tif (!isRecord(input)) return null;\n\tconst coordinatorId = field(input, \"coordinatorId\");\n\tconst identityId = field(input, \"identityId\");\n\tconst accountValue = field(input, \"account\");\n\tconst device = field(input, \"device\");\n\tconst ownership = field(input, \"ownership\");\n\tconst accountLink = field(input, \"accountLink\");\n\tconst identityLink = field(input, \"identityLink\");\n\tif (!isRecord(device) || !isId(coordinatorId) || !isId(identityId)) return null;\n\tconst deviceId = field(device, \"deviceId\");\n\tconst fingerprint = field(device, \"fingerprint\");\n\tif (!isId(deviceId) || !isFingerprint(fingerprint)) return null;\n\tconst account = parseCoordinatorAccountReference(accountValue, options);\n\tif (!account.ok) return null;\n\treturn {\n\t\tcoordinatorId,\n\t\tidentityId,\n\t\taccount: account.account,\n\t\tdeviceId,\n\t\tfingerprint,\n\t\townership,\n\t\taccountLink,\n\t\tidentityLink,\n\t};\n}\n\nfunction readLinkSnapshot(\n\tvalue: unknown,\n\tcoordinatorId: string,\n): CoordinatorAccountLink | undefined {\n\tif (!isRecord(value)) return undefined;\n\tconst snapshotCoordinatorId = field(value, \"coordinatorId\");\n\tconst identityId = field(value, \"identityId\");\n\tconst status = field(value, \"status\");\n\tconst account = readAccountReference(field(value, \"account\"));\n\tif (\n\t\tsnapshotCoordinatorId !== coordinatorId ||\n\t\t!isId(identityId) ||\n\t\t(status !== \"active\" && status !== \"revoked\") ||\n\t\t!account.ok\n\t) {\n\t\treturn undefined;\n\t}\n\t// A different issuer is a valid stored link, but conflicts with this request.\n\treturn { coordinatorId, identityId, status, account: account.account };\n}\n\nfunction validateOwnership(expected: ValidatedLinkInput): CoordinatorAccountLinkDecision | null {\n\tconst { ownership } = expected;\n\tif (!isRecord(ownership)) return { kind: \"rejected\", error: \"invalid_link_input\" };\n\tconst kind = field(ownership, \"kind\");\n\tif (kind === \"invitation_claim\" || kind === \"unavailable\") {\n\t\treturn { kind: \"rejected\", error: \"ownership_review_required\" };\n\t}\n\tif (kind !== \"controller_verified\" && kind !== \"admin_verified\") {\n\t\treturn { kind: \"rejected\", error: \"invalid_link_input\" };\n\t}\n\tconst coordinatorId = field(ownership, \"coordinatorId\");\n\tconst identityId = field(ownership, \"identityId\");\n\tconst deviceId = field(ownership, \"deviceId\");\n\tconst fingerprint = field(ownership, \"fingerprint\");\n\tif (!isId(coordinatorId) || !isId(identityId) || !isId(deviceId) || !isFingerprint(fingerprint)) {\n\t\treturn { kind: \"rejected\", error: \"invalid_link_input\" };\n\t}\n\tif (\n\t\tcoordinatorId !== expected.coordinatorId ||\n\t\tidentityId !== expected.identityId ||\n\t\tdeviceId !== expected.deviceId ||\n\t\tfingerprint !== expected.fingerprint\n\t) {\n\t\treturn { kind: \"rejected\", error: \"ownership_mismatch\" };\n\t}\n\treturn null;\n}\n\nfunction validateSnapshots(expected: ValidatedLinkInput): CoordinatorAccountLinkDecision | null {\n\tconst { coordinatorId, identityId, account } = expected;\n\tconst accountLink =\n\t\texpected.accountLink === null ? null : readLinkSnapshot(expected.accountLink, coordinatorId);\n\tconst identityLink =\n\t\texpected.identityLink === null ? null : readLinkSnapshot(expected.identityLink, coordinatorId);\n\tif (accountLink === undefined || identityLink === undefined) {\n\t\treturn { kind: \"rejected\", error: \"invalid_link_snapshot\" };\n\t}\n\tif (accountLink !== null && !sameAccount(accountLink.account, account)) {\n\t\treturn { kind: \"rejected\", error: \"invalid_link_snapshot\" };\n\t}\n\tif (identityLink !== null && identityLink.identityId !== identityId) {\n\t\treturn { kind: \"rejected\", error: \"invalid_link_snapshot\" };\n\t}\n\tif (accountLink?.status === \"revoked\" || identityLink?.status === \"revoked\") {\n\t\treturn { kind: \"rejected\", error: \"link_revoked\" };\n\t}\n\tif (accountLink !== null && accountLink.identityId !== identityId) {\n\t\treturn { kind: \"rejected\", error: \"account_link_conflict\" };\n\t}\n\tif (identityLink !== null && !sameAccount(identityLink.account, account)) {\n\t\treturn { kind: \"rejected\", error: \"identity_link_conflict\" };\n\t}\n\tif ((accountLink === null) !== (identityLink === null)) {\n\t\treturn { kind: \"rejected\", error: \"invalid_link_snapshot\" };\n\t}\n\treturn null;\n}\n\n/**\n * Metadata decision only. Supply trusted internal ownership evidence and a\n * same-coordinator snapshot; any future writer must recheck both links atomically.\n * Authentication protocol approval remains required before runtime integration.\n */\nexport function decideCoordinatorAccountLink(\n\tinput: CoordinatorAccountLinkInput,\n\toptions: { issuer: string },\n): CoordinatorAccountLinkDecision {\n\tconst validated = readLinkInput(input, options);\n\tif (!validated) return { kind: \"rejected\", error: \"invalid_link_input\" };\n\tconst ownershipDecision = validateOwnership(validated);\n\tif (ownershipDecision) return ownershipDecision;\n\tconst snapshotDecision = validateSnapshots(validated);\n\tif (snapshotDecision) return snapshotDecision;\n\treturn {\n\t\tkind: \"eligible\",\n\t\tdisposition: validated.accountLink === null ? \"create\" : \"existing\",\n\t\tcoordinatorId: validated.coordinatorId,\n\t\tidentityId: validated.identityId,\n\t\taccount: validated.account,\n\t};\n}\n","import { isCoordinatorAccountIssuer } from \"./coordinator-auth-contract.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type {\n\tCoordinatorAuthLinkConfig,\n\tCoordinatorAuthLinkSigner,\n} from \"./coordinator-auth-link-contract.js\";\n\nexport type Captured = Record<string, unknown>;\nexport function isHash(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length === 64 && /^[0-9a-f]{64}$/.test(value);\n}\nexport function capture(value: unknown, fields: readonly string[]): Captured | null {\n\tif (!value || typeof value !== \"object\") return null;\n\ttry {\n\t\tif (Array.isArray(value)) return null;\n\t\tconst result: Captured = {};\n\t\tfor (const key of fields) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\t\tif (!descriptor || !Object.hasOwn(descriptor, \"value\")) return null;\n\t\t\tresult[key] = descriptor.value;\n\t\t}\n\t\treturn result;\n\t} catch {\n\t\treturn null;\n\t}\n}\nexport function captureAuthLinkConfig(value: unknown): CoordinatorAuthLinkConfig | null {\n\tconst c = capture(value, [\"coordinatorId\", \"issuer\", \"revision\", \"enabled\"]);\n\tif (\n\t\t!c ||\n\t\t!isAuthControllerId(c.coordinatorId) ||\n\t\t!isCoordinatorAccountIssuer(c.issuer) ||\n\t\t!isHash(c.revision) ||\n\t\ttypeof c.enabled !== \"boolean\"\n\t)\n\t\treturn null;\n\treturn c as unknown as CoordinatorAuthLinkConfig;\n}\nfunction isPublicKey(value: unknown): value is string {\n\tif (typeof value !== \"string\" || value.length > 4096) return false;\n\tconst flat = value.replace(/[\\r\\n]/g, \"\");\n\treturn flat.length > 0 && flat.trim() === flat && !/[\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(flat);\n}\nexport function captureAuthLinkSigner(value: unknown): CoordinatorAuthLinkSigner | null {\n\tconst s = capture(value, [\"groupId\", \"deviceId\", \"publicKey\", \"fingerprint\"]);\n\tif (\n\t\t!s ||\n\t\t!isAuthControllerId(s.groupId) ||\n\t\t!isAuthControllerId(s.deviceId) ||\n\t\t!isPublicKey(s.publicKey) ||\n\t\t!isHash(s.fingerprint)\n\t)\n\t\treturn null;\n\treturn s as unknown as CoordinatorAuthLinkSigner;\n}\n","import { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport {\n\tAUTH_CURRENT_LEGACY_ASSIGNMENT_ROWS_SQL,\n\tAUTH_CURRENT_LEGACY_ASSIGNMENT_SQL,\n\tAUTH_LEGACY_ASSIGNMENT_CAPTURE_SQL,\n\tcaptureCurrentLegacyAssignment,\n} from \"./coordinator-auth-legacy-assignment.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport type {\n\tCoordinatorAuthLinkConfig,\n\tCoordinatorAuthLinkSigner,\n} from \"./coordinator-auth-link-contract.js\";\nimport { captureAuthLinkConfig, captureAuthLinkSigner } from \"./coordinator-auth-link-input.js\";\nimport type { AuthRead } from \"./coordinator-auth-read-set.js\";\nimport {\n\ted25519KeyIdForRevocation,\n\tparseSshEd25519PublicKeyForRevocation,\n} from \"./coordinator-ed25519-key-id-compat.js\";\nimport {\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES,\n\tlegacyDecisionCountsAsOwnerSql,\n} from \"./coordinator-legacy-team-completion.js\";\nimport { legacyTeamCandidateId } from \"./recipient-policy-identifiers.js\";\n\nexport interface CoordinatorDeviceClaimReadinessInput {\n\t/** The authenticated enrollment and the caller's pinned current local Identity. */\n\tsigner: CoordinatorAuthLinkSigner;\n\tidentityId: string;\n\t/** Internal retry context, never an instruction to ignore a different claimant. */\n\tattemptId?: string;\n}\nexport type CoordinatorDeviceClaimReadiness =\n\t| { kind: \"eligible\"; authority: \"device_claim\"; identityId: string }\n\t| { kind: \"unavailable\" };\n\n// These older tables have text keys, not canonical key-ID columns. Classify their\n// actual key bytes once, then reject any newly introduced text key in the final\n// SQL statement. Other row/Identity changes are checked live by the predicate.\nconst CURRENT_KEYS = `SELECT public_key FROM enrolled_devices\n UNION SELECT public_key FROM coordinator_auth_controller_attestations\n UNION SELECT public_key FROM coordinator_auth_link_attempts\n UNION SELECT bound_public_key AS public_key FROM coordinator_invites`;\n/**\n * Read-set form of the key list: one JSON string per distinct stored text key, in key\n * order. Its guard keeps the rule of AUTH_DEVICE_CLAIM_CURRENT_SUBJECT_COMPATIBLE_SQL:\n * no stored key may be outside the list that was classified. A key that disappears\n * leaves the classification valid, so it does not abort the write.\n */\nexport const AUTH_DEVICE_CLAIM_KEYS_READ: AuthRead = {\n\tsql: `SELECT json_quote(public_key) AS row FROM (${CURRENT_KEYS})\n WHERE typeof(public_key) = 'text' ORDER BY public_key`,\n\tvalues: [],\n\tholds: (seenKeys) => ({\n\t\tsql: `SELECT NOT EXISTS (SELECT public_key FROM (${CURRENT_KEYS}) WHERE typeof(public_key) = 'text'\n EXCEPT SELECT value FROM json_each(?)) AS holds`,\n\t\tvalues: [seenKeys],\n\t}),\n};\nconst KEY_SNAPSHOT_SQL = `SELECT (${AUTH_LEGACY_ASSIGNMENT_CAPTURE_SQL}) AS assignment_snapshot,\n (SELECT count(*) FROM pragma_table_info('coordinator_auth_browser_transactions') WHERE name = 'start_order') AS connection_session,\n (SELECT json_group_array(public_key) FROM (\n SELECT public_key FROM (${CURRENT_KEYS}) WHERE typeof(public_key) = 'text' ORDER BY public_key)) AS keys`;\n\n/** Shared by readiness and INSERT/transition guards; 15 inputs bound once.\n * Predicates read the key lists with json_each(p.same_keys) and json_each(p.key_snapshot)\n * instead of the two key CTEs. SQLite 3.54.0 and 3.54.1 (production D1) refuse a statement\n * that resolves a CTE name after about 100 table references, and each CTE reference counts\n * every table in its body again.\n */\nexport const AUTH_DEVICE_CLAIM_INPUT_SQL = `WITH claim_input(\n coordinator_id, identity_id, group_id, device_id, public_key, fingerprint, key_id,\n now_ms, now_iso, attempt_id, issuer, revision, key_snapshot, same_keys, assignment_snapshot\n) AS (VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?))`;\n\n/** The same 15 inputs as one FROM row, for statements that must not use WITH. */\nexport const AUTH_DEVICE_CLAIM_INPUT_ROW_SQL = `(SELECT ? AS coordinator_id, ? AS identity_id, ? AS group_id,\n ? AS device_id, ? AS public_key, ? AS fingerprint, ? AS key_id, ? AS now_ms, ? AS now_iso, ? AS attempt_id,\n ? AS issuer, ? AS revision, ? AS key_snapshot, ? AS same_keys, ? AS assignment_snapshot)`;\n\nconst sameKey = (column: string) =>\n\t`EXISTS (SELECT 1 FROM json_each(p.same_keys) k WHERE k.value = ${column})`;\nconst otherSubject = (device: string, key: string) =>\n\t`(${device} IS NOT p.device_id OR NOT ${sameKey(key)})`;\n\n/** Current requester contradictions and captured-assignment staleness deny access. */\nexport const AUTH_DEVICE_CLAIM_CURRENT_SUBJECT_COMPATIBLE_SQL = `\n (p.assignment_snapshot IS NULL OR ${AUTH_CURRENT_LEGACY_ASSIGNMENT_SQL})\n AND\n NOT EXISTS (SELECT public_key FROM (${CURRENT_KEYS}) WHERE typeof(public_key) = 'text'\n EXCEPT SELECT value FROM json_each(p.key_snapshot))\n AND NOT EXISTS (SELECT 1 FROM enrolled_devices e WHERE\n (e.device_id = p.device_id OR ${sameKey(\"e.public_key\")})\n AND e.identity_id IS NOT NULL AND e.identity_id <> p.identity_id)\n AND NOT EXISTS (SELECT 1 FROM coordinator_device_ownership_bindings b WHERE\n (b.device_id = p.device_id OR b.key_id = p.key_id) AND b.identity_id <> p.identity_id)`;\n\n/** Negative setup checks shared by first-link admission and legacy completion.\n * p comes from AUTH_DEVICE_CLAIM_INPUT_SQL. Existing exact D/K/X\n * ownership is compatible here. The producer decides whether to reuse it.\n * This predicate never supplies positive authority or first-link absence rules.\n */\nexport const AUTH_DEVICE_CLAIM_BINDING_STRUCTURE_SQL = `(\n (SELECT count(*) FROM enrolled_devices e WHERE e.device_id=p.device_id) BETWEEN 1 AND 50\n AND NOT EXISTS (SELECT 1 FROM enrolled_devices e WHERE e.device_id=p.device_id\n AND (e.public_key<>p.public_key OR e.fingerprint<>p.fingerprint OR (e.identity_id IS NOT NULL AND e.identity_id<>p.identity_id)))\n AND NOT EXISTS (SELECT 1 FROM enrolled_devices e,json_each(p.same_keys) k WHERE e.public_key=k.value AND e.device_id<>p.device_id)\n ) AND (\n NOT EXISTS (SELECT 1 FROM coordinator_device_ownership_bindings b WHERE (b.device_id=p.device_id OR b.key_id=p.key_id)\n AND (b.device_id<>p.device_id OR b.key_id<>p.key_id OR b.identity_id<>p.identity_id OR b.coordinator_id<>p.coordinator_id))\n ) AND (\n NOT EXISTS (SELECT 1 FROM coordinator_owner_enrollment_attempts o WHERE o.coordinator_id=p.coordinator_id\n AND o.state IN ('pending','browser_claimed','oidc_verified','confirmed') AND o.expires_at_ms>p.now_ms\n AND (o.device_id=p.device_id OR o.key_id=p.key_id))\n AND NOT EXISTS (SELECT 1 FROM coordinator_device_rebind_attempts r WHERE r.coordinator_id=p.coordinator_id\n AND r.state IN ('pending','browser_claimed','oidc_verified','confirmed') AND r.expires_at_ms>p.now_ms\n AND (r.device_id=p.device_id OR r.key_id=p.key_id))\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_link_attempts a WHERE a.coordinator_id=p.coordinator_id\n AND a.state IN ('pending','browser_claimed','oidc_verified','confirmed') AND a.expires_at_ms>p.now_ms\n AND a.identity_id<>p.identity_id AND (a.device_id=p.device_id OR a.public_key IN (SELECT value FROM json_each(p.same_keys))))\n )`;\n\n/** A shared reader's own attestations are current checks, not historical origin pins. */\nexport const AUTH_DEVICE_CLAIM_REQUESTER_ATTESTATION_COMPATIBLE_SQL = `NOT EXISTS (\n SELECT 1 FROM coordinator_auth_controller_attestations a WHERE a.coordinator_id = p.coordinator_id\n AND (a.device_id = p.device_id OR ${sameKey(\"a.public_key\")})\n AND (a.revoked_at IS NOT NULL OR a.identity_id <> p.identity_id))`;\n\n// The peer must match its current enrollment, not just an old device label.\nconst matchingLegacyPeerEnrollment = `e.group_id = p.group_id AND e.enabled = 1\n AND e.device_id <> p.device_id AND e.fingerprint <> p.fingerprint\n AND NOT ${sameKey(\"e.public_key\")}\n AND EXISTS (SELECT 1 FROM json_each(p.assignment_snapshot, '$.distinct_keys') k WHERE k.value = e.public_key)\n AND EXISTS (SELECT 1 FROM ${AUTH_CURRENT_LEGACY_ASSIGNMENT_ROWS_SQL} ca, json_each(ca.manifest_json, '$.device_decisions') d\n WHERE json_extract(d.value, '$.device_id') = e.device_id\n AND json_extract(d.value, '$.key_fingerprint') = e.fingerprint\n AND json_extract(d.value, '$.identity_id') = p.identity_id\n AND (json_extract(d.value, '$.decision') = 'included' AND json_extract(d.value, '$.enabled') = 1\n AND ${legacyDecisionCountsAsOwnerSql(\"d.value\")}))`;\nconst live = (alias: string) =>\n\t`${alias}.state IN ('pending','browser_claimed','oidc_verified','confirmed') AND ${alias}.expires_at_ms > p.now_ms`;\n// Pending promises expire. Consumed evidence survives later expiry/revocation,\n// but an invite revoked before consumption supplies no footprint.\nconst inviteLive = `(i.revoked_at IS NULL AND i.expires_at > p.now_iso)`;\nconst inviteConsumed = `(i.consumed_at IS NOT NULL AND i.consumed_at <> '' AND (i.revoked_at IS NULL OR i.revoked_at > i.consumed_at))`;\n/** Alias i: an invite that was consumed and not revoked before its consumption. */\nexport const AUTH_DEVICE_CLAIM_INVITE_CONSUMED_SQL = inviteConsumed;\nconst inviteBinding = `(i.bound_device_id IS NOT NULL OR i.bound_public_key IS NOT NULL)`;\nconst completionJson = `CASE WHEN typeof(c.manifest_json) = 'text' AND json_valid(c.manifest_json) THEN c.manifest_json ELSE '{}' END`;\n\n/** Consumed assignments survive removal/re-enrollment and later token revocation. */\nexport const AUTH_DEVICE_CLAIM_REQUESTER_INVITE_COMPATIBLE_SQL = `NOT EXISTS (\n SELECT 1 FROM coordinator_invites i WHERE ${inviteConsumed}\n AND (i.bound_device_id = p.device_id OR ${sameKey(\"i.bound_public_key\")} OR i.bound_fingerprint = p.fingerprint)\n AND ((i.assigned_identity_id IS NOT NULL AND i.assigned_identity_id <> p.identity_id)\n OR (i.target_identity_id IS NOT NULL AND i.target_identity_id <> p.identity_id)))`;\n\n/** A completed other-Identity binding remains a contradiction without its old controller. */\nexport const AUTH_DEVICE_CLAIM_REQUESTER_LINK_COMPATIBLE_SQL = `NOT EXISTS (\n SELECT 1 FROM coordinator_auth_account_links l JOIN coordinator_auth_link_attempts a\n ON a.coordinator_id = l.coordinator_id AND a.link_id = l.link_id\n WHERE l.coordinator_id = p.coordinator_id AND l.identity_id <> p.identity_id\n AND (a.device_id = p.device_id OR ${sameKey(\"a.public_key\")}))\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_links l JOIN coordinator_auth_link_audit_log a\n ON a.coordinator_id = l.coordinator_id AND a.link_id = l.link_id\n WHERE l.coordinator_id = p.coordinator_id AND a.device_id = p.device_id AND l.identity_id <> p.identity_id)`;\n\n/**\n * Shared by first-link writes and exact-assignment status reads. Another\n * device's guessed label neither contradicts nor competes with this device's\n * own claim. Labels exist only on included rows, so skipping them never skips\n * an exclusion. The label test sits beside the coordinator test so D1's\n * expression depth (max 100) does not grow.\n */\nconst legacyCompletionSql = (predicate: string) => `NOT EXISTS (\n SELECT 1 FROM coordinator_legacy_team_completions c, json_each(${completionJson}, '$.device_decisions') d\n WHERE (${legacyDecisionCountsAsOwnerSql(\"d.value\", \"deny\")} AND json_extract(${completionJson}, '$.coordinator_id') = p.coordinator_id) AND (\n ${predicate}))`;\nconst legacyThisDevice = `(json_extract(d.value, '$.device_id') = p.device_id OR json_extract(d.value, '$.key_fingerprint') = p.fingerprint)`;\nconst legacyPeerBranch = `(json_extract(d.value, '$.identity_id') = p.identity_id\n AND (json_extract(d.value, '$.device_id') IS NOT p.device_id OR json_extract(d.value, '$.key_fingerprint') IS NOT p.fingerprint)\n AND NOT (json_extract(d.value, '$.device_id') <> p.device_id\n AND json_extract(d.value, '$.key_fingerprint') <> p.fingerprint\n AND json_extract(d.value, '$.decision') = 'included' AND json_extract(d.value, '$.enabled') = 1\n AND EXISTS (SELECT 1 FROM ${AUTH_CURRENT_LEGACY_ASSIGNMENT_ROWS_SQL} ca WHERE ca.group_id = c.group_id\n AND ca.candidate_ref = c.candidate_ref AND ca.manifest_json = c.manifest_json)))`;\nexport const AUTH_DEVICE_CLAIM_LEGACY_COMPATIBLE_SQL = legacyCompletionSql(`(${legacyThisDevice}\n AND (json_extract(d.value, '$.decision') = 'excluded' OR json_extract(d.value, '$.identity_id') IS NOT p.identity_id))\n OR ${legacyPeerBranch}`);\n/**\n * The legacy checks an ownership binding cannot waive: an exclusion of this\n * device, and other devices' history under the claimed Identity. A binding\n * waives only history that recorded this device under another Identity.\n */\nexport const AUTH_DEVICE_CLAIM_LEGACY_UNWAIVABLE_SQL = legacyCompletionSql(`(${legacyThisDevice}\n AND json_extract(d.value, '$.decision') = 'excluded')\n OR ${legacyPeerBranch}`);\n\n/**\n * p is the single claim_input row. This is device-claim eligibility, never operator\n * authority. No group-wide member scan may turn unrelated people into a denial.\n * All NULL comparisons below deliberately reject mismatched/absent binding pins.\n */\n// Parenthesized conjunctions avoid a long left-deep AND tree when browser\n// receipt queries embed this predicate under their own conditions (D1 depth 100).\nexport const AUTH_DEVICE_CLAIM_ELIGIBLE_SQL = `(\n EXISTS (SELECT 1 FROM enrolled_devices e JOIN groups g ON g.group_id = e.group_id\n WHERE e.group_id = p.group_id AND e.device_id = p.device_id AND e.public_key = p.public_key\n AND e.fingerprint = p.fingerprint AND e.enabled = 1 AND g.archived_at IS NULL\n AND (e.identity_id IS NULL OR e.identity_id = p.identity_id))\n AND (${AUTH_DEVICE_CLAIM_CURRENT_SUBJECT_COMPATIBLE_SQL})\n AND NOT EXISTS (SELECT 1 FROM coordinator_device_revocations r\n WHERE (r.subject_kind = 'device_id' AND r.subject_value = p.device_id)\n OR (r.subject_kind = 'ed25519_key' AND r.subject_value = p.key_id))\n AND NOT EXISTS (SELECT 1 FROM enrolled_devices e WHERE\n e.identity_id = p.identity_id AND ${otherSubject(\"e.device_id\", \"e.public_key\")}\n AND NOT (${matchingLegacyPeerEnrollment}))\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_controller_attestations a WHERE a.coordinator_id = p.coordinator_id AND (\n ((a.device_id = p.device_id OR ${sameKey(\"a.public_key\")}) AND (a.revoked_at IS NOT NULL OR a.identity_id <> p.identity_id))\n OR ((a.identity_id = p.identity_id OR a.enrollment_identity_id = p.identity_id) AND ${otherSubject(\"a.device_id\", \"a.public_key\")})\n OR (a.group_id = p.group_id AND a.device_id = p.device_id AND a.public_key = p.public_key\n AND a.fingerprint = p.fingerprint AND a.identity_id = p.identity_id AND a.revoked_at IS NULL AND a.revision = 1)))\n ) AND (\n NOT EXISTS (SELECT 1 FROM coordinator_device_ownership_bindings b WHERE\n b.identity_id = p.identity_id AND (b.device_id IS NOT p.device_id OR b.key_id IS NOT p.key_id))\n AND NOT EXISTS (SELECT 1 FROM coordinator_identity_group_grants g\n WHERE g.coordinator_id = p.coordinator_id AND g.identity_id = p.identity_id)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_device_claims d WHERE d.coordinator_id = p.coordinator_id\n AND (d.identity_id = p.identity_id OR d.device_id = p.device_id OR d.key_id = p.key_id))\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_links l\n WHERE l.coordinator_id = p.coordinator_id AND l.identity_id = p.identity_id)\n ) AND (\n (${AUTH_DEVICE_CLAIM_REQUESTER_LINK_COMPATIBLE_SQL})\n AND NOT EXISTS (SELECT 1 FROM coordinator_owner_enrollment_attempts o WHERE o.coordinator_id = p.coordinator_id\n AND ${live(\"o\")} AND (o.device_id = p.device_id OR o.key_id = p.key_id OR o.identity_id = p.identity_id))\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_link_attempts a WHERE a.coordinator_id = p.coordinator_id AND ${live(\"a\")}\n AND NOT (a.attempt_id IS p.attempt_id AND a.authority_kind = 'device_claim' AND a.identity_id = p.identity_id\n AND a.group_id = p.group_id AND a.device_id = p.device_id AND a.public_key = p.public_key AND a.fingerprint = p.fingerprint)\n AND ((a.authority_kind = 'device_claim' AND a.identity_id <> p.identity_id AND (a.device_id = p.device_id OR ${sameKey(\"a.public_key\")}))\n OR (a.identity_id = p.identity_id AND ${otherSubject(\"a.device_id\", \"a.public_key\")})))\n ) AND (\n NOT EXISTS (SELECT 1 FROM coordinator_invites i WHERE (\n (${inviteConsumed} AND (i.bound_device_id = p.device_id OR ${sameKey(\"i.bound_public_key\")} OR i.bound_fingerprint = p.fingerprint)\n AND ((i.assigned_identity_id IS NOT NULL AND i.assigned_identity_id <> p.identity_id) OR (i.target_identity_id IS NOT NULL AND i.target_identity_id <> p.identity_id)))\n OR ((${inviteLive} OR ${inviteConsumed}) AND (\n ((i.assigned_identity_id = p.identity_id OR i.target_identity_id = p.identity_id)\n AND ((${inviteLive} AND (i.consumed_at IS NULL OR i.consumed_at = '')) OR (${inviteBinding} AND ${otherSubject(\"i.bound_device_id\", \"i.bound_public_key\")})))\n OR (i.recipient_actor_id = p.identity_id AND ${inviteBinding} AND ${otherSubject(\"i.bound_device_id\", \"i.bound_public_key\")})\n OR (i.inviter_actor_id = p.identity_id AND i.inviter_device_id IS NOT NULL AND i.inviter_device_id <> p.device_id)))))\n AND ${AUTH_DEVICE_CLAIM_LEGACY_COMPATIBLE_SQL}) AND (${AUTH_DEVICE_CLAIM_BINDING_STRUCTURE_SQL})`;\n\nfunction captureInput(input: CoordinatorDeviceClaimReadinessInput) {\n\ttry {\n\t\tif (!input || typeof input !== \"object\" || Array.isArray(input)) return null;\n\t\tconst identity = Object.getOwnPropertyDescriptor(input, \"identityId\");\n\t\tconst signer = Object.getOwnPropertyDescriptor(input, \"signer\");\n\t\tconst attempt = Object.getOwnPropertyDescriptor(input, \"attemptId\");\n\t\tconst s = signer && \"value\" in signer ? captureAuthLinkSigner(signer.value) : null;\n\t\tif (!identity || !(\"value\" in identity) || !isAuthControllerId(identity.value) || !s)\n\t\t\treturn null;\n\t\tif (attempt && (!(\"value\" in attempt) || !isAuthControllerId(attempt.value))) return null;\n\t\tif (!attempt && \"attemptId\" in input) return null;\n\t\treturn { signer: s, identityId: identity.value, attemptId: attempt?.value ?? null };\n\t} catch {\n\t\treturn null;\n\t}\n}\n\ninterface CapturedClaimEligibility {\n\tidentityId: string;\n\tvalues: AuthLinkStatement[\"values\"];\n\tconnectionSession: boolean;\n}\ninterface ClaimKeySnapshot {\n\tkeys: string;\n\tassignment_snapshot: string | null;\n\tconnection_session: number;\n}\nfunction hasKeyBlob(key: string, blob: Uint8Array): boolean {\n\tconst parsed = parseSshEd25519PublicKeyForRevocation(key);\n\treturn parsed.kind === \"ed25519\" && parsed.blob.every((byte, index) => byte === blob[index]);\n}\n/** A validated claim request with the canonical ID and raw bytes of its key. */\nexport interface DeviceClaimSubject {\n\tconfig: CoordinatorAuthLinkConfig;\n\tsigner: CoordinatorAuthLinkSigner;\n\tidentityId: string;\n\tattemptId: string | null;\n\tkeyId: string;\n\tkeyBlob: Uint8Array;\n}\n\n/** Validates the request and configuration and derives the key ID. Reads nothing. */\nexport async function captureDeviceClaimSubject(\n\tinput: CoordinatorDeviceClaimReadinessInput,\n\tconfig: CoordinatorAuthLinkConfig,\n): Promise<DeviceClaimSubject | null> {\n\tconst c = captureAuthLinkConfig(config);\n\tconst i = captureInput(input);\n\tif (!c?.enabled || !i) return null;\n\tconst target = parseSshEd25519PublicKeyForRevocation(i.signer.publicKey);\n\tif (target.kind !== \"ed25519\") return null;\n\tconst keyId = await ed25519KeyIdForRevocation(i.signer.publicKey);\n\tif (!keyId) return null;\n\treturn { config: c, ...i, keyId, keyBlob: target.blob };\n}\n\n/** The three inputs of AUTH_LEGACY_ASSIGNMENT_CAPTURE_SQL for this subject. */\nexport function deviceClaimAssignmentInputs(\n\tsubject: Pick<DeviceClaimSubject, \"config\" | \"signer\">,\n): AuthLinkStatement[\"values\"] {\n\treturn [\n\t\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES,\n\t\tsubject.signer.groupId,\n\t\tlegacyTeamCandidateId(subject.config.coordinatorId, subject.signer.groupId),\n\t];\n}\n\nexport interface DeviceClaimKeyFacts {\n\t/** Every stored text key. */\n\tkeys: string[];\n\t/** The stored text forms of the subject's own key. */\n\taliases: string[];\n\t/** The legacy assignment this device relies on, or null when it has none. */\n\tassignmentSnapshot: string | null;\n}\n\n/** Classifies the stored keys and the stored legacy assignment for the subject. */\nexport function deriveDeviceClaimKeyFacts(\n\tsubject: DeviceClaimSubject,\n\tstored: { keys: unknown; assignment: string | null | undefined },\n): DeviceClaimKeyFacts {\n\tconst { keys } = stored;\n\tif (!Array.isArray(keys) || !keys.every((key): key is string => typeof key === \"string\"))\n\t\tthrow new Error(\"auth_device_claim_unavailable\");\n\tconst aliases = keys.filter((key) => hasKeyBlob(key, subject.keyBlob));\n\tconst distinctKeys = keys.filter(\n\t\t(key) =>\n\t\t\t!aliases.includes(key) && parseSshEd25519PublicKeyForRevocation(key).kind === \"ed25519\",\n\t);\n\tconst assignmentSnapshot = captureCurrentLegacyAssignment(stored.assignment, {\n\t\tcoordinatorId: subject.config.coordinatorId,\n\t\tidentityId: subject.identityId,\n\t\tsigner: subject.signer,\n\t\tdistinctKeys,\n\t});\n\treturn { keys, aliases, assignmentSnapshot };\n}\n\n/**\n * The clock as the ISO text stored timestamps use. Auth clocks are documented as safe up\n * to Number.MAX_SAFE_INTEGER less a lifetime, past the largest four-digit-year ISO date;\n * there the latest four-digit timestamp keeps comparisons with stored text correct.\n */\nfunction isoClock(now: number): string {\n\treturn now < Date.UTC(10000, 0, 1) ? new Date(now).toISOString() : \"9999-12-31T23:59:59.999Z\";\n}\n\n/** Capture only server-derived key metadata; a later writer must include the SQL guard. */\nexport async function captureDeviceClaimEligibility(\n\tbackend: Pick<AuthLinkBackend, \"first\">,\n\tinput: CoordinatorDeviceClaimReadinessInput,\n\tconfig: CoordinatorAuthLinkConfig,\n\tnow: number,\n): Promise<CapturedClaimEligibility | null> {\n\tconst subject = await captureDeviceClaimSubject(input, config);\n\tif (!subject) return null;\n\tconst row = await backend.first<ClaimKeySnapshot>({\n\t\tsql: KEY_SNAPSHOT_SQL,\n\t\tvalues: deviceClaimAssignmentInputs(subject),\n\t});\n\tconst facts = deriveDeviceClaimKeyFacts(subject, {\n\t\tkeys: JSON.parse(row?.keys ?? \"null\"),\n\t\tassignment: row?.assignment_snapshot,\n\t});\n\treturn {\n\t\tidentityId: subject.identityId,\n\t\tconnectionSession: row?.connection_session === 1,\n\t\tvalues: [\n\t\t\tsubject.config.coordinatorId,\n\t\t\tsubject.identityId,\n\t\t\tsubject.signer.groupId,\n\t\t\tsubject.signer.deviceId,\n\t\t\tsubject.signer.publicKey,\n\t\t\tsubject.signer.fingerprint,\n\t\t\tsubject.keyId,\n\t\t\tnow,\n\t\t\tisoClock(now),\n\t\t\tsubject.attemptId,\n\t\t\tsubject.config.issuer,\n\t\t\tsubject.config.revision,\n\t\t\tJSON.stringify(facts.keys),\n\t\t\tJSON.stringify(facts.aliases),\n\t\t\tfacts.assignmentSnapshot,\n\t\t],\n\t};\n}\n","/**\n * Storage constraints, not an unlink/relink authorization API.\n * The explicit account-schema migration installs this DDL. Management writers\n * compose the winning proof, archive move and successor CAS in one backend.batch;\n * an Identity identifier alone never authorizes these effects.\n */\nexport const CONNECTION_BIRTH_COLUMNS = [\n\t\"coordinator_id\",\n\t\"link_id\",\n\t\"issuer\",\n\t\"subject\",\n\t\"identity_id\",\n\t\"attempt_id\",\n\t\"controller_attestation_id\",\n\t\"auth_config_revision\",\n\t\"created_at_ms\",\n\t\"revoked_at_ms\",\n\t\"authority_kind\",\n\t\"device_claim_id\",\n] as const;\n\nconst current = \"coordinator_auth_account_links\";\nconst history = \"coordinator_auth_account_connection_history\";\nconst orders = \"coordinator_auth_account_connection_orders\";\nconst birthEqual = CONNECTION_BIRTH_COLUMNS.map((c) => `c.${c} IS NEW.${c}`).join(\" AND \");\nconst immutableBirth = CONNECTION_BIRTH_COLUMNS.filter((c) => c !== \"revoked_at_ms\")\n\t.map((c) => `NEW.${c} IS NOT OLD.${c}`)\n\t.join(\" OR \");\n\n/** Aliases h/c: only delete the exact row whose raw birth was just archived. */\nexport const CONNECTION_ARCHIVED_CURRENT_MATCH_SQL = `h.original_rowid = c.rowid AND ${CONNECTION_BIRTH_COLUMNS.map((column) => `h.${column} IS c.${column}`).join(\" AND \")}`;\n\n/** Current + ended rows retain reservations without a separate association table. */\nexport const CONNECTION_RESERVATIONS_SQL = `SELECT coordinator_id, issuer, subject, identity_id, link_id, created_at_ms FROM ${current}\nUNION ALL SELECT coordinator_id, issuer, subject, identity_id, link_id, created_at_ms FROM ${history}`;\n\n/** Alias l must be the pinned current target, never a caller-selected Identity. */\nexport const CONNECTION_NOT_REVOKED_SQL = `l.revoked_at_ms IS NULL AND NOT EXISTS (\n SELECT 1 FROM ${history} h WHERE h.coordinator_id = l.coordinator_id\n AND h.identity_id = l.identity_id AND h.revoked_at_ms IS NOT NULL)`;\n\n/** The disconnected head is the one ended row without a successor, not a timestamp maximum. */\nexport const CONNECTION_DISCONNECTED_HEAD_SQL = `SELECT h.* FROM ${history} h\nWHERE h.coordinator_id = ? AND h.link_id = ? AND h.successor_link_id IS NULL\n AND NOT EXISTS (SELECT 1 FROM ${current} c WHERE c.coordinator_id = h.coordinator_id AND c.identity_id = h.identity_id)\n AND NOT EXISTS (SELECT 1 FROM ${history} r WHERE r.coordinator_id = h.coordinator_id AND r.identity_id = h.identity_id AND r.revoked_at_ms IS NOT NULL)`;\n\n/** Immediately follow each required single-row write inside the same batch. */\nexport const CONNECTION_ASSERT_ONE_WRITE_SQL = `INSERT INTO ${orders} (coordinator_id, last_order)\nSELECT NULL, 0 WHERE changes() <> 1`;\n\n/** Allocate inside the browser-start batch; overflow raises CHECK, never wraps or resets. */\nexport const CONNECTION_ALLOCATE_ORDER_SQL = `UPDATE ${orders} SET last_order = last_order + 1 WHERE coordinator_id = ?`;\n\n/** Aliases b/l require migration-owned start_order/signin_floor columns.\n * This predicate alone does not verify, consume or authorize a browser proof. */\nexport const CONNECTION_SIGNIN_ORDER_SQL = `b.coordinator_id = l.coordinator_id\n AND b.issuer = l.issuer\n AND b.start_order IS NOT NULL AND ((b.purpose = 'signin' AND b.start_order > l.signin_floor)\n OR (b.purpose = 'link' AND b.attempt_id = l.attempt_id AND EXISTS (\n SELECT 1 FROM coordinator_auth_link_attempts a WHERE a.coordinator_id = l.coordinator_id\n AND a.attempt_id = l.attempt_id AND a.link_id = l.link_id\n AND a.browser_transaction_hash = b.browser_transaction_hash AND a.state IN ('finalized','session_redeemed'))))`;\n\n/**\n * Explicit DDL only. The account-schema migration also installs browser order,\n * current floor and prior-attempt columns before management becomes available.\n * original_rowid retains raw old-row evidence; it is not a global generation ID.\n */\nexport const ACCOUNT_CONNECTION_STORAGE_STATEMENTS = [\n\t`CREATE TABLE ${history} (\n coordinator_id TEXT NOT NULL, link_id TEXT NOT NULL, issuer TEXT NOT NULL,\n subject TEXT NOT NULL CHECK(length(subject) BETWEEN 1 AND 255), identity_id TEXT NOT NULL,\n attempt_id TEXT NOT NULL, controller_attestation_id TEXT,\n auth_config_revision TEXT NOT NULL CHECK(length(auth_config_revision) = 64 AND auth_config_revision NOT GLOB '*[^0-9a-f]*'),\n created_at_ms INTEGER NOT NULL, revoked_at_ms INTEGER,\n authority_kind TEXT NOT NULL CHECK(authority_kind IN ('controller_attestation','device_claim')),\n device_claim_id TEXT, original_rowid INTEGER NOT NULL CHECK(typeof(original_rowid) = 'integer'),\n ended_at_ms INTEGER NOT NULL CHECK(typeof(ended_at_ms) = 'integer' AND ended_at_ms BETWEEN 0 AND 9007199254740991 AND ended_at_ms >= created_at_ms),\n end_attempt_id TEXT NOT NULL CHECK(length(end_attempt_id) BETWEEN 1 AND 256),\n successor_link_id TEXT CHECK(successor_link_id IS NULL OR (length(successor_link_id) BETWEEN 1 AND 256 AND successor_link_id <> link_id)),\n PRIMARY KEY(coordinator_id, link_id), UNIQUE(coordinator_id, end_attempt_id),\n UNIQUE(coordinator_id, successor_link_id),\n CHECK((authority_kind = 'controller_attestation' AND controller_attestation_id IS NOT NULL AND device_claim_id IS NULL)\n OR (authority_kind = 'device_claim' AND controller_attestation_id IS NULL AND device_claim_id IS NOT NULL))\n)`,\n\t`CREATE TRIGGER account_connection_history_insert BEFORE INSERT ON ${history}\nWHEN NEW.successor_link_id IS NOT NULL\n OR EXISTS (SELECT 1 FROM ${history} WHERE rowid = NEW.rowid)\n OR EXISTS (SELECT 1 FROM ${history} WHERE coordinator_id = NEW.coordinator_id AND (link_id = NEW.link_id OR end_attempt_id = NEW.end_attempt_id))\n OR EXISTS (SELECT 1 FROM ${history} WHERE coordinator_id = NEW.coordinator_id AND identity_id = NEW.identity_id AND successor_link_id IS NULL)\n OR NOT EXISTS (SELECT 1 FROM ${current} c WHERE c.rowid = NEW.original_rowid AND ${birthEqual})\nBEGIN SELECT RAISE(ABORT, 'connection_archive_source_invalid'); END`,\n\t// BEFORE INSERT uses -1 for an unallocated rowid. Keep stored rowids positive\n\t// so automatic allocation never reaches that sentinel from a negative rowid.\n\t`CREATE TRIGGER account_connection_history_rowid AFTER INSERT ON ${history}\n WHEN NEW.rowid < 1\n BEGIN SELECT RAISE(ABORT, 'connection_archive_source_invalid'); END`,\n\t`CREATE TRIGGER account_connection_history_update BEFORE UPDATE ON ${history}\nWHEN ${immutableBirth}\n OR NEW.rowid IS NOT OLD.rowid\n OR NEW.original_rowid IS NOT OLD.original_rowid OR NEW.ended_at_ms IS NOT OLD.ended_at_ms\n OR NEW.end_attempt_id IS NOT OLD.end_attempt_id\n OR (NEW.revoked_at_ms IS NOT OLD.revoked_at_ms AND (OLD.revoked_at_ms IS NOT NULL OR typeof(NEW.revoked_at_ms) <> 'integer' OR NEW.revoked_at_ms < 0 OR NEW.revoked_at_ms > 9007199254740991))\n OR (NEW.successor_link_id IS NOT OLD.successor_link_id AND (\n OLD.successor_link_id IS NOT NULL OR NEW.successor_link_id IS NULL OR NEW.revoked_at_ms IS NOT NULL\n OR EXISTS (SELECT 1 FROM ${history} h WHERE h.coordinator_id = NEW.coordinator_id AND h.successor_link_id = NEW.successor_link_id AND h.link_id <> OLD.link_id)\n OR NOT EXISTS (SELECT 1 FROM ${current} c WHERE c.coordinator_id = OLD.coordinator_id AND c.link_id = NEW.successor_link_id AND c.identity_id = OLD.identity_id AND c.revoked_at_ms IS NULL)\n OR EXISTS (SELECT 1 FROM ${history} h WHERE h.coordinator_id = OLD.coordinator_id AND h.identity_id = OLD.identity_id AND h.revoked_at_ms IS NOT NULL)))\nBEGIN SELECT RAISE(ABORT, 'connection_history_immutable'); END`,\n\t`CREATE TRIGGER account_connection_history_delete BEFORE DELETE ON ${history}\nBEGIN SELECT RAISE(ABORT, 'connection_history_immutable'); END`,\n\t`CREATE TRIGGER account_connection_current_insert BEFORE INSERT ON ${current}\nWHEN EXISTS (SELECT 1 FROM ${history} h WHERE h.coordinator_id = NEW.coordinator_id AND (\n h.link_id = NEW.link_id OR (h.issuer = NEW.issuer AND h.subject = NEW.subject AND h.identity_id <> NEW.identity_id)\n OR (h.identity_id = NEW.identity_id AND h.revoked_at_ms IS NOT NULL)))\nBEGIN SELECT RAISE(ABORT, 'connection_reserved_or_revoked'); END`,\n\t// This additional proof trigger has a real invariant and also makes V2's\n\t// exact three-trigger proof readiness check fail, including after old init replay.\n\t`CREATE TRIGGER account_connection_claim_history BEFORE INSERT ON coordinator_auth_device_claims\nWHEN EXISTS (SELECT 1 FROM ${history} h WHERE h.coordinator_id = NEW.coordinator_id AND h.identity_id = NEW.identity_id)\nBEGIN SELECT RAISE(ABORT, 'connection_claim_history_reserved'); END`,\n\t`CREATE TABLE ${orders} (\n coordinator_id TEXT PRIMARY KEY NOT NULL,\n last_order INTEGER NOT NULL CHECK(typeof(last_order) = 'integer' AND last_order BETWEEN 0 AND 9007199254740991)\n) WITHOUT ROWID`,\n\t`CREATE TRIGGER account_connection_order_insert BEFORE INSERT ON ${orders}\nWHEN NEW.last_order <> 0 OR EXISTS (SELECT 1 FROM ${orders} WHERE coordinator_id = NEW.coordinator_id)\nBEGIN SELECT RAISE(ABORT, 'connection_order_reset'); END`,\n\t`CREATE TRIGGER account_connection_order_update BEFORE UPDATE ON ${orders}\nWHEN NEW.coordinator_id IS NOT OLD.coordinator_id OR NEW.last_order <> OLD.last_order + 1\nBEGIN SELECT RAISE(ABORT, 'connection_order_reset'); END`,\n\t`CREATE TRIGGER account_connection_order_delete BEFORE DELETE ON ${orders}\nBEGIN SELECT RAISE(ABORT, 'connection_order_reset'); END`,\n] as const;\n","import { CONNECTION_BIRTH_COLUMNS } from \"./coordinator-account-connection-storage.js\";\n\nexport const CONNECTION_BIRTHS_SQL = `SELECT ${CONNECTION_BIRTH_COLUMNS.join(\",\")} FROM coordinator_auth_account_links UNION ALL SELECT ${CONNECTION_BIRTH_COLUMNS.join(\",\")} FROM coordinator_auth_account_connection_history`;\nfunction rootBirths(coordinator: string, link: string): string {\n\treturn `SELECT ${CONNECTION_BIRTH_COLUMNS.join(\",\")} FROM coordinator_auth_account_links WHERE coordinator_id = ${coordinator} AND link_id = ${link}\n UNION ALL SELECT ${CONNECTION_BIRTH_COLUMNS.join(\",\")} FROM coordinator_auth_account_connection_history WHERE coordinator_id = ${coordinator} AND link_id = ${link}`;\n}\n\n/** Trusted SQL aliases only. Historical ownership is independent of current enrollment.\n * The immutable proof's key ID was derived at commit. Signed-device receipts also\n * pass a freshly derived canonical key ID; account sessions need no current key.\n * Link revocation is deliberately checked by the caller, including post-revoke audit.\n */\nexport function authDeviceClaimProvenanceSql(options: {\n\tlink: \"l\" | \"cl\";\n\tcanonicalKeyId?: \"?\";\n\tconnections?: boolean;\n}): string {\n\tif (options.connections) return connectionClaimProvenance(options);\n\treturn genesisClaimProvenance(\n\t\toptions.link,\n\t\t\"coordinator_auth_account_links\",\n\t\toptions.canonicalKeyId,\n\t);\n}\n// These proofs use FROM subqueries, never WITH. A FROM subquery keeps the proof out of\n// the outer expression tree, which D1 limits to depth 100. SQLite 3.54.0 and 3.54.1\n// (production D1) refuse a statement that resolves a WITH name after about 100 table\n// references, and these proofs are embedded late in large statements.\nfunction genesisClaimProvenance(link: string, births: string, canonicalKeyId?: \"?\"): string {\n\tconst l = \"pl\";\n\treturn `EXISTS (SELECT 1 FROM (\n SELECT ct.coordinator_id, ct.link_id, cd.key_id FROM coordinator_auth_link_attempts ct\n JOIN ${births} pl ON pl.coordinator_id = ct.coordinator_id AND pl.link_id = ct.link_id\n JOIN coordinator_auth_device_claims cd ON cd.coordinator_id = ct.coordinator_id AND cd.claim_id = ${l}.device_claim_id\n JOIN coordinator_auth_link_audit_log ca ON ca.coordinator_id = ct.coordinator_id AND ca.link_id = ct.link_id AND ca.action = 'link_created'\n WHERE ct.coordinator_id = ${link}.coordinator_id AND ct.link_id = ${link}.link_id\n AND ct.attempt_id = ${l}.attempt_id\n AND ct.authority_kind = 'device_claim' AND ct.controller_attestation_id IS NULL\n AND ct.controller_review_receipt_id IS NULL AND ct.controller_revision IS NULL AND ct.state IN ('finalized','session_redeemed')\n AND ${l}.authority_kind = 'device_claim' AND ${l}.controller_attestation_id IS NULL\n AND ct.identity_id = ${l}.identity_id AND ct.issuer = ${l}.issuer AND ct.account_subject = ${l}.subject\n AND ct.auth_config_revision = ${l}.auth_config_revision AND ct.finalized_at_ms = ${l}.created_at_ms\n AND ct.browser_transaction_hash IS NOT NULL AND ct.browser_start_hash IS NOT NULL\n AND ct.runtime_verifier_hash IS NOT NULL AND ct.completion_secret_hash IS NOT NULL\n AND ct.created_at_ms <= ct.claimed_at_ms AND ct.claimed_at_ms <= ct.oidc_verified_at_ms\n AND ct.oidc_verified_at_ms <= ct.confirmed_at_ms AND ct.confirmed_at_ms <= ct.finalized_at_ms AND ct.finalized_at_ms < ct.expires_at_ms\n AND cd.attempt_id = ct.attempt_id AND cd.identity_id = ct.identity_id AND cd.group_id = ct.group_id AND cd.device_id = ct.device_id\n AND cd.public_key = ct.public_key AND cd.fingerprint = ct.fingerprint\n AND cd.issuer = ct.issuer AND cd.auth_config_revision = ct.auth_config_revision AND cd.created_at_ms = ct.finalized_at_ms\n AND ca.authority_kind = 'device_claim' AND ca.controller_attestation_id IS NULL AND ca.device_claim_id IS ${l}.device_claim_id\n AND ca.attempt_id = ct.attempt_id AND ca.identity_id = ct.identity_id AND ca.group_id = ct.group_id AND ca.device_id = ct.device_id\n AND ca.fingerprint = ct.fingerprint AND ca.auth_config_revision = ct.auth_config_revision AND ca.created_at_ms = ct.finalized_at_ms) cp\n WHERE cp.coordinator_id = ${link}.coordinator_id AND cp.link_id = ${link}.link_id\n ${canonicalKeyId ? `AND cp.key_id = ${canonicalKeyId}` : \"\"})`;\n}\n\n/** One immutable claim resolves its genesis directly; no recursive lineage walk. */\nexport function authClaimGenesisSql(claim: \"d\" | \"cd\"): string {\n\tconst births = `(${rootBirths(`${claim}.coordinator_id`, `${claim}.claim_id`)})`;\n\treturn `EXISTS (SELECT 1 FROM ${births} gl WHERE gl.coordinator_id = ${claim}.coordinator_id AND gl.link_id = ${claim}.claim_id AND ${genesisClaimProvenance(\"gl\", births)})`;\n}\nfunction connectionClaimProvenance(options: { link: \"l\" | \"cl\"; canonicalKeyId?: \"?\" }): string {\n\tconst l = options.link;\n\tconst births = `(${rootBirths(`${l}.coordinator_id`, `${l}.device_claim_id`)})`;\n\treturn `EXISTS (SELECT 1 FROM (\n SELECT t.coordinator_id,t.link_id,d.key_id FROM coordinator_auth_link_attempts t\n JOIN coordinator_auth_link_audit_log a ON a.coordinator_id = t.coordinator_id AND a.link_id = t.link_id AND a.action = 'link_created'\n JOIN coordinator_auth_device_claims d ON d.coordinator_id = t.coordinator_id AND d.claim_id = ${l}.device_claim_id\n WHERE t.coordinator_id = ${l}.coordinator_id AND t.link_id = ${l}.link_id AND t.attempt_id = ${l}.attempt_id\n AND (${l}.authority_kind = 'device_claim' AND ${l}.controller_attestation_id IS NULL AND t.authority_kind = 'device_claim' AND t.controller_attestation_id IS NULL AND t.controller_review_receipt_id IS NULL AND t.controller_revision IS NULL)\n AND (t.state IN ('finalized','session_redeemed') AND t.identity_id = ${l}.identity_id AND t.issuer = ${l}.issuer AND t.account_subject = ${l}.subject AND t.auth_config_revision = ${l}.auth_config_revision AND t.finalized_at_ms = ${l}.created_at_ms)\n AND (t.browser_start_hash IS NOT NULL AND t.browser_transaction_hash IS NOT NULL AND t.runtime_verifier_hash IS NOT NULL AND t.completion_secret_hash IS NOT NULL AND t.created_at_ms <= t.claimed_at_ms AND t.claimed_at_ms <= t.oidc_verified_at_ms AND t.oidc_verified_at_ms <= t.confirmed_at_ms AND t.confirmed_at_ms <= t.finalized_at_ms AND t.finalized_at_ms < t.expires_at_ms)\n AND (d.identity_id = t.identity_id AND d.issuer = t.issuer AND d.group_id = t.group_id AND d.device_id = t.device_id AND d.public_key = t.public_key AND d.fingerprint = t.fingerprint)\n AND (a.attempt_id = t.attempt_id AND a.identity_id = t.identity_id AND a.group_id = t.group_id AND a.device_id = t.device_id AND a.fingerprint = t.fingerprint AND a.auth_config_revision = t.auth_config_revision AND a.created_at_ms = t.finalized_at_ms AND a.authority_kind = 'device_claim' AND a.controller_attestation_id IS NULL AND a.device_claim_id = d.claim_id)\n AND ((t.prior_link_id IS NULL AND t.link_id = d.claim_id) OR EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id = t.coordinator_id AND h.link_id = t.prior_link_id AND h.identity_id = t.identity_id AND h.successor_link_id = t.link_id))\n AND EXISTS (SELECT 1 FROM ${births} gl WHERE gl.coordinator_id = d.coordinator_id AND gl.link_id = d.claim_id AND ${genesisClaimProvenance(\"gl\", births)})) cp\n ${options.canonicalKeyId ? \"WHERE cp.key_id = ?\" : \"\"})`;\n}\n\n/** Account management only; privileged enrollment/grant proofs remain attested-only. */\nfunction controllerBirthProvenance(link: \"l\"): string {\n\treturn `EXISTS (SELECT 1 FROM (SELECT t.coordinator_id,t.link_id FROM coordinator_auth_link_attempts t\n JOIN coordinator_auth_controller_attestations origin ON origin.coordinator_id=t.coordinator_id AND origin.attestation_id=t.controller_attestation_id\n JOIN coordinator_auth_link_audit_log a ON a.coordinator_id=t.coordinator_id AND a.link_id=t.link_id AND a.action='link_created'\n WHERE (t.coordinator_id=${link}.coordinator_id AND t.link_id=${link}.link_id AND t.attempt_id=${link}.attempt_id AND t.authority_kind='controller_attestation' AND t.controller_attestation_id=${link}.controller_attestation_id)\n AND (t.identity_id=${link}.identity_id AND t.issuer=${link}.issuer AND t.account_subject=${link}.subject AND t.auth_config_revision=${link}.auth_config_revision AND t.finalized_at_ms=${link}.created_at_ms AND t.state IN ('finalized','session_redeemed'))\n AND (t.browser_transaction_hash IS NOT NULL AND t.runtime_verifier_hash IS NOT NULL AND t.completion_secret_hash IS NOT NULL AND t.created_at_ms<=t.claimed_at_ms AND t.claimed_at_ms<=t.oidc_verified_at_ms AND t.oidc_verified_at_ms<=t.confirmed_at_ms AND t.confirmed_at_ms<=t.finalized_at_ms AND t.finalized_at_ms<t.expires_at_ms)\n AND (origin.identity_id=t.identity_id AND origin.group_id=t.group_id AND origin.device_id=t.device_id AND origin.public_key=t.public_key AND origin.fingerprint=t.fingerprint AND origin.review_receipt_id=t.controller_review_receipt_id AND origin.revision=t.controller_revision)\n AND (t.prior_link_id IS NULL OR EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id=t.coordinator_id AND h.identity_id=t.identity_id AND h.link_id=t.prior_link_id AND h.successor_link_id=t.link_id))\n AND (a.attempt_id=t.attempt_id AND a.identity_id=t.identity_id AND a.group_id=t.group_id AND a.device_id=t.device_id AND a.fingerprint=t.fingerprint AND a.controller_attestation_id=t.controller_attestation_id AND a.authority_kind=t.authority_kind AND a.device_claim_id IS NULL AND a.auth_config_revision=t.auth_config_revision AND a.created_at_ms=t.finalized_at_ms)) cr)`;\n}\nexport function authAccountLinkProvenanceSql(\n\tlink: \"l\",\n\toptions: { connections?: boolean } = {},\n): string {\n\treturn `((${link}.authority_kind = 'controller_attestation' AND ${link}.controller_attestation_id IS NOT NULL AND ${link}.device_claim_id IS NULL${options.connections ? ` AND ${controllerBirthProvenance(link)}` : \"\"})\n OR (${authDeviceClaimProvenanceSql({ link, connections: options.connections })}))`;\n}\n","import type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\n\n/**\n * Read-set validation for coordinator authorization.\n *\n * D1 has no interactive transactions, so a decision cannot read, decide and write under\n * one lock. A decision instead works in three steps:\n *\n * 1. Read the facts with small plain queries ({@link readSnapshot}).\n * 2. Decide in TypeScript from those rows alone.\n * 3. Write in one atomic batch whose first statements re-run every read and abort the\n * batch unless each read still supports the decision ({@link writeGuarded}).\n *\n * The decision is void unless its guards run in the batch that writes.\n */\n\n/**\n * One fact query. It returns one JSON value per row in a column named `row`, usually\n * `json_object(...) AS row`. It needs an explicit ORDER BY so the same rows always give\n * the same text. Write it without a WITH clause: production D1 refuses large statements\n * that resolve WITH names, and the guard embeds the read a second time.\n *\n * A read may compute a 0/1 verdict in SQL, such as `'proven', EXISTS (...)`, when a\n * proof joins several tables and its NULL handling is easier to keep exact in SQL. The\n * guard re-runs the whole read, so the verdict is evaluated again inside the winning\n * batch and a changed verdict aborts it.\n */\nexport interface AuthRead extends AuthLinkStatement {\n\t/**\n\t * Replaces the default guard, which requires the read to return byte-identical rows.\n\t * Use it only when the decision survives some changes to those rows, for example a\n\t * list that may lose entries but must not gain any. It receives the JSON array text\n\t * of the rows that were read, and returns a statement with exactly one value: 1 while\n\t * the decision still holds.\n\t */\n\tholds?: (seenRows: string) => AuthLinkStatement;\n}\n\n/** The caller states the row shape of its own reads; the rows come from its SQL. */\ntype RowsByName = Record<string, unknown[]>;\n\nexport interface AuthReadSnapshot<Rows extends RowsByName> {\n\t/** Parsed rows of each read. */\n\trows: Rows;\n\t/** One statement per read. Each aborts its batch when the read no longer holds. */\n\tguards: Record<keyof Rows, AuthLinkStatement>;\n}\n\nexport type GuardedWriteResult =\n\t/** Every guard held and every write assertion passed. */\n\t| \"committed\"\n\t/** A read no longer supports the decision. Nothing was written. */\n\t| \"changed\"\n\t/** A write changed an unexpected number of rows. Nothing was written. */\n\t| \"unmatched\";\n\n// json_extract rejects a path without a leading \"$\", so SQLite raises an error that names\n// the path. SQLite and D1 both put the path in the error message. Callers never see the\n// markers: writeGuarded turns them into a GuardedWriteResult.\nconst SNAPSHOT_CHANGED = \"auth_snapshot_changed\";\nconst WRITE_UNMATCHED = \"auth_write_unmatched\";\n\nfunction abortUnless(condition: string, marker: string): string {\n\treturn `SELECT CASE WHEN ${condition} THEN 1 ELSE json_extract('{}', '${marker}') END AS held`;\n}\n\nconst collected = (sql: string) =>\n\t`SELECT coalesce(json_group_array(json(row)), '[]') AS rows FROM (${sql})`;\n\n/** An SQL condition that is true while the read still supports the decision. */\nfunction holdsCondition(read: AuthRead, seenRows: string): AuthLinkStatement {\n\tif (!read.holds)\n\t\treturn { sql: `(${collected(read.sql)}) IS ?`, values: [...read.values, seenRows] };\n\tconst predicate = read.holds(seenRows);\n\treturn { sql: `(SELECT * FROM (${predicate.sql})) IS 1`, values: predicate.values };\n}\n\nconst abortWhenChanged = (condition: AuthLinkStatement): AuthLinkStatement => ({\n\tsql: abortUnless(condition.sql, SNAPSHOT_CHANGED),\n\tvalues: condition.values,\n});\n\n/**\n * A guard from a caller's own SQL condition, for reads whose rows are compared another\n * way than the default guard does. It aborts its batch, as a changed read does, unless\n * the condition is true.\n */\nexport const snapshotGuard = abortWhenChanged;\n\nexport interface ReadSnapshotOptions {\n\t/**\n\t * Builds each guard from its condition instead of the default guard, whose failure\n\t * {@link writeGuarded} reports as \"changed\". For a batch that must fail its own way,\n\t * or must check the read only when another condition of that batch holds.\n\t */\n\tguard?: (condition: AuthLinkStatement) => AuthLinkStatement;\n}\n\n/** Follows a write in the batch. Aborts unless that write changed exactly `expected` rows. */\nexport function changedRows(expected = 1): AuthLinkStatement {\n\treturn { sql: abortUnless(\"changes() = ?\", WRITE_UNMATCHED), values: [expected] };\n}\n\ntype RowReader = Pick<AuthLinkBackend, \"first\" | \"readBatch\">;\ntype Collected = { rows: string } | null | undefined;\n\n// Without a read batch the reads run one by one. That is still safe: the guards re-check\n// every read in the write batch, so a write commits only if all of them hold at once.\nasync function firstRows(\n\tbackend: RowReader,\n\tstatements: AuthLinkStatement[],\n): Promise<Collected[]> {\n\tif (backend.readBatch)\n\t\treturn (await backend.readBatch<{ rows: string }>(statements)).map((rows) => rows[0]);\n\tconst rows: Collected[] = [];\n\tfor (const statement of statements) rows.push(await backend.first<{ rows: string }>(statement));\n\treturn rows;\n}\n\nasync function readCollected(\n\tbackend: RowReader,\n\tstatements: AuthLinkStatement[],\n): Promise<string[]> {\n\tif (statements.length === 0) return [];\n\treturn (await firstRows(backend, statements)).map((row) => {\n\t\tif (typeof row?.rows !== \"string\") throw new Error(\"auth_read_set_unavailable\");\n\t\treturn row.rows;\n\t});\n}\n\nfunction parseRows(text: string): unknown[] {\n\tconst rows: unknown = JSON.parse(text);\n\tif (!Array.isArray(rows)) throw new Error(\"auth_read_set_unavailable\");\n\treturn rows;\n}\n\n/** Runs the named reads and returns their rows with the guards that pin them. */\nexport async function readSnapshot<Rows extends RowsByName>(\n\tbackend: RowReader,\n\treads: Record<keyof Rows, AuthRead>,\n\toptions: ReadSnapshotOptions = {},\n): Promise<AuthReadSnapshot<Rows>> {\n\tconst guardFor = (read: AuthRead, seenRows: string) =>\n\t\t(options.guard ?? abortWhenChanged)(holdsCondition(read, seenRows));\n\tconst names = Object.keys(reads) as (keyof Rows)[];\n\tconst seen = await readCollected(\n\t\tbackend,\n\t\tnames.map((name) => ({ sql: collected(reads[name].sql), values: reads[name].values })),\n\t);\n\tconst entries = names.map((name, index) => ({ name, text: seen[index] as string }));\n\treturn {\n\t\trows: Object.fromEntries(entries.map(({ name, text }) => [name, parseRows(text)])) as Rows,\n\t\tguards: Object.fromEntries(\n\t\t\tentries.map(({ name, text }) => [name, guardFor(reads[name], text)]),\n\t\t) as Record<keyof Rows, AuthLinkStatement>,\n\t};\n}\n\n/** Whether an error is a default guard's refusal: a read no longer holds. */\nexport function isSnapshotChanged(error: unknown): boolean {\n\treturn String((error as { message?: unknown } | null)?.message ?? error).includes(\n\t\tSNAPSHOT_CHANGED,\n\t);\n}\n\n/** A backend whose reads can run together as one snapshot. */\nexport type AtomicReader = Required<Pick<AuthLinkBackend, \"readBatch\">>;\n\n/**\n * Types a store backend's read batch as required. Every store backend has one. A\n * backend without it refuses each read batch instead of reading one statement at a\n * time, which would check the guards at different moments.\n */\nexport function requireReadBatch<B extends Pick<AuthLinkBackend, \"readBatch\">>(\n\tbackend: B,\n): Omit<B, \"readBatch\"> & AtomicReader {\n\tconst readBatch = backend.readBatch?.bind(backend);\n\tconst refuse = async <T>(): Promise<T[][]> => {\n\t\tthrow new Error(\"auth_read_batch_required\");\n\t};\n\treturn { ...backend, readBatch: readBatch ?? refuse };\n}\n\n/**\n * Runs the guards and then `statement` as one read batch, and returns the statement's\n * first row. `changed` when a guard no longer holds.\n */\nexport async function readAfterGuards<T>(\n\tbackend: AtomicReader,\n\tguards: readonly AuthLinkStatement[],\n\tstatement: AuthLinkStatement,\n): Promise<{ changed: true } | { changed: false; row: T | null }> {\n\ttry {\n\t\tconst rows = await backend.readBatch<T>([...guards, statement]);\n\t\treturn { changed: false, row: rows[guards.length]?.[0] ?? null };\n\t} catch (error) {\n\t\tif (isSnapshotChanged(error)) return { changed: true };\n\t\tthrow error;\n\t}\n}\n\n/** Whether every guard still holds, checked together in one read batch. */\nexport async function guardsHold(\n\tbackend: AtomicReader,\n\tguards: readonly AuthLinkStatement[],\n): Promise<boolean> {\n\tconst read = await readAfterGuards(backend, guards, { sql: \"SELECT 1 AS held\", values: [] });\n\treturn !read.changed;\n}\n\n/**\n * Runs the guards and then the writes as one atomic batch. Any other error propagates,\n * so an unknown outcome is never reported as a refusal.\n */\nexport async function writeGuarded(\n\tbackend: Pick<AuthLinkBackend, \"batch\">,\n\tguards: readonly AuthLinkStatement[],\n\twrites: readonly AuthLinkStatement[],\n): Promise<GuardedWriteResult> {\n\ttry {\n\t\tawait backend.batch([...guards, ...writes]);\n\t\treturn \"committed\";\n\t} catch (error) {\n\t\tif (isSnapshotChanged(error)) return \"changed\";\n\t\tconst message = String((error as { message?: unknown } | null)?.message ?? error);\n\t\tif (message.includes(WRITE_UNMATCHED)) return \"unmatched\";\n\t\tthrow error;\n\t}\n}\n","import {\n\ttype AccountChangeFacts,\n\ttype AccountChangeGrant,\n\ttype AccountChangeSubject,\n\ttype AccountChangeTarget,\n\ttype AccountChangeTargetCandidate,\n\tdecideAccountChange,\n\tpickAccountChangeTarget,\n} from \"./coordinator-account-change-decision.js\";\nimport {\n\tAUTH_DEVICE_CLAIM_INPUT_ROW_SQL,\n\tAUTH_DEVICE_CLAIM_INVITE_CONSUMED_SQL,\n\tAUTH_DEVICE_CLAIM_KEYS_READ,\n\tAUTH_DEVICE_CLAIM_LEGACY_COMPATIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_LEGACY_UNWAIVABLE_SQL,\n\tcaptureDeviceClaimSubject,\n\ttype DeviceClaimKeyFacts,\n\ttype DeviceClaimSubject,\n\tderiveDeviceClaimKeyFacts,\n\tdeviceClaimAssignmentInputs,\n} from \"./coordinator-auth-device-claim-eligibility.js\";\nimport {\n\tAUTH_CURRENT_LEGACY_ASSIGNMENT_SQL,\n\tAUTH_LEGACY_ASSIGNMENT_READ_SQL,\n} from \"./coordinator-auth-legacy-assignment.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport type {\n\tCoordinatorAuthLinkConfig,\n\tCoordinatorAuthLinkSigner,\n} from \"./coordinator-auth-link-contract.js\";\nimport {\n\tauthClaimGenesisSql,\n\tauthDeviceClaimProvenanceSql,\n} from \"./coordinator-auth-link-provenance.js\";\nimport { type AuthRead, readSnapshot } from \"./coordinator-auth-read-set.js\";\n\n/**\n * Account refresh and disconnect authority as read-set validation, in two stages of small\n * plain reads, each stage sent together through `readBatch` when the backend has one:\n *\n * 1. The base: the stored keys, the legacy assignment, the schema variant and, for a\n * device request, the candidate target links.\n * 2. The facts about the subject, which need the key aliases classified from stage 1.\n *\n * decideAccountChange decides from those rows alone. Every write starts its batch with\n * one guard per read the decision depends on; any read that changed aborts the write.\n *\n * Not guarded, and why that matches the old single statement:\n * - The schema variant. The old builder also chose its SQL from a pre-read; a schema\n * change makes the write's own statements fail.\n * - The legacy assignment when the device relies on none. The old statement then\n * skipped the assignment checks, so a new assignment row could not deny it either.\n * - The change attempt row that callback and finalize read first. The old builder also\n * took the target from that pre-read, and the UPDATE re-checks the row's target,\n * Identity and enrollment columns in its own WHERE.\n */\n\nconst ALIASES = \"(SELECT value FROM json_each(?))\";\n\n/** What the fact reads depend on besides the subject. */\ninterface ReadContext {\n\t/** The 15 values of AUTH_DEVICE_CLAIM_INPUT_ROW_SQL for this subject. */\n\tclaimInput: AuthLinkStatement[\"values\"];\n\taliases: string;\n\ttargetLinkId: string;\n}\n\n// The link's controller-review creation records, as the old controller_births join\n// required them. Multi-table proof: the guard re-runs it with the read.\nconst controllerBirthSql = (\n\tconnections: boolean,\n) => `EXISTS (SELECT 1 FROM coordinator_auth_link_attempts b\n JOIN coordinator_auth_link_audit_log ca ON ca.coordinator_id=l.coordinator_id AND ca.link_id=l.link_id AND ca.action='link_created'\n JOIN coordinator_auth_controller_attestations origin ON origin.coordinator_id=l.coordinator_id AND origin.attestation_id=l.controller_attestation_id\n WHERE b.coordinator_id=l.coordinator_id AND b.link_id=l.link_id AND b.attempt_id=l.attempt_id\n AND (l.authority_kind='controller_attestation' AND l.device_claim_id IS NULL AND b.authority_kind=l.authority_kind AND b.controller_attestation_id=l.controller_attestation_id)\n AND (ca.attempt_id=b.attempt_id AND ca.identity_id=l.identity_id AND ca.controller_attestation_id=l.controller_attestation_id AND ca.authority_kind=l.authority_kind AND ca.auth_config_revision=l.auth_config_revision AND ca.group_id=b.group_id AND ca.device_id=b.device_id AND ca.fingerprint=b.fingerprint AND ca.created_at_ms=l.created_at_ms AND b.finalized_at_ms=l.created_at_ms)\n AND (origin.group_id=b.group_id AND origin.device_id=b.device_id AND origin.public_key=b.public_key AND origin.fingerprint=b.fingerprint AND origin.identity_id=b.identity_id AND origin.review_receipt_id=b.controller_review_receipt_id AND origin.revision=b.controller_revision)\n ${connections ? \"AND (b.prior_link_id IS NULL OR EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id=b.coordinator_id AND h.identity_id=b.identity_id AND h.link_id=b.prior_link_id AND h.successor_link_id=b.link_id))\" : \"\"})`;\n\n/**\n * One small plain read per fact, each ordered by its key. A `...Conflicts` read selects\n * only rows that forbid the change, so the decision requires it to be empty and its\n * guard requires it to stay empty.\n */\nconst FACT_READS: {\n\t[Name in keyof AccountChangeFacts]: (p: AccountChangeSubject, context: ReadContext) => AuthRead;\n} = {\n\t// Only the signed group has to be live, so only its rows carry that verdict.\n\tenrollments: (p, { aliases }) => ({\n\t\tsql: `SELECT json_object('group_id',e.group_id,'device_id',e.device_id,'public_key',e.public_key,\n 'fingerprint',e.fingerprint,'identity_id',e.identity_id,'enabled',e.enabled,\n 'group_live',CASE WHEN e.group_id=? THEN EXISTS (SELECT 1 FROM groups g WHERE g.group_id=e.group_id AND g.archived_at IS NULL) END) AS row\n FROM enrolled_devices e WHERE e.device_id=? OR e.public_key IN ${ALIASES} ORDER BY e.device_id,e.group_id`,\n\t\tvalues: [p.groupId, p.deviceId, aliases],\n\t}),\n\tbindings: (p) => ({\n\t\tsql: `SELECT json_object('coordinator_id',b.coordinator_id,'device_id',b.device_id,'key_id',b.key_id,'identity_id',b.identity_id) AS row\n FROM coordinator_device_ownership_bindings b WHERE b.device_id=? OR b.key_id=? ORDER BY b.device_id`,\n\t\tvalues: [p.deviceId, p.keyId],\n\t}),\n\tattestations: (p, { aliases }) => ({\n\t\tsql: `SELECT json_object('attestation_id',t.attestation_id,'identity_id',t.identity_id,'group_id',t.group_id,\n 'device_id',t.device_id,'public_key',t.public_key,'fingerprint',t.fingerprint,'revision',t.revision,'revoked_at',t.revoked_at) AS row\n FROM coordinator_auth_controller_attestations t WHERE t.coordinator_id=?\n AND (t.device_id=? OR t.public_key IN ${ALIASES}) ORDER BY t.attestation_id`,\n\t\tvalues: [p.coordinatorId, p.deviceId, aliases],\n\t}),\n\t// active_link and genesis are verdicts: each joins other tables, and the guard re-runs them.\n\tclaims: (p) => ({\n\t\tsql: `SELECT json_object('claim_id',d.claim_id,'identity_id',d.identity_id,'group_id',d.group_id,\n 'device_id',d.device_id,'public_key',d.public_key,'fingerprint',d.fingerprint,'key_id',d.key_id,\n 'active_link',EXISTS (SELECT 1 FROM coordinator_auth_account_links l WHERE l.coordinator_id=d.coordinator_id AND l.identity_id=d.identity_id AND l.revoked_at_ms IS NULL),\n 'genesis',${p.connections ? authClaimGenesisSql(\"d\") : \"1\"}) AS row\n FROM coordinator_auth_device_claims d WHERE d.coordinator_id=? AND (d.device_id=? OR d.key_id=?) ORDER BY d.claim_id`,\n\t\tvalues: [p.coordinatorId, p.deviceId, p.keyId],\n\t}),\n\t// The creation-record proofs are verdict columns: each compares dozens of columns\n\t// across several tables, and the guard re-runs them with the read.\n\tlink: (p, { targetLinkId }) => ({\n\t\tsql: `SELECT json_object('coordinator_id',l.coordinator_id,'link_id',l.link_id,'identity_id',l.identity_id,\n 'issuer',l.issuer,'subject',l.subject,'auth_config_revision',l.auth_config_revision,'revoked_at_ms',l.revoked_at_ms,\n 'device_claim_id',l.device_claim_id,\n 'attempts',json((SELECT json_group_array(json_object('identity_id',b.identity_id,'issuer',b.issuer,'account_subject',b.account_subject,'auth_config_revision',b.auth_config_revision,'state',b.state))\n FROM coordinator_auth_link_attempts b WHERE b.coordinator_id=l.coordinator_id AND b.link_id=l.link_id AND b.attempt_id=l.attempt_id)),\n 'controller_birth',${controllerBirthSql(p.connections)},\n 'device_birth',${authDeviceClaimProvenanceSql({ link: \"l\", connections: p.connections })}) AS row\n FROM coordinator_auth_account_links l WHERE l.coordinator_id=? AND l.link_id=? ORDER BY l.link_id`,\n\t\tvalues: [p.coordinatorId, targetLinkId],\n\t}),\n\t// The subject Identity is the link's Identity whenever the decision allows.\n\trevokedHistory: (p) => ({\n\t\tsql: `SELECT json_object('link_id',h.link_id) AS row FROM coordinator_auth_account_connection_history h\n WHERE h.coordinator_id=? AND h.identity_id=? AND h.revoked_at_ms IS NOT NULL ORDER BY h.link_id`,\n\t\tvalues: [p.coordinatorId, p.identityId],\n\t}),\n\t// Legacy Team manifests are JSON whose values may have any JSON type; SQL keeps the\n\t// json_extract comparisons exact. The peer branch and the current-assignment proof\n\t// also join enrollments. The guard re-runs all three verdicts.\n\tlegacy: (_p, { claimInput }) => ({\n\t\tsql: `SELECT json_object('assignment_current',(p.assignment_snapshot IS NULL OR ${AUTH_CURRENT_LEGACY_ASSIGNMENT_SQL}),\n 'unwaivable_clear',(${AUTH_DEVICE_CLAIM_LEGACY_UNWAIVABLE_SQL}),\n 'compatible_clear',(${AUTH_DEVICE_CLAIM_LEGACY_COMPATIBLE_SQL})) AS row FROM ${AUTH_DEVICE_CLAIM_INPUT_ROW_SQL} p`,\n\t\tvalues: claimInput,\n\t}),\n\trevocationConflicts: (p) => ({\n\t\tsql: `SELECT json_object('subject_kind',r.subject_kind) AS row FROM coordinator_device_revocations r\n WHERE (r.subject_kind='device_id' AND r.subject_value=?) OR (r.subject_kind='ed25519_key' AND r.subject_value=?)\n ORDER BY r.subject_kind`,\n\t\tvalues: [p.deviceId, p.keyId],\n\t}),\n\tinviteConflicts: (p, { aliases }) => ({\n\t\tsql: `SELECT json_object('invite_id',i.invite_id) AS row FROM coordinator_invites i\n WHERE ${AUTH_DEVICE_CLAIM_INVITE_CONSUMED_SQL}\n AND (i.bound_device_id=? OR i.bound_public_key IN ${ALIASES} OR i.bound_fingerprint=?)\n AND ((i.assigned_identity_id IS NOT NULL AND i.assigned_identity_id<>?)\n OR (i.target_identity_id IS NOT NULL AND i.target_identity_id<>?))\n ORDER BY i.invite_id`,\n\t\tvalues: [p.deviceId, aliases, p.fingerprint, p.identityId, p.identityId],\n\t}),\n\totherIdentityLinkAttemptConflicts: (p, { aliases }) => ({\n\t\tsql: `SELECT json_object('link_id',l.link_id,'attempt_id',a.attempt_id) AS row\n FROM coordinator_auth_account_links l JOIN coordinator_auth_link_attempts a\n ON a.coordinator_id=l.coordinator_id AND a.link_id=l.link_id\n WHERE l.coordinator_id=? AND l.identity_id<>? AND (a.device_id=? OR a.public_key IN ${ALIASES})\n ORDER BY l.link_id,a.attempt_id`,\n\t\tvalues: [p.coordinatorId, p.identityId, p.deviceId, aliases],\n\t}),\n\totherIdentityLinkAuditConflicts: (p) => ({\n\t\tsql: `SELECT json_object('link_id',l.link_id,'action',a.action) AS row\n FROM coordinator_auth_account_links l JOIN coordinator_auth_link_audit_log a\n ON a.coordinator_id=l.coordinator_id AND a.link_id=l.link_id\n WHERE l.coordinator_id=? AND a.device_id=? AND l.identity_id<>? ORDER BY l.link_id,a.action`,\n\t\tvalues: [p.coordinatorId, p.deviceId, p.identityId],\n\t}),\n};\n\nfunction factReads(\n\tp: AccountChangeSubject,\n\tcontext: ReadContext,\n): Record<keyof AccountChangeFacts, AuthRead> {\n\tconst names = Object.keys(FACT_READS) as (keyof AccountChangeFacts)[];\n\treturn Object.fromEntries(names.map((name) => [name, FACT_READS[name](p, context)])) as Record<\n\t\tkeyof AccountChangeFacts,\n\t\tAuthRead\n\t>;\n}\n\n/**\n * Candidate target links, one row per link and binding verdict, in SQL link order. The\n * filters are the old derivation's; pickAccountChangeTarget picks the winner.\n */\nfunction accountChangeTargetRead(\n\tc: CoordinatorAuthLinkConfig,\n\tsigner: CoordinatorAuthLinkSigner,\n\tkeyId: string,\n): AuthRead {\n\treturn {\n\t\tsql: `SELECT json_object('link_id',link_id,'identity_id',identity_id,'bound',bound) AS row FROM (\n SELECT DISTINCT l.link_id,l.identity_id,(ob.device_id = ? AND ob.key_id = ?) AS bound FROM coordinator_auth_account_links l\n LEFT JOIN coordinator_auth_device_claims d ON d.coordinator_id = l.coordinator_id AND d.identity_id = l.identity_id\n LEFT JOIN coordinator_auth_controller_attestations a ON a.coordinator_id = l.coordinator_id AND a.identity_id = l.identity_id\n LEFT JOIN coordinator_device_ownership_bindings ob ON ob.coordinator_id = l.coordinator_id AND ob.identity_id = l.identity_id\n WHERE l.coordinator_id = ? AND ((d.device_id = ? AND d.key_id = ?) OR\n (a.group_id = ? AND a.device_id = ? AND a.public_key = ? AND a.fingerprint = ? AND a.revoked_at IS NULL)\n OR (ob.device_id = ? AND ob.key_id = ?))) ORDER BY link_id,bound`,\n\t\tvalues: [\n\t\t\tsigner.deviceId,\n\t\t\tkeyId,\n\t\t\tc.coordinatorId,\n\t\t\tsigner.deviceId,\n\t\t\tkeyId,\n\t\t\tsigner.groupId,\n\t\t\tsigner.deviceId,\n\t\t\tsigner.publicKey,\n\t\t\tsigner.fingerprint,\n\t\t\tsigner.deviceId,\n\t\t\tkeyId,\n\t\t],\n\t};\n}\n\nconst SESSION_READ: AuthRead = {\n\tsql: \"SELECT json_object('present',count(*)) AS row FROM pragma_table_info('coordinator_auth_browser_transactions') WHERE name = 'start_order'\",\n\tvalues: [],\n};\n\ntype BaseRows = {\n\tkeys: string[];\n\tassignment: unknown[];\n\tsession: { present: number }[];\n\tcandidates: AccountChangeTargetCandidate[];\n};\n\n/** Stage 1: what every account-change authority reads before it knows the key aliases. */\nexport interface AccountChangeBase {\n\t/** The derived target, when the request derives one. */\n\ttarget: AccountChangeTarget | null;\n\tkeys: string[];\n\tassignment: string | null;\n\tconnections: boolean;\n\tguards: Pick<Record<keyof BaseRows, AuthLinkStatement>, \"keys\" | \"assignment\"> & {\n\t\tcandidates?: AuthLinkStatement;\n\t};\n}\n\n/**\n * Reads stage 1. With `deriveTarget`, it also reads the candidate links\n * for this signer and key; a change to them aborts the write even when the same link\n * would still win.\n */\nexport async function readAccountChangeBase(\n\tbackend: Pick<AuthLinkBackend, \"first\" | \"readBatch\">,\n\tc: CoordinatorAuthLinkConfig,\n\tsigner: CoordinatorAuthLinkSigner,\n\toptions: { deriveTarget?: { keyId: string } } = {},\n): Promise<AccountChangeBase> {\n\tconst reads: Partial<Record<keyof BaseRows, AuthRead>> = {\n\t\tkeys: AUTH_DEVICE_CLAIM_KEYS_READ,\n\t\tassignment: {\n\t\t\tsql: AUTH_LEGACY_ASSIGNMENT_READ_SQL,\n\t\t\tvalues: deviceClaimAssignmentInputs({ config: c, signer }),\n\t\t},\n\t\tsession: SESSION_READ,\n\t};\n\tif (options.deriveTarget)\n\t\treads.candidates = accountChangeTargetRead(c, signer, options.deriveTarget.keyId);\n\tconst read = await readSnapshot<BaseRows>(backend, reads as Record<keyof BaseRows, AuthRead>);\n\tconst [assignment] = read.rows.assignment;\n\treturn {\n\t\ttarget: options.deriveTarget ? pickAccountChangeTarget(read.rows.candidates) : null,\n\t\tkeys: read.rows.keys,\n\t\tassignment: assignment ? JSON.stringify(assignment) : null,\n\t\tconnections: read.rows.session[0]?.present === 1,\n\t\tguards: {\n\t\t\tkeys: read.guards.keys,\n\t\t\tassignment: read.guards.assignment,\n\t\t\t...(options.deriveTarget ? { candidates: read.guards.candidates } : {}),\n\t\t},\n\t};\n}\n\n/** The granted link, or null, with the guards for the batch that writes it. */\nexport interface AccountChangeAuthority {\n\t/** The link this device may change, or null when it may not. */\n\tgrant: AccountChangeGrant | null;\n\t/** These go first in the batch that writes. Each aborts it when its read changed. */\n\tguards: AuthLinkStatement[];\n\t/** The same guards by read name. */\n\tparts: Record<string, AuthLinkStatement>;\n}\n\nfunction claimInputValues(\n\tclaim: DeviceClaimSubject,\n\tkeyFacts: DeviceClaimKeyFacts,\n\tnow: number,\n): AuthLinkStatement[\"values\"] {\n\treturn [\n\t\tclaim.config.coordinatorId,\n\t\tclaim.identityId,\n\t\tclaim.signer.groupId,\n\t\tclaim.signer.deviceId,\n\t\tclaim.signer.publicKey,\n\t\tclaim.signer.fingerprint,\n\t\tclaim.keyId,\n\t\tnow,\n\t\tnew Date(now).toISOString(),\n\t\tclaim.attemptId,\n\t\tclaim.config.issuer,\n\t\tclaim.config.revision,\n\t\tJSON.stringify(keyFacts.keys),\n\t\tJSON.stringify(keyFacts.aliases),\n\t\tkeyFacts.assignmentSnapshot,\n\t];\n}\n\nfunction subjectFor(claim: DeviceClaimSubject, base: AccountChangeBase): AccountChangeSubject {\n\treturn {\n\t\tcoordinatorId: claim.config.coordinatorId,\n\t\tidentityId: claim.identityId,\n\t\tgroupId: claim.signer.groupId,\n\t\tdeviceId: claim.signer.deviceId,\n\t\tpublicKey: claim.signer.publicKey,\n\t\tfingerprint: claim.signer.fingerprint,\n\t\tkeyId: claim.keyId,\n\t\tissuer: claim.config.issuer,\n\t\tenabled: claim.config.enabled,\n\t\tconnections: base.connections,\n\t};\n}\n\n/** Stage 1 guards the decision depends on, by part name. */\nfunction baseParts(base: AccountChangeBase, keyFacts: DeviceClaimKeyFacts) {\n\treturn {\n\t\t...(base.guards.candidates ? { target: base.guards.candidates } : {}),\n\t\tkeys: base.guards.keys,\n\t\t// Without an assignment snapshot the old statement skipped the assignment checks.\n\t\t...(keyFacts.assignmentSnapshot === null ? {} : { assignment: base.guards.assignment }),\n\t};\n}\n\n/**\n * Stage 2. Server proof only: reads the facts behind the account-change authority for\n * this signer and target, and decides in TypeScript. The grant is void\n * unless `guards` run first in the batch that writes. Null when the old builder built no\n * statement: the target Identity or the signer's key is not acceptable.\n */\nexport async function prepareAccountChangeAuthority(\n\tbackend: Pick<AuthLinkBackend, \"first\" | \"readBatch\">,\n\tbase: AccountChangeBase,\n\tc: CoordinatorAuthLinkConfig,\n\tsigner: CoordinatorAuthLinkSigner,\n\ttarget: AccountChangeTarget,\n\tnow: number,\n): Promise<AccountChangeAuthority | null> {\n\tconst claim = await captureDeviceClaimSubject({ identityId: target.identity_id, signer }, c);\n\tif (!claim) return null;\n\treturn decideForClaim(backend, base, claim, target, now);\n}\n\n/** Stage 2 for a request already validated, with its key ID derived. */\nasync function decideForClaim(\n\tbackend: Pick<AuthLinkBackend, \"first\" | \"readBatch\">,\n\tbase: AccountChangeBase,\n\tclaim: DeviceClaimSubject,\n\ttarget: AccountChangeTarget,\n\tnow: number,\n): Promise<AccountChangeAuthority> {\n\tconst keyFacts = deriveDeviceClaimKeyFacts(claim, base);\n\tconst subject = subjectFor(claim, base);\n\tconst facts = await readSnapshot<AccountChangeFacts>(\n\t\tbackend,\n\t\tfactReads(subject, {\n\t\t\tclaimInput: claimInputValues(claim, keyFacts, now),\n\t\t\taliases: JSON.stringify(keyFacts.aliases),\n\t\t\ttargetLinkId: target.target_link_id,\n\t\t}),\n\t);\n\tconst parts: Record<string, AuthLinkStatement> = {\n\t\t...baseParts(base, keyFacts),\n\t\t...facts.guards,\n\t};\n\treturn {\n\t\tgrant: decideAccountChange(subject, facts.rows),\n\t\tguards: Object.values(parts),\n\t\tparts,\n\t};\n}\n\n/**\n * Both stages for a target the caller already holds, such as the one a stored change\n * attempt names. Checks the signer and Identity before reading anything, as the old\n * builder did.\n */\nexport async function prepareAccountChangeAuthorityFor(\n\tbackend: Pick<AuthLinkBackend, \"first\" | \"readBatch\">,\n\tc: CoordinatorAuthLinkConfig,\n\tsigner: CoordinatorAuthLinkSigner,\n\ttarget: AccountChangeTarget,\n\tnow: number,\n): Promise<AccountChangeAuthority | null> {\n\tconst claim = await captureDeviceClaimSubject({ identityId: target.identity_id, signer }, c);\n\tif (!claim) return null;\n\tconst base = await readAccountChangeBase(backend, c, signer);\n\treturn decideForClaim(backend, base, claim, target, now);\n}\n","/** Management-attempt schema installed by the explicit account-schema migration. */\nconst table = \"coordinator_account_change_attempts\";\nexport const BROWSER_ACCOUNT_ARCHIVE_GUARD = `CREATE TRIGGER account_change_archive_receipt BEFORE INSERT ON coordinator_auth_account_connection_history\nWHEN NOT EXISTS (SELECT 1 FROM ${table} a WHERE a.coordinator_id = NEW.coordinator_id\n AND a.attempt_id = NEW.end_attempt_id AND a.state = 'committing' AND a.intent = 'disconnect'\n AND a.target_link_id = NEW.link_id AND a.identity_id = NEW.identity_id AND a.issuer = NEW.issuer AND a.target_subject = NEW.subject)\nBEGIN SELECT RAISE(ABORT,'account_change_archive_receipt_invalid'); END`;\nexport const ACCOUNT_CHANGE_SCHEMA_STATEMENTS = [\n\t`CREATE TABLE ${table} (\n coordinator_id TEXT NOT NULL, attempt_id TEXT NOT NULL,\n intent TEXT NOT NULL CHECK(intent IN ('refresh','disconnect')),\n target_link_id TEXT NOT NULL, identity_id TEXT NOT NULL, issuer TEXT NOT NULL, target_subject TEXT NOT NULL,\n group_id TEXT NOT NULL, device_id TEXT NOT NULL, public_key TEXT NOT NULL, fingerprint TEXT NOT NULL,\n key_id TEXT NOT NULL, enrollment_identity_id TEXT, auth_config_revision TEXT NOT NULL,\n runtime_verifier_hash TEXT NOT NULL, browser_start_hash TEXT NOT NULL, loopback_redirect TEXT NOT NULL,\n state TEXT NOT NULL CHECK(state IN ('pending','browser_pending','consumed','verified','confirmed','committing','completed','cancelled','failed','expired')),\n failure_reason TEXT CHECK(failure_reason IN ('device_cancelled','provider_failure','expired')),\n state_hash TEXT, binder_hash TEXT, nonce TEXT, pkce_verifier TEXT, browser_order INTEGER,\n completion_secret_hash TEXT, display_name TEXT, email TEXT, email_verified INTEGER, picture_url TEXT,\n created_at_ms INTEGER NOT NULL, expires_at_ms INTEGER NOT NULL,\n consumed_at_ms INTEGER, verified_at_ms INTEGER, confirmed_at_ms INTEGER, completed_at_ms INTEGER,\n PRIMARY KEY(coordinator_id,attempt_id), UNIQUE(coordinator_id,browser_start_hash),\n UNIQUE(coordinator_id,runtime_verifier_hash), UNIQUE(coordinator_id,state_hash),\n UNIQUE(coordinator_id,binder_hash), UNIQUE(coordinator_id,completion_secret_hash),\n CHECK(typeof(created_at_ms) = 'integer' AND created_at_ms BETWEEN 0 AND 9007199254140991 AND expires_at_ms = created_at_ms + 600000),\n CHECK(browser_order IS NULL OR (typeof(browser_order) = 'integer' AND browser_order BETWEEN 1 AND 9007199254740991)),\n CHECK((state = 'completed') = (completed_at_ms IS NOT NULL)),\n CHECK((state = 'failed' AND failure_reason IS 'provider_failure') OR (state = 'expired' AND failure_reason IS 'expired') OR (state = 'cancelled' AND failure_reason IS 'device_cancelled') OR (state NOT IN ('failed','expired','cancelled') AND failure_reason IS NULL)),\n CHECK(state <> 'pending' OR (state_hash IS NULL AND binder_hash IS NULL AND browser_order IS NULL)),\n CHECK(state <> 'browser_pending' OR (state_hash IS NOT NULL AND binder_hash IS NOT NULL AND nonce IS NOT NULL AND pkce_verifier IS NOT NULL AND browser_order IS NOT NULL)),\n CHECK(state IN ('pending','browser_pending') OR (nonce IS NULL AND pkce_verifier IS NULL)),\n CHECK(state NOT IN ('consumed','verified','confirmed','committing','completed') OR (consumed_at_ms IS NOT NULL AND consumed_at_ms >= created_at_ms AND consumed_at_ms < expires_at_ms)),\n CHECK(state NOT IN ('verified','confirmed','committing','completed') OR (verified_at_ms IS NOT NULL AND verified_at_ms >= consumed_at_ms AND verified_at_ms < expires_at_ms)),\n CHECK(state NOT IN ('confirmed','committing','completed') OR (completion_secret_hash IS NOT NULL AND confirmed_at_ms IS NOT NULL AND confirmed_at_ms >= verified_at_ms AND confirmed_at_ms < expires_at_ms)),\n CHECK(state <> 'completed' OR (completed_at_ms >= confirmed_at_ms AND completed_at_ms < expires_at_ms AND display_name IS NULL AND email IS NULL AND email_verified IS NULL AND picture_url IS NULL)),\n CHECK(email_verified IS NULL OR (email_verified IN (0,1) AND email IS NOT NULL))\n)`,\n\t`CREATE TRIGGER account_change_collision BEFORE INSERT ON ${table}\nWHEN EXISTS (SELECT 1 FROM ${table} WHERE coordinator_id = NEW.coordinator_id AND\n (attempt_id = NEW.attempt_id OR browser_start_hash = NEW.browser_start_hash OR runtime_verifier_hash = NEW.runtime_verifier_hash OR state_hash = NEW.state_hash OR binder_hash = NEW.binder_hash OR completion_secret_hash = NEW.completion_secret_hash))\nBEGIN SELECT RAISE(ABORT,'account_change_collision'); END`,\n\t`CREATE TRIGGER account_change_birth BEFORE UPDATE ON ${table}\nWHEN ${[\"coordinator_id\", \"attempt_id\", \"intent\", \"target_link_id\", \"identity_id\", \"issuer\", \"target_subject\", \"group_id\", \"device_id\", \"public_key\", \"fingerprint\", \"key_id\", \"enrollment_identity_id\", \"auth_config_revision\", \"runtime_verifier_hash\", \"browser_start_hash\", \"loopback_redirect\", \"created_at_ms\", \"expires_at_ms\"].map((c) => `NEW.${c} IS NOT OLD.${c}`).join(\" OR \")}\nBEGIN SELECT RAISE(ABORT,'account_change_birth_immutable'); END`,\n\t`CREATE TRIGGER account_change_transition BEFORE UPDATE ON ${table}\nWHEN OLD.state IN ('completed','cancelled','failed','expired') OR NOT (\n (OLD.state = 'pending' AND NEW.state = 'browser_pending') OR\n (OLD.state = 'browser_pending' AND NEW.state = 'consumed') OR\n (OLD.state = 'consumed' AND ((OLD.intent = 'refresh' AND NEW.state = 'confirmed') OR (OLD.intent = 'disconnect' AND NEW.state = 'verified'))) OR\n (OLD.state = 'verified' AND NEW.state = 'confirmed') OR\n (OLD.state = 'confirmed' AND NEW.state = 'committing') OR\n (OLD.state = 'committing' AND NEW.state = 'completed') OR\n (OLD.state NOT IN ('committing','completed','cancelled','failed','expired') AND NEW.state IN ('cancelled','expired')) OR\n (OLD.state = 'consumed' AND NEW.state = 'failed'))\nBEGIN SELECT RAISE(ABORT,'account_change_transition_invalid'); END`,\n\t`CREATE TRIGGER account_change_receipt_delete BEFORE DELETE ON ${table} WHEN OLD.state = 'completed'\nBEGIN SELECT RAISE(ABORT,'account_change_receipt_immutable'); END`,\n\tBROWSER_ACCOUNT_ARCHIVE_GUARD,\n\t// EXPLAIN in the focused tests checks that the repeated revocation barrier\n\t// changes from a coordinator-prefix scan to an Identity-specific covering lookup.\n\t`CREATE INDEX account_connection_history_identity_revoked ON coordinator_auth_account_connection_history(coordinator_id,identity_id,revoked_at_ms)`,\n\t`ALTER TABLE coordinator_auth_link_profiles ADD COLUMN source_change_attempt_id TEXT`,\n\t`ALTER TABLE coordinator_auth_link_profiles ADD COLUMN source_order INTEGER`,\n\t`ALTER TABLE coordinator_auth_account_profiles ADD COLUMN source_order INTEGER`,\n] as const;\n","/** Device authorization receipts contain no browser or provider proof claims. */\nexport const ACCOUNT_UNLINK_TABLE = \"coordinator_auth_account_connection_unlinks\";\nconst table = ACCOUNT_UNLINK_TABLE;\nconst birth = [\n\t\"coordinator_id\",\n\t\"attempt_id\",\n\t\"target_link_id\",\n\t\"identity_id\",\n\t\"issuer\",\n\t\"target_subject\",\n\t\"group_id\",\n\t\"device_id\",\n\t\"public_key\",\n\t\"fingerprint\",\n\t\"enrollment_identity_id\",\n\t\"auth_config_revision\",\n\t\"request_hash\",\n\t\"created_at_ms\",\n];\nexport const ACCOUNT_UNLINK_SCHEMA_STATEMENTS = [\n\t`CREATE TABLE ${table} (\n coordinator_id TEXT NOT NULL, attempt_id TEXT NOT NULL, target_link_id TEXT NOT NULL,\n identity_id TEXT NOT NULL, issuer TEXT NOT NULL, target_subject TEXT NOT NULL,\n group_id TEXT NOT NULL, device_id TEXT NOT NULL, public_key TEXT NOT NULL, fingerprint TEXT NOT NULL,\n enrollment_identity_id TEXT, auth_config_revision TEXT NOT NULL,\n request_hash TEXT NOT NULL CHECK(length(request_hash)=64 AND request_hash NOT GLOB '*[^0-9a-f]*'),\n state TEXT NOT NULL CHECK(state IN ('committing','completed')),\n created_at_ms INTEGER NOT NULL CHECK(typeof(created_at_ms)='integer' AND created_at_ms BETWEEN 0 AND 9007199254740991),\n completed_at_ms INTEGER,\n PRIMARY KEY(coordinator_id,attempt_id), UNIQUE(coordinator_id,target_link_id),\n CHECK((state='completed')=(completed_at_ms IS NOT NULL)),\n CHECK(completed_at_ms IS NULL OR (typeof(completed_at_ms)='integer' AND completed_at_ms>=created_at_ms AND completed_at_ms<=9007199254740991))\n )`,\n\t`CREATE TRIGGER account_connection_unlink_insert BEFORE INSERT ON ${table}\n WHEN NEW.state<>'committing' OR EXISTS (SELECT 1 FROM ${table} WHERE rowid=NEW.rowid OR (coordinator_id=NEW.coordinator_id AND (attempt_id=NEW.attempt_id OR target_link_id=NEW.target_link_id)))\n BEGIN SELECT RAISE(ABORT,'account_unlink_collision'); END`,\n\t`CREATE TRIGGER account_connection_unlink_rowid AFTER INSERT ON ${table} WHEN NEW.rowid<1\n BEGIN SELECT RAISE(ABORT,'account_unlink_rowid'); END`,\n\t`CREATE TRIGGER account_connection_unlink_update BEFORE UPDATE ON ${table}\n WHEN ${birth.map((c) => `NEW.${c} IS NOT OLD.${c}`).join(\" OR \")} OR NEW.rowid IS NOT OLD.rowid OR OLD.state<>'committing' OR NEW.state<>'completed'\n BEGIN SELECT RAISE(ABORT,'account_unlink_immutable'); END`,\n\t`CREATE TRIGGER account_connection_unlink_delete BEFORE DELETE ON ${table}\n BEGIN SELECT RAISE(ABORT,'account_unlink_immutable'); END`,\n] as const;\n\nexport function accountArchiveReceiptGuard(browserGuard: string): string {\n\treturn browserGuard.replace(\n\t\t\"BEGIN SELECT\",\n\t\t` AND NOT EXISTS (SELECT 1 FROM ${table} a WHERE a.coordinator_id=NEW.coordinator_id\n AND a.attempt_id=NEW.end_attempt_id AND a.state='committing' AND a.target_link_id=NEW.link_id\n AND a.identity_id=NEW.identity_id AND a.issuer=NEW.issuer AND a.target_subject=NEW.subject)\nBEGIN SELECT`,\n\t);\n}\n","/**\n * Committed proof only: future finalization must insert it atomically with the\n * winning attempt, account link, and audit row. No request-to-proof writer lives here.\n * References are logical, and revocation retains this immutable proof forever.\n * This leaf schema is not installed automatically when an existing store opens.\n */\nexport const COORDINATOR_AUTH_DEVICE_CLAIM_SCHEMA_STATEMENTS = [\n\t`\nCREATE TABLE IF NOT EXISTS coordinator_auth_device_claims (\n claim_id TEXT PRIMARY KEY NOT NULL CHECK(\n typeof(claim_id) = 'text' AND length(claim_id) BETWEEN 1 AND 256\n AND claim_id = trim(claim_id) AND instr(claim_id, char(0)) = 0),\n coordinator_id TEXT NOT NULL CHECK(\n typeof(coordinator_id) = 'text' AND length(coordinator_id) BETWEEN 1 AND 256\n AND coordinator_id = trim(coordinator_id) AND instr(coordinator_id, char(0)) = 0),\n identity_id TEXT NOT NULL CHECK(\n typeof(identity_id) = 'text' AND length(identity_id) BETWEEN 1 AND 256\n AND identity_id = trim(identity_id) AND instr(identity_id, char(0)) = 0),\n group_id TEXT NOT NULL CHECK(\n typeof(group_id) = 'text' AND length(group_id) BETWEEN 1 AND 256\n AND group_id = trim(group_id) AND instr(group_id, char(0)) = 0),\n device_id TEXT NOT NULL CHECK(\n typeof(device_id) = 'text' AND length(device_id) BETWEEN 1 AND 256\n AND device_id = trim(device_id) AND instr(device_id, char(0)) = 0),\n public_key TEXT NOT NULL CHECK(\n typeof(public_key) = 'text' AND length(public_key) BETWEEN 1 AND 4096\n AND length(trim(replace(replace(public_key, char(13), ''), char(10), ''))) > 0\n AND instr(public_key, char(0)) = 0),\n fingerprint TEXT NOT NULL CHECK(\n typeof(fingerprint) = 'text' AND length(fingerprint) = 64\n AND fingerprint NOT GLOB '*[^a-f0-9]*' AND instr(fingerprint, char(0)) = 0),\n key_id TEXT NOT NULL CHECK(\n typeof(key_id) = 'text' AND length(key_id) = 64\n AND key_id NOT GLOB '*[^a-f0-9]*' AND instr(key_id, char(0)) = 0),\n attempt_id TEXT NOT NULL CHECK(\n typeof(attempt_id) = 'text' AND length(attempt_id) BETWEEN 1 AND 256\n AND attempt_id = trim(attempt_id) AND instr(attempt_id, char(0)) = 0),\n issuer TEXT NOT NULL CHECK(\n typeof(issuer) = 'text' AND length(trim(issuer)) > 0\n AND issuer = trim(issuer) AND instr(issuer, char(0)) = 0),\n auth_config_revision TEXT NOT NULL CHECK(\n typeof(auth_config_revision) = 'text' AND length(auth_config_revision) = 64\n AND auth_config_revision NOT GLOB '*[^a-f0-9]*' AND instr(auth_config_revision, char(0)) = 0),\n created_at_ms INTEGER NOT NULL CHECK(\n typeof(created_at_ms) = 'integer' AND created_at_ms BETWEEN 0 AND 9007199254740991),\n UNIQUE (coordinator_id, identity_id),\n UNIQUE (coordinator_id, device_id),\n UNIQUE (coordinator_id, key_id),\n UNIQUE (coordinator_id, attempt_id)\n) WITHOUT ROWID;\n`,\n\t`\n-- REPLACE's implicit deletes may skip DELETE triggers when recursive triggers are off.\n-- Check every unique identifier before conflict handling, including UPSERT DO NOTHING.\nCREATE TRIGGER IF NOT EXISTS coordinator_auth_device_claims_insert_collision\nBEFORE INSERT ON coordinator_auth_device_claims\nWHEN EXISTS (\n SELECT 1 FROM coordinator_auth_device_claims\n WHERE claim_id = NEW.claim_id OR (coordinator_id = NEW.coordinator_id AND (\n identity_id = NEW.identity_id OR device_id = NEW.device_id\n OR key_id = NEW.key_id OR attempt_id = NEW.attempt_id\n ))\n)\nBEGIN\n SELECT RAISE(ABORT, 'auth_device_claim_collision');\nEND;\n`,\n\t`\nCREATE TRIGGER IF NOT EXISTS coordinator_auth_device_claims_immutable_update\nBEFORE UPDATE ON coordinator_auth_device_claims\nBEGIN\n SELECT RAISE(ABORT, 'auth_device_claim_immutable');\nEND;\n`,\n\t`\nCREATE TRIGGER IF NOT EXISTS coordinator_auth_device_claims_immutable_delete\nBEFORE DELETE ON coordinator_auth_device_claims\nBEGIN\n SELECT RAISE(ABORT, 'auth_device_claim_immutable');\nEND;\n`,\n] as const;\n\nexport const COORDINATOR_AUTH_DEVICE_CLAIM_SCHEMA_SQL =\n\tCOORDINATOR_AUTH_DEVICE_CLAIM_SCHEMA_STATEMENTS.join(\"\\n\");\n\nconst quoteSql = (value: string) => `'${value.replaceAll(\"'\", \"''\")}'`;\nconst proofDefinitions = COORDINATOR_AUTH_DEVICE_CLAIM_SCHEMA_STATEMENTS.map((statement) =>\n\tstatement.replace(/^(?:\\s|--[^\\n]*\\n)*/u, \"\").replace(/;\\s*$/u, \"\"),\n);\n// Frozen DDL only, not a SQL parser. Protect known literals before removing layout;\n// unknown literals retain their quotes and cannot match a protected literal token.\nconst proofLiterals = [...new Set(proofDefinitions.join(\"\\n\").match(/'(?:[^']|'')*'/gu))];\nfunction canonicalProofSql(\n\texpression: string,\n\tliterals: readonly string[] = proofLiterals,\n): string {\n\tlet sql = expression;\n\tfor (const [index, literal] of literals.entries())\n\t\tsql = `replace(${sql}, ${quoteSql(literal)}, 'literal_${index}')`;\n\treturn `rtrim(replace(replace(replace(replace(replace(${sql}, 'IF NOT EXISTS', ''), ' ', ''), char(10), ''), char(13), ''), char(9), ''), char(59))`;\n}\n\n/** Same effective-definition checks for SQLite, D1 readiness and explicit cutover. */\nexport function authSchemaDefinitionCheck(\n\tdefinition: string,\n\toptions: { auxiliaryObjects?: number; literals?: readonly string[] } = {},\n) {\n\tdefinition = definition.replace(/^(?:\\s|--[^\\n]*\\n)*/u, \"\").replace(/;\\s*$/u, \"\");\n\t// Headers of this repository's frozen declarations only, not a DDL parser.\n\tconst header = /^CREATE (TABLE|TRIGGER|(?:UNIQUE )?INDEX)(?: IF NOT EXISTS)? (\\w+)/u.exec(\n\t\tdefinition,\n\t);\n\tif (!header?.[1] || !header[2]) throw new Error(\"auth_device_claim_definition_invalid\");\n\t// Encode the known ASCII DDL so trigger-body semicolons cannot split cutover statements.\n\tconst hex = [...definition]\n\t\t.map((character) => character.charCodeAt(0).toString(16).padStart(2, \"0\"))\n\t\t.join(\"\");\n\tlet auxiliaryCheck = \"\";\n\tif (options.auxiliaryObjects !== undefined)\n\t\tauxiliaryCheck = ` AND (SELECT count(*) FROM sqlite_master WHERE tbl_name = ${quoteSql(header[2])} COLLATE NOCASE AND type IN ('index','trigger') AND sql IS NOT NULL) = ${options.auxiliaryObjects}`;\n\tconst literals = options.literals ?? [...new Set(definition.match(/'(?:[^']|'')*'/gu))];\n\treturn {\n\t\tname: header[2],\n\t\tmatches: `EXISTS (SELECT 1 FROM sqlite_master WHERE type = ${quoteSql(header[1].toLowerCase().replace(\"unique \", \"\"))} AND name = ${quoteSql(header[2])} COLLATE NOCASE AND ${canonicalProofSql(\"sql\", literals)} = ${canonicalProofSql(`CAST(X'${hex}' AS TEXT)`, literals)}${auxiliaryCheck})`,\n\t};\n}\nexport const authDeviceClaimDefinitionChecks = (auxiliaryObjects = 3) =>\n\tproofDefinitions.map((definition, index) =>\n\t\tauthSchemaDefinitionCheck(definition, {\n\t\t\tauxiliaryObjects: index === 0 ? auxiliaryObjects : undefined,\n\t\t\tliterals: proofLiterals,\n\t\t}),\n\t);\nexport const AUTH_DEVICE_CLAIM_DEFINITION_CHECKS = authDeviceClaimDefinitionChecks();\n\n/**\n * Database columns for an already committed proof, not an authorization input.\n * public_key retains exact enrollment bytes (including PEM line endings);\n * key_id is the canonical SHA-256 key ID, not the PEM fingerprint. Both hashes\n * and auth_config_revision use the lowercase 64-hex format of link capture.\n * CHECKs validate storage shape only; finalization must verify all authority.\n */\nexport interface CoordinatorAuthDeviceClaimRow {\n\treadonly claim_id: string;\n\treadonly coordinator_id: string;\n\treadonly identity_id: string;\n\treadonly group_id: string;\n\treadonly device_id: string;\n\treadonly public_key: string;\n\treadonly fingerprint: string;\n\treadonly key_id: string;\n\treadonly attempt_id: string;\n\treadonly issuer: string;\n\treadonly auth_config_revision: string;\n\treadonly created_at_ms: number;\n}\n","export const AUTH_LINK_PURPOSE = \"coordinator-account-link-v1\";\nexport const AUTH_LINK_ATTEMPT_TTL_MS = 600000;\nexport const AUTH_LINK_MAX_ACTIVE_PER_DEVICE = 2;\nexport const AUTH_LINK_MAX_ACTIVE_PER_IDENTITY = 3;\nexport const AUTH_LINK_CREATE_WINDOW_MS = 3600000;\nexport const AUTH_LINK_MAX_CREATES_PER_DEVICE_WINDOW = 6;\nexport const AUTH_LINK_RETENTION_WINDOW_MS = 2592000000;\nexport const AUTH_LINK_MAX_CREATES_PER_DEVICE_RETENTION = 60;\nexport const AUTH_LINK_MAX_UNFINISHED_PER_COORDINATOR = 10000;\nexport const AUTH_LINK_EXPIRE_BATCH_MAX = 32;\n/** Trusted server configuration, never request JSON. */\nexport interface CoordinatorAuthLinkConfig {\n\tcoordinatorId: string;\n\tissuer: string;\n\trevision: string;\n\tenabled: boolean;\n}\n/** Already verified request key possession; SQL rechecks the selected authority source. */\nexport interface CoordinatorAuthLinkSigner {\n\tgroupId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n}\nexport type CoordinatorAuthLinkRequester =\n\t| { kind: \"device\"; signer: CoordinatorAuthLinkSigner }\n\t| { kind: \"browser\"; browserTransactionHash: string };\nexport type CoordinatorAuthLinkState =\n\t| \"pending\"\n\t| \"browser_claimed\"\n\t| \"oidc_verified\"\n\t| \"confirmed\"\n\t| \"finalized\"\n\t| \"session_redeemed\"\n\t| \"expired\"\n\t| \"failed\";\nexport interface CoordinatorAuthLinkStatus {\n\tattemptId: string;\n\tstate: CoordinatorAuthLinkState;\n\texpiresAtMs: number;\n}\nexport type CoordinatorAuthLinkError =\n\t| \"invalid_input\"\n\t| \"controller_not_active\"\n\t| \"attempt_conflict\"\n\t| \"attempt_limited\"\n\t| \"attempt_unavailable\"\n\t| \"attempt_expired\"\n\t| \"auth_config_changed\"\n\t| \"link_conflict\";\nexport interface CoordinatorAuthLinkRejected {\n\tkind: \"rejected\";\n\terror: CoordinatorAuthLinkError;\n}\nexport interface CoordinatorAuthLinkMaintenanceOptions {\n\tlimit?: number;\n}\nexport type CoordinatorAuthLinkMaintenanceResult =\n\t| { kind: \"maintained\"; processedCount: number; more: boolean }\n\t| CoordinatorAuthLinkRejected;\nexport type CoordinatorAuthLinkResult =\n\t| { kind: \"applied\" | \"existing\"; status: CoordinatorAuthLinkStatus }\n\t| CoordinatorAuthLinkRejected;\nexport type CoordinatorAuthLinkCreateResult =\n\t| { kind: \"created\" | \"existing\"; status: CoordinatorAuthLinkStatus; identityId: string }\n\t| CoordinatorAuthLinkRejected;\nexport type CoordinatorAuthLinkOidcResult =\n\t| {\n\t\t\tkind: \"applied\";\n\t\t\tstatus: CoordinatorAuthLinkStatus;\n\t\t\t/**\n\t\t\t * fingerprint names the device key for consent; desktop pages need not render it.\n\t\t\t * headless is present only for headless attempts, from the same row read.\n\t\t\t */\n\t\t\ttarget: {\n\t\t\t\tidentityId: string;\n\t\t\t\tgroupId: string;\n\t\t\t\tdeviceId: string;\n\t\t\t\tfingerprint: string;\n\t\t\t\theadless?: true;\n\t\t\t};\n\t }\n\t| CoordinatorAuthLinkRejected;\nexport interface CoordinatorAuthLinkCreateInput {\n\t/** Trusted server-selected source; device claims pin the current local Identity. */\n\tauthority: { kind: \"controller_attestation\" } | { kind: \"device_claim\"; identityId: string };\n\t/** Public HTTP callers pin their current Identity for either source kind. */\n\texpectedIdentityId?: string;\n\tattemptId: string;\n\tsigner: CoordinatorAuthLinkSigner;\n\truntimeVerifierHash: string;\n\tloopbackRedirect: string;\n\t/** Required for device claims; trusted attested callers may omit it. */\n\tbrowserStartHash?: string;\n}\nexport interface CoordinatorAuthLinkClaimInput {\n\tattemptId: string;\n\tbrowserTransactionHash: string;\n}\nexport interface CoordinatorAuthLinkOidcInput extends CoordinatorAuthLinkClaimInput {\n\taccount: { issuer: string; subject: string };\n\t/** Optional display claims from the same verified callback, never request JSON. */\n\tprofile?: unknown;\n}\nexport interface CoordinatorAuthLinkConfirmInput extends CoordinatorAuthLinkClaimInput {\n\tcompletionSecretHash: string;\n}\nexport interface CoordinatorAuthLinkFinalizeInput {\n\tpurpose: typeof AUTH_LINK_PURPOSE;\n\tcoordinatorId: string;\n\tattemptId: string;\n\tgroupId: string;\n\tidentityId: string;\n\tdeviceId: string;\n\tfingerprint: string;\n\truntimeVerifierHash: string;\n\tcompletionSecretHash: string;\n\tsigner: CoordinatorAuthLinkSigner;\n}\nexport interface CoordinatorAuthLinkFailInput {\n\tattemptId: string;\n\trequester: CoordinatorAuthLinkRequester;\n\treason: \"cancelled\" | \"provider_failure\" | \"config_failure\";\n}\nexport interface CoordinatorAuthLinkStore {\n\tmaintainAuthLinkAttempts(\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t\toptions?: CoordinatorAuthLinkMaintenanceOptions,\n\t): Promise<CoordinatorAuthLinkMaintenanceResult>;\n\tcreateAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkCreateInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkCreateResult>;\n\tclaimAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkClaimInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkResult>;\n\trecordAuthLinkOidcVerified(\n\t\tinput: CoordinatorAuthLinkOidcInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkOidcResult>;\n\tconfirmAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkConfirmInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkResult>;\n\treadAuthLinkCompletionDestination(\n\t\tinput: CoordinatorAuthLinkClaimInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<{ destination: string } | null>;\n\tfinalizeAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkFinalizeInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkResult>;\n\tfailAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkFailInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkResult>;\n\tgetAuthLinkAttemptStatus(\n\t\tattemptId: string,\n\t\trequester: CoordinatorAuthLinkRequester,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkStatus | null>;\n}\nexport interface CoordinatorAuthLinkOptions {\n\tauthClock?: () => number;\n}\n\nexport const AUTH_LINK_BROWSER_START_COLUMN_SQL =\n\t\"browser_start_hash TEXT CHECK (browser_start_hash IS NULL OR (length(browser_start_hash) = 64 AND browser_start_hash NOT GLOB '*[^0-9a-f]*'))\";\nexport const AUTH_LINK_BROWSER_START_INDEX_SQL = `CREATE UNIQUE INDEX IF NOT EXISTS idx_auth_link_attempts_browser_start\n ON coordinator_auth_link_attempts(coordinator_id, browser_start_hash);`;\n\nexport const AUTH_LINK_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS coordinator_auth_link_attempts (\n coordinator_id TEXT NOT NULL,\n attempt_id TEXT NOT NULL,\n identity_id TEXT NOT NULL,\n group_id TEXT NOT NULL,\n device_id TEXT NOT NULL,\n public_key TEXT NOT NULL,\n fingerprint TEXT NOT NULL CHECK (length(fingerprint) = 64 AND fingerprint NOT GLOB '*[^0-9a-f]*'),\n controller_attestation_id TEXT,\n controller_review_receipt_id TEXT,\n controller_revision INTEGER,\n issuer TEXT NOT NULL,\n auth_config_revision TEXT NOT NULL CHECK (length(auth_config_revision) = 64 AND auth_config_revision NOT GLOB '*[^0-9a-f]*'),\n runtime_verifier_hash TEXT NOT NULL CHECK (length(runtime_verifier_hash) = 64 AND runtime_verifier_hash NOT GLOB '*[^0-9a-f]*'),\n loopback_redirect TEXT NOT NULL,\n state TEXT NOT NULL CHECK (state IN ('pending','browser_claimed','oidc_verified','confirmed','finalized','session_redeemed','expired','failed')),\n browser_transaction_hash TEXT CHECK (browser_transaction_hash IS NULL OR (length(browser_transaction_hash) = 64 AND browser_transaction_hash NOT GLOB '*[^0-9a-f]*')),\n account_subject TEXT CHECK (account_subject IS NULL OR length(account_subject) BETWEEN 1 AND 255),\n completion_secret_hash TEXT CHECK (completion_secret_hash IS NULL OR (length(completion_secret_hash) = 64 AND completion_secret_hash NOT GLOB '*[^0-9a-f]*')),\n link_id TEXT,\n failure_reason TEXT CHECK (failure_reason IS NULL OR failure_reason IN ('device_cancelled','browser_cancelled','provider_failure','config_failure')),\n created_at_ms INTEGER NOT NULL CHECK (typeof(created_at_ms) = 'integer' AND created_at_ms >= 0 AND created_at_ms <= 9007199254140991),\n expires_at_ms INTEGER NOT NULL CHECK (typeof(expires_at_ms) = 'integer' AND expires_at_ms = created_at_ms + 600000),\n claimed_at_ms INTEGER,\n oidc_verified_at_ms INTEGER,\n confirmed_at_ms INTEGER,\n finalized_at_ms INTEGER,\n failed_at_ms INTEGER,\n ${AUTH_LINK_BROWSER_START_COLUMN_SQL},\n authority_kind TEXT NOT NULL CHECK (authority_kind IN ('controller_attestation','device_claim')),\n PRIMARY KEY (coordinator_id, attempt_id),\n UNIQUE (coordinator_id, runtime_verifier_hash),\n UNIQUE (coordinator_id, browser_transaction_hash),\n UNIQUE (coordinator_id, completion_secret_hash),\n UNIQUE (coordinator_id, link_id),\n CHECK (state <> 'pending' OR (browser_transaction_hash IS NULL AND account_subject IS NULL AND completion_secret_hash IS NULL AND link_id IS NULL)),\n CHECK (state NOT IN ('browser_claimed','oidc_verified','confirmed','finalized','session_redeemed') OR browser_transaction_hash IS NOT NULL),\n CHECK (state NOT IN ('oidc_verified','confirmed','finalized','session_redeemed') OR account_subject IS NOT NULL),\n CHECK (state NOT IN ('confirmed','finalized','session_redeemed') OR completion_secret_hash IS NOT NULL),\n CHECK ((state IN ('finalized','session_redeemed') AND link_id IS NOT NULL AND finalized_at_ms IS NOT NULL) OR (state NOT IN ('finalized','session_redeemed') AND link_id IS NULL AND finalized_at_ms IS NULL)),\n CHECK ((state = 'failed' AND failure_reason IS NOT NULL AND failed_at_ms IS NOT NULL) OR (state <> 'failed' AND failure_reason IS NULL AND failed_at_ms IS NULL)),\n CHECK ((authority_kind = 'controller_attestation'\n AND (controller_attestation_id IS NOT NULL AND typeof(controller_attestation_id) = 'text' AND length(controller_attestation_id) BETWEEN 1 AND 256 AND controller_attestation_id = trim(controller_attestation_id) AND instr(controller_attestation_id, char(0)) = 0)\n AND (controller_review_receipt_id IS NOT NULL AND typeof(controller_review_receipt_id) = 'text' AND length(controller_review_receipt_id) BETWEEN 1 AND 256 AND controller_review_receipt_id = trim(controller_review_receipt_id) AND instr(controller_review_receipt_id, char(0)) = 0)\n AND controller_revision IS NOT NULL AND typeof(controller_revision) = 'integer' AND controller_revision = 1)\n OR (authority_kind = 'device_claim' AND controller_attestation_id IS NULL AND controller_review_receipt_id IS NULL AND controller_revision IS NULL))\n);\nCREATE TABLE IF NOT EXISTS coordinator_auth_account_links (\n coordinator_id TEXT NOT NULL,\n link_id TEXT NOT NULL,\n issuer TEXT NOT NULL,\n subject TEXT NOT NULL CHECK (length(subject) BETWEEN 1 AND 255),\n identity_id TEXT NOT NULL,\n attempt_id TEXT NOT NULL,\n controller_attestation_id TEXT,\n auth_config_revision TEXT NOT NULL CHECK (length(auth_config_revision) = 64 AND auth_config_revision NOT GLOB '*[^0-9a-f]*'),\n created_at_ms INTEGER NOT NULL,\n revoked_at_ms INTEGER,\n authority_kind TEXT NOT NULL CHECK (authority_kind IN ('controller_attestation','device_claim')),\n device_claim_id TEXT,\n PRIMARY KEY (coordinator_id, link_id),\n UNIQUE (coordinator_id, issuer, subject),\n UNIQUE (coordinator_id, identity_id),\n UNIQUE (coordinator_id, attempt_id),\n UNIQUE (device_claim_id),\n CHECK ((authority_kind = 'controller_attestation'\n AND (controller_attestation_id IS NOT NULL AND typeof(controller_attestation_id) = 'text' AND length(controller_attestation_id) BETWEEN 1 AND 256 AND controller_attestation_id = trim(controller_attestation_id) AND instr(controller_attestation_id, char(0)) = 0) AND device_claim_id IS NULL)\n OR (authority_kind = 'device_claim' AND controller_attestation_id IS NULL\n AND (device_claim_id IS NOT NULL AND typeof(device_claim_id) = 'text' AND length(device_claim_id) BETWEEN 1 AND 256 AND device_claim_id = trim(device_claim_id) AND instr(device_claim_id, char(0)) = 0)))\n);\nCREATE TABLE IF NOT EXISTS coordinator_auth_link_audit_log (\n coordinator_id TEXT NOT NULL,\n link_id TEXT NOT NULL,\n action TEXT NOT NULL CHECK (action IN ('link_created','link_revoked')),\n attempt_id TEXT NOT NULL,\n identity_id TEXT NOT NULL,\n group_id TEXT NOT NULL,\n device_id TEXT NOT NULL,\n fingerprint TEXT NOT NULL CHECK (length(fingerprint) = 64 AND fingerprint NOT GLOB '*[^0-9a-f]*'),\n controller_attestation_id TEXT,\n auth_config_revision TEXT NOT NULL CHECK (length(auth_config_revision) = 64 AND auth_config_revision NOT GLOB '*[^0-9a-f]*'),\n created_at_ms INTEGER NOT NULL,\n authority_kind TEXT NOT NULL CHECK (authority_kind IN ('controller_attestation','device_claim')),\n device_claim_id TEXT,\n PRIMARY KEY (coordinator_id, link_id, action),\n CHECK ((authority_kind = 'controller_attestation'\n AND (controller_attestation_id IS NOT NULL AND typeof(controller_attestation_id) = 'text' AND length(controller_attestation_id) BETWEEN 1 AND 256 AND controller_attestation_id = trim(controller_attestation_id) AND instr(controller_attestation_id, char(0)) = 0) AND device_claim_id IS NULL)\n OR (authority_kind = 'device_claim' AND controller_attestation_id IS NULL\n AND (device_claim_id IS NOT NULL AND typeof(device_claim_id) = 'text' AND length(device_claim_id) BETWEEN 1 AND 256 AND device_claim_id = trim(device_claim_id) AND instr(device_claim_id, char(0)) = 0)))\n);\nCREATE INDEX IF NOT EXISTS idx_auth_link_attempts_device_created\n ON coordinator_auth_link_attempts(coordinator_id, group_id, device_id, created_at_ms);\nCREATE INDEX IF NOT EXISTS idx_auth_link_attempts_identity_expiry\n ON coordinator_auth_link_attempts(coordinator_id, identity_id, expires_at_ms);\nCREATE INDEX IF NOT EXISTS idx_auth_link_attempts_state_expiry\n ON coordinator_auth_link_attempts(coordinator_id, state, expires_at_ms);\n${AUTH_LINK_BROWSER_START_INDEX_SQL}`;\n","import {\n\tACCOUNT_CHANGE_SCHEMA_STATEMENTS,\n\tBROWSER_ACCOUNT_ARCHIVE_GUARD,\n} from \"./coordinator-account-change-schema.js\";\nimport { ACCOUNT_CONNECTION_STORAGE_STATEMENTS } from \"./coordinator-account-connection-storage.js\";\nimport {\n\tACCOUNT_UNLINK_SCHEMA_STATEMENTS,\n\taccountArchiveReceiptGuard,\n} from \"./coordinator-account-unlink-schema.js\";\nimport {\n\tauthDeviceClaimDefinitionChecks,\n\tauthSchemaDefinitionCheck,\n} from \"./coordinator-auth-device-claim-schema.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_ACTIVE_PER_IDENTITY,\n\tAUTH_LINK_MAX_CREATES_PER_DEVICE_RETENTION,\n\tAUTH_LINK_MAX_CREATES_PER_DEVICE_WINDOW,\n\tAUTH_LINK_MAX_UNFINISHED_PER_COORDINATOR,\n\tAUTH_LINK_RETENTION_WINDOW_MS,\n} from \"./coordinator-auth-link-contract.js\";\n\nexport const AUTH_SCHEMA_UPGRADE_REQUIRED = \"coordinator_auth_schema_upgrade_required\";\nexport const AUTH_SCHEMA_UPGRADE_MESSAGE =\n\t\"Coordinator authentication needs a schema upgrade. Pause auth writers and back up the coordinator database. For the legacy authority upgrade, run codemem coordinator schema upgrade-auth --db-path <coordinator.sqlite>. D1 operators must review and apply outstanding auth migrations before deploying the upgraded Worker. A coordinator already using device-claim auth needs only outstanding additive migrations, including 0033; do not replay its authority-table cutover. Optional account management on an intact V2 database requires codemem coordinator schema upgrade-account --db-path <coordinator.sqlite>; normal V2 linking does not require this extension. Device-signed sync remains available.\";\nexport class CoordinatorAuthSchemaUpgradeRequiredError extends Error {\n\tconstructor() {\n\t\tsuper(AUTH_SCHEMA_UPGRADE_MESSAGE);\n\t\tthis.name = AUTH_SCHEMA_UPGRADE_REQUIRED;\n\t}\n}\n\n/** Shared insertion budgets; this pure leaf has no runtime-store import cycle. */\nexport function connectionAdmissionSql(subject: \"p\" | \"NEW\"): string {\n\tconst now = subject === \"p\" ? \"p.now_ms\" : \"NEW.created_at_ms\";\n\tconst live = `b.state NOT IN ('completed','finalized','session_redeemed','failed','expired','cancelled') AND b.expires_at_ms > ${now}`;\n\treturn `EXISTS (WITH connection_budget AS MATERIALIZED (\n SELECT group_id,device_id,identity_id,state,created_at_ms,expires_at_ms FROM coordinator_account_change_attempts WHERE coordinator_id = ${subject}.coordinator_id\n UNION ALL SELECT group_id,device_id,identity_id,state,created_at_ms,expires_at_ms FROM coordinator_auth_link_attempts WHERE coordinator_id = ${subject}.coordinator_id)\n SELECT 1 WHERE\n (SELECT count(*) FROM connection_budget b WHERE b.group_id = ${subject}.group_id AND b.device_id = ${subject}.device_id AND ${live}) < ${AUTH_LINK_MAX_ACTIVE_PER_DEVICE}\n AND (SELECT count(*) FROM connection_budget b WHERE b.identity_id = ${subject}.identity_id AND ${live}) < ${AUTH_LINK_MAX_ACTIVE_PER_IDENTITY}\n AND (SELECT count(*) FROM connection_budget b WHERE b.group_id = ${subject}.group_id AND b.device_id = ${subject}.device_id AND b.created_at_ms > ${now} - ${AUTH_LINK_CREATE_WINDOW_MS}) < ${AUTH_LINK_MAX_CREATES_PER_DEVICE_WINDOW}\n AND (SELECT count(*) FROM connection_budget b WHERE b.group_id = ${subject}.group_id AND b.device_id = ${subject}.device_id AND b.created_at_ms > ${now} - ${AUTH_LINK_RETENTION_WINDOW_MS}) < ${AUTH_LINK_MAX_CREATES_PER_DEVICE_RETENTION}\n AND (SELECT count(*) FROM connection_budget b WHERE b.state NOT IN ('completed','finalized','session_redeemed')) < ${AUTH_LINK_MAX_UNFINISHED_PER_COORDINATOR})`;\n}\nexport const CONNECTION_SESSION_SCHEMA_STATEMENTS = [\n\t\"ALTER TABLE coordinator_auth_browser_transactions ADD COLUMN start_order INTEGER\",\n\t\"ALTER TABLE coordinator_auth_account_links ADD COLUMN signin_floor INTEGER NOT NULL DEFAULT 0\",\n\t\"ALTER TABLE coordinator_auth_session_receipts ADD COLUMN source_order INTEGER\",\n\t\"ALTER TABLE coordinator_auth_account_connection_history ADD COLUMN signin_floor INTEGER\",\n\t`CREATE TRIGGER connection_history_floor_insert BEFORE INSERT ON coordinator_auth_account_connection_history\n WHEN NEW.signin_floor IS NOT (SELECT c.signin_floor FROM coordinator_auth_account_links c WHERE c.coordinator_id=NEW.coordinator_id AND c.link_id=NEW.link_id AND c.rowid=NEW.original_rowid)\n BEGIN SELECT RAISE(ABORT,'connection_archive_floor_invalid'); END`,\n\t`CREATE TRIGGER connection_history_floor_update BEFORE UPDATE ON coordinator_auth_account_connection_history WHEN NEW.signin_floor IS NOT OLD.signin_floor BEGIN SELECT RAISE(ABORT,'connection_history_immutable'); END`,\n\t`CREATE TRIGGER connection_link_shared_admission BEFORE INSERT ON coordinator_auth_link_attempts WHEN NOT ${connectionAdmissionSql(\"NEW\")} BEGIN SELECT RAISE(ABORT,'connection_attempt_limited'); END`,\n] as const;\nexport const CONNECTION_LINK_SCHEMA_STATEMENTS = [\n\t\"ALTER TABLE coordinator_auth_link_attempts ADD COLUMN prior_link_id TEXT\",\n\t`CREATE TRIGGER connection_link_prior_immutable BEFORE UPDATE ON coordinator_auth_link_attempts WHEN NEW.prior_link_id IS NOT OLD.prior_link_id AND (OLD.state <> 'pending' OR OLD.prior_link_id IS NOT NULL) BEGIN SELECT RAISE(ABORT,'connection_prior_immutable'); END`,\n\t`CREATE UNIQUE INDEX connection_history_head ON coordinator_auth_account_connection_history(coordinator_id,identity_id) WHERE successor_link_id IS NULL`,\n] as const;\nconst extensions = [\n\t...ACCOUNT_CONNECTION_STORAGE_STATEMENTS,\n\t...ACCOUNT_CHANGE_SCHEMA_STATEMENTS,\n\t...CONNECTION_SESSION_SCHEMA_STATEMENTS,\n\t...CONNECTION_LINK_SCHEMA_STATEMENTS,\n];\nconst quote = (s: string) => `'${s.replaceAll(\"'\", \"''\")}'`;\nconst additions = extensions.flatMap((s) => {\n\tconst m = /^ALTER TABLE (\\w+) ADD COLUMN (\\w+) (.+)$/u.exec(s);\n\treturn m ? [{ table: m[1] as string, name: m[2] as string, declaration: m[3] as string }] : [];\n});\nconst baseCounts: Record<string, number> = {\n\tcoordinator_auth_link_attempts: 29,\n\tcoordinator_auth_account_links: 12,\n\tcoordinator_auth_link_audit_log: 13,\n\tcoordinator_auth_browser_transactions: 16,\n\tcoordinator_auth_sessions: 12,\n\tcoordinator_auth_session_receipts: 9,\n\tcoordinator_auth_link_profiles: 12,\n\tcoordinator_auth_account_profiles: 8,\n};\nfunction columnCounts(extended: boolean): string {\n\treturn Object.entries(baseCounts)\n\t\t.map(\n\t\t\t([table, n]) =>\n\t\t\t\t`(SELECT count(*) FROM pragma_table_info(${quote(table)})) = ${n + (extended ? additions.filter((a) => a.table === table).length : 0)}`,\n\t\t)\n\t\t.join(\" AND \");\n}\nfunction v2Readiness(auxiliaryObjects: number): string {\n\treturn `SELECT\n (SELECT count(*) FROM pragma_table_info('coordinator_auth_link_attempts') WHERE lower(name) = 'authority_kind')\n + (SELECT count(*) FROM pragma_table_info('coordinator_auth_account_links') WHERE lower(name) IN ('authority_kind','device_claim_id'))\n + (SELECT count(*) FROM pragma_table_info('coordinator_auth_link_audit_log') WHERE lower(name) IN ('authority_kind','device_claim_id'))\n + (SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = 'coordinator_auth_link_profiles')\n + ${authDeviceClaimDefinitionChecks(auxiliaryObjects)\n\t\t.map(({ matches }) => `(${matches})`)\n\t\t.join(\" + \")} AS ready`;\n}\n/** The old 10-count contract stays unchanged; its exact 3-auxiliary fence remains. */\nexport const AUTH_V2_SCHEMA_READINESS_SQL = v2Readiness(3);\nconst creates = extensions.filter((s) => s.startsWith(\"CREATE\"));\nconst definitions = creates.map((s) => {\n\tconst table = /^CREATE TABLE (\\w+)/u.exec(s)?.[1];\n\tif (!table) return authSchemaDefinitionCheck(s);\n\tconst final =\n\t\ttable === \"coordinator_auth_account_connection_history\"\n\t\t\t? s.replace(\n\t\t\t\t\t\" PRIMARY KEY(coordinator_id\",\n\t\t\t\t\t\" signin_floor INTEGER,\\n PRIMARY KEY(coordinator_id\",\n\t\t\t\t)\n\t\t\t: s;\n\tconst auxiliaryObjects = creates.filter((ddl) => /\\bON (\\w+)/u.exec(ddl)?.[1] === table).length;\n\treturn authSchemaDefinitionCheck(final, { auxiliaryObjects });\n});\nconst reservedObjects = `(name GLOB 'account_connection_*' OR name GLOB 'account_change_*' OR name GLOB 'connection_*' OR name GLOB 'coordinator_auth_account_connection_*' OR name = 'coordinator_account_change_attempts' OR name = 'coordinator_auth_account_associations' OR name = 'coordinator_auth_link_change_attempts')`;\nexport const CONNECTION_SCHEMA_PRESENCE_SQL = `SELECT (EXISTS (SELECT 1 FROM sqlite_master WHERE ${reservedObjects}) OR ${additions.map((a) => `EXISTS (SELECT 1 FROM pragma_table_info(${quote(a.table)}) WHERE lower(name)=${quote(a.name)})`).join(\" OR \")}) AS present`;\nconst inventory = additions.map(\n\t(a) =>\n\t\t`EXISTS (SELECT 1 FROM pragma_table_info(${quote(a.table)}) WHERE lower(name)=${quote(a.name)} AND upper(type)=${quote(a.declaration.split(\" \")[0] as string)} AND \"notnull\"=${a.declaration.includes(\"NOT NULL\") ? 1 : 0} AND dflt_value IS ${a.declaration.includes(\"DEFAULT 0\") ? \"'0'\" : \"NULL\"} AND pk=0)`,\n);\nconst knownCoordinators = `SELECT coordinator_id FROM coordinator_auth_account_links UNION SELECT coordinator_id FROM coordinator_auth_browser_transactions UNION SELECT coordinator_id FROM coordinator_auth_link_attempts UNION SELECT coordinator_id FROM coordinator_auth_sessions`;\nconst rowsValid = `NOT EXISTS (SELECT 1 FROM coordinator_auth_account_links WHERE typeof(signin_floor)<>'integer' OR signin_floor<0 OR signin_floor>9007199254740991)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_browser_transactions WHERE start_order IS NOT NULL AND (typeof(start_order)<>'integer' OR start_order<1 OR start_order>9007199254740991))\n AND NOT EXISTS (SELECT 1 FROM (SELECT coordinator_id FROM coordinator_auth_account_links UNION SELECT coordinator_id FROM coordinator_auth_browser_transactions UNION SELECT coordinator_id FROM coordinator_auth_sessions) c LEFT JOIN coordinator_auth_account_connection_orders o ON o.coordinator_id=c.coordinator_id WHERE o.last_order IS NULL OR o.last_order<1)`;\nconst priorObjectCheck = `NOT EXISTS (SELECT 1 FROM sqlite_master WHERE ${reservedObjects} AND name NOT IN (${definitions.map((d) => quote(d.name)).join(\",\")}))`;\nconst checks = [\n\t...definitions.map((d) => d.matches),\n\t...inventory,\n\tcolumnCounts(true),\n\t`(${v2Readiness(4)})=10`,\n\tpriorObjectCheck,\n\trowsValid,\n];\n// VALUES avoids D1's compound-SELECT term limit without omitting any check.\nconst readiness = (checks: string[]) =>\n\t`SELECT min(column1) AS ready FROM (VALUES ${checks.map((s) => `(CASE WHEN ${s} THEN 1 ELSE 0 END)`).join(\",\")})`;\nconst legacyReadySql = readiness(checks);\nconst unlinkGuard = accountArchiveReceiptGuard(BROWSER_ACCOUNT_ARCHIVE_GUARD);\nconst newDefinitions = [...ACCOUNT_UNLINK_SCHEMA_STATEMENTS, unlinkGuard].map((s) =>\n\tauthSchemaDefinitionCheck(s, s.startsWith(\"CREATE TABLE\") ? { auxiliaryObjects: 4 } : undefined),\n);\nconst oldGuardCheck = authSchemaDefinitionCheck(BROWSER_ACCOUNT_ARCHIVE_GUARD).matches;\nconst currentChecks = checks.filter((s) => s !== oldGuardCheck && s !== priorObjectCheck);\ncurrentChecks.push(\n\t...newDefinitions.map((d) => d.matches),\n\t`NOT EXISTS (SELECT 1 FROM sqlite_master WHERE ${reservedObjects} AND name NOT IN (${[...definitions, ...newDefinitions].map((d) => quote(d.name)).join(\",\")}))`,\n);\nconst readySql = readiness(currentChecks);\n/** Scalar readiness of the exact prior (pre-unlink) account extension. */\nexport const PRIOR_ACCOUNT_CONNECTION_SCHEMA_READINESS_SQL = legacyReadySql;\n/** Scalar readiness query for reads that must check schema and data in one snapshot. */\nexport const ACCOUNT_CONNECTION_SCHEMA_READINESS_SQL = readySql;\nexport const ACCOUNT_CONNECTION_SCHEMA_CHECKS = currentChecks;\nexport function isIncompleteConnectionSchemaError(error: unknown): boolean {\n\treturn /no such (?:table|column)|has no column named|malformed (?:database )?schema/i.test(\n\t\tString(error),\n\t);\n}\nexport type ConnectionSchemaState = \"v2\" | \"ready\" | \"upgrade_required\";\nexport async function readConnectionSchemaState(\n\tbackend: Pick<AuthLinkBackend, \"first\">,\n): Promise<ConnectionSchemaState> {\n\tconst p = await backend.first<{ present: number; v2: number }>({\n\t\tsql: `SELECT (${CONNECTION_SCHEMA_PRESENCE_SQL}) AS present, ((${AUTH_V2_SCHEMA_READINESS_SQL})=10) AS v2`,\n\t\tvalues: [],\n\t});\n\tif (!p?.present) return p?.v2 === 1 ? \"v2\" : \"upgrade_required\";\n\ttry {\n\t\treturn (await backend.first<{ ready: number }>({ sql: readySql, values: [] }))?.ready === 1\n\t\t\t? \"ready\"\n\t\t\t: \"upgrade_required\";\n\t} catch (error) {\n\t\tif (!isIncompleteConnectionSchemaError(error)) throw error;\n\t\treturn \"upgrade_required\";\n\t} // Missing tables/columns are an incomplete extension, not V2.\n}\n\n/** Explicit operator operation only: never called by store initialization. One\n * atomic batch preserves existing rowids, credentials and proof bytes. */\nexport const PRIOR_ACCOUNT_CONNECTION_MIGRATION_STATEMENTS = [\n\t`INSERT INTO coordinator_auth_device_claims (claim_id) SELECT NULL WHERE NOT (((${AUTH_V2_SCHEMA_READINESS_SQL})=10) AND NOT (${CONNECTION_SCHEMA_PRESENCE_SQL}) AND (${columnCounts(false)}))`,\n\t...extensions,\n\t`INSERT INTO coordinator_auth_account_connection_orders (coordinator_id,last_order) SELECT coordinator_id,0 FROM (${knownCoordinators})`,\n\t\"UPDATE coordinator_auth_account_connection_orders SET last_order=last_order+1\",\n\t\"UPDATE coordinator_auth_link_profiles SET source_order=0\",\n\t\"UPDATE coordinator_auth_account_profiles SET source_order=1\",\n\t`UPDATE coordinator_auth_session_receipts AS r SET source_order=1\n WHERE r.source='signin' AND r.attempt_id IS NULL AND EXISTS (\n SELECT 1 FROM coordinator_auth_account_profiles p WHERE p.coordinator_id=r.coordinator_id\n AND p.link_id=r.link_id AND p.source_session_id=r.session_id\n AND p.source_signed_in_at_ms=r.created_at_ms AND p.source_order=1)`,\n\t`INSERT INTO coordinator_auth_account_connection_orders (coordinator_id,last_order) SELECT NULL,0 WHERE NOT (${legacyReadySql})`,\n] as const;\nexport const ACCOUNT_CONNECTION_MIGRATION_STATEMENTS = [\n\t...PRIOR_ACCOUNT_CONNECTION_MIGRATION_STATEMENTS.slice(0, -1),\n\t...ACCOUNT_UNLINK_SCHEMA_STATEMENTS,\n\t\"DROP TRIGGER account_change_archive_receipt\",\n\tunlinkGuard,\n\t`INSERT INTO coordinator_auth_account_connection_orders (coordinator_id,last_order) SELECT NULL,0 WHERE NOT (${readySql})`,\n] as const;\n/** Only the exact prior account extension can take this atomic, no-rebuild delta. */\nexport const ACCOUNT_UNLINK_MIGRATION_STATEMENTS = [\n\t`INSERT INTO coordinator_auth_account_connection_orders (coordinator_id,last_order) SELECT NULL,0 WHERE NOT (${legacyReadySql})`,\n\t...ACCOUNT_UNLINK_SCHEMA_STATEMENTS,\n\t\"DROP TRIGGER account_change_archive_receipt\",\n\tunlinkGuard,\n\t`INSERT INTO coordinator_auth_account_connection_orders (coordinator_id,last_order) SELECT NULL,0 WHERE NOT (${readySql})`,\n] as const;\n/**\n * What brings a schema to the current account extension: nothing once it is current,\n * the full install on intact V2, the unlink delta on the exact prior extension. Any\n * other schema is unsupported and must not be written.\n */\ntype AccountSchemaPlan =\n\t| { kind: \"current\" }\n\t| { kind: \"install\"; statements: readonly string[] }\n\t| { kind: \"unsupported\" };\nfunction accountSchemaPlan(state: ConnectionSchemaState, prior: boolean): AccountSchemaPlan {\n\tif (state === \"ready\") return { kind: \"current\" };\n\tif (state === \"v2\")\n\t\treturn { kind: \"install\", statements: ACCOUNT_CONNECTION_MIGRATION_STATEMENTS };\n\tif (prior) return { kind: \"install\", statements: ACCOUNT_UNLINK_MIGRATION_STATEMENTS };\n\treturn { kind: \"unsupported\" };\n}\nexport async function applyAccountConnectionSchema(backend: AuthLinkBackend): Promise<void> {\n\tconst state = await readConnectionSchemaState(backend);\n\tconst prior = state === \"upgrade_required\" && (await hasPriorAccountSchema(backend));\n\tconst plan = accountSchemaPlan(state, prior);\n\tif (plan.kind === \"current\") throw new Error(\"account_connection_schema_already_installed\");\n\tif (plan.kind === \"unsupported\") throw new CoordinatorAuthSchemaUpgradeRequiredError();\n\tawait backend.batch(plan.statements.map((sql): AuthLinkStatement => ({ sql, values: [] })));\n\tif ((await readConnectionSchemaState(backend)) !== \"ready\")\n\t\tthrow new CoordinatorAuthSchemaUpgradeRequiredError();\n}\nexport async function hasPriorAccountSchema(\n\tbackend: Pick<AuthLinkBackend, \"first\">,\n): Promise<boolean> {\n\ttry {\n\t\treturn (\n\t\t\t(await backend.first<{ ready: number }>({ sql: legacyReadySql, values: [] }))?.ready === 1\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** A synchronous reader, for SQLite store startup inside one IMMEDIATE transaction. */\nexport interface SyncSchemaReader {\n\tfirst<T>(sql: string): T | undefined;\n\trun(sql: string): void;\n}\nexport function readConnectionSchemaStateSync(db: SyncSchemaReader): ConnectionSchemaState {\n\tconst p = db.first<{ present: number; v2: number }>(\n\t\t`SELECT (${CONNECTION_SCHEMA_PRESENCE_SQL}) AS present, ((${AUTH_V2_SCHEMA_READINESS_SQL})=10) AS v2`,\n\t);\n\tif (!p?.present) return p?.v2 === 1 ? \"v2\" : \"upgrade_required\";\n\ttry {\n\t\treturn db.first<{ ready: number }>(readySql)?.ready === 1 ? \"ready\" : \"upgrade_required\";\n\t} catch (error) {\n\t\tif (!isIncompleteConnectionSchemaError(error)) throw error;\n\t\treturn \"upgrade_required\";\n\t}\n}\nfunction hasPriorAccountSchemaSync(db: SyncSchemaReader): boolean {\n\ttry {\n\t\treturn db.first<{ ready: number }>(legacyReadySql)?.ready === 1;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Startup step of the SQLite coordinator: brings an intact V2 or exact prior extension\n * to the current account extension, and leaves a current one alone. Run it inside one\n * IMMEDIATE transaction; any failure throws and rolls the transaction back. An\n * unsupported or partial schema is left untouched, and authentication keeps reporting\n * that it needs an upgrade. Enabling account management stays a configuration choice.\n */\nexport function installAccountConnectionSchemaSync(\n\tdb: SyncSchemaReader,\n): AccountSchemaPlan[\"kind\"] {\n\tconst state = readConnectionSchemaStateSync(db);\n\tconst plan = accountSchemaPlan(\n\t\tstate,\n\t\tstate === \"upgrade_required\" && hasPriorAccountSchemaSync(db),\n\t);\n\tif (plan.kind !== \"install\") return plan.kind;\n\tfor (const sql of plan.statements) db.run(sql);\n\tif (readConnectionSchemaStateSync(db) !== \"ready\")\n\t\tthrow new Error(\"account_connection_schema_install_incomplete\");\n\treturn plan.kind;\n}\n","import {\n\tCoordinatorAuthSchemaUpgradeRequiredError,\n\treadConnectionSchemaState,\n} from \"./coordinator-account-connection-schema.js\";\nimport {\n\tCONNECTION_ALLOCATE_ORDER_SQL,\n\tCONNECTION_ASSERT_ONE_WRITE_SQL,\n} from \"./coordinator-account-connection-storage.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\n\nexport {\n\tCONNECTION_SESSION_SCHEMA_STATEMENTS,\n\tconnectionAdmissionSql,\n} from \"./coordinator-account-connection-schema.js\";\n\n/** Schema choice is database-derived, never a caller-selected exemption.\n * Readiness checks all extension definitions; legacy NULL browser orders cannot\n * admit new sessions after installation. Existing sessions retain their validity. */\nexport async function hasConnectionSessionSchema(\n\tbackend: Pick<AuthLinkBackend, \"first\" | \"readAuthSchemaState\">,\n): Promise<boolean> {\n\tconst state = await (backend.readAuthSchemaState?.() ?? readConnectionSchemaState(backend));\n\tif (state === \"upgrade_required\") throw new CoordinatorAuthSchemaUpgradeRequiredError();\n\treturn state === \"ready\";\n}\n\n/** All allocation, insertion and exact-row stamping share the caller's batch. */\nexport async function orderedBrowserStart(\n\tbackend: AuthLinkBackend,\n\tstatements: AuthLinkStatement[],\n\tcoordinator: string,\n\thash: string,\n): Promise<void> {\n\tif (!(await hasConnectionSessionSchema(backend))) {\n\t\tawait backend.batch(statements);\n\t\treturn;\n\t}\n\tawait backend.batch(orderedBrowserStartStatements(statements, coordinator, hash));\n}\n\n/**\n * The current-schema browser start: allocate the coordinator's next connection order,\n * run the start's own writes, then stamp the new transaction with that order.\n */\nexport function orderedBrowserStartStatements(\n\tstatements: AuthLinkStatement[],\n\tcoordinator: string,\n\thash: string,\n): AuthLinkStatement[] {\n\treturn [\n\t\t...connectionOrderAllocation(coordinator),\n\t\t...statements,\n\t\t...connectionOrderStamp(coordinator, hash),\n\t];\n}\n\nconst ORDERS = \"coordinator_auth_account_connection_orders\";\n\n/** Allocates the coordinator's next order, creating its order row on first use. */\nexport function connectionOrderAllocation(coordinator: string): AuthLinkStatement[] {\n\treturn [\n\t\t{\n\t\t\tsql: `INSERT INTO ${ORDERS} (coordinator_id,last_order) SELECT ?,0 WHERE NOT EXISTS (SELECT 1 FROM ${ORDERS} WHERE coordinator_id = ?)`,\n\t\t\tvalues: [coordinator, coordinator],\n\t\t},\n\t\t{ sql: CONNECTION_ALLOCATE_ORDER_SQL, values: [coordinator] },\n\t\t{ sql: CONNECTION_ASSERT_ONE_WRITE_SQL, values: [] },\n\t];\n}\n\n/** Stamps exactly one unordered transaction with the coordinator's latest order. */\nexport function connectionOrderStamp(coordinator: string, hash: string): AuthLinkStatement[] {\n\treturn [\n\t\t{\n\t\t\tsql: `UPDATE coordinator_auth_browser_transactions SET start_order = (SELECT last_order FROM ${ORDERS} WHERE coordinator_id = ?) WHERE coordinator_id = ? AND browser_transaction_hash = ? AND start_order IS NULL`,\n\t\t\tvalues: [coordinator, coordinator, hash],\n\t\t},\n\t\t{ sql: CONNECTION_ASSERT_ONE_WRITE_SQL, values: [] },\n\t];\n}\n\n/** Publish the browser floor and reject a continuation missing its prior pin.\n * The caller must already compose the successor CAS in this winning batch. */\nexport async function initialConnectionFloor(\n\tbackend: AuthLinkBackend,\n\tcoordinator: string,\n\tlink: string,\n): Promise<AuthLinkStatement[]> {\n\tif (!(await hasConnectionSessionSchema(backend))) return [];\n\treturn [\n\t\t{\n\t\t\tsql: `INSERT INTO coordinator_auth_account_connection_orders (coordinator_id,last_order) SELECT NULL,0 WHERE EXISTS (SELECT 1 FROM coordinator_auth_account_links l JOIN coordinator_auth_link_attempts a ON a.coordinator_id=l.coordinator_id AND a.attempt_id=l.attempt_id JOIN coordinator_auth_account_connection_history h ON h.coordinator_id = l.coordinator_id AND h.identity_id = l.identity_id WHERE l.coordinator_id = ? AND l.link_id = ? AND a.prior_link_id IS NULL)`,\n\t\t\tvalues: [coordinator, link],\n\t\t},\n\t\t{\n\t\t\tsql: `UPDATE coordinator_auth_account_links SET signin_floor = coalesce((SELECT last_order FROM coordinator_auth_account_connection_orders WHERE coordinator_id = ?),0) WHERE coordinator_id = ? AND link_id = ?`,\n\t\t\tvalues: [coordinator, coordinator, link],\n\t\t},\n\t];\n}\n\n/** Source aliases are fixed internal SQL, not request input. Refresh payloads\n * become readable only after their own immutable completed management receipt. */\nexport function connectionProfileColumns(signin: \"p\" | \"m\"): string {\n\t// Order one is the migration's already-verified legacy display snapshot.\n\t// Its expired receipt may have been legitimately purged before installation.\n\tconst validSignin = `(${signin}.source_order = 1 OR EXISTS (SELECT 1 FROM coordinator_auth_session_receipts r WHERE r.coordinator_id = ${signin}.coordinator_id AND r.link_id = ${signin}.link_id AND r.session_id = ${signin}.source_session_id AND r.source = 'signin' AND r.attempt_id IS NULL AND r.created_at_ms = ${signin}.source_signed_in_at_ms AND (${signin}.source_order IS NULL OR r.source_order = ${signin}.source_order)))`;\n\tconst validBirth = `(b.source_change_attempt_id IS NULL OR EXISTS (SELECT 1 FROM coordinator_account_change_attempts x WHERE x.coordinator_id = b.coordinator_id AND x.attempt_id = b.source_change_attempt_id AND x.state = 'completed' AND x.intent = 'refresh' AND x.target_link_id = l.link_id AND x.identity_id = l.identity_id AND x.issuer = l.issuer AND x.target_subject = l.subject AND x.browser_order = b.source_order))`;\n\tconst preferSignin = `${validSignin} AND (NOT ${validBirth} OR coalesce(${signin}.source_order,1) > coalesce(b.source_order,0))`;\n\treturn [\"display_name\", \"email\", \"email_verified\", \"picture_url\"]\n\t\t.map(\n\t\t\t(field) =>\n\t\t\t\t`CASE WHEN ${preferSignin} THEN ${signin}.${field} WHEN ${validBirth} THEN b.${field} END AS ${field}`,\n\t\t)\n\t\t.join(\",\\n\");\n}\n","import type { CoordinatorAuthLinkConfig } from \"./coordinator-auth-link-contract.js\";\nimport type { CoordinatorAuthSession } from \"./coordinator-auth-session-contract.js\";\nimport type { CoordinatorOidcProfile } from \"./coordinator-oidc.js\";\n\nexport const AUTH_ACCOUNT_PROFILE_WRITE_WINDOW_MS = 120000;\nexport interface CoordinatorAuthAccountProfileInput {\n\tcredentialHash: string;\n\tprofile: unknown;\n}\nexport type CoordinatorAuthAccountProfileWriteResult =\n\t| { kind: \"recorded\" }\n\t| { kind: \"not_recorded\" }\n\t| { kind: \"rejected\"; error: \"invalid_input\" | \"auth_config_changed\" };\nexport interface CoordinatorAuthSessionAccount {\n\tsession: CoordinatorAuthSession;\n\tprofile: CoordinatorOidcProfile;\n}\nexport type CoordinatorAuthAccountProfileClearResult =\n\t| { kind: \"cleared\"; deletedCount: number }\n\t| { kind: \"rejected\"; error: \"invalid_input\" };\n/** Display only. Callers must verify OIDC before writing and configured-admin authority\n * before clearing. These operations never issue sessions or grant authority.\n */\nexport interface CoordinatorAuthAccountProfileStore {\n\trecordAuthAccountProfile(\n\t\tinput: CoordinatorAuthAccountProfileInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthAccountProfileWriteResult>;\n\treadAuthSessionAccount(\n\t\tcredentialHash: string,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthSessionAccount | null>;\n\tclearRevokedAuthAccountProfile(\n\t\tinput: { linkId: string },\n\t\tscope: { coordinatorId: string },\n\t): Promise<CoordinatorAuthAccountProfileClearResult>;\n}\n\n// Empty metadata table only: no foreign keys, backfill, or startup writes.\nexport const AUTH_ACCOUNT_PROFILE_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS coordinator_auth_account_profiles (\n coordinator_id TEXT NOT NULL,\n link_id TEXT NOT NULL,\n display_name TEXT CHECK (display_name IS NULL OR (typeof(display_name) = 'text' AND length(display_name) BETWEEN 1 AND 256)),\n email TEXT CHECK (email IS NULL OR (typeof(email) = 'text' AND length(email) BETWEEN 1 AND 320)),\n email_verified INTEGER CHECK (email_verified IS NULL OR (typeof(email_verified) = 'integer' AND email_verified IN (0,1) AND email IS NOT NULL)),\n picture_url TEXT CHECK (picture_url IS NULL OR (typeof(picture_url) = 'text' AND length(picture_url) BETWEEN 1 AND 2048 AND substr(picture_url, 1, 8) = 'https://')),\n source_session_id TEXT NOT NULL,\n source_signed_in_at_ms INTEGER NOT NULL CHECK (typeof(source_signed_in_at_ms) = 'integer' AND source_signed_in_at_ms BETWEEN 0 AND 9007199225940991),\n PRIMARY KEY (coordinator_id, link_id)\n);`;\n","import { hasConnectionSessionSchema } from \"./coordinator-account-connection-session.js\";\nimport {\n\tAUTH_DEVICE_CLAIM_CURRENT_SUBJECT_COMPATIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_INPUT_SQL,\n\tAUTH_DEVICE_CLAIM_LEGACY_COMPATIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_REQUESTER_ATTESTATION_COMPATIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_REQUESTER_INVITE_COMPATIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_REQUESTER_LINK_COMPATIBLE_SQL,\n\tcaptureDeviceClaimEligibility,\n} from \"./coordinator-auth-device-claim-eligibility.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport type {\n\tCoordinatorAuthLinkConfig,\n\tCoordinatorAuthLinkSigner,\n} from \"./coordinator-auth-link-contract.js\";\nimport { authClaimGenesisSql } from \"./coordinator-auth-link-provenance.js\";\n\n/** Additive definitions installed by the explicit account-schema migration. */\nexport { CONNECTION_LINK_SCHEMA_STATEMENTS } from \"./coordinator-account-connection-schema.js\";\n\n/** p is the captured requester, d its original immutable claim. Head lookup is\n * one indexed row; the archived genesis is addressed by claim_id, not recursion. */\nexport const CONNECTION_RELINK_ELIGIBLE_SQL = `(EXISTS (SELECT 1 FROM coordinator_auth_device_claims d\n WHERE (d.coordinator_id = p.coordinator_id AND d.identity_id = p.identity_id AND d.group_id = p.group_id)\n AND (d.device_id = p.device_id AND d.public_key = p.public_key AND d.fingerprint = p.fingerprint)\n AND (d.key_id = p.key_id AND d.issuer = p.issuer) AND ${authClaimGenesisSql(\"d\")})\n AND EXISTS (SELECT 1 FROM enrolled_devices e JOIN groups g ON g.group_id = e.group_id WHERE (e.group_id = p.group_id AND e.device_id = p.device_id AND e.public_key = p.public_key AND e.fingerprint = p.fingerprint) AND (e.enabled = 1 AND g.archived_at IS NULL AND (e.identity_id IS NULL OR e.identity_id = p.identity_id)))\n AND NOT EXISTS (SELECT 1 FROM coordinator_device_revocations r WHERE (r.subject_kind = 'device_id' AND r.subject_value = p.device_id) OR (r.subject_kind = 'ed25519_key' AND r.subject_value = p.key_id)))\n AND (NOT EXISTS (SELECT 1 FROM coordinator_auth_account_links l WHERE l.coordinator_id = p.coordinator_id AND l.identity_id = p.identity_id)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id = p.coordinator_id AND h.identity_id = p.identity_id AND h.revoked_at_ms IS NOT NULL)\n AND EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id = p.coordinator_id AND h.identity_id = p.identity_id AND h.successor_link_id IS NULL))\n AND ((${AUTH_DEVICE_CLAIM_CURRENT_SUBJECT_COMPATIBLE_SQL}) AND (${AUTH_DEVICE_CLAIM_REQUESTER_ATTESTATION_COMPATIBLE_SQL}))\n AND ((${AUTH_DEVICE_CLAIM_REQUESTER_INVITE_COMPATIBLE_SQL}) AND (${AUTH_DEVICE_CLAIM_REQUESTER_LINK_COMPATIBLE_SQL}) AND (${AUTH_DEVICE_CLAIM_LEGACY_COMPATIBLE_SQL}))`;\n\n/** A renewed same-Identity review is distinct from a contradictory assignment. */\nexport const CONNECTION_REQUESTER_ATTESTATION_IDENTITY_SQL = `NOT EXISTS (SELECT 1 FROM coordinator_auth_controller_attestations a\n WHERE a.coordinator_id=p.coordinator_id AND (a.device_id=p.device_id OR EXISTS (SELECT 1 FROM json_each(p.same_keys) k WHERE k.value=a.public_key)) AND a.identity_id<>p.identity_id)`;\nconst otherIdentityClaimSql = (\n\textra: string,\n) => `NOT EXISTS (SELECT 1 FROM coordinator_auth_device_claims d\n WHERE d.coordinator_id=p.coordinator_id AND (d.device_id=p.device_id OR d.key_id=p.key_id) AND d.identity_id<>p.identity_id${extra})`;\nexport const CONNECTION_REQUESTER_IDENTITY_SQL = `${CONNECTION_REQUESTER_ATTESTATION_IDENTITY_SQL}\n AND ${otherIdentityClaimSql(\"\")}`;\n/**\n * With an ownership binding, this device's own claim under its previous\n * Identity is superseded once that Identity has no active link (ADR 0005 S8).\n */\nexport const CONNECTION_REQUESTER_ACTIVE_OTHER_CLAIM_SQL = otherIdentityClaimSql(`\n AND EXISTS (SELECT 1 FROM coordinator_auth_account_links l WHERE l.coordinator_id=d.coordinator_id\n AND l.identity_id=d.identity_id AND l.revoked_at_ms IS NULL)`);\n/** Additional contradictions only: the outer writer must independently require\n * its exact live attestation, current enrollment snapshot and revocation checks. */\nexport async function connectionRequesterGuard(\n\tbackend: AuthLinkBackend,\n\tidentityId: string,\n\tsigner: CoordinatorAuthLinkSigner,\n\tconfig: CoordinatorAuthLinkConfig,\n\tnow: number,\n): Promise<AuthLinkStatement> {\n\tconst p = await captureDeviceClaimEligibility(backend, { identityId, signer }, config, now);\n\tif (!p) return { sql: \"0 = 1\", values: [] };\n\treturn {\n\t\tsql: `EXISTS (${AUTH_DEVICE_CLAIM_INPUT_SQL} SELECT 1 FROM claim_input p WHERE (${AUTH_DEVICE_CLAIM_CURRENT_SUBJECT_COMPATIBLE_SQL}) AND (${CONNECTION_REQUESTER_IDENTITY_SQL}) AND (${AUTH_DEVICE_CLAIM_REQUESTER_INVITE_COMPATIBLE_SQL}) AND (${AUTH_DEVICE_CLAIM_REQUESTER_LINK_COMPATIBLE_SQL}) AND (${AUTH_DEVICE_CLAIM_LEGACY_COMPATIBLE_SQL}))`,\n\t\tvalues: p.values,\n\t};\n}\n\n/** t is the exact winning attempt; source authority is checked independently. */\nexport function connectionFinalizeGuard(t: \"coordinator_auth_link_attempts\"): string {\n\treturn `NOT EXISTS (SELECT 1 FROM coordinator_auth_account_links l WHERE l.coordinator_id = ${t}.coordinator_id AND l.identity_id = ${t}.identity_id)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id = ${t}.coordinator_id AND h.identity_id = ${t}.identity_id AND h.revoked_at_ms IS NOT NULL)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id = ${t}.coordinator_id AND h.issuer = ${t}.issuer AND h.subject = ${t}.account_subject AND h.identity_id <> ${t}.identity_id)\n AND ((${t}.prior_link_id IS NULL AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id = ${t}.coordinator_id AND h.identity_id = ${t}.identity_id)) OR EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id = ${t}.coordinator_id AND h.identity_id = ${t}.identity_id AND h.link_id = ${t}.prior_link_id AND h.successor_link_id IS NULL))`;\n}\n\n/** Pin the server's head in the same transaction as an attested/first creation.\n * The INSERT must be fresh; exact retries are handled by the existing reader. */\nexport async function createPinnedConnection(\n\tbackend: AuthLinkBackend,\n\tstatement: AuthLinkStatement,\n\tpin: { coordinator: string; attempt: string; identity: string; now: number },\n): Promise<number> {\n\tif (!(await hasConnectionSessionSchema(backend))) return backend.run(statement);\n\tconst head = await backend.first<{ link_id: string }>({\n\t\tsql: \"SELECT link_id FROM coordinator_auth_account_connection_history WHERE coordinator_id = ? AND identity_id = ? AND successor_link_id IS NULL\",\n\t\tvalues: [pin.coordinator, pin.identity],\n\t});\n\tawait backend.batch([\n\t\tstatement,\n\t\t{\n\t\t\tsql: `UPDATE coordinator_auth_link_attempts AS t SET prior_link_id = ? WHERE changes() = 1 AND t.coordinator_id = ? AND t.attempt_id = ? AND t.state = 'pending' AND t.created_at_ms = ?\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_links l WHERE l.coordinator_id = t.coordinator_id AND l.identity_id = t.identity_id)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id = t.coordinator_id AND h.identity_id = t.identity_id AND h.revoked_at_ms IS NOT NULL)\n AND ((? IS NULL AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id = t.coordinator_id AND h.identity_id = t.identity_id)) OR EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id = t.coordinator_id AND h.identity_id = t.identity_id AND h.link_id = ? AND h.successor_link_id IS NULL))`,\n\t\t\tvalues: [\n\t\t\t\thead?.link_id ?? null,\n\t\t\t\tpin.coordinator,\n\t\t\t\tpin.attempt,\n\t\t\t\tpin.now,\n\t\t\t\thead?.link_id ?? null,\n\t\t\t\thead?.link_id ?? null,\n\t\t\t],\n\t\t},\n\t\t{\n\t\t\tsql: \"INSERT INTO coordinator_auth_account_connection_orders (coordinator_id,last_order) SELECT NULL,0 WHERE changes() <> 1\",\n\t\t\tvalues: [],\n\t\t},\n\t]);\n\treturn 1;\n}\n\n/** Append after current/audit publication, before profile/session exposure. */\nexport function connectionSuccessorStatements(\n\tcoordinator: string,\n\tattempt: string,\n\tlink: string,\n): AuthLinkStatement[] {\n\tconst pins = [coordinator, attempt, link];\n\treturn [\n\t\t{\n\t\t\tsql: `UPDATE coordinator_auth_account_connection_history SET successor_link_id = ? WHERE successor_link_id IS NULL AND coordinator_id = ? AND link_id = (SELECT prior_link_id FROM coordinator_auth_link_attempts WHERE coordinator_id = ? AND attempt_id = ? AND link_id = ? AND state = 'finalized')`,\n\t\t\tvalues: [link, coordinator, ...pins],\n\t\t},\n\t\t{\n\t\t\tsql: `INSERT INTO coordinator_auth_account_connection_orders (coordinator_id,last_order) SELECT NULL,0 WHERE changes() <> 1 AND EXISTS (SELECT 1 FROM coordinator_auth_link_attempts WHERE coordinator_id = ? AND attempt_id = ? AND link_id = ? AND state = 'finalized' AND prior_link_id IS NOT NULL)`,\n\t\t\tvalues: pins,\n\t\t},\n\t];\n}\n","/**\n * Authority contract for coordinator account links.\n *\n * Every link attempt, account link, and link audit row names its authority source:\n * - `controller_attestation`: an admin-reviewed attestation for the exact enrolled key.\n * - `device_claim`: an eligible enrolled-key claim while an attempt is pending.\n * Link and audit rows reference proof committed after Google verification and\n * device finalization. It is never an operator review.\n *\n * Rows store the kind explicitly and reference only the record that matches it.\n * Readers must fail closed on any row whose references disagree with its kind.\n */\n\nimport { isAuthControllerId as isReference } from \"./coordinator-auth-controller.js\";\n\nexport const AUTH_LINK_AUTHORITY_KINDS = [\"controller_attestation\", \"device_claim\"] as const;\nexport type CoordinatorAuthLinkAuthorityKind = (typeof AUTH_LINK_AUTHORITY_KINDS)[number];\n\nexport type CoordinatorAuthLinkAttemptAuthority =\n\t| {\n\t\t\tkind: \"controller_attestation\";\n\t\t\tcontrollerAttestationId: string;\n\t\t\tcontrollerReviewReceiptId: string;\n\t }\n\t| { kind: \"device_claim\" };\n\nexport type CoordinatorAuthLinkRecordAuthority =\n\t| { kind: \"controller_attestation\"; controllerAttestationId: string }\n\t| { kind: \"device_claim\"; deviceClaimId: string };\n\n/** Link-attempt columns. A pending device claim has no committed claim record yet. */\nexport interface AuthLinkAttemptAuthorityRow {\n\tauthority_kind: unknown;\n\tcontroller_attestation_id: unknown;\n\tcontroller_review_receipt_id: unknown;\n\tcontroller_revision: unknown;\n}\n\n/** Account-link and audit columns. */\nexport interface AuthLinkRecordAuthorityRow {\n\tauthority_kind: unknown;\n\tcontroller_attestation_id: unknown;\n\tdevice_claim_id: unknown;\n}\n\n/** Returns null for a corrupt row; callers must treat that as no authority. */\nexport function readAuthLinkAttemptAuthority(\n\trow: AuthLinkAttemptAuthorityRow,\n): CoordinatorAuthLinkAttemptAuthority | null {\n\tif (row.authority_kind === \"device_claim\") {\n\t\tconst unreferenced =\n\t\t\trow.controller_attestation_id === null &&\n\t\t\trow.controller_review_receipt_id === null &&\n\t\t\trow.controller_revision === null;\n\t\treturn unreferenced ? { kind: \"device_claim\" } : null;\n\t}\n\tif (row.authority_kind !== \"controller_attestation\") return null;\n\tif (\n\t\t!isReference(row.controller_attestation_id) ||\n\t\t!isReference(row.controller_review_receipt_id) ||\n\t\trow.controller_revision !== 1\n\t)\n\t\treturn null;\n\treturn {\n\t\tkind: \"controller_attestation\",\n\t\tcontrollerAttestationId: row.controller_attestation_id,\n\t\tcontrollerReviewReceiptId: row.controller_review_receipt_id,\n\t};\n}\n\n/** Returns null for a corrupt row; callers must treat that as no authority. */\nexport function readAuthLinkRecordAuthority(\n\trow: AuthLinkRecordAuthorityRow,\n): CoordinatorAuthLinkRecordAuthority | null {\n\tif (row.authority_kind === \"device_claim\") {\n\t\tif (row.controller_attestation_id !== null || !isReference(row.device_claim_id)) return null;\n\t\treturn { kind: \"device_claim\", deviceClaimId: row.device_claim_id };\n\t}\n\tif (row.authority_kind !== \"controller_attestation\") return null;\n\tif (!isReference(row.controller_attestation_id) || row.device_claim_id !== null) return null;\n\treturn { kind: \"controller_attestation\", controllerAttestationId: row.controller_attestation_id };\n}\n\n/**\n * Operator-only consumers accept no other source kind. This classifies a stored\n * reference, not caller permission. In-flight links revalidate their source;\n * completed-link consumers apply historical-provenance and active-link checks.\n */\nexport function isOperatorReviewedAuthority(\n\tauthority: CoordinatorAuthLinkRecordAuthority | null,\n): boolean {\n\treturn authority?.kind === \"controller_attestation\";\n}\n\ninterface AccountLinkStatusSubject {\n\tversion: 2;\n\tcoordinatorId: string;\n\tgroupId: string;\n\tdeviceId: string;\n\tfingerprint: string;\n}\ntype AccountMetadata = { email?: string; displayName?: string; pictureUrl?: string };\n\n/**\n * Signed-device account-link status for the requested Identity.\n * `unlinked` is eligibility only; for `device_claim` nothing is verified or\n * reserved until the same operation's device finalization commits.\n * `account` is null whenever the link Identity differs from the requested one, or\n * the requester holds no claim or attestation of its own (ADR 0005 Section 8).\n */\nexport type CoordinatorAccountLinkStatusV2 = AccountLinkStatusSubject &\n\t(\n\t\t| {\n\t\t\t\tstate: \"review_required\" | \"conflict\";\n\t\t\t\tidentityId: null;\n\t\t\t\tauthority: null;\n\t\t\t\taccount: null;\n\t\t }\n\t\t| {\n\t\t\t\tstate: \"unlinked\";\n\t\t\t\tidentityId: string;\n\t\t\t\tauthority: CoordinatorAuthLinkAuthorityKind;\n\t\t\t\taccount: null;\n\t\t }\n\t\t| {\n\t\t\t\tstate: \"linked\";\n\t\t\t\tidentityId: string;\n\t\t\t\tauthority: CoordinatorAuthLinkAuthorityKind;\n\t\t\t\taccount: AccountMetadata | null;\n\t\t }\n\t\t| {\n\t\t\t\tstate: \"revoked\";\n\t\t\t\tidentityId: string;\n\t\t\t\tauthority: CoordinatorAuthLinkAuthorityKind;\n\t\t\t\taccount: null;\n\t\t }\n\t);\n","import { CONNECTION_RELINK_ELIGIBLE_SQL } from \"./coordinator-account-connection-link.js\";\nimport { hasConnectionSessionSchema } from \"./coordinator-account-connection-session.js\";\nimport {\n\tAUTH_DEVICE_CLAIM_ELIGIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_INPUT_SQL,\n\tcaptureDeviceClaimEligibility,\n} from \"./coordinator-auth-device-claim-eligibility.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport type { AuthLinkAttemptAuthorityRow } from \"./coordinator-auth-link-authority.js\";\nimport { readAuthLinkAttemptAuthority } from \"./coordinator-auth-link-authority.js\";\nimport type { CoordinatorAuthLinkConfig } from \"./coordinator-auth-link-contract.js\";\nimport {\n\tauthDeviceClaimProvenanceSql,\n\tCONNECTION_BIRTHS_SQL,\n} from \"./coordinator-auth-link-provenance.js\";\nimport { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\n\ninterface SourceRow extends AuthLinkAttemptAuthorityRow {\n\tprior_link_id?: string | null;\n\tidentity_id: string;\n\tgroup_id: string;\n\tdevice_id: string;\n\tpublic_key: string;\n\tfingerprint: string;\n\truntime_verifier_hash: string;\n\tbrowser_start_hash: string | null;\n\tloopback_redirect: string;\n\tstate: string;\n\tcompletion_secret_hash: string | null;\n}\n/** Private predicate preparation, never a browser status or authorization result. */\nexport async function captureAuthLinkBrowserSource(\n\tbackend: Pick<AuthLinkBackend, \"first\">,\n\ti: { binderHash: string; stateHash?: string; attemptId?: string },\n\tc: CoordinatorAuthLinkConfig & { redirectUri: string },\n\tnow: number,\n): Promise<AuthLinkStatement> {\n\tconst row = await backend.first<{ attempt_id: string | null }>({\n\t\tsql: `SELECT attempt_id FROM coordinator_auth_browser_transactions b WHERE b.coordinator_id = ? AND b.issuer = ? AND b.auth_config_revision = ? AND b.redirect_uri = ? AND b.binder_hash = ?\n AND (? IS NULL OR b.state_hash = ?) AND (? IS NULL OR b.attempt_id = ?) AND b.purpose = 'link'`,\n\t\tvalues: [\n\t\t\tc.coordinatorId,\n\t\t\tc.issuer,\n\t\t\tc.revision,\n\t\t\tc.redirectUri,\n\t\t\ti.binderHash,\n\t\t\ti.stateHash ?? null,\n\t\t\ti.stateHash ?? null,\n\t\t\ti.attemptId ?? null,\n\t\t\ti.attemptId ?? null,\n\t\t],\n\t});\n\tif (!row?.attempt_id) return { sql: \"0 = 1\", values: [] };\n\treturn captureAuthLinkSource(backend, row.attempt_id, c, now, \"a\");\n}\n\n/** Fresh capture for one operation; the winning statement must include its SQL. */\nexport async function captureAuthLinkSource(\n\tbackend: Pick<AuthLinkBackend, \"first\">,\n\tattemptId: string,\n\tconfig: CoordinatorAuthLinkConfig,\n\tnow: number,\n\talias: \"a\" | \"coordinator_auth_link_attempts\" = \"coordinator_auth_link_attempts\",\n\toptions: { currentDevice?: boolean } = {},\n): Promise<AuthLinkStatement> {\n\tconst row = await backend.first<SourceRow>({\n\t\tsql: \"SELECT * FROM coordinator_auth_link_attempts WHERE coordinator_id = ? AND attempt_id = ?\",\n\t\tvalues: [config.coordinatorId, attemptId],\n\t});\n\tconst authority = row && readAuthLinkAttemptAuthority(row);\n\tif (!row || !authority) return { sql: \"0 = 1\", values: [] };\n\tif (authority.kind === \"controller_attestation\")\n\t\treturn { sql: `${alias}.authority_kind = 'controller_attestation'`, values: [] };\n\tif ([\"finalized\", \"session_redeemed\"].includes(row.state)) {\n\t\tconst connections = await hasConnectionSessionSchema(backend);\n\t\tconst keyId = await ed25519KeyIdForRevocation(row.public_key);\n\t\tif (!keyId || row.browser_start_hash === null || row.completion_secret_hash === null)\n\t\t\treturn { sql: \"0 = 1\", values: [] };\n\t\treturn {\n\t\t\tsql: `(${alias}.authority_kind = 'device_claim'\n AND ${alias}.controller_attestation_id IS NULL AND ${alias}.controller_review_receipt_id IS NULL AND ${alias}.controller_revision IS NULL\n AND ${alias}.state IN ('finalized','session_redeemed') AND ${alias}.browser_start_hash = ?\n AND ${alias}.runtime_verifier_hash = ? AND ${alias}.completion_secret_hash = ? AND ${alias}.loopback_redirect = ?\n AND ${authDeviceClaimReceiptSql(alias, connections)}${options.currentDevice ? ` AND ${currentDeviceSql(alias)}` : \"\"})`,\n\t\t\tvalues: [\n\t\t\t\trow.browser_start_hash,\n\t\t\t\trow.runtime_verifier_hash,\n\t\t\t\trow.completion_secret_hash,\n\t\t\t\trow.loopback_redirect,\n\t\t\t\tkeyId,\n\t\t\t\t...(options.currentDevice ? [keyId] : []),\n\t\t\t],\n\t\t};\n\t}\n\tconst captured = await captureDeviceClaimEligibility(\n\t\tbackend,\n\t\t{\n\t\t\tattemptId,\n\t\t\tidentityId: row.identity_id,\n\t\t\tsigner: {\n\t\t\t\tgroupId: row.group_id,\n\t\t\t\tdeviceId: row.device_id,\n\t\t\t\tpublicKey: row.public_key,\n\t\t\t\tfingerprint: row.fingerprint,\n\t\t\t},\n\t\t},\n\t\tconfig,\n\t\tnow,\n\t);\n\tif (!captured || row.browser_start_hash === null) return { sql: \"0 = 1\", values: [] };\n\tif (row.prior_link_id)\n\t\treturn {\n\t\t\tsql: `((${alias}.authority_kind = 'device_claim' AND ${alias}.controller_attestation_id IS NULL AND ${alias}.controller_review_receipt_id IS NULL AND ${alias}.controller_revision IS NULL) AND (${alias}.link_id IS NULL AND ${alias}.prior_link_id = ?)\n AND EXISTS (${AUTH_DEVICE_CLAIM_INPUT_SQL}, connection_eligible AS MATERIALIZED (SELECT p.* FROM claim_input p WHERE ${CONNECTION_RELINK_ELIGIBLE_SQL})\n SELECT 1 FROM connection_eligible p WHERE (p.coordinator_id=${alias}.coordinator_id AND p.attempt_id=${alias}.attempt_id AND p.identity_id=${alias}.identity_id)\n AND (p.group_id=${alias}.group_id AND p.device_id=${alias}.device_id AND p.public_key=${alias}.public_key AND p.fingerprint=${alias}.fingerprint) AND (p.issuer=${alias}.issuer AND p.revision=${alias}.auth_config_revision)\n AND EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id=p.coordinator_id AND h.identity_id=p.identity_id AND h.link_id=${alias}.prior_link_id AND h.successor_link_id IS NULL)))`,\n\t\t\tvalues: [row.prior_link_id, ...captured.values],\n\t\t};\n\t// Separate the full predicate from the correlated browser match to stay below\n\t// native D1's expression-depth limit, without moving authority outside SQL.\n\treturn {\n\t\tsql: `(${alias}.authority_kind = 'device_claim'\n AND ${alias}.controller_attestation_id IS NULL AND ${alias}.controller_review_receipt_id IS NULL\n AND ${alias}.controller_revision IS NULL AND ${alias}.link_id IS NULL\n AND ${alias}.runtime_verifier_hash = ? AND ${alias}.browser_start_hash = ? AND ${alias}.loopback_redirect = ?\n AND EXISTS (${AUTH_DEVICE_CLAIM_INPUT_SQL}, claim_eligible AS MATERIALIZED (\n SELECT p.* FROM claim_input p WHERE ${AUTH_DEVICE_CLAIM_ELIGIBLE_SQL})\n SELECT 1 FROM claim_eligible p\n WHERE ${alias}.coordinator_id = p.coordinator_id AND ${alias}.attempt_id = p.attempt_id\n AND ${alias}.identity_id = p.identity_id AND ${alias}.group_id = p.group_id\n AND ${alias}.device_id = p.device_id AND ${alias}.public_key = p.public_key AND ${alias}.fingerprint = p.fingerprint\n AND ${alias}.issuer = p.issuer AND ${alias}.auth_config_revision = p.revision))`,\n\t\tvalues: [\n\t\t\trow.runtime_verifier_hash,\n\t\t\trow.browser_start_hash,\n\t\t\trow.loopback_redirect,\n\t\t\t...captured.values,\n\t\t],\n\t};\n}\n\nfunction currentDeviceSql(t: string): string {\n\treturn `EXISTS (SELECT 1 FROM enrolled_devices e JOIN groups g ON g.group_id = e.group_id\n WHERE e.group_id = ${t}.group_id AND e.device_id = ${t}.device_id AND e.public_key = ${t}.public_key\n AND e.fingerprint = ${t}.fingerprint AND e.enabled = 1 AND g.archived_at IS NULL\n AND (e.identity_id IS NULL OR e.identity_id = ${t}.identity_id))\n AND NOT EXISTS (SELECT 1 FROM coordinator_device_revocations r\n WHERE (r.subject_kind = 'device_id' AND r.subject_value = ${t}.device_id)\n OR (r.subject_kind = 'ed25519_key' AND r.subject_value = ?))`;\n}\n\n/** Historical committed provenance, not first-binding eligibility or operator authority.\n * The caller binds the canonical key ID derived from the attempt's exact public key.\n */\nfunction authDeviceClaimReceiptSql(t: string, connections: boolean): string {\n\t// Separate the indexed receipt match from its unchanged provenance expression\n\t// so the browser's enclosing predicate stays below native D1 depth 100.\n\treturn `EXISTS (WITH receipt_birth AS MATERIALIZED (\n SELECT cl.* FROM ${connections ? `(${CONNECTION_BIRTHS_SQL})` : \"coordinator_auth_account_links\"} cl\n WHERE cl.coordinator_id = ${t}.coordinator_id AND cl.link_id = ${t}.link_id AND cl.attempt_id = ${t}.attempt_id\n AND cl.revoked_at_ms IS NULL)\n SELECT 1 FROM receipt_birth cl WHERE ${authDeviceClaimProvenanceSql({ link: \"cl\", canonicalKeyId: \"?\", connections })})`;\n}\n","import {\n\tAUTH_SCHEMA_UPGRADE_MESSAGE,\n\tAUTH_SCHEMA_UPGRADE_REQUIRED,\n\tAUTH_V2_SCHEMA_READINESS_SQL,\n\tCoordinatorAuthSchemaUpgradeRequiredError,\n\treadConnectionSchemaState,\n} from \"./coordinator-account-connection-schema.js\";\n\nexport {\n\tAUTH_SCHEMA_UPGRADE_MESSAGE,\n\tAUTH_SCHEMA_UPGRADE_REQUIRED,\n\tCoordinatorAuthSchemaUpgradeRequiredError,\n} from \"./coordinator-account-connection-schema.js\";\n\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport {\n\tcaptureAuthLinkBrowserSource,\n\tcaptureAuthLinkSource,\n} from \"./coordinator-auth-link-source.js\";\n\n// Inspect five authority columns, four proof definitions and the display staging table.\n// No writes or I/O cache; unknown proof variants fail closed.\nexport const AUTH_SCHEMA_READY_COUNT = 10;\nexport const AUTH_SCHEMA_READINESS_SQL = AUTH_V2_SCHEMA_READINESS_SQL;\n\nexport interface CoordinatorAuthSchemaStore {\n\tassertAuthSchemaReady(): Promise<void>;\n}\n\nexport async function assertCoordinatorAuthSchema(\n\tbackend: Pick<AuthLinkBackend, \"first\">,\n\toptions: { connections?: boolean } = {},\n): Promise<void> {\n\tconst state = await readConnectionSchemaState(backend);\n\tif (state === \"upgrade_required\" || (options.connections && state !== \"ready\"))\n\t\tthrow new CoordinatorAuthSchemaUpgradeRequiredError();\n}\n\n/** The wrapper offers a read batch only when the wrapped backend has one. */\nfunction checkedReadBatch(\n\tbackend: AuthLinkBackend,\n\toptions: { connections?: boolean },\n): Pick<AuthLinkBackend, \"readBatch\"> {\n\tconst readBatch = backend.readBatch?.bind(backend);\n\tif (!readBatch) return {};\n\treturn {\n\t\treadBatch: async <T>(statements: AuthLinkStatement[]) => {\n\t\t\tawait assertCoordinatorAuthSchema(backend, options);\n\t\t\treturn readBatch<T>(statements);\n\t\t},\n\t};\n}\n\n/** Protect every optional-auth SQL entry, including trusted callers outside HTTP. */\nexport function withCoordinatorAuthSchema(\n\tbackend: AuthLinkBackend,\n\toptions: { connections?: boolean } = {},\n): AuthLinkBackend {\n\treturn {\n\t\tprepareAuthLinkSource: (...args) => captureAuthLinkSource(backend, ...args),\n\t\tprepareAuthLinkBrowserSource: (...args) => captureAuthLinkBrowserSource(backend, ...args),\n\t\treadAuthSchemaState: () => readConnectionSchemaState(backend),\n\t\tfirst: async <T>(statement: AuthLinkStatement) => {\n\t\t\tawait assertCoordinatorAuthSchema(backend, options);\n\t\t\treturn backend.first<T>(statement);\n\t\t},\n\t\tall: async <T>(statement: AuthLinkStatement) => {\n\t\t\tawait assertCoordinatorAuthSchema(backend, options);\n\t\t\tif (!backend.all) throw new Error(\"ownership_evidence_reader_unavailable\");\n\t\t\treturn backend.all<T>(statement);\n\t\t},\n\t\t...checkedReadBatch(backend, options),\n\t\trun: async (statement) => {\n\t\t\tawait assertCoordinatorAuthSchema(backend, options);\n\t\t\treturn backend.run(statement);\n\t\t},\n\t\tbatch: async (statements) => {\n\t\t\tawait assertCoordinatorAuthSchema(backend, options);\n\t\t\treturn backend.batch(statements);\n\t\t},\n\t};\n}\n\nexport function authPersistenceError(error: unknown, fallback: string): Error {\n\tif (String(error).includes(\"no such table: coordinator_auth_link_profiles\"))\n\t\treturn new CoordinatorAuthSchemaUpgradeRequiredError();\n\treturn error instanceof CoordinatorAuthSchemaUpgradeRequiredError ? error : new Error(fallback);\n}\n\nexport async function assertConfiguredAuthSchema(\n\tstore: Partial<CoordinatorAuthSchemaStore>,\n): Promise<void> {\n\tif (typeof store.assertAuthSchemaReady !== \"function\")\n\t\tthrow new Error(\"auth_schema_readiness_unavailable\");\n\tawait store.assertAuthSchemaReady();\n}\n\nexport function authSchemaUpgradeResponse(): Response {\n\treturn Response.json(\n\t\t{ error: AUTH_SCHEMA_UPGRADE_REQUIRED, message: AUTH_SCHEMA_UPGRADE_MESSAGE },\n\t\t{\n\t\t\tstatus: 503,\n\t\t\theaders: {\n\t\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\t\"X-Codemem-Auth-Error\": AUTH_SCHEMA_UPGRADE_REQUIRED,\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","import type { AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport { authAccountLinkProvenanceSql } from \"./coordinator-auth-link-provenance.js\";\n\nconst history = \"coordinator_auth_account_connection_history\";\nconst current = \"coordinator_auth_account_links\";\nconst audit = \"coordinator_auth_link_audit_log\";\nconst auditColumns =\n\t\"coordinator_id,link_id,action,attempt_id,identity_id,group_id,device_id,fingerprint,controller_attestation_id,auth_config_revision,created_at_ms,authority_kind,device_claim_id\";\nconst birthMatch = `a.coordinator_id=l.coordinator_id AND a.link_id=l.link_id AND a.action='link_created'\n AND (a.attempt_id=l.attempt_id AND a.identity_id=l.identity_id AND a.controller_attestation_id IS l.controller_attestation_id)\n AND (a.authority_kind=l.authority_kind AND a.device_claim_id IS l.device_claim_id AND a.auth_config_revision=l.auth_config_revision AND a.created_at_ms=l.created_at_ms)`;\nconst receiptMatch = `r.coordinator_id=l.coordinator_id AND r.link_id=l.link_id AND r.action='link_revoked'\n AND (r.attempt_id=a.attempt_id AND r.identity_id=a.identity_id AND r.group_id=a.group_id AND r.device_id=a.device_id AND r.fingerprint=a.fingerprint)\n AND (r.controller_attestation_id IS a.controller_attestation_id AND r.authority_kind=a.authority_kind AND r.device_claim_id IS a.device_claim_id AND r.auth_config_revision=a.auth_config_revision AND r.created_at_ms=l.revoked_at_ms)`;\nfunction context(): string {\n\treturn `WITH requested AS MATERIALIZED (SELECT l.* FROM ${history} l WHERE (l.coordinator_id=? AND l.link_id=?) AND (${authAccountLinkProvenanceSql(\"l\", { connections: true })})),\n current_targets AS MATERIALIZED (SELECT l.* FROM ${current} l JOIN requested h ON h.coordinator_id=l.coordinator_id AND h.identity_id=l.identity_id),\n valid_current AS MATERIALIZED (SELECT l.coordinator_id,l.link_id FROM current_targets l WHERE ${authAccountLinkProvenanceSql(\"l\", { connections: true })})`;\n}\n// The requested row's Identity. The last two checks need no provenance of their own: the\n// first check refuses a requested row without it, and the three only ever hold together.\nconst requestedIdentity = `SELECT identity_id FROM ${history} WHERE coordinator_id=? AND link_id=?`;\n// Aliases l: the provenance expression names its row l.\nconst receiptOf = `EXISTS (SELECT 1 FROM ${audit} a JOIN ${audit} r ON ${receiptMatch} WHERE ${birthMatch})`;\nconst provenOf = `(${authAccountLinkProvenanceSql(\"l\", { connections: true })})`;\n\n/**\n * Audit proof is historical equality, not liveness: it remains valid after flags change.\n * The revocation is complete when all three checks hold. Each is a plain statement with\n * its own small nesting, where the old single statement nested them all through WITH\n * stages, past production D1's limit. Every check binds the coordinator and link once\n * per use of the requested row, in order.\n */\nexport function historicalRevocationChecks(coordinator: string, link: string): AuthLinkStatement[] {\n\t// The marker names each check of the completion read, as it named the old statement.\n\tconst marked = (statement: AuthLinkStatement) => ({\n\t\t...statement,\n\t\tsql: `/* historical_revocation_complete */ ${statement.sql}`,\n\t});\n\treturn [\n\t\t// The requested row itself is revoked with its receipt.\n\t\t{\n\t\t\tsql: `SELECT EXISTS (SELECT 1 FROM ${history} l WHERE l.coordinator_id=? AND l.link_id=?\n AND ${provenOf} AND l.revoked_at_ms IS NOT NULL AND ${receiptOf}) AS ok`,\n\t\t\tvalues: [coordinator, link],\n\t\t},\n\t\t// Every current link of its Identity is revoked, valid, and has its receipt: as many\n\t\t// links qualify as there are. A count keeps the deep provenance expression out of a\n\t\t// negated subquery, within production D1's expression depth.\n\t\t{\n\t\t\tsql: `SELECT (SELECT count(*) FROM ${current} l WHERE l.coordinator_id=?\n AND l.identity_id IN (${requestedIdentity}))\n = (SELECT count(*) FROM ${current} l WHERE l.coordinator_id=? AND l.identity_id IN (${requestedIdentity})\n AND l.revoked_at_ms IS NOT NULL AND ${provenOf} AND ${receiptOf}) AS ok`,\n\t\t\tvalues: [coordinator, coordinator, link, coordinator, coordinator, link],\n\t\t},\n\t\t// No session of that Identity is live.\n\t\t{\n\t\t\tsql: `SELECT NOT EXISTS (SELECT 1 FROM coordinator_auth_sessions s WHERE s.coordinator_id=?\n AND s.revoked_at_ms IS NULL AND s.identity_id IN (${requestedIdentity})) AS ok`,\n\t\t\tvalues: [coordinator, coordinator, link],\n\t\t},\n\t].map(marked);\n}\nfunction insertAudit(source: \"requested\" | \"current_targets\"): string {\n\treturn `${context()} INSERT INTO ${audit} (${auditColumns})\n SELECT l.coordinator_id,l.link_id,'link_revoked',a.attempt_id,a.identity_id,a.group_id,a.device_id,a.fingerprint,a.controller_attestation_id,a.auth_config_revision,l.revoked_at_ms,l.authority_kind,l.device_claim_id\n FROM ${source} l ${source === \"current_targets\" ? \"JOIN valid_current v ON v.coordinator_id=l.coordinator_id AND v.link_id=l.link_id\" : \"\"} JOIN ${audit} a ON ${birthMatch} WHERE l.revoked_at_ms IS NOT NULL\n AND NOT EXISTS (SELECT 1 FROM ${audit} r WHERE r.coordinator_id=l.coordinator_id AND r.link_id=l.link_id AND r.action='link_revoked')`;\n}\n/** Derive every replacement from the retained requested Identity inside this one\n * writer transaction; a separately read current-link ID must never drive these effects. */\nexport function historicalRevocationStatements(\n\tcoordinator: string,\n\tlink: string,\n\tnow: number,\n): AuthLinkStatement[] {\n\tconst values = [coordinator, link];\n\treturn [\n\t\t{\n\t\t\tsql: `${context()} UPDATE ${history} AS l SET revoked_at_ms=? WHERE l.revoked_at_ms IS NULL AND EXISTS (SELECT 1 FROM requested h WHERE h.coordinator_id=l.coordinator_id AND h.link_id=l.link_id)`,\n\t\t\tvalues: [...values, now],\n\t\t},\n\t\t{ sql: insertAudit(\"requested\"), values },\n\t\t{\n\t\t\tsql: `${context()} UPDATE ${current} AS l SET revoked_at_ms=(SELECT revoked_at_ms FROM requested) WHERE l.revoked_at_ms IS NULL AND EXISTS (SELECT 1 FROM valid_current v WHERE v.coordinator_id=l.coordinator_id AND v.link_id=l.link_id)`,\n\t\t\tvalues,\n\t\t},\n\t\t{ sql: insertAudit(\"current_targets\"), values },\n\t\t{\n\t\t\tsql: `${context()} UPDATE coordinator_auth_sessions SET revoked_at_ms=(SELECT revoked_at_ms FROM requested) WHERE revoked_at_ms IS NULL AND coordinator_id=? AND identity_id=(SELECT identity_id FROM requested)`,\n\t\t\tvalues: [...values, coordinator],\n\t\t},\n\t\t// A standalone invalid insert fails even when a trigger ignored a required effect,\n\t\t// once for each check of a complete revocation.\n\t\t...historicalRevocationChecks(coordinator, link).map((check) => ({\n\t\t\tsql: `INSERT INTO coordinator_auth_account_connection_orders (coordinator_id,last_order) SELECT NULL,0 WHERE NOT (SELECT ok FROM (${check.sql}))`,\n\t\t\tvalues: check.values,\n\t\t})),\n\t];\n}\n","import type {\n\tCoordinatorAuthBrowserTransactionRejected,\n\tCoordinatorAuthBrowserTransactionStartResult,\n} from \"./coordinator-auth-browser-transaction-contract.js\";\nimport type { AuthLinkBackend } from \"./coordinator-auth-link.js\";\nimport type {\n\tCoordinatorAuthLinkCreateInput,\n\tCoordinatorAuthLinkFinalizeInput,\n\tCoordinatorAuthLinkSigner,\n} from \"./coordinator-auth-link-contract.js\";\nimport { hashCoordinatorAuthProofBytes32 } from \"./coordinator-auth-proof.js\";\n\n/** Same authority and pins as desktop create; the user code hash replaces the start hash. */\nexport type CoordinatorAuthLinkHeadlessCreateInput = Omit<\n\tCoordinatorAuthLinkCreateInput,\n\t\"loopbackRedirect\" | \"browserStartHash\"\n> & { userCodeHash: string };\n/** The device-approved account must equal the attempt's verified account when the link is written. */\nexport interface CoordinatorAuthLinkHeadlessFinalizeInput extends CoordinatorAuthLinkFinalizeInput {\n\tapprovedAccount: { issuer: string; subject: string };\n}\nexport interface CoordinatorAuthLinkHeadlessApprovalInput {\n\tattemptId: string;\n\tsigner: CoordinatorAuthLinkSigner;\n}\n/** Verified account shown on the device before it approves; profile fields are display claims. */\nexport interface CoordinatorAuthLinkHeadlessApproval {\n\tissuer: string;\n\tsubject: string;\n\tdisplayName: string | null;\n\temail: string | null;\n\temailVerified: boolean | null;\n}\nexport interface CoordinatorAuthHeadlessBrowserStartInput {\n\tuserCodeHash: string;\n\tstateHash: string;\n\tbinderHash: string;\n\tnonce: string;\n\tpkceVerifier: string;\n}\nexport type CoordinatorAuthHeadlessBrowserStartResult =\n\t| { kind: \"started\"; expiresAtMs: number; attemptId: string }\n\t| Exclude<CoordinatorAuthBrowserTransactionStartResult, { kind: \"started\" }>\n\t| CoordinatorAuthBrowserTransactionRejected;\n\n/**\n * Headless attempts share the desktop attempt table. This exact loopback value\n * marks the mode; it can never parse as a loopback URL, so desktop completion\n * delivery stays unreachable for headless rows.\n */\nexport const AUTH_LINK_HEADLESS_MARKER = \"codemem-headless:v1\";\n/** SQL literal form of the marker. The constant contains no quote characters. */\nexport const AUTH_LINK_HEADLESS_MARKER_SQL = `'${AUTH_LINK_HEADLESS_MARKER}'`;\n\n/** Consonants only: no vowels (no accidental words) and no 0/O or 1/I confusion. */\nexport const HEADLESS_USER_CODE_ALPHABET = \"BCDFGHJKLMNPQRSTVWXZ\";\nexport const HEADLESS_USER_CODE_LENGTH = 8;\nconst HEADLESS_USER_CODE_PREFIX = \"codemem-headless-link-code-v1:\";\n// 240 is the largest multiple of 20 not above 256; larger bytes would bias the alphabet.\nconst UNBIASED_BYTE_LIMIT = 240;\nconst MAX_RAW_USER_CODE_LENGTH = 64;\nconst GENERATION_BATCH = 16;\n\nexport type HeadlessRandomBytes = (length: number) => Uint8Array;\n\nfunction defaultRandomBytes(length: number): Uint8Array {\n\treturn globalThis.crypto.getRandomValues(new Uint8Array(length));\n}\n\n/** Returns the normalized 8-character code. Display it with formatHeadlessUserCode. */\nexport function generateHeadlessUserCode(\n\toptions: { randomBytes?: HeadlessRandomBytes } = {},\n): string {\n\tconst randomBytes = options.randomBytes ?? defaultRandomBytes;\n\tlet code = \"\";\n\t// Each batch accepts a byte with probability 240/256; 64 batches failing is not a real outcome.\n\tfor (let round = 0; round < 64 && code.length < HEADLESS_USER_CODE_LENGTH; round += 1) {\n\t\tfor (const byte of randomBytes(GENERATION_BATCH)) {\n\t\t\tif (byte >= UNBIASED_BYTE_LIMIT) continue;\n\t\t\tcode += HEADLESS_USER_CODE_ALPHABET[byte % HEADLESS_USER_CODE_ALPHABET.length];\n\t\t\tif (code.length === HEADLESS_USER_CODE_LENGTH) return code;\n\t\t}\n\t}\n\tthrow new Error(\"headless_user_code_entropy_failed\");\n}\n\n/** Formats a normalized code as XXXX-XXXX for display. */\nexport function formatHeadlessUserCode(code: string): string {\n\tconst normalized = normalizeHeadlessUserCode(code);\n\tif (normalized === null) throw new Error(\"headless_user_code_invalid\");\n\treturn `${normalized.slice(0, 4)}-${normalized.slice(4)}`;\n}\n\n/**\n * Accepts typed input: case-insensitive, with '-' and whitespace ignored.\n * Returns null for any other character or a wrong length.\n */\nexport function normalizeHeadlessUserCode(value: unknown): string | null {\n\tif (typeof value !== \"string\" || value.length > MAX_RAW_USER_CODE_LENGTH) return null;\n\tconst stripped = value.replace(/[\\s-]/g, \"\");\n\t// Check ASCII letters before uppercasing: Unicode case mapping can expand characters.\n\tif (!/^[A-Za-z]+$/.test(stripped) || stripped.length !== HEADLESS_USER_CODE_LENGTH) return null;\n\tconst upper = stripped.toUpperCase();\n\tfor (const character of upper) {\n\t\tif (!HEADLESS_USER_CODE_ALPHABET.includes(character)) return null;\n\t}\n\treturn upper;\n}\n\n/** The 32 bytes that play the role of a desktop browser start code. */\nexport async function deriveHeadlessUserCodeStartBytes(\n\tnormalizedCode: string,\n): Promise<Uint8Array> {\n\tif (normalizeHeadlessUserCode(normalizedCode) !== normalizedCode)\n\t\tthrow new Error(\"headless_user_code_invalid\");\n\tconst input = new TextEncoder().encode(`${HEADLESS_USER_CODE_PREFIX}${normalizedCode}`);\n\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", input);\n\treturn new Uint8Array(digest);\n}\n\n/** Stored as browser_start_hash, using the same hash desktop applies to its start code bytes. */\nexport async function hashHeadlessUserCode(normalizedCode: string): Promise<string> {\n\treturn hashCoordinatorAuthProofBytes32(await deriveHeadlessUserCodeStartBytes(normalizedCode));\n}\n\n/**\n * True when another attempt already stores this code hash. A create that fails\n * for this reason can succeed with a fresh code; any other conflict cannot.\n * The unique index covers every retained attempt, whatever its state.\n */\nexport async function isHeadlessUserCodeHeldByAnotherAttempt(\n\tbackend: Pick<AuthLinkBackend, \"first\">,\n\tinput: { coordinatorId: string; userCodeHash: string; attemptId: string },\n): Promise<boolean> {\n\tconst row = await backend.first<{ held: number }>({\n\t\tsql: `SELECT 1 AS held FROM coordinator_auth_link_attempts\n WHERE coordinator_id = ? AND browser_start_hash = ? AND attempt_id <> ? LIMIT 1`,\n\t\tvalues: [input.coordinatorId, input.userCodeHash, input.attemptId],\n\t});\n\treturn row?.held === 1;\n}\n","import type { CoordinatorAuthBrowserConfig } from \"./coordinator-auth-browser-transaction-contract.js\";\nimport type { CoordinatorAccountReference } from \"./coordinator-auth-contract.js\";\nimport type { CoordinatorAuthLinkConfig } from \"./coordinator-auth-link-contract.js\";\n\nexport const AUTH_SESSION_TTL_MS = 28800000;\nexport const AUTH_SESSION_MAX_LIVE_PER_LINK = 10;\nexport const AUTH_LINK_REDEEM_WINDOW_MS = 120000;\nexport const AUTH_GUARDED_SIGNIN_PURGE_GRACE_MS = 86400000;\nexport const AUTH_GUARDED_SIGNIN_RECEIPT_PURGE_AGE_MS = 115200000;\nexport const AUTH_GUARDED_SIGNIN_PURGE_BATCH_MAX = 256;\n/** Server metadata only: never a bearer credential or its commitment. */\nexport interface CoordinatorAuthSession {\n\tsessionId: string;\n\tidentityId: string;\n\tlinkId: string;\n\taccount: CoordinatorAccountReference;\n\texpiresAtMs: number;\n}\nexport type CoordinatorAuthSessionError =\n\t| \"invalid_input\"\n\t| \"auth_config_changed\"\n\t| \"attempt_unavailable\"\n\t| \"redeem_window_expired\"\n\t| \"browser_transaction_used\"\n\t| \"transaction_unavailable\"\n\t| \"session_limited\"\n\t| \"account_not_linked\";\nexport type CoordinatorAuthSessionIssueResult =\n\t| { kind: \"issued\"; session: CoordinatorAuthSession }\n\t| { kind: \"rejected\"; error: CoordinatorAuthSessionError };\nexport type CoordinatorAuthLinkSessionPreserveResult =\n\t| Readonly<{ kind: \"preserved\" }>\n\t| Extract<CoordinatorAuthSessionIssueResult, { kind: \"rejected\" }>;\n/** Hashes come from trusted browser authentication and a fresh 32-byte server generator.\n * Shape validation is not cryptographic evidence; raw credentials never enter this API.\n */\nexport interface CoordinatorAuthLinkSessionRedeemInput {\n\tattemptId: string;\n\tbrowserTransactionHash: string;\n\tcredentialHash: string;\n}\n/** Binding hashes are derived and resolved by the trusted server, never nominated by HTTP JSON. */\nexport interface CoordinatorAuthBoundLinkSessionRedeemInput\n\textends CoordinatorAuthLinkSessionRedeemInput {\n\tbinderHash: string;\n}\n/** Account claims must already be independently verified by the server's OIDC ceremony. */\nexport interface CoordinatorAuthAccountSignInInput {\n\tbrowserTransactionHash: string;\n\taccount: CoordinatorAccountReference;\n\tcredentialHash: string;\n}\n/** Scope comes from trusted server configuration, not network JSON. */\nexport interface CoordinatorAuthSessionScope {\n\tcoordinatorId: string;\n}\nexport interface CoordinatorAuthSessionPurgeOptions {\n\tlimit?: number;\n}\nexport type CoordinatorAuthSessionPurgeResult =\n\t| { kind: \"purged\"; processedCount: number; more: boolean }\n\t| { kind: \"rejected\"; error: \"invalid_input\" };\nexport type CoordinatorAuthSessionSignOutResult =\n\t| { kind: \"signed_out\" }\n\t| { kind: \"rejected\"; error: \"invalid_input\" };\nexport type CoordinatorAuthAccountLinkRevokeResult =\n\t| { kind: \"revoked\" }\n\t| { kind: \"rejected\"; error: \"invalid_input\" | \"link_unavailable\" };\nexport interface CoordinatorAuthSessionStore {\n\t/** Optional metadata cleanup only; more is an operational hint, not authority. */\n\tpurgeAuthGuardedSigninSessions(\n\t\tscope: CoordinatorAuthSessionScope,\n\t\toptions?: CoordinatorAuthSessionPurgeOptions,\n\t): Promise<CoordinatorAuthSessionPurgeResult>;\n\tpurgeAuthGuardedSigninReceipts(\n\t\tscope: CoordinatorAuthSessionScope,\n\t\toptions?: CoordinatorAuthSessionPurgeOptions,\n\t): Promise<CoordinatorAuthSessionPurgeResult>;\n\t/** @deprecated Always rejects; use redeemAuthLinkSessionWithBrowserTransaction with the original binder. */\n\tredeemAuthLinkSession(\n\t\tinput: CoordinatorAuthLinkSessionRedeemInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthSessionIssueResult>;\n\tredeemAuthLinkSessionWithBrowserTransaction(\n\t\tinput: CoordinatorAuthBoundLinkSessionRedeemInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<CoordinatorAuthSessionIssueResult>;\n\t/** credentialHash is the existing live session hash, not a fresh token hash. */\n\tpreserveAuthLinkSessionCompletion(\n\t\tinput: CoordinatorAuthBoundLinkSessionRedeemInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<CoordinatorAuthLinkSessionPreserveResult>;\n\t/** @deprecated Always rejects; use signInWithConsumedBrowserTransaction after verifying provider/browser proof. */\n\tsignInWithAuthAccount(\n\t\tinput: CoordinatorAuthAccountSignInInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthSessionIssueResult>;\n\t/** Caller already verified OIDC claims, original browser binding and CSRF.\n\t * Hashes are trusted server metadata, never accepted from HTTP JSON.\n\t */\n\tsignInWithConsumedBrowserTransaction(\n\t\tinput: CoordinatorAuthAccountSignInInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<CoordinatorAuthSessionIssueResult>;\n\treadAuthSession(\n\t\tcredentialHash: string,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthSession | null>;\n\tsignOutAuthSession(\n\t\tcredentialHash: string,\n\t\tscope: CoordinatorAuthSessionScope,\n\t): Promise<CoordinatorAuthSessionSignOutResult>;\n}\n/** Separate admin capability: future callers MUST authenticate the configured admin.\n * Browser sessions and caller-supplied actor labels never supply this authority.\n */\nexport interface CoordinatorAuthAccountLinkAdminStore {\n\trevokeAuthAccountLink(\n\t\tinput: { linkId: string },\n\t\tscope: CoordinatorAuthSessionScope,\n\t): Promise<CoordinatorAuthAccountLinkRevokeResult>;\n}\n\n// Empty tables only: no foreign keys, backfill, profiles, or provider tokens.\nexport const AUTH_SESSION_RETENTION_COLUMN_SQL = `purge_eligible INTEGER NOT NULL DEFAULT 0 CHECK (typeof(purge_eligible) = 'integer' AND purge_eligible IN (0,1) AND (purge_eligible = 0 OR (source = 'signin' AND attempt_id IS NULL)))`;\nexport const AUTH_SESSION_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS coordinator_auth_session_receipts (\n coordinator_id TEXT NOT NULL,\n browser_transaction_hash TEXT NOT NULL CHECK (length(browser_transaction_hash) = 64 AND browser_transaction_hash NOT GLOB '*[^0-9a-f]*'),\n source TEXT NOT NULL CHECK (source IN ('link_redeem','signin')),\n attempt_id TEXT,\n link_id TEXT NOT NULL,\n session_id TEXT NOT NULL,\n auth_config_revision TEXT NOT NULL CHECK (length(auth_config_revision) = 64 AND auth_config_revision NOT GLOB '*[^0-9a-f]*'),\n created_at_ms INTEGER NOT NULL CHECK (typeof(created_at_ms) = 'integer' AND created_at_ms BETWEEN 0 AND 9007199225940991),\n ${AUTH_SESSION_RETENTION_COLUMN_SQL},\n PRIMARY KEY (coordinator_id, browser_transaction_hash),\n UNIQUE (coordinator_id, session_id),\n UNIQUE (coordinator_id, attempt_id),\n CHECK ((source = 'link_redeem' AND attempt_id IS NOT NULL) OR (source = 'signin' AND attempt_id IS NULL))\n);\nCREATE TABLE IF NOT EXISTS coordinator_auth_sessions (\n coordinator_id TEXT NOT NULL,\n session_id TEXT NOT NULL,\n credential_hash TEXT NOT NULL CHECK (length(credential_hash) = 64 AND credential_hash NOT GLOB '*[^0-9a-f]*'),\n browser_transaction_hash TEXT NOT NULL CHECK (length(browser_transaction_hash) = 64 AND browser_transaction_hash NOT GLOB '*[^0-9a-f]*'),\n link_id TEXT NOT NULL,\n identity_id TEXT NOT NULL,\n issuer TEXT NOT NULL,\n subject TEXT NOT NULL CHECK (length(subject) BETWEEN 1 AND 255),\n auth_config_revision TEXT NOT NULL CHECK (length(auth_config_revision) = 64 AND auth_config_revision NOT GLOB '*[^0-9a-f]*'),\n created_at_ms INTEGER NOT NULL CHECK (typeof(created_at_ms) = 'integer' AND created_at_ms BETWEEN 0 AND 9007199225940991),\n expires_at_ms INTEGER NOT NULL CHECK (typeof(expires_at_ms) = 'integer' AND expires_at_ms BETWEEN 0 AND 9007199254740991 AND expires_at_ms = created_at_ms + 28800000),\n revoked_at_ms INTEGER CHECK (revoked_at_ms IS NULL OR (typeof(revoked_at_ms) = 'integer' AND revoked_at_ms BETWEEN 0 AND 9007199254740991)),\n PRIMARY KEY (coordinator_id, session_id),\n UNIQUE (coordinator_id, credential_hash),\n UNIQUE (coordinator_id, browser_transaction_hash)\n);\nCREATE INDEX IF NOT EXISTS idx_auth_sessions_link_config_expiry\n ON coordinator_auth_sessions(coordinator_id, link_id, auth_config_revision, expires_at_ms);\nCREATE INDEX IF NOT EXISTS idx_auth_sessions_expiry\n ON coordinator_auth_sessions(coordinator_id, expires_at_ms, session_id);\nCREATE INDEX IF NOT EXISTS idx_auth_session_receipts_purge\n ON coordinator_auth_session_receipts(coordinator_id, purge_eligible, created_at_ms, browser_transaction_hash);\n`;\n","import { hasConnectionSessionSchema } from \"./coordinator-account-connection-session.js\";\nimport {\n\tCONNECTION_NOT_REVOKED_SQL,\n\tCONNECTION_SIGNIN_ORDER_SQL,\n} from \"./coordinator-account-connection-storage.js\";\nimport {\n\thistoricalRevocationChecks,\n\thistoricalRevocationStatements,\n} from \"./coordinator-account-historical-revoke.js\";\nimport type { CoordinatorAuthBrowserConfig } from \"./coordinator-auth-browser-transaction-contract.js\";\nimport {\n\tisCoordinatorAccountIssuer,\n\tparseCoordinatorAccountReference,\n} from \"./coordinator-auth-contract.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport type { CoordinatorAuthLinkConfig } from \"./coordinator-auth-link-contract.js\";\nimport { AUTH_LINK_HEADLESS_MARKER_SQL } from \"./coordinator-auth-link-headless.js\";\nimport { authAccountLinkProvenanceSql } from \"./coordinator-auth-link-provenance.js\";\nimport { authPersistenceError } from \"./coordinator-auth-schema.js\";\nimport {\n\tAUTH_GUARDED_SIGNIN_PURGE_BATCH_MAX,\n\tAUTH_GUARDED_SIGNIN_PURGE_GRACE_MS,\n\tAUTH_GUARDED_SIGNIN_RECEIPT_PURGE_AGE_MS,\n\tAUTH_LINK_REDEEM_WINDOW_MS,\n\tAUTH_SESSION_MAX_LIVE_PER_LINK,\n\tAUTH_SESSION_TTL_MS,\n\ttype CoordinatorAuthAccountLinkAdminStore,\n\ttype CoordinatorAuthAccountLinkRevokeResult,\n\ttype CoordinatorAuthAccountSignInInput,\n\ttype CoordinatorAuthBoundLinkSessionRedeemInput,\n\ttype CoordinatorAuthLinkSessionPreserveResult,\n\ttype CoordinatorAuthLinkSessionRedeemInput,\n\ttype CoordinatorAuthSession,\n\ttype CoordinatorAuthSessionError,\n\ttype CoordinatorAuthSessionIssueResult,\n\ttype CoordinatorAuthSessionPurgeOptions,\n\ttype CoordinatorAuthSessionPurgeResult,\n\ttype CoordinatorAuthSessionScope,\n\ttype CoordinatorAuthSessionSignOutResult,\n\ttype CoordinatorAuthSessionStore,\n} from \"./coordinator-auth-session-contract.js\";\n\nexport * from \"./coordinator-auth-session-contract.js\";\n\ntype Captured = Record<string, unknown>;\nfunction capture(value: unknown, fields: readonly string[]): Captured | null {\n\tif (!value || typeof value !== \"object\") return null;\n\ttry {\n\t\tif (Array.isArray(value)) return null;\n\t\tconst result: Captured = {};\n\t\tfor (const key of fields) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\t\tif (!descriptor || !Object.hasOwn(descriptor, \"value\")) return null;\n\t\t\tresult[key] = descriptor.value;\n\t\t}\n\t\treturn result;\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction isHash(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length === 64 && /^[0-9a-f]{64}$/.test(value);\n}\nfunction captureConfig(value: unknown): CoordinatorAuthLinkConfig | null {\n\tconst c = capture(value, [\"coordinatorId\", \"issuer\", \"revision\", \"enabled\"]);\n\tif (\n\t\t!c ||\n\t\t!isAuthControllerId(c.coordinatorId) ||\n\t\t!isCoordinatorAccountIssuer(c.issuer) ||\n\t\t!isHash(c.revision) ||\n\t\ttypeof c.enabled !== \"boolean\"\n\t)\n\t\treturn null;\n\treturn {\n\t\tcoordinatorId: c.coordinatorId,\n\t\tissuer: c.issuer,\n\t\trevision: c.revision,\n\t\tenabled: c.enabled,\n\t};\n}\nfunction captureScope(value: unknown): CoordinatorAuthSessionScope | null {\n\tconst s = capture(value, [\"coordinatorId\"]);\n\treturn s && isAuthControllerId(s.coordinatorId) ? { coordinatorId: s.coordinatorId } : null;\n}\nfunction capturePurgeLimit(value: unknown): number | null {\n\tif (value === undefined) return AUTH_GUARDED_SIGNIN_PURGE_BATCH_MAX;\n\tif (!value || typeof value !== \"object\") return null;\n\ttry {\n\t\tif (Array.isArray(value)) return null;\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, \"limit\");\n\t\tif (!descriptor) return \"limit\" in value ? null : AUTH_GUARDED_SIGNIN_PURGE_BATCH_MAX;\n\t\tif (!Object.hasOwn(descriptor, \"value\")) return null;\n\t\tconst limit: unknown = descriptor.value;\n\t\tif (typeof limit !== \"number\" || !Number.isSafeInteger(limit)) return null;\n\t\treturn limit >= 1 && limit <= AUTH_GUARDED_SIGNIN_PURGE_BATCH_MAX ? limit : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction captureBrowserConfig(value: unknown): CoordinatorAuthBrowserConfig | null {\n\tconst snapshot = capture(value, [\n\t\t\"coordinatorId\",\n\t\t\"issuer\",\n\t\t\"revision\",\n\t\t\"enabled\",\n\t\t\"redirectUri\",\n\t]);\n\tconst c = captureConfig(snapshot);\n\tif (!c || !snapshot || typeof snapshot.redirectUri !== \"string\") return null;\n\tconst redirectUri = snapshot.redirectUri;\n\tif (redirectUri.trim() !== redirectUri || /[\\\\\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(redirectUri))\n\t\treturn null;\n\ttry {\n\t\tconst url = new URL(redirectUri);\n\t\tif (\n\t\t\turl.protocol !== \"https:\" ||\n\t\t\turl.href !== redirectUri ||\n\t\t\turl.username ||\n\t\t\turl.password ||\n\t\t\turl.search ||\n\t\t\turl.hash ||\n\t\t\tredirectUri.includes(\"?\") ||\n\t\t\tredirectUri.includes(\"#\")\n\t\t)\n\t\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t}\n\treturn { ...c, redirectUri };\n}\nfunction captureIssue(\n\tvalue: unknown,\n\textra: string[],\n): (Captured & { browserTransactionHash: string; credentialHash: string }) | null {\n\tconst i = capture(value, [\"browserTransactionHash\", \"credentialHash\", ...extra]);\n\tif (!i || !isHash(i.browserTransactionHash) || !isHash(i.credentialHash)) return null;\n\treturn {\n\t\t...i,\n\t\tbrowserTransactionHash: i.browserTransactionHash,\n\t\tcredentialHash: i.credentialHash,\n\t};\n}\nfunction sessionNow(clock: () => number): number {\n\tlet now: number;\n\ttry {\n\t\tnow = clock();\n\t} catch {\n\t\tthrow new Error(\"auth_session_invalid_clock\");\n\t}\n\tif (!Number.isSafeInteger(now) || now < 0 || now > Number.MAX_SAFE_INTEGER - AUTH_SESSION_TTL_MS)\n\t\tthrow new Error(\"auth_session_invalid_clock\");\n\treturn now;\n}\n\nexport { sessionNow as authSessionNow };\n\nfunction rejected(\n\terror: CoordinatorAuthSessionError,\n): Extract<CoordinatorAuthSessionIssueResult, { kind: \"rejected\" }> {\n\treturn { kind: \"rejected\", error };\n}\ninterface SessionRow {\n\tsession_id: string;\n\tidentity_id: string;\n\tlink_id: string;\n\tissuer: string;\n\tsubject: string;\n\texpires_at_ms: number;\n}\ninterface ReceiptRow {\n\tsession_id: string;\n}\ninterface RedeemDiagnosis {\n\tbrowser_transaction_hash: string | null;\n\tstate: string;\n\tissuer: string;\n\tauth_config_revision: string;\n\tfinalized_at_ms: number | null;\n\texpires_at_ms: number;\n}\nfunction dto(row: SessionRow): CoordinatorAuthSession {\n\treturn {\n\t\tsessionId: row.session_id,\n\t\tidentityId: row.identity_id,\n\t\tlinkId: row.link_id,\n\t\taccount: { issuer: row.issuer, subject: row.subject },\n\t\texpiresAtMs: row.expires_at_ms,\n\t};\n}\nconst SESSION_LINK_IDENTITY_SQL = `l.coordinator_id = s.coordinator_id AND l.link_id = s.link_id\n AND l.identity_id = s.identity_id AND l.issuer = s.issuer AND l.subject = s.subject`;\nexport function authSessionLinkMatchSql(options: { connections: boolean }): string {\n\treturn `${SESSION_LINK_IDENTITY_SQL} AND ${authAccountLinkProvenanceSql(\"l\", options)}`;\n}\nexport const AUTH_SESSION_LINK_MATCH_SQL = authSessionLinkMatchSql({ connections: false });\nexport const AUTH_SESSION_LIVE_GUARD_SQL = `s.coordinator_id = ? AND s.credential_hash = ? AND s.issuer = ? AND s.auth_config_revision = ? AND s.revoked_at_ms IS NULL AND l.revoked_at_ms IS NULL AND s.expires_at_ms > ? AND s.created_at_ms <= ?`;\n// Headless finalize hands no browser a session: the browser never proved device possession.\nconst DESKTOP_ATTEMPT_SQL = `t.loopback_redirect <> ${AUTH_LINK_HEADLESS_MARKER_SQL}`;\nconst RECEIPT_COLUMNS = `coordinator_id, browser_transaction_hash, source, attempt_id, link_id, session_id, auth_config_revision, created_at_ms`;\nfunction redeemReceiptSelectSql(options: { connections: boolean }) {\n\tconst ACCOUNT_PROVENANCE = authAccountLinkProvenanceSql(\"l\", options);\n\treturn `INSERT INTO coordinator_auth_session_receipts (${RECEIPT_COLUMNS})\n SELECT t.coordinator_id, t.browser_transaction_hash, 'link_redeem', t.attempt_id, t.link_id, ?, ?, ?\n FROM coordinator_auth_link_attempts t JOIN coordinator_auth_account_links l\n ON l.coordinator_id = t.coordinator_id AND l.link_id = t.link_id AND l.attempt_id = t.attempt_id\n AND l.identity_id = t.identity_id AND l.issuer = t.issuer AND l.subject = t.account_subject\n AND l.auth_config_revision = t.auth_config_revision AND l.authority_kind = t.authority_kind\n AND ${ACCOUNT_PROVENANCE}\n WHERE t.coordinator_id = ? AND t.attempt_id = ? AND t.browser_transaction_hash = ?\n AND t.state = 'finalized' AND t.issuer = ? AND t.auth_config_revision = ? AND l.revoked_at_ms IS NULL\n AND ${DESKTOP_ATTEMPT_SQL} AND ? >= t.finalized_at_ms AND ? < t.finalized_at_ms + 120000 AND ? < t.expires_at_ms`;\n}\nconst BOUND_LINK_BROWSER_GUARD_SQL = `b.coordinator_id = t.coordinator_id\n AND b.browser_transaction_hash = t.browser_transaction_hash AND b.attempt_id = t.attempt_id\n AND b.binder_hash = ? AND b.purpose = 'link' AND b.state = 'consumed'\n AND b.issuer = ? AND b.auth_config_revision = ? AND b.redirect_uri = ?\n AND b.nonce IS NULL AND b.pkce_verifier IS NULL AND b.claim_token IS NOT NULL\n AND b.consumed_at_ms IS NOT NULL AND b.created_at_ms <= ?\n AND b.consumed_at_ms <= ? AND b.expires_at_ms > ?`;\nfunction boundBrowserGuard(options: { connections: boolean }) {\n\treturn `(${BOUND_LINK_BROWSER_GUARD_SQL})${options.connections ? ` AND (${CONNECTION_SIGNIN_ORDER_SQL}) AND (${CONNECTION_NOT_REVOKED_SQL})` : \"\"}`;\n}\nfunction boundRedeemSql(options: { connections: boolean }) {\n\treturn `${redeemReceiptSelectSql(options)}\n AND EXISTS (SELECT 1 FROM coordinator_auth_browser_transactions b WHERE ${boundBrowserGuard(options)})\n ON CONFLICT(coordinator_id, browser_transaction_hash) DO NOTHING`;\n}\nfunction connectedPreserveCompletionSql(): string {\n\treturn `WITH completion_links AS MATERIALIZED (SELECT l.* FROM coordinator_auth_account_links l WHERE l.coordinator_id = ? AND\n (l.link_id = (SELECT link_id FROM coordinator_auth_link_attempts WHERE coordinator_id = ? AND attempt_id = ?) OR l.link_id = (SELECT link_id FROM coordinator_auth_sessions WHERE coordinator_id = ? AND credential_hash = ?))\n AND (${authAccountLinkProvenanceSql(\"l\", { connections: true })}) AND (${CONNECTION_NOT_REVOKED_SQL})),\n eligible_completion AS MATERIALIZED (SELECT t.coordinator_id,t.attempt_id,t.browser_transaction_hash FROM coordinator_auth_link_attempts t JOIN completion_links l\n ON (l.coordinator_id=t.coordinator_id AND l.link_id=t.link_id AND l.attempt_id=t.attempt_id)\n AND (l.identity_id=t.identity_id AND l.issuer=t.issuer AND l.subject=t.account_subject AND l.auth_config_revision=t.auth_config_revision AND l.authority_kind=t.authority_kind AND l.revoked_at_ms IS NULL)\n WHERE (t.coordinator_id = ? AND t.attempt_id = ? AND t.browser_transaction_hash = ? AND t.issuer = ? AND t.auth_config_revision = ? AND t.state = 'finalized')\n AND ${DESKTOP_ATTEMPT_SQL} AND (t.created_at_ms <= ? AND t.finalized_at_ms <= ? AND ? < t.finalized_at_ms + 120000 AND t.expires_at_ms > ?)\n AND EXISTS (SELECT 1 FROM coordinator_auth_browser_transactions b WHERE ${boundBrowserGuard({ connections: true })})),\n live_existing_session AS MATERIALIZED (SELECT 1 FROM coordinator_auth_sessions s JOIN completion_links l ON ${SESSION_LINK_IDENTITY_SQL} WHERE (${AUTH_SESSION_LIVE_GUARD_SQL}) AND (${CONNECTION_NOT_REVOKED_SQL}))\n UPDATE coordinator_auth_link_attempts AS t SET state='session_redeemed' WHERE t.state='finalized'\n AND EXISTS (SELECT 1 FROM eligible_completion p WHERE p.coordinator_id=t.coordinator_id AND p.attempt_id=t.attempt_id AND p.browser_transaction_hash=t.browser_transaction_hash)\n AND EXISTS (SELECT 1 FROM live_existing_session)`;\n}\nfunction preserveCompletionSql(options: { connections: boolean }) {\n\tif (options.connections) return connectedPreserveCompletionSql();\n\tconst ACCOUNT_PROVENANCE = authAccountLinkProvenanceSql(\"l\", options),\n\t\tLINK_MATCH = authSessionLinkMatchSql(options);\n\treturn `UPDATE coordinator_auth_link_attempts AS t SET state = 'session_redeemed'\n WHERE (t.coordinator_id = ? AND t.attempt_id = ? AND t.browser_transaction_hash = ? AND t.issuer = ? AND t.auth_config_revision = ? AND t.state = 'finalized')\n AND ${DESKTOP_ATTEMPT_SQL} AND (t.created_at_ms <= ? AND t.finalized_at_ms <= ? AND ? < t.finalized_at_ms + 120000 AND t.expires_at_ms > ?)\n AND EXISTS (SELECT 1 FROM coordinator_auth_account_links l\n WHERE (l.coordinator_id = t.coordinator_id AND l.link_id = t.link_id AND l.attempt_id = t.attempt_id)\n AND (l.identity_id = t.identity_id AND l.issuer = t.issuer AND l.subject = t.account_subject)\n AND (l.auth_config_revision = t.auth_config_revision AND l.revoked_at_ms IS NULL AND l.authority_kind = t.authority_kind) AND ${ACCOUNT_PROVENANCE}\n AND EXISTS (SELECT 1 FROM coordinator_auth_browser_transactions b WHERE ${boundBrowserGuard(options)}))\n AND EXISTS (SELECT 1 FROM coordinator_auth_sessions s\n JOIN coordinator_auth_account_links l ON ${LINK_MATCH} WHERE (${AUTH_SESSION_LIVE_GUARD_SQL}))`;\n}\nconst CONSUMED_BROWSER_GUARD_SQL = `b.coordinator_id = ? AND b.browser_transaction_hash = ?\n AND b.purpose = 'signin' AND b.attempt_id IS NULL AND b.state = 'consumed'\n AND b.nonce IS NULL AND b.pkce_verifier IS NULL AND b.claim_token IS NOT NULL\n AND b.issuer = ? AND b.auth_config_revision = ? AND b.redirect_uri = ?\n AND b.created_at_ms <= ? AND b.consumed_at_ms <= ? AND b.expires_at_ms > ?`;\nfunction consumedSigninReceiptSql(options: { connections: boolean }) {\n\tconst ACCOUNT_PROVENANCE = authAccountLinkProvenanceSql(\"l\", options),\n\t\tLINK_MATCH = options.connections ? SESSION_LINK_IDENTITY_SQL : authSessionLinkMatchSql(options);\n\t// The capacity count references the same independently proven link row.\n\treturn `${options.connections ? `WITH admissible_links AS MATERIALIZED (SELECT l.* FROM coordinator_auth_account_links l WHERE (l.coordinator_id = ? AND l.issuer = ? AND l.subject = ?) AND (${ACCOUNT_PROVENANCE}) AND (${CONNECTION_NOT_REVOKED_SQL})) ` : \"\"}INSERT INTO coordinator_auth_session_receipts (${RECEIPT_COLUMNS}, purge_eligible${options.connections ? \",source_order\" : \"\"})\n SELECT b.coordinator_id, b.browser_transaction_hash, 'signin', NULL, l.link_id, ?, ?, ?, 1${options.connections ? \",b.start_order\" : \"\"}\n FROM coordinator_auth_browser_transactions b JOIN ${options.connections ? \"admissible_links\" : \"coordinator_auth_account_links\"} l\n ON l.coordinator_id = b.coordinator_id AND l.issuer = b.issuer\n WHERE (${CONSUMED_BROWSER_GUARD_SQL}) AND l.subject = ? AND l.revoked_at_ms IS NULL ${options.connections ? \"\" : `AND ${ACCOUNT_PROVENANCE}`}\n ${options.connections ? `AND ${CONNECTION_NOT_REVOKED_SQL} AND ${CONNECTION_SIGNIN_ORDER_SQL}` : \"\"}\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_link_attempts t\n WHERE t.coordinator_id = b.coordinator_id AND t.browser_transaction_hash = b.browser_transaction_hash)\n AND (SELECT COUNT(*) FROM coordinator_auth_sessions s WHERE ${LINK_MATCH}\n AND s.auth_config_revision = b.auth_config_revision AND s.revoked_at_ms IS NULL\n AND s.expires_at_ms > ?) < ${AUTH_SESSION_MAX_LIVE_PER_LINK}\n ON CONFLICT(coordinator_id, browser_transaction_hash) DO NOTHING`;\n}\nfunction sessionInsertSql(options: { connections: boolean }) {\n\tconst ACCOUNT_PROVENANCE = authAccountLinkProvenanceSql(\"l\", options);\n\treturn `INSERT INTO coordinator_auth_sessions\n (coordinator_id, session_id, credential_hash, browser_transaction_hash, link_id, identity_id, issuer, subject, auth_config_revision, created_at_ms, expires_at_ms)\n SELECT r.coordinator_id, r.session_id, ?, r.browser_transaction_hash, r.link_id, l.identity_id, l.issuer, l.subject, r.auth_config_revision, r.created_at_ms, r.created_at_ms + 28800000\n FROM coordinator_auth_session_receipts r JOIN coordinator_auth_account_links l ON l.coordinator_id = r.coordinator_id AND l.link_id = r.link_id\n WHERE r.coordinator_id = ? AND r.browser_transaction_hash = ? AND r.session_id = ? AND l.revoked_at_ms IS NULL AND ${ACCOUNT_PROVENANCE}`;\n}\nfunction redeemConsumeSql(options: { connections: boolean }) {\n\tconst ACCOUNT_PROVENANCE = authAccountLinkProvenanceSql(\"l\", options);\n\treturn `UPDATE coordinator_auth_link_attempts SET state = 'session_redeemed'\n WHERE coordinator_id = ? AND attempt_id = ? AND browser_transaction_hash = ? AND state = 'finalized'\n AND loopback_redirect <> ${AUTH_LINK_HEADLESS_MARKER_SQL} AND EXISTS (SELECT 1 FROM coordinator_auth_account_links l WHERE l.coordinator_id = coordinator_auth_link_attempts.coordinator_id\n AND l.link_id = coordinator_auth_link_attempts.link_id AND l.attempt_id = coordinator_auth_link_attempts.attempt_id\n AND l.authority_kind = coordinator_auth_link_attempts.authority_kind AND l.revoked_at_ms IS NULL AND ${ACCOUNT_PROVENANCE})\n AND EXISTS (SELECT 1 FROM coordinator_auth_sessions s WHERE s.coordinator_id = coordinator_auth_link_attempts.coordinator_id AND s.session_id = ? AND s.browser_transaction_hash = coordinator_auth_link_attempts.browser_transaction_hash)`;\n}\nfunction issueReadSql(options: { connections: boolean }) {\n\tconst LINK_MATCH = authSessionLinkMatchSql(options);\n\treturn `SELECT s.session_id, s.identity_id, s.link_id, s.issuer, s.subject, s.expires_at_ms\n FROM coordinator_auth_session_receipts r JOIN coordinator_auth_sessions s\n ON s.coordinator_id = r.coordinator_id AND s.session_id = r.session_id AND s.browser_transaction_hash = r.browser_transaction_hash\n AND s.link_id = r.link_id AND s.auth_config_revision = r.auth_config_revision AND s.created_at_ms = r.created_at_ms\n JOIN coordinator_auth_account_links l ON ${LINK_MATCH}\n WHERE r.coordinator_id = ? AND r.browser_transaction_hash = ? AND r.session_id = ?\n AND s.credential_hash = ? AND r.auth_config_revision = ? AND r.created_at_ms = ? AND s.expires_at_ms = ? AND s.issuer = ?\n AND ((r.source = 'signin' AND r.attempt_id IS NULL) OR (r.source = 'link_redeem' AND EXISTS\n (SELECT 1 FROM coordinator_auth_link_attempts t WHERE t.coordinator_id = r.coordinator_id AND t.attempt_id = r.attempt_id\n AND t.state = 'session_redeemed' AND t.authority_kind = l.authority_kind AND t.link_id = r.link_id AND t.browser_transaction_hash = r.browser_transaction_hash\n AND t.identity_id = s.identity_id AND t.issuer = s.issuer AND t.account_subject = s.subject)))`;\n}\n\nconst PURGE_GUARDED_SIGNIN_SESSIONS_SQL = `DELETE FROM coordinator_auth_sessions\n WHERE coordinator_id = ? AND expires_at_ms <= ? AND session_id IN\n (SELECT s.session_id FROM coordinator_auth_sessions s\n WHERE s.coordinator_id = ? AND s.expires_at_ms <= ?\n AND EXISTS (SELECT 1 FROM coordinator_auth_session_receipts r\n WHERE r.coordinator_id = s.coordinator_id AND r.session_id = s.session_id\n AND r.browser_transaction_hash = s.browser_transaction_hash AND r.link_id = s.link_id\n AND r.auth_config_revision = s.auth_config_revision AND r.created_at_ms = s.created_at_ms\n AND r.source = 'signin' AND r.attempt_id IS NULL AND r.purge_eligible = 1)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_browser_transactions b\n WHERE b.coordinator_id = s.coordinator_id AND b.browser_transaction_hash = s.browser_transaction_hash)\n ORDER BY s.expires_at_ms, s.session_id LIMIT ?)`;\nconst PURGE_GUARDED_SIGNIN_RECEIPTS_SQL = `DELETE FROM coordinator_auth_session_receipts\n WHERE coordinator_id = ? AND purge_eligible = 1 AND source = 'signin' AND attempt_id IS NULL\n AND created_at_ms <= ? AND browser_transaction_hash IN\n (SELECT r.browser_transaction_hash FROM coordinator_auth_session_receipts r\n WHERE r.coordinator_id = ? AND r.purge_eligible = 1 AND r.source = 'signin'\n AND r.attempt_id IS NULL AND r.created_at_ms <= ?\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_browser_transactions b\n WHERE b.coordinator_id = r.coordinator_id AND b.browser_transaction_hash = r.browser_transaction_hash)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_sessions s\n WHERE s.coordinator_id = r.coordinator_id AND s.session_id = r.session_id)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_sessions s\n WHERE s.coordinator_id = r.coordinator_id AND s.browser_transaction_hash = r.browser_transaction_hash)\n ORDER BY r.created_at_ms, r.browser_transaction_hash LIMIT ?)`;\n\n/** Optional persistence only. Future callers authenticate browser/OIDC/CSRF/admin;\n * this capability creates no routes, actors, enrollment, role, or sync permission.\n */\nexport class AuthSessionOperations\n\timplements CoordinatorAuthSessionStore, CoordinatorAuthAccountLinkAdminStore\n{\n\tconstructor(\n\t\tprivate readonly backend: AuthLinkBackend,\n\t\tprivate readonly clock: () => number = Date.now,\n\t) {}\n\tasync purgeAuthGuardedSigninSessions(\n\t\tscope: CoordinatorAuthSessionScope,\n\t\toptions?: CoordinatorAuthSessionPurgeOptions,\n\t): Promise<CoordinatorAuthSessionPurgeResult> {\n\t\treturn this.purgeGuardedSigninMetadata(\n\t\t\tscope,\n\t\t\toptions,\n\t\t\tPURGE_GUARDED_SIGNIN_SESSIONS_SQL,\n\t\t\tAUTH_GUARDED_SIGNIN_PURGE_GRACE_MS,\n\t\t);\n\t}\n\tasync purgeAuthGuardedSigninReceipts(\n\t\tscope: CoordinatorAuthSessionScope,\n\t\toptions?: CoordinatorAuthSessionPurgeOptions,\n\t): Promise<CoordinatorAuthSessionPurgeResult> {\n\t\treturn this.purgeGuardedSigninMetadata(\n\t\t\tscope,\n\t\t\toptions,\n\t\t\tPURGE_GUARDED_SIGNIN_RECEIPTS_SQL,\n\t\t\tAUTH_GUARDED_SIGNIN_RECEIPT_PURGE_AGE_MS,\n\t\t);\n\t}\n\tprivate async purgeGuardedSigninMetadata(\n\t\tscope: CoordinatorAuthSessionScope,\n\t\toptions: CoordinatorAuthSessionPurgeOptions | undefined,\n\t\tsql: string,\n\t\tageMs: number,\n\t): Promise<CoordinatorAuthSessionPurgeResult> {\n\t\tconst s = captureScope(scope);\n\t\tconst limit = capturePurgeLimit(options);\n\t\tif (!s || limit === null) return { kind: \"rejected\", error: \"invalid_input\" };\n\t\tconst cutoff = sessionNow(this.clock) - ageMs;\n\t\ttry {\n\t\t\tconst processedCount = await this.backend.run({\n\t\t\t\tsql,\n\t\t\t\tvalues: [s.coordinatorId, cutoff, s.coordinatorId, cutoff, limit],\n\t\t\t});\n\t\t\treturn { kind: \"purged\", processedCount, more: processedCount === limit };\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_session_persistence_error\");\n\t\t}\n\t}\n\tprivate async first<T>(statement: AuthLinkStatement): Promise<T | null> {\n\t\ttry {\n\t\t\treturn await this.backend.first<T>(statement);\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_session_persistence_error\");\n\t\t}\n\t}\n\tprivate async connectionSchema(): Promise<boolean> {\n\t\ttry {\n\t\t\treturn await hasConnectionSessionSchema(this.backend);\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_session_persistence_error\");\n\t\t}\n\t}\n\tprivate async batch(statements: AuthLinkStatement[]): Promise<void> {\n\t\ttry {\n\t\t\tawait this.backend.batch(statements);\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_session_persistence_error\");\n\t\t}\n\t}\n\tasync redeemAuthLinkSession(\n\t\t_input: CoordinatorAuthLinkSessionRedeemInput,\n\t\t_config: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthSessionIssueResult> {\n\t\t// Retired: this entry has no browser binder and cannot prove redemption.\n\t\treturn rejected(\"attempt_unavailable\");\n\t}\n\t/** Complete once while preserving the existing session and its own active account link. */\n\tasync preserveAuthLinkSessionCompletion(\n\t\tinput: CoordinatorAuthBoundLinkSessionRedeemInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<CoordinatorAuthLinkSessionPreserveResult> {\n\t\tconst c = captureBrowserConfig(config);\n\t\tconst i = captureIssue(input, [\"attemptId\", \"binderHash\"]);\n\t\tif (!c || !i || !isAuthControllerId(i.attemptId) || !isHash(i.binderHash))\n\t\t\treturn rejected(\"invalid_input\");\n\t\tif (!c.enabled) return rejected(\"auth_config_changed\");\n\t\tconst now = sessionNow(this.clock);\n\t\t// credentialHash names the existing live session, which may belong to another linked account.\n\t\t// Completion creates no receipt: it preserves that session and burns only this attempt.\n\t\tconst connections = await this.connectionSchema();\n\t\tlet changed: number;\n\t\ttry {\n\t\t\tchanged = await this.backend.run({\n\t\t\t\tsql: preserveCompletionSql({ connections }),\n\t\t\t\tvalues: [\n\t\t\t\t\t...(connections\n\t\t\t\t\t\t? [c.coordinatorId, c.coordinatorId, i.attemptId, c.coordinatorId, i.credentialHash]\n\t\t\t\t\t\t: []),\n\t\t\t\t\tc.coordinatorId,\n\t\t\t\t\ti.attemptId,\n\t\t\t\t\ti.browserTransactionHash,\n\t\t\t\t\tc.issuer,\n\t\t\t\t\tc.revision,\n\t\t\t\t\tnow,\n\t\t\t\t\tnow,\n\t\t\t\t\tnow,\n\t\t\t\t\tnow,\n\t\t\t\t\ti.binderHash,\n\t\t\t\t\tc.issuer,\n\t\t\t\t\tc.revision,\n\t\t\t\t\tc.redirectUri,\n\t\t\t\t\tnow,\n\t\t\t\t\tnow,\n\t\t\t\t\tnow,\n\t\t\t\t\tc.coordinatorId,\n\t\t\t\t\ti.credentialHash,\n\t\t\t\t\tc.issuer,\n\t\t\t\t\tc.revision,\n\t\t\t\t\tnow,\n\t\t\t\t\tnow,\n\t\t\t\t],\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_session_persistence_error\");\n\t\t}\n\t\tif (changed !== 1) return rejected(\"attempt_unavailable\");\n\t\tconst row = await this.first<{ state: string }>({\n\t\t\tsql: `SELECT state FROM coordinator_auth_link_attempts\n WHERE coordinator_id = ? AND attempt_id = ? AND browser_transaction_hash = ?\n AND issuer = ? AND auth_config_revision = ?`,\n\t\t\tvalues: [c.coordinatorId, i.attemptId, i.browserTransactionHash, c.issuer, c.revision],\n\t\t});\n\t\t// A failed post-commit read must not release cookies or pretend the burn rolled back.\n\t\tif (row?.state !== \"session_redeemed\") throw new Error(\"auth_session_persistence_incomplete\");\n\t\treturn { kind: \"preserved\" };\n\t}\n\t/** Admission binds a finalized link to its consumed original browser transaction. */\n\tasync redeemAuthLinkSessionWithBrowserTransaction(\n\t\tinput: CoordinatorAuthBoundLinkSessionRedeemInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<CoordinatorAuthSessionIssueResult> {\n\t\tconst c = captureBrowserConfig(config);\n\t\tconst i = captureIssue(input, [\"attemptId\", \"binderHash\"]);\n\t\tif (!c || !i || !isAuthControllerId(i.attemptId) || !isHash(i.binderHash))\n\t\t\treturn rejected(\"invalid_input\");\n\t\tif (!c.enabled) return rejected(\"auth_config_changed\");\n\t\tconst now = sessionNow(this.clock);\n\t\tconst sessionId = globalThis.crypto.randomUUID();\n\t\t// The receipt guard is the admission check; only its fresh winner can mint and consume.\n\t\tawait this.batch([\n\t\t\t{\n\t\t\t\tsql: boundRedeemSql({ connections: await this.connectionSchema() }),\n\t\t\t\tvalues: [\n\t\t\t\t\tsessionId,\n\t\t\t\t\tc.revision,\n\t\t\t\t\tnow,\n\t\t\t\t\tc.coordinatorId,\n\t\t\t\t\ti.attemptId,\n\t\t\t\t\ti.browserTransactionHash,\n\t\t\t\t\tc.issuer,\n\t\t\t\t\tc.revision,\n\t\t\t\t\tnow,\n\t\t\t\t\tnow,\n\t\t\t\t\tnow,\n\t\t\t\t\ti.binderHash,\n\t\t\t\t\tc.issuer,\n\t\t\t\t\tc.revision,\n\t\t\t\t\tc.redirectUri,\n\t\t\t\t\tnow,\n\t\t\t\t\tnow,\n\t\t\t\t\tnow,\n\t\t\t\t],\n\t\t\t},\n\t\t\tawait this.sessionInsert(i, c, sessionId),\n\t\t\t{\n\t\t\t\tsql: redeemConsumeSql({ connections: await this.connectionSchema() }),\n\t\t\t\tvalues: [c.coordinatorId, i.attemptId, i.browserTransactionHash, sessionId],\n\t\t\t},\n\t\t]);\n\t\tconst result = await this.issueReceipt(i, c, now, sessionId);\n\t\tif (result) return result;\n\t\treturn this.diagnoseRedeem(i.attemptId, i.browserTransactionHash, c, now);\n\t}\n\tasync signInWithAuthAccount(\n\t\t_input: CoordinatorAuthAccountSignInInput,\n\t\t_config: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthSessionIssueResult> {\n\t\t// Retired: trusted account JSON alone cannot bypass consumed-browser proof.\n\t\treturn rejected(\"transaction_unavailable\");\n\t}\n\t/** Admission only; the caller has already verified JWT, cookie binding and CSRF. */\n\tasync signInWithConsumedBrowserTransaction(\n\t\tinput: CoordinatorAuthAccountSignInInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<CoordinatorAuthSessionIssueResult> {\n\t\tconst c = captureBrowserConfig(config);\n\t\tconst i = captureIssue(input, [\"account\"]);\n\t\tif (!c || !i) return rejected(\"invalid_input\");\n\t\tconst account = parseCoordinatorAccountReference(capture(i.account, [\"issuer\", \"subject\"]), {\n\t\t\tissuer: c.issuer,\n\t\t});\n\t\tif (!account.ok) return rejected(\"invalid_input\");\n\t\tif (!c.enabled) return rejected(\"auth_config_changed\");\n\t\tconst now = sessionNow(this.clock);\n\t\tconst sessionId = globalThis.crypto.randomUUID();\n\t\tconst transactionValues = [\n\t\t\tc.coordinatorId,\n\t\t\ti.browserTransactionHash,\n\t\t\tc.issuer,\n\t\t\tc.revision,\n\t\t\tc.redirectUri,\n\t\t\tnow,\n\t\t\tnow,\n\t\t\tnow,\n\t\t];\n\t\t// Admission and minting share one atomic batch, not a read-then-insert race.\n\t\t// Future-born current-config sessions reserve slots until they become readable.\n\t\tconst connections = await this.connectionSchema();\n\t\tawait this.batch([\n\t\t\t{\n\t\t\t\tsql: consumedSigninReceiptSql({ connections }),\n\t\t\t\tvalues: [\n\t\t\t\t\t...(connections\n\t\t\t\t\t\t? [c.coordinatorId, account.account.issuer, account.account.subject]\n\t\t\t\t\t\t: []),\n\t\t\t\t\tsessionId,\n\t\t\t\t\tc.revision,\n\t\t\t\t\tnow,\n\t\t\t\t\t...transactionValues,\n\t\t\t\t\taccount.account.subject,\n\t\t\t\t\tnow,\n\t\t\t\t],\n\t\t\t},\n\t\t\tawait this.sessionInsert(i, c, sessionId, { connections }),\n\t\t]);\n\t\tconst result = await this.issueReceipt(i, c, now, sessionId, { connections });\n\t\tif (result) return result;\n\t\tconst used = await this.first({\n\t\t\tsql: \"SELECT 1 FROM coordinator_auth_link_attempts WHERE coordinator_id = ? AND browser_transaction_hash = ?\",\n\t\t\tvalues: [c.coordinatorId, i.browserTransactionHash],\n\t\t});\n\t\tif (used) return rejected(\"browser_transaction_used\");\n\t\t// These reads choose rejection labels only; they never admit or reuse a receipt.\n\t\tconst transaction = await this.first({\n\t\t\tsql: `SELECT 1 FROM coordinator_auth_browser_transactions b WHERE ${CONSUMED_BROWSER_GUARD_SQL}`,\n\t\t\tvalues: transactionValues,\n\t\t});\n\t\tif (!transaction) return rejected(\"transaction_unavailable\");\n\t\tconst link = await this.first({\n\t\t\tsql: \"SELECT 1 FROM coordinator_auth_account_links WHERE coordinator_id = ? AND issuer = ? AND subject = ? AND revoked_at_ms IS NULL\",\n\t\t\tvalues: [c.coordinatorId, c.issuer, account.account.subject],\n\t\t});\n\t\tif (!link) return rejected(\"account_not_linked\");\n\t\treturn rejected(\"session_limited\");\n\t}\n\tprivate async sessionInsert(\n\t\ti: { credentialHash: string; browserTransactionHash: string },\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tsessionId: string,\n\t\toptions?: { connections: boolean },\n\t): Promise<AuthLinkStatement> {\n\t\treturn {\n\t\t\tsql: sessionInsertSql({\n\t\t\t\tconnections: options?.connections ?? (await this.connectionSchema()),\n\t\t\t}),\n\t\t\tvalues: [i.credentialHash, c.coordinatorId, i.browserTransactionHash, sessionId],\n\t\t};\n\t}\n\tprivate async issueReceipt(\n\t\ti: { credentialHash: string; browserTransactionHash: string },\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t\tsessionId: string,\n\t\toptions?: { connections: boolean },\n\t): Promise<CoordinatorAuthSessionIssueResult | null> {\n\t\tconst receipt = await this.first<ReceiptRow>({\n\t\t\tsql: \"SELECT session_id FROM coordinator_auth_session_receipts WHERE coordinator_id = ? AND browser_transaction_hash = ?\",\n\t\t\tvalues: [c.coordinatorId, i.browserTransactionHash],\n\t\t});\n\t\tif (!receipt) {\n\t\t\tconst orphan = await this.first({\n\t\t\t\tsql: \"SELECT 1 FROM coordinator_auth_sessions WHERE coordinator_id = ? AND session_id = ?\",\n\t\t\t\tvalues: [c.coordinatorId, sessionId],\n\t\t\t});\n\t\t\tif (orphan) throw new Error(\"auth_session_persistence_incomplete\");\n\t\t\treturn null;\n\t\t}\n\t\tif (receipt.session_id !== sessionId) return rejected(\"browser_transaction_used\");\n\t\t// Reuse only the stricter SQL shape; the SELECT still checks current readiness.\n\t\tconst connections = options?.connections === true || (await this.connectionSchema());\n\t\tconst row = await this.first<SessionRow>({\n\t\t\tsql: `${issueReadSql({ connections })}${connections ? ` AND ${CONNECTION_NOT_REVOKED_SQL}` : \"\"}`,\n\t\t\tvalues: [\n\t\t\t\tc.coordinatorId,\n\t\t\t\ti.browserTransactionHash,\n\t\t\t\tsessionId,\n\t\t\t\ti.credentialHash,\n\t\t\t\tc.revision,\n\t\t\t\tnow,\n\t\t\t\tnow + AUTH_SESSION_TTL_MS,\n\t\t\t\tc.issuer,\n\t\t\t],\n\t\t});\n\t\tif (!row) throw new Error(\"auth_session_persistence_incomplete\");\n\t\treturn { kind: \"issued\", session: dto(row) };\n\t}\n\tprivate async diagnoseRedeem(\n\t\tattemptId: string,\n\t\tbrowserHash: string,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t): Promise<CoordinatorAuthSessionIssueResult> {\n\t\tconst row = await this.first<RedeemDiagnosis>({\n\t\t\tsql: \"SELECT browser_transaction_hash, state, issuer, auth_config_revision, finalized_at_ms, expires_at_ms FROM coordinator_auth_link_attempts WHERE coordinator_id = ? AND attempt_id = ?\",\n\t\t\tvalues: [c.coordinatorId, attemptId],\n\t\t});\n\t\tif (!row || row.browser_transaction_hash !== browserHash)\n\t\t\treturn rejected(\"attempt_unavailable\");\n\t\tif (row.issuer !== c.issuer || row.auth_config_revision !== c.revision)\n\t\t\treturn rejected(\"auth_config_changed\");\n\t\tif (row.state !== \"finalized\" || row.finalized_at_ms === null || now < row.finalized_at_ms)\n\t\t\treturn rejected(\"attempt_unavailable\");\n\t\tif (now >= row.expires_at_ms || now >= row.finalized_at_ms + AUTH_LINK_REDEEM_WINDOW_MS)\n\t\t\treturn rejected(\"redeem_window_expired\");\n\t\treturn rejected(\"attempt_unavailable\");\n\t}\n\tasync readAuthSession(\n\t\tcredentialHash: string,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthSession | null> {\n\t\tconst c = captureConfig(config);\n\t\tif (!c?.enabled || !isHash(credentialHash)) return null;\n\t\tconst now = sessionNow(this.clock);\n\t\tconst connections = await this.connectionSchema();\n\t\tconst row = await this.first<SessionRow>({\n\t\t\tsql: `SELECT s.session_id, s.identity_id, s.link_id, s.issuer, s.subject, s.expires_at_ms FROM coordinator_auth_sessions s JOIN coordinator_auth_account_links l ON ${authSessionLinkMatchSql({ connections })}\n WHERE ${AUTH_SESSION_LIVE_GUARD_SQL}${connections ? ` AND ${CONNECTION_NOT_REVOKED_SQL}` : \"\"}`,\n\t\t\tvalues: [c.coordinatorId, credentialHash, c.issuer, c.revision, now, now],\n\t\t});\n\t\treturn row ? dto(row) : null;\n\t}\n\tasync signOutAuthSession(\n\t\tcredentialHash: string,\n\t\tscope: CoordinatorAuthSessionScope,\n\t): Promise<CoordinatorAuthSessionSignOutResult> {\n\t\tconst s = captureScope(scope);\n\t\tif (!s || !isHash(credentialHash)) return { kind: \"rejected\", error: \"invalid_input\" };\n\t\tconst now = sessionNow(this.clock);\n\t\tawait this.batch([\n\t\t\t{\n\t\t\t\tsql: \"UPDATE coordinator_auth_sessions SET revoked_at_ms = ? WHERE coordinator_id = ? AND credential_hash = ? AND revoked_at_ms IS NULL\",\n\t\t\t\tvalues: [now, s.coordinatorId, credentialHash],\n\t\t\t},\n\t\t]);\n\t\treturn { kind: \"signed_out\" };\n\t}\n\t/** Configured-admin authentication is the caller's prerequisite, never an actor label. */\n\tasync revokeAuthAccountLink(\n\t\tinput: { linkId: string },\n\t\tscope: CoordinatorAuthSessionScope,\n\t): Promise<CoordinatorAuthAccountLinkRevokeResult> {\n\t\tconst s = captureScope(scope);\n\t\tconst i = capture(input, [\"linkId\"]);\n\t\tif (!s || !i || !isAuthControllerId(i.linkId))\n\t\t\treturn { kind: \"rejected\", error: \"invalid_input\" };\n\t\tconst now = sessionNow(this.clock);\n\t\tif (await this.connectionSchema()) {\n\t\t\tconst historical = await this.first({\n\t\t\t\tsql: `SELECT 1 FROM coordinator_auth_account_connection_history l WHERE l.coordinator_id = ? AND l.link_id = ? AND ${authAccountLinkProvenanceSql(\"l\", { connections: true })}`,\n\t\t\t\tvalues: [s.coordinatorId, i.linkId],\n\t\t\t});\n\t\t\tif (historical) {\n\t\t\t\tawait this.batch(historicalRevocationStatements(s.coordinatorId, i.linkId, now));\n\t\t\t\tfor (const check of historicalRevocationChecks(s.coordinatorId, i.linkId)) {\n\t\t\t\t\tconst held = await this.first<{ ok: number }>(check);\n\t\t\t\t\tif (held?.ok !== 1) throw new Error(\"auth_session_persistence_incomplete\");\n\t\t\t\t}\n\t\t\t\treturn { kind: \"revoked\" };\n\t\t\t}\n\t\t}\n\t\tconst connections = await this.connectionSchema();\n\t\tawait this.batch(revokeStatements(i.linkId, s.coordinatorId, now, { connections }));\n\t\tconst link = await this.first<{ revoked_at_ms: number | null }>({\n\t\t\tsql: `SELECT l.revoked_at_ms FROM coordinator_auth_account_links l WHERE l.coordinator_id = ? AND l.link_id = ? AND ${authAccountLinkProvenanceSql(\"l\", { connections })}`,\n\t\t\tvalues: [s.coordinatorId, i.linkId],\n\t\t});\n\t\tif (!link) return { kind: \"rejected\", error: \"link_unavailable\" };\n\t\tconst receipt = await this.first({\n\t\t\tsql: revokeReadSql({ connections }),\n\t\t\tvalues: [s.coordinatorId, i.linkId],\n\t\t});\n\t\tif (link.revoked_at_ms === null || !receipt)\n\t\t\tthrow new Error(\"auth_session_persistence_incomplete\");\n\t\treturn { kind: \"revoked\" };\n\t}\n}\nfunction auditMatch(options: { connections: boolean }) {\n\treturn `a.coordinator_id = l.coordinator_id AND a.link_id = l.link_id AND a.action = 'link_created'\n AND a.attempt_id = l.attempt_id AND a.identity_id = l.identity_id AND a.controller_attestation_id IS l.controller_attestation_id\n AND a.authority_kind = l.authority_kind AND a.device_claim_id IS l.device_claim_id AND ${authAccountLinkProvenanceSql(\"l\", options)}\n AND a.auth_config_revision = l.auth_config_revision AND a.created_at_ms = l.created_at_ms`;\n}\nfunction revokeStatements(\n\tlinkId: string,\n\tcoordinatorId: string,\n\tnow: number,\n\toptions: { connections: boolean },\n): AuthLinkStatement[] {\n\tconst ACCOUNT_PROVENANCE = authAccountLinkProvenanceSql(\"l\", options),\n\t\tAUDIT_MATCH = auditMatch(options);\n\treturn [\n\t\t{\n\t\t\tsql: `UPDATE coordinator_auth_account_links AS l SET revoked_at_ms = ? WHERE l.coordinator_id = ? AND l.link_id = ? AND l.revoked_at_ms IS NULL AND ${ACCOUNT_PROVENANCE}`,\n\t\t\tvalues: [now, coordinatorId, linkId],\n\t\t},\n\t\t{\n\t\t\tsql: `INSERT INTO coordinator_auth_link_audit_log (coordinator_id, link_id, action, attempt_id, identity_id, group_id, device_id, fingerprint, controller_attestation_id, auth_config_revision, created_at_ms, authority_kind, device_claim_id)\n SELECT l.coordinator_id, l.link_id, 'link_revoked', a.attempt_id, a.identity_id, a.group_id, a.device_id, a.fingerprint, a.controller_attestation_id, a.auth_config_revision, l.revoked_at_ms, l.authority_kind, l.device_claim_id\n FROM coordinator_auth_account_links l JOIN coordinator_auth_link_audit_log a ON ${AUDIT_MATCH}\n WHERE l.coordinator_id = ? AND l.link_id = ? AND l.revoked_at_ms IS NOT NULL\n ON CONFLICT(coordinator_id, link_id, action) DO NOTHING`,\n\t\t\tvalues: [coordinatorId, linkId],\n\t\t},\n\t];\n}\nfunction revokeReadSql(options: { connections: boolean }) {\n\treturn `SELECT 1 FROM coordinator_auth_account_links l JOIN coordinator_auth_link_audit_log a ON ${auditMatch(options)}\n JOIN coordinator_auth_link_audit_log r ON r.coordinator_id = l.coordinator_id AND r.link_id = l.link_id AND r.action = 'link_revoked'\n AND r.attempt_id = a.attempt_id AND r.identity_id = a.identity_id AND r.group_id = a.group_id AND r.device_id = a.device_id\n AND r.fingerprint = a.fingerprint AND r.controller_attestation_id IS a.controller_attestation_id AND r.authority_kind = a.authority_kind AND r.device_claim_id IS a.device_claim_id AND r.auth_config_revision = a.auth_config_revision AND r.created_at_ms = l.revoked_at_ms\n WHERE l.coordinator_id = ? AND l.link_id = ? AND l.revoked_at_ms IS NOT NULL`;\n}\n","import {\n\tconnectionProfileColumns,\n\thasConnectionSessionSchema,\n} from \"./coordinator-account-connection-session.js\";\nimport { CONNECTION_NOT_REVOKED_SQL } from \"./coordinator-account-connection-storage.js\";\nimport {\n\tAUTH_ACCOUNT_PROFILE_WRITE_WINDOW_MS,\n\ttype CoordinatorAuthAccountProfileClearResult,\n\ttype CoordinatorAuthAccountProfileInput,\n\ttype CoordinatorAuthAccountProfileStore,\n\ttype CoordinatorAuthAccountProfileWriteResult,\n\ttype CoordinatorAuthSessionAccount,\n} from \"./coordinator-auth-account-profile-contract.js\";\nimport { isCoordinatorAccountIssuer } from \"./coordinator-auth-contract.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport type { CoordinatorAuthLinkConfig } from \"./coordinator-auth-link-contract.js\";\nimport { authAccountLinkProvenanceSql } from \"./coordinator-auth-link-provenance.js\";\nimport { authPersistenceError } from \"./coordinator-auth-schema.js\";\nimport {\n\tAUTH_SESSION_LINK_MATCH_SQL,\n\tAUTH_SESSION_LIVE_GUARD_SQL,\n\tauthSessionLinkMatchSql,\n\tauthSessionNow,\n} from \"./coordinator-auth-session.js\";\nimport type { CoordinatorOidcProfile } from \"./coordinator-oidc.js\";\n\nexport * from \"./coordinator-auth-account-profile-contract.js\";\n\nfunction revokedProfileTargetsSql(options: { connections: boolean }): string {\n\tconst current =\n\t\t\"SELECT l.link_id FROM coordinator_auth_account_links l WHERE l.coordinator_id=? AND l.revoked_at_ms IS NOT NULL\";\n\tif (!options.connections) return `${current} AND l.link_id=?`;\n\treturn `WITH requested AS MATERIALIZED (\n SELECT l.coordinator_id,l.identity_id FROM coordinator_auth_account_connection_history l\n WHERE l.coordinator_id=? AND l.link_id=? AND l.revoked_at_ms IS NOT NULL\n AND ${authAccountLinkProvenanceSql(\"l\", { connections: true })})\n ${current} AND ${authAccountLinkProvenanceSql(\"l\", { connections: true })}\n AND (l.link_id=? OR EXISTS (SELECT 1 FROM requested h WHERE h.coordinator_id=l.coordinator_id AND h.identity_id=l.identity_id))`;\n}\n\nfunction hasPlainPrototype(value: object): boolean {\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\nfunction capture(\n\tvalue: unknown,\n\toptions: { fields: readonly string[]; required: boolean; plain?: boolean },\n): Record<string, unknown> | null {\n\tif (!value || typeof value !== \"object\") return null;\n\ttry {\n\t\tif (Array.isArray(value)) return null;\n\t\tif (options.plain && !hasPlainPrototype(value)) return null;\n\t\tconst result: Record<string, unknown> = Object.create(null);\n\t\tfor (const key of options.fields) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\t\tif (!descriptor) {\n\t\t\t\tif (options.required) return null;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!Object.hasOwn(descriptor, \"value\")) return null;\n\t\t\tresult[key] = descriptor.value;\n\t\t}\n\t\treturn result;\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction isHash(value: unknown): value is string {\n\treturn typeof value === \"string\" && /^[0-9a-f]{64}$/.test(value);\n}\nfunction captureConfig(value: unknown): CoordinatorAuthLinkConfig | null {\n\tconst c = capture(value, {\n\t\tfields: [\"coordinatorId\", \"issuer\", \"revision\", \"enabled\"],\n\t\trequired: true,\n\t});\n\tif (\n\t\t!c ||\n\t\t!isAuthControllerId(c.coordinatorId) ||\n\t\t!isCoordinatorAccountIssuer(c.issuer) ||\n\t\t!isHash(c.revision) ||\n\t\ttypeof c.enabled !== \"boolean\"\n\t)\n\t\treturn null;\n\treturn {\n\t\tcoordinatorId: c.coordinatorId,\n\t\tissuer: c.issuer,\n\t\trevision: c.revision,\n\t\tenabled: c.enabled,\n\t};\n}\nfunction optionalText(value: unknown, maxLength: number): string | undefined {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\tvalue.length === 0 ||\n\t\tvalue.length > maxLength ||\n\t\tvalue.trim().length === 0 ||\n\t\t/[\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(value)\n\t)\n\t\treturn undefined;\n\treturn value;\n}\nfunction optionalPicture(value: unknown): string | undefined {\n\tconst text = optionalText(value, 2048);\n\tif (\n\t\t!text ||\n\t\ttext.trim() !== text ||\n\t\ttext.includes(\"\\\\\") ||\n\t\ttext.includes(\"#\") ||\n\t\t!/^https:\\/\\//i.test(text) ||\n\t\t/^https:\\/\\/[^/?#]*@/i.test(text)\n\t)\n\t\treturn undefined;\n\ttry {\n\t\tconst url = new URL(text);\n\t\tif (url.protocol !== \"https:\" || url.username || url.password || url.hash) return undefined;\n\t\tconst canonical = url.href;\n\t\treturn optionalText(canonical, 2048);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\nfunction projectProfile(fields: Record<string, unknown>): CoordinatorOidcProfile {\n\tconst profile: CoordinatorOidcProfile = {};\n\tconst displayName = optionalText(fields.displayName, 256);\n\tconst email = optionalText(fields.email, 320);\n\tconst pictureUrl = optionalPicture(fields.pictureUrl);\n\tif (displayName !== undefined) profile.displayName = displayName;\n\tif (email !== undefined) {\n\t\tprofile.email = email;\n\t\tif (typeof fields.emailVerified === \"boolean\") profile.emailVerified = fields.emailVerified;\n\t}\n\tif (pictureUrl !== undefined) profile.pictureUrl = pictureUrl;\n\treturn profile;\n}\n/** Capture display claims without invoking accessors or retaining unknown fields. */\nexport function captureAuthAccountProfile(value: unknown): CoordinatorOidcProfile | null {\n\tconst fields = capture(value, {\n\t\tfields: [\"displayName\", \"email\", \"emailVerified\", \"pictureUrl\"],\n\t\trequired: false,\n\t\tplain: true,\n\t});\n\treturn fields ? projectProfile(fields) : null;\n}\ninterface AccountRow {\n\tsession_id: string;\n\tidentity_id: string;\n\tlink_id: string;\n\tissuer: string;\n\tsubject: string;\n\texpires_at_ms: number;\n\tdisplay_name: unknown;\n\temail: unknown;\n\temail_verified: unknown;\n\tpicture_url: unknown;\n}\nfunction sessionFromSql(options: { connections: boolean }) {\n\treturn `FROM coordinator_auth_sessions s JOIN coordinator_auth_account_links l ON ${authSessionLinkMatchSql(options)}`;\n}\nconst SESSION_FROM_SQL = `FROM coordinator_auth_sessions s JOIN coordinator_auth_account_links l ON ${AUTH_SESSION_LINK_MATCH_SQL}`;\nfunction profileSourceSql(options: { connections: boolean }) {\n\treturn `${sessionFromSql(options)}\n JOIN coordinator_auth_session_receipts r ON r.coordinator_id = s.coordinator_id\n AND r.session_id = s.session_id AND r.browser_transaction_hash = s.browser_transaction_hash\n AND r.link_id = s.link_id AND r.auth_config_revision = s.auth_config_revision AND r.created_at_ms = s.created_at_ms\n WHERE ${AUTH_SESSION_LIVE_GUARD_SQL} AND r.source = 'signin' AND r.attempt_id IS NULL\n ${\n\t\toptions.connections\n\t\t\t? `AND ${CONNECTION_NOT_REVOKED_SQL} AND r.source_order IS NOT NULL AND NOT EXISTS (\n SELECT 1 FROM coordinator_auth_link_profiles b JOIN coordinator_account_change_attempts x ON x.coordinator_id = b.coordinator_id AND x.attempt_id = b.source_change_attempt_id\n WHERE b.coordinator_id = l.coordinator_id AND b.link_id = l.link_id AND x.target_link_id = l.link_id AND x.intent = 'refresh' AND x.state = 'completed' AND x.browser_order = b.source_order AND b.source_order >= r.source_order)`\n\t\t\t: \"\"\n}`;\n}\nfunction profileWriteSql(options: { connections: boolean }) {\n\treturn `INSERT INTO coordinator_auth_account_profiles\n (coordinator_id, link_id, display_name, email, email_verified, picture_url, source_session_id, source_signed_in_at_ms${options.connections ? \",source_order\" : \"\"})\n SELECT s.coordinator_id, s.link_id, ?, ?, ?, ?, s.session_id, s.created_at_ms${options.connections ? \",r.source_order\" : \"\"}\n ${profileSourceSql(options)} AND ? < s.created_at_ms + ${AUTH_ACCOUNT_PROFILE_WRITE_WINDOW_MS}\n ON CONFLICT(coordinator_id, link_id) DO UPDATE SET\n display_name = excluded.display_name, email = excluded.email,\n email_verified = excluded.email_verified, picture_url = excluded.picture_url,\n source_session_id = excluded.source_session_id, source_signed_in_at_ms = excluded.source_signed_in_at_ms${options.connections ? \",source_order = excluded.source_order\" : \"\"}\n WHERE ${options.connections ? \"excluded.source_order > coalesce(coordinator_auth_account_profiles.source_order,0)\" : \"excluded.source_signed_in_at_ms > coordinator_auth_account_profiles.source_signed_in_at_ms\"}`;\n}\nfunction profileReadSql(options: { connections: boolean }) {\n\treturn `SELECT s.session_id, s.identity_id, s.link_id, s.issuer, s.subject, s.expires_at_ms,\n ${\n\t\toptions.connections\n\t\t\t? connectionProfileColumns(\"p\")\n\t\t\t: `CASE WHEN p.link_id IS NOT NULL THEN p.display_name ELSE b.display_name END AS display_name,\n CASE WHEN p.link_id IS NOT NULL THEN p.email ELSE b.email END AS email,\n CASE WHEN p.link_id IS NOT NULL THEN p.email_verified ELSE b.email_verified END AS email_verified,\n CASE WHEN p.link_id IS NOT NULL THEN p.picture_url ELSE b.picture_url END AS picture_url`\n}\n ${sessionFromSql(options)} LEFT JOIN coordinator_auth_account_profiles p\n ON p.coordinator_id = s.coordinator_id AND p.link_id = s.link_id\n LEFT JOIN coordinator_auth_link_profiles b ON b.coordinator_id = l.coordinator_id AND b.link_id = l.link_id\n AND b.attempt_id = l.attempt_id AND b.issuer = l.issuer AND b.subject = l.subject\n AND b.auth_config_revision = l.auth_config_revision\n WHERE ${AUTH_SESSION_LIVE_GUARD_SQL}${options.connections ? ` AND ${CONNECTION_NOT_REVOKED_SQL}` : \"\"}`;\n}\nconst PROFILE_RECORDED_SQL = `SELECT 1 ${SESSION_FROM_SQL}\n JOIN coordinator_auth_account_profiles p ON p.coordinator_id = s.coordinator_id AND p.link_id = s.link_id\n AND p.source_session_id = s.session_id\n WHERE ${AUTH_SESSION_LIVE_GUARD_SQL}`;\nconst ORDERED_PROFILE_RECORDED_SQL = `SELECT 1 ${profileSourceSql({ connections: true })}\n AND EXISTS (SELECT 1 FROM coordinator_auth_account_profiles p\n WHERE p.coordinator_id=s.coordinator_id AND p.link_id=s.link_id\n AND p.source_session_id=s.session_id AND p.source_signed_in_at_ms=s.created_at_ms\n AND p.source_order=r.source_order)`;\nfunction liveValues(\n\tc: CoordinatorAuthLinkConfig,\n\tcredentialHash: string,\n\tnow: number,\n): AuthLinkStatement[\"values\"] {\n\treturn [c.coordinatorId, credentialHash, c.issuer, c.revision, now, now];\n}\n\n/** Optional verified display snapshots only. No JWT/cookie verification or authority changes.\n * Purging stays separate from revocation: an older database lacking this table must\n * never prevent revocation. Future public handlers must authenticate the admin first.\n */\nexport class AuthAccountProfileOperations implements CoordinatorAuthAccountProfileStore {\n\tconstructor(\n\t\tprivate readonly backend: AuthLinkBackend,\n\t\tprivate readonly clock: () => number = Date.now,\n\t) {}\n\tprivate async first<T>(statement: AuthLinkStatement): Promise<T | null> {\n\t\ttry {\n\t\t\treturn await this.backend.first<T>(statement);\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_account_profile_persistence_error\");\n\t\t}\n\t}\n\tprivate async connectionSchema(): Promise<boolean> {\n\t\ttry {\n\t\t\treturn await hasConnectionSessionSchema(this.backend);\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_account_profile_persistence_error\");\n\t\t}\n\t}\n\tprivate async run(statement: AuthLinkStatement): Promise<number> {\n\t\ttry {\n\t\t\treturn await this.backend.run(statement);\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_account_profile_persistence_error\");\n\t\t}\n\t}\n\tasync recordAuthAccountProfile(\n\t\tinput: CoordinatorAuthAccountProfileInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthAccountProfileWriteResult> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = capture(input, { fields: [\"credentialHash\", \"profile\"], required: true });\n\t\tif (!c || !i || !isHash(i.credentialHash)) return { kind: \"rejected\", error: \"invalid_input\" };\n\t\tconst fields = capture(i.profile, {\n\t\t\tfields: [\"displayName\", \"email\", \"emailVerified\", \"pictureUrl\"],\n\t\t\trequired: false,\n\t\t\tplain: true,\n\t\t});\n\t\tif (!fields) return { kind: \"rejected\", error: \"invalid_input\" };\n\t\tif (!c.enabled) return { kind: \"rejected\", error: \"auth_config_changed\" };\n\t\tconst profile = projectProfile(fields);\n\t\tconst now = authSessionNow(this.clock);\n\t\tconst connections = await this.connectionSchema();\n\t\tlet verified: number | null = null;\n\t\tif (profile.emailVerified !== undefined) verified = Number(profile.emailVerified);\n\t\tconst changed = await this.run({\n\t\t\tsql: profileWriteSql({ connections }),\n\t\t\tvalues: [\n\t\t\t\tprofile.displayName ?? null,\n\t\t\t\tprofile.email ?? null,\n\t\t\t\tverified,\n\t\t\t\tprofile.pictureUrl ?? null,\n\t\t\t\t...liveValues(c, i.credentialHash, now),\n\t\t\t\tnow,\n\t\t\t],\n\t\t});\n\t\tif (connections && changed !== 0) return { kind: changed === 1 ? \"recorded\" : \"not_recorded\" };\n\t\tconst recorded = await this.first({\n\t\t\tsql: connections ? ORDERED_PROFILE_RECORDED_SQL : PROFILE_RECORDED_SQL,\n\t\t\tvalues: liveValues(c, i.credentialHash, authSessionNow(this.clock)),\n\t\t});\n\t\treturn { kind: recorded ? \"recorded\" : \"not_recorded\" };\n\t}\n\tasync readAuthSessionAccount(\n\t\tcredentialHash: string,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthSessionAccount | null> {\n\t\tconst c = captureConfig(config);\n\t\tif (!c?.enabled || !isHash(credentialHash)) return null;\n\t\tconst row = await this.first<AccountRow>({\n\t\t\tsql: profileReadSql({ connections: await this.connectionSchema() }),\n\t\t\tvalues: liveValues(c, credentialHash, authSessionNow(this.clock)),\n\t\t});\n\t\tif (!row) return null;\n\t\tlet emailVerified: boolean | undefined;\n\t\tif (row.email_verified === 0) emailVerified = false;\n\t\tif (row.email_verified === 1) emailVerified = true;\n\t\treturn {\n\t\t\tsession: {\n\t\t\t\tsessionId: row.session_id,\n\t\t\t\tidentityId: row.identity_id,\n\t\t\t\tlinkId: row.link_id,\n\t\t\t\taccount: { issuer: row.issuer, subject: row.subject },\n\t\t\t\texpiresAtMs: row.expires_at_ms,\n\t\t\t},\n\t\t\tprofile: projectProfile({\n\t\t\t\tdisplayName: row.display_name,\n\t\t\t\temail: row.email,\n\t\t\t\temailVerified,\n\t\t\t\tpictureUrl: row.picture_url,\n\t\t\t}),\n\t\t};\n\t}\n\tasync clearRevokedAuthAccountProfile(\n\t\tinput: { linkId: string },\n\t\tscope: { coordinatorId: string },\n\t): Promise<CoordinatorAuthAccountProfileClearResult> {\n\t\tconst i = capture(input, { fields: [\"linkId\"], required: true });\n\t\tconst s = capture(scope, { fields: [\"coordinatorId\"], required: true });\n\t\tif (!i || !s || !isAuthControllerId(i.linkId) || !isAuthControllerId(s.coordinatorId))\n\t\t\treturn { kind: \"rejected\", error: \"invalid_input\" };\n\t\tconst connections = await this.connectionSchema();\n\t\tconst targets = revokedProfileTargetsSql({ connections });\n\t\tconst pins = [s.coordinatorId, i.linkId];\n\t\tconst values = connections ? [s.coordinatorId, ...pins, ...pins] : [s.coordinatorId, ...pins];\n\t\tlet deletedCount = 0;\n\t\tfor (const table of [\"coordinator_auth_account_profiles\", \"coordinator_auth_link_profiles\"]) {\n\t\t\tdeletedCount += await this.run({\n\t\t\t\tsql: `DELETE FROM ${table} WHERE coordinator_id=? AND link_id IN (${targets})`,\n\t\t\t\tvalues,\n\t\t\t});\n\t\t}\n\t\treturn { kind: \"cleared\", deletedCount };\n\t}\n}\n","import type { AuthLinkBackend } from \"./coordinator-auth-link.js\";\n\nexport const HEADLESS_CODE_LIMITS_TABLE = \"coordinator_headless_link_code_limits\";\nexport const HEADLESS_LINK_PROVENANCE_TABLE = \"coordinator_headless_link_provenance\";\n\n/**\n * Additive storage for headless account linking. The definitions name only\n * their own tables: the auth readiness checks reject any unknown table, view or\n * trigger whose SQL mentions an auth table, and any object named with an auth\n * table's prefix. That is why provenance has no foreign keys.\n *\n * Mirror: packages/cloudflare-coordinator-worker/migrations/0043_add_headless_account_linking.sql\n * (generated from these statements; coordinator-auth-headless-schema.test.ts checks parity).\n */\nexport const HEADLESS_LINK_SCHEMA_STATEMENTS: readonly string[] = Object.freeze([\n\t`CREATE TABLE IF NOT EXISTS ${HEADLESS_CODE_LIMITS_TABLE} (\n coordinator_id TEXT NOT NULL CHECK (typeof(coordinator_id) = 'text' AND length(coordinator_id) BETWEEN 1 AND 256),\n scope TEXT NOT NULL CHECK (scope IN ('client','coordinator')),\n key_hash TEXT NOT NULL CHECK ((scope = 'coordinator' AND key_hash = '')\n OR (scope = 'client' AND length(key_hash) = 64 AND key_hash NOT GLOB '*[^0-9a-f]*')),\n window_start_ms INTEGER NOT NULL CHECK (typeof(window_start_ms) = 'integer'\n AND window_start_ms BETWEEN 0 AND 9007199254740991),\n failures INTEGER NOT NULL CHECK (typeof(failures) = 'integer' AND failures BETWEEN 1 AND 9007199254740991),\n PRIMARY KEY (coordinator_id, scope, key_hash)\n ) WITHOUT ROWID;`,\n\t`CREATE TABLE IF NOT EXISTS ${HEADLESS_LINK_PROVENANCE_TABLE} (\n coordinator_id TEXT NOT NULL,\n link_id TEXT NOT NULL,\n identity_id TEXT NOT NULL,\n issuer TEXT NOT NULL,\n subject TEXT NOT NULL,\n attempt_id TEXT NOT NULL,\n created_at_ms INTEGER NOT NULL CHECK (typeof(created_at_ms) = 'integer' AND created_at_ms >= 0),\n PRIMARY KEY (coordinator_id, link_id),\n UNIQUE (coordinator_id, attempt_id)\n ) WITHOUT ROWID;`,\n\t`CREATE INDEX IF NOT EXISTS idx_headless_link_provenance_account\n ON ${HEADLESS_LINK_PROVENANCE_TABLE} (coordinator_id, issuer, subject, identity_id, created_at_ms);`,\n\t`CREATE TRIGGER IF NOT EXISTS headless_link_provenance_immutable\n BEFORE UPDATE ON ${HEADLESS_LINK_PROVENANCE_TABLE}\n BEGIN SELECT RAISE(ABORT,'headless_link_provenance_immutable'); END;`,\n\t// Rebind refuses headless-linked accounts by finding this row, so losing it would lift the block.\n\t`CREATE TRIGGER IF NOT EXISTS headless_link_provenance_retained\n BEFORE DELETE ON ${HEADLESS_LINK_PROVENANCE_TABLE}\n BEGIN SELECT RAISE(ABORT,'headless_link_provenance_retained'); END;`,\n\t// REPLACE conflict resolution deletes without firing delete triggers unless recursive triggers are on.\n\t`CREATE TRIGGER IF NOT EXISTS headless_link_provenance_no_replace\n BEFORE INSERT ON ${HEADLESS_LINK_PROVENANCE_TABLE}\n WHEN EXISTS (SELECT 1 FROM ${HEADLESS_LINK_PROVENANCE_TABLE} p WHERE p.coordinator_id = NEW.coordinator_id\n AND (p.link_id = NEW.link_id OR p.attempt_id = NEW.attempt_id))\n BEGIN SELECT RAISE(ABORT,'headless_link_provenance_retained'); END;`,\n]);\n\nexport const HEADLESS_LINK_SCHEMA_SQL = HEADLESS_LINK_SCHEMA_STATEMENTS.join(\"\\n\");\n\nconst PRESENT_SQL = `SELECT\n EXISTS (SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = '${HEADLESS_CODE_LIMITS_TABLE}') AS limits,\n EXISTS (SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = '${HEADLESS_LINK_PROVENANCE_TABLE}') AS provenance`;\n\nasync function readPresence(backend: Pick<AuthLinkBackend, \"first\">) {\n\tconst row = await backend.first<{ limits: number; provenance: number }>({\n\t\tsql: PRESENT_SQL,\n\t\tvalues: [],\n\t});\n\treturn { limits: row?.limits === 1, provenance: row?.provenance === 1 };\n}\n\n/**\n * The backend, only when both headless tables exist. A D1 database before\n * migration 0043 returns null: headless linking is off there, and every other\n * auth capability and readiness check is unaffected.\n */\nexport async function readHeadlessLinkBackend(\n\tbackend: AuthLinkBackend,\n): Promise<AuthLinkBackend | null> {\n\tconst present = await readPresence(backend);\n\treturn present.limits && present.provenance ? backend : null;\n}\n\n/** Headless finalize refuses to link when it cannot record provenance in the same batch. */\nexport async function hasHeadlessLinkProvenance(\n\tbackend: Pick<AuthLinkBackend, \"first\">,\n): Promise<boolean> {\n\treturn (await readPresence(backend)).provenance;\n}\n","import {\n\thasHeadlessLinkProvenance,\n\tHEADLESS_LINK_PROVENANCE_TABLE as TABLE,\n} from \"./coordinator-auth-headless-schema.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport { AUTH_LINK_HEADLESS_MARKER_SQL } from \"./coordinator-auth-link-headless.js\";\n\nexport interface HeadlessLinkProvenance {\n\tcoordinatorId: string;\n\tlinkId: string;\n\tidentityId: string;\n\tissuer: string;\n\tsubject: string;\n\tattemptId: string;\n\tcreatedAtMs: number;\n}\nexport type HeadlessLinkProvenanceQuery =\n\t| string\n\t| { identityId: string; issuer: string; subject: string };\n\n/**\n * Selects only the link this finalize batch just wrote: the attempt must carry\n * the batch's own link ID, so an exact retry (which finalizes nothing) inserts\n * no row and cannot collide with the first one.\n */\nexport function headlessLinkProvenanceStatement(\n\tcoordinatorId: string,\n\tattemptId: string,\n\tlinkId: string,\n): AuthLinkStatement {\n\treturn {\n\t\tsql: `INSERT INTO ${TABLE} (coordinator_id, link_id, identity_id, issuer, subject, attempt_id, created_at_ms)\n SELECT t.coordinator_id, t.link_id, t.identity_id, t.issuer, t.account_subject, t.attempt_id, t.finalized_at_ms\n FROM coordinator_auth_link_attempts t JOIN coordinator_auth_account_links l\n ON l.coordinator_id = t.coordinator_id AND l.link_id = t.link_id AND l.attempt_id = t.attempt_id\n WHERE t.coordinator_id = ? AND t.attempt_id = ? AND t.link_id = ? AND t.state = 'finalized'\n AND t.loopback_redirect = ${AUTH_LINK_HEADLESS_MARKER_SQL}`,\n\t\tvalues: [coordinatorId, attemptId, linkId],\n\t};\n}\n\ninterface Row {\n\tcoordinator_id: string;\n\tlink_id: string;\n\tidentity_id: string;\n\tissuer: string;\n\tsubject: string;\n\tattempt_id: string;\n\tcreated_at_ms: number;\n}\n\nfunction lookup(coordinatorId: string, query: HeadlessLinkProvenanceQuery): AuthLinkStatement {\n\tconst select = `SELECT * FROM ${TABLE} WHERE coordinator_id = ?`;\n\tif (typeof query === \"string\")\n\t\treturn { sql: `${select} AND link_id = ?`, values: [coordinatorId, query] };\n\treturn {\n\t\tsql: `${select} AND issuer = ? AND subject = ? AND identity_id = ?\n ORDER BY created_at_ms DESC, link_id DESC LIMIT 1`,\n\t\tvalues: [coordinatorId, query.issuer, query.subject, query.identityId],\n\t};\n}\n\n/**\n * Provenance for one link ID, or the most recent headless link of an account\n * to an Identity. Callers must first confirm the table exists (see\n * readHeadlessLinkBackend); a missing table throws.\n */\nexport async function readHeadlessLinkProvenance(\n\tbackend: Pick<AuthLinkBackend, \"first\">,\n\tcoordinatorId: string,\n\tquery: HeadlessLinkProvenanceQuery,\n): Promise<HeadlessLinkProvenance | null> {\n\tconst row = await backend.first<Row>(lookup(coordinatorId, query));\n\tif (!row) return null;\n\treturn {\n\t\tcoordinatorId: row.coordinator_id,\n\t\tlinkId: row.link_id,\n\t\tidentityId: row.identity_id,\n\t\tissuer: row.issuer,\n\t\tsubject: row.subject,\n\t\tattemptId: row.attempt_id,\n\t\tcreatedAtMs: row.created_at_ms,\n\t};\n}\n\n/**\n * Whether this link was written by headless finalize. False on a coordinator\n * without the provenance table: no link there can be headless.\n */\nexport async function isHeadlessLinkId(\n\tbackend: Pick<AuthLinkBackend, \"first\">,\n\tcoordinatorId: string,\n\tlinkId: string,\n): Promise<boolean> {\n\tif (!(await hasHeadlessLinkProvenance(backend))) return false;\n\treturn (await readHeadlessLinkProvenance(backend, coordinatorId, linkId)) !== null;\n}\n\n/**\n * Commit guard for rebind and owner enrollment on the attempt `a`: its target\n * link has no headless provenance. Include only when the provenance table exists.\n */\nexport const NO_HEADLESS_TARGET_LINK_SQL = `NOT EXISTS (SELECT 1 FROM ${TABLE} p\n WHERE p.coordinator_id = a.coordinator_id AND p.link_id = a.link_id)`;\n\n/**\n * A column expression (1 or 0) for whether the provenance table exists. Callers\n * add it to a read they already make, then reference the table only when it\n * reported 1, so a coordinator without the table never sees a query naming it.\n */\nexport const HEADLESS_PROVENANCE_PRESENT_SQL = `EXISTS (SELECT 1 FROM sqlite_master\n WHERE type = 'table' AND name = '${TABLE}')`;\n\n/** A column expression for whether link `?` of coordinator `coordinator` is headless. Table must exist. */\nexport function headlessLinkExistsSql(coordinator: string): string {\n\treturn `EXISTS (SELECT 1 FROM ${TABLE} hp WHERE hp.coordinator_id = ${coordinator} AND hp.link_id = ?)`;\n}\n","import { captureAuthAccountProfile } from \"./coordinator-auth-account-profile.js\";\nimport type { AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport type {\n\tCoordinatorAuthLinkConfig,\n\tCoordinatorAuthLinkOidcInput,\n} from \"./coordinator-auth-link-contract.js\";\n\n/** Display metadata only. A nullable link_id separates staging from publication. */\nexport const AUTH_LINK_PROFILE_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS coordinator_auth_link_profiles (\n coordinator_id TEXT NOT NULL,\n attempt_id TEXT NOT NULL,\n issuer TEXT NOT NULL,\n subject TEXT NOT NULL,\n auth_config_revision TEXT NOT NULL,\n browser_transaction_hash TEXT NOT NULL,\n link_id TEXT,\n display_name TEXT,\n email TEXT,\n email_verified INTEGER CHECK (email_verified IS NULL OR (email_verified IN (0,1) AND email IS NOT NULL)),\n picture_url TEXT,\n verified_at_ms INTEGER NOT NULL,\n PRIMARY KEY (coordinator_id, attempt_id),\n UNIQUE (coordinator_id, link_id)\n);`;\n\n/** Must immediately follow the verified OIDC update in the same atomic batch.\n * The native change count prevents same-timestamp replays from filling missing claims.\n */\nexport function stageAuthLinkProfile(\n\ti: CoordinatorAuthLinkOidcInput,\n\tc: CoordinatorAuthLinkConfig,\n\tnow: number,\n): AuthLinkStatement | null {\n\tconst p = captureAuthAccountProfile(i.profile);\n\tif (!p) return null;\n\tlet emailVerified: number | null = null;\n\tif (p.emailVerified !== undefined) emailVerified = Number(p.emailVerified);\n\treturn {\n\t\tsql: `INSERT INTO coordinator_auth_link_profiles\n (coordinator_id,attempt_id,issuer,subject,auth_config_revision,browser_transaction_hash,\n display_name,email,email_verified,picture_url,verified_at_ms)\n SELECT coordinator_id,attempt_id,issuer,account_subject,auth_config_revision,browser_transaction_hash,?,?,?,?,oidc_verified_at_ms\n FROM coordinator_auth_link_attempts WHERE changes() = 1 AND coordinator_id = ? AND attempt_id = ? AND issuer = ?\n AND account_subject = ? AND auth_config_revision = ? AND browser_transaction_hash = ?\n AND state = 'oidc_verified' AND oidc_verified_at_ms = ? AND expires_at_ms > ?\n ON CONFLICT(coordinator_id,attempt_id) DO NOTHING`,\n\t\tvalues: [\n\t\t\tp.displayName ?? null,\n\t\t\tp.email ?? null,\n\t\t\temailVerified,\n\t\t\tp.pictureUrl ?? null,\n\t\t\tc.coordinatorId,\n\t\t\ti.attemptId,\n\t\t\tc.issuer,\n\t\t\ti.account.subject,\n\t\t\tc.revision,\n\t\t\ti.browserTransactionHash,\n\t\t\tnow,\n\t\t\tnow,\n\t\t],\n\t};\n}\n\n/** Append to the finalization batch after the link/audit inserts; conflicts roll back all writes. */\nexport function promoteAuthLinkProfile(\n\tcoordinatorId: string,\n\tattemptId: string,\n\tlinkId: string,\n): AuthLinkStatement {\n\treturn {\n\t\tsql: `UPDATE coordinator_auth_link_profiles AS p SET link_id = ? WHERE p.coordinator_id = ?\n AND p.attempt_id = ? AND p.link_id IS NULL AND EXISTS (\n SELECT 1 FROM coordinator_auth_link_attempts t JOIN coordinator_auth_account_links l\n ON l.coordinator_id = t.coordinator_id AND l.attempt_id = t.attempt_id AND l.link_id = t.link_id\n AND l.issuer = t.issuer AND l.subject = t.account_subject AND l.identity_id = t.identity_id\n AND l.auth_config_revision = t.auth_config_revision AND l.revoked_at_ms IS NULL\n WHERE t.coordinator_id = p.coordinator_id AND t.attempt_id = p.attempt_id AND t.link_id = ?\n AND t.state = 'finalized' AND t.issuer = p.issuer AND t.account_subject = p.subject\n AND t.auth_config_revision = p.auth_config_revision AND t.browser_transaction_hash = p.browser_transaction_hash\n AND t.oidc_verified_at_ms = p.verified_at_ms)`,\n\t\tvalues: [linkId, coordinatorId, attemptId, linkId],\n\t};\n}\n\n/** Delete private staging promptly on failure/expiry/config change, and published rows on revocation.\n * Publication never depends on cleanup having run. No authority records are modified.\n */\nexport function cleanAuthLinkProfiles(\n\tc: CoordinatorAuthLinkConfig,\n\tnow: number,\n\tlimit: number,\n): AuthLinkStatement {\n\treturn {\n\t\tsql: `DELETE FROM coordinator_auth_link_profiles WHERE coordinator_id = ? AND attempt_id IN (\n SELECT p.attempt_id FROM coordinator_auth_link_profiles p WHERE p.coordinator_id = ? AND (\n (p.link_id IS NULL AND (p.issuer <> ? OR p.auth_config_revision <> ? OR NOT EXISTS (\n SELECT 1 FROM coordinator_auth_link_attempts t WHERE t.coordinator_id = p.coordinator_id\n AND t.attempt_id = p.attempt_id AND t.state IN ('oidc_verified','confirmed') AND t.expires_at_ms > ?)))\n OR (p.link_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_links l\n WHERE l.coordinator_id = p.coordinator_id AND l.link_id = p.link_id AND l.attempt_id = p.attempt_id\n AND l.issuer = p.issuer AND l.subject = p.subject AND l.auth_config_revision = p.auth_config_revision\n AND l.revoked_at_ms IS NULL))) LIMIT ?)`,\n\t\tvalues: [c.coordinatorId, c.coordinatorId, c.issuer, c.revision, now, limit],\n\t};\n}\n","export type CoordinatorAuthLoopbackResult =\n\t| { ok: true; destination: string; host: \"127.0.0.1\" | \"[::1]\"; port: number }\n\t| { ok: false; error: \"invalid_loopback_destination\" };\n\nconst LOOPBACK_DESTINATION =\n\t/^http:\\/\\/(127\\.0\\.0\\.1|\\[::1\\]):([1-9][0-9]*)\\/codemem\\/auth\\/complete$/;\n\nexport function parseCoordinatorAuthLoopback(value: unknown): CoordinatorAuthLoopbackResult {\n\tif (typeof value !== \"string\") return { ok: false, error: \"invalid_loopback_destination\" };\n\tconst match = LOOPBACK_DESTINATION.exec(value);\n\tif (!match || match[0] !== value) return { ok: false, error: \"invalid_loopback_destination\" };\n\n\tconst port = Number(match[2]);\n\tif (port > 65535) return { ok: false, error: \"invalid_loopback_destination\" };\n\n\treturn {\n\t\tok: true,\n\t\tdestination: value,\n\t\thost: match[1] as \"127.0.0.1\" | \"[::1]\",\n\t\tport,\n\t};\n}\n","import { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { CoordinatorAuthLinkSigner } from \"./coordinator-auth-link-contract.js\";\nimport { capture, captureAuthLinkSigner } from \"./coordinator-auth-link-input.js\";\n\nexport interface DeviceClaimBindingInput {\n\t/** Authenticated by the signed-device boundary, never copied from a request body. */\n\tsigner: CoordinatorAuthLinkSigner;\n\t/** Assertion of the unchanged current/default Identity. The committed claim is authority. */\n\tcurrentIdentityId: string;\n}\nexport interface DeviceClaimBindingReceipt {\n\tbindingId: string;\n\tclaimId: string;\n\tcoordinatorId: string;\n\tdeviceId: string;\n\tkeyId: string;\n\tidentityId: string;\n\tenrollmentCount: number;\n\tboundAt: string;\n}\nexport type DeviceClaimBindingReadiness =\n\t| { kind: \"ready\" }\n\t| { kind: \"complete\"; receipt: DeviceClaimBindingReceipt }\n\t| { kind: \"requires_review\" };\nexport type DeviceClaimBindingResult =\n\t| Exclude<DeviceClaimBindingReadiness, { kind: \"ready\" }>\n\t| { kind: \"completed\"; receipt: DeviceClaimBindingReceipt };\n\nexport function captureDeviceClaimBindingInput(value: unknown): DeviceClaimBindingInput | null {\n\tconst i = capture(value, [\"signer\", \"currentIdentityId\"]);\n\tconst signer = i && captureAuthLinkSigner(i.signer);\n\tif (!i || !signer || !isAuthControllerId(i.currentIdentityId)) return null;\n\treturn { signer, currentIdentityId: i.currentIdentityId };\n}\n\n/** Recognize only the trigger-independent batch assertion. Ordinary malformed\n * JSON, constraint failures and I/O errors retain their original unknown outcome.\n */\nexport function isDeviceClaimBindingConflict(error: unknown): boolean {\n\tlet current = error;\n\tfor (let depth = 0; depth < 4 && current instanceof Error; depth++) {\n\t\tif (\n\t\t\t/(?:bad JSON path:|JSON path error near) ['\"]device_claim_binding_count_mismatch['\"]/.test(\n\t\t\t\tcurrent.message,\n\t\t\t)\n\t\t)\n\t\t\treturn true;\n\t\tcurrent = current.cause;\n\t}\n\treturn false;\n}\n","import type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport type { DeviceClaimBindingInput } from \"./coordinator-device-claim-binding-contract.js\";\nimport type { PreparedDeviceClaimBinding } from \"./coordinator-device-claim-binding-sql.js\";\n\nexport interface ExistingFirstLinkBinding {\n\tdevice_id: string;\n\tkey_id: string;\n\tidentity_id: string;\n\tcoordinator_id: string;\n\tbinding_id: string;\n\tprovenance: \"owner_enrollment\" | \"reviewed_legacy_migration\";\n\tsource_ref: string;\n\tbound_at: string;\n}\nconst COLUMNS = [\n\t\"device_id\",\n\t\"key_id\",\n\t\"identity_id\",\n\t\"coordinator_id\",\n\t\"binding_id\",\n\t\"provenance\",\n\t\"source_ref\",\n\t\"bound_at\",\n] as const;\n\n/** Missing means mint. Null means contradictory ownership, never authority. */\nexport async function readExistingFirstLinkBinding(\n\tbackend: AuthLinkBackend,\n\tinput: DeviceClaimBindingInput,\n\tcoordinatorId: string,\n\tkeyId: string,\n): Promise<ExistingFirstLinkBinding | null | undefined> {\n\tconst row = await backend.first<{ rows: string }>({\n\t\tsql: `SELECT json_group_array(json_object(${COLUMNS.map((c) => `'${c}',${c}`).join(\",\")})) AS rows FROM coordinator_device_ownership_bindings WHERE device_id=? OR key_id=?`,\n\t\tvalues: [input.signer.deviceId, keyId],\n\t});\n\tconst rows = JSON.parse(row?.rows ?? \"[]\") as ExistingFirstLinkBinding[];\n\tif (rows.length === 0) return undefined;\n\tconst binding = rows[0];\n\tif (\n\t\trows.length !== 1 ||\n\t\t!binding ||\n\t\tbinding.device_id !== input.signer.deviceId ||\n\t\tbinding.key_id !== keyId ||\n\t\tbinding.identity_id !== input.currentIdentityId ||\n\t\tbinding.coordinator_id !== coordinatorId\n\t)\n\t\treturn null;\n\tif (\n\t\t![\"owner_enrollment\", \"reviewed_legacy_migration\"].includes(binding.provenance) ||\n\t\t!binding.binding_id ||\n\t\t!binding.source_ref ||\n\t\t!binding.bound_at\n\t)\n\t\treturn null;\n\treturn binding;\n}\n\nexport function existingFirstLinkBindingPin(binding: ExistingFirstLinkBinding): AuthLinkStatement {\n\treturn {\n\t\tsql: `EXISTS (SELECT 1 FROM coordinator_device_ownership_bindings b WHERE ${COLUMNS.map((c) => `b.${c} IS ?`).join(\" AND \")})`,\n\t\tvalues: COLUMNS.map((c) => binding[c]),\n\t};\n}\n\n/** A failing projection runs before table triggers, including RAISE(IGNORE). */\nexport function assertPredicate(predicate: AuthLinkStatement): AuthLinkStatement {\n\treturn {\n\t\tsql: `INSERT INTO coordinator_device_ownership_bindings (device_id,key_id,identity_id,coordinator_id,binding_id,provenance,source_ref,bound_at)\n SELECT json_extract('{}','device_claim_binding_count_mismatch'),NULL,NULL,NULL,NULL,NULL,NULL,NULL WHERE NOT (${predicate.sql})`,\n\t\tvalues: predicate.values,\n\t};\n}\n\n/** Existing positive ownership keeps its original receipt/provenance. Only this\n * device's NULL enrollment fields may change after the claim's winning writes.\n */\nexport function reuseFirstLinkBindingStatements(\n\tplan: PreparedDeviceClaimBinding,\n\tbinding: ExistingFirstLinkBinding,\n): AuthLinkStatement[] {\n\tconst pin = existingFirstLinkBindingPin(binding);\n\tconst { input } = plan;\n\tif (!plan.completedGuard) throw new Error(\"first_link_binding_plan_incomplete\");\n\treturn [\n\t\t...plan.negativeGuards,\n\t\tassertPredicate({ sql: `EXISTS (${plan.guard.sql})`, values: plan.guard.values }),\n\t\t{\n\t\t\tsql: `UPDATE enrolled_devices SET identity_id=? WHERE device_id=? AND identity_id IS NULL AND public_key=? AND fingerprint=? AND ${pin.sql}`,\n\t\t\tvalues: [\n\t\t\t\tinput.currentIdentityId,\n\t\t\t\tinput.signer.deviceId,\n\t\t\t\tinput.signer.publicKey,\n\t\t\t\tinput.signer.fingerprint,\n\t\t\t\t...pin.values,\n\t\t\t],\n\t\t},\n\t\tassertPredicate({ sql: \"changes()=?\", values: [plan.nullCount] }),\n\t\t// Only the retained facts: this batch's own claim and enrollment writes change the rest.\n\t\t...plan.completedNegativeGuards,\n\t\tassertPredicate({\n\t\t\tsql: `EXISTS (${plan.completedGuard.sql})`,\n\t\t\tvalues: plan.completedGuard.values,\n\t\t}),\n\t];\n}\n","/**\n * Limits and column lists of the ownership evidence categories. The reads themselves are\n * in coordinator-owner-negative-reads.ts.\n */\nexport const ROW_LIMIT = 500;\nexport const BYTE_LIMIT = 750_000;\n\nconst controllerColumns =\n\t\"attestation_id,coordinator_id,identity_id,group_id,device_id,public_key,fingerprint,review_receipt_id,evidence_digest,enrollment_identity_id,revision,created_at,revoked_at\";\nexport const CONTROLLER_COLUMNS = controllerColumns.split(\",\");\nexport const RESOLUTION_COLUMNS =\n\t\"coordinator_id,resolution_id,resolution_version,device_id,key_id,owner_identity_id,purpose,scope,source_attestation_id,source_group_id,source_controller_revision,source_public_key,source_fingerprint,source_enrollment_identity_id,source_created_at,source_review_receipt_id,source_evidence_digest,resolution_evidence_digest,reviewed_weak_labels_json,created_at\".split(\n\t\t\",\",\n\t);\n","/**\n * Inert historical-label receipts, never credentials or proof of authority.\n * Future readers must validate the original source and current proof using the\n * exact device AND canonical key. No store-open hook installs this schema.\n * No foreign keys: deleting source state must not erase collision history.\n * Canonical IDs use the full ECMAScript String.trim character set, including BOM.\n */\nexport const LEGACY_OWNER_RESOLUTION_SCHEMA_STATEMENTS = [\n\t`\nCREATE TABLE IF NOT EXISTS coordinator_legacy_owner_resolutions (\n coordinator_id TEXT NOT NULL CHECK (typeof(coordinator_id) = 'text' AND length(coordinator_id) BETWEEN 1 AND 256 AND length(trim(coordinator_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(coordinator_id, char(0)) = 0),\n resolution_id TEXT NOT NULL CHECK (typeof(resolution_id) = 'text' AND length(resolution_id) BETWEEN 1 AND 256 AND length(trim(resolution_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(resolution_id, char(0)) = 0),\n resolution_version INTEGER NOT NULL CHECK (typeof(resolution_version) = 'integer' AND resolution_version = 1),\n device_id TEXT NOT NULL CHECK (typeof(device_id) = 'text' AND length(device_id) BETWEEN 1 AND 256 AND length(trim(device_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(device_id, 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 owner_identity_id TEXT NOT NULL CHECK (typeof(owner_identity_id) = 'text' AND length(owner_identity_id) BETWEEN 1 AND 256 AND length(trim(owner_identity_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(owner_identity_id, char(0)) = 0),\n purpose TEXT NOT NULL CHECK (purpose = 'existing_account_owner'),\n scope TEXT NOT NULL CHECK (scope = 'historical_included_owner_labels_only'),\n source_attestation_id TEXT NOT NULL CHECK (typeof(source_attestation_id) = 'text' AND length(source_attestation_id) BETWEEN 1 AND 256 AND length(trim(source_attestation_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(source_attestation_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 length(trim(source_group_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(source_group_id, char(0)) = 0),\n source_controller_revision INTEGER NOT NULL CHECK (typeof(source_controller_revision) = 'integer' AND source_controller_revision = 1),\n source_public_key TEXT NOT NULL CHECK (typeof(source_public_key) = 'text' AND length(source_public_key) BETWEEN 1 AND 4096 AND length(trim(source_public_key, char(9)||char(10)||char(13)||' ')) > 0 AND instr(source_public_key, char(0)) = 0),\n source_fingerprint TEXT NOT NULL CHECK (typeof(source_fingerprint) = 'text' AND length(source_fingerprint) = 64 AND source_fingerprint NOT GLOB '*[^0-9a-f]*' AND instr(source_fingerprint, char(0)) = 0),\n source_enrollment_identity_id TEXT CHECK (source_enrollment_identity_id IS NULL OR (typeof(source_enrollment_identity_id) = 'text' AND length(source_enrollment_identity_id) BETWEEN 1 AND 256 AND length(trim(source_enrollment_identity_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(source_enrollment_identity_id, char(0)) = 0)),\n source_created_at TEXT NOT NULL CHECK (typeof(source_created_at) = 'text' AND length(source_created_at) BETWEEN 1 AND 256 AND length(trim(source_created_at, char(9)||char(10)||char(13)||' ')) > 0 AND instr(source_created_at, char(0)) = 0),\n source_review_receipt_id TEXT NOT NULL CHECK (typeof(source_review_receipt_id) = 'text' AND length(source_review_receipt_id) BETWEEN 1 AND 256 AND length(trim(source_review_receipt_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(source_review_receipt_id, char(0)) = 0),\n source_evidence_digest TEXT NOT NULL CHECK (typeof(source_evidence_digest) = 'text' AND length(source_evidence_digest) = 64 AND source_evidence_digest NOT GLOB '*[^0-9a-f]*' AND instr(source_evidence_digest, char(0)) = 0),\n resolution_evidence_digest TEXT NOT NULL CHECK (typeof(resolution_evidence_digest) = 'text' AND length(resolution_evidence_digest) = 64 AND resolution_evidence_digest NOT GLOB '*[^0-9a-f]*' AND instr(resolution_evidence_digest, char(0)) = 0),\n reviewed_weak_labels_json TEXT NOT NULL CHECK (typeof(reviewed_weak_labels_json) = 'text' AND length(CAST(reviewed_weak_labels_json AS BLOB)) <= 131072 AND CASE WHEN json_valid(reviewed_weak_labels_json) THEN json_type(reviewed_weak_labels_json) = 'array' ELSE 0 END),\n created_at TEXT NOT NULL CHECK (typeof(created_at) = 'text' AND length(created_at) BETWEEN 1 AND 256 AND length(trim(created_at, char(9)||char(10)||char(13)||' ')) > 0 AND instr(created_at, char(0)) = 0),\n CHECK (\n coordinator_id = trim(coordinator_id, char(9,10,11,12,13,32,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288,65279))\n AND resolution_id = trim(resolution_id, char(9,10,11,12,13,32,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288,65279))\n AND device_id = trim(device_id, char(9,10,11,12,13,32,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288,65279))\n AND owner_identity_id = trim(owner_identity_id, char(9,10,11,12,13,32,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288,65279))\n AND source_attestation_id = trim(source_attestation_id, char(9,10,11,12,13,32,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288,65279))\n AND source_group_id = trim(source_group_id, char(9,10,11,12,13,32,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288,65279))\n AND source_review_receipt_id = trim(source_review_receipt_id, char(9,10,11,12,13,32,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288,65279))\n AND (source_enrollment_identity_id IS NULL OR source_enrollment_identity_id = trim(source_enrollment_identity_id, char(9,10,11,12,13,32,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288,65279)))\n ),\n PRIMARY KEY (coordinator_id, resolution_id)\n) WITHOUT ROWID;\n`,\n\t`\nCREATE INDEX IF NOT EXISTS idx_legacy_owner_resolutions_device\n ON coordinator_legacy_owner_resolutions (coordinator_id, device_id);\n`,\n\t`\nCREATE INDEX IF NOT EXISTS idx_legacy_owner_resolutions_key\n ON coordinator_legacy_owner_resolutions (coordinator_id, key_id);\n`,\n\t`\n-- Reject before REPLACE can erase a receipt, even with recursive triggers off.\n-- Separate indexed probes keep device-OR-key conflicts coordinator-scoped.\nCREATE TRIGGER IF NOT EXISTS legacy_owner_resolution_insert_collision\nBEFORE INSERT ON coordinator_legacy_owner_resolutions\nWHEN EXISTS (SELECT 1 FROM coordinator_legacy_owner_resolutions\n WHERE coordinator_id = NEW.coordinator_id AND resolution_id = NEW.resolution_id)\n OR EXISTS (SELECT 1 FROM coordinator_legacy_owner_resolutions\n WHERE coordinator_id = NEW.coordinator_id AND device_id = NEW.device_id AND owner_identity_id <> NEW.owner_identity_id)\n OR EXISTS (SELECT 1 FROM coordinator_legacy_owner_resolutions\n WHERE coordinator_id = NEW.coordinator_id AND key_id = NEW.key_id AND owner_identity_id <> NEW.owner_identity_id)\nBEGIN SELECT RAISE(ABORT, 'legacy_owner_resolution_collision'); END;\n`,\n\t`\nCREATE TRIGGER IF NOT EXISTS legacy_owner_resolution_immutable_update\nBEFORE UPDATE ON coordinator_legacy_owner_resolutions\nBEGIN SELECT RAISE(ABORT, 'legacy_owner_resolution_immutable'); END;\n`,\n\t`\nCREATE TRIGGER IF NOT EXISTS legacy_owner_resolution_immutable_delete\nBEFORE DELETE ON coordinator_legacy_owner_resolutions\nBEGIN SELECT RAISE(ABORT, 'legacy_owner_resolution_immutable'); END;\n`,\n] as const;\n\nexport const LEGACY_OWNER_RESOLUTION_SCHEMA_SQL =\n\tLEGACY_OWNER_RESOLUTION_SCHEMA_STATEMENTS.join(\"\\n\");\n","import type { AuthLinkBackend } from \"./coordinator-auth-link.js\";\nimport { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport { LEGACY_OWNER_RESOLUTION_SCHEMA_STATEMENTS } from \"./coordinator-legacy-owner-resolution-schema.js\";\n\n/** Shape and key consistency only: never an ownership or provenance proof. */\nexport interface LegacyOwnerResolutionRecord {\n\tcoordinator_id: string;\n\tresolution_id: string;\n\tresolution_version: 1;\n\tdevice_id: string;\n\tkey_id: string;\n\towner_identity_id: string;\n\tpurpose: \"existing_account_owner\";\n\tscope: \"historical_included_owner_labels_only\";\n\tsource_attestation_id: string;\n\tsource_group_id: string;\n\tsource_controller_revision: 1;\n\tsource_public_key: string;\n\tsource_fingerprint: string;\n\tsource_enrollment_identity_id: string | null;\n\tsource_created_at: string;\n\tsource_review_receipt_id: string;\n\tsource_evidence_digest: string;\n\tresolution_evidence_digest: string;\n\treviewed_weak_labels_json: string;\n\tcreated_at: string;\n}\n\nexport interface ReviewedWeakLabel {\n\tlabel: string;\n\tkind: \"legacy_included_owner_label\" | \"consumed_project_actor_label\";\n\tgroup_id: string;\n\tdevice_id: string;\n\tevidence_ref: string;\n\teffect: \"account_owner_display_only\";\n}\n\nexport type LegacyOwnerResolutionSchemaState = \"ready\" | \"missing\" | \"unsupported\";\nconst MAX_WEAK_BYTES = 131072;\nconst encoder = new TextEncoder();\nconst isIdentifier = (v: unknown): v is string =>\n\ttypeof v === \"string\" &&\n\tv.length > 0 &&\n\tv.length <= 256 &&\n\tv.trim() === v &&\n\t!/[\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(v);\nconst isHash = (v: unknown): v is string => typeof v === \"string\" && /^[a-f0-9]{64}$/u.test(v);\nconst isTimestamp = (v: unknown): v is string => {\n\tif (typeof v !== \"string\" || !/^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d\\.\\d{3}Z$/u.test(v)) return false;\n\tconst date = new Date(v);\n\treturn Number.isFinite(date.getTime()) && date.toISOString() === v;\n};\n\nconst recordChecks = {\n\tcoordinator_id: isIdentifier,\n\tresolution_id: isIdentifier,\n\tresolution_version: (v: unknown) => v === 1,\n\tdevice_id: isIdentifier,\n\tkey_id: isHash,\n\towner_identity_id: isIdentifier,\n\tpurpose: (v: unknown) => v === \"existing_account_owner\",\n\tscope: (v: unknown) => v === \"historical_included_owner_labels_only\",\n\tsource_attestation_id: isIdentifier,\n\tsource_group_id: isIdentifier,\n\tsource_controller_revision: (v: unknown) => v === 1,\n\tsource_public_key: (v: unknown) =>\n\t\ttypeof v === \"string\" && v.length > 0 && v.length <= 4096 && !v.includes(\"\\u0000\"),\n\tsource_fingerprint: isHash,\n\tsource_enrollment_identity_id: (v: unknown) => v === null || isIdentifier(v),\n\tsource_created_at: isTimestamp,\n\tsource_review_receipt_id: isIdentifier,\n\tsource_evidence_digest: isHash,\n\tresolution_evidence_digest: isHash,\n\treviewed_weak_labels_json: (v: unknown) => typeof v === \"string\",\n\tcreated_at: isTimestamp,\n} satisfies Record<keyof LegacyOwnerResolutionRecord, (v: unknown) => boolean>;\nconst weakFields = [\"label\", \"kind\", \"group_id\", \"device_id\", \"evidence_ref\", \"effect\"];\n\n/** Copy own data descriptors before validation; never serialize caller objects. */\nfunction captureFields(value: unknown, fields: string[]): Record<string, unknown> | null {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (prototype !== null && prototype !== Object.prototype) return null;\n\tconst keys = Reflect.ownKeys(value);\n\tif (keys.length !== fields.length) return null;\n\tconst captured: Record<string, unknown> = {};\n\tfor (const field of fields) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, field);\n\t\tif (!descriptor || !(\"value\" in descriptor)) return null;\n\t\tcaptured[field] = descriptor.value;\n\t}\n\treturn captured;\n}\n\nfunction captureWeakLabel(value: unknown): ReviewedWeakLabel | null {\n\tconst row = captureFields(value, weakFields);\n\tif (\n\t\t!row ||\n\t\t!isIdentifier(row.label) ||\n\t\t!isIdentifier(row.group_id) ||\n\t\t!isIdentifier(row.device_id) ||\n\t\t!isHash(row.evidence_ref) ||\n\t\t(row.kind !== \"legacy_included_owner_label\" && row.kind !== \"consumed_project_actor_label\") ||\n\t\trow.effect !== \"account_owner_display_only\"\n\t)\n\t\treturn null;\n\treturn {\n\t\tlabel: row.label,\n\t\tkind: row.kind,\n\t\tgroup_id: row.group_id,\n\t\tdevice_id: row.device_id,\n\t\tevidence_ref: row.evidence_ref,\n\t\teffect: row.effect,\n\t};\n}\n\n/** Categories describe reviewed display metadata, not verified server provenance. */\nexport function canonicalReviewedWeakLabels(value: unknown): string | null {\n\ttry {\n\t\tif (!Array.isArray(value)) return null;\n\t\tconst length: unknown = Object.getOwnPropertyDescriptor(value, \"length\")?.value;\n\t\tif (\n\t\t\ttypeof length !== \"number\" ||\n\t\t\t!Number.isInteger(length) ||\n\t\t\tlength < 0 ||\n\t\t\tlength > 256 ||\n\t\t\tReflect.ownKeys(value).length !== length + 1\n\t\t)\n\t\t\treturn null;\n\t\tconst entries: string[] = [];\n\t\tfor (let i = 0; i < length; i++) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, String(i));\n\t\t\tif (!descriptor || !(\"value\" in descriptor)) return null;\n\t\t\tconst entry = captureWeakLabel(descriptor.value);\n\t\t\tif (!entry) return null;\n\t\t\tentries.push(JSON.stringify(entry));\n\t\t}\n\t\tentries.sort(); // ECMAScript binary string order, never locale collation.\n\t\tif (new Set(entries).size !== entries.length) return null;\n\t\tconst json = `[${entries.join(\",\")}]`;\n\t\treturn encoder.encode(json).byteLength <= MAX_WEAK_BYTES ? json : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction isResolutionRecord(\n\trow: Record<string, unknown>,\n): row is LegacyOwnerResolutionRecord & Record<string, unknown> {\n\treturn Object.entries(recordChecks).every(([field, check]) => check(row[field]));\n}\n\nfunction hasCanonicalStoredLabels(json: string): boolean {\n\tif (json.length > MAX_WEAK_BYTES || encoder.encode(json).byteLength > MAX_WEAK_BYTES)\n\t\treturn false;\n\treturn canonicalReviewedWeakLabels(JSON.parse(json)) === json;\n}\n\nexport async function captureLegacyOwnerResolutionRecord(\n\tvalue: unknown,\n): Promise<LegacyOwnerResolutionRecord | null> {\n\ttry {\n\t\tconst row = captureFields(value, Object.keys(recordChecks));\n\t\tif (\n\t\t\t!row ||\n\t\t\t!isResolutionRecord(row) ||\n\t\t\t!hasCanonicalStoredLabels(row.reviewed_weak_labels_json)\n\t\t)\n\t\t\treturn null;\n\t\tif ((await ed25519KeyIdForRevocation(row.source_public_key)) !== row.key_id) return null;\n\t\t// Historical fingerprint and exact key text bind source records in a later reader.\n\t\treturn row;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Tokenize rather than deleting whitespace/comments inside SQL string literals. */\nfunction normalizedDefinition(sql: string): string {\n\tconst tokens =\n\t\tsql.match(\n\t\t\t/'(?:''|[^'])*'|\"(?:\"\"|[^\"])*\"|`(?:``|[^`])*`|\\[[^\\]]*\\]|--[^\\n]*(?:\\n|$)|\\/\\*[\\s\\S]*?\\*\\/|\\s+|[a-zA-Z_][a-zA-Z_0-9]*|\\d+|[^\\s]/gu,\n\t\t) ?? [];\n\tconst normalized = tokens\n\t\t.filter((t) => !/^\\s|^--|^\\/\\*/u.test(t))\n\t\t.map((t) => (/^[a-zA-Z_]/u.test(t) ? t.toLowerCase() : t));\n\tif (normalized.at(-1) === \";\") normalized.pop();\n\treturn normalized.join(\" \").replace(/^(create (?:table|index|trigger)) if not exists /u, \"$1 \");\n}\n\nconst table = \"coordinator_legacy_owner_resolutions\";\nconst definitions = LEGACY_OWNER_RESOLUTION_SCHEMA_STATEMENTS.map(normalizedDefinition);\n\n/** Classify one captured catalog, using the same DDL rules as the live reader. */\nexport function classifyLegacyOwnerResolutionSchemaCatalog(\n\tvalue: unknown,\n): LegacyOwnerResolutionSchemaState {\n\tif (!Array.isArray(value)) return \"unsupported\";\n\tif (value.length === 0) return \"missing\";\n\tif (\n\t\tvalue.some(\n\t\t\t(object) => !object || typeof object.type !== \"string\" || typeof object.sql !== \"string\",\n\t\t)\n\t)\n\t\treturn \"unsupported\";\n\tif (!value.some((object) => object.type === \"table\")) return \"unsupported\";\n\tif (value.length !== definitions.length) return \"unsupported\";\n\tconst actual = value.map((object) => normalizedDefinition(object.sql));\n\treturn definitions.every((ddl) => actual.includes(ddl)) ? \"ready\" : \"unsupported\";\n}\n\nexport async function readLegacyOwnerResolutionSchemaState(\n\tbackend: Pick<AuthLinkBackend, \"first\">,\n): Promise<LegacyOwnerResolutionSchemaState> {\n\ttry {\n\t\t// One catalog snapshot includes every attached trigger and explicit index.\n\t\tconst result = await backend.first<{ objects: string }>({\n\t\t\tsql: `SELECT json_group_array(json_object('type',type,'sql',sql)) AS objects\n\t\t\t FROM sqlite_master WHERE tbl_name = ? AND sql IS NOT NULL`,\n\t\t\tvalues: [table],\n\t\t});\n\t\tif (!result) return \"unsupported\";\n\t\treturn classifyLegacyOwnerResolutionSchemaCatalog(JSON.parse(result.objects));\n\t} catch {\n\t\treturn \"unsupported\";\n\t}\n}\n","import {\n\ttype ControllerHistorySnapshot,\n\tparseControllerHistoryRecord,\n} from \"./coordinator-auth-controller-history.js\";\nimport { RESOLUTION_COLUMNS } from \"./coordinator-device-ownership-evidence-queries.js\";\nimport { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport {\n\tcaptureLegacyOwnerResolutionRecord,\n\ttype ReviewedWeakLabel,\n} from \"./coordinator-legacy-owner-resolution-metadata.js\";\n\nexport type EvidenceRow = (string | number | null)[];\nexport type EvidenceRows = Record<string, EvidenceRow[]>;\nexport function evidenceRows(rows: EvidenceRows, name: string): EvidenceRow[] {\n\tconst result = rows[name];\n\tif (!result) throw new Error(\"missing_evidence\");\n\treturn result;\n}\nexport interface EvidenceSubject {\n\tcoordinatorId: string;\n\tgroupId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n\tkeyId: string;\n}\nexport type OwnershipDecision =\n\t| \"compatible\"\n\t| \"owner_transfer_required\"\n\t| \"weak_label_review_required\"\n\t| \"device_revoked\";\n\nexport function identifier(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length > 0 &&\n\t\tvalue.length <= 256 &&\n\t\tvalue.trim() === value &&\n\t\t!/[\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(value)\n\t);\n}\nexport function hash(value: unknown): value is string {\n\treturn typeof value === \"string\" && /^[a-f0-9]{64}$/u.test(value);\n}\nfunction timestamp(value: unknown): value is string {\n\tif (typeof value !== \"string\" || !/^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d\\.\\d{3}Z$/u.test(value))\n\t\treturn false;\n\treturn Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;\n}\nfunction requireValid(condition: unknown): asserts condition {\n\tif (!condition) throw new Error(\"ownership_evidence_unavailable\");\n}\nexport async function keyId(value: unknown): Promise<string> {\n\trequireValid(typeof value === \"string\" && value.length > 0 && value.length <= 4096);\n\tconst result = await ed25519KeyIdForRevocation(value);\n\trequireValid(result);\n\treturn result;\n}\n\nfunction validateBinding(row: EvidenceRow) {\n\trequireValid(\n\t\trow.length === 8 &&\n\t\t\t[0, 2, 3, 4, 6].every((i) => identifier(row[i])) &&\n\t\t\thash(row[1]) &&\n\t\t\ttimestamp(row[7]),\n\t);\n\trequireValid(row[5] === \"owner_enrollment\" || row[5] === \"reviewed_legacy_migration\");\n}\nasync function validateClaim(row: EvidenceRow) {\n\trequireValid(\n\t\trow.length === 12 &&\n\t\t\t[0, 1, 2, 3, 4, 8, 9].every((i) => identifier(row[i])) &&\n\t\t\thash(row[6]) &&\n\t\t\thash(row[7]) &&\n\t\t\thash(row[10]),\n\t);\n\trequireValid(Number.isSafeInteger(row[11]) && Number(row[11]) >= 0);\n\t// Device collisions remain negative facts even when a stored key ID differs.\n\tawait keyId(row[5]);\n}\nasync function validateController(row: EvidenceRow) {\n\trequireValid(\n\t\trow.length === 13 &&\n\t\t\t[0, 1, 2, 3, 4, 7].every((i) => identifier(row[i])) &&\n\t\t\thash(row[6]) &&\n\t\t\thash(row[8]),\n\t);\n\trequireValid(\n\t\t(row[9] === null || identifier(row[9])) &&\n\t\t\trow[10] === 1 &&\n\t\t\ttimestamp(row[11]) &&\n\t\t\t(row[12] === null || timestamp(row[12])),\n\t);\n\treturn keyId(row[5]);\n}\nasync function validateInvite(row: EvidenceRow) {\n\trequireValid(row.length === 15 && identifier(row[0]) && identifier(row[1]) && identifier(row[2]));\n\trequireValid([3, 4, 5].every((i) => timestamp(row[i])) && (row[6] === null || timestamp(row[6])));\n\trequireValid(String(row[3]) <= String(row[5]) && String(row[5]) <= String(row[4]));\n\trequireValid(row[6] === null || String(row[5]) < String(row[6]));\n\trequireValid(identifier(row[7]) && hash(row[9]) && hash(row[14]));\n\trequireValid([11, 12, 13].every((i) => row[i] === null || identifier(row[i])));\n\trequireValid([\"team_member\", \"add_device\", \"project_share\"].includes(String(row[10])));\n\tif (row[10] === \"team_member\") requireValid(identifier(row[11]) && row[13] === row[11]);\n\tif (row[10] === \"add_device\") requireValid(identifier(row[12]) && row[13] === row[12]);\n\tif (row[10] === \"project_share\") requireValid(identifier(row[13]));\n\treturn keyId(row[8]);\n}\n\nfunction legacyLabels(\n\thistory: ControllerHistorySnapshot,\n\tsubject: EvidenceSubject,\n): ReviewedWeakLabel[] {\n\treturn history.records.flatMap((record) => {\n\t\tconst { manifest } = parseControllerHistoryRecord(record, subject.coordinatorId);\n\t\treturn manifest.device_decisions.flatMap((decision) => {\n\t\t\tif (decision.decision !== \"included\" || !decision.enabled || !decision.identity_id) return [];\n\t\t\tif (\n\t\t\t\tdecision.device_id !== subject.deviceId &&\n\t\t\t\t!history.fingerprints.includes(decision.key_fingerprint)\n\t\t\t)\n\t\t\t\treturn [];\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tlabel: decision.identity_id,\n\t\t\t\t\tkind: \"legacy_included_owner_label\" as const,\n\t\t\t\t\tgroup_id: record.group_id,\n\t\t\t\t\tdevice_id: decision.device_id,\n\t\t\t\t\tevidence_ref: manifest.source_digest,\n\t\t\t\t\teffect: \"account_owner_display_only\" as const,\n\t\t\t\t},\n\t\t\t];\n\t\t});\n\t});\n}\n\nasync function validateResolutionRows(rows: EvidenceRow[]) {\n\tfor (const row of rows) {\n\t\trequireValid(row.length === RESOLUTION_COLUMNS.length);\n\t\trequireValid(\n\t\t\tawait captureLegacyOwnerResolutionRecord(\n\t\t\t\tObject.fromEntries(RESOLUTION_COLUMNS.map((field, i) => [field, row[i]])),\n\t\t\t),\n\t\t);\n\t}\n}\n\nasync function strongSources(\n\trows: EvidenceRows,\n\tsubject: EvidenceSubject,\n\towner: string,\n\tweakLabels: ReviewedWeakLabel[],\n): Promise<boolean> {\n\tlet otherOwner = false;\n\tfor (const row of evidenceRows(rows, \"bindings\")) {\n\t\tvalidateBinding(row);\n\t\tif (row[2] !== owner) otherOwner = true;\n\t}\n\tfor (const row of evidenceRows(rows, \"claims\")) {\n\t\tawait validateClaim(row);\n\t\tif (row[2] !== owner) otherOwner = true;\n\t}\n\tfor (const row of evidenceRows(rows, \"controllers\")) {\n\t\tconst canonicalKey = await validateController(row);\n\t\tif ((row[4] === subject.deviceId || canonicalKey === subject.keyId) && row[2] !== owner)\n\t\t\totherOwner = true;\n\t}\n\tconst inviteConflict = await classifyInvites(\n\t\tevidenceRows(rows, \"invites\"),\n\t\tsubject,\n\t\towner,\n\t\tweakLabels,\n\t);\n\treturn otherOwner || inviteConflict;\n}\n\nasync function classifyInvites(\n\trows: EvidenceRow[],\n\tsubject: EvidenceSubject,\n\towner: string,\n\tweakLabels: ReviewedWeakLabel[],\n): Promise<boolean> {\n\tlet otherOwner = false;\n\tfor (const row of rows) {\n\t\tconst canonicalKey = await validateInvite(row);\n\t\tif (row[7] !== subject.deviceId && canonicalKey !== subject.keyId) continue;\n\t\tif (row[10] === \"project_share\") {\n\t\t\tweakLabels.push({\n\t\t\t\tlabel: String(row[13]),\n\t\t\t\tkind: \"consumed_project_actor_label\",\n\t\t\t\tgroup_id: String(row[1]),\n\t\t\t\tdevice_id: String(row[7]),\n\t\t\t\tevidence_ref: String(row[14]),\n\t\t\t\teffect: \"account_owner_display_only\",\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst invitedOwner = row[10] === \"team_member\" ? row[11] : row[12];\n\t\tif (invitedOwner !== owner) otherOwner = true;\n\t}\n\treturn otherOwner;\n}\n\nexport async function classifyEvidence(\n\trows: EvidenceRows,\n\tsubject: EvidenceSubject,\n\towner: string,\n\thistory: ControllerHistorySnapshot,\n): Promise<{ decision: OwnershipDecision; weakLabels: ReviewedWeakLabel[] }> {\n\tconst enrollment = evidenceRows(rows, \"enrollment\");\n\trequireValid(enrollment.length === 1);\n\tconst current = enrollment[0];\n\trequireValid(current);\n\tconst [group, device, publicKey, fingerprint, label, enabled, archived] = current;\n\trequireValid(\n\t\tgroup === subject.groupId &&\n\t\t\tdevice === subject.deviceId &&\n\t\t\tpublicKey === subject.publicKey &&\n\t\t\tfingerprint === subject.fingerprint &&\n\t\t\tenabled === 1 &&\n\t\t\tarchived === null,\n\t);\n\trequireValid(label === null || identifier(label));\n\tawait validateResolutionRows(evidenceRows(rows, \"resolutions\"));\n\tconst weakLabels = legacyLabels(history, subject);\n\tconst otherOwner = await strongSources(rows, subject, owner, weakLabels);\n\t// Resolution receipts are metadata only, but conflicting owner collisions must\n\t// not disappear just because their original positive source no longer verifies.\n\tconst resolutionConflict = evidenceRows(rows, \"resolutions\").some((row) => row[5] !== owner);\n\tif (evidenceRows(rows, \"revocations\").length) return { decision: \"device_revoked\", weakLabels };\n\tif (otherOwner || resolutionConflict) return { decision: \"owner_transfer_required\", weakLabels };\n\trequireValid(\n\t\tlabel === null || label === owner || weakLabels.some((weak) => weak.label === label),\n\t);\n\tconst relevantLabels = weakLabels.filter((weak) => weak.label !== owner);\n\treturn {\n\t\tdecision: relevantLabels.length ? \"weak_label_review_required\" : \"compatible\",\n\t\tweakLabels: relevantLabels,\n\t};\n}\n","import type { ControllerHistorySnapshot } from \"./coordinator-auth-controller-history.js\";\nimport type { AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport type { EvidenceRow } from \"./coordinator-device-ownership-evidence-classify.js\";\nimport {\n\tCONTROLLER_COLUMNS,\n\tRESOLUTION_COLUMNS,\n\tROW_LIMIT,\n} from \"./coordinator-device-ownership-evidence-queries.js\";\nimport {\n\tcaptureLegacyOwnerResolutionRecord,\n\tclassifyLegacyOwnerResolutionSchemaCatalog,\n} from \"./coordinator-legacy-owner-resolution-metadata.js\";\n\n/**\n * Helpers the negative owner read set shares: the subject it checks, the resolution\n * catalog's classification, evidence row parsing, and the original-source pin.\n */\n\ninterface Backend {\n\tfirst<T>(statement: AuthLinkStatement): Promise<T | null>;\n\tall?<T>(statement: AuthLinkStatement): Promise<T[]>;\n}\n\n/** Trusted subject metadata, not authority. Enrollment is optional for future\n * new-device producers; those producers must independently prove admission.\n */\nexport interface NegativeOwnerSubject {\n\tcoordinatorId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n\townerIdentityId: string;\n\tenrollment?: { groupId: string };\n\tverifiedHistory?: ControllerHistorySnapshot;\n}\n\nexport function capturedCatalogState(encoded: string) {\n\tconst rows: unknown = JSON.parse(encoded);\n\tif (!Array.isArray(rows)) return \"unsupported\";\n\tconst objects: { type: string; sql: string }[] = [];\n\tfor (const row of rows) {\n\t\tif (\n\t\t\t!Array.isArray(row) ||\n\t\t\trow.length !== 4 ||\n\t\t\ttypeof row[0] !== \"string\" ||\n\t\t\ttypeof row[1] !== \"string\" ||\n\t\t\trow[2] !== \"coordinator_legacy_owner_resolutions\" ||\n\t\t\t(row[3] !== null && typeof row[3] !== \"string\")\n\t\t)\n\t\t\treturn \"unsupported\";\n\t\t// The shared reader excludes SQLite's implicit indexes (SQL IS NULL).\n\t\t// Keep those objects in the full catalog pin, not the DDL comparison.\n\t\tif (row[3] !== null) objects.push({ type: row[0], sql: row[3] });\n\t}\n\treturn classifyLegacyOwnerResolutionSchemaCatalog(objects);\n}\n\nexport function parseEvidenceRows(values: { row: string | null }[]): EvidenceRow[] {\n\tif (values.length > ROW_LIMIT) throw new Error(\"ownership_evidence_too_large\");\n\treturn values.map(({ row }) => {\n\t\tif (typeof row !== \"string\") throw new Error(\"ownership_evidence_unavailable\");\n\t\tconst value: unknown = JSON.parse(row);\n\t\tif (\n\t\t\t!Array.isArray(value) ||\n\t\t\tvalue.some((v) => v !== null && typeof v !== \"string\" && typeof v !== \"number\")\n\t\t)\n\t\t\tthrow new Error(\"ownership_evidence_unavailable\");\n\t\treturn value as EvidenceRow;\n\t});\n}\n\nexport async function sourcePins(\n\tbackend: Backend,\n\trows: EvidenceRow[],\n): Promise<AuthLinkStatement> {\n\tconst sources: EvidenceRow[] = [];\n\tfor (const row of rows) {\n\t\tconst resolution = await captureLegacyOwnerResolutionRecord(\n\t\t\tObject.fromEntries(RESOLUTION_COLUMNS.map((column, i) => [column, row[i]])),\n\t\t);\n\t\tif (!resolution) throw new Error(\"ownership_resolution_unavailable\");\n\t\tconst expected = [\n\t\t\tresolution.source_attestation_id,\n\t\t\tresolution.coordinator_id,\n\t\t\tresolution.owner_identity_id,\n\t\t\tresolution.source_group_id,\n\t\t\tresolution.device_id,\n\t\t\tresolution.source_public_key,\n\t\t\tresolution.source_fingerprint,\n\t\t\tresolution.source_review_receipt_id,\n\t\t\tresolution.source_evidence_digest,\n\t\t\tresolution.source_enrollment_identity_id,\n\t\t\tresolution.source_controller_revision,\n\t\t\tresolution.source_created_at,\n\t\t\tnull,\n\t\t];\n\t\tconst source = await backend.first<Record<string, unknown>>({\n\t\t\tsql: `SELECT ${CONTROLLER_COLUMNS.join(\",\")} FROM coordinator_auth_controller_attestations WHERE coordinator_id=? AND attestation_id=?`,\n\t\t\tvalues: [resolution.coordinator_id, resolution.source_attestation_id],\n\t\t});\n\t\tif (source && CONTROLLER_COLUMNS.every((column, i) => source[column] === expected[i]))\n\t\t\tsources.push(expected);\n\t}\n\t// One complete original source suffices; stale same-owner receipts do not\n\t// erase another original, unrevoked source. Metadata was validated separately.\n\tif (sources.length === 0) throw new Error(\"ownership_source_unavailable\");\n\treturn {\n\t\tsql: `SELECT EXISTS (SELECT 1 FROM json_each(?) pin WHERE EXISTS (\n SELECT 1 FROM coordinator_auth_controller_attestations source WHERE ${CONTROLLER_COLUMNS.map((column, i) => `source.${column} IS json_extract(pin.value,'$[${i}]')`).join(\" AND \")})) AS matches`,\n\t\tvalues: [JSON.stringify(sources)],\n\t};\n}\n","import type { ControllerHistorySnapshot } from \"./coordinator-auth-controller-history.js\";\nimport type { AuthRead } from \"./coordinator-auth-read-set.js\";\nimport type { EvidenceSubject } from \"./coordinator-device-ownership-evidence-classify.js\";\nimport {\n\tBYTE_LIMIT,\n\tCONTROLLER_COLUMNS,\n\tRESOLUTION_COLUMNS,\n\tROW_LIMIT,\n} from \"./coordinator-device-ownership-evidence-queries.js\";\n\n/**\n * The plain reads behind the negative owner check. Each one returns what one stage of the\n * evidence statement in coordinator-device-ownership-evidence-queries.ts selected, with\n * that statement's values bound directly instead of read from a JSON snapshot, so no read\n * needs a WITH clause.\n */\n\nconst RESOLUTIONS = \"coordinator_legacy_owner_resolutions\";\nconst HISTORY_MANIFEST_LIMIT = 750_000;\n\n/** The resolution table's schema objects, in creation order as the old pin compared them. */\nexport const NEGATIVE_CATALOG_READ: AuthRead = {\n\tsql: `SELECT json_array(type,name,tbl_name,sql) AS row FROM sqlite_master WHERE tbl_name='${RESOLUTIONS}' ORDER BY rowid`,\n\tvalues: [],\n};\n\n/** Retained resolutions of the subject. A NULL key ID matches only by device. */\nexport function retainedResolutionsRead(\n\tsubject: { coordinatorId: string; deviceId: string },\n\tkeyId: string | null,\n): AuthRead {\n\treturn {\n\t\tsql: `SELECT json_array(${RESOLUTION_COLUMNS.join(\",\")}) AS row FROM ${RESOLUTIONS}\n WHERE coordinator_id=? AND (device_id=? OR key_id=?) ORDER BY row`,\n\t\tvalues: [subject.coordinatorId, subject.deviceId, keyId],\n\t};\n}\n\n/** Resolutions of the device or key in any coordinator, for callers with no namespace. */\nexport function anyNamespaceResolutionsRead(deviceId: string, keyId: string | null): AuthRead {\n\treturn {\n\t\tsql: `SELECT json_array(${RESOLUTION_COLUMNS.join(\",\")}) AS row FROM ${RESOLUTIONS}\n WHERE device_id=? OR key_id=? ORDER BY row`,\n\t\tvalues: [deviceId, keyId],\n\t};\n}\n\n/**\n * One evidence category as its old stage returned it: at most ROW_LIMIT + 1 rows, each the\n * exact `json_array` text, or NULL in every row once the rows together pass BYTE_LIMIT.\n * The text is passed through as a JSON string so its byte count is the one SQLite made.\n * The LIMIT cannot hide a change: more than ROW_LIMIT rows refuse the decision, and up to\n * that, the read returns every row.\n */\nfunction evidenceRead(columns: string, from: string, values: AuthRead[\"values\"]): AuthRead {\n\treturn {\n\t\tsql: `SELECT json_quote(capped || '') AS row FROM (\n SELECT CASE WHEN SUM(length(CAST(row AS BLOB))) OVER () <= ${BYTE_LIMIT} THEN row ELSE NULL END AS capped, row AS raw\n FROM (SELECT json_array(${columns}) AS row FROM ${from} LIMIT ${ROW_LIMIT + 1})) ORDER BY raw`,\n\t\tvalues,\n\t};\n}\n\n/** Adds the old stages' `line`, `tail` and `token` columns to the rows of `source`. */\nfunction tokenized(source: string): string {\n\tconst line =\n\t\t\"ltrim(replace(replace(replace(replace(replace(public_key,char(9),' '),char(10),' '),char(11),' '),char(12),' '),char(13),' '),' ')\";\n\treturn `(SELECT *,CASE WHEN tail IS NOT NULL THEN substr(tail,1,instr(tail || ' ',' ') - 1) ELSE NULL END AS token\n FROM (SELECT *,CASE WHEN substr(line,1,12) = 'ssh-ed25519 ' THEN ltrim(substr(line,13),' ') ELSE NULL END AS tail\n FROM (SELECT *,${line} AS line FROM (${source}))))`;\n}\n\n// Keys whose token could encode the subject key, or that ordinary parsing cannot rule out.\nconst SUSPECT_TOKEN = `instr(public_key,char(0)) > 0 OR token IS NULL OR token GLOB '*[^A-Za-z0-9+/=_-]*'\n OR EXISTS (SELECT 1 FROM json_each(?) f WHERE instr(replace(replace(token,'-','+'),'_','/'),f.value) > 0)`;\n\n// Invites and groups are server-local tables: neither has a coordinator column.\nconst DISCOVERY_SOURCES = `SELECT 'controller' AS source,attestation_id AS id,device_id,public_key\n FROM coordinator_auth_controller_attestations WHERE coordinator_id=?\n UNION ALL SELECT 'invite',invite_id,bound_device_id,bound_public_key FROM coordinator_invites WHERE consumed_at IS NOT NULL`;\nconst HISTORY_KEY_SOURCES = `SELECT public_key,fingerprint FROM enrolled_devices\n UNION SELECT a.public_key,a.fingerprint FROM coordinator_auth_controller_attestations a WHERE a.coordinator_id=?`;\n\nconst DECISION = \"CASE WHEN d.type = 'object' THEN d.value ELSE '{}' END\";\n// The old live_history stage, reading the subject from bound values.\nconst HISTORY_MATCH = `(json_extract(c.parsed,'$.coordinator_id') = ? OR json_extract(c.parsed,'$.coordinator_id') IS NULL)\n AND (EXISTS (SELECT 1 FROM json_each(c.parsed,'$.device_decisions') d\n WHERE json_extract(${DECISION},'$.device_id') = ?\n OR json_extract(${DECISION},'$.key_fingerprint') IN (SELECT value FROM json_each(?))\n OR ((d.type <> 'object' OR json_type(${DECISION},'$.device_id') IS NOT 'text' OR json_type(${DECISION},'$.key_fingerprint') IS NOT 'text')\n AND (instr(CASE WHEN d.type = 'text' THEN json_quote(d.value) ELSE d.value END,json_quote(?)) > 0\n OR EXISTS (SELECT 1 FROM json_each(?) f WHERE instr(d.value,f.value) > 0))))\n OR ((json_valid(c.manifest_json) = 0 OR json_type(c.parsed,'$.device_decisions') IS NOT 'array')\n AND (instr(c.manifest_json,json_quote(?)) > 0 OR EXISTS (SELECT 1 FROM json_each(?) f WHERE instr(c.manifest_json,f.value) > 0))))`;\nconst LIVE_HISTORY = `(SELECT c.group_id,c.candidate_ref,c.manifest_version,c.completed_at,c.created_at,\n CASE WHEN length(CAST(c.manifest_json AS BLOB)) <= ${HISTORY_MANIFEST_LIMIT} THEN c.manifest_json ELSE NULL END AS manifest_json\n FROM (SELECT c.*,CASE WHEN json_valid(c.manifest_json) THEN c.manifest_json ELSE '{}' END AS parsed\n FROM coordinator_legacy_team_completions c) c WHERE ${HISTORY_MATCH})`;\n\nexport interface EvidenceReadInput {\n\tsubject: EvidenceSubject;\n\thistory: ControllerHistorySnapshot;\n}\n\n/** The subject's own rows. Controllers and invites are read next, by the IDs discovered. */\nfunction subjectReads(s: EvidenceSubject, fragments: string) {\n\treturn {\n\t\tdiscovery: evidenceRead(\n\t\t\t\"source,id\",\n\t\t\t`${tokenized(DISCOVERY_SOURCES)} WHERE device_id=? OR public_key=? OR ${SUSPECT_TOKEN}`,\n\t\t\t[s.coordinatorId, s.deviceId, s.publicKey, fragments],\n\t\t),\n\t\tbindings: evidenceRead(\n\t\t\t\"device_id,key_id,identity_id,coordinator_id,binding_id,provenance,source_ref,bound_at\",\n\t\t\t\"coordinator_device_ownership_bindings WHERE device_id=? OR key_id=?\",\n\t\t\t[s.deviceId, s.keyId],\n\t\t),\n\t\tclaims: evidenceRead(\n\t\t\t\"claim_id,coordinator_id,identity_id,group_id,device_id,public_key,fingerprint,key_id,attempt_id,issuer,auth_config_revision,created_at_ms\",\n\t\t\t\"coordinator_auth_device_claims WHERE coordinator_id=? AND (device_id=? OR key_id=?)\",\n\t\t\t[s.coordinatorId, s.deviceId, s.keyId],\n\t\t),\n\t\tenrollment: evidenceRead(\n\t\t\t\"e.group_id,e.device_id,e.public_key,e.fingerprint,e.identity_id,e.enabled,g.archived_at\",\n\t\t\t\"enrolled_devices e JOIN groups g ON g.group_id=e.group_id WHERE e.group_id=? AND e.device_id=?\",\n\t\t\t[s.groupId, s.deviceId],\n\t\t),\n\t\trevocations: evidenceRead(\n\t\t\t\"subject_kind,subject_value,revocation_id,evidence_group_id,evidence_device_id,evidence_public_key,evidence_fingerprint,actor_id,created_at\",\n\t\t\t\"coordinator_device_revocations WHERE (subject_kind='device_id' AND subject_value=?) OR (subject_kind='ed25519_key' AND subject_value=?)\",\n\t\t\t[s.deviceId, s.keyId],\n\t\t),\n\t\tresolutions: evidenceRead(\n\t\t\tRESOLUTION_COLUMNS.join(\",\"),\n\t\t\t`${RESOLUTIONS} WHERE coordinator_id=? AND (device_id=? OR key_id=?)`,\n\t\t\t[s.coordinatorId, s.deviceId, s.keyId],\n\t\t),\n\t\tschema: evidenceRead(\n\t\t\t\"type,name,tbl_name,sql\",\n\t\t\t`sqlite_master WHERE tbl_name='${RESOLUTIONS}' AND sql IS NOT NULL`,\n\t\t\t[],\n\t\t),\n\t};\n}\n\n/** The legacy history rows and keys that the captured history snapshot must still match. */\nfunction historyReads(h: ControllerHistorySnapshot, fragments: string) {\n\tconst fingerprints = JSON.stringify(h.fingerprints);\n\treturn {\n\t\thistory: evidenceRead(\n\t\t\t\"group_id,candidate_ref,manifest_version,completed_at,created_at,manifest_json\",\n\t\t\tLIVE_HISTORY,\n\t\t\t[\n\t\t\t\th.coordinatorId,\n\t\t\t\th.deviceId,\n\t\t\t\tfingerprints,\n\t\t\t\th.deviceId,\n\t\t\t\tfingerprints,\n\t\t\t\th.deviceId,\n\t\t\t\tfingerprints,\n\t\t\t],\n\t\t),\n\t\thistoryKeys: evidenceRead(\n\t\t\t\"public_key,fingerprint\",\n\t\t\t`(SELECT DISTINCT public_key,fingerprint FROM (${HISTORY_KEY_SOURCES})\n WHERE public_key IN (SELECT value FROM json_each(?)))`,\n\t\t\t[h.coordinatorId, JSON.stringify(h.keys.map((key) => key.public_key))],\n\t\t),\n\t\thistoryDiscovery: evidenceRead(\n\t\t\t\"public_key\",\n\t\t\t`(SELECT DISTINCT public_key FROM ${tokenized(HISTORY_KEY_SOURCES)} WHERE public_key=? OR ${SUSPECT_TOKEN})`,\n\t\t\t[h.coordinatorId, h.publicKey, fragments],\n\t\t),\n\t};\n}\n\n/**\n * The rows the controller review's history guard compared with the reviewed snapshot,\n * with that guard's own limits: one more row than the snapshot may hold, so a larger live\n * set can never equal it. Plain rows ordered by their whole text; no byte cap applies.\n */\nexport function controllerHistoryReads(h: ControllerHistorySnapshot): Record<string, AuthRead> {\n\tconst fingerprints = JSON.stringify(h.fingerprints);\n\tconst fragments = JSON.stringify(h.discoveryFragments);\n\tconst rows = (columns: string, from: string, limit: number, values: AuthRead[\"values\"]) => ({\n\t\tsql: `SELECT json_array(${columns}) AS row FROM ${from} ORDER BY row LIMIT ${limit}`,\n\t\tvalues,\n\t});\n\treturn {\n\t\thistory: rows(\n\t\t\t\"group_id,candidate_ref,manifest_version,completed_at,created_at,manifest_json\",\n\t\t\tLIVE_HISTORY,\n\t\t\t501,\n\t\t\t[\n\t\t\t\th.coordinatorId,\n\t\t\t\th.deviceId,\n\t\t\t\tfingerprints,\n\t\t\t\th.deviceId,\n\t\t\t\tfingerprints,\n\t\t\t\th.deviceId,\n\t\t\t\tfingerprints,\n\t\t\t],\n\t\t),\n\t\thistoryKeys: rows(\n\t\t\t\"public_key,fingerprint\",\n\t\t\t`(SELECT DISTINCT public_key,fingerprint FROM (${HISTORY_KEY_SOURCES})\n WHERE public_key IN (SELECT value FROM json_each(?)))`,\n\t\t\t4097,\n\t\t\t[h.coordinatorId, JSON.stringify(h.keys.map((key) => key.public_key))],\n\t\t),\n\t\thistoryDiscovery: rows(\n\t\t\t\"public_key\",\n\t\t\t`(SELECT DISTINCT public_key FROM ${tokenized(HISTORY_KEY_SOURCES)} WHERE public_key=? OR ${SUSPECT_TOKEN})`,\n\t\t\t8193,\n\t\t\t[h.coordinatorId, h.publicKey, fragments],\n\t\t),\n\t};\n}\n\n/** Every category but controllers and invites, which depend on the discovered IDs. */\nexport function evidenceReads({ subject, history }: EvidenceReadInput): Record<string, AuthRead> {\n\tconst fragments = JSON.stringify(history.discoveryFragments);\n\treturn { ...subjectReads(subject, fragments), ...historyReads(history, fragments) };\n}\n\n/** Controller reviews and consumed invites among the discovered keys, as the old stages joined them. */\nexport function discoveredReads(\n\tsubject: EvidenceSubject,\n\tdiscovered: { controllers: string[]; invites: string[] },\n): Record<string, AuthRead> {\n\treturn {\n\t\tcontrollers: evidenceRead(\n\t\t\tCONTROLLER_COLUMNS.join(\",\"),\n\t\t\t\"coordinator_auth_controller_attestations WHERE coordinator_id=? AND attestation_id IN (SELECT value FROM json_each(?))\",\n\t\t\t[subject.coordinatorId, JSON.stringify(discovered.controllers)],\n\t\t),\n\t\tinvites: evidenceRead(\n\t\t\t\"invite_id,group_id,policy,created_at,expires_at,consumed_at,revoked_at,bound_device_id,bound_public_key,bound_fingerprint,invite_kind,assigned_identity_id,target_identity_id,recipient_actor_id,reviewed_preview_digest\",\n\t\t\t\"coordinator_invites WHERE invite_id IN (SELECT value FROM json_each(?))\",\n\t\t\t[JSON.stringify(discovered.invites)],\n\t\t),\n\t};\n}\n\n/** Whether one of the resolutions' original sources is still exactly as reviewed. */\nexport function sourcesRead(pin: AuthRead): AuthRead {\n\treturn {\n\t\tsql: `SELECT json_object('matches',matches) AS row FROM (${pin.sql})`,\n\t\tvalues: pin.values,\n\t};\n}\n","import {\n\ttype ControllerHistorySnapshot,\n\tcaptureControllerHistory,\n} from \"./coordinator-auth-controller-history.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport {\n\ttype AuthReadSnapshot,\n\ttype ReadSnapshotOptions,\n\treadSnapshot,\n} from \"./coordinator-auth-read-set.js\";\nimport {\n\tclassifyEvidence,\n\ttype EvidenceRow,\n\ttype EvidenceRows,\n\ttype EvidenceSubject,\n} from \"./coordinator-device-ownership-evidence-classify.js\";\nimport { BYTE_LIMIT } from \"./coordinator-device-ownership-evidence-queries.js\";\nimport { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport {\n\tcapturedCatalogState,\n\ttype NegativeOwnerSubject,\n\tparseEvidenceRows,\n\tsourcePins,\n} from \"./coordinator-owner-negative-consistency.js\";\nimport {\n\tanyNamespaceResolutionsRead,\n\tdiscoveredReads,\n\tevidenceReads,\n\tNEGATIVE_CATALOG_READ,\n\tretainedResolutionsRead,\n\tsourcesRead,\n} from \"./coordinator-owner-negative-reads.js\";\nimport { sqlEq } from \"./coordinator-sql-compare.js\";\n\n/**\n * Negative owner consistency as a read set: evidence reads, the shared\n * classification, and guards that pin the rows the classification used.\n *\n * The result never grants owner authority. It only says that no\n * retained legacy owner fact for the subject contradicts the producer's owner.\n */\nexport interface NegativeOwnerGuards {\n\t/** Re-run every read the decision used. They go in the batch that writes. */\n\tguards: AuthLinkStatement[];\n\t/**\n\t * Re-run only the resolution catalog, the subject's retained resolutions and their\n\t * original sources. A producer's own writes never change these, so they may run after\n\t * them. They match the old pin's retained recheck.\n\t */\n\tretainedGuards: AuthLinkStatement[];\n}\n\ntype Backend = Pick<AuthLinkBackend, \"first\" | \"all\" | \"readBatch\">;\ntype EvidenceText = (string | null)[];\n\nconst both = (guards: AuthLinkStatement[]): NegativeOwnerGuards => ({\n\tguards,\n\tretainedGuards: guards,\n});\n\n/** null refuses. The catalog guard also covers the table appearing later. */\nfunction catalogState(rows: unknown[]): \"missing\" | \"ready\" | null {\n\tconst encoded = JSON.stringify(rows);\n\tconst state = capturedCatalogState(encoded);\n\tif (state === \"unsupported\" || (state === \"missing\" && rows.length !== 0)) return null;\n\treturn state;\n}\n\n/** Returns null when the subject's retained ownership forbids the owner or cannot be read. */\nexport async function readNegativeOwnerConsistency(\n\tbackend: Backend,\n\tinput: NegativeOwnerSubject,\n\toptions: ReadSnapshotOptions = {},\n): Promise<NegativeOwnerGuards | null> {\n\ttry {\n\t\tconst catalog = await readSnapshot<{ catalog: unknown[] }>(\n\t\t\tbackend,\n\t\t\t{ catalog: NEGATIVE_CATALOG_READ },\n\t\t\toptions,\n\t\t);\n\t\tconst state = catalogState(catalog.rows.catalog);\n\t\tif (state === null) return null;\n\t\t// The missing-schema guard never names the absent table.\n\t\tif (state === \"missing\") return both([catalog.guards.catalog]);\n\t\tconst keyId = await ed25519KeyIdForRevocation(input.publicKey);\n\t\tconst retained = await readSnapshot<{ resolutions: unknown[] }>(\n\t\t\tbackend,\n\t\t\t{ resolutions: retainedResolutionsRead(input, keyId) },\n\t\t\toptions,\n\t\t);\n\t\tconst fixed = { catalog: catalog.guards.catalog, retained: retained.guards.resolutions };\n\t\t// No retained fact for this subject keeps ordinary admission; the guards pin absence.\n\t\tif (retained.rows.resolutions.length === 0) return both([fixed.catalog, fixed.retained]);\n\t\treturn await readResolvedOwnerConsistency(backend, input, keyId, fixed, options);\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * The negative owner check for old internal callers that name no coordinator. It allows\n * only a device with no retained resolution anywhere, and never infers a namespace.\n */\nexport async function readUnknownNamespaceOwnerConsistency(\n\tbackend: Backend,\n\tinput: Pick<NegativeOwnerSubject, \"deviceId\" | \"publicKey\">,\n): Promise<NegativeOwnerGuards | null> {\n\ttry {\n\t\tconst catalog = await readSnapshot<{ catalog: unknown[] }>(backend, {\n\t\t\tcatalog: NEGATIVE_CATALOG_READ,\n\t\t});\n\t\tconst state = catalogState(catalog.rows.catalog);\n\t\tif (state === null) return null;\n\t\tif (state === \"missing\") return both([catalog.guards.catalog]);\n\t\tconst keyId = await ed25519KeyIdForRevocation(input.publicKey);\n\t\tconst retained = await readSnapshot<{ resolutions: unknown[] }>(backend, {\n\t\t\tresolutions: anyNamespaceResolutionsRead(input.deviceId, keyId),\n\t\t});\n\t\tif (retained.rows.resolutions.length !== 0) return null;\n\t\treturn both([catalog.guards.catalog, retained.guards.resolutions]);\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nasync function readResolvedOwnerConsistency(\n\tbackend: Backend,\n\tinput: NegativeOwnerSubject,\n\tkeyId: string | null,\n\tfixed: { catalog: AuthLinkStatement },\n\toptions: ReadSnapshotOptions,\n): Promise<NegativeOwnerGuards | null> {\n\t// The old evidence statement needed a backend that returns rows; keep refusing without one.\n\tconst all = backend.all?.bind(backend);\n\tif (!all) throw new Error(\"ownership_evidence_reader_unavailable\");\n\t// Classification uses this captured history. The evidence reads select the same rows\n\t// again; they must still equal it, and their guards then pin it to the write.\n\tconst history =\n\t\tinput.verifiedHistory ??\n\t\t(await captureControllerHistory(\n\t\t\t{\n\t\t\t\tcoordinatorId: input.coordinatorId,\n\t\t\t\tdeviceId: input.deviceId,\n\t\t\t\tpublicKey: input.publicKey,\n\t\t\t\tfingerprint: input.fingerprint,\n\t\t\t},\n\t\t\t<T>(sql: string, values: string[]) => all<T>({ sql, values }),\n\t\t));\n\tconst subject: EvidenceSubject = {\n\t\tcoordinatorId: input.coordinatorId,\n\t\tdeviceId: input.deviceId,\n\t\tpublicKey: input.publicKey,\n\t\tfingerprint: input.fingerprint,\n\t\tgroupId: input.enrollment?.groupId ?? \"\",\n\t\t// Legacy trusted seed callers can have opaque keys. They still receive\n\t\t// device checks; no canonical-key inference is made from opaque text.\n\t\tkeyId: keyId ?? \"\",\n\t};\n\tconst evidence = await readEvidence(backend, subject, history, options);\n\t// A change between capture and the evidence reads would be pinned but never classified.\n\t// A reviewed history is the caller's to check: the controller review compares it with\n\t// the live rows and guards that comparison, as its old statement did.\n\tif (!input.verifiedHistory && !sameHistory(evidence.rows, history)) return null;\n\tif (!(await ownerCompatible(evidence.rows, subject, input, history))) return null;\n\t// Unguarded: these reads only choose which sources to pin. The verdict read and its\n\t// guard check the chosen sources again, as the old pin did.\n\tconst pin = await sourcePins(backend, evidence.rows.resolutions ?? []);\n\tconst sources = await readSnapshot<{ sources: { matches: number | null }[] }>(\n\t\tbackend,\n\t\t{ sources: sourcesRead(pin) },\n\t\toptions,\n\t);\n\tconst [verdict] = sources.rows.sources;\n\tif (sources.rows.sources.length !== 1 || !sqlEq(verdict?.matches ?? null, 1)) return null;\n\t// The retained guards pin the resolutions the evidence reads saw, not the earlier\n\t// retained read: a resolution added between the two would otherwise leave the full and\n\t// retained guards pinning different rows. The old pins both used the evidence rows.\n\treturn {\n\t\tguards: [fixed.catalog, ...evidence.guards, sources.guards.sources],\n\t\tretainedGuards: [fixed.catalog, evidence.resolutionsGuard, sources.guards.sources],\n\t};\n}\n\nasync function ownerCompatible(\n\trows: EvidenceRows,\n\tsubject: EvidenceSubject,\n\tinput: NegativeOwnerSubject,\n\thistory: ControllerHistorySnapshot,\n): Promise<boolean> {\n\tconst classificationRows = { ...rows };\n\tif (!input.enrollment)\n\t\tclassificationRows.enrollment = [\n\t\t\t[\"\", input.deviceId, input.publicKey, input.fingerprint, null, 1, null],\n\t\t];\n\tconst classification = await classifyEvidence(\n\t\tclassificationRows,\n\t\tsubject,\n\t\tinput.ownerIdentityId,\n\t\thistory,\n\t);\n\treturn [\"compatible\", \"weak_label_review_required\"].includes(classification.decision);\n}\n\nconst rowSet = (rows: unknown[][]) => JSON.stringify(rows.map((row) => JSON.stringify(row)).sort());\n\n/** Whether the evidence reads returned exactly the history that was captured and classified. */\nfunction sameHistory(rows: EvidenceRows, history: ControllerHistorySnapshot): boolean {\n\tconst captured = {\n\t\thistory: history.records.map((r) => [\n\t\t\tr.group_id,\n\t\t\tr.candidate_ref,\n\t\t\tr.manifest_version,\n\t\t\tr.completed_at,\n\t\t\tr.created_at,\n\t\t\tr.manifest_json,\n\t\t]),\n\t\thistoryKeys: history.keys.map((key) => [key.public_key, key.fingerprint]),\n\t\thistoryDiscovery: history.discoveryKeys.map((key) => [key]),\n\t};\n\treturn Object.entries(captured).every(\n\t\t([name, expected]) => rowSet(rows[name] ?? []) === rowSet(expected),\n\t);\n}\n\n/** Parsed rows and their exact text, as the old reader returned each category. */\nfunction parseCategory(text: EvidenceText): { rows: EvidenceRow[]; text: string[] } {\n\tconst rows = parseEvidenceRows(text.map((row) => ({ row })));\n\treturn { rows, text: text.map(String) };\n}\n\nfunction discoveredIds(discovery: EvidenceRow[]) {\n\t// A NULL ID never matched the old `IN (SELECT id ...)`.\n\tconst ids = (source: string) =>\n\t\tdiscovery.flatMap((row) => (row[0] === source && typeof row[1] === \"string\" ? [row[1]] : []));\n\treturn { controllers: ids(\"controller\"), invites: ids(\"invite\") };\n}\n\n/**\n * Reads every evidence category, then the controllers and invites among the discovered\n * keys. Fails like the old reader on too many rows, too many bytes or malformed rows.\n * The ownership evidence collector reads its categories the same way.\n */\nexport async function readEvidence(\n\tbackend: Backend,\n\tsubject: EvidenceSubject,\n\thistory: ControllerHistorySnapshot,\n\toptions: ReadSnapshotOptions,\n): Promise<{\n\trows: EvidenceRows;\n\tguards: AuthLinkStatement[];\n\t/** The guard of the resolutions category alone. */\n\tresolutionsGuard: AuthLinkStatement;\n}> {\n\tconst first = await readSnapshot<Record<string, EvidenceText>>(\n\t\tbackend,\n\t\tevidenceReads({ subject, history }),\n\t\toptions,\n\t);\n\tconst discovery = parseCategory(first.rows.discovery ?? []);\n\tconst next = await readSnapshot<Record<string, EvidenceText>>(\n\t\tbackend,\n\t\tdiscoveredReads(subject, discoveredIds(discovery.rows)),\n\t\toptions,\n\t);\n\tconst snapshots: AuthReadSnapshot<Record<string, EvidenceText>>[] = [first, next];\n\tconst categories = snapshots.flatMap((snapshot) =>\n\t\tObject.entries(snapshot.rows).map(([name, text]) => [name, parseCategory(text)] as const),\n\t);\n\tconst base = {\n\t\tsubject: { ...subject, fragments: history.discoveryFragments },\n\t\tlegacyHistory: history,\n\t};\n\tconst encoded = JSON.stringify({\n\t\t...base,\n\t\trows: Object.fromEntries(categories.map(([name, category]) => [name, category.text])),\n\t});\n\tif (new TextEncoder().encode(encoded).byteLength > BYTE_LIMIT)\n\t\tthrow new Error(\"ownership_evidence_too_large\");\n\treturn {\n\t\trows: Object.fromEntries(categories.map(([name, category]) => [name, category.rows])),\n\t\tguards: snapshots.flatMap((snapshot) => Object.values(snapshot.guards)),\n\t\tresolutionsGuard: requireGuard(first.guards.resolutions),\n\t};\n}\n\nfunction requireGuard(guard: AuthLinkStatement | undefined): AuthLinkStatement {\n\tif (!guard) throw new Error(\"ownership_evidence_unavailable\");\n\treturn guard;\n}\n","import { hasConnectionSessionSchema } from \"./coordinator-account-connection-session.js\";\nimport {\n\tAUTH_DEVICE_CLAIM_BINDING_STRUCTURE_SQL,\n\tAUTH_DEVICE_CLAIM_CURRENT_SUBJECT_COMPATIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_INPUT_SQL,\n\tAUTH_DEVICE_CLAIM_REQUESTER_ATTESTATION_COMPATIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_REQUESTER_INVITE_COMPATIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_REQUESTER_LINK_COMPATIBLE_SQL,\n\tcaptureDeviceClaimEligibility,\n} from \"./coordinator-auth-device-claim-eligibility.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport type { CoordinatorAuthLinkConfig } from \"./coordinator-auth-link-contract.js\";\nimport { captureAuthLinkConfig } from \"./coordinator-auth-link-input.js\";\nimport {\n\tauthClaimGenesisSql,\n\tauthDeviceClaimProvenanceSql,\n} from \"./coordinator-auth-link-provenance.js\";\nimport {\n\tcaptureDeviceClaimBindingInput,\n\ttype DeviceClaimBindingInput,\n} from \"./coordinator-device-claim-binding-contract.js\";\nimport {\n\tassertPredicate,\n\ttype ExistingFirstLinkBinding,\n\texistingFirstLinkBindingPin,\n\treadExistingFirstLinkBinding,\n\treuseFirstLinkBindingStatements,\n} from \"./coordinator-device-claim-binding-reuse.js\";\nimport { legacyDecisionCountsAsOwnerSql } from \"./coordinator-legacy-team-completion.js\";\nimport { readNegativeOwnerConsistency } from \"./coordinator-owner-negative-read-set.js\";\n\nexport interface PreparedDeviceClaimBinding {\n\tguard: AuthLinkStatement;\n\tenrollments: string;\n\tenrollmentCount: number;\n\tnullCount: number;\n\tinput: DeviceClaimBindingInput;\n\tcoordinatorId: string;\n\tnow: number;\n\t/** Producer only: preserve this immutable positive ownership instead of minting. */\n\texistingBinding?: ExistingFirstLinkBinding;\n\tcompletedGuard?: AuthLinkStatement;\n\t/**\n\t * Re-run the retained-ownership reads. They fail with the binding's own error, so a\n\t * changed fact refuses the binding exactly as the old pin inside `guard` did, and they\n\t * run where that pin ran: just before the binding's first write.\n\t */\n\tnegativeGuards: AuthLinkStatement[];\n\t/** The retained facts only, checked again after the enrollment update. */\n\tcompletedNegativeGuards: AuthLinkStatement[];\n}\n\nconst LIVE_SIGNER = `EXISTS (SELECT 1 FROM enrolled_devices e JOIN groups g ON g.group_id=e.group_id\n WHERE e.group_id=p.group_id AND e.device_id=p.device_id AND e.public_key=p.public_key\n AND e.fingerprint=p.fingerprint AND e.enabled=1 AND g.archived_at IS NULL\n AND (e.identity_id IS NULL OR e.identity_id=p.identity_id))`;\nconst EXACT_ENROLLMENTS = `(SELECT count(*) FROM enrolled_devices WHERE device_id=p.device_id)=json_array_length(?)\n AND NOT EXISTS (SELECT 1 FROM enrolled_devices e WHERE e.device_id=p.device_id AND NOT EXISTS\n (SELECT 1 FROM json_each(?) r WHERE e.group_id=json_extract(r.value,'$.groupId')\n AND e.public_key=json_extract(r.value,'$.publicKey') AND e.fingerprint=json_extract(r.value,'$.fingerprint')\n AND e.identity_id IS json_extract(r.value,'$.identityId') AND e.enabled=json_extract(r.value,'$.enabled')))`;\nconst NO_REVOCATION = `NOT EXISTS (SELECT 1 FROM coordinator_device_revocations r\n WHERE (r.subject_kind='device_id' AND r.subject_value=p.device_id) OR (r.subject_kind='ed25519_key' AND r.subject_value=p.key_id))`;\nconst NO_BINDING = `NOT EXISTS (SELECT 1 FROM coordinator_device_ownership_bindings b WHERE b.device_id=p.device_id OR b.key_id=p.key_id)`;\n// Legacy completion checks this requester only. A peer's legitimate prior\n// inclusion under X must not reinstate first-link's no-other-owner restriction.\nconst LEGACY_MANIFEST = `CASE WHEN typeof(c.manifest_json)='text' AND json_valid(c.manifest_json) THEN c.manifest_json ELSE '{}' END`;\nconst REQUESTER_LEGACY_COMPATIBLE = `NOT EXISTS (SELECT 1 FROM coordinator_legacy_team_completions c,\n json_each(${LEGACY_MANIFEST},'$.device_decisions') d\n WHERE json_extract(${LEGACY_MANIFEST},'$.coordinator_id')=p.coordinator_id\n AND (json_extract(d.value,'$.device_id')=p.device_id OR json_extract(d.value,'$.key_fingerprint')=p.fingerprint)\n AND (${legacyDecisionCountsAsOwnerSql(\"d.value\", \"deny\")})\n AND (json_extract(d.value,'$.decision')='excluded' OR json_extract(d.value,'$.identity_id') IS NOT p.identity_id))`;\n\nexport function deviceClaimBindingGenesisSql(connections: boolean): string {\n\treturn connections\n\t\t? authClaimGenesisSql(\"d\")\n\t\t: `EXISTS (SELECT 1 FROM coordinator_auth_account_links l WHERE l.coordinator_id=d.coordinator_id AND l.link_id=d.claim_id AND ${authDeviceClaimProvenanceSql({ link: \"l\" })})`;\n}\nfunction claimSource(connections: boolean) {\n\treturn `EXISTS (SELECT 1 FROM binding_genesis d JOIN binding_live_links l ON l.device_claim_id=d.claim_id)\n AND (SELECT count(*) FROM coordinator_auth_device_claims d WHERE d.coordinator_id=p.coordinator_id\n AND (d.device_id=p.device_id OR d.key_id=p.key_id))=1\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_link_audit_log a WHERE a.coordinator_id=p.coordinator_id\n AND a.identity_id=p.identity_id AND a.action='link_revoked')${connections ? ` AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id=p.coordinator_id AND h.identity_id=p.identity_id AND h.revoked_at_ms IS NOT NULL)` : \"\"}`;\n}\n\n// Positive provenance stays in independent root stages. Nesting the two proof\n// expressions beneath the compatibility conjunction exceeds native D1 depth 100.\nfunction claimSourceStages(connections: boolean): string {\n\treturn `binding_claims AS MATERIALIZED (SELECT d.* FROM coordinator_auth_device_claims d JOIN claim_input p\n ON (d.coordinator_id=p.coordinator_id AND d.identity_id=p.identity_id AND d.group_id=p.group_id)\n AND (d.device_id=p.device_id AND d.public_key=p.public_key AND d.fingerprint=p.fingerprint)\n AND (d.key_id=p.key_id AND d.issuer=p.issuer)),\n binding_genesis AS MATERIALIZED (SELECT d.claim_id FROM binding_claims d WHERE ${deviceClaimBindingGenesisSql(connections)}),\n binding_link_candidates AS MATERIALIZED (SELECT l.* FROM coordinator_auth_account_links l JOIN claim_input p\n ON l.coordinator_id=p.coordinator_id AND l.identity_id=p.identity_id AND l.issuer=p.issuer WHERE l.revoked_at_ms IS NULL),\n binding_live_links AS MATERIALIZED (SELECT l.device_claim_id FROM binding_link_candidates l WHERE ${authDeviceClaimProvenanceSql({ link: \"l\", connections })})`;\n}\n\n/** Captures server metadata only. The returned SQL must run inside the winning batch.\n * Unlike first-link eligibility, existing own claim/link, peer bindings and grants\n * are allowed. No attestation or negative-owner result supplies positive authority.\n */\nexport async function prepareDeviceClaimBinding(\n\tbackend: AuthLinkBackend,\n\tinput: DeviceClaimBindingInput,\n\tconfig: CoordinatorAuthLinkConfig,\n\tnow: number,\n): Promise<PreparedDeviceClaimBinding | null> {\n\treturn prepareBinding(backend, input, config, now, { reuseExistingBinding: false });\n}\n\n/** First-link producer only. Existing ownership keeps its original provenance. */\nexport async function prepareFirstLinkDeviceClaimBinding(\n\tbackend: AuthLinkBackend,\n\tinput: DeviceClaimBindingInput,\n\tconfig: CoordinatorAuthLinkConfig,\n\tnow: number,\n): Promise<PreparedDeviceClaimBinding | null> {\n\treturn prepareBinding(backend, input, config, now, { reuseExistingBinding: true });\n}\n\nasync function captureBindingPreparation(\n\tbackend: AuthLinkBackend,\n\tvalue: DeviceClaimBindingInput,\n\tconfiguration: CoordinatorAuthLinkConfig,\n\tnow: number,\n) {\n\tconst input = captureDeviceClaimBindingInput(value);\n\tconst config = captureAuthLinkConfig(configuration);\n\tif (!input || !config?.enabled || !Number.isSafeInteger(now) || now < 0) return null;\n\tconst captured = await captureDeviceClaimEligibility(\n\t\tbackend,\n\t\t{ signer: input.signer, identityId: input.currentIdentityId },\n\t\tconfig,\n\t\tnow,\n\t);\n\tif (!captured) return null;\n\treturn { input, config, captured };\n}\n\nfunction completedEnrollmentSnapshot(enrollments: string, identityId: string): string {\n\treturn JSON.stringify(\n\t\t(JSON.parse(enrollments) as Record<string, unknown>[]).map((row) => ({ ...row, identityId })),\n\t);\n}\n\n/** Its guards fail with the binding's own error, as the old pin inside `guard` made it fail. */\nfunction readBindingNegativeOwner(\n\tbackend: AuthLinkBackend,\n\tinput: DeviceClaimBindingInput,\n\tcoordinatorId: string,\n) {\n\treturn readNegativeOwnerConsistency(\n\t\tbackend,\n\t\t{\n\t\t\tcoordinatorId,\n\t\t\tdeviceId: input.signer.deviceId,\n\t\t\tpublicKey: input.signer.publicKey,\n\t\t\tfingerprint: input.signer.fingerprint,\n\t\t\townerIdentityId: input.currentIdentityId,\n\t\t\tenrollment: { groupId: input.signer.groupId },\n\t\t},\n\t\t{ guard: (holds) => assertPredicate(holds) },\n\t);\n}\n\nasync function prepareBinding(\n\tbackend: AuthLinkBackend,\n\tvalue: DeviceClaimBindingInput,\n\tconfiguration: CoordinatorAuthLinkConfig,\n\tnow: number,\n\toptions: { reuseExistingBinding: boolean },\n): Promise<PreparedDeviceClaimBinding | null> {\n\tconst prepared = await captureBindingPreparation(backend, value, configuration, now);\n\tif (!prepared) return null;\n\tconst { input, config, captured } = prepared;\n\tconst existingBinding = options.reuseExistingBinding\n\t\t? await readExistingFirstLinkBinding(\n\t\t\t\tbackend,\n\t\t\t\tinput,\n\t\t\t\tconfig.coordinatorId,\n\t\t\t\tcaptured.values[6] as string,\n\t\t\t)\n\t\t: undefined;\n\tif (existingBinding === null) return null;\n\tconst bindingGuard = existingBinding\n\t\t? existingFirstLinkBindingPin(existingBinding)\n\t\t: { sql: NO_BINDING, values: [] };\n\tconst negative = await readBindingNegativeOwner(backend, input, config.coordinatorId);\n\tif (!negative) return null;\n\tconst row = await backend.first<{ rows: string; null_count: number }>({\n\t\tsql: `SELECT json_group_array(json_object('groupId',group_id,'publicKey',public_key,'fingerprint',fingerprint,'identityId',identity_id,'enabled',enabled)) AS rows,\n sum(identity_id IS NULL) AS null_count FROM (SELECT * FROM enrolled_devices WHERE device_id=? ORDER BY group_id LIMIT 51)`,\n\t\tvalues: [input.signer.deviceId],\n\t});\n\tconst count = JSON.parse(row?.rows ?? \"[]\").length as number;\n\tif (!row || count < 1 || count > 50) return null;\n\tconst connections = await hasConnectionSessionSchema(backend);\n\tconst guardInput = {\n\t\tcaptured: captured.values,\n\t\tconnections,\n\t\tbindingGuard,\n\t\tenrollments: row.rows,\n\t};\n\treturn {\n\t\tinput,\n\t\tcoordinatorId: config.coordinatorId,\n\t\tnow,\n\t\tenrollments: row.rows,\n\t\tenrollmentCount: count,\n\t\tnullCount: row.null_count,\n\t\texistingBinding,\n\t\tguard: bindingPlanGuard(guardInput),\n\t\tcompletedGuard: existingBinding\n\t\t\t? bindingPlanGuard({\n\t\t\t\t\t...guardInput,\n\t\t\t\t\tenrollments: completedEnrollmentSnapshot(row.rows, input.currentIdentityId),\n\t\t\t\t})\n\t\t\t: undefined,\n\t\tnegativeGuards: negative.guards,\n\t\tcompletedNegativeGuards: existingBinding ? negative.retainedGuards : [],\n\t};\n}\n\nfunction bindingPlanGuard(input: {\n\tcaptured: AuthLinkStatement[\"values\"];\n\tconnections: boolean;\n\tbindingGuard: AuthLinkStatement;\n\tenrollments: string;\n}): AuthLinkStatement {\n\tconst { captured, connections, bindingGuard, enrollments } = input;\n\t// SQLite 3.54.0 and 3.54.1 (production D1) refuse a statement that resolves a CTE\n\t// name after about 100 table references. Checks that reference CTEs come first and\n\t// binding_guards is the last FROM term of binding_ok, so the plain-table checks\n\t// after them are not counted. The two checks with bound values keep their order.\n\tconst checks = [\n\t\tclaimSource(connections),\n\t\tAUTH_DEVICE_CLAIM_CURRENT_SUBJECT_COMPATIBLE_SQL,\n\t\tLIVE_SIGNER,\n\t\tEXACT_ENROLLMENTS,\n\t\tNO_REVOCATION,\n\t\tbindingGuard.sql,\n\t\tAUTH_DEVICE_CLAIM_BINDING_STRUCTURE_SQL,\n\t\tAUTH_DEVICE_CLAIM_REQUESTER_ATTESTATION_COMPATIBLE_SQL,\n\t\tAUTH_DEVICE_CLAIM_REQUESTER_INVITE_COMPATIBLE_SQL,\n\t\tAUTH_DEVICE_CLAIM_REQUESTER_LINK_COMPATIBLE_SQL,\n\t\tREQUESTER_LEGACY_COMPATIBLE,\n\t];\n\treturn {\n\t\tsql: `${AUTH_DEVICE_CLAIM_INPUT_SQL}, ${claimSourceStages(connections)},\n binding_guards AS MATERIALIZED (SELECT ${checks.map((check, index) => `(${check}) AS g${index}`).join(\",\")} FROM claim_input p),\n binding_ok AS MATERIALIZED (SELECT ${checks.map((_, index) => `g${index}`).join(\" AND \")} AS ok FROM binding_guards)\n SELECT p.*,d.claim_id FROM claim_input p JOIN coordinator_auth_device_claims d ON d.coordinator_id=p.coordinator_id AND d.device_id=p.device_id\n WHERE (SELECT ok FROM binding_ok)=1`,\n\t\tvalues: [...captured, enrollments, enrollments, ...bindingGuard.values],\n\t};\n}\n\n/** The invalid JSON path fails before any BEFORE INSERT trigger can use\n * RAISE(IGNORE) to suppress the assertion. A satisfied count projects no rows.\n */\nfunction assertChanges(expected: number): AuthLinkStatement {\n\treturn {\n\t\tsql: `INSERT INTO coordinator_device_ownership_bindings (device_id,key_id,identity_id,coordinator_id,binding_id,provenance,source_ref,bound_at)\n SELECT json_extract('{}','device_claim_binding_count_mismatch'),NULL,NULL,NULL,NULL,NULL,NULL,NULL WHERE changes()<>?`,\n\t\tvalues: [expected],\n\t};\n}\n\n/** Append after the producer's original strict first-link winning writes, or use\n * the legacy service. Never execute these outside an atomic batch. The claim,\n * genesis attempt/link/audit, and current link must already exist at execution.\n */\nexport function deviceClaimBindingStatements(\n\tplan: PreparedDeviceClaimBinding,\n\tbindingId: string,\n\teventId: string,\n\toptions: {\n\t\t/** Trusted SQL predicate identifying the exact finalized producer winner, with bound values. */ winning?: AuthLinkStatement;\n\t} = {},\n): AuthLinkStatement[] {\n\tconst { input, coordinatorId, now } = plan;\n\tconst pins = [coordinatorId, bindingId, input.signer.deviceId, input.currentIdentityId];\n\tconst winner = `b.coordinator_id=? AND b.binding_id=? AND b.device_id=? AND b.identity_id=? AND b.provenance='owner_enrollment'`;\n\tconst writes = plan.existingBinding\n\t\t? reuseFirstLinkBindingStatements(plan, plan.existingBinding)\n\t\t: [\n\t\t\t\t...plan.negativeGuards,\n\t\t\t\t{\n\t\t\t\t\tsql: `INSERT INTO coordinator_device_ownership_bindings (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,?,'owner_enrollment','device_claim:'||claim_id,? FROM (${plan.guard.sql}) WHERE 1`,\n\t\t\t\t\tvalues: [bindingId, new Date(now).toISOString(), ...plan.guard.values],\n\t\t\t\t},\n\t\t\t\tassertChanges(1),\n\t\t\t\t{\n\t\t\t\t\tsql: `UPDATE enrolled_devices SET identity_id=? WHERE device_id=? AND identity_id IS NULL AND public_key=? AND fingerprint=?\n AND EXISTS (SELECT 1 FROM coordinator_device_ownership_bindings b WHERE ${winner})`,\n\t\t\t\t\tvalues: [\n\t\t\t\t\t\tinput.currentIdentityId,\n\t\t\t\t\t\tinput.signer.deviceId,\n\t\t\t\t\t\tinput.signer.publicKey,\n\t\t\t\t\t\tinput.signer.fingerprint,\n\t\t\t\t\t\t...pins,\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\tassertChanges(plan.nullCount),\n\t\t\t\t// The existing immutable self-bind audit accepts previous=target. It records\n\t\t\t\t// the binding, exact enrollment count and completion time without a new schema.\n\t\t\t\t{\n\t\t\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,target_identity_id,enrollment_count,created_at_ms)\n SELECT b.coordinator_id,?,b.source_ref,'owner_device_rebound',b.binding_id,b.device_id,b.identity_id,b.identity_id,?,?\n FROM coordinator_device_ownership_bindings b WHERE ${winner}`,\n\t\t\t\t\tvalues: [eventId, plan.enrollmentCount, now, ...pins],\n\t\t\t\t},\n\t\t\t\tassertChanges(1),\n\t\t\t];\n\tif (!options.winning) return writes;\n\tconst winning = options.winning;\n\treturn writes.map((statement) => ({\n\t\tsql: `WITH binding_write_winner AS MATERIALIZED (SELECT (${winning.sql}) AS won) ${statement.sql} AND (SELECT won FROM binding_write_winner)=1`,\n\t\tvalues: [...winning.values, ...statement.values],\n\t}));\n}\n","import { hasConnectionSessionSchema } from \"./coordinator-account-connection-session.js\";\nimport type { AuthLinkBackend } from \"./coordinator-auth-link.js\";\nimport type { CoordinatorAuthLinkConfig } from \"./coordinator-auth-link-contract.js\";\nimport { captureAuthLinkConfig } from \"./coordinator-auth-link-input.js\";\nimport {\n\tcaptureDeviceClaimBindingInput,\n\ttype DeviceClaimBindingInput,\n\ttype DeviceClaimBindingReadiness,\n\ttype DeviceClaimBindingReceipt,\n\ttype DeviceClaimBindingResult,\n} from \"./coordinator-device-claim-binding-contract.js\";\nimport {\n\tdeviceClaimBindingGenesisSql,\n\tdeviceClaimBindingStatements,\n\tprepareDeviceClaimBinding,\n\tprepareFirstLinkDeviceClaimBinding,\n} from \"./coordinator-device-claim-binding-sql.js\";\nimport { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\n\nexport type {\n\tDeviceClaimBindingInput,\n\tDeviceClaimBindingReadiness,\n\tDeviceClaimBindingReceipt,\n\tDeviceClaimBindingResult,\n} from \"./coordinator-device-claim-binding-contract.js\";\nexport { isDeviceClaimBindingConflict } from \"./coordinator-device-claim-binding-contract.js\";\nexport {\n\tdeviceClaimBindingStatements,\n\ttype PreparedDeviceClaimBinding,\n\tprepareDeviceClaimBinding,\n\tprepareFirstLinkDeviceClaimBinding,\n} from \"./coordinator-device-claim-binding-sql.js\";\n\n/** Producer completion/retry status, not a claim-specific binding receipt.\n * Positive current claim genesis and the exact existing ownership row must both\n * verify, and every own enrollment must already name the unchanged Identity.\n */\nexport async function readFirstLinkDeviceClaimOwnershipComplete(\n\tbackend: AuthLinkBackend,\n\tinput: DeviceClaimBindingInput,\n\tconfig: CoordinatorAuthLinkConfig,\n\tnow: number,\n): Promise<boolean> {\n\tconst plan = await prepareFirstLinkDeviceClaimBinding(backend, input, config, now);\n\treturn (\n\t\t!!plan?.existingBinding && plan.nullCount === 0 && (await backend.first(plan.guard)) !== null\n\t);\n}\n\n/** Read-only immutable receipt. Enrollment changes after completion do not rewrite\n * history. The signed boundary still authenticates the exact current key.\n */\nexport async function readDeviceClaimBindingReceipt(\n\tbackend: AuthLinkBackend,\n\tvalue: DeviceClaimBindingInput,\n\tconfig: CoordinatorAuthLinkConfig,\n): Promise<DeviceClaimBindingReceipt | null> {\n\tconst i = captureDeviceClaimBindingInput(value);\n\tconst c = captureAuthLinkConfig(config);\n\tif (!i || !c?.enabled) return null;\n\tconst key = await ed25519KeyIdForRevocation(i.signer.publicKey);\n\tif (!key) return null;\n\tconst genesis = deviceClaimBindingGenesisSql(await hasConnectionSessionSchema(backend));\n\treturn backend.first<DeviceClaimBindingReceipt>({\n\t\tsql: `SELECT b.binding_id AS bindingId,d.claim_id AS claimId,b.coordinator_id AS coordinatorId,b.device_id AS deviceId,\n b.key_id AS keyId,b.identity_id AS identityId,a.enrollment_count AS enrollmentCount,b.bound_at AS boundAt\n FROM coordinator_device_ownership_bindings b JOIN coordinator_auth_device_claims d\n ON d.coordinator_id=b.coordinator_id AND b.source_ref='device_claim:'||d.claim_id AND d.device_id=b.device_id\n AND d.key_id=b.key_id AND d.identity_id=b.identity_id\n JOIN coordinator_device_rebind_audit_log a ON a.coordinator_id=b.coordinator_id AND a.binding_id=b.binding_id\n AND a.attempt_id=b.source_ref AND a.action='owner_device_rebound' AND a.device_id=b.device_id\n AND a.previous_identity_id=b.identity_id AND a.target_identity_id=b.identity_id\n AND strftime('%Y-%m-%dT%H:%M:%fZ',a.created_at_ms/1000.0,'unixepoch')=b.bound_at\n WHERE b.coordinator_id=? AND b.device_id=? AND b.key_id=? AND b.identity_id=? AND b.provenance='owner_enrollment'\n AND d.group_id=? AND d.public_key=? AND d.fingerprint=? AND d.issuer=? AND ${genesis}`,\n\t\tvalues: [\n\t\t\tc.coordinatorId,\n\t\t\ti.signer.deviceId,\n\t\t\tkey,\n\t\t\ti.currentIdentityId,\n\t\t\ti.signer.groupId,\n\t\t\ti.signer.publicKey,\n\t\t\ti.signer.fingerprint,\n\t\t\tc.issuer,\n\t\t],\n\t});\n}\n\nexport async function readDeviceClaimBindingReadiness(\n\tbackend: AuthLinkBackend,\n\tvalue: DeviceClaimBindingInput,\n\tconfig: CoordinatorAuthLinkConfig,\n\tnow: number,\n): Promise<DeviceClaimBindingReadiness> {\n\tconst i = captureDeviceClaimBindingInput(value);\n\tconst c = captureAuthLinkConfig(config);\n\tif (!i || !c?.enabled || !Number.isSafeInteger(now) || now < 0)\n\t\treturn { kind: \"requires_review\" };\n\tconst receipt = await readDeviceClaimBindingReceipt(backend, i, c);\n\tif (receipt) return { kind: \"complete\", receipt };\n\tconst plan = await prepareDeviceClaimBinding(backend, i, c, now);\n\tif (!plan || !(await backend.first(plan.guard))) return { kind: \"requires_review\" };\n\treturn { kind: \"ready\" };\n}\n\n/** Unknown outcomes propagate. Callers must read the receipt before retrying.\n * No grants, membership, other-device or local Identity writes occur here.\n */\nexport async function completeDeviceClaimBinding(\n\tbackend: AuthLinkBackend,\n\tvalue: DeviceClaimBindingInput,\n\tconfig: CoordinatorAuthLinkConfig,\n\tnow: number,\n): Promise<DeviceClaimBindingResult> {\n\tconst i = captureDeviceClaimBindingInput(value);\n\tconst c = captureAuthLinkConfig(config);\n\tif (!i || !c?.enabled || !Number.isSafeInteger(now) || now < 0)\n\t\treturn { kind: \"requires_review\" };\n\tconst receipt = await readDeviceClaimBindingReceipt(backend, i, c);\n\tif (receipt) return { kind: \"complete\", receipt };\n\tconst plan = await prepareDeviceClaimBinding(backend, i, c, now);\n\tif (!plan || !(await backend.first(plan.guard))) return { kind: \"requires_review\" };\n\tawait backend.batch(\n\t\tdeviceClaimBindingStatements(\n\t\t\tplan,\n\t\t\tglobalThis.crypto.randomUUID(),\n\t\t\tglobalThis.crypto.randomUUID(),\n\t\t),\n\t);\n\tconst committed = await readDeviceClaimBindingReceipt(backend, i, c);\n\tif (!committed) throw new Error(\"device_claim_binding_outcome_unknown\");\n\treturn { kind: \"completed\", receipt: committed };\n}\n","import {\n\tCONNECTION_RELINK_ELIGIBLE_SQL,\n\tconnectionFinalizeGuard,\n\tconnectionRequesterGuard,\n\tconnectionSuccessorStatements,\n\tcreatePinnedConnection,\n} from \"./coordinator-account-connection-link.js\";\nimport type { ConnectionSchemaState } from \"./coordinator-account-connection-schema.js\";\nimport {\n\thasConnectionSessionSchema,\n\tinitialConnectionFloor,\n} from \"./coordinator-account-connection-session.js\";\nimport { captureAuthAccountProfile } from \"./coordinator-auth-account-profile.js\";\nimport { parseCoordinatorAccountReference } from \"./coordinator-auth-contract.js\";\nimport { isAuthControllerId, isAuthControllerUniqueError } from \"./coordinator-auth-controller.js\";\nimport {\n\tAUTH_DEVICE_CLAIM_ELIGIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_INPUT_SQL,\n\tcaptureDeviceClaimEligibility,\n} from \"./coordinator-auth-device-claim-eligibility.js\";\nimport { headlessLinkProvenanceStatement } from \"./coordinator-auth-headless-provenance.js\";\nimport { hasHeadlessLinkProvenance } from \"./coordinator-auth-headless-schema.js\";\nimport { readAuthLinkAttemptAuthority } from \"./coordinator-auth-link-authority.js\";\nimport {\n\tAUTH_LINK_ATTEMPT_TTL_MS,\n\tAUTH_LINK_CREATE_WINDOW_MS,\n\tAUTH_LINK_EXPIRE_BATCH_MAX,\n\tAUTH_LINK_MAX_ACTIVE_PER_DEVICE,\n\tAUTH_LINK_MAX_ACTIVE_PER_IDENTITY,\n\tAUTH_LINK_MAX_CREATES_PER_DEVICE_RETENTION,\n\tAUTH_LINK_MAX_CREATES_PER_DEVICE_WINDOW,\n\tAUTH_LINK_MAX_UNFINISHED_PER_COORDINATOR,\n\tAUTH_LINK_PURPOSE,\n\tAUTH_LINK_RETENTION_WINDOW_MS,\n\ttype CoordinatorAuthLinkClaimInput,\n\ttype CoordinatorAuthLinkConfig,\n\ttype CoordinatorAuthLinkConfirmInput,\n\ttype CoordinatorAuthLinkCreateInput,\n\ttype CoordinatorAuthLinkCreateResult,\n\ttype CoordinatorAuthLinkError,\n\ttype CoordinatorAuthLinkFailInput,\n\ttype CoordinatorAuthLinkFinalizeInput,\n\ttype CoordinatorAuthLinkMaintenanceOptions,\n\ttype CoordinatorAuthLinkMaintenanceResult,\n\ttype CoordinatorAuthLinkOidcInput,\n\ttype CoordinatorAuthLinkOidcResult,\n\ttype CoordinatorAuthLinkRejected,\n\ttype CoordinatorAuthLinkRequester,\n\ttype CoordinatorAuthLinkResult,\n\ttype CoordinatorAuthLinkSigner,\n\ttype CoordinatorAuthLinkState,\n\ttype CoordinatorAuthLinkStatus,\n\ttype CoordinatorAuthLinkStore,\n} from \"./coordinator-auth-link-contract.js\";\nimport {\n\tAUTH_LINK_HEADLESS_MARKER,\n\tAUTH_LINK_HEADLESS_MARKER_SQL,\n\ttype CoordinatorAuthLinkHeadlessApproval,\n\ttype CoordinatorAuthLinkHeadlessApprovalInput,\n\ttype CoordinatorAuthLinkHeadlessCreateInput,\n\ttype CoordinatorAuthLinkHeadlessFinalizeInput,\n} from \"./coordinator-auth-link-headless.js\";\nimport {\n\ttype Captured,\n\tcapture,\n\tcaptureAuthLinkConfig as captureConfig,\n\tcaptureAuthLinkSigner as captureSigner,\n\tisHash,\n} from \"./coordinator-auth-link-input.js\";\nimport {\n\tcleanAuthLinkProfiles,\n\tpromoteAuthLinkProfile,\n\tstageAuthLinkProfile,\n} from \"./coordinator-auth-link-profile.js\";\nimport { CONNECTION_BIRTHS_SQL } from \"./coordinator-auth-link-provenance.js\";\nimport { captureAuthLinkSource } from \"./coordinator-auth-link-source.js\";\nimport { parseCoordinatorAuthLoopback } from \"./coordinator-auth-loopback.js\";\nimport { writeGuarded } from \"./coordinator-auth-read-set.js\";\nimport { authPersistenceError } from \"./coordinator-auth-schema.js\";\nimport {\n\tdeviceClaimBindingStatements,\n\tisDeviceClaimBindingConflict,\n\tprepareFirstLinkDeviceClaimBinding,\n\treadFirstLinkDeviceClaimOwnershipComplete,\n} from \"./coordinator-device-claim-binding.js\";\nimport { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport { readNegativeOwnerConsistency } from \"./coordinator-owner-negative-read-set.js\";\n\nexport * from \"./coordinator-auth-link-contract.js\";\nexport interface AuthLinkStatement {\n\tsql: string;\n\tvalues: (string | number | null)[];\n}\nexport interface AuthLinkBackend {\n\t/** Internal predicate preparation only; consumers must use checked SQL for output/writes. */\n\tprepareAuthLinkSource?: (\n\t\tattemptId: string,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t\talias?: \"a\" | \"coordinator_auth_link_attempts\",\n\t\toptions?: { currentDevice?: boolean },\n\t) => Promise<AuthLinkStatement>;\n\tprepareAuthLinkBrowserSource?: (\n\t\tinput: { binderHash: string; stateHash?: string; attemptId?: string },\n\t\tconfig: CoordinatorAuthLinkConfig & { redirectUri: string },\n\t\tnow: number,\n\t) => Promise<AuthLinkStatement>;\n\t/** Internal full-schema lookup on the wrapper's captured raw backend; never cached. */\n\treadAuthSchemaState?: () => Promise<ConnectionSchemaState>;\n\tfirst<T>(statement: AuthLinkStatement): Promise<T | null>;\n\tall?<T>(statement: AuthLinkStatement): Promise<T[]>;\n\t/** Runs read statements in one round trip and returns each statement's rows. */\n\treadBatch?<T>(statements: AuthLinkStatement[]): Promise<T[][]>;\n\trun(statement: AuthLinkStatement): Promise<number>;\n\t/** Atomic execution; production backends return each statement's native change count. */\n\tbatch(statements: AuthLinkStatement[]): Promise<unknown>;\n}\ninterface Attempt {\n\tprior_link_id?: string | null;\n\tauthority_kind: \"controller_attestation\" | \"device_claim\";\n\tcoordinator_id: string;\n\tattempt_id: string;\n\tidentity_id: string;\n\tgroup_id: string;\n\tdevice_id: string;\n\tpublic_key: string;\n\tfingerprint: string;\n\tcontroller_attestation_id: string | null;\n\tcontroller_review_receipt_id: string | null;\n\tcontroller_revision: number | null;\n\tissuer: string;\n\tauth_config_revision: string;\n\truntime_verifier_hash: string;\n\tbrowser_start_hash: string | null;\n\tloopback_redirect: string;\n\tstate: CoordinatorAuthLinkState;\n\tbrowser_transaction_hash: string | null;\n\taccount_subject: string | null;\n\tcompletion_secret_hash: string | null;\n\tlink_id: string | null;\n\tfailure_reason: string | null;\n\tcreated_at_ms: number;\n\texpires_at_ms: number;\n}\ninterface StagedProfile {\n\tdisplay_name: string | null;\n\temail: string | null;\n\temail_verified: number | null;\n}\n/** Capture without invoking accessors; null denotes an omitted attested commitment. */\nexport function captureAuthLinkBrowserStartHash(value: unknown): string | null | false {\n\tif (!value || typeof value !== \"object\") return false;\n\ttry {\n\t\tif (Array.isArray(value)) return false;\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, \"browserStartHash\");\n\t\tif (!descriptor) return \"browserStartHash\" in value ? false : null;\n\t\tif (!Object.hasOwn(descriptor, \"value\") || !isHash(descriptor.value)) return false;\n\t\treturn descriptor.value;\n\t} catch {\n\t\treturn false;\n\t}\n}\nfunction captureExpectedIdentity(value: unknown): string | null | false {\n\tif (!value || typeof value !== \"object\") return false;\n\ttry {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, \"expectedIdentityId\");\n\t\tif (!descriptor) return \"expectedIdentityId\" in value ? false : null;\n\t\treturn \"value\" in descriptor && isAuthControllerId(descriptor.value) ? descriptor.value : false;\n\t} catch {\n\t\treturn false;\n\t}\n}\nfunction captureCreateInput(value: unknown):\n\t| (Captured & {\n\t\t\tattemptId: string;\n\t\t\truntimeVerifierHash: string;\n\t\t\tloopbackRedirect: string;\n\t\t\tbrowserStartHash: string | null;\n\t\t\tauthority: CoordinatorAuthLinkCreateInput[\"authority\"];\n\t\t\texpectedIdentityId: string | null;\n\t })\n\t| null {\n\tconst i = capture(value, [\n\t\t\"attemptId\",\n\t\t\"signer\",\n\t\t\"runtimeVerifierHash\",\n\t\t\"loopbackRedirect\",\n\t\t\"authority\",\n\t]);\n\tconst authority = captureCreateAuthority(i?.authority);\n\tconst browserStartHash = captureAuthLinkBrowserStartHash(value);\n\tconst expectedIdentityId = captureExpectedIdentity(value);\n\tif (\n\t\t!i ||\n\t\t!authority ||\n\t\texpectedIdentityId === false ||\n\t\t(expectedIdentityId !== null &&\n\t\t\tauthority.kind === \"device_claim\" &&\n\t\t\tauthority.identityId !== expectedIdentityId) ||\n\t\tbrowserStartHash === false ||\n\t\t(authority.kind === \"device_claim\" && browserStartHash === null) ||\n\t\t!isAuthControllerId(i.attemptId) ||\n\t\t!isHash(i.runtimeVerifierHash) ||\n\t\t!parseCoordinatorAuthLoopback(i.loopbackRedirect).ok\n\t)\n\t\treturn null;\n\treturn {\n\t\t...i,\n\t\tattemptId: i.attemptId,\n\t\truntimeVerifierHash: i.runtimeVerifierHash,\n\t\tloopbackRedirect: i.loopbackRedirect as string,\n\t\tbrowserStartHash,\n\t\tauthority,\n\t\texpectedIdentityId,\n\t};\n}\ntype CreateInput = NonNullable<ReturnType<typeof captureCreateInput>>;\n/** Headless input has no loopback; the marker and user code hash fill the same columns. */\nfunction captureHeadlessCreateInput(value: unknown): CreateInput | null {\n\tconst i = capture(value, [\n\t\t\"attemptId\",\n\t\t\"signer\",\n\t\t\"runtimeVerifierHash\",\n\t\t\"userCodeHash\",\n\t\t\"authority\",\n\t]);\n\tconst authority = captureCreateAuthority(i?.authority);\n\tconst expectedIdentityId = captureExpectedIdentity(value);\n\tif (\n\t\t!i ||\n\t\t!authority ||\n\t\texpectedIdentityId === false ||\n\t\t!isAuthControllerId(i.attemptId) ||\n\t\t!isHash(i.runtimeVerifierHash) ||\n\t\t!isHash(i.userCodeHash)\n\t)\n\t\treturn null;\n\tif (\n\t\texpectedIdentityId !== null &&\n\t\tauthority.kind === \"device_claim\" &&\n\t\tauthority.identityId !== expectedIdentityId\n\t)\n\t\treturn null;\n\treturn {\n\t\tsigner: i.signer,\n\t\tattemptId: i.attemptId,\n\t\truntimeVerifierHash: i.runtimeVerifierHash,\n\t\tloopbackRedirect: AUTH_LINK_HEADLESS_MARKER,\n\t\tbrowserStartHash: i.userCodeHash,\n\t\tauthority,\n\t\texpectedIdentityId,\n\t};\n}\nfunction captureCreateAuthority(\n\tvalue: unknown,\n): CoordinatorAuthLinkCreateInput[\"authority\"] | null {\n\tconst a = capture(value, [\"kind\"]);\n\tif (a?.kind === \"controller_attestation\") return { kind: \"controller_attestation\" };\n\tif (a?.kind !== \"device_claim\") return null;\n\tconst claim = capture(value, [\"identityId\"]);\n\treturn isAuthControllerId(claim?.identityId)\n\t\t? { kind: \"device_claim\", identityId: claim.identityId }\n\t\t: null;\n}\nfunction captureRequester(value: unknown): CoordinatorAuthLinkRequester | null {\n\tconst k = capture(value, [\"kind\"]);\n\tif (k?.kind === \"device\") {\n\t\tconst s = capture(value, [\"signer\"]);\n\t\tconst signer = captureSigner(s?.signer);\n\t\treturn signer ? { kind: \"device\", signer } : null;\n\t}\n\tif (k?.kind !== \"browser\") return null;\n\tconst b = capture(value, [\"browserTransactionHash\"]);\n\treturn isHash(b?.browserTransactionHash)\n\t\t? { kind: \"browser\", browserTransactionHash: b.browserTransactionHash }\n\t\t: null;\n}\nexport function authLinkNow(clock: () => number): number {\n\tlet now: number;\n\ttry {\n\t\tnow = clock();\n\t} catch {\n\t\tthrow new Error(\"auth_link_invalid_clock\");\n\t}\n\tif (\n\t\t!Number.isSafeInteger(now) ||\n\t\tnow < 0 ||\n\t\tnow > Number.MAX_SAFE_INTEGER - AUTH_LINK_ATTEMPT_TTL_MS\n\t)\n\t\tthrow new Error(\"auth_link_invalid_clock\");\n\treturn now;\n}\nconst LINK_HOLDER_SQL = `SELECT 1 AS held FROM coordinator_auth_account_links\n WHERE coordinator_id = ? AND (identity_id = ? OR (issuer = ? AND subject = ?)) LIMIT 1`;\nfunction linkHolderValues(row: Attempt): (string | null)[] {\n\treturn [row.coordinator_id, row.identity_id, row.issuer, row.account_subject];\n}\nfunction rejected(error: CoordinatorAuthLinkError): CoordinatorAuthLinkRejected {\n\treturn { kind: \"rejected\", error };\n}\nfunction isTerminal(row: Attempt): boolean {\n\treturn [\"expired\", \"failed\", \"finalized\", \"session_redeemed\"].includes(row.state);\n}\nfunction status(row: Attempt, now: number): CoordinatorAuthLinkStatus {\n\tconst state = !isTerminal(row) && now >= row.expires_at_ms ? \"expired\" : row.state;\n\treturn { attemptId: row.attempt_id, state, expiresAtMs: row.expires_at_ms };\n}\nfunction configMatches(row: Attempt, c: CoordinatorAuthLinkConfig): boolean {\n\treturn (\n\t\tc.enabled &&\n\t\trow.coordinator_id === c.coordinatorId &&\n\t\trow.issuer === c.issuer &&\n\t\trow.auth_config_revision === c.revision\n\t);\n}\nfunction signerMatches(row: Attempt, s: CoordinatorAuthLinkSigner): boolean {\n\treturn (\n\t\trow.group_id === s.groupId &&\n\t\trow.device_id === s.deviceId &&\n\t\trow.public_key === s.publicKey &&\n\t\trow.fingerprint === s.fingerprint\n\t);\n}\nfunction creationMatches(\n\trow: Attempt,\n\ti: CreateInput,\n\ts: CoordinatorAuthLinkSigner,\n\tc: CoordinatorAuthLinkConfig,\n): boolean {\n\treturn (\n\t\tconfigMatches(row, c) &&\n\t\tsignerMatches(row, s) &&\n\t\trow.authority_kind === i.authority.kind &&\n\t\t(i.expectedIdentityId === null || row.identity_id === i.expectedIdentityId) &&\n\t\t(i.authority.kind !== \"device_claim\" || row.identity_id === i.authority.identityId) &&\n\t\trow.runtime_verifier_hash === i.runtimeVerifierHash &&\n\t\trow.browser_start_hash === i.browserStartHash &&\n\t\trow.loopback_redirect === i.loopbackRedirect\n\t);\n}\nfunction requesterMatches(row: Attempt, r: CoordinatorAuthLinkRequester): boolean {\n\tif (r.kind === \"device\") return signerMatches(row, r.signer);\n\treturn row.browser_transaction_hash === r.browserTransactionHash;\n}\nfunction diagnose(\n\trow: Attempt | null,\n\tc: CoordinatorAuthLinkConfig,\n\tnow: number,\n): CoordinatorAuthLinkRejected {\n\tif (!row) return rejected(\"attempt_unavailable\");\n\tif (!configMatches(row, c)) return rejected(\"auth_config_changed\");\n\tif (row.state === \"expired\") return rejected(\"attempt_expired\");\n\tif (!isTerminal(row) && row.expires_at_ms <= now) return rejected(\"attempt_expired\");\n\treturn rejected(\"attempt_unavailable\");\n}\n// Mode predicates run inside each write so one mode can never advance the other's rows.\nconst DESKTOP_MODE_SQL = `loopback_redirect <> ${AUTH_LINK_HEADLESS_MARKER_SQL}`;\nconst HEADLESS_MODE_SQL = `loopback_redirect = ${AUTH_LINK_HEADLESS_MARKER_SQL}`;\nconst LIVE_CONFIG =\n\t\"coordinator_id = ? AND issuer = ? AND auth_config_revision = ? AND ? = 1 AND authority_kind = 'controller_attestation'\";\nconst CURRENT_CONFIG = \"coordinator_id = ? AND issuer = ? AND auth_config_revision = ? AND ? = 1\";\n// Cancellation and time cleanup release an uncommitted promise, not ownership.\nconst RELEASABLE_SOURCE = `(authority_kind = 'controller_attestation' OR\n (authority_kind = 'device_claim' AND controller_attestation_id IS NULL\n AND controller_review_receipt_id IS NULL AND controller_revision IS NULL))`;\nfunction configValues(c: CoordinatorAuthLinkConfig): (string | number)[] {\n\treturn [c.coordinatorId, c.issuer, c.revision, Number(c.enabled)];\n}\ninterface AuthoritySource {\n\tgroup_id: string;\n\tdevice_id: string;\n\tpublic_key: string;\n\tfingerprint: string;\n\tidentity_id: string | null;\n\tcontroller_identity_id: string;\n\tattestation_id: string;\n\treview_receipt_id: string;\n\trevision: number;\n}\nconst AUTHORITY_COLUMNS = `e.group_id, e.device_id, e.public_key, e.fingerprint, e.identity_id,\n a.identity_id AS controller_identity_id, a.attestation_id, a.review_receipt_id, a.revision`;\n// Pin this call's enrollment, not the historical enrollment Identity in the attestation.\nconst AUTHORITY_GUARD = `AND e.group_id = ? AND e.device_id = ? AND e.public_key = ?\n AND e.fingerprint = ? AND e.identity_id IS ? AND a.identity_id = ?\n AND a.attestation_id = ? AND a.review_receipt_id = ? AND a.revision = ?\n AND NOT EXISTS (SELECT 1 FROM coordinator_device_revocations WHERE\n (subject_kind = 'device_id' AND subject_value = ?) OR\n (subject_kind = 'ed25519_key' AND subject_value = ?))`;\nfunction authorityValues(\n\tsource: AuthoritySource,\n\tkeyId: string | null,\n): (string | number | null)[] {\n\treturn [\n\t\tsource.group_id,\n\t\tsource.device_id,\n\t\tsource.public_key,\n\t\tsource.fingerprint,\n\t\tsource.identity_id,\n\t\tsource.controller_identity_id,\n\t\tsource.attestation_id,\n\t\tsource.review_receipt_id,\n\t\tsource.revision,\n\t\tsource.device_id,\n\t\tkeyId,\n\t];\n}\nasync function deriveAuthority(source: AuthoritySource): Promise<(string | number | null)[]> {\n\tconst values = authorityValues(source, null);\n\ttry {\n\t\tvalues[values.length - 1] = await ed25519KeyIdForRevocation(source.public_key);\n\t\treturn values;\n\t} catch {\n\t\tthrow new Error(\"auth_link_persistence_error\");\n\t}\n}\nconst AUTHORITY_SOURCE_SQL = `coordinator_auth_controller_attestations a\n JOIN enrolled_devices e ON e.group_id = a.group_id AND e.device_id = a.device_id\n JOIN groups g ON g.group_id = a.group_id\n WHERE a.coordinator_id = coordinator_auth_link_attempts.coordinator_id\n AND coordinator_auth_link_attempts.authority_kind = 'controller_attestation'\n AND a.attestation_id = coordinator_auth_link_attempts.controller_attestation_id AND a.review_receipt_id = coordinator_auth_link_attempts.controller_review_receipt_id\n AND a.revision = coordinator_auth_link_attempts.controller_revision AND a.revoked_at IS NULL\n AND a.identity_id = coordinator_auth_link_attempts.identity_id\n AND a.group_id = coordinator_auth_link_attempts.group_id AND a.device_id = coordinator_auth_link_attempts.device_id\n AND a.public_key = coordinator_auth_link_attempts.public_key AND a.fingerprint = coordinator_auth_link_attempts.fingerprint\n AND e.enabled = 1 AND g.archived_at IS NULL AND e.public_key = a.public_key AND e.fingerprint = a.fingerprint\n AND (e.identity_id IS NULL OR e.identity_id = a.identity_id)`;\nconst AUTHORITY = `EXISTS (SELECT 1 FROM ${AUTHORITY_SOURCE_SQL} ${AUTHORITY_GUARD})`;\nconst CREATE_SOURCE_SQL = `FROM coordinator_auth_controller_attestations a\n JOIN enrolled_devices e ON e.group_id = a.group_id AND e.device_id = a.device_id\n JOIN groups g ON g.group_id = a.group_id\n WHERE a.coordinator_id = ? AND a.group_id = ? AND a.device_id = ? AND a.public_key = ? AND a.fingerprint = ?\n AND a.revoked_at IS NULL AND a.revision = 1 AND ? = 1 AND e.enabled = 1 AND g.archived_at IS NULL\n AND e.public_key = a.public_key AND e.fingerprint = a.fingerprint AND (e.identity_id IS NULL OR e.identity_id = a.identity_id)`;\nconst CREATE_SQL = `INSERT INTO coordinator_auth_link_attempts (\n coordinator_id, attempt_id, identity_id, group_id, device_id, public_key, fingerprint,\n controller_attestation_id, controller_review_receipt_id, controller_revision, authority_kind,\n issuer, auth_config_revision, runtime_verifier_hash, loopback_redirect, browser_start_hash, state, created_at_ms, expires_at_ms)\n SELECT ?, ?, a.identity_id, a.group_id, a.device_id, a.public_key, a.fingerprint,\n a.attestation_id, a.review_receipt_id, a.revision, 'controller_attestation', ?, ?, ?, ?, ?, 'pending', ?, ?\n ${CREATE_SOURCE_SQL} ${AUTHORITY_GUARD}\n ${creationAdmissionSql(\"a\")}`;\nfunction creationAdmissionSql(source: \"a\" | \"p\"): string {\n\treturn `\n AND NOT EXISTS (SELECT 1 FROM coordinator_owner_enrollment_attempts t\n WHERE t.coordinator_id = ${source}.coordinator_id AND t.attempt_id = ?)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_browser_transactions t\n WHERE t.coordinator_id = ${source}.coordinator_id AND t.attempt_id = ? AND t.purpose NOT IN ('signin','link'))\n AND (SELECT count(*) FROM coordinator_auth_link_attempts t\n WHERE t.coordinator_id = ${source}.coordinator_id AND t.group_id = ${source}.group_id AND t.device_id = ${source}.device_id\n AND t.state IN ('pending','browser_claimed','oidc_verified','confirmed') AND t.expires_at_ms > ?) < ?\n AND (SELECT count(*) FROM coordinator_auth_link_attempts t\n WHERE t.coordinator_id = ${source}.coordinator_id AND t.identity_id = ${source}.identity_id\n AND t.state IN ('pending','browser_claimed','oidc_verified','confirmed') AND t.expires_at_ms > ?) < ?\n AND (SELECT count(*) FROM coordinator_auth_link_attempts t\n WHERE t.coordinator_id = ${source}.coordinator_id AND t.group_id = ${source}.group_id AND t.device_id = ${source}.device_id\n AND t.created_at_ms > ?) < ?\n AND (SELECT count(*) FROM coordinator_auth_link_attempts t\n WHERE t.coordinator_id = ${source}.coordinator_id AND t.group_id = ${source}.group_id AND t.device_id = ${source}.device_id\n AND t.created_at_ms > ?) < ?\n AND (SELECT count(*) FROM (SELECT 1 FROM coordinator_auth_link_attempts t\n WHERE t.coordinator_id = ${source}.coordinator_id AND t.state NOT IN ('finalized','session_redeemed') LIMIT ?)) < ?`;\n}\nfunction creationAdmissionValues(attemptId: string, now: number): (string | number)[] {\n\treturn [\n\t\tattemptId,\n\t\tattemptId,\n\t\tnow,\n\t\tAUTH_LINK_MAX_ACTIVE_PER_DEVICE,\n\t\tnow,\n\t\tAUTH_LINK_MAX_ACTIVE_PER_IDENTITY,\n\t\tnow - AUTH_LINK_CREATE_WINDOW_MS,\n\t\tAUTH_LINK_MAX_CREATES_PER_DEVICE_WINDOW,\n\t\tnow - AUTH_LINK_RETENTION_WINDOW_MS,\n\t\tAUTH_LINK_MAX_CREATES_PER_DEVICE_RETENTION,\n\t\tAUTH_LINK_MAX_UNFINISHED_PER_COORDINATOR,\n\t\tAUTH_LINK_MAX_UNFINISHED_PER_COORDINATOR,\n\t];\n}\nfunction deviceCreationEligibilitySql(options: { relink: boolean }): string {\n\treturn options.relink ? CONNECTION_RELINK_ELIGIBLE_SQL : AUTH_DEVICE_CLAIM_ELIGIBLE_SQL;\n}\nfunction isSharedAdmissionLimit(error: unknown): boolean {\n\treturn (\n\t\terror instanceof Error &&\n\t\t/^(?:D1_ERROR: )?connection_attempt_limited(?:: SQLITE_CONSTRAINT(?: \\(extended: SQLITE_CONSTRAINT_TRIGGER\\))?)?$/.test(\n\t\t\terror.message,\n\t\t)\n\t);\n}\nconst DEVICE_CREATE_SQL = `${AUTH_DEVICE_CLAIM_INPUT_SQL}\n INSERT INTO coordinator_auth_link_attempts (\n coordinator_id,attempt_id,identity_id,group_id,device_id,public_key,fingerprint,\n controller_attestation_id,controller_review_receipt_id,controller_revision,authority_kind,\n issuer,auth_config_revision,runtime_verifier_hash,loopback_redirect,browser_start_hash,state,created_at_ms,expires_at_ms)\n SELECT p.coordinator_id,p.attempt_id,p.identity_id,p.group_id,p.device_id,p.public_key,p.fingerprint,\n NULL,NULL,NULL,'device_claim',p.issuer,p.revision,?,?,?,'pending',p.now_ms,p.now_ms + ${AUTH_LINK_ATTEMPT_TTL_MS}\n FROM claim_input p WHERE ${AUTH_DEVICE_CLAIM_ELIGIBLE_SQL} ${creationAdmissionSql(\"p\")}`;\nconst DEVICE_RETRY_SQL = `${AUTH_DEVICE_CLAIM_INPUT_SQL}\n SELECT 1 FROM claim_input p JOIN coordinator_auth_link_attempts t\n ON t.coordinator_id = p.coordinator_id AND t.attempt_id = p.attempt_id\n WHERE t.authority_kind = 'device_claim' AND t.identity_id = p.identity_id\n AND t.group_id = p.group_id AND t.device_id = p.device_id AND t.public_key = p.public_key AND t.fingerprint = p.fingerprint\n AND t.issuer = p.issuer AND t.auth_config_revision = p.revision\n AND t.runtime_verifier_hash = ? AND t.browser_start_hash IS ? AND t.loopback_redirect = ?\n AND t.state <> 'expired' AND t.expires_at_ms > p.now_ms AND ${AUTH_DEVICE_CLAIM_ELIGIBLE_SQL}`;\nconst MAINTENANCE_CANDIDATE_SQL = `${RELEASABLE_SOURCE} AND link_id IS NULL AND (\n (state IN ('pending','browser_claimed','oidc_verified','confirmed') AND expires_at_ms <= ?)\n OR (state IN ('failed','expired') AND account_subject IS NOT NULL))`;\nconst MAINTENANCE_SQL = `UPDATE coordinator_auth_link_attempts\n SET state = CASE WHEN state = 'failed' THEN 'failed' ELSE 'expired' END, account_subject = NULL\n WHERE coordinator_id = ? AND ${MAINTENANCE_CANDIDATE_SQL}\n AND attempt_id IN (SELECT attempt_id FROM coordinator_auth_link_attempts\n WHERE coordinator_id = ? AND ${MAINTENANCE_CANDIDATE_SQL}\n ORDER BY expires_at_ms, attempt_id LIMIT ?)`;\nfunction captureMaintenanceLimit(options: unknown): number | null {\n\tif (options === undefined) return AUTH_LINK_EXPIRE_BATCH_MAX;\n\tif (!options || typeof options !== \"object\") return null;\n\ttry {\n\t\tif (Array.isArray(options)) return null;\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(options, \"limit\");\n\t\tif (!descriptor) {\n\t\t\tif (\"limit\" in options) return null;\n\t\t\treturn AUTH_LINK_EXPIRE_BATCH_MAX;\n\t\t}\n\t\tif (!Object.hasOwn(descriptor, \"value\")) return null;\n\t\tconst limit: unknown = descriptor.value;\n\t\tif (\n\t\t\ttypeof limit !== \"number\" ||\n\t\t\t!Number.isSafeInteger(limit) ||\n\t\t\tlimit < 1 ||\n\t\t\tlimit > AUTH_LINK_EXPIRE_BATCH_MAX\n\t\t)\n\t\t\treturn null;\n\t\treturn limit;\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction createSourceValues(\n\tc: CoordinatorAuthLinkConfig,\n\ts: CoordinatorAuthLinkSigner,\n): (string | number)[] {\n\treturn [c.coordinatorId, s.groupId, s.deviceId, s.publicKey, s.fingerprint, Number(c.enabled)];\n}\n\nexport type { AuthoritySource as AuthLinkAuthoritySource };\n// Shared with the read-only own-account query: never derive authority from labels alone.\nexport {\n\tAUTHORITY_COLUMNS as AUTH_LINK_AUTHORITY_COLUMNS,\n\tAUTHORITY_GUARD as AUTH_LINK_AUTHORITY_GUARD_SQL,\n\tCREATE_SOURCE_SQL as AUTH_LINK_CONTROLLER_SOURCE_SQL,\n\tcaptureConfig as captureAuthLinkConfig,\n\tcaptureSigner as captureAuthLinkSigner,\n\tcreateSourceValues as authLinkControllerSourceValues,\n\tderiveAuthority as deriveAuthLinkAuthority,\n};\n\n/** Optional persistence capability. No token verification, routes, sessions or grants. */\nexport class AuthLinkOperations implements CoordinatorAuthLinkStore {\n\tconstructor(\n\t\tprivate readonly backend: AuthLinkBackend,\n\t\tprivate readonly clock: () => number = Date.now,\n\t) {}\n\tprivate async read(\n\t\tattemptId: string,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tsource: { authority: Attempt[\"authority_kind\"] | \"either\" } = {\n\t\t\tauthority: \"controller_attestation\",\n\t\t},\n\t): Promise<Attempt | null> {\n\t\tconst row = await this.first<Attempt>({\n\t\t\tsql: `SELECT * FROM coordinator_auth_link_attempts WHERE coordinator_id = ? AND attempt_id = ?${source.authority === \"either\" ? \"\" : \" AND authority_kind = ?\"}`,\n\t\t\tvalues: [\n\t\t\t\tc.coordinatorId,\n\t\t\t\tattemptId,\n\t\t\t\t...(source.authority === \"either\" ? [] : [source.authority]),\n\t\t\t],\n\t\t});\n\t\tconst authority = row && readAuthLinkAttemptAuthority(row);\n\t\treturn authority && (source.authority === \"either\" || authority.kind === source.authority)\n\t\t\t? row\n\t\t\t: null;\n\t}\n\tprivate async first<T>(statement: AuthLinkStatement): Promise<T | null> {\n\t\ttry {\n\t\t\treturn await this.backend.first<T>(statement);\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_link_persistence_error\");\n\t\t}\n\t}\n\tprivate async connectionSchema(): Promise<boolean> {\n\t\ttry {\n\t\t\treturn await hasConnectionSessionSchema(this.backend);\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_link_persistence_error\");\n\t\t}\n\t}\n\tprivate async execute(\n\t\tstatement: AuthLinkStatement,\n\t\tconflict: CoordinatorAuthLinkError,\n\t\toptions: { sharedAdmission?: boolean } = {},\n\t): Promise<number | CoordinatorAuthLinkRejected> {\n\t\ttry {\n\t\t\treturn await this.backend.run(statement);\n\t\t} catch (error) {\n\t\t\tif (isAuthControllerUniqueError(error)) return rejected(conflict);\n\t\t\tif (options.sharedAdmission && isSharedAdmissionLimit(error)) return 0;\n\t\t\tthrow authPersistenceError(error, \"auth_link_persistence_error\");\n\t\t}\n\t}\n\tprivate async readAuthority(\n\t\tattemptId: string,\n\t\tc: CoordinatorAuthLinkConfig,\n\t): Promise<(string | number | null)[] | null> {\n\t\tconst source = await this.first<AuthoritySource>({\n\t\t\tsql: `SELECT ${AUTHORITY_COLUMNS} FROM coordinator_auth_link_attempts,\n\t\t\t ${AUTHORITY_SOURCE_SQL} AND coordinator_auth_link_attempts.attempt_id = ?\n\t\t\t AND coordinator_auth_link_attempts.coordinator_id = ?\n\t\t\t AND coordinator_auth_link_attempts.issuer = ?\n\t\t\t AND coordinator_auth_link_attempts.auth_config_revision = ? AND ? = 1`,\n\t\t\tvalues: [attemptId, ...configValues(c)],\n\t\t});\n\t\tif (!source) return null;\n\t\treturn deriveAuthority(source);\n\t}\n\tprivate async source(\n\t\tattemptId: string,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t\toptions: { currentDevice?: boolean } = {},\n\t) {\n\t\ttry {\n\t\t\tconst prepare = this.backend.prepareAuthLinkSource;\n\t\t\tif (prepare)\n\t\t\t\treturn await prepare(attemptId, c, now, \"coordinator_auth_link_attempts\", options);\n\t\t\treturn await captureAuthLinkSource(\n\t\t\t\tthis.backend,\n\t\t\t\tattemptId,\n\t\t\t\tc,\n\t\t\t\tnow,\n\t\t\t\t\"coordinator_auth_link_attempts\",\n\t\t\t\toptions,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_link_persistence_error\");\n\t\t}\n\t}\n\tasync maintainAuthLinkAttempts(\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t\toptions?: CoordinatorAuthLinkMaintenanceOptions,\n\t): Promise<CoordinatorAuthLinkMaintenanceResult> {\n\t\tconst c = captureConfig(config);\n\t\tconst limit = captureMaintenanceLimit(options);\n\t\tif (!c || limit === null) return rejected(\"invalid_input\");\n\t\tif (!c.enabled) return rejected(\"auth_config_changed\");\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst result = await this.execute(\n\t\t\t{\n\t\t\t\tsql: MAINTENANCE_SQL,\n\t\t\t\tvalues: [c.coordinatorId, now, c.coordinatorId, now, limit],\n\t\t\t},\n\t\t\t\"attempt_conflict\",\n\t\t);\n\t\tif (typeof result !== \"number\") return result;\n\t\tconst cleaned = await this.execute(cleanAuthLinkProfiles(c, now, limit), \"attempt_conflict\");\n\t\tif (typeof cleaned !== \"number\") return cleaned;\n\t\treturn {\n\t\t\tkind: \"maintained\",\n\t\t\tprocessedCount: result,\n\t\t\tmore: result === limit || cleaned === limit,\n\t\t};\n\t}\n\tasync createAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkCreateInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkCreateResult> {\n\t\treturn this.createCaptured(captureCreateInput(input), config);\n\t}\n\t/** Same authority, admission and exact-retry rules as desktop create. */\n\tasync createHeadlessAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkHeadlessCreateInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkCreateResult> {\n\t\treturn this.createCaptured(captureHeadlessCreateInput(input), config);\n\t}\n\tprivate async createCaptured(\n\t\ti: CreateInput | null,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkCreateResult> {\n\t\tconst c = captureConfig(config);\n\t\tconst s = captureSigner(i?.signer);\n\t\tif (!c || !i || !s) return rejected(\"invalid_input\");\n\t\tif (!c.enabled) return rejected(\"auth_config_changed\");\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst existing = await this.read(i.attemptId, c, { authority: \"either\" });\n\t\tif (existing) return this.retryCreation(existing, i, s, c, now);\n\t\tif (i.authority.kind === \"device_claim\") return this.createDeviceAttempt(i, s, c, now);\n\t\treturn this.createAttestedAttempt(i, s, c, now);\n\t}\n\tprivate async createAttestedAttempt(\n\t\ti: CreateInput,\n\t\ts: CoordinatorAuthLinkSigner,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t): Promise<CoordinatorAuthLinkCreateResult> {\n\t\tconst source = await this.first<AuthoritySource>({\n\t\t\tsql: `SELECT ${AUTHORITY_COLUMNS} ${CREATE_SOURCE_SQL}`,\n\t\t\tvalues: createSourceValues(c, s),\n\t\t});\n\t\tif (!source) {\n\t\t\tconst row = await this.read(i.attemptId, c, { authority: \"either\" });\n\t\t\tif (row) return this.createRetry(row, i, s, c, now, null);\n\t\t\treturn rejected(\"controller_not_active\");\n\t\t}\n\t\tconst authority = await deriveAuthority(source);\n\t\tif (i.expectedIdentityId !== null && source.controller_identity_id !== i.expectedIdentityId)\n\t\t\treturn rejected(\"controller_not_active\");\n\t\tconst values = [\n\t\t\tc.coordinatorId,\n\t\t\ti.attemptId,\n\t\t\tc.issuer,\n\t\t\tc.revision,\n\t\t\ti.runtimeVerifierHash,\n\t\t\ti.loopbackRedirect as string,\n\t\t\ti.browserStartHash,\n\t\t\tnow,\n\t\t\tnow + AUTH_LINK_ATTEMPT_TTL_MS,\n\t\t\t...createSourceValues(c, s),\n\t\t\t...authority,\n\t\t\t...creationAdmissionValues(i.attemptId, now),\n\t\t];\n\t\tconst result = await this.executeCreation(\n\t\t\t{ sql: CREATE_SQL, values },\n\t\t\t{\n\t\t\t\tcoordinator: c.coordinatorId,\n\t\t\t\tattempt: i.attemptId,\n\t\t\t\tidentity: source.controller_identity_id,\n\t\t\t\tnow,\n\t\t\t},\n\t\t\ts,\n\t\t\tc,\n\t\t);\n\t\tconst row = await this.read(i.attemptId, c, { authority: \"either\" });\n\t\tif (result === 0) {\n\t\t\tif (row) return this.createRetry(row, i, s, c, now, authority);\n\t\t\treturn this.diagnoseCreateAdmission(i.attemptId, c, s, authority);\n\t\t}\n\t\t// On the current account schema a refused pinned insert reports a rejection instead of\n\t\t// zero rows. When the V2 insert itself would have written nothing, the V2 diagnosis\n\t\t// names the reason: inactive authority, a reserved ID, or exhausted admission.\n\t\tif (\n\t\t\ttypeof result !== \"number\" &&\n\t\t\t!row &&\n\t\t\t!(await this.wouldAdmitCreation(i, s, c, now, authority))\n\t\t)\n\t\t\treturn this.diagnoseCreateAdmission(i.attemptId, c, s, authority);\n\t\tif (typeof result !== \"number\") return this.createRetry(row, i, s, c, now, authority);\n\t\tif (!row || !creationMatches(row, i, s, c)) throw new Error(\"auth_link_persistence_incomplete\");\n\t\treturn { kind: \"created\", status: status(row, now), identityId: row.identity_id };\n\t}\n\tprivate async executeCreation(\n\t\tstatement: AuthLinkStatement,\n\t\tpin: { coordinator: string; attempt: string; identity: string; now: number },\n\t\tsigner: CoordinatorAuthLinkSigner,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<number | CoordinatorAuthLinkRejected> {\n\t\tif (!(await this.connectionSchema())) return this.execute(statement, \"attempt_conflict\");\n\t\ttry {\n\t\t\tconst guard = await connectionRequesterGuard(\n\t\t\t\tthis.backend,\n\t\t\t\tpin.identity,\n\t\t\t\tsigner,\n\t\t\t\tconfig,\n\t\t\t\tpin.now,\n\t\t\t);\n\t\t\treturn await createPinnedConnection(\n\t\t\t\tthis.backend,\n\t\t\t\t{\n\t\t\t\t\tsql: `${statement.sql} AND ${guard.sql}`,\n\t\t\t\t\tvalues: [...statement.values, ...guard.values],\n\t\t\t\t},\n\t\t\t\tpin,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (isAuthControllerUniqueError(error)) return rejected(\"attempt_conflict\");\n\t\t\tif (isSharedAdmissionLimit(error)) return 0;\n\t\t\tif (String(error).includes(\"NOT NULL constraint failed\"))\n\t\t\t\treturn rejected(\"attempt_unavailable\");\n\t\t\tthrow authPersistenceError(error, \"auth_link_persistence_error\");\n\t\t}\n\t}\n\tprivate async retryCreation(\n\t\trow: Attempt,\n\t\ti: CreateInput,\n\t\ts: CoordinatorAuthLinkSigner,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t): Promise<CoordinatorAuthLinkCreateResult> {\n\t\tif (!creationMatches(row, i, s, c) || row.state === \"expired\" || row.expires_at_ms <= now)\n\t\t\treturn rejected(\"attempt_conflict\");\n\t\tif (i.authority.kind === \"device_claim\") {\n\t\t\tif (row.prior_link_id) return this.retryContinuation(row, i, c, now);\n\t\t\tconst captured = await this.captureDevice(i, s, c, now);\n\t\t\tconst active =\n\t\t\t\tcaptured &&\n\t\t\t\t(await this.first({\n\t\t\t\t\tsql: DEVICE_RETRY_SQL,\n\t\t\t\t\tvalues: [\n\t\t\t\t\t\t...captured.values,\n\t\t\t\t\t\ti.runtimeVerifierHash,\n\t\t\t\t\t\ti.browserStartHash,\n\t\t\t\t\t\ti.loopbackRedirect,\n\t\t\t\t\t],\n\t\t\t\t}));\n\t\t\tif (!active) {\n\t\t\t\tconst current = await this.read(i.attemptId, c, { authority: \"either\" });\n\t\t\t\treturn rejected(\n\t\t\t\t\tcurrent && !creationMatches(current, i, s, c)\n\t\t\t\t\t\t? \"attempt_conflict\"\n\t\t\t\t\t\t: \"attempt_unavailable\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (await this.readOwnerReservation(i.attemptId, c)) return rejected(\"attempt_conflict\");\n\t\t\treturn { kind: \"existing\", status: status(row, now), identityId: row.identity_id };\n\t\t}\n\t\treturn this.createRetry(row, i, s, c, now, await this.readAuthority(i.attemptId, c));\n\t}\n\tprivate async retryContinuation(\n\t\trow: Attempt,\n\t\ti: CreateInput,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t): Promise<CoordinatorAuthLinkCreateResult> {\n\t\tconst source = await this.source(i.attemptId, c, now);\n\t\tif (\n\t\t\t!(await this.first({\n\t\t\t\tsql: `SELECT 1 FROM coordinator_auth_link_attempts WHERE coordinator_id = ? AND attempt_id = ? AND ${source.sql}`,\n\t\t\t\tvalues: [c.coordinatorId, i.attemptId, ...source.values],\n\t\t\t}))\n\t\t)\n\t\t\treturn rejected(\"attempt_unavailable\");\n\t\treturn { kind: \"existing\", status: status(row, now), identityId: row.identity_id };\n\t}\n\tprivate async captureDevice(\n\t\ti: CreateInput,\n\t\ts: CoordinatorAuthLinkSigner,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t) {\n\t\tif (i.authority.kind !== \"device_claim\") return null;\n\t\ttry {\n\t\t\treturn await captureDeviceClaimEligibility(\n\t\t\t\tthis.backend,\n\t\t\t\t{ signer: s, identityId: i.authority.identityId, attemptId: i.attemptId },\n\t\t\t\tc,\n\t\t\t\tnow,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_link_persistence_error\");\n\t\t}\n\t}\n\tprivate async createDeviceAttempt(\n\t\ti: CreateInput,\n\t\ts: CoordinatorAuthLinkSigner,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t): Promise<CoordinatorAuthLinkCreateResult> {\n\t\tconst captured = await this.captureDevice(i, s, c, now);\n\t\tif (!captured) return rejected(\"attempt_unavailable\");\n\t\tconst relink =\n\t\t\tcaptured.connectionSession &&\n\t\t\t(await this.first({\n\t\t\t\tsql: \"SELECT 1 FROM coordinator_auth_device_claims WHERE coordinator_id = ? AND identity_id = ?\",\n\t\t\t\tvalues: [c.coordinatorId, captured.identityId],\n\t\t\t}));\n\t\tconst result = await this.execute(\n\t\t\t{\n\t\t\t\tsql: relink\n\t\t\t\t\t? `${AUTH_DEVICE_CLAIM_INPUT_SQL} INSERT INTO coordinator_auth_link_attempts\n (coordinator_id,attempt_id,identity_id,group_id,device_id,public_key,fingerprint,controller_attestation_id,controller_review_receipt_id,controller_revision,authority_kind,issuer,auth_config_revision,runtime_verifier_hash,loopback_redirect,browser_start_hash,state,created_at_ms,expires_at_ms,prior_link_id)\n SELECT p.coordinator_id,p.attempt_id,p.identity_id,p.group_id,p.device_id,p.public_key,p.fingerprint,NULL,NULL,NULL,'device_claim',p.issuer,p.revision,?,?,?,'pending',p.now_ms,p.now_ms+600000,\n (SELECT h.link_id FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id=p.coordinator_id AND h.identity_id=p.identity_id AND h.successor_link_id IS NULL)\n FROM claim_input p WHERE ${CONNECTION_RELINK_ELIGIBLE_SQL} ${creationAdmissionSql(\"p\")}`\n\t\t\t\t\t: DEVICE_CREATE_SQL,\n\t\t\t\tvalues: [\n\t\t\t\t\t...captured.values,\n\t\t\t\t\ti.runtimeVerifierHash,\n\t\t\t\t\ti.loopbackRedirect,\n\t\t\t\t\ti.browserStartHash,\n\t\t\t\t\t...creationAdmissionValues(i.attemptId, now),\n\t\t\t\t],\n\t\t\t},\n\t\t\t\"attempt_conflict\",\n\t\t\t{ sharedAdmission: captured.connectionSession },\n\t\t);\n\t\tconst eligibility = deviceCreationEligibilitySql({ relink: Boolean(relink) });\n\t\tconst row = await this.read(i.attemptId, c, { authority: \"either\" });\n\t\tif (typeof result !== \"number\" || result === 0) {\n\t\t\tif (row) return this.retryCreation(row, i, s, c, now);\n\t\t\tif (typeof result !== \"number\") return result;\n\t\t\tconst eligible = await this.first({\n\t\t\t\tsql: `${AUTH_DEVICE_CLAIM_INPUT_SQL} SELECT 1 FROM claim_input p WHERE ${eligibility}`,\n\t\t\t\tvalues: captured.values,\n\t\t\t});\n\t\t\tif (!eligible) return rejected(\"attempt_unavailable\");\n\t\t\treturn rejected(\n\t\t\t\t(await this.readOwnerReservation(i.attemptId, c)) ? \"attempt_conflict\" : \"attempt_limited\",\n\t\t\t);\n\t\t}\n\t\tif (!row || !creationMatches(row, i, s, c)) throw new Error(\"auth_link_persistence_incomplete\");\n\t\treturn { kind: \"created\", status: status(row, now), identityId: row.identity_id };\n\t}\n\t/** Whether the attested INSERT's own source, authority and admission predicates hold. */\n\tprivate async wouldAdmitCreation(\n\t\ti: CreateInput,\n\t\ts: CoordinatorAuthLinkSigner,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t\tauthority: (string | number | null)[],\n\t): Promise<boolean> {\n\t\tconst admitted = await this.first({\n\t\t\tsql: `SELECT 1 ${CREATE_SOURCE_SQL} ${AUTHORITY_GUARD} ${creationAdmissionSql(\"a\")}`,\n\t\t\tvalues: [\n\t\t\t\t...createSourceValues(c, s),\n\t\t\t\t...authority,\n\t\t\t\t...creationAdmissionValues(i.attemptId, now),\n\t\t\t],\n\t\t});\n\t\treturn admitted !== null;\n\t}\n\tprivate async diagnoseCreateAdmission(\n\t\tattemptId: string,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\ts: CoordinatorAuthLinkSigner,\n\t\tauthority: (string | number | null)[],\n\t): Promise<CoordinatorAuthLinkCreateResult> {\n\t\tconst active = await this.first({\n\t\t\tsql: `SELECT 1 ${CREATE_SOURCE_SQL} ${AUTHORITY_GUARD}`,\n\t\t\tvalues: [...createSourceValues(c, s), ...authority],\n\t\t});\n\t\tif (!active) return rejected(\"controller_not_active\");\n\t\tconst reserved = await this.readOwnerReservation(attemptId, c);\n\t\treturn rejected(reserved ? \"attempt_conflict\" : \"attempt_limited\");\n\t}\n\tprivate readOwnerReservation(attemptId: string, c: CoordinatorAuthLinkConfig) {\n\t\treturn this.first({\n\t\t\tsql: `SELECT 1 FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = ? AND attempt_id = ?\n UNION ALL SELECT 1 FROM coordinator_auth_browser_transactions WHERE coordinator_id = ? AND attempt_id = ?\n AND purpose NOT IN ('signin','link') LIMIT 1`,\n\t\t\tvalues: [c.coordinatorId, attemptId, c.coordinatorId, attemptId],\n\t\t});\n\t}\n\tprivate async createRetry(\n\t\trow: Attempt | null,\n\t\ti: CreateInput,\n\t\ts: CoordinatorAuthLinkSigner,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t\tauthority: (string | number | null)[] | null,\n\t): Promise<CoordinatorAuthLinkCreateResult> {\n\t\tif (\n\t\t\t!row ||\n\t\t\t!creationMatches(row, i, s, c) ||\n\t\t\trow.state === \"expired\" ||\n\t\t\trow.expires_at_ms <= now\n\t\t)\n\t\t\treturn rejected(\"attempt_conflict\");\n\t\tif (!authority) return rejected(\"controller_not_active\");\n\t\tconst active = await this.first({\n\t\t\tsql: `SELECT 1 FROM coordinator_auth_link_attempts WHERE attempt_id = ? AND ${LIVE_CONFIG} AND ${AUTHORITY}`,\n\t\t\tvalues: [row.attempt_id, ...configValues(c), ...authority],\n\t\t});\n\t\tif (!active) return rejected(\"controller_not_active\");\n\t\tif (await this.readOwnerReservation(row.attempt_id, c)) return rejected(\"attempt_conflict\");\n\t\treturn { kind: \"existing\", status: status(row, now), identityId: row.identity_id };\n\t}\n\tprivate async transition(\n\t\ti: { attemptId: string; browserTransactionHash: string },\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t\tupdate: AuthLinkStatement,\n\t\tafter?: AuthLinkStatement | null,\n\t): Promise<CoordinatorAuthLinkResult> {\n\t\tconst result = after\n\t\t\t? await this.executeTransitionBatch(update, after)\n\t\t\t: await this.execute(update, \"attempt_conflict\");\n\t\tif (typeof result !== \"number\") return result;\n\t\tconst row = await this.read(i.attemptId, c, { authority: \"either\" });\n\t\tif (!result) {\n\t\t\tif (\n\t\t\t\trow &&\n\t\t\t\trow.browser_transaction_hash !== null &&\n\t\t\t\trow.browser_transaction_hash !== i.browserTransactionHash\n\t\t\t)\n\t\t\t\treturn rejected(\"attempt_unavailable\");\n\t\t\treturn diagnose(row, c, now);\n\t\t}\n\t\tif (!row || row.browser_transaction_hash !== i.browserTransactionHash)\n\t\t\tthrow new Error(\"auth_link_persistence_incomplete\");\n\t\treturn { kind: \"applied\", status: status(row, now) };\n\t}\n\tprivate async executeTransitionBatch(update: AuthLinkStatement, after: AuthLinkStatement) {\n\t\ttry {\n\t\t\tconst counts = await this.backend.batch([update, after]);\n\t\t\tif (\n\t\t\t\t!Array.isArray(counts) ||\n\t\t\t\tcounts.length !== 2 ||\n\t\t\t\ttypeof counts[0] !== \"number\" ||\n\t\t\t\t!Number.isSafeInteger(counts[0])\n\t\t\t)\n\t\t\t\tthrow new Error(\"auth_link_batch_result_missing\");\n\t\t\treturn counts[0];\n\t\t} catch (error) {\n\t\t\tif (isAuthControllerUniqueError(error)) return rejected(\"attempt_conflict\");\n\t\t\tthrow authPersistenceError(error, \"auth_link_persistence_error\");\n\t\t}\n\t}\n\tprivate browserInput(\n\t\tinput: unknown,\n\t\textra: string[] = [],\n\t): (CoordinatorAuthLinkClaimInput & Captured) | null {\n\t\tconst i = capture(input, [\"attemptId\", \"browserTransactionHash\", ...extra]);\n\t\tif (!i || !isAuthControllerId(i.attemptId) || !isHash(i.browserTransactionHash)) return null;\n\t\treturn i as CoordinatorAuthLinkClaimInput & Captured;\n\t}\n\tasync claimAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkClaimInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkResult> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = this.browserInput(input);\n\t\tif (!c || !i) return rejected(\"invalid_input\");\n\t\tif (!c.enabled) return rejected(\"auth_config_changed\");\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst update = {\n\t\t\tsql: `UPDATE coordinator_auth_link_attempts SET state = 'browser_claimed', browser_transaction_hash = ?, claimed_at_ms = ? WHERE attempt_id = ? AND ${LIVE_CONFIG} AND expires_at_ms > ? AND state = 'pending' AND browser_start_hash IS NULL AND browser_transaction_hash IS NULL AND ${DESKTOP_MODE_SQL} AND NOT EXISTS (SELECT 1 FROM coordinator_auth_session_receipts r WHERE r.coordinator_id = coordinator_auth_link_attempts.coordinator_id AND r.browser_transaction_hash = ?)`,\n\t\t\tvalues: [\n\t\t\t\ti.browserTransactionHash,\n\t\t\t\tnow,\n\t\t\t\ti.attemptId,\n\t\t\t\t...configValues(c),\n\t\t\t\tnow,\n\t\t\t\ti.browserTransactionHash,\n\t\t\t],\n\t\t};\n\t\tconst result = await this.transition(i, c, now, update);\n\t\tif (result.kind !== \"rejected\" || result.error !== \"attempt_unavailable\") return result;\n\t\tconst row = await this.read(i.attemptId, c);\n\t\tif (\n\t\t\trow &&\n\t\t\tconfigMatches(row, c) &&\n\t\t\trow.expires_at_ms > now &&\n\t\t\trow.state === \"browser_claimed\" &&\n\t\t\trow.browser_start_hash == null &&\n\t\t\trow.browser_transaction_hash === i.browserTransactionHash\n\t\t)\n\t\t\treturn { kind: \"existing\", status: status(row, now) };\n\t\treturn result;\n\t}\n\t/** Caller supplies independently server-verified OIDC claims; this does not validate JWTs. */\n\tasync recordAuthLinkOidcVerified(\n\t\tinput: CoordinatorAuthLinkOidcInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkOidcResult> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = this.browserInput(input, [\"account\"]);\n\t\tif (!c || !i) return rejected(\"invalid_input\");\n\t\tconst accountValue = capture(i.account, [\"issuer\", \"subject\"]);\n\t\tconst account = parseCoordinatorAccountReference(accountValue, { issuer: c.issuer });\n\t\tif (!account.ok) return rejected(\"invalid_input\");\n\t\tif (!c.enabled) return rejected(\"auth_config_changed\");\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(input, \"profile\");\n\t\tconst profile = captureAuthAccountProfile(\n\t\t\tdescriptor && Object.hasOwn(descriptor, \"value\") ? descriptor.value : undefined,\n\t\t);\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst source = await this.source(i.attemptId, c, now);\n\t\tconst staged = stageAuthLinkProfile(\n\t\t\t{\n\t\t\t\tattemptId: i.attemptId,\n\t\t\t\tbrowserTransactionHash: i.browserTransactionHash,\n\t\t\t\taccount: account.account,\n\t\t\t\tprofile,\n\t\t\t},\n\t\t\tc,\n\t\t\tnow,\n\t\t);\n\t\tconst result = await this.transition(\n\t\t\ti,\n\t\t\tc,\n\t\t\tnow,\n\t\t\t{\n\t\t\t\tsql: `UPDATE coordinator_auth_link_attempts SET state = 'oidc_verified', account_subject = ?, oidc_verified_at_ms = ? WHERE attempt_id = ? AND ${CURRENT_CONFIG} AND expires_at_ms > ? AND state = 'browser_claimed' AND browser_transaction_hash = ? AND account_subject IS NULL AND ${source.sql}`,\n\t\t\t\tvalues: [\n\t\t\t\t\taccount.account.subject,\n\t\t\t\t\tnow,\n\t\t\t\t\ti.attemptId,\n\t\t\t\t\t...configValues(c),\n\t\t\t\t\tnow,\n\t\t\t\t\ti.browserTransactionHash,\n\t\t\t\t\t...source.values,\n\t\t\t\t],\n\t\t\t},\n\t\t\tstaged,\n\t\t);\n\t\tif (result.kind === \"rejected\") return result;\n\t\tconst row = await this.read(i.attemptId, c, { authority: \"either\" });\n\t\tif (!row) throw new Error(\"auth_link_persistence_incomplete\");\n\t\treturn {\n\t\t\tkind: \"applied\",\n\t\t\tstatus: result.status,\n\t\t\ttarget: {\n\t\t\t\tidentityId: row.identity_id,\n\t\t\t\tgroupId: row.group_id,\n\t\t\t\tdeviceId: row.device_id,\n\t\t\t\tfingerprint: row.fingerprint,\n\t\t\t\t...(row.loopback_redirect === AUTH_LINK_HEADLESS_MARKER ? { headless: true as const } : {}),\n\t\t\t},\n\t\t};\n\t}\n\t/** completionSecretHash must come from the trusted coordinator generator, not request nomination. */\n\tasync confirmAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkConfirmInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkResult> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = this.browserInput(input, [\"completionSecretHash\"]);\n\t\tif (!c || !i || !isHash(i.completionSecretHash)) return rejected(\"invalid_input\");\n\t\treturn this.confirmWith(i, c, {\n\t\t\tsql: \"?\",\n\t\t\tvalues: [i.completionSecretHash],\n\t\t\tmode: DESKTOP_MODE_SQL,\n\t\t});\n\t}\n\t/** The device already holds the runtime verifier, so it doubles as the completion proof. */\n\tasync confirmHeadlessAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkClaimInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkResult> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = this.browserInput(input);\n\t\tif (!c || !i) return rejected(\"invalid_input\");\n\t\treturn this.confirmWith(i, c, {\n\t\t\tsql: \"runtime_verifier_hash\",\n\t\t\tvalues: [],\n\t\t\tmode: HEADLESS_MODE_SQL,\n\t\t});\n\t}\n\tprivate async confirmWith(\n\t\ti: CoordinatorAuthLinkClaimInput,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tcompletion: { sql: string; values: string[]; mode: string },\n\t): Promise<CoordinatorAuthLinkResult> {\n\t\tif (!c.enabled) return rejected(\"auth_config_changed\");\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst source = await this.source(i.attemptId, c, now);\n\t\treturn this.transition(i, c, now, {\n\t\t\tsql: `UPDATE coordinator_auth_link_attempts SET state = 'confirmed', completion_secret_hash = ${completion.sql}, confirmed_at_ms = ? WHERE attempt_id = ? AND ${CURRENT_CONFIG} AND expires_at_ms > ? AND state = 'oidc_verified' AND browser_transaction_hash = ? AND completion_secret_hash IS NULL AND ${completion.mode} AND ${source.sql}`,\n\t\t\tvalues: [\n\t\t\t\t...completion.values,\n\t\t\t\tnow,\n\t\t\t\ti.attemptId,\n\t\t\t\t...configValues(c),\n\t\t\t\tnow,\n\t\t\t\ti.browserTransactionHash,\n\t\t\t\t...source.values,\n\t\t\t],\n\t\t});\n\t}\n\t/** Read-only snapshot; confirmation must still atomically check the browser proof and state. */\n\tasync readAuthLinkCompletionDestination(\n\t\tinput: CoordinatorAuthLinkClaimInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<{ destination: string } | null> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = this.browserInput(input);\n\t\tif (!c || !i || !c.enabled) return null;\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst source = await this.source(i.attemptId, c, now);\n\t\tconst row = await this.first<Attempt>({\n\t\t\tsql: `SELECT * FROM coordinator_auth_link_attempts WHERE attempt_id = ? AND ${CURRENT_CONFIG}\n AND browser_transaction_hash = ? AND ${source.sql}`,\n\t\t\tvalues: [i.attemptId, ...configValues(c), i.browserTransactionHash, ...source.values],\n\t\t});\n\t\tif (\n\t\t\t!row ||\n\t\t\t!configMatches(row, c) ||\n\t\t\trow.attempt_id !== i.attemptId ||\n\t\t\trow.browser_transaction_hash !== i.browserTransactionHash ||\n\t\t\trow.state !== \"oidc_verified\" ||\n\t\t\t!(row.created_at_ms <= now && now < row.expires_at_ms) ||\n\t\t\t!parseCoordinatorAuthLoopback(row.loopback_redirect).ok\n\t\t)\n\t\t\treturn null;\n\t\treturn { destination: row.loopback_redirect };\n\t}\n\tasync getAuthLinkAttemptStatus(\n\t\tattemptId: string,\n\t\trequester: CoordinatorAuthLinkRequester,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkStatus | null> {\n\t\tconst read = await this.readStatusRow(attemptId, requester, config);\n\t\treturn read && status(read.row, read.now);\n\t}\n\t/**\n\t * The browser-bound status plus the attempt's mode, from the same single row\n\t * read, so browser pages learn the mode without another statement.\n\t */\n\tasync getAuthLinkBrowserAttemptStatus(\n\t\tinput: CoordinatorAuthLinkClaimInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<{ status: CoordinatorAuthLinkStatus; headless: boolean } | null> {\n\t\tconst i = this.browserInput(input);\n\t\tif (!i) return null;\n\t\tconst requester = {\n\t\t\tkind: \"browser\" as const,\n\t\t\tbrowserTransactionHash: i.browserTransactionHash,\n\t\t};\n\t\tconst read = await this.readStatusRow(i.attemptId, requester, config);\n\t\tif (!read) return null;\n\t\tconst headless = read.row.loopback_redirect === AUTH_LINK_HEADLESS_MARKER;\n\t\treturn { status: status(read.row, read.now), headless };\n\t}\n\tprivate async readStatusRow(\n\t\tattemptId: string,\n\t\trequester: CoordinatorAuthLinkRequester,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<{ row: Attempt; now: number } | null> {\n\t\tconst c = captureConfig(config);\n\t\tconst r = captureRequester(requester);\n\t\tif (!c || !r || !isAuthControllerId(attemptId) || !c.enabled) return null;\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst source = await this.source(attemptId, c, now, { currentDevice: r.kind === \"device\" });\n\t\tconst proof = requesterGuard(r);\n\t\tconst row = await this.first<Attempt>({\n\t\t\tsql: `SELECT * FROM coordinator_auth_link_attempts WHERE attempt_id = ? AND ${CURRENT_CONFIG}\n AND ${proof.sql} AND ${source.sql}`,\n\t\t\tvalues: [attemptId, ...configValues(c), ...proof.values, ...source.values],\n\t\t});\n\t\tif (!row || !configMatches(row, c) || !requesterMatches(row, r)) return null;\n\t\treturn { row, now };\n\t}\n\t/** The enrolled name of a headless attempt's device; read only to render headless consent. */\n\tasync readHeadlessAuthLinkDeviceName(\n\t\tinput: CoordinatorAuthLinkClaimInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<string | null> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = this.browserInput(input);\n\t\tif (!c?.enabled || !i) return null;\n\t\tconst row = await this.first<{ display_name: string | null }>({\n\t\t\tsql: `SELECT d.display_name FROM coordinator_auth_link_attempts a\n JOIN enrolled_devices d ON d.group_id = a.group_id AND d.device_id = a.device_id\n WHERE a.coordinator_id = ? AND a.attempt_id = ? AND a.browser_transaction_hash = ? AND a.${HEADLESS_MODE_SQL}`,\n\t\t\tvalues: [c.coordinatorId, i.attemptId, i.browserTransactionHash],\n\t\t});\n\t\treturn typeof row?.display_name === \"string\" ? row.display_name : null;\n\t}\n\t/** The confirmed account for the signing device to approve; null for any other state or mode. */\n\tasync readHeadlessAuthLinkApproval(\n\t\tinput: CoordinatorAuthLinkHeadlessApprovalInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkHeadlessApproval | null> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = capture(input, [\"attemptId\", \"signer\"]);\n\t\tconst s = captureSigner(i?.signer);\n\t\tif (!c?.enabled || !i || !s || !isAuthControllerId(i.attemptId)) return null;\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst source = await this.source(i.attemptId, c, now, { currentDevice: true });\n\t\tconst proof = requesterGuard({ kind: \"device\", signer: s });\n\t\tconst row = await this.first<Attempt>({\n\t\t\tsql: `SELECT * FROM coordinator_auth_link_attempts WHERE attempt_id = ? AND ${CURRENT_CONFIG}\n AND state = 'confirmed' AND expires_at_ms > ? AND ${HEADLESS_MODE_SQL} AND ${proof.sql} AND ${source.sql}`,\n\t\t\tvalues: [i.attemptId, ...configValues(c), now, ...proof.values, ...source.values],\n\t\t});\n\t\tif (\n\t\t\t!row ||\n\t\t\t!configMatches(row, c) ||\n\t\t\t!signerMatches(row, s) ||\n\t\t\trow.state !== \"confirmed\" ||\n\t\t\trow.loopback_redirect !== AUTH_LINK_HEADLESS_MARKER ||\n\t\t\trow.account_subject === null\n\t\t)\n\t\t\treturn null;\n\t\treturn { issuer: row.issuer, subject: row.account_subject, ...(await this.stagedProfile(row)) };\n\t}\n\tprivate async stagedProfile(row: Attempt) {\n\t\tconst profile = await this.first<StagedProfile>({\n\t\t\tsql: `SELECT display_name, email, email_verified FROM coordinator_auth_link_profiles\n WHERE coordinator_id = ? AND attempt_id = ? AND issuer = ? AND subject = ? AND auth_config_revision = ?\n AND browser_transaction_hash = ? AND link_id IS NULL`,\n\t\t\tvalues: [\n\t\t\t\trow.coordinator_id,\n\t\t\t\trow.attempt_id,\n\t\t\t\trow.issuer,\n\t\t\t\trow.account_subject,\n\t\t\t\trow.auth_config_revision,\n\t\t\t\trow.browser_transaction_hash,\n\t\t\t],\n\t\t});\n\t\tlet emailVerified: boolean | null = null;\n\t\tif (profile?.email_verified === 1) emailVerified = true;\n\t\telse if (profile?.email_verified === 0) emailVerified = false;\n\t\treturn {\n\t\t\tdisplayName: profile?.display_name ?? null,\n\t\t\temail: profile?.email ?? null,\n\t\t\temailVerified,\n\t\t};\n\t}\n\tprivate async acknowledgeFailedAttempt(\n\t\trow: Attempt,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t\tkind: \"applied\" | \"existing\",\n\t): Promise<CoordinatorAuthLinkResult> {\n\t\tconst cleanup = await this.execute(\n\t\t\t{\n\t\t\t\tsql: \"DELETE FROM coordinator_auth_link_profiles WHERE coordinator_id = ? AND attempt_id = ? AND link_id IS NULL\",\n\t\t\t\tvalues: [c.coordinatorId, row.attempt_id],\n\t\t\t},\n\t\t\t\"attempt_conflict\",\n\t\t);\n\t\tif (typeof cleanup !== \"number\") return cleanup;\n\t\treturn { kind, status: status(row, now) };\n\t}\n\tasync failAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkFailInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkResult> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = capture(input, [\"attemptId\", \"requester\", \"reason\"]);\n\t\tconst r = captureRequester(i?.requester);\n\t\tif (\n\t\t\t!c ||\n\t\t\t!i ||\n\t\t\t!r ||\n\t\t\t!isAuthControllerId(i.attemptId) ||\n\t\t\t![\"cancelled\", \"provider_failure\", \"config_failure\"].includes(i.reason as string) ||\n\t\t\t(r.kind === \"device\" && i.reason !== \"cancelled\")\n\t\t)\n\t\t\treturn rejected(\"invalid_input\");\n\t\tif (!c.enabled) return rejected(\"auth_config_changed\");\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst reason = i.reason === \"cancelled\" ? `${r.kind}_cancelled` : (i.reason as string);\n\t\tconst proof = requesterGuard(r);\n\t\tconst result = await this.execute(\n\t\t\t{\n\t\t\t\tsql: `UPDATE coordinator_auth_link_attempts SET state = 'failed', failure_reason = ?, failed_at_ms = ?, account_subject = CASE WHEN authority_kind = 'device_claim' THEN NULL ELSE account_subject END WHERE attempt_id = ? AND ${CURRENT_CONFIG} AND ${RELEASABLE_SOURCE} AND link_id IS NULL AND expires_at_ms > ? AND state IN ('pending','browser_claimed','oidc_verified','confirmed') AND ${proof.sql}`,\n\t\t\t\tvalues: [reason, now, i.attemptId, ...configValues(c), now, ...proof.values],\n\t\t\t},\n\t\t\t\"attempt_conflict\",\n\t\t);\n\t\tif (typeof result !== \"number\") return result;\n\t\tconst row = await this.read(i.attemptId, c, { authority: \"either\" });\n\t\tif (row && !requesterMatches(row, r)) return rejected(\"attempt_unavailable\");\n\t\t// A signed own-attempt cancel can acknowledge browser cancellation without\n\t\t// rewriting its reason or creating any account authority.\n\t\tif (\n\t\t\trow &&\n\t\t\tconfigMatches(row, c) &&\n\t\t\tr.kind === \"device\" &&\n\t\t\ti.reason === \"cancelled\" &&\n\t\t\trow.state === \"failed\" &&\n\t\t\trow.failure_reason === \"browser_cancelled\" &&\n\t\t\trow.link_id === null &&\n\t\t\trow.created_at_ms <= now &&\n\t\t\tnow < row.expires_at_ms\n\t\t)\n\t\t\treturn this.acknowledgeFailedAttempt(row, c, now, \"existing\");\n\t\tif (\n\t\t\trow &&\n\t\t\tconfigMatches(row, c) &&\n\t\t\trequesterMatches(row, r) &&\n\t\t\trow.state === \"failed\" &&\n\t\t\trow.failure_reason === reason\n\t\t)\n\t\t\treturn this.acknowledgeFailedAttempt(row, c, now, result ? \"applied\" : \"existing\");\n\t\treturn diagnose(row, c, now);\n\t}\n\tasync finalizeAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkFinalizeInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkResult> {\n\t\treturn this.finalizeWithMode(input, config, { kind: \"desktop\" });\n\t}\n\t/** Links only the account the device approved; any other verified account writes nothing. */\n\tasync finalizeHeadlessAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkHeadlessFinalizeInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkResult> {\n\t\tconst c = captureConfig(config);\n\t\tconst approved = capture(capture(input, [\"approvedAccount\"])?.approvedAccount, [\n\t\t\t\"issuer\",\n\t\t\t\"subject\",\n\t\t]);\n\t\tconst account = c && parseCoordinatorAccountReference(approved, { issuer: c.issuer });\n\t\tif (!account?.ok) return rejected(\"invalid_input\");\n\t\t// Fail closed: a headless link is never written without its provenance row.\n\t\tif (!(await hasHeadlessLinkProvenance(this.backend))) return rejected(\"attempt_unavailable\");\n\t\treturn this.finalizeWithMode(input, config, { kind: \"headless\", ...account.account });\n\t}\n\tprivate async finalizeWithMode(\n\t\tinput: CoordinatorAuthLinkFinalizeInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t\tmode: FinalizeMode,\n\t): Promise<CoordinatorAuthLinkResult> {\n\t\tconst c = captureConfig(config);\n\t\tconst captured = captureFinalize(input, c);\n\t\tconst i: FinalizeRequest | null = captured && { ...captured, mode };\n\t\tif (!c || !i) return rejected(\"invalid_input\");\n\t\tif (!c.enabled) return rejected(\"auth_config_changed\");\n\t\tif (\n\t\t\ti.groupId !== i.signer.groupId ||\n\t\t\ti.deviceId !== i.signer.deviceId ||\n\t\t\ti.fingerprint !== i.signer.fingerprint\n\t\t)\n\t\t\treturn rejected(\"attempt_unavailable\");\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst linkId = globalThis.crypto.randomUUID();\n\t\tconst connections = await this.connectionSchema();\n\t\tconst row = await this.read(i.attemptId, c, { authority: \"either\" });\n\t\tif (row && !finalizeModeMatches(row, mode)) return rejected(\"attempt_unavailable\");\n\t\tif (row?.authority_kind === \"device_claim\") return this.finalizeDevice(i, c, now, linkId, row);\n\t\tconst authority = await this.readAuthority(i.attemptId, c);\n\t\tconst requester = andStatement(\n\t\t\tconnections\n\t\t\t\t? await connectionRequesterGuard(this.backend, i.identityId, i.signer, c, now)\n\t\t\t\t: { sql: \"1 = 1\", values: [] },\n\t\t\tfinalizeModeGuard(mode),\n\t\t);\n\t\ttry {\n\t\t\tawait this.backend.batch([\n\t\t\t\t...finalizeStatements(i, c, now, linkId, authority, connections, requester),\n\t\t\t\t...(connections ? connectionSuccessorStatements(c.coordinatorId, i.attemptId, linkId) : []),\n\t\t\t\tpromoteAuthLinkProfile(c.coordinatorId, i.attemptId, linkId),\n\t\t\t\t...(await initialConnectionFloor(this.backend, c.coordinatorId, linkId)),\n\t\t\t\t...provenanceStatements(i, c, linkId),\n\t\t\t]);\n\t\t} catch (error) {\n\t\t\tif (isAuthControllerUniqueError(error)) return rejected(\"link_conflict\");\n\t\t\tthrow authPersistenceError(error, \"auth_link_persistence_error\");\n\t\t}\n\t\treturn this.finalizeReceipt(i, c, now, linkId);\n\t}\n\tprivate async finalizeDevice(\n\t\ti: FinalizeRequest,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t\tlinkId: string,\n\t\trow: Attempt,\n\t): Promise<CoordinatorAuthLinkResult> {\n\t\tif (!configMatches(row, c) || !finalizeMatches(row, i)) return diagnose(row, c, now);\n\t\tconst source = await this.finalizeSource(i, c, now);\n\t\t// Exact retries read retained evidence. The immutable proof must never be reinserted.\n\t\tif ([\"finalized\", \"session_redeemed\"].includes(row.state))\n\t\t\treturn this.deviceReceipt(i, c, now, linkId, source);\n\t\tconst keyId = await ed25519KeyIdForRevocation(i.signer.publicKey);\n\t\tif (!keyId) return rejected(\"attempt_unavailable\");\n\t\tconst connections = await this.connectionSchema();\n\t\tconst binding = await this.prepareFirstClaimBinding(i, c, now, linkId, row, connections);\n\t\tif (!binding) return rejected(\"attempt_unavailable\");\n\t\tconst consistency = await readNegativeOwnerConsistency(this.backend, {\n\t\t\tcoordinatorId: c.coordinatorId,\n\t\t\townerIdentityId: i.identityId,\n\t\t\tdeviceId: i.signer.deviceId,\n\t\t\tpublicKey: i.signer.publicKey,\n\t\t\tfingerprint: i.signer.fingerprint,\n\t\t\tenrollment: { groupId: i.signer.groupId },\n\t\t});\n\t\tif (!consistency) return rejected(\"attempt_unavailable\");\n\t\ttry {\n\t\t\t// The retained-ownership guards replace the pin the attempt update and claim insert\n\t\t\t// carried. A changed fact writes nothing, as that pin made the whole batch a no-op,\n\t\t\t// and the receipt below then refuses.\n\t\t\tawait writeGuarded(this.backend, consistency.guards, [\n\t\t\t\t...deviceFinalizeStatements(i, c, now, linkId, keyId, source, connections),\n\t\t\t\t...(connections ? connectionSuccessorStatements(c.coordinatorId, i.attemptId, linkId) : []),\n\t\t\t\tpromoteAuthLinkProfile(c.coordinatorId, i.attemptId, linkId),\n\t\t\t\t...(await initialConnectionFloor(this.backend, c.coordinatorId, linkId)),\n\t\t\t\t...provenanceStatements(i, c, linkId),\n\t\t\t\t...binding,\n\t\t\t]);\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\tisAuthControllerUniqueError(error) ||\n\t\t\t\tString(error).includes(\"auth_device_claim_collision\")\n\t\t\t)\n\t\t\t\treturn rejected(\"link_conflict\");\n\t\t\tif (isDeviceClaimBindingConflict(error)) return rejected(\"attempt_unavailable\");\n\t\t\tthrow authPersistenceError(error, \"auth_link_persistence_error\");\n\t\t}\n\t\treturn this.deviceReceipt(i, c, now, linkId, await this.finalizeSource(i, c, now), {\n\t\t\trequireCompleteBinding: true,\n\t\t});\n\t}\n\tprivate async prepareFirstClaimBinding(\n\t\ti: FinalizeRequest,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t\tlinkId: string,\n\t\trow: Attempt,\n\t\tconnections: boolean,\n\t): Promise<AuthLinkStatement[] | null> {\n\t\tif (row.prior_link_id) return [];\n\t\tconst plan = await prepareFirstLinkDeviceClaimBinding(\n\t\t\tthis.backend,\n\t\t\t{ signer: i.signer, currentIdentityId: i.identityId },\n\t\t\tc,\n\t\t\tnow,\n\t\t);\n\t\tif (!plan) return null;\n\t\treturn deviceClaimBindingStatements(\n\t\t\tplan,\n\t\t\tglobalThis.crypto.randomUUID(),\n\t\t\tglobalThis.crypto.randomUUID(),\n\t\t\t{\n\t\t\t\twinning: {\n\t\t\t\t\tsql: `EXISTS (SELECT 1 FROM coordinator_auth_link_attempts WHERE attempt_id = ? AND ${CURRENT_CONFIG}\n AND authority_kind = 'device_claim' AND state = 'finalized' AND link_id = ? AND finalized_at_ms = ?${connections ? \" AND prior_link_id IS NULL\" : \"\"})`,\n\t\t\t\t\tvalues: [i.attemptId, ...configValues(c), linkId, now],\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t}\n\tprivate async finalizeSource(\n\t\ti: FinalizeRequest,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t): Promise<AuthLinkStatement> {\n\t\tconst source = await this.source(i.attemptId, c, now, { currentDevice: true });\n\t\treturn andStatement(source, finalizeModeGuard(i.mode));\n\t}\n\tprivate async deviceReceipt(\n\t\ti: CoordinatorAuthLinkFinalizeInput,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t\tlinkId: string,\n\t\tsource: AuthLinkStatement,\n\t\toptions: { requireCompleteBinding?: boolean } = {},\n\t): Promise<CoordinatorAuthLinkResult> {\n\t\tconst row = await this.first<Attempt>({\n\t\t\tsql: `SELECT * FROM coordinator_auth_link_attempts WHERE attempt_id = ? AND ${CURRENT_CONFIG}\n AND authority_kind = 'device_claim' AND state IN ('finalized','session_redeemed') AND ${source.sql}`,\n\t\t\tvalues: [i.attemptId, ...configValues(c), ...source.values],\n\t\t});\n\t\tif (!row || !finalizeMatches(row, i)) return rejected(\"attempt_unavailable\");\n\t\tif (\n\t\t\toptions.requireCompleteBinding &&\n\t\t\t!row.prior_link_id &&\n\t\t\t!(await readFirstLinkDeviceClaimOwnershipComplete(\n\t\t\t\tthis.backend,\n\t\t\t\t{ signer: i.signer, currentIdentityId: i.identityId },\n\t\t\t\tc,\n\t\t\t\tnow,\n\t\t\t))\n\t\t)\n\t\t\treturn rejected(\"attempt_unavailable\");\n\t\treturn { kind: row.link_id === linkId ? \"applied\" : \"existing\", status: status(row, now) };\n\t}\n\tprivate async finalizeReceipt(\n\t\ti: CoordinatorAuthLinkFinalizeInput,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t\tlinkId: string,\n\t): Promise<CoordinatorAuthLinkResult> {\n\t\tconst row = await this.read(i.attemptId, c);\n\t\tif (\n\t\t\trow &&\n\t\t\tconfigMatches(row, c) &&\n\t\t\tfinalizeMatches(row, i) &&\n\t\t\t[\"finalized\", \"session_redeemed\"].includes(row.state)\n\t\t) {\n\t\t\tconst receipt = await this.first({\n\t\t\t\tsql: receiptSql(await this.connectionSchema()),\n\t\t\t\tvalues: [c.coordinatorId, i.attemptId, row.link_id],\n\t\t\t});\n\t\t\tif (!receipt) throw new Error(\"auth_link_persistence_incomplete\");\n\t\t\treturn { kind: row.link_id === linkId ? \"applied\" : \"existing\", status: status(row, now) };\n\t\t}\n\t\tif (row && !finalizeMatches(row, i)) return rejected(\"attempt_unavailable\");\n\t\tconst diagnosis = diagnose(row, c, now);\n\t\tif (\n\t\t\t!row ||\n\t\t\tdiagnosis.error !== \"attempt_unavailable\" ||\n\t\t\trow.state !== \"confirmed\" ||\n\t\t\t!finalizeMatches(row, i)\n\t\t)\n\t\t\treturn diagnosis;\n\t\t// V2 refuses a link for an Identity or account that any link row already holds,\n\t\t// active or revoked, through its unique indexes. Account management refuses the\n\t\t// same finalization through its connection guards, which write nothing, so report\n\t\t// the same conflict rather than a controller failure.\n\t\tif (await this.first({ sql: LINK_HOLDER_SQL, values: linkHolderValues(row) }))\n\t\t\treturn rejected(\"link_conflict\");\n\t\treturn rejected(\"controller_not_active\");\n\t}\n}\nfunction deviceFinalizeStatements(\n\ti: CoordinatorAuthLinkFinalizeInput,\n\tc: CoordinatorAuthLinkConfig,\n\tnow: number,\n\tlinkId: string,\n\tkeyId: string,\n\tsource: AuthLinkStatement,\n\tconnections = false,\n): AuthLinkStatement[] {\n\t// Every insert selects only this batch's winning transition, never an older receipt.\n\tconst winning = `attempt_id = ? AND ${CURRENT_CONFIG} AND authority_kind = 'device_claim'\n AND state = 'finalized' AND link_id = ? AND finalized_at_ms = ?`;\n\tconst values = [i.attemptId, ...configValues(c), linkId, now];\n\treturn [\n\t\t{\n\t\t\tsql: `UPDATE coordinator_auth_link_attempts SET state = 'finalized', link_id = ?, finalized_at_ms = ?\n WHERE (attempt_id = ? AND ${CURRENT_CONFIG} AND authority_kind = 'device_claim' AND state = 'confirmed')\n AND (created_at_ms <= ? AND expires_at_ms > ?) AND (group_id = ? AND identity_id = ? AND device_id = ? AND fingerprint = ? AND public_key = ?)\n AND (runtime_verifier_hash = ? AND completion_secret_hash = ? AND account_subject IS NOT NULL AND browser_transaction_hash IS NOT NULL)\n AND (created_at_ms <= claimed_at_ms AND claimed_at_ms <= oidc_verified_at_ms AND oidc_verified_at_ms <= confirmed_at_ms AND confirmed_at_ms <= ?)\n AND (${source.sql})${connections ? ` AND (${connectionFinalizeGuard(\"coordinator_auth_link_attempts\")})` : \"\"}`,\n\t\t\tvalues: [\n\t\t\t\tlinkId,\n\t\t\t\tnow,\n\t\t\t\ti.attemptId,\n\t\t\t\t...configValues(c),\n\t\t\t\tnow,\n\t\t\t\tnow,\n\t\t\t\ti.groupId,\n\t\t\t\ti.identityId,\n\t\t\t\ti.deviceId,\n\t\t\t\ti.fingerprint,\n\t\t\t\ti.signer.publicKey,\n\t\t\t\ti.runtimeVerifierHash,\n\t\t\t\ti.completionSecretHash,\n\t\t\t\tnow,\n\t\t\t\t...source.values,\n\t\t\t],\n\t\t},\n\t\t{\n\t\t\tsql: `INSERT INTO coordinator_auth_device_claims\n (claim_id,coordinator_id,identity_id,group_id,device_id,public_key,fingerprint,key_id,attempt_id,issuer,auth_config_revision,created_at_ms)\n SELECT link_id,coordinator_id,identity_id,group_id,device_id,public_key,fingerprint,?,attempt_id,issuer,auth_config_revision,finalized_at_ms\n FROM coordinator_auth_link_attempts WHERE ${winning}${connections ? \" AND prior_link_id IS NULL\" : \"\"}`,\n\t\t\tvalues: [keyId, ...values],\n\t\t},\n\t\t{\n\t\t\tsql: `INSERT INTO coordinator_auth_account_links\n (coordinator_id,link_id,issuer,subject,identity_id,attempt_id,controller_attestation_id,device_claim_id,auth_config_revision,created_at_ms,authority_kind)\n SELECT coordinator_id,link_id,issuer,account_subject,identity_id,attempt_id,NULL,${connections ? \"(SELECT claim_id FROM coordinator_auth_device_claims d WHERE d.coordinator_id=coordinator_auth_link_attempts.coordinator_id AND d.identity_id=coordinator_auth_link_attempts.identity_id)\" : \"link_id\"},auth_config_revision,finalized_at_ms,'device_claim'\n FROM coordinator_auth_link_attempts WHERE ${winning}`,\n\t\t\tvalues,\n\t\t},\n\t\t{\n\t\t\tsql: `INSERT INTO coordinator_auth_link_audit_log\n (coordinator_id,link_id,action,attempt_id,identity_id,group_id,device_id,fingerprint,controller_attestation_id,device_claim_id,auth_config_revision,created_at_ms,authority_kind)\n SELECT coordinator_id,link_id,'link_created',attempt_id,identity_id,group_id,device_id,fingerprint,NULL,${connections ? \"(SELECT claim_id FROM coordinator_auth_device_claims d WHERE d.coordinator_id=coordinator_auth_link_attempts.coordinator_id AND d.identity_id=coordinator_auth_link_attempts.identity_id)\" : \"link_id\"},auth_config_revision,finalized_at_ms,'device_claim'\n FROM coordinator_auth_link_attempts WHERE ${winning}`,\n\t\t\tvalues,\n\t\t},\n\t];\n}\ntype FinalizeMode = { kind: \"desktop\" } | { kind: \"headless\"; issuer: string; subject: string };\ntype FinalizeRequest = CoordinatorAuthLinkFinalizeInput & { mode: FinalizeMode };\n/** Written in the winning finalize batch, so a headless link and its provenance commit together. */\nfunction provenanceStatements(\n\ti: FinalizeRequest,\n\tc: CoordinatorAuthLinkConfig,\n\tlinkId: string,\n): AuthLinkStatement[] {\n\tif (i.mode.kind !== \"headless\") return [];\n\treturn [headlessLinkProvenanceStatement(c.coordinatorId, i.attemptId, linkId)];\n}\nfunction finalizeModeGuard(mode: FinalizeMode): AuthLinkStatement {\n\tconst t = \"coordinator_auth_link_attempts\";\n\tif (mode.kind === \"desktop\") return { sql: `${t}.${DESKTOP_MODE_SQL}`, values: [] };\n\treturn {\n\t\tsql: `${t}.${HEADLESS_MODE_SQL} AND ${t}.issuer = ? AND ${t}.account_subject = ?`,\n\t\tvalues: [mode.issuer, mode.subject],\n\t};\n}\nfunction finalizeModeMatches(row: Attempt, mode: FinalizeMode): boolean {\n\tif (mode.kind === \"desktop\") return row.loopback_redirect !== AUTH_LINK_HEADLESS_MARKER;\n\treturn (\n\t\trow.loopback_redirect === AUTH_LINK_HEADLESS_MARKER &&\n\t\trow.issuer === mode.issuer &&\n\t\trow.account_subject === mode.subject\n\t);\n}\nfunction andStatement(a: AuthLinkStatement, b: AuthLinkStatement): AuthLinkStatement {\n\treturn { sql: `(${a.sql}) AND (${b.sql})`, values: [...a.values, ...b.values] };\n}\nfunction requesterGuard(r: CoordinatorAuthLinkRequester): AuthLinkStatement {\n\tif (r.kind === \"browser\")\n\t\treturn { sql: \"browser_transaction_hash = ?\", values: [r.browserTransactionHash] };\n\treturn {\n\t\tsql: \"group_id = ? AND device_id = ? AND public_key = ? AND fingerprint = ?\",\n\t\tvalues: [r.signer.groupId, r.signer.deviceId, r.signer.publicKey, r.signer.fingerprint],\n\t};\n}\nfunction captureFinalize(\n\tinput: unknown,\n\tc: CoordinatorAuthLinkConfig | null,\n): CoordinatorAuthLinkFinalizeInput | null {\n\tconst i = capture(input, [\n\t\t\"purpose\",\n\t\t\"coordinatorId\",\n\t\t\"attemptId\",\n\t\t\"groupId\",\n\t\t\"identityId\",\n\t\t\"deviceId\",\n\t\t\"fingerprint\",\n\t\t\"runtimeVerifierHash\",\n\t\t\"completionSecretHash\",\n\t\t\"signer\",\n\t]);\n\tconst s = captureSigner(i?.signer);\n\tif (!c || !i || !s || i.purpose !== AUTH_LINK_PURPOSE || i.coordinatorId !== c.coordinatorId)\n\t\treturn null;\n\tif (\n\t\t![i.attemptId, i.groupId, i.identityId, i.deviceId].every(isAuthControllerId) ||\n\t\t![i.fingerprint, i.runtimeVerifierHash, i.completionSecretHash].every(isHash)\n\t)\n\t\treturn null;\n\treturn { ...i, signer: s } as unknown as CoordinatorAuthLinkFinalizeInput;\n}\nfunction finalizeMatches(row: Attempt, i: CoordinatorAuthLinkFinalizeInput): boolean {\n\treturn (\n\t\tsignerMatches(row, i.signer) &&\n\t\trow.identity_id === i.identityId &&\n\t\trow.runtime_verifier_hash === i.runtimeVerifierHash &&\n\t\trow.completion_secret_hash === i.completionSecretHash\n\t);\n}\nfunction finalizeStatements(\n\ti: CoordinatorAuthLinkFinalizeInput,\n\tc: CoordinatorAuthLinkConfig,\n\tnow: number,\n\tlinkId: string,\n\tauthority: (string | number | null)[] | null,\n\tconnections = false,\n\trequester: AuthLinkStatement = { sql: \"1 = 1\", values: [] },\n): AuthLinkStatement[] {\n\tconst authorityGuard = authority ? AUTHORITY : \"0 = 1\";\n\tconst consume: AuthLinkStatement = {\n\t\tsql: `UPDATE coordinator_auth_link_attempts SET state = 'finalized', link_id = ?, finalized_at_ms = ? WHERE attempt_id = ? AND ${LIVE_CONFIG} AND state = 'confirmed' AND expires_at_ms > ? AND group_id = ? AND identity_id = ? AND device_id = ? AND fingerprint = ? AND public_key = ? AND runtime_verifier_hash = ? AND completion_secret_hash = ? AND ${authorityGuard}${connections ? ` AND ${connectionFinalizeGuard(\"coordinator_auth_link_attempts\")}` : \"\"} AND ${requester.sql}`,\n\t\tvalues: [\n\t\t\tlinkId,\n\t\t\tnow,\n\t\t\ti.attemptId,\n\t\t\t...configValues(c),\n\t\t\tnow,\n\t\t\ti.groupId,\n\t\t\ti.identityId,\n\t\t\ti.deviceId,\n\t\t\ti.fingerprint,\n\t\t\ti.signer.publicKey,\n\t\t\ti.runtimeVerifierHash,\n\t\t\ti.completionSecretHash,\n\t\t\t...(authority ?? []),\n\t\t\t...requester.values,\n\t\t],\n\t};\n\tconst link: AuthLinkStatement = {\n\t\tsql: `INSERT INTO coordinator_auth_account_links (coordinator_id, link_id, issuer, subject, identity_id, attempt_id, controller_attestation_id, auth_config_revision, created_at_ms, authority_kind) SELECT coordinator_id, link_id, issuer, account_subject, identity_id, attempt_id, controller_attestation_id, auth_config_revision, finalized_at_ms, 'controller_attestation' FROM coordinator_auth_link_attempts WHERE attempt_id = ? AND ${LIVE_CONFIG} AND link_id = ? AND state = 'finalized'`,\n\t\tvalues: [i.attemptId, ...configValues(c), linkId],\n\t};\n\tconst audit: AuthLinkStatement = {\n\t\tsql: `INSERT INTO coordinator_auth_link_audit_log (coordinator_id, link_id, action, attempt_id, identity_id, group_id, device_id, fingerprint, controller_attestation_id, auth_config_revision, created_at_ms, authority_kind) SELECT t.coordinator_id, t.link_id, 'link_created', t.attempt_id, t.identity_id, t.group_id, t.device_id, t.fingerprint, t.controller_attestation_id, t.auth_config_revision, t.finalized_at_ms, 'controller_attestation' FROM coordinator_auth_link_attempts t JOIN coordinator_auth_account_links l ON l.coordinator_id = t.coordinator_id AND l.link_id = t.link_id AND l.authority_kind = 'controller_attestation' WHERE t.authority_kind = 'controller_attestation' AND t.attempt_id = ? AND t.coordinator_id = ? AND t.issuer = ? AND t.auth_config_revision = ? AND ? = 1 AND t.link_id = ?`,\n\t\tvalues: [i.attemptId, ...configValues(c), linkId],\n\t};\n\treturn [consume, link, audit];\n}\nfunction receiptSql(connections: boolean) {\n\treturn `SELECT 1 FROM coordinator_auth_link_attempts t\n JOIN ${connections ? `(${CONNECTION_BIRTHS_SQL})` : \"coordinator_auth_account_links\"} l ON l.coordinator_id = t.coordinator_id AND l.link_id = t.link_id\n AND l.attempt_id = t.attempt_id AND l.identity_id = t.identity_id AND l.issuer = t.issuer AND l.subject = t.account_subject\n AND l.authority_kind = 'controller_attestation' AND l.controller_attestation_id IS NOT NULL AND l.controller_attestation_id IS t.controller_attestation_id AND l.device_claim_id IS NULL AND l.auth_config_revision = t.auth_config_revision AND l.created_at_ms = t.finalized_at_ms\n JOIN coordinator_auth_link_audit_log a ON a.coordinator_id = t.coordinator_id AND a.link_id = t.link_id AND a.action = 'link_created'\n AND a.attempt_id = t.attempt_id AND a.identity_id = t.identity_id AND a.group_id = t.group_id AND a.device_id = t.device_id\n AND a.fingerprint = t.fingerprint AND a.authority_kind = 'controller_attestation' AND a.controller_attestation_id IS t.controller_attestation_id AND a.device_claim_id IS NULL AND a.auth_config_revision = t.auth_config_revision AND a.created_at_ms = t.finalized_at_ms\n WHERE t.authority_kind = 'controller_attestation' AND t.coordinator_id = ? AND t.attempt_id = ? AND t.link_id = ?`;\n}\n","import {\n\tprepareAccountChangeAuthority,\n\tprepareAccountChangeAuthorityFor,\n\treadAccountChangeBase,\n} from \"./coordinator-account-change-authority.js\";\nimport type {\n\tAccountChangeGrant,\n\tAccountChangeTarget,\n} from \"./coordinator-account-change-decision.js\";\nimport {\n\tconnectionAdmissionSql,\n\thasConnectionSessionSchema,\n} from \"./coordinator-account-connection-session.js\";\nimport {\n\tCONNECTION_ALLOCATE_ORDER_SQL,\n\tCONNECTION_ARCHIVED_CURRENT_MATCH_SQL,\n\tCONNECTION_ASSERT_ONE_WRITE_SQL,\n\tCONNECTION_BIRTH_COLUMNS,\n} from \"./coordinator-account-connection-storage.js\";\nimport { ACCOUNT_UNLINK_TABLE } from \"./coordinator-account-unlink-schema.js\";\nimport { captureAuthAccountProfile } from \"./coordinator-auth-account-profile.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_EXPIRE_BATCH_MAX,\n\ttype CoordinatorAuthLinkConfig,\n\ttype CoordinatorAuthLinkSigner,\n} from \"./coordinator-auth-link-contract.js\";\nimport {\n\tcapture,\n\tcaptureAuthLinkConfig,\n\tcaptureAuthLinkSigner,\n\tisHash,\n} from \"./coordinator-auth-link-input.js\";\nimport { parseCoordinatorAuthLoopback } from \"./coordinator-auth-loopback.js\";\nimport { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport { sqlIs } from \"./coordinator-sql-compare.js\";\n\nconst table = \"coordinator_account_change_attempts\";\nconst history = \"coordinator_auth_account_connection_history\";\nconst orders = \"coordinator_auth_account_connection_orders\";\nconst current = \"coordinator_auth_account_links\";\nconst sql = (query: string, values: AuthLinkStatement[\"values\"] = []): AuthLinkStatement => ({\n\tsql: query,\n\tvalues,\n});\nconst assertOne = sql(CONNECTION_ASSERT_ONE_WRITE_SQL);\ntype Intent = \"refresh\" | \"disconnect\";\ninterface ChangeRow {\n\tattempt_id: string;\n\ttarget_link_id: string;\n\tidentity_id: string;\n\tissuer: string;\n\ttarget_subject: string;\n\tintent: Intent;\n\tstate: string;\n\tauth_config_revision: string;\n\tenrollment_identity_id: string | null;\n\tgroup_id: string;\n\tdevice_id: string;\n\tpublic_key: string;\n\tfingerprint: string;\n\truntime_verifier_hash: string;\n\tcompletion_secret_hash: string | null;\n\tcompleted_at_ms: number;\n\tnonce: string;\n\tpkce_verifier: string;\n\texpires_at_ms: number;\n\tloopback_redirect: string;\n\tdisplay_name: string | null;\n\temail: string | null;\n\temail_verified: number | null;\n\tpicture_url: string | null;\n}\nexport interface AccountChangeOutcome {\n\tintent: Intent;\n\ttargetLinkId: string;\n\tcompletedAtMs: number;\n}\ninterface Signed {\n\tattemptId: string;\n\tsigner: CoordinatorAuthLinkSigner;\n\truntimeVerifierHash: string;\n\texpectedIdentityId: string;\n}\nfunction signed(value: unknown): Signed | null {\n\tconst i = capture(value, [\"attemptId\", \"signer\", \"runtimeVerifierHash\", \"expectedIdentityId\"]);\n\tconst signer = captureAuthLinkSigner(i?.signer);\n\tif (\n\t\t!i ||\n\t\t!signer ||\n\t\t!isAuthControllerId(i.attemptId) ||\n\t\t!isHash(i.runtimeVerifierHash) ||\n\t\t!isAuthControllerId(i.expectedIdentityId)\n\t)\n\t\treturn null;\n\treturn {\n\t\tattemptId: i.attemptId,\n\t\tsigner,\n\t\truntimeVerifierHash: i.runtimeVerifierHash,\n\t\texpectedIdentityId: i.expectedIdentityId,\n\t};\n}\nfunction signerValues(s: CoordinatorAuthLinkSigner): string[] {\n\treturn [s.groupId, s.deviceId, s.publicKey, s.fingerprint];\n}\nconst signedMatch =\n\t\"a.group_id = ? AND a.device_id = ? AND a.public_key = ? AND a.fingerprint = ? AND a.runtime_verifier_hash = ? AND a.identity_id = ?\";\nconst signedValues = (i: Signed) => [\n\t...signerValues(i.signer),\n\ti.runtimeVerifierHash,\n\ti.expectedIdentityId,\n];\nconst configured = \"a.coordinator_id = ? AND a.issuer = ? AND a.auth_config_revision = ? AND ? = 1\";\nconst configValues = (c: CoordinatorAuthLinkConfig) => [\n\tc.coordinatorId,\n\tc.issuer,\n\tc.revision,\n\tNumber(c.enabled),\n];\nconst outcome = (a: ChangeRow): AccountChangeOutcome => ({\n\tintent: a.intent,\n\ttargetLinkId: a.target_link_id,\n\tcompletedAtMs: a.completed_at_ms,\n});\nfunction unlinkInput(value: unknown) {\n\tconst i = capture(value, [\n\t\t\"attemptId\",\n\t\t\"signer\",\n\t\t\"expectedIdentityId\",\n\t\t\"expectedLinkId\",\n\t\t\"requestHash\",\n\t]);\n\tconst signer = captureAuthLinkSigner(i?.signer);\n\tif (\n\t\t!i ||\n\t\t!signer ||\n\t\t!isAuthControllerId(i.attemptId) ||\n\t\t!isAuthControllerId(i.expectedIdentityId) ||\n\t\t!isAuthControllerId(i.expectedLinkId) ||\n\t\t!isHash(i.requestHash)\n\t)\n\t\treturn null;\n\treturn {\n\t\tattemptId: i.attemptId,\n\t\tsigner,\n\t\texpectedIdentityId: i.expectedIdentityId,\n\t\texpectedLinkId: i.expectedLinkId,\n\t\trequestHash: i.requestHash,\n\t};\n}\n\n// LINK and CHANGE share admission budgets; terminal receipts still count toward\n// hourly/retention creation limits, but not toward concurrent live attempts.\n// Retained failures also consume the existing coordinator unfinished budget.\n// Admission is a budget, not authority, so it stays in the INSERT and counts live rows.\nconst admissionInput =\n\t\"(SELECT ? AS coordinator_id, ? AS group_id, ? AS device_id, ? AS identity_id, ? AS now_ms)\";\nconst admissionValues = (\n\tc: CoordinatorAuthLinkConfig,\n\ts: CoordinatorAuthLinkSigner,\n\ttarget: AccountChangeTarget,\n\tnow: number,\n) => [c.coordinatorId, s.groupId, s.deviceId, target.identity_id, now];\nfunction browserPin(value: unknown) {\n\tconst i = capture(value, [\"attemptId\", \"stateHash\", \"binderHash\"]);\n\tif (!i || !isAuthControllerId(i.attemptId) || !isHash(i.stateHash) || !isHash(i.binderHash))\n\t\treturn null;\n\treturn { attemptId: i.attemptId, stateHash: i.stateHash, binderHash: i.binderHash };\n}\nconst browserMatch = \"a.attempt_id = ? AND a.state_hash = ? AND a.binder_hash = ?\";\nconst scrub =\n\t\"nonce = NULL,pkce_verifier = NULL,display_name = NULL,email = NULL,email_verified = NULL,picture_url = NULL\";\n\n/** Alias a: the attempt row still names the granted link, Identity and enrollment Identity. */\nconst grantedRowSql =\n\t\"a.coordinator_id = ? AND a.target_link_id = ? AND a.identity_id = ? AND a.target_subject = ? AND a.issuer = ? AND a.enrollment_identity_id IS ?\";\nconst grantedRowValues = (g: AccountChangeGrant) => [\n\tg.coordinatorId,\n\tg.linkId,\n\tg.identityId,\n\tg.subject,\n\tg.issuer,\n\tg.enrollmentIdentityId,\n];\n\n/** Private persistence boundary only. Signed inputs must come from the\n * signature verifier; verified callbacks must come from the maintained OIDC\n * adapter after state/binder consumption. These methods do not verify signatures,\n * Google tokens, browser cookies or CSRF, and must never be mounted as JSON APIs.\n */\n\nexport class AccountChangeOperations {\n\tconstructor(\n\t\tprivate readonly backend: AuthLinkBackend,\n\t\tprivate readonly clock: () => number = Date.now,\n\t) {}\n\tprivate first<T>(statement: AuthLinkStatement) {\n\t\treturn this.backend.first<T>(statement);\n\t}\n\tprivate async atomic(statements: AuthLinkStatement[]): Promise<boolean> {\n\t\ttry {\n\t\t\tawait this.backend.batch(statements);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\tprivate row(c: CoordinatorAuthLinkConfig, id: string) {\n\t\treturn this.first<ChangeRow>(\n\t\t\tsql(`SELECT * FROM ${table} WHERE coordinator_id = ? AND attempt_id = ?`, [\n\t\t\t\tc.coordinatorId,\n\t\t\t\tid,\n\t\t\t]),\n\t\t);\n\t}\n\t// The grant is void unless its guards run first in the batch that writes.\n\tprivate authority(\n\t\tc: CoordinatorAuthLinkConfig,\n\t\ts: CoordinatorAuthLinkSigner,\n\t\ttarget: AccountChangeTarget,\n\t\tnow: number,\n\t) {\n\t\treturn prepareAccountChangeAuthorityFor(this.backend, c, s, target, now);\n\t}\n\t/** Derives the target from this signer's own proofs, then decides on it. */\n\tprivate async derivedAuthority(\n\t\tc: CoordinatorAuthLinkConfig,\n\t\ts: CoordinatorAuthLinkSigner,\n\t\tkeyId: string,\n\t\taccept: (target: AccountChangeTarget) => boolean,\n\t\tnow: number,\n\t) {\n\t\tconst base = await readAccountChangeBase(this.backend, c, s, { deriveTarget: { keyId } });\n\t\tconst { target } = base;\n\t\tif (!target || !accept(target)) return null;\n\t\tconst authority = await prepareAccountChangeAuthority(this.backend, base, c, s, target, now);\n\t\treturn authority ? { target, ...authority } : null;\n\t}\n\tprivate retryCreate(\n\t\tc: CoordinatorAuthLinkConfig,\n\t\ti: Signed,\n\t\textra: Record<string, unknown>,\n\t\tnow: number,\n\t) {\n\t\treturn this.first(\n\t\t\tsql(\n\t\t\t\t`SELECT 1 FROM ${table} a WHERE ${configured} AND a.attempt_id = ? AND ${signedMatch} AND a.intent = ? AND a.browser_start_hash = ? AND a.loopback_redirect = ? AND a.state NOT IN ('cancelled','failed','expired') AND (a.state = 'completed' OR a.expires_at_ms > ?)`,\n\t\t\t\t[\n\t\t\t\t\t...configValues(c),\n\t\t\t\t\ti.attemptId,\n\t\t\t\t\t...signedValues(i),\n\t\t\t\t\textra.intent as string,\n\t\t\t\t\textra.browserStartHash as string,\n\t\t\t\t\textra.loopbackRedirect as string,\n\t\t\t\t\tnow,\n\t\t\t\t],\n\t\t\t),\n\t\t);\n\t}\n\t/** Descriptive device actions only; create/finalize always recheck current authority. */\n\tasync readCapabilities(\n\t\tvalue: unknown,\n\t\tconfig: unknown,\n\t): Promise<{ refresh: boolean; disconnect: boolean; unlinkTarget?: string }> {\n\t\tconst c = captureAuthLinkConfig(config);\n\t\tconst i = capture(value, [\"signer\", \"expectedIdentityId\"]);\n\t\tconst signer = captureAuthLinkSigner(i?.signer);\n\t\tconst unavailable = { refresh: false, disconnect: false };\n\t\tif (!c?.enabled || !i || !signer || !isAuthControllerId(i.expectedIdentityId))\n\t\t\treturn unavailable;\n\t\tconst key = await ed25519KeyIdForRevocation(signer.publicKey);\n\t\tif (!key) return unavailable;\n\t\tconst authority = await this.derivedAuthority(\n\t\t\tc,\n\t\t\tsigner,\n\t\t\tkey,\n\t\t\t(target) => target.identity_id === i.expectedIdentityId,\n\t\t\tauthLinkNow(this.clock),\n\t\t);\n\t\tif (!authority) return unavailable;\n\t\tconst { target } = authority;\n\t\t// Descriptive only, so nothing re-runs the reads.\n\t\tconst allowed = authority.grant !== null;\n\t\treturn {\n\t\t\trefresh: allowed,\n\t\t\tdisconnect: allowed,\n\t\t\t...(allowed ? { unlinkTarget: target.target_link_id } : {}),\n\t\t};\n\t}\n\t/** Device-signed unlink only. The winning INSERT rechecks live authority and the exact target. */\n\tasync unlink(value: unknown, config: unknown): Promise<AccountChangeOutcome | null> {\n\t\tconst c = captureAuthLinkConfig(config);\n\t\tconst i = unlinkInput(value);\n\t\tif (!c?.enabled || !i) return null;\n\t\tconst { signer } = i;\n\t\tconst pins = [\n\t\t\tc.coordinatorId,\n\t\t\ti.attemptId,\n\t\t\ti.expectedLinkId,\n\t\t\ti.expectedIdentityId,\n\t\t\tc.issuer,\n\t\t\t...signerValues(signer),\n\t\t\tc.revision,\n\t\t\ti.requestHash,\n\t\t];\n\t\tconst retry = () =>\n\t\t\tthis.first<{ targetLinkId: string; completedAtMs: number }>(\n\t\t\t\tsql(\n\t\t\t\t\t`SELECT target_link_id AS targetLinkId,completed_at_ms AS completedAtMs FROM ${ACCOUNT_UNLINK_TABLE} WHERE coordinator_id=? AND attempt_id=? AND target_link_id=? AND identity_id=? AND issuer=? AND group_id=? AND device_id=? AND public_key=? AND fingerprint=? AND auth_config_revision=? AND request_hash=? AND state='completed'`,\n\t\t\t\t\tpins,\n\t\t\t\t),\n\t\t\t);\n\t\tconst prior = await retry();\n\t\tif (prior) return { intent: \"disconnect\", ...prior };\n\t\tconst key = await ed25519KeyIdForRevocation(signer.publicKey);\n\t\tif (!key) return null;\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst authority = await this.derivedAuthority(\n\t\t\tc,\n\t\t\tsigner,\n\t\t\tkey,\n\t\t\t(target) =>\n\t\t\t\ttarget.identity_id === i.expectedIdentityId && target.target_link_id === i.expectedLinkId,\n\t\t\tnow,\n\t\t);\n\t\tif (!authority) return null;\n\t\tconst { grant } = authority;\n\t\tif (grant) await this.atomic([...authority.guards, ...unlinkWrites(c, i, grant, now)]);\n\t\tconst completed = await retry();\n\t\treturn completed ? { intent: \"disconnect\", ...completed } : null;\n\t}\n\tasync create(value: unknown, config: unknown): Promise<boolean> {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = signed(value);\n\t\tconst extra = capture(value, [\"intent\", \"browserStartHash\", \"loopbackRedirect\"]);\n\t\tif (\n\t\t\t!c?.enabled ||\n\t\t\t!i ||\n\t\t\t!extra ||\n\t\t\t!isHash(extra.browserStartHash) ||\n\t\t\t!parseCoordinatorAuthLoopback(extra.loopbackRedirect).ok ||\n\t\t\t(extra.intent !== \"refresh\" && extra.intent !== \"disconnect\")\n\t\t)\n\t\t\treturn false;\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst retry = () => this.retryCreate(c, i, extra, now);\n\t\tif (await this.row(c, i.attemptId)) return !!(await retry());\n\t\tconst key = await ed25519KeyIdForRevocation(i.signer.publicKey);\n\t\tif (!key) return false;\n\t\tconst authority = await this.derivedAuthority(\n\t\t\tc,\n\t\t\ti.signer,\n\t\t\tkey,\n\t\t\t(target) => target.identity_id === i.expectedIdentityId,\n\t\t\tnow,\n\t\t);\n\t\tif (!authority) return false;\n\t\tconst { grant, target } = authority;\n\t\tconst created =\n\t\t\t!!grant &&\n\t\t\t(await this.atomic([\n\t\t\t\t...authority.guards,\n\t\t\t\tcreateWrite({\n\t\t\t\t\tc,\n\t\t\t\t\ti,\n\t\t\t\t\tintent: extra.intent,\n\t\t\t\t\tkey,\n\t\t\t\t\tgrant,\n\t\t\t\t\ttarget,\n\t\t\t\t\tnow,\n\t\t\t\t\tbrowserStartHash: extra.browserStartHash,\n\t\t\t\t\tloopbackRedirect: extra.loopbackRedirect as string,\n\t\t\t\t}),\n\t\t\t\tassertOne,\n\t\t\t]));\n\t\treturn created || !!(await retry());\n\t}\n\tasync claimBrowser(value: unknown, config: unknown): Promise<boolean> {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = capture(value, [\n\t\t\t\t\"attemptId\",\n\t\t\t\t\"browserStartHash\",\n\t\t\t\t\"stateHash\",\n\t\t\t\t\"binderHash\",\n\t\t\t\t\"nonce\",\n\t\t\t\t\"pkceVerifier\",\n\t\t\t]);\n\t\tif (\n\t\t\t!c?.enabled ||\n\t\t\t!i ||\n\t\t\t!isAuthControllerId(i.attemptId) ||\n\t\t\t![i.browserStartHash, i.stateHash, i.binderHash].every(isHash) ||\n\t\t\t![i.nonce, i.pkceVerifier].every(\n\t\t\t\t(v) => typeof v === \"string\" && /^[A-Za-z0-9_-]{43,128}$/.test(v),\n\t\t\t)\n\t\t)\n\t\t\treturn false;\n\t\tconst now = authLinkNow(this.clock);\n\t\treturn this.atomic([\n\t\t\tsql(\n\t\t\t\t`INSERT INTO ${orders} (coordinator_id,last_order) SELECT ?,0 WHERE NOT EXISTS (SELECT 1 FROM ${orders} WHERE coordinator_id = ?)`,\n\t\t\t\t[c.coordinatorId, c.coordinatorId],\n\t\t\t),\n\t\t\tsql(CONNECTION_ALLOCATE_ORDER_SQL, [c.coordinatorId]),\n\t\t\tassertOne,\n\t\t\tsql(\n\t\t\t\t`UPDATE ${table} AS a SET state = 'browser_pending',state_hash = ?,binder_hash = ?,nonce = ?,pkce_verifier = ?,browser_order = (SELECT last_order FROM ${orders} WHERE coordinator_id = a.coordinator_id)\n WHERE ${configured} AND a.attempt_id = ? AND a.browser_start_hash = ? AND a.state = 'pending' AND a.expires_at_ms > ?`,\n\t\t\t\t[\n\t\t\t\t\ti.stateHash as string,\n\t\t\t\t\ti.binderHash as string,\n\t\t\t\t\ti.nonce as string,\n\t\t\t\t\ti.pkceVerifier as string,\n\t\t\t\t\t...configValues(c),\n\t\t\t\t\ti.attemptId,\n\t\t\t\t\ti.browserStartHash as string,\n\t\t\t\t\tnow,\n\t\t\t\t],\n\t\t\t),\n\t\t\tassertOne,\n\t\t]);\n\t}\n\t/** Lookup AND one-use consumption are one private operation; returned secrets\n\t * may be used only by the OIDC exchange, never returned by a public status API. */\n\tasync consumeCallback(value: unknown, config: unknown) {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = capture(value, [\"stateHash\", \"binderHash\"]);\n\t\tif (!c?.enabled || !i || !isHash(i.stateHash) || !isHash(i.binderHash)) return null;\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst a = await this.first<ChangeRow>(\n\t\t\tsql(\n\t\t\t\t`SELECT * FROM ${table} a WHERE ${configured} AND a.state_hash = ? AND a.binder_hash = ? AND a.state = 'browser_pending' AND a.expires_at_ms > ?`,\n\t\t\t\t[...configValues(c), i.stateHash, i.binderHash, now],\n\t\t\t),\n\t\t);\n\t\tif (!a) return null;\n\t\tconst won = await this.atomic([\n\t\t\tsql(\n\t\t\t\t`UPDATE ${table} AS a SET state = 'consumed',nonce = NULL,pkce_verifier = NULL,consumed_at_ms = ? WHERE ${configured} AND a.attempt_id = ? AND a.state_hash = ? AND a.binder_hash = ? AND a.state = 'browser_pending' AND a.expires_at_ms > ?`,\n\t\t\t\t[now, ...configValues(c), a.attempt_id, i.stateHash, i.binderHash, now],\n\t\t\t),\n\t\t\tassertOne,\n\t\t]);\n\t\treturn won ? { attemptId: a.attempt_id, nonce: a.nonce, pkceVerifier: a.pkce_verifier } : null;\n\t}\n\tprivate async callbackAuthority(c: CoordinatorAuthLinkConfig, attemptId: string, now: number) {\n\t\tconst a = await this.row(c, attemptId);\n\t\tif (!a) return null;\n\t\treturn this.authority(\n\t\t\tc,\n\t\t\t{\n\t\t\t\tgroupId: a.group_id,\n\t\t\t\tdeviceId: a.device_id,\n\t\t\t\tpublicKey: a.public_key,\n\t\t\t\tfingerprint: a.fingerprint,\n\t\t\t},\n\t\t\ta,\n\t\t\tnow,\n\t\t);\n\t}\n\t/** Trusted adapter output, not HTTP account JSON. No autoConfirm caller flag. */\n\tasync recordVerifiedCallback(value: unknown, config: unknown): Promise<boolean> {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = capture(value, [\n\t\t\t\t\"attemptId\",\n\t\t\t\t\"stateHash\",\n\t\t\t\t\"binderHash\",\n\t\t\t\t\"issuer\",\n\t\t\t\t\"subject\",\n\t\t\t\t\"profile\",\n\t\t\t\t\"completionSecretHash\",\n\t\t\t]);\n\t\tconst profile = captureAuthAccountProfile(i?.profile);\n\t\tif (\n\t\t\t!c?.enabled ||\n\t\t\t!i ||\n\t\t\t!profile ||\n\t\t\t!isAuthControllerId(i.attemptId) ||\n\t\t\t![i.stateHash, i.binderHash, i.completionSecretHash].every(isHash) ||\n\t\t\ti.issuer !== c.issuer ||\n\t\t\ttypeof i.subject !== \"string\"\n\t\t)\n\t\t\treturn false;\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst authority = await this.callbackAuthority(c, i.attemptId, now);\n\t\tif (!authority) return false;\n\t\tconst { grant } = authority;\n\t\tif (!grant) return false;\n\t\treturn this.atomic([\n\t\t\t...authority.guards,\n\t\t\tsql(\n\t\t\t\t`UPDATE ${table} AS a SET state = CASE intent WHEN 'refresh' THEN 'confirmed' ELSE 'verified' END,verified_at_ms = ?,\n confirmed_at_ms = CASE intent WHEN 'refresh' THEN ? END,completion_secret_hash = CASE intent WHEN 'refresh' THEN ? END,\n display_name = ?,email = ?,email_verified = ?,picture_url = ? WHERE ${configured} AND a.attempt_id = ? AND a.state_hash = ? AND a.binder_hash = ? AND a.target_subject = ? AND a.state = 'consumed' AND a.expires_at_ms > ?\n AND ${grantedRowSql}`,\n\t\t\t\t[\n\t\t\t\t\tnow,\n\t\t\t\t\tnow,\n\t\t\t\t\ti.completionSecretHash as string,\n\t\t\t\t\tprofile.displayName ?? null,\n\t\t\t\t\tprofile.email ?? null,\n\t\t\t\t\tprofile.emailVerified === undefined ? null : Number(profile.emailVerified),\n\t\t\t\t\tprofile.pictureUrl ?? null,\n\t\t\t\t\t...configValues(c),\n\t\t\t\t\ti.attemptId,\n\t\t\t\t\ti.stateHash as string,\n\t\t\t\t\ti.binderHash as string,\n\t\t\t\t\ti.subject,\n\t\t\t\t\tnow,\n\t\t\t\t\t...grantedRowValues(grant),\n\t\t\t\t],\n\t\t\t),\n\t\t\tassertOne,\n\t\t]);\n\t}\n\t/** The browser handler validates the fresh binder and CSRF before this call. */\n\tasync confirmDisconnect(value: unknown, config: unknown): Promise<boolean> {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = browserPin(value),\n\t\t\tproof = capture(value, [\"completionSecretHash\"]);\n\t\tif (!c?.enabled || !i || !proof || !isHash(proof.completionSecretHash)) return false;\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst won = await this.atomic([\n\t\t\tsql(\n\t\t\t\t`UPDATE ${table} AS a SET state = 'confirmed',confirmed_at_ms = ?,completion_secret_hash = ? WHERE ${configured} AND a.attempt_id = ? AND a.state_hash = ? AND a.binder_hash = ? AND a.intent = 'disconnect' AND a.state = 'verified' AND a.expires_at_ms > ?`,\n\t\t\t\t[\n\t\t\t\t\tnow,\n\t\t\t\t\tproof.completionSecretHash,\n\t\t\t\t\t...configValues(c),\n\t\t\t\t\ti.attemptId,\n\t\t\t\t\ti.stateHash as string,\n\t\t\t\t\ti.binderHash as string,\n\t\t\t\t\tnow,\n\t\t\t\t],\n\t\t\t),\n\t\t\tassertOne,\n\t\t]);\n\t\tif (won) return true;\n\t\treturn this.readConfirmedDisconnect(i, proof.completionSecretHash, c);\n\t}\n\tprivate async readConfirmedDisconnect(\n\t\tpins: NonNullable<ReturnType<typeof browserPin>>,\n\t\tcompletionSecretHash: string,\n\t\tc: CoordinatorAuthLinkConfig,\n\t): Promise<boolean> {\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst authority = await this.callbackAuthority(c, pins.attemptId, now);\n\t\tconst grant = authority?.grant;\n\t\tif (!grant) return false;\n\t\t// This request still owns the raw secret; never recover from status alone.\n\t\t// A read only, so nothing re-runs the authority reads.\n\t\treturn !!(await this.first(\n\t\t\tsql(\n\t\t\t\t`SELECT 1 FROM ${table} a WHERE ${configured} AND ${browserMatch}\n AND a.intent='disconnect' AND a.state='confirmed' AND a.completion_secret_hash=? AND a.expires_at_ms>?\n AND ${grantedRowSql}`,\n\t\t\t\t[\n\t\t\t\t\t...configValues(c),\n\t\t\t\t\tpins.attemptId,\n\t\t\t\t\tpins.stateHash,\n\t\t\t\t\tpins.binderHash,\n\t\t\t\t\tcompletionSecretHash,\n\t\t\t\t\tnow,\n\t\t\t\t\t...grantedRowValues(grant),\n\t\t\t\t],\n\t\t\t),\n\t\t));\n\t}\n\tasync finalize(value: unknown, config: unknown): Promise<AccountChangeOutcome | null> {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = signed(value),\n\t\t\tproof = capture(value, [\"completionSecretHash\"]);\n\t\tif (!c?.enabled || !i || !proof || !isHash(proof.completionSecretHash)) return null;\n\t\tconst a = await this.row(c, i.attemptId);\n\t\tif (!a) return null;\n\t\tconst pins = [...configValues(c), i.attemptId, ...signedValues(i), proof.completionSecretHash];\n\t\tconst match = `${configured} AND a.attempt_id = ? AND ${signedMatch} AND a.completion_secret_hash = ?`;\n\t\t// Retained exact-proof retries have no effects, including after target deletion.\n\t\tconst retry = await this.first<ChangeRow>(\n\t\t\tsql(`SELECT * FROM ${table} a WHERE ${match} AND a.state = 'completed'`, pins),\n\t\t);\n\t\tif (retry) return outcome(retry);\n\t\tconst now = authLinkNow(this.clock),\n\t\t\tauthority = await this.authority(c, i.signer, a, now);\n\t\tif (!authority) return null;\n\t\tconst { grant } = authority;\n\t\tconst effects =\n\t\t\ta.intent === \"disconnect\"\n\t\t\t\t? disconnectEffects(c.coordinatorId, i.attemptId, now, {\n\t\t\t\t\t\tconnections: await hasConnectionSessionSchema(this.backend),\n\t\t\t\t\t})\n\t\t\t\t: refreshEffects(c.coordinatorId, i.attemptId);\n\t\t// A denied grant takes the same path as the old statement that matched no row.\n\t\tif (\n\t\t\t!grant ||\n\t\t\t!(await this.atomic([\n\t\t\t\t...authority.guards,\n\t\t\t\tsql(\n\t\t\t\t\t`UPDATE ${table} AS a SET state = 'committing' WHERE ${match} AND a.state = 'confirmed' AND a.expires_at_ms > ?\n AND a.target_link_id = ? AND a.target_subject = ? AND a.enrollment_identity_id IS ?`,\n\t\t\t\t\t[...pins, now, grant.linkId, grant.subject, grant.enrollmentIdentityId],\n\t\t\t\t),\n\t\t\t\tassertOne,\n\t\t\t\t...effects,\n\t\t\t\tsql(\n\t\t\t\t\t`UPDATE ${table} SET state = 'completed',completed_at_ms = ?,display_name = NULL,email = NULL,email_verified = NULL,picture_url = NULL WHERE coordinator_id = ? AND attempt_id = ? AND state = 'committing'`,\n\t\t\t\t\t[now, c.coordinatorId, i.attemptId],\n\t\t\t\t),\n\t\t\t\tassertOne,\n\t\t\t]))\n\t\t) {\n\t\t\tconst completed = await this.first<ChangeRow>(\n\t\t\t\tsql(`SELECT * FROM ${table} a WHERE ${match} AND a.state = 'completed'`, pins),\n\t\t\t);\n\t\t\treturn completed ? outcome(completed) : null;\n\t\t}\n\t\treturn { intent: a.intent, targetLinkId: a.target_link_id, completedAtMs: now };\n\t}\n\tasync cancel(value: unknown, config: unknown): Promise<boolean> {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = signed(value);\n\t\tif (!c?.enabled || !i) return false;\n\t\treturn this.atomic([\n\t\t\tsql(\n\t\t\t\t`UPDATE ${table} AS a SET state = 'cancelled',failure_reason = 'device_cancelled',nonce = NULL,pkce_verifier = NULL,display_name = NULL,email = NULL,email_verified = NULL,picture_url = NULL WHERE ${configured} AND a.attempt_id = ? AND ${signedMatch} AND a.state NOT IN ('completed','committing','cancelled','failed','expired') AND a.expires_at_ms > ?`,\n\t\t\t\t[...configValues(c), i.attemptId, ...signedValues(i), authLinkNow(this.clock)],\n\t\t\t),\n\t\t\tassertOne,\n\t\t]);\n\t}\n\t/** Signed status is descriptive only; it never supplies management authority. */\n\tasync readStatus(value: unknown, config: unknown) {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = signed(value);\n\t\tif (!c?.enabled || !i) return null;\n\t\tconst a = await this.first<ChangeRow>(\n\t\t\tsql(`SELECT * FROM ${table} a WHERE ${configured} AND a.attempt_id = ? AND ${signedMatch}`, [\n\t\t\t\t...configValues(c),\n\t\t\t\ti.attemptId,\n\t\t\t\t...signedValues(i),\n\t\t\t]),\n\t\t);\n\t\tif (!a) return null;\n\t\tconst state =\n\t\t\t[\"pending\", \"browser_pending\", \"consumed\", \"verified\", \"confirmed\"].includes(a.state) &&\n\t\t\ta.expires_at_ms <= authLinkNow(this.clock)\n\t\t\t\t? \"expired\"\n\t\t\t\t: a.state;\n\t\treturn {\n\t\t\tattemptId: a.attempt_id,\n\t\t\tintent: a.intent,\n\t\t\tstate,\n\t\t\texpiresAtMs: a.expires_at_ms,\n\t\t\tidentityId: a.identity_id,\n\t\t};\n\t}\n\t/** Shared callback dispatch can probe exact state/binder without consuming it. */\n\tasync hasPendingCallback(value: unknown, config: unknown): Promise<boolean> {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = capture(value, [\"stateHash\", \"binderHash\"]);\n\t\tif (!c?.enabled || !i || !isHash(i.stateHash) || !isHash(i.binderHash)) return false;\n\t\treturn !!(await this.first(\n\t\t\tsql(\n\t\t\t\t`SELECT 1 FROM ${table} a WHERE ${configured} AND a.state_hash = ? AND a.binder_hash = ? AND a.state = 'browser_pending' AND a.expires_at_ms > ?`,\n\t\t\t\t[...configValues(c), i.stateHash, i.binderHash, authLinkNow(this.clock)],\n\t\t\t),\n\t\t));\n\t}\n\t/** Prepare delivery for an exact consumed proof; the winning write rechecks authority. */\n\tasync readCallbackView(value: unknown, config: unknown) {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = browserPin(value);\n\t\tif (!c?.enabled || !i) return null;\n\t\tconst a = await this.first<ChangeRow>(\n\t\t\tsql(\n\t\t\t\t`SELECT * FROM ${table} a WHERE ${configured} AND ${browserMatch} AND a.state = 'consumed' AND a.expires_at_ms > ?`,\n\t\t\t\t[...configValues(c), i.attemptId, i.stateHash, i.binderHash, authLinkNow(this.clock)],\n\t\t\t),\n\t\t);\n\t\tif (!a || !parseCoordinatorAuthLoopback(a.loopback_redirect).ok) return null;\n\t\treturn { attemptId: a.attempt_id, intent: a.intent, loopbackRedirect: a.loopback_redirect };\n\t}\n\t/** Cookie-authenticated, CSRF-protected hosted confirmation only, not status JSON. */\n\tasync readBrowserView(value: unknown, config: unknown) {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = browserPin(value);\n\t\tif (!c?.enabled || !i) return null;\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst a = await this.first<ChangeRow>(\n\t\t\tsql(\n\t\t\t\t`SELECT * FROM ${table} a WHERE ${configured} AND ${browserMatch} AND a.state IN ('verified','confirmed') AND a.expires_at_ms > ?`,\n\t\t\t\t[...configValues(c), i.attemptId, i.stateHash, i.binderHash, now],\n\t\t\t),\n\t\t);\n\t\tif (!a) return null;\n\t\tif (!parseCoordinatorAuthLoopback(a.loopback_redirect).ok) return null;\n\t\tconst authority = await this.authority(\n\t\t\tc,\n\t\t\t{\n\t\t\t\tgroupId: a.group_id,\n\t\t\t\tdeviceId: a.device_id,\n\t\t\t\tpublicKey: a.public_key,\n\t\t\t\tfingerprint: a.fingerprint,\n\t\t\t},\n\t\t\ta,\n\t\t\tnow,\n\t\t);\n\t\t// A read only, so nothing re-runs the authority reads.\n\t\tconst grant = authority?.grant;\n\t\tif (!grant || !sqlIs(grant.enrollmentIdentityId, a.enrollment_identity_id)) return null;\n\t\tconst profile = captureAuthAccountProfile({\n\t\t\tdisplayName: a.display_name,\n\t\t\temail: a.email,\n\t\t\temailVerified: a.email_verified === null ? undefined : Boolean(a.email_verified),\n\t\t\tpictureUrl: a.picture_url,\n\t\t});\n\t\treturn {\n\t\t\tattemptId: a.attempt_id,\n\t\t\tintent: a.intent,\n\t\t\tstate: a.state,\n\t\t\tloopbackRedirect: a.loopback_redirect,\n\t\t\tidentityId: a.identity_id,\n\t\t\texpiresAtMs: a.expires_at_ms,\n\t\t\tprofile,\n\t\t};\n\t}\n\t/** Private cookie binding lookup; never returns account or redirect data. */\n\tasync readBrowserBinding(value: unknown, config: unknown): Promise<{ stateHash: string } | null> {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = capture(value, [\"attemptId\", \"binderHash\"]);\n\t\tif (!c?.enabled || !i || !isAuthControllerId(i.attemptId) || !isHash(i.binderHash)) return null;\n\t\treturn this.first(\n\t\t\tsql(\n\t\t\t\t`SELECT state_hash AS stateHash FROM ${table} a WHERE ${configured} AND a.attempt_id = ? AND a.binder_hash = ? AND a.state IN ('verified','confirmed') AND a.expires_at_ms > ?`,\n\t\t\t\t[...configValues(c), i.attemptId, i.binderHash, authLinkNow(this.clock)],\n\t\t\t),\n\t\t);\n\t}\n\t/** Private start-code lookup; no account, profile or redirect data before proof. */\n\tasync readStart(value: unknown, config: unknown) {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = capture(value, [\"attemptId\", \"browserStartHash\"]);\n\t\tif (!c?.enabled || !i || !isAuthControllerId(i.attemptId) || !isHash(i.browserStartHash))\n\t\t\treturn null;\n\t\treturn this.first<{ intent: Intent; expiresAtMs: number }>(\n\t\t\tsql(\n\t\t\t\t`SELECT intent,expires_at_ms AS expiresAtMs FROM ${table} a WHERE ${configured} AND a.attempt_id = ? AND a.browser_start_hash = ? AND a.state = 'pending' AND a.expires_at_ms > ?`,\n\t\t\t\t[...configValues(c), i.attemptId, i.browserStartHash, authLinkNow(this.clock)],\n\t\t\t),\n\t\t);\n\t}\n\t/** Cookie-binder activity probe for the shared configured browser handler. */\n\tasync readManagementActivity(value: unknown, config: unknown) {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = capture(value, [\"binderHash\"]);\n\t\tif (!c?.enabled || !i || !isHash(i.binderHash))\n\t\t\treturn { kind: \"rejected\" as const, error: \"auth_config_changed\" as const };\n\t\tconst a = await this.first<ChangeRow>(\n\t\t\tsql(`SELECT * FROM ${table} WHERE coordinator_id = ? AND binder_hash = ?`, [\n\t\t\t\tc.coordinatorId,\n\t\t\t\ti.binderHash,\n\t\t\t]),\n\t\t);\n\t\tif (!a) return { kind: \"inactive\" as const };\n\t\tif (a.issuer !== c.issuer || a.auth_config_revision !== c.revision)\n\t\t\treturn { kind: \"rejected\" as const, error: \"auth_config_changed\" as const };\n\t\tif (\n\t\t\t[\"completed\", \"cancelled\", \"failed\", \"expired\"].includes(a.state) ||\n\t\t\ta.expires_at_ms <= authLinkNow(this.clock)\n\t\t)\n\t\t\treturn { kind: \"inactive\" as const };\n\t\treturn { kind: \"active\" as const };\n\t}\n\t/** Only the exact consumed exchange may report provider failure. */\n\tasync failConsumed(value: unknown, config: unknown): Promise<boolean> {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = browserPin(value);\n\t\tif (!c?.enabled || !i) return false;\n\t\treturn this.atomic([\n\t\t\tsql(\n\t\t\t\t`UPDATE ${table} AS a SET state = 'failed',failure_reason = 'provider_failure',${scrub} WHERE ${configured} AND ${browserMatch} AND a.state = 'consumed' AND a.expires_at_ms > ?`,\n\t\t\t\t[...configValues(c), i.attemptId, i.stateHash, i.binderHash, authLinkNow(this.clock)],\n\t\t\t),\n\t\t\tassertOne,\n\t\t]);\n\t}\n\t/** Coordinator-local maintenance; config rotation/disable must not retain staging. */\n\tasync maintainExpired(\n\t\tcoordinatorId: unknown,\n\t\tlimit: unknown = AUTH_LINK_EXPIRE_BATCH_MAX,\n\t): Promise<number> {\n\t\tif (\n\t\t\t!isAuthControllerId(coordinatorId) ||\n\t\t\ttypeof limit !== \"number\" ||\n\t\t\t!Number.isInteger(limit) ||\n\t\t\tlimit < 1 ||\n\t\t\tlimit > AUTH_LINK_EXPIRE_BATCH_MAX\n\t\t)\n\t\t\treturn 0;\n\t\tconst now = authLinkNow(this.clock);\n\t\treturn this.backend.run(\n\t\t\tsql(\n\t\t\t\t`UPDATE ${table} SET state = 'expired',failure_reason = 'expired',${scrub} WHERE coordinator_id = ? AND state IN ('pending','browser_pending','consumed','verified','confirmed') AND expires_at_ms <= ? AND attempt_id IN (SELECT attempt_id FROM ${table} WHERE coordinator_id = ? AND state IN ('pending','browser_pending','consumed','verified','confirmed') AND expires_at_ms <= ? ORDER BY expires_at_ms,attempt_id LIMIT ?)`,\n\t\t\t\t[coordinatorId, now, coordinatorId, now, limit],\n\t\t\t),\n\t\t);\n\t}\n}\n\n/** The device unlink receipt, its disconnect effects and its completion, after the guards. */\nfunction unlinkWrites(\n\tc: CoordinatorAuthLinkConfig,\n\ti: NonNullable<ReturnType<typeof unlinkInput>>,\n\tgrant: AccountChangeGrant,\n\tnow: number,\n): AuthLinkStatement[] {\n\treturn [\n\t\tsql(\n\t\t\t`INSERT INTO ${ACCOUNT_UNLINK_TABLE} (coordinator_id,attempt_id,target_link_id,identity_id,issuer,target_subject,group_id,device_id,public_key,fingerprint,enrollment_identity_id,auth_config_revision,request_hash,state,created_at_ms)\n VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,'committing',?)`,\n\t\t\t[\n\t\t\t\tgrant.coordinatorId,\n\t\t\t\ti.attemptId,\n\t\t\t\tgrant.linkId,\n\t\t\t\tgrant.identityId,\n\t\t\t\tgrant.issuer,\n\t\t\t\tgrant.subject,\n\t\t\t\t...signerValues(i.signer),\n\t\t\t\tgrant.enrollmentIdentityId,\n\t\t\t\tc.revision,\n\t\t\t\ti.requestHash,\n\t\t\t\tnow,\n\t\t\t],\n\t\t),\n\t\tassertOne,\n\t\t...disconnectEffects(c.coordinatorId, i.attemptId, now, { connections: true, device: true }),\n\t\tsql(\n\t\t\t`UPDATE ${ACCOUNT_UNLINK_TABLE} SET state='completed',completed_at_ms=? WHERE coordinator_id=? AND attempt_id=? AND state='committing'`,\n\t\t\t[now, c.coordinatorId, i.attemptId],\n\t\t),\n\t\tassertOne,\n\t];\n}\n\n/** The pending change attempt for the granted link, when the shared budgets admit it. */\nfunction createWrite(w: {\n\tc: CoordinatorAuthLinkConfig;\n\ti: Signed;\n\tintent: Intent;\n\tkey: string;\n\tgrant: AccountChangeGrant;\n\ttarget: AccountChangeTarget;\n\tnow: number;\n\tbrowserStartHash: string;\n\tloopbackRedirect: string;\n}): AuthLinkStatement {\n\tconst { c, i, grant, now } = w;\n\treturn sql(\n\t\t`INSERT INTO ${table}\n (coordinator_id,attempt_id,intent,target_link_id,identity_id,issuer,target_subject,group_id,device_id,public_key,fingerprint,key_id,enrollment_identity_id,auth_config_revision,runtime_verifier_hash,browser_start_hash,loopback_redirect,state,created_at_ms,expires_at_ms)\n SELECT ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'pending',?,? FROM ${admissionInput} p WHERE ${connectionAdmissionSql(\"p\")}`,\n\t\t[\n\t\t\tgrant.coordinatorId,\n\t\t\ti.attemptId,\n\t\t\tw.intent,\n\t\t\tgrant.linkId,\n\t\t\tgrant.identityId,\n\t\t\tgrant.issuer,\n\t\t\tgrant.subject,\n\t\t\t...signerValues(i.signer),\n\t\t\tw.key,\n\t\t\tgrant.enrollmentIdentityId,\n\t\t\tc.revision,\n\t\t\ti.runtimeVerifierHash,\n\t\t\tw.browserStartHash,\n\t\t\tw.loopbackRedirect,\n\t\t\tnow,\n\t\t\tnow + 600000,\n\t\t\t...admissionValues(c, i.signer, w.target, now),\n\t\t],\n\t);\n}\n\nfunction disconnectEffects(\n\tcoordinator: string,\n\tattempt: string,\n\tnow: number,\n\toptions: { connections: boolean; device?: boolean },\n): AuthLinkStatement[] {\n\tconst table = options.device ? ACCOUNT_UNLINK_TABLE : \"coordinator_account_change_attempts\";\n\tconst intent = options.device ? \"\" : \" AND a.intent = 'disconnect'\";\n\tconst columns = options.connections\n\t\t? [...CONNECTION_BIRTH_COLUMNS, \"signin_floor\"]\n\t\t: CONNECTION_BIRTH_COLUMNS;\n\tconst exactBirth = `${CONNECTION_ARCHIVED_CURRENT_MATCH_SQL}${options.connections ? \" AND h.signin_floor IS c.signin_floor\" : \"\"}`;\n\treturn [\n\t\tsql(\n\t\t\t`INSERT INTO ${history} (${columns.join(\",\")},original_rowid,ended_at_ms,end_attempt_id)\n SELECT ${columns.map((c) => `l.${c}`).join(\",\")},l.rowid,?,a.attempt_id FROM ${current} l JOIN ${table} a ON a.coordinator_id = l.coordinator_id AND a.target_link_id = l.link_id WHERE a.coordinator_id = ? AND a.attempt_id = ? AND a.state = 'committing'${intent}`,\n\t\t\t[now, coordinator, attempt],\n\t\t),\n\t\tassertOne,\n\t\tsql(\n\t\t\t`DELETE FROM ${current} AS c WHERE EXISTS (SELECT 1 FROM ${history} h WHERE h.coordinator_id = ? AND h.end_attempt_id = ? AND ${exactBirth})`,\n\t\t\t[coordinator, attempt],\n\t\t),\n\t\tassertOne,\n\t\tsql(\n\t\t\t`UPDATE coordinator_auth_sessions SET revoked_at_ms = ? WHERE coordinator_id = ? AND link_id = (SELECT target_link_id FROM ${table} WHERE coordinator_id = ? AND attempt_id = ?) AND revoked_at_ms IS NULL`,\n\t\t\t[now, coordinator, coordinator, attempt],\n\t\t),\n\t\tsql(\n\t\t\t`INSERT INTO ${orders} (coordinator_id,last_order) SELECT NULL,0 WHERE EXISTS (\n SELECT 1 FROM coordinator_auth_sessions s JOIN ${table} a ON a.coordinator_id = s.coordinator_id AND a.target_link_id = s.link_id\n WHERE a.coordinator_id = ? AND a.attempt_id = ? AND s.revoked_at_ms IS NULL)`,\n\t\t\t[coordinator, attempt],\n\t\t),\n\t\t...[\"coordinator_auth_account_profiles\", \"coordinator_auth_link_profiles\"].map((name) =>\n\t\t\tsql(\n\t\t\t\t`DELETE FROM ${name} WHERE coordinator_id = ? AND link_id = (SELECT target_link_id FROM ${table} WHERE coordinator_id = ? AND attempt_id = ?)`,\n\t\t\t\t[coordinator, coordinator, attempt],\n\t\t\t),\n\t\t),\n\t\tsql(\n\t\t\t`INSERT INTO ${orders} (coordinator_id,last_order) SELECT NULL,0 WHERE EXISTS (\n SELECT 1 FROM ${table} a WHERE a.coordinator_id = ? AND a.attempt_id = ? AND (\n EXISTS (SELECT 1 FROM coordinator_auth_account_profiles p WHERE p.coordinator_id = a.coordinator_id AND p.link_id = a.target_link_id)\n OR EXISTS (SELECT 1 FROM coordinator_auth_link_profiles p WHERE p.coordinator_id = a.coordinator_id AND p.link_id = a.target_link_id)))`,\n\t\t\t[coordinator, attempt],\n\t\t),\n\t];\n}\nfunction refreshEffects(coordinator: string, attempt: string): AuthLinkStatement[] {\n\t// Keep original birth metadata byte-for-byte; new provenance names the\n\t// management receipt. Never invent a session receipt or a fake birth attempt.\n\treturn [\n\t\tsql(\n\t\t\t`INSERT INTO coordinator_auth_link_profiles\n (coordinator_id,attempt_id,issuer,subject,auth_config_revision,browser_transaction_hash,link_id,verified_at_ms,display_name,email,email_verified,picture_url,source_change_attempt_id,source_order)\n SELECT l.coordinator_id,l.attempt_id,l.issuer,l.subject,l.auth_config_revision,b.browser_transaction_hash,l.link_id,b.oidc_verified_at_ms,a.display_name,a.email,a.email_verified,a.picture_url,a.attempt_id,a.browser_order\n FROM ${table} a JOIN ${current} l ON l.coordinator_id = a.coordinator_id AND l.link_id = a.target_link_id\n JOIN coordinator_auth_link_attempts b ON b.coordinator_id = l.coordinator_id AND b.attempt_id = l.attempt_id AND b.link_id = l.link_id\n WHERE a.coordinator_id = ? AND a.attempt_id = ? AND a.state = 'committing' AND a.intent = 'refresh'\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_profiles p WHERE p.coordinator_id = l.coordinator_id AND p.link_id = l.link_id AND p.source_order >= a.browser_order)\n ON CONFLICT(coordinator_id,link_id) DO UPDATE SET display_name = excluded.display_name,email = excluded.email,email_verified = excluded.email_verified,picture_url = excluded.picture_url,\n source_change_attempt_id = excluded.source_change_attempt_id,source_order = excluded.source_order\n WHERE coalesce(coordinator_auth_link_profiles.source_order,0) < excluded.source_order`,\n\t\t\t[coordinator, attempt],\n\t\t),\n\t\tsql(\n\t\t\t`INSERT INTO ${orders} (coordinator_id,last_order) SELECT NULL,0 WHERE changes() <> 1 AND NOT EXISTS (\n SELECT 1 FROM ${table} a WHERE a.coordinator_id = ? AND a.attempt_id = ? AND (\n EXISTS (SELECT 1 FROM coordinator_auth_link_profiles p WHERE p.coordinator_id = a.coordinator_id AND p.link_id = a.target_link_id AND p.source_order >= a.browser_order)\n OR EXISTS (SELECT 1 FROM coordinator_auth_account_profiles p WHERE p.coordinator_id = a.coordinator_id AND p.link_id = a.target_link_id AND p.source_order >= a.browser_order)))`,\n\t\t\t[coordinator, attempt],\n\t\t),\n\t];\n}\n","import type { CoordinatorAuthLinkConfig } from \"./coordinator-auth-link-contract.js\";\n\nexport const AUTH_BROWSER_TXN_TTL_MS = 600000;\nexport const AUTH_SIGNIN_TXN_WINDOW_MS = 3600000;\nexport const AUTH_SIGNIN_TXN_MAX_STARTS_PER_WINDOW = 1024;\nexport const AUTH_SIGNIN_TXN_MAX_RETAINED = 4096;\nexport const AUTH_BROWSER_TXN_MAINTENANCE_BATCH_MAX = 32;\nexport const AUTH_SIGNIN_TXN_PURGE_AGE_MS = 7200000;\nexport const AUTH_SIGNIN_TXN_PURGE_BATCH_MAX = 256;\n\nexport interface CoordinatorAuthBrowserConfig extends CoordinatorAuthLinkConfig {\n\tredirectUri: string;\n}\ninterface BrowserMaterials {\n\tstateHash: string;\n\tbinderHash: string;\n\tnonce: string;\n\tpkceVerifier: string;\n}\nexport type CoordinatorAuthBrowserTransactionStartInput = BrowserMaterials &\n\t({ purpose: \"signin\" } | { purpose: \"link\"; attemptId: string; browserStartHash?: string });\nexport interface CoordinatorAuthBrowserTransactionConsumeInput {\n\tstateHash: string;\n\tbinderHash: string;\n}\nexport type CoordinatorAuthBrowserTransactionPurpose = \"signin\" | \"link\" | \"owner_enroll\";\n/** Server-only routing hint, never authorization or consumption evidence. */\nexport interface CoordinatorAuthBrowserTransactionPurposeStore {\n\treadAuthBrowserTransactionPurpose(\n\t\tinput: CoordinatorAuthBrowserTransactionConsumeInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<CoordinatorAuthBrowserTransactionPurpose | null>;\n}\nexport interface CoordinatorAuthLinkBrowserTransactionResolveInput {\n\tattemptId: string;\n\tbinderHash: string;\n}\nexport type CoordinatorAuthBrowserTransactionError =\n\t| \"invalid_input\"\n\t| \"auth_config_changed\"\n\t| \"transaction_limited\"\n\t| \"transaction_conflict\"\n\t| \"attempt_unavailable\"\n\t| \"attempt_expired\"\n\t| \"transaction_unavailable\";\nexport interface CoordinatorAuthBrowserTransactionRejected {\n\tkind: \"rejected\";\n\terror: CoordinatorAuthBrowserTransactionError;\n}\nexport type CoordinatorAuthBrowserTransactionStartResult =\n\t| { kind: \"started\"; expiresAtMs: number }\n\t| { kind: \"rejected\"; error: \"clock_retention_blocked\" }\n\t| CoordinatorAuthBrowserTransactionRejected;\n/** Secrets are for the trusted SDK exchange caller only, never an HTTP or polling DTO. */\nexport type CoordinatorAuthBrowserTransactionConsumeResult =\n\t| ({ kind: \"consumed\"; browserTransactionHash: string; nonce: string; pkceVerifier: string } & (\n\t\t\t| { purpose: \"signin\" }\n\t\t\t| { purpose: \"link\"; attemptId: string }\n\t ))\n\t| CoordinatorAuthBrowserTransactionRejected;\nexport interface CoordinatorAuthBrowserTransactionScope {\n\tcoordinatorId: string;\n}\nexport interface CoordinatorAuthBrowserTransactionMaintenanceOptions {\n\tlimit?: number;\n}\nexport interface CoordinatorAuthSigninBrowserTransactionCancelInput {\n\tbinderHash: string;\n}\nexport type CoordinatorAuthSigninBrowserTransactionCancelResult =\n\t| { kind: \"cancelled\" }\n\t| { kind: \"unavailable\" }\n\t| { kind: \"rejected\"; error: \"invalid_input\" };\nexport interface CoordinatorAuthBrowserTransactionRetirementOptions {\n\t/** Omit unused options; explicit undefined values are rejected. */\n\tattemptId?: string;\n\tlimit?: number;\n}\nexport type CoordinatorAuthBrowserTransactionRetirementResult =\n\t| { kind: \"retired\"; processedCount: number; more: boolean }\n\t| { kind: \"rejected\"; error: \"invalid_input\" };\nexport type CoordinatorAuthBrowserTransactionMaintenanceResult =\n\t| { kind: \"maintained\"; processedCount: number; more: boolean }\n\t| { kind: \"rejected\"; error: \"invalid_input\" };\nexport type CoordinatorAuthSigninBrowserTransactionPurgeResult =\n\t| { kind: \"purged\"; processedCount: number; more: boolean }\n\t| { kind: \"rejected\"; error: \"invalid_input\" };\nexport interface CoordinatorAuthBrowserTransactionStore {\n\t/** Server-only binder lookup; never accepts a caller-selected attempt. */\n\treadAuthBrowserTransactionActivity(\n\t\tinput: { binderHash: string },\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<\n\t\t| { kind: \"active\" | \"inactive\" }\n\t\t| { kind: \"rejected\"; error: \"invalid_input\" | \"auth_config_changed\" }\n\t>;\n\tstartAuthBrowserTransaction(\n\t\tinput: CoordinatorAuthBrowserTransactionStartInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<CoordinatorAuthBrowserTransactionStartResult>;\n\tconsumeAuthBrowserTransaction(\n\t\tinput: CoordinatorAuthBrowserTransactionConsumeInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<CoordinatorAuthBrowserTransactionConsumeResult>;\n\tresolveAuthLinkBrowserTransaction(\n\t\tinput: CoordinatorAuthLinkBrowserTransactionResolveInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<{ browserTransactionHash: string } | null>;\n\tmaintainAuthBrowserTransactions(\n\t\tscope: CoordinatorAuthBrowserTransactionScope,\n\t\toptions?: CoordinatorAuthBrowserTransactionMaintenanceOptions,\n\t): Promise<CoordinatorAuthBrowserTransactionMaintenanceResult>;\n\tpurgeAuthSigninBrowserTransactions(\n\t\tscope: CoordinatorAuthBrowserTransactionScope,\n\t\toptions?: CoordinatorAuthBrowserTransactionMaintenanceOptions,\n\t): Promise<CoordinatorAuthSigninBrowserTransactionPurgeResult>;\n\tcancelAuthSigninBrowserTransaction(\n\t\tinput: CoordinatorAuthSigninBrowserTransactionCancelInput,\n\t\tscope: CoordinatorAuthBrowserTransactionScope,\n\t): Promise<CoordinatorAuthSigninBrowserTransactionCancelResult>;\n\tretireAuthBrowserTransactions(\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t\toptions?: CoordinatorAuthBrowserTransactionRetirementOptions,\n\t): Promise<CoordinatorAuthBrowserTransactionRetirementResult>;\n}\n\nexport const AUTH_BROWSER_TXN_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS coordinator_auth_browser_transactions (\n coordinator_id TEXT NOT NULL CHECK (length(coordinator_id) BETWEEN 1 AND 256),\n browser_transaction_hash TEXT NOT NULL CHECK (length(browser_transaction_hash) = 64 AND browser_transaction_hash NOT GLOB '*[^0-9a-f]*'),\n purpose TEXT NOT NULL CHECK (purpose IN ('signin','link','owner_enroll')),\n attempt_id TEXT CHECK (attempt_id IS NULL OR length(attempt_id) BETWEEN 1 AND 256),\n state_hash TEXT NOT NULL CHECK (length(state_hash) = 64 AND state_hash NOT GLOB '*[^0-9a-f]*'),\n binder_hash TEXT NOT NULL CHECK (length(binder_hash) = 64 AND binder_hash NOT GLOB '*[^0-9a-f]*'),\n issuer TEXT NOT NULL,\n auth_config_revision TEXT NOT NULL CHECK (length(auth_config_revision) = 64 AND auth_config_revision NOT GLOB '*[^0-9a-f]*'),\n redirect_uri TEXT NOT NULL,\n state TEXT NOT NULL CHECK (state IN ('pending','consumed','expired')),\n nonce TEXT CHECK (nonce IS NULL OR (length(nonce) BETWEEN 43 AND 128 AND nonce NOT GLOB '*[^A-Za-z0-9._~-]*')),\n pkce_verifier TEXT CHECK (pkce_verifier IS NULL OR (length(pkce_verifier) BETWEEN 43 AND 128 AND pkce_verifier NOT GLOB '*[^A-Za-z0-9._~-]*')),\n claim_token TEXT,\n created_at_ms INTEGER NOT NULL CHECK (typeof(created_at_ms) = 'integer' AND created_at_ms BETWEEN 0 AND 9007199254140991),\n expires_at_ms INTEGER NOT NULL CHECK (typeof(expires_at_ms) = 'integer' AND expires_at_ms > created_at_ms AND expires_at_ms <= created_at_ms + 600000),\n consumed_at_ms INTEGER CHECK (consumed_at_ms IS NULL OR (typeof(consumed_at_ms) = 'integer' AND consumed_at_ms >= created_at_ms AND consumed_at_ms < expires_at_ms AND consumed_at_ms <= 9007199254740991)),\n PRIMARY KEY (coordinator_id, browser_transaction_hash),\n UNIQUE (coordinator_id, state_hash),\n UNIQUE (coordinator_id, binder_hash),\n UNIQUE (coordinator_id, attempt_id),\n UNIQUE (coordinator_id, claim_token),\n CHECK ((purpose IN ('link','owner_enroll') AND attempt_id IS NOT NULL) OR (purpose = 'signin' AND attempt_id IS NULL)),\n CHECK ((state = 'pending' AND nonce IS NOT NULL AND pkce_verifier IS NOT NULL) OR (state <> 'pending' AND nonce IS NULL AND pkce_verifier IS NULL)),\n CHECK ((state = 'consumed' AND claim_token IS NOT NULL AND consumed_at_ms IS NOT NULL) OR (state <> 'consumed' AND claim_token IS NULL AND consumed_at_ms IS NULL))\n);\nCREATE INDEX IF NOT EXISTS idx_auth_browser_txn_purpose_created\n ON coordinator_auth_browser_transactions(coordinator_id, purpose, created_at_ms);\nCREATE INDEX IF NOT EXISTS idx_auth_browser_txn_state_expiry\n ON coordinator_auth_browser_transactions(coordinator_id, state, expires_at_ms);\nCREATE TABLE IF NOT EXISTS coordinator_auth_signin_purge_floors (\n coordinator_id TEXT NOT NULL PRIMARY KEY CHECK (length(coordinator_id) BETWEEN 1 AND 256),\n purged_through_created_at_ms INTEGER NOT NULL CHECK (typeof(purged_through_created_at_ms) = 'integer' AND purged_through_created_at_ms BETWEEN 0 AND 9007199254140991)\n);\n`;\n","import { AUTH_BROWSER_TXN_TTL_MS } from \"./coordinator-auth-browser-transaction-contract.js\";\nimport {\n\tdecodeCoordinatorAuthProof32 as decodeValue,\n\tencodeCoordinatorAuthProof32 as encodeBytes,\n\thashCoordinatorAuthProofBytes32,\n} from \"./coordinator-auth-proof.js\";\nimport { AUTH_SESSION_TTL_MS } from \"./coordinator-auth-session-contract.js\";\n\nexport type CookieKind = \"transaction\" | \"session\" | \"start\";\ndeclare const browserCookieSecretBrand: unique symbol;\nexport type BrowserCookieSecret = Readonly<{ [browserCookieSecretBrand]: true }>;\n\nexport const BROWSER_COOKIE_NAMES = Object.freeze({\n\ttransaction: \"__Host-codemem-auth-transaction\",\n\tsession: \"__Host-codemem-session\",\n\tstart: \"__Host-codemem-auth-start\",\n});\nexport const BROWSER_COOKIE_HEADER_MAX_BYTES = 8192;\nconst MAX_AGE_SECONDS = {\n\ttransaction: AUTH_BROWSER_TXN_TTL_MS / 1000,\n\tsession: AUTH_SESSION_TTL_MS / 1000,\n\tstart: AUTH_BROWSER_TXN_TTL_MS / 1000,\n};\nconst COOKIE_NAME = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\nconst COOKIE_VALUE =\n\t/^(?:[\\x21\\x23-\\x2B\\x2D-\\x3A\\x3C-\\x5B\\x5D-\\x7E]*|\"[\\x21\\x23-\\x2B\\x2D-\\x3A\\x3C-\\x5B\\x5D-\\x7E]*\")$/;\ntype CookieMaterial = Readonly<{\n\tkind: CookieKind;\n\tbytes: Uint8Array<ArrayBuffer>;\n\tencoded: string;\n}>;\nconst secrets = new WeakMap<BrowserCookieSecret, CookieMaterial>();\ntype InvalidCookie = { kind: \"invalid\"; error: \"cookie_duplicate\" | \"cookie_malformed\" };\nexport type BrowserCookieReadResult =\n\t| { kind: \"absent\" }\n\t| InvalidCookie\n\t| { kind: \"present\"; secret: BrowserCookieSecret; cookieHash: string };\n\nfunction validateKind(kind: CookieKind): void {\n\tif (kind !== \"transaction\" && kind !== \"session\" && kind !== \"start\") {\n\t\tthrow new Error(\"auth_browser_credential_invalid_input\");\n\t}\n}\n\nasync function hashBytes(bytes: Uint8Array<ArrayBuffer>): Promise<string> {\n\ttry {\n\t\treturn await hashCoordinatorAuthProofBytes32(bytes);\n\t} catch {\n\t\tthrow new Error(\"auth_browser_credential_crypto_failed\");\n\t}\n}\n\nfunction createSecret(material: CookieMaterial): BrowserCookieSecret {\n\tconst secret = Object.freeze({}) as BrowserCookieSecret;\n\tsecrets.set(secret, Object.freeze(material));\n\treturn secret;\n}\n\nfunction cookieHeader(kind: CookieKind, value: string, maxAge: number): string {\n\treturn `${BROWSER_COOKIE_NAMES[kind]}=${value}; Max-Age=${maxAge}; Path=/; Secure; HttpOnly; SameSite=Lax`;\n}\n\nexport async function issueBrowserCookie(\n\tkind: CookieKind,\n): Promise<{ secret: BrowserCookieSecret; cookieHash: string; setCookie: string }> {\n\tvalidateKind(kind);\n\tlet bytes: Uint8Array<ArrayBuffer>;\n\ttry {\n\t\tbytes = new Uint8Array(32);\n\t\tglobalThis.crypto.getRandomValues(bytes);\n\t} catch {\n\t\tthrow new Error(\"auth_browser_credential_entropy_failed\");\n\t}\n\tconst cookieHash = await hashBytes(bytes);\n\tconst encoded = encodeBytes(bytes);\n\treturn {\n\t\tsecret: createSecret({ kind, bytes, encoded }),\n\t\tcookieHash,\n\t\tsetCookie: cookieHeader(kind, encoded, MAX_AGE_SECONDS[kind]),\n\t};\n}\n\nexport function clearBrowserCookie(kind: CookieKind): string {\n\tvalidateKind(kind);\n\treturn cookieHeader(kind, \"\", 0);\n}\n\n/** Internal credential access only: never send this value through JSON or logs. */\nexport function browserCookieValue(secret: BrowserCookieSecret, expectedKind: CookieKind): string {\n\tvalidateKind(expectedKind);\n\tconst material = secrets.get(secret);\n\tif (!material || material.kind !== expectedKind) {\n\t\tthrow new Error(\"auth_browser_credential_invalid_input\");\n\t}\n\treturn material.encoded;\n}\n\n/**\n * Same-value header promotion only; the secret remains start-kind. Append only after\n * Origin/CSRF checks and durable unique-binder admission commit. No one-shot or\n * freshness proof: Max-Age is a browser hint, not server-side expiry enforcement.\n */\nexport function reissueStartCookieAsTransaction(secret: BrowserCookieSecret): string {\n\treturn cookieHeader(\n\t\t\"transaction\",\n\t\tbrowserCookieValue(secret, \"start\"),\n\t\tMAX_AGE_SECONDS.transaction,\n\t);\n}\n\nfunction trimOws(value: string): string {\n\tlet start = 0;\n\tlet end = value.length;\n\twhile (start < end && (value[start] === \" \" || value[start] === \"\\t\")) start++;\n\twhile (end > start && (value[end - 1] === \" \" || value[end - 1] === \"\\t\")) end--;\n\treturn value.slice(start, end);\n}\n\nfunction isValidHeader(header: string): boolean {\n\tif (header.length > BROWSER_COOKIE_HEADER_MAX_BYTES) return false;\n\tfor (const character of header) {\n\t\tconst code = character.charCodeAt(0);\n\t\tif (code === 9) continue;\n\t\tif (code < 32 || code > 126 || code === 44) return false;\n\t}\n\treturn true;\n}\n\nfunction knownCookieKind(name: string): CookieKind | undefined {\n\tconst lowerName = name.toLowerCase();\n\tif (lowerName === BROWSER_COOKIE_NAMES.transaction.toLowerCase()) return \"transaction\";\n\tif (lowerName === BROWSER_COOKIE_NAMES.session.toLowerCase()) return \"session\";\n\tif (lowerName === BROWSER_COOKIE_NAMES.start.toLowerCase()) return \"start\";\n\treturn undefined;\n}\n\nfunction parseCookies(header: string): Map<CookieKind, CookieMaterial> | InvalidCookie {\n\tconst cookies = new Map<CookieKind, CookieMaterial>();\n\tfor (const segment of header.split(\";\")) {\n\t\tconst pair = trimOws(segment);\n\t\tconst separator = pair.indexOf(\"=\");\n\t\tif (separator < 1) return { kind: \"invalid\", error: \"cookie_malformed\" };\n\t\tconst name = pair.slice(0, separator);\n\t\tconst encoded = pair.slice(separator + 1);\n\t\tif (!COOKIE_NAME.test(name) || !COOKIE_VALUE.test(encoded)) {\n\t\t\treturn { kind: \"invalid\", error: \"cookie_malformed\" };\n\t\t}\n\t\tconst kind = knownCookieKind(name);\n\t\tif (!kind) continue;\n\t\tif (cookies.has(kind)) return { kind: \"invalid\", error: \"cookie_duplicate\" };\n\t\tif (name !== BROWSER_COOKIE_NAMES[kind]) {\n\t\t\treturn { kind: \"invalid\", error: \"cookie_malformed\" };\n\t\t}\n\t\tconst bytes = decodeValue(encoded);\n\t\tif (!bytes) return { kind: \"invalid\", error: \"cookie_malformed\" };\n\t\tcookies.set(kind, { kind, bytes, encoded });\n\t}\n\treturn cookies;\n}\n\n/** A present cookie is not authentication; callers must look up its hash in the store. */\nexport async function readBrowserCookie(\n\tcookieHeader: unknown,\n\tkind: CookieKind,\n): Promise<BrowserCookieReadResult> {\n\tvalidateKind(kind);\n\tif (cookieHeader === null || cookieHeader === undefined) return { kind: \"absent\" };\n\tif (typeof cookieHeader !== \"string\") return { kind: \"invalid\", error: \"cookie_malformed\" };\n\t// For this ASCII-only header, string length is also its byte count.\n\tif (!isValidHeader(cookieHeader)) {\n\t\treturn { kind: \"invalid\", error: \"cookie_malformed\" };\n\t}\n\tif (!trimOws(cookieHeader)) return { kind: \"absent\" };\n\tconst cookies = parseCookies(cookieHeader);\n\tif (!(cookies instanceof Map)) return cookies;\n\tconst material = cookies.get(kind);\n\tif (!material) return { kind: \"absent\" };\n\tconst cookieHash = await hashBytes(material.bytes);\n\treturn { kind: \"present\", secret: createSecret(material), cookieHash };\n}\n","import type { CoordinatorAuthBrowserConfig } from \"./coordinator-auth-browser-transaction-contract.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport {\n\ttype BrowserCookieSecret,\n\tbrowserCookieValue,\n\ttype CookieKind,\n} from \"./coordinator-browser-credential.js\";\n\ndeclare const browserCsrfKeyBrand: unique symbol;\nexport type BrowserCsrfKey = Readonly<{ [browserCsrfKeyBrand]: true }>;\nexport interface BrowserCsrfScope {\n\tpublicOrigin: string;\n\tstore: Pick<CoordinatorAuthBrowserConfig, \"coordinatorId\" | \"revision\">;\n}\n\ntype CryptoKey = Awaited<ReturnType<typeof globalThis.crypto.subtle.importKey>>;\nconst keys = new WeakMap<BrowserCsrfKey, CryptoKey>();\nexport function isBrowserCsrfKey(value: unknown): value is BrowserCsrfKey {\n\treturn typeof value === \"object\" && value !== null && keys.has(value as BrowserCsrfKey);\n}\nconst TOKEN_PATTERN = /^[A-Za-z0-9_-]{85}[AQgw]$/;\nconst typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);\nconst typedArrayTag = Object.getOwnPropertyDescriptor(typedArrayPrototype, Symbol.toStringTag)?.get;\nconst typedArrayByteLength = Object.getOwnPropertyDescriptor(\n\ttypedArrayPrototype,\n\t\"byteLength\",\n)?.get;\n\nfunction invalidInput(): Error {\n\treturn new Error(\"auth_browser_csrf_invalid_input\");\n}\n\nfunction copyKeyBytes(raw: Uint8Array): Uint8Array<ArrayBuffer> {\n\tif (typedArrayTag?.call(raw) !== \"Uint8Array\" || typedArrayByteLength?.call(raw) !== 32) {\n\t\tthrow invalidInput();\n\t}\n\tconst copy = new Uint8Array(32);\n\tUint8Array.prototype.set.call(copy, raw);\n\treturn copy;\n}\n\nasync function importCopiedKey(bytes: Uint8Array<ArrayBuffer>): Promise<BrowserCsrfKey> {\n\ttry {\n\t\tconst cryptoKey = await globalThis.crypto.subtle.importKey(\n\t\t\t\"raw\",\n\t\t\tbytes,\n\t\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n\t\t\tfalse,\n\t\t\t[\"sign\", \"verify\"],\n\t\t);\n\t\tconst key = Object.freeze({}) as BrowserCsrfKey;\n\t\tkeys.set(key, cryptoKey);\n\t\treturn key;\n\t} catch {\n\t\tthrow new Error(\"auth_browser_csrf_crypto_failed\");\n\t}\n}\n\nexport function importBrowserCsrfKey(raw: Uint8Array): Promise<BrowserCsrfKey> {\n\tlet bytes: Uint8Array<ArrayBuffer>;\n\ttry {\n\t\tbytes = copyKeyBytes(raw);\n\t} catch {\n\t\treturn Promise.reject(invalidInput());\n\t}\n\t// Only the owned copy crosses the asynchronous boundary.\n\treturn importCopiedKey(bytes);\n}\n\nfunction ownData(value: unknown, name: string): unknown {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) throw invalidInput();\n\tconst descriptor = Object.getOwnPropertyDescriptor(value, name);\n\tif (!descriptor || !Object.hasOwn(descriptor, \"value\")) throw invalidInput();\n\treturn descriptor.value;\n}\n\nfunction validOrigin(value: unknown): value is string {\n\tif (typeof value !== \"string\" || /[\\\\\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(value)) return false;\n\tconst url = new URL(value);\n\treturn url.protocol === \"https:\" && url.origin === value && !url.username && !url.password;\n}\n\nfunction captureMessageFields(\n\tkey: BrowserCsrfKey,\n\tsecret: BrowserCookieSecret,\n\tpurpose: CookieKind,\n\tscope: BrowserCsrfScope,\n): { cryptoKey: CryptoKey; fields: string[] } {\n\ttry {\n\t\tconst cryptoKey = keys.get(key);\n\t\tif (!cryptoKey || (purpose !== \"transaction\" && purpose !== \"session\" && purpose !== \"start\")) {\n\t\t\tthrow invalidInput();\n\t\t}\n\t\tconst publicOrigin = ownData(scope, \"publicOrigin\");\n\t\tconst store = ownData(scope, \"store\");\n\t\tconst coordinatorId = ownData(store, \"coordinatorId\");\n\t\tconst revision = ownData(store, \"revision\");\n\t\tif (\n\t\t\t!validOrigin(publicOrigin) ||\n\t\t\t!isAuthControllerId(coordinatorId) ||\n\t\t\ttypeof revision !== \"string\" ||\n\t\t\trevision.length !== 64 ||\n\t\t\t!/^[a-f0-9]{64}$/.test(revision)\n\t\t) {\n\t\t\tthrow invalidInput();\n\t\t}\n\t\tconst encodedCookie = browserCookieValue(secret, purpose);\n\t\treturn {\n\t\t\tcryptoKey,\n\t\t\tfields: [\n\t\t\t\t\"codemem-browser-csrf-v1\",\n\t\t\t\tpurpose,\n\t\t\t\tcoordinatorId,\n\t\t\t\tpublicOrigin,\n\t\t\t\trevision,\n\t\t\t\tencodedCookie,\n\t\t\t],\n\t\t};\n\t} catch {\n\t\tthrow invalidInput();\n\t}\n}\n\nfunction encodeBytes(bytes: Uint8Array<ArrayBuffer>): string {\n\treturn btoa(String.fromCharCode(...bytes))\n\t\t.replaceAll(\"+\", \"-\")\n\t\t.replaceAll(\"/\", \"_\")\n\t\t.replace(/=+$/, \"\");\n}\n\nfunction decodeToken(value: unknown): Uint8Array<ArrayBuffer> | null {\n\tif (typeof value !== \"string\" || value.length !== 86 || !TOKEN_PATTERN.test(value)) return null;\n\ttry {\n\t\tconst binary = atob(`${value.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\")}==`);\n\t\tconst bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));\n\t\tif (bytes.length !== 64 || encodeBytes(bytes) !== value) return null;\n\t\treturn bytes;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Shape only: this does not authenticate the token or its browser session. */\nexport function isBrowserCsrfToken(value: unknown): value is string {\n\treturn decodeToken(value) !== null;\n}\n\nfunction messageBytes(fields: string[], nonce: Uint8Array<ArrayBuffer>): Uint8Array<ArrayBuffer> {\n\treturn new TextEncoder().encode(JSON.stringify([...fields, encodeBytes(nonce)]));\n}\n\nexport async function issueBrowserCsrfToken(\n\tkey: BrowserCsrfKey,\n\tsecret: BrowserCookieSecret,\n\tpurpose: CookieKind,\n\tscope: BrowserCsrfScope,\n): Promise<string> {\n\tconst { cryptoKey, fields } = captureMessageFields(key, secret, purpose, scope);\n\tconst nonce = new Uint8Array(32);\n\ttry {\n\t\tglobalThis.crypto.getRandomValues(nonce);\n\t} catch {\n\t\tthrow new Error(\"auth_browser_csrf_entropy_failed\");\n\t}\n\ttry {\n\t\tconst signature = await globalThis.crypto.subtle.sign(\n\t\t\t\"HMAC\",\n\t\t\tcryptoKey,\n\t\t\tmessageBytes(fields, nonce),\n\t\t);\n\t\tconst signatureLength = Object.getOwnPropertyDescriptor(\n\t\t\tArrayBuffer.prototype,\n\t\t\t\"byteLength\",\n\t\t)?.get;\n\t\tif (signatureLength?.call(signature) !== 32) throw new Error(\"auth_browser_csrf_crypto_failed\");\n\t\tconst mac = new Uint8Array(signature);\n\t\tif (mac.length !== 32) throw new Error(\"auth_browser_csrf_crypto_failed\");\n\t\tconst token = new Uint8Array(64);\n\t\ttoken.set(mac);\n\t\ttoken.set(nonce, 32);\n\t\treturn encodeBytes(token);\n\t} catch {\n\t\tthrow new Error(\"auth_browser_csrf_crypto_failed\");\n\t}\n}\n\n/**\n * A separate HMAC key for another purpose, derived from the CSRF key so no new\n * secret is needed. CSRF messages are JSON arrays, so a label that does not\n * start with \"[\" can never sign the same bytes as a token. Rotating the CSRF\n * key changes every derived key.\n */\nexport async function deriveBrowserCsrfSubkey(\n\tkey: BrowserCsrfKey,\n\tlabel: string,\n): Promise<CryptoKey> {\n\tconst cryptoKey = keys.get(key);\n\tif (!cryptoKey || !/^[a-z0-9][a-z0-9:-]{7,127}$/.test(label)) throw invalidInput();\n\tconst bytes = await globalThis.crypto.subtle.sign(\n\t\t\"HMAC\",\n\t\tcryptoKey,\n\t\tnew TextEncoder().encode(label),\n\t);\n\treturn globalThis.crypto.subtle.importKey(\n\t\t\"raw\",\n\t\tbytes,\n\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n\t\tfalse,\n\t\t[\"sign\"],\n\t);\n}\n\n/** Callers must also require a live store lookup before protecting an authenticated action. */\nexport async function verifyBrowserCsrfToken(\n\tkey: BrowserCsrfKey,\n\tsecret: BrowserCookieSecret,\n\tpurpose: CookieKind,\n\tscope: BrowserCsrfScope,\n\ttoken: unknown,\n): Promise<boolean> {\n\ttry {\n\t\tconst payload = decodeToken(token);\n\t\tif (!payload) return false;\n\t\tconst { cryptoKey, fields } = captureMessageFields(key, secret, purpose, scope);\n\t\treturn await globalThis.crypto.subtle.verify(\n\t\t\t\"HMAC\",\n\t\t\tcryptoKey,\n\t\t\tpayload.slice(0, 32),\n\t\t\tmessageBytes(fields, payload.slice(32)),\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n","import { COORDINATOR_AUTH_STYLE as STYLE } from \"./coordinator-auth-browser-style.js\";\nimport { isCoordinatorAccountIssuer } from \"./coordinator-auth-contract.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport { parseCoordinatorAuthLoopback } from \"./coordinator-auth-loopback.js\";\nimport { decodeCoordinatorAuthProof32 } from \"./coordinator-auth-proof.js\";\nimport { isBrowserCsrfToken } from \"./coordinator-browser-csrf.js\";\n\nexport const AUTH_BROWSER_FORM_ACTIONS = Object.freeze({\n\tsignIn: \"/auth/sign-in\",\n\tstartLink: \"/auth/link/start\",\n\tconfirmLink: \"/auth/link/confirm\",\n\tcancelLink: \"/auth/link/cancel\",\n\tcompleteLink: \"/auth/link/complete\",\n\tsignOut: \"/auth/logout\",\n});\n\n// A conservative client policy, not a provider guarantee about picture hosts.\nexport const AUTH_BROWSER_AVATAR_HOSTS = Object.freeze({\n\t\"https://accounts.google.com\": Object.freeze([\"lh3.googleusercontent.com\"]),\n});\n\nexport interface CoordinatorAccountProfileView {\n\ttitle: string;\n\temail?: string;\n\temailNote?: string;\n\tpictureUrl?: string;\n\tinitials: string;\n}\n\nexport interface CoordinatorAuthBrowserEntity {\n\tid: string;\n\tlabel?: string;\n}\n\nexport interface CoordinatorAuthLinkConfirmPageInput {\n\tprofile?: unknown;\n\tissuer: string;\n\tidentity: CoordinatorAuthBrowserEntity;\n\tdevice: CoordinatorAuthBrowserEntity;\n\tgroup?: CoordinatorAuthBrowserEntity;\n\tattemptId: string;\n\tcsrfToken: string;\n}\n\nexport interface CoordinatorAuthCurrentAccountPageInput {\n\tprofile?: unknown;\n\tissuer: string;\n\tidentity: CoordinatorAuthBrowserEntity;\n\tcsrfToken: string;\n}\n\nexport interface CoordinatorAuthSigninPageInput {\n\tcsrfToken: string;\n}\n\nexport interface CoordinatorAuthLinkStartPageInput {\n\tattemptId: string;\n\tstartCode: string;\n\tcsrfToken: string;\n}\n\nexport interface CoordinatorAuthSigninContinuePageInput {\n\tauthorizationUrl: string;\n}\n\nexport type CoordinatorAuthLinkCompletionPageInput =\n\t| { attemptId: string; state: \"waiting\" }\n\t| { attemptId: string; state: \"ready\"; csrfToken: string };\n\nexport interface CoordinatorAuthLinkCompletionHopPageInput {\n\tdestination: string;\n\tattemptId: string;\n\tcompletionSecret: string;\n}\n\nexport interface CoordinatorAuthBrowserPage {\n\tbody: string;\n\theaders: Record<string, string>;\n}\n\nconst GOOGLE_ISSUER = \"https://accounts.google.com\";\nconst INVALID_INPUT = \"auth_browser_view_invalid_input\";\nconst CONTROLS = /[\\p{Cc}\\p{Cf}\\p{Cs}]/u;\nconst SENSITIVE_AUTHORIZATION_KEYS = new Set([\n\t\"code\",\n\t\"code_verifier\",\n\t\"client_secret\",\n\t\"access_token\",\n\t\"refresh_token\",\n\t\"id_token\",\n]);\nconst START_SUBMIT_SCRIPT = \"document.querySelector('form').requestSubmit();\";\n\nfunction invalidInput(): never {\n\tthrow new Error(INVALID_INPUT);\n}\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (prototype !== Object.prototype && prototype !== null) return undefined;\n\treturn value as Record<string, unknown>;\n}\n\nfunction ownData(\n\tvalue: Record<string, unknown>,\n\tkey: string,\n\toptions: { rejectAccessor?: boolean } = {},\n): unknown {\n\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\tif (!descriptor) return undefined;\n\tif (!Object.hasOwn(descriptor, \"value\")) {\n\t\tif (options.rejectAccessor) invalidInput();\n\t\treturn undefined;\n\t}\n\treturn descriptor.value;\n}\n\nfunction displayText(value: unknown, limit: number): string | undefined {\n\tif (typeof value !== \"string\" || value.length > limit || CONTROLS.test(value)) return undefined;\n\tif (!value || value !== value.trim()) return undefined;\n\treturn value;\n}\n\nfunction capturePageField(input: unknown, key: string): unknown {\n\ttry {\n\t\tconst data = record(input);\n\t\tif (!data) return invalidInput();\n\t\treturn ownData(data, key, { rejectAccessor: true });\n\t} catch {\n\t\treturn invalidInput();\n\t}\n}\n\nfunction captureSigninCsrf(input: unknown): string {\n\tconst csrfToken = capturePageField(input, \"csrfToken\");\n\t// Shape validation only; the controller verifies the token before starting sign-in.\n\tif (!isBrowserCsrfToken(csrfToken)) return invalidInput();\n\treturn csrfToken;\n}\n\nfunction captureAuthorizationUrl(input: unknown): string {\n\ttry {\n\t\tconst text = displayText(capturePageField(input, \"authorizationUrl\"), 8192);\n\t\tif (!text || text.includes(\"\\\\\") || text.includes(\"#\")) return invalidInput();\n\t\tconst url = new URL(text);\n\t\tif (\n\t\t\turl.href !== text ||\n\t\t\turl.protocol !== \"https:\" ||\n\t\t\turl.origin !== GOOGLE_ISSUER ||\n\t\t\turl.username ||\n\t\t\turl.password ||\n\t\t\turl.port ||\n\t\t\turl.hash\n\t\t)\n\t\t\treturn invalidInput();\n\t\tfor (const name of url.searchParams.keys()) {\n\t\t\tif (SENSITIVE_AUTHORIZATION_KEYS.has(name.toLowerCase())) return invalidInput();\n\t\t}\n\t\treturn text;\n\t} catch {\n\t\treturn invalidInput();\n\t}\n}\n\nfunction pictureUrl(value: unknown, issuer: string): string | undefined {\n\tconst text = displayText(value, 2048);\n\tif (!text || issuer !== GOOGLE_ISSUER || text.includes(\"\\\\\") || text.includes(\"#\")) return;\n\ttry {\n\t\tconst url = new URL(text);\n\t\tif (\n\t\t\turl.protocol !== \"https:\" ||\n\t\t\turl.username ||\n\t\t\turl.password ||\n\t\t\turl.port ||\n\t\t\t!AUTH_BROWSER_AVATAR_HOSTS[GOOGLE_ISSUER].includes(url.hostname)\n\t\t)\n\t\t\treturn;\n\t\treturn url.href;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction initialsFor(name: string | undefined): string {\n\tif (!name) return \"\";\n\tconst words = name.split(/\\s+/u);\n\tconst chosen = words.length > 1 ? [words[0], words[words.length - 1]] : [words[0]];\n\tconst segmenter = new Intl.Segmenter(\"en\", { granularity: \"grapheme\" });\n\tconst initials: string[] = [];\n\tfor (const word of chosen) {\n\t\tif (!word) continue;\n\t\tconst grapheme = segmenter.segment(word)[Symbol.iterator]().next().value?.segment;\n\t\tif (!grapheme || !/^[\\p{L}\\p{N}]/u.test(grapheme) || [...grapheme].length > 4) continue;\n\t\tconst upper = grapheme.toUpperCase();\n\t\tconst segments = [...segmenter.segment(upper)];\n\t\tif (segments.length !== 1 || [...upper].length > 4 || CONTROLS.test(upper)) continue;\n\t\tinitials.push(upper);\n\t}\n\treturn initials.join(\"\");\n}\n\n/** Presentation metadata only; names and email never confer account authority. */\nexport function projectAccountProfileView(\n\tprofile: unknown,\n\tissuer: string,\n): CoordinatorAccountProfileView {\n\tconst fallback = issuer === GOOGLE_ISSUER ? \"Google account\" : \"Linked account\";\n\ttry {\n\t\tconst data = record(profile);\n\t\tif (!data) return { title: fallback, initials: \"\" };\n\t\tconst name = displayText(ownData(data, \"displayName\"), 256);\n\t\tconst email = displayText(ownData(data, \"email\"), 320);\n\t\tconst view: CoordinatorAccountProfileView = {\n\t\t\ttitle: name ?? email ?? fallback,\n\t\t\tinitials: initialsFor(name),\n\t\t};\n\t\tif (email) {\n\t\t\tview.email = email;\n\t\t\tif (ownData(data, \"emailVerified\") !== true)\n\t\t\t\tview.emailNote = \"Email not verified by provider\";\n\t\t}\n\t\tconst picture = pictureUrl(ownData(data, \"pictureUrl\"), issuer);\n\t\tif (picture) view.pictureUrl = picture;\n\t\treturn view;\n\t} catch {\n\t\treturn { title: fallback, initials: \"\" };\n\t}\n}\n\nexport function escapeHtml(value: string): string {\n\treturn value\n\t\t.replace(/&/g, \"&\")\n\t\t.replace(/</g, \"<\")\n\t\t.replace(/>/g, \">\")\n\t\t.replace(/\"/g, \""\")\n\t\t.replace(/'/g, \"'\");\n}\n\nfunction entity(value: unknown, fallback: string): CoordinatorAuthBrowserEntity {\n\tconst data = record(value);\n\tif (!data) return invalidInput();\n\tconst id = ownData(data, \"id\", { rejectAccessor: true });\n\tif (!isAuthControllerId(id)) return invalidInput();\n\treturn {\n\t\tid,\n\t\tlabel: displayText(ownData(data, \"label\", { rejectAccessor: true }), 256) ?? fallback,\n\t};\n}\n\nfunction capture(input: unknown): {\n\tdata: Record<string, unknown>;\n\tissuer: string;\n\tidentity: CoordinatorAuthBrowserEntity;\n\tcsrfToken: string;\n\tprofile: CoordinatorAccountProfileView;\n} {\n\ttry {\n\t\tconst data = record(input);\n\t\tif (!data) return invalidInput();\n\t\tconst issuer = ownData(data, \"issuer\", { rejectAccessor: true });\n\t\tconst csrfToken = ownData(data, \"csrfToken\", { rejectAccessor: true });\n\t\tif (!isCoordinatorAccountIssuer(issuer) || !isBrowserCsrfToken(csrfToken))\n\t\t\treturn invalidInput();\n\t\treturn {\n\t\t\tdata,\n\t\t\tissuer,\n\t\t\tcsrfToken,\n\t\t\tidentity: entity(ownData(data, \"identity\", { rejectAccessor: true }), \"Identity\"),\n\t\t\tprofile: projectAccountProfileView(\n\t\t\t\townData(data, \"profile\", { rejectAccessor: true }),\n\t\t\t\tissuer,\n\t\t\t),\n\t\t};\n\t} catch {\n\t\treturn invalidInput();\n\t}\n}\n\nexport function profileMarkup(profile: CoordinatorAccountProfileView): string {\n\tlet image = \"\";\n\tif (profile.pictureUrl)\n\t\timage = `<img src=\"${escapeHtml(profile.pictureUrl)}\" alt=\"\" referrerpolicy=\"no-referrer\" loading=\"lazy\" decoding=\"async\">`;\n\tlet details = \"\";\n\tif (profile.email) details += `<p>${escapeHtml(profile.email)}</p>`;\n\tif (profile.emailNote) details += `<p class=\"note\">${escapeHtml(profile.emailNote)}</p>`;\n\treturn `<section class=\"profile\" aria-label=\"Account profile\"><span class=\"avatar\"><span class=\"initials\" aria-hidden=\"true\">${escapeHtml(profile.initials)}</span>${image}</span><div class=\"profile-text\"><h2>${escapeHtml(profile.title)}</h2>${details}</div></section>`;\n}\n\nexport function entityMarkup(value: CoordinatorAuthBrowserEntity, heading: string): string {\n\treturn `<dt>${escapeHtml(heading)}</dt><dd>${escapeHtml(value.label ?? heading)}<br><code>${escapeHtml(value.id)}</code></dd>`;\n}\n\nexport function form(\n\taction: string,\n\tcsrf: string,\n\tlabel: string,\n\toptions: { attemptId?: string; startCode?: string; secondary?: boolean } = {},\n): string {\n\tlet fields = `<input type=\"hidden\" name=\"csrf\" value=\"${escapeHtml(csrf)}\">`;\n\tif (options.attemptId)\n\t\tfields += `<input type=\"hidden\" name=\"attempt_id\" value=\"${escapeHtml(options.attemptId)}\">`;\n\tif (options.startCode)\n\t\tfields += `<input type=\"hidden\" name=\"start_code\" value=\"${escapeHtml(options.startCode)}\">`;\n\tconst className = options.secondary ? ' class=\"secondary\"' : \"\";\n\treturn `<form method=\"post\" action=\"${escapeHtml(action)}\">${fields}<button type=\"submit\"${className}>${escapeHtml(label)}</button></form>`;\n}\n\nexport async function buildPage(\n\ttitle: string,\n\tcontent: string,\n\tissuer?: string,\n\toptions: {\n\t\treferrerPolicy?: \"no-referrer\" | \"same-origin\";\n\t\trefreshUrl?: string;\n\t\tautoSubmit?: boolean;\n\t} = {},\n): Promise<CoordinatorAuthBrowserPage> {\n\ttry {\n\t\tconst digest = await globalThis.crypto.subtle.digest(\n\t\t\t\"SHA-256\",\n\t\t\tnew TextEncoder().encode(STYLE),\n\t\t);\n\t\tconst hash = btoa(String.fromCharCode(...new Uint8Array(digest)));\n\t\tlet script = \"\";\n\t\tlet scriptPolicy = \"\";\n\t\tif (options.autoSubmit) {\n\t\t\tconst scriptDigest = await globalThis.crypto.subtle.digest(\n\t\t\t\t\"SHA-256\",\n\t\t\t\tnew TextEncoder().encode(START_SUBMIT_SCRIPT),\n\t\t\t);\n\t\t\tconst scriptHash = btoa(String.fromCharCode(...new Uint8Array(scriptDigest)));\n\t\t\tscript = `<script>${START_SUBMIT_SCRIPT}</script>`;\n\t\t\tscriptPolicy = `; script-src 'sha256-${scriptHash}'`;\n\t\t}\n\t\tconst refresh = options.refreshUrl\n\t\t\t? `<meta http-equiv=\"refresh\" content=\"0;url=${escapeHtml(options.refreshUrl)}\">`\n\t\t\t: \"\";\n\t\tlet images = \"'none'\";\n\t\tif (issuer === GOOGLE_ISSUER)\n\t\t\timages = AUTH_BROWSER_AVATAR_HOSTS[GOOGLE_ISSUER].map((host) => `https://${host}`).join(\" \");\n\t\treturn {\n\t\t\tbody: `<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><meta name=\"referrer\" content=\"${options.referrerPolicy ?? \"no-referrer\"}\">${refresh}<title>${escapeHtml(title)} · Codemem</title><style>${STYLE}</style></head><body><main><p class=\"brand\">codemem</p>${content}</main>${script}</body></html>`,\n\t\t\theaders: {\n\t\t\t\t\"Content-Type\": \"text/html;charset=utf-8\",\n\t\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\t\"Referrer-Policy\": options.referrerPolicy ?? \"no-referrer\",\n\t\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\t\t\"X-Frame-Options\": \"DENY\",\n\t\t\t\t\"Content-Security-Policy\": `default-src 'none'; style-src 'sha256-${hash}'; img-src ${images}; form-action 'self'; base-uri 'none'; frame-ancestors 'none'${scriptPolicy}`,\n\t\t\t},\n\t\t};\n\t} catch {\n\t\tthrow new Error(\"auth_browser_view_render_failed\");\n\t}\n}\n\n/** Caller releases this secret-bearing page only after confirmation commits. */\nexport async function renderAuthLinkCompletionHopPage(\n\tinput: CoordinatorAuthLinkCompletionHopPageInput,\n): Promise<CoordinatorAuthBrowserPage> {\n\tlet href: string;\n\ttry {\n\t\tconst data = record(input);\n\t\tif (!data) return invalidInput();\n\t\tconst destination = ownData(data, \"destination\", { rejectAccessor: true });\n\t\tconst attemptId = ownData(data, \"attemptId\", { rejectAccessor: true });\n\t\tconst completionSecret = ownData(data, \"completionSecret\", { rejectAccessor: true });\n\t\tconst parsed = parseCoordinatorAuthLoopback(destination);\n\t\tif (\n\t\t\t!parsed.ok ||\n\t\t\t!isAuthControllerId(attemptId) ||\n\t\t\ttypeof completionSecret !== \"string\" ||\n\t\t\tcompletionSecret.length !== 43 ||\n\t\t\t!/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/.test(completionSecret)\n\t\t)\n\t\t\treturn invalidInput();\n\t\t// Concatenation preserves the saved literal, including an explicit :80.\n\t\thref = `${parsed.destination}?attempt_id=${encodeURIComponent(attemptId)}&completion=${completionSecret}`;\n\t} catch {\n\t\treturn invalidInput();\n\t}\n\treturn buildPage(\n\t\t\"Finishing account link\",\n\t\t`<h1>Finishing account link…</h1><p>Returning to Codemem on this computer. If nothing happens, continue below.</p><p class=\"note\">Do not share this link.</p><div class=\"actions\"><a class=\"link\" href=\"${escapeHtml(href)}\" referrerpolicy=\"no-referrer\" rel=\"noreferrer\">Continue on this computer</a></div>`,\n\t\tundefined,\n\t\t{ refreshUrl: href },\n\t);\n}\n\n/** Presentation only; completion still requires live browser binding and device finalization. */\nexport async function renderAuthLinkCompletionPage(\n\tinput: CoordinatorAuthLinkCompletionPageInput,\n): Promise<CoordinatorAuthBrowserPage> {\n\tconst attemptId = capturePageField(input, \"attemptId\");\n\tconst state = capturePageField(input, \"state\");\n\tif (!isAuthControllerId(attemptId)) return invalidInput();\n\tif (state === \"waiting\") {\n\t\tconst href = `${AUTH_BROWSER_FORM_ACTIONS.completeLink}?attempt_id=${encodeURIComponent(attemptId)}`;\n\t\treturn buildPage(\n\t\t\t\"Waiting for this computer\",\n\t\t\t`<h1>Waiting for this computer</h1><p>Finish linking in the Codemem terminal, then check again.</p><div class=\"actions\"><a class=\"link\" href=\"${escapeHtml(href)}\" rel=\"noreferrer\" referrerpolicy=\"no-referrer\">Check again</a></div>`,\n\t\t);\n\t}\n\tif (state !== \"ready\") return invalidInput();\n\tconst csrfToken = capturePageField(input, \"csrfToken\");\n\tif (!isBrowserCsrfToken(csrfToken)) return invalidInput();\n\treturn buildPage(\n\t\t\"Finish linking\",\n\t\t`<h1>Finish linking</h1><p>Your computer confirmed the link. Finish to continue to your account. If you are already signed in, your current session stays unchanged. Sign out first to switch accounts.</p><div class=\"actions\">${form(AUTH_BROWSER_FORM_ACTIONS.completeLink, csrfToken, \"Finish linking\", { attemptId })}</div>`,\n\t\tundefined,\n\t\t{ referrerPolicy: \"same-origin\" },\n\t);\n}\n\n/** Private handoff code stays in hidden form data, never visible copy or provider URLs. */\nexport async function renderAuthLinkStartPage(\n\tinput: CoordinatorAuthLinkStartPageInput,\n): Promise<CoordinatorAuthBrowserPage> {\n\tconst attemptId = capturePageField(input, \"attemptId\");\n\tconst startCode = capturePageField(input, \"startCode\");\n\tconst csrfToken = captureSigninCsrf(input);\n\tif (\n\t\t!isAuthControllerId(attemptId) ||\n\t\ttypeof startCode !== \"string\" ||\n\t\t!decodeCoordinatorAuthProof32(startCode)\n\t)\n\t\treturn invalidInput();\n\treturn buildPage(\n\t\t\"Link this device\",\n\t\t`<h1>Connecting to Google…</h1><p>You’ll choose an account and confirm it before linking. Linking does not change project access.</p><p class=\"note\">If nothing happens, continue below. Do not share this page.</p><div class=\"actions\">${form(AUTH_BROWSER_FORM_ACTIONS.startLink, csrfToken, \"Continue with Google\", { attemptId, startCode })}</div>`,\n\t\tundefined,\n\t\t{ referrerPolicy: \"same-origin\", autoSubmit: true },\n\t);\n}\n\nexport async function renderAuthSigninPage(\n\tinput: CoordinatorAuthSigninPageInput,\n): Promise<CoordinatorAuthBrowserPage> {\n\tconst csrfToken = captureSigninCsrf(input);\n\treturn buildPage(\n\t\t\"Sign in\",\n\t\t`<h1>Sign in</h1><p>Sign in to manage your coordinator account.</p><p>Signing in does not enroll a device or change project access.</p><div class=\"actions\">${form(AUTH_BROWSER_FORM_ACTIONS.signIn, csrfToken, \"Sign in with Google\")}</div>`,\n\t\tundefined,\n\t\t{ referrerPolicy: \"same-origin\" },\n\t);\n}\n\n/**\n * Only pass a trusted SDK-produced URL, never a request-nominated URL.\n * The origin and known-key checks protect the anchor, not the OAuth protocol;\n * the denylist cannot detect arbitrary secret values in other parameters.\n */\nexport async function renderAuthSigninContinuePage(\n\tinput: CoordinatorAuthSigninContinuePageInput,\n): Promise<CoordinatorAuthBrowserPage> {\n\tconst authorizationUrl = captureAuthorizationUrl(input);\n\treturn buildPage(\n\t\t\"Continue sign-in\",\n\t\t`<h1>Continue sign-in</h1><div class=\"actions\"><a class=\"link\" href=\"${escapeHtml(authorizationUrl)}\" referrerpolicy=\"no-referrer\" rel=\"noreferrer\">Continue to Google</a></div>`,\n\t\tundefined,\n\t\t{ refreshUrl: authorizationUrl },\n\t);\n}\n\nexport async function renderAuthLinkConfirmPage(\n\tinput: CoordinatorAuthLinkConfirmPageInput,\n): Promise<CoordinatorAuthBrowserPage> {\n\tconst captured = capture(input);\n\tlet device: CoordinatorAuthBrowserEntity;\n\tlet group: CoordinatorAuthBrowserEntity | undefined;\n\tlet attemptId: string;\n\ttry {\n\t\tdevice = entity(ownData(captured.data, \"device\", { rejectAccessor: true }), \"Device\");\n\t\tconst groupValue = ownData(captured.data, \"group\", { rejectAccessor: true });\n\t\tif (groupValue !== undefined) group = entity(groupValue, \"Group\");\n\t\tconst attempt = ownData(captured.data, \"attemptId\", { rejectAccessor: true });\n\t\tif (!isAuthControllerId(attempt)) return invalidInput();\n\t\tattemptId = attempt;\n\t} catch {\n\t\treturn invalidInput();\n\t}\n\tlet entities = entityMarkup(captured.identity, \"Identity\") + entityMarkup(device, \"Device\");\n\tif (group) entities += entityMarkup(group, \"Group\");\n\tconst actions =\n\t\tform(AUTH_BROWSER_FORM_ACTIONS.confirmLink, captured.csrfToken, \"Link account\", { attemptId }) +\n\t\tform(AUTH_BROWSER_FORM_ACTIONS.cancelLink, captured.csrfToken, \"Cancel linking\", {\n\t\t\tattemptId,\n\t\t\tsecondary: true,\n\t\t});\n\treturn buildPage(\n\t\t\"Link account\",\n\t\t`<h1>Link account</h1>${profileMarkup(captured.profile)}<section aria-label=\"Link details\"><h2>Link details</h2><dl>${entities}</dl><p>Linking this account does not change project sharing, memories, or device keys.</p></section><p>Only confirm if you started linking on this computer. Do not share the link used to start this request.</p><div class=\"actions\">${actions}</div>`,\n\t\tcaptured.issuer,\n\t\t{ referrerPolicy: \"same-origin\" },\n\t);\n}\n\nexport async function renderCurrentAccountPage(\n\tinput: CoordinatorAuthCurrentAccountPageInput,\n): Promise<CoordinatorAuthBrowserPage> {\n\tconst captured = capture(input);\n\treturn buildPage(\n\t\t\"Account\",\n\t\t`<p class=\"eyebrow\">Signed in</p><h1>Account</h1>${profileMarkup(captured.profile)}<section aria-label=\"Identity\"><h2>Identity</h2><dl>${entityMarkup(captured.identity, \"Identity\")}</dl></section><div class=\"actions\">${form(AUTH_BROWSER_FORM_ACTIONS.signOut, captured.csrfToken, \"Sign out\")}</div>`,\n\t\tcaptured.issuer,\n\t\t{ referrerPolicy: \"same-origin\" },\n\t);\n}\n\nexport async function renderAuthBrowserNotice(\n\tkind:\n\t\t| \"expired\"\n\t\t| \"unavailable\"\n\t\t| \"signed_out\"\n\t\t| \"link_cancelled\"\n\t\t| \"signin_in_progress\"\n\t\t| \"signin_unavailable\"\n\t\t| \"auth_unavailable\",\n): Promise<CoordinatorAuthBrowserPage> {\n\tlet title: string;\n\tlet content: string;\n\tswitch (kind) {\n\t\tcase \"link_cancelled\":\n\t\t\ttitle = \"Linking cancelled\";\n\t\t\tcontent =\n\t\t\t\t\"<p>No account was linked in this attempt. Return to your terminal to start again.</p>\";\n\t\t\tbreak;\n\t\tcase \"auth_unavailable\":\n\t\t\ttitle = \"Sign-in or linking unavailable\";\n\t\t\tcontent = \"<p>Return to the flow you started and try again.</p>\";\n\t\t\tbreak;\n\t\tcase \"signin_in_progress\":\n\t\t\ttitle = \"Sign-in already in progress\";\n\t\t\tcontent = \"<p>Finish the open sign-in or account-link flow before starting another.</p>\";\n\t\t\tbreak;\n\t\tcase \"signin_unavailable\":\n\t\t\ttitle = \"Sign-in unavailable\";\n\t\t\tcontent =\n\t\t\t\t'<p>Sign-in is unavailable. Try again.</p><div class=\"actions\"><a class=\"link\" href=\"/auth/sign-in\">Sign in</a></div>';\n\t\t\tbreak;\n\t\tcase \"expired\":\n\t\t\ttitle = \"Link expired\";\n\t\t\tcontent =\n\t\t\t\t\"<p>This account link has expired. Return to your terminal and start linking again.</p>\";\n\t\t\tbreak;\n\t\tcase \"unavailable\":\n\t\t\ttitle = \"Account linking unavailable\";\n\t\t\tcontent =\n\t\t\t\t\"<p>Account linking is unavailable. Return to your terminal and start linking again.</p>\";\n\t\t\tbreak;\n\t\tcase \"signed_out\":\n\t\t\ttitle = \"Signed out\";\n\t\t\tcontent =\n\t\t\t\t'<p>You are signed out.</p><div class=\"actions\"><a class=\"link\" href=\"/auth/sign-in\">Sign in</a></div>';\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn invalidInput();\n\t}\n\treturn buildPage(title, `<h1>${escapeHtml(title)}</h1>${content}`);\n}\n","import { CONNECTION_RELINK_ELIGIBLE_SQL } from \"./coordinator-account-connection-link.js\";\nimport { connectionProfileColumns } from \"./coordinator-account-connection-session.js\";\nimport { projectAccountProfileView } from \"./coordinator-auth-browser-view.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport {\n\tAUTH_DEVICE_CLAIM_CURRENT_SUBJECT_COMPATIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_ELIGIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_INPUT_ROW_SQL,\n\tAUTH_DEVICE_CLAIM_INPUT_SQL,\n\tAUTH_DEVICE_CLAIM_LEGACY_COMPATIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_REQUESTER_ATTESTATION_COMPATIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_REQUESTER_INVITE_COMPATIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_REQUESTER_LINK_COMPATIBLE_SQL,\n\ttype CoordinatorDeviceClaimReadiness,\n\ttype CoordinatorDeviceClaimReadinessInput,\n\tcaptureDeviceClaimEligibility,\n} from \"./coordinator-auth-device-claim-eligibility.js\";\nimport { AUTH_CURRENT_LEGACY_ASSIGNMENT_SQL } from \"./coordinator-auth-legacy-assignment.js\";\nimport {\n\tAUTH_LINK_CONTROLLER_SOURCE_SQL,\n\ttype AuthLinkBackend,\n\ttype AuthLinkStatement,\n\tauthLinkControllerSourceValues,\n\tauthLinkNow,\n\tcaptureAuthLinkConfig,\n\tcaptureAuthLinkSigner,\n} from \"./coordinator-auth-link.js\";\nimport type { CoordinatorAccountLinkStatusV2 } from \"./coordinator-auth-link-authority.js\";\nimport type {\n\tCoordinatorAuthLinkConfig,\n\tCoordinatorAuthLinkSigner,\n} from \"./coordinator-auth-link-contract.js\";\nimport {\n\tauthAccountLinkProvenanceSql,\n\tauthClaimGenesisSql,\n\tauthDeviceClaimProvenanceSql,\n} from \"./coordinator-auth-link-provenance.js\";\nimport { authPersistenceError } from \"./coordinator-auth-schema.js\";\nimport { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\n\n/** Public device-authenticated response. No account identifiers or credentials. */\nexport type CoordinatorAccountLinkStatus = CoordinatorAccountLinkStatusV2;\nexport interface CoordinatorAccountLinkStatusStore {\n\treadAccountLinkStatus(\n\t\tsigner: CoordinatorAuthLinkSigner,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t\toptions: { identityId: string },\n\t): Promise<CoordinatorAccountLinkStatus>;\n}\ninterface StatusRow {\n\tidentity_id: string;\n\tlink_id: string | null;\n\tissuer: string | null;\n\trevoked_at_ms: number | null;\n\tdisplay_name: unknown;\n\temail: unknown;\n\temail_verified: unknown;\n\tpicture_url: unknown;\n\tauthority: \"device_claim\" | \"controller_attestation\";\n\tvalid: number;\n\t/** 1 when the proof is this device's own claim or attestation, not a peer's. */\n\town: number;\n\t/** 1 when this exact device key holds an ownership binding for the Identity. */\n\tbound: number;\n\tclaim_count: number;\n\tcontroller_count: number;\n\tcontroller_identity: string | null;\n}\n\nfunction safeDisplayText(value: unknown, maxLength: number): string | undefined {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\tvalue.length === 0 ||\n\t\tvalue.length > maxLength ||\n\t\tvalue.trim().length === 0 ||\n\t\t/[\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(value)\n\t)\n\t\treturn undefined;\n\treturn value;\n}\n\nfunction claimConflicts(row: StatusRow): boolean {\n\treturn (\n\t\trow.claim_count > 0 &&\n\t\t(row.claim_count !== 1 ||\n\t\t\trow.valid !== 1 ||\n\t\t\trow.controller_count > 1 ||\n\t\t\t(row.controller_identity !== null && row.controller_identity !== row.identity_id))\n\t);\n}\n\nfunction projectStatus(\n\tbase: Extract<CoordinatorAccountLinkStatus, { state: \"review_required\" | \"conflict\" }>,\n\trow: StatusRow | null,\n\tconfig: CoordinatorAuthLinkConfig,\n\tidentityId: string,\n): CoordinatorAccountLinkStatus {\n\tif (!row) return base;\n\tif (claimConflicts(row))\n\t\treturn { ...base, state: \"conflict\", identityId: null, authority: null, account: null };\n\tif (row.valid !== 1 || row.controller_count > 1) return base;\n\tconst derived = { ...base, identityId: row.identity_id, authority: row.authority };\n\tif (row.revoked_at_ms !== null) return { ...derived, state: \"revoked\", account: null };\n\tif (row.link_id === null) {\n\t\tif (row.identity_id !== identityId) return base;\n\t\treturn { ...derived, state: \"unlinked\", account: null };\n\t}\n\tif (row.issuer !== config.issuer) return { ...base, state: \"conflict\" };\n\treturn { ...derived, state: \"linked\", account: requesterAccount(row, identityId) };\n}\n\n/** This device's own claim, ownership binding, or current attestation for the same Identity. */\nfunction requesterHoldsProof(row: StatusRow): boolean {\n\treturn (\n\t\trow.own === 1 ||\n\t\trow.bound === 1 ||\n\t\t(row.controller_count === 1 && row.controller_identity === row.identity_id)\n\t);\n}\n\n/**\n * Profile details need this device's own proof. A peer of the Identity learns\n * only that the account is linked elsewhere (ADR 0005 Section 8).\n */\nfunction requesterAccount(\n\trow: StatusRow,\n\tidentityId: string,\n): CoordinatorAccountLinkStatus[\"account\"] {\n\tif (row.identity_id !== identityId || !requesterHoldsProof(row)) return null;\n\tconst account: NonNullable<CoordinatorAccountLinkStatus[\"account\"]> = {};\n\tconst displayName = safeDisplayText(row.display_name, 256);\n\tconst email = row.email_verified === 1 ? safeDisplayText(row.email, 320) : undefined;\n\tif (displayName !== undefined) account.displayName = displayName;\n\tif (email !== undefined) account.email = email;\n\tconst { pictureUrl } = projectAccountProfileView(\n\t\t{ pictureUrl: row.picture_url },\n\t\trow.issuer ?? \"\",\n\t);\n\tif (pictureUrl !== undefined) account.pictureUrl = pictureUrl;\n\treturn account;\n}\n\n/** This exact device key's ownership binding for the requested Identity (ADR 0005 Section 8). */\nconst REQUESTER_BINDING_SQL = `SELECT 1 FROM coordinator_device_ownership_bindings ob\n WHERE ob.coordinator_id = p.coordinator_id AND ob.device_id = p.device_id AND ob.key_id = p.key_id\n AND ob.identity_id = p.identity_id`;\n\nconst NOT_REVOKED_SQL = `NOT EXISTS (SELECT 1 FROM coordinator_device_revocations r\n WHERE (r.subject_kind = 'device_id' AND r.subject_value = p.device_id)\n OR (r.subject_kind = 'ed25519_key' AND r.subject_value = p.key_id))`;\nconst currentEnrollmentSql = (identity: string) =>\n\t`EXISTS (SELECT 1 FROM enrolled_devices e JOIN groups g ON g.group_id = e.group_id\n WHERE e.group_id = p.group_id AND e.device_id = p.device_id AND e.public_key = p.public_key\n AND e.fingerprint = p.fingerprint AND e.enabled = 1 AND g.archived_at IS NULL\n AND (e.identity_id IS NULL OR e.identity_id = ${identity}))`;\n\n/** This device's old claim under another Identity, once a binding moved it and that link ended. */\nconst SUPERSEDED_OWN_CLAIM_SQL = `d.identity_id <> p.identity_id AND EXISTS (${REQUESTER_BINDING_SQL})\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_links al WHERE al.coordinator_id = d.coordinator_id\n AND al.identity_id = d.identity_id AND al.revoked_at_ms IS NULL)`;\n\nconst CANDIDATE_FIELDS = [\"identity_id\", \"link_id\", \"issuer\", \"revoked_at_ms\", \"valid\", \"own\"];\nconst jsonRows = (fields: string[]) =>\n\t`json_group_array(json_object(${fields.map((field) => `'${field}',${field}`).join(\",\")}))`;\nconst fromJson = (alias: string, fields: string[]) =>\n\tfields.map((field) => `json_extract(${alias}.value,'$.${field}') AS ${field}`).join(\",\");\nconst GENESIS_ROWS = `(SELECT json_extract(value,'$.claim_id') AS claim_id FROM json_each(p.genesis))`;\nconst LINK_ROWS = `(SELECT json_extract(value,'$.link_id') AS link_id,\n json_extract(value,'$.authority_kind') AS authority_kind FROM json_each(p.links))`;\nconst NO_CLAIMS = \"json_array_length(p.claims) = 0\";\nconst NO_CONTROLLER = \"json_array_length(p.controllers) = 0\";\n\n/**\n * One statement, so authority, current enrollment, tombstones and metadata share a\n * snapshot. It uses no WITH: SQLite 3.54.0 and 3.54.1 (production D1) refuse a\n * statement that resolves a WITH name after about 100 table references, and every\n * reference to a WITH block counts its tables again. Each stage is instead a one-row\n * FROM subquery named p that adds a JSON column to the stage inside it, and later\n * stages read those columns with json_each. OFFSET keeps SQLite from flattening a\n * stage into its consumers, so each stage is computed once.\n *\n * Stages, innermost first: the 15 inputs; this device's current controller\n * attestations, its exact legacy assignment and (connection schema) the verified\n * claim genesis; verified links; claims; candidates.\n */\nfunction statusSql(connections: boolean): string {\n\t// A current attestation for this exact enrollment whose device and key are not revoked.\n\tconst controllers = `(SELECT json_group_array(c.controller_identity_id) FROM (\n SELECT a.identity_id AS controller_identity_id ${AUTH_LINK_CONTROLLER_SOURCE_SQL}\n AND 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 = ?))) c)`;\n\tconst assigned = `CASE WHEN (${AUTH_CURRENT_LEGACY_ASSIGNMENT_SQL} AND ${AUTH_DEVICE_CLAIM_LEGACY_COMPATIBLE_SQL})\n AND (${AUTH_DEVICE_CLAIM_CURRENT_SUBJECT_COMPATIBLE_SQL})\n AND (${AUTH_DEVICE_CLAIM_REQUESTER_ATTESTATION_COMPATIBLE_SQL}\n AND ${AUTH_DEVICE_CLAIM_REQUESTER_INVITE_COMPATIBLE_SQL})\n AND (${AUTH_DEVICE_CLAIM_REQUESTER_LINK_COMPATIBLE_SQL}) THEN 1 ELSE 0 END`;\n\tconst genesis = `(SELECT json_group_array(json_object('claim_id',d.claim_id,'identity_id',d.identity_id))\n FROM coordinator_auth_device_claims d WHERE d.coordinator_id = p.coordinator_id\n AND (d.device_id = p.device_id OR d.key_id = p.key_id OR d.identity_id = p.identity_id) AND ${authClaimGenesisSql(\"d\")})`;\n\tconst links = `(SELECT json_group_array(json_object('link_id',l.link_id,'authority_kind',l.authority_kind))\n FROM coordinator_auth_account_links l WHERE l.coordinator_id = p.coordinator_id\n AND (l.identity_id IN (SELECT json_extract(value,'$.identity_id') FROM json_each(p.genesis))\n OR l.identity_id IN (SELECT value FROM json_each(p.controllers)))\n AND ${authAccountLinkProvenanceSql(\"l\", { connections: true })})`;\n\tconst ownClaimProof = connections\n\t\t? \"(sg.claim_id IS NOT NULL AND (l.link_id IS NULL OR sl.link_id IS NOT NULL))\"\n\t\t: authDeviceClaimProvenanceSql({ link: \"l\", canonicalKeyId: \"?\" });\n\tconst peerClaimProof = connections\n\t\t? \"(sl.link_id IS NOT NULL AND sl.authority_kind = 'device_claim')\"\n\t\t: authDeviceClaimProvenanceSql({ link: \"l\" });\n\tconst claims = `(SELECT ${jsonRows(CANDIDATE_FIELDS)} FROM (\n SELECT d.identity_id, l.link_id, l.issuer, l.revoked_at_ms,\n CASE WHEN (l.identity_id = d.identity_id${connections ? \" OR (l.link_id IS NULL AND sg.claim_id IS NOT NULL)\" : \"\"})\n AND ${currentEnrollmentSql(\"d.identity_id\")}\n AND ${NOT_REVOKED_SQL}\n AND ((d.group_id = p.group_id AND d.device_id = p.device_id\n AND d.key_id = p.key_id AND d.fingerprint = p.fingerprint\n AND ${ownClaimProof})\n OR (d.identity_id = p.identity_id AND d.device_id <> p.device_id\n AND d.key_id <> p.key_id AND d.fingerprint <> p.fingerprint\n AND p.assigned = 1\n AND ${peerClaimProof}))\n THEN 1 ELSE 0 END AS valid,\n CASE WHEN d.device_id = p.device_id AND d.key_id = p.key_id THEN 1 ELSE 0 END AS own\n FROM coordinator_auth_device_claims d\n LEFT JOIN coordinator_auth_account_links l ON l.coordinator_id = d.coordinator_id AND ${connections ? \"l.identity_id = d.identity_id\" : \"l.device_claim_id = d.claim_id\"}\n ${connections ? `LEFT JOIN ${GENESIS_ROWS} sg ON sg.claim_id = d.claim_id LEFT JOIN ${LINK_ROWS} sl ON sl.link_id = l.link_id` : \"\"}\n WHERE d.coordinator_id = p.coordinator_id\n AND (d.device_id = p.device_id OR d.key_id = p.key_id\n OR (d.identity_id = p.identity_id AND p.assigned = 1))\n AND NOT (${SUPERSEDED_OWN_CLAIM_SQL})))`;\n\t// A rebound device has no claim of its own; its binding names the Identity and the\n\t// Identity's link is the account. Valid only while the device's exact enrollment is\n\t// current, neither device nor key is revoked, and the link was born through a\n\t// reviewed claim or attestation.\n\tconst candidates = `(SELECT ${jsonRows([...CANDIDATE_FIELDS, \"authority\"])} FROM (\n SELECT ${fromJson(\"c\", CANDIDATE_FIELDS)}, 'device_claim' AS authority FROM json_each(p.claims) c\n UNION ALL SELECT a.value, l.link_id, l.issuer, l.revoked_at_ms,\n ${connections ? \"CASE WHEN l.link_id IS NULL OR valid_controller.link_id IS NOT NULL THEN 1 ELSE 0 END\" : \"1\"}, 1, 'controller_attestation'\n FROM json_each(p.controllers) a LEFT JOIN coordinator_auth_account_links l ON l.coordinator_id = p.coordinator_id\n AND l.identity_id = a.value ${connections ? \"\" : \"AND l.authority_kind = 'controller_attestation' AND l.controller_attestation_id IS NOT NULL AND l.device_claim_id IS NULL\"}\n ${connections ? `LEFT JOIN ${LINK_ROWS} valid_controller ON valid_controller.link_id = l.link_id` : \"\"}\n WHERE ${NO_CLAIMS}\n UNION ALL SELECT ob.identity_id, l.link_id, l.issuer, l.revoked_at_ms,\n CASE WHEN ${currentEnrollmentSql(\"ob.identity_id\")}\n AND ${NOT_REVOKED_SQL}\n AND (l.link_id IS NULL OR ${authAccountLinkProvenanceSql(\"l\", { connections })})\n THEN 1 ELSE 0 END, 1, 'device_claim'\n FROM coordinator_device_ownership_bindings ob\n LEFT JOIN coordinator_auth_account_links l ON l.coordinator_id = p.coordinator_id AND l.identity_id = ob.identity_id\n WHERE ob.coordinator_id = p.coordinator_id AND ob.device_id = p.device_id AND ob.key_id = p.key_id\n AND ob.identity_id = p.identity_id AND ${NO_CLAIMS} AND ${NO_CONTROLLER}\n UNION ALL SELECT p.identity_id, NULL, NULL, NULL, 1, 1, 'device_claim'\n WHERE ${NO_CLAIMS} AND ${NO_CONTROLLER}\n AND NOT EXISTS (${REQUESTER_BINDING_SQL}) AND ${AUTH_DEVICE_CLAIM_ELIGIBLE_SQL}))`;\n\tconst stage = (inner: string, columns: string) =>\n\t\t`(SELECT p.*, ${columns} FROM ${inner} p LIMIT 1 OFFSET 0)`;\n\tconst facts = stage(\n\t\tAUTH_DEVICE_CLAIM_INPUT_ROW_SQL,\n\t\t`${controllers} AS controllers, ${assigned} AS assigned${connections ? `, ${genesis} AS genesis` : \"\"}`,\n\t);\n\tconst linked = connections ? stage(facts, `${links} AS links`) : facts;\n\tconst claimed = stage(linked, `${claims} AS claims`);\n\tconst a = (field: string) => `json_extract(a.value,'$.${field}')`;\n\tconst revoked = connections\n\t\t? `coalesce((SELECT min(h.revoked_at_ms) FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id = p.coordinator_id AND h.identity_id = ${a(\"identity_id\")} AND h.revoked_at_ms IS NOT NULL),${a(\"revoked_at_ms\")})`\n\t\t: a(\"revoked_at_ms\");\n\tconst profile = connections\n\t\t? connectionProfileColumns(\"m\")\n\t\t: `CASE WHEN m.link_id IS NOT NULL THEN m.display_name ELSE b.display_name END AS display_name,\n CASE WHEN m.link_id IS NOT NULL THEN m.email ELSE b.email END AS email,\n CASE WHEN m.link_id IS NOT NULL THEN m.email_verified ELSE b.email_verified END AS email_verified,\n CASE WHEN m.link_id IS NOT NULL THEN m.picture_url ELSE b.picture_url END AS picture_url`;\n\treturn `SELECT ${[\"identity_id\", \"link_id\", \"issuer\", \"valid\", \"own\", \"authority\"].map((field) => `${a(field)} AS ${field}`).join(\",\")},\n EXISTS (${REQUESTER_BINDING_SQL} AND ob.identity_id = ${a(\"identity_id\")}) AS bound,\n ${revoked} AS revoked_at_ms,\n json_array_length(p.claims) AS claim_count,\n json_array_length(p.controllers) AS controller_count,\n json_extract(p.controllers,'$[0]') AS controller_identity,\n ${profile}\n FROM ${stage(claimed, `${candidates} AS candidates`)} p\n JOIN json_each(p.candidates) a\n LEFT JOIN coordinator_auth_account_links l ON l.coordinator_id = p.coordinator_id AND l.link_id = ${a(\"link_id\")}\n AND l.identity_id = ${a(\"identity_id\")} AND ${a(\"identity_id\")} = p.identity_id AND l.issuer = ${a(\"issuer\")}\n AND l.revoked_at_ms IS NULL\n LEFT JOIN coordinator_auth_account_profiles m ON m.coordinator_id = l.coordinator_id\n AND m.link_id = l.link_id\n LEFT JOIN coordinator_auth_link_profiles b ON b.coordinator_id = l.coordinator_id\n AND b.link_id = l.link_id AND b.attempt_id = l.attempt_id AND b.issuer = l.issuer\n AND b.subject = l.subject AND b.auth_config_revision = l.auth_config_revision LIMIT 1`;\n}\n\n/** Bound values in the order statusSql writes its placeholders. */\nfunction statusValues(\n\tconnections: boolean,\n\tcaptured: AuthLinkStatement[\"values\"],\n\tcontrollerSource: AuthLinkStatement[\"values\"],\n\tkeyId: string,\n): AuthLinkStatement[\"values\"] {\n\t// Without the connection schema the own-claim proof pins the canonical key ID.\n\treturn [...(connections ? [] : [keyId]), ...controllerSource, keyId, ...captured];\n}\n\n/** Reads only. Rechecks the exact enrollment and controller after key derivation. */\nexport class AccountLinkStatusOperations implements CoordinatorAccountLinkStatusStore {\n\tconstructor(\n\t\tprivate readonly backend: Pick<AuthLinkBackend, \"first\">,\n\t\tprivate readonly clock: () => number = Date.now,\n\t) {}\n\n\t/** Internal store capability only. It does not reserve a claim or expose account data. */\n\tasync readAuthDeviceClaimReadiness(\n\t\tinput: CoordinatorDeviceClaimReadinessInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorDeviceClaimReadiness> {\n\t\tconst c = captureAuthLinkConfig(config);\n\t\tif (!c?.enabled) return { kind: \"unavailable\" };\n\t\ttry {\n\t\t\tconst captured = await captureDeviceClaimEligibility(\n\t\t\t\tthis.backend,\n\t\t\t\tinput,\n\t\t\t\tc,\n\t\t\t\tauthLinkNow(this.clock),\n\t\t\t);\n\t\t\tif (!captured) return { kind: \"unavailable\" };\n\t\t\tconst row = await this.backend.first<{ eligible: number }>({\n\t\t\t\tsql: `${AUTH_DEVICE_CLAIM_INPUT_SQL} SELECT CASE WHEN (${AUTH_DEVICE_CLAIM_ELIGIBLE_SQL})${captured.connectionSession ? ` OR (${CONNECTION_RELINK_ELIGIBLE_SQL})` : \"\"} THEN 1 ELSE 0 END AS eligible FROM claim_input p`,\n\t\t\t\tvalues: captured.values,\n\t\t\t});\n\t\t\tif (row?.eligible !== 1) return { kind: \"unavailable\" };\n\t\t\treturn { kind: \"eligible\", authority: \"device_claim\", identityId: captured.identityId };\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_device_claim_unavailable\");\n\t\t}\n\t}\n\n\tasync readAccountLinkStatus(\n\t\tsigner: CoordinatorAuthLinkSigner,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t\toptions: { identityId: string },\n\t): Promise<CoordinatorAccountLinkStatus> {\n\t\tconst c = captureAuthLinkConfig(config);\n\t\tconst s = captureAuthLinkSigner(signer);\n\t\tif (!c?.enabled || !s || !isAuthControllerId(options?.identityId))\n\t\t\tthrow new Error(\"account_link_status_unavailable\");\n\t\tconst base: CoordinatorAccountLinkStatus = {\n\t\t\tversion: 2,\n\t\t\tcoordinatorId: c.coordinatorId,\n\t\t\tgroupId: s.groupId,\n\t\t\tdeviceId: s.deviceId,\n\t\t\tfingerprint: s.fingerprint,\n\t\t\tidentityId: null,\n\t\t\tauthority: null,\n\t\t\tstate: \"review_required\",\n\t\t\taccount: null,\n\t\t};\n\t\ttry {\n\t\t\tconst identityId = options.identityId;\n\t\t\tconst keyId = await ed25519KeyIdForRevocation(s.publicKey);\n\t\t\tif (!keyId) return base;\n\t\t\tconst captured = await captureDeviceClaimEligibility(\n\t\t\t\tthis.backend,\n\t\t\t\t{ signer: s, identityId },\n\t\t\t\tc,\n\t\t\t\tauthLinkNow(this.clock),\n\t\t\t);\n\t\t\tif (!captured) return base;\n\t\t\tconst connections = captured.connectionSession;\n\t\t\tconst row = await this.backend.first<StatusRow>({\n\t\t\t\tsql: statusSql(connections),\n\t\t\t\tvalues: statusValues(\n\t\t\t\t\tconnections,\n\t\t\t\t\tcaptured.values,\n\t\t\t\t\tauthLinkControllerSourceValues(c, s),\n\t\t\t\t\tkeyId,\n\t\t\t\t),\n\t\t\t});\n\t\t\treturn projectStatus(base, row, c, identityId);\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"account_link_status_unavailable\");\n\t\t}\n\t}\n}\n","import {\n\tACCOUNT_CONNECTION_SCHEMA_READINESS_SQL,\n\tisIncompleteConnectionSchemaError,\n\treadConnectionSchemaState,\n} from \"./coordinator-account-connection-schema.js\";\nimport { CONNECTION_NOT_REVOKED_SQL } from \"./coordinator-account-connection-storage.js\";\nimport {\n\ttype CoordinatorAuthControllerStore,\n\tisAuthControllerId,\n} from \"./coordinator-auth-controller.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport type {\n\tCoordinatorAuthLinkConfig,\n\tCoordinatorAuthLinkSigner,\n} from \"./coordinator-auth-link-contract.js\";\nimport {\n\tcapture,\n\tcaptureAuthLinkConfig,\n\tcaptureAuthLinkSigner,\n\tisHash,\n} from \"./coordinator-auth-link-input.js\";\nimport { authAccountLinkProvenanceSql } from \"./coordinator-auth-link-provenance.js\";\nimport { authPersistenceError } from \"./coordinator-auth-schema.js\";\nimport { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\n\nexport interface CoordinatorAccountOwnerTargetInput {\n\t/** Explicit operator choice, not the local memory author or an enrollment label. */\n\ttargetIdentityId: string;\n\tsigner: CoordinatorAuthLinkSigner;\n}\nexport interface CoordinatorAccountOwnerTargetStore {\n\treadAccountOwnerTarget(\n\t\tinput: CoordinatorAccountOwnerTargetInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAccountOwnerTarget>;\n}\nexport type CoordinatorAccountOwnerTarget =\n\t| { kind: \"unavailable\" }\n\t| {\n\t\t\tkind: \"ready\";\n\t\t\ttargetIdentityId: string;\n\t\t\t/** The immutable link ID identifies the current connection generation. */\n\t\t\tlinkId: string;\n\t\t\tcurrentGeneration: { authConfigRevision: string; createdAtMs: number };\n\t\t\treview: { attestationId: string; reviewReceiptId: string; evidenceDigest: string } | null;\n\t };\n\ninterface TargetRow {\n\tlink_id: string;\n\tauth_config_revision: string;\n\tcreated_at_ms: number;\n\treview_count: number;\n\tattestation_id: string | null;\n\treview_revoked_at: string | null;\n}\nconst REVIEW_MATCH = `a.coordinator_id=l.coordinator_id AND a.group_id=e.group_id\n AND a.device_id=e.device_id AND a.fingerprint=e.fingerprint`;\nconst TARGET_SQL = `SELECT l.link_id,l.auth_config_revision,l.created_at_ms,\n (SELECT count(*) FROM coordinator_auth_controller_attestations a WHERE ${REVIEW_MATCH}) AS review_count,\n (SELECT a.attestation_id FROM coordinator_auth_controller_attestations a WHERE ${REVIEW_MATCH} LIMIT 1) AS attestation_id,\n (SELECT a.revoked_at FROM coordinator_auth_controller_attestations a WHERE ${REVIEW_MATCH} LIMIT 1) AS review_revoked_at\n FROM coordinator_auth_account_links l\n JOIN enrolled_devices e ON e.group_id=? AND e.device_id=?\n JOIN groups g ON g.group_id=e.group_id\n WHERE l.coordinator_id=? AND l.identity_id=? AND l.issuer=?\n AND e.public_key=? AND e.fingerprint=? AND e.enabled=1 AND g.archived_at IS NULL\n AND (e.identity_id IS NULL OR e.identity_id=l.identity_id)\n AND NOT EXISTS (SELECT 1 FROM coordinator_device_revocations r\n WHERE (r.subject_kind='device_id' AND r.subject_value=e.device_id)\n OR (r.subject_kind='ed25519_key' AND r.subject_value=?))\n AND ${CONNECTION_NOT_REVOKED_SQL}\n AND ${authAccountLinkProvenanceSql(\"l\", { connections: true })}`;\n\nfunction validTarget(row: TargetRow | null): row is TargetRow {\n\tif (!row || !isAuthControllerId(row.link_id) || !isHash(row.auth_config_revision)) return false;\n\tif (!Number.isSafeInteger(row.created_at_ms) || row.created_at_ms < 0) return false;\n\tif (row.review_revoked_at !== null) return false;\n\tif (row.review_count === 0) return row.attestation_id === null;\n\treturn row.review_count === 1 && isAuthControllerId(row.attestation_id);\n}\nfunction sameTarget(a: TargetRow, b: TargetRow | null): boolean {\n\treturn (\n\t\tvalidTarget(b) &&\n\t\ta.link_id === b.link_id &&\n\t\ta.auth_config_revision === b.auth_config_revision &&\n\t\ta.created_at_ms === b.created_at_ms &&\n\t\ta.review_count === b.review_count &&\n\t\ta.attestation_id === b.attestation_id &&\n\t\ta.review_revoked_at === b.review_revoked_at\n\t);\n}\n\nasync function readSchemaReadyTarget(\n\tbackend: Pick<AuthLinkBackend, \"first\">,\n\tstatement: AuthLinkStatement,\n): Promise<TargetRow | null> {\n\ttry {\n\t\treturn await backend.first<TargetRow>({\n\t\t\t...statement,\n\t\t\tsql: `${statement.sql} AND (${ACCOUNT_CONNECTION_SCHEMA_READINESS_SQL})=1`,\n\t\t});\n\t} catch (error) {\n\t\tif (isIncompleteConnectionSchemaError(error)) return null;\n\t\tthrow error;\n\t}\n}\n\n/** Trusted store read only. Future callers MUST authenticate the admin first.\n * A ready result is advisory, not approval to adopt a profile or mutate an account.\n * Null enrollment labels are accepted for review, never treated as ownership proof.\n */\nexport class AccountOwnerTargetOperations {\n\tconstructor(\n\t\tprivate readonly backend: Pick<AuthLinkBackend, \"first\">,\n\t\tprivate readonly reviews: Pick<\n\t\t\tCoordinatorAuthControllerStore,\n\t\t\t\"getActiveAuthControllerAttestation\"\n\t\t>,\n\t) {}\n\n\tasync readAccountOwnerTarget(\n\t\tinput: CoordinatorAccountOwnerTargetInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAccountOwnerTarget> {\n\t\tconst c = captureAuthLinkConfig(config);\n\t\tconst fields = capture(input, [\"targetIdentityId\", \"signer\"]);\n\t\tconst s = captureAuthLinkSigner(fields?.signer);\n\t\tconst identityId = fields?.targetIdentityId;\n\t\tif (!c?.enabled || !s || !isAuthControllerId(identityId)) return { kind: \"unavailable\" };\n\t\ttry {\n\t\t\tif ((await readConnectionSchemaState(this.backend)) !== \"ready\")\n\t\t\t\treturn { kind: \"unavailable\" };\n\t\t\tconst keyId = await ed25519KeyIdForRevocation(s.publicKey);\n\t\t\tif (!keyId) return { kind: \"unavailable\" };\n\t\t\tconst statement = {\n\t\t\t\tsql: TARGET_SQL,\n\t\t\t\tvalues: [\n\t\t\t\t\ts.groupId,\n\t\t\t\t\ts.deviceId,\n\t\t\t\t\tc.coordinatorId,\n\t\t\t\t\tidentityId,\n\t\t\t\t\tc.issuer,\n\t\t\t\t\ts.publicKey,\n\t\t\t\t\ts.fingerprint,\n\t\t\t\t\tkeyId,\n\t\t\t\t],\n\t\t\t};\n\t\t\tconst row = await this.backend.first<TargetRow>(statement);\n\t\t\tif (!validTarget(row)) return { kind: \"unavailable\" };\n\t\t\tconst review = await this.readReview(row, c.coordinatorId, identityId, s);\n\t\t\tif (review === undefined) return { kind: \"unavailable\" };\n\t\t\tif ((await readConnectionSchemaState(this.backend)) !== \"ready\")\n\t\t\t\treturn { kind: \"unavailable\" };\n\t\t\t// Review and schema reads may yield. Recheck both schema and target in one final snapshot.\n\t\t\tif (!sameTarget(row, await readSchemaReadyTarget(this.backend, statement)))\n\t\t\t\treturn { kind: \"unavailable\" };\n\t\t\treturn {\n\t\t\t\tkind: \"ready\",\n\t\t\t\ttargetIdentityId: identityId,\n\t\t\t\tlinkId: row.link_id,\n\t\t\t\tcurrentGeneration: {\n\t\t\t\t\tauthConfigRevision: row.auth_config_revision,\n\t\t\t\t\tcreatedAtMs: row.created_at_ms,\n\t\t\t\t},\n\t\t\t\treview,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"account_owner_target_unavailable\");\n\t\t}\n\t}\n\n\tprivate async readReview(\n\t\trow: TargetRow,\n\t\tcoordinatorId: string,\n\t\tidentityId: string,\n\t\tsigner: CoordinatorAuthLinkSigner,\n\t): Promise<Extract<CoordinatorAccountOwnerTarget, { kind: \"ready\" }>[\"review\"] | undefined> {\n\t\tif (row.attestation_id === null) return null;\n\t\t// Do not reparse review JSON or compare an immutable review to fresh history.\n\t\tconst a = await this.reviews.getActiveAuthControllerAttestation(\n\t\t\tcoordinatorId,\n\t\t\trow.attestation_id,\n\t\t);\n\t\tif (\n\t\t\t!a ||\n\t\t\ta.coordinator_id !== coordinatorId ||\n\t\t\ta.attestation_id !== row.attestation_id ||\n\t\t\ta.identity_id !== identityId ||\n\t\t\ta.group_id !== signer.groupId ||\n\t\t\ta.device_id !== signer.deviceId ||\n\t\t\ta.public_key !== signer.publicKey ||\n\t\t\ta.fingerprint !== signer.fingerprint ||\n\t\t\ta.revoked_at !== null ||\n\t\t\ta.revision !== 1 ||\n\t\t\t!isAuthControllerId(a.review_receipt_id) ||\n\t\t\t!isHash(a.evidence_digest)\n\t\t)\n\t\t\treturn undefined;\n\t\treturn {\n\t\t\tattestationId: a.attestation_id,\n\t\t\treviewReceiptId: a.review_receipt_id,\n\t\t\tevidenceDigest: a.evidence_digest,\n\t\t};\n\t}\n}\n","import {\n\thasConnectionSessionSchema,\n\torderedBrowserStart,\n} from \"./coordinator-account-connection-session.js\";\nimport {\n\tAUTH_BROWSER_TXN_MAINTENANCE_BATCH_MAX,\n\tAUTH_BROWSER_TXN_TTL_MS,\n\tAUTH_SIGNIN_TXN_MAX_RETAINED,\n\tAUTH_SIGNIN_TXN_MAX_STARTS_PER_WINDOW,\n\tAUTH_SIGNIN_TXN_PURGE_AGE_MS,\n\tAUTH_SIGNIN_TXN_PURGE_BATCH_MAX,\n\tAUTH_SIGNIN_TXN_WINDOW_MS,\n\ttype CoordinatorAuthBrowserConfig,\n\ttype CoordinatorAuthBrowserTransactionConsumeInput,\n\ttype CoordinatorAuthBrowserTransactionConsumeResult,\n\ttype CoordinatorAuthBrowserTransactionError,\n\ttype CoordinatorAuthBrowserTransactionMaintenanceOptions,\n\ttype CoordinatorAuthBrowserTransactionMaintenanceResult,\n\ttype CoordinatorAuthBrowserTransactionPurpose,\n\ttype CoordinatorAuthBrowserTransactionRejected,\n\ttype CoordinatorAuthBrowserTransactionRetirementOptions,\n\ttype CoordinatorAuthBrowserTransactionRetirementResult,\n\ttype CoordinatorAuthBrowserTransactionScope,\n\ttype CoordinatorAuthBrowserTransactionStartInput,\n\ttype CoordinatorAuthBrowserTransactionStartResult,\n\ttype CoordinatorAuthBrowserTransactionStore,\n\ttype CoordinatorAuthLinkBrowserTransactionResolveInput,\n\ttype CoordinatorAuthSigninBrowserTransactionCancelInput,\n\ttype CoordinatorAuthSigninBrowserTransactionCancelResult,\n\ttype CoordinatorAuthSigninBrowserTransactionPurgeResult,\n} from \"./coordinator-auth-browser-transaction-contract.js\";\nimport { isCoordinatorAccountIssuer } from \"./coordinator-auth-contract.js\";\nimport { isAuthControllerId, isAuthControllerUniqueError } from \"./coordinator-auth-controller.js\";\nimport {\n\ttype AuthLinkBackend,\n\ttype AuthLinkStatement,\n\tauthLinkNow,\n\tcaptureAuthLinkBrowserStartHash,\n} from \"./coordinator-auth-link.js\";\nimport {\n\tAUTH_LINK_HEADLESS_MARKER_SQL,\n\ttype CoordinatorAuthHeadlessBrowserStartInput,\n\ttype CoordinatorAuthHeadlessBrowserStartResult,\n} from \"./coordinator-auth-link-headless.js\";\nimport {\n\tcaptureAuthLinkBrowserSource,\n\tcaptureAuthLinkSource,\n} from \"./coordinator-auth-link-source.js\";\nimport { authPersistenceError } from \"./coordinator-auth-schema.js\";\n\nexport * from \"./coordinator-auth-browser-transaction-contract.js\";\n\ntype Captured = Record<string, unknown>;\nfunction capture(value: unknown, fields: readonly string[]): Captured | null {\n\tif (!value || typeof value !== \"object\") return null;\n\ttry {\n\t\tif (Array.isArray(value)) return null;\n\t\tconst result: Captured = {};\n\t\tfor (const key of fields) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\t\tif (!descriptor || !Object.hasOwn(descriptor, \"value\")) return null;\n\t\t\tresult[key] = descriptor.value;\n\t\t}\n\t\treturn result;\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction isHash(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length === 64 && /^[0-9a-f]{64}$/.test(value);\n}\nfunction isMaterial(value: unknown): value is string {\n\treturn typeof value === \"string\" && /^[A-Za-z0-9._~-]{43,128}$/.test(value);\n}\nfunction isRedirect(value: unknown): value is string {\n\tif (typeof value !== \"string\" || value.trim() !== value || /[\\\\\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(value))\n\t\treturn false;\n\ttry {\n\t\tconst url = new URL(value);\n\t\treturn (\n\t\t\turl.protocol === \"https:\" &&\n\t\t\turl.href === value &&\n\t\t\t!url.username &&\n\t\t\t!url.password &&\n\t\t\t!url.search &&\n\t\t\t!url.hash &&\n\t\t\t!value.includes(\"?\") &&\n\t\t\t!value.includes(\"#\")\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\nfunction captureConfig(value: unknown): CoordinatorAuthBrowserConfig | null {\n\tconst c = capture(value, [\"coordinatorId\", \"issuer\", \"revision\", \"enabled\", \"redirectUri\"]);\n\tif (\n\t\t!c ||\n\t\t!isAuthControllerId(c.coordinatorId) ||\n\t\t!isCoordinatorAccountIssuer(c.issuer) ||\n\t\t!isHash(c.revision) ||\n\t\ttypeof c.enabled !== \"boolean\" ||\n\t\t!isRedirect(c.redirectUri)\n\t)\n\t\treturn null;\n\treturn {\n\t\tcoordinatorId: c.coordinatorId,\n\t\tissuer: c.issuer,\n\t\trevision: c.revision,\n\t\tenabled: c.enabled,\n\t\tredirectUri: c.redirectUri,\n\t};\n}\nfunction isSigninAttempt(value: object, attempt: PropertyDescriptor | undefined): boolean {\n\tif (attempt) return Object.hasOwn(attempt, \"value\") && attempt.value === undefined;\n\treturn !(\"attemptId\" in value);\n}\nfunction captureStart(value: unknown): CoordinatorAuthBrowserTransactionStartInput | null {\n\tconst i = capture(value, [\"purpose\", \"stateHash\", \"binderHash\", \"nonce\", \"pkceVerifier\"]);\n\tif (\n\t\t!i ||\n\t\t!isHash(i.stateHash) ||\n\t\t!isHash(i.binderHash) ||\n\t\t!isMaterial(i.nonce) ||\n\t\t!isMaterial(i.pkceVerifier)\n\t)\n\t\treturn null;\n\ttry {\n\t\t// Never accept request nomination of the internal, server-generated transaction hash.\n\t\tif (\n\t\t\tObject.getOwnPropertyDescriptor(value, \"browserTransactionHash\") ||\n\t\t\t\"browserTransactionHash\" in (value as object)\n\t\t)\n\t\t\treturn null;\n\t\tconst attempt = Object.getOwnPropertyDescriptor(value, \"attemptId\");\n\t\tif (i.purpose === \"signin\") {\n\t\t\tif (!isSigninAttempt(value as object, attempt)) return null;\n\t\t\treturn {\n\t\t\t\tpurpose: \"signin\",\n\t\t\t\tstateHash: i.stateHash,\n\t\t\t\tbinderHash: i.binderHash,\n\t\t\t\tnonce: i.nonce,\n\t\t\t\tpkceVerifier: i.pkceVerifier,\n\t\t\t};\n\t\t}\n\t\tif (\n\t\t\ti.purpose !== \"link\" ||\n\t\t\t!attempt ||\n\t\t\t!Object.hasOwn(attempt, \"value\") ||\n\t\t\t!isAuthControllerId(attempt.value)\n\t\t)\n\t\t\treturn null;\n\t\tconst browserStartHash = captureAuthLinkBrowserStartHash(value);\n\t\tif (browserStartHash === false) return null;\n\t\treturn {\n\t\t\tpurpose: \"link\",\n\t\t\tattemptId: attempt.value,\n\t\t\t...(browserStartHash === null ? {} : { browserStartHash }),\n\t\t\tstateHash: i.stateHash,\n\t\t\tbinderHash: i.binderHash,\n\t\t\tnonce: i.nonce,\n\t\t\tpkceVerifier: i.pkceVerifier,\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction captureHeadlessStart(value: unknown): CoordinatorAuthHeadlessBrowserStartInput | null {\n\tconst i = capture(value, [\"userCodeHash\", \"stateHash\", \"binderHash\", \"nonce\", \"pkceVerifier\"]);\n\tif (\n\t\t!i ||\n\t\t!isHash(i.userCodeHash) ||\n\t\t!isHash(i.stateHash) ||\n\t\t!isHash(i.binderHash) ||\n\t\t!isMaterial(i.nonce) ||\n\t\t!isMaterial(i.pkceVerifier)\n\t)\n\t\treturn null;\n\treturn {\n\t\tuserCodeHash: i.userCodeHash,\n\t\tstateHash: i.stateHash,\n\t\tbinderHash: i.binderHash,\n\t\tnonce: i.nonce,\n\t\tpkceVerifier: i.pkceVerifier,\n\t};\n}\ntype LinkMode = \"desktop\" | \"headless\";\n/** Both the transaction insert and the attempt claim must name the attempt's mode. */\nfunction withLinkMode(\n\tsource: AuthLinkStatement,\n\talias: \"a\" | \"coordinator_auth_link_attempts\",\n\tmode: LinkMode,\n): AuthLinkStatement {\n\tconst operator = mode === \"headless\" ? \"=\" : \"<>\";\n\treturn {\n\t\tsql: `(${source.sql}) AND ${alias}.loopback_redirect ${operator} ${AUTH_LINK_HEADLESS_MARKER_SQL}`,\n\t\tvalues: source.values,\n\t};\n}\nfunction maintenanceLimit(\n\tvalue: unknown,\n\tmax = AUTH_BROWSER_TXN_MAINTENANCE_BATCH_MAX,\n): number | null {\n\tif (value === undefined) return max;\n\tif (!value || typeof value !== \"object\") return null;\n\ttry {\n\t\tif (Array.isArray(value)) return null;\n\t\tconst d = Object.getOwnPropertyDescriptor(value, \"limit\");\n\t\tif (!d) return \"limit\" in value ? null : max;\n\t\tif (!Object.hasOwn(d, \"value\")) return null;\n\t\tconst limit: unknown = d.value;\n\t\treturn typeof limit === \"number\" && Number.isSafeInteger(limit) && limit >= 1 && limit <= max\n\t\t\t? limit\n\t\t\t: null;\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction captureRetirementOptions(value: unknown): { limit: number; attemptId?: string } | null {\n\tconst limit = maintenanceLimit(value);\n\tif (limit === null) return null;\n\tif (value === undefined) return { limit };\n\ttry {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, \"attemptId\");\n\t\tif (!descriptor) return \"attemptId\" in (value as object) ? null : { limit };\n\t\tif (!Object.hasOwn(descriptor, \"value\") || !isAuthControllerId(descriptor.value)) return null;\n\t\treturn { limit, attemptId: descriptor.value };\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction rejected(\n\terror: CoordinatorAuthBrowserTransactionError,\n): CoordinatorAuthBrowserTransactionRejected {\n\treturn { kind: \"rejected\", error };\n}\nfunction transactionHash(): string {\n\ttry {\n\t\tconst bytes = globalThis.crypto.getRandomValues(new Uint8Array(32));\n\t\treturn Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\t} catch {\n\t\tthrow new Error(\"browser_transaction_entropy_failed\");\n\t}\n}\nfunction claimToken(): string {\n\ttry {\n\t\treturn globalThis.crypto.randomUUID();\n\t} catch {\n\t\tthrow new Error(\"browser_transaction_entropy_failed\");\n\t}\n}\ninterface TransactionRow {\n\tbrowser_transaction_hash: string;\n\tpurpose: string;\n\tattempt_id: string | null;\n\tnonce: string | null;\n\tpkce_verifier: string | null;\n\texpires_at_ms: number;\n}\ninterface AttemptDiagnosis {\n\tissuer: string;\n\tauth_config_revision: string;\n\tstate: string;\n\texpires_at_ms: number;\n}\nfunction isConsumableRow(\n\trow: TransactionRow,\n): row is TransactionRow & { nonce: string; pkce_verifier: string } {\n\tif (\n\t\t!isHash(row.browser_transaction_hash) ||\n\t\t!isMaterial(row.nonce) ||\n\t\t!isMaterial(row.pkce_verifier)\n\t)\n\t\treturn false;\n\tif (row.purpose === \"signin\") return row.attempt_id === null;\n\treturn row.purpose === \"link\" && isAuthControllerId(row.attempt_id);\n}\nconst TABLE = \"coordinator_auth_browser_transactions\";\nconst PURGE_FLOORS = \"coordinator_auth_signin_purge_floors\";\nconst COLUMNS = `coordinator_id, browser_transaction_hash, purpose, attempt_id, state_hash, binder_hash,\n issuer, auth_config_revision, redirect_uri, state, nonce, pkce_verifier, created_at_ms, expires_at_ms, claim_token, consumed_at_ms`;\n// Force a uniqueness failure even when another admission guard suppresses a colliding insert.\nconst ASSERT_HASH_FRESH = `UNION ALL SELECT ${COLUMNS} FROM coordinator_auth_browser_transactions\n WHERE coordinator_id = ? AND browser_transaction_hash = ?`;\nconst FRESH_HASH = `NOT EXISTS (SELECT 1 FROM coordinator_auth_browser_transactions WHERE coordinator_id = ? AND browser_transaction_hash = ?)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_link_attempts WHERE coordinator_id = ? AND browser_transaction_hash = ?)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_session_receipts WHERE coordinator_id = ? AND browser_transaction_hash = ?)`;\nfunction freshValues(c: CoordinatorAuthBrowserConfig, hash: string): (string | number)[] {\n\treturn [c.coordinatorId, hash, c.coordinatorId, hash, c.coordinatorId, hash];\n}\nconst MATCH_CONFIG =\n\t\"b.coordinator_id = ? AND b.issuer = ? AND b.auth_config_revision = ? AND b.redirect_uri = ?\";\nfunction configValues(c: CoordinatorAuthBrowserConfig): string[] {\n\treturn [c.coordinatorId, c.issuer, c.revision, c.redirectUri];\n}\nfunction assertLinkClaim(\n\ti: CoordinatorAuthBrowserTransactionStartInput & { purpose: \"link\" },\n\tc: CoordinatorAuthBrowserConfig,\n\tnow: number,\n\thash: string,\n): AuthLinkStatement {\n\t// A suppressed claim must violate the pending-secret CHECK inside the same atomic batch.\n\treturn {\n\t\tsql: `UPDATE ${TABLE} AS b SET nonce = NULL WHERE ${MATCH_CONFIG} AND b.browser_transaction_hash = ?\n AND b.state = 'pending' AND b.attempt_id = ? AND b.created_at_ms = ? AND NOT EXISTS\n (SELECT 1 FROM coordinator_auth_link_attempts a WHERE a.coordinator_id = b.coordinator_id AND a.attempt_id = b.attempt_id\n AND (a.authority_kind = 'controller_attestation' OR (a.authority_kind = 'device_claim'\n AND a.controller_attestation_id IS NULL AND a.controller_review_receipt_id IS NULL AND a.controller_revision IS NULL))\n AND a.browser_transaction_hash = b.browser_transaction_hash AND a.state = 'browser_claimed'\n AND a.claimed_at_ms = ? AND a.issuer = b.issuer AND a.auth_config_revision = b.auth_config_revision\n AND a.expires_at_ms = b.expires_at_ms AND a.expires_at_ms > ?)`,\n\t\tvalues: [...configValues(c), hash, i.attemptId, now, now, now],\n\t};\n}\nfunction linkMatch(states: string, source = \"a.authority_kind = 'controller_attestation'\"): string {\n\t// One indexed source row separates its proof tree from the browser match.\n\treturn `(b.purpose = 'signin' OR EXISTS (WITH link_source AS MATERIALIZED (\n SELECT a.* FROM coordinator_auth_link_attempts a WHERE (a.coordinator_id = b.coordinator_id AND a.attempt_id = b.attempt_id) AND (${source}))\n SELECT 1 FROM link_source a WHERE (b.purpose = 'link' AND 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.issuer = b.issuer AND a.auth_config_revision = b.auth_config_revision)\n AND (a.expires_at_ms > ? AND a.state IN (${states}))))`;\n}\n// Retirement only destroys pending browser secrets; it cannot grant authority.\nconst LIVE_LINK = linkMatch(\n\t\"'browser_claimed'\",\n\t`(a.authority_kind = 'controller_attestation' OR\n (a.authority_kind = 'device_claim' AND a.controller_attestation_id IS NULL\n AND a.controller_review_receipt_id IS NULL AND a.controller_revision IS NULL AND a.link_id IS NULL))`,\n);\n\n/** Only the owned zero-row marker is a limit rejection, not counter failure. */\nfunction isBrowserAdmissionNoop(error: unknown): boolean {\n\treturn String(error).includes(\n\t\t\"NOT NULL constraint failed: coordinator_auth_account_connection_orders.coordinator_id\",\n\t);\n}\n/** Persistence capability only; consumed secrets are returned solely to a trusted exchange caller. */\nexport class CoordinatorAuthBrowserTransactions implements CoordinatorAuthBrowserTransactionStore {\n\tconstructor(\n\t\tprivate readonly backend: AuthLinkBackend,\n\t\tprivate readonly clock: () => number = Date.now,\n\t) {}\n\tprivate async first<T>(statement: AuthLinkStatement): Promise<T | null> {\n\t\ttry {\n\t\t\treturn await this.backend.first<T>(statement);\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_browser_transaction_persistence_error\");\n\t\t}\n\t}\n\tasync readAuthBrowserTransactionActivity(\n\t\tinput: { binderHash: string },\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): ReturnType<CoordinatorAuthBrowserTransactionStore[\"readAuthBrowserTransactionActivity\"]> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = capture(input, [\"binderHash\"]);\n\t\tif (!c || !i || !isHash(i.binderHash)) return { kind: \"rejected\", error: \"invalid_input\" };\n\t\tif (!c.enabled) return { kind: \"rejected\", error: \"auth_config_changed\" };\n\t\tconst now = authLinkNow(this.clock);\n\t\t// Shared-cookie activity includes management. Config drift fails closed even\n\t\t// for expired rows; unrelated coordinators never match.\n\t\tif (await hasConnectionSessionSchema(this.backend)) {\n\t\t\tconst management = await this.first<{ changed: number; active: number }>({\n\t\t\t\tsql: `SELECT (issuer <> ? OR auth_config_revision <> ?) AS changed,\n (state IN ('pending','browser_pending','consumed','verified','confirmed') AND expires_at_ms > ?) AS active\n FROM coordinator_account_change_attempts WHERE coordinator_id = ? AND binder_hash = ?`,\n\t\t\t\tvalues: [c.issuer, c.revision, now, c.coordinatorId, i.binderHash],\n\t\t\t});\n\t\t\tif (management?.changed) return { kind: \"rejected\", error: \"auth_config_changed\" };\n\t\t\tif (management?.active) return { kind: \"active\" };\n\t\t}\n\t\tconst row = await this.first<{ activity: string }>({\n\t\t\tsql: `SELECT CASE\n WHEN b.issuer <> ? OR b.auth_config_revision <> ? OR b.redirect_uri <> ? THEN 'config_changed'\n WHEN b.state = 'expired' OR b.expires_at_ms <= ? THEN 'inactive'\n WHEN b.purpose = 'signin' AND b.state = 'consumed' THEN 'inactive'\n WHEN b.purpose = 'link' AND EXISTS (SELECT 1 FROM coordinator_auth_link_attempts a\n WHERE 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.issuer = b.issuer\n AND a.auth_config_revision = b.auth_config_revision\n AND (a.state IN ('finalized','session_redeemed','failed','expired') OR a.expires_at_ms <= ?))\n THEN 'inactive' ELSE 'active' END AS activity\n FROM ${TABLE} b WHERE b.coordinator_id = ? AND b.binder_hash = ?`,\n\t\t\tvalues: [c.issuer, c.revision, c.redirectUri, now, now, c.coordinatorId, i.binderHash],\n\t\t});\n\t\tif (!row || row.activity === \"inactive\") return { kind: \"inactive\" };\n\t\tif (row.activity === \"active\") return { kind: \"active\" };\n\t\treturn { kind: \"rejected\", error: \"auth_config_changed\" };\n\t}\n\tasync startAuthBrowserTransaction(\n\t\tinput: CoordinatorAuthBrowserTransactionStartInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<CoordinatorAuthBrowserTransactionStartResult> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = captureStart(input);\n\t\tif (!c || !i) return rejected(\"invalid_input\");\n\t\tif (!c.enabled) return rejected(\"auth_config_changed\");\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst hash = transactionHash();\n\t\tif (i.purpose === \"link\") return this.startLink(i, c, now, hash, \"desktop\");\n\t\ttry {\n\t\t\tawait orderedBrowserStart(\n\t\t\t\tthis.backend,\n\t\t\t\t[\n\t\t\t\t\t{\n\t\t\t\t\t\tsql: `INSERT INTO ${TABLE} (${COLUMNS}) SELECT ?, ?, 'signin', NULL, ?, ?, ?, ?, ?, 'pending', ?, ?, ?, ?, NULL, NULL\n WHERE ${FRESH_HASH}\n AND NOT EXISTS (SELECT 1 FROM ${PURGE_FLOORS} WHERE coordinator_id = ? AND purged_through_created_at_ms > ?)\n AND (SELECT count(*) FROM ${TABLE} WHERE coordinator_id = ? AND purpose = 'signin' AND created_at_ms > ?) < ?\n AND (SELECT count(*) FROM (SELECT 1 FROM ${TABLE} WHERE coordinator_id = ? AND purpose = 'signin' LIMIT ?)) < ?\n ${ASSERT_HASH_FRESH}`,\n\t\t\t\t\t\tvalues: [\n\t\t\t\t\t\t\tc.coordinatorId,\n\t\t\t\t\t\t\thash,\n\t\t\t\t\t\t\ti.stateHash,\n\t\t\t\t\t\t\ti.binderHash,\n\t\t\t\t\t\t\tc.issuer,\n\t\t\t\t\t\t\tc.revision,\n\t\t\t\t\t\t\tc.redirectUri,\n\t\t\t\t\t\t\ti.nonce,\n\t\t\t\t\t\t\ti.pkceVerifier,\n\t\t\t\t\t\t\tnow,\n\t\t\t\t\t\t\tnow + AUTH_BROWSER_TXN_TTL_MS,\n\t\t\t\t\t\t\t...freshValues(c, hash),\n\t\t\t\t\t\t\tc.coordinatorId,\n\t\t\t\t\t\t\tnow - AUTH_SIGNIN_TXN_WINDOW_MS,\n\t\t\t\t\t\t\tc.coordinatorId,\n\t\t\t\t\t\t\tnow - AUTH_SIGNIN_TXN_WINDOW_MS,\n\t\t\t\t\t\t\tAUTH_SIGNIN_TXN_MAX_STARTS_PER_WINDOW,\n\t\t\t\t\t\t\tc.coordinatorId,\n\t\t\t\t\t\t\tAUTH_SIGNIN_TXN_MAX_RETAINED,\n\t\t\t\t\t\t\tAUTH_SIGNIN_TXN_MAX_RETAINED,\n\t\t\t\t\t\t\tc.coordinatorId,\n\t\t\t\t\t\t\thash,\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tc.coordinatorId,\n\t\t\t\thash,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (isAuthControllerUniqueError(error)) return rejected(\"transaction_conflict\");\n\t\t\tif (!isBrowserAdmissionNoop(error))\n\t\t\t\tthrow authPersistenceError(error, \"auth_browser_transaction_persistence_error\");\n\t\t}\n\t\tconst row = await this.startedRow(i, c, hash, now);\n\t\tif (row) return { kind: \"started\", expiresAtMs: row.expires_at_ms };\n\t\tif (await this.hasConflict(i, c, hash)) return rejected(\"transaction_conflict\");\n\t\tif (await this.isSigninRetentionBlocked(c.coordinatorId, now))\n\t\t\treturn { kind: \"rejected\", error: \"clock_retention_blocked\" };\n\t\treturn rejected(\"transaction_limited\");\n\t}\n\tprivate async isSigninRetentionBlocked(coordinatorId: string, now: number): Promise<boolean> {\n\t\tconst row = await this.first({\n\t\t\tsql: `SELECT 1 FROM ${PURGE_FLOORS} WHERE coordinator_id = ? AND purged_through_created_at_ms > ?`,\n\t\t\tvalues: [coordinatorId, now - AUTH_SIGNIN_TXN_WINDOW_MS],\n\t\t});\n\t\treturn row !== null;\n\t}\n\tprivate async hasConflict(\n\t\ti: CoordinatorAuthBrowserTransactionStartInput,\n\t\tc: CoordinatorAuthBrowserConfig,\n\t\thash: string,\n\t): Promise<boolean> {\n\t\tconst row = await this.first({\n\t\t\tsql: `SELECT 1 FROM ${TABLE} WHERE coordinator_id = ? AND (state_hash = ? OR binder_hash = ? OR browser_transaction_hash = ?)\n UNION ALL SELECT 1 FROM coordinator_auth_link_attempts WHERE coordinator_id = ? AND browser_transaction_hash = ?\n UNION ALL SELECT 1 FROM coordinator_auth_session_receipts WHERE coordinator_id = ? AND browser_transaction_hash = ? LIMIT 1`,\n\t\t\tvalues: [\n\t\t\t\tc.coordinatorId,\n\t\t\t\ti.stateHash,\n\t\t\t\ti.binderHash,\n\t\t\t\thash,\n\t\t\t\tc.coordinatorId,\n\t\t\t\thash,\n\t\t\t\tc.coordinatorId,\n\t\t\t\thash,\n\t\t\t],\n\t\t});\n\t\treturn row !== null;\n\t}\n\tprivate async startedRow(\n\t\ti: CoordinatorAuthBrowserTransactionStartInput,\n\t\tc: CoordinatorAuthBrowserConfig,\n\t\thash: string,\n\t\tnow: number,\n\t): Promise<TransactionRow | null> {\n\t\tconst source = i.purpose === \"link\" ? await this.source(i.attemptId, c, now) : null;\n\t\treturn this.first<TransactionRow>({\n\t\t\tsql: `WITH matching_browser AS MATERIALIZED (SELECT b.* FROM ${TABLE} b WHERE ${MATCH_CONFIG} AND b.browser_transaction_hash = ?\n AND b.state_hash = ? AND b.binder_hash = ? AND b.nonce = ? AND b.pkce_verifier = ?\n AND b.purpose = ? AND b.attempt_id IS ? AND b.created_at_ms = ? AND b.state = 'pending' AND b.expires_at_ms > ?)\n SELECT b.* FROM matching_browser b WHERE ${linkMatch(\"'browser_claimed'\", source?.sql)}`,\n\t\t\tvalues: [\n\t\t\t\t...configValues(c),\n\t\t\t\thash,\n\t\t\t\ti.stateHash,\n\t\t\t\ti.binderHash,\n\t\t\t\ti.nonce,\n\t\t\t\ti.pkceVerifier,\n\t\t\t\ti.purpose,\n\t\t\t\ti.purpose === \"link\" ? i.attemptId : null,\n\t\t\t\tnow,\n\t\t\t\tnow,\n\t\t\t\t...(source?.values ?? []),\n\t\t\t\tnow,\n\t\t\t],\n\t\t});\n\t}\n\t/** The user code hash selects one pending headless attempt; desktop attempts never match. */\n\tasync startHeadlessAuthLinkBrowserTransaction(\n\t\tinput: CoordinatorAuthHeadlessBrowserStartInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<CoordinatorAuthHeadlessBrowserStartResult> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = captureHeadlessStart(input);\n\t\tif (!c || !i) return rejected(\"invalid_input\");\n\t\tif (!c.enabled) return rejected(\"auth_config_changed\");\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst hash = transactionHash();\n\t\tconst attempt = await this.first<{ attempt_id: string }>({\n\t\t\tsql: `SELECT attempt_id FROM coordinator_auth_link_attempts WHERE coordinator_id = ? AND browser_start_hash = ?\n AND loopback_redirect = ${AUTH_LINK_HEADLESS_MARKER_SQL} AND state = 'pending' AND expires_at_ms > ?`,\n\t\t\tvalues: [c.coordinatorId, i.userCodeHash, now],\n\t\t});\n\t\tif (!attempt || !isAuthControllerId(attempt.attempt_id)) return rejected(\"attempt_unavailable\");\n\t\tconst { userCodeHash, ...materials } = i;\n\t\tconst link = {\n\t\t\t...materials,\n\t\t\tpurpose: \"link\" as const,\n\t\t\tattemptId: attempt.attempt_id,\n\t\t\tbrowserStartHash: userCodeHash,\n\t\t};\n\t\tconst started = await this.startLink(link, c, now, hash, \"headless\");\n\t\tif (started.kind !== \"started\") return started;\n\t\treturn { ...started, attemptId: attempt.attempt_id };\n\t}\n\tprivate async startLink(\n\t\ti: CoordinatorAuthBrowserTransactionStartInput & { purpose: \"link\" },\n\t\tc: CoordinatorAuthBrowserConfig,\n\t\tnow: number,\n\t\thash: string,\n\t\tmode: LinkMode,\n\t): Promise<CoordinatorAuthBrowserTransactionStartResult> {\n\t\tconst { source, claimSource } = await this.linkSources(i.attemptId, c, now, mode);\n\t\tconst insert: AuthLinkStatement = {\n\t\t\tsql: `INSERT INTO ${TABLE} (${COLUMNS}) SELECT a.coordinator_id, ?, 'link', a.attempt_id, ?, ?, a.issuer,\n a.auth_config_revision, ?, 'pending', ?, ?, ?, a.expires_at_ms, NULL, NULL FROM coordinator_auth_link_attempts a\n WHERE a.coordinator_id = ? AND a.attempt_id = ? AND a.issuer = ? AND a.auth_config_revision = ?\n AND ${source.sql}\n AND a.state = 'pending' AND a.browser_transaction_hash IS NULL AND a.expires_at_ms > ?\n AND ((a.browser_start_hash IS NULL AND ? IS NULL) OR a.browser_start_hash = ?) AND ${FRESH_HASH}\n ${ASSERT_HASH_FRESH}`,\n\t\t\tvalues: [\n\t\t\t\thash,\n\t\t\t\ti.stateHash,\n\t\t\t\ti.binderHash,\n\t\t\t\tc.redirectUri,\n\t\t\t\ti.nonce,\n\t\t\t\ti.pkceVerifier,\n\t\t\t\tnow,\n\t\t\t\tc.coordinatorId,\n\t\t\t\ti.attemptId,\n\t\t\t\tc.issuer,\n\t\t\t\tc.revision,\n\t\t\t\t...source.values,\n\t\t\t\tnow,\n\t\t\t\ti.browserStartHash ?? null,\n\t\t\t\ti.browserStartHash ?? null,\n\t\t\t\t...freshValues(c, hash),\n\t\t\t\tc.coordinatorId,\n\t\t\t\thash,\n\t\t\t],\n\t\t};\n\t\tconst claim: AuthLinkStatement = {\n\t\t\tsql: `UPDATE coordinator_auth_link_attempts SET state = 'browser_claimed', browser_transaction_hash = ?, claimed_at_ms = ?\n WHERE coordinator_id = ? AND attempt_id = ? AND issuer = ? AND auth_config_revision = ?\n AND ${claimSource.sql}\n AND state = 'pending' AND browser_transaction_hash IS NULL AND expires_at_ms > ?\n AND ((browser_start_hash IS NULL AND ? IS NULL) OR browser_start_hash = ?)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_session_receipts r WHERE r.coordinator_id = ? AND r.browser_transaction_hash = ?)\n AND EXISTS (SELECT 1 FROM ${TABLE} b WHERE ${MATCH_CONFIG} AND b.browser_transaction_hash = ? AND b.attempt_id = ?\n AND b.purpose = 'link' AND b.state = 'pending' AND b.state_hash = ? AND b.binder_hash = ? AND b.created_at_ms = ?\n AND b.expires_at_ms = coordinator_auth_link_attempts.expires_at_ms)`,\n\t\t\tvalues: [\n\t\t\t\thash,\n\t\t\t\tnow,\n\t\t\t\tc.coordinatorId,\n\t\t\t\ti.attemptId,\n\t\t\t\tc.issuer,\n\t\t\t\tc.revision,\n\t\t\t\t...claimSource.values,\n\t\t\t\tnow,\n\t\t\t\ti.browserStartHash ?? null,\n\t\t\t\ti.browserStartHash ?? null,\n\t\t\t\tc.coordinatorId,\n\t\t\t\thash,\n\t\t\t\t...configValues(c),\n\t\t\t\thash,\n\t\t\t\ti.attemptId,\n\t\t\t\ti.stateHash,\n\t\t\t\ti.binderHash,\n\t\t\t\tnow,\n\t\t\t],\n\t\t};\n\t\tconst assertion = assertLinkClaim(i, c, now, hash);\n\t\tconst failure = await this.persistLinkStart([insert, claim, assertion], c.coordinatorId, hash);\n\t\tif (failure) return failure;\n\t\treturn this.startLinkReceipt(i, c, now, hash);\n\t}\n\tprivate async linkSources(\n\t\tattemptId: string,\n\t\tc: CoordinatorAuthBrowserConfig,\n\t\tnow: number,\n\t\tmode: LinkMode,\n\t): Promise<{ source: AuthLinkStatement; claimSource: AuthLinkStatement }> {\n\t\tconst table = \"coordinator_auth_link_attempts\";\n\t\treturn {\n\t\t\tsource: withLinkMode(await this.source(attemptId, c, now), \"a\", mode),\n\t\t\tclaimSource: withLinkMode(await this.source(attemptId, c, now, table), table, mode),\n\t\t};\n\t}\n\tprivate async persistLinkStart(\n\t\tstatements: AuthLinkStatement[],\n\t\tcoordinator: string,\n\t\thash: string,\n\t) {\n\t\ttry {\n\t\t\tawait orderedBrowserStart(this.backend, statements, coordinator, hash);\n\t\t} catch (error) {\n\t\t\tif (isAuthControllerUniqueError(error)) return rejected(\"transaction_conflict\");\n\t\t\t// On the current account schema a link start whose conditional insert wrote no\n\t\t\t// row rolls back at the order stamp; the receipt diagnosis then names the reason.\n\t\t\tif (!isBrowserAdmissionNoop(error))\n\t\t\t\tthrow authPersistenceError(error, \"auth_browser_transaction_persistence_incomplete\");\n\t\t}\n\t\treturn null;\n\t}\n\tprivate async source(\n\t\tattemptId: string,\n\t\tc: CoordinatorAuthBrowserConfig,\n\t\tnow: number,\n\t\talias: \"a\" | \"coordinator_auth_link_attempts\" = \"a\",\n\t) {\n\t\ttry {\n\t\t\tif (this.backend.prepareAuthLinkSource)\n\t\t\t\treturn await this.backend.prepareAuthLinkSource(attemptId, c, now, alias);\n\t\t\treturn await captureAuthLinkSource(this.backend, attemptId, c, now, alias);\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_browser_transaction_persistence_error\");\n\t\t}\n\t}\n\tprivate async browserSource(\n\t\ti: { binderHash: string; stateHash?: string; attemptId?: string },\n\t\tc: CoordinatorAuthBrowserConfig,\n\t\tnow: number,\n\t): Promise<AuthLinkStatement> {\n\t\ttry {\n\t\t\tif (this.backend.prepareAuthLinkBrowserSource)\n\t\t\t\treturn await this.backend.prepareAuthLinkBrowserSource(i, c, now);\n\t\t\treturn await captureAuthLinkBrowserSource(this.backend, i, c, now);\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_browser_transaction_persistence_error\");\n\t\t}\n\t}\n\tprivate async startLinkReceipt(\n\t\ti: CoordinatorAuthBrowserTransactionStartInput & { purpose: \"link\" },\n\t\tc: CoordinatorAuthBrowserConfig,\n\t\tnow: number,\n\t\thash: string,\n\t): Promise<CoordinatorAuthBrowserTransactionStartResult> {\n\t\tconst row = await this.startedRow(i, c, hash, now);\n\t\tif (row) return { kind: \"started\", expiresAtMs: row.expires_at_ms };\n\t\tif (await this.hasConflict(i, c, hash)) return rejected(\"transaction_conflict\");\n\t\treturn this.diagnoseAttempt(i.attemptId, c, now);\n\t}\n\tprivate async diagnoseAttempt(\n\t\tattemptId: string,\n\t\tc: CoordinatorAuthBrowserConfig,\n\t\tnow: number,\n\t): Promise<CoordinatorAuthBrowserTransactionRejected> {\n\t\tconst attempt = await this.first<AttemptDiagnosis>({\n\t\t\tsql: \"SELECT issuer, auth_config_revision, state, expires_at_ms FROM coordinator_auth_link_attempts WHERE coordinator_id = ? AND attempt_id = ? AND authority_kind IN ('controller_attestation','device_claim')\",\n\t\t\tvalues: [c.coordinatorId, attemptId],\n\t\t});\n\t\tif (!attempt) return rejected(\"attempt_unavailable\");\n\t\tif (attempt.state === \"expired\" || attempt.expires_at_ms <= now)\n\t\t\treturn rejected(\"attempt_expired\");\n\t\tif (attempt.issuer !== c.issuer || attempt.auth_config_revision !== c.revision)\n\t\t\treturn rejected(\"auth_config_changed\");\n\t\treturn rejected(\"attempt_unavailable\");\n\t}\n\tasync consumeAuthBrowserTransaction(\n\t\tinput: CoordinatorAuthBrowserTransactionConsumeInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<CoordinatorAuthBrowserTransactionConsumeResult> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = capture(input, [\"stateHash\", \"binderHash\"]);\n\t\tif (!c || !i || !isHash(i.stateHash) || !isHash(i.binderHash)) return rejected(\"invalid_input\");\n\t\tif (!c.enabled) return rejected(\"auth_config_changed\");\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst source = await this.browserSource(\n\t\t\t{ stateHash: i.stateHash, binderHash: i.binderHash },\n\t\t\tc,\n\t\t\tnow,\n\t\t);\n\t\tconst liveLink = linkMatch(\"'browser_claimed'\", source.sql);\n\t\tconst row = await this.first<TransactionRow>({\n\t\t\tsql: `WITH matching_browser AS MATERIALIZED (SELECT b.* FROM ${TABLE} b WHERE ${MATCH_CONFIG} AND b.state_hash = ? AND b.binder_hash = ?\n AND b.state = 'pending' AND b.expires_at_ms > ? AND b.created_at_ms <= ?) SELECT b.* FROM matching_browser b WHERE ${liveLink}`,\n\t\t\tvalues: [...configValues(c), i.stateHash, i.binderHash, now, now, ...source.values, now],\n\t\t});\n\t\tif (!row) return this.diagnoseTransactionConfig(i.stateHash, i.binderHash, c);\n\t\tif (!isConsumableRow(row)) return rejected(\"transaction_unavailable\");\n\t\tconst token = claimToken();\n\t\ttry {\n\t\t\tawait this.backend.run({\n\t\t\t\tsql: `UPDATE ${TABLE} AS b SET state = 'consumed', nonce = NULL, pkce_verifier = NULL, claim_token = ?, consumed_at_ms = ?\n WHERE (${MATCH_CONFIG}) AND (b.browser_transaction_hash = ? AND b.state_hash = ? AND b.binder_hash = ?)\n AND (b.purpose = ? AND b.attempt_id IS ? AND b.state = 'pending' AND b.expires_at_ms > ? AND b.created_at_ms <= ?) AND (b.nonce = ? AND b.pkce_verifier = ?) AND ${liveLink}`,\n\t\t\t\tvalues: [\n\t\t\t\t\ttoken,\n\t\t\t\t\tnow,\n\t\t\t\t\t...configValues(c),\n\t\t\t\t\trow.browser_transaction_hash,\n\t\t\t\t\ti.stateHash,\n\t\t\t\t\ti.binderHash,\n\t\t\t\t\trow.purpose,\n\t\t\t\t\trow.attempt_id,\n\t\t\t\t\tnow,\n\t\t\t\t\tnow,\n\t\t\t\t\trow.nonce,\n\t\t\t\t\trow.pkce_verifier,\n\t\t\t\t\t...source.values,\n\t\t\t\t\tnow,\n\t\t\t\t],\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_browser_transaction_persistence_error\");\n\t\t}\n\t\tconst winner = await this.first({\n\t\t\tsql: `SELECT 1 FROM ${TABLE} WHERE coordinator_id = ? AND browser_transaction_hash = ? AND state = 'consumed' AND claim_token = ?`,\n\t\t\tvalues: [c.coordinatorId, row.browser_transaction_hash, token],\n\t\t});\n\t\tif (!winner) return rejected(\"transaction_unavailable\");\n\t\tconst materials = {\n\t\t\tkind: \"consumed\" as const,\n\t\t\tbrowserTransactionHash: row.browser_transaction_hash,\n\t\t\tnonce: row.nonce,\n\t\t\tpkceVerifier: row.pkce_verifier,\n\t\t};\n\t\tif (row.purpose === \"link\" && row.attempt_id !== null)\n\t\t\treturn { ...materials, purpose: \"link\", attemptId: row.attempt_id };\n\t\tif (row.purpose === \"signin\") return { ...materials, purpose: \"signin\" };\n\t\treturn rejected(\"transaction_unavailable\");\n\t}\n\tasync readAuthBrowserTransactionPurpose(\n\t\tinput: CoordinatorAuthBrowserTransactionConsumeInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<CoordinatorAuthBrowserTransactionPurpose | null> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = capture(input, [\"stateHash\", \"binderHash\"]);\n\t\tif (!c?.enabled || !i || !isHash(i.stateHash) || !isHash(i.binderHash)) return null;\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst source = await this.browserSource(\n\t\t\t{ stateHash: i.stateHash, binderHash: i.binderHash },\n\t\t\tc,\n\t\t\tnow,\n\t\t);\n\t\tconst row = await this.first<{ purpose: string }>({\n\t\t\tsql: `WITH matching_browser AS MATERIALIZED (SELECT b.* FROM ${TABLE} b WHERE ${MATCH_CONFIG} AND b.state_hash = ? AND b.binder_hash = ?\n AND b.state = 'pending' AND b.expires_at_ms > ? AND b.created_at_ms <= ?) SELECT b.purpose FROM matching_browser b WHERE (b.purpose <> 'link' OR ${linkMatch(\"'browser_claimed'\", source.sql)})`,\n\t\t\tvalues: [...configValues(c), i.stateHash, i.binderHash, now, now, ...source.values, now],\n\t\t});\n\t\tif (row?.purpose === \"signin\" || row?.purpose === \"link\" || row?.purpose === \"owner_enroll\")\n\t\t\treturn row.purpose;\n\t\treturn null;\n\t}\n\tprivate async diagnoseTransactionConfig(\n\t\tstateHash: string,\n\t\tbinderHash: string,\n\t\tc: CoordinatorAuthBrowserConfig,\n\t): Promise<CoordinatorAuthBrowserTransactionRejected> {\n\t\tconst row = await this.first<{\n\t\t\tissuer: string;\n\t\t\tauth_config_revision: string;\n\t\t\tredirect_uri: string;\n\t\t}>({\n\t\t\tsql: `SELECT issuer, auth_config_revision, redirect_uri FROM ${TABLE} WHERE coordinator_id = ? AND state_hash = ? AND binder_hash = ?`,\n\t\t\tvalues: [c.coordinatorId, stateHash, binderHash],\n\t\t});\n\t\tif (\n\t\t\trow &&\n\t\t\t(row.issuer !== c.issuer ||\n\t\t\t\trow.auth_config_revision !== c.revision ||\n\t\t\t\trow.redirect_uri !== c.redirectUri)\n\t\t)\n\t\t\treturn rejected(\"auth_config_changed\");\n\t\treturn rejected(\"transaction_unavailable\");\n\t}\n\tasync resolveAuthLinkBrowserTransaction(\n\t\tinput: CoordinatorAuthLinkBrowserTransactionResolveInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<{ browserTransactionHash: string } | null> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = capture(input, [\"attemptId\", \"binderHash\"]);\n\t\tif (!c || !i || !c.enabled || !isAuthControllerId(i.attemptId) || !isHash(i.binderHash))\n\t\t\treturn null;\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst source = await this.browserSource(\n\t\t\t{ attemptId: i.attemptId, binderHash: i.binderHash },\n\t\t\tc,\n\t\t\tnow,\n\t\t);\n\t\tconst row = await this.first<{ browser_transaction_hash: string }>({\n\t\t\tsql: `WITH matching_browser AS MATERIALIZED (SELECT b.* FROM ${TABLE} b WHERE ${MATCH_CONFIG} AND b.purpose = 'link'\n AND b.attempt_id = ? AND b.binder_hash = ? AND b.state IN ('pending','consumed') AND b.expires_at_ms > ?) SELECT b.browser_transaction_hash FROM matching_browser b WHERE ${linkMatch(\"'browser_claimed','oidc_verified','confirmed','finalized','session_redeemed'\", source.sql)}`,\n\t\t\tvalues: [...configValues(c), i.attemptId, i.binderHash, now, ...source.values, now],\n\t\t});\n\t\treturn row ? { browserTransactionHash: row.browser_transaction_hash } : null;\n\t}\n\tasync cancelAuthSigninBrowserTransaction(\n\t\tinput: CoordinatorAuthSigninBrowserTransactionCancelInput,\n\t\tscope: CoordinatorAuthBrowserTransactionScope,\n\t): Promise<CoordinatorAuthSigninBrowserTransactionCancelResult> {\n\t\tconst i = capture(input, [\"binderHash\"]);\n\t\tconst s = capture(scope, [\"coordinatorId\"]);\n\t\tif (!i || !isHash(i.binderHash) || !s || !isAuthControllerId(s.coordinatorId))\n\t\t\treturn { kind: \"rejected\", error: \"invalid_input\" };\n\t\tauthLinkNow(this.clock);\n\t\t// Explicit cookie-owner intent remains valid across clock rollback.\n\t\tconst match =\n\t\t\t\"coordinator_id = ? AND binder_hash = ? AND purpose = 'signin' AND attempt_id IS NULL\";\n\t\tconst values = [s.coordinatorId, i.binderHash];\n\t\ttry {\n\t\t\tawait this.backend.run({\n\t\t\t\tsql: `UPDATE ${TABLE} SET state = 'expired', nonce = NULL, pkce_verifier = NULL\n WHERE ${match} AND state = 'pending'`,\n\t\t\t\tvalues,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_browser_transaction_persistence_error\");\n\t\t}\n\t\tconst row = await this.first({\n\t\t\tsql: `SELECT 1 FROM ${TABLE} WHERE ${match} AND state = 'expired' AND nonce IS NULL AND pkce_verifier IS NULL`,\n\t\t\tvalues,\n\t\t});\n\t\treturn row ? { kind: \"cancelled\" } : { kind: \"unavailable\" };\n\t}\n\tasync retireAuthBrowserTransactions(\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t\toptions?: CoordinatorAuthBrowserTransactionRetirementOptions,\n\t): Promise<CoordinatorAuthBrowserTransactionRetirementResult> {\n\t\tconst c = captureConfig(config);\n\t\tconst o = captureRetirementOptions(options);\n\t\tif (!c || !o) return { kind: \"rejected\", error: \"invalid_input\" };\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst attemptFilter = o.attemptId === undefined ? \"\" : \"AND b.attempt_id = ?\";\n\t\tconst attemptValues = o.attemptId === undefined ? [] : [o.attemptId];\n\t\tlet creationGuard = \"b.created_at_ms <= ?\";\n\t\tconst creationValues = [now];\n\t\tif (o.attemptId !== undefined) {\n\t\t\tcreationGuard = `(b.created_at_ms <= ? OR (b.purpose = 'link' AND NOT ${LIVE_LINK}))`;\n\t\t\tcreationValues.push(now);\n\t\t}\n\t\ttry {\n\t\t\tconst processedCount = await this.backend.run({\n\t\t\t\tsql: `UPDATE ${TABLE} SET state = 'expired', nonce = NULL, pkce_verifier = NULL\n WHERE coordinator_id = ? AND purpose IN ('signin','link') AND state = 'pending' AND browser_transaction_hash IN\n (SELECT b.browser_transaction_hash FROM ${TABLE} b\n WHERE b.coordinator_id = ? AND b.purpose IN ('signin','link') AND b.state = 'pending' AND ${creationGuard} ${attemptFilter}\n AND (b.expires_at_ms <= ? OR ? = 0 OR b.issuer <> ? OR b.auth_config_revision <> ? OR b.redirect_uri <> ?\n OR (b.purpose = 'link' AND NOT ${LIVE_LINK}))\n ORDER BY b.expires_at_ms, b.browser_transaction_hash LIMIT ?)`,\n\t\t\t\tvalues: [\n\t\t\t\t\tc.coordinatorId,\n\t\t\t\t\tc.coordinatorId,\n\t\t\t\t\t...creationValues,\n\t\t\t\t\t...attemptValues,\n\t\t\t\t\tnow,\n\t\t\t\t\tNumber(c.enabled),\n\t\t\t\t\tc.issuer,\n\t\t\t\t\tc.revision,\n\t\t\t\t\tc.redirectUri,\n\t\t\t\t\tnow,\n\t\t\t\t\to.limit,\n\t\t\t\t],\n\t\t\t});\n\t\t\treturn { kind: \"retired\", processedCount, more: processedCount === o.limit };\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_browser_transaction_persistence_error\");\n\t\t}\n\t}\n\tasync purgeAuthSigninBrowserTransactions(\n\t\tscope: CoordinatorAuthBrowserTransactionScope,\n\t\toptions?: CoordinatorAuthBrowserTransactionMaintenanceOptions,\n\t): Promise<CoordinatorAuthSigninBrowserTransactionPurgeResult> {\n\t\tconst s = capture(scope, [\"coordinatorId\"]);\n\t\tconst limit = maintenanceLimit(options, AUTH_SIGNIN_TXN_PURGE_BATCH_MAX);\n\t\tif (!s || !isAuthControllerId(s.coordinatorId) || limit === null)\n\t\t\treturn { kind: \"rejected\", error: \"invalid_input\" };\n\t\tconst cutoff = authLinkNow(this.clock) - AUTH_SIGNIN_TXN_PURGE_AGE_MS;\n\t\ttry {\n\t\t\t// Commit the monotonic floor first; the delete independently reads it atomically.\n\t\t\tawait this.advanceSigninPurgeFloor(s.coordinatorId, cutoff);\n\t\t\tconst processedCount = await this.deletePurgedSigninTransactions(\n\t\t\t\ts.coordinatorId,\n\t\t\t\tcutoff,\n\t\t\t\tlimit,\n\t\t\t);\n\t\t\treturn { kind: \"purged\", processedCount, more: processedCount === limit };\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_browser_transaction_persistence_error\");\n\t\t}\n\t}\n\tprivate advanceSigninPurgeFloor(coordinatorId: string, cutoff: number): Promise<number> {\n\t\treturn this.backend.run({\n\t\t\tsql: `INSERT INTO ${PURGE_FLOORS} (coordinator_id, purged_through_created_at_ms)\n SELECT ?, m FROM (SELECT max(created_at_ms) m FROM ${TABLE}\n WHERE coordinator_id = ? AND purpose = 'signin' AND attempt_id IS NULL AND created_at_ms <= ?)\n WHERE m IS NOT NULL ON CONFLICT(coordinator_id) DO UPDATE\n SET purged_through_created_at_ms = excluded.purged_through_created_at_ms\n WHERE excluded.purged_through_created_at_ms > ${PURGE_FLOORS}.purged_through_created_at_ms`,\n\t\t\tvalues: [coordinatorId, coordinatorId, cutoff],\n\t\t});\n\t}\n\tprivate deletePurgedSigninTransactions(\n\t\tcoordinatorId: string,\n\t\tcutoff: number,\n\t\tlimit: number,\n\t): Promise<number> {\n\t\treturn this.backend.run({\n\t\t\tsql: `DELETE FROM ${TABLE}\n WHERE coordinator_id = ? AND purpose = 'signin' AND attempt_id IS NULL AND created_at_ms <= ?\n AND browser_transaction_hash IN (SELECT b.browser_transaction_hash FROM ${TABLE} b\n JOIN ${PURGE_FLOORS} f ON f.coordinator_id = b.coordinator_id\n WHERE b.coordinator_id = ? AND b.purpose = 'signin' AND b.attempt_id IS NULL\n AND b.created_at_ms <= f.purged_through_created_at_ms AND b.created_at_ms <= ?\n ORDER BY b.created_at_ms, b.browser_transaction_hash LIMIT ?)`,\n\t\t\tvalues: [coordinatorId, cutoff, coordinatorId, cutoff, limit],\n\t\t});\n\t}\n\tasync maintainAuthBrowserTransactions(\n\t\tscope: CoordinatorAuthBrowserTransactionScope,\n\t\toptions?: CoordinatorAuthBrowserTransactionMaintenanceOptions,\n\t): Promise<CoordinatorAuthBrowserTransactionMaintenanceResult> {\n\t\tconst s = capture(scope, [\"coordinatorId\"]);\n\t\tconst limit = maintenanceLimit(options);\n\t\tif (!s || !isAuthControllerId(s.coordinatorId) || limit === null)\n\t\t\treturn { kind: \"rejected\", error: \"invalid_input\" };\n\t\tconst now = authLinkNow(this.clock);\n\t\ttry {\n\t\t\t// Global expiry may burn expired owner secrets; link/config retirement must not.\n\t\t\tconst processedCount = await this.backend.run({\n\t\t\t\tsql: `UPDATE ${TABLE} SET state = 'expired', nonce = NULL, pkce_verifier = NULL\n WHERE coordinator_id = ? AND state = 'pending' AND expires_at_ms <= ? AND browser_transaction_hash IN\n (SELECT browser_transaction_hash FROM ${TABLE} WHERE coordinator_id = ? AND state = 'pending' AND expires_at_ms <= ?\n ORDER BY expires_at_ms, browser_transaction_hash LIMIT ?)`,\n\t\t\t\tvalues: [s.coordinatorId, now, s.coordinatorId, now, limit],\n\t\t\t});\n\t\t\treturn { kind: \"maintained\", processedCount, more: processedCount === limit };\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_browser_transaction_persistence_error\");\n\t\t}\n\t}\n}\n","/** Retained trusted controller rows are ownership evidence even if their Team or\n * enrollment is gone. Weak historical Team assignments are not consulted here.\n */\nexport const AUTH_CONTROLLER_SUBJECT_OWNER_CONFLICT_SQL = `WITH owner_subject(value) AS (SELECT ?)\n SELECT 1 AS conflict FROM coordinator_auth_controller_attestations other CROSS JOIN owner_subject s\n WHERE other.coordinator_id=json_extract(s.value,'$.coordinatorId') AND other.identity_id<>?\n AND (other.device_id=json_extract(s.value,'$.deviceId')\n OR other.public_key=json_extract(s.value,'$.publicKey')\n OR other.public_key IN (SELECT json_extract(j.value,'$.public_key') FROM json_each(s.value,'$.keys') j))\n LIMIT 1`;\n\nexport interface CoordinatorAuthControllerOwnerSnapshot {\n\tpurpose: \"existing_account_owner\";\n\tcoordinatorId: string;\n\ttargetIdentityId: string;\n\tissuer: string;\n\tlinkId: string;\n\tauthConfigRevision: string;\n\tcreatedAtMs: number;\n}\n","import { CONNECTION_NOT_REVOKED_SQL } from \"./coordinator-account-connection-storage.js\";\nimport type { CoordinatorAuthControllerReviewInput } from \"./coordinator-auth-controller.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport { authAccountLinkProvenanceSql } from \"./coordinator-auth-link-provenance.js\";\nimport { type AuthRead, readSnapshot } from \"./coordinator-auth-read-set.js\";\nimport { controllerHistoryReads } from \"./coordinator-owner-negative-reads.js\";\nimport { sqlEq } from \"./coordinator-sql-compare.js\";\n\n/**\n * Read-set form of the controller review's snapshot, history and owner checks. The old\n * statements carried them as WITH stages that production D1 refuses. Here each is a plain\n * read, the decision compares it with the reviewed snapshot in TypeScript, and the guards\n * pin what was read to the statement that writes or answers.\n *\n * The checks on the enrollment row itself stay in the statements, with bound values.\n */\n\ntype Values = AuthLinkStatement[\"values\"];\ntype Review = CoordinatorAuthControllerReviewInput;\n\n/** Every ordinary pin the old statements carried besides the snapshot stages. */\nconst AUTHORITY_GUARD = `\n\tAND e.group_id = ? AND e.device_id = ? AND e.public_key = ?\n\tAND e.fingerprint = ? AND e.identity_id IS ?\n\tAND NOT EXISTS (SELECT 1 FROM coordinator_device_revocations WHERE\n\t\t(subject_kind = 'device_id' AND subject_value = ?) OR\n\t\t(subject_kind = 'ed25519_key' AND subject_value = ?))`;\nconst SUBJECT = `FROM enrolled_devices e JOIN groups g ON g.group_id = e.group_id\n\tWHERE e.group_id = ? AND e.device_id = ? AND e.enabled = 1 AND g.archived_at IS NULL\n\t\tAND e.public_key = ? AND e.fingerprint = ? AND (e.identity_id IS NULL OR e.identity_id = ?)`;\nconst CURRENT = `SELECT a.* FROM coordinator_auth_controller_attestations a\n\tJOIN enrolled_devices e ON e.group_id = a.group_id AND e.device_id = a.device_id\n\tJOIN groups g ON g.group_id = a.group_id\n\tWHERE a.coordinator_id = ? AND a.attestation_id = ? AND a.revoked_at IS NULL\n\t\tAND e.enabled = 1 AND g.archived_at IS NULL AND e.public_key = a.public_key\n\t\tAND e.fingerprint = a.fingerprint\n\t\tAND (e.identity_id IS NULL OR e.identity_id = a.identity_id)`;\n\n/** The enrollment-row checks the snapshot made: its label and the history's subject. */\nfunction snapshotRowChecks(review: Review): { sql: string; values: Values } {\n\tconst snapshot = review.verifiedSnapshot;\n\tif (!snapshot) return { sql: \"\", values: [] };\n\tconst history = snapshot.legacyHistory;\n\treturn {\n\t\tsql: ` AND e.identity_id IS ?${history ? \" AND e.device_id = ? AND e.public_key = ? AND e.fingerprint = ?\" : \"\"}`,\n\t\tvalues: [\n\t\t\tsnapshot.enrollmentIdentityId,\n\t\t\t...(history ? [history.deviceId, history.publicKey, history.fingerprint] : []),\n\t\t],\n\t};\n}\n\nexport interface ControllerStatementOptions {\n\t/**\n\t * Also admit the enrollment label the review accepted as weak. Only the explicit owner\n\t * resolution passes it; the snapshot and authority checks still pin that exact label.\n\t */\n\treviewedLabel?: boolean;\n}\n\nfunction subject(\n\treview: Review,\n\toptions: ControllerStatementOptions,\n): { sql: string; values: Values } {\n\tconst values = [\n\t\treview.groupId,\n\t\treview.deviceId,\n\t\treview.publicKey,\n\t\treview.fingerprint,\n\t\treview.identityId,\n\t];\n\tif (!options.reviewedLabel) return { sql: SUBJECT, values };\n\tif (!review.verifiedSnapshot?.accountOwnerTarget)\n\t\tthrow new Error(\"account_owner_authority_unavailable\");\n\treturn {\n\t\tsql: SUBJECT.replace(\n\t\t\t\"(e.identity_id IS NULL OR e.identity_id = ?)\",\n\t\t\t\"(e.identity_id IS NULL OR e.identity_id = ? OR e.identity_id IS ?)\",\n\t\t),\n\t\tvalues: [...values, review.verifiedSnapshot.enrollmentIdentityId],\n\t};\n}\n\n/** The controller insert, with no WITH stage. */\nexport function controllerInsertStatement(\n\treview: Review,\n\tcreatedAt: string,\n\tauthority: Values,\n\toptions: ControllerStatementOptions = {},\n): AuthLinkStatement {\n\tconst rows = snapshotRowChecks(review);\n\tconst source = subject(review, options);\n\treturn {\n\t\tsql: `INSERT INTO coordinator_auth_controller_attestations (\n\t\tattestation_id, coordinator_id, identity_id, group_id, device_id, public_key,\n\t\tfingerprint, review_receipt_id, evidence_digest, enrollment_identity_id, revision, created_at, revoked_at\n\t)\n\tSELECT ?, ?, ?, e.group_id, e.device_id, e.public_key, e.fingerprint, ?, ?, e.identity_id, 1, ?, NULL\n\t${source.sql}${rows.sql} ${AUTHORITY_GUARD}`,\n\t\tvalues: [\n\t\t\treview.attestationId,\n\t\t\treview.coordinatorId,\n\t\t\treview.identityId,\n\t\t\treview.reviewReceiptId,\n\t\t\treview.evidenceDigest,\n\t\t\tcreatedAt,\n\t\t\t...source.values,\n\t\t\t...rows.values,\n\t\t\t...authority,\n\t\t],\n\t};\n}\n\n/** Whether the reviewed enrollment may still be attested, with no WITH stage. */\nexport function controllerEligibleStatement(\n\treview: Review,\n\tauthority: Values,\n\toptions: ControllerStatementOptions = {},\n): AuthLinkStatement {\n\tconst rows = snapshotRowChecks(review);\n\tconst source = subject(review, options);\n\treturn {\n\t\tsql: `SELECT 1 AS eligible ${source.sql}${rows.sql} ${AUTHORITY_GUARD}`,\n\t\tvalues: [...source.values, ...rows.values, ...authority],\n\t};\n}\n\n/** The current attestation checked against live authority, with no WITH stage. */\nexport function controllerActiveStatement(review: Review, authority: Values): AuthLinkStatement {\n\tconst rows = snapshotRowChecks(review);\n\treturn {\n\t\tsql: `${CURRENT} ${AUTHORITY_GUARD}${rows.sql}`,\n\t\tvalues: [review.coordinatorId, review.attestationId, ...authority, ...rows.values],\n\t};\n}\n\nconst INVITES_READ = `SELECT json_array(i.invite_id, i.invite_kind, i.recipient_actor_id,\n\ti.assigned_identity_id, i.target_identity_id, i.reviewed_preview_digest) AS row\n\tFROM coordinator_invites i\n\tWHERE i.group_id = ? AND i.bound_device_id = ? AND i.bound_public_key = ?\n\t\tAND i.bound_fingerprint = ? AND i.revoked_at IS NULL\n\t\tAND i.consumed_at IS NOT NULL AND i.consumed_at != ''\n\t\tAND i.invite_kind IN ('team_member', 'add_device')\n\tORDER BY row`;\n\n// The account owner target's links, each with 0/1 verdicts: it still proves its creation,\n// and neither it nor its Identity's connection history is revoked.\nconst OWNER_LINKS_READ = `SELECT json_object('link_id',l.link_id,\n 'proven',${authAccountLinkProvenanceSql(\"l\", { connections: true })},\n 'live',(${CONNECTION_NOT_REVOKED_SQL})) AS row\n FROM coordinator_auth_account_links l\n WHERE l.coordinator_id=? AND l.identity_id=? AND l.issuer=? AND l.link_id=?\n AND l.auth_config_revision=? AND l.created_at_ms=? ORDER BY l.link_id`;\n// Claims of this enrollment that disagree with the owner target.\nconst OWNER_CLAIM_CONFLICTS_READ = `SELECT json_object('claim_id',d.claim_id) AS row\n FROM coordinator_auth_device_claims d\n WHERE d.coordinator_id=? AND (d.device_id=? OR d.key_id=?)\n AND (d.identity_id<>? OR d.group_id<>? OR d.device_id<>? OR d.public_key<>? OR d.fingerprint<>?)\n ORDER BY d.claim_id`;\n// Controller reviews that disagree: of this enrollment, or of its device or key family\n// for another Identity.\nconst OWNER_CONTROLLER_CONFLICTS_READ = `SELECT json_object('attestation_id',other.attestation_id) AS row\n FROM coordinator_auth_controller_attestations other\n WHERE other.coordinator_id=? AND ((other.group_id=? AND other.device_id=? AND other.fingerprint=?\n AND (other.identity_id<>? OR other.public_key<>? OR other.revoked_at IS NOT NULL))\n OR (other.identity_id<>? AND (other.device_id=? OR other.public_key=?\n OR other.public_key IN (SELECT value FROM json_each(?)))))\n ORDER BY other.attestation_id`;\n\n/** The owner target's reads, bound to the enrollment the review pins. */\nfunction ownerReads(review: Review, authority: Values): Record<string, AuthRead> {\n\tconst target = review.verifiedSnapshot?.accountOwnerTarget;\n\tif (!target) return {};\n\tconst keyId = authority[authority.length - 1];\n\tif (typeof keyId !== \"string\" || keyId.length === 0)\n\t\tthrow new Error(\"account_owner_authority_unavailable\");\n\tconst [group = null, device = null, publicKey = null, fingerprint = null] = authority;\n\tconst keys = review.verifiedSnapshot?.legacyHistory?.keys.map((key) => key.public_key) ?? [];\n\tconst owner = target.targetIdentityId;\n\treturn {\n\t\townerLinks: {\n\t\t\tsql: OWNER_LINKS_READ,\n\t\t\tvalues: [\n\t\t\t\ttarget.coordinatorId,\n\t\t\t\towner,\n\t\t\t\ttarget.issuer,\n\t\t\t\ttarget.linkId,\n\t\t\t\ttarget.authConfigRevision,\n\t\t\t\ttarget.createdAtMs,\n\t\t\t],\n\t\t},\n\t\townerClaimConflicts: {\n\t\t\tsql: OWNER_CLAIM_CONFLICTS_READ,\n\t\t\tvalues: [target.coordinatorId, device, keyId, owner, group, device, publicKey, fingerprint],\n\t\t},\n\t\townerControllerConflicts: {\n\t\t\tsql: OWNER_CONTROLLER_CONFLICTS_READ,\n\t\t\tvalues: [\n\t\t\t\ttarget.coordinatorId,\n\t\t\t\tgroup,\n\t\t\t\tdevice,\n\t\t\t\tfingerprint,\n\t\t\t\towner,\n\t\t\t\tpublicKey,\n\t\t\t\towner,\n\t\t\t\tdevice,\n\t\t\t\tpublicKey,\n\t\t\t\tJSON.stringify(keys),\n\t\t\t],\n\t\t},\n\t};\n}\n\n/** The reads behind the reviewed snapshot. None without a snapshot. */\nexport function controllerReviewReads(review: Review, authority: Values): Record<string, AuthRead> {\n\tconst snapshot = review.verifiedSnapshot;\n\tif (!snapshot) return {};\n\treturn {\n\t\tinvites: {\n\t\t\tsql: INVITES_READ,\n\t\t\tvalues: [review.groupId, review.deviceId, review.publicKey, review.fingerprint],\n\t\t},\n\t\t...(snapshot.legacyHistory ? controllerHistoryReads(snapshot.legacyHistory) : {}),\n\t\t...ownerReads(review, authority),\n\t};\n}\n\nconst rowSet = (rows: unknown[]) => JSON.stringify(rows.map((row) => JSON.stringify(row)).sort());\n\n/**\n * Whether the live rows still match the reviewed snapshot: the same consumed invites,\n * the same legacy history and keys, and an owner target that is still allowed.\n */\nexport function decideControllerReview(review: Review, rows: Record<string, unknown[]>): boolean {\n\tconst snapshot = review.verifiedSnapshot;\n\tif (!snapshot) return true;\n\tconst invites = snapshot.invites.map((i) => [\n\t\ti.inviteId,\n\t\ti.kind,\n\t\ti.actorId,\n\t\ti.assignedIdentityId,\n\t\ti.targetIdentityId,\n\t\ti.digest,\n\t]);\n\tif (rowSet(rows.invites ?? []) !== rowSet(invites)) return false;\n\tconst history = snapshot.legacyHistory;\n\tif (history) {\n\t\tconst expected = {\n\t\t\thistory: history.records.map((r) => [\n\t\t\t\tr.group_id,\n\t\t\t\tr.candidate_ref,\n\t\t\t\tr.manifest_version,\n\t\t\t\tr.completed_at,\n\t\t\t\tr.created_at,\n\t\t\t\tr.manifest_json,\n\t\t\t]),\n\t\t\thistoryKeys: history.keys.map((key) => [key.public_key, key.fingerprint]),\n\t\t\thistoryDiscovery: history.discoveryKeys.map((key) => [key]),\n\t\t};\n\t\tfor (const [name, values] of Object.entries(expected))\n\t\t\tif (rowSet(rows[name] ?? []) !== rowSet(values)) return false;\n\t}\n\tif (!snapshot.accountOwnerTarget) return true;\n\tconst links = (rows.ownerLinks ?? []) as { proven?: number | null; live?: number | null }[];\n\tconst linked = links.some((link) => sqlEq(link.proven ?? null, 1) && sqlEq(link.live ?? null, 1));\n\treturn linked && !rows.ownerClaimConflicts?.length && !rows.ownerControllerConflicts?.length;\n}\n\nexport interface ControllerReviewAuthority {\n\t/** False when the live rows no longer match the reviewed snapshot. */\n\tallowed: boolean;\n\t/** Re-run every read. They lead the batch that writes or answers. */\n\tguards: AuthLinkStatement[];\n}\n\n/** Reads and decides the reviewed snapshot for one controller review. */\nexport async function readControllerReview(\n\tbackend: Pick<AuthLinkBackend, \"first\" | \"readBatch\">,\n\treview: Review,\n\tauthority: Values,\n): Promise<ControllerReviewAuthority> {\n\tconst facts = await readSnapshot<Record<string, unknown[]>>(\n\t\tbackend,\n\t\tcontrollerReviewReads(review, authority),\n\t);\n\treturn {\n\t\tallowed: decideControllerReview(review, facts.rows),\n\t\tguards: Object.values(facts.guards),\n\t};\n}\n\n/** The same decision inside an open SQLite transaction, from reads built beforehand. */\nexport function decideControllerReviewSync(\n\tall: (read: AuthRead) => { row: string }[],\n\treview: Review,\n\treads: Record<string, AuthRead>,\n): boolean {\n\tconst rows = Object.fromEntries(\n\t\tObject.entries(reads).map(([name, read]) => [\n\t\t\tname,\n\t\t\tall(read).map(({ row }) => JSON.parse(row) as unknown),\n\t\t]),\n\t);\n\treturn decideControllerReview(review, rows);\n}\n","import { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport { hashEd25519KeyId } from \"./coordinator-ed25519-key-id.js\";\nimport {\n\ted25519KeyIdForRevocation,\n\tparseSshEd25519PublicKeyForRevocation,\n} from \"./coordinator-ed25519-key-id-compat.js\";\n\nexport interface CoordinatorDeviceRevocationRecord {\n\treadonly subject_kind: \"device_id\" | \"ed25519_key\";\n\treadonly subject_value: string;\n\treadonly revocation_id: string;\n\treadonly evidence_group_id: string;\n\treadonly evidence_device_id: string;\n\treadonly evidence_public_key: string;\n\treadonly evidence_fingerprint: string;\n\treadonly actor_id: string | null;\n\treadonly created_at: string;\n}\n\nexport interface CoordinatorCreateDeviceRevocationInput {\n\tgroupId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n\t/** Audit evidence only; this internal capability requires a trusted caller. */\n\tactorId?: string | null;\n}\nexport interface CoordinatorListDeviceRevocationsInput {\n\tdeviceId?: string;\n\tpublicKey?: string;\n}\nexport interface CoordinatorRecordAuthorizedNonceInput {\n\tgroupId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tnonce: string;\n\tcreatedAt: string;\n}\nexport type CoordinatorCreateDeviceRevocationResult =\n\t| { kind: \"revoked\"; records: CoordinatorDeviceRevocationRecord[] }\n\t| { kind: \"rejected\"; error: \"invalid_input\" | \"enrollment_mismatch\" };\nexport type CoordinatorAuthorizedNonceResult =\n\t| \"recorded\"\n\t| \"nonce_replay\"\n\t| \"device_revoked\"\n\t| \"unknown_device\"\n\t| \"device_disabled\"\n\t| \"group_not_found\"\n\t| \"group_archived\";\n\nexport interface CoordinatorDeviceRevocationStore {\n\tcreateDeviceRevocation(\n\t\tinput: CoordinatorCreateDeviceRevocationInput,\n\t): Promise<CoordinatorCreateDeviceRevocationResult>;\n\tlistDeviceRevocations(\n\t\tinput: CoordinatorListDeviceRevocationsInput,\n\t): Promise<CoordinatorDeviceRevocationRecord[]>;\n\trecordAuthorizedNonce(\n\t\tinput: CoordinatorRecordAuthorizedNonceInput,\n\t): Promise<CoordinatorAuthorizedNonceResult>;\n}\n\nexport const DEVICE_REVOCATION_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS coordinator_device_revocations (\n subject_kind TEXT NOT NULL CHECK(subject_kind IN ('device_id', 'ed25519_key')),\n subject_value TEXT NOT NULL CHECK(\n (subject_kind = 'device_id' AND length(subject_value) BETWEEN 1 AND 256) OR\n (subject_kind = 'ed25519_key' AND length(subject_value) = 64\n AND subject_value NOT GLOB '*[^a-f0-9]*')),\n revocation_id TEXT NOT NULL,\n evidence_group_id TEXT NOT NULL,\n evidence_device_id TEXT NOT NULL,\n evidence_public_key TEXT NOT NULL,\n evidence_fingerprint TEXT NOT NULL,\n actor_id TEXT,\n created_at TEXT NOT NULL,\n PRIMARY KEY (subject_kind, subject_value)\n);\n`;\n\ninterface RevocationStatement {\n\tsql: string;\n\tvalues: (string | null)[];\n\tread?: boolean;\n}\nexport interface DeviceRevocationBackend {\n\t/** All statements, including reads, execute in one transaction. */\n\tbatch(statements: RevocationStatement[]): Promise<unknown[]>;\n\tall(statement: RevocationStatement): Promise<unknown>;\n}\n\nconst INVALID_SCALAR = Symbol(\"invalid_input\");\nfunction own(input: unknown, key: string): unknown {\n\tif (!input || typeof input !== \"object\" || Array.isArray(input)) return undefined;\n\tconst descriptor = Object.getOwnPropertyDescriptor(input, key);\n\tif (!descriptor) return undefined;\n\treturn \"value\" in descriptor ? descriptor.value : INVALID_SCALAR;\n}\nfunction exactText(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length > 0 && !value.includes(\"\\0\");\n}\nfunction captureRevocation(\n\tinput: unknown,\n): Readonly<Required<CoordinatorCreateDeviceRevocationInput>> | null {\n\tconst groupId = own(input, \"groupId\"),\n\t\tdeviceId = own(input, \"deviceId\");\n\tconst publicKey = own(input, \"publicKey\"),\n\t\tfingerprint = own(input, \"fingerprint\");\n\tconst actorId = own(input, \"actorId\") ?? null;\n\tif (\n\t\t!isAuthControllerId(groupId) ||\n\t\t!isAuthControllerId(deviceId) ||\n\t\t!exactText(publicKey) ||\n\t\t!exactText(fingerprint) ||\n\t\t(actorId !== null && !isAuthControllerId(actorId))\n\t)\n\t\treturn null;\n\treturn Object.freeze({ groupId, deviceId, publicKey, fingerprint, actorId });\n}\nfunction captureNonce(input: unknown): Readonly<CoordinatorRecordAuthorizedNonceInput> {\n\tconst groupId = own(input, \"groupId\"),\n\t\tdeviceId = own(input, \"deviceId\");\n\tconst publicKey = own(input, \"publicKey\"),\n\t\tnonce = own(input, \"nonce\");\n\tconst createdAt = own(input, \"createdAt\");\n\tif (\n\t\t!exactText(groupId) ||\n\t\t!exactText(deviceId) ||\n\t\t!exactText(publicKey) ||\n\t\t!exactText(nonce) ||\n\t\t!exactText(createdAt)\n\t)\n\t\tthrow new Error(\"invalid_input\");\n\treturn Object.freeze({ groupId, deviceId, publicKey, nonce, createdAt });\n}\nfunction resultRows<T>(result: unknown): T[] {\n\tif (\n\t\t!result ||\n\t\ttypeof result !== \"object\" ||\n\t\t(\"success\" in result && result.success === false) ||\n\t\t!(\"results\" in result) ||\n\t\t!Array.isArray(result.results)\n\t)\n\t\tthrow new Error(\"device_revocation_incomplete\");\n\treturn result.results as T[];\n}\nfunction resultChanges(result: unknown): number {\n\tif (\n\t\t!result ||\n\t\ttypeof result !== \"object\" ||\n\t\t(\"success\" in result && result.success === false) ||\n\t\t!(\"meta\" in result) ||\n\t\t!result.meta ||\n\t\ttypeof result.meta !== \"object\" ||\n\t\t!(\"changes\" in result.meta) ||\n\t\t!Number.isSafeInteger(result.meta.changes) ||\n\t\t(result.meta.changes as number) < 0\n\t)\n\t\tthrow new Error(\"device_revocation_incomplete\");\n\treturn result.meta.changes as number;\n}\n\nfunction incompleteResult(): never {\n\tthrow new Error(\"device_revocation_incomplete\");\n}\n\nconst CURRENT_TUPLE_SQL = `SELECT 1 FROM enrolled_devices\nWHERE group_id = ? AND device_id = ? AND public_key = ? AND fingerprint = ?`;\n/** Bind the device ID and derived canonical key ID (or null), in that order. */\nexport const DEVICE_REVOCATION_SUBJECT_EXISTS_SQL = `EXISTS (\nSELECT 1 FROM coordinator_device_revocations WHERE\n(subject_kind = 'device_id' AND subject_value = ?) OR\n(subject_kind = 'ed25519_key' AND subject_value = ?))`;\nconst SUBJECTS_SQL = `SELECT * FROM coordinator_device_revocations WHERE\n(subject_kind = 'device_id' AND subject_value = ?) OR\n(subject_kind = 'ed25519_key' AND subject_value = ?)\nORDER BY subject_kind, subject_value`;\nconst NONCE_CONTEXT_SQL = `WITH input(group_id, device_id, public_key, nonce, created_at, key_id)\nAS (VALUES (?, ?, ?, ?, ?, ?))`;\nconst REVOKED_SQL = `EXISTS (SELECT 1 FROM coordinator_device_revocations r WHERE\n(r.subject_kind = 'device_id' AND r.subject_value = i.device_id) OR\n(r.subject_kind = 'ed25519_key' AND r.subject_value = i.key_id))`;\nconst AUTHORIZED_NONCE_SQL = `${NONCE_CONTEXT_SQL}\nINSERT INTO request_nonces(device_id, nonce, created_at)\nSELECT i.device_id, i.nonce, i.created_at FROM input i\nJOIN enrolled_devices e ON e.group_id = i.group_id AND e.device_id = i.device_id\nJOIN groups g ON g.group_id = i.group_id\nWHERE e.public_key = i.public_key AND e.enabled = 1 AND g.archived_at IS NULL\nAND NOT ${REVOKED_SQL}\nON CONFLICT(device_id, nonce) DO NOTHING`;\nconst NONCE_CLASSIFY_SQL = `${NONCE_CONTEXT_SQL}\nSELECT CASE\nWHEN ${REVOKED_SQL} THEN 'device_revoked'\nWHEN g.group_id IS NULL THEN 'group_not_found'\nWHEN g.archived_at IS NOT NULL THEN 'group_archived'\nWHEN e.device_id IS NULL OR e.public_key != i.public_key THEN 'unknown_device'\nWHEN e.enabled != 1 THEN 'device_disabled'\nELSE 'nonce_replay' END AS status\nFROM input i LEFT JOIN groups g ON g.group_id = i.group_id\nLEFT JOIN enrolled_devices e ON e.group_id = i.group_id AND e.device_id = i.device_id`;\n\nfunction revocationStatements(\n\tinput: Required<CoordinatorCreateDeviceRevocationInput>,\n\tkeyId: string | null,\n\tnow: string,\n): RevocationStatement[] {\n\tconst tuple = [input.groupId, input.deviceId, input.publicKey, input.fingerprint];\n\tconst subjects = [{ kind: \"device_id\", value: input.deviceId }];\n\tif (keyId) subjects.push({ kind: \"ed25519_key\", value: keyId });\n\tconst revocationId = globalThis.crypto.randomUUID();\n\tconst writes = subjects.map(({ kind, value }) => ({\n\t\tsql: `INSERT INTO coordinator_device_revocations(subject_kind, subject_value, revocation_id,\nevidence_group_id, evidence_device_id, evidence_public_key, evidence_fingerprint, actor_id, created_at)\nSELECT ?, ?, ?, ?, ?, ?, ?, ?, ? WHERE EXISTS (${CURRENT_TUPLE_SQL})\nON CONFLICT(subject_kind, subject_value) DO NOTHING`,\n\t\tvalues: [kind, value, revocationId, ...tuple, input.actorId, now, ...tuple],\n\t}));\n\treturn [\n\t\t{ sql: CURRENT_TUPLE_SQL, values: tuple, read: true },\n\t\t...writes,\n\t\t{ sql: SUBJECTS_SQL, values: [input.deviceId, keyId], read: true },\n\t];\n}\n\n/** Internal storage capability only. Removal of the current tuple prevents creation and retry. */\nexport class DeviceRevocationOperations implements CoordinatorDeviceRevocationStore {\n\tconstructor(\n\t\tprivate readonly backend: DeviceRevocationBackend,\n\t\tprivate readonly clock: () => number = Date.now,\n\t) {}\n\n\tasync createDeviceRevocation(\n\t\traw: CoordinatorCreateDeviceRevocationInput,\n\t): Promise<CoordinatorCreateDeviceRevocationResult> {\n\t\tconst input = captureRevocation(raw);\n\t\tif (!input) return { kind: \"rejected\", error: \"invalid_input\" };\n\t\tconst keyId = await ed25519KeyIdForRevocation(input.publicKey);\n\t\tconst statements = revocationStatements(input, keyId, new Date(this.clock()).toISOString());\n\t\tconst results = await this.backend.batch(statements).catch(incompleteResult);\n\t\tif (results.length !== statements.length) throw new Error(\"device_revocation_incomplete\");\n\t\tfor (const result of results.slice(1, -1)) resultChanges(result);\n\t\tif (resultRows(results[0]).length === 0)\n\t\t\treturn { kind: \"rejected\", error: \"enrollment_mismatch\" };\n\t\tconst records = resultRows<CoordinatorDeviceRevocationRecord>(results.at(-1));\n\t\tif (\n\t\t\t!records.some((r) => r.subject_kind === \"device_id\" && r.subject_value === input.deviceId) ||\n\t\t\t(keyId && !records.some((r) => r.subject_kind === \"ed25519_key\" && r.subject_value === keyId))\n\t\t)\n\t\t\tthrow new Error(\"device_revocation_incomplete\");\n\t\treturn { kind: \"revoked\", records };\n\t}\n\n\tasync listDeviceRevocations(\n\t\tinput: CoordinatorListDeviceRevocationsInput,\n\t): Promise<CoordinatorDeviceRevocationRecord[]> {\n\t\tconst deviceId = own(input, \"deviceId\"),\n\t\t\tpublicKey = own(input, \"publicKey\");\n\t\tif (\n\t\t\t(deviceId !== undefined && !isAuthControllerId(deviceId)) ||\n\t\t\t(publicKey !== undefined && !exactText(publicKey)) ||\n\t\t\t(deviceId === undefined && publicKey === undefined)\n\t\t)\n\t\t\tthrow new Error(\"invalid_input\");\n\t\tconst keyId =\n\t\t\tpublicKey === undefined ? null : await ed25519KeyIdForRevocation(publicKey as string);\n\t\treturn resultRows<CoordinatorDeviceRevocationRecord>(\n\t\t\tawait this.backend\n\t\t\t\t.all({\n\t\t\t\t\tsql: SUBJECTS_SQL,\n\t\t\t\t\tvalues: [(deviceId as string | undefined) ?? null, keyId],\n\t\t\t\t\tread: true,\n\t\t\t\t})\n\t\t\t\t.catch(incompleteResult),\n\t\t);\n\t}\n\n\tasync recordAuthorizedNonce(\n\t\traw: CoordinatorRecordAuthorizedNonceInput,\n\t): Promise<CoordinatorAuthorizedNonceResult> {\n\t\tconst input = captureNonce(raw);\n\t\tconst parsedKey = parseSshEd25519PublicKeyForRevocation(input.publicKey);\n\t\tif (parsedKey.kind === \"malformed_ed25519\") return \"unknown_device\";\n\t\tconst keyId = await hashEd25519KeyId(parsedKey);\n\t\tconst values = [\n\t\t\tinput.groupId,\n\t\t\tinput.deviceId,\n\t\t\tinput.publicKey,\n\t\t\tinput.nonce,\n\t\t\tinput.createdAt,\n\t\t\tkeyId,\n\t\t];\n\t\tconst results = await this.backend\n\t\t\t.batch([\n\t\t\t\t{ sql: AUTHORIZED_NONCE_SQL, values },\n\t\t\t\t{ sql: NONCE_CLASSIFY_SQL, values, read: true },\n\t\t\t])\n\t\t\t.catch(incompleteResult);\n\t\tif (results.length !== 2) throw new Error(\"device_revocation_incomplete\");\n\t\tconst changes = resultChanges(results[0]);\n\t\tconst rows = resultRows<{ status: CoordinatorAuthorizedNonceResult }>(results[1]);\n\t\tif (rows.length !== 1 || changes > 1) throw new Error(\"device_revocation_incomplete\");\n\t\tif (changes === 1) return \"recorded\";\n\t\tconst status = rows[0]?.status;\n\t\tif (\n\t\t\t!status ||\n\t\t\t![\n\t\t\t\t\"nonce_replay\",\n\t\t\t\t\"device_revoked\",\n\t\t\t\t\"unknown_device\",\n\t\t\t\t\"device_disabled\",\n\t\t\t\t\"group_not_found\",\n\t\t\t\t\"group_archived\",\n\t\t\t].includes(status)\n\t\t)\n\t\t\tthrow new Error(\"device_revocation_incomplete\");\n\t\treturn status;\n\t}\n}\n","import { DEVICE_REVOCATION_SUBJECT_EXISTS_SQL } from \"./coordinator-device-revocation.js\";\nimport type {\n\tCoordinatorBootstrapGrant,\n\tCoordinatorBootstrapGrantAuthorizationError,\n\tCoordinatorBootstrapGrantAuthorizationInput,\n\tCoordinatorBootstrapGrantAuthorizationResult,\n\tCoordinatorEnrollment,\n} from \"./coordinator-store-contract.js\";\n\nconst ENROLLMENT_FIELDS = [\n\t\"group_id\",\n\t\"device_id\",\n\t\"public_key\",\n\t\"fingerprint\",\n\t\"identity_id\",\n\t\"display_name\",\n\t\"enabled\",\n\t\"created_at\",\n] as const;\ntype EnrollmentFields = Pick<CoordinatorEnrollment, (typeof ENROLLMENT_FIELDS)[number]>;\ntype ParticipantAliases<P extends string> = {\n\t[K in keyof EnrollmentFields as `${P}_${K}`]: EnrollmentFields[K] | null;\n};\nexport type BootstrapAuthorizationRow = CoordinatorBootstrapGrant &\n\tParticipantAliases<\"seed_enrollment\"> &\n\tParticipantAliases<\"worker_enrollment\"> & {\n\t\ttarget_group_id: string | null;\n\t\tarchived_at: string | null;\n\t\tstatus?: CoordinatorBootstrapGrantAuthorizationError | \"authorized\";\n\t};\n\nconst COLUMNS_SQL = `b.grant_id, b.group_id, b.seed_device_id, b.worker_device_id,\nb.expires_at, b.created_at, b.created_by, b.revoked_at,\ng.group_id AS target_group_id, g.archived_at,\n${ENROLLMENT_FIELDS.map((f) => `s.${f} AS seed_enrollment_${f}, w.${f} AS worker_enrollment_${f}`).join(\", \")}`;\nconst JOINS_SQL = `FROM coordinator_bootstrap_grants b\nLEFT JOIN groups g ON g.group_id = b.group_id\nLEFT JOIN enrolled_devices s ON s.group_id = b.group_id AND s.device_id = b.seed_device_id\nLEFT JOIN enrolled_devices w ON w.group_id = b.group_id AND w.device_id = b.worker_device_id`;\nexport const BOOTSTRAP_AUTHORIZATION_SOURCE_SQL = `SELECT ${COLUMNS_SQL}\n${JOINS_SQL} WHERE b.grant_id = ?`;\n\nfunction own(input: unknown, key: string): unknown {\n\tif (!input || typeof input !== \"object\" || Array.isArray(input)) return undefined;\n\tconst descriptor = Object.getOwnPropertyDescriptor(input, key);\n\tif (!descriptor) return undefined;\n\tif (!(\"value\" in descriptor)) throw new Error(\"invalid_input\");\n\treturn descriptor.value;\n}\nfunction text(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length > 0 && !value.includes(\"\\0\");\n}\n\n/** Capture every caller-owned primitive before even the source read can yield. */\nexport function captureBootstrapAuthorizationInput(\n\traw: unknown,\n): CoordinatorBootstrapGrantAuthorizationInput {\n\tconst grantId = own(raw, \"grantId\"),\n\t\tnowMs = own(raw, \"nowMs\");\n\tif (!text(grantId) || typeof nowMs !== \"number\" || !Number.isSafeInteger(nowMs) || nowMs < 0)\n\t\tthrow new Error(\"invalid_input\");\n\tconst expectation = own(raw, \"expectedSeed\");\n\tif (expectation === undefined) return { grantId, nowMs };\n\tconst groupId = own(expectation, \"groupId\"),\n\t\tdeviceId = own(expectation, \"deviceId\");\n\tconst publicKey = own(expectation, \"publicKey\"),\n\t\tfingerprint = own(expectation, \"fingerprint\");\n\tif (!text(groupId) || !text(deviceId) || !text(publicKey) || !text(fingerprint))\n\t\tthrow new Error(\"invalid_input\");\n\treturn { grantId, nowMs, expectedSeed: { groupId, deviceId, publicKey, fingerprint } };\n}\n\nexport function rejectBootstrapAuthorization(\n\terror: CoordinatorBootstrapGrantAuthorizationError,\n): CoordinatorBootstrapGrantAuthorizationResult {\n\treturn { kind: \"rejected\", error };\n}\n\nexport function bootstrapAuthorizationSourceError(\n\tinput: CoordinatorBootstrapGrantAuthorizationInput,\n\trow: BootstrapAuthorizationRow | null,\n): CoordinatorBootstrapGrantAuthorizationError | null {\n\tif (!row?.target_group_id) return \"grant_not_found\";\n\tconst expected = input.expectedSeed;\n\tif (\n\t\texpected &&\n\t\t(expected.groupId !== row.group_id ||\n\t\t\texpected.deviceId !== row.seed_device_id ||\n\t\t\texpected.publicKey !== row.seed_enrollment_public_key ||\n\t\t\texpected.fingerprint !== row.seed_enrollment_fingerprint)\n\t)\n\t\treturn \"grant_not_found\";\n\treturn null;\n}\n\nfunction participant(\n\trow: BootstrapAuthorizationRow,\n\tprefix: \"seed_enrollment\" | \"worker_enrollment\",\n): CoordinatorEnrollment {\n\tconst group_id = row[`${prefix}_group_id`],\n\t\tdevice_id = row[`${prefix}_device_id`];\n\tconst public_key = row[`${prefix}_public_key`],\n\t\tfingerprint = row[`${prefix}_fingerprint`];\n\tconst identity_id = row[`${prefix}_identity_id`],\n\t\tdisplay_name = row[`${prefix}_display_name`];\n\tconst enabled = row[`${prefix}_enabled`],\n\t\tcreated_at = row[`${prefix}_created_at`];\n\tif (\n\t\t!text(group_id) ||\n\t\t!text(device_id) ||\n\t\t!text(public_key) ||\n\t\t!text(fingerprint) ||\n\t\t(identity_id !== null && typeof identity_id !== \"string\") ||\n\t\t(display_name !== null && typeof display_name !== \"string\") ||\n\t\tenabled !== 1 ||\n\t\t!text(created_at)\n\t)\n\t\tthrow new Error(\"bootstrap_authorization_unavailable\");\n\treturn {\n\t\tgroup_id,\n\t\tdevice_id,\n\t\tpublic_key,\n\t\tfingerprint,\n\t\tidentity_id,\n\t\tdisplay_name,\n\t\tenabled,\n\t\tcreated_at,\n\t};\n}\n\nconst EXPLICIT_OFFSET_EXPIRY =\n\t/^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d{1,9})?(?:Z|[+-](\\d{2}):(\\d{2}))$/;\n\n/** Parse an explicit-zone timestamp without accepting normalized invalid calendar dates. */\nexport function parseBootstrapExpiry(value: unknown): number {\n\tif (typeof value !== \"string\") return Number.NaN;\n\tconst parts = EXPLICIT_OFFSET_EXPIRY.exec(value);\n\tif (!parts) return Number.NaN;\n\tconst year = Number(parts[1]);\n\tconst month = Number(parts[2]);\n\tconst day = Number(parts[3]);\n\tconst hour = Number(parts[4]);\n\tconst minute = Number(parts[5]);\n\tconst second = Number(parts[6]);\n\tconst offsetHour = Number(parts[7] ?? 0);\n\tconst offsetMinute = Number(parts[8] ?? 0);\n\tconst leapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n\tconst februaryDays = leapYear ? 29 : 28;\n\tconst monthDays = [31, februaryDays, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\tif (month < 1 || month > 12 || day < 1 || day > (monthDays[month - 1] ?? 0)) {\n\t\treturn Number.NaN;\n\t}\n\tif (hour > 23 || minute > 59 || second > 59 || offsetHour > 23 || offsetMinute > 59) {\n\t\treturn Number.NaN;\n\t}\n\treturn Date.parse(value);\n}\n\n// The revocation subjects remain the captured participants even if their keys disappear or rotate.\n// Success pins both tuples and the exact expiry text whose parsed milliseconds were validated.\nexport function bootstrapAuthorizationDecision(\n\tinput: CoordinatorBootstrapGrantAuthorizationInput,\n\trow: BootstrapAuthorizationRow,\n\tkeys: { seed: string | null; worker: string | null },\n) {\n\tconst expiryMs = parseBootstrapExpiry(row.expires_at);\n\tconst expiryValid = Number.isFinite(expiryMs);\n\tconst expected = input.expectedSeed;\n\treturn {\n\t\tsql: `SELECT ${COLUMNS_SQL}, CASE\nWHEN g.group_id IS NULL THEN 'grant_not_found'\nWHEN ? = 1 AND (b.group_id IS NOT ? OR b.seed_device_id IS NOT ?) THEN 'grant_not_found'\nWHEN ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL} OR ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL} THEN 'device_revoked'\nWHEN b.revoked_at IS NOT NULL THEN 'grant_revoked'\nWHEN g.archived_at IS NOT NULL THEN 'group_archived'\nWHEN b.group_id IS NOT ? OR b.seed_device_id IS NOT ? OR b.worker_device_id IS NOT ?\n OR b.expires_at IS NOT ? OR b.revoked_at IS NOT ? THEN 'bootstrap_authorization_unavailable'\nWHEN s.device_id IS NULL OR s.enabled != 1 THEN 'seed_enrollment_not_found'\nWHEN w.device_id IS NULL OR w.enabled != 1 THEN 'worker_enrollment_not_found'\nWHEN s.public_key IS NOT ? OR s.fingerprint IS NOT ? OR s.identity_id IS NOT ?\n OR s.group_id IS NOT ? OR s.device_id IS NOT ? OR s.enabled IS NOT ?\n OR w.public_key IS NOT ? OR w.fingerprint IS NOT ? OR w.identity_id IS NOT ?\n OR w.group_id IS NOT ? OR w.device_id IS NOT ? OR w.enabled IS NOT ? THEN 'bootstrap_authorization_unavailable'\nWHEN ? = 0 THEN 'bootstrap_authorization_unavailable'\nWHEN ? <= ? THEN 'grant_expired'\nELSE 'authorized' END AS status\n${JOINS_SQL} WHERE b.grant_id = ?`,\n\t\tvalues: [\n\t\t\texpected ? 1 : 0,\n\t\t\texpected?.groupId ?? null,\n\t\t\texpected?.deviceId ?? null,\n\t\t\trow.seed_device_id,\n\t\t\tkeys.seed,\n\t\t\trow.worker_device_id,\n\t\t\tkeys.worker,\n\t\t\trow.group_id,\n\t\t\trow.seed_device_id,\n\t\t\trow.worker_device_id,\n\t\t\trow.expires_at,\n\t\t\trow.revoked_at,\n\t\t\trow.seed_enrollment_public_key,\n\t\t\trow.seed_enrollment_fingerprint,\n\t\t\trow.seed_enrollment_identity_id,\n\t\t\trow.seed_enrollment_group_id,\n\t\t\trow.seed_enrollment_device_id,\n\t\t\trow.seed_enrollment_enabled,\n\t\t\trow.worker_enrollment_public_key,\n\t\t\trow.worker_enrollment_fingerprint,\n\t\t\trow.worker_enrollment_identity_id,\n\t\t\trow.worker_enrollment_group_id,\n\t\t\trow.worker_enrollment_device_id,\n\t\t\trow.worker_enrollment_enabled,\n\t\t\texpiryValid ? 1 : 0,\n\t\t\texpiryValid ? expiryMs : 0,\n\t\t\tinput.nowMs,\n\t\t\tinput.grantId,\n\t\t],\n\t};\n}\n\nexport function bootstrapAuthorizationResult(\n\trow: BootstrapAuthorizationRow | null,\n): CoordinatorBootstrapGrantAuthorizationResult {\n\tif (!row) return rejectBootstrapAuthorization(\"bootstrap_authorization_unavailable\");\n\tif (row.status !== \"authorized\") {\n\t\tconst errors: CoordinatorBootstrapGrantAuthorizationError[] = [\n\t\t\t\"grant_not_found\",\n\t\t\t\"seed_enrollment_not_found\",\n\t\t\t\"worker_enrollment_not_found\",\n\t\t\t\"grant_revoked\",\n\t\t\t\"grant_expired\",\n\t\t\t\"group_archived\",\n\t\t\t\"device_revoked\",\n\t\t\t\"bootstrap_authorization_unavailable\",\n\t\t];\n\t\tif (!row.status || !errors.includes(row.status))\n\t\t\treturn rejectBootstrapAuthorization(\"bootstrap_authorization_unavailable\");\n\t\treturn rejectBootstrapAuthorization(row.status);\n\t}\n\tconst grant: CoordinatorBootstrapGrant = {\n\t\tgrant_id: row.grant_id,\n\t\tgroup_id: row.group_id,\n\t\tseed_device_id: row.seed_device_id,\n\t\tworker_device_id: row.worker_device_id,\n\t\texpires_at: row.expires_at,\n\t\tcreated_at: row.created_at,\n\t\tcreated_by: row.created_by,\n\t\trevoked_at: row.revoked_at,\n\t};\n\treturn {\n\t\tkind: \"authorized\",\n\t\tauthorizationVersion: 1,\n\t\tgrant,\n\t\tseedEnrollment: participant(row, \"seed_enrollment\"),\n\t\tworkerEnrollment: participant(row, \"worker_enrollment\"),\n\t};\n}\n","import { DEVICE_REVOCATION_SUBJECT_EXISTS_SQL } from \"./coordinator-device-revocation.js\";\nimport type { CoordinatorCreateBootstrapGrantInput } from \"./coordinator-store-contract.js\";\n\nexport interface BootstrapParticipantSource {\n\tpublic_key: string;\n\tfingerprint: string;\n\tidentity_id: string | null;\n}\n\n// Disabled enrollment still supplies key metadata; raw issuance is not authorization.\nexport const BOOTSTRAP_PARTICIPANT_SOURCE_SQL = `SELECT public_key, fingerprint, identity_id\n\tFROM enrolled_devices WHERE group_id = ? AND device_id = ?`;\nexport const BOOTSTRAP_PARTICIPANTS_REVOKED_SQL = `SELECT 1 WHERE\n\t${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL} OR ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}`;\n\nconst PINNED_PARTICIPANT_SQL = `((? = 0 AND NOT EXISTS (\n\tSELECT 1 FROM enrolled_devices WHERE group_id = ? AND device_id = ?))\n\tOR (? = 1 AND EXISTS (SELECT 1 FROM enrolled_devices\n\t\tWHERE group_id = ? AND device_id = ? AND public_key IS ?\n\t\tAND fingerprint IS ? AND identity_id IS ?)))`;\n\nexport const BOOTSTRAP_RAW_INSERT_SQL = `INSERT INTO coordinator_bootstrap_grants(\n\tgrant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n) SELECT ?, ?, ?, ?, ?, ?, ?, NULL\nWHERE ${PINNED_PARTICIPANT_SQL} AND ${PINNED_PARTICIPANT_SQL}\nAND NOT (${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL} OR ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL})\nRETURNING grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at`;\n\nexport function captureBootstrapParticipantSource(source: BootstrapParticipantSource | null) {\n\tif (!source) return null;\n\tif (\n\t\ttypeof source.public_key !== \"string\" ||\n\t\ttypeof source.fingerprint !== \"string\" ||\n\t\t(source.identity_id !== null && typeof source.identity_id !== \"string\")\n\t) {\n\t\tthrow new Error(\"bootstrap_grant_write_incomplete\");\n\t}\n\treturn {\n\t\tpublic_key: source.public_key,\n\t\tfingerprint: source.fingerprint,\n\t\tidentity_id: source.identity_id,\n\t};\n}\n\nfunction participantPinValues(\n\tgroupId: string,\n\tdeviceId: string,\n\tsource: BootstrapParticipantSource | null,\n) {\n\tconst present = source ? 1 : 0;\n\treturn [\n\t\tpresent,\n\t\tgroupId,\n\t\tdeviceId,\n\t\tpresent,\n\t\tgroupId,\n\t\tdeviceId,\n\t\tsource?.public_key ?? null,\n\t\tsource?.fingerprint ?? null,\n\t\tsource?.identity_id ?? null,\n\t];\n}\n\nexport function bootstrapRawInsertValues(\n\tinput: CoordinatorCreateBootstrapGrantInput,\n\tgrant: { grantId: string; createdAt: string },\n\tparticipants: {\n\t\tseed: BootstrapParticipantSource | null;\n\t\tworker: BootstrapParticipantSource | null;\n\t},\n\trevocationValues: (string | null)[],\n) {\n\treturn [\n\t\tgrant.grantId,\n\t\tinput.groupId,\n\t\tinput.seedDeviceId,\n\t\tinput.workerDeviceId,\n\t\tinput.expiresAt,\n\t\tgrant.createdAt,\n\t\tinput.createdBy ?? null,\n\t\t...participantPinValues(input.groupId, input.seedDeviceId, participants.seed),\n\t\t...participantPinValues(input.groupId, input.workerDeviceId, participants.worker),\n\t\t...revocationValues,\n\t];\n}\n","import type { AuthLinkBackend } from \"./coordinator-auth-link.js\";\n\n/**\n * Storage for ADR 0005 Section 8 rebinding: an enrolled device whose current\n * Identity has no account link of its own moves to the Identity linked to the\n * Google account it signs in with. A self-bind keeps the device's Identity\n * (target = current). Controller-only connections pin their server authority at\n * start before fresh OIDC and browser consent. Both tables are additive. They never change\n * the owner-enrollment tables, whose schema readiness checks compare exact DDL.\n *\n * Mirror: packages/cloudflare-coordinator-worker/migrations/0038_add_device_rebind.sql\n */\nexport const COORDINATOR_DEVICE_REBIND_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS coordinator_device_rebind_attempts (\n coordinator_id TEXT NOT NULL,\n attempt_id TEXT NOT NULL,\n origin TEXT NOT NULL,\n device_id TEXT NOT NULL,\n public_key TEXT NOT NULL,\n key_id TEXT NOT NULL CHECK (length(key_id) = 64 AND key_id NOT GLOB '*[^0-9a-f]*'),\n fingerprint TEXT NOT NULL,\n current_identity_id TEXT NOT NULL CHECK (length(current_identity_id) BETWEEN 1 AND 256),\n issuer TEXT NOT NULL,\n auth_config_revision TEXT NOT NULL,\n loopback_redirect TEXT,\n browser_start_hash TEXT NOT NULL UNIQUE,\n browser_transaction_hash TEXT UNIQUE,\n browser_binder_hash TEXT,\n account_subject TEXT,\n target_identity_id TEXT,\n link_id TEXT,\n link_authority_kind TEXT CHECK (link_authority_kind IS NULL\n OR link_authority_kind IN ('controller_attestation', 'device_claim')),\n review_digest TEXT CHECK (review_digest IS NULL\n OR (length(review_digest) = 64 AND review_digest NOT GLOB '*[^0-9a-f]*')),\n team_effects_json TEXT CHECK (team_effects_json IS NULL OR json_valid(team_effects_json)),\n enrollment_count INTEGER CHECK (enrollment_count IS NULL OR enrollment_count BETWEEN 1 AND 50),\n confirmation_hash TEXT,\n completion_secret_hash TEXT UNIQUE,\n final_key_proof_hash TEXT,\n state TEXT NOT NULL CHECK (state IN\n ('pending', 'browser_claimed', 'oidc_verified', 'confirmed', 'finalized', 'expired', 'failed')),\n created_at_ms INTEGER NOT NULL,\n expires_at_ms INTEGER NOT NULL CHECK (expires_at_ms = created_at_ms + 600000),\n finalized_at_ms INTEGER,\n binding_id TEXT UNIQUE,\n audit_event_id TEXT UNIQUE,\n final_outcome_json TEXT CHECK (final_outcome_json IS NULL OR json_valid(final_outcome_json)),\n start_authority_json TEXT CHECK (start_authority_json IS NULL OR json_valid(start_authority_json)),\n PRIMARY KEY (coordinator_id, attempt_id),\n CHECK (state NOT IN ('confirmed', 'finalized') OR (account_subject IS NOT NULL\n AND target_identity_id IS NOT NULL AND link_id IS NOT NULL AND link_authority_kind IS NOT NULL\n AND review_digest IS NOT NULL AND team_effects_json IS NOT NULL AND enrollment_count IS NOT NULL\n AND confirmation_hash IS NOT NULL AND completion_secret_hash IS NOT NULL)),\n CHECK (state <> 'finalized' OR (finalized_at_ms IS NOT NULL AND binding_id IS NOT NULL\n AND audit_event_id IS NOT NULL AND final_key_proof_hash IS NOT NULL\n AND final_outcome_json IS NOT NULL AND loopback_redirect IS NULL)),\n CHECK (state = 'finalized' OR (finalized_at_ms IS NULL AND binding_id IS NULL\n AND audit_event_id IS NULL AND final_key_proof_hash IS NULL AND final_outcome_json IS NULL)),\n CHECK (state NOT IN ('pending', 'browser_claimed', 'oidc_verified')\n OR (confirmation_hash IS NULL AND completion_secret_hash IS NULL)),\n CHECK (state NOT IN ('pending', 'browser_claimed') OR (account_subject IS NULL\n AND target_identity_id IS NULL AND link_id IS NULL AND link_authority_kind IS NULL\n AND team_effects_json IS NULL AND enrollment_count IS NULL)),\n CHECK (review_digest IS NOT NULL),\n CHECK (state <> 'pending' OR (browser_transaction_hash IS NULL AND browser_binder_hash IS NULL))\n);\n\nCREATE INDEX IF NOT EXISTS idx_coordinator_device_rebind_attempts_device\n ON coordinator_device_rebind_attempts (coordinator_id, device_id, state);\n\n-- Birth facts never change; proofs are set once; only forward transitions are allowed.\n-- The EXISTS clause stops UPDATE OR REPLACE from deleting another row through a unique key.\nCREATE TRIGGER IF NOT EXISTS coordinator_device_rebind_attempt_pins\nBEFORE UPDATE ON coordinator_device_rebind_attempts\nWHEN OLD.state IN ('finalized', 'expired', 'failed') OR NEW.rowid IS NOT OLD.rowid\n OR EXISTS (SELECT 1 FROM coordinator_device_rebind_attempts o\n WHERE NOT (o.coordinator_id = OLD.coordinator_id AND o.attempt_id = OLD.attempt_id)\n AND (o.browser_transaction_hash = NEW.browser_transaction_hash\n OR o.completion_secret_hash = NEW.completion_secret_hash\n OR o.binding_id = NEW.binding_id OR o.audit_event_id = NEW.audit_event_id))\n OR NEW.coordinator_id IS NOT OLD.coordinator_id OR NEW.attempt_id IS NOT OLD.attempt_id\n OR NEW.origin IS NOT OLD.origin OR NEW.device_id IS NOT OLD.device_id\n OR NEW.public_key IS NOT OLD.public_key OR NEW.key_id IS NOT OLD.key_id\n OR NEW.fingerprint IS NOT OLD.fingerprint OR NEW.current_identity_id IS NOT OLD.current_identity_id\n OR NEW.issuer IS NOT OLD.issuer OR NEW.auth_config_revision IS NOT OLD.auth_config_revision\n OR NEW.browser_start_hash IS NOT OLD.browser_start_hash\n OR NEW.start_authority_json IS NOT OLD.start_authority_json\n OR NEW.created_at_ms IS NOT OLD.created_at_ms OR NEW.expires_at_ms IS NOT OLD.expires_at_ms\n OR (OLD.browser_transaction_hash IS NOT NULL AND NEW.browser_transaction_hash IS NOT OLD.browser_transaction_hash)\n OR (OLD.browser_binder_hash IS NOT NULL AND NEW.browser_binder_hash IS NOT OLD.browser_binder_hash)\n OR (OLD.account_subject IS NOT NULL AND NEW.account_subject IS NOT OLD.account_subject)\n OR (OLD.target_identity_id IS NOT NULL AND NEW.target_identity_id IS NOT OLD.target_identity_id)\n OR (OLD.link_id IS NOT NULL AND NEW.link_id IS NOT OLD.link_id)\n OR (OLD.review_digest IS NOT NULL AND NEW.review_digest IS NOT OLD.review_digest)\n OR (OLD.team_effects_json IS NOT NULL AND NEW.team_effects_json IS NOT OLD.team_effects_json)\n OR (OLD.enrollment_count IS NOT NULL AND NEW.enrollment_count IS NOT OLD.enrollment_count)\n OR (OLD.confirmation_hash IS NOT NULL AND NEW.confirmation_hash IS NOT OLD.confirmation_hash)\n OR (OLD.completion_secret_hash IS NOT NULL AND NEW.completion_secret_hash IS NOT OLD.completion_secret_hash)\n OR (NEW.loopback_redirect IS NOT OLD.loopback_redirect\n AND NOT (NEW.loopback_redirect IS NULL AND NEW.state IN ('finalized', 'expired', 'failed')))\n OR NOT ((OLD.state = NEW.state)\n OR (OLD.state = 'pending' AND NEW.state IN ('browser_claimed', 'expired', 'failed'))\n OR (OLD.state = 'browser_claimed' AND NEW.state IN ('oidc_verified', 'expired', 'failed'))\n OR (OLD.state = 'oidc_verified' AND NEW.state IN ('confirmed', 'expired', 'failed'))\n OR (OLD.state = 'confirmed' AND NEW.state IN ('finalized', 'expired', 'failed')))\nBEGIN\n SELECT RAISE(ABORT, 'device_rebind_attempt_immutable');\nEND;\n\n-- REPLACE's implicit deletes may skip DELETE triggers when recursive triggers are off.\nCREATE TRIGGER IF NOT EXISTS coordinator_device_rebind_attempt_insert_collision\nBEFORE INSERT ON coordinator_device_rebind_attempts\nWHEN EXISTS (SELECT 1 FROM coordinator_device_rebind_attempts\n WHERE rowid = NEW.rowid OR (coordinator_id = NEW.coordinator_id AND attempt_id = NEW.attempt_id)\n OR browser_start_hash = NEW.browser_start_hash\n OR browser_transaction_hash = NEW.browser_transaction_hash\n OR completion_secret_hash = NEW.completion_secret_hash\n OR binding_id = NEW.binding_id OR audit_event_id = NEW.audit_event_id)\nBEGIN\n SELECT RAISE(ABORT, 'device_rebind_attempt_collision');\nEND;\n\n-- An automatic rowid reads as -1 before insert; positive rowids keep that from matching a row.\nCREATE TRIGGER IF NOT EXISTS coordinator_device_rebind_attempt_rowid\nAFTER INSERT ON coordinator_device_rebind_attempts\nWHEN NEW.rowid < 1\nBEGIN\n SELECT RAISE(ABORT, 'device_rebind_attempt_rowid');\nEND;\n\nCREATE TRIGGER IF NOT EXISTS coordinator_device_rebind_attempt_retained\nBEFORE DELETE ON coordinator_device_rebind_attempts\nWHEN OLD.state = 'finalized'\nBEGIN\n SELECT RAISE(ABORT, 'device_rebind_attempt_immutable');\nEND;\n\nCREATE TABLE IF NOT EXISTS coordinator_device_rebind_audit_log (\n coordinator_id TEXT NOT NULL,\n event_id TEXT NOT NULL,\n attempt_id TEXT NOT NULL,\n action TEXT NOT NULL CHECK (action = 'owner_device_rebound'),\n binding_id TEXT NOT NULL,\n device_id TEXT NOT NULL,\n previous_identity_id TEXT NOT NULL,\n target_identity_id TEXT NOT NULL,\n enrollment_count INTEGER NOT NULL CHECK (enrollment_count BETWEEN 1 AND 50),\n created_at_ms INTEGER NOT NULL,\n PRIMARY KEY (coordinator_id, event_id),\n UNIQUE (coordinator_id, attempt_id)\n);\n\nCREATE INDEX IF NOT EXISTS idx_coordinator_device_rebind_audit_target\n ON coordinator_device_rebind_audit_log (coordinator_id, target_identity_id, created_at_ms);\n\nCREATE TRIGGER IF NOT EXISTS coordinator_device_rebind_audit_insert_collision\nBEFORE INSERT ON coordinator_device_rebind_audit_log\nWHEN EXISTS (SELECT 1 FROM coordinator_device_rebind_audit_log\n WHERE rowid = NEW.rowid\n OR (coordinator_id = NEW.coordinator_id AND (event_id = NEW.event_id OR attempt_id = NEW.attempt_id)))\nBEGIN\n SELECT RAISE(ABORT, 'device_rebind_audit_collision');\nEND;\n\nCREATE TRIGGER IF NOT EXISTS coordinator_device_rebind_audit_rowid\nAFTER INSERT ON coordinator_device_rebind_audit_log\nWHEN NEW.rowid < 1\nBEGIN\n SELECT RAISE(ABORT, 'device_rebind_audit_rowid');\nEND;\n\nCREATE TRIGGER IF NOT EXISTS coordinator_device_rebind_audit_immutable_update\nBEFORE UPDATE ON coordinator_device_rebind_audit_log\nBEGIN\n SELECT RAISE(ABORT, 'device_rebind_audit_immutable');\nEND;\n\nCREATE TRIGGER IF NOT EXISTS coordinator_device_rebind_audit_immutable_delete\nBEFORE DELETE ON coordinator_device_rebind_audit_log\nBEGIN\n SELECT RAISE(ABORT, 'device_rebind_audit_immutable');\nEND;\n`;\n\nconst PRE_RELEASE_ATTEMPT_OBJECTS = [\n\t\"TRIGGER coordinator_device_rebind_attempt_pins\",\n\t\"TRIGGER coordinator_device_rebind_attempt_insert_collision\",\n\t\"TRIGGER coordinator_device_rebind_attempt_rowid\",\n\t\"TRIGGER coordinator_device_rebind_attempt_retained\",\n\t\"INDEX idx_coordinator_device_rebind_attempts_device\",\n\t\"TABLE coordinator_device_rebind_attempts\",\n];\n\n/**\n * The first pre-release attempts table forbade a review digest before OIDC,\n * but the ceremony pins it at start. A coordinator that opened that build has\n * the old table; recreate it while it is still empty (nothing wrote attempts\n * before the routes shipped). With rows present it is left as is and starts\n * fail closed.\n */\nexport function upgradePreReleaseRebindAttemptsSql(\n\texistingTableSql: string | null,\n\trows: number,\n): string | null {\n\tif (\n\t\t!existingTableSql ||\n\t\texistingTableSql.includes(\"CHECK (review_digest IS NOT NULL)\") ||\n\t\trows > 0\n\t)\n\t\treturn null;\n\treturn PRE_RELEASE_ATTEMPT_OBJECTS.map(\n\t\t(object) => `DROP ${object.replace(\" \", \" IF EXISTS \")};`,\n\t).join(\"\\n\");\n}\n\nconst REBIND_SCHEMA_PRESENT_SQL = `SELECT\n EXISTS (SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'coordinator_device_rebind_attempts'\n AND instr(sql, 'CHECK (review_digest IS NOT NULL)') > 0)\n AND EXISTS (SELECT 1 FROM pragma_table_info('coordinator_device_rebind_attempts')\n WHERE name = 'start_authority_json') AS attempts,\n EXISTS (SELECT 1 FROM sqlite_master WHERE type = 'table'\n AND name = 'coordinator_device_rebind_audit_log') AS audit`;\n\n/**\n * The backend, only when this database has the current rebind tables. Without\n * them (including D1 before migration 0044) rebind routes report not found\n * and the shared OIDC callback skips the rebind hook.\n */\nexport async function readDeviceRebindBackend(\n\tbackend: AuthLinkBackend,\n): Promise<AuthLinkBackend | null> {\n\tconst present = await backend.first<{ attempts: number; audit: number }>({\n\t\tsql: REBIND_SCHEMA_PRESENT_SQL,\n\t\tvalues: [],\n\t});\n\treturn present?.attempts === 1 && present.audit === 1 ? backend : null;\n}\n\nconst ATTEMPTS_TABLE = \"coordinator_device_rebind_attempts\";\nconst REBUILT_TABLE = `${ATTEMPTS_TABLE}_rebuilt`;\n\nfunction attemptStatements() {\n\tconst sql = COORDINATOR_DEVICE_REBIND_SCHEMA_SQL;\n\tconst table = sql.match(\n\t\t/CREATE TABLE IF NOT EXISTS coordinator_device_rebind_attempts \\([\\s\\S]*?\\n\\);/,\n\t)?.[0];\n\tconst index = sql.match(\n\t\t/CREATE INDEX IF NOT EXISTS idx_coordinator_device_rebind_attempts_device[\\s\\S]*?;/,\n\t)?.[0];\n\tconst triggers = sql.match(\n\t\t/CREATE TRIGGER IF NOT EXISTS coordinator_device_rebind_attempt_\\w+[\\s\\S]*?\\nEND;/g,\n\t);\n\tif (!table || !index || triggers?.length !== 4) throw new Error(\"device_rebind_schema_unparsed\");\n\treturn { table, index, triggers };\n}\n\n/**\n * Rebuilds the attempts table without the first release's \"target differs\n * from current\" CHECK, which self-binds need. Rows, the index and every\n * trigger are kept. Mirror: migrations/0040_allow_device_self_bind.sql.\n */\nexport function rebuildRebindAttemptsForSelfBindSql(): string {\n\tconst { table, index, triggers } = attemptStatements();\n\t// 0040 predates the additive authority column. Keep its historical shape.\n\tconst historicalTable = table.replace(/\\n start_authority_json TEXT[^\\n]+,/, \"\");\n\tconst historicalTriggers = triggers.map((sql) =>\n\t\tsql.replace(/\\n OR NEW.start_authority_json IS NOT OLD.start_authority_json/, \"\"),\n\t);\n\tconst names = triggers.map((t) => t.match(/coordinator_device_rebind_attempt_\\w+/)?.[0]);\n\treturn [\n\t\t...names.map((name) => `DROP TRIGGER IF EXISTS ${name};`),\n\t\t\"DROP INDEX IF EXISTS idx_coordinator_device_rebind_attempts_device;\",\n\t\thistoricalTable.replace(\n\t\t\t`CREATE TABLE IF NOT EXISTS ${ATTEMPTS_TABLE}`,\n\t\t\t`CREATE TABLE ${REBUILT_TABLE}`,\n\t\t),\n\t\t`INSERT INTO ${REBUILT_TABLE} SELECT * FROM ${ATTEMPTS_TABLE};`,\n\t\t`DROP TABLE ${ATTEMPTS_TABLE};`,\n\t\t`ALTER TABLE ${REBUILT_TABLE} RENAME TO ${ATTEMPTS_TABLE};`,\n\t\tindex,\n\t\t...historicalTriggers,\n\t].join(\"\\n\");\n}\n\n/**\n * True when an existing attempts table still forbids a self-bind. A\n * pre-release table that kept rows (no review-digest CHECK) is left alone: its\n * rows can't satisfy the current table, and it already fails closed.\n */\nexport function rebindAttemptsNeedSelfBindRebuild(existingTableSql: string | null): boolean {\n\treturn (\n\t\t!!existingTableSql &&\n\t\texistingTableSql.includes(\"target_identity_id <> current_identity_id\") &&\n\t\texistingTableSql.includes(\"CHECK (review_digest IS NOT NULL)\")\n\t);\n}\n","import { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport type { CoordinatorEnrollment } from \"./coordinator-store-contract.js\";\n\n/**\n * The device's ownership binding, if it has exactly one. A rebind (ADR 0005\n * Section 8) writes one, so admins can tell a rebound device from a conflict.\n */\nexport const ENROLLMENT_OWNERSHIP_COLUMNS = `(SELECT CASE WHEN count(*) = 1 THEN max(b.identity_id) END\n\t FROM coordinator_device_ownership_bindings b\n\t WHERE b.device_id = enrolled_devices.device_id) AS ownership_identity_id,\n\t(SELECT CASE WHEN count(*) = 1 THEN max(b.key_id) END\n\t FROM coordinator_device_ownership_bindings b\n\t WHERE b.device_id = enrolled_devices.device_id) AS ownership_key_id`;\n\n/**\n * Keeps `ownership_identity_id` only when the binding names this enrollment's\n * exact key; a binding for another key says nothing about this enrollment.\n */\nexport async function withEnrollmentOwnership(\n\trows: ReadonlyArray<CoordinatorEnrollment & { ownership_key_id?: unknown }>,\n): Promise<CoordinatorEnrollment[]> {\n\treturn Promise.all(\n\t\trows.map(async (row) => {\n\t\t\tconst { ownership_identity_id: identityId, ownership_key_id: keyId, ...base } = row;\n\t\t\tif (typeof identityId !== \"string\" || typeof keyId !== \"string\") return base;\n\t\t\tconst enrollmentKeyId = await ed25519KeyIdForRevocation(row.public_key);\n\t\t\treturn enrollmentKeyId === keyId ? { ...base, ownership_identity_id: identityId } : base;\n\t\t}),\n\t);\n}\n","import { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport { DEVICE_REVOCATION_SUBJECT_EXISTS_SQL } from \"./coordinator-device-revocation.js\";\nimport { COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_GROUPS } from \"./coordinator-legacy-team-completion.js\";\n\n/** Internal transport grants only: these confer no Team/Project access. */\nexport interface CoordinatorIdentityGroupGrant {\n\treadonly coordinator_id: string;\n\treadonly identity_id: string;\n\treadonly group_id: string;\n\treadonly status: \"active\" | \"revoked\";\n\treadonly revision: number;\n\treadonly source_kind: \"controller_attestation\";\n\treadonly source_receipt_id: string;\n\treadonly created_at: string;\n\treadonly revoked_at: string | null;\n}\n\nexport interface CoordinatorIdentityGroupGrantIssueInput {\n\tcoordinatorId: string;\n\tattestationId: string;\n}\nexport interface CoordinatorIdentityGroupGrantScope {\n\tcoordinatorId: string;\n\tidentityId: string;\n}\nexport interface CoordinatorIdentityGroupGrantRevokeInput\n\textends CoordinatorIdentityGroupGrantScope {\n\tgroupId: string;\n\texpectedRevision: number;\n}\nexport type CoordinatorIdentityGroupGrantIssueResult =\n\t| { kind: \"created\" | \"existing\"; grant: CoordinatorIdentityGroupGrant }\n\t| { kind: \"rejected\"; error: \"invalid_grant_input\" | \"grant_authority_unavailable\" };\n\n/** Future authenticated operators own invocation; no routes or automatic issuance. */\nexport interface CoordinatorIdentityGroupGrantStore {\n\tissueIdentityGroupGrantFromControllerAttestation(\n\t\tinput: CoordinatorIdentityGroupGrantIssueInput,\n\t): Promise<CoordinatorIdentityGroupGrantIssueResult>;\n\tlistIdentityGroupGrantRevisions(\n\t\tinput: CoordinatorIdentityGroupGrantScope,\n\t): Promise<CoordinatorIdentityGroupGrant[]>;\n\trevokeIdentityGroupGrant(input: CoordinatorIdentityGroupGrantRevokeInput): Promise<boolean>;\n}\n\n/** Capture once before async I/O; do not invoke getters or accept inherited IDs. */\nexport function captureIdentityGroupGrantInput(\n\tinput: unknown,\n\tfields: readonly string[],\n): Record<string, string | number> | null {\n\ttry {\n\t\tif (!input || typeof input !== \"object\" || Array.isArray(input)) return null;\n\t\tconst captured: Record<string, string | number> = {};\n\t\tfor (const field of fields) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(input, field);\n\t\t\tif (!descriptor || !Object.hasOwn(descriptor, \"value\")) return null;\n\t\t\tconst value: unknown = descriptor.value;\n\t\t\tif (field === \"expectedRevision\") {\n\t\t\t\tif (\n\t\t\t\t\ttypeof value !== \"number\" ||\n\t\t\t\t\t!Number.isSafeInteger(value) ||\n\t\t\t\t\tvalue < 1 ||\n\t\t\t\t\tvalue >= Number.MAX_SAFE_INTEGER\n\t\t\t\t)\n\t\t\t\t\treturn null;\n\t\t\t} else if (!isAuthControllerId(value)) return null;\n\t\t\tcaptured[field] = value as string | number;\n\t\t}\n\t\treturn captured;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nconst GRANT_FIELDS = [\n\t\"coordinator_id\",\n\t\"identity_id\",\n\t\"group_id\",\n\t\"status\",\n\t\"revision\",\n\t\"source_kind\",\n\t\"source_receipt_id\",\n\t\"created_at\",\n\t\"revoked_at\",\n] as const;\n\nfunction isCanonicalGrant(row: CoordinatorIdentityGroupGrant): boolean {\n\tif (!row) return false;\n\tif (\n\t\t![row.coordinator_id, row.identity_id, row.group_id, row.source_receipt_id].every(\n\t\t\tisAuthControllerId,\n\t\t)\n\t)\n\t\treturn false;\n\tif (\n\t\trow.source_kind !== \"controller_attestation\" ||\n\t\t!Number.isSafeInteger(row.revision) ||\n\t\trow.revision < 1\n\t)\n\t\treturn false;\n\tif (typeof row.created_at !== \"string\" || row.created_at.length === 0) return false;\n\tif (row.status === \"active\") return row.revoked_at === null;\n\treturn (\n\t\trow.status === \"revoked\" && typeof row.revoked_at === \"string\" && row.revoked_at.length > 0\n\t);\n}\n\nfunction canonicalRevisionSet(\n\trows: readonly CoordinatorIdentityGroupGrant[],\n): Map<string, CoordinatorIdentityGroupGrant> | null {\n\t// Reuse the existing coordinator group-set limit; never truncate authority sets.\n\tif (\n\t\t!Array.isArray(rows) ||\n\t\trows.length === 0 ||\n\t\trows.length > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_GROUPS\n\t)\n\t\treturn null;\n\tconst result = new Map<string, CoordinatorIdentityGroupGrant>();\n\tfor (const row of rows) {\n\t\tif (!isCanonicalGrant(row)) return null;\n\t\tif (\n\t\t\trow.coordinator_id !== rows[0].coordinator_id ||\n\t\t\trow.identity_id !== rows[0].identity_id ||\n\t\t\tresult.has(row.group_id)\n\t\t)\n\t\t\treturn null;\n\t\tresult.set(row.group_id, row);\n\t}\n\treturn result;\n}\n\n/** Snapshot equality only, NOT authorization for a future enrollment write. */\nexport function compareIdentityGroupGrantRevisions(\n\texpected: readonly CoordinatorIdentityGroupGrant[],\n\tcurrent: readonly CoordinatorIdentityGroupGrant[],\n): boolean {\n\tconst left = canonicalRevisionSet(expected);\n\tconst right = canonicalRevisionSet(current);\n\tif (!left || !right || left.size !== right.size) return false;\n\tfor (const [groupId, row] of left) {\n\t\tconst other = right.get(groupId);\n\t\tif (!other || GRANT_FIELDS.some((field) => row[field] !== other[field])) return false;\n\t}\n\treturn true;\n}\n\n// Independent tombstones: deliberately no enrollment/controller foreign keys.\nexport const IDENTITY_GROUP_GRANT_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS coordinator_identity_group_grants (\n coordinator_id TEXT NOT NULL,\n identity_id TEXT NOT NULL,\n group_id TEXT NOT NULL,\n status TEXT NOT NULL CHECK (status IN ('active', 'revoked')),\n revision INTEGER NOT NULL CHECK (typeof(revision) = 'integer' AND revision BETWEEN 1 AND 9007199254740991),\n source_kind TEXT NOT NULL CHECK (source_kind = 'controller_attestation'),\n source_receipt_id TEXT NOT NULL,\n created_at TEXT NOT NULL,\n revoked_at TEXT,\n PRIMARY KEY (coordinator_id, identity_id, group_id),\n CHECK ((status = 'active' AND revoked_at IS NULL) OR (status = 'revoked' AND revoked_at IS NOT NULL))\n);`;\n\nconst CURRENT_CONTROLLER_FROM_SQL = `\n FROM coordinator_auth_controller_attestations a\n JOIN enrolled_devices e ON e.group_id = a.group_id AND e.device_id = a.device_id\n JOIN groups g ON g.group_id = a.group_id`;\nconst CURRENT_CONTROLLER_EVIDENCE_SQL = `\n a.coordinator_id = ? AND a.attestation_id = ? AND a.revoked_at IS NULL\n AND g.archived_at IS NULL AND e.enabled = 1\n AND e.public_key = a.public_key AND e.fingerprint = a.fingerprint\n AND e.identity_id IS a.enrollment_identity_id\n AND (e.identity_id IS NULL OR e.identity_id = a.identity_id)`;\n\n/** Read the actual current enrollment, never caller-provided key metadata. */\nexport const IDENTITY_GROUP_GRANT_SOURCE_SQL = `\n SELECT e.* ${CURRENT_CONTROLLER_FROM_SQL} WHERE ${CURRENT_CONTROLLER_EVIDENCE_SQL}`;\n\n// Pin the hashed enrollment across D1 awaits; both issuance and retry recheck revocation.\nconst CURRENT_CONTROLLER_WHERE_SQL = `${CURRENT_CONTROLLER_EVIDENCE_SQL}\n AND e.group_id = ? AND e.device_id = ? AND e.public_key = ?\n AND e.fingerprint = ? AND e.identity_id IS ?\n AND NOT ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}`;\n\nexport const IDENTITY_GROUP_GRANT_INSERT_SQL = `\n INSERT INTO coordinator_identity_group_grants (\n coordinator_id, identity_id, group_id, status, revision, source_kind, source_receipt_id, created_at, revoked_at\n ) SELECT a.coordinator_id, a.identity_id, a.group_id, 'active', 1, 'controller_attestation', a.review_receipt_id, ?, NULL\n ${CURRENT_CONTROLLER_FROM_SQL} WHERE ${CURRENT_CONTROLLER_WHERE_SQL}\n ON CONFLICT (coordinator_id, identity_id, group_id) DO NOTHING\n RETURNING *`;\n\n/** Retry checks the grant and exact current evidence together in ONE read. */\nexport const IDENTITY_GROUP_GRANT_RETRY_SQL = `\n SELECT r.* ${CURRENT_CONTROLLER_FROM_SQL}\n JOIN coordinator_identity_group_grants r ON r.coordinator_id = a.coordinator_id\n AND r.identity_id = a.identity_id AND r.group_id = a.group_id\n WHERE ${CURRENT_CONTROLLER_WHERE_SQL}\n AND r.status = 'active' AND r.source_kind = 'controller_attestation'\n AND r.source_receipt_id = a.review_receipt_id`;\n\n/** Listing intentionally does not depend on the old controller device/key. */\nexport const IDENTITY_GROUP_GRANT_LIST_SQL = `\n SELECT * FROM coordinator_identity_group_grants\n WHERE coordinator_id = ? AND identity_id = ? ORDER BY group_id COLLATE BINARY`;\nexport const IDENTITY_GROUP_GRANT_REVOKE_SQL = `\n UPDATE coordinator_identity_group_grants SET status = 'revoked', revision = revision + 1, revoked_at = ?\n WHERE coordinator_id = ? AND identity_id = ? AND group_id = ? AND status = 'active' AND revision = ?`;\n","import { DEVICE_REVOCATION_SUBJECT_EXISTS_SQL } from \"./coordinator-device-revocation.js\";\nimport type { projectInviteGuardEvidence } from \"./coordinator-project-invite-guards.js\";\nimport type {\n\tCoordinatorConsumeProjectInviteInput,\n\tCoordinatorEnrollDeviceInput,\n} from \"./coordinator-store-contract.js\";\n\nexport function captureLegacyProjectInviteInput(\n\tinput: CoordinatorConsumeProjectInviteInput,\n): CoordinatorConsumeProjectInviteInput {\n\tif (!input || typeof input !== \"object\" || Array.isArray(input)) throw new Error(\"invalid_input\");\n\tconst captured: Record<string, unknown> = {};\n\tfor (const field of [\n\t\t\"token\",\n\t\t\"operationId\",\n\t\t\"deviceId\",\n\t\t\"publicKey\",\n\t\t\"fingerprint\",\n\t\t\"recipientActorId\",\n\t\t\"recipientDisplayName\",\n\t\t\"deviceDisplayName\",\n\t\t\"now\",\n\t]) {\n\t\tconst descriptor = legacyEnrollmentDescriptor(input, field);\n\t\tif (descriptor && !(\"value\" in descriptor)) throw new Error(\"invalid_input\");\n\t\tconst value = descriptor?.value;\n\t\tif (typeof value !== \"string\") throw new Error(\"invalid_input\");\n\t\tcaptured[field] = value;\n\t}\n\treturn captured as unknown as CoordinatorConsumeProjectInviteInput;\n}\n\n/** Global ownership metadata, not proof. Bind actual device ID and canonical key ID (or null). */\nexport const DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL = `EXISTS (\nSELECT 1 FROM coordinator_device_ownership_bindings WHERE device_id = ? OR key_id = ?)`;\n\n/** Project actor labels never prove ownership; only the target enrollment is mutated. */\nexport function legacyProjectInviteOwnershipEvidence(\n\tevidence: ReturnType<typeof projectInviteGuardEvidence>,\n\tdeviceId: string,\n\tkeyIds: { incoming: string | null; current: string | null },\n) {\n\tconst ownershipSql = `${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL} OR ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}`;\n\tconst ownershipValues = [deviceId, keyIds.incoming, deviceId, keyIds.current];\n\treturn {\n\t\t...evidence,\n\t\townershipSql,\n\t\townershipValues,\n\t\teligibilitySql: `${evidence.eligibilitySql} AND NOT (${ownershipSql})`,\n\t\teligibilityValues: [...evidence.eligibilityValues, ...ownershipValues],\n\t\tboundEligibilitySql: `${evidence.boundEligibilitySql} AND NOT (${ownershipSql})`,\n\t\tboundEligibilityValues: [...evidence.boundEligibilityValues, ...ownershipValues],\n\t};\n}\n\nexport const LEGACY_DEVICE_DENIAL_SQL = `SELECT CASE\nWHEN ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL} THEN 'device_revoked'\nWHEN ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL} THEN 'device_ownership_requires_verified_identity'\nELSE 'invite_identity_conflict' END AS denial`;\n\n/** Bind captured public key (null for absence), group/device, then group/device/public key. */\nexport const LEGACY_ENROLLMENT_SOURCE_MATCH_SQL = `((? IS NULL AND NOT EXISTS (\nSELECT 1 FROM enrolled_devices WHERE group_id = ? AND device_id = ?)) OR EXISTS (\nSELECT 1 FROM enrolled_devices WHERE group_id = ? AND device_id = ? AND public_key = ?))`;\n\n/** Incoming revocation, incoming ownership, captured current ownership, then source tuple.\n * Source drift deliberately falls through the denial validator to the unavailable error.\n */\nexport const LEGACY_ENROLLMENT_DENIAL_SQL = `SELECT CASE\nWHEN ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL} THEN 'device_revoked'\nWHEN ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL} OR ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}\nTHEN 'device_ownership_requires_verified_identity'\nWHEN NOT ${LEGACY_ENROLLMENT_SOURCE_MATCH_SQL} THEN 'device_ownership_authorization_unavailable'\nELSE 'invite_identity_conflict' END AS denial`;\n\nexport const LEGACY_ENROLLMENT_WRITE_SQL = `INSERT INTO enrolled_devices(\ngroup_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at\n) SELECT ?, ?, ?, ?, ?, ?, 1, ?\nWHERE NOT ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}\nAND NOT ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}\nAND NOT ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}\nAND ${LEGACY_ENROLLMENT_SOURCE_MATCH_SQL}\nON CONFLICT(group_id, device_id) DO UPDATE SET\npublic_key = excluded.public_key, fingerprint = excluded.fingerprint,\nidentity_id = COALESCE(enrolled_devices.identity_id, excluded.identity_id),\ndisplay_name = excluded.display_name, enabled = 1\nWHERE (excluded.identity_id IS NULL OR enrolled_devices.identity_id IS NULL\nOR enrolled_devices.identity_id = excluded.identity_id)\nAND NOT ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}\nAND NOT ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}\nAND enrolled_devices.public_key = ?`;\n\nexport function captureLegacyEnrollmentPublicKey(row: unknown): string | null {\n\tif (row === null) return null;\n\tif (!row || typeof row !== \"object\")\n\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\tconst descriptor = Object.getOwnPropertyDescriptor(row, \"public_key\");\n\tif (!descriptor || !(\"value\" in descriptor) || typeof descriptor.value !== \"string\") {\n\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t}\n\treturn descriptor.value;\n}\n\nexport function captureLegacyEnrollment(\n\tgroupId: string,\n\tinput: CoordinatorEnrollDeviceInput,\n): CoordinatorEnrollDeviceInput {\n\tif (!input || typeof input !== \"object\" || Array.isArray(input)) throw new Error(\"invalid_input\");\n\tconst captured: Record<string, unknown> = {};\n\tfor (const field of [\"deviceId\", \"publicKey\", \"fingerprint\", \"identityId\", \"displayName\"]) {\n\t\tconst descriptor = legacyEnrollmentDescriptor(input, field);\n\t\tif (descriptor && !(\"value\" in descriptor)) throw new Error(\"invalid_input\");\n\t\tcaptured[field] = descriptor?.value;\n\t}\n\tassertLegacyDeviceScope(groupId, captured.deviceId);\n\tif (\n\t\ttypeof captured.publicKey !== \"string\" ||\n\t\ttypeof captured.fingerprint !== \"string\" ||\n\t\t(captured.identityId != null && typeof captured.identityId !== \"string\") ||\n\t\t(captured.displayName != null && typeof captured.displayName !== \"string\")\n\t)\n\t\tthrow new Error(\"invalid_input\");\n\treturn captured as unknown as CoordinatorEnrollDeviceInput;\n}\n\nfunction legacyEnrollmentDescriptor(input: object, field: string): PropertyDescriptor | undefined {\n\ttry {\n\t\treturn Object.getOwnPropertyDescriptor(input, field);\n\t} catch {\n\t\tthrow new Error(\"invalid_input\");\n\t}\n}\n\nexport function assertLegacyDeviceScope(groupId: unknown, deviceId: unknown): void {\n\tif (typeof groupId !== \"string\" || typeof deviceId !== \"string\") throw new Error(\"invalid_input\");\n}\n\nexport function legacyDeviceWriteChanges(result: unknown): number {\n\tif (!result || typeof result !== \"object\" || (\"success\" in result && result.success === false)) {\n\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t}\n\tlet changes: unknown;\n\tif (\n\t\t\"meta\" in result &&\n\t\tresult.meta &&\n\t\ttypeof result.meta === \"object\" &&\n\t\t\"changes\" in result.meta\n\t) {\n\t\tchanges = result.meta.changes;\n\t}\n\tif (typeof changes !== \"number\" || !Number.isSafeInteger(changes) || changes < 0 || changes > 1) {\n\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t}\n\treturn changes;\n}\n\nexport function legacyDeviceDenial(row: unknown): string {\n\tif (\n\t\trow &&\n\t\ttypeof row === \"object\" &&\n\t\t!(\"success\" in row && row.success === false) &&\n\t\t\"denial\" in row\n\t) {\n\t\tconst denial = row.denial;\n\t\tif (\n\t\t\tdenial === \"device_revoked\" ||\n\t\t\tdenial === \"device_ownership_requires_verified_identity\" ||\n\t\t\tdenial === \"invite_identity_conflict\"\n\t\t)\n\t\t\treturn denial;\n\t}\n\tthrow new Error(\"device_ownership_authorization_unavailable\");\n}\n\nexport function legacyDeviceAuthorizationFailure(error: unknown): never {\n\tif (\n\t\terror instanceof Error &&\n\t\t[\n\t\t\t\"device_revoked\",\n\t\t\t\"device_ownership_requires_verified_identity\",\n\t\t\t\"invite_identity_conflict\",\n\t\t].includes(error.message)\n\t)\n\t\tthrow error;\n\tthrow new Error(\"device_ownership_authorization_unavailable\");\n}\n","import { DEVICE_REVOCATION_SUBJECT_EXISTS_SQL } from \"./coordinator-device-revocation.js\";\nimport {\n\tDEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL,\n\tLEGACY_ENROLLMENT_SOURCE_MATCH_SQL,\n} from \"./coordinator-legacy-device-ownership.js\";\nimport type {\n\tCoordinatorEnrollment,\n\tCoordinatorJoinRequest,\n} from \"./coordinator-store-contract.js\";\n\nexport const JOIN_REVIEW_COLUMNS = `request_id, group_id, device_id, public_key, fingerprint,\n display_name, token, status, created_at, reviewed_at, reviewed_by`;\n\n/** Evidence captured before hashing must remain current at every approval writer. */\nexport function joinReviewGuardEvidence(\n\trow: CoordinatorJoinRequest & { public_key: string },\n\tseed: CoordinatorEnrollment | null,\n\tkeys: { recipient: string | null; seed: string | null; current: string | null },\n\tcurrentPublicKey: string | null,\n) {\n\tconst revocationSql = `${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL} OR ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}`;\n\tconst revocationValues = [row.device_id, keys.recipient, seed?.device_id ?? null, keys.seed];\n\t// Reviewer/seed identity is not recipient ownership proof. Retain the old key even after upsert.\n\tconst ownershipSql = `${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL} OR ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}`;\n\tconst ownershipValues = [row.device_id, keys.recipient, row.device_id, keys.current];\n\tconst sourceValues = [\n\t\tcurrentPublicKey,\n\t\trow.group_id,\n\t\trow.device_id,\n\t\trow.group_id,\n\t\trow.device_id,\n\t\tcurrentPublicKey,\n\t];\n\tconst tupleSql = `EXISTS (SELECT 1 FROM coordinator_join_requests jr\n WHERE jr.request_id = ? AND jr.group_id = ? AND jr.device_id = ?\n AND jr.public_key = ? AND jr.fingerprint = ? AND jr.display_name IS ?\n AND jr.token = ? AND jr.created_at = ?)`;\n\tconst tupleValues = [\n\t\trow.request_id,\n\t\trow.group_id,\n\t\trow.device_id,\n\t\trow.public_key,\n\t\trow.fingerprint,\n\t\trow.display_name ?? null,\n\t\trow.token,\n\t\trow.created_at,\n\t];\n\tconst seedSql = `(? = 0 OR EXISTS (SELECT 1 FROM enrolled_devices se\n WHERE se.group_id = ? AND se.device_id = ? AND se.public_key = ?\n AND se.fingerprint = ? AND se.enabled = 1))`;\n\treturn {\n\t\trevocationSql,\n\t\trevocationValues,\n\t\townershipSql,\n\t\townershipValues,\n\t\tsourceSql: LEGACY_ENROLLMENT_SOURCE_MATCH_SQL,\n\t\tsourceValues,\n\t\teligibilitySql: `${tupleSql} AND ${seedSql} AND NOT (${revocationSql}) AND NOT (${ownershipSql})`,\n\t\teligibilityValues: [\n\t\t\t...tupleValues,\n\t\t\tseed ? 1 : 0,\n\t\t\trow.group_id,\n\t\t\tseed?.device_id ?? null,\n\t\t\tseed?.public_key ?? null,\n\t\t\tseed?.fingerprint ?? null,\n\t\t\t...revocationValues,\n\t\t\t...ownershipValues,\n\t\t],\n\t};\n}\n\nexport function joinReviewResultChanges(result: unknown): number {\n\tif (\n\t\t!result ||\n\t\ttypeof result !== \"object\" ||\n\t\t(\"success\" in result && result.success === false) ||\n\t\t!(\"meta\" in result) ||\n\t\t!result.meta ||\n\t\ttypeof result.meta !== \"object\" ||\n\t\t!(\"changes\" in result.meta) ||\n\t\t!Number.isSafeInteger(result.meta.changes) ||\n\t\t(result.meta.changes as number) < 0\n\t)\n\t\tthrow new Error(\"join_review_incomplete\");\n\treturn result.meta.changes as number;\n}\n\nexport function assertJoinReviewConfirmation(result: unknown): void {\n\tif (\n\t\t!result ||\n\t\ttypeof result !== \"object\" ||\n\t\t(\"success\" in result && result.success === false) ||\n\t\t!(\"results\" in result) ||\n\t\t!Array.isArray(result.results) ||\n\t\tresult.results.length !== 1 ||\n\t\tresult.results[0]?.confirmed !== 1\n\t) {\n\t\tthrow new Error(\"join_review_incomplete\");\n\t}\n}\n","import type { AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport {\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES,\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_GROUPS,\n\tCoordinatorLegacyTeamCompletionConflictError,\n\ttype CoordinatorLegacyTeamCompletionWriteResult,\n\tlegacyDecisionCountsAsOwnerSql,\n\tnormalizeCoordinatorLegacyTeamCompletionManifest,\n} from \"./coordinator-legacy-team-completion.js\";\nimport { LEGACY_TEAM_SETUP_MAX_DEVICES } from \"./legacy-team-setup-limits.js\";\n\nconst MAX_KEYS = COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_GROUPS * LEGACY_TEAM_SETUP_MAX_DEVICES;\n\n/** Both the early replay and the post-INSERT winner retain the canonical row. */\nexport function legacyCompletionWriteResult(\n\tstoredJson: string,\n\trequestedJson: string,\n\tstatus: CoordinatorLegacyTeamCompletionWriteResult[\"status\"],\n): CoordinatorLegacyTeamCompletionWriteResult {\n\tif (storedJson !== requestedJson) throw new CoordinatorLegacyTeamCompletionConflictError();\n\treturn {\n\t\tstatus,\n\t\tmanifest: normalizeCoordinatorLegacyTeamCompletionManifest(JSON.parse(storedJson)),\n\t};\n}\n\nconst completionJson = `CASE WHEN json_valid(c.manifest_json) THEN c.manifest_json ELSE '{}' END`;\n\n/** Only requesters and ownership-bearing evidence need canonical-key inference.\n * Keep discovery and the winning statement on the same sources: an ownerless\n * enrollment becomes relevant if it acquires an owner or an included completion.\n * Ledger bindings already carry canonical key IDs and need no text classification.\n */\nconst ownerSourceKeysSql = `legacy_owner_source_keys AS NOT MATERIALIZED (\n SELECT e.public_key FROM legacy_owner_input p,\n json_each(p.manifest, '$.device_decisions') d\n JOIN enrolled_devices e ON e.group_id = p.group_id\n AND e.device_id = json_extract(d.value, '$.device_id')\n AND e.fingerprint = json_extract(d.value, '$.key_fingerprint') AND e.enabled = 1\n WHERE json_extract(d.value, '$.decision') = 'included'\n UNION\n SELECT public_key FROM enrolled_devices WHERE identity_id IS NOT NULL\n UNION\n SELECT e.public_key FROM coordinator_legacy_team_completions c,\n json_each(${completionJson}, '$.device_decisions') d, legacy_owner_input p\n JOIN enrolled_devices e ON e.group_id = c.group_id\n AND e.device_id = json_extract(d.value, '$.device_id')\n AND e.fingerprint = json_extract(d.value, '$.key_fingerprint')\n WHERE json_extract(${completionJson}, '$.coordinator_id') = json_extract(p.manifest, '$.coordinator_id')\n AND (json_extract(d.value, '$.decision') = 'included' AND ${legacyDecisionCountsAsOwnerSql(\"d.value\")})\n)`;\n\n/** Bind canonical manifest JSON, then target group. */\nexport const LEGACY_OWNER_KEYS_SQL = `WITH legacy_owner_input(manifest, group_id) AS (\n VALUES (?, ?)\n), ${ownerSourceKeysSql}\n SELECT public_key FROM legacy_owner_source_keys\n WHERE EXISTS (SELECT 1 FROM legacy_owner_input p, json_each(p.manifest, '$.device_decisions')\n WHERE json_extract(value, '$.decision') = 'included')\n ORDER BY public_key LIMIT ${MAX_KEYS + 1}`;\n\n/** Classify server-held text aliases, never a fingerprint supplied as ownership proof.\n * Invalid unrelated keys supply no key inference; included requesters must have a\n * verified current key in the winning statement. No database I/O occurs here.\n */\nexport async function legacyOwnerKeyMetadata(\n\trows: readonly { public_key: string }[],\n): Promise<string> {\n\tif (rows.length > MAX_KEYS) throw new Error(\"completion_manifest_unavailable\");\n\tconst encoder = new TextEncoder();\n\tif (\n\t\tencoder.encode(JSON.stringify(rows)).byteLength > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES\n\t)\n\t\tthrow new Error(\"completion_manifest_unavailable\");\n\tconst metadata = [];\n\tfor (const { public_key } of rows) {\n\t\tconst keyId = await ed25519KeyIdForRevocation(public_key);\n\t\tlet fingerprint: string | null = null;\n\t\tif (keyId) {\n\t\t\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", encoder.encode(public_key));\n\t\t\tfingerprint = Array.from(new Uint8Array(digest), (byte) =>\n\t\t\t\tbyte.toString(16).padStart(2, \"0\"),\n\t\t\t).join(\"\");\n\t\t}\n\t\tmetadata.push({ public_key, key_id: keyId, fingerprint });\n\t}\n\tconst json = JSON.stringify(metadata);\n\tif (encoder.encode(json).byteLength > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES)\n\t\tthrow new Error(\"completion_manifest_unavailable\");\n\treturn json;\n}\n\n/** Bind canonical manifest JSON, target group, then server-derived key metadata.\n * Ownership-bearing enrollments are re-read at INSERT time. Reject newly relevant\n * text keys rather than letting an unclassified alias evade a canonical-key comparison.\n * Materialize the size-limited key metadata and requested rows so correlated\n * owner checks reuse them instead of repeatedly expanding their JSON inputs.\n * Join requested enrollments directly by group/device; a left-joined enrollment\n * CTE can materialize all groups sharing a key even with NOT MATERIALIZED.\n */\nexport const LEGACY_OWNER_INPUT_SQL = `WITH legacy_owner_input(manifest, group_id, keys) AS (\n VALUES (?, ?, ?)\n ), ${ownerSourceKeysSql}, legacy_owner_keys AS MATERIALIZED (\n SELECT json_extract(value, '$.public_key') AS public_key,\n json_extract(value, '$.key_id') AS key_id,\n json_extract(value, '$.fingerprint') AS fingerprint\n FROM legacy_owner_input p, json_each(p.keys)\n), legacy_owner_enrollments AS NOT MATERIALIZED (\n SELECT e.*, k.key_id FROM enrolled_devices e JOIN legacy_owner_keys k\n ON k.public_key = e.public_key AND k.fingerprint = e.fingerprint AND k.key_id IS NOT NULL\n), legacy_owner_requested AS MATERIALIZED (\n SELECT json_extract(d.value, '$.device_id') AS device_id,\n json_extract(d.value, '$.key_fingerprint') AS fingerprint,\n json_extract(d.value, '$.identity_id') AS identity_id, k.key_id\n FROM legacy_owner_input p, json_each(p.manifest, '$.device_decisions') d\n LEFT JOIN enrolled_devices e ON e.group_id = p.group_id\n AND e.device_id = json_extract(d.value, '$.device_id')\n AND e.fingerprint = json_extract(d.value, '$.key_fingerprint') AND e.enabled = 1\n LEFT JOIN legacy_owner_keys k ON k.public_key = e.public_key\n AND k.fingerprint = e.fingerprint AND k.key_id IS NOT NULL\n WHERE json_extract(d.value, '$.decision') = 'included'\n)`;\n\n// Missing/changed enrollment evidence is unavailable, not an inferred owner clash.\nexport const LEGACY_OWNER_SOURCE_CURRENT_SQL = `(NOT EXISTS (SELECT 1 FROM legacy_owner_requested)\n OR (NOT EXISTS (\n SELECT public_key FROM legacy_owner_source_keys EXCEPT SELECT public_key FROM legacy_owner_keys\n) AND NOT EXISTS (SELECT 1 FROM legacy_owner_requested WHERE key_id IS NULL)))`;\n\n/** Only included owner assignments compete. Labels, exclusions, and other people\n * never supply ownership. A stored label (another device's guess) never blocks a\n * later upload. Requested rows are all checked, labels included, so a new guess\n * still cannot contradict recorded ownership. Old fingerprints need a verified current enrollment\n * for the historical group/device; the exact device ID needs no key inference.\n * This predicate belongs in the winning INSERT, not just a preview/read check.\n */\nexport const LEGACY_OWNER_COMPATIBLE_SQL = `NOT EXISTS (\n SELECT 1 FROM legacy_owner_requested r WHERE\n EXISTS (SELECT 1 FROM legacy_owner_requested other\n WHERE other.key_id = r.key_id AND other.identity_id <> r.identity_id)\n OR EXISTS (SELECT 1 FROM enrolled_devices e\n WHERE e.identity_id IS NOT NULL AND e.identity_id <> r.identity_id\n AND (e.device_id = r.device_id OR EXISTS (\n SELECT 1 FROM legacy_owner_enrollments verified\n WHERE verified.group_id = e.group_id AND verified.device_id = e.device_id\n AND verified.key_id = r.key_id)))\n OR EXISTS (SELECT 1 FROM coordinator_device_ownership_bindings b\n WHERE (b.device_id = r.device_id OR b.key_id = r.key_id) AND b.identity_id <> r.identity_id)\n OR EXISTS (SELECT 1 FROM coordinator_legacy_team_completions c,\n json_each(${completionJson}, '$.device_decisions') d, legacy_owner_input p\n WHERE json_extract(${completionJson}, '$.coordinator_id') = json_extract(p.manifest, '$.coordinator_id')\n AND (json_extract(d.value, '$.decision') = 'included' AND ${legacyDecisionCountsAsOwnerSql(\"d.value\", \"deny\")})\n AND json_extract(d.value, '$.identity_id') <> r.identity_id\n AND (json_extract(d.value, '$.device_id') = r.device_id OR EXISTS (\n SELECT 1 FROM legacy_owner_enrollments e WHERE e.group_id = c.group_id\n AND e.device_id = json_extract(d.value, '$.device_id')\n AND e.fingerprint = json_extract(d.value, '$.key_fingerprint') AND e.key_id = r.key_id)))\n)`;\n\n/** Used only to explain a refused INSERT; this cannot authorize a write. */\nexport const LEGACY_OWNER_DENIAL_SQL = `${LEGACY_OWNER_INPUT_SQL}\n SELECT CASE WHEN NOT ${LEGACY_OWNER_SOURCE_CURRENT_SQL} THEN 'completion_manifest_unavailable'\n WHEN NOT (${LEGACY_OWNER_COMPATIBLE_SQL}) THEN 'completion_conflict'\n ELSE 'completion_manifest_unavailable' END AS denial`;\n\n/**\n * The winning completion INSERT. Every ordinary completion check and both owner checks\n * run in it, so they decide at write time; the capture's guards lead its batch. `proof`\n * starts with the three LEGACY_OWNER_INPUT_SQL values.\n */\nexport function legacyCompletionInsertStatement(input: {\n\tproof: {\n\t\tctes: string;\n\t\tcurrentSql: string;\n\t\tcompatibleSql: string;\n\t\tvalues: readonly (string | number | null)[];\n\t};\n\tgroupId: string;\n\tmanifest: { candidate_ref: string; version: number; completed_at: string };\n\tmanifestJson: string;\n\tcoordinatorId: string | null;\n\tcreatedAt: string;\n}): AuthLinkStatement {\n\tconst { proof, groupId, manifest, manifestJson } = input;\n\treturn {\n\t\tsql: `${LEGACY_OWNER_INPUT_SQL}${proof.ctes}\n INSERT OR IGNORE INTO coordinator_legacy_team_completions(\n group_id, candidate_ref, manifest_version, manifest_json, completed_at, created_at\n ) SELECT ?, ?, ?, ?, ?, ?\n FROM groups\n WHERE group_id = ? AND archived_at IS NULL\n AND NOT EXISTS (\n SELECT 1\n FROM json_each(?, '$.project_mappings') AS requested\n LEFT JOIN coordinator_scopes AS scope\n ON scope.scope_id = json_extract(requested.value, '$.scope_id')\n AND scope.authority_type = 'coordinator'\n AND scope.coordinator_id = ?\n AND scope.group_id = ?\n AND scope.status = 'active'\n WHERE scope.scope_id IS NULL\n )\n AND NOT EXISTS (\n SELECT 1 FROM enrolled_devices AS enrolled\n WHERE enrolled.group_id = ?\n AND NOT EXISTS (\n SELECT 1 FROM json_each(?, '$.device_decisions') AS requested\n WHERE json_extract(requested.value, '$.device_id') = enrolled.device_id\n AND json_extract(requested.value, '$.key_fingerprint') = enrolled.fingerprint\n AND json_extract(requested.value, '$.enabled') = enrolled.enabled\n )\n )\n AND NOT EXISTS (\n SELECT 1 FROM json_each(?, '$.device_decisions') AS requested\n WHERE json_extract(requested.value, '$.decision') = 'included'\n AND NOT EXISTS (\n SELECT 1 FROM enrolled_devices AS enrolled\n WHERE enrolled.group_id = ?\n AND enrolled.device_id = json_extract(requested.value, '$.device_id')\n AND enrolled.fingerprint = json_extract(requested.value, '$.key_fingerprint')\n AND enrolled.enabled = 1\n )\n ) AND ${LEGACY_OWNER_SOURCE_CURRENT_SQL}\n AND (${proof.currentSql}) AND (${proof.compatibleSql})`,\n\t\tvalues: [\n\t\t\t...proof.values,\n\t\t\tgroupId,\n\t\t\tmanifest.candidate_ref,\n\t\t\tmanifest.version,\n\t\t\tmanifestJson,\n\t\t\tmanifest.completed_at,\n\t\t\tinput.createdAt,\n\t\t\tgroupId,\n\t\t\tmanifestJson,\n\t\t\tinput.coordinatorId,\n\t\t\tgroupId,\n\t\t\tgroupId,\n\t\t\tmanifestJson,\n\t\t\tmanifestJson,\n\t\t\tgroupId,\n\t\t],\n\t};\n}\n","import {\n\ttype ControllerHistoryRecord,\n\ttype ControllerHistorySnapshot,\n\tcontrollerHistoryDiscoveryFragments,\n\tparseControllerHistoryRecord,\n} from \"./coordinator-auth-controller-history.js\";\nimport type { AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport { snapshotGuard } from \"./coordinator-auth-read-set.js\";\nimport {\n\tclassifyEvidence,\n\ttype EvidenceRow,\n\ttype EvidenceRows,\n\ttype EvidenceSubject,\n\tidentifier,\n\tkeyId,\n} from \"./coordinator-device-ownership-evidence-classify.js\";\nimport {\n\tCONTROLLER_COLUMNS,\n\tRESOLUTION_COLUMNS,\n} from \"./coordinator-device-ownership-evidence-queries.js\";\nimport {\n\tLEGACY_OWNER_COMPATIBLE_SQL,\n\tLEGACY_OWNER_INPUT_SQL,\n} from \"./coordinator-legacy-owner-compatibility.js\";\nimport {\n\tcanonicalReviewedWeakLabels,\n\tcaptureLegacyOwnerResolutionRecord,\n\tclassifyLegacyOwnerResolutionSchemaCatalog,\n\ttype LegacyOwnerResolutionRecord,\n} from \"./coordinator-legacy-owner-resolution-metadata.js\";\nimport {\n\tcanonicalCoordinatorLegacyTeamCompletionManifestJson,\n\tnormalizeCoordinatorLegacyTeamCompletionManifest,\n} from \"./coordinator-legacy-team-completion.js\";\n\ninterface Backend {\n\tfirst<T>(statement: AuthLinkStatement): Promise<T | null>;\n\tall<T>(statement: AuthLinkStatement): Promise<T[]>;\n}\n\n/** Internal capability, meaningful only to this module's WeakMap. */\nexport interface LegacyCompletionOwnerProof {\n\treadonly version: 1;\n}\n\ninterface Subject extends EvidenceSubject {\n\towner: string;\n\tfragments: string[];\n\tfingerprints: string[];\n}\ninterface KeyMetadata {\n\tpublic_key: string;\n\tkey_id: string | null;\n\tfingerprint: string | null;\n}\ninterface Snapshot {\n\tcoordinator: string;\n\tsubjects: Subject[];\n\tactive: Subject[];\n\tkeys: KeyMetadata[];\n\trows: Record<string, string[]>;\n\tapproved: string[];\n}\ninterface ProofSql {\n\t/**\n\t * One per capture read. Each re-runs its read and aborts its batch unless the rows are\n\t * still the captured set. They lead the winning INSERT's batch, and the denial read.\n\t */\n\treadonly guards: readonly AuthLinkStatement[];\n\t/** Append after LEGACY_OWNER_INPUT_SQL, which already starts WITH. */\n\treadonly ctes: string;\n\t/** \"1\" once captured; \"0\" when the capture is unavailable, so nothing can be written. */\n\treadonly currentSql: string;\n\treadonly compatibleSql: string;\n\t/** Bind after the three LEGACY_OWNER_INPUT_SQL values. */\n\treadonly values: readonly string[];\n}\n\n// A single JSON bind must fit D1's 2 MB string/value limit. This aggregate\n// ceiling is separate from the established per-subject row/history ceilings.\n// Oversized captures are unavailable, never a smaller permitted roster. The ceiling\n// applies to the whole capture, each read's rows included, as one encoded value.\nconst MAX_CAPTURE_BYTES = 2_000_000;\nconst MAX_SUBJECT_ROWS = 500;\nconst MAX_SUBJECT_BYTES = 2_000_000;\nconst MAX_HISTORY_BYTES = 750_000;\nconst MAX_DISCOVERY_KEYS = 8192;\nconst MAX_HISTORY_KEYS = 4096;\nconst encoder = new TextEncoder();\nconst snapshots = new WeakMap<LegacyCompletionOwnerProof, ProofSql>();\nconst table = \"coordinator_legacy_owner_resolutions\";\nconst catalogSql = `SELECT json_array(type,name,tbl_name,sql) AS row\n FROM sqlite_master WHERE tbl_name='${table}' AND sql IS NOT NULL`;\n\nfunction bytes(value: unknown): number {\n\treturn encoder.encode(JSON.stringify(value)).byteLength;\n}\n\nfunction requireProof(condition: unknown): asserts condition {\n\tif (!condition) throw new Error(\"completion_manifest_unavailable\");\n}\n\nfunction rowset(columns: string[], from: string): string {\n\treturn `SELECT DISTINCT json_array(${columns.join(\",\")}) AS row FROM ${from}`;\n}\n\n/** Keep original JSON scalar spellings, including numeric formatting and string\n * escapes. Parsing/stringifying cells would change e.g. 1.0 or escaped Unicode.\n */\nfunction rowAtoms(row: string): string[] {\n\tconst atoms =\n\t\trow.match(/\"(?:[^\"\\\\]|\\\\.)*\"|null|-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?/gu) ?? [];\n\trequireProof(`[${atoms.join(\",\")}]` === row);\n\treturn atoms;\n}\n\nfunction encodeRows(rows: Snapshot[\"rows\"]): {\n\tatoms: string[];\n\trows: Record<string, number[][]>;\n} {\n\tconst atoms: string[] = [];\n\tconst indexes = new Map<string, number>();\n\tconst intern = (atom: string): number => {\n\t\tconst existing = indexes.get(atom);\n\t\tif (existing !== undefined) return existing;\n\t\tconst index = atoms.length;\n\t\tatoms.push(atom);\n\t\tindexes.set(atom, index);\n\t\treturn index;\n\t};\n\treturn {\n\t\tatoms,\n\t\trows: Object.fromEntries(\n\t\t\tObject.entries(rows).map(([name, values]) => [\n\t\t\t\tname,\n\t\t\t\tvalues.map((row) => rowAtoms(row).map(intern)),\n\t\t\t]),\n\t\t),\n\t};\n}\n\n/** The whole capture as one value, measured against the aggregate ceiling. Active\n * subjects refer to the shared roster; row cells refer to one dictionary of original\n * JSON lexemes, so a row whose text is not plain JSON scalars is refused.\n */\nfunction encodeSnapshot(snapshot: Snapshot): string {\n\treturn JSON.stringify({\n\t\t...selector(snapshot),\n\t\tapproved: snapshot.approved,\n\t\t...encodeRows(snapshot.rows),\n\t});\n}\n\n/** What the capture reads select by: the roster, its active members and key metadata. */\nfunction selector(snapshot: Snapshot) {\n\tconst active = new Set(snapshot.active);\n\treturn {\n\t\tcoordinator: snapshot.coordinator,\n\t\tsubjects: snapshot.subjects.map(({ deviceId, keyId, publicKey, fragments, fingerprints }) => ({\n\t\t\tdeviceId,\n\t\t\tkeyId,\n\t\t\tpublicKey,\n\t\t\tfragments,\n\t\t\tfingerprints,\n\t\t})),\n\t\tactive: snapshot.subjects.flatMap((subject, index) => (active.has(subject) ? [index] : [])),\n\t\tkeys: snapshot.keys,\n\t};\n}\n\nconst encodeSelector = (snapshot: Snapshot) => JSON.stringify(selector(snapshot));\n\nconst subjectColumns = [\"deviceId\", \"keyId\", \"publicKey\", \"fragments\", \"fingerprints\"]\n\t.map((name) => `json_extract(j.value,'$.${name}') AS ${name}`)\n\t.join(\",\");\nconst subjectCtes = `completion_proof_input(value) AS MATERIALIZED (SELECT ?),\n completion_proof_subjects AS MATERIALIZED (\n SELECT j.key AS ordinal,j.value,${subjectColumns} FROM completion_proof_input i,json_each(i.value,'$.subjects') j),\n completion_proof_active AS MATERIALIZED (\n SELECT s.* FROM completion_proof_input i,json_each(i.value,'$.active') j\n JOIN completion_proof_subjects s ON s.ordinal=j.value),\n completion_proof_fragments(fragment) AS MATERIALIZED (\n SELECT DISTINCT f.value FROM completion_proof_active s,json_each(s.fragments) f),\n completion_proof_fingerprints(fingerprint) AS MATERIALIZED (\n SELECT DISTINCT f.value FROM completion_proof_active s,json_each(s.value,'$.fingerprints') f),\n completion_proof_keys AS MATERIALIZED (\n SELECT json_extract(j.value,'$.public_key') AS public_key,\n json_extract(j.value,'$.key_id') AS key_id,\n json_extract(j.value,'$.fingerprint') AS fingerprint\n FROM completion_proof_input i,json_each(i.value,'$.keys') j)`;\nconst coordinator = `(SELECT json_extract(value,'$.coordinator') FROM completion_proof_input)`;\nconst field = (name: string) => `s.${name}`;\nconst collision = (device: string, key: string) =>\n\t`(${device} IN (SELECT deviceId FROM completion_proof_active) OR ${key} IN (SELECT keyId FROM completion_proof_active))`;\n\n// Conservative text discovery has the same ordinary-key fast path and malformed\n// token fallback as the accepted single-subject reader. JS alone decides aliases.\n// Materialize token parsing before roster matching: inlining it into each\n// correlated fragment check repeats whitespace/token work for every subject.\n// Distributing the existential OR preserves its rowset while sharing lookup sets.\nconst discoveryCtes = `completion_proof_key_sources AS NOT MATERIALIZED (\n SELECT 'enrollment' AS source,group_id AS id,device_id,public_key,fingerprint FROM enrolled_devices\n UNION ALL SELECT 'controller',attestation_id,device_id,public_key,fingerprint\n FROM coordinator_auth_controller_attestations WHERE coordinator_id=${coordinator}\n UNION ALL SELECT 'invite',invite_id,bound_device_id,bound_public_key,bound_fingerprint\n FROM coordinator_invites WHERE consumed_at IS NOT NULL),\n completion_proof_lines AS NOT MATERIALIZED (\n SELECT *,ltrim(replace(replace(replace(replace(replace(public_key,char(9),' '),char(10),' '),char(11),' '),char(12),' '),char(13),' '),' ') AS line\n FROM completion_proof_key_sources),\n completion_proof_tails AS NOT MATERIALIZED (\n SELECT *,CASE WHEN substr(line,1,12)='ssh-ed25519 ' THEN ltrim(substr(line,13),' ') ELSE NULL END AS tail FROM completion_proof_lines),\n completion_proof_tokens AS MATERIALIZED (\n SELECT *,CASE WHEN tail IS NOT NULL THEN substr(tail,1,instr(tail || ' ',' ')-1) ELSE NULL END AS token FROM completion_proof_tails),\n completion_proof_discovery AS MATERIALIZED (\n SELECT t.* FROM completion_proof_tokens t WHERE EXISTS (SELECT 1 FROM completion_proof_active)\n AND (t.device_id IN (SELECT deviceId FROM completion_proof_active)\n OR t.public_key IN (SELECT publicKey FROM completion_proof_active) OR instr(t.public_key,char(0))>0\n OR t.token IS NULL OR t.token GLOB '*[^A-Za-z0-9+/=_-]*'\n OR EXISTS (SELECT 1 FROM completion_proof_fragments f\n WHERE instr(replace(replace(t.token,'-','+'),'_','/'),f.fragment)>0)))`;\n\nconst resolutionSql = rowset(\n\tRESOLUTION_COLUMNS,\n\t`${table} r WHERE r.coordinator_id=${coordinator}\n AND (r.device_id IN (SELECT deviceId FROM completion_proof_subjects)\n OR r.key_id IN (SELECT keyId FROM completion_proof_subjects))`,\n);\nconst historyParsed = `CASE WHEN json_valid(c.manifest_json) THEN c.manifest_json ELSE '{}' END`;\nconst historyDecision = `CASE WHEN d.type='object' THEN d.value ELSE '{}' END`;\n// Share exact device/fingerprint lookups within each statement, not across capture\n// and INSERT. Only malformed text discovery still needs per-subject matching.\nconst historySql = rowset(\n\t\"c.group_id,c.candidate_ref,c.manifest_version,c.completed_at,c.created_at,c.manifest_json\".split(\n\t\t\",\",\n\t),\n\t`coordinator_legacy_team_completions c\n WHERE (json_extract(${historyParsed},'$.coordinator_id')=${coordinator}\n OR json_extract(${historyParsed},'$.coordinator_id') IS NULL)\n AND (EXISTS (SELECT 1 FROM json_each(${historyParsed},'$.device_decisions') d\n WHERE json_extract(${historyDecision},'$.device_id') IN (SELECT deviceId FROM completion_proof_active)\n OR json_extract(${historyDecision},'$.key_fingerprint') IN (SELECT fingerprint FROM completion_proof_fingerprints)\n OR ((d.type<>'object' OR json_type(${historyDecision},'$.device_id') IS NOT 'text'\n OR json_type(${historyDecision},'$.key_fingerprint') IS NOT 'text')\n AND EXISTS (SELECT 1 FROM completion_proof_active s WHERE\n instr(CASE WHEN d.type='text' THEN json_quote(d.value) ELSE d.value END,json_quote(${field(\"deviceId\")}))>0\n OR EXISTS (SELECT 1 FROM json_each(s.value,'$.fingerprints') f WHERE instr(d.value,f.value)>0))))\n OR ((json_valid(c.manifest_json)=0 OR json_type(${historyParsed},'$.device_decisions') IS NOT 'array')\n AND EXISTS (SELECT 1 FROM completion_proof_active s WHERE instr(c.manifest_json,json_quote(${field(\"deviceId\")}))>0\n OR EXISTS (SELECT 1 FROM json_each(s.value,'$.fingerprints') f WHERE instr(c.manifest_json,f.value)>0))))`,\n);\n\nfunction evidenceQueries(): Record<string, string> {\n\treturn {\n\t\tschema: catalogSql,\n\t\tresolutions: resolutionSql,\n\t\tdiscovery: rowset([\"source\", \"id\"], \"completion_proof_discovery WHERE source<>'enrollment'\"),\n\t\tbindings: rowset(\n\t\t\t\"device_id,key_id,identity_id,coordinator_id,binding_id,provenance,source_ref,bound_at\".split(\n\t\t\t\t\",\",\n\t\t\t),\n\t\t\t`coordinator_device_ownership_bindings WHERE ${collision(\"device_id\", \"key_id\")}`,\n\t\t),\n\t\tclaims: rowset(\n\t\t\t\"claim_id,coordinator_id,identity_id,group_id,device_id,public_key,fingerprint,key_id,attempt_id,issuer,auth_config_revision,created_at_ms\".split(\n\t\t\t\t\",\",\n\t\t\t),\n\t\t\t`coordinator_auth_device_claims WHERE coordinator_id=${coordinator} AND ${collision(\"device_id\", \"key_id\")}`,\n\t\t),\n\t\tcontrollers: rowset(\n\t\t\tCONTROLLER_COLUMNS.map((column) => `c.${column}`),\n\t\t\t`coordinator_auth_controller_attestations c WHERE c.coordinator_id=${coordinator}\n AND (c.attestation_id IN (SELECT id FROM completion_proof_discovery WHERE source='controller')\n OR c.attestation_id IN (SELECT json_extract(row,'$[8]') FROM completion_observed_resolutions))`,\n\t\t),\n\t\tinvites: rowset(\n\t\t\t\"invite_id,group_id,policy,created_at,expires_at,consumed_at,revoked_at,bound_device_id,bound_public_key,bound_fingerprint,invite_kind,assigned_identity_id,target_identity_id,recipient_actor_id,reviewed_preview_digest\".split(\n\t\t\t\t\",\",\n\t\t\t),\n\t\t\t\"coordinator_invites WHERE invite_id IN (SELECT id FROM completion_proof_discovery WHERE source='invite')\",\n\t\t),\n\t\tenrollment: rowset(\n\t\t\t\"e.group_id,e.device_id,e.public_key,e.fingerprint,e.identity_id,e.enabled,g.archived_at\".split(\n\t\t\t\t\",\",\n\t\t\t),\n\t\t\t`enrolled_devices e LEFT JOIN groups g ON g.group_id=e.group_id\n LEFT JOIN completion_proof_keys k ON k.public_key=e.public_key AND k.fingerprint=e.fingerprint\n WHERE ${collision(\"e.device_id\", \"k.key_id\")}`,\n\t\t),\n\t\trevocations: rowset(\n\t\t\t\"subject_kind,subject_value,revocation_id,evidence_group_id,evidence_device_id,evidence_public_key,evidence_fingerprint,actor_id,created_at\".split(\n\t\t\t\t\",\",\n\t\t\t),\n\t\t\t`coordinator_device_revocations v WHERE EXISTS (SELECT 1 FROM completion_proof_active s\n WHERE (v.subject_kind='device_id' AND v.subject_value=${field(\"deviceId\")})\n OR (v.subject_kind='ed25519_key' AND v.subject_value=${field(\"keyId\")}))`,\n\t\t),\n\t\thistory: historySql,\n\t\thistoryKeys: rowset(\n\t\t\t[\"public_key\", \"fingerprint\"],\n\t\t\t\"completion_proof_discovery WHERE source<>'invite'\",\n\t\t),\n\t\thistoryDiscovery: rowset([\"public_key\"], \"completion_proof_discovery WHERE source<>'invite'\"),\n\t};\n}\n\nfunction capturePrefix(queries: Record<string, string>): string {\n\tconst resolutions = queries.resolutions;\n\trequireProof(resolutions);\n\treturn `WITH ${subjectCtes},${discoveryCtes},completion_observed_resolutions(row) AS MATERIALIZED (${resolutions})`;\n}\n\nasync function readRows(\n\tbackend: Backend,\n\tsql: string,\n\tparameters: string[] = [],\n): Promise<{ encoded: string[]; parsed: EvidenceRow[] }> {\n\tconst selected = await backend.all<{ row: string | null }>({\n\t\tsql: `SELECT CASE WHEN SUM(length(CAST(row AS BLOB))) OVER ()<=${MAX_CAPTURE_BYTES}\n THEN row ELSE NULL END AS row FROM (${sql}) LIMIT ${MAX_CAPTURE_BYTES + 1}`,\n\t\tvalues: parameters,\n\t});\n\tconst encoded: string[] = [];\n\tconst parsed = selected.map(({ row }) => {\n\t\trequireProof(typeof row === \"string\");\n\t\tconst value: unknown = JSON.parse(row);\n\t\trequireProof(\n\t\t\tArray.isArray(value) &&\n\t\t\t\tvalue.every(\n\t\t\t\t\t(item) => item === null || typeof item === \"string\" || typeof item === \"number\",\n\t\t\t\t),\n\t\t);\n\t\tencoded.push(row);\n\t\treturn value as EvidenceRow;\n\t});\n\trequireProof(bytes(encoded) <= MAX_CAPTURE_BYTES);\n\treturn { encoded, parsed };\n}\n\nasync function requestedSubjects(input: {\n\tbackend: Backend;\n\tgroupId: string;\n\tmanifestJson: string;\n\tkeyMetadata: string;\n}): Promise<{ subjects: Subject[]; coordinator: string; keys: KeyMetadata[] }> {\n\tconst manifest = normalizeCoordinatorLegacyTeamCompletionManifest(JSON.parse(input.manifestJson));\n\trequireProof(\n\t\tcanonicalCoordinatorLegacyTeamCompletionManifestJson(manifest) === input.manifestJson,\n\t);\n\trequireProof(identifier(input.groupId));\n\tconst selected = await input.backend.all<{\n\t\tdevice_id: string;\n\t\tpublic_key: string;\n\t\tfingerprint: string;\n\t\tidentity_id: string;\n\t\tkey_id: string;\n\t}>({\n\t\tsql: `${LEGACY_OWNER_INPUT_SQL} SELECT r.*,e.public_key FROM legacy_owner_requested r\n JOIN enrolled_devices e ON e.group_id=? AND e.device_id=r.device_id AND e.fingerprint=r.fingerprint`,\n\t\tvalues: [input.manifestJson, input.groupId, input.keyMetadata, input.groupId],\n\t});\n\trequireProof(\n\t\tselected.length === manifest.device_decisions.filter((d) => d.decision === \"included\").length,\n\t);\n\tconst subjects: Subject[] = [];\n\tfor (const row of selected) {\n\t\trequireProof(identifier(row.identity_id) && (await keyId(row.public_key)) === row.key_id);\n\t\tsubjects.push({\n\t\t\tcoordinatorId: manifest.coordinator_id,\n\t\t\tgroupId: input.groupId,\n\t\t\tdeviceId: row.device_id,\n\t\t\tpublicKey: row.public_key,\n\t\t\tfingerprint: row.fingerprint,\n\t\t\tkeyId: row.key_id,\n\t\t\towner: row.identity_id,\n\t\t\tfragments: controllerHistoryDiscoveryFragments(row.public_key),\n\t\t\tfingerprints: [row.fingerprint],\n\t\t});\n\t}\n\treturn { subjects, coordinator: manifest.coordinator_id, keys: JSON.parse(input.keyMetadata) };\n}\n\nfunction relevantFact(row: EvidenceRow, subject: Subject): boolean {\n\treturn row[3] === subject.deviceId || row[4] === subject.keyId;\n}\n\nfunction historyRecord(row: EvidenceRow): ControllerHistoryRecord {\n\treturn Object.fromEntries(\n\t\t[\n\t\t\t\"group_id\",\n\t\t\t\"candidate_ref\",\n\t\t\t\"manifest_version\",\n\t\t\t\"completed_at\",\n\t\t\t\"created_at\",\n\t\t\t\"manifest_json\",\n\t\t].map((column, i) => [column, row[i]]),\n\t) as unknown as ControllerHistoryRecord;\n}\n\nasync function canonicalKeys(rows: EvidenceRows): Promise<Map<string, string>> {\n\tconst keys = new Set<string>();\n\tfor (const row of rows.historyKeys ?? []) keys.add(String(row[0]));\n\tfor (const row of rows.controllers ?? []) keys.add(String(row[5]));\n\tfor (const row of rows.invites ?? []) keys.add(String(row[8]));\n\tconst result = new Map<string, string>();\n\tfor (const text of keys) {\n\t\ttry {\n\t\t\tresult.set(text, await keyId(text));\n\t\t} catch {\n\t\t\t// Discovery is not proof. Relevant device collisions still reach the\n\t\t\t// classifier, which rejects malformed source key text.\n\t\t}\n\t}\n\treturn result;\n}\n\nfunction discoversKey(publicKey: string, subject: Subject): boolean {\n\tif (publicKey === subject.publicKey || publicKey.includes(\"\\u0000\")) return true;\n\tconst line = publicKey.replace(/[\\t\\n\\v\\f\\r]/gu, \" \").replace(/^ +/u, \"\");\n\tif (!line.startsWith(\"ssh-ed25519 \")) return true;\n\tconst token = line.slice(12).replace(/^ +/u, \"\").split(\" \")[0] ?? \"\";\n\tif (/[^A-Za-z0-9+/=_-]/u.test(token)) return true;\n\tconst normalized = token.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\");\n\treturn subject.fragments.some((fragment) => normalized.includes(fragment));\n}\n\n/** Internal capture preparation; not exported from the package entrypoint. */\nexport function prepareCompletionHistory(\n\trows: EvidenceRow[],\n\tdecode: (text: string) => unknown = JSON.parse,\n) {\n\treturn rows.map((row) => {\n\t\tconst record = historyRecord(row);\n\t\tlet decoded = false;\n\t\tlet value: unknown;\n\t\treturn {\n\t\t\trow,\n\t\t\trecord,\n\t\t\tdecode: () => {\n\t\t\t\tif (decoded) return value;\n\t\t\t\tdecoded = true;\n\t\t\t\ttry {\n\t\t\t\t\tvalue = decode(record.manifest_json);\n\t\t\t\t} catch {\n\t\t\t\t\t// A failed raw decode is not itself denial: each subject still\n\t\t\t\t\t// checks whether this malformed row plausibly references it.\n\t\t\t\t}\n\t\t\t\treturn value;\n\t\t\t},\n\t\t};\n\t});\n}\n\n/** Internal subject view; canonical validation remains subject-specific. */\nexport function subjectHistory(\n\trows: EvidenceRows,\n\tsubject: Subject,\n\tkeys: Map<string, string>,\n\tprepared: ReturnType<typeof prepareCompletionHistory>,\n): ControllerHistorySnapshot {\n\tconst pairs = (rows.historyKeys ?? []).filter(\n\t\t(row) => keys.get(String(row[0])) === subject.keyId,\n\t);\n\trequireProof(pairs.length <= MAX_HISTORY_KEYS);\n\tconst fingerprints = new Set([subject.fingerprint, ...pairs.map((row) => String(row[1]))]);\n\tconst records = prepared.filter(({ record, decode }) => {\n\t\t// The SQL selector retains malformed plausible matches. Do not silently drop\n\t\t// them while partitioning a shared capture into individual classifier views.\n\t\tconst value = decode();\n\t\tconst manifest = value as { device_decisions?: unknown[] };\n\t\tif (!Array.isArray(manifest?.device_decisions)) {\n\t\t\trequireProof(!record.manifest_json.includes(JSON.stringify(subject.deviceId)));\n\t\t\trequireProof(![...fingerprints].some((fp) => record.manifest_json.includes(fp)));\n\t\t\treturn false;\n\t\t}\n\t\treturn manifest.device_decisions.some((decision) => {\n\t\t\tconst d = decision as { device_id?: string; key_fingerprint?: string } | null;\n\t\t\tif (d?.device_id === subject.deviceId || fingerprints.has(String(d?.key_fingerprint)))\n\t\t\t\treturn true;\n\t\t\tif (typeof d?.device_id === \"string\" && typeof d?.key_fingerprint === \"string\") return false;\n\t\t\tconst text = JSON.stringify(decision);\n\t\t\treturn (\n\t\t\t\ttext.includes(JSON.stringify(subject.deviceId)) ||\n\t\t\t\t[...fingerprints].some((fp) => text.includes(fp))\n\t\t\t);\n\t\t});\n\t});\n\trequireProof(\n\t\trecords.length <= MAX_SUBJECT_ROWS && bytes(records.map(({ row }) => row)) <= MAX_HISTORY_BYTES,\n\t);\n\tconst history: ControllerHistorySnapshot = {\n\t\t...subject,\n\t\tkeys: pairs.map((row) => ({ public_key: String(row[0]), fingerprint: String(row[1]) })),\n\t\tdiscoveryKeys: (rows.historyDiscovery ?? [])\n\t\t\t.map((row) => String(row[0]))\n\t\t\t.filter((publicKey) => discoversKey(publicKey, subject)),\n\t\tdiscoveryFragments: subject.fragments,\n\t\tfingerprints: [...fingerprints].sort(),\n\t\trecords: records.map(({ record }) => {\n\t\t\tparseControllerHistoryRecord(record, subject.coordinatorId);\n\t\t\treturn record;\n\t\t}),\n\t};\n\trequireProof(bytes(history) <= MAX_HISTORY_BYTES);\n\treturn history;\n}\n\nfunction subjectRows(\n\trows: EvidenceRows,\n\tsubject: Subject,\n\tkeys: Map<string, string>,\n\thistory: ControllerHistorySnapshot,\n): EvidenceRows {\n\tconst matches = (row: EvidenceRow, device: number, key: number) =>\n\t\trow[device] === subject.deviceId ||\n\t\tkeys.get(String(row[key])) === subject.keyId ||\n\t\tdiscoversKey(String(row[key]), subject);\n\tconst selected: EvidenceRows = {\n\t\tbindings: (rows.bindings ?? []).filter(\n\t\t\t(r) => r[0] === subject.deviceId || r[1] === subject.keyId,\n\t\t),\n\t\tclaims: (rows.claims ?? []).filter((r) => r[4] === subject.deviceId || r[7] === subject.keyId),\n\t\tcontrollers: (rows.controllers ?? []).filter((r) => matches(r, 4, 5)),\n\t\tinvites: (rows.invites ?? []).filter((r) => matches(r, 7, 8)),\n\t\tenrollment: (rows.enrollment ?? []).filter(\n\t\t\t(r) => r[0] === subject.groupId && r[1] === subject.deviceId,\n\t\t),\n\t\tresolutions: (rows.resolutions ?? []).filter((r) => relevantFact(r, subject)),\n\t\trevocations: (rows.revocations ?? []).filter(\n\t\t\t(r) =>\n\t\t\t\t(r[0] === \"device_id\" && r[1] === subject.deviceId) ||\n\t\t\t\t(r[0] === \"ed25519_key\" && r[1] === subject.keyId),\n\t\t),\n\t};\n\tfor (const values of Object.values(selected)) requireProof(values.length <= MAX_SUBJECT_ROWS);\n\trequireProof(\n\t\t(selected.controllers?.length ?? 0) + (selected.invites?.length ?? 0) <= MAX_SUBJECT_ROWS,\n\t);\n\trequireProof(bytes(selected) <= MAX_SUBJECT_BYTES);\n\trequireProof(history.discoveryKeys.length <= MAX_DISCOVERY_KEYS);\n\treturn selected;\n}\n\nfunction originalSourceMatches(\n\tresolution: LegacyOwnerResolutionRecord,\n\tsource: EvidenceRow,\n\tsubject: Subject,\n\tkeys: Map<string, string>,\n): boolean {\n\tconst expected: EvidenceRow = [\n\t\tresolution.source_attestation_id,\n\t\tresolution.coordinator_id,\n\t\tresolution.owner_identity_id,\n\t\tresolution.source_group_id,\n\t\tresolution.device_id,\n\t\tresolution.source_public_key,\n\t\tresolution.source_fingerprint,\n\t\tresolution.source_review_receipt_id,\n\t\tresolution.source_evidence_digest,\n\t\tresolution.source_enrollment_identity_id,\n\t\tresolution.source_controller_revision,\n\t\tresolution.source_created_at,\n\t\tnull,\n\t];\n\treturn (\n\t\tsource.length === expected.length &&\n\t\tsource.every((value, i) => value === expected[i]) &&\n\t\tkeys.get(String(source[5])) === subject.keyId\n\t);\n}\n\nasync function hasOriginalSource(\n\trows: EvidenceRows,\n\tsubject: Subject,\n\tkeys: Map<string, string>,\n): Promise<boolean> {\n\tfor (const row of rows.resolutions ?? []) {\n\t\tconst resolution = await captureLegacyOwnerResolutionRecord(\n\t\t\tObject.fromEntries(RESOLUTION_COLUMNS.map((column, i) => [column, row[i]])),\n\t\t);\n\t\trequireProof(resolution);\n\t\tif (\n\t\t\tresolution.coordinator_id === subject.coordinatorId &&\n\t\t\tresolution.device_id === subject.deviceId &&\n\t\t\tresolution.key_id === subject.keyId &&\n\t\t\tresolution.owner_identity_id === subject.owner &&\n\t\t\t(rows.controllers ?? []).some((source) =>\n\t\t\t\toriginalSourceMatches(resolution, source, subject, keys),\n\t\t\t)\n\t\t)\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\nasync function approveSubject(\n\trows: EvidenceRows,\n\tsubject: Subject,\n\tkeys: Map<string, string>,\n\tprepared: ReturnType<typeof prepareCompletionHistory>,\n): Promise<boolean> {\n\tconst history = subjectHistory(rows, subject, keys, prepared);\n\tconst selected = subjectRows(rows, subject, keys, history);\n\tconst classification = await classifyEvidence(selected, subject, subject.owner, history);\n\tif (![\"compatible\", \"weak_label_review_required\"].includes(classification.decision)) return false;\n\t// Duplicate weak source tuples cannot be attributed to one reviewed origin.\n\t// Stored reviewed-label strings are never consulted as positive authority.\n\tif (canonicalReviewedWeakLabels(classification.weakLabels) === null) return false;\n\tconst enrollments = (rows.enrollment ?? []).filter(\n\t\t(row) => row[1] === subject.deviceId || keys.get(String(row[2])) === subject.keyId,\n\t);\n\trequireProof(enrollments.length <= MAX_SUBJECT_ROWS && bytes(enrollments) <= MAX_SUBJECT_BYTES);\n\tfor (const row of enrollments) {\n\t\tif (row[4] === null || row[4] === subject.owner) continue;\n\t\tconst verifiedOrigin = classification.weakLabels.some(\n\t\t\t(weak) =>\n\t\t\t\tweak.label === row[4] &&\n\t\t\t\t(row[0] === subject.groupId || (weak.group_id === row[0] && weak.device_id === row[1])),\n\t\t);\n\t\tif (!verifiedOrigin) return false;\n\t}\n\treturn hasOriginalSource(selected, subject, keys);\n}\n\n/** The WITH prefix each capture read runs under. */\nfunction readPrefix(name: string, queries: Record<string, string>): string {\n\tif (name === \"schema\") return \"\";\n\tif (name === \"resolutions\") return `WITH ${subjectCtes}`;\n\treturn capturePrefix(queries);\n}\n\n/**\n * Internal; exported for its tests. Re-runs one read, `prefix` then a SELECT of distinct\n * `row` texts, and aborts its batch unless those rows are exactly `rows`: equal as sorted\n * text, so each original JSON lexeme must match, and none may be added or removed.\n */\nexport function capturedRowsGuard(\n\tread: { prefix: string; sql: string; values: readonly string[] },\n\trows: readonly string[],\n): AuthLinkStatement {\n\treturn snapshotGuard({\n\t\tsql: `(${read.prefix} SELECT group_concat(row,char(10) ORDER BY row) FROM (${read.sql}))\n IS (SELECT group_concat(value,char(10) ORDER BY value) FROM json_each(?))`,\n\t\tvalues: [...read.values, JSON.stringify(rows)],\n\t});\n}\n\n/** One guard per capture read, bound to the final roster the INSERT also decides on. */\nfunction captureGuards(\n\tqueries: Record<string, string>,\n\trows: Snapshot[\"rows\"],\n\tselectorJson: string,\n): AuthLinkStatement[] {\n\treturn Object.entries(queries).map(([name, sql]) => {\n\t\tconst prefix = readPrefix(name, queries);\n\t\tconst values = prefix ? [selectorJson] : [];\n\t\treturn capturedRowsGuard({ prefix, sql, values }, rows[name] ?? []);\n\t});\n}\n\nconst approvedSubject = `EXISTS (SELECT 1 FROM completion_proof_approved a\n WHERE a.value=json_array(r.device_id,r.key_id,r.identity_id))`;\n/** The approved subjects, each `[device, key, owner]` text. Bind their JSON array. */\nconst approvedCte =\n\t\",completion_proof_approved(value) AS MATERIALIZED (SELECT j.value FROM json_each(?) j)\";\nconst unavailable: ProofSql = {\n\tguards: [],\n\tctes: approvedCte,\n\tcurrentSql: \"0\",\n\tcompatibleSql: \"0\",\n\tvalues: [\"[]\"],\n};\n\n// Only the two weak-label branches gain an exception. Intra-roster owner\n// assignments and ledger bindings retain the exact existing checks.\nfunction replaceExactlyOnce(sql: string, target: string, replacement: string): string {\n\tif (sql.split(target).length !== 2) throw new Error(\"legacy_owner_compatible_sql_drifted\");\n\treturn sql.replace(target, replacement);\n}\n\n// Fails at load rather than silently dropping an exception if the source SQL changes.\nconst recoveredCompatibleSql = replaceExactlyOnce(\n\treplaceExactlyOnce(\n\t\tLEGACY_OWNER_COMPATIBLE_SQL,\n\t\t\"WHERE e.identity_id IS NOT NULL AND e.identity_id <> r.identity_id\",\n\t\t`WHERE e.identity_id IS NOT NULL AND e.identity_id <> r.identity_id AND NOT (${approvedSubject})`,\n\t),\n\t\"AND json_extract(d.value, '$.identity_id') <> r.identity_id\",\n\t`AND json_extract(d.value, '$.identity_id') <> r.identity_id AND NOT (${approvedSubject})`,\n);\n\nfunction remember(sql: ProofSql): LegacyCompletionOwnerProof {\n\tconst token = Object.freeze({ version: 1 as const });\n\tsnapshots.set(\n\t\ttoken,\n\t\tObject.freeze({\n\t\t\t...sql,\n\t\t\tguards: Object.freeze(sql.guards.map((guard) => Object.freeze({ ...guard }))),\n\t\t\tvalues: Object.freeze([...sql.values]),\n\t\t}),\n\t);\n\treturn token;\n}\n\nfunction finishCapture(\n\tsnapshot: Snapshot,\n\tqueries: Record<string, string>,\n\toptions: { compatible: boolean; recovered: boolean },\n): LegacyCompletionOwnerProof {\n\trequireProof(encoder.encode(encodeSnapshot(snapshot)).byteLength <= MAX_CAPTURE_BYTES);\n\tlet compatibleSql = \"0\";\n\tif (options.compatible) {\n\t\tcompatibleSql = LEGACY_OWNER_COMPATIBLE_SQL;\n\t\tif (options.recovered) compatibleSql = recoveredCompatibleSql;\n\t}\n\treturn remember({\n\t\tguards: captureGuards(queries, snapshot.rows, encodeSelector(snapshot)),\n\t\tctes: approvedCte,\n\t\tcurrentSql: \"1\",\n\t\tcompatibleSql,\n\t\tvalues: [JSON.stringify(snapshot.approved)],\n\t});\n}\n\nasync function captureReady(\n\tbackend: Backend,\n\tsnapshot: Snapshot,\n): Promise<LegacyCompletionOwnerProof> {\n\tconst queries = evidenceQueries();\n\tconst initialPrefix = `WITH ${subjectCtes}`;\n\tconst facts = await readRows(backend, `${initialPrefix} ${resolutionSql}`, [\n\t\tencodeSelector(snapshot),\n\t]);\n\tsnapshot.rows.resolutions = facts.encoded;\n\tsnapshot.active = snapshot.subjects.filter((s) => facts.parsed.some((r) => relevantFact(r, s)));\n\tif (snapshot.active.length === 0)\n\t\treturn finishCapture(\n\t\t\tsnapshot,\n\t\t\t{ schema: catalogSql, resolutions: resolutionSql },\n\t\t\t{ compatible: true, recovered: false },\n\t\t);\n\tconst rows: EvidenceRows = { resolutions: facts.parsed };\n\tconst prefix = capturePrefix(queries);\n\t// Capture the shared key inventory once before selecting history by verified\n\t// aliases. History bytes and source rows are stored once, not per roster member.\n\tfor (const name of [\"historyKeys\", \"historyDiscovery\"]) {\n\t\tconst sql = queries[name];\n\t\trequireProof(sql);\n\t\tconst result = await readRows(backend, `${prefix} ${sql}`, [encodeSelector(snapshot)]);\n\t\trows[name] = result.parsed;\n\t\tsnapshot.rows[name] = result.encoded;\n\t}\n\tconst aliasKeys = await canonicalKeys(rows);\n\tfor (const subject of snapshot.active) {\n\t\tsubject.fingerprints = [\n\t\t\t...new Set([\n\t\t\t\tsubject.fingerprint,\n\t\t\t\t...(rows.historyKeys ?? [])\n\t\t\t\t\t.filter((row) => aliasKeys.get(String(row[0])) === subject.keyId)\n\t\t\t\t\t.map((row) => String(row[1])),\n\t\t\t]),\n\t\t].sort();\n\t}\n\tfor (const [name, sql] of Object.entries(queries)) {\n\t\tif (Object.hasOwn(snapshot.rows, name)) continue;\n\t\tconst result = await readRows(backend, `${prefix} ${sql}`, [encodeSelector(snapshot)]);\n\t\trows[name] = result.parsed;\n\t\tsnapshot.rows[name] = result.encoded;\n\t}\n\tconst keys = await canonicalKeys(rows);\n\tconst prepared = prepareCompletionHistory(rows.history ?? []);\n\tlet compatible = true;\n\tfor (const subject of snapshot.active) {\n\t\tif (!(await approveSubject(rows, subject, keys, prepared))) {\n\t\t\tcompatible = false;\n\t\t\tcontinue;\n\t\t}\n\t\tsnapshot.approved.push(JSON.stringify([subject.deviceId, subject.keyId, subject.owner]));\n\t}\n\treturn finishCapture(snapshot, queries, { compatible, recovered: true });\n}\n\n/** Read-only capture. No submitted approved-subject list or source reference is accepted.\n * Call only after the stores validate the canonical manifest and its source binding.\n */\nexport async function captureLegacyCompletionOwnerProof(input: {\n\tbackend: Backend;\n\tgroupId: string;\n\tmanifestJson: string;\n\tkeyMetadata: string;\n}): Promise<LegacyCompletionOwnerProof> {\n\ttry {\n\t\tconst requested = await requestedSubjects(input);\n\t\tconst catalog = await readRows(input.backend, catalogSql);\n\t\tconst state = classifyLegacyOwnerResolutionSchemaCatalog(\n\t\t\tcatalog.parsed.map(([type, name, tbl_name, sql]) => ({ type, name, tbl_name, sql })),\n\t\t);\n\t\tconst snapshot: Snapshot = {\n\t\t\t...requested,\n\t\t\tactive: [],\n\t\t\trows: { schema: catalog.encoded },\n\t\t\tapproved: [],\n\t\t};\n\t\tif (state === \"unsupported\") return remember(unavailable);\n\t\tif (state === \"missing\")\n\t\t\treturn finishCapture(\n\t\t\t\tsnapshot,\n\t\t\t\t{ schema: catalogSql },\n\t\t\t\t{ compatible: true, recovered: false },\n\t\t\t);\n\t\treturn await captureReady(input.backend, snapshot);\n\t} catch {\n\t\treturn remember(unavailable);\n\t}\n}\n\n/** The winning INSERT must use both predicates, in one batch its guards lead. A token\n * by itself grants nothing. Keep LEGACY_OWNER_SOURCE_CURRENT_SQL and all ordinary\n * completion checks as well.\n */\nexport function legacyCompletionOwnerProofSql(proof: LegacyCompletionOwnerProof): ProofSql {\n\treturn snapshots.get(proof) ?? unavailable;\n}\n","import type {\n\tCoordinatorGrantScopeMembershipInput,\n\tCoordinatorRevokeScopeMembershipInput,\n\tCoordinatorScopeMembership,\n} from \"./coordinator-store-contract.js\";\n\nexport const SCOPE_MEMBERSHIP_EFFECT_CONFLICT = \"scope_membership_effect_conflict\";\n\nexport type CoordinatorMembershipErrorCode =\n\t| \"device_not_enrolled\"\n\t| \"scope_group_mismatch\"\n\t| \"scope_inactive\"\n\t| \"scope_not_found\";\n\nconst MEMBERSHIP_ERROR_MESSAGES: Record<CoordinatorMembershipErrorCode, string> = {\n\tdevice_not_enrolled: \"device must be enrolled and enabled in the scope group.\",\n\tscope_group_mismatch: \"membership groupId must match the scope groupId.\",\n\tscope_inactive: \"scope is not active.\",\n\tscope_not_found: \"scopeId must reference an existing scope.\",\n};\n\nexport class CoordinatorMembershipError extends Error {\n\treadonly code: CoordinatorMembershipErrorCode;\n\n\tconstructor(code: CoordinatorMembershipErrorCode) {\n\t\tsuper(MEMBERSHIP_ERROR_MESSAGES[code]);\n\t\tthis.name = \"CoordinatorMembershipError\";\n\t\tthis.code = code;\n\t}\n}\n\nexport interface CoordinatorMembershipEffectReceipt {\n\teffect_id: string;\n\taction: \"grant\" | \"revoke\";\n\trequest_json: string;\n\toutcome_applied: number;\n\tscope_id: string;\n\tdevice_id: string;\n\trole: string | null;\n\tstatus: string | null;\n\tmembership_epoch: number | null;\n\tcoordinator_id: string | null;\n\tgroup_id: string | null;\n\tmanifest_issuer_device_id: string | null;\n\tmanifest_hash: string | null;\n\tsigned_manifest_json: string | null;\n\tupdated_at: string | null;\n\tcreated_at: string;\n}\n\nfunction clean(value: string | null | undefined): string | null {\n\tconst normalized = value?.trim();\n\treturn normalized ? normalized : null;\n}\n\nexport function normalizeMembershipEffectId(value: string): string {\n\tconst effectId = clean(value);\n\tif (!effectId) throw new Error(\"effectId is required.\");\n\tif (effectId.length > 512 || /[\\p{Cc}\\p{Cf}]/u.test(effectId)) {\n\t\tthrow new Error(\"effectId is invalid.\");\n\t}\n\treturn effectId;\n}\n\nexport function grantMembershipEffectRequestJson(\n\topts: CoordinatorGrantScopeMembershipInput,\n): string {\n\treturn JSON.stringify({\n\t\tscopeId: clean(opts.scopeId),\n\t\tdeviceId: clean(opts.deviceId),\n\t\trole: clean(opts.role),\n\t\tmembershipEpoch: opts.membershipEpoch ?? null,\n\t\tcoordinatorId: clean(opts.coordinatorId),\n\t\tgroupId: clean(opts.groupId),\n\t\tmanifestIssuerDeviceId: clean(opts.manifestIssuerDeviceId),\n\t\tmanifestHash: clean(opts.manifestHash),\n\t\tsignedManifestJson: clean(opts.signedManifestJson),\n\t\tactorType: clean(opts.actorType),\n\t\tactorId: clean(opts.actorId),\n\t});\n}\n\nexport function revokeMembershipEffectRequestJson(\n\topts: CoordinatorRevokeScopeMembershipInput,\n): string {\n\treturn JSON.stringify({\n\t\tscopeId: clean(opts.scopeId),\n\t\tdeviceId: clean(opts.deviceId),\n\t\tgroupId: clean(opts.groupId),\n\t\tmembershipEpoch: opts.membershipEpoch ?? null,\n\t\tmanifestHash: clean(opts.manifestHash),\n\t\tsignedManifestJson: clean(opts.signedManifestJson),\n\t\tactorType: clean(opts.actorType),\n\t\tactorId: clean(opts.actorId),\n\t});\n}\n\nexport function assertMatchingMembershipEffectReceipt(\n\treceipt: CoordinatorMembershipEffectReceipt,\n\taction: CoordinatorMembershipEffectReceipt[\"action\"],\n\trequestJson: string,\n): void {\n\tif (receipt.action !== action || receipt.request_json !== requestJson) {\n\t\tthrow new Error(SCOPE_MEMBERSHIP_EFFECT_CONFLICT);\n\t}\n}\n\nexport function membershipFromEffectReceipt(\n\treceipt: CoordinatorMembershipEffectReceipt,\n): CoordinatorScopeMembership {\n\tif (\n\t\treceipt.action !== \"grant\" ||\n\t\treceipt.outcome_applied !== 1 ||\n\t\treceipt.role == null ||\n\t\treceipt.status == null ||\n\t\treceipt.membership_epoch == null ||\n\t\treceipt.updated_at == null\n\t) {\n\t\tthrow new Error(\"scope_membership_effect_receipt_invalid\");\n\t}\n\treturn {\n\t\tscope_id: receipt.scope_id,\n\t\tdevice_id: receipt.device_id,\n\t\trole: receipt.role,\n\t\tstatus: receipt.status,\n\t\tmembership_epoch: receipt.membership_epoch,\n\t\tcoordinator_id: receipt.coordinator_id,\n\t\tgroup_id: receipt.group_id,\n\t\tmanifest_issuer_device_id: receipt.manifest_issuer_device_id,\n\t\tmanifest_hash: receipt.manifest_hash,\n\t\tsigned_manifest_json: receipt.signed_manifest_json,\n\t\tupdated_at: receipt.updated_at,\n\t};\n}\n","/** Inert ceremony storage, not a verified-identity capability or an enrollment writer.\n * Finalized rows are retained prior-commit receipts, never current permission.\n * The winning future UPDATE must write the outcome and purge handoff material together.\n * Fresh installs only: existing tables require explicit migration 0036, never a rebuild on open.\n */\nexport const COORDINATOR_OWNER_ENROLLMENT_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS coordinator_owner_enrollment_attempts (\n coordinator_id TEXT NOT NULL CHECK (typeof(coordinator_id) = 'text' AND length(trim(coordinator_id)) BETWEEN 1 AND 256 AND instr(coordinator_id, char(0)) = 0),\n attempt_id TEXT NOT NULL CHECK (typeof(attempt_id) = 'text' AND length(trim(attempt_id)) BETWEEN 1 AND 256 AND instr(attempt_id, char(0)) = 0),\n purpose TEXT NOT NULL CHECK (purpose = 'owner_enroll'),\n origin TEXT NOT NULL CHECK (typeof(origin) = 'text' AND length(trim(origin)) > 0 AND instr(origin, char(0)) = 0),\n device_id TEXT NOT NULL CHECK (typeof(device_id) = 'text' AND length(trim(device_id)) BETWEEN 1 AND 256 AND instr(device_id, char(0)) = 0),\n public_key TEXT NOT NULL CHECK (typeof(public_key) = 'text' AND length(trim(public_key)) > 0 AND instr(public_key, 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 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 issuer TEXT NOT NULL CHECK (typeof(issuer) = 'text' AND length(trim(issuer)) > 0 AND instr(issuer, char(0)) = 0),\n auth_config_revision TEXT NOT NULL CHECK (typeof(auth_config_revision) = 'text' AND length(auth_config_revision) = 64 AND auth_config_revision NOT GLOB '*[^0-9a-f]*' AND instr(auth_config_revision, char(0)) = 0),\n loopback_redirect TEXT CHECK (loopback_redirect IS NULL OR (typeof(loopback_redirect) = 'text' AND length(trim(loopback_redirect)) > 0 AND instr(loopback_redirect, char(0)) = 0)),\n browser_start_hash TEXT NOT NULL CHECK (typeof(browser_start_hash) = 'text' AND length(browser_start_hash) = 64 AND browser_start_hash NOT GLOB '*[^0-9a-f]*' AND instr(browser_start_hash, char(0)) = 0),\n browser_transaction_hash TEXT CHECK (browser_transaction_hash IS NULL OR (typeof(browser_transaction_hash) = 'text' AND length(browser_transaction_hash) = 64 AND browser_transaction_hash NOT GLOB '*[^0-9a-f]*' AND instr(browser_transaction_hash, char(0)) = 0)),\n browser_binder_hash TEXT CHECK (browser_binder_hash IS NULL OR (typeof(browser_binder_hash) = 'text' AND length(browser_binder_hash) = 64 AND browser_binder_hash NOT GLOB '*[^0-9a-f]*' AND instr(browser_binder_hash, char(0)) = 0)),\n account_subject TEXT CHECK (account_subject IS NULL OR (typeof(account_subject) = 'text' AND length(account_subject) BETWEEN 1 AND 255 AND instr(account_subject, char(0)) = 0)),\n identity_id TEXT CHECK (identity_id IS NULL OR (typeof(identity_id) = 'text' AND length(trim(identity_id)) BETWEEN 1 AND 256 AND instr(identity_id, char(0)) = 0)),\n link_id TEXT CHECK (link_id IS NULL OR (typeof(link_id) = 'text' AND length(trim(link_id)) BETWEEN 1 AND 256 AND instr(link_id, char(0)) = 0)),\n link_attempt_id TEXT CHECK (link_attempt_id IS NULL OR (typeof(link_attempt_id) = 'text' AND length(trim(link_attempt_id)) BETWEEN 1 AND 256 AND instr(link_attempt_id, char(0)) = 0)),\n link_controller_attestation_id TEXT CHECK (link_controller_attestation_id IS NULL OR (typeof(link_controller_attestation_id) = 'text' AND length(trim(link_controller_attestation_id)) BETWEEN 1 AND 256 AND instr(link_controller_attestation_id, char(0)) = 0)),\n link_auth_config_revision TEXT CHECK (link_auth_config_revision IS NULL OR (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 grant_revisions_json TEXT CHECK (grant_revisions_json IS NULL OR (typeof(grant_revisions_json) = 'text' AND json_valid(grant_revisions_json) AND json_type(grant_revisions_json) = 'array')),\n confirmation_hash TEXT CHECK (confirmation_hash IS NULL OR (typeof(confirmation_hash) = 'text' AND length(confirmation_hash) = 64 AND confirmation_hash NOT GLOB '*[^0-9a-f]*' AND instr(confirmation_hash, char(0)) = 0)),\n completion_secret_hash TEXT CHECK (completion_secret_hash IS NULL OR (typeof(completion_secret_hash) = 'text' AND length(completion_secret_hash) = 64 AND completion_secret_hash NOT GLOB '*[^0-9a-f]*' AND instr(completion_secret_hash, char(0)) = 0)),\n final_key_proof_hash TEXT CHECK (final_key_proof_hash IS NULL OR (typeof(final_key_proof_hash) = 'text' AND length(final_key_proof_hash) = 64 AND final_key_proof_hash NOT GLOB '*[^0-9a-f]*' AND instr(final_key_proof_hash, char(0)) = 0)),\n state TEXT NOT NULL CHECK (state IN ('pending','browser_claimed','oidc_verified','confirmed','finalized','expired','failed','retired')),\n created_at_ms INTEGER NOT NULL CHECK (typeof(created_at_ms) = 'integer' AND created_at_ms BETWEEN 0 AND 9007199254140991),\n expires_at_ms INTEGER NOT NULL CHECK (typeof(expires_at_ms) = 'integer' AND expires_at_ms = created_at_ms + 600000),\n finalized_at_ms INTEGER CHECK (finalized_at_ms IS NULL OR (typeof(finalized_at_ms) = 'integer' AND finalized_at_ms >= created_at_ms AND finalized_at_ms < expires_at_ms)),\n binding_id TEXT CHECK (binding_id IS NULL OR (typeof(binding_id) = 'text' AND length(trim(binding_id)) BETWEEN 1 AND 256 AND instr(binding_id, char(0)) = 0)),\n audit_event_id TEXT CHECK (audit_event_id IS NULL OR (typeof(audit_event_id) = 'text' AND length(trim(audit_event_id)) BETWEEN 1 AND 256 AND instr(audit_event_id, char(0)) = 0)),\n final_outcome_json TEXT CHECK (final_outcome_json IS NULL OR (typeof(final_outcome_json) = 'text' AND json_valid(final_outcome_json) AND json_type(final_outcome_json) = 'object')),\n admission_owner_hash TEXT CHECK (admission_owner_hash IS NULL OR (typeof(admission_owner_hash) = 'text' AND length(admission_owner_hash) = 64 AND admission_owner_hash NOT GLOB '*[^0-9a-f]*' AND instr(admission_owner_hash, char(0)) = 0)),\n owner_qualification_id TEXT CHECK (owner_qualification_id IS NULL OR (typeof(owner_qualification_id) = 'text' AND length(owner_qualification_id) BETWEEN 1 AND 256 AND owner_qualification_id = trim(owner_qualification_id) AND length(trim(owner_qualification_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(owner_qualification_id, char(0)) = 0)),\n PRIMARY KEY (coordinator_id, attempt_id),\n UNIQUE (coordinator_id, browser_start_hash),\n UNIQUE (coordinator_id, browser_transaction_hash),\n UNIQUE (coordinator_id, completion_secret_hash),\n CHECK (state NOT IN ('pending','browser_claimed','oidc_verified','confirmed') OR loopback_redirect IS NOT NULL),\n CHECK (state <> 'pending' OR browser_transaction_hash IS NULL),\n CHECK ((browser_transaction_hash IS NULL) = (browser_binder_hash IS NULL)),\n CHECK (state NOT IN ('pending','browser_claimed') OR account_subject IS NULL),\n CHECK (state NOT IN ('pending','browser_claimed','oidc_verified') OR (confirmation_hash IS NULL AND completion_secret_hash IS NULL)),\n CHECK (state NOT IN ('browser_claimed','oidc_verified','confirmed','finalized') OR browser_transaction_hash IS NOT NULL),\n CHECK ((account_subject IS NULL AND identity_id IS NULL AND link_id IS NULL AND link_attempt_id IS NULL AND link_controller_attestation_id IS NULL AND owner_qualification_id IS NULL AND link_auth_config_revision IS NULL AND grant_revisions_json IS NULL) OR (account_subject IS NOT NULL AND identity_id IS NOT NULL AND link_id IS NOT NULL AND link_attempt_id IS NOT NULL AND ((link_controller_attestation_id IS NOT NULL AND owner_qualification_id IS NULL) OR (link_controller_attestation_id IS NULL AND owner_qualification_id IS NOT NULL)) AND link_auth_config_revision IS NOT NULL AND grant_revisions_json IS NOT NULL)),\n CHECK (state NOT IN ('oidc_verified','confirmed','finalized') OR account_subject IS NOT NULL),\n CHECK (state NOT IN ('confirmed','finalized') OR (confirmation_hash IS NOT NULL AND completion_secret_hash IS NOT NULL)),\n CHECK ((state = 'finalized' AND finalized_at_ms IS NOT NULL AND binding_id IS NOT NULL AND audit_event_id IS NOT NULL AND final_outcome_json IS NOT NULL AND final_key_proof_hash IS NOT NULL AND loopback_redirect IS NULL) OR (state <> 'finalized' AND finalized_at_ms IS NULL AND binding_id IS NULL AND audit_event_id IS NULL AND final_outcome_json IS NULL AND final_key_proof_hash IS NULL))\n);\nCREATE INDEX IF NOT EXISTS idx_owner_enrollment_device_created\n ON coordinator_owner_enrollment_attempts(coordinator_id, device_id, created_at_ms);\nCREATE INDEX IF NOT EXISTS idx_owner_enrollment_identity_expiry\n ON coordinator_owner_enrollment_attempts(coordinator_id, identity_id, expires_at_ms);\nCREATE INDEX IF NOT EXISTS idx_owner_enrollment_state_expiry\n ON coordinator_owner_enrollment_attempts(coordinator_id, state, expires_at_ms);\n-- Birth facts and recorded commitments survive retries and transient browser cleanup.\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_pins_update\nBEFORE UPDATE ON coordinator_owner_enrollment_attempts WHEN OLD.state <> 'finalized' AND (\n OLD.coordinator_id IS NOT NEW.coordinator_id OR OLD.attempt_id IS NOT NEW.attempt_id\n OR OLD.purpose IS NOT NEW.purpose OR OLD.origin IS NOT NEW.origin\n OR OLD.device_id IS NOT NEW.device_id OR OLD.public_key IS NOT NEW.public_key\n OR OLD.key_id IS NOT NEW.key_id OR OLD.fingerprint IS NOT NEW.fingerprint\n OR OLD.issuer IS NOT NEW.issuer OR OLD.auth_config_revision IS NOT NEW.auth_config_revision\n OR OLD.browser_start_hash IS NOT NEW.browser_start_hash\n OR OLD.created_at_ms IS NOT NEW.created_at_ms OR OLD.expires_at_ms IS NOT NEW.expires_at_ms\n OR (OLD.loopback_redirect IS NOT NEW.loopback_redirect AND NOT (\n OLD.loopback_redirect IS NOT NULL AND NEW.loopback_redirect IS NULL\n AND NEW.state IN ('finalized','expired','failed','retired')))\n OR (OLD.browser_transaction_hash IS NOT NULL AND OLD.browser_transaction_hash IS NOT NEW.browser_transaction_hash)\n OR (OLD.browser_binder_hash IS NOT NULL AND OLD.browser_binder_hash IS NOT NEW.browser_binder_hash)\n OR (OLD.account_subject IS NOT NULL AND OLD.account_subject IS NOT NEW.account_subject)\n OR (OLD.identity_id IS NOT NULL AND OLD.identity_id IS NOT NEW.identity_id)\n OR (OLD.link_id IS NOT NULL AND OLD.link_id IS NOT NEW.link_id)\n OR (OLD.link_attempt_id IS NOT NULL AND OLD.link_attempt_id IS NOT NEW.link_attempt_id)\n OR (OLD.link_controller_attestation_id IS NOT NULL AND OLD.link_controller_attestation_id IS NOT NEW.link_controller_attestation_id)\n OR (OLD.link_auth_config_revision IS NOT NULL AND OLD.link_auth_config_revision IS NOT NEW.link_auth_config_revision)\n OR (OLD.grant_revisions_json IS NOT NULL AND OLD.grant_revisions_json IS NOT NEW.grant_revisions_json)\n OR (OLD.confirmation_hash IS NOT NULL AND OLD.confirmation_hash IS NOT NEW.confirmation_hash)\n OR (OLD.completion_secret_hash IS NOT NULL AND OLD.completion_secret_hash IS NOT NEW.completion_secret_hash)\n OR (OLD.browser_transaction_hash IS NULL AND NEW.browser_transaction_hash IS NOT NULL\n AND NOT (OLD.state = 'pending' AND NEW.state = 'browser_claimed'))\n OR (OLD.account_subject IS NULL AND NEW.account_subject IS NOT NULL\n AND NOT (OLD.state = 'browser_claimed' AND NEW.state = 'oidc_verified'))\n OR ((OLD.confirmation_hash IS NULL AND NEW.confirmation_hash IS NOT NULL\n OR OLD.completion_secret_hash IS NULL AND NEW.completion_secret_hash IS NOT NULL)\n AND NOT (OLD.state = 'oidc_verified' AND NEW.state = 'confirmed'))\n OR (OLD.state IN ('expired','failed','retired') AND OLD.state IS NOT NEW.state)\n OR (EXISTS (SELECT 1 FROM coordinator_owner_enrollment_attempts a WHERE a.state <> 'finalized'\n AND a.rowid <> OLD.rowid AND (a.rowid = NEW.rowid OR (a.coordinator_id = NEW.coordinator_id\n AND (a.attempt_id = NEW.attempt_id OR a.browser_start_hash = NEW.browser_start_hash\n OR a.browser_transaction_hash = NEW.browser_transaction_hash OR a.completion_secret_hash = NEW.completion_secret_hash))))\n AND NOT EXISTS (SELECT 1 FROM coordinator_owner_enrollment_attempts a WHERE a.state = 'finalized'\n AND a.rowid <> OLD.rowid AND (a.rowid = NEW.rowid OR (a.coordinator_id = NEW.coordinator_id\n AND (a.attempt_id = NEW.attempt_id OR a.browser_start_hash = NEW.browser_start_hash\n OR a.browser_transaction_hash = NEW.browser_transaction_hash OR a.completion_secret_hash = NEW.completion_secret_hash)))))\n)\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_pins_immutable'); END;\n-- REPLACE can delete a conflicting row without running UPDATE or DELETE triggers.\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_pins_insert\nBEFORE INSERT ON coordinator_owner_enrollment_attempts\nWHEN EXISTS (SELECT 1 FROM coordinator_owner_enrollment_attempts a WHERE a.state <> 'finalized'\n AND (a.rowid = NEW.rowid OR (a.coordinator_id = NEW.coordinator_id AND (a.attempt_id = NEW.attempt_id\n OR a.browser_start_hash = NEW.browser_start_hash OR a.browser_transaction_hash = NEW.browser_transaction_hash\n OR a.completion_secret_hash = NEW.completion_secret_hash)))\n AND (a.coordinator_id,a.attempt_id,a.purpose,a.origin,a.device_id,a.public_key,a.key_id,a.fingerprint,\n a.issuer,a.auth_config_revision,a.loopback_redirect,a.browser_start_hash,a.browser_transaction_hash,a.browser_binder_hash,\n a.account_subject,a.identity_id,a.link_id,a.link_attempt_id,a.link_controller_attestation_id,a.link_auth_config_revision,\n a.grant_revisions_json,a.confirmation_hash,a.completion_secret_hash,a.final_key_proof_hash,a.state,\n a.created_at_ms,a.expires_at_ms,a.finalized_at_ms,a.binding_id,a.audit_event_id,a.final_outcome_json)\n IS NOT (NEW.coordinator_id,NEW.attempt_id,NEW.purpose,NEW.origin,NEW.device_id,NEW.public_key,NEW.key_id,NEW.fingerprint,\n NEW.issuer,NEW.auth_config_revision,NEW.loopback_redirect,NEW.browser_start_hash,NEW.browser_transaction_hash,NEW.browser_binder_hash,\n NEW.account_subject,NEW.identity_id,NEW.link_id,NEW.link_attempt_id,NEW.link_controller_attestation_id,NEW.link_auth_config_revision,\n NEW.grant_revisions_json,NEW.confirmation_hash,NEW.completion_secret_hash,NEW.final_key_proof_hash,NEW.state,\n NEW.created_at_ms,NEW.expires_at_ms,NEW.finalized_at_ms,NEW.binding_id,NEW.audit_event_id,NEW.final_outcome_json))\n AND NOT EXISTS (SELECT 1 FROM coordinator_owner_enrollment_attempts a WHERE a.state = 'finalized'\n AND (a.rowid = NEW.rowid OR (a.coordinator_id = NEW.coordinator_id AND (a.attempt_id = NEW.attempt_id\n OR a.browser_start_hash = NEW.browser_start_hash OR a.browser_transaction_hash = NEW.browser_transaction_hash\n OR a.completion_secret_hash = NEW.completion_secret_hash))))\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_pins_immutable'); END;\n-- Admission is a birth fact, including NULL for preexisting/operator attempts.\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_admission_update\nBEFORE UPDATE ON coordinator_owner_enrollment_attempts\nWHEN OLD.admission_owner_hash IS NOT NEW.admission_owner_hash\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_admission_immutable'); END;\n-- Probe each unique key separately; a coordinator-only OR plan scans every prior attempt.\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_admission_insert\nBEFORE INSERT ON coordinator_owner_enrollment_attempts\nWHEN EXISTS (SELECT 1 FROM coordinator_owner_enrollment_attempts a\n WHERE a.rowid IN (\n SELECT rowid FROM coordinator_owner_enrollment_attempts WHERE rowid = NEW.rowid\n UNION ALL SELECT rowid FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = NEW.coordinator_id AND attempt_id = NEW.attempt_id\n UNION ALL SELECT rowid FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = NEW.coordinator_id AND browser_start_hash = NEW.browser_start_hash\n UNION ALL SELECT rowid FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = NEW.coordinator_id AND browser_transaction_hash = NEW.browser_transaction_hash\n UNION ALL SELECT rowid FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = NEW.coordinator_id AND completion_secret_hash = NEW.completion_secret_hash)\n AND a.admission_owner_hash IS NOT NEW.admission_owner_hash)\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_admission_immutable'); END;\n-- The authority branch, including its NULL pin, is fixed at first owner resolution.\n-- A device-claim qualification never becomes the original link's controller attestation.\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_authority_update\nBEFORE UPDATE ON coordinator_owner_enrollment_attempts\nWHEN (OLD.account_subject IS NOT NULL AND (\n OLD.owner_qualification_id IS NOT NEW.owner_qualification_id\n OR OLD.link_controller_attestation_id IS NOT NEW.link_controller_attestation_id))\n OR (OLD.owner_qualification_id IS NOT NEW.owner_qualification_id AND NOT (\n OLD.account_subject IS NULL AND NEW.account_subject IS NOT NULL\n AND OLD.state = 'browser_claimed' AND NEW.state = 'oidc_verified'))\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_pins_immutable'); END;\n-- REPLACE and UPSERT must not switch authority through any unique-key collision.\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_authority_insert\nBEFORE INSERT ON coordinator_owner_enrollment_attempts\nWHEN EXISTS (SELECT 1 FROM coordinator_owner_enrollment_attempts a\n WHERE a.rowid IN (\n SELECT rowid FROM coordinator_owner_enrollment_attempts WHERE rowid = NEW.rowid\n UNION ALL SELECT rowid FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = NEW.coordinator_id AND attempt_id = NEW.attempt_id\n UNION ALL SELECT rowid FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = NEW.coordinator_id AND browser_start_hash = NEW.browser_start_hash\n UNION ALL SELECT rowid FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = NEW.coordinator_id AND browser_transaction_hash = NEW.browser_transaction_hash\n UNION ALL SELECT rowid FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = NEW.coordinator_id AND completion_secret_hash = NEW.completion_secret_hash)\n AND (a.owner_qualification_id IS NOT NEW.owner_qualification_id\n OR a.link_controller_attestation_id IS NOT NEW.link_controller_attestation_id))\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_pins_immutable'); END;\n-- Retained receipts cannot be changed, deleted, or erased through REPLACE.\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_finalized_update\nBEFORE UPDATE ON coordinator_owner_enrollment_attempts WHEN OLD.state = 'finalized'\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_receipt_immutable'); END;\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_finalized_update_collision\nBEFORE UPDATE ON coordinator_owner_enrollment_attempts\nWHEN EXISTS (SELECT 1 FROM coordinator_owner_enrollment_attempts a WHERE a.state = 'finalized'\n AND a.rowid <> OLD.rowid AND (a.rowid = NEW.rowid OR (a.coordinator_id = NEW.coordinator_id\n AND (a.attempt_id = NEW.attempt_id OR a.browser_start_hash = NEW.browser_start_hash\n OR a.browser_transaction_hash = NEW.browser_transaction_hash OR a.completion_secret_hash = NEW.completion_secret_hash))))\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_receipt_immutable'); END;\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_finalized_delete\nBEFORE DELETE ON coordinator_owner_enrollment_attempts WHEN OLD.state = 'finalized'\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_receipt_immutable'); END;\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_finalized_replace\nBEFORE INSERT ON coordinator_owner_enrollment_attempts\nWHEN EXISTS (SELECT 1 FROM coordinator_owner_enrollment_attempts a WHERE a.state = 'finalized'\n AND (a.rowid = NEW.rowid OR (a.coordinator_id = NEW.coordinator_id AND (a.attempt_id = NEW.attempt_id\n OR a.browser_start_hash = NEW.browser_start_hash OR a.browser_transaction_hash = NEW.browser_transaction_hash\n OR a.completion_secret_hash = NEW.completion_secret_hash))))\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_receipt_immutable'); END;\n`;\n","import type { ControllerHistorySnapshot } from \"./coordinator-auth-controller-history.js\";\nimport {\n\ttype EvidenceRow,\n\ttype EvidenceRows,\n\ttype EvidenceSubject,\n\tevidenceRows,\n\tkeyId,\n} from \"./coordinator-device-ownership-evidence-classify.js\";\n\nfunction canonicalRows(rows: EvidenceRow[]): string[] {\n\treturn rows.map((row) => JSON.stringify(row)).sort();\n}\n\nasync function actualSubjectRows(\n\trows: EvidenceRow[],\n\tsubject: EvidenceSubject,\n\tcolumns: { device: number; publicKey: number },\n): Promise<EvidenceRow[]> {\n\tconst relevant: EvidenceRow[] = [];\n\tfor (const row of rows) {\n\t\tif (\n\t\t\trow[columns.device] === subject.deviceId ||\n\t\t\t(await keyId(row[columns.publicKey])) === subject.keyId\n\t\t)\n\t\t\trelevant.push(row);\n\t}\n\treturn relevant;\n}\n\n/** Hash only validated semantic evidence, not conservative SQL discovery inputs.\n * Row positions follow the fixed source column lists; sorting uses code units,\n * never locale rules. Exact source key text remains part of relevant evidence.\n */\nexport async function capturedOwnershipEvidenceDigest(\n\trows: EvidenceRows,\n\tsubject: EvidenceSubject,\n\tcanonicalOwnerId: string,\n\thistory: ControllerHistorySnapshot,\n): Promise<string> {\n\tconst controllers = await actualSubjectRows(evidenceRows(rows, \"controllers\"), subject, {\n\t\tdevice: 4,\n\t\tpublicKey: 5,\n\t});\n\tconst invites = await actualSubjectRows(evidenceRows(rows, \"invites\"), subject, {\n\t\tdevice: 7,\n\t\tpublicKey: 8,\n\t});\n\tconst projection = [\n\t\t\"codemem:reviewed-device-ownership-evidence:v1\",\n\t\t[\"legacy-owner-resolution-schema\", 1, \"ready\"],\n\t\t[\n\t\t\tsubject.coordinatorId,\n\t\t\tsubject.groupId,\n\t\t\tsubject.deviceId,\n\t\t\tsubject.publicKey,\n\t\t\tsubject.fingerprint,\n\t\t\tsubject.keyId,\n\t\t],\n\t\tcanonicalOwnerId,\n\t\t[\n\t\t\t\"enrollment\",\n\t\t\t\"bindings\",\n\t\t\t\"claims\",\n\t\t\t\"resolutions\",\n\t\t\t\"revocations\",\n\t\t\t\"history\",\n\t\t\t\"historyKeys\",\n\t\t].map((name) => [name, canonicalRows(evidenceRows(rows, name))]),\n\t\t[\"controllers\", canonicalRows(controllers)],\n\t\t[\"invites\", canonicalRows(invites)],\n\t\t[\"subjectFingerprints\", [...history.fingerprints].sort()],\n\t];\n\tconst digest = await globalThis.crypto.subtle.digest(\n\t\t\"SHA-256\",\n\t\tnew TextEncoder().encode(JSON.stringify(projection)),\n\t);\n\treturn Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n","import {\n\ttype ControllerHistorySnapshot,\n\tcaptureControllerHistory,\n\tcaptureControllerHistorySnapshot,\n} from \"./coordinator-auth-controller-history.js\";\nimport type { AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport { guardsHold } from \"./coordinator-auth-read-set.js\";\nimport {\n\tclassifyEvidence,\n\ttype EvidenceRows,\n\ttype EvidenceSubject,\n\tevidenceRows,\n\thash,\n\tidentifier,\n\tkeyId,\n\ttype OwnershipDecision,\n} from \"./coordinator-device-ownership-evidence-classify.js\";\nimport { capturedOwnershipEvidenceDigest } from \"./coordinator-device-ownership-evidence-digest.js\";\nimport { CONTROLLER_COLUMNS } from \"./coordinator-device-ownership-evidence-queries.js\";\nimport {\n\tcaptureLegacyOwnerResolutionRecord,\n\tclassifyLegacyOwnerResolutionSchemaCatalog,\n\ttype ReviewedWeakLabel,\n\treadLegacyOwnerResolutionSchemaState,\n} from \"./coordinator-legacy-owner-resolution-metadata.js\";\nimport { readEvidence } from \"./coordinator-owner-negative-read-set.js\";\n\ninterface EvidenceBackend {\n\tfirst<T>(statement: AuthLinkStatement): Promise<T | null>;\n\tall<T>(statement: AuthLinkStatement): Promise<T[]>;\n\t/**\n\t * Runs reads together, so a capture and each recheck are one snapshot. Required: a\n\t * one-at-a-time fallback would check the guards at different moments.\n\t */\n\treadBatch<T>(statements: AuthLinkStatement[]): Promise<T[][]>;\n}\ninterface ActualSigner {\n\tgroupId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n}\ninterface CollectionInput {\n\tcanonicalOwnerId: string;\n\tactualSigner: ActualSigner;\n\tverifiedHistory: ControllerHistorySnapshot;\n}\ninterface RecheckSnapshot {\n\treadonly version: 1;\n}\ntype OwnershipCollection =\n\t| {\n\t\t\tkind: \"collected\";\n\t\t\tdecision: OwnershipDecision;\n\t\t\tweakLabels: ReviewedWeakLabel[];\n\t\t\trecheckSnapshot: RecheckSnapshot;\n\t }\n\t| { kind: \"unavailable\"; authorizationUnavailable: true };\ntype SourceVerification =\n\t| { kind: \"verified_controller_source\" | \"source_missing\" | \"source_revoked\" | \"source_mismatch\" }\n\t| { kind: \"unavailable\"; authorizationUnavailable: true };\nconst unavailable = { kind: \"unavailable\", authorizationUnavailable: true } as const;\n\nfunction captureFields(value: unknown, fields: string[]): Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error(\"invalid_input\");\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (prototype !== Object.prototype && prototype !== null) throw new Error(\"invalid_input\");\n\tif (Reflect.ownKeys(value).length !== fields.length) throw new Error(\"invalid_input\");\n\tconst copy: Record<string, unknown> = {};\n\tfor (const field of fields) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, field);\n\t\tif (!descriptor || !(\"value\" in descriptor)) throw new Error(\"invalid_input\");\n\t\tcopy[field] = descriptor.value;\n\t}\n\treturn copy;\n}\n\nasync function captureSigner(value: unknown, coordinatorId: string): Promise<EvidenceSubject> {\n\tconst signer = captureFields(value, [\"groupId\", \"deviceId\", \"publicKey\", \"fingerprint\"]);\n\tif (!identifier(signer.groupId) || !identifier(signer.deviceId) || !hash(signer.fingerprint))\n\t\tthrow new Error(\"invalid_signer\");\n\tconst canonicalKey = await keyId(signer.publicKey);\n\treturn {\n\t\tcoordinatorId,\n\t\tgroupId: signer.groupId,\n\t\tdeviceId: signer.deviceId,\n\t\tpublicKey: String(signer.publicKey),\n\t\tfingerprint: signer.fingerprint,\n\t\tkeyId: canonicalKey,\n\t};\n}\n\nfunction historyRows(history: ControllerHistorySnapshot): EvidenceRows {\n\treturn {\n\t\thistory: history.records.map((row) => [\n\t\t\trow.group_id,\n\t\t\trow.candidate_ref,\n\t\t\trow.manifest_version,\n\t\t\trow.completed_at,\n\t\t\trow.created_at,\n\t\t\trow.manifest_json,\n\t\t]),\n\t\thistoryKeys: history.keys.map((row) => [row.public_key, row.fingerprint]),\n\t\thistoryDiscovery: history.discoveryKeys.map((publicKey) => [publicKey]),\n\t};\n}\n\nfunction requireSameHistory(rows: EvidenceRows, history: ControllerHistorySnapshot): void {\n\tconst expected = historyRows(history);\n\tfor (const [name, values] of Object.entries(expected)) {\n\t\tif (\n\t\t\tJSON.stringify(values.map((row) => JSON.stringify(row)).sort()) !==\n\t\t\tJSON.stringify(\n\t\t\t\tevidenceRows(rows, name)\n\t\t\t\t\t.map((row) => JSON.stringify(row))\n\t\t\t\t\t.sort(),\n\t\t\t)\n\t\t)\n\t\t\tthrow new Error(\"changed_history\");\n\t}\n}\n\nfunction requireSupportedCapturedSchema(rows: EvidenceRows): void {\n\tconst objects = evidenceRows(rows, \"schema\").map((row) => {\n\t\tif (\n\t\t\trow.length !== 4 ||\n\t\t\ttypeof row[0] !== \"string\" ||\n\t\t\ttypeof row[1] !== \"string\" ||\n\t\t\trow[2] !== \"coordinator_legacy_owner_resolutions\" ||\n\t\t\ttypeof row[3] !== \"string\"\n\t\t)\n\t\t\tthrow new Error(\"invalid_schema_evidence\");\n\t\treturn { type: row[0], sql: row[3] };\n\t});\n\tif (classifyLegacyOwnerResolutionSchemaCatalog(objects) !== \"ready\")\n\t\tthrow new Error(\"unsupported_schema_evidence\");\n}\n\n/** Internal read-only metadata collector. No result of this class grants access. */\nexport class CoordinatorDeviceOwnershipEvidence {\n\tprivate readonly snapshots = new WeakMap<\n\t\tobject,\n\t\t{ guards: AuthLinkStatement[]; digest: string }\n\t>();\n\tprivate readonly coordinatorId: string;\n\tconstructor(\n\t\tprivate readonly backend: EvidenceBackend,\n\t\tconfig: { coordinatorId: string },\n\t) {\n\t\tthis.coordinatorId = config.coordinatorId;\n\t}\n\n\tasync collect(input: CollectionInput): Promise<OwnershipCollection> {\n\t\ttry {\n\t\t\tif (!identifier(this.coordinatorId)) return unavailable;\n\t\t\tconst captured = captureFields(input, [\n\t\t\t\t\"canonicalOwnerId\",\n\t\t\t\t\"actualSigner\",\n\t\t\t\t\"verifiedHistory\",\n\t\t\t]);\n\t\t\tif (!identifier(captured.canonicalOwnerId)) return unavailable;\n\t\t\tconst subject = await captureSigner(captured.actualSigner, this.coordinatorId);\n\t\t\tconst history = await this.verifyHistory(captured.verifiedHistory, subject);\n\t\t\tif ((await readLegacyOwnerResolutionSchemaState(this.backend)) !== \"ready\")\n\t\t\t\treturn unavailable;\n\t\t\tconst { rows, guards } = await readEvidence(this.backend, subject, history, {});\n\t\t\trequireSupportedCapturedSchema(rows);\n\t\t\trequireSameHistory(rows, history);\n\t\t\tconst classification = await classifyEvidence(\n\t\t\t\trows,\n\t\t\t\tsubject,\n\t\t\t\tcaptured.canonicalOwnerId,\n\t\t\t\thistory,\n\t\t\t);\n\t\t\t// The reads ran as two batches; every one must still hold at once.\n\t\t\tif (!(await guardsHold(this.backend, guards))) return unavailable;\n\t\t\tconst digest = await capturedOwnershipEvidenceDigest(\n\t\t\t\trows,\n\t\t\t\tsubject,\n\t\t\t\tcaptured.canonicalOwnerId,\n\t\t\t\thistory,\n\t\t\t);\n\t\t\tconst recheckSnapshot = Object.freeze({ version: 1 as const });\n\t\t\tthis.snapshots.set(recheckSnapshot, { guards, digest });\n\t\t\treturn { kind: \"collected\", ...classification, recheckSnapshot };\n\t\t} catch {\n\t\t\treturn unavailable;\n\t\t}\n\t}\n\n\tprivate async verifyHistory(\n\t\tvalue: unknown,\n\t\tsubject: EvidenceSubject,\n\t): Promise<ControllerHistorySnapshot> {\n\t\tconst captured = captureControllerHistorySnapshot(value);\n\t\tif (!captured) throw new Error(\"invalid_history\");\n\t\tconst live = await captureControllerHistory(\n\t\t\t{\n\t\t\t\tcoordinatorId: subject.coordinatorId,\n\t\t\t\tdeviceId: subject.deviceId,\n\t\t\t\tpublicKey: subject.publicKey,\n\t\t\t\tfingerprint: subject.fingerprint,\n\t\t\t},\n\t\t\t<T>(sql: string, values: string[]) => this.backend.all<T>({ sql, values }),\n\t\t);\n\t\tif (\n\t\t\tlive.coordinatorId !== captured.coordinatorId ||\n\t\t\tlive.deviceId !== captured.deviceId ||\n\t\t\tlive.publicKey !== captured.publicKey ||\n\t\t\tlive.fingerprint !== captured.fingerprint\n\t\t)\n\t\t\tthrow new Error(\"changed_history\");\n\t\trequireSameHistory(historyRows(live), captured);\n\t\treturn live;\n\t}\n\n\t/**\n\t * Guards that re-run every read of this capture, for a later checked batch: each aborts\n\t * it once its read changed. Never an admission or a write. Null for a snapshot this\n\t * reader did not capture, which therefore never matches.\n\t */\n\trecheckGuards(snapshot: RecheckSnapshot): AuthLinkStatement[] | null {\n\t\treturn this.snapshots.get(snapshot)?.guards ?? null;\n\t}\n\n\t/** Private confirmation metadata; only this reader's original capture is accepted. */\n\tasync reviewedEvidenceDigest(snapshot: unknown): Promise<string | null> {\n\t\tif (snapshot === null || typeof snapshot !== \"object\") return null;\n\t\treturn this.snapshots.get(snapshot)?.digest ?? null;\n\t}\n\n\tasync verifyControllerSource(input: {\n\t\tsourceRef: unknown;\n\t\texpectedOwnerId: string;\n\t\tactualSigner: ActualSigner;\n\t}): Promise<SourceVerification> {\n\t\ttry {\n\t\t\tconst captured = captureFields(input, [\"sourceRef\", \"expectedOwnerId\", \"actualSigner\"]);\n\t\t\tconst reference = await captureLegacyOwnerResolutionRecord(captured.sourceRef);\n\t\t\tif (!reference || !identifier(captured.expectedOwnerId)) return unavailable;\n\t\t\tconst subject = await captureSigner(captured.actualSigner, this.coordinatorId);\n\t\t\tif (\n\t\t\t\treference.coordinator_id !== this.coordinatorId ||\n\t\t\t\treference.owner_identity_id !== captured.expectedOwnerId ||\n\t\t\t\treference.device_id !== subject.deviceId ||\n\t\t\t\treference.key_id !== subject.keyId\n\t\t\t)\n\t\t\t\treturn { kind: \"source_mismatch\" };\n\t\t\tconst source = await this.backend.first<Record<string, string | number | null>>({\n\t\t\t\tsql: `SELECT ${CONTROLLER_COLUMNS.map((column) => (column === \"public_key\" ? \"CASE WHEN length(CAST(public_key AS BLOB)) <= 4096 THEN public_key ELSE NULL END AS public_key\" : column)).join(\",\")} FROM coordinator_auth_controller_attestations WHERE coordinator_id=? AND attestation_id=?`,\n\t\t\t\tvalues: [this.coordinatorId, reference.source_attestation_id],\n\t\t\t});\n\t\t\tif (!source) return { kind: \"source_missing\" };\n\t\t\tif (source.revoked_at !== null) return { kind: \"source_revoked\" };\n\t\t\tconst expected = [\n\t\t\t\treference.source_attestation_id,\n\t\t\t\treference.coordinator_id,\n\t\t\t\treference.owner_identity_id,\n\t\t\t\treference.source_group_id,\n\t\t\t\treference.device_id,\n\t\t\t\treference.source_public_key,\n\t\t\t\treference.source_fingerprint,\n\t\t\t\treference.source_review_receipt_id,\n\t\t\t\treference.source_evidence_digest,\n\t\t\t\treference.source_enrollment_identity_id,\n\t\t\t\treference.source_controller_revision,\n\t\t\t\treference.source_created_at,\n\t\t\t\tnull,\n\t\t\t];\n\t\t\tif (\n\t\t\t\t!CONTROLLER_COLUMNS.every((column, i) => source[column] === expected[i]) ||\n\t\t\t\t(await keyId(source.public_key)) !== subject.keyId\n\t\t\t)\n\t\t\t\treturn { kind: \"source_mismatch\" };\n\t\t\treturn { kind: \"verified_controller_source\" };\n\t\t} catch {\n\t\t\treturn unavailable;\n\t\t}\n\t}\n}\n","import {\n\tauthControllerAuthorityValues,\n\ttype CoordinatorAuthControllerAttestation,\n\ttype CoordinatorAuthControllerReviewInput,\n\tcaptureAuthControllerReview,\n\tisAuthControllerId,\n} from \"./coordinator-auth-controller.js\";\nimport {\n\ttype ControllerHistorySnapshot,\n\tcaptureControllerHistorySnapshot,\n} from \"./coordinator-auth-controller-history.js\";\nimport {\n\tcontrollerEligibleStatement,\n\tcontrollerInsertStatement,\n\treadControllerReview,\n} from \"./coordinator-auth-controller-read-set.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport type { CoordinatorDeviceOwnershipEvidence } from \"./coordinator-device-ownership-evidence.js\";\nimport { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport {\n\tcanonicalReviewedWeakLabels,\n\tcaptureLegacyOwnerResolutionRecord,\n\ttype LegacyOwnerResolutionRecord,\n} from \"./coordinator-legacy-owner-resolution-metadata.js\";\n\nexport interface InternalOwnerResolutionReview {\n\tcontrollerReview: CoordinatorAuthControllerReviewInput;\n\texistingController: CoordinatorAuthControllerAttestation | null;\n\texistingResolution: LegacyOwnerResolutionRecord | null;\n\tresolutionId: string;\n\townershipEvidenceDigest: string;\n\tconsent: {\n\t\tpurpose: \"existing_account_owner\";\n\t\tscope: \"historical_included_owner_labels_only\";\n\t\tevidenceDigest: string;\n\t\tconfirmedDigest: string;\n\t};\n}\n\nconst CONTROLLER_FIELDS = [\n\t\"attestation_id\",\n\t\"coordinator_id\",\n\t\"identity_id\",\n\t\"group_id\",\n\t\"device_id\",\n\t\"public_key\",\n\t\"fingerprint\",\n\t\"review_receipt_id\",\n\t\"evidence_digest\",\n\t\"enrollment_identity_id\",\n\t\"revision\",\n\t\"created_at\",\n\t\"revoked_at\",\n] as const;\nconst RESOLUTION_FIELDS = [\n\t\"coordinator_id\",\n\t\"resolution_id\",\n\t\"resolution_version\",\n\t\"device_id\",\n\t\"key_id\",\n\t\"owner_identity_id\",\n\t\"purpose\",\n\t\"scope\",\n\t\"source_attestation_id\",\n\t\"source_group_id\",\n\t\"source_controller_revision\",\n\t\"source_public_key\",\n\t\"source_fingerprint\",\n\t\"source_enrollment_identity_id\",\n\t\"source_created_at\",\n\t\"source_review_receipt_id\",\n\t\"source_evidence_digest\",\n\t\"resolution_evidence_digest\",\n\t\"reviewed_weak_labels_json\",\n\t\"created_at\",\n] as const;\nconst CONTROLLER_TABLE = \"coordinator_auth_controller_attestations\";\nconst RESOLUTION_TABLE = \"coordinator_legacy_owner_resolutions\";\nconst digest = (v: unknown): v is string => typeof v === \"string\" && /^[a-f0-9]{64}$/u.test(v);\n\nfunction exact(value: unknown, fields: readonly string[]): Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value))\n\t\tthrow new Error(\"invalid_review\");\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (prototype !== Object.prototype && prototype !== null) throw new Error(\"invalid_review\");\n\tif (Reflect.ownKeys(value).length !== fields.length) throw new Error(\"invalid_review\");\n\tconst copy: Record<string, unknown> = {};\n\tfor (const field of fields) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, field);\n\t\tif (!descriptor || !(\"value\" in descriptor)) throw new Error(\"invalid_review\");\n\t\tcopy[field] = descriptor.value;\n\t}\n\treturn copy;\n}\n\n/** Reject extensions and accessors at every level before existing shape parsers\n * run. Arrays are copied by descriptors too, never via caller iteration hooks.\n */\nfunction captureTree(value: unknown, depth = 0): unknown {\n\tif (depth > 12) throw new Error(\"invalid_review\");\n\tif (value === null || typeof value === \"string\" || typeof value === \"number\") return value;\n\tif (!value || typeof value !== \"object\") throw new Error(\"invalid_review\");\n\tif (Array.isArray(value)) {\n\t\tconst length = Object.getOwnPropertyDescriptor(value, \"length\")?.value;\n\t\tif (!Number.isSafeInteger(length) || length > 8192) throw new Error(\"invalid_review\");\n\t\tconst fields = Array.from({ length }, (_, i) => String(i));\n\t\tif (Reflect.ownKeys(value).length !== length + 1) throw new Error(\"invalid_review\");\n\t\treturn fields.map((field) => {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, field);\n\t\t\tif (!descriptor || !(\"value\" in descriptor)) throw new Error(\"invalid_review\");\n\t\t\treturn captureTree(descriptor.value, depth + 1);\n\t\t});\n\t}\n\tconst row = exact(\n\t\tvalue,\n\t\tReflect.ownKeys(value).map((key) => {\n\t\t\tif (typeof key !== \"string\") throw new Error(\"invalid_review\");\n\t\t\treturn key;\n\t\t}),\n\t);\n\treturn Object.fromEntries(Object.entries(row).map(([k, v]) => [k, captureTree(v, depth + 1)]));\n}\n\nfunction captureController(value: unknown): CoordinatorAuthControllerAttestation {\n\tconst row = exact(value, CONTROLLER_FIELDS);\n\tconst input = captureAuthControllerReview({\n\t\tattestationId: row.attestation_id,\n\t\tcoordinatorId: row.coordinator_id,\n\t\tidentityId: row.identity_id,\n\t\tgroupId: row.group_id,\n\t\tdeviceId: row.device_id,\n\t\tpublicKey: row.public_key,\n\t\tfingerprint: row.fingerprint,\n\t\treviewReceiptId: row.review_receipt_id,\n\t\tevidenceDigest: row.evidence_digest,\n\t});\n\tif (\n\t\t!input ||\n\t\trow.revision !== 1 ||\n\t\trow.revoked_at !== null ||\n\t\t(row.enrollment_identity_id !== null && !isAuthControllerId(row.enrollment_identity_id)) ||\n\t\t!timestamp(row.created_at)\n\t)\n\t\tthrow new Error(\"invalid_controller\");\n\treturn row as unknown as CoordinatorAuthControllerAttestation;\n}\n\nfunction timestamp(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tNumber.isFinite(Date.parse(value)) &&\n\t\tnew Date(value).toISOString() === value\n\t);\n}\n\nfunction captureReviewController(value: unknown): CoordinatorAuthControllerReviewInput {\n\tconst row = exact(value, [\n\t\t\"attestationId\",\n\t\t\"coordinatorId\",\n\t\t\"identityId\",\n\t\t\"groupId\",\n\t\t\"deviceId\",\n\t\t\"publicKey\",\n\t\t\"fingerprint\",\n\t\t\"reviewReceiptId\",\n\t\t\"evidenceDigest\",\n\t\t\"verifiedSnapshot\",\n\t]);\n\trow.verifiedSnapshot = captureReviewSnapshotFields(row.verifiedSnapshot, row.groupId);\n\tconst captured = captureAuthControllerReview(row);\n\tif (!captured?.verifiedSnapshot?.legacyHistory || !captured.verifiedSnapshot.accountOwnerTarget)\n\t\tthrow new Error(\"invalid_review\");\n\treturn captured;\n}\n\nfunction captureReviewSnapshotFields(value: unknown, groupId: unknown): Record<string, unknown> {\n\tconst snapshot = exact(value, [\n\t\t\"enrollmentIdentityId\",\n\t\t\"invites\",\n\t\t\"legacyHistory\",\n\t\t\"accountOwnerTarget\",\n\t]);\n\tsnapshot.legacyHistory = captureReviewHistory(snapshot.legacyHistory, groupId);\n\tif (!Array.isArray(snapshot.invites)) throw new Error(\"invalid_review\");\n\tfor (const invite of snapshot.invites)\n\t\texact(invite, [\n\t\t\t\"inviteId\",\n\t\t\t\"kind\",\n\t\t\t\"actorId\",\n\t\t\t\"assignedIdentityId\",\n\t\t\t\"targetIdentityId\",\n\t\t\t\"digest\",\n\t\t]);\n\treturn snapshot;\n}\n\nfunction captureReviewHistory(value: unknown, groupId: unknown): ControllerHistorySnapshot {\n\tconst fields = [\n\t\t\"coordinatorId\",\n\t\t\"deviceId\",\n\t\t\"publicKey\",\n\t\t\"fingerprint\",\n\t\t\"keys\",\n\t\t\"discoveryKeys\",\n\t\t\"discoveryFragments\",\n\t\t\"fingerprints\",\n\t\t\"records\",\n\t];\n\tif (value && typeof value === \"object\" && Object.hasOwn(value, \"groupId\")) fields.push(\"groupId\");\n\tconst history = exact(value, fields);\n\tif (Object.hasOwn(history, \"groupId\") && history.groupId !== groupId)\n\t\tthrow new Error(\"invalid_review\");\n\tif (!Array.isArray(history.keys) || !Array.isArray(history.records))\n\t\tthrow new Error(\"invalid_review\");\n\tfor (const key of history.keys) exact(key, [\"public_key\", \"fingerprint\"]);\n\tfor (const record of history.records)\n\t\texact(record, [\n\t\t\t\"group_id\",\n\t\t\t\"candidate_ref\",\n\t\t\t\"manifest_version\",\n\t\t\t\"completed_at\",\n\t\t\t\"created_at\",\n\t\t\t\"manifest_json\",\n\t\t]);\n\tconst captured = captureControllerHistorySnapshot(history);\n\tif (!captured) throw new Error(\"invalid_review\");\n\treturn {\n\t\tcoordinatorId: captured.coordinatorId,\n\t\tdeviceId: captured.deviceId,\n\t\tpublicKey: captured.publicKey,\n\t\tfingerprint: captured.fingerprint,\n\t\tkeys: captured.keys,\n\t\tdiscoveryKeys: captured.discoveryKeys,\n\t\tdiscoveryFragments: captured.discoveryFragments,\n\t\tfingerprints: captured.fingerprints,\n\t\trecords: captured.records,\n\t};\n}\n\n/** Trusted operator-builder input only; this is not a public proof protocol. */\nexport function captureInternalOwnerResolutionReview(\n\tvalue: unknown,\n): InternalOwnerResolutionReview | null {\n\ttry {\n\t\tconst row = exact(captureTree(value), [\n\t\t\t\"controllerReview\",\n\t\t\t\"existingController\",\n\t\t\t\"existingResolution\",\n\t\t\t\"resolutionId\",\n\t\t\t\"ownershipEvidenceDigest\",\n\t\t\t\"consent\",\n\t\t]);\n\t\tconst consent = exact(row.consent, [\"purpose\", \"scope\", \"evidenceDigest\", \"confirmedDigest\"]);\n\t\tif (\n\t\t\tconsent.purpose !== \"existing_account_owner\" ||\n\t\t\tconsent.scope !== \"historical_included_owner_labels_only\" ||\n\t\t\t!digest(consent.evidenceDigest) ||\n\t\t\tconsent.confirmedDigest !== consent.evidenceDigest ||\n\t\t\t!isAuthControllerId(row.resolutionId) ||\n\t\t\t!digest(row.ownershipEvidenceDigest)\n\t\t)\n\t\t\treturn null;\n\t\tconst controllerReview = captureReviewController(row.controllerReview);\n\t\tconst existingController =\n\t\t\trow.existingController === null ? null : captureController(row.existingController);\n\t\t// Canonical key and metadata checks run asynchronously in the writer.\n\t\tconst existingResolution =\n\t\t\trow.existingResolution === null\n\t\t\t\t? null\n\t\t\t\t: (exact(\n\t\t\t\t\t\trow.existingResolution,\n\t\t\t\t\t\tRESOLUTION_FIELDS,\n\t\t\t\t\t) as unknown as LegacyOwnerResolutionRecord);\n\t\treturn {\n\t\t\tcontrollerReview,\n\t\t\texistingController,\n\t\t\texistingResolution,\n\t\t\tresolutionId: row.resolutionId,\n\t\t\townershipEvidenceDigest: row.ownershipEvidenceDigest,\n\t\t\tconsent: {\n\t\t\t\tpurpose: consent.purpose,\n\t\t\t\tscope: consent.scope,\n\t\t\t\tevidenceDigest: consent.evidenceDigest,\n\t\t\t\tconfirmedDigest: consent.confirmedDigest,\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction resolutionRecord(\n\treview: InternalOwnerResolutionReview,\n\tsource: CoordinatorAuthControllerAttestation,\n\tkeyId: string,\n\tlabels: string,\n\tnow: string,\n): LegacyOwnerResolutionRecord {\n\treturn {\n\t\tcoordinator_id: source.coordinator_id,\n\t\tresolution_id: review.resolutionId,\n\t\tresolution_version: 1,\n\t\tdevice_id: source.device_id,\n\t\tkey_id: keyId,\n\t\towner_identity_id: source.identity_id,\n\t\tpurpose: \"existing_account_owner\",\n\t\tscope: \"historical_included_owner_labels_only\",\n\t\tsource_attestation_id: source.attestation_id,\n\t\tsource_group_id: source.group_id,\n\t\tsource_controller_revision: source.revision,\n\t\tsource_public_key: source.public_key,\n\t\tsource_fingerprint: source.fingerprint,\n\t\tsource_enrollment_identity_id: source.enrollment_identity_id,\n\t\tsource_created_at: source.created_at,\n\t\tsource_review_receipt_id: source.review_receipt_id,\n\t\tsource_evidence_digest: source.evidence_digest,\n\t\tresolution_evidence_digest: review.consent.evidenceDigest,\n\t\treviewed_weak_labels_json: labels,\n\t\tcreated_at: now,\n\t};\n}\n\nconst CONTROLLER_ASSERT = `INSERT INTO coordinator_auth_controller_attestations\n\t(attestation_id,coordinator_id,identity_id,group_id,device_id,public_key,fingerprint,\n\treview_receipt_id,evidence_digest,revision,created_at)\n\tSELECT '', '', '', '', '', '', '', '', '', 0, ''`;\nconst RESOLUTION_ASSERT = `INSERT INTO coordinator_legacy_owner_resolutions\n\t(${RESOLUTION_FIELDS.join(\",\")}) SELECT '', '', 0, '', '', '', '', '', '', '', 0, '', '', NULL, '', '', '', '', '[]', ''`;\n\n/** A failing predicate performs an invalid INSERT, forcing rollback. Success\n * writes nothing. No reliance on discarded SELECT expressions or JS counts.\n */\nfunction assertRead(\n\tstatement: AuthLinkStatement,\n\tcolumn: \"matches\" | \"eligible\",\n): AuthLinkStatement[] {\n\tconst predicate = `NOT COALESCE((SELECT ${column} FROM (${statement.sql})),0)`;\n\treturn [CONTROLLER_ASSERT, RESOLUTION_ASSERT].map((prefix) => ({\n\t\tsql: `${prefix} WHERE ${predicate}`,\n\t\tvalues: statement.values,\n\t}));\n}\n\n/**\n * Asserts the enrollment is still eligible under the reviewed weak label. The snapshot and\n * owner reads behind it are pinned by their own guards, which lead the batch.\n */\nfunction assertEligibility(\n\tinput: CoordinatorAuthControllerReviewInput,\n\tauthority: (string | null)[],\n): AuthLinkStatement[] {\n\tconst eligible = controllerEligibleStatement(input, authority, { reviewedLabel: true });\n\treturn assertRead(\n\t\t{ sql: `SELECT EXISTS (${eligible.sql}) AS eligible`, values: eligible.values },\n\t\t\"eligible\",\n\t);\n}\n\nfunction rowPin(\n\ttable: typeof CONTROLLER_TABLE | typeof RESOLUTION_TABLE,\n\trow: CoordinatorAuthControllerAttestation | LegacyOwnerResolutionRecord,\n\tpresent: boolean,\n): AuthLinkStatement {\n\tconst fields = table === CONTROLLER_TABLE ? CONTROLLER_FIELDS : RESOLUTION_FIELDS;\n\tconst id = table === CONTROLLER_TABLE ? \"attestation_id\" : \"resolution_id\";\n\tlet receiptId: string;\n\tif (table === CONTROLLER_TABLE) {\n\t\tif (!(\"attestation_id\" in row)) throw new Error(\"invalid_controller_pin\");\n\t\treceiptId = row.attestation_id;\n\t} else {\n\t\tif (!(\"resolution_id\" in row)) throw new Error(\"invalid_resolution_pin\");\n\t\treceiptId = row.resolution_id;\n\t}\n\tif (!present)\n\t\treturn {\n\t\t\tsql: `SELECT NOT EXISTS (SELECT 1 FROM ${table} WHERE coordinator_id=? AND ${id}=?) AS matches`,\n\t\t\tvalues: [row.coordinator_id, receiptId],\n\t\t};\n\treturn {\n\t\tsql: `WITH pin(value) AS (SELECT ?) SELECT EXISTS (SELECT 1 FROM ${table} r CROSS JOIN pin p WHERE ${fields.map((field) => `r.${field} IS json_extract(p.value,'$.${field}')`).join(\" AND \")}) AS matches`,\n\t\tvalues: [JSON.stringify(row)],\n\t};\n}\n\nasync function requireReviewedEvidence(\n\tevidence: CoordinatorDeviceOwnershipEvidence,\n\tsnapshot: Parameters<CoordinatorDeviceOwnershipEvidence[\"recheckGuards\"]>[0],\n\treview: InternalOwnerResolutionReview,\n): Promise<void> {\n\tconst freshDigest = await evidence.reviewedEvidenceDigest(snapshot);\n\tif (freshDigest === null || freshDigest !== review.ownershipEvidenceDigest)\n\t\tthrow new Error(\"ownership_evidence_changed\");\n}\n\nasync function prepareCommit(\n\tbackend: AuthLinkBackend,\n\tevidence: CoordinatorDeviceOwnershipEvidence,\n\treview: InternalOwnerResolutionReview,\n\tnow: string,\n) {\n\tconst input = review.controllerReview;\n\tconst snapshot = input.verifiedSnapshot;\n\tif (!timestamp(now) || !snapshot?.legacyHistory) throw new Error(\"invalid_review\");\n\tconst signer = {\n\t\tgroupId: input.groupId,\n\t\tdeviceId: input.deviceId,\n\t\tpublicKey: input.publicKey,\n\t\tfingerprint: input.fingerprint,\n\t};\n\tconst keyId = await ed25519KeyIdForRevocation(input.publicKey);\n\tif (!keyId) throw new Error(\"invalid_key\");\n\tconst collected = await evidence.collect({\n\t\tcanonicalOwnerId: input.identityId,\n\t\tactualSigner: signer,\n\t\tverifiedHistory: snapshot.legacyHistory,\n\t});\n\tif (\n\t\tcollected.kind !== \"collected\" ||\n\t\t![\"compatible\", \"weak_label_review_required\"].includes(collected.decision)\n\t)\n\t\tthrow new Error(\"ownership_unavailable\");\n\tawait requireReviewedEvidence(evidence, collected.recheckSnapshot, review);\n\tconst labels = canonicalReviewedWeakLabels(collected.weakLabels);\n\tif (labels === null) throw new Error(\"invalid_labels\");\n\tconst controller = reviewedController(review, snapshot.enrollmentIdentityId, now);\n\tconst proposed = resolutionRecord(review, controller, keyId, labels, now);\n\tif (review.existingController) {\n\t\tconst verified = await evidence.verifyControllerSource({\n\t\t\tsourceRef: proposed,\n\t\t\texpectedOwnerId: input.identityId,\n\t\t\tactualSigner: signer,\n\t\t});\n\t\tif (verified.kind !== \"verified_controller_source\") throw new Error(\"source_mismatch\");\n\t}\n\tconst resolution = await reviewedResolution(review, proposed);\n\tconst authority = authControllerAuthorityValues(\n\t\t{\n\t\t\tgroup_id: input.groupId,\n\t\t\tdevice_id: input.deviceId,\n\t\t\tpublic_key: input.publicKey,\n\t\t\tfingerprint: input.fingerprint,\n\t\t\tidentity_id: snapshot.enrollmentIdentityId,\n\t\t},\n\t\tkeyId,\n\t);\n\t// The evidence guards lead the batch: they re-run every read the review was built on.\n\t// The reviewed snapshot's and owner target's guards follow them.\n\tconst evidenceGuards = evidence.recheckGuards(collected.recheckSnapshot);\n\tif (!evidenceGuards) throw new Error(\"ownership_evidence_changed\");\n\tconst reviewed = await readControllerReview(backend, input, authority);\n\tif (!reviewed.allowed) throw new Error(\"review_changed\");\n\tconst statements = await prepareAssertions(backend, review, controller, resolution, authority);\n\tstatements.unshift(...evidenceGuards, ...reviewed.guards);\n\tappendReceiptWrites(statements, review, resolution, now, authority);\n\treturn { controller, resolution, statements };\n}\n\nfunction reviewedController(\n\treview: InternalOwnerResolutionReview,\n\tenrollmentIdentityId: string | null,\n\tnow: string,\n): CoordinatorAuthControllerAttestation {\n\tconst input = review.controllerReview;\n\treturn (\n\t\treview.existingController ?? {\n\t\t\tattestation_id: input.attestationId,\n\t\t\tcoordinator_id: input.coordinatorId,\n\t\t\tidentity_id: input.identityId,\n\t\t\tgroup_id: input.groupId,\n\t\t\tdevice_id: input.deviceId,\n\t\t\tpublic_key: input.publicKey,\n\t\t\tfingerprint: input.fingerprint,\n\t\t\treview_receipt_id: input.reviewReceiptId,\n\t\t\tevidence_digest: input.evidenceDigest,\n\t\t\tenrollment_identity_id: enrollmentIdentityId,\n\t\t\trevision: 1 as const,\n\t\t\tcreated_at: now,\n\t\t\trevoked_at: null,\n\t\t}\n\t);\n}\n\nasync function reviewedResolution(\n\treview: InternalOwnerResolutionReview,\n\tproposed: LegacyOwnerResolutionRecord,\n): Promise<LegacyOwnerResolutionRecord> {\n\tif (!review.existingResolution) return proposed;\n\tconst old = await captureLegacyOwnerResolutionRecord(review.existingResolution);\n\tif (\n\t\t!review.existingController ||\n\t\t!old ||\n\t\told.resolution_id !== review.resolutionId ||\n\t\t!RESOLUTION_FIELDS.filter(\n\t\t\t(field) =>\n\t\t\t\t![\"resolution_evidence_digest\", \"reviewed_weak_labels_json\", \"created_at\"].includes(field),\n\t\t).every((field) => old[field] === proposed[field])\n\t)\n\t\tthrow new Error(\"resolution_mismatch\");\n\treturn old;\n}\n\nasync function prepareAssertions(\n\tbackend: AuthLinkBackend,\n\treview: InternalOwnerResolutionReview,\n\tcontroller: CoordinatorAuthControllerAttestation,\n\tresolution: LegacyOwnerResolutionRecord,\n\tauthority: (string | null)[],\n): Promise<AuthLinkStatement[]> {\n\tconst input = review.controllerReview;\n\tconst catalog = await backend.first<{ objects: string }>({\n\t\tsql: \"SELECT json_group_array(json_object('type',type,'name',name,'sql',sql)) AS objects FROM sqlite_master WHERE tbl_name='coordinator_legacy_owner_resolutions'\",\n\t\tvalues: [],\n\t});\n\tif (!catalog) throw new Error(\"schema_unavailable\");\n\treturn [\n\t\t...assertEligibility(input, authority),\n\t\t...assertRead(\n\t\t\t{\n\t\t\t\tsql: \"SELECT (SELECT json_group_array(json_object('type',type,'name',name,'sql',sql)) FROM sqlite_master WHERE tbl_name='coordinator_legacy_owner_resolutions') IS ? AS matches\",\n\t\t\t\tvalues: [catalog.objects],\n\t\t\t},\n\t\t\t\"matches\",\n\t\t),\n\t\t...assertRead(\n\t\t\trowPin(CONTROLLER_TABLE, controller, review.existingController !== null),\n\t\t\t\"matches\",\n\t\t),\n\t\t...assertRead(\n\t\t\trowPin(RESOLUTION_TABLE, resolution, review.existingResolution !== null),\n\t\t\t\"matches\",\n\t\t),\n\t];\n}\n\nfunction appendReceiptWrites(\n\tstatements: AuthLinkStatement[],\n\treview: InternalOwnerResolutionReview,\n\tresolution: LegacyOwnerResolutionRecord,\n\tnow: string,\n\tauthority: (string | null)[],\n): void {\n\tconst input = review.controllerReview;\n\tif (!review.existingController) {\n\t\tstatements.push(controllerInsertStatement(input, now, authority, { reviewedLabel: true }));\n\t\tstatements.push({ sql: `${RESOLUTION_ASSERT} WHERE changes() <> 1`, values: [] });\n\t}\n\tif (!review.existingResolution) {\n\t\tstatements.push({\n\t\t\tsql: `INSERT INTO ${RESOLUTION_TABLE} (${RESOLUTION_FIELDS.join(\",\")}) SELECT ${RESOLUTION_FIELDS.map((field) => `json_extract(value,'$.${field}')`).join(\",\")} FROM (SELECT ? AS value)`,\n\t\t\tvalues: [JSON.stringify(resolution)],\n\t\t});\n\t\tstatements.push({ sql: `${CONTROLLER_ASSERT} WHERE changes() <> 1`, values: [] });\n\t}\n}\n\n/** Exactly one checked backend batch. A postcommit read failure is a persistence\n * error, never a claim that the successful transaction changed nothing.\n */\nexport async function commitReviewedOwnerResolution(options: {\n\tbackend: AuthLinkBackend;\n\tevidence: CoordinatorDeviceOwnershipEvidence;\n\treview: unknown;\n\tnow: string;\n}) {\n\ttry {\n\t\tconst review = captureInternalOwnerResolutionReview(options.review);\n\t\tif (!review) throw new Error(\"invalid_review\");\n\t\tconst prepared = await prepareCommit(options.backend, options.evidence, review, options.now);\n\t\tawait options.backend.batch(prepared.statements);\n\t\tconst controller = await options.backend.first<CoordinatorAuthControllerAttestation>({\n\t\t\tsql: `SELECT * FROM ${CONTROLLER_TABLE} WHERE coordinator_id=? AND attestation_id=?`,\n\t\t\tvalues: [prepared.controller.coordinator_id, prepared.controller.attestation_id],\n\t\t});\n\t\tconst resolution = await options.backend.first<LegacyOwnerResolutionRecord>({\n\t\t\tsql: `SELECT * FROM ${RESOLUTION_TABLE} WHERE coordinator_id=? AND resolution_id=?`,\n\t\t\tvalues: [prepared.resolution.coordinator_id, prepared.resolution.resolution_id],\n\t\t});\n\t\tif (\n\t\t\t!controller ||\n\t\t\t!resolution ||\n\t\t\t!CONTROLLER_FIELDS.every((field) => controller[field] === prepared.controller[field]) ||\n\t\t\t!RESOLUTION_FIELDS.every((field) => resolution[field] === prepared.resolution[field])\n\t\t)\n\t\t\tthrow new Error(\"receipt_read_failed\");\n\t\treturn {\n\t\t\tcontroller,\n\t\t\tcontrollerDisposition: review.existingController ? (\"reused\" as const) : (\"created\" as const),\n\t\t\tresolution,\n\t\t\tresolutionDisposition: review.existingResolution ? (\"reused\" as const) : (\"created\" as const),\n\t\t};\n\t} catch {\n\t\tthrow new Error(\"Owner resolution outcome is unavailable; check its status before retrying\");\n\t}\n}\n","import { readConnectionSchemaState } from \"./coordinator-account-connection-schema.js\";\nimport { CONNECTION_NOT_REVOKED_SQL } from \"./coordinator-account-connection-storage.js\";\nimport type {\n\tCoordinatorAuthControllerAttestation,\n\tCoordinatorAuthControllerVerifiedSnapshot,\n} from \"./coordinator-auth-controller.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { ControllerHistorySnapshot } from \"./coordinator-auth-controller-history.js\";\nimport type {\n\tCoordinatorAuthLinkConfig,\n\tCoordinatorAuthLinkSigner,\n} from \"./coordinator-auth-link-contract.js\";\nimport { isHash } from \"./coordinator-auth-link-input.js\";\nimport { authAccountLinkProvenanceSql } from \"./coordinator-auth-link-provenance.js\";\nimport type { CoordinatorDeviceOwnershipEvidence } from \"./coordinator-device-ownership-evidence.js\";\nimport {\n\tCONTROLLER_COLUMNS,\n\tRESOLUTION_COLUMNS,\n} from \"./coordinator-device-ownership-evidence-queries.js\";\nimport { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport {\n\tcaptureLegacyOwnerResolutionRecord,\n\ttype LegacyOwnerResolutionRecord,\n\treadLegacyOwnerResolutionSchemaState,\n} from \"./coordinator-legacy-owner-resolution-metadata.js\";\nimport type {\n\tOwnerResolutionReviewBackend,\n\tOwnerResolutionReviewSelection,\n} from \"./coordinator-owner-resolution-review.js\";\n\nexport interface ResolutionTarget {\n\tlink_id: string;\n\tauth_config_revision: string;\n\tcreated_at_ms: number;\n}\n\nexport class ReviewUnavailable extends Error {}\n\nexport async function requireReviewSchema(backend: OwnerResolutionReviewBackend) {\n\tif (\n\t\t(await readLegacyOwnerResolutionSchemaState(backend)) !== \"ready\" ||\n\t\t(await readConnectionSchemaState(backend)) !== \"ready\"\n\t)\n\t\tthrow new ReviewUnavailable(\n\t\t\t\"upgrade_required: ask the operator to upgrade the coordinator ownership schema\",\n\t\t);\n}\n\n/** Account provenance belongs to A; the requester is collected separately, never impersonated. */\nexport async function readResolutionTarget(\n\tbackend: OwnerResolutionReviewBackend,\n\tselection: OwnerResolutionReviewSelection,\n\tconfig: CoordinatorAuthLinkConfig,\n): Promise<ResolutionTarget> {\n\tconst rows = await backend.all<ResolutionTarget>({\n\t\tsql: `SELECT l.link_id,l.auth_config_revision,l.created_at_ms FROM coordinator_auth_account_links l\n\t\t WHERE l.coordinator_id=? AND l.identity_id=? AND l.issuer=?\n\t\t AND ${CONNECTION_NOT_REVOKED_SQL}\n\t\t AND ${authAccountLinkProvenanceSql(\"l\", { connections: true })} LIMIT 2`,\n\t\tvalues: [config.coordinatorId, selection.identityId, config.issuer],\n\t});\n\tconst row = rows[0];\n\tif (\n\t\trows.length !== 1 ||\n\t\t!row ||\n\t\t!isAuthControllerId(row.link_id) ||\n\t\t!isHash(row.auth_config_revision) ||\n\t\t!Number.isSafeInteger(row.created_at_ms) ||\n\t\trow.created_at_ms < 0\n\t)\n\t\tthrow new ReviewUnavailable(\n\t\t\t\"account_owner_target_unavailable: verify the selected account connection\",\n\t\t);\n\treturn row;\n}\n\nexport async function readResolutionRequester(\n\tbackend: OwnerResolutionReviewBackend,\n\tselection: OwnerResolutionReviewSelection,\n) {\n\tconst row = await backend.first<{\n\t\tpublic_key: string;\n\t\tfingerprint: string;\n\t\tidentity_id: string | null;\n\t}>({\n\t\tsql: `SELECT CASE WHEN length(CAST(e.public_key AS BLOB))<=4096 THEN e.public_key ELSE NULL END AS public_key,\n\t\t e.fingerprint,e.identity_id FROM enrolled_devices e JOIN groups g ON g.group_id=e.group_id\n\t\t WHERE e.group_id=? AND e.device_id=? AND e.enabled=1 AND g.archived_at IS NULL`,\n\t\tvalues: [selection.groupId, selection.deviceId],\n\t});\n\tif (\n\t\t!row ||\n\t\trow.fingerprint !== selection.fingerprint ||\n\t\t!(await ed25519KeyIdForRevocation(row.public_key))\n\t)\n\t\tthrow new ReviewUnavailable(\n\t\t\t\"requester_unavailable: verify the current group, enrollment and key\",\n\t\t);\n\treturn {\n\t\tsigner: {\n\t\t\tgroupId: selection.groupId,\n\t\t\tdeviceId: selection.deviceId,\n\t\t\tpublicKey: row.public_key,\n\t\t\tfingerprint: row.fingerprint,\n\t\t},\n\t\tenrollmentIdentityId: row.identity_id,\n\t};\n}\n\nexport async function readResolutionInvites(\n\tbackend: OwnerResolutionReviewBackend,\n\tsigner: CoordinatorAuthLinkSigner,\n) {\n\tconst invites = await backend.all<CoordinatorAuthControllerVerifiedSnapshot[\"invites\"][number]>({\n\t\tsql: `SELECT invite_id AS inviteId,invite_kind AS kind,recipient_actor_id AS actorId,\n\t\t assigned_identity_id AS assignedIdentityId,target_identity_id AS targetIdentityId,reviewed_preview_digest AS digest\n\t\t FROM coordinator_invites WHERE group_id=? AND bound_device_id=? AND bound_public_key=? AND bound_fingerprint=?\n\t\t AND revoked_at IS NULL AND consumed_at IS NOT NULL AND consumed_at!=''\n\t\t AND invite_kind IN ('team_member','add_device') ORDER BY invite_id LIMIT 501`,\n\t\tvalues: [signer.groupId, signer.deviceId, signer.publicKey, signer.fingerprint],\n\t});\n\tif (invites.length > 500)\n\t\tthrow new ReviewUnavailable(\n\t\t\t\"evidence_too_large: ask the operator to inspect consumed invitations\",\n\t\t);\n\treturn invites;\n}\n\nfunction controllerFromResolution(\n\trow: LegacyOwnerResolutionRecord,\n): CoordinatorAuthControllerAttestation {\n\treturn {\n\t\tattestation_id: row.source_attestation_id,\n\t\tcoordinator_id: row.coordinator_id,\n\t\tidentity_id: row.owner_identity_id,\n\t\tgroup_id: row.source_group_id,\n\t\tdevice_id: row.device_id,\n\t\tpublic_key: row.source_public_key,\n\t\tfingerprint: row.source_fingerprint,\n\t\treview_receipt_id: row.source_review_receipt_id,\n\t\tevidence_digest: row.source_evidence_digest,\n\t\tenrollment_identity_id: row.source_enrollment_identity_id,\n\t\trevision: row.source_controller_revision,\n\t\tcreated_at: row.source_created_at,\n\t\trevoked_at: null,\n\t};\n}\n\nasync function readExistingResolutions(\n\tbackend: OwnerResolutionReviewBackend,\n\tconfig: CoordinatorAuthLinkConfig,\n\tsigner: CoordinatorAuthLinkSigner,\n) {\n\tconst keyId = await ed25519KeyIdForRevocation(signer.publicKey);\n\tconst rows = await backend.all<unknown>({\n\t\tsql: `SELECT ${RESOLUTION_COLUMNS.join(\",\")} FROM coordinator_legacy_owner_resolutions\n\t\t WHERE coordinator_id=? AND (device_id=? OR key_id=?)\n\t\t ORDER BY created_at,resolution_id LIMIT 501`,\n\t\tvalues: [config.coordinatorId, signer.deviceId, keyId],\n\t});\n\tif (rows.length > 500 || new TextEncoder().encode(JSON.stringify(rows)).byteLength > 750_000)\n\t\tthrow new ReviewUnavailable(\"evidence_too_large: inspect retained resolution receipts\");\n\tconst exact: LegacyOwnerResolutionRecord[] = [];\n\tfor (const value of rows) {\n\t\tconst row = await captureLegacyOwnerResolutionRecord(value);\n\t\tif (!row)\n\t\t\tthrow new ReviewUnavailable(\"source_unavailable: inspect retained resolution metadata\");\n\t\tif (row.device_id === signer.deviceId && row.key_id === keyId) exact.push(row);\n\t}\n\tif (rows.length && !exact.length)\n\t\tthrow new ReviewUnavailable(\n\t\t\t\"source_unavailable: ask the operator to inspect the retained resolution subject\",\n\t\t);\n\treturn exact;\n}\n\nasync function verifiedResolutionSource(\n\trows: LegacyOwnerResolutionRecord[],\n\tselection: OwnerResolutionReviewSelection,\n\tsigner: CoordinatorAuthLinkSigner,\n\tevidence: CoordinatorDeviceOwnershipEvidence,\n) {\n\tfor (const resolution of rows) {\n\t\tconst verified = await evidence.verifyControllerSource({\n\t\t\tsourceRef: resolution,\n\t\t\texpectedOwnerId: selection.identityId,\n\t\t\tactualSigner: signer,\n\t\t});\n\t\tif (verified.kind === \"verified_controller_source\")\n\t\t\treturn { controller: controllerFromResolution(resolution), resolution };\n\t}\n\tthrow new ReviewUnavailable(\n\t\t\"source_unavailable: inspect the original controllers and immutable resolution receipts\",\n\t);\n}\n\nasync function readRetainedControllers(\n\tbackend: OwnerResolutionReviewBackend,\n\tconfig: CoordinatorAuthLinkConfig,\n\tsigner: CoordinatorAuthLinkSigner,\n\thistory: ControllerHistorySnapshot,\n) {\n\tconst rows = await backend.all<CoordinatorAuthControllerAttestation>({\n\t\tsql: `SELECT ${CONTROLLER_COLUMNS.join(\",\")} FROM coordinator_auth_controller_attestations\n\t\t WHERE coordinator_id=? AND device_id=? AND (public_key IN (SELECT value FROM json_each(?))\n\t\t OR (group_id=? AND fingerprint=?)) ORDER BY group_id,attestation_id LIMIT 501`,\n\t\tvalues: [\n\t\t\tconfig.coordinatorId,\n\t\t\tsigner.deviceId,\n\t\t\tJSON.stringify(history.keys.map((key) => key.public_key)),\n\t\t\tsigner.groupId,\n\t\t\tsigner.fingerprint,\n\t\t],\n\t});\n\tif (rows.length > 500 || new TextEncoder().encode(JSON.stringify(rows)).byteLength > 750_000)\n\t\tthrow new ReviewUnavailable(\n\t\t\t\"evidence_too_large: ask the operator to inspect retained controllers\",\n\t\t);\n\treturn rows;\n}\n\nexport async function readResolutionSource(options: {\n\tbackend: OwnerResolutionReviewBackend;\n\tconfig: CoordinatorAuthLinkConfig;\n\tselection: OwnerResolutionReviewSelection;\n\tsigner: CoordinatorAuthLinkSigner;\n\thistory: ControllerHistorySnapshot;\n\tevidence: CoordinatorDeviceOwnershipEvidence;\n}) {\n\tconst { backend, config, selection, signer, history, evidence } = options;\n\tconst controllers = await readRetainedControllers(backend, config, signer, history);\n\tconst current = controllers.filter(\n\t\t(row) => row.group_id === signer.groupId && row.fingerprint === signer.fingerprint,\n\t);\n\tif (\n\t\tcurrent.some(\n\t\t\t(row) =>\n\t\t\t\trow.revoked_at !== null ||\n\t\t\t\trow.identity_id !== selection.identityId ||\n\t\t\t\trow.public_key !== signer.publicKey,\n\t\t)\n\t)\n\t\tthrow new ReviewUnavailable(\n\t\t\t\"controller_unavailable: inspect the current controller tombstone or owner conflict\",\n\t\t);\n\tconst resolutions = await readExistingResolutions(backend, config, signer);\n\tif (resolutions.length) return verifiedResolutionSource(resolutions, selection, signer, evidence);\n\tconst controller =\n\t\tcontrollers.find(\n\t\t\t(row) => row.revoked_at === null && row.identity_id === selection.identityId,\n\t\t) ?? null;\n\treturn { controller, resolution: null };\n}\n","import type { CoordinatorAuthControllerAttestation } from \"./coordinator-auth-controller.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { ControllerHistorySnapshot } from \"./coordinator-auth-controller-history.js\";\nimport {\n\ttype ControllerHistoryEvidence,\n\tcaptureControllerHistory,\n\tcontrollerHistoryDigestEvidence,\n\tparseControllerHistoryRecord,\n} from \"./coordinator-auth-controller-history.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport type {\n\tCoordinatorAuthLinkConfig,\n\tCoordinatorAuthLinkSigner,\n} from \"./coordinator-auth-link-contract.js\";\nimport { capture, captureAuthLinkConfig, isHash } from \"./coordinator-auth-link-input.js\";\nimport { guardsHold } from \"./coordinator-auth-read-set.js\";\nimport { CoordinatorDeviceOwnershipEvidence } from \"./coordinator-device-ownership-evidence.js\";\nimport {\n\tcommitReviewedOwnerResolution,\n\ttype InternalOwnerResolutionReview,\n} from \"./coordinator-legacy-owner-resolution-commit.js\";\nimport type {\n\tLegacyOwnerResolutionRecord,\n\tReviewedWeakLabel,\n} from \"./coordinator-legacy-owner-resolution-metadata.js\";\nimport {\n\ttype ResolutionTarget,\n\tReviewUnavailable,\n\treadResolutionInvites,\n\treadResolutionRequester,\n\treadResolutionSource,\n\treadResolutionTarget,\n\trequireReviewSchema,\n} from \"./coordinator-owner-resolution-review-read.js\";\n\nexport interface OwnerResolutionReviewBackend extends AuthLinkBackend {\n\tall<T>(statement: AuthLinkStatement): Promise<T[]>;\n\treadBatch<T>(statements: AuthLinkStatement[]): Promise<T[][]>;\n}\nexport interface OwnerResolutionReviewSelection {\n\tgroupId: string;\n\tdeviceId: string;\n\tidentityId: string;\n\tfingerprint: string;\n}\nexport interface OwnerResolutionReviewConfirmation extends OwnerResolutionReviewSelection {\n\tconfirmOwnerResolutionDigest?: string;\n}\ntype Disposition = \"created\" | \"reused\";\nexport interface OwnerResolutionReviewResult {\n\tpurpose: \"existing_account_owner\";\n\tresolution_scope: \"historical_included_owner_labels_only\";\n\tstate: \"ready\" | \"needs_review\" | \"restored\";\n\treasons: string[];\n\tcoordinator_id: string;\n\tgroup_id: string;\n\tdevice_id: string;\n\tidentity_id: string;\n\tfingerprint: string;\n\towner_resolution_digest?: string;\n\taccount_owner_target?: ResolutionTarget & { identity_id: string };\n\tlegacy_history: ControllerHistoryEvidence[];\n\treviewed_weak_labels: ReviewedWeakLabel[];\n\tattestation_id?: string;\n\trecovery_receipt?: {\n\t\tdisposition: Disposition;\n\t\treview_receipt_id: string;\n\t\tevidence_digest: string;\n\t\tcreated_at: string;\n\t};\n\towner_resolution?: {\n\t\tdisposition: Disposition;\n\t\tresolution_id: string;\n\t\tevidence_digest: string;\n\t\tcreated_at: string;\n\t};\n}\n\n/** Callers must authenticate their trusted operator before using this capability. */\nexport interface CoordinatorOwnerResolutionReviewStore {\n\tpreviewOwnerResolutionReview(\n\t\tselection: OwnerResolutionReviewSelection,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<OwnerResolutionReviewResult>;\n\tconfirmOwnerResolutionReview(\n\t\tselection: OwnerResolutionReviewConfirmation,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<OwnerResolutionReviewResult>;\n}\n\nexport class OwnerResolutionReviewError extends Error {\n\tconstructor(readonly code: \"review_stale\" | \"owner_resolution_outcome_unknown\") {\n\t\tsuper(\n\t\t\tcode === \"review_stale\"\n\t\t\t\t? \"Review changed or confirmation is missing; preview again before confirming\"\n\t\t\t\t: \"Owner resolution outcome is unknown; preview its status before retrying\",\n\t\t);\n\t\tthis.name = \"OwnerResolutionReviewError\";\n\t}\n}\n\nconst PURPOSE = \"existing_account_owner\";\nconst SCOPE = \"historical_included_owner_labels_only\";\nconst SELECTION_FIELDS = [\"groupId\", \"deviceId\", \"identityId\", \"fingerprint\"] as const;\nfunction captureSelection(value: unknown): OwnerResolutionReviewSelection | null {\n\tconst row = capture(value, SELECTION_FIELDS);\n\tif (\n\t\t!row ||\n\t\t!isAuthControllerId(row.groupId) ||\n\t\t!isAuthControllerId(row.deviceId) ||\n\t\t!isAuthControllerId(row.identityId) ||\n\t\t!isHash(row.fingerprint)\n\t)\n\t\treturn null;\n\treturn {\n\t\tgroupId: row.groupId,\n\t\tdeviceId: row.deviceId,\n\t\tidentityId: row.identityId,\n\t\tfingerprint: row.fingerprint,\n\t};\n}\n\nasync function sha(value: unknown): Promise<string> {\n\tconst bytes = new TextEncoder().encode(JSON.stringify(value));\n\tconst digest = await crypto.subtle.digest(\"SHA-256\", bytes);\n\treturn Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction baseResult(\n\tselection: OwnerResolutionReviewSelection | null,\n\tconfig: CoordinatorAuthLinkConfig | null,\n): OwnerResolutionReviewResult {\n\treturn {\n\t\tpurpose: PURPOSE,\n\t\tresolution_scope: SCOPE,\n\t\tstate: \"needs_review\",\n\t\treasons: [],\n\t\tcoordinator_id: config?.coordinatorId ?? \"\",\n\t\tgroup_id: selection?.groupId ?? \"\",\n\t\tdevice_id: selection?.deviceId ?? \"\",\n\t\tidentity_id: selection?.identityId ?? \"\",\n\t\tfingerprint: selection?.fingerprint ?? \"\",\n\t\tlegacy_history: [],\n\t\treviewed_weak_labels: [],\n\t};\n}\n\nfunction receiptResult(\n\tcontroller: CoordinatorAuthControllerAttestation,\n\tresolution: LegacyOwnerResolutionRecord | null,\n\tcontrollerDisposition: Disposition,\n\tresolutionDisposition: Disposition,\n) {\n\treturn {\n\t\tattestation_id: controller.attestation_id,\n\t\trecovery_receipt: {\n\t\t\tdisposition: controllerDisposition,\n\t\t\treview_receipt_id: controller.review_receipt_id,\n\t\t\tevidence_digest: controller.evidence_digest,\n\t\t\tcreated_at: controller.created_at,\n\t\t},\n\t\t...(resolution\n\t\t\t? {\n\t\t\t\t\towner_resolution: {\n\t\t\t\t\t\tdisposition: resolutionDisposition,\n\t\t\t\t\t\tresolution_id: resolution.resolution_id,\n\t\t\t\t\t\tevidence_digest: resolution.resolution_evidence_digest,\n\t\t\t\t\t\tcreated_at: resolution.created_at,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\ninterface PreparedReview {\n\tresult: OwnerResolutionReviewResult;\n\treview?: InternalOwnerResolutionReview;\n\tevidence?: CoordinatorDeviceOwnershipEvidence;\n}\n\ninterface CapturedSubject {\n\tsigner: CoordinatorAuthLinkSigner;\n\tenrollmentIdentityId: string | null;\n\thistory: ControllerHistorySnapshot;\n\tevidence: CoordinatorDeviceOwnershipEvidence;\n\townershipEvidenceDigest: string;\n\tweakLabels: ReviewedWeakLabel[];\n\trecheckSnapshot: Parameters<CoordinatorDeviceOwnershipEvidence[\"recheckGuards\"]>[0];\n}\ntype ResolutionSource = Awaited<ReturnType<typeof readResolutionSource>>;\n\nasync function buildInternalReview(options: {\n\tselection: OwnerResolutionReviewSelection;\n\tconfig: CoordinatorAuthLinkConfig;\n\tsubject: CapturedSubject;\n\tsource: ResolutionSource;\n\ttarget: ResolutionTarget;\n\tinvites: Awaited<ReturnType<typeof readResolutionInvites>>;\n\tdigest: string;\n}): Promise<InternalOwnerResolutionReview> {\n\tconst { selection, config, subject, source, target, invites, digest } = options;\n\tconst attestationId = `controller-v1:${await sha([config.coordinatorId, selection.groupId, selection.deviceId, selection.fingerprint])}`;\n\treturn {\n\t\tcontrollerReview: {\n\t\t\tattestationId,\n\t\t\tcoordinatorId: config.coordinatorId,\n\t\t\tidentityId: selection.identityId,\n\t\t\t...subject.signer,\n\t\t\treviewReceiptId: `review-v1:${await sha([attestationId, selection.identityId, digest])}`,\n\t\t\tevidenceDigest: digest,\n\t\t\tverifiedSnapshot: {\n\t\t\t\tenrollmentIdentityId: subject.enrollmentIdentityId,\n\t\t\t\tinvites,\n\t\t\t\tlegacyHistory: subject.history,\n\t\t\t\taccountOwnerTarget: {\n\t\t\t\t\tpurpose: PURPOSE,\n\t\t\t\t\tcoordinatorId: config.coordinatorId,\n\t\t\t\t\ttargetIdentityId: selection.identityId,\n\t\t\t\t\tissuer: config.issuer,\n\t\t\t\t\tlinkId: target.link_id,\n\t\t\t\t\tauthConfigRevision: target.auth_config_revision,\n\t\t\t\t\tcreatedAtMs: target.created_at_ms,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\texistingController: source.controller,\n\t\texistingResolution: source.resolution,\n\t\townershipEvidenceDigest: subject.ownershipEvidenceDigest,\n\t\tresolutionId:\n\t\t\tsource.resolution?.resolution_id ??\n\t\t\t`resolution-v1:${await sha([config.coordinatorId, selection.deviceId, selection.identityId, digest])}`,\n\t\tconsent: { purpose: PURPOSE, scope: SCOPE, evidenceDigest: digest, confirmedDigest: digest },\n\t};\n}\n\nfunction preparedResult(\n\tbase: OwnerResolutionReviewResult,\n\tsubject: CapturedSubject,\n\ttarget: ResolutionTarget,\n\tsource: ResolutionSource,\n\tdigest: string,\n): OwnerResolutionReviewResult {\n\treturn {\n\t\t...base,\n\t\tstate: source.resolution ? \"restored\" : \"ready\",\n\t\towner_resolution_digest: digest,\n\t\taccount_owner_target: {\n\t\t\tidentity_id: base.identity_id,\n\t\t\tlink_id: target.link_id,\n\t\t\tauth_config_revision: target.auth_config_revision,\n\t\t\tcreated_at_ms: target.created_at_ms,\n\t\t},\n\t\tlegacy_history: subject.history.records.map((row) =>\n\t\t\tparseControllerHistoryRecord(row, base.coordinator_id),\n\t\t),\n\t\treviewed_weak_labels: subject.weakLabels,\n\t\t...(source.controller\n\t\t\t? receiptResult(source.controller, source.resolution, \"reused\", \"reused\")\n\t\t\t: {}),\n\t};\n}\n\n/** Internal review builder, not an HTTP authentication or account-mutation boundary.\n * Each call owns its reader and opaque snapshot; nothing is retained across requests.\n */\nexport class OwnerResolutionReviewOperations implements CoordinatorOwnerResolutionReviewStore {\n\tconstructor(\n\t\tprivate readonly backend: OwnerResolutionReviewBackend,\n\t\tprivate readonly clock: () => number = Date.now,\n\t) {}\n\n\tasync previewOwnerResolutionReview(\n\t\tselection: OwnerResolutionReviewSelection,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<OwnerResolutionReviewResult> {\n\t\treturn (await this.prepare(selection, config)).result;\n\t}\n\n\tasync confirmOwnerResolutionReview(\n\t\tselection: OwnerResolutionReviewConfirmation,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<OwnerResolutionReviewResult> {\n\t\tconst confirmed = capture(selection, [\n\t\t\t\"confirmOwnerResolutionDigest\",\n\t\t])?.confirmOwnerResolutionDigest;\n\t\tconst prepared = await this.prepare(selection, config);\n\t\tif (\n\t\t\t!isHash(confirmed) ||\n\t\t\t!prepared.review ||\n\t\t\t!prepared.evidence ||\n\t\t\tconfirmed !== prepared.result.owner_resolution_digest\n\t\t)\n\t\t\tthrow new OwnerResolutionReviewError(\"review_stale\");\n\t\ttry {\n\t\t\tconst applied = await commitReviewedOwnerResolution({\n\t\t\t\tbackend: this.backend,\n\t\t\t\tevidence: prepared.evidence,\n\t\t\t\treview: prepared.review,\n\t\t\t\tnow: new Date(this.clock()).toISOString(),\n\t\t\t});\n\t\t\treturn {\n\t\t\t\t...prepared.result,\n\t\t\t\tstate: \"ready\",\n\t\t\t\t...receiptResult(\n\t\t\t\t\tapplied.controller,\n\t\t\t\t\tapplied.resolution,\n\t\t\t\t\tapplied.controllerDisposition,\n\t\t\t\t\tapplied.resolutionDisposition,\n\t\t\t\t),\n\t\t\t};\n\t\t} catch {\n\t\t\tthrow new OwnerResolutionReviewError(\"owner_resolution_outcome_unknown\");\n\t\t}\n\t}\n\n\tprivate async prepare(input: unknown, config: unknown): Promise<PreparedReview> {\n\t\tconst selection = captureSelection(input);\n\t\tconst capturedConfig = captureAuthLinkConfig(config);\n\t\tconst result = baseResult(selection, capturedConfig);\n\t\tif (!selection || !capturedConfig?.enabled) {\n\t\t\tresult.reasons = [\n\t\t\t\t\"invalid_selection_or_config: select a current device and an enabled account configuration\",\n\t\t\t];\n\t\t\treturn { result };\n\t\t}\n\t\ttry {\n\t\t\tawait requireReviewSchema(this.backend);\n\t\t\treturn await this.prepareCaptured(selection, capturedConfig, result);\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tresult: {\n\t\t\t\t\t...result,\n\t\t\t\t\treasons: [\n\t\t\t\t\t\terror instanceof ReviewUnavailable\n\t\t\t\t\t\t\t? error.message\n\t\t\t\t\t\t\t: \"review_unavailable: ask the operator to inspect current ownership evidence\",\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t}\n\n\tprivate async captureSubject(\n\t\tselection: OwnerResolutionReviewSelection,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CapturedSubject> {\n\t\tconst { signer, enrollmentIdentityId } = await readResolutionRequester(this.backend, selection);\n\t\tconst history = await captureControllerHistory(\n\t\t\t{\n\t\t\t\tcoordinatorId: config.coordinatorId,\n\t\t\t\tdeviceId: signer.deviceId,\n\t\t\t\tpublicKey: signer.publicKey,\n\t\t\t\tfingerprint: signer.fingerprint,\n\t\t\t},\n\t\t\t<T>(sql: string, values: string[]) => this.backend.all<T>({ sql, values }),\n\t\t);\n\t\tconst evidence = new CoordinatorDeviceOwnershipEvidence(this.backend, config);\n\t\tconst collected = await evidence.collect({\n\t\t\tcanonicalOwnerId: selection.identityId,\n\t\t\tactualSigner: signer,\n\t\t\tverifiedHistory: history,\n\t\t});\n\t\tif (\n\t\t\tcollected.kind !== \"collected\" ||\n\t\t\t![\"compatible\", \"weak_label_review_required\"].includes(collected.decision)\n\t\t)\n\t\t\tthrow new ReviewUnavailable(\n\t\t\t\t\"ownership_unavailable: inspect current device revocations, owner conflicts and historical labels\",\n\t\t\t);\n\t\tconst ownershipEvidenceDigest = await evidence.reviewedEvidenceDigest(\n\t\t\tcollected.recheckSnapshot,\n\t\t);\n\t\tif (!ownershipEvidenceDigest)\n\t\t\tthrow new ReviewUnavailable(\"evidence_unavailable: preview ownership evidence again\");\n\t\treturn {\n\t\t\tsigner,\n\t\t\tenrollmentIdentityId,\n\t\t\thistory,\n\t\t\tevidence,\n\t\t\townershipEvidenceDigest,\n\t\t\tweakLabels: collected.weakLabels,\n\t\t\trecheckSnapshot: collected.recheckSnapshot,\n\t\t};\n\t}\n\n\tprivate async requireUnchangedCapture(\n\t\tselection: OwnerResolutionReviewSelection,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t\tsubject: CapturedSubject,\n\t\ttarget: ResolutionTarget,\n\t): Promise<void> {\n\t\tconst guards = subject.evidence.recheckGuards(subject.recheckSnapshot);\n\t\tconst unchanged = guards !== null && (await guardsHold(this.backend, guards));\n\t\tconst currentTarget = await readResolutionTarget(this.backend, selection, config);\n\t\tif (\n\t\t\t!unchanged ||\n\t\t\tcurrentTarget.link_id !== target.link_id ||\n\t\t\tcurrentTarget.auth_config_revision !== target.auth_config_revision ||\n\t\t\tcurrentTarget.created_at_ms !== target.created_at_ms\n\t\t)\n\t\t\tthrow new ReviewUnavailable(\"review_changed: preview the current ownership evidence again\");\n\t\tawait requireReviewSchema(this.backend);\n\t}\n\n\tprivate async prepareCaptured(\n\t\tselection: OwnerResolutionReviewSelection,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t\tbase: OwnerResolutionReviewResult,\n\t): Promise<PreparedReview> {\n\t\tconst target = await readResolutionTarget(this.backend, selection, config);\n\t\tconst subject = await this.captureSubject(selection, config);\n\t\tconst { signer, history, evidence, ownershipEvidenceDigest } = subject;\n\t\tconst source = await readResolutionSource({\n\t\t\tbackend: this.backend,\n\t\t\tconfig,\n\t\t\tselection,\n\t\t\tsigner,\n\t\t\thistory,\n\t\t\tevidence,\n\t\t});\n\t\tconst invites = await readResolutionInvites(this.backend, signer);\n\t\tawait this.requireUnchangedCapture(selection, config, subject, target);\n\t\tconst digest = await sha([\n\t\t\t\"owner-resolution-review-v1\",\n\t\t\tPURPOSE,\n\t\t\tSCOPE,\n\t\t\tselection,\n\t\t\tconfig.coordinatorId,\n\t\t\tconfig.issuer,\n\t\t\tconfig.revision,\n\t\t\townershipEvidenceDigest,\n\t\t\ttarget,\n\t\t\tcontrollerHistoryDigestEvidence(history),\n\t\t\tsource.controller,\n\t\t\tsource.resolution,\n\t\t\tinvites,\n\t\t]);\n\t\tconst review = await buildInternalReview({\n\t\t\tselection,\n\t\t\tconfig,\n\t\t\tsubject,\n\t\t\tsource,\n\t\t\ttarget,\n\t\t\tinvites,\n\t\t\tdigest,\n\t\t});\n\t\treturn {\n\t\t\tevidence,\n\t\t\treview,\n\t\t\tresult: preparedResult(base, subject, target, source, digest),\n\t\t};\n\t}\n}\n","export interface CapturedPeerEnrollment {\n\treadonly group_id: string;\n\treadonly device_id: string;\n\treadonly public_key: string;\n\treadonly fingerprint: string;\n\treadonly identity_id: string | null;\n\treadonly enabled: number;\n}\n\nexport const CAPTURE_PEER_ENROLLMENTS_SQL = `SELECT group_id, device_id, public_key,\n\tfingerprint, identity_id, enabled FROM enrolled_devices\n\tWHERE group_id = ? AND enabled = 1 AND device_id != ?\n\tORDER BY device_id ASC`;\n\n/** Copy every primitive before async hashing can yield to enrollment changes. */\nexport function capturePeerEnrollments(\n\trows: readonly CapturedPeerEnrollment[],\n): CapturedPeerEnrollment[] {\n\treturn rows.map((row) => ({\n\t\tgroup_id: row.group_id,\n\t\tdevice_id: row.device_id,\n\t\tpublic_key: row.public_key,\n\t\tfingerprint: row.fingerprint,\n\t\tidentity_id: row.identity_id,\n\t\tenabled: row.enabled,\n\t}));\n}\n\n// One JSON parameter keeps the bind count constant even for large groups. Only\n// unchanged captured candidates survive; metadata and presence come from this read.\n// Keep captured rows first so each candidate seeks one enrollment instead of\n// rescanning the captured JSON for every enrolled device when statistics are absent.\nexport const READ_CURRENT_PEERS_SQL = `SELECT e.device_id, e.public_key, e.fingerprint,\n\te.display_name, p.addresses_json, p.last_seen_at, p.expires_at, p.capabilities_json\n\tFROM json_each(?) AS captured\n\tCROSS JOIN enrolled_devices AS e\n\t ON e.group_id = json_extract(captured.value, '$.group_id')\n\t AND e.device_id = json_extract(captured.value, '$.device_id')\n\t AND e.public_key = json_extract(captured.value, '$.public_key')\n\t AND e.fingerprint = json_extract(captured.value, '$.fingerprint')\n\t AND e.identity_id IS json_extract(captured.value, '$.identity_id')\n\t AND e.enabled = json_extract(captured.value, '$.enabled')\n\tLEFT JOIN presence_records AS p\n\t ON p.group_id = e.group_id AND p.device_id = e.device_id\n\tWHERE e.group_id = ? AND e.enabled = 1 AND e.device_id != ?\n\t AND NOT EXISTS (SELECT 1 FROM coordinator_device_revocations AS r WHERE\n\t (r.subject_kind = 'device_id' AND r.subject_value = e.device_id)\n\t OR (r.subject_kind = 'ed25519_key'\n\t AND r.subject_value = json_extract(captured.value, '$.keyId')))\n\tORDER BY e.device_id ASC`;\n\n/** A malformed backend response is not an empty discovery result. */\nexport function requirePeerDiscoveryRows(rows: unknown): Record<string, unknown>[] {\n\tif (!Array.isArray(rows)) throw new Error(\"peer_discovery_unavailable\");\n\tfor (const row of rows) requirePeerDiscoveryRow(row);\n\treturn rows;\n}\n\nfunction requirePeerDiscoveryRow(row: unknown): void {\n\tif (!row || typeof row !== \"object\" || Array.isArray(row)) {\n\t\tthrow new Error(\"peer_discovery_unavailable\");\n\t}\n\tconst record = row as Record<string, unknown>;\n\tfor (const field of [\"device_id\", \"public_key\", \"fingerprint\"]) {\n\t\tif (typeof record[field] !== \"string\") throw new Error(\"peer_discovery_unavailable\");\n\t}\n\tfor (const field of [\n\t\t\"display_name\",\n\t\t\"addresses_json\",\n\t\t\"last_seen_at\",\n\t\t\"expires_at\",\n\t\t\"capabilities_json\",\n\t]) {\n\t\tif (record[field] !== null && typeof record[field] !== \"string\") {\n\t\t\tthrow new Error(\"peer_discovery_unavailable\");\n\t\t}\n\t}\n}\n","import { DEVICE_REVOCATION_SUBJECT_EXISTS_SQL } from \"./coordinator-device-revocation.js\";\nimport type {\n\tCoordinatorConsumeProjectInviteInput,\n\tCoordinatorEnrollment,\n\tCoordinatorInvite,\n} from \"./coordinator-store-contract.js\";\n\nconst revocationSql = `${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}\n\t\tOR ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}`;\n// Pin the reviewed Project intent and the enrollment used to derive the seed key.\n// Every writer owns this guard: a zero-row batch statement does not stop its siblings.\nconst eligibilitySql = `EXISTS (SELECT 1 FROM coordinator_invites pi\n\t\tJOIN groups pg ON pg.group_id = pi.group_id AND pg.archived_at IS NULL\n\t\tWHERE pi.invite_id = ? AND pi.group_id = ? AND pi.revoked_at IS NULL\n\t\tAND pi.operation_id = ? AND pi.project_intent_json = ?\n\t\tAND pi.reviewed_project_set_digest IS ? AND pi.token_digest IS ?\n\t\tAND pi.project_summaries_json IS ? AND pi.inviter_actor_id IS ?\n\t\tAND pi.inviter_device_id IS ? AND pi.expires_at = ?\n\t\tAND ((? = 0 AND NOT EXISTS (SELECT 1 FROM enrolled_devices se\n\t\t\tWHERE se.group_id = pi.group_id AND se.device_id = pi.inviter_device_id))\n\t\t\tOR (? = 1 AND EXISTS (SELECT 1 FROM enrolled_devices se\n\t\t\t\tWHERE se.group_id = pi.group_id AND se.device_id = pi.inviter_device_id\n\t\t\t\tAND se.public_key = ? AND se.fingerprint = ? AND se.enabled = ?)))\n\t\tAND NOT EXISTS (SELECT 1 FROM enrolled_devices re\n\t\t\tWHERE re.group_id = pi.group_id AND re.device_id = ?\n\t\t\tAND (re.public_key <> ? OR re.fingerprint <> ?\n\t\t\t\tOR (re.identity_id IS NOT NULL AND re.identity_id <> ?)))\n\t\tAND NOT (${revocationSql}))`;\nconst bindingSql = `EXISTS (SELECT 1 FROM coordinator_invites bi\n\tWHERE bi.invite_id = ? AND bi.consumed_at IS NOT NULL\n\tAND bi.bound_device_id = ? AND bi.bound_public_key = ? AND bi.bound_fingerprint = ?\n\tAND bi.recipient_actor_id = ? AND bi.recipient_display_name = ?\n\tAND bi.recipient_device_display_name = ?)`;\n\nexport function projectInviteGuardEvidence(\n\tinvite: CoordinatorInvite,\n\topts: CoordinatorConsumeProjectInviteInput,\n\tinviter: CoordinatorEnrollment | null,\n\tkeyIds: { recipient: string | null; inviter: string | null },\n) {\n\tconst revocationValues = [\n\t\topts.deviceId,\n\t\tkeyIds.recipient,\n\t\tinvite.inviter_device_id ?? null,\n\t\tkeyIds.inviter,\n\t];\n\tconst eligibilityValues = [\n\t\tinvite.invite_id,\n\t\tinvite.group_id,\n\t\tinvite.operation_id,\n\t\tinvite.project_intent_json,\n\t\tinvite.reviewed_project_set_digest ?? null,\n\t\tinvite.token_digest ?? null,\n\t\tinvite.project_summaries_json ?? null,\n\t\tinvite.inviter_actor_id ?? null,\n\t\tinvite.inviter_device_id ?? null,\n\t\tinvite.expires_at,\n\t\tinviter ? 1 : 0,\n\t\tinviter ? 1 : 0,\n\t\tinviter?.public_key ?? null,\n\t\tinviter?.fingerprint ?? null,\n\t\tinviter?.enabled ?? null,\n\t\topts.deviceId,\n\t\topts.publicKey,\n\t\topts.fingerprint,\n\t\topts.recipientActorId,\n\t\t...revocationValues,\n\t];\n\treturn {\n\t\trevocationSql,\n\t\trevocationValues,\n\t\teligibilitySql,\n\t\teligibilityValues,\n\t\tboundEligibilitySql: `${eligibilitySql} AND ${bindingSql}`,\n\t\tboundEligibilityValues: [\n\t\t\t...eligibilityValues,\n\t\t\tinvite.invite_id,\n\t\t\topts.deviceId,\n\t\t\topts.publicKey,\n\t\t\topts.fingerprint,\n\t\t\topts.recipientActorId,\n\t\t\topts.recipientDisplayName,\n\t\t\topts.deviceDisplayName,\n\t\t],\n\t};\n}\n","import { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { AuthLinkBackend } from \"./coordinator-auth-link.js\";\nimport {\n\ttype NegativeOwnerGuards,\n\treadNegativeOwnerConsistency,\n\treadUnknownNamespaceOwnerConsistency,\n} from \"./coordinator-owner-negative-read-set.js\";\nimport type { CoordinatorConsumeRecipientInviteInput } from \"./coordinator-store-contract.js\";\n\nexport function validateRecipientOwnerInput(input: CoordinatorConsumeRecipientInviteInput): void {\n\tif (\n\t\t!input.identityId ||\n\t\t!input.deviceId ||\n\t\t!input.publicKey ||\n\t\t!input.fingerprint ||\n\t\tinput.identityId !== input.identityId.trim() ||\n\t\tinput.deviceId !== input.deviceId.trim() ||\n\t\tinput.identityId.length > 256 ||\n\t\tinput.deviceId.length > 256 ||\n\t\t/[\\p{Cc}\\p{Cf}]/u.test(input.identityId) ||\n\t\t/[\\p{Cc}\\p{Cf}]/u.test(input.deviceId)\n\t)\n\t\tthrow new Error(\"invite_identity_conflict\");\n}\n\n/** Reads the recipient's retained ownership. Null refuses the invite. */\nexport function readRecipientOwnerConsistency(\n\tbackend: Pick<AuthLinkBackend, \"first\" | \"all\" | \"readBatch\">,\n\tinput: CoordinatorConsumeRecipientInviteInput,\n): Promise<NegativeOwnerGuards | null> {\n\tif (input.coordinatorId === undefined)\n\t\treturn readUnknownNamespaceOwnerConsistency(backend, input);\n\tif (!isAuthControllerId(input.coordinatorId)) return Promise.resolve(null);\n\treturn readNegativeOwnerConsistency(backend, {\n\t\tcoordinatorId: input.coordinatorId,\n\t\townerIdentityId: input.identityId,\n\t\tdeviceId: input.deviceId,\n\t\tpublicKey: input.publicKey,\n\t\tfingerprint: input.fingerprint,\n\t});\n}\n","import { connectionProfileColumns } from \"./coordinator-account-connection-session.js\";\nimport { CONNECTION_NOT_REVOKED_SQL } from \"./coordinator-account-connection-storage.js\";\nimport type { AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport type {\n\tCoordinatorAuthLinkConfig,\n\tCoordinatorAuthLinkSigner,\n} from \"./coordinator-auth-link-contract.js\";\nimport { authAccountLinkProvenanceSql } from \"./coordinator-auth-link-provenance.js\";\nimport { RESOLUTION_COLUMNS } from \"./coordinator-device-ownership-evidence-queries.js\";\nimport type { LegacyOwnerResolutionRecord } from \"./coordinator-legacy-owner-resolution-metadata.js\";\n\nexport interface ResolvedOwnerProfileRow {\n\tlink_count: number;\n\tlink_id: string | null;\n\tnot_revoked: number | null;\n\tvalid_link: string | null;\n\tdisplay_name: unknown;\n\temail: unknown;\n\temail_verified: unknown;\n\tpicture_url: unknown;\n}\n\n/** All thirteen original fields belong to the same source, including SQL NULLs. */\nconst sourceMatch = `c.attestation_id=r.source_attestation_id\n AND c.coordinator_id=r.coordinator_id AND c.identity_id=r.owner_identity_id\n AND c.group_id=r.source_group_id AND c.device_id=r.device_id\n AND c.public_key=r.source_public_key AND c.fingerprint=r.source_fingerprint\n AND c.review_receipt_id=r.source_review_receipt_id AND c.evidence_digest=r.source_evidence_digest\n AND c.enrollment_identity_id IS r.source_enrollment_identity_id\n AND c.revision=r.source_controller_revision AND c.created_at=r.source_created_at\n AND c.revoked_at IS NULL`;\n\n/**\n * The resolved owner's fact, requester and profile. The evidence the status was built on\n * is checked by guards that run in the same read batch, in front of this query.\n */\nexport function resolvedOwnerProfileQuery(options: {\n\tsigner: CoordinatorAuthLinkSigner;\n\tconfig: CoordinatorAuthLinkConfig;\n\tresolution: LegacyOwnerResolutionRecord;\n\tkeyId: string;\n}): AuthLinkStatement {\n\tconst { signer, config, resolution, keyId } = options;\n\treturn {\n\t\tsql: `WITH resolved_input AS MATERIALIZED (SELECT ? AS coordinator_id,? AS owner_id,\n ? AS group_id,? AS device_id,? AS public_key,? AS fingerprint,? AS key_id,? AS issuer,? AS fact),\n resolved_fact AS MATERIALIZED (\n SELECT r.resolution_id FROM resolved_input i\n JOIN coordinator_legacy_owner_resolutions r ON r.coordinator_id=i.coordinator_id\n AND r.device_id=i.device_id AND r.key_id=i.key_id AND r.owner_identity_id=i.owner_id\n JOIN coordinator_auth_controller_attestations c ON ${sourceMatch}\n WHERE ${RESOLUTION_COLUMNS.map((field) => `r.${field} IS json_extract(i.fact,'$.${field}')`).join(\" AND \")}),\n resolved_requester AS MATERIALIZED (\n SELECT 1 AS present FROM resolved_input i JOIN enrolled_devices e\n ON e.group_id=i.group_id AND e.device_id=i.device_id\n JOIN groups g ON g.group_id=e.group_id\n WHERE e.public_key=i.public_key AND e.fingerprint=i.fingerprint AND e.enabled=1\n AND g.archived_at IS NULL AND NOT EXISTS (\n SELECT 1 FROM coordinator_device_revocations v\n WHERE (v.subject_kind='device_id' AND v.subject_value=i.device_id)\n OR (v.subject_kind='ed25519_key' AND v.subject_value=i.key_id))),\n resolved_links AS MATERIALIZED (\n SELECT l.*,CASE WHEN ${CONNECTION_NOT_REVOKED_SQL} THEN 1 ELSE 0 END AS not_revoked\n FROM coordinator_auth_account_links l JOIN resolved_input i\n ON l.coordinator_id=i.coordinator_id AND l.identity_id=i.owner_id LIMIT 2),\n resolved_valid_links AS MATERIALIZED (\n SELECT l.* FROM resolved_links l JOIN resolved_input i ON l.issuer=i.issuer\n WHERE ${authAccountLinkProvenanceSql(\"l\", { connections: true })}),\n resolved_profiles AS MATERIALIZED (\n SELECT l.link_id,${connectionProfileColumns(\"p\")}\n FROM resolved_valid_links l LEFT JOIN coordinator_auth_account_profiles p\n ON p.coordinator_id=l.coordinator_id AND p.link_id=l.link_id\n LEFT JOIN coordinator_auth_link_profiles b ON b.coordinator_id=l.coordinator_id\n AND b.link_id=l.link_id AND b.attempt_id=l.attempt_id AND b.issuer=l.issuer\n AND b.subject=l.subject AND b.auth_config_revision=l.auth_config_revision\n WHERE l.not_revoked=1)\n SELECT (SELECT count(*) FROM resolved_links) AS link_count,l.link_id,l.not_revoked,\n v.link_id AS valid_link,p.display_name,p.email,p.email_verified,p.picture_url\n FROM resolved_fact f\n JOIN resolved_requester requester ON requester.present=1\n LEFT JOIN resolved_links l ON 1\n LEFT JOIN resolved_valid_links v ON v.link_id=l.link_id\n LEFT JOIN resolved_profiles p ON p.link_id=v.link_id LIMIT 1`,\n\t\tvalues: [\n\t\t\tconfig.coordinatorId,\n\t\t\tresolution.owner_identity_id,\n\t\t\tsigner.groupId,\n\t\t\tsigner.deviceId,\n\t\t\tsigner.publicKey,\n\t\t\tsigner.fingerprint,\n\t\t\tkeyId,\n\t\t\tconfig.issuer,\n\t\t\tJSON.stringify(resolution),\n\t\t],\n\t};\n}\n","import { captureAuthAccountProfile } from \"./coordinator-auth-account-profile.js\";\nimport { projectAccountProfileView } from \"./coordinator-auth-browser-view.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport { captureControllerHistory } from \"./coordinator-auth-controller-history.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport type {\n\tCoordinatorAuthLinkConfig,\n\tCoordinatorAuthLinkSigner,\n} from \"./coordinator-auth-link-contract.js\";\nimport {\n\tcapture,\n\tcaptureAuthLinkConfig,\n\tcaptureAuthLinkSigner,\n\tisHash,\n} from \"./coordinator-auth-link-input.js\";\nimport { readAfterGuards } from \"./coordinator-auth-read-set.js\";\nimport { CoordinatorDeviceOwnershipEvidence } from \"./coordinator-device-ownership-evidence.js\";\nimport {\n\tBYTE_LIMIT,\n\tRESOLUTION_COLUMNS,\n\tROW_LIMIT,\n} from \"./coordinator-device-ownership-evidence-queries.js\";\nimport { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport {\n\tcaptureLegacyOwnerResolutionRecord,\n\ttype LegacyOwnerResolutionRecord,\n} from \"./coordinator-legacy-owner-resolution-metadata.js\";\nimport { requireReviewSchema } from \"./coordinator-owner-resolution-review-read.js\";\nimport {\n\ttype ResolvedOwnerProfileRow,\n\tresolvedOwnerProfileQuery,\n} from \"./coordinator-resolved-account-owner-status-query.js\";\n\ntype ResolvedOwnerBackend = AuthLinkBackend & {\n\tall<T>(statement: AuthLinkStatement): Promise<T[]>;\n\t/** The final read runs behind the evidence guards in one atomic read batch. */\n\treadBatch<T>(statements: AuthLinkStatement[]): Promise<T[][]>;\n};\ninterface SafeProfile {\n\tdisplayName?: string;\n\temail?: string;\n\tpictureUrl?: string;\n}\ninterface StatusSubject {\n\tversion: 1;\n\tcoordinatorId: string;\n\tgroupId: string;\n\tdeviceId: string;\n\tfingerprint: string;\n}\nexport type ResolvedAccountOwnerStatus = StatusSubject &\n\t(\n\t\t| {\n\t\t\t\tstate: \"owner_unconfirmed\";\n\t\t\t\townerIdentity: null;\n\t\t\t\tprofileState: \"unavailable\";\n\t\t\t\tprofile: null;\n\t\t }\n\t\t| {\n\t\t\t\tstate: \"owner_confirmed\";\n\t\t\t\townerIdentity: string;\n\t\t\t\tprofileState: \"linked\";\n\t\t\t\tprofile: SafeProfile;\n\t\t }\n\t\t| {\n\t\t\t\tstate: \"owner_confirmed\";\n\t\t\t\townerIdentity: string;\n\t\t\t\tprofileState: \"account_unlinked\" | \"unavailable\";\n\t\t\t\tprofile: null;\n\t\t }\n\t);\n\nexport class ResolvedAccountOwnerStatusUnavailableError extends Error {\n\tconstructor() {\n\t\tsuper(\"resolved_account_owner_status_unavailable\");\n\t}\n}\n\nexport interface ResolvedAccountOwnerReceiptReference {\n\tattestationId: string;\n\treviewReceiptId: string;\n\treviewEvidenceDigest: string;\n\tresolutionId: string;\n\tresolutionEvidenceDigest: string;\n}\nconst RECEIPT_FIELDS = [\n\t\"attestationId\",\n\t\"reviewReceiptId\",\n\t\"reviewEvidenceDigest\",\n\t\"resolutionId\",\n\t\"resolutionEvidenceDigest\",\n] as const;\n\n/** Capture data descriptors only; never evaluate submitted accessors. */\nexport function captureResolvedAccountOwnerReceiptReference(\n\tvalue: unknown,\n): ResolvedAccountOwnerReceiptReference | null {\n\ttry {\n\t\tconst receipt = capture(value, RECEIPT_FIELDS);\n\t\tif (\n\t\t\t!receipt ||\n\t\t\tReflect.ownKeys(value as object).length !== RECEIPT_FIELDS.length ||\n\t\t\t![Object.prototype, null].includes(Object.getPrototypeOf(value)) ||\n\t\t\t!isAuthControllerId(receipt.attestationId) ||\n\t\t\t!isAuthControllerId(receipt.reviewReceiptId) ||\n\t\t\t!isAuthControllerId(receipt.resolutionId) ||\n\t\t\t!isHash(receipt.reviewEvidenceDigest) ||\n\t\t\t!isHash(receipt.resolutionEvidenceDigest)\n\t\t)\n\t\t\treturn null;\n\t\treturn receipt as unknown as ResolvedAccountOwnerReceiptReference;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction captureExpectedReceipt(options: object): ResolvedAccountOwnerReceiptReference | undefined {\n\ttry {\n\t\tif (!(\"expectedReceipt\" in options)) return undefined;\n\t\tconst outer = capture(options, [\"expectedReceipt\"]);\n\t\tconst receipt = captureResolvedAccountOwnerReceiptReference(outer?.expectedReceipt);\n\t\tif (receipt) return receipt;\n\t} catch {\n\t\t// Malformed descriptors must not turn a constrained read into an ordinary read.\n\t}\n\tthrow new ResolvedAccountOwnerStatusUnavailableError();\n}\n\nfunction projectProfile(row: ResolvedOwnerProfileRow, issuer: string): SafeProfile | null {\n\tconst captured = captureAuthAccountProfile({\n\t\tdisplayName: row.display_name,\n\t\temail: row.email,\n\t\temailVerified: row.email_verified === 1,\n\t\tpictureUrl: row.picture_url,\n\t});\n\tif (!captured) return null;\n\tconst profile: SafeProfile = {};\n\tif (captured.displayName !== undefined) profile.displayName = captured.displayName;\n\tif (captured.emailVerified === true && captured.email !== undefined)\n\t\tprofile.email = captured.email;\n\tconst { pictureUrl } = projectAccountProfileView(captured, issuer);\n\tif (pictureUrl !== undefined) profile.pictureUrl = pictureUrl;\n\treturn profile;\n}\n\nfunction projectStatus(\n\tbase: Extract<ResolvedAccountOwnerStatus, { state: \"owner_unconfirmed\" }>,\n\trow: ResolvedOwnerProfileRow | null,\n\towner: string,\n\tissuer: string,\n): ResolvedAccountOwnerStatus {\n\tif (!row) return base;\n\tconst confirmed = { ...base, state: \"owner_confirmed\" as const, ownerIdentity: owner };\n\tif (row.link_count > 1) return { ...confirmed, profileState: \"unavailable\", profile: null };\n\tif (row.link_count === 0)\n\t\treturn { ...confirmed, profileState: \"account_unlinked\", profile: null };\n\tif (!row.valid_link) return { ...confirmed, profileState: \"unavailable\", profile: null };\n\tif (row.not_revoked === 0)\n\t\treturn { ...confirmed, profileState: \"account_unlinked\", profile: null };\n\tif (!projectProfile(row, issuer))\n\t\treturn { ...confirmed, profileState: \"unavailable\", profile: null };\n\t// This read always comes from a device that runs as another Identity, so it\n\t// holds no proof of its own for the owner. It learns that the owner's account\n\t// is linked, but never the name, email, or picture (ADR 0005 Section 8).\n\t// An empty profile keeps older Viewers' response checks working.\n\treturn { ...confirmed, profileState: \"linked\", profile: {} };\n}\n\nasync function readCandidates(\n\tbackend: ResolvedOwnerBackend,\n\tcoordinator: string,\n\tdevice: string,\n\tkey: string,\n\towner: string,\n\texpectedReceipt?: ResolvedAccountOwnerReceiptReference,\n) {\n\tconst receiptPredicate = expectedReceipt\n\t\t? ` AND source_attestation_id=? AND source_review_receipt_id=? AND source_evidence_digest=?\n AND resolution_id=? AND resolution_evidence_digest=?`\n\t\t: \"\";\n\tconst rows = await backend.all<unknown>({\n\t\tsql: `SELECT ${RESOLUTION_COLUMNS.join(\",\")} FROM coordinator_legacy_owner_resolutions\n WHERE coordinator_id=? AND device_id=? AND key_id=? AND owner_identity_id=?${receiptPredicate}\n ORDER BY created_at,resolution_id LIMIT ${ROW_LIMIT + 1}`,\n\t\tvalues: [\n\t\t\tcoordinator,\n\t\t\tdevice,\n\t\t\tkey,\n\t\t\towner,\n\t\t\t...(expectedReceipt ? RECEIPT_FIELDS.map((field) => expectedReceipt[field]) : []),\n\t\t],\n\t});\n\tif (\n\t\trows.length > ROW_LIMIT ||\n\t\tnew TextEncoder().encode(JSON.stringify(rows)).byteLength > BYTE_LIMIT\n\t)\n\t\tthrow new ResolvedAccountOwnerStatusUnavailableError();\n\tconst candidates: LegacyOwnerResolutionRecord[] = [];\n\tfor (const value of rows) {\n\t\tconst candidate = await captureLegacyOwnerResolutionRecord(value);\n\t\tif (candidate) candidates.push(candidate);\n\t}\n\treturn candidates;\n}\n\n/** Read-only display proof. The selected owner is a query, never an authority input. */\nexport class ResolvedAccountOwnerStatusOperations {\n\tconstructor(private readonly backend: ResolvedOwnerBackend) {}\n\n\tasync readResolvedAccountOwnerStatus(\n\t\tsigner: CoordinatorAuthLinkSigner,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t\toptions: { ownerIdentityId: string; expectedReceipt?: unknown },\n\t): Promise<ResolvedAccountOwnerStatus> {\n\t\tconst s = captureAuthLinkSigner(signer);\n\t\tconst c = captureAuthLinkConfig(config);\n\t\tconst selected = capture(options, [\"ownerIdentityId\"]);\n\t\tif (!s || !c?.enabled || !selected || !isAuthControllerId(selected.ownerIdentityId))\n\t\t\tthrow new ResolvedAccountOwnerStatusUnavailableError();\n\t\tconst expectedReceipt = captureExpectedReceipt(options);\n\t\tconst owner = selected.ownerIdentityId;\n\t\tconst base: Extract<ResolvedAccountOwnerStatus, { state: \"owner_unconfirmed\" }> = {\n\t\t\tversion: 1,\n\t\t\tcoordinatorId: c.coordinatorId,\n\t\t\tgroupId: s.groupId,\n\t\t\tdeviceId: s.deviceId,\n\t\t\tfingerprint: s.fingerprint,\n\t\t\tstate: \"owner_unconfirmed\",\n\t\t\townerIdentity: null,\n\t\t\tprofileState: \"unavailable\",\n\t\t\tprofile: null,\n\t\t};\n\t\ttry {\n\t\t\tawait requireReviewSchema(this.backend);\n\t\t\treturn await this.readCaptured(s, c, owner, base, expectedReceipt);\n\t\t} catch {\n\t\t\tthrow new ResolvedAccountOwnerStatusUnavailableError();\n\t\t}\n\t}\n\n\tprivate async readCaptured(\n\t\tsigner: CoordinatorAuthLinkSigner,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t\towner: string,\n\t\tbase: Extract<ResolvedAccountOwnerStatus, { state: \"owner_unconfirmed\" }>,\n\t\texpectedReceipt?: ResolvedAccountOwnerReceiptReference,\n\t): Promise<ResolvedAccountOwnerStatus> {\n\t\tconst keyId = await ed25519KeyIdForRevocation(signer.publicKey);\n\t\tif (!keyId) return base;\n\t\tconst candidates = await readCandidates(\n\t\t\tthis.backend,\n\t\t\tconfig.coordinatorId,\n\t\t\tsigner.deviceId,\n\t\t\tkeyId,\n\t\t\towner,\n\t\t\texpectedReceipt,\n\t\t);\n\t\tif (!candidates.length) return base;\n\t\tconst history = await captureControllerHistory(\n\t\t\t{ coordinatorId: config.coordinatorId, ...signer },\n\t\t\t<T>(sql: string, values: string[]) => this.backend.all<T>({ sql, values }),\n\t\t);\n\t\tconst evidence = new CoordinatorDeviceOwnershipEvidence(this.backend, config);\n\t\tconst collected = await evidence.collect({\n\t\t\tcanonicalOwnerId: owner,\n\t\t\tactualSigner: signer,\n\t\t\tverifiedHistory: history,\n\t\t});\n\t\tif (\n\t\t\tcollected.kind !== \"collected\" ||\n\t\t\t![\"compatible\", \"weak_label_review_required\"].includes(collected.decision)\n\t\t)\n\t\t\treturn base;\n\t\tfor (const resolution of candidates) {\n\t\t\tconst source = await evidence.verifyControllerSource({\n\t\t\t\tsourceRef: resolution,\n\t\t\t\texpectedOwnerId: owner,\n\t\t\t\tactualSigner: signer,\n\t\t\t});\n\t\t\tif (source.kind !== \"verified_controller_source\") continue;\n\t\t\t// Changed evidence leaves no row, as the old query's evidence join did.\n\t\t\tconst guards = evidence.recheckGuards(collected.recheckSnapshot);\n\t\t\tif (!guards) return projectStatus(base, null, owner, config.issuer);\n\t\t\tconst read = await readAfterGuards<ResolvedOwnerProfileRow>(\n\t\t\t\tthis.backend,\n\t\t\t\tguards,\n\t\t\t\tresolvedOwnerProfileQuery({ signer, config, resolution, keyId }),\n\t\t\t);\n\t\t\treturn projectStatus(base, read.changed ? null : read.row, owner, config.issuer);\n\t\t}\n\t\treturn base;\n\t}\n}\n","import type { CoordinatorAuthSchemaStore } from \"./coordinator-auth-schema.js\";\nimport type { CoordinatorDeviceRevocationStore } from \"./coordinator-device-revocation.js\";\nimport type {\n\tCoordinatorLegacyTeamCompletionManifestV1,\n\tCoordinatorLegacyTeamCompletionRecord,\n\tCoordinatorLegacyTeamCompletionWriteResult,\n} from \"./coordinator-legacy-team-completion.js\";\nimport type { RecipientReviewedIntentV1 } from \"./recipient-reviewed-intent.js\";\n\n/**\n * Normalize a caller-supplied invite expiry to a canonical UTC ISO-8601\n * (`...Z`) string. Invite lookups filter with a SQL `expires_at > ?` string\n * comparison against `new Date().toISOString()`, which is only correct when\n * stored values share that exact format — a `+00:00` offset or date-only value\n * would compare wrong. Shared by both coordinator store implementations.\n */\nexport function normalizeInviteExpiresAt(value: string): string {\n\tconst trimmed = value.trim();\n\tconst parsed = new Date(trimmed);\n\tif (!trimmed || Number.isNaN(parsed.getTime())) {\n\t\tthrow new Error(\"expiresAt must be a valid date.\");\n\t}\n\treturn parsed.toISOString();\n}\n\nexport interface CoordinatorGroup {\n\tgroup_id: string;\n\tdisplay_name: string | null;\n\tarchived_at: string | null;\n\tcreated_at: string;\n}\n\nexport interface CoordinatorEnrollment {\n\tgroup_id: string;\n\tdevice_id: string;\n\tpublic_key: string;\n\tfingerprint: string;\n\tidentity_id: string | null;\n\tdisplay_name: string | null;\n\tenabled: number;\n\tcreated_at: string;\n\t/** Authenticated presence expiry for this exact group/device enrollment. */\n\tpresence_expires_at?: string;\n\t/** Token-free capabilities from the same authenticated presence record. */\n\tpresence_capabilities?: Record<string, unknown>;\n\t/** The Identity this exact device key is bound to, when the coordinator holds one binding. */\n\townership_identity_id?: string;\n}\n\nexport interface CoordinatorInvite {\n\tinvite_id: string;\n\tgroup_id: string;\n\ttoken: string;\n\tpolicy: string;\n\texpires_at: string;\n\tcreated_at: string;\n\tcreated_by: string | null;\n\tteam_name_snapshot: string | null;\n\trevoked_at: string | null;\n\t/** Null/absent identifies a legacy enrollment invite, which grants no project intent by itself. */\n\toperation_id?: string | null;\n\t/** Digest reference only; the reviewed project set remains server-owned operation state. */\n\treviewed_project_set_digest?: string | null;\n\ttoken_digest?: string | null;\n\tinviter_actor_id?: string | null;\n\tinviter_display_name?: string | null;\n\tinviter_device_id?: string | null;\n\tpending_person_id?: string | null;\n\tproject_summaries_json?: string | null;\n\tproject_intent_json?: string | null;\n\tconsumed_at?: string | null;\n\tbound_device_id?: string | null;\n\tbound_public_key?: string | null;\n\tbound_fingerprint?: string | null;\n\trecipient_actor_id?: string | null;\n\trecipient_display_name?: string | null;\n\trecipient_device_display_name?: string | null;\n\ttrust_state?: string | null;\n\tbootstrap_grant_id?: string | null;\n\t/** Explicit lifecycle kind. Null is retained only for pre-migration rows. */\n\tinvite_kind?: CoordinatorInviteKind | null;\n\t/** Policy Team identifier for team-member invitations; never a coordinator group grant. */\n\tpolicy_team_id?: string | null;\n\t/** Identity fixed by an add-device invitation. */\n\ttarget_identity_id?: string | null;\n\t/** Opaque Identity minted by the coordinator for a Team-member invitation. */\n\tassigned_identity_id?: string | null;\n\t/** Digest of the server-owned preview reviewed before invitation creation. */\n\treviewed_preview_digest?: string | null;\n\t/** Canonical JSON for the inviter-reviewed access intent. */\n\treviewed_intent_json?: string | null;\n}\n\nexport type CoordinatorInviteKind =\n\t| \"legacy_enrollment\"\n\t| \"project_share\"\n\t| \"team_member\"\n\t| \"add_device\";\n\nexport type CoordinatorRecipientInviteKind = Extract<\n\tCoordinatorInviteKind,\n\t\"team_member\" | \"add_device\"\n>;\n\nconst COORDINATOR_ASSIGNED_IDENTITY_PATTERN = /^identity:[A-Za-z0-9_-]{18,24}$/u;\n\nexport function isCoordinatorAssignedIdentityId(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue === value.trim() &&\n\t\tCOORDINATOR_ASSIGNED_IDENTITY_PATTERN.test(value)\n\t);\n}\n\nexport function recipientInviteAuthoritativeIdentityId(value: {\n\tkind: CoordinatorRecipientInviteKind;\n\tassigned_identity_id?: unknown;\n\ttarget_identity_id?: unknown;\n}): string {\n\treturn String(\n\t\tvalue.kind === \"team_member\"\n\t\t\t? (value.assigned_identity_id ?? \"\")\n\t\t\t: (value.target_identity_id ?? \"\"),\n\t).trim();\n}\n\nexport interface CoordinatorProjectInviteSummary {\n\tdisplay_name: string;\n\texisting_memory_count: number;\n}\n\nexport interface CoordinatorProjectInviteAcceptance {\n\tstatus: \"accepted\" | \"existing\";\n\tinvite: CoordinatorInvite;\n\tenrollment: CoordinatorEnrollment;\n\tseed_enrollment: CoordinatorEnrollment | null;\n\tbootstrap_grant: CoordinatorBootstrapGrant | null;\n}\n\nexport type CoordinatorRecipientInviteInspection =\n\t| {\n\t\t\tkind: \"team_member\";\n\t\t\tinvite: CoordinatorInvite;\n\t\t\tpolicy_team_id: string;\n\t\t\tassigned_identity_id: string;\n\t\t\treviewed_preview_digest: string;\n\t\t\treviewed_intent?: RecipientReviewedIntentV1;\n\t\t\tbound: boolean;\n\t }\n\t| {\n\t\t\tkind: \"add_device\";\n\t\t\tinvite: CoordinatorInvite;\n\t\t\ttarget_identity_id: string;\n\t\t\treviewed_preview_digest: string;\n\t\t\treviewed_intent?: RecipientReviewedIntentV1;\n\t\t\tbound: boolean;\n\t };\n\nexport interface CoordinatorRecipientInviteAcceptance {\n\tstatus: \"accepted\" | \"existing\";\n\tinvite: CoordinatorInvite;\n\treviewed_intent?: RecipientReviewedIntentV1;\n\tbootstrap_grant?: CoordinatorBootstrapGrant | null;\n}\n\nexport interface CoordinatorJoinRequest {\n\trequest_id: string;\n\tgroup_id: string;\n\tdevice_id: string;\n\tpublic_key: string;\n\tfingerprint: string;\n\tdisplay_name: string | null;\n\ttoken: string;\n\tstatus: string;\n\tcreated_at: string;\n\treviewed_at: string | null;\n\treviewed_by: string | null;\n}\n\nexport interface CoordinatorJoinRequestReviewResult extends CoordinatorJoinRequest {\n\t_no_transition?: boolean;\n\tbootstrap_grant?: CoordinatorBootstrapGrant | null;\n}\n\nexport interface CoordinatorReviewJoinRequestBootstrapGrantInput {\n\tseedDeviceId: string;\n\texpiresAt: string;\n\tcreatedBy?: string | null;\n}\n\nexport interface CoordinatorPresenceRecord {\n\tgroup_id: string;\n\tdevice_id: string;\n\taddresses: string[];\n\texpires_at: string;\n}\n\nexport interface CoordinatorPeerRecord {\n\tdevice_id: string;\n\tpublic_key: string;\n\tfingerprint: string;\n\tdisplay_name: string | null;\n\taddresses: string[];\n\tlast_seen_at: string | null;\n\texpires_at: string | null;\n\tstale: boolean;\n\tcapabilities: Record<string, unknown>;\n}\n\nexport interface CoordinatorReciprocalApproval {\n\trequest_id: string;\n\tgroup_id: string;\n\trequesting_device_id: string;\n\trequested_device_id: string;\n\tstatus: string;\n\tcreated_at: string;\n\tresolved_at: string | null;\n}\n\nexport interface CoordinatorBootstrapGrant {\n\tgrant_id: string;\n\tgroup_id: string;\n\tseed_device_id: string;\n\tworker_device_id: string;\n\texpires_at: string;\n\tcreated_at: string;\n\tcreated_by: string | null;\n\trevoked_at: string | null;\n}\n\nexport interface CoordinatorBootstrapGrantAuthorizationInput {\n\tgrantId: string;\n\t/** Server-trusted time, not a caller-supplied expiry or clock. */\n\tnowMs: number;\n\texpectedSeed?: { groupId: string; deviceId: string; publicKey: string; fingerprint: string };\n}\n\nexport type CoordinatorBootstrapGrantAuthorizationError =\n\t| \"grant_not_found\"\n\t| \"seed_enrollment_not_found\"\n\t| \"worker_enrollment_not_found\"\n\t| \"grant_revoked\"\n\t| \"grant_expired\"\n\t| \"group_archived\"\n\t| \"device_revoked\"\n\t| \"bootstrap_authorization_unavailable\";\n\n/** A current read snapshot, not a permanent authorization capability. */\nexport type CoordinatorBootstrapGrantAuthorizationResult =\n\t| {\n\t\t\tkind: \"authorized\";\n\t\t\tauthorizationVersion: 1;\n\t\t\tgrant: CoordinatorBootstrapGrant;\n\t\t\tseedEnrollment: CoordinatorEnrollment;\n\t\t\tworkerEnrollment: CoordinatorEnrollment;\n\t }\n\t| { kind: \"rejected\"; error: CoordinatorBootstrapGrantAuthorizationError };\n\nexport interface CoordinatorScope {\n\tscope_id: string;\n\tlabel: string;\n\tkind: string;\n\tauthority_type: string;\n\tcoordinator_id: string | null;\n\tgroup_id: string | null;\n\tmanifest_issuer_device_id: string | null;\n\tmembership_epoch: number;\n\tmanifest_hash: string | null;\n\tstatus: string;\n\tcreated_at: string;\n\tupdated_at: string;\n}\n\nexport interface CoordinatorScopeMembership {\n\tscope_id: string;\n\tdevice_id: string;\n\trole: string;\n\tstatus: string;\n\tmembership_epoch: number;\n\tcoordinator_id: string | null;\n\tgroup_id: string | null;\n\tmanifest_issuer_device_id: string | null;\n\tmanifest_hash: string | null;\n\tsigned_manifest_json: string | null;\n\tupdated_at: string;\n}\n\nexport type CoordinatorScopeMembershipAuditAction = \"grant\" | \"revoke\";\n\nexport interface CoordinatorScopeAuthorizationInput {\n\tgroupId: string;\n\tscopeId: string;\n}\n\n/** Current storage snapshot only; neither account-session proof nor a permanent permission. */\nexport type CoordinatorScopeAuthorizationResult =\n\t| {\n\t\t\tkind: \"authorized\";\n\t\t\tauthorizationVersion: 1;\n\t\t\tscope: CoordinatorScope;\n\t\t\tmembers: Array<{\n\t\t\t\tmembership: CoordinatorScopeMembership;\n\t\t\t\tenrollment: CoordinatorEnrollment;\n\t\t\t\tkeyId: string;\n\t\t\t}>;\n\t }\n\t| {\n\t\t\tkind: \"rejected\";\n\t\t\terror:\n\t\t\t\t| \"scope_not_found\"\n\t\t\t\t| \"scope_inactive\"\n\t\t\t\t| \"scope_source_mismatch\"\n\t\t\t\t| \"group_archived\"\n\t\t\t\t| \"scope_authorization_unavailable\";\n\t };\n\nexport interface CoordinatorScopeMembershipAuditEvent {\n\tevent_id: number;\n\teffect_id: string | null;\n\taction: CoordinatorScopeMembershipAuditAction;\n\tscope_id: string;\n\tdevice_id: string;\n\trole: string | null;\n\tstatus: string;\n\tmembership_epoch: number;\n\tprevious_role: string | null;\n\tprevious_status: string | null;\n\tprevious_membership_epoch: number | null;\n\tcoordinator_id: string | null;\n\tgroup_id: string | null;\n\tactor_type: string | null;\n\tactor_id: string | null;\n\tmanifest_hash: string | null;\n\tcreated_at: string;\n}\n\nexport interface CoordinatorEnrollDeviceInput {\n\tdeviceId: string;\n\tfingerprint: string;\n\tpublicKey: string;\n\tdisplayName?: string | null;\n\t/** Null or omitted means the enrollment has no authoritative issuance binding. */\n\tidentityId?: string | null;\n}\n\nexport interface CoordinatorCreateInviteInput {\n\tgroupId: string;\n\tpolicy: string;\n\texpiresAt: string;\n\tcreatedBy?: string | null;\n\toperationId?: string | null;\n\treviewedProjectSetDigest?: string | null;\n\tinviterActorId?: string | null;\n\tinviterDisplayName?: string | null;\n\tinviterDeviceId?: string | null;\n\tpendingPersonId?: string | null;\n\tprojectSummaries?: CoordinatorProjectInviteSummary[] | null;\n\tprojectIntent?: Array<CoordinatorProjectInviteSummary & { canonical_identity: string }> | null;\n\tinviteKind?: CoordinatorInviteKind | null;\n\tpolicyTeamId?: string | null;\n\ttargetIdentityId?: string | null;\n\treviewedPreviewDigest?: string | null;\n\treviewedIntent?: unknown;\n}\n\nexport interface CoordinatorConsumeProjectInviteInput {\n\ttoken: string;\n\toperationId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n\trecipientActorId: string;\n\trecipientDisplayName: string;\n\tdeviceDisplayName: string;\n\t/** Runtime-authoritative timestamp used for expiry, binding, and grant creation. */\n\tnow: string;\n}\n\nexport interface CoordinatorInspectRecipientInviteInput {\n\ttoken: string;\n\tnow: string;\n}\n\nexport interface CoordinatorConsumeRecipientInviteInput {\n\t/** Internal server-config namespace only; never accepted from invite HTTP JSON. */\n\tcoordinatorId?: string;\n\ttoken: string;\n\tinviteKind: CoordinatorRecipientInviteKind;\n\tidentityId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n\trecipientDisplayName?: string | null;\n\tdeviceDisplayName?: string | null;\n\t/** Runtime-authoritative timestamp used for expiry and binding. */\n\tnow: string;\n}\n\nexport interface CoordinatorCreateJoinRequestInput {\n\tgroupId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n\tdisplayName?: string | null;\n\ttoken: string;\n}\n\nexport interface CoordinatorReviewJoinRequestInput {\n\trequestId: string;\n\tapproved: boolean;\n\treviewedBy?: string | null;\n\tbootstrapGrant?: CoordinatorReviewJoinRequestBootstrapGrantInput | null;\n}\n\nexport interface CoordinatorUpsertPresenceInput {\n\tgroupId: string;\n\tdeviceId: string;\n\taddresses: string[];\n\tttlS: number;\n\tcapabilities?: Record<string, unknown> | null;\n}\n\nexport interface CoordinatorCreateReciprocalApprovalInput {\n\tgroupId: string;\n\trequestingDeviceId: string;\n\trequestedDeviceId: string;\n\t/** Complete only this exact pending request in the reverse direction. */\n\texpectedIncomingRequestId?: string;\n}\n\nexport const RECIPROCAL_APPROVAL_REQUEST_CHANGED = \"reciprocal_approval_request_changed\" as const;\n\nexport class CoordinatorReciprocalApprovalRequestChangedError extends Error {\n\treadonly code = RECIPROCAL_APPROVAL_REQUEST_CHANGED;\n\n\tconstructor() {\n\t\tsuper(RECIPROCAL_APPROVAL_REQUEST_CHANGED);\n\t\tthis.name = \"CoordinatorReciprocalApprovalRequestChangedError\";\n\t}\n}\n\nexport interface CoordinatorCreateBootstrapGrantInput {\n\tgroupId: string;\n\tseedDeviceId: string;\n\tworkerDeviceId: string;\n\texpiresAt: string;\n\tcreatedBy?: string | null;\n}\n\nexport interface CoordinatorCreateScopeInput {\n\tscopeId: string;\n\tlabel: string;\n\tkind?: string | null;\n\tauthorityType?: string | null;\n\tcoordinatorId?: string | null;\n\tgroupId?: string | null;\n\tmanifestIssuerDeviceId?: string | null;\n\tmembershipEpoch?: number | null;\n\tmanifestHash?: string | null;\n\tstatus?: string | null;\n}\n\nexport interface CoordinatorUpdateScopeInput {\n\t/** Internal sharing-domain identifier (`scope_id`). */\n\tscopeId: string;\n\t/** User-facing Sharing domain label. Omitted fields keep existing metadata. */\n\tlabel?: string | null;\n\tkind?: string | null;\n\tauthorityType?: string | null;\n\tcoordinatorId?: string | null;\n\tgroupId?: string | null;\n\tmanifestIssuerDeviceId?: string | null;\n\tmembershipEpoch?: number | null;\n\tmanifestHash?: string | null;\n\tstatus?: string | null;\n}\n\nexport interface CoordinatorListScopesInput {\n\tcoordinatorId?: string | null;\n\tgroupId?: string | null;\n\tstatus?: string | null;\n\tincludeInactive?: boolean;\n}\n\nexport interface CoordinatorGrantScopeMembershipInput {\n\teffectId: string;\n\tscopeId: string;\n\tdeviceId: string;\n\trole?: string | null;\n\tmembershipEpoch?: number | null;\n\t/** Optional assertion; persisted authority is derived from the referenced scope. */\n\tcoordinatorId?: string | null;\n\t/** Optional assertion; persisted authority is derived from the referenced scope. */\n\tgroupId?: string | null;\n\tmanifestIssuerDeviceId?: string | null;\n\tmanifestHash?: string | null;\n\tsignedManifestJson?: string | null;\n\tactorType?: string | null;\n\tactorId?: string | null;\n}\n\nexport interface CoordinatorRevokeScopeMembershipInput {\n\teffectId: string;\n\tscopeId: string;\n\tdeviceId: string;\n\t/** Optional assertion; persisted authority is derived from the referenced scope. */\n\tgroupId?: string | null;\n\tmembershipEpoch?: number | null;\n\tmanifestHash?: string | null;\n\tsignedManifestJson?: string | null;\n\tactorType?: string | null;\n\tactorId?: string | null;\n}\n\nexport interface CoordinatorListScopeMembershipAuditInput {\n\tscopeId: string;\n\tdeviceId?: string | null;\n\tlimit?: number | null;\n}\n\nexport interface CoordinatorListReciprocalApprovalsInput {\n\tgroupId: string;\n\tdeviceId: string;\n\tdirection: \"incoming\" | \"outgoing\";\n\tstatus?: string;\n}\n\nexport interface CoordinatorStore\n\textends CoordinatorDeviceRevocationStore,\n\t\tPartial<CoordinatorAuthSchemaStore> {\n\tclose(): Promise<void>;\n\tcreateGroup(groupId: string, displayName?: string | null): Promise<void>;\n\tgetGroup(groupId: string): Promise<CoordinatorGroup | null>;\n\tlistGroups(includeArchived?: boolean): Promise<CoordinatorGroup[]>;\n\trenameGroup(groupId: string, displayName: string): Promise<boolean>;\n\tarchiveGroup(groupId: string, archivedAt?: string): Promise<boolean>;\n\tunarchiveGroup(groupId: string): Promise<boolean>;\n\tenrollDevice(groupId: string, opts: CoordinatorEnrollDeviceInput): Promise<void>;\n\tlistEnrolledDevices(groupId: string, includeDisabled?: boolean): Promise<CoordinatorEnrollment[]>;\n\tgetEnrollment(\n\t\tgroupId: string,\n\t\tdeviceId: string,\n\t\tincludeDisabled?: boolean,\n\t): Promise<CoordinatorEnrollment | null>;\n\trenameDevice(groupId: string, deviceId: string, displayName: string): Promise<boolean>;\n\tsetDeviceEnabled(groupId: string, deviceId: string, enabled: boolean): Promise<boolean>;\n\tremoveDevice(groupId: string, deviceId: string): Promise<boolean>;\n\trecordNonce(deviceId: string, nonce: string, createdAt: string): Promise<boolean>;\n\tcleanupNonces(cutoff: string): Promise<void>;\n\tcreateInvite(opts: CoordinatorCreateInviteInput): Promise<CoordinatorInvite>;\n\tgetInviteByOperationId(groupId: string, operationId: string): Promise<CoordinatorInvite | null>;\n\tgetInviteByToken(token: string): Promise<CoordinatorInvite | null>;\n\tgetInviteByTokenForInspection(token: string): Promise<CoordinatorInvite | null>;\n\tinspectRecipientInvite(\n\t\topts: CoordinatorInspectRecipientInviteInput,\n\t): Promise<CoordinatorRecipientInviteInspection | null>;\n\tconsumeProjectInvite(\n\t\topts: CoordinatorConsumeProjectInviteInput,\n\t): Promise<CoordinatorProjectInviteAcceptance>;\n\tconsumeRecipientInvite(\n\t\topts: CoordinatorConsumeRecipientInviteInput,\n\t): Promise<CoordinatorRecipientInviteAcceptance>;\n\tlistInvites(groupId: string): Promise<CoordinatorInvite[]>;\n\tcreateJoinRequest(opts: CoordinatorCreateJoinRequestInput): Promise<CoordinatorJoinRequest>;\n\tlistJoinRequests(groupId: string, status?: string): Promise<CoordinatorJoinRequest[]>;\n\treviewJoinRequest(\n\t\topts: CoordinatorReviewJoinRequestInput,\n\t): Promise<CoordinatorJoinRequestReviewResult | null>;\n\tcreateReciprocalApproval(\n\t\topts: CoordinatorCreateReciprocalApprovalInput,\n\t): Promise<CoordinatorReciprocalApproval>;\n\tcreateBootstrapGrant(\n\t\topts: CoordinatorCreateBootstrapGrantInput,\n\t): Promise<CoordinatorBootstrapGrant>;\n\tcreateScope(opts: CoordinatorCreateScopeInput): Promise<CoordinatorScope>;\n\tupdateScope(opts: CoordinatorUpdateScopeInput): Promise<CoordinatorScope | null>;\n\tlistScopes(opts?: CoordinatorListScopesInput): Promise<CoordinatorScope[]>;\n\tgetScopeAuthorization(\n\t\tinput: CoordinatorScopeAuthorizationInput,\n\t): Promise<CoordinatorScopeAuthorizationResult>;\n\tgrantScopeMembership(\n\t\topts: CoordinatorGrantScopeMembershipInput,\n\t): Promise<CoordinatorScopeMembership>;\n\trevokeScopeMembership(opts: CoordinatorRevokeScopeMembershipInput): Promise<boolean>;\n\tlistScopeMemberships(\n\t\tscopeId: string,\n\t\tincludeRevoked?: boolean,\n\t): Promise<CoordinatorScopeMembership[]>;\n\t/**\n\t * List one device's memberships across every scope, ordered by scope_id.\n\t *\n\t * Answers \"which scopes is this device in\" with a single indexed lookup,\n\t * rather than reading every member of every scope one scope at a time.\n\t */\n\tlistDeviceScopeMemberships(\n\t\tdeviceId: string,\n\t\tincludeRevoked?: boolean,\n\t): Promise<CoordinatorScopeMembership[]>;\n\tlistScopeMembershipAuditEvents(\n\t\topts: CoordinatorListScopeMembershipAuditInput,\n\t): Promise<CoordinatorScopeMembershipAuditEvent[]>;\n\tgetBootstrapGrant(grantId: string): Promise<CoordinatorBootstrapGrant | null>;\n\tgetBootstrapGrantAuthorization(\n\t\tinput: CoordinatorBootstrapGrantAuthorizationInput,\n\t): Promise<CoordinatorBootstrapGrantAuthorizationResult>;\n\tlistBootstrapGrants(groupId: string): Promise<CoordinatorBootstrapGrant[]>;\n\trevokeBootstrapGrant(grantId: string, revokedAt?: string): Promise<boolean>;\n\tlistReciprocalApprovals(\n\t\topts: CoordinatorListReciprocalApprovalsInput,\n\t): Promise<CoordinatorReciprocalApproval[]>;\n\tcreateLegacyTeamCompletion(\n\t\tgroupId: string,\n\t\tmanifest: CoordinatorLegacyTeamCompletionManifestV1,\n\t): Promise<CoordinatorLegacyTeamCompletionWriteResult>;\n\tgetLegacyTeamCompletion(\n\t\tgroupId: string,\n\t\tcandidateRef: string,\n\t): Promise<CoordinatorLegacyTeamCompletionManifestV1 | null>;\n\tlistLegacyTeamCompletions(groupIds: string[]): Promise<CoordinatorLegacyTeamCompletionRecord[]>;\n\tupsertPresence(opts: CoordinatorUpsertPresenceInput): Promise<CoordinatorPresenceRecord>;\n\tlistGroupPeers(groupId: string, requestingDeviceId: string): Promise<CoordinatorPeerRecord[]>;\n}\n\nexport interface CoordinatorBootstrapGrantVerification {\n\tauthorization_version: 1;\n\tgrant: CoordinatorBootstrapGrant;\n\tseed_enrollment: CoordinatorEnrollment;\n\tworker_enrollment: CoordinatorEnrollment;\n}\n","const MAX_IDENTITY_DISPLAY_LENGTH = 120;\n// Keep machine-shaped cases synchronized with ui/src/lib/identity-presentation.ts.\nconst UUID_NAME = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu;\nconst MACHINE_PREFIX_NAME = /^(?:actor|device|identity|local):\\S+$/iu;\nconst MACHINE_SLUG_NAME = /^(?:actor|device|identity)[_-][a-z0-9][a-z0-9._:-]{4,}$/iu;\nconst PENDING_PERSON_NAME = /^pending[_-]\\S+$/iu;\nconst HEX_HOSTNAME = /^[a-f0-9]{12,64}$/iu;\nconst HOSTNAME_NAME =\n\t/^(?=.{1,253}$)(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.){2,}[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?|[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.local)$/iu;\n\nexport interface ProjectInviteSummary {\n\tdisplay_name: string;\n\texisting_memory_count: number;\n}\n\nexport function normalizeIdentityDisplayName(value: string, field: string): string {\n\tif ([...value].some((character) => /[\\p{Cc}\\p{Cf}]/u.test(character))) {\n\t\tthrow new Error(`${field}_invalid`);\n\t}\n\tconst normalized = value.replace(/\\s+/gu, \" \").trim();\n\tif (!normalized) throw new Error(`${field}_required`);\n\tif ([...normalized].length > MAX_IDENTITY_DISPLAY_LENGTH) {\n\t\tthrow new Error(`${field}_too_long`);\n\t}\n\treturn normalized;\n}\n\nexport function isHumanPresentationName(value: unknown): boolean {\n\tif (typeof value !== \"string\") return false;\n\tlet normalized: string;\n\ttry {\n\t\tnormalized = normalizeIdentityDisplayName(value, \"display_name\");\n\t} catch {\n\t\treturn false;\n\t}\n\treturn ![\n\t\tUUID_NAME,\n\t\tMACHINE_PREFIX_NAME,\n\t\tMACHINE_SLUG_NAME,\n\t\tPENDING_PERSON_NAME,\n\t\tHEX_HOSTNAME,\n\t].some((pattern) => pattern.test(normalized));\n}\n\nexport function normalizeHumanPresentationName(value: string, field: string): string {\n\tconst normalized = normalizeIdentityDisplayName(value, field);\n\tif (!isHumanPresentationName(normalized)) throw new Error(`${field}_invalid`);\n\treturn normalized;\n}\n\nexport function normalizeDeviceDisplayName(value: string, field: string): string {\n\tconst normalized = normalizeIdentityDisplayName(value, field);\n\tif (!HOSTNAME_NAME.test(normalized) && !isHumanPresentationName(normalized)) {\n\t\tthrow new Error(`${field}_invalid`);\n\t}\n\treturn normalized;\n}\n\nexport function normalizeDeviceNameHint(value: string | null | undefined): string | null {\n\tconst candidate = String(value ?? \"\").trim();\n\tconst raw = candidate.replace(/\\.local$/iu, \"\");\n\tif (!raw) return null;\n\tconst normalized = HOSTNAME_NAME.test(candidate) ? raw : raw.replace(/[-_]+/gu, \" \");\n\treturn normalizeDeviceDisplayName(normalized, \"device_display_name\");\n}\n\nexport function friendlyDeviceName(input: {\n\texplicitName?: string | null;\n\tosName?: string | null;\n\tcoordinatorName?: string | null;\n\tfallbackSeed?: string | null;\n}): string {\n\tfor (const candidate of [input.explicitName, input.osName, input.coordinatorName]) {\n\t\tconst candidateText = String(candidate ?? \"\").trim();\n\t\tconst raw = candidateText.replace(/\\.local$/iu, \"\");\n\t\t// Classify before separator normalization so UUIDs and machine slugs cannot\n\t\t// be disguised as human labels by replacing hyphens or underscores.\n\t\tif (HOSTNAME_NAME.test(candidateText)) {\n\t\t\ttry {\n\t\t\t\tconst normalized = normalizeDeviceNameHint(candidateText);\n\t\t\t\tif (normalized) return normalized;\n\t\t\t} catch {\n\t\t\t\t// Unusable automatic hints must degrade to the generated fallback.\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (!raw || !isHumanPresentationName(raw)) continue;\n\t\ttry {\n\t\t\tconst normalized = normalizeDeviceNameHint(candidate);\n\t\t\tif (normalized && isHumanPresentationName(normalized)) return normalized;\n\t\t} catch {\n\t\t\t// Unusable automatic hints must degrade to the generated fallback.\n\t\t}\n\t}\n\tconst seed = String(input.fallbackSeed ?? \"\")\n\t\t.replace(/[^a-z0-9]/giu, \"\")\n\t\t.slice(0, 6);\n\treturn seed ? `Codemem device ${seed}` : \"Codemem device\";\n}\n\nexport function normalizeProjectInviteSummaries(value: unknown): ProjectInviteSummary[] {\n\tif (!Array.isArray(value) || value.length === 0 || value.length > 100) {\n\t\tthrow new Error(\"project_summaries_invalid\");\n\t}\n\treturn value.map((item) => {\n\t\tif (!item || typeof item !== \"object\" || Array.isArray(item)) {\n\t\t\tthrow new Error(\"project_summaries_invalid\");\n\t\t}\n\t\tconst record = item as Record<string, unknown>;\n\t\tif (\n\t\t\t!Number.isSafeInteger(record.existing_memory_count) ||\n\t\t\tNumber(record.existing_memory_count) < 0\n\t\t) {\n\t\t\tthrow new Error(\"project_summaries_invalid\");\n\t\t}\n\t\treturn {\n\t\t\tdisplay_name: normalizeIdentityDisplayName(String(record.display_name ?? \"\"), \"project_name\"),\n\t\t\texisting_memory_count: Number(record.existing_memory_count),\n\t\t};\n\t});\n}\n","import { normalizeIdentityDisplayName } from \"./project-invite-identity.js\";\n\nexport const RECIPIENT_REVIEWED_INTENT_VERSION = 1 as const;\n\nexport type RecipientReviewedIntentProjectSourceV1 =\n\t| { kind: \"direct\" }\n\t| { kind: \"team\"; teamId: string; displayName: string };\n\nexport interface RecipientReviewedIntentProjectV1 {\n\tcanonicalProjectIdentity: string;\n\tdisplayName: string;\n\texistingMemoryCount: number;\n\tfutureMemoriesShared: true;\n\tsources: RecipientReviewedIntentProjectSourceV1[];\n}\n\nexport interface RecipientReviewedIntentExcludedProjectV1 {\n\tcanonicalProjectIdentity: string;\n\tdisplayName: string;\n\texistingMemoryCount: number;\n}\n\ninterface RecipientReviewedIntentBaseV1 {\n\tversion: 1;\n\tprojects: RecipientReviewedIntentProjectV1[];\n\texcludedProjects: RecipientReviewedIntentExcludedProjectV1[];\n}\n\nexport type RecipientReviewedIntentV1 =\n\t| (RecipientReviewedIntentBaseV1 & {\n\t\t\tjourney: \"team\";\n\t\t\tteam: { teamId: string; displayName: string; futureProjectsInherit: true };\n\t })\n\t| (RecipientReviewedIntentBaseV1 & {\n\t\t\tjourney: \"add_device\";\n\t\t\ttargetIdentity: { identityId: string; displayName: string };\n\t });\n\nexport type RecipientReviewedIntentTargetV1 =\n\t| { kind: \"team_member\"; policyTeamId: string }\n\t| { kind: \"add_device\"; targetIdentityId: string };\n\nexport class RecipientReviewedIntentError extends Error {\n\treadonly code: \"recipient_reviewed_intent_invalid\" | \"recipient_invite_intent_mismatch\";\n\n\tconstructor(code: RecipientReviewedIntentError[\"code\"]) {\n\t\tsuper(code);\n\t\tthis.name = \"RecipientReviewedIntentError\";\n\t\tthis.code = code;\n\t}\n}\n\nconst CONTROL_CHARACTER = /[\\p{Cc}\\p{Cf}]/u;\nconst MAX_PROJECTS = 100;\nconst MAX_CANONICAL_BYTES = 64 * 1024;\n\nfunction invalid(): never {\n\tthrow new RecipientReviewedIntentError(\"recipient_reviewed_intent_invalid\");\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) invalid();\n\treturn value as Record<string, unknown>;\n}\n\nfunction assertKeys(value: Record<string, unknown>, keys: readonly string[]): void {\n\tif (Object.keys(value).some((key) => !keys.includes(key))) invalid();\n}\n\nfunction strictText(value: unknown, maxLength: number): string {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\t!value ||\n\t\tvalue !== value.trim() ||\n\t\tvalue.length > maxLength ||\n\t\tCONTROL_CHARACTER.test(value)\n\t) {\n\t\tinvalid();\n\t}\n\treturn value;\n}\n\nfunction displayName(value: unknown): string {\n\tif (typeof value !== \"string\" || CONTROL_CHARACTER.test(value)) invalid();\n\tconst normalized = value.trim().replace(/\\s+/gu, \" \");\n\tif (!normalized || normalized.length > 256) invalid();\n\treturn normalized;\n}\n\nfunction identityDisplayName(value: unknown): string {\n\tif (typeof value !== \"string\") invalid();\n\ttry {\n\t\treturn normalizeIdentityDisplayName(value, \"identity_display_name\");\n\t} catch {\n\t\treturn invalid();\n\t}\n}\n\nfunction memoryCount(value: unknown): number {\n\tif (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 0) invalid();\n\treturn value;\n}\n\nfunction compareText(left: string, right: string): number {\n\treturn left < right ? -1 : left > right ? 1 : 0;\n}\n\nfunction sourceKey(source: RecipientReviewedIntentProjectSourceV1): string {\n\treturn source.kind === \"direct\" ? \"direct\" : `team\\u0000${source.teamId}`;\n}\n\nfunction normalizeSource(value: unknown): RecipientReviewedIntentProjectSourceV1 {\n\tconst input = record(value);\n\tif (input.kind === \"direct\") {\n\t\tassertKeys(input, [\"kind\"]);\n\t\treturn { kind: \"direct\" };\n\t}\n\tif (input.kind !== \"team\") invalid();\n\tassertKeys(input, [\"kind\", \"teamId\", \"displayName\"]);\n\treturn {\n\t\tkind: \"team\",\n\t\tteamId: strictText(input.teamId, 256),\n\t\tdisplayName: displayName(input.displayName),\n\t};\n}\n\nfunction normalizeProject(value: unknown): RecipientReviewedIntentProjectV1 {\n\tconst input = record(value);\n\tassertKeys(input, [\n\t\t\"canonicalProjectIdentity\",\n\t\t\"displayName\",\n\t\t\"existingMemoryCount\",\n\t\t\"futureMemoriesShared\",\n\t\t\"sources\",\n\t]);\n\tif (\n\t\tinput.futureMemoriesShared !== true ||\n\t\t!Array.isArray(input.sources) ||\n\t\t!input.sources.length\n\t) {\n\t\tinvalid();\n\t}\n\tconst sources = input.sources\n\t\t.map(normalizeSource)\n\t\t.toSorted((left, right) => compareText(sourceKey(left), sourceKey(right)));\n\tif (new Set(sources.map(sourceKey)).size !== sources.length) invalid();\n\treturn {\n\t\tcanonicalProjectIdentity: strictText(input.canonicalProjectIdentity, 512),\n\t\tdisplayName: displayName(input.displayName),\n\t\texistingMemoryCount: memoryCount(input.existingMemoryCount),\n\t\tfutureMemoriesShared: true,\n\t\tsources,\n\t};\n}\n\nfunction normalizeExcludedProject(value: unknown): RecipientReviewedIntentExcludedProjectV1 {\n\tconst input = record(value);\n\tassertKeys(input, [\"canonicalProjectIdentity\", \"displayName\", \"existingMemoryCount\"]);\n\treturn {\n\t\tcanonicalProjectIdentity: strictText(input.canonicalProjectIdentity, 512),\n\t\tdisplayName: displayName(input.displayName),\n\t\texistingMemoryCount: memoryCount(input.existingMemoryCount),\n\t};\n}\n\nfunction normalizeProjectLists(\n\tinput: Record<string, unknown>,\n): Pick<RecipientReviewedIntentBaseV1, \"projects\" | \"excludedProjects\"> {\n\tif (\n\t\t!Array.isArray(input.projects) ||\n\t\t!Array.isArray(input.excludedProjects) ||\n\t\tinput.projects.length > MAX_PROJECTS\n\t) {\n\t\tinvalid();\n\t}\n\tconst projects = input.projects\n\t\t.map(normalizeProject)\n\t\t.toSorted((left, right) =>\n\t\t\tcompareText(left.canonicalProjectIdentity, right.canonicalProjectIdentity),\n\t\t);\n\tconst excludedProjects = input.excludedProjects\n\t\t.map(normalizeExcludedProject)\n\t\t.toSorted((left, right) =>\n\t\t\tcompareText(left.canonicalProjectIdentity, right.canonicalProjectIdentity),\n\t\t);\n\tconst includedIds = projects.map((project) => project.canonicalProjectIdentity);\n\tconst excludedIds = excludedProjects.map((project) => project.canonicalProjectIdentity);\n\tif (\n\t\tnew Set(includedIds).size !== includedIds.length ||\n\t\tnew Set(excludedIds).size !== excludedIds.length ||\n\t\texcludedIds.some((projectId) => includedIds.includes(projectId))\n\t) {\n\t\tinvalid();\n\t}\n\treturn { projects, excludedProjects };\n}\n\nfunction assertTarget(\n\tintent: RecipientReviewedIntentV1,\n\ttarget: RecipientReviewedIntentTargetV1,\n): void {\n\tconst matches =\n\t\t(intent.journey === \"team\" &&\n\t\t\ttarget.kind === \"team_member\" &&\n\t\t\tintent.team.teamId === target.policyTeamId) ||\n\t\t(intent.journey === \"add_device\" &&\n\t\t\ttarget.kind === \"add_device\" &&\n\t\t\tintent.targetIdentity.identityId === target.targetIdentityId);\n\tif (!matches) throw new RecipientReviewedIntentError(\"recipient_invite_intent_mismatch\");\n}\n\nexport function normalizeRecipientReviewedIntent(\n\tvalue: unknown,\n\ttarget?: RecipientReviewedIntentTargetV1,\n): RecipientReviewedIntentV1 {\n\tconst input = record(value);\n\tif (input.version !== RECIPIENT_REVIEWED_INTENT_VERSION) invalid();\n\tconst projectLists = normalizeProjectLists(input);\n\tlet intent: RecipientReviewedIntentV1;\n\tif (input.journey === \"team\") {\n\t\tassertKeys(input, [\"version\", \"journey\", \"team\", \"projects\", \"excludedProjects\"]);\n\t\tconst team = record(input.team);\n\t\tassertKeys(team, [\"teamId\", \"displayName\", \"futureProjectsInherit\"]);\n\t\tif (team.futureProjectsInherit !== true) invalid();\n\t\tintent = {\n\t\t\tversion: 1,\n\t\t\tjourney: \"team\",\n\t\t\tteam: {\n\t\t\t\tteamId: strictText(team.teamId, 256),\n\t\t\t\tdisplayName: displayName(team.displayName),\n\t\t\t\tfutureProjectsInherit: true,\n\t\t\t},\n\t\t\t...projectLists,\n\t\t};\n\t} else if (input.journey === \"add_device\") {\n\t\tassertKeys(input, [\"version\", \"journey\", \"targetIdentity\", \"projects\", \"excludedProjects\"]);\n\t\tconst identity = record(input.targetIdentity);\n\t\tassertKeys(identity, [\"identityId\", \"displayName\"]);\n\t\tintent = {\n\t\t\tversion: 1,\n\t\t\tjourney: \"add_device\",\n\t\t\ttargetIdentity: {\n\t\t\t\tidentityId: strictText(identity.identityId, 256),\n\t\t\t\tdisplayName: identityDisplayName(identity.displayName),\n\t\t\t},\n\t\t\t...projectLists,\n\t\t};\n\t} else {\n\t\tinvalid();\n\t}\n\tif (target) assertTarget(intent, target);\n\tif (new TextEncoder().encode(canonicalJson(intent)).byteLength > MAX_CANONICAL_BYTES) invalid();\n\treturn intent;\n}\n\nfunction canonicalJson(value: unknown): string {\n\tif (Array.isArray(value)) return `[${value.map(canonicalJson).join(\",\")}]`;\n\tif (value && typeof value === \"object\") {\n\t\treturn `{${Object.entries(value as Record<string, unknown>)\n\t\t\t.toSorted(([left], [right]) => compareText(left, right))\n\t\t\t.map(([key, child]) => `${JSON.stringify(key)}:${canonicalJson(child)}`)\n\t\t\t.join(\",\")}}`;\n\t}\n\treturn JSON.stringify(value) ?? \"null\";\n}\n\nexport function canonicalRecipientReviewedIntentJson(\n\tvalue: unknown,\n\ttarget?: RecipientReviewedIntentTargetV1,\n): string {\n\treturn canonicalJson(normalizeRecipientReviewedIntent(value, target));\n}\n\nexport async function recipientReviewedIntentDigest(\n\tvalue: unknown,\n\ttarget?: RecipientReviewedIntentTargetV1,\n): Promise<string> {\n\tconst canonical = canonicalRecipientReviewedIntentJson(value, target);\n\tconst bytes = new TextEncoder().encode(`recipient-reviewed-intent-v1\\n${canonical}`);\n\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", bytes);\n\treturn Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nexport async function verifyRecipientReviewedIntent(\n\tvalue: unknown,\n\toptions: { target: RecipientReviewedIntentTargetV1; digest: string },\n): Promise<RecipientReviewedIntentV1> {\n\tconst normalized = normalizeRecipientReviewedIntent(value, options.target);\n\tif ((await recipientReviewedIntentDigest(normalized)) !== options.digest) {\n\t\tthrow new RecipientReviewedIntentError(\"recipient_invite_intent_mismatch\");\n\t}\n\treturn normalized;\n}\n\nexport async function parseStoredRecipientReviewedIntent(\n\tjson: string | null | undefined,\n\toptions: { target: RecipientReviewedIntentTargetV1; digest: string },\n): Promise<RecipientReviewedIntentV1> {\n\tif (!json) throw new Error(\"recipient_invite_review_unavailable\");\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(json);\n\t} catch {\n\t\tthrow new Error(\"recipient_invite_review_unavailable\");\n\t}\n\ttry {\n\t\tconst normalized = normalizeRecipientReviewedIntent(parsed, options.target);\n\t\tif (canonicalJson(normalized) !== json) {\n\t\t\tthrow new Error(\"recipient_invite_review_unavailable\");\n\t\t}\n\t\treturn await verifyRecipientReviewedIntent(normalized, options);\n\t} catch (error) {\n\t\tif (\n\t\t\terror instanceof RecipientReviewedIntentError &&\n\t\t\terror.code === \"recipient_invite_intent_mismatch\"\n\t\t) {\n\t\t\tthrow error;\n\t\t}\n\t\tif (error instanceof Error && error.message === \"recipient_invite_review_unavailable\") {\n\t\t\tthrow error;\n\t\t}\n\t\tthrow new Error(\"recipient_invite_review_unavailable\");\n\t}\n}\n","import { CoordinatorMembershipError } from \"./coordinator-membership-effects.js\";\nimport type {\n\tCoordinatorCreateBootstrapGrantInput,\n\tCoordinatorCreateInviteInput,\n\tCoordinatorCreateScopeInput,\n\tCoordinatorGrantScopeMembershipInput,\n\tCoordinatorInvite,\n\tCoordinatorInviteKind,\n\tCoordinatorRecipientInviteInspection,\n\tCoordinatorReviewJoinRequestBootstrapGrantInput,\n\tCoordinatorScope,\n\tCoordinatorScopeMembership,\n\tCoordinatorUpdateScopeInput,\n} from \"./coordinator-store-contract.js\";\nimport { isCoordinatorAssignedIdentityId } from \"./coordinator-store-contract.js\";\nimport {\n\tcanonicalRecipientReviewedIntentJson,\n\tparseStoredRecipientReviewedIntent,\n\ttype RecipientReviewedIntentTargetV1,\n\tverifyRecipientReviewedIntent,\n} from \"./recipient-reviewed-intent.js\";\n\nfunction normalizeAddress(address: string): string {\n\tconst value = address.trim();\n\tif (!value) return \"\";\n\tconst withScheme = value.includes(\"://\") ? value : `http://${value}`;\n\ttry {\n\t\tconst url = new URL(withScheme);\n\t\tif (!url.hostname) return \"\";\n\t\tif (url.port && (Number(url.port) <= 0 || Number(url.port) > 65535)) return \"\";\n\t\treturn url.origin + url.pathname.replace(/\\/+$/, \"\");\n\t} catch {\n\t\treturn \"\";\n\t}\n}\n\nfunction addressDedupeKey(address: string): string {\n\tif (!address) return \"\";\n\ttry {\n\t\tconst parsed = new URL(address);\n\t\tconst host = parsed.hostname.toLowerCase();\n\t\tif (\n\t\t\t(parsed.protocol === \"http:\" || parsed.protocol === \"\") &&\n\t\t\thost &&\n\t\t\tparsed.port &&\n\t\t\tparsed.pathname === \"/\"\n\t\t) {\n\t\t\treturn `${host}:${parsed.port}`;\n\t\t}\n\t} catch {}\n\treturn address;\n}\n\nexport function mergeCoordinatorAddresses(existing: string[], candidates: string[]): string[] {\n\tconst normalized: string[] = [];\n\tconst seen = new Set<string>();\n\tfor (const address of [...existing, ...candidates]) {\n\t\tconst cleaned = normalizeAddress(address);\n\t\tconst key = addressDedupeKey(cleaned);\n\t\tif (!cleaned || seen.has(key)) continue;\n\t\tseen.add(key);\n\t\tnormalized.push(cleaned);\n\t}\n\treturn normalized;\n}\n\nexport function normalizeCoordinatorBootstrapGrantRequest(\n\tinput: CoordinatorReviewJoinRequestBootstrapGrantInput | null | undefined,\n): CoordinatorCreateBootstrapGrantInput | null {\n\tif (!input) return null;\n\tconst seedDeviceId = String(input.seedDeviceId ?? \"\").trim();\n\tconst expiresAt = String(input.expiresAt ?? \"\").trim();\n\tconst createdBy = String(input.createdBy ?? \"\").trim() || null;\n\tif (!seedDeviceId || !expiresAt) {\n\t\tthrow new Error(\"bootstrapGrant.seedDeviceId and expiresAt are required.\");\n\t}\n\treturn {\n\t\tgroupId: \"\",\n\t\tseedDeviceId,\n\t\tworkerDeviceId: \"\",\n\t\texpiresAt,\n\t\tcreatedBy,\n\t};\n}\n\nexport function normalizeCoordinatorBootstrapGrantInput(\n\topts: CoordinatorCreateBootstrapGrantInput,\n): CoordinatorCreateBootstrapGrantInput {\n\tconst groupId = String(opts.groupId ?? \"\").trim();\n\tconst seedDeviceId = String(opts.seedDeviceId ?? \"\").trim();\n\tconst workerDeviceId = String(opts.workerDeviceId ?? \"\").trim();\n\tconst expiresAt = String(opts.expiresAt ?? \"\").trim();\n\tconst createdBy = String(opts.createdBy ?? \"\").trim() || null;\n\tif (!groupId || !seedDeviceId || !workerDeviceId || !expiresAt) {\n\t\tthrow new Error(\"groupId, seedDeviceId, workerDeviceId, and expiresAt are required.\");\n\t}\n\treturn { groupId, seedDeviceId, workerDeviceId, expiresAt, createdBy };\n}\n\nexport function clean(value: string | null | undefined): string | null {\n\tconst trimmed = value?.trim();\n\treturn trimmed ? trimmed : null;\n}\n\ninterface NormalizedInviteMetadata {\n\tinviteKind: CoordinatorInviteKind;\n\tpolicyTeamId: string | null;\n\ttargetIdentityId: string | null;\n\treviewedPreviewDigest: string | null;\n}\n\nconst RECIPIENT_INVITE_KINDS = new Set<CoordinatorInviteKind>([\n\t\"legacy_enrollment\",\n\t\"project_share\",\n\t\"team_member\",\n\t\"add_device\",\n]);\n\nfunction validateInviteMetadataIdentifiers(metadata: NormalizedInviteMetadata): void {\n\tif (!RECIPIENT_INVITE_KINDS.has(metadata.inviteKind)) {\n\t\tthrow new Error(\"inviteKind is invalid.\");\n\t}\n\tif (\n\t\t[metadata.policyTeamId, metadata.targetIdentityId]\n\t\t\t.filter((value): value is string => Boolean(value))\n\t\t\t.some((value) => value.length > 256 || /[\\p{Cc}\\p{Cf}]/u.test(value))\n\t) {\n\t\tthrow new Error(\"recipient invite identifier is invalid.\");\n\t}\n\tif (metadata.reviewedPreviewDigest && !/^[a-f0-9]{64}$/u.test(metadata.reviewedPreviewDigest)) {\n\t\tthrow new Error(\"reviewedPreviewDigest must be a SHA-256 digest.\");\n\t}\n}\n\ntype InviteMetadataValidator = (\n\toperationId: string | null,\n\tmetadata: NormalizedInviteMetadata,\n) => void;\n\nconst INVITE_METADATA_VALIDATORS: Record<CoordinatorInviteKind, InviteMetadataValidator> = {\n\tproject_share(operationId, metadata) {\n\t\tif (!operationId) throw new Error(\"project_share invite requires operationId.\");\n\t\tif (metadata.policyTeamId || metadata.targetIdentityId || metadata.reviewedPreviewDigest) {\n\t\t\tthrow new Error(\"recipient invite metadata requires a recipient invite kind.\");\n\t\t}\n\t},\n\tlegacy_enrollment(operationId, metadata) {\n\t\tif (operationId) throw new Error(\"legacy_enrollment invite cannot reference an operation.\");\n\t\tif (metadata.policyTeamId || metadata.targetIdentityId || metadata.reviewedPreviewDigest) {\n\t\t\tthrow new Error(\"recipient invite metadata requires a recipient invite kind.\");\n\t\t}\n\t},\n\tteam_member(operationId, metadata) {\n\t\tif (\n\t\t\t!metadata.policyTeamId ||\n\t\t\t!metadata.reviewedPreviewDigest ||\n\t\t\tmetadata.targetIdentityId ||\n\t\t\toperationId\n\t\t) {\n\t\t\tthrow new Error(\"team_member invite metadata is invalid.\");\n\t\t}\n\t},\n\tadd_device(operationId, metadata) {\n\t\tif (\n\t\t\t!metadata.targetIdentityId ||\n\t\t\t!metadata.reviewedPreviewDigest ||\n\t\t\tmetadata.policyTeamId ||\n\t\t\toperationId\n\t\t) {\n\t\t\tthrow new Error(\"add_device invite metadata is invalid.\");\n\t\t}\n\t},\n};\n\nfunction validateInviteMetadataShape(\n\topts: CoordinatorCreateInviteInput,\n\tmetadata: NormalizedInviteMetadata,\n): void {\n\tINVITE_METADATA_VALIDATORS[metadata.inviteKind](clean(opts.operationId), metadata);\n}\n\nfunction reviewedIntentTarget(metadata: NormalizedInviteMetadata): {\n\ttarget: RecipientReviewedIntentTargetV1;\n\tdigest: string;\n} {\n\tif (\n\t\tmetadata.inviteKind === \"team_member\" &&\n\t\tmetadata.policyTeamId &&\n\t\tmetadata.reviewedPreviewDigest\n\t) {\n\t\treturn {\n\t\t\ttarget: { kind: \"team_member\", policyTeamId: metadata.policyTeamId },\n\t\t\tdigest: metadata.reviewedPreviewDigest,\n\t\t};\n\t}\n\tif (\n\t\tmetadata.inviteKind === \"add_device\" &&\n\t\tmetadata.targetIdentityId &&\n\t\tmetadata.reviewedPreviewDigest\n\t) {\n\t\treturn {\n\t\t\ttarget: { kind: \"add_device\", targetIdentityId: metadata.targetIdentityId },\n\t\t\tdigest: metadata.reviewedPreviewDigest,\n\t\t};\n\t}\n\tthrow new Error(\"recipient invite metadata requires a recipient invite kind.\");\n}\n\nexport async function normalizeCoordinatorInviteMetadata(\n\topts: CoordinatorCreateInviteInput,\n): Promise<{\n\tinviteKind: CoordinatorInviteKind;\n\tpolicyTeamId: string | null;\n\ttargetIdentityId: string | null;\n\treviewedPreviewDigest: string | null;\n\treviewedIntentJson: string | null;\n}> {\n\tconst metadata = {\n\t\tinviteKind:\n\t\t\topts.inviteKind ?? (clean(opts.operationId) ? \"project_share\" : \"legacy_enrollment\"),\n\t\tpolicyTeamId: clean(opts.policyTeamId),\n\t\ttargetIdentityId: clean(opts.targetIdentityId),\n\t\treviewedPreviewDigest: clean(opts.reviewedPreviewDigest),\n\t} satisfies NormalizedInviteMetadata;\n\tvalidateInviteMetadataIdentifiers(metadata);\n\tvalidateInviteMetadataShape(opts, metadata);\n\tconst reviewedIntentProvided = opts.reviewedIntent !== undefined && opts.reviewedIntent !== null;\n\tif (!reviewedIntentProvided) {\n\t\tif (metadata.inviteKind === \"team_member\" || metadata.inviteKind === \"add_device\") {\n\t\t\tthrow new Error(\"recipient_invite_review_unavailable\");\n\t\t}\n\t\treturn {\n\t\t\t...metadata,\n\t\t\treviewedIntentJson: null,\n\t\t};\n\t}\n\tconst reviewedIntent = reviewedIntentTarget(metadata);\n\tawait verifyRecipientReviewedIntent(opts.reviewedIntent, {\n\t\ttarget: reviewedIntent.target,\n\t\tdigest: reviewedIntent.digest,\n\t});\n\treturn {\n\t\t...metadata,\n\t\treviewedIntentJson: canonicalRecipientReviewedIntentJson(\n\t\t\topts.reviewedIntent,\n\t\t\treviewedIntent.target,\n\t\t),\n\t};\n}\n\nexport async function inspectCoordinatorRecipientInvite(\n\tinvite: CoordinatorInvite,\n): Promise<CoordinatorRecipientInviteInspection | null> {\n\tif (invite.invite_kind === \"team_member\") {\n\t\tif (\n\t\t\t!invite.policy_team_id ||\n\t\t\t!isCoordinatorAssignedIdentityId(invite.assigned_identity_id) ||\n\t\t\t!invite.reviewed_preview_digest\n\t\t)\n\t\t\tthrow new Error(\"invite_invalid\");\n\t\tconst reviewedIntent = await parseStoredRecipientReviewedIntent(invite.reviewed_intent_json, {\n\t\t\ttarget: { kind: \"team_member\", policyTeamId: invite.policy_team_id },\n\t\t\tdigest: invite.reviewed_preview_digest,\n\t\t});\n\t\treturn {\n\t\t\tkind: \"team_member\",\n\t\t\tinvite,\n\t\t\tpolicy_team_id: invite.policy_team_id,\n\t\t\tassigned_identity_id: invite.assigned_identity_id,\n\t\t\treviewed_preview_digest: invite.reviewed_preview_digest,\n\t\t\treviewed_intent: reviewedIntent,\n\t\t\tbound: Boolean(invite.consumed_at),\n\t\t};\n\t}\n\tif (invite.invite_kind === \"add_device\") {\n\t\tif (!invite.target_identity_id || !invite.reviewed_preview_digest)\n\t\t\tthrow new Error(\"invite_invalid\");\n\t\tconst reviewedIntent = await parseStoredRecipientReviewedIntent(invite.reviewed_intent_json, {\n\t\t\ttarget: { kind: \"add_device\", targetIdentityId: invite.target_identity_id },\n\t\t\tdigest: invite.reviewed_preview_digest,\n\t\t});\n\t\treturn {\n\t\t\tkind: \"add_device\",\n\t\t\tinvite,\n\t\t\ttarget_identity_id: invite.target_identity_id,\n\t\t\treviewed_preview_digest: invite.reviewed_preview_digest,\n\t\t\treviewed_intent: reviewedIntent,\n\t\t\tbound: Boolean(invite.consumed_at),\n\t\t};\n\t}\n\treturn null;\n}\n\nexport function normalizeEpoch(value: number | null | undefined, fallback = 0): number {\n\tif (value == null) return fallback;\n\tif (!Number.isFinite(value) || value < 0)\n\t\tthrow new Error(\"membershipEpoch must be non-negative.\");\n\treturn Math.trunc(value);\n}\n\nexport function normalizeCoordinatorCreateScopeInput(opts: CoordinatorCreateScopeInput) {\n\tconst scopeId = clean(opts.scopeId);\n\tconst label = clean(opts.label);\n\tif (!scopeId || !label) throw new Error(\"scopeId and label are required.\");\n\treturn {\n\t\tscopeId,\n\t\tlabel,\n\t\tkind: clean(opts.kind) ?? \"user\",\n\t\tauthorityType: clean(opts.authorityType) ?? \"coordinator\",\n\t\tcoordinatorId: clean(opts.coordinatorId),\n\t\tgroupId: clean(opts.groupId),\n\t\tmanifestIssuerDeviceId: clean(opts.manifestIssuerDeviceId),\n\t\tmembershipEpoch: normalizeEpoch(opts.membershipEpoch),\n\t\tmanifestHash: clean(opts.manifestHash),\n\t\tstatus: clean(opts.status) ?? \"active\",\n\t};\n}\n\nfunction cleanRequiredUpdate(\n\tvalue: string | null | undefined,\n\tcurrent: string,\n\tfieldName: string,\n): string {\n\tif (value === undefined) return current;\n\tconst cleaned = clean(value);\n\tif (!cleaned) throw new Error(`${fieldName} must not be empty.`);\n\treturn cleaned;\n}\n\nfunction cleanNullableUpdate(\n\tvalue: string | null | undefined,\n\tcurrent: string | null,\n): string | null {\n\treturn value === undefined ? current : clean(value);\n}\n\nexport function normalizeCoordinatorUpdateScopeInput(\n\topts: CoordinatorUpdateScopeInput,\n\texisting: CoordinatorScope,\n) {\n\tconst scopeId = clean(opts.scopeId);\n\tif (!scopeId) throw new Error(\"scopeId is required.\");\n\tconst requestedEpoch = opts.membershipEpoch == null ? null : normalizeEpoch(opts.membershipEpoch);\n\tif (requestedEpoch != null && requestedEpoch < existing.membership_epoch) {\n\t\tthrow new Error(\"membershipEpoch must not move backwards.\");\n\t}\n\treturn {\n\t\tscopeId,\n\t\tlabel: cleanRequiredUpdate(opts.label, existing.label, \"label\"),\n\t\tkind: cleanRequiredUpdate(opts.kind, existing.kind, \"kind\"),\n\t\tauthorityType: cleanRequiredUpdate(\n\t\t\topts.authorityType,\n\t\t\texisting.authority_type,\n\t\t\t\"authorityType\",\n\t\t),\n\t\tcoordinatorId: cleanNullableUpdate(opts.coordinatorId, existing.coordinator_id),\n\t\tgroupId: cleanNullableUpdate(opts.groupId, existing.group_id),\n\t\tmanifestIssuerDeviceId: cleanNullableUpdate(\n\t\t\topts.manifestIssuerDeviceId,\n\t\t\texisting.manifest_issuer_device_id,\n\t\t),\n\t\tmembershipEpoch: requestedEpoch ?? existing.membership_epoch,\n\t\tmanifestHash: cleanNullableUpdate(opts.manifestHash, existing.manifest_hash),\n\t\tstatus: cleanRequiredUpdate(opts.status, existing.status, \"status\"),\n\t};\n}\n\nexport function normalizeCoordinatorGrantScopeMembershipInput(\n\topts: CoordinatorGrantScopeMembershipInput,\n\tscope: CoordinatorScope | null,\n\texisting: CoordinatorScopeMembership | null,\n) {\n\tconst scopeId = clean(opts.scopeId);\n\tconst deviceId = clean(opts.deviceId);\n\tif (!scopeId || !deviceId) throw new Error(\"scopeId and deviceId are required.\");\n\tvalidateMembershipScopeBindings(opts, scope);\n\tconst membershipEpoch = normalizeMembershipEpoch(opts, scope, existing);\n\treturn {\n\t\tscopeId,\n\t\tdeviceId,\n\t\trole: clean(opts.role) ?? \"member\",\n\t\tmembershipEpoch,\n\t\tcoordinatorId: scope?.coordinator_id ?? null,\n\t\tgroupId: scope?.group_id ?? null,\n\t\tmanifestIssuerDeviceId:\n\t\t\tclean(opts.manifestIssuerDeviceId) ?? scope?.manifest_issuer_device_id ?? null,\n\t\tmanifestHash: clean(opts.manifestHash) ?? scope?.manifest_hash ?? null,\n\t\tsignedManifestJson: clean(opts.signedManifestJson),\n\t\tactorType: clean(opts.actorType),\n\t\tactorId: clean(opts.actorId),\n\t};\n}\n\nfunction validateMembershipScopeBindings(\n\topts: CoordinatorGrantScopeMembershipInput,\n\tscope: CoordinatorScope | null,\n): void {\n\tif (clean(opts.coordinatorId) && clean(opts.coordinatorId) !== scope?.coordinator_id) {\n\t\tthrow new Error(\"membership coordinatorId must match the scope coordinatorId.\");\n\t}\n\tif (clean(opts.groupId) && clean(opts.groupId) !== scope?.group_id) {\n\t\tthrow new CoordinatorMembershipError(\"scope_group_mismatch\");\n\t}\n}\n\nfunction normalizeMembershipEpoch(\n\topts: CoordinatorGrantScopeMembershipInput,\n\tscope: CoordinatorScope | null,\n\texisting: CoordinatorScopeMembership | null,\n): number {\n\tconst requestedEpoch = opts.membershipEpoch == null ? null : normalizeEpoch(opts.membershipEpoch);\n\tconst inheritedEpoch = scope?.membership_epoch ?? 0;\n\tif (requestedEpoch != null && requestedEpoch < inheritedEpoch) {\n\t\tthrow new Error(\"membershipEpoch must not be lower than the scope membershipEpoch.\");\n\t}\n\tif (requestedEpoch != null && existing) {\n\t\tconst minimumEpoch =\n\t\t\texisting.status === \"revoked\" ? existing.membership_epoch + 1 : existing.membership_epoch;\n\t\tif (requestedEpoch < minimumEpoch) {\n\t\t\tthrow new Error(\"membershipEpoch must not move backwards.\");\n\t\t}\n\t}\n\treturn (\n\t\trequestedEpoch ??\n\t\t(existing\n\t\t\t? Math.max(\n\t\t\t\t\tinheritedEpoch,\n\t\t\t\t\texisting.membership_epoch + (existing.status === \"revoked\" ? 1 : 0),\n\t\t\t\t)\n\t\t\t: inheritedEpoch)\n\t);\n}\n\nexport function normalizeCoordinatorAuditLimit(limit: number | null | undefined): number {\n\tif (limit == null) return 100;\n\tif (!Number.isFinite(limit)) return 100;\n\treturn Math.max(1, Math.min(1000, Math.trunc(limit)));\n}\n","import {\n\ttype DecodedRelayCheck,\n\tdecodeRelayCheckPacket,\n\ttype RelayAdmissionRole,\n} from \"./relay-admission-codec.js\";\nimport { parseRelayEd25519PublicKey } from \"./relay-ed25519.js\";\n\nexport interface RelayProofSigner {\n\treadonly deviceId: string;\n\treadonly publicKey: string;\n}\n\nexport type RelayProofExpectation =\n\t| { readonly kind: \"admission\"; readonly role: RelayAdmissionRole }\n\t| { readonly kind: \"registration\" };\n\nexport interface RelayProofVerificationOptions {\n\treadonly packet: unknown;\n\treadonly expected: RelayProofExpectation;\n\treadonly signer: RelayProofSigner;\n\treadonly deviceHeader: string;\n\treadonly externalPathname: string;\n}\n\nexport type VerifiedRelayCheckProof = DecodedRelayCheck & {\n\treadonly signer: RelayProofSigner & { readonly keyId: string };\n\treadonly packetDigest: string;\n};\n\nfunction captureExpectation(value: unknown): RelayProofExpectation | null {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return null;\n\tconst keys = Reflect.ownKeys(value);\n\tif (!keys.includes(\"kind\") || !(\"kind\" in value)) return null;\n\tconst kind = value.kind;\n\tif (kind === \"registration\" && keys.length === 1) return { kind };\n\tif (kind !== \"admission\" || keys.length !== 2 || !keys.includes(\"role\") || !(\"role\" in value)) {\n\t\treturn null;\n\t}\n\tconst role = value.role;\n\tif (role !== \"source\" && role !== \"relay\" && role !== \"responder\") return null;\n\treturn { kind, role };\n}\n\nfunction hasInvalidPathCharacter(value: string): boolean {\n\treturn Array.from(value).some((character) => {\n\t\tconst code = character.codePointAt(0) ?? 0;\n\t\treturn (\n\t\t\tcode <= 32 ||\n\t\t\t(code >= 127 && code <= 159) ||\n\t\t\t(code >= 0xd800 && code <= 0xdfff) ||\n\t\t\t\"?#\\\\\".includes(character)\n\t\t);\n\t});\n}\n\nfunction isAdmissionPath(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.startsWith(\"/\") &&\n\t\t!value.startsWith(\"//\") &&\n\t\t!hasInvalidPathCharacter(value) &&\n\t\tvalue.endsWith(\"/v1/relay/admission-check\")\n\t);\n}\n\nfunction matchesExpectation(decoded: DecodedRelayCheck, expected: RelayProofExpectation): boolean {\n\tif (decoded.kind === \"registration\") return expected.kind === \"registration\";\n\treturn expected.kind === \"admission\" && decoded.value.role === expected.role;\n}\n\nfunction captureProofInputs(options: RelayProofVerificationOptions) {\n\tconst { packet, expected, signer, deviceHeader, externalPathname } = options;\n\tconst expectation = captureExpectation(expected);\n\tconst { deviceId, publicKey } = signer;\n\tif (\n\t\t!expectation ||\n\t\ttypeof deviceId !== \"string\" ||\n\t\ttypeof publicKey !== \"string\" ||\n\t\ttypeof deviceHeader !== \"string\" ||\n\t\t!isAdmissionPath(externalPathname)\n\t) {\n\t\treturn null;\n\t}\n\tconst decoded = decodeRelayCheckPacket(packet);\n\tif (!matchesExpectation(decoded, expectation)) return null;\n\tlet signedDeviceId: string;\n\tlet signedKeyId: string;\n\tif (decoded.kind === \"admission\") {\n\t\tsignedDeviceId = decoded.value.sourceDeviceId;\n\t\tsignedKeyId = decoded.value.sourceKeyId;\n\t} else {\n\t\tsignedDeviceId = decoded.value.deviceId;\n\t\tsignedKeyId = decoded.value.keyId;\n\t}\n\tif (deviceHeader !== signedDeviceId || deviceId !== signedDeviceId) return null;\n\treturn {\n\t\tdecoded,\n\t\tsigner: { deviceId, publicKey },\n\t\tsignedKeyId,\n\t\texternalPathname,\n\t\tkey: parseRelayEd25519PublicKey(publicKey),\n\t};\n}\n\nasync function sha256Hex(bytes: Uint8Array): Promise<string> {\n\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", new Uint8Array(bytes));\n\treturn Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Verifies one packet against an explicitly trusted existing key pin, without consuming its nonce.\n * A proof is not fresh or authorized. The caller must still check current authority, enrollments,\n * policy, readiness, quotas, time windows, and nonce insertion in its final atomic decision.\n */\nexport async function verifyRelayCheckProof(\n\toptions: RelayProofVerificationOptions,\n): Promise<VerifiedRelayCheckProof | null> {\n\ttry {\n\t\t// Capture caller-owned data and decode owned bytes before any asynchronous operation.\n\t\tconst captured = captureProofInputs(options);\n\t\tif (!captured) return null;\n\t\tconst { decoded, signer, signedKeyId, externalPathname, key } = captured;\n\t\tconst keyId = await sha256Hex(key.wireKey);\n\t\tif (keyId !== signedKeyId) return null;\n\t\tconst packetDigest = await sha256Hex(decoded.bodyBytes);\n\t\tconst canonical = [\n\t\t\t\"POST\",\n\t\t\texternalPathname,\n\t\t\tdecoded.timestamp,\n\t\t\tdecoded.nonce,\n\t\t\tpacketDigest,\n\t\t].join(\"\\n\");\n\t\tconst verificationKey = await globalThis.crypto.subtle.importKey(\n\t\t\t\"raw\",\n\t\t\tnew Uint8Array(key.rawKey),\n\t\t\t{ name: \"Ed25519\" },\n\t\t\tfalse,\n\t\t\t[\"verify\"],\n\t\t);\n\t\tconst verified = await globalThis.crypto.subtle.verify(\n\t\t\t\"Ed25519\",\n\t\t\tverificationKey,\n\t\t\tnew Uint8Array(decoded.signatureBytes),\n\t\t\tnew TextEncoder().encode(canonical),\n\t\t);\n\t\tif (!verified) return null;\n\t\treturn { ...decoded, signer: { ...signer, keyId }, packetDigest };\n\t} catch {\n\t\treturn null;\n\t}\n}\n","export const DEFAULT_TIME_WINDOW_S = 300;\n"],"mappings":";;;;AAMA,SAAgB,EAA2C,GAGlD;CACR,IACC,EAAM,QAAQ,SAAA,OACd,EAAM,SAAS,SAAA,OACf,EAAM,QAAQ,SAAS,EAAM,SAAS,SAAA,KAEtC,MAAU,MAAM,oCAAoC;AAEtD;AASA,SAAgB,EAAsD,GAG7D;CACR,IACC,EAAM,kBAAkB,OAAO,EAAM,cAAA,KAGrC,MAAU,MAAM,oCAAoC;AAEtD;AAOA,SAAgB,EACf,GACA,GACA,GACO;CACP,IAAI,EAAS,WAAW,GAAG;CAC3B,IAAM,IAAY,CAAC,GAAG,IAAI,IAAI,EAAQ,KAAK,MAAW,EAAO,QAAQ,CAAC,CAAC,GACjE,IACL,EAAU,SAAS,IAAI,2BAA2B,EAAU,UAAU,GAAG,CAAC,CAAC,KAAK,IAAI,EAAE,KAAK,IACtF,IAAiB,OACtB,EACE,QAAQ,yCAAyC,GAAe,CAAC,CACjE,MAAM,CAAC,CACP,IAAI,GAAG,CAAS,KAAK,CACxB;CACA,KACE,EAAU,SAAS,KAAkB,EAAS,SAAA,KAG/C,MAAU,MAAM,oCAAoC;AAEtD;AAEA,SAAgB,EACf,GACA,GACA,GACA,GACO;CACP,IAAI,CAAC,GAAmB;CACxB,IAAM,IAAmB,CAAC,GAAG,IAAI,IAAI,EAAQ,KAAK,MAAW,EAAO,QAAQ,CAAC,CAAC,GACxE,IAAe,EAAiB,UAAU,GAAG,CAAC,CAAC,KAAK,IAAI,GACxD,IAAiB,IAAe,yBAAyB,EAAa,KAAK,IAC3E,IAAqB,OAC1B,EACE,QACA;4BACwB,GACzB,CAAC,CACA,MAAM,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