@codemem/core 0.49.0-beta.1 → 0.49.0-beta.3

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.
Files changed (207) hide show
  1. package/dist/better-sqlite-coordinator-store.d.ts +21 -2
  2. package/dist/better-sqlite-coordinator-store.d.ts.map +1 -1
  3. package/dist/coordinator-account-change-authority.d.ts +56 -0
  4. package/dist/coordinator-account-change-authority.d.ts.map +1 -0
  5. package/dist/coordinator-account-change-decision.d.ts +141 -0
  6. package/dist/coordinator-account-change-decision.d.ts.map +1 -0
  7. package/dist/coordinator-account-change-http-test-fixtures.d.ts +3 -1
  8. package/dist/coordinator-account-change-http-test-fixtures.d.ts.map +1 -1
  9. package/dist/coordinator-account-change-original-sql-test-fixtures.d.ts +61 -0
  10. package/dist/coordinator-account-change-original-sql-test-fixtures.d.ts.map +1 -0
  11. package/dist/coordinator-account-change.d.ts +7 -1
  12. package/dist/coordinator-account-change.d.ts.map +1 -1
  13. package/dist/coordinator-account-connection-link.d.ts +1 -1
  14. package/dist/coordinator-account-connection-link.d.ts.map +1 -1
  15. package/dist/coordinator-account-connection-schema.d.ts +31 -0
  16. package/dist/coordinator-account-connection-schema.d.ts.map +1 -1
  17. package/dist/coordinator-account-connection-session.d.ts +9 -0
  18. package/dist/coordinator-account-connection-session.d.ts.map +1 -1
  19. package/dist/coordinator-account-historical-revoke-original-sql-test-fixtures.d.ts +7 -0
  20. package/dist/coordinator-account-historical-revoke-original-sql-test-fixtures.d.ts.map +1 -0
  21. package/dist/coordinator-account-historical-revoke.d.ts +8 -2
  22. package/dist/coordinator-account-historical-revoke.d.ts.map +1 -1
  23. package/dist/coordinator-account-link-status-client.d.ts +4 -0
  24. package/dist/coordinator-account-link-status-client.d.ts.map +1 -1
  25. package/dist/coordinator-account-link-status.d.ts.map +1 -1
  26. package/dist/coordinator-account-schema-sqlite-test-fixtures.d.ts +58 -0
  27. package/dist/coordinator-account-schema-sqlite-test-fixtures.d.ts.map +1 -0
  28. package/dist/coordinator-account-schema-test-fixtures.d.ts +20 -0
  29. package/dist/coordinator-account-schema-test-fixtures.d.ts.map +1 -0
  30. package/dist/coordinator-api.d.ts.map +1 -1
  31. package/dist/coordinator-auth-browser-owner-purpose-test-harness.d.ts.map +1 -1
  32. package/dist/coordinator-auth-browser-transaction-test-fixtures.d.ts.map +1 -1
  33. package/dist/coordinator-auth-browser-transaction.d.ts.map +1 -1
  34. package/dist/coordinator-auth-controller-consistency-test-fixtures.d.ts +5 -1
  35. package/dist/coordinator-auth-controller-consistency-test-fixtures.d.ts.map +1 -1
  36. package/dist/coordinator-auth-controller-history.d.ts +0 -1
  37. package/dist/coordinator-auth-controller-history.d.ts.map +1 -1
  38. package/dist/coordinator-auth-controller-original-sql-test-fixtures.d.ts +41 -0
  39. package/dist/coordinator-auth-controller-original-sql-test-fixtures.d.ts.map +1 -0
  40. package/dist/coordinator-auth-controller-owner.d.ts +0 -6
  41. package/dist/coordinator-auth-controller-owner.d.ts.map +1 -1
  42. package/dist/coordinator-auth-controller-race-test-fixtures.d.ts +38 -0
  43. package/dist/coordinator-auth-controller-race-test-fixtures.d.ts.map +1 -0
  44. package/dist/coordinator-auth-controller-read-set.d.ts +47 -0
  45. package/dist/coordinator-auth-controller-read-set.d.ts.map +1 -0
  46. package/dist/coordinator-auth-controller-stages-original-sql-test-fixtures.d.ts +8 -0
  47. package/dist/coordinator-auth-controller-stages-original-sql-test-fixtures.d.ts.map +1 -0
  48. package/dist/coordinator-auth-controller.d.ts +1 -21
  49. package/dist/coordinator-auth-controller.d.ts.map +1 -1
  50. package/dist/coordinator-auth-device-claim-eligibility.d.ts +51 -2
  51. package/dist/coordinator-auth-device-claim-eligibility.d.ts.map +1 -1
  52. package/dist/coordinator-auth-historical-store-test-fixture.d.ts +2 -0
  53. package/dist/coordinator-auth-historical-store-test-fixture.d.ts.map +1 -1
  54. package/dist/coordinator-auth-legacy-assignment.d.ts +4 -2
  55. package/dist/coordinator-auth-legacy-assignment.d.ts.map +1 -1
  56. package/dist/coordinator-auth-link-authority-upgrade.d.ts +5 -0
  57. package/dist/coordinator-auth-link-authority-upgrade.d.ts.map +1 -1
  58. package/dist/coordinator-auth-link-maintenance-fixtures.d.ts +2 -2
  59. package/dist/coordinator-auth-link-maintenance-fixtures.d.ts.map +1 -1
  60. package/dist/coordinator-auth-link-provenance.d.ts.map +1 -1
  61. package/dist/coordinator-auth-link-revocation-test-harness.d.ts.map +1 -1
  62. package/dist/coordinator-auth-link-test-fixtures.d.ts +26 -4
  63. package/dist/coordinator-auth-link-test-fixtures.d.ts.map +1 -1
  64. package/dist/coordinator-auth-link.d.ts +5 -0
  65. package/dist/coordinator-auth-link.d.ts.map +1 -1
  66. package/dist/coordinator-auth-read-set.d.ts +99 -0
  67. package/dist/coordinator-auth-read-set.d.ts.map +1 -0
  68. package/dist/coordinator-auth-schema-stage.d.ts +36 -0
  69. package/dist/coordinator-auth-schema-stage.d.ts.map +1 -0
  70. package/dist/coordinator-auth-schema.d.ts.map +1 -1
  71. package/dist/coordinator-auth-session.d.ts.map +1 -1
  72. package/dist/coordinator-auth-store-test-fixtures.d.ts +12 -0
  73. package/dist/coordinator-auth-store-test-fixtures.d.ts.map +1 -1
  74. package/dist/coordinator-controller-revocation-test-harness.d.ts.map +1 -1
  75. package/dist/coordinator-d1-schema-inventory.d.ts +10 -0
  76. package/dist/coordinator-d1-schema-inventory.d.ts.map +1 -0
  77. package/dist/coordinator-device-claim-binding-contract.d.ts +37 -0
  78. package/dist/coordinator-device-claim-binding-contract.d.ts.map +1 -0
  79. package/dist/coordinator-device-claim-binding-reuse.d.ts +23 -0
  80. package/dist/coordinator-device-claim-binding-reuse.d.ts.map +1 -0
  81. package/dist/coordinator-device-claim-binding-sql.d.ts +40 -0
  82. package/dist/coordinator-device-claim-binding-sql.d.ts.map +1 -0
  83. package/dist/coordinator-device-claim-binding.d.ts +21 -0
  84. package/dist/coordinator-device-claim-binding.d.ts.map +1 -0
  85. package/dist/coordinator-device-ownership-evidence-original-sql-test-fixtures.d.ts +88 -0
  86. package/dist/coordinator-device-ownership-evidence-original-sql-test-fixtures.d.ts.map +1 -0
  87. package/dist/coordinator-device-ownership-evidence-queries.d.ts +4 -14
  88. package/dist/coordinator-device-ownership-evidence-queries.d.ts.map +1 -1
  89. package/dist/coordinator-device-ownership-evidence-test-fixtures.d.ts +10 -0
  90. package/dist/coordinator-device-ownership-evidence-test-fixtures.d.ts.map +1 -1
  91. package/dist/coordinator-device-ownership-evidence.d.ts +11 -3
  92. package/dist/coordinator-device-ownership-evidence.d.ts.map +1 -1
  93. package/dist/coordinator-device-rebind-ceremony.d.ts +2 -1
  94. package/dist/coordinator-device-rebind-ceremony.d.ts.map +1 -1
  95. package/dist/coordinator-device-rebind-commit.d.ts.map +1 -1
  96. package/dist/coordinator-device-rebind-proof.d.ts +1 -0
  97. package/dist/coordinator-device-rebind-proof.d.ts.map +1 -1
  98. package/dist/coordinator-device-rebind-schema.d.ts +4 -3
  99. package/dist/coordinator-device-rebind-schema.d.ts.map +1 -1
  100. package/dist/coordinator-device-rebind-test-fixtures.d.ts.map +1 -1
  101. package/dist/coordinator-device-self-bind-authority.d.ts +29 -0
  102. package/dist/coordinator-device-self-bind-authority.d.ts.map +1 -0
  103. package/dist/coordinator-device-self-bind-decision.d.ts +84 -0
  104. package/dist/coordinator-device-self-bind-decision.d.ts.map +1 -0
  105. package/dist/coordinator-device-self-bind-original-sql-test-fixtures.d.ts +17 -0
  106. package/dist/coordinator-device-self-bind-original-sql-test-fixtures.d.ts.map +1 -0
  107. package/dist/coordinator-device-self-bind-test-fixtures.d.ts +114 -0
  108. package/dist/coordinator-device-self-bind-test-fixtures.d.ts.map +1 -0
  109. package/dist/coordinator-device-setup-client.d.ts +26 -0
  110. package/dist/coordinator-device-setup-client.d.ts.map +1 -0
  111. package/dist/coordinator-device-setup-http.d.ts +9 -0
  112. package/dist/coordinator-device-setup-http.d.ts.map +1 -0
  113. package/dist/coordinator-history-sql-equivalence-test-fixtures.d.ts +6 -2
  114. package/dist/coordinator-history-sql-equivalence-test-fixtures.d.ts.map +1 -1
  115. package/dist/coordinator-legacy-completion-owner-proof-original-sql-test-fixtures.d.ts +77 -0
  116. package/dist/coordinator-legacy-completion-owner-proof-original-sql-test-fixtures.d.ts.map +1 -0
  117. package/dist/coordinator-legacy-completion-owner-proof-test-fixtures.d.ts +46 -0
  118. package/dist/coordinator-legacy-completion-owner-proof-test-fixtures.d.ts.map +1 -0
  119. package/dist/coordinator-legacy-completion-owner-proof.d.ts +19 -2
  120. package/dist/coordinator-legacy-completion-owner-proof.d.ts.map +1 -1
  121. package/dist/coordinator-legacy-owner-compatibility.d.ts +23 -0
  122. package/dist/coordinator-legacy-owner-compatibility.d.ts.map +1 -1
  123. package/dist/coordinator-legacy-owner-resolution-commit-original-sql-test-fixtures.d.ts +63 -0
  124. package/dist/coordinator-legacy-owner-resolution-commit-original-sql-test-fixtures.d.ts.map +1 -0
  125. package/dist/coordinator-legacy-owner-resolution-commit-test-fixtures.d.ts +3 -1
  126. package/dist/coordinator-legacy-owner-resolution-commit-test-fixtures.d.ts.map +1 -1
  127. package/dist/coordinator-legacy-owner-resolution-commit.d.ts.map +1 -1
  128. package/dist/coordinator-owner-enrollment-commit.d.ts.map +1 -1
  129. package/dist/coordinator-owner-enrollment-historical-test-fixture.d.ts +2 -0
  130. package/dist/coordinator-owner-enrollment-historical-test-fixture.d.ts.map +1 -1
  131. package/dist/coordinator-owner-enrollment-start-test-fixtures.d.ts.map +1 -1
  132. package/dist/coordinator-owner-negative-consistency.d.ts +11 -17
  133. package/dist/coordinator-owner-negative-consistency.d.ts.map +1 -1
  134. package/dist/coordinator-owner-negative-original-sql-test-fixtures.d.ts +44 -0
  135. package/dist/coordinator-owner-negative-original-sql-test-fixtures.d.ts.map +1 -0
  136. package/dist/coordinator-owner-negative-race-test-fixtures.d.ts +26 -0
  137. package/dist/coordinator-owner-negative-race-test-fixtures.d.ts.map +1 -0
  138. package/dist/coordinator-owner-negative-read-set.d.ts +43 -0
  139. package/dist/coordinator-owner-negative-read-set.d.ts.map +1 -0
  140. package/dist/coordinator-owner-negative-reads.d.ts +32 -0
  141. package/dist/coordinator-owner-negative-reads.d.ts.map +1 -0
  142. package/dist/coordinator-owner-producer-original-sql-test-fixtures.d.ts +26 -0
  143. package/dist/coordinator-owner-producer-original-sql-test-fixtures.d.ts.map +1 -0
  144. package/dist/coordinator-owner-resolution-review-test-fixtures.d.ts +1 -0
  145. package/dist/coordinator-owner-resolution-review-test-fixtures.d.ts.map +1 -1
  146. package/dist/coordinator-owner-resolution-review.d.ts +1 -0
  147. package/dist/coordinator-owner-resolution-review.d.ts.map +1 -1
  148. package/dist/coordinator-producer-negative-owner-test-fixtures.d.ts +8 -2
  149. package/dist/coordinator-producer-negative-owner-test-fixtures.d.ts.map +1 -1
  150. package/dist/coordinator-recipient-negative-race-test-fixtures.d.ts +54 -0
  151. package/dist/coordinator-recipient-negative-race-test-fixtures.d.ts.map +1 -0
  152. package/dist/coordinator-recipient-owner-consistency.d.ts +4 -5
  153. package/dist/coordinator-recipient-owner-consistency.d.ts.map +1 -1
  154. package/dist/coordinator-recipient-owner-original-sql-test-fixtures.d.ts +30 -0
  155. package/dist/coordinator-recipient-owner-original-sql-test-fixtures.d.ts.map +1 -0
  156. package/dist/coordinator-resolved-account-owner-status-query.d.ts +4 -1
  157. package/dist/coordinator-resolved-account-owner-status-query.d.ts.map +1 -1
  158. package/dist/coordinator-resolved-account-owner-status-test-fixtures.d.ts +1 -0
  159. package/dist/coordinator-resolved-account-owner-status-test-fixtures.d.ts.map +1 -1
  160. package/dist/coordinator-resolved-account-owner-status.d.ts +2 -0
  161. package/dist/coordinator-resolved-account-owner-status.d.ts.map +1 -1
  162. package/dist/{coordinator-runtime-Bdad5KeL.js → coordinator-runtime-BXJQAKFD.js} +3 -3
  163. package/dist/{coordinator-runtime-Bdad5KeL.js.map → coordinator-runtime-BXJQAKFD.js.map} +1 -1
  164. package/dist/coordinator-sql-compare.d.ts +22 -0
  165. package/dist/coordinator-sql-compare.d.ts.map +1 -0
  166. package/dist/d1-coordinator-store.d.ts +16 -1
  167. package/dist/d1-coordinator-store.d.ts.map +1 -1
  168. package/dist/index.d.ts +4 -1
  169. package/dist/index.d.ts.map +1 -1
  170. package/dist/index.js +9048 -8412
  171. package/dist/index.js.map +1 -1
  172. package/dist/ingest-events.d.ts.map +1 -1
  173. package/dist/ingest-pipeline.d.ts +38 -2
  174. package/dist/ingest-pipeline.d.ts.map +1 -1
  175. package/dist/internal/cloudflare-coordinator.js +1079 -1074
  176. package/dist/internal/cloudflare-coordinator.js.map +1 -1
  177. package/dist/internal/relay-runtime.js +2 -2
  178. package/dist/linked-legacy-setup-test-fixtures.d.ts +71 -0
  179. package/dist/linked-legacy-setup-test-fixtures.d.ts.map +1 -0
  180. package/dist/operational-status.d.ts +3 -0
  181. package/dist/operational-status.d.ts.map +1 -1
  182. package/dist/{owner-enrollment-start-DgToUaFZ.js → owner-enrollment-start-BFyBKWvZ.js} +2731 -2315
  183. package/dist/owner-enrollment-start-BFyBKWvZ.js.map +1 -0
  184. package/dist/owner-enrollment-start.d.ts.map +1 -1
  185. package/dist/owner-qualified-consumer-access-test-harness.d.ts.map +1 -1
  186. package/dist/owner-qualified-consumer-adversarial-test-harness.d.ts +1 -1
  187. package/dist/owner-qualified-consumer-adversarial-test-harness.d.ts.map +1 -1
  188. package/dist/owner-qualified-consumer-test-harness.d.ts +3 -0
  189. package/dist/owner-qualified-consumer-test-harness.d.ts.map +1 -1
  190. package/dist/owner-qualified-headless-test-harness.d.ts +1 -1
  191. package/dist/owner-qualified-headless-test-harness.d.ts.map +1 -1
  192. package/dist/project-scope-settings.d.ts.map +1 -1
  193. package/dist/raw-event-flush.d.ts.map +1 -1
  194. package/dist/relay-admission-table-keys-test-fixtures.d.ts +2 -1
  195. package/dist/relay-admission-table-keys-test-fixtures.d.ts.map +1 -1
  196. package/dist/{relay-peer-client-DdhDwDFz.js → relay-peer-client-DrTb2oZt.js} +2650 -2627
  197. package/dist/relay-peer-client-DrTb2oZt.js.map +1 -0
  198. package/dist/{sync-auth-constants-WKqJ9CX5.js → sync-auth-constants-BVzVfSmn.js} +4476 -3521
  199. package/dist/sync-auth-constants-BVzVfSmn.js.map +1 -0
  200. package/dist/{sync-reachability-pass-CSg85Qmd.js → sync-reachability-pass-CUe5bK61.js} +12 -12
  201. package/dist/{sync-reachability-pass-CSg85Qmd.js.map → sync-reachability-pass-CUe5bK61.js.map} +1 -1
  202. package/dist/sync-reachability-pass-D9cA54fj.js +2 -0
  203. package/package.json +3 -3
  204. package/dist/owner-enrollment-start-DgToUaFZ.js.map +0 -1
  205. package/dist/relay-peer-client-DdhDwDFz.js.map +0 -1
  206. package/dist/sync-auth-constants-WKqJ9CX5.js.map +0 -1
  207. package/dist/sync-reachability-pass-CQe7nZnN.js +0 -2
@@ -1 +0,0 @@
1
- {"version":3,"file":"sync-auth-constants-WKqJ9CX5.js","names":[],"sources":["../src/legacy-team-setup-limits.ts","../src/recipient-policy-identifiers.ts","../src/coordinator-legacy-team-completion.ts","../src/coordinator-auth-controller-history.ts","../src/coordinator-account-connection-storage.ts","../src/coordinator-auth-link-provenance.ts","../src/coordinator-auth-controller-owner.ts","../src/coordinator-auth-controller.ts","../src/coordinator-auth-browser-style.ts","../src/coordinator-auth-proof.ts","../src/coordinator-account-change-schema.ts","../src/coordinator-account-unlink-schema.ts","../src/coordinator-auth-device-claim-schema.ts","../src/coordinator-auth-link-contract.ts","../src/coordinator-account-connection-schema.ts","../src/coordinator-account-connection-session.ts","../src/coordinator-auth-legacy-assignment.ts","../src/coordinator-auth-contract.ts","../src/coordinator-auth-link-input.ts","../src/coordinator-auth-device-claim-eligibility.ts","../src/coordinator-account-connection-link.ts","../src/coordinator-auth-account-profile-contract.ts","../src/coordinator-auth-link-authority.ts","../src/coordinator-auth-link-source.ts","../src/coordinator-auth-schema.ts","../src/coordinator-account-historical-revoke.ts","../src/coordinator-auth-link-headless.ts","../src/coordinator-auth-session-contract.ts","../src/coordinator-auth-session.ts","../src/coordinator-auth-account-profile.ts","../src/coordinator-auth-headless-schema.ts","../src/coordinator-auth-headless-provenance.ts","../src/coordinator-auth-link-profile.ts","../src/coordinator-auth-loopback.ts","../src/coordinator-device-ownership-evidence-queries.ts","../src/coordinator-legacy-owner-resolution-schema.ts","../src/coordinator-legacy-owner-resolution-metadata.ts","../src/coordinator-device-ownership-evidence-classify.ts","../src/coordinator-owner-negative-consistency.ts","../src/coordinator-auth-link.ts","../src/coordinator-account-change.ts","../src/coordinator-auth-browser-transaction-contract.ts","../src/coordinator-browser-credential.ts","../src/coordinator-browser-csrf.ts","../src/coordinator-auth-browser-view.ts","../src/coordinator-account-link-status.ts","../src/coordinator-account-owner-target.ts","../src/coordinator-auth-browser-transaction.ts","../src/coordinator-device-revocation.ts","../src/coordinator-bootstrap-grant-authorization.ts","../src/coordinator-bootstrap-grant-issuance.ts","../src/coordinator-device-rebind-schema.ts","../src/coordinator-enrollment-ownership.ts","../src/coordinator-identity-group-grant.ts","../src/coordinator-legacy-device-ownership.ts","../src/coordinator-join-review-guards.ts","../src/coordinator-legacy-owner-compatibility.ts","../src/coordinator-legacy-completion-owner-proof.ts","../src/coordinator-membership-effects.ts","../src/coordinator-owner-enrollment-schema.ts","../src/coordinator-device-ownership-evidence-digest.ts","../src/coordinator-device-ownership-evidence.ts","../src/coordinator-legacy-owner-resolution-commit.ts","../src/coordinator-owner-resolution-review-read.ts","../src/coordinator-owner-resolution-review.ts","../src/coordinator-peer-discovery.ts","../src/coordinator-project-invite-guards.ts","../src/coordinator-recipient-owner-consistency.ts","../src/coordinator-resolved-account-owner-status-query.ts","../src/coordinator-resolved-account-owner-status.ts","../src/coordinator-store-contract.ts","../src/project-invite-identity.ts","../src/recipient-reviewed-intent.ts","../src/coordinator-store-input-rules.ts","../src/relay-admission-proof.ts","../src/sync-auth-constants.ts"],"sourcesContent":["import type { Database } from \"./db.js\";\n\nexport const LEGACY_TEAM_SETUP_MAX_DEVICES = 500;\nexport const LEGACY_TEAM_SETUP_MAX_PROJECTS = 500;\nexport const LEGACY_TEAM_SETUP_MAX_PROJECT_DEVICE_PAIRS = 10_000;\n\nexport function requireLegacyTeamSetupSnapshotWithinLimits(input: {\n\tdevices: readonly unknown[];\n\tprojects: readonly unknown[];\n}): void {\n\tif (\n\t\tinput.devices.length > LEGACY_TEAM_SETUP_MAX_DEVICES ||\n\t\tinput.projects.length > LEGACY_TEAM_SETUP_MAX_PROJECTS ||\n\t\tinput.devices.length * input.projects.length > LEGACY_TEAM_SETUP_MAX_PROJECT_DEVICE_PAIRS\n\t) {\n\t\tthrow new Error(\"legacy_team_setup_roster_too_large\");\n\t}\n}\n\n/**\n * Bounds the access-delta derivation itself. Activation recomputes effective\n * devices for every Project the Team touches plus every Project with an\n * active recipient edge, across every assigned device, so a tiny draft can\n * still fan out past the pair budget when the installation already holds many\n * recipients or assignments.\n */\nexport function requireLegacyTeamSetupAccessDeltaTraversalWithinLimit(input: {\n\tprojectIdentities: ReadonlySet<string>;\n\tdeviceCount: number;\n}): void {\n\tif (\n\t\tinput.projectIdentities.size * input.deviceCount >\n\t\tLEGACY_TEAM_SETUP_MAX_PROJECT_DEVICE_PAIRS\n\t) {\n\t\tthrow new Error(\"legacy_team_setup_roster_too_large\");\n\t}\n}\n\n/**\n * Readiness checks re-derive effective devices for every completed Project,\n * and that derivation walks every persisted assignment row. Bound that fan-out\n * so a small roster cannot hide an unbounded Project-by-assignment traversal.\n */\nexport function requireLegacyTeamSetupReachableDevicesWithinLimit(\n\tdb: Database,\n\tdevices: readonly { deviceId: string }[],\n\tprojects: readonly unknown[],\n): void {\n\tif (projects.length === 0) return;\n\tconst deviceIds = [...new Set(devices.map((device) => device.deviceId))];\n\tconst excludeRoster =\n\t\tdeviceIds.length > 0 ? `WHERE device_id NOT IN (${deviceIds.map(() => \"?\").join(\", \")})` : \"\";\n\tconst assignmentRows = Number(\n\t\tdb\n\t\t\t.prepare(`SELECT COUNT(*) FROM identity_devices ${excludeRoster}`)\n\t\t\t.pluck()\n\t\t\t.get(...deviceIds) ?? 0,\n\t);\n\tif (\n\t\t(deviceIds.length + assignmentRows) * projects.length >\n\t\tLEGACY_TEAM_SETUP_MAX_PROJECT_DEVICE_PAIRS\n\t) {\n\t\tthrow new Error(\"legacy_team_setup_roster_too_large\");\n\t}\n}\n\nexport function requireLegacyTeamSetupEffectiveDevicesWithinLimit(\n\tdb: Database,\n\tdevices: readonly { deviceId: string }[],\n\tprojects: readonly unknown[],\n\tpreviousAttemptId: string | null,\n): void {\n\tif (!previousAttemptId) return;\n\tconst currentDeviceIds = [...new Set(devices.map((device) => device.deviceId))];\n\tconst placeholders = currentDeviceIds.map(() => \"?\").join(\", \");\n\tconst excludeCurrent = placeholders ? `AND device_id NOT IN (${placeholders})` : \"\";\n\tconst carriedDeviceCount = Number(\n\t\tdb\n\t\t\t.prepare(\n\t\t\t\t`SELECT COUNT(*) FROM legacy_team_setup_draft_devices\n\t\t\t\t WHERE attempt_id = ? ${excludeCurrent}`,\n\t\t\t)\n\t\t\t.pluck()\n\t\t\t.get(previousAttemptId, ...currentDeviceIds) ?? 0,\n\t);\n\tconst effectiveDeviceCount = devices.length + carriedDeviceCount;\n\tif (\n\t\teffectiveDeviceCount > LEGACY_TEAM_SETUP_MAX_DEVICES ||\n\t\teffectiveDeviceCount * projects.length > LEGACY_TEAM_SETUP_MAX_PROJECT_DEVICE_PAIRS\n\t) {\n\t\tthrow new Error(\"legacy_team_setup_roster_too_large\");\n\t}\n}\n","import { createHash } from \"node:crypto\";\n\n/**\n * Locale-independent UTF-16 code-unit comparison. Every fingerprint and digest\n * in the recipient-policy feature relies on byte-identical ordering across\n * machines, so `localeCompare` (ICU-collation dependent) must never feed a\n * digest.\n */\nexport function compareCodepoints(left: string, right: string): number {\n\treturn left < right ? -1 : left > right ? 1 : 0;\n}\n\nconst RECIPIENT_POLICY_ID_CONTROL_OR_FORMAT_CHARACTER = /[\\p{Cc}\\p{Cf}]/u;\n\nfunction isStrictRecipientPolicyText(value: unknown, maxUtf16Units: number): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length > 0 &&\n\t\tvalue === value.trim() &&\n\t\tvalue.length <= maxUtf16Units &&\n\t\t!RECIPIENT_POLICY_ID_CONTROL_OR_FORMAT_CHARACTER.test(value)\n\t);\n}\n\nexport function isStrictRecipientPolicyId(value: unknown): value is string {\n\treturn isStrictRecipientPolicyText(value, 256);\n}\n\nexport function isStrictRecipientPolicyProjectIdentity(value: unknown): value is string {\n\treturn isStrictRecipientPolicyText(value, 2_048);\n}\n\nconst INVALID_CANONICAL_JSON_MESSAGE = \"Recipient policy value must be strict JSON data\";\n\nfunction invalidCanonicalJson(): never {\n\tthrow new TypeError(INVALID_CANONICAL_JSON_MESSAGE);\n}\n\nfunction serializeJsonString(value: string): string {\n\tconst serialized = JSON.stringify(value);\n\tif (serialized === undefined) return invalidCanonicalJson();\n\treturn serialized;\n}\n\nfunction canonicalJson(value: unknown, ancestors: WeakSet<object>): string {\n\tif (value === null) return \"null\";\n\tif (typeof value === \"boolean\") return value ? \"true\" : \"false\";\n\tif (typeof value === \"string\") return serializeJsonString(value);\n\tif (typeof value === \"number\") {\n\t\tif (!Number.isFinite(value) || Object.is(value, -0)) return invalidCanonicalJson();\n\t\treturn String(value);\n\t}\n\tif (typeof value !== \"object\") return invalidCanonicalJson();\n\tif (ancestors.has(value)) return invalidCanonicalJson();\n\n\tancestors.add(value);\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tif (Object.getPrototypeOf(value) !== Array.prototype) return invalidCanonicalJson();\n\t\t\tconst keys = Reflect.ownKeys(value);\n\t\t\tif (keys.length !== value.length + 1 || keys.some((key) => typeof key !== \"string\")) {\n\t\t\t\treturn invalidCanonicalJson();\n\t\t\t}\n\t\t\tconst children: string[] = [];\n\t\t\tfor (let index = 0; index < value.length; index += 1) {\n\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, String(index));\n\t\t\t\tif (!descriptor?.enumerable || !(\"value\" in descriptor)) return invalidCanonicalJson();\n\t\t\t\tchildren.push(canonicalJson(descriptor.value, ancestors));\n\t\t\t}\n\t\t\treturn `[${children.join(\",\")}]`;\n\t\t}\n\n\t\tconst prototype = Object.getPrototypeOf(value);\n\t\tif (prototype !== Object.prototype && prototype !== null) return invalidCanonicalJson();\n\t\tconst entries = Reflect.ownKeys(value).map((key): [string, unknown] => {\n\t\t\tif (typeof key !== \"string\") return invalidCanonicalJson();\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\t\tif (!descriptor?.enumerable || !(\"value\" in descriptor)) return invalidCanonicalJson();\n\t\t\treturn [key, descriptor.value];\n\t\t});\n\t\treturn `{${entries\n\t\t\t.toSorted(([left], [right]) => compareCodepoints(left, right))\n\t\t\t.map(([key, child]) => `${serializeJsonString(key)}:${canonicalJson(child, ancestors)}`)\n\t\t\t.join(\",\")}}`;\n\t} finally {\n\t\tancestors.delete(value);\n\t}\n}\n\nexport function canonicalRecipientPolicyJson(value: unknown): string {\n\treturn canonicalJson(value, new WeakSet());\n}\n\nexport function recipientPolicyDigest(prefix: string, value: unknown): string {\n\t// Node replaces unpaired UTF-16 surrogates with U+FFFD during UTF-8\n\t// encoding, so accepting them would make distinct domains hash identically.\n\tif (prefix.includes(\"\\0\") || !prefix.isWellFormed()) {\n\t\tthrow new TypeError(\"Recipient policy digest prefix must be well-formed without NUL\");\n\t}\n\treturn `${prefix}:${createHash(\"sha256\")\n\t\t.update(prefix, \"utf8\")\n\t\t.update(\"\\0\", \"utf8\")\n\t\t.update(canonicalRecipientPolicyJson(value), \"utf8\")\n\t\t.digest(\"hex\")}`;\n}\n\n/**\n * Compatibility digest for identifiers persisted by released recipient-policy\n * flows before domain separation was introduced. New digest domains must use\n * `recipientPolicyDigest`; changing these bytes requires an explicit DB rekey.\n */\nexport function legacyRecipientPolicyDigest(prefix: string, value: unknown): string {\n\treturn `${prefix}:${createHash(\"sha256\")\n\t\t.update(canonicalRecipientPolicyJson(value), \"utf8\")\n\t\t.digest(\"hex\")}`;\n}\n\n/**\n * Decision and membership provenances owned by the invite flows. Activation\n * deliberately preserves these rows and readiness must tolerate them; every\n * layer that classifies invite ownership must use this single set —\n * hand-repeated literals with opposite polarity (allowlist vs denylist) are\n * how the two sides drift apart.\n */\nexport const INVITE_DECISION_PROVENANCES = [\"team_invite\", \"coordinator_invite\"] as const;\n\n/**\n * Frozen compatibility identifier persisted by released legacy Team drafts.\n * Changing the JSON tuple bytes or truncation requires an explicit DB rekey.\n */\nexport function legacyTeamCandidateId(coordinatorId: string, groupId: string): string {\n\tconst digest = createHash(\"sha256\")\n\t\t.update(JSON.stringify([coordinatorId, groupId]))\n\t\t.digest(\"hex\")\n\t\t.slice(0, 32);\n\treturn `legacy-team-candidate:${digest}`;\n}\n\nexport function legacyTeamProjectRef(candidateId: string, sourceProjectIdentity: string): string {\n\treturn recipientPolicyDigest(\"legacy-team-project-ref-v1\", [candidateId, sourceProjectIdentity]);\n}\n\nexport function legacyTeamCanonicalProjectRef(\n\tcandidateId: string,\n\tcanonicalProjectIdentity: string,\n): string {\n\treturn recipientPolicyDigest(\"legacy-team-canonical-project-ref-v1\", [\n\t\tcandidateId,\n\t\tcanonicalProjectIdentity,\n\t]);\n}\n\nexport function legacyTeamDeviceRef(candidateId: string, deviceId: string): string {\n\treturn recipientPolicyDigest(\"legacy-team-device-ref-v1\", [candidateId, deviceId]);\n}\n\nexport function deterministicPolicyTeamId(teamCandidateId: string): string {\n\treturn legacyRecipientPolicyDigest(\"policy-team-v1\", teamCandidateId);\n}\n\nexport function legacyTeamRosterFingerprint(\n\tdevices: ReadonlyArray<{\n\t\tdeviceId: string;\n\t\tfingerprint: string;\n\t\tenabled: boolean;\n\t\tidentityId: string | null;\n\t}>,\n): string {\n\treturn recipientPolicyDigest(\n\t\t\"legacy-team-roster-v1\",\n\t\tdevices\n\t\t\t.map((device) => ({\n\t\t\t\tdeviceId: device.deviceId,\n\t\t\t\tfingerprint: device.fingerprint,\n\t\t\t\tenabled: device.enabled,\n\t\t\t\tidentityId: device.identityId,\n\t\t\t}))\n\t\t\t.toSorted((left, right) => compareCodepoints(left.deviceId, right.deviceId)),\n\t);\n}\n","import {\n\tLEGACY_TEAM_SETUP_MAX_DEVICES,\n\tLEGACY_TEAM_SETUP_MAX_PROJECTS,\n} from \"./legacy-team-setup-limits.js\";\nimport {\n\tcompareCodepoints,\n\tdeterministicPolicyTeamId,\n\tlegacyTeamCandidateId,\n} from \"./recipient-policy-identifiers.js\";\n\nexport const COORDINATOR_LEGACY_TEAM_COMPLETION_VERSION = 1 as const;\nexport const COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_GROUPS = 50;\nexport const COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS = 500;\nexport const COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES = 1_500_000;\nexport const COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES =\n\t25 * COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES;\nconst COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_IDENTIFIER_CHARS = 256;\nconst COORDINATOR_LEGACY_TEAM_COMPLETION_RECORD_ENVELOPE_BYTES = 64;\nexport const COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_RESPONSE_BYTES =\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES +\n\t(COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_IDENTIFIER_CHARS +\n\t\tCOORDINATOR_LEGACY_TEAM_COMPLETION_RECORD_ENVELOPE_BYTES) *\n\t\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS +\n\t1024;\nexport const COORDINATOR_LEGACY_TEAM_COMPLETION_CONFLICT = \"completion_conflict\" as const;\n\nexport interface CoordinatorLegacyTeamCompletionMembershipV1 {\n\tidentity_id: string;\n\trole: \"member\";\n}\n\n/**\n * Who asserted an included device's Identity. `self` is the uploading device's\n * own assignment. `label` is that device's guess about another device. It keeps\n * Team access but never counts as ownership evidence. Manifests written before\n * this field existed omit it, and their rows keep the old meaning.\n */\nexport type CoordinatorLegacyTeamCompletionIdentityEvidence = \"self\" | \"label\";\n\nexport interface CoordinatorLegacyTeamCompletionDeviceDecisionV1 {\n\tdevice_id: string;\n\tkey_fingerprint: string;\n\tenabled: boolean;\n\tidentity_id: string | null;\n\tdecision: \"included\" | \"excluded\";\n\tidentity_evidence?: CoordinatorLegacyTeamCompletionIdentityEvidence;\n}\n\n/** False only for a decision another device guessed; such rows never prove ownership. */\nexport function legacyDecisionCountsAsOwner(\n\tdecision: Pick<CoordinatorLegacyTeamCompletionDeviceDecisionV1, \"identity_evidence\">,\n): boolean {\n\treturn decision.identity_evidence !== \"label\";\n}\n\n/**\n * SQL form of {@link legacyDecisionCountsAsOwner} for one `json_each` element,\n * e.g. `legacyDecisionCountsAsOwnerSql(\"d.value\")`. Stored rows are canonical,\n * but an unexpected value must still fail closed: a grant counts only `self` or\n * an absent mark, and a denial counts everything except an explicit label.\n */\nexport function legacyDecisionCountsAsOwnerSql(\n\telement: string,\n\tuse: \"grant\" | \"deny\" = \"grant\",\n): string {\n\tif (use === \"deny\") return `json_extract(${element}, '$.identity_evidence') IS NOT 'label'`;\n\treturn `coalesce(json_extract(${element}, '$.identity_evidence'), 'self') = 'self'`;\n}\n\nexport interface CoordinatorLegacyTeamCompletionProjectMappingV1 {\n\tproject_ref: string;\n\tresolved_project_ref: string;\n\tscope_id: string;\n}\n\nexport interface CoordinatorLegacyTeamCompletionRecipientV1 {\n\tresolved_project_ref: string;\n\tteam_id: string;\n}\n\nexport interface CoordinatorLegacyTeamCompletionManifestV1 {\n\tversion: typeof COORDINATOR_LEGACY_TEAM_COMPLETION_VERSION;\n\tcoordinator_id: string;\n\tcandidate_ref: string;\n\tcandidate_digest: string;\n\tteam_id: string;\n\tteam_digest: string;\n\tsource_digest: string;\n\tfinish_digest: string;\n\taccess_delta_digest: string;\n\tteam: {\n\t\tdisplay_name: string;\n\t\tpolicy_revision: string;\n\t\tdevice_eligibility_mode: \"reviewed_allowlist\";\n\t};\n\tmemberships: CoordinatorLegacyTeamCompletionMembershipV1[];\n\tdevice_decisions: CoordinatorLegacyTeamCompletionDeviceDecisionV1[];\n\tproject_mappings: CoordinatorLegacyTeamCompletionProjectMappingV1[];\n\tproject_recipients: CoordinatorLegacyTeamCompletionRecipientV1[];\n\tcompleted_at: string;\n}\n\nexport interface CoordinatorLegacyTeamCompletionWriteResult {\n\tstatus: \"created\" | \"existing\";\n\tmanifest: CoordinatorLegacyTeamCompletionManifestV1;\n}\n\nexport interface CoordinatorLegacyTeamCompletionRecord {\n\tgroup_id: string;\n\tmanifest: CoordinatorLegacyTeamCompletionManifestV1;\n}\n\nexport interface CoordinatorLegacyTeamCompletionScopeBinding {\n\tscope_id: string | null;\n\tauthority_type: string | null;\n\tcoordinator_id: string | null;\n\tgroup_id: string | null;\n\tstatus: string | null;\n}\n\nexport class CoordinatorLegacyTeamCompletionConflictError extends Error {\n\treadonly code = COORDINATOR_LEGACY_TEAM_COMPLETION_CONFLICT;\n\n\tconstructor() {\n\t\tsuper(COORDINATOR_LEGACY_TEAM_COMPLETION_CONFLICT);\n\t\tthis.name = \"CoordinatorLegacyTeamCompletionConflictError\";\n\t}\n}\n\nfunction invalid(): never {\n\tthrow new Error(\"completion_manifest_invalid\");\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) invalid();\n\treturn value as Record<string, unknown>;\n}\n\nfunction exactFields(value: Record<string, unknown>, fields: readonly string[]): void {\n\tconst allowed = new Set(fields);\n\tif (Object.keys(value).some((field) => !allowed.has(field))) invalid();\n}\n\nfunction isLocalArtifactPath(value: string): boolean {\n\treturn /^(?:[\\\\/]{2}|\\.{1,2}[\\\\/]|\\/|~[\\\\/]|[a-z]:[\\\\/]|file:)/iu.test(value);\n}\n\nfunction identifier(value: unknown): string {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\t!value ||\n\t\tvalue !== value.trim() ||\n\t\tvalue.length > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_IDENTIFIER_CHARS ||\n\t\t/[\\p{Cc}\\p{Cf}]/u.test(value) ||\n\t\tisLocalArtifactPath(value)\n\t) {\n\t\tinvalid();\n\t}\n\treturn value;\n}\n\nfunction digest(value: unknown): string {\n\tconst normalized = identifier(value);\n\tif (!/^[a-f0-9]{64}$/u.test(normalized)) invalid();\n\treturn normalized;\n}\n\nfunction displayName(value: unknown): string {\n\tif (typeof value !== \"string\") invalid();\n\tconst normalized = value.normalize(\"NFC\").trim();\n\tif (\n\t\t!normalized ||\n\t\t[...normalized].length > 120 ||\n\t\t/[\\p{Cc}\\p{Cf}]/u.test(normalized) ||\n\t\tisLocalArtifactPath(normalized)\n\t) {\n\t\tinvalid();\n\t}\n\treturn normalized;\n}\n\nfunction timestamp(value: unknown): string {\n\tif (typeof value !== \"string\" || !value) invalid();\n\tconst parsed = new Date(value);\n\tif (Number.isNaN(parsed.getTime()) || parsed.toISOString() !== value) invalid();\n\treturn value;\n}\n\nfunction array(value: unknown, max: number): unknown[] {\n\tif (!Array.isArray(value) || value.length > max) invalid();\n\treturn value;\n}\n\nfunction uniqueSorted<T>(items: T[], key: (item: T) => string): T[] {\n\tconst sorted = items.toSorted((left, right) => compareCodepoints(key(left), key(right)));\n\tif (sorted.some((item, index) => index > 0 && key(sorted[index - 1] as T) === key(item)))\n\t\tinvalid();\n\treturn sorted;\n}\n\nexport function normalizeCoordinatorLegacyTeamCompletionGroupIds(value: unknown): string[] {\n\treturn uniqueSorted(\n\t\tarray(value, COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_GROUPS).map(identifier),\n\t\t(item) => item,\n\t);\n}\n\nexport function normalizeCoordinatorLegacyTeamCompletionCandidateRef(value: unknown): string {\n\tconst normalized = identifier(value);\n\tif (!/^legacy-team-candidate:[a-f0-9]{32}$/u.test(normalized)) invalid();\n\treturn normalized;\n}\n\nfunction normalizeDeviceDecision(value: unknown): CoordinatorLegacyTeamCompletionDeviceDecisionV1 {\n\tconst item = record(value);\n\texactFields(item, [\n\t\t\"device_id\",\n\t\t\"key_fingerprint\",\n\t\t\"enabled\",\n\t\t\"identity_id\",\n\t\t\"decision\",\n\t\t\"identity_evidence\",\n\t]);\n\tif (item.decision !== \"included\" && item.decision !== \"excluded\") invalid();\n\tif (typeof item.enabled !== \"boolean\") invalid();\n\tconst identityId = item.identity_id == null ? null : identifier(item.identity_id);\n\tif ((item.decision === \"included\") !== Boolean(identityId)) invalid();\n\tif (item.decision === \"included\" && !item.enabled) invalid();\n\tconst decision: CoordinatorLegacyTeamCompletionDeviceDecisionV1[\"decision\"] = item.decision;\n\tconst normalized: CoordinatorLegacyTeamCompletionDeviceDecisionV1 = {\n\t\tdevice_id: identifier(item.device_id),\n\t\tkey_fingerprint: digest(item.key_fingerprint),\n\t\tenabled: item.enabled,\n\t\tidentity_id: identityId,\n\t\tdecision,\n\t};\n\t// Absent stays absent, so manifests written before the field keep their exact bytes.\n\tif (!Object.hasOwn(item, \"identity_evidence\")) return normalized;\n\tif (decision !== \"included\") invalid();\n\tif (item.identity_evidence !== \"self\" && item.identity_evidence !== \"label\") invalid();\n\treturn { ...normalized, identity_evidence: item.identity_evidence };\n}\n\n/**\n * A manifest either predates evidence or marks every included device, and at\n * most one device (the uploader) can speak for itself.\n */\nfunction requireConsistentIdentityEvidence(\n\tdecisions: readonly CoordinatorLegacyTeamCompletionDeviceDecisionV1[],\n): void {\n\tconst included = decisions.filter((decision) => decision.decision === \"included\");\n\tconst marked = included.filter((decision) => decision.identity_evidence !== undefined);\n\tif (marked.length === 0) return;\n\tif (marked.length !== included.length) invalid();\n\tif (marked.filter((decision) => decision.identity_evidence === \"self\").length > 1) invalid();\n}\n\nexport function normalizeCoordinatorLegacyTeamCompletionManifest(\n\tvalue: unknown,\n): CoordinatorLegacyTeamCompletionManifestV1 {\n\tconst input = record(value);\n\texactFields(input, [\n\t\t\"version\",\n\t\t\"coordinator_id\",\n\t\t\"candidate_ref\",\n\t\t\"candidate_digest\",\n\t\t\"team_id\",\n\t\t\"team_digest\",\n\t\t\"source_digest\",\n\t\t\"finish_digest\",\n\t\t\"access_delta_digest\",\n\t\t\"team\",\n\t\t\"memberships\",\n\t\t\"device_decisions\",\n\t\t\"project_mappings\",\n\t\t\"project_recipients\",\n\t\t\"completed_at\",\n\t]);\n\tif (input.version !== COORDINATOR_LEGACY_TEAM_COMPLETION_VERSION) invalid();\n\tconst team = record(input.team);\n\texactFields(team, [\"display_name\", \"policy_revision\", \"device_eligibility_mode\"]);\n\tif (team.device_eligibility_mode !== \"reviewed_allowlist\") invalid();\n\tconst teamId = identifier(input.team_id);\n\tconst memberships = uniqueSorted(\n\t\tarray(input.memberships, LEGACY_TEAM_SETUP_MAX_DEVICES).map((value) => {\n\t\t\tconst item = record(value);\n\t\t\texactFields(item, [\"identity_id\", \"role\"]);\n\t\t\tif (item.role !== \"member\") invalid();\n\t\t\treturn { identity_id: identifier(item.identity_id), role: \"member\" as const };\n\t\t}),\n\t\t(item) => item.identity_id,\n\t);\n\tconst deviceDecisions = uniqueSorted(\n\t\tarray(input.device_decisions, LEGACY_TEAM_SETUP_MAX_DEVICES).map(normalizeDeviceDecision),\n\t\t(item) => item.device_id,\n\t);\n\tif (deviceDecisions.length === 0) invalid();\n\trequireConsistentIdentityEvidence(deviceDecisions);\n\tconst membershipIds = new Set(memberships.map((membership) => membership.identity_id));\n\tconst includedIdentityIds = new Set(\n\t\tdeviceDecisions.flatMap((decision) => (decision.identity_id ? [decision.identity_id] : [])),\n\t);\n\tif (\n\t\tmembershipIds.size !== includedIdentityIds.size ||\n\t\t[...includedIdentityIds].some((identityId) => !membershipIds.has(identityId))\n\t) {\n\t\tinvalid();\n\t}\n\tconst projectMappings = uniqueSorted(\n\t\tarray(input.project_mappings, LEGACY_TEAM_SETUP_MAX_PROJECTS).map((value) => {\n\t\t\tconst item = record(value);\n\t\t\texactFields(item, [\"project_ref\", \"resolved_project_ref\", \"scope_id\"]);\n\t\t\tconst projectRef = identifier(item.project_ref);\n\t\t\tconst resolvedProjectRef = identifier(item.resolved_project_ref);\n\t\t\tif (!/^legacy-team-project-ref-v1:[0-9a-f]{64}$/u.test(projectRef)) invalid();\n\t\t\tif (!/^legacy-team-resolved-project-ref-v1:[0-9a-f]{64}$/u.test(resolvedProjectRef)) {\n\t\t\t\tinvalid();\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tproject_ref: projectRef,\n\t\t\t\tresolved_project_ref: resolvedProjectRef,\n\t\t\t\tscope_id: identifier(item.scope_id),\n\t\t\t};\n\t\t}),\n\t\t(item) => item.project_ref,\n\t);\n\tconst resolvedScopes = new Map<string, string>();\n\tfor (const mapping of projectMappings) {\n\t\tconst priorScopeId = resolvedScopes.get(mapping.resolved_project_ref);\n\t\tif (priorScopeId && priorScopeId !== mapping.scope_id) invalid();\n\t\tresolvedScopes.set(mapping.resolved_project_ref, mapping.scope_id);\n\t}\n\tconst projectRecipients = uniqueSorted(\n\t\tarray(input.project_recipients, LEGACY_TEAM_SETUP_MAX_PROJECTS).map((value) => {\n\t\t\tconst item = record(value);\n\t\t\texactFields(item, [\"resolved_project_ref\", \"team_id\"]);\n\t\t\tconst recipientTeamId = identifier(item.team_id);\n\t\t\tif (recipientTeamId !== teamId) invalid();\n\t\t\tconst resolvedProjectRef = identifier(item.resolved_project_ref);\n\t\t\tif (!/^legacy-team-resolved-project-ref-v1:[0-9a-f]{64}$/u.test(resolvedProjectRef)) {\n\t\t\t\tinvalid();\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tresolved_project_ref: resolvedProjectRef,\n\t\t\t\tteam_id: recipientTeamId,\n\t\t\t};\n\t\t}),\n\t\t(item) => item.resolved_project_ref,\n\t);\n\tconst mappedRecipientRefs = [\n\t\t...new Set(projectMappings.map((mapping) => mapping.resolved_project_ref)),\n\t].toSorted(compareCodepoints);\n\tconst recipientRefs = projectRecipients.map((recipient) => recipient.resolved_project_ref);\n\tif (JSON.stringify(recipientRefs) !== JSON.stringify(mappedRecipientRefs)) {\n\t\tinvalid();\n\t}\n\tconst manifest: CoordinatorLegacyTeamCompletionManifestV1 = {\n\t\tversion: COORDINATOR_LEGACY_TEAM_COMPLETION_VERSION,\n\t\tcoordinator_id: identifier(input.coordinator_id),\n\t\tcandidate_ref: normalizeCoordinatorLegacyTeamCompletionCandidateRef(input.candidate_ref),\n\t\tcandidate_digest: digest(input.candidate_digest),\n\t\tteam_id: teamId,\n\t\tteam_digest: digest(input.team_digest),\n\t\tsource_digest: digest(input.source_digest),\n\t\tfinish_digest: digest(input.finish_digest),\n\t\taccess_delta_digest: digest(input.access_delta_digest),\n\t\tteam: {\n\t\t\tdisplay_name: displayName(team.display_name),\n\t\t\tpolicy_revision: digest(team.policy_revision),\n\t\t\tdevice_eligibility_mode: \"reviewed_allowlist\",\n\t\t},\n\t\tmemberships,\n\t\tdevice_decisions: deviceDecisions,\n\t\tproject_mappings: projectMappings,\n\t\tproject_recipients: projectRecipients,\n\t\tcompleted_at: timestamp(input.completed_at),\n\t};\n\tif (\n\t\tnew TextEncoder().encode(JSON.stringify(manifest)).byteLength >\n\t\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES\n\t) {\n\t\tinvalid();\n\t}\n\treturn manifest;\n}\n\nexport function canonicalCoordinatorLegacyTeamCompletionManifestJson(value: unknown): string {\n\treturn JSON.stringify(normalizeCoordinatorLegacyTeamCompletionManifest(value));\n}\n\nexport function requireCoordinatorLegacyTeamCompletionTeamBinding(\n\tmanifest: CoordinatorLegacyTeamCompletionManifestV1,\n): void {\n\tif (manifest.team_id !== deterministicPolicyTeamId(manifest.candidate_ref)) invalid();\n}\n\nexport function requireCoordinatorLegacyTeamCompletionCandidateBinding(\n\tmanifest: CoordinatorLegacyTeamCompletionManifestV1,\n\tgroupId: string,\n): void {\n\tif (legacyTeamCandidateId(manifest.coordinator_id, groupId) !== manifest.candidate_ref) invalid();\n}\n\nexport function requireCoordinatorLegacyTeamCompletionScopeBindings(\n\tmanifest: CoordinatorLegacyTeamCompletionManifestV1,\n\tgroupId: string,\n\tbindings: CoordinatorLegacyTeamCompletionScopeBinding[],\n): string | null {\n\trequireCoordinatorLegacyTeamCompletionCandidateBinding(manifest, groupId);\n\tconst requestedScopeIds = new Set(manifest.project_mappings.map((mapping) => mapping.scope_id));\n\tif (bindings.length !== requestedScopeIds.size) invalid();\n\tconst coordinatorId = manifest.coordinator_id;\n\tfor (const binding of bindings) {\n\t\tif (\n\t\t\t!binding.scope_id ||\n\t\t\t!requestedScopeIds.has(binding.scope_id) ||\n\t\t\tbinding.authority_type !== \"coordinator\" ||\n\t\t\t!binding.coordinator_id ||\n\t\t\tbinding.group_id !== groupId ||\n\t\t\tbinding.status !== \"active\" ||\n\t\t\tbinding.coordinator_id !== coordinatorId\n\t\t) {\n\t\t\tinvalid();\n\t\t}\n\t}\n\treturn coordinatorId;\n}\n","import { parseSshEd25519PublicKeyForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport {\n\ttype CoordinatorLegacyTeamCompletionManifestV1,\n\tcanonicalCoordinatorLegacyTeamCompletionManifestJson,\n\tnormalizeCoordinatorLegacyTeamCompletionManifest,\n\trequireCoordinatorLegacyTeamCompletionCandidateBinding,\n} from \"./coordinator-legacy-team-completion.js\";\n\nexport interface ControllerHistoryRecord {\n\tgroup_id: string;\n\tcandidate_ref: string;\n\tmanifest_version: number;\n\tcompleted_at: string;\n\tcreated_at: string;\n\tmanifest_json: string;\n}\ninterface HistoryKey {\n\tpublic_key: string;\n\tfingerprint: string;\n}\nexport interface ControllerHistorySnapshot {\n\tcoordinatorId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n\t/** Actual canonical subject aliases, not discovery-filter matches. */\n\tkeys: HistoryKey[];\n\t/** Private race-check inputs; never part of the operator's evidence digest. */\n\tdiscoveryKeys: string[];\n\tdiscoveryFragments: string[];\n\tfingerprints: string[];\n\trecords: ControllerHistoryRecord[];\n}\nexport interface ControllerHistoryEvidence extends ControllerHistoryRecord {\n\tmanifest: CoordinatorLegacyTeamCompletionManifestV1;\n}\nexport interface ControllerHistoryInput {\n\tcoordinatorId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n}\n\nconst MAX_BYTES = 750_000;\n// The encoded snapshot already caps record metadata and JSON-escaped manifest_json\n// at MAX_BYTES. Its parsed manifests add at most MAX_BYTES more; reserve the old\n// response envelope budget for enrollment, invitations, reasons and digest fields.\nexport const CONTROLLER_REVIEW_MAX_RESPONSE_BYTES = 2 * MAX_BYTES + 16_384;\nconst MAX_KEYS = 4096;\nconst MAX_DISCOVERY_KEYS = 8192;\nconst MAX_RECORDS = 500;\n\n// This same predicate selects preview evidence and detects newly relevant rows in\n// the winning write. Malformed unrelated records are not a reason to deny review.\n// Unparseable rows containing a target reference require operator investigation.\n// Enrollment removal must not erase an attested key/fingerprint binding. UNION\n// deduplicates the ordinary new review's existing enrollment pair, while the\n// coordinator filter prevents another namespace's retained keys entering proof.\n// Only canonical parsing below selects aliases; manifest fingerprints add no keys.\nexport const CONTROLLER_HISTORY_CTE = `history_input AS MATERIALIZED (\n SELECT json_extract(value, '$.legacyHistory') AS value FROM snapshot\n), history_key_sources AS NOT MATERIALIZED (\n SELECT public_key, fingerprint FROM enrolled_devices\n UNION\n SELECT a.public_key, a.fingerprint FROM coordinator_auth_controller_attestations a\n CROSS JOIN history_input h\n WHERE a.coordinator_id = json_extract(h.value, '$.coordinatorId')\n), history_rows AS NOT MATERIALIZED (\n SELECT c.*, CASE WHEN json_valid(c.manifest_json) THEN c.manifest_json ELSE '{}' END AS parsed\n FROM coordinator_legacy_team_completions c\n), live_history AS MATERIALIZED (\n SELECT c.group_id, c.candidate_ref, c.manifest_version, c.completed_at, c.created_at,\n CASE WHEN length(CAST(c.manifest_json AS BLOB)) <= ${MAX_BYTES} THEN c.manifest_json ELSE NULL END AS manifest_json\n FROM history_rows c CROSS JOIN history_input h\n WHERE h.value IS NOT NULL\n AND (json_extract(c.parsed, '$.coordinator_id') = json_extract(h.value, '$.coordinatorId')\n OR json_extract(c.parsed, '$.coordinator_id') IS NULL)\n AND (EXISTS (\n SELECT 1 FROM json_each(c.parsed, '$.device_decisions') d\n WHERE json_extract(CASE WHEN d.type = 'object' THEN d.value ELSE '{}' END, '$.device_id') = json_extract(h.value, '$.deviceId')\n OR json_extract(CASE WHEN d.type = 'object' THEN d.value ELSE '{}' END, '$.key_fingerprint')\n IN (SELECT value FROM json_each(h.value, '$.fingerprints'))\n OR ((d.type <> 'object'\n OR json_type(CASE WHEN d.type = 'object' THEN d.value ELSE '{}' END, '$.device_id') IS NOT 'text'\n OR json_type(CASE WHEN d.type = 'object' THEN d.value ELSE '{}' END, '$.key_fingerprint') IS NOT 'text')\n AND (instr(CASE WHEN d.type = 'text' THEN json_quote(d.value) ELSE d.value END,\n json_quote(json_extract(h.value, '$.deviceId'))) > 0\n OR EXISTS (SELECT 1 FROM json_each(h.value, '$.fingerprints') f\n WHERE instr(d.value, f.value) > 0)))\n ) OR ((json_valid(c.manifest_json) = 0 OR json_type(c.parsed, '$.device_decisions') IS NOT 'array') AND (\n instr(c.manifest_json, json_quote(json_extract(h.value, '$.deviceId'))) > 0\n OR EXISTS (SELECT 1 FROM json_each(h.value, '$.fingerprints') f\n WHERE instr(c.manifest_json, f.value) > 0)\n ))) LIMIT ${MAX_RECORDS + 1}\n), snapshot_history AS MATERIALIZED (\n SELECT json_extract(j.value, '$.group_id') AS group_id,\n json_extract(j.value, '$.candidate_ref') AS candidate_ref,\n json_extract(j.value, '$.manifest_version') AS manifest_version,\n json_extract(j.value, '$.completed_at') AS completed_at,\n json_extract(j.value, '$.created_at') AS created_at,\n json_extract(j.value, '$.manifest_json') AS manifest_json\n FROM history_input h, json_each(h.value, '$.records') j\n), snapshot_history_keys AS MATERIALIZED (\n SELECT json_extract(j.value, '$.public_key') AS public_key,\n json_extract(j.value, '$.fingerprint') AS fingerprint\n FROM history_input h, json_each(h.value, '$.keys') j\n), snapshot_discovery_keys AS MATERIALIZED (\n SELECT j.value AS public_key FROM history_input h, json_each(h.value, '$.discoveryKeys') j\n), discovery_lines AS NOT MATERIALIZED (\n SELECT public_key,\n ltrim(replace(replace(replace(replace(replace(public_key,\n char(9), ' '), char(10), ' '), char(11), ' '), char(12), ' '), char(13), ' '), ' ') AS line\n FROM history_key_sources\n), discovery_tails AS NOT MATERIALIZED (\n SELECT public_key, CASE WHEN substr(line, 1, 12) = 'ssh-ed25519 '\n THEN ltrim(substr(line, 13), ' ') ELSE NULL END AS tail FROM discovery_lines\n), discovery_tokens AS NOT MATERIALIZED (\n SELECT public_key, CASE WHEN tail IS NOT NULL\n THEN substr(tail, 1, instr(tail || ' ', ' ') - 1) ELSE NULL END AS token\n FROM discovery_tails\n), live_discovery_keys AS MATERIALIZED (\n SELECT DISTINCT e.public_key FROM discovery_tokens e CROSS JOIN history_input h\n WHERE e.public_key = json_extract(h.value, '$.publicKey')\n OR instr(e.public_key, char(0)) > 0\n OR e.token IS NULL\n OR EXISTS (SELECT 1 FROM json_each(h.value, '$.discoveryFragments') f\n WHERE instr(replace(replace(e.token, '-', '+'), '_', '/'), f.value) > 0)\n OR e.token GLOB '*[^A-Za-z0-9+/=_-]*'\n LIMIT ${MAX_DISCOVERY_KEYS + 1}\n), live_history_keys AS MATERIALIZED (\n SELECT DISTINCT e.public_key, e.fingerprint FROM history_key_sources e\n WHERE e.public_key IN (SELECT public_key FROM snapshot_history_keys)\n LIMIT ${MAX_KEYS + 1}\n)`;\n\nexport const CONTROLLER_HISTORY_KEYS_SQL = `WITH snapshot(value) AS (SELECT ?),\n ${CONTROLLER_HISTORY_CTE}\n SELECT public_key FROM live_discovery_keys ORDER BY public_key`;\n\nconst CONTROLLER_HISTORY_SUBJECT_KEYS_SQL = `WITH snapshot(value) AS (SELECT ?),\n ${CONTROLLER_HISTORY_CTE}\n SELECT public_key, fingerprint FROM live_history_keys ORDER BY public_key, fingerprint`;\n\nexport const CONTROLLER_HISTORY_SELECT_SQL = `WITH snapshot(value) AS (SELECT ?),\n ${CONTROLLER_HISTORY_CTE}\n SELECT group_id, candidate_ref, manifest_version, completed_at, created_at,\n CASE WHEN SUM(length(CAST(manifest_json AS BLOB))) OVER () <= ${MAX_BYTES}\n THEN manifest_json ELSE NULL END AS manifest_json\n FROM live_history ORDER BY group_id, candidate_ref LIMIT ${MAX_RECORDS + 1}`;\n\nexport const CONTROLLER_HISTORY_GUARD = `AND (\n (SELECT value FROM history_input) IS NULL OR (\n json_extract((SELECT value FROM history_input), '$.deviceId') = e.device_id\n AND json_extract((SELECT value FROM history_input), '$.publicKey') = e.public_key\n AND json_extract((SELECT value FROM history_input), '$.fingerprint') = e.fingerprint\n AND (SELECT count(*) FROM live_history) = (SELECT count(*) FROM snapshot_history)\n AND NOT EXISTS (SELECT * FROM live_history EXCEPT SELECT * FROM snapshot_history)\n AND NOT EXISTS (SELECT * FROM live_history_keys EXCEPT SELECT * FROM snapshot_history_keys)\n AND NOT EXISTS (SELECT * FROM snapshot_history_keys EXCEPT SELECT * FROM live_history_keys)\n AND NOT EXISTS (SELECT * FROM live_discovery_keys EXCEPT SELECT * FROM snapshot_discovery_keys)\n AND NOT EXISTS (SELECT * FROM snapshot_discovery_keys EXCEPT SELECT * FROM live_discovery_keys)\n ))`;\n\nexport function parseControllerHistoryRecord(\n\trow: ControllerHistoryRecord,\n\tcoordinatorId: string,\n): ControllerHistoryEvidence {\n\tif (typeof row.group_id !== \"string\" || typeof row.manifest_json !== \"string\")\n\t\tthrow new Error(\"legacy_history_invalid\");\n\tconst manifest = normalizeCoordinatorLegacyTeamCompletionManifest(JSON.parse(row.manifest_json));\n\trequireCoordinatorLegacyTeamCompletionCandidateBinding(manifest, row.group_id);\n\t// Historical Team IDs are retained as evidence, not reinterpreted as owner authority.\n\tif (\n\t\tmanifest.coordinator_id !== coordinatorId ||\n\t\tmanifest.candidate_ref !== row.candidate_ref ||\n\t\tmanifest.version !== row.manifest_version ||\n\t\tmanifest.completed_at !== row.completed_at ||\n\t\ttypeof row.created_at !== \"string\" ||\n\t\t!Number.isFinite(Date.parse(row.created_at)) ||\n\t\tcanonicalCoordinatorLegacyTeamCompletionManifestJson(manifest) !== row.manifest_json\n\t)\n\t\tthrow new Error(\"legacy_history_invalid\");\n\treturn { ...row, manifest };\n}\n\nfunction matchingSubjectKeys(publicKey: string, candidates: string[]): string[] {\n\tconst subject = parseSshEd25519PublicKeyForRevocation(publicKey);\n\treturn candidates.filter((candidate) => {\n\t\tif (candidate === publicKey) return true;\n\t\tif (subject.kind !== \"ed25519\") return false;\n\t\tconst parsed = parseSshEd25519PublicKeyForRevocation(candidate);\n\t\treturn (\n\t\t\tparsed.kind === \"ed25519\" && subject.blob.every((byte, index) => byte === parsed.blob[index])\n\t\t);\n\t});\n}\n\n/** Discovery only: canonical parsing above, never a fragment match, decides alias identity.\n * For any wire offset, one raw-key offset in 0..2 starts on a base64 triplet\n * boundary. Its 27 bytes end before padding and encode to 36 contiguous chars.\n * SQL normalizes URL-safe characters. Any other non-base64 token character\n * (including Buffer-ignored junk or Unicode) takes the conservative GLOB path.\n * ASCII whitespace separates the key type, encoded token and ignored comments;\n * only that token is inspected, never comment punctuation or names. Prefixes\n * outside this ordinary syntax (such as Unicode separators) remain candidates.\n * Embedded NUL also remains a candidate: SQLite token functions stop there,\n * whereas the compatibility base64 decoder can ignore it inside the token.\n */\nexport function controllerHistoryDiscoveryFragments(publicKey: string): string[] {\n\tconst subject = parseSshEd25519PublicKeyForRevocation(publicKey);\n\tif (subject.kind !== \"ed25519\") return [];\n\tconst raw = subject.blob.subarray(19);\n\treturn [0, 1, 2].map((offset) => btoa(String.fromCharCode(...raw.subarray(offset, offset + 27))));\n}\n\nfunction subjectFingerprints(fingerprint: string, keys: HistoryKey[]): string[] {\n\treturn [...new Set([fingerprint, ...keys.map((key) => key.fingerprint)])].sort();\n}\n\n/** Discovery false positives pin classification races, but are not reviewed ownership evidence. */\nexport function controllerHistoryDigestEvidence(history: ControllerHistorySnapshot | undefined) {\n\tif (!history) return undefined;\n\tconst { discoveryKeys: _keys, discoveryFragments: _fragments, ...evidence } = history;\n\treturn evidence;\n}\n\n/** Both backends use the same targeted SELECT, limits and canonical parser. */\nexport async function captureControllerHistory(\n\tinput: ControllerHistoryInput,\n\tall: <T>(sql: string, values: string[]) => Promise<T[]>,\n): Promise<ControllerHistorySnapshot> {\n\tconst discoveryFragments = controllerHistoryDiscoveryFragments(input.publicKey);\n\tconst candidates = await all<{ public_key: string }>(CONTROLLER_HISTORY_KEYS_SQL, [\n\t\tJSON.stringify({ legacyHistory: { ...input, discoveryFragments } }),\n\t]);\n\tif (candidates.length > MAX_DISCOVERY_KEYS) throw new Error(\"legacy_history_too_large\");\n\tconst discoveryKeys = candidates.map((key) => key.public_key);\n\tconst subjectKeys = matchingSubjectKeys(input.publicKey, discoveryKeys);\n\tconst keys = await all<HistoryKey>(CONTROLLER_HISTORY_SUBJECT_KEYS_SQL, [\n\t\tJSON.stringify({\n\t\t\tlegacyHistory: {\n\t\t\t\tcoordinatorId: input.coordinatorId,\n\t\t\t\tkeys: subjectKeys.map((public_key) => ({ public_key })),\n\t\t\t},\n\t\t}),\n\t]);\n\tif (keys.length > MAX_KEYS) throw new Error(\"legacy_history_too_large\");\n\tconst history: ControllerHistorySnapshot = {\n\t\t...input,\n\t\tkeys,\n\t\tdiscoveryKeys,\n\t\tdiscoveryFragments,\n\t\tfingerprints: subjectFingerprints(input.fingerprint, keys),\n\t\trecords: [],\n\t};\n\tconst rows = await all<ControllerHistoryRecord>(CONTROLLER_HISTORY_SELECT_SQL, [\n\t\tJSON.stringify({ legacyHistory: history }),\n\t]);\n\tif (rows.length > MAX_RECORDS) throw new Error(\"legacy_history_too_large\");\n\thistory.records = rows.map((row) => {\n\t\tconst { manifest: _manifest, ...record } = parseControllerHistoryRecord(\n\t\t\trow,\n\t\t\tinput.coordinatorId,\n\t\t);\n\t\treturn record;\n\t});\n\tconst captured = captureControllerHistorySnapshot(history);\n\tif (!captured) throw new Error(\"legacy_history_invalid\");\n\treturn captured;\n}\n\nfunction captureData(value: unknown, budget: { remaining: number }, depth = 0): unknown {\n\tif (--budget.remaining < 0 || depth > 12) throw new Error(\"legacy_history_invalid\");\n\tif (typeof value === \"string\") {\n\t\tbudget.remaining -= value.length;\n\t\tif (budget.remaining < 0) throw new Error(\"legacy_history_too_large\");\n\t\treturn value;\n\t}\n\tif (value === null || typeof value === \"boolean\" || typeof value === \"number\") return value;\n\tif (!value || typeof value !== \"object\") throw new Error(\"legacy_history_invalid\");\n\tconst copy = captureProperties(value, budget, depth);\n\tif (!Array.isArray(value)) return copy;\n\tconst length = Object.getOwnPropertyDescriptor(value, \"length\")?.value;\n\tif (\n\t\t!Number.isSafeInteger(length) ||\n\t\tlength > MAX_DISCOVERY_KEYS ||\n\t\tObject.keys(copy).length !== length\n\t)\n\t\tthrow new Error(\"legacy_history_invalid\");\n\treturn Array.from({ length }, (_, index) => {\n\t\tif (!Object.hasOwn(copy, index)) throw new Error(\"legacy_history_invalid\");\n\t\treturn copy[String(index)];\n\t});\n}\n\nfunction captureProperties(\n\tvalue: object,\n\tbudget: { remaining: number },\n\tdepth: number,\n): Record<string, unknown> {\n\tconst copy: Record<string, unknown> = Object.create(null);\n\tfor (const key of Reflect.ownKeys(value)) {\n\t\tif (Array.isArray(value) && key === \"length\") continue;\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\tif (typeof key !== \"string\" || !descriptor || !Object.hasOwn(descriptor, \"value\"))\n\t\t\tthrow new Error(\"legacy_history_invalid\");\n\t\tcopy[key] = captureData(descriptor.value, budget, depth + 1);\n\t}\n\treturn copy;\n}\n\nfunction stringList(value: unknown): value is string[] {\n\treturn Array.isArray(value) && value.every((item) => typeof item === \"string\" && item.length > 0);\n}\n\nfunction sameStringSet(left: string[], right: string[]): boolean {\n\tconst expected = new Set(left);\n\treturn (\n\t\texpected.size === left.length &&\n\t\tright.length === expected.size &&\n\t\tright.every((item) => expected.delete(item))\n\t);\n}\n\nfunction validSubjectDiscovery(snapshot: ControllerHistorySnapshot): boolean {\n\tif (\n\t\t!stringList(snapshot.discoveryKeys) ||\n\t\tsnapshot.discoveryKeys.length > MAX_DISCOVERY_KEYS ||\n\t\t!Array.isArray(snapshot.discoveryFragments) ||\n\t\tJSON.stringify(snapshot.discoveryFragments) !==\n\t\t\tJSON.stringify(controllerHistoryDiscoveryFragments(snapshot.publicKey)) ||\n\t\t!sameStringSet(snapshot.discoveryKeys, snapshot.discoveryKeys)\n\t)\n\t\treturn false;\n\tconst expected = matchingSubjectKeys(snapshot.publicKey, snapshot.discoveryKeys);\n\tconst actual = [...new Set(snapshot.keys.map((key) => key.public_key))];\n\tif (!sameStringSet(expected, actual)) return false;\n\tif (\n\t\tnew Set(snapshot.keys.map((key) => JSON.stringify([key.public_key, key.fingerprint]))).size !==\n\t\tsnapshot.keys.length\n\t)\n\t\treturn false;\n\treturn (\n\t\tJSON.stringify(snapshot.fingerprints) ===\n\t\tJSON.stringify(subjectFingerprints(snapshot.fingerprint, snapshot.keys))\n\t);\n}\n\n/** Capture JSON data without invoking getters or toJSON on store capability inputs. */\nexport function captureControllerHistorySnapshot(value: unknown): ControllerHistorySnapshot | null {\n\ttry {\n\t\tconst encoded = JSON.stringify(captureData(value, { remaining: MAX_BYTES }));\n\t\tif (!encoded || new TextEncoder().encode(encoded).byteLength > MAX_BYTES) return null;\n\t\tconst snapshot = JSON.parse(encoded) as ControllerHistorySnapshot;\n\t\tif (\n\t\t\t!snapshot ||\n\t\t\t!Array.isArray(snapshot.keys) ||\n\t\t\tsnapshot.keys.length > MAX_KEYS ||\n\t\t\t!Array.isArray(snapshot.fingerprints) ||\n\t\t\t!Array.isArray(snapshot.records) ||\n\t\t\tsnapshot.records.length > MAX_RECORDS ||\n\t\t\t![\n\t\t\t\tsnapshot.coordinatorId,\n\t\t\t\tsnapshot.deviceId,\n\t\t\t\tsnapshot.publicKey,\n\t\t\t\tsnapshot.fingerprint,\n\t\t\t\t...snapshot.fingerprints,\n\t\t\t].every((field) => typeof field === \"string\" && field.length > 0) ||\n\t\t\t!snapshot.keys.every(\n\t\t\t\t(key) => typeof key.public_key === \"string\" && typeof key.fingerprint === \"string\",\n\t\t\t)\n\t\t)\n\t\t\treturn null;\n\t\tif (!validSubjectDiscovery(snapshot)) return null;\n\t\tconst ids = new Set<string>();\n\t\tfor (const row of snapshot.records) {\n\t\t\tparseControllerHistoryRecord(row, snapshot.coordinatorId);\n\t\t\tconst id = JSON.stringify([row.group_id, row.candidate_ref]);\n\t\t\tif (ids.has(id)) return null;\n\t\t\tids.add(id);\n\t\t}\n\t\treturn snapshot;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function parseControllerHistoryEvidence(\n\tvalue: unknown,\n\tcoordinatorId: string,\n): ControllerHistoryEvidence[] {\n\tconst copy = captureData(value, { remaining: MAX_BYTES * 3 });\n\tif (!Array.isArray(copy) || copy.length > MAX_RECORDS) throw new Error(\"legacy_history_invalid\");\n\treturn copy.map((row: ControllerHistoryEvidence) => {\n\t\tconst evidence = parseControllerHistoryRecord(row, coordinatorId);\n\t\tif (\n\t\t\tJSON.stringify(evidence.manifest) !==\n\t\t\tcanonicalCoordinatorLegacyTeamCompletionManifestJson(row.manifest)\n\t\t)\n\t\t\tthrow new Error(\"legacy_history_invalid\");\n\t\treturn evidence;\n\t});\n}\n","/**\n * Storage constraints, not an unlink/relink authorization API.\n * The explicit account-schema migration installs this DDL. Management writers\n * compose the winning proof, archive move and successor CAS in one backend.batch;\n * an Identity identifier alone never authorizes these effects.\n */\nexport const CONNECTION_BIRTH_COLUMNS = [\n\t\"coordinator_id\",\n\t\"link_id\",\n\t\"issuer\",\n\t\"subject\",\n\t\"identity_id\",\n\t\"attempt_id\",\n\t\"controller_attestation_id\",\n\t\"auth_config_revision\",\n\t\"created_at_ms\",\n\t\"revoked_at_ms\",\n\t\"authority_kind\",\n\t\"device_claim_id\",\n] as const;\n\nconst current = \"coordinator_auth_account_links\";\nconst history = \"coordinator_auth_account_connection_history\";\nconst orders = \"coordinator_auth_account_connection_orders\";\nconst birthEqual = CONNECTION_BIRTH_COLUMNS.map((c) => `c.${c} IS NEW.${c}`).join(\" AND \");\nconst immutableBirth = CONNECTION_BIRTH_COLUMNS.filter((c) => c !== \"revoked_at_ms\")\n\t.map((c) => `NEW.${c} IS NOT OLD.${c}`)\n\t.join(\" OR \");\n\n/** Aliases h/c: only delete the exact row whose raw birth was just archived. */\nexport const CONNECTION_ARCHIVED_CURRENT_MATCH_SQL = `h.original_rowid = c.rowid AND ${CONNECTION_BIRTH_COLUMNS.map((column) => `h.${column} IS c.${column}`).join(\" AND \")}`;\n\n/** Current + ended rows retain reservations without a separate association table. */\nexport const CONNECTION_RESERVATIONS_SQL = `SELECT coordinator_id, issuer, subject, identity_id, link_id, created_at_ms FROM ${current}\nUNION ALL SELECT coordinator_id, issuer, subject, identity_id, link_id, created_at_ms FROM ${history}`;\n\n/** Alias l must be the pinned current target, never a caller-selected Identity. */\nexport const CONNECTION_NOT_REVOKED_SQL = `l.revoked_at_ms IS NULL AND NOT EXISTS (\n SELECT 1 FROM ${history} h WHERE h.coordinator_id = l.coordinator_id\n AND h.identity_id = l.identity_id AND h.revoked_at_ms IS NOT NULL)`;\n\n/** The disconnected head is the one ended row without a successor, not a timestamp maximum. */\nexport const CONNECTION_DISCONNECTED_HEAD_SQL = `SELECT h.* FROM ${history} h\nWHERE h.coordinator_id = ? AND h.link_id = ? AND h.successor_link_id IS NULL\n AND NOT EXISTS (SELECT 1 FROM ${current} c WHERE c.coordinator_id = h.coordinator_id AND c.identity_id = h.identity_id)\n AND NOT EXISTS (SELECT 1 FROM ${history} r WHERE r.coordinator_id = h.coordinator_id AND r.identity_id = h.identity_id AND r.revoked_at_ms IS NOT NULL)`;\n\n/** Immediately follow each required single-row write inside the same batch. */\nexport const CONNECTION_ASSERT_ONE_WRITE_SQL = `INSERT INTO ${orders} (coordinator_id, last_order)\nSELECT NULL, 0 WHERE changes() <> 1`;\n\n/** Allocate inside the browser-start batch; overflow raises CHECK, never wraps or resets. */\nexport const CONNECTION_ALLOCATE_ORDER_SQL = `UPDATE ${orders} SET last_order = last_order + 1 WHERE coordinator_id = ?`;\n\n/** Aliases b/l require migration-owned start_order/signin_floor columns.\n * This predicate alone does not verify, consume or authorize a browser proof. */\nexport const CONNECTION_SIGNIN_ORDER_SQL = `b.coordinator_id = l.coordinator_id\n AND b.issuer = l.issuer\n AND b.start_order IS NOT NULL AND ((b.purpose = 'signin' AND b.start_order > l.signin_floor)\n OR (b.purpose = 'link' AND b.attempt_id = l.attempt_id AND EXISTS (\n SELECT 1 FROM coordinator_auth_link_attempts a WHERE a.coordinator_id = l.coordinator_id\n AND a.attempt_id = l.attempt_id AND a.link_id = l.link_id\n AND a.browser_transaction_hash = b.browser_transaction_hash AND a.state IN ('finalized','session_redeemed'))))`;\n\n/**\n * Explicit DDL only. The account-schema migration also installs browser order,\n * current floor and prior-attempt columns before management becomes available.\n * original_rowid retains raw old-row evidence; it is not a global generation ID.\n */\nexport const ACCOUNT_CONNECTION_STORAGE_STATEMENTS = [\n\t`CREATE TABLE ${history} (\n coordinator_id TEXT NOT NULL, link_id TEXT NOT NULL, issuer TEXT NOT NULL,\n subject TEXT NOT NULL CHECK(length(subject) BETWEEN 1 AND 255), identity_id TEXT NOT NULL,\n attempt_id TEXT NOT NULL, controller_attestation_id TEXT,\n auth_config_revision TEXT NOT NULL CHECK(length(auth_config_revision) = 64 AND auth_config_revision NOT GLOB '*[^0-9a-f]*'),\n created_at_ms INTEGER NOT NULL, revoked_at_ms INTEGER,\n authority_kind TEXT NOT NULL CHECK(authority_kind IN ('controller_attestation','device_claim')),\n device_claim_id TEXT, original_rowid INTEGER NOT NULL CHECK(typeof(original_rowid) = 'integer'),\n ended_at_ms INTEGER NOT NULL CHECK(typeof(ended_at_ms) = 'integer' AND ended_at_ms BETWEEN 0 AND 9007199254740991 AND ended_at_ms >= created_at_ms),\n end_attempt_id TEXT NOT NULL CHECK(length(end_attempt_id) BETWEEN 1 AND 256),\n successor_link_id TEXT CHECK(successor_link_id IS NULL OR (length(successor_link_id) BETWEEN 1 AND 256 AND successor_link_id <> link_id)),\n PRIMARY KEY(coordinator_id, link_id), UNIQUE(coordinator_id, end_attempt_id),\n UNIQUE(coordinator_id, successor_link_id),\n CHECK((authority_kind = 'controller_attestation' AND controller_attestation_id IS NOT NULL AND device_claim_id IS NULL)\n OR (authority_kind = 'device_claim' AND controller_attestation_id IS NULL AND device_claim_id IS NOT NULL))\n)`,\n\t`CREATE TRIGGER account_connection_history_insert BEFORE INSERT ON ${history}\nWHEN NEW.successor_link_id IS NOT NULL\n OR EXISTS (SELECT 1 FROM ${history} WHERE rowid = NEW.rowid)\n OR EXISTS (SELECT 1 FROM ${history} WHERE coordinator_id = NEW.coordinator_id AND (link_id = NEW.link_id OR end_attempt_id = NEW.end_attempt_id))\n OR EXISTS (SELECT 1 FROM ${history} WHERE coordinator_id = NEW.coordinator_id AND identity_id = NEW.identity_id AND successor_link_id IS NULL)\n OR NOT EXISTS (SELECT 1 FROM ${current} c WHERE c.rowid = NEW.original_rowid AND ${birthEqual})\nBEGIN SELECT RAISE(ABORT, 'connection_archive_source_invalid'); END`,\n\t// BEFORE INSERT uses -1 for an unallocated rowid. Keep stored rowids positive\n\t// so automatic allocation never reaches that sentinel from a negative rowid.\n\t`CREATE TRIGGER account_connection_history_rowid AFTER INSERT ON ${history}\n WHEN NEW.rowid < 1\n BEGIN SELECT RAISE(ABORT, 'connection_archive_source_invalid'); END`,\n\t`CREATE TRIGGER account_connection_history_update BEFORE UPDATE ON ${history}\nWHEN ${immutableBirth}\n OR NEW.rowid IS NOT OLD.rowid\n OR NEW.original_rowid IS NOT OLD.original_rowid OR NEW.ended_at_ms IS NOT OLD.ended_at_ms\n OR NEW.end_attempt_id IS NOT OLD.end_attempt_id\n OR (NEW.revoked_at_ms IS NOT OLD.revoked_at_ms AND (OLD.revoked_at_ms IS NOT NULL OR typeof(NEW.revoked_at_ms) <> 'integer' OR NEW.revoked_at_ms < 0 OR NEW.revoked_at_ms > 9007199254740991))\n OR (NEW.successor_link_id IS NOT OLD.successor_link_id AND (\n OLD.successor_link_id IS NOT NULL OR NEW.successor_link_id IS NULL OR NEW.revoked_at_ms IS NOT NULL\n OR EXISTS (SELECT 1 FROM ${history} h WHERE h.coordinator_id = NEW.coordinator_id AND h.successor_link_id = NEW.successor_link_id AND h.link_id <> OLD.link_id)\n OR NOT EXISTS (SELECT 1 FROM ${current} c WHERE c.coordinator_id = OLD.coordinator_id AND c.link_id = NEW.successor_link_id AND c.identity_id = OLD.identity_id AND c.revoked_at_ms IS NULL)\n OR EXISTS (SELECT 1 FROM ${history} h WHERE h.coordinator_id = OLD.coordinator_id AND h.identity_id = OLD.identity_id AND h.revoked_at_ms IS NOT NULL)))\nBEGIN SELECT RAISE(ABORT, 'connection_history_immutable'); END`,\n\t`CREATE TRIGGER account_connection_history_delete BEFORE DELETE ON ${history}\nBEGIN SELECT RAISE(ABORT, 'connection_history_immutable'); END`,\n\t`CREATE TRIGGER account_connection_current_insert BEFORE INSERT ON ${current}\nWHEN EXISTS (SELECT 1 FROM ${history} h WHERE h.coordinator_id = NEW.coordinator_id AND (\n h.link_id = NEW.link_id OR (h.issuer = NEW.issuer AND h.subject = NEW.subject AND h.identity_id <> NEW.identity_id)\n OR (h.identity_id = NEW.identity_id AND h.revoked_at_ms IS NOT NULL)))\nBEGIN SELECT RAISE(ABORT, 'connection_reserved_or_revoked'); END`,\n\t// This additional proof trigger has a real invariant and also makes V2's\n\t// exact three-trigger proof readiness check fail, including after old init replay.\n\t`CREATE TRIGGER account_connection_claim_history BEFORE INSERT ON coordinator_auth_device_claims\nWHEN EXISTS (SELECT 1 FROM ${history} h WHERE h.coordinator_id = NEW.coordinator_id AND h.identity_id = NEW.identity_id)\nBEGIN SELECT RAISE(ABORT, 'connection_claim_history_reserved'); END`,\n\t`CREATE TABLE ${orders} (\n coordinator_id TEXT PRIMARY KEY NOT NULL,\n last_order INTEGER NOT NULL CHECK(typeof(last_order) = 'integer' AND last_order BETWEEN 0 AND 9007199254740991)\n) WITHOUT ROWID`,\n\t`CREATE TRIGGER account_connection_order_insert BEFORE INSERT ON ${orders}\nWHEN NEW.last_order <> 0 OR EXISTS (SELECT 1 FROM ${orders} WHERE coordinator_id = NEW.coordinator_id)\nBEGIN SELECT RAISE(ABORT, 'connection_order_reset'); END`,\n\t`CREATE TRIGGER account_connection_order_update BEFORE UPDATE ON ${orders}\nWHEN NEW.coordinator_id IS NOT OLD.coordinator_id OR NEW.last_order <> OLD.last_order + 1\nBEGIN SELECT RAISE(ABORT, 'connection_order_reset'); END`,\n\t`CREATE TRIGGER account_connection_order_delete BEFORE DELETE ON ${orders}\nBEGIN SELECT RAISE(ABORT, 'connection_order_reset'); END`,\n] as const;\n","import { CONNECTION_BIRTH_COLUMNS } from \"./coordinator-account-connection-storage.js\";\n\nexport const CONNECTION_BIRTHS_SQL = `SELECT ${CONNECTION_BIRTH_COLUMNS.join(\",\")} FROM coordinator_auth_account_links UNION ALL SELECT ${CONNECTION_BIRTH_COLUMNS.join(\",\")} FROM coordinator_auth_account_connection_history`;\nfunction rootBirths(coordinator: string, link: string): string {\n\treturn `SELECT ${CONNECTION_BIRTH_COLUMNS.join(\",\")} FROM coordinator_auth_account_links WHERE coordinator_id = ${coordinator} AND link_id = ${link}\n UNION ALL SELECT ${CONNECTION_BIRTH_COLUMNS.join(\",\")} FROM coordinator_auth_account_connection_history WHERE coordinator_id = ${coordinator} AND link_id = ${link}`;\n}\n\n/** Trusted SQL aliases only. Historical ownership is independent of current enrollment.\n * The immutable proof's key ID was derived at commit. Signed-device receipts also\n * pass a freshly derived canonical key ID; account sessions need no current key.\n * Link revocation is deliberately checked by the caller, including post-revoke audit.\n */\nexport function authDeviceClaimProvenanceSql(options: {\n\tlink: \"l\" | \"cl\";\n\tcanonicalKeyId?: \"?\";\n\tconnections?: boolean;\n}): string {\n\tif (options.connections) return connectionClaimProvenance(options);\n\treturn genesisClaimProvenance(\n\t\toptions.link,\n\t\t\"coordinator_auth_account_links\",\n\t\toptions.canonicalKeyId,\n\t);\n}\nfunction genesisClaimProvenance(link: string, births: string, canonicalKeyId?: \"?\"): string {\n\t// Keep provenance independent of the outer session/browser expression tree.\n\t// Native D1 limits expression depth to 100, including correlated subqueries.\n\tconst l = \"pl\";\n\treturn `EXISTS (WITH committed_claim AS MATERIALIZED (\n SELECT ct.coordinator_id, ct.link_id, cd.key_id FROM coordinator_auth_link_attempts ct\n JOIN ${births} pl ON pl.coordinator_id = ct.coordinator_id AND pl.link_id = ct.link_id\n JOIN coordinator_auth_device_claims cd ON cd.coordinator_id = ct.coordinator_id AND cd.claim_id = ${l}.device_claim_id\n JOIN coordinator_auth_link_audit_log ca ON ca.coordinator_id = ct.coordinator_id AND ca.link_id = ct.link_id AND ca.action = 'link_created'\n WHERE ct.coordinator_id = ${link}.coordinator_id AND ct.link_id = ${link}.link_id\n AND ct.attempt_id = ${l}.attempt_id\n AND ct.authority_kind = 'device_claim' AND ct.controller_attestation_id IS NULL\n AND ct.controller_review_receipt_id IS NULL AND ct.controller_revision IS NULL AND ct.state IN ('finalized','session_redeemed')\n AND ${l}.authority_kind = 'device_claim' AND ${l}.controller_attestation_id IS NULL\n AND ct.identity_id = ${l}.identity_id AND ct.issuer = ${l}.issuer AND ct.account_subject = ${l}.subject\n AND ct.auth_config_revision = ${l}.auth_config_revision AND ct.finalized_at_ms = ${l}.created_at_ms\n AND ct.browser_transaction_hash IS NOT NULL AND ct.browser_start_hash IS NOT NULL\n AND ct.runtime_verifier_hash IS NOT NULL AND ct.completion_secret_hash IS NOT NULL\n AND ct.created_at_ms <= ct.claimed_at_ms AND ct.claimed_at_ms <= ct.oidc_verified_at_ms\n AND ct.oidc_verified_at_ms <= ct.confirmed_at_ms AND ct.confirmed_at_ms <= ct.finalized_at_ms AND ct.finalized_at_ms < ct.expires_at_ms\n AND cd.attempt_id = ct.attempt_id AND cd.identity_id = ct.identity_id AND cd.group_id = ct.group_id AND cd.device_id = ct.device_id\n AND cd.public_key = ct.public_key AND cd.fingerprint = ct.fingerprint\n AND cd.issuer = ct.issuer AND cd.auth_config_revision = ct.auth_config_revision AND cd.created_at_ms = ct.finalized_at_ms\n AND ca.authority_kind = 'device_claim' AND ca.controller_attestation_id IS NULL AND ca.device_claim_id IS ${l}.device_claim_id\n AND ca.attempt_id = ct.attempt_id AND ca.identity_id = ct.identity_id AND ca.group_id = ct.group_id AND ca.device_id = ct.device_id\n AND ca.fingerprint = ct.fingerprint AND ca.auth_config_revision = ct.auth_config_revision AND ca.created_at_ms = ct.finalized_at_ms)\n SELECT 1 FROM committed_claim cp WHERE cp.coordinator_id = ${link}.coordinator_id AND cp.link_id = ${link}.link_id\n ${canonicalKeyId ? `AND cp.key_id = ${canonicalKeyId}` : \"\"})`;\n}\n\n/** One immutable claim resolves its genesis directly; no recursive lineage walk. */\nexport function authClaimGenesisSql(claim: \"d\" | \"cd\"): string {\n\treturn `EXISTS (WITH connection_births AS MATERIALIZED (${rootBirths(`${claim}.coordinator_id`, `${claim}.claim_id`)}) SELECT 1 FROM connection_births gl WHERE gl.coordinator_id = ${claim}.coordinator_id AND gl.link_id = ${claim}.claim_id AND ${genesisClaimProvenance(\"gl\", \"connection_births\")})`;\n}\nfunction connectionClaimProvenance(options: { link: \"l\" | \"cl\"; canonicalKeyId?: \"?\" }): string {\n\tconst l = options.link;\n\treturn `EXISTS (WITH connection_births AS MATERIALIZED (${rootBirths(`${l}.coordinator_id`, `${l}.device_claim_id`)}), continuation AS MATERIALIZED (\n SELECT t.coordinator_id,t.link_id,d.key_id FROM coordinator_auth_link_attempts t\n JOIN coordinator_auth_link_audit_log a ON a.coordinator_id = t.coordinator_id AND a.link_id = t.link_id AND a.action = 'link_created'\n JOIN coordinator_auth_device_claims d ON d.coordinator_id = t.coordinator_id AND d.claim_id = ${l}.device_claim_id\n WHERE t.coordinator_id = ${l}.coordinator_id AND t.link_id = ${l}.link_id AND t.attempt_id = ${l}.attempt_id\n AND (${l}.authority_kind = 'device_claim' AND ${l}.controller_attestation_id IS NULL AND t.authority_kind = 'device_claim' AND t.controller_attestation_id IS NULL AND t.controller_review_receipt_id IS NULL AND t.controller_revision IS NULL)\n AND (t.state IN ('finalized','session_redeemed') AND t.identity_id = ${l}.identity_id AND t.issuer = ${l}.issuer AND t.account_subject = ${l}.subject AND t.auth_config_revision = ${l}.auth_config_revision AND t.finalized_at_ms = ${l}.created_at_ms)\n AND (t.browser_start_hash IS NOT NULL AND t.browser_transaction_hash IS NOT NULL AND t.runtime_verifier_hash IS NOT NULL AND t.completion_secret_hash IS NOT NULL AND t.created_at_ms <= t.claimed_at_ms AND t.claimed_at_ms <= t.oidc_verified_at_ms AND t.oidc_verified_at_ms <= t.confirmed_at_ms AND t.confirmed_at_ms <= t.finalized_at_ms AND t.finalized_at_ms < t.expires_at_ms)\n AND (d.identity_id = t.identity_id AND d.issuer = t.issuer AND d.group_id = t.group_id AND d.device_id = t.device_id AND d.public_key = t.public_key AND d.fingerprint = t.fingerprint)\n AND (a.attempt_id = t.attempt_id AND a.identity_id = t.identity_id AND a.group_id = t.group_id AND a.device_id = t.device_id AND a.fingerprint = t.fingerprint AND a.auth_config_revision = t.auth_config_revision AND a.created_at_ms = t.finalized_at_ms AND a.authority_kind = 'device_claim' AND a.controller_attestation_id IS NULL AND a.device_claim_id = d.claim_id)\n AND ((t.prior_link_id IS NULL AND t.link_id = d.claim_id) OR EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id = t.coordinator_id AND h.link_id = t.prior_link_id AND h.identity_id = t.identity_id AND h.successor_link_id = t.link_id))\n AND EXISTS (SELECT 1 FROM connection_births gl WHERE gl.coordinator_id = d.coordinator_id AND gl.link_id = d.claim_id AND ${genesisClaimProvenance(\"gl\", \"connection_births\")}))\n SELECT 1 FROM continuation cp ${options.canonicalKeyId ? \"WHERE cp.key_id = ?\" : \"\"})`;\n}\n\n/** Account management only; privileged enrollment/grant proofs remain attested-only. */\nfunction controllerBirthProvenance(link: \"l\"): string {\n\treturn `EXISTS (WITH controller_receipt AS MATERIALIZED (SELECT t.coordinator_id,t.link_id FROM coordinator_auth_link_attempts t\n JOIN coordinator_auth_controller_attestations origin ON origin.coordinator_id=t.coordinator_id AND origin.attestation_id=t.controller_attestation_id\n JOIN coordinator_auth_link_audit_log a ON a.coordinator_id=t.coordinator_id AND a.link_id=t.link_id AND a.action='link_created'\n WHERE (t.coordinator_id=${link}.coordinator_id AND t.link_id=${link}.link_id AND t.attempt_id=${link}.attempt_id AND t.authority_kind='controller_attestation' AND t.controller_attestation_id=${link}.controller_attestation_id)\n AND (t.identity_id=${link}.identity_id AND t.issuer=${link}.issuer AND t.account_subject=${link}.subject AND t.auth_config_revision=${link}.auth_config_revision AND t.finalized_at_ms=${link}.created_at_ms AND t.state IN ('finalized','session_redeemed'))\n AND (t.browser_transaction_hash IS NOT NULL AND t.runtime_verifier_hash IS NOT NULL AND t.completion_secret_hash IS NOT NULL AND t.created_at_ms<=t.claimed_at_ms AND t.claimed_at_ms<=t.oidc_verified_at_ms AND t.oidc_verified_at_ms<=t.confirmed_at_ms AND t.confirmed_at_ms<=t.finalized_at_ms AND t.finalized_at_ms<t.expires_at_ms)\n AND (origin.identity_id=t.identity_id AND origin.group_id=t.group_id AND origin.device_id=t.device_id AND origin.public_key=t.public_key AND origin.fingerprint=t.fingerprint AND origin.review_receipt_id=t.controller_review_receipt_id AND origin.revision=t.controller_revision)\n AND (t.prior_link_id IS NULL OR EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id=t.coordinator_id AND h.identity_id=t.identity_id AND h.link_id=t.prior_link_id AND h.successor_link_id=t.link_id))\n AND (a.attempt_id=t.attempt_id AND a.identity_id=t.identity_id AND a.group_id=t.group_id AND a.device_id=t.device_id AND a.fingerprint=t.fingerprint AND a.controller_attestation_id=t.controller_attestation_id AND a.authority_kind=t.authority_kind AND a.device_claim_id IS NULL AND a.auth_config_revision=t.auth_config_revision AND a.created_at_ms=t.finalized_at_ms)) SELECT 1 FROM controller_receipt)`;\n}\nexport function authAccountLinkProvenanceSql(\n\tlink: \"l\",\n\toptions: { connections?: boolean } = {},\n): string {\n\treturn `((${link}.authority_kind = 'controller_attestation' AND ${link}.controller_attestation_id IS NOT NULL AND ${link}.device_claim_id IS NULL${options.connections ? ` AND ${controllerBirthProvenance(link)}` : \"\"})\n OR (${authDeviceClaimProvenanceSql({ link, connections: options.connections })}))`;\n}\n","import { CONNECTION_NOT_REVOKED_SQL } from \"./coordinator-account-connection-storage.js\";\nimport { authAccountLinkProvenanceSql } from \"./coordinator-auth-link-provenance.js\";\n\n/** Recovery-only root WITH stage: ordinary seed schemas need no V3 tables.\n * Keep the independent provenance expression outside the enrollment/history\n * expression tree to fit D1's depth 100 limit. Both still share one statement.\n */\nexport const AUTH_CONTROLLER_OWNER_CTE = `controller_owner_connection AS MATERIALIZED (\n SELECT l.coordinator_id,l.identity_id FROM coordinator_auth_account_links l CROSS JOIN snapshot s\n WHERE l.coordinator_id=json_extract(s.value,'$.accountOwnerTarget.coordinatorId')\n AND l.identity_id=json_extract(s.value,'$.accountOwnerTarget.targetIdentityId')\n AND l.issuer=json_extract(s.value,'$.accountOwnerTarget.issuer')\n AND l.link_id=json_extract(s.value,'$.accountOwnerTarget.linkId')\n AND l.auth_config_revision=json_extract(s.value,'$.accountOwnerTarget.authConfigRevision')\n AND l.created_at_ms=json_extract(s.value,'$.accountOwnerTarget.createdAtMs')\n AND ${CONNECTION_NOT_REVOKED_SQL}\n AND ${authAccountLinkProvenanceSql(\"l\", { connections: true })})`;\n\nexport const AUTH_CONTROLLER_OWNER_GUARD = `AND EXISTS (\n SELECT 1 FROM controller_owner_connection l\n WHERE NOT EXISTS (SELECT 1 FROM coordinator_auth_device_claims d\n WHERE d.coordinator_id=l.coordinator_id AND (d.device_id=e.device_id OR d.key_id=?)\n AND (d.identity_id<>l.identity_id OR d.group_id<>e.group_id\n OR d.device_id<>e.device_id OR d.public_key<>e.public_key OR d.fingerprint<>e.fingerprint))\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_controller_attestations other\n WHERE other.coordinator_id=l.coordinator_id AND other.group_id=e.group_id\n AND other.device_id=e.device_id AND other.fingerprint=e.fingerprint\n AND (other.identity_id<>l.identity_id OR other.public_key<>e.public_key OR other.revoked_at IS NOT NULL))\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_controller_attestations other\n WHERE other.coordinator_id=l.coordinator_id AND other.identity_id<>l.identity_id\n AND (other.device_id=e.device_id OR other.public_key=e.public_key\n OR other.public_key IN (SELECT public_key FROM snapshot_history_keys))))`;\n\n/** Retained trusted controller rows are ownership evidence even if their Team or\n * enrollment is gone. Weak historical Team assignments are not consulted here.\n */\nexport const AUTH_CONTROLLER_SUBJECT_OWNER_CONFLICT_SQL = `WITH owner_subject(value) AS (SELECT ?)\n SELECT 1 AS conflict FROM coordinator_auth_controller_attestations other CROSS JOIN owner_subject s\n WHERE other.coordinator_id=json_extract(s.value,'$.coordinatorId') AND other.identity_id<>?\n AND (other.device_id=json_extract(s.value,'$.deviceId')\n OR other.public_key=json_extract(s.value,'$.publicKey')\n OR other.public_key IN (SELECT json_extract(j.value,'$.public_key') FROM json_each(s.value,'$.keys') j))\n LIMIT 1`;\n\nexport interface CoordinatorAuthControllerOwnerSnapshot {\n\tpurpose: \"existing_account_owner\";\n\tcoordinatorId: string;\n\ttargetIdentityId: string;\n\tissuer: string;\n\tlinkId: string;\n\tauthConfigRevision: string;\n\tcreatedAtMs: number;\n}\n","import {\n\tCONTROLLER_HISTORY_CTE,\n\tCONTROLLER_HISTORY_GUARD,\n\ttype ControllerHistoryInput,\n\ttype ControllerHistorySnapshot,\n\tcaptureControllerHistorySnapshot,\n} from \"./coordinator-auth-controller-history.js\";\nimport {\n\tAUTH_CONTROLLER_OWNER_CTE,\n\tAUTH_CONTROLLER_OWNER_GUARD,\n\ttype CoordinatorAuthControllerOwnerSnapshot,\n} from \"./coordinator-auth-controller-owner.js\";\n\n/** Persistence of completed, trusted admin reviews, not authentication of request JSON.\n * Future routes must authenticate the configured admin before invoking this capability.\n * Enrollment identity labels alone never create controller authority.\n */\nexport interface CoordinatorAuthControllerReviewInput {\n\tattestationId: string;\n\tcoordinatorId: string;\n\tidentityId: string;\n\tgroupId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n\treviewReceiptId: string;\n\tevidenceDigest: string;\n\t/** Optional for legacy trusted seed callers; operator routes always supply it. */\n\tverifiedSnapshot?: CoordinatorAuthControllerVerifiedSnapshot;\n}\n\nexport interface CoordinatorAuthControllerVerifiedSnapshot {\n\tenrollmentIdentityId: string | null;\n\taccountOwnerTarget?: CoordinatorAuthControllerOwnerSnapshot;\n\t/** Captured by the trusted history reader when supplied. */\n\tlegacyHistory?: ControllerHistorySnapshot;\n\tinvites: {\n\t\tinviteId: string;\n\t\tkind: \"team_member\" | \"add_device\";\n\t\tactorId: string;\n\t\tassignedIdentityId: string | null;\n\t\ttargetIdentityId: string | null;\n\t\tdigest: string;\n\t}[];\n}\n\nexport interface CoordinatorAuthControllerAttestation {\n\treadonly attestation_id: string;\n\treadonly coordinator_id: string;\n\treadonly identity_id: string;\n\treadonly group_id: string;\n\treadonly device_id: string;\n\treadonly public_key: string;\n\treadonly fingerprint: string;\n\treadonly review_receipt_id: string;\n\treadonly evidence_digest: string;\n\treadonly enrollment_identity_id: string | null;\n\treadonly revision: 1;\n\treadonly created_at: string;\n\treadonly revoked_at: string | null;\n}\n\nexport type CoordinatorAuthControllerCreateResult =\n\t| { kind: \"created\" | \"existing\"; attestation: CoordinatorAuthControllerAttestation }\n\t| {\n\t\t\tkind: \"rejected\";\n\t\t\terror:\n\t\t\t\t| \"invalid_review_input\"\n\t\t\t\t| \"enrollment_mismatch\"\n\t\t\t\t| \"review_stale\"\n\t\t\t\t| \"attestation_conflict\"\n\t\t\t\t| \"attestation_revoked\";\n\t };\n\nexport interface CoordinatorAuthControllerStore {\n\thasAuthControllerSubjectOwnerConflict(\n\t\tinput: CoordinatorAuthControllerSubjectOwnerInput,\n\t): Promise<boolean>;\n\t/** Read-only restore: checks fresh evidence without comparing or rewriting the stored digest. */\n\treadAuthControllerAttestationForSnapshot(\n\t\tinput: CoordinatorAuthControllerReviewInput,\n\t): Promise<CoordinatorAuthControllerAttestation | null>;\n\tcaptureAuthControllerLegacyHistory(\n\t\tinput: ControllerHistoryInput,\n\t): Promise<ControllerHistorySnapshot>;\n\tcreateAuthControllerAttestation(\n\t\tinput: CoordinatorAuthControllerReviewInput,\n\t): Promise<CoordinatorAuthControllerCreateResult>;\n\tgetActiveAuthControllerAttestation(\n\t\tcoordinatorId: string,\n\t\tattestationId: string,\n\t): Promise<CoordinatorAuthControllerAttestation | null>;\n\trevokeAuthControllerAttestation(coordinatorId: string, attestationId: string): Promise<boolean>;\n}\n\nexport interface CoordinatorAuthControllerSubjectOwnerInput {\n\tidentityId: string;\n\t/** Captured by the trusted history reader, never accepted from browser JSON. */\n\thistory: ControllerHistorySnapshot;\n}\n\nexport function authControllerSubjectOwnerConflictValues(\n\tinput: CoordinatorAuthControllerSubjectOwnerInput,\n): string[] {\n\ttry {\n\t\tconst identity = Object.getOwnPropertyDescriptor(input, \"identityId\");\n\t\tconst history = Object.getOwnPropertyDescriptor(input, \"history\");\n\t\tif (\n\t\t\t!identity ||\n\t\t\t!Object.hasOwn(identity, \"value\") ||\n\t\t\t!isAuthControllerId(identity.value) ||\n\t\t\t!history ||\n\t\t\t!Object.hasOwn(history, \"value\")\n\t\t)\n\t\t\tthrow new Error(\"account_owner_subject_invalid\");\n\t\tconst captured = captureControllerHistorySnapshot(history.value);\n\t\tif (\n\t\t\t!captured ||\n\t\t\t!isAuthControllerId(captured.coordinatorId) ||\n\t\t\t!isAuthControllerId(captured.deviceId)\n\t\t)\n\t\t\tthrow new Error(\"account_owner_subject_invalid\");\n\t\treturn [JSON.stringify(captured), identity.value];\n\t} catch {\n\t\tthrow new Error(\"account_owner_subject_invalid\");\n\t}\n}\n\nconst REVIEW_FIELDS = {\n\tattestationId: \"attestation_id\",\n\tcoordinatorId: \"coordinator_id\",\n\tidentityId: \"identity_id\",\n\tgroupId: \"group_id\",\n\tdeviceId: \"device_id\",\n\tpublicKey: \"public_key\",\n\tfingerprint: \"fingerprint\",\n\treviewReceiptId: \"review_receipt_id\",\n\tevidenceDigest: \"evidence_digest\",\n} as const;\n\nexport function isAuthControllerId(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length > 0 &&\n\t\tvalue.length <= 256 &&\n\t\tvalue.trim() === value &&\n\t\t!/[\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(value)\n\t);\n}\n\nfunction isReviewFieldValid(field: string, value: unknown): value is string {\n\tif (typeof value !== \"string\") return false;\n\tif (field === \"fingerprint\" || field === \"evidenceDigest\") {\n\t\treturn value.length === 64 && /^[a-f0-9]{64}$/.test(value);\n\t}\n\tif (field !== \"publicKey\") return isAuthControllerId(value);\n\t// PEM exports include a final line ending. Validate without line endings, but\n\t// retain the original bytes for the authoritative enrollment comparison.\n\tconst withoutLineEndings = value.replace(/[\\r\\n]/g, \"\");\n\treturn (\n\t\twithoutLineEndings.length > 0 &&\n\t\tvalue.length <= 4096 &&\n\t\twithoutLineEndings.trim() === withoutLineEndings &&\n\t\t!/[\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(withoutLineEndings)\n\t);\n}\n\ntype VerifiedInvite = CoordinatorAuthControllerVerifiedSnapshot[\"invites\"][number];\nfunction validSnapshotField(field: keyof VerifiedInvite, value: unknown): boolean {\n\tif (field === \"kind\") return value === \"team_member\" || value === \"add_device\";\n\tif (field === \"digest\") return isReviewFieldValid(\"evidenceDigest\", value);\n\tif (field === \"assignedIdentityId\" || field === \"targetIdentityId\")\n\t\treturn value === null || isAuthControllerId(value);\n\treturn isAuthControllerId(value);\n}\nfunction captureVerifiedInvite(value: unknown): VerifiedInvite | null {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n\tconst fields = [\n\t\t\"inviteId\",\n\t\t\"kind\",\n\t\t\"actorId\",\n\t\t\"assignedIdentityId\",\n\t\t\"targetIdentityId\",\n\t\t\"digest\",\n\t] as const;\n\tconst copy: Record<string, string | null> = {};\n\tfor (const field of fields) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, field);\n\t\tif (!descriptor || !Object.hasOwn(descriptor, \"value\")) return null;\n\t\tif (!validSnapshotField(field, descriptor.value)) return null;\n\t\tcopy[field] = descriptor.value;\n\t}\n\treturn copy as VerifiedInvite;\n}\nfunction captureVerifiedInvites(value: unknown): VerifiedInvite[] | null {\n\tif (!Array.isArray(value)) return null;\n\tconst length = Object.getOwnPropertyDescriptor(value, \"length\");\n\tif (\n\t\t!length ||\n\t\t!Object.hasOwn(length, \"value\") ||\n\t\t!Number.isSafeInteger(length.value) ||\n\t\tlength.value > 4096\n\t)\n\t\treturn null;\n\tconst invites: VerifiedInvite[] = [];\n\tconst ids = new Set<string>();\n\tfor (let index = 0; index < length.value; index++) {\n\t\tconst item = Object.getOwnPropertyDescriptor(value, String(index));\n\t\tif (!item || !Object.hasOwn(item, \"value\")) return null;\n\t\tconst invite = captureVerifiedInvite(item.value);\n\t\tif (!invite || ids.has(invite.inviteId)) return null;\n\t\tids.add(invite.inviteId);\n\t\tinvites.push(invite);\n\t}\n\treturn invites;\n}\nexport function captureVerifiedSnapshot(\n\tvalue: unknown,\n): CoordinatorAuthControllerVerifiedSnapshot | null {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n\tconst identity = Object.getOwnPropertyDescriptor(value, \"enrollmentIdentityId\");\n\tconst list = Object.getOwnPropertyDescriptor(value, \"invites\");\n\tif (!identity || !Object.hasOwn(identity, \"value\") || !list || !Object.hasOwn(list, \"value\"))\n\t\treturn null;\n\tif (identity.value !== null && !isAuthControllerId(identity.value)) return null;\n\tconst invites = captureVerifiedInvites(list.value);\n\tif (!invites) return null;\n\tconst snapshot: CoordinatorAuthControllerVerifiedSnapshot = {\n\t\tenrollmentIdentityId: identity.value as string | null,\n\t\tinvites,\n\t};\n\tconst history = captureOptionalField(value, \"legacyHistory\", captureControllerHistorySnapshot);\n\tconst target = captureOptionalField(value, \"accountOwnerTarget\", captureOwnerTarget);\n\tif (history === null || target === null) return null;\n\tif (history !== undefined) snapshot.legacyHistory = history;\n\tif (target !== undefined) snapshot.accountOwnerTarget = target;\n\tif (new TextEncoder().encode(JSON.stringify(snapshot)).byteLength > 1_000_000) return null;\n\treturn snapshot;\n}\n\nfunction captureOptionalField<T>(\n\tvalue: object,\n\tfield: string,\n\tcapture: (value: unknown) => T | null,\n): T | null | undefined {\n\tconst descriptor = Object.getOwnPropertyDescriptor(value, field);\n\tif (!descriptor) return field in value ? null : undefined;\n\tif (!Object.hasOwn(descriptor, \"value\")) return null;\n\treturn capture(descriptor.value);\n}\n\nfunction captureOwnerTarget(value: unknown): CoordinatorAuthControllerOwnerSnapshot | null {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n\tconst fields = [\n\t\t\"purpose\",\n\t\t\"coordinatorId\",\n\t\t\"targetIdentityId\",\n\t\t\"issuer\",\n\t\t\"linkId\",\n\t\t\"authConfigRevision\",\n\t\t\"createdAtMs\",\n\t] as const;\n\tif (Reflect.ownKeys(value).length !== fields.length) return null;\n\tconst copy: Record<string, unknown> = {};\n\tfor (const field of fields) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, field);\n\t\tif (!descriptor || !Object.hasOwn(descriptor, \"value\")) return null;\n\t\tcopy[field] = descriptor.value;\n\t}\n\tif (\n\t\tcopy.purpose !== \"existing_account_owner\" ||\n\t\t!Number.isSafeInteger(copy.createdAtMs) ||\n\t\t(copy.createdAtMs as number) < 0\n\t)\n\t\treturn null;\n\tif (\n\t\t![\"coordinatorId\", \"targetIdentityId\", \"issuer\", \"linkId\"].every((field) =>\n\t\t\tisAuthControllerId(copy[field]),\n\t\t) ||\n\t\t!isReviewFieldValid(\"evidenceDigest\", copy.authConfigRevision)\n\t)\n\t\treturn null;\n\treturn copy as unknown as CoordinatorAuthControllerOwnerSnapshot;\n}\n\nfunction captureOptionalSnapshot(\n\tinput: object,\n): CoordinatorAuthControllerVerifiedSnapshot | null | undefined {\n\tconst snapshot = Object.getOwnPropertyDescriptor(input, \"verifiedSnapshot\");\n\tif (!snapshot) return \"verifiedSnapshot\" in input ? null : undefined;\n\tif (!Object.hasOwn(snapshot, \"value\")) return null;\n\treturn captureVerifiedSnapshot(snapshot.value);\n}\n\n/** Capture own data properties once, without coercion, inherited fields or getters. */\nexport function captureAuthControllerReview(\n\tinput: unknown,\n): CoordinatorAuthControllerReviewInput | null {\n\tif (!input || typeof input !== \"object\") return null;\n\tconst captured: Partial<CoordinatorAuthControllerReviewInput> = {};\n\ttry {\n\t\tif (Array.isArray(input)) return null;\n\t\tconst fields = Object.keys(REVIEW_FIELDS) as (keyof typeof REVIEW_FIELDS)[];\n\t\tfor (const field of fields) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(input, field);\n\t\t\tif (!descriptor || !Object.hasOwn(descriptor, \"value\")) return null;\n\t\t\tif (!isReviewFieldValid(field, descriptor.value)) return null;\n\t\t\tcaptured[field] = descriptor.value;\n\t\t}\n\t\tconst snapshot = captureOptionalSnapshot(input);\n\t\tif (snapshot === null) return null;\n\t\tif (!historyMatchesReview(snapshot?.legacyHistory, captured)) return null;\n\t\tif (!ownerTargetMatchesReview(snapshot, captured)) return null;\n\t\tif (snapshot !== undefined) captured.verifiedSnapshot = snapshot;\n\t} catch {\n\t\treturn null;\n\t}\n\treturn captured as CoordinatorAuthControllerReviewInput;\n}\n\nfunction historyMatchesReview(\n\thistory: ControllerHistorySnapshot | undefined,\n\tinput: Partial<CoordinatorAuthControllerReviewInput>,\n): boolean {\n\tif (!history) return true;\n\treturn (\n\t\thistory.coordinatorId === input.coordinatorId &&\n\t\thistory.deviceId === input.deviceId &&\n\t\thistory.publicKey === input.publicKey &&\n\t\thistory.fingerprint === input.fingerprint\n\t);\n}\n\nfunction ownerTargetMatchesReview(\n\tsnapshot: CoordinatorAuthControllerVerifiedSnapshot | undefined,\n\tinput: Partial<CoordinatorAuthControllerReviewInput>,\n): boolean {\n\tconst target = snapshot?.accountOwnerTarget;\n\tif (!target) return true;\n\treturn (\n\t\t!!snapshot?.legacyHistory &&\n\t\ttarget.coordinatorId === input.coordinatorId &&\n\t\ttarget.targetIdentityId === input.identityId\n\t);\n}\n\nexport function authControllerRetryResult(\n\tinput: CoordinatorAuthControllerReviewInput,\n\trow: CoordinatorAuthControllerAttestation | null,\n): CoordinatorAuthControllerCreateResult {\n\tif (\n\t\t!row ||\n\t\tObject.entries(REVIEW_FIELDS).some(\n\t\t\t([field, column]) =>\n\t\t\t\tinput[field as keyof CoordinatorAuthControllerReviewInput] !== row[column],\n\t\t)\n\t) {\n\t\treturn { kind: \"rejected\", error: \"attestation_conflict\" };\n\t}\n\tif (row.revoked_at !== null) return { kind: \"rejected\", error: \"attestation_revoked\" };\n\treturn { kind: \"existing\", attestation: row };\n}\n\nexport function authControllerUnavailableResult(\n\tinput: CoordinatorAuthControllerReviewInput,\n): CoordinatorAuthControllerCreateResult {\n\treturn {\n\t\tkind: \"rejected\",\n\t\terror: input.verifiedSnapshot ? \"review_stale\" : \"enrollment_mismatch\",\n\t};\n}\n\n/** Only uniqueness violations are domain conflicts; other backend failures propagate. */\nexport function isAuthControllerUniqueError(error: unknown): boolean {\n\tif (!(error instanceof Error)) return false;\n\tconst code = Object.getOwnPropertyDescriptor(error, \"code\")?.value;\n\treturn (\n\t\tcode === \"SQLITE_CONSTRAINT_UNIQUE\" ||\n\t\tcode === \"SQLITE_CONSTRAINT_PRIMARYKEY\" ||\n\t\t/\\bUNIQUE constraint failed\\b/i.test(error.message)\n\t);\n}\n\nexport const AUTH_CONTROLLER_SCHEMA_SQL = `\n\tCREATE TABLE IF NOT EXISTS coordinator_auth_controller_attestations (\n\t\tattestation_id TEXT NOT NULL,\n\t\tcoordinator_id TEXT NOT NULL,\n\t\tidentity_id TEXT NOT NULL,\n\t\tgroup_id TEXT NOT NULL,\n\t\tdevice_id TEXT NOT NULL,\n\t\tpublic_key TEXT NOT NULL,\n\t\tfingerprint TEXT NOT NULL CHECK (length(fingerprint) = 64 AND fingerprint NOT GLOB '*[^0-9a-f]*'),\n\t\treview_receipt_id TEXT NOT NULL,\n\t\tevidence_digest TEXT NOT NULL CHECK (length(evidence_digest) = 64 AND evidence_digest NOT GLOB '*[^0-9a-f]*'),\n\t\tenrollment_identity_id TEXT,\n\t\trevision INTEGER NOT NULL DEFAULT 1 CHECK (revision = 1),\n\t\tcreated_at TEXT NOT NULL,\n\t\trevoked_at TEXT,\n\t\tPRIMARY KEY (coordinator_id, attestation_id),\n\t\tUNIQUE (coordinator_id, group_id, device_id, fingerprint),\n\t\tUNIQUE (coordinator_id, review_receipt_id)\n\t);`;\n\n// No foreign keys: removal of an enrollment must not erase revocation tombstones.\n// One JSON bind keeps the exact set comparison below D1's parameter limit.\n// Parse each tuple once; EXCEPT uses temporary B-trees rather than an inner\n// JSON scan per live invite. Unique captured/live IDs plus equal counts prove\n// equality; EXCEPT also compares nullable identity fields without losing NULLs.\nconst AUTH_CONTROLLER_SNAPSHOT_CTE = `\n\tWITH snapshot(value) AS (SELECT ?), snapshot_invites AS MATERIALIZED (\n\t\tSELECT json_extract(j.value, '$.inviteId') AS invite_id,\n\t\t\tjson_extract(j.value, '$.kind') AS invite_kind,\n\t\t\tjson_extract(j.value, '$.actorId') AS recipient_actor_id,\n\t\t\tjson_extract(j.value, '$.assignedIdentityId') AS assigned_identity_id,\n\t\t\tjson_extract(j.value, '$.targetIdentityId') AS target_identity_id,\n\t\t\tjson_extract(j.value, '$.digest') AS reviewed_preview_digest\n\t\tFROM json_each((SELECT value FROM snapshot), '$.invites') j\n\t), live_invites AS MATERIALIZED (\n\t\tSELECT i.invite_id, i.invite_kind, i.recipient_actor_id, i.assigned_identity_id,\n\t\t\ti.target_identity_id, i.reviewed_preview_digest FROM coordinator_invites i\n\t\tWHERE i.group_id = ? AND i.bound_device_id = ? AND i.bound_public_key = ?\n\t\t\tAND i.bound_fingerprint = ? AND i.revoked_at IS NULL\n\t\t\tAND i.consumed_at IS NOT NULL AND i.consumed_at != ''\n\t\t\tAND i.invite_kind IN ('team_member', 'add_device')\n\t), ${CONTROLLER_HISTORY_CTE}`;\nconst AUTH_CONTROLLER_SNAPSHOT_GUARD = `\n\tAND ((SELECT value FROM snapshot) IS NULL OR (\n\t\te.identity_id IS json_extract((SELECT value FROM snapshot), '$.enrollmentIdentityId')\n\t\tAND (SELECT count(*) FROM live_invites) =\n\t\t\t(SELECT count(*) FROM snapshot_invites)\n\t\tAND NOT EXISTS (\n\t\t\tSELECT * FROM live_invites\n\t\t\tEXCEPT\n\t\t\tSELECT * FROM snapshot_invites\n\t\t)\n\t)) ${CONTROLLER_HISTORY_GUARD}`;\n\nfunction authControllerSnapshotValues(\n\tinput: CoordinatorAuthControllerReviewInput,\n): (string | null)[] {\n\treturn [\n\t\tinput.verifiedSnapshot ? JSON.stringify(input.verifiedSnapshot) : null,\n\t\tinput.groupId,\n\t\tinput.deviceId,\n\t\tinput.publicKey,\n\t\tinput.fingerprint,\n\t];\n}\n\n/** Pin the actual enrollment used to derive the revocation key across async reads. */\nexport function authControllerAuthorityValues(\n\tsource: {\n\t\tgroup_id: string;\n\t\tdevice_id: string;\n\t\tpublic_key: string;\n\t\tfingerprint: string;\n\t\tidentity_id: string | null;\n\t},\n\tkeyId: string | null,\n): (string | null)[] {\n\treturn [\n\t\tsource.group_id,\n\t\tsource.device_id,\n\t\tsource.public_key,\n\t\tsource.fingerprint,\n\t\tsource.identity_id,\n\t\tsource.device_id,\n\t\tkeyId,\n\t];\n}\n\nconst AUTH_CONTROLLER_AUTHORITY_GUARD = `\n\tAND e.group_id = ? AND e.device_id = ? AND e.public_key = ?\n\tAND e.fingerprint = ? AND e.identity_id IS ?\n\tAND NOT EXISTS (SELECT 1 FROM coordinator_device_revocations WHERE\n\t\t(subject_kind = 'device_id' AND subject_value = ?) OR\n\t\t(subject_kind = 'ed25519_key' AND subject_value = ?))`;\n\nexport const AUTH_CONTROLLER_ENROLLMENT_SQL = `\n\tSELECT e.* FROM enrolled_devices e WHERE e.group_id = ? AND e.device_id = ?`;\n\nexport const AUTH_CONTROLLER_INSERT_SQL = `\n\t${AUTH_CONTROLLER_SNAPSHOT_CTE}\n\tINSERT INTO coordinator_auth_controller_attestations (\n\t\tattestation_id, coordinator_id, identity_id, group_id, device_id, public_key,\n\t\tfingerprint, review_receipt_id, evidence_digest, enrollment_identity_id, revision, created_at, revoked_at\n\t)\n\tSELECT ?, ?, ?, e.group_id, e.device_id, e.public_key, e.fingerprint, ?, ?, e.identity_id, 1, ?, NULL\n\tFROM enrolled_devices e JOIN groups g ON g.group_id = e.group_id\n\tWHERE e.group_id = ? AND e.device_id = ? AND e.enabled = 1 AND g.archived_at IS NULL\n\t\tAND e.public_key = ? AND e.fingerprint = ? AND (e.identity_id IS NULL OR e.identity_id = ?)\n\t\t${AUTH_CONTROLLER_SNAPSHOT_GUARD}\n\t\t${AUTH_CONTROLLER_AUTHORITY_GUARD}`;\n\n/** Retry eligibility is read atomically with all the same live evidence guards. */\nexport const AUTH_CONTROLLER_RETRY_ELIGIBLE_SQL = `\n\t${AUTH_CONTROLLER_SNAPSHOT_CTE}\n\tSELECT 1 AS eligible FROM enrolled_devices e JOIN groups g ON g.group_id = e.group_id\n\tWHERE e.group_id = ? AND e.device_id = ? AND e.enabled = 1 AND g.archived_at IS NULL\n\t\tAND e.public_key = ? AND e.fingerprint = ? AND (e.identity_id IS NULL OR e.identity_id = ?)\n\t\t${AUTH_CONTROLLER_SNAPSHOT_GUARD}\n\t\t${AUTH_CONTROLLER_AUTHORITY_GUARD}`;\n\n/** Named builder keeps ordinary exported SQL unchanged and usable without connection tables. */\nexport function authControllerReviewSql(\n\tbase: string,\n\tinput: CoordinatorAuthControllerReviewInput,\n): string {\n\tif (!input.verifiedSnapshot?.accountOwnerTarget) return base;\n\tconst { subject, statement } = ownerReviewStages(base);\n\treturn `${AUTH_CONTROLLER_SNAPSHOT_CTE}, ${AUTH_CONTROLLER_OWNER_CTE},\n\t\tcontroller_review_subject AS MATERIALIZED (${subject})\n\t\t${statement} ${AUTH_CONTROLLER_OWNER_GUARD}`;\n}\n\n/** Internal explicit-resolution path only. The collector must first prove the\n * current label weak; snapshot and authority guards still pin that exact label.\n * Ordinary creation, retries and mutation readers retain their original SQL.\n */\nexport function authControllerOwnerResolutionSql(\n\tmode: \"create\" | \"eligible\",\n\tinput: CoordinatorAuthControllerReviewInput,\n): string {\n\tconst stages = authControllerOwnerResolutionStages(mode, input);\n\treturn `${stages.ctes} ${stages.statement}`;\n}\n\n/** Keep eligibility proof roots flat when composing a checked batch assertion. */\nexport function authControllerOwnerResolutionStages(\n\tmode: \"create\" | \"eligible\",\n\tinput: CoordinatorAuthControllerReviewInput,\n): { ctes: string; statement: string } {\n\tif (!input.verifiedSnapshot?.accountOwnerTarget)\n\t\tthrow new Error(\"account_owner_authority_unavailable\");\n\tconst base = mode === \"create\" ? AUTH_CONTROLLER_INSERT_SQL : AUTH_CONTROLLER_RETRY_ELIGIBLE_SQL;\n\tconst stages = ownerReviewStages(base);\n\tconst subject = stages.subject.replace(\n\t\t\"(e.identity_id IS NULL OR e.identity_id = ?)\",\n\t\t\"(e.identity_id IS NULL OR e.identity_id = ? OR e.identity_id IS json_extract((SELECT value FROM snapshot), '$.enrollmentIdentityId'))\",\n\t);\n\treturn {\n\t\tctes: `${AUTH_CONTROLLER_SNAPSHOT_CTE}, ${AUTH_CONTROLLER_OWNER_CTE},\n\t\t\tcontroller_review_subject AS MATERIALIZED (${subject})`,\n\t\tstatement: `${stages.statement} ${AUTH_CONTROLLER_OWNER_GUARD}`,\n\t};\n}\n\n/** These are three trusted templates, not arbitrary caller SQL. Keep both deep\n * evidence trees in separate root stages so D1 never combines their depth.\n */\nfunction ownerReviewStages(base: string): { subject: string; statement: string } {\n\tif (base === AUTH_CONTROLLER_INSERT_SQL) {\n\t\tconst insertAt = base.indexOf(\"INSERT INTO coordinator_auth_controller_attestations\");\n\t\tconst sourceAt = base.indexOf(\n\t\t\t\"FROM enrolled_devices e JOIN groups g ON g.group_id = e.group_id\",\n\t\t\tinsertAt,\n\t\t);\n\t\treturn {\n\t\t\tsubject: `SELECT e.* ${base.slice(sourceAt)}`,\n\t\t\tstatement: `${base.slice(insertAt, sourceAt)} FROM controller_review_subject e WHERE 1`,\n\t\t};\n\t}\n\tif (base === AUTH_CONTROLLER_RETRY_ELIGIBLE_SQL) {\n\t\tconst selectAt = base.indexOf(\"SELECT 1 AS eligible FROM enrolled_devices e\");\n\t\treturn {\n\t\t\tsubject: base.slice(selectAt).replace(\"SELECT 1 AS eligible\", \"SELECT e.*\"),\n\t\t\tstatement: \"SELECT 1 AS eligible FROM controller_review_subject e WHERE 1\",\n\t\t};\n\t}\n\tif (base === AUTH_CONTROLLER_RETRY_ACTIVE_SQL) {\n\t\tconst selectAt = base.indexOf(\"SELECT a.* FROM coordinator_auth_controller_attestations a\");\n\t\treturn {\n\t\t\tsubject: base.slice(selectAt),\n\t\t\tstatement: \"SELECT e.* FROM controller_review_subject e WHERE 1\",\n\t\t};\n\t}\n\tthrow new Error(\"account_owner_statement_invalid\");\n}\n\nfunction ownerGuardValues(\n\tinput: CoordinatorAuthControllerReviewInput,\n\tauthority: (string | null)[],\n): (string | null)[] {\n\tif (!input.verifiedSnapshot?.accountOwnerTarget) return [];\n\tconst keyId = authority[authority.length - 1];\n\tif (typeof keyId !== \"string\" || keyId.length === 0)\n\t\tthrow new Error(\"account_owner_authority_unavailable\");\n\treturn [keyId];\n}\n\nexport function authControllerRetryEligibleValues(\n\tinput: CoordinatorAuthControllerReviewInput,\n\tauthority: (string | null)[],\n): (string | null)[] {\n\treturn [\n\t\t...authControllerSnapshotValues(input),\n\t\tinput.groupId,\n\t\tinput.deviceId,\n\t\tinput.publicKey,\n\t\tinput.fingerprint,\n\t\tinput.identityId,\n\t\t...authority,\n\t\t...ownerGuardValues(input, authority),\n\t];\n}\n\nexport function authControllerInsertValues(\n\tinput: CoordinatorAuthControllerReviewInput,\n\tcreatedAt: string,\n\tauthority: (string | null)[],\n): (string | null)[] {\n\tconst snapshot = authControllerSnapshotValues(input);\n\tconst metadata = [\n\t\tinput.attestationId,\n\t\tinput.coordinatorId,\n\t\tinput.identityId,\n\t\tinput.reviewReceiptId,\n\t\tinput.evidenceDigest,\n\t\tcreatedAt,\n\t];\n\tconst enrollmentAndAuthority = [\n\t\tinput.groupId,\n\t\tinput.deviceId,\n\t\tinput.publicKey,\n\t\tinput.fingerprint,\n\t\tinput.identityId,\n\t\t...authority,\n\t];\n\tif (input.verifiedSnapshot?.accountOwnerTarget)\n\t\treturn [\n\t\t\t...snapshot,\n\t\t\t...enrollmentAndAuthority,\n\t\t\t...metadata,\n\t\t\t...ownerGuardValues(input, authority),\n\t\t];\n\treturn [...snapshot, ...metadata, ...enrollmentAndAuthority];\n}\n\nconst AUTH_CONTROLLER_CURRENT_SQL = `\n\tSELECT a.* FROM coordinator_auth_controller_attestations a\n\tJOIN enrolled_devices e ON e.group_id = a.group_id AND e.device_id = a.device_id\n\tJOIN groups g ON g.group_id = a.group_id\n\tWHERE a.coordinator_id = ? AND a.attestation_id = ? AND a.revoked_at IS NULL\n\t\tAND e.enabled = 1 AND g.archived_at IS NULL AND e.public_key = a.public_key\n\t\tAND e.fingerprint = a.fingerprint\n\t\tAND (e.identity_id IS NULL OR e.identity_id = a.identity_id)`;\n\nexport const AUTH_CONTROLLER_CURRENT_ENROLLMENT_SQL = AUTH_CONTROLLER_CURRENT_SQL.replace(\n\t\"SELECT a.*\",\n\t\"SELECT e.*\",\n);\n\nexport const AUTH_CONTROLLER_ACTIVE_SQL = `\n\t${AUTH_CONTROLLER_CURRENT_SQL} ${AUTH_CONTROLLER_AUTHORITY_GUARD}`;\n\n/** D1 retries must return the row checked against live authority in this statement. */\nexport const AUTH_CONTROLLER_RETRY_ACTIVE_SQL = `\n\t${AUTH_CONTROLLER_SNAPSHOT_CTE}\n\t${AUTH_CONTROLLER_ACTIVE_SQL}\n\t${AUTH_CONTROLLER_SNAPSHOT_GUARD}`;\n\nexport function authControllerRetryActiveValues(\n\tinput: CoordinatorAuthControllerReviewInput,\n\tauthority: (string | null)[],\n): (string | null)[] {\n\treturn [\n\t\t...authControllerSnapshotValues(input),\n\t\tinput.coordinatorId,\n\t\tinput.attestationId,\n\t\t...authority,\n\t\t...ownerGuardValues(input, authority),\n\t];\n}\n\nexport const AUTH_CONTROLLER_CONFLICT_SQL = `\n\tSELECT * FROM coordinator_auth_controller_attestations\n\tWHERE coordinator_id = ? AND (attestation_id = ? OR review_receipt_id = ?\n\t\tOR (group_id = ? AND device_id = ? AND fingerprint = ?))\n\tORDER BY CASE WHEN attestation_id = ? THEN 0 ELSE 1 END LIMIT 1`;\n\nexport function authControllerConflictValues(\n\tinput: CoordinatorAuthControllerReviewInput,\n): string[] {\n\treturn [\n\t\tinput.coordinatorId,\n\t\tinput.attestationId,\n\t\tinput.reviewReceiptId,\n\t\tinput.groupId,\n\t\tinput.deviceId,\n\t\tinput.fingerprint,\n\t\tinput.attestationId,\n\t];\n}\n\nexport const AUTH_CONTROLLER_REVOKE_SQL = `\n\tUPDATE coordinator_auth_controller_attestations SET revoked_at = COALESCE(revoked_at, ?)\n\tWHERE coordinator_id = ? AND attestation_id = ?`;\n","/** Standalone auth pages mirror the Viewer's tokens without loading remote assets.\n * Keep these palette values aligned with ui/static/{tokens,themes}.css.\n * Separate origins cannot read the Viewer's saved theme; use the OS preference.\n */\nexport const COORDINATOR_AUTH_STYLE = `\n:root{color-scheme:dark;--surface-0:#0b1016;--surface-1:#0f1720;--surface-2:#111c27;--text-primary:#e7f0f7;--text-secondary:#b7c5d3;--accent:#7ef0c2;--accent-hover:#9eff87;--border:rgba(126,240,194,.12);--border-strong:rgba(126,240,194,.28);--font-sans:\"Geist\",system-ui,-apple-system,sans-serif;--font-mono:\"JetBrains Mono\",ui-monospace,monospace;font-family:var(--font-sans);color:var(--text-primary);background:var(--surface-0)}\n*{box-sizing:border-box}body{margin:0;padding:clamp(1rem,5vw,4rem) 1rem;line-height:1.6}main{max-width:34rem;margin:0 auto;padding:clamp(1.25rem,4vw,2rem);border:1px solid var(--border-strong);border-radius:20px;background:var(--surface-1)}\n.brand{display:flex;align-items:center;gap:.6rem;margin:0 0 1.5rem;color:var(--accent);font-size:.875rem;font-weight:700;letter-spacing:.02em}.brand::before{content:\"\";width:.65rem;height:.65rem;border-radius:3px;background:var(--accent)}\nh1,h2{font-family:inherit;font-weight:600;line-height:1.25;letter-spacing:-.025em}h1{font-size:1.6rem;margin:0 0 1rem}h2{font-size:1.05rem;margin:0 0 .5rem}p{margin:.5rem 0}section{padding:1.25rem 0;border-bottom:1px solid var(--border)}.eyebrow{font-size:.75rem;letter-spacing:.08em;text-transform:uppercase;color:var(--text-secondary)}\n.profile{display:flex;align-items:center;gap:1rem}.profile-text{min-width:0;overflow-wrap:anywhere}.avatar{position:relative;display:inline-flex;align-items:center;justify-content:center;flex:0 0 3rem;width:3rem;height:3rem;border-radius:50%;background:var(--surface-2);color:var(--accent);overflow:hidden}.initials{font-weight:700}.avatar img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}.note{font-size:.875rem;color:var(--text-secondary)}\ndl{margin:0}dt{font-size:.8rem;font-weight:600;color:var(--text-secondary);margin-top:1rem}dd{margin:.25rem 0 0}code{font-family:var(--font-mono);font-size:.8rem;overflow-wrap:anywhere;white-space:pre-wrap}code.command{white-space:nowrap;overflow-wrap:normal}\nlabel{display:block;font-weight:600;margin:1rem 0 .35rem}input[type=text]{font:inherit;font-family:var(--font-mono);font-size:1.1rem;letter-spacing:.12em;text-transform:uppercase;width:100%;min-height:44px;padding:.6rem .8rem;border:1px solid var(--border-strong);border-radius:10px;background:var(--surface-2);color:var(--text-primary)}\n.actions{display:flex;flex-wrap:wrap;gap:.75rem;margin:1.5rem 0 0}form{margin:0}button,.link{font:inherit;font-size:.875rem;font-weight:600;display:inline-flex;align-items:center;justify-content:center;min-height:44px;padding:.65rem 1rem;border:1px solid var(--border-strong);border-radius:10px;background:var(--accent);color:var(--surface-0);cursor:pointer;text-decoration:none}button.secondary{background:transparent;color:var(--accent)}a{color:var(--accent)}button:hover,.link:hover{background:var(--accent-hover);color:var(--surface-0)}:focus-visible{outline:3px solid var(--accent);outline-offset:4px}\n@media(prefers-color-scheme:light){:root{color-scheme:light;--surface-0:#f7faf8;--surface-1:#fff;--surface-2:#eef5f1;--text-primary:#0b1016;--text-secondary:#3f4d5c;--accent:#0f8a68;--accent-hover:#0a6f53;--border:rgba(15,138,104,.16);--border-strong:rgba(15,138,104,.3)}button,.link,button:hover,.link:hover{color:#fff}button.secondary{color:var(--accent)}button.secondary:hover{color:#fff}}\n@media(max-width:30rem){body{padding:1rem}.actions{flex-direction:column}.actions form,.actions button,.actions .link{width:100%}h1{font-size:1.4rem}}\n`;\n","const CANONICAL_PROOF = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;\n\nexport function encodeCoordinatorAuthProof32(bytes: Uint8Array): string {\n\tif (!(bytes instanceof Uint8Array) || bytes.byteLength !== 32) {\n\t\tthrow new Error(\"auth_proof_invalid_input\");\n\t}\n\treturn btoa(String.fromCharCode(...bytes))\n\t\t.replaceAll(\"+\", \"-\")\n\t\t.replaceAll(\"/\", \"_\")\n\t\t.replace(/=+$/, \"\");\n}\n\nexport function decodeCoordinatorAuthProof32(value: unknown): Uint8Array<ArrayBuffer> | null {\n\tif (typeof value !== \"string\" || value.length !== 43 || !CANONICAL_PROOF.test(value)) {\n\t\treturn null;\n\t}\n\ttry {\n\t\tconst binary = atob(`${value.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\")}=`);\n\t\tconst bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));\n\t\tif (bytes.length !== 32 || encodeCoordinatorAuthProof32(bytes) !== value) return null;\n\t\treturn bytes;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport async function hashCoordinatorAuthProofBytes32(bytes: Uint8Array): Promise<string> {\n\tif (!(bytes instanceof Uint8Array) || bytes.byteLength !== 32) {\n\t\tthrow new Error(\"auth_proof_invalid_input\");\n\t}\n\t// Own the input before the digest yields, including callers with shared memory.\n\tconst owned = new Uint8Array(bytes);\n\ttry {\n\t\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", owned);\n\t\treturn Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\n\t\t\t\"\",\n\t\t);\n\t} catch {\n\t\tthrow new Error(\"auth_proof_crypto_failed\");\n\t}\n}\n","/** Management-attempt schema installed by the explicit account-schema migration. */\nconst table = \"coordinator_account_change_attempts\";\nexport const BROWSER_ACCOUNT_ARCHIVE_GUARD = `CREATE TRIGGER account_change_archive_receipt BEFORE INSERT ON coordinator_auth_account_connection_history\nWHEN NOT EXISTS (SELECT 1 FROM ${table} a WHERE a.coordinator_id = NEW.coordinator_id\n AND a.attempt_id = NEW.end_attempt_id AND a.state = 'committing' AND a.intent = 'disconnect'\n AND a.target_link_id = NEW.link_id AND a.identity_id = NEW.identity_id AND a.issuer = NEW.issuer AND a.target_subject = NEW.subject)\nBEGIN SELECT RAISE(ABORT,'account_change_archive_receipt_invalid'); END`;\nexport const ACCOUNT_CHANGE_SCHEMA_STATEMENTS = [\n\t`CREATE TABLE ${table} (\n coordinator_id TEXT NOT NULL, attempt_id TEXT NOT NULL,\n intent TEXT NOT NULL CHECK(intent IN ('refresh','disconnect')),\n target_link_id TEXT NOT NULL, identity_id TEXT NOT NULL, issuer TEXT NOT NULL, target_subject TEXT NOT NULL,\n group_id TEXT NOT NULL, device_id TEXT NOT NULL, public_key TEXT NOT NULL, fingerprint TEXT NOT NULL,\n key_id TEXT NOT NULL, enrollment_identity_id TEXT, auth_config_revision TEXT NOT NULL,\n runtime_verifier_hash TEXT NOT NULL, browser_start_hash TEXT NOT NULL, loopback_redirect TEXT NOT NULL,\n state TEXT NOT NULL CHECK(state IN ('pending','browser_pending','consumed','verified','confirmed','committing','completed','cancelled','failed','expired')),\n failure_reason TEXT CHECK(failure_reason IN ('device_cancelled','provider_failure','expired')),\n state_hash TEXT, binder_hash TEXT, nonce TEXT, pkce_verifier TEXT, browser_order INTEGER,\n completion_secret_hash TEXT, display_name TEXT, email TEXT, email_verified INTEGER, picture_url TEXT,\n created_at_ms INTEGER NOT NULL, expires_at_ms INTEGER NOT NULL,\n consumed_at_ms INTEGER, verified_at_ms INTEGER, confirmed_at_ms INTEGER, completed_at_ms INTEGER,\n PRIMARY KEY(coordinator_id,attempt_id), UNIQUE(coordinator_id,browser_start_hash),\n UNIQUE(coordinator_id,runtime_verifier_hash), UNIQUE(coordinator_id,state_hash),\n UNIQUE(coordinator_id,binder_hash), UNIQUE(coordinator_id,completion_secret_hash),\n CHECK(typeof(created_at_ms) = 'integer' AND created_at_ms BETWEEN 0 AND 9007199254140991 AND expires_at_ms = created_at_ms + 600000),\n CHECK(browser_order IS NULL OR (typeof(browser_order) = 'integer' AND browser_order BETWEEN 1 AND 9007199254740991)),\n CHECK((state = 'completed') = (completed_at_ms IS NOT NULL)),\n CHECK((state = 'failed' AND failure_reason IS 'provider_failure') OR (state = 'expired' AND failure_reason IS 'expired') OR (state = 'cancelled' AND failure_reason IS 'device_cancelled') OR (state NOT IN ('failed','expired','cancelled') AND failure_reason IS NULL)),\n CHECK(state <> 'pending' OR (state_hash IS NULL AND binder_hash IS NULL AND browser_order IS NULL)),\n CHECK(state <> 'browser_pending' OR (state_hash IS NOT NULL AND binder_hash IS NOT NULL AND nonce IS NOT NULL AND pkce_verifier IS NOT NULL AND browser_order IS NOT NULL)),\n CHECK(state IN ('pending','browser_pending') OR (nonce IS NULL AND pkce_verifier IS NULL)),\n CHECK(state NOT IN ('consumed','verified','confirmed','committing','completed') OR (consumed_at_ms IS NOT NULL AND consumed_at_ms >= created_at_ms AND consumed_at_ms < expires_at_ms)),\n CHECK(state NOT IN ('verified','confirmed','committing','completed') OR (verified_at_ms IS NOT NULL AND verified_at_ms >= consumed_at_ms AND verified_at_ms < expires_at_ms)),\n CHECK(state NOT IN ('confirmed','committing','completed') OR (completion_secret_hash IS NOT NULL AND confirmed_at_ms IS NOT NULL AND confirmed_at_ms >= verified_at_ms AND confirmed_at_ms < expires_at_ms)),\n CHECK(state <> 'completed' OR (completed_at_ms >= confirmed_at_ms AND completed_at_ms < expires_at_ms AND display_name IS NULL AND email IS NULL AND email_verified IS NULL AND picture_url IS NULL)),\n CHECK(email_verified IS NULL OR (email_verified IN (0,1) AND email IS NOT NULL))\n)`,\n\t`CREATE TRIGGER account_change_collision BEFORE INSERT ON ${table}\nWHEN EXISTS (SELECT 1 FROM ${table} WHERE coordinator_id = NEW.coordinator_id AND\n (attempt_id = NEW.attempt_id OR browser_start_hash = NEW.browser_start_hash OR runtime_verifier_hash = NEW.runtime_verifier_hash OR state_hash = NEW.state_hash OR binder_hash = NEW.binder_hash OR completion_secret_hash = NEW.completion_secret_hash))\nBEGIN SELECT RAISE(ABORT,'account_change_collision'); END`,\n\t`CREATE TRIGGER account_change_birth BEFORE UPDATE ON ${table}\nWHEN ${[\"coordinator_id\", \"attempt_id\", \"intent\", \"target_link_id\", \"identity_id\", \"issuer\", \"target_subject\", \"group_id\", \"device_id\", \"public_key\", \"fingerprint\", \"key_id\", \"enrollment_identity_id\", \"auth_config_revision\", \"runtime_verifier_hash\", \"browser_start_hash\", \"loopback_redirect\", \"created_at_ms\", \"expires_at_ms\"].map((c) => `NEW.${c} IS NOT OLD.${c}`).join(\" OR \")}\nBEGIN SELECT RAISE(ABORT,'account_change_birth_immutable'); END`,\n\t`CREATE TRIGGER account_change_transition BEFORE UPDATE ON ${table}\nWHEN OLD.state IN ('completed','cancelled','failed','expired') OR NOT (\n (OLD.state = 'pending' AND NEW.state = 'browser_pending') OR\n (OLD.state = 'browser_pending' AND NEW.state = 'consumed') OR\n (OLD.state = 'consumed' AND ((OLD.intent = 'refresh' AND NEW.state = 'confirmed') OR (OLD.intent = 'disconnect' AND NEW.state = 'verified'))) OR\n (OLD.state = 'verified' AND NEW.state = 'confirmed') OR\n (OLD.state = 'confirmed' AND NEW.state = 'committing') OR\n (OLD.state = 'committing' AND NEW.state = 'completed') OR\n (OLD.state NOT IN ('committing','completed','cancelled','failed','expired') AND NEW.state IN ('cancelled','expired')) OR\n (OLD.state = 'consumed' AND NEW.state = 'failed'))\nBEGIN SELECT RAISE(ABORT,'account_change_transition_invalid'); END`,\n\t`CREATE TRIGGER account_change_receipt_delete BEFORE DELETE ON ${table} WHEN OLD.state = 'completed'\nBEGIN SELECT RAISE(ABORT,'account_change_receipt_immutable'); END`,\n\tBROWSER_ACCOUNT_ARCHIVE_GUARD,\n\t// EXPLAIN in the focused tests checks that the repeated revocation barrier\n\t// changes from a coordinator-prefix scan to an Identity-specific covering lookup.\n\t`CREATE INDEX account_connection_history_identity_revoked ON coordinator_auth_account_connection_history(coordinator_id,identity_id,revoked_at_ms)`,\n\t`ALTER TABLE coordinator_auth_link_profiles ADD COLUMN source_change_attempt_id TEXT`,\n\t`ALTER TABLE coordinator_auth_link_profiles ADD COLUMN source_order INTEGER`,\n\t`ALTER TABLE coordinator_auth_account_profiles ADD COLUMN source_order INTEGER`,\n] as const;\n","/** Device authorization receipts contain no browser or provider proof claims. */\nexport const ACCOUNT_UNLINK_TABLE = \"coordinator_auth_account_connection_unlinks\";\nconst table = ACCOUNT_UNLINK_TABLE;\nconst birth = [\n\t\"coordinator_id\",\n\t\"attempt_id\",\n\t\"target_link_id\",\n\t\"identity_id\",\n\t\"issuer\",\n\t\"target_subject\",\n\t\"group_id\",\n\t\"device_id\",\n\t\"public_key\",\n\t\"fingerprint\",\n\t\"enrollment_identity_id\",\n\t\"auth_config_revision\",\n\t\"request_hash\",\n\t\"created_at_ms\",\n];\nexport const ACCOUNT_UNLINK_SCHEMA_STATEMENTS = [\n\t`CREATE TABLE ${table} (\n coordinator_id TEXT NOT NULL, attempt_id TEXT NOT NULL, target_link_id TEXT NOT NULL,\n identity_id TEXT NOT NULL, issuer TEXT NOT NULL, target_subject TEXT NOT NULL,\n group_id TEXT NOT NULL, device_id TEXT NOT NULL, public_key TEXT NOT NULL, fingerprint TEXT NOT NULL,\n enrollment_identity_id TEXT, auth_config_revision TEXT NOT NULL,\n request_hash TEXT NOT NULL CHECK(length(request_hash)=64 AND request_hash NOT GLOB '*[^0-9a-f]*'),\n state TEXT NOT NULL CHECK(state IN ('committing','completed')),\n created_at_ms INTEGER NOT NULL CHECK(typeof(created_at_ms)='integer' AND created_at_ms BETWEEN 0 AND 9007199254740991),\n completed_at_ms INTEGER,\n PRIMARY KEY(coordinator_id,attempt_id), UNIQUE(coordinator_id,target_link_id),\n CHECK((state='completed')=(completed_at_ms IS NOT NULL)),\n CHECK(completed_at_ms IS NULL OR (typeof(completed_at_ms)='integer' AND completed_at_ms>=created_at_ms AND completed_at_ms<=9007199254740991))\n )`,\n\t`CREATE TRIGGER account_connection_unlink_insert BEFORE INSERT ON ${table}\n WHEN NEW.state<>'committing' OR EXISTS (SELECT 1 FROM ${table} WHERE rowid=NEW.rowid OR (coordinator_id=NEW.coordinator_id AND (attempt_id=NEW.attempt_id OR target_link_id=NEW.target_link_id)))\n BEGIN SELECT RAISE(ABORT,'account_unlink_collision'); END`,\n\t`CREATE TRIGGER account_connection_unlink_rowid AFTER INSERT ON ${table} WHEN NEW.rowid<1\n BEGIN SELECT RAISE(ABORT,'account_unlink_rowid'); END`,\n\t`CREATE TRIGGER account_connection_unlink_update BEFORE UPDATE ON ${table}\n WHEN ${birth.map((c) => `NEW.${c} IS NOT OLD.${c}`).join(\" OR \")} OR NEW.rowid IS NOT OLD.rowid OR OLD.state<>'committing' OR NEW.state<>'completed'\n BEGIN SELECT RAISE(ABORT,'account_unlink_immutable'); END`,\n\t`CREATE TRIGGER account_connection_unlink_delete BEFORE DELETE ON ${table}\n BEGIN SELECT RAISE(ABORT,'account_unlink_immutable'); END`,\n] as const;\n\nexport function accountArchiveReceiptGuard(browserGuard: string): string {\n\treturn browserGuard.replace(\n\t\t\"BEGIN SELECT\",\n\t\t` AND NOT EXISTS (SELECT 1 FROM ${table} a WHERE a.coordinator_id=NEW.coordinator_id\n AND a.attempt_id=NEW.end_attempt_id AND a.state='committing' AND a.target_link_id=NEW.link_id\n AND a.identity_id=NEW.identity_id AND a.issuer=NEW.issuer AND a.target_subject=NEW.subject)\nBEGIN SELECT`,\n\t);\n}\n","/**\n * Committed proof only: future finalization must insert it atomically with the\n * winning attempt, account link, and audit row. No request-to-proof writer lives here.\n * References are logical, and revocation retains this immutable proof forever.\n * This leaf schema is not installed automatically when an existing store opens.\n */\nexport const COORDINATOR_AUTH_DEVICE_CLAIM_SCHEMA_STATEMENTS = [\n\t`\nCREATE TABLE IF NOT EXISTS coordinator_auth_device_claims (\n claim_id TEXT PRIMARY KEY NOT NULL CHECK(\n typeof(claim_id) = 'text' AND length(claim_id) BETWEEN 1 AND 256\n AND claim_id = trim(claim_id) AND instr(claim_id, char(0)) = 0),\n coordinator_id TEXT NOT NULL CHECK(\n typeof(coordinator_id) = 'text' AND length(coordinator_id) BETWEEN 1 AND 256\n AND coordinator_id = trim(coordinator_id) AND instr(coordinator_id, char(0)) = 0),\n identity_id TEXT NOT NULL CHECK(\n typeof(identity_id) = 'text' AND length(identity_id) BETWEEN 1 AND 256\n AND identity_id = trim(identity_id) AND instr(identity_id, char(0)) = 0),\n group_id TEXT NOT NULL CHECK(\n typeof(group_id) = 'text' AND length(group_id) BETWEEN 1 AND 256\n AND group_id = trim(group_id) AND instr(group_id, char(0)) = 0),\n device_id TEXT NOT NULL CHECK(\n typeof(device_id) = 'text' AND length(device_id) BETWEEN 1 AND 256\n AND device_id = trim(device_id) AND instr(device_id, char(0)) = 0),\n public_key TEXT NOT NULL CHECK(\n typeof(public_key) = 'text' AND length(public_key) BETWEEN 1 AND 4096\n AND length(trim(replace(replace(public_key, char(13), ''), char(10), ''))) > 0\n AND instr(public_key, char(0)) = 0),\n fingerprint TEXT NOT NULL CHECK(\n typeof(fingerprint) = 'text' AND length(fingerprint) = 64\n AND fingerprint NOT GLOB '*[^a-f0-9]*' AND instr(fingerprint, char(0)) = 0),\n key_id TEXT NOT NULL CHECK(\n typeof(key_id) = 'text' AND length(key_id) = 64\n AND key_id NOT GLOB '*[^a-f0-9]*' AND instr(key_id, char(0)) = 0),\n attempt_id TEXT NOT NULL CHECK(\n typeof(attempt_id) = 'text' AND length(attempt_id) BETWEEN 1 AND 256\n AND attempt_id = trim(attempt_id) AND instr(attempt_id, char(0)) = 0),\n issuer TEXT NOT NULL CHECK(\n typeof(issuer) = 'text' AND length(trim(issuer)) > 0\n AND issuer = trim(issuer) AND instr(issuer, char(0)) = 0),\n auth_config_revision TEXT NOT NULL CHECK(\n typeof(auth_config_revision) = 'text' AND length(auth_config_revision) = 64\n AND auth_config_revision NOT GLOB '*[^a-f0-9]*' AND instr(auth_config_revision, char(0)) = 0),\n created_at_ms INTEGER NOT NULL CHECK(\n typeof(created_at_ms) = 'integer' AND created_at_ms BETWEEN 0 AND 9007199254740991),\n UNIQUE (coordinator_id, identity_id),\n UNIQUE (coordinator_id, device_id),\n UNIQUE (coordinator_id, key_id),\n UNIQUE (coordinator_id, attempt_id)\n) WITHOUT ROWID;\n`,\n\t`\n-- REPLACE's implicit deletes may skip DELETE triggers when recursive triggers are off.\n-- Check every unique identifier before conflict handling, including UPSERT DO NOTHING.\nCREATE TRIGGER IF NOT EXISTS coordinator_auth_device_claims_insert_collision\nBEFORE INSERT ON coordinator_auth_device_claims\nWHEN EXISTS (\n SELECT 1 FROM coordinator_auth_device_claims\n WHERE claim_id = NEW.claim_id OR (coordinator_id = NEW.coordinator_id AND (\n identity_id = NEW.identity_id OR device_id = NEW.device_id\n OR key_id = NEW.key_id OR attempt_id = NEW.attempt_id\n ))\n)\nBEGIN\n SELECT RAISE(ABORT, 'auth_device_claim_collision');\nEND;\n`,\n\t`\nCREATE TRIGGER IF NOT EXISTS coordinator_auth_device_claims_immutable_update\nBEFORE UPDATE ON coordinator_auth_device_claims\nBEGIN\n SELECT RAISE(ABORT, 'auth_device_claim_immutable');\nEND;\n`,\n\t`\nCREATE TRIGGER IF NOT EXISTS coordinator_auth_device_claims_immutable_delete\nBEFORE DELETE ON coordinator_auth_device_claims\nBEGIN\n SELECT RAISE(ABORT, 'auth_device_claim_immutable');\nEND;\n`,\n] as const;\n\nexport const COORDINATOR_AUTH_DEVICE_CLAIM_SCHEMA_SQL =\n\tCOORDINATOR_AUTH_DEVICE_CLAIM_SCHEMA_STATEMENTS.join(\"\\n\");\n\nconst quoteSql = (value: string) => `'${value.replaceAll(\"'\", \"''\")}'`;\nconst proofDefinitions = COORDINATOR_AUTH_DEVICE_CLAIM_SCHEMA_STATEMENTS.map((statement) =>\n\tstatement.replace(/^(?:\\s|--[^\\n]*\\n)*/u, \"\").replace(/;\\s*$/u, \"\"),\n);\n// Frozen DDL only, not a SQL parser. Protect known literals before removing layout;\n// unknown literals retain their quotes and cannot match a protected literal token.\nconst proofLiterals = [...new Set(proofDefinitions.join(\"\\n\").match(/'(?:[^']|'')*'/gu))];\nfunction canonicalProofSql(\n\texpression: string,\n\tliterals: readonly string[] = proofLiterals,\n): string {\n\tlet sql = expression;\n\tfor (const [index, literal] of literals.entries())\n\t\tsql = `replace(${sql}, ${quoteSql(literal)}, 'literal_${index}')`;\n\treturn `rtrim(replace(replace(replace(replace(replace(${sql}, 'IF NOT EXISTS', ''), ' ', ''), char(10), ''), char(13), ''), char(9), ''), char(59))`;\n}\n\n/** Same effective-definition checks for SQLite, D1 readiness and explicit cutover. */\nexport function authSchemaDefinitionCheck(\n\tdefinition: string,\n\toptions: { auxiliaryObjects?: number; literals?: readonly string[] } = {},\n) {\n\tdefinition = definition.replace(/^(?:\\s|--[^\\n]*\\n)*/u, \"\").replace(/;\\s*$/u, \"\");\n\t// Headers of this repository's frozen declarations only, not a DDL parser.\n\tconst header = /^CREATE (TABLE|TRIGGER|(?:UNIQUE )?INDEX)(?: IF NOT EXISTS)? (\\w+)/u.exec(\n\t\tdefinition,\n\t);\n\tif (!header?.[1] || !header[2]) throw new Error(\"auth_device_claim_definition_invalid\");\n\t// Encode the known ASCII DDL so trigger-body semicolons cannot split cutover statements.\n\tconst hex = [...definition]\n\t\t.map((character) => character.charCodeAt(0).toString(16).padStart(2, \"0\"))\n\t\t.join(\"\");\n\tlet auxiliaryCheck = \"\";\n\tif (options.auxiliaryObjects !== undefined)\n\t\tauxiliaryCheck = ` AND (SELECT count(*) FROM sqlite_master WHERE tbl_name = ${quoteSql(header[2])} COLLATE NOCASE AND type IN ('index','trigger') AND sql IS NOT NULL) = ${options.auxiliaryObjects}`;\n\tconst literals = options.literals ?? [...new Set(definition.match(/'(?:[^']|'')*'/gu))];\n\treturn {\n\t\tname: header[2],\n\t\tmatches: `EXISTS (SELECT 1 FROM sqlite_master WHERE type = ${quoteSql(header[1].toLowerCase().replace(\"unique \", \"\"))} AND name = ${quoteSql(header[2])} COLLATE NOCASE AND ${canonicalProofSql(\"sql\", literals)} = ${canonicalProofSql(`CAST(X'${hex}' AS TEXT)`, literals)}${auxiliaryCheck})`,\n\t};\n}\nexport const authDeviceClaimDefinitionChecks = (auxiliaryObjects = 3) =>\n\tproofDefinitions.map((definition, index) =>\n\t\tauthSchemaDefinitionCheck(definition, {\n\t\t\tauxiliaryObjects: index === 0 ? auxiliaryObjects : undefined,\n\t\t\tliterals: proofLiterals,\n\t\t}),\n\t);\nexport const AUTH_DEVICE_CLAIM_DEFINITION_CHECKS = authDeviceClaimDefinitionChecks();\n\n/**\n * Database columns for an already committed proof, not an authorization input.\n * public_key retains exact enrollment bytes (including PEM line endings);\n * key_id is the canonical SHA-256 key ID, not the PEM fingerprint. Both hashes\n * and auth_config_revision use the lowercase 64-hex format of link capture.\n * CHECKs validate storage shape only; finalization must verify all authority.\n */\nexport interface CoordinatorAuthDeviceClaimRow {\n\treadonly claim_id: string;\n\treadonly coordinator_id: string;\n\treadonly identity_id: string;\n\treadonly group_id: string;\n\treadonly device_id: string;\n\treadonly public_key: string;\n\treadonly fingerprint: string;\n\treadonly key_id: string;\n\treadonly attempt_id: string;\n\treadonly issuer: string;\n\treadonly auth_config_revision: string;\n\treadonly created_at_ms: number;\n}\n","export const AUTH_LINK_PURPOSE = \"coordinator-account-link-v1\";\nexport const AUTH_LINK_ATTEMPT_TTL_MS = 600000;\nexport const AUTH_LINK_MAX_ACTIVE_PER_DEVICE = 2;\nexport const AUTH_LINK_MAX_ACTIVE_PER_IDENTITY = 3;\nexport const AUTH_LINK_CREATE_WINDOW_MS = 3600000;\nexport const AUTH_LINK_MAX_CREATES_PER_DEVICE_WINDOW = 6;\nexport const AUTH_LINK_RETENTION_WINDOW_MS = 2592000000;\nexport const AUTH_LINK_MAX_CREATES_PER_DEVICE_RETENTION = 60;\nexport const AUTH_LINK_MAX_UNFINISHED_PER_COORDINATOR = 10000;\nexport const AUTH_LINK_EXPIRE_BATCH_MAX = 32;\n/** Trusted server configuration, never request JSON. */\nexport interface CoordinatorAuthLinkConfig {\n\tcoordinatorId: string;\n\tissuer: string;\n\trevision: string;\n\tenabled: boolean;\n}\n/** Already verified request key possession; SQL rechecks the selected authority source. */\nexport interface CoordinatorAuthLinkSigner {\n\tgroupId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n}\nexport type CoordinatorAuthLinkRequester =\n\t| { kind: \"device\"; signer: CoordinatorAuthLinkSigner }\n\t| { kind: \"browser\"; browserTransactionHash: string };\nexport type CoordinatorAuthLinkState =\n\t| \"pending\"\n\t| \"browser_claimed\"\n\t| \"oidc_verified\"\n\t| \"confirmed\"\n\t| \"finalized\"\n\t| \"session_redeemed\"\n\t| \"expired\"\n\t| \"failed\";\nexport interface CoordinatorAuthLinkStatus {\n\tattemptId: string;\n\tstate: CoordinatorAuthLinkState;\n\texpiresAtMs: number;\n}\nexport type CoordinatorAuthLinkError =\n\t| \"invalid_input\"\n\t| \"controller_not_active\"\n\t| \"attempt_conflict\"\n\t| \"attempt_limited\"\n\t| \"attempt_unavailable\"\n\t| \"attempt_expired\"\n\t| \"auth_config_changed\"\n\t| \"link_conflict\";\nexport interface CoordinatorAuthLinkRejected {\n\tkind: \"rejected\";\n\terror: CoordinatorAuthLinkError;\n}\nexport interface CoordinatorAuthLinkMaintenanceOptions {\n\tlimit?: number;\n}\nexport type CoordinatorAuthLinkMaintenanceResult =\n\t| { kind: \"maintained\"; processedCount: number; more: boolean }\n\t| CoordinatorAuthLinkRejected;\nexport type CoordinatorAuthLinkResult =\n\t| { kind: \"applied\" | \"existing\"; status: CoordinatorAuthLinkStatus }\n\t| CoordinatorAuthLinkRejected;\nexport type CoordinatorAuthLinkCreateResult =\n\t| { kind: \"created\" | \"existing\"; status: CoordinatorAuthLinkStatus; identityId: string }\n\t| CoordinatorAuthLinkRejected;\nexport type CoordinatorAuthLinkOidcResult =\n\t| {\n\t\t\tkind: \"applied\";\n\t\t\tstatus: CoordinatorAuthLinkStatus;\n\t\t\t/**\n\t\t\t * fingerprint names the device key for consent; desktop pages need not render it.\n\t\t\t * headless is present only for headless attempts, from the same row read.\n\t\t\t */\n\t\t\ttarget: {\n\t\t\t\tidentityId: string;\n\t\t\t\tgroupId: string;\n\t\t\t\tdeviceId: string;\n\t\t\t\tfingerprint: string;\n\t\t\t\theadless?: true;\n\t\t\t};\n\t }\n\t| CoordinatorAuthLinkRejected;\nexport interface CoordinatorAuthLinkCreateInput {\n\t/** Trusted server-selected source; device claims pin the current local Identity. */\n\tauthority: { kind: \"controller_attestation\" } | { kind: \"device_claim\"; identityId: string };\n\t/** Public HTTP callers pin their current Identity for either source kind. */\n\texpectedIdentityId?: string;\n\tattemptId: string;\n\tsigner: CoordinatorAuthLinkSigner;\n\truntimeVerifierHash: string;\n\tloopbackRedirect: string;\n\t/** Required for device claims; trusted attested callers may omit it. */\n\tbrowserStartHash?: string;\n}\nexport interface CoordinatorAuthLinkClaimInput {\n\tattemptId: string;\n\tbrowserTransactionHash: string;\n}\nexport interface CoordinatorAuthLinkOidcInput extends CoordinatorAuthLinkClaimInput {\n\taccount: { issuer: string; subject: string };\n\t/** Optional display claims from the same verified callback, never request JSON. */\n\tprofile?: unknown;\n}\nexport interface CoordinatorAuthLinkConfirmInput extends CoordinatorAuthLinkClaimInput {\n\tcompletionSecretHash: string;\n}\nexport interface CoordinatorAuthLinkFinalizeInput {\n\tpurpose: typeof AUTH_LINK_PURPOSE;\n\tcoordinatorId: string;\n\tattemptId: string;\n\tgroupId: string;\n\tidentityId: string;\n\tdeviceId: string;\n\tfingerprint: string;\n\truntimeVerifierHash: string;\n\tcompletionSecretHash: string;\n\tsigner: CoordinatorAuthLinkSigner;\n}\nexport interface CoordinatorAuthLinkFailInput {\n\tattemptId: string;\n\trequester: CoordinatorAuthLinkRequester;\n\treason: \"cancelled\" | \"provider_failure\" | \"config_failure\";\n}\nexport interface CoordinatorAuthLinkStore {\n\tmaintainAuthLinkAttempts(\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t\toptions?: CoordinatorAuthLinkMaintenanceOptions,\n\t): Promise<CoordinatorAuthLinkMaintenanceResult>;\n\tcreateAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkCreateInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkCreateResult>;\n\tclaimAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkClaimInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkResult>;\n\trecordAuthLinkOidcVerified(\n\t\tinput: CoordinatorAuthLinkOidcInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkOidcResult>;\n\tconfirmAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkConfirmInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkResult>;\n\treadAuthLinkCompletionDestination(\n\t\tinput: CoordinatorAuthLinkClaimInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<{ destination: string } | null>;\n\tfinalizeAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkFinalizeInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkResult>;\n\tfailAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkFailInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkResult>;\n\tgetAuthLinkAttemptStatus(\n\t\tattemptId: string,\n\t\trequester: CoordinatorAuthLinkRequester,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkStatus | null>;\n}\nexport interface CoordinatorAuthLinkOptions {\n\tauthClock?: () => number;\n}\n\nexport const AUTH_LINK_BROWSER_START_COLUMN_SQL =\n\t\"browser_start_hash TEXT CHECK (browser_start_hash IS NULL OR (length(browser_start_hash) = 64 AND browser_start_hash NOT GLOB '*[^0-9a-f]*'))\";\nexport const AUTH_LINK_BROWSER_START_INDEX_SQL = `CREATE UNIQUE INDEX IF NOT EXISTS idx_auth_link_attempts_browser_start\n ON coordinator_auth_link_attempts(coordinator_id, browser_start_hash);`;\n\nexport const AUTH_LINK_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS coordinator_auth_link_attempts (\n coordinator_id TEXT NOT NULL,\n attempt_id TEXT NOT NULL,\n identity_id TEXT NOT NULL,\n group_id TEXT NOT NULL,\n device_id TEXT NOT NULL,\n public_key TEXT NOT NULL,\n fingerprint TEXT NOT NULL CHECK (length(fingerprint) = 64 AND fingerprint NOT GLOB '*[^0-9a-f]*'),\n controller_attestation_id TEXT,\n controller_review_receipt_id TEXT,\n controller_revision INTEGER,\n issuer TEXT NOT NULL,\n auth_config_revision TEXT NOT NULL CHECK (length(auth_config_revision) = 64 AND auth_config_revision NOT GLOB '*[^0-9a-f]*'),\n runtime_verifier_hash TEXT NOT NULL CHECK (length(runtime_verifier_hash) = 64 AND runtime_verifier_hash NOT GLOB '*[^0-9a-f]*'),\n loopback_redirect TEXT NOT NULL,\n state TEXT NOT NULL CHECK (state IN ('pending','browser_claimed','oidc_verified','confirmed','finalized','session_redeemed','expired','failed')),\n browser_transaction_hash TEXT CHECK (browser_transaction_hash IS NULL OR (length(browser_transaction_hash) = 64 AND browser_transaction_hash NOT GLOB '*[^0-9a-f]*')),\n account_subject TEXT CHECK (account_subject IS NULL OR length(account_subject) BETWEEN 1 AND 255),\n completion_secret_hash TEXT CHECK (completion_secret_hash IS NULL OR (length(completion_secret_hash) = 64 AND completion_secret_hash NOT GLOB '*[^0-9a-f]*')),\n link_id TEXT,\n failure_reason TEXT CHECK (failure_reason IS NULL OR failure_reason IN ('device_cancelled','browser_cancelled','provider_failure','config_failure')),\n created_at_ms INTEGER NOT NULL CHECK (typeof(created_at_ms) = 'integer' AND created_at_ms >= 0 AND created_at_ms <= 9007199254140991),\n expires_at_ms INTEGER NOT NULL CHECK (typeof(expires_at_ms) = 'integer' AND expires_at_ms = created_at_ms + 600000),\n claimed_at_ms INTEGER,\n oidc_verified_at_ms INTEGER,\n confirmed_at_ms INTEGER,\n finalized_at_ms INTEGER,\n failed_at_ms INTEGER,\n ${AUTH_LINK_BROWSER_START_COLUMN_SQL},\n authority_kind TEXT NOT NULL CHECK (authority_kind IN ('controller_attestation','device_claim')),\n PRIMARY KEY (coordinator_id, attempt_id),\n UNIQUE (coordinator_id, runtime_verifier_hash),\n UNIQUE (coordinator_id, browser_transaction_hash),\n UNIQUE (coordinator_id, completion_secret_hash),\n UNIQUE (coordinator_id, link_id),\n CHECK (state <> 'pending' OR (browser_transaction_hash IS NULL AND account_subject IS NULL AND completion_secret_hash IS NULL AND link_id IS NULL)),\n CHECK (state NOT IN ('browser_claimed','oidc_verified','confirmed','finalized','session_redeemed') OR browser_transaction_hash IS NOT NULL),\n CHECK (state NOT IN ('oidc_verified','confirmed','finalized','session_redeemed') OR account_subject IS NOT NULL),\n CHECK (state NOT IN ('confirmed','finalized','session_redeemed') OR completion_secret_hash IS NOT NULL),\n CHECK ((state IN ('finalized','session_redeemed') AND link_id IS NOT NULL AND finalized_at_ms IS NOT NULL) OR (state NOT IN ('finalized','session_redeemed') AND link_id IS NULL AND finalized_at_ms IS NULL)),\n CHECK ((state = 'failed' AND failure_reason IS NOT NULL AND failed_at_ms IS NOT NULL) OR (state <> 'failed' AND failure_reason IS NULL AND failed_at_ms IS NULL)),\n CHECK ((authority_kind = 'controller_attestation'\n AND (controller_attestation_id IS NOT NULL AND typeof(controller_attestation_id) = 'text' AND length(controller_attestation_id) BETWEEN 1 AND 256 AND controller_attestation_id = trim(controller_attestation_id) AND instr(controller_attestation_id, char(0)) = 0)\n AND (controller_review_receipt_id IS NOT NULL AND typeof(controller_review_receipt_id) = 'text' AND length(controller_review_receipt_id) BETWEEN 1 AND 256 AND controller_review_receipt_id = trim(controller_review_receipt_id) AND instr(controller_review_receipt_id, char(0)) = 0)\n AND controller_revision IS NOT NULL AND typeof(controller_revision) = 'integer' AND controller_revision = 1)\n OR (authority_kind = 'device_claim' AND controller_attestation_id IS NULL AND controller_review_receipt_id IS NULL AND controller_revision IS NULL))\n);\nCREATE TABLE IF NOT EXISTS coordinator_auth_account_links (\n coordinator_id TEXT NOT NULL,\n link_id TEXT NOT NULL,\n issuer TEXT NOT NULL,\n subject TEXT NOT NULL CHECK (length(subject) BETWEEN 1 AND 255),\n identity_id TEXT NOT NULL,\n attempt_id TEXT NOT NULL,\n controller_attestation_id TEXT,\n auth_config_revision TEXT NOT NULL CHECK (length(auth_config_revision) = 64 AND auth_config_revision NOT GLOB '*[^0-9a-f]*'),\n created_at_ms INTEGER NOT NULL,\n revoked_at_ms INTEGER,\n authority_kind TEXT NOT NULL CHECK (authority_kind IN ('controller_attestation','device_claim')),\n device_claim_id TEXT,\n PRIMARY KEY (coordinator_id, link_id),\n UNIQUE (coordinator_id, issuer, subject),\n UNIQUE (coordinator_id, identity_id),\n UNIQUE (coordinator_id, attempt_id),\n UNIQUE (device_claim_id),\n CHECK ((authority_kind = 'controller_attestation'\n AND (controller_attestation_id IS NOT NULL AND typeof(controller_attestation_id) = 'text' AND length(controller_attestation_id) BETWEEN 1 AND 256 AND controller_attestation_id = trim(controller_attestation_id) AND instr(controller_attestation_id, char(0)) = 0) AND device_claim_id IS NULL)\n OR (authority_kind = 'device_claim' AND controller_attestation_id IS NULL\n AND (device_claim_id IS NOT NULL AND typeof(device_claim_id) = 'text' AND length(device_claim_id) BETWEEN 1 AND 256 AND device_claim_id = trim(device_claim_id) AND instr(device_claim_id, char(0)) = 0)))\n);\nCREATE TABLE IF NOT EXISTS coordinator_auth_link_audit_log (\n coordinator_id TEXT NOT NULL,\n link_id TEXT NOT NULL,\n action TEXT NOT NULL CHECK (action IN ('link_created','link_revoked')),\n attempt_id TEXT NOT NULL,\n identity_id TEXT NOT NULL,\n group_id TEXT NOT NULL,\n device_id TEXT NOT NULL,\n fingerprint TEXT NOT NULL CHECK (length(fingerprint) = 64 AND fingerprint NOT GLOB '*[^0-9a-f]*'),\n controller_attestation_id TEXT,\n auth_config_revision TEXT NOT NULL CHECK (length(auth_config_revision) = 64 AND auth_config_revision NOT GLOB '*[^0-9a-f]*'),\n created_at_ms INTEGER NOT NULL,\n authority_kind TEXT NOT NULL CHECK (authority_kind IN ('controller_attestation','device_claim')),\n device_claim_id TEXT,\n PRIMARY KEY (coordinator_id, link_id, action),\n CHECK ((authority_kind = 'controller_attestation'\n AND (controller_attestation_id IS NOT NULL AND typeof(controller_attestation_id) = 'text' AND length(controller_attestation_id) BETWEEN 1 AND 256 AND controller_attestation_id = trim(controller_attestation_id) AND instr(controller_attestation_id, char(0)) = 0) AND device_claim_id IS NULL)\n OR (authority_kind = 'device_claim' AND controller_attestation_id IS NULL\n AND (device_claim_id IS NOT NULL AND typeof(device_claim_id) = 'text' AND length(device_claim_id) BETWEEN 1 AND 256 AND device_claim_id = trim(device_claim_id) AND instr(device_claim_id, char(0)) = 0)))\n);\nCREATE INDEX IF NOT EXISTS idx_auth_link_attempts_device_created\n ON coordinator_auth_link_attempts(coordinator_id, group_id, device_id, created_at_ms);\nCREATE INDEX IF NOT EXISTS idx_auth_link_attempts_identity_expiry\n ON coordinator_auth_link_attempts(coordinator_id, identity_id, expires_at_ms);\nCREATE INDEX IF NOT EXISTS idx_auth_link_attempts_state_expiry\n ON coordinator_auth_link_attempts(coordinator_id, state, expires_at_ms);\n${AUTH_LINK_BROWSER_START_INDEX_SQL}`;\n","import {\n\tACCOUNT_CHANGE_SCHEMA_STATEMENTS,\n\tBROWSER_ACCOUNT_ARCHIVE_GUARD,\n} from \"./coordinator-account-change-schema.js\";\nimport { ACCOUNT_CONNECTION_STORAGE_STATEMENTS } from \"./coordinator-account-connection-storage.js\";\nimport {\n\tACCOUNT_UNLINK_SCHEMA_STATEMENTS,\n\taccountArchiveReceiptGuard,\n} from \"./coordinator-account-unlink-schema.js\";\nimport {\n\tauthDeviceClaimDefinitionChecks,\n\tauthSchemaDefinitionCheck,\n} from \"./coordinator-auth-device-claim-schema.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport {\n\tAUTH_LINK_CREATE_WINDOW_MS,\n\tAUTH_LINK_MAX_ACTIVE_PER_DEVICE,\n\tAUTH_LINK_MAX_ACTIVE_PER_IDENTITY,\n\tAUTH_LINK_MAX_CREATES_PER_DEVICE_RETENTION,\n\tAUTH_LINK_MAX_CREATES_PER_DEVICE_WINDOW,\n\tAUTH_LINK_MAX_UNFINISHED_PER_COORDINATOR,\n\tAUTH_LINK_RETENTION_WINDOW_MS,\n} from \"./coordinator-auth-link-contract.js\";\n\nexport const AUTH_SCHEMA_UPGRADE_REQUIRED = \"coordinator_auth_schema_upgrade_required\";\nexport const AUTH_SCHEMA_UPGRADE_MESSAGE =\n\t\"Coordinator authentication needs a schema upgrade. Pause auth writers and back up the coordinator database. For the legacy authority upgrade, run codemem coordinator schema upgrade-auth --db-path <coordinator.sqlite>. D1 operators must review and apply outstanding auth migrations before deploying the upgraded Worker. A coordinator already using device-claim auth needs only outstanding additive migrations, including 0033; do not replay its authority-table cutover. Optional account management on an intact V2 database requires codemem coordinator schema upgrade-account --db-path <coordinator.sqlite>; normal V2 linking does not require this extension. Device-signed sync remains available.\";\nexport class CoordinatorAuthSchemaUpgradeRequiredError extends Error {\n\tconstructor() {\n\t\tsuper(AUTH_SCHEMA_UPGRADE_MESSAGE);\n\t\tthis.name = AUTH_SCHEMA_UPGRADE_REQUIRED;\n\t}\n}\n\n/** Shared insertion budgets; this pure leaf has no runtime-store import cycle. */\nexport function connectionAdmissionSql(subject: \"p\" | \"NEW\"): string {\n\tconst now = subject === \"p\" ? \"p.now_ms\" : \"NEW.created_at_ms\";\n\tconst live = `b.state NOT IN ('completed','finalized','session_redeemed','failed','expired','cancelled') AND b.expires_at_ms > ${now}`;\n\treturn `EXISTS (WITH connection_budget AS MATERIALIZED (\n SELECT group_id,device_id,identity_id,state,created_at_ms,expires_at_ms FROM coordinator_account_change_attempts WHERE coordinator_id = ${subject}.coordinator_id\n UNION ALL SELECT group_id,device_id,identity_id,state,created_at_ms,expires_at_ms FROM coordinator_auth_link_attempts WHERE coordinator_id = ${subject}.coordinator_id)\n SELECT 1 WHERE\n (SELECT count(*) FROM connection_budget b WHERE b.group_id = ${subject}.group_id AND b.device_id = ${subject}.device_id AND ${live}) < ${AUTH_LINK_MAX_ACTIVE_PER_DEVICE}\n AND (SELECT count(*) FROM connection_budget b WHERE b.identity_id = ${subject}.identity_id AND ${live}) < ${AUTH_LINK_MAX_ACTIVE_PER_IDENTITY}\n AND (SELECT count(*) FROM connection_budget b WHERE b.group_id = ${subject}.group_id AND b.device_id = ${subject}.device_id AND b.created_at_ms > ${now} - ${AUTH_LINK_CREATE_WINDOW_MS}) < ${AUTH_LINK_MAX_CREATES_PER_DEVICE_WINDOW}\n AND (SELECT count(*) FROM connection_budget b WHERE b.group_id = ${subject}.group_id AND b.device_id = ${subject}.device_id AND b.created_at_ms > ${now} - ${AUTH_LINK_RETENTION_WINDOW_MS}) < ${AUTH_LINK_MAX_CREATES_PER_DEVICE_RETENTION}\n AND (SELECT count(*) FROM connection_budget b WHERE b.state NOT IN ('completed','finalized','session_redeemed')) < ${AUTH_LINK_MAX_UNFINISHED_PER_COORDINATOR})`;\n}\nexport const CONNECTION_SESSION_SCHEMA_STATEMENTS = [\n\t\"ALTER TABLE coordinator_auth_browser_transactions ADD COLUMN start_order INTEGER\",\n\t\"ALTER TABLE coordinator_auth_account_links ADD COLUMN signin_floor INTEGER NOT NULL DEFAULT 0\",\n\t\"ALTER TABLE coordinator_auth_session_receipts ADD COLUMN source_order INTEGER\",\n\t\"ALTER TABLE coordinator_auth_account_connection_history ADD COLUMN signin_floor INTEGER\",\n\t`CREATE TRIGGER connection_history_floor_insert BEFORE INSERT ON coordinator_auth_account_connection_history\n WHEN NEW.signin_floor IS NOT (SELECT c.signin_floor FROM coordinator_auth_account_links c WHERE c.coordinator_id=NEW.coordinator_id AND c.link_id=NEW.link_id AND c.rowid=NEW.original_rowid)\n BEGIN SELECT RAISE(ABORT,'connection_archive_floor_invalid'); END`,\n\t`CREATE TRIGGER connection_history_floor_update BEFORE UPDATE ON coordinator_auth_account_connection_history WHEN NEW.signin_floor IS NOT OLD.signin_floor BEGIN SELECT RAISE(ABORT,'connection_history_immutable'); END`,\n\t`CREATE TRIGGER connection_link_shared_admission BEFORE INSERT ON coordinator_auth_link_attempts WHEN NOT ${connectionAdmissionSql(\"NEW\")} BEGIN SELECT RAISE(ABORT,'connection_attempt_limited'); END`,\n] as const;\nexport const CONNECTION_LINK_SCHEMA_STATEMENTS = [\n\t\"ALTER TABLE coordinator_auth_link_attempts ADD COLUMN prior_link_id TEXT\",\n\t`CREATE TRIGGER connection_link_prior_immutable BEFORE UPDATE ON coordinator_auth_link_attempts WHEN NEW.prior_link_id IS NOT OLD.prior_link_id AND (OLD.state <> 'pending' OR OLD.prior_link_id IS NOT NULL) BEGIN SELECT RAISE(ABORT,'connection_prior_immutable'); END`,\n\t`CREATE UNIQUE INDEX connection_history_head ON coordinator_auth_account_connection_history(coordinator_id,identity_id) WHERE successor_link_id IS NULL`,\n] as const;\nconst extensions = [\n\t...ACCOUNT_CONNECTION_STORAGE_STATEMENTS,\n\t...ACCOUNT_CHANGE_SCHEMA_STATEMENTS,\n\t...CONNECTION_SESSION_SCHEMA_STATEMENTS,\n\t...CONNECTION_LINK_SCHEMA_STATEMENTS,\n];\nconst quote = (s: string) => `'${s.replaceAll(\"'\", \"''\")}'`;\nconst additions = extensions.flatMap((s) => {\n\tconst m = /^ALTER TABLE (\\w+) ADD COLUMN (\\w+) (.+)$/u.exec(s);\n\treturn m ? [{ table: m[1] as string, name: m[2] as string, declaration: m[3] as string }] : [];\n});\nconst baseCounts: Record<string, number> = {\n\tcoordinator_auth_link_attempts: 29,\n\tcoordinator_auth_account_links: 12,\n\tcoordinator_auth_link_audit_log: 13,\n\tcoordinator_auth_browser_transactions: 16,\n\tcoordinator_auth_sessions: 12,\n\tcoordinator_auth_session_receipts: 9,\n\tcoordinator_auth_link_profiles: 12,\n\tcoordinator_auth_account_profiles: 8,\n};\nfunction columnCounts(extended: boolean): string {\n\treturn Object.entries(baseCounts)\n\t\t.map(\n\t\t\t([table, n]) =>\n\t\t\t\t`(SELECT count(*) FROM pragma_table_info(${quote(table)})) = ${n + (extended ? additions.filter((a) => a.table === table).length : 0)}`,\n\t\t)\n\t\t.join(\" AND \");\n}\nfunction v2Readiness(auxiliaryObjects: number): string {\n\treturn `SELECT\n (SELECT count(*) FROM pragma_table_info('coordinator_auth_link_attempts') WHERE lower(name) = 'authority_kind')\n + (SELECT count(*) FROM pragma_table_info('coordinator_auth_account_links') WHERE lower(name) IN ('authority_kind','device_claim_id'))\n + (SELECT count(*) FROM pragma_table_info('coordinator_auth_link_audit_log') WHERE lower(name) IN ('authority_kind','device_claim_id'))\n + (SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = 'coordinator_auth_link_profiles')\n + ${authDeviceClaimDefinitionChecks(auxiliaryObjects)\n\t\t.map(({ matches }) => `(${matches})`)\n\t\t.join(\" + \")} AS ready`;\n}\n/** The old 10-count contract stays unchanged; its exact 3-auxiliary fence remains. */\nexport const AUTH_V2_SCHEMA_READINESS_SQL = v2Readiness(3);\nconst creates = extensions.filter((s) => s.startsWith(\"CREATE\"));\nconst definitions = creates.map((s) => {\n\tconst table = /^CREATE TABLE (\\w+)/u.exec(s)?.[1];\n\tif (!table) return authSchemaDefinitionCheck(s);\n\tconst final =\n\t\ttable === \"coordinator_auth_account_connection_history\"\n\t\t\t? s.replace(\n\t\t\t\t\t\" PRIMARY KEY(coordinator_id\",\n\t\t\t\t\t\" signin_floor INTEGER,\\n PRIMARY KEY(coordinator_id\",\n\t\t\t\t)\n\t\t\t: s;\n\tconst auxiliaryObjects = creates.filter((ddl) => /\\bON (\\w+)/u.exec(ddl)?.[1] === table).length;\n\treturn authSchemaDefinitionCheck(final, { auxiliaryObjects });\n});\nconst reservedObjects = `(name GLOB 'account_connection_*' OR name GLOB 'account_change_*' OR name GLOB 'connection_*' OR name GLOB 'coordinator_auth_account_connection_*' OR name = 'coordinator_account_change_attempts' OR name = 'coordinator_auth_account_associations' OR name = 'coordinator_auth_link_change_attempts')`;\nexport const CONNECTION_SCHEMA_PRESENCE_SQL = `SELECT (EXISTS (SELECT 1 FROM sqlite_master WHERE ${reservedObjects}) OR ${additions.map((a) => `EXISTS (SELECT 1 FROM pragma_table_info(${quote(a.table)}) WHERE lower(name)=${quote(a.name)})`).join(\" OR \")}) AS present`;\nconst inventory = additions.map(\n\t(a) =>\n\t\t`EXISTS (SELECT 1 FROM pragma_table_info(${quote(a.table)}) WHERE lower(name)=${quote(a.name)} AND upper(type)=${quote(a.declaration.split(\" \")[0] as string)} AND \"notnull\"=${a.declaration.includes(\"NOT NULL\") ? 1 : 0} AND dflt_value IS ${a.declaration.includes(\"DEFAULT 0\") ? \"'0'\" : \"NULL\"} AND pk=0)`,\n);\nconst knownCoordinators = `SELECT coordinator_id FROM coordinator_auth_account_links UNION SELECT coordinator_id FROM coordinator_auth_browser_transactions UNION SELECT coordinator_id FROM coordinator_auth_link_attempts UNION SELECT coordinator_id FROM coordinator_auth_sessions`;\nconst rowsValid = `NOT EXISTS (SELECT 1 FROM coordinator_auth_account_links WHERE typeof(signin_floor)<>'integer' OR signin_floor<0 OR signin_floor>9007199254740991)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_browser_transactions WHERE start_order IS NOT NULL AND (typeof(start_order)<>'integer' OR start_order<1 OR start_order>9007199254740991))\n AND NOT EXISTS (SELECT 1 FROM (SELECT coordinator_id FROM coordinator_auth_account_links UNION SELECT coordinator_id FROM coordinator_auth_browser_transactions UNION SELECT coordinator_id FROM coordinator_auth_sessions) c LEFT JOIN coordinator_auth_account_connection_orders o ON o.coordinator_id=c.coordinator_id WHERE o.last_order IS NULL OR o.last_order<1)`;\nconst priorObjectCheck = `NOT EXISTS (SELECT 1 FROM sqlite_master WHERE ${reservedObjects} AND name NOT IN (${definitions.map((d) => quote(d.name)).join(\",\")}))`;\nconst checks = [\n\t...definitions.map((d) => d.matches),\n\t...inventory,\n\tcolumnCounts(true),\n\t`(${v2Readiness(4)})=10`,\n\tpriorObjectCheck,\n\trowsValid,\n];\n// VALUES avoids D1's compound-SELECT term limit without omitting any check.\nconst readiness = (checks: string[]) =>\n\t`SELECT min(column1) AS ready FROM (VALUES ${checks.map((s) => `(CASE WHEN ${s} THEN 1 ELSE 0 END)`).join(\",\")})`;\nconst legacyReadySql = readiness(checks);\nconst unlinkGuard = accountArchiveReceiptGuard(BROWSER_ACCOUNT_ARCHIVE_GUARD);\nconst newDefinitions = [...ACCOUNT_UNLINK_SCHEMA_STATEMENTS, unlinkGuard].map((s) =>\n\tauthSchemaDefinitionCheck(s, s.startsWith(\"CREATE TABLE\") ? { auxiliaryObjects: 4 } : undefined),\n);\nconst oldGuardCheck = authSchemaDefinitionCheck(BROWSER_ACCOUNT_ARCHIVE_GUARD).matches;\nconst currentChecks = checks.filter((s) => s !== oldGuardCheck && s !== priorObjectCheck);\ncurrentChecks.push(\n\t...newDefinitions.map((d) => d.matches),\n\t`NOT EXISTS (SELECT 1 FROM sqlite_master WHERE ${reservedObjects} AND name NOT IN (${[...definitions, ...newDefinitions].map((d) => quote(d.name)).join(\",\")}))`,\n);\nconst readySql = readiness(currentChecks);\n/** Scalar readiness query for reads that must check schema and data in one snapshot. */\nexport const ACCOUNT_CONNECTION_SCHEMA_READINESS_SQL = readySql;\nexport const ACCOUNT_CONNECTION_SCHEMA_CHECKS = currentChecks;\nexport function isIncompleteConnectionSchemaError(error: unknown): boolean {\n\treturn /no such (?:table|column)|has no column named|malformed (?:database )?schema/i.test(\n\t\tString(error),\n\t);\n}\nexport type ConnectionSchemaState = \"v2\" | \"ready\" | \"upgrade_required\";\nexport async function readConnectionSchemaState(\n\tbackend: Pick<AuthLinkBackend, \"first\">,\n): Promise<ConnectionSchemaState> {\n\tconst p = await backend.first<{ present: number; v2: number }>({\n\t\tsql: `SELECT (${CONNECTION_SCHEMA_PRESENCE_SQL}) AS present, ((${AUTH_V2_SCHEMA_READINESS_SQL})=10) AS v2`,\n\t\tvalues: [],\n\t});\n\tif (!p?.present) return p?.v2 === 1 ? \"v2\" : \"upgrade_required\";\n\ttry {\n\t\treturn (await backend.first<{ ready: number }>({ sql: readySql, values: [] }))?.ready === 1\n\t\t\t? \"ready\"\n\t\t\t: \"upgrade_required\";\n\t} catch (error) {\n\t\tif (!isIncompleteConnectionSchemaError(error)) throw error;\n\t\treturn \"upgrade_required\";\n\t} // Missing tables/columns are an incomplete extension, not V2.\n}\n\n/** Explicit operator operation only: never called by store initialization. One\n * atomic batch preserves existing rowids, credentials and proof bytes. */\nexport const PRIOR_ACCOUNT_CONNECTION_MIGRATION_STATEMENTS = [\n\t`INSERT INTO coordinator_auth_device_claims (claim_id) SELECT NULL WHERE NOT (((${AUTH_V2_SCHEMA_READINESS_SQL})=10) AND NOT (${CONNECTION_SCHEMA_PRESENCE_SQL}) AND (${columnCounts(false)}))`,\n\t...extensions,\n\t`INSERT INTO coordinator_auth_account_connection_orders (coordinator_id,last_order) SELECT coordinator_id,0 FROM (${knownCoordinators})`,\n\t\"UPDATE coordinator_auth_account_connection_orders SET last_order=last_order+1\",\n\t\"UPDATE coordinator_auth_link_profiles SET source_order=0\",\n\t\"UPDATE coordinator_auth_account_profiles SET source_order=1\",\n\t`UPDATE coordinator_auth_session_receipts AS r SET source_order=1\n WHERE r.source='signin' AND r.attempt_id IS NULL AND EXISTS (\n SELECT 1 FROM coordinator_auth_account_profiles p WHERE p.coordinator_id=r.coordinator_id\n AND p.link_id=r.link_id AND p.source_session_id=r.session_id\n AND p.source_signed_in_at_ms=r.created_at_ms AND p.source_order=1)`,\n\t`INSERT INTO coordinator_auth_account_connection_orders (coordinator_id,last_order) SELECT NULL,0 WHERE NOT (${legacyReadySql})`,\n] as const;\nexport const ACCOUNT_CONNECTION_MIGRATION_STATEMENTS = [\n\t...PRIOR_ACCOUNT_CONNECTION_MIGRATION_STATEMENTS.slice(0, -1),\n\t...ACCOUNT_UNLINK_SCHEMA_STATEMENTS,\n\t\"DROP TRIGGER account_change_archive_receipt\",\n\tunlinkGuard,\n\t`INSERT INTO coordinator_auth_account_connection_orders (coordinator_id,last_order) SELECT NULL,0 WHERE NOT (${readySql})`,\n] as const;\n/** Only the exact prior account extension can take this atomic, no-rebuild delta. */\nexport const ACCOUNT_UNLINK_MIGRATION_STATEMENTS = [\n\t`INSERT INTO coordinator_auth_account_connection_orders (coordinator_id,last_order) SELECT NULL,0 WHERE NOT (${legacyReadySql})`,\n\t...ACCOUNT_UNLINK_SCHEMA_STATEMENTS,\n\t\"DROP TRIGGER account_change_archive_receipt\",\n\tunlinkGuard,\n\t`INSERT INTO coordinator_auth_account_connection_orders (coordinator_id,last_order) SELECT NULL,0 WHERE NOT (${readySql})`,\n] as const;\nexport async function applyAccountConnectionSchema(backend: AuthLinkBackend): Promise<void> {\n\tconst state = await readConnectionSchemaState(backend);\n\tif (state === \"ready\") throw new Error(\"account_connection_schema_already_installed\");\n\tconst legacy = state === \"upgrade_required\" && (await hasPriorAccountSchema(backend));\n\tif (state !== \"v2\" && !legacy) throw new CoordinatorAuthSchemaUpgradeRequiredError();\n\tawait backend.batch(\n\t\t(legacy ? ACCOUNT_UNLINK_MIGRATION_STATEMENTS : ACCOUNT_CONNECTION_MIGRATION_STATEMENTS).map(\n\t\t\t(sql): AuthLinkStatement => ({ sql, values: [] }),\n\t\t),\n\t);\n\tif ((await readConnectionSchemaState(backend)) !== \"ready\")\n\t\tthrow new CoordinatorAuthSchemaUpgradeRequiredError();\n}\nasync function hasPriorAccountSchema(backend: AuthLinkBackend): Promise<boolean> {\n\ttry {\n\t\treturn (\n\t\t\t(await backend.first<{ ready: number }>({ sql: legacyReadySql, values: [] }))?.ready === 1\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n","import {\n\tCoordinatorAuthSchemaUpgradeRequiredError,\n\treadConnectionSchemaState,\n} from \"./coordinator-account-connection-schema.js\";\nimport {\n\tCONNECTION_ALLOCATE_ORDER_SQL,\n\tCONNECTION_ASSERT_ONE_WRITE_SQL,\n} from \"./coordinator-account-connection-storage.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\n\nexport {\n\tCONNECTION_SESSION_SCHEMA_STATEMENTS,\n\tconnectionAdmissionSql,\n} from \"./coordinator-account-connection-schema.js\";\n\n/** Schema choice is database-derived, never a caller-selected exemption.\n * Readiness checks all extension definitions; legacy NULL browser orders cannot\n * admit new sessions after installation. Existing sessions retain their validity. */\nexport async function hasConnectionSessionSchema(\n\tbackend: Pick<AuthLinkBackend, \"first\" | \"readAuthSchemaState\">,\n): Promise<boolean> {\n\tconst state = await (backend.readAuthSchemaState?.() ?? readConnectionSchemaState(backend));\n\tif (state === \"upgrade_required\") throw new CoordinatorAuthSchemaUpgradeRequiredError();\n\treturn state === \"ready\";\n}\n\n/** All allocation, insertion and exact-row stamping share the caller's batch. */\nexport async function orderedBrowserStart(\n\tbackend: AuthLinkBackend,\n\tstatements: AuthLinkStatement[],\n\tcoordinator: string,\n\thash: string,\n): Promise<void> {\n\tif (!(await hasConnectionSessionSchema(backend))) {\n\t\tawait backend.batch(statements);\n\t\treturn;\n\t}\n\tconst orders = \"coordinator_auth_account_connection_orders\";\n\tawait backend.batch([\n\t\t{\n\t\t\tsql: `INSERT INTO ${orders} (coordinator_id,last_order) SELECT ?,0 WHERE NOT EXISTS (SELECT 1 FROM ${orders} WHERE coordinator_id = ?)`,\n\t\t\tvalues: [coordinator, coordinator],\n\t\t},\n\t\t{ sql: CONNECTION_ALLOCATE_ORDER_SQL, values: [coordinator] },\n\t\t{ sql: CONNECTION_ASSERT_ONE_WRITE_SQL, values: [] },\n\t\t...statements,\n\t\t{\n\t\t\tsql: `UPDATE coordinator_auth_browser_transactions SET start_order = (SELECT last_order FROM ${orders} WHERE coordinator_id = ?) WHERE coordinator_id = ? AND browser_transaction_hash = ? AND start_order IS NULL`,\n\t\t\tvalues: [coordinator, coordinator, hash],\n\t\t},\n\t\t{ sql: CONNECTION_ASSERT_ONE_WRITE_SQL, values: [] },\n\t]);\n}\n\n/** Publish the browser floor and reject a continuation missing its prior pin.\n * The caller must already compose the successor CAS in this winning batch. */\nexport async function initialConnectionFloor(\n\tbackend: AuthLinkBackend,\n\tcoordinator: string,\n\tlink: string,\n): Promise<AuthLinkStatement[]> {\n\tif (!(await hasConnectionSessionSchema(backend))) return [];\n\treturn [\n\t\t{\n\t\t\tsql: `INSERT INTO coordinator_auth_account_connection_orders (coordinator_id,last_order) SELECT NULL,0 WHERE EXISTS (SELECT 1 FROM coordinator_auth_account_links l JOIN coordinator_auth_link_attempts a ON a.coordinator_id=l.coordinator_id AND a.attempt_id=l.attempt_id JOIN coordinator_auth_account_connection_history h ON h.coordinator_id = l.coordinator_id AND h.identity_id = l.identity_id WHERE l.coordinator_id = ? AND l.link_id = ? AND a.prior_link_id IS NULL)`,\n\t\t\tvalues: [coordinator, link],\n\t\t},\n\t\t{\n\t\t\tsql: `UPDATE coordinator_auth_account_links SET signin_floor = coalesce((SELECT last_order FROM coordinator_auth_account_connection_orders WHERE coordinator_id = ?),0) WHERE coordinator_id = ? AND link_id = ?`,\n\t\t\tvalues: [coordinator, coordinator, link],\n\t\t},\n\t];\n}\n\n/** Source aliases are fixed internal SQL, not request input. Refresh payloads\n * become readable only after their own immutable completed management receipt. */\nexport function connectionProfileColumns(signin: \"p\" | \"m\"): string {\n\t// Order one is the migration's already-verified legacy display snapshot.\n\t// Its expired receipt may have been legitimately purged before installation.\n\tconst validSignin = `(${signin}.source_order = 1 OR EXISTS (SELECT 1 FROM coordinator_auth_session_receipts r WHERE r.coordinator_id = ${signin}.coordinator_id AND r.link_id = ${signin}.link_id AND r.session_id = ${signin}.source_session_id AND r.source = 'signin' AND r.attempt_id IS NULL AND r.created_at_ms = ${signin}.source_signed_in_at_ms AND (${signin}.source_order IS NULL OR r.source_order = ${signin}.source_order)))`;\n\tconst validBirth = `(b.source_change_attempt_id IS NULL OR EXISTS (SELECT 1 FROM coordinator_account_change_attempts x WHERE x.coordinator_id = b.coordinator_id AND x.attempt_id = b.source_change_attempt_id AND x.state = 'completed' AND x.intent = 'refresh' AND x.target_link_id = l.link_id AND x.identity_id = l.identity_id AND x.issuer = l.issuer AND x.target_subject = l.subject AND x.browser_order = b.source_order))`;\n\tconst preferSignin = `${validSignin} AND (NOT ${validBirth} OR coalesce(${signin}.source_order,1) > coalesce(b.source_order,0))`;\n\treturn [\"display_name\", \"email\", \"email_verified\", \"picture_url\"]\n\t\t.map(\n\t\t\t(field) =>\n\t\t\t\t`CASE WHEN ${preferSignin} THEN ${signin}.${field} WHEN ${validBirth} THEN b.${field} END AS ${field}`,\n\t\t)\n\t\t.join(\",\\n\");\n}\n","import type { CoordinatorAuthLinkSigner } from \"./coordinator-auth-link-contract.js\";\nimport {\n\tcanonicalCoordinatorLegacyTeamCompletionManifestJson,\n\tlegacyDecisionCountsAsOwner,\n\tlegacyDecisionCountsAsOwnerSql,\n\tnormalizeCoordinatorLegacyTeamCompletionManifest,\n} from \"./coordinator-legacy-team-completion.js\";\nimport { legacyTeamCandidateId } from \"./recipient-policy-identifiers.js\";\n\ninterface AssignmentRecord {\n\tgroup_id: string;\n\tcandidate_ref: string;\n\tmanifest_version: number;\n\tcompleted_at: string;\n\tmanifest_json: string;\n}\n\n// The canonical reference scopes one record to this coordinator and group, without fallback.\nexport const AUTH_LEGACY_ASSIGNMENT_CAPTURE_SQL = `SELECT json_object(\n 'group_id', group_id, 'candidate_ref', candidate_ref, 'manifest_version', manifest_version,\n 'completed_at', completed_at, 'manifest_json',\n CASE WHEN length(CAST(manifest_json AS BLOB)) <= ? THEN manifest_json ELSE NULL END)\n FROM coordinator_legacy_team_completions WHERE group_id = ? AND candidate_ref = ?`;\n\n/** A capture is not authority: every consumer must recheck it inside its statement. */\nexport function captureCurrentLegacyAssignment(\n\tsnapshot: string | null | undefined,\n\tinput: {\n\t\tcoordinatorId: string;\n\t\tidentityId: string;\n\t\tsigner: CoordinatorAuthLinkSigner;\n\t\tdistinctKeys: string[];\n\t},\n): string | null {\n\ttry {\n\t\tif (typeof snapshot !== \"string\") return null;\n\t\tconst row: AssignmentRecord | null = JSON.parse(snapshot);\n\t\tif (!row || typeof row.manifest_json !== \"string\") return null;\n\t\tconst manifest = normalizeCoordinatorLegacyTeamCompletionManifest(\n\t\t\tJSON.parse(row.manifest_json),\n\t\t);\n\t\tif (\n\t\t\tcanonicalCoordinatorLegacyTeamCompletionManifestJson(manifest) !== row.manifest_json ||\n\t\t\trow.group_id !== input.signer.groupId ||\n\t\t\trow.candidate_ref !== legacyTeamCandidateId(input.coordinatorId, input.signer.groupId) ||\n\t\t\trow.candidate_ref !== manifest.candidate_ref ||\n\t\t\trow.manifest_version !== manifest.version ||\n\t\t\trow.completed_at !== manifest.completed_at ||\n\t\t\tmanifest.coordinator_id !== input.coordinatorId\n\t\t)\n\t\t\treturn null;\n\t\tconst assigned = manifest.device_decisions.some(\n\t\t\t(d) =>\n\t\t\t\td.device_id === input.signer.deviceId &&\n\t\t\t\td.key_fingerprint === input.signer.fingerprint &&\n\t\t\t\td.identity_id === input.identityId &&\n\t\t\t\td.decision === \"included\" &&\n\t\t\t\td.enabled &&\n\t\t\t\tlegacyDecisionCountsAsOwner(d),\n\t\t);\n\t\treturn assigned ? JSON.stringify({ ...row, distinct_keys: input.distinctKeys }) : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n// A label row (another device's guess) never makes a current assignment. Grouped\n// terms keep D1's expression depth (max 100) unchanged for embedding queries.\n// MATERIALIZED keeps the validated snapshot independent of deeper D1 predicates.\n// Exact bytes and row metadata pin normalization to the record used by the writer.\nexport const AUTH_CURRENT_LEGACY_ASSIGNMENT_CTE = `claim_current_assignment AS MATERIALIZED (\n SELECT c.* FROM claim_input p JOIN coordinator_legacy_team_completions c\n ON c.group_id = p.group_id AND c.group_id = json_extract(p.assignment_snapshot, '$.group_id')\n AND c.candidate_ref = json_extract(p.assignment_snapshot, '$.candidate_ref')\n AND c.manifest_version = json_extract(p.assignment_snapshot, '$.manifest_version')\n AND c.completed_at = json_extract(p.assignment_snapshot, '$.completed_at')\n AND c.manifest_json = json_extract(p.assignment_snapshot, '$.manifest_json')\n WHERE json_extract(json_extract(p.assignment_snapshot, '$.manifest_json'), '$.coordinator_id') = p.coordinator_id\n AND EXISTS (SELECT 1 FROM json_each(json_extract(p.assignment_snapshot, '$.manifest_json'), '$.device_decisions') d\n WHERE json_extract(d.value, '$.device_id') = p.device_id\n AND json_extract(d.value, '$.key_fingerprint') = p.fingerprint\n AND json_extract(d.value, '$.identity_id') = p.identity_id\n AND (json_extract(d.value, '$.decision') = 'included' AND json_extract(d.value, '$.enabled') = 1\n AND ${legacyDecisionCountsAsOwnerSql(\"d.value\")}))\n AND EXISTS (SELECT 1 FROM enrolled_devices e JOIN groups g ON g.group_id = e.group_id\n WHERE e.group_id = p.group_id AND e.device_id = p.device_id AND e.public_key = p.public_key\n AND e.fingerprint = p.fingerprint AND e.enabled = 1 AND g.archived_at IS NULL\n AND (e.identity_id IS NULL OR e.identity_id = p.identity_id))\n AND NOT EXISTS (SELECT 1 FROM coordinator_device_revocations r\n WHERE (r.subject_kind = 'device_id' AND r.subject_value = p.device_id)\n OR (r.subject_kind = 'ed25519_key' AND r.subject_value = p.key_id)))`;\n\nexport const AUTH_CURRENT_LEGACY_ASSIGNMENT_SQL = \"EXISTS (SELECT 1 FROM claim_current_assignment)\";\n","/**\n * Inert coordinator account-link policy. These results authenticate no claims,\n * grant no access, and must not be used as a runtime authorization gate.\n */\nexport interface CoordinatorAccountReference {\n\treadonly issuer: string;\n\treadonly subject: string;\n}\n\nexport type CoordinatorAccountReferenceResult =\n\t| { ok: true; account: CoordinatorAccountReference }\n\t| {\n\t\t\tok: false;\n\t\t\terror: \"invalid_account_reference\" | \"invalid_issuer\" | \"issuer_mismatch\" | \"invalid_subject\";\n\t };\n\nconst CONTROL_OR_FORMAT = /[\\p{Cc}\\p{Cf}\\p{Cs}]/u;\nconst FINGERPRINT = /^[0-9a-f]{64}$/;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nfunction field(value: Record<string, unknown>, key: string): unknown {\n\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\treturn descriptor && Object.hasOwn(descriptor, \"value\") ? descriptor.value : undefined;\n}\n\nfunction isIssuer(value: unknown): value is string {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\t!/^https:\\/\\//i.test(value) ||\n\t\tvalue !== value.trim() ||\n\t\tCONTROL_OR_FORMAT.test(value) ||\n\t\tvalue.includes(\"\\\\\") ||\n\t\tvalue.includes(\"?\") ||\n\t\tvalue.includes(\"#\")\n\t) {\n\t\treturn false;\n\t}\n\ttry {\n\t\tconst url = new URL(value);\n\t\treturn (\n\t\t\turl.protocol === \"https:\" &&\n\t\t\turl.hostname.length > 0 &&\n\t\t\turl.username === \"\" &&\n\t\t\turl.password === \"\" &&\n\t\t\turl.search === \"\" &&\n\t\t\turl.hash === \"\"\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport { isIssuer as isCoordinatorAccountIssuer };\n\nfunction isSubject(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length <= 255 &&\n\t\tvalue.trim().length > 0 &&\n\t\t!CONTROL_OR_FORMAT.test(value)\n\t);\n}\n\nfunction readAccountReference(value: unknown): CoordinatorAccountReferenceResult {\n\tif (!isRecord(value)) return { ok: false, error: \"invalid_account_reference\" };\n\tconst issuer = field(value, \"issuer\");\n\tconst subject = field(value, \"subject\");\n\tif (!isIssuer(issuer)) return { ok: false, error: \"invalid_issuer\" };\n\tif (!isSubject(subject)) return { ok: false, error: \"invalid_subject\" };\n\treturn { ok: true, account: { issuer, subject } };\n}\n\n/** Shape validation only; the caller must authenticate the issuer and subject independently. */\nexport function parseCoordinatorAccountReference(\n\tvalue: unknown,\n\toptions: { issuer: string },\n): CoordinatorAccountReferenceResult {\n\tconst configuredIssuer = isRecord(options) ? field(options, \"issuer\") : undefined;\n\tif (!isIssuer(configuredIssuer)) return { ok: false, error: \"invalid_issuer\" };\n\tconst reference = readAccountReference(value);\n\tif (!reference.ok) return reference;\n\tif (reference.account.issuer !== configuredIssuer) {\n\t\treturn { ok: false, error: \"issuer_mismatch\" };\n\t}\n\treturn reference;\n}\n\nexport interface CoordinatorAccountLink {\n\treadonly coordinatorId: string;\n\treadonly account: CoordinatorAccountReference;\n\treadonly identityId: string;\n\treadonly status: \"active\" | \"revoked\";\n}\n\n/**\n * Kind labels do not verify ownership. The caller must verify proofs first;\n * controller_verified means an existing trusted Identity-controlling device.\n */\nexport type CoordinatorIdentityOwnershipEvidence =\n\t| {\n\t\t\treadonly kind: \"controller_verified\" | \"admin_verified\";\n\t\t\treadonly coordinatorId: string;\n\t\t\treadonly identityId: string;\n\t\t\treadonly deviceId: string;\n\t\t\treadonly fingerprint: string;\n\t }\n\t| { readonly kind: \"invitation_claim\" | \"unavailable\" };\n\nexport interface CoordinatorAccountLinkInput {\n\treadonly coordinatorId: string;\n\treadonly account: CoordinatorAccountReference;\n\treadonly identityId: string;\n\treadonly device: { readonly deviceId: string; readonly fingerprint: string };\n\treadonly ownership: CoordinatorIdentityOwnershipEvidence;\n\treadonly accountLink: CoordinatorAccountLink | null;\n\treadonly identityLink: CoordinatorAccountLink | null;\n}\n\nexport type CoordinatorAccountLinkDecision =\n\t| {\n\t\t\tkind: \"eligible\";\n\t\t\tdisposition: \"create\" | \"existing\";\n\t\t\tcoordinatorId: string;\n\t\t\tidentityId: string;\n\t\t\taccount: CoordinatorAccountReference;\n\t }\n\t| {\n\t\t\tkind: \"rejected\";\n\t\t\terror:\n\t\t\t\t| \"invalid_link_input\"\n\t\t\t\t| \"ownership_review_required\"\n\t\t\t\t| \"ownership_mismatch\"\n\t\t\t\t| \"invalid_link_snapshot\"\n\t\t\t\t| \"account_link_conflict\"\n\t\t\t\t| \"identity_link_conflict\"\n\t\t\t\t| \"link_revoked\";\n\t };\n\nfunction isId(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length > 0 &&\n\t\tvalue.length <= 256 &&\n\t\tvalue === value.trim() &&\n\t\t!CONTROL_OR_FORMAT.test(value)\n\t);\n}\n\nfunction sameAccount(\n\tleft: CoordinatorAccountReference,\n\tright: CoordinatorAccountReference,\n): boolean {\n\treturn left.issuer === right.issuer && left.subject === right.subject;\n}\n\nfunction isFingerprint(value: unknown): value is string {\n\treturn typeof value === \"string\" && FINGERPRINT.test(value);\n}\n\ninterface ValidatedLinkInput {\n\treadonly coordinatorId: string;\n\treadonly identityId: string;\n\treadonly account: CoordinatorAccountReference;\n\treadonly deviceId: string;\n\treadonly fingerprint: string;\n\treadonly ownership: unknown;\n\treadonly accountLink: unknown;\n\treadonly identityLink: unknown;\n}\n\nfunction readLinkInput(input: unknown, options: { issuer: string }): ValidatedLinkInput | null {\n\tif (!isRecord(input)) return null;\n\tconst coordinatorId = field(input, \"coordinatorId\");\n\tconst identityId = field(input, \"identityId\");\n\tconst accountValue = field(input, \"account\");\n\tconst device = field(input, \"device\");\n\tconst ownership = field(input, \"ownership\");\n\tconst accountLink = field(input, \"accountLink\");\n\tconst identityLink = field(input, \"identityLink\");\n\tif (!isRecord(device) || !isId(coordinatorId) || !isId(identityId)) return null;\n\tconst deviceId = field(device, \"deviceId\");\n\tconst fingerprint = field(device, \"fingerprint\");\n\tif (!isId(deviceId) || !isFingerprint(fingerprint)) return null;\n\tconst account = parseCoordinatorAccountReference(accountValue, options);\n\tif (!account.ok) return null;\n\treturn {\n\t\tcoordinatorId,\n\t\tidentityId,\n\t\taccount: account.account,\n\t\tdeviceId,\n\t\tfingerprint,\n\t\townership,\n\t\taccountLink,\n\t\tidentityLink,\n\t};\n}\n\nfunction readLinkSnapshot(\n\tvalue: unknown,\n\tcoordinatorId: string,\n): CoordinatorAccountLink | undefined {\n\tif (!isRecord(value)) return undefined;\n\tconst snapshotCoordinatorId = field(value, \"coordinatorId\");\n\tconst identityId = field(value, \"identityId\");\n\tconst status = field(value, \"status\");\n\tconst account = readAccountReference(field(value, \"account\"));\n\tif (\n\t\tsnapshotCoordinatorId !== coordinatorId ||\n\t\t!isId(identityId) ||\n\t\t(status !== \"active\" && status !== \"revoked\") ||\n\t\t!account.ok\n\t) {\n\t\treturn undefined;\n\t}\n\t// A different issuer is a valid stored link, but conflicts with this request.\n\treturn { coordinatorId, identityId, status, account: account.account };\n}\n\nfunction validateOwnership(expected: ValidatedLinkInput): CoordinatorAccountLinkDecision | null {\n\tconst { ownership } = expected;\n\tif (!isRecord(ownership)) return { kind: \"rejected\", error: \"invalid_link_input\" };\n\tconst kind = field(ownership, \"kind\");\n\tif (kind === \"invitation_claim\" || kind === \"unavailable\") {\n\t\treturn { kind: \"rejected\", error: \"ownership_review_required\" };\n\t}\n\tif (kind !== \"controller_verified\" && kind !== \"admin_verified\") {\n\t\treturn { kind: \"rejected\", error: \"invalid_link_input\" };\n\t}\n\tconst coordinatorId = field(ownership, \"coordinatorId\");\n\tconst identityId = field(ownership, \"identityId\");\n\tconst deviceId = field(ownership, \"deviceId\");\n\tconst fingerprint = field(ownership, \"fingerprint\");\n\tif (!isId(coordinatorId) || !isId(identityId) || !isId(deviceId) || !isFingerprint(fingerprint)) {\n\t\treturn { kind: \"rejected\", error: \"invalid_link_input\" };\n\t}\n\tif (\n\t\tcoordinatorId !== expected.coordinatorId ||\n\t\tidentityId !== expected.identityId ||\n\t\tdeviceId !== expected.deviceId ||\n\t\tfingerprint !== expected.fingerprint\n\t) {\n\t\treturn { kind: \"rejected\", error: \"ownership_mismatch\" };\n\t}\n\treturn null;\n}\n\nfunction validateSnapshots(expected: ValidatedLinkInput): CoordinatorAccountLinkDecision | null {\n\tconst { coordinatorId, identityId, account } = expected;\n\tconst accountLink =\n\t\texpected.accountLink === null ? null : readLinkSnapshot(expected.accountLink, coordinatorId);\n\tconst identityLink =\n\t\texpected.identityLink === null ? null : readLinkSnapshot(expected.identityLink, coordinatorId);\n\tif (accountLink === undefined || identityLink === undefined) {\n\t\treturn { kind: \"rejected\", error: \"invalid_link_snapshot\" };\n\t}\n\tif (accountLink !== null && !sameAccount(accountLink.account, account)) {\n\t\treturn { kind: \"rejected\", error: \"invalid_link_snapshot\" };\n\t}\n\tif (identityLink !== null && identityLink.identityId !== identityId) {\n\t\treturn { kind: \"rejected\", error: \"invalid_link_snapshot\" };\n\t}\n\tif (accountLink?.status === \"revoked\" || identityLink?.status === \"revoked\") {\n\t\treturn { kind: \"rejected\", error: \"link_revoked\" };\n\t}\n\tif (accountLink !== null && accountLink.identityId !== identityId) {\n\t\treturn { kind: \"rejected\", error: \"account_link_conflict\" };\n\t}\n\tif (identityLink !== null && !sameAccount(identityLink.account, account)) {\n\t\treturn { kind: \"rejected\", error: \"identity_link_conflict\" };\n\t}\n\tif ((accountLink === null) !== (identityLink === null)) {\n\t\treturn { kind: \"rejected\", error: \"invalid_link_snapshot\" };\n\t}\n\treturn null;\n}\n\n/**\n * Metadata decision only. Supply trusted internal ownership evidence and a\n * same-coordinator snapshot; any future writer must recheck both links atomically.\n * Authentication protocol approval remains required before runtime integration.\n */\nexport function decideCoordinatorAccountLink(\n\tinput: CoordinatorAccountLinkInput,\n\toptions: { issuer: string },\n): CoordinatorAccountLinkDecision {\n\tconst validated = readLinkInput(input, options);\n\tif (!validated) return { kind: \"rejected\", error: \"invalid_link_input\" };\n\tconst ownershipDecision = validateOwnership(validated);\n\tif (ownershipDecision) return ownershipDecision;\n\tconst snapshotDecision = validateSnapshots(validated);\n\tif (snapshotDecision) return snapshotDecision;\n\treturn {\n\t\tkind: \"eligible\",\n\t\tdisposition: validated.accountLink === null ? \"create\" : \"existing\",\n\t\tcoordinatorId: validated.coordinatorId,\n\t\tidentityId: validated.identityId,\n\t\taccount: validated.account,\n\t};\n}\n","import { isCoordinatorAccountIssuer } from \"./coordinator-auth-contract.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type {\n\tCoordinatorAuthLinkConfig,\n\tCoordinatorAuthLinkSigner,\n} from \"./coordinator-auth-link-contract.js\";\n\nexport type Captured = Record<string, unknown>;\nexport function isHash(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length === 64 && /^[0-9a-f]{64}$/.test(value);\n}\nexport function capture(value: unknown, fields: readonly string[]): Captured | null {\n\tif (!value || typeof value !== \"object\") return null;\n\ttry {\n\t\tif (Array.isArray(value)) return null;\n\t\tconst result: Captured = {};\n\t\tfor (const key of fields) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\t\tif (!descriptor || !Object.hasOwn(descriptor, \"value\")) return null;\n\t\t\tresult[key] = descriptor.value;\n\t\t}\n\t\treturn result;\n\t} catch {\n\t\treturn null;\n\t}\n}\nexport function captureAuthLinkConfig(value: unknown): CoordinatorAuthLinkConfig | null {\n\tconst c = capture(value, [\"coordinatorId\", \"issuer\", \"revision\", \"enabled\"]);\n\tif (\n\t\t!c ||\n\t\t!isAuthControllerId(c.coordinatorId) ||\n\t\t!isCoordinatorAccountIssuer(c.issuer) ||\n\t\t!isHash(c.revision) ||\n\t\ttypeof c.enabled !== \"boolean\"\n\t)\n\t\treturn null;\n\treturn c as unknown as CoordinatorAuthLinkConfig;\n}\nfunction isPublicKey(value: unknown): value is string {\n\tif (typeof value !== \"string\" || value.length > 4096) return false;\n\tconst flat = value.replace(/[\\r\\n]/g, \"\");\n\treturn flat.length > 0 && flat.trim() === flat && !/[\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(flat);\n}\nexport function captureAuthLinkSigner(value: unknown): CoordinatorAuthLinkSigner | null {\n\tconst s = capture(value, [\"groupId\", \"deviceId\", \"publicKey\", \"fingerprint\"]);\n\tif (\n\t\t!s ||\n\t\t!isAuthControllerId(s.groupId) ||\n\t\t!isAuthControllerId(s.deviceId) ||\n\t\t!isPublicKey(s.publicKey) ||\n\t\t!isHash(s.fingerprint)\n\t)\n\t\treturn null;\n\treturn s as unknown as CoordinatorAuthLinkSigner;\n}\n","import { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport {\n\tAUTH_CURRENT_LEGACY_ASSIGNMENT_CTE,\n\tAUTH_CURRENT_LEGACY_ASSIGNMENT_SQL,\n\tAUTH_LEGACY_ASSIGNMENT_CAPTURE_SQL,\n\tcaptureCurrentLegacyAssignment,\n} from \"./coordinator-auth-legacy-assignment.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport type {\n\tCoordinatorAuthLinkConfig,\n\tCoordinatorAuthLinkSigner,\n} from \"./coordinator-auth-link-contract.js\";\nimport { captureAuthLinkConfig, captureAuthLinkSigner } from \"./coordinator-auth-link-input.js\";\nimport {\n\ted25519KeyIdForRevocation,\n\tparseSshEd25519PublicKeyForRevocation,\n} from \"./coordinator-ed25519-key-id-compat.js\";\nimport {\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES,\n\tlegacyDecisionCountsAsOwnerSql,\n} from \"./coordinator-legacy-team-completion.js\";\nimport { legacyTeamCandidateId } from \"./recipient-policy-identifiers.js\";\n\nexport interface CoordinatorDeviceClaimReadinessInput {\n\t/** The authenticated enrollment and the caller's pinned current local Identity. */\n\tsigner: CoordinatorAuthLinkSigner;\n\tidentityId: string;\n\t/** Internal retry context, never an instruction to ignore a different claimant. */\n\tattemptId?: string;\n}\nexport type CoordinatorDeviceClaimReadiness =\n\t| { kind: \"eligible\"; authority: \"device_claim\"; identityId: string }\n\t| { kind: \"unavailable\" };\n\n// These older tables have text keys, not canonical key-ID columns. Classify their\n// actual key bytes once, then reject any newly introduced text key in the final\n// SQL statement. Other row/Identity changes are checked live by the predicate.\nconst CURRENT_KEYS = `SELECT public_key FROM enrolled_devices\n UNION SELECT public_key FROM coordinator_auth_controller_attestations\n UNION SELECT public_key FROM coordinator_auth_link_attempts\n UNION SELECT bound_public_key AS public_key FROM coordinator_invites`;\nconst KEY_SNAPSHOT_SQL = `SELECT (${AUTH_LEGACY_ASSIGNMENT_CAPTURE_SQL}) AS assignment_snapshot,\n (SELECT count(*) FROM pragma_table_info('coordinator_auth_browser_transactions') WHERE name = 'start_order') AS connection_session,\n (SELECT json_group_array(public_key) FROM (\n SELECT public_key FROM (${CURRENT_KEYS}) WHERE typeof(public_key) = 'text' ORDER BY public_key)) AS keys`;\n\n/** Shared by readiness and INSERT/transition guards; 15 inputs bound once. */\nexport const AUTH_DEVICE_CLAIM_INPUT_SQL = `WITH claim_input(\n coordinator_id, identity_id, group_id, device_id, public_key, fingerprint, key_id,\n now_ms, now_iso, attempt_id, issuer, revision, key_snapshot, same_keys, assignment_snapshot\n) AS (VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)),\n claim_known_keys AS (SELECT value FROM claim_input p, json_each(p.key_snapshot)),\n claim_same_keys AS (SELECT value FROM claim_input p, json_each(p.same_keys)),\n ${AUTH_CURRENT_LEGACY_ASSIGNMENT_CTE}`;\n\nconst sameKey = (column: string) =>\n\t`EXISTS (SELECT 1 FROM claim_same_keys k WHERE k.value = ${column})`;\nconst otherSubject = (device: string, key: string) =>\n\t`(${device} IS NOT p.device_id OR NOT ${sameKey(key)})`;\n\n/** Current requester contradictions and captured-assignment staleness deny access. */\nexport const AUTH_DEVICE_CLAIM_CURRENT_SUBJECT_COMPATIBLE_SQL = `\n (p.assignment_snapshot IS NULL OR ${AUTH_CURRENT_LEGACY_ASSIGNMENT_SQL})\n AND\n NOT EXISTS (SELECT public_key FROM (${CURRENT_KEYS}) WHERE typeof(public_key) = 'text'\n EXCEPT SELECT value FROM claim_known_keys)\n AND NOT EXISTS (SELECT 1 FROM enrolled_devices e WHERE\n (e.device_id = p.device_id OR ${sameKey(\"e.public_key\")})\n AND e.identity_id IS NOT NULL AND e.identity_id <> p.identity_id)\n AND NOT EXISTS (SELECT 1 FROM coordinator_device_ownership_bindings b WHERE\n (b.device_id = p.device_id OR b.key_id = p.key_id) AND b.identity_id <> p.identity_id)`;\n\n/** A shared reader's own attestations are current checks, not historical origin pins. */\nexport const AUTH_DEVICE_CLAIM_REQUESTER_ATTESTATION_COMPATIBLE_SQL = `NOT EXISTS (\n SELECT 1 FROM coordinator_auth_controller_attestations a WHERE a.coordinator_id = p.coordinator_id\n AND (a.device_id = p.device_id OR ${sameKey(\"a.public_key\")})\n AND (a.revoked_at IS NOT NULL OR a.identity_id <> p.identity_id))`;\n\n// The peer must match its current enrollment, not just an old device label.\nconst matchingLegacyPeerEnrollment = `e.group_id = p.group_id AND e.enabled = 1\n AND e.device_id <> p.device_id AND e.fingerprint <> p.fingerprint\n AND NOT ${sameKey(\"e.public_key\")}\n AND EXISTS (SELECT 1 FROM json_each(p.assignment_snapshot, '$.distinct_keys') k WHERE k.value = e.public_key)\n AND EXISTS (SELECT 1 FROM claim_current_assignment ca, json_each(ca.manifest_json, '$.device_decisions') d\n WHERE json_extract(d.value, '$.device_id') = e.device_id\n AND json_extract(d.value, '$.key_fingerprint') = e.fingerprint\n AND json_extract(d.value, '$.identity_id') = p.identity_id\n AND (json_extract(d.value, '$.decision') = 'included' AND json_extract(d.value, '$.enabled') = 1\n AND ${legacyDecisionCountsAsOwnerSql(\"d.value\")}))`;\nconst live = (alias: string) =>\n\t`${alias}.state IN ('pending','browser_claimed','oidc_verified','confirmed') AND ${alias}.expires_at_ms > p.now_ms`;\n// Pending promises expire. Consumed evidence survives later expiry/revocation,\n// but an invite revoked before consumption supplies no footprint.\nconst inviteLive = `(i.revoked_at IS NULL AND i.expires_at > p.now_iso)`;\nconst inviteConsumed = `(i.consumed_at IS NOT NULL AND i.consumed_at <> '' AND (i.revoked_at IS NULL OR i.revoked_at > i.consumed_at))`;\nconst inviteBinding = `(i.bound_device_id IS NOT NULL OR i.bound_public_key IS NOT NULL)`;\nconst completionJson = `CASE WHEN typeof(c.manifest_json) = 'text' AND json_valid(c.manifest_json) THEN c.manifest_json ELSE '{}' END`;\n\n/** Consumed assignments survive removal/re-enrollment and later token revocation. */\nexport const AUTH_DEVICE_CLAIM_REQUESTER_INVITE_COMPATIBLE_SQL = `NOT EXISTS (\n SELECT 1 FROM coordinator_invites i WHERE ${inviteConsumed}\n AND (i.bound_device_id = p.device_id OR ${sameKey(\"i.bound_public_key\")} OR i.bound_fingerprint = p.fingerprint)\n AND ((i.assigned_identity_id IS NOT NULL AND i.assigned_identity_id <> p.identity_id)\n OR (i.target_identity_id IS NOT NULL AND i.target_identity_id <> p.identity_id)))`;\n\n/** A completed other-Identity binding remains a contradiction without its old controller. */\nexport const AUTH_DEVICE_CLAIM_REQUESTER_LINK_COMPATIBLE_SQL = `NOT EXISTS (\n SELECT 1 FROM coordinator_auth_account_links l JOIN coordinator_auth_link_attempts a\n ON a.coordinator_id = l.coordinator_id AND a.link_id = l.link_id\n WHERE l.coordinator_id = p.coordinator_id AND l.identity_id <> p.identity_id\n AND (a.device_id = p.device_id OR ${sameKey(\"a.public_key\")}))\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_links l JOIN coordinator_auth_link_audit_log a\n ON a.coordinator_id = l.coordinator_id AND a.link_id = l.link_id\n WHERE l.coordinator_id = p.coordinator_id AND a.device_id = p.device_id AND l.identity_id <> p.identity_id)`;\n\n/**\n * Shared by first-link writes and exact-assignment status reads. Another\n * device's guessed label neither contradicts nor competes with this device's\n * own claim. Labels exist only on included rows, so skipping them never skips\n * an exclusion. The label test sits beside the coordinator test so D1's\n * expression depth (max 100) does not grow.\n */\nconst legacyCompletionSql = (predicate: string) => `NOT EXISTS (\n SELECT 1 FROM coordinator_legacy_team_completions c, json_each(${completionJson}, '$.device_decisions') d\n WHERE (${legacyDecisionCountsAsOwnerSql(\"d.value\", \"deny\")} AND json_extract(${completionJson}, '$.coordinator_id') = p.coordinator_id) AND (\n ${predicate}))`;\nconst legacyThisDevice = `(json_extract(d.value, '$.device_id') = p.device_id OR json_extract(d.value, '$.key_fingerprint') = p.fingerprint)`;\nconst legacyPeerBranch = `(json_extract(d.value, '$.identity_id') = p.identity_id\n AND (json_extract(d.value, '$.device_id') IS NOT p.device_id OR json_extract(d.value, '$.key_fingerprint') IS NOT p.fingerprint)\n AND NOT (json_extract(d.value, '$.device_id') <> p.device_id\n AND json_extract(d.value, '$.key_fingerprint') <> p.fingerprint\n AND json_extract(d.value, '$.decision') = 'included' AND json_extract(d.value, '$.enabled') = 1\n AND EXISTS (SELECT 1 FROM claim_current_assignment ca WHERE ca.group_id = c.group_id\n AND ca.candidate_ref = c.candidate_ref AND ca.manifest_json = c.manifest_json)))`;\nexport const AUTH_DEVICE_CLAIM_LEGACY_COMPATIBLE_SQL = legacyCompletionSql(`(${legacyThisDevice}\n AND (json_extract(d.value, '$.decision') = 'excluded' OR json_extract(d.value, '$.identity_id') IS NOT p.identity_id))\n OR ${legacyPeerBranch}`);\n/**\n * The legacy checks an ownership binding cannot waive: an exclusion of this\n * device, and other devices' history under the claimed Identity. A binding\n * waives only history that recorded this device under another Identity.\n */\nexport const AUTH_DEVICE_CLAIM_LEGACY_UNWAIVABLE_SQL = legacyCompletionSql(`(${legacyThisDevice}\n AND json_extract(d.value, '$.decision') = 'excluded')\n OR ${legacyPeerBranch}`);\n\n/**\n * p is the single claim_input row. This is device-claim eligibility, never operator\n * authority. No group-wide member scan may turn unrelated people into a denial.\n * All NULL comparisons below deliberately reject mismatched/absent binding pins.\n */\n// Parenthesized conjunctions avoid a long left-deep AND tree when browser\n// receipt queries embed this predicate under their own conditions (D1 depth 100).\nexport const AUTH_DEVICE_CLAIM_ELIGIBLE_SQL = `(\n EXISTS (SELECT 1 FROM enrolled_devices e JOIN groups g ON g.group_id = e.group_id\n WHERE e.group_id = p.group_id AND e.device_id = p.device_id AND e.public_key = p.public_key\n AND e.fingerprint = p.fingerprint AND e.enabled = 1 AND g.archived_at IS NULL\n AND (e.identity_id IS NULL OR e.identity_id = p.identity_id))\n AND (${AUTH_DEVICE_CLAIM_CURRENT_SUBJECT_COMPATIBLE_SQL})\n AND NOT EXISTS (SELECT 1 FROM coordinator_device_revocations r\n WHERE (r.subject_kind = 'device_id' AND r.subject_value = p.device_id)\n OR (r.subject_kind = 'ed25519_key' AND r.subject_value = p.key_id))\n AND NOT EXISTS (SELECT 1 FROM enrolled_devices e WHERE\n e.identity_id = p.identity_id AND ${otherSubject(\"e.device_id\", \"e.public_key\")}\n AND NOT (${matchingLegacyPeerEnrollment}))\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_controller_attestations a WHERE a.coordinator_id = p.coordinator_id AND (\n ((a.device_id = p.device_id OR ${sameKey(\"a.public_key\")}) AND (a.revoked_at IS NOT NULL OR a.identity_id <> p.identity_id))\n OR ((a.identity_id = p.identity_id OR a.enrollment_identity_id = p.identity_id) AND ${otherSubject(\"a.device_id\", \"a.public_key\")})\n OR (a.group_id = p.group_id AND a.device_id = p.device_id AND a.public_key = p.public_key\n AND a.fingerprint = p.fingerprint AND a.identity_id = p.identity_id AND a.revoked_at IS NULL AND a.revision = 1)))\n ) AND (\n NOT EXISTS (SELECT 1 FROM coordinator_device_ownership_bindings b WHERE\n b.identity_id = p.identity_id AND (b.device_id IS NOT p.device_id OR b.key_id IS NOT p.key_id))\n AND NOT EXISTS (SELECT 1 FROM coordinator_identity_group_grants g\n WHERE g.coordinator_id = p.coordinator_id AND g.identity_id = p.identity_id)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_device_claims d WHERE d.coordinator_id = p.coordinator_id\n AND (d.identity_id = p.identity_id OR d.device_id = p.device_id OR d.key_id = p.key_id))\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_links l\n WHERE l.coordinator_id = p.coordinator_id AND l.identity_id = p.identity_id)\n ) AND (\n (${AUTH_DEVICE_CLAIM_REQUESTER_LINK_COMPATIBLE_SQL})\n AND NOT EXISTS (SELECT 1 FROM coordinator_owner_enrollment_attempts o WHERE o.coordinator_id = p.coordinator_id\n AND ${live(\"o\")} AND (o.device_id = p.device_id OR o.key_id = p.key_id OR o.identity_id = p.identity_id))\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_link_attempts a WHERE a.coordinator_id = p.coordinator_id AND ${live(\"a\")}\n AND NOT (a.attempt_id IS p.attempt_id AND a.authority_kind = 'device_claim' AND a.identity_id = p.identity_id\n AND a.group_id = p.group_id AND a.device_id = p.device_id AND a.public_key = p.public_key AND a.fingerprint = p.fingerprint)\n AND ((a.authority_kind = 'device_claim' AND a.identity_id <> p.identity_id AND (a.device_id = p.device_id OR ${sameKey(\"a.public_key\")}))\n OR (a.identity_id = p.identity_id AND ${otherSubject(\"a.device_id\", \"a.public_key\")})))\n ) AND (\n NOT EXISTS (SELECT 1 FROM coordinator_invites i WHERE (\n (${inviteConsumed} AND (i.bound_device_id = p.device_id OR ${sameKey(\"i.bound_public_key\")} OR i.bound_fingerprint = p.fingerprint)\n AND ((i.assigned_identity_id IS NOT NULL AND i.assigned_identity_id <> p.identity_id) OR (i.target_identity_id IS NOT NULL AND i.target_identity_id <> p.identity_id)))\n OR ((${inviteLive} OR ${inviteConsumed}) AND (\n ((i.assigned_identity_id = p.identity_id OR i.target_identity_id = p.identity_id)\n AND ((${inviteLive} AND (i.consumed_at IS NULL OR i.consumed_at = '')) OR (${inviteBinding} AND ${otherSubject(\"i.bound_device_id\", \"i.bound_public_key\")})))\n OR (i.recipient_actor_id = p.identity_id AND ${inviteBinding} AND ${otherSubject(\"i.bound_device_id\", \"i.bound_public_key\")})\n OR (i.inviter_actor_id = p.identity_id AND i.inviter_device_id IS NOT NULL AND i.inviter_device_id <> p.device_id)))))\n AND ${AUTH_DEVICE_CLAIM_LEGACY_COMPATIBLE_SQL})`;\n\nfunction captureInput(input: CoordinatorDeviceClaimReadinessInput) {\n\ttry {\n\t\tif (!input || typeof input !== \"object\" || Array.isArray(input)) return null;\n\t\tconst identity = Object.getOwnPropertyDescriptor(input, \"identityId\");\n\t\tconst signer = Object.getOwnPropertyDescriptor(input, \"signer\");\n\t\tconst attempt = Object.getOwnPropertyDescriptor(input, \"attemptId\");\n\t\tconst s = signer && \"value\" in signer ? captureAuthLinkSigner(signer.value) : null;\n\t\tif (!identity || !(\"value\" in identity) || !isAuthControllerId(identity.value) || !s)\n\t\t\treturn null;\n\t\tif (attempt && (!(\"value\" in attempt) || !isAuthControllerId(attempt.value))) return null;\n\t\tif (!attempt && \"attemptId\" in input) return null;\n\t\treturn { signer: s, identityId: identity.value, attemptId: attempt?.value ?? null };\n\t} catch {\n\t\treturn null;\n\t}\n}\n\ninterface CapturedClaimEligibility {\n\tidentityId: string;\n\tvalues: AuthLinkStatement[\"values\"];\n\tconnectionSession: boolean;\n}\ninterface ClaimKeySnapshot {\n\tkeys: string;\n\tassignment_snapshot: string | null;\n\tconnection_session: number;\n}\nfunction hasKeyBlob(key: string, blob: Uint8Array): boolean {\n\tconst parsed = parseSshEd25519PublicKeyForRevocation(key);\n\treturn parsed.kind === \"ed25519\" && parsed.blob.every((byte, index) => byte === blob[index]);\n}\n/** Capture only server-derived key metadata; a later writer must include the SQL guard. */\nexport async function captureDeviceClaimEligibility(\n\tbackend: Pick<AuthLinkBackend, \"first\">,\n\tinput: CoordinatorDeviceClaimReadinessInput,\n\tconfig: CoordinatorAuthLinkConfig,\n\tnow: number,\n): Promise<CapturedClaimEligibility | null> {\n\tconst c = captureAuthLinkConfig(config);\n\tconst i = captureInput(input);\n\tif (!c?.enabled || !i) return null;\n\tconst target = parseSshEd25519PublicKeyForRevocation(i.signer.publicKey);\n\tif (target.kind !== \"ed25519\") return null;\n\tconst keyId = await ed25519KeyIdForRevocation(i.signer.publicKey);\n\tif (!keyId) return null;\n\tconst row = await backend.first<ClaimKeySnapshot>({\n\t\tsql: KEY_SNAPSHOT_SQL,\n\t\tvalues: [\n\t\t\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES,\n\t\t\ti.signer.groupId,\n\t\t\tlegacyTeamCandidateId(c.coordinatorId, i.signer.groupId),\n\t\t],\n\t});\n\tconst keys: unknown = JSON.parse(row?.keys ?? \"null\");\n\tif (!Array.isArray(keys) || !keys.every((key): key is string => typeof key === \"string\"))\n\t\tthrow new Error(\"auth_device_claim_unavailable\");\n\tconst aliases = keys.filter((key) => hasKeyBlob(key, target.blob));\n\tconst distinctKeys = keys.filter(\n\t\t(key) =>\n\t\t\t!aliases.includes(key) && parseSshEd25519PublicKeyForRevocation(key).kind === \"ed25519\",\n\t);\n\tconst assignmentSnapshot = captureCurrentLegacyAssignment(row?.assignment_snapshot, {\n\t\tcoordinatorId: c.coordinatorId,\n\t\tidentityId: i.identityId,\n\t\tsigner: i.signer,\n\t\tdistinctKeys,\n\t});\n\treturn {\n\t\tidentityId: i.identityId,\n\t\tconnectionSession: row?.connection_session === 1,\n\t\tvalues: [\n\t\t\tc.coordinatorId,\n\t\t\ti.identityId,\n\t\t\ti.signer.groupId,\n\t\t\ti.signer.deviceId,\n\t\t\ti.signer.publicKey,\n\t\t\ti.signer.fingerprint,\n\t\t\tkeyId,\n\t\t\tnow,\n\t\t\tnew Date(now).toISOString(),\n\t\t\ti.attemptId,\n\t\t\tc.issuer,\n\t\t\tc.revision,\n\t\t\tJSON.stringify(keys),\n\t\t\tJSON.stringify(aliases),\n\t\t\tassignmentSnapshot,\n\t\t],\n\t};\n}\n","import { hasConnectionSessionSchema } from \"./coordinator-account-connection-session.js\";\nimport {\n\tAUTH_DEVICE_CLAIM_CURRENT_SUBJECT_COMPATIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_INPUT_SQL,\n\tAUTH_DEVICE_CLAIM_LEGACY_COMPATIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_REQUESTER_ATTESTATION_COMPATIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_REQUESTER_INVITE_COMPATIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_REQUESTER_LINK_COMPATIBLE_SQL,\n\tcaptureDeviceClaimEligibility,\n} from \"./coordinator-auth-device-claim-eligibility.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport type {\n\tCoordinatorAuthLinkConfig,\n\tCoordinatorAuthLinkSigner,\n} from \"./coordinator-auth-link-contract.js\";\nimport { authClaimGenesisSql } from \"./coordinator-auth-link-provenance.js\";\n\n/** Additive definitions installed by the explicit account-schema migration. */\nexport { CONNECTION_LINK_SCHEMA_STATEMENTS } from \"./coordinator-account-connection-schema.js\";\n\n/** p is the captured requester, d its original immutable claim. Head lookup is\n * one indexed row; the archived genesis is addressed by claim_id, not recursion. */\nexport const CONNECTION_RELINK_ELIGIBLE_SQL = `(EXISTS (SELECT 1 FROM coordinator_auth_device_claims d\n WHERE (d.coordinator_id = p.coordinator_id AND d.identity_id = p.identity_id AND d.group_id = p.group_id)\n AND (d.device_id = p.device_id AND d.public_key = p.public_key AND d.fingerprint = p.fingerprint)\n AND (d.key_id = p.key_id AND d.issuer = p.issuer) AND ${authClaimGenesisSql(\"d\")})\n AND EXISTS (SELECT 1 FROM enrolled_devices e JOIN groups g ON g.group_id = e.group_id WHERE (e.group_id = p.group_id AND e.device_id = p.device_id AND e.public_key = p.public_key AND e.fingerprint = p.fingerprint) AND (e.enabled = 1 AND g.archived_at IS NULL AND (e.identity_id IS NULL OR e.identity_id = p.identity_id)))\n AND NOT EXISTS (SELECT 1 FROM coordinator_device_revocations r WHERE (r.subject_kind = 'device_id' AND r.subject_value = p.device_id) OR (r.subject_kind = 'ed25519_key' AND r.subject_value = p.key_id)))\n AND (NOT EXISTS (SELECT 1 FROM coordinator_auth_account_links l WHERE l.coordinator_id = p.coordinator_id AND l.identity_id = p.identity_id)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id = p.coordinator_id AND h.identity_id = p.identity_id AND h.revoked_at_ms IS NOT NULL)\n AND EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id = p.coordinator_id AND h.identity_id = p.identity_id AND h.successor_link_id IS NULL))\n AND ((${AUTH_DEVICE_CLAIM_CURRENT_SUBJECT_COMPATIBLE_SQL}) AND (${AUTH_DEVICE_CLAIM_REQUESTER_ATTESTATION_COMPATIBLE_SQL}))\n AND ((${AUTH_DEVICE_CLAIM_REQUESTER_INVITE_COMPATIBLE_SQL}) AND (${AUTH_DEVICE_CLAIM_REQUESTER_LINK_COMPATIBLE_SQL}) AND (${AUTH_DEVICE_CLAIM_LEGACY_COMPATIBLE_SQL}))`;\n\n/** A renewed same-Identity review is distinct from a contradictory assignment. */\nexport const CONNECTION_REQUESTER_ATTESTATION_IDENTITY_SQL = `NOT EXISTS (SELECT 1 FROM coordinator_auth_controller_attestations a\n WHERE a.coordinator_id=p.coordinator_id AND (a.device_id=p.device_id OR EXISTS (SELECT 1 FROM claim_same_keys k WHERE k.value=a.public_key)) AND a.identity_id<>p.identity_id)`;\nconst otherIdentityClaimSql = (\n\textra: string,\n) => `NOT EXISTS (SELECT 1 FROM coordinator_auth_device_claims d\n WHERE d.coordinator_id=p.coordinator_id AND (d.device_id=p.device_id OR d.key_id=p.key_id) AND d.identity_id<>p.identity_id${extra})`;\nexport const CONNECTION_REQUESTER_IDENTITY_SQL = `${CONNECTION_REQUESTER_ATTESTATION_IDENTITY_SQL}\n AND ${otherIdentityClaimSql(\"\")}`;\n/**\n * With an ownership binding, this device's own claim under its previous\n * Identity is superseded once that Identity has no active link (ADR 0005 S8).\n */\nexport const CONNECTION_REQUESTER_ACTIVE_OTHER_CLAIM_SQL = otherIdentityClaimSql(`\n AND EXISTS (SELECT 1 FROM coordinator_auth_account_links l WHERE l.coordinator_id=d.coordinator_id\n AND l.identity_id=d.identity_id AND l.revoked_at_ms IS NULL)`);\n/** Additional contradictions only: the outer writer must independently require\n * its exact live attestation, current enrollment snapshot and revocation checks. */\nexport async function connectionRequesterGuard(\n\tbackend: AuthLinkBackend,\n\tidentityId: string,\n\tsigner: CoordinatorAuthLinkSigner,\n\tconfig: CoordinatorAuthLinkConfig,\n\tnow: number,\n): Promise<AuthLinkStatement> {\n\tconst p = await captureDeviceClaimEligibility(backend, { identityId, signer }, config, now);\n\tif (!p) return { sql: \"0 = 1\", values: [] };\n\treturn {\n\t\tsql: `EXISTS (${AUTH_DEVICE_CLAIM_INPUT_SQL} SELECT 1 FROM claim_input p WHERE (${AUTH_DEVICE_CLAIM_CURRENT_SUBJECT_COMPATIBLE_SQL}) AND (${CONNECTION_REQUESTER_IDENTITY_SQL}) AND (${AUTH_DEVICE_CLAIM_REQUESTER_INVITE_COMPATIBLE_SQL}) AND (${AUTH_DEVICE_CLAIM_REQUESTER_LINK_COMPATIBLE_SQL}) AND (${AUTH_DEVICE_CLAIM_LEGACY_COMPATIBLE_SQL}))`,\n\t\tvalues: p.values,\n\t};\n}\n\n/** t is the exact winning attempt; source authority is checked independently. */\nexport function connectionFinalizeGuard(t: \"coordinator_auth_link_attempts\"): string {\n\treturn `NOT EXISTS (SELECT 1 FROM coordinator_auth_account_links l WHERE l.coordinator_id = ${t}.coordinator_id AND l.identity_id = ${t}.identity_id)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id = ${t}.coordinator_id AND h.identity_id = ${t}.identity_id AND h.revoked_at_ms IS NOT NULL)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id = ${t}.coordinator_id AND h.issuer = ${t}.issuer AND h.subject = ${t}.account_subject AND h.identity_id <> ${t}.identity_id)\n AND ((${t}.prior_link_id IS NULL AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id = ${t}.coordinator_id AND h.identity_id = ${t}.identity_id)) OR EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id = ${t}.coordinator_id AND h.identity_id = ${t}.identity_id AND h.link_id = ${t}.prior_link_id AND h.successor_link_id IS NULL))`;\n}\n\n/** Pin the server's head in the same transaction as an attested/first creation.\n * The INSERT must be fresh; exact retries are handled by the existing reader. */\nexport async function createPinnedConnection(\n\tbackend: AuthLinkBackend,\n\tstatement: AuthLinkStatement,\n\tpin: { coordinator: string; attempt: string; identity: string; now: number },\n): Promise<number> {\n\tif (!(await hasConnectionSessionSchema(backend))) return backend.run(statement);\n\tconst head = await backend.first<{ link_id: string }>({\n\t\tsql: \"SELECT link_id FROM coordinator_auth_account_connection_history WHERE coordinator_id = ? AND identity_id = ? AND successor_link_id IS NULL\",\n\t\tvalues: [pin.coordinator, pin.identity],\n\t});\n\tawait backend.batch([\n\t\tstatement,\n\t\t{\n\t\t\tsql: `UPDATE coordinator_auth_link_attempts AS t SET prior_link_id = ? WHERE changes() = 1 AND t.coordinator_id = ? AND t.attempt_id = ? AND t.state = 'pending' AND t.created_at_ms = ?\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_links l WHERE l.coordinator_id = t.coordinator_id AND l.identity_id = t.identity_id)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id = t.coordinator_id AND h.identity_id = t.identity_id AND h.revoked_at_ms IS NOT NULL)\n AND ((? IS NULL AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id = t.coordinator_id AND h.identity_id = t.identity_id)) OR EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id = t.coordinator_id AND h.identity_id = t.identity_id AND h.link_id = ? AND h.successor_link_id IS NULL))`,\n\t\t\tvalues: [\n\t\t\t\thead?.link_id ?? null,\n\t\t\t\tpin.coordinator,\n\t\t\t\tpin.attempt,\n\t\t\t\tpin.now,\n\t\t\t\thead?.link_id ?? null,\n\t\t\t\thead?.link_id ?? null,\n\t\t\t],\n\t\t},\n\t\t{\n\t\t\tsql: \"INSERT INTO coordinator_auth_account_connection_orders (coordinator_id,last_order) SELECT NULL,0 WHERE changes() <> 1\",\n\t\t\tvalues: [],\n\t\t},\n\t]);\n\treturn 1;\n}\n\n/** Append after current/audit publication, before profile/session exposure. */\nexport function connectionSuccessorStatements(\n\tcoordinator: string,\n\tattempt: string,\n\tlink: string,\n): AuthLinkStatement[] {\n\tconst pins = [coordinator, attempt, link];\n\treturn [\n\t\t{\n\t\t\tsql: `UPDATE coordinator_auth_account_connection_history SET successor_link_id = ? WHERE successor_link_id IS NULL AND coordinator_id = ? AND link_id = (SELECT prior_link_id FROM coordinator_auth_link_attempts WHERE coordinator_id = ? AND attempt_id = ? AND link_id = ? AND state = 'finalized')`,\n\t\t\tvalues: [link, coordinator, ...pins],\n\t\t},\n\t\t{\n\t\t\tsql: `INSERT INTO coordinator_auth_account_connection_orders (coordinator_id,last_order) SELECT NULL,0 WHERE changes() <> 1 AND EXISTS (SELECT 1 FROM coordinator_auth_link_attempts WHERE coordinator_id = ? AND attempt_id = ? AND link_id = ? AND state = 'finalized' AND prior_link_id IS NOT NULL)`,\n\t\t\tvalues: pins,\n\t\t},\n\t];\n}\n","import type { CoordinatorAuthLinkConfig } from \"./coordinator-auth-link-contract.js\";\nimport type { CoordinatorAuthSession } from \"./coordinator-auth-session-contract.js\";\nimport type { CoordinatorOidcProfile } from \"./coordinator-oidc.js\";\n\nexport const AUTH_ACCOUNT_PROFILE_WRITE_WINDOW_MS = 120000;\nexport interface CoordinatorAuthAccountProfileInput {\n\tcredentialHash: string;\n\tprofile: unknown;\n}\nexport type CoordinatorAuthAccountProfileWriteResult =\n\t| { kind: \"recorded\" }\n\t| { kind: \"not_recorded\" }\n\t| { kind: \"rejected\"; error: \"invalid_input\" | \"auth_config_changed\" };\nexport interface CoordinatorAuthSessionAccount {\n\tsession: CoordinatorAuthSession;\n\tprofile: CoordinatorOidcProfile;\n}\nexport type CoordinatorAuthAccountProfileClearResult =\n\t| { kind: \"cleared\"; deletedCount: number }\n\t| { kind: \"rejected\"; error: \"invalid_input\" };\n/** Display only. Callers must verify OIDC before writing and configured-admin authority\n * before clearing. These operations never issue sessions or grant authority.\n */\nexport interface CoordinatorAuthAccountProfileStore {\n\trecordAuthAccountProfile(\n\t\tinput: CoordinatorAuthAccountProfileInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthAccountProfileWriteResult>;\n\treadAuthSessionAccount(\n\t\tcredentialHash: string,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthSessionAccount | null>;\n\tclearRevokedAuthAccountProfile(\n\t\tinput: { linkId: string },\n\t\tscope: { coordinatorId: string },\n\t): Promise<CoordinatorAuthAccountProfileClearResult>;\n}\n\n// Empty metadata table only: no foreign keys, backfill, or startup writes.\nexport const AUTH_ACCOUNT_PROFILE_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS coordinator_auth_account_profiles (\n coordinator_id TEXT NOT NULL,\n link_id TEXT NOT NULL,\n display_name TEXT CHECK (display_name IS NULL OR (typeof(display_name) = 'text' AND length(display_name) BETWEEN 1 AND 256)),\n email TEXT CHECK (email IS NULL OR (typeof(email) = 'text' AND length(email) BETWEEN 1 AND 320)),\n email_verified INTEGER CHECK (email_verified IS NULL OR (typeof(email_verified) = 'integer' AND email_verified IN (0,1) AND email IS NOT NULL)),\n picture_url TEXT CHECK (picture_url IS NULL OR (typeof(picture_url) = 'text' AND length(picture_url) BETWEEN 1 AND 2048 AND substr(picture_url, 1, 8) = 'https://')),\n source_session_id TEXT NOT NULL,\n source_signed_in_at_ms INTEGER NOT NULL CHECK (typeof(source_signed_in_at_ms) = 'integer' AND source_signed_in_at_ms BETWEEN 0 AND 9007199225940991),\n PRIMARY KEY (coordinator_id, link_id)\n);`;\n","/**\n * Authority contract for coordinator account links.\n *\n * Every link attempt, account link, and link audit row names its authority source:\n * - `controller_attestation`: an admin-reviewed attestation for the exact enrolled key.\n * - `device_claim`: an eligible enrolled-key claim while an attempt is pending.\n * Link and audit rows reference proof committed after Google verification and\n * device finalization. It is never an operator review.\n *\n * Rows store the kind explicitly and reference only the record that matches it.\n * Readers must fail closed on any row whose references disagree with its kind.\n */\n\nimport { isAuthControllerId as isReference } from \"./coordinator-auth-controller.js\";\n\nexport const AUTH_LINK_AUTHORITY_KINDS = [\"controller_attestation\", \"device_claim\"] as const;\nexport type CoordinatorAuthLinkAuthorityKind = (typeof AUTH_LINK_AUTHORITY_KINDS)[number];\n\nexport type CoordinatorAuthLinkAttemptAuthority =\n\t| {\n\t\t\tkind: \"controller_attestation\";\n\t\t\tcontrollerAttestationId: string;\n\t\t\tcontrollerReviewReceiptId: string;\n\t }\n\t| { kind: \"device_claim\" };\n\nexport type CoordinatorAuthLinkRecordAuthority =\n\t| { kind: \"controller_attestation\"; controllerAttestationId: string }\n\t| { kind: \"device_claim\"; deviceClaimId: string };\n\n/** Link-attempt columns. A pending device claim has no committed claim record yet. */\nexport interface AuthLinkAttemptAuthorityRow {\n\tauthority_kind: unknown;\n\tcontroller_attestation_id: unknown;\n\tcontroller_review_receipt_id: unknown;\n\tcontroller_revision: unknown;\n}\n\n/** Account-link and audit columns. */\nexport interface AuthLinkRecordAuthorityRow {\n\tauthority_kind: unknown;\n\tcontroller_attestation_id: unknown;\n\tdevice_claim_id: unknown;\n}\n\n/** Returns null for a corrupt row; callers must treat that as no authority. */\nexport function readAuthLinkAttemptAuthority(\n\trow: AuthLinkAttemptAuthorityRow,\n): CoordinatorAuthLinkAttemptAuthority | null {\n\tif (row.authority_kind === \"device_claim\") {\n\t\tconst unreferenced =\n\t\t\trow.controller_attestation_id === null &&\n\t\t\trow.controller_review_receipt_id === null &&\n\t\t\trow.controller_revision === null;\n\t\treturn unreferenced ? { kind: \"device_claim\" } : null;\n\t}\n\tif (row.authority_kind !== \"controller_attestation\") return null;\n\tif (\n\t\t!isReference(row.controller_attestation_id) ||\n\t\t!isReference(row.controller_review_receipt_id) ||\n\t\trow.controller_revision !== 1\n\t)\n\t\treturn null;\n\treturn {\n\t\tkind: \"controller_attestation\",\n\t\tcontrollerAttestationId: row.controller_attestation_id,\n\t\tcontrollerReviewReceiptId: row.controller_review_receipt_id,\n\t};\n}\n\n/** Returns null for a corrupt row; callers must treat that as no authority. */\nexport function readAuthLinkRecordAuthority(\n\trow: AuthLinkRecordAuthorityRow,\n): CoordinatorAuthLinkRecordAuthority | null {\n\tif (row.authority_kind === \"device_claim\") {\n\t\tif (row.controller_attestation_id !== null || !isReference(row.device_claim_id)) return null;\n\t\treturn { kind: \"device_claim\", deviceClaimId: row.device_claim_id };\n\t}\n\tif (row.authority_kind !== \"controller_attestation\") return null;\n\tif (!isReference(row.controller_attestation_id) || row.device_claim_id !== null) return null;\n\treturn { kind: \"controller_attestation\", controllerAttestationId: row.controller_attestation_id };\n}\n\n/**\n * Operator-only consumers accept no other source kind. This classifies a stored\n * reference, not caller permission. In-flight links revalidate their source;\n * completed-link consumers apply historical-provenance and active-link checks.\n */\nexport function isOperatorReviewedAuthority(\n\tauthority: CoordinatorAuthLinkRecordAuthority | null,\n): boolean {\n\treturn authority?.kind === \"controller_attestation\";\n}\n\ninterface AccountLinkStatusSubject {\n\tversion: 2;\n\tcoordinatorId: string;\n\tgroupId: string;\n\tdeviceId: string;\n\tfingerprint: string;\n}\ntype AccountMetadata = { email?: string; displayName?: string; pictureUrl?: string };\n\n/**\n * Signed-device account-link status for the requested Identity.\n * `unlinked` is eligibility only; for `device_claim` nothing is verified or\n * reserved until the same operation's device finalization commits.\n * `account` is null whenever the link Identity differs from the requested one, or\n * the requester holds no claim or attestation of its own (ADR 0005 Section 8).\n */\nexport type CoordinatorAccountLinkStatusV2 = AccountLinkStatusSubject &\n\t(\n\t\t| {\n\t\t\t\tstate: \"review_required\" | \"conflict\";\n\t\t\t\tidentityId: null;\n\t\t\t\tauthority: null;\n\t\t\t\taccount: null;\n\t\t }\n\t\t| {\n\t\t\t\tstate: \"unlinked\";\n\t\t\t\tidentityId: string;\n\t\t\t\tauthority: CoordinatorAuthLinkAuthorityKind;\n\t\t\t\taccount: null;\n\t\t }\n\t\t| {\n\t\t\t\tstate: \"linked\";\n\t\t\t\tidentityId: string;\n\t\t\t\tauthority: CoordinatorAuthLinkAuthorityKind;\n\t\t\t\taccount: AccountMetadata | null;\n\t\t }\n\t\t| {\n\t\t\t\tstate: \"revoked\";\n\t\t\t\tidentityId: string;\n\t\t\t\tauthority: CoordinatorAuthLinkAuthorityKind;\n\t\t\t\taccount: null;\n\t\t }\n\t);\n","import { CONNECTION_RELINK_ELIGIBLE_SQL } from \"./coordinator-account-connection-link.js\";\nimport { hasConnectionSessionSchema } from \"./coordinator-account-connection-session.js\";\nimport {\n\tAUTH_DEVICE_CLAIM_ELIGIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_INPUT_SQL,\n\tcaptureDeviceClaimEligibility,\n} from \"./coordinator-auth-device-claim-eligibility.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport type { AuthLinkAttemptAuthorityRow } from \"./coordinator-auth-link-authority.js\";\nimport { readAuthLinkAttemptAuthority } from \"./coordinator-auth-link-authority.js\";\nimport type { CoordinatorAuthLinkConfig } from \"./coordinator-auth-link-contract.js\";\nimport {\n\tauthDeviceClaimProvenanceSql,\n\tCONNECTION_BIRTHS_SQL,\n} from \"./coordinator-auth-link-provenance.js\";\nimport { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\n\ninterface SourceRow extends AuthLinkAttemptAuthorityRow {\n\tprior_link_id?: string | null;\n\tidentity_id: string;\n\tgroup_id: string;\n\tdevice_id: string;\n\tpublic_key: string;\n\tfingerprint: string;\n\truntime_verifier_hash: string;\n\tbrowser_start_hash: string | null;\n\tloopback_redirect: string;\n\tstate: string;\n\tcompletion_secret_hash: string | null;\n}\n/** Private predicate preparation, never a browser status or authorization result. */\nexport async function captureAuthLinkBrowserSource(\n\tbackend: Pick<AuthLinkBackend, \"first\">,\n\ti: { binderHash: string; stateHash?: string; attemptId?: string },\n\tc: CoordinatorAuthLinkConfig & { redirectUri: string },\n\tnow: number,\n): Promise<AuthLinkStatement> {\n\tconst row = await backend.first<{ attempt_id: string | null }>({\n\t\tsql: `SELECT attempt_id FROM coordinator_auth_browser_transactions b WHERE b.coordinator_id = ? AND b.issuer = ? AND b.auth_config_revision = ? AND b.redirect_uri = ? AND b.binder_hash = ?\n AND (? IS NULL OR b.state_hash = ?) AND (? IS NULL OR b.attempt_id = ?) AND b.purpose = 'link'`,\n\t\tvalues: [\n\t\t\tc.coordinatorId,\n\t\t\tc.issuer,\n\t\t\tc.revision,\n\t\t\tc.redirectUri,\n\t\t\ti.binderHash,\n\t\t\ti.stateHash ?? null,\n\t\t\ti.stateHash ?? null,\n\t\t\ti.attemptId ?? null,\n\t\t\ti.attemptId ?? null,\n\t\t],\n\t});\n\tif (!row?.attempt_id) return { sql: \"0 = 1\", values: [] };\n\treturn captureAuthLinkSource(backend, row.attempt_id, c, now, \"a\");\n}\n\n/** Fresh capture for one operation; the winning statement must include its SQL. */\nexport async function captureAuthLinkSource(\n\tbackend: Pick<AuthLinkBackend, \"first\">,\n\tattemptId: string,\n\tconfig: CoordinatorAuthLinkConfig,\n\tnow: number,\n\talias: \"a\" | \"coordinator_auth_link_attempts\" = \"coordinator_auth_link_attempts\",\n\toptions: { currentDevice?: boolean } = {},\n): Promise<AuthLinkStatement> {\n\tconst row = await backend.first<SourceRow>({\n\t\tsql: \"SELECT * FROM coordinator_auth_link_attempts WHERE coordinator_id = ? AND attempt_id = ?\",\n\t\tvalues: [config.coordinatorId, attemptId],\n\t});\n\tconst authority = row && readAuthLinkAttemptAuthority(row);\n\tif (!row || !authority) return { sql: \"0 = 1\", values: [] };\n\tif (authority.kind === \"controller_attestation\")\n\t\treturn { sql: `${alias}.authority_kind = 'controller_attestation'`, values: [] };\n\tif ([\"finalized\", \"session_redeemed\"].includes(row.state)) {\n\t\tconst connections = await hasConnectionSessionSchema(backend);\n\t\tconst keyId = await ed25519KeyIdForRevocation(row.public_key);\n\t\tif (!keyId || row.browser_start_hash === null || row.completion_secret_hash === null)\n\t\t\treturn { sql: \"0 = 1\", values: [] };\n\t\treturn {\n\t\t\tsql: `(${alias}.authority_kind = 'device_claim'\n AND ${alias}.controller_attestation_id IS NULL AND ${alias}.controller_review_receipt_id IS NULL AND ${alias}.controller_revision IS NULL\n AND ${alias}.state IN ('finalized','session_redeemed') AND ${alias}.browser_start_hash = ?\n AND ${alias}.runtime_verifier_hash = ? AND ${alias}.completion_secret_hash = ? AND ${alias}.loopback_redirect = ?\n AND ${authDeviceClaimReceiptSql(alias, connections)}${options.currentDevice ? ` AND ${currentDeviceSql(alias)}` : \"\"})`,\n\t\t\tvalues: [\n\t\t\t\trow.browser_start_hash,\n\t\t\t\trow.runtime_verifier_hash,\n\t\t\t\trow.completion_secret_hash,\n\t\t\t\trow.loopback_redirect,\n\t\t\t\tkeyId,\n\t\t\t\t...(options.currentDevice ? [keyId] : []),\n\t\t\t],\n\t\t};\n\t}\n\tconst captured = await captureDeviceClaimEligibility(\n\t\tbackend,\n\t\t{\n\t\t\tattemptId,\n\t\t\tidentityId: row.identity_id,\n\t\t\tsigner: {\n\t\t\t\tgroupId: row.group_id,\n\t\t\t\tdeviceId: row.device_id,\n\t\t\t\tpublicKey: row.public_key,\n\t\t\t\tfingerprint: row.fingerprint,\n\t\t\t},\n\t\t},\n\t\tconfig,\n\t\tnow,\n\t);\n\tif (!captured || row.browser_start_hash === null) return { sql: \"0 = 1\", values: [] };\n\tif (row.prior_link_id)\n\t\treturn {\n\t\t\tsql: `((${alias}.authority_kind = 'device_claim' AND ${alias}.controller_attestation_id IS NULL AND ${alias}.controller_review_receipt_id IS NULL AND ${alias}.controller_revision IS NULL) AND (${alias}.link_id IS NULL AND ${alias}.prior_link_id = ?)\n AND EXISTS (${AUTH_DEVICE_CLAIM_INPUT_SQL}, connection_eligible AS MATERIALIZED (SELECT p.* FROM claim_input p WHERE ${CONNECTION_RELINK_ELIGIBLE_SQL})\n SELECT 1 FROM connection_eligible p WHERE (p.coordinator_id=${alias}.coordinator_id AND p.attempt_id=${alias}.attempt_id AND p.identity_id=${alias}.identity_id)\n AND (p.group_id=${alias}.group_id AND p.device_id=${alias}.device_id AND p.public_key=${alias}.public_key AND p.fingerprint=${alias}.fingerprint) AND (p.issuer=${alias}.issuer AND p.revision=${alias}.auth_config_revision)\n AND EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id=p.coordinator_id AND h.identity_id=p.identity_id AND h.link_id=${alias}.prior_link_id AND h.successor_link_id IS NULL)))`,\n\t\t\tvalues: [row.prior_link_id, ...captured.values],\n\t\t};\n\t// Separate the full predicate from the correlated browser match to stay below\n\t// native D1's expression-depth limit, without moving authority outside SQL.\n\treturn {\n\t\tsql: `(${alias}.authority_kind = 'device_claim'\n AND ${alias}.controller_attestation_id IS NULL AND ${alias}.controller_review_receipt_id IS NULL\n AND ${alias}.controller_revision IS NULL AND ${alias}.link_id IS NULL\n AND ${alias}.runtime_verifier_hash = ? AND ${alias}.browser_start_hash = ? AND ${alias}.loopback_redirect = ?\n AND EXISTS (${AUTH_DEVICE_CLAIM_INPUT_SQL}, claim_eligible AS MATERIALIZED (\n SELECT p.* FROM claim_input p WHERE ${AUTH_DEVICE_CLAIM_ELIGIBLE_SQL})\n SELECT 1 FROM claim_eligible p\n WHERE ${alias}.coordinator_id = p.coordinator_id AND ${alias}.attempt_id = p.attempt_id\n AND ${alias}.identity_id = p.identity_id AND ${alias}.group_id = p.group_id\n AND ${alias}.device_id = p.device_id AND ${alias}.public_key = p.public_key AND ${alias}.fingerprint = p.fingerprint\n AND ${alias}.issuer = p.issuer AND ${alias}.auth_config_revision = p.revision))`,\n\t\tvalues: [\n\t\t\trow.runtime_verifier_hash,\n\t\t\trow.browser_start_hash,\n\t\t\trow.loopback_redirect,\n\t\t\t...captured.values,\n\t\t],\n\t};\n}\n\nfunction currentDeviceSql(t: string): string {\n\treturn `EXISTS (SELECT 1 FROM enrolled_devices e JOIN groups g ON g.group_id = e.group_id\n WHERE e.group_id = ${t}.group_id AND e.device_id = ${t}.device_id AND e.public_key = ${t}.public_key\n AND e.fingerprint = ${t}.fingerprint AND e.enabled = 1 AND g.archived_at IS NULL\n AND (e.identity_id IS NULL OR e.identity_id = ${t}.identity_id))\n AND NOT EXISTS (SELECT 1 FROM coordinator_device_revocations r\n WHERE (r.subject_kind = 'device_id' AND r.subject_value = ${t}.device_id)\n OR (r.subject_kind = 'ed25519_key' AND r.subject_value = ?))`;\n}\n\n/** Historical committed provenance, not first-binding eligibility or operator authority.\n * The caller binds the canonical key ID derived from the attempt's exact public key.\n */\nfunction authDeviceClaimReceiptSql(t: string, connections: boolean): string {\n\t// Separate the indexed receipt match from its unchanged provenance expression\n\t// so the browser's enclosing predicate stays below native D1 depth 100.\n\treturn `EXISTS (WITH receipt_birth AS MATERIALIZED (\n SELECT cl.* FROM ${connections ? `(${CONNECTION_BIRTHS_SQL})` : \"coordinator_auth_account_links\"} cl\n WHERE cl.coordinator_id = ${t}.coordinator_id AND cl.link_id = ${t}.link_id AND cl.attempt_id = ${t}.attempt_id\n AND cl.revoked_at_ms IS NULL)\n SELECT 1 FROM receipt_birth cl WHERE ${authDeviceClaimProvenanceSql({ link: \"cl\", canonicalKeyId: \"?\", connections })})`;\n}\n","import {\n\tAUTH_SCHEMA_UPGRADE_MESSAGE,\n\tAUTH_SCHEMA_UPGRADE_REQUIRED,\n\tAUTH_V2_SCHEMA_READINESS_SQL,\n\tCoordinatorAuthSchemaUpgradeRequiredError,\n\treadConnectionSchemaState,\n} from \"./coordinator-account-connection-schema.js\";\n\nexport {\n\tAUTH_SCHEMA_UPGRADE_MESSAGE,\n\tAUTH_SCHEMA_UPGRADE_REQUIRED,\n\tCoordinatorAuthSchemaUpgradeRequiredError,\n} from \"./coordinator-account-connection-schema.js\";\n\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport {\n\tcaptureAuthLinkBrowserSource,\n\tcaptureAuthLinkSource,\n} from \"./coordinator-auth-link-source.js\";\n\n// Inspect five authority columns, four proof definitions and the display staging table.\n// No writes or I/O cache; unknown proof variants fail closed.\nexport const AUTH_SCHEMA_READY_COUNT = 10;\nexport const AUTH_SCHEMA_READINESS_SQL = AUTH_V2_SCHEMA_READINESS_SQL;\n\nexport interface CoordinatorAuthSchemaStore {\n\tassertAuthSchemaReady(): Promise<void>;\n}\n\nexport async function assertCoordinatorAuthSchema(\n\tbackend: Pick<AuthLinkBackend, \"first\">,\n\toptions: { connections?: boolean } = {},\n): Promise<void> {\n\tconst state = await readConnectionSchemaState(backend);\n\tif (state === \"upgrade_required\" || (options.connections && state !== \"ready\"))\n\t\tthrow new CoordinatorAuthSchemaUpgradeRequiredError();\n}\n\n/** Protect every optional-auth SQL entry, including trusted callers outside HTTP. */\nexport function withCoordinatorAuthSchema(\n\tbackend: AuthLinkBackend,\n\toptions: { connections?: boolean } = {},\n): AuthLinkBackend {\n\treturn {\n\t\tprepareAuthLinkSource: (...args) => captureAuthLinkSource(backend, ...args),\n\t\tprepareAuthLinkBrowserSource: (...args) => captureAuthLinkBrowserSource(backend, ...args),\n\t\treadAuthSchemaState: () => readConnectionSchemaState(backend),\n\t\tfirst: async <T>(statement: AuthLinkStatement) => {\n\t\t\tawait assertCoordinatorAuthSchema(backend, options);\n\t\t\treturn backend.first<T>(statement);\n\t\t},\n\t\tall: async <T>(statement: AuthLinkStatement) => {\n\t\t\tawait assertCoordinatorAuthSchema(backend, options);\n\t\t\tif (!backend.all) throw new Error(\"ownership_evidence_reader_unavailable\");\n\t\t\treturn backend.all<T>(statement);\n\t\t},\n\t\trun: async (statement) => {\n\t\t\tawait assertCoordinatorAuthSchema(backend, options);\n\t\t\treturn backend.run(statement);\n\t\t},\n\t\tbatch: async (statements) => {\n\t\t\tawait assertCoordinatorAuthSchema(backend, options);\n\t\t\treturn backend.batch(statements);\n\t\t},\n\t};\n}\n\nexport function authPersistenceError(error: unknown, fallback: string): Error {\n\tif (String(error).includes(\"no such table: coordinator_auth_link_profiles\"))\n\t\treturn new CoordinatorAuthSchemaUpgradeRequiredError();\n\treturn error instanceof CoordinatorAuthSchemaUpgradeRequiredError ? error : new Error(fallback);\n}\n\nexport async function assertConfiguredAuthSchema(\n\tstore: Partial<CoordinatorAuthSchemaStore>,\n): Promise<void> {\n\tif (typeof store.assertAuthSchemaReady !== \"function\")\n\t\tthrow new Error(\"auth_schema_readiness_unavailable\");\n\tawait store.assertAuthSchemaReady();\n}\n\nexport function authSchemaUpgradeResponse(): Response {\n\treturn Response.json(\n\t\t{ error: AUTH_SCHEMA_UPGRADE_REQUIRED, message: AUTH_SCHEMA_UPGRADE_MESSAGE },\n\t\t{\n\t\t\tstatus: 503,\n\t\t\theaders: {\n\t\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\t\"X-Codemem-Auth-Error\": AUTH_SCHEMA_UPGRADE_REQUIRED,\n\t\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\t},\n\t\t},\n\t);\n}\n","import { CONNECTION_BIRTH_COLUMNS } from \"./coordinator-account-connection-storage.js\";\nimport type { AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport { authAccountLinkProvenanceSql } from \"./coordinator-auth-link-provenance.js\";\n\nconst history = \"coordinator_auth_account_connection_history\";\nconst current = \"coordinator_auth_account_links\";\nconst audit = \"coordinator_auth_link_audit_log\";\nconst auditColumns =\n\t\"coordinator_id,link_id,action,attempt_id,identity_id,group_id,device_id,fingerprint,controller_attestation_id,auth_config_revision,created_at_ms,authority_kind,device_claim_id\";\nconst birthMatch = `a.coordinator_id=l.coordinator_id AND a.link_id=l.link_id AND a.action='link_created'\n AND (a.attempt_id=l.attempt_id AND a.identity_id=l.identity_id AND a.controller_attestation_id IS l.controller_attestation_id)\n AND (a.authority_kind=l.authority_kind AND a.device_claim_id IS l.device_claim_id AND a.auth_config_revision=l.auth_config_revision AND a.created_at_ms=l.created_at_ms)`;\nconst receiptMatch = `r.coordinator_id=l.coordinator_id AND r.link_id=l.link_id AND r.action='link_revoked'\n AND (r.attempt_id=a.attempt_id AND r.identity_id=a.identity_id AND r.group_id=a.group_id AND r.device_id=a.device_id AND r.fingerprint=a.fingerprint)\n AND (r.controller_attestation_id IS a.controller_attestation_id AND r.authority_kind=a.authority_kind AND r.device_claim_id IS a.device_claim_id AND r.auth_config_revision=a.auth_config_revision AND r.created_at_ms=l.revoked_at_ms)`;\nfunction context(): string {\n\treturn `WITH requested AS MATERIALIZED (SELECT l.* FROM ${history} l WHERE (l.coordinator_id=? AND l.link_id=?) AND (${authAccountLinkProvenanceSql(\"l\", { connections: true })})),\n current_targets AS MATERIALIZED (SELECT l.* FROM ${current} l JOIN requested h ON h.coordinator_id=l.coordinator_id AND h.identity_id=l.identity_id),\n valid_current AS MATERIALIZED (SELECT l.coordinator_id,l.link_id FROM current_targets l WHERE ${authAccountLinkProvenanceSql(\"l\", { connections: true })})`;\n}\n/** Audit proof is historical equality, not liveness: it remains valid after flags change. */\nexport function historicalRevocationReadSql(): string {\n\tconst columns = CONNECTION_BIRTH_COLUMNS.join(\",\");\n\treturn `/* historical_revocation_complete */ ${context()},\n auditable_links AS MATERIALIZED (SELECT ${columns} FROM requested UNION ALL SELECT ${CONNECTION_BIRTH_COLUMNS.map((c) => `l.${c}`).join(\",\")} FROM current_targets l JOIN valid_current v ON v.coordinator_id=l.coordinator_id AND v.link_id=l.link_id),\n receipts AS MATERIALIZED (SELECT l.coordinator_id,l.link_id FROM auditable_links l JOIN ${audit} a ON ${birthMatch} JOIN ${audit} r ON ${receiptMatch} WHERE l.revoked_at_ms IS NOT NULL)\n SELECT 1 AS revoked FROM requested h WHERE h.revoked_at_ms IS NOT NULL\n AND EXISTS (SELECT 1 FROM receipts r WHERE r.coordinator_id=h.coordinator_id AND r.link_id=h.link_id)\n AND NOT EXISTS (SELECT 1 FROM current_targets c LEFT JOIN receipts r ON r.coordinator_id=c.coordinator_id AND r.link_id=c.link_id WHERE c.revoked_at_ms IS NULL OR r.link_id IS NULL)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_sessions s WHERE s.coordinator_id=h.coordinator_id AND s.identity_id=h.identity_id AND s.revoked_at_ms IS NULL)`;\n}\nfunction insertAudit(source: \"requested\" | \"current_targets\"): string {\n\treturn `${context()} INSERT INTO ${audit} (${auditColumns})\n SELECT l.coordinator_id,l.link_id,'link_revoked',a.attempt_id,a.identity_id,a.group_id,a.device_id,a.fingerprint,a.controller_attestation_id,a.auth_config_revision,l.revoked_at_ms,l.authority_kind,l.device_claim_id\n FROM ${source} l ${source === \"current_targets\" ? \"JOIN valid_current v ON v.coordinator_id=l.coordinator_id AND v.link_id=l.link_id\" : \"\"} JOIN ${audit} a ON ${birthMatch} WHERE l.revoked_at_ms IS NOT NULL\n AND NOT EXISTS (SELECT 1 FROM ${audit} r WHERE r.coordinator_id=l.coordinator_id AND r.link_id=l.link_id AND r.action='link_revoked')`;\n}\n/** Derive every replacement from the retained requested Identity inside this one\n * writer transaction; a separately read current-link ID must never drive these effects. */\nexport function historicalRevocationStatements(\n\tcoordinator: string,\n\tlink: string,\n\tnow: number,\n): AuthLinkStatement[] {\n\tconst values = [coordinator, link];\n\treturn [\n\t\t{\n\t\t\tsql: `${context()} UPDATE ${history} AS l SET revoked_at_ms=? WHERE l.revoked_at_ms IS NULL AND EXISTS (SELECT 1 FROM requested h WHERE h.coordinator_id=l.coordinator_id AND h.link_id=l.link_id)`,\n\t\t\tvalues: [...values, now],\n\t\t},\n\t\t{ sql: insertAudit(\"requested\"), values },\n\t\t{\n\t\t\tsql: `${context()} UPDATE ${current} AS l SET revoked_at_ms=(SELECT revoked_at_ms FROM requested) WHERE l.revoked_at_ms IS NULL AND EXISTS (SELECT 1 FROM valid_current v WHERE v.coordinator_id=l.coordinator_id AND v.link_id=l.link_id)`,\n\t\t\tvalues,\n\t\t},\n\t\t{ sql: insertAudit(\"current_targets\"), values },\n\t\t{\n\t\t\tsql: `${context()} UPDATE coordinator_auth_sessions SET revoked_at_ms=(SELECT revoked_at_ms FROM requested) WHERE revoked_at_ms IS NULL AND coordinator_id=? AND identity_id=(SELECT identity_id FROM requested)`,\n\t\t\tvalues: [...values, coordinator],\n\t\t},\n\t\t// A standalone invalid insert fails even when a trigger ignored a required effect.\n\t\t{\n\t\t\tsql: `INSERT INTO coordinator_auth_account_connection_orders (coordinator_id,last_order) SELECT NULL,0 WHERE NOT EXISTS (${historicalRevocationReadSql()})`,\n\t\t\tvalues,\n\t\t},\n\t];\n}\n","import type {\n\tCoordinatorAuthBrowserTransactionRejected,\n\tCoordinatorAuthBrowserTransactionStartResult,\n} from \"./coordinator-auth-browser-transaction-contract.js\";\nimport type { AuthLinkBackend } from \"./coordinator-auth-link.js\";\nimport type {\n\tCoordinatorAuthLinkCreateInput,\n\tCoordinatorAuthLinkFinalizeInput,\n\tCoordinatorAuthLinkSigner,\n} from \"./coordinator-auth-link-contract.js\";\nimport { hashCoordinatorAuthProofBytes32 } from \"./coordinator-auth-proof.js\";\n\n/** Same authority and pins as desktop create; the user code hash replaces the start hash. */\nexport type CoordinatorAuthLinkHeadlessCreateInput = Omit<\n\tCoordinatorAuthLinkCreateInput,\n\t\"loopbackRedirect\" | \"browserStartHash\"\n> & { userCodeHash: string };\n/** The device-approved account must equal the attempt's verified account when the link is written. */\nexport interface CoordinatorAuthLinkHeadlessFinalizeInput extends CoordinatorAuthLinkFinalizeInput {\n\tapprovedAccount: { issuer: string; subject: string };\n}\nexport interface CoordinatorAuthLinkHeadlessApprovalInput {\n\tattemptId: string;\n\tsigner: CoordinatorAuthLinkSigner;\n}\n/** Verified account shown on the device before it approves; profile fields are display claims. */\nexport interface CoordinatorAuthLinkHeadlessApproval {\n\tissuer: string;\n\tsubject: string;\n\tdisplayName: string | null;\n\temail: string | null;\n\temailVerified: boolean | null;\n}\nexport interface CoordinatorAuthHeadlessBrowserStartInput {\n\tuserCodeHash: string;\n\tstateHash: string;\n\tbinderHash: string;\n\tnonce: string;\n\tpkceVerifier: string;\n}\nexport type CoordinatorAuthHeadlessBrowserStartResult =\n\t| { kind: \"started\"; expiresAtMs: number; attemptId: string }\n\t| Exclude<CoordinatorAuthBrowserTransactionStartResult, { kind: \"started\" }>\n\t| CoordinatorAuthBrowserTransactionRejected;\n\n/**\n * Headless attempts share the desktop attempt table. This exact loopback value\n * marks the mode; it can never parse as a loopback URL, so desktop completion\n * delivery stays unreachable for headless rows.\n */\nexport const AUTH_LINK_HEADLESS_MARKER = \"codemem-headless:v1\";\n/** SQL literal form of the marker. The constant contains no quote characters. */\nexport const AUTH_LINK_HEADLESS_MARKER_SQL = `'${AUTH_LINK_HEADLESS_MARKER}'`;\n\n/** Consonants only: no vowels (no accidental words) and no 0/O or 1/I confusion. */\nexport const HEADLESS_USER_CODE_ALPHABET = \"BCDFGHJKLMNPQRSTVWXZ\";\nexport const HEADLESS_USER_CODE_LENGTH = 8;\nconst HEADLESS_USER_CODE_PREFIX = \"codemem-headless-link-code-v1:\";\n// 240 is the largest multiple of 20 not above 256; larger bytes would bias the alphabet.\nconst UNBIASED_BYTE_LIMIT = 240;\nconst MAX_RAW_USER_CODE_LENGTH = 64;\nconst GENERATION_BATCH = 16;\n\nexport type HeadlessRandomBytes = (length: number) => Uint8Array;\n\nfunction defaultRandomBytes(length: number): Uint8Array {\n\treturn globalThis.crypto.getRandomValues(new Uint8Array(length));\n}\n\n/** Returns the normalized 8-character code. Display it with formatHeadlessUserCode. */\nexport function generateHeadlessUserCode(\n\toptions: { randomBytes?: HeadlessRandomBytes } = {},\n): string {\n\tconst randomBytes = options.randomBytes ?? defaultRandomBytes;\n\tlet code = \"\";\n\t// Each batch accepts a byte with probability 240/256; 64 batches failing is not a real outcome.\n\tfor (let round = 0; round < 64 && code.length < HEADLESS_USER_CODE_LENGTH; round += 1) {\n\t\tfor (const byte of randomBytes(GENERATION_BATCH)) {\n\t\t\tif (byte >= UNBIASED_BYTE_LIMIT) continue;\n\t\t\tcode += HEADLESS_USER_CODE_ALPHABET[byte % HEADLESS_USER_CODE_ALPHABET.length];\n\t\t\tif (code.length === HEADLESS_USER_CODE_LENGTH) return code;\n\t\t}\n\t}\n\tthrow new Error(\"headless_user_code_entropy_failed\");\n}\n\n/** Formats a normalized code as XXXX-XXXX for display. */\nexport function formatHeadlessUserCode(code: string): string {\n\tconst normalized = normalizeHeadlessUserCode(code);\n\tif (normalized === null) throw new Error(\"headless_user_code_invalid\");\n\treturn `${normalized.slice(0, 4)}-${normalized.slice(4)}`;\n}\n\n/**\n * Accepts typed input: case-insensitive, with '-' and whitespace ignored.\n * Returns null for any other character or a wrong length.\n */\nexport function normalizeHeadlessUserCode(value: unknown): string | null {\n\tif (typeof value !== \"string\" || value.length > MAX_RAW_USER_CODE_LENGTH) return null;\n\tconst stripped = value.replace(/[\\s-]/g, \"\");\n\t// Check ASCII letters before uppercasing: Unicode case mapping can expand characters.\n\tif (!/^[A-Za-z]+$/.test(stripped) || stripped.length !== HEADLESS_USER_CODE_LENGTH) return null;\n\tconst upper = stripped.toUpperCase();\n\tfor (const character of upper) {\n\t\tif (!HEADLESS_USER_CODE_ALPHABET.includes(character)) return null;\n\t}\n\treturn upper;\n}\n\n/** The 32 bytes that play the role of a desktop browser start code. */\nexport async function deriveHeadlessUserCodeStartBytes(\n\tnormalizedCode: string,\n): Promise<Uint8Array> {\n\tif (normalizeHeadlessUserCode(normalizedCode) !== normalizedCode)\n\t\tthrow new Error(\"headless_user_code_invalid\");\n\tconst input = new TextEncoder().encode(`${HEADLESS_USER_CODE_PREFIX}${normalizedCode}`);\n\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", input);\n\treturn new Uint8Array(digest);\n}\n\n/** Stored as browser_start_hash, using the same hash desktop applies to its start code bytes. */\nexport async function hashHeadlessUserCode(normalizedCode: string): Promise<string> {\n\treturn hashCoordinatorAuthProofBytes32(await deriveHeadlessUserCodeStartBytes(normalizedCode));\n}\n\n/**\n * True when another attempt already stores this code hash. A create that fails\n * for this reason can succeed with a fresh code; any other conflict cannot.\n * The unique index covers every retained attempt, whatever its state.\n */\nexport async function isHeadlessUserCodeHeldByAnotherAttempt(\n\tbackend: Pick<AuthLinkBackend, \"first\">,\n\tinput: { coordinatorId: string; userCodeHash: string; attemptId: string },\n): Promise<boolean> {\n\tconst row = await backend.first<{ held: number }>({\n\t\tsql: `SELECT 1 AS held FROM coordinator_auth_link_attempts\n WHERE coordinator_id = ? AND browser_start_hash = ? AND attempt_id <> ? LIMIT 1`,\n\t\tvalues: [input.coordinatorId, input.userCodeHash, input.attemptId],\n\t});\n\treturn row?.held === 1;\n}\n","import type { CoordinatorAuthBrowserConfig } from \"./coordinator-auth-browser-transaction-contract.js\";\nimport type { CoordinatorAccountReference } from \"./coordinator-auth-contract.js\";\nimport type { CoordinatorAuthLinkConfig } from \"./coordinator-auth-link-contract.js\";\n\nexport const AUTH_SESSION_TTL_MS = 28800000;\nexport const AUTH_SESSION_MAX_LIVE_PER_LINK = 10;\nexport const AUTH_LINK_REDEEM_WINDOW_MS = 120000;\nexport const AUTH_GUARDED_SIGNIN_PURGE_GRACE_MS = 86400000;\nexport const AUTH_GUARDED_SIGNIN_RECEIPT_PURGE_AGE_MS = 115200000;\nexport const AUTH_GUARDED_SIGNIN_PURGE_BATCH_MAX = 256;\n/** Server metadata only: never a bearer credential or its commitment. */\nexport interface CoordinatorAuthSession {\n\tsessionId: string;\n\tidentityId: string;\n\tlinkId: string;\n\taccount: CoordinatorAccountReference;\n\texpiresAtMs: number;\n}\nexport type CoordinatorAuthSessionError =\n\t| \"invalid_input\"\n\t| \"auth_config_changed\"\n\t| \"attempt_unavailable\"\n\t| \"redeem_window_expired\"\n\t| \"browser_transaction_used\"\n\t| \"transaction_unavailable\"\n\t| \"session_limited\"\n\t| \"account_not_linked\";\nexport type CoordinatorAuthSessionIssueResult =\n\t| { kind: \"issued\"; session: CoordinatorAuthSession }\n\t| { kind: \"rejected\"; error: CoordinatorAuthSessionError };\nexport type CoordinatorAuthLinkSessionPreserveResult =\n\t| Readonly<{ kind: \"preserved\" }>\n\t| Extract<CoordinatorAuthSessionIssueResult, { kind: \"rejected\" }>;\n/** Hashes come from trusted browser authentication and a fresh 32-byte server generator.\n * Shape validation is not cryptographic evidence; raw credentials never enter this API.\n */\nexport interface CoordinatorAuthLinkSessionRedeemInput {\n\tattemptId: string;\n\tbrowserTransactionHash: string;\n\tcredentialHash: string;\n}\n/** Binding hashes are derived and resolved by the trusted server, never nominated by HTTP JSON. */\nexport interface CoordinatorAuthBoundLinkSessionRedeemInput\n\textends CoordinatorAuthLinkSessionRedeemInput {\n\tbinderHash: string;\n}\n/** Account claims must already be independently verified by the server's OIDC ceremony. */\nexport interface CoordinatorAuthAccountSignInInput {\n\tbrowserTransactionHash: string;\n\taccount: CoordinatorAccountReference;\n\tcredentialHash: string;\n}\n/** Scope comes from trusted server configuration, not network JSON. */\nexport interface CoordinatorAuthSessionScope {\n\tcoordinatorId: string;\n}\nexport interface CoordinatorAuthSessionPurgeOptions {\n\tlimit?: number;\n}\nexport type CoordinatorAuthSessionPurgeResult =\n\t| { kind: \"purged\"; processedCount: number; more: boolean }\n\t| { kind: \"rejected\"; error: \"invalid_input\" };\nexport type CoordinatorAuthSessionSignOutResult =\n\t| { kind: \"signed_out\" }\n\t| { kind: \"rejected\"; error: \"invalid_input\" };\nexport type CoordinatorAuthAccountLinkRevokeResult =\n\t| { kind: \"revoked\" }\n\t| { kind: \"rejected\"; error: \"invalid_input\" | \"link_unavailable\" };\nexport interface CoordinatorAuthSessionStore {\n\t/** Optional metadata cleanup only; more is an operational hint, not authority. */\n\tpurgeAuthGuardedSigninSessions(\n\t\tscope: CoordinatorAuthSessionScope,\n\t\toptions?: CoordinatorAuthSessionPurgeOptions,\n\t): Promise<CoordinatorAuthSessionPurgeResult>;\n\tpurgeAuthGuardedSigninReceipts(\n\t\tscope: CoordinatorAuthSessionScope,\n\t\toptions?: CoordinatorAuthSessionPurgeOptions,\n\t): Promise<CoordinatorAuthSessionPurgeResult>;\n\t/** @deprecated Always rejects; use redeemAuthLinkSessionWithBrowserTransaction with the original binder. */\n\tredeemAuthLinkSession(\n\t\tinput: CoordinatorAuthLinkSessionRedeemInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthSessionIssueResult>;\n\tredeemAuthLinkSessionWithBrowserTransaction(\n\t\tinput: CoordinatorAuthBoundLinkSessionRedeemInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<CoordinatorAuthSessionIssueResult>;\n\t/** credentialHash is the existing live session hash, not a fresh token hash. */\n\tpreserveAuthLinkSessionCompletion(\n\t\tinput: CoordinatorAuthBoundLinkSessionRedeemInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<CoordinatorAuthLinkSessionPreserveResult>;\n\t/** @deprecated Always rejects; use signInWithConsumedBrowserTransaction after verifying provider/browser proof. */\n\tsignInWithAuthAccount(\n\t\tinput: CoordinatorAuthAccountSignInInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthSessionIssueResult>;\n\t/** Caller already verified OIDC claims, original browser binding and CSRF.\n\t * Hashes are trusted server metadata, never accepted from HTTP JSON.\n\t */\n\tsignInWithConsumedBrowserTransaction(\n\t\tinput: CoordinatorAuthAccountSignInInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<CoordinatorAuthSessionIssueResult>;\n\treadAuthSession(\n\t\tcredentialHash: string,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthSession | null>;\n\tsignOutAuthSession(\n\t\tcredentialHash: string,\n\t\tscope: CoordinatorAuthSessionScope,\n\t): Promise<CoordinatorAuthSessionSignOutResult>;\n}\n/** Separate admin capability: future callers MUST authenticate the configured admin.\n * Browser sessions and caller-supplied actor labels never supply this authority.\n */\nexport interface CoordinatorAuthAccountLinkAdminStore {\n\trevokeAuthAccountLink(\n\t\tinput: { linkId: string },\n\t\tscope: CoordinatorAuthSessionScope,\n\t): Promise<CoordinatorAuthAccountLinkRevokeResult>;\n}\n\n// Empty tables only: no foreign keys, backfill, profiles, or provider tokens.\nexport const AUTH_SESSION_RETENTION_COLUMN_SQL = `purge_eligible INTEGER NOT NULL DEFAULT 0 CHECK (typeof(purge_eligible) = 'integer' AND purge_eligible IN (0,1) AND (purge_eligible = 0 OR (source = 'signin' AND attempt_id IS NULL)))`;\nexport const AUTH_SESSION_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS coordinator_auth_session_receipts (\n coordinator_id TEXT NOT NULL,\n browser_transaction_hash TEXT NOT NULL CHECK (length(browser_transaction_hash) = 64 AND browser_transaction_hash NOT GLOB '*[^0-9a-f]*'),\n source TEXT NOT NULL CHECK (source IN ('link_redeem','signin')),\n attempt_id TEXT,\n link_id TEXT NOT NULL,\n session_id TEXT NOT NULL,\n auth_config_revision TEXT NOT NULL CHECK (length(auth_config_revision) = 64 AND auth_config_revision NOT GLOB '*[^0-9a-f]*'),\n created_at_ms INTEGER NOT NULL CHECK (typeof(created_at_ms) = 'integer' AND created_at_ms BETWEEN 0 AND 9007199225940991),\n ${AUTH_SESSION_RETENTION_COLUMN_SQL},\n PRIMARY KEY (coordinator_id, browser_transaction_hash),\n UNIQUE (coordinator_id, session_id),\n UNIQUE (coordinator_id, attempt_id),\n CHECK ((source = 'link_redeem' AND attempt_id IS NOT NULL) OR (source = 'signin' AND attempt_id IS NULL))\n);\nCREATE TABLE IF NOT EXISTS coordinator_auth_sessions (\n coordinator_id TEXT NOT NULL,\n session_id TEXT NOT NULL,\n credential_hash TEXT NOT NULL CHECK (length(credential_hash) = 64 AND credential_hash NOT GLOB '*[^0-9a-f]*'),\n browser_transaction_hash TEXT NOT NULL CHECK (length(browser_transaction_hash) = 64 AND browser_transaction_hash NOT GLOB '*[^0-9a-f]*'),\n link_id TEXT NOT NULL,\n identity_id TEXT NOT NULL,\n issuer TEXT NOT NULL,\n subject TEXT NOT NULL CHECK (length(subject) BETWEEN 1 AND 255),\n auth_config_revision TEXT NOT NULL CHECK (length(auth_config_revision) = 64 AND auth_config_revision NOT GLOB '*[^0-9a-f]*'),\n created_at_ms INTEGER NOT NULL CHECK (typeof(created_at_ms) = 'integer' AND created_at_ms BETWEEN 0 AND 9007199225940991),\n expires_at_ms INTEGER NOT NULL CHECK (typeof(expires_at_ms) = 'integer' AND expires_at_ms BETWEEN 0 AND 9007199254740991 AND expires_at_ms = created_at_ms + 28800000),\n revoked_at_ms INTEGER CHECK (revoked_at_ms IS NULL OR (typeof(revoked_at_ms) = 'integer' AND revoked_at_ms BETWEEN 0 AND 9007199254740991)),\n PRIMARY KEY (coordinator_id, session_id),\n UNIQUE (coordinator_id, credential_hash),\n UNIQUE (coordinator_id, browser_transaction_hash)\n);\nCREATE INDEX IF NOT EXISTS idx_auth_sessions_link_config_expiry\n ON coordinator_auth_sessions(coordinator_id, link_id, auth_config_revision, expires_at_ms);\nCREATE INDEX IF NOT EXISTS idx_auth_sessions_expiry\n ON coordinator_auth_sessions(coordinator_id, expires_at_ms, session_id);\nCREATE INDEX IF NOT EXISTS idx_auth_session_receipts_purge\n ON coordinator_auth_session_receipts(coordinator_id, purge_eligible, created_at_ms, browser_transaction_hash);\n`;\n","import { hasConnectionSessionSchema } from \"./coordinator-account-connection-session.js\";\nimport {\n\tCONNECTION_NOT_REVOKED_SQL,\n\tCONNECTION_SIGNIN_ORDER_SQL,\n} from \"./coordinator-account-connection-storage.js\";\nimport {\n\thistoricalRevocationReadSql,\n\thistoricalRevocationStatements,\n} from \"./coordinator-account-historical-revoke.js\";\nimport type { CoordinatorAuthBrowserConfig } from \"./coordinator-auth-browser-transaction-contract.js\";\nimport {\n\tisCoordinatorAccountIssuer,\n\tparseCoordinatorAccountReference,\n} from \"./coordinator-auth-contract.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport type { CoordinatorAuthLinkConfig } from \"./coordinator-auth-link-contract.js\";\nimport { AUTH_LINK_HEADLESS_MARKER_SQL } from \"./coordinator-auth-link-headless.js\";\nimport { authAccountLinkProvenanceSql } from \"./coordinator-auth-link-provenance.js\";\nimport { authPersistenceError } from \"./coordinator-auth-schema.js\";\nimport {\n\tAUTH_GUARDED_SIGNIN_PURGE_BATCH_MAX,\n\tAUTH_GUARDED_SIGNIN_PURGE_GRACE_MS,\n\tAUTH_GUARDED_SIGNIN_RECEIPT_PURGE_AGE_MS,\n\tAUTH_LINK_REDEEM_WINDOW_MS,\n\tAUTH_SESSION_MAX_LIVE_PER_LINK,\n\tAUTH_SESSION_TTL_MS,\n\ttype CoordinatorAuthAccountLinkAdminStore,\n\ttype CoordinatorAuthAccountLinkRevokeResult,\n\ttype CoordinatorAuthAccountSignInInput,\n\ttype CoordinatorAuthBoundLinkSessionRedeemInput,\n\ttype CoordinatorAuthLinkSessionPreserveResult,\n\ttype CoordinatorAuthLinkSessionRedeemInput,\n\ttype CoordinatorAuthSession,\n\ttype CoordinatorAuthSessionError,\n\ttype CoordinatorAuthSessionIssueResult,\n\ttype CoordinatorAuthSessionPurgeOptions,\n\ttype CoordinatorAuthSessionPurgeResult,\n\ttype CoordinatorAuthSessionScope,\n\ttype CoordinatorAuthSessionSignOutResult,\n\ttype CoordinatorAuthSessionStore,\n} from \"./coordinator-auth-session-contract.js\";\n\nexport * from \"./coordinator-auth-session-contract.js\";\n\ntype Captured = Record<string, unknown>;\nfunction capture(value: unknown, fields: readonly string[]): Captured | null {\n\tif (!value || typeof value !== \"object\") return null;\n\ttry {\n\t\tif (Array.isArray(value)) return null;\n\t\tconst result: Captured = {};\n\t\tfor (const key of fields) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\t\tif (!descriptor || !Object.hasOwn(descriptor, \"value\")) return null;\n\t\t\tresult[key] = descriptor.value;\n\t\t}\n\t\treturn result;\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction isHash(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length === 64 && /^[0-9a-f]{64}$/.test(value);\n}\nfunction captureConfig(value: unknown): CoordinatorAuthLinkConfig | null {\n\tconst c = capture(value, [\"coordinatorId\", \"issuer\", \"revision\", \"enabled\"]);\n\tif (\n\t\t!c ||\n\t\t!isAuthControllerId(c.coordinatorId) ||\n\t\t!isCoordinatorAccountIssuer(c.issuer) ||\n\t\t!isHash(c.revision) ||\n\t\ttypeof c.enabled !== \"boolean\"\n\t)\n\t\treturn null;\n\treturn {\n\t\tcoordinatorId: c.coordinatorId,\n\t\tissuer: c.issuer,\n\t\trevision: c.revision,\n\t\tenabled: c.enabled,\n\t};\n}\nfunction captureScope(value: unknown): CoordinatorAuthSessionScope | null {\n\tconst s = capture(value, [\"coordinatorId\"]);\n\treturn s && isAuthControllerId(s.coordinatorId) ? { coordinatorId: s.coordinatorId } : null;\n}\nfunction capturePurgeLimit(value: unknown): number | null {\n\tif (value === undefined) return AUTH_GUARDED_SIGNIN_PURGE_BATCH_MAX;\n\tif (!value || typeof value !== \"object\") return null;\n\ttry {\n\t\tif (Array.isArray(value)) return null;\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, \"limit\");\n\t\tif (!descriptor) return \"limit\" in value ? null : AUTH_GUARDED_SIGNIN_PURGE_BATCH_MAX;\n\t\tif (!Object.hasOwn(descriptor, \"value\")) return null;\n\t\tconst limit: unknown = descriptor.value;\n\t\tif (typeof limit !== \"number\" || !Number.isSafeInteger(limit)) return null;\n\t\treturn limit >= 1 && limit <= AUTH_GUARDED_SIGNIN_PURGE_BATCH_MAX ? limit : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction captureBrowserConfig(value: unknown): CoordinatorAuthBrowserConfig | null {\n\tconst snapshot = capture(value, [\n\t\t\"coordinatorId\",\n\t\t\"issuer\",\n\t\t\"revision\",\n\t\t\"enabled\",\n\t\t\"redirectUri\",\n\t]);\n\tconst c = captureConfig(snapshot);\n\tif (!c || !snapshot || typeof snapshot.redirectUri !== \"string\") return null;\n\tconst redirectUri = snapshot.redirectUri;\n\tif (redirectUri.trim() !== redirectUri || /[\\\\\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(redirectUri))\n\t\treturn null;\n\ttry {\n\t\tconst url = new URL(redirectUri);\n\t\tif (\n\t\t\turl.protocol !== \"https:\" ||\n\t\t\turl.href !== redirectUri ||\n\t\t\turl.username ||\n\t\t\turl.password ||\n\t\t\turl.search ||\n\t\t\turl.hash ||\n\t\t\tredirectUri.includes(\"?\") ||\n\t\t\tredirectUri.includes(\"#\")\n\t\t)\n\t\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t}\n\treturn { ...c, redirectUri };\n}\nfunction captureIssue(\n\tvalue: unknown,\n\textra: string[],\n): (Captured & { browserTransactionHash: string; credentialHash: string }) | null {\n\tconst i = capture(value, [\"browserTransactionHash\", \"credentialHash\", ...extra]);\n\tif (!i || !isHash(i.browserTransactionHash) || !isHash(i.credentialHash)) return null;\n\treturn {\n\t\t...i,\n\t\tbrowserTransactionHash: i.browserTransactionHash,\n\t\tcredentialHash: i.credentialHash,\n\t};\n}\nfunction sessionNow(clock: () => number): number {\n\tlet now: number;\n\ttry {\n\t\tnow = clock();\n\t} catch {\n\t\tthrow new Error(\"auth_session_invalid_clock\");\n\t}\n\tif (!Number.isSafeInteger(now) || now < 0 || now > Number.MAX_SAFE_INTEGER - AUTH_SESSION_TTL_MS)\n\t\tthrow new Error(\"auth_session_invalid_clock\");\n\treturn now;\n}\n\nexport { sessionNow as authSessionNow };\n\nfunction rejected(\n\terror: CoordinatorAuthSessionError,\n): Extract<CoordinatorAuthSessionIssueResult, { kind: \"rejected\" }> {\n\treturn { kind: \"rejected\", error };\n}\ninterface SessionRow {\n\tsession_id: string;\n\tidentity_id: string;\n\tlink_id: string;\n\tissuer: string;\n\tsubject: string;\n\texpires_at_ms: number;\n}\ninterface ReceiptRow {\n\tsession_id: string;\n}\ninterface RedeemDiagnosis {\n\tbrowser_transaction_hash: string | null;\n\tstate: string;\n\tissuer: string;\n\tauth_config_revision: string;\n\tfinalized_at_ms: number | null;\n\texpires_at_ms: number;\n}\nfunction dto(row: SessionRow): CoordinatorAuthSession {\n\treturn {\n\t\tsessionId: row.session_id,\n\t\tidentityId: row.identity_id,\n\t\tlinkId: row.link_id,\n\t\taccount: { issuer: row.issuer, subject: row.subject },\n\t\texpiresAtMs: row.expires_at_ms,\n\t};\n}\nconst SESSION_LINK_IDENTITY_SQL = `l.coordinator_id = s.coordinator_id AND l.link_id = s.link_id\n AND l.identity_id = s.identity_id AND l.issuer = s.issuer AND l.subject = s.subject`;\nexport function authSessionLinkMatchSql(options: { connections: boolean }): string {\n\treturn `${SESSION_LINK_IDENTITY_SQL} AND ${authAccountLinkProvenanceSql(\"l\", options)}`;\n}\nexport const AUTH_SESSION_LINK_MATCH_SQL = authSessionLinkMatchSql({ connections: false });\nexport const AUTH_SESSION_LIVE_GUARD_SQL = `s.coordinator_id = ? AND s.credential_hash = ? AND s.issuer = ? AND s.auth_config_revision = ? AND s.revoked_at_ms IS NULL AND l.revoked_at_ms IS NULL AND s.expires_at_ms > ? AND s.created_at_ms <= ?`;\n// Headless finalize hands no browser a session: the browser never proved device possession.\nconst DESKTOP_ATTEMPT_SQL = `t.loopback_redirect <> ${AUTH_LINK_HEADLESS_MARKER_SQL}`;\nconst RECEIPT_COLUMNS = `coordinator_id, browser_transaction_hash, source, attempt_id, link_id, session_id, auth_config_revision, created_at_ms`;\nfunction redeemReceiptSelectSql(options: { connections: boolean }) {\n\tconst ACCOUNT_PROVENANCE = authAccountLinkProvenanceSql(\"l\", options);\n\treturn `INSERT INTO coordinator_auth_session_receipts (${RECEIPT_COLUMNS})\n SELECT t.coordinator_id, t.browser_transaction_hash, 'link_redeem', t.attempt_id, t.link_id, ?, ?, ?\n FROM coordinator_auth_link_attempts t JOIN coordinator_auth_account_links l\n ON l.coordinator_id = t.coordinator_id AND l.link_id = t.link_id AND l.attempt_id = t.attempt_id\n AND l.identity_id = t.identity_id AND l.issuer = t.issuer AND l.subject = t.account_subject\n AND l.auth_config_revision = t.auth_config_revision AND l.authority_kind = t.authority_kind\n AND ${ACCOUNT_PROVENANCE}\n WHERE t.coordinator_id = ? AND t.attempt_id = ? AND t.browser_transaction_hash = ?\n AND t.state = 'finalized' AND t.issuer = ? AND t.auth_config_revision = ? AND l.revoked_at_ms IS NULL\n AND ${DESKTOP_ATTEMPT_SQL} AND ? >= t.finalized_at_ms AND ? < t.finalized_at_ms + 120000 AND ? < t.expires_at_ms`;\n}\nconst BOUND_LINK_BROWSER_GUARD_SQL = `b.coordinator_id = t.coordinator_id\n AND b.browser_transaction_hash = t.browser_transaction_hash AND b.attempt_id = t.attempt_id\n AND b.binder_hash = ? AND b.purpose = 'link' AND b.state = 'consumed'\n AND b.issuer = ? AND b.auth_config_revision = ? AND b.redirect_uri = ?\n AND b.nonce IS NULL AND b.pkce_verifier IS NULL AND b.claim_token IS NOT NULL\n AND b.consumed_at_ms IS NOT NULL AND b.created_at_ms <= ?\n AND b.consumed_at_ms <= ? AND b.expires_at_ms > ?`;\nfunction boundBrowserGuard(options: { connections: boolean }) {\n\treturn `(${BOUND_LINK_BROWSER_GUARD_SQL})${options.connections ? ` AND (${CONNECTION_SIGNIN_ORDER_SQL}) AND (${CONNECTION_NOT_REVOKED_SQL})` : \"\"}`;\n}\nfunction boundRedeemSql(options: { connections: boolean }) {\n\treturn `${redeemReceiptSelectSql(options)}\n AND EXISTS (SELECT 1 FROM coordinator_auth_browser_transactions b WHERE ${boundBrowserGuard(options)})\n ON CONFLICT(coordinator_id, browser_transaction_hash) DO NOTHING`;\n}\nfunction connectedPreserveCompletionSql(): string {\n\treturn `WITH completion_links AS MATERIALIZED (SELECT l.* FROM coordinator_auth_account_links l WHERE l.coordinator_id = ? AND\n (l.link_id = (SELECT link_id FROM coordinator_auth_link_attempts WHERE coordinator_id = ? AND attempt_id = ?) OR l.link_id = (SELECT link_id FROM coordinator_auth_sessions WHERE coordinator_id = ? AND credential_hash = ?))\n AND (${authAccountLinkProvenanceSql(\"l\", { connections: true })}) AND (${CONNECTION_NOT_REVOKED_SQL})),\n eligible_completion AS MATERIALIZED (SELECT t.coordinator_id,t.attempt_id,t.browser_transaction_hash FROM coordinator_auth_link_attempts t JOIN completion_links l\n ON (l.coordinator_id=t.coordinator_id AND l.link_id=t.link_id AND l.attempt_id=t.attempt_id)\n AND (l.identity_id=t.identity_id AND l.issuer=t.issuer AND l.subject=t.account_subject AND l.auth_config_revision=t.auth_config_revision AND l.authority_kind=t.authority_kind AND l.revoked_at_ms IS NULL)\n WHERE (t.coordinator_id = ? AND t.attempt_id = ? AND t.browser_transaction_hash = ? AND t.issuer = ? AND t.auth_config_revision = ? AND t.state = 'finalized')\n AND ${DESKTOP_ATTEMPT_SQL} AND (t.created_at_ms <= ? AND t.finalized_at_ms <= ? AND ? < t.finalized_at_ms + 120000 AND t.expires_at_ms > ?)\n AND EXISTS (SELECT 1 FROM coordinator_auth_browser_transactions b WHERE ${boundBrowserGuard({ connections: true })})),\n live_existing_session AS MATERIALIZED (SELECT 1 FROM coordinator_auth_sessions s JOIN completion_links l ON ${SESSION_LINK_IDENTITY_SQL} WHERE (${AUTH_SESSION_LIVE_GUARD_SQL}) AND (${CONNECTION_NOT_REVOKED_SQL}))\n UPDATE coordinator_auth_link_attempts AS t SET state='session_redeemed' WHERE t.state='finalized'\n AND EXISTS (SELECT 1 FROM eligible_completion p WHERE p.coordinator_id=t.coordinator_id AND p.attempt_id=t.attempt_id AND p.browser_transaction_hash=t.browser_transaction_hash)\n AND EXISTS (SELECT 1 FROM live_existing_session)`;\n}\nfunction preserveCompletionSql(options: { connections: boolean }) {\n\tif (options.connections) return connectedPreserveCompletionSql();\n\tconst ACCOUNT_PROVENANCE = authAccountLinkProvenanceSql(\"l\", options),\n\t\tLINK_MATCH = authSessionLinkMatchSql(options);\n\treturn `UPDATE coordinator_auth_link_attempts AS t SET state = 'session_redeemed'\n WHERE (t.coordinator_id = ? AND t.attempt_id = ? AND t.browser_transaction_hash = ? AND t.issuer = ? AND t.auth_config_revision = ? AND t.state = 'finalized')\n AND ${DESKTOP_ATTEMPT_SQL} AND (t.created_at_ms <= ? AND t.finalized_at_ms <= ? AND ? < t.finalized_at_ms + 120000 AND t.expires_at_ms > ?)\n AND EXISTS (SELECT 1 FROM coordinator_auth_account_links l\n WHERE (l.coordinator_id = t.coordinator_id AND l.link_id = t.link_id AND l.attempt_id = t.attempt_id)\n AND (l.identity_id = t.identity_id AND l.issuer = t.issuer AND l.subject = t.account_subject)\n AND (l.auth_config_revision = t.auth_config_revision AND l.revoked_at_ms IS NULL AND l.authority_kind = t.authority_kind) AND ${ACCOUNT_PROVENANCE}\n AND EXISTS (SELECT 1 FROM coordinator_auth_browser_transactions b WHERE ${boundBrowserGuard(options)}))\n AND EXISTS (SELECT 1 FROM coordinator_auth_sessions s\n JOIN coordinator_auth_account_links l ON ${LINK_MATCH} WHERE (${AUTH_SESSION_LIVE_GUARD_SQL}))`;\n}\nconst CONSUMED_BROWSER_GUARD_SQL = `b.coordinator_id = ? AND b.browser_transaction_hash = ?\n AND b.purpose = 'signin' AND b.attempt_id IS NULL AND b.state = 'consumed'\n AND b.nonce IS NULL AND b.pkce_verifier IS NULL AND b.claim_token IS NOT NULL\n AND b.issuer = ? AND b.auth_config_revision = ? AND b.redirect_uri = ?\n AND b.created_at_ms <= ? AND b.consumed_at_ms <= ? AND b.expires_at_ms > ?`;\nfunction consumedSigninReceiptSql(options: { connections: boolean }) {\n\tconst ACCOUNT_PROVENANCE = authAccountLinkProvenanceSql(\"l\", options),\n\t\tLINK_MATCH = options.connections ? SESSION_LINK_IDENTITY_SQL : authSessionLinkMatchSql(options);\n\t// The capacity count references the same independently proven link row.\n\treturn `${options.connections ? `WITH admissible_links AS MATERIALIZED (SELECT l.* FROM coordinator_auth_account_links l WHERE (l.coordinator_id = ? AND l.issuer = ? AND l.subject = ?) AND (${ACCOUNT_PROVENANCE}) AND (${CONNECTION_NOT_REVOKED_SQL})) ` : \"\"}INSERT INTO coordinator_auth_session_receipts (${RECEIPT_COLUMNS}, purge_eligible${options.connections ? \",source_order\" : \"\"})\n SELECT b.coordinator_id, b.browser_transaction_hash, 'signin', NULL, l.link_id, ?, ?, ?, 1${options.connections ? \",b.start_order\" : \"\"}\n FROM coordinator_auth_browser_transactions b JOIN ${options.connections ? \"admissible_links\" : \"coordinator_auth_account_links\"} l\n ON l.coordinator_id = b.coordinator_id AND l.issuer = b.issuer\n WHERE (${CONSUMED_BROWSER_GUARD_SQL}) AND l.subject = ? AND l.revoked_at_ms IS NULL ${options.connections ? \"\" : `AND ${ACCOUNT_PROVENANCE}`}\n ${options.connections ? `AND ${CONNECTION_NOT_REVOKED_SQL} AND ${CONNECTION_SIGNIN_ORDER_SQL}` : \"\"}\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_link_attempts t\n WHERE t.coordinator_id = b.coordinator_id AND t.browser_transaction_hash = b.browser_transaction_hash)\n AND (SELECT COUNT(*) FROM coordinator_auth_sessions s WHERE ${LINK_MATCH}\n AND s.auth_config_revision = b.auth_config_revision AND s.revoked_at_ms IS NULL\n AND s.expires_at_ms > ?) < ${AUTH_SESSION_MAX_LIVE_PER_LINK}\n ON CONFLICT(coordinator_id, browser_transaction_hash) DO NOTHING`;\n}\nfunction sessionInsertSql(options: { connections: boolean }) {\n\tconst ACCOUNT_PROVENANCE = authAccountLinkProvenanceSql(\"l\", options);\n\treturn `INSERT INTO coordinator_auth_sessions\n (coordinator_id, session_id, credential_hash, browser_transaction_hash, link_id, identity_id, issuer, subject, auth_config_revision, created_at_ms, expires_at_ms)\n SELECT r.coordinator_id, r.session_id, ?, r.browser_transaction_hash, r.link_id, l.identity_id, l.issuer, l.subject, r.auth_config_revision, r.created_at_ms, r.created_at_ms + 28800000\n FROM coordinator_auth_session_receipts r JOIN coordinator_auth_account_links l ON l.coordinator_id = r.coordinator_id AND l.link_id = r.link_id\n WHERE r.coordinator_id = ? AND r.browser_transaction_hash = ? AND r.session_id = ? AND l.revoked_at_ms IS NULL AND ${ACCOUNT_PROVENANCE}`;\n}\nfunction redeemConsumeSql(options: { connections: boolean }) {\n\tconst ACCOUNT_PROVENANCE = authAccountLinkProvenanceSql(\"l\", options);\n\treturn `UPDATE coordinator_auth_link_attempts SET state = 'session_redeemed'\n WHERE coordinator_id = ? AND attempt_id = ? AND browser_transaction_hash = ? AND state = 'finalized'\n AND loopback_redirect <> ${AUTH_LINK_HEADLESS_MARKER_SQL} AND EXISTS (SELECT 1 FROM coordinator_auth_account_links l WHERE l.coordinator_id = coordinator_auth_link_attempts.coordinator_id\n AND l.link_id = coordinator_auth_link_attempts.link_id AND l.attempt_id = coordinator_auth_link_attempts.attempt_id\n AND l.authority_kind = coordinator_auth_link_attempts.authority_kind AND l.revoked_at_ms IS NULL AND ${ACCOUNT_PROVENANCE})\n AND EXISTS (SELECT 1 FROM coordinator_auth_sessions s WHERE s.coordinator_id = coordinator_auth_link_attempts.coordinator_id AND s.session_id = ? AND s.browser_transaction_hash = coordinator_auth_link_attempts.browser_transaction_hash)`;\n}\nfunction issueReadSql(options: { connections: boolean }) {\n\tconst LINK_MATCH = authSessionLinkMatchSql(options);\n\treturn `SELECT s.session_id, s.identity_id, s.link_id, s.issuer, s.subject, s.expires_at_ms\n FROM coordinator_auth_session_receipts r JOIN coordinator_auth_sessions s\n ON s.coordinator_id = r.coordinator_id AND s.session_id = r.session_id AND s.browser_transaction_hash = r.browser_transaction_hash\n AND s.link_id = r.link_id AND s.auth_config_revision = r.auth_config_revision AND s.created_at_ms = r.created_at_ms\n JOIN coordinator_auth_account_links l ON ${LINK_MATCH}\n WHERE r.coordinator_id = ? AND r.browser_transaction_hash = ? AND r.session_id = ?\n AND s.credential_hash = ? AND r.auth_config_revision = ? AND r.created_at_ms = ? AND s.expires_at_ms = ? AND s.issuer = ?\n AND ((r.source = 'signin' AND r.attempt_id IS NULL) OR (r.source = 'link_redeem' AND EXISTS\n (SELECT 1 FROM coordinator_auth_link_attempts t WHERE t.coordinator_id = r.coordinator_id AND t.attempt_id = r.attempt_id\n AND t.state = 'session_redeemed' AND t.authority_kind = l.authority_kind AND t.link_id = r.link_id AND t.browser_transaction_hash = r.browser_transaction_hash\n AND t.identity_id = s.identity_id AND t.issuer = s.issuer AND t.account_subject = s.subject)))`;\n}\n\nconst PURGE_GUARDED_SIGNIN_SESSIONS_SQL = `DELETE FROM coordinator_auth_sessions\n WHERE coordinator_id = ? AND expires_at_ms <= ? AND session_id IN\n (SELECT s.session_id FROM coordinator_auth_sessions s\n WHERE s.coordinator_id = ? AND s.expires_at_ms <= ?\n AND EXISTS (SELECT 1 FROM coordinator_auth_session_receipts r\n WHERE r.coordinator_id = s.coordinator_id AND r.session_id = s.session_id\n AND r.browser_transaction_hash = s.browser_transaction_hash AND r.link_id = s.link_id\n AND r.auth_config_revision = s.auth_config_revision AND r.created_at_ms = s.created_at_ms\n AND r.source = 'signin' AND r.attempt_id IS NULL AND r.purge_eligible = 1)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_browser_transactions b\n WHERE b.coordinator_id = s.coordinator_id AND b.browser_transaction_hash = s.browser_transaction_hash)\n ORDER BY s.expires_at_ms, s.session_id LIMIT ?)`;\nconst PURGE_GUARDED_SIGNIN_RECEIPTS_SQL = `DELETE FROM coordinator_auth_session_receipts\n WHERE coordinator_id = ? AND purge_eligible = 1 AND source = 'signin' AND attempt_id IS NULL\n AND created_at_ms <= ? AND browser_transaction_hash IN\n (SELECT r.browser_transaction_hash FROM coordinator_auth_session_receipts r\n WHERE r.coordinator_id = ? AND r.purge_eligible = 1 AND r.source = 'signin'\n AND r.attempt_id IS NULL AND r.created_at_ms <= ?\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_browser_transactions b\n WHERE b.coordinator_id = r.coordinator_id AND b.browser_transaction_hash = r.browser_transaction_hash)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_sessions s\n WHERE s.coordinator_id = r.coordinator_id AND s.session_id = r.session_id)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_sessions s\n WHERE s.coordinator_id = r.coordinator_id AND s.browser_transaction_hash = r.browser_transaction_hash)\n ORDER BY r.created_at_ms, r.browser_transaction_hash LIMIT ?)`;\n\n/** Optional persistence only. Future callers authenticate browser/OIDC/CSRF/admin;\n * this capability creates no routes, actors, enrollment, role, or sync permission.\n */\nexport class AuthSessionOperations\n\timplements CoordinatorAuthSessionStore, CoordinatorAuthAccountLinkAdminStore\n{\n\tconstructor(\n\t\tprivate readonly backend: AuthLinkBackend,\n\t\tprivate readonly clock: () => number = Date.now,\n\t) {}\n\tasync purgeAuthGuardedSigninSessions(\n\t\tscope: CoordinatorAuthSessionScope,\n\t\toptions?: CoordinatorAuthSessionPurgeOptions,\n\t): Promise<CoordinatorAuthSessionPurgeResult> {\n\t\treturn this.purgeGuardedSigninMetadata(\n\t\t\tscope,\n\t\t\toptions,\n\t\t\tPURGE_GUARDED_SIGNIN_SESSIONS_SQL,\n\t\t\tAUTH_GUARDED_SIGNIN_PURGE_GRACE_MS,\n\t\t);\n\t}\n\tasync purgeAuthGuardedSigninReceipts(\n\t\tscope: CoordinatorAuthSessionScope,\n\t\toptions?: CoordinatorAuthSessionPurgeOptions,\n\t): Promise<CoordinatorAuthSessionPurgeResult> {\n\t\treturn this.purgeGuardedSigninMetadata(\n\t\t\tscope,\n\t\t\toptions,\n\t\t\tPURGE_GUARDED_SIGNIN_RECEIPTS_SQL,\n\t\t\tAUTH_GUARDED_SIGNIN_RECEIPT_PURGE_AGE_MS,\n\t\t);\n\t}\n\tprivate async purgeGuardedSigninMetadata(\n\t\tscope: CoordinatorAuthSessionScope,\n\t\toptions: CoordinatorAuthSessionPurgeOptions | undefined,\n\t\tsql: string,\n\t\tageMs: number,\n\t): Promise<CoordinatorAuthSessionPurgeResult> {\n\t\tconst s = captureScope(scope);\n\t\tconst limit = capturePurgeLimit(options);\n\t\tif (!s || limit === null) return { kind: \"rejected\", error: \"invalid_input\" };\n\t\tconst cutoff = sessionNow(this.clock) - ageMs;\n\t\ttry {\n\t\t\tconst processedCount = await this.backend.run({\n\t\t\t\tsql,\n\t\t\t\tvalues: [s.coordinatorId, cutoff, s.coordinatorId, cutoff, limit],\n\t\t\t});\n\t\t\treturn { kind: \"purged\", processedCount, more: processedCount === limit };\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_session_persistence_error\");\n\t\t}\n\t}\n\tprivate async first<T>(statement: AuthLinkStatement): Promise<T | null> {\n\t\ttry {\n\t\t\treturn await this.backend.first<T>(statement);\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_session_persistence_error\");\n\t\t}\n\t}\n\tprivate async connectionSchema(): Promise<boolean> {\n\t\ttry {\n\t\t\treturn await hasConnectionSessionSchema(this.backend);\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_session_persistence_error\");\n\t\t}\n\t}\n\tprivate async batch(statements: AuthLinkStatement[]): Promise<void> {\n\t\ttry {\n\t\t\tawait this.backend.batch(statements);\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_session_persistence_error\");\n\t\t}\n\t}\n\tasync redeemAuthLinkSession(\n\t\t_input: CoordinatorAuthLinkSessionRedeemInput,\n\t\t_config: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthSessionIssueResult> {\n\t\t// Retired: this entry has no browser binder and cannot prove redemption.\n\t\treturn rejected(\"attempt_unavailable\");\n\t}\n\t/** Complete once while preserving the existing session and its own active account link. */\n\tasync preserveAuthLinkSessionCompletion(\n\t\tinput: CoordinatorAuthBoundLinkSessionRedeemInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<CoordinatorAuthLinkSessionPreserveResult> {\n\t\tconst c = captureBrowserConfig(config);\n\t\tconst i = captureIssue(input, [\"attemptId\", \"binderHash\"]);\n\t\tif (!c || !i || !isAuthControllerId(i.attemptId) || !isHash(i.binderHash))\n\t\t\treturn rejected(\"invalid_input\");\n\t\tif (!c.enabled) return rejected(\"auth_config_changed\");\n\t\tconst now = sessionNow(this.clock);\n\t\t// credentialHash names the existing live session, which may belong to another linked account.\n\t\t// Completion creates no receipt: it preserves that session and burns only this attempt.\n\t\tconst connections = await this.connectionSchema();\n\t\tlet changed: number;\n\t\ttry {\n\t\t\tchanged = await this.backend.run({\n\t\t\t\tsql: preserveCompletionSql({ connections }),\n\t\t\t\tvalues: [\n\t\t\t\t\t...(connections\n\t\t\t\t\t\t? [c.coordinatorId, c.coordinatorId, i.attemptId, c.coordinatorId, i.credentialHash]\n\t\t\t\t\t\t: []),\n\t\t\t\t\tc.coordinatorId,\n\t\t\t\t\ti.attemptId,\n\t\t\t\t\ti.browserTransactionHash,\n\t\t\t\t\tc.issuer,\n\t\t\t\t\tc.revision,\n\t\t\t\t\tnow,\n\t\t\t\t\tnow,\n\t\t\t\t\tnow,\n\t\t\t\t\tnow,\n\t\t\t\t\ti.binderHash,\n\t\t\t\t\tc.issuer,\n\t\t\t\t\tc.revision,\n\t\t\t\t\tc.redirectUri,\n\t\t\t\t\tnow,\n\t\t\t\t\tnow,\n\t\t\t\t\tnow,\n\t\t\t\t\tc.coordinatorId,\n\t\t\t\t\ti.credentialHash,\n\t\t\t\t\tc.issuer,\n\t\t\t\t\tc.revision,\n\t\t\t\t\tnow,\n\t\t\t\t\tnow,\n\t\t\t\t],\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_session_persistence_error\");\n\t\t}\n\t\tif (changed !== 1) return rejected(\"attempt_unavailable\");\n\t\tconst row = await this.first<{ state: string }>({\n\t\t\tsql: `SELECT state FROM coordinator_auth_link_attempts\n WHERE coordinator_id = ? AND attempt_id = ? AND browser_transaction_hash = ?\n AND issuer = ? AND auth_config_revision = ?`,\n\t\t\tvalues: [c.coordinatorId, i.attemptId, i.browserTransactionHash, c.issuer, c.revision],\n\t\t});\n\t\t// A failed post-commit read must not release cookies or pretend the burn rolled back.\n\t\tif (row?.state !== \"session_redeemed\") throw new Error(\"auth_session_persistence_incomplete\");\n\t\treturn { kind: \"preserved\" };\n\t}\n\t/** Admission binds a finalized link to its consumed original browser transaction. */\n\tasync redeemAuthLinkSessionWithBrowserTransaction(\n\t\tinput: CoordinatorAuthBoundLinkSessionRedeemInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<CoordinatorAuthSessionIssueResult> {\n\t\tconst c = captureBrowserConfig(config);\n\t\tconst i = captureIssue(input, [\"attemptId\", \"binderHash\"]);\n\t\tif (!c || !i || !isAuthControllerId(i.attemptId) || !isHash(i.binderHash))\n\t\t\treturn rejected(\"invalid_input\");\n\t\tif (!c.enabled) return rejected(\"auth_config_changed\");\n\t\tconst now = sessionNow(this.clock);\n\t\tconst sessionId = globalThis.crypto.randomUUID();\n\t\t// The receipt guard is the admission check; only its fresh winner can mint and consume.\n\t\tawait this.batch([\n\t\t\t{\n\t\t\t\tsql: boundRedeemSql({ connections: await this.connectionSchema() }),\n\t\t\t\tvalues: [\n\t\t\t\t\tsessionId,\n\t\t\t\t\tc.revision,\n\t\t\t\t\tnow,\n\t\t\t\t\tc.coordinatorId,\n\t\t\t\t\ti.attemptId,\n\t\t\t\t\ti.browserTransactionHash,\n\t\t\t\t\tc.issuer,\n\t\t\t\t\tc.revision,\n\t\t\t\t\tnow,\n\t\t\t\t\tnow,\n\t\t\t\t\tnow,\n\t\t\t\t\ti.binderHash,\n\t\t\t\t\tc.issuer,\n\t\t\t\t\tc.revision,\n\t\t\t\t\tc.redirectUri,\n\t\t\t\t\tnow,\n\t\t\t\t\tnow,\n\t\t\t\t\tnow,\n\t\t\t\t],\n\t\t\t},\n\t\t\tawait this.sessionInsert(i, c, sessionId),\n\t\t\t{\n\t\t\t\tsql: redeemConsumeSql({ connections: await this.connectionSchema() }),\n\t\t\t\tvalues: [c.coordinatorId, i.attemptId, i.browserTransactionHash, sessionId],\n\t\t\t},\n\t\t]);\n\t\tconst result = await this.issueReceipt(i, c, now, sessionId);\n\t\tif (result) return result;\n\t\treturn this.diagnoseRedeem(i.attemptId, i.browserTransactionHash, c, now);\n\t}\n\tasync signInWithAuthAccount(\n\t\t_input: CoordinatorAuthAccountSignInInput,\n\t\t_config: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthSessionIssueResult> {\n\t\t// Retired: trusted account JSON alone cannot bypass consumed-browser proof.\n\t\treturn rejected(\"transaction_unavailable\");\n\t}\n\t/** Admission only; the caller has already verified JWT, cookie binding and CSRF. */\n\tasync signInWithConsumedBrowserTransaction(\n\t\tinput: CoordinatorAuthAccountSignInInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<CoordinatorAuthSessionIssueResult> {\n\t\tconst c = captureBrowserConfig(config);\n\t\tconst i = captureIssue(input, [\"account\"]);\n\t\tif (!c || !i) return rejected(\"invalid_input\");\n\t\tconst account = parseCoordinatorAccountReference(capture(i.account, [\"issuer\", \"subject\"]), {\n\t\t\tissuer: c.issuer,\n\t\t});\n\t\tif (!account.ok) return rejected(\"invalid_input\");\n\t\tif (!c.enabled) return rejected(\"auth_config_changed\");\n\t\tconst now = sessionNow(this.clock);\n\t\tconst sessionId = globalThis.crypto.randomUUID();\n\t\tconst transactionValues = [\n\t\t\tc.coordinatorId,\n\t\t\ti.browserTransactionHash,\n\t\t\tc.issuer,\n\t\t\tc.revision,\n\t\t\tc.redirectUri,\n\t\t\tnow,\n\t\t\tnow,\n\t\t\tnow,\n\t\t];\n\t\t// Admission and minting share one atomic batch, not a read-then-insert race.\n\t\t// Future-born current-config sessions reserve slots until they become readable.\n\t\tconst connections = await this.connectionSchema();\n\t\tawait this.batch([\n\t\t\t{\n\t\t\t\tsql: consumedSigninReceiptSql({ connections }),\n\t\t\t\tvalues: [\n\t\t\t\t\t...(connections\n\t\t\t\t\t\t? [c.coordinatorId, account.account.issuer, account.account.subject]\n\t\t\t\t\t\t: []),\n\t\t\t\t\tsessionId,\n\t\t\t\t\tc.revision,\n\t\t\t\t\tnow,\n\t\t\t\t\t...transactionValues,\n\t\t\t\t\taccount.account.subject,\n\t\t\t\t\tnow,\n\t\t\t\t],\n\t\t\t},\n\t\t\tawait this.sessionInsert(i, c, sessionId, { connections }),\n\t\t]);\n\t\tconst result = await this.issueReceipt(i, c, now, sessionId, { connections });\n\t\tif (result) return result;\n\t\tconst used = await this.first({\n\t\t\tsql: \"SELECT 1 FROM coordinator_auth_link_attempts WHERE coordinator_id = ? AND browser_transaction_hash = ?\",\n\t\t\tvalues: [c.coordinatorId, i.browserTransactionHash],\n\t\t});\n\t\tif (used) return rejected(\"browser_transaction_used\");\n\t\t// These reads choose rejection labels only; they never admit or reuse a receipt.\n\t\tconst transaction = await this.first({\n\t\t\tsql: `SELECT 1 FROM coordinator_auth_browser_transactions b WHERE ${CONSUMED_BROWSER_GUARD_SQL}`,\n\t\t\tvalues: transactionValues,\n\t\t});\n\t\tif (!transaction) return rejected(\"transaction_unavailable\");\n\t\tconst link = await this.first({\n\t\t\tsql: \"SELECT 1 FROM coordinator_auth_account_links WHERE coordinator_id = ? AND issuer = ? AND subject = ? AND revoked_at_ms IS NULL\",\n\t\t\tvalues: [c.coordinatorId, c.issuer, account.account.subject],\n\t\t});\n\t\tif (!link) return rejected(\"account_not_linked\");\n\t\treturn rejected(\"session_limited\");\n\t}\n\tprivate async sessionInsert(\n\t\ti: { credentialHash: string; browserTransactionHash: string },\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tsessionId: string,\n\t\toptions?: { connections: boolean },\n\t): Promise<AuthLinkStatement> {\n\t\treturn {\n\t\t\tsql: sessionInsertSql({\n\t\t\t\tconnections: options?.connections ?? (await this.connectionSchema()),\n\t\t\t}),\n\t\t\tvalues: [i.credentialHash, c.coordinatorId, i.browserTransactionHash, sessionId],\n\t\t};\n\t}\n\tprivate async issueReceipt(\n\t\ti: { credentialHash: string; browserTransactionHash: string },\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t\tsessionId: string,\n\t\toptions?: { connections: boolean },\n\t): Promise<CoordinatorAuthSessionIssueResult | null> {\n\t\tconst receipt = await this.first<ReceiptRow>({\n\t\t\tsql: \"SELECT session_id FROM coordinator_auth_session_receipts WHERE coordinator_id = ? AND browser_transaction_hash = ?\",\n\t\t\tvalues: [c.coordinatorId, i.browserTransactionHash],\n\t\t});\n\t\tif (!receipt) {\n\t\t\tconst orphan = await this.first({\n\t\t\t\tsql: \"SELECT 1 FROM coordinator_auth_sessions WHERE coordinator_id = ? AND session_id = ?\",\n\t\t\t\tvalues: [c.coordinatorId, sessionId],\n\t\t\t});\n\t\t\tif (orphan) throw new Error(\"auth_session_persistence_incomplete\");\n\t\t\treturn null;\n\t\t}\n\t\tif (receipt.session_id !== sessionId) return rejected(\"browser_transaction_used\");\n\t\t// Reuse only the stricter SQL shape; the SELECT still checks current readiness.\n\t\tconst connections = options?.connections === true || (await this.connectionSchema());\n\t\tconst row = await this.first<SessionRow>({\n\t\t\tsql: `${issueReadSql({ connections })}${connections ? ` AND ${CONNECTION_NOT_REVOKED_SQL}` : \"\"}`,\n\t\t\tvalues: [\n\t\t\t\tc.coordinatorId,\n\t\t\t\ti.browserTransactionHash,\n\t\t\t\tsessionId,\n\t\t\t\ti.credentialHash,\n\t\t\t\tc.revision,\n\t\t\t\tnow,\n\t\t\t\tnow + AUTH_SESSION_TTL_MS,\n\t\t\t\tc.issuer,\n\t\t\t],\n\t\t});\n\t\tif (!row) throw new Error(\"auth_session_persistence_incomplete\");\n\t\treturn { kind: \"issued\", session: dto(row) };\n\t}\n\tprivate async diagnoseRedeem(\n\t\tattemptId: string,\n\t\tbrowserHash: string,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t): Promise<CoordinatorAuthSessionIssueResult> {\n\t\tconst row = await this.first<RedeemDiagnosis>({\n\t\t\tsql: \"SELECT browser_transaction_hash, state, issuer, auth_config_revision, finalized_at_ms, expires_at_ms FROM coordinator_auth_link_attempts WHERE coordinator_id = ? AND attempt_id = ?\",\n\t\t\tvalues: [c.coordinatorId, attemptId],\n\t\t});\n\t\tif (!row || row.browser_transaction_hash !== browserHash)\n\t\t\treturn rejected(\"attempt_unavailable\");\n\t\tif (row.issuer !== c.issuer || row.auth_config_revision !== c.revision)\n\t\t\treturn rejected(\"auth_config_changed\");\n\t\tif (row.state !== \"finalized\" || row.finalized_at_ms === null || now < row.finalized_at_ms)\n\t\t\treturn rejected(\"attempt_unavailable\");\n\t\tif (now >= row.expires_at_ms || now >= row.finalized_at_ms + AUTH_LINK_REDEEM_WINDOW_MS)\n\t\t\treturn rejected(\"redeem_window_expired\");\n\t\treturn rejected(\"attempt_unavailable\");\n\t}\n\tasync readAuthSession(\n\t\tcredentialHash: string,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthSession | null> {\n\t\tconst c = captureConfig(config);\n\t\tif (!c?.enabled || !isHash(credentialHash)) return null;\n\t\tconst now = sessionNow(this.clock);\n\t\tconst connections = await this.connectionSchema();\n\t\tconst row = await this.first<SessionRow>({\n\t\t\tsql: `SELECT s.session_id, s.identity_id, s.link_id, s.issuer, s.subject, s.expires_at_ms FROM coordinator_auth_sessions s JOIN coordinator_auth_account_links l ON ${authSessionLinkMatchSql({ connections })}\n WHERE ${AUTH_SESSION_LIVE_GUARD_SQL}${connections ? ` AND ${CONNECTION_NOT_REVOKED_SQL}` : \"\"}`,\n\t\t\tvalues: [c.coordinatorId, credentialHash, c.issuer, c.revision, now, now],\n\t\t});\n\t\treturn row ? dto(row) : null;\n\t}\n\tasync signOutAuthSession(\n\t\tcredentialHash: string,\n\t\tscope: CoordinatorAuthSessionScope,\n\t): Promise<CoordinatorAuthSessionSignOutResult> {\n\t\tconst s = captureScope(scope);\n\t\tif (!s || !isHash(credentialHash)) return { kind: \"rejected\", error: \"invalid_input\" };\n\t\tconst now = sessionNow(this.clock);\n\t\tawait this.batch([\n\t\t\t{\n\t\t\t\tsql: \"UPDATE coordinator_auth_sessions SET revoked_at_ms = ? WHERE coordinator_id = ? AND credential_hash = ? AND revoked_at_ms IS NULL\",\n\t\t\t\tvalues: [now, s.coordinatorId, credentialHash],\n\t\t\t},\n\t\t]);\n\t\treturn { kind: \"signed_out\" };\n\t}\n\t/** Configured-admin authentication is the caller's prerequisite, never an actor label. */\n\tasync revokeAuthAccountLink(\n\t\tinput: { linkId: string },\n\t\tscope: CoordinatorAuthSessionScope,\n\t): Promise<CoordinatorAuthAccountLinkRevokeResult> {\n\t\tconst s = captureScope(scope);\n\t\tconst i = capture(input, [\"linkId\"]);\n\t\tif (!s || !i || !isAuthControllerId(i.linkId))\n\t\t\treturn { kind: \"rejected\", error: \"invalid_input\" };\n\t\tconst now = sessionNow(this.clock);\n\t\tif (await this.connectionSchema()) {\n\t\t\tconst historical = await this.first({\n\t\t\t\tsql: `SELECT 1 FROM coordinator_auth_account_connection_history l WHERE l.coordinator_id = ? AND l.link_id = ? AND ${authAccountLinkProvenanceSql(\"l\", { connections: true })}`,\n\t\t\t\tvalues: [s.coordinatorId, i.linkId],\n\t\t\t});\n\t\t\tif (historical) {\n\t\t\t\tawait this.batch(historicalRevocationStatements(s.coordinatorId, i.linkId, now));\n\t\t\t\tconst receipt = await this.first({\n\t\t\t\t\tsql: historicalRevocationReadSql(),\n\t\t\t\t\tvalues: [s.coordinatorId, i.linkId],\n\t\t\t\t});\n\t\t\t\tif (!receipt) throw new Error(\"auth_session_persistence_incomplete\");\n\t\t\t\treturn { kind: \"revoked\" };\n\t\t\t}\n\t\t}\n\t\tconst connections = await this.connectionSchema();\n\t\tawait this.batch(revokeStatements(i.linkId, s.coordinatorId, now, { connections }));\n\t\tconst link = await this.first<{ revoked_at_ms: number | null }>({\n\t\t\tsql: `SELECT l.revoked_at_ms FROM coordinator_auth_account_links l WHERE l.coordinator_id = ? AND l.link_id = ? AND ${authAccountLinkProvenanceSql(\"l\", { connections })}`,\n\t\t\tvalues: [s.coordinatorId, i.linkId],\n\t\t});\n\t\tif (!link) return { kind: \"rejected\", error: \"link_unavailable\" };\n\t\tconst receipt = await this.first({\n\t\t\tsql: revokeReadSql({ connections }),\n\t\t\tvalues: [s.coordinatorId, i.linkId],\n\t\t});\n\t\tif (link.revoked_at_ms === null || !receipt)\n\t\t\tthrow new Error(\"auth_session_persistence_incomplete\");\n\t\treturn { kind: \"revoked\" };\n\t}\n}\nfunction auditMatch(options: { connections: boolean }) {\n\treturn `a.coordinator_id = l.coordinator_id AND a.link_id = l.link_id AND a.action = 'link_created'\n AND a.attempt_id = l.attempt_id AND a.identity_id = l.identity_id AND a.controller_attestation_id IS l.controller_attestation_id\n AND a.authority_kind = l.authority_kind AND a.device_claim_id IS l.device_claim_id AND ${authAccountLinkProvenanceSql(\"l\", options)}\n AND a.auth_config_revision = l.auth_config_revision AND a.created_at_ms = l.created_at_ms`;\n}\nfunction revokeStatements(\n\tlinkId: string,\n\tcoordinatorId: string,\n\tnow: number,\n\toptions: { connections: boolean },\n): AuthLinkStatement[] {\n\tconst ACCOUNT_PROVENANCE = authAccountLinkProvenanceSql(\"l\", options),\n\t\tAUDIT_MATCH = auditMatch(options);\n\treturn [\n\t\t{\n\t\t\tsql: `UPDATE coordinator_auth_account_links AS l SET revoked_at_ms = ? WHERE l.coordinator_id = ? AND l.link_id = ? AND l.revoked_at_ms IS NULL AND ${ACCOUNT_PROVENANCE}`,\n\t\t\tvalues: [now, coordinatorId, linkId],\n\t\t},\n\t\t{\n\t\t\tsql: `INSERT INTO coordinator_auth_link_audit_log (coordinator_id, link_id, action, attempt_id, identity_id, group_id, device_id, fingerprint, controller_attestation_id, auth_config_revision, created_at_ms, authority_kind, device_claim_id)\n SELECT l.coordinator_id, l.link_id, 'link_revoked', a.attempt_id, a.identity_id, a.group_id, a.device_id, a.fingerprint, a.controller_attestation_id, a.auth_config_revision, l.revoked_at_ms, l.authority_kind, l.device_claim_id\n FROM coordinator_auth_account_links l JOIN coordinator_auth_link_audit_log a ON ${AUDIT_MATCH}\n WHERE l.coordinator_id = ? AND l.link_id = ? AND l.revoked_at_ms IS NOT NULL\n ON CONFLICT(coordinator_id, link_id, action) DO NOTHING`,\n\t\t\tvalues: [coordinatorId, linkId],\n\t\t},\n\t];\n}\nfunction revokeReadSql(options: { connections: boolean }) {\n\treturn `SELECT 1 FROM coordinator_auth_account_links l JOIN coordinator_auth_link_audit_log a ON ${auditMatch(options)}\n JOIN coordinator_auth_link_audit_log r ON r.coordinator_id = l.coordinator_id AND r.link_id = l.link_id AND r.action = 'link_revoked'\n AND r.attempt_id = a.attempt_id AND r.identity_id = a.identity_id AND r.group_id = a.group_id AND r.device_id = a.device_id\n AND r.fingerprint = a.fingerprint AND r.controller_attestation_id IS a.controller_attestation_id AND r.authority_kind = a.authority_kind AND r.device_claim_id IS a.device_claim_id AND r.auth_config_revision = a.auth_config_revision AND r.created_at_ms = l.revoked_at_ms\n WHERE l.coordinator_id = ? AND l.link_id = ? AND l.revoked_at_ms IS NOT NULL`;\n}\n","import {\n\tconnectionProfileColumns,\n\thasConnectionSessionSchema,\n} from \"./coordinator-account-connection-session.js\";\nimport { CONNECTION_NOT_REVOKED_SQL } from \"./coordinator-account-connection-storage.js\";\nimport {\n\tAUTH_ACCOUNT_PROFILE_WRITE_WINDOW_MS,\n\ttype CoordinatorAuthAccountProfileClearResult,\n\ttype CoordinatorAuthAccountProfileInput,\n\ttype CoordinatorAuthAccountProfileStore,\n\ttype CoordinatorAuthAccountProfileWriteResult,\n\ttype CoordinatorAuthSessionAccount,\n} from \"./coordinator-auth-account-profile-contract.js\";\nimport { isCoordinatorAccountIssuer } from \"./coordinator-auth-contract.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport type { CoordinatorAuthLinkConfig } from \"./coordinator-auth-link-contract.js\";\nimport { authAccountLinkProvenanceSql } from \"./coordinator-auth-link-provenance.js\";\nimport { authPersistenceError } from \"./coordinator-auth-schema.js\";\nimport {\n\tAUTH_SESSION_LINK_MATCH_SQL,\n\tAUTH_SESSION_LIVE_GUARD_SQL,\n\tauthSessionLinkMatchSql,\n\tauthSessionNow,\n} from \"./coordinator-auth-session.js\";\nimport type { CoordinatorOidcProfile } from \"./coordinator-oidc.js\";\n\nexport * from \"./coordinator-auth-account-profile-contract.js\";\n\nfunction revokedProfileTargetsSql(options: { connections: boolean }): string {\n\tconst current =\n\t\t\"SELECT l.link_id FROM coordinator_auth_account_links l WHERE l.coordinator_id=? AND l.revoked_at_ms IS NOT NULL\";\n\tif (!options.connections) return `${current} AND l.link_id=?`;\n\treturn `WITH requested AS MATERIALIZED (\n SELECT l.coordinator_id,l.identity_id FROM coordinator_auth_account_connection_history l\n WHERE l.coordinator_id=? AND l.link_id=? AND l.revoked_at_ms IS NOT NULL\n AND ${authAccountLinkProvenanceSql(\"l\", { connections: true })})\n ${current} AND ${authAccountLinkProvenanceSql(\"l\", { connections: true })}\n AND (l.link_id=? OR EXISTS (SELECT 1 FROM requested h WHERE h.coordinator_id=l.coordinator_id AND h.identity_id=l.identity_id))`;\n}\n\nfunction hasPlainPrototype(value: object): boolean {\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\nfunction capture(\n\tvalue: unknown,\n\toptions: { fields: readonly string[]; required: boolean; plain?: boolean },\n): Record<string, unknown> | null {\n\tif (!value || typeof value !== \"object\") return null;\n\ttry {\n\t\tif (Array.isArray(value)) return null;\n\t\tif (options.plain && !hasPlainPrototype(value)) return null;\n\t\tconst result: Record<string, unknown> = Object.create(null);\n\t\tfor (const key of options.fields) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\t\tif (!descriptor) {\n\t\t\t\tif (options.required) return null;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!Object.hasOwn(descriptor, \"value\")) return null;\n\t\t\tresult[key] = descriptor.value;\n\t\t}\n\t\treturn result;\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction isHash(value: unknown): value is string {\n\treturn typeof value === \"string\" && /^[0-9a-f]{64}$/.test(value);\n}\nfunction captureConfig(value: unknown): CoordinatorAuthLinkConfig | null {\n\tconst c = capture(value, {\n\t\tfields: [\"coordinatorId\", \"issuer\", \"revision\", \"enabled\"],\n\t\trequired: true,\n\t});\n\tif (\n\t\t!c ||\n\t\t!isAuthControllerId(c.coordinatorId) ||\n\t\t!isCoordinatorAccountIssuer(c.issuer) ||\n\t\t!isHash(c.revision) ||\n\t\ttypeof c.enabled !== \"boolean\"\n\t)\n\t\treturn null;\n\treturn {\n\t\tcoordinatorId: c.coordinatorId,\n\t\tissuer: c.issuer,\n\t\trevision: c.revision,\n\t\tenabled: c.enabled,\n\t};\n}\nfunction optionalText(value: unknown, maxLength: number): string | undefined {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\tvalue.length === 0 ||\n\t\tvalue.length > maxLength ||\n\t\tvalue.trim().length === 0 ||\n\t\t/[\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(value)\n\t)\n\t\treturn undefined;\n\treturn value;\n}\nfunction optionalPicture(value: unknown): string | undefined {\n\tconst text = optionalText(value, 2048);\n\tif (\n\t\t!text ||\n\t\ttext.trim() !== text ||\n\t\ttext.includes(\"\\\\\") ||\n\t\ttext.includes(\"#\") ||\n\t\t!/^https:\\/\\//i.test(text) ||\n\t\t/^https:\\/\\/[^/?#]*@/i.test(text)\n\t)\n\t\treturn undefined;\n\ttry {\n\t\tconst url = new URL(text);\n\t\tif (url.protocol !== \"https:\" || url.username || url.password || url.hash) return undefined;\n\t\tconst canonical = url.href;\n\t\treturn optionalText(canonical, 2048);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\nfunction projectProfile(fields: Record<string, unknown>): CoordinatorOidcProfile {\n\tconst profile: CoordinatorOidcProfile = {};\n\tconst displayName = optionalText(fields.displayName, 256);\n\tconst email = optionalText(fields.email, 320);\n\tconst pictureUrl = optionalPicture(fields.pictureUrl);\n\tif (displayName !== undefined) profile.displayName = displayName;\n\tif (email !== undefined) {\n\t\tprofile.email = email;\n\t\tif (typeof fields.emailVerified === \"boolean\") profile.emailVerified = fields.emailVerified;\n\t}\n\tif (pictureUrl !== undefined) profile.pictureUrl = pictureUrl;\n\treturn profile;\n}\n/** Capture display claims without invoking accessors or retaining unknown fields. */\nexport function captureAuthAccountProfile(value: unknown): CoordinatorOidcProfile | null {\n\tconst fields = capture(value, {\n\t\tfields: [\"displayName\", \"email\", \"emailVerified\", \"pictureUrl\"],\n\t\trequired: false,\n\t\tplain: true,\n\t});\n\treturn fields ? projectProfile(fields) : null;\n}\ninterface AccountRow {\n\tsession_id: string;\n\tidentity_id: string;\n\tlink_id: string;\n\tissuer: string;\n\tsubject: string;\n\texpires_at_ms: number;\n\tdisplay_name: unknown;\n\temail: unknown;\n\temail_verified: unknown;\n\tpicture_url: unknown;\n}\nfunction sessionFromSql(options: { connections: boolean }) {\n\treturn `FROM coordinator_auth_sessions s JOIN coordinator_auth_account_links l ON ${authSessionLinkMatchSql(options)}`;\n}\nconst SESSION_FROM_SQL = `FROM coordinator_auth_sessions s JOIN coordinator_auth_account_links l ON ${AUTH_SESSION_LINK_MATCH_SQL}`;\nfunction profileSourceSql(options: { connections: boolean }) {\n\treturn `${sessionFromSql(options)}\n JOIN coordinator_auth_session_receipts r ON r.coordinator_id = s.coordinator_id\n AND r.session_id = s.session_id AND r.browser_transaction_hash = s.browser_transaction_hash\n AND r.link_id = s.link_id AND r.auth_config_revision = s.auth_config_revision AND r.created_at_ms = s.created_at_ms\n WHERE ${AUTH_SESSION_LIVE_GUARD_SQL} AND r.source = 'signin' AND r.attempt_id IS NULL\n ${\n\t\toptions.connections\n\t\t\t? `AND ${CONNECTION_NOT_REVOKED_SQL} AND r.source_order IS NOT NULL AND NOT EXISTS (\n SELECT 1 FROM coordinator_auth_link_profiles b JOIN coordinator_account_change_attempts x ON x.coordinator_id = b.coordinator_id AND x.attempt_id = b.source_change_attempt_id\n WHERE b.coordinator_id = l.coordinator_id AND b.link_id = l.link_id AND x.target_link_id = l.link_id AND x.intent = 'refresh' AND x.state = 'completed' AND x.browser_order = b.source_order AND b.source_order >= r.source_order)`\n\t\t\t: \"\"\n}`;\n}\nfunction profileWriteSql(options: { connections: boolean }) {\n\treturn `INSERT INTO coordinator_auth_account_profiles\n (coordinator_id, link_id, display_name, email, email_verified, picture_url, source_session_id, source_signed_in_at_ms${options.connections ? \",source_order\" : \"\"})\n SELECT s.coordinator_id, s.link_id, ?, ?, ?, ?, s.session_id, s.created_at_ms${options.connections ? \",r.source_order\" : \"\"}\n ${profileSourceSql(options)} AND ? < s.created_at_ms + ${AUTH_ACCOUNT_PROFILE_WRITE_WINDOW_MS}\n ON CONFLICT(coordinator_id, link_id) DO UPDATE SET\n display_name = excluded.display_name, email = excluded.email,\n email_verified = excluded.email_verified, picture_url = excluded.picture_url,\n source_session_id = excluded.source_session_id, source_signed_in_at_ms = excluded.source_signed_in_at_ms${options.connections ? \",source_order = excluded.source_order\" : \"\"}\n WHERE ${options.connections ? \"excluded.source_order > coalesce(coordinator_auth_account_profiles.source_order,0)\" : \"excluded.source_signed_in_at_ms > coordinator_auth_account_profiles.source_signed_in_at_ms\"}`;\n}\nfunction profileReadSql(options: { connections: boolean }) {\n\treturn `SELECT s.session_id, s.identity_id, s.link_id, s.issuer, s.subject, s.expires_at_ms,\n ${\n\t\toptions.connections\n\t\t\t? connectionProfileColumns(\"p\")\n\t\t\t: `CASE WHEN p.link_id IS NOT NULL THEN p.display_name ELSE b.display_name END AS display_name,\n CASE WHEN p.link_id IS NOT NULL THEN p.email ELSE b.email END AS email,\n CASE WHEN p.link_id IS NOT NULL THEN p.email_verified ELSE b.email_verified END AS email_verified,\n CASE WHEN p.link_id IS NOT NULL THEN p.picture_url ELSE b.picture_url END AS picture_url`\n}\n ${sessionFromSql(options)} LEFT JOIN coordinator_auth_account_profiles p\n ON p.coordinator_id = s.coordinator_id AND p.link_id = s.link_id\n LEFT JOIN coordinator_auth_link_profiles b ON b.coordinator_id = l.coordinator_id AND b.link_id = l.link_id\n AND b.attempt_id = l.attempt_id AND b.issuer = l.issuer AND b.subject = l.subject\n AND b.auth_config_revision = l.auth_config_revision\n WHERE ${AUTH_SESSION_LIVE_GUARD_SQL}${options.connections ? ` AND ${CONNECTION_NOT_REVOKED_SQL}` : \"\"}`;\n}\nconst PROFILE_RECORDED_SQL = `SELECT 1 ${SESSION_FROM_SQL}\n JOIN coordinator_auth_account_profiles p ON p.coordinator_id = s.coordinator_id AND p.link_id = s.link_id\n AND p.source_session_id = s.session_id\n WHERE ${AUTH_SESSION_LIVE_GUARD_SQL}`;\nconst ORDERED_PROFILE_RECORDED_SQL = `SELECT 1 ${profileSourceSql({ connections: true })}\n AND EXISTS (SELECT 1 FROM coordinator_auth_account_profiles p\n WHERE p.coordinator_id=s.coordinator_id AND p.link_id=s.link_id\n AND p.source_session_id=s.session_id AND p.source_signed_in_at_ms=s.created_at_ms\n AND p.source_order=r.source_order)`;\nfunction liveValues(\n\tc: CoordinatorAuthLinkConfig,\n\tcredentialHash: string,\n\tnow: number,\n): AuthLinkStatement[\"values\"] {\n\treturn [c.coordinatorId, credentialHash, c.issuer, c.revision, now, now];\n}\n\n/** Optional verified display snapshots only. No JWT/cookie verification or authority changes.\n * Purging stays separate from revocation: an older database lacking this table must\n * never prevent revocation. Future public handlers must authenticate the admin first.\n */\nexport class AuthAccountProfileOperations implements CoordinatorAuthAccountProfileStore {\n\tconstructor(\n\t\tprivate readonly backend: AuthLinkBackend,\n\t\tprivate readonly clock: () => number = Date.now,\n\t) {}\n\tprivate async first<T>(statement: AuthLinkStatement): Promise<T | null> {\n\t\ttry {\n\t\t\treturn await this.backend.first<T>(statement);\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_account_profile_persistence_error\");\n\t\t}\n\t}\n\tprivate async connectionSchema(): Promise<boolean> {\n\t\ttry {\n\t\t\treturn await hasConnectionSessionSchema(this.backend);\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_account_profile_persistence_error\");\n\t\t}\n\t}\n\tprivate async run(statement: AuthLinkStatement): Promise<number> {\n\t\ttry {\n\t\t\treturn await this.backend.run(statement);\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_account_profile_persistence_error\");\n\t\t}\n\t}\n\tasync recordAuthAccountProfile(\n\t\tinput: CoordinatorAuthAccountProfileInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthAccountProfileWriteResult> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = capture(input, { fields: [\"credentialHash\", \"profile\"], required: true });\n\t\tif (!c || !i || !isHash(i.credentialHash)) return { kind: \"rejected\", error: \"invalid_input\" };\n\t\tconst fields = capture(i.profile, {\n\t\t\tfields: [\"displayName\", \"email\", \"emailVerified\", \"pictureUrl\"],\n\t\t\trequired: false,\n\t\t\tplain: true,\n\t\t});\n\t\tif (!fields) return { kind: \"rejected\", error: \"invalid_input\" };\n\t\tif (!c.enabled) return { kind: \"rejected\", error: \"auth_config_changed\" };\n\t\tconst profile = projectProfile(fields);\n\t\tconst now = authSessionNow(this.clock);\n\t\tconst connections = await this.connectionSchema();\n\t\tlet verified: number | null = null;\n\t\tif (profile.emailVerified !== undefined) verified = Number(profile.emailVerified);\n\t\tconst changed = await this.run({\n\t\t\tsql: profileWriteSql({ connections }),\n\t\t\tvalues: [\n\t\t\t\tprofile.displayName ?? null,\n\t\t\t\tprofile.email ?? null,\n\t\t\t\tverified,\n\t\t\t\tprofile.pictureUrl ?? null,\n\t\t\t\t...liveValues(c, i.credentialHash, now),\n\t\t\t\tnow,\n\t\t\t],\n\t\t});\n\t\tif (connections && changed !== 0) return { kind: changed === 1 ? \"recorded\" : \"not_recorded\" };\n\t\tconst recorded = await this.first({\n\t\t\tsql: connections ? ORDERED_PROFILE_RECORDED_SQL : PROFILE_RECORDED_SQL,\n\t\t\tvalues: liveValues(c, i.credentialHash, authSessionNow(this.clock)),\n\t\t});\n\t\treturn { kind: recorded ? \"recorded\" : \"not_recorded\" };\n\t}\n\tasync readAuthSessionAccount(\n\t\tcredentialHash: string,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthSessionAccount | null> {\n\t\tconst c = captureConfig(config);\n\t\tif (!c?.enabled || !isHash(credentialHash)) return null;\n\t\tconst row = await this.first<AccountRow>({\n\t\t\tsql: profileReadSql({ connections: await this.connectionSchema() }),\n\t\t\tvalues: liveValues(c, credentialHash, authSessionNow(this.clock)),\n\t\t});\n\t\tif (!row) return null;\n\t\tlet emailVerified: boolean | undefined;\n\t\tif (row.email_verified === 0) emailVerified = false;\n\t\tif (row.email_verified === 1) emailVerified = true;\n\t\treturn {\n\t\t\tsession: {\n\t\t\t\tsessionId: row.session_id,\n\t\t\t\tidentityId: row.identity_id,\n\t\t\t\tlinkId: row.link_id,\n\t\t\t\taccount: { issuer: row.issuer, subject: row.subject },\n\t\t\t\texpiresAtMs: row.expires_at_ms,\n\t\t\t},\n\t\t\tprofile: projectProfile({\n\t\t\t\tdisplayName: row.display_name,\n\t\t\t\temail: row.email,\n\t\t\t\temailVerified,\n\t\t\t\tpictureUrl: row.picture_url,\n\t\t\t}),\n\t\t};\n\t}\n\tasync clearRevokedAuthAccountProfile(\n\t\tinput: { linkId: string },\n\t\tscope: { coordinatorId: string },\n\t): Promise<CoordinatorAuthAccountProfileClearResult> {\n\t\tconst i = capture(input, { fields: [\"linkId\"], required: true });\n\t\tconst s = capture(scope, { fields: [\"coordinatorId\"], required: true });\n\t\tif (!i || !s || !isAuthControllerId(i.linkId) || !isAuthControllerId(s.coordinatorId))\n\t\t\treturn { kind: \"rejected\", error: \"invalid_input\" };\n\t\tconst connections = await this.connectionSchema();\n\t\tconst targets = revokedProfileTargetsSql({ connections });\n\t\tconst pins = [s.coordinatorId, i.linkId];\n\t\tconst values = connections ? [s.coordinatorId, ...pins, ...pins] : [s.coordinatorId, ...pins];\n\t\tlet deletedCount = 0;\n\t\tfor (const table of [\"coordinator_auth_account_profiles\", \"coordinator_auth_link_profiles\"]) {\n\t\t\tdeletedCount += await this.run({\n\t\t\t\tsql: `DELETE FROM ${table} WHERE coordinator_id=? AND link_id IN (${targets})`,\n\t\t\t\tvalues,\n\t\t\t});\n\t\t}\n\t\treturn { kind: \"cleared\", deletedCount };\n\t}\n}\n","import type { AuthLinkBackend } from \"./coordinator-auth-link.js\";\n\nexport const HEADLESS_CODE_LIMITS_TABLE = \"coordinator_headless_link_code_limits\";\nexport const HEADLESS_LINK_PROVENANCE_TABLE = \"coordinator_headless_link_provenance\";\n\n/**\n * Additive storage for headless account linking. The definitions name only\n * their own tables: the auth readiness checks reject any unknown table, view or\n * trigger whose SQL mentions an auth table, and any object named with an auth\n * table's prefix. That is why provenance has no foreign keys.\n *\n * Mirror: packages/cloudflare-coordinator-worker/migrations/0043_add_headless_account_linking.sql\n * (generated from these statements; coordinator-auth-headless-schema.test.ts checks parity).\n */\nexport const HEADLESS_LINK_SCHEMA_STATEMENTS: readonly string[] = Object.freeze([\n\t`CREATE TABLE IF NOT EXISTS ${HEADLESS_CODE_LIMITS_TABLE} (\n coordinator_id TEXT NOT NULL CHECK (typeof(coordinator_id) = 'text' AND length(coordinator_id) BETWEEN 1 AND 256),\n scope TEXT NOT NULL CHECK (scope IN ('client','coordinator')),\n key_hash TEXT NOT NULL CHECK ((scope = 'coordinator' AND key_hash = '')\n OR (scope = 'client' AND length(key_hash) = 64 AND key_hash NOT GLOB '*[^0-9a-f]*')),\n window_start_ms INTEGER NOT NULL CHECK (typeof(window_start_ms) = 'integer'\n AND window_start_ms BETWEEN 0 AND 9007199254740991),\n failures INTEGER NOT NULL CHECK (typeof(failures) = 'integer' AND failures BETWEEN 1 AND 9007199254740991),\n PRIMARY KEY (coordinator_id, scope, key_hash)\n ) WITHOUT ROWID;`,\n\t`CREATE TABLE IF NOT EXISTS ${HEADLESS_LINK_PROVENANCE_TABLE} (\n coordinator_id TEXT NOT NULL,\n link_id TEXT NOT NULL,\n identity_id TEXT NOT NULL,\n issuer TEXT NOT NULL,\n subject TEXT NOT NULL,\n attempt_id TEXT NOT NULL,\n created_at_ms INTEGER NOT NULL CHECK (typeof(created_at_ms) = 'integer' AND created_at_ms >= 0),\n PRIMARY KEY (coordinator_id, link_id),\n UNIQUE (coordinator_id, attempt_id)\n ) WITHOUT ROWID;`,\n\t`CREATE INDEX IF NOT EXISTS idx_headless_link_provenance_account\n ON ${HEADLESS_LINK_PROVENANCE_TABLE} (coordinator_id, issuer, subject, identity_id, created_at_ms);`,\n\t`CREATE TRIGGER IF NOT EXISTS headless_link_provenance_immutable\n BEFORE UPDATE ON ${HEADLESS_LINK_PROVENANCE_TABLE}\n BEGIN SELECT RAISE(ABORT,'headless_link_provenance_immutable'); END;`,\n\t// Rebind refuses headless-linked accounts by finding this row, so losing it would lift the block.\n\t`CREATE TRIGGER IF NOT EXISTS headless_link_provenance_retained\n BEFORE DELETE ON ${HEADLESS_LINK_PROVENANCE_TABLE}\n BEGIN SELECT RAISE(ABORT,'headless_link_provenance_retained'); END;`,\n\t// REPLACE conflict resolution deletes without firing delete triggers unless recursive triggers are on.\n\t`CREATE TRIGGER IF NOT EXISTS headless_link_provenance_no_replace\n BEFORE INSERT ON ${HEADLESS_LINK_PROVENANCE_TABLE}\n WHEN EXISTS (SELECT 1 FROM ${HEADLESS_LINK_PROVENANCE_TABLE} p WHERE p.coordinator_id = NEW.coordinator_id\n AND (p.link_id = NEW.link_id OR p.attempt_id = NEW.attempt_id))\n BEGIN SELECT RAISE(ABORT,'headless_link_provenance_retained'); END;`,\n]);\n\nexport const HEADLESS_LINK_SCHEMA_SQL = HEADLESS_LINK_SCHEMA_STATEMENTS.join(\"\\n\");\n\nconst PRESENT_SQL = `SELECT\n EXISTS (SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = '${HEADLESS_CODE_LIMITS_TABLE}') AS limits,\n EXISTS (SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = '${HEADLESS_LINK_PROVENANCE_TABLE}') AS provenance`;\n\nasync function readPresence(backend: Pick<AuthLinkBackend, \"first\">) {\n\tconst row = await backend.first<{ limits: number; provenance: number }>({\n\t\tsql: PRESENT_SQL,\n\t\tvalues: [],\n\t});\n\treturn { limits: row?.limits === 1, provenance: row?.provenance === 1 };\n}\n\n/**\n * The backend, only when both headless tables exist. A D1 database before\n * migration 0043 returns null: headless linking is off there, and every other\n * auth capability and readiness check is unaffected.\n */\nexport async function readHeadlessLinkBackend(\n\tbackend: AuthLinkBackend,\n): Promise<AuthLinkBackend | null> {\n\tconst present = await readPresence(backend);\n\treturn present.limits && present.provenance ? backend : null;\n}\n\n/** Headless finalize refuses to link when it cannot record provenance in the same batch. */\nexport async function hasHeadlessLinkProvenance(\n\tbackend: Pick<AuthLinkBackend, \"first\">,\n): Promise<boolean> {\n\treturn (await readPresence(backend)).provenance;\n}\n","import {\n\thasHeadlessLinkProvenance,\n\tHEADLESS_LINK_PROVENANCE_TABLE as TABLE,\n} from \"./coordinator-auth-headless-schema.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport { AUTH_LINK_HEADLESS_MARKER_SQL } from \"./coordinator-auth-link-headless.js\";\n\nexport interface HeadlessLinkProvenance {\n\tcoordinatorId: string;\n\tlinkId: string;\n\tidentityId: string;\n\tissuer: string;\n\tsubject: string;\n\tattemptId: string;\n\tcreatedAtMs: number;\n}\nexport type HeadlessLinkProvenanceQuery =\n\t| string\n\t| { identityId: string; issuer: string; subject: string };\n\n/**\n * Selects only the link this finalize batch just wrote: the attempt must carry\n * the batch's own link ID, so an exact retry (which finalizes nothing) inserts\n * no row and cannot collide with the first one.\n */\nexport function headlessLinkProvenanceStatement(\n\tcoordinatorId: string,\n\tattemptId: string,\n\tlinkId: string,\n): AuthLinkStatement {\n\treturn {\n\t\tsql: `INSERT INTO ${TABLE} (coordinator_id, link_id, identity_id, issuer, subject, attempt_id, created_at_ms)\n SELECT t.coordinator_id, t.link_id, t.identity_id, t.issuer, t.account_subject, t.attempt_id, t.finalized_at_ms\n FROM coordinator_auth_link_attempts t JOIN coordinator_auth_account_links l\n ON l.coordinator_id = t.coordinator_id AND l.link_id = t.link_id AND l.attempt_id = t.attempt_id\n WHERE t.coordinator_id = ? AND t.attempt_id = ? AND t.link_id = ? AND t.state = 'finalized'\n AND t.loopback_redirect = ${AUTH_LINK_HEADLESS_MARKER_SQL}`,\n\t\tvalues: [coordinatorId, attemptId, linkId],\n\t};\n}\n\ninterface Row {\n\tcoordinator_id: string;\n\tlink_id: string;\n\tidentity_id: string;\n\tissuer: string;\n\tsubject: string;\n\tattempt_id: string;\n\tcreated_at_ms: number;\n}\n\nfunction lookup(coordinatorId: string, query: HeadlessLinkProvenanceQuery): AuthLinkStatement {\n\tconst select = `SELECT * FROM ${TABLE} WHERE coordinator_id = ?`;\n\tif (typeof query === \"string\")\n\t\treturn { sql: `${select} AND link_id = ?`, values: [coordinatorId, query] };\n\treturn {\n\t\tsql: `${select} AND issuer = ? AND subject = ? AND identity_id = ?\n ORDER BY created_at_ms DESC, link_id DESC LIMIT 1`,\n\t\tvalues: [coordinatorId, query.issuer, query.subject, query.identityId],\n\t};\n}\n\n/**\n * Provenance for one link ID, or the most recent headless link of an account\n * to an Identity. Callers must first confirm the table exists (see\n * readHeadlessLinkBackend); a missing table throws.\n */\nexport async function readHeadlessLinkProvenance(\n\tbackend: Pick<AuthLinkBackend, \"first\">,\n\tcoordinatorId: string,\n\tquery: HeadlessLinkProvenanceQuery,\n): Promise<HeadlessLinkProvenance | null> {\n\tconst row = await backend.first<Row>(lookup(coordinatorId, query));\n\tif (!row) return null;\n\treturn {\n\t\tcoordinatorId: row.coordinator_id,\n\t\tlinkId: row.link_id,\n\t\tidentityId: row.identity_id,\n\t\tissuer: row.issuer,\n\t\tsubject: row.subject,\n\t\tattemptId: row.attempt_id,\n\t\tcreatedAtMs: row.created_at_ms,\n\t};\n}\n\n/**\n * Whether this link was written by headless finalize. False on a coordinator\n * without the provenance table: no link there can be headless.\n */\nexport async function isHeadlessLinkId(\n\tbackend: Pick<AuthLinkBackend, \"first\">,\n\tcoordinatorId: string,\n\tlinkId: string,\n): Promise<boolean> {\n\tif (!(await hasHeadlessLinkProvenance(backend))) return false;\n\treturn (await readHeadlessLinkProvenance(backend, coordinatorId, linkId)) !== null;\n}\n\n/**\n * Commit guard for rebind and owner enrollment on the attempt `a`: its target\n * link has no headless provenance. Include only when the provenance table exists.\n */\nexport const NO_HEADLESS_TARGET_LINK_SQL = `NOT EXISTS (SELECT 1 FROM ${TABLE} p\n WHERE p.coordinator_id = a.coordinator_id AND p.link_id = a.link_id)`;\n\n/**\n * A column expression (1 or 0) for whether the provenance table exists. Callers\n * add it to a read they already make, then reference the table only when it\n * reported 1, so a coordinator without the table never sees a query naming it.\n */\nexport const HEADLESS_PROVENANCE_PRESENT_SQL = `EXISTS (SELECT 1 FROM sqlite_master\n WHERE type = 'table' AND name = '${TABLE}')`;\n\n/** A column expression for whether link `?` of coordinator `coordinator` is headless. Table must exist. */\nexport function headlessLinkExistsSql(coordinator: string): string {\n\treturn `EXISTS (SELECT 1 FROM ${TABLE} hp WHERE hp.coordinator_id = ${coordinator} AND hp.link_id = ?)`;\n}\n","import { captureAuthAccountProfile } from \"./coordinator-auth-account-profile.js\";\nimport type { AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport type {\n\tCoordinatorAuthLinkConfig,\n\tCoordinatorAuthLinkOidcInput,\n} from \"./coordinator-auth-link-contract.js\";\n\n/** Display metadata only. A nullable link_id separates staging from publication. */\nexport const AUTH_LINK_PROFILE_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS coordinator_auth_link_profiles (\n coordinator_id TEXT NOT NULL,\n attempt_id TEXT NOT NULL,\n issuer TEXT NOT NULL,\n subject TEXT NOT NULL,\n auth_config_revision TEXT NOT NULL,\n browser_transaction_hash TEXT NOT NULL,\n link_id TEXT,\n display_name TEXT,\n email TEXT,\n email_verified INTEGER CHECK (email_verified IS NULL OR (email_verified IN (0,1) AND email IS NOT NULL)),\n picture_url TEXT,\n verified_at_ms INTEGER NOT NULL,\n PRIMARY KEY (coordinator_id, attempt_id),\n UNIQUE (coordinator_id, link_id)\n);`;\n\n/** Must immediately follow the verified OIDC update in the same atomic batch.\n * The native change count prevents same-timestamp replays from filling missing claims.\n */\nexport function stageAuthLinkProfile(\n\ti: CoordinatorAuthLinkOidcInput,\n\tc: CoordinatorAuthLinkConfig,\n\tnow: number,\n): AuthLinkStatement | null {\n\tconst p = captureAuthAccountProfile(i.profile);\n\tif (!p) return null;\n\tlet emailVerified: number | null = null;\n\tif (p.emailVerified !== undefined) emailVerified = Number(p.emailVerified);\n\treturn {\n\t\tsql: `INSERT INTO coordinator_auth_link_profiles\n (coordinator_id,attempt_id,issuer,subject,auth_config_revision,browser_transaction_hash,\n display_name,email,email_verified,picture_url,verified_at_ms)\n SELECT coordinator_id,attempt_id,issuer,account_subject,auth_config_revision,browser_transaction_hash,?,?,?,?,oidc_verified_at_ms\n FROM coordinator_auth_link_attempts WHERE changes() = 1 AND coordinator_id = ? AND attempt_id = ? AND issuer = ?\n AND account_subject = ? AND auth_config_revision = ? AND browser_transaction_hash = ?\n AND state = 'oidc_verified' AND oidc_verified_at_ms = ? AND expires_at_ms > ?\n ON CONFLICT(coordinator_id,attempt_id) DO NOTHING`,\n\t\tvalues: [\n\t\t\tp.displayName ?? null,\n\t\t\tp.email ?? null,\n\t\t\temailVerified,\n\t\t\tp.pictureUrl ?? null,\n\t\t\tc.coordinatorId,\n\t\t\ti.attemptId,\n\t\t\tc.issuer,\n\t\t\ti.account.subject,\n\t\t\tc.revision,\n\t\t\ti.browserTransactionHash,\n\t\t\tnow,\n\t\t\tnow,\n\t\t],\n\t};\n}\n\n/** Append to the finalization batch after the link/audit inserts; conflicts roll back all writes. */\nexport function promoteAuthLinkProfile(\n\tcoordinatorId: string,\n\tattemptId: string,\n\tlinkId: string,\n): AuthLinkStatement {\n\treturn {\n\t\tsql: `UPDATE coordinator_auth_link_profiles AS p SET link_id = ? WHERE p.coordinator_id = ?\n AND p.attempt_id = ? AND p.link_id IS NULL AND EXISTS (\n SELECT 1 FROM coordinator_auth_link_attempts t JOIN coordinator_auth_account_links l\n ON l.coordinator_id = t.coordinator_id AND l.attempt_id = t.attempt_id AND l.link_id = t.link_id\n AND l.issuer = t.issuer AND l.subject = t.account_subject AND l.identity_id = t.identity_id\n AND l.auth_config_revision = t.auth_config_revision AND l.revoked_at_ms IS NULL\n WHERE t.coordinator_id = p.coordinator_id AND t.attempt_id = p.attempt_id AND t.link_id = ?\n AND t.state = 'finalized' AND t.issuer = p.issuer AND t.account_subject = p.subject\n AND t.auth_config_revision = p.auth_config_revision AND t.browser_transaction_hash = p.browser_transaction_hash\n AND t.oidc_verified_at_ms = p.verified_at_ms)`,\n\t\tvalues: [linkId, coordinatorId, attemptId, linkId],\n\t};\n}\n\n/** Delete private staging promptly on failure/expiry/config change, and published rows on revocation.\n * Publication never depends on cleanup having run. No authority records are modified.\n */\nexport function cleanAuthLinkProfiles(\n\tc: CoordinatorAuthLinkConfig,\n\tnow: number,\n\tlimit: number,\n): AuthLinkStatement {\n\treturn {\n\t\tsql: `DELETE FROM coordinator_auth_link_profiles WHERE coordinator_id = ? AND attempt_id IN (\n SELECT p.attempt_id FROM coordinator_auth_link_profiles p WHERE p.coordinator_id = ? AND (\n (p.link_id IS NULL AND (p.issuer <> ? OR p.auth_config_revision <> ? OR NOT EXISTS (\n SELECT 1 FROM coordinator_auth_link_attempts t WHERE t.coordinator_id = p.coordinator_id\n AND t.attempt_id = p.attempt_id AND t.state IN ('oidc_verified','confirmed') AND t.expires_at_ms > ?)))\n OR (p.link_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_links l\n WHERE l.coordinator_id = p.coordinator_id AND l.link_id = p.link_id AND l.attempt_id = p.attempt_id\n AND l.issuer = p.issuer AND l.subject = p.subject AND l.auth_config_revision = p.auth_config_revision\n AND l.revoked_at_ms IS NULL))) LIMIT ?)`,\n\t\tvalues: [c.coordinatorId, c.coordinatorId, c.issuer, c.revision, now, limit],\n\t};\n}\n","export type CoordinatorAuthLoopbackResult =\n\t| { ok: true; destination: string; host: \"127.0.0.1\" | \"[::1]\"; port: number }\n\t| { ok: false; error: \"invalid_loopback_destination\" };\n\nconst LOOPBACK_DESTINATION =\n\t/^http:\\/\\/(127\\.0\\.0\\.1|\\[::1\\]):([1-9][0-9]*)\\/codemem\\/auth\\/complete$/;\n\nexport function parseCoordinatorAuthLoopback(value: unknown): CoordinatorAuthLoopbackResult {\n\tif (typeof value !== \"string\") return { ok: false, error: \"invalid_loopback_destination\" };\n\tconst match = LOOPBACK_DESTINATION.exec(value);\n\tif (!match || match[0] !== value) return { ok: false, error: \"invalid_loopback_destination\" };\n\n\tconst port = Number(match[2]);\n\tif (port > 65535) return { ok: false, error: \"invalid_loopback_destination\" };\n\n\treturn {\n\t\tok: true,\n\t\tdestination: value,\n\t\thost: match[1] as \"127.0.0.1\" | \"[::1]\",\n\t\tport,\n\t};\n}\n","import { CONTROLLER_HISTORY_CTE } from \"./coordinator-auth-controller-history.js\";\nimport type { AuthLinkStatement } from \"./coordinator-auth-link.js\";\n\nexport const ROW_LIMIT = 500;\nexport const BYTE_LIMIT = 750_000;\nexport interface EvidenceQuery {\n\tname: string;\n\tsql: string;\n}\n\nconst controllerColumns =\n\t\"attestation_id,coordinator_id,identity_id,group_id,device_id,public_key,fingerprint,review_receipt_id,evidence_digest,enrollment_identity_id,revision,created_at,revoked_at\";\nexport const CONTROLLER_COLUMNS = controllerColumns.split(\",\");\nexport const RESOLUTION_COLUMNS =\n\t\"coordinator_id,resolution_id,resolution_version,device_id,key_id,owner_identity_id,purpose,scope,source_attestation_id,source_group_id,source_controller_revision,source_public_key,source_fingerprint,source_enrollment_identity_id,source_created_at,source_review_receipt_id,source_evidence_digest,resolution_evidence_digest,reviewed_weak_labels_json,created_at\".split(\n\t\t\",\",\n\t);\n\n// Invites and groups are server-local tables: neither has a coordinator column.\n// Their stored bound subject is the constraint; labels never supply a namespace.\nconst sources = `ownership_input AS MATERIALIZED (\n SELECT json_extract(value,'$.subject') AS value FROM snapshot\n), ownership_key_sources AS NOT MATERIALIZED (\n SELECT 'controller' AS source, attestation_id AS id, device_id, public_key FROM coordinator_auth_controller_attestations\n WHERE coordinator_id = (SELECT json_extract(value,'$.coordinatorId') FROM ownership_input)\n UNION ALL\n SELECT 'invite', invite_id, bound_device_id, bound_public_key FROM coordinator_invites WHERE consumed_at IS NOT NULL\n), ownership_lines AS NOT MATERIALIZED (\n SELECT *, ltrim(replace(replace(replace(replace(replace(public_key,char(9),' '),char(10),' '),char(11),' '),char(12),' '),char(13),' '),' ') AS line\n FROM ownership_key_sources\n), ownership_tails AS NOT MATERIALIZED (\n SELECT *, CASE WHEN substr(line,1,12) = 'ssh-ed25519 ' THEN ltrim(substr(line,13),' ') ELSE NULL END AS tail FROM ownership_lines\n), ownership_tokens AS NOT MATERIALIZED (\n SELECT *, CASE WHEN tail IS NOT NULL THEN substr(tail,1,instr(tail || ' ',' ') - 1) ELSE NULL END AS token FROM ownership_tails\n), ownership_discovery AS MATERIALIZED (\n SELECT source,id FROM ownership_tokens CROSS JOIN ownership_input p\n WHERE device_id = json_extract(p.value,'$.deviceId')\n OR public_key = json_extract(p.value,'$.publicKey')\n OR instr(public_key,char(0)) > 0 OR token IS NULL\n OR token GLOB '*[^A-Za-z0-9+/=_-]*'\n OR EXISTS (SELECT 1 FROM json_each(p.value,'$.fragments') f\n WHERE instr(replace(replace(token,'-','+'),'_','/'),f.value) > 0)\n LIMIT ${ROW_LIMIT + 1}\n)`;\n\nfunction rowQuery(name: string, columns: string[], from: string): EvidenceQuery {\n\treturn {\n\t\tname,\n\t\tsql: `SELECT json_array(${columns.join(\",\")}) AS row FROM ${from} LIMIT ${ROW_LIMIT + 1}`,\n\t};\n}\nconst subject = (field: string) => `(SELECT json_extract(value,'$.${field}') FROM ownership_input)`;\n\nexport const EVIDENCE_QUERIES: EvidenceQuery[] = [\n\trowQuery(\"discovery\", [\"source\", \"id\"], \"ownership_discovery\"),\n\trowQuery(\n\t\t\"bindings\",\n\t\t\"device_id,key_id,identity_id,coordinator_id,binding_id,provenance,source_ref,bound_at\".split(\n\t\t\t\",\",\n\t\t),\n\t\t`coordinator_device_ownership_bindings WHERE device_id=${subject(\"deviceId\")} OR key_id=${subject(\"keyId\")}`,\n\t),\n\trowQuery(\n\t\t\"claims\",\n\t\t\"claim_id,coordinator_id,identity_id,group_id,device_id,public_key,fingerprint,key_id,attempt_id,issuer,auth_config_revision,created_at_ms\".split(\n\t\t\t\",\",\n\t\t),\n\t\t`coordinator_auth_device_claims WHERE coordinator_id=${subject(\"coordinatorId\")} AND (device_id=${subject(\"deviceId\")} OR key_id=${subject(\"keyId\")})`,\n\t),\n\trowQuery(\n\t\t\"controllers\",\n\t\tCONTROLLER_COLUMNS,\n\t\t`coordinator_auth_controller_attestations WHERE coordinator_id=${subject(\"coordinatorId\")} AND attestation_id IN (SELECT id FROM ownership_discovery WHERE source='controller')`,\n\t),\n\trowQuery(\n\t\t\"invites\",\n\t\t\"invite_id,group_id,policy,created_at,expires_at,consumed_at,revoked_at,bound_device_id,bound_public_key,bound_fingerprint,invite_kind,assigned_identity_id,target_identity_id,recipient_actor_id,reviewed_preview_digest\".split(\n\t\t\t\",\",\n\t\t),\n\t\t\"coordinator_invites WHERE invite_id IN (SELECT id FROM ownership_discovery WHERE source='invite')\",\n\t),\n\trowQuery(\n\t\t\"enrollment\",\n\t\t\"e.group_id,e.device_id,e.public_key,e.fingerprint,e.identity_id,e.enabled,g.archived_at\".split(\n\t\t\t\",\",\n\t\t),\n\t\t`enrolled_devices e JOIN groups g ON g.group_id=e.group_id WHERE e.group_id=${subject(\"groupId\")} AND e.device_id=${subject(\"deviceId\")}`,\n\t),\n\trowQuery(\n\t\t\"revocations\",\n\t\t\"subject_kind,subject_value,revocation_id,evidence_group_id,evidence_device_id,evidence_public_key,evidence_fingerprint,actor_id,created_at\".split(\n\t\t\t\",\",\n\t\t),\n\t\t`coordinator_device_revocations WHERE (subject_kind='device_id' AND subject_value=${subject(\"deviceId\")}) OR (subject_kind='ed25519_key' AND subject_value=${subject(\"keyId\")})`,\n\t),\n\trowQuery(\n\t\t\"resolutions\",\n\t\tRESOLUTION_COLUMNS,\n\t\t`coordinator_legacy_owner_resolutions WHERE coordinator_id=${subject(\"coordinatorId\")} AND (device_id=${subject(\"deviceId\")} OR key_id=${subject(\"keyId\")})`,\n\t),\n\trowQuery(\n\t\t\"schema\",\n\t\t[\"type\", \"name\", \"tbl_name\", \"sql\"],\n\t\t\"sqlite_master WHERE tbl_name='coordinator_legacy_owner_resolutions' AND sql IS NOT NULL\",\n\t),\n\trowQuery(\n\t\t\"history\",\n\t\t\"group_id,candidate_ref,manifest_version,completed_at,created_at,manifest_json\".split(\",\"),\n\t\t\"live_history\",\n\t),\n\trowQuery(\"historyKeys\", [\"public_key\", \"fingerprint\"], \"live_history_keys\"),\n\trowQuery(\"historyDiscovery\", [\"public_key\"], \"live_discovery_keys\"),\n];\n\n// Stream unfiltered inventory and key normalization; materialize only filtered\n// discovery and rowset comparisons so unrelated key text is not copied repeatedly.\nconst prefix = `WITH snapshot(value) AS MATERIALIZED (SELECT ?),\n ${CONTROLLER_HISTORY_CTE}, ${sources}`;\n\nexport function readEvidenceQuery(query: EvidenceQuery, encoded: string): AuthLinkStatement {\n\treturn {\n\t\tsql: `${prefix}, selected AS MATERIALIZED (${query.sql})\n SELECT CASE WHEN SUM(length(CAST(row AS BLOB))) OVER () <= ${BYTE_LIMIT} THEN row ELSE NULL END AS row FROM selected ORDER BY row`,\n\t\tvalues: [encoded],\n\t};\n}\n\nexport interface CapturedEvidenceRow {\n\tcategory: string;\n\trow_count: number;\n\trow: string | null;\n}\n\nconst CATEGORY_BLOCK_SIZE = 5;\n\nexport function readCombinedEvidenceQuery(encoded: string): AuthLinkStatement {\n\tconst stages = EVIDENCE_QUERIES.map(\n\t\t({ name, sql }) => `selected_${name}(row) AS MATERIALIZED (${sql})`,\n\t);\n\tconst categories = EVIDENCE_QUERIES.map(\n\t\t({ name }) => `SELECT '${name}' AS category,\n (SELECT count(*) FROM selected_${name}) AS row_count, s.row\n FROM (SELECT 1) LEFT JOIN selected_${name} s ON 1`,\n\t);\n\tconst blocks: string[] = [];\n\tfor (let offset = 0; offset < categories.length; offset += CATEGORY_BLOCK_SIZE) {\n\t\tconst name = `category_block_${offset}`;\n\t\tstages.push(\n\t\t\t`${name} AS MATERIALIZED (${categories.slice(offset, offset + CATEGORY_BLOCK_SIZE).join(\"\\nUNION ALL\\n\")})`,\n\t\t);\n\t\tblocks.push(`SELECT * FROM ${name}`);\n\t}\n\tstages.push(`captured AS (${blocks.join(\"\\nUNION ALL\\n\")})`);\n\treturn {\n\t\t// Independent branches avoid rescanning other categories for each emitted row.\n\t\t// Materialized blocks keep each compound SELECT within D1's five-term limit.\n\t\t// Empty categories retain an explicit count/NULL marker. Bound the entire\n\t\t// response, not just each category, before evidence text crosses the backend.\n\t\tsql: `${prefix}, ${stages.join(\",\\n\")}\n SELECT category, row_count,\n CASE WHEN SUM(length(CAST(row AS BLOB))) OVER () <= ${BYTE_LIMIT} THEN row ELSE NULL END AS row\n FROM captured ORDER BY category, row`,\n\t\tvalues: [encoded],\n\t};\n}\n\nexport function atomicEvidenceQuery(encoded: string): AuthLinkStatement {\n\tconst stages = EVIDENCE_QUERIES.flatMap(({ name, sql }) => [\n\t\t`observed_${name}(row) AS MATERIALIZED (${sql})`,\n\t\t`expected_${name}(row) AS MATERIALIZED (SELECT j.value FROM snapshot s,json_each(s.value,'$.rows.${name}') j)`,\n\t\t`difference_${name}(row) AS MATERIALIZED (\n SELECT row FROM observed_${name} EXCEPT SELECT row FROM expected_${name})`,\n\t\t`missing_${name}(row) AS MATERIALIZED (\n SELECT row FROM expected_${name} EXCEPT SELECT row FROM observed_${name})`,\n\t]);\n\tconst matches = EVIDENCE_QUERIES.flatMap(({ name }) => [\n\t\t`NOT EXISTS (SELECT 1 FROM difference_${name})`,\n\t\t`NOT EXISTS (SELECT 1 FROM missing_${name})`,\n\t]).join(\" AND \");\n\treturn {\n\t\tsql: `${prefix}, ${stages.join(\",\\n\")} SELECT ${matches} AS matches`,\n\t\tvalues: [encoded],\n\t};\n}\n","/**\n * Inert historical-label receipts, never credentials or proof of authority.\n * Future readers must validate the original source and current proof using the\n * exact device AND canonical key. No store-open hook installs this schema.\n * No foreign keys: deleting source state must not erase collision history.\n * Canonical IDs use the full ECMAScript String.trim character set, including BOM.\n */\nexport const LEGACY_OWNER_RESOLUTION_SCHEMA_STATEMENTS = [\n\t`\nCREATE TABLE IF NOT EXISTS coordinator_legacy_owner_resolutions (\n coordinator_id TEXT NOT NULL CHECK (typeof(coordinator_id) = 'text' AND length(coordinator_id) BETWEEN 1 AND 256 AND length(trim(coordinator_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(coordinator_id, char(0)) = 0),\n resolution_id TEXT NOT NULL CHECK (typeof(resolution_id) = 'text' AND length(resolution_id) BETWEEN 1 AND 256 AND length(trim(resolution_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(resolution_id, char(0)) = 0),\n resolution_version INTEGER NOT NULL CHECK (typeof(resolution_version) = 'integer' AND resolution_version = 1),\n device_id TEXT NOT NULL CHECK (typeof(device_id) = 'text' AND length(device_id) BETWEEN 1 AND 256 AND length(trim(device_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(device_id, char(0)) = 0),\n key_id TEXT NOT NULL CHECK (typeof(key_id) = 'text' AND length(key_id) = 64 AND key_id NOT GLOB '*[^0-9a-f]*' AND instr(key_id, char(0)) = 0),\n owner_identity_id TEXT NOT NULL CHECK (typeof(owner_identity_id) = 'text' AND length(owner_identity_id) BETWEEN 1 AND 256 AND length(trim(owner_identity_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(owner_identity_id, char(0)) = 0),\n purpose TEXT NOT NULL CHECK (purpose = 'existing_account_owner'),\n scope TEXT NOT NULL CHECK (scope = 'historical_included_owner_labels_only'),\n source_attestation_id TEXT NOT NULL CHECK (typeof(source_attestation_id) = 'text' AND length(source_attestation_id) BETWEEN 1 AND 256 AND length(trim(source_attestation_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(source_attestation_id, char(0)) = 0),\n source_group_id TEXT NOT NULL CHECK (typeof(source_group_id) = 'text' AND length(source_group_id) BETWEEN 1 AND 256 AND length(trim(source_group_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(source_group_id, char(0)) = 0),\n source_controller_revision INTEGER NOT NULL CHECK (typeof(source_controller_revision) = 'integer' AND source_controller_revision = 1),\n source_public_key TEXT NOT NULL CHECK (typeof(source_public_key) = 'text' AND length(source_public_key) BETWEEN 1 AND 4096 AND length(trim(source_public_key, char(9)||char(10)||char(13)||' ')) > 0 AND instr(source_public_key, char(0)) = 0),\n source_fingerprint TEXT NOT NULL CHECK (typeof(source_fingerprint) = 'text' AND length(source_fingerprint) = 64 AND source_fingerprint NOT GLOB '*[^0-9a-f]*' AND instr(source_fingerprint, char(0)) = 0),\n source_enrollment_identity_id TEXT CHECK (source_enrollment_identity_id IS NULL OR (typeof(source_enrollment_identity_id) = 'text' AND length(source_enrollment_identity_id) BETWEEN 1 AND 256 AND length(trim(source_enrollment_identity_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(source_enrollment_identity_id, char(0)) = 0)),\n source_created_at TEXT NOT NULL CHECK (typeof(source_created_at) = 'text' AND length(source_created_at) BETWEEN 1 AND 256 AND length(trim(source_created_at, char(9)||char(10)||char(13)||' ')) > 0 AND instr(source_created_at, char(0)) = 0),\n source_review_receipt_id TEXT NOT NULL CHECK (typeof(source_review_receipt_id) = 'text' AND length(source_review_receipt_id) BETWEEN 1 AND 256 AND length(trim(source_review_receipt_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(source_review_receipt_id, char(0)) = 0),\n source_evidence_digest TEXT NOT NULL CHECK (typeof(source_evidence_digest) = 'text' AND length(source_evidence_digest) = 64 AND source_evidence_digest NOT GLOB '*[^0-9a-f]*' AND instr(source_evidence_digest, char(0)) = 0),\n resolution_evidence_digest TEXT NOT NULL CHECK (typeof(resolution_evidence_digest) = 'text' AND length(resolution_evidence_digest) = 64 AND resolution_evidence_digest NOT GLOB '*[^0-9a-f]*' AND instr(resolution_evidence_digest, char(0)) = 0),\n reviewed_weak_labels_json TEXT NOT NULL CHECK (typeof(reviewed_weak_labels_json) = 'text' AND length(CAST(reviewed_weak_labels_json AS BLOB)) <= 131072 AND CASE WHEN json_valid(reviewed_weak_labels_json) THEN json_type(reviewed_weak_labels_json) = 'array' ELSE 0 END),\n created_at TEXT NOT NULL CHECK (typeof(created_at) = 'text' AND length(created_at) BETWEEN 1 AND 256 AND length(trim(created_at, char(9)||char(10)||char(13)||' ')) > 0 AND instr(created_at, char(0)) = 0),\n CHECK (\n coordinator_id = trim(coordinator_id, char(9,10,11,12,13,32,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288,65279))\n AND resolution_id = trim(resolution_id, char(9,10,11,12,13,32,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288,65279))\n AND device_id = trim(device_id, char(9,10,11,12,13,32,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288,65279))\n AND owner_identity_id = trim(owner_identity_id, char(9,10,11,12,13,32,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288,65279))\n AND source_attestation_id = trim(source_attestation_id, char(9,10,11,12,13,32,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288,65279))\n AND source_group_id = trim(source_group_id, char(9,10,11,12,13,32,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288,65279))\n AND source_review_receipt_id = trim(source_review_receipt_id, char(9,10,11,12,13,32,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288,65279))\n AND (source_enrollment_identity_id IS NULL OR source_enrollment_identity_id = trim(source_enrollment_identity_id, char(9,10,11,12,13,32,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288,65279)))\n ),\n PRIMARY KEY (coordinator_id, resolution_id)\n) WITHOUT ROWID;\n`,\n\t`\nCREATE INDEX IF NOT EXISTS idx_legacy_owner_resolutions_device\n ON coordinator_legacy_owner_resolutions (coordinator_id, device_id);\n`,\n\t`\nCREATE INDEX IF NOT EXISTS idx_legacy_owner_resolutions_key\n ON coordinator_legacy_owner_resolutions (coordinator_id, key_id);\n`,\n\t`\n-- Reject before REPLACE can erase a receipt, even with recursive triggers off.\n-- Separate indexed probes keep device-OR-key conflicts coordinator-scoped.\nCREATE TRIGGER IF NOT EXISTS legacy_owner_resolution_insert_collision\nBEFORE INSERT ON coordinator_legacy_owner_resolutions\nWHEN EXISTS (SELECT 1 FROM coordinator_legacy_owner_resolutions\n WHERE coordinator_id = NEW.coordinator_id AND resolution_id = NEW.resolution_id)\n OR EXISTS (SELECT 1 FROM coordinator_legacy_owner_resolutions\n WHERE coordinator_id = NEW.coordinator_id AND device_id = NEW.device_id AND owner_identity_id <> NEW.owner_identity_id)\n OR EXISTS (SELECT 1 FROM coordinator_legacy_owner_resolutions\n WHERE coordinator_id = NEW.coordinator_id AND key_id = NEW.key_id AND owner_identity_id <> NEW.owner_identity_id)\nBEGIN SELECT RAISE(ABORT, 'legacy_owner_resolution_collision'); END;\n`,\n\t`\nCREATE TRIGGER IF NOT EXISTS legacy_owner_resolution_immutable_update\nBEFORE UPDATE ON coordinator_legacy_owner_resolutions\nBEGIN SELECT RAISE(ABORT, 'legacy_owner_resolution_immutable'); END;\n`,\n\t`\nCREATE TRIGGER IF NOT EXISTS legacy_owner_resolution_immutable_delete\nBEFORE DELETE ON coordinator_legacy_owner_resolutions\nBEGIN SELECT RAISE(ABORT, 'legacy_owner_resolution_immutable'); END;\n`,\n] as const;\n\nexport const LEGACY_OWNER_RESOLUTION_SCHEMA_SQL =\n\tLEGACY_OWNER_RESOLUTION_SCHEMA_STATEMENTS.join(\"\\n\");\n","import type { AuthLinkBackend } from \"./coordinator-auth-link.js\";\nimport { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport { LEGACY_OWNER_RESOLUTION_SCHEMA_STATEMENTS } from \"./coordinator-legacy-owner-resolution-schema.js\";\n\n/** Shape and key consistency only: never an ownership or provenance proof. */\nexport interface LegacyOwnerResolutionRecord {\n\tcoordinator_id: string;\n\tresolution_id: string;\n\tresolution_version: 1;\n\tdevice_id: string;\n\tkey_id: string;\n\towner_identity_id: string;\n\tpurpose: \"existing_account_owner\";\n\tscope: \"historical_included_owner_labels_only\";\n\tsource_attestation_id: string;\n\tsource_group_id: string;\n\tsource_controller_revision: 1;\n\tsource_public_key: string;\n\tsource_fingerprint: string;\n\tsource_enrollment_identity_id: string | null;\n\tsource_created_at: string;\n\tsource_review_receipt_id: string;\n\tsource_evidence_digest: string;\n\tresolution_evidence_digest: string;\n\treviewed_weak_labels_json: string;\n\tcreated_at: string;\n}\n\nexport interface ReviewedWeakLabel {\n\tlabel: string;\n\tkind: \"legacy_included_owner_label\" | \"consumed_project_actor_label\";\n\tgroup_id: string;\n\tdevice_id: string;\n\tevidence_ref: string;\n\teffect: \"account_owner_display_only\";\n}\n\nexport type LegacyOwnerResolutionSchemaState = \"ready\" | \"missing\" | \"unsupported\";\nconst MAX_WEAK_BYTES = 131072;\nconst encoder = new TextEncoder();\nconst isIdentifier = (v: unknown): v is string =>\n\ttypeof v === \"string\" &&\n\tv.length > 0 &&\n\tv.length <= 256 &&\n\tv.trim() === v &&\n\t!/[\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(v);\nconst isHash = (v: unknown): v is string => typeof v === \"string\" && /^[a-f0-9]{64}$/u.test(v);\nconst isTimestamp = (v: unknown): v is string => {\n\tif (typeof v !== \"string\" || !/^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d\\.\\d{3}Z$/u.test(v)) return false;\n\tconst date = new Date(v);\n\treturn Number.isFinite(date.getTime()) && date.toISOString() === v;\n};\n\nconst recordChecks = {\n\tcoordinator_id: isIdentifier,\n\tresolution_id: isIdentifier,\n\tresolution_version: (v: unknown) => v === 1,\n\tdevice_id: isIdentifier,\n\tkey_id: isHash,\n\towner_identity_id: isIdentifier,\n\tpurpose: (v: unknown) => v === \"existing_account_owner\",\n\tscope: (v: unknown) => v === \"historical_included_owner_labels_only\",\n\tsource_attestation_id: isIdentifier,\n\tsource_group_id: isIdentifier,\n\tsource_controller_revision: (v: unknown) => v === 1,\n\tsource_public_key: (v: unknown) =>\n\t\ttypeof v === \"string\" && v.length > 0 && v.length <= 4096 && !v.includes(\"\\u0000\"),\n\tsource_fingerprint: isHash,\n\tsource_enrollment_identity_id: (v: unknown) => v === null || isIdentifier(v),\n\tsource_created_at: isTimestamp,\n\tsource_review_receipt_id: isIdentifier,\n\tsource_evidence_digest: isHash,\n\tresolution_evidence_digest: isHash,\n\treviewed_weak_labels_json: (v: unknown) => typeof v === \"string\",\n\tcreated_at: isTimestamp,\n} satisfies Record<keyof LegacyOwnerResolutionRecord, (v: unknown) => boolean>;\nconst weakFields = [\"label\", \"kind\", \"group_id\", \"device_id\", \"evidence_ref\", \"effect\"];\n\n/** Copy own data descriptors before validation; never serialize caller objects. */\nfunction captureFields(value: unknown, fields: string[]): Record<string, unknown> | null {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (prototype !== null && prototype !== Object.prototype) return null;\n\tconst keys = Reflect.ownKeys(value);\n\tif (keys.length !== fields.length) return null;\n\tconst captured: Record<string, unknown> = {};\n\tfor (const field of fields) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, field);\n\t\tif (!descriptor || !(\"value\" in descriptor)) return null;\n\t\tcaptured[field] = descriptor.value;\n\t}\n\treturn captured;\n}\n\nfunction captureWeakLabel(value: unknown): ReviewedWeakLabel | null {\n\tconst row = captureFields(value, weakFields);\n\tif (\n\t\t!row ||\n\t\t!isIdentifier(row.label) ||\n\t\t!isIdentifier(row.group_id) ||\n\t\t!isIdentifier(row.device_id) ||\n\t\t!isHash(row.evidence_ref) ||\n\t\t(row.kind !== \"legacy_included_owner_label\" && row.kind !== \"consumed_project_actor_label\") ||\n\t\trow.effect !== \"account_owner_display_only\"\n\t)\n\t\treturn null;\n\treturn {\n\t\tlabel: row.label,\n\t\tkind: row.kind,\n\t\tgroup_id: row.group_id,\n\t\tdevice_id: row.device_id,\n\t\tevidence_ref: row.evidence_ref,\n\t\teffect: row.effect,\n\t};\n}\n\n/** Categories describe reviewed display metadata, not verified server provenance. */\nexport function canonicalReviewedWeakLabels(value: unknown): string | null {\n\ttry {\n\t\tif (!Array.isArray(value)) return null;\n\t\tconst length: unknown = Object.getOwnPropertyDescriptor(value, \"length\")?.value;\n\t\tif (\n\t\t\ttypeof length !== \"number\" ||\n\t\t\t!Number.isInteger(length) ||\n\t\t\tlength < 0 ||\n\t\t\tlength > 256 ||\n\t\t\tReflect.ownKeys(value).length !== length + 1\n\t\t)\n\t\t\treturn null;\n\t\tconst entries: string[] = [];\n\t\tfor (let i = 0; i < length; i++) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, String(i));\n\t\t\tif (!descriptor || !(\"value\" in descriptor)) return null;\n\t\t\tconst entry = captureWeakLabel(descriptor.value);\n\t\t\tif (!entry) return null;\n\t\t\tentries.push(JSON.stringify(entry));\n\t\t}\n\t\tentries.sort(); // ECMAScript binary string order, never locale collation.\n\t\tif (new Set(entries).size !== entries.length) return null;\n\t\tconst json = `[${entries.join(\",\")}]`;\n\t\treturn encoder.encode(json).byteLength <= MAX_WEAK_BYTES ? json : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction isResolutionRecord(\n\trow: Record<string, unknown>,\n): row is LegacyOwnerResolutionRecord & Record<string, unknown> {\n\treturn Object.entries(recordChecks).every(([field, check]) => check(row[field]));\n}\n\nfunction hasCanonicalStoredLabels(json: string): boolean {\n\tif (json.length > MAX_WEAK_BYTES || encoder.encode(json).byteLength > MAX_WEAK_BYTES)\n\t\treturn false;\n\treturn canonicalReviewedWeakLabels(JSON.parse(json)) === json;\n}\n\nexport async function captureLegacyOwnerResolutionRecord(\n\tvalue: unknown,\n): Promise<LegacyOwnerResolutionRecord | null> {\n\ttry {\n\t\tconst row = captureFields(value, Object.keys(recordChecks));\n\t\tif (\n\t\t\t!row ||\n\t\t\t!isResolutionRecord(row) ||\n\t\t\t!hasCanonicalStoredLabels(row.reviewed_weak_labels_json)\n\t\t)\n\t\t\treturn null;\n\t\tif ((await ed25519KeyIdForRevocation(row.source_public_key)) !== row.key_id) return null;\n\t\t// Historical fingerprint and exact key text bind source records in a later reader.\n\t\treturn row;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Tokenize rather than deleting whitespace/comments inside SQL string literals. */\nfunction normalizedDefinition(sql: string): string {\n\tconst tokens =\n\t\tsql.match(\n\t\t\t/'(?:''|[^'])*'|\"(?:\"\"|[^\"])*\"|`(?:``|[^`])*`|\\[[^\\]]*\\]|--[^\\n]*(?:\\n|$)|\\/\\*[\\s\\S]*?\\*\\/|\\s+|[a-zA-Z_][a-zA-Z_0-9]*|\\d+|[^\\s]/gu,\n\t\t) ?? [];\n\tconst normalized = tokens\n\t\t.filter((t) => !/^\\s|^--|^\\/\\*/u.test(t))\n\t\t.map((t) => (/^[a-zA-Z_]/u.test(t) ? t.toLowerCase() : t));\n\tif (normalized.at(-1) === \";\") normalized.pop();\n\treturn normalized.join(\" \").replace(/^(create (?:table|index|trigger)) if not exists /u, \"$1 \");\n}\n\nconst table = \"coordinator_legacy_owner_resolutions\";\nconst definitions = LEGACY_OWNER_RESOLUTION_SCHEMA_STATEMENTS.map(normalizedDefinition);\n\n/** Classify one captured catalog, using the same DDL rules as the live reader. */\nexport function classifyLegacyOwnerResolutionSchemaCatalog(\n\tvalue: unknown,\n): LegacyOwnerResolutionSchemaState {\n\tif (!Array.isArray(value)) return \"unsupported\";\n\tif (value.length === 0) return \"missing\";\n\tif (\n\t\tvalue.some(\n\t\t\t(object) => !object || typeof object.type !== \"string\" || typeof object.sql !== \"string\",\n\t\t)\n\t)\n\t\treturn \"unsupported\";\n\tif (!value.some((object) => object.type === \"table\")) return \"unsupported\";\n\tif (value.length !== definitions.length) return \"unsupported\";\n\tconst actual = value.map((object) => normalizedDefinition(object.sql));\n\treturn definitions.every((ddl) => actual.includes(ddl)) ? \"ready\" : \"unsupported\";\n}\n\nexport async function readLegacyOwnerResolutionSchemaState(\n\tbackend: Pick<AuthLinkBackend, \"first\">,\n): Promise<LegacyOwnerResolutionSchemaState> {\n\ttry {\n\t\t// One catalog snapshot includes every attached trigger and explicit index.\n\t\tconst result = await backend.first<{ objects: string }>({\n\t\t\tsql: `SELECT json_group_array(json_object('type',type,'sql',sql)) AS objects\n\t\t\t FROM sqlite_master WHERE tbl_name = ? AND sql IS NOT NULL`,\n\t\t\tvalues: [table],\n\t\t});\n\t\tif (!result) return \"unsupported\";\n\t\treturn classifyLegacyOwnerResolutionSchemaCatalog(JSON.parse(result.objects));\n\t} catch {\n\t\treturn \"unsupported\";\n\t}\n}\n","import {\n\ttype ControllerHistorySnapshot,\n\tparseControllerHistoryRecord,\n} from \"./coordinator-auth-controller-history.js\";\nimport { RESOLUTION_COLUMNS } from \"./coordinator-device-ownership-evidence-queries.js\";\nimport { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport {\n\tcaptureLegacyOwnerResolutionRecord,\n\ttype ReviewedWeakLabel,\n} from \"./coordinator-legacy-owner-resolution-metadata.js\";\n\nexport type EvidenceRow = (string | number | null)[];\nexport type EvidenceRows = Record<string, EvidenceRow[]>;\nexport function evidenceRows(rows: EvidenceRows, name: string): EvidenceRow[] {\n\tconst result = rows[name];\n\tif (!result) throw new Error(\"missing_evidence\");\n\treturn result;\n}\nexport interface EvidenceSubject {\n\tcoordinatorId: string;\n\tgroupId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n\tkeyId: string;\n}\nexport type OwnershipDecision =\n\t| \"compatible\"\n\t| \"owner_transfer_required\"\n\t| \"weak_label_review_required\"\n\t| \"device_revoked\";\n\nexport function identifier(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length > 0 &&\n\t\tvalue.length <= 256 &&\n\t\tvalue.trim() === value &&\n\t\t!/[\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(value)\n\t);\n}\nexport function hash(value: unknown): value is string {\n\treturn typeof value === \"string\" && /^[a-f0-9]{64}$/u.test(value);\n}\nfunction timestamp(value: unknown): value is string {\n\tif (typeof value !== \"string\" || !/^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d\\.\\d{3}Z$/u.test(value))\n\t\treturn false;\n\treturn Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;\n}\nfunction requireValid(condition: unknown): asserts condition {\n\tif (!condition) throw new Error(\"ownership_evidence_unavailable\");\n}\nexport async function keyId(value: unknown): Promise<string> {\n\trequireValid(typeof value === \"string\" && value.length > 0 && value.length <= 4096);\n\tconst result = await ed25519KeyIdForRevocation(value);\n\trequireValid(result);\n\treturn result;\n}\n\nfunction validateBinding(row: EvidenceRow) {\n\trequireValid(\n\t\trow.length === 8 &&\n\t\t\t[0, 2, 3, 4, 6].every((i) => identifier(row[i])) &&\n\t\t\thash(row[1]) &&\n\t\t\ttimestamp(row[7]),\n\t);\n\trequireValid(row[5] === \"owner_enrollment\" || row[5] === \"reviewed_legacy_migration\");\n}\nasync function validateClaim(row: EvidenceRow) {\n\trequireValid(\n\t\trow.length === 12 &&\n\t\t\t[0, 1, 2, 3, 4, 8, 9].every((i) => identifier(row[i])) &&\n\t\t\thash(row[6]) &&\n\t\t\thash(row[7]) &&\n\t\t\thash(row[10]),\n\t);\n\trequireValid(Number.isSafeInteger(row[11]) && Number(row[11]) >= 0);\n\t// Device collisions remain negative facts even when a stored key ID differs.\n\tawait keyId(row[5]);\n}\nasync function validateController(row: EvidenceRow) {\n\trequireValid(\n\t\trow.length === 13 &&\n\t\t\t[0, 1, 2, 3, 4, 7].every((i) => identifier(row[i])) &&\n\t\t\thash(row[6]) &&\n\t\t\thash(row[8]),\n\t);\n\trequireValid(\n\t\t(row[9] === null || identifier(row[9])) &&\n\t\t\trow[10] === 1 &&\n\t\t\ttimestamp(row[11]) &&\n\t\t\t(row[12] === null || timestamp(row[12])),\n\t);\n\treturn keyId(row[5]);\n}\nasync function validateInvite(row: EvidenceRow) {\n\trequireValid(row.length === 15 && identifier(row[0]) && identifier(row[1]) && identifier(row[2]));\n\trequireValid([3, 4, 5].every((i) => timestamp(row[i])) && (row[6] === null || timestamp(row[6])));\n\trequireValid(String(row[3]) <= String(row[5]) && String(row[5]) <= String(row[4]));\n\trequireValid(row[6] === null || String(row[5]) < String(row[6]));\n\trequireValid(identifier(row[7]) && hash(row[9]) && hash(row[14]));\n\trequireValid([11, 12, 13].every((i) => row[i] === null || identifier(row[i])));\n\trequireValid([\"team_member\", \"add_device\", \"project_share\"].includes(String(row[10])));\n\tif (row[10] === \"team_member\") requireValid(identifier(row[11]) && row[13] === row[11]);\n\tif (row[10] === \"add_device\") requireValid(identifier(row[12]) && row[13] === row[12]);\n\tif (row[10] === \"project_share\") requireValid(identifier(row[13]));\n\treturn keyId(row[8]);\n}\n\nfunction legacyLabels(\n\thistory: ControllerHistorySnapshot,\n\tsubject: EvidenceSubject,\n): ReviewedWeakLabel[] {\n\treturn history.records.flatMap((record) => {\n\t\tconst { manifest } = parseControllerHistoryRecord(record, subject.coordinatorId);\n\t\treturn manifest.device_decisions.flatMap((decision) => {\n\t\t\tif (decision.decision !== \"included\" || !decision.enabled || !decision.identity_id) return [];\n\t\t\tif (\n\t\t\t\tdecision.device_id !== subject.deviceId &&\n\t\t\t\t!history.fingerprints.includes(decision.key_fingerprint)\n\t\t\t)\n\t\t\t\treturn [];\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tlabel: decision.identity_id,\n\t\t\t\t\tkind: \"legacy_included_owner_label\" as const,\n\t\t\t\t\tgroup_id: record.group_id,\n\t\t\t\t\tdevice_id: decision.device_id,\n\t\t\t\t\tevidence_ref: manifest.source_digest,\n\t\t\t\t\teffect: \"account_owner_display_only\" as const,\n\t\t\t\t},\n\t\t\t];\n\t\t});\n\t});\n}\n\nasync function validateResolutionRows(rows: EvidenceRow[]) {\n\tfor (const row of rows) {\n\t\trequireValid(row.length === RESOLUTION_COLUMNS.length);\n\t\trequireValid(\n\t\t\tawait captureLegacyOwnerResolutionRecord(\n\t\t\t\tObject.fromEntries(RESOLUTION_COLUMNS.map((field, i) => [field, row[i]])),\n\t\t\t),\n\t\t);\n\t}\n}\n\nasync function strongSources(\n\trows: EvidenceRows,\n\tsubject: EvidenceSubject,\n\towner: string,\n\tweakLabels: ReviewedWeakLabel[],\n): Promise<boolean> {\n\tlet otherOwner = false;\n\tfor (const row of evidenceRows(rows, \"bindings\")) {\n\t\tvalidateBinding(row);\n\t\tif (row[2] !== owner) otherOwner = true;\n\t}\n\tfor (const row of evidenceRows(rows, \"claims\")) {\n\t\tawait validateClaim(row);\n\t\tif (row[2] !== owner) otherOwner = true;\n\t}\n\tfor (const row of evidenceRows(rows, \"controllers\")) {\n\t\tconst canonicalKey = await validateController(row);\n\t\tif ((row[4] === subject.deviceId || canonicalKey === subject.keyId) && row[2] !== owner)\n\t\t\totherOwner = true;\n\t}\n\tconst inviteConflict = await classifyInvites(\n\t\tevidenceRows(rows, \"invites\"),\n\t\tsubject,\n\t\towner,\n\t\tweakLabels,\n\t);\n\treturn otherOwner || inviteConflict;\n}\n\nasync function classifyInvites(\n\trows: EvidenceRow[],\n\tsubject: EvidenceSubject,\n\towner: string,\n\tweakLabels: ReviewedWeakLabel[],\n): Promise<boolean> {\n\tlet otherOwner = false;\n\tfor (const row of rows) {\n\t\tconst canonicalKey = await validateInvite(row);\n\t\tif (row[7] !== subject.deviceId && canonicalKey !== subject.keyId) continue;\n\t\tif (row[10] === \"project_share\") {\n\t\t\tweakLabels.push({\n\t\t\t\tlabel: String(row[13]),\n\t\t\t\tkind: \"consumed_project_actor_label\",\n\t\t\t\tgroup_id: String(row[1]),\n\t\t\t\tdevice_id: String(row[7]),\n\t\t\t\tevidence_ref: String(row[14]),\n\t\t\t\teffect: \"account_owner_display_only\",\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst invitedOwner = row[10] === \"team_member\" ? row[11] : row[12];\n\t\tif (invitedOwner !== owner) otherOwner = true;\n\t}\n\treturn otherOwner;\n}\n\nexport async function classifyEvidence(\n\trows: EvidenceRows,\n\tsubject: EvidenceSubject,\n\towner: string,\n\thistory: ControllerHistorySnapshot,\n): Promise<{ decision: OwnershipDecision; weakLabels: ReviewedWeakLabel[] }> {\n\tconst enrollment = evidenceRows(rows, \"enrollment\");\n\trequireValid(enrollment.length === 1);\n\tconst current = enrollment[0];\n\trequireValid(current);\n\tconst [group, device, publicKey, fingerprint, label, enabled, archived] = current;\n\trequireValid(\n\t\tgroup === subject.groupId &&\n\t\t\tdevice === subject.deviceId &&\n\t\t\tpublicKey === subject.publicKey &&\n\t\t\tfingerprint === subject.fingerprint &&\n\t\t\tenabled === 1 &&\n\t\t\tarchived === null,\n\t);\n\trequireValid(label === null || identifier(label));\n\tawait validateResolutionRows(evidenceRows(rows, \"resolutions\"));\n\tconst weakLabels = legacyLabels(history, subject);\n\tconst otherOwner = await strongSources(rows, subject, owner, weakLabels);\n\t// Resolution receipts are metadata only, but conflicting owner collisions must\n\t// not disappear just because their original positive source no longer verifies.\n\tconst resolutionConflict = evidenceRows(rows, \"resolutions\").some((row) => row[5] !== owner);\n\tif (evidenceRows(rows, \"revocations\").length) return { decision: \"device_revoked\", weakLabels };\n\tif (otherOwner || resolutionConflict) return { decision: \"owner_transfer_required\", weakLabels };\n\trequireValid(\n\t\tlabel === null || label === owner || weakLabels.some((weak) => weak.label === label),\n\t);\n\tconst relevantLabels = weakLabels.filter((weak) => weak.label !== owner);\n\treturn {\n\t\tdecision: relevantLabels.length ? \"weak_label_review_required\" : \"compatible\",\n\t\tweakLabels: relevantLabels,\n\t};\n}\n","import {\n\ttype ControllerHistorySnapshot,\n\tcaptureControllerHistory,\n} from \"./coordinator-auth-controller-history.js\";\nimport type { AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport {\n\tclassifyEvidence,\n\ttype EvidenceRow,\n\ttype EvidenceRows,\n\ttype EvidenceSubject,\n} from \"./coordinator-device-ownership-evidence-classify.js\";\nimport {\n\tatomicEvidenceQuery,\n\tBYTE_LIMIT,\n\tCONTROLLER_COLUMNS,\n\tEVIDENCE_QUERIES,\n\tRESOLUTION_COLUMNS,\n\tROW_LIMIT,\n\treadEvidenceQuery,\n} from \"./coordinator-device-ownership-evidence-queries.js\";\nimport { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport {\n\tcaptureLegacyOwnerResolutionRecord,\n\tclassifyLegacyOwnerResolutionSchemaCatalog,\n} from \"./coordinator-legacy-owner-resolution-metadata.js\";\n\ninterface Backend {\n\tfirst<T>(statement: AuthLinkStatement): Promise<T | null>;\n\tall?<T>(statement: AuthLinkStatement): Promise<T[]>;\n}\n\nexport interface NegativeOwnerConsistency extends AuthLinkStatement {\n\t/** Catalog, retained facts and original source only; unaffected by producer output. */\n\tretainedRecheck: AuthLinkStatement;\n}\n\nfunction consistencyResult(statement: AuthLinkStatement): NegativeOwnerConsistency {\n\treturn { ...statement, retainedRecheck: statement };\n}\n\nasync function captureNegativeCatalog(backend: Backend) {\n\tconst catalog = await backend.first<{ objects: string }>({ sql: catalogSql, values: [] });\n\tif (!catalog || typeof catalog.objects !== \"string\") return null;\n\tconst state = capturedCatalogState(catalog.objects);\n\tif (state === \"unsupported\" || (state === \"missing\" && catalog.objects !== \"[]\")) return null;\n\treturn { ...catalog, state, pin: `(${catalogSql.replace(\" AS objects\", \"\")}) IS ?` };\n}\n\n/** Trusted subject metadata, not authority. Enrollment is optional for future\n * new-device producers; those producers must independently prove admission.\n */\nexport interface NegativeOwnerSubject {\n\tcoordinatorId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n\townerIdentityId: string;\n\tenrollment?: { groupId: string };\n\tverifiedHistory?: ControllerHistorySnapshot;\n}\n\nconst catalogSql = `SELECT json_group_array(json_array(type,name,tbl_name,sql)) AS objects\n FROM sqlite_master WHERE tbl_name='coordinator_legacy_owner_resolutions'`;\n\nfunction capturedCatalogState(encoded: string) {\n\tconst rows: unknown = JSON.parse(encoded);\n\tif (!Array.isArray(rows)) return \"unsupported\";\n\tconst objects: { type: string; sql: string }[] = [];\n\tfor (const row of rows) {\n\t\tif (\n\t\t\t!Array.isArray(row) ||\n\t\t\trow.length !== 4 ||\n\t\t\ttypeof row[0] !== \"string\" ||\n\t\t\ttypeof row[1] !== \"string\" ||\n\t\t\trow[2] !== \"coordinator_legacy_owner_resolutions\" ||\n\t\t\t(row[3] !== null && typeof row[3] !== \"string\")\n\t\t)\n\t\t\treturn \"unsupported\";\n\t\t// The shared reader excludes SQLite's implicit indexes (SQL IS NULL).\n\t\t// Keep those objects in the full catalog pin, not the DDL comparison.\n\t\tif (row[3] !== null) objects.push({ type: row[0], sql: row[3] });\n\t}\n\treturn classifyLegacyOwnerResolutionSchemaCatalog(objects);\n}\n\nfunction parseRows(values: { row: string | null }[]): EvidenceRow[] {\n\tif (values.length > ROW_LIMIT) throw new Error(\"ownership_evidence_too_large\");\n\treturn values.map(({ row }) => {\n\t\tif (typeof row !== \"string\") throw new Error(\"ownership_evidence_unavailable\");\n\t\tconst value: unknown = JSON.parse(row);\n\t\tif (\n\t\t\t!Array.isArray(value) ||\n\t\t\tvalue.some((v) => v !== null && typeof v !== \"string\" && typeof v !== \"number\")\n\t\t)\n\t\t\tthrow new Error(\"ownership_evidence_unavailable\");\n\t\treturn value as EvidenceRow;\n\t});\n}\n\nasync function captureEvidence(\n\tbackend: Backend,\n\tsubject: EvidenceSubject,\n\tlegacyHistory: ControllerHistorySnapshot,\n) {\n\tconst base = {\n\t\tsubject: { ...subject, fragments: legacyHistory.discoveryFragments },\n\t\tlegacyHistory,\n\t};\n\tconst parameters = JSON.stringify(base);\n\tconst rows: EvidenceRows = {};\n\tconst encodedRows: Record<string, string[]> = {};\n\tfor (const query of EVIDENCE_QUERIES) {\n\t\tif (!backend.all) throw new Error(\"ownership_evidence_reader_unavailable\");\n\t\tconst values = await backend.all<{ row: string | null }>(readEvidenceQuery(query, parameters));\n\t\trows[query.name] = parseRows(values);\n\t\tencodedRows[query.name] = values.map(({ row }) => String(row));\n\t}\n\tconst encoded = JSON.stringify({ ...base, rows: encodedRows });\n\tif (new TextEncoder().encode(encoded).byteLength > BYTE_LIMIT)\n\t\tthrow new Error(\"ownership_evidence_too_large\");\n\treturn { rows, encoded };\n}\n\nasync function sourcePins(backend: Backend, rows: EvidenceRow[]): Promise<AuthLinkStatement> {\n\tconst sources: EvidenceRow[] = [];\n\tfor (const row of rows) {\n\t\tconst resolution = await captureLegacyOwnerResolutionRecord(\n\t\t\tObject.fromEntries(RESOLUTION_COLUMNS.map((column, i) => [column, row[i]])),\n\t\t);\n\t\tif (!resolution) throw new Error(\"ownership_resolution_unavailable\");\n\t\tconst expected = [\n\t\t\tresolution.source_attestation_id,\n\t\t\tresolution.coordinator_id,\n\t\t\tresolution.owner_identity_id,\n\t\t\tresolution.source_group_id,\n\t\t\tresolution.device_id,\n\t\t\tresolution.source_public_key,\n\t\t\tresolution.source_fingerprint,\n\t\t\tresolution.source_review_receipt_id,\n\t\t\tresolution.source_evidence_digest,\n\t\t\tresolution.source_enrollment_identity_id,\n\t\t\tresolution.source_controller_revision,\n\t\t\tresolution.source_created_at,\n\t\t\tnull,\n\t\t];\n\t\tconst source = await backend.first<Record<string, unknown>>({\n\t\t\tsql: `SELECT ${CONTROLLER_COLUMNS.join(\",\")} FROM coordinator_auth_controller_attestations WHERE coordinator_id=? AND attestation_id=?`,\n\t\t\tvalues: [resolution.coordinator_id, resolution.source_attestation_id],\n\t\t});\n\t\tif (source && CONTROLLER_COLUMNS.every((column, i) => source[column] === expected[i]))\n\t\t\tsources.push(expected);\n\t}\n\t// One complete original source suffices; stale same-owner receipts do not\n\t// erase another original, unrevoked source. Metadata was validated separately.\n\tif (sources.length === 0) throw new Error(\"ownership_source_unavailable\");\n\treturn {\n\t\tsql: `SELECT EXISTS (SELECT 1 FROM json_each(?) pin WHERE EXISTS (\n SELECT 1 FROM coordinator_auth_controller_attestations source WHERE ${CONTROLLER_COLUMNS.map((column, i) => `source.${column} IS json_extract(pin.value,'$[${i}]')`).join(\" AND \")})) AS matches`,\n\t\tvalues: [JSON.stringify(sources)],\n\t};\n}\n\nfunction absentSubjectResolutions(\n\tinput: NegativeOwnerSubject,\n\tkeyId: string | null,\n): AuthLinkStatement {\n\treturn {\n\t\tsql: `SELECT NOT EXISTS (SELECT 1 FROM coordinator_legacy_owner_resolutions\n WHERE coordinator_id=? AND (device_id=? OR key_id=?)) AS matches`,\n\t\tvalues: [input.coordinatorId, input.deviceId, keyId],\n\t};\n}\n\n/** Returns only a negative write predicate. No result grants owner authority.\n * The missing-schema predicate deliberately never names the absent table.\n */\nexport async function prepareNegativeOwnerConsistency(\n\tbackend: Backend,\n\tinput: NegativeOwnerSubject,\n): Promise<NegativeOwnerConsistency | null> {\n\ttry {\n\t\tconst catalog = await captureNegativeCatalog(backend);\n\t\tif (!catalog) return null;\n\t\tconst catalogPin = catalog.pin;\n\t\tif (catalog.state === \"missing\") {\n\t\t\treturn consistencyResult({\n\t\t\t\tsql: `SELECT ${catalogPin} AS matches`,\n\t\t\t\tvalues: [catalog.objects],\n\t\t\t});\n\t\t}\n\t\tconst keyId = await ed25519KeyIdForRevocation(input.publicKey);\n\t\tconst absent = absentSubjectResolutions(input, keyId);\n\t\tconst result = await backend.first<{ matches: number }>(absent);\n\t\tif (!result) return null;\n\t\t// Ready deployments with no retained fact for this subject keep ordinary\n\t\t// admission semantics and limits. The winning write still pins absence.\n\t\tif (result.matches === 1)\n\t\t\treturn consistencyResult({\n\t\t\t\tsql: `WITH consistency_absent AS MATERIALIZED (${absent.sql}) SELECT ${catalogPin}\n AND (SELECT matches FROM consistency_absent) AS matches`,\n\t\t\t\tvalues: [...absent.values, catalog.objects],\n\t\t\t});\n\t\treturn await prepareResolvedOwnerConsistency(backend, input, keyId, catalog);\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Compatibility for old internal callers, never infer a coordinator namespace. */\nexport async function prepareUnknownNamespaceOwnerConsistency(\n\tbackend: Backend,\n\tinput: Pick<NegativeOwnerSubject, \"deviceId\" | \"publicKey\">,\n): Promise<NegativeOwnerConsistency | null> {\n\ttry {\n\t\tconst catalog = await captureNegativeCatalog(backend);\n\t\tif (!catalog) return null;\n\t\tif (catalog.state === \"missing\")\n\t\t\treturn consistencyResult({\n\t\t\t\tsql: `SELECT ${catalog.pin} AS matches`,\n\t\t\t\tvalues: [catalog.objects],\n\t\t\t});\n\t\tconst keyId = await ed25519KeyIdForRevocation(input.publicKey);\n\t\tconst absent: AuthLinkStatement = {\n\t\t\tsql: \"SELECT NOT EXISTS (SELECT 1 FROM coordinator_legacy_owner_resolutions WHERE device_id=? OR key_id=?) AS matches\",\n\t\t\tvalues: [input.deviceId, keyId],\n\t\t};\n\t\tif ((await backend.first<{ matches: number }>(absent))?.matches !== 1) return null;\n\t\treturn consistencyResult({\n\t\t\tsql: `WITH consistency_absent AS MATERIALIZED (${absent.sql}) SELECT ${catalog.pin} AND (SELECT matches FROM consistency_absent) AS matches`,\n\t\t\tvalues: [...absent.values, catalog.objects],\n\t\t});\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nasync function prepareResolvedOwnerConsistency(\n\tbackend: Backend,\n\tinput: NegativeOwnerSubject,\n\tkeyId: string | null,\n\tcatalog: { objects: string },\n): Promise<NegativeOwnerConsistency | null> {\n\tconst catalogPin = `(${catalogSql.replace(\" AS objects\", \"\")}) IS ?`;\n\tconst history =\n\t\tinput.verifiedHistory ??\n\t\t(await captureControllerHistory(\n\t\t\t{\n\t\t\t\tcoordinatorId: input.coordinatorId,\n\t\t\t\tdeviceId: input.deviceId,\n\t\t\t\tpublicKey: input.publicKey,\n\t\t\t\tfingerprint: input.fingerprint,\n\t\t\t},\n\t\t\t<T>(sql: string, values: string[]) => {\n\t\t\t\tif (!backend.all) throw new Error(\"ownership_evidence_reader_unavailable\");\n\t\t\t\treturn backend.all<T>({ sql, values });\n\t\t\t},\n\t\t));\n\tconst subject: EvidenceSubject = {\n\t\tcoordinatorId: input.coordinatorId,\n\t\tdeviceId: input.deviceId,\n\t\tpublicKey: input.publicKey,\n\t\tfingerprint: input.fingerprint,\n\t\tgroupId: input.enrollment?.groupId ?? \"\",\n\t\t// Legacy trusted seed callers can have opaque keys. They still receive\n\t\t// device checks; no canonical-key inference is made from opaque text.\n\t\tkeyId: keyId ?? \"\",\n\t};\n\tconst { rows, encoded } = await captureEvidence(backend, subject, history);\n\tconst classificationRows = { ...rows };\n\tif (!input.enrollment)\n\t\tclassificationRows.enrollment = [\n\t\t\t[\"\", input.deviceId, input.publicKey, input.fingerprint, null, 1, null],\n\t\t];\n\tconst classification = await classifyEvidence(\n\t\tclassificationRows,\n\t\tsubject,\n\t\tinput.ownerIdentityId,\n\t\thistory,\n\t);\n\tif (![\"compatible\", \"weak_label_review_required\"].includes(classification.decision)) return null;\n\tconst sources = await sourcePins(backend, rows.resolutions ?? []);\n\tconst evidence = atomicEvidenceQuery(encoded);\n\tconst retainedRecheck = retainedFactsRecheck(\n\t\tinput,\n\t\tkeyId,\n\t\trows.resolutions ?? [],\n\t\tsources,\n\t\tcatalog,\n\t);\n\treturn {\n\t\tsql: `WITH consistency_evidence AS MATERIALIZED (${evidence.sql}),\n consistency_sources AS MATERIALIZED (${sources.sql})\n SELECT ${catalogPin} AND (SELECT matches FROM consistency_evidence)\n AND (SELECT matches FROM consistency_sources) AS matches`,\n\t\tvalues: [...evidence.values, ...sources.values, catalog.objects],\n\t\tretainedRecheck,\n\t};\n}\n\nfunction retainedFactsRecheck(\n\tinput: NegativeOwnerSubject,\n\tkeyId: string | null,\n\trows: EvidenceRow[],\n\tsources: AuthLinkStatement,\n\tcatalog: { objects: string },\n): AuthLinkStatement {\n\treturn {\n\t\tsql: `WITH consistency_sources AS MATERIALIZED (${sources.sql}), consistency_facts AS MATERIALIZED (\n SELECT json_group_array(row) AS rows FROM (SELECT json_array(${RESOLUTION_COLUMNS.join(\",\")}) AS row\n FROM coordinator_legacy_owner_resolutions WHERE coordinator_id=? AND (device_id=? OR key_id=?) ORDER BY row))\n SELECT (${catalogSql.replace(\" AS objects\", \"\")}) IS ? AND (SELECT matches FROM consistency_sources)\n AND (SELECT rows FROM consistency_facts) IS ? AS matches`,\n\t\tvalues: [\n\t\t\t...sources.values,\n\t\t\tinput.coordinatorId,\n\t\t\tinput.deviceId,\n\t\t\tkeyId,\n\t\t\tcatalog.objects,\n\t\t\tJSON.stringify(rows.map((row) => JSON.stringify(row)).sort()),\n\t\t],\n\t};\n}\n\n/** Keep the ordinary authority and evidence trees in independent materialized\n * root stages instead of nesting one predicate beneath the other's SQL tree.\n */\nexport function withNegativeOwnerConsistency(\n\tstatement: AuthLinkStatement,\n\tpredicate: AuthLinkStatement,\n): AuthLinkStatement {\n\tif (!statement.sql.trimStart().startsWith(\"WITH \"))\n\t\tthrow new Error(\"invalid_controller_statement\");\n\treturn {\n\t\tsql: `WITH negative_owner_consistency AS MATERIALIZED (${predicate.sql}), ${statement.sql.trimStart().slice(5)} AND (SELECT matches FROM negative_owner_consistency)`,\n\t\tvalues: [...predicate.values, ...statement.values],\n\t};\n}\n\n/** Compose only trusted producer statements; all captured data remains bound. */\nexport function withNegativeOwnerWrite(\n\tstatement: AuthLinkStatement,\n\tpredicate: AuthLinkStatement,\n): AuthLinkStatement {\n\tconst sql = statement.sql.trimStart();\n\tconst tail = sql.startsWith(\"WITH \") ? sql.slice(5) : sql;\n\tconst separator = sql.startsWith(\"WITH \") ? \",\" : \"\";\n\tconst conflict = tail.indexOf(\"ON CONFLICT\");\n\tconst beforeConflict = conflict < 0 ? tail : tail.slice(0, conflict);\n\tconst afterConflict = conflict < 0 ? \"\" : tail.slice(conflict);\n\treturn {\n\t\tsql: `WITH negative_owner_consistency AS MATERIALIZED (${predicate.sql})${separator} ${beforeConflict} AND (SELECT matches FROM negative_owner_consistency) ${afterConflict}`,\n\t\tvalues: [...predicate.values, ...statement.values],\n\t};\n}\n","import {\n\tCONNECTION_RELINK_ELIGIBLE_SQL,\n\tconnectionFinalizeGuard,\n\tconnectionRequesterGuard,\n\tconnectionSuccessorStatements,\n\tcreatePinnedConnection,\n} from \"./coordinator-account-connection-link.js\";\nimport type { ConnectionSchemaState } from \"./coordinator-account-connection-schema.js\";\nimport {\n\thasConnectionSessionSchema,\n\tinitialConnectionFloor,\n} from \"./coordinator-account-connection-session.js\";\nimport { captureAuthAccountProfile } from \"./coordinator-auth-account-profile.js\";\nimport { parseCoordinatorAccountReference } from \"./coordinator-auth-contract.js\";\nimport { isAuthControllerId, isAuthControllerUniqueError } from \"./coordinator-auth-controller.js\";\nimport {\n\tAUTH_DEVICE_CLAIM_ELIGIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_INPUT_SQL,\n\tcaptureDeviceClaimEligibility,\n} from \"./coordinator-auth-device-claim-eligibility.js\";\nimport { headlessLinkProvenanceStatement } from \"./coordinator-auth-headless-provenance.js\";\nimport { hasHeadlessLinkProvenance } from \"./coordinator-auth-headless-schema.js\";\nimport { readAuthLinkAttemptAuthority } from \"./coordinator-auth-link-authority.js\";\nimport {\n\tAUTH_LINK_ATTEMPT_TTL_MS,\n\tAUTH_LINK_CREATE_WINDOW_MS,\n\tAUTH_LINK_EXPIRE_BATCH_MAX,\n\tAUTH_LINK_MAX_ACTIVE_PER_DEVICE,\n\tAUTH_LINK_MAX_ACTIVE_PER_IDENTITY,\n\tAUTH_LINK_MAX_CREATES_PER_DEVICE_RETENTION,\n\tAUTH_LINK_MAX_CREATES_PER_DEVICE_WINDOW,\n\tAUTH_LINK_MAX_UNFINISHED_PER_COORDINATOR,\n\tAUTH_LINK_PURPOSE,\n\tAUTH_LINK_RETENTION_WINDOW_MS,\n\ttype CoordinatorAuthLinkClaimInput,\n\ttype CoordinatorAuthLinkConfig,\n\ttype CoordinatorAuthLinkConfirmInput,\n\ttype CoordinatorAuthLinkCreateInput,\n\ttype CoordinatorAuthLinkCreateResult,\n\ttype CoordinatorAuthLinkError,\n\ttype CoordinatorAuthLinkFailInput,\n\ttype CoordinatorAuthLinkFinalizeInput,\n\ttype CoordinatorAuthLinkMaintenanceOptions,\n\ttype CoordinatorAuthLinkMaintenanceResult,\n\ttype CoordinatorAuthLinkOidcInput,\n\ttype CoordinatorAuthLinkOidcResult,\n\ttype CoordinatorAuthLinkRejected,\n\ttype CoordinatorAuthLinkRequester,\n\ttype CoordinatorAuthLinkResult,\n\ttype CoordinatorAuthLinkSigner,\n\ttype CoordinatorAuthLinkState,\n\ttype CoordinatorAuthLinkStatus,\n\ttype CoordinatorAuthLinkStore,\n} from \"./coordinator-auth-link-contract.js\";\nimport {\n\tAUTH_LINK_HEADLESS_MARKER,\n\tAUTH_LINK_HEADLESS_MARKER_SQL,\n\ttype CoordinatorAuthLinkHeadlessApproval,\n\ttype CoordinatorAuthLinkHeadlessApprovalInput,\n\ttype CoordinatorAuthLinkHeadlessCreateInput,\n\ttype CoordinatorAuthLinkHeadlessFinalizeInput,\n} from \"./coordinator-auth-link-headless.js\";\nimport {\n\ttype Captured,\n\tcapture,\n\tcaptureAuthLinkConfig as captureConfig,\n\tcaptureAuthLinkSigner as captureSigner,\n\tisHash,\n} from \"./coordinator-auth-link-input.js\";\nimport {\n\tcleanAuthLinkProfiles,\n\tpromoteAuthLinkProfile,\n\tstageAuthLinkProfile,\n} from \"./coordinator-auth-link-profile.js\";\nimport { CONNECTION_BIRTHS_SQL } from \"./coordinator-auth-link-provenance.js\";\nimport { captureAuthLinkSource } from \"./coordinator-auth-link-source.js\";\nimport { parseCoordinatorAuthLoopback } from \"./coordinator-auth-loopback.js\";\nimport { authPersistenceError } from \"./coordinator-auth-schema.js\";\nimport { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport {\n\tprepareNegativeOwnerConsistency,\n\twithNegativeOwnerWrite,\n} from \"./coordinator-owner-negative-consistency.js\";\n\nexport * from \"./coordinator-auth-link-contract.js\";\nexport interface AuthLinkStatement {\n\tsql: string;\n\tvalues: (string | number | null)[];\n}\nexport interface AuthLinkBackend {\n\t/** Internal predicate preparation only; consumers must use checked SQL for output/writes. */\n\tprepareAuthLinkSource?: (\n\t\tattemptId: string,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t\talias?: \"a\" | \"coordinator_auth_link_attempts\",\n\t\toptions?: { currentDevice?: boolean },\n\t) => Promise<AuthLinkStatement>;\n\tprepareAuthLinkBrowserSource?: (\n\t\tinput: { binderHash: string; stateHash?: string; attemptId?: string },\n\t\tconfig: CoordinatorAuthLinkConfig & { redirectUri: string },\n\t\tnow: number,\n\t) => Promise<AuthLinkStatement>;\n\t/** Internal full-schema lookup on the wrapper's captured raw backend; never cached. */\n\treadAuthSchemaState?: () => Promise<ConnectionSchemaState>;\n\tfirst<T>(statement: AuthLinkStatement): Promise<T | null>;\n\tall?<T>(statement: AuthLinkStatement): Promise<T[]>;\n\trun(statement: AuthLinkStatement): Promise<number>;\n\t/** Atomic execution; production backends return each statement's native change count. */\n\tbatch(statements: AuthLinkStatement[]): Promise<unknown>;\n}\ninterface Attempt {\n\tprior_link_id?: string | null;\n\tauthority_kind: \"controller_attestation\" | \"device_claim\";\n\tcoordinator_id: string;\n\tattempt_id: string;\n\tidentity_id: string;\n\tgroup_id: string;\n\tdevice_id: string;\n\tpublic_key: string;\n\tfingerprint: string;\n\tcontroller_attestation_id: string | null;\n\tcontroller_review_receipt_id: string | null;\n\tcontroller_revision: number | null;\n\tissuer: string;\n\tauth_config_revision: string;\n\truntime_verifier_hash: string;\n\tbrowser_start_hash: string | null;\n\tloopback_redirect: string;\n\tstate: CoordinatorAuthLinkState;\n\tbrowser_transaction_hash: string | null;\n\taccount_subject: string | null;\n\tcompletion_secret_hash: string | null;\n\tlink_id: string | null;\n\tfailure_reason: string | null;\n\tcreated_at_ms: number;\n\texpires_at_ms: number;\n}\ninterface StagedProfile {\n\tdisplay_name: string | null;\n\temail: string | null;\n\temail_verified: number | null;\n}\n/** Capture without invoking accessors; null denotes an omitted attested commitment. */\nexport function captureAuthLinkBrowserStartHash(value: unknown): string | null | false {\n\tif (!value || typeof value !== \"object\") return false;\n\ttry {\n\t\tif (Array.isArray(value)) return false;\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, \"browserStartHash\");\n\t\tif (!descriptor) return \"browserStartHash\" in value ? false : null;\n\t\tif (!Object.hasOwn(descriptor, \"value\") || !isHash(descriptor.value)) return false;\n\t\treturn descriptor.value;\n\t} catch {\n\t\treturn false;\n\t}\n}\nfunction captureExpectedIdentity(value: unknown): string | null | false {\n\tif (!value || typeof value !== \"object\") return false;\n\ttry {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, \"expectedIdentityId\");\n\t\tif (!descriptor) return \"expectedIdentityId\" in value ? false : null;\n\t\treturn \"value\" in descriptor && isAuthControllerId(descriptor.value) ? descriptor.value : false;\n\t} catch {\n\t\treturn false;\n\t}\n}\nfunction captureCreateInput(value: unknown):\n\t| (Captured & {\n\t\t\tattemptId: string;\n\t\t\truntimeVerifierHash: string;\n\t\t\tloopbackRedirect: string;\n\t\t\tbrowserStartHash: string | null;\n\t\t\tauthority: CoordinatorAuthLinkCreateInput[\"authority\"];\n\t\t\texpectedIdentityId: string | null;\n\t })\n\t| null {\n\tconst i = capture(value, [\n\t\t\"attemptId\",\n\t\t\"signer\",\n\t\t\"runtimeVerifierHash\",\n\t\t\"loopbackRedirect\",\n\t\t\"authority\",\n\t]);\n\tconst authority = captureCreateAuthority(i?.authority);\n\tconst browserStartHash = captureAuthLinkBrowserStartHash(value);\n\tconst expectedIdentityId = captureExpectedIdentity(value);\n\tif (\n\t\t!i ||\n\t\t!authority ||\n\t\texpectedIdentityId === false ||\n\t\t(expectedIdentityId !== null &&\n\t\t\tauthority.kind === \"device_claim\" &&\n\t\t\tauthority.identityId !== expectedIdentityId) ||\n\t\tbrowserStartHash === false ||\n\t\t(authority.kind === \"device_claim\" && browserStartHash === null) ||\n\t\t!isAuthControllerId(i.attemptId) ||\n\t\t!isHash(i.runtimeVerifierHash) ||\n\t\t!parseCoordinatorAuthLoopback(i.loopbackRedirect).ok\n\t)\n\t\treturn null;\n\treturn {\n\t\t...i,\n\t\tattemptId: i.attemptId,\n\t\truntimeVerifierHash: i.runtimeVerifierHash,\n\t\tloopbackRedirect: i.loopbackRedirect as string,\n\t\tbrowserStartHash,\n\t\tauthority,\n\t\texpectedIdentityId,\n\t};\n}\ntype CreateInput = NonNullable<ReturnType<typeof captureCreateInput>>;\n/** Headless input has no loopback; the marker and user code hash fill the same columns. */\nfunction captureHeadlessCreateInput(value: unknown): CreateInput | null {\n\tconst i = capture(value, [\n\t\t\"attemptId\",\n\t\t\"signer\",\n\t\t\"runtimeVerifierHash\",\n\t\t\"userCodeHash\",\n\t\t\"authority\",\n\t]);\n\tconst authority = captureCreateAuthority(i?.authority);\n\tconst expectedIdentityId = captureExpectedIdentity(value);\n\tif (\n\t\t!i ||\n\t\t!authority ||\n\t\texpectedIdentityId === false ||\n\t\t!isAuthControllerId(i.attemptId) ||\n\t\t!isHash(i.runtimeVerifierHash) ||\n\t\t!isHash(i.userCodeHash)\n\t)\n\t\treturn null;\n\tif (\n\t\texpectedIdentityId !== null &&\n\t\tauthority.kind === \"device_claim\" &&\n\t\tauthority.identityId !== expectedIdentityId\n\t)\n\t\treturn null;\n\treturn {\n\t\tsigner: i.signer,\n\t\tattemptId: i.attemptId,\n\t\truntimeVerifierHash: i.runtimeVerifierHash,\n\t\tloopbackRedirect: AUTH_LINK_HEADLESS_MARKER,\n\t\tbrowserStartHash: i.userCodeHash,\n\t\tauthority,\n\t\texpectedIdentityId,\n\t};\n}\nfunction captureCreateAuthority(\n\tvalue: unknown,\n): CoordinatorAuthLinkCreateInput[\"authority\"] | null {\n\tconst a = capture(value, [\"kind\"]);\n\tif (a?.kind === \"controller_attestation\") return { kind: \"controller_attestation\" };\n\tif (a?.kind !== \"device_claim\") return null;\n\tconst claim = capture(value, [\"identityId\"]);\n\treturn isAuthControllerId(claim?.identityId)\n\t\t? { kind: \"device_claim\", identityId: claim.identityId }\n\t\t: null;\n}\nfunction captureRequester(value: unknown): CoordinatorAuthLinkRequester | null {\n\tconst k = capture(value, [\"kind\"]);\n\tif (k?.kind === \"device\") {\n\t\tconst s = capture(value, [\"signer\"]);\n\t\tconst signer = captureSigner(s?.signer);\n\t\treturn signer ? { kind: \"device\", signer } : null;\n\t}\n\tif (k?.kind !== \"browser\") return null;\n\tconst b = capture(value, [\"browserTransactionHash\"]);\n\treturn isHash(b?.browserTransactionHash)\n\t\t? { kind: \"browser\", browserTransactionHash: b.browserTransactionHash }\n\t\t: null;\n}\nexport function authLinkNow(clock: () => number): number {\n\tlet now: number;\n\ttry {\n\t\tnow = clock();\n\t} catch {\n\t\tthrow new Error(\"auth_link_invalid_clock\");\n\t}\n\tif (\n\t\t!Number.isSafeInteger(now) ||\n\t\tnow < 0 ||\n\t\tnow > Number.MAX_SAFE_INTEGER - AUTH_LINK_ATTEMPT_TTL_MS\n\t)\n\t\tthrow new Error(\"auth_link_invalid_clock\");\n\treturn now;\n}\nfunction rejected(error: CoordinatorAuthLinkError): CoordinatorAuthLinkRejected {\n\treturn { kind: \"rejected\", error };\n}\nfunction isTerminal(row: Attempt): boolean {\n\treturn [\"expired\", \"failed\", \"finalized\", \"session_redeemed\"].includes(row.state);\n}\nfunction status(row: Attempt, now: number): CoordinatorAuthLinkStatus {\n\tconst state = !isTerminal(row) && now >= row.expires_at_ms ? \"expired\" : row.state;\n\treturn { attemptId: row.attempt_id, state, expiresAtMs: row.expires_at_ms };\n}\nfunction configMatches(row: Attempt, c: CoordinatorAuthLinkConfig): boolean {\n\treturn (\n\t\tc.enabled &&\n\t\trow.coordinator_id === c.coordinatorId &&\n\t\trow.issuer === c.issuer &&\n\t\trow.auth_config_revision === c.revision\n\t);\n}\nfunction signerMatches(row: Attempt, s: CoordinatorAuthLinkSigner): boolean {\n\treturn (\n\t\trow.group_id === s.groupId &&\n\t\trow.device_id === s.deviceId &&\n\t\trow.public_key === s.publicKey &&\n\t\trow.fingerprint === s.fingerprint\n\t);\n}\nfunction creationMatches(\n\trow: Attempt,\n\ti: CreateInput,\n\ts: CoordinatorAuthLinkSigner,\n\tc: CoordinatorAuthLinkConfig,\n): boolean {\n\treturn (\n\t\tconfigMatches(row, c) &&\n\t\tsignerMatches(row, s) &&\n\t\trow.authority_kind === i.authority.kind &&\n\t\t(i.expectedIdentityId === null || row.identity_id === i.expectedIdentityId) &&\n\t\t(i.authority.kind !== \"device_claim\" || row.identity_id === i.authority.identityId) &&\n\t\trow.runtime_verifier_hash === i.runtimeVerifierHash &&\n\t\trow.browser_start_hash === i.browserStartHash &&\n\t\trow.loopback_redirect === i.loopbackRedirect\n\t);\n}\nfunction requesterMatches(row: Attempt, r: CoordinatorAuthLinkRequester): boolean {\n\tif (r.kind === \"device\") return signerMatches(row, r.signer);\n\treturn row.browser_transaction_hash === r.browserTransactionHash;\n}\nfunction diagnose(\n\trow: Attempt | null,\n\tc: CoordinatorAuthLinkConfig,\n\tnow: number,\n): CoordinatorAuthLinkRejected {\n\tif (!row) return rejected(\"attempt_unavailable\");\n\tif (!configMatches(row, c)) return rejected(\"auth_config_changed\");\n\tif (row.state === \"expired\") return rejected(\"attempt_expired\");\n\tif (!isTerminal(row) && row.expires_at_ms <= now) return rejected(\"attempt_expired\");\n\treturn rejected(\"attempt_unavailable\");\n}\n// Mode predicates run inside each write so one mode can never advance the other's rows.\nconst DESKTOP_MODE_SQL = `loopback_redirect <> ${AUTH_LINK_HEADLESS_MARKER_SQL}`;\nconst HEADLESS_MODE_SQL = `loopback_redirect = ${AUTH_LINK_HEADLESS_MARKER_SQL}`;\nconst LIVE_CONFIG =\n\t\"coordinator_id = ? AND issuer = ? AND auth_config_revision = ? AND ? = 1 AND authority_kind = 'controller_attestation'\";\nconst CURRENT_CONFIG = \"coordinator_id = ? AND issuer = ? AND auth_config_revision = ? AND ? = 1\";\n// Cancellation and time cleanup release an uncommitted promise, not ownership.\nconst RELEASABLE_SOURCE = `(authority_kind = 'controller_attestation' OR\n (authority_kind = 'device_claim' AND controller_attestation_id IS NULL\n AND controller_review_receipt_id IS NULL AND controller_revision IS NULL))`;\nfunction configValues(c: CoordinatorAuthLinkConfig): (string | number)[] {\n\treturn [c.coordinatorId, c.issuer, c.revision, Number(c.enabled)];\n}\ninterface AuthoritySource {\n\tgroup_id: string;\n\tdevice_id: string;\n\tpublic_key: string;\n\tfingerprint: string;\n\tidentity_id: string | null;\n\tcontroller_identity_id: string;\n\tattestation_id: string;\n\treview_receipt_id: string;\n\trevision: number;\n}\nconst AUTHORITY_COLUMNS = `e.group_id, e.device_id, e.public_key, e.fingerprint, e.identity_id,\n a.identity_id AS controller_identity_id, a.attestation_id, a.review_receipt_id, a.revision`;\n// Pin this call's enrollment, not the historical enrollment Identity in the attestation.\nconst AUTHORITY_GUARD = `AND e.group_id = ? AND e.device_id = ? AND e.public_key = ?\n AND e.fingerprint = ? AND e.identity_id IS ? AND a.identity_id = ?\n AND a.attestation_id = ? AND a.review_receipt_id = ? AND a.revision = ?\n AND NOT EXISTS (SELECT 1 FROM coordinator_device_revocations WHERE\n (subject_kind = 'device_id' AND subject_value = ?) OR\n (subject_kind = 'ed25519_key' AND subject_value = ?))`;\nfunction authorityValues(\n\tsource: AuthoritySource,\n\tkeyId: string | null,\n): (string | number | null)[] {\n\treturn [\n\t\tsource.group_id,\n\t\tsource.device_id,\n\t\tsource.public_key,\n\t\tsource.fingerprint,\n\t\tsource.identity_id,\n\t\tsource.controller_identity_id,\n\t\tsource.attestation_id,\n\t\tsource.review_receipt_id,\n\t\tsource.revision,\n\t\tsource.device_id,\n\t\tkeyId,\n\t];\n}\nasync function deriveAuthority(source: AuthoritySource): Promise<(string | number | null)[]> {\n\tconst values = authorityValues(source, null);\n\ttry {\n\t\tvalues[values.length - 1] = await ed25519KeyIdForRevocation(source.public_key);\n\t\treturn values;\n\t} catch {\n\t\tthrow new Error(\"auth_link_persistence_error\");\n\t}\n}\nconst AUTHORITY_SOURCE_SQL = `coordinator_auth_controller_attestations a\n JOIN enrolled_devices e ON e.group_id = a.group_id AND e.device_id = a.device_id\n JOIN groups g ON g.group_id = a.group_id\n WHERE a.coordinator_id = coordinator_auth_link_attempts.coordinator_id\n AND coordinator_auth_link_attempts.authority_kind = 'controller_attestation'\n AND a.attestation_id = coordinator_auth_link_attempts.controller_attestation_id AND a.review_receipt_id = coordinator_auth_link_attempts.controller_review_receipt_id\n AND a.revision = coordinator_auth_link_attempts.controller_revision AND a.revoked_at IS NULL\n AND a.identity_id = coordinator_auth_link_attempts.identity_id\n AND a.group_id = coordinator_auth_link_attempts.group_id AND a.device_id = coordinator_auth_link_attempts.device_id\n AND a.public_key = coordinator_auth_link_attempts.public_key AND a.fingerprint = coordinator_auth_link_attempts.fingerprint\n AND e.enabled = 1 AND g.archived_at IS NULL AND e.public_key = a.public_key AND e.fingerprint = a.fingerprint\n AND (e.identity_id IS NULL OR e.identity_id = a.identity_id)`;\nconst AUTHORITY = `EXISTS (SELECT 1 FROM ${AUTHORITY_SOURCE_SQL} ${AUTHORITY_GUARD})`;\nconst CREATE_SOURCE_SQL = `FROM coordinator_auth_controller_attestations a\n JOIN enrolled_devices e ON e.group_id = a.group_id AND e.device_id = a.device_id\n JOIN groups g ON g.group_id = a.group_id\n WHERE a.coordinator_id = ? AND a.group_id = ? AND a.device_id = ? AND a.public_key = ? AND a.fingerprint = ?\n AND a.revoked_at IS NULL AND a.revision = 1 AND ? = 1 AND e.enabled = 1 AND g.archived_at IS NULL\n AND e.public_key = a.public_key AND e.fingerprint = a.fingerprint AND (e.identity_id IS NULL OR e.identity_id = a.identity_id)`;\nconst CREATE_SQL = `INSERT INTO coordinator_auth_link_attempts (\n coordinator_id, attempt_id, identity_id, group_id, device_id, public_key, fingerprint,\n controller_attestation_id, controller_review_receipt_id, controller_revision, authority_kind,\n issuer, auth_config_revision, runtime_verifier_hash, loopback_redirect, browser_start_hash, state, created_at_ms, expires_at_ms)\n SELECT ?, ?, a.identity_id, a.group_id, a.device_id, a.public_key, a.fingerprint,\n a.attestation_id, a.review_receipt_id, a.revision, 'controller_attestation', ?, ?, ?, ?, ?, 'pending', ?, ?\n ${CREATE_SOURCE_SQL} ${AUTHORITY_GUARD}\n ${creationAdmissionSql(\"a\")}`;\nfunction creationAdmissionSql(source: \"a\" | \"p\"): string {\n\treturn `\n AND NOT EXISTS (SELECT 1 FROM coordinator_owner_enrollment_attempts t\n WHERE t.coordinator_id = ${source}.coordinator_id AND t.attempt_id = ?)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_browser_transactions t\n WHERE t.coordinator_id = ${source}.coordinator_id AND t.attempt_id = ? AND t.purpose NOT IN ('signin','link'))\n AND (SELECT count(*) FROM coordinator_auth_link_attempts t\n WHERE t.coordinator_id = ${source}.coordinator_id AND t.group_id = ${source}.group_id AND t.device_id = ${source}.device_id\n AND t.state IN ('pending','browser_claimed','oidc_verified','confirmed') AND t.expires_at_ms > ?) < ?\n AND (SELECT count(*) FROM coordinator_auth_link_attempts t\n WHERE t.coordinator_id = ${source}.coordinator_id AND t.identity_id = ${source}.identity_id\n AND t.state IN ('pending','browser_claimed','oidc_verified','confirmed') AND t.expires_at_ms > ?) < ?\n AND (SELECT count(*) FROM coordinator_auth_link_attempts t\n WHERE t.coordinator_id = ${source}.coordinator_id AND t.group_id = ${source}.group_id AND t.device_id = ${source}.device_id\n AND t.created_at_ms > ?) < ?\n AND (SELECT count(*) FROM coordinator_auth_link_attempts t\n WHERE t.coordinator_id = ${source}.coordinator_id AND t.group_id = ${source}.group_id AND t.device_id = ${source}.device_id\n AND t.created_at_ms > ?) < ?\n AND (SELECT count(*) FROM (SELECT 1 FROM coordinator_auth_link_attempts t\n WHERE t.coordinator_id = ${source}.coordinator_id AND t.state NOT IN ('finalized','session_redeemed') LIMIT ?)) < ?`;\n}\nfunction creationAdmissionValues(attemptId: string, now: number): (string | number)[] {\n\treturn [\n\t\tattemptId,\n\t\tattemptId,\n\t\tnow,\n\t\tAUTH_LINK_MAX_ACTIVE_PER_DEVICE,\n\t\tnow,\n\t\tAUTH_LINK_MAX_ACTIVE_PER_IDENTITY,\n\t\tnow - AUTH_LINK_CREATE_WINDOW_MS,\n\t\tAUTH_LINK_MAX_CREATES_PER_DEVICE_WINDOW,\n\t\tnow - AUTH_LINK_RETENTION_WINDOW_MS,\n\t\tAUTH_LINK_MAX_CREATES_PER_DEVICE_RETENTION,\n\t\tAUTH_LINK_MAX_UNFINISHED_PER_COORDINATOR,\n\t\tAUTH_LINK_MAX_UNFINISHED_PER_COORDINATOR,\n\t];\n}\nfunction deviceCreationEligibilitySql(options: { relink: boolean }): string {\n\treturn options.relink ? CONNECTION_RELINK_ELIGIBLE_SQL : AUTH_DEVICE_CLAIM_ELIGIBLE_SQL;\n}\nfunction isSharedAdmissionLimit(error: unknown): boolean {\n\treturn (\n\t\terror instanceof Error &&\n\t\t/^(?:D1_ERROR: )?connection_attempt_limited(?:: SQLITE_CONSTRAINT(?: \\(extended: SQLITE_CONSTRAINT_TRIGGER\\))?)?$/.test(\n\t\t\terror.message,\n\t\t)\n\t);\n}\nconst DEVICE_CREATE_SQL = `${AUTH_DEVICE_CLAIM_INPUT_SQL}\n INSERT INTO coordinator_auth_link_attempts (\n coordinator_id,attempt_id,identity_id,group_id,device_id,public_key,fingerprint,\n controller_attestation_id,controller_review_receipt_id,controller_revision,authority_kind,\n issuer,auth_config_revision,runtime_verifier_hash,loopback_redirect,browser_start_hash,state,created_at_ms,expires_at_ms)\n SELECT p.coordinator_id,p.attempt_id,p.identity_id,p.group_id,p.device_id,p.public_key,p.fingerprint,\n NULL,NULL,NULL,'device_claim',p.issuer,p.revision,?,?,?,'pending',p.now_ms,p.now_ms + ${AUTH_LINK_ATTEMPT_TTL_MS}\n FROM claim_input p WHERE ${AUTH_DEVICE_CLAIM_ELIGIBLE_SQL} ${creationAdmissionSql(\"p\")}`;\nconst DEVICE_RETRY_SQL = `${AUTH_DEVICE_CLAIM_INPUT_SQL}\n SELECT 1 FROM claim_input p JOIN coordinator_auth_link_attempts t\n ON t.coordinator_id = p.coordinator_id AND t.attempt_id = p.attempt_id\n WHERE t.authority_kind = 'device_claim' AND t.identity_id = p.identity_id\n AND t.group_id = p.group_id AND t.device_id = p.device_id AND t.public_key = p.public_key AND t.fingerprint = p.fingerprint\n AND t.issuer = p.issuer AND t.auth_config_revision = p.revision\n AND t.runtime_verifier_hash = ? AND t.browser_start_hash IS ? AND t.loopback_redirect = ?\n AND t.state <> 'expired' AND t.expires_at_ms > p.now_ms AND ${AUTH_DEVICE_CLAIM_ELIGIBLE_SQL}`;\nconst MAINTENANCE_CANDIDATE_SQL = `${RELEASABLE_SOURCE} AND link_id IS NULL AND (\n (state IN ('pending','browser_claimed','oidc_verified','confirmed') AND expires_at_ms <= ?)\n OR (state IN ('failed','expired') AND account_subject IS NOT NULL))`;\nconst MAINTENANCE_SQL = `UPDATE coordinator_auth_link_attempts\n SET state = CASE WHEN state = 'failed' THEN 'failed' ELSE 'expired' END, account_subject = NULL\n WHERE coordinator_id = ? AND ${MAINTENANCE_CANDIDATE_SQL}\n AND attempt_id IN (SELECT attempt_id FROM coordinator_auth_link_attempts\n WHERE coordinator_id = ? AND ${MAINTENANCE_CANDIDATE_SQL}\n ORDER BY expires_at_ms, attempt_id LIMIT ?)`;\nfunction captureMaintenanceLimit(options: unknown): number | null {\n\tif (options === undefined) return AUTH_LINK_EXPIRE_BATCH_MAX;\n\tif (!options || typeof options !== \"object\") return null;\n\ttry {\n\t\tif (Array.isArray(options)) return null;\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(options, \"limit\");\n\t\tif (!descriptor) {\n\t\t\tif (\"limit\" in options) return null;\n\t\t\treturn AUTH_LINK_EXPIRE_BATCH_MAX;\n\t\t}\n\t\tif (!Object.hasOwn(descriptor, \"value\")) return null;\n\t\tconst limit: unknown = descriptor.value;\n\t\tif (\n\t\t\ttypeof limit !== \"number\" ||\n\t\t\t!Number.isSafeInteger(limit) ||\n\t\t\tlimit < 1 ||\n\t\t\tlimit > AUTH_LINK_EXPIRE_BATCH_MAX\n\t\t)\n\t\t\treturn null;\n\t\treturn limit;\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction createSourceValues(\n\tc: CoordinatorAuthLinkConfig,\n\ts: CoordinatorAuthLinkSigner,\n): (string | number)[] {\n\treturn [c.coordinatorId, s.groupId, s.deviceId, s.publicKey, s.fingerprint, Number(c.enabled)];\n}\n\nexport type { AuthoritySource as AuthLinkAuthoritySource };\n// Shared with the read-only own-account query: never derive authority from labels alone.\nexport {\n\tAUTHORITY_COLUMNS as AUTH_LINK_AUTHORITY_COLUMNS,\n\tAUTHORITY_GUARD as AUTH_LINK_AUTHORITY_GUARD_SQL,\n\tCREATE_SOURCE_SQL as AUTH_LINK_CONTROLLER_SOURCE_SQL,\n\tcaptureConfig as captureAuthLinkConfig,\n\tcaptureSigner as captureAuthLinkSigner,\n\tcreateSourceValues as authLinkControllerSourceValues,\n\tderiveAuthority as deriveAuthLinkAuthority,\n};\n\n/** Optional persistence capability. No token verification, routes, sessions or grants. */\nexport class AuthLinkOperations implements CoordinatorAuthLinkStore {\n\tconstructor(\n\t\tprivate readonly backend: AuthLinkBackend,\n\t\tprivate readonly clock: () => number = Date.now,\n\t) {}\n\tprivate async read(\n\t\tattemptId: string,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tsource: { authority: Attempt[\"authority_kind\"] | \"either\" } = {\n\t\t\tauthority: \"controller_attestation\",\n\t\t},\n\t): Promise<Attempt | null> {\n\t\tconst row = await this.first<Attempt>({\n\t\t\tsql: `SELECT * FROM coordinator_auth_link_attempts WHERE coordinator_id = ? AND attempt_id = ?${source.authority === \"either\" ? \"\" : \" AND authority_kind = ?\"}`,\n\t\t\tvalues: [\n\t\t\t\tc.coordinatorId,\n\t\t\t\tattemptId,\n\t\t\t\t...(source.authority === \"either\" ? [] : [source.authority]),\n\t\t\t],\n\t\t});\n\t\tconst authority = row && readAuthLinkAttemptAuthority(row);\n\t\treturn authority && (source.authority === \"either\" || authority.kind === source.authority)\n\t\t\t? row\n\t\t\t: null;\n\t}\n\tprivate async first<T>(statement: AuthLinkStatement): Promise<T | null> {\n\t\ttry {\n\t\t\treturn await this.backend.first<T>(statement);\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_link_persistence_error\");\n\t\t}\n\t}\n\tprivate async connectionSchema(): Promise<boolean> {\n\t\ttry {\n\t\t\treturn await hasConnectionSessionSchema(this.backend);\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_link_persistence_error\");\n\t\t}\n\t}\n\tprivate async execute(\n\t\tstatement: AuthLinkStatement,\n\t\tconflict: CoordinatorAuthLinkError,\n\t\toptions: { sharedAdmission?: boolean } = {},\n\t): Promise<number | CoordinatorAuthLinkRejected> {\n\t\ttry {\n\t\t\treturn await this.backend.run(statement);\n\t\t} catch (error) {\n\t\t\tif (isAuthControllerUniqueError(error)) return rejected(conflict);\n\t\t\tif (options.sharedAdmission && isSharedAdmissionLimit(error)) return 0;\n\t\t\tthrow authPersistenceError(error, \"auth_link_persistence_error\");\n\t\t}\n\t}\n\tprivate async readAuthority(\n\t\tattemptId: string,\n\t\tc: CoordinatorAuthLinkConfig,\n\t): Promise<(string | number | null)[] | null> {\n\t\tconst source = await this.first<AuthoritySource>({\n\t\t\tsql: `SELECT ${AUTHORITY_COLUMNS} FROM coordinator_auth_link_attempts,\n\t\t\t ${AUTHORITY_SOURCE_SQL} AND coordinator_auth_link_attempts.attempt_id = ?\n\t\t\t AND coordinator_auth_link_attempts.coordinator_id = ?\n\t\t\t AND coordinator_auth_link_attempts.issuer = ?\n\t\t\t AND coordinator_auth_link_attempts.auth_config_revision = ? AND ? = 1`,\n\t\t\tvalues: [attemptId, ...configValues(c)],\n\t\t});\n\t\tif (!source) return null;\n\t\treturn deriveAuthority(source);\n\t}\n\tprivate async source(\n\t\tattemptId: string,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t\toptions: { currentDevice?: boolean } = {},\n\t) {\n\t\ttry {\n\t\t\tconst prepare = this.backend.prepareAuthLinkSource;\n\t\t\tif (prepare)\n\t\t\t\treturn await prepare(attemptId, c, now, \"coordinator_auth_link_attempts\", options);\n\t\t\treturn await captureAuthLinkSource(\n\t\t\t\tthis.backend,\n\t\t\t\tattemptId,\n\t\t\t\tc,\n\t\t\t\tnow,\n\t\t\t\t\"coordinator_auth_link_attempts\",\n\t\t\t\toptions,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_link_persistence_error\");\n\t\t}\n\t}\n\tasync maintainAuthLinkAttempts(\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t\toptions?: CoordinatorAuthLinkMaintenanceOptions,\n\t): Promise<CoordinatorAuthLinkMaintenanceResult> {\n\t\tconst c = captureConfig(config);\n\t\tconst limit = captureMaintenanceLimit(options);\n\t\tif (!c || limit === null) return rejected(\"invalid_input\");\n\t\tif (!c.enabled) return rejected(\"auth_config_changed\");\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst result = await this.execute(\n\t\t\t{\n\t\t\t\tsql: MAINTENANCE_SQL,\n\t\t\t\tvalues: [c.coordinatorId, now, c.coordinatorId, now, limit],\n\t\t\t},\n\t\t\t\"attempt_conflict\",\n\t\t);\n\t\tif (typeof result !== \"number\") return result;\n\t\tconst cleaned = await this.execute(cleanAuthLinkProfiles(c, now, limit), \"attempt_conflict\");\n\t\tif (typeof cleaned !== \"number\") return cleaned;\n\t\treturn {\n\t\t\tkind: \"maintained\",\n\t\t\tprocessedCount: result,\n\t\t\tmore: result === limit || cleaned === limit,\n\t\t};\n\t}\n\tasync createAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkCreateInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkCreateResult> {\n\t\treturn this.createCaptured(captureCreateInput(input), config);\n\t}\n\t/** Same authority, admission and exact-retry rules as desktop create. */\n\tasync createHeadlessAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkHeadlessCreateInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkCreateResult> {\n\t\treturn this.createCaptured(captureHeadlessCreateInput(input), config);\n\t}\n\tprivate async createCaptured(\n\t\ti: CreateInput | null,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkCreateResult> {\n\t\tconst c = captureConfig(config);\n\t\tconst s = captureSigner(i?.signer);\n\t\tif (!c || !i || !s) return rejected(\"invalid_input\");\n\t\tif (!c.enabled) return rejected(\"auth_config_changed\");\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst existing = await this.read(i.attemptId, c, { authority: \"either\" });\n\t\tif (existing) return this.retryCreation(existing, i, s, c, now);\n\t\tif (i.authority.kind === \"device_claim\") return this.createDeviceAttempt(i, s, c, now);\n\t\treturn this.createAttestedAttempt(i, s, c, now);\n\t}\n\tprivate async createAttestedAttempt(\n\t\ti: CreateInput,\n\t\ts: CoordinatorAuthLinkSigner,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t): Promise<CoordinatorAuthLinkCreateResult> {\n\t\tconst source = await this.first<AuthoritySource>({\n\t\t\tsql: `SELECT ${AUTHORITY_COLUMNS} ${CREATE_SOURCE_SQL}`,\n\t\t\tvalues: createSourceValues(c, s),\n\t\t});\n\t\tif (!source) {\n\t\t\tconst row = await this.read(i.attemptId, c, { authority: \"either\" });\n\t\t\tif (row) return this.createRetry(row, i, s, c, now, null);\n\t\t\treturn rejected(\"controller_not_active\");\n\t\t}\n\t\tconst authority = await deriveAuthority(source);\n\t\tif (i.expectedIdentityId !== null && source.controller_identity_id !== i.expectedIdentityId)\n\t\t\treturn rejected(\"controller_not_active\");\n\t\tconst values = [\n\t\t\tc.coordinatorId,\n\t\t\ti.attemptId,\n\t\t\tc.issuer,\n\t\t\tc.revision,\n\t\t\ti.runtimeVerifierHash,\n\t\t\ti.loopbackRedirect as string,\n\t\t\ti.browserStartHash,\n\t\t\tnow,\n\t\t\tnow + AUTH_LINK_ATTEMPT_TTL_MS,\n\t\t\t...createSourceValues(c, s),\n\t\t\t...authority,\n\t\t\t...creationAdmissionValues(i.attemptId, now),\n\t\t];\n\t\tconst result = await this.executeCreation(\n\t\t\t{ sql: CREATE_SQL, values },\n\t\t\t{\n\t\t\t\tcoordinator: c.coordinatorId,\n\t\t\t\tattempt: i.attemptId,\n\t\t\t\tidentity: source.controller_identity_id,\n\t\t\t\tnow,\n\t\t\t},\n\t\t\ts,\n\t\t\tc,\n\t\t);\n\t\tconst row = await this.read(i.attemptId, c, { authority: \"either\" });\n\t\tif (result === 0) {\n\t\t\tif (row) return this.createRetry(row, i, s, c, now, authority);\n\t\t\treturn this.diagnoseCreateAdmission(i.attemptId, c, s, authority);\n\t\t}\n\t\tif (typeof result !== \"number\") return this.createRetry(row, i, s, c, now, authority);\n\t\tif (!row || !creationMatches(row, i, s, c)) throw new Error(\"auth_link_persistence_incomplete\");\n\t\treturn { kind: \"created\", status: status(row, now), identityId: row.identity_id };\n\t}\n\tprivate async executeCreation(\n\t\tstatement: AuthLinkStatement,\n\t\tpin: { coordinator: string; attempt: string; identity: string; now: number },\n\t\tsigner: CoordinatorAuthLinkSigner,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<number | CoordinatorAuthLinkRejected> {\n\t\tif (!(await this.connectionSchema())) return this.execute(statement, \"attempt_conflict\");\n\t\ttry {\n\t\t\tconst guard = await connectionRequesterGuard(\n\t\t\t\tthis.backend,\n\t\t\t\tpin.identity,\n\t\t\t\tsigner,\n\t\t\t\tconfig,\n\t\t\t\tpin.now,\n\t\t\t);\n\t\t\treturn await createPinnedConnection(\n\t\t\t\tthis.backend,\n\t\t\t\t{\n\t\t\t\t\tsql: `${statement.sql} AND ${guard.sql}`,\n\t\t\t\t\tvalues: [...statement.values, ...guard.values],\n\t\t\t\t},\n\t\t\t\tpin,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (isAuthControllerUniqueError(error)) return rejected(\"attempt_conflict\");\n\t\t\tif (isSharedAdmissionLimit(error)) return 0;\n\t\t\tif (String(error).includes(\"NOT NULL constraint failed\"))\n\t\t\t\treturn rejected(\"attempt_unavailable\");\n\t\t\tthrow authPersistenceError(error, \"auth_link_persistence_error\");\n\t\t}\n\t}\n\tprivate async retryCreation(\n\t\trow: Attempt,\n\t\ti: CreateInput,\n\t\ts: CoordinatorAuthLinkSigner,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t): Promise<CoordinatorAuthLinkCreateResult> {\n\t\tif (!creationMatches(row, i, s, c) || row.state === \"expired\" || row.expires_at_ms <= now)\n\t\t\treturn rejected(\"attempt_conflict\");\n\t\tif (i.authority.kind === \"device_claim\") {\n\t\t\tif (row.prior_link_id) return this.retryContinuation(row, i, c, now);\n\t\t\tconst captured = await this.captureDevice(i, s, c, now);\n\t\t\tconst active =\n\t\t\t\tcaptured &&\n\t\t\t\t(await this.first({\n\t\t\t\t\tsql: DEVICE_RETRY_SQL,\n\t\t\t\t\tvalues: [\n\t\t\t\t\t\t...captured.values,\n\t\t\t\t\t\ti.runtimeVerifierHash,\n\t\t\t\t\t\ti.browserStartHash,\n\t\t\t\t\t\ti.loopbackRedirect,\n\t\t\t\t\t],\n\t\t\t\t}));\n\t\t\tif (!active) {\n\t\t\t\tconst current = await this.read(i.attemptId, c, { authority: \"either\" });\n\t\t\t\treturn rejected(\n\t\t\t\t\tcurrent && !creationMatches(current, i, s, c)\n\t\t\t\t\t\t? \"attempt_conflict\"\n\t\t\t\t\t\t: \"attempt_unavailable\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (await this.readOwnerReservation(i.attemptId, c)) return rejected(\"attempt_conflict\");\n\t\t\treturn { kind: \"existing\", status: status(row, now), identityId: row.identity_id };\n\t\t}\n\t\treturn this.createRetry(row, i, s, c, now, await this.readAuthority(i.attemptId, c));\n\t}\n\tprivate async retryContinuation(\n\t\trow: Attempt,\n\t\ti: CreateInput,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t): Promise<CoordinatorAuthLinkCreateResult> {\n\t\tconst source = await this.source(i.attemptId, c, now);\n\t\tif (\n\t\t\t!(await this.first({\n\t\t\t\tsql: `SELECT 1 FROM coordinator_auth_link_attempts WHERE coordinator_id = ? AND attempt_id = ? AND ${source.sql}`,\n\t\t\t\tvalues: [c.coordinatorId, i.attemptId, ...source.values],\n\t\t\t}))\n\t\t)\n\t\t\treturn rejected(\"attempt_unavailable\");\n\t\treturn { kind: \"existing\", status: status(row, now), identityId: row.identity_id };\n\t}\n\tprivate async captureDevice(\n\t\ti: CreateInput,\n\t\ts: CoordinatorAuthLinkSigner,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t) {\n\t\tif (i.authority.kind !== \"device_claim\") return null;\n\t\ttry {\n\t\t\treturn await captureDeviceClaimEligibility(\n\t\t\t\tthis.backend,\n\t\t\t\t{ signer: s, identityId: i.authority.identityId, attemptId: i.attemptId },\n\t\t\t\tc,\n\t\t\t\tnow,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_link_persistence_error\");\n\t\t}\n\t}\n\tprivate async createDeviceAttempt(\n\t\ti: CreateInput,\n\t\ts: CoordinatorAuthLinkSigner,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t): Promise<CoordinatorAuthLinkCreateResult> {\n\t\tconst captured = await this.captureDevice(i, s, c, now);\n\t\tif (!captured) return rejected(\"attempt_unavailable\");\n\t\tconst relink =\n\t\t\tcaptured.connectionSession &&\n\t\t\t(await this.first({\n\t\t\t\tsql: \"SELECT 1 FROM coordinator_auth_device_claims WHERE coordinator_id = ? AND identity_id = ?\",\n\t\t\t\tvalues: [c.coordinatorId, captured.identityId],\n\t\t\t}));\n\t\tconst result = await this.execute(\n\t\t\t{\n\t\t\t\tsql: relink\n\t\t\t\t\t? `${AUTH_DEVICE_CLAIM_INPUT_SQL} INSERT INTO coordinator_auth_link_attempts\n (coordinator_id,attempt_id,identity_id,group_id,device_id,public_key,fingerprint,controller_attestation_id,controller_review_receipt_id,controller_revision,authority_kind,issuer,auth_config_revision,runtime_verifier_hash,loopback_redirect,browser_start_hash,state,created_at_ms,expires_at_ms,prior_link_id)\n SELECT p.coordinator_id,p.attempt_id,p.identity_id,p.group_id,p.device_id,p.public_key,p.fingerprint,NULL,NULL,NULL,'device_claim',p.issuer,p.revision,?,?,?,'pending',p.now_ms,p.now_ms+600000,\n (SELECT h.link_id FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id=p.coordinator_id AND h.identity_id=p.identity_id AND h.successor_link_id IS NULL)\n FROM claim_input p WHERE ${CONNECTION_RELINK_ELIGIBLE_SQL} ${creationAdmissionSql(\"p\")}`\n\t\t\t\t\t: DEVICE_CREATE_SQL,\n\t\t\t\tvalues: [\n\t\t\t\t\t...captured.values,\n\t\t\t\t\ti.runtimeVerifierHash,\n\t\t\t\t\ti.loopbackRedirect,\n\t\t\t\t\ti.browserStartHash,\n\t\t\t\t\t...creationAdmissionValues(i.attemptId, now),\n\t\t\t\t],\n\t\t\t},\n\t\t\t\"attempt_conflict\",\n\t\t\t{ sharedAdmission: captured.connectionSession },\n\t\t);\n\t\tconst eligibility = deviceCreationEligibilitySql({ relink: Boolean(relink) });\n\t\tconst row = await this.read(i.attemptId, c, { authority: \"either\" });\n\t\tif (typeof result !== \"number\" || result === 0) {\n\t\t\tif (row) return this.retryCreation(row, i, s, c, now);\n\t\t\tif (typeof result !== \"number\") return result;\n\t\t\tconst eligible = await this.first({\n\t\t\t\tsql: `${AUTH_DEVICE_CLAIM_INPUT_SQL} SELECT 1 FROM claim_input p WHERE ${eligibility}`,\n\t\t\t\tvalues: captured.values,\n\t\t\t});\n\t\t\tif (!eligible) return rejected(\"attempt_unavailable\");\n\t\t\treturn rejected(\n\t\t\t\t(await this.readOwnerReservation(i.attemptId, c)) ? \"attempt_conflict\" : \"attempt_limited\",\n\t\t\t);\n\t\t}\n\t\tif (!row || !creationMatches(row, i, s, c)) throw new Error(\"auth_link_persistence_incomplete\");\n\t\treturn { kind: \"created\", status: status(row, now), identityId: row.identity_id };\n\t}\n\tprivate async diagnoseCreateAdmission(\n\t\tattemptId: string,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\ts: CoordinatorAuthLinkSigner,\n\t\tauthority: (string | number | null)[],\n\t): Promise<CoordinatorAuthLinkCreateResult> {\n\t\tconst active = await this.first({\n\t\t\tsql: `SELECT 1 ${CREATE_SOURCE_SQL} ${AUTHORITY_GUARD}`,\n\t\t\tvalues: [...createSourceValues(c, s), ...authority],\n\t\t});\n\t\tif (!active) return rejected(\"controller_not_active\");\n\t\tconst reserved = await this.readOwnerReservation(attemptId, c);\n\t\treturn rejected(reserved ? \"attempt_conflict\" : \"attempt_limited\");\n\t}\n\tprivate readOwnerReservation(attemptId: string, c: CoordinatorAuthLinkConfig) {\n\t\treturn this.first({\n\t\t\tsql: `SELECT 1 FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = ? AND attempt_id = ?\n UNION ALL SELECT 1 FROM coordinator_auth_browser_transactions WHERE coordinator_id = ? AND attempt_id = ?\n AND purpose NOT IN ('signin','link') LIMIT 1`,\n\t\t\tvalues: [c.coordinatorId, attemptId, c.coordinatorId, attemptId],\n\t\t});\n\t}\n\tprivate async createRetry(\n\t\trow: Attempt | null,\n\t\ti: CreateInput,\n\t\ts: CoordinatorAuthLinkSigner,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t\tauthority: (string | number | null)[] | null,\n\t): Promise<CoordinatorAuthLinkCreateResult> {\n\t\tif (\n\t\t\t!row ||\n\t\t\t!creationMatches(row, i, s, c) ||\n\t\t\trow.state === \"expired\" ||\n\t\t\trow.expires_at_ms <= now\n\t\t)\n\t\t\treturn rejected(\"attempt_conflict\");\n\t\tif (!authority) return rejected(\"controller_not_active\");\n\t\tconst active = await this.first({\n\t\t\tsql: `SELECT 1 FROM coordinator_auth_link_attempts WHERE attempt_id = ? AND ${LIVE_CONFIG} AND ${AUTHORITY}`,\n\t\t\tvalues: [row.attempt_id, ...configValues(c), ...authority],\n\t\t});\n\t\tif (!active) return rejected(\"controller_not_active\");\n\t\tif (await this.readOwnerReservation(row.attempt_id, c)) return rejected(\"attempt_conflict\");\n\t\treturn { kind: \"existing\", status: status(row, now), identityId: row.identity_id };\n\t}\n\tprivate async transition(\n\t\ti: { attemptId: string; browserTransactionHash: string },\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t\tupdate: AuthLinkStatement,\n\t\tafter?: AuthLinkStatement | null,\n\t): Promise<CoordinatorAuthLinkResult> {\n\t\tconst result = after\n\t\t\t? await this.executeTransitionBatch(update, after)\n\t\t\t: await this.execute(update, \"attempt_conflict\");\n\t\tif (typeof result !== \"number\") return result;\n\t\tconst row = await this.read(i.attemptId, c, { authority: \"either\" });\n\t\tif (!result) {\n\t\t\tif (\n\t\t\t\trow &&\n\t\t\t\trow.browser_transaction_hash !== null &&\n\t\t\t\trow.browser_transaction_hash !== i.browserTransactionHash\n\t\t\t)\n\t\t\t\treturn rejected(\"attempt_unavailable\");\n\t\t\treturn diagnose(row, c, now);\n\t\t}\n\t\tif (!row || row.browser_transaction_hash !== i.browserTransactionHash)\n\t\t\tthrow new Error(\"auth_link_persistence_incomplete\");\n\t\treturn { kind: \"applied\", status: status(row, now) };\n\t}\n\tprivate async executeTransitionBatch(update: AuthLinkStatement, after: AuthLinkStatement) {\n\t\ttry {\n\t\t\tconst counts = await this.backend.batch([update, after]);\n\t\t\tif (\n\t\t\t\t!Array.isArray(counts) ||\n\t\t\t\tcounts.length !== 2 ||\n\t\t\t\ttypeof counts[0] !== \"number\" ||\n\t\t\t\t!Number.isSafeInteger(counts[0])\n\t\t\t)\n\t\t\t\tthrow new Error(\"auth_link_batch_result_missing\");\n\t\t\treturn counts[0];\n\t\t} catch (error) {\n\t\t\tif (isAuthControllerUniqueError(error)) return rejected(\"attempt_conflict\");\n\t\t\tthrow authPersistenceError(error, \"auth_link_persistence_error\");\n\t\t}\n\t}\n\tprivate browserInput(\n\t\tinput: unknown,\n\t\textra: string[] = [],\n\t): (CoordinatorAuthLinkClaimInput & Captured) | null {\n\t\tconst i = capture(input, [\"attemptId\", \"browserTransactionHash\", ...extra]);\n\t\tif (!i || !isAuthControllerId(i.attemptId) || !isHash(i.browserTransactionHash)) return null;\n\t\treturn i as CoordinatorAuthLinkClaimInput & Captured;\n\t}\n\tasync claimAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkClaimInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkResult> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = this.browserInput(input);\n\t\tif (!c || !i) return rejected(\"invalid_input\");\n\t\tif (!c.enabled) return rejected(\"auth_config_changed\");\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst update = {\n\t\t\tsql: `UPDATE coordinator_auth_link_attempts SET state = 'browser_claimed', browser_transaction_hash = ?, claimed_at_ms = ? WHERE attempt_id = ? AND ${LIVE_CONFIG} AND expires_at_ms > ? AND state = 'pending' AND browser_start_hash IS NULL AND browser_transaction_hash IS NULL AND ${DESKTOP_MODE_SQL} AND NOT EXISTS (SELECT 1 FROM coordinator_auth_session_receipts r WHERE r.coordinator_id = coordinator_auth_link_attempts.coordinator_id AND r.browser_transaction_hash = ?)`,\n\t\t\tvalues: [\n\t\t\t\ti.browserTransactionHash,\n\t\t\t\tnow,\n\t\t\t\ti.attemptId,\n\t\t\t\t...configValues(c),\n\t\t\t\tnow,\n\t\t\t\ti.browserTransactionHash,\n\t\t\t],\n\t\t};\n\t\tconst result = await this.transition(i, c, now, update);\n\t\tif (result.kind !== \"rejected\" || result.error !== \"attempt_unavailable\") return result;\n\t\tconst row = await this.read(i.attemptId, c);\n\t\tif (\n\t\t\trow &&\n\t\t\tconfigMatches(row, c) &&\n\t\t\trow.expires_at_ms > now &&\n\t\t\trow.state === \"browser_claimed\" &&\n\t\t\trow.browser_start_hash == null &&\n\t\t\trow.browser_transaction_hash === i.browserTransactionHash\n\t\t)\n\t\t\treturn { kind: \"existing\", status: status(row, now) };\n\t\treturn result;\n\t}\n\t/** Caller supplies independently server-verified OIDC claims; this does not validate JWTs. */\n\tasync recordAuthLinkOidcVerified(\n\t\tinput: CoordinatorAuthLinkOidcInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkOidcResult> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = this.browserInput(input, [\"account\"]);\n\t\tif (!c || !i) return rejected(\"invalid_input\");\n\t\tconst accountValue = capture(i.account, [\"issuer\", \"subject\"]);\n\t\tconst account = parseCoordinatorAccountReference(accountValue, { issuer: c.issuer });\n\t\tif (!account.ok) return rejected(\"invalid_input\");\n\t\tif (!c.enabled) return rejected(\"auth_config_changed\");\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(input, \"profile\");\n\t\tconst profile = captureAuthAccountProfile(\n\t\t\tdescriptor && Object.hasOwn(descriptor, \"value\") ? descriptor.value : undefined,\n\t\t);\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst source = await this.source(i.attemptId, c, now);\n\t\tconst staged = stageAuthLinkProfile(\n\t\t\t{\n\t\t\t\tattemptId: i.attemptId,\n\t\t\t\tbrowserTransactionHash: i.browserTransactionHash,\n\t\t\t\taccount: account.account,\n\t\t\t\tprofile,\n\t\t\t},\n\t\t\tc,\n\t\t\tnow,\n\t\t);\n\t\tconst result = await this.transition(\n\t\t\ti,\n\t\t\tc,\n\t\t\tnow,\n\t\t\t{\n\t\t\t\tsql: `UPDATE coordinator_auth_link_attempts SET state = 'oidc_verified', account_subject = ?, oidc_verified_at_ms = ? WHERE attempt_id = ? AND ${CURRENT_CONFIG} AND expires_at_ms > ? AND state = 'browser_claimed' AND browser_transaction_hash = ? AND account_subject IS NULL AND ${source.sql}`,\n\t\t\t\tvalues: [\n\t\t\t\t\taccount.account.subject,\n\t\t\t\t\tnow,\n\t\t\t\t\ti.attemptId,\n\t\t\t\t\t...configValues(c),\n\t\t\t\t\tnow,\n\t\t\t\t\ti.browserTransactionHash,\n\t\t\t\t\t...source.values,\n\t\t\t\t],\n\t\t\t},\n\t\t\tstaged,\n\t\t);\n\t\tif (result.kind === \"rejected\") return result;\n\t\tconst row = await this.read(i.attemptId, c, { authority: \"either\" });\n\t\tif (!row) throw new Error(\"auth_link_persistence_incomplete\");\n\t\treturn {\n\t\t\tkind: \"applied\",\n\t\t\tstatus: result.status,\n\t\t\ttarget: {\n\t\t\t\tidentityId: row.identity_id,\n\t\t\t\tgroupId: row.group_id,\n\t\t\t\tdeviceId: row.device_id,\n\t\t\t\tfingerprint: row.fingerprint,\n\t\t\t\t...(row.loopback_redirect === AUTH_LINK_HEADLESS_MARKER ? { headless: true as const } : {}),\n\t\t\t},\n\t\t};\n\t}\n\t/** completionSecretHash must come from the trusted coordinator generator, not request nomination. */\n\tasync confirmAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkConfirmInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkResult> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = this.browserInput(input, [\"completionSecretHash\"]);\n\t\tif (!c || !i || !isHash(i.completionSecretHash)) return rejected(\"invalid_input\");\n\t\treturn this.confirmWith(i, c, {\n\t\t\tsql: \"?\",\n\t\t\tvalues: [i.completionSecretHash],\n\t\t\tmode: DESKTOP_MODE_SQL,\n\t\t});\n\t}\n\t/** The device already holds the runtime verifier, so it doubles as the completion proof. */\n\tasync confirmHeadlessAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkClaimInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkResult> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = this.browserInput(input);\n\t\tif (!c || !i) return rejected(\"invalid_input\");\n\t\treturn this.confirmWith(i, c, {\n\t\t\tsql: \"runtime_verifier_hash\",\n\t\t\tvalues: [],\n\t\t\tmode: HEADLESS_MODE_SQL,\n\t\t});\n\t}\n\tprivate async confirmWith(\n\t\ti: CoordinatorAuthLinkClaimInput,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tcompletion: { sql: string; values: string[]; mode: string },\n\t): Promise<CoordinatorAuthLinkResult> {\n\t\tif (!c.enabled) return rejected(\"auth_config_changed\");\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst source = await this.source(i.attemptId, c, now);\n\t\treturn this.transition(i, c, now, {\n\t\t\tsql: `UPDATE coordinator_auth_link_attempts SET state = 'confirmed', completion_secret_hash = ${completion.sql}, confirmed_at_ms = ? WHERE attempt_id = ? AND ${CURRENT_CONFIG} AND expires_at_ms > ? AND state = 'oidc_verified' AND browser_transaction_hash = ? AND completion_secret_hash IS NULL AND ${completion.mode} AND ${source.sql}`,\n\t\t\tvalues: [\n\t\t\t\t...completion.values,\n\t\t\t\tnow,\n\t\t\t\ti.attemptId,\n\t\t\t\t...configValues(c),\n\t\t\t\tnow,\n\t\t\t\ti.browserTransactionHash,\n\t\t\t\t...source.values,\n\t\t\t],\n\t\t});\n\t}\n\t/** Read-only snapshot; confirmation must still atomically check the browser proof and state. */\n\tasync readAuthLinkCompletionDestination(\n\t\tinput: CoordinatorAuthLinkClaimInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<{ destination: string } | null> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = this.browserInput(input);\n\t\tif (!c || !i || !c.enabled) return null;\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst source = await this.source(i.attemptId, c, now);\n\t\tconst row = await this.first<Attempt>({\n\t\t\tsql: `SELECT * FROM coordinator_auth_link_attempts WHERE attempt_id = ? AND ${CURRENT_CONFIG}\n AND browser_transaction_hash = ? AND ${source.sql}`,\n\t\t\tvalues: [i.attemptId, ...configValues(c), i.browserTransactionHash, ...source.values],\n\t\t});\n\t\tif (\n\t\t\t!row ||\n\t\t\t!configMatches(row, c) ||\n\t\t\trow.attempt_id !== i.attemptId ||\n\t\t\trow.browser_transaction_hash !== i.browserTransactionHash ||\n\t\t\trow.state !== \"oidc_verified\" ||\n\t\t\t!(row.created_at_ms <= now && now < row.expires_at_ms) ||\n\t\t\t!parseCoordinatorAuthLoopback(row.loopback_redirect).ok\n\t\t)\n\t\t\treturn null;\n\t\treturn { destination: row.loopback_redirect };\n\t}\n\tasync getAuthLinkAttemptStatus(\n\t\tattemptId: string,\n\t\trequester: CoordinatorAuthLinkRequester,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkStatus | null> {\n\t\tconst read = await this.readStatusRow(attemptId, requester, config);\n\t\treturn read && status(read.row, read.now);\n\t}\n\t/**\n\t * The browser-bound status plus the attempt's mode, from the same single row\n\t * read, so browser pages learn the mode without another statement.\n\t */\n\tasync getAuthLinkBrowserAttemptStatus(\n\t\tinput: CoordinatorAuthLinkClaimInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<{ status: CoordinatorAuthLinkStatus; headless: boolean } | null> {\n\t\tconst i = this.browserInput(input);\n\t\tif (!i) return null;\n\t\tconst requester = {\n\t\t\tkind: \"browser\" as const,\n\t\t\tbrowserTransactionHash: i.browserTransactionHash,\n\t\t};\n\t\tconst read = await this.readStatusRow(i.attemptId, requester, config);\n\t\tif (!read) return null;\n\t\tconst headless = read.row.loopback_redirect === AUTH_LINK_HEADLESS_MARKER;\n\t\treturn { status: status(read.row, read.now), headless };\n\t}\n\tprivate async readStatusRow(\n\t\tattemptId: string,\n\t\trequester: CoordinatorAuthLinkRequester,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<{ row: Attempt; now: number } | null> {\n\t\tconst c = captureConfig(config);\n\t\tconst r = captureRequester(requester);\n\t\tif (!c || !r || !isAuthControllerId(attemptId) || !c.enabled) return null;\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst source = await this.source(attemptId, c, now, { currentDevice: r.kind === \"device\" });\n\t\tconst proof = requesterGuard(r);\n\t\tconst row = await this.first<Attempt>({\n\t\t\tsql: `SELECT * FROM coordinator_auth_link_attempts WHERE attempt_id = ? AND ${CURRENT_CONFIG}\n AND ${proof.sql} AND ${source.sql}`,\n\t\t\tvalues: [attemptId, ...configValues(c), ...proof.values, ...source.values],\n\t\t});\n\t\tif (!row || !configMatches(row, c) || !requesterMatches(row, r)) return null;\n\t\treturn { row, now };\n\t}\n\t/** The enrolled name of a headless attempt's device; read only to render headless consent. */\n\tasync readHeadlessAuthLinkDeviceName(\n\t\tinput: CoordinatorAuthLinkClaimInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<string | null> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = this.browserInput(input);\n\t\tif (!c?.enabled || !i) return null;\n\t\tconst row = await this.first<{ display_name: string | null }>({\n\t\t\tsql: `SELECT d.display_name FROM coordinator_auth_link_attempts a\n JOIN enrolled_devices d ON d.group_id = a.group_id AND d.device_id = a.device_id\n WHERE a.coordinator_id = ? AND a.attempt_id = ? AND a.browser_transaction_hash = ? AND a.${HEADLESS_MODE_SQL}`,\n\t\t\tvalues: [c.coordinatorId, i.attemptId, i.browserTransactionHash],\n\t\t});\n\t\treturn typeof row?.display_name === \"string\" ? row.display_name : null;\n\t}\n\t/** The confirmed account for the signing device to approve; null for any other state or mode. */\n\tasync readHeadlessAuthLinkApproval(\n\t\tinput: CoordinatorAuthLinkHeadlessApprovalInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkHeadlessApproval | null> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = capture(input, [\"attemptId\", \"signer\"]);\n\t\tconst s = captureSigner(i?.signer);\n\t\tif (!c?.enabled || !i || !s || !isAuthControllerId(i.attemptId)) return null;\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst source = await this.source(i.attemptId, c, now, { currentDevice: true });\n\t\tconst proof = requesterGuard({ kind: \"device\", signer: s });\n\t\tconst row = await this.first<Attempt>({\n\t\t\tsql: `SELECT * FROM coordinator_auth_link_attempts WHERE attempt_id = ? AND ${CURRENT_CONFIG}\n AND state = 'confirmed' AND expires_at_ms > ? AND ${HEADLESS_MODE_SQL} AND ${proof.sql} AND ${source.sql}`,\n\t\t\tvalues: [i.attemptId, ...configValues(c), now, ...proof.values, ...source.values],\n\t\t});\n\t\tif (\n\t\t\t!row ||\n\t\t\t!configMatches(row, c) ||\n\t\t\t!signerMatches(row, s) ||\n\t\t\trow.state !== \"confirmed\" ||\n\t\t\trow.loopback_redirect !== AUTH_LINK_HEADLESS_MARKER ||\n\t\t\trow.account_subject === null\n\t\t)\n\t\t\treturn null;\n\t\treturn { issuer: row.issuer, subject: row.account_subject, ...(await this.stagedProfile(row)) };\n\t}\n\tprivate async stagedProfile(row: Attempt) {\n\t\tconst profile = await this.first<StagedProfile>({\n\t\t\tsql: `SELECT display_name, email, email_verified FROM coordinator_auth_link_profiles\n WHERE coordinator_id = ? AND attempt_id = ? AND issuer = ? AND subject = ? AND auth_config_revision = ?\n AND browser_transaction_hash = ? AND link_id IS NULL`,\n\t\t\tvalues: [\n\t\t\t\trow.coordinator_id,\n\t\t\t\trow.attempt_id,\n\t\t\t\trow.issuer,\n\t\t\t\trow.account_subject,\n\t\t\t\trow.auth_config_revision,\n\t\t\t\trow.browser_transaction_hash,\n\t\t\t],\n\t\t});\n\t\tlet emailVerified: boolean | null = null;\n\t\tif (profile?.email_verified === 1) emailVerified = true;\n\t\telse if (profile?.email_verified === 0) emailVerified = false;\n\t\treturn {\n\t\t\tdisplayName: profile?.display_name ?? null,\n\t\t\temail: profile?.email ?? null,\n\t\t\temailVerified,\n\t\t};\n\t}\n\tprivate async acknowledgeFailedAttempt(\n\t\trow: Attempt,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t\tkind: \"applied\" | \"existing\",\n\t): Promise<CoordinatorAuthLinkResult> {\n\t\tconst cleanup = await this.execute(\n\t\t\t{\n\t\t\t\tsql: \"DELETE FROM coordinator_auth_link_profiles WHERE coordinator_id = ? AND attempt_id = ? AND link_id IS NULL\",\n\t\t\t\tvalues: [c.coordinatorId, row.attempt_id],\n\t\t\t},\n\t\t\t\"attempt_conflict\",\n\t\t);\n\t\tif (typeof cleanup !== \"number\") return cleanup;\n\t\treturn { kind, status: status(row, now) };\n\t}\n\tasync failAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkFailInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkResult> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = capture(input, [\"attemptId\", \"requester\", \"reason\"]);\n\t\tconst r = captureRequester(i?.requester);\n\t\tif (\n\t\t\t!c ||\n\t\t\t!i ||\n\t\t\t!r ||\n\t\t\t!isAuthControllerId(i.attemptId) ||\n\t\t\t![\"cancelled\", \"provider_failure\", \"config_failure\"].includes(i.reason as string) ||\n\t\t\t(r.kind === \"device\" && i.reason !== \"cancelled\")\n\t\t)\n\t\t\treturn rejected(\"invalid_input\");\n\t\tif (!c.enabled) return rejected(\"auth_config_changed\");\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst reason = i.reason === \"cancelled\" ? `${r.kind}_cancelled` : (i.reason as string);\n\t\tconst proof = requesterGuard(r);\n\t\tconst result = await this.execute(\n\t\t\t{\n\t\t\t\tsql: `UPDATE coordinator_auth_link_attempts SET state = 'failed', failure_reason = ?, failed_at_ms = ?, account_subject = CASE WHEN authority_kind = 'device_claim' THEN NULL ELSE account_subject END WHERE attempt_id = ? AND ${CURRENT_CONFIG} AND ${RELEASABLE_SOURCE} AND link_id IS NULL AND expires_at_ms > ? AND state IN ('pending','browser_claimed','oidc_verified','confirmed') AND ${proof.sql}`,\n\t\t\t\tvalues: [reason, now, i.attemptId, ...configValues(c), now, ...proof.values],\n\t\t\t},\n\t\t\t\"attempt_conflict\",\n\t\t);\n\t\tif (typeof result !== \"number\") return result;\n\t\tconst row = await this.read(i.attemptId, c, { authority: \"either\" });\n\t\tif (row && !requesterMatches(row, r)) return rejected(\"attempt_unavailable\");\n\t\t// A signed own-attempt cancel can acknowledge browser cancellation without\n\t\t// rewriting its reason or creating any account authority.\n\t\tif (\n\t\t\trow &&\n\t\t\tconfigMatches(row, c) &&\n\t\t\tr.kind === \"device\" &&\n\t\t\ti.reason === \"cancelled\" &&\n\t\t\trow.state === \"failed\" &&\n\t\t\trow.failure_reason === \"browser_cancelled\" &&\n\t\t\trow.link_id === null &&\n\t\t\trow.created_at_ms <= now &&\n\t\t\tnow < row.expires_at_ms\n\t\t)\n\t\t\treturn this.acknowledgeFailedAttempt(row, c, now, \"existing\");\n\t\tif (\n\t\t\trow &&\n\t\t\tconfigMatches(row, c) &&\n\t\t\trequesterMatches(row, r) &&\n\t\t\trow.state === \"failed\" &&\n\t\t\trow.failure_reason === reason\n\t\t)\n\t\t\treturn this.acknowledgeFailedAttempt(row, c, now, result ? \"applied\" : \"existing\");\n\t\treturn diagnose(row, c, now);\n\t}\n\tasync finalizeAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkFinalizeInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkResult> {\n\t\treturn this.finalizeWithMode(input, config, { kind: \"desktop\" });\n\t}\n\t/** Links only the account the device approved; any other verified account writes nothing. */\n\tasync finalizeHeadlessAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkHeadlessFinalizeInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAuthLinkResult> {\n\t\tconst c = captureConfig(config);\n\t\tconst approved = capture(capture(input, [\"approvedAccount\"])?.approvedAccount, [\n\t\t\t\"issuer\",\n\t\t\t\"subject\",\n\t\t]);\n\t\tconst account = c && parseCoordinatorAccountReference(approved, { issuer: c.issuer });\n\t\tif (!account?.ok) return rejected(\"invalid_input\");\n\t\t// Fail closed: a headless link is never written without its provenance row.\n\t\tif (!(await hasHeadlessLinkProvenance(this.backend))) return rejected(\"attempt_unavailable\");\n\t\treturn this.finalizeWithMode(input, config, { kind: \"headless\", ...account.account });\n\t}\n\tprivate async finalizeWithMode(\n\t\tinput: CoordinatorAuthLinkFinalizeInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t\tmode: FinalizeMode,\n\t): Promise<CoordinatorAuthLinkResult> {\n\t\tconst c = captureConfig(config);\n\t\tconst captured = captureFinalize(input, c);\n\t\tconst i: FinalizeRequest | null = captured && { ...captured, mode };\n\t\tif (!c || !i) return rejected(\"invalid_input\");\n\t\tif (!c.enabled) return rejected(\"auth_config_changed\");\n\t\tif (\n\t\t\ti.groupId !== i.signer.groupId ||\n\t\t\ti.deviceId !== i.signer.deviceId ||\n\t\t\ti.fingerprint !== i.signer.fingerprint\n\t\t)\n\t\t\treturn rejected(\"attempt_unavailable\");\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst linkId = globalThis.crypto.randomUUID();\n\t\tconst connections = await this.connectionSchema();\n\t\tconst row = await this.read(i.attemptId, c, { authority: \"either\" });\n\t\tif (row && !finalizeModeMatches(row, mode)) return rejected(\"attempt_unavailable\");\n\t\tif (row?.authority_kind === \"device_claim\") return this.finalizeDevice(i, c, now, linkId, row);\n\t\tconst authority = await this.readAuthority(i.attemptId, c);\n\t\tconst requester = andStatement(\n\t\t\tconnections\n\t\t\t\t? await connectionRequesterGuard(this.backend, i.identityId, i.signer, c, now)\n\t\t\t\t: { sql: \"1 = 1\", values: [] },\n\t\t\tfinalizeModeGuard(mode),\n\t\t);\n\t\ttry {\n\t\t\tawait this.backend.batch([\n\t\t\t\t...finalizeStatements(i, c, now, linkId, authority, connections, requester),\n\t\t\t\t...(connections ? connectionSuccessorStatements(c.coordinatorId, i.attemptId, linkId) : []),\n\t\t\t\tpromoteAuthLinkProfile(c.coordinatorId, i.attemptId, linkId),\n\t\t\t\t...(await initialConnectionFloor(this.backend, c.coordinatorId, linkId)),\n\t\t\t\t...provenanceStatements(i, c, linkId),\n\t\t\t]);\n\t\t} catch (error) {\n\t\t\tif (isAuthControllerUniqueError(error)) return rejected(\"link_conflict\");\n\t\t\tthrow authPersistenceError(error, \"auth_link_persistence_error\");\n\t\t}\n\t\treturn this.finalizeReceipt(i, c, now, linkId);\n\t}\n\tprivate async finalizeDevice(\n\t\ti: FinalizeRequest,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t\tlinkId: string,\n\t\trow: Attempt,\n\t): Promise<CoordinatorAuthLinkResult> {\n\t\tif (!configMatches(row, c) || !finalizeMatches(row, i)) return diagnose(row, c, now);\n\t\tconst source = await this.finalizeSource(i, c, now);\n\t\t// Exact retries read retained evidence. The immutable proof must never be reinserted.\n\t\tif ([\"finalized\", \"session_redeemed\"].includes(row.state))\n\t\t\treturn this.deviceReceipt(i, c, now, linkId, source);\n\t\tconst keyId = await ed25519KeyIdForRevocation(i.signer.publicKey);\n\t\tif (!keyId) return rejected(\"attempt_unavailable\");\n\t\tconst connections = await this.connectionSchema();\n\t\tconst consistency = await prepareNegativeOwnerConsistency(this.backend, {\n\t\t\tcoordinatorId: c.coordinatorId,\n\t\t\townerIdentityId: i.identityId,\n\t\t\tdeviceId: i.signer.deviceId,\n\t\t\tpublicKey: i.signer.publicKey,\n\t\t\tfingerprint: i.signer.fingerprint,\n\t\t\tenrollment: { groupId: i.signer.groupId },\n\t\t});\n\t\tif (!consistency) return rejected(\"attempt_unavailable\");\n\t\ttry {\n\t\t\tawait this.backend.batch([\n\t\t\t\t...deviceFinalizeStatements(i, c, now, linkId, keyId, source, connections).map(\n\t\t\t\t\t(statement, index) =>\n\t\t\t\t\t\tindex < 2 ? withNegativeOwnerWrite(statement, consistency) : statement,\n\t\t\t\t),\n\t\t\t\t...(connections ? connectionSuccessorStatements(c.coordinatorId, i.attemptId, linkId) : []),\n\t\t\t\tpromoteAuthLinkProfile(c.coordinatorId, i.attemptId, linkId),\n\t\t\t\t...(await initialConnectionFloor(this.backend, c.coordinatorId, linkId)),\n\t\t\t\t...provenanceStatements(i, c, linkId),\n\t\t\t]);\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\tisAuthControllerUniqueError(error) ||\n\t\t\t\tString(error).includes(\"auth_device_claim_collision\")\n\t\t\t)\n\t\t\t\treturn rejected(\"link_conflict\");\n\t\t\tthrow authPersistenceError(error, \"auth_link_persistence_error\");\n\t\t}\n\t\treturn this.deviceReceipt(i, c, now, linkId, await this.finalizeSource(i, c, now));\n\t}\n\tprivate async finalizeSource(\n\t\ti: FinalizeRequest,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t): Promise<AuthLinkStatement> {\n\t\tconst source = await this.source(i.attemptId, c, now, { currentDevice: true });\n\t\treturn andStatement(source, finalizeModeGuard(i.mode));\n\t}\n\tprivate async deviceReceipt(\n\t\ti: CoordinatorAuthLinkFinalizeInput,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t\tlinkId: string,\n\t\tsource: AuthLinkStatement,\n\t): Promise<CoordinatorAuthLinkResult> {\n\t\tconst row = await this.first<Attempt>({\n\t\t\tsql: `SELECT * FROM coordinator_auth_link_attempts WHERE attempt_id = ? AND ${CURRENT_CONFIG}\n AND authority_kind = 'device_claim' AND state IN ('finalized','session_redeemed') AND ${source.sql}`,\n\t\t\tvalues: [i.attemptId, ...configValues(c), ...source.values],\n\t\t});\n\t\tif (!row || !finalizeMatches(row, i)) return rejected(\"attempt_unavailable\");\n\t\treturn { kind: row.link_id === linkId ? \"applied\" : \"existing\", status: status(row, now) };\n\t}\n\tprivate async finalizeReceipt(\n\t\ti: CoordinatorAuthLinkFinalizeInput,\n\t\tc: CoordinatorAuthLinkConfig,\n\t\tnow: number,\n\t\tlinkId: string,\n\t): Promise<CoordinatorAuthLinkResult> {\n\t\tconst row = await this.read(i.attemptId, c);\n\t\tif (\n\t\t\trow &&\n\t\t\tconfigMatches(row, c) &&\n\t\t\tfinalizeMatches(row, i) &&\n\t\t\t[\"finalized\", \"session_redeemed\"].includes(row.state)\n\t\t) {\n\t\t\tconst receipt = await this.first({\n\t\t\t\tsql: receiptSql(await this.connectionSchema()),\n\t\t\t\tvalues: [c.coordinatorId, i.attemptId, row.link_id],\n\t\t\t});\n\t\t\tif (!receipt) throw new Error(\"auth_link_persistence_incomplete\");\n\t\t\treturn { kind: row.link_id === linkId ? \"applied\" : \"existing\", status: status(row, now) };\n\t\t}\n\t\tif (row && !finalizeMatches(row, i)) return rejected(\"attempt_unavailable\");\n\t\tconst diagnosis = diagnose(row, c, now);\n\t\tif (\n\t\t\t!row ||\n\t\t\tdiagnosis.error !== \"attempt_unavailable\" ||\n\t\t\trow.state !== \"confirmed\" ||\n\t\t\t!finalizeMatches(row, i)\n\t\t)\n\t\t\treturn diagnosis;\n\t\treturn rejected(\"controller_not_active\");\n\t}\n}\nfunction deviceFinalizeStatements(\n\ti: CoordinatorAuthLinkFinalizeInput,\n\tc: CoordinatorAuthLinkConfig,\n\tnow: number,\n\tlinkId: string,\n\tkeyId: string,\n\tsource: AuthLinkStatement,\n\tconnections = false,\n): AuthLinkStatement[] {\n\t// Every insert selects only this batch's winning transition, never an older receipt.\n\tconst winning = `attempt_id = ? AND ${CURRENT_CONFIG} AND authority_kind = 'device_claim'\n AND state = 'finalized' AND link_id = ? AND finalized_at_ms = ?`;\n\tconst values = [i.attemptId, ...configValues(c), linkId, now];\n\treturn [\n\t\t{\n\t\t\tsql: `UPDATE coordinator_auth_link_attempts SET state = 'finalized', link_id = ?, finalized_at_ms = ?\n WHERE (attempt_id = ? AND ${CURRENT_CONFIG} AND authority_kind = 'device_claim' AND state = 'confirmed')\n AND (created_at_ms <= ? AND expires_at_ms > ?) AND (group_id = ? AND identity_id = ? AND device_id = ? AND fingerprint = ? AND public_key = ?)\n AND (runtime_verifier_hash = ? AND completion_secret_hash = ? AND account_subject IS NOT NULL AND browser_transaction_hash IS NOT NULL)\n AND (created_at_ms <= claimed_at_ms AND claimed_at_ms <= oidc_verified_at_ms AND oidc_verified_at_ms <= confirmed_at_ms AND confirmed_at_ms <= ?)\n AND (${source.sql})${connections ? ` AND (${connectionFinalizeGuard(\"coordinator_auth_link_attempts\")})` : \"\"}`,\n\t\t\tvalues: [\n\t\t\t\tlinkId,\n\t\t\t\tnow,\n\t\t\t\ti.attemptId,\n\t\t\t\t...configValues(c),\n\t\t\t\tnow,\n\t\t\t\tnow,\n\t\t\t\ti.groupId,\n\t\t\t\ti.identityId,\n\t\t\t\ti.deviceId,\n\t\t\t\ti.fingerprint,\n\t\t\t\ti.signer.publicKey,\n\t\t\t\ti.runtimeVerifierHash,\n\t\t\t\ti.completionSecretHash,\n\t\t\t\tnow,\n\t\t\t\t...source.values,\n\t\t\t],\n\t\t},\n\t\t{\n\t\t\tsql: `INSERT INTO coordinator_auth_device_claims\n (claim_id,coordinator_id,identity_id,group_id,device_id,public_key,fingerprint,key_id,attempt_id,issuer,auth_config_revision,created_at_ms)\n SELECT link_id,coordinator_id,identity_id,group_id,device_id,public_key,fingerprint,?,attempt_id,issuer,auth_config_revision,finalized_at_ms\n FROM coordinator_auth_link_attempts WHERE ${winning}${connections ? \" AND prior_link_id IS NULL\" : \"\"}`,\n\t\t\tvalues: [keyId, ...values],\n\t\t},\n\t\t{\n\t\t\tsql: `INSERT INTO coordinator_auth_account_links\n (coordinator_id,link_id,issuer,subject,identity_id,attempt_id,controller_attestation_id,device_claim_id,auth_config_revision,created_at_ms,authority_kind)\n SELECT coordinator_id,link_id,issuer,account_subject,identity_id,attempt_id,NULL,${connections ? \"(SELECT claim_id FROM coordinator_auth_device_claims d WHERE d.coordinator_id=coordinator_auth_link_attempts.coordinator_id AND d.identity_id=coordinator_auth_link_attempts.identity_id)\" : \"link_id\"},auth_config_revision,finalized_at_ms,'device_claim'\n FROM coordinator_auth_link_attempts WHERE ${winning}`,\n\t\t\tvalues,\n\t\t},\n\t\t{\n\t\t\tsql: `INSERT INTO coordinator_auth_link_audit_log\n (coordinator_id,link_id,action,attempt_id,identity_id,group_id,device_id,fingerprint,controller_attestation_id,device_claim_id,auth_config_revision,created_at_ms,authority_kind)\n SELECT coordinator_id,link_id,'link_created',attempt_id,identity_id,group_id,device_id,fingerprint,NULL,${connections ? \"(SELECT claim_id FROM coordinator_auth_device_claims d WHERE d.coordinator_id=coordinator_auth_link_attempts.coordinator_id AND d.identity_id=coordinator_auth_link_attempts.identity_id)\" : \"link_id\"},auth_config_revision,finalized_at_ms,'device_claim'\n FROM coordinator_auth_link_attempts WHERE ${winning}`,\n\t\t\tvalues,\n\t\t},\n\t];\n}\ntype FinalizeMode = { kind: \"desktop\" } | { kind: \"headless\"; issuer: string; subject: string };\ntype FinalizeRequest = CoordinatorAuthLinkFinalizeInput & { mode: FinalizeMode };\n/** Written in the winning finalize batch, so a headless link and its provenance commit together. */\nfunction provenanceStatements(\n\ti: FinalizeRequest,\n\tc: CoordinatorAuthLinkConfig,\n\tlinkId: string,\n): AuthLinkStatement[] {\n\tif (i.mode.kind !== \"headless\") return [];\n\treturn [headlessLinkProvenanceStatement(c.coordinatorId, i.attemptId, linkId)];\n}\nfunction finalizeModeGuard(mode: FinalizeMode): AuthLinkStatement {\n\tconst t = \"coordinator_auth_link_attempts\";\n\tif (mode.kind === \"desktop\") return { sql: `${t}.${DESKTOP_MODE_SQL}`, values: [] };\n\treturn {\n\t\tsql: `${t}.${HEADLESS_MODE_SQL} AND ${t}.issuer = ? AND ${t}.account_subject = ?`,\n\t\tvalues: [mode.issuer, mode.subject],\n\t};\n}\nfunction finalizeModeMatches(row: Attempt, mode: FinalizeMode): boolean {\n\tif (mode.kind === \"desktop\") return row.loopback_redirect !== AUTH_LINK_HEADLESS_MARKER;\n\treturn (\n\t\trow.loopback_redirect === AUTH_LINK_HEADLESS_MARKER &&\n\t\trow.issuer === mode.issuer &&\n\t\trow.account_subject === mode.subject\n\t);\n}\nfunction andStatement(a: AuthLinkStatement, b: AuthLinkStatement): AuthLinkStatement {\n\treturn { sql: `(${a.sql}) AND (${b.sql})`, values: [...a.values, ...b.values] };\n}\nfunction requesterGuard(r: CoordinatorAuthLinkRequester): AuthLinkStatement {\n\tif (r.kind === \"browser\")\n\t\treturn { sql: \"browser_transaction_hash = ?\", values: [r.browserTransactionHash] };\n\treturn {\n\t\tsql: \"group_id = ? AND device_id = ? AND public_key = ? AND fingerprint = ?\",\n\t\tvalues: [r.signer.groupId, r.signer.deviceId, r.signer.publicKey, r.signer.fingerprint],\n\t};\n}\nfunction captureFinalize(\n\tinput: unknown,\n\tc: CoordinatorAuthLinkConfig | null,\n): CoordinatorAuthLinkFinalizeInput | null {\n\tconst i = capture(input, [\n\t\t\"purpose\",\n\t\t\"coordinatorId\",\n\t\t\"attemptId\",\n\t\t\"groupId\",\n\t\t\"identityId\",\n\t\t\"deviceId\",\n\t\t\"fingerprint\",\n\t\t\"runtimeVerifierHash\",\n\t\t\"completionSecretHash\",\n\t\t\"signer\",\n\t]);\n\tconst s = captureSigner(i?.signer);\n\tif (!c || !i || !s || i.purpose !== AUTH_LINK_PURPOSE || i.coordinatorId !== c.coordinatorId)\n\t\treturn null;\n\tif (\n\t\t![i.attemptId, i.groupId, i.identityId, i.deviceId].every(isAuthControllerId) ||\n\t\t![i.fingerprint, i.runtimeVerifierHash, i.completionSecretHash].every(isHash)\n\t)\n\t\treturn null;\n\treturn { ...i, signer: s } as unknown as CoordinatorAuthLinkFinalizeInput;\n}\nfunction finalizeMatches(row: Attempt, i: CoordinatorAuthLinkFinalizeInput): boolean {\n\treturn (\n\t\tsignerMatches(row, i.signer) &&\n\t\trow.identity_id === i.identityId &&\n\t\trow.runtime_verifier_hash === i.runtimeVerifierHash &&\n\t\trow.completion_secret_hash === i.completionSecretHash\n\t);\n}\nfunction finalizeStatements(\n\ti: CoordinatorAuthLinkFinalizeInput,\n\tc: CoordinatorAuthLinkConfig,\n\tnow: number,\n\tlinkId: string,\n\tauthority: (string | number | null)[] | null,\n\tconnections = false,\n\trequester: AuthLinkStatement = { sql: \"1 = 1\", values: [] },\n): AuthLinkStatement[] {\n\tconst authorityGuard = authority ? AUTHORITY : \"0 = 1\";\n\tconst consume: AuthLinkStatement = {\n\t\tsql: `UPDATE coordinator_auth_link_attempts SET state = 'finalized', link_id = ?, finalized_at_ms = ? WHERE attempt_id = ? AND ${LIVE_CONFIG} AND state = 'confirmed' AND expires_at_ms > ? AND group_id = ? AND identity_id = ? AND device_id = ? AND fingerprint = ? AND public_key = ? AND runtime_verifier_hash = ? AND completion_secret_hash = ? AND ${authorityGuard}${connections ? ` AND ${connectionFinalizeGuard(\"coordinator_auth_link_attempts\")}` : \"\"} AND ${requester.sql}`,\n\t\tvalues: [\n\t\t\tlinkId,\n\t\t\tnow,\n\t\t\ti.attemptId,\n\t\t\t...configValues(c),\n\t\t\tnow,\n\t\t\ti.groupId,\n\t\t\ti.identityId,\n\t\t\ti.deviceId,\n\t\t\ti.fingerprint,\n\t\t\ti.signer.publicKey,\n\t\t\ti.runtimeVerifierHash,\n\t\t\ti.completionSecretHash,\n\t\t\t...(authority ?? []),\n\t\t\t...requester.values,\n\t\t],\n\t};\n\tconst link: AuthLinkStatement = {\n\t\tsql: `INSERT INTO coordinator_auth_account_links (coordinator_id, link_id, issuer, subject, identity_id, attempt_id, controller_attestation_id, auth_config_revision, created_at_ms, authority_kind) SELECT coordinator_id, link_id, issuer, account_subject, identity_id, attempt_id, controller_attestation_id, auth_config_revision, finalized_at_ms, 'controller_attestation' FROM coordinator_auth_link_attempts WHERE attempt_id = ? AND ${LIVE_CONFIG} AND link_id = ? AND state = 'finalized'`,\n\t\tvalues: [i.attemptId, ...configValues(c), linkId],\n\t};\n\tconst audit: AuthLinkStatement = {\n\t\tsql: `INSERT INTO coordinator_auth_link_audit_log (coordinator_id, link_id, action, attempt_id, identity_id, group_id, device_id, fingerprint, controller_attestation_id, auth_config_revision, created_at_ms, authority_kind) SELECT t.coordinator_id, t.link_id, 'link_created', t.attempt_id, t.identity_id, t.group_id, t.device_id, t.fingerprint, t.controller_attestation_id, t.auth_config_revision, t.finalized_at_ms, 'controller_attestation' FROM coordinator_auth_link_attempts t JOIN coordinator_auth_account_links l ON l.coordinator_id = t.coordinator_id AND l.link_id = t.link_id AND l.authority_kind = 'controller_attestation' WHERE t.authority_kind = 'controller_attestation' AND t.attempt_id = ? AND t.coordinator_id = ? AND t.issuer = ? AND t.auth_config_revision = ? AND ? = 1 AND t.link_id = ?`,\n\t\tvalues: [i.attemptId, ...configValues(c), linkId],\n\t};\n\treturn [consume, link, audit];\n}\nfunction receiptSql(connections: boolean) {\n\treturn `SELECT 1 FROM coordinator_auth_link_attempts t\n JOIN ${connections ? `(${CONNECTION_BIRTHS_SQL})` : \"coordinator_auth_account_links\"} l ON l.coordinator_id = t.coordinator_id AND l.link_id = t.link_id\n AND l.attempt_id = t.attempt_id AND l.identity_id = t.identity_id AND l.issuer = t.issuer AND l.subject = t.account_subject\n AND l.authority_kind = 'controller_attestation' AND l.controller_attestation_id IS NOT NULL AND l.controller_attestation_id IS t.controller_attestation_id AND l.device_claim_id IS NULL AND l.auth_config_revision = t.auth_config_revision AND l.created_at_ms = t.finalized_at_ms\n JOIN coordinator_auth_link_audit_log a ON a.coordinator_id = t.coordinator_id AND a.link_id = t.link_id AND a.action = 'link_created'\n AND a.attempt_id = t.attempt_id AND a.identity_id = t.identity_id AND a.group_id = t.group_id AND a.device_id = t.device_id\n AND a.fingerprint = t.fingerprint AND a.authority_kind = 'controller_attestation' AND a.controller_attestation_id IS t.controller_attestation_id AND a.device_claim_id IS NULL AND a.auth_config_revision = t.auth_config_revision AND a.created_at_ms = t.finalized_at_ms\n WHERE t.authority_kind = 'controller_attestation' AND t.coordinator_id = ? AND t.attempt_id = ? AND t.link_id = ?`;\n}\n","import {\n\tCONNECTION_REQUESTER_ACTIVE_OTHER_CLAIM_SQL,\n\tCONNECTION_REQUESTER_ATTESTATION_IDENTITY_SQL,\n\tCONNECTION_REQUESTER_IDENTITY_SQL,\n} from \"./coordinator-account-connection-link.js\";\nimport {\n\tconnectionAdmissionSql,\n\thasConnectionSessionSchema,\n} from \"./coordinator-account-connection-session.js\";\nimport {\n\tCONNECTION_ALLOCATE_ORDER_SQL,\n\tCONNECTION_ARCHIVED_CURRENT_MATCH_SQL,\n\tCONNECTION_ASSERT_ONE_WRITE_SQL,\n\tCONNECTION_BIRTH_COLUMNS,\n\tCONNECTION_NOT_REVOKED_SQL,\n} from \"./coordinator-account-connection-storage.js\";\nimport { ACCOUNT_UNLINK_TABLE } from \"./coordinator-account-unlink-schema.js\";\nimport { captureAuthAccountProfile } from \"./coordinator-auth-account-profile.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport {\n\tAUTH_DEVICE_CLAIM_CURRENT_SUBJECT_COMPATIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_INPUT_SQL,\n\tAUTH_DEVICE_CLAIM_LEGACY_COMPATIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_LEGACY_UNWAIVABLE_SQL,\n\tAUTH_DEVICE_CLAIM_REQUESTER_ATTESTATION_COMPATIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_REQUESTER_INVITE_COMPATIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_REQUESTER_LINK_COMPATIBLE_SQL,\n\tcaptureDeviceClaimEligibility,\n} from \"./coordinator-auth-device-claim-eligibility.js\";\nimport {\n\tAUTH_LINK_CONTROLLER_SOURCE_SQL,\n\ttype AuthLinkBackend,\n\ttype AuthLinkStatement,\n\tauthLinkControllerSourceValues,\n\tauthLinkNow,\n} from \"./coordinator-auth-link.js\";\nimport {\n\tAUTH_LINK_EXPIRE_BATCH_MAX,\n\ttype CoordinatorAuthLinkConfig,\n\ttype CoordinatorAuthLinkSigner,\n} from \"./coordinator-auth-link-contract.js\";\nimport {\n\tcapture,\n\tcaptureAuthLinkConfig,\n\tcaptureAuthLinkSigner,\n\tisHash,\n} from \"./coordinator-auth-link-input.js\";\nimport {\n\tauthClaimGenesisSql,\n\tauthDeviceClaimProvenanceSql,\n} from \"./coordinator-auth-link-provenance.js\";\nimport { parseCoordinatorAuthLoopback } from \"./coordinator-auth-loopback.js\";\nimport { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\n\nconst table = \"coordinator_account_change_attempts\";\nconst history = \"coordinator_auth_account_connection_history\";\nconst orders = \"coordinator_auth_account_connection_orders\";\nconst current = \"coordinator_auth_account_links\";\nconst sql = (query: string, values: AuthLinkStatement[\"values\"] = []): AuthLinkStatement => ({\n\tsql: query,\n\tvalues,\n});\nconst assertOne = sql(CONNECTION_ASSERT_ONE_WRITE_SQL);\ntype Intent = \"refresh\" | \"disconnect\";\ninterface ChangeRow {\n\tattempt_id: string;\n\ttarget_link_id: string;\n\tidentity_id: string;\n\tissuer: string;\n\ttarget_subject: string;\n\tintent: Intent;\n\tstate: string;\n\tauth_config_revision: string;\n\tenrollment_identity_id: string | null;\n\tgroup_id: string;\n\tdevice_id: string;\n\tpublic_key: string;\n\tfingerprint: string;\n\truntime_verifier_hash: string;\n\tcompletion_secret_hash: string | null;\n\tcompleted_at_ms: number;\n\tnonce: string;\n\tpkce_verifier: string;\n\texpires_at_ms: number;\n\tloopback_redirect: string;\n\tdisplay_name: string | null;\n\temail: string | null;\n\temail_verified: number | null;\n\tpicture_url: string | null;\n}\nexport interface AccountChangeOutcome {\n\tintent: Intent;\n\ttargetLinkId: string;\n\tcompletedAtMs: number;\n}\ninterface Signed {\n\tattemptId: string;\n\tsigner: CoordinatorAuthLinkSigner;\n\truntimeVerifierHash: string;\n\texpectedIdentityId: string;\n}\nfunction signed(value: unknown): Signed | null {\n\tconst i = capture(value, [\"attemptId\", \"signer\", \"runtimeVerifierHash\", \"expectedIdentityId\"]);\n\tconst signer = captureAuthLinkSigner(i?.signer);\n\tif (\n\t\t!i ||\n\t\t!signer ||\n\t\t!isAuthControllerId(i.attemptId) ||\n\t\t!isHash(i.runtimeVerifierHash) ||\n\t\t!isAuthControllerId(i.expectedIdentityId)\n\t)\n\t\treturn null;\n\treturn {\n\t\tattemptId: i.attemptId,\n\t\tsigner,\n\t\truntimeVerifierHash: i.runtimeVerifierHash,\n\t\texpectedIdentityId: i.expectedIdentityId,\n\t};\n}\nfunction signerValues(s: CoordinatorAuthLinkSigner): string[] {\n\treturn [s.groupId, s.deviceId, s.publicKey, s.fingerprint];\n}\nconst signedMatch =\n\t\"a.group_id = ? AND a.device_id = ? AND a.public_key = ? AND a.fingerprint = ? AND a.runtime_verifier_hash = ? AND a.identity_id = ?\";\nconst signedValues = (i: Signed) => [\n\t...signerValues(i.signer),\n\ti.runtimeVerifierHash,\n\ti.expectedIdentityId,\n];\nconst configured = \"a.coordinator_id = ? AND a.issuer = ? AND a.auth_config_revision = ? AND ? = 1\";\nconst configValues = (c: CoordinatorAuthLinkConfig) => [\n\tc.coordinatorId,\n\tc.issuer,\n\tc.revision,\n\tNumber(c.enabled),\n];\nconst outcome = (a: ChangeRow): AccountChangeOutcome => ({\n\tintent: a.intent,\n\ttargetLinkId: a.target_link_id,\n\tcompletedAtMs: a.completed_at_ms,\n});\nfunction unlinkInput(value: unknown) {\n\tconst i = capture(value, [\n\t\t\"attemptId\",\n\t\t\"signer\",\n\t\t\"expectedIdentityId\",\n\t\t\"expectedLinkId\",\n\t\t\"requestHash\",\n\t]);\n\tconst signer = captureAuthLinkSigner(i?.signer);\n\tif (\n\t\t!i ||\n\t\t!signer ||\n\t\t!isAuthControllerId(i.attemptId) ||\n\t\t!isAuthControllerId(i.expectedIdentityId) ||\n\t\t!isAuthControllerId(i.expectedLinkId) ||\n\t\t!isHash(i.requestHash)\n\t)\n\t\treturn null;\n\treturn {\n\t\tattemptId: i.attemptId,\n\t\tsigner,\n\t\texpectedIdentityId: i.expectedIdentityId,\n\t\texpectedLinkId: i.expectedLinkId,\n\t\trequestHash: i.requestHash,\n\t};\n}\n\n// LINK and CHANGE share admission budgets; terminal receipts still count toward\n// hourly/retention creation limits, but not toward concurrent live attempts.\n// Retained failures also consume the existing coordinator unfinished budget.\nconst admission = `, change_admitted AS (SELECT p.* FROM claim_input p WHERE ${connectionAdmissionSql(\"p\")})`;\nfunction browserPin(value: unknown) {\n\tconst i = capture(value, [\"attemptId\", \"stateHash\", \"binderHash\"]);\n\tif (!i || !isAuthControllerId(i.attemptId) || !isHash(i.stateHash) || !isHash(i.binderHash))\n\t\treturn null;\n\treturn { attemptId: i.attemptId, stateHash: i.stateHash, binderHash: i.binderHash };\n}\nconst browserMatch = \"a.attempt_id = ? AND a.state_hash = ? AND a.binder_hash = ?\";\nconst scrub =\n\t\"nonce = NULL,pkce_verifier = NULL,display_name = NULL,email = NULL,email_verified = NULL,picture_url = NULL\";\n\n/** Private persistence boundary only. Signed inputs must come from the\n * signature verifier; verified callbacks must come from the maintained OIDC\n * adapter after state/binder consumption. These methods do not verify signatures,\n * Google tokens, browser cookies or CSRF, and must never be mounted as JSON APIs.\n */\n/** This exact device key's ownership binding for the requested Identity, if any. */\nconst REQUESTER_BINDING_SQL = `SELECT ob.binding_id, ob.identity_id FROM claim_input p\n JOIN coordinator_device_ownership_bindings ob ON ob.coordinator_id = p.coordinator_id\n AND ob.device_id = p.device_id AND ob.key_id = p.key_id AND ob.identity_id = p.identity_id`;\n\nexport class AccountChangeOperations {\n\tconstructor(\n\t\tprivate readonly backend: AuthLinkBackend,\n\t\tprivate readonly clock: () => number = Date.now,\n\t) {}\n\tprivate first<T>(statement: AuthLinkStatement) {\n\t\treturn this.backend.first<T>(statement);\n\t}\n\tprivate async atomic(statements: AuthLinkStatement[]): Promise<boolean> {\n\t\ttry {\n\t\t\tawait this.backend.batch(statements);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\tprivate row(c: CoordinatorAuthLinkConfig, id: string) {\n\t\treturn this.first<ChangeRow>(\n\t\t\tsql(`SELECT * FROM ${table} WHERE coordinator_id = ? AND attempt_id = ?`, [\n\t\t\t\tc.coordinatorId,\n\t\t\t\tid,\n\t\t\t]),\n\t\t);\n\t}\n\t// An ownership binding (ADR 0005 Section 8 rebind) is this exact device key's own\n\t// proof for its Identity, like its own claim or attestation, and it supersedes\n\t// conflicting legacy Team history for that device.\n\tprivate async authority(\n\t\tc: CoordinatorAuthLinkConfig,\n\t\ts: CoordinatorAuthLinkSigner,\n\t\ttarget: { identity_id: string; target_link_id: string },\n\t\tnow: number,\n\t) {\n\t\tconst captured = await captureDeviceClaimEligibility(\n\t\t\tthis.backend,\n\t\t\t{ identityId: target.identity_id, signer: s },\n\t\t\tc,\n\t\t\tnow,\n\t\t);\n\t\tif (!captured) return null;\n\t\t// Independent proof facts keep native D1's expression depth below 100.\n\t\tconst facts = `,\n device_births AS MATERIALIZED (SELECT l.coordinator_id,l.link_id FROM coordinator_auth_account_links l JOIN claim_input p ON p.coordinator_id=l.coordinator_id AND p.identity_id=l.identity_id WHERE ${authDeviceClaimProvenanceSql({ link: \"l\", connections: captured.connectionSession })}),\n original_claims AS MATERIALIZED (SELECT d.* FROM coordinator_auth_device_claims d JOIN claim_input p ON p.coordinator_id=d.coordinator_id AND p.identity_id=d.identity_id WHERE ${captured.connectionSession ? authClaimGenesisSql(\"d\") : \"1 = 1\"}),\n controller_births AS MATERIALIZED (SELECT l.coordinator_id,l.link_id FROM coordinator_auth_account_links l\n JOIN coordinator_auth_link_attempts b ON b.coordinator_id=l.coordinator_id AND b.link_id=l.link_id AND b.attempt_id=l.attempt_id\n JOIN coordinator_auth_link_audit_log ca ON ca.coordinator_id=l.coordinator_id AND ca.link_id=l.link_id AND ca.action='link_created'\n JOIN coordinator_auth_controller_attestations origin ON origin.coordinator_id=l.coordinator_id AND origin.attestation_id=l.controller_attestation_id\n WHERE (l.authority_kind='controller_attestation' AND l.device_claim_id IS NULL AND b.authority_kind=l.authority_kind AND b.controller_attestation_id=l.controller_attestation_id)\n AND (ca.attempt_id=b.attempt_id AND ca.identity_id=l.identity_id AND ca.controller_attestation_id=l.controller_attestation_id AND ca.authority_kind=l.authority_kind AND ca.auth_config_revision=l.auth_config_revision AND ca.group_id=b.group_id AND ca.device_id=b.device_id AND ca.fingerprint=b.fingerprint AND ca.created_at_ms=l.created_at_ms AND b.finalized_at_ms=l.created_at_ms)\n AND (origin.group_id=b.group_id AND origin.device_id=b.device_id AND origin.public_key=b.public_key AND origin.fingerprint=b.fingerprint AND origin.identity_id=b.identity_id AND origin.review_receipt_id=b.controller_review_receipt_id AND origin.revision=b.controller_revision)\n ${captured.connectionSession ? \"AND (b.prior_link_id IS NULL OR EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id=b.coordinator_id AND h.identity_id=b.identity_id AND h.link_id=b.prior_link_id AND h.successor_link_id=b.link_id))\" : \"\"})`;\n\t\treturn sql(\n\t\t\t`${AUTH_DEVICE_CLAIM_INPUT_SQL}, current_controller AS MATERIALIZED (SELECT a.* ${AUTH_LINK_CONTROLLER_SOURCE_SQL})${facts},\n requester_binding AS MATERIALIZED (${REQUESTER_BINDING_SQL}),\n requester_ok AS MATERIALIZED (SELECT p.* FROM claim_input p WHERE (${AUTH_DEVICE_CLAIM_CURRENT_SUBJECT_COMPATIBLE_SQL}) AND (${CONNECTION_REQUESTER_ATTESTATION_IDENTITY_SQL}) AND ((${CONNECTION_REQUESTER_IDENTITY_SQL}) OR (EXISTS (SELECT 1 FROM requester_binding) AND ${CONNECTION_REQUESTER_ACTIVE_OTHER_CLAIM_SQL})) AND ((${AUTH_DEVICE_CLAIM_REQUESTER_ATTESTATION_COMPATIBLE_SQL}) OR EXISTS (SELECT 1 FROM current_controller cc WHERE cc.identity_id=p.identity_id)) AND (${AUTH_DEVICE_CLAIM_REQUESTER_INVITE_COMPATIBLE_SQL}) AND (${AUTH_DEVICE_CLAIM_REQUESTER_LINK_COMPATIBLE_SQL}) AND (${AUTH_DEVICE_CLAIM_LEGACY_UNWAIVABLE_SQL}) AND ((${AUTH_DEVICE_CLAIM_LEGACY_COMPATIBLE_SQL}) OR EXISTS (SELECT 1 FROM requester_binding))), change_authority AS MATERIALIZED (\n SELECT l.*,e.identity_id AS enrollment_identity_id FROM requester_ok p\n JOIN ${current} l ON l.coordinator_id = p.coordinator_id AND l.link_id = ? AND l.identity_id = p.identity_id AND l.issuer = p.issuer\n JOIN enrolled_devices e ON e.group_id = p.group_id AND e.device_id = p.device_id AND e.public_key = p.public_key AND e.fingerprint = p.fingerprint\n JOIN groups g ON g.group_id = e.group_id\n JOIN coordinator_auth_link_attempts b ON b.coordinator_id = l.coordinator_id AND b.link_id = l.link_id AND b.attempt_id = l.attempt_id\n LEFT JOIN controller_births cb ON cb.coordinator_id=l.coordinator_id AND cb.link_id=l.link_id\n LEFT JOIN device_births db ON db.coordinator_id=l.coordinator_id AND db.link_id=l.link_id\n LEFT JOIN current_controller cc ON cc.identity_id=l.identity_id\n LEFT JOIN requester_binding rb ON rb.identity_id=l.identity_id\n LEFT JOIN original_claims d ON d.coordinator_id=l.coordinator_id AND ${captured.connectionSession ? \"d.identity_id=l.identity_id\" : \"d.claim_id=l.device_claim_id\"} AND d.group_id=p.group_id AND d.device_id=p.device_id AND d.public_key=p.public_key AND d.fingerprint=p.fingerprint AND d.key_id=p.key_id\n WHERE (e.enabled = 1 AND g.archived_at IS NULL AND (e.identity_id IS NULL OR e.identity_id = l.identity_id))\n AND (b.identity_id = l.identity_id AND b.issuer = l.issuer AND b.account_subject = l.subject AND b.auth_config_revision = l.auth_config_revision AND b.state IN ('finalized','session_redeemed'))\n AND (${CONNECTION_NOT_REVOKED_SQL})\n AND NOT EXISTS (SELECT 1 FROM coordinator_device_revocations r WHERE (r.subject_kind = 'device_id' AND r.subject_value = p.device_id) OR (r.subject_kind = 'ed25519_key' AND r.subject_value = p.key_id))\n AND (cb.link_id IS NOT NULL OR db.link_id IS NOT NULL) AND (cc.attestation_id IS NOT NULL OR d.claim_id IS NOT NULL OR rb.binding_id IS NOT NULL))`,\n\t\t\t[...captured.values, ...authLinkControllerSourceValues(c, s), target.target_link_id],\n\t\t);\n\t}\n\t// Expected Identity is checked after deriving authority, never used to grant it.\n\t// This device's binding wins a tie; the authority check still denies when an\n\t// older claim's link is active.\n\tprivate deriveTarget(c: CoordinatorAuthLinkConfig, i: Pick<Signed, \"signer\">, key: string) {\n\t\treturn this.first<{ identity_id: string; target_link_id: string }>(\n\t\t\tsql(\n\t\t\t\t`SELECT l.identity_id,l.link_id AS target_link_id FROM ${current} l\n LEFT JOIN coordinator_auth_device_claims d ON d.coordinator_id = l.coordinator_id AND d.identity_id = l.identity_id\n LEFT JOIN coordinator_auth_controller_attestations a ON a.coordinator_id = l.coordinator_id AND a.identity_id = l.identity_id\n LEFT JOIN coordinator_device_ownership_bindings ob ON ob.coordinator_id = l.coordinator_id AND ob.identity_id = l.identity_id\n WHERE l.coordinator_id = ? AND ((d.device_id = ? AND d.key_id = ?) OR\n (a.group_id = ? AND a.device_id = ? AND a.public_key = ? AND a.fingerprint = ? AND a.revoked_at IS NULL)\n OR (ob.device_id = ? AND ob.key_id = ?))\n ORDER BY (ob.device_id = ? AND ob.key_id = ?) DESC, l.link_id`,\n\t\t\t\t[\n\t\t\t\t\tc.coordinatorId,\n\t\t\t\t\ti.signer.deviceId,\n\t\t\t\t\tkey,\n\t\t\t\t\t...signerValues(i.signer),\n\t\t\t\t\ti.signer.deviceId,\n\t\t\t\t\tkey,\n\t\t\t\t\ti.signer.deviceId,\n\t\t\t\t\tkey,\n\t\t\t\t],\n\t\t\t),\n\t\t);\n\t}\n\tprivate retryCreate(\n\t\tc: CoordinatorAuthLinkConfig,\n\t\ti: Signed,\n\t\textra: Record<string, unknown>,\n\t\tnow: number,\n\t) {\n\t\treturn this.first(\n\t\t\tsql(\n\t\t\t\t`SELECT 1 FROM ${table} a WHERE ${configured} AND a.attempt_id = ? AND ${signedMatch} AND a.intent = ? AND a.browser_start_hash = ? AND a.loopback_redirect = ? AND a.state NOT IN ('cancelled','failed','expired') AND (a.state = 'completed' OR a.expires_at_ms > ?)`,\n\t\t\t\t[\n\t\t\t\t\t...configValues(c),\n\t\t\t\t\ti.attemptId,\n\t\t\t\t\t...signedValues(i),\n\t\t\t\t\textra.intent as string,\n\t\t\t\t\textra.browserStartHash as string,\n\t\t\t\t\textra.loopbackRedirect as string,\n\t\t\t\t\tnow,\n\t\t\t\t],\n\t\t\t),\n\t\t);\n\t}\n\t/** Descriptive device actions only; create/finalize always recheck current authority. */\n\tasync readCapabilities(\n\t\tvalue: unknown,\n\t\tconfig: unknown,\n\t): Promise<{ refresh: boolean; disconnect: boolean; unlinkTarget?: string }> {\n\t\tconst c = captureAuthLinkConfig(config);\n\t\tconst i = capture(value, [\"signer\", \"expectedIdentityId\"]);\n\t\tconst signer = captureAuthLinkSigner(i?.signer);\n\t\tconst unavailable = { refresh: false, disconnect: false };\n\t\tif (!c?.enabled || !i || !signer || !isAuthControllerId(i.expectedIdentityId))\n\t\t\treturn unavailable;\n\t\tconst key = await ed25519KeyIdForRevocation(signer.publicKey);\n\t\tif (!key) return unavailable;\n\t\tconst target = await this.deriveTarget(c, { signer }, key);\n\t\tif (!target || target.identity_id !== i.expectedIdentityId) return unavailable;\n\t\tconst authority = await this.authority(c, signer, target, authLinkNow(this.clock));\n\t\tif (!authority) return unavailable;\n\t\tconst allowed = !!(await this.first(\n\t\t\tsql(`${authority.sql} SELECT 1 FROM change_authority`, authority.values),\n\t\t));\n\t\treturn {\n\t\t\trefresh: allowed,\n\t\t\tdisconnect: allowed,\n\t\t\t...(allowed ? { unlinkTarget: target.target_link_id } : {}),\n\t\t};\n\t}\n\t/** Device-signed unlink only. The winning INSERT rechecks live authority and the exact target. */\n\tasync unlink(value: unknown, config: unknown): Promise<AccountChangeOutcome | null> {\n\t\tconst c = captureAuthLinkConfig(config);\n\t\tconst i = unlinkInput(value);\n\t\tif (!c?.enabled || !i) return null;\n\t\tconst { signer } = i;\n\t\tconst pins = [\n\t\t\tc.coordinatorId,\n\t\t\ti.attemptId,\n\t\t\ti.expectedLinkId,\n\t\t\ti.expectedIdentityId,\n\t\t\tc.issuer,\n\t\t\t...signerValues(signer),\n\t\t\tc.revision,\n\t\t\ti.requestHash,\n\t\t];\n\t\tconst retry = () =>\n\t\t\tthis.first<{ targetLinkId: string; completedAtMs: number }>(\n\t\t\t\tsql(\n\t\t\t\t\t`SELECT target_link_id AS targetLinkId,completed_at_ms AS completedAtMs FROM ${ACCOUNT_UNLINK_TABLE} WHERE coordinator_id=? AND attempt_id=? AND target_link_id=? AND identity_id=? AND issuer=? AND group_id=? AND device_id=? AND public_key=? AND fingerprint=? AND auth_config_revision=? AND request_hash=? AND state='completed'`,\n\t\t\t\t\tpins,\n\t\t\t\t),\n\t\t\t);\n\t\tconst prior = await retry();\n\t\tif (prior) return { intent: \"disconnect\", ...prior };\n\t\tconst key = await ed25519KeyIdForRevocation(signer.publicKey);\n\t\tif (!key) return null;\n\t\tconst target = await this.deriveTarget(c, { signer }, key);\n\t\tif (\n\t\t\t!target ||\n\t\t\ttarget.identity_id !== i.expectedIdentityId ||\n\t\t\ttarget.target_link_id !== i.expectedLinkId\n\t\t)\n\t\t\treturn null;\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst authority = await this.authority(c, signer, target, now);\n\t\tif (!authority) return null;\n\t\tawait this.atomic([\n\t\t\tsql(\n\t\t\t\t`${authority.sql} INSERT INTO ${ACCOUNT_UNLINK_TABLE} (coordinator_id,attempt_id,target_link_id,identity_id,issuer,target_subject,group_id,device_id,public_key,fingerprint,enrollment_identity_id,auth_config_revision,request_hash,state,created_at_ms)\n SELECT coordinator_id,?,link_id,identity_id,issuer,subject,?,?,?,?,enrollment_identity_id,?,?,'committing',? FROM change_authority`,\n\t\t\t\t[...authority.values, i.attemptId, ...signerValues(signer), c.revision, i.requestHash, now],\n\t\t\t),\n\t\t\tassertOne,\n\t\t\t...disconnectEffects(c.coordinatorId, i.attemptId, now, { connections: true, device: true }),\n\t\t\tsql(\n\t\t\t\t`UPDATE ${ACCOUNT_UNLINK_TABLE} SET state='completed',completed_at_ms=? WHERE coordinator_id=? AND attempt_id=? AND state='committing'`,\n\t\t\t\t[now, c.coordinatorId, i.attemptId],\n\t\t\t),\n\t\t\tassertOne,\n\t\t]);\n\t\tconst completed = await retry();\n\t\treturn completed ? { intent: \"disconnect\", ...completed } : null;\n\t}\n\tasync create(value: unknown, config: unknown): Promise<boolean> {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = signed(value);\n\t\tconst extra = capture(value, [\"intent\", \"browserStartHash\", \"loopbackRedirect\"]);\n\t\tif (\n\t\t\t!c?.enabled ||\n\t\t\t!i ||\n\t\t\t!extra ||\n\t\t\t!isHash(extra.browserStartHash) ||\n\t\t\t!parseCoordinatorAuthLoopback(extra.loopbackRedirect).ok ||\n\t\t\t(extra.intent !== \"refresh\" && extra.intent !== \"disconnect\")\n\t\t)\n\t\t\treturn false;\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst retry = () => this.retryCreate(c, i, extra, now);\n\t\tif (await this.row(c, i.attemptId)) return !!(await retry());\n\t\tconst key = await ed25519KeyIdForRevocation(i.signer.publicKey);\n\t\tif (!key) return false;\n\t\tconst target = await this.deriveTarget(c, i, key);\n\t\tif (!target || target.identity_id !== i.expectedIdentityId) return false;\n\t\tconst authority = await this.authority(c, i.signer, target, now);\n\t\tif (!authority) return false;\n\t\treturn (\n\t\t\t(await this.atomic([\n\t\t\t\tsql(\n\t\t\t\t\t`${authority.sql}${admission} INSERT INTO ${table}\n (coordinator_id,attempt_id,intent,target_link_id,identity_id,issuer,target_subject,group_id,device_id,public_key,fingerprint,key_id,enrollment_identity_id,auth_config_revision,runtime_verifier_hash,browser_start_hash,loopback_redirect,state,created_at_ms,expires_at_ms)\n SELECT coordinator_id,?,?,link_id,identity_id,issuer,subject,?,?,?,?,?,enrollment_identity_id,?,?,?,?,'pending',?,? FROM change_authority WHERE EXISTS (SELECT 1 FROM change_admitted)`,\n\t\t\t\t\t[\n\t\t\t\t\t\t...authority.values,\n\t\t\t\t\t\ti.attemptId,\n\t\t\t\t\t\textra.intent,\n\t\t\t\t\t\t...signerValues(i.signer),\n\t\t\t\t\t\tkey,\n\t\t\t\t\t\tc.revision,\n\t\t\t\t\t\ti.runtimeVerifierHash,\n\t\t\t\t\t\textra.browserStartHash,\n\t\t\t\t\t\textra.loopbackRedirect as string,\n\t\t\t\t\t\tnow,\n\t\t\t\t\t\tnow + 600000,\n\t\t\t\t\t],\n\t\t\t\t),\n\t\t\t\tassertOne,\n\t\t\t])) || !!(await retry())\n\t\t);\n\t}\n\tasync claimBrowser(value: unknown, config: unknown): Promise<boolean> {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = capture(value, [\n\t\t\t\t\"attemptId\",\n\t\t\t\t\"browserStartHash\",\n\t\t\t\t\"stateHash\",\n\t\t\t\t\"binderHash\",\n\t\t\t\t\"nonce\",\n\t\t\t\t\"pkceVerifier\",\n\t\t\t]);\n\t\tif (\n\t\t\t!c?.enabled ||\n\t\t\t!i ||\n\t\t\t!isAuthControllerId(i.attemptId) ||\n\t\t\t![i.browserStartHash, i.stateHash, i.binderHash].every(isHash) ||\n\t\t\t![i.nonce, i.pkceVerifier].every(\n\t\t\t\t(v) => typeof v === \"string\" && /^[A-Za-z0-9_-]{43,128}$/.test(v),\n\t\t\t)\n\t\t)\n\t\t\treturn false;\n\t\tconst now = authLinkNow(this.clock);\n\t\treturn this.atomic([\n\t\t\tsql(\n\t\t\t\t`INSERT INTO ${orders} (coordinator_id,last_order) SELECT ?,0 WHERE NOT EXISTS (SELECT 1 FROM ${orders} WHERE coordinator_id = ?)`,\n\t\t\t\t[c.coordinatorId, c.coordinatorId],\n\t\t\t),\n\t\t\tsql(CONNECTION_ALLOCATE_ORDER_SQL, [c.coordinatorId]),\n\t\t\tassertOne,\n\t\t\tsql(\n\t\t\t\t`UPDATE ${table} AS a SET state = 'browser_pending',state_hash = ?,binder_hash = ?,nonce = ?,pkce_verifier = ?,browser_order = (SELECT last_order FROM ${orders} WHERE coordinator_id = a.coordinator_id)\n WHERE ${configured} AND a.attempt_id = ? AND a.browser_start_hash = ? AND a.state = 'pending' AND a.expires_at_ms > ?`,\n\t\t\t\t[\n\t\t\t\t\ti.stateHash as string,\n\t\t\t\t\ti.binderHash as string,\n\t\t\t\t\ti.nonce as string,\n\t\t\t\t\ti.pkceVerifier as string,\n\t\t\t\t\t...configValues(c),\n\t\t\t\t\ti.attemptId,\n\t\t\t\t\ti.browserStartHash as string,\n\t\t\t\t\tnow,\n\t\t\t\t],\n\t\t\t),\n\t\t\tassertOne,\n\t\t]);\n\t}\n\t/** Lookup AND one-use consumption are one private operation; returned secrets\n\t * may be used only by the OIDC exchange, never returned by a public status API. */\n\tasync consumeCallback(value: unknown, config: unknown) {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = capture(value, [\"stateHash\", \"binderHash\"]);\n\t\tif (!c?.enabled || !i || !isHash(i.stateHash) || !isHash(i.binderHash)) return null;\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst a = await this.first<ChangeRow>(\n\t\t\tsql(\n\t\t\t\t`SELECT * FROM ${table} a WHERE ${configured} AND a.state_hash = ? AND a.binder_hash = ? AND a.state = 'browser_pending' AND a.expires_at_ms > ?`,\n\t\t\t\t[...configValues(c), i.stateHash, i.binderHash, now],\n\t\t\t),\n\t\t);\n\t\tif (!a) return null;\n\t\tconst won = await this.atomic([\n\t\t\tsql(\n\t\t\t\t`UPDATE ${table} AS a SET state = 'consumed',nonce = NULL,pkce_verifier = NULL,consumed_at_ms = ? WHERE ${configured} AND a.attempt_id = ? AND a.state_hash = ? AND a.binder_hash = ? AND a.state = 'browser_pending' AND a.expires_at_ms > ?`,\n\t\t\t\t[now, ...configValues(c), a.attempt_id, i.stateHash, i.binderHash, now],\n\t\t\t),\n\t\t\tassertOne,\n\t\t]);\n\t\treturn won ? { attemptId: a.attempt_id, nonce: a.nonce, pkceVerifier: a.pkce_verifier } : null;\n\t}\n\tprivate async callbackAuthority(c: CoordinatorAuthLinkConfig, attemptId: string, now: number) {\n\t\tconst a = await this.row(c, attemptId);\n\t\tif (!a) return null;\n\t\treturn this.authority(\n\t\t\tc,\n\t\t\t{\n\t\t\t\tgroupId: a.group_id,\n\t\t\t\tdeviceId: a.device_id,\n\t\t\t\tpublicKey: a.public_key,\n\t\t\t\tfingerprint: a.fingerprint,\n\t\t\t},\n\t\t\ta,\n\t\t\tnow,\n\t\t);\n\t}\n\t/** Trusted adapter output, not HTTP account JSON. No autoConfirm caller flag. */\n\tasync recordVerifiedCallback(value: unknown, config: unknown): Promise<boolean> {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = capture(value, [\n\t\t\t\t\"attemptId\",\n\t\t\t\t\"stateHash\",\n\t\t\t\t\"binderHash\",\n\t\t\t\t\"issuer\",\n\t\t\t\t\"subject\",\n\t\t\t\t\"profile\",\n\t\t\t\t\"completionSecretHash\",\n\t\t\t]);\n\t\tconst profile = captureAuthAccountProfile(i?.profile);\n\t\tif (\n\t\t\t!c?.enabled ||\n\t\t\t!i ||\n\t\t\t!profile ||\n\t\t\t!isAuthControllerId(i.attemptId) ||\n\t\t\t![i.stateHash, i.binderHash, i.completionSecretHash].every(isHash) ||\n\t\t\ti.issuer !== c.issuer ||\n\t\t\ttypeof i.subject !== \"string\"\n\t\t)\n\t\t\treturn false;\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst authority = await this.callbackAuthority(c, i.attemptId, now);\n\t\tif (!authority) return false;\n\t\treturn this.atomic([\n\t\t\tsql(\n\t\t\t\t`${authority.sql} UPDATE ${table} AS a SET state = CASE intent WHEN 'refresh' THEN 'confirmed' ELSE 'verified' END,verified_at_ms = ?,\n confirmed_at_ms = CASE intent WHEN 'refresh' THEN ? END,completion_secret_hash = CASE intent WHEN 'refresh' THEN ? END,\n display_name = ?,email = ?,email_verified = ?,picture_url = ? WHERE ${configured} AND a.attempt_id = ? AND a.state_hash = ? AND a.binder_hash = ? AND a.target_subject = ? AND a.state = 'consumed' AND a.expires_at_ms > ?\n AND EXISTS (SELECT 1 FROM change_authority l WHERE l.coordinator_id = a.coordinator_id AND l.link_id = a.target_link_id AND l.identity_id = a.identity_id AND l.subject = a.target_subject AND l.issuer = a.issuer AND l.enrollment_identity_id IS a.enrollment_identity_id)`,\n\t\t\t\t[\n\t\t\t\t\t...authority.values,\n\t\t\t\t\tnow,\n\t\t\t\t\tnow,\n\t\t\t\t\ti.completionSecretHash as string,\n\t\t\t\t\tprofile.displayName ?? null,\n\t\t\t\t\tprofile.email ?? null,\n\t\t\t\t\tprofile.emailVerified === undefined ? null : Number(profile.emailVerified),\n\t\t\t\t\tprofile.pictureUrl ?? null,\n\t\t\t\t\t...configValues(c),\n\t\t\t\t\ti.attemptId,\n\t\t\t\t\ti.stateHash as string,\n\t\t\t\t\ti.binderHash as string,\n\t\t\t\t\ti.subject,\n\t\t\t\t\tnow,\n\t\t\t\t],\n\t\t\t),\n\t\t\tassertOne,\n\t\t]);\n\t}\n\t/** The browser handler validates the fresh binder and CSRF before this call. */\n\tasync confirmDisconnect(value: unknown, config: unknown): Promise<boolean> {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = browserPin(value),\n\t\t\tproof = capture(value, [\"completionSecretHash\"]);\n\t\tif (!c?.enabled || !i || !proof || !isHash(proof.completionSecretHash)) return false;\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst won = await this.atomic([\n\t\t\tsql(\n\t\t\t\t`UPDATE ${table} AS a SET state = 'confirmed',confirmed_at_ms = ?,completion_secret_hash = ? WHERE ${configured} AND a.attempt_id = ? AND a.state_hash = ? AND a.binder_hash = ? AND a.intent = 'disconnect' AND a.state = 'verified' AND a.expires_at_ms > ?`,\n\t\t\t\t[\n\t\t\t\t\tnow,\n\t\t\t\t\tproof.completionSecretHash,\n\t\t\t\t\t...configValues(c),\n\t\t\t\t\ti.attemptId,\n\t\t\t\t\ti.stateHash as string,\n\t\t\t\t\ti.binderHash as string,\n\t\t\t\t\tnow,\n\t\t\t\t],\n\t\t\t),\n\t\t\tassertOne,\n\t\t]);\n\t\tif (won) return true;\n\t\treturn this.readConfirmedDisconnect(i, proof.completionSecretHash, c);\n\t}\n\tprivate async readConfirmedDisconnect(\n\t\tpins: NonNullable<ReturnType<typeof browserPin>>,\n\t\tcompletionSecretHash: string,\n\t\tc: CoordinatorAuthLinkConfig,\n\t): Promise<boolean> {\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst authority = await this.callbackAuthority(c, pins.attemptId, now);\n\t\tif (!authority) return false;\n\t\t// This request still owns the raw secret; never recover from status alone.\n\t\treturn !!(await this.first(\n\t\t\tsql(\n\t\t\t\t`${authority.sql} SELECT 1 FROM ${table} a WHERE ${configured} AND ${browserMatch}\n AND a.intent='disconnect' AND a.state='confirmed' AND a.completion_secret_hash=? AND a.expires_at_ms>?\n AND EXISTS (SELECT 1 FROM change_authority l WHERE l.coordinator_id=a.coordinator_id AND l.link_id=a.target_link_id\n AND l.identity_id=a.identity_id AND l.subject=a.target_subject AND l.issuer=a.issuer AND l.enrollment_identity_id IS a.enrollment_identity_id)`,\n\t\t\t\t[\n\t\t\t\t\t...authority.values,\n\t\t\t\t\t...configValues(c),\n\t\t\t\t\tpins.attemptId,\n\t\t\t\t\tpins.stateHash,\n\t\t\t\t\tpins.binderHash,\n\t\t\t\t\tcompletionSecretHash,\n\t\t\t\t\tnow,\n\t\t\t\t],\n\t\t\t),\n\t\t));\n\t}\n\tasync finalize(value: unknown, config: unknown): Promise<AccountChangeOutcome | null> {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = signed(value),\n\t\t\tproof = capture(value, [\"completionSecretHash\"]);\n\t\tif (!c?.enabled || !i || !proof || !isHash(proof.completionSecretHash)) return null;\n\t\tconst a = await this.row(c, i.attemptId);\n\t\tif (!a) return null;\n\t\tconst pins = [...configValues(c), i.attemptId, ...signedValues(i), proof.completionSecretHash];\n\t\tconst match = `${configured} AND a.attempt_id = ? AND ${signedMatch} AND a.completion_secret_hash = ?`;\n\t\t// Retained exact-proof retries have no effects, including after target deletion.\n\t\tconst retry = await this.first<ChangeRow>(\n\t\t\tsql(`SELECT * FROM ${table} a WHERE ${match} AND a.state = 'completed'`, pins),\n\t\t);\n\t\tif (retry) return outcome(retry);\n\t\tconst now = authLinkNow(this.clock),\n\t\t\tauthority = await this.authority(c, i.signer, a, now);\n\t\tif (!authority) return null;\n\t\tconst won = sql(\n\t\t\t`${authority.sql} UPDATE ${table} AS a SET state = 'committing' WHERE ${match} AND a.state = 'confirmed' AND a.expires_at_ms > ?\n AND EXISTS (SELECT 1 FROM change_authority ca WHERE ca.link_id = a.target_link_id AND ca.subject = a.target_subject AND ca.enrollment_identity_id IS a.enrollment_identity_id)`,\n\t\t\t[...authority.values, ...pins, now],\n\t\t);\n\t\tconst effects =\n\t\t\ta.intent === \"disconnect\"\n\t\t\t\t? disconnectEffects(c.coordinatorId, i.attemptId, now, {\n\t\t\t\t\t\tconnections: await hasConnectionSessionSchema(this.backend),\n\t\t\t\t\t})\n\t\t\t\t: refreshEffects(c.coordinatorId, i.attemptId);\n\t\tif (\n\t\t\t!(await this.atomic([\n\t\t\t\twon,\n\t\t\t\tassertOne,\n\t\t\t\t...effects,\n\t\t\t\tsql(\n\t\t\t\t\t`UPDATE ${table} SET state = 'completed',completed_at_ms = ?,display_name = NULL,email = NULL,email_verified = NULL,picture_url = NULL WHERE coordinator_id = ? AND attempt_id = ? AND state = 'committing'`,\n\t\t\t\t\t[now, c.coordinatorId, i.attemptId],\n\t\t\t\t),\n\t\t\t\tassertOne,\n\t\t\t]))\n\t\t) {\n\t\t\tconst completed = await this.first<ChangeRow>(\n\t\t\t\tsql(`SELECT * FROM ${table} a WHERE ${match} AND a.state = 'completed'`, pins),\n\t\t\t);\n\t\t\treturn completed ? outcome(completed) : null;\n\t\t}\n\t\treturn { intent: a.intent, targetLinkId: a.target_link_id, completedAtMs: now };\n\t}\n\tasync cancel(value: unknown, config: unknown): Promise<boolean> {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = signed(value);\n\t\tif (!c?.enabled || !i) return false;\n\t\treturn this.atomic([\n\t\t\tsql(\n\t\t\t\t`UPDATE ${table} AS a SET state = 'cancelled',failure_reason = 'device_cancelled',nonce = NULL,pkce_verifier = NULL,display_name = NULL,email = NULL,email_verified = NULL,picture_url = NULL WHERE ${configured} AND a.attempt_id = ? AND ${signedMatch} AND a.state NOT IN ('completed','committing','cancelled','failed','expired') AND a.expires_at_ms > ?`,\n\t\t\t\t[...configValues(c), i.attemptId, ...signedValues(i), authLinkNow(this.clock)],\n\t\t\t),\n\t\t\tassertOne,\n\t\t]);\n\t}\n\t/** Signed status is descriptive only; it never supplies management authority. */\n\tasync readStatus(value: unknown, config: unknown) {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = signed(value);\n\t\tif (!c?.enabled || !i) return null;\n\t\tconst a = await this.first<ChangeRow>(\n\t\t\tsql(`SELECT * FROM ${table} a WHERE ${configured} AND a.attempt_id = ? AND ${signedMatch}`, [\n\t\t\t\t...configValues(c),\n\t\t\t\ti.attemptId,\n\t\t\t\t...signedValues(i),\n\t\t\t]),\n\t\t);\n\t\tif (!a) return null;\n\t\tconst state =\n\t\t\t[\"pending\", \"browser_pending\", \"consumed\", \"verified\", \"confirmed\"].includes(a.state) &&\n\t\t\ta.expires_at_ms <= authLinkNow(this.clock)\n\t\t\t\t? \"expired\"\n\t\t\t\t: a.state;\n\t\treturn {\n\t\t\tattemptId: a.attempt_id,\n\t\t\tintent: a.intent,\n\t\t\tstate,\n\t\t\texpiresAtMs: a.expires_at_ms,\n\t\t\tidentityId: a.identity_id,\n\t\t};\n\t}\n\t/** Shared callback dispatch can probe exact state/binder without consuming it. */\n\tasync hasPendingCallback(value: unknown, config: unknown): Promise<boolean> {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = capture(value, [\"stateHash\", \"binderHash\"]);\n\t\tif (!c?.enabled || !i || !isHash(i.stateHash) || !isHash(i.binderHash)) return false;\n\t\treturn !!(await this.first(\n\t\t\tsql(\n\t\t\t\t`SELECT 1 FROM ${table} a WHERE ${configured} AND a.state_hash = ? AND a.binder_hash = ? AND a.state = 'browser_pending' AND a.expires_at_ms > ?`,\n\t\t\t\t[...configValues(c), i.stateHash, i.binderHash, authLinkNow(this.clock)],\n\t\t\t),\n\t\t));\n\t}\n\t/** Prepare delivery for an exact consumed proof; the winning write rechecks authority. */\n\tasync readCallbackView(value: unknown, config: unknown) {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = browserPin(value);\n\t\tif (!c?.enabled || !i) return null;\n\t\tconst a = await this.first<ChangeRow>(\n\t\t\tsql(\n\t\t\t\t`SELECT * FROM ${table} a WHERE ${configured} AND ${browserMatch} AND a.state = 'consumed' AND a.expires_at_ms > ?`,\n\t\t\t\t[...configValues(c), i.attemptId, i.stateHash, i.binderHash, authLinkNow(this.clock)],\n\t\t\t),\n\t\t);\n\t\tif (!a || !parseCoordinatorAuthLoopback(a.loopback_redirect).ok) return null;\n\t\treturn { attemptId: a.attempt_id, intent: a.intent, loopbackRedirect: a.loopback_redirect };\n\t}\n\t/** Cookie-authenticated, CSRF-protected hosted confirmation only, not status JSON. */\n\tasync readBrowserView(value: unknown, config: unknown) {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = browserPin(value);\n\t\tif (!c?.enabled || !i) return null;\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst a = await this.first<ChangeRow>(\n\t\t\tsql(\n\t\t\t\t`SELECT * FROM ${table} a WHERE ${configured} AND ${browserMatch} AND a.state IN ('verified','confirmed') AND a.expires_at_ms > ?`,\n\t\t\t\t[...configValues(c), i.attemptId, i.stateHash, i.binderHash, now],\n\t\t\t),\n\t\t);\n\t\tif (!a) return null;\n\t\tif (!parseCoordinatorAuthLoopback(a.loopback_redirect).ok) return null;\n\t\tconst authority = await this.authority(\n\t\t\tc,\n\t\t\t{\n\t\t\t\tgroupId: a.group_id,\n\t\t\t\tdeviceId: a.device_id,\n\t\t\t\tpublicKey: a.public_key,\n\t\t\t\tfingerprint: a.fingerprint,\n\t\t\t},\n\t\t\ta,\n\t\t\tnow,\n\t\t);\n\t\tif (\n\t\t\t!authority ||\n\t\t\t!(await this.first(\n\t\t\t\tsql(`${authority.sql} SELECT 1 FROM change_authority WHERE enrollment_identity_id IS ?`, [\n\t\t\t\t\t...authority.values,\n\t\t\t\t\ta.enrollment_identity_id,\n\t\t\t\t]),\n\t\t\t))\n\t\t)\n\t\t\treturn null;\n\t\tconst profile = captureAuthAccountProfile({\n\t\t\tdisplayName: a.display_name,\n\t\t\temail: a.email,\n\t\t\temailVerified: a.email_verified === null ? undefined : Boolean(a.email_verified),\n\t\t\tpictureUrl: a.picture_url,\n\t\t});\n\t\treturn {\n\t\t\tattemptId: a.attempt_id,\n\t\t\tintent: a.intent,\n\t\t\tstate: a.state,\n\t\t\tloopbackRedirect: a.loopback_redirect,\n\t\t\tidentityId: a.identity_id,\n\t\t\texpiresAtMs: a.expires_at_ms,\n\t\t\tprofile,\n\t\t};\n\t}\n\t/** Private cookie binding lookup; never returns account or redirect data. */\n\tasync readBrowserBinding(value: unknown, config: unknown): Promise<{ stateHash: string } | null> {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = capture(value, [\"attemptId\", \"binderHash\"]);\n\t\tif (!c?.enabled || !i || !isAuthControllerId(i.attemptId) || !isHash(i.binderHash)) return null;\n\t\treturn this.first(\n\t\t\tsql(\n\t\t\t\t`SELECT state_hash AS stateHash FROM ${table} a WHERE ${configured} AND a.attempt_id = ? AND a.binder_hash = ? AND a.state IN ('verified','confirmed') AND a.expires_at_ms > ?`,\n\t\t\t\t[...configValues(c), i.attemptId, i.binderHash, authLinkNow(this.clock)],\n\t\t\t),\n\t\t);\n\t}\n\t/** Private start-code lookup; no account, profile or redirect data before proof. */\n\tasync readStart(value: unknown, config: unknown) {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = capture(value, [\"attemptId\", \"browserStartHash\"]);\n\t\tif (!c?.enabled || !i || !isAuthControllerId(i.attemptId) || !isHash(i.browserStartHash))\n\t\t\treturn null;\n\t\treturn this.first<{ intent: Intent; expiresAtMs: number }>(\n\t\t\tsql(\n\t\t\t\t`SELECT intent,expires_at_ms AS expiresAtMs FROM ${table} a WHERE ${configured} AND a.attempt_id = ? AND a.browser_start_hash = ? AND a.state = 'pending' AND a.expires_at_ms > ?`,\n\t\t\t\t[...configValues(c), i.attemptId, i.browserStartHash, authLinkNow(this.clock)],\n\t\t\t),\n\t\t);\n\t}\n\t/** Cookie-binder activity probe for the shared configured browser handler. */\n\tasync readManagementActivity(value: unknown, config: unknown) {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = capture(value, [\"binderHash\"]);\n\t\tif (!c?.enabled || !i || !isHash(i.binderHash))\n\t\t\treturn { kind: \"rejected\" as const, error: \"auth_config_changed\" as const };\n\t\tconst a = await this.first<ChangeRow>(\n\t\t\tsql(`SELECT * FROM ${table} WHERE coordinator_id = ? AND binder_hash = ?`, [\n\t\t\t\tc.coordinatorId,\n\t\t\t\ti.binderHash,\n\t\t\t]),\n\t\t);\n\t\tif (!a) return { kind: \"inactive\" as const };\n\t\tif (a.issuer !== c.issuer || a.auth_config_revision !== c.revision)\n\t\t\treturn { kind: \"rejected\" as const, error: \"auth_config_changed\" as const };\n\t\tif (\n\t\t\t[\"completed\", \"cancelled\", \"failed\", \"expired\"].includes(a.state) ||\n\t\t\ta.expires_at_ms <= authLinkNow(this.clock)\n\t\t)\n\t\t\treturn { kind: \"inactive\" as const };\n\t\treturn { kind: \"active\" as const };\n\t}\n\t/** Only the exact consumed exchange may report provider failure. */\n\tasync failConsumed(value: unknown, config: unknown): Promise<boolean> {\n\t\tconst c = captureAuthLinkConfig(config),\n\t\t\ti = browserPin(value);\n\t\tif (!c?.enabled || !i) return false;\n\t\treturn this.atomic([\n\t\t\tsql(\n\t\t\t\t`UPDATE ${table} AS a SET state = 'failed',failure_reason = 'provider_failure',${scrub} WHERE ${configured} AND ${browserMatch} AND a.state = 'consumed' AND a.expires_at_ms > ?`,\n\t\t\t\t[...configValues(c), i.attemptId, i.stateHash, i.binderHash, authLinkNow(this.clock)],\n\t\t\t),\n\t\t\tassertOne,\n\t\t]);\n\t}\n\t/** Coordinator-local maintenance; config rotation/disable must not retain staging. */\n\tasync maintainExpired(\n\t\tcoordinatorId: unknown,\n\t\tlimit: unknown = AUTH_LINK_EXPIRE_BATCH_MAX,\n\t): Promise<number> {\n\t\tif (\n\t\t\t!isAuthControllerId(coordinatorId) ||\n\t\t\ttypeof limit !== \"number\" ||\n\t\t\t!Number.isInteger(limit) ||\n\t\t\tlimit < 1 ||\n\t\t\tlimit > AUTH_LINK_EXPIRE_BATCH_MAX\n\t\t)\n\t\t\treturn 0;\n\t\tconst now = authLinkNow(this.clock);\n\t\treturn this.backend.run(\n\t\t\tsql(\n\t\t\t\t`UPDATE ${table} SET state = 'expired',failure_reason = 'expired',${scrub} WHERE coordinator_id = ? AND state IN ('pending','browser_pending','consumed','verified','confirmed') AND expires_at_ms <= ? AND attempt_id IN (SELECT attempt_id FROM ${table} WHERE coordinator_id = ? AND state IN ('pending','browser_pending','consumed','verified','confirmed') AND expires_at_ms <= ? ORDER BY expires_at_ms,attempt_id LIMIT ?)`,\n\t\t\t\t[coordinatorId, now, coordinatorId, now, limit],\n\t\t\t),\n\t\t);\n\t}\n}\n\nfunction disconnectEffects(\n\tcoordinator: string,\n\tattempt: string,\n\tnow: number,\n\toptions: { connections: boolean; device?: boolean },\n): AuthLinkStatement[] {\n\tconst table = options.device ? ACCOUNT_UNLINK_TABLE : \"coordinator_account_change_attempts\";\n\tconst intent = options.device ? \"\" : \" AND a.intent = 'disconnect'\";\n\tconst columns = options.connections\n\t\t? [...CONNECTION_BIRTH_COLUMNS, \"signin_floor\"]\n\t\t: CONNECTION_BIRTH_COLUMNS;\n\tconst exactBirth = `${CONNECTION_ARCHIVED_CURRENT_MATCH_SQL}${options.connections ? \" AND h.signin_floor IS c.signin_floor\" : \"\"}`;\n\treturn [\n\t\tsql(\n\t\t\t`INSERT INTO ${history} (${columns.join(\",\")},original_rowid,ended_at_ms,end_attempt_id)\n SELECT ${columns.map((c) => `l.${c}`).join(\",\")},l.rowid,?,a.attempt_id FROM ${current} l JOIN ${table} a ON a.coordinator_id = l.coordinator_id AND a.target_link_id = l.link_id WHERE a.coordinator_id = ? AND a.attempt_id = ? AND a.state = 'committing'${intent}`,\n\t\t\t[now, coordinator, attempt],\n\t\t),\n\t\tassertOne,\n\t\tsql(\n\t\t\t`DELETE FROM ${current} AS c WHERE EXISTS (SELECT 1 FROM ${history} h WHERE h.coordinator_id = ? AND h.end_attempt_id = ? AND ${exactBirth})`,\n\t\t\t[coordinator, attempt],\n\t\t),\n\t\tassertOne,\n\t\tsql(\n\t\t\t`UPDATE coordinator_auth_sessions SET revoked_at_ms = ? WHERE coordinator_id = ? AND link_id = (SELECT target_link_id FROM ${table} WHERE coordinator_id = ? AND attempt_id = ?) AND revoked_at_ms IS NULL`,\n\t\t\t[now, coordinator, coordinator, attempt],\n\t\t),\n\t\tsql(\n\t\t\t`INSERT INTO ${orders} (coordinator_id,last_order) SELECT NULL,0 WHERE EXISTS (\n SELECT 1 FROM coordinator_auth_sessions s JOIN ${table} a ON a.coordinator_id = s.coordinator_id AND a.target_link_id = s.link_id\n WHERE a.coordinator_id = ? AND a.attempt_id = ? AND s.revoked_at_ms IS NULL)`,\n\t\t\t[coordinator, attempt],\n\t\t),\n\t\t...[\"coordinator_auth_account_profiles\", \"coordinator_auth_link_profiles\"].map((name) =>\n\t\t\tsql(\n\t\t\t\t`DELETE FROM ${name} WHERE coordinator_id = ? AND link_id = (SELECT target_link_id FROM ${table} WHERE coordinator_id = ? AND attempt_id = ?)`,\n\t\t\t\t[coordinator, coordinator, attempt],\n\t\t\t),\n\t\t),\n\t\tsql(\n\t\t\t`INSERT INTO ${orders} (coordinator_id,last_order) SELECT NULL,0 WHERE EXISTS (\n SELECT 1 FROM ${table} a WHERE a.coordinator_id = ? AND a.attempt_id = ? AND (\n EXISTS (SELECT 1 FROM coordinator_auth_account_profiles p WHERE p.coordinator_id = a.coordinator_id AND p.link_id = a.target_link_id)\n OR EXISTS (SELECT 1 FROM coordinator_auth_link_profiles p WHERE p.coordinator_id = a.coordinator_id AND p.link_id = a.target_link_id)))`,\n\t\t\t[coordinator, attempt],\n\t\t),\n\t];\n}\nfunction refreshEffects(coordinator: string, attempt: string): AuthLinkStatement[] {\n\t// Keep original birth metadata byte-for-byte; new provenance names the\n\t// management receipt. Never invent a session receipt or a fake birth attempt.\n\treturn [\n\t\tsql(\n\t\t\t`INSERT INTO coordinator_auth_link_profiles\n (coordinator_id,attempt_id,issuer,subject,auth_config_revision,browser_transaction_hash,link_id,verified_at_ms,display_name,email,email_verified,picture_url,source_change_attempt_id,source_order)\n SELECT l.coordinator_id,l.attempt_id,l.issuer,l.subject,l.auth_config_revision,b.browser_transaction_hash,l.link_id,b.oidc_verified_at_ms,a.display_name,a.email,a.email_verified,a.picture_url,a.attempt_id,a.browser_order\n FROM ${table} a JOIN ${current} l ON l.coordinator_id = a.coordinator_id AND l.link_id = a.target_link_id\n JOIN coordinator_auth_link_attempts b ON b.coordinator_id = l.coordinator_id AND b.attempt_id = l.attempt_id AND b.link_id = l.link_id\n WHERE a.coordinator_id = ? AND a.attempt_id = ? AND a.state = 'committing' AND a.intent = 'refresh'\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_profiles p WHERE p.coordinator_id = l.coordinator_id AND p.link_id = l.link_id AND p.source_order >= a.browser_order)\n ON CONFLICT(coordinator_id,link_id) DO UPDATE SET display_name = excluded.display_name,email = excluded.email,email_verified = excluded.email_verified,picture_url = excluded.picture_url,\n source_change_attempt_id = excluded.source_change_attempt_id,source_order = excluded.source_order\n WHERE coalesce(coordinator_auth_link_profiles.source_order,0) < excluded.source_order`,\n\t\t\t[coordinator, attempt],\n\t\t),\n\t\tsql(\n\t\t\t`INSERT INTO ${orders} (coordinator_id,last_order) SELECT NULL,0 WHERE changes() <> 1 AND NOT EXISTS (\n SELECT 1 FROM ${table} a WHERE a.coordinator_id = ? AND a.attempt_id = ? AND (\n EXISTS (SELECT 1 FROM coordinator_auth_link_profiles p WHERE p.coordinator_id = a.coordinator_id AND p.link_id = a.target_link_id AND p.source_order >= a.browser_order)\n OR EXISTS (SELECT 1 FROM coordinator_auth_account_profiles p WHERE p.coordinator_id = a.coordinator_id AND p.link_id = a.target_link_id AND p.source_order >= a.browser_order)))`,\n\t\t\t[coordinator, attempt],\n\t\t),\n\t];\n}\n","import type { CoordinatorAuthLinkConfig } from \"./coordinator-auth-link-contract.js\";\n\nexport const AUTH_BROWSER_TXN_TTL_MS = 600000;\nexport const AUTH_SIGNIN_TXN_WINDOW_MS = 3600000;\nexport const AUTH_SIGNIN_TXN_MAX_STARTS_PER_WINDOW = 1024;\nexport const AUTH_SIGNIN_TXN_MAX_RETAINED = 4096;\nexport const AUTH_BROWSER_TXN_MAINTENANCE_BATCH_MAX = 32;\nexport const AUTH_SIGNIN_TXN_PURGE_AGE_MS = 7200000;\nexport const AUTH_SIGNIN_TXN_PURGE_BATCH_MAX = 256;\n\nexport interface CoordinatorAuthBrowserConfig extends CoordinatorAuthLinkConfig {\n\tredirectUri: string;\n}\ninterface BrowserMaterials {\n\tstateHash: string;\n\tbinderHash: string;\n\tnonce: string;\n\tpkceVerifier: string;\n}\nexport type CoordinatorAuthBrowserTransactionStartInput = BrowserMaterials &\n\t({ purpose: \"signin\" } | { purpose: \"link\"; attemptId: string; browserStartHash?: string });\nexport interface CoordinatorAuthBrowserTransactionConsumeInput {\n\tstateHash: string;\n\tbinderHash: string;\n}\nexport type CoordinatorAuthBrowserTransactionPurpose = \"signin\" | \"link\" | \"owner_enroll\";\n/** Server-only routing hint, never authorization or consumption evidence. */\nexport interface CoordinatorAuthBrowserTransactionPurposeStore {\n\treadAuthBrowserTransactionPurpose(\n\t\tinput: CoordinatorAuthBrowserTransactionConsumeInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<CoordinatorAuthBrowserTransactionPurpose | null>;\n}\nexport interface CoordinatorAuthLinkBrowserTransactionResolveInput {\n\tattemptId: string;\n\tbinderHash: string;\n}\nexport type CoordinatorAuthBrowserTransactionError =\n\t| \"invalid_input\"\n\t| \"auth_config_changed\"\n\t| \"transaction_limited\"\n\t| \"transaction_conflict\"\n\t| \"attempt_unavailable\"\n\t| \"attempt_expired\"\n\t| \"transaction_unavailable\";\nexport interface CoordinatorAuthBrowserTransactionRejected {\n\tkind: \"rejected\";\n\terror: CoordinatorAuthBrowserTransactionError;\n}\nexport type CoordinatorAuthBrowserTransactionStartResult =\n\t| { kind: \"started\"; expiresAtMs: number }\n\t| { kind: \"rejected\"; error: \"clock_retention_blocked\" }\n\t| CoordinatorAuthBrowserTransactionRejected;\n/** Secrets are for the trusted SDK exchange caller only, never an HTTP or polling DTO. */\nexport type CoordinatorAuthBrowserTransactionConsumeResult =\n\t| ({ kind: \"consumed\"; browserTransactionHash: string; nonce: string; pkceVerifier: string } & (\n\t\t\t| { purpose: \"signin\" }\n\t\t\t| { purpose: \"link\"; attemptId: string }\n\t ))\n\t| CoordinatorAuthBrowserTransactionRejected;\nexport interface CoordinatorAuthBrowserTransactionScope {\n\tcoordinatorId: string;\n}\nexport interface CoordinatorAuthBrowserTransactionMaintenanceOptions {\n\tlimit?: number;\n}\nexport interface CoordinatorAuthSigninBrowserTransactionCancelInput {\n\tbinderHash: string;\n}\nexport type CoordinatorAuthSigninBrowserTransactionCancelResult =\n\t| { kind: \"cancelled\" }\n\t| { kind: \"unavailable\" }\n\t| { kind: \"rejected\"; error: \"invalid_input\" };\nexport interface CoordinatorAuthBrowserTransactionRetirementOptions {\n\t/** Omit unused options; explicit undefined values are rejected. */\n\tattemptId?: string;\n\tlimit?: number;\n}\nexport type CoordinatorAuthBrowserTransactionRetirementResult =\n\t| { kind: \"retired\"; processedCount: number; more: boolean }\n\t| { kind: \"rejected\"; error: \"invalid_input\" };\nexport type CoordinatorAuthBrowserTransactionMaintenanceResult =\n\t| { kind: \"maintained\"; processedCount: number; more: boolean }\n\t| { kind: \"rejected\"; error: \"invalid_input\" };\nexport type CoordinatorAuthSigninBrowserTransactionPurgeResult =\n\t| { kind: \"purged\"; processedCount: number; more: boolean }\n\t| { kind: \"rejected\"; error: \"invalid_input\" };\nexport interface CoordinatorAuthBrowserTransactionStore {\n\t/** Server-only binder lookup; never accepts a caller-selected attempt. */\n\treadAuthBrowserTransactionActivity(\n\t\tinput: { binderHash: string },\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<\n\t\t| { kind: \"active\" | \"inactive\" }\n\t\t| { kind: \"rejected\"; error: \"invalid_input\" | \"auth_config_changed\" }\n\t>;\n\tstartAuthBrowserTransaction(\n\t\tinput: CoordinatorAuthBrowserTransactionStartInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<CoordinatorAuthBrowserTransactionStartResult>;\n\tconsumeAuthBrowserTransaction(\n\t\tinput: CoordinatorAuthBrowserTransactionConsumeInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<CoordinatorAuthBrowserTransactionConsumeResult>;\n\tresolveAuthLinkBrowserTransaction(\n\t\tinput: CoordinatorAuthLinkBrowserTransactionResolveInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<{ browserTransactionHash: string } | null>;\n\tmaintainAuthBrowserTransactions(\n\t\tscope: CoordinatorAuthBrowserTransactionScope,\n\t\toptions?: CoordinatorAuthBrowserTransactionMaintenanceOptions,\n\t): Promise<CoordinatorAuthBrowserTransactionMaintenanceResult>;\n\tpurgeAuthSigninBrowserTransactions(\n\t\tscope: CoordinatorAuthBrowserTransactionScope,\n\t\toptions?: CoordinatorAuthBrowserTransactionMaintenanceOptions,\n\t): Promise<CoordinatorAuthSigninBrowserTransactionPurgeResult>;\n\tcancelAuthSigninBrowserTransaction(\n\t\tinput: CoordinatorAuthSigninBrowserTransactionCancelInput,\n\t\tscope: CoordinatorAuthBrowserTransactionScope,\n\t): Promise<CoordinatorAuthSigninBrowserTransactionCancelResult>;\n\tretireAuthBrowserTransactions(\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t\toptions?: CoordinatorAuthBrowserTransactionRetirementOptions,\n\t): Promise<CoordinatorAuthBrowserTransactionRetirementResult>;\n}\n\nexport const AUTH_BROWSER_TXN_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS coordinator_auth_browser_transactions (\n coordinator_id TEXT NOT NULL CHECK (length(coordinator_id) BETWEEN 1 AND 256),\n browser_transaction_hash TEXT NOT NULL CHECK (length(browser_transaction_hash) = 64 AND browser_transaction_hash NOT GLOB '*[^0-9a-f]*'),\n purpose TEXT NOT NULL CHECK (purpose IN ('signin','link','owner_enroll')),\n attempt_id TEXT CHECK (attempt_id IS NULL OR length(attempt_id) BETWEEN 1 AND 256),\n state_hash TEXT NOT NULL CHECK (length(state_hash) = 64 AND state_hash NOT GLOB '*[^0-9a-f]*'),\n binder_hash TEXT NOT NULL CHECK (length(binder_hash) = 64 AND binder_hash NOT GLOB '*[^0-9a-f]*'),\n issuer TEXT NOT NULL,\n auth_config_revision TEXT NOT NULL CHECK (length(auth_config_revision) = 64 AND auth_config_revision NOT GLOB '*[^0-9a-f]*'),\n redirect_uri TEXT NOT NULL,\n state TEXT NOT NULL CHECK (state IN ('pending','consumed','expired')),\n nonce TEXT CHECK (nonce IS NULL OR (length(nonce) BETWEEN 43 AND 128 AND nonce NOT GLOB '*[^A-Za-z0-9._~-]*')),\n pkce_verifier TEXT CHECK (pkce_verifier IS NULL OR (length(pkce_verifier) BETWEEN 43 AND 128 AND pkce_verifier NOT GLOB '*[^A-Za-z0-9._~-]*')),\n claim_token TEXT,\n created_at_ms INTEGER NOT NULL CHECK (typeof(created_at_ms) = 'integer' AND created_at_ms BETWEEN 0 AND 9007199254140991),\n expires_at_ms INTEGER NOT NULL CHECK (typeof(expires_at_ms) = 'integer' AND expires_at_ms > created_at_ms AND expires_at_ms <= created_at_ms + 600000),\n consumed_at_ms INTEGER CHECK (consumed_at_ms IS NULL OR (typeof(consumed_at_ms) = 'integer' AND consumed_at_ms >= created_at_ms AND consumed_at_ms < expires_at_ms AND consumed_at_ms <= 9007199254740991)),\n PRIMARY KEY (coordinator_id, browser_transaction_hash),\n UNIQUE (coordinator_id, state_hash),\n UNIQUE (coordinator_id, binder_hash),\n UNIQUE (coordinator_id, attempt_id),\n UNIQUE (coordinator_id, claim_token),\n CHECK ((purpose IN ('link','owner_enroll') AND attempt_id IS NOT NULL) OR (purpose = 'signin' AND attempt_id IS NULL)),\n CHECK ((state = 'pending' AND nonce IS NOT NULL AND pkce_verifier IS NOT NULL) OR (state <> 'pending' AND nonce IS NULL AND pkce_verifier IS NULL)),\n CHECK ((state = 'consumed' AND claim_token IS NOT NULL AND consumed_at_ms IS NOT NULL) OR (state <> 'consumed' AND claim_token IS NULL AND consumed_at_ms IS NULL))\n);\nCREATE INDEX IF NOT EXISTS idx_auth_browser_txn_purpose_created\n ON coordinator_auth_browser_transactions(coordinator_id, purpose, created_at_ms);\nCREATE INDEX IF NOT EXISTS idx_auth_browser_txn_state_expiry\n ON coordinator_auth_browser_transactions(coordinator_id, state, expires_at_ms);\nCREATE TABLE IF NOT EXISTS coordinator_auth_signin_purge_floors (\n coordinator_id TEXT NOT NULL PRIMARY KEY CHECK (length(coordinator_id) BETWEEN 1 AND 256),\n purged_through_created_at_ms INTEGER NOT NULL CHECK (typeof(purged_through_created_at_ms) = 'integer' AND purged_through_created_at_ms BETWEEN 0 AND 9007199254140991)\n);\n`;\n","import { AUTH_BROWSER_TXN_TTL_MS } from \"./coordinator-auth-browser-transaction-contract.js\";\nimport {\n\tdecodeCoordinatorAuthProof32 as decodeValue,\n\tencodeCoordinatorAuthProof32 as encodeBytes,\n\thashCoordinatorAuthProofBytes32,\n} from \"./coordinator-auth-proof.js\";\nimport { AUTH_SESSION_TTL_MS } from \"./coordinator-auth-session-contract.js\";\n\nexport type CookieKind = \"transaction\" | \"session\" | \"start\";\ndeclare const browserCookieSecretBrand: unique symbol;\nexport type BrowserCookieSecret = Readonly<{ [browserCookieSecretBrand]: true }>;\n\nexport const BROWSER_COOKIE_NAMES = Object.freeze({\n\ttransaction: \"__Host-codemem-auth-transaction\",\n\tsession: \"__Host-codemem-session\",\n\tstart: \"__Host-codemem-auth-start\",\n});\nexport const BROWSER_COOKIE_HEADER_MAX_BYTES = 8192;\nconst MAX_AGE_SECONDS = {\n\ttransaction: AUTH_BROWSER_TXN_TTL_MS / 1000,\n\tsession: AUTH_SESSION_TTL_MS / 1000,\n\tstart: AUTH_BROWSER_TXN_TTL_MS / 1000,\n};\nconst COOKIE_NAME = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\nconst COOKIE_VALUE =\n\t/^(?:[\\x21\\x23-\\x2B\\x2D-\\x3A\\x3C-\\x5B\\x5D-\\x7E]*|\"[\\x21\\x23-\\x2B\\x2D-\\x3A\\x3C-\\x5B\\x5D-\\x7E]*\")$/;\ntype CookieMaterial = Readonly<{\n\tkind: CookieKind;\n\tbytes: Uint8Array<ArrayBuffer>;\n\tencoded: string;\n}>;\nconst secrets = new WeakMap<BrowserCookieSecret, CookieMaterial>();\ntype InvalidCookie = { kind: \"invalid\"; error: \"cookie_duplicate\" | \"cookie_malformed\" };\nexport type BrowserCookieReadResult =\n\t| { kind: \"absent\" }\n\t| InvalidCookie\n\t| { kind: \"present\"; secret: BrowserCookieSecret; cookieHash: string };\n\nfunction validateKind(kind: CookieKind): void {\n\tif (kind !== \"transaction\" && kind !== \"session\" && kind !== \"start\") {\n\t\tthrow new Error(\"auth_browser_credential_invalid_input\");\n\t}\n}\n\nasync function hashBytes(bytes: Uint8Array<ArrayBuffer>): Promise<string> {\n\ttry {\n\t\treturn await hashCoordinatorAuthProofBytes32(bytes);\n\t} catch {\n\t\tthrow new Error(\"auth_browser_credential_crypto_failed\");\n\t}\n}\n\nfunction createSecret(material: CookieMaterial): BrowserCookieSecret {\n\tconst secret = Object.freeze({}) as BrowserCookieSecret;\n\tsecrets.set(secret, Object.freeze(material));\n\treturn secret;\n}\n\nfunction cookieHeader(kind: CookieKind, value: string, maxAge: number): string {\n\treturn `${BROWSER_COOKIE_NAMES[kind]}=${value}; Max-Age=${maxAge}; Path=/; Secure; HttpOnly; SameSite=Lax`;\n}\n\nexport async function issueBrowserCookie(\n\tkind: CookieKind,\n): Promise<{ secret: BrowserCookieSecret; cookieHash: string; setCookie: string }> {\n\tvalidateKind(kind);\n\tlet bytes: Uint8Array<ArrayBuffer>;\n\ttry {\n\t\tbytes = new Uint8Array(32);\n\t\tglobalThis.crypto.getRandomValues(bytes);\n\t} catch {\n\t\tthrow new Error(\"auth_browser_credential_entropy_failed\");\n\t}\n\tconst cookieHash = await hashBytes(bytes);\n\tconst encoded = encodeBytes(bytes);\n\treturn {\n\t\tsecret: createSecret({ kind, bytes, encoded }),\n\t\tcookieHash,\n\t\tsetCookie: cookieHeader(kind, encoded, MAX_AGE_SECONDS[kind]),\n\t};\n}\n\nexport function clearBrowserCookie(kind: CookieKind): string {\n\tvalidateKind(kind);\n\treturn cookieHeader(kind, \"\", 0);\n}\n\n/** Internal credential access only: never send this value through JSON or logs. */\nexport function browserCookieValue(secret: BrowserCookieSecret, expectedKind: CookieKind): string {\n\tvalidateKind(expectedKind);\n\tconst material = secrets.get(secret);\n\tif (!material || material.kind !== expectedKind) {\n\t\tthrow new Error(\"auth_browser_credential_invalid_input\");\n\t}\n\treturn material.encoded;\n}\n\n/**\n * Same-value header promotion only; the secret remains start-kind. Append only after\n * Origin/CSRF checks and durable unique-binder admission commit. No one-shot or\n * freshness proof: Max-Age is a browser hint, not server-side expiry enforcement.\n */\nexport function reissueStartCookieAsTransaction(secret: BrowserCookieSecret): string {\n\treturn cookieHeader(\n\t\t\"transaction\",\n\t\tbrowserCookieValue(secret, \"start\"),\n\t\tMAX_AGE_SECONDS.transaction,\n\t);\n}\n\nfunction trimOws(value: string): string {\n\tlet start = 0;\n\tlet end = value.length;\n\twhile (start < end && (value[start] === \" \" || value[start] === \"\\t\")) start++;\n\twhile (end > start && (value[end - 1] === \" \" || value[end - 1] === \"\\t\")) end--;\n\treturn value.slice(start, end);\n}\n\nfunction isValidHeader(header: string): boolean {\n\tif (header.length > BROWSER_COOKIE_HEADER_MAX_BYTES) return false;\n\tfor (const character of header) {\n\t\tconst code = character.charCodeAt(0);\n\t\tif (code === 9) continue;\n\t\tif (code < 32 || code > 126 || code === 44) return false;\n\t}\n\treturn true;\n}\n\nfunction knownCookieKind(name: string): CookieKind | undefined {\n\tconst lowerName = name.toLowerCase();\n\tif (lowerName === BROWSER_COOKIE_NAMES.transaction.toLowerCase()) return \"transaction\";\n\tif (lowerName === BROWSER_COOKIE_NAMES.session.toLowerCase()) return \"session\";\n\tif (lowerName === BROWSER_COOKIE_NAMES.start.toLowerCase()) return \"start\";\n\treturn undefined;\n}\n\nfunction parseCookies(header: string): Map<CookieKind, CookieMaterial> | InvalidCookie {\n\tconst cookies = new Map<CookieKind, CookieMaterial>();\n\tfor (const segment of header.split(\";\")) {\n\t\tconst pair = trimOws(segment);\n\t\tconst separator = pair.indexOf(\"=\");\n\t\tif (separator < 1) return { kind: \"invalid\", error: \"cookie_malformed\" };\n\t\tconst name = pair.slice(0, separator);\n\t\tconst encoded = pair.slice(separator + 1);\n\t\tif (!COOKIE_NAME.test(name) || !COOKIE_VALUE.test(encoded)) {\n\t\t\treturn { kind: \"invalid\", error: \"cookie_malformed\" };\n\t\t}\n\t\tconst kind = knownCookieKind(name);\n\t\tif (!kind) continue;\n\t\tif (cookies.has(kind)) return { kind: \"invalid\", error: \"cookie_duplicate\" };\n\t\tif (name !== BROWSER_COOKIE_NAMES[kind]) {\n\t\t\treturn { kind: \"invalid\", error: \"cookie_malformed\" };\n\t\t}\n\t\tconst bytes = decodeValue(encoded);\n\t\tif (!bytes) return { kind: \"invalid\", error: \"cookie_malformed\" };\n\t\tcookies.set(kind, { kind, bytes, encoded });\n\t}\n\treturn cookies;\n}\n\n/** A present cookie is not authentication; callers must look up its hash in the store. */\nexport async function readBrowserCookie(\n\tcookieHeader: unknown,\n\tkind: CookieKind,\n): Promise<BrowserCookieReadResult> {\n\tvalidateKind(kind);\n\tif (cookieHeader === null || cookieHeader === undefined) return { kind: \"absent\" };\n\tif (typeof cookieHeader !== \"string\") return { kind: \"invalid\", error: \"cookie_malformed\" };\n\t// For this ASCII-only header, string length is also its byte count.\n\tif (!isValidHeader(cookieHeader)) {\n\t\treturn { kind: \"invalid\", error: \"cookie_malformed\" };\n\t}\n\tif (!trimOws(cookieHeader)) return { kind: \"absent\" };\n\tconst cookies = parseCookies(cookieHeader);\n\tif (!(cookies instanceof Map)) return cookies;\n\tconst material = cookies.get(kind);\n\tif (!material) return { kind: \"absent\" };\n\tconst cookieHash = await hashBytes(material.bytes);\n\treturn { kind: \"present\", secret: createSecret(material), cookieHash };\n}\n","import type { CoordinatorAuthBrowserConfig } from \"./coordinator-auth-browser-transaction-contract.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport {\n\ttype BrowserCookieSecret,\n\tbrowserCookieValue,\n\ttype CookieKind,\n} from \"./coordinator-browser-credential.js\";\n\ndeclare const browserCsrfKeyBrand: unique symbol;\nexport type BrowserCsrfKey = Readonly<{ [browserCsrfKeyBrand]: true }>;\nexport interface BrowserCsrfScope {\n\tpublicOrigin: string;\n\tstore: Pick<CoordinatorAuthBrowserConfig, \"coordinatorId\" | \"revision\">;\n}\n\ntype CryptoKey = Awaited<ReturnType<typeof globalThis.crypto.subtle.importKey>>;\nconst keys = new WeakMap<BrowserCsrfKey, CryptoKey>();\nexport function isBrowserCsrfKey(value: unknown): value is BrowserCsrfKey {\n\treturn typeof value === \"object\" && value !== null && keys.has(value as BrowserCsrfKey);\n}\nconst TOKEN_PATTERN = /^[A-Za-z0-9_-]{85}[AQgw]$/;\nconst typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);\nconst typedArrayTag = Object.getOwnPropertyDescriptor(typedArrayPrototype, Symbol.toStringTag)?.get;\nconst typedArrayByteLength = Object.getOwnPropertyDescriptor(\n\ttypedArrayPrototype,\n\t\"byteLength\",\n)?.get;\n\nfunction invalidInput(): Error {\n\treturn new Error(\"auth_browser_csrf_invalid_input\");\n}\n\nfunction copyKeyBytes(raw: Uint8Array): Uint8Array<ArrayBuffer> {\n\tif (typedArrayTag?.call(raw) !== \"Uint8Array\" || typedArrayByteLength?.call(raw) !== 32) {\n\t\tthrow invalidInput();\n\t}\n\tconst copy = new Uint8Array(32);\n\tUint8Array.prototype.set.call(copy, raw);\n\treturn copy;\n}\n\nasync function importCopiedKey(bytes: Uint8Array<ArrayBuffer>): Promise<BrowserCsrfKey> {\n\ttry {\n\t\tconst cryptoKey = await globalThis.crypto.subtle.importKey(\n\t\t\t\"raw\",\n\t\t\tbytes,\n\t\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n\t\t\tfalse,\n\t\t\t[\"sign\", \"verify\"],\n\t\t);\n\t\tconst key = Object.freeze({}) as BrowserCsrfKey;\n\t\tkeys.set(key, cryptoKey);\n\t\treturn key;\n\t} catch {\n\t\tthrow new Error(\"auth_browser_csrf_crypto_failed\");\n\t}\n}\n\nexport function importBrowserCsrfKey(raw: Uint8Array): Promise<BrowserCsrfKey> {\n\tlet bytes: Uint8Array<ArrayBuffer>;\n\ttry {\n\t\tbytes = copyKeyBytes(raw);\n\t} catch {\n\t\treturn Promise.reject(invalidInput());\n\t}\n\t// Only the owned copy crosses the asynchronous boundary.\n\treturn importCopiedKey(bytes);\n}\n\nfunction ownData(value: unknown, name: string): unknown {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) throw invalidInput();\n\tconst descriptor = Object.getOwnPropertyDescriptor(value, name);\n\tif (!descriptor || !Object.hasOwn(descriptor, \"value\")) throw invalidInput();\n\treturn descriptor.value;\n}\n\nfunction validOrigin(value: unknown): value is string {\n\tif (typeof value !== \"string\" || /[\\\\\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(value)) return false;\n\tconst url = new URL(value);\n\treturn url.protocol === \"https:\" && url.origin === value && !url.username && !url.password;\n}\n\nfunction captureMessageFields(\n\tkey: BrowserCsrfKey,\n\tsecret: BrowserCookieSecret,\n\tpurpose: CookieKind,\n\tscope: BrowserCsrfScope,\n): { cryptoKey: CryptoKey; fields: string[] } {\n\ttry {\n\t\tconst cryptoKey = keys.get(key);\n\t\tif (!cryptoKey || (purpose !== \"transaction\" && purpose !== \"session\" && purpose !== \"start\")) {\n\t\t\tthrow invalidInput();\n\t\t}\n\t\tconst publicOrigin = ownData(scope, \"publicOrigin\");\n\t\tconst store = ownData(scope, \"store\");\n\t\tconst coordinatorId = ownData(store, \"coordinatorId\");\n\t\tconst revision = ownData(store, \"revision\");\n\t\tif (\n\t\t\t!validOrigin(publicOrigin) ||\n\t\t\t!isAuthControllerId(coordinatorId) ||\n\t\t\ttypeof revision !== \"string\" ||\n\t\t\trevision.length !== 64 ||\n\t\t\t!/^[a-f0-9]{64}$/.test(revision)\n\t\t) {\n\t\t\tthrow invalidInput();\n\t\t}\n\t\tconst encodedCookie = browserCookieValue(secret, purpose);\n\t\treturn {\n\t\t\tcryptoKey,\n\t\t\tfields: [\n\t\t\t\t\"codemem-browser-csrf-v1\",\n\t\t\t\tpurpose,\n\t\t\t\tcoordinatorId,\n\t\t\t\tpublicOrigin,\n\t\t\t\trevision,\n\t\t\t\tencodedCookie,\n\t\t\t],\n\t\t};\n\t} catch {\n\t\tthrow invalidInput();\n\t}\n}\n\nfunction encodeBytes(bytes: Uint8Array<ArrayBuffer>): string {\n\treturn btoa(String.fromCharCode(...bytes))\n\t\t.replaceAll(\"+\", \"-\")\n\t\t.replaceAll(\"/\", \"_\")\n\t\t.replace(/=+$/, \"\");\n}\n\nfunction decodeToken(value: unknown): Uint8Array<ArrayBuffer> | null {\n\tif (typeof value !== \"string\" || value.length !== 86 || !TOKEN_PATTERN.test(value)) return null;\n\ttry {\n\t\tconst binary = atob(`${value.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\")}==`);\n\t\tconst bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));\n\t\tif (bytes.length !== 64 || encodeBytes(bytes) !== value) return null;\n\t\treturn bytes;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Shape only: this does not authenticate the token or its browser session. */\nexport function isBrowserCsrfToken(value: unknown): value is string {\n\treturn decodeToken(value) !== null;\n}\n\nfunction messageBytes(fields: string[], nonce: Uint8Array<ArrayBuffer>): Uint8Array<ArrayBuffer> {\n\treturn new TextEncoder().encode(JSON.stringify([...fields, encodeBytes(nonce)]));\n}\n\nexport async function issueBrowserCsrfToken(\n\tkey: BrowserCsrfKey,\n\tsecret: BrowserCookieSecret,\n\tpurpose: CookieKind,\n\tscope: BrowserCsrfScope,\n): Promise<string> {\n\tconst { cryptoKey, fields } = captureMessageFields(key, secret, purpose, scope);\n\tconst nonce = new Uint8Array(32);\n\ttry {\n\t\tglobalThis.crypto.getRandomValues(nonce);\n\t} catch {\n\t\tthrow new Error(\"auth_browser_csrf_entropy_failed\");\n\t}\n\ttry {\n\t\tconst signature = await globalThis.crypto.subtle.sign(\n\t\t\t\"HMAC\",\n\t\t\tcryptoKey,\n\t\t\tmessageBytes(fields, nonce),\n\t\t);\n\t\tconst signatureLength = Object.getOwnPropertyDescriptor(\n\t\t\tArrayBuffer.prototype,\n\t\t\t\"byteLength\",\n\t\t)?.get;\n\t\tif (signatureLength?.call(signature) !== 32) throw new Error(\"auth_browser_csrf_crypto_failed\");\n\t\tconst mac = new Uint8Array(signature);\n\t\tif (mac.length !== 32) throw new Error(\"auth_browser_csrf_crypto_failed\");\n\t\tconst token = new Uint8Array(64);\n\t\ttoken.set(mac);\n\t\ttoken.set(nonce, 32);\n\t\treturn encodeBytes(token);\n\t} catch {\n\t\tthrow new Error(\"auth_browser_csrf_crypto_failed\");\n\t}\n}\n\n/**\n * A separate HMAC key for another purpose, derived from the CSRF key so no new\n * secret is needed. CSRF messages are JSON arrays, so a label that does not\n * start with \"[\" can never sign the same bytes as a token. Rotating the CSRF\n * key changes every derived key.\n */\nexport async function deriveBrowserCsrfSubkey(\n\tkey: BrowserCsrfKey,\n\tlabel: string,\n): Promise<CryptoKey> {\n\tconst cryptoKey = keys.get(key);\n\tif (!cryptoKey || !/^[a-z0-9][a-z0-9:-]{7,127}$/.test(label)) throw invalidInput();\n\tconst bytes = await globalThis.crypto.subtle.sign(\n\t\t\"HMAC\",\n\t\tcryptoKey,\n\t\tnew TextEncoder().encode(label),\n\t);\n\treturn globalThis.crypto.subtle.importKey(\n\t\t\"raw\",\n\t\tbytes,\n\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n\t\tfalse,\n\t\t[\"sign\"],\n\t);\n}\n\n/** Callers must also require a live store lookup before protecting an authenticated action. */\nexport async function verifyBrowserCsrfToken(\n\tkey: BrowserCsrfKey,\n\tsecret: BrowserCookieSecret,\n\tpurpose: CookieKind,\n\tscope: BrowserCsrfScope,\n\ttoken: unknown,\n): Promise<boolean> {\n\ttry {\n\t\tconst payload = decodeToken(token);\n\t\tif (!payload) return false;\n\t\tconst { cryptoKey, fields } = captureMessageFields(key, secret, purpose, scope);\n\t\treturn await globalThis.crypto.subtle.verify(\n\t\t\t\"HMAC\",\n\t\t\tcryptoKey,\n\t\t\tpayload.slice(0, 32),\n\t\t\tmessageBytes(fields, payload.slice(32)),\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n","import { COORDINATOR_AUTH_STYLE as STYLE } from \"./coordinator-auth-browser-style.js\";\nimport { isCoordinatorAccountIssuer } from \"./coordinator-auth-contract.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport { parseCoordinatorAuthLoopback } from \"./coordinator-auth-loopback.js\";\nimport { decodeCoordinatorAuthProof32 } from \"./coordinator-auth-proof.js\";\nimport { isBrowserCsrfToken } from \"./coordinator-browser-csrf.js\";\n\nexport const AUTH_BROWSER_FORM_ACTIONS = Object.freeze({\n\tsignIn: \"/auth/sign-in\",\n\tstartLink: \"/auth/link/start\",\n\tconfirmLink: \"/auth/link/confirm\",\n\tcancelLink: \"/auth/link/cancel\",\n\tcompleteLink: \"/auth/link/complete\",\n\tsignOut: \"/auth/logout\",\n});\n\n// A conservative client policy, not a provider guarantee about picture hosts.\nexport const AUTH_BROWSER_AVATAR_HOSTS = Object.freeze({\n\t\"https://accounts.google.com\": Object.freeze([\"lh3.googleusercontent.com\"]),\n});\n\nexport interface CoordinatorAccountProfileView {\n\ttitle: string;\n\temail?: string;\n\temailNote?: string;\n\tpictureUrl?: string;\n\tinitials: string;\n}\n\nexport interface CoordinatorAuthBrowserEntity {\n\tid: string;\n\tlabel?: string;\n}\n\nexport interface CoordinatorAuthLinkConfirmPageInput {\n\tprofile?: unknown;\n\tissuer: string;\n\tidentity: CoordinatorAuthBrowserEntity;\n\tdevice: CoordinatorAuthBrowserEntity;\n\tgroup?: CoordinatorAuthBrowserEntity;\n\tattemptId: string;\n\tcsrfToken: string;\n}\n\nexport interface CoordinatorAuthCurrentAccountPageInput {\n\tprofile?: unknown;\n\tissuer: string;\n\tidentity: CoordinatorAuthBrowserEntity;\n\tcsrfToken: string;\n}\n\nexport interface CoordinatorAuthSigninPageInput {\n\tcsrfToken: string;\n}\n\nexport interface CoordinatorAuthLinkStartPageInput {\n\tattemptId: string;\n\tstartCode: string;\n\tcsrfToken: string;\n}\n\nexport interface CoordinatorAuthSigninContinuePageInput {\n\tauthorizationUrl: string;\n}\n\nexport type CoordinatorAuthLinkCompletionPageInput =\n\t| { attemptId: string; state: \"waiting\" }\n\t| { attemptId: string; state: \"ready\"; csrfToken: string };\n\nexport interface CoordinatorAuthLinkCompletionHopPageInput {\n\tdestination: string;\n\tattemptId: string;\n\tcompletionSecret: string;\n}\n\nexport interface CoordinatorAuthBrowserPage {\n\tbody: string;\n\theaders: Record<string, string>;\n}\n\nconst GOOGLE_ISSUER = \"https://accounts.google.com\";\nconst INVALID_INPUT = \"auth_browser_view_invalid_input\";\nconst CONTROLS = /[\\p{Cc}\\p{Cf}\\p{Cs}]/u;\nconst SENSITIVE_AUTHORIZATION_KEYS = new Set([\n\t\"code\",\n\t\"code_verifier\",\n\t\"client_secret\",\n\t\"access_token\",\n\t\"refresh_token\",\n\t\"id_token\",\n]);\nconst START_SUBMIT_SCRIPT = \"document.querySelector('form').requestSubmit();\";\n\nfunction invalidInput(): never {\n\tthrow new Error(INVALID_INPUT);\n}\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (prototype !== Object.prototype && prototype !== null) return undefined;\n\treturn value as Record<string, unknown>;\n}\n\nfunction ownData(\n\tvalue: Record<string, unknown>,\n\tkey: string,\n\toptions: { rejectAccessor?: boolean } = {},\n): unknown {\n\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\tif (!descriptor) return undefined;\n\tif (!Object.hasOwn(descriptor, \"value\")) {\n\t\tif (options.rejectAccessor) invalidInput();\n\t\treturn undefined;\n\t}\n\treturn descriptor.value;\n}\n\nfunction displayText(value: unknown, limit: number): string | undefined {\n\tif (typeof value !== \"string\" || value.length > limit || CONTROLS.test(value)) return undefined;\n\tif (!value || value !== value.trim()) return undefined;\n\treturn value;\n}\n\nfunction capturePageField(input: unknown, key: string): unknown {\n\ttry {\n\t\tconst data = record(input);\n\t\tif (!data) return invalidInput();\n\t\treturn ownData(data, key, { rejectAccessor: true });\n\t} catch {\n\t\treturn invalidInput();\n\t}\n}\n\nfunction captureSigninCsrf(input: unknown): string {\n\tconst csrfToken = capturePageField(input, \"csrfToken\");\n\t// Shape validation only; the controller verifies the token before starting sign-in.\n\tif (!isBrowserCsrfToken(csrfToken)) return invalidInput();\n\treturn csrfToken;\n}\n\nfunction captureAuthorizationUrl(input: unknown): string {\n\ttry {\n\t\tconst text = displayText(capturePageField(input, \"authorizationUrl\"), 8192);\n\t\tif (!text || text.includes(\"\\\\\") || text.includes(\"#\")) return invalidInput();\n\t\tconst url = new URL(text);\n\t\tif (\n\t\t\turl.href !== text ||\n\t\t\turl.protocol !== \"https:\" ||\n\t\t\turl.origin !== GOOGLE_ISSUER ||\n\t\t\turl.username ||\n\t\t\turl.password ||\n\t\t\turl.port ||\n\t\t\turl.hash\n\t\t)\n\t\t\treturn invalidInput();\n\t\tfor (const name of url.searchParams.keys()) {\n\t\t\tif (SENSITIVE_AUTHORIZATION_KEYS.has(name.toLowerCase())) return invalidInput();\n\t\t}\n\t\treturn text;\n\t} catch {\n\t\treturn invalidInput();\n\t}\n}\n\nfunction pictureUrl(value: unknown, issuer: string): string | undefined {\n\tconst text = displayText(value, 2048);\n\tif (!text || issuer !== GOOGLE_ISSUER || text.includes(\"\\\\\") || text.includes(\"#\")) return;\n\ttry {\n\t\tconst url = new URL(text);\n\t\tif (\n\t\t\turl.protocol !== \"https:\" ||\n\t\t\turl.username ||\n\t\t\turl.password ||\n\t\t\turl.port ||\n\t\t\t!AUTH_BROWSER_AVATAR_HOSTS[GOOGLE_ISSUER].includes(url.hostname)\n\t\t)\n\t\t\treturn;\n\t\treturn url.href;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction initialsFor(name: string | undefined): string {\n\tif (!name) return \"\";\n\tconst words = name.split(/\\s+/u);\n\tconst chosen = words.length > 1 ? [words[0], words[words.length - 1]] : [words[0]];\n\tconst segmenter = new Intl.Segmenter(\"en\", { granularity: \"grapheme\" });\n\tconst initials: string[] = [];\n\tfor (const word of chosen) {\n\t\tif (!word) continue;\n\t\tconst grapheme = segmenter.segment(word)[Symbol.iterator]().next().value?.segment;\n\t\tif (!grapheme || !/^[\\p{L}\\p{N}]/u.test(grapheme) || [...grapheme].length > 4) continue;\n\t\tconst upper = grapheme.toUpperCase();\n\t\tconst segments = [...segmenter.segment(upper)];\n\t\tif (segments.length !== 1 || [...upper].length > 4 || CONTROLS.test(upper)) continue;\n\t\tinitials.push(upper);\n\t}\n\treturn initials.join(\"\");\n}\n\n/** Presentation metadata only; names and email never confer account authority. */\nexport function projectAccountProfileView(\n\tprofile: unknown,\n\tissuer: string,\n): CoordinatorAccountProfileView {\n\tconst fallback = issuer === GOOGLE_ISSUER ? \"Google account\" : \"Linked account\";\n\ttry {\n\t\tconst data = record(profile);\n\t\tif (!data) return { title: fallback, initials: \"\" };\n\t\tconst name = displayText(ownData(data, \"displayName\"), 256);\n\t\tconst email = displayText(ownData(data, \"email\"), 320);\n\t\tconst view: CoordinatorAccountProfileView = {\n\t\t\ttitle: name ?? email ?? fallback,\n\t\t\tinitials: initialsFor(name),\n\t\t};\n\t\tif (email) {\n\t\t\tview.email = email;\n\t\t\tif (ownData(data, \"emailVerified\") !== true)\n\t\t\t\tview.emailNote = \"Email not verified by provider\";\n\t\t}\n\t\tconst picture = pictureUrl(ownData(data, \"pictureUrl\"), issuer);\n\t\tif (picture) view.pictureUrl = picture;\n\t\treturn view;\n\t} catch {\n\t\treturn { title: fallback, initials: \"\" };\n\t}\n}\n\nexport function escapeHtml(value: string): string {\n\treturn value\n\t\t.replace(/&/g, \"&amp;\")\n\t\t.replace(/</g, \"&lt;\")\n\t\t.replace(/>/g, \"&gt;\")\n\t\t.replace(/\"/g, \"&quot;\")\n\t\t.replace(/'/g, \"&#39;\");\n}\n\nfunction entity(value: unknown, fallback: string): CoordinatorAuthBrowserEntity {\n\tconst data = record(value);\n\tif (!data) return invalidInput();\n\tconst id = ownData(data, \"id\", { rejectAccessor: true });\n\tif (!isAuthControllerId(id)) return invalidInput();\n\treturn {\n\t\tid,\n\t\tlabel: displayText(ownData(data, \"label\", { rejectAccessor: true }), 256) ?? fallback,\n\t};\n}\n\nfunction capture(input: unknown): {\n\tdata: Record<string, unknown>;\n\tissuer: string;\n\tidentity: CoordinatorAuthBrowserEntity;\n\tcsrfToken: string;\n\tprofile: CoordinatorAccountProfileView;\n} {\n\ttry {\n\t\tconst data = record(input);\n\t\tif (!data) return invalidInput();\n\t\tconst issuer = ownData(data, \"issuer\", { rejectAccessor: true });\n\t\tconst csrfToken = ownData(data, \"csrfToken\", { rejectAccessor: true });\n\t\tif (!isCoordinatorAccountIssuer(issuer) || !isBrowserCsrfToken(csrfToken))\n\t\t\treturn invalidInput();\n\t\treturn {\n\t\t\tdata,\n\t\t\tissuer,\n\t\t\tcsrfToken,\n\t\t\tidentity: entity(ownData(data, \"identity\", { rejectAccessor: true }), \"Identity\"),\n\t\t\tprofile: projectAccountProfileView(\n\t\t\t\townData(data, \"profile\", { rejectAccessor: true }),\n\t\t\t\tissuer,\n\t\t\t),\n\t\t};\n\t} catch {\n\t\treturn invalidInput();\n\t}\n}\n\nexport function profileMarkup(profile: CoordinatorAccountProfileView): string {\n\tlet image = \"\";\n\tif (profile.pictureUrl)\n\t\timage = `<img src=\"${escapeHtml(profile.pictureUrl)}\" alt=\"\" referrerpolicy=\"no-referrer\" loading=\"lazy\" decoding=\"async\">`;\n\tlet details = \"\";\n\tif (profile.email) details += `<p>${escapeHtml(profile.email)}</p>`;\n\tif (profile.emailNote) details += `<p class=\"note\">${escapeHtml(profile.emailNote)}</p>`;\n\treturn `<section class=\"profile\" aria-label=\"Account profile\"><span class=\"avatar\"><span class=\"initials\" aria-hidden=\"true\">${escapeHtml(profile.initials)}</span>${image}</span><div class=\"profile-text\"><h2>${escapeHtml(profile.title)}</h2>${details}</div></section>`;\n}\n\nexport function entityMarkup(value: CoordinatorAuthBrowserEntity, heading: string): string {\n\treturn `<dt>${escapeHtml(heading)}</dt><dd>${escapeHtml(value.label ?? heading)}<br><code>${escapeHtml(value.id)}</code></dd>`;\n}\n\nexport function form(\n\taction: string,\n\tcsrf: string,\n\tlabel: string,\n\toptions: { attemptId?: string; startCode?: string; secondary?: boolean } = {},\n): string {\n\tlet fields = `<input type=\"hidden\" name=\"csrf\" value=\"${escapeHtml(csrf)}\">`;\n\tif (options.attemptId)\n\t\tfields += `<input type=\"hidden\" name=\"attempt_id\" value=\"${escapeHtml(options.attemptId)}\">`;\n\tif (options.startCode)\n\t\tfields += `<input type=\"hidden\" name=\"start_code\" value=\"${escapeHtml(options.startCode)}\">`;\n\tconst className = options.secondary ? ' class=\"secondary\"' : \"\";\n\treturn `<form method=\"post\" action=\"${escapeHtml(action)}\">${fields}<button type=\"submit\"${className}>${escapeHtml(label)}</button></form>`;\n}\n\nexport async function buildPage(\n\ttitle: string,\n\tcontent: string,\n\tissuer?: string,\n\toptions: {\n\t\treferrerPolicy?: \"no-referrer\" | \"same-origin\";\n\t\trefreshUrl?: string;\n\t\tautoSubmit?: boolean;\n\t} = {},\n): Promise<CoordinatorAuthBrowserPage> {\n\ttry {\n\t\tconst digest = await globalThis.crypto.subtle.digest(\n\t\t\t\"SHA-256\",\n\t\t\tnew TextEncoder().encode(STYLE),\n\t\t);\n\t\tconst hash = btoa(String.fromCharCode(...new Uint8Array(digest)));\n\t\tlet script = \"\";\n\t\tlet scriptPolicy = \"\";\n\t\tif (options.autoSubmit) {\n\t\t\tconst scriptDigest = await globalThis.crypto.subtle.digest(\n\t\t\t\t\"SHA-256\",\n\t\t\t\tnew TextEncoder().encode(START_SUBMIT_SCRIPT),\n\t\t\t);\n\t\t\tconst scriptHash = btoa(String.fromCharCode(...new Uint8Array(scriptDigest)));\n\t\t\tscript = `<script>${START_SUBMIT_SCRIPT}</script>`;\n\t\t\tscriptPolicy = `; script-src 'sha256-${scriptHash}'`;\n\t\t}\n\t\tconst refresh = options.refreshUrl\n\t\t\t? `<meta http-equiv=\"refresh\" content=\"0;url=${escapeHtml(options.refreshUrl)}\">`\n\t\t\t: \"\";\n\t\tlet images = \"'none'\";\n\t\tif (issuer === GOOGLE_ISSUER)\n\t\t\timages = AUTH_BROWSER_AVATAR_HOSTS[GOOGLE_ISSUER].map((host) => `https://${host}`).join(\" \");\n\t\treturn {\n\t\t\tbody: `<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><meta name=\"referrer\" content=\"${options.referrerPolicy ?? \"no-referrer\"}\">${refresh}<title>${escapeHtml(title)} · Codemem</title><style>${STYLE}</style></head><body><main><p class=\"brand\">codemem</p>${content}</main>${script}</body></html>`,\n\t\t\theaders: {\n\t\t\t\t\"Content-Type\": \"text/html;charset=utf-8\",\n\t\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\t\"Referrer-Policy\": options.referrerPolicy ?? \"no-referrer\",\n\t\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\t\t\"X-Frame-Options\": \"DENY\",\n\t\t\t\t\"Content-Security-Policy\": `default-src 'none'; style-src 'sha256-${hash}'; img-src ${images}; form-action 'self'; base-uri 'none'; frame-ancestors 'none'${scriptPolicy}`,\n\t\t\t},\n\t\t};\n\t} catch {\n\t\tthrow new Error(\"auth_browser_view_render_failed\");\n\t}\n}\n\n/** Caller releases this secret-bearing page only after confirmation commits. */\nexport async function renderAuthLinkCompletionHopPage(\n\tinput: CoordinatorAuthLinkCompletionHopPageInput,\n): Promise<CoordinatorAuthBrowserPage> {\n\tlet href: string;\n\ttry {\n\t\tconst data = record(input);\n\t\tif (!data) return invalidInput();\n\t\tconst destination = ownData(data, \"destination\", { rejectAccessor: true });\n\t\tconst attemptId = ownData(data, \"attemptId\", { rejectAccessor: true });\n\t\tconst completionSecret = ownData(data, \"completionSecret\", { rejectAccessor: true });\n\t\tconst parsed = parseCoordinatorAuthLoopback(destination);\n\t\tif (\n\t\t\t!parsed.ok ||\n\t\t\t!isAuthControllerId(attemptId) ||\n\t\t\ttypeof completionSecret !== \"string\" ||\n\t\t\tcompletionSecret.length !== 43 ||\n\t\t\t!/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/.test(completionSecret)\n\t\t)\n\t\t\treturn invalidInput();\n\t\t// Concatenation preserves the saved literal, including an explicit :80.\n\t\thref = `${parsed.destination}?attempt_id=${encodeURIComponent(attemptId)}&completion=${completionSecret}`;\n\t} catch {\n\t\treturn invalidInput();\n\t}\n\treturn buildPage(\n\t\t\"Finishing account link\",\n\t\t`<h1>Finishing account link…</h1><p>Returning to Codemem on this computer. If nothing happens, continue below.</p><p class=\"note\">Do not share this link.</p><div class=\"actions\"><a class=\"link\" href=\"${escapeHtml(href)}\" referrerpolicy=\"no-referrer\" rel=\"noreferrer\">Continue on this computer</a></div>`,\n\t\tundefined,\n\t\t{ refreshUrl: href },\n\t);\n}\n\n/** Presentation only; completion still requires live browser binding and device finalization. */\nexport async function renderAuthLinkCompletionPage(\n\tinput: CoordinatorAuthLinkCompletionPageInput,\n): Promise<CoordinatorAuthBrowserPage> {\n\tconst attemptId = capturePageField(input, \"attemptId\");\n\tconst state = capturePageField(input, \"state\");\n\tif (!isAuthControllerId(attemptId)) return invalidInput();\n\tif (state === \"waiting\") {\n\t\tconst href = `${AUTH_BROWSER_FORM_ACTIONS.completeLink}?attempt_id=${encodeURIComponent(attemptId)}`;\n\t\treturn buildPage(\n\t\t\t\"Waiting for this computer\",\n\t\t\t`<h1>Waiting for this computer</h1><p>Finish linking in the Codemem terminal, then check again.</p><div class=\"actions\"><a class=\"link\" href=\"${escapeHtml(href)}\" rel=\"noreferrer\" referrerpolicy=\"no-referrer\">Check again</a></div>`,\n\t\t);\n\t}\n\tif (state !== \"ready\") return invalidInput();\n\tconst csrfToken = capturePageField(input, \"csrfToken\");\n\tif (!isBrowserCsrfToken(csrfToken)) return invalidInput();\n\treturn buildPage(\n\t\t\"Finish linking\",\n\t\t`<h1>Finish linking</h1><p>Your computer confirmed the link. Finish to continue to your account. If you are already signed in, your current session stays unchanged. Sign out first to switch accounts.</p><div class=\"actions\">${form(AUTH_BROWSER_FORM_ACTIONS.completeLink, csrfToken, \"Finish linking\", { attemptId })}</div>`,\n\t\tundefined,\n\t\t{ referrerPolicy: \"same-origin\" },\n\t);\n}\n\n/** Private handoff code stays in hidden form data, never visible copy or provider URLs. */\nexport async function renderAuthLinkStartPage(\n\tinput: CoordinatorAuthLinkStartPageInput,\n): Promise<CoordinatorAuthBrowserPage> {\n\tconst attemptId = capturePageField(input, \"attemptId\");\n\tconst startCode = capturePageField(input, \"startCode\");\n\tconst csrfToken = captureSigninCsrf(input);\n\tif (\n\t\t!isAuthControllerId(attemptId) ||\n\t\ttypeof startCode !== \"string\" ||\n\t\t!decodeCoordinatorAuthProof32(startCode)\n\t)\n\t\treturn invalidInput();\n\treturn buildPage(\n\t\t\"Link this device\",\n\t\t`<h1>Connecting to Google…</h1><p>You’ll choose an account and confirm it before linking. Linking does not change project access.</p><p class=\"note\">If nothing happens, continue below. Do not share this page.</p><div class=\"actions\">${form(AUTH_BROWSER_FORM_ACTIONS.startLink, csrfToken, \"Continue with Google\", { attemptId, startCode })}</div>`,\n\t\tundefined,\n\t\t{ referrerPolicy: \"same-origin\", autoSubmit: true },\n\t);\n}\n\nexport async function renderAuthSigninPage(\n\tinput: CoordinatorAuthSigninPageInput,\n): Promise<CoordinatorAuthBrowserPage> {\n\tconst csrfToken = captureSigninCsrf(input);\n\treturn buildPage(\n\t\t\"Sign in\",\n\t\t`<h1>Sign in</h1><p>Sign in to manage your coordinator account.</p><p>Signing in does not enroll a device or change project access.</p><div class=\"actions\">${form(AUTH_BROWSER_FORM_ACTIONS.signIn, csrfToken, \"Sign in with Google\")}</div>`,\n\t\tundefined,\n\t\t{ referrerPolicy: \"same-origin\" },\n\t);\n}\n\n/**\n * Only pass a trusted SDK-produced URL, never a request-nominated URL.\n * The origin and known-key checks protect the anchor, not the OAuth protocol;\n * the denylist cannot detect arbitrary secret values in other parameters.\n */\nexport async function renderAuthSigninContinuePage(\n\tinput: CoordinatorAuthSigninContinuePageInput,\n): Promise<CoordinatorAuthBrowserPage> {\n\tconst authorizationUrl = captureAuthorizationUrl(input);\n\treturn buildPage(\n\t\t\"Continue sign-in\",\n\t\t`<h1>Continue sign-in</h1><div class=\"actions\"><a class=\"link\" href=\"${escapeHtml(authorizationUrl)}\" referrerpolicy=\"no-referrer\" rel=\"noreferrer\">Continue to Google</a></div>`,\n\t\tundefined,\n\t\t{ refreshUrl: authorizationUrl },\n\t);\n}\n\nexport async function renderAuthLinkConfirmPage(\n\tinput: CoordinatorAuthLinkConfirmPageInput,\n): Promise<CoordinatorAuthBrowserPage> {\n\tconst captured = capture(input);\n\tlet device: CoordinatorAuthBrowserEntity;\n\tlet group: CoordinatorAuthBrowserEntity | undefined;\n\tlet attemptId: string;\n\ttry {\n\t\tdevice = entity(ownData(captured.data, \"device\", { rejectAccessor: true }), \"Device\");\n\t\tconst groupValue = ownData(captured.data, \"group\", { rejectAccessor: true });\n\t\tif (groupValue !== undefined) group = entity(groupValue, \"Group\");\n\t\tconst attempt = ownData(captured.data, \"attemptId\", { rejectAccessor: true });\n\t\tif (!isAuthControllerId(attempt)) return invalidInput();\n\t\tattemptId = attempt;\n\t} catch {\n\t\treturn invalidInput();\n\t}\n\tlet entities = entityMarkup(captured.identity, \"Identity\") + entityMarkup(device, \"Device\");\n\tif (group) entities += entityMarkup(group, \"Group\");\n\tconst actions =\n\t\tform(AUTH_BROWSER_FORM_ACTIONS.confirmLink, captured.csrfToken, \"Link account\", { attemptId }) +\n\t\tform(AUTH_BROWSER_FORM_ACTIONS.cancelLink, captured.csrfToken, \"Cancel linking\", {\n\t\t\tattemptId,\n\t\t\tsecondary: true,\n\t\t});\n\treturn buildPage(\n\t\t\"Link account\",\n\t\t`<h1>Link account</h1>${profileMarkup(captured.profile)}<section aria-label=\"Link details\"><h2>Link details</h2><dl>${entities}</dl><p>Linking this account does not change project sharing, memories, or device keys.</p></section><p>Only confirm if you started linking on this computer. Do not share the link used to start this request.</p><div class=\"actions\">${actions}</div>`,\n\t\tcaptured.issuer,\n\t\t{ referrerPolicy: \"same-origin\" },\n\t);\n}\n\nexport async function renderCurrentAccountPage(\n\tinput: CoordinatorAuthCurrentAccountPageInput,\n): Promise<CoordinatorAuthBrowserPage> {\n\tconst captured = capture(input);\n\treturn buildPage(\n\t\t\"Account\",\n\t\t`<p class=\"eyebrow\">Signed in</p><h1>Account</h1>${profileMarkup(captured.profile)}<section aria-label=\"Identity\"><h2>Identity</h2><dl>${entityMarkup(captured.identity, \"Identity\")}</dl></section><div class=\"actions\">${form(AUTH_BROWSER_FORM_ACTIONS.signOut, captured.csrfToken, \"Sign out\")}</div>`,\n\t\tcaptured.issuer,\n\t\t{ referrerPolicy: \"same-origin\" },\n\t);\n}\n\nexport async function renderAuthBrowserNotice(\n\tkind:\n\t\t| \"expired\"\n\t\t| \"unavailable\"\n\t\t| \"signed_out\"\n\t\t| \"link_cancelled\"\n\t\t| \"signin_in_progress\"\n\t\t| \"signin_unavailable\"\n\t\t| \"auth_unavailable\",\n): Promise<CoordinatorAuthBrowserPage> {\n\tlet title: string;\n\tlet content: string;\n\tswitch (kind) {\n\t\tcase \"link_cancelled\":\n\t\t\ttitle = \"Linking cancelled\";\n\t\t\tcontent =\n\t\t\t\t\"<p>No account was linked in this attempt. Return to your terminal to start again.</p>\";\n\t\t\tbreak;\n\t\tcase \"auth_unavailable\":\n\t\t\ttitle = \"Sign-in or linking unavailable\";\n\t\t\tcontent = \"<p>Return to the flow you started and try again.</p>\";\n\t\t\tbreak;\n\t\tcase \"signin_in_progress\":\n\t\t\ttitle = \"Sign-in already in progress\";\n\t\t\tcontent = \"<p>Finish the open sign-in or account-link flow before starting another.</p>\";\n\t\t\tbreak;\n\t\tcase \"signin_unavailable\":\n\t\t\ttitle = \"Sign-in unavailable\";\n\t\t\tcontent =\n\t\t\t\t'<p>Sign-in is unavailable. Try again.</p><div class=\"actions\"><a class=\"link\" href=\"/auth/sign-in\">Sign in</a></div>';\n\t\t\tbreak;\n\t\tcase \"expired\":\n\t\t\ttitle = \"Link expired\";\n\t\t\tcontent =\n\t\t\t\t\"<p>This account link has expired. Return to your terminal and start linking again.</p>\";\n\t\t\tbreak;\n\t\tcase \"unavailable\":\n\t\t\ttitle = \"Account linking unavailable\";\n\t\t\tcontent =\n\t\t\t\t\"<p>Account linking is unavailable. Return to your terminal and start linking again.</p>\";\n\t\t\tbreak;\n\t\tcase \"signed_out\":\n\t\t\ttitle = \"Signed out\";\n\t\t\tcontent =\n\t\t\t\t'<p>You are signed out.</p><div class=\"actions\"><a class=\"link\" href=\"/auth/sign-in\">Sign in</a></div>';\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn invalidInput();\n\t}\n\treturn buildPage(title, `<h1>${escapeHtml(title)}</h1>${content}`);\n}\n","import { CONNECTION_RELINK_ELIGIBLE_SQL } from \"./coordinator-account-connection-link.js\";\nimport { connectionProfileColumns } from \"./coordinator-account-connection-session.js\";\nimport { projectAccountProfileView } from \"./coordinator-auth-browser-view.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport {\n\tAUTH_DEVICE_CLAIM_CURRENT_SUBJECT_COMPATIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_ELIGIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_INPUT_SQL,\n\tAUTH_DEVICE_CLAIM_LEGACY_COMPATIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_REQUESTER_ATTESTATION_COMPATIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_REQUESTER_INVITE_COMPATIBLE_SQL,\n\tAUTH_DEVICE_CLAIM_REQUESTER_LINK_COMPATIBLE_SQL,\n\ttype CoordinatorDeviceClaimReadiness,\n\ttype CoordinatorDeviceClaimReadinessInput,\n\tcaptureDeviceClaimEligibility,\n} from \"./coordinator-auth-device-claim-eligibility.js\";\nimport { AUTH_CURRENT_LEGACY_ASSIGNMENT_SQL } from \"./coordinator-auth-legacy-assignment.js\";\nimport {\n\tAUTH_LINK_AUTHORITY_COLUMNS,\n\tAUTH_LINK_CONTROLLER_SOURCE_SQL,\n\ttype AuthLinkBackend,\n\tauthLinkControllerSourceValues,\n\tauthLinkNow,\n\tcaptureAuthLinkConfig,\n\tcaptureAuthLinkSigner,\n} from \"./coordinator-auth-link.js\";\nimport type { CoordinatorAccountLinkStatusV2 } from \"./coordinator-auth-link-authority.js\";\nimport type {\n\tCoordinatorAuthLinkConfig,\n\tCoordinatorAuthLinkSigner,\n} from \"./coordinator-auth-link-contract.js\";\nimport {\n\tauthAccountLinkProvenanceSql,\n\tauthClaimGenesisSql,\n\tauthDeviceClaimProvenanceSql,\n} from \"./coordinator-auth-link-provenance.js\";\nimport { authPersistenceError } from \"./coordinator-auth-schema.js\";\nimport { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\n\n/** Public device-authenticated response. No account identifiers or credentials. */\nexport type CoordinatorAccountLinkStatus = CoordinatorAccountLinkStatusV2;\nexport interface CoordinatorAccountLinkStatusStore {\n\treadAccountLinkStatus(\n\t\tsigner: CoordinatorAuthLinkSigner,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t\toptions: { identityId: string },\n\t): Promise<CoordinatorAccountLinkStatus>;\n}\ninterface StatusRow {\n\tidentity_id: string;\n\tlink_id: string | null;\n\tissuer: string | null;\n\trevoked_at_ms: number | null;\n\tdisplay_name: unknown;\n\temail: unknown;\n\temail_verified: unknown;\n\tpicture_url: unknown;\n\tauthority: \"device_claim\" | \"controller_attestation\";\n\tvalid: number;\n\t/** 1 when the proof is this device's own claim or attestation, not a peer's. */\n\town: number;\n\t/** 1 when this exact device key holds an ownership binding for the Identity. */\n\tbound: number;\n\tclaim_count: number;\n\tcontroller_count: number;\n\tcontroller_identity: string | null;\n}\n\nfunction safeDisplayText(value: unknown, maxLength: number): string | undefined {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\tvalue.length === 0 ||\n\t\tvalue.length > maxLength ||\n\t\tvalue.trim().length === 0 ||\n\t\t/[\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(value)\n\t)\n\t\treturn undefined;\n\treturn value;\n}\n\nfunction claimConflicts(row: StatusRow): boolean {\n\treturn (\n\t\trow.claim_count > 0 &&\n\t\t(row.claim_count !== 1 ||\n\t\t\trow.valid !== 1 ||\n\t\t\trow.controller_count > 1 ||\n\t\t\t(row.controller_identity !== null && row.controller_identity !== row.identity_id))\n\t);\n}\n\nfunction projectStatus(\n\tbase: Extract<CoordinatorAccountLinkStatus, { state: \"review_required\" | \"conflict\" }>,\n\trow: StatusRow | null,\n\tconfig: CoordinatorAuthLinkConfig,\n\tidentityId: string,\n): CoordinatorAccountLinkStatus {\n\tif (!row) return base;\n\tif (claimConflicts(row))\n\t\treturn { ...base, state: \"conflict\", identityId: null, authority: null, account: null };\n\tif (row.valid !== 1 || row.controller_count > 1) return base;\n\tconst derived = { ...base, identityId: row.identity_id, authority: row.authority };\n\tif (row.revoked_at_ms !== null) return { ...derived, state: \"revoked\", account: null };\n\tif (row.link_id === null) {\n\t\tif (row.identity_id !== identityId) return base;\n\t\treturn { ...derived, state: \"unlinked\", account: null };\n\t}\n\tif (row.issuer !== config.issuer) return { ...base, state: \"conflict\" };\n\treturn { ...derived, state: \"linked\", account: requesterAccount(row, identityId) };\n}\n\n/** This device's own claim, ownership binding, or current attestation for the same Identity. */\nfunction requesterHoldsProof(row: StatusRow): boolean {\n\treturn (\n\t\trow.own === 1 ||\n\t\trow.bound === 1 ||\n\t\t(row.controller_count === 1 && row.controller_identity === row.identity_id)\n\t);\n}\n\n/**\n * Profile details need this device's own proof. A peer of the Identity learns\n * only that the account is linked elsewhere (ADR 0005 Section 8).\n */\nfunction requesterAccount(\n\trow: StatusRow,\n\tidentityId: string,\n): CoordinatorAccountLinkStatus[\"account\"] {\n\tif (row.identity_id !== identityId || !requesterHoldsProof(row)) return null;\n\tconst account: NonNullable<CoordinatorAccountLinkStatus[\"account\"]> = {};\n\tconst displayName = safeDisplayText(row.display_name, 256);\n\tconst email = row.email_verified === 1 ? safeDisplayText(row.email, 320) : undefined;\n\tif (displayName !== undefined) account.displayName = displayName;\n\tif (email !== undefined) account.email = email;\n\tconst { pictureUrl } = projectAccountProfileView(\n\t\t{ pictureUrl: row.picture_url },\n\t\trow.issuer ?? \"\",\n\t);\n\tif (pictureUrl !== undefined) account.pictureUrl = pictureUrl;\n\treturn account;\n}\n\n/** This exact device key's ownership binding for the requested Identity (ADR 0005 Section 8). */\nconst REQUESTER_BINDING_SQL = `SELECT 1 FROM claim_input bp JOIN coordinator_device_ownership_bindings ob\n ON ob.coordinator_id = bp.coordinator_id AND ob.device_id = bp.device_id AND ob.key_id = bp.key_id\n AND ob.identity_id = bp.identity_id`;\n\n/**\n * A rebound device has no claim of its own; its binding names the Identity and\n * the Identity's link is the account. Valid only while the device's exact\n * enrollment is current, neither device nor key is revoked, and the link was\n * born through a reviewed claim or attestation.\n */\nconst bindingCandidateSql = (\n\tconnections: boolean,\n) => `SELECT ob.identity_id, l.link_id, l.issuer, l.revoked_at_ms,\n CASE WHEN EXISTS (SELECT 1 FROM enrolled_devices e JOIN groups g ON g.group_id = e.group_id\n WHERE e.group_id = p.group_id AND e.device_id = p.device_id AND e.public_key = p.public_key\n AND e.fingerprint = p.fingerprint AND e.enabled = 1 AND g.archived_at IS NULL\n AND (e.identity_id IS NULL OR e.identity_id = ob.identity_id))\n AND NOT EXISTS (SELECT 1 FROM coordinator_device_revocations r\n WHERE (r.subject_kind = 'device_id' AND r.subject_value = p.device_id)\n OR (r.subject_kind = 'ed25519_key' AND r.subject_value = p.key_id))\n AND (l.link_id IS NULL OR ${authAccountLinkProvenanceSql(\"l\", { connections })})\n THEN 1 ELSE 0 END, 1, 'device_claim'\n FROM claim_input p JOIN coordinator_device_ownership_bindings ob ON ob.coordinator_id = p.coordinator_id\n AND ob.device_id = p.device_id AND ob.key_id = p.key_id AND ob.identity_id = p.identity_id\n LEFT JOIN coordinator_auth_account_links l ON l.coordinator_id = p.coordinator_id\n AND l.identity_id = ob.identity_id`;\n\n/** This device's old claim under another Identity, once a binding moved it and that link ended. */\nconst SUPERSEDED_OWN_CLAIM_SQL = `d.identity_id <> p.identity_id AND EXISTS (${REQUESTER_BINDING_SQL})\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_links al WHERE al.coordinator_id = d.coordinator_id\n AND al.identity_id = d.identity_id AND al.revoked_at_ms IS NULL)`;\n\nfunction statusConnectionFacts(connections: boolean): string {\n\tif (!connections) return \"\";\n\treturn `,\n status_genesis AS MATERIALIZED (SELECT d.coordinator_id,d.claim_id,d.identity_id FROM coordinator_auth_device_claims d JOIN claim_input p ON p.coordinator_id=d.coordinator_id WHERE (d.device_id=p.device_id OR d.key_id=p.key_id OR d.identity_id=p.identity_id) AND ${authClaimGenesisSql(\"d\")}),\n status_subjects AS MATERIALIZED (SELECT coordinator_id,identity_id FROM status_genesis UNION SELECT p.coordinator_id,c.controller_identity_id FROM controller c CROSS JOIN claim_input p),\n status_links AS MATERIALIZED (SELECT l.coordinator_id,l.link_id,l.authority_kind FROM coordinator_auth_account_links l JOIN status_subjects ss ON ss.coordinator_id=l.coordinator_id AND ss.identity_id=l.identity_id WHERE ${authAccountLinkProvenanceSql(\"l\", { connections: true })})`;\n}\n/** Reads only. Rechecks the exact enrollment and controller after key derivation. */\nexport class AccountLinkStatusOperations implements CoordinatorAccountLinkStatusStore {\n\tconstructor(\n\t\tprivate readonly backend: Pick<AuthLinkBackend, \"first\">,\n\t\tprivate readonly clock: () => number = Date.now,\n\t) {}\n\n\t/** Internal store capability only. It does not reserve a claim or expose account data. */\n\tasync readAuthDeviceClaimReadiness(\n\t\tinput: CoordinatorDeviceClaimReadinessInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorDeviceClaimReadiness> {\n\t\tconst c = captureAuthLinkConfig(config);\n\t\tif (!c?.enabled) return { kind: \"unavailable\" };\n\t\ttry {\n\t\t\tconst captured = await captureDeviceClaimEligibility(\n\t\t\t\tthis.backend,\n\t\t\t\tinput,\n\t\t\t\tc,\n\t\t\t\tauthLinkNow(this.clock),\n\t\t\t);\n\t\t\tif (!captured) return { kind: \"unavailable\" };\n\t\t\tconst row = await this.backend.first<{ eligible: number }>({\n\t\t\t\tsql: `${AUTH_DEVICE_CLAIM_INPUT_SQL} SELECT CASE WHEN (${AUTH_DEVICE_CLAIM_ELIGIBLE_SQL})${captured.connectionSession ? ` OR (${CONNECTION_RELINK_ELIGIBLE_SQL})` : \"\"} THEN 1 ELSE 0 END AS eligible FROM claim_input p`,\n\t\t\t\tvalues: captured.values,\n\t\t\t});\n\t\t\tif (row?.eligible !== 1) return { kind: \"unavailable\" };\n\t\t\treturn { kind: \"eligible\", authority: \"device_claim\", identityId: captured.identityId };\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_device_claim_unavailable\");\n\t\t}\n\t}\n\n\tasync readAccountLinkStatus(\n\t\tsigner: CoordinatorAuthLinkSigner,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t\toptions: { identityId: string },\n\t): Promise<CoordinatorAccountLinkStatus> {\n\t\tconst c = captureAuthLinkConfig(config);\n\t\tconst s = captureAuthLinkSigner(signer);\n\t\tif (!c?.enabled || !s || !isAuthControllerId(options?.identityId))\n\t\t\tthrow new Error(\"account_link_status_unavailable\");\n\t\tconst base: CoordinatorAccountLinkStatus = {\n\t\t\tversion: 2,\n\t\t\tcoordinatorId: c.coordinatorId,\n\t\t\tgroupId: s.groupId,\n\t\t\tdeviceId: s.deviceId,\n\t\t\tfingerprint: s.fingerprint,\n\t\t\tidentityId: null,\n\t\t\tauthority: null,\n\t\t\tstate: \"review_required\",\n\t\t\taccount: null,\n\t\t};\n\t\ttry {\n\t\t\tconst identityId = options.identityId;\n\t\t\tconst keyId = await ed25519KeyIdForRevocation(s.publicKey);\n\t\t\tif (!keyId) return base;\n\t\t\tconst captured = await captureDeviceClaimEligibility(\n\t\t\t\tthis.backend,\n\t\t\t\t{ signer: s, identityId },\n\t\t\t\tc,\n\t\t\t\tauthLinkNow(this.clock),\n\t\t\t);\n\t\t\tif (!captured) return base;\n\t\t\tconst connections = captured.connectionSession;\n\t\t\tconst connectionFacts = statusConnectionFacts(connections);\n\t\t\t// Authority, current enrollment, tombstones and metadata share one snapshot.\n\t\t\tconst row = await this.backend.first<StatusRow>({\n\t\t\t\tsql: `${AUTH_DEVICE_CLAIM_INPUT_SQL}, controller AS (\n SELECT ${AUTH_LINK_AUTHORITY_COLUMNS} ${AUTH_LINK_CONTROLLER_SOURCE_SQL}\n AND NOT EXISTS (SELECT 1 FROM coordinator_device_revocations r\n WHERE (r.subject_kind = 'device_id' AND r.subject_value = a.device_id)\n OR (r.subject_kind = 'ed25519_key' AND r.subject_value = ?))),\n status_assignment AS MATERIALIZED (SELECT 1 FROM claim_input p\n WHERE (${AUTH_CURRENT_LEGACY_ASSIGNMENT_SQL} AND ${AUTH_DEVICE_CLAIM_LEGACY_COMPATIBLE_SQL})\n AND (${AUTH_DEVICE_CLAIM_CURRENT_SUBJECT_COMPATIBLE_SQL})\n AND (${AUTH_DEVICE_CLAIM_REQUESTER_ATTESTATION_COMPATIBLE_SQL}\n AND ${AUTH_DEVICE_CLAIM_REQUESTER_INVITE_COMPATIBLE_SQL})\n AND (${AUTH_DEVICE_CLAIM_REQUESTER_LINK_COMPATIBLE_SQL}))${connectionFacts},\n claims AS MATERIALIZED (SELECT d.identity_id, l.link_id, l.issuer, l.revoked_at_ms,\n CASE WHEN (l.identity_id = d.identity_id${connections ? \" OR (l.link_id IS NULL AND sg.claim_id IS NOT NULL)\" : \"\"})\n AND EXISTS (SELECT 1 FROM enrolled_devices e JOIN groups g ON g.group_id = e.group_id\n WHERE e.group_id = p.group_id AND e.device_id = p.device_id AND e.public_key = p.public_key\n AND e.fingerprint = p.fingerprint AND e.enabled = 1 AND g.archived_at IS NULL\n AND (e.identity_id IS NULL OR e.identity_id = d.identity_id))\n AND NOT EXISTS (SELECT 1 FROM coordinator_device_revocations r\n WHERE (r.subject_kind = 'device_id' AND r.subject_value = p.device_id)\n OR (r.subject_kind = 'ed25519_key' AND r.subject_value = p.key_id))\n AND ((d.group_id = p.group_id AND d.device_id = p.device_id\n AND d.key_id = p.key_id AND d.fingerprint = p.fingerprint\n AND ${connections ? \"(sg.claim_id IS NOT NULL AND (l.link_id IS NULL OR sl.link_id IS NOT NULL) AND d.key_id = ?)\" : authDeviceClaimProvenanceSql({ link: \"l\", canonicalKeyId: \"?\" })})\n OR (d.identity_id = p.identity_id AND d.device_id <> p.device_id\n AND d.key_id <> p.key_id AND d.fingerprint <> p.fingerprint\n AND EXISTS (SELECT 1 FROM status_assignment)\n AND ${connections ? \"(sl.link_id IS NOT NULL AND sl.authority_kind = 'device_claim')\" : authDeviceClaimProvenanceSql({ link: \"l\" })}))\n THEN 1 ELSE 0 END AS valid,\n CASE WHEN d.device_id = p.device_id AND d.key_id = p.key_id THEN 1 ELSE 0 END AS own\n FROM claim_input p JOIN coordinator_auth_device_claims d ON d.coordinator_id = p.coordinator_id\n LEFT JOIN coordinator_auth_account_links l ON l.coordinator_id = d.coordinator_id AND ${connections ? \"l.identity_id = d.identity_id\" : \"l.device_claim_id = d.claim_id\"}\n ${connections ? \"LEFT JOIN status_genesis sg ON sg.coordinator_id=d.coordinator_id AND sg.claim_id=d.claim_id LEFT JOIN status_links sl ON sl.coordinator_id=l.coordinator_id AND sl.link_id=l.link_id\" : \"\"}\n WHERE (d.device_id = p.device_id OR d.key_id = p.key_id\n OR (d.identity_id = p.identity_id AND EXISTS (SELECT 1 FROM status_assignment)))\n AND NOT (${SUPERSEDED_OWN_CLAIM_SQL})),\n candidates AS (\n SELECT *, 'device_claim' AS authority FROM claims\n UNION ALL SELECT a.controller_identity_id, l.link_id, l.issuer, l.revoked_at_ms, ${connections ? \"CASE WHEN l.link_id IS NULL OR valid_controller.link_id IS NOT NULL THEN 1 ELSE 0 END\" : \"1\"}, 1, 'controller_attestation'\n FROM controller a LEFT JOIN coordinator_auth_account_links l ON l.coordinator_id = ?\n AND l.identity_id = a.controller_identity_id ${connections ? \"\" : \"AND l.authority_kind = 'controller_attestation' AND l.controller_attestation_id IS NOT NULL AND l.device_claim_id IS NULL\"}\n ${connections ? \"LEFT JOIN status_links valid_controller ON valid_controller.coordinator_id=l.coordinator_id AND valid_controller.link_id=l.link_id\" : \"\"}\n WHERE NOT EXISTS (SELECT 1 FROM claims)\n UNION ALL ${bindingCandidateSql(connections)}\n WHERE NOT EXISTS (SELECT 1 FROM claims) AND NOT EXISTS (SELECT 1 FROM controller)\n UNION ALL SELECT p.identity_id, NULL, NULL, NULL, 1, 1, 'device_claim' FROM claim_input p\n WHERE NOT EXISTS (SELECT 1 FROM claims) AND NOT EXISTS (SELECT 1 FROM controller)\n AND NOT EXISTS (${REQUESTER_BINDING_SQL}) AND ${AUTH_DEVICE_CLAIM_ELIGIBLE_SQL})\n SELECT a.identity_id,a.link_id,a.issuer,a.valid,a.own,a.authority,\n EXISTS (${REQUESTER_BINDING_SQL} AND ob.identity_id = a.identity_id) AS bound,\n ${connections ? `coalesce((SELECT min(h.revoked_at_ms) FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id = (SELECT coordinator_id FROM claim_input) AND h.identity_id = a.identity_id AND h.revoked_at_ms IS NOT NULL),a.revoked_at_ms)` : \"a.revoked_at_ms\"} AS revoked_at_ms,\n (SELECT count(*) FROM claims) AS claim_count,\n (SELECT count(*) FROM controller) AS controller_count,\n (SELECT controller_identity_id FROM controller LIMIT 1) AS controller_identity,\n ${\n\t\tconnections\n\t\t\t? connectionProfileColumns(\"m\")\n\t\t\t: `CASE WHEN m.link_id IS NOT NULL THEN m.display_name ELSE b.display_name END AS display_name,\n CASE WHEN m.link_id IS NOT NULL THEN m.email ELSE b.email END AS email,\n CASE WHEN m.link_id IS NOT NULL THEN m.email_verified ELSE b.email_verified END AS email_verified,\n CASE WHEN m.link_id IS NOT NULL THEN m.picture_url ELSE b.picture_url END AS picture_url`\n\t}\n FROM candidates a\n LEFT JOIN coordinator_auth_account_links l ON l.coordinator_id = ? AND l.link_id = a.link_id\n AND l.identity_id = a.identity_id AND a.identity_id = ? AND l.issuer = a.issuer\n AND l.revoked_at_ms IS NULL\n LEFT JOIN coordinator_auth_account_profiles m ON m.coordinator_id = l.coordinator_id\n AND m.link_id = l.link_id\n LEFT JOIN coordinator_auth_link_profiles b ON b.coordinator_id = l.coordinator_id\n AND b.link_id = l.link_id AND b.attempt_id = l.attempt_id AND b.issuer = l.issuer\n AND b.subject = l.subject AND b.auth_config_revision = l.auth_config_revision LIMIT 1`,\n\t\t\t\tvalues: [\n\t\t\t\t\t...captured.values,\n\t\t\t\t\t...authLinkControllerSourceValues(c, s),\n\t\t\t\t\tkeyId,\n\t\t\t\t\tkeyId,\n\t\t\t\t\tc.coordinatorId,\n\t\t\t\t\tc.coordinatorId,\n\t\t\t\t\tidentityId,\n\t\t\t\t],\n\t\t\t});\n\t\t\treturn projectStatus(base, row, c, identityId);\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"account_link_status_unavailable\");\n\t\t}\n\t}\n}\n","import {\n\tACCOUNT_CONNECTION_SCHEMA_READINESS_SQL,\n\tisIncompleteConnectionSchemaError,\n\treadConnectionSchemaState,\n} from \"./coordinator-account-connection-schema.js\";\nimport { CONNECTION_NOT_REVOKED_SQL } from \"./coordinator-account-connection-storage.js\";\nimport {\n\ttype CoordinatorAuthControllerStore,\n\tisAuthControllerId,\n} from \"./coordinator-auth-controller.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport type {\n\tCoordinatorAuthLinkConfig,\n\tCoordinatorAuthLinkSigner,\n} from \"./coordinator-auth-link-contract.js\";\nimport {\n\tcapture,\n\tcaptureAuthLinkConfig,\n\tcaptureAuthLinkSigner,\n\tisHash,\n} from \"./coordinator-auth-link-input.js\";\nimport { authAccountLinkProvenanceSql } from \"./coordinator-auth-link-provenance.js\";\nimport { authPersistenceError } from \"./coordinator-auth-schema.js\";\nimport { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\n\nexport interface CoordinatorAccountOwnerTargetInput {\n\t/** Explicit operator choice, not the local memory author or an enrollment label. */\n\ttargetIdentityId: string;\n\tsigner: CoordinatorAuthLinkSigner;\n}\nexport interface CoordinatorAccountOwnerTargetStore {\n\treadAccountOwnerTarget(\n\t\tinput: CoordinatorAccountOwnerTargetInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAccountOwnerTarget>;\n}\nexport type CoordinatorAccountOwnerTarget =\n\t| { kind: \"unavailable\" }\n\t| {\n\t\t\tkind: \"ready\";\n\t\t\ttargetIdentityId: string;\n\t\t\t/** The immutable link ID identifies the current connection generation. */\n\t\t\tlinkId: string;\n\t\t\tcurrentGeneration: { authConfigRevision: string; createdAtMs: number };\n\t\t\treview: { attestationId: string; reviewReceiptId: string; evidenceDigest: string } | null;\n\t };\n\ninterface TargetRow {\n\tlink_id: string;\n\tauth_config_revision: string;\n\tcreated_at_ms: number;\n\treview_count: number;\n\tattestation_id: string | null;\n\treview_revoked_at: string | null;\n}\nconst REVIEW_MATCH = `a.coordinator_id=l.coordinator_id AND a.group_id=e.group_id\n AND a.device_id=e.device_id AND a.fingerprint=e.fingerprint`;\nconst TARGET_SQL = `SELECT l.link_id,l.auth_config_revision,l.created_at_ms,\n (SELECT count(*) FROM coordinator_auth_controller_attestations a WHERE ${REVIEW_MATCH}) AS review_count,\n (SELECT a.attestation_id FROM coordinator_auth_controller_attestations a WHERE ${REVIEW_MATCH} LIMIT 1) AS attestation_id,\n (SELECT a.revoked_at FROM coordinator_auth_controller_attestations a WHERE ${REVIEW_MATCH} LIMIT 1) AS review_revoked_at\n FROM coordinator_auth_account_links l\n JOIN enrolled_devices e ON e.group_id=? AND e.device_id=?\n JOIN groups g ON g.group_id=e.group_id\n WHERE l.coordinator_id=? AND l.identity_id=? AND l.issuer=?\n AND e.public_key=? AND e.fingerprint=? AND e.enabled=1 AND g.archived_at IS NULL\n AND (e.identity_id IS NULL OR e.identity_id=l.identity_id)\n AND NOT EXISTS (SELECT 1 FROM coordinator_device_revocations r\n WHERE (r.subject_kind='device_id' AND r.subject_value=e.device_id)\n OR (r.subject_kind='ed25519_key' AND r.subject_value=?))\n AND ${CONNECTION_NOT_REVOKED_SQL}\n AND ${authAccountLinkProvenanceSql(\"l\", { connections: true })}`;\n\nfunction validTarget(row: TargetRow | null): row is TargetRow {\n\tif (!row || !isAuthControllerId(row.link_id) || !isHash(row.auth_config_revision)) return false;\n\tif (!Number.isSafeInteger(row.created_at_ms) || row.created_at_ms < 0) return false;\n\tif (row.review_revoked_at !== null) return false;\n\tif (row.review_count === 0) return row.attestation_id === null;\n\treturn row.review_count === 1 && isAuthControllerId(row.attestation_id);\n}\nfunction sameTarget(a: TargetRow, b: TargetRow | null): boolean {\n\treturn (\n\t\tvalidTarget(b) &&\n\t\ta.link_id === b.link_id &&\n\t\ta.auth_config_revision === b.auth_config_revision &&\n\t\ta.created_at_ms === b.created_at_ms &&\n\t\ta.review_count === b.review_count &&\n\t\ta.attestation_id === b.attestation_id &&\n\t\ta.review_revoked_at === b.review_revoked_at\n\t);\n}\n\nasync function readSchemaReadyTarget(\n\tbackend: Pick<AuthLinkBackend, \"first\">,\n\tstatement: AuthLinkStatement,\n): Promise<TargetRow | null> {\n\ttry {\n\t\treturn await backend.first<TargetRow>({\n\t\t\t...statement,\n\t\t\tsql: `${statement.sql} AND (${ACCOUNT_CONNECTION_SCHEMA_READINESS_SQL})=1`,\n\t\t});\n\t} catch (error) {\n\t\tif (isIncompleteConnectionSchemaError(error)) return null;\n\t\tthrow error;\n\t}\n}\n\n/** Trusted store read only. Future callers MUST authenticate the admin first.\n * A ready result is advisory, not approval to adopt a profile or mutate an account.\n * Null enrollment labels are accepted for review, never treated as ownership proof.\n */\nexport class AccountOwnerTargetOperations {\n\tconstructor(\n\t\tprivate readonly backend: Pick<AuthLinkBackend, \"first\">,\n\t\tprivate readonly reviews: Pick<\n\t\t\tCoordinatorAuthControllerStore,\n\t\t\t\"getActiveAuthControllerAttestation\"\n\t\t>,\n\t) {}\n\n\tasync readAccountOwnerTarget(\n\t\tinput: CoordinatorAccountOwnerTargetInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CoordinatorAccountOwnerTarget> {\n\t\tconst c = captureAuthLinkConfig(config);\n\t\tconst fields = capture(input, [\"targetIdentityId\", \"signer\"]);\n\t\tconst s = captureAuthLinkSigner(fields?.signer);\n\t\tconst identityId = fields?.targetIdentityId;\n\t\tif (!c?.enabled || !s || !isAuthControllerId(identityId)) return { kind: \"unavailable\" };\n\t\ttry {\n\t\t\tif ((await readConnectionSchemaState(this.backend)) !== \"ready\")\n\t\t\t\treturn { kind: \"unavailable\" };\n\t\t\tconst keyId = await ed25519KeyIdForRevocation(s.publicKey);\n\t\t\tif (!keyId) return { kind: \"unavailable\" };\n\t\t\tconst statement = {\n\t\t\t\tsql: TARGET_SQL,\n\t\t\t\tvalues: [\n\t\t\t\t\ts.groupId,\n\t\t\t\t\ts.deviceId,\n\t\t\t\t\tc.coordinatorId,\n\t\t\t\t\tidentityId,\n\t\t\t\t\tc.issuer,\n\t\t\t\t\ts.publicKey,\n\t\t\t\t\ts.fingerprint,\n\t\t\t\t\tkeyId,\n\t\t\t\t],\n\t\t\t};\n\t\t\tconst row = await this.backend.first<TargetRow>(statement);\n\t\t\tif (!validTarget(row)) return { kind: \"unavailable\" };\n\t\t\tconst review = await this.readReview(row, c.coordinatorId, identityId, s);\n\t\t\tif (review === undefined) return { kind: \"unavailable\" };\n\t\t\tif ((await readConnectionSchemaState(this.backend)) !== \"ready\")\n\t\t\t\treturn { kind: \"unavailable\" };\n\t\t\t// Review and schema reads may yield. Recheck both schema and target in one final snapshot.\n\t\t\tif (!sameTarget(row, await readSchemaReadyTarget(this.backend, statement)))\n\t\t\t\treturn { kind: \"unavailable\" };\n\t\t\treturn {\n\t\t\t\tkind: \"ready\",\n\t\t\t\ttargetIdentityId: identityId,\n\t\t\t\tlinkId: row.link_id,\n\t\t\t\tcurrentGeneration: {\n\t\t\t\t\tauthConfigRevision: row.auth_config_revision,\n\t\t\t\t\tcreatedAtMs: row.created_at_ms,\n\t\t\t\t},\n\t\t\t\treview,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"account_owner_target_unavailable\");\n\t\t}\n\t}\n\n\tprivate async readReview(\n\t\trow: TargetRow,\n\t\tcoordinatorId: string,\n\t\tidentityId: string,\n\t\tsigner: CoordinatorAuthLinkSigner,\n\t): Promise<Extract<CoordinatorAccountOwnerTarget, { kind: \"ready\" }>[\"review\"] | undefined> {\n\t\tif (row.attestation_id === null) return null;\n\t\t// Do not reparse review JSON or compare an immutable review to fresh history.\n\t\tconst a = await this.reviews.getActiveAuthControllerAttestation(\n\t\t\tcoordinatorId,\n\t\t\trow.attestation_id,\n\t\t);\n\t\tif (\n\t\t\t!a ||\n\t\t\ta.coordinator_id !== coordinatorId ||\n\t\t\ta.attestation_id !== row.attestation_id ||\n\t\t\ta.identity_id !== identityId ||\n\t\t\ta.group_id !== signer.groupId ||\n\t\t\ta.device_id !== signer.deviceId ||\n\t\t\ta.public_key !== signer.publicKey ||\n\t\t\ta.fingerprint !== signer.fingerprint ||\n\t\t\ta.revoked_at !== null ||\n\t\t\ta.revision !== 1 ||\n\t\t\t!isAuthControllerId(a.review_receipt_id) ||\n\t\t\t!isHash(a.evidence_digest)\n\t\t)\n\t\t\treturn undefined;\n\t\treturn {\n\t\t\tattestationId: a.attestation_id,\n\t\t\treviewReceiptId: a.review_receipt_id,\n\t\t\tevidenceDigest: a.evidence_digest,\n\t\t};\n\t}\n}\n","import {\n\thasConnectionSessionSchema,\n\torderedBrowserStart,\n} from \"./coordinator-account-connection-session.js\";\nimport {\n\tAUTH_BROWSER_TXN_MAINTENANCE_BATCH_MAX,\n\tAUTH_BROWSER_TXN_TTL_MS,\n\tAUTH_SIGNIN_TXN_MAX_RETAINED,\n\tAUTH_SIGNIN_TXN_MAX_STARTS_PER_WINDOW,\n\tAUTH_SIGNIN_TXN_PURGE_AGE_MS,\n\tAUTH_SIGNIN_TXN_PURGE_BATCH_MAX,\n\tAUTH_SIGNIN_TXN_WINDOW_MS,\n\ttype CoordinatorAuthBrowserConfig,\n\ttype CoordinatorAuthBrowserTransactionConsumeInput,\n\ttype CoordinatorAuthBrowserTransactionConsumeResult,\n\ttype CoordinatorAuthBrowserTransactionError,\n\ttype CoordinatorAuthBrowserTransactionMaintenanceOptions,\n\ttype CoordinatorAuthBrowserTransactionMaintenanceResult,\n\ttype CoordinatorAuthBrowserTransactionPurpose,\n\ttype CoordinatorAuthBrowserTransactionRejected,\n\ttype CoordinatorAuthBrowserTransactionRetirementOptions,\n\ttype CoordinatorAuthBrowserTransactionRetirementResult,\n\ttype CoordinatorAuthBrowserTransactionScope,\n\ttype CoordinatorAuthBrowserTransactionStartInput,\n\ttype CoordinatorAuthBrowserTransactionStartResult,\n\ttype CoordinatorAuthBrowserTransactionStore,\n\ttype CoordinatorAuthLinkBrowserTransactionResolveInput,\n\ttype CoordinatorAuthSigninBrowserTransactionCancelInput,\n\ttype CoordinatorAuthSigninBrowserTransactionCancelResult,\n\ttype CoordinatorAuthSigninBrowserTransactionPurgeResult,\n} from \"./coordinator-auth-browser-transaction-contract.js\";\nimport { isCoordinatorAccountIssuer } from \"./coordinator-auth-contract.js\";\nimport { isAuthControllerId, isAuthControllerUniqueError } from \"./coordinator-auth-controller.js\";\nimport {\n\ttype AuthLinkBackend,\n\ttype AuthLinkStatement,\n\tauthLinkNow,\n\tcaptureAuthLinkBrowserStartHash,\n} from \"./coordinator-auth-link.js\";\nimport {\n\tAUTH_LINK_HEADLESS_MARKER_SQL,\n\ttype CoordinatorAuthHeadlessBrowserStartInput,\n\ttype CoordinatorAuthHeadlessBrowserStartResult,\n} from \"./coordinator-auth-link-headless.js\";\nimport {\n\tcaptureAuthLinkBrowserSource,\n\tcaptureAuthLinkSource,\n} from \"./coordinator-auth-link-source.js\";\nimport { authPersistenceError } from \"./coordinator-auth-schema.js\";\n\nexport * from \"./coordinator-auth-browser-transaction-contract.js\";\n\ntype Captured = Record<string, unknown>;\nfunction capture(value: unknown, fields: readonly string[]): Captured | null {\n\tif (!value || typeof value !== \"object\") return null;\n\ttry {\n\t\tif (Array.isArray(value)) return null;\n\t\tconst result: Captured = {};\n\t\tfor (const key of fields) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\t\tif (!descriptor || !Object.hasOwn(descriptor, \"value\")) return null;\n\t\t\tresult[key] = descriptor.value;\n\t\t}\n\t\treturn result;\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction isHash(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length === 64 && /^[0-9a-f]{64}$/.test(value);\n}\nfunction isMaterial(value: unknown): value is string {\n\treturn typeof value === \"string\" && /^[A-Za-z0-9._~-]{43,128}$/.test(value);\n}\nfunction isRedirect(value: unknown): value is string {\n\tif (typeof value !== \"string\" || value.trim() !== value || /[\\\\\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(value))\n\t\treturn false;\n\ttry {\n\t\tconst url = new URL(value);\n\t\treturn (\n\t\t\turl.protocol === \"https:\" &&\n\t\t\turl.href === value &&\n\t\t\t!url.username &&\n\t\t\t!url.password &&\n\t\t\t!url.search &&\n\t\t\t!url.hash &&\n\t\t\t!value.includes(\"?\") &&\n\t\t\t!value.includes(\"#\")\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\nfunction captureConfig(value: unknown): CoordinatorAuthBrowserConfig | null {\n\tconst c = capture(value, [\"coordinatorId\", \"issuer\", \"revision\", \"enabled\", \"redirectUri\"]);\n\tif (\n\t\t!c ||\n\t\t!isAuthControllerId(c.coordinatorId) ||\n\t\t!isCoordinatorAccountIssuer(c.issuer) ||\n\t\t!isHash(c.revision) ||\n\t\ttypeof c.enabled !== \"boolean\" ||\n\t\t!isRedirect(c.redirectUri)\n\t)\n\t\treturn null;\n\treturn {\n\t\tcoordinatorId: c.coordinatorId,\n\t\tissuer: c.issuer,\n\t\trevision: c.revision,\n\t\tenabled: c.enabled,\n\t\tredirectUri: c.redirectUri,\n\t};\n}\nfunction isSigninAttempt(value: object, attempt: PropertyDescriptor | undefined): boolean {\n\tif (attempt) return Object.hasOwn(attempt, \"value\") && attempt.value === undefined;\n\treturn !(\"attemptId\" in value);\n}\nfunction captureStart(value: unknown): CoordinatorAuthBrowserTransactionStartInput | null {\n\tconst i = capture(value, [\"purpose\", \"stateHash\", \"binderHash\", \"nonce\", \"pkceVerifier\"]);\n\tif (\n\t\t!i ||\n\t\t!isHash(i.stateHash) ||\n\t\t!isHash(i.binderHash) ||\n\t\t!isMaterial(i.nonce) ||\n\t\t!isMaterial(i.pkceVerifier)\n\t)\n\t\treturn null;\n\ttry {\n\t\t// Never accept request nomination of the internal, server-generated transaction hash.\n\t\tif (\n\t\t\tObject.getOwnPropertyDescriptor(value, \"browserTransactionHash\") ||\n\t\t\t\"browserTransactionHash\" in (value as object)\n\t\t)\n\t\t\treturn null;\n\t\tconst attempt = Object.getOwnPropertyDescriptor(value, \"attemptId\");\n\t\tif (i.purpose === \"signin\") {\n\t\t\tif (!isSigninAttempt(value as object, attempt)) return null;\n\t\t\treturn {\n\t\t\t\tpurpose: \"signin\",\n\t\t\t\tstateHash: i.stateHash,\n\t\t\t\tbinderHash: i.binderHash,\n\t\t\t\tnonce: i.nonce,\n\t\t\t\tpkceVerifier: i.pkceVerifier,\n\t\t\t};\n\t\t}\n\t\tif (\n\t\t\ti.purpose !== \"link\" ||\n\t\t\t!attempt ||\n\t\t\t!Object.hasOwn(attempt, \"value\") ||\n\t\t\t!isAuthControllerId(attempt.value)\n\t\t)\n\t\t\treturn null;\n\t\tconst browserStartHash = captureAuthLinkBrowserStartHash(value);\n\t\tif (browserStartHash === false) return null;\n\t\treturn {\n\t\t\tpurpose: \"link\",\n\t\t\tattemptId: attempt.value,\n\t\t\t...(browserStartHash === null ? {} : { browserStartHash }),\n\t\t\tstateHash: i.stateHash,\n\t\t\tbinderHash: i.binderHash,\n\t\t\tnonce: i.nonce,\n\t\t\tpkceVerifier: i.pkceVerifier,\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction captureHeadlessStart(value: unknown): CoordinatorAuthHeadlessBrowserStartInput | null {\n\tconst i = capture(value, [\"userCodeHash\", \"stateHash\", \"binderHash\", \"nonce\", \"pkceVerifier\"]);\n\tif (\n\t\t!i ||\n\t\t!isHash(i.userCodeHash) ||\n\t\t!isHash(i.stateHash) ||\n\t\t!isHash(i.binderHash) ||\n\t\t!isMaterial(i.nonce) ||\n\t\t!isMaterial(i.pkceVerifier)\n\t)\n\t\treturn null;\n\treturn {\n\t\tuserCodeHash: i.userCodeHash,\n\t\tstateHash: i.stateHash,\n\t\tbinderHash: i.binderHash,\n\t\tnonce: i.nonce,\n\t\tpkceVerifier: i.pkceVerifier,\n\t};\n}\ntype LinkMode = \"desktop\" | \"headless\";\n/** Both the transaction insert and the attempt claim must name the attempt's mode. */\nfunction withLinkMode(\n\tsource: AuthLinkStatement,\n\talias: \"a\" | \"coordinator_auth_link_attempts\",\n\tmode: LinkMode,\n): AuthLinkStatement {\n\tconst operator = mode === \"headless\" ? \"=\" : \"<>\";\n\treturn {\n\t\tsql: `(${source.sql}) AND ${alias}.loopback_redirect ${operator} ${AUTH_LINK_HEADLESS_MARKER_SQL}`,\n\t\tvalues: source.values,\n\t};\n}\nfunction maintenanceLimit(\n\tvalue: unknown,\n\tmax = AUTH_BROWSER_TXN_MAINTENANCE_BATCH_MAX,\n): number | null {\n\tif (value === undefined) return max;\n\tif (!value || typeof value !== \"object\") return null;\n\ttry {\n\t\tif (Array.isArray(value)) return null;\n\t\tconst d = Object.getOwnPropertyDescriptor(value, \"limit\");\n\t\tif (!d) return \"limit\" in value ? null : max;\n\t\tif (!Object.hasOwn(d, \"value\")) return null;\n\t\tconst limit: unknown = d.value;\n\t\treturn typeof limit === \"number\" && Number.isSafeInteger(limit) && limit >= 1 && limit <= max\n\t\t\t? limit\n\t\t\t: null;\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction captureRetirementOptions(value: unknown): { limit: number; attemptId?: string } | null {\n\tconst limit = maintenanceLimit(value);\n\tif (limit === null) return null;\n\tif (value === undefined) return { limit };\n\ttry {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, \"attemptId\");\n\t\tif (!descriptor) return \"attemptId\" in (value as object) ? null : { limit };\n\t\tif (!Object.hasOwn(descriptor, \"value\") || !isAuthControllerId(descriptor.value)) return null;\n\t\treturn { limit, attemptId: descriptor.value };\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction rejected(\n\terror: CoordinatorAuthBrowserTransactionError,\n): CoordinatorAuthBrowserTransactionRejected {\n\treturn { kind: \"rejected\", error };\n}\nfunction transactionHash(): string {\n\ttry {\n\t\tconst bytes = globalThis.crypto.getRandomValues(new Uint8Array(32));\n\t\treturn Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\t} catch {\n\t\tthrow new Error(\"browser_transaction_entropy_failed\");\n\t}\n}\nfunction claimToken(): string {\n\ttry {\n\t\treturn globalThis.crypto.randomUUID();\n\t} catch {\n\t\tthrow new Error(\"browser_transaction_entropy_failed\");\n\t}\n}\ninterface TransactionRow {\n\tbrowser_transaction_hash: string;\n\tpurpose: string;\n\tattempt_id: string | null;\n\tnonce: string | null;\n\tpkce_verifier: string | null;\n\texpires_at_ms: number;\n}\ninterface AttemptDiagnosis {\n\tissuer: string;\n\tauth_config_revision: string;\n\tstate: string;\n\texpires_at_ms: number;\n}\nfunction isConsumableRow(\n\trow: TransactionRow,\n): row is TransactionRow & { nonce: string; pkce_verifier: string } {\n\tif (\n\t\t!isHash(row.browser_transaction_hash) ||\n\t\t!isMaterial(row.nonce) ||\n\t\t!isMaterial(row.pkce_verifier)\n\t)\n\t\treturn false;\n\tif (row.purpose === \"signin\") return row.attempt_id === null;\n\treturn row.purpose === \"link\" && isAuthControllerId(row.attempt_id);\n}\nconst TABLE = \"coordinator_auth_browser_transactions\";\nconst PURGE_FLOORS = \"coordinator_auth_signin_purge_floors\";\nconst COLUMNS = `coordinator_id, browser_transaction_hash, purpose, attempt_id, state_hash, binder_hash,\n issuer, auth_config_revision, redirect_uri, state, nonce, pkce_verifier, created_at_ms, expires_at_ms, claim_token, consumed_at_ms`;\n// Force a uniqueness failure even when another admission guard suppresses a colliding insert.\nconst ASSERT_HASH_FRESH = `UNION ALL SELECT ${COLUMNS} FROM coordinator_auth_browser_transactions\n WHERE coordinator_id = ? AND browser_transaction_hash = ?`;\nconst FRESH_HASH = `NOT EXISTS (SELECT 1 FROM coordinator_auth_browser_transactions WHERE coordinator_id = ? AND browser_transaction_hash = ?)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_link_attempts WHERE coordinator_id = ? AND browser_transaction_hash = ?)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_session_receipts WHERE coordinator_id = ? AND browser_transaction_hash = ?)`;\nfunction freshValues(c: CoordinatorAuthBrowserConfig, hash: string): (string | number)[] {\n\treturn [c.coordinatorId, hash, c.coordinatorId, hash, c.coordinatorId, hash];\n}\nconst MATCH_CONFIG =\n\t\"b.coordinator_id = ? AND b.issuer = ? AND b.auth_config_revision = ? AND b.redirect_uri = ?\";\nfunction configValues(c: CoordinatorAuthBrowserConfig): string[] {\n\treturn [c.coordinatorId, c.issuer, c.revision, c.redirectUri];\n}\nfunction assertLinkClaim(\n\ti: CoordinatorAuthBrowserTransactionStartInput & { purpose: \"link\" },\n\tc: CoordinatorAuthBrowserConfig,\n\tnow: number,\n\thash: string,\n): AuthLinkStatement {\n\t// A suppressed claim must violate the pending-secret CHECK inside the same atomic batch.\n\treturn {\n\t\tsql: `UPDATE ${TABLE} AS b SET nonce = NULL WHERE ${MATCH_CONFIG} AND b.browser_transaction_hash = ?\n AND b.state = 'pending' AND b.attempt_id = ? AND b.created_at_ms = ? AND NOT EXISTS\n (SELECT 1 FROM coordinator_auth_link_attempts a WHERE a.coordinator_id = b.coordinator_id AND a.attempt_id = b.attempt_id\n AND (a.authority_kind = 'controller_attestation' OR (a.authority_kind = 'device_claim'\n AND a.controller_attestation_id IS NULL AND a.controller_review_receipt_id IS NULL AND a.controller_revision IS NULL))\n AND a.browser_transaction_hash = b.browser_transaction_hash AND a.state = 'browser_claimed'\n AND a.claimed_at_ms = ? AND a.issuer = b.issuer AND a.auth_config_revision = b.auth_config_revision\n AND a.expires_at_ms = b.expires_at_ms AND a.expires_at_ms > ?)`,\n\t\tvalues: [...configValues(c), hash, i.attemptId, now, now, now],\n\t};\n}\nfunction linkMatch(states: string, source = \"a.authority_kind = 'controller_attestation'\"): string {\n\t// One indexed source row separates its proof tree from the browser match.\n\treturn `(b.purpose = 'signin' OR EXISTS (WITH link_source AS MATERIALIZED (\n SELECT a.* FROM coordinator_auth_link_attempts a WHERE (a.coordinator_id = b.coordinator_id AND a.attempt_id = b.attempt_id) AND (${source}))\n SELECT 1 FROM link_source a WHERE (b.purpose = 'link' AND a.coordinator_id = b.coordinator_id AND a.attempt_id = b.attempt_id)\n AND (a.browser_transaction_hash = b.browser_transaction_hash AND a.issuer = b.issuer AND a.auth_config_revision = b.auth_config_revision)\n AND (a.expires_at_ms > ? AND a.state IN (${states}))))`;\n}\n// Retirement only destroys pending browser secrets; it cannot grant authority.\nconst LIVE_LINK = linkMatch(\n\t\"'browser_claimed'\",\n\t`(a.authority_kind = 'controller_attestation' OR\n (a.authority_kind = 'device_claim' AND a.controller_attestation_id IS NULL\n AND a.controller_review_receipt_id IS NULL AND a.controller_revision IS NULL AND a.link_id IS NULL))`,\n);\n\n/** Only the owned zero-row marker is a limit rejection, not counter failure. */\nfunction isBrowserAdmissionNoop(error: unknown): boolean {\n\treturn String(error).includes(\n\t\t\"NOT NULL constraint failed: coordinator_auth_account_connection_orders.coordinator_id\",\n\t);\n}\n/** Persistence capability only; consumed secrets are returned solely to a trusted exchange caller. */\nexport class CoordinatorAuthBrowserTransactions implements CoordinatorAuthBrowserTransactionStore {\n\tconstructor(\n\t\tprivate readonly backend: AuthLinkBackend,\n\t\tprivate readonly clock: () => number = Date.now,\n\t) {}\n\tprivate async first<T>(statement: AuthLinkStatement): Promise<T | null> {\n\t\ttry {\n\t\t\treturn await this.backend.first<T>(statement);\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_browser_transaction_persistence_error\");\n\t\t}\n\t}\n\tasync readAuthBrowserTransactionActivity(\n\t\tinput: { binderHash: string },\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): ReturnType<CoordinatorAuthBrowserTransactionStore[\"readAuthBrowserTransactionActivity\"]> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = capture(input, [\"binderHash\"]);\n\t\tif (!c || !i || !isHash(i.binderHash)) return { kind: \"rejected\", error: \"invalid_input\" };\n\t\tif (!c.enabled) return { kind: \"rejected\", error: \"auth_config_changed\" };\n\t\tconst now = authLinkNow(this.clock);\n\t\t// Shared-cookie activity includes management. Config drift fails closed even\n\t\t// for expired rows; unrelated coordinators never match.\n\t\tif (await hasConnectionSessionSchema(this.backend)) {\n\t\t\tconst management = await this.first<{ changed: number; active: number }>({\n\t\t\t\tsql: `SELECT (issuer <> ? OR auth_config_revision <> ?) AS changed,\n (state IN ('pending','browser_pending','consumed','verified','confirmed') AND expires_at_ms > ?) AS active\n FROM coordinator_account_change_attempts WHERE coordinator_id = ? AND binder_hash = ?`,\n\t\t\t\tvalues: [c.issuer, c.revision, now, c.coordinatorId, i.binderHash],\n\t\t\t});\n\t\t\tif (management?.changed) return { kind: \"rejected\", error: \"auth_config_changed\" };\n\t\t\tif (management?.active) return { kind: \"active\" };\n\t\t}\n\t\tconst row = await this.first<{ activity: string }>({\n\t\t\tsql: `SELECT CASE\n WHEN b.issuer <> ? OR b.auth_config_revision <> ? OR b.redirect_uri <> ? THEN 'config_changed'\n WHEN b.state = 'expired' OR b.expires_at_ms <= ? THEN 'inactive'\n WHEN b.purpose = 'signin' AND b.state = 'consumed' THEN 'inactive'\n WHEN b.purpose = 'link' AND EXISTS (SELECT 1 FROM coordinator_auth_link_attempts a\n WHERE a.coordinator_id = b.coordinator_id AND a.attempt_id = b.attempt_id\n AND a.browser_transaction_hash = b.browser_transaction_hash AND a.issuer = b.issuer\n AND a.auth_config_revision = b.auth_config_revision\n AND (a.state IN ('finalized','session_redeemed','failed','expired') OR a.expires_at_ms <= ?))\n THEN 'inactive' ELSE 'active' END AS activity\n FROM ${TABLE} b WHERE b.coordinator_id = ? AND b.binder_hash = ?`,\n\t\t\tvalues: [c.issuer, c.revision, c.redirectUri, now, now, c.coordinatorId, i.binderHash],\n\t\t});\n\t\tif (!row || row.activity === \"inactive\") return { kind: \"inactive\" };\n\t\tif (row.activity === \"active\") return { kind: \"active\" };\n\t\treturn { kind: \"rejected\", error: \"auth_config_changed\" };\n\t}\n\tasync startAuthBrowserTransaction(\n\t\tinput: CoordinatorAuthBrowserTransactionStartInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<CoordinatorAuthBrowserTransactionStartResult> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = captureStart(input);\n\t\tif (!c || !i) return rejected(\"invalid_input\");\n\t\tif (!c.enabled) return rejected(\"auth_config_changed\");\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst hash = transactionHash();\n\t\tif (i.purpose === \"link\") return this.startLink(i, c, now, hash, \"desktop\");\n\t\ttry {\n\t\t\tawait orderedBrowserStart(\n\t\t\t\tthis.backend,\n\t\t\t\t[\n\t\t\t\t\t{\n\t\t\t\t\t\tsql: `INSERT INTO ${TABLE} (${COLUMNS}) SELECT ?, ?, 'signin', NULL, ?, ?, ?, ?, ?, 'pending', ?, ?, ?, ?, NULL, NULL\n WHERE ${FRESH_HASH}\n AND NOT EXISTS (SELECT 1 FROM ${PURGE_FLOORS} WHERE coordinator_id = ? AND purged_through_created_at_ms > ?)\n AND (SELECT count(*) FROM ${TABLE} WHERE coordinator_id = ? AND purpose = 'signin' AND created_at_ms > ?) < ?\n AND (SELECT count(*) FROM (SELECT 1 FROM ${TABLE} WHERE coordinator_id = ? AND purpose = 'signin' LIMIT ?)) < ?\n ${ASSERT_HASH_FRESH}`,\n\t\t\t\t\t\tvalues: [\n\t\t\t\t\t\t\tc.coordinatorId,\n\t\t\t\t\t\t\thash,\n\t\t\t\t\t\t\ti.stateHash,\n\t\t\t\t\t\t\ti.binderHash,\n\t\t\t\t\t\t\tc.issuer,\n\t\t\t\t\t\t\tc.revision,\n\t\t\t\t\t\t\tc.redirectUri,\n\t\t\t\t\t\t\ti.nonce,\n\t\t\t\t\t\t\ti.pkceVerifier,\n\t\t\t\t\t\t\tnow,\n\t\t\t\t\t\t\tnow + AUTH_BROWSER_TXN_TTL_MS,\n\t\t\t\t\t\t\t...freshValues(c, hash),\n\t\t\t\t\t\t\tc.coordinatorId,\n\t\t\t\t\t\t\tnow - AUTH_SIGNIN_TXN_WINDOW_MS,\n\t\t\t\t\t\t\tc.coordinatorId,\n\t\t\t\t\t\t\tnow - AUTH_SIGNIN_TXN_WINDOW_MS,\n\t\t\t\t\t\t\tAUTH_SIGNIN_TXN_MAX_STARTS_PER_WINDOW,\n\t\t\t\t\t\t\tc.coordinatorId,\n\t\t\t\t\t\t\tAUTH_SIGNIN_TXN_MAX_RETAINED,\n\t\t\t\t\t\t\tAUTH_SIGNIN_TXN_MAX_RETAINED,\n\t\t\t\t\t\t\tc.coordinatorId,\n\t\t\t\t\t\t\thash,\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tc.coordinatorId,\n\t\t\t\thash,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (isAuthControllerUniqueError(error)) return rejected(\"transaction_conflict\");\n\t\t\tif (!isBrowserAdmissionNoop(error))\n\t\t\t\tthrow authPersistenceError(error, \"auth_browser_transaction_persistence_error\");\n\t\t}\n\t\tconst row = await this.startedRow(i, c, hash, now);\n\t\tif (row) return { kind: \"started\", expiresAtMs: row.expires_at_ms };\n\t\tif (await this.hasConflict(i, c, hash)) return rejected(\"transaction_conflict\");\n\t\tif (await this.isSigninRetentionBlocked(c.coordinatorId, now))\n\t\t\treturn { kind: \"rejected\", error: \"clock_retention_blocked\" };\n\t\treturn rejected(\"transaction_limited\");\n\t}\n\tprivate async isSigninRetentionBlocked(coordinatorId: string, now: number): Promise<boolean> {\n\t\tconst row = await this.first({\n\t\t\tsql: `SELECT 1 FROM ${PURGE_FLOORS} WHERE coordinator_id = ? AND purged_through_created_at_ms > ?`,\n\t\t\tvalues: [coordinatorId, now - AUTH_SIGNIN_TXN_WINDOW_MS],\n\t\t});\n\t\treturn row !== null;\n\t}\n\tprivate async hasConflict(\n\t\ti: CoordinatorAuthBrowserTransactionStartInput,\n\t\tc: CoordinatorAuthBrowserConfig,\n\t\thash: string,\n\t): Promise<boolean> {\n\t\tconst row = await this.first({\n\t\t\tsql: `SELECT 1 FROM ${TABLE} WHERE coordinator_id = ? AND (state_hash = ? OR binder_hash = ? OR browser_transaction_hash = ?)\n UNION ALL SELECT 1 FROM coordinator_auth_link_attempts WHERE coordinator_id = ? AND browser_transaction_hash = ?\n UNION ALL SELECT 1 FROM coordinator_auth_session_receipts WHERE coordinator_id = ? AND browser_transaction_hash = ? LIMIT 1`,\n\t\t\tvalues: [\n\t\t\t\tc.coordinatorId,\n\t\t\t\ti.stateHash,\n\t\t\t\ti.binderHash,\n\t\t\t\thash,\n\t\t\t\tc.coordinatorId,\n\t\t\t\thash,\n\t\t\t\tc.coordinatorId,\n\t\t\t\thash,\n\t\t\t],\n\t\t});\n\t\treturn row !== null;\n\t}\n\tprivate async startedRow(\n\t\ti: CoordinatorAuthBrowserTransactionStartInput,\n\t\tc: CoordinatorAuthBrowserConfig,\n\t\thash: string,\n\t\tnow: number,\n\t): Promise<TransactionRow | null> {\n\t\tconst source = i.purpose === \"link\" ? await this.source(i.attemptId, c, now) : null;\n\t\treturn this.first<TransactionRow>({\n\t\t\tsql: `WITH matching_browser AS MATERIALIZED (SELECT b.* FROM ${TABLE} b WHERE ${MATCH_CONFIG} AND b.browser_transaction_hash = ?\n AND b.state_hash = ? AND b.binder_hash = ? AND b.nonce = ? AND b.pkce_verifier = ?\n AND b.purpose = ? AND b.attempt_id IS ? AND b.created_at_ms = ? AND b.state = 'pending' AND b.expires_at_ms > ?)\n SELECT b.* FROM matching_browser b WHERE ${linkMatch(\"'browser_claimed'\", source?.sql)}`,\n\t\t\tvalues: [\n\t\t\t\t...configValues(c),\n\t\t\t\thash,\n\t\t\t\ti.stateHash,\n\t\t\t\ti.binderHash,\n\t\t\t\ti.nonce,\n\t\t\t\ti.pkceVerifier,\n\t\t\t\ti.purpose,\n\t\t\t\ti.purpose === \"link\" ? i.attemptId : null,\n\t\t\t\tnow,\n\t\t\t\tnow,\n\t\t\t\t...(source?.values ?? []),\n\t\t\t\tnow,\n\t\t\t],\n\t\t});\n\t}\n\t/** The user code hash selects one pending headless attempt; desktop attempts never match. */\n\tasync startHeadlessAuthLinkBrowserTransaction(\n\t\tinput: CoordinatorAuthHeadlessBrowserStartInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<CoordinatorAuthHeadlessBrowserStartResult> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = captureHeadlessStart(input);\n\t\tif (!c || !i) return rejected(\"invalid_input\");\n\t\tif (!c.enabled) return rejected(\"auth_config_changed\");\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst hash = transactionHash();\n\t\tconst attempt = await this.first<{ attempt_id: string }>({\n\t\t\tsql: `SELECT attempt_id FROM coordinator_auth_link_attempts WHERE coordinator_id = ? AND browser_start_hash = ?\n AND loopback_redirect = ${AUTH_LINK_HEADLESS_MARKER_SQL} AND state = 'pending' AND expires_at_ms > ?`,\n\t\t\tvalues: [c.coordinatorId, i.userCodeHash, now],\n\t\t});\n\t\tif (!attempt || !isAuthControllerId(attempt.attempt_id)) return rejected(\"attempt_unavailable\");\n\t\tconst { userCodeHash, ...materials } = i;\n\t\tconst link = {\n\t\t\t...materials,\n\t\t\tpurpose: \"link\" as const,\n\t\t\tattemptId: attempt.attempt_id,\n\t\t\tbrowserStartHash: userCodeHash,\n\t\t};\n\t\tconst started = await this.startLink(link, c, now, hash, \"headless\");\n\t\tif (started.kind !== \"started\") return started;\n\t\treturn { ...started, attemptId: attempt.attempt_id };\n\t}\n\tprivate async startLink(\n\t\ti: CoordinatorAuthBrowserTransactionStartInput & { purpose: \"link\" },\n\t\tc: CoordinatorAuthBrowserConfig,\n\t\tnow: number,\n\t\thash: string,\n\t\tmode: LinkMode,\n\t): Promise<CoordinatorAuthBrowserTransactionStartResult> {\n\t\tconst { source, claimSource } = await this.linkSources(i.attemptId, c, now, mode);\n\t\tconst insert: AuthLinkStatement = {\n\t\t\tsql: `INSERT INTO ${TABLE} (${COLUMNS}) SELECT a.coordinator_id, ?, 'link', a.attempt_id, ?, ?, a.issuer,\n a.auth_config_revision, ?, 'pending', ?, ?, ?, a.expires_at_ms, NULL, NULL FROM coordinator_auth_link_attempts a\n WHERE a.coordinator_id = ? AND a.attempt_id = ? AND a.issuer = ? AND a.auth_config_revision = ?\n AND ${source.sql}\n AND a.state = 'pending' AND a.browser_transaction_hash IS NULL AND a.expires_at_ms > ?\n AND ((a.browser_start_hash IS NULL AND ? IS NULL) OR a.browser_start_hash = ?) AND ${FRESH_HASH}\n ${ASSERT_HASH_FRESH}`,\n\t\t\tvalues: [\n\t\t\t\thash,\n\t\t\t\ti.stateHash,\n\t\t\t\ti.binderHash,\n\t\t\t\tc.redirectUri,\n\t\t\t\ti.nonce,\n\t\t\t\ti.pkceVerifier,\n\t\t\t\tnow,\n\t\t\t\tc.coordinatorId,\n\t\t\t\ti.attemptId,\n\t\t\t\tc.issuer,\n\t\t\t\tc.revision,\n\t\t\t\t...source.values,\n\t\t\t\tnow,\n\t\t\t\ti.browserStartHash ?? null,\n\t\t\t\ti.browserStartHash ?? null,\n\t\t\t\t...freshValues(c, hash),\n\t\t\t\tc.coordinatorId,\n\t\t\t\thash,\n\t\t\t],\n\t\t};\n\t\tconst claim: AuthLinkStatement = {\n\t\t\tsql: `UPDATE coordinator_auth_link_attempts SET state = 'browser_claimed', browser_transaction_hash = ?, claimed_at_ms = ?\n WHERE coordinator_id = ? AND attempt_id = ? AND issuer = ? AND auth_config_revision = ?\n AND ${claimSource.sql}\n AND state = 'pending' AND browser_transaction_hash IS NULL AND expires_at_ms > ?\n AND ((browser_start_hash IS NULL AND ? IS NULL) OR browser_start_hash = ?)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_session_receipts r WHERE r.coordinator_id = ? AND r.browser_transaction_hash = ?)\n AND EXISTS (SELECT 1 FROM ${TABLE} b WHERE ${MATCH_CONFIG} AND b.browser_transaction_hash = ? AND b.attempt_id = ?\n AND b.purpose = 'link' AND b.state = 'pending' AND b.state_hash = ? AND b.binder_hash = ? AND b.created_at_ms = ?\n AND b.expires_at_ms = coordinator_auth_link_attempts.expires_at_ms)`,\n\t\t\tvalues: [\n\t\t\t\thash,\n\t\t\t\tnow,\n\t\t\t\tc.coordinatorId,\n\t\t\t\ti.attemptId,\n\t\t\t\tc.issuer,\n\t\t\t\tc.revision,\n\t\t\t\t...claimSource.values,\n\t\t\t\tnow,\n\t\t\t\ti.browserStartHash ?? null,\n\t\t\t\ti.browserStartHash ?? null,\n\t\t\t\tc.coordinatorId,\n\t\t\t\thash,\n\t\t\t\t...configValues(c),\n\t\t\t\thash,\n\t\t\t\ti.attemptId,\n\t\t\t\ti.stateHash,\n\t\t\t\ti.binderHash,\n\t\t\t\tnow,\n\t\t\t],\n\t\t};\n\t\tconst assertion = assertLinkClaim(i, c, now, hash);\n\t\tconst failure = await this.persistLinkStart([insert, claim, assertion], c.coordinatorId, hash);\n\t\tif (failure) return failure;\n\t\treturn this.startLinkReceipt(i, c, now, hash);\n\t}\n\tprivate async linkSources(\n\t\tattemptId: string,\n\t\tc: CoordinatorAuthBrowserConfig,\n\t\tnow: number,\n\t\tmode: LinkMode,\n\t): Promise<{ source: AuthLinkStatement; claimSource: AuthLinkStatement }> {\n\t\tconst table = \"coordinator_auth_link_attempts\";\n\t\treturn {\n\t\t\tsource: withLinkMode(await this.source(attemptId, c, now), \"a\", mode),\n\t\t\tclaimSource: withLinkMode(await this.source(attemptId, c, now, table), table, mode),\n\t\t};\n\t}\n\tprivate async persistLinkStart(\n\t\tstatements: AuthLinkStatement[],\n\t\tcoordinator: string,\n\t\thash: string,\n\t) {\n\t\ttry {\n\t\t\tawait orderedBrowserStart(this.backend, statements, coordinator, hash);\n\t\t} catch (error) {\n\t\t\tif (isAuthControllerUniqueError(error)) return rejected(\"transaction_conflict\");\n\t\t\tthrow authPersistenceError(error, \"auth_browser_transaction_persistence_incomplete\");\n\t\t}\n\t\treturn null;\n\t}\n\tprivate async source(\n\t\tattemptId: string,\n\t\tc: CoordinatorAuthBrowserConfig,\n\t\tnow: number,\n\t\talias: \"a\" | \"coordinator_auth_link_attempts\" = \"a\",\n\t) {\n\t\ttry {\n\t\t\tif (this.backend.prepareAuthLinkSource)\n\t\t\t\treturn await this.backend.prepareAuthLinkSource(attemptId, c, now, alias);\n\t\t\treturn await captureAuthLinkSource(this.backend, attemptId, c, now, alias);\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_browser_transaction_persistence_error\");\n\t\t}\n\t}\n\tprivate async browserSource(\n\t\ti: { binderHash: string; stateHash?: string; attemptId?: string },\n\t\tc: CoordinatorAuthBrowserConfig,\n\t\tnow: number,\n\t): Promise<AuthLinkStatement> {\n\t\ttry {\n\t\t\tif (this.backend.prepareAuthLinkBrowserSource)\n\t\t\t\treturn await this.backend.prepareAuthLinkBrowserSource(i, c, now);\n\t\t\treturn await captureAuthLinkBrowserSource(this.backend, i, c, now);\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_browser_transaction_persistence_error\");\n\t\t}\n\t}\n\tprivate async startLinkReceipt(\n\t\ti: CoordinatorAuthBrowserTransactionStartInput & { purpose: \"link\" },\n\t\tc: CoordinatorAuthBrowserConfig,\n\t\tnow: number,\n\t\thash: string,\n\t): Promise<CoordinatorAuthBrowserTransactionStartResult> {\n\t\tconst row = await this.startedRow(i, c, hash, now);\n\t\tif (row) return { kind: \"started\", expiresAtMs: row.expires_at_ms };\n\t\tif (await this.hasConflict(i, c, hash)) return rejected(\"transaction_conflict\");\n\t\treturn this.diagnoseAttempt(i.attemptId, c, now);\n\t}\n\tprivate async diagnoseAttempt(\n\t\tattemptId: string,\n\t\tc: CoordinatorAuthBrowserConfig,\n\t\tnow: number,\n\t): Promise<CoordinatorAuthBrowserTransactionRejected> {\n\t\tconst attempt = await this.first<AttemptDiagnosis>({\n\t\t\tsql: \"SELECT issuer, auth_config_revision, state, expires_at_ms FROM coordinator_auth_link_attempts WHERE coordinator_id = ? AND attempt_id = ? AND authority_kind IN ('controller_attestation','device_claim')\",\n\t\t\tvalues: [c.coordinatorId, attemptId],\n\t\t});\n\t\tif (!attempt) return rejected(\"attempt_unavailable\");\n\t\tif (attempt.state === \"expired\" || attempt.expires_at_ms <= now)\n\t\t\treturn rejected(\"attempt_expired\");\n\t\tif (attempt.issuer !== c.issuer || attempt.auth_config_revision !== c.revision)\n\t\t\treturn rejected(\"auth_config_changed\");\n\t\treturn rejected(\"attempt_unavailable\");\n\t}\n\tasync consumeAuthBrowserTransaction(\n\t\tinput: CoordinatorAuthBrowserTransactionConsumeInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<CoordinatorAuthBrowserTransactionConsumeResult> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = capture(input, [\"stateHash\", \"binderHash\"]);\n\t\tif (!c || !i || !isHash(i.stateHash) || !isHash(i.binderHash)) return rejected(\"invalid_input\");\n\t\tif (!c.enabled) return rejected(\"auth_config_changed\");\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst source = await this.browserSource(\n\t\t\t{ stateHash: i.stateHash, binderHash: i.binderHash },\n\t\t\tc,\n\t\t\tnow,\n\t\t);\n\t\tconst liveLink = linkMatch(\"'browser_claimed'\", source.sql);\n\t\tconst row = await this.first<TransactionRow>({\n\t\t\tsql: `WITH matching_browser AS MATERIALIZED (SELECT b.* FROM ${TABLE} b WHERE ${MATCH_CONFIG} AND b.state_hash = ? AND b.binder_hash = ?\n AND b.state = 'pending' AND b.expires_at_ms > ? AND b.created_at_ms <= ?) SELECT b.* FROM matching_browser b WHERE ${liveLink}`,\n\t\t\tvalues: [...configValues(c), i.stateHash, i.binderHash, now, now, ...source.values, now],\n\t\t});\n\t\tif (!row) return this.diagnoseTransactionConfig(i.stateHash, i.binderHash, c);\n\t\tif (!isConsumableRow(row)) return rejected(\"transaction_unavailable\");\n\t\tconst token = claimToken();\n\t\ttry {\n\t\t\tawait this.backend.run({\n\t\t\t\tsql: `UPDATE ${TABLE} AS b SET state = 'consumed', nonce = NULL, pkce_verifier = NULL, claim_token = ?, consumed_at_ms = ?\n WHERE (${MATCH_CONFIG}) AND (b.browser_transaction_hash = ? AND b.state_hash = ? AND b.binder_hash = ?)\n AND (b.purpose = ? AND b.attempt_id IS ? AND b.state = 'pending' AND b.expires_at_ms > ? AND b.created_at_ms <= ?) AND (b.nonce = ? AND b.pkce_verifier = ?) AND ${liveLink}`,\n\t\t\t\tvalues: [\n\t\t\t\t\ttoken,\n\t\t\t\t\tnow,\n\t\t\t\t\t...configValues(c),\n\t\t\t\t\trow.browser_transaction_hash,\n\t\t\t\t\ti.stateHash,\n\t\t\t\t\ti.binderHash,\n\t\t\t\t\trow.purpose,\n\t\t\t\t\trow.attempt_id,\n\t\t\t\t\tnow,\n\t\t\t\t\tnow,\n\t\t\t\t\trow.nonce,\n\t\t\t\t\trow.pkce_verifier,\n\t\t\t\t\t...source.values,\n\t\t\t\t\tnow,\n\t\t\t\t],\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_browser_transaction_persistence_error\");\n\t\t}\n\t\tconst winner = await this.first({\n\t\t\tsql: `SELECT 1 FROM ${TABLE} WHERE coordinator_id = ? AND browser_transaction_hash = ? AND state = 'consumed' AND claim_token = ?`,\n\t\t\tvalues: [c.coordinatorId, row.browser_transaction_hash, token],\n\t\t});\n\t\tif (!winner) return rejected(\"transaction_unavailable\");\n\t\tconst materials = {\n\t\t\tkind: \"consumed\" as const,\n\t\t\tbrowserTransactionHash: row.browser_transaction_hash,\n\t\t\tnonce: row.nonce,\n\t\t\tpkceVerifier: row.pkce_verifier,\n\t\t};\n\t\tif (row.purpose === \"link\" && row.attempt_id !== null)\n\t\t\treturn { ...materials, purpose: \"link\", attemptId: row.attempt_id };\n\t\tif (row.purpose === \"signin\") return { ...materials, purpose: \"signin\" };\n\t\treturn rejected(\"transaction_unavailable\");\n\t}\n\tasync readAuthBrowserTransactionPurpose(\n\t\tinput: CoordinatorAuthBrowserTransactionConsumeInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<CoordinatorAuthBrowserTransactionPurpose | null> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = capture(input, [\"stateHash\", \"binderHash\"]);\n\t\tif (!c?.enabled || !i || !isHash(i.stateHash) || !isHash(i.binderHash)) return null;\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst source = await this.browserSource(\n\t\t\t{ stateHash: i.stateHash, binderHash: i.binderHash },\n\t\t\tc,\n\t\t\tnow,\n\t\t);\n\t\tconst row = await this.first<{ purpose: string }>({\n\t\t\tsql: `WITH matching_browser AS MATERIALIZED (SELECT b.* FROM ${TABLE} b WHERE ${MATCH_CONFIG} AND b.state_hash = ? AND b.binder_hash = ?\n AND b.state = 'pending' AND b.expires_at_ms > ? AND b.created_at_ms <= ?) SELECT b.purpose FROM matching_browser b WHERE (b.purpose <> 'link' OR ${linkMatch(\"'browser_claimed'\", source.sql)})`,\n\t\t\tvalues: [...configValues(c), i.stateHash, i.binderHash, now, now, ...source.values, now],\n\t\t});\n\t\tif (row?.purpose === \"signin\" || row?.purpose === \"link\" || row?.purpose === \"owner_enroll\")\n\t\t\treturn row.purpose;\n\t\treturn null;\n\t}\n\tprivate async diagnoseTransactionConfig(\n\t\tstateHash: string,\n\t\tbinderHash: string,\n\t\tc: CoordinatorAuthBrowserConfig,\n\t): Promise<CoordinatorAuthBrowserTransactionRejected> {\n\t\tconst row = await this.first<{\n\t\t\tissuer: string;\n\t\t\tauth_config_revision: string;\n\t\t\tredirect_uri: string;\n\t\t}>({\n\t\t\tsql: `SELECT issuer, auth_config_revision, redirect_uri FROM ${TABLE} WHERE coordinator_id = ? AND state_hash = ? AND binder_hash = ?`,\n\t\t\tvalues: [c.coordinatorId, stateHash, binderHash],\n\t\t});\n\t\tif (\n\t\t\trow &&\n\t\t\t(row.issuer !== c.issuer ||\n\t\t\t\trow.auth_config_revision !== c.revision ||\n\t\t\t\trow.redirect_uri !== c.redirectUri)\n\t\t)\n\t\t\treturn rejected(\"auth_config_changed\");\n\t\treturn rejected(\"transaction_unavailable\");\n\t}\n\tasync resolveAuthLinkBrowserTransaction(\n\t\tinput: CoordinatorAuthLinkBrowserTransactionResolveInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t): Promise<{ browserTransactionHash: string } | null> {\n\t\tconst c = captureConfig(config);\n\t\tconst i = capture(input, [\"attemptId\", \"binderHash\"]);\n\t\tif (!c || !i || !c.enabled || !isAuthControllerId(i.attemptId) || !isHash(i.binderHash))\n\t\t\treturn null;\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst source = await this.browserSource(\n\t\t\t{ attemptId: i.attemptId, binderHash: i.binderHash },\n\t\t\tc,\n\t\t\tnow,\n\t\t);\n\t\tconst row = await this.first<{ browser_transaction_hash: string }>({\n\t\t\tsql: `WITH matching_browser AS MATERIALIZED (SELECT b.* FROM ${TABLE} b WHERE ${MATCH_CONFIG} AND b.purpose = 'link'\n AND b.attempt_id = ? AND b.binder_hash = ? AND b.state IN ('pending','consumed') AND b.expires_at_ms > ?) SELECT b.browser_transaction_hash FROM matching_browser b WHERE ${linkMatch(\"'browser_claimed','oidc_verified','confirmed','finalized','session_redeemed'\", source.sql)}`,\n\t\t\tvalues: [...configValues(c), i.attemptId, i.binderHash, now, ...source.values, now],\n\t\t});\n\t\treturn row ? { browserTransactionHash: row.browser_transaction_hash } : null;\n\t}\n\tasync cancelAuthSigninBrowserTransaction(\n\t\tinput: CoordinatorAuthSigninBrowserTransactionCancelInput,\n\t\tscope: CoordinatorAuthBrowserTransactionScope,\n\t): Promise<CoordinatorAuthSigninBrowserTransactionCancelResult> {\n\t\tconst i = capture(input, [\"binderHash\"]);\n\t\tconst s = capture(scope, [\"coordinatorId\"]);\n\t\tif (!i || !isHash(i.binderHash) || !s || !isAuthControllerId(s.coordinatorId))\n\t\t\treturn { kind: \"rejected\", error: \"invalid_input\" };\n\t\tauthLinkNow(this.clock);\n\t\t// Explicit cookie-owner intent remains valid across clock rollback.\n\t\tconst match =\n\t\t\t\"coordinator_id = ? AND binder_hash = ? AND purpose = 'signin' AND attempt_id IS NULL\";\n\t\tconst values = [s.coordinatorId, i.binderHash];\n\t\ttry {\n\t\t\tawait this.backend.run({\n\t\t\t\tsql: `UPDATE ${TABLE} SET state = 'expired', nonce = NULL, pkce_verifier = NULL\n WHERE ${match} AND state = 'pending'`,\n\t\t\t\tvalues,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_browser_transaction_persistence_error\");\n\t\t}\n\t\tconst row = await this.first({\n\t\t\tsql: `SELECT 1 FROM ${TABLE} WHERE ${match} AND state = 'expired' AND nonce IS NULL AND pkce_verifier IS NULL`,\n\t\t\tvalues,\n\t\t});\n\t\treturn row ? { kind: \"cancelled\" } : { kind: \"unavailable\" };\n\t}\n\tasync retireAuthBrowserTransactions(\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t\toptions?: CoordinatorAuthBrowserTransactionRetirementOptions,\n\t): Promise<CoordinatorAuthBrowserTransactionRetirementResult> {\n\t\tconst c = captureConfig(config);\n\t\tconst o = captureRetirementOptions(options);\n\t\tif (!c || !o) return { kind: \"rejected\", error: \"invalid_input\" };\n\t\tconst now = authLinkNow(this.clock);\n\t\tconst attemptFilter = o.attemptId === undefined ? \"\" : \"AND b.attempt_id = ?\";\n\t\tconst attemptValues = o.attemptId === undefined ? [] : [o.attemptId];\n\t\tlet creationGuard = \"b.created_at_ms <= ?\";\n\t\tconst creationValues = [now];\n\t\tif (o.attemptId !== undefined) {\n\t\t\tcreationGuard = `(b.created_at_ms <= ? OR (b.purpose = 'link' AND NOT ${LIVE_LINK}))`;\n\t\t\tcreationValues.push(now);\n\t\t}\n\t\ttry {\n\t\t\tconst processedCount = await this.backend.run({\n\t\t\t\tsql: `UPDATE ${TABLE} SET state = 'expired', nonce = NULL, pkce_verifier = NULL\n WHERE coordinator_id = ? AND purpose IN ('signin','link') AND state = 'pending' AND browser_transaction_hash IN\n (SELECT b.browser_transaction_hash FROM ${TABLE} b\n WHERE b.coordinator_id = ? AND b.purpose IN ('signin','link') AND b.state = 'pending' AND ${creationGuard} ${attemptFilter}\n AND (b.expires_at_ms <= ? OR ? = 0 OR b.issuer <> ? OR b.auth_config_revision <> ? OR b.redirect_uri <> ?\n OR (b.purpose = 'link' AND NOT ${LIVE_LINK}))\n ORDER BY b.expires_at_ms, b.browser_transaction_hash LIMIT ?)`,\n\t\t\t\tvalues: [\n\t\t\t\t\tc.coordinatorId,\n\t\t\t\t\tc.coordinatorId,\n\t\t\t\t\t...creationValues,\n\t\t\t\t\t...attemptValues,\n\t\t\t\t\tnow,\n\t\t\t\t\tNumber(c.enabled),\n\t\t\t\t\tc.issuer,\n\t\t\t\t\tc.revision,\n\t\t\t\t\tc.redirectUri,\n\t\t\t\t\tnow,\n\t\t\t\t\to.limit,\n\t\t\t\t],\n\t\t\t});\n\t\t\treturn { kind: \"retired\", processedCount, more: processedCount === o.limit };\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_browser_transaction_persistence_error\");\n\t\t}\n\t}\n\tasync purgeAuthSigninBrowserTransactions(\n\t\tscope: CoordinatorAuthBrowserTransactionScope,\n\t\toptions?: CoordinatorAuthBrowserTransactionMaintenanceOptions,\n\t): Promise<CoordinatorAuthSigninBrowserTransactionPurgeResult> {\n\t\tconst s = capture(scope, [\"coordinatorId\"]);\n\t\tconst limit = maintenanceLimit(options, AUTH_SIGNIN_TXN_PURGE_BATCH_MAX);\n\t\tif (!s || !isAuthControllerId(s.coordinatorId) || limit === null)\n\t\t\treturn { kind: \"rejected\", error: \"invalid_input\" };\n\t\tconst cutoff = authLinkNow(this.clock) - AUTH_SIGNIN_TXN_PURGE_AGE_MS;\n\t\ttry {\n\t\t\t// Commit the monotonic floor first; the delete independently reads it atomically.\n\t\t\tawait this.advanceSigninPurgeFloor(s.coordinatorId, cutoff);\n\t\t\tconst processedCount = await this.deletePurgedSigninTransactions(\n\t\t\t\ts.coordinatorId,\n\t\t\t\tcutoff,\n\t\t\t\tlimit,\n\t\t\t);\n\t\t\treturn { kind: \"purged\", processedCount, more: processedCount === limit };\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_browser_transaction_persistence_error\");\n\t\t}\n\t}\n\tprivate advanceSigninPurgeFloor(coordinatorId: string, cutoff: number): Promise<number> {\n\t\treturn this.backend.run({\n\t\t\tsql: `INSERT INTO ${PURGE_FLOORS} (coordinator_id, purged_through_created_at_ms)\n SELECT ?, m FROM (SELECT max(created_at_ms) m FROM ${TABLE}\n WHERE coordinator_id = ? AND purpose = 'signin' AND attempt_id IS NULL AND created_at_ms <= ?)\n WHERE m IS NOT NULL ON CONFLICT(coordinator_id) DO UPDATE\n SET purged_through_created_at_ms = excluded.purged_through_created_at_ms\n WHERE excluded.purged_through_created_at_ms > ${PURGE_FLOORS}.purged_through_created_at_ms`,\n\t\t\tvalues: [coordinatorId, coordinatorId, cutoff],\n\t\t});\n\t}\n\tprivate deletePurgedSigninTransactions(\n\t\tcoordinatorId: string,\n\t\tcutoff: number,\n\t\tlimit: number,\n\t): Promise<number> {\n\t\treturn this.backend.run({\n\t\t\tsql: `DELETE FROM ${TABLE}\n WHERE coordinator_id = ? AND purpose = 'signin' AND attempt_id IS NULL AND created_at_ms <= ?\n AND browser_transaction_hash IN (SELECT b.browser_transaction_hash FROM ${TABLE} b\n JOIN ${PURGE_FLOORS} f ON f.coordinator_id = b.coordinator_id\n WHERE b.coordinator_id = ? AND b.purpose = 'signin' AND b.attempt_id IS NULL\n AND b.created_at_ms <= f.purged_through_created_at_ms AND b.created_at_ms <= ?\n ORDER BY b.created_at_ms, b.browser_transaction_hash LIMIT ?)`,\n\t\t\tvalues: [coordinatorId, cutoff, coordinatorId, cutoff, limit],\n\t\t});\n\t}\n\tasync maintainAuthBrowserTransactions(\n\t\tscope: CoordinatorAuthBrowserTransactionScope,\n\t\toptions?: CoordinatorAuthBrowserTransactionMaintenanceOptions,\n\t): Promise<CoordinatorAuthBrowserTransactionMaintenanceResult> {\n\t\tconst s = capture(scope, [\"coordinatorId\"]);\n\t\tconst limit = maintenanceLimit(options);\n\t\tif (!s || !isAuthControllerId(s.coordinatorId) || limit === null)\n\t\t\treturn { kind: \"rejected\", error: \"invalid_input\" };\n\t\tconst now = authLinkNow(this.clock);\n\t\ttry {\n\t\t\t// Global expiry may burn expired owner secrets; link/config retirement must not.\n\t\t\tconst processedCount = await this.backend.run({\n\t\t\t\tsql: `UPDATE ${TABLE} SET state = 'expired', nonce = NULL, pkce_verifier = NULL\n WHERE coordinator_id = ? AND state = 'pending' AND expires_at_ms <= ? AND browser_transaction_hash IN\n (SELECT browser_transaction_hash FROM ${TABLE} WHERE coordinator_id = ? AND state = 'pending' AND expires_at_ms <= ?\n ORDER BY expires_at_ms, browser_transaction_hash LIMIT ?)`,\n\t\t\t\tvalues: [s.coordinatorId, now, s.coordinatorId, now, limit],\n\t\t\t});\n\t\t\treturn { kind: \"maintained\", processedCount, more: processedCount === limit };\n\t\t} catch (error) {\n\t\t\tthrow authPersistenceError(error, \"auth_browser_transaction_persistence_error\");\n\t\t}\n\t}\n}\n","import { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport { hashEd25519KeyId } from \"./coordinator-ed25519-key-id.js\";\nimport {\n\ted25519KeyIdForRevocation,\n\tparseSshEd25519PublicKeyForRevocation,\n} from \"./coordinator-ed25519-key-id-compat.js\";\n\nexport interface CoordinatorDeviceRevocationRecord {\n\treadonly subject_kind: \"device_id\" | \"ed25519_key\";\n\treadonly subject_value: string;\n\treadonly revocation_id: string;\n\treadonly evidence_group_id: string;\n\treadonly evidence_device_id: string;\n\treadonly evidence_public_key: string;\n\treadonly evidence_fingerprint: string;\n\treadonly actor_id: string | null;\n\treadonly created_at: string;\n}\n\nexport interface CoordinatorCreateDeviceRevocationInput {\n\tgroupId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n\t/** Audit evidence only; this internal capability requires a trusted caller. */\n\tactorId?: string | null;\n}\nexport interface CoordinatorListDeviceRevocationsInput {\n\tdeviceId?: string;\n\tpublicKey?: string;\n}\nexport interface CoordinatorRecordAuthorizedNonceInput {\n\tgroupId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tnonce: string;\n\tcreatedAt: string;\n}\nexport type CoordinatorCreateDeviceRevocationResult =\n\t| { kind: \"revoked\"; records: CoordinatorDeviceRevocationRecord[] }\n\t| { kind: \"rejected\"; error: \"invalid_input\" | \"enrollment_mismatch\" };\nexport type CoordinatorAuthorizedNonceResult =\n\t| \"recorded\"\n\t| \"nonce_replay\"\n\t| \"device_revoked\"\n\t| \"unknown_device\"\n\t| \"device_disabled\"\n\t| \"group_not_found\"\n\t| \"group_archived\";\n\nexport interface CoordinatorDeviceRevocationStore {\n\tcreateDeviceRevocation(\n\t\tinput: CoordinatorCreateDeviceRevocationInput,\n\t): Promise<CoordinatorCreateDeviceRevocationResult>;\n\tlistDeviceRevocations(\n\t\tinput: CoordinatorListDeviceRevocationsInput,\n\t): Promise<CoordinatorDeviceRevocationRecord[]>;\n\trecordAuthorizedNonce(\n\t\tinput: CoordinatorRecordAuthorizedNonceInput,\n\t): Promise<CoordinatorAuthorizedNonceResult>;\n}\n\nexport const DEVICE_REVOCATION_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS coordinator_device_revocations (\n subject_kind TEXT NOT NULL CHECK(subject_kind IN ('device_id', 'ed25519_key')),\n subject_value TEXT NOT NULL CHECK(\n (subject_kind = 'device_id' AND length(subject_value) BETWEEN 1 AND 256) OR\n (subject_kind = 'ed25519_key' AND length(subject_value) = 64\n AND subject_value NOT GLOB '*[^a-f0-9]*')),\n revocation_id TEXT NOT NULL,\n evidence_group_id TEXT NOT NULL,\n evidence_device_id TEXT NOT NULL,\n evidence_public_key TEXT NOT NULL,\n evidence_fingerprint TEXT NOT NULL,\n actor_id TEXT,\n created_at TEXT NOT NULL,\n PRIMARY KEY (subject_kind, subject_value)\n);\n`;\n\ninterface RevocationStatement {\n\tsql: string;\n\tvalues: (string | null)[];\n\tread?: boolean;\n}\nexport interface DeviceRevocationBackend {\n\t/** All statements, including reads, execute in one transaction. */\n\tbatch(statements: RevocationStatement[]): Promise<unknown[]>;\n\tall(statement: RevocationStatement): Promise<unknown>;\n}\n\nconst INVALID_SCALAR = Symbol(\"invalid_input\");\nfunction own(input: unknown, key: string): unknown {\n\tif (!input || typeof input !== \"object\" || Array.isArray(input)) return undefined;\n\tconst descriptor = Object.getOwnPropertyDescriptor(input, key);\n\tif (!descriptor) return undefined;\n\treturn \"value\" in descriptor ? descriptor.value : INVALID_SCALAR;\n}\nfunction exactText(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length > 0 && !value.includes(\"\\0\");\n}\nfunction captureRevocation(\n\tinput: unknown,\n): Readonly<Required<CoordinatorCreateDeviceRevocationInput>> | null {\n\tconst groupId = own(input, \"groupId\"),\n\t\tdeviceId = own(input, \"deviceId\");\n\tconst publicKey = own(input, \"publicKey\"),\n\t\tfingerprint = own(input, \"fingerprint\");\n\tconst actorId = own(input, \"actorId\") ?? null;\n\tif (\n\t\t!isAuthControllerId(groupId) ||\n\t\t!isAuthControllerId(deviceId) ||\n\t\t!exactText(publicKey) ||\n\t\t!exactText(fingerprint) ||\n\t\t(actorId !== null && !isAuthControllerId(actorId))\n\t)\n\t\treturn null;\n\treturn Object.freeze({ groupId, deviceId, publicKey, fingerprint, actorId });\n}\nfunction captureNonce(input: unknown): Readonly<CoordinatorRecordAuthorizedNonceInput> {\n\tconst groupId = own(input, \"groupId\"),\n\t\tdeviceId = own(input, \"deviceId\");\n\tconst publicKey = own(input, \"publicKey\"),\n\t\tnonce = own(input, \"nonce\");\n\tconst createdAt = own(input, \"createdAt\");\n\tif (\n\t\t!exactText(groupId) ||\n\t\t!exactText(deviceId) ||\n\t\t!exactText(publicKey) ||\n\t\t!exactText(nonce) ||\n\t\t!exactText(createdAt)\n\t)\n\t\tthrow new Error(\"invalid_input\");\n\treturn Object.freeze({ groupId, deviceId, publicKey, nonce, createdAt });\n}\nfunction resultRows<T>(result: unknown): T[] {\n\tif (\n\t\t!result ||\n\t\ttypeof result !== \"object\" ||\n\t\t(\"success\" in result && result.success === false) ||\n\t\t!(\"results\" in result) ||\n\t\t!Array.isArray(result.results)\n\t)\n\t\tthrow new Error(\"device_revocation_incomplete\");\n\treturn result.results as T[];\n}\nfunction resultChanges(result: unknown): number {\n\tif (\n\t\t!result ||\n\t\ttypeof result !== \"object\" ||\n\t\t(\"success\" in result && result.success === false) ||\n\t\t!(\"meta\" in result) ||\n\t\t!result.meta ||\n\t\ttypeof result.meta !== \"object\" ||\n\t\t!(\"changes\" in result.meta) ||\n\t\t!Number.isSafeInteger(result.meta.changes) ||\n\t\t(result.meta.changes as number) < 0\n\t)\n\t\tthrow new Error(\"device_revocation_incomplete\");\n\treturn result.meta.changes as number;\n}\n\nfunction incompleteResult(): never {\n\tthrow new Error(\"device_revocation_incomplete\");\n}\n\nconst CURRENT_TUPLE_SQL = `SELECT 1 FROM enrolled_devices\nWHERE group_id = ? AND device_id = ? AND public_key = ? AND fingerprint = ?`;\n/** Bind the device ID and derived canonical key ID (or null), in that order. */\nexport const DEVICE_REVOCATION_SUBJECT_EXISTS_SQL = `EXISTS (\nSELECT 1 FROM coordinator_device_revocations WHERE\n(subject_kind = 'device_id' AND subject_value = ?) OR\n(subject_kind = 'ed25519_key' AND subject_value = ?))`;\nconst SUBJECTS_SQL = `SELECT * FROM coordinator_device_revocations WHERE\n(subject_kind = 'device_id' AND subject_value = ?) OR\n(subject_kind = 'ed25519_key' AND subject_value = ?)\nORDER BY subject_kind, subject_value`;\nconst NONCE_CONTEXT_SQL = `WITH input(group_id, device_id, public_key, nonce, created_at, key_id)\nAS (VALUES (?, ?, ?, ?, ?, ?))`;\nconst REVOKED_SQL = `EXISTS (SELECT 1 FROM coordinator_device_revocations r WHERE\n(r.subject_kind = 'device_id' AND r.subject_value = i.device_id) OR\n(r.subject_kind = 'ed25519_key' AND r.subject_value = i.key_id))`;\nconst AUTHORIZED_NONCE_SQL = `${NONCE_CONTEXT_SQL}\nINSERT INTO request_nonces(device_id, nonce, created_at)\nSELECT i.device_id, i.nonce, i.created_at FROM input i\nJOIN enrolled_devices e ON e.group_id = i.group_id AND e.device_id = i.device_id\nJOIN groups g ON g.group_id = i.group_id\nWHERE e.public_key = i.public_key AND e.enabled = 1 AND g.archived_at IS NULL\nAND NOT ${REVOKED_SQL}\nON CONFLICT(device_id, nonce) DO NOTHING`;\nconst NONCE_CLASSIFY_SQL = `${NONCE_CONTEXT_SQL}\nSELECT CASE\nWHEN ${REVOKED_SQL} THEN 'device_revoked'\nWHEN g.group_id IS NULL THEN 'group_not_found'\nWHEN g.archived_at IS NOT NULL THEN 'group_archived'\nWHEN e.device_id IS NULL OR e.public_key != i.public_key THEN 'unknown_device'\nWHEN e.enabled != 1 THEN 'device_disabled'\nELSE 'nonce_replay' END AS status\nFROM input i LEFT JOIN groups g ON g.group_id = i.group_id\nLEFT JOIN enrolled_devices e ON e.group_id = i.group_id AND e.device_id = i.device_id`;\n\nfunction revocationStatements(\n\tinput: Required<CoordinatorCreateDeviceRevocationInput>,\n\tkeyId: string | null,\n\tnow: string,\n): RevocationStatement[] {\n\tconst tuple = [input.groupId, input.deviceId, input.publicKey, input.fingerprint];\n\tconst subjects = [{ kind: \"device_id\", value: input.deviceId }];\n\tif (keyId) subjects.push({ kind: \"ed25519_key\", value: keyId });\n\tconst revocationId = globalThis.crypto.randomUUID();\n\tconst writes = subjects.map(({ kind, value }) => ({\n\t\tsql: `INSERT INTO coordinator_device_revocations(subject_kind, subject_value, revocation_id,\nevidence_group_id, evidence_device_id, evidence_public_key, evidence_fingerprint, actor_id, created_at)\nSELECT ?, ?, ?, ?, ?, ?, ?, ?, ? WHERE EXISTS (${CURRENT_TUPLE_SQL})\nON CONFLICT(subject_kind, subject_value) DO NOTHING`,\n\t\tvalues: [kind, value, revocationId, ...tuple, input.actorId, now, ...tuple],\n\t}));\n\treturn [\n\t\t{ sql: CURRENT_TUPLE_SQL, values: tuple, read: true },\n\t\t...writes,\n\t\t{ sql: SUBJECTS_SQL, values: [input.deviceId, keyId], read: true },\n\t];\n}\n\n/** Internal storage capability only. Removal of the current tuple prevents creation and retry. */\nexport class DeviceRevocationOperations implements CoordinatorDeviceRevocationStore {\n\tconstructor(\n\t\tprivate readonly backend: DeviceRevocationBackend,\n\t\tprivate readonly clock: () => number = Date.now,\n\t) {}\n\n\tasync createDeviceRevocation(\n\t\traw: CoordinatorCreateDeviceRevocationInput,\n\t): Promise<CoordinatorCreateDeviceRevocationResult> {\n\t\tconst input = captureRevocation(raw);\n\t\tif (!input) return { kind: \"rejected\", error: \"invalid_input\" };\n\t\tconst keyId = await ed25519KeyIdForRevocation(input.publicKey);\n\t\tconst statements = revocationStatements(input, keyId, new Date(this.clock()).toISOString());\n\t\tconst results = await this.backend.batch(statements).catch(incompleteResult);\n\t\tif (results.length !== statements.length) throw new Error(\"device_revocation_incomplete\");\n\t\tfor (const result of results.slice(1, -1)) resultChanges(result);\n\t\tif (resultRows(results[0]).length === 0)\n\t\t\treturn { kind: \"rejected\", error: \"enrollment_mismatch\" };\n\t\tconst records = resultRows<CoordinatorDeviceRevocationRecord>(results.at(-1));\n\t\tif (\n\t\t\t!records.some((r) => r.subject_kind === \"device_id\" && r.subject_value === input.deviceId) ||\n\t\t\t(keyId && !records.some((r) => r.subject_kind === \"ed25519_key\" && r.subject_value === keyId))\n\t\t)\n\t\t\tthrow new Error(\"device_revocation_incomplete\");\n\t\treturn { kind: \"revoked\", records };\n\t}\n\n\tasync listDeviceRevocations(\n\t\tinput: CoordinatorListDeviceRevocationsInput,\n\t): Promise<CoordinatorDeviceRevocationRecord[]> {\n\t\tconst deviceId = own(input, \"deviceId\"),\n\t\t\tpublicKey = own(input, \"publicKey\");\n\t\tif (\n\t\t\t(deviceId !== undefined && !isAuthControllerId(deviceId)) ||\n\t\t\t(publicKey !== undefined && !exactText(publicKey)) ||\n\t\t\t(deviceId === undefined && publicKey === undefined)\n\t\t)\n\t\t\tthrow new Error(\"invalid_input\");\n\t\tconst keyId =\n\t\t\tpublicKey === undefined ? null : await ed25519KeyIdForRevocation(publicKey as string);\n\t\treturn resultRows<CoordinatorDeviceRevocationRecord>(\n\t\t\tawait this.backend\n\t\t\t\t.all({\n\t\t\t\t\tsql: SUBJECTS_SQL,\n\t\t\t\t\tvalues: [(deviceId as string | undefined) ?? null, keyId],\n\t\t\t\t\tread: true,\n\t\t\t\t})\n\t\t\t\t.catch(incompleteResult),\n\t\t);\n\t}\n\n\tasync recordAuthorizedNonce(\n\t\traw: CoordinatorRecordAuthorizedNonceInput,\n\t): Promise<CoordinatorAuthorizedNonceResult> {\n\t\tconst input = captureNonce(raw);\n\t\tconst parsedKey = parseSshEd25519PublicKeyForRevocation(input.publicKey);\n\t\tif (parsedKey.kind === \"malformed_ed25519\") return \"unknown_device\";\n\t\tconst keyId = await hashEd25519KeyId(parsedKey);\n\t\tconst values = [\n\t\t\tinput.groupId,\n\t\t\tinput.deviceId,\n\t\t\tinput.publicKey,\n\t\t\tinput.nonce,\n\t\t\tinput.createdAt,\n\t\t\tkeyId,\n\t\t];\n\t\tconst results = await this.backend\n\t\t\t.batch([\n\t\t\t\t{ sql: AUTHORIZED_NONCE_SQL, values },\n\t\t\t\t{ sql: NONCE_CLASSIFY_SQL, values, read: true },\n\t\t\t])\n\t\t\t.catch(incompleteResult);\n\t\tif (results.length !== 2) throw new Error(\"device_revocation_incomplete\");\n\t\tconst changes = resultChanges(results[0]);\n\t\tconst rows = resultRows<{ status: CoordinatorAuthorizedNonceResult }>(results[1]);\n\t\tif (rows.length !== 1 || changes > 1) throw new Error(\"device_revocation_incomplete\");\n\t\tif (changes === 1) return \"recorded\";\n\t\tconst status = rows[0]?.status;\n\t\tif (\n\t\t\t!status ||\n\t\t\t![\n\t\t\t\t\"nonce_replay\",\n\t\t\t\t\"device_revoked\",\n\t\t\t\t\"unknown_device\",\n\t\t\t\t\"device_disabled\",\n\t\t\t\t\"group_not_found\",\n\t\t\t\t\"group_archived\",\n\t\t\t].includes(status)\n\t\t)\n\t\t\tthrow new Error(\"device_revocation_incomplete\");\n\t\treturn status;\n\t}\n}\n","import { DEVICE_REVOCATION_SUBJECT_EXISTS_SQL } from \"./coordinator-device-revocation.js\";\nimport type {\n\tCoordinatorBootstrapGrant,\n\tCoordinatorBootstrapGrantAuthorizationError,\n\tCoordinatorBootstrapGrantAuthorizationInput,\n\tCoordinatorBootstrapGrantAuthorizationResult,\n\tCoordinatorEnrollment,\n} from \"./coordinator-store-contract.js\";\n\nconst ENROLLMENT_FIELDS = [\n\t\"group_id\",\n\t\"device_id\",\n\t\"public_key\",\n\t\"fingerprint\",\n\t\"identity_id\",\n\t\"display_name\",\n\t\"enabled\",\n\t\"created_at\",\n] as const;\ntype EnrollmentFields = Pick<CoordinatorEnrollment, (typeof ENROLLMENT_FIELDS)[number]>;\ntype ParticipantAliases<P extends string> = {\n\t[K in keyof EnrollmentFields as `${P}_${K}`]: EnrollmentFields[K] | null;\n};\nexport type BootstrapAuthorizationRow = CoordinatorBootstrapGrant &\n\tParticipantAliases<\"seed_enrollment\"> &\n\tParticipantAliases<\"worker_enrollment\"> & {\n\t\ttarget_group_id: string | null;\n\t\tarchived_at: string | null;\n\t\tstatus?: CoordinatorBootstrapGrantAuthorizationError | \"authorized\";\n\t};\n\nconst COLUMNS_SQL = `b.grant_id, b.group_id, b.seed_device_id, b.worker_device_id,\nb.expires_at, b.created_at, b.created_by, b.revoked_at,\ng.group_id AS target_group_id, g.archived_at,\n${ENROLLMENT_FIELDS.map((f) => `s.${f} AS seed_enrollment_${f}, w.${f} AS worker_enrollment_${f}`).join(\", \")}`;\nconst JOINS_SQL = `FROM coordinator_bootstrap_grants b\nLEFT JOIN groups g ON g.group_id = b.group_id\nLEFT JOIN enrolled_devices s ON s.group_id = b.group_id AND s.device_id = b.seed_device_id\nLEFT JOIN enrolled_devices w ON w.group_id = b.group_id AND w.device_id = b.worker_device_id`;\nexport const BOOTSTRAP_AUTHORIZATION_SOURCE_SQL = `SELECT ${COLUMNS_SQL}\n${JOINS_SQL} WHERE b.grant_id = ?`;\n\nfunction own(input: unknown, key: string): unknown {\n\tif (!input || typeof input !== \"object\" || Array.isArray(input)) return undefined;\n\tconst descriptor = Object.getOwnPropertyDescriptor(input, key);\n\tif (!descriptor) return undefined;\n\tif (!(\"value\" in descriptor)) throw new Error(\"invalid_input\");\n\treturn descriptor.value;\n}\nfunction text(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length > 0 && !value.includes(\"\\0\");\n}\n\n/** Capture every caller-owned primitive before even the source read can yield. */\nexport function captureBootstrapAuthorizationInput(\n\traw: unknown,\n): CoordinatorBootstrapGrantAuthorizationInput {\n\tconst grantId = own(raw, \"grantId\"),\n\t\tnowMs = own(raw, \"nowMs\");\n\tif (!text(grantId) || typeof nowMs !== \"number\" || !Number.isSafeInteger(nowMs) || nowMs < 0)\n\t\tthrow new Error(\"invalid_input\");\n\tconst expectation = own(raw, \"expectedSeed\");\n\tif (expectation === undefined) return { grantId, nowMs };\n\tconst groupId = own(expectation, \"groupId\"),\n\t\tdeviceId = own(expectation, \"deviceId\");\n\tconst publicKey = own(expectation, \"publicKey\"),\n\t\tfingerprint = own(expectation, \"fingerprint\");\n\tif (!text(groupId) || !text(deviceId) || !text(publicKey) || !text(fingerprint))\n\t\tthrow new Error(\"invalid_input\");\n\treturn { grantId, nowMs, expectedSeed: { groupId, deviceId, publicKey, fingerprint } };\n}\n\nexport function rejectBootstrapAuthorization(\n\terror: CoordinatorBootstrapGrantAuthorizationError,\n): CoordinatorBootstrapGrantAuthorizationResult {\n\treturn { kind: \"rejected\", error };\n}\n\nexport function bootstrapAuthorizationSourceError(\n\tinput: CoordinatorBootstrapGrantAuthorizationInput,\n\trow: BootstrapAuthorizationRow | null,\n): CoordinatorBootstrapGrantAuthorizationError | null {\n\tif (!row?.target_group_id) return \"grant_not_found\";\n\tconst expected = input.expectedSeed;\n\tif (\n\t\texpected &&\n\t\t(expected.groupId !== row.group_id ||\n\t\t\texpected.deviceId !== row.seed_device_id ||\n\t\t\texpected.publicKey !== row.seed_enrollment_public_key ||\n\t\t\texpected.fingerprint !== row.seed_enrollment_fingerprint)\n\t)\n\t\treturn \"grant_not_found\";\n\treturn null;\n}\n\nfunction participant(\n\trow: BootstrapAuthorizationRow,\n\tprefix: \"seed_enrollment\" | \"worker_enrollment\",\n): CoordinatorEnrollment {\n\tconst group_id = row[`${prefix}_group_id`],\n\t\tdevice_id = row[`${prefix}_device_id`];\n\tconst public_key = row[`${prefix}_public_key`],\n\t\tfingerprint = row[`${prefix}_fingerprint`];\n\tconst identity_id = row[`${prefix}_identity_id`],\n\t\tdisplay_name = row[`${prefix}_display_name`];\n\tconst enabled = row[`${prefix}_enabled`],\n\t\tcreated_at = row[`${prefix}_created_at`];\n\tif (\n\t\t!text(group_id) ||\n\t\t!text(device_id) ||\n\t\t!text(public_key) ||\n\t\t!text(fingerprint) ||\n\t\t(identity_id !== null && typeof identity_id !== \"string\") ||\n\t\t(display_name !== null && typeof display_name !== \"string\") ||\n\t\tenabled !== 1 ||\n\t\t!text(created_at)\n\t)\n\t\tthrow new Error(\"bootstrap_authorization_unavailable\");\n\treturn {\n\t\tgroup_id,\n\t\tdevice_id,\n\t\tpublic_key,\n\t\tfingerprint,\n\t\tidentity_id,\n\t\tdisplay_name,\n\t\tenabled,\n\t\tcreated_at,\n\t};\n}\n\nconst EXPLICIT_OFFSET_EXPIRY =\n\t/^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d{1,9})?(?:Z|[+-](\\d{2}):(\\d{2}))$/;\n\n/** Parse an explicit-zone timestamp without accepting normalized invalid calendar dates. */\nexport function parseBootstrapExpiry(value: unknown): number {\n\tif (typeof value !== \"string\") return Number.NaN;\n\tconst parts = EXPLICIT_OFFSET_EXPIRY.exec(value);\n\tif (!parts) return Number.NaN;\n\tconst year = Number(parts[1]);\n\tconst month = Number(parts[2]);\n\tconst day = Number(parts[3]);\n\tconst hour = Number(parts[4]);\n\tconst minute = Number(parts[5]);\n\tconst second = Number(parts[6]);\n\tconst offsetHour = Number(parts[7] ?? 0);\n\tconst offsetMinute = Number(parts[8] ?? 0);\n\tconst leapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n\tconst februaryDays = leapYear ? 29 : 28;\n\tconst monthDays = [31, februaryDays, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\tif (month < 1 || month > 12 || day < 1 || day > (monthDays[month - 1] ?? 0)) {\n\t\treturn Number.NaN;\n\t}\n\tif (hour > 23 || minute > 59 || second > 59 || offsetHour > 23 || offsetMinute > 59) {\n\t\treturn Number.NaN;\n\t}\n\treturn Date.parse(value);\n}\n\n// The revocation subjects remain the captured participants even if their keys disappear or rotate.\n// Success pins both tuples and the exact expiry text whose parsed milliseconds were validated.\nexport function bootstrapAuthorizationDecision(\n\tinput: CoordinatorBootstrapGrantAuthorizationInput,\n\trow: BootstrapAuthorizationRow,\n\tkeys: { seed: string | null; worker: string | null },\n) {\n\tconst expiryMs = parseBootstrapExpiry(row.expires_at);\n\tconst expiryValid = Number.isFinite(expiryMs);\n\tconst expected = input.expectedSeed;\n\treturn {\n\t\tsql: `SELECT ${COLUMNS_SQL}, CASE\nWHEN g.group_id IS NULL THEN 'grant_not_found'\nWHEN ? = 1 AND (b.group_id IS NOT ? OR b.seed_device_id IS NOT ?) THEN 'grant_not_found'\nWHEN ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL} OR ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL} THEN 'device_revoked'\nWHEN b.revoked_at IS NOT NULL THEN 'grant_revoked'\nWHEN g.archived_at IS NOT NULL THEN 'group_archived'\nWHEN b.group_id IS NOT ? OR b.seed_device_id IS NOT ? OR b.worker_device_id IS NOT ?\n OR b.expires_at IS NOT ? OR b.revoked_at IS NOT ? THEN 'bootstrap_authorization_unavailable'\nWHEN s.device_id IS NULL OR s.enabled != 1 THEN 'seed_enrollment_not_found'\nWHEN w.device_id IS NULL OR w.enabled != 1 THEN 'worker_enrollment_not_found'\nWHEN s.public_key IS NOT ? OR s.fingerprint IS NOT ? OR s.identity_id IS NOT ?\n OR s.group_id IS NOT ? OR s.device_id IS NOT ? OR s.enabled IS NOT ?\n OR w.public_key IS NOT ? OR w.fingerprint IS NOT ? OR w.identity_id IS NOT ?\n OR w.group_id IS NOT ? OR w.device_id IS NOT ? OR w.enabled IS NOT ? THEN 'bootstrap_authorization_unavailable'\nWHEN ? = 0 THEN 'bootstrap_authorization_unavailable'\nWHEN ? <= ? THEN 'grant_expired'\nELSE 'authorized' END AS status\n${JOINS_SQL} WHERE b.grant_id = ?`,\n\t\tvalues: [\n\t\t\texpected ? 1 : 0,\n\t\t\texpected?.groupId ?? null,\n\t\t\texpected?.deviceId ?? null,\n\t\t\trow.seed_device_id,\n\t\t\tkeys.seed,\n\t\t\trow.worker_device_id,\n\t\t\tkeys.worker,\n\t\t\trow.group_id,\n\t\t\trow.seed_device_id,\n\t\t\trow.worker_device_id,\n\t\t\trow.expires_at,\n\t\t\trow.revoked_at,\n\t\t\trow.seed_enrollment_public_key,\n\t\t\trow.seed_enrollment_fingerprint,\n\t\t\trow.seed_enrollment_identity_id,\n\t\t\trow.seed_enrollment_group_id,\n\t\t\trow.seed_enrollment_device_id,\n\t\t\trow.seed_enrollment_enabled,\n\t\t\trow.worker_enrollment_public_key,\n\t\t\trow.worker_enrollment_fingerprint,\n\t\t\trow.worker_enrollment_identity_id,\n\t\t\trow.worker_enrollment_group_id,\n\t\t\trow.worker_enrollment_device_id,\n\t\t\trow.worker_enrollment_enabled,\n\t\t\texpiryValid ? 1 : 0,\n\t\t\texpiryValid ? expiryMs : 0,\n\t\t\tinput.nowMs,\n\t\t\tinput.grantId,\n\t\t],\n\t};\n}\n\nexport function bootstrapAuthorizationResult(\n\trow: BootstrapAuthorizationRow | null,\n): CoordinatorBootstrapGrantAuthorizationResult {\n\tif (!row) return rejectBootstrapAuthorization(\"bootstrap_authorization_unavailable\");\n\tif (row.status !== \"authorized\") {\n\t\tconst errors: CoordinatorBootstrapGrantAuthorizationError[] = [\n\t\t\t\"grant_not_found\",\n\t\t\t\"seed_enrollment_not_found\",\n\t\t\t\"worker_enrollment_not_found\",\n\t\t\t\"grant_revoked\",\n\t\t\t\"grant_expired\",\n\t\t\t\"group_archived\",\n\t\t\t\"device_revoked\",\n\t\t\t\"bootstrap_authorization_unavailable\",\n\t\t];\n\t\tif (!row.status || !errors.includes(row.status))\n\t\t\treturn rejectBootstrapAuthorization(\"bootstrap_authorization_unavailable\");\n\t\treturn rejectBootstrapAuthorization(row.status);\n\t}\n\tconst grant: CoordinatorBootstrapGrant = {\n\t\tgrant_id: row.grant_id,\n\t\tgroup_id: row.group_id,\n\t\tseed_device_id: row.seed_device_id,\n\t\tworker_device_id: row.worker_device_id,\n\t\texpires_at: row.expires_at,\n\t\tcreated_at: row.created_at,\n\t\tcreated_by: row.created_by,\n\t\trevoked_at: row.revoked_at,\n\t};\n\treturn {\n\t\tkind: \"authorized\",\n\t\tauthorizationVersion: 1,\n\t\tgrant,\n\t\tseedEnrollment: participant(row, \"seed_enrollment\"),\n\t\tworkerEnrollment: participant(row, \"worker_enrollment\"),\n\t};\n}\n","import { DEVICE_REVOCATION_SUBJECT_EXISTS_SQL } from \"./coordinator-device-revocation.js\";\nimport type { CoordinatorCreateBootstrapGrantInput } from \"./coordinator-store-contract.js\";\n\nexport interface BootstrapParticipantSource {\n\tpublic_key: string;\n\tfingerprint: string;\n\tidentity_id: string | null;\n}\n\n// Disabled enrollment still supplies key metadata; raw issuance is not authorization.\nexport const BOOTSTRAP_PARTICIPANT_SOURCE_SQL = `SELECT public_key, fingerprint, identity_id\n\tFROM enrolled_devices WHERE group_id = ? AND device_id = ?`;\nexport const BOOTSTRAP_PARTICIPANTS_REVOKED_SQL = `SELECT 1 WHERE\n\t${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL} OR ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}`;\n\nconst PINNED_PARTICIPANT_SQL = `((? = 0 AND NOT EXISTS (\n\tSELECT 1 FROM enrolled_devices WHERE group_id = ? AND device_id = ?))\n\tOR (? = 1 AND EXISTS (SELECT 1 FROM enrolled_devices\n\t\tWHERE group_id = ? AND device_id = ? AND public_key IS ?\n\t\tAND fingerprint IS ? AND identity_id IS ?)))`;\n\nexport const BOOTSTRAP_RAW_INSERT_SQL = `INSERT INTO coordinator_bootstrap_grants(\n\tgrant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n) SELECT ?, ?, ?, ?, ?, ?, ?, NULL\nWHERE ${PINNED_PARTICIPANT_SQL} AND ${PINNED_PARTICIPANT_SQL}\nAND NOT (${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL} OR ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL})\nRETURNING grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at`;\n\nexport function captureBootstrapParticipantSource(source: BootstrapParticipantSource | null) {\n\tif (!source) return null;\n\tif (\n\t\ttypeof source.public_key !== \"string\" ||\n\t\ttypeof source.fingerprint !== \"string\" ||\n\t\t(source.identity_id !== null && typeof source.identity_id !== \"string\")\n\t) {\n\t\tthrow new Error(\"bootstrap_grant_write_incomplete\");\n\t}\n\treturn {\n\t\tpublic_key: source.public_key,\n\t\tfingerprint: source.fingerprint,\n\t\tidentity_id: source.identity_id,\n\t};\n}\n\nfunction participantPinValues(\n\tgroupId: string,\n\tdeviceId: string,\n\tsource: BootstrapParticipantSource | null,\n) {\n\tconst present = source ? 1 : 0;\n\treturn [\n\t\tpresent,\n\t\tgroupId,\n\t\tdeviceId,\n\t\tpresent,\n\t\tgroupId,\n\t\tdeviceId,\n\t\tsource?.public_key ?? null,\n\t\tsource?.fingerprint ?? null,\n\t\tsource?.identity_id ?? null,\n\t];\n}\n\nexport function bootstrapRawInsertValues(\n\tinput: CoordinatorCreateBootstrapGrantInput,\n\tgrant: { grantId: string; createdAt: string },\n\tparticipants: {\n\t\tseed: BootstrapParticipantSource | null;\n\t\tworker: BootstrapParticipantSource | null;\n\t},\n\trevocationValues: (string | null)[],\n) {\n\treturn [\n\t\tgrant.grantId,\n\t\tinput.groupId,\n\t\tinput.seedDeviceId,\n\t\tinput.workerDeviceId,\n\t\tinput.expiresAt,\n\t\tgrant.createdAt,\n\t\tinput.createdBy ?? null,\n\t\t...participantPinValues(input.groupId, input.seedDeviceId, participants.seed),\n\t\t...participantPinValues(input.groupId, input.workerDeviceId, participants.worker),\n\t\t...revocationValues,\n\t];\n}\n","import type { AuthLinkBackend } from \"./coordinator-auth-link.js\";\n\n/**\n * Storage for ADR 0005 Section 8 rebinding: an enrolled device whose current\n * Identity has no account link of its own moves to the Identity linked to the\n * Google account it signs in with. A self-bind keeps the device's Identity\n * (target = current) and gives a device without its own proof a binding. Both tables are additive. They never change\n * the owner-enrollment tables, whose schema readiness checks compare exact DDL.\n *\n * Mirror: packages/cloudflare-coordinator-worker/migrations/0038_add_device_rebind.sql\n */\nexport const COORDINATOR_DEVICE_REBIND_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS coordinator_device_rebind_attempts (\n coordinator_id TEXT NOT NULL,\n attempt_id TEXT NOT NULL,\n origin TEXT NOT NULL,\n device_id TEXT NOT NULL,\n public_key TEXT NOT NULL,\n key_id TEXT NOT NULL CHECK (length(key_id) = 64 AND key_id NOT GLOB '*[^0-9a-f]*'),\n fingerprint TEXT NOT NULL,\n current_identity_id TEXT NOT NULL CHECK (length(current_identity_id) BETWEEN 1 AND 256),\n issuer TEXT NOT NULL,\n auth_config_revision TEXT NOT NULL,\n loopback_redirect TEXT,\n browser_start_hash TEXT NOT NULL UNIQUE,\n browser_transaction_hash TEXT UNIQUE,\n browser_binder_hash TEXT,\n account_subject TEXT,\n target_identity_id TEXT,\n link_id TEXT,\n link_authority_kind TEXT CHECK (link_authority_kind IS NULL\n OR link_authority_kind IN ('controller_attestation', 'device_claim')),\n review_digest TEXT CHECK (review_digest IS NULL\n OR (length(review_digest) = 64 AND review_digest NOT GLOB '*[^0-9a-f]*')),\n team_effects_json TEXT CHECK (team_effects_json IS NULL OR json_valid(team_effects_json)),\n enrollment_count INTEGER CHECK (enrollment_count IS NULL OR enrollment_count BETWEEN 1 AND 50),\n confirmation_hash TEXT,\n completion_secret_hash TEXT UNIQUE,\n final_key_proof_hash TEXT,\n state TEXT NOT NULL CHECK (state IN\n ('pending', 'browser_claimed', 'oidc_verified', 'confirmed', 'finalized', 'expired', 'failed')),\n created_at_ms INTEGER NOT NULL,\n expires_at_ms INTEGER NOT NULL CHECK (expires_at_ms = created_at_ms + 600000),\n finalized_at_ms INTEGER,\n binding_id TEXT UNIQUE,\n audit_event_id TEXT UNIQUE,\n final_outcome_json TEXT CHECK (final_outcome_json IS NULL OR json_valid(final_outcome_json)),\n PRIMARY KEY (coordinator_id, attempt_id),\n CHECK (state NOT IN ('confirmed', 'finalized') OR (account_subject IS NOT NULL\n AND target_identity_id IS NOT NULL AND link_id IS NOT NULL AND link_authority_kind IS NOT NULL\n AND review_digest IS NOT NULL AND team_effects_json IS NOT NULL AND enrollment_count IS NOT NULL\n AND confirmation_hash IS NOT NULL AND completion_secret_hash IS NOT NULL)),\n CHECK (state <> 'finalized' OR (finalized_at_ms IS NOT NULL AND binding_id IS NOT NULL\n AND audit_event_id IS NOT NULL AND final_key_proof_hash IS NOT NULL\n AND final_outcome_json IS NOT NULL AND loopback_redirect IS NULL)),\n CHECK (state = 'finalized' OR (finalized_at_ms IS NULL AND binding_id IS NULL\n AND audit_event_id IS NULL AND final_key_proof_hash IS NULL AND final_outcome_json IS NULL)),\n CHECK (state NOT IN ('pending', 'browser_claimed', 'oidc_verified')\n OR (confirmation_hash IS NULL AND completion_secret_hash IS NULL)),\n CHECK (state NOT IN ('pending', 'browser_claimed') OR (account_subject IS NULL\n AND target_identity_id IS NULL AND link_id IS NULL AND link_authority_kind IS NULL\n AND team_effects_json IS NULL AND enrollment_count IS NULL)),\n CHECK (review_digest IS NOT NULL),\n CHECK (state <> 'pending' OR (browser_transaction_hash IS NULL AND browser_binder_hash IS NULL))\n);\n\nCREATE INDEX IF NOT EXISTS idx_coordinator_device_rebind_attempts_device\n ON coordinator_device_rebind_attempts (coordinator_id, device_id, state);\n\n-- Birth facts never change; proofs are set once; only forward transitions are allowed.\n-- The EXISTS clause stops UPDATE OR REPLACE from deleting another row through a unique key.\nCREATE TRIGGER IF NOT EXISTS coordinator_device_rebind_attempt_pins\nBEFORE UPDATE ON coordinator_device_rebind_attempts\nWHEN OLD.state IN ('finalized', 'expired', 'failed') OR NEW.rowid IS NOT OLD.rowid\n OR EXISTS (SELECT 1 FROM coordinator_device_rebind_attempts o\n WHERE NOT (o.coordinator_id = OLD.coordinator_id AND o.attempt_id = OLD.attempt_id)\n AND (o.browser_transaction_hash = NEW.browser_transaction_hash\n OR o.completion_secret_hash = NEW.completion_secret_hash\n OR o.binding_id = NEW.binding_id OR o.audit_event_id = NEW.audit_event_id))\n OR NEW.coordinator_id IS NOT OLD.coordinator_id OR NEW.attempt_id IS NOT OLD.attempt_id\n OR NEW.origin IS NOT OLD.origin OR NEW.device_id IS NOT OLD.device_id\n OR NEW.public_key IS NOT OLD.public_key OR NEW.key_id IS NOT OLD.key_id\n OR NEW.fingerprint IS NOT OLD.fingerprint OR NEW.current_identity_id IS NOT OLD.current_identity_id\n OR NEW.issuer IS NOT OLD.issuer OR NEW.auth_config_revision IS NOT OLD.auth_config_revision\n OR NEW.browser_start_hash IS NOT OLD.browser_start_hash\n OR NEW.created_at_ms IS NOT OLD.created_at_ms OR NEW.expires_at_ms IS NOT OLD.expires_at_ms\n OR (OLD.browser_transaction_hash IS NOT NULL AND NEW.browser_transaction_hash IS NOT OLD.browser_transaction_hash)\n OR (OLD.browser_binder_hash IS NOT NULL AND NEW.browser_binder_hash IS NOT OLD.browser_binder_hash)\n OR (OLD.account_subject IS NOT NULL AND NEW.account_subject IS NOT OLD.account_subject)\n OR (OLD.target_identity_id IS NOT NULL AND NEW.target_identity_id IS NOT OLD.target_identity_id)\n OR (OLD.link_id IS NOT NULL AND NEW.link_id IS NOT OLD.link_id)\n OR (OLD.review_digest IS NOT NULL AND NEW.review_digest IS NOT OLD.review_digest)\n OR (OLD.team_effects_json IS NOT NULL AND NEW.team_effects_json IS NOT OLD.team_effects_json)\n OR (OLD.enrollment_count IS NOT NULL AND NEW.enrollment_count IS NOT OLD.enrollment_count)\n OR (OLD.confirmation_hash IS NOT NULL AND NEW.confirmation_hash IS NOT OLD.confirmation_hash)\n OR (OLD.completion_secret_hash IS NOT NULL AND NEW.completion_secret_hash IS NOT OLD.completion_secret_hash)\n OR (NEW.loopback_redirect IS NOT OLD.loopback_redirect\n AND NOT (NEW.loopback_redirect IS NULL AND NEW.state IN ('finalized', 'expired', 'failed')))\n OR NOT ((OLD.state = NEW.state)\n OR (OLD.state = 'pending' AND NEW.state IN ('browser_claimed', 'expired', 'failed'))\n OR (OLD.state = 'browser_claimed' AND NEW.state IN ('oidc_verified', 'expired', 'failed'))\n OR (OLD.state = 'oidc_verified' AND NEW.state IN ('confirmed', 'expired', 'failed'))\n OR (OLD.state = 'confirmed' AND NEW.state IN ('finalized', 'expired', 'failed')))\nBEGIN\n SELECT RAISE(ABORT, 'device_rebind_attempt_immutable');\nEND;\n\n-- REPLACE's implicit deletes may skip DELETE triggers when recursive triggers are off.\nCREATE TRIGGER IF NOT EXISTS coordinator_device_rebind_attempt_insert_collision\nBEFORE INSERT ON coordinator_device_rebind_attempts\nWHEN EXISTS (SELECT 1 FROM coordinator_device_rebind_attempts\n WHERE rowid = NEW.rowid OR (coordinator_id = NEW.coordinator_id AND attempt_id = NEW.attempt_id)\n OR browser_start_hash = NEW.browser_start_hash\n OR browser_transaction_hash = NEW.browser_transaction_hash\n OR completion_secret_hash = NEW.completion_secret_hash\n OR binding_id = NEW.binding_id OR audit_event_id = NEW.audit_event_id)\nBEGIN\n SELECT RAISE(ABORT, 'device_rebind_attempt_collision');\nEND;\n\n-- An automatic rowid reads as -1 before insert; positive rowids keep that from matching a row.\nCREATE TRIGGER IF NOT EXISTS coordinator_device_rebind_attempt_rowid\nAFTER INSERT ON coordinator_device_rebind_attempts\nWHEN NEW.rowid < 1\nBEGIN\n SELECT RAISE(ABORT, 'device_rebind_attempt_rowid');\nEND;\n\nCREATE TRIGGER IF NOT EXISTS coordinator_device_rebind_attempt_retained\nBEFORE DELETE ON coordinator_device_rebind_attempts\nWHEN OLD.state = 'finalized'\nBEGIN\n SELECT RAISE(ABORT, 'device_rebind_attempt_immutable');\nEND;\n\nCREATE TABLE IF NOT EXISTS coordinator_device_rebind_audit_log (\n coordinator_id TEXT NOT NULL,\n event_id TEXT NOT NULL,\n attempt_id TEXT NOT NULL,\n action TEXT NOT NULL CHECK (action = 'owner_device_rebound'),\n binding_id TEXT NOT NULL,\n device_id TEXT NOT NULL,\n previous_identity_id TEXT NOT NULL,\n target_identity_id TEXT NOT NULL,\n enrollment_count INTEGER NOT NULL CHECK (enrollment_count BETWEEN 1 AND 50),\n created_at_ms INTEGER NOT NULL,\n PRIMARY KEY (coordinator_id, event_id),\n UNIQUE (coordinator_id, attempt_id)\n);\n\nCREATE INDEX IF NOT EXISTS idx_coordinator_device_rebind_audit_target\n ON coordinator_device_rebind_audit_log (coordinator_id, target_identity_id, created_at_ms);\n\nCREATE TRIGGER IF NOT EXISTS coordinator_device_rebind_audit_insert_collision\nBEFORE INSERT ON coordinator_device_rebind_audit_log\nWHEN EXISTS (SELECT 1 FROM coordinator_device_rebind_audit_log\n WHERE rowid = NEW.rowid\n OR (coordinator_id = NEW.coordinator_id AND (event_id = NEW.event_id OR attempt_id = NEW.attempt_id)))\nBEGIN\n SELECT RAISE(ABORT, 'device_rebind_audit_collision');\nEND;\n\nCREATE TRIGGER IF NOT EXISTS coordinator_device_rebind_audit_rowid\nAFTER INSERT ON coordinator_device_rebind_audit_log\nWHEN NEW.rowid < 1\nBEGIN\n SELECT RAISE(ABORT, 'device_rebind_audit_rowid');\nEND;\n\nCREATE TRIGGER IF NOT EXISTS coordinator_device_rebind_audit_immutable_update\nBEFORE UPDATE ON coordinator_device_rebind_audit_log\nBEGIN\n SELECT RAISE(ABORT, 'device_rebind_audit_immutable');\nEND;\n\nCREATE TRIGGER IF NOT EXISTS coordinator_device_rebind_audit_immutable_delete\nBEFORE DELETE ON coordinator_device_rebind_audit_log\nBEGIN\n SELECT RAISE(ABORT, 'device_rebind_audit_immutable');\nEND;\n`;\n\nconst PRE_RELEASE_ATTEMPT_OBJECTS = [\n\t\"TRIGGER coordinator_device_rebind_attempt_pins\",\n\t\"TRIGGER coordinator_device_rebind_attempt_insert_collision\",\n\t\"TRIGGER coordinator_device_rebind_attempt_rowid\",\n\t\"TRIGGER coordinator_device_rebind_attempt_retained\",\n\t\"INDEX idx_coordinator_device_rebind_attempts_device\",\n\t\"TABLE coordinator_device_rebind_attempts\",\n];\n\n/**\n * The first pre-release attempts table forbade a review digest before OIDC,\n * but the ceremony pins it at start. A coordinator that opened that build has\n * the old table; recreate it while it is still empty (nothing wrote attempts\n * before the routes shipped). With rows present it is left as is and starts\n * fail closed.\n */\nexport function upgradePreReleaseRebindAttemptsSql(\n\texistingTableSql: string | null,\n\trows: number,\n): string | null {\n\tif (\n\t\t!existingTableSql ||\n\t\texistingTableSql.includes(\"CHECK (review_digest IS NOT NULL)\") ||\n\t\trows > 0\n\t)\n\t\treturn null;\n\treturn PRE_RELEASE_ATTEMPT_OBJECTS.map(\n\t\t(object) => `DROP ${object.replace(\" \", \" IF EXISTS \")};`,\n\t).join(\"\\n\");\n}\n\nconst REBIND_SCHEMA_PRESENT_SQL = `SELECT\n EXISTS (SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'coordinator_device_rebind_attempts'\n AND instr(sql, 'CHECK (review_digest IS NOT NULL)') > 0) AS attempts,\n EXISTS (SELECT 1 FROM sqlite_master WHERE type = 'table'\n AND name = 'coordinator_device_rebind_audit_log') AS audit`;\n\n/**\n * The backend, only when this database has the current rebind tables. Without\n * them (a D1 database before migration 0038) rebind routes report not found\n * and the shared OIDC callback skips the rebind hook.\n */\nexport async function readDeviceRebindBackend(\n\tbackend: AuthLinkBackend,\n): Promise<AuthLinkBackend | null> {\n\tconst present = await backend.first<{ attempts: number; audit: number }>({\n\t\tsql: REBIND_SCHEMA_PRESENT_SQL,\n\t\tvalues: [],\n\t});\n\treturn present?.attempts === 1 && present.audit === 1 ? backend : null;\n}\n\nconst ATTEMPTS_TABLE = \"coordinator_device_rebind_attempts\";\nconst REBUILT_TABLE = `${ATTEMPTS_TABLE}_rebuilt`;\n\nfunction attemptStatements() {\n\tconst sql = COORDINATOR_DEVICE_REBIND_SCHEMA_SQL;\n\tconst table = sql.match(\n\t\t/CREATE TABLE IF NOT EXISTS coordinator_device_rebind_attempts \\([\\s\\S]*?\\n\\);/,\n\t)?.[0];\n\tconst index = sql.match(\n\t\t/CREATE INDEX IF NOT EXISTS idx_coordinator_device_rebind_attempts_device[\\s\\S]*?;/,\n\t)?.[0];\n\tconst triggers = sql.match(\n\t\t/CREATE TRIGGER IF NOT EXISTS coordinator_device_rebind_attempt_\\w+[\\s\\S]*?\\nEND;/g,\n\t);\n\tif (!table || !index || triggers?.length !== 4) throw new Error(\"device_rebind_schema_unparsed\");\n\treturn { table, index, triggers };\n}\n\n/**\n * Rebuilds the attempts table without the first release's \"target differs\n * from current\" CHECK, which self-binds need. Rows, the index and every\n * trigger are kept. Mirror: migrations/0040_allow_device_self_bind.sql.\n */\nexport function rebuildRebindAttemptsForSelfBindSql(): string {\n\tconst { table, index, triggers } = attemptStatements();\n\tconst names = triggers.map((t) => t.match(/coordinator_device_rebind_attempt_\\w+/)?.[0]);\n\treturn [\n\t\t...names.map((name) => `DROP TRIGGER IF EXISTS ${name};`),\n\t\t\"DROP INDEX IF EXISTS idx_coordinator_device_rebind_attempts_device;\",\n\t\ttable.replace(`CREATE TABLE IF NOT EXISTS ${ATTEMPTS_TABLE}`, `CREATE TABLE ${REBUILT_TABLE}`),\n\t\t`INSERT INTO ${REBUILT_TABLE} SELECT * FROM ${ATTEMPTS_TABLE};`,\n\t\t`DROP TABLE ${ATTEMPTS_TABLE};`,\n\t\t`ALTER TABLE ${REBUILT_TABLE} RENAME TO ${ATTEMPTS_TABLE};`,\n\t\tindex,\n\t\t...triggers,\n\t].join(\"\\n\");\n}\n\n/**\n * True when an existing attempts table still forbids a self-bind. A\n * pre-release table that kept rows (no review-digest CHECK) is left alone: its\n * rows can't satisfy the current table, and it already fails closed.\n */\nexport function rebindAttemptsNeedSelfBindRebuild(existingTableSql: string | null): boolean {\n\treturn (\n\t\t!!existingTableSql &&\n\t\texistingTableSql.includes(\"target_identity_id <> current_identity_id\") &&\n\t\texistingTableSql.includes(\"CHECK (review_digest IS NOT NULL)\")\n\t);\n}\n","import { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport type { CoordinatorEnrollment } from \"./coordinator-store-contract.js\";\n\n/**\n * The device's ownership binding, if it has exactly one. A rebind (ADR 0005\n * Section 8) writes one, so admins can tell a rebound device from a conflict.\n */\nexport const ENROLLMENT_OWNERSHIP_COLUMNS = `(SELECT CASE WHEN count(*) = 1 THEN max(b.identity_id) END\n\t FROM coordinator_device_ownership_bindings b\n\t WHERE b.device_id = enrolled_devices.device_id) AS ownership_identity_id,\n\t(SELECT CASE WHEN count(*) = 1 THEN max(b.key_id) END\n\t FROM coordinator_device_ownership_bindings b\n\t WHERE b.device_id = enrolled_devices.device_id) AS ownership_key_id`;\n\n/**\n * Keeps `ownership_identity_id` only when the binding names this enrollment's\n * exact key; a binding for another key says nothing about this enrollment.\n */\nexport async function withEnrollmentOwnership(\n\trows: ReadonlyArray<CoordinatorEnrollment & { ownership_key_id?: unknown }>,\n): Promise<CoordinatorEnrollment[]> {\n\treturn Promise.all(\n\t\trows.map(async (row) => {\n\t\t\tconst { ownership_identity_id: identityId, ownership_key_id: keyId, ...base } = row;\n\t\t\tif (typeof identityId !== \"string\" || typeof keyId !== \"string\") return base;\n\t\t\tconst enrollmentKeyId = await ed25519KeyIdForRevocation(row.public_key);\n\t\t\treturn enrollmentKeyId === keyId ? { ...base, ownership_identity_id: identityId } : base;\n\t\t}),\n\t);\n}\n","import { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport { DEVICE_REVOCATION_SUBJECT_EXISTS_SQL } from \"./coordinator-device-revocation.js\";\nimport { COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_GROUPS } from \"./coordinator-legacy-team-completion.js\";\n\n/** Internal transport grants only: these confer no Team/Project access. */\nexport interface CoordinatorIdentityGroupGrant {\n\treadonly coordinator_id: string;\n\treadonly identity_id: string;\n\treadonly group_id: string;\n\treadonly status: \"active\" | \"revoked\";\n\treadonly revision: number;\n\treadonly source_kind: \"controller_attestation\";\n\treadonly source_receipt_id: string;\n\treadonly created_at: string;\n\treadonly revoked_at: string | null;\n}\n\nexport interface CoordinatorIdentityGroupGrantIssueInput {\n\tcoordinatorId: string;\n\tattestationId: string;\n}\nexport interface CoordinatorIdentityGroupGrantScope {\n\tcoordinatorId: string;\n\tidentityId: string;\n}\nexport interface CoordinatorIdentityGroupGrantRevokeInput\n\textends CoordinatorIdentityGroupGrantScope {\n\tgroupId: string;\n\texpectedRevision: number;\n}\nexport type CoordinatorIdentityGroupGrantIssueResult =\n\t| { kind: \"created\" | \"existing\"; grant: CoordinatorIdentityGroupGrant }\n\t| { kind: \"rejected\"; error: \"invalid_grant_input\" | \"grant_authority_unavailable\" };\n\n/** Future authenticated operators own invocation; no routes or automatic issuance. */\nexport interface CoordinatorIdentityGroupGrantStore {\n\tissueIdentityGroupGrantFromControllerAttestation(\n\t\tinput: CoordinatorIdentityGroupGrantIssueInput,\n\t): Promise<CoordinatorIdentityGroupGrantIssueResult>;\n\tlistIdentityGroupGrantRevisions(\n\t\tinput: CoordinatorIdentityGroupGrantScope,\n\t): Promise<CoordinatorIdentityGroupGrant[]>;\n\trevokeIdentityGroupGrant(input: CoordinatorIdentityGroupGrantRevokeInput): Promise<boolean>;\n}\n\n/** Capture once before async I/O; do not invoke getters or accept inherited IDs. */\nexport function captureIdentityGroupGrantInput(\n\tinput: unknown,\n\tfields: readonly string[],\n): Record<string, string | number> | null {\n\ttry {\n\t\tif (!input || typeof input !== \"object\" || Array.isArray(input)) return null;\n\t\tconst captured: Record<string, string | number> = {};\n\t\tfor (const field of fields) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(input, field);\n\t\t\tif (!descriptor || !Object.hasOwn(descriptor, \"value\")) return null;\n\t\t\tconst value: unknown = descriptor.value;\n\t\t\tif (field === \"expectedRevision\") {\n\t\t\t\tif (\n\t\t\t\t\ttypeof value !== \"number\" ||\n\t\t\t\t\t!Number.isSafeInteger(value) ||\n\t\t\t\t\tvalue < 1 ||\n\t\t\t\t\tvalue >= Number.MAX_SAFE_INTEGER\n\t\t\t\t)\n\t\t\t\t\treturn null;\n\t\t\t} else if (!isAuthControllerId(value)) return null;\n\t\t\tcaptured[field] = value as string | number;\n\t\t}\n\t\treturn captured;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nconst GRANT_FIELDS = [\n\t\"coordinator_id\",\n\t\"identity_id\",\n\t\"group_id\",\n\t\"status\",\n\t\"revision\",\n\t\"source_kind\",\n\t\"source_receipt_id\",\n\t\"created_at\",\n\t\"revoked_at\",\n] as const;\n\nfunction isCanonicalGrant(row: CoordinatorIdentityGroupGrant): boolean {\n\tif (!row) return false;\n\tif (\n\t\t![row.coordinator_id, row.identity_id, row.group_id, row.source_receipt_id].every(\n\t\t\tisAuthControllerId,\n\t\t)\n\t)\n\t\treturn false;\n\tif (\n\t\trow.source_kind !== \"controller_attestation\" ||\n\t\t!Number.isSafeInteger(row.revision) ||\n\t\trow.revision < 1\n\t)\n\t\treturn false;\n\tif (typeof row.created_at !== \"string\" || row.created_at.length === 0) return false;\n\tif (row.status === \"active\") return row.revoked_at === null;\n\treturn (\n\t\trow.status === \"revoked\" && typeof row.revoked_at === \"string\" && row.revoked_at.length > 0\n\t);\n}\n\nfunction canonicalRevisionSet(\n\trows: readonly CoordinatorIdentityGroupGrant[],\n): Map<string, CoordinatorIdentityGroupGrant> | null {\n\t// Reuse the existing coordinator group-set limit; never truncate authority sets.\n\tif (\n\t\t!Array.isArray(rows) ||\n\t\trows.length === 0 ||\n\t\trows.length > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_GROUPS\n\t)\n\t\treturn null;\n\tconst result = new Map<string, CoordinatorIdentityGroupGrant>();\n\tfor (const row of rows) {\n\t\tif (!isCanonicalGrant(row)) return null;\n\t\tif (\n\t\t\trow.coordinator_id !== rows[0].coordinator_id ||\n\t\t\trow.identity_id !== rows[0].identity_id ||\n\t\t\tresult.has(row.group_id)\n\t\t)\n\t\t\treturn null;\n\t\tresult.set(row.group_id, row);\n\t}\n\treturn result;\n}\n\n/** Snapshot equality only, NOT authorization for a future enrollment write. */\nexport function compareIdentityGroupGrantRevisions(\n\texpected: readonly CoordinatorIdentityGroupGrant[],\n\tcurrent: readonly CoordinatorIdentityGroupGrant[],\n): boolean {\n\tconst left = canonicalRevisionSet(expected);\n\tconst right = canonicalRevisionSet(current);\n\tif (!left || !right || left.size !== right.size) return false;\n\tfor (const [groupId, row] of left) {\n\t\tconst other = right.get(groupId);\n\t\tif (!other || GRANT_FIELDS.some((field) => row[field] !== other[field])) return false;\n\t}\n\treturn true;\n}\n\n// Independent tombstones: deliberately no enrollment/controller foreign keys.\nexport const IDENTITY_GROUP_GRANT_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS coordinator_identity_group_grants (\n coordinator_id TEXT NOT NULL,\n identity_id TEXT NOT NULL,\n group_id TEXT NOT NULL,\n status TEXT NOT NULL CHECK (status IN ('active', 'revoked')),\n revision INTEGER NOT NULL CHECK (typeof(revision) = 'integer' AND revision BETWEEN 1 AND 9007199254740991),\n source_kind TEXT NOT NULL CHECK (source_kind = 'controller_attestation'),\n source_receipt_id TEXT NOT NULL,\n created_at TEXT NOT NULL,\n revoked_at TEXT,\n PRIMARY KEY (coordinator_id, identity_id, group_id),\n CHECK ((status = 'active' AND revoked_at IS NULL) OR (status = 'revoked' AND revoked_at IS NOT NULL))\n);`;\n\nconst CURRENT_CONTROLLER_FROM_SQL = `\n FROM coordinator_auth_controller_attestations a\n JOIN enrolled_devices e ON e.group_id = a.group_id AND e.device_id = a.device_id\n JOIN groups g ON g.group_id = a.group_id`;\nconst CURRENT_CONTROLLER_EVIDENCE_SQL = `\n a.coordinator_id = ? AND a.attestation_id = ? AND a.revoked_at IS NULL\n AND g.archived_at IS NULL AND e.enabled = 1\n AND e.public_key = a.public_key AND e.fingerprint = a.fingerprint\n AND e.identity_id IS a.enrollment_identity_id\n AND (e.identity_id IS NULL OR e.identity_id = a.identity_id)`;\n\n/** Read the actual current enrollment, never caller-provided key metadata. */\nexport const IDENTITY_GROUP_GRANT_SOURCE_SQL = `\n SELECT e.* ${CURRENT_CONTROLLER_FROM_SQL} WHERE ${CURRENT_CONTROLLER_EVIDENCE_SQL}`;\n\n// Pin the hashed enrollment across D1 awaits; both issuance and retry recheck revocation.\nconst CURRENT_CONTROLLER_WHERE_SQL = `${CURRENT_CONTROLLER_EVIDENCE_SQL}\n AND e.group_id = ? AND e.device_id = ? AND e.public_key = ?\n AND e.fingerprint = ? AND e.identity_id IS ?\n AND NOT ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}`;\n\nexport const IDENTITY_GROUP_GRANT_INSERT_SQL = `\n INSERT INTO coordinator_identity_group_grants (\n coordinator_id, identity_id, group_id, status, revision, source_kind, source_receipt_id, created_at, revoked_at\n ) SELECT a.coordinator_id, a.identity_id, a.group_id, 'active', 1, 'controller_attestation', a.review_receipt_id, ?, NULL\n ${CURRENT_CONTROLLER_FROM_SQL} WHERE ${CURRENT_CONTROLLER_WHERE_SQL}\n ON CONFLICT (coordinator_id, identity_id, group_id) DO NOTHING\n RETURNING *`;\n\n/** Retry checks the grant and exact current evidence together in ONE read. */\nexport const IDENTITY_GROUP_GRANT_RETRY_SQL = `\n SELECT r.* ${CURRENT_CONTROLLER_FROM_SQL}\n JOIN coordinator_identity_group_grants r ON r.coordinator_id = a.coordinator_id\n AND r.identity_id = a.identity_id AND r.group_id = a.group_id\n WHERE ${CURRENT_CONTROLLER_WHERE_SQL}\n AND r.status = 'active' AND r.source_kind = 'controller_attestation'\n AND r.source_receipt_id = a.review_receipt_id`;\n\n/** Listing intentionally does not depend on the old controller device/key. */\nexport const IDENTITY_GROUP_GRANT_LIST_SQL = `\n SELECT * FROM coordinator_identity_group_grants\n WHERE coordinator_id = ? AND identity_id = ? ORDER BY group_id COLLATE BINARY`;\nexport const IDENTITY_GROUP_GRANT_REVOKE_SQL = `\n UPDATE coordinator_identity_group_grants SET status = 'revoked', revision = revision + 1, revoked_at = ?\n WHERE coordinator_id = ? AND identity_id = ? AND group_id = ? AND status = 'active' AND revision = ?`;\n","import { DEVICE_REVOCATION_SUBJECT_EXISTS_SQL } from \"./coordinator-device-revocation.js\";\nimport type { projectInviteGuardEvidence } from \"./coordinator-project-invite-guards.js\";\nimport type {\n\tCoordinatorConsumeProjectInviteInput,\n\tCoordinatorEnrollDeviceInput,\n} from \"./coordinator-store-contract.js\";\n\nexport function captureLegacyProjectInviteInput(\n\tinput: CoordinatorConsumeProjectInviteInput,\n): CoordinatorConsumeProjectInviteInput {\n\tif (!input || typeof input !== \"object\" || Array.isArray(input)) throw new Error(\"invalid_input\");\n\tconst captured: Record<string, unknown> = {};\n\tfor (const field of [\n\t\t\"token\",\n\t\t\"operationId\",\n\t\t\"deviceId\",\n\t\t\"publicKey\",\n\t\t\"fingerprint\",\n\t\t\"recipientActorId\",\n\t\t\"recipientDisplayName\",\n\t\t\"deviceDisplayName\",\n\t\t\"now\",\n\t]) {\n\t\tconst descriptor = legacyEnrollmentDescriptor(input, field);\n\t\tif (descriptor && !(\"value\" in descriptor)) throw new Error(\"invalid_input\");\n\t\tconst value = descriptor?.value;\n\t\tif (typeof value !== \"string\") throw new Error(\"invalid_input\");\n\t\tcaptured[field] = value;\n\t}\n\treturn captured as unknown as CoordinatorConsumeProjectInviteInput;\n}\n\n/** Global ownership metadata, not proof. Bind actual device ID and canonical key ID (or null). */\nexport const DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL = `EXISTS (\nSELECT 1 FROM coordinator_device_ownership_bindings WHERE device_id = ? OR key_id = ?)`;\n\n/** Project actor labels never prove ownership; only the target enrollment is mutated. */\nexport function legacyProjectInviteOwnershipEvidence(\n\tevidence: ReturnType<typeof projectInviteGuardEvidence>,\n\tdeviceId: string,\n\tkeyIds: { incoming: string | null; current: string | null },\n) {\n\tconst ownershipSql = `${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL} OR ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}`;\n\tconst ownershipValues = [deviceId, keyIds.incoming, deviceId, keyIds.current];\n\treturn {\n\t\t...evidence,\n\t\townershipSql,\n\t\townershipValues,\n\t\teligibilitySql: `${evidence.eligibilitySql} AND NOT (${ownershipSql})`,\n\t\teligibilityValues: [...evidence.eligibilityValues, ...ownershipValues],\n\t\tboundEligibilitySql: `${evidence.boundEligibilitySql} AND NOT (${ownershipSql})`,\n\t\tboundEligibilityValues: [...evidence.boundEligibilityValues, ...ownershipValues],\n\t};\n}\n\nexport const LEGACY_DEVICE_DENIAL_SQL = `SELECT CASE\nWHEN ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL} THEN 'device_revoked'\nWHEN ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL} THEN 'device_ownership_requires_verified_identity'\nELSE 'invite_identity_conflict' END AS denial`;\n\n/** Bind captured public key (null for absence), group/device, then group/device/public key. */\nexport const LEGACY_ENROLLMENT_SOURCE_MATCH_SQL = `((? IS NULL AND NOT EXISTS (\nSELECT 1 FROM enrolled_devices WHERE group_id = ? AND device_id = ?)) OR EXISTS (\nSELECT 1 FROM enrolled_devices WHERE group_id = ? AND device_id = ? AND public_key = ?))`;\n\n/** Incoming revocation, incoming ownership, captured current ownership, then source tuple.\n * Source drift deliberately falls through the denial validator to the unavailable error.\n */\nexport const LEGACY_ENROLLMENT_DENIAL_SQL = `SELECT CASE\nWHEN ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL} THEN 'device_revoked'\nWHEN ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL} OR ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}\nTHEN 'device_ownership_requires_verified_identity'\nWHEN NOT ${LEGACY_ENROLLMENT_SOURCE_MATCH_SQL} THEN 'device_ownership_authorization_unavailable'\nELSE 'invite_identity_conflict' END AS denial`;\n\nexport const LEGACY_ENROLLMENT_WRITE_SQL = `INSERT INTO enrolled_devices(\ngroup_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at\n) SELECT ?, ?, ?, ?, ?, ?, 1, ?\nWHERE NOT ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}\nAND NOT ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}\nAND NOT ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}\nAND ${LEGACY_ENROLLMENT_SOURCE_MATCH_SQL}\nON CONFLICT(group_id, device_id) DO UPDATE SET\npublic_key = excluded.public_key, fingerprint = excluded.fingerprint,\nidentity_id = COALESCE(enrolled_devices.identity_id, excluded.identity_id),\ndisplay_name = excluded.display_name, enabled = 1\nWHERE (excluded.identity_id IS NULL OR enrolled_devices.identity_id IS NULL\nOR enrolled_devices.identity_id = excluded.identity_id)\nAND NOT ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}\nAND NOT ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}\nAND enrolled_devices.public_key = ?`;\n\nexport function captureLegacyEnrollmentPublicKey(row: unknown): string | null {\n\tif (row === null) return null;\n\tif (!row || typeof row !== \"object\")\n\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\tconst descriptor = Object.getOwnPropertyDescriptor(row, \"public_key\");\n\tif (!descriptor || !(\"value\" in descriptor) || typeof descriptor.value !== \"string\") {\n\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t}\n\treturn descriptor.value;\n}\n\nexport function captureLegacyEnrollment(\n\tgroupId: string,\n\tinput: CoordinatorEnrollDeviceInput,\n): CoordinatorEnrollDeviceInput {\n\tif (!input || typeof input !== \"object\" || Array.isArray(input)) throw new Error(\"invalid_input\");\n\tconst captured: Record<string, unknown> = {};\n\tfor (const field of [\"deviceId\", \"publicKey\", \"fingerprint\", \"identityId\", \"displayName\"]) {\n\t\tconst descriptor = legacyEnrollmentDescriptor(input, field);\n\t\tif (descriptor && !(\"value\" in descriptor)) throw new Error(\"invalid_input\");\n\t\tcaptured[field] = descriptor?.value;\n\t}\n\tassertLegacyDeviceScope(groupId, captured.deviceId);\n\tif (\n\t\ttypeof captured.publicKey !== \"string\" ||\n\t\ttypeof captured.fingerprint !== \"string\" ||\n\t\t(captured.identityId != null && typeof captured.identityId !== \"string\") ||\n\t\t(captured.displayName != null && typeof captured.displayName !== \"string\")\n\t)\n\t\tthrow new Error(\"invalid_input\");\n\treturn captured as unknown as CoordinatorEnrollDeviceInput;\n}\n\nfunction legacyEnrollmentDescriptor(input: object, field: string): PropertyDescriptor | undefined {\n\ttry {\n\t\treturn Object.getOwnPropertyDescriptor(input, field);\n\t} catch {\n\t\tthrow new Error(\"invalid_input\");\n\t}\n}\n\nexport function assertLegacyDeviceScope(groupId: unknown, deviceId: unknown): void {\n\tif (typeof groupId !== \"string\" || typeof deviceId !== \"string\") throw new Error(\"invalid_input\");\n}\n\nexport function legacyDeviceWriteChanges(result: unknown): number {\n\tif (!result || typeof result !== \"object\" || (\"success\" in result && result.success === false)) {\n\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t}\n\tlet changes: unknown;\n\tif (\n\t\t\"meta\" in result &&\n\t\tresult.meta &&\n\t\ttypeof result.meta === \"object\" &&\n\t\t\"changes\" in result.meta\n\t) {\n\t\tchanges = result.meta.changes;\n\t}\n\tif (typeof changes !== \"number\" || !Number.isSafeInteger(changes) || changes < 0 || changes > 1) {\n\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t}\n\treturn changes;\n}\n\nexport function legacyDeviceDenial(row: unknown): string {\n\tif (\n\t\trow &&\n\t\ttypeof row === \"object\" &&\n\t\t!(\"success\" in row && row.success === false) &&\n\t\t\"denial\" in row\n\t) {\n\t\tconst denial = row.denial;\n\t\tif (\n\t\t\tdenial === \"device_revoked\" ||\n\t\t\tdenial === \"device_ownership_requires_verified_identity\" ||\n\t\t\tdenial === \"invite_identity_conflict\"\n\t\t)\n\t\t\treturn denial;\n\t}\n\tthrow new Error(\"device_ownership_authorization_unavailable\");\n}\n\nexport function legacyDeviceAuthorizationFailure(error: unknown): never {\n\tif (\n\t\terror instanceof Error &&\n\t\t[\n\t\t\t\"device_revoked\",\n\t\t\t\"device_ownership_requires_verified_identity\",\n\t\t\t\"invite_identity_conflict\",\n\t\t].includes(error.message)\n\t)\n\t\tthrow error;\n\tthrow new Error(\"device_ownership_authorization_unavailable\");\n}\n","import { DEVICE_REVOCATION_SUBJECT_EXISTS_SQL } from \"./coordinator-device-revocation.js\";\nimport {\n\tDEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL,\n\tLEGACY_ENROLLMENT_SOURCE_MATCH_SQL,\n} from \"./coordinator-legacy-device-ownership.js\";\nimport type {\n\tCoordinatorEnrollment,\n\tCoordinatorJoinRequest,\n} from \"./coordinator-store-contract.js\";\n\nexport const JOIN_REVIEW_COLUMNS = `request_id, group_id, device_id, public_key, fingerprint,\n display_name, token, status, created_at, reviewed_at, reviewed_by`;\n\n/** Evidence captured before hashing must remain current at every approval writer. */\nexport function joinReviewGuardEvidence(\n\trow: CoordinatorJoinRequest & { public_key: string },\n\tseed: CoordinatorEnrollment | null,\n\tkeys: { recipient: string | null; seed: string | null; current: string | null },\n\tcurrentPublicKey: string | null,\n) {\n\tconst revocationSql = `${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL} OR ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}`;\n\tconst revocationValues = [row.device_id, keys.recipient, seed?.device_id ?? null, keys.seed];\n\t// Reviewer/seed identity is not recipient ownership proof. Retain the old key even after upsert.\n\tconst ownershipSql = `${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL} OR ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}`;\n\tconst ownershipValues = [row.device_id, keys.recipient, row.device_id, keys.current];\n\tconst sourceValues = [\n\t\tcurrentPublicKey,\n\t\trow.group_id,\n\t\trow.device_id,\n\t\trow.group_id,\n\t\trow.device_id,\n\t\tcurrentPublicKey,\n\t];\n\tconst tupleSql = `EXISTS (SELECT 1 FROM coordinator_join_requests jr\n WHERE jr.request_id = ? AND jr.group_id = ? AND jr.device_id = ?\n AND jr.public_key = ? AND jr.fingerprint = ? AND jr.display_name IS ?\n AND jr.token = ? AND jr.created_at = ?)`;\n\tconst tupleValues = [\n\t\trow.request_id,\n\t\trow.group_id,\n\t\trow.device_id,\n\t\trow.public_key,\n\t\trow.fingerprint,\n\t\trow.display_name ?? null,\n\t\trow.token,\n\t\trow.created_at,\n\t];\n\tconst seedSql = `(? = 0 OR EXISTS (SELECT 1 FROM enrolled_devices se\n WHERE se.group_id = ? AND se.device_id = ? AND se.public_key = ?\n AND se.fingerprint = ? AND se.enabled = 1))`;\n\treturn {\n\t\trevocationSql,\n\t\trevocationValues,\n\t\townershipSql,\n\t\townershipValues,\n\t\tsourceSql: LEGACY_ENROLLMENT_SOURCE_MATCH_SQL,\n\t\tsourceValues,\n\t\teligibilitySql: `${tupleSql} AND ${seedSql} AND NOT (${revocationSql}) AND NOT (${ownershipSql})`,\n\t\teligibilityValues: [\n\t\t\t...tupleValues,\n\t\t\tseed ? 1 : 0,\n\t\t\trow.group_id,\n\t\t\tseed?.device_id ?? null,\n\t\t\tseed?.public_key ?? null,\n\t\t\tseed?.fingerprint ?? null,\n\t\t\t...revocationValues,\n\t\t\t...ownershipValues,\n\t\t],\n\t};\n}\n\nexport function joinReviewResultChanges(result: unknown): number {\n\tif (\n\t\t!result ||\n\t\ttypeof result !== \"object\" ||\n\t\t(\"success\" in result && result.success === false) ||\n\t\t!(\"meta\" in result) ||\n\t\t!result.meta ||\n\t\ttypeof result.meta !== \"object\" ||\n\t\t!(\"changes\" in result.meta) ||\n\t\t!Number.isSafeInteger(result.meta.changes) ||\n\t\t(result.meta.changes as number) < 0\n\t)\n\t\tthrow new Error(\"join_review_incomplete\");\n\treturn result.meta.changes as number;\n}\n\nexport function assertJoinReviewConfirmation(result: unknown): void {\n\tif (\n\t\t!result ||\n\t\ttypeof result !== \"object\" ||\n\t\t(\"success\" in result && result.success === false) ||\n\t\t!(\"results\" in result) ||\n\t\t!Array.isArray(result.results) ||\n\t\tresult.results.length !== 1 ||\n\t\tresult.results[0]?.confirmed !== 1\n\t) {\n\t\tthrow new Error(\"join_review_incomplete\");\n\t}\n}\n","import { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport {\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES,\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_GROUPS,\n\tCoordinatorLegacyTeamCompletionConflictError,\n\ttype CoordinatorLegacyTeamCompletionWriteResult,\n\tlegacyDecisionCountsAsOwnerSql,\n\tnormalizeCoordinatorLegacyTeamCompletionManifest,\n} from \"./coordinator-legacy-team-completion.js\";\nimport { LEGACY_TEAM_SETUP_MAX_DEVICES } from \"./legacy-team-setup-limits.js\";\n\nconst MAX_KEYS = COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_GROUPS * LEGACY_TEAM_SETUP_MAX_DEVICES;\n\n/** Both the early replay and the post-INSERT winner retain the canonical row. */\nexport function legacyCompletionWriteResult(\n\tstoredJson: string,\n\trequestedJson: string,\n\tstatus: CoordinatorLegacyTeamCompletionWriteResult[\"status\"],\n): CoordinatorLegacyTeamCompletionWriteResult {\n\tif (storedJson !== requestedJson) throw new CoordinatorLegacyTeamCompletionConflictError();\n\treturn {\n\t\tstatus,\n\t\tmanifest: normalizeCoordinatorLegacyTeamCompletionManifest(JSON.parse(storedJson)),\n\t};\n}\n\nconst completionJson = `CASE WHEN json_valid(c.manifest_json) THEN c.manifest_json ELSE '{}' END`;\n\n/** Only requesters and ownership-bearing evidence need canonical-key inference.\n * Keep discovery and the winning statement on the same sources: an ownerless\n * enrollment becomes relevant if it acquires an owner or an included completion.\n * Ledger bindings already carry canonical key IDs and need no text classification.\n */\nconst ownerSourceKeysSql = `legacy_owner_source_keys AS NOT MATERIALIZED (\n SELECT e.public_key FROM legacy_owner_input p,\n json_each(p.manifest, '$.device_decisions') d\n JOIN enrolled_devices e ON e.group_id = p.group_id\n AND e.device_id = json_extract(d.value, '$.device_id')\n AND e.fingerprint = json_extract(d.value, '$.key_fingerprint') AND e.enabled = 1\n WHERE json_extract(d.value, '$.decision') = 'included'\n UNION\n SELECT public_key FROM enrolled_devices WHERE identity_id IS NOT NULL\n UNION\n SELECT e.public_key FROM coordinator_legacy_team_completions c,\n json_each(${completionJson}, '$.device_decisions') d, legacy_owner_input p\n JOIN enrolled_devices e ON e.group_id = c.group_id\n AND e.device_id = json_extract(d.value, '$.device_id')\n AND e.fingerprint = json_extract(d.value, '$.key_fingerprint')\n WHERE json_extract(${completionJson}, '$.coordinator_id') = json_extract(p.manifest, '$.coordinator_id')\n AND (json_extract(d.value, '$.decision') = 'included' AND ${legacyDecisionCountsAsOwnerSql(\"d.value\")})\n)`;\n\n/** Bind canonical manifest JSON, then target group. */\nexport const LEGACY_OWNER_KEYS_SQL = `WITH legacy_owner_input(manifest, group_id) AS (\n VALUES (?, ?)\n), ${ownerSourceKeysSql}\n SELECT public_key FROM legacy_owner_source_keys\n WHERE EXISTS (SELECT 1 FROM legacy_owner_input p, json_each(p.manifest, '$.device_decisions')\n WHERE json_extract(value, '$.decision') = 'included')\n ORDER BY public_key LIMIT ${MAX_KEYS + 1}`;\n\n/** Classify server-held text aliases, never a fingerprint supplied as ownership proof.\n * Invalid unrelated keys supply no key inference; included requesters must have a\n * verified current key in the winning statement. No database I/O occurs here.\n */\nexport async function legacyOwnerKeyMetadata(\n\trows: readonly { public_key: string }[],\n): Promise<string> {\n\tif (rows.length > MAX_KEYS) throw new Error(\"completion_manifest_unavailable\");\n\tconst encoder = new TextEncoder();\n\tif (\n\t\tencoder.encode(JSON.stringify(rows)).byteLength > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES\n\t)\n\t\tthrow new Error(\"completion_manifest_unavailable\");\n\tconst metadata = [];\n\tfor (const { public_key } of rows) {\n\t\tconst keyId = await ed25519KeyIdForRevocation(public_key);\n\t\tlet fingerprint: string | null = null;\n\t\tif (keyId) {\n\t\t\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", encoder.encode(public_key));\n\t\t\tfingerprint = Array.from(new Uint8Array(digest), (byte) =>\n\t\t\t\tbyte.toString(16).padStart(2, \"0\"),\n\t\t\t).join(\"\");\n\t\t}\n\t\tmetadata.push({ public_key, key_id: keyId, fingerprint });\n\t}\n\tconst json = JSON.stringify(metadata);\n\tif (encoder.encode(json).byteLength > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES)\n\t\tthrow new Error(\"completion_manifest_unavailable\");\n\treturn json;\n}\n\n/** Bind canonical manifest JSON, target group, then server-derived key metadata.\n * Ownership-bearing enrollments are re-read at INSERT time. Reject newly relevant\n * text keys rather than letting an unclassified alias evade a canonical-key comparison.\n * Materialize the size-limited key metadata and requested rows so correlated\n * owner checks reuse them instead of repeatedly expanding their JSON inputs.\n * Join requested enrollments directly by group/device; a left-joined enrollment\n * CTE can materialize all groups sharing a key even with NOT MATERIALIZED.\n */\nexport const LEGACY_OWNER_INPUT_SQL = `WITH legacy_owner_input(manifest, group_id, keys) AS (\n VALUES (?, ?, ?)\n ), ${ownerSourceKeysSql}, legacy_owner_keys AS MATERIALIZED (\n SELECT json_extract(value, '$.public_key') AS public_key,\n json_extract(value, '$.key_id') AS key_id,\n json_extract(value, '$.fingerprint') AS fingerprint\n FROM legacy_owner_input p, json_each(p.keys)\n), legacy_owner_enrollments AS NOT MATERIALIZED (\n SELECT e.*, k.key_id FROM enrolled_devices e JOIN legacy_owner_keys k\n ON k.public_key = e.public_key AND k.fingerprint = e.fingerprint AND k.key_id IS NOT NULL\n), legacy_owner_requested AS MATERIALIZED (\n SELECT json_extract(d.value, '$.device_id') AS device_id,\n json_extract(d.value, '$.key_fingerprint') AS fingerprint,\n json_extract(d.value, '$.identity_id') AS identity_id, k.key_id\n FROM legacy_owner_input p, json_each(p.manifest, '$.device_decisions') d\n LEFT JOIN enrolled_devices e ON e.group_id = p.group_id\n AND e.device_id = json_extract(d.value, '$.device_id')\n AND e.fingerprint = json_extract(d.value, '$.key_fingerprint') AND e.enabled = 1\n LEFT JOIN legacy_owner_keys k ON k.public_key = e.public_key\n AND k.fingerprint = e.fingerprint AND k.key_id IS NOT NULL\n WHERE json_extract(d.value, '$.decision') = 'included'\n)`;\n\n// Missing/changed enrollment evidence is unavailable, not an inferred owner clash.\nexport const LEGACY_OWNER_SOURCE_CURRENT_SQL = `(NOT EXISTS (SELECT 1 FROM legacy_owner_requested)\n OR (NOT EXISTS (\n SELECT public_key FROM legacy_owner_source_keys EXCEPT SELECT public_key FROM legacy_owner_keys\n) AND NOT EXISTS (SELECT 1 FROM legacy_owner_requested WHERE key_id IS NULL)))`;\n\n/** Only included owner assignments compete. Labels, exclusions, and other people\n * never supply ownership. A stored label (another device's guess) never blocks a\n * later upload. Requested rows are all checked, labels included, so a new guess\n * still cannot contradict recorded ownership. Old fingerprints need a verified current enrollment\n * for the historical group/device; the exact device ID needs no key inference.\n * This predicate belongs in the winning INSERT, not just a preview/read check.\n */\nexport const LEGACY_OWNER_COMPATIBLE_SQL = `NOT EXISTS (\n SELECT 1 FROM legacy_owner_requested r WHERE\n EXISTS (SELECT 1 FROM legacy_owner_requested other\n WHERE other.key_id = r.key_id AND other.identity_id <> r.identity_id)\n OR EXISTS (SELECT 1 FROM enrolled_devices e\n WHERE e.identity_id IS NOT NULL AND e.identity_id <> r.identity_id\n AND (e.device_id = r.device_id OR EXISTS (\n SELECT 1 FROM legacy_owner_enrollments verified\n WHERE verified.group_id = e.group_id AND verified.device_id = e.device_id\n AND verified.key_id = r.key_id)))\n OR EXISTS (SELECT 1 FROM coordinator_device_ownership_bindings b\n WHERE (b.device_id = r.device_id OR b.key_id = r.key_id) AND b.identity_id <> r.identity_id)\n OR EXISTS (SELECT 1 FROM coordinator_legacy_team_completions c,\n json_each(${completionJson}, '$.device_decisions') d, legacy_owner_input p\n WHERE json_extract(${completionJson}, '$.coordinator_id') = json_extract(p.manifest, '$.coordinator_id')\n AND (json_extract(d.value, '$.decision') = 'included' AND ${legacyDecisionCountsAsOwnerSql(\"d.value\", \"deny\")})\n AND json_extract(d.value, '$.identity_id') <> r.identity_id\n AND (json_extract(d.value, '$.device_id') = r.device_id OR EXISTS (\n SELECT 1 FROM legacy_owner_enrollments e WHERE e.group_id = c.group_id\n AND e.device_id = json_extract(d.value, '$.device_id')\n AND e.fingerprint = json_extract(d.value, '$.key_fingerprint') AND e.key_id = r.key_id)))\n)`;\n\n/** Used only to explain a refused INSERT; this cannot authorize a write. */\nexport const LEGACY_OWNER_DENIAL_SQL = `${LEGACY_OWNER_INPUT_SQL}\n SELECT CASE WHEN NOT ${LEGACY_OWNER_SOURCE_CURRENT_SQL} THEN 'completion_manifest_unavailable'\n WHEN NOT (${LEGACY_OWNER_COMPATIBLE_SQL}) THEN 'completion_conflict'\n ELSE 'completion_manifest_unavailable' END AS denial`;\n","import {\n\ttype ControllerHistoryRecord,\n\ttype ControllerHistorySnapshot,\n\tcontrollerHistoryDiscoveryFragments,\n\tparseControllerHistoryRecord,\n} from \"./coordinator-auth-controller-history.js\";\nimport type { AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport {\n\tclassifyEvidence,\n\ttype EvidenceRow,\n\ttype EvidenceRows,\n\ttype EvidenceSubject,\n\tidentifier,\n\tkeyId,\n} from \"./coordinator-device-ownership-evidence-classify.js\";\nimport {\n\tCONTROLLER_COLUMNS,\n\tRESOLUTION_COLUMNS,\n} from \"./coordinator-device-ownership-evidence-queries.js\";\nimport {\n\tLEGACY_OWNER_COMPATIBLE_SQL,\n\tLEGACY_OWNER_INPUT_SQL,\n} from \"./coordinator-legacy-owner-compatibility.js\";\nimport {\n\tcanonicalReviewedWeakLabels,\n\tcaptureLegacyOwnerResolutionRecord,\n\tclassifyLegacyOwnerResolutionSchemaCatalog,\n\ttype LegacyOwnerResolutionRecord,\n} from \"./coordinator-legacy-owner-resolution-metadata.js\";\nimport {\n\tcanonicalCoordinatorLegacyTeamCompletionManifestJson,\n\tnormalizeCoordinatorLegacyTeamCompletionManifest,\n} from \"./coordinator-legacy-team-completion.js\";\n\ninterface Backend {\n\tfirst<T>(statement: AuthLinkStatement): Promise<T | null>;\n\tall<T>(statement: AuthLinkStatement): Promise<T[]>;\n}\n\n/** Internal capability, meaningful only to this module's WeakMap. */\nexport interface LegacyCompletionOwnerProof {\n\treadonly version: 1;\n}\n\ninterface Subject extends EvidenceSubject {\n\towner: string;\n\tfragments: string[];\n\tfingerprints: string[];\n}\ninterface KeyMetadata {\n\tpublic_key: string;\n\tkey_id: string | null;\n\tfingerprint: string | null;\n}\ninterface Snapshot {\n\tcoordinator: string;\n\tsubjects: Subject[];\n\tactive: Subject[];\n\tkeys: KeyMetadata[];\n\trows: Record<string, string[]>;\n\tapproved: string[];\n}\ninterface ProofSql {\n\t/** Append after LEGACY_OWNER_INPUT_SQL, which already starts WITH. */\n\treadonly ctes: string;\n\treadonly currentSql: string;\n\treadonly compatibleSql: string;\n\t/** Bind after the three LEGACY_OWNER_INPUT_SQL values. */\n\treadonly values: readonly string[];\n}\n\n// A single JSON bind must fit D1's 2 MB string/value limit. This aggregate\n// ceiling is separate from the established per-subject row/history ceilings.\n// Oversized captures are unavailable, never a smaller permitted roster.\nconst MAX_CAPTURE_BYTES = 2_000_000;\nconst MAX_SUBJECT_ROWS = 500;\nconst MAX_SUBJECT_BYTES = 2_000_000;\nconst MAX_HISTORY_BYTES = 750_000;\nconst MAX_DISCOVERY_KEYS = 8192;\nconst MAX_HISTORY_KEYS = 4096;\nconst encoder = new TextEncoder();\nconst snapshots = new WeakMap<LegacyCompletionOwnerProof, ProofSql>();\nconst table = \"coordinator_legacy_owner_resolutions\";\nconst catalogSql = `SELECT json_array(type,name,tbl_name,sql) AS row\n FROM sqlite_master WHERE tbl_name='${table}' AND sql IS NOT NULL`;\n\nfunction bytes(value: unknown): number {\n\treturn encoder.encode(JSON.stringify(value)).byteLength;\n}\n\nfunction requireProof(condition: unknown): asserts condition {\n\tif (!condition) throw new Error(\"completion_manifest_unavailable\");\n}\n\nfunction rowset(columns: string[], from: string): string {\n\treturn `SELECT DISTINCT json_array(${columns.join(\",\")}) AS row FROM ${from}`;\n}\n\n/** Keep original JSON scalar spellings, including numeric formatting and string\n * escapes. Parsing/stringifying cells would change e.g. 1.0 or escaped Unicode.\n */\nfunction rowAtoms(row: string): string[] {\n\tconst atoms =\n\t\trow.match(/\"(?:[^\"\\\\]|\\\\.)*\"|null|-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?/gu) ?? [];\n\trequireProof(`[${atoms.join(\",\")}]` === row);\n\treturn atoms;\n}\n\nfunction encodeRows(rows: Snapshot[\"rows\"]): {\n\tatoms: string[];\n\trows: Record<string, number[][]>;\n} {\n\tconst atoms: string[] = [];\n\tconst indexes = new Map<string, number>();\n\tconst intern = (atom: string): number => {\n\t\tconst existing = indexes.get(atom);\n\t\tif (existing !== undefined) return existing;\n\t\tconst index = atoms.length;\n\t\tatoms.push(atom);\n\t\tindexes.set(atom, index);\n\t\treturn index;\n\t};\n\treturn {\n\t\tatoms,\n\t\trows: Object.fromEntries(\n\t\t\tObject.entries(rows).map(([name, values]) => [\n\t\t\t\tname,\n\t\t\t\tvalues.map((row) => rowAtoms(row).map(intern)),\n\t\t\t]),\n\t\t),\n\t};\n}\n\n/** SQL needs only selector fields. Active subjects refer to this shared roster;\n * expected row cells refer to one private dictionary of original JSON lexemes.\n */\nfunction encodeSnapshot(snapshot: Snapshot): string {\n\tconst active = new Set(snapshot.active);\n\treturn JSON.stringify({\n\t\t...snapshot,\n\t\tsubjects: snapshot.subjects.map(({ deviceId, keyId, publicKey, fragments, fingerprints }) => ({\n\t\t\tdeviceId,\n\t\t\tkeyId,\n\t\t\tpublicKey,\n\t\t\tfragments,\n\t\t\tfingerprints,\n\t\t})),\n\t\tactive: snapshot.subjects.flatMap((subject, index) => (active.has(subject) ? [index] : [])),\n\t\t...encodeRows(snapshot.rows),\n\t});\n}\n\nconst subjectColumns = [\"deviceId\", \"keyId\", \"publicKey\", \"fragments\", \"fingerprints\"]\n\t.map((name) => `json_extract(j.value,'$.${name}') AS ${name}`)\n\t.join(\",\");\nconst subjectCtes = `completion_proof_input(value) AS MATERIALIZED (SELECT ?),\n completion_proof_atoms(atom_index,lexeme) AS MATERIALIZED (\n SELECT j.key,j.value FROM completion_proof_input i,json_each(i.value,'$.atoms') j),\n completion_proof_subjects AS MATERIALIZED (\n SELECT j.key AS ordinal,j.value,${subjectColumns} FROM completion_proof_input i,json_each(i.value,'$.subjects') j),\n completion_proof_active AS MATERIALIZED (\n SELECT s.* FROM completion_proof_input i,json_each(i.value,'$.active') j\n JOIN completion_proof_subjects s ON s.ordinal=j.value),\n completion_proof_fragments(fragment) AS MATERIALIZED (\n SELECT DISTINCT f.value FROM completion_proof_active s,json_each(s.fragments) f),\n completion_proof_fingerprints(fingerprint) AS MATERIALIZED (\n SELECT DISTINCT f.value FROM completion_proof_active s,json_each(s.value,'$.fingerprints') f),\n completion_proof_approved AS MATERIALIZED (\n SELECT j.value FROM completion_proof_input i,json_each(i.value,'$.approved') j),\n completion_proof_keys AS MATERIALIZED (\n SELECT json_extract(j.value,'$.public_key') AS public_key,\n json_extract(j.value,'$.key_id') AS key_id,\n json_extract(j.value,'$.fingerprint') AS fingerprint\n FROM completion_proof_input i,json_each(i.value,'$.keys') j)`;\nconst coordinator = `(SELECT json_extract(value,'$.coordinator') FROM completion_proof_input)`;\nconst field = (name: string) => `s.${name}`;\nconst collision = (device: string, key: string) =>\n\t`(${device} IN (SELECT deviceId FROM completion_proof_active) OR ${key} IN (SELECT keyId FROM completion_proof_active))`;\n\n// Conservative text discovery has the same ordinary-key fast path and malformed\n// token fallback as the accepted single-subject reader. JS alone decides aliases.\n// Materialize token parsing before roster matching: inlining it into each\n// correlated fragment check repeats whitespace/token work for every subject.\n// Distributing the existential OR preserves its rowset while sharing lookup sets.\nconst discoveryCtes = `completion_proof_key_sources AS NOT MATERIALIZED (\n SELECT 'enrollment' AS source,group_id AS id,device_id,public_key,fingerprint FROM enrolled_devices\n UNION ALL SELECT 'controller',attestation_id,device_id,public_key,fingerprint\n FROM coordinator_auth_controller_attestations WHERE coordinator_id=${coordinator}\n UNION ALL SELECT 'invite',invite_id,bound_device_id,bound_public_key,bound_fingerprint\n FROM coordinator_invites WHERE consumed_at IS NOT NULL),\n completion_proof_lines AS NOT MATERIALIZED (\n SELECT *,ltrim(replace(replace(replace(replace(replace(public_key,char(9),' '),char(10),' '),char(11),' '),char(12),' '),char(13),' '),' ') AS line\n FROM completion_proof_key_sources),\n completion_proof_tails AS NOT MATERIALIZED (\n SELECT *,CASE WHEN substr(line,1,12)='ssh-ed25519 ' THEN ltrim(substr(line,13),' ') ELSE NULL END AS tail FROM completion_proof_lines),\n completion_proof_tokens AS MATERIALIZED (\n SELECT *,CASE WHEN tail IS NOT NULL THEN substr(tail,1,instr(tail || ' ',' ')-1) ELSE NULL END AS token FROM completion_proof_tails),\n completion_proof_discovery AS MATERIALIZED (\n SELECT t.* FROM completion_proof_tokens t WHERE EXISTS (SELECT 1 FROM completion_proof_active)\n AND (t.device_id IN (SELECT deviceId FROM completion_proof_active)\n OR t.public_key IN (SELECT publicKey FROM completion_proof_active) OR instr(t.public_key,char(0))>0\n OR t.token IS NULL OR t.token GLOB '*[^A-Za-z0-9+/=_-]*'\n OR EXISTS (SELECT 1 FROM completion_proof_fragments f\n WHERE instr(replace(replace(t.token,'-','+'),'_','/'),f.fragment)>0)))`;\n\nconst resolutionSql = rowset(\n\tRESOLUTION_COLUMNS,\n\t`${table} r WHERE r.coordinator_id=${coordinator}\n AND (r.device_id IN (SELECT deviceId FROM completion_proof_subjects)\n OR r.key_id IN (SELECT keyId FROM completion_proof_subjects))`,\n);\nconst historyParsed = `CASE WHEN json_valid(c.manifest_json) THEN c.manifest_json ELSE '{}' END`;\nconst historyDecision = `CASE WHEN d.type='object' THEN d.value ELSE '{}' END`;\n// Share exact device/fingerprint lookups within each statement, not across capture\n// and INSERT. Only malformed text discovery still needs per-subject matching.\nconst historySql = rowset(\n\t\"c.group_id,c.candidate_ref,c.manifest_version,c.completed_at,c.created_at,c.manifest_json\".split(\n\t\t\",\",\n\t),\n\t`coordinator_legacy_team_completions c\n WHERE (json_extract(${historyParsed},'$.coordinator_id')=${coordinator}\n OR json_extract(${historyParsed},'$.coordinator_id') IS NULL)\n AND (EXISTS (SELECT 1 FROM json_each(${historyParsed},'$.device_decisions') d\n WHERE json_extract(${historyDecision},'$.device_id') IN (SELECT deviceId FROM completion_proof_active)\n OR json_extract(${historyDecision},'$.key_fingerprint') IN (SELECT fingerprint FROM completion_proof_fingerprints)\n OR ((d.type<>'object' OR json_type(${historyDecision},'$.device_id') IS NOT 'text'\n OR json_type(${historyDecision},'$.key_fingerprint') IS NOT 'text')\n AND EXISTS (SELECT 1 FROM completion_proof_active s WHERE\n instr(CASE WHEN d.type='text' THEN json_quote(d.value) ELSE d.value END,json_quote(${field(\"deviceId\")}))>0\n OR EXISTS (SELECT 1 FROM json_each(s.value,'$.fingerprints') f WHERE instr(d.value,f.value)>0))))\n OR ((json_valid(c.manifest_json)=0 OR json_type(${historyParsed},'$.device_decisions') IS NOT 'array')\n AND EXISTS (SELECT 1 FROM completion_proof_active s WHERE instr(c.manifest_json,json_quote(${field(\"deviceId\")}))>0\n OR EXISTS (SELECT 1 FROM json_each(s.value,'$.fingerprints') f WHERE instr(c.manifest_json,f.value)>0))))`,\n);\n\nfunction evidenceQueries(): Record<string, string> {\n\treturn {\n\t\tschema: catalogSql,\n\t\tresolutions: resolutionSql,\n\t\tdiscovery: rowset([\"source\", \"id\"], \"completion_proof_discovery WHERE source<>'enrollment'\"),\n\t\tbindings: rowset(\n\t\t\t\"device_id,key_id,identity_id,coordinator_id,binding_id,provenance,source_ref,bound_at\".split(\n\t\t\t\t\",\",\n\t\t\t),\n\t\t\t`coordinator_device_ownership_bindings WHERE ${collision(\"device_id\", \"key_id\")}`,\n\t\t),\n\t\tclaims: rowset(\n\t\t\t\"claim_id,coordinator_id,identity_id,group_id,device_id,public_key,fingerprint,key_id,attempt_id,issuer,auth_config_revision,created_at_ms\".split(\n\t\t\t\t\",\",\n\t\t\t),\n\t\t\t`coordinator_auth_device_claims WHERE coordinator_id=${coordinator} AND ${collision(\"device_id\", \"key_id\")}`,\n\t\t),\n\t\tcontrollers: rowset(\n\t\t\tCONTROLLER_COLUMNS.map((column) => `c.${column}`),\n\t\t\t`coordinator_auth_controller_attestations c WHERE c.coordinator_id=${coordinator}\n AND (c.attestation_id IN (SELECT id FROM completion_proof_discovery WHERE source='controller')\n OR c.attestation_id IN (SELECT json_extract(row,'$[8]') FROM completion_observed_resolutions))`,\n\t\t),\n\t\tinvites: rowset(\n\t\t\t\"invite_id,group_id,policy,created_at,expires_at,consumed_at,revoked_at,bound_device_id,bound_public_key,bound_fingerprint,invite_kind,assigned_identity_id,target_identity_id,recipient_actor_id,reviewed_preview_digest\".split(\n\t\t\t\t\",\",\n\t\t\t),\n\t\t\t\"coordinator_invites WHERE invite_id IN (SELECT id FROM completion_proof_discovery WHERE source='invite')\",\n\t\t),\n\t\tenrollment: rowset(\n\t\t\t\"e.group_id,e.device_id,e.public_key,e.fingerprint,e.identity_id,e.enabled,g.archived_at\".split(\n\t\t\t\t\",\",\n\t\t\t),\n\t\t\t`enrolled_devices e LEFT JOIN groups g ON g.group_id=e.group_id\n LEFT JOIN completion_proof_keys k ON k.public_key=e.public_key AND k.fingerprint=e.fingerprint\n WHERE ${collision(\"e.device_id\", \"k.key_id\")}`,\n\t\t),\n\t\trevocations: rowset(\n\t\t\t\"subject_kind,subject_value,revocation_id,evidence_group_id,evidence_device_id,evidence_public_key,evidence_fingerprint,actor_id,created_at\".split(\n\t\t\t\t\",\",\n\t\t\t),\n\t\t\t`coordinator_device_revocations v WHERE EXISTS (SELECT 1 FROM completion_proof_active s\n WHERE (v.subject_kind='device_id' AND v.subject_value=${field(\"deviceId\")})\n OR (v.subject_kind='ed25519_key' AND v.subject_value=${field(\"keyId\")}))`,\n\t\t),\n\t\thistory: historySql,\n\t\thistoryKeys: rowset(\n\t\t\t[\"public_key\", \"fingerprint\"],\n\t\t\t\"completion_proof_discovery WHERE source<>'invite'\",\n\t\t),\n\t\thistoryDiscovery: rowset([\"public_key\"], \"completion_proof_discovery WHERE source<>'invite'\"),\n\t};\n}\n\nfunction capturePrefix(queries: Record<string, string>): string {\n\tconst resolutions = queries.resolutions;\n\trequireProof(resolutions);\n\treturn `WITH ${subjectCtes},${discoveryCtes},completion_observed_resolutions(row) AS MATERIALIZED (${resolutions})`;\n}\n\nasync function readRows(\n\tbackend: Backend,\n\tsql: string,\n\tparameters: string[] = [],\n): Promise<{ encoded: string[]; parsed: EvidenceRow[] }> {\n\tconst selected = await backend.all<{ row: string | null }>({\n\t\tsql: `SELECT CASE WHEN SUM(length(CAST(row AS BLOB))) OVER ()<=${MAX_CAPTURE_BYTES}\n THEN row ELSE NULL END AS row FROM (${sql}) LIMIT ${MAX_CAPTURE_BYTES + 1}`,\n\t\tvalues: parameters,\n\t});\n\tconst encoded: string[] = [];\n\tconst parsed = selected.map(({ row }) => {\n\t\trequireProof(typeof row === \"string\");\n\t\tconst value: unknown = JSON.parse(row);\n\t\trequireProof(\n\t\t\tArray.isArray(value) &&\n\t\t\t\tvalue.every(\n\t\t\t\t\t(item) => item === null || typeof item === \"string\" || typeof item === \"number\",\n\t\t\t\t),\n\t\t);\n\t\tencoded.push(row);\n\t\treturn value as EvidenceRow;\n\t});\n\trequireProof(bytes(encoded) <= MAX_CAPTURE_BYTES);\n\treturn { encoded, parsed };\n}\n\nasync function requestedSubjects(input: {\n\tbackend: Backend;\n\tgroupId: string;\n\tmanifestJson: string;\n\tkeyMetadata: string;\n}): Promise<{ subjects: Subject[]; coordinator: string; keys: KeyMetadata[] }> {\n\tconst manifest = normalizeCoordinatorLegacyTeamCompletionManifest(JSON.parse(input.manifestJson));\n\trequireProof(\n\t\tcanonicalCoordinatorLegacyTeamCompletionManifestJson(manifest) === input.manifestJson,\n\t);\n\trequireProof(identifier(input.groupId));\n\tconst selected = await input.backend.all<{\n\t\tdevice_id: string;\n\t\tpublic_key: string;\n\t\tfingerprint: string;\n\t\tidentity_id: string;\n\t\tkey_id: string;\n\t}>({\n\t\tsql: `${LEGACY_OWNER_INPUT_SQL} SELECT r.*,e.public_key FROM legacy_owner_requested r\n JOIN enrolled_devices e ON e.group_id=? AND e.device_id=r.device_id AND e.fingerprint=r.fingerprint`,\n\t\tvalues: [input.manifestJson, input.groupId, input.keyMetadata, input.groupId],\n\t});\n\trequireProof(\n\t\tselected.length === manifest.device_decisions.filter((d) => d.decision === \"included\").length,\n\t);\n\tconst subjects: Subject[] = [];\n\tfor (const row of selected) {\n\t\trequireProof(identifier(row.identity_id) && (await keyId(row.public_key)) === row.key_id);\n\t\tsubjects.push({\n\t\t\tcoordinatorId: manifest.coordinator_id,\n\t\t\tgroupId: input.groupId,\n\t\t\tdeviceId: row.device_id,\n\t\t\tpublicKey: row.public_key,\n\t\t\tfingerprint: row.fingerprint,\n\t\t\tkeyId: row.key_id,\n\t\t\towner: row.identity_id,\n\t\t\tfragments: controllerHistoryDiscoveryFragments(row.public_key),\n\t\t\tfingerprints: [row.fingerprint],\n\t\t});\n\t}\n\treturn { subjects, coordinator: manifest.coordinator_id, keys: JSON.parse(input.keyMetadata) };\n}\n\nfunction relevantFact(row: EvidenceRow, subject: Subject): boolean {\n\treturn row[3] === subject.deviceId || row[4] === subject.keyId;\n}\n\nfunction historyRecord(row: EvidenceRow): ControllerHistoryRecord {\n\treturn Object.fromEntries(\n\t\t[\n\t\t\t\"group_id\",\n\t\t\t\"candidate_ref\",\n\t\t\t\"manifest_version\",\n\t\t\t\"completed_at\",\n\t\t\t\"created_at\",\n\t\t\t\"manifest_json\",\n\t\t].map((column, i) => [column, row[i]]),\n\t) as unknown as ControllerHistoryRecord;\n}\n\nasync function canonicalKeys(rows: EvidenceRows): Promise<Map<string, string>> {\n\tconst keys = new Set<string>();\n\tfor (const row of rows.historyKeys ?? []) keys.add(String(row[0]));\n\tfor (const row of rows.controllers ?? []) keys.add(String(row[5]));\n\tfor (const row of rows.invites ?? []) keys.add(String(row[8]));\n\tconst result = new Map<string, string>();\n\tfor (const text of keys) {\n\t\ttry {\n\t\t\tresult.set(text, await keyId(text));\n\t\t} catch {\n\t\t\t// Discovery is not proof. Relevant device collisions still reach the\n\t\t\t// classifier, which rejects malformed source key text.\n\t\t}\n\t}\n\treturn result;\n}\n\nfunction discoversKey(publicKey: string, subject: Subject): boolean {\n\tif (publicKey === subject.publicKey || publicKey.includes(\"\\u0000\")) return true;\n\tconst line = publicKey.replace(/[\\t\\n\\v\\f\\r]/gu, \" \").replace(/^ +/u, \"\");\n\tif (!line.startsWith(\"ssh-ed25519 \")) return true;\n\tconst token = line.slice(12).replace(/^ +/u, \"\").split(\" \")[0] ?? \"\";\n\tif (/[^A-Za-z0-9+/=_-]/u.test(token)) return true;\n\tconst normalized = token.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\");\n\treturn subject.fragments.some((fragment) => normalized.includes(fragment));\n}\n\n/** Internal capture preparation; not exported from the package entrypoint. */\nexport function prepareCompletionHistory(\n\trows: EvidenceRow[],\n\tdecode: (text: string) => unknown = JSON.parse,\n) {\n\treturn rows.map((row) => {\n\t\tconst record = historyRecord(row);\n\t\tlet decoded = false;\n\t\tlet value: unknown;\n\t\treturn {\n\t\t\trow,\n\t\t\trecord,\n\t\t\tdecode: () => {\n\t\t\t\tif (decoded) return value;\n\t\t\t\tdecoded = true;\n\t\t\t\ttry {\n\t\t\t\t\tvalue = decode(record.manifest_json);\n\t\t\t\t} catch {\n\t\t\t\t\t// A failed raw decode is not itself denial: each subject still\n\t\t\t\t\t// checks whether this malformed row plausibly references it.\n\t\t\t\t}\n\t\t\t\treturn value;\n\t\t\t},\n\t\t};\n\t});\n}\n\n/** Internal subject view; canonical validation remains subject-specific. */\nexport function subjectHistory(\n\trows: EvidenceRows,\n\tsubject: Subject,\n\tkeys: Map<string, string>,\n\tprepared: ReturnType<typeof prepareCompletionHistory>,\n): ControllerHistorySnapshot {\n\tconst pairs = (rows.historyKeys ?? []).filter(\n\t\t(row) => keys.get(String(row[0])) === subject.keyId,\n\t);\n\trequireProof(pairs.length <= MAX_HISTORY_KEYS);\n\tconst fingerprints = new Set([subject.fingerprint, ...pairs.map((row) => String(row[1]))]);\n\tconst records = prepared.filter(({ record, decode }) => {\n\t\t// The SQL selector retains malformed plausible matches. Do not silently drop\n\t\t// them while partitioning a shared capture into individual classifier views.\n\t\tconst value = decode();\n\t\tconst manifest = value as { device_decisions?: unknown[] };\n\t\tif (!Array.isArray(manifest?.device_decisions)) {\n\t\t\trequireProof(!record.manifest_json.includes(JSON.stringify(subject.deviceId)));\n\t\t\trequireProof(![...fingerprints].some((fp) => record.manifest_json.includes(fp)));\n\t\t\treturn false;\n\t\t}\n\t\treturn manifest.device_decisions.some((decision) => {\n\t\t\tconst d = decision as { device_id?: string; key_fingerprint?: string } | null;\n\t\t\tif (d?.device_id === subject.deviceId || fingerprints.has(String(d?.key_fingerprint)))\n\t\t\t\treturn true;\n\t\t\tif (typeof d?.device_id === \"string\" && typeof d?.key_fingerprint === \"string\") return false;\n\t\t\tconst text = JSON.stringify(decision);\n\t\t\treturn (\n\t\t\t\ttext.includes(JSON.stringify(subject.deviceId)) ||\n\t\t\t\t[...fingerprints].some((fp) => text.includes(fp))\n\t\t\t);\n\t\t});\n\t});\n\trequireProof(\n\t\trecords.length <= MAX_SUBJECT_ROWS && bytes(records.map(({ row }) => row)) <= MAX_HISTORY_BYTES,\n\t);\n\tconst history: ControllerHistorySnapshot = {\n\t\t...subject,\n\t\tkeys: pairs.map((row) => ({ public_key: String(row[0]), fingerprint: String(row[1]) })),\n\t\tdiscoveryKeys: (rows.historyDiscovery ?? [])\n\t\t\t.map((row) => String(row[0]))\n\t\t\t.filter((publicKey) => discoversKey(publicKey, subject)),\n\t\tdiscoveryFragments: subject.fragments,\n\t\tfingerprints: [...fingerprints].sort(),\n\t\trecords: records.map(({ record }) => {\n\t\t\tparseControllerHistoryRecord(record, subject.coordinatorId);\n\t\t\treturn record;\n\t\t}),\n\t};\n\trequireProof(bytes(history) <= MAX_HISTORY_BYTES);\n\treturn history;\n}\n\nfunction subjectRows(\n\trows: EvidenceRows,\n\tsubject: Subject,\n\tkeys: Map<string, string>,\n\thistory: ControllerHistorySnapshot,\n): EvidenceRows {\n\tconst matches = (row: EvidenceRow, device: number, key: number) =>\n\t\trow[device] === subject.deviceId ||\n\t\tkeys.get(String(row[key])) === subject.keyId ||\n\t\tdiscoversKey(String(row[key]), subject);\n\tconst selected: EvidenceRows = {\n\t\tbindings: (rows.bindings ?? []).filter(\n\t\t\t(r) => r[0] === subject.deviceId || r[1] === subject.keyId,\n\t\t),\n\t\tclaims: (rows.claims ?? []).filter((r) => r[4] === subject.deviceId || r[7] === subject.keyId),\n\t\tcontrollers: (rows.controllers ?? []).filter((r) => matches(r, 4, 5)),\n\t\tinvites: (rows.invites ?? []).filter((r) => matches(r, 7, 8)),\n\t\tenrollment: (rows.enrollment ?? []).filter(\n\t\t\t(r) => r[0] === subject.groupId && r[1] === subject.deviceId,\n\t\t),\n\t\tresolutions: (rows.resolutions ?? []).filter((r) => relevantFact(r, subject)),\n\t\trevocations: (rows.revocations ?? []).filter(\n\t\t\t(r) =>\n\t\t\t\t(r[0] === \"device_id\" && r[1] === subject.deviceId) ||\n\t\t\t\t(r[0] === \"ed25519_key\" && r[1] === subject.keyId),\n\t\t),\n\t};\n\tfor (const values of Object.values(selected)) requireProof(values.length <= MAX_SUBJECT_ROWS);\n\trequireProof(\n\t\t(selected.controllers?.length ?? 0) + (selected.invites?.length ?? 0) <= MAX_SUBJECT_ROWS,\n\t);\n\trequireProof(bytes(selected) <= MAX_SUBJECT_BYTES);\n\trequireProof(history.discoveryKeys.length <= MAX_DISCOVERY_KEYS);\n\treturn selected;\n}\n\nfunction originalSourceMatches(\n\tresolution: LegacyOwnerResolutionRecord,\n\tsource: EvidenceRow,\n\tsubject: Subject,\n\tkeys: Map<string, string>,\n): boolean {\n\tconst expected: EvidenceRow = [\n\t\tresolution.source_attestation_id,\n\t\tresolution.coordinator_id,\n\t\tresolution.owner_identity_id,\n\t\tresolution.source_group_id,\n\t\tresolution.device_id,\n\t\tresolution.source_public_key,\n\t\tresolution.source_fingerprint,\n\t\tresolution.source_review_receipt_id,\n\t\tresolution.source_evidence_digest,\n\t\tresolution.source_enrollment_identity_id,\n\t\tresolution.source_controller_revision,\n\t\tresolution.source_created_at,\n\t\tnull,\n\t];\n\treturn (\n\t\tsource.length === expected.length &&\n\t\tsource.every((value, i) => value === expected[i]) &&\n\t\tkeys.get(String(source[5])) === subject.keyId\n\t);\n}\n\nasync function hasOriginalSource(\n\trows: EvidenceRows,\n\tsubject: Subject,\n\tkeys: Map<string, string>,\n): Promise<boolean> {\n\tfor (const row of rows.resolutions ?? []) {\n\t\tconst resolution = await captureLegacyOwnerResolutionRecord(\n\t\t\tObject.fromEntries(RESOLUTION_COLUMNS.map((column, i) => [column, row[i]])),\n\t\t);\n\t\trequireProof(resolution);\n\t\tif (\n\t\t\tresolution.coordinator_id === subject.coordinatorId &&\n\t\t\tresolution.device_id === subject.deviceId &&\n\t\t\tresolution.key_id === subject.keyId &&\n\t\t\tresolution.owner_identity_id === subject.owner &&\n\t\t\t(rows.controllers ?? []).some((source) =>\n\t\t\t\toriginalSourceMatches(resolution, source, subject, keys),\n\t\t\t)\n\t\t)\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\nasync function approveSubject(\n\trows: EvidenceRows,\n\tsubject: Subject,\n\tkeys: Map<string, string>,\n\tprepared: ReturnType<typeof prepareCompletionHistory>,\n): Promise<boolean> {\n\tconst history = subjectHistory(rows, subject, keys, prepared);\n\tconst selected = subjectRows(rows, subject, keys, history);\n\tconst classification = await classifyEvidence(selected, subject, subject.owner, history);\n\tif (![\"compatible\", \"weak_label_review_required\"].includes(classification.decision)) return false;\n\t// Duplicate weak source tuples cannot be attributed to one reviewed origin.\n\t// Stored reviewed-label strings are never consulted as positive authority.\n\tif (canonicalReviewedWeakLabels(classification.weakLabels) === null) return false;\n\tconst enrollments = (rows.enrollment ?? []).filter(\n\t\t(row) => row[1] === subject.deviceId || keys.get(String(row[2])) === subject.keyId,\n\t);\n\trequireProof(enrollments.length <= MAX_SUBJECT_ROWS && bytes(enrollments) <= MAX_SUBJECT_BYTES);\n\tfor (const row of enrollments) {\n\t\tif (row[4] === null || row[4] === subject.owner) continue;\n\t\tconst verifiedOrigin = classification.weakLabels.some(\n\t\t\t(weak) =>\n\t\t\t\tweak.label === row[4] &&\n\t\t\t\t(row[0] === subject.groupId || (weak.group_id === row[0] && weak.device_id === row[1])),\n\t\t);\n\t\tif (!verifiedOrigin) return false;\n\t}\n\treturn hasOriginalSource(selected, subject, keys);\n}\n\nfunction pinSql(queries: Record<string, string>): { ctes: string; predicate: string } {\n\tconst stages: string[] = [];\n\tconst predicates: string[] = [];\n\tfor (const [name, sql] of Object.entries(queries)) {\n\t\tif (name !== \"resolutions\")\n\t\t\tstages.push(`completion_observed_${name}(row) AS MATERIALIZED (${sql})`);\n\t\tstages.push(`completion_expected_${name}(row) AS MATERIALIZED (\n SELECT '[' || group_concat(a.lexeme,',' ORDER BY c.key) || ']'\n FROM completion_proof_input i,json_each(i.value,'$.rows.${name}') r,\n json_each(r.value) c JOIN completion_proof_atoms a ON a.atom_index=c.value\n GROUP BY r.key)`);\n\t\tstages.push(`completion_added_${name}(row) AS MATERIALIZED (\n SELECT row FROM completion_observed_${name} EXCEPT SELECT row FROM completion_expected_${name})`);\n\t\tstages.push(`completion_removed_${name}(row) AS MATERIALIZED (\n SELECT row FROM completion_expected_${name} EXCEPT SELECT row FROM completion_observed_${name})`);\n\t\tpredicates.push(\n\t\t\t`NOT EXISTS (SELECT 1 FROM completion_added_${name})`,\n\t\t\t`NOT EXISTS (SELECT 1 FROM completion_removed_${name})`,\n\t\t);\n\t}\n\treturn { ctes: stages.join(\",\\n\"), predicate: predicates.join(\" AND \") };\n}\n\nconst approvedSubject = `EXISTS (SELECT 1 FROM completion_proof_approved a\n WHERE a.value=json_array(r.device_id,r.key_id,r.identity_id))`;\n\n// Only the two weak-label branches gain an exception. Intra-roster owner\n// assignments and ledger bindings retain the exact existing checks.\nfunction replaceExactlyOnce(sql: string, target: string, replacement: string): string {\n\tif (sql.split(target).length !== 2) throw new Error(\"legacy_owner_compatible_sql_drifted\");\n\treturn sql.replace(target, replacement);\n}\n\n// Fails at load rather than silently dropping an exception if the source SQL changes.\nconst recoveredCompatibleSql = replaceExactlyOnce(\n\treplaceExactlyOnce(\n\t\tLEGACY_OWNER_COMPATIBLE_SQL,\n\t\t\"WHERE e.identity_id IS NOT NULL AND e.identity_id <> r.identity_id\",\n\t\t`WHERE e.identity_id IS NOT NULL AND e.identity_id <> r.identity_id AND NOT (${approvedSubject})`,\n\t),\n\t\"AND json_extract(d.value, '$.identity_id') <> r.identity_id\",\n\t`AND json_extract(d.value, '$.identity_id') <> r.identity_id AND NOT (${approvedSubject})`,\n);\n\nfunction remember(sql: ProofSql): LegacyCompletionOwnerProof {\n\tconst token = Object.freeze({ version: 1 as const });\n\tsnapshots.set(token, Object.freeze({ ...sql, values: Object.freeze([...sql.values]) }));\n\treturn token;\n}\n\nfunction finishCapture(\n\tsnapshot: Snapshot,\n\tqueries: Record<string, string>,\n\toptions: { compatible: boolean; recovered: boolean; missing?: boolean },\n): LegacyCompletionOwnerProof {\n\tconst encoded = encodeSnapshot(snapshot);\n\trequireProof(encoder.encode(encoded).byteLength <= MAX_CAPTURE_BYTES);\n\tconst pin = pinSql(queries);\n\tlet ctes = `,${subjectCtes}`;\n\tif (!options.missing) {\n\t\tctes += `,${discoveryCtes},completion_observed_resolutions(row) AS MATERIALIZED (${resolutionSql})`;\n\t}\n\tctes += `,${pin.ctes}`;\n\tlet compatibleSql = \"0\";\n\tif (options.compatible) {\n\t\tcompatibleSql = LEGACY_OWNER_COMPATIBLE_SQL;\n\t\tif (options.recovered) compatibleSql = recoveredCompatibleSql;\n\t}\n\treturn remember({ ctes, currentSql: pin.predicate, compatibleSql, values: [encoded] });\n}\n\nasync function captureReady(\n\tbackend: Backend,\n\tsnapshot: Snapshot,\n): Promise<LegacyCompletionOwnerProof> {\n\tconst queries = evidenceQueries();\n\tconst initialPrefix = `WITH ${subjectCtes}`;\n\tconst facts = await readRows(backend, `${initialPrefix} ${resolutionSql}`, [\n\t\tencodeSnapshot(snapshot),\n\t]);\n\tsnapshot.rows.resolutions = facts.encoded;\n\tsnapshot.active = snapshot.subjects.filter((s) => facts.parsed.some((r) => relevantFact(r, s)));\n\tif (snapshot.active.length === 0)\n\t\treturn finishCapture(\n\t\t\tsnapshot,\n\t\t\t{ schema: catalogSql, resolutions: resolutionSql },\n\t\t\t{ compatible: true, recovered: false },\n\t\t);\n\tconst rows: EvidenceRows = { resolutions: facts.parsed };\n\tconst prefix = capturePrefix(queries);\n\t// Capture the shared key inventory once before selecting history by verified\n\t// aliases. History bytes and source rows are stored once, not per roster member.\n\tfor (const name of [\"historyKeys\", \"historyDiscovery\"]) {\n\t\tconst sql = queries[name];\n\t\trequireProof(sql);\n\t\tconst result = await readRows(backend, `${prefix} ${sql}`, [encodeSnapshot(snapshot)]);\n\t\trows[name] = result.parsed;\n\t\tsnapshot.rows[name] = result.encoded;\n\t}\n\tconst aliasKeys = await canonicalKeys(rows);\n\tfor (const subject of snapshot.active) {\n\t\tsubject.fingerprints = [\n\t\t\t...new Set([\n\t\t\t\tsubject.fingerprint,\n\t\t\t\t...(rows.historyKeys ?? [])\n\t\t\t\t\t.filter((row) => aliasKeys.get(String(row[0])) === subject.keyId)\n\t\t\t\t\t.map((row) => String(row[1])),\n\t\t\t]),\n\t\t].sort();\n\t}\n\tfor (const [name, sql] of Object.entries(queries)) {\n\t\tif (Object.hasOwn(snapshot.rows, name)) continue;\n\t\tconst result = await readRows(backend, `${prefix} ${sql}`, [encodeSnapshot(snapshot)]);\n\t\trows[name] = result.parsed;\n\t\tsnapshot.rows[name] = result.encoded;\n\t}\n\tconst keys = await canonicalKeys(rows);\n\tconst prepared = prepareCompletionHistory(rows.history ?? []);\n\tlet compatible = true;\n\tfor (const subject of snapshot.active) {\n\t\tif (!(await approveSubject(rows, subject, keys, prepared))) {\n\t\t\tcompatible = false;\n\t\t\tcontinue;\n\t\t}\n\t\tsnapshot.approved.push(JSON.stringify([subject.deviceId, subject.keyId, subject.owner]));\n\t}\n\treturn finishCapture(snapshot, queries, { compatible, recovered: true });\n}\n\n/** Read-only capture. No submitted approved-subject list or source reference is accepted.\n * Call only after the stores validate the canonical manifest and its source binding.\n */\nexport async function captureLegacyCompletionOwnerProof(input: {\n\tbackend: Backend;\n\tgroupId: string;\n\tmanifestJson: string;\n\tkeyMetadata: string;\n}): Promise<LegacyCompletionOwnerProof> {\n\ttry {\n\t\tconst requested = await requestedSubjects(input);\n\t\tconst catalog = await readRows(input.backend, catalogSql);\n\t\tconst state = classifyLegacyOwnerResolutionSchemaCatalog(\n\t\t\tcatalog.parsed.map(([type, name, tbl_name, sql]) => ({ type, name, tbl_name, sql })),\n\t\t);\n\t\tconst snapshot: Snapshot = {\n\t\t\t...requested,\n\t\t\tactive: [],\n\t\t\trows: { schema: catalog.encoded },\n\t\t\tapproved: [],\n\t\t};\n\t\tif (state === \"unsupported\")\n\t\t\treturn remember({ ctes: \"\", currentSql: \"0\", compatibleSql: \"0\", values: [] });\n\t\tif (state === \"missing\")\n\t\t\treturn finishCapture(\n\t\t\t\tsnapshot,\n\t\t\t\t{ schema: catalogSql },\n\t\t\t\t{ compatible: true, recovered: false, missing: true },\n\t\t\t);\n\t\treturn await captureReady(input.backend, snapshot);\n\t} catch {\n\t\treturn remember({ ctes: \"\", currentSql: \"0\", compatibleSql: \"0\", values: [] });\n\t}\n}\n\n/** The winning INSERT must use both predicates. A token by itself grants nothing.\n * Keep LEGACY_OWNER_SOURCE_CURRENT_SQL and all ordinary completion checks as well.\n */\nexport function legacyCompletionOwnerProofSql(proof: LegacyCompletionOwnerProof): ProofSql {\n\treturn snapshots.get(proof) ?? { ctes: \"\", currentSql: \"0\", compatibleSql: \"0\", values: [] };\n}\n","import type {\n\tCoordinatorGrantScopeMembershipInput,\n\tCoordinatorRevokeScopeMembershipInput,\n\tCoordinatorScopeMembership,\n} from \"./coordinator-store-contract.js\";\n\nexport const SCOPE_MEMBERSHIP_EFFECT_CONFLICT = \"scope_membership_effect_conflict\";\n\nexport type CoordinatorMembershipErrorCode =\n\t| \"device_not_enrolled\"\n\t| \"scope_group_mismatch\"\n\t| \"scope_inactive\"\n\t| \"scope_not_found\";\n\nconst MEMBERSHIP_ERROR_MESSAGES: Record<CoordinatorMembershipErrorCode, string> = {\n\tdevice_not_enrolled: \"device must be enrolled and enabled in the scope group.\",\n\tscope_group_mismatch: \"membership groupId must match the scope groupId.\",\n\tscope_inactive: \"scope is not active.\",\n\tscope_not_found: \"scopeId must reference an existing scope.\",\n};\n\nexport class CoordinatorMembershipError extends Error {\n\treadonly code: CoordinatorMembershipErrorCode;\n\n\tconstructor(code: CoordinatorMembershipErrorCode) {\n\t\tsuper(MEMBERSHIP_ERROR_MESSAGES[code]);\n\t\tthis.name = \"CoordinatorMembershipError\";\n\t\tthis.code = code;\n\t}\n}\n\nexport interface CoordinatorMembershipEffectReceipt {\n\teffect_id: string;\n\taction: \"grant\" | \"revoke\";\n\trequest_json: string;\n\toutcome_applied: number;\n\tscope_id: string;\n\tdevice_id: string;\n\trole: string | null;\n\tstatus: string | null;\n\tmembership_epoch: number | null;\n\tcoordinator_id: string | null;\n\tgroup_id: string | null;\n\tmanifest_issuer_device_id: string | null;\n\tmanifest_hash: string | null;\n\tsigned_manifest_json: string | null;\n\tupdated_at: string | null;\n\tcreated_at: string;\n}\n\nfunction clean(value: string | null | undefined): string | null {\n\tconst normalized = value?.trim();\n\treturn normalized ? normalized : null;\n}\n\nexport function normalizeMembershipEffectId(value: string): string {\n\tconst effectId = clean(value);\n\tif (!effectId) throw new Error(\"effectId is required.\");\n\tif (effectId.length > 512 || /[\\p{Cc}\\p{Cf}]/u.test(effectId)) {\n\t\tthrow new Error(\"effectId is invalid.\");\n\t}\n\treturn effectId;\n}\n\nexport function grantMembershipEffectRequestJson(\n\topts: CoordinatorGrantScopeMembershipInput,\n): string {\n\treturn JSON.stringify({\n\t\tscopeId: clean(opts.scopeId),\n\t\tdeviceId: clean(opts.deviceId),\n\t\trole: clean(opts.role),\n\t\tmembershipEpoch: opts.membershipEpoch ?? null,\n\t\tcoordinatorId: clean(opts.coordinatorId),\n\t\tgroupId: clean(opts.groupId),\n\t\tmanifestIssuerDeviceId: clean(opts.manifestIssuerDeviceId),\n\t\tmanifestHash: clean(opts.manifestHash),\n\t\tsignedManifestJson: clean(opts.signedManifestJson),\n\t\tactorType: clean(opts.actorType),\n\t\tactorId: clean(opts.actorId),\n\t});\n}\n\nexport function revokeMembershipEffectRequestJson(\n\topts: CoordinatorRevokeScopeMembershipInput,\n): string {\n\treturn JSON.stringify({\n\t\tscopeId: clean(opts.scopeId),\n\t\tdeviceId: clean(opts.deviceId),\n\t\tgroupId: clean(opts.groupId),\n\t\tmembershipEpoch: opts.membershipEpoch ?? null,\n\t\tmanifestHash: clean(opts.manifestHash),\n\t\tsignedManifestJson: clean(opts.signedManifestJson),\n\t\tactorType: clean(opts.actorType),\n\t\tactorId: clean(opts.actorId),\n\t});\n}\n\nexport function assertMatchingMembershipEffectReceipt(\n\treceipt: CoordinatorMembershipEffectReceipt,\n\taction: CoordinatorMembershipEffectReceipt[\"action\"],\n\trequestJson: string,\n): void {\n\tif (receipt.action !== action || receipt.request_json !== requestJson) {\n\t\tthrow new Error(SCOPE_MEMBERSHIP_EFFECT_CONFLICT);\n\t}\n}\n\nexport function membershipFromEffectReceipt(\n\treceipt: CoordinatorMembershipEffectReceipt,\n): CoordinatorScopeMembership {\n\tif (\n\t\treceipt.action !== \"grant\" ||\n\t\treceipt.outcome_applied !== 1 ||\n\t\treceipt.role == null ||\n\t\treceipt.status == null ||\n\t\treceipt.membership_epoch == null ||\n\t\treceipt.updated_at == null\n\t) {\n\t\tthrow new Error(\"scope_membership_effect_receipt_invalid\");\n\t}\n\treturn {\n\t\tscope_id: receipt.scope_id,\n\t\tdevice_id: receipt.device_id,\n\t\trole: receipt.role,\n\t\tstatus: receipt.status,\n\t\tmembership_epoch: receipt.membership_epoch,\n\t\tcoordinator_id: receipt.coordinator_id,\n\t\tgroup_id: receipt.group_id,\n\t\tmanifest_issuer_device_id: receipt.manifest_issuer_device_id,\n\t\tmanifest_hash: receipt.manifest_hash,\n\t\tsigned_manifest_json: receipt.signed_manifest_json,\n\t\tupdated_at: receipt.updated_at,\n\t};\n}\n","/** Inert ceremony storage, not a verified-identity capability or an enrollment writer.\n * Finalized rows are retained prior-commit receipts, never current permission.\n * The winning future UPDATE must write the outcome and purge handoff material together.\n * Fresh installs only: existing tables require explicit migration 0036, never a rebuild on open.\n */\nexport const COORDINATOR_OWNER_ENROLLMENT_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS coordinator_owner_enrollment_attempts (\n coordinator_id TEXT NOT NULL CHECK (typeof(coordinator_id) = 'text' AND length(trim(coordinator_id)) BETWEEN 1 AND 256 AND instr(coordinator_id, char(0)) = 0),\n attempt_id TEXT NOT NULL CHECK (typeof(attempt_id) = 'text' AND length(trim(attempt_id)) BETWEEN 1 AND 256 AND instr(attempt_id, char(0)) = 0),\n purpose TEXT NOT NULL CHECK (purpose = 'owner_enroll'),\n origin TEXT NOT NULL CHECK (typeof(origin) = 'text' AND length(trim(origin)) > 0 AND instr(origin, char(0)) = 0),\n device_id TEXT NOT NULL CHECK (typeof(device_id) = 'text' AND length(trim(device_id)) BETWEEN 1 AND 256 AND instr(device_id, char(0)) = 0),\n public_key TEXT NOT NULL CHECK (typeof(public_key) = 'text' AND length(trim(public_key)) > 0 AND instr(public_key, char(0)) = 0),\n key_id TEXT NOT NULL CHECK (typeof(key_id) = 'text' AND length(key_id) = 64 AND key_id NOT GLOB '*[^0-9a-f]*' AND instr(key_id, char(0)) = 0),\n fingerprint TEXT NOT NULL CHECK (typeof(fingerprint) = 'text' AND length(fingerprint) = 64 AND fingerprint NOT GLOB '*[^0-9a-f]*' AND instr(fingerprint, char(0)) = 0),\n issuer TEXT NOT NULL CHECK (typeof(issuer) = 'text' AND length(trim(issuer)) > 0 AND instr(issuer, char(0)) = 0),\n auth_config_revision TEXT NOT NULL CHECK (typeof(auth_config_revision) = 'text' AND length(auth_config_revision) = 64 AND auth_config_revision NOT GLOB '*[^0-9a-f]*' AND instr(auth_config_revision, char(0)) = 0),\n loopback_redirect TEXT CHECK (loopback_redirect IS NULL OR (typeof(loopback_redirect) = 'text' AND length(trim(loopback_redirect)) > 0 AND instr(loopback_redirect, char(0)) = 0)),\n browser_start_hash TEXT NOT NULL CHECK (typeof(browser_start_hash) = 'text' AND length(browser_start_hash) = 64 AND browser_start_hash NOT GLOB '*[^0-9a-f]*' AND instr(browser_start_hash, char(0)) = 0),\n browser_transaction_hash TEXT CHECK (browser_transaction_hash IS NULL OR (typeof(browser_transaction_hash) = 'text' AND length(browser_transaction_hash) = 64 AND browser_transaction_hash NOT GLOB '*[^0-9a-f]*' AND instr(browser_transaction_hash, char(0)) = 0)),\n browser_binder_hash TEXT CHECK (browser_binder_hash IS NULL OR (typeof(browser_binder_hash) = 'text' AND length(browser_binder_hash) = 64 AND browser_binder_hash NOT GLOB '*[^0-9a-f]*' AND instr(browser_binder_hash, char(0)) = 0)),\n account_subject TEXT CHECK (account_subject IS NULL OR (typeof(account_subject) = 'text' AND length(account_subject) BETWEEN 1 AND 255 AND instr(account_subject, char(0)) = 0)),\n identity_id TEXT CHECK (identity_id IS NULL OR (typeof(identity_id) = 'text' AND length(trim(identity_id)) BETWEEN 1 AND 256 AND instr(identity_id, char(0)) = 0)),\n link_id TEXT CHECK (link_id IS NULL OR (typeof(link_id) = 'text' AND length(trim(link_id)) BETWEEN 1 AND 256 AND instr(link_id, char(0)) = 0)),\n link_attempt_id TEXT CHECK (link_attempt_id IS NULL OR (typeof(link_attempt_id) = 'text' AND length(trim(link_attempt_id)) BETWEEN 1 AND 256 AND instr(link_attempt_id, char(0)) = 0)),\n link_controller_attestation_id TEXT CHECK (link_controller_attestation_id IS NULL OR (typeof(link_controller_attestation_id) = 'text' AND length(trim(link_controller_attestation_id)) BETWEEN 1 AND 256 AND instr(link_controller_attestation_id, char(0)) = 0)),\n link_auth_config_revision TEXT CHECK (link_auth_config_revision IS NULL OR (typeof(link_auth_config_revision) = 'text' AND length(link_auth_config_revision) = 64 AND link_auth_config_revision NOT GLOB '*[^0-9a-f]*' AND instr(link_auth_config_revision, char(0)) = 0)),\n grant_revisions_json TEXT CHECK (grant_revisions_json IS NULL OR (typeof(grant_revisions_json) = 'text' AND json_valid(grant_revisions_json) AND json_type(grant_revisions_json) = 'array')),\n confirmation_hash TEXT CHECK (confirmation_hash IS NULL OR (typeof(confirmation_hash) = 'text' AND length(confirmation_hash) = 64 AND confirmation_hash NOT GLOB '*[^0-9a-f]*' AND instr(confirmation_hash, char(0)) = 0)),\n completion_secret_hash TEXT CHECK (completion_secret_hash IS NULL OR (typeof(completion_secret_hash) = 'text' AND length(completion_secret_hash) = 64 AND completion_secret_hash NOT GLOB '*[^0-9a-f]*' AND instr(completion_secret_hash, char(0)) = 0)),\n final_key_proof_hash TEXT CHECK (final_key_proof_hash IS NULL OR (typeof(final_key_proof_hash) = 'text' AND length(final_key_proof_hash) = 64 AND final_key_proof_hash NOT GLOB '*[^0-9a-f]*' AND instr(final_key_proof_hash, char(0)) = 0)),\n state TEXT NOT NULL CHECK (state IN ('pending','browser_claimed','oidc_verified','confirmed','finalized','expired','failed','retired')),\n created_at_ms INTEGER NOT NULL CHECK (typeof(created_at_ms) = 'integer' AND created_at_ms BETWEEN 0 AND 9007199254140991),\n expires_at_ms INTEGER NOT NULL CHECK (typeof(expires_at_ms) = 'integer' AND expires_at_ms = created_at_ms + 600000),\n finalized_at_ms INTEGER CHECK (finalized_at_ms IS NULL OR (typeof(finalized_at_ms) = 'integer' AND finalized_at_ms >= created_at_ms AND finalized_at_ms < expires_at_ms)),\n binding_id TEXT CHECK (binding_id IS NULL OR (typeof(binding_id) = 'text' AND length(trim(binding_id)) BETWEEN 1 AND 256 AND instr(binding_id, char(0)) = 0)),\n audit_event_id TEXT CHECK (audit_event_id IS NULL OR (typeof(audit_event_id) = 'text' AND length(trim(audit_event_id)) BETWEEN 1 AND 256 AND instr(audit_event_id, char(0)) = 0)),\n final_outcome_json TEXT CHECK (final_outcome_json IS NULL OR (typeof(final_outcome_json) = 'text' AND json_valid(final_outcome_json) AND json_type(final_outcome_json) = 'object')),\n admission_owner_hash TEXT CHECK (admission_owner_hash IS NULL OR (typeof(admission_owner_hash) = 'text' AND length(admission_owner_hash) = 64 AND admission_owner_hash NOT GLOB '*[^0-9a-f]*' AND instr(admission_owner_hash, char(0)) = 0)),\n owner_qualification_id TEXT CHECK (owner_qualification_id IS NULL OR (typeof(owner_qualification_id) = 'text' AND length(owner_qualification_id) BETWEEN 1 AND 256 AND owner_qualification_id = trim(owner_qualification_id) AND length(trim(owner_qualification_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(owner_qualification_id, char(0)) = 0)),\n PRIMARY KEY (coordinator_id, attempt_id),\n UNIQUE (coordinator_id, browser_start_hash),\n UNIQUE (coordinator_id, browser_transaction_hash),\n UNIQUE (coordinator_id, completion_secret_hash),\n CHECK (state NOT IN ('pending','browser_claimed','oidc_verified','confirmed') OR loopback_redirect IS NOT NULL),\n CHECK (state <> 'pending' OR browser_transaction_hash IS NULL),\n CHECK ((browser_transaction_hash IS NULL) = (browser_binder_hash IS NULL)),\n CHECK (state NOT IN ('pending','browser_claimed') OR account_subject IS NULL),\n CHECK (state NOT IN ('pending','browser_claimed','oidc_verified') OR (confirmation_hash IS NULL AND completion_secret_hash IS NULL)),\n CHECK (state NOT IN ('browser_claimed','oidc_verified','confirmed','finalized') OR browser_transaction_hash IS NOT NULL),\n CHECK ((account_subject IS NULL AND identity_id IS NULL AND link_id IS NULL AND link_attempt_id IS NULL AND link_controller_attestation_id IS NULL AND owner_qualification_id IS NULL AND link_auth_config_revision IS NULL AND grant_revisions_json IS NULL) OR (account_subject IS NOT NULL AND identity_id IS NOT NULL AND link_id IS NOT NULL AND link_attempt_id IS NOT NULL AND ((link_controller_attestation_id IS NOT NULL AND owner_qualification_id IS NULL) OR (link_controller_attestation_id IS NULL AND owner_qualification_id IS NOT NULL)) AND link_auth_config_revision IS NOT NULL AND grant_revisions_json IS NOT NULL)),\n CHECK (state NOT IN ('oidc_verified','confirmed','finalized') OR account_subject IS NOT NULL),\n CHECK (state NOT IN ('confirmed','finalized') OR (confirmation_hash IS NOT NULL AND completion_secret_hash IS NOT NULL)),\n CHECK ((state = 'finalized' AND finalized_at_ms IS NOT NULL AND binding_id IS NOT NULL AND audit_event_id IS NOT NULL AND final_outcome_json IS NOT NULL AND final_key_proof_hash IS NOT NULL AND loopback_redirect IS NULL) OR (state <> 'finalized' AND finalized_at_ms IS NULL AND binding_id IS NULL AND audit_event_id IS NULL AND final_outcome_json IS NULL AND final_key_proof_hash IS NULL))\n);\nCREATE INDEX IF NOT EXISTS idx_owner_enrollment_device_created\n ON coordinator_owner_enrollment_attempts(coordinator_id, device_id, created_at_ms);\nCREATE INDEX IF NOT EXISTS idx_owner_enrollment_identity_expiry\n ON coordinator_owner_enrollment_attempts(coordinator_id, identity_id, expires_at_ms);\nCREATE INDEX IF NOT EXISTS idx_owner_enrollment_state_expiry\n ON coordinator_owner_enrollment_attempts(coordinator_id, state, expires_at_ms);\n-- Birth facts and recorded commitments survive retries and transient browser cleanup.\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_pins_update\nBEFORE UPDATE ON coordinator_owner_enrollment_attempts WHEN OLD.state <> 'finalized' AND (\n OLD.coordinator_id IS NOT NEW.coordinator_id OR OLD.attempt_id IS NOT NEW.attempt_id\n OR OLD.purpose IS NOT NEW.purpose OR OLD.origin IS NOT NEW.origin\n OR OLD.device_id IS NOT NEW.device_id OR OLD.public_key IS NOT NEW.public_key\n OR OLD.key_id IS NOT NEW.key_id OR OLD.fingerprint IS NOT NEW.fingerprint\n OR OLD.issuer IS NOT NEW.issuer OR OLD.auth_config_revision IS NOT NEW.auth_config_revision\n OR OLD.browser_start_hash IS NOT NEW.browser_start_hash\n OR OLD.created_at_ms IS NOT NEW.created_at_ms OR OLD.expires_at_ms IS NOT NEW.expires_at_ms\n OR (OLD.loopback_redirect IS NOT NEW.loopback_redirect AND NOT (\n OLD.loopback_redirect IS NOT NULL AND NEW.loopback_redirect IS NULL\n AND NEW.state IN ('finalized','expired','failed','retired')))\n OR (OLD.browser_transaction_hash IS NOT NULL AND OLD.browser_transaction_hash IS NOT NEW.browser_transaction_hash)\n OR (OLD.browser_binder_hash IS NOT NULL AND OLD.browser_binder_hash IS NOT NEW.browser_binder_hash)\n OR (OLD.account_subject IS NOT NULL AND OLD.account_subject IS NOT NEW.account_subject)\n OR (OLD.identity_id IS NOT NULL AND OLD.identity_id IS NOT NEW.identity_id)\n OR (OLD.link_id IS NOT NULL AND OLD.link_id IS NOT NEW.link_id)\n OR (OLD.link_attempt_id IS NOT NULL AND OLD.link_attempt_id IS NOT NEW.link_attempt_id)\n OR (OLD.link_controller_attestation_id IS NOT NULL AND OLD.link_controller_attestation_id IS NOT NEW.link_controller_attestation_id)\n OR (OLD.link_auth_config_revision IS NOT NULL AND OLD.link_auth_config_revision IS NOT NEW.link_auth_config_revision)\n OR (OLD.grant_revisions_json IS NOT NULL AND OLD.grant_revisions_json IS NOT NEW.grant_revisions_json)\n OR (OLD.confirmation_hash IS NOT NULL AND OLD.confirmation_hash IS NOT NEW.confirmation_hash)\n OR (OLD.completion_secret_hash IS NOT NULL AND OLD.completion_secret_hash IS NOT NEW.completion_secret_hash)\n OR (OLD.browser_transaction_hash IS NULL AND NEW.browser_transaction_hash IS NOT NULL\n AND NOT (OLD.state = 'pending' AND NEW.state = 'browser_claimed'))\n OR (OLD.account_subject IS NULL AND NEW.account_subject IS NOT NULL\n AND NOT (OLD.state = 'browser_claimed' AND NEW.state = 'oidc_verified'))\n OR ((OLD.confirmation_hash IS NULL AND NEW.confirmation_hash IS NOT NULL\n OR OLD.completion_secret_hash IS NULL AND NEW.completion_secret_hash IS NOT NULL)\n AND NOT (OLD.state = 'oidc_verified' AND NEW.state = 'confirmed'))\n OR (OLD.state IN ('expired','failed','retired') AND OLD.state IS NOT NEW.state)\n OR (EXISTS (SELECT 1 FROM coordinator_owner_enrollment_attempts a WHERE a.state <> 'finalized'\n AND a.rowid <> OLD.rowid AND (a.rowid = NEW.rowid OR (a.coordinator_id = NEW.coordinator_id\n AND (a.attempt_id = NEW.attempt_id OR a.browser_start_hash = NEW.browser_start_hash\n OR a.browser_transaction_hash = NEW.browser_transaction_hash OR a.completion_secret_hash = NEW.completion_secret_hash))))\n AND NOT EXISTS (SELECT 1 FROM coordinator_owner_enrollment_attempts a WHERE a.state = 'finalized'\n AND a.rowid <> OLD.rowid AND (a.rowid = NEW.rowid OR (a.coordinator_id = NEW.coordinator_id\n AND (a.attempt_id = NEW.attempt_id OR a.browser_start_hash = NEW.browser_start_hash\n OR a.browser_transaction_hash = NEW.browser_transaction_hash OR a.completion_secret_hash = NEW.completion_secret_hash)))))\n)\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_pins_immutable'); END;\n-- REPLACE can delete a conflicting row without running UPDATE or DELETE triggers.\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_pins_insert\nBEFORE INSERT ON coordinator_owner_enrollment_attempts\nWHEN EXISTS (SELECT 1 FROM coordinator_owner_enrollment_attempts a WHERE a.state <> 'finalized'\n AND (a.rowid = NEW.rowid OR (a.coordinator_id = NEW.coordinator_id AND (a.attempt_id = NEW.attempt_id\n OR a.browser_start_hash = NEW.browser_start_hash OR a.browser_transaction_hash = NEW.browser_transaction_hash\n OR a.completion_secret_hash = NEW.completion_secret_hash)))\n AND (a.coordinator_id,a.attempt_id,a.purpose,a.origin,a.device_id,a.public_key,a.key_id,a.fingerprint,\n a.issuer,a.auth_config_revision,a.loopback_redirect,a.browser_start_hash,a.browser_transaction_hash,a.browser_binder_hash,\n a.account_subject,a.identity_id,a.link_id,a.link_attempt_id,a.link_controller_attestation_id,a.link_auth_config_revision,\n a.grant_revisions_json,a.confirmation_hash,a.completion_secret_hash,a.final_key_proof_hash,a.state,\n a.created_at_ms,a.expires_at_ms,a.finalized_at_ms,a.binding_id,a.audit_event_id,a.final_outcome_json)\n IS NOT (NEW.coordinator_id,NEW.attempt_id,NEW.purpose,NEW.origin,NEW.device_id,NEW.public_key,NEW.key_id,NEW.fingerprint,\n NEW.issuer,NEW.auth_config_revision,NEW.loopback_redirect,NEW.browser_start_hash,NEW.browser_transaction_hash,NEW.browser_binder_hash,\n NEW.account_subject,NEW.identity_id,NEW.link_id,NEW.link_attempt_id,NEW.link_controller_attestation_id,NEW.link_auth_config_revision,\n NEW.grant_revisions_json,NEW.confirmation_hash,NEW.completion_secret_hash,NEW.final_key_proof_hash,NEW.state,\n NEW.created_at_ms,NEW.expires_at_ms,NEW.finalized_at_ms,NEW.binding_id,NEW.audit_event_id,NEW.final_outcome_json))\n AND NOT EXISTS (SELECT 1 FROM coordinator_owner_enrollment_attempts a WHERE a.state = 'finalized'\n AND (a.rowid = NEW.rowid OR (a.coordinator_id = NEW.coordinator_id AND (a.attempt_id = NEW.attempt_id\n OR a.browser_start_hash = NEW.browser_start_hash OR a.browser_transaction_hash = NEW.browser_transaction_hash\n OR a.completion_secret_hash = NEW.completion_secret_hash))))\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_pins_immutable'); END;\n-- Admission is a birth fact, including NULL for preexisting/operator attempts.\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_admission_update\nBEFORE UPDATE ON coordinator_owner_enrollment_attempts\nWHEN OLD.admission_owner_hash IS NOT NEW.admission_owner_hash\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_admission_immutable'); END;\n-- Probe each unique key separately; a coordinator-only OR plan scans every prior attempt.\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_admission_insert\nBEFORE INSERT ON coordinator_owner_enrollment_attempts\nWHEN EXISTS (SELECT 1 FROM coordinator_owner_enrollment_attempts a\n WHERE a.rowid IN (\n SELECT rowid FROM coordinator_owner_enrollment_attempts WHERE rowid = NEW.rowid\n UNION ALL SELECT rowid FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = NEW.coordinator_id AND attempt_id = NEW.attempt_id\n UNION ALL SELECT rowid FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = NEW.coordinator_id AND browser_start_hash = NEW.browser_start_hash\n UNION ALL SELECT rowid FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = NEW.coordinator_id AND browser_transaction_hash = NEW.browser_transaction_hash\n UNION ALL SELECT rowid FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = NEW.coordinator_id AND completion_secret_hash = NEW.completion_secret_hash)\n AND a.admission_owner_hash IS NOT NEW.admission_owner_hash)\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_admission_immutable'); END;\n-- The authority branch, including its NULL pin, is fixed at first owner resolution.\n-- A device-claim qualification never becomes the original link's controller attestation.\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_authority_update\nBEFORE UPDATE ON coordinator_owner_enrollment_attempts\nWHEN (OLD.account_subject IS NOT NULL AND (\n OLD.owner_qualification_id IS NOT NEW.owner_qualification_id\n OR OLD.link_controller_attestation_id IS NOT NEW.link_controller_attestation_id))\n OR (OLD.owner_qualification_id IS NOT NEW.owner_qualification_id AND NOT (\n OLD.account_subject IS NULL AND NEW.account_subject IS NOT NULL\n AND OLD.state = 'browser_claimed' AND NEW.state = 'oidc_verified'))\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_pins_immutable'); END;\n-- REPLACE and UPSERT must not switch authority through any unique-key collision.\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_authority_insert\nBEFORE INSERT ON coordinator_owner_enrollment_attempts\nWHEN EXISTS (SELECT 1 FROM coordinator_owner_enrollment_attempts a\n WHERE a.rowid IN (\n SELECT rowid FROM coordinator_owner_enrollment_attempts WHERE rowid = NEW.rowid\n UNION ALL SELECT rowid FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = NEW.coordinator_id AND attempt_id = NEW.attempt_id\n UNION ALL SELECT rowid FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = NEW.coordinator_id AND browser_start_hash = NEW.browser_start_hash\n UNION ALL SELECT rowid FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = NEW.coordinator_id AND browser_transaction_hash = NEW.browser_transaction_hash\n UNION ALL SELECT rowid FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = NEW.coordinator_id AND completion_secret_hash = NEW.completion_secret_hash)\n AND (a.owner_qualification_id IS NOT NEW.owner_qualification_id\n OR a.link_controller_attestation_id IS NOT NEW.link_controller_attestation_id))\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_pins_immutable'); END;\n-- Retained receipts cannot be changed, deleted, or erased through REPLACE.\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_finalized_update\nBEFORE UPDATE ON coordinator_owner_enrollment_attempts WHEN OLD.state = 'finalized'\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_receipt_immutable'); END;\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_finalized_update_collision\nBEFORE UPDATE ON coordinator_owner_enrollment_attempts\nWHEN EXISTS (SELECT 1 FROM coordinator_owner_enrollment_attempts a WHERE a.state = 'finalized'\n AND a.rowid <> OLD.rowid AND (a.rowid = NEW.rowid OR (a.coordinator_id = NEW.coordinator_id\n AND (a.attempt_id = NEW.attempt_id OR a.browser_start_hash = NEW.browser_start_hash\n OR a.browser_transaction_hash = NEW.browser_transaction_hash OR a.completion_secret_hash = NEW.completion_secret_hash))))\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_receipt_immutable'); END;\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_finalized_delete\nBEFORE DELETE ON coordinator_owner_enrollment_attempts WHEN OLD.state = 'finalized'\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_receipt_immutable'); END;\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_finalized_replace\nBEFORE INSERT ON coordinator_owner_enrollment_attempts\nWHEN EXISTS (SELECT 1 FROM coordinator_owner_enrollment_attempts a WHERE a.state = 'finalized'\n AND (a.rowid = NEW.rowid OR (a.coordinator_id = NEW.coordinator_id AND (a.attempt_id = NEW.attempt_id\n OR a.browser_start_hash = NEW.browser_start_hash OR a.browser_transaction_hash = NEW.browser_transaction_hash\n OR a.completion_secret_hash = NEW.completion_secret_hash))))\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_receipt_immutable'); END;\n`;\n","import type { ControllerHistorySnapshot } from \"./coordinator-auth-controller-history.js\";\nimport {\n\ttype EvidenceRow,\n\ttype EvidenceRows,\n\ttype EvidenceSubject,\n\tevidenceRows,\n\tkeyId,\n} from \"./coordinator-device-ownership-evidence-classify.js\";\n\nfunction canonicalRows(rows: EvidenceRow[]): string[] {\n\treturn rows.map((row) => JSON.stringify(row)).sort();\n}\n\nasync function actualSubjectRows(\n\trows: EvidenceRow[],\n\tsubject: EvidenceSubject,\n\tcolumns: { device: number; publicKey: number },\n): Promise<EvidenceRow[]> {\n\tconst relevant: EvidenceRow[] = [];\n\tfor (const row of rows) {\n\t\tif (\n\t\t\trow[columns.device] === subject.deviceId ||\n\t\t\t(await keyId(row[columns.publicKey])) === subject.keyId\n\t\t)\n\t\t\trelevant.push(row);\n\t}\n\treturn relevant;\n}\n\n/** Hash only validated semantic evidence, not conservative SQL discovery inputs.\n * Row positions follow the fixed source column lists; sorting uses code units,\n * never locale rules. Exact source key text remains part of relevant evidence.\n */\nexport async function capturedOwnershipEvidenceDigest(\n\trows: EvidenceRows,\n\tsubject: EvidenceSubject,\n\tcanonicalOwnerId: string,\n\thistory: ControllerHistorySnapshot,\n): Promise<string> {\n\tconst controllers = await actualSubjectRows(evidenceRows(rows, \"controllers\"), subject, {\n\t\tdevice: 4,\n\t\tpublicKey: 5,\n\t});\n\tconst invites = await actualSubjectRows(evidenceRows(rows, \"invites\"), subject, {\n\t\tdevice: 7,\n\t\tpublicKey: 8,\n\t});\n\tconst projection = [\n\t\t\"codemem:reviewed-device-ownership-evidence:v1\",\n\t\t[\"legacy-owner-resolution-schema\", 1, \"ready\"],\n\t\t[\n\t\t\tsubject.coordinatorId,\n\t\t\tsubject.groupId,\n\t\t\tsubject.deviceId,\n\t\t\tsubject.publicKey,\n\t\t\tsubject.fingerprint,\n\t\t\tsubject.keyId,\n\t\t],\n\t\tcanonicalOwnerId,\n\t\t[\n\t\t\t\"enrollment\",\n\t\t\t\"bindings\",\n\t\t\t\"claims\",\n\t\t\t\"resolutions\",\n\t\t\t\"revocations\",\n\t\t\t\"history\",\n\t\t\t\"historyKeys\",\n\t\t].map((name) => [name, canonicalRows(evidenceRows(rows, name))]),\n\t\t[\"controllers\", canonicalRows(controllers)],\n\t\t[\"invites\", canonicalRows(invites)],\n\t\t[\"subjectFingerprints\", [...history.fingerprints].sort()],\n\t];\n\tconst digest = await globalThis.crypto.subtle.digest(\n\t\t\"SHA-256\",\n\t\tnew TextEncoder().encode(JSON.stringify(projection)),\n\t);\n\treturn Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n","import {\n\ttype ControllerHistorySnapshot,\n\tcaptureControllerHistory,\n\tcaptureControllerHistorySnapshot,\n\tcontrollerHistoryDiscoveryFragments,\n} from \"./coordinator-auth-controller-history.js\";\nimport type { AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport {\n\tclassifyEvidence,\n\ttype EvidenceRow,\n\ttype EvidenceRows,\n\ttype EvidenceSubject,\n\tevidenceRows,\n\thash,\n\tidentifier,\n\tkeyId,\n\ttype OwnershipDecision,\n} from \"./coordinator-device-ownership-evidence-classify.js\";\nimport { capturedOwnershipEvidenceDigest } from \"./coordinator-device-ownership-evidence-digest.js\";\nimport {\n\tatomicEvidenceQuery,\n\tBYTE_LIMIT,\n\ttype CapturedEvidenceRow,\n\tCONTROLLER_COLUMNS,\n\tEVIDENCE_QUERIES,\n\tROW_LIMIT,\n\treadCombinedEvidenceQuery,\n} from \"./coordinator-device-ownership-evidence-queries.js\";\nimport {\n\tcaptureLegacyOwnerResolutionRecord,\n\tclassifyLegacyOwnerResolutionSchemaCatalog,\n\ttype ReviewedWeakLabel,\n\treadLegacyOwnerResolutionSchemaState,\n} from \"./coordinator-legacy-owner-resolution-metadata.js\";\n\ninterface EvidenceBackend {\n\tfirst<T>(statement: AuthLinkStatement): Promise<T | null>;\n\tall<T>(statement: AuthLinkStatement): Promise<T[]>;\n}\ninterface ActualSigner {\n\tgroupId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n}\ninterface CollectionInput {\n\tcanonicalOwnerId: string;\n\tactualSigner: ActualSigner;\n\tverifiedHistory: ControllerHistorySnapshot;\n}\ninterface RecheckSnapshot {\n\treadonly version: 1;\n}\ntype OwnershipCollection =\n\t| {\n\t\t\tkind: \"collected\";\n\t\t\tdecision: OwnershipDecision;\n\t\t\tweakLabels: ReviewedWeakLabel[];\n\t\t\trecheckSnapshot: RecheckSnapshot;\n\t }\n\t| { kind: \"unavailable\"; authorizationUnavailable: true };\ntype SourceVerification =\n\t| { kind: \"verified_controller_source\" | \"source_missing\" | \"source_revoked\" | \"source_mismatch\" }\n\t| { kind: \"unavailable\"; authorizationUnavailable: true };\nconst unavailable = { kind: \"unavailable\", authorizationUnavailable: true } as const;\n\nfunction captureFields(value: unknown, fields: string[]): Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error(\"invalid_input\");\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (prototype !== Object.prototype && prototype !== null) throw new Error(\"invalid_input\");\n\tif (Reflect.ownKeys(value).length !== fields.length) throw new Error(\"invalid_input\");\n\tconst copy: Record<string, unknown> = {};\n\tfor (const field of fields) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, field);\n\t\tif (!descriptor || !(\"value\" in descriptor)) throw new Error(\"invalid_input\");\n\t\tcopy[field] = descriptor.value;\n\t}\n\treturn copy;\n}\n\nasync function captureSigner(value: unknown, coordinatorId: string): Promise<EvidenceSubject> {\n\tconst signer = captureFields(value, [\"groupId\", \"deviceId\", \"publicKey\", \"fingerprint\"]);\n\tif (!identifier(signer.groupId) || !identifier(signer.deviceId) || !hash(signer.fingerprint))\n\t\tthrow new Error(\"invalid_signer\");\n\tconst canonicalKey = await keyId(signer.publicKey);\n\treturn {\n\t\tcoordinatorId,\n\t\tgroupId: signer.groupId,\n\t\tdeviceId: signer.deviceId,\n\t\tpublicKey: String(signer.publicKey),\n\t\tfingerprint: signer.fingerprint,\n\t\tkeyId: canonicalKey,\n\t};\n}\n\nfunction parseRows(rows: { row: string | null }[]): { encoded: string[]; parsed: EvidenceRow[] } {\n\tif (rows.length > ROW_LIMIT) throw new Error(\"evidence_too_large\");\n\tconst encoded: string[] = [];\n\tlet bytes = 0;\n\tconst parsed = rows.map(({ row }) => {\n\t\tif (typeof row !== \"string\") throw new Error(\"invalid_evidence\");\n\t\tbytes += new TextEncoder().encode(row).byteLength;\n\t\tif (bytes > BYTE_LIMIT) throw new Error(\"evidence_too_large\");\n\t\tconst value: unknown = JSON.parse(row);\n\t\tif (\n\t\t\t!Array.isArray(value) ||\n\t\t\tvalue.some((item) => item !== null && typeof item !== \"string\" && typeof item !== \"number\")\n\t\t)\n\t\t\tthrow new Error(\"invalid_evidence\");\n\t\tencoded.push(row);\n\t\treturn value as EvidenceRow;\n\t});\n\treturn { encoded, parsed };\n}\n\nfunction requireCapturedCategory(category: CapturedEvidenceRow[]): CapturedEvidenceRow[] {\n\tconst count = category[0]?.row_count;\n\tif (typeof count !== \"number\" || !Number.isInteger(count) || count < 0 || count > ROW_LIMIT)\n\t\tthrow new Error(\"invalid_evidence\");\n\tif (category.length !== Math.max(1, count)) throw new Error(\"invalid_evidence\");\n\tif (category.some((row) => row.row_count !== count)) throw new Error(\"invalid_evidence\");\n\tif (count !== 0) return category;\n\tif (category[0]?.row !== null) throw new Error(\"invalid_evidence\");\n\treturn [];\n}\n\nfunction groupCapturedRows(captured: CapturedEvidenceRow[]): Map<string, CapturedEvidenceRow[]> {\n\tif (captured.length > EVIDENCE_QUERIES.length * (ROW_LIMIT + 1))\n\t\tthrow new Error(\"evidence_too_large\");\n\tconst categories = new Map<string, CapturedEvidenceRow[]>(\n\t\tEVIDENCE_QUERIES.map(({ name }) => [name, []]),\n\t);\n\tfor (const value of captured) {\n\t\tconst row = captureFields(value, [\"category\", \"row_count\", \"row\"]);\n\t\tif (typeof row.category !== \"string\") throw new Error(\"invalid_evidence\");\n\t\tconst category = categories.get(row.category);\n\t\tif (!category) throw new Error(\"invalid_evidence\");\n\t\tcategory.push(value);\n\t}\n\tfor (const [name, category] of categories)\n\t\tcategories.set(name, requireCapturedCategory(category));\n\treturn categories;\n}\n\nfunction historyRows(history: ControllerHistorySnapshot): EvidenceRows {\n\treturn {\n\t\thistory: history.records.map((row) => [\n\t\t\trow.group_id,\n\t\t\trow.candidate_ref,\n\t\t\trow.manifest_version,\n\t\t\trow.completed_at,\n\t\t\trow.created_at,\n\t\t\trow.manifest_json,\n\t\t]),\n\t\thistoryKeys: history.keys.map((row) => [row.public_key, row.fingerprint]),\n\t\thistoryDiscovery: history.discoveryKeys.map((publicKey) => [publicKey]),\n\t};\n}\n\nfunction requireSameHistory(rows: EvidenceRows, history: ControllerHistorySnapshot): void {\n\tconst expected = historyRows(history);\n\tfor (const [name, values] of Object.entries(expected)) {\n\t\tif (\n\t\t\tJSON.stringify(values.map((row) => JSON.stringify(row)).sort()) !==\n\t\t\tJSON.stringify(\n\t\t\t\tevidenceRows(rows, name)\n\t\t\t\t\t.map((row) => JSON.stringify(row))\n\t\t\t\t\t.sort(),\n\t\t\t)\n\t\t)\n\t\t\tthrow new Error(\"changed_history\");\n\t}\n}\n\nfunction requireSupportedCapturedSchema(rows: EvidenceRows): void {\n\tconst objects = evidenceRows(rows, \"schema\").map((row) => {\n\t\tif (\n\t\t\trow.length !== 4 ||\n\t\t\ttypeof row[0] !== \"string\" ||\n\t\t\ttypeof row[1] !== \"string\" ||\n\t\t\trow[2] !== \"coordinator_legacy_owner_resolutions\" ||\n\t\t\ttypeof row[3] !== \"string\"\n\t\t)\n\t\t\tthrow new Error(\"invalid_schema_evidence\");\n\t\treturn { type: row[0], sql: row[3] };\n\t});\n\tif (classifyLegacyOwnerResolutionSchemaCatalog(objects) !== \"ready\")\n\t\tthrow new Error(\"unsupported_schema_evidence\");\n}\n\n/** Internal read-only metadata collector. No result of this class grants access. */\nexport class CoordinatorDeviceOwnershipEvidence {\n\tprivate readonly snapshots = new WeakMap<object, { encoded: string; digest: string }>();\n\tprivate readonly coordinatorId: string;\n\tconstructor(\n\t\tprivate readonly backend: EvidenceBackend,\n\t\tconfig: { coordinatorId: string },\n\t) {\n\t\tthis.coordinatorId = config.coordinatorId;\n\t}\n\n\tasync collect(input: CollectionInput): Promise<OwnershipCollection> {\n\t\ttry {\n\t\t\tif (!identifier(this.coordinatorId)) return unavailable;\n\t\t\tconst captured = captureFields(input, [\n\t\t\t\t\"canonicalOwnerId\",\n\t\t\t\t\"actualSigner\",\n\t\t\t\t\"verifiedHistory\",\n\t\t\t]);\n\t\t\tif (!identifier(captured.canonicalOwnerId)) return unavailable;\n\t\t\tconst subject = await captureSigner(captured.actualSigner, this.coordinatorId);\n\t\t\tconst history = await this.verifyHistory(captured.verifiedHistory, subject);\n\t\t\tif ((await readLegacyOwnerResolutionSchemaState(this.backend)) !== \"ready\")\n\t\t\t\treturn unavailable;\n\t\t\tconst { rows, encoded } = await this.captureRows(subject, history);\n\t\t\trequireSupportedCapturedSchema(rows);\n\t\t\trequireSameHistory(rows, history);\n\t\t\tconst classification = await classifyEvidence(\n\t\t\t\trows,\n\t\t\t\tsubject,\n\t\t\t\tcaptured.canonicalOwnerId,\n\t\t\t\thistory,\n\t\t\t);\n\t\t\tconst matches = await this.backend.first<{ matches: number }>(atomicEvidenceQuery(encoded));\n\t\t\tif (matches?.matches !== 1) return unavailable;\n\t\t\tconst digest = await capturedOwnershipEvidenceDigest(\n\t\t\t\trows,\n\t\t\t\tsubject,\n\t\t\t\tcaptured.canonicalOwnerId,\n\t\t\t\thistory,\n\t\t\t);\n\t\t\tconst recheckSnapshot = Object.freeze({ version: 1 as const });\n\t\t\tthis.snapshots.set(recheckSnapshot, { encoded, digest });\n\t\t\treturn { kind: \"collected\", ...classification, recheckSnapshot };\n\t\t} catch {\n\t\t\treturn unavailable;\n\t\t}\n\t}\n\n\tprivate async verifyHistory(\n\t\tvalue: unknown,\n\t\tsubject: EvidenceSubject,\n\t): Promise<ControllerHistorySnapshot> {\n\t\tconst captured = captureControllerHistorySnapshot(value);\n\t\tif (!captured) throw new Error(\"invalid_history\");\n\t\tconst live = await captureControllerHistory(\n\t\t\t{\n\t\t\t\tcoordinatorId: subject.coordinatorId,\n\t\t\t\tdeviceId: subject.deviceId,\n\t\t\t\tpublicKey: subject.publicKey,\n\t\t\t\tfingerprint: subject.fingerprint,\n\t\t\t},\n\t\t\t<T>(sql: string, values: string[]) => this.backend.all<T>({ sql, values }),\n\t\t);\n\t\tif (\n\t\t\tlive.coordinatorId !== captured.coordinatorId ||\n\t\t\tlive.deviceId !== captured.deviceId ||\n\t\t\tlive.publicKey !== captured.publicKey ||\n\t\t\tlive.fingerprint !== captured.fingerprint\n\t\t)\n\t\t\tthrow new Error(\"changed_history\");\n\t\trequireSameHistory(historyRows(live), captured);\n\t\treturn live;\n\t}\n\n\tprivate async captureRows(\n\t\tsubject: EvidenceSubject,\n\t\tlegacyHistory: ControllerHistorySnapshot,\n\t): Promise<{ rows: EvidenceRows; encoded: string }> {\n\t\tconst base = {\n\t\t\tsubject: { ...subject, fragments: controllerHistoryDiscoveryFragments(subject.publicKey) },\n\t\t\tlegacyHistory,\n\t\t};\n\t\tconst parameters = JSON.stringify(base);\n\t\tconst categories = groupCapturedRows(\n\t\t\tawait this.backend.all<CapturedEvidenceRow>(readCombinedEvidenceQuery(parameters)),\n\t\t);\n\t\tconst rows: EvidenceRows = {};\n\t\tconst encodedRows: Record<string, string[]> = {};\n\t\tlet bytes = parameters.length;\n\t\tfor (const [name, category] of categories) {\n\t\t\tconst values = parseRows(category);\n\t\t\trows[name] = values.parsed;\n\t\t\tencodedRows[name] = values.encoded;\n\t\t\tbytes += values.encoded.reduce((total, row) => total + row.length, 0);\n\t\t\tif (bytes > BYTE_LIMIT) throw new Error(\"evidence_too_large\");\n\t\t}\n\t\tconst encoded = JSON.stringify({ ...base, rows: encodedRows });\n\t\tif (new TextEncoder().encode(encoded).byteLength > BYTE_LIMIT)\n\t\t\tthrow new Error(\"evidence_too_large\");\n\t\treturn { rows, encoded };\n\t}\n\n\t/** A predicate for a future checked batch, never an admission or a write. */\n\tprepareAtomicRecheck(snapshot: RecheckSnapshot): AuthLinkStatement {\n\t\tconst encoded = this.snapshots.get(snapshot)?.encoded;\n\t\tif (!encoded) return { sql: \"SELECT 0 AS matches\", values: [] };\n\t\treturn atomicEvidenceQuery(encoded);\n\t}\n\n\t/** Private confirmation metadata; only this reader's original capture is accepted. */\n\tasync reviewedEvidenceDigest(snapshot: unknown): Promise<string | null> {\n\t\tif (snapshot === null || typeof snapshot !== \"object\") return null;\n\t\treturn this.snapshots.get(snapshot)?.digest ?? null;\n\t}\n\n\tasync verifyControllerSource(input: {\n\t\tsourceRef: unknown;\n\t\texpectedOwnerId: string;\n\t\tactualSigner: ActualSigner;\n\t}): Promise<SourceVerification> {\n\t\ttry {\n\t\t\tconst captured = captureFields(input, [\"sourceRef\", \"expectedOwnerId\", \"actualSigner\"]);\n\t\t\tconst reference = await captureLegacyOwnerResolutionRecord(captured.sourceRef);\n\t\t\tif (!reference || !identifier(captured.expectedOwnerId)) return unavailable;\n\t\t\tconst subject = await captureSigner(captured.actualSigner, this.coordinatorId);\n\t\t\tif (\n\t\t\t\treference.coordinator_id !== this.coordinatorId ||\n\t\t\t\treference.owner_identity_id !== captured.expectedOwnerId ||\n\t\t\t\treference.device_id !== subject.deviceId ||\n\t\t\t\treference.key_id !== subject.keyId\n\t\t\t)\n\t\t\t\treturn { kind: \"source_mismatch\" };\n\t\t\tconst source = await this.backend.first<Record<string, string | number | null>>({\n\t\t\t\tsql: `SELECT ${CONTROLLER_COLUMNS.map((column) => (column === \"public_key\" ? \"CASE WHEN length(CAST(public_key AS BLOB)) <= 4096 THEN public_key ELSE NULL END AS public_key\" : column)).join(\",\")} FROM coordinator_auth_controller_attestations WHERE coordinator_id=? AND attestation_id=?`,\n\t\t\t\tvalues: [this.coordinatorId, reference.source_attestation_id],\n\t\t\t});\n\t\t\tif (!source) return { kind: \"source_missing\" };\n\t\t\tif (source.revoked_at !== null) return { kind: \"source_revoked\" };\n\t\t\tconst expected = [\n\t\t\t\treference.source_attestation_id,\n\t\t\t\treference.coordinator_id,\n\t\t\t\treference.owner_identity_id,\n\t\t\t\treference.source_group_id,\n\t\t\t\treference.device_id,\n\t\t\t\treference.source_public_key,\n\t\t\t\treference.source_fingerprint,\n\t\t\t\treference.source_review_receipt_id,\n\t\t\t\treference.source_evidence_digest,\n\t\t\t\treference.source_enrollment_identity_id,\n\t\t\t\treference.source_controller_revision,\n\t\t\t\treference.source_created_at,\n\t\t\t\tnull,\n\t\t\t];\n\t\t\tif (\n\t\t\t\t!CONTROLLER_COLUMNS.every((column, i) => source[column] === expected[i]) ||\n\t\t\t\t(await keyId(source.public_key)) !== subject.keyId\n\t\t\t)\n\t\t\t\treturn { kind: \"source_mismatch\" };\n\t\t\treturn { kind: \"verified_controller_source\" };\n\t\t} catch {\n\t\t\treturn unavailable;\n\t\t}\n\t}\n}\n","import {\n\tauthControllerAuthorityValues,\n\tauthControllerInsertValues,\n\tauthControllerOwnerResolutionSql,\n\tauthControllerOwnerResolutionStages,\n\tauthControllerRetryEligibleValues,\n\ttype CoordinatorAuthControllerAttestation,\n\ttype CoordinatorAuthControllerReviewInput,\n\tcaptureAuthControllerReview,\n\tisAuthControllerId,\n} from \"./coordinator-auth-controller.js\";\nimport {\n\ttype ControllerHistorySnapshot,\n\tcaptureControllerHistorySnapshot,\n} from \"./coordinator-auth-controller-history.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport type { CoordinatorDeviceOwnershipEvidence } from \"./coordinator-device-ownership-evidence.js\";\nimport { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport {\n\tcanonicalReviewedWeakLabels,\n\tcaptureLegacyOwnerResolutionRecord,\n\ttype LegacyOwnerResolutionRecord,\n} from \"./coordinator-legacy-owner-resolution-metadata.js\";\n\nexport interface InternalOwnerResolutionReview {\n\tcontrollerReview: CoordinatorAuthControllerReviewInput;\n\texistingController: CoordinatorAuthControllerAttestation | null;\n\texistingResolution: LegacyOwnerResolutionRecord | null;\n\tresolutionId: string;\n\townershipEvidenceDigest: string;\n\tconsent: {\n\t\tpurpose: \"existing_account_owner\";\n\t\tscope: \"historical_included_owner_labels_only\";\n\t\tevidenceDigest: string;\n\t\tconfirmedDigest: string;\n\t};\n}\n\nconst CONTROLLER_FIELDS = [\n\t\"attestation_id\",\n\t\"coordinator_id\",\n\t\"identity_id\",\n\t\"group_id\",\n\t\"device_id\",\n\t\"public_key\",\n\t\"fingerprint\",\n\t\"review_receipt_id\",\n\t\"evidence_digest\",\n\t\"enrollment_identity_id\",\n\t\"revision\",\n\t\"created_at\",\n\t\"revoked_at\",\n] as const;\nconst RESOLUTION_FIELDS = [\n\t\"coordinator_id\",\n\t\"resolution_id\",\n\t\"resolution_version\",\n\t\"device_id\",\n\t\"key_id\",\n\t\"owner_identity_id\",\n\t\"purpose\",\n\t\"scope\",\n\t\"source_attestation_id\",\n\t\"source_group_id\",\n\t\"source_controller_revision\",\n\t\"source_public_key\",\n\t\"source_fingerprint\",\n\t\"source_enrollment_identity_id\",\n\t\"source_created_at\",\n\t\"source_review_receipt_id\",\n\t\"source_evidence_digest\",\n\t\"resolution_evidence_digest\",\n\t\"reviewed_weak_labels_json\",\n\t\"created_at\",\n] as const;\nconst CONTROLLER_TABLE = \"coordinator_auth_controller_attestations\";\nconst RESOLUTION_TABLE = \"coordinator_legacy_owner_resolutions\";\nconst digest = (v: unknown): v is string => typeof v === \"string\" && /^[a-f0-9]{64}$/u.test(v);\n\nfunction exact(value: unknown, fields: readonly string[]): Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value))\n\t\tthrow new Error(\"invalid_review\");\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (prototype !== Object.prototype && prototype !== null) throw new Error(\"invalid_review\");\n\tif (Reflect.ownKeys(value).length !== fields.length) throw new Error(\"invalid_review\");\n\tconst copy: Record<string, unknown> = {};\n\tfor (const field of fields) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, field);\n\t\tif (!descriptor || !(\"value\" in descriptor)) throw new Error(\"invalid_review\");\n\t\tcopy[field] = descriptor.value;\n\t}\n\treturn copy;\n}\n\n/** Reject extensions and accessors at every level before existing shape parsers\n * run. Arrays are copied by descriptors too, never via caller iteration hooks.\n */\nfunction captureTree(value: unknown, depth = 0): unknown {\n\tif (depth > 12) throw new Error(\"invalid_review\");\n\tif (value === null || typeof value === \"string\" || typeof value === \"number\") return value;\n\tif (!value || typeof value !== \"object\") throw new Error(\"invalid_review\");\n\tif (Array.isArray(value)) {\n\t\tconst length = Object.getOwnPropertyDescriptor(value, \"length\")?.value;\n\t\tif (!Number.isSafeInteger(length) || length > 8192) throw new Error(\"invalid_review\");\n\t\tconst fields = Array.from({ length }, (_, i) => String(i));\n\t\tif (Reflect.ownKeys(value).length !== length + 1) throw new Error(\"invalid_review\");\n\t\treturn fields.map((field) => {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, field);\n\t\t\tif (!descriptor || !(\"value\" in descriptor)) throw new Error(\"invalid_review\");\n\t\t\treturn captureTree(descriptor.value, depth + 1);\n\t\t});\n\t}\n\tconst row = exact(\n\t\tvalue,\n\t\tReflect.ownKeys(value).map((key) => {\n\t\t\tif (typeof key !== \"string\") throw new Error(\"invalid_review\");\n\t\t\treturn key;\n\t\t}),\n\t);\n\treturn Object.fromEntries(Object.entries(row).map(([k, v]) => [k, captureTree(v, depth + 1)]));\n}\n\nfunction captureController(value: unknown): CoordinatorAuthControllerAttestation {\n\tconst row = exact(value, CONTROLLER_FIELDS);\n\tconst input = captureAuthControllerReview({\n\t\tattestationId: row.attestation_id,\n\t\tcoordinatorId: row.coordinator_id,\n\t\tidentityId: row.identity_id,\n\t\tgroupId: row.group_id,\n\t\tdeviceId: row.device_id,\n\t\tpublicKey: row.public_key,\n\t\tfingerprint: row.fingerprint,\n\t\treviewReceiptId: row.review_receipt_id,\n\t\tevidenceDigest: row.evidence_digest,\n\t});\n\tif (\n\t\t!input ||\n\t\trow.revision !== 1 ||\n\t\trow.revoked_at !== null ||\n\t\t(row.enrollment_identity_id !== null && !isAuthControllerId(row.enrollment_identity_id)) ||\n\t\t!timestamp(row.created_at)\n\t)\n\t\tthrow new Error(\"invalid_controller\");\n\treturn row as unknown as CoordinatorAuthControllerAttestation;\n}\n\nfunction timestamp(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tNumber.isFinite(Date.parse(value)) &&\n\t\tnew Date(value).toISOString() === value\n\t);\n}\n\nfunction captureReviewController(value: unknown): CoordinatorAuthControllerReviewInput {\n\tconst row = exact(value, [\n\t\t\"attestationId\",\n\t\t\"coordinatorId\",\n\t\t\"identityId\",\n\t\t\"groupId\",\n\t\t\"deviceId\",\n\t\t\"publicKey\",\n\t\t\"fingerprint\",\n\t\t\"reviewReceiptId\",\n\t\t\"evidenceDigest\",\n\t\t\"verifiedSnapshot\",\n\t]);\n\trow.verifiedSnapshot = captureReviewSnapshotFields(row.verifiedSnapshot, row.groupId);\n\tconst captured = captureAuthControllerReview(row);\n\tif (!captured?.verifiedSnapshot?.legacyHistory || !captured.verifiedSnapshot.accountOwnerTarget)\n\t\tthrow new Error(\"invalid_review\");\n\treturn captured;\n}\n\nfunction captureReviewSnapshotFields(value: unknown, groupId: unknown): Record<string, unknown> {\n\tconst snapshot = exact(value, [\n\t\t\"enrollmentIdentityId\",\n\t\t\"invites\",\n\t\t\"legacyHistory\",\n\t\t\"accountOwnerTarget\",\n\t]);\n\tsnapshot.legacyHistory = captureReviewHistory(snapshot.legacyHistory, groupId);\n\tif (!Array.isArray(snapshot.invites)) throw new Error(\"invalid_review\");\n\tfor (const invite of snapshot.invites)\n\t\texact(invite, [\n\t\t\t\"inviteId\",\n\t\t\t\"kind\",\n\t\t\t\"actorId\",\n\t\t\t\"assignedIdentityId\",\n\t\t\t\"targetIdentityId\",\n\t\t\t\"digest\",\n\t\t]);\n\treturn snapshot;\n}\n\nfunction captureReviewHistory(value: unknown, groupId: unknown): ControllerHistorySnapshot {\n\tconst fields = [\n\t\t\"coordinatorId\",\n\t\t\"deviceId\",\n\t\t\"publicKey\",\n\t\t\"fingerprint\",\n\t\t\"keys\",\n\t\t\"discoveryKeys\",\n\t\t\"discoveryFragments\",\n\t\t\"fingerprints\",\n\t\t\"records\",\n\t];\n\tif (value && typeof value === \"object\" && Object.hasOwn(value, \"groupId\")) fields.push(\"groupId\");\n\tconst history = exact(value, fields);\n\tif (Object.hasOwn(history, \"groupId\") && history.groupId !== groupId)\n\t\tthrow new Error(\"invalid_review\");\n\tif (!Array.isArray(history.keys) || !Array.isArray(history.records))\n\t\tthrow new Error(\"invalid_review\");\n\tfor (const key of history.keys) exact(key, [\"public_key\", \"fingerprint\"]);\n\tfor (const record of history.records)\n\t\texact(record, [\n\t\t\t\"group_id\",\n\t\t\t\"candidate_ref\",\n\t\t\t\"manifest_version\",\n\t\t\t\"completed_at\",\n\t\t\t\"created_at\",\n\t\t\t\"manifest_json\",\n\t\t]);\n\tconst captured = captureControllerHistorySnapshot(history);\n\tif (!captured) throw new Error(\"invalid_review\");\n\treturn {\n\t\tcoordinatorId: captured.coordinatorId,\n\t\tdeviceId: captured.deviceId,\n\t\tpublicKey: captured.publicKey,\n\t\tfingerprint: captured.fingerprint,\n\t\tkeys: captured.keys,\n\t\tdiscoveryKeys: captured.discoveryKeys,\n\t\tdiscoveryFragments: captured.discoveryFragments,\n\t\tfingerprints: captured.fingerprints,\n\t\trecords: captured.records,\n\t};\n}\n\n/** Trusted operator-builder input only; this is not a public proof protocol. */\nexport function captureInternalOwnerResolutionReview(\n\tvalue: unknown,\n): InternalOwnerResolutionReview | null {\n\ttry {\n\t\tconst row = exact(captureTree(value), [\n\t\t\t\"controllerReview\",\n\t\t\t\"existingController\",\n\t\t\t\"existingResolution\",\n\t\t\t\"resolutionId\",\n\t\t\t\"ownershipEvidenceDigest\",\n\t\t\t\"consent\",\n\t\t]);\n\t\tconst consent = exact(row.consent, [\"purpose\", \"scope\", \"evidenceDigest\", \"confirmedDigest\"]);\n\t\tif (\n\t\t\tconsent.purpose !== \"existing_account_owner\" ||\n\t\t\tconsent.scope !== \"historical_included_owner_labels_only\" ||\n\t\t\t!digest(consent.evidenceDigest) ||\n\t\t\tconsent.confirmedDigest !== consent.evidenceDigest ||\n\t\t\t!isAuthControllerId(row.resolutionId) ||\n\t\t\t!digest(row.ownershipEvidenceDigest)\n\t\t)\n\t\t\treturn null;\n\t\tconst controllerReview = captureReviewController(row.controllerReview);\n\t\tconst existingController =\n\t\t\trow.existingController === null ? null : captureController(row.existingController);\n\t\t// Canonical key and metadata checks run asynchronously in the writer.\n\t\tconst existingResolution =\n\t\t\trow.existingResolution === null\n\t\t\t\t? null\n\t\t\t\t: (exact(\n\t\t\t\t\t\trow.existingResolution,\n\t\t\t\t\t\tRESOLUTION_FIELDS,\n\t\t\t\t\t) as unknown as LegacyOwnerResolutionRecord);\n\t\treturn {\n\t\t\tcontrollerReview,\n\t\t\texistingController,\n\t\t\texistingResolution,\n\t\t\tresolutionId: row.resolutionId,\n\t\t\townershipEvidenceDigest: row.ownershipEvidenceDigest,\n\t\t\tconsent: {\n\t\t\t\tpurpose: consent.purpose,\n\t\t\t\tscope: consent.scope,\n\t\t\t\tevidenceDigest: consent.evidenceDigest,\n\t\t\t\tconfirmedDigest: consent.confirmedDigest,\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction resolutionRecord(\n\treview: InternalOwnerResolutionReview,\n\tsource: CoordinatorAuthControllerAttestation,\n\tkeyId: string,\n\tlabels: string,\n\tnow: string,\n): LegacyOwnerResolutionRecord {\n\treturn {\n\t\tcoordinator_id: source.coordinator_id,\n\t\tresolution_id: review.resolutionId,\n\t\tresolution_version: 1,\n\t\tdevice_id: source.device_id,\n\t\tkey_id: keyId,\n\t\towner_identity_id: source.identity_id,\n\t\tpurpose: \"existing_account_owner\",\n\t\tscope: \"historical_included_owner_labels_only\",\n\t\tsource_attestation_id: source.attestation_id,\n\t\tsource_group_id: source.group_id,\n\t\tsource_controller_revision: source.revision,\n\t\tsource_public_key: source.public_key,\n\t\tsource_fingerprint: source.fingerprint,\n\t\tsource_enrollment_identity_id: source.enrollment_identity_id,\n\t\tsource_created_at: source.created_at,\n\t\tsource_review_receipt_id: source.review_receipt_id,\n\t\tsource_evidence_digest: source.evidence_digest,\n\t\tresolution_evidence_digest: review.consent.evidenceDigest,\n\t\treviewed_weak_labels_json: labels,\n\t\tcreated_at: now,\n\t};\n}\n\nconst CONTROLLER_ASSERT = `INSERT INTO coordinator_auth_controller_attestations\n\t(attestation_id,coordinator_id,identity_id,group_id,device_id,public_key,fingerprint,\n\treview_receipt_id,evidence_digest,revision,created_at)\n\tSELECT '', '', '', '', '', '', '', '', '', 0, ''`;\nconst RESOLUTION_ASSERT = `INSERT INTO coordinator_legacy_owner_resolutions\n\t(${RESOLUTION_FIELDS.join(\",\")}) SELECT '', '', 0, '', '', '', '', '', '', '', 0, '', '', NULL, '', '', '', '', '[]', ''`;\n\n/** A failing predicate performs an invalid INSERT, forcing rollback. Success\n * writes nothing. No reliance on discarded SELECT expressions or JS counts.\n */\nfunction assertRead(\n\tstatement: AuthLinkStatement,\n\tcolumn: \"matches\" | \"eligible\",\n): AuthLinkStatement[] {\n\tconst predicate = `NOT COALESCE((SELECT ${column} FROM (${statement.sql})),0)`;\n\treturn [CONTROLLER_ASSERT, RESOLUTION_ASSERT].map((prefix) => ({\n\t\tsql: `${prefix} WHERE ${predicate}`,\n\t\tvalues: statement.values,\n\t}));\n}\n\nfunction assertEligibility(\n\tinput: CoordinatorAuthControllerReviewInput,\n\tauthority: (string | null)[],\n): AuthLinkStatement[] {\n\tconst stages = authControllerOwnerResolutionStages(\"eligible\", input);\n\treturn [CONTROLLER_ASSERT, RESOLUTION_ASSERT].map((prefix) => ({\n\t\tsql: `${stages.ctes}, owner_resolution_eligibility AS MATERIALIZED (${stages.statement})\n\t\t\t${prefix} FROM (SELECT 1) pending\n\t\t\tLEFT JOIN owner_resolution_eligibility eligible_result ON 1\n\t\t\tWHERE eligible_result.eligible IS NULL`,\n\t\tvalues: authControllerRetryEligibleValues(input, authority),\n\t}));\n}\n\nfunction rowPin(\n\ttable: typeof CONTROLLER_TABLE | typeof RESOLUTION_TABLE,\n\trow: CoordinatorAuthControllerAttestation | LegacyOwnerResolutionRecord,\n\tpresent: boolean,\n): AuthLinkStatement {\n\tconst fields = table === CONTROLLER_TABLE ? CONTROLLER_FIELDS : RESOLUTION_FIELDS;\n\tconst id = table === CONTROLLER_TABLE ? \"attestation_id\" : \"resolution_id\";\n\tlet receiptId: string;\n\tif (table === CONTROLLER_TABLE) {\n\t\tif (!(\"attestation_id\" in row)) throw new Error(\"invalid_controller_pin\");\n\t\treceiptId = row.attestation_id;\n\t} else {\n\t\tif (!(\"resolution_id\" in row)) throw new Error(\"invalid_resolution_pin\");\n\t\treceiptId = row.resolution_id;\n\t}\n\tif (!present)\n\t\treturn {\n\t\t\tsql: `SELECT NOT EXISTS (SELECT 1 FROM ${table} WHERE coordinator_id=? AND ${id}=?) AS matches`,\n\t\t\tvalues: [row.coordinator_id, receiptId],\n\t\t};\n\treturn {\n\t\tsql: `WITH pin(value) AS (SELECT ?) SELECT EXISTS (SELECT 1 FROM ${table} r CROSS JOIN pin p WHERE ${fields.map((field) => `r.${field} IS json_extract(p.value,'$.${field}')`).join(\" AND \")}) AS matches`,\n\t\tvalues: [JSON.stringify(row)],\n\t};\n}\n\nasync function requireReviewedEvidence(\n\tevidence: CoordinatorDeviceOwnershipEvidence,\n\tsnapshot: Parameters<CoordinatorDeviceOwnershipEvidence[\"prepareAtomicRecheck\"]>[0],\n\treview: InternalOwnerResolutionReview,\n): Promise<void> {\n\tconst freshDigest = await evidence.reviewedEvidenceDigest(snapshot);\n\tif (freshDigest === null || freshDigest !== review.ownershipEvidenceDigest)\n\t\tthrow new Error(\"ownership_evidence_changed\");\n}\n\nasync function prepareCommit(\n\tbackend: AuthLinkBackend,\n\tevidence: CoordinatorDeviceOwnershipEvidence,\n\treview: InternalOwnerResolutionReview,\n\tnow: string,\n) {\n\tconst input = review.controllerReview;\n\tconst snapshot = input.verifiedSnapshot;\n\tif (!timestamp(now) || !snapshot?.legacyHistory) throw new Error(\"invalid_review\");\n\tconst signer = {\n\t\tgroupId: input.groupId,\n\t\tdeviceId: input.deviceId,\n\t\tpublicKey: input.publicKey,\n\t\tfingerprint: input.fingerprint,\n\t};\n\tconst keyId = await ed25519KeyIdForRevocation(input.publicKey);\n\tif (!keyId) throw new Error(\"invalid_key\");\n\tconst collected = await evidence.collect({\n\t\tcanonicalOwnerId: input.identityId,\n\t\tactualSigner: signer,\n\t\tverifiedHistory: snapshot.legacyHistory,\n\t});\n\tif (\n\t\tcollected.kind !== \"collected\" ||\n\t\t![\"compatible\", \"weak_label_review_required\"].includes(collected.decision)\n\t)\n\t\tthrow new Error(\"ownership_unavailable\");\n\tawait requireReviewedEvidence(evidence, collected.recheckSnapshot, review);\n\tconst labels = canonicalReviewedWeakLabels(collected.weakLabels);\n\tif (labels === null) throw new Error(\"invalid_labels\");\n\tconst controller = reviewedController(review, snapshot.enrollmentIdentityId, now);\n\tconst proposed = resolutionRecord(review, controller, keyId, labels, now);\n\tif (review.existingController) {\n\t\tconst verified = await evidence.verifyControllerSource({\n\t\t\tsourceRef: proposed,\n\t\t\texpectedOwnerId: input.identityId,\n\t\t\tactualSigner: signer,\n\t\t});\n\t\tif (verified.kind !== \"verified_controller_source\") throw new Error(\"source_mismatch\");\n\t}\n\tconst resolution = await reviewedResolution(review, proposed);\n\tconst authority = authControllerAuthorityValues(\n\t\t{\n\t\t\tgroup_id: input.groupId,\n\t\t\tdevice_id: input.deviceId,\n\t\t\tpublic_key: input.publicKey,\n\t\t\tfingerprint: input.fingerprint,\n\t\t\tidentity_id: snapshot.enrollmentIdentityId,\n\t\t},\n\t\tkeyId,\n\t);\n\tconst statements = await prepareAssertions(\n\t\tbackend,\n\t\treview,\n\t\tcontroller,\n\t\tresolution,\n\t\tevidence.prepareAtomicRecheck(collected.recheckSnapshot),\n\t\tauthority,\n\t);\n\tappendReceiptWrites(statements, review, resolution, now, authority);\n\treturn { controller, resolution, statements };\n}\n\nfunction reviewedController(\n\treview: InternalOwnerResolutionReview,\n\tenrollmentIdentityId: string | null,\n\tnow: string,\n): CoordinatorAuthControllerAttestation {\n\tconst input = review.controllerReview;\n\treturn (\n\t\treview.existingController ?? {\n\t\t\tattestation_id: input.attestationId,\n\t\t\tcoordinator_id: input.coordinatorId,\n\t\t\tidentity_id: input.identityId,\n\t\t\tgroup_id: input.groupId,\n\t\t\tdevice_id: input.deviceId,\n\t\t\tpublic_key: input.publicKey,\n\t\t\tfingerprint: input.fingerprint,\n\t\t\treview_receipt_id: input.reviewReceiptId,\n\t\t\tevidence_digest: input.evidenceDigest,\n\t\t\tenrollment_identity_id: enrollmentIdentityId,\n\t\t\trevision: 1 as const,\n\t\t\tcreated_at: now,\n\t\t\trevoked_at: null,\n\t\t}\n\t);\n}\n\nasync function reviewedResolution(\n\treview: InternalOwnerResolutionReview,\n\tproposed: LegacyOwnerResolutionRecord,\n): Promise<LegacyOwnerResolutionRecord> {\n\tif (!review.existingResolution) return proposed;\n\tconst old = await captureLegacyOwnerResolutionRecord(review.existingResolution);\n\tif (\n\t\t!review.existingController ||\n\t\t!old ||\n\t\told.resolution_id !== review.resolutionId ||\n\t\t!RESOLUTION_FIELDS.filter(\n\t\t\t(field) =>\n\t\t\t\t![\"resolution_evidence_digest\", \"reviewed_weak_labels_json\", \"created_at\"].includes(field),\n\t\t).every((field) => old[field] === proposed[field])\n\t)\n\t\tthrow new Error(\"resolution_mismatch\");\n\treturn old;\n}\n\nasync function prepareAssertions(\n\tbackend: AuthLinkBackend,\n\treview: InternalOwnerResolutionReview,\n\tcontroller: CoordinatorAuthControllerAttestation,\n\tresolution: LegacyOwnerResolutionRecord,\n\tevidenceRecheck: AuthLinkStatement,\n\tauthority: (string | null)[],\n): Promise<AuthLinkStatement[]> {\n\tconst input = review.controllerReview;\n\tconst catalog = await backend.first<{ objects: string }>({\n\t\tsql: \"SELECT json_group_array(json_object('type',type,'name',name,'sql',sql)) AS objects FROM sqlite_master WHERE tbl_name='coordinator_legacy_owner_resolutions'\",\n\t\tvalues: [],\n\t});\n\tif (!catalog) throw new Error(\"schema_unavailable\");\n\treturn [\n\t\t...assertRead(evidenceRecheck, \"matches\"),\n\t\t...assertEligibility(input, authority),\n\t\t...assertRead(\n\t\t\t{\n\t\t\t\tsql: \"SELECT (SELECT json_group_array(json_object('type',type,'name',name,'sql',sql)) FROM sqlite_master WHERE tbl_name='coordinator_legacy_owner_resolutions') IS ? AS matches\",\n\t\t\t\tvalues: [catalog.objects],\n\t\t\t},\n\t\t\t\"matches\",\n\t\t),\n\t\t...assertRead(\n\t\t\trowPin(CONTROLLER_TABLE, controller, review.existingController !== null),\n\t\t\t\"matches\",\n\t\t),\n\t\t...assertRead(\n\t\t\trowPin(RESOLUTION_TABLE, resolution, review.existingResolution !== null),\n\t\t\t\"matches\",\n\t\t),\n\t];\n}\n\nfunction appendReceiptWrites(\n\tstatements: AuthLinkStatement[],\n\treview: InternalOwnerResolutionReview,\n\tresolution: LegacyOwnerResolutionRecord,\n\tnow: string,\n\tauthority: (string | null)[],\n): void {\n\tconst input = review.controllerReview;\n\tif (!review.existingController) {\n\t\tstatements.push({\n\t\t\tsql: authControllerOwnerResolutionSql(\"create\", input),\n\t\t\tvalues: authControllerInsertValues(input, now, authority),\n\t\t});\n\t\tstatements.push({ sql: `${RESOLUTION_ASSERT} WHERE changes() <> 1`, values: [] });\n\t}\n\tif (!review.existingResolution) {\n\t\tstatements.push({\n\t\t\tsql: `INSERT INTO ${RESOLUTION_TABLE} (${RESOLUTION_FIELDS.join(\",\")}) SELECT ${RESOLUTION_FIELDS.map((field) => `json_extract(value,'$.${field}')`).join(\",\")} FROM (SELECT ? AS value)`,\n\t\t\tvalues: [JSON.stringify(resolution)],\n\t\t});\n\t\tstatements.push({ sql: `${CONTROLLER_ASSERT} WHERE changes() <> 1`, values: [] });\n\t}\n}\n\n/** Exactly one checked backend batch. A postcommit read failure is a persistence\n * error, never a claim that the successful transaction changed nothing.\n */\nexport async function commitReviewedOwnerResolution(options: {\n\tbackend: AuthLinkBackend;\n\tevidence: CoordinatorDeviceOwnershipEvidence;\n\treview: unknown;\n\tnow: string;\n}) {\n\ttry {\n\t\tconst review = captureInternalOwnerResolutionReview(options.review);\n\t\tif (!review) throw new Error(\"invalid_review\");\n\t\tconst prepared = await prepareCommit(options.backend, options.evidence, review, options.now);\n\t\tawait options.backend.batch(prepared.statements);\n\t\tconst controller = await options.backend.first<CoordinatorAuthControllerAttestation>({\n\t\t\tsql: `SELECT * FROM ${CONTROLLER_TABLE} WHERE coordinator_id=? AND attestation_id=?`,\n\t\t\tvalues: [prepared.controller.coordinator_id, prepared.controller.attestation_id],\n\t\t});\n\t\tconst resolution = await options.backend.first<LegacyOwnerResolutionRecord>({\n\t\t\tsql: `SELECT * FROM ${RESOLUTION_TABLE} WHERE coordinator_id=? AND resolution_id=?`,\n\t\t\tvalues: [prepared.resolution.coordinator_id, prepared.resolution.resolution_id],\n\t\t});\n\t\tif (\n\t\t\t!controller ||\n\t\t\t!resolution ||\n\t\t\t!CONTROLLER_FIELDS.every((field) => controller[field] === prepared.controller[field]) ||\n\t\t\t!RESOLUTION_FIELDS.every((field) => resolution[field] === prepared.resolution[field])\n\t\t)\n\t\t\tthrow new Error(\"receipt_read_failed\");\n\t\treturn {\n\t\t\tcontroller,\n\t\t\tcontrollerDisposition: review.existingController ? (\"reused\" as const) : (\"created\" as const),\n\t\t\tresolution,\n\t\t\tresolutionDisposition: review.existingResolution ? (\"reused\" as const) : (\"created\" as const),\n\t\t};\n\t} catch {\n\t\tthrow new Error(\"Owner resolution outcome is unavailable; check its status before retrying\");\n\t}\n}\n","import { readConnectionSchemaState } from \"./coordinator-account-connection-schema.js\";\nimport { CONNECTION_NOT_REVOKED_SQL } from \"./coordinator-account-connection-storage.js\";\nimport type {\n\tCoordinatorAuthControllerAttestation,\n\tCoordinatorAuthControllerVerifiedSnapshot,\n} from \"./coordinator-auth-controller.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { ControllerHistorySnapshot } from \"./coordinator-auth-controller-history.js\";\nimport type {\n\tCoordinatorAuthLinkConfig,\n\tCoordinatorAuthLinkSigner,\n} from \"./coordinator-auth-link-contract.js\";\nimport { isHash } from \"./coordinator-auth-link-input.js\";\nimport { authAccountLinkProvenanceSql } from \"./coordinator-auth-link-provenance.js\";\nimport type { CoordinatorDeviceOwnershipEvidence } from \"./coordinator-device-ownership-evidence.js\";\nimport {\n\tCONTROLLER_COLUMNS,\n\tRESOLUTION_COLUMNS,\n} from \"./coordinator-device-ownership-evidence-queries.js\";\nimport { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport {\n\tcaptureLegacyOwnerResolutionRecord,\n\ttype LegacyOwnerResolutionRecord,\n\treadLegacyOwnerResolutionSchemaState,\n} from \"./coordinator-legacy-owner-resolution-metadata.js\";\nimport type {\n\tOwnerResolutionReviewBackend,\n\tOwnerResolutionReviewSelection,\n} from \"./coordinator-owner-resolution-review.js\";\n\nexport interface ResolutionTarget {\n\tlink_id: string;\n\tauth_config_revision: string;\n\tcreated_at_ms: number;\n}\n\nexport class ReviewUnavailable extends Error {}\n\nexport async function requireReviewSchema(backend: OwnerResolutionReviewBackend) {\n\tif (\n\t\t(await readLegacyOwnerResolutionSchemaState(backend)) !== \"ready\" ||\n\t\t(await readConnectionSchemaState(backend)) !== \"ready\"\n\t)\n\t\tthrow new ReviewUnavailable(\n\t\t\t\"upgrade_required: ask the operator to upgrade the coordinator ownership schema\",\n\t\t);\n}\n\n/** Account provenance belongs to A; the requester is collected separately, never impersonated. */\nexport async function readResolutionTarget(\n\tbackend: OwnerResolutionReviewBackend,\n\tselection: OwnerResolutionReviewSelection,\n\tconfig: CoordinatorAuthLinkConfig,\n): Promise<ResolutionTarget> {\n\tconst rows = await backend.all<ResolutionTarget>({\n\t\tsql: `SELECT l.link_id,l.auth_config_revision,l.created_at_ms FROM coordinator_auth_account_links l\n\t\t WHERE l.coordinator_id=? AND l.identity_id=? AND l.issuer=?\n\t\t AND ${CONNECTION_NOT_REVOKED_SQL}\n\t\t AND ${authAccountLinkProvenanceSql(\"l\", { connections: true })} LIMIT 2`,\n\t\tvalues: [config.coordinatorId, selection.identityId, config.issuer],\n\t});\n\tconst row = rows[0];\n\tif (\n\t\trows.length !== 1 ||\n\t\t!row ||\n\t\t!isAuthControllerId(row.link_id) ||\n\t\t!isHash(row.auth_config_revision) ||\n\t\t!Number.isSafeInteger(row.created_at_ms) ||\n\t\trow.created_at_ms < 0\n\t)\n\t\tthrow new ReviewUnavailable(\n\t\t\t\"account_owner_target_unavailable: verify the selected account connection\",\n\t\t);\n\treturn row;\n}\n\nexport async function readResolutionRequester(\n\tbackend: OwnerResolutionReviewBackend,\n\tselection: OwnerResolutionReviewSelection,\n) {\n\tconst row = await backend.first<{\n\t\tpublic_key: string;\n\t\tfingerprint: string;\n\t\tidentity_id: string | null;\n\t}>({\n\t\tsql: `SELECT CASE WHEN length(CAST(e.public_key AS BLOB))<=4096 THEN e.public_key ELSE NULL END AS public_key,\n\t\t e.fingerprint,e.identity_id FROM enrolled_devices e JOIN groups g ON g.group_id=e.group_id\n\t\t WHERE e.group_id=? AND e.device_id=? AND e.enabled=1 AND g.archived_at IS NULL`,\n\t\tvalues: [selection.groupId, selection.deviceId],\n\t});\n\tif (\n\t\t!row ||\n\t\trow.fingerprint !== selection.fingerprint ||\n\t\t!(await ed25519KeyIdForRevocation(row.public_key))\n\t)\n\t\tthrow new ReviewUnavailable(\n\t\t\t\"requester_unavailable: verify the current group, enrollment and key\",\n\t\t);\n\treturn {\n\t\tsigner: {\n\t\t\tgroupId: selection.groupId,\n\t\t\tdeviceId: selection.deviceId,\n\t\t\tpublicKey: row.public_key,\n\t\t\tfingerprint: row.fingerprint,\n\t\t},\n\t\tenrollmentIdentityId: row.identity_id,\n\t};\n}\n\nexport async function readResolutionInvites(\n\tbackend: OwnerResolutionReviewBackend,\n\tsigner: CoordinatorAuthLinkSigner,\n) {\n\tconst invites = await backend.all<CoordinatorAuthControllerVerifiedSnapshot[\"invites\"][number]>({\n\t\tsql: `SELECT invite_id AS inviteId,invite_kind AS kind,recipient_actor_id AS actorId,\n\t\t assigned_identity_id AS assignedIdentityId,target_identity_id AS targetIdentityId,reviewed_preview_digest AS digest\n\t\t FROM coordinator_invites WHERE group_id=? AND bound_device_id=? AND bound_public_key=? AND bound_fingerprint=?\n\t\t AND revoked_at IS NULL AND consumed_at IS NOT NULL AND consumed_at!=''\n\t\t AND invite_kind IN ('team_member','add_device') ORDER BY invite_id LIMIT 501`,\n\t\tvalues: [signer.groupId, signer.deviceId, signer.publicKey, signer.fingerprint],\n\t});\n\tif (invites.length > 500)\n\t\tthrow new ReviewUnavailable(\n\t\t\t\"evidence_too_large: ask the operator to inspect consumed invitations\",\n\t\t);\n\treturn invites;\n}\n\nfunction controllerFromResolution(\n\trow: LegacyOwnerResolutionRecord,\n): CoordinatorAuthControllerAttestation {\n\treturn {\n\t\tattestation_id: row.source_attestation_id,\n\t\tcoordinator_id: row.coordinator_id,\n\t\tidentity_id: row.owner_identity_id,\n\t\tgroup_id: row.source_group_id,\n\t\tdevice_id: row.device_id,\n\t\tpublic_key: row.source_public_key,\n\t\tfingerprint: row.source_fingerprint,\n\t\treview_receipt_id: row.source_review_receipt_id,\n\t\tevidence_digest: row.source_evidence_digest,\n\t\tenrollment_identity_id: row.source_enrollment_identity_id,\n\t\trevision: row.source_controller_revision,\n\t\tcreated_at: row.source_created_at,\n\t\trevoked_at: null,\n\t};\n}\n\nasync function readExistingResolutions(\n\tbackend: OwnerResolutionReviewBackend,\n\tconfig: CoordinatorAuthLinkConfig,\n\tsigner: CoordinatorAuthLinkSigner,\n) {\n\tconst keyId = await ed25519KeyIdForRevocation(signer.publicKey);\n\tconst rows = await backend.all<unknown>({\n\t\tsql: `SELECT ${RESOLUTION_COLUMNS.join(\",\")} FROM coordinator_legacy_owner_resolutions\n\t\t WHERE coordinator_id=? AND (device_id=? OR key_id=?)\n\t\t ORDER BY created_at,resolution_id LIMIT 501`,\n\t\tvalues: [config.coordinatorId, signer.deviceId, keyId],\n\t});\n\tif (rows.length > 500 || new TextEncoder().encode(JSON.stringify(rows)).byteLength > 750_000)\n\t\tthrow new ReviewUnavailable(\"evidence_too_large: inspect retained resolution receipts\");\n\tconst exact: LegacyOwnerResolutionRecord[] = [];\n\tfor (const value of rows) {\n\t\tconst row = await captureLegacyOwnerResolutionRecord(value);\n\t\tif (!row)\n\t\t\tthrow new ReviewUnavailable(\"source_unavailable: inspect retained resolution metadata\");\n\t\tif (row.device_id === signer.deviceId && row.key_id === keyId) exact.push(row);\n\t}\n\tif (rows.length && !exact.length)\n\t\tthrow new ReviewUnavailable(\n\t\t\t\"source_unavailable: ask the operator to inspect the retained resolution subject\",\n\t\t);\n\treturn exact;\n}\n\nasync function verifiedResolutionSource(\n\trows: LegacyOwnerResolutionRecord[],\n\tselection: OwnerResolutionReviewSelection,\n\tsigner: CoordinatorAuthLinkSigner,\n\tevidence: CoordinatorDeviceOwnershipEvidence,\n) {\n\tfor (const resolution of rows) {\n\t\tconst verified = await evidence.verifyControllerSource({\n\t\t\tsourceRef: resolution,\n\t\t\texpectedOwnerId: selection.identityId,\n\t\t\tactualSigner: signer,\n\t\t});\n\t\tif (verified.kind === \"verified_controller_source\")\n\t\t\treturn { controller: controllerFromResolution(resolution), resolution };\n\t}\n\tthrow new ReviewUnavailable(\n\t\t\"source_unavailable: inspect the original controllers and immutable resolution receipts\",\n\t);\n}\n\nasync function readRetainedControllers(\n\tbackend: OwnerResolutionReviewBackend,\n\tconfig: CoordinatorAuthLinkConfig,\n\tsigner: CoordinatorAuthLinkSigner,\n\thistory: ControllerHistorySnapshot,\n) {\n\tconst rows = await backend.all<CoordinatorAuthControllerAttestation>({\n\t\tsql: `SELECT ${CONTROLLER_COLUMNS.join(\",\")} FROM coordinator_auth_controller_attestations\n\t\t WHERE coordinator_id=? AND device_id=? AND (public_key IN (SELECT value FROM json_each(?))\n\t\t OR (group_id=? AND fingerprint=?)) ORDER BY group_id,attestation_id LIMIT 501`,\n\t\tvalues: [\n\t\t\tconfig.coordinatorId,\n\t\t\tsigner.deviceId,\n\t\t\tJSON.stringify(history.keys.map((key) => key.public_key)),\n\t\t\tsigner.groupId,\n\t\t\tsigner.fingerprint,\n\t\t],\n\t});\n\tif (rows.length > 500 || new TextEncoder().encode(JSON.stringify(rows)).byteLength > 750_000)\n\t\tthrow new ReviewUnavailable(\n\t\t\t\"evidence_too_large: ask the operator to inspect retained controllers\",\n\t\t);\n\treturn rows;\n}\n\nexport async function readResolutionSource(options: {\n\tbackend: OwnerResolutionReviewBackend;\n\tconfig: CoordinatorAuthLinkConfig;\n\tselection: OwnerResolutionReviewSelection;\n\tsigner: CoordinatorAuthLinkSigner;\n\thistory: ControllerHistorySnapshot;\n\tevidence: CoordinatorDeviceOwnershipEvidence;\n}) {\n\tconst { backend, config, selection, signer, history, evidence } = options;\n\tconst controllers = await readRetainedControllers(backend, config, signer, history);\n\tconst current = controllers.filter(\n\t\t(row) => row.group_id === signer.groupId && row.fingerprint === signer.fingerprint,\n\t);\n\tif (\n\t\tcurrent.some(\n\t\t\t(row) =>\n\t\t\t\trow.revoked_at !== null ||\n\t\t\t\trow.identity_id !== selection.identityId ||\n\t\t\t\trow.public_key !== signer.publicKey,\n\t\t)\n\t)\n\t\tthrow new ReviewUnavailable(\n\t\t\t\"controller_unavailable: inspect the current controller tombstone or owner conflict\",\n\t\t);\n\tconst resolutions = await readExistingResolutions(backend, config, signer);\n\tif (resolutions.length) return verifiedResolutionSource(resolutions, selection, signer, evidence);\n\tconst controller =\n\t\tcontrollers.find(\n\t\t\t(row) => row.revoked_at === null && row.identity_id === selection.identityId,\n\t\t) ?? null;\n\treturn { controller, resolution: null };\n}\n","import type { CoordinatorAuthControllerAttestation } from \"./coordinator-auth-controller.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { ControllerHistorySnapshot } from \"./coordinator-auth-controller-history.js\";\nimport {\n\ttype ControllerHistoryEvidence,\n\tcaptureControllerHistory,\n\tcontrollerHistoryDigestEvidence,\n\tparseControllerHistoryRecord,\n} from \"./coordinator-auth-controller-history.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport type {\n\tCoordinatorAuthLinkConfig,\n\tCoordinatorAuthLinkSigner,\n} from \"./coordinator-auth-link-contract.js\";\nimport { capture, captureAuthLinkConfig, isHash } from \"./coordinator-auth-link-input.js\";\nimport { CoordinatorDeviceOwnershipEvidence } from \"./coordinator-device-ownership-evidence.js\";\nimport {\n\tcommitReviewedOwnerResolution,\n\ttype InternalOwnerResolutionReview,\n} from \"./coordinator-legacy-owner-resolution-commit.js\";\nimport type {\n\tLegacyOwnerResolutionRecord,\n\tReviewedWeakLabel,\n} from \"./coordinator-legacy-owner-resolution-metadata.js\";\nimport {\n\ttype ResolutionTarget,\n\tReviewUnavailable,\n\treadResolutionInvites,\n\treadResolutionRequester,\n\treadResolutionSource,\n\treadResolutionTarget,\n\trequireReviewSchema,\n} from \"./coordinator-owner-resolution-review-read.js\";\n\nexport interface OwnerResolutionReviewBackend extends AuthLinkBackend {\n\tall<T>(statement: AuthLinkStatement): Promise<T[]>;\n}\nexport interface OwnerResolutionReviewSelection {\n\tgroupId: string;\n\tdeviceId: string;\n\tidentityId: string;\n\tfingerprint: string;\n}\nexport interface OwnerResolutionReviewConfirmation extends OwnerResolutionReviewSelection {\n\tconfirmOwnerResolutionDigest?: string;\n}\ntype Disposition = \"created\" | \"reused\";\nexport interface OwnerResolutionReviewResult {\n\tpurpose: \"existing_account_owner\";\n\tresolution_scope: \"historical_included_owner_labels_only\";\n\tstate: \"ready\" | \"needs_review\" | \"restored\";\n\treasons: string[];\n\tcoordinator_id: string;\n\tgroup_id: string;\n\tdevice_id: string;\n\tidentity_id: string;\n\tfingerprint: string;\n\towner_resolution_digest?: string;\n\taccount_owner_target?: ResolutionTarget & { identity_id: string };\n\tlegacy_history: ControllerHistoryEvidence[];\n\treviewed_weak_labels: ReviewedWeakLabel[];\n\tattestation_id?: string;\n\trecovery_receipt?: {\n\t\tdisposition: Disposition;\n\t\treview_receipt_id: string;\n\t\tevidence_digest: string;\n\t\tcreated_at: string;\n\t};\n\towner_resolution?: {\n\t\tdisposition: Disposition;\n\t\tresolution_id: string;\n\t\tevidence_digest: string;\n\t\tcreated_at: string;\n\t};\n}\n\n/** Callers must authenticate their trusted operator before using this capability. */\nexport interface CoordinatorOwnerResolutionReviewStore {\n\tpreviewOwnerResolutionReview(\n\t\tselection: OwnerResolutionReviewSelection,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<OwnerResolutionReviewResult>;\n\tconfirmOwnerResolutionReview(\n\t\tselection: OwnerResolutionReviewConfirmation,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<OwnerResolutionReviewResult>;\n}\n\nexport class OwnerResolutionReviewError extends Error {\n\tconstructor(readonly code: \"review_stale\" | \"owner_resolution_outcome_unknown\") {\n\t\tsuper(\n\t\t\tcode === \"review_stale\"\n\t\t\t\t? \"Review changed or confirmation is missing; preview again before confirming\"\n\t\t\t\t: \"Owner resolution outcome is unknown; preview its status before retrying\",\n\t\t);\n\t\tthis.name = \"OwnerResolutionReviewError\";\n\t}\n}\n\nconst PURPOSE = \"existing_account_owner\";\nconst SCOPE = \"historical_included_owner_labels_only\";\nconst SELECTION_FIELDS = [\"groupId\", \"deviceId\", \"identityId\", \"fingerprint\"] as const;\nfunction captureSelection(value: unknown): OwnerResolutionReviewSelection | null {\n\tconst row = capture(value, SELECTION_FIELDS);\n\tif (\n\t\t!row ||\n\t\t!isAuthControllerId(row.groupId) ||\n\t\t!isAuthControllerId(row.deviceId) ||\n\t\t!isAuthControllerId(row.identityId) ||\n\t\t!isHash(row.fingerprint)\n\t)\n\t\treturn null;\n\treturn {\n\t\tgroupId: row.groupId,\n\t\tdeviceId: row.deviceId,\n\t\tidentityId: row.identityId,\n\t\tfingerprint: row.fingerprint,\n\t};\n}\n\nasync function sha(value: unknown): Promise<string> {\n\tconst bytes = new TextEncoder().encode(JSON.stringify(value));\n\tconst digest = await crypto.subtle.digest(\"SHA-256\", bytes);\n\treturn Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction baseResult(\n\tselection: OwnerResolutionReviewSelection | null,\n\tconfig: CoordinatorAuthLinkConfig | null,\n): OwnerResolutionReviewResult {\n\treturn {\n\t\tpurpose: PURPOSE,\n\t\tresolution_scope: SCOPE,\n\t\tstate: \"needs_review\",\n\t\treasons: [],\n\t\tcoordinator_id: config?.coordinatorId ?? \"\",\n\t\tgroup_id: selection?.groupId ?? \"\",\n\t\tdevice_id: selection?.deviceId ?? \"\",\n\t\tidentity_id: selection?.identityId ?? \"\",\n\t\tfingerprint: selection?.fingerprint ?? \"\",\n\t\tlegacy_history: [],\n\t\treviewed_weak_labels: [],\n\t};\n}\n\nfunction receiptResult(\n\tcontroller: CoordinatorAuthControllerAttestation,\n\tresolution: LegacyOwnerResolutionRecord | null,\n\tcontrollerDisposition: Disposition,\n\tresolutionDisposition: Disposition,\n) {\n\treturn {\n\t\tattestation_id: controller.attestation_id,\n\t\trecovery_receipt: {\n\t\t\tdisposition: controllerDisposition,\n\t\t\treview_receipt_id: controller.review_receipt_id,\n\t\t\tevidence_digest: controller.evidence_digest,\n\t\t\tcreated_at: controller.created_at,\n\t\t},\n\t\t...(resolution\n\t\t\t? {\n\t\t\t\t\towner_resolution: {\n\t\t\t\t\t\tdisposition: resolutionDisposition,\n\t\t\t\t\t\tresolution_id: resolution.resolution_id,\n\t\t\t\t\t\tevidence_digest: resolution.resolution_evidence_digest,\n\t\t\t\t\t\tcreated_at: resolution.created_at,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\ninterface PreparedReview {\n\tresult: OwnerResolutionReviewResult;\n\treview?: InternalOwnerResolutionReview;\n\tevidence?: CoordinatorDeviceOwnershipEvidence;\n}\n\ninterface CapturedSubject {\n\tsigner: CoordinatorAuthLinkSigner;\n\tenrollmentIdentityId: string | null;\n\thistory: ControllerHistorySnapshot;\n\tevidence: CoordinatorDeviceOwnershipEvidence;\n\townershipEvidenceDigest: string;\n\tweakLabels: ReviewedWeakLabel[];\n\trecheckSnapshot: Parameters<CoordinatorDeviceOwnershipEvidence[\"prepareAtomicRecheck\"]>[0];\n}\ntype ResolutionSource = Awaited<ReturnType<typeof readResolutionSource>>;\n\nasync function buildInternalReview(options: {\n\tselection: OwnerResolutionReviewSelection;\n\tconfig: CoordinatorAuthLinkConfig;\n\tsubject: CapturedSubject;\n\tsource: ResolutionSource;\n\ttarget: ResolutionTarget;\n\tinvites: Awaited<ReturnType<typeof readResolutionInvites>>;\n\tdigest: string;\n}): Promise<InternalOwnerResolutionReview> {\n\tconst { selection, config, subject, source, target, invites, digest } = options;\n\tconst attestationId = `controller-v1:${await sha([config.coordinatorId, selection.groupId, selection.deviceId, selection.fingerprint])}`;\n\treturn {\n\t\tcontrollerReview: {\n\t\t\tattestationId,\n\t\t\tcoordinatorId: config.coordinatorId,\n\t\t\tidentityId: selection.identityId,\n\t\t\t...subject.signer,\n\t\t\treviewReceiptId: `review-v1:${await sha([attestationId, selection.identityId, digest])}`,\n\t\t\tevidenceDigest: digest,\n\t\t\tverifiedSnapshot: {\n\t\t\t\tenrollmentIdentityId: subject.enrollmentIdentityId,\n\t\t\t\tinvites,\n\t\t\t\tlegacyHistory: subject.history,\n\t\t\t\taccountOwnerTarget: {\n\t\t\t\t\tpurpose: PURPOSE,\n\t\t\t\t\tcoordinatorId: config.coordinatorId,\n\t\t\t\t\ttargetIdentityId: selection.identityId,\n\t\t\t\t\tissuer: config.issuer,\n\t\t\t\t\tlinkId: target.link_id,\n\t\t\t\t\tauthConfigRevision: target.auth_config_revision,\n\t\t\t\t\tcreatedAtMs: target.created_at_ms,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\texistingController: source.controller,\n\t\texistingResolution: source.resolution,\n\t\townershipEvidenceDigest: subject.ownershipEvidenceDigest,\n\t\tresolutionId:\n\t\t\tsource.resolution?.resolution_id ??\n\t\t\t`resolution-v1:${await sha([config.coordinatorId, selection.deviceId, selection.identityId, digest])}`,\n\t\tconsent: { purpose: PURPOSE, scope: SCOPE, evidenceDigest: digest, confirmedDigest: digest },\n\t};\n}\n\nfunction preparedResult(\n\tbase: OwnerResolutionReviewResult,\n\tsubject: CapturedSubject,\n\ttarget: ResolutionTarget,\n\tsource: ResolutionSource,\n\tdigest: string,\n): OwnerResolutionReviewResult {\n\treturn {\n\t\t...base,\n\t\tstate: source.resolution ? \"restored\" : \"ready\",\n\t\towner_resolution_digest: digest,\n\t\taccount_owner_target: {\n\t\t\tidentity_id: base.identity_id,\n\t\t\tlink_id: target.link_id,\n\t\t\tauth_config_revision: target.auth_config_revision,\n\t\t\tcreated_at_ms: target.created_at_ms,\n\t\t},\n\t\tlegacy_history: subject.history.records.map((row) =>\n\t\t\tparseControllerHistoryRecord(row, base.coordinator_id),\n\t\t),\n\t\treviewed_weak_labels: subject.weakLabels,\n\t\t...(source.controller\n\t\t\t? receiptResult(source.controller, source.resolution, \"reused\", \"reused\")\n\t\t\t: {}),\n\t};\n}\n\n/** Internal review builder, not an HTTP authentication or account-mutation boundary.\n * Each call owns its reader and opaque snapshot; nothing is retained across requests.\n */\nexport class OwnerResolutionReviewOperations implements CoordinatorOwnerResolutionReviewStore {\n\tconstructor(\n\t\tprivate readonly backend: OwnerResolutionReviewBackend,\n\t\tprivate readonly clock: () => number = Date.now,\n\t) {}\n\n\tasync previewOwnerResolutionReview(\n\t\tselection: OwnerResolutionReviewSelection,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<OwnerResolutionReviewResult> {\n\t\treturn (await this.prepare(selection, config)).result;\n\t}\n\n\tasync confirmOwnerResolutionReview(\n\t\tselection: OwnerResolutionReviewConfirmation,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<OwnerResolutionReviewResult> {\n\t\tconst confirmed = capture(selection, [\n\t\t\t\"confirmOwnerResolutionDigest\",\n\t\t])?.confirmOwnerResolutionDigest;\n\t\tconst prepared = await this.prepare(selection, config);\n\t\tif (\n\t\t\t!isHash(confirmed) ||\n\t\t\t!prepared.review ||\n\t\t\t!prepared.evidence ||\n\t\t\tconfirmed !== prepared.result.owner_resolution_digest\n\t\t)\n\t\t\tthrow new OwnerResolutionReviewError(\"review_stale\");\n\t\ttry {\n\t\t\tconst applied = await commitReviewedOwnerResolution({\n\t\t\t\tbackend: this.backend,\n\t\t\t\tevidence: prepared.evidence,\n\t\t\t\treview: prepared.review,\n\t\t\t\tnow: new Date(this.clock()).toISOString(),\n\t\t\t});\n\t\t\treturn {\n\t\t\t\t...prepared.result,\n\t\t\t\tstate: \"ready\",\n\t\t\t\t...receiptResult(\n\t\t\t\t\tapplied.controller,\n\t\t\t\t\tapplied.resolution,\n\t\t\t\t\tapplied.controllerDisposition,\n\t\t\t\t\tapplied.resolutionDisposition,\n\t\t\t\t),\n\t\t\t};\n\t\t} catch {\n\t\t\tthrow new OwnerResolutionReviewError(\"owner_resolution_outcome_unknown\");\n\t\t}\n\t}\n\n\tprivate async prepare(input: unknown, config: unknown): Promise<PreparedReview> {\n\t\tconst selection = captureSelection(input);\n\t\tconst capturedConfig = captureAuthLinkConfig(config);\n\t\tconst result = baseResult(selection, capturedConfig);\n\t\tif (!selection || !capturedConfig?.enabled) {\n\t\t\tresult.reasons = [\n\t\t\t\t\"invalid_selection_or_config: select a current device and an enabled account configuration\",\n\t\t\t];\n\t\t\treturn { result };\n\t\t}\n\t\ttry {\n\t\t\tawait requireReviewSchema(this.backend);\n\t\t\treturn await this.prepareCaptured(selection, capturedConfig, result);\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tresult: {\n\t\t\t\t\t...result,\n\t\t\t\t\treasons: [\n\t\t\t\t\t\terror instanceof ReviewUnavailable\n\t\t\t\t\t\t\t? error.message\n\t\t\t\t\t\t\t: \"review_unavailable: ask the operator to inspect current ownership evidence\",\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t}\n\n\tprivate async captureSubject(\n\t\tselection: OwnerResolutionReviewSelection,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t): Promise<CapturedSubject> {\n\t\tconst { signer, enrollmentIdentityId } = await readResolutionRequester(this.backend, selection);\n\t\tconst history = await captureControllerHistory(\n\t\t\t{\n\t\t\t\tcoordinatorId: config.coordinatorId,\n\t\t\t\tdeviceId: signer.deviceId,\n\t\t\t\tpublicKey: signer.publicKey,\n\t\t\t\tfingerprint: signer.fingerprint,\n\t\t\t},\n\t\t\t<T>(sql: string, values: string[]) => this.backend.all<T>({ sql, values }),\n\t\t);\n\t\tconst evidence = new CoordinatorDeviceOwnershipEvidence(this.backend, config);\n\t\tconst collected = await evidence.collect({\n\t\t\tcanonicalOwnerId: selection.identityId,\n\t\t\tactualSigner: signer,\n\t\t\tverifiedHistory: history,\n\t\t});\n\t\tif (\n\t\t\tcollected.kind !== \"collected\" ||\n\t\t\t![\"compatible\", \"weak_label_review_required\"].includes(collected.decision)\n\t\t)\n\t\t\tthrow new ReviewUnavailable(\n\t\t\t\t\"ownership_unavailable: inspect current device revocations, owner conflicts and historical labels\",\n\t\t\t);\n\t\tconst ownershipEvidenceDigest = await evidence.reviewedEvidenceDigest(\n\t\t\tcollected.recheckSnapshot,\n\t\t);\n\t\tif (!ownershipEvidenceDigest)\n\t\t\tthrow new ReviewUnavailable(\"evidence_unavailable: preview ownership evidence again\");\n\t\treturn {\n\t\t\tsigner,\n\t\t\tenrollmentIdentityId,\n\t\t\thistory,\n\t\t\tevidence,\n\t\t\townershipEvidenceDigest,\n\t\t\tweakLabels: collected.weakLabels,\n\t\t\trecheckSnapshot: collected.recheckSnapshot,\n\t\t};\n\t}\n\n\tprivate async requireUnchangedCapture(\n\t\tselection: OwnerResolutionReviewSelection,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t\tsubject: CapturedSubject,\n\t\ttarget: ResolutionTarget,\n\t): Promise<void> {\n\t\tconst check = await this.backend.first<{ matches: number }>(\n\t\t\tsubject.evidence.prepareAtomicRecheck(subject.recheckSnapshot),\n\t\t);\n\t\tconst currentTarget = await readResolutionTarget(this.backend, selection, config);\n\t\tif (\n\t\t\tcheck?.matches !== 1 ||\n\t\t\tcurrentTarget.link_id !== target.link_id ||\n\t\t\tcurrentTarget.auth_config_revision !== target.auth_config_revision ||\n\t\t\tcurrentTarget.created_at_ms !== target.created_at_ms\n\t\t)\n\t\t\tthrow new ReviewUnavailable(\"review_changed: preview the current ownership evidence again\");\n\t\tawait requireReviewSchema(this.backend);\n\t}\n\n\tprivate async prepareCaptured(\n\t\tselection: OwnerResolutionReviewSelection,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t\tbase: OwnerResolutionReviewResult,\n\t): Promise<PreparedReview> {\n\t\tconst target = await readResolutionTarget(this.backend, selection, config);\n\t\tconst subject = await this.captureSubject(selection, config);\n\t\tconst { signer, history, evidence, ownershipEvidenceDigest } = subject;\n\t\tconst source = await readResolutionSource({\n\t\t\tbackend: this.backend,\n\t\t\tconfig,\n\t\t\tselection,\n\t\t\tsigner,\n\t\t\thistory,\n\t\t\tevidence,\n\t\t});\n\t\tconst invites = await readResolutionInvites(this.backend, signer);\n\t\tawait this.requireUnchangedCapture(selection, config, subject, target);\n\t\tconst digest = await sha([\n\t\t\t\"owner-resolution-review-v1\",\n\t\t\tPURPOSE,\n\t\t\tSCOPE,\n\t\t\tselection,\n\t\t\tconfig.coordinatorId,\n\t\t\tconfig.issuer,\n\t\t\tconfig.revision,\n\t\t\townershipEvidenceDigest,\n\t\t\ttarget,\n\t\t\tcontrollerHistoryDigestEvidence(history),\n\t\t\tsource.controller,\n\t\t\tsource.resolution,\n\t\t\tinvites,\n\t\t]);\n\t\tconst review = await buildInternalReview({\n\t\t\tselection,\n\t\t\tconfig,\n\t\t\tsubject,\n\t\t\tsource,\n\t\t\ttarget,\n\t\t\tinvites,\n\t\t\tdigest,\n\t\t});\n\t\treturn {\n\t\t\tevidence,\n\t\t\treview,\n\t\t\tresult: preparedResult(base, subject, target, source, digest),\n\t\t};\n\t}\n}\n","export interface CapturedPeerEnrollment {\n\treadonly group_id: string;\n\treadonly device_id: string;\n\treadonly public_key: string;\n\treadonly fingerprint: string;\n\treadonly identity_id: string | null;\n\treadonly enabled: number;\n}\n\nexport const CAPTURE_PEER_ENROLLMENTS_SQL = `SELECT group_id, device_id, public_key,\n\tfingerprint, identity_id, enabled FROM enrolled_devices\n\tWHERE group_id = ? AND enabled = 1 AND device_id != ?\n\tORDER BY device_id ASC`;\n\n/** Copy every primitive before async hashing can yield to enrollment changes. */\nexport function capturePeerEnrollments(\n\trows: readonly CapturedPeerEnrollment[],\n): CapturedPeerEnrollment[] {\n\treturn rows.map((row) => ({\n\t\tgroup_id: row.group_id,\n\t\tdevice_id: row.device_id,\n\t\tpublic_key: row.public_key,\n\t\tfingerprint: row.fingerprint,\n\t\tidentity_id: row.identity_id,\n\t\tenabled: row.enabled,\n\t}));\n}\n\n// One JSON parameter keeps the bind count constant even for large groups. Only\n// unchanged captured candidates survive; metadata and presence come from this read.\n// Keep captured rows first so each candidate seeks one enrollment instead of\n// rescanning the captured JSON for every enrolled device when statistics are absent.\nexport const READ_CURRENT_PEERS_SQL = `SELECT e.device_id, e.public_key, e.fingerprint,\n\te.display_name, p.addresses_json, p.last_seen_at, p.expires_at, p.capabilities_json\n\tFROM json_each(?) AS captured\n\tCROSS JOIN enrolled_devices AS e\n\t ON e.group_id = json_extract(captured.value, '$.group_id')\n\t AND e.device_id = json_extract(captured.value, '$.device_id')\n\t AND e.public_key = json_extract(captured.value, '$.public_key')\n\t AND e.fingerprint = json_extract(captured.value, '$.fingerprint')\n\t AND e.identity_id IS json_extract(captured.value, '$.identity_id')\n\t AND e.enabled = json_extract(captured.value, '$.enabled')\n\tLEFT JOIN presence_records AS p\n\t ON p.group_id = e.group_id AND p.device_id = e.device_id\n\tWHERE e.group_id = ? AND e.enabled = 1 AND e.device_id != ?\n\t AND NOT EXISTS (SELECT 1 FROM coordinator_device_revocations AS r WHERE\n\t (r.subject_kind = 'device_id' AND r.subject_value = e.device_id)\n\t OR (r.subject_kind = 'ed25519_key'\n\t AND r.subject_value = json_extract(captured.value, '$.keyId')))\n\tORDER BY e.device_id ASC`;\n\n/** A malformed backend response is not an empty discovery result. */\nexport function requirePeerDiscoveryRows(rows: unknown): Record<string, unknown>[] {\n\tif (!Array.isArray(rows)) throw new Error(\"peer_discovery_unavailable\");\n\tfor (const row of rows) requirePeerDiscoveryRow(row);\n\treturn rows;\n}\n\nfunction requirePeerDiscoveryRow(row: unknown): void {\n\tif (!row || typeof row !== \"object\" || Array.isArray(row)) {\n\t\tthrow new Error(\"peer_discovery_unavailable\");\n\t}\n\tconst record = row as Record<string, unknown>;\n\tfor (const field of [\"device_id\", \"public_key\", \"fingerprint\"]) {\n\t\tif (typeof record[field] !== \"string\") throw new Error(\"peer_discovery_unavailable\");\n\t}\n\tfor (const field of [\n\t\t\"display_name\",\n\t\t\"addresses_json\",\n\t\t\"last_seen_at\",\n\t\t\"expires_at\",\n\t\t\"capabilities_json\",\n\t]) {\n\t\tif (record[field] !== null && typeof record[field] !== \"string\") {\n\t\t\tthrow new Error(\"peer_discovery_unavailable\");\n\t\t}\n\t}\n}\n","import { DEVICE_REVOCATION_SUBJECT_EXISTS_SQL } from \"./coordinator-device-revocation.js\";\nimport type {\n\tCoordinatorConsumeProjectInviteInput,\n\tCoordinatorEnrollment,\n\tCoordinatorInvite,\n} from \"./coordinator-store-contract.js\";\n\nconst revocationSql = `${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}\n\t\tOR ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}`;\n// Pin the reviewed Project intent and the enrollment used to derive the seed key.\n// Every writer owns this guard: a zero-row batch statement does not stop its siblings.\nconst eligibilitySql = `EXISTS (SELECT 1 FROM coordinator_invites pi\n\t\tJOIN groups pg ON pg.group_id = pi.group_id AND pg.archived_at IS NULL\n\t\tWHERE pi.invite_id = ? AND pi.group_id = ? AND pi.revoked_at IS NULL\n\t\tAND pi.operation_id = ? AND pi.project_intent_json = ?\n\t\tAND pi.reviewed_project_set_digest IS ? AND pi.token_digest IS ?\n\t\tAND pi.project_summaries_json IS ? AND pi.inviter_actor_id IS ?\n\t\tAND pi.inviter_device_id IS ? AND pi.expires_at = ?\n\t\tAND ((? = 0 AND NOT EXISTS (SELECT 1 FROM enrolled_devices se\n\t\t\tWHERE se.group_id = pi.group_id AND se.device_id = pi.inviter_device_id))\n\t\t\tOR (? = 1 AND EXISTS (SELECT 1 FROM enrolled_devices se\n\t\t\t\tWHERE se.group_id = pi.group_id AND se.device_id = pi.inviter_device_id\n\t\t\t\tAND se.public_key = ? AND se.fingerprint = ? AND se.enabled = ?)))\n\t\tAND NOT EXISTS (SELECT 1 FROM enrolled_devices re\n\t\t\tWHERE re.group_id = pi.group_id AND re.device_id = ?\n\t\t\tAND (re.public_key <> ? OR re.fingerprint <> ?\n\t\t\t\tOR (re.identity_id IS NOT NULL AND re.identity_id <> ?)))\n\t\tAND NOT (${revocationSql}))`;\nconst bindingSql = `EXISTS (SELECT 1 FROM coordinator_invites bi\n\tWHERE bi.invite_id = ? AND bi.consumed_at IS NOT NULL\n\tAND bi.bound_device_id = ? AND bi.bound_public_key = ? AND bi.bound_fingerprint = ?\n\tAND bi.recipient_actor_id = ? AND bi.recipient_display_name = ?\n\tAND bi.recipient_device_display_name = ?)`;\n\nexport function projectInviteGuardEvidence(\n\tinvite: CoordinatorInvite,\n\topts: CoordinatorConsumeProjectInviteInput,\n\tinviter: CoordinatorEnrollment | null,\n\tkeyIds: { recipient: string | null; inviter: string | null },\n) {\n\tconst revocationValues = [\n\t\topts.deviceId,\n\t\tkeyIds.recipient,\n\t\tinvite.inviter_device_id ?? null,\n\t\tkeyIds.inviter,\n\t];\n\tconst eligibilityValues = [\n\t\tinvite.invite_id,\n\t\tinvite.group_id,\n\t\tinvite.operation_id,\n\t\tinvite.project_intent_json,\n\t\tinvite.reviewed_project_set_digest ?? null,\n\t\tinvite.token_digest ?? null,\n\t\tinvite.project_summaries_json ?? null,\n\t\tinvite.inviter_actor_id ?? null,\n\t\tinvite.inviter_device_id ?? null,\n\t\tinvite.expires_at,\n\t\tinviter ? 1 : 0,\n\t\tinviter ? 1 : 0,\n\t\tinviter?.public_key ?? null,\n\t\tinviter?.fingerprint ?? null,\n\t\tinviter?.enabled ?? null,\n\t\topts.deviceId,\n\t\topts.publicKey,\n\t\topts.fingerprint,\n\t\topts.recipientActorId,\n\t\t...revocationValues,\n\t];\n\treturn {\n\t\trevocationSql,\n\t\trevocationValues,\n\t\teligibilitySql,\n\t\teligibilityValues,\n\t\tboundEligibilitySql: `${eligibilitySql} AND ${bindingSql}`,\n\t\tboundEligibilityValues: [\n\t\t\t...eligibilityValues,\n\t\t\tinvite.invite_id,\n\t\t\topts.deviceId,\n\t\t\topts.publicKey,\n\t\t\topts.fingerprint,\n\t\t\topts.recipientActorId,\n\t\t\topts.recipientDisplayName,\n\t\t\topts.deviceDisplayName,\n\t\t],\n\t};\n}\n","import { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport {\n\ttype NegativeOwnerConsistency,\n\tprepareNegativeOwnerConsistency,\n\tprepareUnknownNamespaceOwnerConsistency,\n\twithNegativeOwnerWrite,\n} from \"./coordinator-owner-negative-consistency.js\";\nimport type { CoordinatorConsumeRecipientInviteInput } from \"./coordinator-store-contract.js\";\n\nexport function validateRecipientOwnerInput(input: CoordinatorConsumeRecipientInviteInput): void {\n\tif (\n\t\t!input.identityId ||\n\t\t!input.deviceId ||\n\t\t!input.publicKey ||\n\t\t!input.fingerprint ||\n\t\tinput.identityId !== input.identityId.trim() ||\n\t\tinput.deviceId !== input.deviceId.trim() ||\n\t\tinput.identityId.length > 256 ||\n\t\tinput.deviceId.length > 256 ||\n\t\t/[\\p{Cc}\\p{Cf}]/u.test(input.identityId) ||\n\t\t/[\\p{Cc}\\p{Cf}]/u.test(input.deviceId)\n\t)\n\t\tthrow new Error(\"invite_identity_conflict\");\n}\n\nexport function prepareRecipientOwnerConsistency(\n\tbackend: Pick<AuthLinkBackend, \"first\" | \"all\">,\n\tinput: CoordinatorConsumeRecipientInviteInput,\n): Promise<NegativeOwnerConsistency | null> {\n\tif (input.coordinatorId === undefined)\n\t\treturn prepareUnknownNamespaceOwnerConsistency(backend, input);\n\tif (!isAuthControllerId(input.coordinatorId)) return Promise.resolve(null);\n\treturn prepareNegativeOwnerConsistency(backend, {\n\t\tcoordinatorId: input.coordinatorId,\n\t\townerIdentityId: input.identityId,\n\t\tdeviceId: input.deviceId,\n\t\tpublicKey: input.publicKey,\n\t\tfingerprint: input.fingerprint,\n\t});\n}\n\nexport async function assertRecipientOwnerConsistency(\n\tbackend: Pick<AuthLinkBackend, \"first\">,\n\tpredicate: AuthLinkStatement | null,\n): Promise<void> {\n\tif (!predicate || (await backend.first<{ matches: number }>(predicate))?.matches !== 1)\n\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n}\n\nexport function recipientOwnerWriteSql(sql: string, predicate: AuthLinkStatement): string {\n\treturn withNegativeOwnerWrite({ sql, values: [] }, predicate).sql;\n}\n","import { connectionProfileColumns } from \"./coordinator-account-connection-session.js\";\nimport { CONNECTION_NOT_REVOKED_SQL } from \"./coordinator-account-connection-storage.js\";\nimport type { AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport type {\n\tCoordinatorAuthLinkConfig,\n\tCoordinatorAuthLinkSigner,\n} from \"./coordinator-auth-link-contract.js\";\nimport { authAccountLinkProvenanceSql } from \"./coordinator-auth-link-provenance.js\";\nimport { RESOLUTION_COLUMNS } from \"./coordinator-device-ownership-evidence-queries.js\";\nimport type { LegacyOwnerResolutionRecord } from \"./coordinator-legacy-owner-resolution-metadata.js\";\n\nexport interface ResolvedOwnerProfileRow {\n\tlink_count: number;\n\tlink_id: string | null;\n\tnot_revoked: number | null;\n\tvalid_link: string | null;\n\tdisplay_name: unknown;\n\temail: unknown;\n\temail_verified: unknown;\n\tpicture_url: unknown;\n}\n\n/** All thirteen original fields belong to the same source, including SQL NULLs. */\nconst sourceMatch = `c.attestation_id=r.source_attestation_id\n AND c.coordinator_id=r.coordinator_id AND c.identity_id=r.owner_identity_id\n AND c.group_id=r.source_group_id AND c.device_id=r.device_id\n AND c.public_key=r.source_public_key AND c.fingerprint=r.source_fingerprint\n AND c.review_receipt_id=r.source_review_receipt_id AND c.evidence_digest=r.source_evidence_digest\n AND c.enrollment_identity_id IS r.source_enrollment_identity_id\n AND c.revision=r.source_controller_revision AND c.created_at=r.source_created_at\n AND c.revoked_at IS NULL`;\n\nexport function resolvedOwnerProfileQuery(options: {\n\tsigner: CoordinatorAuthLinkSigner;\n\tconfig: CoordinatorAuthLinkConfig;\n\tresolution: LegacyOwnerResolutionRecord;\n\tkeyId: string;\n\trecheck: AuthLinkStatement;\n}): AuthLinkStatement {\n\tconst { signer, config, resolution, keyId, recheck } = options;\n\treturn {\n\t\tsql: `WITH resolved_input AS MATERIALIZED (SELECT ? AS coordinator_id,? AS owner_id,\n ? AS group_id,? AS device_id,? AS public_key,? AS fingerprint,? AS key_id,? AS issuer,? AS fact),\n resolved_evidence AS MATERIALIZED (${recheck.sql}),\n resolved_fact AS MATERIALIZED (\n SELECT r.resolution_id FROM resolved_input i\n JOIN coordinator_legacy_owner_resolutions r ON r.coordinator_id=i.coordinator_id\n AND r.device_id=i.device_id AND r.key_id=i.key_id AND r.owner_identity_id=i.owner_id\n JOIN coordinator_auth_controller_attestations c ON ${sourceMatch}\n WHERE ${RESOLUTION_COLUMNS.map((field) => `r.${field} IS json_extract(i.fact,'$.${field}')`).join(\" AND \")}),\n resolved_requester AS MATERIALIZED (\n SELECT 1 AS present FROM resolved_input i JOIN enrolled_devices e\n ON e.group_id=i.group_id AND e.device_id=i.device_id\n JOIN groups g ON g.group_id=e.group_id\n WHERE e.public_key=i.public_key AND e.fingerprint=i.fingerprint AND e.enabled=1\n AND g.archived_at IS NULL AND NOT EXISTS (\n SELECT 1 FROM coordinator_device_revocations v\n WHERE (v.subject_kind='device_id' AND v.subject_value=i.device_id)\n OR (v.subject_kind='ed25519_key' AND v.subject_value=i.key_id))),\n resolved_links AS MATERIALIZED (\n SELECT l.*,CASE WHEN ${CONNECTION_NOT_REVOKED_SQL} THEN 1 ELSE 0 END AS not_revoked\n FROM coordinator_auth_account_links l JOIN resolved_input i\n ON l.coordinator_id=i.coordinator_id AND l.identity_id=i.owner_id LIMIT 2),\n resolved_valid_links AS MATERIALIZED (\n SELECT l.* FROM resolved_links l JOIN resolved_input i ON l.issuer=i.issuer\n WHERE ${authAccountLinkProvenanceSql(\"l\", { connections: true })}),\n resolved_profiles AS MATERIALIZED (\n SELECT l.link_id,${connectionProfileColumns(\"p\")}\n FROM resolved_valid_links l LEFT JOIN coordinator_auth_account_profiles p\n ON p.coordinator_id=l.coordinator_id AND p.link_id=l.link_id\n LEFT JOIN coordinator_auth_link_profiles b ON b.coordinator_id=l.coordinator_id\n AND b.link_id=l.link_id AND b.attempt_id=l.attempt_id AND b.issuer=l.issuer\n AND b.subject=l.subject AND b.auth_config_revision=l.auth_config_revision\n WHERE l.not_revoked=1)\n SELECT (SELECT count(*) FROM resolved_links) AS link_count,l.link_id,l.not_revoked,\n v.link_id AS valid_link,p.display_name,p.email,p.email_verified,p.picture_url\n FROM resolved_fact f JOIN resolved_evidence evidence ON evidence.matches=1\n JOIN resolved_requester requester ON requester.present=1\n LEFT JOIN resolved_links l ON 1\n LEFT JOIN resolved_valid_links v ON v.link_id=l.link_id\n LEFT JOIN resolved_profiles p ON p.link_id=v.link_id LIMIT 1`,\n\t\tvalues: [\n\t\t\tconfig.coordinatorId,\n\t\t\tresolution.owner_identity_id,\n\t\t\tsigner.groupId,\n\t\t\tsigner.deviceId,\n\t\t\tsigner.publicKey,\n\t\t\tsigner.fingerprint,\n\t\t\tkeyId,\n\t\t\tconfig.issuer,\n\t\t\tJSON.stringify(resolution),\n\t\t\t...recheck.values,\n\t\t],\n\t};\n}\n","import { captureAuthAccountProfile } from \"./coordinator-auth-account-profile.js\";\nimport { projectAccountProfileView } from \"./coordinator-auth-browser-view.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport { captureControllerHistory } from \"./coordinator-auth-controller-history.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport type {\n\tCoordinatorAuthLinkConfig,\n\tCoordinatorAuthLinkSigner,\n} from \"./coordinator-auth-link-contract.js\";\nimport {\n\tcapture,\n\tcaptureAuthLinkConfig,\n\tcaptureAuthLinkSigner,\n\tisHash,\n} from \"./coordinator-auth-link-input.js\";\nimport { CoordinatorDeviceOwnershipEvidence } from \"./coordinator-device-ownership-evidence.js\";\nimport {\n\tBYTE_LIMIT,\n\tRESOLUTION_COLUMNS,\n\tROW_LIMIT,\n} from \"./coordinator-device-ownership-evidence-queries.js\";\nimport { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport {\n\tcaptureLegacyOwnerResolutionRecord,\n\ttype LegacyOwnerResolutionRecord,\n} from \"./coordinator-legacy-owner-resolution-metadata.js\";\nimport { requireReviewSchema } from \"./coordinator-owner-resolution-review-read.js\";\nimport {\n\ttype ResolvedOwnerProfileRow,\n\tresolvedOwnerProfileQuery,\n} from \"./coordinator-resolved-account-owner-status-query.js\";\n\ntype ResolvedOwnerBackend = AuthLinkBackend & {\n\tall<T>(statement: AuthLinkStatement): Promise<T[]>;\n};\ninterface SafeProfile {\n\tdisplayName?: string;\n\temail?: string;\n\tpictureUrl?: string;\n}\ninterface StatusSubject {\n\tversion: 1;\n\tcoordinatorId: string;\n\tgroupId: string;\n\tdeviceId: string;\n\tfingerprint: string;\n}\nexport type ResolvedAccountOwnerStatus = StatusSubject &\n\t(\n\t\t| {\n\t\t\t\tstate: \"owner_unconfirmed\";\n\t\t\t\townerIdentity: null;\n\t\t\t\tprofileState: \"unavailable\";\n\t\t\t\tprofile: null;\n\t\t }\n\t\t| {\n\t\t\t\tstate: \"owner_confirmed\";\n\t\t\t\townerIdentity: string;\n\t\t\t\tprofileState: \"linked\";\n\t\t\t\tprofile: SafeProfile;\n\t\t }\n\t\t| {\n\t\t\t\tstate: \"owner_confirmed\";\n\t\t\t\townerIdentity: string;\n\t\t\t\tprofileState: \"account_unlinked\" | \"unavailable\";\n\t\t\t\tprofile: null;\n\t\t }\n\t);\n\nexport class ResolvedAccountOwnerStatusUnavailableError extends Error {\n\tconstructor() {\n\t\tsuper(\"resolved_account_owner_status_unavailable\");\n\t}\n}\n\nexport interface ResolvedAccountOwnerReceiptReference {\n\tattestationId: string;\n\treviewReceiptId: string;\n\treviewEvidenceDigest: string;\n\tresolutionId: string;\n\tresolutionEvidenceDigest: string;\n}\nconst RECEIPT_FIELDS = [\n\t\"attestationId\",\n\t\"reviewReceiptId\",\n\t\"reviewEvidenceDigest\",\n\t\"resolutionId\",\n\t\"resolutionEvidenceDigest\",\n] as const;\n\n/** Capture data descriptors only; never evaluate submitted accessors. */\nexport function captureResolvedAccountOwnerReceiptReference(\n\tvalue: unknown,\n): ResolvedAccountOwnerReceiptReference | null {\n\ttry {\n\t\tconst receipt = capture(value, RECEIPT_FIELDS);\n\t\tif (\n\t\t\t!receipt ||\n\t\t\tReflect.ownKeys(value as object).length !== RECEIPT_FIELDS.length ||\n\t\t\t![Object.prototype, null].includes(Object.getPrototypeOf(value)) ||\n\t\t\t!isAuthControllerId(receipt.attestationId) ||\n\t\t\t!isAuthControllerId(receipt.reviewReceiptId) ||\n\t\t\t!isAuthControllerId(receipt.resolutionId) ||\n\t\t\t!isHash(receipt.reviewEvidenceDigest) ||\n\t\t\t!isHash(receipt.resolutionEvidenceDigest)\n\t\t)\n\t\t\treturn null;\n\t\treturn receipt as unknown as ResolvedAccountOwnerReceiptReference;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction captureExpectedReceipt(options: object): ResolvedAccountOwnerReceiptReference | undefined {\n\ttry {\n\t\tif (!(\"expectedReceipt\" in options)) return undefined;\n\t\tconst outer = capture(options, [\"expectedReceipt\"]);\n\t\tconst receipt = captureResolvedAccountOwnerReceiptReference(outer?.expectedReceipt);\n\t\tif (receipt) return receipt;\n\t} catch {\n\t\t// Malformed descriptors must not turn a constrained read into an ordinary read.\n\t}\n\tthrow new ResolvedAccountOwnerStatusUnavailableError();\n}\n\nfunction projectProfile(row: ResolvedOwnerProfileRow, issuer: string): SafeProfile | null {\n\tconst captured = captureAuthAccountProfile({\n\t\tdisplayName: row.display_name,\n\t\temail: row.email,\n\t\temailVerified: row.email_verified === 1,\n\t\tpictureUrl: row.picture_url,\n\t});\n\tif (!captured) return null;\n\tconst profile: SafeProfile = {};\n\tif (captured.displayName !== undefined) profile.displayName = captured.displayName;\n\tif (captured.emailVerified === true && captured.email !== undefined)\n\t\tprofile.email = captured.email;\n\tconst { pictureUrl } = projectAccountProfileView(captured, issuer);\n\tif (pictureUrl !== undefined) profile.pictureUrl = pictureUrl;\n\treturn profile;\n}\n\nfunction projectStatus(\n\tbase: Extract<ResolvedAccountOwnerStatus, { state: \"owner_unconfirmed\" }>,\n\trow: ResolvedOwnerProfileRow | null,\n\towner: string,\n\tissuer: string,\n): ResolvedAccountOwnerStatus {\n\tif (!row) return base;\n\tconst confirmed = { ...base, state: \"owner_confirmed\" as const, ownerIdentity: owner };\n\tif (row.link_count > 1) return { ...confirmed, profileState: \"unavailable\", profile: null };\n\tif (row.link_count === 0)\n\t\treturn { ...confirmed, profileState: \"account_unlinked\", profile: null };\n\tif (!row.valid_link) return { ...confirmed, profileState: \"unavailable\", profile: null };\n\tif (row.not_revoked === 0)\n\t\treturn { ...confirmed, profileState: \"account_unlinked\", profile: null };\n\tif (!projectProfile(row, issuer))\n\t\treturn { ...confirmed, profileState: \"unavailable\", profile: null };\n\t// This read always comes from a device that runs as another Identity, so it\n\t// holds no proof of its own for the owner. It learns that the owner's account\n\t// is linked, but never the name, email, or picture (ADR 0005 Section 8).\n\t// An empty profile keeps older Viewers' response checks working.\n\treturn { ...confirmed, profileState: \"linked\", profile: {} };\n}\n\nasync function readCandidates(\n\tbackend: ResolvedOwnerBackend,\n\tcoordinator: string,\n\tdevice: string,\n\tkey: string,\n\towner: string,\n\texpectedReceipt?: ResolvedAccountOwnerReceiptReference,\n) {\n\tconst receiptPredicate = expectedReceipt\n\t\t? ` AND source_attestation_id=? AND source_review_receipt_id=? AND source_evidence_digest=?\n AND resolution_id=? AND resolution_evidence_digest=?`\n\t\t: \"\";\n\tconst rows = await backend.all<unknown>({\n\t\tsql: `SELECT ${RESOLUTION_COLUMNS.join(\",\")} FROM coordinator_legacy_owner_resolutions\n WHERE coordinator_id=? AND device_id=? AND key_id=? AND owner_identity_id=?${receiptPredicate}\n ORDER BY created_at,resolution_id LIMIT ${ROW_LIMIT + 1}`,\n\t\tvalues: [\n\t\t\tcoordinator,\n\t\t\tdevice,\n\t\t\tkey,\n\t\t\towner,\n\t\t\t...(expectedReceipt ? RECEIPT_FIELDS.map((field) => expectedReceipt[field]) : []),\n\t\t],\n\t});\n\tif (\n\t\trows.length > ROW_LIMIT ||\n\t\tnew TextEncoder().encode(JSON.stringify(rows)).byteLength > BYTE_LIMIT\n\t)\n\t\tthrow new ResolvedAccountOwnerStatusUnavailableError();\n\tconst candidates: LegacyOwnerResolutionRecord[] = [];\n\tfor (const value of rows) {\n\t\tconst candidate = await captureLegacyOwnerResolutionRecord(value);\n\t\tif (candidate) candidates.push(candidate);\n\t}\n\treturn candidates;\n}\n\n/** Read-only display proof. The selected owner is a query, never an authority input. */\nexport class ResolvedAccountOwnerStatusOperations {\n\tconstructor(private readonly backend: ResolvedOwnerBackend) {}\n\n\tasync readResolvedAccountOwnerStatus(\n\t\tsigner: CoordinatorAuthLinkSigner,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t\toptions: { ownerIdentityId: string; expectedReceipt?: unknown },\n\t): Promise<ResolvedAccountOwnerStatus> {\n\t\tconst s = captureAuthLinkSigner(signer);\n\t\tconst c = captureAuthLinkConfig(config);\n\t\tconst selected = capture(options, [\"ownerIdentityId\"]);\n\t\tif (!s || !c?.enabled || !selected || !isAuthControllerId(selected.ownerIdentityId))\n\t\t\tthrow new ResolvedAccountOwnerStatusUnavailableError();\n\t\tconst expectedReceipt = captureExpectedReceipt(options);\n\t\tconst owner = selected.ownerIdentityId;\n\t\tconst base: Extract<ResolvedAccountOwnerStatus, { state: \"owner_unconfirmed\" }> = {\n\t\t\tversion: 1,\n\t\t\tcoordinatorId: c.coordinatorId,\n\t\t\tgroupId: s.groupId,\n\t\t\tdeviceId: s.deviceId,\n\t\t\tfingerprint: s.fingerprint,\n\t\t\tstate: \"owner_unconfirmed\",\n\t\t\townerIdentity: null,\n\t\t\tprofileState: \"unavailable\",\n\t\t\tprofile: null,\n\t\t};\n\t\ttry {\n\t\t\tawait requireReviewSchema(this.backend);\n\t\t\treturn await this.readCaptured(s, c, owner, base, expectedReceipt);\n\t\t} catch {\n\t\t\tthrow new ResolvedAccountOwnerStatusUnavailableError();\n\t\t}\n\t}\n\n\tprivate async readCaptured(\n\t\tsigner: CoordinatorAuthLinkSigner,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t\towner: string,\n\t\tbase: Extract<ResolvedAccountOwnerStatus, { state: \"owner_unconfirmed\" }>,\n\t\texpectedReceipt?: ResolvedAccountOwnerReceiptReference,\n\t): Promise<ResolvedAccountOwnerStatus> {\n\t\tconst keyId = await ed25519KeyIdForRevocation(signer.publicKey);\n\t\tif (!keyId) return base;\n\t\tconst candidates = await readCandidates(\n\t\t\tthis.backend,\n\t\t\tconfig.coordinatorId,\n\t\t\tsigner.deviceId,\n\t\t\tkeyId,\n\t\t\towner,\n\t\t\texpectedReceipt,\n\t\t);\n\t\tif (!candidates.length) return base;\n\t\tconst history = await captureControllerHistory(\n\t\t\t{ coordinatorId: config.coordinatorId, ...signer },\n\t\t\t<T>(sql: string, values: string[]) => this.backend.all<T>({ sql, values }),\n\t\t);\n\t\tconst evidence = new CoordinatorDeviceOwnershipEvidence(this.backend, config);\n\t\tconst collected = await evidence.collect({\n\t\t\tcanonicalOwnerId: owner,\n\t\t\tactualSigner: signer,\n\t\t\tverifiedHistory: history,\n\t\t});\n\t\tif (\n\t\t\tcollected.kind !== \"collected\" ||\n\t\t\t![\"compatible\", \"weak_label_review_required\"].includes(collected.decision)\n\t\t)\n\t\t\treturn base;\n\t\tfor (const resolution of candidates) {\n\t\t\tconst source = await evidence.verifyControllerSource({\n\t\t\t\tsourceRef: resolution,\n\t\t\t\texpectedOwnerId: owner,\n\t\t\t\tactualSigner: signer,\n\t\t\t});\n\t\t\tif (source.kind !== \"verified_controller_source\") continue;\n\t\t\tconst row = await this.backend.first<ResolvedOwnerProfileRow>(\n\t\t\t\tresolvedOwnerProfileQuery({\n\t\t\t\t\tsigner,\n\t\t\t\t\tconfig,\n\t\t\t\t\tresolution,\n\t\t\t\t\tkeyId,\n\t\t\t\t\trecheck: evidence.prepareAtomicRecheck(collected.recheckSnapshot),\n\t\t\t\t}),\n\t\t\t);\n\t\t\treturn projectStatus(base, row, owner, config.issuer);\n\t\t}\n\t\treturn base;\n\t}\n}\n","import type { CoordinatorAuthSchemaStore } from \"./coordinator-auth-schema.js\";\nimport type { CoordinatorDeviceRevocationStore } from \"./coordinator-device-revocation.js\";\nimport type {\n\tCoordinatorLegacyTeamCompletionManifestV1,\n\tCoordinatorLegacyTeamCompletionRecord,\n\tCoordinatorLegacyTeamCompletionWriteResult,\n} from \"./coordinator-legacy-team-completion.js\";\nimport type { RecipientReviewedIntentV1 } from \"./recipient-reviewed-intent.js\";\n\n/**\n * Normalize a caller-supplied invite expiry to a canonical UTC ISO-8601\n * (`...Z`) string. Invite lookups filter with a SQL `expires_at > ?` string\n * comparison against `new Date().toISOString()`, which is only correct when\n * stored values share that exact format — a `+00:00` offset or date-only value\n * would compare wrong. Shared by both coordinator store implementations.\n */\nexport function normalizeInviteExpiresAt(value: string): string {\n\tconst trimmed = value.trim();\n\tconst parsed = new Date(trimmed);\n\tif (!trimmed || Number.isNaN(parsed.getTime())) {\n\t\tthrow new Error(\"expiresAt must be a valid date.\");\n\t}\n\treturn parsed.toISOString();\n}\n\nexport interface CoordinatorGroup {\n\tgroup_id: string;\n\tdisplay_name: string | null;\n\tarchived_at: string | null;\n\tcreated_at: string;\n}\n\nexport interface CoordinatorEnrollment {\n\tgroup_id: string;\n\tdevice_id: string;\n\tpublic_key: string;\n\tfingerprint: string;\n\tidentity_id: string | null;\n\tdisplay_name: string | null;\n\tenabled: number;\n\tcreated_at: string;\n\t/** Authenticated presence expiry for this exact group/device enrollment. */\n\tpresence_expires_at?: string;\n\t/** Token-free capabilities from the same authenticated presence record. */\n\tpresence_capabilities?: Record<string, unknown>;\n\t/** The Identity this exact device key is bound to, when the coordinator holds one binding. */\n\townership_identity_id?: string;\n}\n\nexport interface CoordinatorInvite {\n\tinvite_id: string;\n\tgroup_id: string;\n\ttoken: string;\n\tpolicy: string;\n\texpires_at: string;\n\tcreated_at: string;\n\tcreated_by: string | null;\n\tteam_name_snapshot: string | null;\n\trevoked_at: string | null;\n\t/** Null/absent identifies a legacy enrollment invite, which grants no project intent by itself. */\n\toperation_id?: string | null;\n\t/** Digest reference only; the reviewed project set remains server-owned operation state. */\n\treviewed_project_set_digest?: string | null;\n\ttoken_digest?: string | null;\n\tinviter_actor_id?: string | null;\n\tinviter_display_name?: string | null;\n\tinviter_device_id?: string | null;\n\tpending_person_id?: string | null;\n\tproject_summaries_json?: string | null;\n\tproject_intent_json?: string | null;\n\tconsumed_at?: string | null;\n\tbound_device_id?: string | null;\n\tbound_public_key?: string | null;\n\tbound_fingerprint?: string | null;\n\trecipient_actor_id?: string | null;\n\trecipient_display_name?: string | null;\n\trecipient_device_display_name?: string | null;\n\ttrust_state?: string | null;\n\tbootstrap_grant_id?: string | null;\n\t/** Explicit lifecycle kind. Null is retained only for pre-migration rows. */\n\tinvite_kind?: CoordinatorInviteKind | null;\n\t/** Policy Team identifier for team-member invitations; never a coordinator group grant. */\n\tpolicy_team_id?: string | null;\n\t/** Identity fixed by an add-device invitation. */\n\ttarget_identity_id?: string | null;\n\t/** Opaque Identity minted by the coordinator for a Team-member invitation. */\n\tassigned_identity_id?: string | null;\n\t/** Digest of the server-owned preview reviewed before invitation creation. */\n\treviewed_preview_digest?: string | null;\n\t/** Canonical JSON for the inviter-reviewed access intent. */\n\treviewed_intent_json?: string | null;\n}\n\nexport type CoordinatorInviteKind =\n\t| \"legacy_enrollment\"\n\t| \"project_share\"\n\t| \"team_member\"\n\t| \"add_device\";\n\nexport type CoordinatorRecipientInviteKind = Extract<\n\tCoordinatorInviteKind,\n\t\"team_member\" | \"add_device\"\n>;\n\nconst COORDINATOR_ASSIGNED_IDENTITY_PATTERN = /^identity:[A-Za-z0-9_-]{18,24}$/u;\n\nexport function isCoordinatorAssignedIdentityId(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue === value.trim() &&\n\t\tCOORDINATOR_ASSIGNED_IDENTITY_PATTERN.test(value)\n\t);\n}\n\nexport function recipientInviteAuthoritativeIdentityId(value: {\n\tkind: CoordinatorRecipientInviteKind;\n\tassigned_identity_id?: unknown;\n\ttarget_identity_id?: unknown;\n}): string {\n\treturn String(\n\t\tvalue.kind === \"team_member\"\n\t\t\t? (value.assigned_identity_id ?? \"\")\n\t\t\t: (value.target_identity_id ?? \"\"),\n\t).trim();\n}\n\nexport interface CoordinatorProjectInviteSummary {\n\tdisplay_name: string;\n\texisting_memory_count: number;\n}\n\nexport interface CoordinatorProjectInviteAcceptance {\n\tstatus: \"accepted\" | \"existing\";\n\tinvite: CoordinatorInvite;\n\tenrollment: CoordinatorEnrollment;\n\tseed_enrollment: CoordinatorEnrollment | null;\n\tbootstrap_grant: CoordinatorBootstrapGrant | null;\n}\n\nexport type CoordinatorRecipientInviteInspection =\n\t| {\n\t\t\tkind: \"team_member\";\n\t\t\tinvite: CoordinatorInvite;\n\t\t\tpolicy_team_id: string;\n\t\t\tassigned_identity_id: string;\n\t\t\treviewed_preview_digest: string;\n\t\t\treviewed_intent?: RecipientReviewedIntentV1;\n\t\t\tbound: boolean;\n\t }\n\t| {\n\t\t\tkind: \"add_device\";\n\t\t\tinvite: CoordinatorInvite;\n\t\t\ttarget_identity_id: string;\n\t\t\treviewed_preview_digest: string;\n\t\t\treviewed_intent?: RecipientReviewedIntentV1;\n\t\t\tbound: boolean;\n\t };\n\nexport interface CoordinatorRecipientInviteAcceptance {\n\tstatus: \"accepted\" | \"existing\";\n\tinvite: CoordinatorInvite;\n\treviewed_intent?: RecipientReviewedIntentV1;\n\tbootstrap_grant?: CoordinatorBootstrapGrant | null;\n}\n\nexport interface CoordinatorJoinRequest {\n\trequest_id: string;\n\tgroup_id: string;\n\tdevice_id: string;\n\tpublic_key: string;\n\tfingerprint: string;\n\tdisplay_name: string | null;\n\ttoken: string;\n\tstatus: string;\n\tcreated_at: string;\n\treviewed_at: string | null;\n\treviewed_by: string | null;\n}\n\nexport interface CoordinatorJoinRequestReviewResult extends CoordinatorJoinRequest {\n\t_no_transition?: boolean;\n\tbootstrap_grant?: CoordinatorBootstrapGrant | null;\n}\n\nexport interface CoordinatorReviewJoinRequestBootstrapGrantInput {\n\tseedDeviceId: string;\n\texpiresAt: string;\n\tcreatedBy?: string | null;\n}\n\nexport interface CoordinatorPresenceRecord {\n\tgroup_id: string;\n\tdevice_id: string;\n\taddresses: string[];\n\texpires_at: string;\n}\n\nexport interface CoordinatorPeerRecord {\n\tdevice_id: string;\n\tpublic_key: string;\n\tfingerprint: string;\n\tdisplay_name: string | null;\n\taddresses: string[];\n\tlast_seen_at: string | null;\n\texpires_at: string | null;\n\tstale: boolean;\n\tcapabilities: Record<string, unknown>;\n}\n\nexport interface CoordinatorReciprocalApproval {\n\trequest_id: string;\n\tgroup_id: string;\n\trequesting_device_id: string;\n\trequested_device_id: string;\n\tstatus: string;\n\tcreated_at: string;\n\tresolved_at: string | null;\n}\n\nexport interface CoordinatorBootstrapGrant {\n\tgrant_id: string;\n\tgroup_id: string;\n\tseed_device_id: string;\n\tworker_device_id: string;\n\texpires_at: string;\n\tcreated_at: string;\n\tcreated_by: string | null;\n\trevoked_at: string | null;\n}\n\nexport interface CoordinatorBootstrapGrantAuthorizationInput {\n\tgrantId: string;\n\t/** Server-trusted time, not a caller-supplied expiry or clock. */\n\tnowMs: number;\n\texpectedSeed?: { groupId: string; deviceId: string; publicKey: string; fingerprint: string };\n}\n\nexport type CoordinatorBootstrapGrantAuthorizationError =\n\t| \"grant_not_found\"\n\t| \"seed_enrollment_not_found\"\n\t| \"worker_enrollment_not_found\"\n\t| \"grant_revoked\"\n\t| \"grant_expired\"\n\t| \"group_archived\"\n\t| \"device_revoked\"\n\t| \"bootstrap_authorization_unavailable\";\n\n/** A current read snapshot, not a permanent authorization capability. */\nexport type CoordinatorBootstrapGrantAuthorizationResult =\n\t| {\n\t\t\tkind: \"authorized\";\n\t\t\tauthorizationVersion: 1;\n\t\t\tgrant: CoordinatorBootstrapGrant;\n\t\t\tseedEnrollment: CoordinatorEnrollment;\n\t\t\tworkerEnrollment: CoordinatorEnrollment;\n\t }\n\t| { kind: \"rejected\"; error: CoordinatorBootstrapGrantAuthorizationError };\n\nexport interface CoordinatorScope {\n\tscope_id: string;\n\tlabel: string;\n\tkind: string;\n\tauthority_type: string;\n\tcoordinator_id: string | null;\n\tgroup_id: string | null;\n\tmanifest_issuer_device_id: string | null;\n\tmembership_epoch: number;\n\tmanifest_hash: string | null;\n\tstatus: string;\n\tcreated_at: string;\n\tupdated_at: string;\n}\n\nexport interface CoordinatorScopeMembership {\n\tscope_id: string;\n\tdevice_id: string;\n\trole: string;\n\tstatus: string;\n\tmembership_epoch: number;\n\tcoordinator_id: string | null;\n\tgroup_id: string | null;\n\tmanifest_issuer_device_id: string | null;\n\tmanifest_hash: string | null;\n\tsigned_manifest_json: string | null;\n\tupdated_at: string;\n}\n\nexport type CoordinatorScopeMembershipAuditAction = \"grant\" | \"revoke\";\n\nexport interface CoordinatorScopeAuthorizationInput {\n\tgroupId: string;\n\tscopeId: string;\n}\n\n/** Current storage snapshot only; neither account-session proof nor a permanent permission. */\nexport type CoordinatorScopeAuthorizationResult =\n\t| {\n\t\t\tkind: \"authorized\";\n\t\t\tauthorizationVersion: 1;\n\t\t\tscope: CoordinatorScope;\n\t\t\tmembers: Array<{\n\t\t\t\tmembership: CoordinatorScopeMembership;\n\t\t\t\tenrollment: CoordinatorEnrollment;\n\t\t\t\tkeyId: string;\n\t\t\t}>;\n\t }\n\t| {\n\t\t\tkind: \"rejected\";\n\t\t\terror:\n\t\t\t\t| \"scope_not_found\"\n\t\t\t\t| \"scope_inactive\"\n\t\t\t\t| \"scope_source_mismatch\"\n\t\t\t\t| \"group_archived\"\n\t\t\t\t| \"scope_authorization_unavailable\";\n\t };\n\nexport interface CoordinatorScopeMembershipAuditEvent {\n\tevent_id: number;\n\teffect_id: string | null;\n\taction: CoordinatorScopeMembershipAuditAction;\n\tscope_id: string;\n\tdevice_id: string;\n\trole: string | null;\n\tstatus: string;\n\tmembership_epoch: number;\n\tprevious_role: string | null;\n\tprevious_status: string | null;\n\tprevious_membership_epoch: number | null;\n\tcoordinator_id: string | null;\n\tgroup_id: string | null;\n\tactor_type: string | null;\n\tactor_id: string | null;\n\tmanifest_hash: string | null;\n\tcreated_at: string;\n}\n\nexport interface CoordinatorEnrollDeviceInput {\n\tdeviceId: string;\n\tfingerprint: string;\n\tpublicKey: string;\n\tdisplayName?: string | null;\n\t/** Null or omitted means the enrollment has no authoritative issuance binding. */\n\tidentityId?: string | null;\n}\n\nexport interface CoordinatorCreateInviteInput {\n\tgroupId: string;\n\tpolicy: string;\n\texpiresAt: string;\n\tcreatedBy?: string | null;\n\toperationId?: string | null;\n\treviewedProjectSetDigest?: string | null;\n\tinviterActorId?: string | null;\n\tinviterDisplayName?: string | null;\n\tinviterDeviceId?: string | null;\n\tpendingPersonId?: string | null;\n\tprojectSummaries?: CoordinatorProjectInviteSummary[] | null;\n\tprojectIntent?: Array<CoordinatorProjectInviteSummary & { canonical_identity: string }> | null;\n\tinviteKind?: CoordinatorInviteKind | null;\n\tpolicyTeamId?: string | null;\n\ttargetIdentityId?: string | null;\n\treviewedPreviewDigest?: string | null;\n\treviewedIntent?: unknown;\n}\n\nexport interface CoordinatorConsumeProjectInviteInput {\n\ttoken: string;\n\toperationId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n\trecipientActorId: string;\n\trecipientDisplayName: string;\n\tdeviceDisplayName: string;\n\t/** Runtime-authoritative timestamp used for expiry, binding, and grant creation. */\n\tnow: string;\n}\n\nexport interface CoordinatorInspectRecipientInviteInput {\n\ttoken: string;\n\tnow: string;\n}\n\nexport interface CoordinatorConsumeRecipientInviteInput {\n\t/** Internal server-config namespace only; never accepted from invite HTTP JSON. */\n\tcoordinatorId?: string;\n\ttoken: string;\n\tinviteKind: CoordinatorRecipientInviteKind;\n\tidentityId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n\trecipientDisplayName?: string | null;\n\tdeviceDisplayName?: string | null;\n\t/** Runtime-authoritative timestamp used for expiry and binding. */\n\tnow: string;\n}\n\nexport interface CoordinatorCreateJoinRequestInput {\n\tgroupId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n\tdisplayName?: string | null;\n\ttoken: string;\n}\n\nexport interface CoordinatorReviewJoinRequestInput {\n\trequestId: string;\n\tapproved: boolean;\n\treviewedBy?: string | null;\n\tbootstrapGrant?: CoordinatorReviewJoinRequestBootstrapGrantInput | null;\n}\n\nexport interface CoordinatorUpsertPresenceInput {\n\tgroupId: string;\n\tdeviceId: string;\n\taddresses: string[];\n\tttlS: number;\n\tcapabilities?: Record<string, unknown> | null;\n}\n\nexport interface CoordinatorCreateReciprocalApprovalInput {\n\tgroupId: string;\n\trequestingDeviceId: string;\n\trequestedDeviceId: string;\n\t/** Complete only this exact pending request in the reverse direction. */\n\texpectedIncomingRequestId?: string;\n}\n\nexport const RECIPROCAL_APPROVAL_REQUEST_CHANGED = \"reciprocal_approval_request_changed\" as const;\n\nexport class CoordinatorReciprocalApprovalRequestChangedError extends Error {\n\treadonly code = RECIPROCAL_APPROVAL_REQUEST_CHANGED;\n\n\tconstructor() {\n\t\tsuper(RECIPROCAL_APPROVAL_REQUEST_CHANGED);\n\t\tthis.name = \"CoordinatorReciprocalApprovalRequestChangedError\";\n\t}\n}\n\nexport interface CoordinatorCreateBootstrapGrantInput {\n\tgroupId: string;\n\tseedDeviceId: string;\n\tworkerDeviceId: string;\n\texpiresAt: string;\n\tcreatedBy?: string | null;\n}\n\nexport interface CoordinatorCreateScopeInput {\n\tscopeId: string;\n\tlabel: string;\n\tkind?: string | null;\n\tauthorityType?: string | null;\n\tcoordinatorId?: string | null;\n\tgroupId?: string | null;\n\tmanifestIssuerDeviceId?: string | null;\n\tmembershipEpoch?: number | null;\n\tmanifestHash?: string | null;\n\tstatus?: string | null;\n}\n\nexport interface CoordinatorUpdateScopeInput {\n\t/** Internal sharing-domain identifier (`scope_id`). */\n\tscopeId: string;\n\t/** User-facing Sharing domain label. Omitted fields keep existing metadata. */\n\tlabel?: string | null;\n\tkind?: string | null;\n\tauthorityType?: string | null;\n\tcoordinatorId?: string | null;\n\tgroupId?: string | null;\n\tmanifestIssuerDeviceId?: string | null;\n\tmembershipEpoch?: number | null;\n\tmanifestHash?: string | null;\n\tstatus?: string | null;\n}\n\nexport interface CoordinatorListScopesInput {\n\tcoordinatorId?: string | null;\n\tgroupId?: string | null;\n\tstatus?: string | null;\n\tincludeInactive?: boolean;\n}\n\nexport interface CoordinatorGrantScopeMembershipInput {\n\teffectId: string;\n\tscopeId: string;\n\tdeviceId: string;\n\trole?: string | null;\n\tmembershipEpoch?: number | null;\n\t/** Optional assertion; persisted authority is derived from the referenced scope. */\n\tcoordinatorId?: string | null;\n\t/** Optional assertion; persisted authority is derived from the referenced scope. */\n\tgroupId?: string | null;\n\tmanifestIssuerDeviceId?: string | null;\n\tmanifestHash?: string | null;\n\tsignedManifestJson?: string | null;\n\tactorType?: string | null;\n\tactorId?: string | null;\n}\n\nexport interface CoordinatorRevokeScopeMembershipInput {\n\teffectId: string;\n\tscopeId: string;\n\tdeviceId: string;\n\t/** Optional assertion; persisted authority is derived from the referenced scope. */\n\tgroupId?: string | null;\n\tmembershipEpoch?: number | null;\n\tmanifestHash?: string | null;\n\tsignedManifestJson?: string | null;\n\tactorType?: string | null;\n\tactorId?: string | null;\n}\n\nexport interface CoordinatorListScopeMembershipAuditInput {\n\tscopeId: string;\n\tdeviceId?: string | null;\n\tlimit?: number | null;\n}\n\nexport interface CoordinatorListReciprocalApprovalsInput {\n\tgroupId: string;\n\tdeviceId: string;\n\tdirection: \"incoming\" | \"outgoing\";\n\tstatus?: string;\n}\n\nexport interface CoordinatorStore\n\textends CoordinatorDeviceRevocationStore,\n\t\tPartial<CoordinatorAuthSchemaStore> {\n\tclose(): Promise<void>;\n\tcreateGroup(groupId: string, displayName?: string | null): Promise<void>;\n\tgetGroup(groupId: string): Promise<CoordinatorGroup | null>;\n\tlistGroups(includeArchived?: boolean): Promise<CoordinatorGroup[]>;\n\trenameGroup(groupId: string, displayName: string): Promise<boolean>;\n\tarchiveGroup(groupId: string, archivedAt?: string): Promise<boolean>;\n\tunarchiveGroup(groupId: string): Promise<boolean>;\n\tenrollDevice(groupId: string, opts: CoordinatorEnrollDeviceInput): Promise<void>;\n\tlistEnrolledDevices(groupId: string, includeDisabled?: boolean): Promise<CoordinatorEnrollment[]>;\n\tgetEnrollment(\n\t\tgroupId: string,\n\t\tdeviceId: string,\n\t\tincludeDisabled?: boolean,\n\t): Promise<CoordinatorEnrollment | null>;\n\trenameDevice(groupId: string, deviceId: string, displayName: string): Promise<boolean>;\n\tsetDeviceEnabled(groupId: string, deviceId: string, enabled: boolean): Promise<boolean>;\n\tremoveDevice(groupId: string, deviceId: string): Promise<boolean>;\n\trecordNonce(deviceId: string, nonce: string, createdAt: string): Promise<boolean>;\n\tcleanupNonces(cutoff: string): Promise<void>;\n\tcreateInvite(opts: CoordinatorCreateInviteInput): Promise<CoordinatorInvite>;\n\tgetInviteByOperationId(groupId: string, operationId: string): Promise<CoordinatorInvite | null>;\n\tgetInviteByToken(token: string): Promise<CoordinatorInvite | null>;\n\tgetInviteByTokenForInspection(token: string): Promise<CoordinatorInvite | null>;\n\tinspectRecipientInvite(\n\t\topts: CoordinatorInspectRecipientInviteInput,\n\t): Promise<CoordinatorRecipientInviteInspection | null>;\n\tconsumeProjectInvite(\n\t\topts: CoordinatorConsumeProjectInviteInput,\n\t): Promise<CoordinatorProjectInviteAcceptance>;\n\tconsumeRecipientInvite(\n\t\topts: CoordinatorConsumeRecipientInviteInput,\n\t): Promise<CoordinatorRecipientInviteAcceptance>;\n\tlistInvites(groupId: string): Promise<CoordinatorInvite[]>;\n\tcreateJoinRequest(opts: CoordinatorCreateJoinRequestInput): Promise<CoordinatorJoinRequest>;\n\tlistJoinRequests(groupId: string, status?: string): Promise<CoordinatorJoinRequest[]>;\n\treviewJoinRequest(\n\t\topts: CoordinatorReviewJoinRequestInput,\n\t): Promise<CoordinatorJoinRequestReviewResult | null>;\n\tcreateReciprocalApproval(\n\t\topts: CoordinatorCreateReciprocalApprovalInput,\n\t): Promise<CoordinatorReciprocalApproval>;\n\tcreateBootstrapGrant(\n\t\topts: CoordinatorCreateBootstrapGrantInput,\n\t): Promise<CoordinatorBootstrapGrant>;\n\tcreateScope(opts: CoordinatorCreateScopeInput): Promise<CoordinatorScope>;\n\tupdateScope(opts: CoordinatorUpdateScopeInput): Promise<CoordinatorScope | null>;\n\tlistScopes(opts?: CoordinatorListScopesInput): Promise<CoordinatorScope[]>;\n\tgetScopeAuthorization(\n\t\tinput: CoordinatorScopeAuthorizationInput,\n\t): Promise<CoordinatorScopeAuthorizationResult>;\n\tgrantScopeMembership(\n\t\topts: CoordinatorGrantScopeMembershipInput,\n\t): Promise<CoordinatorScopeMembership>;\n\trevokeScopeMembership(opts: CoordinatorRevokeScopeMembershipInput): Promise<boolean>;\n\tlistScopeMemberships(\n\t\tscopeId: string,\n\t\tincludeRevoked?: boolean,\n\t): Promise<CoordinatorScopeMembership[]>;\n\t/**\n\t * List one device's memberships across every scope, ordered by scope_id.\n\t *\n\t * Answers \"which scopes is this device in\" with a single indexed lookup,\n\t * rather than reading every member of every scope one scope at a time.\n\t */\n\tlistDeviceScopeMemberships(\n\t\tdeviceId: string,\n\t\tincludeRevoked?: boolean,\n\t): Promise<CoordinatorScopeMembership[]>;\n\tlistScopeMembershipAuditEvents(\n\t\topts: CoordinatorListScopeMembershipAuditInput,\n\t): Promise<CoordinatorScopeMembershipAuditEvent[]>;\n\tgetBootstrapGrant(grantId: string): Promise<CoordinatorBootstrapGrant | null>;\n\tgetBootstrapGrantAuthorization(\n\t\tinput: CoordinatorBootstrapGrantAuthorizationInput,\n\t): Promise<CoordinatorBootstrapGrantAuthorizationResult>;\n\tlistBootstrapGrants(groupId: string): Promise<CoordinatorBootstrapGrant[]>;\n\trevokeBootstrapGrant(grantId: string, revokedAt?: string): Promise<boolean>;\n\tlistReciprocalApprovals(\n\t\topts: CoordinatorListReciprocalApprovalsInput,\n\t): Promise<CoordinatorReciprocalApproval[]>;\n\tcreateLegacyTeamCompletion(\n\t\tgroupId: string,\n\t\tmanifest: CoordinatorLegacyTeamCompletionManifestV1,\n\t): Promise<CoordinatorLegacyTeamCompletionWriteResult>;\n\tgetLegacyTeamCompletion(\n\t\tgroupId: string,\n\t\tcandidateRef: string,\n\t): Promise<CoordinatorLegacyTeamCompletionManifestV1 | null>;\n\tlistLegacyTeamCompletions(groupIds: string[]): Promise<CoordinatorLegacyTeamCompletionRecord[]>;\n\tupsertPresence(opts: CoordinatorUpsertPresenceInput): Promise<CoordinatorPresenceRecord>;\n\tlistGroupPeers(groupId: string, requestingDeviceId: string): Promise<CoordinatorPeerRecord[]>;\n}\n\nexport interface CoordinatorBootstrapGrantVerification {\n\tauthorization_version: 1;\n\tgrant: CoordinatorBootstrapGrant;\n\tseed_enrollment: CoordinatorEnrollment;\n\tworker_enrollment: CoordinatorEnrollment;\n}\n","const MAX_IDENTITY_DISPLAY_LENGTH = 120;\n// Keep machine-shaped cases synchronized with ui/src/lib/identity-presentation.ts.\nconst UUID_NAME = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu;\nconst MACHINE_PREFIX_NAME = /^(?:actor|device|identity|local):\\S+$/iu;\nconst MACHINE_SLUG_NAME = /^(?:actor|device|identity)[_-][a-z0-9][a-z0-9._:-]{4,}$/iu;\nconst PENDING_PERSON_NAME = /^pending[_-]\\S+$/iu;\nconst HEX_HOSTNAME = /^[a-f0-9]{12,64}$/iu;\nconst HOSTNAME_NAME =\n\t/^(?=.{1,253}$)(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.){2,}[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?|[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.local)$/iu;\n\nexport interface ProjectInviteSummary {\n\tdisplay_name: string;\n\texisting_memory_count: number;\n}\n\nexport function normalizeIdentityDisplayName(value: string, field: string): string {\n\tif ([...value].some((character) => /[\\p{Cc}\\p{Cf}]/u.test(character))) {\n\t\tthrow new Error(`${field}_invalid`);\n\t}\n\tconst normalized = value.replace(/\\s+/gu, \" \").trim();\n\tif (!normalized) throw new Error(`${field}_required`);\n\tif ([...normalized].length > MAX_IDENTITY_DISPLAY_LENGTH) {\n\t\tthrow new Error(`${field}_too_long`);\n\t}\n\treturn normalized;\n}\n\nexport function isHumanPresentationName(value: unknown): boolean {\n\tif (typeof value !== \"string\") return false;\n\tlet normalized: string;\n\ttry {\n\t\tnormalized = normalizeIdentityDisplayName(value, \"display_name\");\n\t} catch {\n\t\treturn false;\n\t}\n\treturn ![\n\t\tUUID_NAME,\n\t\tMACHINE_PREFIX_NAME,\n\t\tMACHINE_SLUG_NAME,\n\t\tPENDING_PERSON_NAME,\n\t\tHEX_HOSTNAME,\n\t].some((pattern) => pattern.test(normalized));\n}\n\nexport function normalizeHumanPresentationName(value: string, field: string): string {\n\tconst normalized = normalizeIdentityDisplayName(value, field);\n\tif (!isHumanPresentationName(normalized)) throw new Error(`${field}_invalid`);\n\treturn normalized;\n}\n\nexport function normalizeDeviceDisplayName(value: string, field: string): string {\n\tconst normalized = normalizeIdentityDisplayName(value, field);\n\tif (!HOSTNAME_NAME.test(normalized) && !isHumanPresentationName(normalized)) {\n\t\tthrow new Error(`${field}_invalid`);\n\t}\n\treturn normalized;\n}\n\nexport function normalizeDeviceNameHint(value: string | null | undefined): string | null {\n\tconst candidate = String(value ?? \"\").trim();\n\tconst raw = candidate.replace(/\\.local$/iu, \"\");\n\tif (!raw) return null;\n\tconst normalized = HOSTNAME_NAME.test(candidate) ? raw : raw.replace(/[-_]+/gu, \" \");\n\treturn normalizeDeviceDisplayName(normalized, \"device_display_name\");\n}\n\nexport function friendlyDeviceName(input: {\n\texplicitName?: string | null;\n\tosName?: string | null;\n\tcoordinatorName?: string | null;\n\tfallbackSeed?: string | null;\n}): string {\n\tfor (const candidate of [input.explicitName, input.osName, input.coordinatorName]) {\n\t\tconst candidateText = String(candidate ?? \"\").trim();\n\t\tconst raw = candidateText.replace(/\\.local$/iu, \"\");\n\t\t// Classify before separator normalization so UUIDs and machine slugs cannot\n\t\t// be disguised as human labels by replacing hyphens or underscores.\n\t\tif (HOSTNAME_NAME.test(candidateText)) {\n\t\t\ttry {\n\t\t\t\tconst normalized = normalizeDeviceNameHint(candidateText);\n\t\t\t\tif (normalized) return normalized;\n\t\t\t} catch {\n\t\t\t\t// Unusable automatic hints must degrade to the generated fallback.\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (!raw || !isHumanPresentationName(raw)) continue;\n\t\ttry {\n\t\t\tconst normalized = normalizeDeviceNameHint(candidate);\n\t\t\tif (normalized && isHumanPresentationName(normalized)) return normalized;\n\t\t} catch {\n\t\t\t// Unusable automatic hints must degrade to the generated fallback.\n\t\t}\n\t}\n\tconst seed = String(input.fallbackSeed ?? \"\")\n\t\t.replace(/[^a-z0-9]/giu, \"\")\n\t\t.slice(0, 6);\n\treturn seed ? `Codemem device ${seed}` : \"Codemem device\";\n}\n\nexport function normalizeProjectInviteSummaries(value: unknown): ProjectInviteSummary[] {\n\tif (!Array.isArray(value) || value.length === 0 || value.length > 100) {\n\t\tthrow new Error(\"project_summaries_invalid\");\n\t}\n\treturn value.map((item) => {\n\t\tif (!item || typeof item !== \"object\" || Array.isArray(item)) {\n\t\t\tthrow new Error(\"project_summaries_invalid\");\n\t\t}\n\t\tconst record = item as Record<string, unknown>;\n\t\tif (\n\t\t\t!Number.isSafeInteger(record.existing_memory_count) ||\n\t\t\tNumber(record.existing_memory_count) < 0\n\t\t) {\n\t\t\tthrow new Error(\"project_summaries_invalid\");\n\t\t}\n\t\treturn {\n\t\t\tdisplay_name: normalizeIdentityDisplayName(String(record.display_name ?? \"\"), \"project_name\"),\n\t\t\texisting_memory_count: Number(record.existing_memory_count),\n\t\t};\n\t});\n}\n","import { normalizeIdentityDisplayName } from \"./project-invite-identity.js\";\n\nexport const RECIPIENT_REVIEWED_INTENT_VERSION = 1 as const;\n\nexport type RecipientReviewedIntentProjectSourceV1 =\n\t| { kind: \"direct\" }\n\t| { kind: \"team\"; teamId: string; displayName: string };\n\nexport interface RecipientReviewedIntentProjectV1 {\n\tcanonicalProjectIdentity: string;\n\tdisplayName: string;\n\texistingMemoryCount: number;\n\tfutureMemoriesShared: true;\n\tsources: RecipientReviewedIntentProjectSourceV1[];\n}\n\nexport interface RecipientReviewedIntentExcludedProjectV1 {\n\tcanonicalProjectIdentity: string;\n\tdisplayName: string;\n\texistingMemoryCount: number;\n}\n\ninterface RecipientReviewedIntentBaseV1 {\n\tversion: 1;\n\tprojects: RecipientReviewedIntentProjectV1[];\n\texcludedProjects: RecipientReviewedIntentExcludedProjectV1[];\n}\n\nexport type RecipientReviewedIntentV1 =\n\t| (RecipientReviewedIntentBaseV1 & {\n\t\t\tjourney: \"team\";\n\t\t\tteam: { teamId: string; displayName: string; futureProjectsInherit: true };\n\t })\n\t| (RecipientReviewedIntentBaseV1 & {\n\t\t\tjourney: \"add_device\";\n\t\t\ttargetIdentity: { identityId: string; displayName: string };\n\t });\n\nexport type RecipientReviewedIntentTargetV1 =\n\t| { kind: \"team_member\"; policyTeamId: string }\n\t| { kind: \"add_device\"; targetIdentityId: string };\n\nexport class RecipientReviewedIntentError extends Error {\n\treadonly code: \"recipient_reviewed_intent_invalid\" | \"recipient_invite_intent_mismatch\";\n\n\tconstructor(code: RecipientReviewedIntentError[\"code\"]) {\n\t\tsuper(code);\n\t\tthis.name = \"RecipientReviewedIntentError\";\n\t\tthis.code = code;\n\t}\n}\n\nconst CONTROL_CHARACTER = /[\\p{Cc}\\p{Cf}]/u;\nconst MAX_PROJECTS = 100;\nconst MAX_CANONICAL_BYTES = 64 * 1024;\n\nfunction invalid(): never {\n\tthrow new RecipientReviewedIntentError(\"recipient_reviewed_intent_invalid\");\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) invalid();\n\treturn value as Record<string, unknown>;\n}\n\nfunction assertKeys(value: Record<string, unknown>, keys: readonly string[]): void {\n\tif (Object.keys(value).some((key) => !keys.includes(key))) invalid();\n}\n\nfunction strictText(value: unknown, maxLength: number): string {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\t!value ||\n\t\tvalue !== value.trim() ||\n\t\tvalue.length > maxLength ||\n\t\tCONTROL_CHARACTER.test(value)\n\t) {\n\t\tinvalid();\n\t}\n\treturn value;\n}\n\nfunction displayName(value: unknown): string {\n\tif (typeof value !== \"string\" || CONTROL_CHARACTER.test(value)) invalid();\n\tconst normalized = value.trim().replace(/\\s+/gu, \" \");\n\tif (!normalized || normalized.length > 256) invalid();\n\treturn normalized;\n}\n\nfunction identityDisplayName(value: unknown): string {\n\tif (typeof value !== \"string\") invalid();\n\ttry {\n\t\treturn normalizeIdentityDisplayName(value, \"identity_display_name\");\n\t} catch {\n\t\treturn invalid();\n\t}\n}\n\nfunction memoryCount(value: unknown): number {\n\tif (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 0) invalid();\n\treturn value;\n}\n\nfunction compareText(left: string, right: string): number {\n\treturn left < right ? -1 : left > right ? 1 : 0;\n}\n\nfunction sourceKey(source: RecipientReviewedIntentProjectSourceV1): string {\n\treturn source.kind === \"direct\" ? \"direct\" : `team\\u0000${source.teamId}`;\n}\n\nfunction normalizeSource(value: unknown): RecipientReviewedIntentProjectSourceV1 {\n\tconst input = record(value);\n\tif (input.kind === \"direct\") {\n\t\tassertKeys(input, [\"kind\"]);\n\t\treturn { kind: \"direct\" };\n\t}\n\tif (input.kind !== \"team\") invalid();\n\tassertKeys(input, [\"kind\", \"teamId\", \"displayName\"]);\n\treturn {\n\t\tkind: \"team\",\n\t\tteamId: strictText(input.teamId, 256),\n\t\tdisplayName: displayName(input.displayName),\n\t};\n}\n\nfunction normalizeProject(value: unknown): RecipientReviewedIntentProjectV1 {\n\tconst input = record(value);\n\tassertKeys(input, [\n\t\t\"canonicalProjectIdentity\",\n\t\t\"displayName\",\n\t\t\"existingMemoryCount\",\n\t\t\"futureMemoriesShared\",\n\t\t\"sources\",\n\t]);\n\tif (\n\t\tinput.futureMemoriesShared !== true ||\n\t\t!Array.isArray(input.sources) ||\n\t\t!input.sources.length\n\t) {\n\t\tinvalid();\n\t}\n\tconst sources = input.sources\n\t\t.map(normalizeSource)\n\t\t.toSorted((left, right) => compareText(sourceKey(left), sourceKey(right)));\n\tif (new Set(sources.map(sourceKey)).size !== sources.length) invalid();\n\treturn {\n\t\tcanonicalProjectIdentity: strictText(input.canonicalProjectIdentity, 512),\n\t\tdisplayName: displayName(input.displayName),\n\t\texistingMemoryCount: memoryCount(input.existingMemoryCount),\n\t\tfutureMemoriesShared: true,\n\t\tsources,\n\t};\n}\n\nfunction normalizeExcludedProject(value: unknown): RecipientReviewedIntentExcludedProjectV1 {\n\tconst input = record(value);\n\tassertKeys(input, [\"canonicalProjectIdentity\", \"displayName\", \"existingMemoryCount\"]);\n\treturn {\n\t\tcanonicalProjectIdentity: strictText(input.canonicalProjectIdentity, 512),\n\t\tdisplayName: displayName(input.displayName),\n\t\texistingMemoryCount: memoryCount(input.existingMemoryCount),\n\t};\n}\n\nfunction normalizeProjectLists(\n\tinput: Record<string, unknown>,\n): Pick<RecipientReviewedIntentBaseV1, \"projects\" | \"excludedProjects\"> {\n\tif (\n\t\t!Array.isArray(input.projects) ||\n\t\t!Array.isArray(input.excludedProjects) ||\n\t\tinput.projects.length > MAX_PROJECTS\n\t) {\n\t\tinvalid();\n\t}\n\tconst projects = input.projects\n\t\t.map(normalizeProject)\n\t\t.toSorted((left, right) =>\n\t\t\tcompareText(left.canonicalProjectIdentity, right.canonicalProjectIdentity),\n\t\t);\n\tconst excludedProjects = input.excludedProjects\n\t\t.map(normalizeExcludedProject)\n\t\t.toSorted((left, right) =>\n\t\t\tcompareText(left.canonicalProjectIdentity, right.canonicalProjectIdentity),\n\t\t);\n\tconst includedIds = projects.map((project) => project.canonicalProjectIdentity);\n\tconst excludedIds = excludedProjects.map((project) => project.canonicalProjectIdentity);\n\tif (\n\t\tnew Set(includedIds).size !== includedIds.length ||\n\t\tnew Set(excludedIds).size !== excludedIds.length ||\n\t\texcludedIds.some((projectId) => includedIds.includes(projectId))\n\t) {\n\t\tinvalid();\n\t}\n\treturn { projects, excludedProjects };\n}\n\nfunction assertTarget(\n\tintent: RecipientReviewedIntentV1,\n\ttarget: RecipientReviewedIntentTargetV1,\n): void {\n\tconst matches =\n\t\t(intent.journey === \"team\" &&\n\t\t\ttarget.kind === \"team_member\" &&\n\t\t\tintent.team.teamId === target.policyTeamId) ||\n\t\t(intent.journey === \"add_device\" &&\n\t\t\ttarget.kind === \"add_device\" &&\n\t\t\tintent.targetIdentity.identityId === target.targetIdentityId);\n\tif (!matches) throw new RecipientReviewedIntentError(\"recipient_invite_intent_mismatch\");\n}\n\nexport function normalizeRecipientReviewedIntent(\n\tvalue: unknown,\n\ttarget?: RecipientReviewedIntentTargetV1,\n): RecipientReviewedIntentV1 {\n\tconst input = record(value);\n\tif (input.version !== RECIPIENT_REVIEWED_INTENT_VERSION) invalid();\n\tconst projectLists = normalizeProjectLists(input);\n\tlet intent: RecipientReviewedIntentV1;\n\tif (input.journey === \"team\") {\n\t\tassertKeys(input, [\"version\", \"journey\", \"team\", \"projects\", \"excludedProjects\"]);\n\t\tconst team = record(input.team);\n\t\tassertKeys(team, [\"teamId\", \"displayName\", \"futureProjectsInherit\"]);\n\t\tif (team.futureProjectsInherit !== true) invalid();\n\t\tintent = {\n\t\t\tversion: 1,\n\t\t\tjourney: \"team\",\n\t\t\tteam: {\n\t\t\t\tteamId: strictText(team.teamId, 256),\n\t\t\t\tdisplayName: displayName(team.displayName),\n\t\t\t\tfutureProjectsInherit: true,\n\t\t\t},\n\t\t\t...projectLists,\n\t\t};\n\t} else if (input.journey === \"add_device\") {\n\t\tassertKeys(input, [\"version\", \"journey\", \"targetIdentity\", \"projects\", \"excludedProjects\"]);\n\t\tconst identity = record(input.targetIdentity);\n\t\tassertKeys(identity, [\"identityId\", \"displayName\"]);\n\t\tintent = {\n\t\t\tversion: 1,\n\t\t\tjourney: \"add_device\",\n\t\t\ttargetIdentity: {\n\t\t\t\tidentityId: strictText(identity.identityId, 256),\n\t\t\t\tdisplayName: identityDisplayName(identity.displayName),\n\t\t\t},\n\t\t\t...projectLists,\n\t\t};\n\t} else {\n\t\tinvalid();\n\t}\n\tif (target) assertTarget(intent, target);\n\tif (new TextEncoder().encode(canonicalJson(intent)).byteLength > MAX_CANONICAL_BYTES) invalid();\n\treturn intent;\n}\n\nfunction canonicalJson(value: unknown): string {\n\tif (Array.isArray(value)) return `[${value.map(canonicalJson).join(\",\")}]`;\n\tif (value && typeof value === \"object\") {\n\t\treturn `{${Object.entries(value as Record<string, unknown>)\n\t\t\t.toSorted(([left], [right]) => compareText(left, right))\n\t\t\t.map(([key, child]) => `${JSON.stringify(key)}:${canonicalJson(child)}`)\n\t\t\t.join(\",\")}}`;\n\t}\n\treturn JSON.stringify(value) ?? \"null\";\n}\n\nexport function canonicalRecipientReviewedIntentJson(\n\tvalue: unknown,\n\ttarget?: RecipientReviewedIntentTargetV1,\n): string {\n\treturn canonicalJson(normalizeRecipientReviewedIntent(value, target));\n}\n\nexport async function recipientReviewedIntentDigest(\n\tvalue: unknown,\n\ttarget?: RecipientReviewedIntentTargetV1,\n): Promise<string> {\n\tconst canonical = canonicalRecipientReviewedIntentJson(value, target);\n\tconst bytes = new TextEncoder().encode(`recipient-reviewed-intent-v1\\n${canonical}`);\n\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", bytes);\n\treturn Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nexport async function verifyRecipientReviewedIntent(\n\tvalue: unknown,\n\toptions: { target: RecipientReviewedIntentTargetV1; digest: string },\n): Promise<RecipientReviewedIntentV1> {\n\tconst normalized = normalizeRecipientReviewedIntent(value, options.target);\n\tif ((await recipientReviewedIntentDigest(normalized)) !== options.digest) {\n\t\tthrow new RecipientReviewedIntentError(\"recipient_invite_intent_mismatch\");\n\t}\n\treturn normalized;\n}\n\nexport async function parseStoredRecipientReviewedIntent(\n\tjson: string | null | undefined,\n\toptions: { target: RecipientReviewedIntentTargetV1; digest: string },\n): Promise<RecipientReviewedIntentV1> {\n\tif (!json) throw new Error(\"recipient_invite_review_unavailable\");\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(json);\n\t} catch {\n\t\tthrow new Error(\"recipient_invite_review_unavailable\");\n\t}\n\ttry {\n\t\tconst normalized = normalizeRecipientReviewedIntent(parsed, options.target);\n\t\tif (canonicalJson(normalized) !== json) {\n\t\t\tthrow new Error(\"recipient_invite_review_unavailable\");\n\t\t}\n\t\treturn await verifyRecipientReviewedIntent(normalized, options);\n\t} catch (error) {\n\t\tif (\n\t\t\terror instanceof RecipientReviewedIntentError &&\n\t\t\terror.code === \"recipient_invite_intent_mismatch\"\n\t\t) {\n\t\t\tthrow error;\n\t\t}\n\t\tif (error instanceof Error && error.message === \"recipient_invite_review_unavailable\") {\n\t\t\tthrow error;\n\t\t}\n\t\tthrow new Error(\"recipient_invite_review_unavailable\");\n\t}\n}\n","import { CoordinatorMembershipError } from \"./coordinator-membership-effects.js\";\nimport type {\n\tCoordinatorCreateBootstrapGrantInput,\n\tCoordinatorCreateInviteInput,\n\tCoordinatorCreateScopeInput,\n\tCoordinatorGrantScopeMembershipInput,\n\tCoordinatorInvite,\n\tCoordinatorInviteKind,\n\tCoordinatorRecipientInviteInspection,\n\tCoordinatorReviewJoinRequestBootstrapGrantInput,\n\tCoordinatorScope,\n\tCoordinatorScopeMembership,\n\tCoordinatorUpdateScopeInput,\n} from \"./coordinator-store-contract.js\";\nimport { isCoordinatorAssignedIdentityId } from \"./coordinator-store-contract.js\";\nimport {\n\tcanonicalRecipientReviewedIntentJson,\n\tparseStoredRecipientReviewedIntent,\n\ttype RecipientReviewedIntentTargetV1,\n\tverifyRecipientReviewedIntent,\n} from \"./recipient-reviewed-intent.js\";\n\nfunction normalizeAddress(address: string): string {\n\tconst value = address.trim();\n\tif (!value) return \"\";\n\tconst withScheme = value.includes(\"://\") ? value : `http://${value}`;\n\ttry {\n\t\tconst url = new URL(withScheme);\n\t\tif (!url.hostname) return \"\";\n\t\tif (url.port && (Number(url.port) <= 0 || Number(url.port) > 65535)) return \"\";\n\t\treturn url.origin + url.pathname.replace(/\\/+$/, \"\");\n\t} catch {\n\t\treturn \"\";\n\t}\n}\n\nfunction addressDedupeKey(address: string): string {\n\tif (!address) return \"\";\n\ttry {\n\t\tconst parsed = new URL(address);\n\t\tconst host = parsed.hostname.toLowerCase();\n\t\tif (\n\t\t\t(parsed.protocol === \"http:\" || parsed.protocol === \"\") &&\n\t\t\thost &&\n\t\t\tparsed.port &&\n\t\t\tparsed.pathname === \"/\"\n\t\t) {\n\t\t\treturn `${host}:${parsed.port}`;\n\t\t}\n\t} catch {}\n\treturn address;\n}\n\nexport function mergeCoordinatorAddresses(existing: string[], candidates: string[]): string[] {\n\tconst normalized: string[] = [];\n\tconst seen = new Set<string>();\n\tfor (const address of [...existing, ...candidates]) {\n\t\tconst cleaned = normalizeAddress(address);\n\t\tconst key = addressDedupeKey(cleaned);\n\t\tif (!cleaned || seen.has(key)) continue;\n\t\tseen.add(key);\n\t\tnormalized.push(cleaned);\n\t}\n\treturn normalized;\n}\n\nexport function normalizeCoordinatorBootstrapGrantRequest(\n\tinput: CoordinatorReviewJoinRequestBootstrapGrantInput | null | undefined,\n): CoordinatorCreateBootstrapGrantInput | null {\n\tif (!input) return null;\n\tconst seedDeviceId = String(input.seedDeviceId ?? \"\").trim();\n\tconst expiresAt = String(input.expiresAt ?? \"\").trim();\n\tconst createdBy = String(input.createdBy ?? \"\").trim() || null;\n\tif (!seedDeviceId || !expiresAt) {\n\t\tthrow new Error(\"bootstrapGrant.seedDeviceId and expiresAt are required.\");\n\t}\n\treturn {\n\t\tgroupId: \"\",\n\t\tseedDeviceId,\n\t\tworkerDeviceId: \"\",\n\t\texpiresAt,\n\t\tcreatedBy,\n\t};\n}\n\nexport function normalizeCoordinatorBootstrapGrantInput(\n\topts: CoordinatorCreateBootstrapGrantInput,\n): CoordinatorCreateBootstrapGrantInput {\n\tconst groupId = String(opts.groupId ?? \"\").trim();\n\tconst seedDeviceId = String(opts.seedDeviceId ?? \"\").trim();\n\tconst workerDeviceId = String(opts.workerDeviceId ?? \"\").trim();\n\tconst expiresAt = String(opts.expiresAt ?? \"\").trim();\n\tconst createdBy = String(opts.createdBy ?? \"\").trim() || null;\n\tif (!groupId || !seedDeviceId || !workerDeviceId || !expiresAt) {\n\t\tthrow new Error(\"groupId, seedDeviceId, workerDeviceId, and expiresAt are required.\");\n\t}\n\treturn { groupId, seedDeviceId, workerDeviceId, expiresAt, createdBy };\n}\n\nexport function clean(value: string | null | undefined): string | null {\n\tconst trimmed = value?.trim();\n\treturn trimmed ? trimmed : null;\n}\n\ninterface NormalizedInviteMetadata {\n\tinviteKind: CoordinatorInviteKind;\n\tpolicyTeamId: string | null;\n\ttargetIdentityId: string | null;\n\treviewedPreviewDigest: string | null;\n}\n\nconst RECIPIENT_INVITE_KINDS = new Set<CoordinatorInviteKind>([\n\t\"legacy_enrollment\",\n\t\"project_share\",\n\t\"team_member\",\n\t\"add_device\",\n]);\n\nfunction validateInviteMetadataIdentifiers(metadata: NormalizedInviteMetadata): void {\n\tif (!RECIPIENT_INVITE_KINDS.has(metadata.inviteKind)) {\n\t\tthrow new Error(\"inviteKind is invalid.\");\n\t}\n\tif (\n\t\t[metadata.policyTeamId, metadata.targetIdentityId]\n\t\t\t.filter((value): value is string => Boolean(value))\n\t\t\t.some((value) => value.length > 256 || /[\\p{Cc}\\p{Cf}]/u.test(value))\n\t) {\n\t\tthrow new Error(\"recipient invite identifier is invalid.\");\n\t}\n\tif (metadata.reviewedPreviewDigest && !/^[a-f0-9]{64}$/u.test(metadata.reviewedPreviewDigest)) {\n\t\tthrow new Error(\"reviewedPreviewDigest must be a SHA-256 digest.\");\n\t}\n}\n\ntype InviteMetadataValidator = (\n\toperationId: string | null,\n\tmetadata: NormalizedInviteMetadata,\n) => void;\n\nconst INVITE_METADATA_VALIDATORS: Record<CoordinatorInviteKind, InviteMetadataValidator> = {\n\tproject_share(operationId, metadata) {\n\t\tif (!operationId) throw new Error(\"project_share invite requires operationId.\");\n\t\tif (metadata.policyTeamId || metadata.targetIdentityId || metadata.reviewedPreviewDigest) {\n\t\t\tthrow new Error(\"recipient invite metadata requires a recipient invite kind.\");\n\t\t}\n\t},\n\tlegacy_enrollment(operationId, metadata) {\n\t\tif (operationId) throw new Error(\"legacy_enrollment invite cannot reference an operation.\");\n\t\tif (metadata.policyTeamId || metadata.targetIdentityId || metadata.reviewedPreviewDigest) {\n\t\t\tthrow new Error(\"recipient invite metadata requires a recipient invite kind.\");\n\t\t}\n\t},\n\tteam_member(operationId, metadata) {\n\t\tif (\n\t\t\t!metadata.policyTeamId ||\n\t\t\t!metadata.reviewedPreviewDigest ||\n\t\t\tmetadata.targetIdentityId ||\n\t\t\toperationId\n\t\t) {\n\t\t\tthrow new Error(\"team_member invite metadata is invalid.\");\n\t\t}\n\t},\n\tadd_device(operationId, metadata) {\n\t\tif (\n\t\t\t!metadata.targetIdentityId ||\n\t\t\t!metadata.reviewedPreviewDigest ||\n\t\t\tmetadata.policyTeamId ||\n\t\t\toperationId\n\t\t) {\n\t\t\tthrow new Error(\"add_device invite metadata is invalid.\");\n\t\t}\n\t},\n};\n\nfunction validateInviteMetadataShape(\n\topts: CoordinatorCreateInviteInput,\n\tmetadata: NormalizedInviteMetadata,\n): void {\n\tINVITE_METADATA_VALIDATORS[metadata.inviteKind](clean(opts.operationId), metadata);\n}\n\nfunction reviewedIntentTarget(metadata: NormalizedInviteMetadata): {\n\ttarget: RecipientReviewedIntentTargetV1;\n\tdigest: string;\n} {\n\tif (\n\t\tmetadata.inviteKind === \"team_member\" &&\n\t\tmetadata.policyTeamId &&\n\t\tmetadata.reviewedPreviewDigest\n\t) {\n\t\treturn {\n\t\t\ttarget: { kind: \"team_member\", policyTeamId: metadata.policyTeamId },\n\t\t\tdigest: metadata.reviewedPreviewDigest,\n\t\t};\n\t}\n\tif (\n\t\tmetadata.inviteKind === \"add_device\" &&\n\t\tmetadata.targetIdentityId &&\n\t\tmetadata.reviewedPreviewDigest\n\t) {\n\t\treturn {\n\t\t\ttarget: { kind: \"add_device\", targetIdentityId: metadata.targetIdentityId },\n\t\t\tdigest: metadata.reviewedPreviewDigest,\n\t\t};\n\t}\n\tthrow new Error(\"recipient invite metadata requires a recipient invite kind.\");\n}\n\nexport async function normalizeCoordinatorInviteMetadata(\n\topts: CoordinatorCreateInviteInput,\n): Promise<{\n\tinviteKind: CoordinatorInviteKind;\n\tpolicyTeamId: string | null;\n\ttargetIdentityId: string | null;\n\treviewedPreviewDigest: string | null;\n\treviewedIntentJson: string | null;\n}> {\n\tconst metadata = {\n\t\tinviteKind:\n\t\t\topts.inviteKind ?? (clean(opts.operationId) ? \"project_share\" : \"legacy_enrollment\"),\n\t\tpolicyTeamId: clean(opts.policyTeamId),\n\t\ttargetIdentityId: clean(opts.targetIdentityId),\n\t\treviewedPreviewDigest: clean(opts.reviewedPreviewDigest),\n\t} satisfies NormalizedInviteMetadata;\n\tvalidateInviteMetadataIdentifiers(metadata);\n\tvalidateInviteMetadataShape(opts, metadata);\n\tconst reviewedIntentProvided = opts.reviewedIntent !== undefined && opts.reviewedIntent !== null;\n\tif (!reviewedIntentProvided) {\n\t\tif (metadata.inviteKind === \"team_member\" || metadata.inviteKind === \"add_device\") {\n\t\t\tthrow new Error(\"recipient_invite_review_unavailable\");\n\t\t}\n\t\treturn {\n\t\t\t...metadata,\n\t\t\treviewedIntentJson: null,\n\t\t};\n\t}\n\tconst reviewedIntent = reviewedIntentTarget(metadata);\n\tawait verifyRecipientReviewedIntent(opts.reviewedIntent, {\n\t\ttarget: reviewedIntent.target,\n\t\tdigest: reviewedIntent.digest,\n\t});\n\treturn {\n\t\t...metadata,\n\t\treviewedIntentJson: canonicalRecipientReviewedIntentJson(\n\t\t\topts.reviewedIntent,\n\t\t\treviewedIntent.target,\n\t\t),\n\t};\n}\n\nexport async function inspectCoordinatorRecipientInvite(\n\tinvite: CoordinatorInvite,\n): Promise<CoordinatorRecipientInviteInspection | null> {\n\tif (invite.invite_kind === \"team_member\") {\n\t\tif (\n\t\t\t!invite.policy_team_id ||\n\t\t\t!isCoordinatorAssignedIdentityId(invite.assigned_identity_id) ||\n\t\t\t!invite.reviewed_preview_digest\n\t\t)\n\t\t\tthrow new Error(\"invite_invalid\");\n\t\tconst reviewedIntent = await parseStoredRecipientReviewedIntent(invite.reviewed_intent_json, {\n\t\t\ttarget: { kind: \"team_member\", policyTeamId: invite.policy_team_id },\n\t\t\tdigest: invite.reviewed_preview_digest,\n\t\t});\n\t\treturn {\n\t\t\tkind: \"team_member\",\n\t\t\tinvite,\n\t\t\tpolicy_team_id: invite.policy_team_id,\n\t\t\tassigned_identity_id: invite.assigned_identity_id,\n\t\t\treviewed_preview_digest: invite.reviewed_preview_digest,\n\t\t\treviewed_intent: reviewedIntent,\n\t\t\tbound: Boolean(invite.consumed_at),\n\t\t};\n\t}\n\tif (invite.invite_kind === \"add_device\") {\n\t\tif (!invite.target_identity_id || !invite.reviewed_preview_digest)\n\t\t\tthrow new Error(\"invite_invalid\");\n\t\tconst reviewedIntent = await parseStoredRecipientReviewedIntent(invite.reviewed_intent_json, {\n\t\t\ttarget: { kind: \"add_device\", targetIdentityId: invite.target_identity_id },\n\t\t\tdigest: invite.reviewed_preview_digest,\n\t\t});\n\t\treturn {\n\t\t\tkind: \"add_device\",\n\t\t\tinvite,\n\t\t\ttarget_identity_id: invite.target_identity_id,\n\t\t\treviewed_preview_digest: invite.reviewed_preview_digest,\n\t\t\treviewed_intent: reviewedIntent,\n\t\t\tbound: Boolean(invite.consumed_at),\n\t\t};\n\t}\n\treturn null;\n}\n\nexport function normalizeEpoch(value: number | null | undefined, fallback = 0): number {\n\tif (value == null) return fallback;\n\tif (!Number.isFinite(value) || value < 0)\n\t\tthrow new Error(\"membershipEpoch must be non-negative.\");\n\treturn Math.trunc(value);\n}\n\nexport function normalizeCoordinatorCreateScopeInput(opts: CoordinatorCreateScopeInput) {\n\tconst scopeId = clean(opts.scopeId);\n\tconst label = clean(opts.label);\n\tif (!scopeId || !label) throw new Error(\"scopeId and label are required.\");\n\treturn {\n\t\tscopeId,\n\t\tlabel,\n\t\tkind: clean(opts.kind) ?? \"user\",\n\t\tauthorityType: clean(opts.authorityType) ?? \"coordinator\",\n\t\tcoordinatorId: clean(opts.coordinatorId),\n\t\tgroupId: clean(opts.groupId),\n\t\tmanifestIssuerDeviceId: clean(opts.manifestIssuerDeviceId),\n\t\tmembershipEpoch: normalizeEpoch(opts.membershipEpoch),\n\t\tmanifestHash: clean(opts.manifestHash),\n\t\tstatus: clean(opts.status) ?? \"active\",\n\t};\n}\n\nfunction cleanRequiredUpdate(\n\tvalue: string | null | undefined,\n\tcurrent: string,\n\tfieldName: string,\n): string {\n\tif (value === undefined) return current;\n\tconst cleaned = clean(value);\n\tif (!cleaned) throw new Error(`${fieldName} must not be empty.`);\n\treturn cleaned;\n}\n\nfunction cleanNullableUpdate(\n\tvalue: string | null | undefined,\n\tcurrent: string | null,\n): string | null {\n\treturn value === undefined ? current : clean(value);\n}\n\nexport function normalizeCoordinatorUpdateScopeInput(\n\topts: CoordinatorUpdateScopeInput,\n\texisting: CoordinatorScope,\n) {\n\tconst scopeId = clean(opts.scopeId);\n\tif (!scopeId) throw new Error(\"scopeId is required.\");\n\tconst requestedEpoch = opts.membershipEpoch == null ? null : normalizeEpoch(opts.membershipEpoch);\n\tif (requestedEpoch != null && requestedEpoch < existing.membership_epoch) {\n\t\tthrow new Error(\"membershipEpoch must not move backwards.\");\n\t}\n\treturn {\n\t\tscopeId,\n\t\tlabel: cleanRequiredUpdate(opts.label, existing.label, \"label\"),\n\t\tkind: cleanRequiredUpdate(opts.kind, existing.kind, \"kind\"),\n\t\tauthorityType: cleanRequiredUpdate(\n\t\t\topts.authorityType,\n\t\t\texisting.authority_type,\n\t\t\t\"authorityType\",\n\t\t),\n\t\tcoordinatorId: cleanNullableUpdate(opts.coordinatorId, existing.coordinator_id),\n\t\tgroupId: cleanNullableUpdate(opts.groupId, existing.group_id),\n\t\tmanifestIssuerDeviceId: cleanNullableUpdate(\n\t\t\topts.manifestIssuerDeviceId,\n\t\t\texisting.manifest_issuer_device_id,\n\t\t),\n\t\tmembershipEpoch: requestedEpoch ?? existing.membership_epoch,\n\t\tmanifestHash: cleanNullableUpdate(opts.manifestHash, existing.manifest_hash),\n\t\tstatus: cleanRequiredUpdate(opts.status, existing.status, \"status\"),\n\t};\n}\n\nexport function normalizeCoordinatorGrantScopeMembershipInput(\n\topts: CoordinatorGrantScopeMembershipInput,\n\tscope: CoordinatorScope | null,\n\texisting: CoordinatorScopeMembership | null,\n) {\n\tconst scopeId = clean(opts.scopeId);\n\tconst deviceId = clean(opts.deviceId);\n\tif (!scopeId || !deviceId) throw new Error(\"scopeId and deviceId are required.\");\n\tvalidateMembershipScopeBindings(opts, scope);\n\tconst membershipEpoch = normalizeMembershipEpoch(opts, scope, existing);\n\treturn {\n\t\tscopeId,\n\t\tdeviceId,\n\t\trole: clean(opts.role) ?? \"member\",\n\t\tmembershipEpoch,\n\t\tcoordinatorId: scope?.coordinator_id ?? null,\n\t\tgroupId: scope?.group_id ?? null,\n\t\tmanifestIssuerDeviceId:\n\t\t\tclean(opts.manifestIssuerDeviceId) ?? scope?.manifest_issuer_device_id ?? null,\n\t\tmanifestHash: clean(opts.manifestHash) ?? scope?.manifest_hash ?? null,\n\t\tsignedManifestJson: clean(opts.signedManifestJson),\n\t\tactorType: clean(opts.actorType),\n\t\tactorId: clean(opts.actorId),\n\t};\n}\n\nfunction validateMembershipScopeBindings(\n\topts: CoordinatorGrantScopeMembershipInput,\n\tscope: CoordinatorScope | null,\n): void {\n\tif (clean(opts.coordinatorId) && clean(opts.coordinatorId) !== scope?.coordinator_id) {\n\t\tthrow new Error(\"membership coordinatorId must match the scope coordinatorId.\");\n\t}\n\tif (clean(opts.groupId) && clean(opts.groupId) !== scope?.group_id) {\n\t\tthrow new CoordinatorMembershipError(\"scope_group_mismatch\");\n\t}\n}\n\nfunction normalizeMembershipEpoch(\n\topts: CoordinatorGrantScopeMembershipInput,\n\tscope: CoordinatorScope | null,\n\texisting: CoordinatorScopeMembership | null,\n): number {\n\tconst requestedEpoch = opts.membershipEpoch == null ? null : normalizeEpoch(opts.membershipEpoch);\n\tconst inheritedEpoch = scope?.membership_epoch ?? 0;\n\tif (requestedEpoch != null && requestedEpoch < inheritedEpoch) {\n\t\tthrow new Error(\"membershipEpoch must not be lower than the scope membershipEpoch.\");\n\t}\n\tif (requestedEpoch != null && existing) {\n\t\tconst minimumEpoch =\n\t\t\texisting.status === \"revoked\" ? existing.membership_epoch + 1 : existing.membership_epoch;\n\t\tif (requestedEpoch < minimumEpoch) {\n\t\t\tthrow new Error(\"membershipEpoch must not move backwards.\");\n\t\t}\n\t}\n\treturn (\n\t\trequestedEpoch ??\n\t\t(existing\n\t\t\t? Math.max(\n\t\t\t\t\tinheritedEpoch,\n\t\t\t\t\texisting.membership_epoch + (existing.status === \"revoked\" ? 1 : 0),\n\t\t\t\t)\n\t\t\t: inheritedEpoch)\n\t);\n}\n\nexport function normalizeCoordinatorAuditLimit(limit: number | null | undefined): number {\n\tif (limit == null) return 100;\n\tif (!Number.isFinite(limit)) return 100;\n\treturn Math.max(1, Math.min(1000, Math.trunc(limit)));\n}\n","import {\n\ttype DecodedRelayCheck,\n\tdecodeRelayCheckPacket,\n\ttype RelayAdmissionRole,\n} from \"./relay-admission-codec.js\";\nimport { parseRelayEd25519PublicKey } from \"./relay-ed25519.js\";\n\nexport interface RelayProofSigner {\n\treadonly deviceId: string;\n\treadonly publicKey: string;\n}\n\nexport type RelayProofExpectation =\n\t| { readonly kind: \"admission\"; readonly role: RelayAdmissionRole }\n\t| { readonly kind: \"registration\" };\n\nexport interface RelayProofVerificationOptions {\n\treadonly packet: unknown;\n\treadonly expected: RelayProofExpectation;\n\treadonly signer: RelayProofSigner;\n\treadonly deviceHeader: string;\n\treadonly externalPathname: string;\n}\n\nexport type VerifiedRelayCheckProof = DecodedRelayCheck & {\n\treadonly signer: RelayProofSigner & { readonly keyId: string };\n\treadonly packetDigest: string;\n};\n\nfunction captureExpectation(value: unknown): RelayProofExpectation | null {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return null;\n\tconst keys = Reflect.ownKeys(value);\n\tif (!keys.includes(\"kind\") || !(\"kind\" in value)) return null;\n\tconst kind = value.kind;\n\tif (kind === \"registration\" && keys.length === 1) return { kind };\n\tif (kind !== \"admission\" || keys.length !== 2 || !keys.includes(\"role\") || !(\"role\" in value)) {\n\t\treturn null;\n\t}\n\tconst role = value.role;\n\tif (role !== \"source\" && role !== \"relay\" && role !== \"responder\") return null;\n\treturn { kind, role };\n}\n\nfunction hasInvalidPathCharacter(value: string): boolean {\n\treturn Array.from(value).some((character) => {\n\t\tconst code = character.codePointAt(0) ?? 0;\n\t\treturn (\n\t\t\tcode <= 32 ||\n\t\t\t(code >= 127 && code <= 159) ||\n\t\t\t(code >= 0xd800 && code <= 0xdfff) ||\n\t\t\t\"?#\\\\\".includes(character)\n\t\t);\n\t});\n}\n\nfunction isAdmissionPath(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.startsWith(\"/\") &&\n\t\t!value.startsWith(\"//\") &&\n\t\t!hasInvalidPathCharacter(value) &&\n\t\tvalue.endsWith(\"/v1/relay/admission-check\")\n\t);\n}\n\nfunction matchesExpectation(decoded: DecodedRelayCheck, expected: RelayProofExpectation): boolean {\n\tif (decoded.kind === \"registration\") return expected.kind === \"registration\";\n\treturn expected.kind === \"admission\" && decoded.value.role === expected.role;\n}\n\nfunction captureProofInputs(options: RelayProofVerificationOptions) {\n\tconst { packet, expected, signer, deviceHeader, externalPathname } = options;\n\tconst expectation = captureExpectation(expected);\n\tconst { deviceId, publicKey } = signer;\n\tif (\n\t\t!expectation ||\n\t\ttypeof deviceId !== \"string\" ||\n\t\ttypeof publicKey !== \"string\" ||\n\t\ttypeof deviceHeader !== \"string\" ||\n\t\t!isAdmissionPath(externalPathname)\n\t) {\n\t\treturn null;\n\t}\n\tconst decoded = decodeRelayCheckPacket(packet);\n\tif (!matchesExpectation(decoded, expectation)) return null;\n\tlet signedDeviceId: string;\n\tlet signedKeyId: string;\n\tif (decoded.kind === \"admission\") {\n\t\tsignedDeviceId = decoded.value.sourceDeviceId;\n\t\tsignedKeyId = decoded.value.sourceKeyId;\n\t} else {\n\t\tsignedDeviceId = decoded.value.deviceId;\n\t\tsignedKeyId = decoded.value.keyId;\n\t}\n\tif (deviceHeader !== signedDeviceId || deviceId !== signedDeviceId) return null;\n\treturn {\n\t\tdecoded,\n\t\tsigner: { deviceId, publicKey },\n\t\tsignedKeyId,\n\t\texternalPathname,\n\t\tkey: parseRelayEd25519PublicKey(publicKey),\n\t};\n}\n\nasync function sha256Hex(bytes: Uint8Array): Promise<string> {\n\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", new Uint8Array(bytes));\n\treturn Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Verifies one packet against an explicitly trusted existing key pin, without consuming its nonce.\n * A proof is not fresh or authorized. The caller must still check current authority, enrollments,\n * policy, readiness, quotas, time windows, and nonce insertion in its final atomic decision.\n */\nexport async function verifyRelayCheckProof(\n\toptions: RelayProofVerificationOptions,\n): Promise<VerifiedRelayCheckProof | null> {\n\ttry {\n\t\t// Capture caller-owned data and decode owned bytes before any asynchronous operation.\n\t\tconst captured = captureProofInputs(options);\n\t\tif (!captured) return null;\n\t\tconst { decoded, signer, signedKeyId, externalPathname, key } = captured;\n\t\tconst keyId = await sha256Hex(key.wireKey);\n\t\tif (keyId !== signedKeyId) return null;\n\t\tconst packetDigest = await sha256Hex(decoded.bodyBytes);\n\t\tconst canonical = [\n\t\t\t\"POST\",\n\t\t\texternalPathname,\n\t\t\tdecoded.timestamp,\n\t\t\tdecoded.nonce,\n\t\t\tpacketDigest,\n\t\t].join(\"\\n\");\n\t\tconst verificationKey = await globalThis.crypto.subtle.importKey(\n\t\t\t\"raw\",\n\t\t\tnew Uint8Array(key.rawKey),\n\t\t\t{ name: \"Ed25519\" },\n\t\t\tfalse,\n\t\t\t[\"verify\"],\n\t\t);\n\t\tconst verified = await globalThis.crypto.subtle.verify(\n\t\t\t\"Ed25519\",\n\t\t\tverificationKey,\n\t\t\tnew Uint8Array(decoded.signatureBytes),\n\t\t\tnew TextEncoder().encode(canonical),\n\t\t);\n\t\tif (!verified) return null;\n\t\treturn { ...decoded, signer: { ...signer, keyId }, packetDigest };\n\t} catch {\n\t\treturn null;\n\t}\n}\n","export const DEFAULT_TIME_WINDOW_S = 300;\n"],"mappings":";;;;AAMA,SAAgB,EAA2C,GAGlD;CACR,IACC,EAAM,QAAQ,SAAA,OACd,EAAM,SAAS,SAAA,OACf,EAAM,QAAQ,SAAS,EAAM,SAAS,SAAA,KAEtC,MAAU,MAAM,oCAAoC;AAEtD;AASA,SAAgB,EAAsD,GAG7D;CACR,IACC,EAAM,kBAAkB,OAAO,EAAM,cAAA,KAGrC,MAAU,MAAM,oCAAoC;AAEtD;AAOA,SAAgB,EACf,GACA,GACA,GACO;CACP,IAAI,EAAS,WAAW,GAAG;CAC3B,IAAM,IAAY,CAAC,GAAG,IAAI,IAAI,EAAQ,KAAK,MAAW,EAAO,QAAQ,CAAC,CAAC,GACjE,IACL,EAAU,SAAS,IAAI,2BAA2B,EAAU,UAAU,GAAG,CAAC,CAAC,KAAK,IAAI,EAAE,KAAK,IACtF,IAAiB,OACtB,EACE,QAAQ,yCAAyC,GAAe,CAAC,CACjE,MAAM,CAAC,CACP,IAAI,GAAG,CAAS,KAAK,CACxB;C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