@codemem/core 0.46.2 → 0.47.0-beta.2

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 (465) hide show
  1. package/dist/address-utils.d.ts.map +1 -1
  2. package/dist/better-sqlite-coordinator-runtime.d.ts +2 -0
  3. package/dist/better-sqlite-coordinator-runtime.d.ts.map +1 -1
  4. package/dist/better-sqlite-coordinator-store.d.ts +109 -5
  5. package/dist/better-sqlite-coordinator-store.d.ts.map +1 -1
  6. package/dist/coordinator-account-change-browser.d.ts +39 -0
  7. package/dist/coordinator-account-change-browser.d.ts.map +1 -0
  8. package/dist/coordinator-account-change-contract.d.ts +4 -0
  9. package/dist/coordinator-account-change-contract.d.ts.map +1 -0
  10. package/dist/coordinator-account-change-http-test-fixtures.d.ts +101 -0
  11. package/dist/coordinator-account-change-http-test-fixtures.d.ts.map +1 -0
  12. package/dist/coordinator-account-change-schema.d.ts +5 -0
  13. package/dist/coordinator-account-change-schema.d.ts.map +1 -0
  14. package/dist/coordinator-account-change.d.ts +100 -0
  15. package/dist/coordinator-account-change.d.ts.map +1 -0
  16. package/dist/coordinator-account-connection-link.d.ts +25 -0
  17. package/dist/coordinator-account-connection-link.d.ts.map +1 -0
  18. package/dist/coordinator-account-connection-schema.d.ts +68 -0
  19. package/dist/coordinator-account-connection-schema.d.ts.map +1 -0
  20. package/dist/coordinator-account-connection-session.d.ts +15 -0
  21. package/dist/coordinator-account-connection-session.d.ts.map +1 -0
  22. package/dist/coordinator-account-connection-storage.d.ts +46 -0
  23. package/dist/coordinator-account-connection-storage.d.ts.map +1 -0
  24. package/dist/coordinator-account-historical-revoke.d.ts +7 -0
  25. package/dist/coordinator-account-historical-revoke.d.ts.map +1 -0
  26. package/dist/coordinator-account-link-receipt.d.ts +20 -0
  27. package/dist/coordinator-account-link-receipt.d.ts.map +1 -0
  28. package/dist/coordinator-account-link-receiver.d.ts +28 -0
  29. package/dist/coordinator-account-link-receiver.d.ts.map +1 -0
  30. package/dist/coordinator-account-link-runtime.d.ts +45 -0
  31. package/dist/coordinator-account-link-runtime.d.ts.map +1 -0
  32. package/dist/coordinator-account-link-signer.d.ts +15 -0
  33. package/dist/coordinator-account-link-signer.d.ts.map +1 -0
  34. package/dist/coordinator-account-link-status-client.d.ts +37 -0
  35. package/dist/coordinator-account-link-status-client.d.ts.map +1 -0
  36. package/dist/coordinator-account-link-status.d.ts +23 -0
  37. package/dist/coordinator-account-link-status.d.ts.map +1 -0
  38. package/dist/coordinator-account-unlink-schema.d.ts +7 -0
  39. package/dist/coordinator-account-unlink-schema.d.ts.map +1 -0
  40. package/dist/coordinator-actions.d.ts +29 -0
  41. package/dist/coordinator-actions.d.ts.map +1 -1
  42. package/dist/coordinator-api.d.ts +21 -1
  43. package/dist/coordinator-api.d.ts.map +1 -1
  44. package/dist/coordinator-auth-account-profile-contract.d.ts +41 -0
  45. package/dist/coordinator-auth-account-profile-contract.d.ts.map +1 -0
  46. package/dist/coordinator-auth-account-profile.d.ts +27 -0
  47. package/dist/coordinator-auth-account-profile.d.ts.map +1 -0
  48. package/dist/coordinator-auth-browser-migration-test-harness.d.ts +18 -0
  49. package/dist/coordinator-auth-browser-migration-test-harness.d.ts.map +1 -0
  50. package/dist/coordinator-auth-browser-owner-purpose-test-harness.d.ts +6 -0
  51. package/dist/coordinator-auth-browser-owner-purpose-test-harness.d.ts.map +1 -0
  52. package/dist/coordinator-auth-browser-proof-test-fixtures.d.ts +25 -0
  53. package/dist/coordinator-auth-browser-proof-test-fixtures.d.ts.map +1 -0
  54. package/dist/coordinator-auth-browser-schema-upgrade.d.ts +6 -0
  55. package/dist/coordinator-auth-browser-schema-upgrade.d.ts.map +1 -0
  56. package/dist/coordinator-auth-browser-style.d.ts +6 -0
  57. package/dist/coordinator-auth-browser-style.d.ts.map +1 -0
  58. package/dist/coordinator-auth-browser-transaction-contract.d.ts +130 -0
  59. package/dist/coordinator-auth-browser-transaction-contract.d.ts.map +1 -0
  60. package/dist/coordinator-auth-browser-transaction-test-fixtures.d.ts +14 -0
  61. package/dist/coordinator-auth-browser-transaction-test-fixtures.d.ts.map +1 -0
  62. package/dist/coordinator-auth-browser-transaction.d.ts +36 -0
  63. package/dist/coordinator-auth-browser-transaction.d.ts.map +1 -0
  64. package/dist/coordinator-auth-browser-view.d.ts +84 -0
  65. package/dist/coordinator-auth-browser-view.d.ts.map +1 -0
  66. package/dist/coordinator-auth-contract.d.ts +71 -0
  67. package/dist/coordinator-auth-contract.d.ts.map +1 -0
  68. package/dist/coordinator-auth-controller-review-route.d.ts +38 -0
  69. package/dist/coordinator-auth-controller-review-route.d.ts.map +1 -0
  70. package/dist/coordinator-auth-controller.d.ts +87 -0
  71. package/dist/coordinator-auth-controller.d.ts.map +1 -0
  72. package/dist/coordinator-auth-device-claim-eligibility.d.ts +43 -0
  73. package/dist/coordinator-auth-device-claim-eligibility.d.ts.map +1 -0
  74. package/dist/coordinator-auth-device-claim-schema.d.ts +116 -0
  75. package/dist/coordinator-auth-device-claim-schema.d.ts.map +1 -0
  76. package/dist/coordinator-auth-historical-migration-test-fixture.d.ts +2 -0
  77. package/dist/coordinator-auth-historical-migration-test-fixture.d.ts.map +1 -0
  78. package/dist/coordinator-auth-historical-store-test-fixture.d.ts +13 -0
  79. package/dist/coordinator-auth-historical-store-test-fixture.d.ts.map +1 -0
  80. package/dist/coordinator-auth-historical-test-fixture.d.ts +48 -0
  81. package/dist/coordinator-auth-historical-test-fixture.d.ts.map +1 -0
  82. package/dist/coordinator-auth-legacy-assignment.d.ts +12 -0
  83. package/dist/coordinator-auth-legacy-assignment.d.ts.map +1 -0
  84. package/dist/coordinator-auth-lifecycle-admission-schema.d.ts +28 -0
  85. package/dist/coordinator-auth-lifecycle-admission-schema.d.ts.map +1 -0
  86. package/dist/coordinator-auth-lifecycle-browser-schema.d.ts +15 -0
  87. package/dist/coordinator-auth-lifecycle-browser-schema.d.ts.map +1 -0
  88. package/dist/coordinator-auth-lifecycle-current-readiness.d.ts +7 -0
  89. package/dist/coordinator-auth-lifecycle-current-readiness.d.ts.map +1 -0
  90. package/dist/coordinator-auth-lifecycle-first-link.d.ts +17 -0
  91. package/dist/coordinator-auth-lifecycle-first-link.d.ts.map +1 -0
  92. package/dist/coordinator-auth-lifecycle-fresh-schema.d.ts +14 -0
  93. package/dist/coordinator-auth-lifecycle-fresh-schema.d.ts.map +1 -0
  94. package/dist/coordinator-auth-lifecycle-predecessor-shapes.d.ts +24 -0
  95. package/dist/coordinator-auth-lifecycle-predecessor-shapes.d.ts.map +1 -0
  96. package/dist/coordinator-auth-lifecycle-predecessor.d.ts +9 -0
  97. package/dist/coordinator-auth-lifecycle-predecessor.d.ts.map +1 -0
  98. package/dist/coordinator-auth-lifecycle-profile-schema.d.ts +13 -0
  99. package/dist/coordinator-auth-lifecycle-profile-schema.d.ts.map +1 -0
  100. package/dist/coordinator-auth-lifecycle-recognition.d.ts +22 -0
  101. package/dist/coordinator-auth-lifecycle-recognition.d.ts.map +1 -0
  102. package/dist/coordinator-auth-lifecycle-schema.d.ts +20 -0
  103. package/dist/coordinator-auth-lifecycle-schema.d.ts.map +1 -0
  104. package/dist/coordinator-auth-lifecycle-upgrade-copy.d.ts +36 -0
  105. package/dist/coordinator-auth-lifecycle-upgrade-copy.d.ts.map +1 -0
  106. package/dist/coordinator-auth-lifecycle-upgrade-sqlite.d.ts +11 -0
  107. package/dist/coordinator-auth-lifecycle-upgrade-sqlite.d.ts.map +1 -0
  108. package/dist/coordinator-auth-lifecycle-upgrade-test-fixture.d.ts +31 -0
  109. package/dist/coordinator-auth-lifecycle-upgrade-test-fixture.d.ts.map +1 -0
  110. package/dist/coordinator-auth-lifecycle-upgrade.d.ts +6 -0
  111. package/dist/coordinator-auth-lifecycle-upgrade.d.ts.map +1 -0
  112. package/dist/coordinator-auth-link-authority-upgrade.d.ts +17 -0
  113. package/dist/coordinator-auth-link-authority-upgrade.d.ts.map +1 -0
  114. package/dist/coordinator-auth-link-authority.d.ts +92 -0
  115. package/dist/coordinator-auth-link-authority.d.ts.map +1 -0
  116. package/dist/coordinator-auth-link-change-schema.d.ts +21 -0
  117. package/dist/coordinator-auth-link-change-schema.d.ts.map +1 -0
  118. package/dist/coordinator-auth-link-contract.d.ts +137 -0
  119. package/dist/coordinator-auth-link-contract.d.ts.map +1 -0
  120. package/dist/coordinator-auth-link-input.d.ts +7 -0
  121. package/dist/coordinator-auth-link-input.d.ts.map +1 -0
  122. package/dist/coordinator-auth-link-legacy-inline-test-fixture.d.ts +2 -0
  123. package/dist/coordinator-auth-link-legacy-inline-test-fixture.d.ts.map +1 -0
  124. package/dist/coordinator-auth-link-liveness.d.ts +8 -0
  125. package/dist/coordinator-auth-link-liveness.d.ts.map +1 -0
  126. package/dist/coordinator-auth-link-maintenance-fixtures.d.ts +14 -0
  127. package/dist/coordinator-auth-link-maintenance-fixtures.d.ts.map +1 -0
  128. package/dist/coordinator-auth-link-profile.d.ts +15 -0
  129. package/dist/coordinator-auth-link-profile.d.ts.map +1 -0
  130. package/dist/coordinator-auth-link-provenance.d.ts +17 -0
  131. package/dist/coordinator-auth-link-provenance.d.ts.map +1 -0
  132. package/dist/coordinator-auth-link-revocation-test-harness.d.ts +19 -0
  133. package/dist/coordinator-auth-link-revocation-test-harness.d.ts.map +1 -0
  134. package/dist/coordinator-auth-link-source.d.ts +15 -0
  135. package/dist/coordinator-auth-link-source.d.ts.map +1 -0
  136. package/dist/coordinator-auth-link-test-fixtures.d.ts +49 -0
  137. package/dist/coordinator-auth-link-test-fixtures.d.ts.map +1 -0
  138. package/dist/coordinator-auth-link.d.ts +91 -0
  139. package/dist/coordinator-auth-link.d.ts.map +1 -0
  140. package/dist/coordinator-auth-loopback.d.ts +11 -0
  141. package/dist/coordinator-auth-loopback.d.ts.map +1 -0
  142. package/dist/coordinator-auth-proof.d.ts +4 -0
  143. package/dist/coordinator-auth-proof.d.ts.map +1 -0
  144. package/dist/coordinator-auth-schema-operator.d.ts +6 -0
  145. package/dist/coordinator-auth-schema-operator.d.ts.map +1 -0
  146. package/dist/coordinator-auth-schema.d.ts +18 -0
  147. package/dist/coordinator-auth-schema.d.ts.map +1 -0
  148. package/dist/coordinator-auth-session-bound-test-fixtures.d.ts +7 -0
  149. package/dist/coordinator-auth-session-bound-test-fixtures.d.ts.map +1 -0
  150. package/dist/coordinator-auth-session-contract.d.ts +104 -0
  151. package/dist/coordinator-auth-session-contract.d.ts.map +1 -0
  152. package/dist/coordinator-auth-session-test-fixtures.d.ts +31 -0
  153. package/dist/coordinator-auth-session-test-fixtures.d.ts.map +1 -0
  154. package/dist/coordinator-auth-session.d.ts +44 -0
  155. package/dist/coordinator-auth-session.d.ts.map +1 -0
  156. package/dist/coordinator-auth-store-test-fixtures.d.ts +26 -0
  157. package/dist/coordinator-auth-store-test-fixtures.d.ts.map +1 -0
  158. package/dist/coordinator-bootstrap-authorization-api-test-harness.d.ts +5 -0
  159. package/dist/coordinator-bootstrap-authorization-api-test-harness.d.ts.map +1 -0
  160. package/dist/coordinator-bootstrap-authorization-test-harness.d.ts +11 -0
  161. package/dist/coordinator-bootstrap-authorization-test-harness.d.ts.map +1 -0
  162. package/dist/coordinator-bootstrap-grant-authorization.d.ts +28 -0
  163. package/dist/coordinator-bootstrap-grant-authorization.d.ts.map +1 -0
  164. package/dist/coordinator-bootstrap-grant-issuance.d.ts +22 -0
  165. package/dist/coordinator-bootstrap-grant-issuance.d.ts.map +1 -0
  166. package/dist/coordinator-bootstrap-revocation-test-harness.d.ts +11 -0
  167. package/dist/coordinator-bootstrap-revocation-test-harness.d.ts.map +1 -0
  168. package/dist/coordinator-browser-account.d.ts +36 -0
  169. package/dist/coordinator-browser-account.d.ts.map +1 -0
  170. package/dist/coordinator-browser-auth-app.d.ts +84 -0
  171. package/dist/coordinator-browser-auth-app.d.ts.map +1 -0
  172. package/dist/coordinator-browser-auth-callback.d.ts +47 -0
  173. package/dist/coordinator-browser-auth-callback.d.ts.map +1 -0
  174. package/dist/coordinator-browser-auth-config.d.ts +32 -0
  175. package/dist/coordinator-browser-auth-config.d.ts.map +1 -0
  176. package/dist/coordinator-browser-credential.d.ts +40 -0
  177. package/dist/coordinator-browser-credential.d.ts.map +1 -0
  178. package/dist/coordinator-browser-csrf.d.ts +19 -0
  179. package/dist/coordinator-browser-csrf.d.ts.map +1 -0
  180. package/dist/coordinator-browser-form-body.d.ts +42 -0
  181. package/dist/coordinator-browser-form-body.d.ts.map +1 -0
  182. package/dist/coordinator-browser-form-guard.d.ts +55 -0
  183. package/dist/coordinator-browser-form-guard.d.ts.map +1 -0
  184. package/dist/coordinator-browser-link-completion.d.ts +32 -0
  185. package/dist/coordinator-browser-link-completion.d.ts.map +1 -0
  186. package/dist/coordinator-browser-link-start.d.ts +39 -0
  187. package/dist/coordinator-browser-link-start.d.ts.map +1 -0
  188. package/dist/coordinator-browser-link.d.ts +36 -0
  189. package/dist/coordinator-browser-link.d.ts.map +1 -0
  190. package/dist/coordinator-browser-request.d.ts +10 -0
  191. package/dist/coordinator-browser-request.d.ts.map +1 -0
  192. package/dist/coordinator-browser-signin-start.d.ts +38 -0
  193. package/dist/coordinator-browser-signin-start.d.ts.map +1 -0
  194. package/dist/coordinator-browser-start-transaction.d.ts +6 -0
  195. package/dist/coordinator-browser-start-transaction.d.ts.map +1 -0
  196. package/dist/coordinator-controller-revocation-test-harness.d.ts +11 -0
  197. package/dist/coordinator-controller-revocation-test-harness.d.ts.map +1 -0
  198. package/dist/coordinator-d1-scope-authorization-test-harness.d.ts +14 -0
  199. package/dist/coordinator-d1-scope-authorization-test-harness.d.ts.map +1 -0
  200. package/dist/coordinator-device-account-change.d.ts +17 -0
  201. package/dist/coordinator-device-account-change.d.ts.map +1 -0
  202. package/dist/coordinator-device-auth-link.d.ts +43 -0
  203. package/dist/coordinator-device-auth-link.d.ts.map +1 -0
  204. package/dist/coordinator-device-local.d.ts +9 -0
  205. package/dist/coordinator-device-local.d.ts.map +1 -0
  206. package/dist/coordinator-device-ownership-schema.d.ts +3 -0
  207. package/dist/coordinator-device-ownership-schema.d.ts.map +1 -0
  208. package/dist/coordinator-device-ownership-test-harness.d.ts +17 -0
  209. package/dist/coordinator-device-ownership-test-harness.d.ts.map +1 -0
  210. package/dist/coordinator-device-revocation-client.d.ts +41 -0
  211. package/dist/coordinator-device-revocation-client.d.ts.map +1 -0
  212. package/dist/coordinator-device-revocation-handler-test-harness.d.ts +4 -0
  213. package/dist/coordinator-device-revocation-handler-test-harness.d.ts.map +1 -0
  214. package/dist/coordinator-device-revocation-handler.d.ts +17 -0
  215. package/dist/coordinator-device-revocation-handler.d.ts.map +1 -0
  216. package/dist/coordinator-device-revocation-route.d.ts +14 -0
  217. package/dist/coordinator-device-revocation-route.d.ts.map +1 -0
  218. package/dist/coordinator-device-revocation-test-harness.d.ts +34 -0
  219. package/dist/coordinator-device-revocation-test-harness.d.ts.map +1 -0
  220. package/dist/coordinator-device-revocation.d.ts +67 -0
  221. package/dist/coordinator-device-revocation.d.ts.map +1 -0
  222. package/dist/coordinator-ed25519-key-id-compat.d.ts +6 -0
  223. package/dist/coordinator-ed25519-key-id-compat.d.ts.map +1 -0
  224. package/dist/coordinator-ed25519-key-id-test-fixtures.d.ts +30 -0
  225. package/dist/coordinator-ed25519-key-id-test-fixtures.d.ts.map +1 -0
  226. package/dist/coordinator-ed25519-key-id.d.ts +21 -0
  227. package/dist/coordinator-ed25519-key-id.d.ts.map +1 -0
  228. package/dist/coordinator-enrollment-revocation-test-harness.d.ts +6 -0
  229. package/dist/coordinator-enrollment-revocation-test-harness.d.ts.map +1 -0
  230. package/dist/coordinator-hono-test-fixtures.d.ts +2 -0
  231. package/dist/coordinator-hono-test-fixtures.d.ts.map +1 -0
  232. package/dist/coordinator-identity-grant-revocation-test-harness.d.ts +11 -0
  233. package/dist/coordinator-identity-grant-revocation-test-harness.d.ts.map +1 -0
  234. package/dist/coordinator-identity-group-grant-client.d.ts +9 -0
  235. package/dist/coordinator-identity-group-grant-client.d.ts.map +1 -0
  236. package/dist/coordinator-identity-group-grant-input-test-harness.d.ts +3 -0
  237. package/dist/coordinator-identity-group-grant-input-test-harness.d.ts.map +1 -0
  238. package/dist/coordinator-identity-group-grant-test-harness.d.ts +17 -0
  239. package/dist/coordinator-identity-group-grant-test-harness.d.ts.map +1 -0
  240. package/dist/coordinator-identity-group-grant.d.ts +51 -0
  241. package/dist/coordinator-identity-group-grant.d.ts.map +1 -0
  242. package/dist/coordinator-invite-review.d.ts +64 -0
  243. package/dist/coordinator-invite-review.d.ts.map +1 -0
  244. package/dist/coordinator-join-review-guards.d.ts +22 -0
  245. package/dist/coordinator-join-review-guards.d.ts.map +1 -0
  246. package/dist/coordinator-join-revocation-test-harness.d.ts +23 -0
  247. package/dist/coordinator-join-revocation-test-harness.d.ts.map +1 -0
  248. package/dist/coordinator-legacy-device-ownership.d.ts +34 -0
  249. package/dist/coordinator-legacy-device-ownership.d.ts.map +1 -0
  250. package/dist/coordinator-oidc-test-fixtures.d.ts +50 -0
  251. package/dist/coordinator-oidc-test-fixtures.d.ts.map +1 -0
  252. package/dist/coordinator-oidc.d.ts +59 -0
  253. package/dist/coordinator-oidc.d.ts.map +1 -0
  254. package/dist/coordinator-owner-attempt-migration-test-harness.d.ts +16 -0
  255. package/dist/coordinator-owner-attempt-migration-test-harness.d.ts.map +1 -0
  256. package/dist/coordinator-owner-enrollment-client.d.ts +29 -0
  257. package/dist/coordinator-owner-enrollment-client.d.ts.map +1 -0
  258. package/dist/coordinator-owner-enrollment-commit-test-fixtures.d.ts +31 -0
  259. package/dist/coordinator-owner-enrollment-commit-test-fixtures.d.ts.map +1 -0
  260. package/dist/coordinator-owner-enrollment-commit.d.ts +23 -0
  261. package/dist/coordinator-owner-enrollment-commit.d.ts.map +1 -0
  262. package/dist/coordinator-owner-enrollment-historical-test-fixture.d.ts +11 -0
  263. package/dist/coordinator-owner-enrollment-historical-test-fixture.d.ts.map +1 -0
  264. package/dist/coordinator-owner-enrollment-http.d.ts +67 -0
  265. package/dist/coordinator-owner-enrollment-http.d.ts.map +1 -0
  266. package/dist/coordinator-owner-enrollment-proof.d.ts +67 -0
  267. package/dist/coordinator-owner-enrollment-proof.d.ts.map +1 -0
  268. package/dist/coordinator-owner-enrollment-qualification-schema.d.ts +107 -0
  269. package/dist/coordinator-owner-enrollment-qualification-schema.d.ts.map +1 -0
  270. package/dist/coordinator-owner-enrollment-qualification-test-harness.d.ts +39 -0
  271. package/dist/coordinator-owner-enrollment-qualification-test-harness.d.ts.map +1 -0
  272. package/dist/coordinator-owner-enrollment-qualification.d.ts +56 -0
  273. package/dist/coordinator-owner-enrollment-qualification.d.ts.map +1 -0
  274. package/dist/coordinator-owner-enrollment-schema.d.ts +7 -0
  275. package/dist/coordinator-owner-enrollment-schema.d.ts.map +1 -0
  276. package/dist/coordinator-owner-enrollment-start-test-fixtures.d.ts +54 -0
  277. package/dist/coordinator-owner-enrollment-start-test-fixtures.d.ts.map +1 -0
  278. package/dist/coordinator-owner-enrollment-test-harness.d.ts +72 -0
  279. package/dist/coordinator-owner-enrollment-test-harness.d.ts.map +1 -0
  280. package/dist/coordinator-owner-profile-adoption.d.ts +34 -0
  281. package/dist/coordinator-owner-profile-adoption.d.ts.map +1 -0
  282. package/dist/coordinator-owner-profile-client-test-harness.d.ts +57 -0
  283. package/dist/coordinator-owner-profile-client-test-harness.d.ts.map +1 -0
  284. package/dist/coordinator-owner-profile-client.d.ts +38 -0
  285. package/dist/coordinator-owner-profile-client.d.ts.map +1 -0
  286. package/dist/coordinator-owner-profile-files.d.ts +62 -0
  287. package/dist/coordinator-owner-profile-files.d.ts.map +1 -0
  288. package/dist/coordinator-owner-qualification-http.d.ts +14 -0
  289. package/dist/coordinator-owner-qualification-http.d.ts.map +1 -0
  290. package/dist/coordinator-owner-qualification-route.d.ts +16 -0
  291. package/dist/coordinator-owner-qualification-route.d.ts.map +1 -0
  292. package/dist/coordinator-owner-review-local.d.ts +35 -0
  293. package/dist/coordinator-owner-review-local.d.ts.map +1 -0
  294. package/dist/coordinator-peer-discovery-revocation-test-harness.d.ts +21 -0
  295. package/dist/coordinator-peer-discovery-revocation-test-harness.d.ts.map +1 -0
  296. package/dist/coordinator-peer-discovery.d.ts +15 -0
  297. package/dist/coordinator-peer-discovery.d.ts.map +1 -0
  298. package/dist/coordinator-project-invite-guards.d.ts +13 -0
  299. package/dist/coordinator-project-invite-guards.d.ts.map +1 -0
  300. package/dist/coordinator-project-revocation-test-harness.d.ts +25 -0
  301. package/dist/coordinator-project-revocation-test-harness.d.ts.map +1 -0
  302. package/dist/coordinator-recipient-revocation-test-harness.d.ts +30 -0
  303. package/dist/coordinator-recipient-revocation-test-harness.d.ts.map +1 -0
  304. package/dist/coordinator-runtime.d.ts +1 -0
  305. package/dist/coordinator-runtime.d.ts.map +1 -1
  306. package/dist/coordinator-scope-authorization-api-test-harness.d.ts +8 -0
  307. package/dist/coordinator-scope-authorization-api-test-harness.d.ts.map +1 -0
  308. package/dist/coordinator-scope-authorization-response.d.ts +10 -0
  309. package/dist/coordinator-scope-authorization-response.d.ts.map +1 -0
  310. package/dist/coordinator-scope-authorization.d.ts +25 -0
  311. package/dist/coordinator-scope-authorization.d.ts.map +1 -0
  312. package/dist/coordinator-store-contract.d.ts +48 -1
  313. package/dist/coordinator-store-contract.d.ts.map +1 -1
  314. package/dist/coordinator-store.d.ts +2 -1
  315. package/dist/coordinator-store.d.ts.map +1 -1
  316. package/dist/d1-coordinator-runtime.d.ts +9 -1
  317. package/dist/d1-coordinator-runtime.d.ts.map +1 -1
  318. package/dist/d1-coordinator-store.d.ts +108 -5
  319. package/dist/d1-coordinator-store.d.ts.map +1 -1
  320. package/dist/db.d.ts.map +1 -1
  321. package/dist/export-import.d.ts +2 -0
  322. package/dist/export-import.d.ts.map +1 -1
  323. package/dist/extraction-tier-routing.d.ts.map +1 -1
  324. package/dist/filters.d.ts +8 -3
  325. package/dist/filters.d.ts.map +1 -1
  326. package/dist/index.d.ts +38 -10
  327. package/dist/index.d.ts.map +1 -1
  328. package/dist/index.js +27792 -22924
  329. package/dist/index.js.map +1 -1
  330. package/dist/ingest-pipeline.d.ts +4 -0
  331. package/dist/ingest-pipeline.d.ts.map +1 -1
  332. package/dist/ingest-xml-parser.d.ts +2 -5
  333. package/dist/ingest-xml-parser.d.ts.map +1 -1
  334. package/dist/ingest-xml-scan.d.ts +30 -0
  335. package/dist/ingest-xml-scan.d.ts.map +1 -0
  336. package/dist/internal/cloudflare-coordinator.d.ts +23 -2
  337. package/dist/internal/cloudflare-coordinator.d.ts.map +1 -1
  338. package/dist/internal/cloudflare-coordinator.js +4109 -372
  339. package/dist/internal/cloudflare-coordinator.js.map +1 -1
  340. package/dist/legacy-recipient-policy-projection.d.ts.map +1 -1
  341. package/dist/maintenance/relink.d.ts.map +1 -1
  342. package/dist/managed-scope-test-fixtures.d.ts +25 -0
  343. package/dist/managed-scope-test-fixtures.d.ts.map +1 -0
  344. package/dist/memory-creation-provenance.d.ts +13 -0
  345. package/dist/memory-creation-provenance.d.ts.map +1 -0
  346. package/dist/memory-local-capture-test-fixtures.d.ts +39 -0
  347. package/dist/memory-local-capture-test-fixtures.d.ts.map +1 -0
  348. package/dist/memory-local-capture.d.ts +29 -0
  349. package/dist/memory-local-capture.d.ts.map +1 -0
  350. package/dist/memory-ownership-recovery.d.ts.map +1 -1
  351. package/dist/memory-retirement-delivery.d.ts.map +1 -1
  352. package/dist/memory-source-identity.d.ts +3 -0
  353. package/dist/memory-source-identity.d.ts.map +1 -1
  354. package/dist/observer-client.d.ts.map +1 -1
  355. package/dist/observer-output.d.ts.map +1 -1
  356. package/dist/opencode-v2-generation.d.ts.map +1 -1
  357. package/dist/owned-recipient-d1-test-harness.d.ts +7 -0
  358. package/dist/owned-recipient-d1-test-harness.d.ts.map +1 -0
  359. package/dist/owner-browser-admission-authority.d.ts +24 -0
  360. package/dist/owner-browser-admission-authority.d.ts.map +1 -0
  361. package/dist/owner-browser-admission-body.d.ts +8 -0
  362. package/dist/owner-browser-admission-body.d.ts.map +1 -0
  363. package/dist/owner-browser-admission.d.ts +30 -0
  364. package/dist/owner-browser-admission.d.ts.map +1 -0
  365. package/dist/owner-enrollment-admission.d.ts +58 -0
  366. package/dist/owner-enrollment-admission.d.ts.map +1 -0
  367. package/dist/owner-enrollment-link-authority.d.ts +26 -0
  368. package/dist/owner-enrollment-link-authority.d.ts.map +1 -0
  369. package/dist/owner-enrollment-owner-pin-test-harness.d.ts +21 -0
  370. package/dist/owner-enrollment-owner-pin-test-harness.d.ts.map +1 -0
  371. package/dist/owner-enrollment-owner-pin.d.ts +14 -0
  372. package/dist/owner-enrollment-owner-pin.d.ts.map +1 -0
  373. package/dist/owner-enrollment-start-xsoRbhG2.js +14318 -0
  374. package/dist/owner-enrollment-start-xsoRbhG2.js.map +1 -0
  375. package/dist/owner-enrollment-start.d.ts +109 -0
  376. package/dist/owner-enrollment-start.d.ts.map +1 -0
  377. package/dist/owner-qualified-consumer-access-test-harness.d.ts +3 -0
  378. package/dist/owner-qualified-consumer-access-test-harness.d.ts.map +1 -0
  379. package/dist/owner-qualified-consumer-adversarial-test-harness.d.ts +5 -0
  380. package/dist/owner-qualified-consumer-adversarial-test-harness.d.ts.map +1 -0
  381. package/dist/owner-qualified-consumer-test-fixture.d.ts +4 -0
  382. package/dist/owner-qualified-consumer-test-fixture.d.ts.map +1 -0
  383. package/dist/owner-qualified-consumer-test-harness.d.ts +69 -0
  384. package/dist/owner-qualified-consumer-test-harness.d.ts.map +1 -0
  385. package/dist/pi-session-search.d.ts +73 -0
  386. package/dist/pi-session-search.d.ts.map +1 -0
  387. package/dist/pi-sessions-import.d.ts +72 -0
  388. package/dist/pi-sessions-import.d.ts.map +1 -0
  389. package/dist/policy-team-device-eligibility.d.ts.map +1 -1
  390. package/dist/project-scope-settings.d.ts +4 -0
  391. package/dist/project-scope-settings.d.ts.map +1 -1
  392. package/dist/{promise-B3UhYSzv.js → promise-BgC-VNzX.js} +436 -214
  393. package/dist/promise-BgC-VNzX.js.map +1 -0
  394. package/dist/{service-contender-9rqn6x4v-pocTjwT1.js → pty-handoff-9rqn6x4v-Dxw6kceQ.js} +2 -2
  395. package/dist/pty-handoff-9rqn6x4v-Dxw6kceQ.js.map +1 -0
  396. package/dist/raw-event-auth-recovery.d.ts +1 -1
  397. package/dist/raw-event-auth-recovery.d.ts.map +1 -1
  398. package/dist/raw-event-flush.d.ts.map +1 -1
  399. package/dist/recipient-policy-deny-overlay.d.ts +9 -0
  400. package/dist/recipient-policy-deny-overlay.d.ts.map +1 -0
  401. package/dist/recipient-policy-reconciliation.d.ts +1 -9
  402. package/dist/recipient-policy-reconciliation.d.ts.map +1 -1
  403. package/dist/ref-queries.d.ts +1 -1
  404. package/dist/ref-queries.d.ts.map +1 -1
  405. package/dist/schema-bootstrap.d.ts.map +1 -1
  406. package/dist/schema.d.ts +160 -0
  407. package/dist/schema.d.ts.map +1 -1
  408. package/dist/scope-membership-cache-test-fixtures.d.ts +19 -0
  409. package/dist/scope-membership-cache-test-fixtures.d.ts.map +1 -0
  410. package/dist/scope-membership-cache.d.ts +15 -2
  411. package/dist/scope-membership-cache.d.ts.map +1 -1
  412. package/dist/scope-membership-evidence.d.ts +17 -0
  413. package/dist/scope-membership-evidence.d.ts.map +1 -0
  414. package/dist/scope-membership-snapshot.d.ts +22 -0
  415. package/dist/scope-membership-snapshot.d.ts.map +1 -0
  416. package/dist/scope-membership-wire.d.ts +4 -0
  417. package/dist/scope-membership-wire.d.ts.map +1 -0
  418. package/dist/scope-resolution.d.ts +15 -37
  419. package/dist/scope-resolution.d.ts.map +1 -1
  420. package/dist/scope-stamping.d.ts +7 -0
  421. package/dist/scope-stamping.d.ts.map +1 -1
  422. package/dist/scope-write-authority-error.d.ts +5 -0
  423. package/dist/scope-write-authority-error.d.ts.map +1 -0
  424. package/dist/search.d.ts +3 -1
  425. package/dist/search.d.ts.map +1 -1
  426. package/dist/session-export-identity-mutation.d.ts +4 -0
  427. package/dist/session-export-identity-mutation.d.ts.map +1 -0
  428. package/dist/session-export-identity.d.ts +7 -0
  429. package/dist/session-export-identity.d.ts.map +1 -0
  430. package/dist/shared-owned-device-enrollment-test-harness.d.ts +33 -0
  431. package/dist/shared-owned-device-enrollment-test-harness.d.ts.map +1 -0
  432. package/dist/shared-owned-join-approval-test-harness.d.ts +9 -0
  433. package/dist/shared-owned-join-approval-test-harness.d.ts.map +1 -0
  434. package/dist/shared-owned-project-invites-test-harness.d.ts +23 -0
  435. package/dist/shared-owned-project-invites-test-harness.d.ts.map +1 -0
  436. package/dist/shared-owned-recipient-invites-test-harness.d.ts +11 -0
  437. package/dist/shared-owned-recipient-invites-test-harness.d.ts.map +1 -0
  438. package/dist/shared-ownership-writer-lifecycle-test-harness.d.ts +19 -0
  439. package/dist/shared-ownership-writer-lifecycle-test-harness.d.ts.map +1 -0
  440. package/dist/store.d.ts +81 -13
  441. package/dist/store.d.ts.map +1 -1
  442. package/dist/sync-bootstrap.d.ts.map +1 -1
  443. package/dist/sync-http-client.d.ts +1 -0
  444. package/dist/sync-http-client.d.ts.map +1 -1
  445. package/dist/sync-identity.d.ts +6 -0
  446. package/dist/sync-identity.d.ts.map +1 -1
  447. package/dist/sync-pass.d.ts.map +1 -1
  448. package/dist/sync-replication.d.ts +6 -3
  449. package/dist/sync-replication.d.ts.map +1 -1
  450. package/dist/sync-scope-protocol.d.ts +6 -0
  451. package/dist/sync-scope-protocol.d.ts.map +1 -1
  452. package/dist/sync-status-test-fixtures.d.ts +21 -0
  453. package/dist/sync-status-test-fixtures.d.ts.map +1 -0
  454. package/dist/test-schema.generated.d.ts +1 -1
  455. package/dist/test-schema.generated.d.ts.map +1 -1
  456. package/dist/vectors.d.ts.map +1 -1
  457. package/dist/wildcard-match.d.ts +9 -0
  458. package/dist/wildcard-match.d.ts.map +1 -0
  459. package/dist/workspace-identity.d.ts +18 -0
  460. package/dist/workspace-identity.d.ts.map +1 -0
  461. package/package.json +5 -4
  462. package/dist/coordinator-api-CdUQtf5l.js +0 -3755
  463. package/dist/coordinator-api-CdUQtf5l.js.map +0 -1
  464. package/dist/promise-B3UhYSzv.js.map +0 -1
  465. package/dist/service-contender-9rqn6x4v-pocTjwT1.js.map +0 -1
@@ -1,11 +1,2937 @@
1
- import { $ as e, A as t, C as n, D as r, E as i, J as a, O as o, Q as s, S as c, T as l, W as u, X as d, Y as f, Z as p, at as m, b as h, ct as g, dt as _, et as v, ft as y, ht as b, it as x, k as S, lt as C, mt as w, n as T, nt as E, ot as ee, q as D, rt as te, st as O, t as k, tt as A, ut as j, w as M, x as N, y as P } from "../coordinator-api-CdUQtf5l.js";
1
+ import { $ as e, $n as t, $t as n, A as r, Ar as i, At as a, Bn as o, Br as s, Bt as c, C as l, Ci as u, Cn as d, Cr as f, D as p, Dn as m, Dr as h, Dt as g, Ei as ee, En as te, Et as ne, Fn as _, Fr as re, Ft as ie, Gn as ae, Gt as oe, Hn as se, Ht as ce, In as le, Ir as ue, It as de, J as fe, Jn as pe, Jt as me, K as he, Kn as ge, Kt as _e, Ln as v, Lr as ve, Lt as ye, Mn as be, Mr as xe, Mt as Se, Ni as Ce, Nn as we, Nr as Te, Nt as Ee, Or as De, Ot as Oe, Pn as ke, Pr as Ae, Pt as y, Q as b, Qn as je, Qt as Me, Rn as Ne, Rr as Pe, Rt as Fe, S as Ie, Si as Le, Sn as Re, Sr as ze, St as Be, Ti as x, Tn as Ve, Tt as He, Ui as Ue, Un as We, Ur as Ge, Ut as Ke, Vi as qe, Vn as Je, Vr as Ye, Vt as Xe, Wn as Ze, Wr as Qe, Wt as $e, Xn as et, Xt as tt, Yn as nt, Yt as rt, Zn as it, Zt as at, _ as S, _i as ot, _r as st, a as ct, an as lt, at as ut, b as dt, bi as ft, bn as pt, c as mt, ci as ht, cn as gt, cr as _t, ct as vt, d as yt, di as bt, dn as xt, dr as St, en as Ct, er as wt, et as Tt, f as Et, fi as Dt, fn as Ot, fr as kt, g as C, gn as At, gr as jt, h as Mt, hi as Nt, hn as Pt, i as Ft, in as It, ir as Lt, it as Rt, ji as zt, jn as Bt, jr as Vt, jt as Ht, k as Ut, ki as Wt, kn as Gt, kr as Kt, kt as qt, l as Jt, li as Yt, ln as Xt, lr as Zt, m as Qt, n as $t, nn as en, nr as tn, nt as nn, o as rn, on as an, or as on, ot as sn, p as cn, pi as ln, pn as un, qn as w, qt as dn, rn as fn, rr as pn, rt as mn, s as hn, sn as gn, sr as _n, st as vn, t as yn, tn as bn, tt as xn, u as Sn, ui as Cn, un as wn, v as Tn, vi as En, vn as Dn, vr as On, w as T, wi as kn, wn as An, x as E, xn as jn, xr as Mn, y as Nn, yi as Pn, yn as Fn, yr as In, zn as Ln, zr as Rn, zt as zn } from "../owner-enrollment-start-xsoRbhG2.js";
2
+ //#region src/coordinator-account-change-browser.ts
3
+ var D = Object.freeze({
4
+ start: "/auth/account/change/start",
5
+ confirm: "/auth/account/change/confirm"
6
+ });
7
+ function Bn(e, t = 200) {
8
+ return new Response(e.body, {
9
+ status: t,
10
+ headers: e.headers
11
+ });
12
+ }
13
+ function O(e) {
14
+ return e.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&#39;");
15
+ }
16
+ async function k(e = 403) {
17
+ try {
18
+ return Bn(await v("auth_unavailable"), e);
19
+ } catch {
20
+ return new Response("Account change unavailable. Return to your terminal and try again.", {
21
+ status: 503,
22
+ headers: {
23
+ "Cache-Control": "no-store",
24
+ "Referrer-Policy": "no-referrer",
25
+ "X-Content-Type-Options": "nosniff"
26
+ }
27
+ });
28
+ }
29
+ }
30
+ async function Vn(e, t, n, r = "") {
31
+ let i = (await v("auth_unavailable")).headers;
32
+ i["Referrer-Policy"] = "same-origin";
33
+ let a = Object.entries(n).map(([e, t]) => `<input type="hidden" name="${O(e)}" value="${O(t)}">`).join("");
34
+ return new Response(`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="referrer" content="same-origin"><title>${O(e)}</title><main><h1>${O(e)}</h1><p>${O(r)}</p><form method="post" action="${t}">${a}<button type="submit">${O(e)}</button></form></main></html>`, { headers: i });
35
+ }
36
+ async function Hn(e) {
37
+ let t = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(e));
38
+ return Array.from(new Uint8Array(t), (e) => e.toString(16).padStart(2, "0")).join("");
39
+ }
40
+ function Un(e, t) {
41
+ if (e.length > 8192 || e.includes("#")) return null;
42
+ let n = new URL(e);
43
+ if (n.href !== e || `${n.origin}${n.pathname}` !== t || n.username || n.password || [...n.searchParams].length !== 2 || n.searchParams.getAll("attempt_id").length !== 1 || n.searchParams.getAll("start_code").length !== 1) return null;
44
+ let r = n.searchParams.get("attempt_id"), i = n.searchParams.get("start_code");
45
+ return !x(r) || !i || !tn(i) ? null : {
46
+ attemptId: r,
47
+ startCode: i
48
+ };
49
+ }
50
+ async function Wn(e, t, n, r) {
51
+ let i = tn(n);
52
+ if (!i) return null;
53
+ let a = await Lt(i), o = await e.readStart({
54
+ attemptId: t,
55
+ browserStartHash: a
56
+ }, r);
57
+ return !o || o.intent !== "refresh" && o.intent !== "disconnect" ? null : {
58
+ browserStartHash: a,
59
+ intent: o.intent
60
+ };
61
+ }
62
+ async function Gn(e, n, r) {
63
+ let i = await C(e, n.existing, r);
64
+ if (i === "invalid" || i === "active") return !1;
65
+ let a = await t(e, "transaction");
66
+ return a.kind === "absent" || a.kind === "present" && (await n.readers.readManagementActivity({ binderHash: a.cookieHash }, r)).kind === "inactive";
67
+ }
68
+ async function Kn(e, t) {
69
+ return Bn(await Ne({
70
+ destination: e.loopbackRedirect,
71
+ attemptId: e.attemptId,
72
+ completionSecret: t
73
+ }));
74
+ }
75
+ async function qn(e) {
76
+ let n = await t(e, "start");
77
+ return n.kind === "invalid" ? null : n.kind === "present" ? n : je("start");
78
+ }
79
+ async function Jn(e, t) {
80
+ let { input: n, config: r, scope: i, startUrl: a } = e;
81
+ try {
82
+ let e = S(t);
83
+ if (e.method !== "GET") return k(405);
84
+ let o = Un(e.url, a);
85
+ if (!o) return k(400);
86
+ if (!await Wn(n.readers, o.attemptId, o.startCode, r)) return k();
87
+ if (!await Gn(e.cookie, n, r)) return k(409);
88
+ let s = await qn(e.cookie);
89
+ if (!s) return k(400);
90
+ let c = await w(n.csrfKey, s.secret, "start", i), l = await Vn("Continue with Google", D.start, {
91
+ attempt_id: o.attemptId,
92
+ start_code: o.startCode,
93
+ csrf: c
94
+ });
95
+ return "setCookie" in s && l.headers.append("Set-Cookie", s.setCookie), l;
96
+ } catch {
97
+ return k(503);
98
+ }
99
+ }
100
+ async function Yn(e, t, n) {
101
+ let { input: r, config: i, scope: a, startUrl: o } = e;
102
+ try {
103
+ let s = S(t);
104
+ if (s.method !== "POST") return k(405);
105
+ if (s.url !== o) return k(404);
106
+ let c = await E({
107
+ request: t,
108
+ clientKey: n,
109
+ scope: a,
110
+ csrfKey: r.csrfKey,
111
+ limiter: r.limiter,
112
+ action: "link_start"
113
+ });
114
+ return c.ok ? c.action === "link_start" ? await Gn(s.cookie, r, i) ? await Xn(e, s.cookie, c) : k(409) : k() : k(c.error === "rate_limited" ? 429 : 403);
115
+ } catch {
116
+ return k(503);
117
+ }
118
+ }
119
+ async function Xn(e, n, r) {
120
+ let { input: i, config: a, client: o } = e, s = await Wn(i.readers, r.attemptId, r.startCode, a), c = await t(n, "start");
121
+ if (!s || c.kind !== "present" || c.cookieHash !== r.cookieHash) return k();
122
+ let l = await o.createAuthorizationRequest(), u = Bn(await se({ authorizationUrl: l.authorizationUrl }));
123
+ return await i.operations.claimBrowser({
124
+ attemptId: r.attemptId,
125
+ browserStartHash: s.browserStartHash,
126
+ stateHash: await Hn(l.material.state),
127
+ binderHash: r.cookieHash,
128
+ nonce: l.material.nonce,
129
+ pkceVerifier: l.material.pkceVerifier
130
+ }, a) ? (u.headers.append("Set-Cookie", wt(c.secret)), u.headers.append("Set-Cookie", it("start")), u) : k(409);
131
+ }
132
+ async function Zn(e, n) {
133
+ let { config: r } = e, i = S(n);
134
+ if (i.method !== "GET" || i.url.length > 8192 || i.url.includes("#")) return null;
135
+ let a = new URL(i.url), o = new URL(r.redirectUri);
136
+ if (a.origin !== o.origin || a.pathname !== o.pathname || a.username || a.password || a.searchParams.getAll("state").length !== 1) return null;
137
+ let s = a.searchParams.get("state");
138
+ if (!s || !/^[A-Za-z0-9._~-]{43,128}$/.test(s)) return null;
139
+ let c = await t(i.cookie, "transaction");
140
+ return c.kind === "present" ? {
141
+ state: s,
142
+ stateHash: await Hn(s),
143
+ binderHash: c.cookieHash,
144
+ cookie: c,
145
+ callbackUrl: i.url
146
+ } : null;
147
+ }
148
+ async function Qn(e, t) {
149
+ let { input: n, config: r } = e;
150
+ try {
151
+ let i = await Zn(e, t);
152
+ return !!i && await n.operations.hasPendingCallback({
153
+ stateHash: i.stateHash,
154
+ binderHash: i.binderHash
155
+ }, r);
156
+ } catch {
157
+ return !1;
158
+ }
159
+ }
160
+ async function $n(e, t, n, r, i) {
161
+ let { input: a, config: o, scope: s } = e, c = await a.operations.readCallbackView(t, o);
162
+ if (!c || c.attemptId !== t.attemptId) throw Error("callback_unavailable");
163
+ if (c.intent === "refresh") return Kn(c, n);
164
+ if (c.intent !== "disconnect") throw Error("callback_unavailable");
165
+ let l = await w(a.csrfKey, r.secret, "transaction", s), u = le(i, o.issuer);
166
+ return Vn("Disconnect Google account", D.confirm, {
167
+ attempt_id: t.attemptId,
168
+ csrf: l
169
+ }, `${u.email ?? u.title}. Disconnecting ends browser sessions for this connection and removes its display profile. Identity, device keys, history, membership, and access grants stay unchanged.`);
170
+ }
171
+ async function er(e, t) {
172
+ let { input: n, config: r } = e, i = await n.readers.readBrowserBinding(t, r);
173
+ if (!i || !/^[a-f0-9]{64}$/.test(i.stateHash)) return null;
174
+ let a = await n.operations.readBrowserView({
175
+ ...t,
176
+ stateHash: i.stateHash
177
+ }, r);
178
+ return a ? {
179
+ ...a,
180
+ stateHash: i.stateHash
181
+ } : null;
182
+ }
183
+ async function tr(e, t, n) {
184
+ let { input: r, config: i } = e;
185
+ try {
186
+ if (!x(n)) return k(503);
187
+ if (!dt(t, r.limiter, JSON.stringify([
188
+ "browser-callback",
189
+ i.coordinatorId,
190
+ n
191
+ ]), 20).allowed) return k(429);
192
+ let a = await Zn(e, t);
193
+ if (!a) return k();
194
+ let o = {
195
+ stateHash: a.stateHash,
196
+ binderHash: a.binderHash
197
+ };
198
+ if (await r.existing.readAuthBrowserTransactionPurpose(o, i)) return k();
199
+ let s = await r.operations.consumeCallback(o, i);
200
+ return s ? await nr(e, a, s, {
201
+ ...o,
202
+ attemptId: s.attemptId
203
+ }) : k();
204
+ } catch {
205
+ return k(503);
206
+ }
207
+ }
208
+ async function nr(e, t, n, r) {
209
+ let { input: i, config: a, client: o } = e;
210
+ try {
211
+ if (!n.nonce || !n.pkceVerifier) throw Error("missing_material");
212
+ let s = await o.verifyCallback({
213
+ callbackUrl: t.callbackUrl,
214
+ material: {
215
+ state: t.state,
216
+ nonce: n.nonce,
217
+ pkceVerifier: n.pkceVerifier
218
+ }
219
+ });
220
+ if (!s.ok) throw Error("provider_rejected");
221
+ let c = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)), l = await $n(e, r, pn(c), t.cookie, s.profile);
222
+ if (!await i.operations.recordVerifiedCallback({
223
+ ...r,
224
+ issuer: s.account.issuer,
225
+ subject: s.account.subject,
226
+ profile: s.profile,
227
+ completionSecretHash: await Lt(c)
228
+ }, a)) throw Error("account_rejected");
229
+ return l;
230
+ } catch {
231
+ return await i.operations.failConsumed(r, a), k();
232
+ }
233
+ }
234
+ async function rr(e, t, n) {
235
+ let { input: r, config: i, scope: a, confirmUrl: o } = e;
236
+ try {
237
+ let s = S(t);
238
+ if (s.method !== "POST") return k(405);
239
+ if (s.url !== o) return k(404);
240
+ let c = await E({
241
+ request: t,
242
+ clientKey: n,
243
+ scope: a,
244
+ csrfKey: r.csrfKey,
245
+ limiter: r.limiter,
246
+ action: "transaction_attempt"
247
+ });
248
+ if (!c.ok) return k(c.error === "rate_limited" ? 429 : 403);
249
+ if (c.action !== "transaction_attempt") return k();
250
+ let l = await er(e, {
251
+ attemptId: c.attemptId,
252
+ binderHash: c.cookieHash
253
+ });
254
+ if (!l || !ir(l, c)) return k();
255
+ let u = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)), d = await Kn(l, pn(u));
256
+ return await r.operations.confirmDisconnect({
257
+ attemptId: l.attemptId,
258
+ stateHash: l.stateHash,
259
+ binderHash: c.cookieHash,
260
+ completionSecretHash: await Lt(u)
261
+ }, i) ? d : k();
262
+ } catch {
263
+ return k(503);
264
+ }
265
+ }
266
+ function ir(e, t) {
267
+ return e.attemptId === t.attemptId && e.intent === "disconnect" && e.state === "verified";
268
+ }
269
+ async function ar(e) {
270
+ let t = T(e.config);
271
+ if (t.kind !== "enabled") return {
272
+ ok: !1,
273
+ error: "browser_auth_unavailable"
274
+ };
275
+ if (!ge(e.csrfKey) || !e.readers || [
276
+ "readStart",
277
+ "readManagementActivity",
278
+ "readBrowserBinding"
279
+ ].some((t) => typeof Reflect.get(e.readers, t) != "function")) return {
280
+ ok: !1,
281
+ error: "private_reader_required"
282
+ };
283
+ let n = await Mt(t.oidc, e.oidcOptions);
284
+ if (!n.ok) return n;
285
+ let r = {
286
+ input: e,
287
+ client: n.client,
288
+ config: t.store,
289
+ scope: {
290
+ publicOrigin: t.publicOrigin,
291
+ store: t.store
292
+ },
293
+ startUrl: `${t.publicOrigin}${D.start}`,
294
+ confirmUrl: `${t.publicOrigin}${D.confirm}`
295
+ };
296
+ return {
297
+ ok: !0,
298
+ handlers: Object.freeze({
299
+ startPage: (e) => Jn(r, e),
300
+ start: (e, t) => Yn(r, e, t),
301
+ matchesCallback: (e) => Qn(r, e),
302
+ callback: (e, t) => tr(r, e, t),
303
+ confirm: (e, t) => rr(r, e, t)
304
+ })
305
+ };
306
+ }
307
+ //#endregion
308
+ //#region src/coordinator-browser-account.ts
309
+ function or(e) {
310
+ if (typeof e != "object" || !e || Array.isArray(e)) throw Error();
311
+ }
312
+ function sr(e) {
313
+ or(e);
314
+ let t = Object.getPrototypeOf(e);
315
+ if (t !== Object.prototype && t !== null) throw Error();
316
+ }
317
+ function A(e, t) {
318
+ or(e);
319
+ let n = Object.getOwnPropertyDescriptor(e, t);
320
+ if (!n || !Object.hasOwn(n, "value")) throw Error();
321
+ return n.value;
322
+ }
323
+ function cr(e, t) {
324
+ or(e);
325
+ let n = /* @__PURE__ */ new Set(), r = e;
326
+ for (; r !== null;) {
327
+ if (n.has(r)) throw Error();
328
+ n.add(r);
329
+ let e = Object.getOwnPropertyDescriptor(r, t);
330
+ if (e) {
331
+ if (!Object.hasOwn(e, "value") || typeof e.value != "function") throw Error();
332
+ return e.value;
333
+ }
334
+ r = Object.getPrototypeOf(r);
335
+ }
336
+ throw Error();
337
+ }
338
+ function lr(e, t) {
339
+ return Object.freeze({
340
+ response: e,
341
+ outcome: t
342
+ });
343
+ }
344
+ function ur(e, t = 200, n) {
345
+ let r = new Headers(e.headers);
346
+ return r.set("Cache-Control", "no-store"), n && new Headers(n).forEach((e, t) => {
347
+ r.set(t, e);
348
+ }), new Response(e.body, {
349
+ status: t,
350
+ headers: r
351
+ });
352
+ }
353
+ function dr() {
354
+ return lr(new Response("Account unavailable. Try again.", {
355
+ status: 503,
356
+ headers: {
357
+ "Content-Type": "text/plain;charset=utf-8",
358
+ "Cache-Control": "no-store",
359
+ "Referrer-Policy": "no-referrer",
360
+ "X-Content-Type-Options": "nosniff"
361
+ }
362
+ }), "internal_error");
363
+ }
364
+ async function j(e, t, n) {
365
+ try {
366
+ return lr(ur(await v(e === 200 ? "signed_out" : "auth_unavailable"), e, n), t);
367
+ } catch {
368
+ return dr();
369
+ }
370
+ }
371
+ function fr(e, t, n) {
372
+ return e.method === n ? e.url === t ? null : j(404, "not_found") : j(405, "method_not_allowed", { Allow: n });
373
+ }
374
+ function pr(e, t) {
375
+ sr(e);
376
+ let n = A(e, "account");
377
+ sr(n);
378
+ let r = A(n, "issuer"), i = A(e, "identityId");
379
+ if (r !== t.storeConfig.issuer || !x(i)) throw Error();
380
+ return i;
381
+ }
382
+ async function mr(e, n) {
383
+ try {
384
+ let r = S(n), i = fr(r, `${e.publicOrigin}/auth/account`, "GET");
385
+ if (i) return await i;
386
+ let a = await t(r.cookie, "session");
387
+ if (a.kind === "invalid") return await j(200, "cookie_invalid");
388
+ if (a.kind === "absent") return await j(200, "signed_out");
389
+ let o = await e.store.readAuthSessionAccount(a.cookieHash, e.storeConfig);
390
+ if (o === null) return await j(200, "signed_out");
391
+ sr(o);
392
+ let s = pr(A(o, "session"), e), c = A(o, "profile"), l = await w(e.csrfKey, a.secret, "session", e.scope);
393
+ return lr(ur(await Ze({
394
+ profile: c,
395
+ issuer: e.storeConfig.issuer,
396
+ identity: { id: s },
397
+ csrfToken: l
398
+ })), "account_page");
399
+ } catch {
400
+ return await j(503, "internal_error");
401
+ }
402
+ }
403
+ function hr(e) {
404
+ switch (e.error) {
405
+ case "origin_rejected": return j(403, e.error);
406
+ case "rate_limited": return j(429, e.error, { "Retry-After": String(e.retryAfterS) });
407
+ case "cookie_missing": return j(200, "signed_out");
408
+ case "unsupported_media_type": return j(415, e.error);
409
+ case "body_too_large": return j(413, e.error);
410
+ case "form_invalid": return j(400, e.error);
411
+ case "cookie_invalid":
412
+ case "csrf_invalid": return j(403, e.error);
413
+ default: return j(503, "internal_error");
414
+ }
415
+ }
416
+ async function gr(e, t) {
417
+ let n = ur(await v("signed_out"));
418
+ n.headers.append("Set-Cookie", it("session"));
419
+ let r = await e.store.readAuthSession(t, e.storeConfig);
420
+ if (r === null) return lr(n, "already_signed_out");
421
+ pr(r, e);
422
+ let i = await e.store.signOutAuthSession(t, e.signoutScope);
423
+ if (sr(i), A(i, "kind") !== "signed_out") return j(503, "internal_error");
424
+ let a = await e.store.readAuthSession(t, e.storeConfig);
425
+ return a === null ? lr(n, "signed_out") : (pr(a, e), j(503, "signout_unconfirmed"));
426
+ }
427
+ async function _r(e, n, r) {
428
+ try {
429
+ let i = S(n), a = fr(i, `${e.publicOrigin}${_.signOut}`, "POST");
430
+ if (a) return await a;
431
+ let o = await E({
432
+ request: n,
433
+ scope: e.scope,
434
+ csrfKey: e.csrfKey,
435
+ action: "session_logout",
436
+ limiter: e.limiter,
437
+ clientKey: r
438
+ });
439
+ if (!o.ok) return await hr(o);
440
+ if (o.action !== "session_logout") return await j(503, "internal_error");
441
+ let s = await t(i.cookie, "session");
442
+ return s.kind !== "present" || s.cookieHash !== o.cookieHash ? await j(503, "internal_error") : await gr(e, s.cookieHash);
443
+ } catch {
444
+ return await j(503, "internal_error");
445
+ }
446
+ }
447
+ function vr(e) {
448
+ let t = cr(e, "readAuthSessionAccount"), n = cr(e, "readAuthSession"), r = cr(e, "signOutAuthSession");
449
+ return Object.freeze({
450
+ readAuthSessionAccount: t.bind(e),
451
+ readAuthSession: n.bind(e),
452
+ signOutAuthSession: r.bind(e)
453
+ });
454
+ }
455
+ async function yr(e) {
456
+ try {
457
+ let t = A(e, "config"), n = T(t);
458
+ if (n.kind === "disabled") return Object.freeze({
459
+ ok: !1,
460
+ error: "browser_auth_disabled"
461
+ });
462
+ if (n.kind === "invalid") return Object.freeze({
463
+ ok: !1,
464
+ error: "browser_auth_config_invalid",
465
+ field: n.field
466
+ });
467
+ let r = A(e, "csrfKey");
468
+ or(r);
469
+ let i = vr(A(e, "store")), a = A(e, "limiter");
470
+ cr(a, "check");
471
+ let o = Object.freeze({
472
+ storeConfig: n.store,
473
+ publicOrigin: n.publicOrigin,
474
+ scope: Object.freeze({
475
+ publicOrigin: n.publicOrigin,
476
+ store: n.store
477
+ }),
478
+ signoutScope: Object.freeze({ coordinatorId: n.store.coordinatorId }),
479
+ csrfKey: r,
480
+ store: i,
481
+ limiter: a
482
+ });
483
+ return Object.freeze({
484
+ ok: !0,
485
+ handlers: Object.freeze({
486
+ account: (e) => mr(o, e),
487
+ logout: (e, t) => _r(o, e, t)
488
+ })
489
+ });
490
+ } catch {
491
+ return Object.freeze({
492
+ ok: !1,
493
+ error: "invalid_input"
494
+ });
495
+ }
496
+ }
497
+ //#endregion
498
+ //#region src/coordinator-browser-auth-callback.ts
499
+ function M(e, t) {
500
+ if (typeof e != "object" || !e || Array.isArray(e)) throw Error();
501
+ let n = Object.getOwnPropertyDescriptor(e, t);
502
+ if (n && !Object.hasOwn(n, "value")) throw Error();
503
+ return n?.value;
504
+ }
505
+ function br(e, t) {
506
+ if (typeof e != "object" || !e || Array.isArray(e)) throw Error();
507
+ let n = /* @__PURE__ */ new Set(), r = e;
508
+ for (; r !== null;) {
509
+ if (n.has(r)) throw Error();
510
+ n.add(r);
511
+ let e = Object.getOwnPropertyDescriptor(r, t);
512
+ if (e) {
513
+ if (!Object.hasOwn(e, "value") || typeof e.value != "function") throw Error();
514
+ return e.value;
515
+ }
516
+ r = Object.getPrototypeOf(r);
517
+ }
518
+ throw Error();
519
+ }
520
+ function xr(e) {
521
+ let t = br(e, "consumeAuthBrowserTransaction"), n = br(e, "readAuthSession"), r = br(e, "signInWithConsumedBrowserTransaction"), i = br(e, "recordAuthAccountProfile");
522
+ return Object.freeze({
523
+ consumeAuthBrowserTransaction: (...n) => Reflect.apply(t, e, n),
524
+ readAuthSession: (...t) => Reflect.apply(n, e, t),
525
+ signInWithConsumedBrowserTransaction: (...t) => Reflect.apply(r, e, t),
526
+ recordAuthAccountProfile: (...t) => Reflect.apply(i, e, t)
527
+ });
528
+ }
529
+ function Sr(e) {
530
+ let t = M(e, "oidcOptions");
531
+ if (t === void 0) return;
532
+ let n = M(t, "fetch"), r = M(t, "timeoutSeconds");
533
+ return Object.freeze({
534
+ fetch: n,
535
+ timeoutSeconds: r
536
+ });
537
+ }
538
+ function Cr(e, t) {
539
+ let n = e;
540
+ for (; n !== null;) {
541
+ let e = Object.getOwnPropertyDescriptor(n, t);
542
+ if (e) return e.get;
543
+ n = Object.getPrototypeOf(n);
544
+ }
545
+ }
546
+ var wr = Object.freeze({
547
+ method: Cr(Request.prototype, "method"),
548
+ url: Cr(Request.prototype, "url"),
549
+ headers: Cr(Request.prototype, "headers")
550
+ }), Tr = Headers.prototype.get, Er = Cr(Response.prototype, "status");
551
+ function Dr(e) {
552
+ let t = wr.method?.call(e), n = wr.url?.call(e), r = wr.headers?.call(e);
553
+ if (typeof t != "string" || typeof n != "string") throw Error();
554
+ return Object.freeze({
555
+ method: t,
556
+ url: n,
557
+ cookie: Tr.call(r, "cookie")
558
+ });
559
+ }
560
+ function N(e, t) {
561
+ return Object.freeze({
562
+ response: e,
563
+ outcome: t
564
+ });
565
+ }
566
+ async function P(e, t, n = {}) {
567
+ try {
568
+ let r = await v("auth_unavailable"), i = new Headers(r.headers);
569
+ return n.allow && i.set("Allow", n.allow), N(new Response(r.body, {
570
+ status: e,
571
+ headers: i
572
+ }), t);
573
+ } catch {
574
+ let e = new Headers({
575
+ "Content-Type": "text/plain;charset=utf-8",
576
+ "Cache-Control": "no-store",
577
+ "Referrer-Policy": "no-referrer",
578
+ "X-Content-Type-Options": "nosniff"
579
+ });
580
+ return n.allow && e.set("Allow", n.allow), N(new Response("Sign-in or linking unavailable. Return to the flow you started and try again.", {
581
+ status: 503,
582
+ headers: e
583
+ }), "internal_error");
584
+ }
585
+ }
586
+ function Or(e, t) {
587
+ let n = new Headers({
588
+ Location: new URL("/auth/account", e.publicOrigin).href,
589
+ "Cache-Control": "no-store",
590
+ "Referrer-Policy": "no-referrer"
591
+ });
592
+ return t && n.append("Set-Cookie", t), new Response(null, {
593
+ status: 303,
594
+ headers: n
595
+ });
596
+ }
597
+ function kr(e, t) {
598
+ if (t.url.length > 8192 || t.url.includes("#")) return { error: "callback_invalid" };
599
+ let n;
600
+ try {
601
+ n = new URL(t.url);
602
+ } catch {
603
+ return { error: "callback_invalid" };
604
+ }
605
+ let r = new URL(e.callbackURI);
606
+ if (n.origin !== r.origin || n.pathname !== r.pathname) return { error: "not_found" };
607
+ let i = n.searchParams.getAll("state"), a = i[0];
608
+ return i.length !== 1 || typeof a != "string" || a.length < 43 || a.length > 128 || !/^[A-Za-z0-9._~-]+$/.test(a) ? { error: "state_invalid" } : { state: a };
609
+ }
610
+ async function Ar(e) {
611
+ let t = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(e));
612
+ return Array.from(new Uint8Array(t), (e) => e.toString(16).padStart(2, "0")).join("");
613
+ }
614
+ async function jr(e, t, n, r) {
615
+ try {
616
+ let i = await e.client.verifyCallback({
617
+ callbackUrl: t.url,
618
+ material: {
619
+ state: n,
620
+ nonce: r.nonce,
621
+ pkceVerifier: r.pkceVerifier
622
+ }
623
+ });
624
+ if (!i.ok) return Object.freeze({
625
+ ok: !1,
626
+ error: i.error
627
+ });
628
+ if (i.account.issuer !== e.storeConfig.issuer) throw Error();
629
+ return Object.freeze({
630
+ ok: !0,
631
+ account: Object.freeze({ ...i.account }),
632
+ profile: Object.freeze({ ...i.profile })
633
+ });
634
+ } catch {
635
+ return Object.freeze({
636
+ ok: !1,
637
+ error: "oidc_verification_failed"
638
+ });
639
+ }
640
+ }
641
+ async function Mr(e, t, n, r) {
642
+ try {
643
+ let i = await e.completeLink(Object.freeze({
644
+ attemptId: t.attemptId,
645
+ browserTransactionHash: t.browserTransactionHash,
646
+ transactionCookie: n.secret,
647
+ transactionCookieHash: n.cookieHash,
648
+ verification: r
649
+ }));
650
+ if (!Er || typeof Reflect.apply(Er, i, []) != "number") throw Error();
651
+ return N(i, "link_dispatched");
652
+ } catch {
653
+ return P(503, "link_continuation_failed");
654
+ }
655
+ }
656
+ async function Nr(e, t, n, r) {
657
+ try {
658
+ if ((await e.store.recordAuthAccountProfile({
659
+ credentialHash: t,
660
+ profile: n.profile
661
+ }, e.storeConfig)).kind === "recorded") return N(r, "signed_in");
662
+ } catch {}
663
+ return N(r, "signed_in_profile_not_recorded");
664
+ }
665
+ async function Pr(e, n, r, i) {
666
+ if (!i.ok) return P(403, "verification_failed");
667
+ let a = await t(n.cookie, "session");
668
+ if (a.kind === "invalid") throw Error();
669
+ if (a.kind === "present" && await e.store.readAuthSession(a.cookieHash, e.storeConfig)) return N(Or(e), "session_live");
670
+ let o = await je("session"), s = Or(e, o.setCookie);
671
+ return (await e.store.signInWithConsumedBrowserTransaction({
672
+ browserTransactionHash: r.browserTransactionHash,
673
+ account: i.account,
674
+ credentialHash: o.cookieHash
675
+ }, e.storeConfig)).kind === "issued" ? Nr(e, o.cookieHash, i, s) : P(403, "signin_rejected");
676
+ }
677
+ async function Fr(e, t, n, r, i) {
678
+ if (!e.readPurpose) return null;
679
+ let a = await e.readPurpose({
680
+ stateHash: r,
681
+ binderHash: i
682
+ }, e.storeConfig);
683
+ return a === "owner_enroll" && e.ownerCallback ? N(await e.ownerCallback(t, n), "owner_dispatched") : a === "signin" || a === "link" ? null : P(403, "transaction_unavailable");
684
+ }
685
+ async function Ir(e, n, r) {
686
+ try {
687
+ let i = Dr(n);
688
+ if (i.method !== "GET") return await P(405, "method_not_allowed", { allow: "GET" });
689
+ let a = kr(e, i);
690
+ if ("error" in a) return await P(a.error === "not_found" ? 404 : 400, a.error);
691
+ let o = await t(i.cookie, "transaction");
692
+ if (o.kind === "invalid") return await P(400, "cookie_invalid");
693
+ if (o.kind === "absent") return await P(403, "cookie_missing");
694
+ let s = await Ar(a.state), c = await e.accountChangeCallback?.(n, r ?? "", o.cookieHash);
695
+ if (c) return N(c, "account_change_dispatched");
696
+ let l = await Fr(e, n, r, s, o.cookieHash);
697
+ if (l) return l;
698
+ let u = await e.store.consumeAuthBrowserTransaction({
699
+ stateHash: s,
700
+ binderHash: o.cookieHash
701
+ }, e.storeConfig);
702
+ if (u.kind !== "consumed") return await P(403, "transaction_unavailable");
703
+ let d = await jr(e, i, a.state, u);
704
+ if (u.purpose === "link") return await Mr(e, u, o, d);
705
+ if (u.purpose !== "signin") throw Error();
706
+ return await Pr(e, i, u, d);
707
+ } catch {
708
+ return P(503, "internal_error");
709
+ }
710
+ }
711
+ async function Lr(e) {
712
+ try {
713
+ let t = T(M(e, "config"));
714
+ if (t.kind === "disabled") return Object.freeze({
715
+ ok: !1,
716
+ error: "browser_auth_disabled"
717
+ });
718
+ if (t.kind === "invalid") return Object.freeze({
719
+ ok: !1,
720
+ error: "browser_auth_config_invalid",
721
+ field: t.field
722
+ });
723
+ let n = M(e, "completeLink");
724
+ if (typeof n != "function") throw Error();
725
+ let r = xr(M(e, "store")), i = M(e, "ownerCallback"), a = M(e, "accountChangeCallback");
726
+ if (a !== void 0 && typeof a != "function") throw Error();
727
+ let o;
728
+ if (i !== void 0) {
729
+ if (typeof i != "function") throw Error();
730
+ let t = M(e, "purposeStore"), n = br(t, "readAuthBrowserTransactionPurpose");
731
+ o = (...e) => Reflect.apply(n, t, e);
732
+ }
733
+ let s = Sr(e), c = await Mt(t.oidc, s);
734
+ if (!c.ok) return Object.freeze({
735
+ ok: !1,
736
+ error: c.error
737
+ });
738
+ let l = Object.freeze({
739
+ storeConfig: t.store,
740
+ publicOrigin: t.publicOrigin,
741
+ callbackURI: t.store.redirectUri,
742
+ client: c.client,
743
+ store: r,
744
+ completeLink: n,
745
+ ownerCallback: i,
746
+ accountChangeCallback: a,
747
+ readPurpose: o
748
+ });
749
+ return Object.freeze({
750
+ ok: !0,
751
+ handlers: Object.freeze({ callback: (e, t = "") => Ir(l, e, t) })
752
+ });
753
+ } catch {
754
+ return Object.freeze({
755
+ ok: !1,
756
+ error: "invalid_input"
757
+ });
758
+ }
759
+ }
760
+ //#endregion
761
+ //#region src/coordinator-browser-link.ts
762
+ function Rr(e, t) {
763
+ return Object.freeze({
764
+ response: e,
765
+ outcome: t
766
+ });
767
+ }
768
+ function zr(e, t = 200, n) {
769
+ let r = new Headers(e.headers);
770
+ return r.set("Cache-Control", "no-store"), n && new Headers(n).forEach((e, t) => {
771
+ r.set(t, e);
772
+ }), new Response(e.body, {
773
+ status: t,
774
+ headers: r
775
+ });
776
+ }
777
+ function Br() {
778
+ return Rr(new Response("Account linking unavailable. Try again.", {
779
+ status: 503,
780
+ headers: {
781
+ "Content-Type": "text/plain;charset=utf-8",
782
+ "Cache-Control": "no-store",
783
+ "Referrer-Policy": "no-referrer",
784
+ "X-Content-Type-Options": "nosniff"
785
+ }
786
+ }), "internal_error");
787
+ }
788
+ async function F(e, t, n) {
789
+ try {
790
+ return Rr(zr(await v("auth_unavailable"), e, n), t);
791
+ } catch {
792
+ return Br();
793
+ }
794
+ }
795
+ function Vr(e) {
796
+ switch (e.error) {
797
+ case "rate_limited": return F(429, e.error, { "Retry-After": String(e.retryAfterS) });
798
+ case "unsupported_media_type": return F(415, e.error);
799
+ case "body_too_large": return F(413, e.error);
800
+ case "form_invalid": return F(400, e.error);
801
+ case "origin_rejected":
802
+ case "cookie_missing":
803
+ case "cookie_invalid":
804
+ case "csrf_invalid": return F(403, e.error);
805
+ default: return F(503, "internal_error");
806
+ }
807
+ }
808
+ async function Hr(e, t, n, r) {
809
+ let i = zr(await v(r === "cancelled" ? "link_cancelled" : "auth_unavailable"), r === "cancelled" ? 200 : 403), a = await e.store.failAuthLinkAttempt({
810
+ attemptId: t,
811
+ requester: {
812
+ kind: "browser",
813
+ browserTransactionHash: n
814
+ },
815
+ reason: r
816
+ }, e.config);
817
+ if (a.kind !== "applied" && a.kind !== "existing" || a.status.state !== "failed") return F(403, "link_rejected");
818
+ let o = await e.store.retireAuthBrowserTransactions(e.config, { attemptId: t });
819
+ return o.kind !== "retired" || o.more ? F(503, "internal_error") : r === "cancelled" ? Rr(i, "link_cancelled") : Rr(i, "link_rejected");
820
+ }
821
+ async function Ur(e, n) {
822
+ try {
823
+ let r = Gr(n);
824
+ if (r === null) return (await F(403, "link_rejected")).response;
825
+ let i = await t(`${nt.transaction}=${r}`, "transaction");
826
+ if (i.kind !== "present" || i.cookieHash !== n.transactionCookieHash) return (await F(403, "link_rejected")).response;
827
+ let a = await e.store.resolveAuthLinkBrowserTransaction({
828
+ attemptId: n.attemptId,
829
+ binderHash: i.cookieHash
830
+ }, e.config);
831
+ if (!a || a.browserTransactionHash !== n.browserTransactionHash) return (await F(403, "link_rejected")).response;
832
+ if (!n.verification.ok) return (await Hr(e, n.attemptId, a.browserTransactionHash, "provider_failure")).response;
833
+ if (n.verification.account.issuer !== e.config.issuer) return (await F(403, "link_rejected")).response;
834
+ let o = await e.store.recordAuthLinkOidcVerified({
835
+ attemptId: n.attemptId,
836
+ browserTransactionHash: a.browserTransactionHash,
837
+ account: n.verification.account,
838
+ profile: n.verification.profile
839
+ }, e.config);
840
+ return o.kind === "applied" ? await Wr(e, n.attemptId, i.secret, n.verification.profile, o.target) : (await F(403, "link_rejected")).response;
841
+ } catch {
842
+ return (await F(503, "internal_error")).response;
843
+ }
844
+ }
845
+ async function Wr(e, t, n, r, i) {
846
+ let a = await w(e.csrfKey, n, "transaction", e.scope);
847
+ return zr(await o({
848
+ profile: r,
849
+ issuer: e.config.issuer,
850
+ identity: { id: i.identityId },
851
+ device: { id: i.deviceId },
852
+ group: { id: i.groupId },
853
+ attemptId: t,
854
+ csrfToken: a
855
+ }));
856
+ }
857
+ function Gr(e) {
858
+ try {
859
+ return et(e.transactionCookie, "transaction");
860
+ } catch {
861
+ return null;
862
+ }
863
+ }
864
+ async function Kr(e, t, n) {
865
+ let r = await e.store.readAuthLinkCompletionDestination({
866
+ attemptId: t,
867
+ browserTransactionHash: n
868
+ }, e.config);
869
+ if (!r) return F(403, "link_rejected");
870
+ let i = globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)), a = btoa(String.fromCharCode(...i)).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, ""), o = await globalThis.crypto.subtle.digest("SHA-256", i), s = Array.from(new Uint8Array(o), (e) => e.toString(16).padStart(2, "0")).join(""), c = zr(await Ne({
871
+ destination: r.destination,
872
+ attemptId: t,
873
+ completionSecret: a
874
+ }));
875
+ return (await e.store.confirmAuthLinkAttempt({
876
+ attemptId: t,
877
+ browserTransactionHash: n,
878
+ completionSecretHash: s
879
+ }, e.config)).kind === "applied" ? Rr(c, "link_confirmed") : F(403, "link_rejected");
880
+ }
881
+ async function qr(e, n, r, i) {
882
+ try {
883
+ let a = S(n);
884
+ if (a.method !== "POST") return await F(405, "method_not_allowed", { Allow: "POST" });
885
+ if (a.url !== `${e.scope.publicOrigin}${_[i]}`) return await F(404, "not_found");
886
+ let o = await E({
887
+ request: n,
888
+ clientKey: r,
889
+ scope: e.scope,
890
+ csrfKey: e.csrfKey,
891
+ limiter: e.limiter,
892
+ action: "transaction_attempt"
893
+ });
894
+ if (!o.ok) return await Vr(o);
895
+ if (o.action !== "transaction_attempt") return await F(503, "internal_error");
896
+ let s = await t(a.cookie, "transaction");
897
+ if (s.kind !== "present" || s.cookieHash !== o.cookieHash) return await F(403, "link_rejected");
898
+ let c = await e.store.resolveAuthLinkBrowserTransaction({
899
+ attemptId: o.attemptId,
900
+ binderHash: o.cookieHash
901
+ }, e.config);
902
+ return c ? i === "cancelLink" ? await Hr(e, o.attemptId, c.browserTransactionHash, "cancelled") : await Kr(e, o.attemptId, c.browserTransactionHash) : await F(403, "link_rejected");
903
+ } catch {
904
+ return await F(503, "internal_error");
905
+ }
906
+ }
907
+ function Jr(e) {
908
+ let t = Object.freeze({
909
+ coordinatorId: e.config.coordinatorId,
910
+ issuer: e.config.issuer,
911
+ revision: e.config.revision,
912
+ redirectUri: e.config.redirectUri,
913
+ enabled: e.config.enabled
914
+ });
915
+ if (!t.enabled) return Object.freeze({
916
+ ok: !1,
917
+ error: "browser_auth_disabled"
918
+ });
919
+ let n = e.store, r = Object.freeze({
920
+ resolveAuthLinkBrowserTransaction: n.resolveAuthLinkBrowserTransaction.bind(n),
921
+ retireAuthBrowserTransactions: n.retireAuthBrowserTransactions.bind(n),
922
+ recordAuthLinkOidcVerified: n.recordAuthLinkOidcVerified.bind(n),
923
+ readAuthLinkCompletionDestination: n.readAuthLinkCompletionDestination.bind(n),
924
+ confirmAuthLinkAttempt: n.confirmAuthLinkAttempt.bind(n),
925
+ failAuthLinkAttempt: n.failAuthLinkAttempt.bind(n)
926
+ }), i = Object.freeze({
927
+ publicOrigin: new URL(t.redirectUri).origin,
928
+ store: t
929
+ }), a = Object.freeze({
930
+ config: t,
931
+ scope: i,
932
+ store: r,
933
+ csrfKey: e.csrfKey,
934
+ limiter: e.limiter
935
+ });
936
+ return Object.freeze({
937
+ ok: !0,
938
+ handlers: Object.freeze({
939
+ completeLink: (e) => Ur(a, e),
940
+ confirm: (e, t) => qr(a, e, t, "confirmLink"),
941
+ cancel: (e, t) => qr(a, e, t, "cancelLink")
942
+ })
943
+ });
944
+ }
945
+ //#endregion
946
+ //#region src/coordinator-browser-link-completion.ts
947
+ function Yr(e, t) {
948
+ return Object.freeze({
949
+ response: e,
950
+ outcome: t
951
+ });
952
+ }
953
+ function Xr(e, t = 200, n) {
954
+ let r = new Headers(e.headers);
955
+ return n && new Headers(n).forEach((e, t) => {
956
+ r.set(t, e);
957
+ }), new Response(e.body, {
958
+ status: t,
959
+ headers: r
960
+ });
961
+ }
962
+ async function I(e, t, n) {
963
+ try {
964
+ return Yr(Xr(await v("auth_unavailable"), e, n), t);
965
+ } catch {
966
+ return Yr(new Response("Linking unavailable. Try again.", {
967
+ status: 503,
968
+ headers: {
969
+ "Content-Type": "text/plain;charset=utf-8",
970
+ "Cache-Control": "no-store",
971
+ "Referrer-Policy": "no-referrer",
972
+ "X-Content-Type-Options": "nosniff"
973
+ }
974
+ }), "internal_error");
975
+ }
976
+ }
977
+ function Zr(e) {
978
+ let t = [...e.searchParams], n = t[0];
979
+ if (t.length !== 1 || !n || n[0] !== "attempt_id") return null;
980
+ let r = n[1];
981
+ return x(r) ? r : null;
982
+ }
983
+ async function Qr(e, t, n) {
984
+ let r = await e.store.resolveAuthLinkBrowserTransaction({
985
+ attemptId: t,
986
+ binderHash: n
987
+ }, e.config);
988
+ if (r === null) return null;
989
+ let i = r.browserTransactionHash, a = await e.store.getAuthLinkAttemptStatus(t, {
990
+ kind: "browser",
991
+ browserTransactionHash: i
992
+ }, e.config);
993
+ return a === null ? null : {
994
+ browserTransactionHash: i,
995
+ state: a.state
996
+ };
997
+ }
998
+ async function $r(e, n) {
999
+ try {
1000
+ let r = S(n);
1001
+ if (r.method !== "GET") return await I(405, "method_not_allowed", { Allow: "GET" });
1002
+ if (r.url.length > 8192) return await I(400, "query_invalid");
1003
+ let i = new URL(r.url);
1004
+ if (r.url.includes("#") || `${i.origin}${i.pathname}` != `${e.publicOrigin}${_.completeLink}` || i.username || i.password) return await I(404, "not_found");
1005
+ let a = Zr(i);
1006
+ if (a === null) return await I(400, "query_invalid");
1007
+ let o = await t(r.cookie, "transaction");
1008
+ if (o.kind !== "present") return await I(403, "cookie_invalid");
1009
+ let s = await Qr(e, a, o.cookieHash);
1010
+ if (s?.state === "confirmed") return Yr(Xr(await Ln({
1011
+ attemptId: a,
1012
+ state: "waiting"
1013
+ })), "waiting");
1014
+ if (s?.state !== "finalized") return await I(403, "completion_rejected");
1015
+ let c = await w(e.csrfKey, o.secret, "transaction", e.scope);
1016
+ return Yr(Xr(await Ln({
1017
+ attemptId: a,
1018
+ state: "ready",
1019
+ csrfToken: c
1020
+ })), "ready");
1021
+ } catch {
1022
+ return await I(503, "internal_error");
1023
+ }
1024
+ }
1025
+ function ei(e) {
1026
+ switch (e.error) {
1027
+ case "origin_rejected":
1028
+ case "cookie_invalid":
1029
+ case "csrf_invalid": return I(403, e.error);
1030
+ case "cookie_missing": return I(403, "cookie_invalid");
1031
+ case "client_unidentified": return I(503, "internal_error");
1032
+ case "rate_limited": return I(429, e.error, { "Retry-After": String(e.retryAfterS) });
1033
+ case "unsupported_media_type": return I(415, e.error);
1034
+ case "body_too_large": return I(413, e.error);
1035
+ case "form_invalid": return I(400, e.error);
1036
+ default: return I(503, "internal_error");
1037
+ }
1038
+ }
1039
+ function ti(e, t) {
1040
+ let n = new Headers({
1041
+ Location: `${e.publicOrigin}/auth/account`,
1042
+ "Cache-Control": "no-store",
1043
+ "Referrer-Policy": "no-referrer"
1044
+ });
1045
+ return t && n.append("Set-Cookie", t), new Response(null, {
1046
+ status: 303,
1047
+ headers: n
1048
+ });
1049
+ }
1050
+ async function ni(e, n, r, i, a) {
1051
+ let o = await t(n, "session");
1052
+ if (o.kind === "invalid") return I(403, "cookie_invalid");
1053
+ if (o.kind === "present" && await e.store.readAuthSession(o.cookieHash, e.config) !== null) {
1054
+ let t = ti(e);
1055
+ return (await e.store.preserveAuthLinkSessionCompletion({
1056
+ attemptId: r,
1057
+ browserTransactionHash: a,
1058
+ binderHash: i,
1059
+ credentialHash: o.cookieHash
1060
+ }, e.config)).kind === "preserved" ? Yr(t, "session_preserved") : I(403, "completion_rejected");
1061
+ }
1062
+ let s = await je("session"), c = ti(e, s.setCookie);
1063
+ return (await e.store.redeemAuthLinkSessionWithBrowserTransaction({
1064
+ attemptId: r,
1065
+ browserTransactionHash: a,
1066
+ binderHash: i,
1067
+ credentialHash: s.cookieHash
1068
+ }, e.config)).kind === "issued" ? Yr(c, "session_issued") : I(403, "completion_rejected");
1069
+ }
1070
+ async function ri(e, n, r) {
1071
+ try {
1072
+ let i = S(n);
1073
+ if (i.method !== "POST") return await I(405, "method_not_allowed", { Allow: "POST" });
1074
+ if (i.url !== `${e.publicOrigin}${_.completeLink}`) return await I(404, "not_found");
1075
+ let a = await E({
1076
+ request: n,
1077
+ scope: e.scope,
1078
+ csrfKey: e.csrfKey,
1079
+ action: "transaction_attempt",
1080
+ limiter: e.limiter,
1081
+ clientKey: r
1082
+ });
1083
+ if (!a.ok) return await ei(a);
1084
+ if (a.action !== "transaction_attempt") return await I(503, "internal_error");
1085
+ let o = await t(i.cookie, "transaction");
1086
+ if (o.kind !== "present" || o.cookieHash !== a.cookieHash) return await I(403, "cookie_invalid");
1087
+ let s = await Qr(e, a.attemptId, a.cookieHash);
1088
+ return s?.state === "finalized" ? await ni(e, i.cookie, a.attemptId, a.cookieHash, s.browserTransactionHash) : await I(403, "completion_rejected");
1089
+ } catch {
1090
+ return await I(503, "internal_error");
1091
+ }
1092
+ }
1093
+ function ii(e) {
1094
+ if (!e.config?.enabled) return Object.freeze({
1095
+ ok: !1,
1096
+ error: "browser_auth_disabled"
1097
+ });
1098
+ let t = Object.freeze({
1099
+ enabled: e.config.enabled,
1100
+ coordinatorId: e.config.coordinatorId,
1101
+ issuer: e.config.issuer,
1102
+ revision: e.config.revision,
1103
+ redirectUri: e.config.redirectUri
1104
+ }), n = e.store, r = Object.freeze({
1105
+ resolveAuthLinkBrowserTransaction: n.resolveAuthLinkBrowserTransaction.bind(n),
1106
+ getAuthLinkAttemptStatus: n.getAuthLinkAttemptStatus.bind(n),
1107
+ readAuthSession: n.readAuthSession.bind(n),
1108
+ preserveAuthLinkSessionCompletion: n.preserveAuthLinkSessionCompletion.bind(n),
1109
+ redeemAuthLinkSessionWithBrowserTransaction: n.redeemAuthLinkSessionWithBrowserTransaction.bind(n)
1110
+ }), i = new URL(t.redirectUri).origin, a = Object.freeze({
1111
+ config: t,
1112
+ publicOrigin: i,
1113
+ scope: Object.freeze({
1114
+ publicOrigin: i,
1115
+ store: t
1116
+ }),
1117
+ csrfKey: e.csrfKey,
1118
+ store: r,
1119
+ limiter: e.limiter
1120
+ });
1121
+ return Object.freeze({
1122
+ ok: !0,
1123
+ handlers: Object.freeze({
1124
+ page: (e) => $r(a, e),
1125
+ complete: (e, t) => ri(a, e, t)
1126
+ })
1127
+ });
1128
+ }
1129
+ //#endregion
1130
+ //#region src/coordinator-browser-link-start.ts
1131
+ var ai = Object.getOwnPropertyDescriptor(Request.prototype, "headers")?.get, oi = Headers.prototype.get, si = 8192;
1132
+ function L(e, t) {
1133
+ if (typeof e != "object" || !e || Array.isArray(e)) throw Error();
1134
+ let n = Object.getOwnPropertyDescriptor(e, t);
1135
+ if (n && !Object.hasOwn(n, "value")) throw Error();
1136
+ return n?.value;
1137
+ }
1138
+ function ci(e, t) {
1139
+ if (typeof e != "object" || !e || Array.isArray(e)) throw Error();
1140
+ let n = /* @__PURE__ */ new Set(), r = e;
1141
+ for (; r !== null;) {
1142
+ if (n.has(r)) throw Error();
1143
+ n.add(r);
1144
+ let e = Object.getOwnPropertyDescriptor(r, t);
1145
+ if (e) {
1146
+ if (!Object.hasOwn(e, "value") || typeof e.value != "function") throw Error();
1147
+ return e.value;
1148
+ }
1149
+ r = Object.getPrototypeOf(r);
1150
+ }
1151
+ throw Error();
1152
+ }
1153
+ function li(e, t) {
1154
+ return Object.freeze({
1155
+ response: e,
1156
+ outcome: t
1157
+ });
1158
+ }
1159
+ function ui(e, t = 200, n) {
1160
+ let r = new Headers(e.headers);
1161
+ return n && new Headers(n).forEach((e, t) => {
1162
+ r.set(t, e);
1163
+ }), new Response(e.body, {
1164
+ status: t,
1165
+ headers: r
1166
+ });
1167
+ }
1168
+ async function R(e, t, n) {
1169
+ try {
1170
+ return li(ui(await v("unavailable"), e, n), t);
1171
+ } catch {
1172
+ return li(new Response("Account linking unavailable. Return to your terminal and try again.", {
1173
+ status: 503,
1174
+ headers: {
1175
+ "Content-Type": "text/plain;charset=utf-8",
1176
+ "Cache-Control": "no-store",
1177
+ "Referrer-Policy": "no-referrer",
1178
+ "X-Content-Type-Options": "nosniff"
1179
+ }
1180
+ }), "internal_error");
1181
+ }
1182
+ }
1183
+ function di(e, t) {
1184
+ let n = new URL(t);
1185
+ if (t.includes("#") || n.href !== t || `${n.origin}${n.pathname}` !== e.startUrl || n.username || n.password || [...n.searchParams].length !== 2 || n.searchParams.getAll("attempt_id").length !== 1 || n.searchParams.getAll("start_code").length !== 1) return null;
1186
+ let r = n.searchParams.get("attempt_id"), i = n.searchParams.get("start_code");
1187
+ return !x(r) || typeof i != "string" || !tn(i) ? null : Object.freeze({
1188
+ attemptId: r,
1189
+ startCode: i
1190
+ });
1191
+ }
1192
+ async function fi(e, n) {
1193
+ try {
1194
+ let r = Tn(n);
1195
+ if (r.method !== "GET") return await R(405, "method_not_allowed", { Allow: "GET" });
1196
+ if (r.url.length > si) return await R(400, "form_invalid");
1197
+ let i = new URL(r.url);
1198
+ if (`${i.origin}${i.pathname}` !== e.startUrl || i.username || i.password) return await R(404, "not_found");
1199
+ let a = di(e, r.url);
1200
+ if (!a) return await R(400, "form_invalid");
1201
+ let o = S(n), s = await C(o.cookie, e.store, e.storeConfig);
1202
+ if (s === "invalid") return await R(400, "cookie_invalid");
1203
+ if (s === "active") return await R(409, "link_in_progress");
1204
+ let c = await t(o.cookie, "start");
1205
+ if (c.kind === "invalid") return await R(400, "cookie_invalid");
1206
+ let l = c.kind === "present" ? c : await je("start"), u = await w(e.csrfKey, l.secret, "start", e.scope), d = ui(await Je({
1207
+ ...a,
1208
+ csrfToken: u
1209
+ }));
1210
+ return "setCookie" in l && d.headers.append("Set-Cookie", l.setCookie), li(d, "link_start_page");
1211
+ } catch {
1212
+ return await R(503, "internal_error");
1213
+ }
1214
+ }
1215
+ function pi(e) {
1216
+ return e.ok ? null : e.error === "origin_rejected" ? R(403, "origin_rejected") : e.error === "rate_limited" ? R(429, "rate_limited", { "Retry-After": String(e.retryAfterS) }) : e.error === "client_unidentified" || e.error === "invalid_input" ? R(503, "internal_error") : null;
1217
+ }
1218
+ function mi(e) {
1219
+ switch (e.error) {
1220
+ case "unsupported_media_type": return R(415, e.error);
1221
+ case "body_too_large": return R(413, e.error);
1222
+ case "form_invalid": return R(400, e.error);
1223
+ case "cookie_invalid":
1224
+ case "cookie_missing":
1225
+ case "csrf_invalid": return R(403, e.error);
1226
+ default: return R(503, "internal_error");
1227
+ }
1228
+ }
1229
+ async function hi(e, n, r) {
1230
+ let i = await t(n.cookie, "start");
1231
+ if (i.kind !== "present" || i.cookieHash !== r.cookieHash) return R(503, "internal_error");
1232
+ let a = tn(r.startCode);
1233
+ if (!a) return R(400, "form_invalid");
1234
+ let o = await Lt(a), s;
1235
+ try {
1236
+ s = await e.client.createAuthorizationRequest();
1237
+ } catch {
1238
+ return R(503, "provider_request_failed");
1239
+ }
1240
+ let c = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(s.material.state)), l = Array.from(new Uint8Array(c), (e) => e.toString(16).padStart(2, "0")).join(""), u = ui(await se({ authorizationUrl: s.authorizationUrl }));
1241
+ u.headers.append("Set-Cookie", wt(i.secret)), u.headers.append("Set-Cookie", it("start"));
1242
+ let d = await e.store.startAuthBrowserTransaction({
1243
+ purpose: "link",
1244
+ attemptId: r.attemptId,
1245
+ browserStartHash: o,
1246
+ stateHash: l,
1247
+ binderHash: r.cookieHash,
1248
+ nonce: s.material.nonce,
1249
+ pkceVerifier: s.material.pkceVerifier
1250
+ }, e.storeConfig);
1251
+ if (d.kind === "started") return li(u, "link_started");
1252
+ if (d.kind === "rejected") {
1253
+ if (d.error === "attempt_unavailable" || d.error === "attempt_expired") return R(409, "attempt_unavailable");
1254
+ if (d.error === "transaction_conflict") return R(409, "start_conflict");
1255
+ if (d.error === "transaction_limited" || d.error === "clock_retention_blocked") return R(503, "start_limited");
1256
+ }
1257
+ return R(503, "internal_error");
1258
+ }
1259
+ async function gi(e, t, n) {
1260
+ try {
1261
+ let r = Tn(t);
1262
+ if (r.method !== "POST") return await R(405, "method_not_allowed", { Allow: "POST" });
1263
+ if (r.url.length > si) return await R(400, "form_invalid");
1264
+ let i = ai?.call(t);
1265
+ if (new URL(r.url).origin !== e.scope.publicOrigin || oi.call(i, "origin") !== e.scope.publicOrigin) return await R(403, "origin_rejected");
1266
+ if (r.url !== e.startUrl) return await R(404, "not_found");
1267
+ let a = S(t), o = await E({
1268
+ request: t,
1269
+ scope: e.scope,
1270
+ csrfKey: e.csrfKey,
1271
+ action: "link_start",
1272
+ limiter: e.limiter,
1273
+ clientKey: n
1274
+ }), s = pi(o);
1275
+ if (s) return await s;
1276
+ let c = await C(a.cookie, e.store, e.storeConfig);
1277
+ return c === "invalid" ? await R(400, "cookie_invalid") : c === "active" ? await R(409, "link_in_progress") : o.ok ? o.action === "link_start" ? await hi(e, a, o) : await R(503, "internal_error") : await mi(o);
1278
+ } catch {
1279
+ return await R(503, "internal_error");
1280
+ }
1281
+ }
1282
+ function _i(e) {
1283
+ let t = L(e, "oidcOptions");
1284
+ if (t !== void 0) return Object.freeze({
1285
+ fetch: L(t, "fetch"),
1286
+ timeoutSeconds: L(t, "timeoutSeconds")
1287
+ });
1288
+ }
1289
+ async function vi(e) {
1290
+ try {
1291
+ let t = T(L(e, "config"));
1292
+ if (t.kind === "disabled") return Object.freeze({
1293
+ ok: !1,
1294
+ error: "browser_auth_disabled"
1295
+ });
1296
+ if (t.kind === "invalid") return Object.freeze({
1297
+ ok: !1,
1298
+ error: "browser_auth_config_invalid",
1299
+ field: t.field
1300
+ });
1301
+ let n = L(e, "csrfKey"), r = L(e, "store"), i = ci(r, "startAuthBrowserTransaction"), a = ci(r, "readAuthBrowserTransactionActivity"), o = Object.freeze({
1302
+ startAuthBrowserTransaction: i.bind(r),
1303
+ readAuthBrowserTransactionActivity: a.bind(r)
1304
+ }), s = L(e, "limiter");
1305
+ ci(s, "check");
1306
+ let c = _i(e), l = Object.freeze({
1307
+ publicOrigin: t.publicOrigin,
1308
+ store: t.store
1309
+ }), u = new URL("/auth/link/start", t.publicOrigin).href, d = await Mt(t.oidc, c);
1310
+ if (!d.ok) return Object.freeze({
1311
+ ok: !1,
1312
+ error: d.error
1313
+ });
1314
+ let f = Object.freeze({
1315
+ storeConfig: t.store,
1316
+ scope: l,
1317
+ csrfKey: n,
1318
+ store: o,
1319
+ limiter: s,
1320
+ client: d.client,
1321
+ startUrl: u
1322
+ });
1323
+ return Object.freeze({
1324
+ ok: !0,
1325
+ handlers: Object.freeze({
1326
+ linkStartPage: (e) => fi(f, e),
1327
+ linkStart: (e, t) => gi(f, e, t)
1328
+ })
1329
+ });
1330
+ } catch {
1331
+ return Object.freeze({
1332
+ ok: !1,
1333
+ error: "invalid_input"
1334
+ });
1335
+ }
1336
+ }
1337
+ //#endregion
1338
+ //#region src/coordinator-browser-signin-start.ts
1339
+ function z(e, t) {
1340
+ if (typeof e != "object" || !e || Array.isArray(e)) throw Error();
1341
+ let n = Object.getOwnPropertyDescriptor(e, t);
1342
+ if (n && !Object.hasOwn(n, "value")) throw Error();
1343
+ return n?.value;
1344
+ }
1345
+ function yi(e, t) {
1346
+ if (typeof e != "object" || !e || Array.isArray(e)) throw Error();
1347
+ let n = /* @__PURE__ */ new Set(), r = e;
1348
+ for (; r !== null;) {
1349
+ if (n.has(r)) throw Error();
1350
+ n.add(r);
1351
+ let e = Object.getOwnPropertyDescriptor(r, t);
1352
+ if (e) {
1353
+ if (!Object.hasOwn(e, "value") || typeof e.value != "function") throw Error();
1354
+ return e.value;
1355
+ }
1356
+ r = Object.getPrototypeOf(r);
1357
+ }
1358
+ throw Error();
1359
+ }
1360
+ function bi(e) {
1361
+ let t = Request.prototype;
1362
+ for (; t !== null;) {
1363
+ let n = Object.getOwnPropertyDescriptor(t, e);
1364
+ if (n) return n.get;
1365
+ t = Object.getPrototypeOf(t);
1366
+ }
1367
+ }
1368
+ var xi = Object.freeze({
1369
+ method: bi("method"),
1370
+ url: bi("url"),
1371
+ headers: bi("headers")
1372
+ }), Si = Headers.prototype.get;
1373
+ function Ci(e) {
1374
+ let t = xi.method?.call(e), n = xi.url?.call(e), r = xi.headers?.call(e);
1375
+ if (typeof t != "string" || typeof n != "string") throw Error();
1376
+ return Object.freeze({
1377
+ method: t,
1378
+ url: n,
1379
+ cookie: Si.call(r, "cookie")
1380
+ });
1381
+ }
1382
+ function wi(e, t) {
1383
+ return Object.freeze({
1384
+ response: e,
1385
+ outcome: t
1386
+ });
1387
+ }
1388
+ function Ti(e, t = 200, n) {
1389
+ let r = new Headers(e.headers);
1390
+ return r.set("Cache-Control", "no-store"), n && new Headers(n).forEach((e, t) => {
1391
+ r.set(t, e);
1392
+ }), new Response(e.body, {
1393
+ status: t,
1394
+ headers: r
1395
+ });
1396
+ }
1397
+ function Ei() {
1398
+ return wi(new Response("Sign-in unavailable. Try again.", {
1399
+ status: 503,
1400
+ headers: {
1401
+ "Content-Type": "text/plain;charset=utf-8",
1402
+ "Cache-Control": "no-store",
1403
+ "Referrer-Policy": "no-referrer",
1404
+ "X-Content-Type-Options": "nosniff"
1405
+ }
1406
+ }), "internal_error");
1407
+ }
1408
+ async function B(e, t, n) {
1409
+ try {
1410
+ return wi(Ti(await v(t === "signin_in_progress" || t === "start_conflict" ? "signin_in_progress" : "signin_unavailable"), e, n), t);
1411
+ } catch {
1412
+ return Ei();
1413
+ }
1414
+ }
1415
+ function Di(e) {
1416
+ return wi(new Response(null, {
1417
+ status: 303,
1418
+ headers: {
1419
+ Location: e.accountUrl,
1420
+ "Cache-Control": "no-store",
1421
+ "Referrer-Policy": "no-referrer"
1422
+ }
1423
+ }), "session_live");
1424
+ }
1425
+ async function Oi(e, n) {
1426
+ let r = await t(n.cookie, "session");
1427
+ if (r.kind === "invalid") throw Error();
1428
+ return r.kind !== "absent" && await e.store.readAuthSession(r.cookieHash, e.storeConfig) !== null;
1429
+ }
1430
+ function ki(e, t, n) {
1431
+ return t.method === n ? t.url === e.signinUrl ? null : B(404, "not_found") : B(405, "method_not_allowed", { Allow: n });
1432
+ }
1433
+ async function Ai(e, n) {
1434
+ try {
1435
+ let r = Ci(n), i = ki(e, r, "GET");
1436
+ if (i) return await i;
1437
+ let a = await C(r.cookie, e.store, e.storeConfig);
1438
+ if (a === "invalid") return await B(400, "cookie_invalid");
1439
+ if (a === "active") return await B(409, "signin_in_progress");
1440
+ if (await Oi(e, r)) return Di(e);
1441
+ let o = await t(r.cookie, "start");
1442
+ if (o.kind === "invalid") return await B(400, "cookie_invalid");
1443
+ let s = o.kind === "present" ? o : await je("start"), c = await w(e.csrfKey, s.secret, "start", e.scope), l = Ti(await We({ csrfToken: c }));
1444
+ return "setCookie" in s && l.headers.append("Set-Cookie", s.setCookie), wi(l, "signin_page");
1445
+ } catch {
1446
+ return await B(503, "internal_error");
1447
+ }
1448
+ }
1449
+ function ji(e) {
1450
+ return e.ok ? null : e.error === "origin_rejected" ? B(403, "origin_rejected") : e.error === "rate_limited" ? B(429, "rate_limited", { "Retry-After": String(e.retryAfterS) }) : e.error === "client_unidentified" || e.error === "invalid_input" ? B(503, "internal_error") : null;
1451
+ }
1452
+ function Mi(e) {
1453
+ switch (e.error) {
1454
+ case "unsupported_media_type": return B(415, e.error);
1455
+ case "body_too_large": return B(413, e.error);
1456
+ case "form_invalid": return B(400, e.error);
1457
+ case "cookie_invalid":
1458
+ case "cookie_missing":
1459
+ case "csrf_invalid": return B(403, e.error);
1460
+ default: return B(503, "internal_error");
1461
+ }
1462
+ }
1463
+ async function Ni(e, n, r) {
1464
+ let i = await t(n.cookie, "start");
1465
+ if (i.kind !== "present" || i.cookieHash !== r) return B(503, "internal_error");
1466
+ let a;
1467
+ try {
1468
+ a = await e.client.createAuthorizationRequest();
1469
+ } catch {
1470
+ return B(503, "provider_request_failed");
1471
+ }
1472
+ let o = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(a.material.state)), s = Array.from(new Uint8Array(o), (e) => e.toString(16).padStart(2, "0")).join(""), c = Ti(await se({ authorizationUrl: a.authorizationUrl }));
1473
+ c.headers.append("Set-Cookie", wt(i.secret)), c.headers.append("Set-Cookie", it("start"));
1474
+ let l = await e.store.startAuthBrowserTransaction({
1475
+ purpose: "signin",
1476
+ stateHash: s,
1477
+ binderHash: r,
1478
+ nonce: a.material.nonce,
1479
+ pkceVerifier: a.material.pkceVerifier
1480
+ }, e.storeConfig);
1481
+ if (l.kind === "started") return wi(c, "signin_started");
1482
+ if (l.kind === "rejected") {
1483
+ if (l.error === "transaction_conflict") return B(409, "start_conflict");
1484
+ if (l.error === "transaction_limited" || l.error === "clock_retention_blocked") return B(503, "start_limited");
1485
+ }
1486
+ return B(503, "internal_error");
1487
+ }
1488
+ async function Pi(e, t, n) {
1489
+ try {
1490
+ let r = Ci(t), i = ki(e, r, "POST");
1491
+ if (i) return await i;
1492
+ let a = await E({
1493
+ request: t,
1494
+ scope: e.scope,
1495
+ csrfKey: e.csrfKey,
1496
+ action: "signin_start",
1497
+ limiter: e.limiter,
1498
+ clientKey: n
1499
+ }), o = ji(a);
1500
+ if (o) return await o;
1501
+ let s = await C(r.cookie, e.store, e.storeConfig);
1502
+ return s === "invalid" ? await B(400, "cookie_invalid") : s === "active" ? await B(409, "signin_in_progress") : a.ok ? a.action === "signin_start" ? await Oi(e, r) ? Di(e) : await Ni(e, r, a.cookieHash) : await B(503, "internal_error") : await Mi(a);
1503
+ } catch {
1504
+ return await B(503, "internal_error");
1505
+ }
1506
+ }
1507
+ function Fi(e) {
1508
+ let t = z(e, "oidcOptions");
1509
+ if (t === void 0) return;
1510
+ let n = z(t, "fetch"), r = z(t, "timeoutSeconds");
1511
+ return Object.freeze({
1512
+ fetch: n,
1513
+ timeoutSeconds: r
1514
+ });
1515
+ }
1516
+ async function Ii(e) {
1517
+ try {
1518
+ let t = T(z(e, "config"));
1519
+ if (t.kind === "disabled") return Object.freeze({
1520
+ ok: !1,
1521
+ error: "browser_auth_disabled"
1522
+ });
1523
+ if (t.kind === "invalid") return Object.freeze({
1524
+ ok: !1,
1525
+ error: "browser_auth_config_invalid",
1526
+ field: t.field
1527
+ });
1528
+ let n = z(e, "csrfKey"), r = z(e, "store"), i = yi(r, "startAuthBrowserTransaction"), a = yi(r, "readAuthSession"), o = yi(r, "readAuthBrowserTransactionActivity"), s = Object.freeze({
1529
+ startAuthBrowserTransaction: i.bind(r),
1530
+ readAuthSession: a.bind(r),
1531
+ readAuthBrowserTransactionActivity: o.bind(r)
1532
+ }), c = z(e, "limiter");
1533
+ yi(c, "check");
1534
+ let l = Fi(e), u = Object.freeze({
1535
+ publicOrigin: t.publicOrigin,
1536
+ store: t.store
1537
+ }), d = new URL("/auth/sign-in", t.publicOrigin).href, f = new URL("/auth/account", t.publicOrigin).href, p = await Mt(t.oidc, l);
1538
+ if (!p.ok) return Object.freeze({
1539
+ ok: !1,
1540
+ error: p.error
1541
+ });
1542
+ let m = Object.freeze({
1543
+ storeConfig: t.store,
1544
+ scope: u,
1545
+ csrfKey: n,
1546
+ store: s,
1547
+ limiter: c,
1548
+ client: p.client,
1549
+ signinUrl: d,
1550
+ accountUrl: f
1551
+ });
1552
+ return Object.freeze({
1553
+ ok: !0,
1554
+ handlers: Object.freeze({
1555
+ signInPage: (e) => Ai(m, e),
1556
+ signInStart: (e, t) => Pi(m, e, t)
1557
+ })
1558
+ });
1559
+ } catch {
1560
+ return Object.freeze({
1561
+ ok: !1,
1562
+ error: "invalid_input"
1563
+ });
1564
+ }
1565
+ }
1566
+ //#endregion
1567
+ //#region src/coordinator-owner-enrollment-http.ts
1568
+ var Li = "/auth/owner/start", Ri = "/auth/owner/confirm", zi = "/v1/auth/owner-attempts";
1569
+ function Bi(e, t, n = {}) {
1570
+ let r = new Headers(n);
1571
+ return r.set("Cache-Control", "no-store"), r.set("Referrer-Policy", "no-referrer"), r.set("X-Content-Type-Options", "nosniff"), r.set("Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'; base-uri 'none'"), new Response(e, {
1572
+ status: t,
1573
+ headers: r
1574
+ });
1575
+ }
1576
+ function V(e = 400) {
1577
+ return Bi("Owner enrollment unavailable.", e);
1578
+ }
1579
+ function Vi(e) {
1580
+ return Bi(JSON.stringify(e), 200, { "Content-Type": "application/json" });
1581
+ }
1582
+ function H(e) {
1583
+ return e.replace(/[&<>"']/g, (e) => ({
1584
+ "&": "&amp;",
1585
+ "<": "&lt;",
1586
+ ">": "&gt;",
1587
+ "\"": "&quot;",
1588
+ "'": "&#39;"
1589
+ })[e] ?? "");
1590
+ }
1591
+ function Hi(e, t) {
1592
+ return `<input type="hidden" name="${H(e)}" value="${H(t)}">`;
1593
+ }
1594
+ function Ui(e, t, n) {
1595
+ return `<form method="post" action="${e}">${Object.entries(t).map(([e, t]) => Hi(e, t)).join("")}<button type="submit">${n}</button></form>`;
1596
+ }
1597
+ function Wi(e, t = []) {
1598
+ let n = new Headers({ "Content-Type": "text/html; charset=utf-8" });
1599
+ for (let e of t) n.append("Set-Cookie", e);
1600
+ return Bi(`<!doctype html><html lang="en"><meta charset="utf-8"><title>Enroll owner device</title><body>${e}</body></html>`, 200, n);
1601
+ }
1602
+ function Gi(e, t) {
1603
+ let n = new Headers({ Location: e });
1604
+ for (let e of t) n.append("Set-Cookie", e);
1605
+ return Bi(null, 303, n);
1606
+ }
1607
+ async function Ki(e, t) {
1608
+ let n = new URL(e.url), r = n.searchParams.get("attempt_id"), i = n.searchParams.get("start_code"), a = new URLSearchParams({
1609
+ csrf: "",
1610
+ attempt_id: r ?? "",
1611
+ start_code: i ?? ""
1612
+ });
1613
+ return n.searchParams.size !== 2 || !Ie(new TextEncoder().encode(a.toString()), "link_start").ok ? V() : qi(e, t, {
1614
+ attemptId: r ?? "",
1615
+ startCode: i ?? ""
1616
+ });
1617
+ }
1618
+ async function qi(e, n, r) {
1619
+ let { scope: i, key: a } = n, o = await n.transactionActivity(e.headers.get("cookie")), s = await t(e.headers.get("cookie"), "start");
1620
+ if (o === "active" || o === "invalid" || s.kind === "invalid") return V();
1621
+ let c = s.kind === "absent" ? await je("start") : null, l = s.kind === "present" ? s.secret : c?.secret;
1622
+ if (!l) return V();
1623
+ let u = await w(a, l, "start", i);
1624
+ return Wi(`<h1>Enroll owner device</h1>${r.deviceId && r.fingerprint ? `<p>Compare these details with your local device review before choosing an account.</p><dl><dt>Device ID</dt><dd>${H(r.deviceId)}</dd><dt>Key fingerprint</dt><dd>${H(r.fingerprint)}</dd></dl>` : ""}${Ui(Li, {
1625
+ csrf: u,
1626
+ attempt_id: r.attemptId,
1627
+ start_code: r.startCode
1628
+ }, "Choose account")}`, c ? [c.setCookie] : []);
1629
+ }
1630
+ function Ji(e) {
1631
+ let t = e.confirmation, n = {
1632
+ "Verified account subject": t.subject,
1633
+ Issuer: t.issuer,
1634
+ Identity: t.identityId,
1635
+ "Pending device ID": t.deviceId,
1636
+ Fingerprint: t.fingerprint,
1637
+ Groups: t.groups.join(", ")
1638
+ };
1639
+ return Wi(`<h1>Confirm owner device</h1><dl>${Object.entries(n).map(([e, t]) => `<dt>${H(e)}</dt><dd>${H(t)}</dd>`).join("")}</dl>${Ui(Ri, {
1640
+ csrf: e.csrf,
1641
+ attempt_id: t.attemptId,
1642
+ confirmation_hash: t.confirmationHash
1643
+ }, "Enroll this device")}`);
1644
+ }
1645
+ function Yi(e, t) {
1646
+ return e.headers.get("origin") === t && /^application\/x-www-form-urlencoded(?:\s*;\s*charset=utf-8)?$/i.test(e.headers.get("content-type") ?? "");
1647
+ }
1648
+ async function Xi(e, n, r, i) {
1649
+ if (!Yi(e, i) || (await t(e.headers.get("cookie"), "transaction")).kind !== "present") return V();
1650
+ let a = e.clone(), o = await l({
1651
+ body: a.body,
1652
+ contentLength: a.headers.get("content-length")
1653
+ });
1654
+ if (!o.ok) return V();
1655
+ let s = new TextDecoder("utf-8", {
1656
+ fatal: !0,
1657
+ ignoreBOM: !0
1658
+ }).decode(o.bytes);
1659
+ if (!/^[A-Za-z0-9*._%+=&-]+$/.test(s)) return V();
1660
+ let c = new URLSearchParams(s), u = c.getAll("confirmation_hash");
1661
+ if (u.length !== 1 || !/^[a-f0-9]{64}$/.test(u[0] ?? "")) return V();
1662
+ c.delete("confirmation_hash");
1663
+ let d = c.toString();
1664
+ if (!Ie(new TextEncoder().encode(d), "transaction_attempt").ok) return V();
1665
+ let f = new Headers(e.headers);
1666
+ f.delete("content-length");
1667
+ let p = new Request(e.url, {
1668
+ method: "POST",
1669
+ headers: f,
1670
+ body: d
1671
+ }), m = await n.confirm(p, r, u[0]);
1672
+ if (m.kind !== "confirmed") return V();
1673
+ let h = Zt(m.loopbackRedirect);
1674
+ if (!h.ok) return V();
1675
+ let g = new URL(h.destination);
1676
+ return g.searchParams.set("attempt_id", m.confirmation.attemptId), g.searchParams.set("completion", m.completionSecret), g.searchParams.set("confirmation", m.confirmation.confirmationHash), Gi(g.href, [it("transaction")]);
1677
+ }
1678
+ async function Zi(e, t, n) {
1679
+ if (!/^application\/json(?:\s*;\s*charset=utf-8)?$/i.test(e.headers.get("content-type") ?? "")) return V(415);
1680
+ let r = await l({
1681
+ body: e.body,
1682
+ contentLength: e.headers.get("content-length")
1683
+ });
1684
+ if (!r.ok) return V();
1685
+ let i = JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(r.bytes));
1686
+ if (!i || typeof i != "object" || Array.isArray(i)) return V();
1687
+ let a = new URL(e.url).pathname.endsWith("/finalize"), o = a ? [
1688
+ "attemptId",
1689
+ "completionSecret",
1690
+ "signature"
1691
+ ] : [
1692
+ "attemptId",
1693
+ "deviceId",
1694
+ "publicKey",
1695
+ "loopbackRedirect",
1696
+ "browserStartCode",
1697
+ "signature"
1698
+ ];
1699
+ if (Object.keys(i).length !== o.length || o.some((e) => typeof Reflect.get(i, e) != "string")) return V();
1700
+ let s = a ? await t.finalize(i) : await t.start(i, n, /^Bearer (v1\.[A-Za-z0-9._-]+)$/.exec(e.headers.get("authorization") ?? "")?.[1]);
1701
+ return s.kind === "started" || s.kind === "finalized" || s.kind === "prior_commit" ? Vi(s) : V();
1702
+ }
1703
+ function Qi(e, t, n = "/v1/auth/owner-pilot") {
1704
+ return e === n || e === t ? "GET" : e === Li ? "GET, POST" : e === Ri || e === zi || e === `${zi}/finalize` ? "POST" : null;
1705
+ }
1706
+ function $i(e, t = "private") {
1707
+ return Qi(e, "", t === "production" ? "/v1/auth/owner-config" : "/v1/auth/owner-pilot") !== null && e !== "";
1708
+ }
1709
+ async function ea(e, t, n) {
1710
+ let { api: r, scope: i, pin: a, callback: o } = n, s = new URL(e.url).pathname;
1711
+ if (s === n.pinPath) return Vi(a);
1712
+ if (s === zi || s === `${zi}/finalize`) return Zi(e, r, t);
1713
+ if (s === Li && e.method === "GET") return Ki(e, n);
1714
+ if (s === Li) {
1715
+ let n = await r.claimBrowser(e, t);
1716
+ return n.kind === "browser_claimed" ? Gi(n.authorizationUrl, n.setCookies) : V();
1717
+ }
1718
+ if (s === Ri) return Xi(e, r, t, i.publicOrigin);
1719
+ if (s === o) {
1720
+ let t = await r.verifyCallback(e);
1721
+ return t.kind === "verified" ? Ji(t) : V();
1722
+ }
1723
+ return V(404);
1724
+ }
1725
+ function ta(e, t) {
1726
+ let n = new URL(e.url);
1727
+ if (e.url.length > 8192 || n.origin !== t.pin.origin || n.username || n.password || n.hash) return V();
1728
+ let r = Qi(n.pathname, t.callback, t.pinPath);
1729
+ if (!r) return V(404);
1730
+ if (!r.split(", ").includes(e.method)) return Bi(null, 405, { Allow: r });
1731
+ if (n.search && ![Li, t.callback].includes(n.pathname) || e.method === "POST" && n.search) return V();
1732
+ let i = e.headers.get("origin");
1733
+ return i !== null && i !== t.pin.origin ? V() : null;
1734
+ }
1735
+ async function na(e, t, n) {
1736
+ try {
1737
+ return ta(e, n) || (!x(t) || t.length > 128 ? V() : dt(e, n.limiter, JSON.stringify([
1738
+ "owner-http",
1739
+ n.pin.coordinatorId,
1740
+ t
1741
+ ]), 60).allowed ? await ea(e, t, n) : V(429));
1742
+ } catch {
1743
+ return V();
1744
+ }
1745
+ }
1746
+ function ra(e, t, n, r) {
1747
+ if (r.production) {
1748
+ if (e.mode !== "production") throw Error("owner_enrollment_http_unavailable");
1749
+ return {
1750
+ ...e,
1751
+ mode: "production",
1752
+ purpose: "owner_enroll",
1753
+ csrfKey: t,
1754
+ limiter: n
1755
+ };
1756
+ }
1757
+ return {
1758
+ ...e,
1759
+ mode: "local_test",
1760
+ purpose: "owner_enroll",
1761
+ csrfKey: t,
1762
+ limiter: n,
1763
+ admissionKey: void 0
1764
+ };
1765
+ }
1766
+ async function ia(e) {
1767
+ if (e.mode !== void 0 && e.mode !== "private" && e.mode !== "local_test" && e.mode !== "production") throw Error("owner_enrollment_http_unavailable");
1768
+ let t = T(e.config);
1769
+ if (t.kind !== "enabled") throw Error("owner_enrollment_http_unavailable");
1770
+ let n = new URL(t.store.redirectUri).pathname;
1771
+ if ($i(n, "private") || $i(n, "production")) throw Error("owner_enrollment_http_unavailable");
1772
+ let i = e.mode === "production", a = i ? e.csrfKey : await ae(globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32))), o = i ? e.limiter : r({ now: e.clock }), s = ra(e, a, o, { production: i }), c = await yn(s);
1773
+ if (!c.ok) throw Error("owner_enrollment_http_unavailable");
1774
+ let l = Object.freeze({
1775
+ coordinatorId: t.store.coordinatorId,
1776
+ origin: t.publicOrigin,
1777
+ issuer: t.store.issuer,
1778
+ revision: t.store.revision
1779
+ }), u = {
1780
+ publicOrigin: l.origin,
1781
+ store: t.store
1782
+ }, d = i ? "/v1/auth/owner-config" : "/v1/auth/owner-pilot", f = new we(s.backend, s.clock);
1783
+ return aa({
1784
+ api: c.enrollment,
1785
+ scope: u,
1786
+ key: a,
1787
+ pin: l,
1788
+ callback: n,
1789
+ pinPath: d,
1790
+ limiter: o,
1791
+ transactionActivity: (e) => C(e, f, t.store)
1792
+ }, { production: i });
1793
+ }
1794
+ function aa(e, t) {
1795
+ let { pin: n, callback: r } = e, { production: i } = t;
1796
+ return {
1797
+ pin: n,
1798
+ startOwnerBound: (...t) => e.api.startOwnerBound(...t),
1799
+ matchesPath: (e) => $i(e, i ? "production" : "private"),
1800
+ handle: (t, n) => i && new URL(t.url).pathname === r ? Promise.resolve(V(404)) : na(t, n, e),
1801
+ handleCallback: (t, n) => new URL(t.url).pathname === r ? na(t, n, e) : Promise.resolve(V(404))
1802
+ };
1803
+ }
1804
+ //#endregion
1805
+ //#region src/owner-browser-admission-body.ts
1806
+ var oa = 16384, sa = [
1807
+ "attemptId",
1808
+ "deviceId",
1809
+ "publicKey",
1810
+ "loopbackRedirect",
1811
+ "browserStartCode",
1812
+ "signature"
1813
+ ];
1814
+ async function ca(e) {
1815
+ let t = e.headers.get("content-length");
1816
+ if (t !== null && (!/^[0-9]{1,10}$/.test(t) || Number(t) > 16384) || !e.body) return null;
1817
+ let n = e.body.getReader(), r = new Uint8Array(oa), i = 0;
1818
+ try {
1819
+ for (;;) {
1820
+ let e = await n.read();
1821
+ if (e.done) return r.subarray(0, i);
1822
+ if (!(e.value instanceof Uint8Array) || e.value.byteLength > r.length - i) return n.cancel().catch(() => {}), null;
1823
+ r.set(e.value, i), i += e.value.byteLength;
1824
+ }
1825
+ } catch {
1826
+ return n.cancel().catch(() => {}), null;
1827
+ } finally {
1828
+ n.releaseLock();
1829
+ }
1830
+ }
1831
+ function la(e) {
1832
+ let t = "\"(?:[^\"\\\\\0-]|\\\\(?:[\"\\\\/bfnrt]|u[0-9a-fA-F]{4}))*\"", n = `${t}\\s*:\\s*${t}`;
1833
+ if (!RegExp(`^\\s*\\{\\s*"start"\\s*:\\s*\\{\\s*${n}(?:\\s*,\\s*${n})*\\s*\\}\\s*\\}\\s*$`).test(e)) return null;
1834
+ let r = /* @__PURE__ */ new Set();
1835
+ for (let n of e.matchAll(RegExp(`(${t})\\s*:\\s*${t}`, "g"))) {
1836
+ let e = JSON.parse(n[1] ?? "null");
1837
+ if (typeof e != "string" || !sa.includes(e) || r.has(e)) return null;
1838
+ r.add(e);
1839
+ }
1840
+ return r.size === sa.length ? Object.freeze(JSON.parse(e).start) : null;
1841
+ }
1842
+ async function ua(e) {
1843
+ try {
1844
+ let t = e.headers.get("content-type") ?? "";
1845
+ if (t.length > 256 || !/^multipart\/form-data\s*;/i.test(t)) return null;
1846
+ let n = await ca(e);
1847
+ if (!n) return null;
1848
+ let r = await new Request(e.url, {
1849
+ method: "POST",
1850
+ headers: { "Content-Type": t },
1851
+ body: n
1852
+ }).formData();
1853
+ if ([...r.entries()].length !== 2 || r.getAll("csrf").length !== 1 || r.getAll("request").length !== 1) return null;
1854
+ let i = r.get("csrf"), a = r.get("request");
1855
+ if (typeof i != "string" || !(a instanceof File)) return null;
1856
+ let o = la(new TextDecoder("utf-8", {
1857
+ fatal: !0,
1858
+ ignoreBOM: !0
1859
+ }).decode(await a.arrayBuffer()));
1860
+ return o ? {
1861
+ csrf: i,
1862
+ start: o
1863
+ } : null;
1864
+ } catch {
1865
+ return null;
1866
+ }
1867
+ }
1868
+ //#endregion
1869
+ //#region src/owner-browser-admission.ts
1870
+ var da = "/auth/owner/admit";
1871
+ function fa(e, t = 400, n = []) {
1872
+ let r = new Headers({
1873
+ "Content-Type": "text/html; charset=utf-8",
1874
+ "Cache-Control": "no-store",
1875
+ "Referrer-Policy": "no-referrer",
1876
+ "X-Content-Type-Options": "nosniff",
1877
+ "Content-Security-Policy": "default-src 'none'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'"
1878
+ });
1879
+ for (let e of n) r.append("Set-Cookie", e);
1880
+ return new Response(e, {
1881
+ status: t,
1882
+ headers: r
1883
+ });
1884
+ }
1885
+ function U(e = 400) {
1886
+ return fa("Owner admission unavailable. Sign in at <a href=\"/auth/sign-in\">Sign in</a> and prepare a new device request on this computer.", e);
1887
+ }
1888
+ function pa(e) {
1889
+ return e.replace(/[&<>"']/g, (e) => ({
1890
+ "&": "&amp;",
1891
+ "<": "&lt;",
1892
+ ">": "&gt;",
1893
+ "\"": "&quot;",
1894
+ "'": "&#39;"
1895
+ })[e] ?? "");
1896
+ }
1897
+ function ma(e) {
1898
+ return fa(`<!doctype html><html lang="en"><meta charset="utf-8"><title>Authorize device request</title><body>
1899
+ <h1>Authorize device request</h1>
1900
+ <p>Upload the private capability-request.json created on this computer. Do not upload a request sent by someone else: its signature proves possession of a key, not that the key belongs to this computer.</p>
1901
+ <p>Read your local device review first. Compare the device ID and key fingerprint shown in the next step before choosing an account. This authorizes a request; it does not finish enrollment. A fresh account check and device confirmation still follow.</p>
1902
+ <form method="post" action="${da}" enctype="multipart/form-data">
1903
+ <input type="hidden" name="csrf" value="${pa(e)}">
1904
+ <label>Private device request <input type="file" name="request" accept="application/json,.json" required></label>
1905
+ <button type="submit">Authorize device request</button></form></body></html>`, 200);
1906
+ }
1907
+ function ha(e, t) {
1908
+ let n = new URL(e.url), r = e.headers.get("origin");
1909
+ return e.url.length <= 8192 && n.origin === t && !n.username && !n.password && !n.search && !n.hash && (r === null || r === t) && (e.method !== "POST" || r === t);
1910
+ }
1911
+ function ga(e) {
1912
+ let t = T(e.config);
1913
+ if (t.kind === "enabled" && new URL(t.store.redirectUri).pathname === "/auth/owner/admit") throw Error("owner_admission_callback_collision");
1914
+ let n = e.enabled && t.kind === "enabled" && ge(e.csrfKey) && hn(e.admissionKey);
1915
+ return async (r, i) => {
1916
+ if (new URL(r.url).pathname !== "/auth/owner/admit") return null;
1917
+ if (!n || t.kind !== "enabled") return U(404);
1918
+ try {
1919
+ return _a(r, i, e, t) || await ya(r, i, e, t);
1920
+ } catch {
1921
+ return U();
1922
+ }
1923
+ };
1924
+ }
1925
+ function _a(e, t, n, r) {
1926
+ return ha(e, r.publicOrigin) ? e.method !== "GET" && e.method !== "POST" ? U(405) : !x(t) || t.length > 128 ? U() : n.limiter.check(JSON.stringify([
1927
+ "owner-admit-client",
1928
+ r.store.coordinatorId,
1929
+ t
1930
+ ]), 20).allowed ? null : U(429) : U();
1931
+ }
1932
+ async function va(e, n, r, i) {
1933
+ let a = new we(n, i), o = (e) => C(e, a, r.store), s = await o(e.headers.get("cookie"));
1934
+ return s === "active" || s === "invalid" || (await t(e.headers.get("cookie"), "start")).kind === "invalid" ? null : o;
1935
+ }
1936
+ async function ya(e, n, r, i) {
1937
+ let { backend: a, csrfKey: o } = r;
1938
+ if (!await Ft(a)) return U();
1939
+ let s = await t(e.headers.get("cookie"), "session");
1940
+ if (s.kind !== "present") return U(403);
1941
+ let c = await r.readSession(s.cookieHash, i.store);
1942
+ if (!c) return U(403);
1943
+ let l = () => _t(r.clock ?? Date.now), u = {
1944
+ backend: a,
1945
+ config: i.store,
1946
+ sessionCookieHash: s.cookieHash
1947
+ }, d = await ct({
1948
+ ...u,
1949
+ time: l(),
1950
+ deviceId: "",
1951
+ fingerprint: ""
1952
+ });
1953
+ if (!d || d.identityId !== c.identityId || d.linkId !== c.linkId || d.issuer !== c.account.issuer || d.subject !== c.account.subject) return U(403);
1954
+ if (!r.limiter.check(JSON.stringify([
1955
+ "owner-admit-identity",
1956
+ d.coordinatorId,
1957
+ d.identityId
1958
+ ]), 10).allowed) return U(429);
1959
+ let f = {
1960
+ publicOrigin: i.publicOrigin,
1961
+ store: i.store
1962
+ }, p = await va(e, a, i, l);
1963
+ return p ? e.method === "GET" ? ma(await w(o, s.secret, "session", f)) : ba(e, n, r, i, {
1964
+ cookie: s,
1965
+ owner: d,
1966
+ transactionActivity: p,
1967
+ now: l
1968
+ }) : U();
1969
+ }
1970
+ async function ba(e, t, n, r, i) {
1971
+ let { cookie: a, owner: o, transactionActivity: s, now: c } = i, { backend: l, csrfKey: u, admissionKey: d } = n, f = {
1972
+ publicOrigin: r.publicOrigin,
1973
+ store: r.store
1974
+ }, p = await ua(e);
1975
+ if (!p || !await pe(u, a.secret, "session", f, p.csrf)) return U();
1976
+ let { start: m } = p, h = await $t(m.publicKey), g = await ct({
1977
+ backend: l,
1978
+ config: r.store,
1979
+ sessionCookieHash: a.cookieHash,
1980
+ time: c(),
1981
+ deviceId: m.deviceId,
1982
+ fingerprint: h
1983
+ });
1984
+ if (!g || JSON.stringify(g) !== JSON.stringify(o)) return U(403);
1985
+ let ee = {
1986
+ coordinatorId: r.store.coordinatorId,
1987
+ origin: r.publicOrigin,
1988
+ issuer: r.store.issuer,
1989
+ revision: r.store.revision
1990
+ }, te = await Jt(d, ee, m, {
1991
+ resolvedOwner: g,
1992
+ nowMs: c(),
1993
+ ttlMs: 6e4
1994
+ });
1995
+ return (await (await n.getEnrollment()).startOwnerBound(m, t, {
1996
+ admissionToken: te,
1997
+ resolvedOwner: g,
1998
+ sessionCookieHash: a.cookieHash
1999
+ })).kind === "started" ? qi(e, {
2000
+ scope: f,
2001
+ key: u,
2002
+ transactionActivity: s
2003
+ }, {
2004
+ attemptId: m.attemptId,
2005
+ startCode: m.browserStartCode,
2006
+ deviceId: m.deviceId,
2007
+ fingerprint: h
2008
+ }) : U();
2009
+ }
2010
+ //#endregion
2011
+ //#region src/coordinator-browser-auth-app.ts
2012
+ var xa = /* @__PURE__ */ new WeakMap(), Sa = /* @__PURE__ */ new WeakMap(), Ca = {
2013
+ "/auth/sign-in": ["GET", "POST"],
2014
+ "/auth/link/start": ["GET", "POST"],
2015
+ "/auth/link/confirm": ["POST"],
2016
+ "/auth/link/cancel": ["POST"],
2017
+ "/auth/link/complete": ["GET", "POST"],
2018
+ "/auth/account": ["GET"],
2019
+ "/auth/logout": ["POST"],
2020
+ "/auth/owner/start": ["GET", "POST"],
2021
+ "/auth/owner/confirm": ["POST"],
2022
+ "/auth/account/change/start": ["GET", "POST"],
2023
+ "/auth/account/change/confirm": ["POST"]
2024
+ }, wa = [
2025
+ "/auth/owner/start",
2026
+ "/auth/owner/confirm",
2027
+ "/v1/auth/owner-config",
2028
+ "/v1/auth/owner-attempts",
2029
+ "/v1/auth/owner-attempts/finalize"
2030
+ ];
2031
+ function W(e, t) {
2032
+ if (typeof e != "object" || !e || Array.isArray(e)) throw Error();
2033
+ let n = Object.getOwnPropertyDescriptor(e, t);
2034
+ if (n && !Object.hasOwn(n, "value")) throw Error();
2035
+ return n?.value;
2036
+ }
2037
+ function G(e) {
2038
+ return Object.freeze({
2039
+ kind: "invalid",
2040
+ error: "browser_auth_config_invalid",
2041
+ field: e
2042
+ });
2043
+ }
2044
+ function Ta(e) {
2045
+ if (e === void 0) return Object.freeze({});
2046
+ let t = W(e, "fetch"), n = W(e, "timeoutSeconds");
2047
+ if (t !== void 0 && typeof t != "function" || n !== void 0 && (typeof n != "number" || !Number.isFinite(n) || n < 1 || n > 30)) throw Error();
2048
+ return Object.freeze({
2049
+ fetch: t,
2050
+ timeoutSeconds: n
2051
+ });
2052
+ }
2053
+ function Ea(e) {
2054
+ try {
2055
+ let t = W(e, "config"), n = T(t);
2056
+ if (n.kind === "disabled") {
2057
+ let e = Object.freeze({ kind: "disabled" }), n = t === void 0 ? void 0 : W(t, "coordinatorId");
2058
+ return x(n) && Sa.set(e, n), e;
2059
+ }
2060
+ if (n.kind === "invalid") return G(n.field);
2061
+ let r = new URL(n.store.redirectUri).pathname;
2062
+ if (!/^\/auth\/[A-Za-z0-9._~/-]+$/.test(r) || r === "/auth/owner/admit" || Object.hasOwn(Ca, r)) return G("redirectUri");
2063
+ let i;
2064
+ try {
2065
+ i = W(e, "csrfKey");
2066
+ } catch {
2067
+ return G("csrfKey");
2068
+ }
2069
+ if (!ge(i)) return G("csrfKey");
2070
+ let a;
2071
+ try {
2072
+ a = Ta(W(e, "oidcOptions"));
2073
+ } catch {
2074
+ return G("oidcOptions");
2075
+ }
2076
+ let o = Object.freeze({
2077
+ ...n.store,
2078
+ clientId: n.oidc.clientId,
2079
+ clientSecret: n.oidc.clientSecret
2080
+ }), s = W(e, "ownerEnrollment");
2081
+ if (s !== void 0 && typeof s != "function") return G("ownerEnrollment");
2082
+ let c = Object.freeze({ kind: "enabled" });
2083
+ return xa.set(c, Object.freeze({
2084
+ settings: n,
2085
+ config: o,
2086
+ csrfKey: i,
2087
+ oidcOptions: a,
2088
+ callbackPath: r,
2089
+ ownerEnrollment: s
2090
+ })), c;
2091
+ } catch {
2092
+ return G("config");
2093
+ }
2094
+ }
2095
+ function Da(e) {
2096
+ let t = xa.get(e);
2097
+ if (t) return {
2098
+ storeConfig: t.settings.store,
2099
+ resolveAccountChanges: Va,
2100
+ register: () => {}
2101
+ };
2102
+ }
2103
+ function Oa(e, t, n, r) {
2104
+ let i = xa.get(e);
2105
+ if (!i) return null;
2106
+ let a = new URL(t.url), o = i.ownerEnrollment && a.pathname !== i.callbackPath ? Qi(a.pathname, i.callbackPath, "/v1/auth/owner-config") : null, s = Ca[a.pathname];
2107
+ return wa.includes(a.pathname) && (s = o?.split(", ") ?? []), a.pathname === i.callbackPath && (s = ["GET"]), s?.length ? s.includes(t.method) ? a.origin === i.settings.publicOrigin ? o ? ka(i, t, n, r) : Aa(i, t, n, r) : new Response("Not found.", { status: 404 }) : new Response("Method not allowed.", {
2108
+ status: 405,
2109
+ headers: { Allow: s.join(", ") }
2110
+ }) : null;
2111
+ }
2112
+ function ka(e, t, n, r) {
2113
+ let i = ta(t, {
2114
+ pin: {
2115
+ coordinatorId: e.config.coordinatorId,
2116
+ revision: e.config.revision,
2117
+ issuer: e.config.issuer,
2118
+ origin: e.settings.publicOrigin
2119
+ },
2120
+ callback: e.callbackPath,
2121
+ pinPath: "/v1/auth/owner-config"
2122
+ });
2123
+ if (i) return i;
2124
+ if (!x(r) || r.length > 128) return new Response("Invalid request.", { status: 400 });
2125
+ let a = dt(t, n, JSON.stringify([
2126
+ "owner-http",
2127
+ e.config.coordinatorId,
2128
+ r
2129
+ ]), 60, { admitSetup: !0 });
2130
+ return a.allowed ? !0 : new Response("Too many requests.", {
2131
+ status: 429,
2132
+ headers: { "Retry-After": String(a.retryAfterS) }
2133
+ });
2134
+ }
2135
+ function Aa(e, t, n, r) {
2136
+ if (t.method !== "POST") return !0;
2137
+ let i = new URL(t.url), a = "transaction_attempt";
2138
+ i.pathname === "/auth/logout" && (a = "session_logout"), i.pathname === "/auth/sign-in" && (a = "signin_start"), i.pathname === "/auth/link/start" && (a = "link_start"), i.pathname === D.start && (a = "link_start");
2139
+ let o = Nn({
2140
+ request: t,
2141
+ scope: e.settings,
2142
+ csrfKey: e.csrfKey,
2143
+ action: a,
2144
+ limiter: n,
2145
+ clientKey: r
2146
+ });
2147
+ if (!o) return !0;
2148
+ let s = 503;
2149
+ return o.error === "rate_limited" && (s = 429), o.error === "origin_rejected" && (s = 403), new Response("Authentication request rejected.", {
2150
+ status: s,
2151
+ headers: {
2152
+ "Cache-Control": "no-store",
2153
+ "Referrer-Policy": "no-referrer",
2154
+ "X-Content-Type-Options": "nosniff",
2155
+ ...o.retryAfterS ? { "Retry-After": String(o.retryAfterS) } : {}
2156
+ }
2157
+ });
2158
+ }
2159
+ function ja() {
2160
+ return new Response("Authentication unavailable. Try again.", {
2161
+ status: 503,
2162
+ headers: {
2163
+ "Content-Type": "text/plain;charset=utf-8",
2164
+ "Cache-Control": "no-store",
2165
+ "Referrer-Policy": "no-referrer",
2166
+ "X-Content-Type-Options": "nosniff"
2167
+ }
2168
+ });
2169
+ }
2170
+ function Ma(e, t, n) {
2171
+ for (let r of t) e.all(r.path, async (e) => {
2172
+ try {
2173
+ let t = e.req.raw, i;
2174
+ return t.method === "GET" && (i = r.get), t.method === "POST" && (i = r.post), i ? (await i(t, n(e) ?? "")).response : new Response("Method not allowed.", {
2175
+ status: 405,
2176
+ headers: {
2177
+ Allow: [r.get && "GET", r.post && "POST"].filter(Boolean).join(", "),
2178
+ "Cache-Control": "no-store",
2179
+ "Referrer-Policy": "no-referrer",
2180
+ "X-Content-Type-Options": "nosniff",
2181
+ "Content-Type": "text/plain;charset=utf-8"
2182
+ }
2183
+ });
2184
+ } catch {
2185
+ return ja();
2186
+ }
2187
+ });
2188
+ }
2189
+ async function Na(e, t, n) {
2190
+ if (e.kind === "disabled") return Object.freeze({
2191
+ ok: !1,
2192
+ error: "browser_auth_disabled"
2193
+ });
2194
+ if (e.kind === "invalid") return Object.freeze({
2195
+ ok: !1,
2196
+ error: "browser_auth_config_invalid"
2197
+ });
2198
+ try {
2199
+ let r = xa.get(e);
2200
+ if (!r) return Object.freeze({
2201
+ ok: !1,
2202
+ error: "browser_auth_setup_failed"
2203
+ });
2204
+ let i = await Ia(t);
2205
+ if ("error" in i) return Object.freeze({
2206
+ ok: !1,
2207
+ error: i.error
2208
+ });
2209
+ let a = r.ownerEnrollment ? Ha(t) : void 0, o = Object.freeze({
2210
+ config: r.config,
2211
+ csrfKey: r.csrfKey,
2212
+ oidcOptions: r.oidcOptions,
2213
+ store: t,
2214
+ limiter: n
2215
+ }), s = Jr({
2216
+ ...o,
2217
+ config: r.settings.store
2218
+ }), c = ii({
2219
+ ...o,
2220
+ config: r.settings.store
2221
+ });
2222
+ if (!s.ok || !c.ok) return Object.freeze({
2223
+ ok: !1,
2224
+ error: "browser_auth_setup_failed"
2225
+ });
2226
+ let l = await Ii(o), u = await vi(o), d = await za(r, n), f = await Pa(r, t, n, i.operations), p = await Lr({
2227
+ ...o,
2228
+ completeLink: s.handlers.completeLink,
2229
+ ownerCallback: d?.handleCallback,
2230
+ purposeStore: a,
2231
+ accountChangeCallback: f.callback
2232
+ }), m = await yr(o);
2233
+ if (!l.ok || !u.ok || !p.ok || !m.ok) return Object.freeze({
2234
+ ok: !1,
2235
+ error: "browser_auth_setup_failed"
2236
+ });
2237
+ let h = Object.freeze([
2238
+ {
2239
+ path: "/auth/sign-in",
2240
+ get: l.handlers.signInPage,
2241
+ post: l.handlers.signInStart
2242
+ },
2243
+ {
2244
+ path: "/auth/link/start",
2245
+ get: u.handlers.linkStartPage,
2246
+ post: u.handlers.linkStart
2247
+ },
2248
+ {
2249
+ path: r.callbackPath,
2250
+ get: p.handlers.callback
2251
+ },
2252
+ {
2253
+ path: "/auth/link/confirm",
2254
+ post: s.handlers.confirm
2255
+ },
2256
+ {
2257
+ path: "/auth/link/cancel",
2258
+ post: s.handlers.cancel
2259
+ },
2260
+ {
2261
+ path: "/auth/link/complete",
2262
+ get: c.handlers.page,
2263
+ post: c.handlers.complete
2264
+ },
2265
+ {
2266
+ path: "/auth/account",
2267
+ get: m.handlers.account
2268
+ },
2269
+ {
2270
+ path: "/auth/logout",
2271
+ post: m.handlers.logout
2272
+ },
2273
+ ...Ra(d),
2274
+ ...f.routes
2275
+ ]);
2276
+ return Fa(r.settings.store, h, { accountChanges: f.enabled });
2277
+ } catch (e) {
2278
+ return La(e);
2279
+ }
2280
+ }
2281
+ async function Pa(e, t, n, r) {
2282
+ if (!r) return {
2283
+ enabled: !1,
2284
+ routes: []
2285
+ };
2286
+ let i = await ar({
2287
+ config: e.config,
2288
+ csrfKey: e.csrfKey,
2289
+ oidcOptions: e.oidcOptions,
2290
+ limiter: n,
2291
+ operations: r,
2292
+ readers: {
2293
+ readStart: r.readStart.bind(r),
2294
+ readManagementActivity: r.readManagementActivity.bind(r),
2295
+ readBrowserBinding: r.readBrowserBinding.bind(r)
2296
+ },
2297
+ existing: {
2298
+ ...Ha(t),
2299
+ readAuthBrowserTransactionActivity: t.readAuthBrowserTransactionActivity.bind(t)
2300
+ }
2301
+ });
2302
+ if (!i.ok) throw Error();
2303
+ return {
2304
+ enabled: !0,
2305
+ routes: [{
2306
+ path: D.start,
2307
+ get: async (e) => ({ response: await i.handlers.startPage(e) }),
2308
+ post: async (e, t) => ({ response: await i.handlers.start(e, t) })
2309
+ }, {
2310
+ path: D.confirm,
2311
+ post: async (e, t) => ({ response: await i.handlers.confirm(e, t) })
2312
+ }],
2313
+ callback: async (t, n, a) => {
2314
+ let o = await r.readManagementActivity({ binderHash: a }, e.settings.store);
2315
+ return await i.handlers.matchesCallback(t) || o.kind !== "inactive" ? i.handlers.callback(t, n) : null;
2316
+ }
2317
+ };
2318
+ }
2319
+ function Fa(e, t, n) {
2320
+ return Object.freeze({
2321
+ ok: !0,
2322
+ auth: Object.freeze({
2323
+ storeConfig: e,
2324
+ resolveAccountChanges: n.accountChanges ? Va : void 0,
2325
+ register: (e, n) => Ma(e, t, n)
2326
+ })
2327
+ });
2328
+ }
2329
+ async function Ia(e) {
2330
+ try {
2331
+ let t = Ba(e, "readAccountChangeCapability");
2332
+ return t ? { operations: await t() } : (await jt(e), { operations: await Va(e) });
2333
+ } catch (e) {
2334
+ return e instanceof zt ? { error: Wt } : { error: "browser_auth_store_unavailable" };
2335
+ }
2336
+ }
2337
+ function La(e) {
2338
+ return e instanceof zt ? Object.freeze({
2339
+ ok: !1,
2340
+ error: Wt
2341
+ }) : Object.freeze({
2342
+ ok: !1,
2343
+ error: "browser_auth_setup_failed"
2344
+ });
2345
+ }
2346
+ function Ra(e) {
2347
+ if (!e) return [];
2348
+ let t = async (t, n) => ({ response: await e.handle(t, n) ?? ja() });
2349
+ return wa.map((e) => ({
2350
+ path: e,
2351
+ get: t,
2352
+ post: t
2353
+ }));
2354
+ }
2355
+ async function za(e, t) {
2356
+ if (!e.ownerEnrollment) return;
2357
+ let n = await e.ownerEnrollment(Object.freeze({
2358
+ config: e.config,
2359
+ csrfKey: e.csrfKey,
2360
+ oidcOptions: e.oidcOptions,
2361
+ limiter: t
2362
+ })), r = W(n, "handle"), i = W(n, "handleCallback");
2363
+ if (typeof r != "function" || typeof i != "function") throw Error();
2364
+ return Object.freeze({
2365
+ handle: (...e) => Reflect.apply(r, n, e),
2366
+ handleCallback: (...e) => Reflect.apply(i, n, e)
2367
+ });
2368
+ }
2369
+ function Ba(e, t) {
2370
+ if (!e || typeof e != "object") throw Error();
2371
+ let n = e, r = /* @__PURE__ */ new Set();
2372
+ for (; n;) {
2373
+ if (r.has(n)) throw Error();
2374
+ r.add(n);
2375
+ let i = Object.getOwnPropertyDescriptor(n, t);
2376
+ if (i) {
2377
+ if (!Object.hasOwn(i, "value") || typeof i.value != "function") throw Error();
2378
+ let t = i.value;
2379
+ return (...n) => Reflect.apply(t, e, n);
2380
+ }
2381
+ n = Object.getPrototypeOf(n);
2382
+ }
2383
+ }
2384
+ async function Va(e) {
2385
+ let t = Ba(e, "readAccountChangeCapability");
2386
+ if (t) return await t();
2387
+ let n = Ba(e, "readAccountConnectionSchemaState"), r = Ba(e, "getAccountChanges");
2388
+ if (!n && !r) return null;
2389
+ if (!n || !r) throw Error();
2390
+ let i = await n();
2391
+ if (i === "v2") return null;
2392
+ if (i !== "ready") throw new zt();
2393
+ return await r();
2394
+ }
2395
+ function Ha(e) {
2396
+ let t = e, n = /* @__PURE__ */ new Set();
2397
+ for (; t !== null;) {
2398
+ if (n.has(t)) throw Error();
2399
+ n.add(t);
2400
+ let r = Object.getOwnPropertyDescriptor(t, "readAuthBrowserTransactionPurpose");
2401
+ if (r) {
2402
+ if (!Object.hasOwn(r, "value") || typeof r.value != "function") throw Error();
2403
+ let t = r.value;
2404
+ return Object.freeze({ readAuthBrowserTransactionPurpose: (...n) => Reflect.apply(t, e, n) });
2405
+ }
2406
+ t = Object.getPrototypeOf(t);
2407
+ }
2408
+ throw Error();
2409
+ }
2410
+ async function Ua(e, t, n = {}) {
2411
+ if (e.kind === "disabled") return Wa(e, t);
2412
+ let r = "options";
2413
+ try {
2414
+ let i = xa.get(e), a = n.maxBatches ?? 4;
2415
+ if (e.kind !== "enabled" || !i || !Number.isSafeInteger(a) || a < 1 || a > 8) throw Error();
2416
+ let o = i.settings.store, s = await Va(t), c = Object.freeze({ coordinatorId: o.coordinatorId }), l = [
2417
+ {
2418
+ step: "link_attempts",
2419
+ run: () => t.maintainAuthLinkAttempts(o, { limit: 32 })
2420
+ },
2421
+ {
2422
+ step: "browser_retirement",
2423
+ run: () => t.retireAuthBrowserTransactions(o, { limit: 32 })
2424
+ },
2425
+ {
2426
+ step: "browser_expiry",
2427
+ run: () => t.maintainAuthBrowserTransactions(c, { limit: 32 })
2428
+ },
2429
+ {
2430
+ step: "signin_transactions",
2431
+ run: () => t.purgeAuthSigninBrowserTransactions(c, { limit: 256 })
2432
+ },
2433
+ {
2434
+ step: "signin_sessions",
2435
+ run: () => t.purgeAuthGuardedSigninSessions(c, { limit: 256 })
2436
+ },
2437
+ {
2438
+ step: "signin_receipts",
2439
+ run: () => t.purgeAuthGuardedSigninReceipts(c, { limit: 256 })
2440
+ },
2441
+ ...s ? [{
2442
+ step: "account_changes",
2443
+ run: async () => {
2444
+ let e = await s.maintainExpired(o.coordinatorId, 32);
2445
+ return {
2446
+ kind: "maintained",
2447
+ processedCount: e,
2448
+ more: e === 32
2449
+ };
2450
+ }
2451
+ }] : []
2452
+ ], u = 0, d = !1;
2453
+ for (let e of l) {
2454
+ r = e.step;
2455
+ let t = await Ga(e.run, a);
2456
+ if (u += t.processedCount, !Number.isSafeInteger(u)) throw Error();
2457
+ d ||= t.more;
2458
+ }
2459
+ return Object.freeze({
2460
+ kind: "maintained",
2461
+ processedCount: u,
2462
+ more: d
2463
+ });
2464
+ } catch {
2465
+ return Object.freeze({
2466
+ kind: "failed",
2467
+ error: "maintenance_failed",
2468
+ step: r
2469
+ });
2470
+ }
2471
+ }
2472
+ async function Wa(e, t) {
2473
+ let n = Sa.get(e);
2474
+ if (!n) return Object.freeze({ kind: "disabled" });
2475
+ try {
2476
+ let e = await Va(t);
2477
+ if (!e) return Object.freeze({ kind: "disabled" });
2478
+ let r = await e.maintainExpired(n, 32);
2479
+ return Object.freeze({
2480
+ kind: "maintained",
2481
+ processedCount: r,
2482
+ more: r === 32
2483
+ });
2484
+ } catch {
2485
+ return Object.freeze({
2486
+ kind: "failed",
2487
+ error: "maintenance_failed",
2488
+ step: "account_changes"
2489
+ });
2490
+ }
2491
+ }
2492
+ async function Ga(e, t) {
2493
+ let n = 0;
2494
+ for (let r = 0; r < t; r++) {
2495
+ let t = await e();
2496
+ if (t.kind === "rejected" || typeof t.processedCount != "number" || !Number.isSafeInteger(t.processedCount) || t.processedCount < 0 || typeof t.more != "boolean" || (n += t.processedCount, !Number.isSafeInteger(n))) throw Error();
2497
+ if (!t.more) return {
2498
+ processedCount: n,
2499
+ more: !1
2500
+ };
2501
+ }
2502
+ return {
2503
+ processedCount: n,
2504
+ more: !0
2505
+ };
2506
+ }
2507
+ //#endregion
2508
+ //#region src/coordinator-owner-enrollment-qualification.ts
2509
+ var K = {
2510
+ coordinator_id: "l.coordinator_id",
2511
+ link_id: "l.link_id",
2512
+ device_claim_id: "d.claim_id",
2513
+ identity_id: "l.identity_id",
2514
+ source_group_id: "a.group_id",
2515
+ device_id: "a.device_id",
2516
+ public_key: "a.public_key",
2517
+ fingerprint: "a.fingerprint",
2518
+ key_id: "d.key_id",
2519
+ controller_attestation_id: "a.attestation_id",
2520
+ controller_attestation_revision: "a.revision",
2521
+ controller_attestation_created_at: "a.created_at",
2522
+ review_receipt_id: "a.review_receipt_id",
2523
+ evidence_digest: "a.evidence_digest",
2524
+ enrollment_identity_id: "a.enrollment_identity_id",
2525
+ link_attempt_id: "l.attempt_id",
2526
+ link_auth_config_revision: "l.auth_config_revision",
2527
+ link_created_at_ms: "l.created_at_ms"
2528
+ }, Ka = `json_array(${[
2529
+ ...Object.values(K),
2530
+ "l.issuer",
2531
+ "l.subject",
2532
+ "l.authority_kind",
2533
+ "l.controller_attestation_id",
2534
+ "l.signin_floor",
2535
+ "l.revoked_at_ms",
2536
+ "d.identity_id",
2537
+ "d.group_id",
2538
+ "d.device_id",
2539
+ "d.public_key",
2540
+ "d.fingerprint",
2541
+ "d.attempt_id",
2542
+ "d.issuer",
2543
+ "d.auth_config_revision",
2544
+ "d.created_at_ms",
2545
+ "e.identity_id",
2546
+ "e.public_key",
2547
+ "e.fingerprint",
2548
+ "e.enabled",
2549
+ "e.created_at",
2550
+ "e.display_name"
2551
+ ].join(",")})`, qa = `FROM coordinator_auth_controller_attestations a
2552
+ JOIN enrolled_devices e ON e.group_id=a.group_id AND e.device_id=a.device_id
2553
+ JOIN groups g ON g.group_id=e.group_id
2554
+ JOIN coordinator_auth_account_links l ON l.coordinator_id=a.coordinator_id AND l.identity_id=a.identity_id
2555
+ JOIN coordinator_auth_device_claims d ON d.coordinator_id=l.coordinator_id AND d.claim_id=l.device_claim_id
2556
+ WHERE (a.coordinator_id=? AND a.attestation_id=? AND l.issuer=?)
2557
+ AND (a.revoked_at IS NULL AND a.revision=1 AND length(a.review_receipt_id)>0 AND length(a.evidence_digest)=64)
2558
+ AND (e.public_key=a.public_key AND e.fingerprint=a.fingerprint AND e.enabled=1 AND g.archived_at IS NULL)
2559
+ AND (e.identity_id IS NULL OR e.identity_id=a.identity_id)
2560
+ AND e.identity_id IS a.enrollment_identity_id
2561
+ AND (a.enrollment_identity_id IS NULL OR a.enrollment_identity_id=a.identity_id)
2562
+ AND (d.identity_id=a.identity_id AND d.group_id=a.group_id AND d.device_id=a.device_id
2563
+ AND d.public_key=a.public_key AND d.fingerprint=a.fingerprint)
2564
+ AND (${Qt({
2565
+ link: "l",
2566
+ connections: !0
2567
+ })})
2568
+ AND (${ze({
2569
+ link: "l",
2570
+ connections: !0
2571
+ })})`, Ja = Object.entries(K).map(([e, t]) => `${t} AS ${e}`).join(","), Ya = cn.map((e, t) => qe(e.replace(/^(?:\s|--[^\n]*\n)*/u, "").replace(/;\s*$/u, ""), t === 0 ? { auxiliaryObjects: 5 } : void 0).matches).join(" AND ");
2572
+ async function Xa(e, t) {
2573
+ let n = new TextEncoder().encode(JSON.stringify([
2574
+ "codemem.owner-enrollment-qualification.preview.v1",
2575
+ t.enabled,
2576
+ t.coordinatorId,
2577
+ t.issuer,
2578
+ t.revision,
2579
+ e.snapshot
2580
+ ])), r = await crypto.subtle.digest("SHA-256", n);
2581
+ return Array.from(new Uint8Array(r), (e) => e.toString(16).padStart(2, "0")).join("");
2582
+ }
2583
+ function Za(e, t) {
2584
+ return {
2585
+ kind: "ready",
2586
+ digest: t,
2587
+ attestationId: e.controller_attestation_id,
2588
+ reviewReceiptId: e.review_receipt_id,
2589
+ linkId: e.link_id,
2590
+ claimId: e.device_claim_id,
2591
+ identityId: e.identity_id,
2592
+ groupId: e.source_group_id,
2593
+ deviceId: e.device_id,
2594
+ fingerprint: e.fingerprint
2595
+ };
2596
+ }
2597
+ var q = () => ({
2598
+ kind: "rejected",
2599
+ error: "unavailable"
2600
+ }), Qa = class {
2601
+ backend;
2602
+ clock;
2603
+ config;
2604
+ constructor(e, t, n = Date.now) {
2605
+ this.backend = e, this.clock = n, this.config = De(t);
2606
+ }
2607
+ async schemaReady() {
2608
+ return await Ce(this.backend) === "ready" && (await this.backend.first({
2609
+ sql: `SELECT (${Ya}) AS ready`,
2610
+ values: []
2611
+ }))?.ready === 1;
2612
+ }
2613
+ async prepare(e, t) {
2614
+ let n = this.config;
2615
+ if (!n?.enabled || !await this.schemaReady()) return null;
2616
+ let r = await this.backend.first({
2617
+ sql: `SELECT ${Ja}, ${Ka} AS snapshot ${qa}`,
2618
+ values: [
2619
+ n.coordinatorId,
2620
+ e,
2621
+ n.issuer
2622
+ ]
2623
+ });
2624
+ if (!r || !Kt(r.evidence_digest)) return null;
2625
+ let i = await f(r.public_key);
2626
+ if (!i || i !== r.key_id) return null;
2627
+ let a = {
2628
+ source: r,
2629
+ guard: await Mn(this.backend, r.identity_id, {
2630
+ groupId: r.source_group_id,
2631
+ deviceId: r.device_id,
2632
+ publicKey: r.public_key,
2633
+ fingerprint: r.fingerprint
2634
+ }, n, t),
2635
+ digest: await Xa(r, n)
2636
+ };
2637
+ return await this.live(a) ? a : null;
2638
+ }
2639
+ liveStatement(e) {
2640
+ let t = this.config;
2641
+ return t ? {
2642
+ sql: `${qa} AND (${Ka}=?) AND (${e.guard.sql})
2643
+ AND NOT EXISTS (SELECT 1 FROM coordinator_device_revocations r
2644
+ WHERE (r.subject_kind='device_id' AND r.subject_value=a.device_id)
2645
+ OR (r.subject_kind='ed25519_key' AND r.subject_value=d.key_id))`,
2646
+ values: [
2647
+ t.coordinatorId,
2648
+ e.source.controller_attestation_id,
2649
+ t.issuer,
2650
+ e.source.snapshot,
2651
+ ...e.guard.values
2652
+ ]
2653
+ } : {
2654
+ sql: "SELECT 1 WHERE 0",
2655
+ values: []
2656
+ };
2657
+ }
2658
+ async live(e) {
2659
+ let t = this.liveStatement(e);
2660
+ return !!await this.backend.first({
2661
+ sql: `SELECT 1 ${t.sql}`,
2662
+ values: t.values
2663
+ });
2664
+ }
2665
+ async preview(e) {
2666
+ let t = h(e, ["attestationId"]);
2667
+ if (!x(t?.attestationId)) return {
2668
+ kind: "rejected",
2669
+ error: "invalid_input"
2670
+ };
2671
+ try {
2672
+ let e = await this.prepare(t.attestationId, _t(this.clock));
2673
+ if (!e) return q();
2674
+ let n = await this.existing(e);
2675
+ return n && !this.matches(n, e.source) ? {
2676
+ kind: "rejected",
2677
+ error: "qualification_conflict"
2678
+ } : Za(e.source, e.digest);
2679
+ } catch {
2680
+ return q();
2681
+ }
2682
+ }
2683
+ async issue(e) {
2684
+ let t = h(e, ["attestationId", "expectedDigest"]);
2685
+ if (!x(t?.attestationId) || !Kt(t?.expectedDigest)) return {
2686
+ kind: "rejected",
2687
+ error: "invalid_input"
2688
+ };
2689
+ let n = !1;
2690
+ try {
2691
+ let e = _t(this.clock), r = await this.prepare(t.attestationId, e);
2692
+ if (!r) return q();
2693
+ if (r.digest !== t.expectedDigest) return {
2694
+ kind: "rejected",
2695
+ error: "preview_changed"
2696
+ };
2697
+ let i = crypto.randomUUID(), a = this.liveStatement(r), o = {
2698
+ sql: `INSERT INTO coordinator_owner_enrollment_qualifications
2699
+ (qualification_id,${Object.keys(K).join(",")},created_at_ms,revoked_at_ms)
2700
+ SELECT ?,${Object.values(K).join(",")},?,NULL ${a.sql}
2701
+ AND l.created_at_ms<=? AND NOT EXISTS (SELECT 1 FROM coordinator_owner_enrollment_qualifications q
2702
+ WHERE q.coordinator_id=l.coordinator_id AND q.link_id=l.link_id)`,
2703
+ values: [
2704
+ i,
2705
+ e,
2706
+ ...a.values,
2707
+ e
2708
+ ]
2709
+ };
2710
+ return n = !0, await this.backend.run(o) === 1 ? {
2711
+ kind: "created",
2712
+ qualificationId: i
2713
+ } : await this.retry(r);
2714
+ } catch {
2715
+ return n ? { kind: "outcome_unknown" } : q();
2716
+ }
2717
+ }
2718
+ existing(e) {
2719
+ return this.backend.first({
2720
+ sql: "SELECT * FROM coordinator_owner_enrollment_qualifications WHERE coordinator_id=? AND link_id=?",
2721
+ values: [e.source.coordinator_id, e.source.link_id]
2722
+ });
2723
+ }
2724
+ async revoke(e) {
2725
+ let t = h(e, ["qualificationId", "linkId"]);
2726
+ if (!x(t?.qualificationId) || !x(t?.linkId)) return {
2727
+ kind: "rejected",
2728
+ error: "invalid_input"
2729
+ };
2730
+ let n = !1;
2731
+ try {
2732
+ let e = this.config, r = _t(this.clock);
2733
+ if (!e?.enabled || !await this.schemaReady()) return q();
2734
+ let i = [
2735
+ e.coordinatorId,
2736
+ t.qualificationId,
2737
+ t.linkId
2738
+ ], a = {
2739
+ sql: "UPDATE coordinator_owner_enrollment_qualifications SET revoked_at_ms=MAX(?,created_at_ms)\n WHERE coordinator_id=? AND qualification_id=? AND link_id=? AND revoked_at_ms IS NULL",
2740
+ values: [r, ...i]
2741
+ };
2742
+ n = !0, await this.backend.run(a);
2743
+ let o = await this.backend.first({
2744
+ sql: "SELECT qualification_id FROM coordinator_owner_enrollment_qualifications\n WHERE coordinator_id=? AND qualification_id=? AND link_id=? AND revoked_at_ms IS NOT NULL",
2745
+ values: i
2746
+ });
2747
+ return o ? {
2748
+ kind: "revoked",
2749
+ qualificationId: o.qualification_id
2750
+ } : q();
2751
+ } catch {
2752
+ return n ? { kind: "outcome_unknown" } : q();
2753
+ }
2754
+ }
2755
+ matches(e, t) {
2756
+ return e.revoked_at_ms === null && Object.keys(K).every((n) => {
2757
+ let r = n;
2758
+ return e[r] === t[r];
2759
+ });
2760
+ }
2761
+ async retry(e) {
2762
+ let t = this.liveStatement(e), n = await this.backend.first({
2763
+ sql: `WITH qualification_live_source AS MATERIALIZED (
2764
+ SELECT ${Ja} ${t.sql})
2765
+ SELECT q.* FROM coordinator_owner_enrollment_qualifications q
2766
+ JOIN qualification_live_source source ON ${Object.keys(K).map((e) => `q.${e} IS source.${e}`).join(" AND ")}
2767
+ WHERE q.revoked_at_ms IS NULL`,
2768
+ values: t.values
2769
+ });
2770
+ return n ? {
2771
+ kind: "existing",
2772
+ qualificationId: n.qualification_id
2773
+ } : {
2774
+ kind: "rejected",
2775
+ error: "qualification_conflict"
2776
+ };
2777
+ }
2778
+ }, $a = "CASE WHEN substr(sql, 1, 52) = 'CREATE TABLE \"coordinator_owner_enrollment_attempts\"'\n THEN 'CREATE TABLE coordinator_owner_enrollment_attempts' || substr(sql, 53) ELSE sql END", eo = Xe.replace(/^--[^\n]*$/gm, "").trim().split(/\n(?=CREATE )/u).map((e, t) => {
2779
+ let n = qe(e.trim().replace(/;$/u, ""), t === 0 ? { auxiliaryObjects: 13 } : void 0);
2780
+ return t === 0 ? {
2781
+ ...n,
2782
+ matches: n.matches.replace(/\bsql\b/u, $a)
2783
+ } : n;
2784
+ }).map((e) => e.matches).join(" AND ");
2785
+ async function to(e, t) {
2786
+ if (!e || !t || e.length > 8192) return !1;
2787
+ let n = (e) => crypto.subtle.digest("SHA-256", new TextEncoder().encode(e)), [r, i] = await Promise.all([n(t), n(e)]), a = await crypto.subtle.importKey("raw", r, {
2788
+ name: "HMAC",
2789
+ hash: "SHA-256"
2790
+ }, !1, ["sign", "verify"]), o = await crypto.subtle.sign("HMAC", a, r);
2791
+ return crypto.subtle.verify("HMAC", a, o, i);
2792
+ }
2793
+ function no(e) {
2794
+ return !e || Object.keys(e).some((e) => !["attestation_id", "confirm_evidence_digest"].includes(e)) || !p(e.attestation_id) || Object.hasOwn(e, "confirm_evidence_digest") && !Kt(e.confirm_evidence_digest) ? null : {
2795
+ attestationId: e.attestation_id,
2796
+ expectedDigest: e.confirm_evidence_digest
2797
+ };
2798
+ }
2799
+ async function ro(e, t) {
2800
+ let n = await to(e.req.header("X-Codemem-Coordinator-Admin"), t.adminSecret());
2801
+ return t.rateLimitedResponse(e, `owner-qualification:${n ? "admin" : "anonymous"}`, { authenticated: n }) || (n ? null : e.json({ error: "unauthorized" }, 401));
2802
+ }
2803
+ async function io(e, t, n) {
2804
+ if (n === "unavailable") try {
2805
+ if (!await t.schemaReady()) return e.json({ error: "qualification_unavailable" }, 503);
2806
+ } catch {
2807
+ return e.json({ error: "qualification_unavailable" }, 503);
2808
+ }
2809
+ return e.json({ error: n }, 409);
2810
+ }
2811
+ async function ao(e, t, n, r) {
2812
+ let i = await t.preview({ attestationId: n });
2813
+ return i.kind === "rejected" ? io(e, t, i.error) : e.json({
2814
+ state: "ready",
2815
+ coordinator_id: r,
2816
+ evidence_digest: i.digest,
2817
+ attestation_id: i.attestationId,
2818
+ review_receipt_id: i.reviewReceiptId,
2819
+ link_id: i.linkId,
2820
+ claim_id: i.claimId,
2821
+ identity_id: i.identityId,
2822
+ group_id: i.groupId,
2823
+ device_id: i.deviceId,
2824
+ fingerprint: i.fingerprint
2825
+ });
2826
+ }
2827
+ async function oo(e, t, n, r) {
2828
+ try {
2829
+ let i = await t.issue(n);
2830
+ return i.kind === "outcome_unknown" ? e.json({ error: "qualification_outcome_unknown" }, 503) : i.kind === "rejected" ? await io(e, t, i.error) : e.json({
2831
+ state: i.kind,
2832
+ qualification_id: i.qualificationId,
2833
+ attestation_id: n.attestationId,
2834
+ coordinator_id: r,
2835
+ evidence_digest: n.expectedDigest
2836
+ }, i.kind === "created" ? 201 : 200);
2837
+ } catch {
2838
+ return e.json({ error: "qualification_outcome_unknown" }, 503);
2839
+ }
2840
+ }
2841
+ async function so(e, t) {
2842
+ return (await e.first({
2843
+ sql: `SELECT (${eo}) AS ready`,
2844
+ values: []
2845
+ }))?.ready === 1 && await t.schemaReady();
2846
+ }
2847
+ function co(e) {
2848
+ let t = De(e.config), n = { ...e }, r = n.backend, i = t && r ? new Qa(r, t) : null;
2849
+ return async (e) => {
2850
+ e.header("Cache-Control", "no-store"), e.header("Referrer-Policy", "no-referrer"), e.header("X-Content-Type-Options", "nosniff");
2851
+ try {
2852
+ let a = await ro(e, n);
2853
+ if (a) return a;
2854
+ if (!t?.enabled || !i || !r) return e.json({ error: "qualification_unavailable" }, 503);
2855
+ let o = await n.readRequestBytes(e, 4096);
2856
+ if (!o) return e.json({ error: "body_too_large" }, 413);
2857
+ let s = no(n.parseJsonObject(o));
2858
+ return s ? await so(r, i) ? s.expectedDigest === void 0 ? await ao(e, i, s.attestationId, t.coordinatorId) : await oo(e, i, {
2859
+ attestationId: s.attestationId,
2860
+ expectedDigest: s.expectedDigest
2861
+ }, t.coordinatorId) : e.json({ error: "qualification_unavailable" }, 503) : e.json({ error: "qualification_invalid_input" }, 400);
2862
+ } catch {
2863
+ return e.json({ error: "qualification_unavailable" }, 503);
2864
+ }
2865
+ };
2866
+ }
2867
+ //#endregion
2868
+ //#region src/coordinator-owner-qualification-http.ts
2869
+ var lo = "/v1/admin/owner-qualifications", uo = 5e3;
2870
+ function fo(e, t) {
2871
+ let n = e.req.raw, r = new URL(n.url);
2872
+ if (n.method !== "POST") return e.json({ error: "method_not_allowed" }, 405);
2873
+ if (r.origin !== t || r.protocol !== "https:" || r.search || r.hash || r.username || r.password || n.headers.has("Origin") || n.headers.has("Transfer-Encoding")) return e.json({ error: "qualification_invalid_input" }, 400);
2874
+ if (!/^application\/json(?:\s*;\s*charset=utf-8)?$/i.test(n.headers.get("Content-Type") ?? "") || n.headers.has("Content-Encoding")) return e.json({ error: "invalid_content_type" }, 415);
2875
+ let i = n.headers.get("Content-Length");
2876
+ return i !== null && !/^[0-9]{1,10}$/.test(i) ? e.json({ error: "qualification_invalid_input" }, 400) : i !== null && Number(i) > 4096 ? e.json({ error: "body_too_large" }, 413) : null;
2877
+ }
2878
+ async function po(e, t) {
2879
+ let n = e.req.raw;
2880
+ if (n.signal.aborted || !n.body) return null;
2881
+ let r = n.body.getReader(), i, a = () => {}, o = new Promise((e) => {
2882
+ a = () => e(null), i = setTimeout(a, uo), n.signal.addEventListener("abort", a, { once: !0 }), n.signal.aborted && a();
2883
+ });
2884
+ try {
2885
+ return await mo(n, r, o, t);
2886
+ } catch {
2887
+ return null;
2888
+ } finally {
2889
+ clearTimeout(i), n.signal.removeEventListener("abort", a), r.cancel().catch(() => void 0), r.releaseLock();
2890
+ }
2891
+ }
2892
+ async function mo(e, t, n, r) {
2893
+ let i = new Uint8Array(r), a = 0;
2894
+ for (;;) {
2895
+ let o = await Promise.race([t.read(), n]);
2896
+ if (!o || e.signal.aborted) return null;
2897
+ if (o.done) {
2898
+ let t = e.headers.get("Content-Length");
2899
+ return t !== null && Number(t) !== a ? null : i.subarray(0, a);
2900
+ }
2901
+ if (!(o.value instanceof Uint8Array) || o.value.byteLength > r - a) return null;
2902
+ i.set(o.value, a), a += o.value.byteLength;
2903
+ }
2904
+ }
2905
+ function ho(e) {
2906
+ try {
2907
+ let t = JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(e));
2908
+ return t && typeof t == "object" && !Array.isArray(t) ? t : null;
2909
+ } catch {
2910
+ return null;
2911
+ }
2912
+ }
2913
+ function go(e) {
2914
+ let t = { ...e }, n = co({
2915
+ config: t.config,
2916
+ backend: t.backend,
2917
+ adminSecret: () => t.adminSecret,
2918
+ readRequestBytes: po,
2919
+ parseJsonObject: ho,
2920
+ rateLimitedResponse: (e, n, { authenticated: r }) => {
2921
+ let i = t.limiter.check(n, r ? 20 : 60);
2922
+ return i.allowed ? !r || !t.config || !t.backend ? null : fo(e, t.origin) : (e.header("Retry-After", String(i.retryAfterS)), e.json({ error: "rate_limited" }, 429));
2923
+ }
2924
+ }), r = new he();
2925
+ return r.all(lo, n), { fetch: (e) => r.fetch(e) };
2926
+ }
2927
+ //#endregion
2
2928
  //#region src/d1-coordinator-store.ts
3
- function F(e) {
2929
+ function J(e) {
4
2930
  if (e == null) throw Error("expected row");
5
2931
  return e;
6
2932
  }
7
- function I(e) {
8
- let { presence_capabilities_json: t, presence_expires_at: n, ...r } = F(e);
2933
+ function _o(e) {
2934
+ let { presence_capabilities_json: t, presence_expires_at: n, ...r } = J(e);
9
2935
  if (typeof n != "string" || typeof t != "string") return r;
10
2936
  try {
11
2937
  let e = JSON.parse(t);
@@ -23,10 +2949,10 @@ function I(e) {
23
2949
  return r;
24
2950
  }
25
2951
  }
26
- function L() {
2952
+ function Y() {
27
2953
  return (/* @__PURE__ */ new Date()).toISOString();
28
2954
  }
29
- function R(e, t) {
2955
+ function vo(e, t) {
30
2956
  return e <= t ? {
31
2957
  low: e,
32
2958
  high: t
@@ -35,583 +2961,1375 @@ function R(e, t) {
35
2961
  high: e
36
2962
  };
37
2963
  }
38
- function z(e) {
2964
+ function yo(e) {
39
2965
  return e instanceof Error && /unique|constraint/i.test(e.message);
40
2966
  }
41
- function B(e) {
2967
+ function X(e) {
42
2968
  let t = new Uint8Array(e);
43
2969
  globalThis.crypto.getRandomValues(t);
44
2970
  let n = [];
45
2971
  for (let e of t) n.push("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"[e % 64] ?? "A");
46
2972
  return n.join("");
47
2973
  }
48
- async function V(e) {
2974
+ async function bo(e) {
49
2975
  let t = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(e));
50
2976
  return Array.from(new Uint8Array(t), (e) => e.toString(16).padStart(2, "0")).join("");
51
2977
  }
52
- var H = "invite_id, group_id, token, policy, expires_at, created_at, created_by,\n team_name_snapshot, revoked_at, operation_id, reviewed_project_set_digest, token_digest,\n inviter_actor_id, inviter_display_name, inviter_device_id, pending_person_id,\n project_summaries_json, project_intent_json, consumed_at, bound_device_id, bound_public_key, bound_fingerprint,\n recipient_actor_id, recipient_display_name, recipient_device_display_name, trust_state,\n bootstrap_grant_id, invite_kind, policy_team_id, target_identity_id, assigned_identity_id,\n reviewed_preview_digest, reviewed_intent_json", U = "group_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at", W = "enrolled_devices.group_id, enrolled_devices.device_id,\n enrolled_devices.public_key, enrolled_devices.fingerprint, enrolled_devices.identity_id,\n enrolled_devices.display_name, enrolled_devices.enabled, enrolled_devices.created_at,\n presence_records.expires_at AS presence_expires_at,\n presence_records.capabilities_json AS presence_capabilities_json";
53
- function G(e, t) {
2978
+ var xo = "invite_id, group_id, token, policy, expires_at, created_at, created_by,\n team_name_snapshot, revoked_at, operation_id, reviewed_project_set_digest, token_digest,\n inviter_actor_id, inviter_display_name, inviter_device_id, pending_person_id,\n project_summaries_json, project_intent_json, consumed_at, bound_device_id, bound_public_key, bound_fingerprint,\n recipient_actor_id, recipient_display_name, recipient_device_display_name, trust_state,\n bootstrap_grant_id, invite_kind, policy_team_id, target_identity_id, assigned_identity_id,\n reviewed_preview_digest, reviewed_intent_json", So = "group_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at", Co = "enrolled_devices.group_id, enrolled_devices.device_id,\n enrolled_devices.public_key, enrolled_devices.fingerprint, enrolled_devices.identity_id,\n enrolled_devices.display_name, enrolled_devices.enabled, enrolled_devices.created_at,\n presence_records.expires_at AS presence_expires_at,\n presence_records.capabilities_json AS presence_capabilities_json";
2979
+ function wo(e, t) {
54
2980
  return e.prepare("INSERT INTO coordinator_scope_membership_audit_log(\n effect_id, action, scope_id, device_id, role, status, membership_epoch,\n previous_role, previous_status, previous_membership_epoch,\n coordinator_id, group_id, actor_type, actor_id, manifest_hash, created_at\n )\n SELECT receipt.effect_id, ?, membership.scope_id, membership.device_id, membership.role, membership.status,\n membership.membership_epoch, ?, ?, ?, membership.coordinator_id, membership.group_id,\n ?, ?, membership.manifest_hash, ?\n FROM (SELECT 1 WHERE changes() > 0) AS required\n JOIN coordinator_scope_membership_effect_receipts AS receipt\n ON receipt.effect_id = ? AND receipt.action = ? AND receipt.request_json = ?\n AND receipt.outcome_applied = 1\n LEFT JOIN coordinator_scope_memberships AS membership\n ON membership.scope_id = ?\n AND membership.device_id = ?\n AND membership.status = ?\n AND membership.membership_epoch = ?\n AND membership.updated_at = ?").bind(t.action, t.previous?.role ?? null, t.previous?.status ?? null, t.previous?.membership_epoch ?? null, t.actorType, t.actorId, t.createdAt, t.effectId, t.action, t.requestJson, t.scopeId, t.deviceId, t.status, t.membershipEpoch, t.updatedAt);
55
2981
  }
56
- async function K(e, t) {
57
- return await Z(e.prepare("SELECT effect_id, action, request_json, outcome_applied, scope_id, device_id,\n role, status, membership_epoch, coordinator_id, group_id, manifest_issuer_device_id,\n manifest_hash, signed_manifest_json, updated_at, created_at\n FROM coordinator_scope_membership_effect_receipts WHERE effect_id = ?").bind(t));
2982
+ async function To(e, t) {
2983
+ return await Q(e.prepare("SELECT effect_id, action, request_json, outcome_applied, scope_id, device_id,\n role, status, membership_epoch, coordinator_id, group_id, manifest_issuer_device_id,\n manifest_hash, signed_manifest_json, updated_at, created_at\n FROM coordinator_scope_membership_effect_receipts WHERE effect_id = ?").bind(t));
58
2984
  }
59
- function q(e, t) {
2985
+ function Eo(e, t) {
60
2986
  return e.prepare("INSERT INTO coordinator_scope_membership_effect_receipts(\n effect_id, action, request_json, outcome_applied, scope_id, device_id,\n role, status, membership_epoch, coordinator_id, group_id, manifest_issuer_device_id,\n manifest_hash, signed_manifest_json, updated_at, created_at\n )\n SELECT ?, 'grant', ?, 1, membership.scope_id, membership.device_id,\n membership.role, membership.status, membership.membership_epoch,\n membership.coordinator_id, membership.group_id, membership.manifest_issuer_device_id,\n membership.manifest_hash, membership.signed_manifest_json, membership.updated_at, ?\n FROM coordinator_scope_memberships AS membership\n WHERE changes() > 0 AND membership.scope_id = ? AND membership.device_id = ?").bind(t.effectId, t.requestJson, t.createdAt, t.scopeId, t.deviceId);
61
2987
  }
62
- function ne(e, t) {
2988
+ function Do(e, t) {
63
2989
  return e.prepare("INSERT INTO coordinator_scope_membership_effect_receipts(\n effect_id, action, request_json, outcome_applied, scope_id, device_id,\n role, status, membership_epoch, coordinator_id, group_id, manifest_issuer_device_id,\n manifest_hash, signed_manifest_json, updated_at, created_at\n )\n SELECT ?, 'revoke', ?, changed.applied, ?, ?, membership.role, membership.status,\n membership.membership_epoch, membership.coordinator_id, membership.group_id,\n membership.manifest_issuer_device_id, membership.manifest_hash,\n membership.signed_manifest_json, membership.updated_at, ?\n FROM (SELECT CASE WHEN changes() > 0 THEN 1 ELSE 0 END AS applied) AS changed\n LEFT JOIN coordinator_scope_memberships AS membership\n ON changed.applied = 1 AND membership.scope_id = ? AND membership.device_id = ?\n WHERE NOT EXISTS (\n SELECT 1 FROM coordinator_scope_membership_effect_receipts WHERE effect_id = ?\n )").bind(t.effectId, t.requestJson, t.scopeId, t.deviceId, t.createdAt, t.scopeId, t.deviceId, t.effectId);
64
2990
  }
65
- async function J(e, t) {
2991
+ async function Oo(e, t) {
66
2992
  if (!e.batch) throw Error("D1 batch support is required for audited scope membership changes.");
67
2993
  return await e.batch(t);
68
2994
  }
69
- function Y(e) {
2995
+ function ko(e) {
70
2996
  return Number(e?.meta?.changes ?? 0);
71
2997
  }
72
- async function X(e) {
2998
+ function Ao(e, t = {}) {
2999
+ return In({
3000
+ first: (t) => e.prepare(t.sql).bind(...t.values).first(),
3001
+ run: (t) => $(e.prepare(t.sql).bind(...t.values)),
3002
+ batch: async (t) => {
3003
+ if (!e.batch) throw Error("auth_link_atomic_batch_required");
3004
+ return (await e.batch(t.map((t) => e.prepare(t.sql).bind(...t.values)))).map(ko);
3005
+ }
3006
+ }, t);
3007
+ }
3008
+ async function Z(e) {
73
3009
  let t = await e.all();
74
3010
  return Array.isArray(t?.results) ? t.results : [];
75
3011
  }
76
- async function Z(e) {
3012
+ async function Q(e) {
77
3013
  return await e.first();
78
3014
  }
79
- async function Q(e) {
3015
+ function jo(e) {
3016
+ if (!e || Array.isArray(e) || "success" in e && e.success !== !0 || !Array.isArray(e.results)) throw Error("scope_authorization_unavailable");
3017
+ return e.results;
3018
+ }
3019
+ async function $(e) {
80
3020
  let t = await e.run();
81
3021
  return Number(t?.meta?.changes ?? 0);
82
3022
  }
83
- var $ = class {
3023
+ var Mo = `${Bt}
3024
+ OR ${Bt}`, No = Me, Po = `EXISTS (
3025
+ SELECT 1 FROM coordinator_invites ri
3026
+ JOIN groups rg ON rg.group_id = ri.group_id AND rg.archived_at IS NULL
3027
+ WHERE ri.invite_id = ? AND ri.group_id = ? AND ri.revoked_at IS NULL
3028
+ AND ri.invite_kind = ? AND ri.reviewed_intent_json IS ?
3029
+ AND ri.reviewed_preview_digest IS ? AND ri.policy_team_id IS ?
3030
+ AND ri.target_identity_id IS ? AND ri.assigned_identity_id IS ?
3031
+ AND ri.inviter_device_id IS ?
3032
+ AND ri.token_digest IS ? AND (ri.token = ? OR ri.token = 'consumed:' || ri.invite_id)
3033
+ AND (ri.consumed_at IS NULL OR (ri.bound_device_id = ? AND ri.bound_public_key = ?
3034
+ AND ri.bound_fingerprint = ? AND ri.recipient_actor_id = ?))
3035
+ AND ((? = 0 AND NOT EXISTS (SELECT 1 FROM enrolled_devices se
3036
+ WHERE se.group_id = ri.group_id AND se.device_id = ri.inviter_device_id))
3037
+ OR (? = 1 AND EXISTS (SELECT 1 FROM enrolled_devices se
3038
+ WHERE se.group_id = ri.group_id AND se.device_id = ri.inviter_device_id
3039
+ AND se.public_key = ? AND se.fingerprint = ? AND se.enabled = ?)))
3040
+ AND NOT EXISTS (SELECT 1 FROM enrolled_devices re
3041
+ WHERE re.group_id = ri.group_id AND re.device_id = ?
3042
+ AND (re.public_key <> ? OR re.fingerprint <> ?
3043
+ OR (re.identity_id IS NOT NULL AND re.identity_id <> ?)))
3044
+ AND NOT (${Mo}) AND NOT (${No}))`, Fo = "EXISTS (SELECT 1 FROM coordinator_invites bi\n WHERE bi.invite_id = ? AND bi.consumed_at IS NOT NULL\n AND bi.bound_device_id = ? AND bi.bound_public_key = ?\n AND bi.bound_fingerprint = ? AND bi.recipient_actor_id = ?)";
3045
+ function Io(e, t) {
3046
+ if (e && (e.public_key !== t.publicKey || e.fingerprint !== t.fingerprint || e.identity_id !== null && e.identity_id !== t.identityId)) throw Error("invite_identity_conflict");
3047
+ }
3048
+ function Lo(e, t, n) {
3049
+ if (!(!e.consumed_at && !n.requireBinding)) {
3050
+ if (e.bound_device_id !== t.deviceId || e.bound_public_key !== t.publicKey || e.bound_fingerprint !== t.fingerprint) throw Error("invite_already_bound");
3051
+ if (e.recipient_actor_id !== t.identityId) throw Error("invite_identity_conflict");
3052
+ }
3053
+ }
3054
+ function Ro(e, t) {
3055
+ if (!e) throw Error("invite_acceptance_incomplete");
3056
+ if (Io(e, t), e.identity_id !== t.identityId) throw Error("invite_identity_conflict");
3057
+ }
3058
+ function zo(e, t, n, r) {
3059
+ let i = [
3060
+ t.deviceId,
3061
+ r.recipient,
3062
+ e.inviter_device_id,
3063
+ r.inviter
3064
+ ], a = [t.deviceId, r.recipient], o = [
3065
+ e.invite_id,
3066
+ e.group_id,
3067
+ t.inviteKind,
3068
+ e.reviewed_intent_json,
3069
+ e.reviewed_preview_digest,
3070
+ e.policy_team_id,
3071
+ e.target_identity_id,
3072
+ e.assigned_identity_id,
3073
+ e.inviter_device_id,
3074
+ e.token_digest,
3075
+ e.token,
3076
+ t.deviceId,
3077
+ t.publicKey,
3078
+ t.fingerprint,
3079
+ t.identityId,
3080
+ +!!n,
3081
+ +!!n,
3082
+ n?.public_key ?? null,
3083
+ n?.fingerprint ?? null,
3084
+ n?.enabled ?? null,
3085
+ t.deviceId,
3086
+ t.publicKey,
3087
+ t.fingerprint,
3088
+ t.identityId,
3089
+ ...i,
3090
+ ...a
3091
+ ], s = [
3092
+ e.invite_id,
3093
+ t.deviceId,
3094
+ t.publicKey,
3095
+ t.fingerprint,
3096
+ t.identityId
3097
+ ];
3098
+ return {
3099
+ revocationValues: i,
3100
+ ownershipValues: a,
3101
+ eligibilitySql: Po,
3102
+ eligibilityValues: o,
3103
+ boundEligibilitySql: `${Po} AND ${Fo}`,
3104
+ boundEligibilityValues: [...o, ...s]
3105
+ };
3106
+ }
3107
+ async function Bo(e, t) {
3108
+ try {
3109
+ let n = await Q(e());
3110
+ if (!n || "success" in n && n.success === !1 || t.some((e) => n[e] !== 0 && n[e] !== 1)) throw Error("device_ownership_authorization_unavailable");
3111
+ return n;
3112
+ } catch {
3113
+ throw Error("device_ownership_authorization_unavailable");
3114
+ }
3115
+ }
3116
+ async function Vo(e, t, n) {
3117
+ let r = await f(n.publicKey), i = t.inviter_device_id ? await Q(e.prepare(`SELECT ${So}
3118
+ FROM enrolled_devices WHERE group_id = ? AND device_id = ?`).bind(t.group_id, t.inviter_device_id)) : null, a = i ? { ...i } : null, o = zo(t, n, a, {
3119
+ recipient: r,
3120
+ inviter: a ? await f(a.public_key) : null
3121
+ }), s = async (i) => {
3122
+ let a = i.requireBinding ? `${o.boundEligibilitySql} AND EXISTS (SELECT 1 FROM enrolled_devices
3123
+ WHERE group_id = ? AND device_id = ? AND public_key = ? AND fingerprint = ? AND enabled = 1)` : o.eligibilitySql, s = i.requireBinding ? [
3124
+ ...o.boundEligibilityValues,
3125
+ t.group_id,
3126
+ n.deviceId,
3127
+ n.publicKey,
3128
+ n.fingerprint
3129
+ ] : o.eligibilityValues;
3130
+ if ((await Bo(() => e.prepare(`SELECT (${Mo}) AS revoked`).bind(...o.revocationValues), ["revoked"])).revoked === 1) throw Error("device_revoked");
3131
+ let c = await Bo(() => e.prepare(`SELECT (${Mo}) AS revoked,
3132
+ (${No}) AS owned, (${a}) AS eligible`).bind(...o.revocationValues, ...o.ownershipValues, ...s), [
3133
+ "revoked",
3134
+ "owned",
3135
+ "eligible"
3136
+ ]);
3137
+ if (c.revoked === 1) throw Error("device_revoked");
3138
+ c.eligible === 0 && await Wo(e, t, n, r, { owned: c.owned === 1 });
3139
+ };
3140
+ return {
3141
+ ...o,
3142
+ assertEligible: s
3143
+ };
3144
+ }
3145
+ async function Ho(e, t, n) {
3146
+ if (!e.batch) throw Error("device_ownership_authorization_unavailable");
3147
+ try {
3148
+ let r = await e.batch([...t, e.prepare(`SELECT CASE WHEN ${n.sql}
3149
+ THEN 1 ELSE json('recipient_invite_authorization_failed') END AS confirmed`).bind(...n.values)]), i = r[t.length];
3150
+ if (gt(i) !== 0 || i?.results?.[0]?.confirmed !== 1) throw Error("device_ownership_authorization_unavailable");
3151
+ for (let e of r.slice(0, t.length)) gt(e);
3152
+ return gt(r[0]);
3153
+ } catch {
3154
+ throw await n.assertEligible({ requireBinding: !1 }), Error("device_ownership_authorization_unavailable");
3155
+ }
3156
+ }
3157
+ async function Uo(e, t, n, r) {
3158
+ await Ho(e, [e.prepare(`UPDATE enrolled_devices SET identity_id = ?
3159
+ WHERE group_id = ? AND device_id = ? AND identity_id IS NULL
3160
+ AND public_key = ? AND fingerprint = ? AND ${r.sql}`).bind(t.identityId, n.group_id, t.deviceId, t.publicKey, t.fingerprint, ...r.values)], r);
3161
+ }
3162
+ async function Wo(e, t, n, r, i = {}) {
3163
+ let a = await Q(e.prepare("SELECT public_key\n FROM enrolled_devices WHERE group_id = ? AND device_id = ?").bind(t.group_id, t.inviter_device_id)), o = a ? await f(a.public_key) : null;
3164
+ if (await Q(e.prepare(`SELECT 1 AS revoked
3165
+ WHERE ${Mo}`).bind(n.deviceId, r, t.inviter_device_id, o))) throw Error("device_revoked");
3166
+ let s = await Q(e.prepare("SELECT i.revoked_at, g.group_id AS current_group_id, g.archived_at,\n i.consumed_at, i.bound_device_id, i.bound_public_key, i.bound_fingerprint, i.recipient_actor_id\n FROM coordinator_invites i LEFT JOIN groups g ON g.group_id = i.group_id\n WHERE i.invite_id = ?").bind(t.invite_id));
3167
+ throw !s || s.revoked_at ? Error("invite_invalid") : s.current_group_id === null ? Error("group_not_found") : s.archived_at ? Error("group_archived") : i.owned ? Error("device_ownership_requires_verified_identity") : (Lo(s, n, { requireBinding: !1 }), Error("invite_acceptance_incomplete"));
3168
+ }
3169
+ function Go(e, t, n, r, i) {
3170
+ let a = i.requireBinding ? r.boundEligibilitySql : r.eligibilitySql, o = i.requireBinding ? r.boundEligibilityValues : r.eligibilityValues, s = t.consumed_at || i.requireBinding ? Xo : "1", c = s === "1" ? [] : [t.group_id, n.deviceId];
3171
+ return e.prepare(`SELECT (${r.revocationSql}) AS revoked, (${r.ownershipSql}) AS owned,
3172
+ (${a} AND ${s}) AS eligible`).bind(...r.revocationValues, ...r.ownershipValues, ...o, ...c);
3173
+ }
3174
+ async function Ko(e, t, n) {
3175
+ let r = {
3176
+ ...n,
3177
+ identityId: n.recipientActorId
3178
+ }, i = await Q(e.prepare(`SELECT ${So} FROM enrolled_devices WHERE group_id = ? AND device_id = ?`).bind(t.group_id, n.deviceId)), a = It(i), o = i ? { ...i } : null, s = await f(n.publicKey), c = a === null ? null : await f(a), l = t.inviter_device_id ? await Q(e.prepare(`SELECT ${So}
3179
+ FROM enrolled_devices WHERE group_id = ? AND device_id = ?`).bind(t.group_id, t.inviter_device_id)) : null, u = It(l), d = l ? { ...l } : null, p = u === null ? null : await f(u), m = de(t, n, d, {
3180
+ recipient: s,
3181
+ inviter: p
3182
+ }), h = Xt(m, n.deviceId, {
3183
+ incoming: s,
3184
+ current: c
3185
+ }), g = async (i) => {
3186
+ let a = await Bo(() => Go(e, t, n, h, i), [
3187
+ "revoked",
3188
+ "owned",
3189
+ "eligible"
3190
+ ]);
3191
+ if (a.revoked === 1) throw Error("device_revoked");
3192
+ a.eligible === 0 && (a.owned === 0 && Io(o, r), await Wo(e, t, r, s, { owned: a.owned === 1 }));
3193
+ };
3194
+ return await g({ requireBinding: !1 }), Io(o, r), {
3195
+ ...h,
3196
+ assertEligible: g
3197
+ };
3198
+ }
3199
+ function qo(e, t, n, r) {
3200
+ return e.prepare(`UPDATE enrolled_devices SET identity_id = ?
3201
+ WHERE group_id = ? AND device_id = ? AND identity_id IS NULL AND enabled = 1
3202
+ AND public_key = ? AND fingerprint = ? AND ${r.boundEligibilitySql}`).bind(t.recipientActorId, n.group_id, t.deviceId, t.publicKey, t.fingerprint, ...r.boundEligibilityValues);
3203
+ }
3204
+ function Jo(e, t) {
3205
+ if (e.bound_device_id !== t.deviceId || e.bound_public_key !== t.publicKey || e.bound_fingerprint !== t.fingerprint) throw Error("invite_already_bound");
3206
+ if (e.recipient_actor_id !== t.recipientActorId || e.recipient_display_name !== t.recipientDisplayName || e.recipient_device_display_name !== t.deviceDisplayName) throw Error("invite_identity_conflict");
3207
+ }
3208
+ var Yo = "EXISTS (SELECT 1 FROM enrolled_devices WHERE group_id = ?\n AND device_id = ? AND public_key = ? AND fingerprint = ? AND identity_id = ? AND enabled = 1)", Xo = "EXISTS (SELECT 1 FROM enrolled_devices\n WHERE group_id = ? AND device_id = ? AND enabled = 1)";
3209
+ function Zo(e, t) {
3210
+ return [
3211
+ e.group_id,
3212
+ t.deviceId,
3213
+ t.publicKey,
3214
+ t.fingerprint,
3215
+ t.recipientActorId
3216
+ ];
3217
+ }
3218
+ async function Qo(e, t, n, r, i, a) {
3219
+ n.consumed_at && t.splice(1, 1, qo(e, r, n, i));
3220
+ let o = await Ho(e, t, {
3221
+ sql: `${i.boundEligibilitySql} AND ${Yo}`,
3222
+ values: [...i.boundEligibilityValues, ...a],
3223
+ assertEligible: i.assertEligible
3224
+ });
3225
+ return !n.consumed_at && o === 1;
3226
+ }
3227
+ var $o = class {
3228
+ accountChangeBackend;
3229
+ accountChangesCapability;
84
3230
  db;
85
- constructor(e) {
86
- this.db = e;
3231
+ authLinks;
3232
+ async assertAuthSchemaReady() {
3233
+ await st({ first: ({ sql: e, values: t }) => this.db.prepare(e).bind(...t).first() });
3234
+ }
3235
+ accountLinkStatus;
3236
+ deviceRevocations;
3237
+ authSessions;
3238
+ authAccountProfiles;
3239
+ authBrowserTransactions;
3240
+ constructor(e, t = {}) {
3241
+ this.db = e, this.deviceRevocations = new be({
3242
+ all: (t) => e.prepare(t.sql).bind(...t.values).all(),
3243
+ batch: async (t) => {
3244
+ if (!e.batch) throw Error("device_revocation_atomic_batch_required");
3245
+ return e.batch(t.map((t) => e.prepare(t.sql).bind(...t.values)));
3246
+ }
3247
+ }, t.authClock);
3248
+ let n = Ao(e);
3249
+ this.accountChangeBackend = Ao(e, { connections: !0 }), this.accountChangesCapability = new on(this.accountChangeBackend, t.authClock), this.authLinks = new _n(n, t.authClock), this.accountLinkStatus = new ke(n, t.authClock), this.authSessions = new kt(n, t.authClock), this.authAccountProfiles = new St(n, t.authClock), this.authBrowserTransactions = new we(n, t.authClock);
3250
+ }
3251
+ async getAccountChanges() {
3252
+ return await this.accountChangeBackend.first({
3253
+ sql: "SELECT 1",
3254
+ values: []
3255
+ }), this.accountChangesCapability;
3256
+ }
3257
+ readAccountConnectionSchemaState() {
3258
+ return Ce({ first: ({ sql: e, values: t }) => this.db.prepare(e).bind(...t).first() });
3259
+ }
3260
+ async readAccountChangeCapability() {
3261
+ let e = await this.readAccountConnectionSchemaState();
3262
+ if (e === "upgrade_required") throw new zt();
3263
+ return e === "ready" ? this.accountChangesCapability : null;
3264
+ }
3265
+ async readAuthBrowserTransactionActivity(e, t) {
3266
+ return this.authBrowserTransactions.readAuthBrowserTransactionActivity(e, t);
3267
+ }
3268
+ async startAuthBrowserTransaction(e, t) {
3269
+ return this.authBrowserTransactions.startAuthBrowserTransaction(e, t);
3270
+ }
3271
+ async consumeAuthBrowserTransaction(e, t) {
3272
+ return this.authBrowserTransactions.consumeAuthBrowserTransaction(e, t);
3273
+ }
3274
+ async readAuthBrowserTransactionPurpose(e, t) {
3275
+ return this.authBrowserTransactions.readAuthBrowserTransactionPurpose(e, t);
3276
+ }
3277
+ async resolveAuthLinkBrowserTransaction(e, t) {
3278
+ return this.authBrowserTransactions.resolveAuthLinkBrowserTransaction(e, t);
3279
+ }
3280
+ async cancelAuthSigninBrowserTransaction(e, t) {
3281
+ return this.authBrowserTransactions.cancelAuthSigninBrowserTransaction(e, t);
3282
+ }
3283
+ async retireAuthBrowserTransactions(e, t) {
3284
+ return this.authBrowserTransactions.retireAuthBrowserTransactions(e, t);
3285
+ }
3286
+ async purgeAuthSigninBrowserTransactions(e, t) {
3287
+ return this.authBrowserTransactions.purgeAuthSigninBrowserTransactions(e, t);
3288
+ }
3289
+ async maintainAuthBrowserTransactions(e, t) {
3290
+ return this.authBrowserTransactions.maintainAuthBrowserTransactions(e, t);
3291
+ }
3292
+ async redeemAuthLinkSession(e, t) {
3293
+ return this.authSessions.redeemAuthLinkSession(e, t);
3294
+ }
3295
+ async redeemAuthLinkSessionWithBrowserTransaction(e, t) {
3296
+ return this.authSessions.redeemAuthLinkSessionWithBrowserTransaction(e, t);
3297
+ }
3298
+ async preserveAuthLinkSessionCompletion(e, t) {
3299
+ return this.authSessions.preserveAuthLinkSessionCompletion(e, t);
3300
+ }
3301
+ async purgeAuthGuardedSigninSessions(e, t) {
3302
+ return this.authSessions.purgeAuthGuardedSigninSessions(e, t);
3303
+ }
3304
+ async purgeAuthGuardedSigninReceipts(e, t) {
3305
+ return this.authSessions.purgeAuthGuardedSigninReceipts(e, t);
3306
+ }
3307
+ async signInWithAuthAccount(e, t) {
3308
+ return this.authSessions.signInWithAuthAccount(e, t);
3309
+ }
3310
+ async signInWithConsumedBrowserTransaction(e, t) {
3311
+ return this.authSessions.signInWithConsumedBrowserTransaction(e, t);
3312
+ }
3313
+ async readAuthSession(e, t) {
3314
+ return this.authSessions.readAuthSession(e, t);
3315
+ }
3316
+ async recordAuthAccountProfile(e, t) {
3317
+ return this.authAccountProfiles.recordAuthAccountProfile(e, t);
3318
+ }
3319
+ async readAuthSessionAccount(e, t) {
3320
+ return this.authAccountProfiles.readAuthSessionAccount(e, t);
3321
+ }
3322
+ async clearRevokedAuthAccountProfile(e, t) {
3323
+ return this.authAccountProfiles.clearRevokedAuthAccountProfile(e, t);
3324
+ }
3325
+ async signOutAuthSession(e, t) {
3326
+ return this.authSessions.signOutAuthSession(e, t);
3327
+ }
3328
+ async revokeAuthAccountLink(e, t) {
3329
+ return this.authSessions.revokeAuthAccountLink(e, t);
3330
+ }
3331
+ async maintainAuthLinkAttempts(e, t) {
3332
+ return this.authLinks.maintainAuthLinkAttempts(e, t);
3333
+ }
3334
+ readAccountLinkStatus(...e) {
3335
+ return this.accountLinkStatus.readAccountLinkStatus(...e);
3336
+ }
3337
+ readAuthDeviceClaimReadiness(...e) {
3338
+ return this.accountLinkStatus.readAuthDeviceClaimReadiness(...e);
3339
+ }
3340
+ async createAuthLinkAttempt(e, t) {
3341
+ return this.authLinks.createAuthLinkAttempt(e, t);
3342
+ }
3343
+ async claimAuthLinkAttempt(e, t) {
3344
+ return this.authLinks.claimAuthLinkAttempt(e, t);
3345
+ }
3346
+ async recordAuthLinkOidcVerified(e, t) {
3347
+ return this.authLinks.recordAuthLinkOidcVerified(e, t);
3348
+ }
3349
+ async confirmAuthLinkAttempt(e, t) {
3350
+ return this.authLinks.confirmAuthLinkAttempt(e, t);
3351
+ }
3352
+ async readAuthLinkCompletionDestination(e, t) {
3353
+ return this.authLinks.readAuthLinkCompletionDestination(e, t);
3354
+ }
3355
+ async finalizeAuthLinkAttempt(e, t) {
3356
+ return this.authLinks.finalizeAuthLinkAttempt(e, t);
3357
+ }
3358
+ async failAuthLinkAttempt(e, t) {
3359
+ return this.authLinks.failAuthLinkAttempt(e, t);
3360
+ }
3361
+ async getAuthLinkAttemptStatus(e, t, n) {
3362
+ return this.authLinks.getAuthLinkAttemptStatus(e, t, n);
87
3363
  }
88
3364
  async close() {}
3365
+ async issueIdentityGroupGrantFromControllerAttestation(e) {
3366
+ let t = At(e, ["coordinatorId", "attestationId"]);
3367
+ if (!t) return {
3368
+ kind: "rejected",
3369
+ error: "invalid_grant_input"
3370
+ };
3371
+ try {
3372
+ let e = await Q(this.db.prepare(Pt).bind(t.coordinatorId, t.attestationId));
3373
+ if (!e) return {
3374
+ kind: "rejected",
3375
+ error: "grant_authority_unavailable"
3376
+ };
3377
+ let n = [
3378
+ t.coordinatorId,
3379
+ t.attestationId,
3380
+ e.group_id,
3381
+ e.device_id,
3382
+ e.public_key,
3383
+ e.fingerprint,
3384
+ e.identity_id,
3385
+ e.device_id,
3386
+ await f(e.public_key)
3387
+ ], r = await Q(this.db.prepare(wn).bind(Y(), ...n));
3388
+ if (r) return {
3389
+ kind: "created",
3390
+ grant: r
3391
+ };
3392
+ let i = await Q(this.db.prepare(Ot).bind(...n));
3393
+ return i ? {
3394
+ kind: "existing",
3395
+ grant: i
3396
+ } : {
3397
+ kind: "rejected",
3398
+ error: "grant_authority_unavailable"
3399
+ };
3400
+ } catch {
3401
+ throw Error("identity_group_grant_write_incomplete");
3402
+ }
3403
+ }
3404
+ async listIdentityGroupGrantRevisions(e) {
3405
+ let t = At(e, ["coordinatorId", "identityId"]);
3406
+ if (!t) throw Error("invalid_grant_input");
3407
+ let n = await this.db.prepare(xt).bind(t.coordinatorId, t.identityId).all();
3408
+ if (!Array.isArray(n?.results)) throw Error("identity_group_grant_read_incomplete");
3409
+ return n.results;
3410
+ }
3411
+ async revokeIdentityGroupGrant(e) {
3412
+ let t = At(e, [
3413
+ "coordinatorId",
3414
+ "identityId",
3415
+ "groupId",
3416
+ "expectedRevision"
3417
+ ]);
3418
+ if (!t) return !1;
3419
+ let n = (await this.db.prepare(un).bind(Y(), t.coordinatorId, t.identityId, t.groupId, t.expectedRevision).run())?.meta?.changes;
3420
+ if (typeof n != "number" || !Number.isSafeInteger(n) || n < 0 || n > 1) throw Error("identity_group_grant_write_incomplete");
3421
+ return n === 1;
3422
+ }
3423
+ async createAuthControllerAttestation(e) {
3424
+ let t = kn(e);
3425
+ if (!t) return {
3426
+ kind: "rejected",
3427
+ error: "invalid_review_input"
3428
+ };
3429
+ let n = await Q(this.db.prepare(bt).bind(t.groupId, t.deviceId));
3430
+ if (!n) return u(t);
3431
+ let r = ot(n, await f(n.public_key));
3432
+ try {
3433
+ if (await $(this.db.prepare(Dt).bind(...Pn(t, Y(), r))) === 0) return {
3434
+ kind: "rejected",
3435
+ error: t.verifiedSnapshot ? "review_stale" : "enrollment_mismatch"
3436
+ };
3437
+ } catch (e) {
3438
+ if (!ee(e)) throw e;
3439
+ return this.resolveAuthControllerRetry(t, r);
3440
+ }
3441
+ let i = await Q(this.db.prepare(ht).bind(t.coordinatorId, t.attestationId, ...r));
3442
+ if (!i) throw Error("auth_controller_persistence_incomplete");
3443
+ return {
3444
+ kind: "created",
3445
+ attestation: i
3446
+ };
3447
+ }
3448
+ async resolveAuthControllerRetry(e, t) {
3449
+ let n = await Q(this.db.prepare(Yt).bind(...En(e))), r = Le(e, n);
3450
+ if (r.kind === "rejected") return r;
3451
+ let i = await Q(this.db.prepare(ln).bind(...ft(e, t)));
3452
+ return i ? Le(e, i) : {
3453
+ kind: "rejected",
3454
+ error: e.verifiedSnapshot ? "review_stale" : "enrollment_mismatch"
3455
+ };
3456
+ }
3457
+ async getActiveAuthControllerAttestation(e, t) {
3458
+ if (!x(e) || !x(t)) return null;
3459
+ let n = await Q(this.db.prepare(Cn).bind(e, t));
3460
+ if (!n) return null;
3461
+ let r = ot(n, await f(n.public_key));
3462
+ return Q(this.db.prepare(ht).bind(e, t, ...r));
3463
+ }
3464
+ async revokeAuthControllerAttestation(e, t) {
3465
+ return !x(e) || !x(t) ? !1 : await $(this.db.prepare(Nt).bind(Y(), e, t)) > 0;
3466
+ }
89
3467
  async createGroup(e, t) {
90
- await this.db.prepare("INSERT OR IGNORE INTO groups(group_id, display_name, archived_at, created_at) VALUES (?, ?, NULL, ?)").bind(e, t ?? null, L()).run();
3468
+ await this.db.prepare("INSERT OR IGNORE INTO groups(group_id, display_name, archived_at, created_at) VALUES (?, ?, NULL, ?)").bind(e, t ?? null, Y()).run();
91
3469
  }
92
3470
  async getGroup(e) {
93
- let t = await Z(this.db.prepare("SELECT group_id, display_name, archived_at, created_at FROM groups WHERE group_id = ?").bind(e));
94
- return t ? F(t) : null;
3471
+ let t = await Q(this.db.prepare("SELECT group_id, display_name, archived_at, created_at FROM groups WHERE group_id = ?").bind(e));
3472
+ return t ? J(t) : null;
95
3473
  }
96
3474
  async listGroups(e = !1) {
97
3475
  let t = e ? "" : "WHERE archived_at IS NULL";
98
- return (await X(this.db.prepare(`SELECT group_id, display_name, archived_at, created_at FROM groups ${t} ORDER BY created_at ASC`))).map((e) => F(e));
3476
+ return (await Z(this.db.prepare(`SELECT group_id, display_name, archived_at, created_at FROM groups ${t} ORDER BY created_at ASC`))).map((e) => J(e));
99
3477
  }
100
3478
  async renameGroup(e, t) {
101
- return await Q(this.db.prepare("UPDATE groups SET display_name = ? WHERE group_id = ?").bind(t, e)) > 0;
3479
+ return await $(this.db.prepare("UPDATE groups SET display_name = ? WHERE group_id = ?").bind(t, e)) > 0;
102
3480
  }
103
- async archiveGroup(e, t = L()) {
104
- return await Q(this.db.prepare("UPDATE groups SET archived_at = ? WHERE group_id = ? AND archived_at IS NULL").bind(t, e)) > 0;
3481
+ async archiveGroup(e, t = Y()) {
3482
+ return await $(this.db.prepare("UPDATE groups SET archived_at = ? WHERE group_id = ? AND archived_at IS NULL").bind(t, e)) > 0;
105
3483
  }
106
3484
  async unarchiveGroup(e) {
107
- return await Q(this.db.prepare("UPDATE groups SET archived_at = NULL WHERE group_id = ? AND archived_at IS NOT NULL").bind(e)) > 0;
3485
+ return await $(this.db.prepare("UPDATE groups SET archived_at = NULL WHERE group_id = ? AND archived_at IS NOT NULL").bind(e)) > 0;
108
3486
  }
109
3487
  async enrollDevice(e, t) {
110
- if (await Q(this.db.prepare("INSERT INTO enrolled_devices(\n group_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at\n ) VALUES (?, ?, ?, ?, ?, ?, 1, ?)\n ON CONFLICT(group_id, device_id) DO UPDATE SET\n public_key = excluded.public_key,\n fingerprint = excluded.fingerprint,\n identity_id = COALESCE(enrolled_devices.identity_id, excluded.identity_id),\n display_name = excluded.display_name,\n enabled = 1\n WHERE excluded.identity_id IS NULL\n OR enrolled_devices.identity_id IS NULL\n OR enrolled_devices.identity_id = excluded.identity_id").bind(e, t.deviceId, t.publicKey, t.fingerprint, t.identityId ?? null, t.displayName ?? null, L())) === 0) throw Error("invite_identity_conflict");
3488
+ let { deviceId: n, publicKey: r, fingerprint: i, identityId: a, displayName: o } = fn(e, t);
3489
+ try {
3490
+ let t = It(await Q(this.db.prepare("SELECT public_key FROM enrolled_devices WHERE group_id = ? AND device_id = ?").bind(e, n))), s = await f(r), c = t === null ? null : await f(t), l = [
3491
+ t,
3492
+ e,
3493
+ n,
3494
+ e,
3495
+ n,
3496
+ t
3497
+ ], u = await this.db.prepare(bn).bind(e, n, r, i, a ?? null, o ?? null, Y(), n, s, n, s, n, c, ...l, n, s, n, c, t).run();
3498
+ if (gt(u) === 1) return;
3499
+ let d = await Q(this.db.prepare(Ct).bind(n, s, n, s, n, c, ...l));
3500
+ throw Error(gn(d));
3501
+ } catch (e) {
3502
+ an(e);
3503
+ }
111
3504
  }
112
3505
  async listEnrolledDevices(e, t) {
113
3506
  let n = t ? "" : "AND enrolled_devices.enabled = 1";
114
- return (await X(this.db.prepare(`SELECT ${W}
3507
+ return (await Z(this.db.prepare(`SELECT ${Co}
115
3508
  FROM enrolled_devices
116
3509
  LEFT JOIN presence_records
117
3510
  ON presence_records.group_id = enrolled_devices.group_id
118
3511
  AND presence_records.device_id = enrolled_devices.device_id
119
3512
  WHERE enrolled_devices.group_id = ? ${n}
120
- ORDER BY enrolled_devices.created_at ASC, enrolled_devices.device_id ASC`).bind(e))).map(I);
3513
+ ORDER BY enrolled_devices.created_at ASC, enrolled_devices.device_id ASC`).bind(e))).map(_o);
121
3514
  }
122
3515
  async getEnrollment(e, t, n = !1) {
123
- let r = n ? "" : "AND enabled = 1", i = await Z(this.db.prepare(`SELECT ${U}
3516
+ let r = n ? "" : "AND enabled = 1", i = await Q(this.db.prepare(`SELECT ${So}
124
3517
  FROM enrolled_devices
125
3518
  WHERE group_id = ? AND device_id = ? ${r}`).bind(e, t));
126
- return i ? F(i) : null;
3519
+ return i ? J(i) : null;
127
3520
  }
128
3521
  async renameDevice(e, t, n) {
129
- return await Q(this.db.prepare("UPDATE enrolled_devices SET display_name = ?\n WHERE group_id = ? AND device_id = ?").bind(n, e, t)) > 0;
3522
+ return await $(this.db.prepare("UPDATE enrolled_devices SET display_name = ?\n WHERE group_id = ? AND device_id = ?").bind(n, e, t)) > 0;
130
3523
  }
131
- async setDeviceEnabled(e, t, n) {
132
- return await Q(this.db.prepare("UPDATE enrolled_devices SET enabled = ?\n WHERE group_id = ? AND device_id = ?").bind(+!!n, e, t)) > 0;
3524
+ async setDeviceEnabled(e, t, r) {
3525
+ if (en(e, t), typeof r != "boolean") throw Error("invalid_input");
3526
+ if (r) try {
3527
+ let r = await Q(this.db.prepare("SELECT public_key FROM enrolled_devices WHERE group_id = ? AND device_id = ?").bind(e, t));
3528
+ if (r === null) return !1;
3529
+ if (!r) throw Error("device_ownership_authorization_unavailable");
3530
+ let i = r.public_key;
3531
+ if (typeof i != "string") throw Error("device_ownership_authorization_unavailable");
3532
+ let a = await f(i), o = await this.db.prepare(`UPDATE enrolled_devices SET enabled = 1
3533
+ WHERE group_id = ? AND device_id = ? AND public_key = ?
3534
+ AND NOT ${Bt}
3535
+ AND NOT ${Me}`).bind(e, t, i, t, a, t, a).run();
3536
+ if (gt(o) === 1) return !0;
3537
+ let s = gn(await Q(this.db.prepare(n).bind(t, a, t, a)));
3538
+ if (s === "device_ownership_requires_verified_identity") throw Error(s);
3539
+ return !1;
3540
+ } catch (e) {
3541
+ an(e);
3542
+ }
3543
+ return await $(this.db.prepare("UPDATE enrolled_devices SET enabled = ?\n WHERE group_id = ? AND device_id = ?").bind(+!!r, e, t)) > 0;
133
3544
  }
134
3545
  async removeDevice(e, t) {
135
3546
  if (!this.db.batch) throw Error("D1 batch support is required for atomic device removal.");
136
- return Y((await this.db.batch([
3547
+ return ko((await this.db.batch([
137
3548
  this.db.prepare("DELETE FROM presence_records WHERE group_id = ? AND device_id = ?").bind(e, t),
138
3549
  this.db.prepare("DELETE FROM coordinator_reciprocal_approvals WHERE group_id = ? AND (requesting_device_id = ? OR requested_device_id = ?)").bind(e, t, t),
139
3550
  this.db.prepare("DELETE FROM enrolled_devices WHERE group_id = ? AND device_id = ?").bind(e, t)
140
3551
  ]))[2]) > 0;
141
3552
  }
142
3553
  async recordNonce(e, t, n) {
143
- return await Q(this.db.prepare("INSERT OR IGNORE INTO request_nonces(device_id, nonce, created_at) VALUES (?, ?, ?)").bind(e, t, n)) > 0;
3554
+ return await $(this.db.prepare("INSERT OR IGNORE INTO request_nonces(device_id, nonce, created_at) VALUES (?, ?, ?)").bind(e, t, n)) > 0;
144
3555
  }
145
3556
  async cleanupNonces(e) {
146
3557
  await this.db.prepare("DELETE FROM request_nonces WHERE created_at < ?").bind(e).run();
147
3558
  }
3559
+ async createDeviceRevocation(e) {
3560
+ return this.deviceRevocations.createDeviceRevocation(e);
3561
+ }
3562
+ async listDeviceRevocations(e) {
3563
+ return this.deviceRevocations.listDeviceRevocations(e);
3564
+ }
3565
+ async recordAuthorizedNonce(e) {
3566
+ return this.deviceRevocations.recordAuthorizedNonce(e);
3567
+ }
148
3568
  async createInvite(e) {
149
- let t = L(), n = B(12), r = B(24), i = await V(r), a = D(e.expiresAt), s = await this.getGroup(e.groupId), c = String(e.operationId ?? "").trim() || null, l = String(e.reviewedProjectSetDigest ?? "").trim() || null, u = await o(e), d = u.inviteKind === "team_member" ? `identity:${B(18)}` : null;
150
- if (!!c != !!l) throw Error("operationId and reviewedProjectSetDigest must be provided together.");
151
- let f = async () => {
152
- if (!c) return null;
153
- let t = await Z(this.db.prepare(`SELECT ${H} FROM coordinator_invites WHERE operation_id = ?`).bind(c));
3569
+ let t = Y(), n = X(12), r = X(24), i = await bo(r), a = He(e.expiresAt), o = await this.getGroup(e.groupId), s = String(e.operationId ?? "").trim() || null, c = String(e.reviewedProjectSetDigest ?? "").trim() || null, l = await sn(e), u = l.inviteKind === "team_member" ? `identity:${X(18)}` : null;
3570
+ if (!!s != !!c) throw Error("operationId and reviewedProjectSetDigest must be provided together.");
3571
+ let d = async () => {
3572
+ if (!s) return null;
3573
+ let t = await Q(this.db.prepare(`SELECT ${xo} FROM coordinator_invites WHERE operation_id = ?`).bind(s));
154
3574
  if (!t) return null;
155
3575
  if (t.consumed_at) throw Error("invite_already_bound");
156
- if (t.group_id !== e.groupId || t.policy !== e.policy || t.invite_kind !== u.inviteKind || t.reviewed_project_set_digest !== l || t.inviter_actor_id !== (String(e.inviterActorId ?? "").trim() || null) || t.inviter_display_name !== (String(e.inviterDisplayName ?? "").trim() || null) || t.inviter_device_id !== (String(e.inviterDeviceId ?? "").trim() || null) || t.pending_person_id !== (String(e.pendingPersonId ?? "").trim() || null) || t.project_summaries_json !== (e.projectSummaries ? JSON.stringify(e.projectSummaries) : null) || t.project_intent_json !== (e.projectIntent ? JSON.stringify(e.projectIntent) : null) || t.policy_team_id !== u.policyTeamId || t.target_identity_id !== u.targetIdentityId || t.reviewed_preview_digest !== u.reviewedPreviewDigest || t.reviewed_intent_json !== u.reviewedIntentJson) throw Error("invite_operation_intent_conflict");
157
- return F(t);
158
- }, p = async (n) => {
3576
+ if (t.group_id !== e.groupId || t.policy !== e.policy || t.invite_kind !== l.inviteKind || t.reviewed_project_set_digest !== c || t.inviter_actor_id !== (String(e.inviterActorId ?? "").trim() || null) || t.inviter_display_name !== (String(e.inviterDisplayName ?? "").trim() || null) || t.inviter_device_id !== (String(e.inviterDeviceId ?? "").trim() || null) || t.pending_person_id !== (String(e.pendingPersonId ?? "").trim() || null) || t.project_summaries_json !== (e.projectSummaries ? JSON.stringify(e.projectSummaries) : null) || t.project_intent_json !== (e.projectIntent ? JSON.stringify(e.projectIntent) : null) || t.policy_team_id !== l.policyTeamId || t.target_identity_id !== l.targetIdentityId || t.reviewed_preview_digest !== l.reviewedPreviewDigest || t.reviewed_intent_json !== l.reviewedIntentJson) throw Error("invite_operation_intent_conflict");
3577
+ return J(t);
3578
+ }, f = async (n) => {
159
3579
  if (!n.revoked_at && n.expires_at > t) return n;
160
- await Q(this.db.prepare("UPDATE coordinator_invites\n SET token = ?, token_digest = ?, expires_at = ?, created_at = ?, created_by = ?,\n team_name_snapshot = ?, revoked_at = NULL\n WHERE operation_id = ? AND token = ?\n AND (revoked_at IS NOT NULL OR expires_at <= ?)").bind(r, i, a, t, e.createdBy ?? null, s?.display_name ?? null, c, n.token, t));
161
- let o = await f();
162
- if (!o) throw Error("invite_operation_reissue_failed");
163
- return o;
3580
+ await $(this.db.prepare("UPDATE coordinator_invites\n SET token = ?, token_digest = ?, expires_at = ?, created_at = ?, created_by = ?,\n team_name_snapshot = ?, revoked_at = NULL\n WHERE operation_id = ? AND token = ?\n AND (revoked_at IS NOT NULL OR expires_at <= ?)").bind(r, i, a, t, e.createdBy ?? null, o?.display_name ?? null, s, n.token, t));
3581
+ let c = await d();
3582
+ if (!c) throw Error("invite_operation_reissue_failed");
3583
+ return c;
164
3584
  };
165
- if (c) {
166
- let e = await f();
167
- if (e) return await p(e);
3585
+ if (s) {
3586
+ let e = await d();
3587
+ if (e) return await f(e);
168
3588
  }
169
3589
  try {
170
- await this.db.prepare("INSERT INTO coordinator_invites(\n invite_id, group_id, token, policy, expires_at, created_at, created_by,\n team_name_snapshot, revoked_at, operation_id, reviewed_project_set_digest,\n token_digest, inviter_actor_id, inviter_display_name, inviter_device_id,\n pending_person_id, project_summaries_json, project_intent_json, trust_state,\n invite_kind, policy_team_id, target_identity_id, assigned_identity_id,\n reviewed_preview_digest, reviewed_intent_json\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").bind(n, e.groupId, r, e.policy, a, t, e.createdBy ?? null, s?.display_name ?? null, c, l, i, String(e.inviterActorId ?? "").trim() || null, String(e.inviterDisplayName ?? "").trim() || null, String(e.inviterDeviceId ?? "").trim() || null, String(e.pendingPersonId ?? "").trim() || null, e.projectSummaries ? JSON.stringify(e.projectSummaries) : null, e.projectIntent ? JSON.stringify(e.projectIntent) : null, c ? "pending" : null, u.inviteKind, u.policyTeamId, u.targetIdentityId, d, u.reviewedPreviewDigest, u.reviewedIntentJson).run();
3590
+ await this.db.prepare("INSERT INTO coordinator_invites(\n invite_id, group_id, token, policy, expires_at, created_at, created_by,\n team_name_snapshot, revoked_at, operation_id, reviewed_project_set_digest,\n token_digest, inviter_actor_id, inviter_display_name, inviter_device_id,\n pending_person_id, project_summaries_json, project_intent_json, trust_state,\n invite_kind, policy_team_id, target_identity_id, assigned_identity_id,\n reviewed_preview_digest, reviewed_intent_json\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").bind(n, e.groupId, r, e.policy, a, t, e.createdBy ?? null, o?.display_name ?? null, s, c, i, String(e.inviterActorId ?? "").trim() || null, String(e.inviterDisplayName ?? "").trim() || null, String(e.inviterDeviceId ?? "").trim() || null, String(e.pendingPersonId ?? "").trim() || null, e.projectSummaries ? JSON.stringify(e.projectSummaries) : null, e.projectIntent ? JSON.stringify(e.projectIntent) : null, s ? "pending" : null, l.inviteKind, l.policyTeamId, l.targetIdentityId, u, l.reviewedPreviewDigest, l.reviewedIntentJson).run();
171
3591
  } catch (e) {
172
- if (c) {
173
- let e = await f();
174
- if (e) return await p(e);
3592
+ if (s) {
3593
+ let e = await d();
3594
+ if (e) return await f(e);
175
3595
  }
176
3596
  throw e;
177
3597
  }
178
- return F(await Z(this.db.prepare(`SELECT ${H} FROM coordinator_invites WHERE invite_id = ?`).bind(n)));
3598
+ return J(await Q(this.db.prepare(`SELECT ${xo} FROM coordinator_invites WHERE invite_id = ?`).bind(n)));
179
3599
  }
180
3600
  async getInviteByToken(e) {
181
- let t = await V(e), n = await Z(this.db.prepare(`SELECT ${H}
3601
+ let t = await bo(e), n = await Q(this.db.prepare(`SELECT ${xo}
182
3602
  FROM coordinator_invites
183
3603
  WHERE (token_digest = ? OR token = ?)
184
3604
  AND revoked_at IS NULL
185
- AND expires_at > ?`).bind(t, e, L()));
186
- return n ? F(n) : null;
3605
+ AND expires_at > ?`).bind(t, e, Y()));
3606
+ return n ? J(n) : null;
187
3607
  }
188
3608
  async getInviteByTokenForInspection(e) {
189
- let t = await V(e), n = await Z(this.db.prepare(`SELECT ${H} FROM coordinator_invites WHERE token_digest = ? OR token = ?`).bind(t, e));
190
- return n ? F(n) : null;
3609
+ let t = await bo(e), n = await Q(this.db.prepare(`SELECT ${xo} FROM coordinator_invites WHERE token_digest = ? OR token = ?`).bind(t, e));
3610
+ return n ? J(n) : null;
191
3611
  }
192
- async inspectRecipientInvite(e) {
193
- let t = await this.getInviteByTokenForInspection(e.token);
194
- if (!t) return null;
195
- let n = await N(t);
3612
+ async inspectRecipientInvite(t) {
3613
+ let n = await this.getInviteByTokenForInspection(t.token);
196
3614
  if (!n) return null;
197
- if (t.revoked_at) throw Error("invite_invalid");
198
- if (!t.consumed_at && new Date(t.expires_at) <= new Date(D(e.now))) throw Error("invite_expired");
199
- let r = await this.getGroup(t.group_id);
200
- if (!r) throw Error("group_not_found");
201
- if (r.archived_at) throw Error("group_archived");
202
- return n;
3615
+ let r = await e(n);
3616
+ if (!r) return null;
3617
+ if (n.revoked_at) throw Error("invite_invalid");
3618
+ if (!n.consumed_at && new Date(n.expires_at) <= new Date(He(t.now))) throw Error("invite_expired");
3619
+ let i = await this.getGroup(n.group_id);
3620
+ if (!i) throw Error("group_not_found");
3621
+ if (i.archived_at) throw Error("group_archived");
3622
+ return r;
203
3623
  }
204
- async consumeRecipientInvite(e) {
205
- let t = D(e.now), n = e.recipientDisplayName ?? null, r = e.deviceDisplayName ?? null;
206
- if (!e.identityId || !e.deviceId || !e.publicKey || !e.fingerprint || e.identityId !== e.identityId.trim() || e.deviceId !== e.deviceId.trim() || e.identityId.length > 256 || e.deviceId.length > 256 || /[\p{Cc}\p{Cf}]/u.test(e.identityId) || /[\p{Cc}\p{Cf}]/u.test(e.deviceId)) throw Error("invite_identity_conflict");
207
- let i = await V(e.token), o = await this.getInviteByTokenForInspection(e.token), s = o ? await N(o) : null;
208
- if (!o || !s || s.kind !== e.inviteKind || o.revoked_at) throw Error("invite_invalid");
209
- let c = await this.getGroup(o.group_id);
210
- if (!c) throw Error("group_not_found");
211
- if (c.archived_at) throw Error("group_archived");
212
- if (!o.consumed_at && new Date(o.expires_at) <= new Date(t)) throw Error("invite_expired");
213
- if (P(e.publicKey) !== e.fingerprint) throw Error("fingerprint_mismatch");
214
- let l = a(s);
215
- if (l !== e.identityId) throw Error("invite_identity_conflict");
216
- let u = o.bound_device_id === e.deviceId && o.bound_public_key === e.publicKey && o.bound_fingerprint === e.fingerprint;
217
- if (o.consumed_at && !u) throw Error("invite_already_bound");
218
- if (o.consumed_at && o.recipient_actor_id !== l) throw Error("invite_identity_conflict");
219
- let d = await Z(this.db.prepare(`SELECT ${U}
220
- FROM enrolled_devices WHERE group_id = ? AND device_id = ?`).bind(o.group_id, e.deviceId));
221
- if (d && (d.public_key !== e.publicKey || d.fingerprint !== e.fingerprint || d.identity_id !== null && d.identity_id !== l)) throw Error("invite_identity_conflict");
222
- let f = 0, p = B(12);
223
- if (!o.consumed_at) {
3624
+ async recoverRecipientInviteGrant(e, t, n) {
3625
+ if (!this.db.batch) throw Error("D1 batch support is required for atomic bootstrap grant recovery.");
3626
+ await Ho(this.db, [this.db.prepare(`UPDATE coordinator_invites SET bootstrap_grant_id = ?,
3627
+ trust_state = 'bootstrap_grant_created'
3628
+ WHERE invite_id = ? AND invite_kind = 'add_device'
3629
+ AND bootstrap_grant_id IS NULL AND inviter_device_id IS NOT NULL
3630
+ AND bound_device_id = ? AND recipient_actor_id = ? AND expires_at > ?
3631
+ AND EXISTS (SELECT 1 FROM enrolled_devices e
3632
+ WHERE e.group_id = coordinator_invites.group_id
3633
+ AND e.device_id = coordinator_invites.inviter_device_id AND e.enabled = 1)
3634
+ AND ${n.sql}`).bind(X(12), e.invite_id, t.deviceId, t.identityId, n.consumedAt, ...n.values), this.db.prepare(`INSERT OR IGNORE INTO coordinator_bootstrap_grants(
3635
+ grant_id, group_id, seed_device_id, worker_device_id, expires_at,
3636
+ created_at, created_by, revoked_at
3637
+ ) SELECT i.bootstrap_grant_id, i.group_id, i.inviter_device_id, i.bound_device_id,
3638
+ i.expires_at, ?, i.recipient_actor_id, NULL FROM coordinator_invites i
3639
+ JOIN enrolled_devices e ON e.group_id = i.group_id
3640
+ AND e.device_id = i.inviter_device_id AND e.enabled = 1
3641
+ WHERE i.invite_id = ? AND i.invite_kind = 'add_device'
3642
+ AND i.bootstrap_grant_id IS NOT NULL AND i.bound_device_id = ?
3643
+ AND ${n.sql}`).bind(n.consumedAt, e.invite_id, t.deviceId, ...n.values)], n);
3644
+ }
3645
+ async consumeRecipientInvite(t) {
3646
+ let n = { ...t }, r = He(n.now), i = n.recipientDisplayName ?? null, a = n.deviceDisplayName ?? null;
3647
+ if (!n.identityId || !n.deviceId || !n.publicKey || !n.fingerprint || n.identityId !== n.identityId.trim() || n.deviceId !== n.deviceId.trim() || n.identityId.length > 256 || n.deviceId.length > 256 || /[\p{Cc}\p{Cf}]/u.test(n.identityId) || /[\p{Cc}\p{Cf}]/u.test(n.deviceId)) throw Error("invite_identity_conflict");
3648
+ let o = await bo(n.token), s = structuredClone(await this.getInviteByTokenForInspection(n.token)), c = s ? await e(s) : null;
3649
+ if (!s || !c || c.kind !== n.inviteKind || s.revoked_at) throw Error("invite_invalid");
3650
+ let l = await this.getGroup(s.group_id);
3651
+ if (!l) throw Error("group_not_found");
3652
+ if (l.archived_at) throw Error("group_archived");
3653
+ if (!s.consumed_at && new Date(s.expires_at) <= new Date(r)) throw Error("invite_expired");
3654
+ if (Ue(n.publicKey) !== n.fingerprint) throw Error("fingerprint_mismatch");
3655
+ let u = ne(c);
3656
+ if (u !== n.identityId) throw Error("invite_identity_conflict");
3657
+ Lo(s, n, { requireBinding: !1 }), Io(await Q(this.db.prepare(`SELECT ${So}
3658
+ FROM enrolled_devices WHERE group_id = ? AND device_id = ?`).bind(s.group_id, n.deviceId)), n);
3659
+ let { eligibilitySql: d, eligibilityValues: f, boundEligibilitySql: p, boundEligibilityValues: m, assertEligible: h } = await Vo(this.db, s, n);
3660
+ await h({ requireBinding: !!s.consumed_at });
3661
+ let g = 0, ee = X(12);
3662
+ if (!s.consumed_at) {
224
3663
  if (!this.db.batch) throw Error("D1 batch support is required for atomic invite consume.");
225
- f = Y((await this.db.batch([
226
- this.db.prepare("UPDATE coordinator_invites SET token = ?, consumed_at = ?, bound_device_id = ?,\n bound_public_key = ?, bound_fingerprint = ?, recipient_actor_id = ?,\n recipient_display_name = ?, recipient_device_display_name = ?\n WHERE (token_digest = ? OR token = ?) AND consumed_at IS NULL\n AND revoked_at IS NULL AND expires_at > ? AND invite_kind = ?\n AND reviewed_intent_json = ? AND reviewed_preview_digest = ?\n AND ((invite_kind = 'team_member' AND assigned_identity_id = ?)\n OR (invite_kind = 'add_device' AND target_identity_id = ?))\n AND NOT EXISTS (\n SELECT 1 FROM enrolled_devices e\n WHERE e.group_id = coordinator_invites.group_id AND e.device_id = ?\n AND (e.public_key <> ? OR e.fingerprint <> ?\n OR (e.identity_id IS NOT NULL AND e.identity_id <> ?))\n )\n AND EXISTS (SELECT 1 FROM groups g WHERE g.group_id = coordinator_invites.group_id\n AND g.archived_at IS NULL)").bind(`consumed:${o.invite_id}`, t, e.deviceId, e.publicKey, e.fingerprint, l, n, r, i, e.token, t, e.inviteKind, o.reviewed_intent_json, o.reviewed_preview_digest, l, l, e.deviceId, e.publicKey, e.fingerprint, l),
227
- this.db.prepare("INSERT INTO enrolled_devices(\n group_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at\n ) SELECT i.group_id, i.bound_device_id, i.bound_public_key, i.bound_fingerprint,\n i.recipient_actor_id, i.recipient_device_display_name, 1, ? FROM coordinator_invites i\n JOIN groups g ON g.group_id = i.group_id AND g.archived_at IS NULL\n WHERE (i.token_digest = ? OR i.token = ?) AND i.bound_device_id = ?\n AND i.bound_public_key = ? AND i.bound_fingerprint = ?\n AND i.recipient_actor_id = ?\n ON CONFLICT(group_id, device_id) DO UPDATE SET\n identity_id = COALESCE(enrolled_devices.identity_id, excluded.identity_id),\n display_name = COALESCE(enrolled_devices.display_name, excluded.display_name),\n enabled = 1\n WHERE enrolled_devices.identity_id IS NULL\n OR enrolled_devices.identity_id = excluded.identity_id").bind(t, i, e.token, e.deviceId, e.publicKey, e.fingerprint, l),
228
- this.db.prepare("UPDATE coordinator_invites SET bootstrap_grant_id = ?,\n trust_state = 'bootstrap_grant_created'\n WHERE (token_digest = ? OR token = ?) AND invite_kind = 'add_device'\n AND bootstrap_grant_id IS NULL AND inviter_device_id IS NOT NULL\n AND expires_at > ?\n AND EXISTS (SELECT 1 FROM enrolled_devices e\n WHERE e.group_id = coordinator_invites.group_id\n AND e.device_id = coordinator_invites.inviter_device_id AND e.enabled = 1)").bind(p, i, e.token, t),
229
- this.db.prepare("INSERT OR IGNORE INTO coordinator_bootstrap_grants(\n grant_id, group_id, seed_device_id, worker_device_id, expires_at,\n created_at, created_by, revoked_at\n ) SELECT i.bootstrap_grant_id, i.group_id, i.inviter_device_id, i.bound_device_id,\n i.expires_at, ?, i.recipient_actor_id, NULL FROM coordinator_invites i\n JOIN enrolled_devices e ON e.group_id = i.group_id\n AND e.device_id = i.inviter_device_id AND e.enabled = 1\n WHERE (i.token_digest = ? OR i.token = ?) AND i.invite_kind = 'add_device'\n AND i.bootstrap_grant_id IS NOT NULL AND i.bound_device_id = ?").bind(t, i, e.token, e.deviceId)
230
- ]))[0]);
231
- }
232
- let m = await this.getGroup(o.group_id);
233
- if (!m) throw Error("group_not_found");
234
- if (m.archived_at) throw Error("group_archived");
235
- let h = await Z(this.db.prepare(`SELECT ${U}
236
- FROM enrolled_devices WHERE group_id = ? AND device_id = ?`).bind(o.group_id, e.deviceId));
237
- if (h && (h.public_key !== e.publicKey || h.fingerprint !== e.fingerprint || h.identity_id !== null && h.identity_id !== l)) throw Error("invite_identity_conflict");
238
- let g = await this.getInviteByTokenForInspection(e.token);
239
- if (!g || g.revoked_at || !g.consumed_at && new Date(g.expires_at) <= new Date(t)) throw Error("invite_invalid");
240
- let _ = await N(g);
241
- if (!_ || _.kind !== e.inviteKind) throw Error("invite_invalid");
242
- if (a(_) !== l) throw Error("invite_identity_conflict");
243
- if (g.bound_device_id !== e.deviceId || g.bound_public_key !== e.publicKey || g.bound_fingerprint !== e.fingerprint) throw Error("invite_already_bound");
244
- if (g.recipient_actor_id !== l) throw Error("invite_identity_conflict");
245
- await this.db.prepare("UPDATE enrolled_devices SET identity_id = ?\n WHERE group_id = ? AND device_id = ? AND identity_id IS NULL\n AND public_key = ? AND fingerprint = ?").bind(l, g.group_id, e.deviceId, e.publicKey, e.fingerprint).run();
246
- let v = await this.getEnrollment(g.group_id, e.deviceId);
247
- if (!v) throw Error("invite_acceptance_incomplete");
248
- if (v.public_key !== e.publicKey || v.fingerprint !== e.fingerprint || v.identity_id !== l) throw Error("invite_identity_conflict");
249
- let y = g;
250
- if (_.kind === "add_device" && g.inviter_device_id && !g.bootstrap_grant_id && new Date(g.expires_at) > new Date(t)) {
251
- if (!this.db.batch) throw Error("D1 batch support is required for atomic bootstrap grant recovery.");
252
- let n = B(12);
253
- await this.db.batch([this.db.prepare("UPDATE coordinator_invites SET bootstrap_grant_id = ?,\n trust_state = 'bootstrap_grant_created'\n WHERE invite_id = ? AND invite_kind = 'add_device'\n AND bootstrap_grant_id IS NULL AND inviter_device_id IS NOT NULL\n AND bound_device_id = ? AND recipient_actor_id = ? AND expires_at > ?\n AND EXISTS (SELECT 1 FROM enrolled_devices e\n WHERE e.group_id = coordinator_invites.group_id\n AND e.device_id = coordinator_invites.inviter_device_id AND e.enabled = 1)").bind(n, g.invite_id, e.deviceId, l, t), this.db.prepare("INSERT OR IGNORE INTO coordinator_bootstrap_grants(\n grant_id, group_id, seed_device_id, worker_device_id, expires_at,\n created_at, created_by, revoked_at\n ) SELECT i.bootstrap_grant_id, i.group_id, i.inviter_device_id, i.bound_device_id,\n i.expires_at, ?, i.recipient_actor_id, NULL FROM coordinator_invites i\n JOIN enrolled_devices e ON e.group_id = i.group_id\n AND e.device_id = i.inviter_device_id AND e.enabled = 1\n WHERE i.invite_id = ? AND i.invite_kind = 'add_device'\n AND i.bootstrap_grant_id IS NOT NULL AND i.bound_device_id = ?").bind(t, g.invite_id, e.deviceId)]);
254
- let r = await this.getInviteByTokenForInspection(e.token);
255
- if (!r) throw Error("invite_invalid");
256
- y = r;
257
- }
258
- let b = y.bootstrap_grant_id ? await this.getBootstrapGrant(y.bootstrap_grant_id) : null;
259
- return {
260
- status: f === 1 ? "accepted" : "existing",
261
- invite: y,
262
- reviewed_intent: _.reviewed_intent,
263
- bootstrap_grant: b
3664
+ g = await Ho(this.db, [
3665
+ this.db.prepare(`UPDATE coordinator_invites SET token = ?, consumed_at = ?, bound_device_id = ?,
3666
+ bound_public_key = ?, bound_fingerprint = ?, recipient_actor_id = ?,
3667
+ recipient_display_name = ?, recipient_device_display_name = ?
3668
+ WHERE (token_digest = ? OR token = ?) AND consumed_at IS NULL
3669
+ AND invite_id = ? AND group_id = ?
3670
+ AND revoked_at IS NULL AND expires_at > ? AND invite_kind = ?
3671
+ AND reviewed_intent_json = ? AND reviewed_preview_digest = ?
3672
+ AND ((invite_kind = 'team_member' AND assigned_identity_id = ?)
3673
+ OR (invite_kind = 'add_device' AND target_identity_id = ?))
3674
+ AND NOT EXISTS (
3675
+ SELECT 1 FROM enrolled_devices e
3676
+ WHERE e.group_id = coordinator_invites.group_id AND e.device_id = ?
3677
+ AND (e.public_key <> ? OR e.fingerprint <> ?
3678
+ OR (e.identity_id IS NOT NULL AND e.identity_id <> ?))
3679
+ )
3680
+ AND EXISTS (SELECT 1 FROM groups g WHERE g.group_id = coordinator_invites.group_id
3681
+ AND g.archived_at IS NULL)
3682
+ AND ${d}`).bind(`consumed:${s.invite_id}`, r, n.deviceId, n.publicKey, n.fingerprint, u, i, a, o, n.token, s.invite_id, s.group_id, r, n.inviteKind, s.reviewed_intent_json, s.reviewed_preview_digest, u, u, n.deviceId, n.publicKey, n.fingerprint, u, ...f),
3683
+ this.db.prepare(`INSERT INTO enrolled_devices(
3684
+ group_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at
3685
+ ) SELECT i.group_id, i.bound_device_id, i.bound_public_key, i.bound_fingerprint,
3686
+ i.recipient_actor_id, i.recipient_device_display_name, 1, ? FROM coordinator_invites i
3687
+ JOIN groups g ON g.group_id = i.group_id AND g.archived_at IS NULL
3688
+ WHERE (i.token_digest = ? OR i.token = ?) AND i.bound_device_id = ?
3689
+ AND i.invite_id = ? AND i.group_id = ? AND changes() = 1
3690
+ AND i.bound_public_key = ? AND i.bound_fingerprint = ?
3691
+ AND i.recipient_actor_id = ?
3692
+ AND ${p}
3693
+ ON CONFLICT(group_id, device_id) DO UPDATE SET
3694
+ identity_id = COALESCE(enrolled_devices.identity_id, excluded.identity_id),
3695
+ display_name = COALESCE(enrolled_devices.display_name, excluded.display_name),
3696
+ enabled = 1
3697
+ WHERE enrolled_devices.identity_id IS NULL
3698
+ OR enrolled_devices.identity_id = excluded.identity_id`).bind(r, o, n.token, n.deviceId, s.invite_id, s.group_id, n.publicKey, n.fingerprint, u, ...m),
3699
+ this.db.prepare(`UPDATE coordinator_invites SET bootstrap_grant_id = ?,
3700
+ trust_state = 'bootstrap_grant_created'
3701
+ WHERE (token_digest = ? OR token = ?) AND invite_kind = 'add_device'
3702
+ AND invite_id = ? AND group_id = ?
3703
+ AND bootstrap_grant_id IS NULL AND inviter_device_id IS NOT NULL
3704
+ AND expires_at > ?
3705
+ AND EXISTS (SELECT 1 FROM enrolled_devices e
3706
+ WHERE e.group_id = coordinator_invites.group_id
3707
+ AND e.device_id = coordinator_invites.inviter_device_id AND e.enabled = 1)
3708
+ AND ${p}`).bind(ee, o, n.token, s.invite_id, s.group_id, r, ...m),
3709
+ this.db.prepare(`INSERT OR IGNORE INTO coordinator_bootstrap_grants(
3710
+ grant_id, group_id, seed_device_id, worker_device_id, expires_at,
3711
+ created_at, created_by, revoked_at
3712
+ ) SELECT i.bootstrap_grant_id, i.group_id, i.inviter_device_id, i.bound_device_id,
3713
+ i.expires_at, ?, i.recipient_actor_id, NULL FROM coordinator_invites i
3714
+ JOIN enrolled_devices e ON e.group_id = i.group_id
3715
+ AND e.device_id = i.inviter_device_id AND e.enabled = 1
3716
+ WHERE (i.token_digest = ? OR i.token = ?) AND i.invite_kind = 'add_device'
3717
+ AND i.invite_id = ? AND i.group_id = ?
3718
+ AND i.bootstrap_grant_id IS NOT NULL AND i.bound_device_id = ?
3719
+ AND ${p}`).bind(r, o, n.token, s.invite_id, s.group_id, n.deviceId, ...m)
3720
+ ], {
3721
+ sql: d,
3722
+ values: f,
3723
+ assertEligible: h
3724
+ });
3725
+ }
3726
+ await h({ requireBinding: !1 });
3727
+ let te = await this.getGroup(s.group_id);
3728
+ if (!te) throw Error("group_not_found");
3729
+ if (te.archived_at) throw Error("group_archived");
3730
+ Io(await Q(this.db.prepare(`SELECT ${So}
3731
+ FROM enrolled_devices WHERE group_id = ? AND device_id = ?`).bind(s.group_id, n.deviceId)), n);
3732
+ let _ = await this.getInviteByTokenForInspection(n.token);
3733
+ if (!_ || _.revoked_at || !_.consumed_at && new Date(_.expires_at) <= new Date(r)) throw Error("invite_invalid");
3734
+ let re = await e(_);
3735
+ if (!re || re.kind !== n.inviteKind) throw Error("invite_invalid");
3736
+ if (ne(re) !== u) throw Error("invite_identity_conflict");
3737
+ Lo(_, n, { requireBinding: !0 }), await Uo(this.db, n, _, {
3738
+ sql: p,
3739
+ values: m,
3740
+ assertEligible: h
3741
+ }), await h({ requireBinding: !0 }), Ro(await this.getEnrollment(_.group_id, n.deviceId), n);
3742
+ let ie = _;
3743
+ if (re.kind === "add_device" && _.inviter_device_id && !_.bootstrap_grant_id && new Date(_.expires_at) > new Date(r)) {
3744
+ await this.recoverRecipientInviteGrant(_, n, {
3745
+ sql: p,
3746
+ values: m,
3747
+ consumedAt: r,
3748
+ assertEligible: h
3749
+ });
3750
+ let e = await this.getInviteByTokenForInspection(n.token);
3751
+ if (!e) throw Error("invite_invalid");
3752
+ ie = e;
3753
+ }
3754
+ let ae = ie.bootstrap_grant_id ? await this.getBootstrapGrant(ie.bootstrap_grant_id) : null;
3755
+ return await h({ requireBinding: !0 }), {
3756
+ status: g === 1 ? "accepted" : "existing",
3757
+ invite: ie,
3758
+ reviewed_intent: re.reviewed_intent,
3759
+ bootstrap_grant: ae
264
3760
  };
265
3761
  }
266
3762
  async consumeProjectInvite(e) {
3763
+ let t = lt(e);
267
3764
  if (!this.db.batch) throw Error("D1 batch support is required for atomic invite consume.");
268
- let t = D(e.now), n = await V(e.token), r = await this.getInviteByTokenForInspection(e.token);
269
- if (!r?.operation_id || !r.project_intent_json || r.revoked_at) throw Error("invite_invalid");
270
- let i = await this.getGroup(r.group_id);
271
- if (!i) throw Error("group_not_found");
272
- if (i.archived_at) throw Error("group_archived");
273
- if (r.operation_id !== e.operationId) throw Error("invite_invalid");
274
- if (P(e.publicKey) !== e.fingerprint) throw Error("fingerprint_mismatch");
275
- if (!r.consumed_at && new Date(r.expires_at) <= new Date(t)) throw Error("invite_expired");
276
- let a = r.bound_device_id === e.deviceId && r.bound_public_key === e.publicKey && r.bound_fingerprint === e.fingerprint;
277
- if (r.consumed_at && !a) throw Error("invite_already_bound");
278
- if (r.consumed_at && (r.recipient_actor_id !== e.recipientActorId || r.recipient_display_name !== e.recipientDisplayName || r.recipient_device_display_name !== e.deviceDisplayName)) throw Error("invite_identity_conflict");
279
- let o = await Z(this.db.prepare(`SELECT ${U}
280
- FROM enrolled_devices WHERE group_id = ? AND device_id = ?`).bind(r.group_id, e.deviceId));
281
- if (o && (o.public_key !== e.publicKey || o.fingerprint !== e.fingerprint || o.identity_id != null && o.identity_id !== e.recipientActorId)) throw Error("invite_identity_conflict");
282
- let s = B(12), c = Y((await this.db.batch([
283
- this.db.prepare("UPDATE coordinator_invites SET token = ?, consumed_at = ?, bound_device_id = ?,\n bound_public_key = ?, bound_fingerprint = ?, recipient_actor_id = ?,\n recipient_display_name = ?, recipient_device_display_name = ?,\n trust_state = 'pending_inviter_device'\n WHERE (token_digest = ? OR token = ?) AND consumed_at IS NULL\n AND EXISTS (SELECT 1 FROM groups g WHERE g.group_id = coordinator_invites.group_id\n AND g.archived_at IS NULL)").bind(`consumed:${r.invite_id}`, t, e.deviceId, e.publicKey, e.fingerprint, e.recipientActorId, e.recipientDisplayName, e.deviceDisplayName, n, e.token),
284
- this.db.prepare("INSERT INTO enrolled_devices(\n group_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at\n ) SELECT i.group_id, i.bound_device_id, i.bound_public_key, i.bound_fingerprint,\n i.recipient_actor_id, i.recipient_device_display_name, 1, ? FROM coordinator_invites i\n JOIN groups g ON g.group_id = i.group_id AND g.archived_at IS NULL\n WHERE (i.token_digest = ? OR i.token = ?) AND i.bound_device_id = ? AND ? = 1\n ON CONFLICT(group_id, device_id) DO UPDATE SET\n identity_id = COALESCE(enrolled_devices.identity_id, excluded.identity_id),\n display_name = excluded.display_name, enabled = 1\n WHERE enrolled_devices.identity_id IS NULL\n OR enrolled_devices.identity_id = excluded.identity_id").bind(t, n, e.token, e.deviceId, +!r.consumed_at),
285
- this.db.prepare("UPDATE coordinator_invites SET bootstrap_grant_id = ?,\n trust_state = 'bootstrap_grant_created'\n WHERE (token_digest = ? OR token = ?) AND bootstrap_grant_id IS NULL\n AND bound_device_id = ?\n AND EXISTS (SELECT 1 FROM groups g WHERE g.group_id = coordinator_invites.group_id\n AND g.archived_at IS NULL)\n AND expires_at > ?\n AND EXISTS (SELECT 1 FROM enrolled_devices e WHERE e.group_id = coordinator_invites.group_id\n AND e.device_id = coordinator_invites.inviter_device_id AND e.enabled = 1)").bind(s, n, e.token, e.deviceId, t),
286
- this.db.prepare("INSERT OR IGNORE INTO coordinator_bootstrap_grants(\n grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at,\n created_by, revoked_at\n ) SELECT i.bootstrap_grant_id, i.group_id, i.inviter_device_id, i.bound_device_id,\n i.expires_at, ?, i.inviter_actor_id, NULL FROM coordinator_invites i\n JOIN groups g ON g.group_id = i.group_id AND g.archived_at IS NULL\n JOIN enrolled_devices e ON e.group_id = i.group_id AND e.device_id = i.inviter_device_id\n WHERE (i.token_digest = ? OR i.token = ?) AND i.bootstrap_grant_id IS NOT NULL\n AND i.bound_device_id = ? AND e.enabled = 1").bind(t, n, e.token, e.deviceId)
287
- ]))[0]) === 1, l = await this.getGroup(r.group_id);
288
- if (!l) throw Error("group_not_found");
289
- if (l.archived_at) throw Error("group_archived");
290
- let u = await this.getInviteByTokenForInspection(e.token);
291
- if (!u) throw Error("invite_invalid");
292
- if (u.bound_device_id !== e.deviceId || u.bound_public_key !== e.publicKey || u.bound_fingerprint !== e.fingerprint) throw Error("invite_already_bound");
293
- if (u.recipient_actor_id !== e.recipientActorId || u.recipient_display_name !== e.recipientDisplayName || u.recipient_device_display_name !== e.deviceDisplayName) throw Error("invite_identity_conflict");
294
- c || await this.db.prepare("UPDATE enrolled_devices SET identity_id = ?\n WHERE group_id = ? AND device_id = ? AND identity_id IS NULL AND enabled = 1\n AND public_key = ? AND fingerprint = ?").bind(e.recipientActorId, u.group_id, e.deviceId, e.publicKey, e.fingerprint).run();
295
- let d = await this.getEnrollment(u.group_id, e.deviceId);
296
- if (!d) throw Error("invite_acceptance_incomplete");
297
- if (d.identity_id !== e.recipientActorId) throw Error("invite_identity_conflict");
298
- let f = u.inviter_device_id ? await this.getEnrollment(u.group_id, u.inviter_device_id) : null, p = u.bootstrap_grant_id ? await this.getBootstrapGrant(u.bootstrap_grant_id) : null;
3765
+ let n = He(t.now), r = await bo(t.token), i = await this.getInviteByTokenForInspection(t.token), a = i ? { ...i } : null;
3766
+ if (!a?.operation_id || !a.project_intent_json || a.revoked_at) throw Error("invite_invalid");
3767
+ let o = await this.getGroup(a.group_id);
3768
+ if (!o) throw Error("group_not_found");
3769
+ if (o.archived_at) throw Error("group_archived");
3770
+ if (a.operation_id !== t.operationId) throw Error("invite_invalid");
3771
+ if (Ue(t.publicKey) !== t.fingerprint) throw Error("fingerprint_mismatch");
3772
+ if (!a.consumed_at && new Date(a.expires_at) <= new Date(n)) throw Error("invite_expired");
3773
+ a.consumed_at && Jo(a, t);
3774
+ let s = await Ko(this.db, a, t), c = X(12), l = Zo(a, t), u = [
3775
+ this.db.prepare(`UPDATE coordinator_invites SET token = ?, consumed_at = ?, bound_device_id = ?,
3776
+ bound_public_key = ?, bound_fingerprint = ?, recipient_actor_id = ?,
3777
+ recipient_display_name = ?, recipient_device_display_name = ?,
3778
+ trust_state = 'pending_inviter_device'
3779
+ WHERE (token_digest = ? OR token = ?) AND consumed_at IS NULL
3780
+ AND EXISTS (SELECT 1 FROM groups g WHERE g.group_id = coordinator_invites.group_id
3781
+ AND g.archived_at IS NULL)
3782
+ AND revoked_at IS NULL AND expires_at > ? AND ${s.eligibilitySql}`).bind(`consumed:${a.invite_id}`, n, t.deviceId, t.publicKey, t.fingerprint, t.recipientActorId, t.recipientDisplayName, t.deviceDisplayName, r, t.token, n, ...s.eligibilityValues),
3783
+ this.db.prepare(`INSERT INTO enrolled_devices(
3784
+ group_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at
3785
+ ) SELECT i.group_id, i.bound_device_id, i.bound_public_key, i.bound_fingerprint,
3786
+ i.recipient_actor_id, i.recipient_device_display_name, 1, ? FROM coordinator_invites i
3787
+ JOIN groups g ON g.group_id = i.group_id AND g.archived_at IS NULL
3788
+ WHERE (i.token_digest = ? OR i.token = ?) AND i.bound_device_id = ? AND changes() = 1
3789
+ AND ${s.boundEligibilitySql}
3790
+ ON CONFLICT(group_id, device_id) DO UPDATE SET
3791
+ identity_id = COALESCE(enrolled_devices.identity_id, excluded.identity_id),
3792
+ display_name = excluded.display_name, enabled = 1
3793
+ WHERE (enrolled_devices.identity_id IS NULL
3794
+ OR enrolled_devices.identity_id = excluded.identity_id)
3795
+ AND ${s.boundEligibilitySql}`).bind(n, r, t.token, t.deviceId, ...s.boundEligibilityValues, ...s.boundEligibilityValues),
3796
+ this.db.prepare(`UPDATE coordinator_invites SET bootstrap_grant_id = ?,
3797
+ trust_state = 'bootstrap_grant_created'
3798
+ WHERE (token_digest = ? OR token = ?) AND bootstrap_grant_id IS NULL
3799
+ AND bound_device_id = ?
3800
+ AND (changes() = 1 OR ? = 1) AND ${Yo}
3801
+ AND EXISTS (SELECT 1 FROM groups g WHERE g.group_id = coordinator_invites.group_id
3802
+ AND g.archived_at IS NULL)
3803
+ AND expires_at > ?
3804
+ AND EXISTS (SELECT 1 FROM enrolled_devices e WHERE e.group_id = coordinator_invites.group_id
3805
+ AND e.device_id = coordinator_invites.inviter_device_id AND e.enabled = 1)
3806
+ AND ${s.boundEligibilitySql}`).bind(c, r, t.token, t.deviceId, +!!a.consumed_at, ...l, n, ...s.boundEligibilityValues),
3807
+ this.db.prepare(`INSERT OR IGNORE INTO coordinator_bootstrap_grants(
3808
+ grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at,
3809
+ created_by, revoked_at
3810
+ ) SELECT i.bootstrap_grant_id, i.group_id, i.inviter_device_id, i.bound_device_id,
3811
+ i.expires_at, ?, i.inviter_actor_id, NULL FROM coordinator_invites i
3812
+ JOIN groups g ON g.group_id = i.group_id AND g.archived_at IS NULL
3813
+ JOIN enrolled_devices e ON e.group_id = i.group_id AND e.device_id = i.inviter_device_id
3814
+ WHERE (i.token_digest = ? OR i.token = ?)
3815
+ AND ((i.bootstrap_grant_id = ? AND changes() = 1)
3816
+ OR (i.bootstrap_grant_id = ? AND ? = 1))
3817
+ AND i.bound_device_id = ? AND e.enabled = 1
3818
+ AND ${s.boundEligibilitySql} AND ${Yo}`).bind(n, r, t.token, c, a.bootstrap_grant_id ?? null, +!!a.consumed_at, t.deviceId, ...s.boundEligibilityValues, ...l)
3819
+ ], d = await Qo(this.db, u, a, t, s, l);
3820
+ await s.assertEligible({ requireBinding: !1 });
3821
+ let f = await this.getGroup(a.group_id);
3822
+ if (!f) throw Error("group_not_found");
3823
+ if (f.archived_at) throw Error("group_archived");
3824
+ let p = await this.getInviteByTokenForInspection(t.token);
3825
+ if (!p) throw Error("invite_invalid");
3826
+ Jo(p, t);
3827
+ let m = await this.getEnrollment(p.group_id, t.deviceId), h = p.inviter_device_id ? await this.getEnrollment(p.group_id, p.inviter_device_id) : null, g = p.bootstrap_grant_id ? await this.getBootstrapGrant(p.bootstrap_grant_id) : null;
3828
+ if (await s.assertEligible({ requireBinding: !0 }), !m) throw Error("invite_acceptance_incomplete");
3829
+ if (m.identity_id !== t.recipientActorId) throw Error("invite_identity_conflict");
299
3830
  return {
300
- status: c ? "accepted" : "existing",
301
- invite: u,
302
- enrollment: d,
303
- seed_enrollment: f,
304
- bootstrap_grant: p
3831
+ status: d ? "accepted" : "existing",
3832
+ invite: p,
3833
+ enrollment: m,
3834
+ seed_enrollment: h,
3835
+ bootstrap_grant: g
305
3836
  };
306
3837
  }
307
3838
  async listInvites(e) {
308
- return (await X(this.db.prepare(`SELECT ${H}
3839
+ return (await Z(this.db.prepare(`SELECT ${xo}
309
3840
  FROM coordinator_invites WHERE group_id = ?
310
- ORDER BY created_at DESC`).bind(e))).map((e) => F(e));
3841
+ ORDER BY created_at DESC`).bind(e))).map((e) => J(e));
311
3842
  }
312
3843
  async createJoinRequest(e) {
313
- let t = L(), n = B(12);
314
- return await this.db.prepare("INSERT INTO coordinator_join_requests(\n request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n ) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, NULL, NULL)").bind(n, e.groupId, e.deviceId, e.publicKey, e.fingerprint, e.displayName ?? null, e.token, t).run(), F(await Z(this.db.prepare("SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n FROM coordinator_join_requests WHERE request_id = ?").bind(n)));
3844
+ let t = Y(), n = X(12);
3845
+ return await this.db.prepare("INSERT INTO coordinator_join_requests(\n request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n ) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, NULL, NULL)").bind(n, e.groupId, e.deviceId, e.publicKey, e.fingerprint, e.displayName ?? null, e.token, t).run(), J(await Q(this.db.prepare("SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n FROM coordinator_join_requests WHERE request_id = ?").bind(n)));
315
3846
  }
316
3847
  async listJoinRequests(e, t) {
317
3848
  let n = t ?? "pending";
318
- return (await X(this.db.prepare("SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n FROM coordinator_join_requests\n WHERE group_id = ? AND status = ?\n ORDER BY created_at ASC, device_id ASC").bind(e, n))).map((e) => F(e));
3849
+ return (await Z(this.db.prepare("SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n FROM coordinator_join_requests\n WHERE group_id = ? AND status = ?\n ORDER BY created_at ASC, device_id ASC").bind(e, n))).map((e) => J(e));
319
3850
  }
320
3851
  async reviewJoinRequest(e) {
321
- let t = await Z(this.db.prepare("SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status,\n created_at, reviewed_at, reviewed_by\n FROM coordinator_join_requests WHERE request_id = ?").bind(e.requestId));
3852
+ e = {
3853
+ ...e,
3854
+ bootstrapGrant: e.bootstrapGrant ? { ...e.bootstrapGrant } : e.bootstrapGrant
3855
+ };
3856
+ let t = await Q(this.db.prepare("SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status,\n created_at, reviewed_at, reviewed_by\n FROM coordinator_join_requests WHERE request_id = ?").bind(e.requestId));
322
3857
  if (!t) return null;
323
- if (t.status !== "pending") return {
324
- ...F(t),
3858
+ let n = { ...t };
3859
+ if (n.status !== "pending") return {
3860
+ ...J(n),
325
3861
  _no_transition: !0
326
3862
  };
327
- let n = l(e.bootstrapGrant), r = L(), i = e.approved ? "approved" : "denied", a = null, o = null;
328
- if (e.approved && n) {
329
- if (!await Z(this.db.prepare("SELECT device_id FROM enrolled_devices WHERE group_id = ? AND device_id = ? AND enabled = 1").bind(t.group_id, n.seedDeviceId))) throw Error("bootstrap grant seed device is not enrolled in the group.");
330
- if (n.seedDeviceId === t.device_id) throw Error("bootstrap grant seed and worker device ids must differ.");
331
- a = {
332
- ...n,
333
- groupId: t.group_id,
334
- workerDeviceId: t.device_id
3863
+ let r = mn(e.bootstrapGrant);
3864
+ if (!e.approved) return this.denyJoinRequest(e);
3865
+ if (!this.db.batch) throw Error("join_review_unavailable");
3866
+ let i = Y(), { guard: a, bootstrapGrantInput: o } = await this.prepareJoinApproval(n, r), s = [this.db.prepare(`UPDATE coordinator_join_requests
3867
+ SET status = ?, reviewed_at = ?, reviewed_by = ?
3868
+ WHERE request_id = ? AND status = 'pending'
3869
+ AND ${a.eligibilitySql} AND ${a.sourceSql}`).bind("approved", i, e.reviewedBy ?? null, e.requestId, ...a.eligibilityValues, ...a.sourceValues)], c = o ? X(12) : null;
3870
+ return s.push(...this.prepareJoinApprovalStatements(n, a, i, e.reviewedBy ?? null, o, c)), await this.executeJoinApprovalBatch(s, {
3871
+ requestId: e.requestId,
3872
+ guard: a
3873
+ }) ? this.readCompletedJoinReview(e.requestId, c) : this.classifyJoinReviewFailure(e.requestId, a);
3874
+ }
3875
+ async prepareJoinApproval(e, t) {
3876
+ let n = null, r = null;
3877
+ if (t) {
3878
+ if (r = await Q(this.db.prepare("SELECT * FROM enrolled_devices WHERE group_id = ? AND device_id = ? AND enabled = 1").bind(e.group_id, t.seedDeviceId)), !r) throw Error("bootstrap grant seed device is not enrolled in the group.");
3879
+ if (r = { ...r }, t.seedDeviceId === e.device_id) throw Error("bootstrap grant seed and worker device ids must differ.");
3880
+ n = {
3881
+ ...t,
3882
+ groupId: e.group_id,
3883
+ workerDeviceId: e.device_id
335
3884
  };
336
3885
  }
337
- if (this.db.batch) {
338
- let t = [];
339
- if (t.push(this.db.prepare("UPDATE coordinator_join_requests\n SET status = ?, reviewed_at = ?, reviewed_by = ?\n WHERE request_id = ? AND status = 'pending'").bind(i, r, e.reviewedBy ?? null, e.requestId)), e.approved && (t.push(this.db.prepare("INSERT INTO enrolled_devices(\n group_id, device_id, public_key, fingerprint, display_name, enabled, created_at\n )\n SELECT group_id, device_id, public_key, fingerprint, display_name, 1, ?\n FROM coordinator_join_requests\n WHERE request_id = ?\n AND status = 'approved'\n AND reviewed_at = ?\n ON CONFLICT(group_id, device_id) DO UPDATE SET\n public_key = excluded.public_key,\n fingerprint = excluded.fingerprint,\n display_name = excluded.display_name,\n enabled = 1").bind(L(), e.requestId, r)), a)) {
340
- o = B(12);
341
- let n = L();
342
- t.push(this.db.prepare("INSERT INTO coordinator_bootstrap_grants(\n grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n ) SELECT ?, ?, ?, ?, ?, ?, ?, NULL\n WHERE EXISTS (\n SELECT 1 FROM coordinator_join_requests\n WHERE request_id = ? AND status = 'approved' AND reviewed_at = ?\n )").bind(o, a.groupId, a.seedDeviceId, a.workerDeviceId, a.expiresAt, n, a.createdBy ?? null, e.requestId, r));
343
- }
344
- await this.db.batch(t);
345
- } else {
346
- let n = null;
347
- if (e.approved && (await this.enrollDevice(t.group_id, {
348
- deviceId: t.device_id,
349
- fingerprint: t.fingerprint,
350
- publicKey: t.public_key,
351
- displayName: (t.display_name ?? "").trim() || null
352
- }), a)) {
353
- let e = await this.createBootstrapGrant(a);
354
- n = e.grant_id, o = e.grant_id;
355
- }
356
- if (await Q(this.db.prepare("UPDATE coordinator_join_requests\n SET status = ?, reviewed_at = ?, reviewed_by = ?\n WHERE request_id = ? AND status = 'pending'").bind(i, r, e.reviewedBy ?? null, e.requestId)) === 0) {
357
- n && await this.revokeBootstrapGrant(n);
358
- let t = await Z(this.db.prepare("SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n FROM coordinator_join_requests WHERE request_id = ?").bind(e.requestId));
359
- return t ? {
360
- ...F(t),
361
- _no_transition: !0
362
- } : null;
3886
+ let i = It(await Q(this.db.prepare("SELECT public_key FROM enrolled_devices WHERE group_id = ? AND device_id = ?").bind(e.group_id, e.device_id))), a = tt(e, r, {
3887
+ recipient: await f(e.public_key),
3888
+ seed: r ? await f(r.public_key) : null,
3889
+ current: i === null ? null : await f(i)
3890
+ }, i);
3891
+ return await this.assertJoinOwnershipAvailable(a), {
3892
+ guard: a,
3893
+ bootstrapGrantInput: n
3894
+ };
3895
+ }
3896
+ async assertJoinOwnershipAvailable(e) {
3897
+ if ((await Bo(() => this.db.prepare(`SELECT (${e.revocationSql}) AS revoked`).bind(...e.revocationValues), ["revoked"])).revoked === 1) throw Error("device_revoked");
3898
+ let t = await Bo(() => this.db.prepare(`SELECT (${e.revocationSql}) AS revoked, (${e.ownershipSql}) AS owned`).bind(...e.revocationValues, ...e.ownershipValues), ["revoked", "owned"]);
3899
+ if (t.revoked === 1) throw Error("device_revoked");
3900
+ if (t.owned === 1) throw Error("device_ownership_requires_verified_identity");
3901
+ }
3902
+ async executeJoinApprovalBatch(e, t) {
3903
+ if (!this.db.batch) throw Error("join_review_unavailable");
3904
+ let n;
3905
+ try {
3906
+ n = await this.db.batch(e);
3907
+ } catch {
3908
+ let e;
3909
+ try {
3910
+ e = await Q(this.db.prepare("SELECT status FROM coordinator_join_requests WHERE request_id = ?").bind(t.requestId));
3911
+ } catch {
3912
+ throw Error("join_review_incomplete");
363
3913
  }
3914
+ throw e?.status === "pending" && await this.assertJoinOwnershipAvailable(t.guard), Error("join_review_incomplete");
364
3915
  }
365
- let s = await Z(this.db.prepare("SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n FROM coordinator_join_requests WHERE request_id = ?").bind(e.requestId));
366
- if (!s) return null;
367
- let c = a ? o ? await this.getBootstrapGrant(o) : await this.createBootstrapGrant(a) : null;
3916
+ if (n.length !== e.length) throw Error("join_review_incomplete");
3917
+ rt(n.at(-1));
3918
+ let r = n.slice(0, -1).map(at), i = r[0];
3919
+ if (i !== 0 && i !== 1 || r.some((e) => e !== i)) throw Error("join_review_incomplete");
3920
+ return i === 1;
3921
+ }
3922
+ async denyJoinRequest(e) {
3923
+ let t = this.db.prepare("UPDATE coordinator_join_requests SET status = 'denied', reviewed_at = ?, reviewed_by = ?\n WHERE request_id = ? AND status = 'pending'").bind(Y(), e.reviewedBy ?? null, e.requestId), n = this.db.batch ? at((await this.db.batch([t]))[0]) : await $(t);
3924
+ if (n === 0) return this.classifyJoinReviewFailure(e.requestId, null);
3925
+ if (n !== 1) throw Error("join_review_incomplete");
3926
+ return this.readCompletedJoinReview(e.requestId, null);
3927
+ }
3928
+ async readCompletedJoinReview(e, t) {
3929
+ let n = await Q(this.db.prepare(`SELECT ${me} FROM coordinator_join_requests WHERE request_id = ?`).bind(e));
3930
+ if (!n) throw Error("join_review_incomplete");
3931
+ let r = t ? await this.getBootstrapGrant(t) : null;
3932
+ if (t && !r) throw Error("join_review_incomplete");
368
3933
  return {
369
- ...F(s),
370
- bootstrap_grant: c
3934
+ ...n,
3935
+ bootstrap_grant: r
3936
+ };
3937
+ }
3938
+ prepareJoinApprovalStatements(e, t, n, r, i, a) {
3939
+ let o = `${t.eligibilitySql} AND EXISTS (SELECT 1 FROM coordinator_join_requests
3940
+ WHERE request_id = ? AND status = 'approved' AND reviewed_at = ? AND reviewed_by IS ?)`, s = [
3941
+ ...t.eligibilityValues,
3942
+ e.request_id,
3943
+ n,
3944
+ r
3945
+ ], c = `${o} AND EXISTS (SELECT 1 FROM enrolled_devices
3946
+ WHERE group_id = ? AND device_id = ? AND public_key = ? AND fingerprint = ? AND enabled = 1)`, l = [
3947
+ ...s,
3948
+ e.group_id,
3949
+ e.device_id,
3950
+ e.public_key,
3951
+ e.fingerprint
3952
+ ], u = [this.db.prepare(`INSERT INTO enrolled_devices(
3953
+ group_id, device_id, public_key, fingerprint, display_name, enabled, created_at)
3954
+ SELECT ?, ?, ?, ?, ?, 1, ? FROM (SELECT 1 WHERE changes() = 1) AS winner
3955
+ WHERE CASE WHEN ${o} AND ${t.sourceSql} THEN 1 ELSE json('join_review_incomplete') END
3956
+ ON CONFLICT(group_id, device_id) DO UPDATE SET public_key = excluded.public_key,
3957
+ fingerprint = excluded.fingerprint, display_name = excluded.display_name, enabled = 1
3958
+ WHERE CASE WHEN ${t.eligibilitySql} AND ${t.sourceSql}
3959
+ THEN 1 ELSE json('join_review_incomplete') END`).bind(e.group_id, e.device_id, e.public_key, e.fingerprint, e.display_name ?? null, Y(), ...s, ...t.sourceValues, ...t.eligibilityValues, ...t.sourceValues)];
3960
+ return i && a && u.push(this.db.prepare(`INSERT INTO coordinator_bootstrap_grants(
3961
+ grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at)
3962
+ SELECT ?, ?, ?, ?, ?, ?, ?, NULL FROM (SELECT 1 WHERE changes() = 1) AS winner
3963
+ WHERE CASE WHEN ${c} THEN 1 ELSE json('join_review_incomplete') END`).bind(a, i.groupId, i.seedDeviceId, i.workerDeviceId, i.expiresAt, Y(), i.createdBy ?? null, ...l)), u.push(this.prepareJoinApprovalConfirmation(e, n, r, t, c, l, i, a)), u;
3964
+ }
3965
+ prepareJoinApprovalConfirmation(e, t, n, r, i, a, o, s) {
3966
+ let c = `${i} AND (? IS NULL OR EXISTS (
3967
+ SELECT 1 FROM coordinator_bootstrap_grants WHERE grant_id = ? AND group_id = ?
3968
+ AND seed_device_id = ? AND worker_device_id = ? AND expires_at = ? AND revoked_at IS NULL))`, l = `NOT EXISTS (SELECT 1 FROM coordinator_join_requests
3969
+ WHERE request_id = ? AND status = 'approved' AND reviewed_at = ? AND reviewed_by IS ?)
3970
+ OR (${r.eligibilitySql})`;
3971
+ return this.db.prepare(`SELECT CASE WHEN changes() = 0 THEN
3972
+ CASE WHEN ${l} THEN 1 ELSE json('join_review_incomplete') END
3973
+ WHEN ${c} THEN 1 ELSE json('join_review_incomplete') END AS confirmed`).bind(e.request_id, t, n, ...r.eligibilityValues, ...a, s, s, e.group_id, o?.seedDeviceId ?? null, e.device_id, o?.expiresAt ?? null);
3974
+ }
3975
+ async classifyJoinReviewFailure(e, t) {
3976
+ let n = await Q(this.db.prepare(`SELECT ${me} FROM coordinator_join_requests WHERE request_id = ?`).bind(e));
3977
+ if (!n) return null;
3978
+ if (n.status !== "pending") return {
3979
+ ...n,
3980
+ _no_transition: !0
371
3981
  };
3982
+ throw t && await this.assertJoinOwnershipAvailable(t), Error("join_review_incomplete");
372
3983
  }
373
3984
  async createReciprocalApproval(e) {
374
3985
  let t = e.groupId.trim(), n = e.requestingDeviceId.trim(), r = e.requestedDeviceId.trim(), i = e.expectedIncomingRequestId !== void 0, a = e.expectedIncomingRequestId?.trim() ?? "";
375
3986
  if (!t || !n || !r) throw Error("groupId, requestingDeviceId, and requestedDeviceId are required.");
376
3987
  if (n === r) throw Error("requesting and requested device ids must differ.");
377
3988
  if (i) {
378
- let e = L();
379
- if (await Q(this.db.prepare("UPDATE coordinator_reciprocal_approvals\n SET status = 'completed', resolved_at = ?\n WHERE request_id = ?\n AND group_id = ?\n AND requesting_device_id = ?\n AND requested_device_id = ?\n AND status = 'pending'").bind(e, a, t, r, n)) !== 1) throw new u();
380
- return F(await Z(this.db.prepare("SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n FROM coordinator_reciprocal_approvals WHERE request_id = ?").bind(a)));
3989
+ let e = Y();
3990
+ if (await $(this.db.prepare("UPDATE coordinator_reciprocal_approvals\n SET status = 'completed', resolved_at = ?\n WHERE request_id = ?\n AND group_id = ?\n AND requesting_device_id = ?\n AND requested_device_id = ?\n AND status = 'pending'").bind(e, a, t, r, n)) !== 1) throw new Be();
3991
+ return J(await Q(this.db.prepare("SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n FROM coordinator_reciprocal_approvals WHERE request_id = ?").bind(a)));
381
3992
  }
382
- let o = R(n, r), s = await Z(this.db.prepare("SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n FROM coordinator_reciprocal_approvals\n WHERE group_id = ? AND requesting_device_id = ? AND requested_device_id = ? AND status = 'pending'\n ORDER BY created_at DESC LIMIT 1").bind(t, n, r));
383
- if (s) return F(s);
384
- let c = await Z(this.db.prepare("SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n FROM coordinator_reciprocal_approvals\n WHERE group_id = ? AND requesting_device_id = ? AND requested_device_id = ? AND status = 'pending'\n ORDER BY created_at DESC LIMIT 1").bind(t, r, n));
3993
+ let o = vo(n, r), s = await Q(this.db.prepare("SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n FROM coordinator_reciprocal_approvals\n WHERE group_id = ? AND requesting_device_id = ? AND requested_device_id = ? AND status = 'pending'\n ORDER BY created_at DESC LIMIT 1").bind(t, n, r));
3994
+ if (s) return J(s);
3995
+ let c = await Q(this.db.prepare("SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n FROM coordinator_reciprocal_approvals\n WHERE group_id = ? AND requesting_device_id = ? AND requested_device_id = ? AND status = 'pending'\n ORDER BY created_at DESC LIMIT 1").bind(t, r, n));
385
3996
  if (c) {
386
- let e = L();
387
- return await this.db.prepare("UPDATE coordinator_reciprocal_approvals SET status = 'completed', resolved_at = ? WHERE request_id = ?").bind(e, c.request_id).run(), F(await Z(this.db.prepare("SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n FROM coordinator_reciprocal_approvals WHERE request_id = ?").bind(c.request_id)));
3997
+ let e = Y();
3998
+ return await this.db.prepare("UPDATE coordinator_reciprocal_approvals SET status = 'completed', resolved_at = ? WHERE request_id = ?").bind(e, c.request_id).run(), J(await Q(this.db.prepare("SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n FROM coordinator_reciprocal_approvals WHERE request_id = ?").bind(c.request_id)));
388
3999
  }
389
- let l = B(12), d = L();
4000
+ let l = X(12), u = Y();
390
4001
  try {
391
- await this.db.prepare("INSERT INTO coordinator_reciprocal_approvals(\n request_id,\n group_id,\n requesting_device_id,\n requested_device_id,\n pending_pair_low_device_id,\n pending_pair_high_device_id,\n status,\n created_at,\n resolved_at\n ) VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, NULL)").bind(l, t, n, r, o.low, o.high, d).run();
4002
+ await this.db.prepare("INSERT INTO coordinator_reciprocal_approvals(\n request_id,\n group_id,\n requesting_device_id,\n requested_device_id,\n pending_pair_low_device_id,\n pending_pair_high_device_id,\n status,\n created_at,\n resolved_at\n ) VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, NULL)").bind(l, t, n, r, o.low, o.high, u).run();
392
4003
  } catch (e) {
393
- if (!z(e)) throw e;
394
- let i = await Z(this.db.prepare("SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n FROM coordinator_reciprocal_approvals\n WHERE group_id = ? AND requesting_device_id = ? AND requested_device_id = ? AND status = 'pending'\n ORDER BY created_at DESC LIMIT 1").bind(t, n, r));
395
- if (i) return F(i);
396
- let a = await Z(this.db.prepare("SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n FROM coordinator_reciprocal_approvals\n WHERE group_id = ? AND requesting_device_id = ? AND requested_device_id = ? AND status = 'pending'\n ORDER BY created_at DESC LIMIT 1").bind(t, r, n));
4004
+ if (!yo(e)) throw e;
4005
+ let i = await Q(this.db.prepare("SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n FROM coordinator_reciprocal_approvals\n WHERE group_id = ? AND requesting_device_id = ? AND requested_device_id = ? AND status = 'pending'\n ORDER BY created_at DESC LIMIT 1").bind(t, n, r));
4006
+ if (i) return J(i);
4007
+ let a = await Q(this.db.prepare("SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n FROM coordinator_reciprocal_approvals\n WHERE group_id = ? AND requesting_device_id = ? AND requested_device_id = ? AND status = 'pending'\n ORDER BY created_at DESC LIMIT 1").bind(t, r, n));
397
4008
  if (a) {
398
- let e = L();
399
- return await this.db.prepare("UPDATE coordinator_reciprocal_approvals SET status = 'completed', resolved_at = ? WHERE request_id = ?").bind(e, a.request_id).run(), F(await Z(this.db.prepare("SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n FROM coordinator_reciprocal_approvals WHERE request_id = ?").bind(a.request_id)));
4009
+ let e = Y();
4010
+ return await this.db.prepare("UPDATE coordinator_reciprocal_approvals SET status = 'completed', resolved_at = ? WHERE request_id = ?").bind(e, a.request_id).run(), J(await Q(this.db.prepare("SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n FROM coordinator_reciprocal_approvals WHERE request_id = ?").bind(a.request_id)));
400
4011
  }
401
4012
  throw e;
402
4013
  }
403
- return F(await Z(this.db.prepare("SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n FROM coordinator_reciprocal_approvals WHERE request_id = ?").bind(l)));
4014
+ return J(await Q(this.db.prepare("SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n FROM coordinator_reciprocal_approvals WHERE request_id = ?").bind(l)));
4015
+ }
4016
+ async getBootstrapParticipantSource(e, t) {
4017
+ let n = await Q(this.db.prepare(Fn).bind(e, t));
4018
+ return Re(n);
404
4019
  }
405
4020
  async createBootstrapGrant(e) {
406
- let t = M(e), n = B(12), r = L();
407
- return await this.db.prepare("INSERT INTO coordinator_bootstrap_grants(\n grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, NULL)").bind(n, t.groupId, t.seedDeviceId, t.workerDeviceId, t.expiresAt, r, t.createdBy).run(), F(await Z(this.db.prepare("SELECT grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n FROM coordinator_bootstrap_grants WHERE grant_id = ?").bind(n)));
4021
+ let t = nn(e);
4022
+ try {
4023
+ let e = () => this.db.prepare(Dn);
4024
+ if (await Q(e().bind(t.seedDeviceId, null, t.workerDeviceId, null))) throw Error("device_revoked");
4025
+ let n = await this.getBootstrapParticipantSource(t.groupId, t.seedDeviceId), r = await this.getBootstrapParticipantSource(t.groupId, t.workerDeviceId), i = [
4026
+ t.seedDeviceId,
4027
+ n ? await f(n.public_key) : null,
4028
+ t.workerDeviceId,
4029
+ r ? await f(r.public_key) : null
4030
+ ];
4031
+ if (await Q(e().bind(...i))) throw Error("device_revoked");
4032
+ let a = jn(t, {
4033
+ grantId: X(12),
4034
+ createdAt: Y()
4035
+ }, {
4036
+ seed: n,
4037
+ worker: r
4038
+ }, i), o = await Q(this.db.prepare(pt).bind(...a));
4039
+ if (o) return J(o);
4040
+ throw await Q(e().bind(...i)) ? Error("device_revoked") : Error("bootstrap_grant_write_incomplete");
4041
+ } catch (e) {
4042
+ throw e instanceof Error && e.message === "device_revoked" ? e : Error("bootstrap_grant_write_incomplete");
4043
+ }
408
4044
  }
409
4045
  async getScope(e) {
410
- let t = await Z(this.db.prepare("SELECT scope_id, label, kind, authority_type, coordinator_id, group_id,\n manifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n FROM coordinator_scopes WHERE scope_id = ?").bind(e));
411
- return t ? F(t) : null;
4046
+ let t = await Q(this.db.prepare("SELECT scope_id, label, kind, authority_type, coordinator_id, group_id,\n manifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n FROM coordinator_scopes WHERE scope_id = ?").bind(e));
4047
+ return t ? J(t) : null;
412
4048
  }
413
4049
  async getScopeMembership(e, t) {
414
- let n = await Z(this.db.prepare("SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n manifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n FROM coordinator_scope_memberships\n WHERE scope_id = ? AND device_id = ?").bind(e, t));
415
- return n ? F(n) : null;
4050
+ let n = await Q(this.db.prepare("SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n manifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n FROM coordinator_scope_memberships\n WHERE scope_id = ? AND device_id = ?").bind(e, t));
4051
+ return n ? J(n) : null;
416
4052
  }
417
4053
  async createScope(e) {
418
- let t = i(e);
4054
+ let t = Rt(e);
419
4055
  if (await this.getScope(t.scopeId)) throw Error("scopeId already exists.");
420
- let n = L();
4056
+ let n = Y();
421
4057
  await this.db.prepare("INSERT INTO coordinator_scopes(\n scope_id, label, kind, authority_type, coordinator_id, group_id,\n manifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").bind(t.scopeId, t.label, t.kind, t.authorityType, t.coordinatorId, t.groupId, t.manifestIssuerDeviceId, t.membershipEpoch, t.manifestHash, t.status, n, n).run();
422
4058
  let r = await this.getScope(t.scopeId);
423
4059
  if (!r) throw Error("scope insert returned no row");
424
4060
  return r;
425
4061
  }
426
4062
  async updateScope(e) {
427
- let t = h(e.scopeId), n = t ? await this.getScope(t) : null;
4063
+ let t = b(e.scopeId), n = t ? await this.getScope(t) : null;
428
4064
  if (!n) return null;
429
- let r = S(e, n);
430
- return await this.db.prepare("UPDATE coordinator_scopes\n SET label = ?,\n kind = ?,\n authority_type = ?,\n coordinator_id = ?,\n group_id = ?,\n manifest_issuer_device_id = ?,\n membership_epoch = ?,\n manifest_hash = ?,\n status = ?,\n updated_at = ?\n WHERE scope_id = ?").bind(r.label, r.kind, r.authorityType, r.coordinatorId, r.groupId, r.manifestIssuerDeviceId, r.membershipEpoch, r.manifestHash, r.status, L(), r.scopeId).run(), await this.getScope(r.scopeId);
4065
+ let r = vn(e, n);
4066
+ return await this.db.prepare("UPDATE coordinator_scopes\n SET label = ?,\n kind = ?,\n authority_type = ?,\n coordinator_id = ?,\n group_id = ?,\n manifest_issuer_device_id = ?,\n membership_epoch = ?,\n manifest_hash = ?,\n status = ?,\n updated_at = ?\n WHERE scope_id = ?").bind(r.label, r.kind, r.authorityType, r.coordinatorId, r.groupId, r.manifestIssuerDeviceId, r.membershipEpoch, r.manifestHash, r.status, Y(), r.scopeId).run(), await this.getScope(r.scopeId);
431
4067
  }
432
4068
  async listScopes(e = {}) {
433
- let t = [], n = [], r = h(e.coordinatorId), i = h(e.groupId), a = h(e.status);
4069
+ let t = [], n = [], r = b(e.coordinatorId), i = b(e.groupId), a = b(e.status);
434
4070
  r && (t.push("coordinator_id = ?"), n.push(r)), i && (t.push("group_id = ?"), n.push(i)), a ? (t.push("status = ?"), n.push(a)) : e.includeInactive || t.push("status = 'active'");
435
4071
  let o = t.length ? `WHERE ${t.join(" AND ")}` : "", s = this.db.prepare(`SELECT scope_id, label, kind, authority_type, coordinator_id, group_id,
436
4072
  manifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at
437
4073
  FROM coordinator_scopes ${o}
438
4074
  ORDER BY coordinator_id ASC, group_id ASC, scope_id ASC`);
439
- return (await X(n.length ? s.bind(...n) : s)).map((e) => F(e));
440
- }
441
- async grantScopeMembership(t) {
442
- let n = e(t.effectId), i = p(t), a = await K(this.db, n);
443
- if (a) return d(a, "grant", i), s(a);
444
- let o = h(t.scopeId), c = h(t.deviceId), l = o ? await this.getScope(o) : null;
445
- if (!l) throw new f("scope_not_found");
446
- if (l.status !== "active") throw new f("scope_inactive");
447
- let u = o && c ? await this.getScopeMembership(o, c) : null, m = r(t, l, u);
448
- if (m.groupId && !await this.getEnrollment(m.groupId, m.deviceId)) throw new f("device_not_enrolled");
449
- let g = L();
450
- await J(this.db, [
451
- this.db.prepare("INSERT INTO coordinator_scope_memberships(\n scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n manifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n ) SELECT ?, ?, ?, 'active', ?, ?, ?, ?, ?, ?, ?\n WHERE NOT EXISTS (\n SELECT 1 FROM coordinator_scope_membership_effect_receipts WHERE effect_id = ?\n )\n ON CONFLICT(scope_id, device_id) DO UPDATE SET\n role = excluded.role,\n status = 'active',\n membership_epoch = excluded.membership_epoch,\n coordinator_id = excluded.coordinator_id,\n group_id = excluded.group_id,\n manifest_issuer_device_id = excluded.manifest_issuer_device_id,\n manifest_hash = excluded.manifest_hash,\n signed_manifest_json = excluded.signed_manifest_json,\n updated_at = excluded.updated_at\n WHERE excluded.membership_epoch > coordinator_scope_memberships.membership_epoch\n OR (\n excluded.membership_epoch = coordinator_scope_memberships.membership_epoch\n AND coordinator_scope_memberships.status != 'revoked'\n )").bind(m.scopeId, m.deviceId, m.role, m.membershipEpoch, m.coordinatorId, m.groupId, m.manifestIssuerDeviceId, m.manifestHash, m.signedManifestJson, g, n),
452
- q(this.db, {
453
- effectId: n,
454
- requestJson: i,
455
- scopeId: m.scopeId,
456
- deviceId: m.deviceId,
457
- createdAt: g
4075
+ return (await Z(n.length ? s.bind(...n) : s)).map((e) => J(e));
4076
+ }
4077
+ async getScopeAuthorization(e) {
4078
+ try {
4079
+ let t = Ht(e), n = await this.db.prepare(`SELECT ${a.join(", ")} FROM coordinator_scopes WHERE scope_id = ?`).bind(t.scopeId).first();
4080
+ if (n === null) return {
4081
+ kind: "rejected",
4082
+ error: "scope_not_found"
4083
+ };
4084
+ y(n, a);
4085
+ let r = { ...n };
4086
+ if (r.scope_id !== t.scopeId) throw Error("scope_authorization_unavailable");
4087
+ let i = ie(r, t.groupId);
4088
+ if (i) return {
4089
+ kind: "rejected",
4090
+ error: i
4091
+ };
4092
+ let o = await this.db.prepare("SELECT group_id, archived_at FROM groups WHERE group_id = ?").bind(t.groupId).first();
4093
+ if (o === null) return {
4094
+ kind: "rejected",
4095
+ error: "scope_source_mismatch"
4096
+ };
4097
+ if (y(o, ["group_id"]), o.group_id !== t.groupId) throw Error("scope_authorization_unavailable");
4098
+ if (o.archived_at !== null) return y(o, ["archived_at"]), {
4099
+ kind: "rejected",
4100
+ error: "group_archived"
4101
+ };
4102
+ let s = await this.captureScopeAuthorizationMembers(r, t.groupId), c = await this.db.prepare(qt).bind(JSON.stringify([r]), JSON.stringify(s)).first();
4103
+ if (y(c, a), !c || a.some((e) => c[e] !== r[e])) throw Error("scope_authorization_unavailable");
4104
+ return {
4105
+ kind: "authorized",
4106
+ authorizationVersion: 1,
4107
+ scope: r,
4108
+ members: Ee(c.members_json, s)
4109
+ };
4110
+ } catch {
4111
+ return {
4112
+ kind: "rejected",
4113
+ error: "scope_authorization_unavailable"
4114
+ };
4115
+ }
4116
+ }
4117
+ async captureScopeAuthorizationMembers(e, t) {
4118
+ let n = jo(await this.db.prepare(`SELECT ${Oe.join(", ")} FROM coordinator_scope_memberships WHERE scope_id = ? ORDER BY device_id ASC`).bind(e.scope_id).all()).flatMap((t) => (y(t, ["status"]), t.status === "active" ? (y(t, Oe), Se(e, t) ? [{ ...t }] : []) : [])), r = await this.captureScopeAuthorizationEnrollments(n, t), i = [];
4119
+ for (let e of n) {
4120
+ let t = r.get(e.device_id);
4121
+ t?.enabled === 1 && i.push({
4122
+ membership: e,
4123
+ enrollment: t
4124
+ });
4125
+ }
4126
+ let a = [];
4127
+ for (let e of i) {
4128
+ let t = await f(e.enrollment.public_key);
4129
+ t !== null && a.push({
4130
+ ...e,
4131
+ keyId: t
4132
+ });
4133
+ }
4134
+ return a;
4135
+ }
4136
+ async captureScopeAuthorizationEnrollments(e, t) {
4137
+ let n = new Set(e.map((e) => e.device_id)), r = await this.db.prepare(`SELECT ${g.join(", ")} FROM enrolled_devices WHERE group_id = ?
4138
+ AND device_id IN (SELECT value FROM json_each(?))`).bind(t, JSON.stringify([...n])).all(), i = /* @__PURE__ */ new Map();
4139
+ for (let e of jo(r)) {
4140
+ if (y(e, g), e.group_id !== t || !n.delete(e.device_id)) throw Error("scope_authorization_unavailable");
4141
+ i.set(e.device_id, { ...e });
4142
+ }
4143
+ return i;
4144
+ }
4145
+ async grantScopeMembership(e) {
4146
+ let t = _e(e.effectId), n = $e(e), r = await To(this.db, t);
4147
+ if (r) return Ke(r, "grant", n), oe(r);
4148
+ let i = b(e.scopeId), a = b(e.deviceId), o = i ? await this.getScope(i) : null;
4149
+ if (!o) throw new ce("scope_not_found");
4150
+ if (o.status !== "active") throw new ce("scope_inactive");
4151
+ let s = i && a ? await this.getScopeMembership(i, a) : null, c = ut(e, o, s);
4152
+ if (c.groupId && !await this.getEnrollment(c.groupId, c.deviceId)) throw new ce("device_not_enrolled");
4153
+ let l = Y();
4154
+ await Oo(this.db, [
4155
+ this.db.prepare("INSERT INTO coordinator_scope_memberships(\n scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n manifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n ) SELECT ?, ?, ?, 'active', ?, ?, ?, ?, ?, ?, ?\n WHERE NOT EXISTS (\n SELECT 1 FROM coordinator_scope_membership_effect_receipts WHERE effect_id = ?\n )\n ON CONFLICT(scope_id, device_id) DO UPDATE SET\n role = excluded.role,\n status = 'active',\n membership_epoch = excluded.membership_epoch,\n coordinator_id = excluded.coordinator_id,\n group_id = excluded.group_id,\n manifest_issuer_device_id = excluded.manifest_issuer_device_id,\n manifest_hash = excluded.manifest_hash,\n signed_manifest_json = excluded.signed_manifest_json,\n updated_at = excluded.updated_at\n WHERE excluded.membership_epoch > coordinator_scope_memberships.membership_epoch\n OR (\n excluded.membership_epoch = coordinator_scope_memberships.membership_epoch\n AND coordinator_scope_memberships.status != 'revoked'\n )").bind(c.scopeId, c.deviceId, c.role, c.membershipEpoch, c.coordinatorId, c.groupId, c.manifestIssuerDeviceId, c.manifestHash, c.signedManifestJson, l, t),
4156
+ Eo(this.db, {
4157
+ effectId: t,
4158
+ requestJson: n,
4159
+ scopeId: c.scopeId,
4160
+ deviceId: c.deviceId,
4161
+ createdAt: l
458
4162
  }),
459
- G(this.db, {
460
- effectId: n,
461
- requestJson: i,
4163
+ wo(this.db, {
4164
+ effectId: t,
4165
+ requestJson: n,
462
4166
  action: "grant",
463
- previous: u,
464
- scopeId: m.scopeId,
465
- deviceId: m.deviceId,
4167
+ previous: s,
4168
+ scopeId: c.scopeId,
4169
+ deviceId: c.deviceId,
466
4170
  status: "active",
467
- membershipEpoch: m.membershipEpoch,
468
- updatedAt: g,
469
- actorType: m.actorType,
470
- actorId: m.actorId,
471
- createdAt: g
4171
+ membershipEpoch: c.membershipEpoch,
4172
+ updatedAt: l,
4173
+ actorType: c.actorType,
4174
+ actorId: c.actorId,
4175
+ createdAt: l
472
4176
  })
473
4177
  ]);
474
- let _ = await K(this.db, n);
475
- if (!_) throw Error("scope membership grant was not applied.");
476
- return d(_, "grant", i), s(_);
477
- }
478
- async revokeScopeMembership(n) {
479
- let r = h(n.scopeId), i = h(n.deviceId);
480
- if (!r || !i) throw Error("scopeId and deviceId are required.");
481
- let a = e(n.effectId), o = v(n), s = await K(this.db, a);
482
- if (s) return d(s, "revoke", o), s.outcome_applied === 1;
483
- let c = n.membershipEpoch == null ? null : t(n.membershipEpoch), l = h(n.groupId), u = l ? await this.getScope(r) : null;
484
- if (l && l !== u?.group_id) throw new f("scope_group_mismatch");
485
- let p = await this.getScopeMembership(r, i);
486
- if (c != null && p && c <= p.membership_epoch) throw Error("membershipEpoch must increase on revoke.");
487
- let m = L(), g = c ?? (p?.membership_epoch ?? -1) + 1, _ = this.db.prepare("UPDATE coordinator_scope_memberships\n SET status = 'revoked',\n membership_epoch = CASE WHEN ? IS NULL THEN membership_epoch + 1 ELSE ? END,\n manifest_hash = COALESCE(?, manifest_hash),\n signed_manifest_json = COALESCE(?, signed_manifest_json),\n updated_at = ?\n WHERE scope_id = ? AND device_id = ? AND membership_epoch = ? AND status = ?\n AND NOT EXISTS (\n SELECT 1 FROM coordinator_scope_membership_effect_receipts WHERE effect_id = ?\n )").bind(c, c, h(n.manifestHash), h(n.signedManifestJson), m, r, i, p?.membership_epoch ?? -1, p?.status ?? "", a), y = ne(this.db, {
488
- effectId: a,
489
- requestJson: o,
490
- scopeId: r,
491
- deviceId: i,
492
- createdAt: m
493
- }), b = G(this.db, {
494
- effectId: a,
495
- requestJson: o,
4178
+ let u = await To(this.db, t);
4179
+ if (!u) throw Error("scope membership grant was not applied.");
4180
+ return Ke(u, "grant", n), oe(u);
4181
+ }
4182
+ async revokeScopeMembership(e) {
4183
+ let t = b(e.scopeId), n = b(e.deviceId);
4184
+ if (!t || !n) throw Error("scopeId and deviceId are required.");
4185
+ let r = _e(e.effectId), i = dn(e), a = await To(this.db, r);
4186
+ if (a) return Ke(a, "revoke", i), a.outcome_applied === 1;
4187
+ let o = e.membershipEpoch == null ? null : vt(e.membershipEpoch), s = b(e.groupId), c = s ? await this.getScope(t) : null;
4188
+ if (s && s !== c?.group_id) throw new ce("scope_group_mismatch");
4189
+ let l = await this.getScopeMembership(t, n);
4190
+ if (o != null && l && o <= l.membership_epoch) throw Error("membershipEpoch must increase on revoke.");
4191
+ let u = Y(), d = o ?? (l?.membership_epoch ?? -1) + 1, f = this.db.prepare("UPDATE coordinator_scope_memberships\n SET status = 'revoked',\n membership_epoch = CASE WHEN ? IS NULL THEN membership_epoch + 1 ELSE ? END,\n manifest_hash = COALESCE(?, manifest_hash),\n signed_manifest_json = COALESCE(?, signed_manifest_json),\n updated_at = ?\n WHERE scope_id = ? AND device_id = ? AND membership_epoch = ? AND status = ?\n AND NOT EXISTS (\n SELECT 1 FROM coordinator_scope_membership_effect_receipts WHERE effect_id = ?\n )").bind(o, o, b(e.manifestHash), b(e.signedManifestJson), u, t, n, l?.membership_epoch ?? -1, l?.status ?? "", r), p = Do(this.db, {
4192
+ effectId: r,
4193
+ requestJson: i,
4194
+ scopeId: t,
4195
+ deviceId: n,
4196
+ createdAt: u
4197
+ }), m = wo(this.db, {
4198
+ effectId: r,
4199
+ requestJson: i,
496
4200
  action: "revoke",
497
- previous: p,
498
- scopeId: r,
499
- deviceId: i,
4201
+ previous: l,
4202
+ scopeId: t,
4203
+ deviceId: n,
500
4204
  status: "revoked",
501
- membershipEpoch: g,
502
- updatedAt: m,
503
- actorType: h(n.actorType),
504
- actorId: h(n.actorId),
505
- createdAt: m
4205
+ membershipEpoch: d,
4206
+ updatedAt: u,
4207
+ actorType: b(e.actorType),
4208
+ actorId: b(e.actorId),
4209
+ createdAt: u
506
4210
  });
507
4211
  try {
508
- await J(this.db, [
509
- _,
510
- y,
511
- b
4212
+ await Oo(this.db, [
4213
+ f,
4214
+ p,
4215
+ m
512
4216
  ]);
513
4217
  } catch (e) {
514
- let t = await this.getScopeMembership(r, i);
515
- if (p && (!t || t.membership_epoch !== p.membership_epoch || t.status !== p.status)) return !1;
4218
+ let r = await this.getScopeMembership(t, n);
4219
+ if (l && (!r || r.membership_epoch !== l.membership_epoch || r.status !== l.status)) return !1;
516
4220
  throw e;
517
4221
  }
518
- let x = await K(this.db, a);
519
- if (!x) throw Error("scope membership revoke receipt was not persisted.");
520
- return d(x, "revoke", o), x.outcome_applied === 1;
4222
+ let h = await To(this.db, r);
4223
+ if (!h) throw Error("scope membership revoke receipt was not persisted.");
4224
+ return Ke(h, "revoke", i), h.outcome_applied === 1;
521
4225
  }
522
4226
  async listScopeMemberships(e, t = !1) {
523
- let n = h(e);
4227
+ let n = b(e);
524
4228
  if (!n) throw Error("scopeId is required.");
525
4229
  let r = t ? "" : "AND status = 'active'";
526
- return (await X(this.db.prepare(`SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,
4230
+ return (await Z(this.db.prepare(`SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,
527
4231
  manifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at
528
4232
  FROM coordinator_scope_memberships
529
4233
  WHERE scope_id = ? ${r}
530
- ORDER BY device_id ASC`).bind(n))).map((e) => F(e));
4234
+ ORDER BY device_id ASC`).bind(n))).map((e) => J(e));
531
4235
  }
532
4236
  async listDeviceScopeMemberships(e, t = !1) {
533
- let n = h(e);
4237
+ let n = b(e);
534
4238
  if (!n) throw Error("deviceId is required.");
535
4239
  let r = t ? "" : "AND status = 'active'";
536
- return (await X(this.db.prepare(`SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,
4240
+ return (await Z(this.db.prepare(`SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,
537
4241
  manifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at
538
4242
  FROM coordinator_scope_memberships
539
4243
  WHERE device_id = ? ${r}
540
- ORDER BY scope_id ASC`).bind(n))).map((e) => F(e));
4244
+ ORDER BY scope_id ASC`).bind(n))).map((e) => J(e));
541
4245
  }
542
4246
  async listScopeMembershipAuditEvents(e) {
543
- let t = h(e.scopeId);
4247
+ let t = b(e.scopeId);
544
4248
  if (!t) throw Error("scopeId is required.");
545
- let r = h(e.deviceId), i = n(e.limit), a = r ? "scope_id = ? AND device_id = ?" : "scope_id = ?", o = r ? [
4249
+ let n = b(e.deviceId), r = xn(e.limit), i = n ? "scope_id = ? AND device_id = ?" : "scope_id = ?", a = n ? [
546
4250
  t,
547
- r,
548
- i
549
- ] : [t, i];
550
- return (await X(this.db.prepare(`SELECT event_id, effect_id, action, scope_id, device_id, role, status, membership_epoch,
4251
+ n,
4252
+ r
4253
+ ] : [t, r];
4254
+ return (await Z(this.db.prepare(`SELECT event_id, effect_id, action, scope_id, device_id, role, status, membership_epoch,
551
4255
  previous_role, previous_status, previous_membership_epoch,
552
4256
  coordinator_id, group_id, actor_type, actor_id, manifest_hash, created_at
553
4257
  FROM coordinator_scope_membership_audit_log
554
- WHERE ${a}
4258
+ WHERE ${i}
555
4259
  ORDER BY event_id ASC
556
- LIMIT ?`).bind(...o))).map((e) => F(e));
4260
+ LIMIT ?`).bind(...a))).map((e) => J(e));
557
4261
  }
558
4262
  async getBootstrapGrant(e) {
559
- let t = await Z(this.db.prepare("SELECT grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n FROM coordinator_bootstrap_grants WHERE grant_id = ?").bind(e));
560
- return t ? F(t) : null;
4263
+ let t = await Q(this.db.prepare("SELECT grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n FROM coordinator_bootstrap_grants WHERE grant_id = ?").bind(e));
4264
+ return t ? J(t) : null;
4265
+ }
4266
+ async getBootstrapGrantAuthorization(e) {
4267
+ try {
4268
+ let t = m(e), n = await Q(this.db.prepare(d).bind(t.grantId)), r = te(t, n);
4269
+ if (r) return Gt(r);
4270
+ if (!n) return Gt("bootstrap_authorization_unavailable");
4271
+ let i = { ...n }, a = {
4272
+ seed: i.seed_enrollment_public_key === null ? null : await f(i.seed_enrollment_public_key),
4273
+ worker: i.worker_enrollment_public_key === null ? null : await f(i.worker_enrollment_public_key)
4274
+ }, o = An(t, i, a), s = await Q(this.db.prepare(o.sql).bind(...o.values));
4275
+ return Ve(s);
4276
+ } catch {
4277
+ return Gt("bootstrap_authorization_unavailable");
4278
+ }
561
4279
  }
562
4280
  async listBootstrapGrants(e) {
563
- return (await X(this.db.prepare("SELECT grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n FROM coordinator_bootstrap_grants WHERE group_id = ?\n ORDER BY created_at DESC, grant_id DESC").bind(e))).map((e) => F(e));
4281
+ return (await Z(this.db.prepare("SELECT grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n FROM coordinator_bootstrap_grants WHERE group_id = ?\n ORDER BY created_at DESC, grant_id DESC").bind(e))).map((e) => J(e));
564
4282
  }
565
- async revokeBootstrapGrant(e, t = L()) {
566
- return await Q(this.db.prepare("UPDATE coordinator_bootstrap_grants\n SET revoked_at = COALESCE(revoked_at, ?)\n WHERE grant_id = ?").bind(t, e)) > 0;
4283
+ async revokeBootstrapGrant(e, t = Y()) {
4284
+ return await $(this.db.prepare("UPDATE coordinator_bootstrap_grants\n SET revoked_at = COALESCE(revoked_at, ?)\n WHERE grant_id = ?").bind(t, e)) > 0;
567
4285
  }
568
4286
  async listReciprocalApprovals(e) {
569
4287
  let t = e.direction === "incoming" ? "requested_device_id" : "requesting_device_id", n = e.status?.trim() || "pending";
570
- return (await X(this.db.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at
4288
+ return (await Z(this.db.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at
571
4289
  FROM coordinator_reciprocal_approvals
572
4290
  WHERE group_id = ? AND ${t} = ? AND status = ?
573
- ORDER BY created_at ASC, request_id ASC`).bind(e.groupId, e.deviceId, n))).map((e) => F(e));
4291
+ ORDER BY created_at ASC, request_id ASC`).bind(e.groupId, e.deviceId, n))).map((e) => J(e));
574
4292
  }
575
4293
  async createLegacyTeamCompletion(e, t) {
576
- let [n] = _([e]);
4294
+ let [n] = s([e]);
577
4295
  if (!n) throw Error("completion_manifest_invalid");
578
4296
  let r = await this.getGroup(n);
579
4297
  if (!r) throw Error("group_not_found");
580
4298
  if (r.archived_at) throw Error("group_archived");
581
- let i = C(t), a = JSON.parse(i);
582
- b(a);
583
- let o = await Z(this.db.prepare("SELECT manifest_json FROM coordinator_legacy_team_completions\n WHERE group_id = ? AND candidate_ref = ?").bind(n, a.candidate_ref));
4299
+ let i = Pe(t), a = JSON.parse(i);
4300
+ Qe(a);
4301
+ let o = await Q(this.db.prepare("SELECT manifest_json FROM coordinator_legacy_team_completions\n WHERE group_id = ? AND candidate_ref = ?").bind(n, a.candidate_ref));
584
4302
  if (o) {
585
- if (o.manifest_json !== i) throw new g();
4303
+ if (o.manifest_json !== i) throw new ve();
586
4304
  return {
587
4305
  status: "existing",
588
- manifest: y(JSON.parse(o.manifest_json))
4306
+ manifest: Ye(JSON.parse(o.manifest_json))
589
4307
  };
590
4308
  }
591
- let s = await X(this.db.prepare("SELECT DISTINCT\n requested.scope_id,\n scope.authority_type,\n scope.coordinator_id,\n scope.group_id,\n scope.status\n FROM (\n SELECT json_extract(value, '$.scope_id') AS scope_id\n FROM json_each(?, '$.project_mappings')\n ) AS requested\n LEFT JOIN coordinator_scopes AS scope ON scope.scope_id = requested.scope_id").bind(i)), c = w(a, n, s), l = await Q(this.db.prepare("INSERT OR IGNORE INTO coordinator_legacy_team_completions(\n group_id, candidate_ref, manifest_version, manifest_json, completed_at, created_at\n ) SELECT ?, ?, ?, ?, ?, ?\n FROM groups\n WHERE group_id = ? AND archived_at IS NULL\n AND NOT EXISTS (\n SELECT 1\n FROM json_each(?, '$.project_mappings') AS requested\n LEFT JOIN coordinator_scopes AS scope\n ON scope.scope_id = json_extract(requested.value, '$.scope_id')\n AND scope.authority_type = 'coordinator'\n AND scope.coordinator_id = ?\n AND scope.group_id = ?\n AND scope.status = 'active'\n WHERE scope.scope_id IS NULL\n )\n AND NOT EXISTS (\n SELECT 1 FROM enrolled_devices AS enrolled\n WHERE enrolled.group_id = ?\n AND NOT EXISTS (\n SELECT 1 FROM json_each(?, '$.device_decisions') AS requested\n WHERE json_extract(requested.value, '$.device_id') = enrolled.device_id\n AND json_extract(requested.value, '$.key_fingerprint') = enrolled.fingerprint\n AND json_extract(requested.value, '$.enabled') = enrolled.enabled\n )\n )\n AND NOT EXISTS (\n SELECT 1 FROM json_each(?, '$.device_decisions') AS requested\n WHERE json_extract(requested.value, '$.decision') = 'included'\n AND NOT EXISTS (\n SELECT 1 FROM enrolled_devices AS enrolled\n WHERE enrolled.group_id = ?\n AND enrolled.device_id = json_extract(requested.value, '$.device_id')\n AND enrolled.fingerprint = json_extract(requested.value, '$.key_fingerprint')\n AND enrolled.enabled = 1\n )\n )").bind(n, a.candidate_ref, a.version, i, a.completed_at, L(), n, i, c, n, n, i, i, n)), u = await Z(this.db.prepare("SELECT manifest_json FROM coordinator_legacy_team_completions\n WHERE group_id = ? AND candidate_ref = ?").bind(n, a.candidate_ref));
592
- if (!u) {
4309
+ let c = await Z(this.db.prepare("SELECT DISTINCT\n requested.scope_id,\n scope.authority_type,\n scope.coordinator_id,\n scope.group_id,\n scope.status\n FROM (\n SELECT json_extract(value, '$.scope_id') AS scope_id\n FROM json_each(?, '$.project_mappings')\n ) AS requested\n LEFT JOIN coordinator_scopes AS scope ON scope.scope_id = requested.scope_id").bind(i)), l = Ge(a, n, c), u = await $(this.db.prepare("INSERT OR IGNORE INTO coordinator_legacy_team_completions(\n group_id, candidate_ref, manifest_version, manifest_json, completed_at, created_at\n ) SELECT ?, ?, ?, ?, ?, ?\n FROM groups\n WHERE group_id = ? AND archived_at IS NULL\n AND NOT EXISTS (\n SELECT 1\n FROM json_each(?, '$.project_mappings') AS requested\n LEFT JOIN coordinator_scopes AS scope\n ON scope.scope_id = json_extract(requested.value, '$.scope_id')\n AND scope.authority_type = 'coordinator'\n AND scope.coordinator_id = ?\n AND scope.group_id = ?\n AND scope.status = 'active'\n WHERE scope.scope_id IS NULL\n )\n AND NOT EXISTS (\n SELECT 1 FROM enrolled_devices AS enrolled\n WHERE enrolled.group_id = ?\n AND NOT EXISTS (\n SELECT 1 FROM json_each(?, '$.device_decisions') AS requested\n WHERE json_extract(requested.value, '$.device_id') = enrolled.device_id\n AND json_extract(requested.value, '$.key_fingerprint') = enrolled.fingerprint\n AND json_extract(requested.value, '$.enabled') = enrolled.enabled\n )\n )\n AND NOT EXISTS (\n SELECT 1 FROM json_each(?, '$.device_decisions') AS requested\n WHERE json_extract(requested.value, '$.decision') = 'included'\n AND NOT EXISTS (\n SELECT 1 FROM enrolled_devices AS enrolled\n WHERE enrolled.group_id = ?\n AND enrolled.device_id = json_extract(requested.value, '$.device_id')\n AND enrolled.fingerprint = json_extract(requested.value, '$.key_fingerprint')\n AND enrolled.enabled = 1\n )\n )").bind(n, a.candidate_ref, a.version, i, a.completed_at, Y(), n, i, l, n, n, i, i, n)), d = await Q(this.db.prepare("SELECT manifest_json FROM coordinator_legacy_team_completions\n WHERE group_id = ? AND candidate_ref = ?").bind(n, a.candidate_ref));
4310
+ if (!d) {
593
4311
  let e = await this.getGroup(n);
594
4312
  if (!e) throw Error("group_not_found");
595
4313
  if (e.archived_at) throw Error("group_archived");
596
- let t = await X(this.db.prepare("SELECT DISTINCT\n requested.scope_id,\n scope.authority_type,\n scope.coordinator_id,\n scope.group_id,\n scope.status\n FROM (\n SELECT json_extract(value, '$.scope_id') AS scope_id\n FROM json_each(?, '$.project_mappings')\n ) AS requested\n LEFT JOIN coordinator_scopes AS scope ON scope.scope_id = requested.scope_id").bind(i));
597
- throw w(a, n, t), Error("completion_manifest_unavailable");
4314
+ let t = await Z(this.db.prepare("SELECT DISTINCT\n requested.scope_id,\n scope.authority_type,\n scope.coordinator_id,\n scope.group_id,\n scope.status\n FROM (\n SELECT json_extract(value, '$.scope_id') AS scope_id\n FROM json_each(?, '$.project_mappings')\n ) AS requested\n LEFT JOIN coordinator_scopes AS scope ON scope.scope_id = requested.scope_id").bind(i));
4315
+ throw Ge(a, n, t), Error("completion_manifest_unavailable");
598
4316
  }
599
- if (u.manifest_json !== i) throw new g();
4317
+ if (d.manifest_json !== i) throw new ve();
600
4318
  return {
601
- status: l === 1 ? "created" : "existing",
602
- manifest: y(JSON.parse(u.manifest_json))
4319
+ status: u === 1 ? "created" : "existing",
4320
+ manifest: Ye(JSON.parse(d.manifest_json))
603
4321
  };
604
4322
  }
605
4323
  async getLegacyTeamCompletion(e, t) {
606
- let [n] = _([e]), r = j(t);
4324
+ let [n] = s([e]), r = Rn(t);
607
4325
  if (!n) throw Error("completion_manifest_invalid");
608
- let i = await Z(this.db.prepare("SELECT manifest_json FROM coordinator_legacy_team_completions\n WHERE group_id = ? AND candidate_ref = ?").bind(n, r));
609
- return i ? y(JSON.parse(i.manifest_json)) : null;
4326
+ let i = await Q(this.db.prepare("SELECT manifest_json FROM coordinator_legacy_team_completions\n WHERE group_id = ? AND candidate_ref = ?").bind(n, r));
4327
+ return i ? Ye(JSON.parse(i.manifest_json)) : null;
610
4328
  }
611
4329
  async listLegacyTeamCompletions(e) {
612
- let t = _(e);
4330
+ let t = s(e);
613
4331
  if (t.length === 0) return [];
614
- let n = t.map(() => "?").join(", "), r = await Z(this.db.prepare(`SELECT
4332
+ let n = t.map(() => "?").join(", "), r = await Q(this.db.prepare(`SELECT
615
4333
  COUNT(*) AS record_count,
616
4334
  COALESCE(SUM(
617
4335
  LENGTH(CAST(group_id AS BLOB)) + LENGTH(CAST(manifest_json AS BLOB))
@@ -620,7 +4338,7 @@ var $ = class {
620
4338
  FROM coordinator_legacy_team_completions
621
4339
  WHERE group_id IN (${n})`).bind(...t));
622
4340
  if (!r || r.record_count > 500 || r.batch_bytes > 375e5 || r.max_manifest_bytes > 15e5) throw Error("completion_results_too_large");
623
- let i = await X(this.db.prepare(`WITH completion_stats AS (
4341
+ let i = await Z(this.db.prepare(`WITH completion_stats AS (
624
4342
  SELECT
625
4343
  COUNT(*) AS record_count,
626
4344
  COALESCE(SUM(
@@ -635,20 +4353,20 @@ var $ = class {
635
4353
  CROSS JOIN completion_stats
636
4354
  WHERE completions.group_id IN (${n})
637
4355
  AND completion_stats.record_count <= 500
638
- AND completion_stats.batch_bytes <= ${E}
639
- AND completion_stats.max_manifest_bytes <= ${x}
640
- AND LENGTH(completions.manifest_json) <= ${x}
641
- AND LENGTH(CAST(completions.manifest_json AS BLOB)) <= ${x}
4356
+ AND completion_stats.batch_bytes <= ${Vt}
4357
+ AND completion_stats.max_manifest_bytes <= ${Te}
4358
+ AND LENGTH(completions.manifest_json) <= ${Te}
4359
+ AND LENGTH(CAST(completions.manifest_json AS BLOB)) <= ${Te}
642
4360
  ORDER BY completions.group_id, completions.completed_at, completions.candidate_ref
643
4361
  LIMIT 501`).bind(...t, ...t));
644
4362
  if (i.length === 0 && r.record_count > 0 || i.length > 500 || i.reduce((e, t) => e + new TextEncoder().encode(t.group_id).byteLength + new TextEncoder().encode(t.manifest_json).byteLength, 0) > 375e5) throw Error("completion_results_too_large");
645
4363
  return i.map((e) => ({
646
4364
  group_id: e.group_id,
647
- manifest: y(JSON.parse(e.manifest_json))
4365
+ manifest: Ye(JSON.parse(e.manifest_json))
648
4366
  }));
649
4367
  }
650
4368
  async upsertPresence(e) {
651
- let t = /* @__PURE__ */ new Date(), n = new Date(t.getTime() + e.ttlS * 1e3).toISOString(), r = c([], e.addresses);
4369
+ let t = /* @__PURE__ */ new Date(), n = new Date(t.getTime() + e.ttlS * 1e3).toISOString(), r = Tt([], e.addresses);
652
4370
  return await this.db.prepare("INSERT INTO presence_records(group_id, device_id, addresses_json, last_seen_at, expires_at, capabilities_json)\n VALUES (?, ?, ?, ?, ?, ?)\n ON CONFLICT(group_id, device_id) DO UPDATE SET\n addresses_json = excluded.addresses_json,\n last_seen_at = excluded.last_seen_at,\n expires_at = excluded.expires_at,\n capabilities_json = excluded.capabilities_json").bind(e.groupId, e.deviceId, JSON.stringify(r), t.toISOString(), n, JSON.stringify(e.capabilities ?? {})).run(), {
653
4371
  group_id: e.groupId,
654
4372
  device_id: e.deviceId,
@@ -657,14 +4375,27 @@ var $ = class {
657
4375
  };
658
4376
  }
659
4377
  async listGroupPeers(e, t) {
660
- let n = L();
661
- return (await X(this.db.prepare("SELECT enrolled_devices.device_id, enrolled_devices.public_key, enrolled_devices.fingerprint, enrolled_devices.display_name,\n presence_records.addresses_json, presence_records.last_seen_at, presence_records.expires_at,\n presence_records.capabilities_json\n FROM enrolled_devices\n LEFT JOIN presence_records\n ON presence_records.group_id = enrolled_devices.group_id\n AND presence_records.device_id = enrolled_devices.device_id\n WHERE enrolled_devices.group_id = ?\n AND enrolled_devices.enabled = 1\n AND enrolled_devices.device_id != ?\n ORDER BY enrolled_devices.device_id ASC").bind(e, t))).map((e) => {
4378
+ try {
4379
+ return await this.readGroupPeers(e, t);
4380
+ } catch {
4381
+ throw Error("peer_discovery_unavailable");
4382
+ }
4383
+ }
4384
+ async readGroupPeers(e, t) {
4385
+ let n = Y(), r = await this.db.prepare(ye).bind(e, t).all();
4386
+ if (!Array.isArray(r?.results) || r.success === !1) throw Error("peer_discovery_unavailable");
4387
+ let i = zn(r.results), a = await Promise.all(i.map(async (e) => ({
4388
+ ...e,
4389
+ keyId: await f(e.public_key)
4390
+ }))), o = await this.db.prepare(Fe).bind(JSON.stringify(a), e, t).all();
4391
+ if (o?.success === !1) throw Error("peer_discovery_unavailable");
4392
+ return c(o?.results).map((e) => {
662
4393
  let t = String(e.expires_at ?? "").trim(), r = !0;
663
4394
  if (t) {
664
4395
  let e = new Date(t);
665
4396
  r = Number.isNaN(e.getTime()) || e.toISOString() <= n;
666
4397
  }
667
- let i = r ? [] : c([], JSON.parse(String(e.addresses_json ?? "[]")));
4398
+ let i = r ? [] : Tt([], JSON.parse(String(e.addresses_json ?? "[]")));
668
4399
  return {
669
4400
  device_id: String(e.device_id ?? ""),
670
4401
  public_key: String(e.public_key ?? ""),
@@ -681,18 +4412,24 @@ var $ = class {
681
4412
  };
682
4413
  //#endregion
683
4414
  //#region src/d1-coordinator-runtime.ts
684
- function re(e) {
685
- let t = {
4415
+ function es(e) {
4416
+ let t = e.db, n = {
686
4417
  adminSecret: () => String(e.adminSecret ?? "").trim() || null,
687
4418
  now: e.now ?? (() => (/* @__PURE__ */ new Date()).toISOString())
688
4419
  };
689
- return k({
690
- storeFactory: () => new $(e.db),
691
- runtime: t,
692
- requestVerifier: e.requestVerifier
4420
+ return Ut({
4421
+ storeFactory: () => new $o(t),
4422
+ deviceRevocation: e.deviceRevocation,
4423
+ runtime: n,
4424
+ requestVerifier: e.requestVerifier,
4425
+ requestRateLimit: e.requestRateLimit,
4426
+ browserAuth: e.browserAuth?.kind === "ready" ? {
4427
+ ...e.browserAuth,
4428
+ storeFactory: () => new $o(t)
4429
+ } : e.browserAuth
693
4430
  });
694
4431
  }
695
4432
  //#endregion
696
- export { A as COORDINATOR_LEGACY_TEAM_COMPLETION_CONFLICT, E as COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES, te as COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_RESPONSE_BYTES, x as COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES, m as COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_GROUPS, ee as COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS, O as COORDINATOR_LEGACY_TEAM_COMPLETION_VERSION, g as CoordinatorLegacyTeamCompletionConflictError, $ as D1CoordinatorStore, T as DEFAULT_TIME_WINDOW_S, C as canonicalCoordinatorLegacyTeamCompletionManifestJson, re as createD1CoordinatorApp, j as normalizeCoordinatorLegacyTeamCompletionCandidateRef, _ as normalizeCoordinatorLegacyTeamCompletionGroupIds, y as normalizeCoordinatorLegacyTeamCompletionManifest };
4433
+ export { ke as AccountLinkStatusOperations, kt as AuthSessionOperations, i as COORDINATOR_LEGACY_TEAM_COMPLETION_CONFLICT, Vt as COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES, xe as COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_RESPONSE_BYTES, Te as COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES, Ae as COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_GROUPS, re as COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS, ue as COORDINATOR_LEGACY_TEAM_COMPLETION_VERSION, ve as CoordinatorLegacyTeamCompletionConflictError, $o as D1CoordinatorStore, fe as DEFAULT_TIME_WINDOW_S, da as OWNER_BROWSER_ADMISSION_PATH, lo as OWNER_QUALIFICATION_PATH, Oa as admitCoordinatorBrowserAuthSetup, On as authSchemaUpgradeResponse, Pe as canonicalCoordinatorLegacyTeamCompletionManifestJson, T as captureCoordinatorBrowserAuthConfig, Ea as captureCoordinatorBrowserAuthOptions, Da as coordinatorBrowserAuthDeviceRoutes, ja as coordinatorBrowserAuthUnavailableResponse, Ut as createCoordinatorApp, Na as createCoordinatorBrowserAuth, ia as createCoordinatorOwnerEnrollmentHttp, Ao as createD1AuthLinkBackend, es as createD1CoordinatorApp, r as createInMemoryRequestRateLimiter, ga as createOwnerBrowserAdmissionHandler, co as createOwnerQualificationHandler, go as createOwnerQualificationHttp, ae as importBrowserCsrfKey, rn as importOwnerEnrollmentAdmissionKey, hn as isOwnerEnrollmentAdmissionKey, mt as issueOwnerEnrollmentAdmission, Jt as issueOwnerEnrollmentAdmissionV2, Ua as maintainCoordinatorBrowserAuth, $i as matchesCoordinatorOwnerEnrollmentHttpPath, Rn as normalizeCoordinatorLegacyTeamCompletionCandidateRef, s as normalizeCoordinatorLegacyTeamCompletionGroupIds, Ye as normalizeCoordinatorLegacyTeamCompletionManifest, Sn as ownerEnrollmentOwnerCommitment, yt as verifyOwnerEnrollmentAdmission, Et as verifyOwnerEnrollmentAdmissionV2 };
697
4434
 
698
4435
  //# sourceMappingURL=cloudflare-coordinator.js.map