@yielded/auth-persistence 0.1.0-beta.7

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 (526) hide show
  1. package/README.md +21 -0
  2. package/dist/Drizzle.d.mts +28 -0
  3. package/dist/Drizzle.mjs +28 -0
  4. package/dist/DrizzleD1.d.mts +963 -0
  5. package/dist/DrizzleD1.mjs +29 -0
  6. package/dist/DrizzleD1.mjs.map +1 -0
  7. package/dist/DrizzleLibsql.d.mts +2284 -0
  8. package/dist/DrizzleLibsql.mjs +92 -0
  9. package/dist/DrizzleLibsql.mjs.map +1 -0
  10. package/dist/DrizzleMysql2.d.mts +1820 -0
  11. package/dist/DrizzleMysql2.mjs +55 -0
  12. package/dist/DrizzleMysql2.mjs.map +1 -0
  13. package/dist/DrizzlePglite.d.mts +1826 -0
  14. package/dist/DrizzlePglite.mjs +53 -0
  15. package/dist/DrizzlePglite.mjs.map +1 -0
  16. package/dist/DrizzlePostgres.d.mts +1826 -0
  17. package/dist/DrizzlePostgres.mjs +53 -0
  18. package/dist/DrizzlePostgres.mjs.map +1 -0
  19. package/dist/DrizzleSqliteBun.d.mts +2279 -0
  20. package/dist/DrizzleSqliteBun.mjs +70 -0
  21. package/dist/DrizzleSqliteBun.mjs.map +1 -0
  22. package/dist/DrizzleSqliteDo.d.mts +2329 -0
  23. package/dist/DrizzleSqliteDo.mjs +105 -0
  24. package/dist/DrizzleSqliteDo.mjs.map +1 -0
  25. package/dist/DrizzleSqliteNode.d.mts +2279 -0
  26. package/dist/DrizzleSqliteNode.mjs +70 -0
  27. package/dist/DrizzleSqliteNode.mjs.map +1 -0
  28. package/dist/DrizzleSqliteWasm.d.mts +2282 -0
  29. package/dist/DrizzleSqliteWasm.mjs +70 -0
  30. package/dist/DrizzleSqliteWasm.mjs.map +1 -0
  31. package/dist/drizzle/D1BatchStatements.d.mts +11 -0
  32. package/dist/drizzle/D1BatchStatements.mjs +8 -0
  33. package/dist/drizzle/D1BatchStatements.mjs.map +1 -0
  34. package/dist/drizzle/PasswordPreparedPostconditions.mjs +12 -0
  35. package/dist/drizzle/PasswordPreparedPostconditions.mjs.map +1 -0
  36. package/dist/drizzle/SuppliedService.d.mts +10 -0
  37. package/dist/drizzle/d1-emails.d.mts +62 -0
  38. package/dist/drizzle/d1-emails.mjs +580 -0
  39. package/dist/drizzle/d1-emails.mjs.map +1 -0
  40. package/dist/drizzle/d1-generated-statement.d.mts +2 -0
  41. package/dist/drizzle/d1-generated-statement.mjs +79 -0
  42. package/dist/drizzle/d1-generated-statement.mjs.map +1 -0
  43. package/dist/drizzle/d1-identity.d.mts +31 -0
  44. package/dist/drizzle/d1-identity.mjs +119 -0
  45. package/dist/drizzle/d1-identity.mjs.map +1 -0
  46. package/dist/drizzle/d1-oauth.d.mts +301 -0
  47. package/dist/drizzle/d1-oauth.mjs +76 -0
  48. package/dist/drizzle/d1-oauth.mjs.map +1 -0
  49. package/dist/drizzle/d1-passkey.d.mts +51 -0
  50. package/dist/drizzle/d1-passkey.mjs +95 -0
  51. package/dist/drizzle/d1-passkey.mjs.map +1 -0
  52. package/dist/drizzle/d1-password-prepared.d.mts +25 -0
  53. package/dist/drizzle/d1-password-prepared.mjs +461 -0
  54. package/dist/drizzle/d1-password-prepared.mjs.map +1 -0
  55. package/dist/drizzle/d1-passwords.d.mts +87 -0
  56. package/dist/drizzle/d1-passwords.mjs +1004 -0
  57. package/dist/drizzle/d1-passwords.mjs.map +1 -0
  58. package/dist/drizzle/d1-phone.d.mts +26 -0
  59. package/dist/drizzle/d1-phone.mjs +30 -0
  60. package/dist/drizzle/d1-phone.mjs.map +1 -0
  61. package/dist/drizzle/d1-planning.d.mts +12 -0
  62. package/dist/drizzle/d1-planning.mjs +43 -0
  63. package/dist/drizzle/d1-planning.mjs.map +1 -0
  64. package/dist/drizzle/d1-proofs.d.mts +80 -0
  65. package/dist/drizzle/d1-proofs.mjs +830 -0
  66. package/dist/drizzle/d1-proofs.mjs.map +1 -0
  67. package/dist/drizzle/d1-sessions.d.mts +67 -0
  68. package/dist/drizzle/d1-sessions.mjs +966 -0
  69. package/dist/drizzle/d1-sessions.mjs.map +1 -0
  70. package/dist/drizzle/d1-totp.d.mts +26 -0
  71. package/dist/drizzle/d1-totp.mjs +27 -0
  72. package/dist/drizzle/d1-totp.mjs.map +1 -0
  73. package/dist/drizzle/email-model.d.mts +354 -0
  74. package/dist/drizzle/email-model.mjs +21 -0
  75. package/dist/drizzle/email-model.mjs.map +1 -0
  76. package/dist/drizzle/email-registration.d.mts +30 -0
  77. package/dist/drizzle/email-registration.mjs +238 -0
  78. package/dist/drizzle/email-registration.mjs.map +1 -0
  79. package/dist/drizzle/email-sql.d.mts +4 -0
  80. package/dist/drizzle/email-sql.mjs +9 -0
  81. package/dist/drizzle/email-sql.mjs.map +1 -0
  82. package/dist/drizzle/email-target.d.mts +20 -0
  83. package/dist/drizzle/email-target.mjs +72 -0
  84. package/dist/drizzle/email-target.mjs.map +1 -0
  85. package/dist/drizzle/model.d.mts +250 -0
  86. package/dist/drizzle/model.mjs +58 -0
  87. package/dist/drizzle/model.mjs.map +1 -0
  88. package/dist/drizzle/mysql-emails.d.mts +71 -0
  89. package/dist/drizzle/mysql-emails.mjs +38 -0
  90. package/dist/drizzle/mysql-emails.mjs.map +1 -0
  91. package/dist/drizzle/mysql-identity.d.mts +22 -0
  92. package/dist/drizzle/mysql-identity.mjs +94 -0
  93. package/dist/drizzle/mysql-identity.mjs.map +1 -0
  94. package/dist/drizzle/mysql-password-prepared.d.mts +30 -0
  95. package/dist/drizzle/mysql-password-prepared.mjs +16 -0
  96. package/dist/drizzle/mysql-password-prepared.mjs.map +1 -0
  97. package/dist/drizzle/mysql-passwords.d.mts +86 -0
  98. package/dist/drizzle/mysql-passwords.mjs +38 -0
  99. package/dist/drizzle/mysql-passwords.mjs.map +1 -0
  100. package/dist/drizzle/mysql-proofs.d.mts +75 -0
  101. package/dist/drizzle/mysql-proofs.mjs +23 -0
  102. package/dist/drizzle/mysql-proofs.mjs.map +1 -0
  103. package/dist/drizzle/mysql-sessions.d.mts +237 -0
  104. package/dist/drizzle/mysql-sessions.mjs +53 -0
  105. package/dist/drizzle/mysql-sessions.mjs.map +1 -0
  106. package/dist/drizzle/mysql.d.mts +70 -0
  107. package/dist/drizzle/mysql.mjs +218 -0
  108. package/dist/drizzle/mysql.mjs.map +1 -0
  109. package/dist/drizzle/oauth-accounts.mjs +358 -0
  110. package/dist/drizzle/oauth-accounts.mjs.map +1 -0
  111. package/dist/drizzle/oauth-connected-access.mjs +210 -0
  112. package/dist/drizzle/oauth-connected-access.mjs.map +1 -0
  113. package/dist/drizzle/oauth-connected-collection.mjs +202 -0
  114. package/dist/drizzle/oauth-connected-collection.mjs.map +1 -0
  115. package/dist/drizzle/oauth-connected-custody.mjs +146 -0
  116. package/dist/drizzle/oauth-connected-custody.mjs.map +1 -0
  117. package/dist/drizzle/oauth-connected-drivers.mjs +76 -0
  118. package/dist/drizzle/oauth-connected-drivers.mjs.map +1 -0
  119. package/dist/drizzle/oauth-connected-flow.mjs +247 -0
  120. package/dist/drizzle/oauth-connected-flow.mjs.map +1 -0
  121. package/dist/drizzle/oauth-connected-input.mjs +103 -0
  122. package/dist/drizzle/oauth-connected-input.mjs.map +1 -0
  123. package/dist/drizzle/oauth-connected-maintenance.mjs +214 -0
  124. package/dist/drizzle/oauth-connected-maintenance.mjs.map +1 -0
  125. package/dist/drizzle/oauth-connected-management.mjs +228 -0
  126. package/dist/drizzle/oauth-connected-management.mjs.map +1 -0
  127. package/dist/drizzle/oauth-connected-model.d.mts +278 -0
  128. package/dist/drizzle/oauth-connected-model.mjs +22 -0
  129. package/dist/drizzle/oauth-connected-model.mjs.map +1 -0
  130. package/dist/drizzle/oauth-connected-reference.d.mts +17 -0
  131. package/dist/drizzle/oauth-connected-reference.mjs +53 -0
  132. package/dist/drizzle/oauth-connected-reference.mjs.map +1 -0
  133. package/dist/drizzle/oauth-connected-settlement.mjs +117 -0
  134. package/dist/drizzle/oauth-connected-settlement.mjs.map +1 -0
  135. package/dist/drizzle/oauth-connected-state.d.mts +14 -0
  136. package/dist/drizzle/oauth-connected-state.mjs +422 -0
  137. package/dist/drizzle/oauth-connected-state.mjs.map +1 -0
  138. package/dist/drizzle/oauth-connected-target.d.mts +753 -0
  139. package/dist/drizzle/oauth-connected-target.mjs +91 -0
  140. package/dist/drizzle/oauth-connected-target.mjs.map +1 -0
  141. package/dist/drizzle/oauth-drivers.mjs +51 -0
  142. package/dist/drizzle/oauth-drivers.mjs.map +1 -0
  143. package/dist/drizzle/oauth-flow.d.mts +5 -0
  144. package/dist/drizzle/oauth-flow.mjs +253 -0
  145. package/dist/drizzle/oauth-flow.mjs.map +1 -0
  146. package/dist/drizzle/oauth-input.mjs +127 -0
  147. package/dist/drizzle/oauth-input.mjs.map +1 -0
  148. package/dist/drizzle/oauth-model.d.mts +463 -0
  149. package/dist/drizzle/oauth-model.mjs +49 -0
  150. package/dist/drizzle/oauth-model.mjs.map +1 -0
  151. package/dist/drizzle/oauth-mysql.mjs +8 -0
  152. package/dist/drizzle/oauth-mysql.mjs.map +1 -0
  153. package/dist/drizzle/oauth-owner.d.mts +4 -0
  154. package/dist/drizzle/oauth-owner.mjs +10 -0
  155. package/dist/drizzle/oauth-owner.mjs.map +1 -0
  156. package/dist/drizzle/oauth-registration.d.mts +6 -0
  157. package/dist/drizzle/oauth-registration.mjs +374 -0
  158. package/dist/drizzle/oauth-registration.mjs.map +1 -0
  159. package/dist/drizzle/oauth-state.mjs +107 -0
  160. package/dist/drizzle/oauth-state.mjs.map +1 -0
  161. package/dist/drizzle/oauth-target.d.mts +111 -0
  162. package/dist/drizzle/oauth-target.mjs +246 -0
  163. package/dist/drizzle/oauth-target.mjs.map +1 -0
  164. package/dist/drizzle/passkey-drivers.mjs +34 -0
  165. package/dist/drizzle/passkey-drivers.mjs.map +1 -0
  166. package/dist/drizzle/passkey-kernel.mjs +8 -0
  167. package/dist/drizzle/passkey-kernel.mjs.map +1 -0
  168. package/dist/drizzle/passkey-model.d.mts +272 -0
  169. package/dist/drizzle/passkey-model.mjs +34 -0
  170. package/dist/drizzle/passkey-model.mjs.map +1 -0
  171. package/dist/drizzle/passkey-registration-ceremony-model.d.mts +50 -0
  172. package/dist/drizzle/passkey-registration-ceremony-model.mjs +18 -0
  173. package/dist/drizzle/passkey-registration-ceremony-model.mjs.map +1 -0
  174. package/dist/drizzle/passkey-state.mjs +7 -0
  175. package/dist/drizzle/passkey-state.mjs.map +1 -0
  176. package/dist/drizzle/passkey-target.d.mts +9 -0
  177. package/dist/drizzle/passkey-target.mjs +7 -0
  178. package/dist/drizzle/passkey-target.mjs.map +1 -0
  179. package/dist/drizzle/passkey-write-drivers.mjs +32 -0
  180. package/dist/drizzle/passkey-write-drivers.mjs.map +1 -0
  181. package/dist/drizzle/passkey-write-model.d.mts +190 -0
  182. package/dist/drizzle/passkey-write-model.mjs +13 -0
  183. package/dist/drizzle/passkey-write-model.mjs.map +1 -0
  184. package/dist/drizzle/passkey-write-target.d.mts +11 -0
  185. package/dist/drizzle/passkey-write-target.mjs +7 -0
  186. package/dist/drizzle/passkey-write-target.mjs.map +1 -0
  187. package/dist/drizzle/password-model.d.mts +329 -0
  188. package/dist/drizzle/password-model.mjs +23 -0
  189. package/dist/drizzle/password-model.mjs.map +1 -0
  190. package/dist/drizzle/password-prepared-model.d.mts +94 -0
  191. package/dist/drizzle/password-prepared-model.mjs +11 -0
  192. package/dist/drizzle/password-prepared-model.mjs.map +1 -0
  193. package/dist/drizzle/password-prepared-sql.mjs +390 -0
  194. package/dist/drizzle/password-prepared-sql.mjs.map +1 -0
  195. package/dist/drizzle/password-prepared-state.mjs +104 -0
  196. package/dist/drizzle/password-prepared-state.mjs.map +1 -0
  197. package/dist/drizzle/password-prepared-target.d.mts +12 -0
  198. package/dist/drizzle/password-prepared-target.mjs +56 -0
  199. package/dist/drizzle/password-prepared-target.mjs.map +1 -0
  200. package/dist/drizzle/password-registration.d.mts +19 -0
  201. package/dist/drizzle/password-registration.mjs +135 -0
  202. package/dist/drizzle/password-registration.mjs.map +1 -0
  203. package/dist/drizzle/password-sql.d.mts +5 -0
  204. package/dist/drizzle/password-sql.mjs +9 -0
  205. package/dist/drizzle/password-sql.mjs.map +1 -0
  206. package/dist/drizzle/password-target.d.mts +17 -0
  207. package/dist/drizzle/password-target.mjs +61 -0
  208. package/dist/drizzle/password-target.mjs.map +1 -0
  209. package/dist/drizzle/pg-emails.d.mts +72 -0
  210. package/dist/drizzle/pg-emails.mjs +38 -0
  211. package/dist/drizzle/pg-emails.mjs.map +1 -0
  212. package/dist/drizzle/pg-password-prepared.d.mts +31 -0
  213. package/dist/drizzle/pg-password-prepared.mjs +16 -0
  214. package/dist/drizzle/pg-password-prepared.mjs.map +1 -0
  215. package/dist/drizzle/pg-passwords.d.mts +87 -0
  216. package/dist/drizzle/pg-passwords.mjs +38 -0
  217. package/dist/drizzle/pg-passwords.mjs.map +1 -0
  218. package/dist/drizzle/pg-proofs.d.mts +76 -0
  219. package/dist/drizzle/pg-proofs.mjs +22 -0
  220. package/dist/drizzle/pg-proofs.mjs.map +1 -0
  221. package/dist/drizzle/pg-sessions.d.mts +238 -0
  222. package/dist/drizzle/pg-sessions.mjs +53 -0
  223. package/dist/drizzle/pg-sessions.mjs.map +1 -0
  224. package/dist/drizzle/pg.d.mts +81 -0
  225. package/dist/drizzle/pg.mjs +290 -0
  226. package/dist/drizzle/pg.mjs.map +1 -0
  227. package/dist/drizzle/phone-model.d.mts +115 -0
  228. package/dist/drizzle/phone-model.mjs +39 -0
  229. package/dist/drizzle/phone-model.mjs.map +1 -0
  230. package/dist/drizzle/phone-state.mjs +16 -0
  231. package/dist/drizzle/phone-state.mjs.map +1 -0
  232. package/dist/drizzle/phone-target.d.mts +17 -0
  233. package/dist/drizzle/phone-target.mjs +170 -0
  234. package/dist/drizzle/phone-target.mjs.map +1 -0
  235. package/dist/drizzle/proof-model.d.mts +286 -0
  236. package/dist/drizzle/proof-model.mjs +17 -0
  237. package/dist/drizzle/proof-model.mjs.map +1 -0
  238. package/dist/drizzle/proof-sql.d.mts +4 -0
  239. package/dist/drizzle/proof-sql.mjs +8 -0
  240. package/dist/drizzle/proof-sql.mjs.map +1 -0
  241. package/dist/drizzle/proof-target.d.mts +12 -0
  242. package/dist/drizzle/proof-target.mjs +36 -0
  243. package/dist/drizzle/proof-target.mjs.map +1 -0
  244. package/dist/drizzle/query-operations.mjs +26 -0
  245. package/dist/drizzle/query-operations.mjs.map +1 -0
  246. package/dist/drizzle/session-model.d.mts +200 -0
  247. package/dist/drizzle/session-model.mjs +20 -0
  248. package/dist/drizzle/session-model.mjs.map +1 -0
  249. package/dist/drizzle/session-sql.mjs +8 -0
  250. package/dist/drizzle/session-sql.mjs.map +1 -0
  251. package/dist/drizzle/session-target.d.mts +28 -0
  252. package/dist/drizzle/session-target.mjs +47 -0
  253. package/dist/drizzle/session-target.mjs.map +1 -0
  254. package/dist/drizzle/sqlite-emails.mjs +45 -0
  255. package/dist/drizzle/sqlite-emails.mjs.map +1 -0
  256. package/dist/drizzle/sqlite-identity.mjs +91 -0
  257. package/dist/drizzle/sqlite-identity.mjs.map +1 -0
  258. package/dist/drizzle/sqlite-password-prepared.mjs +21 -0
  259. package/dist/drizzle/sqlite-password-prepared.mjs.map +1 -0
  260. package/dist/drizzle/sqlite-passwords.mjs +49 -0
  261. package/dist/drizzle/sqlite-passwords.mjs.map +1 -0
  262. package/dist/drizzle/sqlite-proofs.mjs +29 -0
  263. package/dist/drizzle/sqlite-proofs.mjs.map +1 -0
  264. package/dist/drizzle/sqlite-sessions.mjs +74 -0
  265. package/dist/drizzle/sqlite-sessions.mjs.map +1 -0
  266. package/dist/drizzle/sqlite.d.mts +78 -0
  267. package/dist/drizzle/sqlite.mjs +217 -0
  268. package/dist/drizzle/sqlite.mjs.map +1 -0
  269. package/dist/drizzle/standalone-guard.mjs +19 -0
  270. package/dist/drizzle/standalone-guard.mjs.map +1 -0
  271. package/dist/drizzle/step-up-model.d.mts +65 -0
  272. package/dist/drizzle/step-up-model.mjs +9 -0
  273. package/dist/drizzle/step-up-model.mjs.map +1 -0
  274. package/dist/drizzle/step-up-state.mjs +32 -0
  275. package/dist/drizzle/step-up-state.mjs.map +1 -0
  276. package/dist/drizzle/totp-model.d.mts +84 -0
  277. package/dist/drizzle/totp-model.mjs +13 -0
  278. package/dist/drizzle/totp-model.mjs.map +1 -0
  279. package/dist/drizzle/totp-state.d.mts +38 -0
  280. package/dist/drizzle/totp-state.mjs +287 -0
  281. package/dist/drizzle/totp-state.mjs.map +1 -0
  282. package/dist/drizzle/totp-target.d.mts +17 -0
  283. package/dist/drizzle/totp-target.mjs +81 -0
  284. package/dist/drizzle/totp-target.mjs.map +1 -0
  285. package/dist/drizzle/transaction-execution.d.mts +4 -0
  286. package/dist/drizzle/transaction-execution.mjs +11 -0
  287. package/dist/drizzle/transaction-execution.mjs.map +1 -0
  288. package/dist/drizzle/transaction-mysql.mjs +46 -0
  289. package/dist/drizzle/transaction-mysql.mjs.map +1 -0
  290. package/dist/drizzle/transaction-owner.d.mts +2 -0
  291. package/dist/drizzle/transaction-owner.mjs +8 -0
  292. package/dist/drizzle/transaction-owner.mjs.map +1 -0
  293. package/dist/index.d.mts +5 -0
  294. package/dist/index.mjs +5 -0
  295. package/dist/internal/configuration.d.mts +174 -0
  296. package/dist/internal/configuration.mjs +7 -0
  297. package/dist/internal/configuration.mjs.map +1 -0
  298. package/dist/internal/drizzle-migrations.mjs +19 -0
  299. package/dist/internal/drizzle-migrations.mjs.map +1 -0
  300. package/dist/internal/drizzle-postgres.mjs +39 -0
  301. package/dist/internal/drizzle-postgres.mjs.map +1 -0
  302. package/dist/internal/drizzle-sqlite.mjs +37 -0
  303. package/dist/internal/drizzle-sqlite.mjs.map +1 -0
  304. package/dist/internal/email-kernel.d.mts +13 -0
  305. package/dist/internal/email-kernel.mjs +487 -0
  306. package/dist/internal/email-kernel.mjs.map +1 -0
  307. package/dist/internal/mapping-error.d.mts +11 -0
  308. package/dist/internal/mapping-error.mjs +30 -0
  309. package/dist/internal/mapping-error.mjs.map +1 -0
  310. package/dist/internal/passkey/admission.d.mts +7 -0
  311. package/dist/internal/passkey/admission.mjs +216 -0
  312. package/dist/internal/passkey/admission.mjs.map +1 -0
  313. package/dist/internal/passkey/credentials.d.mts +6 -0
  314. package/dist/internal/passkey/credentials.mjs +249 -0
  315. package/dist/internal/passkey/credentials.mjs.map +1 -0
  316. package/dist/internal/passkey/enrollment.mjs +138 -0
  317. package/dist/internal/passkey/enrollment.mjs.map +1 -0
  318. package/dist/internal/passkey/flow.d.mts +10 -0
  319. package/dist/internal/passkey/flow.mjs +452 -0
  320. package/dist/internal/passkey/flow.mjs.map +1 -0
  321. package/dist/internal/passkey/management.mjs +231 -0
  322. package/dist/internal/passkey/management.mjs.map +1 -0
  323. package/dist/internal/passkey/registration-ceremony.d.mts +9 -0
  324. package/dist/internal/passkey/registration-ceremony.mjs +129 -0
  325. package/dist/internal/passkey/registration-ceremony.mjs.map +1 -0
  326. package/dist/internal/passkey/registration-custody.d.mts +2 -0
  327. package/dist/internal/passkey/registration-custody.mjs +52 -0
  328. package/dist/internal/passkey/registration-custody.mjs.map +1 -0
  329. package/dist/internal/passkey/registration-write.mjs +211 -0
  330. package/dist/internal/passkey/registration-write.mjs.map +1 -0
  331. package/dist/internal/passkey/state.d.mts +5 -0
  332. package/dist/internal/passkey/state.mjs +234 -0
  333. package/dist/internal/passkey/state.mjs.map +1 -0
  334. package/dist/internal/passkey/target.d.mts +19 -0
  335. package/dist/internal/passkey/target.mjs +190 -0
  336. package/dist/internal/passkey/target.mjs.map +1 -0
  337. package/dist/internal/passkey/write-state.mjs +345 -0
  338. package/dist/internal/passkey/write-state.mjs.map +1 -0
  339. package/dist/internal/passkey/write-target.mjs +192 -0
  340. package/dist/internal/passkey/write-target.mjs.map +1 -0
  341. package/dist/internal/passkey-kernel.mjs +49 -0
  342. package/dist/internal/passkey-kernel.mjs.map +1 -0
  343. package/dist/internal/passkeys.mjs +367 -0
  344. package/dist/internal/passkeys.mjs.map +1 -0
  345. package/dist/internal/password-kernel.d.mts +13 -0
  346. package/dist/internal/password-kernel.mjs +704 -0
  347. package/dist/internal/password-kernel.mjs.map +1 -0
  348. package/dist/internal/persistence.mjs +289 -0
  349. package/dist/internal/persistence.mjs.map +1 -0
  350. package/dist/internal/phone-kernel.mjs +434 -0
  351. package/dist/internal/phone-kernel.mjs.map +1 -0
  352. package/dist/internal/proof-kernel.d.mts +9 -0
  353. package/dist/internal/proof-kernel.mjs +619 -0
  354. package/dist/internal/proof-kernel.mjs.map +1 -0
  355. package/dist/internal/query-operations.d.mts +3 -0
  356. package/dist/internal/registration.mjs +65 -0
  357. package/dist/internal/registration.mjs.map +1 -0
  358. package/dist/internal/session-kernel.mjs +737 -0
  359. package/dist/internal/session-kernel.mjs.map +1 -0
  360. package/dist/internal/sql-persistence.d.mts +11 -0
  361. package/dist/internal/sql-persistence.mjs +37 -0
  362. package/dist/internal/sql-persistence.mjs.map +1 -0
  363. package/dist/internal/sql-query.mjs +207 -0
  364. package/dist/internal/sql-query.mjs.map +1 -0
  365. package/dist/internal/sql-table.d.mts +37 -0
  366. package/dist/internal/sql-table.mjs +71 -0
  367. package/dist/internal/sql-table.mjs.map +1 -0
  368. package/dist/internal/storage-mapping.mjs +687 -0
  369. package/dist/internal/storage-mapping.mjs.map +1 -0
  370. package/dist/internal/storage-tables.d.mts +914 -0
  371. package/dist/internal/storage-tables.mjs +387 -0
  372. package/dist/internal/storage-tables.mjs.map +1 -0
  373. package/dist/internal/storage-validation.mjs +58 -0
  374. package/dist/internal/storage-validation.mjs.map +1 -0
  375. package/dist/internal/transaction-execution-kernel.d.mts +18 -0
  376. package/dist/internal/transaction-execution-kernel.mjs +118 -0
  377. package/dist/internal/transaction-execution-kernel.mjs.map +1 -0
  378. package/dist/internal/transaction-kernel.d.mts +7 -0
  379. package/dist/internal/transaction-kernel.mjs +260 -0
  380. package/dist/internal/transaction-kernel.mjs.map +1 -0
  381. package/package.json +1 -0
  382. package/src/Drizzle.ts +378 -0
  383. package/src/DrizzleD1.ts +136 -0
  384. package/src/DrizzleLibsql.ts +301 -0
  385. package/src/DrizzleMysql2.ts +184 -0
  386. package/src/DrizzlePglite.ts +174 -0
  387. package/src/DrizzlePostgres.ts +174 -0
  388. package/src/DrizzleSqliteBun.ts +258 -0
  389. package/src/DrizzleSqliteDo.ts +473 -0
  390. package/src/DrizzleSqliteNode.ts +259 -0
  391. package/src/DrizzleSqliteWasm.ts +263 -0
  392. package/src/drizzle/D1BatchStatements.ts +10 -0
  393. package/src/drizzle/PasswordPreparedPostconditions.ts +30 -0
  394. package/src/drizzle/SuppliedService.ts +10 -0
  395. package/src/drizzle/d1-emails.ts +1829 -0
  396. package/src/drizzle/d1-generated-statement.ts +129 -0
  397. package/src/drizzle/d1-identity.ts +375 -0
  398. package/src/drizzle/d1-oauth.ts +340 -0
  399. package/src/drizzle/d1-passkey.ts +373 -0
  400. package/src/drizzle/d1-password-prepared.ts +1270 -0
  401. package/src/drizzle/d1-passwords.ts +2656 -0
  402. package/src/drizzle/d1-phone.ts +96 -0
  403. package/src/drizzle/d1-planning.ts +104 -0
  404. package/src/drizzle/d1-proofs.ts +2305 -0
  405. package/src/drizzle/d1-sessions.ts +2857 -0
  406. package/src/drizzle/d1-totp.ts +78 -0
  407. package/src/drizzle/email-model.ts +516 -0
  408. package/src/drizzle/email-registration.ts +698 -0
  409. package/src/drizzle/email-sql.ts +24 -0
  410. package/src/drizzle/email-target.ts +243 -0
  411. package/src/drizzle/model.ts +463 -0
  412. package/src/drizzle/mysql-emails.ts +321 -0
  413. package/src/drizzle/mysql-identity.ts +324 -0
  414. package/src/drizzle/mysql-password-prepared.ts +204 -0
  415. package/src/drizzle/mysql-passwords.ts +339 -0
  416. package/src/drizzle/mysql-proofs.ts +181 -0
  417. package/src/drizzle/mysql-sessions.ts +741 -0
  418. package/src/drizzle/mysql.ts +687 -0
  419. package/src/drizzle/oauth-accounts.ts +804 -0
  420. package/src/drizzle/oauth-connected-access.ts +354 -0
  421. package/src/drizzle/oauth-connected-collection.ts +324 -0
  422. package/src/drizzle/oauth-connected-custody.ts +277 -0
  423. package/src/drizzle/oauth-connected-drivers.ts +465 -0
  424. package/src/drizzle/oauth-connected-flow.ts +441 -0
  425. package/src/drizzle/oauth-connected-input.ts +127 -0
  426. package/src/drizzle/oauth-connected-maintenance.ts +345 -0
  427. package/src/drizzle/oauth-connected-management.ts +365 -0
  428. package/src/drizzle/oauth-connected-model.ts +347 -0
  429. package/src/drizzle/oauth-connected-reference.ts +112 -0
  430. package/src/drizzle/oauth-connected-settlement.ts +226 -0
  431. package/src/drizzle/oauth-connected-state.ts +845 -0
  432. package/src/drizzle/oauth-connected-target.ts +264 -0
  433. package/src/drizzle/oauth-drivers.ts +569 -0
  434. package/src/drizzle/oauth-flow.ts +462 -0
  435. package/src/drizzle/oauth-input.ts +201 -0
  436. package/src/drizzle/oauth-model.ts +617 -0
  437. package/src/drizzle/oauth-mysql.ts +10 -0
  438. package/src/drizzle/oauth-owner.ts +29 -0
  439. package/src/drizzle/oauth-registration.ts +640 -0
  440. package/src/drizzle/oauth-state.ts +215 -0
  441. package/src/drizzle/oauth-target.ts +750 -0
  442. package/src/drizzle/passkey-drivers.ts +385 -0
  443. package/src/drizzle/passkey-kernel.ts +3 -0
  444. package/src/drizzle/passkey-model.ts +353 -0
  445. package/src/drizzle/passkey-registration-ceremony-model.ts +69 -0
  446. package/src/drizzle/passkey-state.ts +3 -0
  447. package/src/drizzle/passkey-target.ts +23 -0
  448. package/src/drizzle/passkey-write-drivers.ts +395 -0
  449. package/src/drizzle/passkey-write-model.ts +271 -0
  450. package/src/drizzle/passkey-write-target.ts +9 -0
  451. package/src/drizzle/password-model.ts +491 -0
  452. package/src/drizzle/password-prepared-model.ts +259 -0
  453. package/src/drizzle/password-prepared-sql.ts +1191 -0
  454. package/src/drizzle/password-prepared-state.ts +231 -0
  455. package/src/drizzle/password-prepared-target.ts +160 -0
  456. package/src/drizzle/password-registration.ts +374 -0
  457. package/src/drizzle/password-sql.ts +12 -0
  458. package/src/drizzle/password-target.ts +224 -0
  459. package/src/drizzle/pg-emails.ts +321 -0
  460. package/src/drizzle/pg-password-prepared.ts +205 -0
  461. package/src/drizzle/pg-passwords.ts +338 -0
  462. package/src/drizzle/pg-proofs.ts +191 -0
  463. package/src/drizzle/pg-sessions.ts +750 -0
  464. package/src/drizzle/pg.ts +984 -0
  465. package/src/drizzle/phone-model.ts +190 -0
  466. package/src/drizzle/phone-state.ts +21 -0
  467. package/src/drizzle/phone-target.ts +472 -0
  468. package/src/drizzle/proof-model.ts +398 -0
  469. package/src/drizzle/proof-sql.ts +9 -0
  470. package/src/drizzle/proof-target.ts +122 -0
  471. package/src/drizzle/query-operations.ts +37 -0
  472. package/src/drizzle/session-model.ts +370 -0
  473. package/src/drizzle/session-sql.ts +13 -0
  474. package/src/drizzle/session-target.ts +338 -0
  475. package/src/drizzle/sqlite-emails.ts +366 -0
  476. package/src/drizzle/sqlite-identity.ts +344 -0
  477. package/src/drizzle/sqlite-password-prepared.ts +260 -0
  478. package/src/drizzle/sqlite-passwords.ts +497 -0
  479. package/src/drizzle/sqlite-proofs.ts +202 -0
  480. package/src/drizzle/sqlite-sessions.ts +971 -0
  481. package/src/drizzle/sqlite.ts +705 -0
  482. package/src/drizzle/standalone-guard.ts +38 -0
  483. package/src/drizzle/step-up-model.ts +128 -0
  484. package/src/drizzle/step-up-state.ts +139 -0
  485. package/src/drizzle/totp-model.ts +92 -0
  486. package/src/drizzle/totp-state.ts +525 -0
  487. package/src/drizzle/totp-target.ts +308 -0
  488. package/src/drizzle/transaction-execution.ts +12 -0
  489. package/src/drizzle/transaction-mysql.ts +104 -0
  490. package/src/drizzle/transaction-owner.ts +10 -0
  491. package/src/index.ts +4 -0
  492. package/src/internal/configuration.ts +282 -0
  493. package/src/internal/drizzle-migrations.ts +30 -0
  494. package/src/internal/drizzle-postgres.ts +81 -0
  495. package/src/internal/drizzle-sqlite.ts +79 -0
  496. package/src/internal/email-kernel.ts +1532 -0
  497. package/src/internal/mapping-error.ts +36 -0
  498. package/src/internal/passkey/admission.ts +362 -0
  499. package/src/internal/passkey/credentials.ts +511 -0
  500. package/src/internal/passkey/enrollment.ts +326 -0
  501. package/src/internal/passkey/flow.ts +1062 -0
  502. package/src/internal/passkey/management.ts +422 -0
  503. package/src/internal/passkey/registration-ceremony.ts +283 -0
  504. package/src/internal/passkey/registration-custody.ts +91 -0
  505. package/src/internal/passkey/registration-write.ts +426 -0
  506. package/src/internal/passkey/state.ts +354 -0
  507. package/src/internal/passkey/target.ts +586 -0
  508. package/src/internal/passkey/write-state.ts +681 -0
  509. package/src/internal/passkey/write-target.ts +452 -0
  510. package/src/internal/passkey-kernel.ts +102 -0
  511. package/src/internal/passkeys.ts +597 -0
  512. package/src/internal/password-kernel.ts +2122 -0
  513. package/src/internal/persistence.ts +590 -0
  514. package/src/internal/phone-kernel.ts +843 -0
  515. package/src/internal/proof-kernel.ts +1949 -0
  516. package/src/internal/query-operations.ts +26 -0
  517. package/src/internal/registration.ts +160 -0
  518. package/src/internal/session-kernel.ts +2210 -0
  519. package/src/internal/sql-persistence.ts +45 -0
  520. package/src/internal/sql-query.ts +298 -0
  521. package/src/internal/sql-table.ts +89 -0
  522. package/src/internal/storage-mapping.ts +706 -0
  523. package/src/internal/storage-tables.ts +408 -0
  524. package/src/internal/storage-validation.ts +117 -0
  525. package/src/internal/transaction-execution-kernel.ts +317 -0
  526. package/src/internal/transaction-kernel.ts +582 -0
@@ -0,0 +1,1949 @@
1
+ import {
2
+ coordinateCommit,
3
+ CurrentCommitJournal,
4
+ hasCommitScope,
5
+ LifecycleHooks,
6
+ HookConfigurationError,
7
+ } from "@yielded/auth/Hooks";
8
+ import { reportPersistenceFailure } from "@yielded/auth/Persistence";
9
+ import {
10
+ type ProofCompletionPlan,
11
+ ProofBinding,
12
+ type ProofAttemptDecision,
13
+ type ProofCleanupResult,
14
+ type ProofCompletionDecision,
15
+ type ProofDeliveryOutcome,
16
+ type ProofVersion,
17
+ type ProofBudget,
18
+ type ProofPolicy,
19
+ ProofPersistence,
20
+ type ProofDeliveryClaim,
21
+ ProofRequestConflict,
22
+ ProofUnavailable,
23
+ } from "@yielded/auth/Proofs";
24
+ /* oxlint-disable no-explicit-any -- existing storage kernels erase foreign table shapes; domain errors remain typed. */
25
+ import type { Table, sql } from "drizzle-orm";
26
+ import type { EffectDrizzleQueryError } from "drizzle-orm/effect-core";
27
+ import { Cause, Context, DateTime, Effect, Option, Schema } from "effect";
28
+ import type * as SqlError from "effect/unstable/sql/SqlError";
29
+
30
+ import {
31
+ CurrentPasswordPreparedTransaction,
32
+ PasswordPreparedPostconditions,
33
+ } from "../drizzle/PasswordPreparedPostconditions";
34
+ import {
35
+ type AnyProofPersistenceMapping,
36
+ requiredProofConstraints,
37
+ type ProofPersistenceMapping,
38
+ type ProofAction,
39
+ type ProofCommandDecision,
40
+ type ProofContinuationRecord,
41
+ type ProofScopeKeys,
42
+ type ProofScopeKind,
43
+ } from "../drizzle/proof-model";
44
+ import { PersistenceMappingError } from "./mapping-error";
45
+ import type { QueryOperations } from "./query-operations";
46
+
47
+ type AdapterFailure = EffectDrizzleQueryError | PersistenceMappingError | SqlError.SqlError;
48
+
49
+ export interface ProofSqlQuery<A = ReadonlyArray<any>> extends Effect.Effect<A, AdapterFailure> {
50
+ readonly getSQL: () => ReturnType<typeof sql>;
51
+ readonly from: (...args: ReadonlyArray<any>) => ProofSqlQuery<A>;
52
+ readonly where: (...args: ReadonlyArray<any>) => ProofSqlQuery<A>;
53
+ readonly limit: (...args: ReadonlyArray<any>) => ProofSqlQuery<A>;
54
+ readonly orderBy: (...args: ReadonlyArray<any>) => ProofSqlQuery<A>;
55
+ readonly for: (...args: ReadonlyArray<any>) => ProofSqlQuery<A>;
56
+ readonly set: (...args: ReadonlyArray<any>) => ProofSqlQuery<A>;
57
+ readonly values: (...args: ReadonlyArray<any>) => ProofSqlQuery<A>;
58
+ readonly onConflictDoNothing: (...args: ReadonlyArray<any>) => ProofSqlQuery<A>;
59
+ readonly onDuplicateKeyUpdate: (...args: ReadonlyArray<any>) => ProofSqlQuery<A>;
60
+ }
61
+
62
+ export interface ProofSqlDatabase {
63
+ readonly select: (...args: ReadonlyArray<any>) => ProofSqlQuery;
64
+ readonly insert: (...args: ReadonlyArray<any>) => ProofSqlQuery;
65
+ readonly update: (...args: ReadonlyArray<any>) => ProofSqlQuery;
66
+ readonly delete: (...args: ReadonlyArray<any>) => ProofSqlQuery;
67
+ readonly transaction: <A, E, R>(
68
+ body: (transaction: ProofSqlDatabase) => Effect.Effect<A, E, R>,
69
+ ) => Effect.Effect<A, E | SqlError.SqlError, R>;
70
+ }
71
+
72
+ export class CurrentProofSql extends Context.Service<CurrentProofSql, ProofSqlDatabase>()(
73
+ "effect-auth/CurrentProofSql",
74
+ ) {}
75
+
76
+ export interface ProofSqlConfiguration {
77
+ readonly mode: "interactive" | "synchronous";
78
+ readonly locking: boolean;
79
+ readonly standaloneGuard: Effect.Effect<void, ProofUnavailable>;
80
+ readonly coordinated?: boolean;
81
+ /** Dialect-native insert-if-absent used to create serialization anchors. */
82
+ readonly insertIfAbsent: (
83
+ query: ProofSqlQuery,
84
+ selfKey: string,
85
+ selfValue: unknown,
86
+ ) => ProofSqlQuery;
87
+ }
88
+
89
+ type Database = ProofSqlDatabase;
90
+
91
+ type Mapping = AnyProofPersistenceMapping;
92
+
93
+ interface ScopeEntry {
94
+ readonly kind: ProofScopeKind;
95
+ readonly key: string;
96
+ readonly budget: ProofBudget;
97
+ }
98
+
99
+ export const makeProofKernel = (operations: QueryOperations) => {
100
+ const { and, eq, gte, inArray, isNull, lte, notExists, sql, column, updateValues } = operations;
101
+ const unavailable = () => ProofUnavailable.make({});
102
+
103
+ const translateFailure = <A, E, R>(
104
+ effect: Effect.Effect<A, E, R>,
105
+ ): Effect.Effect<A, ProofUnavailable, R> =>
106
+ reportPersistenceFailure(
107
+ effect,
108
+ (error) => Schema.is(ProofUnavailable)(error) || Schema.is(HookConfigurationError)(error),
109
+ ).pipe(Effect.catchCause((cause) => Effect.failCause(Cause.map(cause, () => unavailable()))));
110
+
111
+ const translateIssueFailure = <A, E, R>(
112
+ effect: Effect.Effect<A, E, R>,
113
+ ): Effect.Effect<A, ProofUnavailable | ProofRequestConflict, R> =>
114
+ reportPersistenceFailure(
115
+ effect,
116
+ (error) =>
117
+ Schema.is(ProofUnavailable)(error) ||
118
+ Schema.is(ProofRequestConflict)(error) ||
119
+ Schema.is(HookConfigurationError)(error),
120
+ ).pipe(
121
+ Effect.catchCause((cause) =>
122
+ Effect.failCause(
123
+ Cause.map(cause, (error) =>
124
+ Schema.is(ProofRequestConflict)(error) ? error : unavailable(),
125
+ ),
126
+ ),
127
+ ),
128
+ );
129
+
130
+ const conflict = () => ProofRequestConflict.make({});
131
+
132
+ const validConstraints = (mapping: Mapping) =>
133
+ Object.entries(requiredProofConstraints).every(
134
+ ([key, value]) => mapping.constraints[key as keyof typeof requiredProofConstraints] === value,
135
+ );
136
+
137
+ const selectRows = (query: ProofSqlQuery, locking: boolean) =>
138
+ locking && typeof query.for === "function" ? query.for("update") : query;
139
+
140
+ const allocateVersion = (
141
+ mapping: Mapping,
142
+ mode: ProofSqlConfiguration["mode"],
143
+ ): Effect.Effect<ProofVersion, ProofUnavailable | PersistenceMappingError> => {
144
+ if (mode === "synchronous")
145
+ return mapping.allocateVersionSync === undefined
146
+ ? Effect.fail(unavailable())
147
+ : Effect.try({
148
+ try: mapping.allocateVersionSync,
149
+ catch: (cause) => new PersistenceMappingError({ operation: "mapping", cause }),
150
+ });
151
+ if (mapping.allocateVersion !== undefined) return mapping.allocateVersion;
152
+
153
+ return mapping.allocateVersionSync === undefined
154
+ ? Effect.fail(unavailable())
155
+ : Effect.try({
156
+ try: mapping.allocateVersionSync,
157
+ catch: (cause) => new PersistenceMappingError({ operation: "mapping", cause }),
158
+ });
159
+ };
160
+
161
+ const canonicalBinding = Schema.encodeSync(Schema.fromJsonString(ProofBinding));
162
+
163
+ const sameBinding = (left: ProofBinding, right: ProofBinding): boolean =>
164
+ canonicalBinding(left) === canonicalBinding(right);
165
+
166
+ const requestColumns = (mapping: Mapping) => ({
167
+ moduleId: column(mapping.request.table, mapping.request.moduleId),
168
+ requestId: column(mapping.request.table, mapping.request.requestId),
169
+ fingerprint: column(mapping.request.table, mapping.request.fingerprint),
170
+ proofId: column(mapping.request.table, mapping.request.proofId),
171
+ retentionUntil: column(mapping.request.table, mapping.request.retentionUntil),
172
+ });
173
+
174
+ const seriesColumns = (mapping: Mapping) => ({
175
+ moduleId: column(mapping.series.table, mapping.series.moduleId),
176
+ purpose: column(mapping.series.table, mapping.series.purpose),
177
+ scopeKey: column(mapping.series.table, mapping.series.scopeKey),
178
+ activeProofId: column(mapping.series.table, mapping.series.activeProofId),
179
+ lastIssueAt: column(mapping.series.table, mapping.series.lastIssueAt),
180
+ version: column(mapping.series.table, mapping.series.version),
181
+ });
182
+
183
+ const generationColumns = (mapping: Mapping) => ({
184
+ moduleId: column(mapping.generation.table, mapping.generation.moduleId),
185
+ purpose: column(mapping.generation.table, mapping.generation.purpose),
186
+ proofId: column(mapping.generation.table, mapping.generation.proofId),
187
+ requestId: column(mapping.generation.table, mapping.generation.requestId),
188
+ seriesKey: column(mapping.generation.table, mapping.generation.seriesKey),
189
+ deliveryId: column(mapping.generation.table, mapping.generation.deliveryId),
190
+ verifierKeyId: column(mapping.generation.table, mapping.generation.verifierKeyId),
191
+ verifierDigest: column(mapping.generation.table, mapping.generation.verifierDigest),
192
+ issuedAt: column(mapping.generation.table, mapping.generation.issuedAt),
193
+ expiresAt: column(mapping.generation.table, mapping.generation.expiresAt),
194
+ version: column(mapping.generation.table, mapping.generation.version),
195
+ state: column(mapping.generation.table, mapping.generation.state),
196
+ sendCount: column(mapping.generation.table, mapping.generation.sendCount),
197
+ deliveryState: column(mapping.generation.table, mapping.generation.deliveryState),
198
+ claimVersion: column(mapping.generation.table, mapping.generation.claimVersion),
199
+ claimDeadline: column(mapping.generation.table, mapping.generation.claimDeadline),
200
+ retryAt: column(mapping.generation.table, mapping.generation.retryAt),
201
+ deliveryRetryMillis: column(mapping.generation.table, mapping.generation.deliveryRetryMillis),
202
+ retentionUntil: column(mapping.generation.table, mapping.generation.retentionUntil),
203
+ });
204
+
205
+ const continuationColumns = (mapping: Mapping) => ({
206
+ moduleId: column(mapping.continuation.table, mapping.continuation.moduleId),
207
+ purpose: column(mapping.continuation.table, mapping.continuation.purpose),
208
+ continuationId: column(mapping.continuation.table, mapping.continuation.continuationId),
209
+ digest: column(mapping.continuation.table, mapping.continuation.digest),
210
+ proofId: column(mapping.continuation.table, mapping.continuation.proofId),
211
+ seriesKey: column(mapping.continuation.table, mapping.continuation.seriesKey),
212
+ expiresAt: column(mapping.continuation.table, mapping.continuation.expiresAt),
213
+ consumed: column(mapping.continuation.table, mapping.continuation.consumed),
214
+ version: column(mapping.continuation.table, mapping.continuation.version),
215
+ retentionUntil: column(mapping.continuation.table, mapping.continuation.retentionUntil),
216
+ });
217
+
218
+ const scopeColumns = (mapping: Mapping) => ({
219
+ moduleId: column(mapping.rateScope.table, mapping.rateScope.moduleId),
220
+ purpose: column(mapping.rateScope.table, mapping.rateScope.purpose),
221
+ action: column(mapping.rateScope.table, mapping.rateScope.action),
222
+ scopeKind: column(mapping.rateScope.table, mapping.rateScope.scopeKind),
223
+ scopeKey: column(mapping.rateScope.table, mapping.rateScope.scopeKey),
224
+ });
225
+
226
+ const abuseColumns = (mapping: Mapping) => ({
227
+ moduleId: column(mapping.abuseEvent.table, mapping.abuseEvent.moduleId),
228
+ purpose: column(mapping.abuseEvent.table, mapping.abuseEvent.purpose),
229
+ action: column(mapping.abuseEvent.table, mapping.abuseEvent.action),
230
+ scopeKind: column(mapping.abuseEvent.table, mapping.abuseEvent.scopeKind),
231
+ scopeKey: column(mapping.abuseEvent.table, mapping.abuseEvent.scopeKey),
232
+ commandId: column(mapping.abuseEvent.table, mapping.abuseEvent.commandId),
233
+ occurredAt: column(mapping.abuseEvent.table, mapping.abuseEvent.occurredAt),
234
+ retentionUntil: column(mapping.abuseEvent.table, mapping.abuseEvent.retentionUntil),
235
+ });
236
+
237
+ const failureColumns = (mapping: Mapping) => ({
238
+ moduleId: column(mapping.failureEvent.table, mapping.failureEvent.moduleId),
239
+ purpose: column(mapping.failureEvent.table, mapping.failureEvent.purpose),
240
+ seriesKey: column(mapping.failureEvent.table, mapping.failureEvent.seriesKey),
241
+ commandId: column(mapping.failureEvent.table, mapping.failureEvent.commandId),
242
+ occurredAt: column(mapping.failureEvent.table, mapping.failureEvent.occurredAt),
243
+ retentionUntil: column(mapping.failureEvent.table, mapping.failureEvent.retentionUntil),
244
+ });
245
+
246
+ const commandColumns = (mapping: Mapping) => ({
247
+ moduleId: column(mapping.command.table, mapping.command.moduleId),
248
+ commandId: column(mapping.command.table, mapping.command.commandId),
249
+ kind: column(mapping.command.table, mapping.command.kind),
250
+ decision: column(mapping.command.table, mapping.command.decision),
251
+ retentionUntil: column(mapping.command.table, mapping.command.retentionUntil),
252
+ });
253
+
254
+ const nowMillis = DateTime.now.pipe(Effect.map(DateTime.toEpochMillis));
255
+
256
+ const lockAuthority = Effect.fn("DrizzleProof.lockAuthority")(function* (
257
+ mapping: Mapping,
258
+ moduleId: string,
259
+ purpose: any,
260
+ binding: ProofBinding,
261
+ locking: boolean,
262
+ ) {
263
+ const database = yield* CurrentProofSql;
264
+
265
+ const authority = mapping.authority;
266
+ let nativeSubjectId: unknown | undefined;
267
+
268
+ // Canonical order: subject, identifier rows, credentials sorted by ID.
269
+ if (binding._tag !== "Identifier") {
270
+ if (
271
+ authority.subject === undefined ||
272
+ authority.credential === undefined ||
273
+ authority.subjectId === undefined
274
+ )
275
+ return yield* unavailable();
276
+ nativeSubjectId = yield* authority.subjectId.toNative(binding.revision.subjectId);
277
+ const subject = authority.subject;
278
+
279
+ const rows = yield* selectRows(
280
+ database
281
+ .select()
282
+ .from(subject.table)
283
+ .where(eq(column(subject.table, subject.id), nativeSubjectId))
284
+ .limit(1),
285
+ locking,
286
+ );
287
+
288
+ const row = rows[0];
289
+
290
+ if (
291
+ row === undefined ||
292
+ !subject.isActiveStatus(row[subject.status]) ||
293
+ row[subject.securityRevision] !== binding.revision.securityRevision
294
+ )
295
+ return false;
296
+ }
297
+ const identifier = authority.identifier;
298
+
299
+ const identifierRows = yield* selectRows(
300
+ database
301
+ .select()
302
+ .from(identifier.table)
303
+ .where(
304
+ and(
305
+ eq(column(identifier.table, identifier.namespace), binding.identifier.namespace),
306
+ eq(column(identifier.table, identifier.value), binding.identifier.value),
307
+ ),
308
+ ),
309
+ locking,
310
+ );
311
+
312
+ if (
313
+ !identifier.isCurrent(
314
+ {
315
+ moduleId,
316
+ purpose,
317
+ binding,
318
+ ...(nativeSubjectId === undefined ? {} : { nativeSubjectId }),
319
+ },
320
+ identifierRows,
321
+ )
322
+ )
323
+ return false;
324
+ if (binding._tag === "Identifier") return true;
325
+ const credential = authority.credential!;
326
+
327
+ const expected = [...binding.revision.credentials].sort((a, b) =>
328
+ a.credentialId.localeCompare(b.credentialId),
329
+ );
330
+
331
+ const rows =
332
+ expected.length === 0
333
+ ? []
334
+ : yield* selectRows(
335
+ database
336
+ .select()
337
+ .from(credential.table)
338
+ .where(
339
+ and(
340
+ eq(column(credential.table, credential.subjectId), nativeSubjectId),
341
+ inArray(
342
+ column(credential.table, credential.credentialId),
343
+ expected.map((item) => item.credentialId),
344
+ ),
345
+ ),
346
+ ),
347
+ locking,
348
+ );
349
+
350
+ if (rows.length !== expected.length) return false;
351
+
352
+ const actual = rows
353
+ .map((row: any) => ({
354
+ credentialId: row[credential.credentialId] as string,
355
+ revision: row[credential.revision],
356
+ active:
357
+ credential.status === undefined ||
358
+ credential.isActiveStatus?.(row[credential.status]) === true,
359
+ }))
360
+ .sort((a: any, b: any) => a.credentialId.localeCompare(b.credentialId));
361
+
362
+ return actual.every(
363
+ (item: any, index: number) =>
364
+ item.active &&
365
+ item.credentialId === expected[index]?.credentialId &&
366
+ item.revision === expected[index]?.revision,
367
+ );
368
+ });
369
+
370
+ const scopeEntries = (
371
+ keys: ProofScopeKeys,
372
+ binding: ProofBinding,
373
+ action: ProofAction,
374
+ policy: ProofPolicy,
375
+ ): ReadonlyArray<ScopeEntry> => {
376
+ const suffix = action === "issue" ? "Issues" : "Attempts";
377
+ const simple = action === "issue" ? "issues" : "attempts";
378
+
379
+ const entries: ScopeEntry[] = [
380
+ { kind: "action", key: "*", budget: policy.abuse[`action${suffix}`] },
381
+ { kind: "identifier", key: keys.identifier, budget: policy.abuse[simple] },
382
+ ];
383
+
384
+ if (binding._tag !== "Identifier")
385
+ entries.push({
386
+ kind: "subject",
387
+ key: keys.subject,
388
+ budget: policy.abuse[`subject${suffix}`],
389
+ });
390
+
391
+ return entries;
392
+ };
393
+
394
+ const lockScopes = Effect.fn("DrizzleProof.lockScopes")(function* (
395
+ mapping: Mapping,
396
+ configuration: ProofSqlConfiguration,
397
+ moduleId: string,
398
+ purpose: any,
399
+ action: ProofAction,
400
+ entries: ReadonlyArray<ScopeEntry>,
401
+ ) {
402
+ const database = yield* CurrentProofSql;
403
+
404
+ const c = scopeColumns(mapping);
405
+
406
+ for (const entry of entries) {
407
+ const values = mapping.rateScope.encodeInsert({
408
+ moduleId,
409
+ purpose,
410
+ action,
411
+ scopeKind: entry.kind,
412
+ scopeKey: entry.key,
413
+ });
414
+
415
+ const query = database.insert(mapping.rateScope.table).values(values);
416
+
417
+ yield* configuration.insertIfAbsent(query, mapping.rateScope.scopeKey, entry.key);
418
+ yield* selectRows(
419
+ database
420
+ .select()
421
+ .from(mapping.rateScope.table)
422
+ .where(
423
+ and(
424
+ eq(c.moduleId, moduleId),
425
+ eq(c.purpose, purpose),
426
+ eq(c.action, action),
427
+ eq(c.scopeKind, entry.kind),
428
+ eq(c.scopeKey, entry.key),
429
+ ),
430
+ )
431
+ .limit(1),
432
+ configuration.locking,
433
+ );
434
+ }
435
+ });
436
+
437
+ const admittedScopes = Effect.fn("DrizzleProof.admittedScopes")(function* (
438
+ mapping: Mapping,
439
+ moduleId: string,
440
+ purpose: any,
441
+ action: ProofAction,
442
+ entries: ReadonlyArray<ScopeEntry>,
443
+ now: number,
444
+ ) {
445
+ const database = yield* CurrentProofSql;
446
+
447
+ const c = abuseColumns(mapping);
448
+ const admitted: ScopeEntry[] = [];
449
+
450
+ for (const entry of entries) {
451
+ const rows = yield* selectRows(
452
+ database
453
+ .select({ commandId: c.commandId })
454
+ .from(mapping.abuseEvent.table)
455
+ .where(
456
+ and(
457
+ eq(c.moduleId, moduleId),
458
+ eq(c.purpose, purpose),
459
+ eq(c.action, action),
460
+ eq(c.scopeKind, entry.kind),
461
+ eq(c.scopeKey, entry.key),
462
+ gte(c.occurredAt, mapping.encodeInstant(now - entry.budget.windowMillis)),
463
+ ),
464
+ )
465
+ .limit(entry.budget.limit),
466
+ true,
467
+ );
468
+
469
+ if (rows.length < entry.budget.limit) admitted.push(entry);
470
+ }
471
+
472
+ return admitted;
473
+ });
474
+
475
+ const insertScopeEvents = Effect.fn("Drizzle.insertScopeEvents")(function* (
476
+ mapping: Mapping,
477
+ moduleId: string,
478
+ purpose: any,
479
+ action: ProofAction,
480
+ commandId: string,
481
+ entries: ReadonlyArray<ScopeEntry>,
482
+ now: number,
483
+ retentionUntil: number,
484
+ ) {
485
+ const database = yield* CurrentProofSql;
486
+
487
+ return yield* Effect.forEach(
488
+ entries,
489
+ (entry) =>
490
+ database.insert(mapping.abuseEvent.table).values(
491
+ mapping.abuseEvent.encodeInsert({
492
+ moduleId,
493
+ purpose,
494
+ action,
495
+ scopeKind: entry.kind,
496
+ scopeKey: entry.key,
497
+ commandId,
498
+ occurredAtMillis: now,
499
+ retentionUntilMillis: retentionUntil,
500
+ }),
501
+ ),
502
+ { discard: true },
503
+ );
504
+ });
505
+
506
+ const ensureSeries = Effect.fn("DrizzleProof.ensureSeries")(function* (
507
+ mapping: Mapping,
508
+ configuration: ProofSqlConfiguration,
509
+ moduleId: string,
510
+ purpose: any,
511
+ scopeKey: string,
512
+ ) {
513
+ const database = yield* CurrentProofSql;
514
+
515
+ const c = seriesColumns(mapping);
516
+ const initialVersion = yield* allocateVersion(mapping, configuration.mode);
517
+
518
+ const query = database
519
+ .insert(mapping.series.table)
520
+ .values(
521
+ mapping.series.encodeInsert({ moduleId, purpose, scopeKey, version: initialVersion }),
522
+ );
523
+
524
+ yield* configuration.insertIfAbsent(query, mapping.series.scopeKey, scopeKey);
525
+
526
+ const rows = yield* selectRows(
527
+ database
528
+ .select()
529
+ .from(mapping.series.table)
530
+ .where(and(eq(c.moduleId, moduleId), eq(c.purpose, purpose), eq(c.scopeKey, scopeKey)))
531
+ .limit(1),
532
+ configuration.locking,
533
+ );
534
+
535
+ return rows[0] ?? (yield* unavailable());
536
+ });
537
+
538
+ const readGeneration = Effect.fn("Drizzle.readGeneration")(function* (
539
+ mapping: Mapping,
540
+ moduleId: string,
541
+ proofId: string,
542
+ locking: boolean,
543
+ ) {
544
+ const database = yield* CurrentProofSql;
545
+
546
+ const c = generationColumns(mapping);
547
+
548
+ return yield* selectRows(
549
+ database
550
+ .select()
551
+ .from(mapping.generation.table)
552
+ .where(and(eq(c.moduleId, moduleId), eq(c.proofId, proofId)))
553
+ .limit(1),
554
+ locking,
555
+ );
556
+ });
557
+
558
+ const failureCount = Effect.fn("DrizzleProof.failureCount")(function* (
559
+ mapping: Mapping,
560
+ moduleId: string,
561
+ purpose: any,
562
+ seriesKey: string,
563
+ now: number,
564
+ policy: ProofPolicy,
565
+ ) {
566
+ const database = yield* CurrentProofSql;
567
+
568
+ const c = failureColumns(mapping);
569
+
570
+ const rows = yield* selectRows(
571
+ database
572
+ .select({ commandId: c.commandId })
573
+ .from(mapping.failureEvent.table)
574
+ .where(
575
+ and(
576
+ eq(c.moduleId, moduleId),
577
+ eq(c.purpose, purpose),
578
+ eq(c.seriesKey, seriesKey),
579
+ gte(c.occurredAt, mapping.encodeInstant(now - policy.abuse.attempts.windowMillis)),
580
+ ),
581
+ )
582
+ .limit(policy.maximumFailedAttempts),
583
+ true,
584
+ );
585
+
586
+ return rows.length;
587
+ });
588
+
589
+ const commandRow = Effect.fn("Drizzle.commandRow")(function* (
590
+ mapping: Mapping,
591
+ moduleId: string,
592
+ commandId: string,
593
+ locking: boolean,
594
+ ) {
595
+ const database = yield* CurrentProofSql;
596
+
597
+ const c = commandColumns(mapping);
598
+
599
+ return yield* selectRows(
600
+ database
601
+ .select()
602
+ .from(mapping.command.table)
603
+ .where(and(eq(c.moduleId, moduleId), eq(c.commandId, commandId)))
604
+ .limit(1),
605
+ locking,
606
+ );
607
+ });
608
+
609
+ const insertCommand = Effect.fn("Drizzle.insertCommand")(function* (
610
+ mapping: Mapping,
611
+ moduleId: string,
612
+ commandId: string,
613
+ kind: "attempt" | "complete",
614
+ decision: ProofCommandDecision,
615
+ retentionUntil: number,
616
+ ) {
617
+ const database = yield* CurrentProofSql;
618
+
619
+ return yield* database.insert(mapping.command.table).values(
620
+ mapping.command.encodeInsert({
621
+ moduleId,
622
+ commandId,
623
+ kind,
624
+ decision,
625
+ retentionUntilMillis: retentionUntil,
626
+ }),
627
+ );
628
+ });
629
+
630
+ const owned = <A, E, R>(
631
+ database: Database,
632
+ mapping: Mapping,
633
+ configuration: ProofSqlConfiguration,
634
+ body: Effect.Effect<A, E, R>,
635
+ ) => {
636
+ if (!validConstraints(mapping)) return Effect.fail(unavailable());
637
+
638
+ const run = coordinateCommit(
639
+ () =>
640
+ database.transaction((transaction) =>
641
+ body.pipe(Effect.provideService(CurrentProofSql, transaction)),
642
+ ),
643
+ { mode: configuration.mode },
644
+ ).pipe(Effect.map((result) => result.value));
645
+
646
+ return configuration.coordinated !== true
647
+ ? Effect.gen(function* () {
648
+ if (yield* hasCommitScope) return yield* unavailable();
649
+ yield* configuration.standaloneGuard;
650
+
651
+ return yield* run;
652
+ })
653
+ : run;
654
+ };
655
+
656
+ const makeSqlProofPersistence = Effect.fn("makeSqlProofPersistence")(function* (
657
+ database: Database,
658
+ mapping: Mapping,
659
+ configuration: ProofSqlConfiguration,
660
+ ): Effect.fn.Return<ProofPersistence["Service"], never, LifecycleHooks> {
661
+ const hooks = yield* LifecycleHooks;
662
+
663
+ return ProofPersistence.of({
664
+ issue: (input, prepare) =>
665
+ owned(
666
+ database,
667
+ mapping,
668
+ configuration,
669
+ Effect.gen(function* () {
670
+ const transaction = yield* CurrentProofSql;
671
+ const journal = yield* CurrentCommitJournal;
672
+
673
+ const keys = mapping.scopeKeys({
674
+ moduleId: input.record.moduleId,
675
+ purpose: input.record.purpose,
676
+ binding: input.record.binding,
677
+ });
678
+
679
+ const authorityCurrent = yield* lockAuthority(
680
+ mapping,
681
+ input.record.moduleId,
682
+ input.record.purpose,
683
+ input.record.binding,
684
+ configuration.locking,
685
+ );
686
+
687
+ const scopes = scopeEntries(keys, input.record.binding, "issue", input.policy);
688
+
689
+ yield* lockScopes(
690
+ mapping,
691
+ configuration,
692
+ input.record.moduleId,
693
+ input.record.purpose,
694
+ "issue",
695
+ scopes.slice(0, 1),
696
+ );
697
+ const actionNow = yield* nowMillis;
698
+
699
+ const actionOpen =
700
+ (yield* admittedScopes(
701
+ mapping,
702
+ input.record.moduleId,
703
+ input.record.purpose,
704
+ "issue",
705
+ scopes.slice(0, 1),
706
+ actionNow,
707
+ )).length === 1;
708
+
709
+ if (actionOpen)
710
+ yield* lockScopes(
711
+ mapping,
712
+ configuration,
713
+ input.record.moduleId,
714
+ input.record.purpose,
715
+ "issue",
716
+ scopes.slice(1),
717
+ );
718
+
719
+ const series = actionOpen
720
+ ? yield* ensureSeries(
721
+ mapping,
722
+ configuration,
723
+ input.record.moduleId,
724
+ input.record.purpose,
725
+ keys.series,
726
+ )
727
+ : undefined;
728
+
729
+ const now = yield* nowMillis;
730
+ const retentionUntil = now + input.policy.requestRetentionMillis;
731
+ const rc = requestColumns(mapping);
732
+
733
+ let requestRows = yield* selectRows(
734
+ transaction
735
+ .select()
736
+ .from(mapping.request.table)
737
+ .where(
738
+ and(
739
+ eq(rc.moduleId, input.record.moduleId),
740
+ eq(rc.requestId, input.record.requestId),
741
+ ),
742
+ )
743
+ .limit(1),
744
+ configuration.locking,
745
+ );
746
+
747
+ let request = requestRows[0];
748
+
749
+ if (request !== undefined) {
750
+ const retainedUntil = yield* mapping.decodeInstant(
751
+ request[mapping.request.retentionUntil],
752
+ );
753
+
754
+ if (retainedUntil > now) {
755
+ if (request[mapping.request.fingerprint] !== input.record.fingerprint)
756
+ return yield* conflict();
757
+ const receipt = yield* mapping.request.decodeReceipt(request);
758
+
759
+ return prepare({ _tag: "Existing", receipt }, journal);
760
+ }
761
+ yield* transaction
762
+ .delete(mapping.request.table)
763
+ .where(
764
+ and(
765
+ eq(rc.moduleId, input.record.moduleId),
766
+ eq(rc.requestId, input.record.requestId),
767
+ lte(rc.retentionUntil, mapping.encodeInstant(now)),
768
+ ),
769
+ );
770
+ }
771
+
772
+ const requestInsert = mapping.request.encodeInsert({
773
+ record: input.record,
774
+ createdAtMillis: now,
775
+ retentionUntilMillis: retentionUntil,
776
+ });
777
+
778
+ const requestQuery = transaction.insert(mapping.request.table).values(requestInsert);
779
+
780
+ yield* configuration.insertIfAbsent(
781
+ requestQuery,
782
+ mapping.request.requestId,
783
+ input.record.requestId,
784
+ );
785
+ requestRows = yield* selectRows(
786
+ transaction
787
+ .select()
788
+ .from(mapping.request.table)
789
+ .where(
790
+ and(
791
+ eq(rc.moduleId, input.record.moduleId),
792
+ eq(rc.requestId, input.record.requestId),
793
+ ),
794
+ )
795
+ .limit(1),
796
+ configuration.locking,
797
+ );
798
+ request = requestRows[0];
799
+
800
+ if (request === undefined) return yield* unavailable();
801
+ if (request[mapping.request.fingerprint] !== input.record.fingerprint)
802
+ return yield* conflict();
803
+ if (request[mapping.request.proofId] !== input.record.proofId) {
804
+ const receipt = yield* mapping.request.decodeReceipt(request);
805
+
806
+ return prepare({ _tag: "Existing", receipt }, journal);
807
+ }
808
+
809
+ const admitted = actionOpen
810
+ ? yield* admittedScopes(
811
+ mapping,
812
+ input.record.moduleId,
813
+ input.record.purpose,
814
+ "issue",
815
+ scopes,
816
+ now,
817
+ )
818
+ : [];
819
+
820
+ const sc = seriesColumns(mapping);
821
+
822
+ const lastIssueAt =
823
+ series?.[mapping.series.lastIssueAt] === null ||
824
+ series?.[mapping.series.lastIssueAt] === undefined
825
+ ? undefined
826
+ : yield* mapping.decodeInstant(series[mapping.series.lastIssueAt]);
827
+
828
+ const activeProofId = series?.[mapping.series.activeProofId] as
829
+ | string
830
+ | null
831
+ | undefined;
832
+
833
+ const supersedesCurrent =
834
+ input.supersedes === undefined || input.supersedes === activeProofId;
835
+
836
+ const allowed =
837
+ authorityCurrent &&
838
+ input.eligible &&
839
+ admitted.length === scopes.length &&
840
+ input.record.issuedAtMillis <= now &&
841
+ input.record.expiresAtMillis > now &&
842
+ supersedesCurrent &&
843
+ (lastIssueAt === undefined ||
844
+ now - lastIssueAt >= input.policy.abuse.resendCooldownMillis);
845
+
846
+ const receipt = {
847
+ requestId: input.record.requestId,
848
+ reference: {
849
+ proofId: input.record.proofId,
850
+ purpose: input.record.purpose,
851
+ keyId: input.record.verifier.keyId,
852
+ },
853
+ };
854
+
855
+ const prepared = prepare(
856
+ allowed
857
+ ? ({ _tag: "Issued", record: input.record } as const)
858
+ : ({ _tag: "Suppressed", receipt } as const),
859
+ journal,
860
+ );
861
+
862
+ if (admitted.length > 0)
863
+ yield* insertScopeEvents(
864
+ mapping,
865
+ input.record.moduleId,
866
+ input.record.purpose,
867
+ "issue",
868
+ input.record.requestId,
869
+ admitted,
870
+ now,
871
+ retentionUntil,
872
+ );
873
+ if (!allowed) return prepared;
874
+ if (activeProofId !== null && activeProofId !== undefined)
875
+ yield* transaction
876
+ .update(mapping.generation.table)
877
+ .set(updateValues<any>([[mapping.generation.state, "superseded"]]))
878
+ .where(
879
+ and(
880
+ eq(generationColumns(mapping).moduleId, input.record.moduleId),
881
+ eq(generationColumns(mapping).proofId, activeProofId),
882
+ eq(generationColumns(mapping).state, "active"),
883
+ ),
884
+ );
885
+ yield* transaction.insert(mapping.generation.table).values(
886
+ mapping.generation.encodeInsert({
887
+ record: input.record,
888
+ seriesKey: keys.series,
889
+ retentionUntilMillis: retentionUntil,
890
+ state: "active",
891
+ deliveryState: "new",
892
+ policy: input.policy,
893
+ }),
894
+ );
895
+ const nextVersion = yield* allocateVersion(mapping, configuration.mode);
896
+
897
+ yield* transaction
898
+ .update(mapping.series.table)
899
+ .set(
900
+ updateValues<any>([
901
+ [mapping.series.activeProofId, input.record.proofId],
902
+ [mapping.series.lastIssueAt, mapping.encodeInstant(now)],
903
+ [mapping.series.version, nextVersion],
904
+ ]),
905
+ )
906
+ .where(
907
+ and(
908
+ eq(sc.moduleId, input.record.moduleId),
909
+ eq(sc.purpose, input.record.purpose),
910
+ eq(sc.scopeKey, keys.series),
911
+ ),
912
+ );
913
+
914
+ return prepared;
915
+ }),
916
+ ).pipe(
917
+ Effect.provideService(CurrentProofSql, database),
918
+ Effect.provideService(LifecycleHooks, hooks),
919
+ translateIssueFailure,
920
+ ),
921
+ attempt: (input, prepare) =>
922
+ owned(
923
+ database,
924
+ mapping,
925
+ configuration,
926
+ Effect.gen(function* () {
927
+ const transaction = yield* CurrentProofSql;
928
+ const journal = yield* CurrentCommitJournal;
929
+
930
+ const keys = mapping.scopeKeys({
931
+ moduleId: input.moduleId,
932
+ purpose: input.purpose,
933
+ binding: input.binding,
934
+ });
935
+
936
+ const authorityCurrent = yield* lockAuthority(
937
+ mapping,
938
+ input.moduleId,
939
+ input.purpose,
940
+ input.binding,
941
+ configuration.locking,
942
+ );
943
+
944
+ const scopes = scopeEntries(keys, input.binding, "attempt", input.policy);
945
+
946
+ yield* lockScopes(
947
+ mapping,
948
+ configuration,
949
+ input.moduleId,
950
+ input.purpose,
951
+ "attempt",
952
+ scopes.slice(0, 1),
953
+ );
954
+ const actionNow = yield* nowMillis;
955
+
956
+ const actionOpen =
957
+ (yield* admittedScopes(
958
+ mapping,
959
+ input.moduleId,
960
+ input.purpose,
961
+ "attempt",
962
+ scopes.slice(0, 1),
963
+ actionNow,
964
+ )).length === 1;
965
+
966
+ if (actionOpen)
967
+ yield* lockScopes(
968
+ mapping,
969
+ configuration,
970
+ input.moduleId,
971
+ input.purpose,
972
+ "attempt",
973
+ scopes.slice(1),
974
+ );
975
+
976
+ const series = actionOpen
977
+ ? yield* ensureSeries(
978
+ mapping,
979
+ configuration,
980
+ input.moduleId,
981
+ input.purpose,
982
+ keys.series,
983
+ )
984
+ : undefined;
985
+
986
+ const generation = (yield* readGeneration(
987
+ mapping,
988
+ input.moduleId,
989
+ input.proofId,
990
+ configuration.locking,
991
+ ))[0];
992
+
993
+ const existingCommand = (yield* commandRow(
994
+ mapping,
995
+ input.moduleId,
996
+ input.continuationId,
997
+ configuration.locking,
998
+ ))[0];
999
+
1000
+ if (existingCommand !== undefined) {
1001
+ if (existingCommand[mapping.command.decision] === "rejected")
1002
+ return prepare({ _tag: "Rejected" }, journal);
1003
+
1004
+ return yield* unavailable();
1005
+ }
1006
+ const now = yield* nowMillis;
1007
+
1008
+ const admitted = actionOpen
1009
+ ? yield* admittedScopes(
1010
+ mapping,
1011
+ input.moduleId,
1012
+ input.purpose,
1013
+ "attempt",
1014
+ scopes,
1015
+ now,
1016
+ )
1017
+ : [];
1018
+
1019
+ const failures = yield* failureCount(
1020
+ mapping,
1021
+ input.moduleId,
1022
+ input.purpose,
1023
+ keys.series,
1024
+ now,
1025
+ input.policy,
1026
+ );
1027
+
1028
+ const gc = generationColumns(mapping);
1029
+ const activeProofId = series?.[mapping.series.activeProofId];
1030
+
1031
+ const storedBinding =
1032
+ generation === undefined
1033
+ ? undefined
1034
+ : yield* mapping.generation.decodeBinding(generation);
1035
+
1036
+ const candidateMatches =
1037
+ generation !== undefined &&
1038
+ input.candidate !== undefined &&
1039
+ generation[mapping.generation.verifierKeyId] === input.candidate.keyId &&
1040
+ generation[mapping.generation.verifierDigest] === input.candidate.digest;
1041
+
1042
+ const currentGeneration =
1043
+ generation !== undefined &&
1044
+ generation[mapping.generation.purpose] === input.purpose &&
1045
+ generation[mapping.generation.state] === "active" &&
1046
+ activeProofId === input.proofId &&
1047
+ storedBinding !== undefined &&
1048
+ sameBinding(storedBinding, input.binding) &&
1049
+ Number(yield* mapping.decodeInstant(generation[mapping.generation.expiresAt])) > now;
1050
+
1051
+ const accepted =
1052
+ authorityCurrent &&
1053
+ currentGeneration &&
1054
+ candidateMatches &&
1055
+ admitted.length === scopes.length &&
1056
+ failures < input.policy.maximumFailedAttempts;
1057
+
1058
+ const retentionUntil = now + input.policy.requestRetentionMillis;
1059
+
1060
+ if (!accepted) {
1061
+ const prepared = prepare({ _tag: "Rejected" }, journal);
1062
+
1063
+ yield* insertCommand(
1064
+ mapping,
1065
+ input.moduleId,
1066
+ input.continuationId,
1067
+ "attempt",
1068
+ "rejected",
1069
+ retentionUntil,
1070
+ );
1071
+ yield* insertScopeEvents(
1072
+ mapping,
1073
+ input.moduleId,
1074
+ input.purpose,
1075
+ "attempt",
1076
+ input.continuationId,
1077
+ admitted,
1078
+ now,
1079
+ retentionUntil,
1080
+ );
1081
+ if (
1082
+ admitted.length === scopes.length &&
1083
+ currentGeneration &&
1084
+ !candidateMatches &&
1085
+ failures < input.policy.maximumFailedAttempts
1086
+ )
1087
+ yield* transaction.insert(mapping.failureEvent.table).values(
1088
+ mapping.failureEvent.encodeInsert({
1089
+ moduleId: input.moduleId,
1090
+ purpose: input.purpose,
1091
+ seriesKey: keys.series,
1092
+ commandId: input.continuationId,
1093
+ occurredAtMillis: now,
1094
+ retentionUntilMillis: retentionUntil,
1095
+ }),
1096
+ );
1097
+
1098
+ return prepared;
1099
+ }
1100
+ const version = yield* allocateVersion(mapping, configuration.mode);
1101
+
1102
+ const expiresAt = Math.min(
1103
+ Number(yield* mapping.decodeInstant(generation![mapping.generation.expiresAt])),
1104
+ now + input.policy.continuationLifetimeMillis,
1105
+ );
1106
+
1107
+ const continuation: ProofContinuationRecord = {
1108
+ moduleId: input.moduleId,
1109
+ purpose: input.purpose,
1110
+ continuationId: input.continuationId,
1111
+ digest: input.continuationDigest,
1112
+ proofId: input.proofId,
1113
+ seriesKey: keys.series,
1114
+ binding: input.binding,
1115
+ expiresAtMillis: expiresAt,
1116
+ version,
1117
+ };
1118
+
1119
+ const decision: ProofAttemptDecision = {
1120
+ _tag: "Accepted",
1121
+ continuation: {
1122
+ continuationId: input.continuationId,
1123
+ purpose: input.purpose,
1124
+ expiresAtMillis: expiresAt,
1125
+ },
1126
+ };
1127
+
1128
+ const prepared = prepare(decision, journal);
1129
+
1130
+ yield* insertCommand(
1131
+ mapping,
1132
+ input.moduleId,
1133
+ input.continuationId,
1134
+ "attempt",
1135
+ "accepted",
1136
+ retentionUntil,
1137
+ );
1138
+ yield* insertScopeEvents(
1139
+ mapping,
1140
+ input.moduleId,
1141
+ input.purpose,
1142
+ "attempt",
1143
+ input.continuationId,
1144
+ scopes,
1145
+ now,
1146
+ retentionUntil,
1147
+ );
1148
+ yield* transaction
1149
+ .update(mapping.generation.table)
1150
+ .set(updateValues<any>([[mapping.generation.state, "consumed"]]))
1151
+ .where(
1152
+ and(
1153
+ eq(gc.moduleId, input.moduleId),
1154
+ eq(gc.proofId, input.proofId),
1155
+ eq(gc.state, "active"),
1156
+ ),
1157
+ );
1158
+ yield* transaction.insert(mapping.continuation.table).values(
1159
+ mapping.continuation.encodeInsert({
1160
+ ...continuation,
1161
+ retentionUntilMillis: retentionUntil,
1162
+ }),
1163
+ );
1164
+
1165
+ return prepared;
1166
+ }),
1167
+ ).pipe(
1168
+ Effect.provideService(CurrentProofSql, database),
1169
+ Effect.provideService(LifecycleHooks, hooks),
1170
+ translateFailure,
1171
+ ),
1172
+ complete: (input, prepare) =>
1173
+ owned(
1174
+ database,
1175
+ mapping,
1176
+ configuration,
1177
+ Effect.gen(function* () {
1178
+ const journal = yield* CurrentCommitJournal;
1179
+
1180
+ return yield* completeIn(mapping, configuration, input, (decision) =>
1181
+ prepare(decision, journal),
1182
+ );
1183
+ }),
1184
+ ).pipe(
1185
+ Effect.provideService(CurrentProofSql, database),
1186
+ Effect.provideService(LifecycleHooks, hooks),
1187
+ translateFailure,
1188
+ ),
1189
+ claimDelivery: (input, prepare) =>
1190
+ owned(
1191
+ database,
1192
+ mapping,
1193
+ configuration,
1194
+ Effect.gen(function* () {
1195
+ const transaction = yield* CurrentProofSql;
1196
+ const journal = yield* CurrentCommitJournal;
1197
+
1198
+ const rows = yield* readGeneration(
1199
+ mapping,
1200
+ input.moduleId,
1201
+ input.proofId,
1202
+ configuration.locking,
1203
+ );
1204
+
1205
+ const row = rows[0];
1206
+ const now = yield* nowMillis;
1207
+
1208
+ if (row === undefined) return prepare({ _tag: "Declined" }, journal);
1209
+ const c = generationColumns(mapping);
1210
+ const expiresAt = yield* mapping.decodeInstant(row[mapping.generation.expiresAt]);
1211
+
1212
+ const claimDeadline =
1213
+ row[mapping.generation.claimDeadline] === null ||
1214
+ row[mapping.generation.claimDeadline] === undefined
1215
+ ? undefined
1216
+ : yield* mapping.decodeInstant(row[mapping.generation.claimDeadline]);
1217
+
1218
+ const retryAt =
1219
+ row[mapping.generation.retryAt] === null ||
1220
+ row[mapping.generation.retryAt] === undefined
1221
+ ? undefined
1222
+ : yield* mapping.decodeInstant(row[mapping.generation.retryAt]);
1223
+
1224
+ let state = row[mapping.generation.deliveryState] as string;
1225
+
1226
+ if (state === "claimed" && claimDeadline !== undefined && claimDeadline <= now) {
1227
+ state = "ambiguous";
1228
+ yield* transaction
1229
+ .update(mapping.generation.table)
1230
+ .set(updateValues<any>([[mapping.generation.deliveryState, "ambiguous"]]))
1231
+ .where(and(eq(c.moduleId, input.moduleId), eq(c.proofId, input.proofId)));
1232
+ }
1233
+
1234
+ const canClaim =
1235
+ row[mapping.generation.version] === input.version &&
1236
+ row[mapping.generation.deliveryId] === input.deliveryId &&
1237
+ row[mapping.generation.state] === "active" &&
1238
+ expiresAt > now &&
1239
+ Number(row[mapping.generation.sendCount]) < input.policy.maximumDeliveryAttempts &&
1240
+ (state === "new" ||
1241
+ (state === "ambiguous" &&
1242
+ input.allowAmbiguousRetry &&
1243
+ (retryAt === undefined || retryAt <= now)));
1244
+
1245
+ if (!canClaim) return prepare({ _tag: "Declined" }, journal);
1246
+ const claimVersion = yield* allocateVersion(mapping, configuration.mode);
1247
+ const decision: ProofDeliveryClaim = { _tag: "Claimed", claimVersion };
1248
+ const prepared = prepare(decision, journal);
1249
+
1250
+ yield* transaction
1251
+ .update(mapping.generation.table)
1252
+ .set(
1253
+ updateValues<any>([
1254
+ [mapping.generation.sendCount, Number(row[mapping.generation.sendCount]) + 1],
1255
+ [mapping.generation.deliveryState, "claimed"],
1256
+ [mapping.generation.claimVersion, claimVersion],
1257
+ [
1258
+ mapping.generation.claimDeadline,
1259
+ mapping.encodeInstant(now + input.policy.deliveryClaimMillis),
1260
+ ],
1261
+ [
1262
+ mapping.generation.retryAt,
1263
+ mapping.encodeInstant(now + input.policy.deliveryRetryMillis),
1264
+ ],
1265
+ ]),
1266
+ )
1267
+ .where(and(eq(c.moduleId, input.moduleId), eq(c.proofId, input.proofId)));
1268
+
1269
+ return prepared;
1270
+ }),
1271
+ ).pipe(
1272
+ Effect.provideService(CurrentProofSql, database),
1273
+ Effect.provideService(LifecycleHooks, hooks),
1274
+ translateFailure,
1275
+ ),
1276
+ settleDelivery: (input, prepare) =>
1277
+ owned(
1278
+ database,
1279
+ mapping,
1280
+ configuration,
1281
+ Effect.gen(function* () {
1282
+ const transaction = yield* CurrentProofSql;
1283
+ const journal = yield* CurrentCommitJournal;
1284
+
1285
+ const initial = (yield* readGeneration(
1286
+ mapping,
1287
+ input.moduleId,
1288
+ input.proofId,
1289
+ false,
1290
+ ))[0];
1291
+
1292
+ if (initial === undefined) return prepare(undefined, journal);
1293
+ const keys = initial[mapping.generation.seriesKey] as string;
1294
+
1295
+ yield* ensureSeries(
1296
+ mapping,
1297
+ configuration,
1298
+ input.moduleId,
1299
+ initial[mapping.generation.purpose],
1300
+ keys,
1301
+ );
1302
+
1303
+ const row = (yield* readGeneration(
1304
+ mapping,
1305
+ input.moduleId,
1306
+ input.proofId,
1307
+ configuration.locking,
1308
+ ))[0];
1309
+
1310
+ const prepared = prepare(undefined, journal);
1311
+
1312
+ if (
1313
+ row === undefined ||
1314
+ row[mapping.generation.version] !== input.version ||
1315
+ row[mapping.generation.deliveryId] !== input.deliveryId ||
1316
+ row[mapping.generation.claimVersion] !== input.claimVersion ||
1317
+ row[mapping.generation.deliveryState] !== "claimed"
1318
+ )
1319
+ return prepared;
1320
+ const c = generationColumns(mapping);
1321
+ const outcome: ProofDeliveryOutcome = input.outcome;
1322
+
1323
+ const state =
1324
+ outcome._tag === "Accepted"
1325
+ ? "accepted"
1326
+ : outcome._tag === "DefiniteFailure"
1327
+ ? "failed"
1328
+ : "ambiguous";
1329
+
1330
+ const values: Array<readonly [string, unknown]> = [
1331
+ [mapping.generation.deliveryState, state],
1332
+ [mapping.generation.claimDeadline, null],
1333
+ ];
1334
+
1335
+ if (outcome._tag === "Ambiguous")
1336
+ values.push([
1337
+ mapping.generation.retryAt,
1338
+ mapping.encodeInstant(
1339
+ (yield* nowMillis) + Number(row[mapping.generation.deliveryRetryMillis]),
1340
+ ),
1341
+ ]);
1342
+ if (outcome._tag === "DefiniteFailure")
1343
+ values.push([mapping.generation.state, "cancelled"]);
1344
+ yield* transaction
1345
+ .update(mapping.generation.table)
1346
+ .set(updateValues<any>(values))
1347
+ .where(and(eq(c.moduleId, input.moduleId), eq(c.proofId, input.proofId)));
1348
+ if (outcome._tag === "DefiniteFailure") {
1349
+ const sc = seriesColumns(mapping);
1350
+
1351
+ yield* transaction
1352
+ .update(mapping.series.table)
1353
+ .set(updateValues<any>([[mapping.series.activeProofId, null]]))
1354
+ .where(
1355
+ and(
1356
+ eq(sc.moduleId, input.moduleId),
1357
+ eq(sc.purpose, row[mapping.generation.purpose]),
1358
+ eq(sc.scopeKey, keys),
1359
+ eq(sc.activeProofId, input.proofId),
1360
+ ),
1361
+ );
1362
+ }
1363
+
1364
+ return prepared;
1365
+ }),
1366
+ ).pipe(
1367
+ Effect.provideService(CurrentProofSql, database),
1368
+ Effect.provideService(LifecycleHooks, hooks),
1369
+ translateFailure,
1370
+ ),
1371
+ cancel: (input, prepare) =>
1372
+ owned(
1373
+ database,
1374
+ mapping,
1375
+ configuration,
1376
+ Effect.gen(function* () {
1377
+ const transaction = yield* CurrentProofSql;
1378
+ const journal = yield* CurrentCommitJournal;
1379
+
1380
+ const authorityCurrent = yield* lockAuthority(
1381
+ mapping,
1382
+ input.moduleId,
1383
+ input.purpose,
1384
+ input.binding,
1385
+ configuration.locking,
1386
+ );
1387
+
1388
+ const keys = mapping.scopeKeys({
1389
+ moduleId: input.moduleId,
1390
+ purpose: input.purpose,
1391
+ binding: input.binding,
1392
+ });
1393
+
1394
+ const series = yield* ensureSeries(
1395
+ mapping,
1396
+ configuration,
1397
+ input.moduleId,
1398
+ input.purpose,
1399
+ keys.series,
1400
+ );
1401
+
1402
+ const active = series[mapping.series.activeProofId] as string | undefined | null;
1403
+ const prepared = prepare(undefined, journal);
1404
+
1405
+ if (authorityCurrent && active !== undefined && active !== null) {
1406
+ const gc = generationColumns(mapping);
1407
+ const sc = seriesColumns(mapping);
1408
+
1409
+ const row = (yield* readGeneration(
1410
+ mapping,
1411
+ input.moduleId,
1412
+ active,
1413
+ configuration.locking,
1414
+ ))[0];
1415
+
1416
+ const storedBinding =
1417
+ row === undefined ? undefined : yield* mapping.generation.decodeBinding(row);
1418
+
1419
+ if (storedBinding === undefined || !sameBinding(storedBinding, input.binding))
1420
+ return prepared;
1421
+
1422
+ yield* transaction
1423
+ .update(mapping.generation.table)
1424
+ .set(updateValues<any>([[mapping.generation.state, "cancelled"]]))
1425
+ .where(and(eq(gc.moduleId, input.moduleId), eq(gc.proofId, active)));
1426
+ yield* transaction
1427
+ .update(mapping.series.table)
1428
+ .set(updateValues<any>([[mapping.series.activeProofId, null]]))
1429
+ .where(
1430
+ and(
1431
+ eq(sc.moduleId, input.moduleId),
1432
+ eq(sc.purpose, input.purpose),
1433
+ eq(sc.scopeKey, keys.series),
1434
+ eq(sc.activeProofId, active),
1435
+ ),
1436
+ );
1437
+ }
1438
+
1439
+ return prepared;
1440
+ }),
1441
+ ).pipe(
1442
+ Effect.provideService(CurrentProofSql, database),
1443
+ Effect.provideService(LifecycleHooks, hooks),
1444
+ translateFailure,
1445
+ ),
1446
+ cleanup: (input, prepare) =>
1447
+ owned(
1448
+ database,
1449
+ mapping,
1450
+ configuration,
1451
+ Effect.gen(function* () {
1452
+ const transaction = yield* CurrentProofSql;
1453
+ const journal = yield* CurrentCommitJournal;
1454
+
1455
+ const now = yield* nowMillis;
1456
+ const nativeNow = mapping.encodeInstant(now);
1457
+ const gc = generationColumns(mapping);
1458
+ const cc = continuationColumns(mapping);
1459
+ const rc = requestColumns(mapping);
1460
+ const ac = abuseColumns(mapping);
1461
+ const fc = failureColumns(mapping);
1462
+ const mc = commandColumns(mapping);
1463
+ const sc = seriesColumns(mapping);
1464
+ const rsc = scopeColumns(mapping);
1465
+ let remaining = input.limit;
1466
+ let hasMore = false;
1467
+
1468
+ const take = <A>(query: ProofSqlQuery<ReadonlyArray<A>>) =>
1469
+ selectRows(query.limit(remaining + 1), configuration.locking).pipe(
1470
+ Effect.map((rows) => {
1471
+ if (rows.length > remaining) hasMore = true;
1472
+ const selected = rows.slice(0, remaining);
1473
+
1474
+ remaining -= selected.length;
1475
+
1476
+ return selected;
1477
+ }),
1478
+ );
1479
+
1480
+ // Child rows and secret-bearing generations are removed before their
1481
+ // retained request/decision records. Every selected row counts toward
1482
+ // one caller-wide limit and is locked until this owner commits.
1483
+ const continuations = yield* take(
1484
+ transaction
1485
+ .select({ continuationId: cc.continuationId })
1486
+ .from(mapping.continuation.table)
1487
+ .where(and(eq(cc.moduleId, input.moduleId), lte(cc.retentionUntil, nativeNow)))
1488
+ .orderBy(cc.retentionUntil),
1489
+ );
1490
+
1491
+ const generations = yield* take(
1492
+ transaction
1493
+ .select({ proofId: gc.proofId })
1494
+ .from(mapping.generation.table)
1495
+ .where(and(eq(gc.moduleId, input.moduleId), lte(gc.retentionUntil, nativeNow)))
1496
+ .orderBy(gc.retentionUntil),
1497
+ );
1498
+
1499
+ const requests = yield* take(
1500
+ transaction
1501
+ .select({ requestId: rc.requestId })
1502
+ .from(mapping.request.table)
1503
+ .where(and(eq(rc.moduleId, input.moduleId), lte(rc.retentionUntil, nativeNow)))
1504
+ .orderBy(rc.retentionUntil),
1505
+ );
1506
+
1507
+ const abuse = yield* take(
1508
+ transaction
1509
+ .select({
1510
+ action: ac.action,
1511
+ scopeKind: ac.scopeKind,
1512
+ scopeKey: ac.scopeKey,
1513
+ commandId: ac.commandId,
1514
+ })
1515
+ .from(mapping.abuseEvent.table)
1516
+ .where(and(eq(ac.moduleId, input.moduleId), lte(ac.retentionUntil, nativeNow)))
1517
+ .orderBy(ac.retentionUntil),
1518
+ );
1519
+
1520
+ const failures = yield* take(
1521
+ transaction
1522
+ .select({ seriesKey: fc.seriesKey, commandId: fc.commandId })
1523
+ .from(mapping.failureEvent.table)
1524
+ .where(and(eq(fc.moduleId, input.moduleId), lte(fc.retentionUntil, nativeNow)))
1525
+ .orderBy(fc.retentionUntil),
1526
+ );
1527
+
1528
+ const commands = yield* take(
1529
+ transaction
1530
+ .select({ commandId: mc.commandId })
1531
+ .from(mapping.command.table)
1532
+ .where(and(eq(mc.moduleId, input.moduleId), lte(mc.retentionUntil, nativeNow)))
1533
+ .orderBy(mc.retentionUntil),
1534
+ );
1535
+
1536
+ const series = yield* take(
1537
+ transaction
1538
+ .select({ purpose: sc.purpose, scopeKey: sc.scopeKey })
1539
+ .from(mapping.series.table)
1540
+ .where(
1541
+ and(
1542
+ eq(sc.moduleId, input.moduleId),
1543
+ isNull(sc.activeProofId),
1544
+ notExists(
1545
+ transaction
1546
+ .select({ one: sql`1` })
1547
+ .from(mapping.generation.table)
1548
+ .where(
1549
+ and(
1550
+ eq(gc.moduleId, sc.moduleId),
1551
+ eq(gc.purpose, sc.purpose),
1552
+ eq(gc.seriesKey, sc.scopeKey),
1553
+ ),
1554
+ ),
1555
+ ),
1556
+ notExists(
1557
+ transaction
1558
+ .select({ one: sql`1` })
1559
+ .from(mapping.failureEvent.table)
1560
+ .where(
1561
+ and(
1562
+ eq(fc.moduleId, sc.moduleId),
1563
+ eq(fc.purpose, sc.purpose),
1564
+ eq(fc.seriesKey, sc.scopeKey),
1565
+ ),
1566
+ ),
1567
+ ),
1568
+ ),
1569
+ ),
1570
+ );
1571
+
1572
+ const rateScopes = yield* take(
1573
+ transaction
1574
+ .select({
1575
+ purpose: rsc.purpose,
1576
+ action: rsc.action,
1577
+ scopeKind: rsc.scopeKind,
1578
+ scopeKey: rsc.scopeKey,
1579
+ })
1580
+ .from(mapping.rateScope.table)
1581
+ .where(
1582
+ and(
1583
+ eq(rsc.moduleId, input.moduleId),
1584
+ notExists(
1585
+ transaction
1586
+ .select({ one: sql`1` })
1587
+ .from(mapping.abuseEvent.table)
1588
+ .where(
1589
+ and(
1590
+ eq(ac.moduleId, rsc.moduleId),
1591
+ eq(ac.purpose, rsc.purpose),
1592
+ eq(ac.action, rsc.action),
1593
+ eq(ac.scopeKind, rsc.scopeKind),
1594
+ eq(ac.scopeKey, rsc.scopeKey),
1595
+ ),
1596
+ ),
1597
+ ),
1598
+ ),
1599
+ ),
1600
+ );
1601
+
1602
+ // Removing the final history row can make an anchor eligible only after this
1603
+ // transaction/batch commits. One extra page lets the caller reclaim it.
1604
+ hasMore ||= generations.length > 0 || failures.length > 0 || abuse.length > 0;
1605
+ const removed = input.limit - remaining;
1606
+ const prepared = prepare({ removed, hasMore } satisfies ProofCleanupResult, journal);
1607
+
1608
+ if (continuations.length > 0)
1609
+ yield* transaction.delete(mapping.continuation.table).where(
1610
+ and(
1611
+ eq(cc.moduleId, input.moduleId),
1612
+ inArray(
1613
+ cc.continuationId,
1614
+ continuations.map((row: any) => row.continuationId),
1615
+ ),
1616
+ lte(cc.retentionUntil, nativeNow),
1617
+ ),
1618
+ );
1619
+ if (generations.length > 0)
1620
+ yield* transaction
1621
+ .update(mapping.series.table)
1622
+ .set(updateValues<any>([[mapping.series.activeProofId, null]]))
1623
+ .where(
1624
+ and(
1625
+ eq(sc.moduleId, input.moduleId),
1626
+ inArray(
1627
+ sc.activeProofId,
1628
+ generations.map((row: any) => row.proofId),
1629
+ ),
1630
+ ),
1631
+ );
1632
+ if (generations.length > 0)
1633
+ yield* transaction.delete(mapping.generation.table).where(
1634
+ and(
1635
+ eq(gc.moduleId, input.moduleId),
1636
+ inArray(
1637
+ gc.proofId,
1638
+ generations.map((row: any) => row.proofId),
1639
+ ),
1640
+ lte(gc.retentionUntil, nativeNow),
1641
+ ),
1642
+ );
1643
+ if (requests.length > 0)
1644
+ yield* transaction.delete(mapping.request.table).where(
1645
+ and(
1646
+ eq(rc.moduleId, input.moduleId),
1647
+ inArray(
1648
+ rc.requestId,
1649
+ requests.map((row: any) => row.requestId),
1650
+ ),
1651
+ lte(rc.retentionUntil, nativeNow),
1652
+ ),
1653
+ );
1654
+ for (const row of abuse)
1655
+ yield* transaction
1656
+ .delete(mapping.abuseEvent.table)
1657
+ .where(
1658
+ and(
1659
+ eq(ac.moduleId, input.moduleId),
1660
+ eq(ac.action, row.action),
1661
+ eq(ac.scopeKind, row.scopeKind),
1662
+ eq(ac.scopeKey, row.scopeKey),
1663
+ eq(ac.commandId, row.commandId),
1664
+ lte(ac.retentionUntil, nativeNow),
1665
+ ),
1666
+ );
1667
+ for (const row of failures)
1668
+ yield* transaction
1669
+ .delete(mapping.failureEvent.table)
1670
+ .where(
1671
+ and(
1672
+ eq(fc.moduleId, input.moduleId),
1673
+ eq(fc.seriesKey, row.seriesKey),
1674
+ eq(fc.commandId, row.commandId),
1675
+ lte(fc.retentionUntil, nativeNow),
1676
+ ),
1677
+ );
1678
+ if (commands.length > 0)
1679
+ yield* transaction.delete(mapping.command.table).where(
1680
+ and(
1681
+ eq(mc.moduleId, input.moduleId),
1682
+ inArray(
1683
+ mc.commandId,
1684
+ commands.map((row: any) => row.commandId),
1685
+ ),
1686
+ lte(mc.retentionUntil, nativeNow),
1687
+ ),
1688
+ );
1689
+ for (const row of series)
1690
+ yield* transaction.delete(mapping.series.table).where(
1691
+ and(
1692
+ eq(sc.moduleId, input.moduleId),
1693
+ eq(sc.purpose, row.purpose),
1694
+ eq(sc.scopeKey, row.scopeKey),
1695
+ isNull(sc.activeProofId),
1696
+ notExists(
1697
+ transaction
1698
+ .select({ one: sql`1` })
1699
+ .from(mapping.generation.table)
1700
+ .where(
1701
+ and(
1702
+ eq(gc.moduleId, sc.moduleId),
1703
+ eq(gc.purpose, sc.purpose),
1704
+ eq(gc.seriesKey, sc.scopeKey),
1705
+ ),
1706
+ ),
1707
+ ),
1708
+ ),
1709
+ );
1710
+ for (const row of rateScopes)
1711
+ yield* transaction.delete(mapping.rateScope.table).where(
1712
+ and(
1713
+ eq(rsc.moduleId, input.moduleId),
1714
+ eq(rsc.purpose, row.purpose),
1715
+ eq(rsc.action, row.action),
1716
+ eq(rsc.scopeKind, row.scopeKind),
1717
+ eq(rsc.scopeKey, row.scopeKey),
1718
+ notExists(
1719
+ transaction
1720
+ .select({ one: sql`1` })
1721
+ .from(mapping.abuseEvent.table)
1722
+ .where(
1723
+ and(
1724
+ eq(ac.moduleId, rsc.moduleId),
1725
+ eq(ac.purpose, rsc.purpose),
1726
+ eq(ac.action, rsc.action),
1727
+ eq(ac.scopeKind, rsc.scopeKind),
1728
+ eq(ac.scopeKey, rsc.scopeKey),
1729
+ ),
1730
+ ),
1731
+ ),
1732
+ ),
1733
+ );
1734
+
1735
+ return prepared;
1736
+ }),
1737
+ ).pipe(
1738
+ Effect.provideService(CurrentProofSql, database),
1739
+ Effect.provideService(LifecycleHooks, hooks),
1740
+ translateFailure,
1741
+ ),
1742
+ });
1743
+ });
1744
+
1745
+ const inspectCompletionIn = Effect.fn("DrizzleProof.inspectCompletionIn")(function* (
1746
+ mapping: Mapping,
1747
+ configuration: ProofSqlConfiguration,
1748
+ input: ProofCompletionPlan["input"],
1749
+ ensure: boolean,
1750
+ ) {
1751
+ const database = yield* CurrentProofSql;
1752
+
1753
+ const authorityCurrent = yield* lockAuthority(
1754
+ mapping,
1755
+ input.moduleId,
1756
+ input.purpose,
1757
+ input.binding,
1758
+ configuration.locking,
1759
+ );
1760
+
1761
+ const keys = mapping.scopeKeys({
1762
+ moduleId: input.moduleId,
1763
+ purpose: input.purpose,
1764
+ binding: input.binding,
1765
+ });
1766
+
1767
+ if (ensure)
1768
+ yield* ensureSeries(mapping, configuration, input.moduleId, input.purpose, keys.series);
1769
+ const c = continuationColumns(mapping);
1770
+
1771
+ const rows = yield* selectRows(
1772
+ database
1773
+ .select()
1774
+ .from(mapping.continuation.table)
1775
+ .where(and(eq(c.moduleId, input.moduleId), eq(c.continuationId, input.continuationId)))
1776
+ .limit(1),
1777
+ configuration.locking,
1778
+ );
1779
+
1780
+ const row = rows[0];
1781
+ const now = yield* nowMillis;
1782
+ const record = row === undefined ? undefined : yield* mapping.continuation.decode(row);
1783
+
1784
+ const completed =
1785
+ authorityCurrent &&
1786
+ row !== undefined &&
1787
+ record !== undefined &&
1788
+ record.moduleId === input.moduleId &&
1789
+ record.continuationId === input.continuationId &&
1790
+ record.purpose === input.purpose &&
1791
+ record.digest === input.continuationDigest &&
1792
+ record.seriesKey === keys.series &&
1793
+ sameBinding(record.binding, input.binding) &&
1794
+ row[mapping.continuation.consumed] === false &&
1795
+ record.expiresAtMillis > now;
1796
+
1797
+ return completed ? { record: record!, row, columns: c } : undefined;
1798
+ });
1799
+
1800
+ /** Nonconsuming same-owner preflight; it never inserts a series or changes expiry. */
1801
+ const checkProofCompletionIn = Effect.fn("Drizzle.checkProofCompletionIn")(function* (
1802
+ mapping: Mapping,
1803
+ configuration: ProofSqlConfiguration,
1804
+ input: ProofCompletionPlan["input"],
1805
+ ) {
1806
+ return yield* inspectCompletionIn(mapping, configuration, input, false).pipe(
1807
+ Effect.map((value) => value !== undefined),
1808
+ );
1809
+ });
1810
+
1811
+ const completeIn = Effect.fn("DrizzleProof.completeIn")(function* <A, E = never, R = never>(
1812
+ mapping: Mapping,
1813
+ configuration: ProofSqlConfiguration,
1814
+ input: ProofCompletionPlan["input"],
1815
+ prepare: (decision: ProofCompletionDecision) => A,
1816
+ protectedMutation?: Effect.Effect<boolean, E, R>,
1817
+ ) {
1818
+ const database = yield* CurrentProofSql;
1819
+
1820
+ const accepted = yield* inspectCompletionIn(mapping, configuration, input, true);
1821
+
1822
+ if (accepted === undefined) return prepare("rejected");
1823
+ const { record, row: original, columns: c } = accepted;
1824
+
1825
+ if (protectedMutation !== undefined && !(yield* protectedMutation)) return yield* unavailable();
1826
+ const value = prepare("completed");
1827
+
1828
+ yield* database
1829
+ .update(mapping.continuation.table)
1830
+ .set(updateValues<any>([[mapping.continuation.consumed, true]]))
1831
+ .where(
1832
+ and(
1833
+ eq(c.moduleId, input.moduleId),
1834
+ eq(c.continuationId, input.continuationId),
1835
+ eq(c.digest, input.continuationDigest),
1836
+ eq(c.consumed, false),
1837
+ ),
1838
+ );
1839
+ yield* insertCommand(
1840
+ mapping,
1841
+ input.moduleId,
1842
+ input.continuationDigest,
1843
+ "complete",
1844
+ "completed",
1845
+ record.expiresAtMillis,
1846
+ );
1847
+
1848
+ const assertApplied = Effect.flatMap(CurrentPasswordPreparedTransaction, (currentTransaction) =>
1849
+ Effect.gen(function* () {
1850
+ const persisted = (yield* selectRows(
1851
+ currentTransaction
1852
+ .select()
1853
+ .from(mapping.continuation.table)
1854
+ .where(and(eq(c.moduleId, input.moduleId), eq(c.continuationId, input.continuationId)))
1855
+ .limit(1),
1856
+ false,
1857
+ ))[0];
1858
+
1859
+ const command = (yield* commandRow(
1860
+ mapping,
1861
+ input.moduleId,
1862
+ input.continuationDigest,
1863
+ false,
1864
+ ))[0];
1865
+
1866
+ const decoded =
1867
+ persisted === undefined ? undefined : yield* mapping.continuation.decode(persisted);
1868
+
1869
+ const immutable = [
1870
+ mapping.continuation.moduleId,
1871
+ mapping.continuation.purpose,
1872
+ mapping.continuation.continuationId,
1873
+ mapping.continuation.digest,
1874
+ mapping.continuation.proofId,
1875
+ mapping.continuation.seriesKey,
1876
+ mapping.continuation.version,
1877
+ ];
1878
+
1879
+ if (
1880
+ persisted === undefined ||
1881
+ decoded === undefined ||
1882
+ !sameBinding(decoded.binding, record.binding) ||
1883
+ persisted[mapping.continuation.consumed] !== true ||
1884
+ immutable.some((key) => persisted[key] !== original[key]) ||
1885
+ (yield* mapping.decodeInstant(persisted[mapping.continuation.expiresAt])) !==
1886
+ record.expiresAtMillis ||
1887
+ (yield* mapping.decodeInstant(persisted[mapping.continuation.retentionUntil])) !==
1888
+ (yield* mapping.decodeInstant(original[mapping.continuation.retentionUntil])) ||
1889
+ command === undefined ||
1890
+ command[mapping.command.kind] !== "complete" ||
1891
+ command[mapping.command.decision] !== "completed" ||
1892
+ (yield* mapping.decodeInstant(command[mapping.command.retentionUntil])) !==
1893
+ record.expiresAtMillis
1894
+ )
1895
+ return yield* unavailable();
1896
+
1897
+ if (record.expiresAtMillis <= (yield* nowMillis)) return yield* unavailable();
1898
+ }).pipe(Effect.provideService(CurrentProofSql, currentTransaction)),
1899
+ );
1900
+
1901
+ yield* assertApplied.pipe(Effect.provideService(CurrentPasswordPreparedTransaction, database));
1902
+ const postconditions = yield* Effect.serviceOption(PasswordPreparedPostconditions);
1903
+
1904
+ if (
1905
+ Option.isSome(postconditions) &&
1906
+ !postconditions.value.register(assertApplied.pipe(translateFailure))
1907
+ )
1908
+ return yield* unavailable();
1909
+
1910
+ return value;
1911
+ });
1912
+
1913
+ /** Private same-owner seam for password and identifier mutations. */
1914
+ const completeProofPlanIn = Effect.fn("Drizzle.completeProofPlanIn")(function* <
1915
+ Rq extends Table,
1916
+ S extends Table,
1917
+ G extends Table,
1918
+ Cn extends Table,
1919
+ Rs extends Table,
1920
+ Aev extends Table,
1921
+ F extends Table,
1922
+ C extends Table,
1923
+ Sub extends Table,
1924
+ I extends Table,
1925
+ Cr extends Table,
1926
+ NativeId,
1927
+ A,
1928
+ E,
1929
+ R,
1930
+ >(
1931
+ mapping: ProofPersistenceMapping<Rq, S, G, Cn, Rs, Aev, F, C, Sub, I, Cr, NativeId>,
1932
+ configuration: ProofSqlConfiguration,
1933
+ plan: ProofCompletionPlan,
1934
+ protectedMutation: Effect.Effect<boolean, E, R>,
1935
+ project: (decision: ProofCompletionDecision) => A,
1936
+ ) {
1937
+ const journal = yield* CurrentCommitJournal;
1938
+
1939
+ return yield* completeIn(
1940
+ mapping as unknown as Mapping,
1941
+ configuration,
1942
+ plan.input,
1943
+ (decision) => plan.prepare(decision, journal, project),
1944
+ protectedMutation,
1945
+ );
1946
+ });
1947
+
1948
+ return { makeSqlProofPersistence, checkProofCompletionIn, completeProofPlanIn };
1949
+ };