@codemem/core 0.49.0 → 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/distill-draft.d.ts +6 -0
- package/dist/distill-draft.d.ts.map +1 -1
- package/dist/distill-judge.d.ts +1 -1
- package/dist/distill-judge.d.ts.map +1 -1
- 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 +11664 -10635
- 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 +29 -29
- 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-j0rOyeuZ.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-pass.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 +3 -7
- 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-Co6WjaUD.js → sync-reachability-pass-DKEORTbs.js} +2934 -2865
- package/dist/sync-reachability-pass-DKEORTbs.js.map +1 -0
- package/dist/sync-reachability-pass.d.ts.map +1 -1
- 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-BYCjEE7A.js +0 -594
- package/dist/coordinator-runtime-BYCjEE7A.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-j0rOyeuZ.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-5bOMxdoW.js +0 -2
- package/dist/sync-reachability-pass-Co6WjaUD.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
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"coordinator-runtime-ynLTJI6d.js","names":[],"sources":["../src/identity-device-assignment.ts","../src/coordinator-rejoin-timestamp.ts","../src/retired-device-aliases.ts","../src/device-identity-inventory.ts","../src/recipient-policy-actor-eligibility.ts","../src/device-identity-binding.ts","../src/coordinator-peer-revocation.ts","../src/coordinator-removal-notice.ts","../src/memory-retirement-trust.ts","../src/pairing-removal.ts","../src/device-retirement.ts","../src/coordinator-runtime.ts"],"sourcesContent":["import type { Database } from \"./db.js\";\n\nexport type IdentityDeviceAssignmentExpectation =\n\t| { kind: \"absent\" }\n\t| { kind: \"existing\"; assignmentVersion: number; identityId: string };\n\nexport interface IdentityDeviceAssignmentInsertValues {\n\tdisplayName: string;\n\tprovenance: string;\n\trevision: string;\n\tmigrationState: string;\n\tsourceFingerprint?: string | null;\n\tidempotencyKey: string;\n}\n\nexport interface AssignIdentityDeviceInput {\n\tdeviceId: string;\n\ttargetIdentityId: string;\n\texpectation: IdentityDeviceAssignmentExpectation;\n\tinsert?: IdentityDeviceAssignmentInsertValues;\n\tnow?: string;\n}\n\nexport interface AssignIdentityDeviceResult {\n\tassignmentVersion: number;\n\tchanged: boolean;\n\tinvalidatedDecisionCount: number;\n\tinvalidatedTeamCount: number;\n}\n\nexport type IdentityDeviceAssignmentErrorCode =\n\t| \"team_setup_assignment_changed\"\n\t| \"identity_device_assignment_insert_values_required\"\n\t| \"identity_device_assignment_transaction_required\";\n\nexport class IdentityDeviceAssignmentError extends Error {\n\treadonly code: IdentityDeviceAssignmentErrorCode;\n\n\tconstructor(code: IdentityDeviceAssignmentErrorCode) {\n\t\tsuper(code);\n\t\tthis.name = \"IdentityDeviceAssignmentError\";\n\t\tthis.code = code;\n\t}\n}\n\ninterface AssignmentRow {\n\tidentity_id: string;\n\tassignment_version: number;\n\tstatus: string;\n}\n\nfunction assignmentChanged(): never {\n\tthrow new IdentityDeviceAssignmentError(\"team_setup_assignment_changed\");\n}\n\nfunction isDeviceIdConflict(error: unknown): boolean {\n\treturn (\n\t\ttypeof error === \"object\" &&\n\t\terror !== null &&\n\t\t\"code\" in error &&\n\t\terror.code === \"SQLITE_CONSTRAINT_PRIMARYKEY\"\n\t);\n}\n\nfunction currentAssignment(db: Database, deviceId: string): AssignmentRow | null {\n\treturn (\n\t\t(db\n\t\t\t.prepare(\n\t\t\t\t`SELECT identity_id, assignment_version, status\n\t\t\t\t FROM identity_devices\n\t\t\t\t WHERE device_id = ?`,\n\t\t\t)\n\t\t\t.get(deviceId) as AssignmentRow | undefined) ?? null\n\t);\n}\n\nfunction requireExpectedAssignment(\n\trow: AssignmentRow | null,\n\texpectation: IdentityDeviceAssignmentExpectation,\n): void {\n\tif (expectation.kind === \"absent\") {\n\t\tif (row) assignmentChanged();\n\t\treturn;\n\t}\n\tif (\n\t\trow?.status !== \"active\" ||\n\t\trow.identity_id !== expectation.identityId ||\n\t\trow.assignment_version !== expectation.assignmentVersion\n\t) {\n\t\tassignmentChanged();\n\t}\n}\n\n/**\n * A device that moved to another Identity loses reviewed-Team inclusion until\n * those Teams are reviewed again.\n */\nexport function invalidateIncludedTeamDecisions(\n\tdb: Database,\n\tdeviceId: string,\n\tnow: string,\n): { invalidatedDecisionCount: number; invalidatedTeamCount: number } {\n\tconst affectedTeams = db\n\t\t.prepare(\n\t\t\t`SELECT d.team_id\n\t\t\t FROM policy_team_device_decisions d\n\t\t\t JOIN policy_teams t ON t.team_id = d.team_id\n\t\t\t WHERE d.device_id = ?\n\t\t\t AND d.decision = 'included'\n\t\t\t AND t.device_eligibility_mode = 'reviewed_allowlist'`,\n\t\t)\n\t\t.all(deviceId) as Array<{ team_id: string }>;\n\tconst invalidatedDecisions = db\n\t\t.prepare(\n\t\t\t`UPDATE policy_team_device_decisions\n\t\t\t SET decision = 'unresolved', updated_at = ?\n\t\t\t WHERE device_id = ?\n\t\t\t AND decision = 'included'\n\t\t\t AND team_id IN (\n\t\t\t SELECT team_id FROM policy_teams\n\t\t\t WHERE device_eligibility_mode = 'reviewed_allowlist'\n\t\t\t )`,\n\t\t)\n\t\t.run(now, deviceId);\n\n\tfor (const team of affectedTeams) {\n\t\t// Clear the stale completion fingerprint so compatibility diagnostics and\n\t\t// older non-terminal migration records fail closed after reassignment.\n\t\tdb.prepare(\n\t\t\t`UPDATE policy_teams\n\t\t\t SET source_fingerprint = NULL, updated_at = ?\n\t\t\t WHERE team_id = ?`,\n\t\t).run(now, team.team_id);\n\t}\n\n\treturn {\n\t\tinvalidatedDecisionCount: invalidatedDecisions.changes,\n\t\tinvalidatedTeamCount: affectedTeams.length,\n\t};\n}\n\n/**\n * Applies one canonical device assignment mutation inside the caller's transaction.\n * Reassignments revoke reviewed-Team inclusion until those Teams are reviewed again.\n */\nexport function assignIdentityDeviceInTransaction(\n\tdb: Database,\n\tinput: AssignIdentityDeviceInput,\n): AssignIdentityDeviceResult {\n\tif (!db.inTransaction) {\n\t\tthrow new IdentityDeviceAssignmentError(\"identity_device_assignment_transaction_required\");\n\t}\n\n\tconst before = currentAssignment(db, input.deviceId);\n\trequireExpectedAssignment(before, input.expectation);\n\tif (before?.status === \"active\" && before?.identity_id === input.targetIdentityId) {\n\t\treturn {\n\t\t\tassignmentVersion: before.assignment_version,\n\t\t\tchanged: false,\n\t\t\tinvalidatedDecisionCount: 0,\n\t\t\tinvalidatedTeamCount: 0,\n\t\t};\n\t}\n\n\tconst now = input.now ?? new Date().toISOString();\n\tif (!before) {\n\t\tconst insert = input.insert;\n\t\tif (!insert) {\n\t\t\tthrow new IdentityDeviceAssignmentError(\"identity_device_assignment_insert_values_required\");\n\t\t}\n\t\ttry {\n\t\t\tdb.prepare(\n\t\t\t\t`INSERT INTO identity_devices(\n\t\t\t\t device_id, identity_id, display_name, status, provenance, revision,\n\t\t\t\t migration_state, source_fingerprint, idempotency_key, created_at, updated_at\n\t\t\t\t ) VALUES (?, ?, ?, 'active', ?, ?, ?, ?, ?, ?, ?)`,\n\t\t\t).run(\n\t\t\t\tinput.deviceId,\n\t\t\t\tinput.targetIdentityId,\n\t\t\t\tinsert.displayName,\n\t\t\t\tinsert.provenance,\n\t\t\t\tinsert.revision,\n\t\t\t\tinsert.migrationState,\n\t\t\t\tinsert.sourceFingerprint ?? null,\n\t\t\t\tinsert.idempotencyKey,\n\t\t\t\tnow,\n\t\t\t\tnow,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (isDeviceIdConflict(error)) assignmentChanged();\n\t\t\tthrow error;\n\t\t}\n\t} else {\n\t\tconst expectation = input.expectation;\n\t\tif (expectation.kind !== \"existing\") assignmentChanged();\n\t\t// A reassignment to a DIFFERENT identity invalidates metadata bound to\n\t\t// the former one: an invite-provenance `source_fingerprint` describes\n\t\t// the old binding, and leaving it in place makes recipient onboarding\n\t\t// reject every later valid invite for the corrected binding as a\n\t\t// `device_binding_conflict`. Clearing it marks the binding as reviewed\n\t\t// rather than invite-keyed; same-identity CAS refreshes keep it.\n\t\tconst identityChanged = expectation.identityId !== input.targetIdentityId;\n\t\tconst updated = db\n\t\t\t.prepare(\n\t\t\t\t`UPDATE identity_devices\n\t\t\t\t SET identity_id = ?, ${identityChanged ? \"source_fingerprint = NULL,\" : \"\"} updated_at = ?\n\t\t\t\t WHERE device_id = ?\n\t\t\t\t AND identity_id = ?\n\t\t\t\t AND assignment_version = ?\n\t\t\t\t AND status = 'active'`,\n\t\t\t)\n\t\t\t.run(\n\t\t\t\tinput.targetIdentityId,\n\t\t\t\tnow,\n\t\t\t\tinput.deviceId,\n\t\t\t\texpectation.identityId,\n\t\t\t\texpectation.assignmentVersion,\n\t\t\t);\n\t\tif (updated.changes !== 1) assignmentChanged();\n\t}\n\n\tconst after = currentAssignment(db, input.deviceId);\n\tif (after?.status !== \"active\" || after.identity_id !== input.targetIdentityId) {\n\t\tassignmentChanged();\n\t}\n\n\tif (!before) {\n\t\treturn {\n\t\t\tassignmentVersion: after.assignment_version,\n\t\t\tchanged: true,\n\t\t\tinvalidatedDecisionCount: 0,\n\t\t\tinvalidatedTeamCount: 0,\n\t\t};\n\t}\n\n\treturn {\n\t\tassignmentVersion: after.assignment_version,\n\t\tchanged: true,\n\t\t...invalidateIncludedTeamDecisions(db, input.deviceId, now),\n\t};\n}\n","/** Display-only: a malformed marker is dropped, so it can never change what the Viewer shows or allows. */\nexport function isRejoinTimestamp(value: unknown): value is number {\n\t// 8.64e15 is the largest millisecond value a Date can hold.\n\treturn typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0 && value <= 8.64e15;\n}\n","import { createHash } from \"node:crypto\";\nimport { parseSshEd25519PublicKeyForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport type { Database } from \"./db.js\";\n\n/*\n * Device IDs this device knows were retired. A `device_id` row means the\n * coordinator revoked that ID outright. A `key` row means the coordinator revoked\n * the key this device pinned for that ID, so the ID stays retired only while no\n * pairing under it pins a different key. Keys compare by canonical key ID when\n * both sides parse, because different key text can carry the same key.\n */\n\nexport type RetiredAliasKind = \"device_id\" | \"key\";\n\nexport interface RetiredAlias {\n\tkind: RetiredAliasKind;\n\tfingerprint: string;\n\tkeyId: string | null;\n}\n\nexport interface CurrentPin {\n\tpublicKey: string | null;\n\tfingerprint: string | null;\n}\n\n/**\n * The coordinator's canonical key ID (SHA-256 of the canonical SSH blob), computed\n * synchronously so the inventory can use it. Null for keys that aren't SSH Ed25519.\n */\nexport function canonicalKeyId(publicKey: string | null): string | null {\n\tif (!publicKey) return null;\n\tconst parsed = parseSshEd25519PublicKeyForRevocation(publicKey);\n\tif (parsed.kind !== \"ed25519\") return null;\n\treturn createHash(\"sha256\").update(parsed.blob).digest(\"hex\");\n}\n\nexport function ensureRetiredDeviceAliasSchema(db: Database): void {\n\tdb.exec(`CREATE TABLE IF NOT EXISTS retired_device_aliases (\n\t\tdevice_id TEXT PRIMARY KEY,\n\t\tkind TEXT NOT NULL CHECK(kind IN ('device_id', 'key')),\n\t\tfingerprint TEXT NOT NULL,\n\t\tkey_id TEXT,\n\t\tretired_at TEXT NOT NULL\n\t)`);\n}\n\n/** Every recorded alias. Empty before this device retires anything. */\nexport function listRetiredDeviceAliases(db: Database): Map<string, RetiredAlias> {\n\tconst table = db\n\t\t.prepare(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'retired_device_aliases'\")\n\t\t.get();\n\tif (!table) return new Map();\n\tconst rows = db\n\t\t.prepare(\"SELECT device_id, kind, fingerprint, key_id FROM retired_device_aliases\")\n\t\t.all() as Array<{\n\t\tdevice_id: string;\n\t\tkind: RetiredAliasKind;\n\t\tfingerprint: string;\n\t\tkey_id: string | null;\n\t}>;\n\treturn new Map(\n\t\trows.map((row) => [\n\t\t\trow.device_id,\n\t\t\t{ kind: row.kind, fingerprint: row.fingerprint, keyId: row.key_id },\n\t\t]),\n\t);\n}\n\n/** Whether an alias still retires its ID, given the key a current pairing under it pins. */\nexport function retiredAliasApplies(\n\talias: RetiredAlias | undefined,\n\tcurrentPin: CurrentPin | null,\n): boolean {\n\tif (!alias) return false;\n\tif (alias.kind === \"device_id\") return true;\n\tif (!currentPin || (!currentPin.publicKey && !currentPin.fingerprint)) return true;\n\tconst currentKeyId = canonicalKeyId(currentPin.publicKey);\n\tif (alias.keyId && currentKeyId) return currentKeyId === alias.keyId;\n\treturn currentPin.fingerprint === alias.fingerprint;\n}\n\nexport function recordRetiredDeviceAliases(\n\tdb: Database,\n\taliases: Array<{\n\t\tdeviceId: string;\n\t\tkind: RetiredAliasKind;\n\t\tfingerprint: string;\n\t\tkeyId: string | null;\n\t}>,\n): void {\n\tensureRetiredDeviceAliasSchema(db);\n\t// An ID revocation outranks a key-only record; otherwise the latest key wins.\n\tconst upsert = db.prepare(\n\t\t`INSERT INTO retired_device_aliases(device_id, kind, fingerprint, key_id, retired_at)\n\t\t VALUES (?, ?, ?, ?, ?)\n\t\t ON CONFLICT(device_id) DO UPDATE SET\n\t\t kind = CASE WHEN retired_device_aliases.kind = 'device_id' THEN 'device_id' ELSE excluded.kind END,\n\t\t fingerprint = excluded.fingerprint,\n\t\t key_id = excluded.key_id,\n\t\t retired_at = excluded.retired_at`,\n\t);\n\tconst now = new Date().toISOString();\n\tfor (const alias of aliases)\n\t\tupsert.run(alias.deviceId, alias.kind, alias.fingerprint, alias.keyId, now);\n}\n","import { isRejoinTimestamp } from \"./coordinator-rejoin-timestamp.js\";\nimport type { CoordinatorEnrollment } from \"./coordinator-store-contract.js\";\nimport type { Database } from \"./db.js\";\nimport { listRetiredDeviceAliases, retiredAliasApplies } from \"./retired-device-aliases.js\";\nimport { fingerprintPublicKey } from \"./sync-fingerprint.js\";\n\nexport const DEVICE_IDENTITY_INVENTORY_VERSION = 1 as const;\nexport const DEVICE_IDENTITY_INVENTORY_LIMIT = 500;\nconst DEVICE_IDENTITY_EVIDENCE_LIMIT = 2_000;\n\nexport type DeviceIdentityInventoryState =\n\t| \"configured\"\n\t| \"setup_required\"\n\t| \"pairing_required\"\n\t| \"conflicted\"\n\t/** Coordinator infrastructure such as a relay health probe; never paired or assigned. */\n\t| \"service\"\n\t/** Revoked coordinator-wide by device ID or key; counted as revoked, never set up again. */\n\t| \"retired\";\n\nexport type DeviceIdentityInventorySource =\n\t| \"local_device\"\n\t| \"sync_peer\"\n\t| \"coordinator_enrollment\"\n\t| \"identity_binding\";\n\nexport interface DeviceIdentityLocalDeviceEvidence {\n\tdeviceId: string;\n\tdisplayName: string;\n\tpublicKey: string;\n\tfingerprint: string;\n}\n\nexport interface DeviceIdentityPeerEvidence {\n\tdeviceId: string;\n\tdisplayName: string;\n\tpublicKey: string | null;\n\tpinnedFingerprint: string | null;\n\tsuggestedIdentityId: string | null;\n\ttrustProvenance: string | null;\n\tclaimedLocalActor: boolean;\n\t/** This device recorded the ID as retired and the pairing still pins the retired key. */\n\tretired?: boolean;\n}\n\nexport interface DeviceIdentityBindingEvidence {\n\tdeviceId: string;\n\tdisplayName: string;\n\tidentityId: string;\n\tstatus: string;\n\tidentityStatus: string | null;\n\t/** This device recorded the ID as retired, so the binding reads retired without the coordinator. */\n\tretired?: boolean;\n}\n\nexport interface DeviceIdentityCoordinatorEvidence {\n\tavailability: \"available\" | \"unavailable\";\n\tsafeErrorCode: string | null;\n\tenrollments: CoordinatorEnrollment[];\n}\n\nexport interface DeviceIdentityInventorySnapshot {\n\tlocalDevice: DeviceIdentityLocalDeviceEvidence | null;\n\tpeers: DeviceIdentityPeerEvidence[];\n\tbindings: DeviceIdentityBindingEvidence[];\n\tcoordinator: DeviceIdentityCoordinatorEvidence;\n\tlocalEvidenceTruncated?: boolean;\n}\n\nexport interface DeviceIdentityInventoryInput {\n\tlocalDeviceId: string;\n\tlocalDisplayName?: string;\n\tcoordinator: DeviceIdentityCoordinatorEvidence;\n}\n\nexport interface DeviceIdentityInventoryItemV1 {\n\tversion: typeof DEVICE_IDENTITY_INVENTORY_VERSION;\n\tdeviceId: string;\n\tevidenceDeviceIds: string[];\n\tdisplayName: string;\n\tstate: DeviceIdentityInventoryState;\n\tidentityId: string | null;\n\tsuggestedIdentityId: string | null;\n\tvalidatedFingerprint: string | null;\n\tisLocal: boolean;\n\tsources: DeviceIdentityInventorySource[];\n\tconflictCodes: string[];\n\t/**\n\t * Display only. The newest enabled coordinator enrollment that Google sign-in rejoin wrote\n\t * for another device. It grants nothing and changes no state or action.\n\t */\n\trejoin?: DeviceIdentityRejoinEvidenceV1;\n}\n\nexport interface DeviceIdentityRejoinEvidenceV1 {\n\t/** The enrollment's own device ID, which can differ from the item's ID when keys match. */\n\tdeviceId: string;\n\trejoinedAtMs: number;\n}\n\nexport interface DeviceIdentityInventoryV1 {\n\tversion: typeof DEVICE_IDENTITY_INVENTORY_VERSION;\n\titems: DeviceIdentityInventoryItemV1[];\n\tcoordinatorEvidence: Pick<DeviceIdentityCoordinatorEvidence, \"availability\" | \"safeErrorCode\">;\n\ttruncated: boolean;\n}\n\ninterface Evidence {\n\tdeviceId: string;\n\tdisplayName: string;\n\tsource: DeviceIdentityInventorySource;\n\tfingerprint: string | null;\n\tfingerprintConflict: boolean;\n\tisLocal: boolean;\n\tsuggestedIdentityId: string | null;\n\tbindingIdentityId: string | null;\n\tbindingStatus: string | null;\n\tbindingIdentityStatus: string | null;\n\tbindingAuthoritative: boolean;\n\tenrollmentEnabled: boolean | null;\n\tpairingProof: boolean;\n\tserviceDevice: boolean;\n\trevoked: boolean;\n\t/** Only from an enabled coordinator enrollment; see DeviceIdentityInventoryItemV1.rejoin. */\n\trejoinedAtMs: number | null;\n}\n\nfunction clean(value: unknown): string | null {\n\treturn typeof value === \"string\" && value.trim() ? value.trim() : null;\n}\n\nfunction fingerprint(\n\tpublicKey: string | null,\n\tclaimed: string | null,\n): {\n\tvalue: string | null;\n\tconflict: boolean;\n} {\n\tif (!publicKey) return { value: claimed, conflict: false };\n\tconst derived = fingerprintPublicKey(publicKey);\n\tif (claimed && claimed !== derived) return { value: null, conflict: true };\n\treturn { value: claimed ?? derived, conflict: false };\n}\n\nfunction localEvidence(value: DeviceIdentityLocalDeviceEvidence): Evidence {\n\tconst validated = fingerprint(clean(value.publicKey), clean(value.fingerprint));\n\treturn {\n\t\tdeviceId: value.deviceId,\n\t\tdisplayName: value.displayName,\n\t\tsource: \"local_device\",\n\t\tfingerprint: validated.value,\n\t\tfingerprintConflict: validated.conflict,\n\t\tisLocal: true,\n\t\tsuggestedIdentityId: null,\n\t\tbindingIdentityId: null,\n\t\tbindingStatus: null,\n\t\tbindingIdentityStatus: null,\n\t\tbindingAuthoritative: false,\n\t\tenrollmentEnabled: null,\n\t\tpairingProof: true,\n\t\tserviceDevice: false,\n\t\trevoked: false,\n\t\trejoinedAtMs: null,\n\t};\n}\n\nfunction peerEvidence(value: DeviceIdentityPeerEvidence): Evidence {\n\tconst validated = fingerprint(clean(value.publicKey), clean(value.pinnedFingerprint));\n\treturn {\n\t\tdeviceId: value.deviceId,\n\t\tdisplayName: value.displayName,\n\t\tsource: \"sync_peer\",\n\t\tfingerprint: validated.value,\n\t\tfingerprintConflict: validated.conflict,\n\t\tisLocal: false,\n\t\tsuggestedIdentityId: clean(value.suggestedIdentityId),\n\t\tbindingIdentityId: null,\n\t\tbindingStatus: null,\n\t\tbindingIdentityStatus: null,\n\t\tbindingAuthoritative: false,\n\t\tenrollmentEnabled: null,\n\t\tpairingProof: clean(value.trustProvenance) !== \"coordinator_policy\" || value.claimedLocalActor,\n\t\tserviceDevice: false,\n\t\trevoked: value.retired === true,\n\t\trejoinedAtMs: null,\n\t};\n}\n\nfunction bindingEvidence(value: DeviceIdentityBindingEvidence): Evidence {\n\treturn {\n\t\tdeviceId: value.deviceId,\n\t\tdisplayName: value.displayName,\n\t\tsource: \"identity_binding\",\n\t\tfingerprint: null,\n\t\tfingerprintConflict: false,\n\t\tisLocal: false,\n\t\tsuggestedIdentityId: null,\n\t\tbindingIdentityId: value.identityId,\n\t\tbindingStatus: value.status,\n\t\tbindingIdentityStatus: value.identityStatus,\n\t\tbindingAuthoritative: true,\n\t\tenrollmentEnabled: null,\n\t\tpairingProof: false,\n\t\tserviceDevice: false,\n\t\t// This device confirmed the retirement, so it holds even when the coordinator is unreachable.\n\t\trevoked: value.retired === true,\n\t\trejoinedAtMs: null,\n\t};\n}\n\nfunction enrollmentEvidence(value: CoordinatorEnrollment): Evidence {\n\tconst validated = fingerprint(clean(value.public_key), clean(value.fingerprint));\n\treturn {\n\t\tdeviceId: value.device_id,\n\t\tdisplayName: clean(value.display_name) ?? \"\",\n\t\tsource: \"coordinator_enrollment\",\n\t\tfingerprint: validated.value,\n\t\tfingerprintConflict: validated.conflict,\n\t\tisLocal: false,\n\t\tsuggestedIdentityId: clean(value.identity_id),\n\t\tbindingIdentityId: null,\n\t\tbindingStatus: null,\n\t\tbindingIdentityStatus: null,\n\t\tbindingAuthoritative: false,\n\t\tenrollmentEnabled: value.enabled === 1,\n\t\tpairingProof: false,\n\t\tserviceDevice: value.service_role === \"relay_health_probe\",\n\t\trevoked: value.revoked === true,\n\t\trejoinedAtMs:\n\t\t\tvalue.enabled === 1 && isRejoinTimestamp(value.rejoined_at_ms) ? value.rejoined_at_ms : null,\n\t};\n}\n\nfunction evidence(snapshot: DeviceIdentityInventorySnapshot): Evidence[] {\n\treturn [\n\t\t...(snapshot.localDevice ? [localEvidence(snapshot.localDevice)] : []),\n\t\t...snapshot.peers.map(peerEvidence),\n\t\t...snapshot.bindings.map(bindingEvidence),\n\t\t...(snapshot.coordinator.availability === \"available\"\n\t\t\t? snapshot.coordinator.enrollments.map(enrollmentEvidence)\n\t\t\t: []),\n\t].filter((item) => clean(item.deviceId) != null);\n}\n\nfunction groups(items: Evidence[]): Evidence[][] {\n\tconst parent = items.map((_, index) => index);\n\tconst root = (index: number): number => {\n\t\tconst next = parent[index] ?? index;\n\t\tif (next === index) return index;\n\t\tparent[index] = root(next);\n\t\treturn parent[index] ?? index;\n\t};\n\tconst union = (left: number, right: number): void => {\n\t\tconst leftRoot = root(left);\n\t\tconst rightRoot = root(right);\n\t\tif (leftRoot !== rightRoot) parent[rightRoot] = leftRoot;\n\t};\n\tconst byDeviceId = new Map<string, number>();\n\tconst byFingerprint = new Map<string, number>();\n\titems.forEach((item, index) => {\n\t\tconst deviceMatch = byDeviceId.get(item.deviceId);\n\t\tif (deviceMatch == null) byDeviceId.set(item.deviceId, index);\n\t\telse union(index, deviceMatch);\n\t\tif (!item.fingerprint || item.fingerprintConflict) return;\n\t\tconst fingerprintMatch = byFingerprint.get(item.fingerprint);\n\t\tif (fingerprintMatch == null) byFingerprint.set(item.fingerprint, index);\n\t\telse union(index, fingerprintMatch);\n\t});\n\tconst grouped = new Map<number, Evidence[]>();\n\titems.forEach((item, index) => {\n\t\tconst key = root(index);\n\t\tgrouped.set(key, [...(grouped.get(key) ?? []), item]);\n\t});\n\treturn [...grouped.values()];\n}\n\nconst SOURCE_ORDER: DeviceIdentityInventorySource[] = [\n\t\"local_device\",\n\t\"identity_binding\",\n\t\"sync_peer\",\n\t\"coordinator_enrollment\",\n];\n\nfunction preferred(group: Evidence[], source: DeviceIdentityInventorySource): Evidence | null {\n\treturn group.find((item) => item.source === source) ?? null;\n}\n\nfunction preferredDisplayName(group: Evidence[]): string {\n\t// Keep missing source labels empty until projection so generated copy cannot outrank real names.\n\tfor (const source of SOURCE_ORDER) {\n\t\tconst named = group\n\t\t\t.filter(\n\t\t\t\t(item) =>\n\t\t\t\t\titem.source === source &&\n\t\t\t\t\titem.displayName.length > 0 &&\n\t\t\t\t\t![\"Canonical device\", \"Unnamed device\"].includes(item.displayName),\n\t\t\t)\n\t\t\t.toSorted(\n\t\t\t\t(left, right) =>\n\t\t\t\t\tleft.deviceId.localeCompare(right.deviceId) ||\n\t\t\t\t\tleft.displayName.localeCompare(right.displayName),\n\t\t\t)[0];\n\t\tif (named) return named.displayName;\n\t}\n\treturn \"Unnamed device\";\n}\n\nfunction inventoryState(\n\tgroup: Evidence[],\n\tfacts: { conflicted: boolean; activeBindings: Evidence[] },\n): DeviceIdentityInventoryState {\n\t// Revocation is final, so it outranks every setup or review state.\n\tif (group.some((item) => item.revoked)) return \"retired\";\n\t// Conflicting evidence stays visible for review, even for a coordinator-labeled device.\n\tif (facts.conflicted) return \"conflicted\";\n\t// Any local, peer, or binding evidence means a person-managed device, so it stays visible.\n\tif (group.every((item) => item.source === \"coordinator_enrollment\" && item.serviceDevice))\n\t\treturn \"service\";\n\tif (facts.activeBindings.length > 0) return \"configured\";\n\tconst hasPairingProof = group.some((item) => item.pairingProof);\n\tconst hasCoordinatorEvidence = group.some(\n\t\t(item) =>\n\t\t\titem.source === \"coordinator_enrollment\" ||\n\t\t\t(item.source === \"sync_peer\" && !item.pairingProof),\n\t);\n\treturn hasCoordinatorEvidence && !hasPairingProof ? \"pairing_required\" : \"setup_required\";\n}\n\n/** One unbound suggestion, never for devices that can't be set up. */\nfunction suggestedIdentity(\n\tstate: DeviceIdentityInventoryState,\n\tactiveBindings: Evidence[],\n\tsuggestedIdentityIds: Set<string>,\n): string | null {\n\tif (state === \"service\" || state === \"retired\" || activeBindings.length > 0) return null;\n\treturn suggestedIdentityIds.size === 1 ? ([...suggestedIdentityIds][0] ?? null) : null;\n}\n\n/** A binding that device removal ended is not a revoked binding that needs review. */\nfunction isRevokedBinding(item: Evidence): boolean {\n\treturn (\n\t\titem.source === \"identity_binding\" &&\n\t\titem.bindingAuthoritative &&\n\t\titem.bindingStatus !== \"active\" &&\n\t\titem.bindingStatus !== \"removed\"\n\t);\n}\n\n/** The newest rejoin among the group's enrollments; equal timestamps resolve by device ID. */\nfunction latestRejoin(group: Evidence[]): DeviceIdentityRejoinEvidenceV1 | null {\n\tconst marked = group.flatMap((item) =>\n\t\titem.rejoinedAtMs === null\n\t\t\t? []\n\t\t\t: [{ deviceId: item.deviceId, rejoinedAtMs: item.rejoinedAtMs }],\n\t);\n\treturn (\n\t\tmarked.toSorted(\n\t\t\t(left, right) =>\n\t\t\t\tright.rejoinedAtMs - left.rejoinedAtMs || left.deviceId.localeCompare(right.deviceId),\n\t\t)[0] ?? null\n\t);\n}\n\nfunction withInventoryRejoin(\n\titem: DeviceIdentityInventoryItemV1,\n\tgroup: Evidence[],\n): DeviceIdentityInventoryItemV1 {\n\tif (item.isLocal || [\"retired\", \"service\", \"conflicted\"].includes(item.state)) return item;\n\tconst rejoin = latestRejoin(group);\n\treturn rejoin ? { ...item, rejoin } : item;\n}\n\nfunction groupFingerprints(group: Evidence[]) {\n\treturn new Set(\n\t\tgroup.flatMap((item) =>\n\t\t\titem.fingerprint && !item.fingerprintConflict ? [item.fingerprint] : [],\n\t\t),\n\t);\n}\n\nfunction projectGroup(group: Evidence[]): DeviceIdentityInventoryItemV1 {\n\tconst deviceIds = [...new Set(group.map((item) => item.deviceId))].toSorted();\n\tconst fingerprints = groupFingerprints(group);\n\tconst activeBindings = group.filter(\n\t\t(item) =>\n\t\t\titem.source === \"identity_binding\" &&\n\t\t\titem.bindingAuthoritative &&\n\t\t\titem.bindingStatus === \"active\",\n\t);\n\tconst bindingIdentityIds = new Set(\n\t\tactiveBindings.flatMap((item) => (item.bindingIdentityId ? [item.bindingIdentityId] : [])),\n\t);\n\tconst suggestedIdentityIds = new Set(\n\t\tgroup.flatMap((item) => (item.suggestedIdentityId ? [item.suggestedIdentityId] : [])),\n\t);\n\tconst conflictCodes = [\n\t\tgroup.some((item) => item.fingerprintConflict) ? \"fingerprint_invalid\" : null,\n\t\tfingerprints.size > 1 ? \"fingerprint_conflict\" : null,\n\t\tbindingIdentityIds.size > 1 ? \"identity_binding_conflict\" : null,\n\t\tgroup.some(\n\t\t\t(item) =>\n\t\t\t\titem.source === \"identity_binding\" &&\n\t\t\t\titem.bindingAuthoritative &&\n\t\t\t\titem.bindingStatus === \"active\" &&\n\t\t\t\titem.bindingIdentityStatus !== \"active\",\n\t\t)\n\t\t\t? \"identity_inactive\"\n\t\t\t: null,\n\t\tgroup.some(isRevokedBinding) ? \"identity_binding_revoked\" : null,\n\t\tgroup.some(\n\t\t\t(item) => item.source === \"coordinator_enrollment\" && item.enrollmentEnabled === false,\n\t\t)\n\t\t\t? \"coordinator_enrollment_disabled\"\n\t\t\t: null,\n\t].filter((code): code is string => code != null);\n\tconst state = inventoryState(group, { conflicted: conflictCodes.length > 0, activeBindings });\n\tconst selected = SOURCE_ORDER.map((source) => preferred(group, source)).find(\n\t\t(item): item is Evidence => item != null,\n\t);\n\tconst sources = SOURCE_ORDER.filter((source) => group.some((item) => item.source === source));\n\tconst item: DeviceIdentityInventoryItemV1 = {\n\t\tversion: DEVICE_IDENTITY_INVENTORY_VERSION,\n\t\tdeviceId: selected?.deviceId ?? deviceIds[0] ?? \"\",\n\t\tevidenceDeviceIds: deviceIds,\n\t\tdisplayName: preferredDisplayName(group),\n\t\tstate,\n\t\tidentityId:\n\t\t\tstate === \"configured\" && bindingIdentityIds.size === 1\n\t\t\t\t? ([...bindingIdentityIds][0] ?? null)\n\t\t\t\t: null,\n\t\tsuggestedIdentityId: suggestedIdentity(state, activeBindings, suggestedIdentityIds),\n\t\tvalidatedFingerprint: fingerprints.size === 1 ? ([...fingerprints][0] ?? null) : null,\n\t\tisLocal: group.some((item) => item.isLocal),\n\t\tsources,\n\t\tconflictCodes: [...new Set(conflictCodes)].toSorted(),\n\t};\n\treturn withInventoryRejoin(item, group);\n}\n\nexport function projectDeviceIdentityInventory(\n\tsnapshot: DeviceIdentityInventorySnapshot,\n\toptions: { limit?: number } = {},\n): DeviceIdentityInventoryV1 {\n\tconst limit = Math.max(1, Math.min(options.limit ?? DEVICE_IDENTITY_INVENTORY_LIMIT, 2_000));\n\tconst projected = groups(evidence(snapshot))\n\t\t.map(projectGroup)\n\t\t.toSorted(\n\t\t\t(left, right) =>\n\t\t\t\tNumber(right.isLocal) - Number(left.isLocal) ||\n\t\t\t\tleft.displayName.localeCompare(right.displayName) ||\n\t\t\t\tleft.deviceId.localeCompare(right.deviceId),\n\t\t);\n\treturn {\n\t\tversion: DEVICE_IDENTITY_INVENTORY_VERSION,\n\t\titems: projected.slice(0, limit),\n\t\tcoordinatorEvidence: {\n\t\t\tavailability: snapshot.coordinator.availability,\n\t\t\tsafeErrorCode: snapshot.coordinator.safeErrorCode,\n\t\t},\n\t\ttruncated: snapshot.localEvidenceTruncated === true || projected.length > limit,\n\t};\n}\n\nfunction bindingDisplayName(value: Record<string, unknown>): string {\n\tconst name = clean(value.display_name) ?? \"\";\n\t// Historical rows record assignment provenance, not whether the label was generated.\n\tif (value.provenance === \"coordinator_enrollment\" && name === \"Enrolled device\") return \"\";\n\tif (\n\t\t[\"managed_exact_project\", \"review_resolution\"].includes(String(value.provenance)) &&\n\t\tname === \"Peer device\"\n\t)\n\t\treturn \"\";\n\treturn name;\n}\n\nfunction bindingRowEvidence(\n\tvalue: Record<string, unknown>,\n\tretired: (deviceId: string) => boolean,\n): DeviceIdentityBindingEvidence {\n\tconst deviceId = String(value.device_id ?? \"\");\n\treturn {\n\t\tdeviceId,\n\t\tdisplayName: bindingDisplayName(value),\n\t\tidentityId: String(value.identity_id ?? \"\"),\n\t\tstatus: String(value.status ?? \"\"),\n\t\tidentityStatus: clean(value.identity_status),\n\t\tretired: retired(deviceId),\n\t};\n}\n\n/** A binding that device removal ended is absent, unless it still marks a blocked device. */\nfunction bindingEvidenceRows(\n\trows: unknown[],\n\tretired: (deviceId: string) => boolean,\n): DeviceIdentityBindingEvidence[] {\n\treturn rows\n\t\t.slice(0, DEVICE_IDENTITY_EVIDENCE_LIMIT + 1)\n\t\t.map((row) => bindingRowEvidence(row as Record<string, unknown>, retired))\n\t\t.filter((binding) => binding.status !== \"removed\" || binding.retired);\n}\n\n/** Whether this device recorded an ID as retired, given the key now pinned under it. */\nfunction retiredDeviceCheck(\n\tdb: Database,\n\tpeers: DeviceIdentityPeerEvidence[],\n): (deviceId: string) => boolean {\n\tconst aliases = listRetiredDeviceAliases(db);\n\tconst pins = new Map(\n\t\tpeers.map((peer) => [\n\t\t\tpeer.deviceId,\n\t\t\t{ publicKey: peer.publicKey, fingerprint: peer.pinnedFingerprint },\n\t\t]),\n\t);\n\treturn (deviceId) => retiredAliasApplies(aliases.get(deviceId), pins.get(deviceId) ?? null);\n}\n\nexport function loadDeviceIdentityInventorySnapshot(\n\tdb: Database,\n\tinput: DeviceIdentityInventoryInput,\n): DeviceIdentityInventorySnapshot {\n\tconst localRow = db\n\t\t.prepare(\n\t\t\t`SELECT device_id, public_key, fingerprint FROM sync_device\n\t\t\t WHERE device_id = ? LIMIT 1`,\n\t\t)\n\t\t.get(input.localDeviceId) as\n\t\t| { device_id: string; public_key: string; fingerprint: string }\n\t\t| undefined;\n\tconst peerRows = db\n\t\t.prepare(\n\t\t\t`SELECT peer_device_id, name, public_key, pinned_fingerprint, actor_id,\n\t\t\t trust_provenance, claimed_local_actor\n\t\t\t FROM sync_peers ORDER BY peer_device_id LIMIT ?`,\n\t\t)\n\t\t.all(DEVICE_IDENTITY_EVIDENCE_LIMIT + 1);\n\tconst peers = peerRows\n\t\t.slice(0, DEVICE_IDENTITY_EVIDENCE_LIMIT)\n\t\t.map((row): DeviceIdentityPeerEvidence => {\n\t\t\tconst value = row as Record<string, unknown>;\n\t\t\treturn {\n\t\t\t\tdeviceId: String(value.peer_device_id ?? \"\"),\n\t\t\t\tdisplayName: clean(value.name) ?? \"\",\n\t\t\t\tpublicKey: clean(value.public_key),\n\t\t\t\tpinnedFingerprint: clean(value.pinned_fingerprint),\n\t\t\t\tsuggestedIdentityId: clean(value.actor_id),\n\t\t\t\ttrustProvenance: clean(value.trust_provenance),\n\t\t\t\tclaimedLocalActor: value.claimed_local_actor === 1,\n\t\t\t};\n\t\t});\n\tconst bindingRows = db\n\t\t.prepare(\n\t\t\t`SELECT device.device_id, device.display_name, device.identity_id, device.status, device.provenance,\n\t\t\t actor.status AS identity_status\n\t\t\t FROM identity_devices device\n\t\t\t LEFT JOIN actors actor ON actor.actor_id = device.identity_id\n\t\t\t ORDER BY CASE\n\t\t\t WHEN device.device_id = ? THEN 0\n\t\t\t WHEN device.device_id IN (\n\t\t\t SELECT peer_device_id FROM sync_peers ORDER BY peer_device_id LIMIT ?\n\t\t\t ) THEN 1\n\t\t\t ELSE 2\n\t\t\t END, device.device_id LIMIT ?`,\n\t\t)\n\t\t.all(input.localDeviceId, DEVICE_IDENTITY_EVIDENCE_LIMIT, DEVICE_IDENTITY_EVIDENCE_LIMIT + 2);\n\tconst retired = retiredDeviceCheck(db, peers);\n\tconst bindings = bindingEvidenceRows(bindingRows, retired);\n\treturn {\n\t\tlocalDevice: localRow\n\t\t\t? {\n\t\t\t\t\tdeviceId: localRow.device_id,\n\t\t\t\t\tdisplayName: clean(input.localDisplayName) ?? \"\",\n\t\t\t\t\tpublicKey: localRow.public_key,\n\t\t\t\t\tfingerprint: localRow.fingerprint,\n\t\t\t\t}\n\t\t\t: null,\n\t\tpeers: peers.map((peer) => ({ ...peer, retired: retired(peer.deviceId) })),\n\t\tbindings,\n\t\tcoordinator: input.coordinator,\n\t\tlocalEvidenceTruncated:\n\t\t\tpeerRows.length > DEVICE_IDENTITY_EVIDENCE_LIMIT ||\n\t\t\tbindingRows.length > DEVICE_IDENTITY_EVIDENCE_LIMIT + 1,\n\t};\n}\n\nexport function listDeviceIdentityInventory(\n\tdb: Database,\n\tinput: DeviceIdentityInventoryInput,\n\toptions: { limit?: number } = {},\n): DeviceIdentityInventoryV1 {\n\treturn projectDeviceIdentityInventory(loadDeviceIdentityInventorySnapshot(db, input), options);\n}\n","import type { Database } from \"./db.js\";\n\nexport interface RecipientPolicyActorEligibilityState {\n\tstatus: string;\n\tmergedIntoActorId: string | null;\n}\n\nexport function isActiveUnmergedActorState(\n\tactor: RecipientPolicyActorEligibilityState | null | undefined,\n): boolean {\n\treturn actor?.status === \"active\" && actor.mergedIntoActorId === null;\n}\n\nfunction actorEligibility(\n\tdb: Database,\n\tactorId: string,\n): (RecipientPolicyActorEligibilityState & { isLocal: boolean }) | null {\n\tconst row = db\n\t\t.prepare(\"SELECT is_local, status, merged_into_actor_id FROM actors WHERE actor_id = ? LIMIT 1\")\n\t\t.get(actorId) as\n\t\t| { is_local: number; status: string; merged_into_actor_id: string | null }\n\t\t| undefined;\n\treturn row\n\t\t? {\n\t\t\t\tisLocal: row.is_local === 1,\n\t\t\t\tstatus: row.status,\n\t\t\t\tmergedIntoActorId: row.merged_into_actor_id,\n\t\t\t}\n\t\t: null;\n}\n\nexport function isActiveUnmergedActor(db: Database, actorId: string): boolean {\n\treturn isActiveUnmergedActorState(actorEligibility(db, actorId));\n}\n\nexport function isActiveUnmergedLocalActor(db: Database, actorId: string): boolean {\n\tconst actor = actorEligibility(db, actorId);\n\treturn actor?.isLocal === true && isActiveUnmergedActorState(actor);\n}\n\nexport function activeUnmergedActorIds(db: Database): string[] {\n\treturn db\n\t\t.prepare(\n\t\t\t\"SELECT actor_id FROM actors WHERE status = 'active' AND merged_into_actor_id IS NULL ORDER BY actor_id\",\n\t\t)\n\t\t.pluck()\n\t\t.all() as string[];\n}\n\nexport function activeUnmergedActorIdsFor(db: Database, actorIds: readonly string[]): string[] {\n\tconst uniqueActorIds = [...new Set(actorIds)];\n\tif (uniqueActorIds.length === 0) return [];\n\treturn db\n\t\t.prepare(\n\t\t\t`SELECT actor_id FROM actors\n\t\t\t WHERE actor_id IN (${uniqueActorIds.map(() => \"?\").join(\", \")})\n\t\t\t AND status = 'active' AND merged_into_actor_id IS NULL\n\t\t\t ORDER BY actor_id`,\n\t\t)\n\t\t.pluck()\n\t\t.all(...uniqueActorIds) as string[];\n}\n\nexport function preferredActiveUnmergedLocalActorId(\n\tdb: Database,\n\tprimaryActorId: string,\n\tsecondaryActorId: string,\n): string | null {\n\tif (isActiveUnmergedLocalActor(db, primaryActorId)) return primaryActorId;\n\tif (secondaryActorId !== primaryActorId && isActiveUnmergedLocalActor(db, secondaryActorId)) {\n\t\treturn secondaryActorId;\n\t}\n\treturn (\n\t\t(db\n\t\t\t.prepare(\n\t\t\t\t`SELECT actor_id FROM actors\n\t\t\t\t WHERE is_local = 1 AND status = 'active' AND merged_into_actor_id IS NULL\n\t\t\t\t ORDER BY actor_id LIMIT 1`,\n\t\t\t)\n\t\t\t.pluck()\n\t\t\t.get() as string | undefined) ?? null\n\t);\n}\n","import type { Database } from \"./db.js\";\nimport {\n\ttype DeviceIdentityInventoryInput,\n\ttype DeviceIdentityInventoryItemV1,\n\tlistDeviceIdentityInventory,\n} from \"./device-identity-inventory.js\";\nimport { invalidateIncludedTeamDecisions } from \"./identity-device-assignment.js\";\nimport {\n\tisActiveUnmergedActor,\n\tisActiveUnmergedLocalActor,\n} from \"./recipient-policy-actor-eligibility.js\";\nimport {\n\tcanonicalRecipientPolicyJson,\n\tlegacyRecipientPolicyDigest,\n} from \"./recipient-policy-identifiers.js\";\nimport {\n\tcanonicalRepositoryProjectIdentity,\n\trepositoryIdentitiesByWorkspace,\n} from \"./repository-mapping-aliases.js\";\n\nexport const DEVICE_IDENTITY_BINDING_VERSION = 1 as const;\nconst BINDING_LIMIT = 100;\n\nexport interface DeviceIdentityBindingSelectionV1 {\n\tdeviceId: string;\n\ttargetIdentityId: string;\n\tconfirmed: boolean;\n\tallowRebind?: boolean;\n}\n\nexport interface DeviceIdentityBindingPreviewRequestV1 {\n\tbindings: DeviceIdentityBindingSelectionV1[];\n}\n\nexport interface DeviceIdentityBindingCommitRequestV1\n\textends DeviceIdentityBindingPreviewRequestV1 {\n\treviewedInventoryDigest: string;\n}\n\nexport type DeviceIdentityBindingActionV1 = \"bind\" | \"rebind\" | \"unchanged\";\nexport type DeviceIdentityBindingStatusV1 =\n\t| \"ready\"\n\t| \"applied\"\n\t| \"invalid\"\n\t| \"not_found\"\n\t| \"stale\"\n\t| \"conflict\";\n\nexport interface DeviceIdentityBindingOutcomeV1 {\n\tdeviceId: string;\n\tdisplayName: string;\n\ttargetIdentityId: string;\n\tpreviousIdentityId: string | null;\n\taction: DeviceIdentityBindingActionV1;\n\tisLocal: boolean;\n}\n\nexport interface DeviceIdentityBindingPreviewV1 {\n\tversion: typeof DEVICE_IDENTITY_BINDING_VERSION;\n\tstatus: Exclude<DeviceIdentityBindingStatusV1, \"applied\" | \"stale\">;\n\treviewedInventoryDigest: string;\n\terrorCode: string | null;\n\toutcomes: DeviceIdentityBindingOutcomeV1[];\n\twriteCount: number;\n}\n\nexport interface DeviceIdentityBindingCommitV1 {\n\tversion: typeof DEVICE_IDENTITY_BINDING_VERSION;\n\tstatus: Exclude<DeviceIdentityBindingStatusV1, \"ready\">;\n\treviewedInventoryDigest: string;\n\terrorCode: string | null;\n\toutcomes: DeviceIdentityBindingOutcomeV1[];\n\twriteCount: number;\n\tidempotent: boolean;\n}\n\nexport interface DeviceIdentityBindingContext {\n\tlocalActorId: string;\n\tlocalDeviceId: string;\n\tnow?: () => string;\n}\n\ninterface StoredBindingCommit {\n\trequest_json: string;\n\toutcomes_json: string;\n\twrite_count: number;\n}\n\ninterface StoredBinding {\n\tidentity_id: string;\n\tstatus: string;\n\tassignment_version: number;\n}\n\nclass BindingWriteBoundaryError extends Error {\n\tconstructor(\n\t\treadonly status: \"stale\" | \"conflict\",\n\t\treadonly errorCode: string,\n\t) {\n\t\tsuper(errorCode);\n\t}\n}\n\nconst canonicalJson = canonicalRecipientPolicyJson;\nconst digest = legacyRecipientPolicyDigest;\n\nfunction normalizedRequest(request: DeviceIdentityBindingPreviewRequestV1): string {\n\treturn canonicalJson({\n\t\tbindings: request.bindings.map((binding) => ({\n\t\t\tdeviceId: binding.deviceId,\n\t\t\ttargetIdentityId: binding.targetIdentityId,\n\t\t\tconfirmed: binding.confirmed,\n\t\t\tallowRebind: binding.allowRebind === true,\n\t\t})),\n\t});\n}\n\nfunction failure(\n\tstatus: \"invalid\" | \"not_found\" | \"conflict\",\n\terrorCode: string,\n): DeviceIdentityBindingPreviewV1 {\n\treturn {\n\t\tversion: DEVICE_IDENTITY_BINDING_VERSION,\n\t\tstatus,\n\t\treviewedInventoryDigest: \"\",\n\t\terrorCode,\n\t\toutcomes: [],\n\t\twriteCount: 0,\n\t};\n}\n\nfunction validSelection(value: DeviceIdentityBindingSelectionV1): boolean {\n\treturn (\n\t\ttypeof value?.deviceId === \"string\" &&\n\t\tvalue.deviceId.trim() === value.deviceId &&\n\t\tvalue.deviceId.length > 0 &&\n\t\ttypeof value.targetIdentityId === \"string\" &&\n\t\tvalue.targetIdentityId.trim() === value.targetIdentityId &&\n\t\tvalue.targetIdentityId.length > 0 &&\n\t\tvalue.confirmed === true &&\n\t\t(value.allowRebind === undefined || typeof value.allowRebind === \"boolean\")\n\t);\n}\n\nfunction outcome(\n\titem: DeviceIdentityInventoryItemV1,\n\tselection: DeviceIdentityBindingSelectionV1,\n\tdeviceId: string,\n): DeviceIdentityBindingOutcomeV1 | DeviceIdentityBindingPreviewV1 {\n\tif (item.state === \"service\") return failure(\"conflict\", \"device_service_role\");\n\tif (item.state === \"retired\") return failure(\"conflict\", \"device_retired\");\n\tif (item.state === \"pairing_required\") return failure(\"conflict\", \"device_pairing_required\");\n\tif (item.state === \"conflicted\") return failure(\"conflict\", \"device_evidence_conflict\");\n\tif (item.state === \"configured\" && item.identityId !== selection.targetIdentityId) {\n\t\tif (selection.allowRebind !== true) {\n\t\t\treturn failure(\"conflict\", \"device_rebind_confirmation_required\");\n\t\t}\n\t\treturn {\n\t\t\tdeviceId,\n\t\t\tdisplayName: item.displayName,\n\t\t\ttargetIdentityId: selection.targetIdentityId,\n\t\t\tpreviousIdentityId: item.identityId,\n\t\t\taction: \"rebind\",\n\t\t\tisLocal: item.isLocal,\n\t\t};\n\t}\n\treturn {\n\t\tdeviceId,\n\t\tdisplayName: item.displayName,\n\t\ttargetIdentityId: selection.targetIdentityId,\n\t\tpreviousIdentityId: item.identityId,\n\t\taction: item.state === \"configured\" ? \"unchanged\" : \"bind\",\n\t\tisLocal: item.isLocal,\n\t};\n}\n\nfunction reviewedItemEvidence(item: DeviceIdentityInventoryItemV1): Record<string, unknown> {\n\treturn {\n\t\tdeviceId: item.deviceId,\n\t\tevidenceDeviceIds: item.evidenceDeviceIds,\n\t\tstate: item.state,\n\t\tidentityId: item.identityId,\n\t\tvalidatedFingerprint: item.validatedFingerprint,\n\t\tisLocal: item.isLocal,\n\t\tsources: item.sources,\n\t\tconflictCodes: item.conflictCodes,\n\t};\n}\n\n/**\n * The bindings that device removal ended, among the devices under review. The\n * inventory leaves an ended binding out, so a device that was bound, removed,\n * and paired again looks exactly as it did before its first bind. Without this\n * evidence the new confirmation would digest to the first commit and be read as\n * a stale retry of it. The end time makes a confirmation after each removal a\n * commit of its own.\n */\nfunction endedBindingEvidence(\n\tdb: Database,\n\tselectedItems: DeviceIdentityInventoryItemV1[],\n): Array<{ deviceId: string; status: string; endedAt: string }> {\n\tconst ended = db.prepare(\n\t\t\"SELECT status, updated_at FROM identity_devices WHERE device_id = ? AND status = 'removed'\",\n\t);\n\tconst deviceIds = [...new Set(selectedItems.flatMap((item) => item.evidenceDeviceIds))];\n\treturn deviceIds.toSorted().flatMap((deviceId) => {\n\t\tconst row = ended.get(deviceId) as { status: string; updated_at: string } | undefined;\n\t\treturn row ? [{ deviceId, status: row.status, endedAt: row.updated_at }] : [];\n\t});\n}\n\nfunction reviewedDigest(\n\tdb: Database,\n\treviewed: {\n\t\tselectedItems: DeviceIdentityInventoryItemV1[];\n\t\tinventory: ReturnType<typeof listDeviceIdentityInventory>;\n\t\trequest: DeviceIdentityBindingPreviewRequestV1;\n\t},\n): string {\n\tconst endedBindings = endedBindingEvidence(db, reviewed.selectedItems);\n\treturn digest(\"device-identity-binding-preview-v1\", {\n\t\tselectedItems: reviewed.selectedItems.map(reviewedItemEvidence),\n\t\tcoordinatorAvailability: reviewed.inventory.coordinatorEvidence.availability,\n\t\tinventoryTruncated: reviewed.inventory.truncated,\n\t\trequest: JSON.parse(normalizedRequest(reviewed.request)),\n\t\t// Present only when a binding ended, so every other digest is what it was before.\n\t\t...(endedBindings.length > 0 ? { endedBindings } : {}),\n\t});\n}\n\nexport function previewDeviceIdentityBindings(\n\tdb: Database,\n\tinventoryInput: DeviceIdentityInventoryInput,\n\trequest: DeviceIdentityBindingPreviewRequestV1,\n): DeviceIdentityBindingPreviewV1 {\n\tif (\n\t\t!request ||\n\t\t!Array.isArray(request.bindings) ||\n\t\trequest.bindings.length === 0 ||\n\t\trequest.bindings.length > BINDING_LIMIT ||\n\t\trequest.bindings.some((binding) => !validSelection(binding))\n\t) {\n\t\treturn failure(\"invalid\", \"binding_request_invalid\");\n\t}\n\tconst deviceIds = request.bindings.map((binding) => binding.deviceId);\n\tif (new Set(deviceIds).size !== deviceIds.length) {\n\t\treturn failure(\"invalid\", \"duplicate_device_id\");\n\t}\n\tconst inventory = listDeviceIdentityInventory(db, inventoryInput);\n\tif (inventory.truncated) return failure(\"conflict\", \"device_inventory_truncated\");\n\tconst inventoryByDeviceId = new Map(inventory.items.map((item) => [item.deviceId, item]));\n\tconst selectedItems: DeviceIdentityInventoryItemV1[] = [];\n\tfor (const selection of request.bindings) {\n\t\tconst item = inventoryByDeviceId.get(selection.deviceId);\n\t\tif (!item) return failure(\"not_found\", \"device_not_found\");\n\t\tselectedItems.push(item);\n\t}\n\tif (inventory.coordinatorEvidence.availability !== \"available\") {\n\t\tconst localOnlyWithoutCoordinator =\n\t\t\tinventory.coordinatorEvidence.safeErrorCode === \"coordinator_not_configured\" &&\n\t\t\tselectedItems.every((item) => item.isLocal);\n\t\tif (!localOnlyWithoutCoordinator) {\n\t\t\treturn failure(\"conflict\", \"device_inventory_incomplete\");\n\t\t}\n\t}\n\tconst outcomes: DeviceIdentityBindingOutcomeV1[] = [];\n\tfor (const [index, selection] of request.bindings.entries()) {\n\t\tif (!isActiveUnmergedActor(db, selection.targetIdentityId)) {\n\t\t\treturn failure(\"not_found\", \"target_identity_unavailable\");\n\t\t}\n\t\tconst item = selectedItems[index];\n\t\tif (!item) return failure(\"not_found\", \"device_not_found\");\n\t\tlet authoritativeDeviceId = item.deviceId;\n\t\tif (item.state === \"configured\") {\n\t\t\tconst activeBindingDeviceIds = item.evidenceDeviceIds.filter(\n\t\t\t\t(deviceId) => currentBinding(db, deviceId)?.status === \"active\",\n\t\t\t);\n\t\t\tif (activeBindingDeviceIds.length !== 1) {\n\t\t\t\treturn failure(\"conflict\", \"device_evidence_conflict\");\n\t\t\t}\n\t\t\tauthoritativeDeviceId = activeBindingDeviceIds[0] ?? item.deviceId;\n\t\t}\n\t\tconst planned = outcome(item, selection, authoritativeDeviceId);\n\t\tif (\"status\" in planned) return planned;\n\t\toutcomes.push(planned);\n\t}\n\tconst reviewedInventoryDigest = reviewedDigest(db, { selectedItems, inventory, request });\n\treturn {\n\t\tversion: DEVICE_IDENTITY_BINDING_VERSION,\n\t\tstatus: \"ready\",\n\t\treviewedInventoryDigest,\n\t\terrorCode: null,\n\t\toutcomes,\n\t\twriteCount: outcomes.filter((item) => item.action !== \"unchanged\").length,\n\t};\n}\n\nfunction currentBinding(db: Database, deviceId: string): StoredBinding | undefined {\n\treturn db\n\t\t.prepare(\n\t\t\t`SELECT identity_id, status, assignment_version FROM identity_devices\n\t\t\t WHERE device_id = ?`,\n\t\t)\n\t\t.get(deviceId) as StoredBinding | undefined;\n}\n\nfunction exactRetry(\n\tdb: Database,\n\tinventoryInput: DeviceIdentityInventoryInput,\n\tcommitDigest: string,\n\trequestJson: string,\n\trequest: DeviceIdentityBindingCommitRequestV1,\n): DeviceIdentityBindingCommitV1 | null {\n\tconst stored = db\n\t\t.prepare(\n\t\t\t`SELECT request_json, outcomes_json, write_count\n\t\t\t FROM device_identity_binding_commits WHERE commit_digest = ?`,\n\t\t)\n\t\t.get(commitDigest) as StoredBindingCommit | undefined;\n\tif (!stored) return null;\n\tif (stored.request_json !== requestJson) {\n\t\treturn {\n\t\t\t...failure(\"conflict\", \"binding_commit_conflict\"),\n\t\t\tstatus: \"conflict\",\n\t\t\treviewedInventoryDigest: request.reviewedInventoryDigest,\n\t\t\tidempotent: false,\n\t\t};\n\t}\n\tconst outcomes = JSON.parse(stored.outcomes_json) as DeviceIdentityBindingOutcomeV1[];\n\tconst stillApplied = outcomes.every((item) => {\n\t\tconst binding = currentBinding(db, item.deviceId);\n\t\treturn (\n\t\t\tbinding?.status === \"active\" &&\n\t\t\tbinding.identity_id === item.targetIdentityId &&\n\t\t\tisActiveUnmergedActor(db, item.targetIdentityId)\n\t\t);\n\t});\n\tif (!stillApplied) {\n\t\treturn {\n\t\t\tversion: DEVICE_IDENTITY_BINDING_VERSION,\n\t\t\tstatus: \"stale\",\n\t\t\treviewedInventoryDigest: request.reviewedInventoryDigest,\n\t\t\terrorCode: \"binding_retry_stale\",\n\t\t\toutcomes: [],\n\t\t\twriteCount: 0,\n\t\t\tidempotent: false,\n\t\t};\n\t}\n\tconst revalidated = previewDeviceIdentityBindings(db, inventoryInput, request);\n\tif (\n\t\trevalidated.status === \"invalid\" ||\n\t\trevalidated.status === \"not_found\" ||\n\t\trevalidated.status === \"conflict\"\n\t) {\n\t\treturn {\n\t\t\t...revalidated,\n\t\t\tstatus: revalidated.status,\n\t\t\treviewedInventoryDigest: request.reviewedInventoryDigest,\n\t\t\tidempotent: false,\n\t\t};\n\t}\n\tif (revalidated.outcomes.some((item) => item.action !== \"unchanged\")) {\n\t\treturn {\n\t\t\tversion: DEVICE_IDENTITY_BINDING_VERSION,\n\t\t\tstatus: \"stale\",\n\t\t\treviewedInventoryDigest: request.reviewedInventoryDigest,\n\t\t\terrorCode: \"binding_retry_stale\",\n\t\t\toutcomes: [],\n\t\t\twriteCount: 0,\n\t\t\tidempotent: false,\n\t\t};\n\t}\n\treturn {\n\t\tversion: DEVICE_IDENTITY_BINDING_VERSION,\n\t\tstatus: \"applied\",\n\t\treviewedInventoryDigest: request.reviewedInventoryDigest,\n\t\terrorCode: null,\n\t\toutcomes,\n\t\twriteCount: 0,\n\t\tidempotent: true,\n\t};\n}\n\ninterface BindingRowValues {\n\trevision: string;\n\tcommitDigest: string;\n\tidempotencyKey: string;\n\tnow: string;\n}\n\nexport interface EndedBindingReactivation {\n\tdeviceId: string;\n\ttargetIdentityId: string;\n\tdisplayName: string;\n\tprovenance: string;\n\trevision: string;\n\tmigrationState: string;\n\tsourceFingerprint: string | null;\n\tidempotencyKey: string;\n\tnow: string;\n}\n\n/**\n * The one write that makes a binding that device removal ended active again.\n * Its callers are an explicit bind in Devices, a coordinator enrollment the\n * current snapshot lists, and an invitation the device just accepted. The row\n * is reused, so per-Team decisions for the same Identity still apply. A\n * different Identity raises `assignment_version` through the table's trigger\n * and returns reviewed-Team inclusions to unresolved, as any reassignment does.\n * Returns null when the device has no ended binding.\n */\nexport function reactivateEndedBindingInTransaction(\n\tdb: Database,\n\tinput: EndedBindingReactivation,\n): { assignmentVersion: number; previousIdentityId: string } | null {\n\tif (!db.inTransaction) throw new Error(\"binding_reactivation_transaction_required\");\n\tconst ended = currentBinding(db, input.deviceId);\n\tif (ended?.status !== \"removed\") return null;\n\tdb.prepare(\n\t\t`UPDATE identity_devices SET identity_id = ?, display_name = ?, status = 'active',\n\t\t provenance = ?, revision = ?, migration_state = ?, source_fingerprint = ?,\n\t\t idempotency_key = ?, updated_at = ?\n\t\t WHERE device_id = ? AND status = 'removed'`,\n\t).run(\n\t\tinput.targetIdentityId,\n\t\tinput.displayName,\n\t\tinput.provenance,\n\t\tinput.revision,\n\t\tinput.migrationState,\n\t\tinput.sourceFingerprint,\n\t\tinput.idempotencyKey,\n\t\tinput.now,\n\t\tinput.deviceId,\n\t);\n\tif (ended.identity_id !== input.targetIdentityId) {\n\t\tinvalidateIncludedTeamDecisions(db, input.deviceId, input.now);\n\t}\n\tconst assignmentVersion = currentBinding(db, input.deviceId)?.assignment_version ?? 0;\n\twakeRecipientPoliciesForIdentities(db, [ended.identity_id, input.targetIdentityId], input.now);\n\treturn { assignmentVersion, previousIdentityId: ended.identity_id };\n}\n\n/** Binds a device that has no binding, or only one that device removal ended. */\nfunction bindDevice(\n\tdb: Database,\n\toutcome: DeviceIdentityBindingOutcomeV1,\n\tbefore: StoredBinding | undefined,\n\trow: BindingRowValues,\n): void {\n\tif (before && before.status !== \"removed\") {\n\t\tthrow new BindingWriteBoundaryError(\"conflict\", \"binding_write_conflict\");\n\t}\n\tif (before) {\n\t\tconst reactivated = reactivateEndedBindingInTransaction(db, {\n\t\t\tdeviceId: outcome.deviceId,\n\t\t\ttargetIdentityId: outcome.targetIdentityId,\n\t\t\tdisplayName: outcome.displayName,\n\t\t\tprovenance: \"user_confirmed_identity_setup\",\n\t\t\trevision: row.revision,\n\t\t\tmigrationState: \"user_managed\",\n\t\t\tsourceFingerprint: row.commitDigest,\n\t\t\tidempotencyKey: row.idempotencyKey,\n\t\t\tnow: row.now,\n\t\t});\n\t\tif (!reactivated) throw new BindingWriteBoundaryError(\"stale\", \"binding_write_stale\");\n\t\treturn;\n\t}\n\tdb.prepare(\n\t\t`INSERT INTO identity_devices(\n\t\t device_id, identity_id, display_name, status, provenance, revision, migration_state,\n\t\t source_fingerprint, idempotency_key, created_at, updated_at\n\t\t ) VALUES (?, ?, ?, 'active', 'user_confirmed_identity_setup', ?, 'user_managed', ?, ?, ?, ?)`,\n\t).run(\n\t\toutcome.deviceId,\n\t\toutcome.targetIdentityId,\n\t\toutcome.displayName,\n\t\trow.revision,\n\t\trow.commitDigest,\n\t\trow.idempotencyKey,\n\t\trow.now,\n\t\trow.now,\n\t);\n}\n\nfunction writeBinding(\n\tdb: Database,\n\tcontext: DeviceIdentityBindingContext,\n\tcommitDigest: string,\n\toutcome: DeviceIdentityBindingOutcomeV1,\n\tnow: string,\n): void {\n\tconst before = currentBinding(db, outcome.deviceId);\n\tif (\n\t\toutcome.action === \"rebind\" &&\n\t\t(before?.status !== \"active\" || before.identity_id !== outcome.previousIdentityId)\n\t) {\n\t\tthrow new BindingWriteBoundaryError(\"stale\", \"binding_rebind_stale\");\n\t}\n\tif (\n\t\toutcome.action === \"unchanged\" &&\n\t\t(before?.status !== \"active\" || before.identity_id !== outcome.targetIdentityId)\n\t) {\n\t\tthrow new BindingWriteBoundaryError(\"stale\", \"binding_unchanged_stale\");\n\t}\n\tconst revision = digest(\"device-identity-binding-revision-v1\", [commitDigest, outcome.deviceId]);\n\tconst idempotencyKey = digest(\"device-identity-binding-row-v1\", [commitDigest, outcome.deviceId]);\n\tif (outcome.action === \"rebind\") {\n\t\tconst updated = db\n\t\t\t.prepare(\n\t\t\t\t`UPDATE identity_devices SET identity_id = ?, status = 'active',\n\t\t\t provenance = 'user_confirmed_identity_setup', revision = ?, migration_state = 'user_managed',\n\t\t\t source_fingerprint = ?, idempotency_key = ?, updated_at = ?\n\t\t\t WHERE device_id = ? AND identity_id = ? AND status = 'active'`,\n\t\t\t)\n\t\t\t.run(\n\t\t\t\toutcome.targetIdentityId,\n\t\t\t\trevision,\n\t\t\t\tcommitDigest,\n\t\t\t\tidempotencyKey,\n\t\t\t\tnow,\n\t\t\t\toutcome.deviceId,\n\t\t\t\toutcome.previousIdentityId,\n\t\t\t);\n\t\tif (updated.changes !== 1) {\n\t\t\tthrow new BindingWriteBoundaryError(\"stale\", \"binding_rebind_stale\");\n\t\t}\n\t} else if (outcome.action === \"bind\") {\n\t\tbindDevice(db, outcome, before, { revision, commitDigest, idempotencyKey, now });\n\t}\n\tconst after = currentBinding(db, outcome.deviceId);\n\tif (after?.status !== \"active\" || after.identity_id !== outcome.targetIdentityId) {\n\t\tthrow new BindingWriteBoundaryError(\"stale\", \"binding_write_stale\");\n\t}\n\tdb.prepare(\n\t\t`INSERT INTO device_identity_binding_audit(\n\t\t event_id, commit_digest, device_id, previous_identity_id, target_identity_id,\n\t\t action, previous_assignment_version, resulting_assignment_version,\n\t\t decided_by_identity_id, decided_by_device_id, created_at\n\t\t ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n\t).run(\n\t\tdigest(\"device-identity-binding-event-v1\", [commitDigest, outcome.deviceId]),\n\t\tcommitDigest,\n\t\toutcome.deviceId,\n\t\tbefore?.identity_id ?? null,\n\t\toutcome.targetIdentityId,\n\t\toutcome.action,\n\t\tbefore?.assignment_version ?? null,\n\t\tafter.assignment_version,\n\t\tcontext.localActorId,\n\t\tcontext.localDeviceId,\n\t\tnow,\n\t);\n}\n\nexport function wakeRecipientPoliciesForIdentities(\n\tdb: Database,\n\tidentityIds: Iterable<string>,\n\tnow: string,\n): void {\n\tconst projects = db.prepare(\n\t\t`SELECT DISTINCT recipient.canonical_project_identity\n\t\t FROM project_recipients recipient\n\t\t WHERE recipient.status = 'active'\n\t\t AND (\n\t\t (recipient.recipient_kind = 'identity' AND recipient.recipient_id = ?)\n\t\t OR (recipient.recipient_kind = 'team' AND recipient.recipient_id IN (\n\t\t SELECT membership.team_id\n\t\t FROM policy_team_memberships membership\n\t\t JOIN policy_teams team ON team.team_id = membership.team_id\n\t\t WHERE membership.identity_id = ? AND team.status = 'active'\n\t\t AND (\n\t\t (team.device_eligibility_mode = 'person_all_devices' AND membership.status = 'active')\n\t\t OR (team.device_eligibility_mode = 'reviewed_allowlist'\n\t\t AND membership.status = 'reviewed_active')\n\t\t )\n\t\t ))\n\t\t )`,\n\t);\n\tconst projectIdentities = new Set<string>();\n\tfor (const identityId of new Set(identityIds)) {\n\t\tfor (const projectId of projects.pluck().all(identityId, identityId) as string[]) {\n\t\t\tprojectIdentities.add(projectId);\n\t\t}\n\t}\n\twakeRecipientPoliciesForProjectIdentities(db, projectIdentities, now);\n}\n\nexport function wakeRecipientPoliciesForProjectIdentities(\n\tdb: Database,\n\tprojectIdentities: Iterable<string>,\n\t_now: string,\n): void {\n\tconst requested = [...projectIdentities];\n\tif (requested.length === 0) return;\n\tconst repositoryIdentities = repositoryIdentitiesByWorkspace(db);\n\tconst targets = new Set(\n\t\trequested.map((identity) => canonicalRepositoryProjectIdentity(repositoryIdentities, identity)),\n\t);\n\tconst authorityIds = db\n\t\t.prepare(\"SELECT canonical_project_identity FROM recipient_policy_authority_states\")\n\t\t.pluck()\n\t\t.all() as string[];\n\tconst wake = db.prepare(\n\t\t`UPDATE recipient_policy_authority_states\n\t\t SET last_attempt_at = NULL, wake_epoch = wake_epoch + 1\n\t\t WHERE canonical_project_identity = ?`,\n\t);\n\tfor (const authorityId of authorityIds) {\n\t\tconst canonical = canonicalRepositoryProjectIdentity(repositoryIdentities, authorityId);\n\t\tif (targets.has(canonical)) wake.run(authorityId);\n\t}\n}\n\nfunction wakePoliciesForBindingChanges(\n\tdb: Database,\n\toutcomes: DeviceIdentityBindingOutcomeV1[],\n\tnow: string,\n): void {\n\tconst changedIdentities = new Set<string>();\n\tfor (const outcome of outcomes) {\n\t\tif (outcome.action === \"unchanged\") continue;\n\t\tif (outcome.previousIdentityId) changedIdentities.add(outcome.previousIdentityId);\n\t\tchangedIdentities.add(outcome.targetIdentityId);\n\t}\n\twakeRecipientPoliciesForIdentities(db, changedIdentities, now);\n}\n\nfunction commitInTransaction(\n\tdb: Database,\n\tcontext: DeviceIdentityBindingContext,\n\tinventoryInput: DeviceIdentityInventoryInput,\n\trequest: DeviceIdentityBindingCommitRequestV1,\n): DeviceIdentityBindingCommitV1 {\n\tif (typeof request.reviewedInventoryDigest !== \"string\" || !request.reviewedInventoryDigest) {\n\t\treturn {\n\t\t\t...failure(\"invalid\", \"reviewed_inventory_digest_required\"),\n\t\t\tstatus: \"invalid\",\n\t\t\tidempotent: false,\n\t\t};\n\t}\n\tconst requestJson = normalizedRequest(request);\n\tconst commitDigest = digest(\"device-identity-binding-commit-v1\", {\n\t\trequest: JSON.parse(requestJson),\n\t\treviewedInventoryDigest: request.reviewedInventoryDigest,\n\t});\n\tconst retry = exactRetry(db, inventoryInput, commitDigest, requestJson, request);\n\tif (retry) return retry;\n\tconst preview = previewDeviceIdentityBindings(db, inventoryInput, request);\n\tif (preview.status !== \"ready\") {\n\t\treturn { ...preview, status: preview.status, idempotent: false };\n\t}\n\tif (preview.reviewedInventoryDigest !== request.reviewedInventoryDigest) {\n\t\treturn {\n\t\t\t...preview,\n\t\t\tstatus: \"stale\",\n\t\t\terrorCode: \"binding_evidence_stale\",\n\t\t\twriteCount: 0,\n\t\t\tidempotent: false,\n\t\t};\n\t}\n\tif (!isActiveUnmergedLocalActor(db, context.localActorId)) {\n\t\treturn {\n\t\t\t...preview,\n\t\t\tstatus: \"invalid\",\n\t\t\terrorCode: \"deciding_identity_unavailable\",\n\t\t\twriteCount: 0,\n\t\t\tidempotent: false,\n\t\t};\n\t}\n\tconst now = (context.now ?? (() => new Date().toISOString()))();\n\tdb.prepare(\n\t\t`INSERT INTO device_identity_binding_commits(\n\t\t commit_digest, reviewed_inventory_digest, request_json, outcomes_json, write_count,\n\t\t decided_by_identity_id, decided_by_device_id, created_at\n\t\t ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n\t).run(\n\t\tcommitDigest,\n\t\trequest.reviewedInventoryDigest,\n\t\trequestJson,\n\t\tcanonicalJson(preview.outcomes),\n\t\tpreview.writeCount,\n\t\tcontext.localActorId,\n\t\tcontext.localDeviceId,\n\t\tnow,\n\t);\n\tfor (const item of preview.outcomes) writeBinding(db, context, commitDigest, item, now);\n\twakePoliciesForBindingChanges(db, preview.outcomes, now);\n\treturn {\n\t\t...preview,\n\t\tstatus: \"applied\",\n\t\tidempotent: false,\n\t};\n}\n\nexport function commitDeviceIdentityBindings(\n\tdb: Database,\n\tcontext: DeviceIdentityBindingContext,\n\tinventoryInput: DeviceIdentityInventoryInput,\n\trequest: DeviceIdentityBindingCommitRequestV1,\n): DeviceIdentityBindingCommitV1 {\n\ttry {\n\t\treturn db\n\t\t\t.transaction(() => commitInTransaction(db, context, inventoryInput, request))\n\t\t\t.immediate();\n\t} catch (error) {\n\t\tif (error instanceof BindingWriteBoundaryError) {\n\t\t\treturn {\n\t\t\t\tversion: DEVICE_IDENTITY_BINDING_VERSION,\n\t\t\t\tstatus: error.status,\n\t\t\t\treviewedInventoryDigest: request.reviewedInventoryDigest ?? \"\",\n\t\t\t\terrorCode: error.errorCode,\n\t\t\t\toutcomes: [],\n\t\t\t\twriteCount: 0,\n\t\t\t\tidempotent: false,\n\t\t\t};\n\t\t}\n\t\tconst code =\n\t\t\terror && typeof error === \"object\" && \"code\" in error\n\t\t\t\t? String((error as { code?: unknown }).code ?? \"\")\n\t\t\t\t: \"\";\n\t\tif (code.startsWith(\"SQLITE_CONSTRAINT\")) {\n\t\t\treturn {\n\t\t\t\t...failure(\"conflict\", \"binding_commit_conflict\"),\n\t\t\t\tstatus: \"conflict\",\n\t\t\t\treviewedInventoryDigest: request.reviewedInventoryDigest ?? \"\",\n\t\t\t\tidempotent: false,\n\t\t\t};\n\t\t}\n\t\tthrow error;\n\t}\n}\n","import { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { CoordinatorSyncConfig } from \"./coordinator-sync-config.js\";\nimport type { Database } from \"./db.js\";\nimport { readPeerRemovalCheckState } from \"./peer-removal-check-state.js\";\nimport type { MemoryStore } from \"./store.js\";\nimport { buildAuthHeaders } from \"./sync-auth.js\";\nimport { buildBaseUrl, requestJson } from \"./sync-http-client.js\";\n\n/** Matches the coordinator's per-request limit on `/v1/peers/revocations`. */\nconst CHECK_BATCH_SIZE = 25;\n\n/** `unsupported` means the coordinator predates the check; `failed` means the answer was unusable. */\nexport type PeerRevocationCheckStatus = \"checked\" | \"unsupported\" | \"failed\";\n\n/** A device this device asks the coordinator about. A binding without a pairing has no key to send. */\nexport interface PeerRemovalLookupEntry {\n\tdevice_id: string;\n\tpublic_key?: string;\n}\n\nexport interface PeerRemovalLookup {\n\tstatus: PeerRevocationCheckStatus;\n\t/** IDs this device sent that the coordinator blocked. Never also in `removed`. */\n\trevoked: string[];\n\t/** IDs this device sent that the coordinator removed. */\n\tremoved: string[];\n\t/** IDs this device sent that the coordinator holds any enrollment for. */\n\tenrolled: string[];\n\t/**\n\t * The lowest `removal_seq` among the replies of a lookup that every batch\n\t * answered and that left out no pairing or binding. Otherwise null.\n\t */\n\tremovalSeq: number | null;\n\t/** The local counter value read in the same transaction as the entries. */\n\tgeneration: number | null;\n\t/** Groups that answered this device's signed request with `403 device_removed`. */\n\tremovedFromGroups: string[];\n}\n\n/** What the coordinator says about one device, or that it gave no usable answer. */\nexport type PeerRemovalAnswer =\n\t| { answered: true; enrolled: boolean; removed: boolean; revoked: boolean }\n\t| { answered: false };\n\nclass CheckStatusError extends Error {\n\tconstructor(readonly status: number) {\n\t\tsuper(`peer revocation check failed (${status})`);\n\t}\n}\n\ninterface PeerRemovalReply {\n\trevoked: string[];\n\tremoved: string[];\n\tenrolled: string[];\n\tremovalSeq: number;\n}\n\ntype StoreLike = Pick<MemoryStore, \"db\" | \"dbPath\">;\ntype SignedRequest = {\n\tlocalDeviceId: string;\n\tgroupId: string;\n\tkeysDir?: string;\n\tremovedFromGroups?: string[];\n};\n\n/** The stored key when the coordinator would accept it. Otherwise the device is asked about by ID only. */\nfunction usableKey(publicKey: string | null | undefined): string | undefined {\n\tif (typeof publicKey !== \"string\" || publicKey.trim() === \"\") return undefined;\n\treturn publicKey.length <= 4096 && !publicKey.includes(\"\\0\") ? publicKey : undefined;\n}\n\nfunction lookupEntry(deviceId: string, publicKey?: string | null): PeerRemovalLookupEntry {\n\tconst key = usableKey(publicKey);\n\treturn key === undefined ? { device_id: deviceId } : { device_id: deviceId, public_key: key };\n}\n\n/**\n * One entry for every pairing and every device with an active binding, by device\n * ID. A pairing sends its key when it has a usable one. `omitted` is true when a\n * device ID fails the coordinator's identifier rule: sending it would fail the\n * whole batch, so it is left out, and the lookup then covers less than this\n * device holds.\n */\nfunction lookupEntries(\n\tdb: Database,\n\tlocalDeviceId: string,\n): { entries: PeerRemovalLookupEntry[]; omitted: boolean } {\n\tconst pairings = db\n\t\t.prepare(\n\t\t\t`SELECT peer_device_id, public_key FROM sync_peers\n\t\t\t WHERE peer_device_id IS NOT ? ORDER BY peer_device_id`,\n\t\t)\n\t\t.all(localDeviceId) as Array<{ peer_device_id: unknown; public_key: string | null }>;\n\tconst keys = new Map(pairings.map((row) => [row.peer_device_id, row.public_key]));\n\tconst bound = db\n\t\t.prepare(\n\t\t\t`SELECT device_id FROM identity_devices\n\t\t\t WHERE status = 'active' AND device_id IS NOT ? ORDER BY device_id`,\n\t\t)\n\t\t.pluck()\n\t\t.all(localDeviceId) as unknown[];\n\tconst deviceIds = [...keys.keys(), ...bound.filter((deviceId) => !keys.has(deviceId))];\n\tconst entries = deviceIds\n\t\t.filter((deviceId) => isAuthControllerId(deviceId))\n\t\t.map((deviceId) => lookupEntry(deviceId, keys.get(deviceId)));\n\treturn { entries, omitted: entries.length !== deviceIds.length };\n}\n\n/** The reply's IDs among those this device asked about. Anything else in the array is ignored. */\nfunction sentIds(value: unknown[], sent: Set<string>): string[] {\n\treturn value.filter((id): id is string => typeof id === \"string\" && sent.has(id));\n}\n\n/** A reply without all three arrays and the integer is invalid, and the caller keeps every pairing. */\nfunction parseReply(\n\tresponse: Record<string, unknown> | null,\n\tentries: PeerRemovalLookupEntry[],\n): PeerRemovalReply {\n\tconst { version, revoked, removed, enrolled, removal_seq: removalSeq } = response ?? {};\n\tif (\n\t\tversion !== 1 ||\n\t\t!Array.isArray(revoked) ||\n\t\t!Array.isArray(removed) ||\n\t\t!Array.isArray(enrolled) ||\n\t\t!Number.isSafeInteger(removalSeq) ||\n\t\t(removalSeq as number) < 0\n\t)\n\t\tthrow new Error(\"peer_revocation_response_invalid\");\n\tconst sent = new Set(entries.map((entry) => entry.device_id));\n\tconst blocked = sentIds(revoked, sent);\n\treturn {\n\t\trevoked: blocked,\n\t\t// A block outranks a removal when a reply lists an ID in both.\n\t\tremoved: sentIds(removed, sent).filter((id) => !blocked.includes(id)),\n\t\tenrolled: sentIds(enrolled, sent),\n\t\tremovalSeq: removalSeq as number,\n\t};\n}\n\nasync function checkBatch(\n\tstore: StoreLike,\n\tconfig: CoordinatorSyncConfig,\n\trequest: SignedRequest,\n\tentries: PeerRemovalLookupEntry[],\n): Promise<PeerRemovalReply> {\n\tconst body = { peers: entries };\n\tconst bodyBytes = Buffer.from(JSON.stringify(body), \"utf8\");\n\tconst url = `${buildBaseUrl(config.syncCoordinatorUrl)}/v1/peers/revocations?group_id=${encodeURIComponent(request.groupId)}`;\n\tconst headers = buildAuthHeaders({\n\t\tdeviceId: request.localDeviceId,\n\t\tdbPath: store.dbPath,\n\t\tmethod: \"POST\",\n\t\turl,\n\t\tbodyBytes,\n\t\tkeysDir: request.keysDir,\n\t});\n\tconst [status, response] = await requestJson(\"POST\", url, {\n\t\theaders,\n\t\tbody,\n\t\tbodyBytes,\n\t\ttimeoutS: Math.max(1, config.syncCoordinatorTimeoutS),\n\t});\n\tif (status === 403 && response?.error === \"device_removed\")\n\t\trequest.removedFromGroups?.push(request.groupId);\n\tif (status !== 200) throw new CheckStatusError(status);\n\treturn parseReply(response, entries);\n}\n\ntype FirstAnswer =\n\t| { kind: \"answered\"; groupId: string; reply: PeerRemovalReply }\n\t| { kind: \"unsupported\" }\n\t| { kind: \"refused\" };\n\n/**\n * How one group turned the check away. A disabled, removed, or archived\n * enrollment in a group still leaves the others, so those answers let the caller\n * try the next group. Any other failure is `failed`, and the caller ends the lookup.\n */\nfunction groupRefusal(error: unknown): \"unsupported\" | \"refused\" | \"failed\" {\n\tif (!(error instanceof CheckStatusError)) return \"failed\";\n\tif (error.status === 404) return \"unsupported\";\n\tif (error.status !== 401 && error.status !== 403 && error.status !== 409) return \"failed\";\n\treturn \"refused\";\n}\n\n/** Finds an authorized group, recording confirmed removals even if a later request fails. */\nasync function firstAuthorizedGroup(\n\tstore: StoreLike,\n\tconfig: CoordinatorSyncConfig,\n\toptions: { localDeviceId: string; keysDir?: string },\n\tfirstBatch: PeerRemovalLookupEntry[],\n\tremovedFromGroups?: string[],\n): Promise<FirstAnswer> {\n\tfor (const groupId of config.syncCoordinatorGroups) {\n\t\ttry {\n\t\t\tconst reply = await checkBatch(\n\t\t\t\tstore,\n\t\t\t\tconfig,\n\t\t\t\t{ ...options, groupId, removedFromGroups },\n\t\t\t\tfirstBatch,\n\t\t\t);\n\t\t\treturn { kind: \"answered\", groupId, reply };\n\t\t} catch (error) {\n\t\t\tconst refusal = groupRefusal(error);\n\t\t\tif (refusal === \"failed\") throw error;\n\t\t\tif (refusal === \"unsupported\") return { kind: \"unsupported\" };\n\t\t}\n\t}\n\treturn { kind: \"refused\" };\n}\n\nfunction batchesOf(entries: PeerRemovalLookupEntry[]): PeerRemovalLookupEntry[][] {\n\t// A device with nothing to ask about still sends one request, to learn `removal_seq`.\n\tif (entries.length === 0) return [[]];\n\tconst batches: PeerRemovalLookupEntry[][] = [];\n\tfor (let start = 0; start < entries.length; start += CHECK_BATCH_SIZE) {\n\t\tbatches.push(entries.slice(start, start + CHECK_BATCH_SIZE));\n\t}\n\treturn batches;\n}\n\nfunction unanswered(\n\tstatus: PeerRevocationCheckStatus,\n\tgeneration: number | null,\n\tremovedFromGroups: string[] = [],\n): PeerRemovalLookup {\n\treturn {\n\t\tstatus,\n\t\trevoked: [],\n\t\tremoved: [],\n\t\tenrolled: [],\n\t\tremovalSeq: null,\n\t\tgeneration,\n\t\tremovedFromGroups,\n\t};\n}\n\n/**\n * Asks the coordinator which of this device's pairings and bound devices it has\n * blocked, removed, or still holds an enrollment for. Any failure keeps every\n * pairing: the lists are empty and `removalSeq` is null unless every batch\n * returned a valid reply. It changes no local state.\n */\nexport async function fetchPeerRemovalLookup(\n\tstore: StoreLike,\n\tconfig: CoordinatorSyncConfig,\n\toptions: { localDeviceId: string; keysDir?: string },\n): Promise<PeerRemovalLookup> {\n\t// One read transaction, so the counter describes exactly these entries.\n\tconst { entries, omitted, generation } = store.db.transaction(() => ({\n\t\t...lookupEntries(store.db, options.localDeviceId),\n\t\tgeneration: readPeerRemovalCheckState(store.db)?.generation ?? null,\n\t}))();\n\tconst removedFromGroups: string[] = [];\n\ttry {\n\t\tconst [firstBatch = [], ...laterBatches] = batchesOf(entries);\n\t\tconst first = await firstAuthorizedGroup(store, config, options, firstBatch, removedFromGroups);\n\t\tif (first.kind === \"unsupported\")\n\t\t\treturn unanswered(\"unsupported\", generation, removedFromGroups);\n\t\tif (first.kind === \"refused\") return unanswered(\"failed\", generation, removedFromGroups);\n\t\tconst replies = [first.reply];\n\t\tconst request = { ...options, groupId: first.groupId, removedFromGroups };\n\t\tfor (const batch of laterBatches) {\n\t\t\treplies.push(await checkBatch(store, config, request, batch));\n\t\t}\n\t\treturn {\n\t\t\tstatus: \"checked\",\n\t\t\trevoked: replies.flatMap((reply) => reply.revoked),\n\t\t\tremoved: replies.flatMap((reply) => reply.removed),\n\t\t\tenrolled: replies.flatMap((reply) => reply.enrolled),\n\t\t\t// A removal recorded between two requests is above the lowest number, so it is not counted.\n\t\t\t// With a pairing or binding left out, no number describes everything this device holds.\n\t\t\tremovalSeq: omitted ? null : Math.min(...replies.map((reply) => reply.removalSeq)),\n\t\t\tgeneration,\n\t\t\tremovedFromGroups: [],\n\t\t};\n\t} catch {\n\t\treturn unanswered(\"failed\", generation, removedFromGroups);\n\t}\n}\n\n/**\n * Asks the coordinator about one device. No answer covers every case in which\n * the caller must not guess: the coordinator cannot be reached, predates the\n * check, replies with anything but a valid 200, or refuses this device in every\n * configured group. It changes no local state.\n */\nexport async function queryPeerRemoval(\n\tstore: StoreLike,\n\tconfig: CoordinatorSyncConfig,\n\toptions: { localDeviceId: string; keysDir?: string; deviceId: string; publicKey?: string },\n): Promise<PeerRemovalAnswer> {\n\t// A key the caller names but the coordinator would reject cannot be asked about.\n\tconst keyUnusable = options.publicKey !== undefined && usableKey(options.publicKey) === undefined;\n\tif (!isAuthControllerId(options.deviceId) || keyUnusable) return { answered: false };\n\tconst entry = lookupEntry(options.deviceId, options.publicKey);\n\ttry {\n\t\tconst first = await firstAuthorizedGroup(store, config, options, [entry]);\n\t\tif (first.kind !== \"answered\") return { answered: false };\n\t\treturn {\n\t\t\tanswered: true,\n\t\t\tenrolled: first.reply.enrolled.includes(options.deviceId),\n\t\t\tremoved: first.reply.removed.includes(options.deviceId),\n\t\t\trevoked: first.reply.revoked.includes(options.deviceId),\n\t\t};\n\t} catch {\n\t\treturn { answered: false };\n\t}\n}\n","import type { Database } from \"./db.js\";\n\n/*\n * The removed device's own side. The coordinator answers a signed request from a\n * device it removed with `403 device_removed`, per group. This device records\n * each such answer. Once every configured group of the coordinator has given\n * it, this device is removed from sharing: it stops outbound sync to peers it\n * found through that coordinator and deletes nothing. Only the removal lookup\n * reads these answers, and only a lookup that every batch answered with a valid\n * reply clears the record. Other signed requests neither set nor clear it.\n */\n\nconst TABLE = \"sync_coordinator_device_removed\";\n\nexport interface CoordinatorRemovalState {\n\t/** Every configured group answered `device_removed`. */\n\tremoved: boolean;\n\t/** The configured groups that gave that answer. */\n\tremovedFromGroups: string[];\n}\n\nfunction tableExists(db: Database): boolean {\n\treturn (\n\t\tdb.prepare(\"SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = ?\").get(TABLE) !==\n\t\tundefined\n\t);\n}\n\n/** Records that these groups of the coordinator answered `device_removed`. */\nexport function recordCoordinatorDeviceRemoved(\n\tdb: Database,\n\tnotice: { coordinatorId: string; groupIds: string[]; now?: string },\n): void {\n\tif (notice.groupIds.length === 0) return;\n\tdb.transaction(() => {\n\t\tdb.exec(`CREATE TABLE IF NOT EXISTS ${TABLE} (\n\t\t\tcoordinator_id TEXT NOT NULL,\n\t\t\tgroup_id TEXT NOT NULL,\n\t\t\tnoticed_at TEXT NOT NULL,\n\t\t\tPRIMARY KEY (coordinator_id, group_id)\n\t\t)`);\n\t\tconst insert = db.prepare(\n\t\t\t`INSERT OR IGNORE INTO ${TABLE}(coordinator_id, group_id, noticed_at) VALUES (?, ?, ?)`,\n\t\t);\n\t\tconst now = notice.now ?? new Date().toISOString();\n\t\tfor (const groupId of notice.groupIds) insert.run(notice.coordinatorId, groupId, now);\n\t}).immediate();\n}\n\n/** The coordinator accepted a signed request from this device, so it is not removed. */\nexport function clearCoordinatorDeviceRemoved(db: Database, coordinatorId: string): void {\n\tif (!tableExists(db)) return;\n\tdb.prepare(`DELETE FROM ${TABLE} WHERE coordinator_id = ?`).run(coordinatorId);\n}\n\n/** Whether this device is removed from sharing on the coordinator, judged against its configured groups. */\nexport function readCoordinatorRemovalState(\n\tdb: Database,\n\tcoordinator: { coordinatorId: string; groupIds: string[] },\n): CoordinatorRemovalState {\n\tif (!tableExists(db)) return { removed: false, removedFromGroups: [] };\n\tconst noticed = new Set(\n\t\tdb\n\t\t\t.prepare(`SELECT group_id FROM ${TABLE} WHERE coordinator_id = ?`)\n\t\t\t.pluck()\n\t\t\t.all(coordinator.coordinatorId) as string[],\n\t);\n\tconst removedFromGroups = coordinator.groupIds.filter((groupId) => noticed.has(groupId));\n\treturn {\n\t\tremoved:\n\t\t\tcoordinator.groupIds.length > 0 && removedFromGroups.length === coordinator.groupIds.length,\n\t\tremovedFromGroups,\n\t};\n}\n","import type { Database } from \"./db.js\";\nimport type { RetirementPeer } from \"./memory-retirement-delivery.js\";\nimport { fingerprintPublicKey } from \"./sync-fingerprint.js\";\n\ninterface PinnedPeer {\n\tpublic_key: string | null;\n\tpinned_fingerprint: string | null;\n}\n\nfunction validPin(row: PinnedPeer | undefined): row is PinnedPeer & { public_key: string } {\n\treturn Boolean(\n\t\trow?.public_key &&\n\t\t\trow.pinned_fingerprint &&\n\t\t\tfingerprintPublicKey(row.public_key) === row.pinned_fingerprint,\n\t);\n}\n\n/** Copy existing pairing evidence before deleting policy trust, inside the same transaction. */\nexport function retainRetirementPeerTrust(\n\tdb: Database,\n\toptions: { localDeviceId: string; peerDeviceId: string },\n): void {\n\tif (!db.inTransaction) throw new Error(\"retirement_trust_transaction_required\");\n\tconst row = db\n\t\t.prepare(\"SELECT public_key, pinned_fingerprint FROM sync_peers WHERE peer_device_id = ?\")\n\t\t.get(options.peerDeviceId) as PinnedPeer | undefined;\n\tif (!validPin(row)) return;\n\t// First trusted binding wins. Discovery/key rotation cannot silently replace historical authority.\n\tdb.prepare(`INSERT OR IGNORE INTO memory_retirement_peer_trust\n\t\t(local_device_id, peer_device_id, public_key, pinned_fingerprint) VALUES (?, ?, ?, ?)`).run(\n\t\toptions.localDeviceId,\n\t\toptions.peerDeviceId,\n\t\trow.public_key,\n\t\trow.pinned_fingerprint,\n\t);\n}\n\n/** Retirement delivery/ack/reset only. Never use this lookup to authorize content sync. */\nexport function getRetirementPeer(\n\tdb: Database,\n\toptions: { localDeviceId: string; peerDeviceId: string },\n): RetirementPeer | null {\n\tconst retained = db\n\t\t.prepare(`SELECT public_key, pinned_fingerprint FROM memory_retirement_peer_trust\n\t\tWHERE local_device_id = ? AND peer_device_id = ?`)\n\t\t.get(options.localDeviceId, options.peerDeviceId) as PinnedPeer | undefined;\n\tconst row =\n\t\tretained ??\n\t\t(db\n\t\t\t.prepare(\"SELECT public_key, pinned_fingerprint FROM sync_peers WHERE peer_device_id = ?\")\n\t\t\t.get(options.peerDeviceId) as PinnedPeer | undefined);\n\tif (!validPin(row)) return null;\n\treturn { deviceId: options.peerDeviceId, publicKey: row.public_key };\n}\n","import type { Database } from \"./db.js\";\nimport { wakeRecipientPoliciesForIdentities } from \"./device-identity-binding.js\";\nimport { retainRetirementPeerTrust } from \"./memory-retirement-trust.js\";\nimport { canonicalKeyId, recordRetiredDeviceAliases } from \"./retired-device-aliases.js\";\nimport { deletePeerSyncChannelProgress } from \"./sync-channel-progress.js\";\nimport { fingerprintPublicKey } from \"./sync-fingerprint.js\";\n\n/*\n * The only code that deletes a pairing. A pairing's sync progress lives in three\n * tables: the two replication cursor tables and the channel pass's per-scope\n * progress. Progress left behind makes a later pairing with the same device ID\n * resume from the old position and skip history in that direction. Every removal\n * therefore deletes the pairing and all of its progress in one transaction.\n *\n * Removal also ends the device's Identity binding by status, unless the reason\n * is `disconnect` or `policy`. The row stays, because deleting it would delete\n * the device's per-Team decisions and a later rejoin would then widen access\n * past a recorded exclusion.\n */\n\nexport type RetiredDeviceAliasRecord = Parameters<typeof recordRetiredDeviceAliases>[1][number];\n\n/** A coordinator-policy pairing, named by the discovery fields its cleanup requires. */\nexport interface PolicyPairing {\n\tdeviceId: string;\n\tcoordinatorId: string;\n\tgroupId: string;\n}\n\nexport type PairingRemoval =\n\t/** The coordinator removed the device, or this device removed it locally. It may pair again. */\n\t| { reason: \"removed\" | \"local\"; deviceIds: string[] }\n\t/**\n\t * This device withdrew its own connection to the device. The binding stays active,\n\t * because this device may not change the other device's access.\n\t */\n\t| { reason: \"disconnect\"; deviceIds: string[] }\n\t/**\n\t * The coordinator blocked the device. Without `retiredAliases`, each validated\n\t * pinned key is recorded as a key-only alias.\n\t */\n\t| { reason: \"revoked\"; deviceIds: string[]; retiredAliases?: RetiredDeviceAliasRecord[] }\n\t/** A coordinator-policy pairing lost its last shared Project. Its binding stays active. */\n\t| { reason: \"policy\"; pairings: PolicyPairing[] };\n\n/** Rows changed in each table. */\nexport interface PairingRemovalCounts {\n\tsyncPeers: number;\n\treplicationCursors: number;\n\treplicationCursorsV2: number;\n\tsyncChannelProgress: number;\n\t/** Bindings whose status changed from `active` to `removed`. */\n\tidentityDevices: number;\n}\n\nexport type PairingRemovalInput = PairingRemoval & { localDeviceId: string };\n\n/** The peer's pinned key as a key-only alias, only when its fingerprint matches the stored key. */\nfunction pinnedKeyAlias(db: Database, deviceId: string): RetiredDeviceAliasRecord[] {\n\tconst row = db\n\t\t.prepare(\"SELECT public_key, pinned_fingerprint FROM sync_peers WHERE peer_device_id = ?\")\n\t\t.get(deviceId) as { public_key: string | null; pinned_fingerprint: string | null } | undefined;\n\tif (!row?.public_key || !row.pinned_fingerprint) return [];\n\tif (fingerprintPublicKey(row.public_key) !== row.pinned_fingerprint) return [];\n\treturn [\n\t\t{\n\t\t\tdeviceId,\n\t\t\tkind: \"key\",\n\t\t\tfingerprint: row.pinned_fingerprint,\n\t\t\tkeyId: canonicalKeyId(row.public_key),\n\t\t},\n\t];\n}\n\nfunction deletePairing(db: Database, deviceId: string): number {\n\treturn db.prepare(\"DELETE FROM sync_peers WHERE peer_device_id = ?\").run(deviceId).changes;\n}\n\n/** Deletes only a row that is still the policy-derived pairing the caller selected. */\nfunction deletePolicyPairing(db: Database, pairing: PolicyPairing): number {\n\treturn db\n\t\t.prepare(\n\t\t\t`DELETE FROM sync_peers\n\t\t\t WHERE peer_device_id = ? AND claimed_local_actor = 0\n\t\t\t AND actor_id IS NULL AND pending_bootstrap_grant_id IS NULL\n\t\t\t AND trust_provenance = 'coordinator_policy'\n\t\t\t AND discovered_via_coordinator_id = ? AND discovered_via_group_id = ?`,\n\t\t)\n\t\t.run(pairing.deviceId, pairing.coordinatorId, pairing.groupId).changes;\n}\n\nfunction deleteSyncProgress(db: Database, deviceId: string) {\n\treturn {\n\t\treplicationCursors: db\n\t\t\t.prepare(\"DELETE FROM replication_cursors WHERE peer_device_id = ?\")\n\t\t\t.run(deviceId).changes,\n\t\treplicationCursorsV2: db\n\t\t\t.prepare(\"DELETE FROM replication_cursors_v2 WHERE peer_device_id = ?\")\n\t\t\t.run(deviceId).changes,\n\t\tsyncChannelProgress: deletePeerSyncChannelProgress(db, deviceId),\n\t};\n}\n\n/** Ends the device's active binding and returns its Identity, or null when none was active. */\nfunction endBinding(db: Database, deviceId: string, now: string): string | null {\n\tconst ended = db\n\t\t.prepare(\n\t\t\t`UPDATE identity_devices SET status = 'removed', updated_at = ?\n\t\t\t WHERE device_id = ? AND status = 'active' RETURNING identity_id`,\n\t\t)\n\t\t.get(now, deviceId) as { identity_id: string } | undefined;\n\treturn ended?.identity_id ?? null;\n}\n\nfunction addCounts(\n\ttotal: PairingRemovalCounts,\n\tpart: Omit<PairingRemovalCounts, \"identityDevices\">,\n): void {\n\ttotal.syncPeers += part.syncPeers;\n\ttotal.replicationCursors += part.replicationCursors;\n\ttotal.replicationCursorsV2 += part.replicationCursorsV2;\n\ttotal.syncChannelProgress += part.syncChannelProgress;\n}\n\nfunction removePolicyPairings(\n\tdb: Database,\n\tlocalDeviceId: string,\n\tpairings: PolicyPairing[],\n): PairingRemovalCounts {\n\tconst counts = emptyCounts();\n\tfor (const pairing of pairings) {\n\t\t// Content sync stops, but retirement controls still need this peer's pinned key.\n\t\tretainRetirementPeerTrust(db, { localDeviceId, peerDeviceId: pairing.deviceId });\n\t\tconst syncPeers = deletePolicyPairing(db, pairing);\n\t\t// A pairing that no longer matches is live, and its progress rows hold its position.\n\t\tif (syncPeers === 0) continue;\n\t\taddCounts(counts, { syncPeers, ...deleteSyncProgress(db, pairing.deviceId) });\n\t}\n\treturn counts;\n}\n\nfunction removeDevices(\n\tdb: Database,\n\tinput: Extract<PairingRemovalInput, { deviceIds: string[] }>,\n): PairingRemovalCounts {\n\tconst counts = emptyCounts();\n\tconst deviceIds = [...new Set(input.deviceIds)];\n\tif (input.reason === \"revoked\") {\n\t\t// A retired alias stops the ID from pairing again with the blocked key.\n\t\trecordRetiredDeviceAliases(\n\t\t\tdb,\n\t\t\tinput.retiredAliases ?? deviceIds.flatMap((deviceId) => pinnedKeyAlias(db, deviceId)),\n\t\t);\n\t}\n\tconst now = new Date().toISOString();\n\tconst endedIdentityIds = new Set<string>();\n\tfor (const deviceId of deviceIds) {\n\t\t// Content sync stops, but retirement controls still need this peer's pinned key.\n\t\tretainRetirementPeerTrust(db, { localDeviceId: input.localDeviceId, peerDeviceId: deviceId });\n\t\taddCounts(counts, {\n\t\t\tsyncPeers: deletePairing(db, deviceId),\n\t\t\t...deleteSyncProgress(db, deviceId),\n\t\t});\n\t\tif (input.reason === \"disconnect\") continue;\n\t\t// This device's own binding is never ended by removing a pairing.\n\t\tif (deviceId === input.localDeviceId) continue;\n\t\tconst identityId = endBinding(db, deviceId, now);\n\t\tif (!identityId) continue;\n\t\tcounts.identityDevices += 1;\n\t\tendedIdentityIds.add(identityId);\n\t}\n\tif (endedIdentityIds.size === 0) return counts;\n\t// Projects shared with those Identities no longer include the device.\n\twakeRecipientPoliciesForIdentities(db, endedIdentityIds, now);\n\treturn counts;\n}\n\nfunction emptyCounts(): PairingRemovalCounts {\n\treturn {\n\t\tsyncPeers: 0,\n\t\treplicationCursors: 0,\n\t\treplicationCursorsV2: 0,\n\t\tsyncChannelProgress: 0,\n\t\tidentityDevices: 0,\n\t};\n}\n\n/**\n * Removes each device's pairing and sync progress, and ends its Identity binding\n * unless the reason is `disconnect` or `policy`. Memory retirement trust is retained first, and\n * `sync_attempts` and `sync_scope_rejections` stay as diagnostic history. One\n * immediate transaction: any failure leaves every table unchanged.\n */\nexport function removePairingState(db: Database, input: PairingRemovalInput): PairingRemovalCounts {\n\treturn db\n\t\t.transaction(() =>\n\t\t\tinput.reason === \"policy\"\n\t\t\t\t? removePolicyPairings(db, input.localDeviceId, input.pairings)\n\t\t\t\t: removeDevices(db, input),\n\t\t)\n\t\t.immediate();\n}\n","import type { CoordinatorEnrollment } from \"./coordinator-store-contract.js\";\nimport type { Database } from \"./db.js\";\nimport {\n\ttype DeviceIdentityInventoryItemV1,\n\tlistDeviceIdentityInventory,\n} from \"./device-identity-inventory.js\";\nimport { removePairingState } from \"./pairing-removal.js\";\nimport {\n\tcanonicalKeyId,\n\tlistRetiredDeviceAliases,\n\tretiredAliasApplies,\n} from \"./retired-device-aliases.js\";\nimport { fingerprintPublicKey } from \"./sync-fingerprint.js\";\n\n/*\n * One device can appear under several IDs that share a key: a local pairing, a\n * coordinator enrollment, and an Identity binding. Coordinator revocation blocks\n * the chosen enrollment's device ID and the key's canonical ID under every device\n * ID, so retirement works on the whole group. The group comes from the device\n * inventory Devices shows. Every safety check compares canonical key IDs, because\n * different key text can carry the same canonical key.\n */\n\nexport interface RetireTarget {\n\t/** Every ID in the device's inventory group except this device. */\n\taliasDeviceIds: string[];\n\tdisplayName: string;\n\tfingerprint: string;\n\t/** The canonical key ID the coordinator revokes under every device ID. */\n\tkeyId: string;\n\t/** The enrollment the coordinator needs as revocation evidence. */\n\tgroupId: string;\n\tenrollmentDeviceId: string;\n}\n\nexport type RetireTargetError =\n\t| \"device_not_enrolled\"\n\t| \"cannot_retire_this_device\"\n\t| \"local_identity_unverified\"\n\t| \"device_already_retired\"\n\t| \"device_enrollment_conflict\"\n\t| \"device_key_unrecognized\"\n\t| \"device_evidence_incomplete\";\n\nexport interface RetireTargetInput {\n\tlocalDeviceId: string;\n\tenrollments: CoordinatorEnrollment[];\n\tdeviceId: string;\n}\n\nconst FINGERPRINT_CONFLICTS = new Set([\"fingerprint_conflict\", \"fingerprint_invalid\"]);\n\n/**\n * This device's canonical key ID, only when exactly one consistent identity row\n * exists for the ID the viewer runs as. Anything else can hide this device from\n * the inventory, so device-removal checks refuse rather than guess.\n */\nexport function verifiedLocalKeyId(db: Database, localDeviceId: string): string | null {\n\tconst rows = db\n\t\t.prepare(\"SELECT device_id, public_key, fingerprint FROM sync_device\")\n\t\t.all() as Array<{\n\t\tdevice_id: string;\n\t\tpublic_key: string | null;\n\t\tfingerprint: string | null;\n\t}>;\n\tconst [row] = rows;\n\tif (rows.length !== 1 || !row || row.device_id !== localDeviceId || !row.public_key) return null;\n\tif (row.fingerprint !== fingerprintPublicKey(row.public_key)) return null;\n\treturn canonicalKeyId(row.public_key);\n}\n\nfunction inventoryGroup(\n\tdb: Database,\n\tinput: RetireTargetInput,\n): DeviceIdentityInventoryItemV1 | RetireTargetError {\n\tconst inventory = listDeviceIdentityInventory(\n\t\tdb,\n\t\t{\n\t\t\tlocalDeviceId: input.localDeviceId,\n\t\t\tcoordinator: {\n\t\t\t\tavailability: \"available\",\n\t\t\t\tsafeErrorCode: null,\n\t\t\t\tenrollments: input.enrollments,\n\t\t\t},\n\t\t},\n\t\t{ limit: 2_000 },\n\t);\n\tif (inventory.truncated) return \"device_evidence_incomplete\";\n\treturn (\n\t\tinventory.items.find((item) => item.evidenceDeviceIds.includes(input.deviceId)) ??\n\t\t\"device_not_enrolled\"\n\t);\n}\n\nfunction groupError(item: DeviceIdentityInventoryItemV1): RetireTargetError | null {\n\tif (item.isLocal) return \"cannot_retire_this_device\";\n\tif (item.state === \"retired\") return \"device_already_retired\";\n\tif (item.conflictCodes.some((code) => FINGERPRINT_CONFLICTS.has(code)))\n\t\treturn \"device_enrollment_conflict\";\n\tif (!item.validatedFingerprint) return \"device_enrollment_conflict\";\n\treturn null;\n}\n\nfunction pinnedKeys(\n\tdb: Database,\n): Array<{ deviceId: string; publicKey: string; fingerprint: string | null }> {\n\treturn (\n\t\tdb\n\t\t\t.prepare(\n\t\t\t\t\"SELECT peer_device_id, public_key, pinned_fingerprint FROM sync_peers WHERE public_key IS NOT NULL\",\n\t\t\t)\n\t\t\t.all() as Array<{\n\t\t\tpeer_device_id: string;\n\t\t\tpublic_key: string;\n\t\t\tpinned_fingerprint: string | null;\n\t\t}>\n\t).map((row) => ({\n\t\tdeviceId: row.peer_device_id,\n\t\tpublicKey: row.public_key,\n\t\tfingerprint: row.pinned_fingerprint?.trim() || null,\n\t}));\n}\n\n/** True when evidence outside the group carries the same canonical key, which revocation would also block. */\nfunction canonicalKeyCollides(\n\tdb: Database,\n\tinput: RetireTargetInput,\n\tgroup: Set<string>,\n\tkeyId: string,\n): boolean {\n\tconst outside = [\n\t\t...input.enrollments.map((row) => ({ deviceId: row.device_id, publicKey: row.public_key })),\n\t\t...pinnedKeys(db),\n\t].filter((row) => !group.has(row.deviceId));\n\treturn outside.some((row) => canonicalKeyId(row.publicKey) === keyId);\n}\n\nfunction alreadyRetired(db: Database, group: string[]): boolean {\n\tconst aliases = listRetiredDeviceAliases(db);\n\tconst pinned = new Map(pinnedKeys(db).map((row) => [row.deviceId, row]));\n\treturn group.some((id) => retiredAliasApplies(aliases.get(id), pinned.get(id) ?? null));\n}\n\nfunction revocationEvidence(\n\tinput: RetireTargetInput,\n\titem: DeviceIdentityInventoryItemV1,\n\tfingerprint: string,\n): CoordinatorEnrollment | undefined {\n\treturn input.enrollments\n\t\t.filter(\n\t\t\t(row) => item.evidenceDeviceIds.includes(row.device_id) && row.fingerprint === fingerprint,\n\t\t)\n\t\t.toSorted(\n\t\t\t(a, b) => a.group_id.localeCompare(b.group_id) || a.device_id.localeCompare(b.device_id),\n\t\t)[0];\n}\n\n/**\n * The full alias group for a device the person picked by any of its IDs, plus the\n * enrollment the coordinator revokes. Fails closed on any ambiguity.\n */\nexport function resolveRetireTarget(\n\tdb: Database,\n\tinput: RetireTargetInput,\n): RetireTarget | RetireTargetError {\n\tconst localKeyId = verifiedLocalKeyId(db, input.localDeviceId);\n\tif (!localKeyId) return \"local_identity_unverified\";\n\tif (input.deviceId === input.localDeviceId) return \"cannot_retire_this_device\";\n\tconst item = inventoryGroup(db, input);\n\tif (typeof item === \"string\") return item;\n\tconst error = groupError(item);\n\tif (error) return error;\n\tif (alreadyRetired(db, item.evidenceDeviceIds)) return \"device_already_retired\";\n\tconst fingerprint = item.validatedFingerprint as string;\n\tconst evidence = revocationEvidence(input, item, fingerprint);\n\tif (!evidence) return \"device_not_enrolled\";\n\tconst keyId = canonicalKeyId(evidence.public_key);\n\tif (!keyId) return \"device_key_unrecognized\";\n\tif (keyId === localKeyId) return \"cannot_retire_this_device\";\n\tif (canonicalKeyCollides(db, input, new Set(item.evidenceDeviceIds), keyId))\n\t\treturn \"device_enrollment_conflict\";\n\treturn {\n\t\taliasDeviceIds: item.evidenceDeviceIds.filter((id) => id !== input.localDeviceId),\n\t\tdisplayName: item.displayName,\n\t\tfingerprint,\n\t\tkeyId,\n\t\tgroupId: evidence.group_id,\n\t\tenrollmentDeviceId: evidence.device_id,\n\t};\n}\n\n/**\n * Deletes each revoked peer's pairing and cursors and ends its binding, whatever its\n * trust source. The coordinator doesn't say which subject matched, so each pinned key\n * is recorded as a key-only alias that a later pairing with a different key clears.\n */\nexport function removeRevokedPeers(\n\tdb: Database,\n\tlocalDeviceId: string,\n\tpeerDeviceIds: string[],\n): number {\n\tconst deviceIds = peerDeviceIds.filter((id) => id !== localDeviceId);\n\tif (deviceIds.length === 0) return 0;\n\treturn removePairingState(db, { localDeviceId, reason: \"revoked\", deviceIds }).syncPeers;\n}\n\n/**\n * Whether the ID's current pairing, if any, still pins the revoked key. A pairing\n * can change while the coordinator commit is in flight, and the coordinator only\n * revoked the old key for an ID other than the enrollment's.\n */\nfunction stillPinsRetiredKey(db: Database, deviceId: string, target: RetireTarget): boolean {\n\tconst row = db\n\t\t.prepare(\"SELECT public_key, pinned_fingerprint FROM sync_peers WHERE peer_device_id = ?\")\n\t\t.get(deviceId) as { public_key: string | null; pinned_fingerprint: string | null } | undefined;\n\tif (!row) return true;\n\tconst revoked = { kind: \"key\" as const, fingerprint: target.fingerprint, keyId: target.keyId };\n\treturn retiredAliasApplies(revoked, {\n\t\tpublicKey: row.public_key,\n\t\tfingerprint: row.pinned_fingerprint,\n\t});\n}\n\n/**\n * After a confirmed coordinator revocation: record every alias that still carries\n * the revoked key, then unpair them and end their bindings. The enrollment's ID is\n * revoked outright.\n */\nexport function retireDeviceLocally(db: Database, localDeviceId: string, target: RetireTarget) {\n\treturn db\n\t\t.transaction(() => {\n\t\t\tconst deviceIds = target.aliasDeviceIds.filter(\n\t\t\t\t(id) =>\n\t\t\t\t\tid !== localDeviceId &&\n\t\t\t\t\t(id === target.enrollmentDeviceId || stillPinsRetiredKey(db, id, target)),\n\t\t\t);\n\t\t\treturn removePairingState(db, {\n\t\t\t\tlocalDeviceId,\n\t\t\t\treason: \"revoked\",\n\t\t\t\tdeviceIds,\n\t\t\t\tretiredAliases: deviceIds.map((deviceId) => ({\n\t\t\t\t\tdeviceId,\n\t\t\t\t\t// Only the evidence enrollment's ID is revoked outright; the others lose the key.\n\t\t\t\t\tkind: deviceId === target.enrollmentDeviceId ? (\"device_id\" as const) : (\"key\" as const),\n\t\t\t\t\tfingerprint: target.fingerprint,\n\t\t\t\t\tkeyId: target.keyId,\n\t\t\t\t})),\n\t\t\t}).syncPeers;\n\t\t})\n\t\t.immediate();\n}\n","import { networkInterfaces } from \"node:os\";\nimport {\n\tformatHostPort,\n\tmergeAddresses,\n\tmergeCoordinatorPeerAddresses,\n\tnormalizeAddress,\n} from \"./address-utils.js\";\nimport {\n\tfetchPeerRemovalLookup,\n\ttype PeerRemovalLookup,\n\ttype PeerRevocationCheckStatus,\n} from \"./coordinator-peer-revocation.js\";\nimport {\n\tclearCoordinatorDeviceRemoved,\n\trecordCoordinatorDeviceRemoved,\n} from \"./coordinator-removal-notice.js\";\nimport {\n\ttype CoordinatorReciprocalApproval,\n\tCoordinatorReciprocalApprovalRequestChangedError,\n} from \"./coordinator-store-contract.js\";\nimport {\n\ttype CoordinatorSyncConfig,\n\tcoordinatorEnabled,\n\treadCoordinatorSyncConfig,\n} from \"./coordinator-sync-config.js\";\nimport type { Database } from \"./db.js\";\nimport { removeRevokedPeers } from \"./device-retirement.js\";\nimport { retainRetirementPeerTrust } from \"./memory-retirement-trust.js\";\nimport { removePairingState } from \"./pairing-removal.js\";\nimport {\n\treadAppliedRemovalSeq,\n\treadPeerRemovalCheckState,\n\tstoreAppliedRemovalSeq,\n} from \"./peer-removal-check-state.js\";\nimport { getEffectiveCachedScopeAuthorization } from \"./scope-membership-cache.js\";\nimport type { MemoryStore } from \"./store.js\";\nimport { buildAuthHeaders } from \"./sync-auth.js\";\nimport { LOCAL_SYNC_CAPABILITY, LOCAL_SYNC_FEATURES } from \"./sync-capability.js\";\nimport { fingerprintPublicKey } from \"./sync-fingerprint.js\";\nimport { buildBaseUrl, requestJson } from \"./sync-http-client.js\";\nimport { ensureDeviceIdentity, loadPublicKey } from \"./sync-identity.js\";\nimport { updatePeerAddresses } from \"./sync-peer-addresses.js\";\n\nexport {\n\ttype CoordinatorSyncConfig,\n\tcoordinatorEnabled,\n\treadCoordinatorSyncConfig,\n} from \"./coordinator-sync-config.js\";\n\ntype PresenceStoreLike = Pick<MemoryStore, \"db\" | \"dbPath\">;\n\nfunction clean(value: unknown): string {\n\treturn typeof value === \"string\" ? value.trim() : \"\";\n}\n\nfunction mergeStringLists(existing: string[], candidates: string[]): string[] {\n\tconst merged: string[] = [];\n\tconst seen = new Set<string>();\n\tfor (const value of [...existing, ...candidates]) {\n\t\tconst cleanValue = value.trim();\n\t\tif (!cleanValue || seen.has(cleanValue)) continue;\n\t\tseen.add(cleanValue);\n\t\tmerged.push(cleanValue);\n\t}\n\treturn merged;\n}\n\nfunction earliestValidExpiry(existing: unknown, candidate: unknown): unknown {\n\tconst existingMs = Date.parse(clean(existing));\n\tconst candidateMs = Date.parse(clean(candidate));\n\tif (!Number.isFinite(existingMs)) return Number.isFinite(candidateMs) ? candidate : existing;\n\tif (!Number.isFinite(candidateMs)) return existing;\n\treturn candidateMs < existingMs ? candidate : existing;\n}\n\ntype PresenceStatus = \"posted\" | \"not_enrolled\" | \"error\";\n\ninterface PresenceSnapshot {\n\tstatus: PresenceStatus;\n\terror: string | null;\n\tadvertisedAddresses: unknown;\n\tnextRefreshAtMs: number;\n}\n\ninterface CoordinatorStatusCacheEntry {\n\tsnapshot: Record<string, unknown>;\n\tdiscoveredPeers: Record<string, unknown>[];\n\tnextRefreshAtMs: number;\n}\n\nconst coordinatorPresenceCache = new Map<string, PresenceSnapshot>();\nconst coordinatorStatusCache = new Map<string, CoordinatorStatusCacheEntry>();\nconst coordinatorStatusCacheGenerations = new Map<string, number>();\nconst COORDINATOR_STATUS_SNAPSHOT_CACHE_MS = 30_000;\n\nfunction coordinatorStatusRefreshDeadline(now: number, peers: Record<string, unknown>[]): number {\n\tlet deadline = now + COORDINATOR_STATUS_SNAPSHOT_CACHE_MS;\n\tfor (const peer of peers) {\n\t\tif (peer.stale) continue;\n\t\tconst expiresAtMs = Date.parse(clean(peer.expires_at));\n\t\tif (!Number.isFinite(expiresAtMs)) continue;\n\t\t// Never re-serve an expired peer, even if local clock skew disables this cache.\n\t\tif (expiresAtMs <= now) return now;\n\t\tdeadline = Math.min(deadline, expiresAtMs);\n\t}\n\treturn deadline;\n}\n\nfunction invalidateCoordinatorStatusCache(cacheKey: string): void {\n\tcoordinatorStatusCache.delete(cacheKey);\n\tcoordinatorStatusCacheGenerations.set(\n\t\tcacheKey,\n\t\t(coordinatorStatusCacheGenerations.get(cacheKey) ?? 0) + 1,\n\t);\n}\n\nfunction presenceCacheKey(store: PresenceStoreLike, config: CoordinatorSyncConfig): string {\n\tconst groups = [...config.syncCoordinatorGroups].sort().join(\",\");\n\treturn [\n\t\tstore.dbPath,\n\t\tconfig.syncCoordinatorUrl,\n\t\tgroups,\n\t\tcoordinatorStatusIdentityCacheSegment(store),\n\t\tconfig.syncHost,\n\t\tconfig.syncPort,\n\t\tconfig.syncAdvertise,\n\t\tconfig.syncCoordinatorPresenceTtlS,\n\t].join(\"|\");\n}\n\nfunction coordinatorStatusIdentityCacheSegment(store: PresenceStoreLike): string {\n\tconst keysDir = process.env.CODEMEM_KEYS_DIR?.trim() || \"\";\n\ttry {\n\t\tconst row = store.db.prepare(\"SELECT device_id, fingerprint FROM sync_device LIMIT 1\").get() as\n\t\t\t| { device_id?: string | null; fingerprint?: string | null }\n\t\t\t| undefined;\n\t\treturn `${keysDir}|${row?.device_id ?? \"\"}|${row?.fingerprint ?? \"\"}`;\n\t} catch {\n\t\treturn keysDir;\n\t}\n}\n\nfunction coordinatorStatusCacheKey(\n\tstore: PresenceStoreLike,\n\tconfig: CoordinatorSyncConfig,\n): string {\n\treturn [\n\t\tpresenceCacheKey(store, config),\n\t\tconfig.syncEnabled ? \"sync-enabled\" : \"sync-disabled\",\n\t\tconfig.syncHost,\n\t\tconfig.syncPort,\n\t\tconfig.syncAdvertise,\n\t\tconfig.syncCoordinatorPresenceTtlS,\n\t].join(\"|\");\n}\n\nfunction pairedPeerCount(store: PresenceStoreLike): number {\n\treturn Number(\n\t\t(\n\t\t\tstore.db.prepare(\"SELECT COUNT(1) AS total FROM sync_peers\").get() as\n\t\t\t\t| { total?: number }\n\t\t\t\t| undefined\n\t\t)?.total ?? 0,\n\t);\n}\n\nfunction presenceRefreshIntervalMs(config: CoordinatorSyncConfig): number {\n\tconst ttl = Math.max(1, config.syncCoordinatorPresenceTtlS);\n\tconst halfTtl = Math.floor(ttl / 2);\n\tconst refreshS = Math.max(5, Math.min(60, halfTtl > 0 ? halfTtl : 1));\n\treturn refreshS * 1000;\n}\n\nfunction presenceRetryIntervalMs(): number {\n\treturn 30_000;\n}\n\nasync function refreshCoordinatorPresenceStatus(\n\tstore: PresenceStoreLike,\n\tconfig: CoordinatorSyncConfig,\n\tsnapshot: Record<string, unknown>,\n\tnow: number,\n): Promise<void> {\n\tconst presenceKey = presenceCacheKey(store, config);\n\tconst cachedPresence = coordinatorPresenceCache.get(presenceKey);\n\tif (cachedPresence && now < cachedPresence.nextRefreshAtMs) {\n\t\tsnapshot.presence_status = cachedPresence.status;\n\t\tsnapshot.presence_error = cachedPresence.error;\n\t\tsnapshot.advertised_addresses = cachedPresence.advertisedAddresses;\n\t\treturn;\n\t}\n\ttry {\n\t\tconst registration = await registerCoordinatorPresence(store, config);\n\t\tconst first = registration?.responses?.[0];\n\t\tconst advertisedAddresses =\n\t\t\tfirst && typeof first === \"object\"\n\t\t\t\t? ((first as Record<string, unknown>).addresses ?? [])\n\t\t\t\t: [];\n\t\tsnapshot.presence_status = \"posted\";\n\t\tsnapshot.presence_error = null;\n\t\tsnapshot.advertised_addresses = advertisedAddresses;\n\t\tcoordinatorPresenceCache.set(presenceKey, {\n\t\t\tstatus: \"posted\",\n\t\t\terror: null,\n\t\t\tadvertisedAddresses,\n\t\t\tnextRefreshAtMs: now + presenceRefreshIntervalMs(config),\n\t\t});\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconst status: PresenceStatus = message.includes(\"unknown_device\") ? \"not_enrolled\" : \"error\";\n\t\tconst nextRefreshAtMs = status === \"not_enrolled\" ? now : now + presenceRetryIntervalMs();\n\t\tsnapshot.presence_status = status;\n\t\tsnapshot.presence_error = message;\n\t\tsnapshot.advertised_addresses = [];\n\t\tcoordinatorPresenceCache.set(presenceKey, {\n\t\t\tstatus,\n\t\t\terror: message,\n\t\t\tadvertisedAddresses: [],\n\t\t\tnextRefreshAtMs,\n\t\t});\n\t}\n}\n\nexport function advertisedSyncAddresses(config: CoordinatorSyncConfig): string[] {\n\tconst advertise = config.syncAdvertise.toLowerCase();\n\tif (advertise && advertise !== \"auto\" && advertise !== \"default\") {\n\t\treturn mergeAddresses(\n\t\t\t[],\n\t\t\tadvertise\n\t\t\t\t.split(\",\")\n\t\t\t\t.map((item) => item.trim())\n\t\t\t\t.filter(Boolean),\n\t\t\t{ defaultHttpPort: config.syncPort },\n\t\t);\n\t}\n\tif (config.syncHost && config.syncHost !== \"0.0.0.0\") {\n\t\treturn [normalizeAddress(formatHostPort(config.syncHost, config.syncPort))].filter(Boolean);\n\t}\n\tconst addresses = Object.values(networkInterfaces())\n\t\t.flatMap((entries) => entries ?? [])\n\t\t.filter((entry) => !entry.internal)\n\t\t.map((entry) => entry.address)\n\t\t.filter((address) => address && address !== \"127.0.0.1\" && address !== \"::1\")\n\t\t.map((address) => normalizeAddress(formatHostPort(address, config.syncPort)))\n\t\t.filter(Boolean);\n\treturn [...new Set(addresses)];\n}\n\nexport async function registerCoordinatorPresence(\n\tstore: PresenceStoreLike,\n\tconfig: CoordinatorSyncConfig,\n\toptions?: { keysDir?: string },\n): Promise<{ groups: string[]; responses: Record<string, unknown>[] } | null> {\n\tif (!coordinatorEnabled(config)) return null;\n\tconst keysDir = options?.keysDir ?? (process.env.CODEMEM_KEYS_DIR?.trim() || undefined);\n\tconst [deviceId, fingerprint] = ensureDeviceIdentity(store.db, { keysDir });\n\tconst publicKey = loadPublicKey(keysDir);\n\tif (!publicKey) throw new Error(\"public key missing\");\n\tconst baseUrl = buildBaseUrl(config.syncCoordinatorUrl);\n\tconst payload = {\n\t\tfingerprint,\n\t\tpublic_key: publicKey,\n\t\taddresses: advertisedSyncAddresses(config),\n\t\tttl_s: Math.max(1, config.syncCoordinatorPresenceTtlS),\n\t\tcapabilities: {\n\t\t\tsync_capability: LOCAL_SYNC_CAPABILITY,\n\t\t\tsync_features: LOCAL_SYNC_FEATURES,\n\t\t\t// 0 until a complete lookup has covered every pairing and binding this device has now.\n\t\t\tapplied_removal_seq: readAppliedRemovalSeq(store.db),\n\t\t},\n\t};\n\tconst responses: Record<string, unknown>[] = [];\n\tfor (const groupId of config.syncCoordinatorGroups) {\n\t\tconst groupPayload = { ...payload, group_id: groupId };\n\t\tconst bodyBytes = Buffer.from(JSON.stringify(groupPayload), \"utf8\");\n\t\tconst url = `${baseUrl}/v1/presence`;\n\t\tconst headers = buildAuthHeaders({\n\t\t\tdeviceId,\n\t\t\tdbPath: store.dbPath,\n\t\t\tmethod: \"POST\",\n\t\t\turl,\n\t\t\tbodyBytes,\n\t\t\tkeysDir,\n\t\t});\n\t\tconst [status, response] = await requestJson(\"POST\", url, {\n\t\t\theaders,\n\t\t\tbody: groupPayload,\n\t\t\tbodyBytes,\n\t\t\ttimeoutS: Math.max(1, config.syncCoordinatorTimeoutS),\n\t\t});\n\t\tif (status !== 200 || !response) {\n\t\t\tconst detail = typeof response?.error === \"string\" ? response.error : \"unknown\";\n\t\t\tthrow new Error(`coordinator presence failed (${status}: ${detail})`);\n\t\t}\n\t\tresponses.push(response);\n\t}\n\treturn { groups: config.syncCoordinatorGroups, responses };\n}\n\nexport async function lookupCoordinatorPeers(\n\tstore: PresenceStoreLike,\n\tconfig: CoordinatorSyncConfig,\n\toptions?: { keysDir?: string },\n): Promise<Record<string, unknown>[]> {\n\tif (!coordinatorEnabled(config)) return [];\n\tconst keysDir = options?.keysDir ?? (process.env.CODEMEM_KEYS_DIR?.trim() || undefined);\n\tconst [deviceId] = ensureDeviceIdentity(store.db, { keysDir });\n\tconst baseUrl = buildBaseUrl(config.syncCoordinatorUrl);\n\tconst merged = new Map<string, Record<string, unknown>>();\n\tfor (const groupId of config.syncCoordinatorGroups) {\n\t\tconst url = `${baseUrl}/v1/peers?group_id=${encodeURIComponent(groupId)}`;\n\t\tconst headers = buildAuthHeaders({\n\t\t\tdeviceId,\n\t\t\tdbPath: store.dbPath,\n\t\t\tmethod: \"GET\",\n\t\t\turl,\n\t\t\tbodyBytes: Buffer.alloc(0),\n\t\t\tkeysDir,\n\t\t});\n\t\tconst [status, response] = await requestJson(\"GET\", url, {\n\t\t\theaders,\n\t\t\ttimeoutS: Math.max(1, config.syncCoordinatorTimeoutS),\n\t\t});\n\t\tif (status !== 200 || !response) {\n\t\t\tconst detail = typeof response?.error === \"string\" ? response.error : \"unknown\";\n\t\t\tthrow new Error(`coordinator lookup failed (${status}: ${detail})`);\n\t\t}\n\t\tconst items = Array.isArray(response.items) ? response.items : [];\n\t\tfor (const item of items) {\n\t\t\tif (!item || typeof item !== \"object\") continue;\n\t\t\tconst record = item as Record<string, unknown>;\n\t\t\tconst device = clean(record.device_id);\n\t\t\tconst fingerprint = clean(record.fingerprint);\n\t\t\tif (!device) continue;\n\t\t\tconst freshAddresses = record.stale\n\t\t\t\t? []\n\t\t\t\t: Array.isArray(record.addresses)\n\t\t\t\t\t? record.addresses.filter((x): x is string => typeof x === \"string\")\n\t\t\t\t\t: [];\n\t\t\tconst key = `${device}:${fingerprint}`;\n\t\t\tconst existing = merged.get(key);\n\t\t\tif (!existing) {\n\t\t\t\tmerged.set(key, {\n\t\t\t\t\t...record,\n\t\t\t\t\taddresses: mergeAddresses([], freshAddresses),\n\t\t\t\t\tcoordinator_id: baseUrl,\n\t\t\t\t\tgroups: [groupId],\n\t\t\t\t\tfresh_groups: record.stale ? [] : [groupId],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tmergeCoordinatorPeerGroup(existing, record, groupId, freshAddresses);\n\t\t}\n\t}\n\treturn [...merged.values()];\n}\n\nfunction mergeCoordinatorPeerGroup(\n\texisting: Record<string, unknown>,\n\trecord: Record<string, unknown>,\n\tgroupId: string,\n\tfreshAddresses: string[],\n): void {\n\texisting.addresses = mergeAddresses(stringList(existing.addresses), freshAddresses);\n\texisting.groups = mergeStringLists(stringList(existing.groups), [groupId]);\n\tconst wasStale = Boolean(existing.stale);\n\tconst isStale = Boolean(record.stale);\n\texisting.fresh_groups = mergeStringLists(\n\t\tstringList(existing.fresh_groups),\n\t\tisStale ? [] : [groupId],\n\t);\n\texisting.stale = wasStale && isStale;\n\tconst newer = clean(record.last_seen_at) > clean(existing.last_seen_at);\n\tconst updateLastSeen = newer || (wasStale && !isStale);\n\tif (updateLastSeen && (!isStale || wasStale)) existing.last_seen_at = record.last_seen_at;\n\t// Unioned fresh addresses are valid only until the earliest group expiry.\n\tif (!isStale)\n\t\texisting.expires_at = wasStale\n\t\t\t? record.expires_at\n\t\t\t: earliestValidExpiry(existing.expires_at, record.expires_at);\n\telse if (wasStale && updateLastSeen) existing.expires_at = record.expires_at;\n}\n\nfunction stringList(value: unknown): string[] {\n\tif (!Array.isArray(value)) return [];\n\treturn value.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0);\n}\n\nfunction coordinatorPeerGroups(value: unknown): string[] | null {\n\tif (!Array.isArray(value) || value.length === 0) return null;\n\tconst groups: string[] = [];\n\tfor (const item of value) {\n\t\tif (typeof item !== \"string\" || !item.trim()) return null;\n\t\tgroups.push(item.trim());\n\t}\n\treturn groups;\n}\n\nfunction parseAddressCache(value: unknown): string[] {\n\tif (typeof value !== \"string\" || value.trim().length === 0) return [];\n\ttry {\n\t\tconst parsed = JSON.parse(value) as unknown;\n\t\treturn stringList(parsed);\n\t} catch {\n\t\treturn [];\n\t}\n}\n\n/**\n * Refresh cached transport addresses for existing, already-trusted peers from\n * coordinator discovery results.\n *\n * This intentionally does not create peers or change trust/scope metadata. A\n * discovered device can refresh a local peer only when both the device id and\n * the pinned fingerprint match the existing row.\n */\ntype StoredCoordinatorPeerAddressRow = {\n\tpeer_device_id: string | null;\n\tpinned_fingerprint: string | null;\n\taddresses_json: string | null;\n\tmanual_addresses_json: string | null;\n\tlast_success_address: string | null;\n};\n\nfunction refreshCoordinatorPeerRow(\n\trow: StoredCoordinatorPeerAddressRow,\n\tdiscoveredAddressesByPinnedPeer: Map<string, string[]>,\n\tupdate: (addresses: string, manual: string, deviceId: string, fingerprint: string) => void,\n): boolean {\n\tconst deviceId = clean(row.peer_device_id);\n\tconst fingerprint = clean(row.pinned_fingerprint);\n\tif (!deviceId || !fingerprint) return false;\n\tconst discovered = discoveredAddressesByPinnedPeer.get(`${deviceId}:${fingerprint}`);\n\tif (!discovered?.length) return false;\n\tconst existing = mergeAddresses(parseAddressCache(row.addresses_json), []);\n\tconst manual =\n\t\trow.manual_addresses_json == null ? existing : parseAddressCache(row.manual_addresses_json);\n\tconst merged = mergeCoordinatorPeerAddresses(existing, discovered, manual, {\n\t\tsuccessfulAddress: row.last_success_address ?? undefined,\n\t});\n\tif (JSON.stringify(merged) === JSON.stringify(existing) && row.manual_addresses_json != null) {\n\t\treturn false;\n\t}\n\tupdate(JSON.stringify(merged), JSON.stringify(manual), deviceId, fingerprint);\n\treturn true;\n}\n\nexport function refreshStoredCoordinatorPeerAddresses(\n\tdb: Database,\n\tpeers: Record<string, unknown>[],\n): number {\n\tconst discoveredAddressesByPinnedPeer = new Map<string, string[]>();\n\tfor (const peer of peers) {\n\t\tif (peer.stale) continue;\n\t\tconst deviceId = clean(peer.device_id);\n\t\tconst fingerprint = clean(peer.fingerprint);\n\t\tif (!deviceId || !fingerprint) continue;\n\t\tconst addresses = stringList(peer.addresses);\n\t\tif (addresses.length === 0) continue;\n\t\tconst key = `${deviceId}:${fingerprint}`;\n\t\tdiscoveredAddressesByPinnedPeer.set(\n\t\t\tkey,\n\t\t\tmergeAddresses(discoveredAddressesByPinnedPeer.get(key) ?? [], addresses),\n\t\t);\n\t}\n\tif (discoveredAddressesByPinnedPeer.size === 0) return 0;\n\n\tconst rows = db\n\t\t.prepare(\n\t\t\t\"SELECT peer_device_id, pinned_fingerprint, addresses_json, manual_addresses_json, last_success_address FROM sync_peers\",\n\t\t)\n\t\t.all() as StoredCoordinatorPeerAddressRow[];\n\tconst update = db.prepare(\n\t\t\"UPDATE sync_peers SET addresses_json = ?, manual_addresses_json = ? WHERE peer_device_id = ? AND pinned_fingerprint = ?\",\n\t);\n\tconst write = (addresses: string, manual: string, deviceId: string, fingerprint: string) => {\n\t\tupdate.run(addresses, manual, deviceId, fingerprint);\n\t};\n\tlet updated = 0;\n\tconst refresh = db.transaction(() => {\n\t\tfor (const row of rows) {\n\t\t\tif (refreshCoordinatorPeerRow(row, discoveredAddressesByPinnedPeer, write)) updated += 1;\n\t\t}\n\t});\n\trefresh.immediate();\n\treturn updated;\n}\n\ntype SharedManagedScopeState =\n\t| { state: \"authorized\"; groupId: string }\n\t| { state: \"not_authorized\" | \"indeterminate\" };\n\nexport interface SharedManagedScope {\n\treadonly scopeId: string;\n\treadonly groupId: string;\n}\n\nexport interface SharedManagedScopesQuery {\n\treadonly localDeviceId: string;\n\treadonly peerDeviceId: string;\n\treadonly coordinatorId: string;\n\t/** Null accepts every group under the coordinator. */\n\treadonly peerGroupIds: string[] | null;\n\treadonly peerPublicKey: string;\n\t/**\n\t * Space kinds to consider. Defaults to managed Projects, which coordinator\n\t * peer trust requires. Relay also routes through coordinator team Spaces.\n\t */\n\treadonly kinds?: readonly string[];\n}\n\n/**\n * Every active managed Space that both devices share under one coordinator,\n * with fresh cached authorization for both keys, ordered by scope ID.\n * `indeterminate` reports a shared Space whose authorization is only stale.\n */\nexport function sharedManagedScopes(\n\tdb: Database,\n\tquery: SharedManagedScopesQuery,\n): { scopes: SharedManagedScope[]; indeterminate: boolean } {\n\tconst { localDeviceId, peerDeviceId, coordinatorId, peerGroupIds, peerPublicKey } = query;\n\tconst kinds = query.kinds?.length ? query.kinds : [\"managed_project\"];\n\tconst localPublicKey = db\n\t\t.prepare(\"SELECT public_key FROM sync_device WHERE device_id = ?\")\n\t\t.pluck()\n\t\t.get(localDeviceId) as string | undefined;\n\tconst candidateScopes = db\n\t\t.prepare(\n\t\t\t`SELECT scope.scope_id, scope.coordinator_id, scope.group_id\n\t\t\t FROM scope_memberships local_member\n\t\t\t JOIN scope_memberships peer_member\n\t\t\t ON peer_member.scope_id = local_member.scope_id\n\t\t\t JOIN replication_scopes scope\n\t\t\t ON scope.scope_id = local_member.scope_id\n\t\t\t WHERE local_member.device_id = ?\n\t\t\t AND peer_member.device_id = ?\n\t\t\t AND scope.status = 'active'\n\t\t\t AND scope.kind IN (${kinds.map(() => \"?\").join(\", \")})\n\t\t\t AND scope.authority_type = 'coordinator'\n\t\t\t ORDER BY scope.scope_id`,\n\t\t)\n\t\t.all(localDeviceId, peerDeviceId, ...kinds) as Array<{\n\t\tscope_id: string;\n\t\tcoordinator_id: string | null;\n\t\tgroup_id: string | null;\n\t}>;\n\tconst scopes: SharedManagedScope[] = [];\n\tlet indeterminate = false;\n\tfor (const scope of candidateScopes) {\n\t\tconst scopeId = clean(scope.scope_id);\n\t\tconst groupId = clean(scope.group_id);\n\t\tif (\n\t\t\t!scopeId ||\n\t\t\tclean(scope.coordinator_id) !== coordinatorId ||\n\t\t\t!groupId ||\n\t\t\t(peerGroupIds !== null && !peerGroupIds.includes(groupId))\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst authority = { coordinatorId, groupId };\n\t\tconst localAuthorization = getEffectiveCachedScopeAuthorization(db, {\n\t\t\tdeviceId: localDeviceId,\n\t\t\tscopeId,\n\t\t\tauthority,\n\t\t\texpectedPublicKey: localPublicKey ?? \"\",\n\t\t});\n\t\tconst peerAuthorization = getEffectiveCachedScopeAuthorization(db, {\n\t\t\tdeviceId: peerDeviceId,\n\t\t\tscopeId,\n\t\t\tauthority,\n\t\t\texpectedPublicKey: peerPublicKey,\n\t\t});\n\t\tif (!localAuthorization.authorized || !peerAuthorization.authorized) continue;\n\t\tif (localAuthorization.freshness !== \"fresh\" || peerAuthorization.freshness !== \"fresh\") {\n\t\t\tindeterminate = true;\n\t\t\tcontinue;\n\t\t}\n\t\tscopes.push({ scopeId, groupId });\n\t}\n\treturn { scopes, indeterminate };\n}\n\nfunction sharedManagedScopeState(\n\tdb: Database,\n\tlocalDeviceId: string,\n\tpeerDeviceId: string,\n\tcoordinatorId: string,\n\tpeerGroupIds: string[] | null,\n\tpeerPublicKey: string,\n): SharedManagedScopeState {\n\tconst { scopes, indeterminate } = sharedManagedScopes(db, {\n\t\tlocalDeviceId,\n\t\tpeerDeviceId,\n\t\tcoordinatorId,\n\t\tpeerGroupIds,\n\t\tpeerPublicKey,\n\t});\n\t// Scopes are ordered by scope_id, so the group comes from the lowest authorized\n\t// scope ID. Earlier code took the first row in unspecified SQLite order.\n\tconst [first] = scopes;\n\tif (first) return { state: \"authorized\", groupId: first.groupId };\n\treturn { state: indeterminate ? \"indeterminate\" : \"not_authorized\" };\n}\n\n/**\n * Trust coordinator-discovered devices only after local policy proves that\n * both devices are active members of a Project managed by the exact\n * coordinator and group that supplied the discovered key.\n */\nfunction updateTrustedCoordinatorPeerAddresses(\n\tdb: Database,\n\tpeerDeviceId: string,\n\tpeer: Record<string, unknown>,\n\tfingerprint: string,\n\tpublicKey: string,\n): void {\n\tconst addresses = peer.stale ? [] : stringList(peer.addresses);\n\tupdatePeerAddresses(db, peerDeviceId, addresses, {\n\t\tname: clean(peer.display_name) || undefined,\n\t\tpinnedFingerprint: fingerprint,\n\t\tpublicKey,\n\t\tcoordinatorCandidates: true,\n\t});\n}\n\n/** Call ensureDeviceIdentity with this runtime's keys before trusting the stored local key. */\nexport function trustCoordinatorPeersWithSharedManagedScopes(\n\tdb: Database,\n\tlocalDeviceId: string,\n\tpeers: Record<string, unknown>[],\n): number {\n\tlet trusted = 0;\n\tfor (const peer of peers) {\n\t\tconst peerDeviceId = clean(peer.device_id);\n\t\tconst publicKey = clean(peer.public_key);\n\t\tconst fingerprint = clean(peer.fingerprint);\n\t\tconst coordinatorId = clean(peer.coordinator_id);\n\t\tconst peerGroupIds = coordinatorPeerGroups(peer.groups);\n\t\tif (\n\t\t\t!peerDeviceId ||\n\t\t\tpeerDeviceId === localDeviceId ||\n\t\t\t!publicKey ||\n\t\t\t!fingerprint ||\n\t\t\t!coordinatorId ||\n\t\t\t!peerGroupIds\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (!coordinatorPeerKeyMatchesFingerprint(publicKey, fingerprint)) continue;\n\t\tconst sharedScope = sharedManagedScopeState(\n\t\t\tdb,\n\t\t\tlocalDeviceId,\n\t\t\tpeerDeviceId,\n\t\t\tcoordinatorId,\n\t\t\tpeerGroupIds,\n\t\t\tpublicKey,\n\t\t);\n\t\tif (sharedScope.state !== \"authorized\") continue;\n\t\tconst existing = db\n\t\t\t.prepare(\n\t\t\t\t`SELECT pinned_fingerprint, public_key, claimed_local_actor, actor_id,\n\t\t\t\t pending_bootstrap_grant_id, trust_provenance\n\t\t\t\t FROM sync_peers WHERE peer_device_id = ? LIMIT 1`,\n\t\t\t)\n\t\t\t.get(peerDeviceId) as\n\t\t\t| {\n\t\t\t\t\tpinned_fingerprint: string | null;\n\t\t\t\t\tpublic_key: string | null;\n\t\t\t\t\tclaimed_local_actor: number;\n\t\t\t\t\tactor_id: string | null;\n\t\t\t\t\tpending_bootstrap_grant_id: string | null;\n\t\t\t\t\ttrust_provenance: string | null;\n\t\t\t }\n\t\t\t| undefined;\n\t\tif (\n\t\t\texisting &&\n\t\t\t(existing.claimed_local_actor === 1 ||\n\t\t\t\t(clean(existing.pinned_fingerprint) &&\n\t\t\t\t\tclean(existing.pinned_fingerprint) !== fingerprint) ||\n\t\t\t\t(clean(existing.public_key) && clean(existing.public_key) !== publicKey))\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst existingHasTrust = Boolean(\n\t\t\tclean(existing?.pinned_fingerprint) || clean(existing?.public_key),\n\t\t);\n\t\tconst policyDerivedTrust =\n\t\t\t!existing ||\n\t\t\t(existing.claimed_local_actor === 0 &&\n\t\t\t\texisting.actor_id == null &&\n\t\t\t\texisting.pending_bootstrap_grant_id == null &&\n\t\t\t\t(!existingHasTrust || existing.trust_provenance === \"coordinator_policy\"));\n\t\tupdateTrustedCoordinatorPeerAddresses(db, peerDeviceId, peer, fingerprint, publicKey);\n\t\tif (policyDerivedTrust) {\n\t\t\tdb.prepare(\n\t\t\t\t`UPDATE sync_peers SET discovered_via_coordinator_id = ?,\n\t\t\t\t discovered_via_group_id = ?, trust_provenance = 'coordinator_policy'\n\t\t\t\t WHERE peer_device_id = ?\n\t\t\t\t AND claimed_local_actor = 0 AND actor_id IS NULL\n\t\t\t\t AND pending_bootstrap_grant_id IS NULL`,\n\t\t\t).run(coordinatorId, sharedScope.groupId, peerDeviceId);\n\t\t}\n\t\ttrusted += 1;\n\t}\n\treturn trusted;\n}\n\nfunction coordinatorPeerKeyMatchesFingerprint(publicKey: string, fingerprint: string): boolean {\n\ttry {\n\t\treturn fingerprintPublicKey(publicKey) === fingerprint;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** Delete only policy-derived peer rows, and their sync progress, after their last fresh shared scope ends. */\nexport function revokeUnauthorizedCoordinatorPeerTrust(\n\tdb: Database,\n\tlocalDeviceId: string,\n): number {\n\treturn db.transaction(() => revokeCoordinatorPeerTrust(db, localDeviceId)).immediate();\n}\n\nfunction revokeCoordinatorPeerTrust(db: Database, localDeviceId: string): number {\n\tconst peers = db\n\t\t.prepare(\n\t\t\t`SELECT peer_device_id, public_key, discovered_via_coordinator_id, discovered_via_group_id\n\t\t\t FROM sync_peers\n\t\t\t WHERE claimed_local_actor = 0\n\t\t\t AND actor_id IS NULL\n\t\t\t AND pending_bootstrap_grant_id IS NULL\n\t\t\t AND trust_provenance = 'coordinator_policy'\n\t\t\t AND discovered_via_coordinator_id IS NOT NULL\n\t\t\t AND discovered_via_group_id IS NOT NULL\n\t\t\t AND (pinned_fingerprint IS NOT NULL OR public_key IS NOT NULL)`,\n\t\t)\n\t\t.all() as Array<{\n\t\tpeer_device_id: string;\n\t\tpublic_key: string | null;\n\t\tdiscovered_via_coordinator_id: string;\n\t\tdiscovered_via_group_id: string;\n\t}>;\n\tlet revoked = 0;\n\tfor (const peer of peers) {\n\t\tconst peerDeviceId = clean(peer.peer_device_id);\n\t\tconst coordinatorId = clean(peer.discovered_via_coordinator_id);\n\t\tconst groupId = clean(peer.discovered_via_group_id);\n\t\tif (!peerDeviceId || !coordinatorId || !groupId) continue;\n\t\t// Keep the stored key while any shared group under its coordinator still authorizes it.\n\t\tconst sharedScope = sharedManagedScopeState(\n\t\t\tdb,\n\t\t\tlocalDeviceId,\n\t\t\tpeerDeviceId,\n\t\t\tcoordinatorId,\n\t\t\tnull,\n\t\t\tclean(peer.public_key),\n\t\t);\n\t\tif (sharedScope.state !== \"not_authorized\") continue;\n\t\t// The device keeps its Identity binding: only this policy-derived pairing ended.\n\t\trevoked += removePairingState(db, {\n\t\t\tlocalDeviceId,\n\t\t\treason: \"policy\",\n\t\t\tpairings: [{ deviceId: peerDeviceId, coordinatorId, groupId }],\n\t\t}).syncPeers;\n\t}\n\treturn revoked;\n}\n\ninterface CoordinatorPeerRotation {\n\tpeerDeviceId: string;\n\tcoordinatorId: string;\n\tgroupId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n\tpreviousPublicKey: string;\n\tpreviousFingerprint: string;\n}\n\nfunction loadRotatablePolicyPeer(db: Database, peerDeviceId: string, coordinatorId: string) {\n\treturn db\n\t\t.prepare(\n\t\t\t`SELECT public_key, pinned_fingerprint FROM sync_peers\n\t\t\t WHERE peer_device_id = ? AND discovered_via_coordinator_id = ?\n\t\t\t AND trust_provenance = 'coordinator_policy'\n\t\t\t AND claimed_local_actor = 0 AND actor_id IS NULL\n\t\t\t AND pending_bootstrap_grant_id IS NULL`,\n\t\t)\n\t\t.get(peerDeviceId, coordinatorId) as\n\t\t| { public_key: string | null; pinned_fingerprint: string | null }\n\t\t| undefined;\n}\n\nfunction authorizedCoordinatorPeerRotation(\n\tdb: Database,\n\tlocalDeviceId: string,\n\tpeer: Record<string, unknown>,\n): CoordinatorPeerRotation | null {\n\tconst peerDeviceId = clean(peer.device_id);\n\tconst coordinatorId = clean(peer.coordinator_id);\n\tconst publicKey = clean(peer.public_key);\n\tconst fingerprint = clean(peer.fingerprint);\n\tconst groups = coordinatorPeerGroups(peer.groups);\n\tif (!peerDeviceId || peerDeviceId === localDeviceId || !coordinatorId || !groups) return null;\n\tif (!coordinatorPeerKeyMatchesFingerprint(publicKey, fingerprint)) return null;\n\tconst previous = loadRotatablePolicyPeer(db, peerDeviceId, coordinatorId);\n\tif (!previous?.public_key || !previous.pinned_fingerprint) return null;\n\tif (!coordinatorPeerKeyMatchesFingerprint(previous.public_key, previous.pinned_fingerprint))\n\t\treturn null;\n\tconst authorized = sharedManagedScopeState(\n\t\tdb,\n\t\tlocalDeviceId,\n\t\tpeerDeviceId,\n\t\tcoordinatorId,\n\t\tgroups,\n\t\tpublicKey,\n\t);\n\tif (authorized.state !== \"authorized\") return null;\n\t// Canonical aliases of the same key remain authorized and must not transfer retirement trust.\n\tconst previousAuthorization = sharedManagedScopeState(\n\t\tdb,\n\t\tlocalDeviceId,\n\t\tpeerDeviceId,\n\t\tcoordinatorId,\n\t\tnull,\n\t\tprevious.public_key,\n\t);\n\tif (previousAuthorization.state !== \"not_authorized\") return null;\n\treturn {\n\t\tpeerDeviceId,\n\t\tcoordinatorId,\n\t\tgroupId: authorized.groupId,\n\t\tpublicKey,\n\t\tfingerprint,\n\t\tpreviousPublicKey: previous.public_key,\n\t\tpreviousFingerprint: previous.pinned_fingerprint,\n\t};\n}\n\nfunction replaceCoordinatorPeerTrust(\n\tdb: Database,\n\tlocalDeviceId: string,\n\trotation: CoordinatorPeerRotation,\n): void {\n\tretainRetirementPeerTrust(db, { localDeviceId, peerDeviceId: rotation.peerDeviceId });\n\t// Only trust fields change: discovery cannot overwrite the peer's settings or runtime state.\n\tdb.prepare(\n\t\t`UPDATE sync_peers SET public_key = ?, pinned_fingerprint = ?, discovered_via_group_id = ?\n\t\t WHERE peer_device_id = ? AND discovered_via_coordinator_id = ?\n\t\t AND public_key = ? AND pinned_fingerprint = ?\n\t\t AND trust_provenance = 'coordinator_policy'\n\t\t AND claimed_local_actor = 0 AND actor_id IS NULL\n\t\t AND pending_bootstrap_grant_id IS NULL`,\n\t).run(\n\t\trotation.publicKey,\n\t\trotation.fingerprint,\n\t\trotation.groupId,\n\t\trotation.peerDeviceId,\n\t\trotation.coordinatorId,\n\t\trotation.previousPublicKey,\n\t\trotation.previousFingerprint,\n\t);\n}\n\nfunction reconcileCoordinatorPeerTrust(\n\tdb: Database,\n\tlocalDeviceId: string,\n\tpeers: Record<string, unknown>[],\n): number {\n\treturn db\n\t\t.transaction(() => {\n\t\t\tconst rotatedDevices = new Set<string>();\n\t\t\tfor (const peer of peers) {\n\t\t\t\tconst rotation = authorizedCoordinatorPeerRotation(db, localDeviceId, peer);\n\t\t\t\tif (!rotation) continue;\n\t\t\t\treplaceCoordinatorPeerTrust(db, localDeviceId, rotation);\n\t\t\t\trefreshRotatedCoordinatorPeerAddresses(db, rotation, peer);\n\t\t\t\trotatedDevices.add(rotation.peerDeviceId);\n\t\t\t}\n\t\t\trevokeCoordinatorPeerTrust(db, localDeviceId);\n\t\t\tconst remainingPeers = peers.filter((peer) => !rotatedDevices.has(clean(peer.device_id)));\n\t\t\treturn (\n\t\t\t\trotatedDevices.size +\n\t\t\t\ttrustCoordinatorPeersWithSharedManagedScopes(db, localDeviceId, remainingPeers)\n\t\t\t);\n\t\t})\n\t\t.immediate();\n}\n\nfunction refreshRotatedCoordinatorPeerAddresses(\n\tdb: Database,\n\trotation: CoordinatorPeerRotation,\n\tpeer: Record<string, unknown>,\n): void {\n\tif (peer.stale) return;\n\tconst row = db\n\t\t.prepare(\n\t\t\t`SELECT peer_device_id, pinned_fingerprint, addresses_json, manual_addresses_json,\n\t\t\t last_success_address FROM sync_peers WHERE peer_device_id = ?`,\n\t\t)\n\t\t.get(rotation.peerDeviceId) as StoredCoordinatorPeerAddressRow;\n\tconst addresses = new Map([\n\t\t[`${rotation.peerDeviceId}:${rotation.fingerprint}`, stringList(peer.addresses)],\n\t]);\n\trefreshCoordinatorPeerRow(row, addresses, (merged, manual, deviceId, fingerprint) => {\n\t\tdb.prepare(\n\t\t\t`UPDATE sync_peers SET addresses_json = ?,\n\t\t\t manual_addresses_json = COALESCE(manual_addresses_json, ?)\n\t\t\t WHERE peer_device_id = ? AND pinned_fingerprint = ?`,\n\t\t).run(merged, manual, deviceId, fingerprint);\n\t});\n}\n\nexport async function refreshAuthorizedCoordinatorPeerTrust(\n\tstore: PresenceStoreLike,\n\tconfig: CoordinatorSyncConfig,\n\toptions?: { keysDir?: string },\n): Promise<{ peers: Record<string, unknown>[]; trusted: number }> {\n\tif (!coordinatorEnabled(config)) return { peers: [], trusted: 0 };\n\tconst keysDir = options?.keysDir ?? (process.env.CODEMEM_KEYS_DIR?.trim() || undefined);\n\tconst [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir });\n\tconst peers = await lookupCoordinatorPeers(store, config, { keysDir });\n\trefreshStoredCoordinatorPeerAddresses(store.db, peers);\n\tconst trusted = reconcileCoordinatorPeerTrust(store.db, localDeviceId, peers);\n\treturn { peers, trusted };\n}\n\n/** The removed device's own side: which groups answered `device_removed`, or that one accepted it. */\nfunction recordRemovalNotice(db: Database, coordinatorId: string, lookup: PeerRemovalLookup): void {\n\tif (lookup.status === \"checked\") {\n\t\tclearCoordinatorDeviceRemoved(db, coordinatorId);\n\t\treturn;\n\t}\n\trecordCoordinatorDeviceRemoved(db, { coordinatorId, groupIds: lookup.removedFromGroups });\n}\n\n/**\n * Applies the coordinator's answer about this device's pairings and bound\n * devices: a blocked or removed device loses its pairing, its sync progress, and\n * its binding. It runs on its own, so a group that rejects presence or peer\n * lookups can't block it. An unknown answer keeps every pairing until a later\n * check succeeds. A changed pairing generation invalidates the whole peer\n * answer. After a complete lookup the coordinator's removal number is stored\n * for the next presence update.\n */\nexport async function removeCoordinatorRevokedPeers(\n\tstore: PresenceStoreLike,\n\tconfig: CoordinatorSyncConfig,\n\toptions?: { keysDir?: string },\n): Promise<{\n\trevoked: number;\n\tremoved: number;\n\t/** Devices the coordinator still holds an enrollment for. Nothing here acts on them. */\n\tenrolled: string[];\n\tstatus: PeerRevocationCheckStatus;\n}> {\n\tif (!coordinatorEnabled(config))\n\t\treturn { revoked: 0, removed: 0, enrolled: [], status: \"unsupported\" };\n\tconst keysDir = options?.keysDir ?? (process.env.CODEMEM_KEYS_DIR?.trim() || undefined);\n\tconst [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir });\n\tconst lookup = await fetchPeerRemovalLookup(store, config, { localDeviceId, keysDir });\n\tconst db = store.db;\n\tconst coordinatorId = buildBaseUrl(config.syncCoordinatorUrl);\n\tif (lookup.status !== \"checked\") {\n\t\trecordRemovalNotice(db, coordinatorId, lookup);\n\t\treturn { revoked: 0, removed: 0, enrolled: [], status: lookup.status };\n\t}\n\n\treturn db\n\t\t.transaction(() => {\n\t\t\t// Hold the write lock from the generation check through cleanup and acknowledgement.\n\t\t\tconst generation = lookup.generation;\n\t\t\tif (generation === null || readPeerRemovalCheckState(db)?.generation !== generation) {\n\t\t\t\treturn { revoked: 0, removed: 0, enrolled: [], status: \"failed\" as const };\n\t\t\t}\n\t\t\trecordRemovalNotice(db, coordinatorId, lookup);\n\t\t\tconst revoked = removeRevokedPeers(db, localDeviceId, lookup.revoked);\n\t\t\tconst removed = removePairingState(db, {\n\t\t\t\tlocalDeviceId,\n\t\t\t\treason: \"removed\",\n\t\t\t\tdeviceIds: lookup.removed.filter((deviceId) => deviceId !== localDeviceId),\n\t\t\t}).syncPeers;\n\t\t\tif (lookup.removalSeq !== null) {\n\t\t\t\tstoreAppliedRemovalSeq(db, { generation, removalSeq: lookup.removalSeq });\n\t\t\t}\n\t\t\treturn { revoked, removed, enrolled: lookup.enrolled, status: lookup.status };\n\t\t})\n\t\t.immediate();\n}\n\n/**\n * Fetch the set of coordinator peer device IDs whose presence has expired.\n *\n * Returns an empty set when the coordinator is disabled or the lookup fails.\n * Intended as a best-effort preflight for the sync daemon — failures degrade\n * gracefully to the existing reactive shouldSkipOfflinePeer backoff.\n */\nexport async function fetchCoordinatorStalePeers(\n\tdb: Database,\n\tdbPath: string,\n\tkeysDir?: string,\n\toptions?: { peers?: Record<string, unknown>[] },\n): Promise<Set<string>> {\n\t// A caller that already looked peers up this tick passes that snapshot in.\n\t// Its addresses have been stored by refreshAuthorizedCoordinatorPeerTrust\n\t// already, so reusing it skips a second identical /v1/peers round trip and\n\t// a duplicate refreshStoredCoordinatorPeerAddresses write. The snapshot is\n\t// seconds old, which is well inside the tolerance of a best-effort offline\n\t// preflight.\n\tif (options?.peers) return coordinatorStalePeerKeys(options.peers);\n\tconst config = readCoordinatorSyncConfig();\n\tif (!coordinatorEnabled(config)) return new Set();\n\ttry {\n\t\tconst peers = await lookupCoordinatorPeers({ db, dbPath }, config, { keysDir });\n\t\trefreshStoredCoordinatorPeerAddresses(db, peers);\n\t\treturn coordinatorStalePeerKeys(peers);\n\t} catch {\n\t\t// Best-effort: if coordinator lookup fails, skip the optimization.\n\t\treturn new Set();\n\t}\n}\n\n/**\n * Reduce a coordinator peer listing to the device IDs and pinned peer keys\n * whose presence has expired.\n *\n * Split out of fetchCoordinatorStalePeers so a caller holding a peer snapshot\n * can derive the same set without repeating the lookup.\n */\nexport function coordinatorStalePeerKeys(peers: Record<string, unknown>[]): Set<string> {\n\t// A device may appear under multiple fingerprints (key rotation, multi-group).\n\t// Skip device-wide only when all entries are stale, but also return pinned\n\t// peer keys so an old trusted fingerprint stays fail-closed even when the\n\t// same device id has a fresh replacement fingerprint.\n\tconst freshDevices = new Set<string>();\n\tconst staleDevices = new Set<string>();\n\tconst freshPinnedPeers = new Set<string>();\n\tconst stalePinnedPeers = new Set<string>();\n\tfor (const peer of peers) {\n\t\tconst deviceId = clean(peer.device_id);\n\t\tif (!deviceId) continue;\n\t\tconst fingerprint = clean(peer.fingerprint);\n\t\tconst pinnedPeerKey = fingerprint ? `${deviceId}:${fingerprint}` : \"\";\n\t\tif (peer.stale) {\n\t\t\tstaleDevices.add(deviceId);\n\t\t\tif (pinnedPeerKey) stalePinnedPeers.add(pinnedPeerKey);\n\t\t} else {\n\t\t\tfreshDevices.add(deviceId);\n\t\t\tif (pinnedPeerKey) freshPinnedPeers.add(pinnedPeerKey);\n\t\t}\n\t}\n\t// Remove any device that has at least one fresh entry\n\tfor (const deviceId of freshDevices) {\n\t\tstaleDevices.delete(deviceId);\n\t}\n\tfor (const pinnedPeerKey of freshPinnedPeers) {\n\t\tstalePinnedPeers.delete(pinnedPeerKey);\n\t}\n\treturn new Set([...staleDevices, ...stalePinnedPeers]);\n}\n\nexport async function listCoordinatorReciprocalApprovals(\n\tstore: MemoryStore,\n\tconfig: CoordinatorSyncConfig,\n\toptions: { direction: \"incoming\" | \"outgoing\"; status?: string },\n): Promise<CoordinatorReciprocalApproval[]> {\n\tif (!coordinatorEnabled(config)) return [];\n\tconst keysDir = process.env.CODEMEM_KEYS_DIR?.trim() || undefined;\n\tconst [deviceId] = ensureDeviceIdentity(store.db, { keysDir });\n\tconst baseUrl = buildBaseUrl(config.syncCoordinatorUrl);\n\tconst merged = new Map<string, CoordinatorReciprocalApproval>();\n\tfor (const groupId of config.syncCoordinatorGroups) {\n\t\tconst params = new URLSearchParams({\n\t\t\tgroup_id: groupId,\n\t\t\tdirection: options.direction,\n\t\t\tstatus: options.status?.trim() || \"pending\",\n\t\t});\n\t\tconst url = `${baseUrl}/v1/reciprocal-approvals?${params.toString()}`;\n\t\tconst headers = buildAuthHeaders({\n\t\t\tdeviceId,\n\t\t\tdbPath: store.dbPath,\n\t\t\tmethod: \"GET\",\n\t\t\turl,\n\t\t\tbodyBytes: Buffer.alloc(0),\n\t\t\tkeysDir,\n\t\t});\n\t\tconst [status, response] = await requestJson(\"GET\", url, {\n\t\t\theaders,\n\t\t\ttimeoutS: Math.max(1, config.syncCoordinatorTimeoutS),\n\t\t});\n\t\tif (status !== 200 || !response) {\n\t\t\tconst detail = typeof response?.error === \"string\" ? response.error : \"unknown\";\n\t\t\tthrow new Error(`coordinator reciprocal approval lookup failed (${status}: ${detail})`);\n\t\t}\n\t\tconst items = Array.isArray(response.items) ? response.items : [];\n\t\tfor (const item of items) {\n\t\t\tif (!item || typeof item !== \"object\") continue;\n\t\t\tconst record = item as CoordinatorReciprocalApproval;\n\t\t\tconst requestId = clean(record.request_id);\n\t\t\tif (!requestId) continue;\n\t\t\tmerged.set(requestId, record);\n\t\t}\n\t}\n\treturn [...merged.values()];\n}\n\nexport async function createCoordinatorReciprocalApproval(\n\tstore: MemoryStore,\n\tconfig: CoordinatorSyncConfig,\n\toptions: {\n\t\tgroupId: string;\n\t\trequestedDeviceId: string;\n\t\texpectedIncomingRequestId?: string;\n\t},\n): Promise<CoordinatorReciprocalApproval> {\n\tif (!coordinatorEnabled(config)) throw new Error(\"Coordinator not configured.\");\n\tconst groupId = options.groupId.trim();\n\tconst requestedDeviceId = options.requestedDeviceId.trim();\n\tconst expectedIncomingRequestId = options.expectedIncomingRequestId?.trim();\n\tif (!groupId || !requestedDeviceId) {\n\t\tthrow new Error(\"groupId and requestedDeviceId are required.\");\n\t}\n\tif (options.expectedIncomingRequestId !== undefined && !expectedIncomingRequestId) {\n\t\tthrow new Error(\"expectedIncomingRequestId must not be empty when provided.\");\n\t}\n\tconst keysDir = process.env.CODEMEM_KEYS_DIR?.trim() || undefined;\n\tconst [deviceId] = ensureDeviceIdentity(store.db, { keysDir });\n\tconst baseUrl = buildBaseUrl(config.syncCoordinatorUrl);\n\tconst url = `${baseUrl}/v1/reciprocal-approvals`;\n\tconst payload = {\n\t\tgroup_id: groupId,\n\t\trequested_device_id: requestedDeviceId,\n\t\t...(expectedIncomingRequestId !== undefined\n\t\t\t? { expected_incoming_request_id: expectedIncomingRequestId }\n\t\t\t: {}),\n\t};\n\tconst bodyBytes = Buffer.from(JSON.stringify(payload), \"utf8\");\n\tconst headers = buildAuthHeaders({\n\t\tdeviceId,\n\t\tdbPath: store.dbPath,\n\t\tmethod: \"POST\",\n\t\turl,\n\t\tbodyBytes,\n\t\tkeysDir,\n\t});\n\tconst [status, response] = await requestJson(\"POST\", url, {\n\t\theaders,\n\t\tbody: payload,\n\t\tbodyBytes,\n\t\ttimeoutS: Math.max(1, config.syncCoordinatorTimeoutS),\n\t});\n\tif (status !== 200 || !response || !response.request || typeof response.request !== \"object\") {\n\t\tconst detail = typeof response?.error === \"string\" ? response.error : \"unknown\";\n\t\tif (status === 409 && detail === \"reciprocal_approval_request_changed\") {\n\t\t\tinvalidateCoordinatorStatusCache(coordinatorStatusCacheKey(store, config));\n\t\t\tthrow new CoordinatorReciprocalApprovalRequestChangedError();\n\t\t}\n\t\tthrow new Error(`coordinator reciprocal approval create failed (${status}: ${detail})`);\n\t}\n\tinvalidateCoordinatorStatusCache(coordinatorStatusCacheKey(store, config));\n\treturn response.request as CoordinatorReciprocalApproval;\n}\n\nfunction indexReciprocalApprovalsByPeer(\n\titems: CoordinatorReciprocalApproval[],\n\tkey: \"requesting_device_id\" | \"requested_device_id\",\n): Map<string, CoordinatorReciprocalApproval> {\n\tconst indexed = new Map<string, CoordinatorReciprocalApproval>();\n\tfor (const item of items) {\n\t\tconst deviceId = clean(item[key]);\n\t\tif (!deviceId) continue;\n\t\tindexed.set(deviceId, item);\n\t}\n\treturn indexed;\n}\n\nexport async function coordinatorStatusSnapshot(\n\tstore: MemoryStore,\n\tconfig: CoordinatorSyncConfig,\n): Promise<Record<string, unknown>> {\n\tconst currentPairedPeerCount = pairedPeerCount(store);\n\tif (!coordinatorEnabled(config)) {\n\t\treturn {\n\t\t\tenabled: false,\n\t\t\tconfigured: false,\n\t\t\tsync_enabled: config.syncEnabled,\n\t\t\tcoordinator_url: config.syncCoordinatorUrl || null,\n\t\t\tgroups: config.syncCoordinatorGroups,\n\t\t\tpaired_peer_count: currentPairedPeerCount,\n\t\t};\n\t}\n\tconst keysDir = process.env.CODEMEM_KEYS_DIR?.trim() || undefined;\n\tconst [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir });\n\tconst cacheKey = coordinatorStatusCacheKey(store, config);\n\tconst cacheGeneration = coordinatorStatusCacheGenerations.get(cacheKey) ?? 0;\n\tlet now = Date.now();\n\tconst cachedSnapshot = coordinatorStatusCache.get(cacheKey);\n\tif (cachedSnapshot && now < cachedSnapshot.nextRefreshAtMs) {\n\t\tconst snapshot = structuredClone(cachedSnapshot.snapshot);\n\t\tawait refreshCoordinatorPresenceStatus(store, config, snapshot, now);\n\t\tnow = Date.now();\n\t\tif (snapshot.presence_status === \"not_enrolled\") {\n\t\t\tinvalidateCoordinatorStatusCache(cacheKey);\n\t\t\tsnapshot.fresh_peer_count = 0;\n\t\t\tsnapshot.stale_peer_count = 0;\n\t\t\tsnapshot.discovered_peer_count = 0;\n\t\t\tsnapshot.discovered_devices = [];\n\t\t\tsnapshot.reciprocal_approvals = { incoming: [], outgoing: [] };\n\t\t\treturn {\n\t\t\t\t...snapshot,\n\t\t\t\tpaired_peer_count: pairedPeerCount(store),\n\t\t\t};\n\t\t}\n\t\tif (now < cachedSnapshot.nextRefreshAtMs) {\n\t\t\treconcileCoordinatorPeerTrust(store.db, localDeviceId, cachedSnapshot.discoveredPeers);\n\t\t\treturn {\n\t\t\t\t...snapshot,\n\t\t\t\tpaired_peer_count: pairedPeerCount(store),\n\t\t\t};\n\t\t}\n\t}\n\tconst snapshot: Record<string, unknown> = {\n\t\tenabled: true,\n\t\tconfigured: true,\n\t\tsync_enabled: config.syncEnabled,\n\t\tcoordinator_url: config.syncCoordinatorUrl,\n\t\tgroups: config.syncCoordinatorGroups,\n\t\tpaired_peer_count: currentPairedPeerCount,\n\t\tpresence_status: \"unknown\",\n\t\tpresence_error: null,\n\t\tadvertised_addresses: [],\n\t\tfresh_peer_count: 0,\n\t\tstale_peer_count: 0,\n\t\tdiscovered_peer_count: 0,\n\t\tdiscovered_devices: [],\n\t};\n\tawait refreshCoordinatorPresenceStatus(store, config, snapshot, now);\n\tlet discoveredPeers: Record<string, unknown>[] = [];\n\ttry {\n\t\tconst { peers } = await refreshAuthorizedCoordinatorPeerTrust(store, config, { keysDir });\n\t\tdiscoveredPeers = structuredClone(peers);\n\t\tlet incomingApprovals: CoordinatorReciprocalApproval[] = [];\n\t\tlet outgoingApprovals: CoordinatorReciprocalApproval[] = [];\n\t\ttry {\n\t\t\tincomingApprovals = await listCoordinatorReciprocalApprovals(store, config, {\n\t\t\t\tdirection: \"incoming\",\n\t\t\t});\n\t\t\toutgoingApprovals = await listCoordinatorReciprocalApprovals(store, config, {\n\t\t\t\tdirection: \"outgoing\",\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tsnapshot.reciprocal_approval_error = error instanceof Error ? error.message : String(error);\n\t\t}\n\t\tconst incomingByPeer = indexReciprocalApprovalsByPeer(\n\t\t\tincomingApprovals,\n\t\t\t\"requesting_device_id\",\n\t\t);\n\t\tconst outgoingByPeer = indexReciprocalApprovalsByPeer(outgoingApprovals, \"requested_device_id\");\n\t\tsnapshot.discovered_peer_count = peers.length;\n\t\tsnapshot.fresh_peer_count = peers.filter((peer) => !peer.stale).length;\n\t\tsnapshot.stale_peer_count = peers.filter((peer) => Boolean(peer.stale)).length;\n\t\tsnapshot.reciprocal_approvals = {\n\t\t\tincoming: incomingApprovals,\n\t\t\toutgoing: outgoingApprovals,\n\t\t};\n\t\tsnapshot.discovered_devices = peers.map((peer) =>\n\t\t\tdiscoveredPeerStatus(peer, incomingByPeer, outgoingByPeer),\n\t\t);\n\t} catch (error) {\n\t\tsnapshot.lookup_error = error instanceof Error ? error.message : String(error);\n\t}\n\tif (\n\t\tsnapshot.presence_status !== \"not_enrolled\" &&\n\t\t!snapshot.lookup_error &&\n\t\t!snapshot.reciprocal_approval_error &&\n\t\t(coordinatorStatusCacheGenerations.get(cacheKey) ?? 0) === cacheGeneration\n\t) {\n\t\tcoordinatorStatusCache.set(cacheKey, {\n\t\t\tsnapshot: structuredClone(snapshot),\n\t\t\tdiscoveredPeers,\n\t\t\tnextRefreshAtMs: coordinatorStatusRefreshDeadline(Date.now(), discoveredPeers),\n\t\t});\n\t}\n\treturn snapshot;\n}\n\nfunction discoveredPeerStatus(\n\tpeer: Record<string, unknown>,\n\tincomingByPeer: ReadonlyMap<string, CoordinatorReciprocalApproval>,\n\toutgoingByPeer: ReadonlyMap<string, CoordinatorReciprocalApproval>,\n) {\n\tconst incoming = incomingByPeer.get(clean(peer.device_id));\n\tconst outgoing = outgoingByPeer.get(clean(peer.device_id));\n\treturn {\n\t\tdevice_id: peer.device_id,\n\t\tdisplay_name: peer.display_name ?? null,\n\t\tfingerprint: peer.fingerprint ?? null,\n\t\taddresses: Array.isArray(peer.addresses) ? peer.addresses : [],\n\t\tgroups: Array.isArray(peer.groups) ? peer.groups : [],\n\t\tlast_seen_at: peer.last_seen_at ?? null,\n\t\texpires_at: peer.expires_at ?? null,\n\t\tstale: Boolean(peer.stale),\n\t\tneeds_local_approval: Boolean(incoming),\n\t\twaiting_for_peer_approval: Boolean(outgoing),\n\t\tincoming_reciprocal_request_id: incoming?.request_id ?? null,\n\t\toutgoing_reciprocal_request_id: outgoing?.request_id ?? null,\n\t};\n}\n\nexport async function listCoordinatorJoinRequests(\n\tconfig: CoordinatorSyncConfig,\n): Promise<Record<string, unknown>[]> {\n\tconst groupId = config.syncCoordinatorGroup || config.syncCoordinatorGroups[0] || \"\";\n\tif (!groupId || !config.syncCoordinatorUrl || !config.syncCoordinatorAdminSecret) return [];\n\tconst url = `${buildBaseUrl(config.syncCoordinatorUrl)}/v1/admin/join-requests?group_id=${encodeURIComponent(groupId)}`;\n\tconst [status, response] = await requestJson(\"GET\", url, {\n\t\theaders: { \"X-Codemem-Coordinator-Admin\": config.syncCoordinatorAdminSecret },\n\t\ttimeoutS: Math.max(1, config.syncCoordinatorTimeoutS),\n\t});\n\tif (status !== 200 || !response) return [];\n\treturn Array.isArray(response.items)\n\t\t? response.items.filter(\n\t\t\t\t(item): item is Record<string, unknown> => Boolean(item) && typeof item === \"object\",\n\t\t\t)\n\t\t: [];\n}\n"],"mappings":";;;;;;;AAmCA,IAAa,IAAb,cAAmD,MAAM;CACxD;CAEA,YAAY,GAAyC;EAGpD,AAFA,MAAM,CAAI,GACV,KAAK,OAAO,iCACZ,KAAK,OAAO;CACb;AACD;AAQA,SAAS,IAA2B;CACnC,MAAM,IAAI,EAA8B,+BAA+B;AACxE;AAEA,SAAS,GAAmB,GAAyB;CACpD,OACC,OAAO,KAAU,cACjB,KACA,UAAU,KACV,EAAM,SAAS;AAEjB;AAEA,SAAS,GAAkB,GAAc,GAAwC;CAChF,OACE,EACC,QACA,sGAGD,CAAC,CACA,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,QAAQ,EAAS,KAAK,IAChC,EAAS,MAAM,QACd,MAA0C,EAAQ,KAAS,OAAO,KAAS,QAC7E,IACC,CAAC;AACL"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type PeerRevocationCheckStatus } from "./coordinator-peer-revocation.js";
|
|
1
2
|
import { type CoordinatorReciprocalApproval } from "./coordinator-store-contract.js";
|
|
2
3
|
import { type CoordinatorSyncConfig } from "./coordinator-sync-config.js";
|
|
3
4
|
import type { Database } from "./db.js";
|
|
@@ -43,7 +44,7 @@ export declare function sharedManagedScopes(db: Database, query: SharedManagedSc
|
|
|
43
44
|
};
|
|
44
45
|
/** Call ensureDeviceIdentity with this runtime's keys before trusting the stored local key. */
|
|
45
46
|
export declare function trustCoordinatorPeersWithSharedManagedScopes(db: Database, localDeviceId: string, peers: Record<string, unknown>[]): number;
|
|
46
|
-
/** Delete only policy-derived peer rows after their last fresh shared scope ends. */
|
|
47
|
+
/** Delete only policy-derived peer rows, and their sync progress, after their last fresh shared scope ends. */
|
|
47
48
|
export declare function revokeUnauthorizedCoordinatorPeerTrust(db: Database, localDeviceId: string): number;
|
|
48
49
|
export declare function refreshAuthorizedCoordinatorPeerTrust(store: PresenceStoreLike, config: CoordinatorSyncConfig, options?: {
|
|
49
50
|
keysDir?: string;
|
|
@@ -51,6 +52,24 @@ export declare function refreshAuthorizedCoordinatorPeerTrust(store: PresenceSto
|
|
|
51
52
|
peers: Record<string, unknown>[];
|
|
52
53
|
trusted: number;
|
|
53
54
|
}>;
|
|
55
|
+
/**
|
|
56
|
+
* Applies the coordinator's answer about this device's pairings and bound
|
|
57
|
+
* devices: a blocked or removed device loses its pairing, its sync progress, and
|
|
58
|
+
* its binding. It runs on its own, so a group that rejects presence or peer
|
|
59
|
+
* lookups can't block it. An unknown answer keeps every pairing until a later
|
|
60
|
+
* check succeeds. A changed pairing generation invalidates the whole peer
|
|
61
|
+
* answer. After a complete lookup the coordinator's removal number is stored
|
|
62
|
+
* for the next presence update.
|
|
63
|
+
*/
|
|
64
|
+
export declare function removeCoordinatorRevokedPeers(store: PresenceStoreLike, config: CoordinatorSyncConfig, options?: {
|
|
65
|
+
keysDir?: string;
|
|
66
|
+
}): Promise<{
|
|
67
|
+
revoked: number;
|
|
68
|
+
removed: number;
|
|
69
|
+
/** Devices the coordinator still holds an enrollment for. Nothing here acts on them. */
|
|
70
|
+
enrolled: string[];
|
|
71
|
+
status: PeerRevocationCheckStatus;
|
|
72
|
+
}>;
|
|
54
73
|
/**
|
|
55
74
|
* Fetch the set of coordinator peer device IDs whose presence has expired.
|
|
56
75
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"coordinator-runtime.d.ts","sourceRoot":"","sources":["../src/coordinator-runtime.ts"],"names":[],"mappings":"AAOA,OAAO,EACN,KAAK,6BAA6B,EAElC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACN,KAAK,qBAAqB,EAG1B,MAAM,8BAA8B,CAAC;AACtC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"coordinator-runtime.d.ts","sourceRoot":"","sources":["../src/coordinator-runtime.ts"],"names":[],"mappings":"AAOA,OAAO,EAGN,KAAK,yBAAyB,EAC9B,MAAM,kCAAkC,CAAC;AAK1C,OAAO,EACN,KAAK,6BAA6B,EAElC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACN,KAAK,qBAAqB,EAG1B,MAAM,8BAA8B,CAAC;AACtC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAUxC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAQ9C,OAAO,EACN,KAAK,qBAAqB,EAC1B,kBAAkB,EAClB,yBAAyB,GACzB,MAAM,8BAA8B,CAAC;AAEtC,KAAK,iBAAiB,GAAG,IAAI,CAAC,WAAW,EAAE,IAAI,GAAG,QAAQ,CAAC,CAAC;AA8K5D,wBAAgB,uBAAuB,C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AA;CAAE,GAC7C,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAkBtB;AAED;;;;;;GAMG;AACH,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,GAAG,CAAC,MAAM,CAAC,CA8BtF;AAED,wBAAsB,kCAAkC,CACvD,KAAK,EAAE,WAAW,EAClB,MAAM,EAAE,qBAAqB,EAC7B,OAAO,EAAE;IAAE,SAAS,EAAE,UAAU,GAAG,UAAU,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,GAC9D,OAAO,CAAC,6BAA6B,EAAE,CAAC,CAuC1C;AAED,wBAAsB,mCAAmC,CACxD,KAAK,EAAE,WAAW,EAClB,MAAM,EAAE,qBAAqB,EAC7B,OAAO,EAAE;IACR,OAAO,EAAE,MAAM,CAAC;IAChB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,yBAAyB,CAAC,EAAE,MAAM,CAAC;CACnC,GACC,OAAO,CAAC,6BAA6B,CAAC,CA+CxC;AAeD,wBAAsB,yBAAyB,CAC9C,KAAK,EAAE,WAAW,EAClB,MAAM,EAAE,qBAAqB,GAC3B,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAyGlC;AAyBD,wBAAsB,2BAA2B,CAChD,MAAM,EAAE,qBAAqB,GAC3B,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC,CAcpC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"coordinator-scope-authorization-api-test-harness.d.ts","sourceRoot":"","sources":["../src/coordinator-scope-authorization-api-test-harness.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"coordinator-scope-authorization-api-test-harness.d.ts","sourceRoot":"","sources":["../src/coordinator-scope-authorization-api-test-harness.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EACX,eAAe,EACf,YAAY,EACZ,MAAM,oDAAoD,CAAC;AAC5D,OAAO,EAAsB,KAAK,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAGpF,KAAK,IAAI,GAAG,UAAU,CAAC,OAAO,eAAe,CAAC,CAAC;AAC/C,eAAO,MAAM,aAAa,QAAqC,CAAC;AAqFhE,wBAAgB,6BAA6B,CAAC,IAAI,EAAE,IAAI,QAMvD;AAwTD,wBAAgB,2BAA2B,CAC1C,IAAI,EAAE,IAAI,EACV,QAAQ,EAAE,CAAC,CAAC,EAAE,YAAY,KAAK,cAAc,QA2C7C"}
|