@codemem/core 0.47.0-beta.3 → 0.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. package/dist/account-owner-association-directory.d.ts +6 -0
  2. package/dist/account-owner-association-directory.d.ts.map +1 -0
  3. package/dist/account-owner-association.d.ts +50 -0
  4. package/dist/account-owner-association.d.ts.map +1 -0
  5. package/dist/better-sqlite-coordinator-store.d.ts +27 -1
  6. package/dist/better-sqlite-coordinator-store.d.ts.map +1 -1
  7. package/dist/coordinator-account-change.d.ts +0 -5
  8. package/dist/coordinator-account-change.d.ts.map +1 -1
  9. package/dist/coordinator-account-connection-link.d.ts +7 -1
  10. package/dist/coordinator-account-connection-link.d.ts.map +1 -1
  11. package/dist/coordinator-account-connection-schema.d.ts +3 -0
  12. package/dist/coordinator-account-connection-schema.d.ts.map +1 -1
  13. package/dist/coordinator-account-link-receiver.d.ts +19 -0
  14. package/dist/coordinator-account-link-receiver.d.ts.map +1 -1
  15. package/dist/coordinator-account-link-status.d.ts.map +1 -1
  16. package/dist/coordinator-account-owner-target.d.ts +40 -0
  17. package/dist/coordinator-account-owner-target.d.ts.map +1 -0
  18. package/dist/coordinator-actions.d.ts +5 -0
  19. package/dist/coordinator-actions.d.ts.map +1 -1
  20. package/dist/coordinator-api.d.ts +2 -0
  21. package/dist/coordinator-api.d.ts.map +1 -1
  22. package/dist/coordinator-auth-browser-view.d.ts +6 -0
  23. package/dist/coordinator-auth-browser-view.d.ts.map +1 -1
  24. package/dist/coordinator-auth-controller-consistency-test-fixtures.d.ts +51 -0
  25. package/dist/coordinator-auth-controller-consistency-test-fixtures.d.ts.map +1 -0
  26. package/dist/coordinator-auth-controller-history.d.ts +71 -0
  27. package/dist/coordinator-auth-controller-history.d.ts.map +1 -0
  28. package/dist/coordinator-auth-controller-owner-review.d.ts +35 -0
  29. package/dist/coordinator-auth-controller-owner-review.d.ts.map +1 -0
  30. package/dist/coordinator-auth-controller-owner.d.ts +20 -0
  31. package/dist/coordinator-auth-controller-owner.d.ts.map +1 -0
  32. package/dist/coordinator-auth-controller-review-route.d.ts +16 -2
  33. package/dist/coordinator-auth-controller-review-route.d.ts.map +1 -1
  34. package/dist/coordinator-auth-controller.d.ts +30 -3
  35. package/dist/coordinator-auth-controller.d.ts.map +1 -1
  36. package/dist/coordinator-auth-device-claim-eligibility.d.ts +8 -3
  37. package/dist/coordinator-auth-device-claim-eligibility.d.ts.map +1 -1
  38. package/dist/coordinator-auth-historical-store-test-fixture.d.ts.map +1 -1
  39. package/dist/coordinator-auth-legacy-assignment.d.ts +1 -1
  40. package/dist/coordinator-auth-legacy-assignment.d.ts.map +1 -1
  41. package/dist/coordinator-auth-link-authority.d.ts +2 -1
  42. package/dist/coordinator-auth-link-authority.d.ts.map +1 -1
  43. package/dist/coordinator-auth-link.d.ts +1 -0
  44. package/dist/coordinator-auth-link.d.ts.map +1 -1
  45. package/dist/coordinator-auth-schema.d.ts.map +1 -1
  46. package/dist/coordinator-auth-store-test-fixtures.d.ts.map +1 -1
  47. package/dist/coordinator-browser-auth-app.d.ts.map +1 -1
  48. package/dist/coordinator-browser-auth-callback.d.ts +7 -1
  49. package/dist/coordinator-browser-auth-callback.d.ts.map +1 -1
  50. package/dist/coordinator-device-auth-link.d.ts +6 -1
  51. package/dist/coordinator-device-auth-link.d.ts.map +1 -1
  52. package/dist/coordinator-device-ownership-evidence-classify.d.ts +22 -0
  53. package/dist/coordinator-device-ownership-evidence-classify.d.ts.map +1 -0
  54. package/dist/coordinator-device-ownership-evidence-digest.d.ts +8 -0
  55. package/dist/coordinator-device-ownership-evidence-digest.d.ts.map +1 -0
  56. package/dist/coordinator-device-ownership-evidence-queries.d.ts +13 -0
  57. package/dist/coordinator-device-ownership-evidence-queries.d.ts.map +1 -0
  58. package/dist/coordinator-device-ownership-evidence-test-fixtures.d.ts +80 -0
  59. package/dist/coordinator-device-ownership-evidence-test-fixtures.d.ts.map +1 -0
  60. package/dist/coordinator-device-ownership-evidence.d.ts +60 -0
  61. package/dist/coordinator-device-ownership-evidence.d.ts.map +1 -0
  62. package/dist/coordinator-device-ownership-schema.d.ts +7 -1
  63. package/dist/coordinator-device-ownership-schema.d.ts.map +1 -1
  64. package/dist/coordinator-device-rebind-browser.d.ts +26 -0
  65. package/dist/coordinator-device-rebind-browser.d.ts.map +1 -0
  66. package/dist/coordinator-device-rebind-ceremony.d.ts +126 -0
  67. package/dist/coordinator-device-rebind-ceremony.d.ts.map +1 -0
  68. package/dist/coordinator-device-rebind-client.d.ts +82 -0
  69. package/dist/coordinator-device-rebind-client.d.ts.map +1 -0
  70. package/dist/coordinator-device-rebind-commit.d.ts +58 -0
  71. package/dist/coordinator-device-rebind-commit.d.ts.map +1 -0
  72. package/dist/coordinator-device-rebind-http.d.ts +11 -0
  73. package/dist/coordinator-device-rebind-http.d.ts.map +1 -0
  74. package/dist/coordinator-device-rebind-proof.d.ts +55 -0
  75. package/dist/coordinator-device-rebind-proof.d.ts.map +1 -0
  76. package/dist/coordinator-device-rebind-schema.d.ts +38 -0
  77. package/dist/coordinator-device-rebind-schema.d.ts.map +1 -0
  78. package/dist/coordinator-device-rebind-test-fixtures.d.ts +47 -0
  79. package/dist/coordinator-device-rebind-test-fixtures.d.ts.map +1 -0
  80. package/dist/coordinator-device-rebind-view.d.ts +37 -0
  81. package/dist/coordinator-device-rebind-view.d.ts.map +1 -0
  82. package/dist/coordinator-enrollment-ownership.d.ts +14 -0
  83. package/dist/coordinator-enrollment-ownership.d.ts.map +1 -0
  84. package/dist/coordinator-enrollment-reconciler.d.ts.map +1 -1
  85. package/dist/coordinator-history-sql-equivalence-test-fixtures.d.ts +35 -0
  86. package/dist/coordinator-history-sql-equivalence-test-fixtures.d.ts.map +1 -0
  87. package/dist/coordinator-legacy-completion-owner-proof.d.ts +47 -0
  88. package/dist/coordinator-legacy-completion-owner-proof.d.ts.map +1 -0
  89. package/dist/coordinator-legacy-owner-compatibility.d.ts +33 -0
  90. package/dist/coordinator-legacy-owner-compatibility.d.ts.map +1 -0
  91. package/dist/coordinator-legacy-owner-resolution-birth-test-fixtures.d.ts +3 -0
  92. package/dist/coordinator-legacy-owner-resolution-birth-test-fixtures.d.ts.map +1 -0
  93. package/dist/coordinator-legacy-owner-resolution-commit-test-fixtures.d.ts +54 -0
  94. package/dist/coordinator-legacy-owner-resolution-commit-test-fixtures.d.ts.map +1 -0
  95. package/dist/coordinator-legacy-owner-resolution-commit.d.ts +34 -0
  96. package/dist/coordinator-legacy-owner-resolution-commit.d.ts.map +1 -0
  97. package/dist/coordinator-legacy-owner-resolution-metadata.d.ts +40 -0
  98. package/dist/coordinator-legacy-owner-resolution-metadata.d.ts.map +1 -0
  99. package/dist/coordinator-legacy-owner-resolution-schema.d.ts +70 -0
  100. package/dist/coordinator-legacy-owner-resolution-schema.d.ts.map +1 -0
  101. package/dist/coordinator-legacy-owner-resolution-upgrade.d.ts +4 -0
  102. package/dist/coordinator-legacy-owner-resolution-upgrade.d.ts.map +1 -0
  103. package/dist/coordinator-legacy-team-completion.d.ts +17 -0
  104. package/dist/coordinator-legacy-team-completion.d.ts.map +1 -1
  105. package/dist/coordinator-owner-enrollment-commit.d.ts +7 -6
  106. package/dist/coordinator-owner-enrollment-commit.d.ts.map +1 -1
  107. package/dist/coordinator-owner-negative-consistency.d.ts +38 -0
  108. package/dist/coordinator-owner-negative-consistency.d.ts.map +1 -0
  109. package/dist/coordinator-owner-resolution-review-client.d.ts +17 -0
  110. package/dist/coordinator-owner-resolution-review-client.d.ts.map +1 -0
  111. package/dist/coordinator-owner-resolution-review-read.d.ts +48 -0
  112. package/dist/coordinator-owner-resolution-review-read.d.ts.map +1 -0
  113. package/dist/coordinator-owner-resolution-review-test-fixtures.d.ts +60 -0
  114. package/dist/coordinator-owner-resolution-review-test-fixtures.d.ts.map +1 -0
  115. package/dist/coordinator-owner-resolution-review.d.ts +73 -0
  116. package/dist/coordinator-owner-resolution-review.d.ts.map +1 -0
  117. package/dist/coordinator-producer-negative-owner-test-fixtures.d.ts +26 -0
  118. package/dist/coordinator-producer-negative-owner-test-fixtures.d.ts.map +1 -0
  119. package/dist/coordinator-recipient-owner-consistency.d.ts +8 -0
  120. package/dist/coordinator-recipient-owner-consistency.d.ts.map +1 -0
  121. package/dist/coordinator-resolved-account-owner-status-client.d.ts +27 -0
  122. package/dist/coordinator-resolved-account-owner-status-client.d.ts.map +1 -0
  123. package/dist/coordinator-resolved-account-owner-status-query.d.ts +21 -0
  124. package/dist/coordinator-resolved-account-owner-status-query.d.ts.map +1 -0
  125. package/dist/coordinator-resolved-account-owner-status-test-fixtures.d.ts +84 -0
  126. package/dist/coordinator-resolved-account-owner-status-test-fixtures.d.ts.map +1 -0
  127. package/dist/coordinator-resolved-account-owner-status.d.ts +57 -0
  128. package/dist/coordinator-resolved-account-owner-status.d.ts.map +1 -0
  129. package/dist/coordinator-store-contract.d.ts +4 -0
  130. package/dist/coordinator-store-contract.d.ts.map +1 -1
  131. package/dist/coordinator-store-test-harness.d.ts.map +1 -1
  132. package/dist/d1-coordinator-runtime.d.ts +1 -0
  133. package/dist/d1-coordinator-runtime.d.ts.map +1 -1
  134. package/dist/d1-coordinator-store.d.ts +23 -1
  135. package/dist/d1-coordinator-store.d.ts.map +1 -1
  136. package/dist/db.d.ts.map +1 -1
  137. package/dist/index.d.ts +20 -5
  138. package/dist/index.d.ts.map +1 -1
  139. package/dist/index.js +13953 -18682
  140. package/dist/index.js.map +1 -1
  141. package/dist/internal/cloudflare-coordinator.js +1806 -1329
  142. package/dist/internal/cloudflare-coordinator.js.map +1 -1
  143. package/dist/legacy-team-setup-completion-manifest.d.ts.map +1 -1
  144. package/dist/legacy-team-setup-draft.d.ts +7 -0
  145. package/dist/legacy-team-setup-draft.d.ts.map +1 -1
  146. package/dist/local-identity-generation.d.ts +14 -0
  147. package/dist/local-identity-generation.d.ts.map +1 -0
  148. package/dist/local-identity-switch.d.ts +82 -0
  149. package/dist/local-identity-switch.d.ts.map +1 -0
  150. package/dist/memory-retirement-delivery.d.ts.map +1 -1
  151. package/dist/operational-status.d.ts.map +1 -1
  152. package/dist/owner-enrollment-start-XwN1p7du.js +8395 -0
  153. package/dist/owner-enrollment-start-XwN1p7du.js.map +1 -0
  154. package/dist/pack.d.ts +4 -4
  155. package/dist/pack.d.ts.map +1 -1
  156. package/dist/recipient-policy-contract-Ca40IBUh.js +24 -0
  157. package/dist/recipient-policy-contract-Ca40IBUh.js.map +1 -0
  158. package/dist/recipient-policy-contract.js +2 -24
  159. package/dist/same-actor-peers.d.ts +4 -0
  160. package/dist/same-actor-peers.d.ts.map +1 -0
  161. package/dist/schema-bootstrap.d.ts.map +1 -1
  162. package/dist/schema.d.ts +38 -0
  163. package/dist/schema.d.ts.map +1 -1
  164. package/dist/search.d.ts +2 -0
  165. package/dist/search.d.ts.map +1 -1
  166. package/dist/semantic/semantic-executor-seam.d.ts +30 -0
  167. package/dist/semantic/semantic-executor-seam.d.ts.map +1 -0
  168. package/dist/semantic/semantic-ranking-reference.test-helper.d.ts +34 -0
  169. package/dist/semantic/semantic-ranking-reference.test-helper.d.ts.map +1 -0
  170. package/dist/semantic/semantic-ranking.d.ts +50 -0
  171. package/dist/semantic/semantic-ranking.d.ts.map +1 -0
  172. package/dist/semantic/semantic-ranking.test-helper.d.ts +17 -0
  173. package/dist/semantic/semantic-ranking.test-helper.d.ts.map +1 -0
  174. package/dist/semantic/semantic-worker-entry.d.ts +2 -0
  175. package/dist/semantic/semantic-worker-entry.d.ts.map +1 -0
  176. package/dist/semantic/semantic-worker-executor.d.ts +20 -0
  177. package/dist/semantic/semantic-worker-executor.d.ts.map +1 -0
  178. package/dist/semantic/semantic-worker-job.d.ts +2 -0
  179. package/dist/semantic/semantic-worker-job.d.ts.map +1 -0
  180. package/dist/semantic/semantic-worker-protocol.d.ts +48 -0
  181. package/dist/semantic/semantic-worker-protocol.d.ts.map +1 -0
  182. package/dist/semantic/semantic-worker-queue.d.ts +32 -0
  183. package/dist/semantic/semantic-worker-queue.d.ts.map +1 -0
  184. package/dist/semantic/semantic-worker-ranking.d.ts +8 -0
  185. package/dist/semantic/semantic-worker-ranking.d.ts.map +1 -0
  186. package/dist/semantic/semantic-worker-test-fixtures.d.ts +55 -0
  187. package/dist/semantic/semantic-worker-test-fixtures.d.ts.map +1 -0
  188. package/dist/semantic/validated-vector-index-audit.d.ts +10 -0
  189. package/dist/semantic/validated-vector-index-audit.d.ts.map +1 -0
  190. package/dist/semantic/validated-vector-index-mutations.d.ts +23 -0
  191. package/dist/semantic/validated-vector-index-mutations.d.ts.map +1 -0
  192. package/dist/semantic/validated-vector-index-state.d.ts +77 -0
  193. package/dist/semantic/validated-vector-index-state.d.ts.map +1 -0
  194. package/dist/semantic/validated-vector-index-statements.d.ts +30 -0
  195. package/dist/semantic/validated-vector-index-statements.d.ts.map +1 -0
  196. package/dist/semantic/validated-vector-index.d.ts +16 -0
  197. package/dist/semantic/validated-vector-index.d.ts.map +1 -0
  198. package/dist/semantic/validated-vector-index.test-helper.d.ts +9 -0
  199. package/dist/semantic/validated-vector-index.test-helper.d.ts.map +1 -0
  200. package/dist/semantic-query.d.ts +10 -0
  201. package/dist/semantic-query.d.ts.map +1 -0
  202. package/dist/semantic-worker-entry.js +14 -0
  203. package/dist/semantic-worker-entry.js.map +1 -0
  204. package/dist/semantic-worker-job-a7S-qbRH.js +49 -0
  205. package/dist/semantic-worker-job-a7S-qbRH.js.map +1 -0
  206. package/dist/semantic-worker-ranking-hRyoWJtp.js +7680 -0
  207. package/dist/semantic-worker-ranking-hRyoWJtp.js.map +1 -0
  208. package/dist/store.d.ts +25 -12
  209. package/dist/store.d.ts.map +1 -1
  210. package/dist/test-schema.generated.d.ts +1 -1
  211. package/dist/test-schema.generated.d.ts.map +1 -1
  212. package/dist/types.d.ts +4 -0
  213. package/dist/types.d.ts.map +1 -1
  214. package/dist/usage-aggregate-index.d.ts +4 -0
  215. package/dist/usage-aggregate-index.d.ts.map +1 -0
  216. package/dist/vector-index-maintenance.d.ts +28 -0
  217. package/dist/vector-index-maintenance.d.ts.map +1 -0
  218. package/dist/vector-index-upgrade.d.ts +21 -0
  219. package/dist/vector-index-upgrade.d.ts.map +1 -0
  220. package/dist/vector-layout.d.ts +21 -0
  221. package/dist/vector-layout.d.ts.map +1 -0
  222. package/dist/vector-migration.d.ts.map +1 -1
  223. package/dist/vector-writes.d.ts +26 -0
  224. package/dist/vector-writes.d.ts.map +1 -0
  225. package/dist/vectors.d.ts +8 -3
  226. package/dist/vectors.d.ts.map +1 -1
  227. package/dist/workspace-identity-C2g2-ZRR.js +10038 -0
  228. package/dist/workspace-identity-C2g2-ZRR.js.map +1 -0
  229. package/package.json +5 -5
  230. package/dist/owner-enrollment-start-xsoRbhG2.js +0 -14318
  231. package/dist/owner-enrollment-start-xsoRbhG2.js.map +0 -1
  232. package/dist/recipient-policy-contract.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"owner-enrollment-start-xsoRbhG2.js","names":["errorHandler","Hono","Node","Node","HonoBase","USER_AGENT","ERR_INVALID_ARG_VALUE","ERR_INVALID_ARG_TYPE","CodedTypeError","allowInsecureRequests","clockTolerance","customFetch","decoder","signal","performDiscovery","assertString","randomBytes","calculatePKCECodeChallenge","ClientSecretPost","None","oauth.ClientSecretPost","oauth.None","oauth.customFetch","oauth.clockTolerance","oauth.calculatePKCECodeChallenge","oauth.generateRandomCodeVerifier","oauth.generateRandomNonce","oauth.generateRandomState","oauth.ResponseBodyError","oauth.AuthorizationResponseError","oauth.WWWAuthenticateChallengeError","oauth.OperationProcessingError","oauth.HTTP_REQUEST_FORBIDDEN","oauth.REQUEST_PROTOCOL_FORBIDDEN","oauth.RESPONSE_IS_NOT_CONFORM","oauth.RESPONSE_IS_NOT_JSON","oauth.PARSE_ERROR","oauth.INVALID_RESPONSE","oauth.JWT_CLAIM_COMPARISON","oauth.JSON_ATTRIBUTE_COMPARISON","oauth.JWT_TIMESTAMP_CHECK","oauth.UnsupportedOperationError","oauth.UNSUPPORTED_OPERATION","oauth.discoveryRequest","oauth.allowInsecureRequests","oauth.processDiscoveryResponse","oauth._nodiscoverycheck","oauth.clockSkew","oauth._expectedIssuer","oauth.getValidatedIdTokenClaims","oauth\n .validateApplicationLevelSignature","oauth.jwksCache","jwksCache","oauth.formPostResponse","oauth.validateAuthResponse","oauth\n .authorizationCodeGrantRequest","oauth.nopkce","oauth.processAuthorizationCodeResponse","oauth.jweDecrypt","oauth.resolveEndpoint","oauth\n .userInfoRequest","oauth.processUserInfoResponse","oauth.isDPoPNonceError"],"sources":["../src/sync-fingerprint.ts","../src/project-identity.ts","../src/coordinator-account-change-schema.ts","../src/coordinator-account-connection-storage.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-controller.ts","../src/legacy-team-setup-limits.ts","../src/recipient-policy-identifiers.ts","../src/coordinator-legacy-team-completion.ts","../src/coordinator-auth-legacy-assignment.ts","../src/coordinator-auth-contract.ts","../src/coordinator-auth-link-input.ts","../src/coordinator-ed25519-key-id.ts","../src/coordinator-ed25519-key-id-compat.ts","../src/coordinator-auth-device-claim-eligibility.ts","../src/coordinator-auth-link-provenance.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-session-contract.ts","../src/coordinator-auth-session.ts","../src/coordinator-auth-account-profile.ts","../src/coordinator-auth-link-profile.ts","../src/coordinator-auth-loopback.ts","../src/coordinator-auth-link.ts","../src/coordinator-account-change.ts","../src/coordinator-auth-browser-style.ts","../src/coordinator-auth-proof.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-auth-browser-transaction.ts","../src/coordinator-device-revocation.ts","../src/coordinator-bootstrap-grant-authorization.ts","../src/coordinator-bootstrap-grant-issuance.ts","../src/coordinator-identity-group-grant.ts","../src/coordinator-legacy-device-ownership.ts","../src/coordinator-join-review-guards.ts","../src/coordinator-membership-effects.ts","../src/coordinator-owner-enrollment-schema.ts","../src/coordinator-peer-discovery.ts","../src/coordinator-project-invite-guards.ts","../src/coordinator-scope-authorization.ts","../src/coordinator-store-contract.ts","../src/project-invite-identity.ts","../src/recipient-reviewed-intent.ts","../src/coordinator-store-input-rules.ts","../src/scope-membership-semantics.ts","../src/sync-auth-constants.ts","../src/workspace-identity.ts","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/compose.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/request/constants.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/utils/buffer.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/utils/body.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/utils/url.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/request.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/utils/html.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/context.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/router.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/utils/constants.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/hono-base.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/router/utils.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/router/reg-exp-router/matcher.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/router/reg-exp-router/node.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/router/reg-exp-router/trie.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/router/reg-exp-router/router.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/router/smart-router/router.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/router/trie-router/node.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/router/trie-router/router.js","../../../node_modules/.pnpm/hono@4.13.5/node_modules/hono/dist/hono.js","../src/coordinator-auth-controller-review-route.ts","../src/coordinator-account-change-contract.ts","../src/coordinator-device-account-change.ts","../src/coordinator-device-auth-link.ts","../src/coordinator-device-revocation-handler.ts","../src/coordinator-device-revocation-route.ts","../src/coordinator-invites.ts","../src/coordinator-scope-authorization-response.ts","../src/project-invite-acceptance.ts","../src/project-share-intent.ts","../../../node_modules/.pnpm/limiter@3.0.0/node_modules/limiter/dist/esm/clock.js","../../../node_modules/.pnpm/limiter@3.0.0/node_modules/limiter/dist/esm/TokenBucket.js","../../../node_modules/.pnpm/limiter@3.0.0/node_modules/limiter/dist/esm/RateLimiter.js","../src/request-rate-limit.ts","../src/coordinator-api.ts","../src/coordinator-identity-group-grant-client.ts","../src/coordinator-owner-enrollment-proof.ts","../src/coordinator-browser-auth-config.ts","../src/coordinator-browser-form-body.ts","../src/coordinator-browser-form-guard.ts","../src/coordinator-browser-request.ts","../src/coordinator-browser-start-transaction.ts","../../../node_modules/.pnpm/oauth4webapi@3.8.8/node_modules/oauth4webapi/build/index.js","../../../node_modules/.pnpm/openid-client@6.8.8/node_modules/openid-client/build/index.js","../src/coordinator-oidc.ts","../src/coordinator-auth-link-liveness.ts","../src/coordinator-owner-enrollment-qualification-schema.ts","../src/owner-enrollment-link-authority.ts","../src/owner-enrollment-admission.ts","../src/owner-enrollment-owner-pin.ts","../src/coordinator-owner-enrollment-commit.ts","../src/owner-browser-admission-authority.ts","../src/owner-enrollment-start.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\n\n/** SHA-256 hex digest of a public key string. */\nexport function fingerprintPublicKey(publicKey: string): string {\n\treturn createHash(\"sha256\").update(publicKey, \"utf-8\").digest(\"hex\");\n}\n","const COMMAND_FAILURE_PREFIX = /^(?:command failed(?:\\s|:)|error:\\s|fatal:\\s|git:\\s)/iu;\nconst WRAPPED_GIT_FAILURE =\n\t/^(?:giterror|git error|git command failed):[^\\r\\n]*(?:not a git repository|unknown revision or path|no such remote)\\b/iu;\n\n/** Return true when a discovery failure was supplied where Project identity was expected. */\nexport function isMalformedProjectIdentity(value: unknown): boolean {\n\tif (typeof value !== \"string\") return false;\n\tconst cleaned = value.trim();\n\tif (!cleaned) return false;\n\tif (cleaned.includes(\"\\n\") || cleaned.includes(\"\\r\")) return true;\n\treturn COMMAND_FAILURE_PREFIX.test(cleaned) || WRAPPED_GIT_FAILURE.test(cleaned);\n}\n\nexport function cleanProjectIdentity(value: string | null | undefined): string | null {\n\tconst cleaned = value?.trim();\n\tif (!cleaned || isMalformedProjectIdentity(cleaned)) return null;\n\treturn cleaned;\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","/**\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","/** 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\ttarget: { identityId: string; groupId: string; deviceId: string };\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 upgrade-auth-schema --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 upgrade-account-schema --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);\nexport const ACCOUNT_CONNECTION_SCHEMA_CHECKS = currentChecks;\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 (\n\t\t\t!/no such (?:table|column)|has no column named|malformed (?:database )?schema/i.test(\n\t\t\t\tString(error),\n\t\t\t)\n\t\t)\n\t\t\tthrow 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","/** 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\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\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\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 = { enrollmentIdentityId: identity.value as string | null, invites };\n\tif (new TextEncoder().encode(JSON.stringify(snapshot)).byteLength > 1_000_000) return null;\n\treturn snapshot;\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 (snapshot !== undefined) captured.verifiedSnapshot = snapshot;\n\t} catch {\n\t\treturn null;\n\t}\n\treturn captured as CoordinatorAuthControllerReviewInput;\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)`;\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))`;\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\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];\n}\n\nexport function authControllerInsertValues(\n\tinput: CoordinatorAuthControllerReviewInput,\n\tcreatedAt: string,\n\tauthority: (string | null)[],\n): (string | null)[] {\n\treturn [\n\t\t...authControllerSnapshotValues(input),\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\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}\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];\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","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\nexport interface CoordinatorLegacyTeamCompletionDeviceDecisionV1 {\n\tdevice_id: string;\n\tkey_fingerprint: string;\n\tenabled: boolean;\n\tidentity_id: string | null;\n\tdecision: \"included\" | \"excluded\";\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\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((value) => {\n\t\t\tconst item = record(value);\n\t\t\texactFields(item, [\"device_id\", \"key_fingerprint\", \"enabled\", \"identity_id\", \"decision\"]);\n\t\t\tif (item.decision !== \"included\" && item.decision !== \"excluded\") invalid();\n\t\t\tif (typeof item.enabled !== \"boolean\") invalid();\n\t\t\tconst identityId = item.identity_id == null ? null : identifier(item.identity_id);\n\t\t\tif ((item.decision === \"included\") !== Boolean(identityId)) invalid();\n\t\t\tif (item.decision === \"included\" && !item.enabled) invalid();\n\t\t\tconst decision: CoordinatorLegacyTeamCompletionDeviceDecisionV1[\"decision\"] = item.decision;\n\t\t\treturn {\n\t\t\t\tdevice_id: identifier(item.device_id),\n\t\t\t\tkey_fingerprint: digest(item.key_fingerprint),\n\t\t\t\tenabled: item.enabled,\n\t\t\t\tidentity_id: identityId,\n\t\t\t\tdecision,\n\t\t\t};\n\t\t}),\n\t\t(item) => item.device_id,\n\t);\n\tif (deviceDecisions.length === 0) invalid();\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 type { CoordinatorAuthLinkSigner } from \"./coordinator-auth-link-contract.js\";\nimport {\n\tcanonicalCoordinatorLegacyTeamCompletionManifestJson,\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);\n\t\treturn assigned ? JSON.stringify({ ...row, distinct_keys: input.distinctKeys }) : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\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 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","export type SshEd25519Parse =\n\t| { kind: \"ed25519\"; blob: Uint8Array }\n\t| { kind: \"malformed_ed25519\" }\n\t| { kind: \"other\" };\n\nfunction decodeWire(encoded: string): Uint8Array | null {\n\ttry {\n\t\tconst binary = atob(encoded);\n\t\treturn Uint8Array.from(binary, (character) => character.charCodeAt(0));\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction readRawKey(wire: Uint8Array): Uint8Array | null {\n\tif (wire.length < 4) return null;\n\tconst view = new DataView(wire.buffer, wire.byteOffset, wire.byteLength);\n\tconst typeEnd = 4 + view.getUint32(0);\n\tif (wire.length < typeEnd + 4) return null;\n\tconst keyLength = view.getUint32(typeEnd);\n\tconst keyStart = typeEnd + 4;\n\tif (keyLength !== 32 || wire.length < keyStart + keyLength) return null;\n\treturn wire.subarray(keyStart, keyStart + keyLength);\n}\n\nfunction canonicalBlob(rawKey: Uint8Array): Uint8Array {\n\tconst blob = new Uint8Array(51);\n\tconst view = new DataView(blob.buffer);\n\tview.setUint32(0, 11);\n\tblob.set(new TextEncoder().encode(\"ssh-ed25519\"), 4);\n\tview.setUint32(15, 32);\n\tblob.set(rawKey, 19);\n\treturn blob;\n}\n\n/**\n * Internal string contract, not an authentication acceptance check. Like the\n * Worker verifier, skip the inner type bytes and ignore trailing wire bytes.\n * atob rejects some encodings accepted by Node's Buffer base64 decoder.\n */\nexport function parseSshEd25519PublicKey(publicKey: string): SshEd25519Parse {\n\treturn parseSshEd25519PublicKeyWithDecoder(publicKey, decodeWire);\n}\n\n/** Internal trusted decoder seam; callers must not use it to decide authentication acceptance. */\nexport function parseSshEd25519PublicKeyWithDecoder(\n\tpublicKey: string,\n\tdecode: (encoded: string) => Uint8Array | null,\n): SshEd25519Parse {\n\tif (typeof publicKey !== \"string\") return { kind: \"other\" };\n\tconst [keyType, keyData] = publicKey.trim().split(/\\s+/);\n\tif (keyType !== \"ssh-ed25519\") return { kind: \"other\" };\n\tif (!keyData) return { kind: \"malformed_ed25519\" };\n\tlet wire: Uint8Array | null;\n\ttry {\n\t\twire = decode(keyData);\n\t} catch {\n\t\treturn { kind: \"malformed_ed25519\" };\n\t}\n\tif (!wire) return { kind: \"malformed_ed25519\" };\n\tconst rawKey = readRawKey(wire);\n\tif (!rawKey) return { kind: \"malformed_ed25519\" };\n\treturn { kind: \"ed25519\", blob: canonicalBlob(rawKey) };\n}\n\n/** SHA-256 hex of the canonical SSH blob; leaves legacy text fingerprints unchanged. */\nexport async function ed25519KeyId(publicKey: string): Promise<string | null> {\n\treturn hashEd25519KeyId(parseSshEd25519PublicKey(publicKey));\n}\n\n/** Internal canonical identity hash, not proof of key possession or authorization. */\nexport async function hashEd25519KeyId(parsed: SshEd25519Parse): Promise<string | null> {\n\tif (parsed.kind !== \"ed25519\") return null;\n\t// Copy to an owned ArrayBuffer for the portable Web Crypto BufferSource API.\n\tconst bytes = new Uint8Array(parsed.blob);\n\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", bytes.buffer);\n\treturn Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n","import { Buffer } from \"node:buffer\";\nimport {\n\thashEd25519KeyId,\n\tparseSshEd25519PublicKeyWithDecoder,\n\ttype SshEd25519Parse,\n} from \"./coordinator-ed25519-key-id.js\";\n\nfunction decodeWireForRevocation(encoded: string): Uint8Array | null {\n\ttry {\n\t\treturn Buffer.from(encoded, \"base64\");\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Metadata only: Buffer aliases do not expand signature acceptance or prove key possession. */\nexport function parseSshEd25519PublicKeyForRevocation(publicKey: string): SshEd25519Parse {\n\treturn parseSshEd25519PublicKeyWithDecoder(publicKey, decodeWireForRevocation);\n}\n\n/** Canonical SSH identity for revocation metadata, not an authorization check. */\nexport async function ed25519KeyIdForRevocation(publicKey: string): Promise<string | null> {\n\treturn hashEd25519KeyId(parseSshEd25519PublicKeyForRevocation(publicKey));\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 { COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES } 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)`;\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/** Shared by first-link writes and exact-assignment status reads. */\nexport const AUTH_DEVICE_CLAIM_LEGACY_COMPATIBLE_SQL = `NOT EXISTS (\n SELECT 1 FROM coordinator_legacy_team_completions c, json_each(${completionJson}, '$.device_decisions') d\n WHERE json_extract(${completionJson}, '$.coordinator_id') = p.coordinator_id AND (\n ((json_extract(d.value, '$.device_id') = p.device_id OR json_extract(d.value, '$.key_fingerprint') = p.fingerprint)\n AND (json_extract(d.value, '$.decision') = 'excluded' OR json_extract(d.value, '$.identity_id') IS NOT p.identity_id))\n OR (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)))))`;\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 { 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 { 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_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)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_device_claims d 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)`;\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.\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\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 { 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 { 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 <= ?`;\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 ? >= 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 (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 (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 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 { 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 {\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 { 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\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\";\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\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}\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>>;\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}\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\tconst c = captureConfig(config);\n\t\tconst i = captureCreateInput(input);\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 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: { identityId: row.identity_id, groupId: row.group_id, deviceId: row.device_id },\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\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 = ?, 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 ${source.sql}`,\n\t\t\tvalues: [\n\t\t\t\ti.completionSecretHash,\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 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 status(row, now);\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\tconst c = captureConfig(config);\n\t\tconst i = captureFinalize(input, c);\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?.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 = connections\n\t\t\t? await connectionRequesterGuard(this.backend, i.identityId, i.signer, c, now)\n\t\t\t: { sql: \"1 = 1\", values: [] };\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]);\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: CoordinatorAuthLinkFinalizeInput,\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.source(i.attemptId, c, now, { currentDevice: true });\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\ttry {\n\t\t\tawait this.backend.batch([\n\t\t\t\t...deviceFinalizeStatements(i, c, now, linkId, keyId, source, connections),\n\t\t\t\t...(connections ? connectionSuccessorStatements(c.coordinatorId, i.attemptId, linkId) : []),\n\t\t\t\tpromoteAuthLinkProfile(c.coordinatorId, i.attemptId, linkId),\n\t\t\t\t...(await initialConnectionFloor(this.backend, c.coordinatorId, linkId)),\n\t\t\t]);\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(\n\t\t\ti,\n\t\t\tc,\n\t\t\tnow,\n\t\t\tlinkId,\n\t\t\tawait this.source(i.attemptId, c, now, { currentDevice: true }),\n\t\t);\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}\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 { CONNECTION_REQUESTER_IDENTITY_SQL } 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_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 */\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\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_ok AS MATERIALIZED (SELECT p.* FROM claim_input p WHERE (${AUTH_DEVICE_CLAIM_CURRENT_SUBJECT_COMPATIBLE_SQL}) AND (${CONNECTION_REQUESTER_IDENTITY_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_COMPATIBLE_SQL})), 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 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))`,\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\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 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\t\t\t\t[c.coordinatorId, i.signer.deviceId, key, ...signerValues(i.signer)],\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","/** 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}\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","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/** 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\nfunction 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\nfunction 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\nfunction 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\nfunction 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\nasync 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\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\tif (row.identity_id !== identityId) return { ...derived, state: \"linked\", account: 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 { ...derived, state: \"linked\", account };\n}\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 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 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\"}, '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 SELECT p.identity_id, NULL, NULL, NULL, 1, 'device_claim' FROM claim_input p\n WHERE NOT EXISTS (SELECT 1 FROM claims) AND NOT EXISTS (SELECT 1 FROM controller)\n AND ${AUTH_DEVICE_CLAIM_ELIGIBLE_SQL})\n SELECT a.identity_id,a.link_id,a.issuer,a.valid,a.authority,\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\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\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 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);\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\tprivate async startLink(\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 source = await this.source(i.attemptId, c, now);\n\t\tconst claimSource = await this.source(i.attemptId, c, now, \"coordinator_auth_link_attempts\");\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 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 { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport { DEVICE_REVOCATION_SUBJECT_EXISTS_SQL } from \"./coordinator-device-revocation.js\";\nimport { COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_GROUPS } from \"./coordinator-legacy-team-completion.js\";\n\n/** Internal transport grants only: these confer no Team/Project access. */\nexport interface CoordinatorIdentityGroupGrant {\n\treadonly coordinator_id: string;\n\treadonly identity_id: string;\n\treadonly group_id: string;\n\treadonly status: \"active\" | \"revoked\";\n\treadonly revision: number;\n\treadonly source_kind: \"controller_attestation\";\n\treadonly source_receipt_id: string;\n\treadonly created_at: string;\n\treadonly revoked_at: string | null;\n}\n\nexport interface CoordinatorIdentityGroupGrantIssueInput {\n\tcoordinatorId: string;\n\tattestationId: string;\n}\nexport interface CoordinatorIdentityGroupGrantScope {\n\tcoordinatorId: string;\n\tidentityId: string;\n}\nexport interface CoordinatorIdentityGroupGrantRevokeInput\n\textends CoordinatorIdentityGroupGrantScope {\n\tgroupId: string;\n\texpectedRevision: number;\n}\nexport type CoordinatorIdentityGroupGrantIssueResult =\n\t| { kind: \"created\" | \"existing\"; grant: CoordinatorIdentityGroupGrant }\n\t| { kind: \"rejected\"; error: \"invalid_grant_input\" | \"grant_authority_unavailable\" };\n\n/** Future authenticated operators own invocation; no routes or automatic issuance. */\nexport interface CoordinatorIdentityGroupGrantStore {\n\tissueIdentityGroupGrantFromControllerAttestation(\n\t\tinput: CoordinatorIdentityGroupGrantIssueInput,\n\t): Promise<CoordinatorIdentityGroupGrantIssueResult>;\n\tlistIdentityGroupGrantRevisions(\n\t\tinput: CoordinatorIdentityGroupGrantScope,\n\t): Promise<CoordinatorIdentityGroupGrant[]>;\n\trevokeIdentityGroupGrant(input: CoordinatorIdentityGroupGrantRevokeInput): Promise<boolean>;\n}\n\n/** Capture once before async I/O; do not invoke getters or accept inherited IDs. */\nexport function captureIdentityGroupGrantInput(\n\tinput: unknown,\n\tfields: readonly string[],\n): Record<string, string | number> | null {\n\ttry {\n\t\tif (!input || typeof input !== \"object\" || Array.isArray(input)) return null;\n\t\tconst captured: Record<string, string | number> = {};\n\t\tfor (const field of fields) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(input, field);\n\t\t\tif (!descriptor || !Object.hasOwn(descriptor, \"value\")) return null;\n\t\t\tconst value: unknown = descriptor.value;\n\t\t\tif (field === \"expectedRevision\") {\n\t\t\t\tif (\n\t\t\t\t\ttypeof value !== \"number\" ||\n\t\t\t\t\t!Number.isSafeInteger(value) ||\n\t\t\t\t\tvalue < 1 ||\n\t\t\t\t\tvalue >= Number.MAX_SAFE_INTEGER\n\t\t\t\t)\n\t\t\t\t\treturn null;\n\t\t\t} else if (!isAuthControllerId(value)) return null;\n\t\t\tcaptured[field] = value as string | number;\n\t\t}\n\t\treturn captured;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nconst GRANT_FIELDS = [\n\t\"coordinator_id\",\n\t\"identity_id\",\n\t\"group_id\",\n\t\"status\",\n\t\"revision\",\n\t\"source_kind\",\n\t\"source_receipt_id\",\n\t\"created_at\",\n\t\"revoked_at\",\n] as const;\n\nfunction isCanonicalGrant(row: CoordinatorIdentityGroupGrant): boolean {\n\tif (!row) return false;\n\tif (\n\t\t![row.coordinator_id, row.identity_id, row.group_id, row.source_receipt_id].every(\n\t\t\tisAuthControllerId,\n\t\t)\n\t)\n\t\treturn false;\n\tif (\n\t\trow.source_kind !== \"controller_attestation\" ||\n\t\t!Number.isSafeInteger(row.revision) ||\n\t\trow.revision < 1\n\t)\n\t\treturn false;\n\tif (typeof row.created_at !== \"string\" || row.created_at.length === 0) return false;\n\tif (row.status === \"active\") return row.revoked_at === null;\n\treturn (\n\t\trow.status === \"revoked\" && typeof row.revoked_at === \"string\" && row.revoked_at.length > 0\n\t);\n}\n\nfunction canonicalRevisionSet(\n\trows: readonly CoordinatorIdentityGroupGrant[],\n): Map<string, CoordinatorIdentityGroupGrant> | null {\n\t// Reuse the existing coordinator group-set limit; never truncate authority sets.\n\tif (\n\t\t!Array.isArray(rows) ||\n\t\trows.length === 0 ||\n\t\trows.length > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_GROUPS\n\t)\n\t\treturn null;\n\tconst result = new Map<string, CoordinatorIdentityGroupGrant>();\n\tfor (const row of rows) {\n\t\tif (!isCanonicalGrant(row)) return null;\n\t\tif (\n\t\t\trow.coordinator_id !== rows[0].coordinator_id ||\n\t\t\trow.identity_id !== rows[0].identity_id ||\n\t\t\tresult.has(row.group_id)\n\t\t)\n\t\t\treturn null;\n\t\tresult.set(row.group_id, row);\n\t}\n\treturn result;\n}\n\n/** Snapshot equality only, NOT authorization for a future enrollment write. */\nexport function compareIdentityGroupGrantRevisions(\n\texpected: readonly CoordinatorIdentityGroupGrant[],\n\tcurrent: readonly CoordinatorIdentityGroupGrant[],\n): boolean {\n\tconst left = canonicalRevisionSet(expected);\n\tconst right = canonicalRevisionSet(current);\n\tif (!left || !right || left.size !== right.size) return false;\n\tfor (const [groupId, row] of left) {\n\t\tconst other = right.get(groupId);\n\t\tif (!other || GRANT_FIELDS.some((field) => row[field] !== other[field])) return false;\n\t}\n\treturn true;\n}\n\n// Independent tombstones: deliberately no enrollment/controller foreign keys.\nexport const IDENTITY_GROUP_GRANT_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS coordinator_identity_group_grants (\n coordinator_id TEXT NOT NULL,\n identity_id TEXT NOT NULL,\n group_id TEXT NOT NULL,\n status TEXT NOT NULL CHECK (status IN ('active', 'revoked')),\n revision INTEGER NOT NULL CHECK (typeof(revision) = 'integer' AND revision BETWEEN 1 AND 9007199254740991),\n source_kind TEXT NOT NULL CHECK (source_kind = 'controller_attestation'),\n source_receipt_id TEXT NOT NULL,\n created_at TEXT NOT NULL,\n revoked_at TEXT,\n PRIMARY KEY (coordinator_id, identity_id, group_id),\n CHECK ((status = 'active' AND revoked_at IS NULL) OR (status = 'revoked' AND revoked_at IS NOT NULL))\n);`;\n\nconst CURRENT_CONTROLLER_FROM_SQL = `\n FROM coordinator_auth_controller_attestations a\n JOIN enrolled_devices e ON e.group_id = a.group_id AND e.device_id = a.device_id\n JOIN groups g ON g.group_id = a.group_id`;\nconst CURRENT_CONTROLLER_EVIDENCE_SQL = `\n a.coordinator_id = ? AND a.attestation_id = ? AND a.revoked_at IS NULL\n AND g.archived_at IS NULL AND e.enabled = 1\n AND e.public_key = a.public_key AND e.fingerprint = a.fingerprint\n AND e.identity_id IS a.enrollment_identity_id\n AND (e.identity_id IS NULL OR e.identity_id = a.identity_id)`;\n\n/** Read the actual current enrollment, never caller-provided key metadata. */\nexport const IDENTITY_GROUP_GRANT_SOURCE_SQL = `\n SELECT e.* ${CURRENT_CONTROLLER_FROM_SQL} WHERE ${CURRENT_CONTROLLER_EVIDENCE_SQL}`;\n\n// Pin the hashed enrollment across D1 awaits; both issuance and retry recheck revocation.\nconst CURRENT_CONTROLLER_WHERE_SQL = `${CURRENT_CONTROLLER_EVIDENCE_SQL}\n AND e.group_id = ? AND e.device_id = ? AND e.public_key = ?\n AND e.fingerprint = ? AND e.identity_id IS ?\n AND NOT ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}`;\n\nexport const IDENTITY_GROUP_GRANT_INSERT_SQL = `\n INSERT INTO coordinator_identity_group_grants (\n coordinator_id, identity_id, group_id, status, revision, source_kind, source_receipt_id, created_at, revoked_at\n ) SELECT a.coordinator_id, a.identity_id, a.group_id, 'active', 1, 'controller_attestation', a.review_receipt_id, ?, NULL\n ${CURRENT_CONTROLLER_FROM_SQL} WHERE ${CURRENT_CONTROLLER_WHERE_SQL}\n ON CONFLICT (coordinator_id, identity_id, group_id) DO NOTHING\n RETURNING *`;\n\n/** Retry checks the grant and exact current evidence together in ONE read. */\nexport const IDENTITY_GROUP_GRANT_RETRY_SQL = `\n SELECT r.* ${CURRENT_CONTROLLER_FROM_SQL}\n JOIN coordinator_identity_group_grants r ON r.coordinator_id = a.coordinator_id\n AND r.identity_id = a.identity_id AND r.group_id = a.group_id\n WHERE ${CURRENT_CONTROLLER_WHERE_SQL}\n AND r.status = 'active' AND r.source_kind = 'controller_attestation'\n AND r.source_receipt_id = a.review_receipt_id`;\n\n/** Listing intentionally does not depend on the old controller device/key. */\nexport const IDENTITY_GROUP_GRANT_LIST_SQL = `\n SELECT * FROM coordinator_identity_group_grants\n WHERE coordinator_id = ? AND identity_id = ? ORDER BY group_id COLLATE BINARY`;\nexport const IDENTITY_GROUP_GRANT_REVOKE_SQL = `\n UPDATE coordinator_identity_group_grants SET status = 'revoked', revision = revision + 1, revoked_at = ?\n WHERE coordinator_id = ? AND identity_id = ? AND group_id = ? AND status = 'active' AND revision = ?`;\n","import { DEVICE_REVOCATION_SUBJECT_EXISTS_SQL } from \"./coordinator-device-revocation.js\";\nimport type { projectInviteGuardEvidence } from \"./coordinator-project-invite-guards.js\";\nimport type {\n\tCoordinatorConsumeProjectInviteInput,\n\tCoordinatorEnrollDeviceInput,\n} from \"./coordinator-store-contract.js\";\n\nexport function captureLegacyProjectInviteInput(\n\tinput: CoordinatorConsumeProjectInviteInput,\n): CoordinatorConsumeProjectInviteInput {\n\tif (!input || typeof input !== \"object\" || Array.isArray(input)) throw new Error(\"invalid_input\");\n\tconst captured: Record<string, unknown> = {};\n\tfor (const field of [\n\t\t\"token\",\n\t\t\"operationId\",\n\t\t\"deviceId\",\n\t\t\"publicKey\",\n\t\t\"fingerprint\",\n\t\t\"recipientActorId\",\n\t\t\"recipientDisplayName\",\n\t\t\"deviceDisplayName\",\n\t\t\"now\",\n\t]) {\n\t\tconst descriptor = legacyEnrollmentDescriptor(input, field);\n\t\tif (descriptor && !(\"value\" in descriptor)) throw new Error(\"invalid_input\");\n\t\tconst value = descriptor?.value;\n\t\tif (typeof value !== \"string\") throw new Error(\"invalid_input\");\n\t\tcaptured[field] = value;\n\t}\n\treturn captured as unknown as CoordinatorConsumeProjectInviteInput;\n}\n\n/** Global ownership metadata, not proof. Bind actual device ID and canonical key ID (or null). */\nexport const DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL = `EXISTS (\nSELECT 1 FROM coordinator_device_ownership_bindings WHERE device_id = ? OR key_id = ?)`;\n\n/** Project actor labels never prove ownership; only the target enrollment is mutated. */\nexport function legacyProjectInviteOwnershipEvidence(\n\tevidence: ReturnType<typeof projectInviteGuardEvidence>,\n\tdeviceId: string,\n\tkeyIds: { incoming: string | null; current: string | null },\n) {\n\tconst ownershipSql = `${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL} OR ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}`;\n\tconst ownershipValues = [deviceId, keyIds.incoming, deviceId, keyIds.current];\n\treturn {\n\t\t...evidence,\n\t\townershipSql,\n\t\townershipValues,\n\t\teligibilitySql: `${evidence.eligibilitySql} AND NOT (${ownershipSql})`,\n\t\teligibilityValues: [...evidence.eligibilityValues, ...ownershipValues],\n\t\tboundEligibilitySql: `${evidence.boundEligibilitySql} AND NOT (${ownershipSql})`,\n\t\tboundEligibilityValues: [...evidence.boundEligibilityValues, ...ownershipValues],\n\t};\n}\n\nexport const LEGACY_DEVICE_DENIAL_SQL = `SELECT CASE\nWHEN ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL} THEN 'device_revoked'\nWHEN ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL} THEN 'device_ownership_requires_verified_identity'\nELSE 'invite_identity_conflict' END AS denial`;\n\n/** Bind captured public key (null for absence), group/device, then group/device/public key. */\nexport const LEGACY_ENROLLMENT_SOURCE_MATCH_SQL = `((? IS NULL AND NOT EXISTS (\nSELECT 1 FROM enrolled_devices WHERE group_id = ? AND device_id = ?)) OR EXISTS (\nSELECT 1 FROM enrolled_devices WHERE group_id = ? AND device_id = ? AND public_key = ?))`;\n\n/** Incoming revocation, incoming ownership, captured current ownership, then source tuple.\n * Source drift deliberately falls through the denial validator to the unavailable error.\n */\nexport const LEGACY_ENROLLMENT_DENIAL_SQL = `SELECT CASE\nWHEN ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL} THEN 'device_revoked'\nWHEN ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL} OR ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}\nTHEN 'device_ownership_requires_verified_identity'\nWHEN NOT ${LEGACY_ENROLLMENT_SOURCE_MATCH_SQL} THEN 'device_ownership_authorization_unavailable'\nELSE 'invite_identity_conflict' END AS denial`;\n\nexport const LEGACY_ENROLLMENT_WRITE_SQL = `INSERT INTO enrolled_devices(\ngroup_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at\n) SELECT ?, ?, ?, ?, ?, ?, 1, ?\nWHERE NOT ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}\nAND NOT ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}\nAND NOT ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}\nAND ${LEGACY_ENROLLMENT_SOURCE_MATCH_SQL}\nON CONFLICT(group_id, device_id) DO UPDATE SET\npublic_key = excluded.public_key, fingerprint = excluded.fingerprint,\nidentity_id = COALESCE(enrolled_devices.identity_id, excluded.identity_id),\ndisplay_name = excluded.display_name, enabled = 1\nWHERE (excluded.identity_id IS NULL OR enrolled_devices.identity_id IS NULL\nOR enrolled_devices.identity_id = excluded.identity_id)\nAND NOT ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}\nAND NOT ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}\nAND enrolled_devices.public_key = ?`;\n\nexport function captureLegacyEnrollmentPublicKey(row: unknown): string | null {\n\tif (row === null) return null;\n\tif (!row || typeof row !== \"object\")\n\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\tconst descriptor = Object.getOwnPropertyDescriptor(row, \"public_key\");\n\tif (!descriptor || !(\"value\" in descriptor) || typeof descriptor.value !== \"string\") {\n\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t}\n\treturn descriptor.value;\n}\n\nexport function captureLegacyEnrollment(\n\tgroupId: string,\n\tinput: CoordinatorEnrollDeviceInput,\n): CoordinatorEnrollDeviceInput {\n\tif (!input || typeof input !== \"object\" || Array.isArray(input)) throw new Error(\"invalid_input\");\n\tconst captured: Record<string, unknown> = {};\n\tfor (const field of [\"deviceId\", \"publicKey\", \"fingerprint\", \"identityId\", \"displayName\"]) {\n\t\tconst descriptor = legacyEnrollmentDescriptor(input, field);\n\t\tif (descriptor && !(\"value\" in descriptor)) throw new Error(\"invalid_input\");\n\t\tcaptured[field] = descriptor?.value;\n\t}\n\tassertLegacyDeviceScope(groupId, captured.deviceId);\n\tif (\n\t\ttypeof captured.publicKey !== \"string\" ||\n\t\ttypeof captured.fingerprint !== \"string\" ||\n\t\t(captured.identityId != null && typeof captured.identityId !== \"string\") ||\n\t\t(captured.displayName != null && typeof captured.displayName !== \"string\")\n\t)\n\t\tthrow new Error(\"invalid_input\");\n\treturn captured as unknown as CoordinatorEnrollDeviceInput;\n}\n\nfunction legacyEnrollmentDescriptor(input: object, field: string): PropertyDescriptor | undefined {\n\ttry {\n\t\treturn Object.getOwnPropertyDescriptor(input, field);\n\t} catch {\n\t\tthrow new Error(\"invalid_input\");\n\t}\n}\n\nexport function assertLegacyDeviceScope(groupId: unknown, deviceId: unknown): void {\n\tif (typeof groupId !== \"string\" || typeof deviceId !== \"string\") throw new Error(\"invalid_input\");\n}\n\nexport function legacyDeviceWriteChanges(result: unknown): number {\n\tif (!result || typeof result !== \"object\" || (\"success\" in result && result.success === false)) {\n\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t}\n\tlet changes: unknown;\n\tif (\n\t\t\"meta\" in result &&\n\t\tresult.meta &&\n\t\ttypeof result.meta === \"object\" &&\n\t\t\"changes\" in result.meta\n\t) {\n\t\tchanges = result.meta.changes;\n\t}\n\tif (typeof changes !== \"number\" || !Number.isSafeInteger(changes) || changes < 0 || changes > 1) {\n\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t}\n\treturn changes;\n}\n\nexport function legacyDeviceDenial(row: unknown): string {\n\tif (\n\t\trow &&\n\t\ttypeof row === \"object\" &&\n\t\t!(\"success\" in row && row.success === false) &&\n\t\t\"denial\" in row\n\t) {\n\t\tconst denial = row.denial;\n\t\tif (\n\t\t\tdenial === \"device_revoked\" ||\n\t\t\tdenial === \"device_ownership_requires_verified_identity\" ||\n\t\t\tdenial === \"invite_identity_conflict\"\n\t\t)\n\t\t\treturn denial;\n\t}\n\tthrow new Error(\"device_ownership_authorization_unavailable\");\n}\n\nexport function legacyDeviceAuthorizationFailure(error: unknown): never {\n\tif (\n\t\terror instanceof Error &&\n\t\t[\n\t\t\t\"device_revoked\",\n\t\t\t\"device_ownership_requires_verified_identity\",\n\t\t\t\"invite_identity_conflict\",\n\t\t].includes(error.message)\n\t)\n\t\tthrow error;\n\tthrow new Error(\"device_ownership_authorization_unavailable\");\n}\n","import { DEVICE_REVOCATION_SUBJECT_EXISTS_SQL } from \"./coordinator-device-revocation.js\";\nimport {\n\tDEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL,\n\tLEGACY_ENROLLMENT_SOURCE_MATCH_SQL,\n} from \"./coordinator-legacy-device-ownership.js\";\nimport type {\n\tCoordinatorEnrollment,\n\tCoordinatorJoinRequest,\n} from \"./coordinator-store-contract.js\";\n\nexport const JOIN_REVIEW_COLUMNS = `request_id, group_id, device_id, public_key, fingerprint,\n display_name, token, status, created_at, reviewed_at, reviewed_by`;\n\n/** Evidence captured before hashing must remain current at every approval writer. */\nexport function joinReviewGuardEvidence(\n\trow: CoordinatorJoinRequest & { public_key: string },\n\tseed: CoordinatorEnrollment | null,\n\tkeys: { recipient: string | null; seed: string | null; current: string | null },\n\tcurrentPublicKey: string | null,\n) {\n\tconst revocationSql = `${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL} OR ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}`;\n\tconst revocationValues = [row.device_id, keys.recipient, seed?.device_id ?? null, keys.seed];\n\t// Reviewer/seed identity is not recipient ownership proof. Retain the old key even after upsert.\n\tconst ownershipSql = `${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL} OR ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}`;\n\tconst ownershipValues = [row.device_id, keys.recipient, row.device_id, keys.current];\n\tconst sourceValues = [\n\t\tcurrentPublicKey,\n\t\trow.group_id,\n\t\trow.device_id,\n\t\trow.group_id,\n\t\trow.device_id,\n\t\tcurrentPublicKey,\n\t];\n\tconst tupleSql = `EXISTS (SELECT 1 FROM coordinator_join_requests jr\n WHERE jr.request_id = ? AND jr.group_id = ? AND jr.device_id = ?\n AND jr.public_key = ? AND jr.fingerprint = ? AND jr.display_name IS ?\n AND jr.token = ? AND jr.created_at = ?)`;\n\tconst tupleValues = [\n\t\trow.request_id,\n\t\trow.group_id,\n\t\trow.device_id,\n\t\trow.public_key,\n\t\trow.fingerprint,\n\t\trow.display_name ?? null,\n\t\trow.token,\n\t\trow.created_at,\n\t];\n\tconst seedSql = `(? = 0 OR EXISTS (SELECT 1 FROM enrolled_devices se\n WHERE se.group_id = ? AND se.device_id = ? AND se.public_key = ?\n AND se.fingerprint = ? AND se.enabled = 1))`;\n\treturn {\n\t\trevocationSql,\n\t\trevocationValues,\n\t\townershipSql,\n\t\townershipValues,\n\t\tsourceSql: LEGACY_ENROLLMENT_SOURCE_MATCH_SQL,\n\t\tsourceValues,\n\t\teligibilitySql: `${tupleSql} AND ${seedSql} AND NOT (${revocationSql}) AND NOT (${ownershipSql})`,\n\t\teligibilityValues: [\n\t\t\t...tupleValues,\n\t\t\tseed ? 1 : 0,\n\t\t\trow.group_id,\n\t\t\tseed?.device_id ?? null,\n\t\t\tseed?.public_key ?? null,\n\t\t\tseed?.fingerprint ?? null,\n\t\t\t...revocationValues,\n\t\t\t...ownershipValues,\n\t\t],\n\t};\n}\n\nexport function joinReviewResultChanges(result: unknown): number {\n\tif (\n\t\t!result ||\n\t\ttypeof result !== \"object\" ||\n\t\t(\"success\" in result && result.success === false) ||\n\t\t!(\"meta\" in result) ||\n\t\t!result.meta ||\n\t\ttypeof result.meta !== \"object\" ||\n\t\t!(\"changes\" in result.meta) ||\n\t\t!Number.isSafeInteger(result.meta.changes) ||\n\t\t(result.meta.changes as number) < 0\n\t)\n\t\tthrow new Error(\"join_review_incomplete\");\n\treturn result.meta.changes as number;\n}\n\nexport function assertJoinReviewConfirmation(result: unknown): void {\n\tif (\n\t\t!result ||\n\t\ttypeof result !== \"object\" ||\n\t\t(\"success\" in result && result.success === false) ||\n\t\t!(\"results\" in result) ||\n\t\t!Array.isArray(result.results) ||\n\t\tresult.results.length !== 1 ||\n\t\tresult.results[0]?.confirmed !== 1\n\t) {\n\t\tthrow new Error(\"join_review_incomplete\");\n\t}\n}\n","import type {\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","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.\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\tJOIN 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 type {\n\tCoordinatorEnrollment,\n\tCoordinatorScope,\n\tCoordinatorScopeAuthorizationInput,\n\tCoordinatorScopeAuthorizationResult,\n\tCoordinatorScopeMembership,\n} from \"./coordinator-store-contract.js\";\n\nexport const SCOPE_FIELDS = [\n\t\"scope_id\",\n\t\"label\",\n\t\"kind\",\n\t\"authority_type\",\n\t\"coordinator_id\",\n\t\"group_id\",\n\t\"manifest_issuer_device_id\",\n\t\"membership_epoch\",\n\t\"manifest_hash\",\n\t\"status\",\n\t\"created_at\",\n\t\"updated_at\",\n] as const;\nexport const MEMBERSHIP_FIELDS = [\n\t\"scope_id\",\n\t\"device_id\",\n\t\"role\",\n\t\"status\",\n\t\"membership_epoch\",\n\t\"coordinator_id\",\n\t\"group_id\",\n\t\"manifest_issuer_device_id\",\n\t\"manifest_hash\",\n\t\"signed_manifest_json\",\n\t\"updated_at\",\n] as const;\nexport const 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;\n\nconst NULLABLE_FIELDS = new Set([\n\t\"coordinator_id\",\n\t\"group_id\",\n\t\"manifest_issuer_device_id\",\n\t\"manifest_hash\",\n\t\"signed_manifest_json\",\n\t\"identity_id\",\n\t\"display_name\",\n]);\nfunction text(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length > 0 && !value.includes(\"\\0\");\n}\n\nexport function captureScopeAuthorizationInput(\n\traw: CoordinatorScopeAuthorizationInput,\n): CoordinatorScopeAuthorizationInput {\n\tconst group = Object.getOwnPropertyDescriptor(raw, \"groupId\");\n\tconst scope = Object.getOwnPropertyDescriptor(raw, \"scopeId\");\n\tif (\n\t\t!group ||\n\t\t!scope ||\n\t\t!(\"value\" in group) ||\n\t\t!(\"value\" in scope) ||\n\t\t!text(group.value) ||\n\t\t!text(scope.value)\n\t)\n\t\tthrow new Error(\"scope_authorization_unavailable\");\n\treturn { groupId: group.value, scopeId: scope.value };\n}\n\n/** Reject malformed storage instead of treating it as an empty snapshot. */\nexport function requireScopeAuthorizationRecord(row: unknown, fields: readonly string[]): void {\n\tif (!row || typeof row !== \"object\" || Array.isArray(row))\n\t\tthrow new Error(\"scope_authorization_unavailable\");\n\tconst record = row as Record<string, unknown>;\n\tfor (const field of fields) {\n\t\tif (!validField(field, record[field])) throw new Error(\"scope_authorization_unavailable\");\n\t}\n}\n\nfunction validField(field: string, value: unknown): boolean {\n\tif (field === \"membership_epoch\" || field === \"enabled\")\n\t\treturn Number.isSafeInteger(value) && (value as number) >= 0;\n\t// Key parsing decides whether string evidence is usable, including empty legacy text.\n\tif (field === \"public_key\") return typeof value === \"string\";\n\tif (field === \"display_name\" || field === \"identity_id\")\n\t\treturn value === null || (typeof value === \"string\" && !value.includes(\"\\0\"));\n\tif (NULLABLE_FIELDS.has(field) && value === null) return true;\n\treturn text(value);\n}\n\nexport function scopeAuthorizationError(\n\tscope: CoordinatorScope,\n\tgroupId: string,\n): Extract<CoordinatorScopeAuthorizationResult, { kind: \"rejected\" }>[\"error\"] | null {\n\tif (scope.group_id !== groupId || scope.authority_type !== \"coordinator\")\n\t\treturn \"scope_source_mismatch\";\n\tif (scope.status !== \"active\") return \"scope_inactive\";\n\treturn null;\n}\n\n/** Null legacy member source fields inherit the explicit scope source, never owner/issuer authority.\n * An unbound scope group cannot authorize; a null coordinator ID preserves group-bound legacy rows.\n * Neither source metadata nor roles and labels infer tenant ownership or account-session proof. */\nexport function isCurrentScopeMember(\n\tscope: CoordinatorScope,\n\tmember: CoordinatorScopeMembership,\n): boolean {\n\tif (\n\t\tmember.scope_id !== scope.scope_id ||\n\t\tmember.status !== \"active\" ||\n\t\tmember.membership_epoch < scope.membership_epoch\n\t)\n\t\treturn false;\n\treturn (\n\t\t[\"group_id\", \"coordinator_id\", \"manifest_issuer_device_id\", \"manifest_hash\"] as const\n\t).every((field) => member[field] === null || member[field] === scope[field]);\n}\n\nexport interface CapturedScopeMember {\n\tmembership: CoordinatorScopeMembership;\n\tenrollment: CoordinatorEnrollment;\n\tkeyId: string;\n}\n\nexport function parseScopeAuthorizationMembers(\n\traw: unknown,\n\tcaptured: CapturedScopeMember[],\n): CapturedScopeMember[] {\n\tif (typeof raw !== \"string\") throw new Error(\"scope_authorization_unavailable\");\n\tconst members: unknown = JSON.parse(raw);\n\tif (!Array.isArray(members)) throw new Error(\"scope_authorization_unavailable\");\n\tconst expected = new Set(captured.map((member) => JSON.stringify(member)));\n\tfor (const member of members) {\n\t\tconst encoded = JSON.stringify(member);\n\t\tif (!expected.delete(encoded)) throw new Error(\"scope_authorization_unavailable\");\n\t}\n\treturn (members as CapturedScopeMember[]).sort(compareMemberDeviceIds);\n}\n\nfunction compareMemberDeviceIds(left: CapturedScopeMember, right: CapturedScopeMember): number {\n\tconst leftId = left.membership.device_id;\n\tconst rightId = right.membership.device_id;\n\tif (leftId < rightId) return -1;\n\tif (leftId > rightId) return 1;\n\treturn 0;\n}\n\nfunction pinned(alias: string, fields: readonly string[], path: string): string {\n\treturn fields\n\t\t.map((field) => `${alias}.${field} IS json_extract(captured.value, '$.${path}${field}')`)\n\t\t.join(\" AND \");\n}\n\n/** Final reads pin every captured DTO field and canonical revocation subject; no replacement key is promoted. */\nexport const READ_CURRENT_SCOPE_SQL = `SELECT s.* FROM json_each(?) captured\nJOIN coordinator_scopes s ON ${pinned(\"s\", SCOPE_FIELDS, \"\")}\nJOIN groups g ON g.group_id = s.group_id WHERE g.archived_at IS NULL AND s.status = 'active'\nAND s.authority_type = 'coordinator'`;\nexport const READ_CURRENT_SCOPE_MEMBERS_SQL = `SELECT captured.value FROM json_each(?) captured\nJOIN coordinator_scope_memberships m ON ${pinned(\"m\", MEMBERSHIP_FIELDS, \"membership.\")}\nJOIN enrolled_devices e ON ${pinned(\"e\", ENROLLMENT_FIELDS, \"enrollment.\")}\nWHERE e.enabled = 1 AND m.status = 'active'\nAND NOT EXISTS (SELECT 1 FROM coordinator_device_revocations r WHERE\n(r.subject_kind = 'device_id' AND r.subject_value = e.device_id) OR\n(r.subject_kind = 'ed25519_key' AND r.subject_value = json_extract(captured.value, '$.keyId')))\nORDER BY m.device_id ASC`;\n\nexport const READ_SCOPE_AUTHORIZATION_SQL = `WITH current_scope AS (${READ_CURRENT_SCOPE_SQL})\nSELECT current_scope.*, (SELECT json_group_array(json(value)) FROM\n(${READ_CURRENT_SCOPE_MEMBERS_SQL})) AS members_json FROM current_scope`;\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}\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\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\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","export const SCOPE_MEMBERSHIP_REVOCATION_LIMITATION =\n\t\"Revocation blocks future sync for this Space. It does not remove data already copied to the revoked device; offline devices, backups, copied databases, malicious peers, or old versions may retain data.\";\n\nexport interface ScopeMembershipRevocationNotice {\n\tscope_id: string;\n\tdevice_id: string;\n\tmembership_epoch: number | null;\n\tprevents_future_sync: true;\n\tdeletes_already_copied_data: false;\n\tmessage: string;\n}\n\nexport interface ScopeMembershipEpochStatus {\n\tmembership_epoch: number | null;\n\trequired_epoch: number | null;\n\tstale: boolean;\n\treason: \"current\" | \"stale_epoch\" | \"unknown_epoch\";\n}\n\nexport function scopeMembershipEpochStatus(input: {\n\tmembershipEpoch?: number | null;\n\trequiredEpoch?: number | null;\n}): ScopeMembershipEpochStatus {\n\tconst membershipEpoch = Number.isFinite(input.membershipEpoch)\n\t\t? Number(input.membershipEpoch)\n\t\t: null;\n\tconst requiredEpoch = Number.isFinite(input.requiredEpoch) ? Number(input.requiredEpoch) : null;\n\tif (membershipEpoch == null || requiredEpoch == null) {\n\t\treturn {\n\t\t\tmembership_epoch: membershipEpoch,\n\t\t\trequired_epoch: requiredEpoch,\n\t\t\tstale: false,\n\t\t\treason: \"unknown_epoch\",\n\t\t};\n\t}\n\treturn {\n\t\tmembership_epoch: membershipEpoch,\n\t\trequired_epoch: requiredEpoch,\n\t\tstale: membershipEpoch < requiredEpoch,\n\t\treason: membershipEpoch < requiredEpoch ? \"stale_epoch\" : \"current\",\n\t};\n}\n\nexport function explainScopeMembershipRevocation(input: {\n\tscopeId: string;\n\tdeviceId: string;\n\tmembershipEpoch?: number | null;\n}): ScopeMembershipRevocationNotice {\n\treturn {\n\t\tscope_id: input.scopeId,\n\t\tdevice_id: input.deviceId,\n\t\tmembership_epoch: Number.isFinite(input.membershipEpoch) ? Number(input.membershipEpoch) : null,\n\t\tprevents_future_sync: true,\n\t\tdeletes_already_copied_data: false,\n\t\tmessage: SCOPE_MEMBERSHIP_REVOCATION_LIMITATION,\n\t};\n}\n","export const DEFAULT_TIME_WINDOW_S = 300;\n","import { createHash } from \"node:crypto\";\nimport { resolve } from \"node:path\";\nimport { cleanProjectIdentity, isMalformedProjectIdentity } from \"./project-identity.js\";\n\nexport type WorkspaceIdentitySource =\n\t| \"git_remote\"\n\t| \"git_remote_branch\"\n\t| \"git_repository\"\n\t| \"cwd\"\n\t| \"workspace_id\"\n\t| \"unmapped\";\n\nexport interface WorkspaceIdentityInput {\n\tgitRemote?: string | null;\n\tgitBranch?: string | null;\n\trepositoryIdentity?: string | null;\n\tcwd?: string | null;\n\tworkspaceId?: string | null;\n\tproject?: string | null;\n\tbranchScoped?: boolean;\n\tallowRepositoryCwdFallback?: boolean;\n}\n\nexport interface CanonicalWorkspaceIdentity {\n\tvalue: string;\n\tsource: WorkspaceIdentitySource;\n\tdisplayProject: string | null;\n}\n\nfunction normalizeSlash(value: string): string {\n\tconst normalized = value.trim().replaceAll(\"\\\\\", \"/\").replace(/\\/+$/, \"\");\n\treturn normalized || value.trim();\n}\n\nfunction normalizeCwd(cwd: string): string {\n\t// Callers should pass an already-realpathed session cwd when symlink\n\t// resolution matters; this pure helper only normalizes path syntax.\n\treturn normalizeSlash(resolve(cwd));\n}\n\nfunction unmappedIdentity(input: WorkspaceIdentityInput): string {\n\tconst validSeed = [input.cwd, input.project, input.workspaceId]\n\t\t.map((value) => cleanProjectIdentity(value))\n\t\t.find((value) => value !== null);\n\tconst identityTuple = [\n\t\tinput.gitRemote,\n\t\tinput.gitBranch,\n\t\tinput.cwd,\n\t\tinput.project,\n\t\tinput.workspaceId,\n\t].map((value) => (typeof value === \"string\" ? value.trim() : null));\n\tlet seed = validSeed ?? \"unknown\";\n\tif (!validSeed && identityTuple.some(isMalformedProjectIdentity)) {\n\t\tseed = JSON.stringify(identityTuple);\n\t}\n\tconst digest = createHash(\"sha256\").update(seed, \"utf8\").digest(\"hex\");\n\treturn `unmapped:${digest}`;\n}\n\nexport function canonicalWorkspaceIdentity(\n\tinput: WorkspaceIdentityInput,\n): CanonicalWorkspaceIdentity {\n\tconst gitRemote = cleanProjectIdentity(input.gitRemote);\n\tconst gitBranch = cleanProjectIdentity(input.gitBranch);\n\tconst repositoryIdentity = cleanProjectIdentity(input.repositoryIdentity);\n\tconst cwd = cleanProjectIdentity(input.cwd);\n\tconst workspaceId = cleanProjectIdentity(input.workspaceId);\n\tconst project = cleanProjectIdentity(input.project);\n\n\tif (repositoryIdentity && !input.branchScoped) {\n\t\treturn {\n\t\t\tvalue: normalizeSlash(repositoryIdentity),\n\t\t\tsource: \"git_repository\",\n\t\t\tdisplayProject: project,\n\t\t};\n\t}\n\n\tif (gitRemote) {\n\t\tconst normalizedRemote = normalizeSlash(gitRemote);\n\t\tif (input.branchScoped && gitBranch) {\n\t\t\treturn {\n\t\t\t\tvalue: `${normalizedRemote}:${gitBranch}`,\n\t\t\t\tsource: \"git_remote_branch\",\n\t\t\t\tdisplayProject: project,\n\t\t\t};\n\t\t}\n\t\treturn { value: normalizedRemote, source: \"git_remote\", displayProject: project };\n\t}\n\n\tif (repositoryIdentity) {\n\t\treturn {\n\t\t\tvalue: normalizeSlash(repositoryIdentity),\n\t\t\tsource: \"git_repository\",\n\t\t\tdisplayProject: project,\n\t\t};\n\t}\n\n\tif (cwd) {\n\t\treturn { value: normalizeCwd(cwd), source: \"cwd\", displayProject: project };\n\t}\n\n\tif (workspaceId) {\n\t\treturn { value: normalizeSlash(workspaceId), source: \"workspace_id\", displayProject: project };\n\t}\n\n\treturn { value: unmappedIdentity(input), source: \"unmapped\", displayProject: project };\n}\n","// src/compose.ts\nvar compose = (middleware, onError, onNotFound) => {\n return (context, next) => {\n let index = -1;\n return dispatch(0);\n async function dispatch(i) {\n if (i <= index) {\n throw new Error(\"next() called multiple times\");\n }\n index = i;\n let res;\n let isError = false;\n let handler;\n if (middleware[i]) {\n handler = middleware[i][0][0];\n context.req.routeIndex = i;\n } else {\n handler = i === middleware.length && next || void 0;\n }\n if (handler) {\n try {\n res = await handler(context, () => dispatch(i + 1));\n } catch (err) {\n if (err instanceof Error && onError) {\n context.error = err;\n res = await onError(err, context);\n isError = true;\n } else {\n throw err;\n }\n }\n } else {\n if (context.finalized === false && onNotFound) {\n res = await onNotFound(context);\n }\n }\n if (res && (context.finalized === false || isError)) {\n context.res = res;\n }\n return context;\n }\n };\n};\nexport {\n compose\n};\n","// src/request/constants.ts\nvar GET_MATCH_RESULT = /* @__PURE__ */ Symbol();\nexport {\n GET_MATCH_RESULT\n};\n","// src/utils/buffer.ts\nimport { sha256 } from \"./crypto.js\";\nvar equal = (a, b) => {\n if (a === b) {\n return true;\n }\n if (a.byteLength !== b.byteLength) {\n return false;\n }\n const va = new DataView(a);\n const vb = new DataView(b);\n let i = va.byteLength;\n while (i--) {\n if (va.getUint8(i) !== vb.getUint8(i)) {\n return false;\n }\n }\n return true;\n};\nvar constantTimeEqualString = (a, b) => {\n const aLen = a.length;\n const bLen = b.length;\n const maxLen = Math.max(aLen, bLen);\n let out = aLen ^ bLen;\n for (let i = 0; i < maxLen; i++) {\n const aChar = i < aLen ? a.charCodeAt(i) : 0;\n const bChar = i < bLen ? b.charCodeAt(i) : 0;\n out |= aChar ^ bChar;\n }\n return out === 0;\n};\nvar timingSafeEqualString = async (a, b, hashFunction) => {\n if (!hashFunction) {\n hashFunction = sha256;\n }\n const [sa, sb] = await Promise.all([hashFunction(a), hashFunction(b)]);\n if (sa == null || sb == null || typeof sa !== \"string\" || typeof sb !== \"string\") {\n return false;\n }\n const hashEqual = constantTimeEqualString(sa, sb);\n const originalEqual = constantTimeEqualString(a, b);\n return hashEqual && originalEqual;\n};\nvar timingSafeEqual = async (a, b, hashFunction) => {\n if (typeof a === \"string\" && typeof b === \"string\") {\n return timingSafeEqualString(a, b, hashFunction);\n }\n if (!hashFunction) {\n hashFunction = sha256;\n }\n const [sa, sb] = await Promise.all([hashFunction(a), hashFunction(b)]);\n if (!sa || !sb || typeof sa !== \"string\" || typeof sb !== \"string\") {\n return false;\n }\n return timingSafeEqualString(sa, sb);\n};\nvar bufferToString = (buffer) => {\n if (buffer instanceof ArrayBuffer) {\n const enc = new TextDecoder(\"utf-8\");\n return enc.decode(buffer);\n }\n return buffer;\n};\nvar bufferToFormData = (arrayBuffer, contentType) => {\n const response = new Response(arrayBuffer, {\n headers: {\n // Normalize the media type (case-insensitive) while keeping parameters like the boundary\n \"Content-Type\": contentType.replace(/^[^;]+/, (mediaType) => mediaType.toLowerCase())\n }\n });\n return response.formData();\n};\nexport {\n bufferToFormData,\n bufferToString,\n equal,\n timingSafeEqual\n};\n","// src/utils/body.ts\nimport { bufferToFormData } from \"./buffer.js\";\nvar MAX_NESTING_DEPTH = 32;\nvar MAX_NESTED_OBJECTS = 1e4;\nvar isRawRequest = (request) => \"headers\" in request;\nvar parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {\n const { all = false, dot = false } = options;\n const headers = isRawRequest(request) ? request.headers : request.raw.headers;\n const contentType = headers.get(\"Content-Type\");\n const mediaType = contentType?.split(\";\")[0].trim().toLowerCase();\n if (mediaType === \"multipart/form-data\" || mediaType === \"application/x-www-form-urlencoded\") {\n return parseFormData(request, { all, dot });\n }\n return {};\n};\nasync function parseFormData(request, options) {\n if (!isRawRequest(request) && request.bodyCache.formData) {\n return convertFormDataToBodyData(\n await request.bodyCache.formData,\n options\n );\n }\n const headers = isRawRequest(request) ? request.headers : request.raw.headers;\n const arrayBuffer = await request.arrayBuffer();\n const formDataPromise = bufferToFormData(arrayBuffer, headers.get(\"Content-Type\") || \"\");\n if (!isRawRequest(request)) {\n request.bodyCache.formData = formDataPromise;\n }\n const formData = await formDataPromise;\n if (formData) {\n return convertFormDataToBodyData(formData, options);\n }\n return {};\n}\nfunction convertFormDataToBodyData(formData, options) {\n const form = /* @__PURE__ */ Object.create(null);\n const nestingState = { count: 0 };\n formData.forEach((value, key) => {\n const shouldParseAllValues = options.all || key.endsWith(\"[]\");\n if (!shouldParseAllValues) {\n form[key] = value;\n } else {\n handleParsingAllValues(form, key, value);\n }\n });\n if (options.dot) {\n Object.entries(form).forEach(([key, value]) => {\n const shouldParseDotValues = key.includes(\".\");\n if (shouldParseDotValues) {\n handleParsingNestedValues(form, key, value, nestingState);\n delete form[key];\n }\n });\n }\n return form;\n}\nvar handleParsingAllValues = (form, key, value) => {\n if (form[key] !== void 0) {\n if (Array.isArray(form[key])) {\n ;\n form[key].push(value);\n } else {\n form[key] = [form[key], value];\n }\n } else {\n if (!key.endsWith(\"[]\")) {\n form[key] = value;\n } else {\n form[key] = [value];\n }\n }\n};\nvar handleParsingNestedValues = (form, key, value, state) => {\n if (/(?:^|\\.)__proto__\\./.test(key)) {\n return;\n }\n let nestedForm = form;\n const keys = key.split(\".\", MAX_NESTING_DEPTH + 2);\n if (keys.length > MAX_NESTING_DEPTH + 1) {\n throwNestingLimitExceeded();\n }\n keys.forEach((key2, index) => {\n if (index === keys.length - 1) {\n nestedForm[key2] = value;\n } else {\n if (!nestedForm[key2] || typeof nestedForm[key2] !== \"object\" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {\n if (state.count++ >= MAX_NESTED_OBJECTS) {\n throwNestingLimitExceeded();\n }\n nestedForm[key2] = /* @__PURE__ */ Object.create(null);\n }\n nestedForm = nestedForm[key2];\n }\n });\n};\nvar throwNestingLimitExceeded = () => {\n throw new Error(\"Nesting limit exceeded\");\n};\nexport {\n parseBody\n};\n","// src/utils/url.ts\nvar splitPath = (path) => {\n const paths = path.split(\"/\");\n if (paths[0] === \"\") {\n paths.shift();\n }\n return paths;\n};\nvar splitRoutingPath = (routePath) => {\n const { groups, path } = extractGroupsFromPath(routePath);\n const paths = splitPath(path);\n return replaceGroupMarks(paths, groups);\n};\nvar extractGroupsFromPath = (path) => {\n const groups = [];\n path = path.replace(/\\{[^}]+\\}/g, (match, index) => {\n const mark = `@${index}`;\n groups.push([mark, match]);\n return mark;\n });\n return { groups, path };\n};\nvar replaceGroupMarks = (paths, groups) => {\n for (let i = groups.length - 1; i >= 0; i--) {\n const [mark] = groups[i];\n for (let j = paths.length - 1; j >= 0; j--) {\n if (paths[j].includes(mark)) {\n paths[j] = paths[j].replace(mark, groups[i][1]);\n break;\n }\n }\n }\n return paths;\n};\nvar patternCache = {};\nvar getPattern = (label, next) => {\n if (label === \"*\") {\n return \"*\";\n }\n const match = label.match(/^\\:([^\\{\\}]+)(?:\\{(.+)\\})?$/);\n if (match) {\n const cacheKey = `${label}#${next}`;\n if (!patternCache[cacheKey]) {\n if (match[2]) {\n patternCache[cacheKey] = next && next[0] !== \":\" && next[0] !== \"*\" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];\n } else {\n patternCache[cacheKey] = [label, match[1], true];\n }\n }\n return patternCache[cacheKey];\n }\n return null;\n};\nvar tryDecode = (str, decoder) => {\n try {\n return decoder(str);\n } catch {\n return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {\n try {\n return decoder(match);\n } catch {\n return match;\n }\n });\n }\n};\nvar tryDecodeURI = (str) => tryDecode(str, decodeURI);\nvar getPath = (request) => {\n const url = request.url;\n const start = url.indexOf(\"/\", url.indexOf(\":\") + 4);\n let i = start;\n for (; i < url.length; i++) {\n const charCode = url.charCodeAt(i);\n if (charCode === 37) {\n const queryIndex = url.indexOf(\"?\", i);\n const hashIndex = url.indexOf(\"#\", i);\n const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);\n const path = url.slice(start, end);\n return tryDecodeURI(path.includes(\"%25\") ? path.replace(/%25/g, \"%2525\") : path);\n } else if (charCode === 63 || charCode === 35) {\n break;\n }\n }\n return url.slice(start, i);\n};\nvar getQueryStrings = (url) => {\n const queryIndex = url.indexOf(\"?\", 8);\n if (queryIndex === -1) {\n return \"\";\n }\n const hashIndex = url.indexOf(\"#\", 8);\n return hashIndex === -1 ? url.slice(queryIndex) : queryIndex < hashIndex ? url.slice(queryIndex, hashIndex) : \"\";\n};\nvar getPathNoStrict = (request) => {\n const result = getPath(request);\n return result.length > 1 && result.at(-1) === \"/\" ? result.slice(0, -1) : result;\n};\nvar mergePath = (base, sub, ...rest) => {\n if (rest.length) {\n sub = mergePath(sub, ...rest);\n }\n return `${base?.[0] === \"/\" ? \"\" : \"/\"}${base}${sub === \"/\" ? \"\" : `${base?.at(-1) === \"/\" ? \"\" : \"/\"}${sub?.[0] === \"/\" ? sub.slice(1) : sub}`}`;\n};\nvar checkOptionalParameter = (path) => {\n if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(\":\")) {\n return null;\n }\n const segments = path.split(\"/\");\n const results = [];\n let basePath = \"\";\n segments.forEach((segment) => {\n if (segment !== \"\" && !/\\:/.test(segment)) {\n basePath += \"/\" + segment;\n } else if (/\\:/.test(segment)) {\n if (segment.charCodeAt(segment.length - 1) === 63) {\n if (results.length === 0 && basePath === \"\") {\n results.push(\"/\");\n } else {\n results.push(basePath);\n }\n const optionalSegment = segment.slice(0, -1);\n basePath += \"/\" + optionalSegment;\n results.push(basePath);\n } else {\n basePath += \"/\" + segment;\n }\n }\n });\n return results.filter((v, i, a) => a.indexOf(v) === i);\n};\nvar tryDecodeURIComponent = (str) => str.indexOf(\"%\") !== -1 ? tryDecode(str, decodeURIComponent_) : str;\nvar _decodeURI = (value) => {\n if (value.indexOf(\"+\") !== -1) {\n value = value.replace(/\\+/g, \" \");\n }\n return tryDecodeURIComponent(value);\n};\nvar _getQueryParam = (url, key, multiple) => {\n const hashIndex = url.indexOf(\"#\", 8);\n if (hashIndex !== -1) {\n url = url.slice(0, hashIndex);\n }\n let encoded;\n if (!multiple && key && key.indexOf(\"%\") === -1 && key.indexOf(\"+\") === -1) {\n let keyIndex2 = url.indexOf(\"?\", 8);\n if (keyIndex2 === -1) {\n return void 0;\n }\n if (!url.startsWith(key, keyIndex2 + 1)) {\n keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);\n }\n while (keyIndex2 !== -1) {\n const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);\n if (trailingKeyCode === 61) {\n const valueIndex = keyIndex2 + key.length + 2;\n const endIndex = url.indexOf(\"&\", valueIndex);\n return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));\n } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {\n return \"\";\n }\n keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);\n }\n encoded = /[%+]/.test(url);\n if (!encoded) {\n return void 0;\n }\n }\n const results = /* @__PURE__ */ Object.create(null);\n encoded ??= /[%+]/.test(url);\n let keyIndex = url.indexOf(\"?\", 8);\n while (keyIndex !== -1) {\n const nextKeyIndex = url.indexOf(\"&\", keyIndex + 1);\n let valueIndex = url.indexOf(\"=\", keyIndex);\n if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {\n valueIndex = -1;\n }\n let name = url.slice(\n keyIndex + 1,\n valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex\n );\n if (encoded) {\n name = _decodeURI(name);\n }\n keyIndex = nextKeyIndex;\n if (name === \"\") {\n continue;\n }\n let value;\n if (valueIndex === -1) {\n value = \"\";\n } else {\n value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);\n if (encoded) {\n value = _decodeURI(value);\n }\n }\n if (multiple) {\n if (!(results[name] && Array.isArray(results[name]))) {\n results[name] = [];\n }\n ;\n results[name].push(value);\n } else {\n results[name] ??= value;\n }\n }\n return key ? results[key] : results;\n};\nvar getQueryParam = _getQueryParam;\nvar getQueryParams = (url, key) => {\n return _getQueryParam(url, key, true);\n};\nvar decodeURIComponent_ = decodeURIComponent;\nexport {\n checkOptionalParameter,\n decodeURIComponent_,\n getPath,\n getPathNoStrict,\n getPattern,\n getQueryParam,\n getQueryParams,\n getQueryStrings,\n mergePath,\n splitPath,\n splitRoutingPath,\n tryDecode,\n tryDecodeURI,\n tryDecodeURIComponent\n};\n","// src/request.ts\nimport { HTTPException } from \"./http-exception.js\";\nimport { GET_MATCH_RESULT } from \"./request/constants.js\";\nimport { parseBody } from \"./utils/body.js\";\nimport { getQueryParam, getQueryParams, tryDecodeURIComponent } from \"./utils/url.js\";\nvar HonoRequest = class {\n /**\n * `.raw` can get the raw Request object.\n *\n * @see {@link https://hono.dev/docs/api/request#raw}\n *\n * @example\n * ```ts\n * // For Cloudflare Workers\n * app.post('/', async (c) => {\n * const metadata = c.req.raw.cf?.hostMetadata?\n * ...\n * })\n * ```\n */\n raw;\n #validatedData;\n // Short name of validatedData\n #matchResult;\n routeIndex = 0;\n /**\n * `.path` can get the pathname of the request.\n *\n * @see {@link https://hono.dev/docs/api/request#path}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const pathname = c.req.path // `/about/me`\n * })\n * ```\n */\n path;\n bodyCache = {};\n constructor(request, path = \"/\", matchResult = [[]]) {\n this.raw = request;\n this.path = path;\n this.#matchResult = matchResult;\n }\n param(key) {\n return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();\n }\n #getDecodedParam(key) {\n const paramKey = this.#matchResult[0][this.routeIndex]?.[1][key];\n const param = this.#getParamValue(paramKey);\n return param && tryDecodeURIComponent(param);\n }\n #getAllDecodedParams() {\n const decoded = {};\n const keys = Object.keys(this.#matchResult[0][this.routeIndex]?.[1] ?? {});\n for (const key of keys) {\n const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);\n if (value !== void 0) {\n decoded[key] = tryDecodeURIComponent(value);\n }\n }\n return decoded;\n }\n #getParamValue(paramKey) {\n return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;\n }\n query(key) {\n return getQueryParam(this.url, key);\n }\n queries(key) {\n return getQueryParams(this.url, key);\n }\n header(name) {\n if (name) {\n return this.raw.headers.get(name) ?? void 0;\n }\n const headerData = /* @__PURE__ */ Object.create(null);\n this.raw.headers.forEach((value, key) => {\n headerData[key] = value;\n });\n return headerData;\n }\n async parseBody(options) {\n return parseBody(this, options);\n }\n #cachedBody = (key) => {\n const { bodyCache, raw } = this;\n const cachedBody = bodyCache[key];\n if (cachedBody) {\n return cachedBody;\n }\n for (const anyCachedKey in bodyCache) {\n return bodyCache[anyCachedKey].then((body) => {\n if (anyCachedKey === \"json\") {\n body = JSON.stringify(body);\n }\n return new Response(body)[key]();\n });\n }\n return bodyCache[key] = raw[key]();\n };\n /**\n * `.json()` can parse Request body of type `application/json`\n *\n * @see {@link https://hono.dev/docs/api/request#json}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.json()\n * })\n * ```\n */\n json() {\n return this.#cachedBody(\"text\").then((text) => JSON.parse(text));\n }\n /**\n * `.text()` can parse Request body of type `text/plain`\n *\n * @see {@link https://hono.dev/docs/api/request#text}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.text()\n * })\n * ```\n */\n text() {\n return this.#cachedBody(\"text\");\n }\n /**\n * `.arrayBuffer()` parse Request body as an `ArrayBuffer`\n *\n * @see {@link https://hono.dev/docs/api/request#arraybuffer}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.arrayBuffer()\n * })\n * ```\n */\n arrayBuffer() {\n return this.#cachedBody(\"arrayBuffer\");\n }\n /**\n * `.bytes()` parses the request body as a `Uint8Array`.\n *\n * @see {@link https://hono.dev/docs/api/request#bytes}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.bytes()\n * })\n * ```\n */\n bytes() {\n return this.#cachedBody(\"arrayBuffer\").then((buffer) => new Uint8Array(buffer));\n }\n /**\n * Parses the request body as a `Blob`.\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.blob();\n * });\n * ```\n * @see https://hono.dev/docs/api/request#blob\n */\n blob() {\n return this.#cachedBody(\"blob\");\n }\n /**\n * Parses the request body as `FormData`.\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.formData();\n * });\n * ```\n * @see https://hono.dev/docs/api/request#formdata\n */\n formData() {\n return this.#cachedBody(\"formData\");\n }\n /**\n * Adds validated data to the request.\n *\n * @param target - The target of the validation.\n * @param data - The validated data to add.\n */\n addValidatedData(target, data) {\n ;\n (this.#validatedData ??= {})[target] = data;\n }\n valid(target) {\n return this.#validatedData?.[target];\n }\n /**\n * `.url()` can get the request url strings.\n *\n * @see {@link https://hono.dev/docs/api/request#url}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const url = c.req.url // `http://localhost:8787/about/me`\n * ...\n * })\n * ```\n */\n get url() {\n return this.raw.url;\n }\n /**\n * `.method()` can get the method name of the request.\n *\n * @see {@link https://hono.dev/docs/api/request#method}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const method = c.req.method // `GET`\n * })\n * ```\n */\n get method() {\n return this.raw.method;\n }\n get [GET_MATCH_RESULT]() {\n return this.#matchResult;\n }\n /**\n * `.matchedRoutes()` can return a matched route in the handler\n *\n * @deprecated\n *\n * Use matchedRoutes helper defined in \"hono/route\" instead.\n *\n * @see {@link https://hono.dev/docs/api/request#matchedroutes}\n *\n * @example\n * ```ts\n * app.use('*', async function logger(c, next) {\n * await next()\n * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {\n * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')\n * console.log(\n * method,\n * ' ',\n * path,\n * ' '.repeat(Math.max(10 - path.length, 0)),\n * name,\n * i === c.req.routeIndex ? '<- respond from here' : ''\n * )\n * })\n * })\n * ```\n */\n get matchedRoutes() {\n return this.#matchResult[0].map(([[, route]]) => route);\n }\n /**\n * `routePath()` can retrieve the path registered within the handler\n *\n * @deprecated\n *\n * Use routePath helper defined in \"hono/route\" instead.\n *\n * @see {@link https://hono.dev/docs/api/request#routepath}\n *\n * @example\n * ```ts\n * app.get('/posts/:id', (c) => {\n * return c.json({ path: c.req.routePath })\n * })\n * ```\n */\n get routePath() {\n return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;\n }\n};\nvar cloneRawRequest = async (req) => {\n if (!req.raw.bodyUsed) {\n return req.raw.clone();\n }\n const cacheKey = Object.keys(req.bodyCache)[0];\n if (!cacheKey) {\n throw new HTTPException(500, {\n message: \"Cannot clone request: body was already consumed and not cached. Please use HonoRequest methods (e.g., req.json(), req.text()) instead of consuming req.raw directly.\"\n });\n }\n let body = await req[cacheKey]();\n const headers = req.header();\n if (cacheKey === \"json\") {\n body = JSON.stringify(body);\n delete headers[\"content-length\"];\n } else if (body instanceof FormData) {\n delete headers[\"content-type\"];\n delete headers[\"content-length\"];\n }\n const requestInit = {\n body,\n cache: req.raw.cache,\n credentials: req.raw.credentials,\n headers,\n integrity: req.raw.integrity,\n keepalive: req.raw.keepalive,\n method: req.method,\n mode: req.raw.mode,\n redirect: req.raw.redirect,\n referrer: req.raw.referrer,\n referrerPolicy: req.raw.referrerPolicy,\n signal: req.raw.signal\n };\n return new Request(req.url, requestInit);\n};\nexport {\n HonoRequest,\n cloneRawRequest\n};\n","// src/utils/html.ts\nvar HtmlEscapedCallbackPhase = {\n Stringify: 1,\n BeforeStream: 2,\n Stream: 3\n};\nvar raw = (value, callbacks) => {\n const escapedString = new String(value);\n escapedString.isEscaped = true;\n escapedString.callbacks = callbacks;\n return escapedString;\n};\nvar escapeRe = /[&<>'\"]/;\nvar stringBufferToString = async (buffer, callbacks) => {\n let str = \"\";\n callbacks ||= [];\n const resolvedBuffer = await Promise.all(buffer);\n for (let i = resolvedBuffer.length - 1; ; i--) {\n str += resolvedBuffer[i];\n i--;\n if (i < 0) {\n break;\n }\n let r = resolvedBuffer[i];\n if (typeof r === \"object\") {\n callbacks.push(...r.callbacks || []);\n }\n const isEscaped = r.isEscaped;\n r = await (typeof r === \"object\" ? r.toString() : r);\n if (typeof r === \"object\") {\n callbacks.push(...r.callbacks || []);\n }\n if (r.isEscaped ?? isEscaped) {\n str += r;\n } else {\n const buf = [str];\n escapeToBuffer(r, buf);\n str = buf[0];\n }\n }\n return raw(str, callbacks);\n};\nvar escapeToBuffer = (str, buffer) => {\n const match = str.search(escapeRe);\n if (match === -1) {\n buffer[0] += str;\n return;\n }\n let escape;\n let index;\n let lastIndex = 0;\n for (index = match; index < str.length; index++) {\n switch (str.charCodeAt(index)) {\n case 34:\n escape = \"&quot;\";\n break;\n case 39:\n escape = \"&#39;\";\n break;\n case 38:\n escape = \"&amp;\";\n break;\n case 60:\n escape = \"&lt;\";\n break;\n case 62:\n escape = \"&gt;\";\n break;\n default:\n continue;\n }\n buffer[0] += str.substring(lastIndex, index) + escape;\n lastIndex = index + 1;\n }\n buffer[0] += str.substring(lastIndex, index);\n};\nvar resolveCallbackSync = (str) => {\n const callbacks = str.callbacks;\n if (!callbacks?.length) {\n return str;\n }\n const buffer = [str];\n const context = {};\n callbacks.forEach((c) => c({ phase: HtmlEscapedCallbackPhase.Stringify, buffer, context }));\n return buffer[0];\n};\nvar resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {\n if (typeof str === \"object\" && !(str instanceof String)) {\n if (!(str instanceof Promise)) {\n str = str.toString();\n }\n if (str instanceof Promise) {\n str = await str;\n }\n }\n const callbacks = str.callbacks;\n if (!callbacks?.length) {\n return Promise.resolve(str);\n }\n if (buffer) {\n buffer[0] += str;\n } else {\n buffer = [str];\n }\n const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(\n (res) => Promise.all(\n res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))\n ).then(() => buffer[0])\n );\n if (preserveCallbacks) {\n return raw(await resStr, callbacks);\n } else {\n return resStr;\n }\n};\nexport {\n HtmlEscapedCallbackPhase,\n escapeToBuffer,\n raw,\n resolveCallback,\n resolveCallbackSync,\n stringBufferToString\n};\n","// src/context.ts\nimport { HonoRequest } from \"./request.js\";\nimport { HtmlEscapedCallbackPhase, resolveCallback } from \"./utils/html.js\";\nvar TEXT_PLAIN = \"text/plain; charset=UTF-8\";\nvar setDefaultContentType = (contentType, headers) => {\n return {\n \"Content-Type\": contentType,\n ...headers\n };\n};\nvar createResponseInstance = (body, init) => new Response(body, init);\nvar Context = class {\n #rawRequest;\n #req;\n /**\n * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.\n *\n * @see {@link https://hono.dev/docs/api/context#env}\n *\n * @example\n * ```ts\n * // Environment object for Cloudflare Workers\n * app.get('*', async c => {\n * const counter = c.env.COUNTER\n * })\n * ```\n */\n env = {};\n #var;\n finalized = false;\n /**\n * `.error` can get the error object from the middleware if the Handler throws an error.\n *\n * @see {@link https://hono.dev/docs/api/context#error}\n *\n * @example\n * ```ts\n * app.use('*', async (c, next) => {\n * await next()\n * if (c.error) {\n * // do something...\n * }\n * })\n * ```\n */\n error;\n #status;\n #executionCtx;\n #res;\n #layout;\n #renderer;\n #notFoundHandler;\n #preparedHeaders;\n #matchResult;\n #path;\n /**\n * Creates an instance of the Context class.\n *\n * @param req - The Request object.\n * @param options - Optional configuration options for the context.\n */\n constructor(req, options) {\n this.#rawRequest = req;\n if (options) {\n this.#executionCtx = options.executionCtx;\n this.env = options.env;\n this.#notFoundHandler = options.notFoundHandler;\n this.#path = options.path;\n this.#matchResult = options.matchResult;\n }\n }\n /**\n * `.req` is the instance of {@link HonoRequest}.\n */\n get req() {\n this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);\n return this.#req;\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#event}\n * The FetchEvent associated with the current request.\n *\n * @throws Will throw an error if the context does not have a FetchEvent.\n */\n get event() {\n if (this.#executionCtx && \"respondWith\" in this.#executionCtx) {\n return this.#executionCtx;\n } else {\n throw Error(\"This context has no FetchEvent\");\n }\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#executionctx}\n * The ExecutionContext associated with the current request.\n *\n * @throws Will throw an error if the context does not have an ExecutionContext.\n */\n get executionCtx() {\n if (this.#executionCtx) {\n return this.#executionCtx;\n } else {\n throw Error(\"This context has no ExecutionContext\");\n }\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#res}\n * The Response object for the current request.\n */\n get res() {\n return this.#res ||= createResponseInstance(null, {\n headers: this.#preparedHeaders ??= new Headers()\n });\n }\n /**\n * Sets the Response object for the current request.\n *\n * @param _res - The Response object to set.\n */\n set res(_res) {\n if (this.#res && _res) {\n _res = createResponseInstance(_res.body, _res);\n for (const [k, v] of this.#res.headers.entries()) {\n if (k === \"content-type\") {\n continue;\n }\n if (k === \"set-cookie\") {\n const cookies = this.#res.headers.getSetCookie();\n _res.headers.delete(\"set-cookie\");\n for (const cookie of cookies) {\n _res.headers.append(\"set-cookie\", cookie);\n }\n } else {\n _res.headers.set(k, v);\n }\n }\n }\n this.#res = _res;\n this.finalized = true;\n }\n /**\n * `.render()` can create a response within a layout.\n *\n * @see {@link https://hono.dev/docs/api/context#render-setrenderer}\n *\n * @example\n * ```ts\n * app.get('/', (c) => {\n * return c.render('Hello!')\n * })\n * ```\n */\n render = (...args) => {\n this.#renderer ??= (content) => this.html(content);\n return this.#renderer(...args);\n };\n /**\n * Sets the layout for the response.\n *\n * @param layout - The layout to set.\n * @returns The layout function.\n */\n setLayout = (layout) => this.#layout = layout;\n /**\n * Gets the current layout for the response.\n *\n * @returns The current layout function.\n */\n getLayout = () => this.#layout;\n /**\n * `.setRenderer()` can set the layout in the custom middleware.\n *\n * @see {@link https://hono.dev/docs/api/context#render-setrenderer}\n *\n * @example\n * ```tsx\n * app.use('*', async (c, next) => {\n * c.setRenderer((content) => {\n * return c.html(\n * <html>\n * <body>\n * <p>{content}</p>\n * </body>\n * </html>\n * )\n * })\n * await next()\n * })\n * ```\n */\n setRenderer = (renderer) => {\n this.#renderer = renderer;\n };\n /**\n * `.header()` can set headers.\n *\n * @see {@link https://hono.dev/docs/api/context#header}\n *\n * @example\n * ```ts\n * app.get('/welcome', (c) => {\n * // Set headers\n * c.header('X-Message', 'Hello!')\n * c.header('Content-Type', 'text/plain')\n *\n * // Append multiple headers using the append option (e.g. Vary)\n * c.header('Vary', 'Accept-Encoding', { append: true })\n * c.header('Vary', 'User-Agent', { append: true })\n *\n * return c.body('Thank you for coming')\n * })\n * ```\n */\n header = (name, value, options) => {\n if (this.finalized) {\n this.#res = createResponseInstance(this.#res.body, this.#res);\n }\n const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();\n if (value === void 0) {\n headers.delete(name);\n } else if (options?.append) {\n headers.append(name, value);\n } else {\n headers.set(name, value);\n }\n };\n status = (status) => {\n this.#status = status;\n };\n /**\n * `.set()` can set the value specified by the key.\n *\n * @see {@link https://hono.dev/docs/api/context#set-get}\n *\n * @example\n * ```ts\n * app.use('*', async (c, next) => {\n * c.set('message', 'Hono is hot!!')\n * await next()\n * })\n * ```\n */\n set = (key, value) => {\n this.#var ??= /* @__PURE__ */ new Map();\n this.#var.set(key, value);\n };\n /**\n * `.get()` can use the value specified by the key.\n *\n * @see {@link https://hono.dev/docs/api/context#set-get}\n *\n * @example\n * ```ts\n * app.get('/', (c) => {\n * const message = c.get('message')\n * return c.text(`The message is \"${message}\"`)\n * })\n * ```\n */\n get = (key) => {\n return this.#var ? this.#var.get(key) : void 0;\n };\n /**\n * `.var` can access the value of a variable.\n *\n * @see {@link https://hono.dev/docs/api/context#var}\n *\n * @example\n * ```ts\n * const result = c.var.client.oneMethod()\n * ```\n */\n // c.var.propName is a read-only\n get var() {\n if (!this.#var) {\n return {};\n }\n return Object.fromEntries(this.#var);\n }\n #newResponse(data, arg, headers) {\n let responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders;\n if (typeof arg === \"object\" && arg.headers) {\n responseHeaders ??= new Headers();\n for (const [key, value] of new Headers(arg.headers)) {\n if (key === \"set-cookie\") {\n responseHeaders.append(key, value);\n } else {\n responseHeaders.set(key, value);\n }\n }\n }\n if (headers) {\n if (!responseHeaders) {\n let count = 0;\n for (const k in headers) {\n if (++count > 1 || typeof headers[k] !== \"string\") {\n responseHeaders = new Headers();\n break;\n }\n }\n }\n if (responseHeaders) {\n for (const k in headers) {\n const v = headers[k];\n if (typeof v === \"string\") {\n responseHeaders.set(k, v);\n } else {\n responseHeaders.delete(k);\n for (const v2 of v) {\n responseHeaders.append(k, v2);\n }\n }\n }\n }\n }\n const status = typeof arg === \"number\" ? arg : arg?.status ?? this.#status;\n return createResponseInstance(data, {\n status,\n headers: responseHeaders ?? headers\n });\n }\n newResponse = (...args) => this.#newResponse(...args);\n /**\n * `.body()` can return the HTTP response.\n * You can set headers with `.header()` and set HTTP status code with `.status`.\n * This can also be set in `.text()`, `.json()` and so on.\n *\n * @see {@link https://hono.dev/docs/api/context#body}\n *\n * @example\n * ```ts\n * app.get('/welcome', (c) => {\n * // Set headers\n * c.header('X-Message', 'Hello!')\n * c.header('Content-Type', 'text/plain')\n * // Set HTTP status code\n * c.status(201)\n *\n * // Return the response body\n * return c.body('Thank you for coming')\n * })\n * ```\n */\n body = (data, arg, headers) => this.#newResponse(data, arg, headers);\n /**\n * `.text()` can render text as `Content-Type:text/plain`.\n *\n * @see {@link https://hono.dev/docs/api/context#text}\n *\n * @example\n * ```ts\n * app.get('/say', (c) => {\n * return c.text('Hello!')\n * })\n * ```\n */\n text = (text, arg, headers) => {\n return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(\n text,\n arg,\n setDefaultContentType(TEXT_PLAIN, headers)\n );\n };\n /**\n * `.json()` can render JSON as `Content-Type:application/json`.\n *\n * @see {@link https://hono.dev/docs/api/context#json}\n *\n * @example\n * ```ts\n * app.get('/api', (c) => {\n * return c.json({ message: 'Hello!' })\n * })\n * ```\n */\n json = (object, arg, headers) => {\n return this.#newResponse(\n JSON.stringify(object),\n arg,\n setDefaultContentType(\"application/json\", headers)\n );\n };\n html = (html, arg, headers) => {\n const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType(\"text/html; charset=UTF-8\", headers));\n return typeof html === \"object\" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);\n };\n /**\n * `.redirect()` can Redirect, default status code is 302.\n *\n * @see {@link https://hono.dev/docs/api/context#redirect}\n *\n * @example\n * ```ts\n * app.get('/redirect', (c) => {\n * return c.redirect('/')\n * })\n * app.get('/redirect-permanently', (c) => {\n * return c.redirect('/', 301)\n * })\n * ```\n */\n redirect = (location, status) => {\n const locationString = String(location);\n this.header(\n \"Location\",\n // Multibyes should be encoded\n // eslint-disable-next-line no-control-regex\n !/[^\\x00-\\xFF]/.test(locationString) ? locationString : encodeURI(locationString)\n );\n return this.newResponse(null, status ?? 302);\n };\n /**\n * `.notFound()` can return the Not Found Response.\n *\n * @see {@link https://hono.dev/docs/api/context#notfound}\n *\n * @example\n * ```ts\n * app.get('/notfound', (c) => {\n * return c.notFound()\n * })\n * ```\n */\n notFound = () => {\n this.#notFoundHandler ??= () => createResponseInstance();\n return this.#notFoundHandler(this);\n };\n};\nexport {\n Context,\n TEXT_PLAIN\n};\n","// src/router.ts\nvar METHOD_NAME_ALL = \"ALL\";\nvar METHOD_NAME_ALL_LOWERCASE = \"all\";\nvar METHODS = [\"get\", \"post\", \"put\", \"delete\", \"options\", \"patch\", \"query\"];\nvar MESSAGE_MATCHER_IS_ALREADY_BUILT = \"Can not add a route since the matcher is already built.\";\nvar UnsupportedPathError = class extends Error {\n};\nexport {\n MESSAGE_MATCHER_IS_ALREADY_BUILT,\n METHODS,\n METHOD_NAME_ALL,\n METHOD_NAME_ALL_LOWERCASE,\n UnsupportedPathError\n};\n","// src/utils/constants.ts\nvar COMPOSED_HANDLER = \"__COMPOSED_HANDLER\";\nexport {\n COMPOSED_HANDLER\n};\n","// src/hono-base.ts\nimport { compose } from \"./compose.js\";\nimport { Context } from \"./context.js\";\nimport { METHODS, METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE } from \"./router.js\";\nimport { COMPOSED_HANDLER } from \"./utils/constants.js\";\nimport { getPath, getPathNoStrict, mergePath } from \"./utils/url.js\";\nvar notFoundHandler = (c) => {\n return c.text(\"404 Not Found\", 404);\n};\nvar errorHandler = (err, c) => {\n if (\"getResponse\" in err) {\n const res = err.getResponse();\n return c.newResponse(res.body, res);\n }\n console.error(err);\n return c.text(\"Internal Server Error\", 500);\n};\nvar Hono = class _Hono {\n get;\n post;\n put;\n delete;\n options;\n patch;\n query;\n all;\n on;\n use;\n /*\n This class is like an abstract class and does not have a router.\n To use it, inherit the class and implement router in the constructor.\n */\n router;\n getPath;\n // Cannot use `#` because it requires visibility at JavaScript runtime.\n _basePath = \"/\";\n #path = \"/\";\n routes = [];\n constructor(options = {}) {\n const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];\n allMethods.forEach((method) => {\n this[method] = (args1, ...args) => {\n if (typeof args1 === \"string\") {\n this.#path = args1;\n } else {\n this.#addRoute(method, this.#path, args1);\n }\n args.forEach((handler) => {\n this.#addRoute(method, this.#path, handler);\n });\n return this;\n };\n });\n this.on = (method, path, ...handlers) => {\n for (const p of [path].flat()) {\n this.#path = p;\n for (const m of [method].flat()) {\n handlers.map((handler) => {\n this.#addRoute(m.toUpperCase(), this.#path, handler);\n });\n }\n }\n return this;\n };\n this.use = (arg1, ...handlers) => {\n if (typeof arg1 === \"string\") {\n this.#path = arg1;\n } else {\n this.#path = \"*\";\n handlers.unshift(arg1);\n }\n handlers.forEach((handler) => {\n this.#addRoute(METHOD_NAME_ALL, this.#path, handler);\n });\n return this;\n };\n const { strict, ...optionsWithoutStrict } = options;\n Object.assign(this, optionsWithoutStrict);\n this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;\n }\n #clone() {\n const clone = new _Hono({\n router: this.router,\n getPath: this.getPath\n });\n clone.errorHandler = this.errorHandler;\n clone.#notFoundHandler = this.#notFoundHandler;\n clone.routes = this.routes;\n return clone;\n }\n #notFoundHandler = notFoundHandler;\n // Cannot use `#` because it requires visibility at JavaScript runtime.\n errorHandler = errorHandler;\n /**\n * `.route()` allows grouping other Hono instance in routes.\n *\n * @see {@link https://hono.dev/docs/api/routing#grouping}\n *\n * @param {string} path - base Path\n * @param {Hono} app - other Hono instance\n * @returns {Hono} routed Hono instance\n *\n * @example\n * ```ts\n * const app = new Hono()\n * const app2 = new Hono()\n *\n * app2.get(\"/user\", (c) => c.text(\"user\"))\n * app.route(\"/api\", app2) // GET /api/user\n * ```\n */\n route(path, app) {\n const subApp = this.basePath(path);\n app.routes.map((r) => {\n let handler;\n if (app.errorHandler === errorHandler) {\n handler = r.handler;\n } else {\n handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;\n handler[COMPOSED_HANDLER] = r.handler;\n }\n subApp.#addRoute(r.method, r.path, handler, r.basePath);\n });\n return this;\n }\n /**\n * `.basePath()` allows base paths to be specified.\n *\n * @see {@link https://hono.dev/docs/api/routing#base-path}\n *\n * @param {string} path - base Path\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * const api = new Hono().basePath('/api')\n * ```\n */\n basePath(path) {\n const subApp = this.#clone();\n subApp._basePath = mergePath(this._basePath, path);\n return subApp;\n }\n /**\n * `.onError()` handles an error and returns a customized Response.\n *\n * @see {@link https://hono.dev/docs/api/hono#error-handling}\n *\n * @param {ErrorHandler} handler - request Handler for error\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * app.onError((err, c) => {\n * console.error(`${err}`)\n * return c.text('Custom Error Message', 500)\n * })\n * ```\n */\n onError = (handler) => {\n this.errorHandler = handler;\n return this;\n };\n /**\n * `.notFound()` allows you to customize a Not Found Response.\n *\n * @see {@link https://hono.dev/docs/api/hono#not-found}\n *\n * @param {NotFoundHandler} handler - request handler for not-found\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * app.notFound((c) => {\n * return c.text('Custom 404 Message', 404)\n * })\n * ```\n */\n notFound = (handler) => {\n this.#notFoundHandler = handler;\n return this;\n };\n /**\n * `.mount()` allows you to mount applications built with other frameworks into your Hono application.\n *\n * @see {@link https://hono.dev/docs/api/hono#mount}\n *\n * @param {string} path - base Path\n * @param {Function} applicationHandler - other Request Handler\n * @param {MountOptions} [options] - options of `.mount()`\n * @returns {Hono} mounted Hono instance\n *\n * @example\n * ```ts\n * import { Router as IttyRouter } from 'itty-router'\n * import { Hono } from 'hono'\n * // Create itty-router application\n * const ittyRouter = IttyRouter()\n * // GET /itty-router/hello\n * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))\n *\n * const app = new Hono()\n * app.mount('/itty-router', ittyRouter.handle)\n * ```\n *\n * @example\n * ```ts\n * const app = new Hono()\n * // Send the request to another application without modification.\n * app.mount('/app', anotherApp, {\n * replaceRequest: (req) => req,\n * })\n * ```\n */\n mount(path, applicationHandler, options) {\n let replaceRequest;\n let optionHandler;\n if (options) {\n if (typeof options === \"function\") {\n optionHandler = options;\n } else {\n optionHandler = options.optionHandler;\n if (options.replaceRequest === false) {\n replaceRequest = (request) => request;\n } else {\n replaceRequest = options.replaceRequest;\n }\n }\n }\n const getOptions = optionHandler ? (c) => {\n const options2 = optionHandler(c);\n return Array.isArray(options2) ? options2 : [options2];\n } : (c) => {\n let executionContext = void 0;\n try {\n executionContext = c.executionCtx;\n } catch {\n }\n return [c.env, executionContext];\n };\n replaceRequest ||= (() => {\n const mergedPath = mergePath(this._basePath, path);\n const pathPrefixLength = mergedPath === \"/\" ? 0 : mergedPath.length;\n return (request) => {\n const url = new URL(request.url);\n url.pathname = this.getPath(request).slice(pathPrefixLength) || \"/\";\n return new Request(url, request);\n };\n })();\n const handler = async (c, next) => {\n const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));\n if (res) {\n return res;\n }\n await next();\n };\n this.#addRoute(METHOD_NAME_ALL, mergePath(path, \"*\"), handler);\n return this;\n }\n #addRoute(method, path, handler, baseRoutePath) {\n method = method.toUpperCase();\n path = mergePath(this._basePath, path);\n const r = {\n basePath: baseRoutePath !== void 0 ? mergePath(this._basePath, baseRoutePath) : this._basePath,\n path,\n method,\n handler\n };\n this.router.add(method, path, [handler, r]);\n this.routes.push(r);\n }\n #handleError(err, c) {\n if (err instanceof Error) {\n return this.errorHandler(err, c);\n }\n throw err;\n }\n #dispatch(request, executionCtx, env, method) {\n if (method === \"HEAD\") {\n return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, \"GET\")))();\n }\n const path = this.getPath(request, { env });\n const matchResult = this.router.match(method, path);\n const c = new Context(request, {\n path,\n matchResult,\n env,\n executionCtx,\n notFoundHandler: this.#notFoundHandler\n });\n if (matchResult[0].length === 1) {\n let res;\n try {\n res = matchResult[0][0][0][0](c, async () => {\n c.res = await this.#notFoundHandler(c);\n });\n } catch (err) {\n return this.#handleError(err, c);\n }\n return res instanceof Promise ? res.then(\n (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))\n ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);\n }\n const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);\n return (async () => {\n try {\n const context = await composed(c);\n if (!context.finalized) {\n throw new Error(\n \"Context is not finalized. Did you forget to return a Response object or `await next()`?\"\n );\n }\n return context.res;\n } catch (err) {\n return this.#handleError(err, c);\n }\n })();\n }\n /**\n * `.fetch()` will be entry point of your app.\n *\n * @see {@link https://hono.dev/docs/api/hono#fetch}\n *\n * @param {Request} request - request Object of request\n * @param {Env} env - env Object\n * @param {ExecutionContext} executionCtx - context of execution\n * @returns {Response | Promise<Response>} response of request\n *\n */\n fetch = (request, ...rest) => {\n return this.#dispatch(request, rest[1], rest[0], request.method);\n };\n /**\n * `.request()` is a useful method for testing.\n * You can pass a URL or pathname to send a GET request.\n * app will return a Response object.\n * ```ts\n * test('GET /hello is ok', async () => {\n * const res = await app.request('/hello')\n * expect(res.status).toBe(200)\n * })\n * ```\n * @see https://hono.dev/docs/api/hono#request\n */\n request = (input, requestInit, Env, executionCtx) => {\n if (input instanceof Request) {\n return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);\n }\n input = input.toString();\n return this.fetch(\n new Request(\n /^https?:\\/\\//.test(input) ? input : `http://localhost${mergePath(\"/\", input)}`,\n requestInit\n ),\n Env,\n executionCtx\n );\n };\n /**\n * `.fire()` automatically adds a global fetch event listener.\n * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.\n * @deprecated\n * Use `fire` from `hono/service-worker` instead.\n * ```ts\n * import { Hono } from 'hono'\n * import { fire } from 'hono/service-worker'\n *\n * const app = new Hono()\n * // ...\n * fire(app)\n * ```\n * @see https://hono.dev/docs/api/hono#fire\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API\n * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/\n */\n fire = () => {\n addEventListener(\"fetch\", (event) => {\n event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));\n });\n };\n};\nexport {\n Hono as HonoBase\n};\n","// src/router/utils.ts\nvar createNullObject = () => /* @__PURE__ */ Object.create(null);\nexport {\n createNullObject\n};\n","// src/router/reg-exp-router/matcher.ts\nimport { METHOD_NAME_ALL } from \"../../router.js\";\nvar emptyParam = [];\nfunction match(method, path) {\n const matchers = this.buildAllMatchers();\n const match2 = ((method2, path2) => {\n const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];\n const staticMatch = matcher[2][path2];\n if (staticMatch) {\n return staticMatch;\n }\n const match3 = path2.match(matcher[0]);\n if (!match3) {\n return [[], emptyParam];\n }\n const index = match3.indexOf(\"\", 1);\n return [matcher[1][index], match3];\n });\n this.match = match2;\n return match2(method, path);\n}\nexport {\n emptyParam,\n match\n};\n","// src/router/reg-exp-router/node.ts\nimport { createNullObject } from \"../utils.js\";\nvar LABEL_REG_EXP_STR = \"[^/]+\";\nvar ONLY_WILDCARD_REG_EXP_STR = \".*\";\nvar TAIL_WILDCARD_REG_EXP_STR = \"(?:|/.*)\";\nvar PATH_ERROR = /* @__PURE__ */ Symbol();\nvar regExpMetaChars = new Set(\".\\\\+*[^]$()\");\nfunction compareKey(a, b) {\n if (a.length === 1) {\n return b.length === 1 ? a < b ? -1 : 1 : -1;\n }\n if (b.length === 1) {\n return 1;\n }\n if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {\n return b === TAIL_WILDCARD_REG_EXP_STR ? -1 : 1;\n } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {\n return -1;\n }\n if (a === LABEL_REG_EXP_STR) {\n return 1;\n } else if (b === LABEL_REG_EXP_STR) {\n return -1;\n }\n return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;\n}\nvar Node = class _Node {\n // handler index of a dynamic path, or -1 for a static path terminal\n #index;\n #varIndex;\n #children = createNullObject();\n insert(tokens, index, paramMap, context, isStatic) {\n let node = this;\n for (let i = 0, len = tokens.length; i < len; i++) {\n const token = tokens[i];\n const pattern = token.length === 1 ? token === \"*\" ? i === len - 1 ? [\"\", \"\", ONLY_WILDCARD_REG_EXP_STR] : [\"\", \"\", LABEL_REG_EXP_STR] : null : token === \"/*\" ? [\"\", \"\", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\\:([^\\{\\}]+)(?:\\{(.+)\\})?$/);\n let nextNode;\n if (pattern) {\n const name = pattern[1];\n let regexpStr = pattern[2] || LABEL_REG_EXP_STR;\n if (name && pattern[2]) {\n if (regexpStr === \".*\") {\n throw PATH_ERROR;\n }\n regexpStr = regexpStr.replace(/^\\((?!\\?:)(?=[^)]+\\)$)/, \"(?:\");\n if (/\\((?!\\?:)/.test(regexpStr)) {\n throw PATH_ERROR;\n }\n if (regexpStr.length === 1 && regExpMetaChars.has(regexpStr)) {\n throw PATH_ERROR;\n }\n }\n nextNode = node.#children[regexpStr];\n if (!nextNode) {\n if (regexpStr !== ONLY_WILDCARD_REG_EXP_STR && regexpStr !== TAIL_WILDCARD_REG_EXP_STR) {\n for (const k in node.#children) {\n if (\n // a single-char pattern coexists with single-char literals as a literal does\n (regexpStr.length > 1 || k.length > 1) && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR\n ) {\n throw PATH_ERROR;\n }\n }\n }\n nextNode = node.#children[regexpStr] = new _Node();\n }\n if (name !== \"\") {\n nextNode.#varIndex ??= context.varIndex++;\n paramMap.push([name, nextNode.#varIndex]);\n }\n } else {\n nextNode = node.#children[token];\n if (!nextNode) {\n for (const k in node.#children) {\n if (k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR) {\n throw PATH_ERROR;\n }\n }\n nextNode = node.#children[token] = new _Node();\n }\n }\n node = nextNode;\n }\n if (node.#index !== void 0) {\n throw PATH_ERROR;\n }\n node.#index = isStatic ? -1 : index;\n }\n buildRegExpStr() {\n const childKeys = Object.keys(this.#children).sort(compareKey);\n const strList = childKeys.map((k) => {\n const c = this.#children[k];\n const childStr = c.buildRegExpStr();\n return childStr === \"\" ? \"\" : (typeof c.#varIndex === \"number\" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\\\${k}` : k) + childStr;\n }).filter(Boolean);\n if (typeof this.#index === \"number\" && this.#index !== -1) {\n strList.unshift(`#${this.#index}`);\n }\n if (strList.length === 0) {\n return \"\";\n }\n if (strList.length === 1) {\n return strList[0];\n }\n return \"(?:\" + strList.join(\"|\") + \")\";\n }\n};\nexport {\n LABEL_REG_EXP_STR,\n Node,\n ONLY_WILDCARD_REG_EXP_STR,\n PATH_ERROR,\n TAIL_WILDCARD_REG_EXP_STR\n};\n","// src/router/reg-exp-router/trie.ts\nimport { createNullObject } from \"../utils.js\";\nimport { Node } from \"./node.js\";\nvar Trie = class {\n #context = { varIndex: 0 };\n #root = new Node();\n #index = 0;\n // dynamic path -> [handler index, param assoc]; static paths are not registered\n paths = createNullObject();\n insert(path, isStatic) {\n if (isStatic) {\n this.#root.insert(path.split(\"\"), 0, [], this.#context, true);\n return;\n }\n const paramAssoc = [];\n const groups = [];\n let markedPath = path;\n for (let i = 0; ; ) {\n let replaced = false;\n markedPath = markedPath.replace(/\\{[^}]+\\}/g, (m) => {\n const mark = `@\\\\${i}`;\n groups[i] = [mark, m];\n i++;\n replaced = true;\n return mark;\n });\n if (!replaced) {\n break;\n }\n }\n const tokens = markedPath.match(/(?::[^\\/]+)|(?:\\/\\*$)|./g) || [];\n for (let i = groups.length - 1; i >= 0; i--) {\n const [mark] = groups[i];\n for (let j = tokens.length - 1; j >= 0; j--) {\n if (tokens[j].indexOf(mark) !== -1) {\n tokens[j] = tokens[j].replace(mark, groups[i][1]);\n break;\n }\n }\n }\n this.#root.insert(tokens, this.#index, paramAssoc, this.#context, false);\n this.paths[path] = [this.#index++, paramAssoc];\n }\n buildRegExp() {\n let regexp = this.#root.buildRegExpStr();\n if (regexp === \"\") {\n return [/^$/, [], []];\n }\n let captureIndex = 0;\n const indexReplacementMap = [];\n const paramReplacementMap = [];\n regexp = regexp.replace(/#(\\d+)|@(\\d+)|\\.\\*\\$/g, (_, handlerIndex, paramIndex) => {\n if (handlerIndex !== void 0) {\n indexReplacementMap[++captureIndex] = Number(handlerIndex);\n return \"$()\";\n }\n if (paramIndex !== void 0) {\n paramReplacementMap[Number(paramIndex)] = ++captureIndex;\n return \"\";\n }\n return \"\";\n });\n return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];\n }\n};\nexport {\n Trie\n};\n","// src/router/reg-exp-router/router.ts\nimport {\n MESSAGE_MATCHER_IS_ALREADY_BUILT,\n METHOD_NAME_ALL,\n UnsupportedPathError\n} from \"../../router.js\";\nimport { checkOptionalParameter } from \"../../utils/url.js\";\nimport { createNullObject } from \"../utils.js\";\nimport { match, emptyParam } from \"./matcher.js\";\nimport {\n LABEL_REG_EXP_STR,\n ONLY_WILDCARD_REG_EXP_STR,\n PATH_ERROR,\n TAIL_WILDCARD_REG_EXP_STR\n} from \"./node.js\";\nimport { Trie } from \"./trie.js\";\nvar wildcardRegExpCache = createNullObject();\nfunction buildWildcardRegExp(path) {\n return wildcardRegExpCache[path] ??= new RegExp(\n `^${path.replace(\n /\\/:[^/{}]+(?:\\{\\[\\^\\/]\\+})?(?=[/{]|$)|\\/?\\*$|([.\\\\+*[^\\]$()?{}|])/g,\n (match2, metaChar) => metaChar ? `\\\\${metaChar}` : match2 === \"/*\" ? TAIL_WILDCARD_REG_EXP_STR : match2 === \"*\" ? ONLY_WILDCARD_REG_EXP_STR : `/:${LABEL_REG_EXP_STR}`\n )}$`\n );\n}\nfunction findMiddleware(middleware, path) {\n for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {\n if (buildWildcardRegExp(k).test(path)) {\n return [...middleware[k]];\n }\n }\n return void 0;\n}\nvar RegExpRouter = class {\n name = \"RegExpRouter\";\n #middleware;\n #routes;\n #tries;\n constructor() {\n this.#middleware = { [METHOD_NAME_ALL]: createNullObject() };\n this.#routes = { [METHOD_NAME_ALL]: createNullObject() };\n this.#tries = { [METHOD_NAME_ALL]: new Trie() };\n }\n #insertPath(method, path) {\n try {\n this.#tries[method].insert(path, !/\\*|\\/:/.test(path));\n } catch (e) {\n throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;\n }\n }\n add(method, path, handler) {\n const middleware = this.#middleware;\n const routes = this.#routes;\n if (!middleware) {\n throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);\n }\n if (!middleware[method]) {\n this.#tries[method] = new Trie();\n for (const handlerMap of [middleware, routes]) {\n handlerMap[method] = createNullObject();\n for (const p in handlerMap[METHOD_NAME_ALL]) {\n handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];\n this.#insertPath(method, p);\n }\n }\n }\n if (path === \"/*\") {\n path = \"*\";\n }\n const methods = method === METHOD_NAME_ALL ? Object.keys(middleware) : [method];\n if (/\\*$/.test(path)) {\n const re = buildWildcardRegExp(path);\n for (const m of methods) {\n if (!middleware[m][path]) {\n this.#insertPath(m, path);\n middleware[m][path] = findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];\n }\n }\n for (const handlerMap of [middleware, routes]) {\n for (const m of methods) {\n for (const p in handlerMap[m]) {\n re.test(p) && handlerMap[m][p].push([handler, path]);\n }\n }\n }\n return;\n }\n const paths = checkOptionalParameter(path) || [path];\n for (const path2 of paths) {\n for (const m of methods) {\n if (!routes[m][path2]) {\n this.#insertPath(m, path2);\n routes[m][path2] = findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || [];\n }\n routes[m][path2].push([handler, path2]);\n }\n }\n }\n match = match;\n buildAllMatchers() {\n const matchers = createNullObject();\n for (const method of Object.keys(this.#routes)) {\n matchers[method] = this.#buildMatcher(method);\n }\n this.#middleware = this.#routes = this.#tries = void 0;\n wildcardRegExpCache = createNullObject();\n return matchers;\n }\n #buildMatcher(method) {\n const middleware = this.#middleware[method];\n const routes = this.#routes[method];\n const trie = this.#tries[method];\n const staticMap = createNullObject();\n const handlerData = [];\n const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();\n for (const r of [middleware, routes]) {\n for (const path in r) {\n const handlers = r[path];\n const pathData = trie.paths[path];\n if (!pathData) {\n staticMap[path] = [handlers.map(([h]) => [h, createNullObject()]), emptyParam];\n continue;\n }\n handlerData[pathData[0]] = handlers.map(([h, handlerPath]) => [\n h,\n trie.paths[handlerPath][1].reduceRight((map, [key], i) => {\n map[key] = paramReplacementMap[pathData[1][i][1]];\n return map;\n }, createNullObject())\n ]);\n }\n }\n return [regexp, indexReplacementMap.map((i) => handlerData[i]), staticMap];\n }\n};\nexport {\n RegExpRouter\n};\n","// src/router/smart-router/router.ts\nimport { MESSAGE_MATCHER_IS_ALREADY_BUILT, UnsupportedPathError } from \"../../router.js\";\nvar SmartRouter = class {\n name = \"SmartRouter\";\n #routers = [];\n #routes = [];\n constructor(init) {\n this.#routers = init.routers;\n }\n add(method, path, handler) {\n if (!this.#routes) {\n throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);\n }\n this.#routes.push([method, path, handler]);\n }\n match(method, path) {\n if (!this.#routes) {\n throw new Error(\"Fatal error\");\n }\n const routers = this.#routers;\n const routes = this.#routes;\n const len = routers.length;\n let i = 0;\n let res;\n for (; i < len; i++) {\n const router = routers[i];\n try {\n for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {\n router.add(...routes[i2]);\n }\n res = router.match(method, path);\n } catch (e) {\n if (e instanceof UnsupportedPathError) {\n continue;\n }\n throw e;\n }\n this.match = router.match.bind(router);\n this.#routers = [router];\n this.#routes = void 0;\n break;\n }\n if (i === len) {\n throw new Error(\"Fatal error\");\n }\n this.name = `SmartRouter + ${this.activeRouter.name}`;\n return res;\n }\n get activeRouter() {\n if (this.#routes || this.#routers.length !== 1) {\n throw new Error(\"No active router has been determined yet.\");\n }\n return this.#routers[0];\n }\n};\nexport {\n SmartRouter\n};\n","// src/router/trie-router/node.ts\nimport { METHOD_NAME_ALL } from \"../../router.js\";\nimport { getPattern, splitPath, splitRoutingPath } from \"../../utils/url.js\";\nimport { createNullObject } from \"../utils.js\";\nvar emptyParams = createNullObject();\nvar order = 0;\nvar Node = class _Node {\n #methods = [];\n #children = createNullObject();\n #patterns = [];\n #pattern;\n #params = emptyParams;\n insert(method, path, handler) {\n let curNode = this;\n const parts = splitRoutingPath(path);\n const possibleKeys = /* @__PURE__ */ new Set();\n let i = 0;\n for (const p of parts) {\n const nextP = parts[++i];\n const pattern = getPattern(p, nextP) || (nextP === void 0 && p && p.indexOf(\"*\") === p.length - 1 ? p : null);\n const isParam = Array.isArray(pattern);\n const key = isParam ? pattern[0] : pattern || p;\n const child = curNode.#children[key] ||= new _Node();\n if (pattern && !child.#pattern) {\n child.#pattern = pattern;\n curNode.#patterns.push(child);\n }\n curNode = child;\n if (isParam) {\n possibleKeys.add(pattern[1]);\n }\n }\n curNode.#methods.push({\n [method]: {\n handler,\n possibleKeys: [...possibleKeys],\n score: ++order\n }\n });\n }\n #pushHandlerSets(handlerSets, node, method, nodeParams, params) {\n for (let i = 0, len = node.#methods.length; i < len; i++) {\n const m = node.#methods[i];\n const handlerSet = m[method] || m[METHOD_NAME_ALL];\n if (handlerSet) {\n handlerSet.params = createNullObject();\n handlerSets.push(handlerSet);\n for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {\n const key = handlerSet.possibleKeys[i2];\n handlerSet.params[key] = params?.[key] && !i2 ? params[key] : nodeParams[key] ?? params?.[key];\n }\n }\n }\n }\n search(method, path) {\n const handlerSets = [];\n this.#params = emptyParams;\n const curNode = this;\n let curNodes = [curNode];\n const parts = splitPath(path);\n const curNodesQueue = [];\n const len = parts.length;\n let partOffsets = null;\n for (let i = 0; i < len; i++) {\n const part = parts[i];\n const isLast = i === len - 1;\n const tempNodes = [];\n for (let j = 0, len2 = curNodes.length; j < len2; j++) {\n const node = curNodes[j];\n const nextNode = node.#children[part];\n if (nextNode) {\n nextNode.#params = node.#params;\n if (isLast) {\n if (nextNode.#children[\"*\"]) {\n this.#pushHandlerSets(handlerSets, nextNode.#children[\"*\"], method, node.#params);\n }\n this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);\n } else {\n tempNodes.push(nextNode);\n }\n }\n for (const child of node.#patterns) {\n const pattern = child.#pattern;\n const params = node.#params === emptyParams ? {} : { ...node.#params };\n if (typeof pattern === \"string\") {\n if (pattern === \"*\" || part.startsWith(pattern.slice(0, -1))) {\n this.#pushHandlerSets(handlerSets, child, method, node.#params);\n if (pattern === \"*\") {\n child.#params = params;\n tempNodes.push(child);\n }\n }\n continue;\n }\n const [, name, matcher] = pattern;\n if (!part && matcher === true) {\n continue;\n }\n if (matcher !== true) {\n if (!partOffsets) {\n partOffsets = [];\n let offset = path[0] === \"/\" ? 1 : 0;\n for (let p = 0; p < len; p++) {\n partOffsets[p] = offset;\n offset += parts[p].length + 1;\n }\n }\n const restPathString = path.slice(partOffsets[i]);\n const m = matcher.exec(restPathString);\n if (m) {\n params[name] = m[0];\n this.#pushHandlerSets(handlerSets, child, method, node.#params, params);\n if (m[0].length === restPathString.length && child.#children[\"*\"]) {\n this.#pushHandlerSets(\n handlerSets,\n child.#children[\"*\"],\n method,\n node.#params,\n params\n );\n }\n for (const _ in child.#children) {\n child.#params = params;\n const componentCount = m[0].match(/\\//g)?.length ?? 0;\n const targetCurNodes = curNodesQueue[componentCount] ||= [];\n targetCurNodes.push(child);\n break;\n }\n continue;\n }\n }\n if (matcher === true || matcher.test(part)) {\n params[name] = part;\n if (isLast) {\n this.#pushHandlerSets(handlerSets, child, method, params, node.#params);\n if (child.#children[\"*\"]) {\n this.#pushHandlerSets(\n handlerSets,\n child.#children[\"*\"],\n method,\n params,\n node.#params\n );\n }\n } else {\n child.#params = params;\n tempNodes.push(child);\n }\n }\n }\n }\n const shifted = curNodesQueue.shift();\n curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;\n }\n if (handlerSets[1]) {\n handlerSets.sort((a, b) => {\n return a.score - b.score;\n });\n }\n return [handlerSets.map(({ handler, params }) => [handler, params])];\n }\n};\nexport {\n Node\n};\n","// src/router/trie-router/router.ts\nimport { checkOptionalParameter } from \"../../utils/url.js\";\nimport { Node } from \"./node.js\";\nvar TrieRouter = class {\n name = \"TrieRouter\";\n #node = new Node();\n add(method, path, handler) {\n for (const result of checkOptionalParameter(path) || [path]) {\n this.#node.insert(method, result, handler);\n }\n }\n match(method, path) {\n return this.#node.search(method, path);\n }\n};\nexport {\n TrieRouter\n};\n","// src/hono.ts\nimport { HonoBase } from \"./hono-base.js\";\nimport { RegExpRouter } from \"./router/reg-exp-router/index.js\";\nimport { SmartRouter } from \"./router/smart-router/index.js\";\nimport { TrieRouter } from \"./router/trie-router/index.js\";\nvar Hono = class extends HonoBase {\n /**\n * Creates an instance of the Hono class.\n *\n * @param options - Optional configuration options for the Hono instance.\n */\n constructor(options = {}) {\n super(options);\n this.router = options.router ?? new SmartRouter({\n routers: [new RegExpRouter(), new TrieRouter()]\n });\n }\n};\nexport {\n Hono\n};\n","import type { Context } from \"hono\";\nimport type { CoordinatorAuthBrowserConfig } from \"./coordinator-auth-browser-transaction-contract.js\";\nimport {\n\ttype CoordinatorAuthControllerStore,\n\ttype CoordinatorAuthControllerVerifiedSnapshot,\n\tcaptureVerifiedSnapshot,\n\tisAuthControllerId,\n} from \"./coordinator-auth-controller.js\";\nimport {\n\tassertConfiguredAuthSchema,\n\tauthSchemaUpgradeResponse,\n\tCoordinatorAuthSchemaUpgradeRequiredError,\n} from \"./coordinator-auth-schema.js\";\nimport type {\n\tCoordinatorEnrollment,\n\tCoordinatorInvite,\n\tCoordinatorStore,\n} from \"./coordinator-store-contract.js\";\n\nexport type CoordinatorControllerReviewStore = CoordinatorStore &\n\tPick<CoordinatorAuthControllerStore, \"createAuthControllerAttestation\">;\nexport interface CoordinatorControllerReviewDeps {\n\tconfig: CoordinatorAuthBrowserConfig;\n\tstoreFactory: () => CoordinatorControllerReviewStore;\n\tadminSecret: () => string | null;\n\treadRequestBytes: (c: Context, maxBytes: number) => Promise<Uint8Array | null>;\n\tparseJsonObject: (raw: Uint8Array) => Record<string, unknown> | null;\n\trateLimitedResponse: (\n\t\tc: Context,\n\t\tkey: string,\n\t\toptions: { authenticated: boolean },\n\t) => Response | null;\n}\ninterface ReviewInput {\n\tgroup_id: string;\n\tdevice_id: string;\n\tidentity_id: string;\n\tfingerprint: string;\n\tconfirm_evidence_digest?: string;\n}\nexport type CoordinatorControllerReviewReason =\n\t| \"group_unavailable\"\n\t| \"enrollment_unavailable\"\n\t| \"key_mismatch\"\n\t| \"enrollment_identity_mismatch\"\n\t| \"invite_identity_mismatch\"\n\t| \"invite_evidence_invalid\";\nexport interface CoordinatorControllerReviewPreview {\n\tstate: \"ready\" | \"needs_review\";\n\treasons: CoordinatorControllerReviewReason[];\n\tcoordinator_id: string;\n\tevidence_digest?: string;\n\tenrollment: {\n\t\tdevice_id: string;\n\t\tdisplay_name: string | null;\n\t\tfingerprint: string;\n\t\tidentity_label: \"none\" | \"matches\";\n\t} | null;\n\treviewed_invites: { invite_id: string; kind: \"team_member\" | \"add_device\" }[];\n\treviewed_invite_count: number;\n}\nconst PATH = \"/v1/admin/auth-controller-reviews\";\nconst FIELDS = [\"group_id\", \"device_id\", \"identity_id\", \"fingerprint\"] as const;\nconst ALLOWED_FIELDS: readonly string[] = [...FIELDS, \"confirm_evidence_digest\"];\nfunction isHash(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length === 64 && /^[a-f0-9]{64}$/.test(value);\n}\nfunction captureInput(data: Record<string, unknown> | null): ReviewInput | null {\n\tif (!data || Array.isArray(data)) return null;\n\tconst keys = Reflect.ownKeys(data);\n\tif (keys.some((key) => typeof key !== \"string\" || !ALLOWED_FIELDS.includes(key))) return null;\n\tconst copy: Record<string, string> = {};\n\tfor (const key of keys) {\n\t\tif (typeof key !== \"string\") return null;\n\t\tconst field = Object.getOwnPropertyDescriptor(data, key);\n\t\tif (!field || !Object.hasOwn(field, \"value\") || typeof field.value !== \"string\") return null;\n\t\tcopy[key] = field.value;\n\t}\n\tif (!FIELDS.every((key) => Object.hasOwn(copy, key))) return null;\n\tconst { group_id, device_id, identity_id, fingerprint } = copy;\n\tif (\n\t\t!isAuthControllerId(group_id) ||\n\t\t!isAuthControllerId(device_id) ||\n\t\t!isAuthControllerId(identity_id) ||\n\t\t!isHash(fingerprint)\n\t)\n\t\treturn null;\n\tif (Object.hasOwn(copy, \"confirm_evidence_digest\") && !isHash(copy.confirm_evidence_digest))\n\t\treturn null;\n\tconst input: ReviewInput = {\n\t\tgroup_id,\n\t\tdevice_id,\n\t\tidentity_id,\n\t\tfingerprint,\n\t};\n\tif (Object.hasOwn(copy, \"confirm_evidence_digest\"))\n\t\tinput.confirm_evidence_digest = copy.confirm_evidence_digest;\n\treturn input;\n}\nasync function digestBytes(value: string): Promise<ArrayBuffer> {\n\treturn globalThis.crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(value));\n}\nasync function hash(value: unknown): Promise<string> {\n\tconst bytes = await digestBytes(JSON.stringify(value));\n\treturn Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\nasync function authenticate(\n\tprovided: string | undefined,\n\tconfigured: string | null,\n): Promise<boolean> {\n\tif (!configured || !provided || provided.length > 8192) return false;\n\t// Native verification compares fixed-length MACs; no JS secret-string comparison.\n\tconst [expected, actual] = await Promise.all([digestBytes(configured), digestBytes(provided)]);\n\tconst key = await globalThis.crypto.subtle.importKey(\n\t\t\"raw\",\n\t\texpected,\n\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n\t\tfalse,\n\t\t[\"sign\", \"verify\"],\n\t);\n\tconst signature = await globalThis.crypto.subtle.sign(\"HMAC\", key, expected);\n\treturn globalThis.crypto.subtle.verify(\"HMAC\", key, signature, actual);\n}\nfunction boundInvites(\n\tinvites: CoordinatorInvite[],\n\tenrollment: CoordinatorEnrollment,\n): CoordinatorInvite[] {\n\treturn invites\n\t\t.filter(\n\t\t\t(invite) =>\n\t\t\t\tinvite.group_id === enrollment.group_id &&\n\t\t\t\tinvite.revoked_at === null &&\n\t\t\t\t!!invite.consumed_at &&\n\t\t\t\t(invite.invite_kind === \"team_member\" || invite.invite_kind === \"add_device\") &&\n\t\t\t\tinvite.bound_device_id === enrollment.device_id &&\n\t\t\t\tinvite.bound_public_key === enrollment.public_key &&\n\t\t\t\tinvite.bound_fingerprint === enrollment.fingerprint,\n\t\t)\n\t\t.map((invite) => ({ ...invite }))\n\t\t.sort((a, b) => (a.invite_id < b.invite_id ? -1 : Number(a.invite_id > b.invite_id)));\n}\nfunction inviteIdentityMatches(invite: CoordinatorInvite, identityId: string): boolean {\n\tconst authoritative =\n\t\tinvite.invite_kind === \"team_member\" ? invite.assigned_identity_id : invite.target_identity_id;\n\treturn authoritative === identityId && invite.recipient_actor_id === identityId;\n}\nfunction enrollmentReasons(\n\tenrollment: CoordinatorEnrollment | null,\n\tinput: ReviewInput,\n): CoordinatorControllerReviewReason[] {\n\tif (enrollment?.enabled !== 1) return [\"enrollment_unavailable\"];\n\tconst reasons: CoordinatorControllerReviewReason[] = [];\n\tif (enrollment.fingerprint !== input.fingerprint) reasons.push(\"key_mismatch\");\n\tif (enrollment.identity_id !== null && enrollment.identity_id !== input.identity_id)\n\t\treasons.push(\"enrollment_identity_mismatch\");\n\treturn reasons;\n}\nasync function preview(\n\tstore: CoordinatorControllerReviewStore,\n\tinput: ReviewInput,\n\tcoordinatorId: string,\n) {\n\tconst groupResult = await store.getGroup(input.group_id);\n\tconst group = groupResult ? { ...groupResult } : null;\n\tconst enrollmentResult = await store.getEnrollment(input.group_id, input.device_id);\n\tconst enrollment = enrollmentResult ? { ...enrollmentResult } : null;\n\tconst reasons = enrollmentReasons(enrollment, input);\n\tif (!group || group.archived_at !== null) reasons.push(\"group_unavailable\");\n\tconst bound = enrollment ? boundInvites(await store.listInvites(input.group_id), enrollment) : [];\n\tif (bound.some((invite) => !inviteIdentityMatches(invite, input.identity_id)))\n\t\treasons.push(\"invite_identity_mismatch\");\n\tif (bound.some((invite) => !isHash(invite.reviewed_preview_digest)))\n\t\treasons.push(\"invite_evidence_invalid\");\n\tconst invites = bound.filter((invite) => isHash(invite.reviewed_preview_digest));\n\tconst verifiedSnapshot = verifiedInviteSnapshot(enrollment, invites);\n\taddSnapshotReasons(verifiedSnapshot, reasons);\n\tconst result: CoordinatorControllerReviewPreview = {\n\t\tstate: reasons.length ? \"needs_review\" : \"ready\",\n\t\treasons,\n\t\tcoordinator_id: coordinatorId,\n\t\tenrollment: null,\n\t\treviewed_invite_count: invites.length,\n\t\t// Ten references fit the action's 16 KiB limit even with 256-character Unicode IDs.\n\t\treviewed_invites: invites.slice(0, 10).map((invite) => ({\n\t\t\tinvite_id: invite.invite_id,\n\t\t\tkind: invite.invite_kind as \"team_member\" | \"add_device\",\n\t\t})),\n\t};\n\tif (enrollment && !reasons.includes(\"enrollment_identity_mismatch\"))\n\t\tresult.enrollment = {\n\t\t\tdevice_id: enrollment.device_id,\n\t\t\tdisplay_name: enrollment.display_name?.slice(0, 256) ?? null,\n\t\t\tfingerprint: enrollment.fingerprint,\n\t\t\tidentity_label: enrollment.identity_id === null ? \"none\" : \"matches\",\n\t\t};\n\tif (result.state === \"ready\" && enrollment)\n\t\tresult.evidence_digest = await hash([\n\t\t\t\"codemem-controller-review-v1\",\n\t\t\tcoordinatorId,\n\t\t\tinput.group_id,\n\t\t\tenrollment.device_id,\n\t\t\tenrollment.public_key,\n\t\t\tenrollment.fingerprint,\n\t\t\tinput.identity_id,\n\t\t\tenrollment.identity_id,\n\t\t\tinvites.map((invite) => [\n\t\t\t\tinvite.invite_id,\n\t\t\t\tinvite.invite_kind,\n\t\t\t\tinvite.recipient_actor_id,\n\t\t\t\tinvite.assigned_identity_id,\n\t\t\t\tinvite.target_identity_id,\n\t\t\t\tinvite.reviewed_preview_digest,\n\t\t\t]),\n\t\t]);\n\treturn { result, enrollment, verifiedSnapshot };\n}\nfunction addSnapshotReasons(\n\tsnapshot: CoordinatorAuthControllerVerifiedSnapshot,\n\treasons: CoordinatorControllerReviewReason[],\n): void {\n\tif (!captureVerifiedSnapshot(snapshot)) reasons.push(\"invite_evidence_invalid\");\n}\nfunction verifiedInviteSnapshot(\n\tenrollment: CoordinatorEnrollment | null,\n\tinvites: CoordinatorInvite[],\n): CoordinatorAuthControllerVerifiedSnapshot {\n\treturn {\n\t\tenrollmentIdentityId: enrollment?.identity_id ?? null,\n\t\tinvites: invites.map((invite) => ({\n\t\t\tinviteId: invite.invite_id,\n\t\t\tkind: invite.invite_kind as \"team_member\" | \"add_device\",\n\t\t\tactorId: invite.recipient_actor_id as string,\n\t\t\tassignedIdentityId: invite.assigned_identity_id ?? null,\n\t\t\ttargetIdentityId: invite.target_identity_id ?? null,\n\t\t\tdigest: invite.reviewed_preview_digest as string,\n\t\t})),\n\t};\n}\nasync function applyReview(\n\tc: Context,\n\tstore: CoordinatorControllerReviewStore,\n\tinput: ReviewInput,\n\tcoordinatorId: string,\n): Promise<Response> {\n\tconst { result, enrollment, verifiedSnapshot } = await preview(store, input, coordinatorId);\n\tif (input.confirm_evidence_digest === undefined) return c.json(result);\n\tif (result.state !== \"ready\" || !enrollment || !result.evidence_digest)\n\t\treturn c.json({ error: \"needs_review\", ...result }, 409);\n\tif (input.confirm_evidence_digest !== result.evidence_digest)\n\t\treturn c.json({ error: \"review_stale\" }, 409);\n\tconst attestationId = `controller-v1:${await hash([coordinatorId, input.group_id, input.device_id, input.fingerprint])}`;\n\tconst reviewReceiptId = `review-v1:${await hash([attestationId, input.identity_id, result.evidence_digest])}`;\n\tconst created = await store.createAuthControllerAttestation({\n\t\tattestationId,\n\t\tcoordinatorId,\n\t\tidentityId: input.identity_id,\n\t\tgroupId: input.group_id,\n\t\tdeviceId: input.device_id,\n\t\tpublicKey: enrollment.public_key,\n\t\tfingerprint: enrollment.fingerprint,\n\t\treviewReceiptId,\n\t\tevidenceDigest: result.evidence_digest,\n\t\tverifiedSnapshot,\n\t});\n\tif (created.kind === \"rejected\") {\n\t\tif (created.error === \"enrollment_mismatch\" || created.error === \"review_stale\")\n\t\t\treturn c.json({ error: \"review_stale\" }, 409);\n\t\tif (created.error === \"attestation_conflict\" || created.error === \"attestation_revoked\")\n\t\t\treturn c.json({ error: \"already_reviewed_or_needs_review\" }, 409);\n\t\treturn c.json({ error: \"review_unavailable\" }, 403);\n\t}\n\tconst row = created.attestation;\n\treturn c.json(\n\t\t{\n\t\t\tstate: created.kind,\n\t\t\tattestation_id: row.attestation_id,\n\t\t\tcoordinator_id: row.coordinator_id,\n\t\t\tgroup_id: row.group_id,\n\t\t\tdevice_id: row.device_id,\n\t\t\tfingerprint: row.fingerprint,\n\t\t\tidentity_id: row.identity_id,\n\t\t\tcreated_at: row.created_at,\n\t\t},\n\t\tcreated.kind === \"created\" ? 201 : 200,\n\t);\n}\nasync function handleReview(c: Context, deps: CoordinatorControllerReviewDeps): Promise<Response> {\n\tc.header(\"Cache-Control\", \"no-store\");\n\tc.header(\"Referrer-Policy\", \"no-referrer\");\n\tc.header(\"X-Content-Type-Options\", \"nosniff\");\n\tlet store: CoordinatorControllerReviewStore | undefined;\n\ttry {\n\t\ttry {\n\t\t\tconst provided = c.req.header(\"X-Codemem-Coordinator-Admin\");\n\t\t\tconst configured = deps.adminSecret();\n\t\t\tif (!(await authenticate(provided, configured))) {\n\t\t\t\treturn (\n\t\t\t\t\tdeps.rateLimitedResponse(c, \"controller-review:anonymous\", { authenticated: false }) ??\n\t\t\t\t\tc.json({ error: \"unauthorized\" }, 401)\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst limited = deps.rateLimitedResponse(c, \"controller-review:admin\", {\n\t\t\t\tauthenticated: true,\n\t\t\t});\n\t\t\tif (limited) return limited;\n\t\t\tconst raw = await deps.readRequestBytes(c, 4096);\n\t\t\tif (!raw) return c.json({ error: \"body_too_large\" }, 413);\n\t\t\tconst input = captureInput(deps.parseJsonObject(raw));\n\t\t\tif (!input) return c.json({ error: \"review_invalid_input\" }, 400);\n\t\t\tstore = deps.storeFactory();\n\t\t\tawait assertConfiguredAuthSchema(store);\n\t\t\treturn await applyReview(c, store, input, deps.config.coordinatorId);\n\t\t} finally {\n\t\t\tawait store?.close();\n\t\t}\n\t} catch (error) {\n\t\tif (error instanceof CoordinatorAuthSchemaUpgradeRequiredError)\n\t\t\treturn authSchemaUpgradeResponse();\n\t\treturn c.json({ error: \"review_unavailable\" }, 503);\n\t}\n}\n/** Existing configured admin authority only; local evidence is not an authentication proof. */\nexport function registerCoordinatorAuthControllerReviewRoutes(\n\tapp: { post(path: string, handler: (c: Context) => Promise<Response>): unknown },\n\tdeps: CoordinatorControllerReviewDeps,\n): void {\n\tif (!deps.config.enabled) return;\n\tconst { enabled, coordinatorId, issuer, revision, redirectUri } = deps.config;\n\tconst captured = {\n\t\t...deps,\n\t\tconfig: Object.freeze({ enabled, coordinatorId, issuer, revision, redirectUri }),\n\t};\n\tapp.post(PATH, (c) => handleReview(c, captured));\n}\n","/** Separate proof domain from initial account linking. Safe for runtime clients. */\nexport const AUTH_ACCOUNT_CHANGE_PURPOSE = \"coordinator-account-change-v1\";\nexport type CoordinatorAccountChangeIntent = \"refresh\" | \"disconnect\";\n","import type { Context, Hono } from \"hono\";\nimport type { AccountChangeOperations } from \"./coordinator-account-change.js\";\nimport { AUTH_ACCOUNT_CHANGE_PURPOSE } from \"./coordinator-account-change-contract.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { CoordinatorAuthLinkSigner } from \"./coordinator-auth-link-contract.js\";\nimport { parseCoordinatorAuthLoopback } from \"./coordinator-auth-loopback.js\";\nimport {\n\tdecodeCoordinatorAuthProof32,\n\thashCoordinatorAuthProofBytes32,\n} from \"./coordinator-auth-proof.js\";\nimport type { registerCoordinatorDeviceAuthLinkRoutes } from \"./coordinator-device-auth-link.js\";\n\ntype LinkDeps = Parameters<typeof registerCoordinatorDeviceAuthLinkRoutes>[1];\ntype ChangeOperations = Pick<\n\tAccountChangeOperations,\n\t\"create\" | \"readStatus\" | \"finalize\" | \"cancel\" | \"readCapabilities\" | \"unlink\"\n>;\nexport interface CoordinatorDeviceAccountChangeOptions {\n\tconfig: LinkDeps[\"config\"];\n\tstoreFactory: LinkDeps[\"storeFactory\"];\n\t/** Must check the account-change schema, not only the older link schema. */\n\tassertReady: (store: ReturnType<LinkDeps[\"storeFactory\"]>) => Promise<void>;\n\toperationsFactory: (\n\t\tstore: ReturnType<LinkDeps[\"storeFactory\"]>,\n\t) => ChangeOperations | null | Promise<ChangeOperations | null>;\n}\ntype Deps = Omit<LinkDeps, \"config\" | \"storeFactory\"> & CoordinatorDeviceAccountChangeOptions;\ntype Action = \"create\" | \"status\" | \"finalize\" | \"cancel\" | \"capabilities\" | \"unlink\";\nconst pins = [\"group_id\", \"identity_id\", \"runtime_verifier_hash\"] as const;\nconst fields = {\n\tunlink: [\"group_id\", \"identity_id\", \"attempt_id\", \"target_link_id\"],\n\tcapabilities: [\"group_id\", \"identity_id\"],\n\tcreate: [...pins, \"intent\", \"attempt_id\", \"browser_start_hash\", \"loopback_redirect\"],\n\tstatus: pins,\n\tcancel: pins,\n\tfinalize: [\n\t\t\"purpose\",\n\t\t\"coordinator_id\",\n\t\t\"attempt_id\",\n\t\t\"group_id\",\n\t\t\"identity_id\",\n\t\t\"device_id\",\n\t\t\"fingerprint\",\n\t\t\"runtime_verifier\",\n\t\t\"completion\",\n\t],\n} as const;\ntype Input = Record<(typeof fields)[Action][number], string>;\nconst isHash = (value: string) => /^[a-f0-9]{64}$/.test(value);\nfunction exactInput(value: Record<string, unknown> | null, action: Action): value is Input {\n\treturn (\n\t\tvalue !== null &&\n\t\tObject.keys(value).length === fields[action].length &&\n\t\tfields[action].every((key) => Object.hasOwn(value, key) && typeof value[key] === \"string\")\n\t);\n}\nfunction unavailable(c: Context): Response {\n\treturn c.json({ error: \"authentication_unavailable\" }, 503);\n}\nfunction denied(c: Context): Response {\n\treturn c.json({ error: \"account_change_unavailable\" }, 403);\n}\nfunction invalid(c: Context): Response {\n\treturn c.json({ error: \"account_change_invalid_input\" }, 400);\n}\n\nasync function readInput(c: Context, action: Action, deps: Deps) {\n\tconst url = new URL(c.req.url);\n\tif (url.origin !== new URL(deps.config.redirectUri).origin) return denied(c);\n\tif (action === \"status\" || action === \"capabilities\") {\n\t\tconst entries = [...url.searchParams.entries()];\n\t\tif (c.req.raw.body !== null || entries.length !== fields[action].length) return invalid(c);\n\t\tconst data = Object.fromEntries(entries);\n\t\tif (!exactInput(data, action)) return invalid(c);\n\t\treturn { data, raw: new Uint8Array() };\n\t}\n\tif (url.search) return invalid(c);\n\tconst raw = await deps.readRequestBytes(c, 4096);\n\tif (!raw) return c.json({ error: \"body_too_large\" }, 413);\n\tconst data = deps.parseJsonObject(raw);\n\tif (!exactInput(data, action)) return invalid(c);\n\treturn { data, raw };\n}\nfunction validPins(data: Input, attemptId: string): boolean {\n\treturn (\n\t\tisAuthControllerId(attemptId) &&\n\t\tisAuthControllerId(data.group_id) &&\n\t\tisAuthControllerId(data.identity_id)\n\t);\n}\nfunction validInput(data: Input, action: Action, attemptId: string, deps: Deps): boolean {\n\tif (action === \"capabilities\")\n\t\treturn isAuthControllerId(data.group_id) && isAuthControllerId(data.identity_id);\n\tif (!validPins(data, attemptId)) return false;\n\tif (action === \"unlink\") return isAuthControllerId(data.target_link_id);\n\tif (action === \"finalize\") {\n\t\treturn (\n\t\t\tdata.purpose === AUTH_ACCOUNT_CHANGE_PURPOSE &&\n\t\t\tdata.coordinator_id === deps.config.coordinatorId &&\n\t\t\tdata.attempt_id === attemptId &&\n\t\t\tisAuthControllerId(data.device_id) &&\n\t\t\tisHash(data.fingerprint) &&\n\t\t\tdecodeCoordinatorAuthProof32(data.runtime_verifier) !== null &&\n\t\t\tdecodeCoordinatorAuthProof32(data.completion) !== null\n\t\t);\n\t}\n\tif (!isHash(data.runtime_verifier_hash)) return false;\n\tif (action !== \"create\") return true;\n\treturn (\n\t\t(data.intent === \"refresh\" || data.intent === \"disconnect\") &&\n\t\tisHash(data.browser_start_hash) &&\n\t\tparseCoordinatorAuthLoopback(data.loopback_redirect).ok\n\t);\n}\nasync function finalizeProof(\n\tc: Context,\n\tdata: Input,\n\tinput: {\n\t\tattemptId: string;\n\t\tsigner: CoordinatorAuthLinkSigner;\n\t\texpectedIdentityId: string;\n\t\truntimeVerifierHash: string;\n\t},\n\toperations: ChangeOperations,\n\tdeps: Deps,\n): Promise<string | Response> {\n\tif (data.device_id !== input.signer.deviceId || data.fingerprint !== input.signer.fingerprint)\n\t\treturn denied(c);\n\tconst verifier = decodeCoordinatorAuthProof32(data.runtime_verifier);\n\tconst completion = decodeCoordinatorAuthProof32(data.completion);\n\tif (!verifier || !completion) return invalid(c);\n\tconst runtimeVerifierHash = await hashCoordinatorAuthProofBytes32(verifier);\n\tconst result = await operations.finalize(\n\t\t{\n\t\t\t...input,\n\t\t\truntimeVerifierHash,\n\t\t\tcompletionSecretHash: await hashCoordinatorAuthProofBytes32(completion),\n\t\t},\n\t\tdeps.config,\n\t);\n\treturn result ? runtimeVerifierHash : denied(c);\n}\nasync function applyAction(\n\tc: Context,\n\taction: Action,\n\tdata: Input,\n\tattemptId: string,\n\tsigner: CoordinatorAuthLinkSigner,\n\toperations: ChangeOperations,\n\tdeps: Deps,\n): Promise<Response> {\n\tif (action === \"unlink\") return applyUnlink(c, data, attemptId, signer, operations, deps);\n\tif (action === \"capabilities\") {\n\t\tconst { unlinkTarget, ...actions } = await operations.readCapabilities(\n\t\t\t{ signer, expectedIdentityId: data.identity_id },\n\t\t\tdeps.config,\n\t\t);\n\t\treturn c.json({\n\t\t\tcoordinator_id: deps.config.coordinatorId,\n\t\t\tidentity_id: data.identity_id,\n\t\t\tactions,\n\t\t\t...(unlinkTarget ? { unlink_target: unlinkTarget } : {}),\n\t\t});\n\t}\n\treturn applyBrowserAction(c, action, data, attemptId, signer, operations, deps);\n}\nasync function applyUnlink(\n\tc: Context,\n\tdata: Input,\n\tattemptId: string,\n\tsigner: CoordinatorAuthLinkSigner,\n\toperations: ChangeOperations,\n\tdeps: Deps,\n): Promise<Response> {\n\tconst digest = await crypto.subtle.digest(\n\t\t\"SHA-256\",\n\t\tnew TextEncoder().encode(JSON.stringify(fields.unlink.map((key) => data[key]))),\n\t);\n\tconst requestHash = Array.from(new Uint8Array(digest), (byte) =>\n\t\tbyte.toString(16).padStart(2, \"0\"),\n\t).join(\"\");\n\tconst result = await operations.unlink(\n\t\t{\n\t\t\tattemptId,\n\t\t\tsigner,\n\t\t\texpectedIdentityId: data.identity_id,\n\t\t\texpectedLinkId: data.target_link_id,\n\t\t\trequestHash,\n\t\t},\n\t\tdeps.config,\n\t);\n\treturn result\n\t\t? c.json({\n\t\t\t\tstate: \"completed\",\n\t\t\t\tattemptId,\n\t\t\t\tidentityId: data.identity_id,\n\t\t\t\tcoordinatorId: deps.config.coordinatorId,\n\t\t\t\ttargetLinkId: result.targetLinkId,\n\t\t\t})\n\t\t: denied(c);\n}\nasync function applyBrowserAction(\n\tc: Context,\n\taction: Action,\n\tdata: Input,\n\tattemptId: string,\n\tsigner: CoordinatorAuthLinkSigner,\n\toperations: ChangeOperations,\n\tdeps: Deps,\n): Promise<Response> {\n\tconst input = {\n\t\tattemptId,\n\t\tsigner,\n\t\texpectedIdentityId: data.identity_id,\n\t\truntimeVerifierHash: data.runtime_verifier_hash,\n\t};\n\tif (action === \"finalize\") {\n\t\tconst proof = await finalizeProof(c, data, input, operations, deps);\n\t\tif (proof instanceof Response) return proof;\n\t\tinput.runtimeVerifierHash = proof;\n\t}\n\tif (action === \"create\") {\n\t\tconst created = await operations.create(\n\t\t\t{\n\t\t\t\t...input,\n\t\t\t\tintent: data.intent,\n\t\t\t\tbrowserStartHash: data.browser_start_hash,\n\t\t\t\tloopbackRedirect: data.loopback_redirect,\n\t\t\t},\n\t\t\tdeps.config,\n\t\t);\n\t\tif (!created) return denied(c);\n\t}\n\tif (action === \"cancel\" && !(await operations.cancel(input, deps.config))) return denied(c);\n\tconst status = await operations.readStatus(input, deps.config);\n\tif (!status) return denied(c);\n\t// Explicit allowlist: private browser state and provider data never cross HTTP.\n\tconst publicStatus = {\n\t\tattemptId: status.attemptId,\n\t\tintent: status.intent,\n\t\tstate: status.state,\n\t\texpiresAtMs: status.expiresAtMs,\n\t\tidentityId: status.identityId,\n\t};\n\tif (action === \"finalize\" && status.state !== \"completed\") return unavailable(c);\n\tif (action === \"create\")\n\t\treturn c.json({\n\t\t\tcoordinator_id: deps.config.coordinatorId,\n\t\t\tidentity_id: status.identityId,\n\t\t\tstatus: publicStatus,\n\t\t});\n\treturn c.json({ status: publicStatus });\n}\nasync function handle(c: Context, action: Action, deps: Deps): Promise<Response> {\n\tc.header(\"Cache-Control\", \"no-store\");\n\tc.header(\"Referrer-Policy\", \"no-referrer\");\n\tlet store: ReturnType<Deps[\"storeFactory\"]> | undefined;\n\ttry {\n\t\ttry {\n\t\t\tconst input = await readInput(c, action, deps);\n\t\t\tif (input instanceof Response) return input;\n\t\t\tconst attemptId = [\"create\", \"unlink\"].includes(action)\n\t\t\t\t? input.data.attempt_id\n\t\t\t\t: (c.req.param(\"attemptId\") ?? \"\");\n\t\t\tif (!validInput(input.data, action, attemptId, deps)) return invalid(c);\n\t\t\tstore = deps.storeFactory();\n\t\t\tconst auth = await deps.authorizeRequest(store, {\n\t\t\t\tmethod: c.req.method,\n\t\t\t\turl: c.req.url,\n\t\t\t\tgroupId: input.data.group_id,\n\t\t\t\tbody: input.raw,\n\t\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t\t});\n\t\t\tif (!auth.ok || !auth.enrollment)\n\t\t\t\treturn (\n\t\t\t\t\tdeps.rateLimitedResponse(c, `account-change:${action}`, { authenticated: false }) ??\n\t\t\t\t\tc.json({ error: \"account_change_unavailable\" }, deps.authErrorStatus(auth.error))\n\t\t\t\t);\n\t\t\tconst enrollment = auth.enrollment;\n\t\t\tconst limited = deps.rateLimitedResponse(\n\t\t\t\tc,\n\t\t\t\t`${deps.config.coordinatorId}:${enrollment.device_id}`,\n\t\t\t\t{ authenticated: true },\n\t\t\t);\n\t\t\tif (limited) return limited;\n\t\t\tawait deps.assertReady(store);\n\t\t\tconst operations = await deps.operationsFactory(store);\n\t\t\tif (!operations) return c.json({ error: \"not_found\" }, 404);\n\t\t\treturn await applyAction(\n\t\t\t\tc,\n\t\t\t\taction,\n\t\t\t\tinput.data,\n\t\t\t\tattemptId,\n\t\t\t\t{\n\t\t\t\t\tgroupId: enrollment.group_id,\n\t\t\t\t\tdeviceId: enrollment.device_id,\n\t\t\t\t\tpublicKey: enrollment.public_key,\n\t\t\t\t\tfingerprint: enrollment.fingerprint,\n\t\t\t\t},\n\t\t\t\toperations,\n\t\t\t\tdeps,\n\t\t\t);\n\t\t} finally {\n\t\t\tawait store?.close();\n\t\t}\n\t} catch {\n\t\treturn unavailable(c);\n\t}\n}\n\n/** Explicit capability only; signed admission precedes account-change schema checks. */\nexport function registerCoordinatorDeviceAccountChangeRoutes(app: Hono, deps: Deps): void {\n\tif (!deps.config.enabled) return;\n\tconst { coordinatorId, issuer, revision, enabled, redirectUri } = deps.config;\n\tconst captured = {\n\t\t...deps,\n\t\tconfig: Object.freeze({ coordinatorId, issuer, revision, enabled, redirectUri }),\n\t};\n\tapp.post(\"/v1/auth/account-changes\", (c) => handle(c, \"create\", captured));\n\tapp.post(\"/v1/auth/account-unlinks\", (c) => handle(c, \"unlink\", captured));\n\tapp.get(\"/v1/auth/account-changes\", (c) => handle(c, \"capabilities\", captured));\n\tapp.get(\"/v1/auth/account-changes/:attemptId\", (c) => handle(c, \"status\", captured));\n\tapp.post(\"/v1/auth/account-changes/:attemptId/finalize\", (c) => handle(c, \"finalize\", captured));\n\tapp.post(\"/v1/auth/account-changes/:attemptId/cancel\", (c) => handle(c, \"cancel\", captured));\n}\n","import type { Context } from \"hono\";\nimport type { CoordinatorAccountLinkStatusStore } from \"./coordinator-account-link-status.js\";\nimport type {\n\tCoordinatorAuthBrowserConfig,\n\tCoordinatorAuthBrowserTransactionStore,\n} from \"./coordinator-auth-browser-transaction-contract.js\";\nimport type { CoordinatorAuthControllerStore } from \"./coordinator-auth-controller.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport {\n\tAUTH_LINK_PURPOSE,\n\ttype CoordinatorAuthLinkRejected,\n\ttype CoordinatorAuthLinkSigner,\n\ttype CoordinatorAuthLinkStore,\n} from \"./coordinator-auth-link-contract.js\";\nimport { parseCoordinatorAuthLoopback } from \"./coordinator-auth-loopback.js\";\nimport {\n\tdecodeCoordinatorAuthProof32,\n\thashCoordinatorAuthProofBytes32,\n} from \"./coordinator-auth-proof.js\";\nimport {\n\tassertConfiguredAuthSchema,\n\tauthSchemaUpgradeResponse,\n\tCoordinatorAuthSchemaUpgradeRequiredError,\n} from \"./coordinator-auth-schema.js\";\nimport type { CoordinatorEnrollment, CoordinatorStore } from \"./coordinator-store-contract.js\";\n\nexport type CoordinatorDeviceAuthLinkStore = CoordinatorStore &\n\tPartial<CoordinatorAccountLinkStatusStore> &\n\tPick<CoordinatorAuthControllerStore, \"createAuthControllerAttestation\"> &\n\tPick<\n\t\tCoordinatorAuthLinkStore,\n\t\t| \"createAuthLinkAttempt\"\n\t\t| \"getAuthLinkAttemptStatus\"\n\t\t| \"finalizeAuthLinkAttempt\"\n\t\t| \"failAuthLinkAttempt\"\n\t> &\n\tPick<CoordinatorAuthBrowserTransactionStore, \"retireAuthBrowserTransactions\">;\n\nexport interface CoordinatorDeviceAuthLinkOptions {\n\tconfig: CoordinatorAuthBrowserConfig;\n\tstoreFactory: () => CoordinatorDeviceAuthLinkStore;\n}\n\ninterface SignedRequest {\n\tmethod: string;\n\turl: string;\n\tgroupId: string;\n\tbody: Uint8Array;\n\tdeviceId: string | null;\n\tsignature: string | null;\n\ttimestamp: string | null;\n\tnonce: string | null;\n}\ninterface DeviceAuthLinkDeps extends CoordinatorDeviceAuthLinkOptions {\n\tauthorizeRequest: (\n\t\tstore: CoordinatorDeviceAuthLinkStore,\n\t\trequest: SignedRequest,\n\t) => Promise<{ ok: boolean; error: string; enrollment: CoordinatorEnrollment | null }>;\n\tauthErrorStatus: (error: string) => 401 | 403 | 409;\n\treadRequestBytes: (c: Context, maxBytes: number) => Promise<Uint8Array | null>;\n\tparseJsonObject: (raw: Uint8Array) => Record<string, unknown> | null;\n\trateLimitedResponse: (\n\t\tc: Context,\n\t\tkey: string,\n\t\toptions: { authenticated: boolean },\n\t) => Response | null;\n}\ninterface DeviceAuthLinkApp {\n\tget(path: string, handler: (c: Context) => Promise<Response>): unknown;\n\tpost(path: string, handler: (c: Context) => Promise<Response>): unknown;\n}\ntype Action = \"create\" | \"status\" | \"finalize\" | \"cancel\" | \"account_status\";\nconst FIELDS = {\n\tcreate: [\n\t\t\"group_id\",\n\t\t\"identity_id\",\n\t\t\"authority\",\n\t\t\"attempt_id\",\n\t\t\"runtime_verifier_hash\",\n\t\t\"browser_start_hash\",\n\t\t\"loopback_redirect\",\n\t],\n\tfinalize: [\n\t\t\"purpose\",\n\t\t\"coordinator_id\",\n\t\t\"attempt_id\",\n\t\t\"group_id\",\n\t\t\"identity_id\",\n\t\t\"device_id\",\n\t\t\"fingerprint\",\n\t\t\"runtime_verifier\",\n\t\t\"completion\",\n\t],\n\tcancel: [\"group_id\"],\n} as const;\n\nfunction exactStrings<T extends string>(\n\tdata: Record<string, unknown> | null,\n\tfields: readonly T[],\n): data is Record<T, string> {\n\treturn (\n\t\tdata !== null &&\n\t\tObject.keys(data).length === fields.length &&\n\t\tfields.every((field) => Object.hasOwn(data, field) && typeof data[field] === \"string\")\n\t);\n}\nfunction isHash(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length === 64 && /^[a-f0-9]{64}$/.test(value);\n}\nfunction validInput(\n\taction: Action,\n\tdata: Record<string, unknown>,\n\tattemptId: string,\n\tconfig: CoordinatorAuthBrowserConfig,\n): data is Record<string, unknown> & { group_id: string } {\n\tif (!isAuthControllerId(data.group_id) || !isAuthControllerId(attemptId)) return false;\n\tif (action === \"create\") {\n\t\treturn (\n\t\t\texactStrings(data, FIELDS.create) &&\n\t\t\tisAuthControllerId(data.identity_id) &&\n\t\t\t(data.authority === \"device_claim\" || data.authority === \"controller_attestation\") &&\n\t\t\tisHash(data.runtime_verifier_hash) &&\n\t\t\tisHash(data.browser_start_hash) &&\n\t\t\tparseCoordinatorAuthLoopback(data.loopback_redirect).ok\n\t\t);\n\t}\n\tif (action !== \"finalize\") return true;\n\treturn (\n\t\texactStrings(data, FIELDS.finalize) &&\n\t\tdata.purpose === AUTH_LINK_PURPOSE &&\n\t\tdata.coordinator_id === config.coordinatorId &&\n\t\tdata.attempt_id === attemptId &&\n\t\tisAuthControllerId(data.identity_id) &&\n\t\tisAuthControllerId(data.device_id) &&\n\t\tisHash(data.fingerprint) &&\n\t\tdecodeCoordinatorAuthProof32(data.runtime_verifier) !== null &&\n\t\tdecodeCoordinatorAuthProof32(data.completion) !== null\n\t);\n}\nfunction rejectedResponse(\n\tc: Context,\n\tresult: CoordinatorAuthLinkRejected,\n\toptions: { reviewRequired?: boolean } = {},\n): Response {\n\tif (result.error === \"attempt_limited\") return c.json({ error: \"auth_link_limited\" }, 429);\n\tif (result.error === \"attempt_conflict\" || result.error === \"link_conflict\") {\n\t\treturn c.json({ error: \"auth_link_conflict\" }, 409);\n\t}\n\tif (options.reviewRequired && result.error === \"controller_not_active\") {\n\t\treturn c.json({ error: \"auth_link_review_required\" }, 403);\n\t}\n\treturn c.json({ error: \"auth_link_unavailable\" }, 403);\n}\n\nasync function applyDeviceAction(\n\tc: Context,\n\taction: Action,\n\tstore: CoordinatorDeviceAuthLinkStore,\n\tdata: Record<string, unknown> & { group_id: string },\n\tattemptId: string,\n\tsigner: CoordinatorAuthLinkSigner,\n\tconfig: CoordinatorAuthBrowserConfig,\n): Promise<Response> {\n\tif (action === \"account_status\") {\n\t\tif (!store.readAccountLinkStatus) return c.json({ error: \"auth_link_unavailable\" }, 503);\n\t\treturn c.json(\n\t\t\tawait store.readAccountLinkStatus(signer, config, { identityId: String(data.identity_id) }),\n\t\t);\n\t}\n\tif (action === \"status\") {\n\t\tconst status = await store.getAuthLinkAttemptStatus(\n\t\t\tattemptId,\n\t\t\t{ kind: \"device\", signer },\n\t\t\tconfig,\n\t\t);\n\t\tif (!status) return c.json({ error: \"auth_link_unavailable\" }, 404);\n\t\treturn c.json({ status });\n\t}\n\tif (action === \"create\") {\n\t\treturn createDeviceAttempt(c, store, data, attemptId, signer, config);\n\t}\n\tif (action === \"cancel\") {\n\t\treturn cancelDeviceAttempt(c, store, attemptId, signer, config);\n\t}\n\tif (!exactStrings(data, FIELDS.finalize))\n\t\treturn c.json({ error: \"auth_link_invalid_input\" }, 400);\n\treturn finalizeDeviceAttempt(c, store, data, attemptId, signer, config);\n}\n\nasync function createDeviceAttempt(\n\tc: Context,\n\tstore: CoordinatorDeviceAuthLinkStore,\n\tdata: Record<string, unknown>,\n\tattemptId: string,\n\tsigner: CoordinatorAuthLinkSigner,\n\tconfig: CoordinatorAuthBrowserConfig,\n): Promise<Response> {\n\tif (!exactStrings(data, FIELDS.create)) return c.json({ error: \"auth_link_invalid_input\" }, 400);\n\tif (!store.readAccountLinkStatus) return c.json({ error: \"auth_link_unavailable\" }, 503);\n\tconst current = await store.readAccountLinkStatus(signer, config, {\n\t\tidentityId: data.identity_id,\n\t});\n\tif (\n\t\t(current.state !== \"unlinked\" && current.state !== \"linked\") ||\n\t\tcurrent.identityId !== data.identity_id ||\n\t\tcurrent.authority !== data.authority\n\t)\n\t\treturn c.json({ error: \"auth_link_review_required\" }, 403);\n\tconst authority =\n\t\tcurrent.authority === \"device_claim\"\n\t\t\t? { kind: \"device_claim\" as const, identityId: data.identity_id }\n\t\t\t: { kind: \"controller_attestation\" as const };\n\tconst result = await store.createAuthLinkAttempt(\n\t\t{\n\t\t\tauthority,\n\t\t\texpectedIdentityId: data.identity_id,\n\t\t\tattemptId,\n\t\t\tsigner,\n\t\t\truntimeVerifierHash: data.runtime_verifier_hash,\n\t\t\tbrowserStartHash: data.browser_start_hash,\n\t\t\tloopbackRedirect: data.loopback_redirect,\n\t\t},\n\t\tconfig,\n\t);\n\tif (result.kind === \"rejected\") {\n\t\tif (result.error === \"attempt_unavailable\")\n\t\t\treturn c.json({ error: \"auth_link_review_required\" }, 403);\n\t\treturn rejectedResponse(c, result, { reviewRequired: true });\n\t}\n\treturn c.json(\n\t\t{\n\t\t\tstatus: result.status,\n\t\t\tidentity_id: result.identityId,\n\t\t\tauthority: current.authority,\n\t\t\tcoordinator_id: config.coordinatorId,\n\t\t},\n\t\tresult.kind === \"created\" ? 201 : 200,\n\t);\n}\n\nasync function cancelDeviceAttempt(\n\tc: Context,\n\tstore: CoordinatorDeviceAuthLinkStore,\n\tattemptId: string,\n\tsigner: CoordinatorAuthLinkSigner,\n\tconfig: CoordinatorAuthBrowserConfig,\n): Promise<Response> {\n\tconst result = await store.failAuthLinkAttempt(\n\t\t{\n\t\t\tattemptId,\n\t\t\trequester: { kind: \"device\", signer },\n\t\t\treason: \"cancelled\",\n\t\t},\n\t\tconfig,\n\t);\n\tif (result.kind === \"rejected\") return rejectedResponse(c, result);\n\tif (result.status.state !== \"failed\") return c.json({ error: \"auth_link_unavailable\" }, 503);\n\t// Failure is already committed: cleanup faults must never report success.\n\tconst retired = await store.retireAuthBrowserTransactions(config, { attemptId });\n\tif (retired.kind !== \"retired\" || retired.more)\n\t\treturn c.json({ error: \"auth_link_unavailable\" }, 503);\n\treturn c.json({ status: result.status });\n}\n\nasync function finalizeDeviceAttempt(\n\tc: Context,\n\tstore: CoordinatorDeviceAuthLinkStore,\n\tdata: Record<(typeof FIELDS.finalize)[number], string>,\n\tattemptId: string,\n\tsigner: CoordinatorAuthLinkSigner,\n\tconfig: CoordinatorAuthBrowserConfig,\n): Promise<Response> {\n\tconst runtimeVerifier = decodeCoordinatorAuthProof32(data.runtime_verifier);\n\tconst completion = decodeCoordinatorAuthProof32(data.completion);\n\tif (!runtimeVerifier || !completion) return c.json({ error: \"auth_link_invalid_input\" }, 400);\n\tconst runtimeVerifierHash = await hashCoordinatorAuthProofBytes32(runtimeVerifier);\n\tconst completionSecretHash = await hashCoordinatorAuthProofBytes32(completion);\n\tconst result = await store.finalizeAuthLinkAttempt(\n\t\t{\n\t\t\tpurpose: AUTH_LINK_PURPOSE,\n\t\t\tcoordinatorId: config.coordinatorId,\n\t\t\tattemptId,\n\t\t\tgroupId: data.group_id,\n\t\t\tidentityId: data.identity_id,\n\t\t\tdeviceId: data.device_id,\n\t\t\tfingerprint: data.fingerprint,\n\t\t\truntimeVerifierHash,\n\t\t\tcompletionSecretHash,\n\t\t\tsigner,\n\t\t},\n\t\tconfig,\n\t);\n\tif (result.kind === \"rejected\") return rejectedResponse(c, result, { reviewRequired: true });\n\treturn c.json({ status: result.status });\n}\n\nfunction readAccountStatusInput(\n\tc: Context,\n\turl: string,\n\tdeps: DeviceAuthLinkDeps,\n): { raw: Uint8Array; data: Record<string, unknown> } | Response {\n\tconst parsed = new URL(url);\n\tconst origin = new URL(deps.config.redirectUri).origin;\n\tif (parsed.origin !== origin) return c.json({ error: \"auth_link_unavailable\" }, 403);\n\tconst entries = [...parsed.searchParams.entries()];\n\tif (\n\t\tc.req.raw.body !== null ||\n\t\tentries.length !== 3 ||\n\t\tparsed.searchParams.getAll(\"identity_id\").length !== 1 ||\n\t\tparsed.searchParams.getAll(\"group_id\").length !== 1 ||\n\t\tparsed.searchParams.getAll(\"coordinator_origin\").length !== 1\n\t) {\n\t\treturn c.json({ error: \"auth_link_invalid_input\" }, 400);\n\t}\n\tif (parsed.searchParams.get(\"coordinator_origin\") !== origin)\n\t\treturn c.json({ error: \"auth_link_unavailable\" }, 403);\n\treturn {\n\t\traw: new Uint8Array(),\n\t\tdata: {\n\t\t\tgroup_id: parsed.searchParams.get(\"group_id\"),\n\t\t\tidentity_id: parsed.searchParams.get(\"identity_id\"),\n\t\t},\n\t};\n}\n\nasync function readDeviceInput(\n\tc: Context,\n\taction: Action,\n\turl: string,\n\tdeps: DeviceAuthLinkDeps,\n): Promise<{ raw: Uint8Array; data: Record<string, unknown> } | Response> {\n\tif (action === \"account_status\") return readAccountStatusInput(c, url, deps);\n\tif (action === \"status\") {\n\t\tconst entries = [...new URL(url).searchParams.entries()];\n\t\tconst entry = entries[0];\n\t\tif (entries.length !== 1 || !entry || entry[0] !== \"group_id\") {\n\t\t\treturn c.json({ error: \"auth_link_invalid_input\" }, 400);\n\t\t}\n\t\treturn { raw: new Uint8Array(), data: { group_id: entry[1] } };\n\t}\n\tconst raw = await deps.readRequestBytes(c, 4096);\n\tif (!raw) return c.json({ error: \"body_too_large\" }, 413);\n\tconst data = deps.parseJsonObject(raw);\n\tif (!exactStrings(data, FIELDS[action])) return c.json({ error: \"auth_link_invalid_input\" }, 400);\n\treturn { raw, data };\n}\n\nfunction validDeviceInput(\n\taction: Action,\n\tdata: Record<string, unknown>,\n\tattemptId: unknown,\n\tconfig: CoordinatorAuthBrowserConfig,\n): data is Record<string, unknown> & { group_id: string } {\n\tif (action === \"account_status\")\n\t\treturn isAuthControllerId(data.group_id) && isAuthControllerId(data.identity_id);\n\treturn isAuthControllerId(attemptId) && validInput(action, data, attemptId, config);\n}\n\nasync function handleDeviceRequest(\n\tc: Context,\n\taction: Action,\n\tdeps: DeviceAuthLinkDeps,\n): Promise<Response> {\n\tc.header(\"Cache-Control\", \"no-store\");\n\tconst { config, storeFactory, authorizeRequest, rateLimitedResponse, authErrorStatus } = deps;\n\tlet store: CoordinatorDeviceAuthLinkStore | undefined;\n\ttry {\n\t\ttry {\n\t\t\tconst request = {\n\t\t\t\tmethod: c.req.method,\n\t\t\t\turl: c.req.url,\n\t\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t\t};\n\t\t\tconst pathAttemptId = c.req.param(\"attemptId\") ?? \"\";\n\t\t\tconst input = await readDeviceInput(c, action, request.url, deps);\n\t\t\tif (input instanceof Response) return input;\n\t\t\tconst { raw, data } = input;\n\t\t\tconst attemptId = action === \"create\" ? data.attempt_id : pathAttemptId;\n\t\t\tif (!validDeviceInput(action, data, attemptId, config))\n\t\t\t\treturn c.json({ error: \"auth_link_invalid_input\" }, 400);\n\t\t\tstore = storeFactory();\n\t\t\tconst auth = await authorizeRequest(store, {\n\t\t\t\t...request,\n\t\t\t\tgroupId: data.group_id,\n\t\t\t\tbody: raw,\n\t\t\t});\n\t\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\t\treturn (\n\t\t\t\t\trateLimitedResponse(c, `link:${action}`, { authenticated: false }) ??\n\t\t\t\t\tc.json({ error: \"auth_link_unavailable\" }, authErrorStatus(auth.error))\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst enrollment = auth.enrollment;\n\t\t\tconst limited = rateLimitedResponse(c, `${config.coordinatorId}:${enrollment.device_id}`, {\n\t\t\t\tauthenticated: true,\n\t\t\t});\n\t\t\tif (limited) return limited;\n\t\t\tawait assertConfiguredAuthSchema(store);\n\t\t\tconst signer = {\n\t\t\t\tgroupId: enrollment.group_id,\n\t\t\t\tdeviceId: enrollment.device_id,\n\t\t\t\tpublicKey: enrollment.public_key,\n\t\t\t\tfingerprint: enrollment.fingerprint,\n\t\t\t};\n\t\t\treturn await applyDeviceAction(c, action, store, data, String(attemptId), signer, config);\n\t\t} finally {\n\t\t\tawait store?.close();\n\t\t}\n\t} catch (error) {\n\t\treturn deviceAuthFailure(c, error);\n\t}\n}\n\nfunction deviceAuthFailure(c: Context, error: unknown): Response {\n\tif (error instanceof CoordinatorAuthSchemaUpgradeRequiredError)\n\t\treturn authSchemaUpgradeResponse();\n\treturn c.json({ error: \"auth_link_unavailable\" }, 503);\n}\n\n/** Mount only for the actual ready browser-auth adapter, never the legacy link option. */\nexport function registerCoordinatorAccountLinkStatusRoute(\n\tapp: DeviceAuthLinkApp,\n\tdeps: DeviceAuthLinkDeps,\n): void {\n\tif (!deps.config.enabled) return;\n\tconst { coordinatorId, issuer, revision, enabled, redirectUri } = deps.config;\n\tconst config = Object.freeze({ coordinatorId, issuer, revision, enabled, redirectUri });\n\tapp.get(\"/v1/auth/account-link-status\", (c) =>\n\t\thandleDeviceRequest(c, \"account_status\", { ...deps, config }),\n\t);\n}\n\nexport function registerCoordinatorDeviceAuthLinkRoutes(\n\tapp: DeviceAuthLinkApp,\n\tdeps: DeviceAuthLinkDeps,\n): void {\n\tconst { coordinatorId, issuer, revision, enabled, redirectUri } = deps.config;\n\tif (!enabled) return;\n\t// Retain only the reviewed configuration snapshot, never SDK secrets.\n\tconst config = Object.freeze({ coordinatorId, issuer, revision, enabled, redirectUri });\n\tconst {\n\t\tstoreFactory,\n\t\tauthorizeRequest,\n\t\tauthErrorStatus,\n\t\treadRequestBytes,\n\t\tparseJsonObject,\n\t\trateLimitedResponse,\n\t} = deps;\n\tconst captured = {\n\t\tconfig,\n\t\tstoreFactory,\n\t\tauthorizeRequest,\n\t\tauthErrorStatus,\n\t\treadRequestBytes,\n\t\tparseJsonObject,\n\t\trateLimitedResponse,\n\t};\n\tapp.post(\"/v1/auth/link-attempts\", (c) => handleDeviceRequest(c, \"create\", captured));\n\tapp.get(\"/v1/auth/link-attempts/:attemptId\", (c) => handleDeviceRequest(c, \"status\", captured));\n\tapp.post(\"/v1/auth/link-attempts/:attemptId/finalize\", (c) =>\n\t\thandleDeviceRequest(c, \"finalize\", captured),\n\t);\n\tapp.post(\"/v1/auth/link-attempts/:attemptId/cancel\", (c) =>\n\t\thandleDeviceRequest(c, \"cancel\", captured),\n\t);\n}\n","import { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type {\n\tCoordinatorCreateDeviceRevocationInput,\n\tCoordinatorCreateDeviceRevocationResult,\n\tCoordinatorDeviceRevocationRecord,\n} from \"./coordinator-device-revocation.js\";\nimport { ed25519KeyId } from \"./coordinator-ed25519-key-id.js\";\nimport type { CoordinatorStore } from \"./coordinator-store-contract.js\";\n\nexport type CoordinatorDeviceRevocationAction = \"preview\" | \"commit\";\nfunction isAction(action: unknown): action is CoordinatorDeviceRevocationAction {\n\treturn action === \"preview\" || action === \"commit\";\n}\nexport interface CoordinatorDeviceRevocationHandlerOptions {\n\tstore: Pick<CoordinatorStore, \"getEnrollment\" | \"createDeviceRevocation\">;\n\t/** Server composition only: never derive this from a request or enrollment. */\n\ttrustedCoordinatorId: string | null;\n\tadminSecret?: string | null;\n\t/** Transport admission only, called after native admin authentication and context checks. */\n\tbeforeBody?: (request: Request) => Response | null;\n}\ninterface RevocationInput {\n\tgroup_id: string;\n\tdevice_id: string;\n\texpected_digest?: string;\n}\nexport const COORDINATOR_DEVICE_REVOCATION_MAX_BODY_BYTES = 4096;\nconst MAX_BODY_BYTES = COORDINATOR_DEVICE_REVOCATION_MAX_BODY_BYTES;\nconst SCOPE = \"whole_database_device_id_any_key_and_canonical_key_any_device_all_groups\";\nfunction response(body: unknown, status = 200): Response {\n\treturn Response.json(body, {\n\t\tstatus,\n\t\theaders: {\n\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t},\n\t});\n}\nfunction failure(error: string, status: number): Response {\n\treturn response({ error }, status);\n}\nfunction isDigest(value: unknown): value is string {\n\treturn typeof value === \"string\" && /^[a-f0-9]{64}$/.test(value);\n}\nasync function digestBytes(value: string): Promise<ArrayBuffer> {\n\treturn globalThis.crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(value));\n}\nasync function authenticate(provided: string | null, configured: string | null): Promise<boolean> {\n\tif (typeof configured !== \"string\" || !configured || !provided || provided.length > 8192)\n\t\treturn false;\n\t// Match the controller-review native fixed-length MAC verification pattern.\n\tconst [expected, actual] = await Promise.all([digestBytes(configured), digestBytes(provided)]);\n\tconst key = await globalThis.crypto.subtle.importKey(\n\t\t\"raw\",\n\t\texpected,\n\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n\t\tfalse,\n\t\t[\"sign\", \"verify\"],\n\t);\n\tconst signature = await globalThis.crypto.subtle.sign(\"HMAC\", key, expected);\n\treturn globalThis.crypto.subtle.verify(\"HMAC\", key, signature, actual);\n}\nfunction matchesDeclaredBodyLength(declared: string | null, size: number): boolean {\n\tif (declared === null) return true;\n\treturn /^[0-9]{1,10}$/.test(declared) && Number(declared) === size;\n}\nasync function readBody(request: Request): Promise<Uint8Array | null> {\n\tconst declaredLength = request.headers.get(\"Content-Length\");\n\tif (!request.body) return new Uint8Array();\n\tconst reader = request.body.getReader();\n\tconst signal = AbortSignal.any([request.signal, AbortSignal.timeout(10_000)]);\n\tconst bytes = new Uint8Array(MAX_BODY_BYTES);\n\tlet size = 0;\n\tlet onAbort = () => {};\n\ttry {\n\t\t// Resolve interruption so an abort before the first read cannot orphan a rejection.\n\t\tconst aborted = new Promise<null>((resolve) => {\n\t\t\tonAbort = () => resolve(null);\n\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tif (signal.aborted) onAbort();\n\t\t});\n\t\twhile (true) {\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst chunk = await Promise.race([reader.read(), aborted]);\n\t\t\tif (chunk === null) throw new Error(\"revocation_body_stopped\");\n\t\t\tconst { done, value } = chunk;\n\t\t\tif (done) {\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t\t// Empty input follows the existing invalid-input 400 path before store access.\n\t\t\t\tif (!matchesDeclaredBodyLength(declaredLength, size)) return new Uint8Array();\n\t\t\t\treturn bytes.subarray(0, size);\n\t\t\t}\n\t\t\tif (value.byteLength > MAX_BODY_BYTES - size) return null;\n\t\t\tbytes.set(value, size);\n\t\t\tsize += value.byteLength;\n\t\t}\n\t} finally {\n\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t// Stream teardown must not extend a deadline or delay an oversized-body refusal.\n\t\tvoid reader.cancel().catch(() => {});\n\t\treader.releaseLock();\n\t}\n}\nfunction parseInput(\n\traw: Uint8Array,\n\taction: CoordinatorDeviceRevocationAction,\n): RevocationInput | null {\n\ttry {\n\t\tconst data: unknown = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(raw));\n\t\tif (!data || typeof data !== \"object\" || Array.isArray(data)) return null;\n\t\tconst fields =\n\t\t\taction === \"commit\"\n\t\t\t\t? [\"group_id\", \"device_id\", \"expected_digest\"]\n\t\t\t\t: [\"group_id\", \"device_id\"];\n\t\tconst keys = Object.keys(data);\n\t\tif (keys.length !== fields.length || keys.some((key) => !fields.includes(key))) return null;\n\t\tif (!(\"group_id\" in data) || !(\"device_id\" in data)) return null;\n\t\tif (!isAuthControllerId(data.group_id) || !isAuthControllerId(data.device_id)) return null;\n\t\tconst input: RevocationInput = { group_id: data.group_id, device_id: data.device_id };\n\t\tif (action === \"commit\") {\n\t\t\tif (!(\"expected_digest\" in data) || !isDigest(data.expected_digest)) return null;\n\t\t\tinput.expected_digest = data.expected_digest;\n\t\t}\n\t\treturn input;\n\t} catch {\n\t\treturn null;\n\t}\n}\n/** Existing canonical parsers intentionally accept invalid inner types/trailing bytes. */\nfunction isStrictEd25519Key(publicKey: string): boolean {\n\tif (publicKey.length > 16384 || /[\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(publicKey.replaceAll(\"\\t\", \"\")))\n\t\treturn false;\n\tconst [type, encoded] = publicKey.trim().split(/\\s+/);\n\tif (type !== \"ssh-ed25519\" || !encoded || !/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)) return false;\n\ttry {\n\t\tconst wire = Uint8Array.from(atob(encoded), (character) => character.charCodeAt(0));\n\t\tif (wire.length !== 51) return false;\n\t\tconst view = new DataView(wire.buffer);\n\t\treturn (\n\t\t\tview.getUint32(0) === 11 &&\n\t\t\tnew TextDecoder().decode(wire.subarray(4, 15)) === \"ssh-ed25519\" &&\n\t\t\tview.getUint32(15) === 32\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\nasync function evidenceDigest(\n\tcoordinatorId: string,\n\ttuple: CoordinatorCreateDeviceRevocationInput,\n\tkeyId: string,\n): Promise<string> {\n\tconst bytes = await digestBytes(\n\t\tJSON.stringify([\n\t\t\t\"codemem-global-device-revocation\",\n\t\t\t1,\n\t\t\t\"revoke\",\n\t\t\tcoordinatorId,\n\t\t\ttuple.groupId,\n\t\t\ttuple.deviceId,\n\t\t\ttuple.publicKey,\n\t\t\ttuple.fingerprint,\n\t\t\tkeyId,\n\t\t]),\n\t);\n\treturn Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\ntype RevocationReference = Pick<\n\tCoordinatorDeviceRevocationRecord,\n\t\"subject_kind\" | \"subject_value\" | \"revocation_id\" | \"created_at\"\n>;\nfunction isReceiptText(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length > 0 && !value.includes(\"\\0\");\n}\nfunction captureRevocationReferences(\n\tresult: CoordinatorCreateDeviceRevocationResult,\n\tdeviceId: string,\n\tkeyId: string,\n): RevocationReference[] | null {\n\tif (result?.kind !== \"revoked\" || !Array.isArray(result.records)) return null;\n\t// First retained subjects may have different revocation IDs and historical metadata.\n\tconst references: RevocationReference[] = [];\n\tfor (const [kind, value] of [\n\t\t[\"device_id\", deviceId],\n\t\t[\"ed25519_key\", keyId],\n\t] as const) {\n\t\tconst matching = result.records.filter(\n\t\t\t(row) => row?.subject_kind === kind && row.subject_value === value,\n\t\t);\n\t\tif (matching.length !== 1) return null;\n\t\tconst row = matching[0];\n\t\tif (!row) return null;\n\t\tconst reference = {\n\t\t\tsubject_kind: kind,\n\t\t\tsubject_value: value,\n\t\t\trevocation_id: row.revocation_id,\n\t\t\tcreated_at: row.created_at,\n\t\t};\n\t\tif (!isReceiptText(reference.revocation_id) || !isReceiptText(reference.created_at))\n\t\t\treturn null;\n\t\treferences.push(reference);\n\t}\n\treturn references;\n}\nasync function applyAction(\n\taction: CoordinatorDeviceRevocationAction,\n\tstore: CoordinatorDeviceRevocationHandlerOptions[\"store\"],\n\tcoordinatorId: string,\n\tinput: RevocationInput,\n): Promise<Response> {\n\tconst includeDisabled = true;\n\tconst enrollment = await store.getEnrollment(input.group_id, input.device_id, includeDisabled);\n\tif (!enrollment) return failure(\"revocation_target_unavailable\", 409);\n\t// Copy the exact tuple before any crypto await; never refresh it during commit.\n\tconst tuple = Object.freeze({\n\t\tgroupId: enrollment.group_id,\n\t\tdeviceId: enrollment.device_id,\n\t\tpublicKey: enrollment.public_key,\n\t\tfingerprint: enrollment.fingerprint,\n\t});\n\tif (\n\t\ttuple.groupId !== input.group_id ||\n\t\ttuple.deviceId !== input.device_id ||\n\t\ttypeof tuple.publicKey !== \"string\" ||\n\t\t!isStrictEd25519Key(tuple.publicKey) ||\n\t\ttypeof tuple.fingerprint !== \"string\" ||\n\t\t!tuple.fingerprint ||\n\t\ttuple.fingerprint.includes(\"\\0\")\n\t)\n\t\treturn failure(\"revocation_target_unavailable\", 409);\n\tconst keyId = await ed25519KeyId(tuple.publicKey);\n\tif (!keyId) return failure(\"revocation_target_unavailable\", 409);\n\tconst digest = await evidenceDigest(coordinatorId, tuple, keyId);\n\tconst subjects = {\n\t\tversion: 1,\n\t\tcoordinator_id: coordinatorId,\n\t\tgroup_id: tuple.groupId,\n\t\tdevice_id: tuple.deviceId,\n\t\tkey_id: keyId,\n\t\tscope: SCOPE,\n\t};\n\tif (action === \"preview\")\n\t\treturn response({ state: \"ready\", ...subjects, expected_digest: digest });\n\tif (input.expected_digest !== digest) return failure(\"revocation_preview_stale\", 409);\n\tconst result = await store.createDeviceRevocation(tuple);\n\tif (result?.kind === \"rejected\" && result.error === \"enrollment_mismatch\")\n\t\treturn failure(\"revocation_preview_stale\", 409);\n\tconst revocations = captureRevocationReferences(result, tuple.deviceId, keyId);\n\tif (!revocations) return failure(\"device_revocation_incomplete\", 503);\n\treturn response({ state: \"revoked\", ...subjects, revocations });\n}\n\n/**\n * Internal capability. Transport registration and per-request store ownership live\n * in the runtime route adapter; direct callers retain ownership of their store.\n */\nexport function createCoordinatorDeviceRevocationHandler(\n\toptions: CoordinatorDeviceRevocationHandlerOptions,\n): (action: CoordinatorDeviceRevocationAction, request: Request) => Promise<Response> {\n\tconst fixed = Object.freeze({\n\t\tstore: options.store,\n\t\ttrustedCoordinatorId: options.trustedCoordinatorId,\n\t\tadminSecret: options.adminSecret ?? null,\n\t\tbeforeBody: options.beforeBody,\n\t});\n\treturn async (action: CoordinatorDeviceRevocationAction, request: Request): Promise<Response> => {\n\t\tconst { store, trustedCoordinatorId, adminSecret } = fixed;\n\t\ttry {\n\t\t\tif (!(await authenticate(request.headers.get(\"X-Codemem-Coordinator-Admin\"), adminSecret)))\n\t\t\t\treturn failure(\"unauthorized\", 401);\n\t\t\tif (!isAuthControllerId(trustedCoordinatorId) || !store)\n\t\t\t\treturn failure(\"revocation_unavailable\", 503);\n\t\t\tif (!isAction(action)) return failure(\"revocation_invalid_input\", 400);\n\t\t\tconst admission = fixed.beforeBody?.(request);\n\t\t\tif (admission) return admission;\n\t\t\tconst raw = await readBody(request);\n\t\t\tif (!raw) return failure(\"body_too_large\", 413);\n\t\t\tconst input = parseInput(raw, action);\n\t\t\tif (!input) return failure(\"revocation_invalid_input\", 400);\n\t\t\treturn await applyAction(action, store, trustedCoordinatorId, input);\n\t\t} catch {\n\t\t\t// A lost receipt can follow a committed write: no rollback or compensation claim.\n\t\t\treturn failure(\"device_revocation_incomplete\", 503);\n\t\t}\n\t};\n}\n","import type { Context, Hono } from \"hono\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport {\n\tCOORDINATOR_DEVICE_REVOCATION_MAX_BODY_BYTES,\n\tcreateCoordinatorDeviceRevocationHandler,\n} from \"./coordinator-device-revocation-handler.js\";\nimport type { CoordinatorStore } from \"./coordinator-store-contract.js\";\n\n/** Server composition only. The route always uses the runtime's concrete DB factory. */\nexport interface CoordinatorDeviceRevocationContext {\n\tcoordinatorId: string;\n}\n\nfunction failure(error: string, status: number): Response {\n\treturn Response.json(\n\t\t{ error },\n\t\t{\n\t\t\tstatus,\n\t\t\theaders: {\n\t\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\t},\n\t\t},\n\t);\n}\n\nfunction transportAdmission(request: Request): Response | null {\n\tif (request.method !== \"POST\") return failure(\"method_not_allowed\", 405);\n\tconst url = new URL(request.url);\n\tif (url.search || url.username || url.password) return failure(\"revocation_invalid_input\", 400);\n\tif (\n\t\t!/^application\\/json(?:\\s*;\\s*charset=utf-8)?$/i.test(request.headers.get(\"Content-Type\") ?? \"\")\n\t)\n\t\treturn failure(\"unsupported_media_type\", 415);\n\tif (request.headers.has(\"Content-Encoding\")) return failure(\"unsupported_media_type\", 415);\n\tconst length = request.headers.get(\"Content-Length\");\n\tif (length !== null) {\n\t\tif (request.headers.has(\"Transfer-Encoding\")) return failure(\"revocation_invalid_input\", 400);\n\t\tif (!/^[0-9]{1,10}$/.test(length)) return failure(\"revocation_invalid_input\", 400);\n\t\tif (Number(length) > COORDINATOR_DEVICE_REVOCATION_MAX_BODY_BYTES)\n\t\t\treturn failure(\"body_too_large\", 413);\n\t}\n\treturn null;\n}\n\nexport function registerCoordinatorDeviceRevocationRoutes(\n\tapp: Hono,\n\toptions: {\n\t\tcontext?: CoordinatorDeviceRevocationContext;\n\t\tconfiguredCoordinatorIds: readonly unknown[];\n\t\tstoreFactory: () => CoordinatorStore;\n\t\tadminSecret: () => string | null;\n\t\trateLimitedResponse: (c: Context, key: string, authenticated: boolean) => Response | null;\n\t},\n): void {\n\tconst selectedId = options.context?.coordinatorId;\n\tconst trustedCoordinatorId =\n\t\tisAuthControllerId(selectedId) &&\n\t\toptions.configuredCoordinatorIds.every((id) => id === selectedId)\n\t\t\t? selectedId\n\t\t\t: null;\n\tconst storeFactory = options.storeFactory;\n\tconst adminSecret = options.adminSecret;\n\tconst rateLimitedResponse = options.rateLimitedResponse;\n\tfor (const [path, action] of [\n\t\t[\"/v1/admin/devices/revoke-preview\", \"preview\"],\n\t\t[\"/v1/admin/devices/revoke\", \"commit\"],\n\t] as const) {\n\t\tapp.all(path, async (c) => {\n\t\t\tlet selectedStore: CoordinatorStore | undefined;\n\t\t\ttry {\n\t\t\t\t// Capture credentials before crypto/body awaits. The factory and ID were pinned\n\t\t\t\t// at composition; opening the DB is deferred until authenticated input is valid.\n\t\t\t\tconst secret = adminSecret();\n\t\t\t\tconst limited = rateLimitedResponse(c, c.req.path, false);\n\t\t\t\tif (limited) return limited;\n\t\t\t\tconst selected = () => (selectedStore ??= storeFactory());\n\t\t\t\tconst handler = createCoordinatorDeviceRevocationHandler({\n\t\t\t\t\ttrustedCoordinatorId,\n\t\t\t\t\tadminSecret: secret,\n\t\t\t\t\tstore: {\n\t\t\t\t\t\tgetEnrollment: (...args) => selected().getEnrollment(...args),\n\t\t\t\t\t\tcreateDeviceRevocation: (...args) => selected().createDeviceRevocation(...args),\n\t\t\t\t\t},\n\t\t\t\t\tbeforeBody: (request) =>\n\t\t\t\t\t\trateLimitedResponse(c, \"admin\", true) ?? transportAdmission(request),\n\t\t\t\t});\n\t\t\t\treturn await handler(action, c.req.raw);\n\t\t\t} catch {\n\t\t\t\treturn failure(\"device_revocation_incomplete\", 503);\n\t\t\t} finally {\n\t\t\t\t// Only the per-request selected store is owned here, never browser/runtime stores.\n\t\t\t\tif (selectedStore) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait selectedStore.close();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t/* No backend details in responses. */\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n}\n","/**\n * Invite link encoding/decoding for the coordinator join flow.\n *\n * Ported from codemem/coordinator_invites.py.\n */\n\nexport interface InvitePayload {\n\tv: number;\n\tkind: \"coordinator_team_invite\" | \"team_member\" | \"add_device\" | string;\n\tcoordinator_url: string;\n\tgroup_id: string;\n\tpolicy: string;\n\ttoken: string;\n\texpires_at: string;\n\tteam_name: string | null;\n\t/** Present only for project-first invites. All values are display-only; access intent stays coordinator-owned. */\n\toperation_id?: string;\n\tinviter_name?: string | null;\n\tinviter_device_id?: string;\n\tproject_summaries?: Array<{ display_name: string; existing_memory_count: number }>;\n\t/** Policy metadata for recipient-aware invites. It is preview-only and never grants scope access. */\n\tpolicy_team_id?: string;\n\ttarget_identity_id?: string;\n\tassigned_identity_id?: string;\n\treviewed_preview_digest?: string;\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n\tlet binary = \"\";\n\tfor (const byte of bytes) binary += String.fromCharCode(byte);\n\treturn btoa(binary);\n}\n\nfunction base64ToBytes(base64: string): Uint8Array {\n\tconst binary = atob(base64);\n\tconst bytes = new Uint8Array(binary.length);\n\tfor (let index = 0; index < binary.length; index += 1) {\n\t\tbytes[index] = binary.charCodeAt(index);\n\t}\n\treturn bytes;\n}\n\nfunction toBase64Url(base64: string): string {\n\treturn base64.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nfunction fromBase64Url(value: string): string {\n\tconst padded = value.replace(/-/g, \"+\").replace(/_/g, \"/\");\n\treturn padded + \"=\".repeat((4 - (padded.length % 4)) % 4);\n}\n\n/** Encode an invite payload as a compact base64url string (no padding). */\nexport function encodeInvitePayload(payload: InvitePayload): string {\n\tconst json = JSON.stringify(payload);\n\tconst bytes = new TextEncoder().encode(json);\n\treturn toBase64Url(bytesToBase64(bytes));\n}\n\n/** Decode a base64url invite payload string back to an InvitePayload. */\nexport function decodeInvitePayload(value: string): InvitePayload {\n\tconst json = new TextDecoder().decode(base64ToBytes(fromBase64Url(value)));\n\tconst data: unknown = JSON.parse(json);\n\tif (typeof data !== \"object\" || data === null) {\n\t\tthrow new Error(\"invalid invite payload\");\n\t}\n\treturn data as InvitePayload;\n}\n\n/** Build a `codemem://join?invite=...` link from an encoded payload. */\nexport function inviteLink(encodedPayload: string): string {\n\treturn `codemem://join?invite=${encodeURIComponent(encodedPayload)}`;\n}\n\n/**\n * Extract the raw encoded payload from either a `codemem://` link or a raw value.\n *\n * Throws if a `codemem://` link is provided but has no `invite` query parameter.\n */\nexport function extractInvitePayload(value: string): string {\n\tconst raw = value.trim();\n\tif (raw.startsWith(\"codemem://\")) {\n\t\tconst url = new URL(raw);\n\t\tconst invite = url.searchParams.get(\"invite\") ?? \"\";\n\t\tif (!invite) {\n\t\t\tthrow new Error(\"invite payload missing from link\");\n\t\t}\n\t\treturn invite;\n\t}\n\treturn raw;\n}\n","import type { Context } from \"hono\";\nimport type { CoordinatorEnrollment, CoordinatorStore } from \"./coordinator-store-contract.js\";\n\n/** Only this current member/key snapshot can supply remote cache authority.\n * Catalogue version 1 is discovery metadata, not permission or an account login. */\nexport async function scopeAuthorizationResponse(\n\tc: Context,\n\tstore: CoordinatorStore,\n\tinput: { groupId: string; scopeId: string; requester: CoordinatorEnrollment },\n): Promise<Response> {\n\ttry {\n\t\tconst result = await store.getScopeAuthorization({\n\t\t\tgroupId: input.groupId,\n\t\t\tscopeId: input.scopeId,\n\t\t});\n\t\tif (result.kind === \"rejected\") {\n\t\t\tswitch (result.error) {\n\t\t\t\tcase \"scope_not_found\":\n\t\t\t\tcase \"scope_inactive\":\n\t\t\t\tcase \"scope_source_mismatch\":\n\t\t\t\tcase \"group_archived\":\n\t\t\t\t\treturn c.json({ error: \"scope_not_found\" }, 404);\n\t\t\t\tdefault:\n\t\t\t\t\treturn c.json({ error: \"scope_authorization_unavailable\" }, 503);\n\t\t\t}\n\t\t}\n\t\tif (\n\t\t\tresult.kind !== \"authorized\" ||\n\t\t\tresult.authorizationVersion !== 1 ||\n\t\t\tresult.scope.scope_id !== input.scopeId ||\n\t\t\tresult.scope.group_id !== input.groupId\n\t\t) {\n\t\t\treturn c.json({ error: \"scope_authorization_unavailable\" }, 503);\n\t\t}\n\t\t// Match the principal copied before signature verification, not a newly\n\t\t// read enrollment: rotation after admission must not grant an unchecked key.\n\t\tconst requester = input.requester;\n\t\tconst authorized = result.members.some(\n\t\t\t({ membership, enrollment }) =>\n\t\t\t\tmembership.device_id === requester.device_id &&\n\t\t\t\tenrollment.device_id === requester.device_id &&\n\t\t\t\tenrollment.group_id === input.groupId &&\n\t\t\t\trequester.group_id === input.groupId &&\n\t\t\t\tenrollment.public_key === requester.public_key &&\n\t\t\t\tenrollment.fingerprint === requester.fingerprint &&\n\t\t\t\tenrollment.identity_id === requester.identity_id,\n\t\t);\n\t\tif (!authorized) return c.json({ error: \"scope_membership_required\" }, 403);\n\t\treturn c.json({\n\t\t\tauthorization_version: 1,\n\t\t\tscope: result.scope,\n\t\t\titems: result.members.map(({ membership, enrollment, keyId }) => ({\n\t\t\t\tmembership,\n\t\t\t\tenrollment,\n\t\t\t\tkey_id: keyId,\n\t\t\t})),\n\t\t});\n\t} catch {\n\t\treturn c.json({ error: \"scope_authorization_unavailable\" }, 503);\n\t}\n}\n","export const PROJECT_INVITE_PENDING_STATUS = \"pending_setup\" as const;\n\nexport const PROJECT_SYNC_ENABLEMENT_FAILED = \"project_sync_enablement_failed\" as const;\n\nexport const PROJECT_SYNC_ENABLEMENT_FAILURE_DETAIL =\n\t\"Invitation was accepted, but sync could not be enabled. Make the codemem config writable, then retry.\";\n\nexport class ProjectSyncEnablementError extends Error {\n\treadonly code = PROJECT_SYNC_ENABLEMENT_FAILED;\n\treadonly detail = PROJECT_SYNC_ENABLEMENT_FAILURE_DETAIL;\n\n\tconstructor(options?: ErrorOptions) {\n\t\tsuper(PROJECT_SYNC_ENABLEMENT_FAILURE_DETAIL, options);\n\t\tthis.name = \"ProjectSyncEnablementError\";\n\t}\n}\n\nexport function isProjectSyncEnablementError(error: unknown): error is ProjectSyncEnablementError {\n\treturn (\n\t\ttypeof error === \"object\" &&\n\t\terror !== null &&\n\t\t\"code\" in error &&\n\t\terror.code === PROJECT_SYNC_ENABLEMENT_FAILED &&\n\t\t\"detail\" in error &&\n\t\terror.detail === PROJECT_SYNC_ENABLEMENT_FAILURE_DETAIL\n\t);\n}\n","import { createHash } from \"node:crypto\";\nimport { normalizeIdentityDisplayName } from \"./project-invite-identity.js\";\nimport { canonicalWorkspaceIdentity } from \"./workspace-identity.js\";\n\nexport const SHARE_HISTORY_POLICY = \"existing_and_future\" as const;\n\nexport interface ShareProjectIntent {\n\tcanonicalIdentity: string;\n\tdisplayName: string;\n\tidentitySource: string;\n\texistingMemoryCount: number;\n}\n\nexport interface AcceptedProjectIntent {\n\tcanonical_identity: string;\n\tdisplay_name: string;\n\texisting_memory_count: number;\n}\n\nfunction digest(value: unknown): string {\n\treturn createHash(\"sha256\").update(JSON.stringify(value)).digest(\"hex\");\n}\n\nexport function shareProjectSetDigest(projects: ShareProjectIntent[]): string {\n\tconst reviewedProjects = projects\n\t\t.map((project) => ({\n\t\t\tcanonicalIdentity: project.canonicalIdentity,\n\t\t\texistingMemoryCount: project.existingMemoryCount,\n\t\t}))\n\t\t.toSorted((left, right) => left.canonicalIdentity.localeCompare(right.canonicalIdentity));\n\treturn digest({ v: 1, historyPolicy: SHARE_HISTORY_POLICY, projects: reviewedProjects });\n}\n\nexport function acceptedProjectIntentDigest(projects: AcceptedProjectIntent[]): string {\n\treturn shareProjectSetDigest(\n\t\tprojects.map((project) => ({\n\t\t\tcanonicalIdentity: project.canonical_identity,\n\t\t\tdisplayName: project.display_name,\n\t\t\tidentitySource: \"coordinator_acceptance\",\n\t\t\texistingMemoryCount: project.existing_memory_count,\n\t\t})),\n\t);\n}\n\nexport function parseAcceptedProjectIntent(value: unknown): AcceptedProjectIntent[] {\n\tif (!Array.isArray(value) || value.length === 0 || value.length > 100) {\n\t\tthrow new Error(\"operation_intent_invalid\");\n\t}\n\tconst projects = value.map((item) => {\n\t\tif (!item || typeof item !== \"object\" || Array.isArray(item)) {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t\tconst record = item as Record<string, unknown>;\n\t\tif (typeof record.canonical_identity !== \"string\" || typeof record.display_name !== \"string\") {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t\tconst canonicalIdentityRaw = record.canonical_identity;\n\t\tconst canonicalIdentity = canonicalIdentityRaw.trim();\n\t\tconst displayNameRaw = record.display_name;\n\t\tlet displayName: string;\n\t\ttry {\n\t\t\tdisplayName = normalizeIdentityDisplayName(displayNameRaw, \"project_name\");\n\t\t} catch {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t\tconst count = record.existing_memory_count;\n\t\tconst canonicalIdentityRoundTrip = canonicalWorkspaceIdentity({\n\t\t\tgitRemote: canonicalIdentity,\n\t\t}).value;\n\t\tif (\n\t\t\t!canonicalIdentity ||\n\t\t\tcanonicalIdentity !== canonicalIdentityRaw ||\n\t\t\tcanonicalIdentity.length > 2048 ||\n\t\t\tcanonicalIdentity.startsWith(\"unmapped:\") ||\n\t\t\tcanonicalIdentityRoundTrip !== canonicalIdentity ||\n\t\t\tdisplayName !== displayNameRaw ||\n\t\t\t!Number.isSafeInteger(count) ||\n\t\t\tNumber(count) < 0 ||\n\t\t\t/[\\p{Cc}\\p{Cf}]/u.test(canonicalIdentity) ||\n\t\t\t/[\\p{Cc}\\p{Cf}]/u.test(displayName)\n\t\t) {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t\treturn {\n\t\t\tcanonical_identity: canonicalIdentity,\n\t\t\tdisplay_name: displayName,\n\t\t\texisting_memory_count: Number(count),\n\t\t};\n\t});\n\tif (new Set(projects.map((project) => project.canonical_identity)).size !== projects.length) {\n\t\tthrow new Error(\"operation_intent_invalid\");\n\t}\n\treturn projects.toSorted((left, right) =>\n\t\tleft.canonical_identity.localeCompare(right.canonical_identity),\n\t);\n}\n","// generate timestamp or delta\n// see http://nodejs.org/api/process.html#process_process_hrtime\nfunction hrtime(previousTimestamp) {\n const clocktime = performance.now() * 1e-3;\n let seconds = Math.floor(clocktime);\n let nanoseconds = Math.floor((clocktime % 1) * 1e9);\n if (previousTimestamp != undefined) {\n seconds = seconds - previousTimestamp[0];\n nanoseconds = nanoseconds - previousTimestamp[1];\n if (nanoseconds < 0) {\n seconds--;\n nanoseconds += 1e9;\n }\n }\n return [seconds, nanoseconds];\n}\n// The current timestamp in whole milliseconds\nexport function getMilliseconds() {\n const [seconds, nanoseconds] = hrtime();\n return seconds * 1e3 + Math.floor(nanoseconds / 1e6);\n}\n// Wait for a specified number of milliseconds before fulfilling the returned promise.\nexport function wait(ms) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n//# sourceMappingURL=clock.js.map","import { getMilliseconds, wait } from \"./clock.js\";\n/**\n * A hierarchical token bucket for rate limiting. See\n * http://en.wikipedia.org/wiki/Token_bucket for more information.\n *\n * @param options\n * @param options.bucketSize Maximum number of tokens to hold in the bucket.\n * Also known as the burst rate.\n * @param options.tokensPerInterval Number of tokens to drip into the bucket\n * over the course of one interval.\n * @param options.interval The interval length in milliseconds, or as\n * one of the following strings: 'second', 'minute', 'hour', day'.\n * @param options.parentBucket Optional. A token bucket that will act as\n * the parent of this bucket.\n */\nexport class TokenBucket {\n bucketSize;\n tokensPerInterval;\n interval;\n parentBucket;\n content;\n lastDrip;\n constructor({ bucketSize, tokensPerInterval, interval, parentBucket }) {\n this.bucketSize = bucketSize;\n this.tokensPerInterval = tokensPerInterval;\n if (typeof interval === \"string\") {\n switch (interval) {\n case \"sec\":\n case \"second\":\n this.interval = 1000;\n break;\n case \"min\":\n case \"minute\":\n this.interval = 1000 * 60;\n break;\n case \"hr\":\n case \"hour\":\n this.interval = 1000 * 60 * 60;\n break;\n case \"day\":\n this.interval = 1000 * 60 * 60 * 24;\n break;\n default:\n throw new Error(\"Invalid interval \" + interval);\n }\n }\n else {\n this.interval = interval;\n }\n this.parentBucket = parentBucket;\n this.content = 0;\n this.lastDrip = getMilliseconds();\n }\n /**\n * Remove the requested number of tokens. If the bucket (and any parent\n * buckets) contains enough tokens this will happen immediately. Otherwise,\n * the removal will happen when enough tokens become available.\n * @param count The number of tokens to remove.\n * @returns A promise for the remainingTokens count.\n */\n async removeTokens(count) {\n // Is this an infinite size bucket?\n if (this.bucketSize === 0) {\n return Number.POSITIVE_INFINITY;\n }\n // Make sure the bucket can hold the requested number of tokens\n if (count > this.bucketSize) {\n throw new Error(`Requested tokens ${count} exceeds bucket size ${this.bucketSize}`);\n }\n // Drip new tokens into this bucket\n this.drip();\n const comeBackLater = async () => {\n // How long do we need to wait to make up the difference in tokens?\n const waitMs = Math.ceil((count - this.content) * (this.interval / this.tokensPerInterval));\n await wait(waitMs);\n return this.removeTokens(count);\n };\n // If we don't have enough tokens in this bucket, come back later\n if (count > this.content)\n return comeBackLater();\n if (this.parentBucket != undefined) {\n // Remove the requested from the parent bucket first\n const remainingTokens = await this.parentBucket.removeTokens(count);\n // Check that we still have enough tokens in this bucket\n if (count > this.content)\n return comeBackLater();\n // Tokens were removed from the parent bucket, now remove them from\n // this bucket. Note that we look at the current bucket and parent\n // bucket's remaining tokens and return the smaller of the two values\n this.content -= count;\n return Math.min(remainingTokens, this.content);\n }\n else {\n // Remove the requested tokens from this bucket\n this.content -= count;\n return this.content;\n }\n }\n /**\n * Attempt to remove the requested number of tokens and return immediately.\n * If the bucket (and any parent buckets) contains enough tokens this will\n * return true, otherwise false is returned.\n * @param {Number} count The number of tokens to remove.\n * @param {Boolean} True if the tokens were successfully removed, otherwise\n * false.\n */\n tryRemoveTokens(count) {\n // Is this an infinite size bucket?\n if (!this.bucketSize)\n return true;\n // Make sure the bucket can hold the requested number of tokens\n if (count > this.bucketSize)\n return false;\n // Drip new tokens into this bucket\n this.drip();\n // If we don't have enough tokens in this bucket, return false\n if (count > this.content)\n return false;\n // Try to remove the requested tokens from the parent bucket\n if (this.parentBucket && !this.parentBucket.tryRemoveTokens(count))\n return false;\n // Remove the requested tokens from this bucket and return\n this.content -= count;\n return true;\n }\n /**\n * Add any new tokens to the bucket since the last drip.\n * @returns {Boolean} True if new tokens were added, otherwise false.\n */\n drip() {\n if (this.tokensPerInterval === 0) {\n const prevContent = this.content;\n this.content = this.bucketSize;\n return this.content > prevContent;\n }\n const now = getMilliseconds();\n const deltaMS = Math.max(now - this.lastDrip, 0);\n this.lastDrip = now;\n const dripAmount = deltaMS * (this.tokensPerInterval / this.interval);\n const prevContent = this.content;\n this.content = Math.min(this.content + dripAmount, this.bucketSize);\n return Math.floor(this.content) > Math.floor(prevContent);\n }\n}\n//# sourceMappingURL=TokenBucket.js.map","import { TokenBucket } from \"./TokenBucket.js\";\nimport { getMilliseconds, wait } from \"./clock.js\";\n/**\n * A generic rate limiter. Underneath the hood, this uses a token bucket plus\n * an additional check to limit how many tokens we can remove each interval.\n *\n * @param options\n * @param options.tokensPerInterval Maximum number of tokens that can be\n * removed at any given moment and over the course of one interval.\n * @param options.interval The interval length in milliseconds, or as\n * one of the following strings: 'second', 'minute', 'hour', day'.\n * @param options.fireImmediately Whether or not the promise will resolve\n * immediately when rate limiting is in effect (default is false).\n */\nexport class RateLimiter {\n tokenBucket;\n curIntervalStart;\n tokensThisInterval;\n fireImmediately;\n constructor({ tokensPerInterval, interval, fireImmediately }) {\n this.tokenBucket = new TokenBucket({\n bucketSize: tokensPerInterval,\n tokensPerInterval,\n interval,\n });\n // Fill the token bucket to start\n this.tokenBucket.content = tokensPerInterval;\n this.curIntervalStart = getMilliseconds();\n this.tokensThisInterval = 0;\n this.fireImmediately = fireImmediately ?? false;\n }\n /**\n * Remove the requested number of tokens. If the rate limiter contains enough\n * tokens and we haven't spent too many tokens in this interval already, this\n * will happen immediately. Otherwise, the removal will happen when enough\n * tokens become available.\n * @param count The number of tokens to remove.\n * @returns A promise for the remainingTokens count.\n */\n async removeTokens(count) {\n // Make sure the request isn't for more than we can handle\n if (count > this.tokenBucket.bucketSize) {\n throw new Error(`Requested tokens ${count} exceeds maximum tokens per interval ${this.tokenBucket.bucketSize}`);\n }\n const now = getMilliseconds();\n // Advance the current interval and reset the current interval token count\n // if needed\n if (now < this.curIntervalStart || now - this.curIntervalStart >= this.tokenBucket.interval) {\n this.curIntervalStart = now;\n this.tokensThisInterval = 0;\n }\n // If we don't have enough tokens left in this interval, wait until the\n // next interval\n if (count > this.tokenBucket.tokensPerInterval - this.tokensThisInterval) {\n if (this.fireImmediately) {\n return -1;\n }\n else {\n const waitMs = Math.ceil(this.curIntervalStart + this.tokenBucket.interval - now);\n await wait(waitMs);\n const remainingTokens = await this.tokenBucket.removeTokens(count);\n this.tokensThisInterval += count;\n return remainingTokens;\n }\n }\n // Remove the requested number of tokens from the token bucket\n const remainingTokens = await this.tokenBucket.removeTokens(count);\n this.tokensThisInterval += count;\n return remainingTokens;\n }\n /**\n * Attempt to remove the requested number of tokens and return immediately.\n * If the bucket (and any parent buckets) contains enough tokens and we\n * haven't spent too many tokens in this interval already, this will return\n * true. Otherwise, false is returned.\n * @param {Number} count The number of tokens to remove.\n * @param {Boolean} True if the tokens were successfully removed, otherwise\n * false.\n */\n tryRemoveTokens(count) {\n // Make sure the request isn't for more than we can handle\n if (count > this.tokenBucket.bucketSize)\n return false;\n const now = getMilliseconds();\n // Advance the current interval and reset the current interval token count\n // if needed\n if (now < this.curIntervalStart || now - this.curIntervalStart >= this.tokenBucket.interval) {\n this.curIntervalStart = now;\n this.tokensThisInterval = 0;\n }\n // If we don't have enough tokens left in this interval, return false\n if (count > this.tokenBucket.tokensPerInterval - this.tokensThisInterval)\n return false;\n // Try to remove the requested number of tokens from the token bucket\n const removed = this.tokenBucket.tryRemoveTokens(count);\n if (removed) {\n this.tokensThisInterval += count;\n }\n return removed;\n }\n /**\n * Returns the number of tokens remaining in the TokenBucket.\n * @returns {Number} The number of tokens remaining.\n */\n getTokensRemaining() {\n this.tokenBucket.drip();\n return this.tokenBucket.content;\n }\n}\n//# sourceMappingURL=RateLimiter.js.map","import { RateLimiter } from \"limiter\";\n\nexport interface InMemoryRequestRateLimiter {\n\tcheck(key: string, limit: number): { allowed: boolean; retryAfterS: number };\n}\n\nexport interface CreateInMemoryRequestRateLimiterOptions {\n\twindowMs?: number;\n\tnow?: () => number;\n}\n\n/**\n * Best-effort, per-isolate request rate limiter.\n *\n * Buckets live in a module-local Map, so on Cloudflare Workers the limits are\n * enforced per isolate, not fleet-wide: the effective ceiling is multiplied by\n * the number of live isolates and resets whenever an isolate is evicted. This\n * is acceptable as a coarse abuse brake but is NOT a hard global limit. The\n * unauthenticated /v1/join surface is the most exposed to this gap. Real\n * fleet-wide enforcement needs a shared counter backed by a Durable Object or\n * D1/KV.\n */\nexport function createInMemoryRequestRateLimiter(\n\toptions: CreateInMemoryRequestRateLimiterOptions = {},\n): InMemoryRequestRateLimiter {\n\tconst windowMs = Math.max(1000, Math.trunc(options.windowMs ?? 60_000));\n\tconst now = options.now ?? (() => Date.now());\n\tconst buckets = new Map<string, { limiter: RateLimiter; lastUsedAt: number }>();\n\tlet checks = 0;\n\n\tfunction estimatedRetryAfterS(limit: number): number {\n\t\treturn Math.max(1, Math.ceil(windowMs / Math.max(1, limit) / 1000));\n\t}\n\n\tfunction cleanupExpiredBuckets(currentNow: number): void {\n\t\tif (buckets.size < 64 || checks % 64 !== 0) return;\n\t\tconst staleBefore = currentNow - windowMs * 10;\n\t\tfor (const [key, bucket] of buckets) {\n\t\t\tif (bucket.lastUsedAt < staleBefore) buckets.delete(key);\n\t\t}\n\t}\n\n\treturn {\n\t\tcheck(key: string, limit: number) {\n\t\t\tconst safeLimit = Math.max(1, Math.trunc(limit));\n\t\t\tchecks += 1;\n\t\t\tconst currentNow = now();\n\t\t\tcleanupExpiredBuckets(currentNow);\n\t\t\tconst bucketKey = `${safeLimit}:${key}`;\n\t\t\tlet bucket = buckets.get(bucketKey);\n\t\t\tif (!bucket) {\n\t\t\t\tbucket = {\n\t\t\t\t\tlimiter: new RateLimiter({\n\t\t\t\t\t\ttokensPerInterval: safeLimit,\n\t\t\t\t\t\tinterval: windowMs,\n\t\t\t\t\t\tfireImmediately: true,\n\t\t\t\t\t}),\n\t\t\t\t\tlastUsedAt: currentNow,\n\t\t\t\t};\n\t\t\t\tbuckets.set(bucketKey, bucket);\n\t\t\t}\n\t\t\tbucket.lastUsedAt = currentNow;\n\t\t\tif (bucket.limiter.tryRemoveTokens(1)) {\n\t\t\t\treturn { allowed: true, retryAfterS: 0 };\n\t\t\t}\n\t\t\treturn { allowed: false, retryAfterS: estimatedRetryAfterS(safeLimit) };\n\t\t},\n\t};\n}\n","/**\n * Coordinator API — Hono-based HTTP server for the coordinator relay.\n *\n * Manages device enrollment, presence, invites, and join requests.\n * Ported from codemem/coordinator_api.py.\n */\n\nimport type { Context } from \"hono\";\nimport { Hono } from \"hono\";\nimport { registerCoordinatorAuthControllerReviewRoutes } from \"./coordinator-auth-controller-review-route.js\";\nimport {\n\tAUTH_SCHEMA_UPGRADE_REQUIRED,\n\tassertConfiguredAuthSchema,\n\tauthSchemaUpgradeResponse,\n} from \"./coordinator-auth-schema.js\";\nimport type {\n\tCoordinatorBrowserAuth,\n\tCoordinatorBrowserAuthClientKey,\n} from \"./coordinator-browser-auth-app.js\";\nimport {\n\ttype CoordinatorDeviceAccountChangeOptions,\n\tregisterCoordinatorDeviceAccountChangeRoutes,\n} from \"./coordinator-device-account-change.js\";\nimport {\n\ttype CoordinatorDeviceAuthLinkOptions,\n\ttype CoordinatorDeviceAuthLinkStore,\n\tregisterCoordinatorAccountLinkStatusRoute,\n\tregisterCoordinatorDeviceAuthLinkRoutes,\n} from \"./coordinator-device-auth-link.js\";\nimport {\n\ttype CoordinatorDeviceRevocationContext,\n\tregisterCoordinatorDeviceRevocationRoutes,\n} from \"./coordinator-device-revocation-route.js\";\nimport type { InvitePayload } from \"./coordinator-invites.js\";\nimport { encodeInvitePayload, inviteLink } from \"./coordinator-invites.js\";\nimport type { CoordinatorLegacyTeamCompletionManifestV1 } from \"./coordinator-legacy-team-completion.js\";\nimport {\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES,\n\tCoordinatorLegacyTeamCompletionConflictError,\n\tnormalizeCoordinatorLegacyTeamCompletionCandidateRef,\n\tnormalizeCoordinatorLegacyTeamCompletionGroupIds,\n\tnormalizeCoordinatorLegacyTeamCompletionManifest,\n\trequireCoordinatorLegacyTeamCompletionTeamBinding,\n} from \"./coordinator-legacy-team-completion.js\";\nimport {\n\tCoordinatorMembershipError,\n\tSCOPE_MEMBERSHIP_EFFECT_CONFLICT,\n} from \"./coordinator-membership-effects.js\";\nimport { scopeAuthorizationResponse } from \"./coordinator-scope-authorization-response.js\";\nimport type {\n\tCoordinatorBootstrapGrantAuthorizationError,\n\tCoordinatorBootstrapGrantAuthorizationInput,\n\tCoordinatorBootstrapGrantVerification,\n\tCoordinatorEnrollment,\n\tCoordinatorInviteKind,\n\tCoordinatorScope,\n\tCoordinatorScopeMembership,\n\tCoordinatorStore,\n} from \"./coordinator-store-contract.js\";\nimport { CoordinatorReciprocalApprovalRequestChangedError } from \"./coordinator-store-contract.js\";\nimport { PROJECT_INVITE_PENDING_STATUS } from \"./project-invite-acceptance.js\";\nimport {\n\tnormalizeDeviceDisplayName,\n\tnormalizeHumanPresentationName,\n\tnormalizeProjectInviteSummaries,\n} from \"./project-invite-identity.js\";\nimport { acceptedProjectIntentDigest, parseAcceptedProjectIntent } from \"./project-share-intent.js\";\nimport {\n\tRecipientReviewedIntentError,\n\ttype RecipientReviewedIntentV1,\n\tverifyRecipientReviewedIntent,\n} from \"./recipient-reviewed-intent.js\";\nimport {\n\tcreateInMemoryRequestRateLimiter,\n\ttype InMemoryRequestRateLimiter,\n} from \"./request-rate-limit.js\";\nimport { explainScopeMembershipRevocation } from \"./scope-membership-semantics.js\";\nimport { DEFAULT_TIME_WINDOW_S } from \"./sync-auth-constants.js\";\nimport { fingerprintPublicKey } from \"./sync-fingerprint.js\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst MAX_BODY_BYTES = 64 * 1024;\nconst MAX_LEGACY_TEAM_COMPLETION_BODY_BYTES = COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES + 1024;\nconst ADMIN_HEADER = \"X-Codemem-Coordinator-Admin\";\nconst ADMIN_ACTOR_HEADER = \"X-Codemem-Coordinator-Admin-Actor\";\nconst DEFAULT_COORDINATOR_READ_LIMIT = 120;\nconst DEFAULT_COORDINATOR_MUTATION_LIMIT = 30;\n\nexport interface CoordinatorRequestRateLimitOptions {\n\tlimiter?: InMemoryRequestRateLimiter;\n\treadLimit?: number;\n\tmutationLimit?: number;\n\tunauthenticatedReadLimit?: number;\n\tunauthenticatedMutationLimit?: number;\n}\n\nexport interface CoordinatorRuntimeDeps {\n\tadminSecret(): string | null;\n\tnow(): string;\n}\n\nexport interface CreateCoordinatorAppOptions {\n\tstoreFactory: (options?: { existingOnly: true }) => CoordinatorStore;\n\truntime: CoordinatorRuntimeDeps;\n\trequestVerifier: CoordinatorRequestVerifier;\n\trequestRateLimit?: CoordinatorRequestRateLimitOptions;\n\tauthLink?: CoordinatorDeviceAuthLinkOptions;\n\tbrowserAuth?: CoordinatorAppBrowserAuthOptions;\n\taccountChanges?: CoordinatorDeviceAccountChangeOptions;\n\tdeviceRevocation?: CoordinatorDeviceRevocationContext;\n}\nexport type CoordinatorAppBrowserAuthOptions =\n\t| {\n\t\t\tkind: \"ready\";\n\t\t\tauth: CoordinatorBrowserAuth;\n\t\t\tstoreFactory: () => CoordinatorDeviceAuthLinkStore;\n\t\t\tclientKey: CoordinatorBrowserAuthClientKey;\n\t }\n\t| { kind: \"unavailable\"; error?: typeof AUTH_SCHEMA_UPGRADE_REQUIRED };\n\nfunction recipientInviteErrorStatus(code: string): 403 | 404 | 409 | 410 {\n\tif (code === \"device_revoked\") return 403;\n\tif (code === \"invite_expired\") return 410;\n\tif (code === \"invite_invalid\") return 404;\n\treturn 409;\n}\n\nfunction authenticationUnavailableResponse(): Response {\n\treturn new Response(\"Authentication unavailable. Try again.\", {\n\t\tstatus: 503,\n\t\theaders: {\n\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\t\"Content-Type\": \"text/plain;charset=utf-8\",\n\t\t},\n\t});\n}\n\nfunction accountChangeOptions(\n\topts: CreateCoordinatorAppOptions,\n): CoordinatorDeviceAccountChangeOptions | undefined {\n\tconst ready = opts.browserAuth?.kind === \"ready\" ? opts.browserAuth : undefined;\n\tconst configured = ready?.auth.storeConfig ?? opts.authLink?.config;\n\tif (\n\t\topts.accountChanges &&\n\t\tconfigured &&\n\t\t[\"coordinatorId\", \"issuer\", \"revision\", \"redirectUri\", \"enabled\"].some(\n\t\t\t(key) => Reflect.get(configured, key) !== Reflect.get(opts.accountChanges?.config ?? {}, key),\n\t\t)\n\t)\n\t\tthrow new Error(\"coordinator_auth_configuration_conflict\");\n\tif (opts.accountChanges) return opts.accountChanges;\n\tif (!ready?.auth.resolveAccountChanges) return undefined;\n\treturn {\n\t\tconfig: ready.auth.storeConfig,\n\t\tstoreFactory: ready.storeFactory,\n\t\tassertReady: assertConfiguredAuthSchema,\n\t\toperationsFactory: ready.auth.resolveAccountChanges,\n\t};\n}\nfunction registerOptionalCoordinatorAuth(\n\tapp: Hono,\n\topts: CreateCoordinatorAppOptions,\n\tdeps: Omit<\n\t\tParameters<typeof registerCoordinatorDeviceAuthLinkRoutes>[1],\n\t\t\"config\" | \"storeFactory\"\n\t>,\n): void {\n\tif (opts.authLink && opts.browserAuth) throw new Error(\"coordinator_auth_configuration_conflict\");\n\tconst accountChanges = accountChangeOptions(opts);\n\tconst unavailable =\n\t\topts.browserAuth?.kind === \"unavailable\" &&\n\t\topts.browserAuth.error === AUTH_SCHEMA_UPGRADE_REQUIRED\n\t\t\t? authSchemaUpgradeResponse\n\t\t\t: authenticationUnavailableResponse;\n\tif (opts.browserAuth?.kind !== \"ready\") {\n\t\tapp.all(\"/v1/auth/account-link-status\", unavailable);\n\t}\n\tif (opts.browserAuth?.kind === \"unavailable\") {\n\t\tfor (const path of [\n\t\t\t\"/auth/*\",\n\t\t\t\"/v1/auth/link-attempts\",\n\t\t\t\"/v1/auth/link-attempts/*\",\n\t\t\t\"/v1/auth/account-changes\",\n\t\t\t\"/v1/auth/account-changes/*\",\n\t\t\t\"/v1/auth/owner-config\",\n\t\t\t\"/v1/auth/owner-attempts\",\n\t\t\t\"/v1/auth/owner-attempts/*\",\n\t\t\t\"/v1/admin/auth-controller-reviews\",\n\t\t]) {\n\t\t\tapp.all(path, unavailable);\n\t\t}\n\t\treturn;\n\t}\n\tif (accountChanges)\n\t\tregisterCoordinatorDeviceAccountChangeRoutes(app, { ...deps, ...accountChanges });\n\tconst ready = opts.browserAuth;\n\tconst authLink =\n\t\tready?.kind === \"ready\"\n\t\t\t? { config: ready.auth.storeConfig, storeFactory: ready.storeFactory }\n\t\t\t: opts.authLink;\n\tif (authLink?.config.enabled) {\n\t\tregisterCoordinatorDeviceAuthLinkRoutes(app, { ...deps, ...authLink });\n\t\tregisterCoordinatorAuthControllerReviewRoutes(app, {\n\t\t\t...deps,\n\t\t\t...authLink,\n\t\t\tadminSecret: () => opts.runtime.adminSecret(),\n\t\t});\n\t}\n\tif (ready?.kind === \"ready\") {\n\t\tregisterCoordinatorAccountLinkStatusRoute(app, {\n\t\t\t...deps,\n\t\t\tconfig: ready.auth.storeConfig,\n\t\t\tstoreFactory: ready.storeFactory,\n\t\t});\n\t\tready.auth.register(app, ready.clientKey);\n\t}\n}\n\nexport interface CoordinatorVerifyRequestInput {\n\tmethod: string;\n\tpathWithQuery: string;\n\tbodyBytes: Uint8Array;\n\ttimestamp: string;\n\tnonce: string;\n\tsignature: string;\n\tpublicKey: string;\n\tdeviceId: string;\n}\n\nfunction registerCoordinatorRuntimeRoutes(\n\tapp: Hono,\n\topts: CreateCoordinatorAppOptions,\n\tdeps: Parameters<typeof registerOptionalCoordinatorAuth>[2],\n): void {\n\tconst createStore = opts.storeFactory;\n\tregisterCoordinatorDeviceRevocationRoutes(app, {\n\t\tcontext: opts.deviceRevocation,\n\t\tconfiguredCoordinatorIds: [\n\t\t\topts.authLink?.config,\n\t\t\topts.browserAuth?.kind === \"ready\" ? opts.browserAuth.auth.storeConfig : undefined,\n\t\t\topts.accountChanges?.config,\n\t\t]\n\t\t\t.filter((config) => config !== undefined)\n\t\t\t.map((config) => config?.coordinatorId),\n\t\tstoreFactory: () => createStore({ existingOnly: true }),\n\t\tadminSecret: opts.runtime.adminSecret.bind(opts.runtime),\n\t\trateLimitedResponse: (c, key, authenticated) =>\n\t\t\tdeps.rateLimitedResponse(c, key, { authenticated }),\n\t});\n\tregisterOptionalCoordinatorAuth(app, opts, deps);\n}\n\nexport type CoordinatorRequestVerifier = (\n\tinput: CoordinatorVerifyRequestInput,\n) => Promise<boolean> | boolean;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction authorizeAdmin(\n\theaderValue: string | null | undefined,\n\truntime: CoordinatorRuntimeDeps,\n): { ok: boolean; error: string } {\n\tconst expected = runtime.adminSecret();\n\tif (!expected) return { ok: false, error: \"admin_not_configured\" };\n\tconst provided = (headerValue ?? \"\").trim();\n\tif (!provided) return { ok: false, error: \"missing_admin_header\" };\n\tif (provided !== expected) return { ok: false, error: \"invalid_admin_secret\" };\n\treturn { ok: true, error: \"ok\" };\n}\n\n/** Extract path + query string from a full URL for signature verification. */\nfunction pathWithQuery(url: string): string {\n\tconst parsed = new URL(url);\n\treturn parsed.search ? `${parsed.pathname}${parsed.search}` : parsed.pathname;\n}\n\nasync function cleanupNonces(store: CoordinatorStore, cutoff: string): Promise<void> {\n\tawait store.cleanupNonces(cutoff);\n}\n\ninterface AuthResult {\n\tok: boolean;\n\terror: string;\n\tenrollment: CoordinatorEnrollment | null;\n}\n\nasync function authorizeRequest(\n\tstore: CoordinatorStore,\n\truntime: CoordinatorRuntimeDeps,\n\trequestVerifier: CoordinatorRequestVerifier,\n\topts: {\n\t\tmethod: string;\n\t\turl: string;\n\t\tgroupId: string;\n\t\tbody: Uint8Array;\n\t\tdeviceId: string | null;\n\t\tsignature: string | null;\n\t\ttimestamp: string | null;\n\t\tnonce: string | null;\n\t},\n): Promise<AuthResult> {\n\tconst { deviceId, signature, timestamp, nonce } = opts;\n\tif (!deviceId || !signature || !timestamp || !nonce) {\n\t\treturn { ok: false, error: \"missing_headers\", enrollment: null };\n\t}\n\n\tconst sourceEnrollment = await store.getEnrollment(opts.groupId, deviceId, true);\n\tif (!sourceEnrollment) {\n\t\treturn { ok: false, error: \"unknown_device\", enrollment: null };\n\t}\n\tconst enrollment = { ...sourceEnrollment };\n\tif (enrollment.enabled !== 1) {\n\t\treturn { ok: false, error: \"device_disabled\", enrollment: null };\n\t}\n\tconst group = await store.getGroup(opts.groupId);\n\tif (!group) {\n\t\treturn { ok: false, error: \"group_not_found\", enrollment: null };\n\t}\n\tif (group.archived_at) {\n\t\treturn { ok: false, error: \"group_archived\", enrollment: null };\n\t}\n\n\tconst publicKey = enrollment.public_key;\n\tif (typeof publicKey !== \"string\")\n\t\treturn { ok: false, error: \"unknown_device\", enrollment: null };\n\tlet valid: boolean;\n\ttry {\n\t\tvalid = await requestVerifier({\n\t\t\tmethod: opts.method,\n\t\t\tpathWithQuery: pathWithQuery(opts.url),\n\t\t\tbodyBytes: opts.body,\n\t\t\ttimestamp,\n\t\t\tnonce,\n\t\t\tsignature,\n\t\t\tpublicKey: String(publicKey),\n\t\t\tdeviceId,\n\t\t});\n\t} catch {\n\t\treturn { ok: false, error: \"signature_verification_error\", enrollment: null };\n\t}\n\n\tif (!valid) {\n\t\treturn { ok: false, error: \"invalid_signature\", enrollment: null };\n\t}\n\n\tconst createdAt = runtime.now();\n\tconst admission = await store.recordAuthorizedNonce({\n\t\tgroupId: opts.groupId,\n\t\tdeviceId,\n\t\tpublicKey,\n\t\tnonce,\n\t\tcreatedAt,\n\t});\n\tif (admission !== \"recorded\") {\n\t\treturn { ok: false, error: admission, enrollment: null };\n\t}\n\n\t// Clock-source note: the nonce timestamp/cutoff below is driven by the\n\t// injected runtime.now(), while the request freshness window is enforced\n\t// inside requestVerifier using real Date.now() (see the worker's\n\t// request-verifier). In production both are wall-clock so they agree. Under\n\t// an injected/frozen clock they can diverge; the freshness check is not\n\t// reachable from runtime.now(), so tests that freeze runtime.now() must keep\n\t// timestamps within DEFAULT_TIME_WINDOW_S of real time for the verifier to\n\t// accept them. Unifying the two would require threading the clock into the\n\t// verifier signature across the core/worker boundary.\n\tconst cutoff = new Date(\n\t\tnew Date(createdAt).getTime() - DEFAULT_TIME_WINDOW_S * 2 * 1000,\n\t).toISOString();\n\tawait cleanupNonces(store, cutoff);\n\n\treturn { ok: true, error: \"ok\", enrollment };\n}\n\nfunction authErrorStatus(error: string): 401 | 403 | 409 {\n\tif (error === \"device_disabled\" || error === \"device_revoked\") return 403;\n\tif (error === \"group_archived\") return 409;\n\treturn 401;\n}\n\nfunction bootstrapAuthorizationErrorStatus(\n\terror: CoordinatorBootstrapGrantAuthorizationError,\n): 403 | 404 | 409 | 503 {\n\tswitch (error) {\n\t\tcase \"grant_not_found\":\n\t\tcase \"seed_enrollment_not_found\":\n\t\tcase \"worker_enrollment_not_found\":\n\t\t\treturn 404;\n\t\tcase \"grant_revoked\":\n\t\tcase \"grant_expired\":\n\t\tcase \"device_revoked\":\n\t\t\treturn 403;\n\t\tcase \"group_archived\":\n\t\t\treturn 409;\n\t\tdefault:\n\t\t\treturn 503;\n\t}\n}\n\nasync function bootstrapAuthorizationResponse(\n\tc: Context,\n\tstore: CoordinatorStore,\n\tinput: CoordinatorBootstrapGrantAuthorizationInput,\n) {\n\ttry {\n\t\tconst result = await store.getBootstrapGrantAuthorization(input);\n\t\tif (result.kind === \"rejected\") {\n\t\t\treturn c.json({ error: result.error }, bootstrapAuthorizationErrorStatus(result.error));\n\t\t}\n\t\tconst payload: CoordinatorBootstrapGrantVerification = {\n\t\t\tauthorization_version: result.authorizationVersion,\n\t\t\tgrant: result.grant,\n\t\t\tseed_enrollment: result.seedEnrollment,\n\t\t\tworker_enrollment: result.workerEnrollment,\n\t\t};\n\t\treturn c.json(payload);\n\t} catch {\n\t\treturn c.json({ error: \"bootstrap_authorization_unavailable\" }, 503);\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// App factory\n// ---------------------------------------------------------------------------\n\nasync function readRequestBytes(c: Context, maxBytes = MAX_BODY_BYTES): Promise<Uint8Array | null> {\n\tconst contentLength = Number.parseInt(c.req.header(\"content-length\") ?? \"\", 10);\n\tif (Number.isFinite(contentLength) && contentLength > maxBytes) {\n\t\treturn null;\n\t}\n\tconst stream = c.req.raw.body;\n\tif (!stream) return new Uint8Array();\n\tconst reader = stream.getReader();\n\tconst chunks: Uint8Array[] = [];\n\tlet total = 0;\n\ttry {\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) break;\n\t\t\tif (!value) continue;\n\t\t\ttotal += value.byteLength;\n\t\t\tif (total > maxBytes) {\n\t\t\t\tawait reader.cancel();\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tchunks.push(value);\n\t\t}\n\t} finally {\n\t\treader.releaseLock();\n\t}\n\tconst combined = new Uint8Array(total);\n\tlet offset = 0;\n\tfor (const chunk of chunks) {\n\t\tcombined.set(chunk, offset);\n\t\toffset += chunk.byteLength;\n\t}\n\treturn combined;\n}\n\nfunction deviceRevokedResponse(c: Context, error: unknown): Response {\n\tconst ownership = deviceOwnershipErrorResponse(c, error);\n\tif (ownership) return ownership;\n\tif (error instanceof Error && error.message === \"device_revoked\") {\n\t\treturn c.json({ error: \"device_revoked\" }, 403);\n\t}\n\tthrow error;\n}\n\nfunction deviceOwnershipErrorResponse(c: Context, error: unknown): Response | null {\n\tif (!(error instanceof Error)) return null;\n\tif (error.message === \"device_ownership_requires_verified_identity\") {\n\t\treturn c.json({ error: \"device_ownership_requires_verified_identity\" }, 403);\n\t}\n\tif (error.message === \"device_ownership_authorization_unavailable\") {\n\t\treturn c.json({ error: \"device_ownership_authorization_unavailable\" }, 503);\n\t}\n\treturn null;\n}\n\nfunction recipientInviteAcceptanceErrorResponse(c: Context, error: unknown): Response {\n\tconst ownership = deviceOwnershipErrorResponse(c, error);\n\tif (ownership) return ownership;\n\tconst code = error instanceof Error ? error.message : \"invite_invalid\";\n\treturn c.json({ error: code }, recipientInviteErrorStatus(code));\n}\n\nfunction projectInviteAcceptanceErrorResponse(c: Context, error: unknown): Response {\n\tconst ownership = deviceOwnershipErrorResponse(c, error);\n\tif (ownership) return ownership;\n\tconst code = error instanceof Error ? error.message : \"invite_invalid\";\n\tif (code === \"device_revoked\") return c.json({ error: \"device_revoked\" }, 403);\n\tif (code === \"invite_expired\") return c.json({ error: code }, 410);\n\tif (code === \"invite_invalid\") return c.json({ error: code }, 404);\n\treturn c.json({ error: code }, 409);\n}\n\nasync function enrollAdminDevice(\n\tc: Context,\n\tstore: CoordinatorStore,\n\tgroupId: string,\n\tinput: Parameters<CoordinatorStore[\"enrollDevice\"]>[1],\n): Promise<Response> {\n\ttry {\n\t\tawait store.createGroup(groupId);\n\t\tawait store.enrollDevice(groupId, input);\n\t\treturn c.json({ ok: true });\n\t} catch (error) {\n\t\treturn deviceRevokedResponse(c, error);\n\t} finally {\n\t\tawait store.close();\n\t}\n}\n\nasync function reviewJoinRequestWithRevocationDenial(\n\t...args: Parameters<typeof handleJoinRequestReview>\n): Promise<Response> {\n\ttry {\n\t\treturn await handleJoinRequestReview(...args);\n\t} catch (error) {\n\t\tif (\n\t\t\terror instanceof Error &&\n\t\t\t(error.message === \"join_review_unavailable\" || error.message === \"join_review_incomplete\")\n\t\t) {\n\t\t\treturn args[0].json({ error: error.message }, 503);\n\t\t}\n\t\treturn deviceRevokedResponse(args[0], error);\n\t}\n}\n\nasync function enableAdminDevice(\n\tc: Context,\n\tstore: CoordinatorStore,\n\tgroupId: string,\n\tdeviceId: string,\n): Promise<Response> {\n\ttry {\n\t\tconst ok = await store.setDeviceEnabled(groupId, deviceId, true);\n\t\tif (!ok) return c.json({ error: \"device_not_found\" }, 404);\n\t\treturn c.json({ ok: true });\n\t} catch (error) {\n\t\treturn deviceRevokedResponse(c, error);\n\t} finally {\n\t\tawait store.close();\n\t}\n}\n\nasync function peerDiscoveryResponse(\n\tc: Context,\n\tstore: CoordinatorStore,\n\tgroupId: string,\n\trequestingDeviceId: string,\n): Promise<Response> {\n\ttry {\n\t\tconst items = await store.listGroupPeers(groupId, requestingDeviceId);\n\t\treturn c.json({ items });\n\t} catch {\n\t\treturn c.json({ error: \"peer_discovery_unavailable\" }, 503);\n\t}\n}\n\nexport function createCoordinatorApp(\n\topts?: CreateCoordinatorAppOptions,\n): InstanceType<typeof Hono> {\n\tif (!opts?.storeFactory || !opts.runtime || !opts.requestVerifier) {\n\t\tthrow new Error(\"createCoordinatorApp requires storeFactory, runtime, and requestVerifier.\");\n\t}\n\tconst runtime = opts.runtime;\n\tconst createStore = opts.storeFactory;\n\tconst requestVerifier = opts.requestVerifier;\n\tconst requestRateLimit = opts.requestRateLimit ?? {};\n\tconst rateLimiter = requestRateLimit.limiter ?? createInMemoryRequestRateLimiter();\n\tconst readLimit = Math.max(\n\t\t1,\n\t\tMath.trunc(requestRateLimit.readLimit ?? DEFAULT_COORDINATOR_READ_LIMIT),\n\t);\n\tconst mutationLimit = Math.max(\n\t\t1,\n\t\tMath.trunc(requestRateLimit.mutationLimit ?? DEFAULT_COORDINATOR_MUTATION_LIMIT),\n\t);\n\tconst unauthenticatedReadLimit = Math.max(\n\t\t1,\n\t\tMath.trunc(requestRateLimit.unauthenticatedReadLimit ?? Math.min(20, readLimit)),\n\t);\n\tconst unauthenticatedMutationLimit = Math.max(\n\t\t1,\n\t\tMath.trunc(requestRateLimit.unauthenticatedMutationLimit ?? Math.min(10, mutationLimit)),\n\t);\n\tconst app = new Hono();\n\tconst textDecoder = new TextDecoder();\n\n\tfunction rateLimitedResponse(c: Context, key: string, authenticated: boolean) {\n\t\tconst isRead = c.req.method === \"GET\" || c.req.method === \"HEAD\" || c.req.method === \"OPTIONS\";\n\t\tconst result = rateLimiter.check(\n\t\t\t`${c.req.method}:${authenticated ? \"auth\" : \"anon\"}:${key}`,\n\t\t\tauthenticated\n\t\t\t\t? isRead\n\t\t\t\t\t? readLimit\n\t\t\t\t\t: mutationLimit\n\t\t\t\t: isRead\n\t\t\t\t\t? unauthenticatedReadLimit\n\t\t\t\t\t: unauthenticatedMutationLimit,\n\t\t);\n\t\tif (result.allowed) return null;\n\t\tc.header(\"Retry-After\", String(result.retryAfterS));\n\t\treturn c.json({ error: \"rate_limited\", retry_after_s: result.retryAfterS }, 429);\n\t}\n\n\tfunction parseJsonObject(raw: Uint8Array): Record<string, unknown> | null {\n\t\ttry {\n\t\t\tconst data: unknown = JSON.parse(textDecoder.decode(raw));\n\t\t\tif (typeof data !== \"object\" || data === null || Array.isArray(data)) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn data as Record<string, unknown>;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tregisterCoordinatorRuntimeRoutes(app, opts, {\n\t\tauthorizeRequest: (store, request) =>\n\t\t\tauthorizeRequest(store, runtime, requestVerifier, request),\n\t\tauthErrorStatus,\n\t\treadRequestBytes,\n\t\tparseJsonObject,\n\t\trateLimitedResponse: (c, key, options) => rateLimitedResponse(c, key, options.authenticated),\n\t});\n\n\tfunction optionalString(data: Record<string, unknown>, key: string): string | null {\n\t\tconst value = data[key];\n\t\tif (value == null) return null;\n\t\treturn String(value).trim() || null;\n\t}\n\n\tfunction optionalHeaderString(value: string | null | undefined): string | null {\n\t\treturn value?.trim() || null;\n\t}\n\n\tfunction optionalNumber(data: Record<string, unknown>, key: string): number | null {\n\t\tconst value = data[key];\n\t\tif (value == null || value === \"\") return null;\n\t\tif (typeof value !== \"number\" && typeof value !== \"string\") return Number.NaN;\n\t\tif (typeof value === \"string\") {\n\t\t\tconst trimmed = value.trim();\n\t\t\tif (!trimmed) return Number.NaN;\n\t\t\tconst number = Number(trimmed);\n\t\t\treturn Number.isFinite(number) ? Math.trunc(number) : Number.NaN;\n\t\t}\n\t\tconst number = value;\n\t\treturn Number.isFinite(number) ? Math.trunc(number) : Number.NaN;\n\t}\n\n\tfunction queryFlag(value: string | undefined | null): boolean {\n\t\treturn [\"1\", \"true\", \"yes\"].includes(\n\t\t\tString(value ?? \"\")\n\t\t\t\t.trim()\n\t\t\t\t.toLowerCase(),\n\t\t);\n\t}\n\n\tfunction storedProjectIntent(value: string | null | undefined) {\n\t\ttry {\n\t\t\treturn parseAcceptedProjectIntent(JSON.parse(value ?? \"\"));\n\t\t} catch {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t}\n\n\tfunction buildAcceptedProjectIntent(invite: {\n\t\toperation_id?: string | null;\n\t\treviewed_project_set_digest?: string | null;\n\t\tproject_intent_json?: string | null;\n\t}) {\n\t\tconst operationId = String(invite.operation_id ?? \"\").trim();\n\t\tconst reviewedProjectSetDigest = String(invite.reviewed_project_set_digest ?? \"\").trim();\n\t\tif (\n\t\t\t!/^share_[a-f0-9]{40}$/u.test(operationId) ||\n\t\t\t!/^[a-f0-9]{64}$/u.test(reviewedProjectSetDigest)\n\t\t) {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t\tconst projects = storedProjectIntent(invite.project_intent_json);\n\t\tconst computedDigest = acceptedProjectIntentDigest(projects);\n\t\tif (computedDigest !== reviewedProjectSetDigest) {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t\treturn {\n\t\t\toperation_id: operationId,\n\t\t\treviewed_project_set_digest: reviewedProjectSetDigest,\n\t\t\tprojects,\n\t\t};\n\t}\n\n\tfunction storedProjectSummaries(\n\t\tvalue: string | null | undefined,\n\t): ReturnType<typeof normalizeProjectInviteSummaries> {\n\t\ttry {\n\t\t\treturn normalizeProjectInviteSummaries(JSON.parse(value ?? \"\"));\n\t\t} catch {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t}\n\n\tasync function requireActiveAdminGroup(store: CoordinatorStore, groupId: string, c: Context) {\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\t\tconst group = await store.getGroup(groupId);\n\t\tif (!group) return c.json({ error: \"group_not_found\" }, 404);\n\t\tif (group.archived_at) return c.json({ error: \"group_archived\" }, 409);\n\t\treturn null;\n\t}\n\n\tasync function findAdminScope(\n\t\tstore: CoordinatorStore,\n\t\tgroupId: string,\n\t\tscopeId: string,\n\t\tc: Context,\n\t): Promise<{ scope: CoordinatorScope | null; response: Response | null }> {\n\t\tconst groupError = await requireActiveAdminGroup(store, groupId, c);\n\t\tif (groupError) return { scope: null, response: groupError };\n\t\tif (!scopeId) return { scope: null, response: c.json({ error: \"scope_id_required\" }, 400) };\n\t\tconst matching = await store.listScopes({ groupId, includeInactive: true });\n\t\tconst scope = matching.find((item) => item.scope_id === scopeId) ?? null;\n\t\tif (!scope) return { scope: null, response: c.json({ error: \"scope_not_found\" }, 404) };\n\t\treturn { scope, response: null };\n\t}\n\n\tasync function authorizeGroupMember(store: CoordinatorStore, groupId: string, c: Context) {\n\t\tconst auth = await authorizeRequest(store, runtime, requestVerifier, {\n\t\t\tmethod: c.req.method,\n\t\t\turl: c.req.url,\n\t\t\tgroupId,\n\t\t\tbody: new Uint8Array(0),\n\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t});\n\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\treturn {\n\t\t\t\tauth,\n\t\t\t\tresponse:\n\t\t\t\t\trateLimitedResponse(c, c.req.path, false) ??\n\t\t\t\t\tc.json({ error: auth.error }, authErrorStatus(auth.error)),\n\t\t\t};\n\t\t}\n\t\tconst limited = rateLimitedResponse(c, String(auth.enrollment.device_id), true);\n\t\treturn { auth, response: limited };\n\t}\n\n\tfunction activeCurrentMembership(\n\t\tmembership: CoordinatorScopeMembership,\n\t\tscope: CoordinatorScope,\n\t): boolean {\n\t\treturn membership.status === \"active\" && membership.membership_epoch >= scope.membership_epoch;\n\t}\n\n\t// -----------------------------------------------------------------------\n\t// POST /v1/presence — upsert device presence (authenticated)\n\t// -----------------------------------------------------------------------\n\n\tapp.post(\"/v1/presence\", async (c) => {\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) {\n\t\t\treturn c.json({ error: \"body_too_large\" }, 413);\n\t\t}\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tif (!groupId) {\n\t\t\treturn c.json({ error: \"group_id_required\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst auth = await authorizeRequest(store, runtime, requestVerifier, {\n\t\t\t\tmethod: c.req.method,\n\t\t\t\turl: c.req.url,\n\t\t\t\tgroupId,\n\t\t\t\tbody: raw,\n\t\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t\t});\n\t\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\t\tconst limited = rateLimitedResponse(c, c.req.path, false);\n\t\t\t\tif (limited) return limited;\n\t\t\t\treturn c.json({ error: auth.error }, authErrorStatus(auth.error));\n\t\t\t}\n\t\t\tconst limited = rateLimitedResponse(c, String(auth.enrollment.device_id), true);\n\t\t\tif (limited) return limited;\n\n\t\t\tif (data.fingerprint && String(data.fingerprint) !== String(auth.enrollment.fingerprint)) {\n\t\t\t\treturn c.json({ error: \"fingerprint_mismatch\" }, 401);\n\t\t\t}\n\n\t\t\tconst rawAddresses = data.addresses ?? [];\n\t\t\tif (!Array.isArray(rawAddresses) || !rawAddresses.every((item) => typeof item === \"string\")) {\n\t\t\t\treturn c.json({ error: \"addresses_must_be_list_of_strings\" }, 400);\n\t\t\t}\n\n\t\t\tlet ttlS: number;\n\t\t\ttry {\n\t\t\t\tttlS = Math.max(1, Number.parseInt(String(data.ttl_s ?? 180), 10));\n\t\t\t\tif (Number.isNaN(ttlS)) {\n\t\t\t\t\treturn c.json({ error: \"ttl_s_must_be_int\" }, 400);\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\treturn c.json({ error: \"ttl_s_must_be_int\" }, 400);\n\t\t\t}\n\n\t\t\tconst response = await store.upsertPresence({\n\t\t\t\tgroupId,\n\t\t\t\tdeviceId: String(auth.enrollment.device_id),\n\t\t\t\taddresses: rawAddresses as string[],\n\t\t\t\tttlS,\n\t\t\t\tcapabilities:\n\t\t\t\t\ttypeof data.capabilities === \"object\" &&\n\t\t\t\t\tdata.capabilities !== null &&\n\t\t\t\t\t!Array.isArray(data.capabilities)\n\t\t\t\t\t\t? (data.capabilities as Record<string, unknown>)\n\t\t\t\t\t\t: undefined,\n\t\t\t});\n\n\t\t\treturn c.json({ ok: true, ...response });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// GET /v1/peers — list group peers (authenticated)\n\t// -----------------------------------------------------------------------\n\n\tapp.get(\"/v1/peers\", async (c) => {\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) {\n\t\t\treturn c.json({ error: \"group_id_required\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst auth = await authorizeRequest(store, runtime, requestVerifier, {\n\t\t\t\tmethod: c.req.method,\n\t\t\t\turl: c.req.url,\n\t\t\t\tgroupId,\n\t\t\t\tbody: new Uint8Array(0),\n\t\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t\t});\n\t\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\t\tconst limited = rateLimitedResponse(c, c.req.path, false);\n\t\t\t\tif (limited) return limited;\n\t\t\t\treturn c.json({ error: auth.error }, authErrorStatus(auth.error));\n\t\t\t}\n\t\t\tconst limited = rateLimitedResponse(c, String(auth.enrollment.device_id), true);\n\t\t\tif (limited) return limited;\n\n\t\t\treturn await peerDiscoveryResponse(c, store, groupId, String(auth.enrollment.device_id));\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// GET /v1/scopes — discovery catalogue, never member/key authority\n\t// -----------------------------------------------------------------------\n\n\tapp.get(\"/v1/scopes\", async (c) => {\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst { auth, response } = await authorizeGroupMember(store, groupId, c);\n\t\t\tif (response) return response;\n\t\t\tif (!auth.enrollment) return c.json({ error: \"unknown_device\" }, 401);\n\t\t\tconst scopes = await store.listScopes({ groupId, includeInactive: false });\n\t\t\t// One indexed lookup of the requester's own memberships, rather than\n\t\t\t// reading every member of every scope to answer a question about one\n\t\t\t// device. (scope_id, device_id) is unique, so the map is 1:1.\n\t\t\tconst memberships = await store.listDeviceScopeMemberships(\n\t\t\t\tString(auth.enrollment.device_id),\n\t\t\t\tfalse,\n\t\t\t);\n\t\t\tconst membershipByScope = new Map(\n\t\t\t\tmemberships.map((membership) => [membership.scope_id, membership]),\n\t\t\t);\n\t\t\tconst items: CoordinatorScope[] = scopes.filter((scope) => {\n\t\t\t\tif (scope.status !== \"active\") return false;\n\t\t\t\tconst membership = membershipByScope.get(scope.scope_id);\n\t\t\t\treturn Boolean(membership && activeCurrentMembership(membership, scope));\n\t\t\t});\n\t\t\t// Version describes the catalogue format only. Consumers must fetch each\n\t\t\t// actual scope's current member snapshot before granting cache authority.\n\t\t\treturn c.json({ version: 1, items });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// GET /v1/scopes/:scope_id/members — list members of an authorized scope\n\t// -----------------------------------------------------------------------\n\n\tapp.get(\"/v1/scopes/:scope_id/members\", async (c) => {\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = String(c.req.param(\"scope_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\t\tif (!scopeId) return c.json({ error: \"scope_id_required\" }, 400);\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst { auth, response } = await authorizeGroupMember(store, groupId, c);\n\t\t\tif (response) return response;\n\t\t\tif (!auth.enrollment) return c.json({ error: \"unknown_device\" }, 401);\n\t\t\treturn await scopeAuthorizationResponse(c, store, {\n\t\t\t\tgroupId,\n\t\t\t\tscopeId,\n\t\t\t\trequester: auth.enrollment,\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// GET /v1/reciprocal-approvals — list pending local approval state\n\t// -----------------------------------------------------------------------\n\n\tapp.get(\"/v1/reciprocal-approvals\", async (c) => {\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tconst direction = (c.req.query(\"direction\") ?? \"incoming\").trim();\n\t\tconst status = (c.req.query(\"status\") ?? \"pending\").trim() || \"pending\";\n\t\tif (!groupId) {\n\t\t\treturn c.json({ error: \"group_id_required\" }, 400);\n\t\t}\n\t\tif (![\"incoming\", \"outgoing\"].includes(direction)) {\n\t\t\treturn c.json({ error: \"direction_must_be_incoming_or_outgoing\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst auth = await authorizeRequest(store, runtime, requestVerifier, {\n\t\t\t\tmethod: c.req.method,\n\t\t\t\turl: c.req.url,\n\t\t\t\tgroupId,\n\t\t\t\tbody: new Uint8Array(0),\n\t\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t\t});\n\t\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\t\treturn (\n\t\t\t\t\trateLimitedResponse(c, c.req.path, false) ??\n\t\t\t\t\tc.json({ error: auth.error }, authErrorStatus(auth.error))\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst limited = rateLimitedResponse(c, String(auth.enrollment.device_id), true);\n\t\t\tif (limited) return limited;\n\t\t\tconst items = await store.listReciprocalApprovals({\n\t\t\t\tgroupId,\n\t\t\t\tdeviceId: String(auth.enrollment.device_id),\n\t\t\t\tdirection: direction as \"incoming\" | \"outgoing\",\n\t\t\t\tstatus,\n\t\t\t});\n\t\t\treturn c.json({ items });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// POST /v1/reciprocal-approvals — register a local trust action\n\t// -----------------------------------------------------------------------\n\n\tapp.post(\"/v1/reciprocal-approvals\", async (c) => {\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) {\n\t\t\treturn c.json({ error: \"body_too_large\" }, 413);\n\t\t}\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst requestedDeviceId = String(data.requested_device_id ?? \"\").trim();\n\t\tconst expectedIncomingRequestId = Object.hasOwn(data, \"expected_incoming_request_id\")\n\t\t\t? String(data.expected_incoming_request_id ?? \"\").trim()\n\t\t\t: undefined;\n\t\tif (!groupId || !requestedDeviceId) {\n\t\t\treturn c.json({ error: \"group_id_and_requested_device_id_required\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst auth = await authorizeRequest(store, runtime, requestVerifier, {\n\t\t\t\tmethod: c.req.method,\n\t\t\t\turl: c.req.url,\n\t\t\t\tgroupId,\n\t\t\t\tbody: raw,\n\t\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t\t});\n\t\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\t\treturn (\n\t\t\t\t\trateLimitedResponse(c, c.req.path, false) ??\n\t\t\t\t\tc.json({ error: auth.error }, authErrorStatus(auth.error))\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst limited = rateLimitedResponse(c, String(auth.enrollment.device_id), true);\n\t\t\tif (limited) return limited;\n\t\t\tif (requestedDeviceId === String(auth.enrollment.device_id)) {\n\t\t\t\treturn c.json({ error: \"requested_device_must_differ\" }, 400);\n\t\t\t}\n\t\t\tconst targetEnrollment = await store.getEnrollment(groupId, requestedDeviceId);\n\t\t\tif (!targetEnrollment) {\n\t\t\t\treturn c.json({ error: \"requested_device_not_found\" }, 404);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst request = await store.createReciprocalApproval({\n\t\t\t\t\tgroupId,\n\t\t\t\t\trequestingDeviceId: String(auth.enrollment.device_id),\n\t\t\t\t\trequestedDeviceId,\n\t\t\t\t\t...(expectedIncomingRequestId !== undefined ? { expectedIncomingRequestId } : {}),\n\t\t\t\t});\n\t\t\t\treturn c.json({ ok: true, request });\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof CoordinatorReciprocalApprovalRequestChangedError) {\n\t\t\t\t\treturn c.json({ error: error.code }, 409);\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// POST /v1/invites/add-device — create an Identity-owned device invite\n\t// -----------------------------------------------------------------------\n\n\tapp.post(\"/v1/invites/add-device\", async (c) => {\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst allowedFields = new Set([\n\t\t\t\"group_id\",\n\t\t\t\"expires_at\",\n\t\t\t\"reviewed_preview_digest\",\n\t\t\t\"reviewed_intent\",\n\t\t]);\n\t\tif (Object.keys(data).some((key) => !allowedFields.has(key))) {\n\t\t\treturn c.json({ error: \"unexpected_add_device_invite_fields\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst expiresAt = String(data.expires_at ?? \"\").trim();\n\t\tconst reviewedPreviewDigest = String(data.reviewed_preview_digest ?? \"\").trim();\n\t\tif (!groupId || !expiresAt) {\n\t\t\treturn c.json({ error: \"group_id_and_expires_at_required\" }, 400);\n\t\t}\n\t\tif (Number.isNaN(new Date(expiresAt).getTime())) {\n\t\t\treturn c.json({ error: \"invalid_expires_at\" }, 400);\n\t\t}\n\t\tif (!/^[a-f0-9]{64}$/u.test(reviewedPreviewDigest)) {\n\t\t\treturn c.json({ error: \"reviewed_preview_digest_invalid\" }, 400);\n\t\t}\n\t\tif (data.reviewed_intent == null) {\n\t\t\treturn c.json({ error: \"recipient_invite_review_unavailable\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst auth = await authorizeRequest(store, runtime, requestVerifier, {\n\t\t\t\tmethod: c.req.method,\n\t\t\t\turl: c.req.url,\n\t\t\t\tgroupId,\n\t\t\t\tbody: raw,\n\t\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t\t});\n\t\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\t\treturn (\n\t\t\t\t\trateLimitedResponse(c, c.req.path, false) ??\n\t\t\t\t\tc.json({ error: auth.error }, authErrorStatus(auth.error))\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst limited = rateLimitedResponse(c, String(auth.enrollment.device_id), true);\n\t\t\tif (limited) return limited;\n\n\t\t\tconst targetIdentityId = auth.enrollment.identity_id;\n\t\t\tif (\n\t\t\t\t!targetIdentityId ||\n\t\t\t\ttargetIdentityId !== targetIdentityId.trim() ||\n\t\t\t\ttargetIdentityId.length > 256 ||\n\t\t\t\t/[\\p{Cc}\\p{Cf}]/u.test(targetIdentityId)\n\t\t\t) {\n\t\t\t\treturn c.json({ error: \"identity_binding_required\" }, 403);\n\t\t\t}\n\n\t\t\tlet reviewedIntent: RecipientReviewedIntentV1;\n\t\t\ttry {\n\t\t\t\treviewedIntent = await verifyRecipientReviewedIntent(data.reviewed_intent, {\n\t\t\t\t\ttarget: { kind: \"add_device\", targetIdentityId },\n\t\t\t\t\tdigest: reviewedPreviewDigest,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (\n\t\t\t\t\terror instanceof RecipientReviewedIntentError &&\n\t\t\t\t\terror.code === \"recipient_invite_intent_mismatch\"\n\t\t\t\t) {\n\t\t\t\t\treturn c.json({ error: error.code }, 409);\n\t\t\t\t}\n\t\t\t\treturn c.json({ error: \"recipient_invite_review_unavailable\" }, 400);\n\t\t\t}\n\n\t\t\tconst invite = await store.createInvite({\n\t\t\t\tgroupId,\n\t\t\t\tpolicy: \"auto_admit\",\n\t\t\t\texpiresAt,\n\t\t\t\tcreatedBy: targetIdentityId,\n\t\t\t\tinviterDeviceId: String(auth.enrollment.device_id),\n\t\t\t\tinviteKind: \"add_device\",\n\t\t\t\ttargetIdentityId,\n\t\t\t\treviewedPreviewDigest,\n\t\t\t\treviewedIntent,\n\t\t\t});\n\t\t\tconst payload: InvitePayload = {\n\t\t\t\tv: 1,\n\t\t\t\tkind: \"add_device\",\n\t\t\t\tcoordinator_url: new URL(c.req.url).origin,\n\t\t\t\tgroup_id: groupId,\n\t\t\t\tpolicy: invite.policy,\n\t\t\t\ttoken: String(invite.token ?? \"\"),\n\t\t\t\texpires_at: invite.expires_at,\n\t\t\t\tteam_name: (invite.team_name_snapshot as string) ?? null,\n\t\t\t\ttarget_identity_id: invite.target_identity_id ?? undefined,\n\t\t\t\tinviter_device_id: invite.inviter_device_id ?? undefined,\n\t\t\t\treviewed_preview_digest: invite.reviewed_preview_digest ?? undefined,\n\t\t\t};\n\t\t\tconst encoded = encodeInvitePayload(payload);\n\t\t\tconst { token: _token, ...inviteWithoutToken } = invite;\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\tinvite: inviteWithoutToken,\n\t\t\t\tpayload,\n\t\t\t\tencoded,\n\t\t\t\tlink: inviteLink(encoded),\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// Admin routes\n\t// -----------------------------------------------------------------------\n\n\t// POST /v1/admin/devices — enroll a device\n\tapp.post(\"/v1/admin/devices\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst deviceId = String(data.device_id ?? \"\").trim();\n\t\tconst fingerprint = String(data.fingerprint ?? \"\").trim();\n\t\tconst publicKey = String(data.public_key ?? \"\").trim();\n\t\tconst displayName = String(data.display_name ?? \"\").trim() || null;\n\n\t\tif (!groupId || !deviceId || !fingerprint || !publicKey) {\n\t\t\treturn c.json({ error: \"group_id_device_id_fingerprint_public_key_required\" }, 400);\n\t\t}\n\t\tif (fingerprintPublicKey(publicKey) !== fingerprint) {\n\t\t\treturn c.json({ error: \"fingerprint_mismatch\" }, 400);\n\t\t}\n\n\t\treturn enrollAdminDevice(c, createStore(), groupId, {\n\t\t\tdeviceId,\n\t\t\tfingerprint,\n\t\t\tpublicKey,\n\t\t\tdisplayName,\n\t\t});\n\t});\n\n\t// GET /v1/admin/groups — list coordinator groups\n\tapp.get(\"/v1/admin/groups\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst includeArchived = [\"1\", \"true\", \"yes\"].includes(\n\t\t\t(c.req.query(\"include_archived\") ?? \"0\").trim().toLowerCase(),\n\t\t);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\treturn c.json({ items: await store.listGroups(includeArchived) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/admin/groups\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst displayName = String(data.display_name ?? \"\").trim() || null;\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tawait store.createGroup(groupId, displayName);\n\t\t\treturn c.json({ ok: true, group: await store.getGroup(groupId) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/admin/groups/rename\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst displayName = String(data.display_name ?? \"\").trim();\n\t\tif (!groupId || !displayName) {\n\t\t\treturn c.json({ error: \"group_id_and_display_name_required\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.renameGroup(groupId, displayName);\n\t\t\tif (!ok) return c.json({ error: \"group_not_found\" }, 404);\n\t\t\treturn c.json({ ok: true, group: await store.getGroup(groupId) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/admin/groups/archive\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.archiveGroup(groupId, runtime.now());\n\t\t\tif (!ok) return c.json({ error: \"group_not_found_or_already_archived\" }, 404);\n\t\t\treturn c.json({ ok: true, group: await store.getGroup(groupId) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/admin/groups/unarchive\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.unarchiveGroup(groupId);\n\t\t\tif (!ok) return c.json({ error: \"group_not_found_or_not_archived\" }, 404);\n\t\t\treturn c.json({ ok: true, group: await store.getGroup(groupId) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// GET /v1/admin/groups/:group_id/scopes — list Sharing domains for a group\n\tapp.get(\"/v1/admin/groups/:group_id/scopes\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst groupError = await requireActiveAdminGroup(store, groupId, c);\n\t\t\tif (groupError) return groupError;\n\t\t\tconst includeInactive = queryFlag(c.req.query(\"include_inactive\"));\n\t\t\treturn c.json({\n\t\t\t\titems: await store.listScopes({ groupId, includeInactive }),\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/groups/:group_id/scopes — create a Sharing domain\n\tapp.post(\"/v1/admin/groups/:group_id/scopes\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = optionalString(data, \"scope_id\");\n\t\tconst label = optionalString(data, \"label\");\n\t\tconst membershipEpoch = optionalNumber(data, \"membership_epoch\");\n\t\tif (!scopeId || !label) return c.json({ error: \"scope_id_and_label_required\" }, 400);\n\t\tif (Number.isNaN(membershipEpoch)) {\n\t\t\treturn c.json({ error: \"membership_epoch_must_be_number\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst groupError = await requireActiveAdminGroup(store, groupId, c);\n\t\t\tif (groupError) return groupError;\n\t\t\tconst scope = await store.createScope({\n\t\t\t\tscopeId,\n\t\t\t\tlabel,\n\t\t\t\tkind: optionalString(data, \"kind\"),\n\t\t\t\tauthorityType: optionalString(data, \"authority_type\"),\n\t\t\t\tcoordinatorId: optionalString(data, \"coordinator_id\"),\n\t\t\t\tgroupId,\n\t\t\t\tmanifestIssuerDeviceId: optionalString(data, \"manifest_issuer_device_id\"),\n\t\t\t\tmembershipEpoch,\n\t\t\t\tmanifestHash: optionalString(data, \"manifest_hash\"),\n\t\t\t\tstatus: optionalString(data, \"status\"),\n\t\t\t});\n\t\t\treturn c.json({ ok: true, scope }, 201);\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error) }, 400);\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// PATCH /v1/admin/groups/:group_id/scopes/:scope_id — update Sharing domain metadata\n\tapp.patch(\"/v1/admin/groups/:group_id/scopes/:scope_id\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = String(c.req.param(\"scope_id\") ?? \"\").trim();\n\t\tconst membershipEpoch = optionalNumber(data, \"membership_epoch\");\n\t\tif (!scopeId) return c.json({ error: \"scope_id_required\" }, 400);\n\t\tif (Number.isNaN(membershipEpoch)) {\n\t\t\treturn c.json({ error: \"membership_epoch_must_be_number\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst lookup = await findAdminScope(store, groupId, scopeId, c);\n\t\t\tif (lookup.response) return lookup.response;\n\t\t\tconst scope = await store.updateScope({\n\t\t\t\tscopeId,\n\t\t\t\tlabel: data.label === undefined ? undefined : optionalString(data, \"label\"),\n\t\t\t\tkind: data.kind === undefined ? undefined : optionalString(data, \"kind\"),\n\t\t\t\tauthorityType:\n\t\t\t\t\tdata.authority_type === undefined ? undefined : optionalString(data, \"authority_type\"),\n\t\t\t\tcoordinatorId:\n\t\t\t\t\tdata.coordinator_id === undefined ? undefined : optionalString(data, \"coordinator_id\"),\n\t\t\t\tgroupId,\n\t\t\t\tmanifestIssuerDeviceId:\n\t\t\t\t\tdata.manifest_issuer_device_id === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: optionalString(data, \"manifest_issuer_device_id\"),\n\t\t\t\tmembershipEpoch,\n\t\t\t\tmanifestHash:\n\t\t\t\t\tdata.manifest_hash === undefined ? undefined : optionalString(data, \"manifest_hash\"),\n\t\t\t\tstatus: data.status === undefined ? undefined : optionalString(data, \"status\"),\n\t\t\t});\n\t\t\tif (!scope) return c.json({ error: \"scope_not_found\" }, 404);\n\t\t\treturn c.json({ ok: true, scope });\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error) }, 400);\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// GET /v1/admin/groups/:group_id/scopes/:scope_id/members — list explicit grants\n\tapp.get(\"/v1/admin/groups/:group_id/scopes/:scope_id/members\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = String(c.req.param(\"scope_id\") ?? \"\").trim();\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst lookup = await findAdminScope(store, groupId, scopeId, c);\n\t\t\tif (lookup.response) return lookup.response;\n\t\t\treturn c.json({\n\t\t\t\titems: await store.listScopeMemberships(scopeId, queryFlag(c.req.query(\"include_revoked\"))),\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/groups/:group_id/scopes/:scope_id/members — grant device access\n\tapp.post(\"/v1/admin/groups/:group_id/scopes/:scope_id/members\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = String(c.req.param(\"scope_id\") ?? \"\").trim();\n\t\tconst effectId = optionalString(data, \"effect_id\");\n\t\tconst deviceId = optionalString(data, \"device_id\");\n\t\tconst membershipEpoch = optionalNumber(data, \"membership_epoch\");\n\t\tif (!effectId) return c.json({ error: \"effect_id_required\" }, 400);\n\t\tif (!deviceId) return c.json({ error: \"device_id_required\" }, 400);\n\t\tif (Number.isNaN(membershipEpoch)) {\n\t\t\treturn c.json({ error: \"membership_epoch_must_be_number\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst lookup = await findAdminScope(store, groupId, scopeId, c);\n\t\t\tif (lookup.response) return lookup.response;\n\t\t\tconst membership = await store.grantScopeMembership({\n\t\t\t\teffectId,\n\t\t\t\tscopeId,\n\t\t\t\tdeviceId,\n\t\t\t\trole: optionalString(data, \"role\"),\n\t\t\t\tmembershipEpoch,\n\t\t\t\tcoordinatorId: optionalString(data, \"coordinator_id\"),\n\t\t\t\tgroupId,\n\t\t\t\tmanifestIssuerDeviceId: optionalString(data, \"manifest_issuer_device_id\"),\n\t\t\t\tmanifestHash: optionalString(data, \"manifest_hash\"),\n\t\t\t\tsignedManifestJson: optionalString(data, \"signed_manifest_json\"),\n\t\t\t\tactorType: \"admin\",\n\t\t\t\tactorId: optionalHeaderString(c.req.header(ADMIN_ACTOR_HEADER)),\n\t\t\t});\n\t\t\treturn c.json({ ok: true, membership }, 201);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tif (\n\t\t\t\terror instanceof CoordinatorMembershipError &&\n\t\t\t\t(error.code === \"scope_not_found\" || error.code === \"scope_group_mismatch\")\n\t\t\t) {\n\t\t\t\treturn c.json({ error: \"scope_not_found\" }, 404);\n\t\t\t}\n\t\t\tif (error instanceof CoordinatorMembershipError && error.code === \"device_not_enrolled\") {\n\t\t\t\treturn c.json({ error: \"device_not_enrolled_for_scope_group\" }, 404);\n\t\t\t}\n\t\t\tconst scopeInactive =\n\t\t\t\terror instanceof CoordinatorMembershipError && error.code === \"scope_inactive\";\n\t\t\treturn c.json(\n\t\t\t\t{ error: scopeInactive ? \"scope_not_active\" : message },\n\t\t\t\tmessage === SCOPE_MEMBERSHIP_EFFECT_CONFLICT || scopeInactive ? 409 : 400,\n\t\t\t);\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/groups/:group_id/scopes/:scope_id/members/:device_id/revoke\n\tapp.post(\"/v1/admin/groups/:group_id/scopes/:scope_id/members/:device_id/revoke\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = raw.byteLength > 0 ? parseJsonObject(raw) : {};\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = String(c.req.param(\"scope_id\") ?? \"\").trim();\n\t\tconst deviceId = String(c.req.param(\"device_id\") ?? \"\").trim();\n\t\tconst effectId = optionalString(data, \"effect_id\");\n\t\tconst membershipEpoch = optionalNumber(data, \"membership_epoch\");\n\t\tif (!effectId) return c.json({ error: \"effect_id_required\" }, 400);\n\t\tif (!deviceId) return c.json({ error: \"device_id_required\" }, 400);\n\t\tif (Number.isNaN(membershipEpoch)) {\n\t\t\treturn c.json({ error: \"membership_epoch_must_be_number\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst lookup = await findAdminScope(store, groupId, scopeId, c);\n\t\t\tif (lookup.response) return lookup.response;\n\t\t\tconst ok = await store.revokeScopeMembership({\n\t\t\t\teffectId,\n\t\t\t\tscopeId,\n\t\t\t\tdeviceId,\n\t\t\t\tgroupId,\n\t\t\t\tmembershipEpoch,\n\t\t\t\tmanifestHash: optionalString(data, \"manifest_hash\"),\n\t\t\t\tsignedManifestJson: optionalString(data, \"signed_manifest_json\"),\n\t\t\t\tactorType: \"admin\",\n\t\t\t\tactorId: optionalHeaderString(c.req.header(ADMIN_ACTOR_HEADER)),\n\t\t\t});\n\t\t\tif (!ok) return c.json({ error: \"membership_not_found\" }, 404);\n\t\t\tlet revokedMembership: CoordinatorScopeMembership | undefined;\n\t\t\ttry {\n\t\t\t\trevokedMembership = (await store.listScopeMemberships(scopeId, true)).find(\n\t\t\t\t\t(membership) => membership.device_id === deviceId,\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\trevokedMembership = undefined;\n\t\t\t}\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tdevice_id: deviceId,\n\t\t\t\trevocation: explainScopeMembershipRevocation({\n\t\t\t\t\tscopeId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tmembershipEpoch: revokedMembership?.membership_epoch ?? membershipEpoch,\n\t\t\t\t}),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tif (error instanceof CoordinatorMembershipError && error.code === \"scope_group_mismatch\") {\n\t\t\t\treturn c.json({ error: \"scope_not_found\" }, 404);\n\t\t\t}\n\t\t\treturn c.json({ error: message }, message === SCOPE_MEMBERSHIP_EFFECT_CONFLICT ? 409 : 400);\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// GET /v1/admin/devices — list enrolled devices\n\tapp.get(\"/v1/admin/devices\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\n\t\tconst includeDisabled = [\"1\", \"true\", \"yes\"].includes(\n\t\t\t(c.req.query(\"include_disabled\") ?? \"0\").trim().toLowerCase(),\n\t\t);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\treturn c.json({ items: await store.listEnrolledDevices(groupId, includeDisabled) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/devices/rename\n\tapp.post(\"/v1/admin/devices/rename\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst deviceId = String(data.device_id ?? \"\").trim();\n\t\tconst displayName = String(data.display_name ?? \"\").trim();\n\n\t\tif (!groupId || !deviceId) {\n\t\t\treturn c.json({ error: \"group_id_and_device_id_required\" }, 400);\n\t\t}\n\t\tif (!displayName) {\n\t\t\treturn c.json({ error: \"display_name_required\" }, 400);\n\t\t}\n\t\tlet normalizedDisplayName: string;\n\t\ttry {\n\t\t\tnormalizedDisplayName = normalizeHumanPresentationName(displayName, \"display_name\");\n\t\t} catch (error) {\n\t\t\treturn c.json(\n\t\t\t\t{ error: error instanceof Error ? error.message : \"display_name_invalid\" },\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.renameDevice(groupId, deviceId, normalizedDisplayName);\n\t\t\tif (!ok) return c.json({ error: \"device_not_found\" }, 404);\n\t\t\tconst device = await store.getEnrollment(groupId, deviceId);\n\t\t\treturn c.json({ ok: true, device });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/devices/disable\n\tapp.post(\"/v1/admin/devices/disable\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst deviceId = String(data.device_id ?? \"\").trim();\n\n\t\tif (!groupId || !deviceId) {\n\t\t\treturn c.json({ error: \"group_id_and_device_id_required\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.setDeviceEnabled(groupId, deviceId, false);\n\t\t\tif (!ok) return c.json({ error: \"device_not_found\" }, 404);\n\t\t\treturn c.json({ ok: true });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/devices/enable\n\tapp.post(\"/v1/admin/devices/enable\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst deviceId = String(data.device_id ?? \"\").trim();\n\n\t\tif (!groupId || !deviceId) {\n\t\t\treturn c.json({ error: \"group_id_and_device_id_required\" }, 400);\n\t\t}\n\n\t\treturn enableAdminDevice(c, createStore(), groupId, deviceId);\n\t});\n\n\t// POST /v1/admin/devices/remove\n\tapp.post(\"/v1/admin/devices/remove\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst deviceId = String(data.device_id ?? \"\").trim();\n\n\t\tif (!groupId || !deviceId) {\n\t\t\treturn c.json({ error: \"group_id_and_device_id_required\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.removeDevice(groupId, deviceId);\n\t\t\tif (!ok) return c.json({ error: \"device_not_found\" }, 404);\n\t\t\treturn c.json({ ok: true });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/admin/legacy-team-completions\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\t\tconst raw = await readRequestBytes(c, MAX_LEGACY_TEAM_COMPLETION_BODY_BYTES);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\t\tif (Object.keys(data).some((key) => key !== \"group_id\" && key !== \"manifest\")) {\n\t\t\treturn c.json({ error: \"completion_manifest_invalid\" }, 400);\n\t\t}\n\t\tlet groupId: string;\n\t\tlet manifest: CoordinatorLegacyTeamCompletionManifestV1;\n\t\ttry {\n\t\t\tconst groupIds = normalizeCoordinatorLegacyTeamCompletionGroupIds([data.group_id]);\n\t\t\tconst normalizedGroupId = groupIds[0];\n\t\t\tif (!normalizedGroupId) throw new Error(\"completion_manifest_invalid\");\n\t\t\tgroupId = normalizedGroupId;\n\t\t\tmanifest = normalizeCoordinatorLegacyTeamCompletionManifest(data.manifest);\n\t\t\trequireCoordinatorLegacyTeamCompletionTeamBinding(manifest);\n\t\t} catch {\n\t\t\treturn c.json({ error: \"completion_manifest_invalid\" }, 400);\n\t\t}\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst result = await store.createLegacyTeamCompletion(groupId, manifest);\n\t\t\treturn c.json({ ok: true, ...result }, result.status === \"created\" ? 201 : 200);\n\t\t} catch (error) {\n\t\t\tif (error instanceof CoordinatorLegacyTeamCompletionConflictError) {\n\t\t\t\treturn c.json({ error: error.code }, 409);\n\t\t\t}\n\t\t\tconst code = error instanceof Error ? error.message : \"completion_manifest_invalid\";\n\t\t\tif (code === \"group_not_found\") return c.json({ error: code }, 404);\n\t\t\tif (code === \"group_archived\") return c.json({ error: code }, 409);\n\t\t\tif (code === \"completion_manifest_unavailable\") {\n\t\t\t\treturn c.json({ error: code }, 409);\n\t\t\t}\n\t\t\tif (code === \"completion_manifest_invalid\") return c.json({ error: code }, 400);\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.get(\"/v1/admin/legacy-team-completions\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\t\tconst groupId = String(c.req.query(\"group_id\") ?? \"\").trim();\n\t\tlet candidateRef: string;\n\t\ttry {\n\t\t\tif (normalizeCoordinatorLegacyTeamCompletionGroupIds([groupId]).length !== 1) {\n\t\t\t\tthrow new Error(\"completion_manifest_invalid\");\n\t\t\t}\n\t\t\tcandidateRef = normalizeCoordinatorLegacyTeamCompletionCandidateRef(\n\t\t\t\tc.req.query(\"candidate_ref\"),\n\t\t\t);\n\t\t} catch {\n\t\t\treturn c.json({ error: \"group_id_and_candidate_ref_required\" }, 400);\n\t\t}\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst manifest = await store.getLegacyTeamCompletion(groupId, candidateRef);\n\t\t\treturn manifest ? c.json({ manifest }) : c.json({ error: \"completion_not_found\" }, 404);\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/admin/legacy-team-completions/query\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data || Object.keys(data).some((key) => key !== \"group_ids\")) {\n\t\t\treturn c.json({ error: \"completion_query_invalid\" }, 400);\n\t\t}\n\t\tlet groupIds: string[];\n\t\ttry {\n\t\t\tgroupIds = normalizeCoordinatorLegacyTeamCompletionGroupIds(data.group_ids);\n\t\t\tif (groupIds.length === 0) throw new Error(\"completion_query_invalid\");\n\t\t} catch {\n\t\t\treturn c.json({ error: \"completion_query_invalid\" }, 400);\n\t\t}\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\treturn c.json({ items: await store.listLegacyTeamCompletions(groupIds) });\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"completion_results_too_large\") {\n\t\t\t\treturn c.json({ error: error.message }, 413);\n\t\t\t}\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/invites — create an invite\n\tapp.post(\"/v1/admin/invites\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst policy = String(data.policy ?? \"auto_admit\").trim();\n\t\tconst expiresAt = String(data.expires_at ?? \"\").trim();\n\t\tconst createdBy = String(data.created_by ?? \"\").trim() || null;\n\t\tconst operationId = String(data.operation_id ?? \"\").trim() || null;\n\t\tconst reviewedProjectSetDigest = String(data.reviewed_project_set_digest ?? \"\").trim() || null;\n\t\tconst inviterActorId = String(data.inviter_actor_id ?? \"\").trim() || null;\n\t\tconst inviterDisplayName = String(data.inviter_display_name ?? \"\").trim() || null;\n\t\tconst inviterDeviceId = String(data.inviter_device_id ?? \"\").trim() || null;\n\t\tconst pendingPersonId = String(data.pending_person_id ?? \"\").trim() || null;\n\t\tconst requestedInviteKind = String(data.invite_kind ?? data.kind ?? \"\").trim();\n\t\tconst policyTeamId = String(data.policy_team_id ?? \"\").trim() || null;\n\t\tconst targetIdentityId = String(data.target_identity_id ?? \"\").trim() || null;\n\t\tconst reviewedPreviewDigest = String(data.reviewed_preview_digest ?? \"\").trim() || null;\n\t\tlet reviewedIntent: RecipientReviewedIntentV1 | undefined;\n\t\tlet projectSummaries: ReturnType<typeof normalizeProjectInviteSummaries> | null = null;\n\t\tlet projectIntent: Array<{\n\t\t\tcanonical_identity: string;\n\t\t\tdisplay_name: string;\n\t\t\texisting_memory_count: number;\n\t\t}> | null = null;\n\n\t\tif (!groupId || ![\"auto_admit\", \"approval_required\"].includes(policy) || !expiresAt) {\n\t\t\treturn c.json({ error: \"group_id_policy_and_expires_at_required\" }, 400);\n\t\t}\n\t\tif (Object.hasOwn(data, \"assigned_identity_id\")) {\n\t\t\treturn c.json({ error: \"assigned_identity_id_forbidden\" }, 400);\n\t\t}\n\t\t// Validate the date at the boundary so store.createInvite's\n\t\t// normalizeInviteExpiresAt throw can't escape as an unhandled 500.\n\t\tif (Number.isNaN(new Date(expiresAt).getTime())) {\n\t\t\treturn c.json({ error: \"invalid_expires_at\" }, 400);\n\t\t}\n\t\tif (Boolean(operationId) !== Boolean(reviewedProjectSetDigest)) {\n\t\t\treturn c.json({ error: \"operation_intent_reference_incomplete\" }, 400);\n\t\t}\n\t\tconst inviteKind = (requestedInviteKind ||\n\t\t\t(operationId ? \"project_share\" : \"legacy_enrollment\")) as CoordinatorInviteKind;\n\t\tif (\n\t\t\t!([\"legacy_enrollment\", \"project_share\", \"team_member\", \"add_device\"] as const).includes(\n\t\t\t\tinviteKind,\n\t\t\t)\n\t\t) {\n\t\t\treturn c.json({ error: \"invite_kind_invalid\" }, 400);\n\t\t}\n\t\tif (inviteKind === \"project_share\" ? !operationId : Boolean(operationId)) {\n\t\t\treturn c.json({ error: \"invite_kind_intent_mismatch\" }, 400);\n\t\t}\n\t\tif (reviewedPreviewDigest && !/^[a-f0-9]{64}$/u.test(reviewedPreviewDigest)) {\n\t\t\treturn c.json({ error: \"reviewed_preview_digest_invalid\" }, 400);\n\t\t}\n\t\tif (\n\t\t\t(inviteKind === \"team_member\" &&\n\t\t\t\t(!policyTeamId || !reviewedPreviewDigest || Boolean(targetIdentityId))) ||\n\t\t\t(inviteKind === \"add_device\" &&\n\t\t\t\t(!targetIdentityId || !reviewedPreviewDigest || Boolean(policyTeamId))) ||\n\t\t\t(![\"team_member\", \"add_device\"].includes(inviteKind) &&\n\t\t\t\tBoolean(policyTeamId || targetIdentityId || reviewedPreviewDigest))\n\t\t) {\n\t\t\treturn c.json({ error: \"recipient_invite_metadata_invalid\" }, 400);\n\t\t}\n\t\tif (\n\t\t\t[policyTeamId, targetIdentityId]\n\t\t\t\t.filter((value): value is string => Boolean(value))\n\t\t\t\t.some((value) => value.length > 256 || /[\\p{Cc}\\p{Cf}]/u.test(value))\n\t\t) {\n\t\t\treturn c.json({ error: \"recipient_invite_identifier_invalid\" }, 400);\n\t\t}\n\t\tif (inviteKind === \"team_member\" || inviteKind === \"add_device\") {\n\t\t\tif (data.reviewed_intent == null) {\n\t\t\t\treturn c.json({ error: \"recipient_invite_review_unavailable\" }, 400);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treviewedIntent = await verifyRecipientReviewedIntent(data.reviewed_intent, {\n\t\t\t\t\ttarget:\n\t\t\t\t\t\tinviteKind === \"team_member\"\n\t\t\t\t\t\t\t? { kind: \"team_member\", policyTeamId: String(policyTeamId) }\n\t\t\t\t\t\t\t: { kind: \"add_device\", targetIdentityId: String(targetIdentityId) },\n\t\t\t\t\tdigest: String(reviewedPreviewDigest),\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (\n\t\t\t\t\terror instanceof RecipientReviewedIntentError &&\n\t\t\t\t\terror.code === \"recipient_invite_intent_mismatch\"\n\t\t\t\t) {\n\t\t\t\t\treturn c.json({ error: error.code }, 409);\n\t\t\t\t}\n\t\t\t\treturn c.json({ error: \"recipient_invite_review_unavailable\" }, 400);\n\t\t\t}\n\t\t} else if (data.reviewed_intent != null) {\n\t\t\treturn c.json({ error: \"recipient_invite_metadata_invalid\" }, 400);\n\t\t}\n\t\tif (\n\t\t\t(operationId && !/^share_[a-f0-9]{40}$/u.test(operationId)) ||\n\t\t\t(reviewedProjectSetDigest && !/^[a-f0-9]{64}$/u.test(reviewedProjectSetDigest))\n\t\t) {\n\t\t\treturn c.json({ error: \"operation_intent_reference_invalid\" }, 400);\n\t\t}\n\t\tif (operationId) {\n\t\t\tif (!inviterActorId || !inviterDisplayName || !inviterDeviceId || !pendingPersonId) {\n\t\t\t\treturn c.json({ error: \"project_invite_identity_context_required\" }, 400);\n\t\t\t}\n\t\t\tif (\n\t\t\t\t[inviterActorId, inviterDeviceId, pendingPersonId].some(\n\t\t\t\t\t(value) => value.length > 256 || /[\\p{Cc}\\p{Cf}]/u.test(value),\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\treturn c.json({ error: \"project_invite_identity_context_invalid\" }, 400);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tnormalizeHumanPresentationName(inviterDisplayName, \"inviter_display_name\");\n\t\t\t\tprojectSummaries = normalizeProjectInviteSummaries(data.project_summaries);\n\t\t\t\tif (\n\t\t\t\t\t!Array.isArray(data.project_intent) ||\n\t\t\t\t\tdata.project_intent.length !== projectSummaries.length\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"project_intent_invalid\");\n\t\t\t\t}\n\t\t\t\tprojectIntent = data.project_intent.map((item, index) => {\n\t\t\t\t\tlet parsed: ReturnType<typeof parseAcceptedProjectIntent>[number] | undefined;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tparsed = parseAcceptedProjectIntent([item])[0];\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tthrow new Error(\"project_intent_invalid\");\n\t\t\t\t\t}\n\t\t\t\t\tconst summary = projectSummaries?.[index];\n\t\t\t\t\tif (\n\t\t\t\t\t\t!parsed ||\n\t\t\t\t\t\t!summary ||\n\t\t\t\t\t\tparsed.display_name !== summary.display_name ||\n\t\t\t\t\t\tparsed.existing_memory_count !== summary.existing_memory_count\n\t\t\t\t\t) {\n\t\t\t\t\t\tthrow new Error(\"project_intent_invalid\");\n\t\t\t\t\t}\n\t\t\t\t\treturn parsed;\n\t\t\t\t});\n\t\t\t\tif (\n\t\t\t\t\tnew Set(projectIntent.map((item) => item.canonical_identity)).size !==\n\t\t\t\t\tprojectIntent.length\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"project_intent_invalid\");\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{ error: error instanceof Error ? error.message : \"project_invite_invalid\" },\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst group = await store.getGroup(groupId);\n\t\t\tif (!group) return c.json({ error: \"group_not_found\" }, 404);\n\t\t\tif (group.archived_at) return c.json({ error: \"group_archived\" }, 409);\n\n\t\t\tconst invite = await store.createInvite({\n\t\t\t\tgroupId,\n\t\t\t\tpolicy,\n\t\t\t\texpiresAt,\n\t\t\t\tcreatedBy,\n\t\t\t\toperationId,\n\t\t\t\treviewedProjectSetDigest,\n\t\t\t\tinviterActorId,\n\t\t\t\tinviterDisplayName,\n\t\t\t\tinviterDeviceId,\n\t\t\t\tpendingPersonId,\n\t\t\t\tprojectSummaries,\n\t\t\t\tprojectIntent,\n\t\t\t\tinviteKind,\n\t\t\t\tpolicyTeamId,\n\t\t\t\ttargetIdentityId,\n\t\t\t\treviewedPreviewDigest,\n\t\t\t\treviewedIntent,\n\t\t\t});\n\n\t\t\tconst payload: InvitePayload = {\n\t\t\t\tv: 1,\n\t\t\t\tkind:\n\t\t\t\t\tinvite.invite_kind === \"team_member\" || invite.invite_kind === \"add_device\"\n\t\t\t\t\t\t? invite.invite_kind\n\t\t\t\t\t\t: \"coordinator_team_invite\",\n\t\t\t\tcoordinator_url: String(data.coordinator_url ?? \"\").trim(),\n\t\t\t\tgroup_id: groupId,\n\t\t\t\tpolicy: invite.policy,\n\t\t\t\ttoken: String(invite.token ?? \"\"),\n\t\t\t\texpires_at: invite.expires_at,\n\t\t\t\tteam_name: (invite.team_name_snapshot as string) ?? null,\n\t\t\t\t...(invite.operation_id\n\t\t\t\t\t? {\n\t\t\t\t\t\t\toperation_id: invite.operation_id,\n\t\t\t\t\t\t\tinviter_name: invite.inviter_display_name ?? null,\n\t\t\t\t\t\t\tproject_summaries: projectSummaries ?? [],\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t...(invite.invite_kind === \"team_member\"\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tpolicy_team_id: invite.policy_team_id ?? undefined,\n\t\t\t\t\t\t\tassigned_identity_id: invite.assigned_identity_id ?? undefined,\n\t\t\t\t\t\t\treviewed_preview_digest: invite.reviewed_preview_digest ?? undefined,\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t...(invite.invite_kind === \"add_device\"\n\t\t\t\t\t? {\n\t\t\t\t\t\t\ttarget_identity_id: invite.target_identity_id ?? undefined,\n\t\t\t\t\t\t\tinviter_device_id: invite.inviter_device_id ?? undefined,\n\t\t\t\t\t\t\treviewed_preview_digest: invite.reviewed_preview_digest ?? undefined,\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t};\n\t\t\tconst encoded = encodeInvitePayload(payload);\n\n\t\t\t// Omit token from the returned invite object (matches Python)\n\t\t\tconst { token: _token, ...inviteWithoutToken } = invite;\n\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\tinvite: inviteWithoutToken,\n\t\t\t\tpayload,\n\t\t\t\tencoded,\n\t\t\t\tlink: inviteLink(encoded),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"invite_operation_intent_conflict\") {\n\t\t\t\treturn c.json({ error: \"invite_operation_intent_conflict\" }, 409);\n\t\t\t}\n\t\t\tif (error instanceof Error && error.message === \"invite_already_bound\") {\n\t\t\t\treturn c.json({ error: \"invite_already_bound\" }, 409);\n\t\t\t}\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/invites/inspect\", async (c) => {\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\t\tconst token = String(data.token ?? \"\").trim();\n\t\tif (!token) return c.json({ error: \"invite_invalid\" }, 404);\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst invite = await store.getInviteByTokenForInspection(token);\n\t\t\tif (!invite || invite.revoked_at) return c.json({ error: \"invite_invalid\" }, 404);\n\t\t\tif (invite.invite_kind === \"team_member\" || invite.invite_kind === \"add_device\") {\n\t\t\t\ttry {\n\t\t\t\t\tconst inspection = await store.inspectRecipientInvite({ token, now: runtime.now() });\n\t\t\t\t\tif (!inspection) return c.json({ error: \"invite_invalid\" }, 404);\n\t\t\t\t\treturn c.json(\n\t\t\t\t\t\tinspection.kind === \"team_member\"\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tkind: inspection.kind,\n\t\t\t\t\t\t\t\t\tpolicy_team_id: inspection.policy_team_id,\n\t\t\t\t\t\t\t\t\tassigned_identity_id: inspection.assigned_identity_id,\n\t\t\t\t\t\t\t\t\treviewed_preview_digest: inspection.reviewed_preview_digest,\n\t\t\t\t\t\t\t\t\treviewed_intent: inspection.reviewed_intent,\n\t\t\t\t\t\t\t\t\tbound: inspection.bound,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\tkind: inspection.kind,\n\t\t\t\t\t\t\t\t\ttarget_identity_id: inspection.target_identity_id,\n\t\t\t\t\t\t\t\t\treviewed_preview_digest: inspection.reviewed_preview_digest,\n\t\t\t\t\t\t\t\t\treviewed_intent: inspection.reviewed_intent,\n\t\t\t\t\t\t\t\t\tbound: inspection.bound,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst code = error instanceof Error ? error.message : \"invite_invalid\";\n\t\t\t\t\tconst status = code === \"invite_expired\" ? 410 : code === \"invite_invalid\" ? 404 : 409;\n\t\t\t\t\treturn c.json({ error: code }, status);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst projectInvite = Boolean(invite.operation_id || invite.reviewed_project_set_digest);\n\t\t\tif (\n\t\t\t\tnew Date(invite.expires_at) <= new Date(runtime.now()) &&\n\t\t\t\t(!projectInvite || !invite.consumed_at)\n\t\t\t) {\n\t\t\t\treturn c.json({ error: \"invite_expired\" }, 410);\n\t\t\t}\n\t\t\tif (!invite.operation_id) {\n\t\t\t\treturn c.json({ kind: \"legacy_team_invite\", team_name: invite.team_name_snapshot });\n\t\t\t}\n\t\t\tif (!invite.project_intent_json || !invite.project_summaries_json) {\n\t\t\t\treturn c.json({ error: \"invite_invalid\" }, 404);\n\t\t\t}\n\t\t\tlet projects: ReturnType<typeof normalizeProjectInviteSummaries>;\n\t\t\ttry {\n\t\t\t\tprojects = storedProjectSummaries(invite.project_summaries_json);\n\t\t\t} catch {\n\t\t\t\treturn c.json({ error: \"invite_invalid\" }, 409);\n\t\t\t}\n\t\t\treturn c.json({\n\t\t\t\tkind: \"project_share_invite\",\n\t\t\t\toperation_id: invite.operation_id,\n\t\t\t\tinviter_name: invite.inviter_display_name,\n\t\t\t\tteam_name: invite.team_name_snapshot,\n\t\t\t\tprojects,\n\t\t\t\tbound: Boolean(invite.consumed_at),\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// GET /v1/admin/invites — list invites\n\tapp.get(\"/v1/admin/invites\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst rows = (await store.listInvites(groupId)).map(\n\t\t\t\t({ token: _token, ...inviteWithoutToken }) => inviteWithoutToken,\n\t\t\t);\n\t\t\treturn c.json({ items: rows });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.get(\"/v1/admin/project-invites/:operationId\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok) return c.json({ error: adminAuth.error }, 401);\n\t\tconst operationId = String(c.req.param(\"operationId\") ?? \"\").trim();\n\t\tconst groupId = String(c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!operationId || !groupId)\n\t\t\treturn c.json({ error: \"operation_id_and_group_id_required\" }, 400);\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst invite = (await store.listInvites(groupId)).find(\n\t\t\t\t(item) => item.operation_id === operationId,\n\t\t\t);\n\t\t\tif (!invite) return c.json({ error: \"operation_not_found\" }, 404);\n\t\t\tlet projects: ReturnType<typeof storedProjectIntent>;\n\t\t\ttry {\n\t\t\t\tprojects = storedProjectIntent(invite.project_intent_json);\n\t\t\t} catch {\n\t\t\t\treturn c.json({ error: \"operation_intent_invalid\" }, 409);\n\t\t\t}\n\t\t\tlet inviteLinkValue: string | null = null;\n\t\t\tif (\n\t\t\t\t!invite.consumed_at &&\n\t\t\t\t!invite.revoked_at &&\n\t\t\t\tnew Date(invite.expires_at) > new Date(runtime.now()) &&\n\t\t\t\tinvite.token &&\n\t\t\t\t!invite.token.startsWith(\"consumed:\")\n\t\t\t) {\n\t\t\t\tconst summaries = projects.map((project) => ({\n\t\t\t\t\tdisplay_name: String(project.display_name ?? \"\"),\n\t\t\t\t\texisting_memory_count: Number(project.existing_memory_count ?? 0),\n\t\t\t\t}));\n\t\t\t\tconst payload: InvitePayload = {\n\t\t\t\t\tv: 1,\n\t\t\t\t\tkind: \"coordinator_team_invite\",\n\t\t\t\t\tcoordinator_url: new URL(c.req.url).origin,\n\t\t\t\t\tgroup_id: invite.group_id,\n\t\t\t\t\tpolicy: invite.policy,\n\t\t\t\t\ttoken: invite.token,\n\t\t\t\t\texpires_at: invite.expires_at,\n\t\t\t\t\tteam_name: invite.team_name_snapshot,\n\t\t\t\t\toperation_id: operationId,\n\t\t\t\t\tinviter_name: invite.inviter_display_name ?? null,\n\t\t\t\t\tproject_summaries: summaries,\n\t\t\t\t};\n\t\t\t\tinviteLinkValue = inviteLink(encodeInvitePayload(payload));\n\t\t\t}\n\t\t\treturn c.json({\n\t\t\t\toperation_id: invite.operation_id,\n\t\t\t\tgroup_id: invite.group_id,\n\t\t\t\treviewed_project_set_digest: invite.reviewed_project_set_digest,\n\t\t\t\tstate: invite.consumed_at ? \"accepted\" : \"waiting_for_acceptance\",\n\t\t\t\tpending_person_id: invite.pending_person_id,\n\t\t\t\trecipient_actor_id: invite.recipient_actor_id,\n\t\t\t\trecipient_display_name: invite.recipient_display_name,\n\t\t\t\trecipient_device_id: invite.bound_device_id,\n\t\t\t\trecipient_device_display_name: invite.recipient_device_display_name,\n\t\t\t\trecipient_public_key: invite.bound_public_key,\n\t\t\t\trecipient_fingerprint: invite.bound_fingerprint,\n\t\t\t\tconsumed_at: invite.consumed_at,\n\t\t\t\tbootstrap_grant_id: invite.bootstrap_grant_id,\n\t\t\t\ttrust_state: invite.trust_state,\n\t\t\t\tprojects,\n\t\t\t\tinvite_link: inviteLinkValue,\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.get(\"/v1/admin/bootstrap-grants/:grantId\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst grantId = String(c.req.param(\"grantId\") ?? \"\").trim();\n\t\tif (!grantId) return c.json({ error: \"grant_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\treturn await bootstrapAuthorizationResponse(c, store, {\n\t\t\t\tgrantId,\n\t\t\t\tnowMs: Date.parse(runtime.now()),\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.get(\"/v1/bootstrap-grants/:grantId\", async (c) => {\n\t\tconst grantId = String(c.req.param(\"grantId\") ?? \"\").trim();\n\t\tconst groupId = String(c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!grantId || !groupId) return c.json({ error: \"grant_id_and_group_id_required\" }, 400);\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst auth = await authorizeRequest(store, runtime, requestVerifier, {\n\t\t\t\tmethod: c.req.method,\n\t\t\t\turl: c.req.url,\n\t\t\t\tgroupId,\n\t\t\t\tbody: new Uint8Array(0),\n\t\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t\t});\n\t\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\t\treturn (\n\t\t\t\t\trateLimitedResponse(c, c.req.path, false) ??\n\t\t\t\t\tc.json({ error: auth.error }, authErrorStatus(auth.error))\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst limited = rateLimitedResponse(c, String(auth.enrollment.device_id), true);\n\t\t\tif (limited) return limited;\n\t\t\treturn await bootstrapAuthorizationResponse(c, store, {\n\t\t\t\tgrantId,\n\t\t\t\tnowMs: Date.parse(runtime.now()),\n\t\t\t\texpectedSeed: {\n\t\t\t\t\tgroupId: auth.enrollment.group_id,\n\t\t\t\t\tdeviceId: auth.enrollment.device_id,\n\t\t\t\t\tpublicKey: auth.enrollment.public_key,\n\t\t\t\t\tfingerprint: auth.enrollment.fingerprint,\n\t\t\t\t},\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.get(\"/v1/admin/bootstrap-grants\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\treturn c.json({ items: await store.listBootstrapGrants(groupId) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/admin/bootstrap-grants/revoke\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst grantId = String(data.grant_id ?? \"\").trim();\n\t\tif (!grantId) return c.json({ error: \"grant_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.revokeBootstrapGrant(grantId, runtime.now());\n\t\t\tif (!ok) return c.json({ error: \"grant_not_found\" }, 404);\n\t\t\treturn c.json({ ok: true, grant_id: grantId });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/join-requests/approve\n\tapp.post(\"/v1/admin/join-requests/approve\", async (c) => {\n\t\treturn reviewJoinRequestWithRevocationDenial(c, true, {\n\t\t\tcreateStore,\n\t\t\truntime,\n\t\t\trateLimitedResponse,\n\t\t});\n\t});\n\n\t// POST /v1/admin/join-requests/deny\n\tapp.post(\"/v1/admin/join-requests/deny\", async (c) => {\n\t\treturn reviewJoinRequestWithRevocationDenial(c, false, {\n\t\t\tcreateStore,\n\t\t\truntime,\n\t\t\trateLimitedResponse,\n\t\t});\n\t});\n\n\t// GET /v1/admin/join-requests — list join requests\n\tapp.get(\"/v1/admin/join-requests\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\treturn c.json({ items: await store.listJoinRequests(groupId) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// POST /v1/join — join via invite token (unauthenticated)\n\t// -----------------------------------------------------------------------\n\n\tapp.post(\"/v1/join\", async (c) => {\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst token = String(data.token ?? \"\").trim();\n\t\tconst deviceId = String(data.device_id ?? \"\").trim();\n\t\tconst fingerprint = String(data.fingerprint ?? \"\").trim();\n\t\tconst publicKey = String(data.public_key ?? \"\").trim();\n\t\tconst displayName = String(data.display_name ?? \"\").trim() || null;\n\t\tconst operationId = String(data.operation_id ?? \"\").trim();\n\t\tconst recipientActorId = String(data.recipient_actor_id ?? \"\").trim();\n\t\tconst recipientDisplayName = String(data.recipient_display_name ?? \"\").trim();\n\t\tconst deviceDisplayName = String(data.device_display_name ?? \"\").trim();\n\n\t\tif (!token || !deviceId || !fingerprint || !publicKey) {\n\t\t\treturn c.json({ error: \"token_device_id_fingerprint_public_key_required\" }, 400);\n\t\t}\n\t\tif (fingerprintPublicKey(publicKey) !== fingerprint) {\n\t\t\treturn c.json({ error: \"fingerprint_mismatch\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst invite = await store.getInviteByTokenForInspection(token);\n\t\t\tif (!invite) return c.json({ error: \"invite_invalid\" }, 404);\n\t\t\tconst projectInvite = Boolean(invite.operation_id || invite.reviewed_project_set_digest);\n\t\t\tconst recipientInvite =\n\t\t\t\tinvite.invite_kind === \"team_member\" || invite.invite_kind === \"add_device\";\n\t\t\tif (invite.revoked_at) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{ error: projectInvite || recipientInvite ? \"invite_invalid\" : \"revoked_token\" },\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!invite.consumed_at && new Date(invite.expires_at) <= new Date(runtime.now())) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{ error: projectInvite || recipientInvite ? \"invite_expired\" : \"expired_token\" },\n\t\t\t\t\t410,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (recipientInvite) {\n\t\t\t\tconst allowedRecipientAcceptanceFields = new Set([\n\t\t\t\t\t\"token\",\n\t\t\t\t\t\"invite_kind\",\n\t\t\t\t\t\"kind\",\n\t\t\t\t\t\"identity_id\",\n\t\t\t\t\t\"device_id\",\n\t\t\t\t\t\"public_key\",\n\t\t\t\t\t\"fingerprint\",\n\t\t\t\t\t\"recipient_display_name\",\n\t\t\t\t\t\"device_display_name\",\n\t\t\t\t]);\n\t\t\t\tif (Object.keys(data).some((key) => !allowedRecipientAcceptanceFields.has(key))) {\n\t\t\t\t\treturn c.json({ error: \"unexpected_recipient_invite_fields\" }, 400);\n\t\t\t\t}\n\t\t\t\tconst requestedKind = String(data.invite_kind ?? data.kind ?? \"\").trim();\n\t\t\t\tconst identityId = String(data.identity_id ?? \"\").trim();\n\t\t\t\tif (!identityId || requestedKind !== invite.invite_kind) {\n\t\t\t\t\treturn c.json({ error: \"recipient_invite_binding_required\" }, 400);\n\t\t\t\t}\n\t\t\t\tif (identityId.length > 256 || /[\\p{Cc}\\p{Cf}]/u.test(identityId)) {\n\t\t\t\t\treturn c.json({ error: \"identity_id_invalid\" }, 400);\n\t\t\t\t}\n\t\t\t\tlet normalizedRecipientDisplayName: string | null = null;\n\t\t\t\tlet normalizedDeviceDisplayName: string | null = null;\n\t\t\t\ttry {\n\t\t\t\t\tif (data.recipient_display_name != null) {\n\t\t\t\t\t\tif (typeof data.recipient_display_name !== \"string\") {\n\t\t\t\t\t\t\tthrow new Error(\"recipient_display_name_invalid\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tnormalizedRecipientDisplayName = normalizeHumanPresentationName(\n\t\t\t\t\t\t\tdata.recipient_display_name,\n\t\t\t\t\t\t\t\"recipient_display_name\",\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (data.device_display_name != null) {\n\t\t\t\t\t\tif (typeof data.device_display_name !== \"string\") {\n\t\t\t\t\t\t\tthrow new Error(\"device_display_name_invalid\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tnormalizedDeviceDisplayName = normalizeDeviceDisplayName(\n\t\t\t\t\t\t\tdata.device_display_name,\n\t\t\t\t\t\t\t\"device_display_name\",\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn c.json(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\terror: error instanceof Error ? error.message : \"recipient_invite_identity_invalid\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t400,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\tinvite.invite_kind === \"add_device\" &&\n\t\t\t\t\tString(invite.inviter_device_id ?? \"\").trim() === deviceId\n\t\t\t\t) {\n\t\t\t\t\treturn c.json({ error: \"add_device_invite_self_acceptance_forbidden\" }, 409);\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst acceptance = await store.consumeRecipientInvite({\n\t\t\t\t\t\ttoken,\n\t\t\t\t\t\tinviteKind: invite.invite_kind as \"team_member\" | \"add_device\",\n\t\t\t\t\t\tidentityId,\n\t\t\t\t\t\tdeviceId,\n\t\t\t\t\t\tpublicKey,\n\t\t\t\t\t\tfingerprint,\n\t\t\t\t\t\trecipientDisplayName: normalizedRecipientDisplayName,\n\t\t\t\t\t\tdeviceDisplayName: normalizedDeviceDisplayName,\n\t\t\t\t\t\tnow: runtime.now(),\n\t\t\t\t\t});\n\t\t\t\t\treturn c.json({\n\t\t\t\t\t\tok: true,\n\t\t\t\t\t\tstatus: acceptance.status,\n\t\t\t\t\t\tkind: acceptance.invite.invite_kind,\n\t\t\t\t\t\tgroup_id: acceptance.invite.group_id,\n\t\t\t\t\t\tidentity_id: acceptance.invite.recipient_actor_id,\n\t\t\t\t\t\tpolicy_team_id: acceptance.invite.policy_team_id ?? null,\n\t\t\t\t\t\ttarget_identity_id: acceptance.invite.target_identity_id ?? null,\n\t\t\t\t\t\tassigned_identity_id: acceptance.invite.assigned_identity_id ?? null,\n\t\t\t\t\t\tbootstrap_grant_id: acceptance.bootstrap_grant?.grant_id ?? null,\n\t\t\t\t\t\tinviter_device: acceptance.bootstrap_grant\n\t\t\t\t\t\t\t? await store.getEnrollment(\n\t\t\t\t\t\t\t\t\tacceptance.invite.group_id,\n\t\t\t\t\t\t\t\t\tacceptance.bootstrap_grant.seed_device_id,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\t\treviewed_preview_digest: acceptance.invite.reviewed_preview_digest,\n\t\t\t\t\t\treviewed_intent: acceptance.reviewed_intent,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn recipientInviteAcceptanceErrorResponse(c, error);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (invite.operation_id || invite.reviewed_project_set_digest) {\n\t\t\t\tconst allowedProjectAcceptanceFields = new Set([\n\t\t\t\t\t\"token\",\n\t\t\t\t\t\"operation_id\",\n\t\t\t\t\t\"device_id\",\n\t\t\t\t\t\"public_key\",\n\t\t\t\t\t\"fingerprint\",\n\t\t\t\t\t\"display_name\",\n\t\t\t\t\t\"recipient_actor_id\",\n\t\t\t\t\t\"recipient_display_name\",\n\t\t\t\t\t\"device_display_name\",\n\t\t\t\t]);\n\t\t\t\tif (Object.keys(data).some((key) => !allowedProjectAcceptanceFields.has(key))) {\n\t\t\t\t\treturn c.json({ error: \"unexpected_project_invite_fields\" }, 400);\n\t\t\t\t}\n\t\t\t\tif (!operationId || !recipientActorId || !recipientDisplayName || !deviceDisplayName) {\n\t\t\t\t\treturn c.json({ error: \"project_invite_identity_required\" }, 400);\n\t\t\t\t}\n\t\t\t\tif (String(invite.inviter_device_id ?? \"\").trim() === deviceId) {\n\t\t\t\t\treturn c.json({ error: \"project_invite_self_acceptance_forbidden\" }, 409);\n\t\t\t\t}\n\t\t\t\tif (recipientActorId.length > 256 || /[\\p{Cc}\\p{Cf}]/u.test(recipientActorId)) {\n\t\t\t\t\treturn c.json({ error: \"recipient_actor_id_invalid\" }, 400);\n\t\t\t\t}\n\t\t\t\tlet normalizedRecipientName: string;\n\t\t\t\tlet normalizedDeviceName: string;\n\t\t\t\ttry {\n\t\t\t\t\tnormalizedRecipientName = normalizeHumanPresentationName(\n\t\t\t\t\t\trecipientDisplayName,\n\t\t\t\t\t\t\"recipient_display_name\",\n\t\t\t\t\t);\n\t\t\t\t\tnormalizedDeviceName = normalizeDeviceDisplayName(\n\t\t\t\t\t\tdeviceDisplayName,\n\t\t\t\t\t\t\"device_display_name\",\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn c.json(\n\t\t\t\t\t\t{ error: error instanceof Error ? error.message : \"project_invite_identity_invalid\" },\n\t\t\t\t\t\t400,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tlet acceptedIntent: ReturnType<typeof buildAcceptedProjectIntent>;\n\t\t\t\ttry {\n\t\t\t\t\tacceptedIntent = buildAcceptedProjectIntent(invite);\n\t\t\t\t} catch {\n\t\t\t\t\treturn c.json({ error: \"operation_intent_invalid\" }, 409);\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst acceptance = await store.consumeProjectInvite({\n\t\t\t\t\t\ttoken,\n\t\t\t\t\t\toperationId,\n\t\t\t\t\t\tdeviceId,\n\t\t\t\t\t\tpublicKey,\n\t\t\t\t\t\tfingerprint,\n\t\t\t\t\t\trecipientActorId,\n\t\t\t\t\t\trecipientDisplayName: normalizedRecipientName,\n\t\t\t\t\t\tdeviceDisplayName: normalizedDeviceName,\n\t\t\t\t\t\tnow: runtime.now(),\n\t\t\t\t\t});\n\t\t\t\t\treturn c.json({\n\t\t\t\t\t\tok: true,\n\t\t\t\t\t\tstatus: PROJECT_INVITE_PENDING_STATUS,\n\t\t\t\t\t\tgroup_id: acceptance.invite.group_id,\n\t\t\t\t\t\toperation_id: acceptance.invite.operation_id,\n\t\t\t\t\t\ttrust_state: acceptance.invite.trust_state,\n\t\t\t\t\t\tbootstrap_grant_id: acceptance.bootstrap_grant?.grant_id ?? null,\n\t\t\t\t\t\tinviter_device: acceptance.seed_enrollment\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tdevice_id: acceptance.seed_enrollment.device_id,\n\t\t\t\t\t\t\t\t\tpublic_key: acceptance.seed_enrollment.public_key,\n\t\t\t\t\t\t\t\t\tfingerprint: acceptance.seed_enrollment.fingerprint,\n\t\t\t\t\t\t\t\t\tdisplay_name: acceptance.seed_enrollment.display_name,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\t\taccepted_project_intent: acceptedIntent,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn projectInviteAcceptanceErrorResponse(c, error);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst projectAcceptanceFields = [\n\t\t\t\t\"operation_id\",\n\t\t\t\t\"recipient_actor_id\",\n\t\t\t\t\"recipient_display_name\",\n\t\t\t\t\"device_display_name\",\n\t\t\t];\n\t\t\tif (projectAcceptanceFields.some((field) => Object.hasOwn(data, field))) {\n\t\t\t\treturn c.json({ error: \"unexpected_project_invite_fields\" }, 400);\n\t\t\t}\n\t\t\tconst group = await store.getGroup(String(invite.group_id));\n\t\t\tif (!group) return c.json({ error: \"group_not_found\" }, 404);\n\t\t\tif (group.archived_at) return c.json({ error: \"group_archived\" }, 409);\n\n\t\t\tconst inviteGroupId = String(invite.group_id);\n\t\t\tconst existing = await store.getEnrollment(inviteGroupId, deviceId);\n\t\t\tif (existing) {\n\t\t\t\treturn c.json({\n\t\t\t\t\tok: true,\n\t\t\t\t\tstatus: \"already_enrolled\",\n\t\t\t\t\tgroup_id: invite.group_id,\n\t\t\t\t\tpolicy: invite.policy,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst invitePolicy = String(invite.policy);\n\t\t\tif (![\"auto_admit\", \"approval_required\"].includes(invitePolicy)) {\n\t\t\t\treturn c.json({ error: `unknown invite policy: ${invitePolicy}` }, 400);\n\t\t\t}\n\n\t\t\tif (invitePolicy === \"approval_required\") {\n\t\t\t\tconst request = await store.createJoinRequest({\n\t\t\t\t\tgroupId: inviteGroupId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tpublicKey,\n\t\t\t\t\tfingerprint,\n\t\t\t\t\tdisplayName,\n\t\t\t\t\ttoken,\n\t\t\t\t});\n\t\t\t\treturn c.json({\n\t\t\t\t\tok: true,\n\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\tgroup_id: invite.group_id,\n\t\t\t\t\tpolicy: invite.policy,\n\t\t\t\t\trequest_id: request.request_id,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tawait store.enrollDevice(inviteGroupId, {\n\t\t\t\tdeviceId,\n\t\t\t\tfingerprint,\n\t\t\t\tpublicKey,\n\t\t\t\tdisplayName,\n\t\t\t});\n\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\tstatus: \"enrolled\",\n\t\t\t\tgroup_id: invite.group_id,\n\t\t\t\tpolicy: invite.policy,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\treturn deviceRevokedResponse(c, error);\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\treturn app;\n}\n\n// ---------------------------------------------------------------------------\n// Shared handler for approve/deny\n// ---------------------------------------------------------------------------\n\nasync function handleJoinRequestReview(\n\tc: Context,\n\tapproved: boolean,\n\tdeps: {\n\t\tcreateStore: () => CoordinatorStore;\n\t\truntime: CoordinatorRuntimeDeps;\n\t\trateLimitedResponse: (c: Context, key: string, authenticated: boolean) => Response | null;\n\t},\n) {\n\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), deps.runtime);\n\tif (!adminAuth.ok)\n\t\treturn (\n\t\t\tdeps.rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401)\n\t\t);\n\tconst limited = deps.rateLimitedResponse(c, \"admin\", true);\n\tif (limited) return limited;\n\n\tconst raw = await (async () => {\n\t\tconst contentLength = Number.parseInt(c.req.header(\"content-length\") ?? \"\", 10);\n\t\tif (Number.isFinite(contentLength) && contentLength > MAX_BODY_BYTES) {\n\t\t\treturn null;\n\t\t}\n\t\tconst stream = c.req.raw.body;\n\t\tif (!stream) return new Uint8Array();\n\t\tconst reader = stream.getReader();\n\t\tconst chunks: Uint8Array[] = [];\n\t\tlet total = 0;\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\t\t\t\tif (!value) continue;\n\t\t\t\ttotal += value.byteLength;\n\t\t\t\tif (total > MAX_BODY_BYTES) {\n\t\t\t\t\tawait reader.cancel();\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tchunks.push(value);\n\t\t\t}\n\t\t} finally {\n\t\t\treader.releaseLock();\n\t\t}\n\t\tconst combined = new Uint8Array(total);\n\t\tlet offset = 0;\n\t\tfor (const chunk of chunks) {\n\t\t\tcombined.set(chunk, offset);\n\t\t\toffset += chunk.byteLength;\n\t\t}\n\t\treturn combined;\n\t})();\n\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\tlet data: Record<string, unknown> | null;\n\ttry {\n\t\tconst textDecoder = new TextDecoder();\n\t\tconst parsed: unknown = JSON.parse(textDecoder.decode(raw));\n\t\tdata =\n\t\t\ttypeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed)\n\t\t\t\t? (parsed as Record<string, unknown>)\n\t\t\t\t: null;\n\t} catch {\n\t\tdata = null;\n\t}\n\tif (!data) {\n\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t}\n\n\tconst requestId = String(data.request_id ?? \"\").trim();\n\tconst reviewedBy = String(data.reviewed_by ?? \"\").trim() || null;\n\tconst bootstrapGrantSeedDeviceId = String(data.bootstrap_grant_seed_device_id ?? \"\").trim();\n\tconst bootstrapGrantExpiresAt = String(data.bootstrap_grant_expires_at ?? \"\").trim();\n\n\tif (!requestId) return c.json({ error: \"request_id_required\" }, 400);\n\tconst bootstrapGrantFields = [bootstrapGrantSeedDeviceId, bootstrapGrantExpiresAt].filter(\n\t\tBoolean,\n\t).length;\n\tif (bootstrapGrantFields > 0 && bootstrapGrantFields < 2) {\n\t\treturn c.json(\n\t\t\t{ error: \"bootstrap_grant_seed_device_id_and_expires_at_required_together\" },\n\t\t\t400,\n\t\t);\n\t}\n\n\tconst store = deps.createStore();\n\ttry {\n\t\tconst request = await store.reviewJoinRequest({\n\t\t\trequestId,\n\t\t\tapproved,\n\t\t\treviewedBy,\n\t\t\tbootstrapGrant:\n\t\t\t\tapproved && bootstrapGrantSeedDeviceId && bootstrapGrantExpiresAt\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tseedDeviceId: bootstrapGrantSeedDeviceId,\n\t\t\t\t\t\t\texpiresAt: bootstrapGrantExpiresAt,\n\t\t\t\t\t\t\tcreatedBy: reviewedBy,\n\t\t\t\t\t\t}\n\t\t\t\t\t: null,\n\t\t});\n\n\t\tif (!request) return c.json({ error: \"request_not_found\" }, 404);\n\n\t\tif (request._no_transition) {\n\t\t\treturn c.json({ error: \"request_not_pending\", status: request.status }, 409);\n\t\t}\n\n\t\treturn c.json({ ok: true, request });\n\t} finally {\n\t\tawait store.close();\n\t}\n}\n","import { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { CoordinatorIdentityGroupGrant } from \"./coordinator-identity-group-grant.js\";\n\nexport function isCoordinatorControllerAttestationReference(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" && value.length === 78 && /^controller-v1:[a-f0-9]{64}$/.test(value)\n\t);\n}\n\nexport interface CoordinatorIdentityGroupGrantActionResult {\n\tkind: \"created\" | \"existing\";\n\tgrant: CoordinatorIdentityGroupGrant;\n}\n\n/** Return only validated transport-grant fields, never arbitrary server output. */\nexport function parseCoordinatorIdentityGroupGrantResponse(\n\tpayload: Record<string, unknown> | null,\n): CoordinatorIdentityGroupGrantActionResult {\n\tconst value = payload?.grant;\n\tif (!value || typeof value !== \"object\" || Array.isArray(value))\n\t\tthrow new Error(\"identity_group_grant_response_invalid\");\n\tconst grant = value as Record<string, unknown>;\n\tif (\n\t\t(payload?.kind !== \"created\" && payload?.kind !== \"existing\") ||\n\t\t!isAuthControllerId(grant.coordinator_id) ||\n\t\t!isAuthControllerId(grant.identity_id) ||\n\t\t!isAuthControllerId(grant.group_id) ||\n\t\t!isAuthControllerId(grant.source_receipt_id) ||\n\t\tgrant.status !== \"active\" ||\n\t\tgrant.source_kind !== \"controller_attestation\" ||\n\t\ttypeof grant.revision !== \"number\" ||\n\t\t!Number.isSafeInteger(grant.revision) ||\n\t\tgrant.revision < 1 ||\n\t\t!isAuthControllerId(grant.created_at) ||\n\t\t!Number.isFinite(Date.parse(grant.created_at)) ||\n\t\tgrant.revoked_at !== null\n\t)\n\t\tthrow new Error(\"identity_group_grant_response_invalid\");\n\treturn {\n\t\tkind: payload.kind,\n\t\tgrant: {\n\t\t\tcoordinator_id: grant.coordinator_id,\n\t\t\tidentity_id: grant.identity_id,\n\t\t\tgroup_id: grant.group_id,\n\t\t\tstatus: grant.status,\n\t\t\trevision: grant.revision,\n\t\t\tsource_kind: grant.source_kind,\n\t\t\tsource_receipt_id: grant.source_receipt_id,\n\t\t\tcreated_at: grant.created_at,\n\t\t\trevoked_at: grant.revoked_at,\n\t\t},\n\t};\n}\n","import {\n\tdecodeCoordinatorAuthProof32,\n\thashCoordinatorAuthProofBytes32,\n} from \"./coordinator-auth-proof.js\";\nimport { ed25519KeyId, parseSshEd25519PublicKey } from \"./coordinator-ed25519-key-id.js\";\n\n/** Private ceremony metadata and pending-key proof, never current account/group authority. */\nexport interface OwnerAttempt {\n\tcoordinator_id: string;\n\tattempt_id: string;\n\tpurpose: \"owner_enroll\";\n\torigin: string;\n\tdevice_id: string;\n\tpublic_key: string;\n\tkey_id: string;\n\tfingerprint: string;\n\tissuer: string;\n\tauth_config_revision: string;\n\tadmission_owner_hash: string | null;\n\tloopback_redirect: string | null;\n\tbrowser_start_hash: string;\n\tbrowser_transaction_hash: string | null;\n\tbrowser_binder_hash: string | null;\n\taccount_subject: string | null;\n\tidentity_id: string | null;\n\tlink_id: string | null;\n\tlink_attempt_id: string | null;\n\tlink_controller_attestation_id: string | null;\n\tlink_auth_config_revision: string | null;\n\tgrant_revisions_json: string | null;\n\tconfirmation_hash: string | null;\n\tcompletion_secret_hash: string | null;\n\tfinal_key_proof_hash: string | null;\n\tstate: string;\n\tcreated_at_ms: number;\n\texpires_at_ms: number;\n\tfinalized_at_ms: number | null;\n\tbinding_id: string | null;\n\taudit_event_id: string | null;\n\tfinal_outcome_json: string | null;\n}\n\n/** The optional column exists only after explicit schema installation. */\nexport interface OwnerAuthorityAttempt extends OwnerAttempt {\n\towner_qualification_id?: string | null;\n}\n\nexport interface GrantPin {\n\tgroupId: string;\n\trevision: number;\n}\nexport function readGrantPins(value: string | null): GrantPin[] | null {\n\ttry {\n\t\tconst pins: unknown = JSON.parse(value ?? \"null\");\n\t\tif (!Array.isArray(pins) || pins.length < 1 || pins.length > 50) return null;\n\t\tif (\n\t\t\t!pins.every(\n\t\t\t\t(p) =>\n\t\t\t\t\tp &&\n\t\t\t\t\ttypeof p === \"object\" &&\n\t\t\t\t\ttypeof p.groupId === \"string\" &&\n\t\t\t\t\tp.groupId.trim().length > 0 &&\n\t\t\t\t\tp.groupId === p.groupId.trim() &&\n\t\t\t\t\t!p.groupId.includes(\"\\0\") &&\n\t\t\t\t\tNumber.isSafeInteger(p.revision) &&\n\t\t\t\t\tp.revision > 0,\n\t\t\t)\n\t\t)\n\t\t\treturn null;\n\t\tif (new Set(pins.map((p) => p.groupId)).size !== pins.length) return null;\n\t\treturn pins.map(({ groupId, revision }) => ({ groupId, revision }));\n\t} catch {\n\t\treturn null;\n\t}\n}\nexport function validAttemptTime(row: OwnerAttempt): boolean {\n\treturn (\n\t\tNumber.isSafeInteger(row.created_at_ms) &&\n\t\trow.created_at_ms >= 0 &&\n\t\trow.created_at_ms <= 9007199254140991 &&\n\t\trow.expires_at_ms === row.created_at_ms + 600000\n\t);\n}\nexport function validWriteTime(value: unknown): value is number {\n\treturn (\n\t\tNumber.isSafeInteger(value) &&\n\t\ttypeof value === \"number\" &&\n\t\tvalue >= 0 &&\n\t\tvalue <= 8640000000000000\n\t);\n}\n\ntype OwnerFinalPins = Pick<\n\tOwnerAttempt,\n\t| \"coordinator_id\"\n\t| \"origin\"\n\t| \"auth_config_revision\"\n\t| \"attempt_id\"\n\t| \"device_id\"\n\t| \"public_key\"\n\t| \"key_id\"\n\t| \"fingerprint\"\n\t| \"issuer\"\n\t| \"confirmation_hash\"\n>;\n\n/** The pending device can sign these pins from its start and the owner-only loopback delivery. */\nexport function ownerEnrollmentFinalMessage(a: OwnerFinalPins, completionSecret: string): string {\n\treturn JSON.stringify([\n\t\t\"codemem-owner-enrollment-finalize-v2\",\n\t\t\"owner_enroll\",\n\t\ta.coordinator_id,\n\t\ta.origin,\n\t\ta.auth_config_revision,\n\t\ta.attempt_id,\n\t\ta.device_id,\n\t\ta.public_key,\n\t\ta.key_id,\n\t\ta.fingerprint,\n\t\ta.issuer,\n\t\ta.confirmation_hash,\n\t\tcompletionSecret,\n\t]);\n}\n/** Commitment shown to the original browser, including the exact linked account and grants. */\nexport async function ownerEnrollmentConfirmationHash(a: OwnerAuthorityAttempt): Promise<string> {\n\tconst fields = `coordinator_id attempt_id origin device_id public_key key_id fingerprint\n issuer account_subject identity_id link_id link_attempt_id link_controller_attestation_id\n link_auth_config_revision auth_config_revision browser_start_hash browser_transaction_hash\n browser_binder_hash grant_revisions_json created_at_ms expires_at_ms`.split(/\\s+/);\n\tconst message = JSON.stringify([\n\t\t\"owner_enroll\",\n\t\t...fields.map((field) => a[field as keyof OwnerAttempt]),\n\t\t// Keep existing operator confirmation/proof commitments byte-for-byte unchanged.\n\t\t...(a.admission_owner_hash === null ? [] : [a.admission_owner_hash]),\n\t\t...(a.owner_qualification_id == null\n\t\t\t? []\n\t\t\t: [\"codemem.owner-enrollment.qualification.v1\", a.owner_qualification_id]),\n\t]);\n\tconst digest = await globalThis.crypto.subtle.digest(\n\t\t\"SHA-256\",\n\t\tnew TextEncoder().encode(message),\n\t);\n\treturn Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n/** Verifies the pending-key signature and hashes proof bytes, not the stored completion hash or current authority. */\nexport async function verifyPendingKeySignatureAndHashes(\n\ta: OwnerAttempt,\n\tcompletionSecret: string,\n\tsignature: string,\n) {\n\tconst bytes = decodeCoordinatorAuthProof32(completionSecret);\n\tif (!bytes || (await ed25519KeyId(a.public_key)) !== a.key_id) return null;\n\t// Legacy fingerprints hash the exact key text, unlike the canonical SSH key ID.\n\tconst fingerprintDigest = await globalThis.crypto.subtle.digest(\n\t\t\"SHA-256\",\n\t\tnew TextEncoder().encode(a.public_key),\n\t);\n\tconst fingerprint = Array.from(new Uint8Array(fingerprintDigest), (b) =>\n\t\tb.toString(16).padStart(2, \"0\"),\n\t).join(\"\");\n\tif (fingerprint !== a.fingerprint) return null;\n\tconst completionHash = await hashCoordinatorAuthProofBytes32(bytes);\n\tconst message = ownerEnrollmentFinalMessage(a, completionSecret);\n\tif (!(await verifyOwnerEnrollmentSignature(a.public_key, message, signature))) return null;\n\tconst digest = await globalThis.crypto.subtle.digest(\n\t\t\"SHA-256\",\n\t\tnew TextEncoder().encode(signature),\n\t);\n\tconst keyProofHash = Array.from(new Uint8Array(digest), (b) =>\n\t\tb.toString(16).padStart(2, \"0\"),\n\t).join(\"\");\n\treturn { completionHash, keyProofHash };\n}\nexport async function verifyOwnerEnrollmentSignature(\n\tpublicKey: string,\n\tmessage: string,\n\tsignature: string,\n): Promise<boolean> {\n\ttry {\n\t\tif (typeof signature !== \"string\" || !/^[A-Za-z0-9_-]{85}[AQgw]$/.test(signature)) return false;\n\t\tconst binary = atob(`${signature.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\")}==`);\n\t\tconst bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));\n\t\tconst parsed = parseSshEd25519PublicKey(publicKey);\n\t\tif (parsed.kind !== \"ed25519\" || bytes.length !== 64) return false;\n\t\tconst key = await globalThis.crypto.subtle.importKey(\n\t\t\t\"raw\",\n\t\t\tnew Uint8Array(parsed.blob.slice(19)),\n\t\t\t{ name: \"Ed25519\" },\n\t\t\tfalse,\n\t\t\t[\"verify\"],\n\t\t);\n\t\treturn await globalThis.crypto.subtle.verify(\n\t\t\t\"Ed25519\",\n\t\t\tkey,\n\t\t\tbytes,\n\t\t\tnew TextEncoder().encode(message),\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** Validates proof and metadata only; the atomic writer must still check live authority in SQL. */\nexport async function verifyOwnerEnrollmentCompletion(\n\ta: OwnerAttempt,\n\trevision: string,\n\tnow: number,\n\tcompletionSecret: string,\n\tsignature: string,\n) {\n\tconst grants = readGrantPins(a.grant_revisions_json);\n\tif (\n\t\t!grants ||\n\t\ta.purpose !== \"owner_enroll\" ||\n\t\ta.state !== \"confirmed\" ||\n\t\t![a.account_subject, a.identity_id, a.link_id, a.confirmation_hash].every(isNonemptyText) ||\n\t\t!validAttemptTime(a) ||\n\t\t!validWriteTime(now) ||\n\t\tnow < a.created_at_ms ||\n\t\tnow >= a.expires_at_ms ||\n\t\trevision !== a.auth_config_revision\n\t)\n\t\treturn null;\n\tif ((await ownerEnrollmentConfirmationHash(a)) !== a.confirmation_hash) return null;\n\tconst proof = await verifyPendingKeySignatureAndHashes(a, completionSecret, signature);\n\tif (!proof || proof.completionHash !== a.completion_secret_hash) return null;\n\treturn { grants, ...proof };\n}\nfunction isNonemptyText(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.trim().length > 0;\n}\nfunction receiptOutcomeMatches(row: OwnerAttempt): boolean {\n\tconst grants = readGrantPins(row.grant_revisions_json);\n\ttry {\n\t\tconst outcome = JSON.parse(row.final_outcome_json ?? \"null\");\n\t\treturn (\n\t\t\t!!grants &&\n\t\t\toutcome?.kind === \"finalized\" &&\n\t\t\toutcome.bindingId === row.binding_id &&\n\t\t\tJSON.stringify(outcome.groups) === JSON.stringify(grants.map((g) => g.groupId))\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Receipt shape is not evidence that a database commit occurred or permission remains active. */\nexport function validOwnerEnrollmentReceiptMetadata(a: OwnerAttempt): boolean {\n\treturn (\n\t\ta.purpose === \"owner_enroll\" &&\n\t\ta.state === \"finalized\" &&\n\t\t!!a.binding_id &&\n\t\t!!a.audit_event_id &&\n\t\tisNonemptyText(a.final_key_proof_hash) &&\n\t\tisNonemptyText(a.completion_secret_hash) &&\n\t\treceiptOutcomeMatches(a) &&\n\t\tvalidAttemptTime(a) &&\n\t\tvalidWriteTime(a.finalized_at_ms) &&\n\t\ta.finalized_at_ms >= a.created_at_ms &&\n\t\ta.finalized_at_ms < a.expires_at_ms\n\t);\n}\n","/** Trusted server-side data only, never request JSON or an environment loader.\n * Enabled settings contain SDK secrets: never use them as an HTTP or logging DTO.\n */\nimport type { CoordinatorAuthBrowserConfig } from \"./coordinator-auth-browser-transaction-contract.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { CoordinatorOidcProviderConfig } from \"./coordinator-oidc.js\";\n\nexport const COORDINATOR_BROWSER_AUTH_ISSUER = \"https://accounts.google.com\";\n\nexport interface CoordinatorBrowserAuthConfig {\n\tenabled: boolean;\n\tcoordinatorId: string;\n\tissuer: string;\n\tclientId: string;\n\tclientSecret: string;\n\tredirectUri: string;\n\trevision: string;\n}\n\nexport type CoordinatorBrowserAuthConfigField =\n\t| \"config\"\n\t| \"enabled\"\n\t| \"unknown_field\"\n\t| \"coordinatorId\"\n\t| \"issuer\"\n\t| \"clientId\"\n\t| \"clientSecret\"\n\t| \"redirectUri\"\n\t| \"revision\";\n\nexport type CoordinatorBrowserAuthSettings =\n\t| Readonly<{ kind: \"disabled\" }>\n\t| Readonly<{ kind: \"invalid\"; field: CoordinatorBrowserAuthConfigField }>\n\t| Readonly<{\n\t\t\tkind: \"enabled\";\n\t\t\tpublicOrigin: string;\n\t\t\tstore: Readonly<CoordinatorAuthBrowserConfig>;\n\t\t\toidc: Readonly<CoordinatorOidcProviderConfig>;\n\t }>;\n\nconst CONFIG_KEYS = [\n\t\"enabled\",\n\t\"coordinatorId\",\n\t\"issuer\",\n\t\"clientId\",\n\t\"clientSecret\",\n\t\"redirectUri\",\n\t\"revision\",\n] as const;\n\nfunction invalid(field: CoordinatorBrowserAuthConfigField): CoordinatorBrowserAuthSettings {\n\treturn Object.freeze({ kind: \"invalid\", field });\n}\n\nfunction ownDataValue(value: object, key: keyof CoordinatorBrowserAuthConfig): unknown {\n\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\tif (!descriptor || !Object.hasOwn(descriptor, \"value\")) return undefined;\n\treturn descriptor.value;\n}\n\nfunction isCredential(value: unknown, maxLength: number): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length > 0 &&\n\t\tvalue.length <= maxLength &&\n\t\tvalue.trim() === value &&\n\t\t!/[\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(value)\n\t);\n}\n\nfunction redirectOrigin(value: unknown): string | null {\n\tif (typeof value !== \"string\" || value.trim() !== value) return null;\n\tif (/[\\p{Cc}\\p{Cf}\\p{Cs}\\\\?#]/u.test(value)) return null;\n\ttry {\n\t\tconst url = new URL(value);\n\t\tif (url.protocol !== \"https:\" || url.href !== value) return null;\n\t\tif (url.username || url.password || url.search || url.hash) return null;\n\t\treturn url.origin;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction captureEnabled(value: object): CoordinatorBrowserAuthSettings {\n\tconst keys = Reflect.ownKeys(value);\n\tif (keys.some((key) => typeof key !== \"string\" || !CONFIG_KEYS.some((known) => known === key)))\n\t\treturn invalid(\"unknown_field\");\n\tconst coordinatorId = ownDataValue(value, \"coordinatorId\");\n\tconst issuer = ownDataValue(value, \"issuer\");\n\tconst clientId = ownDataValue(value, \"clientId\");\n\tconst clientSecret = ownDataValue(value, \"clientSecret\");\n\tconst redirectUri = ownDataValue(value, \"redirectUri\");\n\tconst revision = ownDataValue(value, \"revision\");\n\tif (!isAuthControllerId(coordinatorId)) return invalid(\"coordinatorId\");\n\tif (issuer !== COORDINATOR_BROWSER_AUTH_ISSUER) return invalid(\"issuer\");\n\tif (!isCredential(clientId, 256)) return invalid(\"clientId\");\n\tif (!isCredential(clientSecret, 4096)) return invalid(\"clientSecret\");\n\tconst publicOrigin = redirectOrigin(redirectUri);\n\tif (typeof redirectUri !== \"string\" || publicOrigin === null) return invalid(\"redirectUri\");\n\tif (typeof revision !== \"string\" || revision.length !== 64 || !/^[a-f0-9]{64}$/.test(revision))\n\t\treturn invalid(\"revision\");\n\treturn Object.freeze({\n\t\tkind: \"enabled\",\n\t\tpublicOrigin,\n\t\tstore: Object.freeze({ enabled: true, coordinatorId, issuer, redirectUri, revision }),\n\t\toidc: Object.freeze({ issuer, clientId, clientSecret, redirectUri }),\n\t});\n}\n\n/** Capture own data descriptors once; getters are never evaluated. Reflection\n * may execute proxy traps, whose exceptions are returned without input details.\n */\nexport function captureCoordinatorBrowserAuthConfig(\n\tvalue: unknown,\n): CoordinatorBrowserAuthSettings {\n\ttry {\n\t\tif (value === undefined) return Object.freeze({ kind: \"disabled\" });\n\t\tif (value === null || typeof value !== \"object\" || Array.isArray(value))\n\t\t\treturn invalid(\"config\");\n\t\tconst prototype = Object.getPrototypeOf(value);\n\t\tif (prototype !== Object.prototype && prototype !== null) return invalid(\"config\");\n\t\tconst enabled = ownDataValue(value, \"enabled\");\n\t\tif (enabled === false) return Object.freeze({ kind: \"disabled\" });\n\t\tif (enabled !== true) return invalid(\"enabled\");\n\t\treturn captureEnabled(value);\n\t} catch {\n\t\treturn invalid(\"config\");\n\t}\n}\n","import { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport { decodeCoordinatorAuthProof32 } from \"./coordinator-auth-proof.js\";\n\nexport const BROWSER_FORM_BODY_MAX_BYTES = 4096;\nexport type BrowserFormAction =\n\t| \"transaction_attempt\"\n\t| \"session_logout\"\n\t| \"signin_start\"\n\t| \"link_start\";\ntype FormInvalid = Readonly<{ ok: false; error: \"form_invalid\" }>;\ntype ReadResult =\n\t| Readonly<{ ok: true; bytes: Uint8Array<ArrayBuffer> }>\n\t| FormInvalid\n\t| Readonly<{ ok: false; error: \"body_too_large\" }>;\ntype ParseResult =\n\t| FormInvalid\n\t| Readonly<{ ok: true; action: \"session_logout\"; csrf: string }>\n\t| Readonly<{ ok: true; action: \"signin_start\"; csrf: string }>\n\t| Readonly<{ ok: true; action: \"link_start\"; csrf: string; attemptId: string; startCode: string }>\n\t| Readonly<{ ok: true; action: \"transaction_attempt\"; csrf: string; attemptId: string }>;\nconst FORM_INVALID: FormInvalid = Object.freeze({ ok: false, error: \"form_invalid\" });\nconst BODY_TOO_LARGE = Object.freeze({ ok: false, error: \"body_too_large\" } as const);\nconst typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);\nconst typedArrayTag = Object.getOwnPropertyDescriptor(typedArrayPrototype, Symbol.toStringTag)?.get;\nconst typedArrayLength = Object.getOwnPropertyDescriptor(typedArrayPrototype, \"byteLength\")?.get;\nconst streamLocked = Object.getOwnPropertyDescriptor(ReadableStream.prototype, \"locked\")?.get;\n\nfunction ownData(input: unknown, key: string): unknown {\n\tif (typeof input !== \"object\" || input === null || Array.isArray(input)) throw FORM_INVALID;\n\tconst descriptor = Object.getOwnPropertyDescriptor(input, key);\n\tif (!descriptor || !Object.hasOwn(descriptor, \"value\")) throw FORM_INVALID;\n\treturn descriptor.value;\n}\n\nfunction declaredLengthError(value: unknown): FormInvalid | typeof BODY_TOO_LARGE | null {\n\tif (value === null || value === undefined) return null;\n\tif (typeof value !== \"string\" || value.length < 1 || value.length > 10) return FORM_INVALID;\n\t// Keep the final character explicitly within the declared-length grammar.\n\tif (!/^[0-9]+$/.test(value) || !/^[0-9]$/.test(value.slice(-1))) return FORM_INVALID;\n\tif (Number(value) > BROWSER_FORM_BODY_MAX_BYTES) return BODY_TOO_LARGE;\n\treturn null;\n}\n\nfunction nativeByteLength(value: unknown): number {\n\tif (typedArrayTag?.call(value) !== \"Uint8Array\") throw FORM_INVALID;\n\tconst length: unknown = typedArrayLength?.call(value);\n\tif (typeof length !== \"number\") throw FORM_INVALID;\n\treturn length;\n}\n\nfunction cancelReader(reader: ReadableStreamDefaultReader<Uint8Array>): void {\n\ttry {\n\t\t// Untrusted teardown can outlive this call; never wait for its completion.\n\t\tvoid ReadableStreamDefaultReader.prototype.cancel.call(reader).catch(() => {});\n\t} catch {\n\t\t// Cleanup cannot replace the fixed public error.\n\t}\n}\n\nasync function collectBytes(reader: ReadableStreamDefaultReader<Uint8Array>): Promise<ReadResult> {\n\ttry {\n\t\t// One owned allocation bounds storage, even with thousands of tiny chunks.\n\t\tconst bytes = new Uint8Array(BROWSER_FORM_BODY_MAX_BYTES);\n\t\tlet total = 0;\n\t\tfor (;;) {\n\t\t\tconst chunk = await ReadableStreamDefaultReader.prototype.read.call(reader);\n\t\t\tif (chunk.done) return Object.freeze({ ok: true, bytes: bytes.subarray(0, total) });\n\t\t\tconst length = nativeByteLength(chunk.value);\n\t\t\tif (length > BROWSER_FORM_BODY_MAX_BYTES - total) {\n\t\t\t\tcancelReader(reader);\n\t\t\t\treturn BODY_TOO_LARGE;\n\t\t\t}\n\t\t\t// Copy before the next read can let a producer reuse or mutate its buffer.\n\t\t\tUint8Array.prototype.set.call(bytes, chunk.value, total);\n\t\t\ttotal += length;\n\t\t}\n\t} catch {\n\t\tcancelReader(reader);\n\t\treturn FORM_INVALID;\n\t} finally {\n\t\ttry {\n\t\t\tReadableStreamDefaultReader.prototype.releaseLock.call(reader);\n\t\t} catch {\n\t\t\t// A failed release must not reject the caller's promise.\n\t\t}\n\t}\n}\n\n/** Byte limits only. Slow-sender deadlines must be enforced by the transport. */\nexport async function readBrowserFormBody(input: {\n\tbody: ReadableStream<Uint8Array> | null;\n\tcontentLength: unknown;\n}): Promise<ReadResult> {\n\ttry {\n\t\tconst body = ownData(input, \"body\");\n\t\tconst error = declaredLengthError(ownData(input, \"contentLength\"));\n\t\tif (error) return error;\n\t\tif (body === null || streamLocked?.call(body) !== false) return FORM_INVALID;\n\t\t// Fetch body extraction rejects disturbed streams without reading them.\n\t\tnew Response(body as ReadableStream<Uint8Array>);\n\t\tconst reader = ReadableStream.prototype.getReader.call(\n\t\t\tbody,\n\t\t) as ReadableStreamDefaultReader<Uint8Array>;\n\t\treturn await collectBytes(reader);\n\t} catch {\n\t\treturn FORM_INVALID;\n\t}\n}\n\nfunction decodeRawBody(bytes: Uint8Array): string {\n\tconst length = nativeByteLength(bytes);\n\tif (length === 0 || length > BROWSER_FORM_BODY_MAX_BYTES) throw FORM_INVALID;\n\t// Preserve BOM so the ASCII grammar rejects it instead of silently stripping it.\n\tconst raw = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(bytes);\n\tif (\n\t\traw.length > BROWSER_FORM_BODY_MAX_BYTES ||\n\t\t!/^[A-Za-z0-9*._%+=&-]+$/.test(raw) ||\n\t\t!/^[A-Za-z0-9*._%+=&-]+$/.test(raw.slice(-1))\n\t) {\n\t\tthrow FORM_INVALID;\n\t}\n\treturn raw;\n}\n\nfunction decodeFields(raw: string, action: BrowserFormAction): Readonly<Record<string, string>> {\n\tconst fields: Record<string, string> = Object.create(null);\n\tfor (const segment of raw.split(\"&\")) {\n\t\tconst equals = segment.indexOf(\"=\");\n\t\tif (equals < 1 || equals !== segment.lastIndexOf(\"=\")) throw FORM_INVALID;\n\t\tconst key = decodeURIComponent(segment.slice(0, equals).replaceAll(\"+\", \" \"));\n\t\tconst attemptField =\n\t\t\tkey === \"attempt_id\" && (action === \"transaction_attempt\" || action === \"link_start\");\n\t\tconst startField = key === \"start_code\" && action === \"link_start\";\n\t\tif (key !== \"csrf\" && !attemptField && !startField) {\n\t\t\tthrow FORM_INVALID;\n\t\t}\n\t\tif (Object.hasOwn(fields, key)) throw FORM_INVALID;\n\t\tfields[key] = decodeURIComponent(segment.slice(equals + 1).replaceAll(\"+\", \" \"));\n\t}\n\treturn Object.freeze(fields);\n}\n\n/** Grammar and field checks only; this does not authenticate CSRF or an attempt. */\nexport function parseBrowserFormBody(bytes: Uint8Array, action: BrowserFormAction): ParseResult {\n\ttry {\n\t\tif (\n\t\t\taction !== \"session_logout\" &&\n\t\t\taction !== \"transaction_attempt\" &&\n\t\t\taction !== \"signin_start\" &&\n\t\t\taction !== \"link_start\"\n\t\t)\n\t\t\treturn FORM_INVALID;\n\t\tconst fields = decodeFields(decodeRawBody(bytes), action);\n\t\tif (!Object.hasOwn(fields, \"csrf\")) return FORM_INVALID;\n\t\tconst csrf = fields.csrf;\n\t\tif (typeof csrf !== \"string\") return FORM_INVALID;\n\t\tif (action === \"session_logout\" || action === \"signin_start\") {\n\t\t\treturn Object.freeze({ ok: true, action, csrf });\n\t\t}\n\t\tconst attemptId = fields.attempt_id;\n\t\tif (!isAuthControllerId(attemptId)) return FORM_INVALID;\n\t\tif (action === \"link_start\") {\n\t\t\tconst startCode = fields.start_code;\n\t\t\tif (typeof startCode !== \"string\" || !decodeCoordinatorAuthProof32(startCode))\n\t\t\t\treturn FORM_INVALID;\n\t\t\treturn Object.freeze({ ok: true, action, csrf, attemptId, startCode });\n\t\t}\n\t\treturn Object.freeze({ ok: true, action, csrf, attemptId });\n\t} catch {\n\t\treturn FORM_INVALID;\n\t}\n}\n","import { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport { type CookieKind, readBrowserCookie } from \"./coordinator-browser-credential.js\";\nimport {\n\ttype BrowserCsrfKey,\n\ttype BrowserCsrfScope,\n\tisBrowserCsrfToken,\n\tverifyBrowserCsrfToken,\n} from \"./coordinator-browser-csrf.js\";\nimport {\n\tBROWSER_FORM_BODY_MAX_BYTES,\n\ttype BrowserFormAction,\n\tparseBrowserFormBody,\n\treadBrowserFormBody,\n} from \"./coordinator-browser-form-body.js\";\nimport type { InMemoryRequestRateLimiter } from \"./request-rate-limit.js\";\n\nexport const BROWSER_FORM_REJECTIONS = Object.freeze([\n\t\"invalid_input\",\n\t\"method_not_allowed\",\n\t\"client_unidentified\",\n\t\"rate_limited\",\n\t\"origin_rejected\",\n\t\"unsupported_media_type\",\n\t\"body_too_large\",\n\t\"form_invalid\",\n\t\"cookie_missing\",\n\t\"cookie_invalid\",\n\t\"csrf_invalid\",\n] as const);\ntype Rejection = (typeof BROWSER_FORM_REJECTIONS)[number];\ntype Failure = Readonly<{ ok: false; error: Rejection; retryAfterS?: number }>;\nexport type BrowserFormGuardResult =\n\t| Readonly<{ ok: true; action: \"session_logout\"; cookieHash: string }>\n\t| Readonly<{ ok: true; action: \"signin_start\"; cookieHash: string }>\n\t| Readonly<{\n\t\t\tok: true;\n\t\t\taction: \"link_start\";\n\t\t\tcookieHash: string;\n\t\t\tattemptId: string;\n\t\t\tstartCode: string;\n\t }>\n\t| Readonly<{ ok: true; action: \"transaction_attempt\"; cookieHash: string; attemptId: string }>\n\t| Failure;\nexport interface BrowserFormGuardInput {\n\trequest: Request;\n\tscope: BrowserCsrfScope;\n\tcsrfKey: BrowserCsrfKey;\n\taction: BrowserFormAction;\n\tlimiter: InMemoryRequestRateLimiter;\n\tclientKey: string;\n\tlimit?: number;\n}\nconst INVALID_INPUT: Failure = Object.freeze({ ok: false, error: \"invalid_input\" });\nconst ACTION_COOKIE_KINDS: Readonly<Record<BrowserFormAction, CookieKind>> = Object.freeze({\n\ttransaction_attempt: \"transaction\",\n\tsession_logout: \"session\",\n\tsignin_start: \"start\",\n\tlink_start: \"start\",\n});\nconst ratePolicies = new WeakMap<InMemoryRequestRateLimiter, Map<string, number>>();\nconst setupAdmission = Symbol(\"browser-auth-setup-admission\");\n/** Setup may spend the handler's token, but only this exact Request can redeem it once. */\nexport function checkBrowserAuthRequestRate(\n\trequest: Request,\n\tlimiter: InMemoryRequestRateLimiter,\n\tkey: string,\n\tlimit: number,\n\toptions: { admitSetup?: boolean; check?: InMemoryRequestRateLimiter[\"check\"] } = {},\n) {\n\tconst admission = Object.getOwnPropertyDescriptor(request, setupAdmission)?.value;\n\tif (\n\t\t!options.admitSetup &&\n\t\tadmission?.limiter === limiter &&\n\t\tadmission.key === key &&\n\t\tadmission.limit === limit\n\t) {\n\t\tReflect.deleteProperty(request, setupAdmission);\n\t\treturn { allowed: true, retryAfterS: 0 };\n\t}\n\tconst result = (options.check ?? limiter.check).call(limiter, key, limit);\n\tif (options.admitSetup && result.allowed)\n\t\tObject.defineProperty(request, setupAdmission, {\n\t\t\tvalue: { limiter, key, limit },\n\t\t\tconfigurable: true,\n\t\t});\n\treturn result;\n}\n\nexport function admitBrowserFormSetup(input: BrowserFormGuardInput): Failure | null {\n\ttry {\n\t\tconst snapshot = captureInput(input);\n\t\treturn checkOrigin(snapshot) ?? checkRate(snapshot, { admitSetup: true });\n\t} catch {\n\t\treturn INVALID_INPUT;\n\t}\n}\nconst headersGet = Headers.prototype.get;\nfunction nativeRequestGetter(name: string): ((this: Request) => unknown) | undefined {\n\tlet prototype: object | null = Request.prototype;\n\twhile (prototype !== null) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(prototype, name);\n\t\tif (descriptor) return descriptor.get;\n\t\tprototype = Object.getPrototypeOf(prototype);\n\t}\n\treturn undefined;\n}\nconst requestGetters = Object.freeze({\n\tmethod: nativeRequestGetter(\"method\"),\n\turl: nativeRequestGetter(\"url\"),\n\theaders: nativeRequestGetter(\"headers\"),\n\tbody: nativeRequestGetter(\"body\"),\n});\ntype Snapshot = Readonly<{\n\trequest: Request;\n\tscope: BrowserCsrfScope;\n\tcsrfKey: BrowserCsrfKey;\n\taction: BrowserFormAction;\n\tkind: CookieKind;\n\tlimiter: InMemoryRequestRateLimiter;\n\tcheck: InMemoryRequestRateLimiter[\"check\"];\n\tclientKey: unknown;\n\tlimit: unknown;\n\tmethod: string;\n\turl: string;\n\torigin: string | null;\n\tmediaType: string | null;\n\tcontentLength: string | null;\n\tcookie: string | null;\n\tbody: ReadableStream<Uint8Array> | null;\n}>;\n\nfunction reject(error: Rejection): Failure {\n\treturn Object.freeze({ ok: false, error });\n}\n\nfunction ownData(value: unknown, name: string): unknown {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) throw INVALID_INPUT;\n\tconst descriptor = Object.getOwnPropertyDescriptor(value, name);\n\tif (!descriptor || !Object.hasOwn(descriptor, \"value\")) throw INVALID_INPUT;\n\treturn descriptor.value;\n}\n\nfunction captureScope(value: unknown): BrowserCsrfScope {\n\tconst publicOrigin = ownData(value, \"publicOrigin\");\n\tconst store = ownData(value, \"store\");\n\tconst coordinatorId = ownData(store, \"coordinatorId\");\n\tconst revision = ownData(store, \"revision\");\n\tif (typeof publicOrigin !== \"string\" || /[\\\\\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(publicOrigin)) {\n\t\tthrow INVALID_INPUT;\n\t}\n\tconst url = new URL(publicOrigin);\n\tif (url.protocol !== \"https:\" || url.origin !== publicOrigin || url.username || url.password) {\n\t\tthrow INVALID_INPUT;\n\t}\n\tif (\n\t\t!isAuthControllerId(coordinatorId) ||\n\t\ttypeof revision !== \"string\" ||\n\t\trevision.length !== 64 ||\n\t\t!/^[a-f0-9]{64}$/.test(revision)\n\t)\n\t\tthrow INVALID_INPUT;\n\treturn Object.freeze({ publicOrigin, store: Object.freeze({ coordinatorId, revision }) });\n}\n\nfunction captureCheck(value: unknown): InMemoryRequestRateLimiter[\"check\"] {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) throw INVALID_INPUT;\n\tconst seen = new Set<object>();\n\tlet cursor: object | null = value;\n\twhile (cursor !== null) {\n\t\tif (seen.has(cursor)) throw INVALID_INPUT;\n\t\tseen.add(cursor);\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(cursor, \"check\");\n\t\tif (descriptor) {\n\t\t\tif (!Object.hasOwn(descriptor, \"value\") || typeof descriptor.value !== \"function\") {\n\t\t\t\tthrow INVALID_INPUT;\n\t\t\t}\n\t\t\treturn descriptor.value;\n\t\t}\n\t\tcursor = Object.getPrototypeOf(cursor);\n\t}\n\tthrow INVALID_INPUT;\n}\n\nfunction captureInput(input: BrowserFormGuardInput): Snapshot {\n\tconst request = ownData(input, \"request\");\n\tconst scope = captureScope(ownData(input, \"scope\"));\n\tconst csrfKey = ownData(input, \"csrfKey\") as BrowserCsrfKey;\n\tconst action = ownData(input, \"action\");\n\tconst limiter = ownData(input, \"limiter\");\n\tconst check = captureCheck(limiter);\n\tconst clientKey = ownData(input, \"clientKey\");\n\tconst limitDescriptor = Object.getOwnPropertyDescriptor(input, \"limit\");\n\tif (limitDescriptor && !Object.hasOwn(limitDescriptor, \"value\")) throw INVALID_INPUT;\n\tconst suppliedLimit: unknown = limitDescriptor?.value;\n\tconst limit = suppliedLimit === undefined ? 20 : suppliedLimit;\n\tif (\n\t\t!(request instanceof Request) ||\n\t\t(action !== \"session_logout\" &&\n\t\t\taction !== \"transaction_attempt\" &&\n\t\t\taction !== \"signin_start\" &&\n\t\t\taction !== \"link_start\")\n\t) {\n\t\tthrow INVALID_INPUT;\n\t}\n\t// Native getters enforce the Request brand and ignore caller-owned overrides.\n\tconst method: unknown = requestGetters.method?.call(request);\n\tconst url: unknown = requestGetters.url?.call(request);\n\tconst headers = requestGetters.headers?.call(request) as Headers;\n\tconst body = requestGetters.body?.call(request) as ReadableStream<Uint8Array> | null;\n\tif (typeof method !== \"string\" || typeof url !== \"string\") throw INVALID_INPUT;\n\treturn Object.freeze({\n\t\trequest,\n\t\tscope,\n\t\tcsrfKey,\n\t\taction,\n\t\tkind: ACTION_COOKIE_KINDS[action],\n\t\tlimiter: limiter as InMemoryRequestRateLimiter,\n\t\tcheck,\n\t\tclientKey,\n\t\tlimit,\n\t\tmethod,\n\t\turl,\n\t\tbody,\n\t\torigin: headersGet.call(headers, \"origin\"),\n\t\tmediaType: headersGet.call(headers, \"content-type\"),\n\t\tcontentLength: headersGet.call(headers, \"content-length\"),\n\t\tcookie: headersGet.call(headers, \"cookie\"),\n\t});\n}\n\nfunction pinRatePolicy(snapshot: Snapshot, limit: number): boolean {\n\tlet policies = ratePolicies.get(snapshot.limiter);\n\tif (!policies) {\n\t\tpolicies = new Map();\n\t\tratePolicies.set(snapshot.limiter, policies);\n\t}\n\tconst coordinatorId = snapshot.scope.store.coordinatorId;\n\tconst existing = policies.get(coordinatorId);\n\tif (existing !== undefined) return existing === limit;\n\tpolicies.set(coordinatorId, limit);\n\treturn true;\n}\n\nfunction checkRate(snapshot: Snapshot, options: { admitSetup?: boolean } = {}): Failure | null {\n\tconst { clientKey, limit } = snapshot;\n\tif (!isAuthControllerId(clientKey) || clientKey.length > 128) {\n\t\treturn reject(\"client_unidentified\");\n\t}\n\tif (typeof limit !== \"number\" || !Number.isSafeInteger(limit) || limit < 1 || limit > 1000) {\n\t\treturn INVALID_INPUT;\n\t}\n\t// The injected limiter includes the limit in its internal bucket key.\n\tif (!pinRatePolicy(snapshot, limit)) return INVALID_INPUT;\n\tconst result: unknown = checkBrowserAuthRequestRate(\n\t\tsnapshot.request,\n\t\tsnapshot.limiter,\n\t\tJSON.stringify([\"browser-form\", snapshot.scope.store.coordinatorId, clientKey]),\n\t\tlimit,\n\t\t{ ...options, check: snapshot.check },\n\t);\n\tconst allowed = ownData(result, \"allowed\");\n\tconst retryAfterS = ownData(result, \"retryAfterS\");\n\tif (\n\t\ttypeof allowed !== \"boolean\" ||\n\t\ttypeof retryAfterS !== \"number\" ||\n\t\t!Number.isFinite(retryAfterS)\n\t)\n\t\treturn INVALID_INPUT;\n\tif (allowed === true) {\n\t\treturn Number.isSafeInteger(retryAfterS) && retryAfterS >= 0 ? null : INVALID_INPUT;\n\t}\n\treturn Object.freeze({\n\t\tok: false,\n\t\terror: \"rate_limited\",\n\t\tretryAfterS: Math.max(1, Math.min(3600, Math.ceil(retryAfterS))),\n\t});\n}\n\nfunction validMediaType(value: string | null): boolean {\n\tif (value === null || /[^\\x20-\\x7e\\t]/.test(value)) return false;\n\tconst parts = value.toLowerCase().split(\";\");\n\tif (parts.length > 2 || parts[0]?.trim() !== \"application/x-www-form-urlencoded\") return false;\n\tif (parts.length === 1) return true;\n\tconst charset = parts[1]?.split(\"=\");\n\treturn (\n\t\tcharset?.length === 2 && charset[0]?.trim() === \"charset\" && charset[1]?.trim() === \"utf-8\"\n\t);\n}\n\nfunction checkOrigin(snapshot: Snapshot): Failure | null {\n\tif (\n\t\tnew URL(snapshot.url).origin !== snapshot.scope.publicOrigin ||\n\t\tsnapshot.origin !== snapshot.scope.publicOrigin\n\t)\n\t\treturn reject(\"origin_rejected\");\n\treturn null;\n}\n\nfunction checkMediaAndLength(snapshot: Snapshot): Failure | null {\n\tif (!validMediaType(snapshot.mediaType)) return reject(\"unsupported_media_type\");\n\tconst length = snapshot.contentLength;\n\tif (length === null) return null;\n\tif (\n\t\tlength.length < 1 ||\n\t\tlength.length > 10 ||\n\t\t!/^[0-9]+$/.test(length) ||\n\t\t!/^[0-9]$/.test(length.slice(-1))\n\t)\n\t\treturn reject(\"form_invalid\");\n\tif (Number(length) > BROWSER_FORM_BODY_MAX_BYTES) return reject(\"body_too_large\");\n\treturn null;\n}\n\nasync function verifyForm(snapshot: Snapshot): Promise<BrowserFormGuardResult> {\n\tlet cookie: Awaited<ReturnType<typeof readBrowserCookie>>;\n\ttry {\n\t\tcookie = await readBrowserCookie(snapshot.cookie, snapshot.kind);\n\t} catch {\n\t\treturn reject(\"cookie_invalid\");\n\t}\n\tif (cookie.kind === \"absent\") return reject(\"cookie_missing\");\n\tif (cookie.kind !== \"present\") return reject(\"cookie_invalid\");\n\tconst body = await readBrowserFormBody({\n\t\tbody: snapshot.body,\n\t\tcontentLength: snapshot.contentLength,\n\t});\n\tif (!body.ok) return reject(body.error);\n\tconst form = parseBrowserFormBody(body.bytes, snapshot.action);\n\tif (!form.ok) return reject(form.error);\n\tif (\n\t\t!isBrowserCsrfToken(form.csrf) ||\n\t\t!(await verifyBrowserCsrfToken(\n\t\t\tsnapshot.csrfKey,\n\t\t\tcookie.secret,\n\t\t\tsnapshot.kind,\n\t\t\tsnapshot.scope,\n\t\t\tform.csrf,\n\t\t))\n\t)\n\t\treturn reject(\"csrf_invalid\");\n\tif (form.action === \"session_logout\" || form.action === \"signin_start\") {\n\t\treturn Object.freeze({ ok: true, action: form.action, cookieHash: cookie.cookieHash });\n\t}\n\tif (form.action === \"link_start\") {\n\t\treturn Object.freeze({\n\t\t\tok: true,\n\t\t\taction: form.action,\n\t\t\tcookieHash: cookie.cookieHash,\n\t\t\tattemptId: form.attemptId,\n\t\t\tstartCode: form.startCode,\n\t\t});\n\t}\n\treturn Object.freeze({\n\t\tok: true,\n\t\taction: form.action,\n\t\tcookieHash: cookie.cookieHash,\n\t\tattemptId: form.attemptId,\n\t});\n}\n\n/** Unmounted transport guard, not authentication. Require a live store lookup afterwards.\n * cookieHash is sensitive internal data, never an HTTP response or log DTO.\n * Supply server-owned scope, an imported CSRF key, and trusted platform client identity.\n */\nexport async function guardBrowserForm(\n\tinput: BrowserFormGuardInput,\n): Promise<BrowserFormGuardResult> {\n\ttry {\n\t\tconst snapshot = captureInput(input);\n\t\tif (snapshot.method !== \"POST\") return reject(\"method_not_allowed\");\n\t\tconst originError = checkOrigin(snapshot);\n\t\tif (originError) return originError;\n\t\tconst rateError = checkRate(snapshot);\n\t\tif (rateError) return rateError;\n\t\tconst headerError = checkMediaAndLength(snapshot);\n\t\tif (headerError) return headerError;\n\t\treturn await verifyForm(snapshot);\n\t} catch {\n\t\treturn INVALID_INPUT;\n\t}\n}\n","function nativeRequestGetter(name: string): ((this: Request) => unknown) | undefined {\n\tlet prototype: object | null = Request.prototype;\n\twhile (prototype !== null) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(prototype, name);\n\t\tif (descriptor) return descriptor.get;\n\t\tprototype = Object.getPrototypeOf(prototype);\n\t}\n\treturn undefined;\n}\nconst requestGetters = Object.freeze({\n\tmethod: nativeRequestGetter(\"method\"),\n\turl: nativeRequestGetter(\"url\"),\n\theaders: nativeRequestGetter(\"headers\"),\n});\nconst headersGet = Headers.prototype.get;\nexport function snapshotBrowserRoute(request: Request) {\n\tconst method = requestGetters.method?.call(request);\n\tconst url = requestGetters.url?.call(request);\n\tif (typeof method !== \"string\" || typeof url !== \"string\") throw new Error();\n\treturn Object.freeze({ method, url });\n}\n\nexport function snapshotBrowserRequest(request: Request) {\n\tconst route = snapshotBrowserRoute(request);\n\tconst headers = requestGetters.headers?.call(request) as Headers;\n\treturn Object.freeze({ ...route, cookie: headersGet.call(headers, \"cookie\") });\n}\n","import type {\n\tCoordinatorAuthBrowserConfig,\n\tCoordinatorAuthBrowserTransactionStore,\n} from \"./coordinator-auth-browser-transaction-contract.js\";\nimport { readBrowserCookie } from \"./coordinator-browser-credential.js\";\n\ntype ActivityStore = Pick<\n\tCoordinatorAuthBrowserTransactionStore,\n\t\"readAuthBrowserTransactionActivity\"\n>;\n\n/** Invalid credentials and config drift deny restart; lookup faults reach the handler's catch. */\nexport async function readBrowserStartTransaction(\n\tcookie: unknown,\n\tstore: ActivityStore,\n\tconfig: CoordinatorAuthBrowserConfig,\n): Promise<\"absent\" | \"invalid\" | \"active\" | \"inactive\"> {\n\tconst transaction = await readBrowserCookie(cookie, \"transaction\");\n\tif (transaction.kind !== \"present\") return transaction.kind;\n\tconst activity = await store.readAuthBrowserTransactionActivity(\n\t\t{ binderHash: transaction.cookieHash },\n\t\tconfig,\n\t);\n\tif (activity.kind === \"rejected\") return \"invalid\";\n\treturn activity.kind;\n}\n","let USER_AGENT;\nif (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {\n const NAME = 'oauth4webapi';\n const VERSION = 'v3.8.8';\n USER_AGENT = `${NAME}/${VERSION}`;\n}\nfunction looseInstanceOf(input, expected) {\n if (input == null) {\n return false;\n }\n try {\n return (input instanceof expected ||\n Object.getPrototypeOf(input)[Symbol.toStringTag] === expected.prototype[Symbol.toStringTag]);\n }\n catch {\n return false;\n }\n}\nconst ERR_INVALID_ARG_VALUE = 'ERR_INVALID_ARG_VALUE';\nconst ERR_INVALID_ARG_TYPE = 'ERR_INVALID_ARG_TYPE';\nfunction CodedTypeError(message, code, cause) {\n const err = new TypeError(message, { cause });\n Object.assign(err, { code });\n return err;\n}\nexport const allowInsecureRequests = Symbol();\nexport const clockSkew = Symbol();\nexport const clockTolerance = Symbol();\nexport const customFetch = Symbol();\nexport const modifyAssertion = Symbol();\nexport const jweDecrypt = Symbol();\nexport const jwksCache = Symbol();\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\nfunction buf(input) {\n if (typeof input === 'string') {\n return encoder.encode(input);\n }\n return decoder.decode(input);\n}\nlet encodeBase64Url;\nif (Uint8Array.prototype.toBase64) {\n encodeBase64Url = (input) => {\n if (input instanceof ArrayBuffer) {\n input = new Uint8Array(input);\n }\n return input.toBase64({ alphabet: 'base64url', omitPadding: true });\n };\n}\nelse {\n const CHUNK_SIZE = 0x8000;\n encodeBase64Url = (input) => {\n if (input instanceof ArrayBuffer) {\n input = new Uint8Array(input);\n }\n const arr = [];\n for (let i = 0; i < input.byteLength; i += CHUNK_SIZE) {\n arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));\n }\n return btoa(arr.join('')).replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\n };\n}\nlet decodeBase64Url;\nif (Uint8Array.fromBase64) {\n decodeBase64Url = (input) => {\n try {\n return Uint8Array.fromBase64(input, { alphabet: 'base64url' });\n }\n catch (cause) {\n throw CodedTypeError('The input to be decoded is not correctly encoded.', ERR_INVALID_ARG_VALUE, cause);\n }\n };\n}\nelse {\n decodeBase64Url = (input) => {\n try {\n const binary = atob(input.replace(/-/g, '+').replace(/_/g, '/').replace(/\\s/g, ''));\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n }\n catch (cause) {\n throw CodedTypeError('The input to be decoded is not correctly encoded.', ERR_INVALID_ARG_VALUE, cause);\n }\n };\n}\nfunction b64u(input) {\n if (typeof input === 'string') {\n return decodeBase64Url(input);\n }\n return encodeBase64Url(input);\n}\nexport class UnsupportedOperationError extends Error {\n code;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n this.code = UNSUPPORTED_OPERATION;\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nexport class OperationProcessingError extends Error {\n code;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n if (options?.code) {\n this.code = options?.code;\n }\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nfunction OPE(message, code, cause) {\n return new OperationProcessingError(message, { code, cause });\n}\nasync function calculateJwkThumbprint(jwk) {\n let components;\n switch (jwk.kty) {\n case 'EC':\n components = {\n crv: jwk.crv,\n kty: jwk.kty,\n x: jwk.x,\n y: jwk.y,\n };\n break;\n case 'OKP':\n components = {\n crv: jwk.crv,\n kty: jwk.kty,\n x: jwk.x,\n };\n break;\n case 'AKP':\n components = {\n alg: jwk.alg,\n kty: jwk.kty,\n pub: jwk.pub,\n };\n break;\n case 'RSA':\n components = {\n e: jwk.e,\n kty: jwk.kty,\n n: jwk.n,\n };\n break;\n default:\n throw new UnsupportedOperationError('unsupported JWK key type', { cause: jwk });\n }\n return b64u(await crypto.subtle.digest('SHA-256', buf(JSON.stringify(components))));\n}\nfunction assertCryptoKey(key, it) {\n if (!(key instanceof CryptoKey)) {\n throw CodedTypeError(`${it} must be a CryptoKey`, ERR_INVALID_ARG_TYPE);\n }\n}\nfunction assertPrivateKey(key, it) {\n assertCryptoKey(key, it);\n if (key.type !== 'private') {\n throw CodedTypeError(`${it} must be a private CryptoKey`, ERR_INVALID_ARG_VALUE);\n }\n}\nfunction assertPublicKey(key, it) {\n assertCryptoKey(key, it);\n if (key.type !== 'public') {\n throw CodedTypeError(`${it} must be a public CryptoKey`, ERR_INVALID_ARG_VALUE);\n }\n}\nfunction normalizeTyp(value) {\n return value.toLowerCase().replace(/^application\\//, '');\n}\nfunction isJsonObject(input) {\n if (input === null || typeof input !== 'object' || Array.isArray(input)) {\n return false;\n }\n return true;\n}\nfunction prepareHeaders(input) {\n if (looseInstanceOf(input, Headers)) {\n input = Object.fromEntries(input.entries());\n }\n const headers = new Headers(input ?? {});\n if (USER_AGENT && !headers.has('user-agent')) {\n headers.set('user-agent', USER_AGENT);\n }\n if (headers.has('authorization')) {\n throw CodedTypeError('\"options.headers\" must not include the \"authorization\" header name', ERR_INVALID_ARG_VALUE);\n }\n return headers;\n}\nfunction signal(url, value) {\n if (value !== undefined) {\n if (typeof value === 'function') {\n value = value(url.href);\n }\n if (!(value instanceof AbortSignal)) {\n throw CodedTypeError('\"options.signal\" must return or be an instance of AbortSignal', ERR_INVALID_ARG_TYPE);\n }\n return value;\n }\n return undefined;\n}\nfunction replaceDoubleSlash(pathname) {\n if (pathname.includes('//')) {\n return pathname.replace('//', '/');\n }\n return pathname;\n}\nfunction prependWellKnown(url, wellKnown, allowTerminatingSlash = false) {\n if (url.pathname === '/') {\n url.pathname = wellKnown;\n }\n else {\n url.pathname = replaceDoubleSlash(`${wellKnown}/${allowTerminatingSlash ? url.pathname : url.pathname.replace(/(\\/)$/, '')}`);\n }\n return url;\n}\nfunction appendWellKnown(url, wellKnown) {\n url.pathname = replaceDoubleSlash(`${url.pathname}/${wellKnown}`);\n return url;\n}\nasync function performDiscovery(input, urlName, transform, options) {\n if (!(input instanceof URL)) {\n throw CodedTypeError(`\"${urlName}\" must be an instance of URL`, ERR_INVALID_ARG_TYPE);\n }\n checkProtocol(input, options?.[allowInsecureRequests] !== true);\n const url = transform(new URL(input.href));\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n return (options?.[customFetch] || fetch)(url.href, {\n body: undefined,\n headers: Object.fromEntries(headers.entries()),\n method: 'GET',\n redirect: 'manual',\n signal: signal(url, options?.signal),\n });\n}\nexport async function discoveryRequest(issuerIdentifier, options) {\n return performDiscovery(issuerIdentifier, 'issuerIdentifier', (url) => {\n switch (options?.algorithm) {\n case undefined:\n case 'oidc':\n appendWellKnown(url, '.well-known/openid-configuration');\n break;\n case 'oauth2':\n prependWellKnown(url, '.well-known/oauth-authorization-server');\n break;\n default:\n throw CodedTypeError('\"options.algorithm\" must be \"oidc\" (default), or \"oauth2\"', ERR_INVALID_ARG_VALUE);\n }\n return url;\n }, options);\n}\nfunction assertNumber(input, allow0, it, code, cause) {\n try {\n if (typeof input !== 'number' || !Number.isFinite(input)) {\n throw CodedTypeError(`${it} must be a number`, ERR_INVALID_ARG_TYPE, cause);\n }\n if (input > 0)\n return;\n if (allow0) {\n if (input !== 0) {\n throw CodedTypeError(`${it} must be a non-negative number`, ERR_INVALID_ARG_VALUE, cause);\n }\n return;\n }\n throw CodedTypeError(`${it} must be a positive number`, ERR_INVALID_ARG_VALUE, cause);\n }\n catch (err) {\n if (code) {\n throw OPE(err.message, code, cause);\n }\n throw err;\n }\n}\nfunction assertString(input, it, code, cause) {\n try {\n if (typeof input !== 'string') {\n throw CodedTypeError(`${it} must be a string`, ERR_INVALID_ARG_TYPE, cause);\n }\n if (input.length === 0) {\n throw CodedTypeError(`${it} must not be empty`, ERR_INVALID_ARG_VALUE, cause);\n }\n }\n catch (err) {\n if (code) {\n throw OPE(err.message, code, cause);\n }\n throw err;\n }\n}\nexport async function processDiscoveryResponse(expectedIssuerIdentifier, response) {\n const expected = expectedIssuerIdentifier;\n if (!(expected instanceof URL) && expected !== _nodiscoverycheck) {\n throw CodedTypeError('\"expectedIssuerIdentifier\" must be an instance of URL', ERR_INVALID_ARG_TYPE);\n }\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n if (response.status !== 200) {\n throw OPE('\"response\" is not a conform Authorization Server Metadata response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);\n }\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.issuer, '\"response\" body \"issuer\" property', INVALID_RESPONSE, { body: json });\n if (expected !== _nodiscoverycheck && new URL(json.issuer).href !== expected.href) {\n throw OPE('\"response\" body \"issuer\" property does not match the expected value', JSON_ATTRIBUTE_COMPARISON, { expected: expected.href, body: json, attribute: 'issuer' });\n }\n return json;\n}\nfunction assertApplicationJson(response) {\n assertContentType(response, 'application/json');\n}\nfunction notJson(response, ...types) {\n let msg = '\"response\" content-type must be ';\n if (types.length > 2) {\n const last = types.pop();\n msg += `${types.join(', ')}, or ${last}`;\n }\n else if (types.length === 2) {\n msg += `${types[0]} or ${types[1]}`;\n }\n else {\n msg += types[0];\n }\n return OPE(msg, RESPONSE_IS_NOT_JSON, response);\n}\nfunction assertContentTypes(response, ...types) {\n if (!types.includes(getContentType(response))) {\n throw notJson(response, ...types);\n }\n}\nfunction assertContentType(response, contentType) {\n if (getContentType(response) !== contentType) {\n throw notJson(response, contentType);\n }\n}\nfunction randomBytes() {\n return b64u(crypto.getRandomValues(new Uint8Array(32)));\n}\nexport function generateRandomCodeVerifier() {\n return randomBytes();\n}\nexport function generateRandomState() {\n return randomBytes();\n}\nexport function generateRandomNonce() {\n return randomBytes();\n}\nexport async function calculatePKCECodeChallenge(codeVerifier) {\n assertString(codeVerifier, 'codeVerifier');\n return b64u(await crypto.subtle.digest('SHA-256', buf(codeVerifier)));\n}\nfunction getKeyAndKid(input) {\n if (input instanceof CryptoKey) {\n return { key: input };\n }\n if (!(input?.key instanceof CryptoKey)) {\n return {};\n }\n if (input.kid !== undefined) {\n assertString(input.kid, '\"kid\"');\n }\n return {\n key: input.key,\n kid: input.kid,\n };\n}\nfunction psAlg(key) {\n switch (key.algorithm.hash.name) {\n case 'SHA-256':\n return 'PS256';\n case 'SHA-384':\n return 'PS384';\n case 'SHA-512':\n return 'PS512';\n default:\n throw new UnsupportedOperationError('unsupported RsaHashedKeyAlgorithm hash name', {\n cause: key,\n });\n }\n}\nfunction rsAlg(key) {\n switch (key.algorithm.hash.name) {\n case 'SHA-256':\n return 'RS256';\n case 'SHA-384':\n return 'RS384';\n case 'SHA-512':\n return 'RS512';\n default:\n throw new UnsupportedOperationError('unsupported RsaHashedKeyAlgorithm hash name', {\n cause: key,\n });\n }\n}\nfunction esAlg(key) {\n switch (key.algorithm.namedCurve) {\n case 'P-256':\n return 'ES256';\n case 'P-384':\n return 'ES384';\n case 'P-521':\n return 'ES512';\n default:\n throw new UnsupportedOperationError('unsupported EcKeyAlgorithm namedCurve', { cause: key });\n }\n}\nfunction keyToJws(key) {\n switch (key.algorithm.name) {\n case 'RSA-PSS':\n return psAlg(key);\n case 'RSASSA-PKCS1-v1_5':\n return rsAlg(key);\n case 'ECDSA':\n return esAlg(key);\n case 'Ed25519':\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n return key.algorithm.name;\n case 'EdDSA':\n return 'Ed25519';\n default:\n throw new UnsupportedOperationError('unsupported CryptoKey algorithm name', { cause: key });\n }\n}\nfunction getClockSkew(client) {\n const skew = client?.[clockSkew];\n return typeof skew === 'number' && Number.isFinite(skew) ? skew : 0;\n}\nfunction getClockTolerance(client) {\n const tolerance = client?.[clockTolerance];\n return typeof tolerance === 'number' && Number.isFinite(tolerance) && Math.sign(tolerance) !== -1\n ? tolerance\n : 30;\n}\nfunction epochTime() {\n return Math.floor(Date.now() / 1000);\n}\nfunction assertAs(as) {\n if (typeof as !== 'object' || as === null) {\n throw CodedTypeError('\"as\" must be an object', ERR_INVALID_ARG_TYPE);\n }\n assertString(as.issuer, '\"as.issuer\"');\n}\nfunction assertClient(client) {\n if (typeof client !== 'object' || client === null) {\n throw CodedTypeError('\"client\" must be an object', ERR_INVALID_ARG_TYPE);\n }\n assertString(client.client_id, '\"client.client_id\"');\n}\nfunction formUrlEncode(token) {\n return encodeURIComponent(token).replace(/(?:[-_.!~*'()]|%20)/g, (substring) => {\n switch (substring) {\n case '-':\n case '_':\n case '.':\n case '!':\n case '~':\n case '*':\n case \"'\":\n case '(':\n case ')':\n return `%${substring.charCodeAt(0).toString(16).toUpperCase()}`;\n case '%20':\n return '+';\n default:\n throw new Error();\n }\n });\n}\nexport function ClientSecretPost(clientSecret) {\n assertString(clientSecret, '\"clientSecret\"');\n return (_as, client, body, _headers) => {\n body.set('client_id', client.client_id);\n body.set('client_secret', clientSecret);\n };\n}\nexport function ClientSecretBasic(clientSecret) {\n assertString(clientSecret, '\"clientSecret\"');\n return (_as, client, _body, headers) => {\n const username = formUrlEncode(client.client_id);\n const password = formUrlEncode(clientSecret);\n const credentials = btoa(`${username}:${password}`);\n headers.set('authorization', `Basic ${credentials}`);\n };\n}\nfunction clientAssertionPayload(as, client) {\n const now = epochTime() + getClockSkew(client);\n return {\n jti: randomBytes(),\n aud: as.issuer,\n exp: now + 60,\n iat: now,\n nbf: now,\n iss: client.client_id,\n sub: client.client_id,\n };\n}\nexport function PrivateKeyJwt(clientPrivateKey, options) {\n const { key, kid } = getKeyAndKid(clientPrivateKey);\n assertPrivateKey(key, '\"clientPrivateKey.key\"');\n return async (as, client, body, _headers) => {\n const header = { alg: keyToJws(key), kid };\n const payload = clientAssertionPayload(as, client);\n options?.[modifyAssertion]?.(header, payload);\n body.set('client_id', client.client_id);\n body.set('client_assertion_type', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer');\n body.set('client_assertion', await signJwt(header, payload, key));\n };\n}\nexport function ClientSecretJwt(clientSecret, options) {\n assertString(clientSecret, '\"clientSecret\"');\n const modify = options?.[modifyAssertion];\n let key;\n return async (as, client, body, _headers) => {\n key ||= await crypto.subtle.importKey('raw', buf(clientSecret), { hash: 'SHA-256', name: 'HMAC' }, false, ['sign']);\n const header = { alg: 'HS256' };\n const payload = clientAssertionPayload(as, client);\n modify?.(header, payload);\n const data = `${b64u(buf(JSON.stringify(header)))}.${b64u(buf(JSON.stringify(payload)))}`;\n const hmac = await crypto.subtle.sign(key.algorithm, key, buf(data));\n body.set('client_id', client.client_id);\n body.set('client_assertion_type', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer');\n body.set('client_assertion', `${data}.${b64u(new Uint8Array(hmac))}`);\n };\n}\nexport function None() {\n return (_as, client, body, _headers) => {\n body.set('client_id', client.client_id);\n };\n}\nexport function TlsClientAuth() {\n return None();\n}\nasync function signJwt(header, payload, key) {\n if (!key.usages.includes('sign')) {\n throw CodedTypeError('CryptoKey instances used for signing assertions must include \"sign\" in their \"usages\"', ERR_INVALID_ARG_VALUE);\n }\n const input = `${b64u(buf(JSON.stringify(header)))}.${b64u(buf(JSON.stringify(payload)))}`;\n const signature = b64u(await crypto.subtle.sign(keyToSubtle(key), key, buf(input)));\n return `${input}.${signature}`;\n}\nexport async function issueRequestObject(as, client, parameters, privateKey, options) {\n assertAs(as);\n assertClient(client);\n parameters = new URLSearchParams(parameters);\n const { key, kid } = getKeyAndKid(privateKey);\n assertPrivateKey(key, '\"privateKey.key\"');\n parameters.set('client_id', client.client_id);\n const now = epochTime() + getClockSkew(client);\n const claims = {\n ...Object.fromEntries(parameters.entries()),\n jti: randomBytes(),\n aud: as.issuer,\n exp: now + 60,\n iat: now,\n nbf: now,\n iss: client.client_id,\n };\n let resource;\n if (parameters.has('resource') &&\n (resource = parameters.getAll('resource')) &&\n resource.length > 1) {\n claims.resource = resource;\n }\n {\n let value = parameters.get('max_age');\n if (value !== null) {\n claims.max_age = parseInt(value, 10);\n assertNumber(claims.max_age, true, '\"max_age\" parameter');\n }\n }\n {\n let value = parameters.get('claims');\n if (value !== null) {\n try {\n claims.claims = JSON.parse(value);\n }\n catch (cause) {\n throw OPE('failed to parse the \"claims\" parameter as JSON', PARSE_ERROR, cause);\n }\n if (!isJsonObject(claims.claims)) {\n throw CodedTypeError('\"claims\" parameter must be a JSON with a top level object', ERR_INVALID_ARG_VALUE);\n }\n }\n }\n {\n let value = parameters.get('authorization_details');\n if (value !== null) {\n try {\n claims.authorization_details = JSON.parse(value);\n }\n catch (cause) {\n throw OPE('failed to parse the \"authorization_details\" parameter as JSON', PARSE_ERROR, cause);\n }\n if (!Array.isArray(claims.authorization_details)) {\n throw CodedTypeError('\"authorization_details\" parameter must be a JSON with a top level array', ERR_INVALID_ARG_VALUE);\n }\n }\n }\n const header = {\n alg: keyToJws(key),\n typ: 'oauth-authz-req+jwt',\n kid,\n };\n options?.[modifyAssertion]?.(header, claims);\n return signJwt(header, claims, key);\n}\nlet jwkCache;\nasync function getSetPublicJwkCache(key, alg) {\n const { kty, e, n, x, y, crv, pub } = await crypto.subtle.exportKey('jwk', key);\n const jwk = { kty, e, n, x, y, crv, pub };\n if (kty === 'AKP')\n jwk.alg = alg;\n jwkCache.set(key, jwk);\n return jwk;\n}\nasync function publicJwk(key, alg) {\n jwkCache ||= new WeakMap();\n return jwkCache.get(key) || getSetPublicJwkCache(key, alg);\n}\nconst URLParse = URL.parse\n ?\n (url, base) => URL.parse(url, base)\n : (url, base) => {\n try {\n return new URL(url, base);\n }\n catch {\n return null;\n }\n };\nexport function checkProtocol(url, enforceHttps) {\n if (enforceHttps && url.protocol !== 'https:') {\n throw OPE('only requests to HTTPS are allowed', HTTP_REQUEST_FORBIDDEN, url);\n }\n if (url.protocol !== 'https:' && url.protocol !== 'http:') {\n throw OPE('only HTTP and HTTPS requests are allowed', REQUEST_PROTOCOL_FORBIDDEN, url);\n }\n}\nfunction validateEndpoint(value, endpoint, useMtlsAlias, enforceHttps) {\n let url;\n if (typeof value !== 'string' || !(url = URLParse(value))) {\n throw OPE(`authorization server metadata does not contain a valid ${useMtlsAlias ? `\"as.mtls_endpoint_aliases.${endpoint}\"` : `\"as.${endpoint}\"`}`, value === undefined ? MISSING_SERVER_METADATA : INVALID_SERVER_METADATA, { attribute: useMtlsAlias ? `mtls_endpoint_aliases.${endpoint}` : endpoint });\n }\n checkProtocol(url, enforceHttps);\n return url;\n}\nexport function resolveEndpoint(as, endpoint, useMtlsAlias, enforceHttps) {\n if (useMtlsAlias && as.mtls_endpoint_aliases && endpoint in as.mtls_endpoint_aliases) {\n return validateEndpoint(as.mtls_endpoint_aliases[endpoint], endpoint, useMtlsAlias, enforceHttps);\n }\n return validateEndpoint(as[endpoint], endpoint, useMtlsAlias, enforceHttps);\n}\nexport async function pushedAuthorizationRequest(as, client, clientAuthentication, parameters, options) {\n assertAs(as);\n assertClient(client);\n const url = resolveEndpoint(as, 'pushed_authorization_request_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const body = new URLSearchParams(parameters);\n body.set('client_id', client.client_id);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n if (options?.DPoP !== undefined) {\n assertDPoP(options.DPoP);\n await options.DPoP.addProof(url, headers, 'POST');\n }\n const response = await authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);\n options?.DPoP?.cacheNonce(response, url);\n return response;\n}\nclass DPoPHandler {\n #header;\n #privateKey;\n #publicKey;\n #clockSkew;\n #modifyAssertion;\n #map;\n #jkt;\n constructor(client, keyPair, options) {\n assertPrivateKey(keyPair?.privateKey, '\"DPoP.privateKey\"');\n assertPublicKey(keyPair?.publicKey, '\"DPoP.publicKey\"');\n if (!keyPair.publicKey.extractable) {\n throw CodedTypeError('\"DPoP.publicKey.extractable\" must be true', ERR_INVALID_ARG_VALUE);\n }\n this.#modifyAssertion = options?.[modifyAssertion];\n this.#clockSkew = getClockSkew(client);\n this.#privateKey = keyPair.privateKey;\n this.#publicKey = keyPair.publicKey;\n branded.add(this);\n }\n #get(key) {\n this.#map ||= new Map();\n let item = this.#map.get(key);\n if (item) {\n this.#map.delete(key);\n this.#map.set(key, item);\n }\n return item;\n }\n #set(key, val) {\n this.#map ||= new Map();\n this.#map.delete(key);\n if (this.#map.size === 100) {\n this.#map.delete(this.#map.keys().next().value);\n }\n this.#map.set(key, val);\n }\n async calculateThumbprint() {\n if (!this.#jkt) {\n const jwk = await crypto.subtle.exportKey('jwk', this.#publicKey);\n this.#jkt ||= await calculateJwkThumbprint(jwk);\n }\n return this.#jkt;\n }\n async addProof(url, headers, htm, accessToken) {\n const alg = keyToJws(this.#privateKey);\n this.#header ||= {\n alg,\n typ: 'dpop+jwt',\n jwk: await publicJwk(this.#publicKey, alg),\n };\n const nonce = this.#get(url.origin);\n const now = epochTime() + this.#clockSkew;\n const payload = {\n iat: now,\n jti: randomBytes(),\n htm,\n nonce,\n htu: `${url.origin}${url.pathname}`,\n ath: accessToken\n ? b64u(await crypto.subtle.digest('SHA-256', buf(accessToken)))\n : undefined,\n };\n this.#modifyAssertion?.(this.#header, payload);\n headers.set('dpop', await signJwt(this.#header, payload, this.#privateKey));\n }\n cacheNonce(response, url) {\n try {\n const nonce = response.headers.get('dpop-nonce');\n if (nonce) {\n this.#set(url.origin, nonce);\n }\n }\n catch { }\n }\n}\nexport function isDPoPNonceError(err) {\n if (err instanceof WWWAuthenticateChallengeError) {\n return err.cause.some((challenge) => challenge.scheme === 'dpop' && challenge.parameters.error === 'use_dpop_nonce');\n }\n if (err instanceof ResponseBodyError) {\n return err.error === 'use_dpop_nonce';\n }\n return false;\n}\nexport function DPoP(client, keyPair, options) {\n return new DPoPHandler(client, keyPair, options);\n}\nexport class ResponseBodyError extends Error {\n cause;\n code;\n error;\n status;\n error_description;\n response;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n this.code = RESPONSE_BODY_ERROR;\n this.cause = options.cause;\n this.error = options.cause.error;\n this.status = options.response.status;\n this.error_description = options.cause.error_description;\n Object.defineProperty(this, 'response', { enumerable: false, value: options.response });\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nexport class AuthorizationResponseError extends Error {\n cause;\n code;\n error;\n error_description;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n this.code = AUTHORIZATION_RESPONSE_ERROR;\n this.cause = options.cause;\n this.error = options.cause.get('error');\n this.error_description = options.cause.get('error_description') ?? undefined;\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nexport class WWWAuthenticateChallengeError extends Error {\n cause;\n code;\n response;\n status;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n this.code = WWW_AUTHENTICATE_CHALLENGE;\n this.cause = options.cause;\n this.status = options.response.status;\n this.response = options.response;\n Object.defineProperty(this, 'response', { enumerable: false });\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nconst tokenMatch = \"[a-zA-Z0-9!#$%&\\\\'\\\\*\\\\+\\\\-\\\\.\\\\^_`\\\\|~]+\";\nconst token68Match = '[a-zA-Z0-9\\\\-\\\\._\\\\~\\\\+\\\\/]+={0,2}';\nconst quotedMatch = '\"((?:[^\"\\\\\\\\]|\\\\\\\\[\\\\s\\\\S])*)\"';\nconst quotedParamMatcher = '(' + tokenMatch + ')\\\\s*=\\\\s*' + quotedMatch;\nconst paramMatcher = '(' + tokenMatch + ')\\\\s*=\\\\s*(' + tokenMatch + ')';\nconst schemeRE = new RegExp('^[,\\\\s]*(' + tokenMatch + ')');\nconst quotedParamRE = new RegExp('^[,\\\\s]*' + quotedParamMatcher + '[,\\\\s]*(.*)');\nconst unquotedParamRE = new RegExp('^[,\\\\s]*' + paramMatcher + '[,\\\\s]*(.*)');\nconst token68ParamRE = new RegExp('^(' + token68Match + ')(?:$|[,\\\\s])(.*)');\nfunction parseWwwAuthenticateChallenges(response) {\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n const header = response.headers.get('www-authenticate');\n if (header === null) {\n return undefined;\n }\n const challenges = [];\n let rest = header;\n while (rest) {\n let match = rest.match(schemeRE);\n const scheme = match?.['1'].toLowerCase();\n if (!scheme) {\n return undefined;\n }\n const afterScheme = rest.substring(match[0].length);\n if (afterScheme && !afterScheme.match(/^[\\s,]/)) {\n return undefined;\n }\n const spaceMatch = afterScheme.match(/^\\s+(.*)$/);\n const hasParameters = !!spaceMatch;\n rest = spaceMatch ? spaceMatch[1] : undefined;\n const parameters = {};\n let token68;\n if (hasParameters) {\n while (rest) {\n let key;\n let value;\n if ((match = rest.match(quotedParamRE))) {\n ;\n [, key, value, rest] = match;\n if (value.includes('\\\\')) {\n value = value.replace(/\\\\([\\s\\S])/g, '$1');\n }\n parameters[key.toLowerCase()] = value;\n continue;\n }\n if ((match = rest.match(unquotedParamRE))) {\n ;\n [, key, value, rest] = match;\n parameters[key.toLowerCase()] = value;\n continue;\n }\n if ((match = rest.match(token68ParamRE))) {\n if (Object.keys(parameters).length) {\n break;\n }\n ;\n [, token68, rest] = match;\n break;\n }\n return undefined;\n }\n }\n else {\n rest = afterScheme || undefined;\n }\n const challenge = { scheme, parameters };\n if (token68) {\n challenge.token68 = token68;\n }\n challenges.push(challenge);\n }\n if (!challenges.length) {\n return undefined;\n }\n return challenges;\n}\nexport async function processPushedAuthorizationResponse(as, client, response) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 201, 'Pushed Authorization Request Endpoint');\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.request_uri, '\"response\" body \"request_uri\" property', INVALID_RESPONSE, {\n body: json,\n });\n let expiresIn = typeof json.expires_in !== 'number' ? parseFloat(json.expires_in) : json.expires_in;\n assertNumber(expiresIn, true, '\"response\" body \"expires_in\" property', INVALID_RESPONSE, {\n body: json,\n });\n json.expires_in = expiresIn;\n return json;\n}\nasync function parseOAuthResponseErrorBody(response) {\n if (response.status > 399 && response.status < 500) {\n assertReadableResponse(response);\n assertApplicationJson(response);\n try {\n const json = await response.clone().json();\n if (isJsonObject(json) && typeof json.error === 'string' && json.error.length) {\n return json;\n }\n }\n catch { }\n }\n return undefined;\n}\nasync function checkOAuthBodyError(response, expected, label) {\n if (response.status !== expected) {\n checkAuthenticationChallenges(response);\n let err;\n if ((err = await parseOAuthResponseErrorBody(response))) {\n await response.body?.cancel();\n throw new ResponseBodyError('server responded with an error in the response body', {\n cause: err,\n response,\n });\n }\n throw OPE(`\"response\" is not a conform ${label} response (unexpected HTTP status code)`, RESPONSE_IS_NOT_CONFORM, response);\n }\n}\nfunction assertDPoP(option) {\n if (!branded.has(option)) {\n throw CodedTypeError('\"options.DPoP\" is not a valid DPoPHandle', ERR_INVALID_ARG_VALUE);\n }\n}\nasync function resourceRequest(accessToken, method, url, headers, body, options) {\n assertString(accessToken, '\"accessToken\"');\n if (!(url instanceof URL)) {\n throw CodedTypeError('\"url\" must be an instance of URL', ERR_INVALID_ARG_TYPE);\n }\n checkProtocol(url, options?.[allowInsecureRequests] !== true);\n headers = prepareHeaders(headers);\n if (options?.DPoP) {\n assertDPoP(options.DPoP);\n await options.DPoP.addProof(url, headers, method.toUpperCase(), accessToken);\n }\n headers.set('authorization', `${headers.has('dpop') ? 'DPoP' : 'Bearer'} ${accessToken}`);\n const response = await (options?.[customFetch] || fetch)(url.href, {\n duplex: looseInstanceOf(body, ReadableStream) ? 'half' : undefined,\n body,\n headers: Object.fromEntries(headers.entries()),\n method,\n redirect: 'manual',\n signal: signal(url, options?.signal),\n });\n options?.DPoP?.cacheNonce(response, url);\n return response;\n}\nexport async function protectedResourceRequest(accessToken, method, url, headers, body, options) {\n const response = await resourceRequest(accessToken, method, url, headers, body, options);\n checkAuthenticationChallenges(response);\n return response;\n}\nexport async function userInfoRequest(as, client, accessToken, options) {\n assertAs(as);\n assertClient(client);\n const url = resolveEndpoint(as, 'userinfo_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const headers = prepareHeaders(options?.headers);\n if (client.userinfo_signed_response_alg) {\n headers.set('accept', 'application/jwt');\n }\n else {\n headers.set('accept', 'application/json');\n headers.append('accept', 'application/jwt');\n }\n return resourceRequest(accessToken, 'GET', url, headers, null, {\n ...options,\n [clockSkew]: getClockSkew(client),\n });\n}\nlet jwksMap;\nlet jwksRequests;\nlet jwksKeys;\nfunction setJwksCache(as, jwks, uat, cache) {\n jwksMap ||= new WeakMap();\n jwksMap.set(as, {\n jwks,\n uat,\n get age() {\n return epochTime() - this.uat;\n },\n });\n if (cache) {\n Object.assign(cache, { jwks: structuredClone(jwks), uat });\n }\n}\nfunction isFreshJwksCache(input) {\n if (typeof input !== 'object' || input === null) {\n return false;\n }\n if (!('uat' in input) || typeof input.uat !== 'number' || epochTime() - input.uat >= 300) {\n return false;\n }\n if (!('jwks' in input) ||\n !isJsonObject(input.jwks) ||\n !Array.isArray(input.jwks.keys) ||\n !Array.prototype.every.call(input.jwks.keys, isJsonObject)) {\n return false;\n }\n return true;\n}\nfunction clearJwksCache(as, cache) {\n jwksMap?.delete(as);\n delete cache?.jwks;\n delete cache?.uat;\n}\nasync function getPublicSigKeyFromIssuerJwksUri(as, options, header) {\n const { alg, kid } = header;\n checkSupportedJwsAlg(header);\n if (!jwksMap?.has(as) && isFreshJwksCache(options?.[jwksCache])) {\n setJwksCache(as, options?.[jwksCache].jwks, options?.[jwksCache].uat);\n }\n let jwks;\n let age;\n if (jwksMap?.has(as)) {\n ;\n ({ jwks, age } = jwksMap.get(as));\n if (age >= 300) {\n clearJwksCache(as, options?.[jwksCache]);\n return getPublicSigKeyFromIssuerJwksUri(as, options, header);\n }\n }\n else {\n const downloaded = await jwksRequest(as, options);\n jwks = downloaded.jwks;\n age = epochTime() - downloaded.uat;\n setJwksCache(as, jwks, downloaded.uat, options?.[jwksCache]);\n }\n let kty;\n switch (alg.slice(0, 2)) {\n case 'RS':\n case 'PS':\n kty = 'RSA';\n break;\n case 'ES':\n kty = 'EC';\n break;\n case 'Ed':\n kty = 'OKP';\n break;\n case 'ML':\n kty = 'AKP';\n break;\n default:\n throw new UnsupportedOperationError('unsupported JWS algorithm', { cause: { alg } });\n }\n const candidates = jwks.keys.filter((jwk) => {\n if (jwk.kty !== kty) {\n return false;\n }\n if (kid !== undefined && kid !== jwk.kid) {\n return false;\n }\n if (jwk.alg !== undefined && alg !== jwk.alg) {\n return false;\n }\n if (jwk.use !== undefined && jwk.use !== 'sig') {\n return false;\n }\n if (jwk.key_ops?.includes('verify') === false) {\n return false;\n }\n switch (true) {\n case alg === 'ES256' && jwk.crv !== 'P-256':\n case alg === 'ES384' && jwk.crv !== 'P-384':\n case alg === 'ES512' && jwk.crv !== 'P-521':\n case alg === 'Ed25519' && jwk.crv !== 'Ed25519':\n case alg === 'EdDSA' && jwk.crv !== 'Ed25519':\n return false;\n }\n return true;\n });\n const { 0: jwk, length } = candidates;\n if (!length) {\n if (age >= 60) {\n clearJwksCache(as, options?.[jwksCache]);\n return getPublicSigKeyFromIssuerJwksUri(as, options, header);\n }\n throw OPE('error when selecting a JWT verification key, no applicable keys found', KEY_SELECTION, { header, candidates, jwks_uri: new URL(as.jwks_uri) });\n }\n if (length !== 1) {\n throw OPE('error when selecting a JWT verification key, multiple applicable keys found, a \"kid\" JWT Header Parameter is required', KEY_SELECTION, { header, candidates, jwks_uri: new URL(as.jwks_uri) });\n }\n jwksKeys ||= new WeakMap();\n let keys = jwksKeys.get(jwk);\n if (!keys) {\n keys = new Map();\n jwksKeys.set(jwk, keys);\n }\n let key = keys.get(alg);\n if (!key) {\n key = importJwk(alg, jwk).catch((cause) => {\n keys.delete(alg);\n throw cause;\n });\n keys.set(alg, key);\n }\n return key;\n}\nexport const skipSubjectCheck = Symbol();\nexport function getContentType(input) {\n return input.headers.get('content-type')?.split(';')[0];\n}\nexport async function processUserInfoResponse(as, client, expectedSubject, response, options) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n checkAuthenticationChallenges(response);\n if (response.status !== 200) {\n throw OPE('\"response\" is not a conform UserInfo Endpoint response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);\n }\n assertReadableResponse(response);\n let json;\n if (getContentType(response) === 'application/jwt') {\n const { claims, jwt } = await validateJwt(await response.text(), checkSigningAlgorithm.bind(undefined, client.userinfo_signed_response_alg, as.userinfo_signing_alg_values_supported, undefined), getClockSkew(client), getClockTolerance(client), options?.[jweDecrypt])\n .then(validateOptionalAudience.bind(undefined, client.client_id))\n .then(validateOptionalIssuer.bind(undefined, as));\n jwtRefs.set(response, jwt);\n json = claims;\n }\n else {\n if (client.userinfo_signed_response_alg) {\n throw OPE('JWT UserInfo Response expected', JWT_USERINFO_EXPECTED, response);\n }\n json = await getResponseJsonBody(response);\n }\n assertString(json.sub, '\"response\" body \"sub\" property', INVALID_RESPONSE, { body: json });\n switch (expectedSubject) {\n case skipSubjectCheck:\n break;\n default:\n assertString(expectedSubject, '\"expectedSubject\"');\n if (json.sub !== expectedSubject) {\n throw OPE('unexpected \"response\" body \"sub\" property value', JSON_ATTRIBUTE_COMPARISON, {\n expected: expectedSubject,\n body: json,\n attribute: 'sub',\n });\n }\n }\n return json;\n}\nasync function authenticatedRequest(as, client, clientAuthentication, url, body, headers, options) {\n await clientAuthentication(as, client, body, headers);\n headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');\n return (options?.[customFetch] || fetch)(url.href, {\n body,\n headers: Object.fromEntries(headers.entries()),\n method: 'POST',\n redirect: 'manual',\n signal: signal(url, options?.signal),\n });\n}\nasync function tokenEndpointRequest(as, client, clientAuthentication, grantType, parameters, options) {\n const url = resolveEndpoint(as, 'token_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n parameters.set('grant_type', grantType);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n if (options?.DPoP !== undefined) {\n assertDPoP(options.DPoP);\n await options.DPoP.addProof(url, headers, 'POST');\n }\n const response = await authenticatedRequest(as, client, clientAuthentication, url, parameters, headers, options);\n options?.DPoP?.cacheNonce(response, url);\n return response;\n}\nexport async function refreshTokenGrantRequest(as, client, clientAuthentication, refreshToken, options) {\n assertAs(as);\n assertClient(client);\n assertString(refreshToken, '\"refreshToken\"');\n const parameters = new URLSearchParams(options?.additionalParameters);\n parameters.set('refresh_token', refreshToken);\n return tokenEndpointRequest(as, client, clientAuthentication, 'refresh_token', parameters, options);\n}\nconst idTokenClaims = new WeakMap();\nconst jwtRefs = new WeakMap();\nexport function getValidatedIdTokenClaims(ref) {\n if (!ref.id_token) {\n return undefined;\n }\n const claims = idTokenClaims.get(ref);\n if (!claims) {\n throw CodedTypeError('\"ref\" was already garbage collected or did not resolve from the proper sources', ERR_INVALID_ARG_VALUE);\n }\n return claims;\n}\nexport async function validateApplicationLevelSignature(as, ref, options) {\n assertAs(as);\n if (!jwtRefs.has(ref)) {\n throw CodedTypeError('\"ref\" does not contain a processed JWT Response to verify the signature of', ERR_INVALID_ARG_VALUE);\n }\n const { 0: protectedHeader, 1: payload, 2: encodedSignature } = jwtRefs.get(ref).split('.');\n const header = JSON.parse(buf(b64u(protectedHeader)));\n if (header.alg.startsWith('HS')) {\n throw new UnsupportedOperationError('unsupported JWS algorithm', { cause: { alg: header.alg } });\n }\n let key;\n key = await getPublicSigKeyFromIssuerJwksUri(as, options, header);\n await validateJwsSignature(protectedHeader, payload, key, b64u(encodedSignature));\n}\nasync function processGenericAccessTokenResponse(as, client, response, additionalRequiredIdTokenClaims, decryptFn, recognizedTokenTypes) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 200, 'Token Endpoint');\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.access_token, '\"response\" body \"access_token\" property', INVALID_RESPONSE, {\n body: json,\n });\n assertString(json.token_type, '\"response\" body \"token_type\" property', INVALID_RESPONSE, {\n body: json,\n });\n json.token_type = json.token_type.toLowerCase();\n if (json.expires_in !== undefined) {\n let expiresIn = typeof json.expires_in !== 'number' ? parseFloat(json.expires_in) : json.expires_in;\n assertNumber(expiresIn, true, '\"response\" body \"expires_in\" property', INVALID_RESPONSE, {\n body: json,\n });\n json.expires_in = expiresIn;\n }\n if (json.refresh_token !== undefined) {\n assertString(json.refresh_token, '\"response\" body \"refresh_token\" property', INVALID_RESPONSE, {\n body: json,\n });\n }\n if (json.scope !== undefined && typeof json.scope !== 'string') {\n throw OPE('\"response\" body \"scope\" property must be a string', INVALID_RESPONSE, { body: json });\n }\n if (json.id_token !== undefined) {\n assertString(json.id_token, '\"response\" body \"id_token\" property', INVALID_RESPONSE, {\n body: json,\n });\n const requiredClaims = [];\n if (client.require_auth_time === true) {\n requiredClaims.push('auth_time');\n }\n if (client.default_max_age !== undefined) {\n assertNumber(client.default_max_age, true, '\"client.default_max_age\"');\n requiredClaims.push('auth_time');\n }\n if (additionalRequiredIdTokenClaims?.length) {\n requiredClaims.push(...additionalRequiredIdTokenClaims);\n }\n const { claims, jwt } = await validateIdTokenClaims(as, client, json.id_token, requiredClaims, decryptFn);\n validateIdTokenAuthorizedParty(client, claims);\n validateIdTokenAuthTimeClaim(claims);\n jwtRefs.set(response, jwt);\n idTokenClaims.set(json, claims);\n }\n if (recognizedTokenTypes?.[json.token_type] !== undefined) {\n recognizedTokenTypes[json.token_type](response, json);\n }\n else if (json.token_type !== 'dpop' && json.token_type !== 'bearer') {\n throw new UnsupportedOperationError('unsupported `token_type` value', { cause: { body: json } });\n }\n return json;\n}\nfunction checkAuthenticationChallenges(response) {\n let challenges;\n if ((challenges = parseWwwAuthenticateChallenges(response))) {\n throw new WWWAuthenticateChallengeError('server responded with a challenge in the WWW-Authenticate HTTP Header', { cause: challenges, response });\n }\n}\nexport async function processRefreshTokenResponse(as, client, response, options) {\n return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nfunction validateOptionalAudience(expected, result) {\n if (result.claims.aud !== undefined) {\n return validateAudience(expected, result);\n }\n return result;\n}\nfunction validateAudience(expected, result) {\n if (Array.isArray(result.claims.aud)) {\n if (!result.claims.aud.includes(expected)) {\n throw OPE('unexpected JWT \"aud\" (audience) claim value', JWT_CLAIM_COMPARISON, {\n expected,\n claims: result.claims,\n claim: 'aud',\n });\n }\n }\n else if (result.claims.aud !== expected) {\n throw OPE('unexpected JWT \"aud\" (audience) claim value', JWT_CLAIM_COMPARISON, {\n expected,\n claims: result.claims,\n claim: 'aud',\n });\n }\n return result;\n}\nfunction validateOptionalIssuer(as, result) {\n if (result.claims.iss !== undefined) {\n return validateIssuer(as, result);\n }\n return result;\n}\nfunction validateIssuer(as, result) {\n const expected = as[_expectedIssuer]?.(result) ?? as.issuer;\n if (result.claims.iss !== expected) {\n throw OPE('unexpected JWT \"iss\" (issuer) claim value', JWT_CLAIM_COMPARISON, {\n expected,\n claims: result.claims,\n claim: 'iss',\n });\n }\n return result;\n}\nconst branded = new WeakSet();\nfunction brand(searchParams) {\n branded.add(searchParams);\n return searchParams;\n}\nexport const nopkce = Symbol();\nexport async function authorizationCodeGrantRequest(as, client, clientAuthentication, callbackParameters, redirectUri, codeVerifier, options) {\n assertAs(as);\n assertClient(client);\n if (!branded.has(callbackParameters)) {\n throw CodedTypeError('\"callbackParameters\" must be an instance of URLSearchParams obtained from \"validateAuthResponse()\", or \"validateJwtAuthResponse()', ERR_INVALID_ARG_VALUE);\n }\n assertString(redirectUri, '\"redirectUri\"');\n const code = getURLSearchParameter(callbackParameters, 'code');\n if (!code) {\n throw OPE('no authorization code in \"callbackParameters\"', INVALID_RESPONSE);\n }\n const parameters = new URLSearchParams(options?.additionalParameters);\n parameters.set('redirect_uri', redirectUri);\n parameters.set('code', code);\n if (codeVerifier !== nopkce) {\n assertString(codeVerifier, '\"codeVerifier\"');\n parameters.set('code_verifier', codeVerifier);\n }\n return tokenEndpointRequest(as, client, clientAuthentication, 'authorization_code', parameters, options);\n}\nconst jwtClaimNames = {\n aud: 'audience',\n c_hash: 'code hash',\n client_id: 'client id',\n exp: 'expiration time',\n iat: 'issued at',\n iss: 'issuer',\n jti: 'jwt id',\n nonce: 'nonce',\n s_hash: 'state hash',\n sub: 'subject',\n ath: 'access token hash',\n htm: 'http method',\n htu: 'http uri',\n cnf: 'confirmation',\n auth_time: 'authentication time',\n};\nfunction validatePresence(required, result) {\n for (const claim of required) {\n if (result.claims[claim] === undefined) {\n throw OPE(`JWT \"${claim}\" (${jwtClaimNames[claim]}) claim missing`, INVALID_RESPONSE, {\n claims: result.claims,\n });\n }\n }\n return result;\n}\nfunction validateStringClaim(claim, result) {\n if (typeof result.claims[claim] !== 'string') {\n throw OPE(`unexpected JWT \"${claim}\" (${jwtClaimNames[claim]}) claim type`, INVALID_RESPONSE, {\n claims: result.claims,\n });\n }\n return result;\n}\nfunction validateIdTokenClaims(as, client, idToken, requiredClaims, decryptFn) {\n return validateJwt(idToken, checkSigningAlgorithm.bind(undefined, client.id_token_signed_response_alg, as.id_token_signing_alg_values_supported, 'RS256'), getClockSkew(client), getClockTolerance(client), decryptFn)\n .then(validatePresence.bind(undefined, ['aud', 'exp', 'iat', 'iss', 'sub', ...requiredClaims]))\n .then(validateIssuer.bind(undefined, as))\n .then(validateAudience.bind(undefined, client.client_id))\n .then(validateStringClaim.bind(undefined, 'sub'));\n}\nfunction resolveIdTokenMaxAge(client, maxAge) {\n if (maxAge === skipAuthTimeCheck) {\n return maxAge;\n }\n const fromClient = maxAge === undefined;\n if (fromClient) {\n maxAge = client.default_max_age;\n }\n if (maxAge === undefined) {\n return skipAuthTimeCheck;\n }\n assertNumber(maxAge, true, fromClient ? '\"client.default_max_age\"' : '\"maxAge\" argument');\n return maxAge;\n}\nfunction validateIdTokenAuthTimeClaim(claims) {\n if (claims.auth_time !== undefined) {\n assertNumber(claims.auth_time, true, 'ID Token \"auth_time\" (authentication time)', INVALID_RESPONSE, { claims });\n }\n}\nfunction validateIdTokenAuthTime(client, claims, maxAge) {\n if (maxAge === skipAuthTimeCheck) {\n return;\n }\n const now = epochTime() + getClockSkew(client);\n const tolerance = getClockTolerance(client);\n if (claims.auth_time + maxAge < now - tolerance) {\n throw OPE('too much time has elapsed since the last End-User authentication', JWT_TIMESTAMP_CHECK, { claims, now, tolerance, claim: 'auth_time' });\n }\n}\nfunction validateIdTokenNonce(claims, expectedNonce) {\n const expected = expectedNonce === expectNoNonce ? undefined : expectedNonce;\n if (claims.nonce !== expected) {\n throw OPE('unexpected ID Token \"nonce\" claim value', JWT_CLAIM_COMPARISON, {\n expected,\n claims,\n claim: 'nonce',\n });\n }\n}\nfunction validateIdTokenAuthorizedParty(client, claims) {\n if (Array.isArray(claims.aud) && claims.aud.length !== 1) {\n if (claims.azp === undefined) {\n throw OPE('ID Token \"aud\" (audience) claim includes additional untrusted audiences', JWT_CLAIM_COMPARISON, { claims, claim: 'aud' });\n }\n if (claims.azp !== client.client_id) {\n throw OPE('unexpected ID Token \"azp\" (authorized party) claim value', JWT_CLAIM_COMPARISON, {\n expected: client.client_id,\n claims,\n claim: 'azp',\n });\n }\n }\n}\nexport const expectNoNonce = Symbol();\nexport const skipAuthTimeCheck = Symbol();\nexport async function processAuthorizationCodeResponse(as, client, response, options) {\n if (typeof options?.expectedNonce === 'string' ||\n typeof options?.maxAge === 'number' ||\n options?.requireIdToken) {\n return processAuthorizationCodeOpenIDResponse(as, client, response, options.expectedNonce, options.maxAge, options[jweDecrypt], options.recognizedTokenTypes);\n }\n return processAuthorizationCodeOAuth2Response(as, client, response, options?.maxAge, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nasync function processAuthorizationCodeOpenIDResponse(as, client, response, expectedNonce, maxAge, decryptFn, recognizedTokenTypes) {\n const additionalRequiredClaims = [];\n switch (expectedNonce) {\n case undefined:\n expectedNonce = expectNoNonce;\n break;\n case expectNoNonce:\n break;\n default:\n assertString(expectedNonce, '\"expectedNonce\" argument');\n additionalRequiredClaims.push('nonce');\n }\n maxAge = resolveIdTokenMaxAge(client, maxAge);\n if (maxAge !== skipAuthTimeCheck) {\n additionalRequiredClaims.push('auth_time');\n }\n const result = await processGenericAccessTokenResponse(as, client, response, additionalRequiredClaims, decryptFn, recognizedTokenTypes);\n assertString(result.id_token, '\"response\" body \"id_token\" property', INVALID_RESPONSE, {\n body: result,\n });\n const claims = getValidatedIdTokenClaims(result);\n validateIdTokenAuthTime(client, claims, maxAge);\n validateIdTokenNonce(claims, expectedNonce);\n return result;\n}\nasync function processAuthorizationCodeOAuth2Response(as, client, response, maxAge, decryptFn, recognizedTokenTypes) {\n const result = await processGenericAccessTokenResponse(as, client, response, undefined, decryptFn, recognizedTokenTypes);\n const claims = getValidatedIdTokenClaims(result);\n if (claims) {\n validateIdTokenAuthTime(client, claims, resolveIdTokenMaxAge(client, maxAge));\n validateIdTokenNonce(claims, expectNoNonce);\n }\n return result;\n}\nexport const WWW_AUTHENTICATE_CHALLENGE = 'OAUTH_WWW_AUTHENTICATE_CHALLENGE';\nexport const RESPONSE_BODY_ERROR = 'OAUTH_RESPONSE_BODY_ERROR';\nexport const UNSUPPORTED_OPERATION = 'OAUTH_UNSUPPORTED_OPERATION';\nexport const AUTHORIZATION_RESPONSE_ERROR = 'OAUTH_AUTHORIZATION_RESPONSE_ERROR';\nexport const JWT_USERINFO_EXPECTED = 'OAUTH_JWT_USERINFO_EXPECTED';\nexport const PARSE_ERROR = 'OAUTH_PARSE_ERROR';\nexport const INVALID_RESPONSE = 'OAUTH_INVALID_RESPONSE';\nexport const INVALID_REQUEST = 'OAUTH_INVALID_REQUEST';\nexport const RESPONSE_IS_NOT_JSON = 'OAUTH_RESPONSE_IS_NOT_JSON';\nexport const RESPONSE_IS_NOT_CONFORM = 'OAUTH_RESPONSE_IS_NOT_CONFORM';\nexport const HTTP_REQUEST_FORBIDDEN = 'OAUTH_HTTP_REQUEST_FORBIDDEN';\nexport const REQUEST_PROTOCOL_FORBIDDEN = 'OAUTH_REQUEST_PROTOCOL_FORBIDDEN';\nexport const JWT_TIMESTAMP_CHECK = 'OAUTH_JWT_TIMESTAMP_CHECK_FAILED';\nexport const JWT_CLAIM_COMPARISON = 'OAUTH_JWT_CLAIM_COMPARISON_FAILED';\nexport const JSON_ATTRIBUTE_COMPARISON = 'OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED';\nexport const KEY_SELECTION = 'OAUTH_KEY_SELECTION_FAILED';\nexport const MISSING_SERVER_METADATA = 'OAUTH_MISSING_SERVER_METADATA';\nexport const INVALID_SERVER_METADATA = 'OAUTH_INVALID_SERVER_METADATA';\nfunction checkJwtType(expected, result) {\n if (typeof result.header.typ !== 'string' || normalizeTyp(result.header.typ) !== expected) {\n throw OPE('unexpected JWT \"typ\" header parameter value', INVALID_RESPONSE, {\n header: result.header,\n });\n }\n return result;\n}\nexport async function clientCredentialsGrantRequest(as, client, clientAuthentication, parameters, options) {\n assertAs(as);\n assertClient(client);\n return tokenEndpointRequest(as, client, clientAuthentication, 'client_credentials', new URLSearchParams(parameters), options);\n}\nexport async function genericTokenEndpointRequest(as, client, clientAuthentication, grantType, parameters, options) {\n assertAs(as);\n assertClient(client);\n assertString(grantType, '\"grantType\"');\n return tokenEndpointRequest(as, client, clientAuthentication, grantType, new URLSearchParams(parameters), options);\n}\nexport async function processGenericTokenEndpointResponse(as, client, response, options) {\n return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nexport async function processClientCredentialsResponse(as, client, response, options) {\n return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nexport async function revocationRequest(as, client, clientAuthentication, token, options) {\n assertAs(as);\n assertClient(client);\n assertString(token, '\"token\"');\n const url = resolveEndpoint(as, 'revocation_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const body = new URLSearchParams(options?.additionalParameters);\n body.set('token', token);\n const headers = prepareHeaders(options?.headers);\n headers.delete('accept');\n return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);\n}\nexport async function processRevocationResponse(response) {\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 200, 'Revocation Endpoint');\n return undefined;\n}\nfunction assertReadableResponse(response) {\n if (response.bodyUsed) {\n throw CodedTypeError('\"response\" body has been used already', ERR_INVALID_ARG_VALUE);\n }\n}\nexport async function introspectionRequest(as, client, clientAuthentication, token, options) {\n assertAs(as);\n assertClient(client);\n assertString(token, '\"token\"');\n const url = resolveEndpoint(as, 'introspection_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const body = new URLSearchParams(options?.additionalParameters);\n body.set('token', token);\n const headers = prepareHeaders(options?.headers);\n if (options?.requestJwtResponse ?? client.introspection_signed_response_alg) {\n headers.set('accept', 'application/token-introspection+jwt');\n }\n else {\n headers.set('accept', 'application/json');\n }\n return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);\n}\nexport async function processIntrospectionResponse(as, client, response, options) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 200, 'Introspection Endpoint');\n let json;\n if (getContentType(response) === 'application/token-introspection+jwt') {\n assertReadableResponse(response);\n const { claims, jwt } = await validateJwt(await response.text(), checkSigningAlgorithm.bind(undefined, client.introspection_signed_response_alg, as.introspection_signing_alg_values_supported, 'RS256'), getClockSkew(client), getClockTolerance(client), options?.[jweDecrypt])\n .then(checkJwtType.bind(undefined, 'token-introspection+jwt'))\n .then(validatePresence.bind(undefined, ['aud', 'iat', 'iss']))\n .then(validateIssuer.bind(undefined, as))\n .then(validateAudience.bind(undefined, client.client_id));\n jwtRefs.set(response, jwt);\n if (!isJsonObject(claims.token_introspection)) {\n throw OPE('JWT \"token_introspection\" claim must be a JSON object', INVALID_RESPONSE, {\n claims,\n });\n }\n json = claims.token_introspection;\n }\n else {\n assertReadableResponse(response);\n json = await getResponseJsonBody(response);\n }\n if (typeof json.active !== 'boolean') {\n throw OPE('\"response\" body \"active\" property must be a boolean', INVALID_RESPONSE, {\n body: json,\n });\n }\n return json;\n}\nasync function jwksRequest(as, options) {\n assertAs(as);\n const url = resolveEndpoint(as, 'jwks_uri', false, options?.[allowInsecureRequests] !== true);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n headers.append('accept', 'application/jwk-set+json');\n const requestHeaders = Object.fromEntries(headers.entries());\n const headersKey = JSON.stringify(requestHeaders);\n const fetcher = options?.[customFetch] || fetch;\n const requestSignal = signal(url, options?.signal);\n jwksRequests ||= new WeakMap();\n const requests = jwksRequests.get(as) ?? new Set();\n for (const pending of requests) {\n if (pending.url === url.href &&\n pending.headers === headersKey &&\n pending.fetch === fetcher &&\n pending.signal === requestSignal) {\n return pending.promise;\n }\n }\n const pending = {\n url: url.href,\n headers: headersKey,\n fetch: fetcher,\n signal: requestSignal,\n promise: Promise.resolve()\n .then(() => fetcher(url.href, {\n body: undefined,\n headers: requestHeaders,\n method: 'GET',\n redirect: 'manual',\n signal: requestSignal,\n }))\n .then(processJwksResponse)\n .then((jwks) => {\n const uat = epochTime();\n setJwksCache(as, jwks, uat);\n return { jwks, uat };\n })\n .finally(() => {\n requests.delete(pending);\n if (!requests.size) {\n jwksRequests.delete(as);\n }\n }),\n };\n requests.add(pending);\n jwksRequests.set(as, requests);\n return pending.promise;\n}\nasync function processJwksResponse(response) {\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n if (response.status !== 200) {\n throw OPE('\"response\" is not a conform JSON Web Key Set response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);\n }\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response, (response) => assertContentTypes(response, 'application/json', 'application/jwk-set+json'));\n if (!Array.isArray(json.keys)) {\n throw OPE('\"response\" body \"keys\" property must be an array', INVALID_RESPONSE, { body: json });\n }\n if (!Array.prototype.every.call(json.keys, isJsonObject)) {\n throw OPE('\"response\" body \"keys\" property members must be JWK formatted objects', INVALID_RESPONSE, { body: json });\n }\n return json;\n}\nfunction supported(alg) {\n switch (alg) {\n case 'PS256':\n case 'ES256':\n case 'RS256':\n case 'PS384':\n case 'ES384':\n case 'RS384':\n case 'PS512':\n case 'ES512':\n case 'RS512':\n case 'Ed25519':\n case 'EdDSA':\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n return true;\n default:\n return false;\n }\n}\nfunction checkSupportedJwsAlg(header) {\n if (!supported(header.alg)) {\n throw new UnsupportedOperationError('unsupported JWS \"alg\" identifier', {\n cause: { alg: header.alg },\n });\n }\n}\nfunction checkRsaKeyAlgorithm(key) {\n const { algorithm } = key;\n if (typeof algorithm.modulusLength !== 'number' || algorithm.modulusLength < 2048) {\n throw new UnsupportedOperationError(`unsupported ${algorithm.name} modulusLength`, {\n cause: key,\n });\n }\n}\nfunction ecdsaHashName(key) {\n const { algorithm } = key;\n switch (algorithm.namedCurve) {\n case 'P-256':\n return 'SHA-256';\n case 'P-384':\n return 'SHA-384';\n case 'P-521':\n return 'SHA-512';\n default:\n throw new UnsupportedOperationError('unsupported ECDSA namedCurve', { cause: key });\n }\n}\nfunction keyToSubtle(key) {\n switch (key.algorithm.name) {\n case 'ECDSA':\n return {\n name: key.algorithm.name,\n hash: ecdsaHashName(key),\n };\n case 'RSA-PSS': {\n checkRsaKeyAlgorithm(key);\n switch (key.algorithm.hash.name) {\n case 'SHA-256':\n case 'SHA-384':\n case 'SHA-512':\n return {\n name: key.algorithm.name,\n saltLength: parseInt(key.algorithm.hash.name.slice(-3), 10) >> 3,\n };\n default:\n throw new UnsupportedOperationError('unsupported RSA-PSS hash name', { cause: key });\n }\n }\n case 'RSASSA-PKCS1-v1_5':\n checkRsaKeyAlgorithm(key);\n return key.algorithm.name;\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n case 'Ed25519':\n return key.algorithm.name;\n }\n throw new UnsupportedOperationError('unsupported CryptoKey algorithm name', { cause: key });\n}\nasync function validateJwsSignature(protectedHeader, payload, key, signature) {\n const data = buf(`${protectedHeader}.${payload}`);\n const algorithm = keyToSubtle(key);\n const verified = await crypto.subtle.verify(algorithm, key, signature, data);\n if (!verified) {\n throw OPE('JWT signature verification failed', INVALID_RESPONSE, {\n key,\n data,\n signature,\n algorithm,\n });\n }\n}\nasync function validateJwt(jws, checkAlg, clockSkew, clockTolerance, decryptJwt) {\n let { 0: protectedHeader, 1: payload, length } = jws.split('.');\n if (length === 5) {\n if (decryptJwt !== undefined) {\n jws = await decryptJwt(jws);\n ({ 0: protectedHeader, 1: payload, length } = jws.split('.'));\n }\n else {\n throw new UnsupportedOperationError('JWE decryption is not configured', { cause: jws });\n }\n }\n if (length !== 3) {\n throw OPE('Invalid JWT', INVALID_RESPONSE, jws);\n }\n let header;\n try {\n header = JSON.parse(buf(b64u(protectedHeader)));\n }\n catch (cause) {\n throw OPE('failed to parse JWT Header body as base64url encoded JSON', PARSE_ERROR, cause);\n }\n if (!isJsonObject(header)) {\n throw OPE('JWT Header must be a top level object', INVALID_RESPONSE, jws);\n }\n checkAlg(header);\n if (header.crit !== undefined) {\n throw new UnsupportedOperationError('no JWT \"crit\" header parameter extensions are supported', {\n cause: { header },\n });\n }\n let claims;\n try {\n claims = JSON.parse(buf(b64u(payload)));\n }\n catch (cause) {\n throw OPE('failed to parse JWT Payload body as base64url encoded JSON', PARSE_ERROR, cause);\n }\n if (!isJsonObject(claims)) {\n throw OPE('JWT Payload must be a top level object', INVALID_RESPONSE, jws);\n }\n const now = epochTime() + clockSkew;\n if (claims.exp !== undefined) {\n if (typeof claims.exp !== 'number') {\n throw OPE('unexpected JWT \"exp\" (expiration time) claim type', INVALID_RESPONSE, { claims });\n }\n if (claims.exp <= now - clockTolerance) {\n throw OPE('unexpected JWT \"exp\" (expiration time) claim value, expiration is past current timestamp', JWT_TIMESTAMP_CHECK, { claims, now, tolerance: clockTolerance, claim: 'exp' });\n }\n }\n if (claims.iat !== undefined) {\n if (typeof claims.iat !== 'number') {\n throw OPE('unexpected JWT \"iat\" (issued at) claim type', INVALID_RESPONSE, { claims });\n }\n }\n if (claims.iss !== undefined) {\n if (typeof claims.iss !== 'string') {\n throw OPE('unexpected JWT \"iss\" (issuer) claim type', INVALID_RESPONSE, { claims });\n }\n }\n if (claims.nbf !== undefined) {\n if (typeof claims.nbf !== 'number') {\n throw OPE('unexpected JWT \"nbf\" (not before) claim type', INVALID_RESPONSE, { claims });\n }\n if (claims.nbf > now + clockTolerance) {\n throw OPE('unexpected JWT \"nbf\" (not before) claim value', JWT_TIMESTAMP_CHECK, {\n claims,\n now,\n tolerance: clockTolerance,\n claim: 'nbf',\n });\n }\n }\n if (claims.aud !== undefined) {\n if (typeof claims.aud !== 'string' && !Array.isArray(claims.aud)) {\n throw OPE('unexpected JWT \"aud\" (audience) claim type', INVALID_RESPONSE, { claims });\n }\n }\n return { header, claims, jwt: jws };\n}\nexport async function validateJwtAuthResponse(as, client, parameters, expectedState, options) {\n assertAs(as);\n assertClient(client);\n if (parameters instanceof URL) {\n parameters = parameters.searchParams;\n }\n if (!(parameters instanceof URLSearchParams)) {\n throw CodedTypeError('\"parameters\" must be an instance of URLSearchParams, or URL', ERR_INVALID_ARG_TYPE);\n }\n const response = getURLSearchParameter(parameters, 'response');\n if (!response) {\n throw OPE('\"parameters\" does not contain a JARM response', INVALID_RESPONSE);\n }\n const { claims, header, jwt } = await validateJwt(response, checkSigningAlgorithm.bind(undefined, client.authorization_signed_response_alg, as.authorization_signing_alg_values_supported, 'RS256'), getClockSkew(client), getClockTolerance(client), options?.[jweDecrypt])\n .then(validatePresence.bind(undefined, ['aud', 'exp', 'iss']))\n .then(validateIssuer.bind(undefined, as))\n .then(validateAudience.bind(undefined, client.client_id));\n const { 0: protectedHeader, 1: payload, 2: encodedSignature } = jwt.split('.');\n const signature = b64u(encodedSignature);\n const key = await getPublicSigKeyFromIssuerJwksUri(as, options, header);\n await validateJwsSignature(protectedHeader, payload, key, signature);\n const result = new URLSearchParams();\n for (const [key, value] of Object.entries(claims)) {\n if (typeof value === 'string' && key !== 'aud') {\n result.set(key, value);\n }\n }\n return validateAuthResponse(as, client, result, expectedState);\n}\nasync function idTokenHash(data, header, claimName) {\n let algorithm;\n switch (header.alg) {\n case 'RS256':\n case 'PS256':\n case 'ES256':\n algorithm = 'SHA-256';\n break;\n case 'RS384':\n case 'PS384':\n case 'ES384':\n algorithm = 'SHA-384';\n break;\n case 'RS512':\n case 'PS512':\n case 'ES512':\n case 'Ed25519':\n case 'EdDSA':\n algorithm = 'SHA-512';\n break;\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n algorithm = { name: 'cSHAKE256', length: 512, outputLength: 512 };\n break;\n default:\n throw new UnsupportedOperationError(`unsupported JWS algorithm for ${claimName} calculation`, { cause: { alg: header.alg } });\n }\n const digest = await crypto.subtle.digest(algorithm, buf(data));\n return b64u(digest.slice(0, digest.byteLength / 2));\n}\nasync function idTokenHashMatches(data, actual, header, claimName) {\n const expected = await idTokenHash(data, header, claimName);\n return actual === expected;\n}\nexport async function validateDetachedSignatureResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options) {\n return validateHybridResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options, true);\n}\nexport async function validateCodeIdTokenResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options) {\n return validateHybridResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options, false);\n}\nasync function consumeStream(request) {\n if (request.bodyUsed) {\n throw CodedTypeError('form_post Request instances must contain a readable body', ERR_INVALID_ARG_VALUE, { cause: request });\n }\n return request.text();\n}\nexport async function formPostResponse(request) {\n if (request.method !== 'POST') {\n throw CodedTypeError('form_post responses are expected to use the POST method', ERR_INVALID_ARG_VALUE, { cause: request });\n }\n if (getContentType(request) !== 'application/x-www-form-urlencoded') {\n throw CodedTypeError('form_post responses are expected to use the application/x-www-form-urlencoded content-type', ERR_INVALID_ARG_VALUE, { cause: request });\n }\n return consumeStream(request);\n}\nasync function validateHybridResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options, fapi) {\n assertAs(as);\n assertClient(client);\n if (parameters instanceof URL) {\n if (!parameters.hash.length) {\n throw CodedTypeError('\"parameters\" as an instance of URL must contain a hash (fragment) with the Authorization Response parameters', ERR_INVALID_ARG_VALUE);\n }\n parameters = new URLSearchParams(parameters.hash.slice(1));\n }\n else if (looseInstanceOf(parameters, Request)) {\n parameters = new URLSearchParams(await formPostResponse(parameters));\n }\n else if (parameters instanceof URLSearchParams) {\n parameters = new URLSearchParams(parameters);\n }\n else {\n throw CodedTypeError('\"parameters\" must be an instance of URLSearchParams, URL, or Response', ERR_INVALID_ARG_TYPE);\n }\n const id_token = getURLSearchParameter(parameters, 'id_token');\n parameters.delete('id_token');\n switch (expectedState) {\n case undefined:\n case expectNoState:\n break;\n default:\n assertString(expectedState, '\"expectedState\" argument');\n }\n const result = validateAuthResponse({\n ...as,\n authorization_response_iss_parameter_supported: false,\n }, client, parameters, expectedState);\n if (!id_token) {\n throw OPE('\"parameters\" does not contain an ID Token', INVALID_RESPONSE);\n }\n const code = getURLSearchParameter(parameters, 'code');\n if (!code) {\n throw OPE('\"parameters\" does not contain an Authorization Code', INVALID_RESPONSE);\n }\n const requiredClaims = ['nonce', 'c_hash'];\n const state = parameters.get('state');\n if (fapi && (typeof expectedState === 'string' || state !== null)) {\n requiredClaims.push('s_hash');\n }\n maxAge = resolveIdTokenMaxAge(client, maxAge);\n if (client.require_auth_time || maxAge !== skipAuthTimeCheck) {\n requiredClaims.push('auth_time');\n }\n const { claims, header, jwt } = await validateIdTokenClaims(as, client, id_token, requiredClaims, options?.[jweDecrypt]);\n const clockSkew = getClockSkew(client);\n const now = epochTime() + clockSkew;\n if (claims.iat < now - 3600) {\n throw OPE('unexpected JWT \"iat\" (issued at) claim value, it is too far in the past', JWT_TIMESTAMP_CHECK, { now, claims, claim: 'iat' });\n }\n assertString(claims.c_hash, 'ID Token \"c_hash\" (code hash) claim value', INVALID_RESPONSE, {\n claims,\n });\n validateIdTokenAuthTimeClaim(claims);\n validateIdTokenAuthTime(client, claims, maxAge);\n assertString(expectedNonce, '\"expectedNonce\" argument');\n validateIdTokenNonce(claims, expectedNonce);\n validateIdTokenAuthorizedParty(client, claims);\n const { 0: protectedHeader, 1: payload, 2: encodedSignature } = jwt.split('.');\n const signature = b64u(encodedSignature);\n const key = await getPublicSigKeyFromIssuerJwksUri(as, options, header);\n await validateJwsSignature(protectedHeader, payload, key, signature);\n if ((await idTokenHashMatches(code, claims.c_hash, header, 'c_hash')) !== true) {\n throw OPE('invalid ID Token \"c_hash\" (code hash) claim value', JWT_CLAIM_COMPARISON, {\n code,\n alg: header.alg,\n claim: 'c_hash',\n claims,\n });\n }\n if ((fapi && state !== null) || claims.s_hash !== undefined) {\n assertString(claims.s_hash, 'ID Token \"s_hash\" (state hash) claim value', INVALID_RESPONSE, {\n claims,\n });\n assertString(state, '\"state\" response parameter', INVALID_RESPONSE, { parameters });\n if ((await idTokenHashMatches(state, claims.s_hash, header, 's_hash')) !== true) {\n throw OPE('invalid ID Token \"s_hash\" (state hash) claim value', JWT_CLAIM_COMPARISON, {\n state,\n alg: header.alg,\n claim: 's_hash',\n claims,\n });\n }\n }\n return result;\n}\nfunction checkSigningAlgorithm(client, issuer, fallback, header) {\n if (client !== undefined) {\n if (typeof client === 'string' ? header.alg !== client : !client.includes(header.alg)) {\n throw OPE('unexpected JWT \"alg\" header parameter', INVALID_RESPONSE, {\n header,\n expected: client,\n reason: 'client configuration',\n });\n }\n return;\n }\n if (Array.isArray(issuer)) {\n if (!issuer.includes(header.alg)) {\n throw OPE('unexpected JWT \"alg\" header parameter', INVALID_RESPONSE, {\n header,\n expected: issuer,\n reason: 'authorization server metadata',\n });\n }\n return;\n }\n if (fallback !== undefined) {\n if (typeof fallback === 'string'\n ? header.alg !== fallback\n : typeof fallback === 'function'\n ? !fallback(header.alg)\n : !fallback.includes(header.alg)) {\n throw OPE('unexpected JWT \"alg\" header parameter', INVALID_RESPONSE, {\n header,\n expected: fallback,\n reason: 'default value',\n });\n }\n return;\n }\n throw OPE('missing client or server configuration to verify used JWT \"alg\" header parameter', undefined, { client, issuer, fallback });\n}\nfunction getURLSearchParameter(parameters, name) {\n const { 0: value, length } = parameters.getAll(name);\n if (length > 1) {\n throw OPE(`\"${name}\" parameter must be provided only once`, INVALID_RESPONSE);\n }\n return value;\n}\nexport const skipStateCheck = Symbol();\nexport const expectNoState = Symbol();\nexport function validateAuthResponse(as, client, parameters, expectedState) {\n assertAs(as);\n assertClient(client);\n if (parameters instanceof URL) {\n parameters = parameters.searchParams;\n }\n if (!(parameters instanceof URLSearchParams)) {\n throw CodedTypeError('\"parameters\" must be an instance of URLSearchParams, or URL', ERR_INVALID_ARG_TYPE);\n }\n if (getURLSearchParameter(parameters, 'response')) {\n throw OPE('\"parameters\" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()', INVALID_RESPONSE, { parameters });\n }\n const iss = getURLSearchParameter(parameters, 'iss');\n const state = getURLSearchParameter(parameters, 'state');\n if (!iss && as.authorization_response_iss_parameter_supported) {\n throw OPE('response parameter \"iss\" (issuer) missing', INVALID_RESPONSE, { parameters });\n }\n if (iss && iss !== as.issuer) {\n throw OPE('unexpected \"iss\" (issuer) response parameter value', INVALID_RESPONSE, {\n expected: as.issuer,\n parameters,\n });\n }\n switch (expectedState) {\n case undefined:\n case expectNoState:\n if (state !== undefined) {\n throw OPE('unexpected \"state\" response parameter encountered', INVALID_RESPONSE, {\n expected: undefined,\n parameters,\n });\n }\n break;\n case skipStateCheck:\n break;\n default:\n assertString(expectedState, '\"expectedState\" argument');\n if (state !== expectedState) {\n throw OPE(state === undefined\n ? 'response parameter \"state\" missing'\n : 'unexpected \"state\" response parameter value', INVALID_RESPONSE, { expected: expectedState, parameters });\n }\n }\n const error = getURLSearchParameter(parameters, 'error');\n if (error) {\n throw new AuthorizationResponseError('authorization response from the server is an error', {\n cause: parameters,\n });\n }\n const id_token = getURLSearchParameter(parameters, 'id_token');\n const token = getURLSearchParameter(parameters, 'token');\n if (id_token !== undefined || token !== undefined) {\n throw new UnsupportedOperationError('implicit and hybrid flows are not supported');\n }\n return brand(new URLSearchParams(parameters));\n}\nfunction algToSubtle(alg) {\n switch (alg) {\n case 'PS256':\n case 'PS384':\n case 'PS512':\n return { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` };\n case 'RS256':\n case 'RS384':\n case 'RS512':\n return { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` };\n case 'ES256':\n case 'ES384':\n return { name: 'ECDSA', namedCurve: `P-${alg.slice(-3)}` };\n case 'ES512':\n return { name: 'ECDSA', namedCurve: 'P-521' };\n case 'EdDSA':\n return 'Ed25519';\n case 'Ed25519':\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n return alg;\n default:\n throw new UnsupportedOperationError('unsupported JWS algorithm', { cause: { alg } });\n }\n}\nasync function importJwk(alg, jwk) {\n const { ext, key_ops, use, ...key } = jwk;\n return crypto.subtle.importKey('jwk', key, algToSubtle(alg), true, ['verify']);\n}\nexport async function deviceAuthorizationRequest(as, client, clientAuthentication, parameters, options) {\n assertAs(as);\n assertClient(client);\n const url = resolveEndpoint(as, 'device_authorization_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const body = new URLSearchParams(parameters);\n body.set('client_id', client.client_id);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);\n}\nexport async function processDeviceAuthorizationResponse(as, client, response) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 200, 'Device Authorization Endpoint');\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.device_code, '\"response\" body \"device_code\" property', INVALID_RESPONSE, {\n body: json,\n });\n assertString(json.user_code, '\"response\" body \"user_code\" property', INVALID_RESPONSE, {\n body: json,\n });\n assertString(json.verification_uri, '\"response\" body \"verification_uri\" property', INVALID_RESPONSE, { body: json });\n let expiresIn = typeof json.expires_in !== 'number' ? parseFloat(json.expires_in) : json.expires_in;\n assertNumber(expiresIn, true, '\"response\" body \"expires_in\" property', INVALID_RESPONSE, {\n body: json,\n });\n json.expires_in = expiresIn;\n if (json.verification_uri_complete !== undefined) {\n assertString(json.verification_uri_complete, '\"response\" body \"verification_uri_complete\" property', INVALID_RESPONSE, { body: json });\n }\n if (json.interval !== undefined) {\n assertNumber(json.interval, false, '\"response\" body \"interval\" property', INVALID_RESPONSE, {\n body: json,\n });\n }\n return json;\n}\nexport async function deviceCodeGrantRequest(as, client, clientAuthentication, deviceCode, options) {\n assertAs(as);\n assertClient(client);\n assertString(deviceCode, '\"deviceCode\"');\n const parameters = new URLSearchParams(options?.additionalParameters);\n parameters.set('device_code', deviceCode);\n return tokenEndpointRequest(as, client, clientAuthentication, 'urn:ietf:params:oauth:grant-type:device_code', parameters, options);\n}\nexport async function processDeviceCodeResponse(as, client, response, options) {\n return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nexport async function generateKeyPair(alg, options) {\n assertString(alg, '\"alg\"');\n const algorithm = algToSubtle(alg);\n if (alg.startsWith('PS') || alg.startsWith('RS')) {\n Object.assign(algorithm, {\n modulusLength: options?.modulusLength ?? 2048,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n });\n }\n return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, [\n 'sign',\n 'verify',\n ]);\n}\nfunction normalizeHtu(htu) {\n const url = new URL(htu);\n url.search = '';\n url.hash = '';\n return url.href;\n}\nasync function validateDPoP(request, accessToken, accessTokenClaims, options) {\n const headerValue = request.headers.get('dpop');\n if (headerValue === null) {\n throw OPE('operation indicated DPoP use but the request has no DPoP HTTP Header', INVALID_REQUEST, { headers: request.headers });\n }\n if (request.headers.get('authorization')?.toLowerCase().startsWith('dpop ') === false) {\n throw OPE(`operation indicated DPoP use but the request's Authorization HTTP Header scheme is not DPoP`, INVALID_REQUEST, { headers: request.headers });\n }\n if (typeof accessTokenClaims.cnf?.jkt !== 'string') {\n throw OPE('operation indicated DPoP use but the JWT Access Token has no jkt confirmation claim', INVALID_REQUEST, { claims: accessTokenClaims });\n }\n const clockSkew = getClockSkew(options);\n const proof = await validateJwt(headerValue, checkSigningAlgorithm.bind(undefined, options?.signingAlgorithms, undefined, supported), clockSkew, getClockTolerance(options), undefined)\n .then(checkJwtType.bind(undefined, 'dpop+jwt'))\n .then(validatePresence.bind(undefined, ['iat', 'jti', 'ath', 'htm', 'htu']))\n .then(validateStringClaim.bind(undefined, 'jti'));\n const now = epochTime() + clockSkew;\n const diff = Math.abs(now - proof.claims.iat);\n if (diff > 300) {\n throw OPE('DPoP Proof iat is not recent enough', JWT_TIMESTAMP_CHECK, {\n now,\n claims: proof.claims,\n claim: 'iat',\n });\n }\n if (proof.claims.htm !== request.method) {\n throw OPE('DPoP Proof htm mismatch', JWT_CLAIM_COMPARISON, {\n expected: request.method,\n claims: proof.claims,\n claim: 'htm',\n });\n }\n if (typeof proof.claims.htu !== 'string' ||\n normalizeHtu(proof.claims.htu) !== normalizeHtu(request.url)) {\n throw OPE('DPoP Proof htu mismatch', JWT_CLAIM_COMPARISON, {\n expected: normalizeHtu(request.url),\n claims: proof.claims,\n claim: 'htu',\n });\n }\n {\n const expected = b64u(await crypto.subtle.digest('SHA-256', buf(accessToken)));\n if (proof.claims.ath !== expected) {\n throw OPE('DPoP Proof ath mismatch', JWT_CLAIM_COMPARISON, {\n expected,\n claims: proof.claims,\n claim: 'ath',\n });\n }\n }\n const { jwk, alg } = proof.header;\n if (!isJsonObject(jwk)) {\n throw OPE('DPoP Proof jwk header parameter must be a JSON object', INVALID_REQUEST, {\n header: proof.header,\n });\n }\n {\n const expected = await calculateJwkThumbprint(jwk);\n if (accessTokenClaims.cnf.jkt !== expected) {\n throw OPE('JWT Access Token confirmation mismatch', JWT_CLAIM_COMPARISON, {\n expected,\n claims: accessTokenClaims,\n claim: 'cnf.jkt',\n });\n }\n }\n const { 0: protectedHeader, 1: payload, 2: encodedSignature } = headerValue.split('.');\n const signature = b64u(encodedSignature);\n const key = await importJwk(alg, jwk);\n if (key.type !== 'public') {\n throw OPE('DPoP Proof jwk header parameter must contain a public key', INVALID_REQUEST, {\n header: proof.header,\n });\n }\n await validateJwsSignature(protectedHeader, payload, key, signature);\n}\nexport async function validateJwtAccessToken(as, request, expectedAudience, options) {\n assertAs(as);\n if (!looseInstanceOf(request, Request)) {\n throw CodedTypeError('\"request\" must be an instance of Request', ERR_INVALID_ARG_TYPE);\n }\n assertString(expectedAudience, '\"expectedAudience\"');\n const authorization = request.headers.get('authorization');\n if (authorization === null) {\n throw OPE('\"request\" is missing an Authorization HTTP Header', INVALID_REQUEST, {\n headers: request.headers,\n });\n }\n let { 0: scheme, 1: accessToken, length } = authorization.split(/ +/);\n scheme = scheme.toLowerCase();\n switch (scheme) {\n case 'dpop':\n case 'bearer':\n break;\n default:\n throw new UnsupportedOperationError('unsupported Authorization HTTP Header scheme', {\n cause: { headers: request.headers },\n });\n }\n if (length !== 2) {\n throw OPE('invalid Authorization HTTP Header format', INVALID_REQUEST, {\n headers: request.headers,\n });\n }\n const requiredClaims = [\n 'iss',\n 'exp',\n 'aud',\n 'sub',\n 'iat',\n 'jti',\n 'client_id',\n ];\n if (options?.requireDPoP || scheme === 'dpop' || request.headers.has('dpop')) {\n requiredClaims.push('cnf');\n }\n const { claims, header } = await validateJwt(accessToken, checkSigningAlgorithm.bind(undefined, options?.signingAlgorithms, undefined, supported), getClockSkew(options), getClockTolerance(options), undefined)\n .then(checkJwtType.bind(undefined, 'at+jwt'))\n .then(validatePresence.bind(undefined, requiredClaims))\n .then(validateIssuer.bind(undefined, as))\n .then(validateAudience.bind(undefined, expectedAudience))\n .catch(reassignRSCode);\n for (const claim of ['client_id', 'jti', 'sub']) {\n if (typeof claims[claim] !== 'string') {\n throw OPE(`unexpected JWT \"${claim}\" claim type`, INVALID_REQUEST, { claims });\n }\n }\n if ('cnf' in claims) {\n if (!isJsonObject(claims.cnf)) {\n throw OPE('unexpected JWT \"cnf\" (confirmation) claim value', INVALID_REQUEST, { claims });\n }\n const { 0: cnf, length } = Object.keys(claims.cnf);\n if (length) {\n if (length !== 1) {\n throw new UnsupportedOperationError('multiple confirmation claims are not supported', {\n cause: { claims },\n });\n }\n if (cnf !== 'jkt') {\n throw new UnsupportedOperationError('unsupported JWT Confirmation method', {\n cause: { claims },\n });\n }\n }\n }\n const { 0: protectedHeader, 1: payload, 2: encodedSignature } = accessToken.split('.');\n const signature = b64u(encodedSignature);\n const key = await getPublicSigKeyFromIssuerJwksUri(as, options, header);\n await validateJwsSignature(protectedHeader, payload, key, signature);\n if (options?.requireDPoP ||\n scheme === 'dpop' ||\n claims.cnf?.jkt !== undefined ||\n request.headers.has('dpop')) {\n await validateDPoP(request, accessToken, claims, options).catch(reassignRSCode);\n }\n return claims;\n}\nfunction reassignRSCode(err) {\n if (err instanceof OperationProcessingError && err?.code === INVALID_REQUEST) {\n err.code = INVALID_RESPONSE;\n }\n throw err;\n}\nexport async function backchannelAuthenticationRequest(as, client, clientAuthentication, parameters, options) {\n assertAs(as);\n assertClient(client);\n const url = resolveEndpoint(as, 'backchannel_authentication_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const body = new URLSearchParams(parameters);\n body.set('client_id', client.client_id);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);\n}\nexport async function processBackchannelAuthenticationResponse(as, client, response) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 200, 'Backchannel Authentication Endpoint');\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.auth_req_id, '\"response\" body \"auth_req_id\" property', INVALID_RESPONSE, {\n body: json,\n });\n let expiresIn = typeof json.expires_in !== 'number' ? parseFloat(json.expires_in) : json.expires_in;\n assertNumber(expiresIn, true, '\"response\" body \"expires_in\" property', INVALID_RESPONSE, {\n body: json,\n });\n json.expires_in = expiresIn;\n if (json.interval !== undefined) {\n assertNumber(json.interval, false, '\"response\" body \"interval\" property', INVALID_RESPONSE, {\n body: json,\n });\n }\n return json;\n}\nexport async function backchannelAuthenticationGrantRequest(as, client, clientAuthentication, authReqId, options) {\n assertAs(as);\n assertClient(client);\n assertString(authReqId, '\"authReqId\"');\n const parameters = new URLSearchParams(options?.additionalParameters);\n parameters.set('auth_req_id', authReqId);\n return tokenEndpointRequest(as, client, clientAuthentication, 'urn:openid:params:grant-type:ciba', parameters, options);\n}\nexport async function processBackchannelAuthenticationGrantResponse(as, client, response, options) {\n return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nexport async function dynamicClientRegistrationRequest(as, metadata, options) {\n assertAs(as);\n const url = resolveEndpoint(as, 'registration_endpoint', metadata.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n headers.set('content-type', 'application/json');\n const method = 'POST';\n if (options?.DPoP) {\n assertDPoP(options.DPoP);\n await options.DPoP.addProof(url, headers, method, options.initialAccessToken);\n }\n if (options?.initialAccessToken) {\n headers.set('authorization', `${headers.has('dpop') ? 'DPoP' : 'Bearer'} ${options.initialAccessToken}`);\n }\n const response = await (options?.[customFetch] || fetch)(url.href, {\n body: JSON.stringify(metadata),\n headers: Object.fromEntries(headers.entries()),\n method,\n redirect: 'manual',\n signal: signal(url, options?.signal),\n });\n options?.DPoP?.cacheNonce(response, url);\n return response;\n}\nexport async function processDynamicClientRegistrationResponse(response) {\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 201, 'Dynamic Client Registration Endpoint');\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.client_id, '\"response\" body \"client_id\" property', INVALID_RESPONSE, {\n body: json,\n });\n if (json.client_secret !== undefined) {\n assertString(json.client_secret, '\"response\" body \"client_secret\" property', INVALID_RESPONSE, {\n body: json,\n });\n }\n if (json.client_secret) {\n assertNumber(json.client_secret_expires_at, true, '\"response\" body \"client_secret_expires_at\" property', INVALID_RESPONSE, {\n body: json,\n });\n }\n return json;\n}\nexport async function resourceDiscoveryRequest(resourceIdentifier, options) {\n return performDiscovery(resourceIdentifier, 'resourceIdentifier', (url) => {\n prependWellKnown(url, '.well-known/oauth-protected-resource', true);\n return url;\n }, options);\n}\nexport async function processResourceDiscoveryResponse(expectedResourceIdentifier, response) {\n const expected = expectedResourceIdentifier;\n if (!(expected instanceof URL) && expected !== _nodiscoverycheck) {\n throw CodedTypeError('\"expectedResourceIdentifier\" must be an instance of URL', ERR_INVALID_ARG_TYPE);\n }\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n if (response.status !== 200) {\n throw OPE('\"response\" is not a conform Resource Server Metadata response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);\n }\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.resource, '\"response\" body \"resource\" property', INVALID_RESPONSE, {\n body: json,\n });\n if (expected !== _nodiscoverycheck && new URL(json.resource).href !== expected.href) {\n throw OPE('\"response\" body \"resource\" property does not match the expected value', JSON_ATTRIBUTE_COMPARISON, { expected: expected.href, body: json, attribute: 'resource' });\n }\n return json;\n}\nasync function getResponseJsonBody(response, check = assertApplicationJson) {\n let json;\n try {\n json = await response.json();\n }\n catch (cause) {\n check(response);\n throw OPE('failed to parse \"response\" body as JSON', PARSE_ERROR, cause);\n }\n if (!isJsonObject(json)) {\n throw OPE('\"response\" body must be a top level object', INVALID_RESPONSE, { body: json });\n }\n return json;\n}\nexport const _nopkce = nopkce;\nexport const _nodiscoverycheck = Symbol();\nexport const _expectedIssuer = Symbol();\n//# sourceMappingURL=index.js.map","import * as oauth from 'oauth4webapi';\nimport { compactDecrypt } from 'jose/jwe/compact/decrypt';\nimport { JOSEError } from 'jose/errors';\nlet headers;\nlet USER_AGENT;\nif (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {\n const NAME = 'openid-client';\n const VERSION = 'v6.8.8';\n USER_AGENT = `${NAME}/${VERSION}`;\n headers = { 'user-agent': USER_AGENT };\n}\nconst int = (config) => {\n return props.get(config);\n};\nlet props;\nexport { AuthorizationResponseError, ResponseBodyError, WWWAuthenticateChallengeError, } from 'oauth4webapi';\nexport function ClientSecretPost(clientSecret) {\n if (clientSecret !== undefined) {\n return oauth.ClientSecretPost(clientSecret);\n }\n const cache = new WeakMap();\n return (as, client, body, headers) => {\n let auth;\n if (!(auth = cache.get(client))) {\n assertString(client.client_secret, '\"metadata.client_secret\"');\n auth = oauth.ClientSecretPost(client.client_secret);\n cache.set(client, auth);\n }\n return auth(as, client, body, headers);\n };\n}\nfunction assertString(input, it) {\n if (typeof input !== 'string') {\n throw CodedTypeError(`${it} must be a string`, ERR_INVALID_ARG_TYPE);\n }\n if (input.length === 0) {\n throw CodedTypeError(`${it} must not be empty`, ERR_INVALID_ARG_VALUE);\n }\n}\nexport function ClientSecretBasic(clientSecret) {\n if (clientSecret !== undefined) {\n return oauth.ClientSecretBasic(clientSecret);\n }\n const cache = new WeakMap();\n return (as, client, body, headers) => {\n let auth;\n if (!(auth = cache.get(client))) {\n assertString(client.client_secret, '\"metadata.client_secret\"');\n auth = oauth.ClientSecretBasic(client.client_secret);\n cache.set(client, auth);\n }\n return auth(as, client, body, headers);\n };\n}\nexport function ClientSecretJwt(clientSecret, options) {\n if (clientSecret !== undefined) {\n return oauth.ClientSecretJwt(clientSecret, options);\n }\n const cache = new WeakMap();\n return (as, client, body, headers) => {\n let auth;\n if (!(auth = cache.get(client))) {\n assertString(client.client_secret, '\"metadata.client_secret\"');\n auth = oauth.ClientSecretJwt(client.client_secret, options);\n cache.set(client, auth);\n }\n return auth(as, client, body, headers);\n };\n}\nexport function None() {\n return oauth.None();\n}\nexport function PrivateKeyJwt(clientPrivateKey, options) {\n return oauth.PrivateKeyJwt(clientPrivateKey, options);\n}\nexport function TlsClientAuth() {\n return oauth.TlsClientAuth();\n}\nexport const skipStateCheck = oauth.skipStateCheck;\nexport const skipSubjectCheck = oauth.skipSubjectCheck;\nexport const customFetch = oauth.customFetch;\nexport const modifyAssertion = oauth.modifyAssertion;\nexport const clockSkew = oauth.clockSkew;\nexport const clockTolerance = oauth.clockTolerance;\nconst ERR_INVALID_ARG_VALUE = 'ERR_INVALID_ARG_VALUE';\nconst ERR_INVALID_ARG_TYPE = 'ERR_INVALID_ARG_TYPE';\nfunction CodedTypeError(message, code, cause) {\n const err = new TypeError(message, { cause });\n Object.assign(err, { code });\n return err;\n}\nexport function calculatePKCECodeChallenge(codeVerifier) {\n return oauth.calculatePKCECodeChallenge(codeVerifier);\n}\nexport function randomPKCECodeVerifier() {\n return oauth.generateRandomCodeVerifier();\n}\nexport function randomNonce() {\n return oauth.generateRandomNonce();\n}\nexport function randomState() {\n return oauth.generateRandomState();\n}\nexport class ClientError extends Error {\n code;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n this.code = options?.code;\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nconst decoder = new TextDecoder();\nfunction e(msg, cause, code) {\n return new ClientError(msg, { cause, code });\n}\nfunction errorHandler(err) {\n if (err instanceof TypeError ||\n err instanceof ClientError ||\n err instanceof oauth.ResponseBodyError ||\n err instanceof oauth.AuthorizationResponseError ||\n err instanceof oauth.WWWAuthenticateChallengeError) {\n throw err;\n }\n if (err instanceof oauth.OperationProcessingError) {\n switch (err.code) {\n case oauth.HTTP_REQUEST_FORBIDDEN:\n throw e('only requests to HTTPS are allowed', err, err.code);\n case oauth.REQUEST_PROTOCOL_FORBIDDEN:\n throw e('only requests to HTTP or HTTPS are allowed', err, err.code);\n case oauth.RESPONSE_IS_NOT_CONFORM:\n throw e('unexpected HTTP response status code', err.cause, err.code);\n case oauth.RESPONSE_IS_NOT_JSON:\n throw e('unexpected response content-type', err.cause, err.code);\n case oauth.PARSE_ERROR:\n throw e('parsing error occured', err, err.code);\n case oauth.INVALID_RESPONSE:\n throw e('invalid response encountered', err, err.code);\n case oauth.JWT_CLAIM_COMPARISON:\n throw e('unexpected JWT claim value encountered', err, err.code);\n case oauth.JSON_ATTRIBUTE_COMPARISON:\n throw e('unexpected JSON attribute value encountered', err, err.code);\n case oauth.JWT_TIMESTAMP_CHECK:\n throw e('JWT timestamp claim value failed validation', err, err.code);\n default:\n throw e(err.message, err, err.code);\n }\n }\n if (err instanceof oauth.UnsupportedOperationError) {\n throw e('unsupported operation', err, err.code);\n }\n if (err instanceof DOMException) {\n switch (err.name) {\n case 'OperationError':\n throw e('runtime operation error', err, oauth.UNSUPPORTED_OPERATION);\n case 'NotSupportedError':\n throw e('runtime unsupported operation', err, oauth.UNSUPPORTED_OPERATION);\n case 'TimeoutError':\n throw e('operation timed out', err, 'OAUTH_TIMEOUT');\n case 'AbortError':\n throw e('operation aborted', err, 'OAUTH_ABORT');\n }\n }\n throw new ClientError('something went wrong', { cause: err });\n}\nexport function randomDPoPKeyPair(alg, options) {\n return oauth\n .generateKeyPair(alg ?? 'ES256', {\n extractable: options?.extractable,\n })\n .catch(errorHandler);\n}\nfunction handleEntraId(server, as, options) {\n if (server.origin === 'https://login.microsoftonline.com' &&\n (!options?.algorithm || options.algorithm === 'oidc')) {\n as[kEntraId] = true;\n return true;\n }\n return false;\n}\nfunction handleB2Clogin(server, options) {\n if (server.hostname.endsWith('.b2clogin.com') &&\n (!options?.algorithm || options.algorithm === 'oidc')) {\n return true;\n }\n return false;\n}\nexport async function dynamicClientRegistration(server, metadata, clientAuthentication, options) {\n let as;\n if (options?.flag === retry) {\n as = options.as;\n }\n else {\n as = await performDiscovery(server, options);\n }\n const clockSkew = metadata[oauth.clockSkew] ?? 0;\n const clockTolerance = metadata[oauth.clockTolerance] ?? 30;\n metadata = structuredClone(metadata);\n metadata[oauth.clockSkew] = clockSkew;\n metadata[oauth.clockTolerance] = clockTolerance;\n const timeout = options?.timeout ?? 30;\n const signal = AbortSignal.timeout(timeout * 1000);\n let registered;\n try {\n registered = await oauth\n .dynamicClientRegistrationRequest(as, metadata, {\n initialAccessToken: options?.initialAccessToken,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n [oauth.customFetch]: options?.[customFetch],\n [oauth.allowInsecureRequests]: options?.execute?.includes(allowInsecureRequests),\n signal,\n })\n .then(oauth.processDynamicClientRegistrationResponse);\n }\n catch (err) {\n if (retryable(err, options)) {\n return dynamicClientRegistration(server, metadata, clientAuthentication, {\n ...options,\n flag: retry,\n as,\n });\n }\n errorHandler(err);\n }\n registered[oauth.clockSkew] = clockSkew;\n registered[oauth.clockTolerance] = clockTolerance;\n const instance = new Configuration(as, registered.client_id, registered, clientAuthentication);\n let internals = int(instance);\n if (options?.[customFetch]) {\n internals.fetch = options[customFetch];\n }\n if (options?.timeout !== undefined) {\n internals.timeout = options.timeout;\n }\n if (options?.execute) {\n for (const extension of options.execute) {\n extension(instance);\n }\n }\n return instance;\n}\nexport async function discovery(server, clientId, metadata, clientAuthentication, options) {\n const as = await performDiscovery(server, options);\n const instance = new Configuration(as, clientId, metadata, clientAuthentication);\n let internals = int(instance);\n if (options?.[customFetch]) {\n internals.fetch = options[customFetch];\n }\n if (options?.timeout !== undefined) {\n internals.timeout = options.timeout;\n }\n if (options?.execute) {\n for (const extension of options.execute) {\n extension(instance);\n }\n }\n return instance;\n}\nasync function performDiscovery(server, options) {\n if (!(server instanceof URL)) {\n throw CodedTypeError('\"server\" must be an instance of URL', ERR_INVALID_ARG_TYPE);\n }\n const resolve = !server.href.includes('/.well-known/');\n const timeout = options?.timeout ?? 30;\n const signal = AbortSignal.timeout(timeout * 1000);\n const as = await (resolve\n ? oauth.discoveryRequest(server, {\n algorithm: options?.algorithm,\n [oauth.customFetch]: options?.[customFetch],\n [oauth.allowInsecureRequests]: options?.execute?.includes(allowInsecureRequests),\n signal,\n headers: new Headers(headers),\n })\n : (options?.[customFetch] || fetch)((() => {\n oauth.checkProtocol(server, options?.execute?.includes(allowInsecureRequests) ? false : true);\n return server.href;\n })(), {\n headers: Object.fromEntries(new Headers({ accept: 'application/json', ...headers }).entries()),\n body: undefined,\n method: 'GET',\n redirect: 'manual',\n signal,\n }))\n .then((response) => oauth.processDiscoveryResponse(oauth._nodiscoverycheck, response))\n .catch(errorHandler);\n if (resolve && new URL(as.issuer).href !== server.href) {\n handleEntraId(server, as, options) ||\n handleB2Clogin(server, options) ||\n (() => {\n throw new ClientError('discovered metadata issuer does not match the expected issuer', {\n code: oauth.JSON_ATTRIBUTE_COMPARISON,\n cause: {\n expected: server.href,\n body: as,\n attribute: 'issuer',\n },\n });\n })();\n }\n return as;\n}\nfunction isRsaOaep(input) {\n return input.name === 'RSA-OAEP';\n}\nfunction isEcdh(input) {\n return input.name === 'ECDH';\n}\nconst ecdhEs = 'ECDH-ES';\nconst ecdhEsA128Kw = 'ECDH-ES+A128KW';\nconst ecdhEsA192Kw = 'ECDH-ES+A192KW';\nconst ecdhEsA256Kw = 'ECDH-ES+A256KW';\nfunction checkEcdhAlg(algs, alg, pk) {\n switch (alg) {\n case undefined:\n algs.add(ecdhEs);\n algs.add(ecdhEsA128Kw);\n algs.add(ecdhEsA192Kw);\n algs.add(ecdhEsA256Kw);\n break;\n case ecdhEs:\n case ecdhEsA128Kw:\n case ecdhEsA192Kw:\n case ecdhEsA256Kw:\n algs.add(alg);\n break;\n default:\n throw CodedTypeError('invalid key alg', ERR_INVALID_ARG_VALUE, { pk });\n }\n}\nexport function enableDecryptingResponses(config, contentEncryptionAlgorithms = [\n 'A128GCM',\n 'A192GCM',\n 'A256GCM',\n 'A128CBC-HS256',\n 'A192CBC-HS384',\n 'A256CBC-HS512',\n], ...keys) {\n if (int(config).decrypt !== undefined) {\n throw new TypeError('enableDecryptingResponses can only be called on a given Configuration instance once');\n }\n if (keys.length === 0) {\n throw CodedTypeError('no keys were provided', ERR_INVALID_ARG_VALUE);\n }\n const algs = new Set();\n const normalized = [];\n for (const pk of keys) {\n let key;\n if ('key' in pk) {\n key = { key: pk.key };\n if (typeof pk.alg === 'string')\n key.alg = pk.alg;\n if (typeof pk.kid === 'string')\n key.kid = pk.kid;\n }\n else {\n key = { key: pk };\n }\n if (key.key.type !== 'private') {\n throw CodedTypeError('only private keys must be provided', ERR_INVALID_ARG_VALUE);\n }\n if (isRsaOaep(key.key.algorithm)) {\n switch (key.key.algorithm.hash.name) {\n case 'SHA-1':\n case 'SHA-256':\n case 'SHA-384':\n case 'SHA-512': {\n let alg = 'RSA-OAEP';\n let sha;\n if ((sha = parseInt(key.key.algorithm.hash.name.slice(-3), 10))) {\n alg = `${alg}-${sha}`;\n }\n key.alg ||= alg;\n if (alg !== key.alg)\n throw CodedTypeError('invalid key alg', ERR_INVALID_ARG_VALUE, {\n pk,\n });\n algs.add(key.alg);\n break;\n }\n default:\n throw CodedTypeError('only SHA-512, SHA-384, SHA-256, and SHA-1 RSA-OAEP keys are supported', ERR_INVALID_ARG_VALUE);\n }\n }\n else if (isEcdh(key.key.algorithm)) {\n if (key.key.algorithm.namedCurve !== 'P-256') {\n throw CodedTypeError('Only P-256 ECDH keys are supported', ERR_INVALID_ARG_VALUE);\n }\n checkEcdhAlg(algs, key.alg, pk);\n }\n else if (key.key.algorithm.name === 'X25519') {\n checkEcdhAlg(algs, key.alg, pk);\n }\n else {\n throw CodedTypeError('only RSA-OAEP, ECDH, or X25519 keys are supported', ERR_INVALID_ARG_VALUE);\n }\n normalized.push(key);\n }\n int(config).decrypt = async (jwe) => decrypt(normalized, jwe, contentEncryptionAlgorithms, [...algs]).catch(errorHandler);\n}\nfunction checkCryptoKey(key, alg, epk) {\n if (alg.startsWith('RSA-OAEP')) {\n return key.algorithm.name === 'RSA-OAEP';\n }\n if (alg.startsWith('ECDH-ES')) {\n if (key.algorithm.name !== 'ECDH' && key.algorithm.name !== 'X25519') {\n return false;\n }\n if (key.algorithm.name === 'ECDH') {\n return epk?.crv === key.algorithm.namedCurve;\n }\n if (key.algorithm.name === 'X25519') {\n return epk?.crv === 'X25519';\n }\n }\n return false;\n}\nfunction selectCryptoKeyForDecryption(keys, alg, kid, epk) {\n const { 0: key, length } = keys.filter((key) => {\n if (kid !== undefined && kid !== key.kid) {\n return false;\n }\n if (key.alg && alg !== key.alg) {\n return false;\n }\n return checkCryptoKey(key.key, alg, epk);\n });\n if (!key) {\n throw e('no applicable decryption key selected', undefined, 'OAUTH_DECRYPTION_FAILED');\n }\n if (length !== 1) {\n throw e('multiple applicable decryption keys selected', undefined, 'OAUTH_DECRYPTION_FAILED');\n }\n return key.key;\n}\nasync function decrypt(keys, jwe, contentEncryptionAlgorithms, keyManagementAlgorithms) {\n return decoder.decode((await compactDecrypt(jwe, (header) => {\n const { kid, alg, epk } = header;\n return selectCryptoKeyForDecryption(keys, alg, kid, epk);\n }, { keyManagementAlgorithms, contentEncryptionAlgorithms }).catch((err) => {\n if (err instanceof JOSEError) {\n throw e('decryption failed', err, 'OAUTH_DECRYPTION_FAILED');\n }\n errorHandler(err);\n })).plaintext);\n}\nfunction getServerHelpers(metadata) {\n return {\n supportsPKCE: {\n __proto__: null,\n value(method = 'S256') {\n return (metadata.code_challenge_methods_supported?.includes(method) === true);\n },\n },\n };\n}\nfunction addServerHelpers(metadata) {\n Object.defineProperties(metadata, getServerHelpers(metadata));\n}\nconst kEntraId = Symbol();\nexport class Configuration {\n constructor(server, clientId, metadata, clientAuthentication) {\n if (typeof clientId !== 'string' || !clientId.length) {\n throw CodedTypeError('\"clientId\" must be a non-empty string', ERR_INVALID_ARG_TYPE);\n }\n if (typeof metadata === 'string') {\n metadata = { client_secret: metadata };\n }\n if (metadata?.client_id !== undefined && clientId !== metadata.client_id) {\n throw CodedTypeError('\"clientId\" and \"metadata.client_id\" must be the same', ERR_INVALID_ARG_VALUE);\n }\n const client = {\n ...structuredClone(metadata),\n client_id: clientId,\n };\n client[oauth.clockSkew] = metadata?.[oauth.clockSkew] ?? 0;\n client[oauth.clockTolerance] = metadata?.[oauth.clockTolerance] ?? 30;\n let auth;\n if (clientAuthentication) {\n auth = clientAuthentication;\n }\n else {\n if (typeof client.client_secret === 'string' &&\n client.client_secret.length) {\n auth = ClientSecretPost(client.client_secret);\n }\n else {\n auth = None();\n }\n }\n let c = Object.freeze(client);\n const clone = structuredClone(server);\n if (kEntraId in server) {\n clone[oauth._expectedIssuer] = ({ claims: { tid } }) => server.issuer.replace('{tenantid}', tid);\n }\n let as = Object.freeze(clone);\n props ||= new WeakMap();\n props.set(this, {\n __proto__: null,\n as,\n c,\n auth,\n tlsOnly: true,\n timeout: 30,\n jwksCache: {},\n });\n }\n serverMetadata() {\n const metadata = structuredClone(int(this).as);\n addServerHelpers(metadata);\n return metadata;\n }\n clientMetadata() {\n const metadata = structuredClone(int(this).c);\n return metadata;\n }\n get timeout() {\n return int(this).timeout;\n }\n set timeout(value) {\n int(this).timeout = value;\n }\n get [customFetch]() {\n return int(this).fetch;\n }\n set [customFetch](value) {\n int(this).fetch = value;\n }\n}\nObject.freeze(Configuration.prototype);\nfunction getHelpers(response) {\n let exp = undefined;\n if (response.expires_in !== undefined) {\n exp = Date.now() + response.expires_in * 1000;\n }\n return {\n expiresIn: {\n __proto__: null,\n value() {\n if (exp) {\n const now = Date.now();\n if (exp > now) {\n return Math.floor((exp - now) / 1000);\n }\n return 0;\n }\n return undefined;\n },\n },\n claims: {\n __proto__: null,\n value() {\n return oauth.getValidatedIdTokenClaims(response);\n },\n },\n };\n}\nfunction addHelpers(response) {\n Object.defineProperties(response, getHelpers(response));\n}\nexport function getDPoPHandle(config, keyPair, options) {\n checkConfig(config);\n return oauth.DPoP(int(config).c, keyPair, options);\n}\nasync function handleRetryAfter(response, currentInterval, signal, throwIfInvalid = false) {\n const retryAfter = response.headers.get('retry-after')?.trim();\n if (retryAfter === undefined)\n return;\n let delaySeconds;\n if (/^\\d+$/.test(retryAfter)) {\n delaySeconds = parseInt(retryAfter, 10);\n }\n else {\n const retryDate = new Date(retryAfter);\n if (Number.isFinite(retryDate.getTime())) {\n const now = new Date();\n const delayMs = retryDate.getTime() - now.getTime();\n if (delayMs > 0) {\n delaySeconds = Math.ceil(delayMs / 1000);\n }\n }\n }\n if (throwIfInvalid && !Number.isFinite(delaySeconds)) {\n throw new oauth.OperationProcessingError('invalid Retry-After header value', { cause: response });\n }\n if (delaySeconds > currentInterval) {\n await wait(delaySeconds - currentInterval, signal);\n }\n}\nfunction wait(duration, signal) {\n return new Promise((resolve, reject) => {\n const waitStep = (remaining) => {\n try {\n signal.throwIfAborted();\n }\n catch (err) {\n reject(err);\n return;\n }\n if (remaining <= 0) {\n resolve();\n return;\n }\n const currentWait = Math.min(remaining, 5);\n setTimeout(() => waitStep(remaining - currentWait), currentWait * 1000);\n };\n waitStep(duration);\n });\n}\nfunction pollRequestSignal(pollingSignal, timeout) {\n const timeoutSignal = signal(timeout);\n if (!timeoutSignal) {\n return {\n signal: pollingSignal,\n cleanup() { },\n };\n }\n const controller = new AbortController();\n const abort = (event) => {\n const source = event.target;\n controller.abort(source.reason);\n };\n if (pollingSignal.aborted) {\n controller.abort(pollingSignal.reason);\n }\n else if (timeoutSignal.aborted) {\n controller.abort(timeoutSignal.reason);\n }\n else {\n pollingSignal.addEventListener('abort', abort, { once: true });\n timeoutSignal.addEventListener('abort', abort, { once: true });\n }\n return {\n signal: controller.signal,\n cleanup() {\n pollingSignal.removeEventListener('abort', abort);\n timeoutSignal.removeEventListener('abort', abort);\n },\n };\n}\nasync function pollGrant(config, authorizationResponse, grantCode, request, processResponse, parameters, options) {\n const requestParameters = new URLSearchParams(parameters);\n let interval = authorizationResponse.interval ?? 5;\n const pollingSignal = options?.signal ??\n AbortSignal.timeout(authorizationResponse.expires_in * 1000);\n for (;;) {\n try {\n await wait(interval, pollingSignal);\n }\n catch (error) {\n errorHandler(error);\n }\n const { as, c, auth, fetch, tlsOnly, nonRepudiation, timeout, decrypt } = int(config);\n const requestSignal = pollRequestSignal(pollingSignal, timeout);\n try {\n const response = await request(as, c, auth, grantCode, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n additionalParameters: requestParameters,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: requestSignal.signal,\n }).catch(errorHandler);\n if (response.status === 503 && response.headers.has('retry-after')) {\n await response.body?.cancel();\n await handleRetryAfter(response, interval, pollingSignal, true);\n options = { ...options, flag: undefined };\n continue;\n }\n let result;\n try {\n result = await processResponse(as, c, response, {\n [oauth.jweDecrypt]: decrypt,\n });\n }\n catch (error) {\n if (retryable(error, options)) {\n options = { ...options, flag: retry };\n continue;\n }\n if (error instanceof oauth.ResponseBodyError &&\n (error.error === 'slow_down' ||\n error.error === 'authorization_pending')) {\n if (error.error === 'slow_down')\n interval += 5;\n await handleRetryAfter(error.response, interval, pollingSignal);\n options = { ...options, flag: undefined };\n continue;\n }\n errorHandler(error);\n }\n result.id_token && (await nonRepudiation?.(response));\n addHelpers(result);\n return result;\n }\n finally {\n requestSignal.cleanup();\n }\n }\n}\nexport async function pollDeviceAuthorizationGrant(config, deviceAuthorizationResponse, parameters, options) {\n checkConfig(config);\n return pollGrant(config, deviceAuthorizationResponse, deviceAuthorizationResponse.device_code, oauth.deviceCodeGrantRequest, oauth.processDeviceCodeResponse, parameters, options);\n}\nexport async function initiateDeviceAuthorization(config, parameters) {\n checkConfig(config);\n const { as, c, auth, fetch, tlsOnly, timeout } = int(config);\n return oauth\n .deviceAuthorizationRequest(as, c, auth, parameters, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .then((response) => oauth.processDeviceAuthorizationResponse(as, c, response))\n .catch(errorHandler);\n}\nexport async function initiateBackchannelAuthentication(config, parameters) {\n checkConfig(config);\n const { as, c, auth, fetch, tlsOnly, timeout } = int(config);\n return oauth\n .backchannelAuthenticationRequest(as, c, auth, parameters, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .then((response) => oauth.processBackchannelAuthenticationResponse(as, c, response))\n .catch(errorHandler);\n}\nexport async function pollBackchannelAuthenticationGrant(config, backchannelAuthenticationResponse, parameters, options) {\n checkConfig(config);\n return pollGrant(config, backchannelAuthenticationResponse, backchannelAuthenticationResponse.auth_req_id, oauth.backchannelAuthenticationGrantRequest, oauth.processBackchannelAuthenticationGrantResponse, parameters, options);\n}\nexport function allowInsecureRequests(config) {\n int(config).tlsOnly = false;\n}\nexport function setJwksCache(config, jwksCache) {\n int(config).jwksCache = structuredClone(jwksCache);\n}\nexport function getJwksCache(config) {\n const cache = int(config).jwksCache;\n if (cache.uat) {\n return cache;\n }\n return undefined;\n}\nexport function enableNonRepudiationChecks(config) {\n checkConfig(config);\n int(config).nonRepudiation = (response) => {\n const { as, fetch, tlsOnly, timeout, jwksCache } = int(config);\n return oauth\n .validateApplicationLevelSignature(as, response, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n headers: new Headers(headers),\n signal: signal(timeout),\n [oauth.jwksCache]: jwksCache,\n })\n .catch(errorHandler);\n };\n}\nexport function useJwtResponseMode(config) {\n checkConfig(config);\n const { hybrid, implicit } = int(config);\n if (hybrid || implicit) {\n throw e('JARM cannot be combined with a hybrid or implicit response types', undefined, oauth.UNSUPPORTED_OPERATION);\n }\n int(config).jarm = (authorizationResponse, expectedState) => validateJARMResponse(config, authorizationResponse, expectedState);\n}\nexport function enableDetachedSignatureResponseChecks(config) {\n if (!int(config).hybrid) {\n throw e('\"code id_token\" response type must be configured to be used first', undefined, oauth.UNSUPPORTED_OPERATION);\n }\n int(config).hybrid = (authorizationResponse, expectedNonce, expectedState, maxAge) => validateCodeIdTokenResponse(config, authorizationResponse, expectedNonce, expectedState, maxAge, true);\n}\nexport async function implicitAuthentication(config, currentUrl, expectedNonce, checks) {\n checkConfig(config);\n if (!(currentUrl instanceof URL) &&\n !webInstanceOf(currentUrl, 'Request')) {\n throw CodedTypeError('\"currentUrl\" must be an instance of URL, or Request', ERR_INVALID_ARG_TYPE);\n }\n if (typeof expectedNonce !== 'string') {\n throw CodedTypeError('\"expectedNonce\" must be a string', ERR_INVALID_ARG_TYPE);\n }\n const { as, c, fetch, tlsOnly, timeout, decrypt, implicit, jwksCache } = int(config);\n if (!implicit) {\n throw new TypeError('implicitAuthentication() cannot be used by clients using flows other than response_type=id_token');\n }\n let params;\n if (!(currentUrl instanceof URL)) {\n const request = currentUrl;\n switch (request.method) {\n case 'GET':\n params = new URLSearchParams(new URL(request.url).hash.slice(1));\n break;\n case 'POST':\n params = new URLSearchParams(await oauth.formPostResponse(request));\n break;\n default:\n throw CodedTypeError('unexpected Request HTTP method', ERR_INVALID_ARG_VALUE);\n }\n }\n else {\n params = new URLSearchParams(currentUrl.hash.slice(1));\n }\n try {\n {\n const decoy = new URLSearchParams(params);\n decoy.delete('id_token');\n oauth.validateAuthResponse({\n ...as,\n authorization_response_iss_parameter_supported: undefined,\n }, c, decoy, checks?.expectedState);\n }\n {\n const decoy = new Response(JSON.stringify({\n access_token: 'decoy',\n token_type: 'bearer',\n id_token: params.get('id_token'),\n }), {\n headers: new Headers({ 'content-type': 'application/json' }),\n });\n const ref = await oauth.processAuthorizationCodeResponse(as, c, decoy, {\n expectedNonce,\n maxAge: checks?.maxAge,\n [oauth.jweDecrypt]: decrypt,\n });\n await oauth.validateApplicationLevelSignature(as, decoy, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n headers: new Headers(headers),\n signal: signal(timeout),\n [oauth.jwksCache]: jwksCache,\n });\n return oauth.getValidatedIdTokenClaims(ref);\n }\n }\n catch (err) {\n errorHandler(err);\n }\n}\nexport function useCodeIdTokenResponseType(config) {\n checkConfig(config);\n const { jarm, implicit } = int(config);\n if (jarm || implicit) {\n throw e('\"code id_token\" response type cannot be combined with JARM or implicit response type', undefined, oauth.UNSUPPORTED_OPERATION);\n }\n int(config).hybrid = (authorizationResponse, expectedNonce, expectedState, maxAge) => validateCodeIdTokenResponse(config, authorizationResponse, expectedNonce, expectedState, maxAge, false);\n}\nexport function useIdTokenResponseType(config) {\n checkConfig(config);\n const { jarm, hybrid } = int(config);\n if (jarm || hybrid) {\n throw e('\"id_token\" response type cannot be combined with JARM or hybrid response type', undefined, oauth.UNSUPPORTED_OPERATION);\n }\n int(config).implicit = true;\n}\nfunction stripParams(url) {\n url = new URL(url);\n url.search = '';\n url.hash = '';\n return url.href;\n}\nfunction webInstanceOf(input, toStringTag) {\n try {\n return Object.getPrototypeOf(input)[Symbol.toStringTag] === toStringTag;\n }\n catch {\n return false;\n }\n}\nexport async function authorizationCodeGrant(config, currentUrl, checks, tokenEndpointParameters, options) {\n checkConfig(config);\n if (options?.flag !== retry &&\n !(currentUrl instanceof URL) &&\n !webInstanceOf(currentUrl, 'Request')) {\n throw CodedTypeError('\"currentUrl\" must be an instance of URL, or Request', ERR_INVALID_ARG_TYPE);\n }\n let authResponse;\n let redirectUri;\n const { as, c, auth, fetch, tlsOnly, jarm, hybrid, nonRepudiation, timeout, decrypt, implicit } = int(config);\n if (options?.flag === retry) {\n authResponse = options.authResponse;\n redirectUri = options.redirectUri;\n }\n else {\n if (!(currentUrl instanceof URL)) {\n const request = currentUrl;\n currentUrl = new URL(currentUrl.url);\n switch (request.method) {\n case 'GET':\n break;\n case 'POST':\n const params = new URLSearchParams(await oauth.formPostResponse(request));\n if (hybrid) {\n currentUrl.hash = params.toString();\n }\n else {\n for (const [k, v] of params.entries()) {\n currentUrl.searchParams.append(k, v);\n }\n }\n break;\n default:\n throw CodedTypeError('unexpected Request HTTP method', ERR_INVALID_ARG_VALUE);\n }\n }\n redirectUri = stripParams(currentUrl);\n switch (true) {\n case !!jarm:\n authResponse = await jarm(currentUrl, checks?.expectedState);\n break;\n case !!hybrid:\n authResponse = await hybrid(currentUrl, checks?.expectedNonce, checks?.expectedState, checks?.maxAge);\n break;\n case !!implicit:\n throw new TypeError('authorizationCodeGrant() cannot be used by response_type=id_token clients');\n default:\n try {\n authResponse = oauth.validateAuthResponse(as, c, currentUrl.searchParams, checks?.expectedState);\n }\n catch (err) {\n errorHandler(err);\n }\n }\n }\n const response = await oauth\n .authorizationCodeGrantRequest(as, c, auth, authResponse, redirectUri, checks?.pkceCodeVerifier || oauth.nopkce, {\n additionalParameters: tokenEndpointParameters,\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .catch(errorHandler);\n if (typeof checks?.expectedNonce === 'string' ||\n typeof checks?.maxAge === 'number') {\n checks.idTokenExpected = true;\n }\n const p = oauth.processAuthorizationCodeResponse(as, c, response, {\n expectedNonce: checks?.expectedNonce,\n maxAge: checks?.maxAge,\n requireIdToken: checks?.idTokenExpected,\n [oauth.jweDecrypt]: decrypt,\n });\n let result;\n try {\n result = await p;\n }\n catch (err) {\n if (retryable(err, options)) {\n return authorizationCodeGrant(config, undefined, checks, tokenEndpointParameters, {\n ...options,\n flag: retry,\n authResponse: authResponse,\n redirectUri: redirectUri,\n });\n }\n errorHandler(err);\n }\n result.id_token && (await nonRepudiation?.(response));\n addHelpers(result);\n return result;\n}\nasync function validateJARMResponse(config, authorizationResponse, expectedState) {\n const { as, c, fetch, tlsOnly, timeout, decrypt, jwksCache } = int(config);\n return oauth\n .validateJwtAuthResponse(as, c, authorizationResponse, expectedState, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n headers: new Headers(headers),\n signal: signal(timeout),\n [oauth.jweDecrypt]: decrypt,\n [oauth.jwksCache]: jwksCache,\n })\n .catch(errorHandler);\n}\nasync function validateCodeIdTokenResponse(config, authorizationResponse, expectedNonce, expectedState, maxAge, fapi) {\n if (typeof expectedNonce !== 'string') {\n throw CodedTypeError('\"expectedNonce\" must be a string', ERR_INVALID_ARG_TYPE);\n }\n if (expectedState !== undefined && typeof expectedState !== 'string') {\n throw CodedTypeError('\"expectedState\" must be a string', ERR_INVALID_ARG_TYPE);\n }\n const { as, c, fetch, tlsOnly, timeout, decrypt, jwksCache } = int(config);\n return (fapi\n ? oauth.validateDetachedSignatureResponse\n : oauth.validateCodeIdTokenResponse)(as, c, authorizationResponse, expectedNonce, expectedState, maxAge, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n headers: new Headers(headers),\n signal: signal(timeout),\n [oauth.jweDecrypt]: decrypt,\n [oauth.jwksCache]: jwksCache,\n }).catch(errorHandler);\n}\nexport async function refreshTokenGrant(config, refreshToken, parameters, options) {\n checkConfig(config);\n parameters = new URLSearchParams(parameters);\n const { as, c, auth, fetch, tlsOnly, nonRepudiation, timeout, decrypt } = int(config);\n const response = await oauth\n .refreshTokenGrantRequest(as, c, auth, refreshToken, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n additionalParameters: parameters,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .catch(errorHandler);\n const p = oauth.processRefreshTokenResponse(as, c, response, {\n [oauth.jweDecrypt]: decrypt,\n });\n let result;\n try {\n result = await p;\n }\n catch (err) {\n if (retryable(err, options)) {\n return refreshTokenGrant(config, refreshToken, parameters, {\n ...options,\n flag: retry,\n });\n }\n errorHandler(err);\n }\n result.id_token && (await nonRepudiation?.(response));\n addHelpers(result);\n return result;\n}\nexport async function clientCredentialsGrant(config, parameters, options) {\n checkConfig(config);\n parameters = new URLSearchParams(parameters);\n const { as, c, auth, fetch, tlsOnly, timeout } = int(config);\n const response = await oauth\n .clientCredentialsGrantRequest(as, c, auth, parameters, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .catch(errorHandler);\n const p = oauth.processClientCredentialsResponse(as, c, response);\n let result;\n try {\n result = await p;\n }\n catch (err) {\n if (retryable(err, options)) {\n return clientCredentialsGrant(config, parameters, {\n ...options,\n flag: retry,\n });\n }\n errorHandler(err);\n }\n addHelpers(result);\n return result;\n}\nexport function buildAuthorizationUrl(config, parameters) {\n checkConfig(config);\n const { as, c, tlsOnly, hybrid, jarm, implicit } = int(config);\n const authorizationEndpoint = oauth.resolveEndpoint(as, 'authorization_endpoint', false, tlsOnly);\n parameters = new URLSearchParams(parameters);\n if (!parameters.has('client_id')) {\n parameters.set('client_id', c.client_id);\n }\n if (!parameters.has('request_uri') && !parameters.has('request')) {\n if (!parameters.has('response_type')) {\n parameters.set('response_type', hybrid ? 'code id_token' : implicit ? 'id_token' : 'code');\n }\n if (implicit && !parameters.has('nonce')) {\n throw CodedTypeError('response_type=id_token clients must provide a nonce parameter in their authorization request parameters', ERR_INVALID_ARG_VALUE);\n }\n if (jarm) {\n parameters.set('response_mode', 'jwt');\n }\n }\n for (const [k, v] of parameters.entries()) {\n authorizationEndpoint.searchParams.append(k, v);\n }\n return authorizationEndpoint;\n}\nexport async function buildAuthorizationUrlWithJAR(config, parameters, signingKey, options) {\n checkConfig(config);\n const authorizationEndpoint = buildAuthorizationUrl(config, parameters);\n parameters = authorizationEndpoint.searchParams;\n if (!signingKey) {\n throw CodedTypeError('\"signingKey\" must be provided', ERR_INVALID_ARG_VALUE);\n }\n const { as, c } = int(config);\n const request = await oauth\n .issueRequestObject(as, c, parameters, signingKey, options)\n .catch(errorHandler);\n return buildAuthorizationUrl(config, { request });\n}\nexport async function buildAuthorizationUrlWithPAR(config, parameters, options) {\n checkConfig(config);\n const authorizationEndpoint = buildAuthorizationUrl(config, parameters);\n const { as, c, auth, fetch, tlsOnly, timeout } = int(config);\n const response = await oauth\n .pushedAuthorizationRequest(as, c, auth, authorizationEndpoint.searchParams, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .catch(errorHandler);\n const p = oauth.processPushedAuthorizationResponse(as, c, response);\n let result;\n try {\n result = await p;\n }\n catch (err) {\n if (retryable(err, options)) {\n return buildAuthorizationUrlWithPAR(config, parameters, {\n ...options,\n flag: retry,\n });\n }\n errorHandler(err);\n }\n return buildAuthorizationUrl(config, { request_uri: result.request_uri });\n}\nexport function buildEndSessionUrl(config, parameters) {\n checkConfig(config);\n const { as, c, tlsOnly } = int(config);\n const endSessionEndpoint = oauth.resolveEndpoint(as, 'end_session_endpoint', false, tlsOnly);\n parameters = new URLSearchParams(parameters);\n if (!parameters.has('client_id')) {\n parameters.set('client_id', c.client_id);\n }\n for (const [k, v] of parameters.entries()) {\n endSessionEndpoint.searchParams.append(k, v);\n }\n return endSessionEndpoint;\n}\nfunction checkConfig(input) {\n if (!(input instanceof Configuration)) {\n throw CodedTypeError('\"config\" must be an instance of Configuration', ERR_INVALID_ARG_TYPE);\n }\n if (Object.getPrototypeOf(input) !== Configuration.prototype) {\n throw CodedTypeError('subclassing Configuration is not allowed', ERR_INVALID_ARG_VALUE);\n }\n}\nfunction signal(timeout) {\n return timeout ? AbortSignal.timeout(timeout * 1000) : undefined;\n}\nexport async function fetchUserInfo(config, accessToken, expectedSubject, options) {\n checkConfig(config);\n const { as, c, fetch, tlsOnly, nonRepudiation, timeout, decrypt } = int(config);\n const response = await oauth\n .userInfoRequest(as, c, accessToken, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .catch(errorHandler);\n let exec = oauth.processUserInfoResponse(as, c, expectedSubject, response, {\n [oauth.jweDecrypt]: decrypt,\n });\n let result;\n try {\n result = await exec;\n }\n catch (err) {\n if (retryable(err, options)) {\n return fetchUserInfo(config, accessToken, expectedSubject, {\n ...options,\n flag: retry,\n });\n }\n errorHandler(err);\n }\n oauth.getContentType(response) === 'application/jwt' &&\n (await nonRepudiation?.(response));\n return result;\n}\nfunction retryable(err, options) {\n if (options?.DPoP && options.flag !== retry) {\n return oauth.isDPoPNonceError(err);\n }\n return false;\n}\nexport async function tokenIntrospection(config, token, parameters) {\n checkConfig(config);\n const { as, c, auth, fetch, tlsOnly, nonRepudiation, timeout, decrypt } = int(config);\n const response = await oauth\n .introspectionRequest(as, c, auth, token, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n additionalParameters: new URLSearchParams(parameters),\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .catch(errorHandler);\n const result = await oauth\n .processIntrospectionResponse(as, c, response, {\n [oauth.jweDecrypt]: decrypt,\n })\n .catch(errorHandler);\n oauth.getContentType(response) === 'application/token-introspection+jwt' &&\n (await nonRepudiation?.(response));\n return result;\n}\nconst retry = Symbol();\nexport async function genericGrantRequest(config, grantType, parameters, options) {\n checkConfig(config);\n const { as, c, auth, fetch, tlsOnly, timeout, decrypt, nonRepudiation } = int(config);\n const response = await oauth\n .genericTokenEndpointRequest(as, c, auth, grantType, new URLSearchParams(parameters), {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .catch(errorHandler);\n let recognizedTokenTypes;\n if (grantType === 'urn:ietf:params:oauth:grant-type:token-exchange') {\n recognizedTokenTypes = { n_a: () => { } };\n }\n const p = oauth.processGenericTokenEndpointResponse(as, c, response, {\n [oauth.jweDecrypt]: decrypt,\n recognizedTokenTypes,\n });\n let result;\n try {\n result = await p;\n }\n catch (err) {\n if (retryable(err, options)) {\n return genericGrantRequest(config, grantType, parameters, {\n ...options,\n flag: retry,\n });\n }\n errorHandler(err);\n }\n result.id_token && (await nonRepudiation?.(response));\n addHelpers(result);\n return result;\n}\nexport async function tokenRevocation(config, token, parameters) {\n checkConfig(config);\n const { as, c, auth, fetch, tlsOnly, timeout } = int(config);\n return oauth\n .revocationRequest(as, c, auth, token, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n additionalParameters: new URLSearchParams(parameters),\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .then(oauth.processRevocationResponse)\n .catch(errorHandler);\n}\nexport async function fetchProtectedResource(config, accessToken, url, method, body, headers, options) {\n checkConfig(config);\n headers ||= new Headers();\n if (USER_AGENT && !headers.has('user-agent')) {\n headers.set('user-agent', USER_AGENT);\n }\n const { fetch, tlsOnly, timeout } = int(config);\n const exec = oauth.protectedResourceRequest(accessToken, method, url, headers, body, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n DPoP: options?.DPoP,\n signal: signal(timeout),\n });\n let result;\n try {\n result = await exec;\n }\n catch (err) {\n if (retryable(err, options)) {\n return fetchProtectedResource(config, accessToken, url, method, body, headers, {\n ...options,\n flag: retry,\n });\n }\n errorHandler(err);\n }\n return result;\n}\n//# sourceMappingURL=index.js.map","import * as oidc from \"openid-client\";\nimport {\n\ttype CoordinatorAccountReference,\n\tisCoordinatorAccountIssuer,\n\tparseCoordinatorAccountReference,\n} from \"./coordinator-auth-contract.js\";\n\nexport interface CoordinatorOidcProviderConfig {\n\tissuer: string;\n\tclientId: string;\n\tclientSecret: string;\n\tredirectUri: string;\n}\n\n/** Trusted transport options, not a JSON configuration surface. */\nexport interface CoordinatorOidcOptions {\n\tfetch?: oidc.CustomFetch;\n\ttimeoutSeconds?: number;\n}\n\n/** Secret transaction material: keep server-side, never in browser JSON. */\nexport type CoordinatorOidcMaterial = { state: string; nonce: string; pkceVerifier: string };\n\n/** Display metadata only; these fields never grant permissions. */\nexport interface CoordinatorOidcProfile {\n\tdisplayName?: string;\n\temail?: string;\n\temailVerified?: boolean;\n\tpictureUrl?: string;\n}\n\ntype CallbackResult =\n\t| { ok: true; account: CoordinatorAccountReference; profile: CoordinatorOidcProfile }\n\t| { ok: false; error: \"invalid_callback\" | \"oidc_verification_failed\" };\n\nexport interface CoordinatorOidcClient {\n\tcreateAuthorizationRequest(): Promise<{\n\t\tauthorizationUrl: string;\n\t\tmaterial: CoordinatorOidcMaterial;\n\t}>;\n\tverifyCallback(\n\t\tinput: { callbackUrl: string; material: CoordinatorOidcMaterial },\n\t\toptions?: { fetchUserInfo?: boolean },\n\t): Promise<CallbackResult>;\n}\n\nconst CONTROL = /[\\p{Cc}\\p{Cf}\\p{Cs}]/u;\nconst MATERIAL = /^[A-Za-z0-9._~-]{43,128}$/;\n\nfunction capture(value: unknown, keys: string[]): Record<string, unknown> {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) throw new Error();\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (prototype !== Object.prototype && prototype !== null) throw new Error();\n\tconst result: Record<string, unknown> = {};\n\tfor (const key of keys) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\tif (descriptor && !Object.hasOwn(descriptor, \"value\")) throw new Error();\n\t\tresult[key] = descriptor?.value;\n\t}\n\treturn result;\n}\n\nfunction httpsUrl(value: unknown, options: { allowQuery: boolean }): URL | undefined {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\tvalue !== value.trim() ||\n\t\tCONTROL.test(value) ||\n\t\tvalue.includes(\"\\\\\") ||\n\t\tvalue.includes(\"#\") ||\n\t\t(!options.allowQuery && value.includes(\"?\")) ||\n\t\t!/^https:\\/\\//i.test(value)\n\t)\n\t\treturn undefined;\n\ttry {\n\t\tconst url = new URL(value);\n\t\tif (url.protocol !== \"https:\" || !url.hostname || url.username || url.password || url.hash) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn url;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction credential(value: unknown, maximum: number): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length <= maximum &&\n\t\tvalue.trim().length > 0 &&\n\t\tvalue.trim() === value &&\n\t\t!CONTROL.test(value)\n\t);\n}\n\nfunction captureConfiguration(config: unknown, options: unknown) {\n\tconst c = capture(config, [\"issuer\", \"clientId\", \"clientSecret\", \"redirectUri\"]);\n\tconst o = capture(options === undefined ? {} : options, [\"fetch\", \"timeoutSeconds\"]);\n\tconst redirect = httpsUrl(c.redirectUri, { allowQuery: false });\n\tif (\n\t\t!isCoordinatorAccountIssuer(c.issuer) ||\n\t\t!httpsUrl(c.issuer, { allowQuery: false }) ||\n\t\t!credential(c.clientId, 256) ||\n\t\t!credential(c.clientSecret, 4096) ||\n\t\ttypeof c.redirectUri !== \"string\" ||\n\t\t!redirect ||\n\t\tredirect.href !== c.redirectUri ||\n\t\t(o.fetch !== undefined && typeof o.fetch !== \"function\")\n\t)\n\t\tthrow new Error();\n\tconst timeout = o.timeoutSeconds === undefined ? 10 : o.timeoutSeconds;\n\tif (typeof timeout !== \"number\" || !Number.isFinite(timeout) || timeout < 1 || timeout > 30) {\n\t\tthrow new Error();\n\t}\n\treturn {\n\t\tissuer: c.issuer,\n\t\tclientId: c.clientId,\n\t\tclientSecret: c.clientSecret,\n\t\tredirectUri: c.redirectUri,\n\t\tfetch: o.fetch as oidc.CustomFetch | undefined,\n\t\ttimeout,\n\t};\n}\n\nfunction validateMetadata(config: oidc.Configuration, issuer: string): void {\n\tconst metadata = config.serverMetadata();\n\tif (metadata.issuer !== issuer) throw new Error();\n\tfor (const endpoint of [\n\t\tmetadata.authorization_endpoint,\n\t\tmetadata.token_endpoint,\n\t\tmetadata.jwks_uri,\n\t]) {\n\t\tif (!httpsUrl(endpoint, { allowQuery: true })) throw new Error();\n\t}\n\tif (\n\t\tmetadata.userinfo_endpoint !== undefined &&\n\t\t!httpsUrl(metadata.userinfo_endpoint, { allowQuery: true })\n\t)\n\t\tthrow new Error();\n}\n\nfunction captureCallback(input: unknown, options: unknown, redirectUri: string) {\n\tconst i = capture(input, [\"callbackUrl\", \"material\"]);\n\tconst m = capture(i.material, [\"state\", \"nonce\", \"pkceVerifier\"]);\n\tconst o = capture(options === undefined ? {} : options, [\"fetchUserInfo\"]);\n\tif (o.fetchUserInfo !== undefined && typeof o.fetchUserInfo !== \"boolean\") throw new Error();\n\tif (\n\t\ttypeof m.state !== \"string\" ||\n\t\t!MATERIAL.test(m.state) ||\n\t\ttypeof m.nonce !== \"string\" ||\n\t\t!MATERIAL.test(m.nonce) ||\n\t\ttypeof m.pkceVerifier !== \"string\" ||\n\t\t!MATERIAL.test(m.pkceVerifier)\n\t)\n\t\tthrow new Error();\n\tconst url = httpsUrl(i.callbackUrl, { allowQuery: true });\n\tconst redirect = new URL(redirectUri);\n\tif (!url || url.origin !== redirect.origin || url.pathname !== redirect.pathname)\n\t\tthrow new Error();\n\treturn {\n\t\turl,\n\t\tstate: m.state,\n\t\tnonce: m.nonce,\n\t\tpkceVerifier: m.pkceVerifier,\n\t\tfetchUserInfo: o.fetchUserInfo === true,\n\t};\n}\n\nfunction displayString(value: unknown, maximum: number): value is string {\n\treturn (\n\t\ttypeof value === \"string\" && value.length > 0 && value.length <= maximum && !CONTROL.test(value)\n\t);\n}\n\nfunction projectProfile(claims: unknown): CoordinatorOidcProfile {\n\tconst c = capture(claims, [\"name\", \"email\", \"email_verified\", \"picture\"]);\n\tconst profile: CoordinatorOidcProfile = {};\n\tif (displayString(c.name, 256)) profile.displayName = c.name;\n\tif (displayString(c.email, 320)) profile.email = c.email;\n\tif (profile.email !== undefined && typeof c.email_verified === \"boolean\") {\n\t\tprofile.emailVerified = c.email_verified;\n\t}\n\t// Rendering needs its own image policy; this adapter never fetches pictures.\n\tif (displayString(c.picture, 2048) && httpsUrl(c.picture, { allowQuery: true })) {\n\t\tprofile.pictureUrl = c.picture;\n\t}\n\treturn profile;\n}\n\nfunction mergeProfile(\n\tprofile: CoordinatorOidcProfile,\n\textra: CoordinatorOidcProfile,\n): CoordinatorOidcProfile {\n\tconst merged = { ...profile, ...extra };\n\tif (extra.email !== undefined && extra.emailVerified === undefined) delete merged.emailVerified;\n\treturn merged;\n}\n\nasync function authorizationRequest(config: oidc.Configuration, redirectUri: string) {\n\ttry {\n\t\tconst material = {\n\t\t\tstate: oidc.randomState(),\n\t\t\tnonce: oidc.randomNonce(),\n\t\t\tpkceVerifier: oidc.randomPKCECodeVerifier(),\n\t\t};\n\t\tconst challenge = await oidc.calculatePKCECodeChallenge(material.pkceVerifier);\n\t\tconst url = oidc.buildAuthorizationUrl(config, {\n\t\t\tredirect_uri: redirectUri,\n\t\t\tresponse_type: \"code\",\n\t\t\tscope: \"openid email profile\",\n\t\t\tstate: material.state,\n\t\t\tnonce: material.nonce,\n\t\t\tcode_challenge: challenge,\n\t\t\tcode_challenge_method: \"S256\",\n\t\t\tresponse_mode: \"query\",\n\t\t\taccess_type: \"online\",\n\t\t});\n\t\treturn { authorizationUrl: url.href, material };\n\t} catch {\n\t\tthrow new Error(\"oidc_request_failed\");\n\t}\n}\n\nfunction adapter(\n\tconfig: oidc.Configuration,\n\tissuer: string,\n\tredirectUri: string,\n): CoordinatorOidcClient {\n\treturn {\n\t\tcreateAuthorizationRequest: () => authorizationRequest(config, redirectUri),\n\t\tasync verifyCallback(input, options): Promise<CallbackResult> {\n\t\t\tlet callback: ReturnType<typeof captureCallback>;\n\t\t\ttry {\n\t\t\t\tcallback = captureCallback(input, options, redirectUri);\n\t\t\t} catch {\n\t\t\t\treturn { ok: false, error: \"invalid_callback\" };\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst tokens = await oidc.authorizationCodeGrant(config, callback.url, {\n\t\t\t\t\tpkceCodeVerifier: callback.pkceVerifier,\n\t\t\t\t\texpectedState: callback.state,\n\t\t\t\t\texpectedNonce: callback.nonce,\n\t\t\t\t\tidTokenExpected: true,\n\t\t\t\t});\n\t\t\t\tconst claims = tokens.claims();\n\t\t\t\tif (!claims || claims.iss !== issuer) throw new Error();\n\t\t\t\tconst reference = parseCoordinatorAccountReference(\n\t\t\t\t\t{ issuer: claims.iss, subject: claims.sub },\n\t\t\t\t\t{ issuer },\n\t\t\t\t);\n\t\t\t\tif (!reference.ok) throw new Error();\n\t\t\t\tlet profile = projectProfile(claims);\n\t\t\t\tif (callback.fetchUserInfo) {\n\t\t\t\t\tconst userInfo = await oidc.fetchUserInfo(\n\t\t\t\t\t\tconfig,\n\t\t\t\t\t\ttokens.access_token,\n\t\t\t\t\t\treference.account.subject,\n\t\t\t\t\t);\n\t\t\t\t\tprofile = mergeProfile(profile, projectProfile(userInfo));\n\t\t\t\t}\n\t\t\t\treturn { ok: true, account: { ...reference.account }, profile };\n\t\t\t} catch {\n\t\t\t\treturn { ok: false, error: \"oidc_verification_failed\" };\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * Proof verification only. Durable transaction consumption and browser binding\n * belong to the caller; an in-memory replay set cannot replace those checks.\n */\nexport async function createCoordinatorOidcClient(\n\tconfig: CoordinatorOidcProviderConfig,\n\toptions?: CoordinatorOidcOptions,\n): Promise<\n\t| { ok: true; client: CoordinatorOidcClient }\n\t| { ok: false; error: \"invalid_provider_configuration\" | \"oidc_discovery_failed\" }\n> {\n\tlet captured: ReturnType<typeof captureConfiguration>;\n\ttry {\n\t\tcaptured = captureConfiguration(config, options);\n\t} catch {\n\t\treturn { ok: false, error: \"invalid_provider_configuration\" };\n\t}\n\ttry {\n\t\tconst privateConfig = await oidc.discovery(\n\t\t\tnew URL(captured.issuer),\n\t\t\tcaptured.clientId,\n\t\t\t{\n\t\t\t\tclient_secret: captured.clientSecret,\n\t\t\t\tid_token_signed_response_alg: \"RS256\",\n\t\t\t\t[oidc.clockTolerance]: 0,\n\t\t\t},\n\t\t\toidc.ClientSecretPost(captured.clientSecret),\n\t\t\t{\n\t\t\t\t[oidc.customFetch]: captured.fetch,\n\t\t\t\ttimeout: captured.timeout,\n\t\t\t\texecute: [oidc.enableNonRepudiationChecks],\n\t\t\t},\n\t\t);\n\t\tvalidateMetadata(privateConfig, captured.issuer);\n\t\treturn { ok: true, client: adapter(privateConfig, captured.issuer, captured.redirectUri) };\n\t} catch {\n\t\treturn { ok: false, error: \"oidc_discovery_failed\" };\n\t}\n}\n","/** Lifecycle state only, not historical provenance or current device authority.\n * Callers must also validate the link's full authority-specific proof.\n */\nexport function authLinkLiveGenerationSql(options: {\n\tlink: \"l\" | \"cl\";\n\tconnections?: true;\n}): string {\n\tconst link = options.link;\n\tif (link !== \"l\" && link !== \"cl\") throw new Error(\"auth_link_alias_invalid\");\n\t// The complete connection schema retains disconnected generations in history,\n\t// not as ended rows in the current table. Callers must check full readiness;\n\t// this is an explicit storage representation, never a partial-schema fallback.\n\tif (options.connections)\n\t\treturn `(${link}.revoked_at_ms IS NULL\n AND EXISTS (SELECT 1 FROM coordinator_auth_account_links current_generation\n WHERE current_generation.coordinator_id=${link}.coordinator_id AND current_generation.link_id=${link}.link_id\n AND current_generation.identity_id=${link}.identity_id AND current_generation.issuer=${link}.issuer\n AND current_generation.subject=${link}.subject AND current_generation.revoked_at_ms IS NULL)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history barrier\n WHERE barrier.coordinator_id=${link}.coordinator_id AND barrier.identity_id=${link}.identity_id AND barrier.revoked_at_ms IS NOT NULL))`;\n\treturn `(${link}.revoked_at_ms IS NULL AND ${link}.ended_at_ms IS NULL\n AND EXISTS (SELECT 1 FROM coordinator_auth_account_associations live_association\n WHERE live_association.coordinator_id = ${link}.coordinator_id\n AND live_association.issuer = ${link}.issuer AND live_association.subject = ${link}.subject\n AND live_association.identity_id = ${link}.identity_id)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_account_links security_barrier\n WHERE security_barrier.coordinator_id = ${link}.coordinator_id\n AND security_barrier.identity_id = ${link}.identity_id\n AND security_barrier.revoked_at_ms IS NOT NULL))`;\n}\n","/**\n * Inert storage only, not an issuer or proof of authority. Future issuance must\n * resolve every fact server-side from the exact link, claim and genuine review.\n * No subject/email copy or cascading references: historical evidence survives\n * removal or revocation of the original device. Nothing installs this on open.\n */\nexport interface CoordinatorOwnerEnrollmentQualificationRow {\n\treadonly qualification_id: string;\n\treadonly coordinator_id: string;\n\treadonly link_id: string;\n\treadonly device_claim_id: string;\n\treadonly identity_id: string;\n\treadonly source_group_id: string;\n\treadonly device_id: string;\n\treadonly public_key: string;\n\treadonly fingerprint: string;\n\treadonly key_id: string;\n\treadonly controller_attestation_id: string;\n\treadonly controller_attestation_revision: number;\n\treadonly controller_attestation_created_at: string;\n\treadonly review_receipt_id: string;\n\treadonly evidence_digest: string;\n\treadonly enrollment_identity_id: string | null;\n\treadonly link_attempt_id: string;\n\treadonly link_auth_config_revision: string;\n\treadonly link_created_at_ms: number;\n\treadonly created_at_ms: number;\n\treadonly revoked_at_ms: number | null;\n}\n\n// Separate complete statements allow native D1 batches without splitting triggers.\nexport const COORDINATOR_OWNER_ENROLLMENT_QUALIFICATION_SCHEMA_STATEMENTS = [\n\t`\nCREATE TABLE IF NOT EXISTS coordinator_owner_enrollment_qualifications (\n qualification_id TEXT PRIMARY KEY NOT NULL CHECK (typeof(qualification_id) = 'text' AND length(qualification_id) BETWEEN 1 AND 256 AND qualification_id = trim(qualification_id) AND length(trim(qualification_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(qualification_id, char(0)) = 0),\n coordinator_id TEXT NOT NULL CHECK (typeof(coordinator_id) = 'text' AND length(coordinator_id) BETWEEN 1 AND 256 AND coordinator_id = trim(coordinator_id) AND length(trim(coordinator_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(coordinator_id, char(0)) = 0),\n link_id TEXT NOT NULL CHECK (typeof(link_id) = 'text' AND length(link_id) BETWEEN 1 AND 256 AND link_id = trim(link_id) AND length(trim(link_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(link_id, char(0)) = 0),\n device_claim_id TEXT NOT NULL CHECK (typeof(device_claim_id) = 'text' AND length(device_claim_id) BETWEEN 1 AND 256 AND device_claim_id = trim(device_claim_id) AND length(trim(device_claim_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(device_claim_id, char(0)) = 0),\n identity_id TEXT NOT NULL CHECK (typeof(identity_id) = 'text' AND length(identity_id) BETWEEN 1 AND 256 AND identity_id = trim(identity_id) AND length(trim(identity_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(identity_id, char(0)) = 0),\n source_group_id TEXT NOT NULL CHECK (typeof(source_group_id) = 'text' AND length(source_group_id) BETWEEN 1 AND 256 AND source_group_id = trim(source_group_id) AND length(trim(source_group_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(source_group_id, char(0)) = 0),\n device_id TEXT NOT NULL CHECK (typeof(device_id) = 'text' AND length(device_id) BETWEEN 1 AND 256 AND device_id = trim(device_id) AND length(trim(device_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(device_id, char(0)) = 0),\n public_key TEXT NOT NULL CHECK (typeof(public_key) = 'text' AND length(public_key) BETWEEN 1 AND 4096 AND length(trim(public_key, char(9)||char(10)||char(13)||' ')) > 0 AND instr(public_key, char(0)) = 0),\n fingerprint TEXT NOT NULL CHECK (typeof(fingerprint) = 'text' AND length(fingerprint) = 64 AND fingerprint NOT GLOB '*[^0-9a-f]*' AND instr(fingerprint, char(0)) = 0),\n key_id TEXT NOT NULL CHECK (typeof(key_id) = 'text' AND length(key_id) = 64 AND key_id NOT GLOB '*[^0-9a-f]*' AND instr(key_id, char(0)) = 0),\n controller_attestation_id TEXT NOT NULL CHECK (typeof(controller_attestation_id) = 'text' AND length(controller_attestation_id) BETWEEN 1 AND 256 AND controller_attestation_id = trim(controller_attestation_id) AND length(trim(controller_attestation_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(controller_attestation_id, char(0)) = 0),\n controller_attestation_revision INTEGER NOT NULL CHECK (typeof(controller_attestation_revision) = 'integer' AND controller_attestation_revision = 1),\n controller_attestation_created_at TEXT NOT NULL CHECK (typeof(controller_attestation_created_at) = 'text' AND length(trim(controller_attestation_created_at, char(9)||char(10)||char(13)||' ')) > 0 AND instr(controller_attestation_created_at, char(0)) = 0),\n review_receipt_id TEXT NOT NULL CHECK (typeof(review_receipt_id) = 'text' AND length(review_receipt_id) BETWEEN 1 AND 256 AND review_receipt_id = trim(review_receipt_id) AND length(trim(review_receipt_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(review_receipt_id, char(0)) = 0),\n evidence_digest TEXT NOT NULL CHECK (typeof(evidence_digest) = 'text' AND length(evidence_digest) = 64 AND evidence_digest NOT GLOB '*[^0-9a-f]*' AND instr(evidence_digest, char(0)) = 0),\n enrollment_identity_id TEXT CHECK (enrollment_identity_id IS NULL OR (typeof(enrollment_identity_id) = 'text' AND length(enrollment_identity_id) BETWEEN 1 AND 256 AND enrollment_identity_id = trim(enrollment_identity_id) AND length(trim(enrollment_identity_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(enrollment_identity_id, char(0)) = 0)),\n link_attempt_id TEXT NOT NULL CHECK (typeof(link_attempt_id) = 'text' AND length(link_attempt_id) BETWEEN 1 AND 256 AND link_attempt_id = trim(link_attempt_id) AND length(trim(link_attempt_id, char(9)||char(10)||char(13)||' ')) > 0 AND instr(link_attempt_id, char(0)) = 0),\n link_auth_config_revision TEXT NOT NULL CHECK (typeof(link_auth_config_revision) = 'text' AND length(link_auth_config_revision) = 64 AND link_auth_config_revision NOT GLOB '*[^0-9a-f]*' AND instr(link_auth_config_revision, char(0)) = 0),\n link_created_at_ms INTEGER NOT NULL CHECK (typeof(link_created_at_ms) = 'integer' AND link_created_at_ms BETWEEN 0 AND 9007199254740991),\n created_at_ms INTEGER NOT NULL CHECK (typeof(created_at_ms) = 'integer' AND created_at_ms BETWEEN link_created_at_ms AND 9007199254740991),\n revoked_at_ms INTEGER CHECK (revoked_at_ms IS NULL OR (typeof(revoked_at_ms) = 'integer' AND revoked_at_ms BETWEEN created_at_ms AND 9007199254740991)),\n UNIQUE (coordinator_id, link_id)\n) WITHOUT ROWID;\n`,\n\t`\n-- Qualifications are born active; revocation requires an explicit UPDATE.\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_qualification_insert_active\nBEFORE INSERT ON coordinator_owner_enrollment_qualifications\nWHEN NEW.revoked_at_ms IS NOT NULL\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_qualification_birth_revoked'); END;\n`,\n\t`\n-- Each collision probe uses a unique index, never a coordinator-wide OR scan.\n-- Reject even same-value UPSERT/REPLACE: revocation must use explicit UPDATE.\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_qualification_insert_collision\nBEFORE INSERT ON coordinator_owner_enrollment_qualifications\nWHEN EXISTS (SELECT 1 FROM coordinator_owner_enrollment_qualifications WHERE qualification_id = NEW.qualification_id)\n OR EXISTS (SELECT 1 FROM coordinator_owner_enrollment_qualifications WHERE coordinator_id = NEW.coordinator_id AND link_id = NEW.link_id)\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_qualification_collision'); END;\n`,\n\t`\n-- Compare storage classes explicitly, including the nullable enrollment snapshot.\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_qualification_immutable_update\nBEFORE UPDATE ON coordinator_owner_enrollment_qualifications\nWHEN OLD.qualification_id IS NOT NEW.qualification_id OR typeof(NEW.qualification_id) <> 'text'\n OR OLD.coordinator_id IS NOT NEW.coordinator_id OR typeof(NEW.coordinator_id) <> 'text'\n OR OLD.link_id IS NOT NEW.link_id OR typeof(NEW.link_id) <> 'text'\n OR OLD.device_claim_id IS NOT NEW.device_claim_id OR typeof(NEW.device_claim_id) <> 'text'\n OR OLD.identity_id IS NOT NEW.identity_id OR typeof(NEW.identity_id) <> 'text'\n OR OLD.source_group_id IS NOT NEW.source_group_id OR typeof(NEW.source_group_id) <> 'text'\n OR OLD.device_id IS NOT NEW.device_id OR typeof(NEW.device_id) <> 'text'\n OR OLD.public_key IS NOT NEW.public_key OR typeof(NEW.public_key) <> 'text'\n OR OLD.fingerprint IS NOT NEW.fingerprint OR typeof(NEW.fingerprint) <> 'text'\n OR OLD.key_id IS NOT NEW.key_id OR typeof(NEW.key_id) <> 'text'\n OR OLD.controller_attestation_id IS NOT NEW.controller_attestation_id OR typeof(NEW.controller_attestation_id) <> 'text'\n OR OLD.controller_attestation_revision IS NOT NEW.controller_attestation_revision OR typeof(NEW.controller_attestation_revision) <> 'integer'\n OR OLD.controller_attestation_created_at IS NOT NEW.controller_attestation_created_at OR typeof(NEW.controller_attestation_created_at) <> 'text'\n OR OLD.review_receipt_id IS NOT NEW.review_receipt_id OR typeof(NEW.review_receipt_id) <> 'text'\n OR OLD.evidence_digest IS NOT NEW.evidence_digest OR typeof(NEW.evidence_digest) <> 'text'\n OR OLD.enrollment_identity_id IS NOT NEW.enrollment_identity_id OR typeof(OLD.enrollment_identity_id) <> typeof(NEW.enrollment_identity_id)\n OR OLD.link_attempt_id IS NOT NEW.link_attempt_id OR typeof(NEW.link_attempt_id) <> 'text'\n OR OLD.link_auth_config_revision IS NOT NEW.link_auth_config_revision OR typeof(NEW.link_auth_config_revision) <> 'text'\n OR OLD.link_created_at_ms IS NOT NEW.link_created_at_ms OR typeof(NEW.link_created_at_ms) <> 'integer'\n OR OLD.created_at_ms IS NOT NEW.created_at_ms OR typeof(NEW.created_at_ms) <> 'integer'\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_qualification_immutable'); END;\n`,\n\t`\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_qualification_revocation_update\nBEFORE UPDATE ON coordinator_owner_enrollment_qualifications\nWHEN (OLD.revoked_at_ms IS NOT NULL AND OLD.revoked_at_ms IS NOT NEW.revoked_at_ms)\n OR (NEW.revoked_at_ms IS NOT NULL AND (typeof(NEW.revoked_at_ms) <> 'integer'\n OR NEW.revoked_at_ms < OLD.created_at_ms OR NEW.revoked_at_ms > 9007199254740991))\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_qualification_revocation_monotonic'); END;\n`,\n\t`\nCREATE TRIGGER IF NOT EXISTS owner_enrollment_qualification_immutable_delete\nBEFORE DELETE ON coordinator_owner_enrollment_qualifications\nBEGIN SELECT RAISE(ABORT, 'owner_enrollment_qualification_immutable'); END;\n`,\n] as const;\n\nexport const COORDINATOR_OWNER_ENROLLMENT_QUALIFICATION_SCHEMA_SQL =\n\tCOORDINATOR_OWNER_ENROLLMENT_QUALIFICATION_SCHEMA_STATEMENTS.join(\"\\n\");\n","import { readConnectionSchemaState } from \"./coordinator-account-connection-schema.js\";\nimport { authSchemaDefinitionCheck } from \"./coordinator-auth-device-claim-schema.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport { authLinkLiveGenerationSql } from \"./coordinator-auth-link-liveness.js\";\nimport { authDeviceClaimProvenanceSql } from \"./coordinator-auth-link-provenance.js\";\nimport type { OwnerAuthorityAttempt } from \"./coordinator-owner-enrollment-proof.js\";\nimport { COORDINATOR_OWNER_ENROLLMENT_QUALIFICATION_SCHEMA_STATEMENTS } from \"./coordinator-owner-enrollment-qualification-schema.js\";\nimport { COORDINATOR_OWNER_ENROLLMENT_SCHEMA_SQL } from \"./coordinator-owner-enrollment-schema.js\";\n\n// Only the frozen 0036 table/authority guards and canonical 0035 ledger enable claims.\n// Absence preserves legacy controller SQL; partial storage never enables a claim.\nconst attemptDefinitions =\n\tCOORDINATOR_OWNER_ENROLLMENT_SCHEMA_SQL.match(\n\t\t/CREATE (?:TABLE|TRIGGER|INDEX)[\\s\\S]*?;(?=\\s*(?:--|CREATE|$))/gu,\n\t) ?? [];\nconst requiredAttempts = attemptDefinitions.filter(\n\t(sql) =>\n\t\t/^CREATE TABLE/u.test(sql) ||\n\t\t/CREATE TRIGGER IF NOT EXISTS owner_enrollment_authority_/u.test(sql),\n);\nconst readiness = [\n\t...requiredAttempts,\n\t...COORDINATOR_OWNER_ENROLLMENT_QUALIFICATION_SCHEMA_STATEMENTS,\n]\n\t.map((sql) => {\n\t\tconst check = authSchemaDefinitionCheck(sql).matches;\n\t\tif (!sql.startsWith(\"CREATE TABLE IF NOT EXISTS coordinator_owner_enrollment_attempts\"))\n\t\t\treturn check;\n\t\t// ALTER RENAME in official 0036 quotes this header only. Retain every body byte\n\t\t// for the full definition comparison, including quoted literals and CHECKs.\n\t\tconst header = 'CREATE TABLE \"coordinator_owner_enrollment_attempts\"';\n\t\treturn check.replace(\n\t\t\t\"FROM sqlite_master WHERE\",\n\t\t\t`FROM (SELECT type,name,CASE WHEN substr(sql,1,${header.length}) = '${header}'\n THEN 'CREATE TABLE coordinator_owner_enrollment_attempts' || substr(sql,${header.length + 1})\n ELSE sql END AS sql FROM sqlite_master) WHERE`,\n\t\t);\n\t})\n\t.join(\" AND \");\n\n/** Historical review birth, not current controller authority or old-device liveness. */\nconst QUALIFIED_LINKS = `SELECT l.coordinator_id,l.link_id,q.qualification_id\n FROM owner_claim_proven_links l\n JOIN coordinator_owner_enrollment_qualifications q ON q.coordinator_id=l.coordinator_id AND q.link_id=l.link_id\n JOIN coordinator_auth_device_claims d ON d.coordinator_id=l.coordinator_id AND d.claim_id=l.device_claim_id\n JOIN coordinator_auth_controller_attestations origin ON origin.coordinator_id=q.coordinator_id AND origin.attestation_id=q.controller_attestation_id\n WHERE l.authority_kind='device_claim' AND l.controller_attestation_id IS NULL\n AND q.revoked_at_ms IS NULL AND q.device_claim_id=d.claim_id AND q.identity_id=l.identity_id\n AND q.link_attempt_id=l.attempt_id AND q.link_auth_config_revision=l.auth_config_revision AND q.link_created_at_ms=l.created_at_ms\n AND q.source_group_id=d.group_id AND q.device_id=d.device_id AND q.public_key=d.public_key\n AND q.fingerprint=d.fingerprint AND q.key_id=d.key_id AND q.identity_id=d.identity_id\n AND origin.identity_id=q.identity_id AND origin.group_id=q.source_group_id AND origin.device_id=q.device_id\n AND origin.public_key=q.public_key AND origin.fingerprint=q.fingerprint\n AND origin.revision=q.controller_attestation_revision AND origin.revision=1\n AND origin.created_at=q.controller_attestation_created_at AND origin.review_receipt_id=q.review_receipt_id\n AND origin.evidence_digest=q.evidence_digest AND origin.enrollment_identity_id IS q.enrollment_identity_id\n AND (q.enrollment_identity_id IS NULL OR q.enrollment_identity_id=q.identity_id)\n AND (${authLinkLiveGenerationSql({ link: \"l\", connections: true })})`;\n\n/** Scope SQL is private composition, with values from a session or stored attempt.\n * No scope means no rows, never a coordinator-wide authority scan.\n */\nexport async function readOwnerLinkAuthority(\n\tbackend: AuthLinkBackend,\n\ttime = Date.now(),\n\tscope: AuthLinkStatement = { sql: \"0\", values: [] },\n) {\n\tconst capturedScope = { sql: scope.sql, values: [...scope.values] };\n\tif (!Number.isSafeInteger(time) || time < 0) throw new Error(\"owner_authority_invalid_time\");\n\tconst column = await backend.first<{ present: number }>({\n\t\tsql: \"SELECT EXISTS (SELECT 1 FROM pragma_table_info('coordinator_owner_enrollment_attempts') WHERE name='owner_qualification_id') AS present\",\n\t\tvalues: [],\n\t});\n\tconst hasPin = column?.present === 1;\n\tlet qualified = false;\n\tif (hasPin && (await readConnectionSchemaState(backend)) === \"ready\") {\n\t\tconst result = await backend.first<{ ready: number }>({\n\t\t\tsql: `SELECT (${readiness}) AS ready`,\n\t\t\tvalues: [],\n\t\t});\n\t\tqualified = result?.ready === 1 && requiredAttempts.length === 3;\n\t}\n\treturn ownerLinkAuthoritySql({ hasPin, qualified, time, scope: capturedScope });\n}\n\n/** Controller-only SQL: cannot admit a claim or use qualification evidence.\n * The attempt is the operation's SELECT * snapshot, never request JSON.\n * Optional qualification-schema reads add no authority to this legacy branch.\n */\nexport function controllerOwnerLinkAuthority(\n\tattempt: OwnerAuthorityAttempt,\n\tscope: AuthLinkStatement,\n) {\n\treturn ownerLinkAuthoritySql({\n\t\thasPin: Object.hasOwn(attempt, \"owner_qualification_id\"),\n\t\tqualified: false,\n\t\ttime: 0,\n\t\tscope: { sql: scope.sql, values: [...scope.values] },\n\t});\n}\n\nfunction ownerLinkAuthoritySql({\n\thasPin,\n\tqualified,\n\ttime,\n\tscope,\n}: {\n\thasPin: boolean;\n\tqualified: boolean;\n\ttime: number;\n\tscope: AuthLinkStatement;\n}) {\n\tconst qualification = qualified\n\t\t? \"(SELECT q.qualification_id FROM owner_qualified_links q WHERE q.coordinator_id=l.coordinator_id AND q.link_id=l.link_id)\"\n\t\t: \"NULL\";\n\tconst controller =\n\t\t\"l.authority_kind='controller_attestation' AND l.controller_attestation_id IS NOT NULL AND l.device_claim_id IS NULL\";\n\tconst controllerPin = hasPin\n\t\t? `(${controller}) AND a.owner_qualification_id IS NULL`\n\t\t: `(${controller})`;\n\tconst authorityPin = qualified\n\t\t? \"l.owner_qualification_id IS a.owner_qualification_id\"\n\t\t: controllerPin;\n\t// Materialize retained claim proof before adding qualification and attempt equality;\n\t// nesting all three in one predicate exceeds native D1's expression depth of 100.\n\tlet withSql = \"\";\n\tif (qualified || scope.sql !== \"0\") {\n\t\twithSql = `WITH owner_scope_links AS MATERIALIZED (\n SELECT l.* FROM coordinator_auth_account_links l WHERE ${scope.sql})${\n\t\tqualified\n\t\t\t? `, owner_claim_proven_links AS MATERIALIZED (\n SELECT l.* FROM owner_scope_links l\n WHERE ${authDeviceClaimProvenanceSql({ link: \"l\", connections: true })}),\n owner_qualified_links AS MATERIALIZED (${QUALIFIED_LINKS} AND q.created_at_ms <= ${time}),\n owner_authorized_links AS MATERIALIZED (\n SELECT l.*,${qualification} AS owner_qualification_id FROM owner_scope_links l\n WHERE (${controller}) OR ${qualification} IS NOT NULL) `\n\t\t\t: \"\"\n} `;\n\t}\n\treturn {\n\t\thasPin,\n\t\tvalues: scope.values,\n\t\twith: withSql,\n\t\tqualification,\n\t\tlink: `((${controller}) OR ${qualification} IS NOT NULL)`,\n\t\tactive: `EXISTS (SELECT 1 FROM ${qualified ? \"owner_authorized_links\" : \"owner_scope_links\"} l\n WHERE l.coordinator_id=a.coordinator_id AND l.link_id=a.link_id\n AND l.issuer=a.issuer AND l.subject=a.account_subject AND l.identity_id=a.identity_id\n AND l.attempt_id=a.link_attempt_id AND l.auth_config_revision=a.link_auth_config_revision AND l.revoked_at_ms IS NULL\n AND l.controller_attestation_id IS a.link_controller_attestation_id\n AND ${authorityPin})`,\n\t};\n}\n","import { parseCoordinatorAccountReference } from \"./coordinator-auth-contract.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport { parseCoordinatorAuthLoopback } from \"./coordinator-auth-loopback.js\";\nimport {\n\tdecodeCoordinatorAuthProof32,\n\tencodeCoordinatorAuthProof32,\n} from \"./coordinator-auth-proof.js\";\nimport { parseSshEd25519PublicKey } from \"./coordinator-ed25519-key-id.js\";\nimport { verifyOwnerEnrollmentSignature } from \"./coordinator-owner-enrollment-proof.js\";\nimport type { OwnerEnrollmentStart } from \"./owner-enrollment-start.js\";\n\nexport interface OwnerEnrollmentAdmissionPin {\n\tcoordinatorId: string;\n\torigin: string;\n\tissuer: string;\n\trevision: string;\n}\ndeclare const admissionKeyBrand: unique symbol;\nexport type OwnerEnrollmentAdmissionKey = Readonly<{ [admissionKeyBrand]: true }>;\ntype CryptoKey = Awaited<ReturnType<typeof globalThis.crypto.subtle.importKey>>;\nconst keys = new WeakMap<OwnerEnrollmentAdmissionKey, CryptoKey>();\nconst MAX_TTL_MS = 15 * 60 * 1000;\n\nexport function isOwnerEnrollmentAdmissionKey(\n\tvalue: unknown,\n): value is OwnerEnrollmentAdmissionKey {\n\treturn (\n\t\ttypeof value === \"object\" && value !== null && keys.has(value as OwnerEnrollmentAdmissionKey)\n\t);\n}\n\n/** Server-only key import. Sharing raw CSRF bytes is safe because the MAC domain differs. */\nexport async function importOwnerEnrollmentAdmissionKey(\n\traw: Uint8Array,\n): Promise<OwnerEnrollmentAdmissionKey> {\n\tif (!(raw instanceof Uint8Array) || raw.byteLength !== 32)\n\t\tthrow new Error(\"owner_admission_invalid_key\");\n\tconst cryptoKey = await globalThis.crypto.subtle.importKey(\n\t\t\"raw\",\n\t\tnew Uint8Array(raw),\n\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n\t\tfalse,\n\t\t[\"sign\", \"verify\"],\n\t);\n\tconst key = Object.freeze({}) as OwnerEnrollmentAdmissionKey;\n\tkeys.set(key, cryptoKey);\n\treturn key;\n}\n\nfunction text(value: unknown, maximum: number): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length > 0 &&\n\t\tvalue.length <= maximum &&\n\t\t!/[\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(value)\n\t);\n}\n\nfunction startTuple(pin: OwnerEnrollmentAdmissionPin, start: OwnerEnrollmentStart): string {\n\tconst parsed = parseSshEd25519PublicKey(start.publicKey);\n\tconst origin = new URL(pin.origin);\n\tif (\n\t\t!isAuthControllerId(pin.coordinatorId) ||\n\t\t!text(pin.revision, 64) ||\n\t\t!/^[a-f0-9]{64}$/.test(pin.revision) ||\n\t\torigin.protocol !== \"https:\" ||\n\t\torigin.origin !== pin.origin ||\n\t\t!text(pin.issuer, 4096) ||\n\t\t!isAuthControllerId(start.attemptId) ||\n\t\t!isAuthControllerId(start.deviceId) ||\n\t\t!text(start.publicKey, 80) ||\n\t\tparsed.kind !== \"ed25519\" ||\n\t\tstart.publicKey !== `ssh-ed25519 ${btoa(String.fromCharCode(...parsed.blob))}` ||\n\t\t!text(start.loopbackRedirect, 4096) ||\n\t\t!parseCoordinatorAuthLoopback(start.loopbackRedirect).ok ||\n\t\t!decodeCoordinatorAuthProof32(start.browserStartCode) ||\n\t\t!text(start.signature, 86)\n\t)\n\t\tthrow new Error(\"owner_admission_invalid_start\");\n\treturn JSON.stringify([\n\t\t\"codemem-owner-enrollment-start-v1\",\n\t\t\"owner_enroll\",\n\t\tpin.coordinatorId,\n\t\tpin.origin,\n\t\tpin.issuer,\n\t\tpin.revision,\n\t\tstart.attemptId,\n\t\tstart.deviceId,\n\t\tstart.publicKey,\n\t\tstart.loopbackRedirect,\n\t\tstart.browserStartCode,\n\t]);\n}\n\nfunction validTimes(issued: number, expires: number, now: number): boolean {\n\treturn (\n\t\t[issued, expires, now].every((n) => Number.isSafeInteger(n) && n >= 0) &&\n\t\tissued <= now &&\n\t\tnow < expires &&\n\t\texpires > issued &&\n\t\texpires - issued <= MAX_TTL_MS\n\t);\n}\n\nfunction message(\n\ttuple: string,\n\tsignature: string,\n\tissued: number,\n\texpires: number,\n): Uint8Array<ArrayBuffer> {\n\treturn new TextEncoder().encode(\n\t\tJSON.stringify([\"codemem-owner-enrollment-admission-v1\", issued, expires, tuple, signature]),\n\t);\n}\n\n/** Admin-only issuer: call only after reviewing this exact signed start. No durable state is created. */\nexport async function issueOwnerEnrollmentAdmission(\n\tkey: OwnerEnrollmentAdmissionKey,\n\tpin: OwnerEnrollmentAdmissionPin,\n\tstart: OwnerEnrollmentStart,\n\toptions: { nowMs: number; ttlMs: number },\n): Promise<string> {\n\tconst cryptoKey = keys.get(key);\n\tconst tuple = startTuple(pin, start);\n\tconst issued = options.nowMs;\n\tconst expires = issued + options.ttlMs;\n\tconst signature = start.signature;\n\tif (\n\t\t!cryptoKey ||\n\t\t!validTimes(issued, expires, issued) ||\n\t\t!(await verifyOwnerEnrollmentSignature(start.publicKey, tuple, signature))\n\t) {\n\t\tthrow new Error(\"owner_admission_invalid_start\");\n\t}\n\tconst mac = await globalThis.crypto.subtle.sign(\n\t\t\"HMAC\",\n\t\tcryptoKey,\n\t\tmessage(tuple, signature, issued, expires),\n\t);\n\treturn `v1.${issued}.${expires}.${encodeCoordinatorAuthProof32(new Uint8Array(mac))}`;\n}\n\n/** Exact retries still reach the retained-attempt uniqueness and capacity checks; this is not a replay store. */\nexport async function verifyOwnerEnrollmentAdmission(\n\tkey: OwnerEnrollmentAdmissionKey,\n\ttoken: unknown,\n\tpin: OwnerEnrollmentAdmissionPin,\n\tstart: OwnerEnrollmentStart,\n\tnowMs: number,\n): Promise<boolean> {\n\ttry {\n\t\tconst cryptoKey = keys.get(key);\n\t\tif (!cryptoKey || typeof token !== \"string\" || token.length > 81) return false;\n\t\tconst parts = /^v1\\.(0|[1-9][0-9]{0,15})\\.(0|[1-9][0-9]{0,15})\\.([A-Za-z0-9_-]{43})$/.exec(\n\t\t\ttoken,\n\t\t);\n\t\tif (!parts) return false;\n\t\tconst issued = Number(parts[1]);\n\t\tconst expires = Number(parts[2]);\n\t\tconst mac = decodeCoordinatorAuthProof32(parts[3]);\n\t\tif (!mac || !validTimes(issued, expires, nowMs)) return false;\n\t\treturn await globalThis.crypto.subtle.verify(\n\t\t\t\"HMAC\",\n\t\t\tcryptoKey,\n\t\t\tmac,\n\t\t\tmessage(startTuple(pin, start), start.signature, issued, expires),\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** Server-resolved account/link only. This structural type confers no authorization. */\nexport interface OwnerEnrollmentResolvedOwner {\n\treadonly coordinatorId: string;\n\treadonly issuer: string;\n\treadonly subject: string;\n\treadonly identityId: string;\n\treadonly linkId: string;\n}\n\nexport interface OwnerEnrollmentAdmissionV2Options {\n\treadonly resolvedOwner: OwnerEnrollmentResolvedOwner;\n\treadonly nowMs: number;\n\treadonly ttlMs: number;\n}\n\nexport interface OwnerEnrollmentAdmissionV2VerificationOptions {\n\treadonly resolvedOwner: OwnerEnrollmentResolvedOwner;\n\treadonly nowMs: number;\n}\n\nfunction ownerTuple(owner: OwnerEnrollmentResolvedOwner): string {\n\tconst { coordinatorId, issuer, subject, identityId, linkId } = owner;\n\tif (\n\t\t!isAuthControllerId(coordinatorId) ||\n\t\t!text(issuer, 4096) ||\n\t\t!parseCoordinatorAccountReference({ issuer, subject }, { issuer }).ok ||\n\t\t!isAuthControllerId(identityId) ||\n\t\t!isAuthControllerId(linkId)\n\t)\n\t\tthrow new Error(\"owner_admission_invalid_owner\");\n\treturn JSON.stringify([\n\t\t\"codemem-owner-enrollment-owner-commitment-v1\",\n\t\tcoordinatorId,\n\t\tissuer,\n\t\tsubject,\n\t\tidentityId,\n\t\tlinkId,\n\t]);\n}\n\nasync function hashOwnerTuple(tuple: string): Promise<string> {\n\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(tuple));\n\treturn Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Unmounted primitive: hashes canonical JSON [domain, coordinator, issuer, subject, Identity, link].\n * Returns lowercase SHA-256 hex, not authority or anonymization of guessable account data.\n */\nexport async function ownerEnrollmentOwnerCommitment(\n\towner: OwnerEnrollmentResolvedOwner,\n): Promise<string> {\n\treturn hashOwnerTuple(ownerTuple(owner));\n}\n\nfunction admissionV2Input(\n\tpin: OwnerEnrollmentAdmissionPin,\n\tstart: OwnerEnrollmentStart,\n\towner: OwnerEnrollmentResolvedOwner,\n) {\n\t// Copy every caller-owned field before crypto can yield. No later reads from inputs.\n\tconst pinned = {\n\t\tcoordinatorId: pin.coordinatorId,\n\t\torigin: pin.origin,\n\t\tissuer: pin.issuer,\n\t\trevision: pin.revision,\n\t};\n\tconst pending = {\n\t\tattemptId: start.attemptId,\n\t\tdeviceId: start.deviceId,\n\t\tpublicKey: start.publicKey,\n\t\tloopbackRedirect: start.loopbackRedirect,\n\t\tbrowserStartCode: start.browserStartCode,\n\t\tsignature: start.signature,\n\t};\n\tconst resolved = {\n\t\tcoordinatorId: owner.coordinatorId,\n\t\tissuer: owner.issuer,\n\t\tsubject: owner.subject,\n\t\tidentityId: owner.identityId,\n\t\tlinkId: owner.linkId,\n\t};\n\tconst ownerMessage = ownerTuple(resolved);\n\tif (\n\t\tresolved.coordinatorId !== pinned.coordinatorId ||\n\t\tresolved.issuer !== pinned.issuer ||\n\t\t!text(pinned.origin, 4096) ||\n\t\t!text(pending.browserStartCode, 43)\n\t)\n\t\tthrow new Error(\"owner_admission_invalid_start\");\n\treturn {\n\t\ttuple: startTuple(pinned, pending),\n\t\tpublicKey: pending.publicKey,\n\t\tsignature: pending.signature,\n\t\townerMessage,\n\t};\n}\n\nfunction messageV2(\n\ttuple: string,\n\tsignature: string,\n\tissued: number,\n\texpires: number,\n\townerCommitment: string,\n): Uint8Array<ArrayBuffer> {\n\treturn new TextEncoder().encode(\n\t\tJSON.stringify([\n\t\t\t\"codemem-owner-enrollment-admission-v2\",\n\t\t\tissued,\n\t\t\texpires,\n\t\t\ttuple,\n\t\t\tsignature,\n\t\t\townerCommitment,\n\t\t]),\n\t);\n}\n\n/**\n * Unmounted server-only issuer, NOT a self-service endpoint. Before calling, authenticate the\n * session and resolve its active account link, Identity and grants server-side. Never accept\n * resolvedOwner from request JSON. A type or commitment alone does not authorize issuance.\n * Uses the existing private admission key; v1 operator issuance/verification stays unchanged.\n */\nexport async function issueOwnerEnrollmentAdmissionV2(\n\tkey: OwnerEnrollmentAdmissionKey,\n\tpin: OwnerEnrollmentAdmissionPin,\n\tstart: OwnerEnrollmentStart,\n\toptions: OwnerEnrollmentAdmissionV2Options,\n): Promise<string> {\n\tconst cryptoKey = keys.get(key);\n\tconst input = admissionV2Input(pin, start, options.resolvedOwner);\n\tconst issued = options.nowMs;\n\tconst ttl = options.ttlMs;\n\tconst expires = issued + ttl;\n\tif (!cryptoKey || !Number.isSafeInteger(ttl) || !validTimes(issued, expires, issued))\n\t\tthrow new Error(\"owner_admission_invalid_start\");\n\tif (!(await verifyOwnerEnrollmentSignature(input.publicKey, input.tuple, input.signature)))\n\t\tthrow new Error(\"owner_admission_invalid_start\");\n\tconst commitment = await hashOwnerTuple(input.ownerMessage);\n\tconst mac = await globalThis.crypto.subtle.sign(\n\t\t\"HMAC\",\n\t\tcryptoKey,\n\t\tmessageV2(input.tuple, input.signature, issued, expires, commitment),\n\t);\n\treturn `v2.${issued}.${expires}.${commitment}.${encodeCoordinatorAuthProof32(new Uint8Array(mac))}`;\n}\n\n/**\n * Unmounted v2-only verifier; no v1 fallback. The hash companion is authenticated, not raw owner data.\n * Callers must separately retain an immutable attempt owner pin, compare it at callback/finalize,\n * and recheck live session/link/grant authority. This primitive creates no attempt or replay state.\n */\nexport async function verifyOwnerEnrollmentAdmissionV2(\n\tkey: OwnerEnrollmentAdmissionKey,\n\ttoken: unknown,\n\tpin: OwnerEnrollmentAdmissionPin,\n\tstart: OwnerEnrollmentStart,\n\toptions: OwnerEnrollmentAdmissionV2VerificationOptions,\n): Promise<boolean> {\n\ttry {\n\t\tconst cryptoKey = keys.get(key);\n\t\tif (!cryptoKey || typeof token !== \"string\" || token.length > 146) return false;\n\t\tconst parts =\n\t\t\t/^v2\\.(0|[1-9][0-9]{0,15})\\.(0|[1-9][0-9]{0,15})\\.([a-f0-9]{64})\\.([A-Za-z0-9_-]{43})$/.exec(\n\t\t\t\ttoken,\n\t\t\t);\n\t\tif (!parts) return false;\n\t\tconst issued = Number(parts[1]);\n\t\tconst expires = Number(parts[2]);\n\t\tconst commitment = parts[3];\n\t\tconst mac = decodeCoordinatorAuthProof32(parts[4]);\n\t\tconst now = options.nowMs;\n\t\tif (!mac || !commitment || !validTimes(issued, expires, now)) return false;\n\t\tconst input = admissionV2Input(pin, start, options.resolvedOwner);\n\t\tif ((await hashOwnerTuple(input.ownerMessage)) !== commitment) return false;\n\t\treturn await globalThis.crypto.subtle.verify(\n\t\t\t\"HMAC\",\n\t\t\tcryptoKey,\n\t\t\tmac,\n\t\t\tmessageV2(input.tuple, input.signature, issued, expires, commitment),\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n","import { ownerEnrollmentOwnerCommitment } from \"./owner-enrollment-admission.js\";\n\n/** NULL denotes the existing operator path, never an owner inferred from a device. */\nexport function validAdmissionOwnerHash(value: unknown): value is string | null {\n\treturn value === null || (typeof value === \"string\" && /^[a-f0-9]{64}$/.test(value));\n}\n\ninterface OwnerPin {\n\tadmission_owner_hash: string | null;\n\tcoordinator_id: string;\n\tissuer: string;\n\taccount_subject: string | null;\n\tidentity_id: string | null;\n\tlink_id: string | null;\n}\n\n/** Recompute from independently verified, exact account/link facts, not the token companion. */\nexport async function matchesAdmissionOwner(row: OwnerPin): Promise<boolean> {\n\tif (!validAdmissionOwnerHash(row.admission_owner_hash)) return false;\n\tif (row.admission_owner_hash === null) return true;\n\tif (!row.account_subject || !row.identity_id || !row.link_id) return false;\n\ttry {\n\t\treturn (\n\t\t\trow.admission_owner_hash ===\n\t\t\t(await ownerEnrollmentOwnerCommitment({\n\t\t\t\tcoordinatorId: row.coordinator_id,\n\t\t\t\tissuer: row.issuer,\n\t\t\t\tsubject: row.account_subject,\n\t\t\t\tidentityId: row.identity_id,\n\t\t\t\tlinkId: row.link_id,\n\t\t\t}))\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n","import type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport {\n\ted25519KeyIdForRevocation,\n\tparseSshEd25519PublicKeyForRevocation,\n} from \"./coordinator-ed25519-key-id-compat.js\";\nimport { COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS } from \"./coordinator-legacy-team-completion.js\";\nimport {\n\ttype OwnerAuthorityAttempt as OwnerAttempt,\n\townerEnrollmentConfirmationHash,\n\tvalidOwnerEnrollmentReceiptMetadata,\n\tverifyOwnerEnrollmentCompletion,\n} from \"./coordinator-owner-enrollment-proof.js\";\nimport { readOwnerLinkAuthority } from \"./owner-enrollment-link-authority.js\";\nimport { matchesAdmissionOwner } from \"./owner-enrollment-owner-pin.js\";\n\nexport {\n\ttype OwnerAttempt,\n\tverifyOwnerEnrollmentSignature,\n} from \"./coordinator-owner-enrollment-proof.js\";\n\n/** Matches the optional Worker owner-enrollment audit migration. */\nexport const COORDINATOR_OWNER_ENROLLMENT_AUDIT_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS coordinator_owner_enrollment_audit_log (\n coordinator_id TEXT NOT NULL, event_id TEXT NOT NULL, attempt_id TEXT NOT NULL,\n action TEXT NOT NULL CHECK (action = 'owner_device_enrolled'),\n binding_id TEXT NOT NULL, device_id TEXT NOT NULL, created_at_ms INTEGER NOT NULL,\n PRIMARY KEY (coordinator_id, event_id), UNIQUE (coordinator_id, attempt_id)\n);`;\n\n/** Historical link provenance is equality only: never consult the old controller/device. */\nexport const OWNER_ACTIVE_LINK_SQL = `EXISTS (SELECT 1 FROM coordinator_auth_account_links l\n WHERE l.coordinator_id = a.coordinator_id AND l.link_id = a.link_id\n AND l.authority_kind = 'controller_attestation' AND l.controller_attestation_id IS NOT NULL AND l.device_claim_id IS NULL\n AND l.issuer = a.issuer AND l.subject = a.account_subject AND l.identity_id = a.identity_id\n AND l.attempt_id = a.link_attempt_id AND l.controller_attestation_id = a.link_controller_attestation_id\n AND l.auth_config_revision = a.link_auth_config_revision AND l.revoked_at_ms IS NULL)`;\n\n// Private SQL expressions only: a is the stored attempt in both callers.\nexport function ownerExcludedLegacyDecisionSql(\n\tgroupExpression: \"r.group_id\" | \"json_extract(p.value,'$.groupId')\",\n): string {\n\treturn `EXISTS (SELECT 1 FROM coordinator_legacy_team_completions c, json_each(c.manifest_json,'$.device_decisions') d\n WHERE c.group_id = ${groupExpression} AND json_extract(c.manifest_json,'$.coordinator_id') = a.coordinator_id\n AND json_extract(d.value,'$.decision') = 'excluded'\n AND (json_extract(d.value,'$.device_id') = a.device_id OR json_extract(d.value,'$.key_fingerprint') = a.fingerprint\n OR NOT EXISTS (SELECT 1 FROM enrolled_devices e WHERE e.group_id = c.group_id\n AND e.device_id = json_extract(d.value,'$.device_id') AND e.fingerprint = json_extract(d.value,'$.key_fingerprint'))))`;\n}\n\nconst LIVE_GRANTS = `json_array_length(a.grant_revisions_json) BETWEEN 1 AND 50\n AND NOT EXISTS (SELECT 1 FROM json_each(a.grant_revisions_json) p\n WHERE NOT EXISTS (SELECT 1 FROM coordinator_identity_group_grants r JOIN groups g ON g.group_id = r.group_id\n WHERE r.coordinator_id = a.coordinator_id AND r.identity_id = a.identity_id\n AND r.group_id = json_extract(p.value,'$.groupId') AND r.revision = json_extract(p.value,'$.revision')\n AND r.status = 'active' AND r.revoked_at IS NULL AND g.archived_at IS NULL)\n OR ${ownerExcludedLegacyDecisionSql(\"json_extract(p.value,'$.groupId')\")})`;\n\nconst NO_REVOCATION = `NOT EXISTS (SELECT 1 FROM coordinator_device_revocations\n WHERE (subject_kind = 'device_id' AND subject_value = a.device_id)\n OR (subject_kind = 'ed25519_key' AND subject_value = a.key_id))`;\n\ninterface EnrollmentKey {\n\tgroupId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n}\nasync function collisionSnapshot(\n\tbackend: AuthLinkBackend,\n\trow: OwnerAttempt,\n): Promise<string | null> {\n\t// This bounded scan fails closed above 500 enrollments; it is not an enrollment quota.\n\tconst source = await backend.first<{ rows: string }>({\n\t\tsql: `SELECT json_group_array(json_object('groupId',group_id,'deviceId',device_id,'publicKey',public_key)) AS rows FROM\n (SELECT group_id,device_id,public_key FROM enrolled_devices LIMIT ?)`,\n\t\tvalues: [COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS + 1],\n\t});\n\tif (!source) return null;\n\tconst rows = JSON.parse(source.rows) as EnrollmentKey[];\n\tif (rows.length > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS) return null;\n\tfor (const existing of rows) {\n\t\tif (existing.deviceId === row.device_id) return null;\n\t\tconst parsed = parseSshEd25519PublicKeyForRevocation(existing.publicKey);\n\t\tif (parsed.kind === \"malformed_ed25519\") return null;\n\t\tif ((await ed25519KeyIdForRevocation(existing.publicKey)) === row.key_id) return null;\n\t}\n\treturn source.rows;\n}\n\n// Every stored key must still belong to the scanned set inside the winning SQL update.\n// Concurrent unrelated enrollment changes deliberately deny this attempt.\nconst SAME_KEYS = `(SELECT count(*) FROM enrolled_devices) = json_array_length(?)\n AND NOT EXISTS (SELECT 1 FROM enrolled_devices e WHERE NOT EXISTS (SELECT 1 FROM json_each(?) k\n WHERE e.group_id = json_extract(k.value,'$.groupId') AND e.device_id = json_extract(k.value,'$.deviceId')\n AND e.public_key = json_extract(k.value,'$.publicKey')))`;\nconst WINNER = `coordinator_id = ? AND attempt_id = ? AND state = 'finalized' AND binding_id = ?`;\nfunction assertWrite(winner: string[], expected: number): AuthLinkStatement {\n\t// The finalized-row trigger (and invalid-state CHECK) aborts the native batch on a count mismatch.\n\treturn {\n\t\tsql: `UPDATE coordinator_owner_enrollment_attempts SET state = 'invalid' WHERE ${WINNER} AND changes() <> ?`,\n\t\tvalues: [...winner, expected],\n\t};\n}\n\n/** Internal atomic finalization, not a package export or standalone ownership writer.\n * The later ceremony caller must supply trusted current config and a stored confirmed attempt.\n * SQL failures propagate: a failed post-commit read must not claim nothing changed.\n */\nexport async function commitOwnerEnrollment(input: {\n\tbackend: AuthLinkBackend;\n\trow: OwnerAttempt;\n\trevision: string;\n\tnow: number;\n\tcompletionSecret: string;\n\tsignature: string;\n}): Promise<boolean> {\n\tconst { backend, revision, now, completionSecret, signature } = input;\n\tconst a = Object.freeze({ ...input.row });\n\tconst proof = await verifyOwnerEnrollmentCompletion(\n\t\ta,\n\t\trevision,\n\t\tnow,\n\t\tcompletionSecret,\n\t\tsignature,\n\t);\n\tif (!proof || !(await matchesAdmissionOwner(a))) return false;\n\tconst { grants } = proof;\n\tconst snapshot = await collisionSnapshot(backend, a);\n\tif (snapshot === null) return false;\n\tconst bindingId = globalThis.crypto.randomUUID();\n\tconst eventId = globalThis.crypto.randomUUID();\n\tconst outcome = JSON.stringify({\n\t\tkind: \"finalized\",\n\t\tbindingId,\n\t\tgroups: grants.map((g) => g.groupId),\n\t});\n\tconst winner = [a.coordinator_id, a.attempt_id, bindingId];\n\tconst authority = await readOwnerLinkAuthority(backend, now, {\n\t\tsql: \"l.coordinator_id=? AND l.link_id=?\",\n\t\tvalues: [a.coordinator_id, a.link_id],\n\t});\n\tif (!authority.hasPin && a.owner_qualification_id != null) return false;\n\tconst update = winningUpdate(a, {\n\t\trevision,\n\t\tnow,\n\t\tbindingId,\n\t\teventId,\n\t\toutcome,\n\t\tsnapshot,\n\t\t...proof,\n\t});\n\t// UPDATE FROM keeps the full live-link proof separate from final pins and grants.\n\t// Both stages still evaluate inside this one winning statement in the atomic batch.\n\t// Scope the retained attempt before materialization, not just in the final UPDATE.\n\tupdate.sql = `${authority.with ? `${authority.with},` : \"WITH\"} owner_commit_links AS MATERIALIZED (\n SELECT a.coordinator_id,a.attempt_id FROM coordinator_owner_enrollment_attempts a\n WHERE a.coordinator_id=? AND a.attempt_id=? AND ${authority.active}) ${update.sql\n\t\t.replace(\"loopback_redirect = NULL\", \"loopback_redirect = NULL FROM owner_commit_links p\")\n\t\t.replace(\n\t\t\tOWNER_ACTIVE_LINK_SQL,\n\t\t\t\"p.coordinator_id=a.coordinator_id AND p.attempt_id=a.attempt_id\",\n\t\t)}`;\n\tupdate.values.unshift(...authority.values, a.coordinator_id, a.attempt_id);\n\tif (authority.hasPin) {\n\t\tupdate.sql += \" AND a.owner_qualification_id IS ?\";\n\t\tupdate.values.push(a.owner_qualification_id ?? null);\n\t}\n\tawait backend.batch([update, ...dependentWrites(winner, now, grants.length)]);\n\tconst committed = await backend.first({\n\t\tsql: `SELECT 1 FROM coordinator_owner_enrollment_attempts WHERE ${WINNER}`,\n\t\tvalues: winner,\n\t});\n\treturn committed !== null;\n}\nconst WINNING_UPDATE_SQL = `UPDATE coordinator_owner_enrollment_attempts AS a SET state = 'finalized',\n finalized_at_ms = ?, binding_id = ?, audit_event_id = ?, final_outcome_json = ?,\n final_key_proof_hash = ?, loopback_redirect = NULL\n WHERE a.coordinator_id = ? AND a.attempt_id = ? AND a.purpose = 'owner_enroll'\n AND a.state = 'confirmed' AND a.created_at_ms <= ? AND a.expires_at_ms > ?\n AND a.auth_config_revision = ? AND a.origin = ? AND a.issuer = ?\n AND a.admission_owner_hash IS ?\n AND a.device_id = ? AND a.public_key = ? AND a.key_id = ? AND a.fingerprint = ?\n AND a.browser_start_hash = ? AND a.browser_transaction_hash = ? AND a.browser_binder_hash = ?\n AND a.account_subject = ? AND a.identity_id = ? AND a.link_id = ?\n AND a.link_attempt_id = ? AND a.link_controller_attestation_id IS ? AND a.link_auth_config_revision = ?\n AND a.grant_revisions_json = ? AND a.confirmation_hash = ? AND a.completion_secret_hash = ?\n AND a.loopback_redirect = ? AND a.created_at_ms = ? AND a.expires_at_ms = ?\n AND ${OWNER_ACTIVE_LINK_SQL} AND ${LIVE_GRANTS} AND ${NO_REVOCATION}\n AND NOT EXISTS (SELECT 1 FROM coordinator_device_ownership_bindings b WHERE b.device_id = a.device_id OR b.key_id = a.key_id)\n AND ${SAME_KEYS}`;\nfunction winningPins(a: OwnerAttempt): AuthLinkStatement[\"values\"] {\n\treturn [\n\t\ta.origin,\n\t\ta.issuer,\n\t\ta.admission_owner_hash,\n\t\ta.device_id,\n\t\ta.public_key,\n\t\ta.key_id,\n\t\ta.fingerprint,\n\t\ta.browser_start_hash,\n\t\ta.browser_transaction_hash,\n\t\ta.browser_binder_hash,\n\t\ta.account_subject,\n\t\ta.identity_id,\n\t\ta.link_id,\n\t\ta.link_attempt_id,\n\t\ta.link_controller_attestation_id,\n\t\ta.link_auth_config_revision,\n\t\ta.grant_revisions_json,\n\t\ta.confirmation_hash,\n\t];\n}\nfunction winningUpdate(\n\ta: OwnerAttempt,\n\toptions: {\n\t\trevision: string;\n\t\tnow: number;\n\t\tbindingId: string;\n\t\teventId: string;\n\t\toutcome: string;\n\t\tsnapshot: string;\n\t\tcompletionHash: string;\n\t\tkeyProofHash: string;\n\t},\n): AuthLinkStatement {\n\tconst { revision, now, bindingId, eventId, outcome, snapshot, completionHash, keyProofHash } =\n\t\toptions;\n\treturn {\n\t\tsql: WINNING_UPDATE_SQL,\n\t\tvalues: [\n\t\t\tnow,\n\t\t\tbindingId,\n\t\t\teventId,\n\t\t\toutcome,\n\t\t\tkeyProofHash,\n\t\t\ta.coordinator_id,\n\t\t\ta.attempt_id,\n\t\t\tnow,\n\t\t\tnow,\n\t\t\trevision,\n\t\t\t...winningPins(a),\n\t\t\tcompletionHash,\n\t\t\ta.loopback_redirect,\n\t\t\ta.created_at_ms,\n\t\t\ta.expires_at_ms,\n\t\t\tsnapshot,\n\t\t\tsnapshot,\n\t\t],\n\t};\n}\nfunction dependentWrites(winner: string[], now: number, grantCount: number): AuthLinkStatement[] {\n\tconst binding: AuthLinkStatement = {\n\t\tsql: `INSERT INTO coordinator_device_ownership_bindings\n (device_id,key_id,identity_id,coordinator_id,binding_id,provenance,source_ref,bound_at)\n SELECT device_id,key_id,identity_id,coordinator_id,binding_id,'owner_enrollment',attempt_id,?\n FROM coordinator_owner_enrollment_attempts WHERE ${WINNER} AND changes() = 1`,\n\t\tvalues: [new Date(now).toISOString(), ...winner],\n\t};\n\tconst enrollment: AuthLinkStatement = {\n\t\tsql: `INSERT INTO enrolled_devices (group_id,device_id,public_key,fingerprint,identity_id,enabled,created_at)\n SELECT r.group_id,a.device_id,a.public_key,a.fingerprint,a.identity_id,1,?\n FROM coordinator_owner_enrollment_attempts a JOIN json_each(a.grant_revisions_json) p\n JOIN coordinator_identity_group_grants r ON r.coordinator_id = a.coordinator_id AND r.identity_id = a.identity_id\n AND r.group_id = json_extract(p.value,'$.groupId') AND r.revision = json_extract(p.value,'$.revision')\n JOIN groups g ON g.group_id = r.group_id\n WHERE a.coordinator_id = ? AND a.attempt_id = ? AND a.state = 'finalized' AND a.binding_id = ?\n AND r.status = 'active' AND r.revoked_at IS NULL AND g.archived_at IS NULL`,\n\t\tvalues: [new Date(now).toISOString(), ...winner],\n\t};\n\tconst audit: AuthLinkStatement = {\n\t\tsql: `INSERT INTO coordinator_owner_enrollment_audit_log\n (coordinator_id,event_id,attempt_id,action,binding_id,device_id,created_at_ms)\n SELECT coordinator_id,audit_event_id,attempt_id,'owner_device_enrolled',binding_id,device_id,finalized_at_ms\n FROM coordinator_owner_enrollment_attempts WHERE ${WINNER}`,\n\t\tvalues: winner,\n\t};\n\treturn [\n\t\tbinding,\n\t\tassertWrite(winner, 1),\n\t\tenrollment,\n\t\tassertWrite(winner, grantCount),\n\t\taudit,\n\t\tassertWrite(winner, 1),\n\t];\n}\n\nconst RECEIPT_SQL = `SELECT 1 FROM coordinator_device_ownership_bindings b\n WHERE b.device_id = ? AND b.key_id = ? AND b.identity_id = ? AND b.coordinator_id = ?\n AND b.binding_id = ? AND b.provenance = 'owner_enrollment' AND b.source_ref = ? AND b.bound_at = ?\n AND EXISTS (SELECT 1 FROM coordinator_owner_enrollment_attempts a\n WHERE a.coordinator_id = b.coordinator_id AND a.attempt_id = b.source_ref AND a.state = 'finalized'\n AND a.binding_id = b.binding_id AND a.device_id = b.device_id AND a.key_id = b.key_id AND a.identity_id = b.identity_id\n AND a.final_outcome_json = ? AND a.finalized_at_ms = ? AND a.audit_event_id = ?\n AND a.grant_revisions_json = ? AND a.public_key = ? AND a.fingerprint = ?\n AND a.purpose = ? AND a.origin = ? AND a.issuer = ? AND a.auth_config_revision = ?\n AND a.admission_owner_hash IS ?\n AND a.account_subject = ? AND a.link_id = ? AND a.link_attempt_id IS ?\n AND a.link_controller_attestation_id IS ? AND a.link_auth_config_revision IS ?\n AND a.browser_start_hash = ? AND a.browser_transaction_hash IS ? AND a.browser_binder_hash IS ?\n AND a.confirmation_hash IS ? AND a.completion_secret_hash IS ? AND a.final_key_proof_hash IS ?\n AND a.created_at_ms = ? AND a.expires_at_ms = ? AND a.loopback_redirect IS ?)\n AND NOT EXISTS (SELECT 1 FROM coordinator_owner_enrollment_audit_log e\n WHERE e.coordinator_id = ? AND (e.attempt_id = ? OR e.event_id = ?) AND\n (e.event_id <> ? OR e.attempt_id <> ? OR e.action <> 'owner_device_enrolled' OR e.binding_id <> ? OR e.device_id <> ? OR e.created_at_ms <> ?))\n AND NOT EXISTS (SELECT 1 FROM enrolled_devices e, json_each(?) g\n WHERE e.group_id = json_extract(g.value,'$.groupId') AND e.device_id = ?\n AND (e.public_key <> ? OR e.fingerprint <> ? OR e.identity_id IS NOT ? OR e.created_at <> ?))`;\nfunction receiptValues(row: OwnerAttempt): AuthLinkStatement[\"values\"] {\n\tconst timestamp = new Date(row.finalized_at_ms as number).toISOString();\n\treturn [\n\t\trow.device_id,\n\t\trow.key_id,\n\t\trow.identity_id,\n\t\trow.coordinator_id,\n\t\trow.binding_id,\n\t\trow.attempt_id,\n\t\ttimestamp,\n\t\trow.final_outcome_json,\n\t\trow.finalized_at_ms,\n\t\trow.audit_event_id,\n\t\trow.grant_revisions_json,\n\t\trow.public_key,\n\t\trow.fingerprint,\n\t\trow.purpose,\n\t\trow.origin,\n\t\trow.issuer,\n\t\trow.auth_config_revision,\n\t\trow.admission_owner_hash,\n\t\trow.account_subject,\n\t\trow.link_id,\n\t\trow.link_attempt_id,\n\t\trow.link_controller_attestation_id,\n\t\trow.link_auth_config_revision,\n\t\trow.browser_start_hash,\n\t\trow.browser_transaction_hash,\n\t\trow.browser_binder_hash,\n\t\trow.confirmation_hash,\n\t\trow.completion_secret_hash,\n\t\trow.final_key_proof_hash,\n\t\trow.created_at_ms,\n\t\trow.expires_at_ms,\n\t\trow.loopback_redirect,\n\t\trow.coordinator_id,\n\t\trow.attempt_id,\n\t\trow.audit_event_id,\n\t\trow.audit_event_id,\n\t\trow.attempt_id,\n\t\trow.binding_id,\n\t\trow.device_id,\n\t\trow.finalized_at_ms,\n\t\trow.grant_revisions_json,\n\t\trow.device_id,\n\t\trow.public_key,\n\t\trow.fingerprint,\n\t\trow.identity_id,\n\t\ttimestamp,\n\t];\n}\n/** Prior writes only; missing enrollment/audit rows are never repaired and revocations are never undone. */\nexport async function readOwnerEnrollmentReceipt(\n\tbackend: AuthLinkBackend,\n\trow: OwnerAttempt,\n): Promise<boolean> {\n\tconst a = Object.freeze({ ...row });\n\tif (!validOwnerEnrollmentReceiptMetadata(a) || !(await matchesAdmissionOwner(a))) return false;\n\tif ((await ownerEnrollmentConfirmationHash(a)) !== a.confirmation_hash) return false;\n\tconst authority = await readOwnerLinkAuthority(backend);\n\tif (!authority.hasPin && a.owner_qualification_id != null) return false;\n\tlet sql = RECEIPT_SQL;\n\tconst values = receiptValues(a);\n\tif (authority.hasPin) {\n\t\tsql += ` AND EXISTS (SELECT 1 FROM coordinator_owner_enrollment_attempts a\n WHERE a.coordinator_id=b.coordinator_id AND a.attempt_id=b.source_ref AND a.owner_qualification_id IS ?)`;\n\t\tvalues.push(a.owner_qualification_id ?? null);\n\t}\n\tconst found = await backend.first({ sql, values });\n\treturn found !== null;\n}\n","import { hasConnectionSessionSchema } from \"./coordinator-account-connection-session.js\";\nimport { CONNECTION_NOT_REVOKED_SQL } from \"./coordinator-account-connection-storage.js\";\nimport type { CoordinatorAuthBrowserConfig } from \"./coordinator-auth-browser-transaction-contract.js\";\nimport type { AuthLinkBackend, AuthLinkStatement } from \"./coordinator-auth-link.js\";\nimport { authAccountLinkProvenanceSql } from \"./coordinator-auth-link-provenance.js\";\nimport { AUTH_SESSION_LIVE_GUARD_SQL } from \"./coordinator-auth-session.js\";\nimport { ownerExcludedLegacyDecisionSql } from \"./coordinator-owner-enrollment-commit.js\";\nimport type { OwnerEnrollmentResolvedOwner } from \"./owner-enrollment-admission.js\";\nimport { readOwnerLinkAuthority } from \"./owner-enrollment-link-authority.js\";\n\nexport const OWNER_ADMISSION_SCHEMA_READY_SQL = `EXISTS (SELECT 1 FROM pragma_table_info('coordinator_owner_enrollment_attempts')\n WHERE name = 'admission_owner_hash') AND (SELECT count(*) FROM sqlite_master\n WHERE type = 'trigger' AND tbl_name = 'coordinator_owner_enrollment_attempts'\n AND name IN ('owner_enrollment_admission_insert','owner_enrollment_admission_update')) = 2`;\n\nexport async function ownerAdmissionSchemaReady(backend: AuthLinkBackend): Promise<boolean> {\n\tconst row = await backend.first<{ ready: number }>({\n\t\tsql: `SELECT (${OWNER_ADMISSION_SCHEMA_READY_SQL}) AS ready`,\n\t\tvalues: [],\n\t});\n\treturn row?.ready === 1;\n}\n\n/** Uses the management session's full database-derived provenance, not a new login shortcut.\n * Alias a supplies the pending device so exclusions are identical to callback/commit.\n * Controller enrollment is historical evidence: its old device need not remain active.\n */\nasync function authoritySql(\n\tbackend: AuthLinkBackend,\n\ttime: number,\n\tcoordinatorId: string,\n\tsessionCookieHash: string,\n) {\n\t// The credential's unique session selects at most one link before any proof work.\n\t// This is only a work scope: the live session and all authority guards still win below.\n\tconst scope = {\n\t\tsql: `l.coordinator_id=? AND l.link_id=(SELECT link_id FROM coordinator_auth_sessions\n WHERE coordinator_id=? AND credential_hash=?)`,\n\t\tvalues: [coordinatorId, coordinatorId, sessionCookieHash],\n\t};\n\tconst connections = await hasConnectionSessionSchema(backend);\n\tconst authority = await readOwnerLinkAuthority(backend, time, scope);\n\treturn {\n\t\tvalues: authority.values,\n\t\t// Isolate the full session provenance from grant/exact-owner/INSERT predicates.\n\t\t// Native D1 counts nested provenance toward its expression-depth limit of 100.\n\t\twith: `${authority.with ? `${authority.with},` : \"WITH\"} owner_admission_proven_links AS MATERIALIZED (\n SELECT l.* FROM owner_scope_links l WHERE ${authAccountLinkProvenanceSql(\"l\", { connections })}),\n owner_admission_links AS MATERIALIZED (\n SELECT l.* FROM owner_admission_proven_links l WHERE ${authority.link}\n ${connections ? `AND (${CONNECTION_NOT_REVOKED_SQL})` : \"\"}),\n owner_admission_sessions AS MATERIALIZED (\n SELECT s.coordinator_id,s.identity_id,s.link_id,s.issuer,s.subject,l.authority_kind,l.controller_attestation_id\n FROM coordinator_auth_sessions s JOIN owner_admission_links l\n ON l.coordinator_id=s.coordinator_id AND l.link_id=s.link_id AND l.identity_id=s.identity_id\n AND l.issuer=s.issuer AND l.subject=s.subject WHERE (${AUTH_SESSION_LIVE_GUARD_SQL}))`,\n\t\tfrom: `FROM (SELECT ? AS coordinator_id,? AS device_id,? AS fingerprint) a\n JOIN owner_admission_sessions s ON s.coordinator_id = a.coordinator_id\n WHERE EXISTS (SELECT 1 FROM coordinator_identity_group_grants r JOIN groups g ON g.group_id = r.group_id\n WHERE r.coordinator_id = s.coordinator_id AND r.identity_id = s.identity_id\n AND r.status = 'active' AND r.revoked_at IS NULL AND g.archived_at IS NULL\n AND NOT ${ownerExcludedLegacyDecisionSql(\"r.group_id\")})`,\n\t};\n}\nfunction sessionValues(config: CoordinatorAuthBrowserConfig, hash: string, time: number) {\n\treturn [config.coordinatorId, hash, config.issuer, config.revision, time, time];\n}\n\nexport async function readOwnerAdmissionAuthority(input: {\n\tbackend: AuthLinkBackend;\n\tconfig: CoordinatorAuthBrowserConfig;\n\tsessionCookieHash: string;\n\ttime: number;\n\tdeviceId: string;\n\tfingerprint: string;\n}): Promise<OwnerEnrollmentResolvedOwner | null> {\n\tconst { backend, config, sessionCookieHash, time, deviceId, fingerprint } = input;\n\tconst authority = await authoritySql(backend, time, config.coordinatorId, sessionCookieHash);\n\tconst row = await backend.first<{\n\t\tidentity_id: string;\n\t\tlink_id: string;\n\t\tissuer: string;\n\t\tsubject: string;\n\t}>({\n\t\tsql: `${authority.with} SELECT s.identity_id,s.link_id,s.issuer,s.subject ${authority.from}`,\n\t\tvalues: [\n\t\t\t...authority.values,\n\t\t\t...sessionValues(config, sessionCookieHash, time),\n\t\t\tconfig.coordinatorId,\n\t\t\tdeviceId,\n\t\t\tfingerprint,\n\t\t],\n\t});\n\treturn row\n\t\t? {\n\t\t\t\tcoordinatorId: config.coordinatorId,\n\t\t\t\tissuer: row.issuer,\n\t\t\t\tsubject: row.subject,\n\t\t\t\tidentityId: row.identity_id,\n\t\t\t\tlinkId: row.link_id,\n\t\t\t}\n\t\t: null;\n}\n\n/** Materialized by the winning INSERT; revocation/config/grant races cannot create a new attempt. */\nexport async function ownerAdmissionSessionGuard(input: {\n\tbackend: AuthLinkBackend;\n\tconfig: CoordinatorAuthBrowserConfig;\n\tsessionCookieHash: string;\n\towner: OwnerEnrollmentResolvedOwner;\n\tdeviceId: string;\n\tfingerprint: string;\n\ttime: number;\n}): Promise<AuthLinkStatement> {\n\tconst { backend, config, sessionCookieHash, owner, deviceId, fingerprint, time } = input;\n\tconst authority = await authoritySql(backend, time, config.coordinatorId, sessionCookieHash);\n\treturn {\n\t\tsql: `${authority.with} SELECT 1 ${authority.from}\n AND s.link_id = ? AND s.identity_id = ? AND s.issuer = ? AND s.subject = ?`,\n\t\tvalues: [\n\t\t\t...authority.values,\n\t\t\t...sessionValues(config, sessionCookieHash, time),\n\t\t\tconfig.coordinatorId,\n\t\t\tdeviceId,\n\t\t\tfingerprint,\n\t\t\towner.linkId,\n\t\t\towner.identityId,\n\t\t\towner.issuer,\n\t\t\towner.subject,\n\t\t],\n\t};\n}\n","import { CoordinatorAuthBrowserTransactions } from \"./coordinator-auth-browser-transaction.js\";\nimport type { CoordinatorAuthBrowserConfig } from \"./coordinator-auth-browser-transaction-contract.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport {\n\ttype AuthLinkBackend,\n\ttype AuthLinkStatement,\n\tauthLinkNow,\n} from \"./coordinator-auth-link.js\";\nimport {\n\tAUTH_LINK_CREATE_WINDOW_MS,\n\tAUTH_LINK_MAX_ACTIVE_PER_DEVICE,\n\tAUTH_LINK_MAX_CREATES_PER_DEVICE_WINDOW,\n\tAUTH_LINK_MAX_UNFINISHED_PER_COORDINATOR,\n} from \"./coordinator-auth-link-contract.js\";\nimport { parseCoordinatorAuthLoopback } from \"./coordinator-auth-loopback.js\";\nimport {\n\tdecodeCoordinatorAuthProof32,\n\thashCoordinatorAuthProofBytes32,\n} from \"./coordinator-auth-proof.js\";\nimport { captureCoordinatorBrowserAuthConfig } from \"./coordinator-browser-auth-config.js\";\nimport {\n\tclearBrowserCookie,\n\treadBrowserCookie,\n\treissueStartCookieAsTransaction,\n} from \"./coordinator-browser-credential.js\";\nimport {\n\ttype BrowserCsrfKey,\n\ttype BrowserCsrfScope,\n\tisBrowserCsrfKey,\n\tissueBrowserCsrfToken,\n} from \"./coordinator-browser-csrf.js\";\nimport { guardBrowserForm } from \"./coordinator-browser-form-guard.js\";\nimport { snapshotBrowserRequest } from \"./coordinator-browser-request.js\";\nimport { readBrowserStartTransaction } from \"./coordinator-browser-start-transaction.js\";\nimport { ed25519KeyId } from \"./coordinator-ed25519-key-id.js\";\nimport {\n\ttype CoordinatorOidcClient,\n\ttype CoordinatorOidcOptions,\n\tcreateCoordinatorOidcClient,\n} from \"./coordinator-oidc.js\";\nimport {\n\tcommitOwnerEnrollment,\n\tOWNER_ACTIVE_LINK_SQL,\n\townerExcludedLegacyDecisionSql,\n\treadOwnerEnrollmentReceipt,\n} from \"./coordinator-owner-enrollment-commit.js\";\nimport {\n\ttype OwnerAuthorityAttempt as OwnerAttempt,\n\townerEnrollmentConfirmationHash,\n\treadGrantPins,\n\tvalidAttemptTime,\n\tverifyOwnerEnrollmentSignature,\n\tverifyPendingKeySignatureAndHashes,\n} from \"./coordinator-owner-enrollment-proof.js\";\nimport {\n\tOWNER_ADMISSION_SCHEMA_READY_SQL,\n\townerAdmissionSessionGuard,\n} from \"./owner-browser-admission-authority.js\";\nimport {\n\tisOwnerEnrollmentAdmissionKey,\n\ttype OwnerEnrollmentAdmissionKey,\n\ttype OwnerEnrollmentResolvedOwner,\n\townerEnrollmentOwnerCommitment,\n\tverifyOwnerEnrollmentAdmission,\n\tverifyOwnerEnrollmentAdmissionV2,\n} from \"./owner-enrollment-admission.js\";\nimport {\n\tcontrollerOwnerLinkAuthority,\n\treadOwnerLinkAuthority,\n} from \"./owner-enrollment-link-authority.js\";\nimport { matchesAdmissionOwner, validAdmissionOwnerHash } from \"./owner-enrollment-owner-pin.js\";\nimport type { InMemoryRequestRateLimiter } from \"./request-rate-limit.js\";\n\nexport interface OwnerEnrollmentStart {\n\tattemptId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tloopbackRedirect: string;\n\tbrowserStartCode: string;\n\tsignature: string;\n}\n/** Trusted internal composition only. Never deserialize resolvedOwner from public request JSON. */\nexport interface OwnerEnrollmentOwnerBoundStartOptions {\n\tadmissionToken: string;\n\tresolvedOwner: OwnerEnrollmentResolvedOwner;\n\t/** Trusted browser composition only; never accepted from signed-start JSON. */\n\tsessionCookieHash?: string;\n}\ninterface OwnerEnrollmentFinalize {\n\tattemptId: string;\n\tcompletionSecret: string;\n\tsignature: string;\n}\nexport type OwnerEnrollmentReceipt = {\n\tkind: \"finalized\" | \"prior_commit\";\n\tbindingId: string;\n\tidentityId: string;\n\tgroups: string[];\n};\nexport type OwnerEnrollmentStartResult =\n\t| { kind: \"rejected\"; error: \"owner_enrollment_unavailable\" | \"owner_enrollment_unknown\" }\n\t| { kind: \"started\"; attemptId: string; expiresAtMs: number }\n\t| { kind: \"browser_claimed\"; authorizationUrl: string; setCookies: string[] }\n\t| { kind: \"verified\"; confirmation: OwnerEnrollmentConfirmation; csrf: string }\n\t| {\n\t\t\tkind: \"confirmed\";\n\t\t\tcompletionSecret: string;\n\t\t\tloopbackRedirect: string;\n\t\t\tconfirmation: OwnerEnrollmentConfirmation;\n\t }\n\t| OwnerEnrollmentReceipt;\ninterface OwnerEnrollmentConfirmation {\n\tattemptId: string;\n\tcoordinatorId: string;\n\torigin: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tkeyId: string;\n\tfingerprint: string;\n\tissuer: string;\n\tsubject: string;\n\tidentityId: string;\n\tlinkId: string;\n\trevision: string;\n\tconfirmationHash: string;\n\tgroups: readonly string[];\n}\ntype StartPin = { coordinatorId: string; origin: string; issuer: string; revision: string };\ninterface OwnerEnrollmentCompositionBase {\n\tpurpose: \"owner_enroll\";\n\tconfig: unknown;\n\tbackend: AuthLinkBackend;\n\tcsrfKey: BrowserCsrfKey;\n\tlimiter: InMemoryRequestRateLimiter;\n\toidcOptions: CoordinatorOidcOptions;\n\tclock?: () => number;\n}\nexport type OwnerEnrollmentComposition = OwnerEnrollmentCompositionBase &\n\t(\n\t\t| { mode: \"local_test\"; admissionKey?: never }\n\t\t| { mode: \"production\"; admissionKey: OwnerEnrollmentAdmissionKey }\n\t);\ntype Context = {\n\tbackend: AuthLinkBackend;\n\tc: CoordinatorAuthBrowserConfig;\n\tpin: StartPin;\n\tcsrfKey: BrowserCsrfKey;\n\tscope: BrowserCsrfScope;\n\tlimiter: InMemoryRequestRateLimiter;\n\tclient: CoordinatorOidcClient;\n\tnow: () => number;\n\tadmissionKey?: OwnerEnrollmentAdmissionKey;\n};\nconst unavailable: OwnerEnrollmentStartResult = Object.freeze({\n\tkind: \"rejected\",\n\terror: \"owner_enrollment_unavailable\",\n});\nconst OWNER_START_CLIENT_LIMIT = 20;\nconst OWNER_MAX_ACTIVE_PER_COORDINATOR = 1000;\nfunction own(value: unknown, name: string): unknown {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error();\n\tconst descriptor = Object.getOwnPropertyDescriptor(value, name);\n\tif (!descriptor || !Object.hasOwn(descriptor, \"value\")) throw new Error();\n\treturn descriptor.value;\n}\nfunction text(value: unknown, maximum: number): string {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\t!value ||\n\t\tvalue.length > maximum ||\n\t\t/[\\p{Cc}\\p{Cf}\\p{Cs}]/u.test(value)\n\t)\n\t\tthrow new Error();\n\treturn value;\n}\nfunction id(value: unknown): string {\n\tif (!isAuthControllerId(value)) throw new Error();\n\treturn value;\n}\nfunction captureStart(value: unknown): OwnerEnrollmentStart {\n\treturn Object.freeze({\n\t\tattemptId: id(own(value, \"attemptId\")),\n\t\tdeviceId: id(own(value, \"deviceId\")),\n\t\tpublicKey: text(own(value, \"publicKey\"), 4096),\n\t\tloopbackRedirect: text(own(value, \"loopbackRedirect\"), 4096),\n\t\tbrowserStartCode: text(own(value, \"browserStartCode\"), 43),\n\t\tsignature: text(own(value, \"signature\"), 86),\n\t});\n}\nfunction captureResolvedOwner(value: unknown): OwnerEnrollmentResolvedOwner {\n\treturn Object.freeze({\n\t\tcoordinatorId: id(own(value, \"coordinatorId\")),\n\t\tissuer: text(own(value, \"issuer\"), 4096),\n\t\tsubject: text(own(value, \"subject\"), 255),\n\t\tidentityId: id(own(value, \"identityId\")),\n\t\tlinkId: id(own(value, \"linkId\")),\n\t});\n}\nexport async function ownerEnrollmentHash(value: string): Promise<string> {\n\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(value));\n\treturn Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\nasync function proofHash(value: string): Promise<string> {\n\tconst bytes = decodeCoordinatorAuthProof32(value);\n\tif (!bytes) throw new Error();\n\treturn hashCoordinatorAuthProofBytes32(bytes);\n}\n/** Pending-key proof only; no account or ownership authority. */\nexport function ownerEnrollmentStartMessage(input: OwnerEnrollmentStart, config: StartPin): string {\n\treturn JSON.stringify([\n\t\t\"codemem-owner-enrollment-start-v1\",\n\t\t\"owner_enroll\",\n\t\tconfig.coordinatorId,\n\t\tconfig.origin,\n\t\tconfig.issuer,\n\t\tconfig.revision,\n\t\tinput.attemptId,\n\t\tinput.deviceId,\n\t\tinput.publicKey,\n\t\tinput.loopbackRedirect,\n\t\tinput.browserStartCode,\n\t]);\n}\nasync function boundary(\n\taction: () => Promise<OwnerEnrollmentStartResult>,\n): Promise<OwnerEnrollmentStartResult> {\n\ttry {\n\t\treturn await action();\n\t} catch {\n\t\treturn { kind: \"rejected\", error: \"owner_enrollment_unknown\" };\n\t}\n}\n\n/** Opt-in server composition. Production requires exact-start admission; local fixtures require custom fetch.\n * Native SQLite atomic batch semantics and schema constraints are required; errors\n * report unknown, never a claim that an attempted commit made no changes.\n */\nfunction captureComposition(input: OwnerEnrollmentComposition) {\n\tconst mode = own(input, \"mode\");\n\tif (\n\t\town(input, \"purpose\") !== \"owner_enroll\" ||\n\t\t![\"local_test\", \"production\"].includes(mode as string)\n\t)\n\t\tthrow new Error();\n\tconst settings = captureCoordinatorBrowserAuthConfig(own(input, \"config\"));\n\tif (settings.kind !== \"enabled\") throw new Error();\n\tconst oidcOptions = captureOwnerOidcOptions(mode, own(input, \"oidcOptions\"));\n\tconst admissionKey = mode === \"production\" ? own(input, \"admissionKey\") : undefined;\n\tif (mode === \"production\" && !isOwnerEnrollmentAdmissionKey(admissionKey)) throw new Error();\n\tconst csrfKey = own(input, \"csrfKey\");\n\tconst limiter = own(input, \"limiter\") as InMemoryRequestRateLimiter;\n\tif (!isBrowserCsrfKey(csrfKey) || typeof limiter?.check !== \"function\") throw new Error();\n\tconst backend = own(input, \"backend\") as AuthLinkBackend;\n\tif (\n\t\t!backend ||\n\t\t![backend.first, backend.run, backend.batch].every((f) => typeof f === \"function\")\n\t)\n\t\tthrow new Error();\n\treturn {\n\t\tmode,\n\t\tsettings,\n\t\tbackend,\n\t\tcsrfKey,\n\t\tlimiter,\n\t\toidcOptions,\n\t\tadmissionKey: admissionKey as OwnerEnrollmentAdmissionKey | undefined,\n\t};\n}\n\nfunction captureOwnerOidcOptions(mode: unknown, value: unknown): CoordinatorOidcOptions {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error();\n\tconst captured: Record<string, unknown> = {};\n\tfor (const name of [\"fetch\", \"timeoutSeconds\"]) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, name);\n\t\tif (descriptor && !Object.hasOwn(descriptor, \"value\")) throw new Error();\n\t\tcaptured[name] = descriptor?.value;\n\t}\n\tconst { fetch, timeoutSeconds } = captured;\n\tif (fetch !== undefined && typeof fetch !== \"function\") throw new Error();\n\tif (mode === \"local_test\" && typeof fetch !== \"function\") throw new Error();\n\tif (\n\t\ttimeoutSeconds !== undefined &&\n\t\t(typeof timeoutSeconds !== \"number\" ||\n\t\t\t!Number.isFinite(timeoutSeconds) ||\n\t\t\ttimeoutSeconds < 1 ||\n\t\t\ttimeoutSeconds > 30)\n\t)\n\t\tthrow new Error();\n\treturn {\n\t\tfetch: fetch as CoordinatorOidcOptions[\"fetch\"],\n\t\ttimeoutSeconds: timeoutSeconds as number | undefined,\n\t};\n}\n\nexport async function createCoordinatorOwnerEnrollment(input: OwnerEnrollmentComposition) {\n\ttry {\n\t\tconst { mode, settings, backend, csrfKey, limiter, oidcOptions, admissionKey } =\n\t\t\tcaptureComposition(input);\n\t\tconst client = await composeOidcClient(mode, settings.oidc, oidcOptions);\n\t\tconst c = settings.store;\n\t\tconst clock = input.clock ?? Date.now;\n\t\tconst context: Context = {\n\t\t\tbackend,\n\t\t\tc,\n\t\t\tclient,\n\t\t\tadmissionKey,\n\t\t\tnow: () => authLinkNow(clock),\n\t\t\tpin: Object.freeze({\n\t\t\t\tcoordinatorId: c.coordinatorId,\n\t\t\t\torigin: settings.publicOrigin,\n\t\t\t\tissuer: c.issuer,\n\t\t\t\trevision: c.revision,\n\t\t\t}),\n\t\t\tscope: Object.freeze({ publicOrigin: settings.publicOrigin, store: c }),\n\t\t\tcsrfKey,\n\t\t\tlimiter,\n\t\t};\n\t\treturn {\n\t\t\tok: true as const,\n\t\t\tenrollment: Object.freeze({\n\t\t\t\t// clientKey must come from the trusted transport, never the signed request body.\n\t\t\t\tstart: (value: OwnerEnrollmentStart, clientKey: string, admissionToken?: string) =>\n\t\t\t\t\tboundary(() =>\n\t\t\t\t\t\tstart(context, value, clientKey, { kind: \"operator\", token: admissionToken }),\n\t\t\t\t\t),\n\t\t\t\t// Unmounted until a separately reviewed authenticated browser issuer exists.\n\t\t\t\tstartOwnerBound: (\n\t\t\t\t\tvalue: OwnerEnrollmentStart,\n\t\t\t\t\tclientKey: string,\n\t\t\t\t\toptions: OwnerEnrollmentOwnerBoundStartOptions,\n\t\t\t\t) => boundary(() => start(context, value, clientKey, { kind: \"owner\", options })),\n\t\t\t\tclaimBrowser: (request: Request, clientKey: string) =>\n\t\t\t\t\tboundary(() => claimBrowser(context, request, clientKey)),\n\t\t\t\tverifyCallback: (request: Request) => boundary(() => verifyCallback(context, request)),\n\t\t\t\tconfirm: (request: Request, clientKey: string, confirmationCommitment: string) =>\n\t\t\t\t\tboundary(() => confirm(context, request, clientKey, confirmationCommitment)),\n\t\t\t\tfinalize: (value: OwnerEnrollmentFinalize) => boundary(() => finalize(context, value)),\n\t\t\t}),\n\t\t};\n\t} catch {\n\t\treturn { ok: false as const };\n\t}\n}\n\nasync function composeOidcClient(\n\tmode: unknown,\n\tconfig: Parameters<typeof createCoordinatorOidcClient>[0],\n\toptions: CoordinatorOidcOptions,\n): Promise<CoordinatorOidcClient> {\n\tif (mode === \"production\") return deferredOidcClient(config, options);\n\tconst result = await createCoordinatorOidcClient(config, options);\n\tif (!result.ok) throw new Error(\"owner_enrollment_oidc_unavailable\");\n\treturn result.client;\n}\n\n/** Discovery is deferred until an eligible browser claim or consumed callback. */\nfunction deferredOidcClient(\n\tconfig: Parameters<typeof createCoordinatorOidcClient>[0],\n\toptions: CoordinatorOidcOptions,\n): CoordinatorOidcClient {\n\tlet settled: CoordinatorOidcClient | undefined;\n\tasync function getClient() {\n\t\tif (settled) return settled;\n\t\tconst result = await createCoordinatorOidcClient(config, options);\n\t\tif (!result.ok) throw new Error(\"owner_enrollment_oidc_unavailable\");\n\t\tsettled ??= result.client;\n\t\treturn settled;\n\t}\n\treturn {\n\t\tcreateAuthorizationRequest: async () => (await getClient()).createAuthorizationRequest(),\n\t\tverifyCallback: async (input, callbackOptions) =>\n\t\t\t(await getClient()).verifyCallback(input, callbackOptions),\n\t};\n}\n\ninterface OwnerBrowserTransaction {\n\tbrowser_transaction_hash: string;\n\tattempt_id: string;\n\tstate_hash: string;\n\tbinder_hash: string;\n\tnonce: string;\n\tpkce_verifier: string;\n\tcreated_at_ms: number;\n\texpires_at_ms: number;\n}\ninterface ConsumedOwnerBrowser {\n\ttxn: OwnerBrowserTransaction;\n\trow: OwnerAttempt;\n\tclaimToken: string;\n}\nasync function verifyCallback(\n\tcontext: Context,\n\trequest: Request,\n): Promise<OwnerEnrollmentStartResult> {\n\tconst snapshot = snapshotBrowserRequest(request);\n\tif (snapshot.method !== \"GET\" || snapshot.url.length > 8192 || snapshot.url.includes(\"#\"))\n\t\treturn unavailable;\n\tconst url = new URL(snapshot.url);\n\tconst redirect = new URL(context.c.redirectUri);\n\tconst states = url.searchParams.getAll(\"state\");\n\tif (\n\t\turl.origin !== redirect.origin ||\n\t\turl.pathname !== redirect.pathname ||\n\t\turl.username ||\n\t\turl.password ||\n\t\tstates.length !== 1 ||\n\t\t!/^[A-Za-z0-9._~-]{43,128}$/.test(states[0] ?? \"\")\n\t)\n\t\treturn unavailable;\n\tconst state = states[0] as string;\n\tconst cookie = await readBrowserCookie(snapshot.cookie, \"transaction\");\n\tif (cookie.kind !== \"present\") return unavailable;\n\tconst consumed = await consumeOwnerBrowser(context, state, cookie.cookieHash);\n\tif (!consumed) return unavailable;\n\t// Capture the original material before burning it; the maintained client verifies\n\t// ID-token signatures, issuer, nonce and PKCE. No browser session supplies identity.\n\tconst verified = await context.client.verifyCallback(\n\t\t{\n\t\t\tcallbackUrl: snapshot.url,\n\t\t\tmaterial: { state, nonce: consumed.txn.nonce, pkceVerifier: consumed.txn.pkce_verifier },\n\t\t},\n\t\t{ fetchUserInfo: false },\n\t);\n\tif (!verified.ok || verified.account.issuer !== context.c.issuer) return unavailable;\n\tconst row = await persistVerified(context, consumed, verified.account);\n\tif (!row) return unavailable;\n\tconst confirmation = await confirmationView(row);\n\tconst csrf = await issueBrowserCsrfToken(\n\t\tcontext.csrfKey,\n\t\tcookie.secret,\n\t\t\"transaction\",\n\t\tcontext.scope,\n\t);\n\treturn { kind: \"verified\", confirmation, csrf };\n}\nfunction ownerAttemptSql(state: \"browser_claimed\" | \"oidc_verified\"): string {\n\treturn `a.coordinator_id = ? AND a.attempt_id = ? AND a.purpose = 'owner_enroll'\n AND a.state = '${state}' AND a.origin = ? AND a.issuer = ? AND a.auth_config_revision = ?\n AND a.browser_transaction_hash = ? AND a.browser_binder_hash = ?\n AND a.device_id = ? AND a.public_key = ? AND a.key_id = ? AND a.fingerprint = ?\n AND a.browser_start_hash = ? AND a.loopback_redirect = ? AND a.created_at_ms = ? AND a.expires_at_ms = ?\n AND a.admission_owner_hash IS ?\n AND ${OWNER_ADMISSION_SCHEMA_READY_SQL}\n AND a.created_at_ms <= ? AND a.expires_at_ms > ?`;\n}\nfunction callbackAttemptValues(\n\tcontext: Context,\n\ta: OwnerAttempt,\n\ttime: number,\n): AuthLinkStatement[\"values\"] {\n\treturn [\n\t\tcontext.c.coordinatorId,\n\t\ta.attempt_id,\n\t\tcontext.pin.origin,\n\t\tcontext.c.issuer,\n\t\tcontext.c.revision,\n\t\ta.browser_transaction_hash,\n\t\ta.browser_binder_hash,\n\t\ta.device_id,\n\t\ta.public_key,\n\t\ta.key_id,\n\t\ta.fingerprint,\n\t\ta.browser_start_hash,\n\t\ta.loopback_redirect,\n\t\ta.created_at_ms,\n\t\ta.expires_at_ms,\n\t\ta.admission_owner_hash,\n\t\ttime,\n\t\ttime,\n\t];\n}\nconst CALLBACK_TXN_SQL = `b.coordinator_id = ? AND b.browser_transaction_hash = ? AND b.purpose = 'owner_enroll'\n AND b.attempt_id = ? AND b.state_hash = ? AND b.binder_hash = ? AND b.issuer = ?\n AND b.auth_config_revision = ? AND b.redirect_uri = ? AND b.created_at_ms = ? AND b.expires_at_ms = ?\n AND b.created_at_ms <= ? AND b.expires_at_ms > ?`;\nfunction callbackTxnValues(\n\tcontext: Context,\n\tb: OwnerBrowserTransaction,\n\ttime: number,\n): AuthLinkStatement[\"values\"] {\n\treturn [\n\t\tcontext.c.coordinatorId,\n\t\tb.browser_transaction_hash,\n\t\tb.attempt_id,\n\t\tb.state_hash,\n\t\tb.binder_hash,\n\t\tcontext.c.issuer,\n\t\tcontext.c.revision,\n\t\tcontext.c.redirectUri,\n\t\tb.created_at_ms,\n\t\tb.expires_at_ms,\n\t\ttime,\n\t\ttime,\n\t];\n}\nasync function consumeOwnerBrowser(\n\tcontext: Context,\n\tstate: string,\n\tbinderHash: string,\n): Promise<ConsumedOwnerBrowser | null> {\n\tconst time = context.now();\n\tconst txn = await context.backend.first<OwnerBrowserTransaction>({\n\t\tsql: `SELECT * FROM coordinator_auth_browser_transactions WHERE coordinator_id = ?\n AND purpose = 'owner_enroll' AND state_hash = ? AND binder_hash = ? AND state = 'pending'\n AND issuer = ? AND auth_config_revision = ? AND redirect_uri = ? AND created_at_ms <= ? AND expires_at_ms > ?`,\n\t\tvalues: [\n\t\t\tcontext.c.coordinatorId,\n\t\t\tawait ownerEnrollmentHash(state),\n\t\t\tbinderHash,\n\t\t\tcontext.c.issuer,\n\t\t\tcontext.c.revision,\n\t\t\tcontext.c.redirectUri,\n\t\t\ttime,\n\t\t\ttime,\n\t\t],\n\t});\n\tif (!txn) return null;\n\tconst row = await readAttempt(context, txn.attempt_id);\n\tif (\n\t\t!live(context, row, time) ||\n\t\trow.state !== \"browser_claimed\" ||\n\t\trow.browser_transaction_hash !== txn.browser_transaction_hash ||\n\t\trow.browser_binder_hash !== binderHash ||\n\t\trow.expires_at_ms !== txn.expires_at_ms ||\n\t\ttxn.created_at_ms < row.created_at_ms\n\t)\n\t\treturn null;\n\tconst claimToken = globalThis.crypto.randomUUID();\n\tconst burnTime = context.now();\n\tconst wrote = await context.backend.run({\n\t\tsql: `UPDATE coordinator_auth_browser_transactions AS b SET state = 'consumed',claim_token = ?,\n consumed_at_ms = ?,nonce = NULL,pkce_verifier = NULL WHERE ${CALLBACK_TXN_SQL}\n AND b.state = 'pending' AND b.nonce = ? AND b.pkce_verifier = ?\n AND EXISTS (SELECT 1 FROM coordinator_owner_enrollment_attempts a WHERE ${ownerAttemptSql(\"browser_claimed\")})`,\n\t\tvalues: [\n\t\t\tclaimToken,\n\t\t\tburnTime,\n\t\t\t...callbackTxnValues(context, txn, burnTime),\n\t\t\ttxn.nonce,\n\t\t\ttxn.pkce_verifier,\n\t\t\t...callbackAttemptValues(context, row, burnTime),\n\t\t],\n\t});\n\treturn wrote === 1 ? { txn, row, claimToken } : null;\n}\ninterface OwnerAccountLink {\n\tlink_id: string;\n\tidentity_id: string;\n\tattempt_id: string;\n\tcontroller_attestation_id: string | null;\n\towner_qualification_id: string | null;\n\tauth_config_revision: string;\n\tcreated_at_ms: number;\n\tauthority_kind: string;\n\tdevice_claim_id: string | null;\n}\n// Filter each Team before pinning; the winning update repeats this exact snapshot.\nconst CALLBACK_GRANTS_SQL = `SELECT json_group_array(json_object('groupId',groupId,'revision',revision)) FROM\n (SELECT r.group_id AS groupId,r.revision AS revision FROM coordinator_identity_group_grants r\n JOIN groups g ON g.group_id = r.group_id WHERE r.coordinator_id = a.coordinator_id AND r.identity_id = ?\n AND r.status = 'active' AND r.revoked_at IS NULL AND g.archived_at IS NULL\n AND NOT ${ownerExcludedLegacyDecisionSql(\"r.group_id\")} ORDER BY r.group_id LIMIT 51)`;\nasync function persistVerified(\n\tcontext: Context,\n\tconsumed: ConsumedOwnerBrowser,\n\taccount: { issuer: string; subject: string },\n): Promise<OwnerAttempt | null> {\n\tconst candidate = await context.backend.first<OwnerAccountLink>({\n\t\tsql: `SELECT l.*,NULL AS owner_qualification_id FROM coordinator_auth_account_links l WHERE l.coordinator_id = ? AND l.issuer = ? AND l.subject = ? AND l.revoked_at_ms IS NULL`,\n\t\tvalues: [context.c.coordinatorId, account.issuer, account.subject],\n\t});\n\tif (!candidate) return null;\n\tconst resolved = await callbackLinkAuthority(context, consumed.row, candidate);\n\tif (!resolved) return null;\n\tconst { link, authority } = resolved;\n\tif (\n\t\t!(await matchesAdmissionOwner({\n\t\t\t...consumed.row,\n\t\t\tissuer: account.issuer,\n\t\t\taccount_subject: account.subject,\n\t\t\tidentity_id: link.identity_id,\n\t\t\tlink_id: link.link_id,\n\t\t}))\n\t)\n\t\treturn null;\n\tconst grants = await context.backend.first<{ rows: string }>({\n\t\tsql: `SELECT (${CALLBACK_GRANTS_SQL}) AS rows FROM coordinator_owner_enrollment_attempts a\n WHERE ${ownerAttemptSql(\"browser_claimed\")}`,\n\t\tvalues: [link.identity_id, ...callbackAttemptValues(context, consumed.row, context.now())],\n\t});\n\tif (!grants || !readGrantPins(grants.rows)) return null;\n\tconst time = context.now();\n\tconst wrote = await context.backend.run(\n\t\tverifiedStatement(context, consumed, account, link, grants.rows, time, authority),\n\t);\n\tif (wrote !== 1) return null;\n\tconst row = await readAttempt(context, consumed.row.attempt_id);\n\t// A missing or changed post-write read is unknown, not evidence the write failed.\n\tif (\n\t\trow?.state !== \"oidc_verified\" ||\n\t\trow.admission_owner_hash !== consumed.row.admission_owner_hash ||\n\t\trow.link_id !== link.link_id ||\n\t\t(row.owner_qualification_id ?? null) !== link.owner_qualification_id ||\n\t\trow.link_controller_attestation_id !== link.controller_attestation_id ||\n\t\trow.account_subject !== account.subject ||\n\t\trow.grant_revisions_json !== grants.rows ||\n\t\trow.browser_transaction_hash !== consumed.txn.browser_transaction_hash ||\n\t\trow.browser_binder_hash !== consumed.txn.binder_hash\n\t)\n\t\tthrow new Error();\n\treturn row;\n}\nasync function callbackLinkAuthority(\n\tcontext: Context,\n\tattempt: OwnerAttempt,\n\tlink: OwnerAccountLink,\n) {\n\tconst scope = {\n\t\tsql: \"l.coordinator_id=? AND l.link_id=?\",\n\t\tvalues: [context.c.coordinatorId, link.link_id],\n\t};\n\tif (\n\t\tlink.authority_kind === \"controller_attestation\" &&\n\t\tisAuthControllerId(link.controller_attestation_id) &&\n\t\tlink.device_claim_id === null\n\t)\n\t\treturn { authority: controllerOwnerLinkAuthority(attempt, scope), link };\n\tif (\n\t\tlink.authority_kind !== \"device_claim\" ||\n\t\tlink.controller_attestation_id !== null ||\n\t\t!isAuthControllerId(link.device_claim_id)\n\t)\n\t\treturn null;\n\tconst authority = await readOwnerLinkAuthority(context.backend, context.now(), scope);\n\tconst qualified = await context.backend.first<{ owner_qualification_id: string | null }>({\n\t\tsql: `${authority.with}SELECT ${authority.qualification} AS owner_qualification_id\n FROM owner_scope_links l WHERE l.coordinator_id=? AND l.link_id=?\n AND l.revoked_at_ms IS NULL AND ${authority.link}`,\n\t\tvalues: [...authority.values, context.c.coordinatorId, link.link_id],\n\t});\n\tif (!qualified?.owner_qualification_id) return null;\n\treturn { authority, link: { ...link, owner_qualification_id: qualified.owner_qualification_id } };\n}\nfunction verifiedStatement(\n\tcontext: Context,\n\tconsumed: ConsumedOwnerBrowser,\n\taccount: { issuer: string; subject: string },\n\tlink: OwnerAccountLink,\n\tgrants: string,\n\ttime: number,\n\tauthority: Awaited<ReturnType<typeof readOwnerLinkAuthority>>,\n): AuthLinkStatement {\n\t// Keep consumed-browser proof and link provenance in separate native D1 depth trees.\n\treturn {\n\t\tsql: `${authority.with ? `${authority.with},` : \"WITH\"} owner_callback_attempts AS MATERIALIZED (\n SELECT a.coordinator_id,a.attempt_id FROM coordinator_owner_enrollment_attempts a\n WHERE ${ownerAttemptSql(\"browser_claimed\")}\n AND EXISTS (SELECT 1 FROM coordinator_auth_browser_transactions b WHERE ${CALLBACK_TXN_SQL}\n AND b.state = 'consumed' AND b.claim_token = ? AND b.nonce IS NULL AND b.pkce_verifier IS NULL)),\n owner_callback_links AS MATERIALIZED (\n SELECT l.*,${authority.qualification} AS owner_qualification_id FROM owner_scope_links l\n WHERE ${authority.link})\n UPDATE coordinator_owner_enrollment_attempts AS a SET state = 'oidc_verified',\n account_subject = ?,identity_id = ?,link_id = ?,link_attempt_id = ?,link_controller_attestation_id = ?,\n ${authority.hasPin ? \"owner_qualification_id = ?,\" : \"\"}link_auth_config_revision = ?,grant_revisions_json = ?\n WHERE a.coordinator_id=? AND a.attempt_id=?\n AND EXISTS (SELECT 1 FROM owner_callback_attempts p WHERE p.coordinator_id=a.coordinator_id AND p.attempt_id=a.attempt_id)\n AND EXISTS (SELECT 1 FROM owner_callback_links l WHERE l.coordinator_id = a.coordinator_id\n AND l.link_id = ? AND l.issuer = a.issuer AND l.subject = ? AND l.identity_id = ? AND l.attempt_id = ?\n AND l.controller_attestation_id IS ? AND l.owner_qualification_id IS ? AND l.auth_config_revision = ? AND l.created_at_ms = ? AND l.revoked_at_ms IS NULL)\n AND (${CALLBACK_GRANTS_SQL}) = ?\n AND ${NO_COLLISION_SQL}`,\n\t\tvalues: [\n\t\t\t...authority.values,\n\t\t\t...callbackAttemptValues(context, consumed.row, time),\n\t\t\t...callbackTxnValues(context, consumed.txn, time),\n\t\t\tconsumed.claimToken,\n\t\t\taccount.subject,\n\t\t\tlink.identity_id,\n\t\t\tlink.link_id,\n\t\t\tlink.attempt_id,\n\t\t\tlink.controller_attestation_id,\n\t\t\t...(authority.hasPin ? [link.owner_qualification_id] : []),\n\t\t\tlink.auth_config_revision,\n\t\t\tgrants,\n\t\t\tconsumed.row.coordinator_id,\n\t\t\tconsumed.row.attempt_id,\n\t\t\tlink.link_id,\n\t\t\taccount.subject,\n\t\t\tlink.identity_id,\n\t\t\tlink.attempt_id,\n\t\t\tlink.controller_attestation_id,\n\t\t\tlink.owner_qualification_id,\n\t\t\tlink.auth_config_revision,\n\t\t\tlink.created_at_ms,\n\t\t\tlink.identity_id,\n\t\t\tgrants,\n\t\t\tconsumed.row.device_id,\n\t\t\tconsumed.row.key_id,\n\t\t\tconsumed.row.device_id,\n\t\t\tconsumed.row.key_id,\n\t\t],\n\t};\n}\nasync function confirmationView(row: OwnerAttempt): Promise<OwnerEnrollmentConfirmation> {\n\tif (!row.account_subject || !row.identity_id || !row.link_id) throw new Error();\n\tif (!(await matchesAdmissionOwner(row))) throw new Error();\n\tconst grants = readGrantPins(row.grant_revisions_json);\n\tif (!grants) throw new Error();\n\t// Display commitment; confirm() persists it with the completion-secret hash.\n\tconst confirmationHash = await ownerEnrollmentConfirmationHash(row);\n\treturn Object.freeze({\n\t\tattemptId: row.attempt_id,\n\t\tcoordinatorId: row.coordinator_id,\n\t\torigin: row.origin,\n\t\tdeviceId: row.device_id,\n\t\tpublicKey: row.public_key,\n\t\tkeyId: row.key_id,\n\t\tfingerprint: row.fingerprint,\n\t\tissuer: row.issuer,\n\t\tsubject: row.account_subject,\n\t\tidentityId: row.identity_id,\n\t\tlinkId: row.link_id,\n\t\trevision: row.auth_config_revision,\n\t\tconfirmationHash,\n\t\tgroups: Object.freeze(grants.map((grant) => grant.groupId)),\n\t});\n}\n\n// Both the preflight read and winning update require the consumed transaction,\n// exact linked account provenance, and the same active grant snapshot shown to the user.\nconst CONFIRM_AUTHORITY_SQL = `${OWNER_ACTIVE_LINK_SQL}\n AND (${CALLBACK_GRANTS_SQL}) = a.grant_revisions_json\n AND NOT EXISTS (SELECT 1 FROM json_each(a.grant_revisions_json) p WHERE ${ownerExcludedLegacyDecisionSql(\"json_extract(p.value,'$.groupId')\")})\n AND EXISTS (SELECT 1 FROM coordinator_auth_browser_transactions b\n WHERE b.coordinator_id = a.coordinator_id AND b.attempt_id = a.attempt_id AND b.purpose = 'owner_enroll'\n AND b.browser_transaction_hash = a.browser_transaction_hash AND b.binder_hash = a.browser_binder_hash\n AND b.issuer = a.issuer AND b.auth_config_revision = a.auth_config_revision AND b.redirect_uri = ?\n AND b.state = 'consumed' AND b.claim_token IS NOT NULL AND b.nonce IS NULL AND b.pkce_verifier IS NULL\n AND b.created_at_ms >= a.created_at_ms AND b.created_at_ms <= ?\n AND b.expires_at_ms = a.expires_at_ms)`;\nfunction confirmAuthorityValues(context: Context, row: OwnerAttempt, time: number) {\n\treturn [row.coordinator_id, row.attempt_id, row.identity_id, context.c.redirectUri, time];\n}\nfunction confirmAuthorityCte(authority: Awaited<ReturnType<typeof readOwnerLinkAuthority>>) {\n\t// JOIN/UPDATE FROM consumes this stage without nesting its proof under attempt pins.\n\treturn `${authority.with ? `${authority.with},` : \"WITH\"} owner_confirm_authority AS MATERIALIZED (\n SELECT a.coordinator_id,a.attempt_id FROM coordinator_owner_enrollment_attempts a\n WHERE a.coordinator_id=? AND a.attempt_id=?\n AND ${CONFIRM_AUTHORITY_SQL.replace(OWNER_ACTIVE_LINK_SQL, authority.active)}) `;\n}\nconst CONFIRM_AUTHORITY_MATCH_SQL = `p.coordinator_id=a.coordinator_id AND p.attempt_id=a.attempt_id`;\nasync function readConfirmableAttempt(\n\tcontext: Context,\n\tattemptId: string,\n\tbinderHash: string,\n): Promise<OwnerAttempt | null> {\n\tconst row = await context.backend.first<OwnerAttempt>({\n\t\tsql: `SELECT * FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = ?\n AND attempt_id = ? AND purpose = 'owner_enroll' AND state = 'oidc_verified' AND browser_binder_hash = ?\n AND ${OWNER_ADMISSION_SCHEMA_READY_SQL}`,\n\t\tvalues: [context.c.coordinatorId, attemptId, binderHash],\n\t});\n\tconst time = context.now();\n\tif (!live(context, row, time) || !row.browser_transaction_hash || !row.loopback_redirect)\n\t\treturn null;\n\tif (!parseCoordinatorAuthLoopback(row.loopback_redirect).ok) return null;\n\tconst authority = await readOwnerLinkAuthority(context.backend, time, {\n\t\tsql: \"l.coordinator_id=? AND l.link_id=?\",\n\t\tvalues: [row.coordinator_id, row.link_id],\n\t});\n\tconst current = await context.backend.first({\n\t\tsql: `${confirmAuthorityCte(authority)}SELECT 1 FROM coordinator_owner_enrollment_attempts a\n JOIN owner_confirm_authority p ON ${CONFIRM_AUTHORITY_MATCH_SQL} WHERE\n ${ownerAttemptSql(\"oidc_verified\")}`,\n\t\tvalues: [\n\t\t\t...authority.values,\n\t\t\t...confirmAuthorityValues(context, row, time),\n\t\t\t...callbackAttemptValues(context, row, time),\n\t\t],\n\t});\n\treturn current ? row : null;\n}\nasync function confirm(\n\tcontext: Context,\n\trequest: Request,\n\tclientKey: string,\n\tconfirmationCommitment: string,\n): Promise<OwnerEnrollmentStartResult> {\n\tconst snapshot = snapshotBrowserRequest(request);\n\tconst checked = await guardBrowserForm({\n\t\trequest,\n\t\tclientKey,\n\t\taction: \"transaction_attempt\",\n\t\tscope: context.scope,\n\t\tcsrfKey: context.csrfKey,\n\t\tlimiter: context.limiter,\n\t});\n\tif (!checked.ok || checked.action !== \"transaction_attempt\") return unavailable;\n\tconst cookie = await readBrowserCookie(snapshot.cookie, \"transaction\");\n\tif (cookie.kind !== \"present\" || cookie.cookieHash !== checked.cookieHash) return unavailable;\n\tconst row = await readConfirmableAttempt(context, checked.attemptId, cookie.cookieHash);\n\tif (!row?.loopback_redirect) return unavailable;\n\tconst confirmation = await confirmationView(row);\n\tif (confirmationCommitment !== confirmation.confirmationHash) return unavailable;\n\tconst completionSecret = mintCompletionSecret();\n\tconst completionHash = await proofHash(completionSecret);\n\tconst time = context.now();\n\tconst wrote = await context.backend.run(\n\t\tawait confirmStatement(context, row, {\n\t\t\tconfirmationHash: confirmation.confirmationHash,\n\t\t\tcompletionHash,\n\t\t\ttime,\n\t\t}),\n\t);\n\tif (wrote !== 1) return unavailable;\n\treturn {\n\t\tkind: \"confirmed\",\n\t\tcompletionSecret,\n\t\tloopbackRedirect: row.loopback_redirect,\n\t\tconfirmation,\n\t};\n}\nfunction mintCompletionSecret(): string {\n\tconst bytes = globalThis.crypto.getRandomValues(new Uint8Array(32));\n\treturn btoa(String.fromCharCode(...bytes))\n\t\t.replaceAll(\"+\", \"-\")\n\t\t.replaceAll(\"/\", \"_\")\n\t\t.replace(/=+$/, \"\");\n}\nasync function confirmStatement(\n\tcontext: Context,\n\ta: OwnerAttempt,\n\tp: { confirmationHash: string; completionHash: string; time: number },\n): Promise<AuthLinkStatement> {\n\tconst authority = await readOwnerLinkAuthority(context.backend, p.time, {\n\t\tsql: \"l.coordinator_id=? AND l.link_id=?\",\n\t\tvalues: [a.coordinator_id, a.link_id],\n\t});\n\treturn {\n\t\tsql: `${confirmAuthorityCte(authority)}UPDATE coordinator_owner_enrollment_attempts AS a SET state = 'confirmed',\n confirmation_hash = ?,completion_secret_hash = ? FROM owner_confirm_authority p WHERE\n ${ownerAttemptSql(\"oidc_verified\")}\n AND a.account_subject = ? AND a.identity_id = ? AND a.link_id = ? AND a.link_attempt_id = ?\n AND a.link_controller_attestation_id IS ? ${authority.hasPin ? \"AND a.owner_qualification_id IS ?\" : \"\"} AND a.link_auth_config_revision = ? AND a.grant_revisions_json = ?\n AND a.confirmation_hash IS NULL AND a.completion_secret_hash IS NULL\n AND ${CONFIRM_AUTHORITY_MATCH_SQL} AND ${NO_COLLISION_SQL}`,\n\t\tvalues: [\n\t\t\t...authority.values,\n\t\t\t...confirmAuthorityValues(context, a, p.time),\n\t\t\tp.confirmationHash,\n\t\t\tp.completionHash,\n\t\t\t...callbackAttemptValues(context, a, p.time),\n\t\t\ta.account_subject,\n\t\t\ta.identity_id,\n\t\t\ta.link_id,\n\t\t\ta.link_attempt_id,\n\t\t\ta.link_controller_attestation_id,\n\t\t\t...(authority.hasPin ? [a.owner_qualification_id ?? null] : []),\n\t\t\ta.link_auth_config_revision,\n\t\t\ta.grant_revisions_json,\n\t\t\ta.device_id,\n\t\t\ta.key_id,\n\t\t\ta.device_id,\n\t\t\ta.key_id,\n\t\t],\n\t};\n}\nfunction captureFinalize(value: unknown): OwnerEnrollmentFinalize {\n\treturn Object.freeze({\n\t\tattemptId: id(own(value, \"attemptId\")),\n\t\tcompletionSecret: text(own(value, \"completionSecret\"), 43),\n\t\tsignature: text(own(value, \"signature\"), 86),\n\t});\n}\nfunction matchesFinalScope(context: Context, row: OwnerAttempt | null): row is OwnerAttempt {\n\treturn (\n\t\t!!row &&\n\t\trow.purpose === \"owner_enroll\" &&\n\t\trow.coordinator_id === context.c.coordinatorId &&\n\t\trow.origin === context.pin.origin &&\n\t\trow.issuer === context.c.issuer &&\n\t\tvalidAdmissionOwnerHash(row.admission_owner_hash) &&\n\t\t// A committed receipt is historical evidence; only a new commit needs the live revision.\n\t\t(row.state === \"finalized\" || row.auth_config_revision === context.c.revision) &&\n\t\t!!row.confirmation_hash\n\t);\n}\nasync function finalize(\n\tcontext: Context,\n\tvalue: OwnerEnrollmentFinalize,\n): Promise<OwnerEnrollmentStartResult> {\n\tlet i: OwnerEnrollmentFinalize;\n\ttry {\n\t\ti = captureFinalize(value);\n\t} catch {\n\t\treturn unavailable;\n\t}\n\tconst row = await readAttempt(context, i.attemptId);\n\tif (!matchesFinalScope(context, row)) return unavailable;\n\tconst proof = await verifyPendingKeySignatureAndHashes(row, i.completionSecret, i.signature);\n\tif (!proof || proof.completionHash !== row.completion_secret_hash) return unavailable;\n\tif (row.state === \"finalized\") return priorCommit(context, row, proof);\n\tconst time = context.now();\n\tif (!live(context, row, time) || row.state !== \"confirmed\") return unavailable;\n\tif ((await confirmationView(row)).confirmationHash !== row.confirmation_hash) return unavailable;\n\tconst committed = await commitOwnerEnrollment({\n\t\tbackend: context.backend,\n\t\trow,\n\t\trevision: context.c.revision,\n\t\tnow: time,\n\t\tcompletionSecret: i.completionSecret,\n\t\tsignature: i.signature,\n\t});\n\treturn readFinalOutcome(context, i, { committed });\n}\nasync function readFinalOutcome(\n\tcontext: Context,\n\ti: OwnerEnrollmentFinalize,\n\toptions: { committed: boolean },\n): Promise<OwnerEnrollmentStartResult> {\n\tconst fresh = await readAttempt(context, i.attemptId);\n\t// A failed/missing post-commit read never proves rollback or successful completion.\n\tif (!fresh) throw new Error();\n\tif (!matchesFinalScope(context, fresh) || fresh.state !== \"finalized\") {\n\t\tif (options.committed) throw new Error();\n\t\treturn unavailable;\n\t}\n\tconst proof = await verifyPendingKeySignatureAndHashes(fresh, i.completionSecret, i.signature);\n\tif (!proof || !(await matchesReceipt(context, fresh, proof))) throw new Error();\n\tif (!options.committed) return receipt(fresh, \"prior_commit\");\n\treturn receipt(fresh, \"finalized\");\n}\ntype FinalProof = { completionHash: string; keyProofHash: string };\nasync function matchesReceipt(context: Context, row: OwnerAttempt, proof: FinalProof) {\n\treturn (\n\t\trow.completion_secret_hash === proof.completionHash &&\n\t\trow.final_key_proof_hash === proof.keyProofHash &&\n\t\t(await readOwnerEnrollmentReceipt(context.backend, row))\n\t);\n}\nasync function priorCommit(\n\tcontext: Context,\n\trow: OwnerAttempt,\n\tproof: FinalProof,\n): Promise<OwnerEnrollmentStartResult> {\n\tif (!(await matchesReceipt(context, row, proof))) return unavailable;\n\treturn receipt(row, \"prior_commit\");\n}\nfunction receipt(row: OwnerAttempt, kind: \"finalized\" | \"prior_commit\"): OwnerEnrollmentReceipt {\n\tconst grants = readGrantPins(row.grant_revisions_json);\n\tif (!grants || !row.binding_id || !isAuthControllerId(row.identity_id)) throw new Error();\n\treturn {\n\t\tkind,\n\t\tbindingId: row.binding_id,\n\t\tidentityId: row.identity_id,\n\t\tgroups: grants.map((grant) => grant.groupId),\n\t};\n}\nconst NO_COLLISION_SQL = `NOT EXISTS (SELECT 1 FROM coordinator_device_ownership_bindings WHERE device_id = ? OR key_id = ?)\n AND NOT EXISTS (SELECT 1 FROM coordinator_device_revocations WHERE (subject_kind = 'device_id' AND subject_value = ?)\n OR (subject_kind = 'ed25519_key' AND subject_value = ?))`;\nasync function start(\n\tcontext: Context,\n\tvalue: OwnerEnrollmentStart,\n\tclientKey: string,\n\tadmissionInput:\n\t\t| { kind: \"operator\"; token?: string }\n\t\t| { kind: \"owner\"; options: OwnerEnrollmentOwnerBoundStartOptions },\n): Promise<OwnerEnrollmentStartResult> {\n\t// Capture both the signed start and server-resolved owner before any async work.\n\tconst captured = captureStartInputs(value, admissionInput);\n\tif (!isAuthControllerId(clientKey) || clientKey.length > 128) return unavailable;\n\tconst admission = context.limiter.check(\n\t\tJSON.stringify([\"owner-enrollment-start\", context.c.coordinatorId, clientKey]),\n\t\tOWNER_START_CLIENT_LIMIT,\n\t);\n\tif (own(admission, \"allowed\") !== true) return unavailable;\n\tif (!captured) return unavailable;\n\tconst { i } = captured;\n\tlet browserStartHash: string;\n\ttry {\n\t\tbrowserStartHash = await proofHash(i.browserStartCode);\n\t} catch {\n\t\treturn unavailable;\n\t}\n\tconst verifiedAdmission = await verifyStartAdmission(context, captured);\n\tif (!verifiedAdmission) return unavailable;\n\tconst { admissionOwnerHash } = verifiedAdmission;\n\tif (!parseCoordinatorAuthLoopback(i.loopbackRedirect).ok) return unavailable;\n\tconst keyId = await ed25519KeyId(i.publicKey);\n\tif (\n\t\t!keyId ||\n\t\t!(await verifyOwnerEnrollmentSignature(\n\t\t\ti.publicKey,\n\t\t\townerEnrollmentStartMessage(i, context.pin),\n\t\t\ti.signature,\n\t\t))\n\t)\n\t\treturn unavailable;\n\tconst fingerprint = await ownerEnrollmentHash(i.publicKey);\n\tconst time = context.now();\n\tconst statement = startStatement(context, i, {\n\t\tkeyId,\n\t\tfingerprint,\n\t\tbrowserStartHash,\n\t\ttime,\n\t\tadmissionOwnerHash,\n\t});\n\tif (captured.owner && captured.sessionCookieHash !== undefined) {\n\t\tconst guard = await ownerAdmissionSessionGuard({\n\t\t\tbackend: context.backend,\n\t\t\tconfig: context.c,\n\t\t\tsessionCookieHash: captured.sessionCookieHash,\n\t\t\towner: captured.owner,\n\t\t\tdeviceId: i.deviceId,\n\t\t\tfingerprint,\n\t\t\ttime,\n\t\t});\n\t\t// Keep connection provenance out of the INSERT's expression tree (D1 depth 100).\n\t\t// Materialization is inside this same winning statement, not an earlier read.\n\t\tstatement.sql = `WITH owner_admission_authority AS MATERIALIZED (${guard.sql})\n ${statement.sql} AND EXISTS (SELECT 1 FROM owner_admission_authority)`;\n\t\tstatement.values.unshift(...guard.values);\n\t}\n\tconst wrote = await context.backend.run(statement);\n\tif (wrote !== 1) return unavailable;\n\treturn { kind: \"started\", attemptId: i.attemptId, expiresAtMs: time + 600000 };\n}\nfunction captureStartInputs(value: OwnerEnrollmentStart, admission: Parameters<typeof start>[3]) {\n\ttry {\n\t\tconst i = captureStart(value);\n\t\tif (admission.kind === \"operator\") return { i, token: admission.token, owner: null };\n\t\treturn {\n\t\t\ti,\n\t\t\ttoken: own(admission.options, \"admissionToken\"),\n\t\t\towner: captureResolvedOwner(own(admission.options, \"resolvedOwner\")),\n\t\t\tsessionCookieHash: captureSessionCookieHash(admission.options),\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction captureSessionCookieHash(\n\toptions: OwnerEnrollmentOwnerBoundStartOptions,\n): string | undefined {\n\tconst descriptor = Object.getOwnPropertyDescriptor(options, \"sessionCookieHash\");\n\tif (!descriptor) return undefined;\n\tif (\n\t\t!Object.hasOwn(descriptor, \"value\") ||\n\t\ttypeof descriptor.value !== \"string\" ||\n\t\t!/^[a-f0-9]{64}$/.test(descriptor.value)\n\t)\n\t\tthrow new Error();\n\treturn descriptor.value;\n}\nasync function verifyStartAdmission(\n\tcontext: Context,\n\tcaptured: NonNullable<ReturnType<typeof captureStartInputs>>,\n) {\n\tconst { i, token, owner } = captured;\n\tif (owner) {\n\t\tif (\n\t\t\t!context.admissionKey ||\n\t\t\t!(await verifyOwnerEnrollmentAdmissionV2(context.admissionKey, token, context.pin, i, {\n\t\t\t\tresolvedOwner: owner,\n\t\t\t\tnowMs: context.now(),\n\t\t\t}))\n\t\t)\n\t\t\treturn null;\n\t\treturn { admissionOwnerHash: await ownerEnrollmentOwnerCommitment(owner) };\n\t}\n\tif (\n\t\tcontext.admissionKey &&\n\t\t!(await verifyOwnerEnrollmentAdmission(\n\t\t\tcontext.admissionKey,\n\t\t\ttoken,\n\t\t\tcontext.pin,\n\t\t\ti,\n\t\t\tcontext.now(),\n\t\t))\n\t)\n\t\treturn null;\n\treturn { admissionOwnerHash: null };\n}\nfunction startStatement(\n\tcontext: Context,\n\ti: OwnerEnrollmentStart,\n\tp: {\n\t\tkeyId: string;\n\t\tfingerprint: string;\n\t\tbrowserStartHash: string;\n\t\ttime: number;\n\t\tadmissionOwnerHash: string | null;\n\t},\n): AuthLinkStatement {\n\tconst { c, pin } = context;\n\t// Signed starts have no issued-at: retain every attempt ID as a replay tombstone.\n\t// Expiry frees active slots only; no purge is supported, and storage fails closed.\n\treturn {\n\t\tsql: `INSERT INTO coordinator_owner_enrollment_attempts\n (coordinator_id,attempt_id,purpose,origin,device_id,public_key,key_id,fingerprint,issuer,auth_config_revision,\n loopback_redirect,browser_start_hash,state,created_at_ms,expires_at_ms,admission_owner_hash)\n SELECT ?,?,'owner_enroll',?,?,?,?,?,?,?,?,?,'pending',?,?,?\n WHERE ${OWNER_ADMISSION_SCHEMA_READY_SQL} AND ${NO_COLLISION_SQL}\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_link_attempts WHERE coordinator_id = ? AND attempt_id = ?)\n AND NOT EXISTS (SELECT 1 FROM coordinator_auth_browser_transactions WHERE coordinator_id = ?\n AND attempt_id = ? AND purpose <> 'signin')\n AND (SELECT count(*) FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = ? AND device_id = ?\n AND state IN ('pending','browser_claimed','oidc_verified','confirmed') AND expires_at_ms > ?) < ?\n AND (SELECT count(*) FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = ? AND device_id = ? AND created_at_ms > ?) < ?\n AND (SELECT count(*) FROM (SELECT 1 FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = ?\n AND state IN ('pending','browser_claimed','oidc_verified','confirmed') AND expires_at_ms > ? LIMIT ?)) < ?\n AND (SELECT count(*) FROM (SELECT 1 FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = ?\n AND state <> 'finalized' LIMIT ?)) < ?`,\n\t\tvalues: [\n\t\t\tc.coordinatorId,\n\t\t\ti.attemptId,\n\t\t\tpin.origin,\n\t\t\ti.deviceId,\n\t\t\ti.publicKey,\n\t\t\tp.keyId,\n\t\t\tp.fingerprint,\n\t\t\tc.issuer,\n\t\t\tc.revision,\n\t\t\ti.loopbackRedirect,\n\t\t\tp.browserStartHash,\n\t\t\tp.time,\n\t\t\tp.time + 600000,\n\t\t\tp.admissionOwnerHash,\n\t\t\ti.deviceId,\n\t\t\tp.keyId,\n\t\t\ti.deviceId,\n\t\t\tp.keyId,\n\t\t\tc.coordinatorId,\n\t\t\ti.attemptId,\n\t\t\tc.coordinatorId,\n\t\t\ti.attemptId,\n\t\t\tc.coordinatorId,\n\t\t\ti.deviceId,\n\t\t\tp.time,\n\t\t\tAUTH_LINK_MAX_ACTIVE_PER_DEVICE,\n\t\t\tc.coordinatorId,\n\t\t\ti.deviceId,\n\t\t\tp.time - AUTH_LINK_CREATE_WINDOW_MS,\n\t\t\tAUTH_LINK_MAX_CREATES_PER_DEVICE_WINDOW,\n\t\t\tc.coordinatorId,\n\t\t\tp.time,\n\t\t\tOWNER_MAX_ACTIVE_PER_COORDINATOR,\n\t\t\tOWNER_MAX_ACTIVE_PER_COORDINATOR,\n\t\t\tc.coordinatorId,\n\t\t\tAUTH_LINK_MAX_UNFINISHED_PER_COORDINATOR,\n\t\t\tAUTH_LINK_MAX_UNFINISHED_PER_COORDINATOR,\n\t\t],\n\t};\n}\nasync function readAttempt(context: Context, attemptId: string): Promise<OwnerAttempt | null> {\n\treturn context.backend.first<OwnerAttempt>({\n\t\tsql: `SELECT * FROM coordinator_owner_enrollment_attempts WHERE coordinator_id = ? AND attempt_id = ?\n AND ${OWNER_ADMISSION_SCHEMA_READY_SQL}`,\n\t\tvalues: [context.c.coordinatorId, attemptId],\n\t});\n}\nfunction live(context: Context, row: OwnerAttempt | null, time: number): row is OwnerAttempt {\n\treturn (\n\t\t!!row &&\n\t\trow.coordinator_id === context.c.coordinatorId &&\n\t\trow.purpose === \"owner_enroll\" &&\n\t\trow.origin === context.pin.origin &&\n\t\trow.issuer === context.c.issuer &&\n\t\trow.auth_config_revision === context.c.revision &&\n\t\tvalidAdmissionOwnerHash(row.admission_owner_hash) &&\n\t\tvalidAttemptTime(row) &&\n\t\trow.created_at_ms <= time &&\n\t\trow.expires_at_ms > time\n\t);\n}\nasync function claimBrowser(\n\tcontext: Context,\n\trequest: Request,\n\tclientKey: string,\n): Promise<OwnerEnrollmentStartResult> {\n\tconst snapshot = snapshotBrowserRequest(request);\n\tconst transaction = await readBrowserStartTransaction(\n\t\tsnapshot.cookie,\n\t\tnew CoordinatorAuthBrowserTransactions(context.backend, context.now),\n\t\tcontext.c,\n\t);\n\tif (transaction === \"active\" || transaction === \"invalid\") return unavailable;\n\tconst checked = await guardBrowserForm({\n\t\trequest,\n\t\tclientKey,\n\t\taction: \"link_start\",\n\t\tscope: context.scope,\n\t\tcsrfKey: context.csrfKey,\n\t\tlimiter: context.limiter,\n\t});\n\tif (!checked.ok || checked.action !== \"link_start\") return unavailable;\n\tconst cookie = await readBrowserCookie(snapshot.cookie, \"start\");\n\tif (cookie.kind !== \"present\" || cookie.cookieHash !== checked.cookieHash) return unavailable;\n\tconst row = await readAttempt(context, checked.attemptId);\n\tconst startHash = await proofHash(checked.startCode);\n\tif (\n\t\t!live(context, row, context.now()) ||\n\t\trow.state !== \"pending\" ||\n\t\trow.browser_start_hash !== startHash\n\t)\n\t\treturn unavailable;\n\tconst authorization = await context.client.createAuthorizationRequest();\n\tconst authorizationUrl = new URL(authorization.authorizationUrl);\n\tauthorizationUrl.searchParams.set(\"prompt\", \"select_account\");\n\tconst time = context.now();\n\tif (!live(context, row, time)) return unavailable;\n\tconst hash = await hashCoordinatorAuthProofBytes32(\n\t\tglobalThis.crypto.getRandomValues(new Uint8Array(32)),\n\t);\n\tconst stateHash = await ownerEnrollmentHash(authorization.material.state);\n\tconst setCookies = [reissueStartCookieAsTransaction(cookie.secret), clearBrowserCookie(\"start\")];\n\tawait context.backend.batch(\n\t\tclaimStatements(context, row, authorization, {\n\t\t\ttime,\n\t\t\thash,\n\t\t\tstateHash,\n\t\t\tbinder: checked.cookieHash,\n\t\t}),\n\t);\n\tconst claimed = await readAttempt(context, row.attempt_id);\n\tif (\n\t\tclaimed?.state !== \"browser_claimed\" ||\n\t\tclaimed.browser_transaction_hash !== hash ||\n\t\tclaimed.browser_binder_hash !== checked.cookieHash\n\t) {\n\t\tthrow new Error();\n\t}\n\treturn { kind: \"browser_claimed\", authorizationUrl: authorizationUrl.href, setCookies };\n}\n// A standalone INSERT must fail even if the raced attempt was deleted. UPDATE-based\n// assertions could affect zero rows and silently leave an orphan transaction.\nfunction assertOneWrite(): AuthLinkStatement {\n\treturn {\n\t\tsql: \"INSERT INTO coordinator_auth_browser_transactions (purpose) SELECT 'owner_enroll' WHERE changes() <> 1\",\n\t\tvalues: [],\n\t};\n}\ntype ClaimPin = { time: number; hash: string; stateHash: string; binder: string };\nfunction claimStatements(\n\tcontext: Context,\n\trow: OwnerAttempt,\n\tauthorization: Awaited<ReturnType<CoordinatorOidcClient[\"createAuthorizationRequest\"]>>,\n\tp: ClaimPin,\n): AuthLinkStatement[] {\n\treturn [\n\t\tinsertBrowser(context, row, authorization, p),\n\t\tassertOneWrite(),\n\t\tupdateAttempt(context, row, authorization, p),\n\t\tassertOneWrite(),\n\t];\n}\nconst PENDING_SQL = `coordinator_id = ? AND attempt_id = ? AND purpose = 'owner_enroll' AND state = 'pending'\n AND origin = ? AND issuer = ? AND auth_config_revision = ? AND browser_start_hash = ?\n AND created_at_ms = ? AND expires_at_ms = ? AND created_at_ms <= ? AND expires_at_ms > ?\n AND admission_owner_hash IS ?\n AND ${OWNER_ADMISSION_SCHEMA_READY_SQL}\n AND browser_transaction_hash IS NULL AND browser_binder_hash IS NULL`;\nfunction pendingValues(\n\tcontext: Context,\n\trow: OwnerAttempt,\n\tp: ClaimPin,\n): (string | number | null)[] {\n\treturn [\n\t\tcontext.c.coordinatorId,\n\t\trow.attempt_id,\n\t\tcontext.pin.origin,\n\t\tcontext.c.issuer,\n\t\tcontext.c.revision,\n\t\trow.browser_start_hash,\n\t\trow.created_at_ms,\n\t\trow.expires_at_ms,\n\t\tp.time,\n\t\tp.time,\n\t\trow.admission_owner_hash,\n\t];\n}\nfunction insertBrowser(\n\tcontext: Context,\n\trow: OwnerAttempt,\n\tauthorization: Awaited<ReturnType<CoordinatorOidcClient[\"createAuthorizationRequest\"]>>,\n\tp: ClaimPin,\n): AuthLinkStatement {\n\treturn {\n\t\tsql: `INSERT INTO coordinator_auth_browser_transactions\n (coordinator_id,browser_transaction_hash,purpose,attempt_id,state_hash,binder_hash,issuer,auth_config_revision,redirect_uri,\n state,nonce,pkce_verifier,created_at_ms,expires_at_ms)\n SELECT coordinator_id,?,'owner_enroll',attempt_id,?,?,issuer,auth_config_revision,?,'pending',?,?,?,expires_at_ms\n FROM coordinator_owner_enrollment_attempts WHERE ${PENDING_SQL} AND ${NO_COLLISION_SQL}`,\n\t\tvalues: [\n\t\t\tp.hash,\n\t\t\tp.stateHash,\n\t\t\tp.binder,\n\t\t\tcontext.c.redirectUri,\n\t\t\tauthorization.material.nonce,\n\t\t\tauthorization.material.pkceVerifier,\n\t\t\tp.time,\n\t\t\t...pendingValues(context, row, p),\n\t\t\trow.device_id,\n\t\t\trow.key_id,\n\t\t\trow.device_id,\n\t\t\trow.key_id,\n\t\t],\n\t};\n}\nfunction updateAttempt(\n\tcontext: Context,\n\trow: OwnerAttempt,\n\tauthorization: Awaited<ReturnType<CoordinatorOidcClient[\"createAuthorizationRequest\"]>>,\n\tp: ClaimPin,\n): AuthLinkStatement {\n\treturn {\n\t\tsql: `UPDATE coordinator_owner_enrollment_attempts AS a SET state = 'browser_claimed',browser_transaction_hash = ?,browser_binder_hash = ?\n WHERE ${PENDING_SQL} AND ${NO_COLLISION_SQL}\n AND EXISTS (SELECT 1 FROM coordinator_auth_browser_transactions b WHERE b.coordinator_id = a.coordinator_id\n AND b.attempt_id = a.attempt_id AND b.browser_transaction_hash = ? AND b.purpose = 'owner_enroll'\n AND b.binder_hash = ? AND b.state_hash = ? AND b.issuer = a.issuer AND b.auth_config_revision = a.auth_config_revision\n AND b.redirect_uri = ? AND b.state = 'pending' AND b.nonce = ? AND b.pkce_verifier = ?\n AND b.created_at_ms = ? AND b.expires_at_ms = a.expires_at_ms)`,\n\t\tvalues: [\n\t\t\tp.hash,\n\t\t\tp.binder,\n\t\t\t...pendingValues(context, row, p),\n\t\t\trow.device_id,\n\t\t\trow.key_id,\n\t\t\trow.device_id,\n\t\t\trow.key_id,\n\t\t\tp.hash,\n\t\t\tp.binder,\n\t\t\tp.stateHash,\n\t\t\tcontext.c.redirectUri,\n\t\t\tauthorization.material.nonce,\n\t\t\tauthorization.material.pkceVerifier,\n\t\t\tp.time,\n\t\t],\n\t};\n}\n"],"x_google_ignoreList":[59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,89,90,91,101,102],"mappings":";;;;AAGA,SAAgB,EAAqB,GAA2B;CAC/D,OAAO,EAAW,QA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