@yielded/auth-persistence-drizzle 0.1.0-beta.24 → 0.1.0-beta.26

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 (383) hide show
  1. package/README.md +4 -2
  2. package/dist/D1.d.mts +495 -1151
  3. package/dist/D1.mjs +41 -19
  4. package/dist/D1.mjs.map +1 -1
  5. package/dist/Libsql.d.mts +385 -1996
  6. package/dist/Libsql.mjs +43 -47
  7. package/dist/Libsql.mjs.map +1 -1
  8. package/dist/Mysql2.d.mts +397 -1743
  9. package/dist/Mysql2.mjs +35 -41
  10. package/dist/Mysql2.mjs.map +1 -1
  11. package/dist/Pglite.d.mts +397 -1743
  12. package/dist/Pglite.mjs +42 -31
  13. package/dist/Pglite.mjs.map +1 -1
  14. package/dist/Postgres.d.mts +397 -1743
  15. package/dist/Postgres.mjs +42 -31
  16. package/dist/Postgres.mjs.map +1 -1
  17. package/dist/SqliteBun.d.mts +385 -1992
  18. package/dist/SqliteBun.mjs +43 -43
  19. package/dist/SqliteBun.mjs.map +1 -1
  20. package/dist/SqliteDo.d.mts +385 -1991
  21. package/dist/SqliteDo.mjs +42 -41
  22. package/dist/SqliteDo.mjs.map +1 -1
  23. package/dist/SqliteNode.d.mts +385 -1992
  24. package/dist/SqliteNode.mjs +43 -43
  25. package/dist/SqliteNode.mjs.map +1 -1
  26. package/dist/SqliteWasm.d.mts +385 -1992
  27. package/dist/SqliteWasm.mjs +43 -43
  28. package/dist/SqliteWasm.mjs.map +1 -1
  29. package/dist/drizzle/d1-identity.mjs +2 -2
  30. package/dist/drizzle/d1-identity.mjs.map +1 -1
  31. package/dist/drizzle/driver-types.d.mts +15 -0
  32. package/dist/drizzle/email-drivers.mjs +32 -0
  33. package/dist/drizzle/email-drivers.mjs.map +1 -0
  34. package/dist/drizzle/email-model.d.mts +9 -13
  35. package/dist/drizzle/email-target.d.mts +10 -11
  36. package/dist/drizzle/email-target.mjs +33 -70
  37. package/dist/drizzle/email-target.mjs.map +1 -1
  38. package/dist/drizzle/model.d.mts +1 -10
  39. package/dist/drizzle/model.mjs +1 -2
  40. package/dist/drizzle/model.mjs.map +1 -1
  41. package/dist/drizzle/mysql-identity.mjs +3 -6
  42. package/dist/drizzle/mysql-identity.mjs.map +1 -1
  43. package/dist/drizzle/native-clock.d.mts +9 -0
  44. package/dist/drizzle/native-clock.mjs +18 -0
  45. package/dist/drizzle/native-clock.mjs.map +1 -0
  46. package/dist/drizzle/native-database.d.mts +46 -0
  47. package/dist/drizzle/native-database.mjs +6 -5
  48. package/dist/drizzle/native-database.mjs.map +1 -1
  49. package/dist/drizzle/native-sql-table.mjs +13 -5
  50. package/dist/drizzle/native-sql-table.mjs.map +1 -1
  51. package/dist/drizzle/native-target.d.mts +6 -0
  52. package/dist/drizzle/native-target.mjs +44 -0
  53. package/dist/drizzle/native-target.mjs.map +1 -0
  54. package/dist/drizzle/oauth-connected-drivers.mjs +4 -56
  55. package/dist/drizzle/oauth-connected-drivers.mjs.map +1 -1
  56. package/dist/drizzle/oauth-connected-model.d.mts +5 -22
  57. package/dist/drizzle/oauth-connected-model.mjs +1 -7
  58. package/dist/drizzle/oauth-connected-reference.d.mts +5 -7
  59. package/dist/drizzle/oauth-connected-reference.mjs +11 -3
  60. package/dist/drizzle/oauth-connected-reference.mjs.map +1 -1
  61. package/dist/drizzle/oauth-drivers.mjs +1 -2
  62. package/dist/drizzle/oauth-drivers.mjs.map +1 -1
  63. package/dist/drizzle/oauth-model.d.mts +11 -37
  64. package/dist/drizzle/oauth-model.mjs +3 -4
  65. package/dist/drizzle/oauth-model.mjs.map +1 -1
  66. package/dist/drizzle/oauth-proxy.d.mts +1 -1
  67. package/dist/drizzle/oauth-proxy.mjs +1 -1
  68. package/dist/drizzle/oauth-target.d.mts +9 -6
  69. package/dist/drizzle/oauth-target.mjs +47 -15
  70. package/dist/drizzle/oauth-target.mjs.map +1 -1
  71. package/dist/drizzle/passkey/target.d.mts +14 -0
  72. package/dist/drizzle/passkey/target.mjs +52 -0
  73. package/dist/drizzle/passkey/target.mjs.map +1 -0
  74. package/dist/drizzle/passkey/write-target.d.mts +11 -0
  75. package/dist/drizzle/passkey/write-target.mjs +28 -0
  76. package/dist/drizzle/passkey/write-target.mjs.map +1 -0
  77. package/dist/drizzle/passkey-drivers.mjs +2 -4
  78. package/dist/drizzle/passkey-drivers.mjs.map +1 -1
  79. package/dist/drizzle/passkey-model.d.mts +5 -26
  80. package/dist/drizzle/passkey-model.mjs +2 -8
  81. package/dist/drizzle/passkey-registration-ceremony-model.d.mts +3 -6
  82. package/dist/drizzle/passkey-write-drivers.mjs +2 -3
  83. package/dist/drizzle/passkey-write-drivers.mjs.map +1 -1
  84. package/dist/drizzle/passkey-write-model.d.mts +7 -9
  85. package/dist/drizzle/passkey-write-model.mjs +1 -3
  86. package/dist/drizzle/passkey-write-model.mjs.map +1 -1
  87. package/dist/drizzle/password-drivers.mjs +31 -0
  88. package/dist/drizzle/password-drivers.mjs.map +1 -0
  89. package/dist/drizzle/password-model.d.mts +7 -10
  90. package/dist/drizzle/password-target.d.mts +7 -8
  91. package/dist/drizzle/password-target.mjs +23 -68
  92. package/dist/drizzle/password-target.mjs.map +1 -1
  93. package/dist/drizzle/pg-identity.mjs +3 -6
  94. package/dist/drizzle/pg-identity.mjs.map +1 -1
  95. package/dist/drizzle/phone-drivers.mjs +24 -0
  96. package/dist/drizzle/phone-drivers.mjs.map +1 -0
  97. package/dist/drizzle/phone-model.d.mts +13 -104
  98. package/dist/drizzle/phone-model.mjs +5 -33
  99. package/dist/drizzle/phone-model.mjs.map +1 -1
  100. package/dist/drizzle/phone-target.mjs +22 -171
  101. package/dist/drizzle/phone-target.mjs.map +1 -1
  102. package/dist/drizzle/proof-drivers.mjs +24 -0
  103. package/dist/drizzle/proof-drivers.mjs.map +1 -0
  104. package/dist/drizzle/proof-model.d.mts +7 -15
  105. package/dist/drizzle/proof-target.d.mts +5 -5
  106. package/dist/drizzle/proof-target.mjs +14 -28
  107. package/dist/drizzle/proof-target.mjs.map +1 -1
  108. package/dist/drizzle/session-drivers.mjs +97 -0
  109. package/dist/drizzle/session-drivers.mjs.map +1 -0
  110. package/dist/drizzle/session-model.d.mts +11 -22
  111. package/dist/drizzle/sqlite-do-database.d.mts +3 -3
  112. package/dist/drizzle/sqlite-do-database.mjs +6 -1
  113. package/dist/drizzle/sqlite-do-database.mjs.map +1 -1
  114. package/dist/drizzle/sqlite-identity.mjs +3 -5
  115. package/dist/drizzle/sqlite-identity.mjs.map +1 -1
  116. package/dist/drizzle/step-up-model.d.mts +2 -5
  117. package/dist/drizzle/storage-validation.mjs +2 -1
  118. package/dist/drizzle/storage-validation.mjs.map +1 -1
  119. package/dist/drizzle/totp-model.d.mts +7 -74
  120. package/dist/drizzle/totp-model.mjs +1 -5
  121. package/dist/drizzle/totp-model.mjs.map +1 -1
  122. package/dist/drizzle/totp-target.mjs +39 -75
  123. package/dist/drizzle/totp-target.mjs.map +1 -1
  124. package/dist/drizzle/transaction-handle.mjs +13 -0
  125. package/dist/drizzle/transaction-handle.mjs.map +1 -0
  126. package/dist/drizzle/transaction-mysql.mjs +43 -12
  127. package/dist/drizzle/transaction-mysql.mjs.map +1 -1
  128. package/dist/index.d.mts +17 -22
  129. package/dist/index.mjs +10 -16
  130. package/dist/internal/drizzle-postgres.mjs +4 -6
  131. package/dist/internal/drizzle-postgres.mjs.map +1 -1
  132. package/dist/internal/drizzle-sqlite.mjs +4 -6
  133. package/dist/internal/drizzle-sqlite.mjs.map +1 -1
  134. package/package.json +1 -1
  135. package/src/D1.ts +77 -74
  136. package/src/Libsql.ts +65 -105
  137. package/src/Mysql2.ts +52 -87
  138. package/src/Pglite.ts +74 -81
  139. package/src/Postgres.ts +74 -81
  140. package/src/SqliteBun.ts +65 -113
  141. package/src/SqliteDo.ts +58 -106
  142. package/src/SqliteNode.ts +65 -113
  143. package/src/SqliteWasm.ts +65 -113
  144. package/src/drizzle/d1-identity.ts +2 -2
  145. package/src/drizzle/driver-types.ts +26 -0
  146. package/src/drizzle/email-drivers.ts +320 -0
  147. package/src/drizzle/email-model.ts +24 -78
  148. package/src/drizzle/email-target.ts +118 -211
  149. package/src/drizzle/model.ts +0 -2
  150. package/src/drizzle/mysql-identity.ts +4 -24
  151. package/src/drizzle/native-clock.ts +21 -0
  152. package/src/drizzle/native-database.ts +59 -18
  153. package/src/drizzle/native-sql-table.ts +104 -87
  154. package/src/drizzle/native-target.ts +120 -0
  155. package/src/drizzle/oauth-connected-drivers.ts +24 -233
  156. package/src/drizzle/oauth-connected-model.ts +3 -93
  157. package/src/drizzle/oauth-connected-reference.ts +16 -25
  158. package/src/drizzle/oauth-drivers.ts +58 -99
  159. package/src/drizzle/oauth-model.ts +27 -132
  160. package/src/drizzle/oauth-target.ts +250 -33
  161. package/src/drizzle/passkey/target.ts +205 -0
  162. package/src/drizzle/passkey/write-target.ts +91 -0
  163. package/src/drizzle/passkey-drivers.ts +35 -133
  164. package/src/drizzle/passkey-model.ts +3 -81
  165. package/src/drizzle/passkey-registration-ceremony-model.ts +5 -25
  166. package/src/drizzle/passkey-write-drivers.ts +32 -102
  167. package/src/drizzle/passkey-write-model.ts +10 -44
  168. package/src/drizzle/password-drivers.ts +286 -0
  169. package/src/drizzle/password-model.ts +10 -44
  170. package/src/drizzle/password-target.ts +85 -239
  171. package/src/drizzle/pg-identity.ts +4 -19
  172. package/src/drizzle/phone-drivers.ts +142 -0
  173. package/src/drizzle/phone-model.ts +22 -162
  174. package/src/drizzle/phone-target.ts +51 -493
  175. package/src/drizzle/proof-drivers.ts +123 -0
  176. package/src/drizzle/proof-model.ts +12 -123
  177. package/src/drizzle/proof-target.ts +38 -102
  178. package/src/drizzle/session-drivers.ts +696 -0
  179. package/src/drizzle/session-model.ts +54 -118
  180. package/src/drizzle/sqlite-do-database.ts +8 -0
  181. package/src/drizzle/sqlite-identity.ts +4 -22
  182. package/src/drizzle/step-up-model.ts +13 -37
  183. package/src/drizzle/storage-validation.ts +2 -1
  184. package/src/drizzle/totp-model.ts +20 -77
  185. package/src/drizzle/totp-target.ts +121 -261
  186. package/src/drizzle/transaction-handle.ts +41 -0
  187. package/src/drizzle/transaction-mysql.ts +90 -25
  188. package/src/index.ts +7 -122
  189. package/src/internal/drizzle-postgres.ts +4 -7
  190. package/src/internal/drizzle-sqlite.ts +4 -7
  191. package/dist/drizzle/crypto.mjs +0 -11
  192. package/dist/drizzle/crypto.mjs.map +0 -1
  193. package/dist/drizzle/d1-emails.d.mts +0 -62
  194. package/dist/drizzle/d1-emails.mjs +0 -626
  195. package/dist/drizzle/d1-emails.mjs.map +0 -1
  196. package/dist/drizzle/d1-generated-statement.mjs +0 -79
  197. package/dist/drizzle/d1-generated-statement.mjs.map +0 -1
  198. package/dist/drizzle/d1-oauth.d.mts +0 -331
  199. package/dist/drizzle/d1-oauth.mjs +0 -79
  200. package/dist/drizzle/d1-oauth.mjs.map +0 -1
  201. package/dist/drizzle/d1-passkey.d.mts +0 -37
  202. package/dist/drizzle/d1-passkey.mjs +0 -98
  203. package/dist/drizzle/d1-passkey.mjs.map +0 -1
  204. package/dist/drizzle/d1-password-prepared.d.mts +0 -25
  205. package/dist/drizzle/d1-password-prepared.mjs +0 -473
  206. package/dist/drizzle/d1-password-prepared.mjs.map +0 -1
  207. package/dist/drizzle/d1-passwords.d.mts +0 -70
  208. package/dist/drizzle/d1-passwords.mjs +0 -808
  209. package/dist/drizzle/d1-passwords.mjs.map +0 -1
  210. package/dist/drizzle/d1-phone.d.mts +0 -23
  211. package/dist/drizzle/d1-phone.mjs +0 -33
  212. package/dist/drizzle/d1-phone.mjs.map +0 -1
  213. package/dist/drizzle/d1-planning.d.mts +0 -11
  214. package/dist/drizzle/d1-planning.mjs +0 -43
  215. package/dist/drizzle/d1-planning.mjs.map +0 -1
  216. package/dist/drizzle/d1-proofs.d.mts +0 -80
  217. package/dist/drizzle/d1-proofs.mjs +0 -842
  218. package/dist/drizzle/d1-proofs.mjs.map +0 -1
  219. package/dist/drizzle/d1-sessions.d.mts +0 -68
  220. package/dist/drizzle/d1-sessions.mjs +0 -987
  221. package/dist/drizzle/d1-sessions.mjs.map +0 -1
  222. package/dist/drizzle/d1-totp.d.mts +0 -23
  223. package/dist/drizzle/d1-totp.mjs +0 -30
  224. package/dist/drizzle/d1-totp.mjs.map +0 -1
  225. package/dist/drizzle/email-registration.d.mts +0 -33
  226. package/dist/drizzle/email-registration.mjs +0 -281
  227. package/dist/drizzle/email-registration.mjs.map +0 -1
  228. package/dist/drizzle/email-sql.d.mts +0 -1
  229. package/dist/drizzle/email-sql.mjs +0 -9
  230. package/dist/drizzle/email-sql.mjs.map +0 -1
  231. package/dist/drizzle/mysql-emails.d.mts +0 -71
  232. package/dist/drizzle/mysql-emails.mjs +0 -43
  233. package/dist/drizzle/mysql-emails.mjs.map +0 -1
  234. package/dist/drizzle/mysql-password-prepared.d.mts +0 -30
  235. package/dist/drizzle/mysql-password-prepared.mjs +0 -21
  236. package/dist/drizzle/mysql-password-prepared.mjs.map +0 -1
  237. package/dist/drizzle/mysql-passwords.d.mts +0 -71
  238. package/dist/drizzle/mysql-passwords.mjs +0 -43
  239. package/dist/drizzle/mysql-passwords.mjs.map +0 -1
  240. package/dist/drizzle/mysql-proofs.d.mts +0 -75
  241. package/dist/drizzle/mysql-proofs.mjs +0 -28
  242. package/dist/drizzle/mysql-proofs.mjs.map +0 -1
  243. package/dist/drizzle/mysql-sessions.d.mts +0 -92
  244. package/dist/drizzle/mysql-sessions.mjs +0 -58
  245. package/dist/drizzle/mysql-sessions.mjs.map +0 -1
  246. package/dist/drizzle/oauth-connected-model.mjs.map +0 -1
  247. package/dist/drizzle/oauth-connected-target.d.mts +0 -6
  248. package/dist/drizzle/oauth-connected-target.mjs +0 -12
  249. package/dist/drizzle/oauth-connected-target.mjs.map +0 -1
  250. package/dist/drizzle/oauth-kernel.mjs +0 -11
  251. package/dist/drizzle/oauth-kernel.mjs.map +0 -1
  252. package/dist/drizzle/oauth-mysql.mjs +0 -8
  253. package/dist/drizzle/oauth-mysql.mjs.map +0 -1
  254. package/dist/drizzle/passkey-kernel.mjs +0 -8
  255. package/dist/drizzle/passkey-kernel.mjs.map +0 -1
  256. package/dist/drizzle/passkey-model.mjs.map +0 -1
  257. package/dist/drizzle/passkey-registration-ceremony-model.mjs +0 -2
  258. package/dist/drizzle/passkey-state.mjs +0 -7
  259. package/dist/drizzle/passkey-state.mjs.map +0 -1
  260. package/dist/drizzle/passkey-target.d.mts +0 -2
  261. package/dist/drizzle/passkey-target.mjs +0 -7
  262. package/dist/drizzle/passkey-target.mjs.map +0 -1
  263. package/dist/drizzle/passkey-write-target.d.mts +0 -5
  264. package/dist/drizzle/passkey-write-target.mjs +0 -7
  265. package/dist/drizzle/passkey-write-target.mjs.map +0 -1
  266. package/dist/drizzle/password-prepared-model.d.mts +0 -92
  267. package/dist/drizzle/password-prepared-model.mjs +0 -11
  268. package/dist/drizzle/password-prepared-model.mjs.map +0 -1
  269. package/dist/drizzle/password-prepared-sql.mjs +0 -395
  270. package/dist/drizzle/password-prepared-sql.mjs.map +0 -1
  271. package/dist/drizzle/password-prepared-state.mjs +0 -104
  272. package/dist/drizzle/password-prepared-state.mjs.map +0 -1
  273. package/dist/drizzle/password-prepared-target.d.mts +0 -13
  274. package/dist/drizzle/password-prepared-target.mjs +0 -62
  275. package/dist/drizzle/password-prepared-target.mjs.map +0 -1
  276. package/dist/drizzle/password-registration.d.mts +0 -7
  277. package/dist/drizzle/password-registration.mjs +0 -137
  278. package/dist/drizzle/password-registration.mjs.map +0 -1
  279. package/dist/drizzle/password-sql.d.mts +0 -1
  280. package/dist/drizzle/password-sql.mjs +0 -10
  281. package/dist/drizzle/password-sql.mjs.map +0 -1
  282. package/dist/drizzle/pg-emails.d.mts +0 -72
  283. package/dist/drizzle/pg-emails.mjs +0 -43
  284. package/dist/drizzle/pg-emails.mjs.map +0 -1
  285. package/dist/drizzle/pg-password-prepared.d.mts +0 -31
  286. package/dist/drizzle/pg-password-prepared.mjs +0 -21
  287. package/dist/drizzle/pg-password-prepared.mjs.map +0 -1
  288. package/dist/drizzle/pg-passwords.d.mts +0 -72
  289. package/dist/drizzle/pg-passwords.mjs +0 -43
  290. package/dist/drizzle/pg-passwords.mjs.map +0 -1
  291. package/dist/drizzle/pg-proofs.d.mts +0 -76
  292. package/dist/drizzle/pg-proofs.mjs +0 -27
  293. package/dist/drizzle/pg-proofs.mjs.map +0 -1
  294. package/dist/drizzle/pg-sessions.d.mts +0 -93
  295. package/dist/drizzle/pg-sessions.mjs +0 -58
  296. package/dist/drizzle/pg-sessions.mjs.map +0 -1
  297. package/dist/drizzle/phone-state.mjs +0 -14
  298. package/dist/drizzle/phone-state.mjs.map +0 -1
  299. package/dist/drizzle/phone-target.d.mts +0 -15
  300. package/dist/drizzle/proof-sql.d.mts +0 -1
  301. package/dist/drizzle/proof-sql.mjs +0 -8
  302. package/dist/drizzle/proof-sql.mjs.map +0 -1
  303. package/dist/drizzle/query-operations.mjs +0 -31
  304. package/dist/drizzle/query-operations.mjs.map +0 -1
  305. package/dist/drizzle/session-sql.d.mts +0 -1
  306. package/dist/drizzle/session-sql.mjs +0 -9
  307. package/dist/drizzle/session-sql.mjs.map +0 -1
  308. package/dist/drizzle/session-target.d.mts +0 -30
  309. package/dist/drizzle/session-target.mjs +0 -49
  310. package/dist/drizzle/session-target.mjs.map +0 -1
  311. package/dist/drizzle/sqlite-emails.mjs +0 -50
  312. package/dist/drizzle/sqlite-emails.mjs.map +0 -1
  313. package/dist/drizzle/sqlite-password-prepared.mjs +0 -26
  314. package/dist/drizzle/sqlite-password-prepared.mjs.map +0 -1
  315. package/dist/drizzle/sqlite-passwords.mjs +0 -54
  316. package/dist/drizzle/sqlite-passwords.mjs.map +0 -1
  317. package/dist/drizzle/sqlite-proofs.mjs +0 -34
  318. package/dist/drizzle/sqlite-proofs.mjs.map +0 -1
  319. package/dist/drizzle/sqlite-sessions.mjs +0 -79
  320. package/dist/drizzle/sqlite-sessions.mjs.map +0 -1
  321. package/dist/drizzle/standalone-guard.d.mts +0 -2
  322. package/dist/drizzle/standalone-guard.mjs +0 -21
  323. package/dist/drizzle/standalone-guard.mjs.map +0 -1
  324. package/dist/drizzle/totp-state.d.mts +0 -37
  325. package/dist/drizzle/totp-state.mjs +0 -287
  326. package/dist/drizzle/totp-state.mjs.map +0 -1
  327. package/dist/drizzle/totp-target.d.mts +0 -15
  328. package/dist/drizzle/transaction-execution.d.mts +0 -2
  329. package/dist/drizzle/transaction-execution.mjs +0 -11
  330. package/dist/drizzle/transaction-execution.mjs.map +0 -1
  331. package/dist/drizzle/transaction-owner.d.mts +0 -1
  332. package/dist/drizzle/transaction-owner.mjs +0 -8
  333. package/dist/drizzle/transaction-owner.mjs.map +0 -1
  334. package/src/drizzle/crypto.ts +0 -14
  335. package/src/drizzle/d1-emails.ts +0 -1945
  336. package/src/drizzle/d1-generated-statement.ts +0 -129
  337. package/src/drizzle/d1-oauth.ts +0 -360
  338. package/src/drizzle/d1-passkey.ts +0 -383
  339. package/src/drizzle/d1-password-prepared.ts +0 -1265
  340. package/src/drizzle/d1-passwords.ts +0 -2060
  341. package/src/drizzle/d1-phone.ts +0 -103
  342. package/src/drizzle/d1-planning.ts +0 -104
  343. package/src/drizzle/d1-proofs.ts +0 -2354
  344. package/src/drizzle/d1-sessions.ts +0 -2940
  345. package/src/drizzle/d1-totp.ts +0 -88
  346. package/src/drizzle/email-registration.ts +0 -850
  347. package/src/drizzle/email-sql.ts +0 -25
  348. package/src/drizzle/mysql-emails.ts +0 -343
  349. package/src/drizzle/mysql-password-prepared.ts +0 -198
  350. package/src/drizzle/mysql-passwords.ts +0 -343
  351. package/src/drizzle/mysql-proofs.ts +0 -196
  352. package/src/drizzle/mysql-sessions.ts +0 -780
  353. package/src/drizzle/oauth-connected-target.ts +0 -21
  354. package/src/drizzle/oauth-kernel.ts +0 -10
  355. package/src/drizzle/oauth-mysql.ts +0 -10
  356. package/src/drizzle/passkey-kernel.ts +0 -4
  357. package/src/drizzle/passkey-state.ts +0 -3
  358. package/src/drizzle/passkey-target.ts +0 -23
  359. package/src/drizzle/passkey-write-target.ts +0 -9
  360. package/src/drizzle/password-prepared-model.ts +0 -241
  361. package/src/drizzle/password-prepared-sql.ts +0 -1201
  362. package/src/drizzle/password-prepared-state.ts +0 -231
  363. package/src/drizzle/password-prepared-target.ts +0 -169
  364. package/src/drizzle/password-registration.ts +0 -369
  365. package/src/drizzle/password-sql.ts +0 -16
  366. package/src/drizzle/pg-emails.ts +0 -343
  367. package/src/drizzle/pg-password-prepared.ts +0 -199
  368. package/src/drizzle/pg-passwords.ts +0 -342
  369. package/src/drizzle/pg-proofs.ts +0 -206
  370. package/src/drizzle/pg-sessions.ts +0 -789
  371. package/src/drizzle/phone-state.ts +0 -21
  372. package/src/drizzle/proof-sql.ts +0 -10
  373. package/src/drizzle/query-operations.ts +0 -49
  374. package/src/drizzle/session-sql.ts +0 -15
  375. package/src/drizzle/session-target.ts +0 -337
  376. package/src/drizzle/sqlite-emails.ts +0 -393
  377. package/src/drizzle/sqlite-password-prepared.ts +0 -230
  378. package/src/drizzle/sqlite-passwords.ts +0 -497
  379. package/src/drizzle/sqlite-proofs.ts +0 -229
  380. package/src/drizzle/sqlite-sessions.ts +0 -1013
  381. package/src/drizzle/totp-state.ts +0 -525
  382. package/src/drizzle/transaction-execution.ts +0 -13
  383. package/src/drizzle/transaction-owner.ts +0 -11
@@ -1,842 +0,0 @@
1
- import { requiredProofConstraints } from "./proof-model.mjs";
2
- import { PersistenceMappingError as PersistenceMappingError$1, column, isMappedConstraintConflict, updateValues } from "./model.mjs";
3
- import { balancedD1And } from "./d1-generated-statement.mjs";
4
- import { validateDrizzleStorage } from "./storage-validation.mjs";
5
- import { Database } from "./d1-database.mjs";
6
- import { D1BatchStatements } from "./D1BatchStatements.mjs";
7
- import { CurrentD1PlanningDatabase, makeD1Owner } from "./d1-planning.mjs";
8
- import { nativeDatabase } from "./native-database.mjs";
9
- import { NativeDatabase } from "@yielded/auth-persistence/Adapter";
10
- import { and, count, eq, gte, inArray, isNull, lte, notExists, or, sql } from "drizzle-orm";
11
- import { Cause, Context, Effect, Schema } from "effect";
12
- import { CurrentCommitJournal, HookConfigurationError, LifecycleHooks, coordinateCommit, hasCommitScope } from "@yielded/auth/Hooks";
13
- import { reportPersistenceFailure } from "@yielded/auth/Persistence";
14
- import { ProofBinding, ProofPersistence, ProofRequestConflict, ProofUnavailable } from "@yielded/auth/Proofs";
15
- //#region src/drizzle/d1-proofs.ts
16
- const unavailable = () => ProofUnavailable.make({});
17
- const everyFailureMatches = (cause, classify) => classify !== void 0 && cause.reasons.length > 0 && cause.reasons.every((reason) => Cause.isFailReason(reason) && classify(Cause.fail(reason.error)));
18
- const conflict = () => ProofRequestConflict.make({});
19
- const validConstraints = (mapping) => Object.entries(requiredProofConstraints).every(([key, value]) => mapping.constraints[key] === value);
20
- const canonicalBinding = Schema.encodeSync(Schema.fromJsonString(ProofBinding));
21
- const sameBinding = (left, right) => canonicalBinding(left) === canonicalBinding(right);
22
- const containsFailure = (failure, predicate) => {
23
- const seen = /* @__PURE__ */ new Set();
24
- const pending = [failure];
25
- for (let inspected = 0; inspected < 32 && pending.length > 0; inspected++) {
26
- const current = pending.shift();
27
- if (current === void 0 || current === null || seen.has(current)) continue;
28
- seen.add(current);
29
- if (predicate(current)) return true;
30
- if (Cause.isCause(current)) {
31
- for (const reason of current.reasons) if (Cause.isFailReason(reason)) pending.push(reason.error);
32
- else if (Cause.isDieReason(reason)) pending.push(reason.defect);
33
- continue;
34
- }
35
- if (typeof current !== "object") continue;
36
- const wrapped = current;
37
- if (wrapped.cause !== void 0) pending.push(wrapped.cause);
38
- if (wrapped.reason !== void 0) pending.push(wrapped.reason);
39
- if (wrapped.message !== void 0) pending.push(wrapped.message);
40
- }
41
- return false;
42
- };
43
- const isGuardFailure = (cause, marker) => {
44
- const nativeMessage = `bad JSON path: '${`$[${marker.replaceAll("'", "''")}]`}': SQLITE_ERROR`;
45
- return containsFailure(cause, (value) => value === nativeMessage || value === `D1_ERROR: ${nativeMessage}`);
46
- };
47
- const statement = Effect.fn(function* (query) {
48
- const database = yield* CurrentD1PlanningDatabase;
49
- const rendered = query.toSQL();
50
- return database.$client.unsafe(rendered.sql, rendered.params);
51
- });
52
- const readEngineNowMillis = Effect.fn("Drizzle.readEngineNowMillis")(function* (mapping) {
53
- return yield* (yield* CurrentD1PlanningDatabase).select({ value: mapping.d1.engineNowMillis.as("engine_now_millis") }).from(sql`(select 1)`).pipe(Effect.flatMap((rows) => {
54
- const value = Number(rows[0]?.value);
55
- return Number.isFinite(value) ? Effect.succeed(value) : Effect.fail(unavailable());
56
- }));
57
- });
58
- const driverValues = (values, entries) => ({
59
- ...values,
60
- ...Object.fromEntries(entries)
61
- });
62
- const assertion = Effect.fn(function* (condition, marker) {
63
- const database = yield* CurrentD1PlanningDatabase;
64
- return yield* statement(database.select({ ok: sql`case when ${condition} then 1 else json_extract('[]', ${`$[${marker}]`}) end`.as("ok") }).from(sql`(select 1)`));
65
- });
66
- const allocateVersion = (mapping) => mapping.allocateVersion !== void 0 ? mapping.allocateVersion : mapping.allocateVersionSync === void 0 ? Effect.fail(unavailable()) : Effect.try({
67
- try: mapping.allocateVersionSync,
68
- catch: (cause) => new PersistenceMappingError$1({
69
- operation: "mapping",
70
- cause
71
- })
72
- });
73
- const requestColumns = (mapping) => ({
74
- moduleId: column(mapping.request.table, mapping.request.moduleId),
75
- requestId: column(mapping.request.table, mapping.request.requestId),
76
- fingerprint: column(mapping.request.table, mapping.request.fingerprint),
77
- proofId: column(mapping.request.table, mapping.request.proofId),
78
- retentionUntil: column(mapping.request.table, mapping.request.retentionUntil)
79
- });
80
- const seriesColumns = (mapping) => ({
81
- moduleId: column(mapping.series.table, mapping.series.moduleId),
82
- purpose: column(mapping.series.table, mapping.series.purpose),
83
- scopeKey: column(mapping.series.table, mapping.series.scopeKey),
84
- activeProofId: column(mapping.series.table, mapping.series.activeProofId),
85
- lastIssueAt: column(mapping.series.table, mapping.series.lastIssueAt),
86
- version: column(mapping.series.table, mapping.series.version)
87
- });
88
- const generationColumns = (mapping) => ({
89
- moduleId: column(mapping.generation.table, mapping.generation.moduleId),
90
- purpose: column(mapping.generation.table, mapping.generation.purpose),
91
- proofId: column(mapping.generation.table, mapping.generation.proofId),
92
- seriesKey: column(mapping.generation.table, mapping.generation.seriesKey),
93
- deliveryId: column(mapping.generation.table, mapping.generation.deliveryId),
94
- verifierKeyId: column(mapping.generation.table, mapping.generation.verifierKeyId),
95
- verifierDigest: column(mapping.generation.table, mapping.generation.verifierDigest),
96
- expiresAt: column(mapping.generation.table, mapping.generation.expiresAt),
97
- version: column(mapping.generation.table, mapping.generation.version),
98
- state: column(mapping.generation.table, mapping.generation.state),
99
- sendCount: column(mapping.generation.table, mapping.generation.sendCount),
100
- deliveryState: column(mapping.generation.table, mapping.generation.deliveryState),
101
- claimVersion: column(mapping.generation.table, mapping.generation.claimVersion),
102
- claimDeadline: column(mapping.generation.table, mapping.generation.claimDeadline),
103
- retryAt: column(mapping.generation.table, mapping.generation.retryAt),
104
- deliveryRetryMillis: column(mapping.generation.table, mapping.generation.deliveryRetryMillis),
105
- retentionUntil: column(mapping.generation.table, mapping.generation.retentionUntil)
106
- });
107
- const continuationColumns = (mapping) => ({
108
- moduleId: column(mapping.continuation.table, mapping.continuation.moduleId),
109
- continuationId: column(mapping.continuation.table, mapping.continuation.continuationId),
110
- digest: column(mapping.continuation.table, mapping.continuation.digest),
111
- consumed: column(mapping.continuation.table, mapping.continuation.consumed),
112
- retentionUntil: column(mapping.continuation.table, mapping.continuation.retentionUntil)
113
- });
114
- const scopeColumns = (mapping) => ({
115
- moduleId: column(mapping.rateScope.table, mapping.rateScope.moduleId),
116
- purpose: column(mapping.rateScope.table, mapping.rateScope.purpose),
117
- action: column(mapping.rateScope.table, mapping.rateScope.action),
118
- scopeKind: column(mapping.rateScope.table, mapping.rateScope.scopeKind),
119
- scopeKey: column(mapping.rateScope.table, mapping.rateScope.scopeKey)
120
- });
121
- const abuseColumns = (mapping) => ({
122
- moduleId: column(mapping.abuseEvent.table, mapping.abuseEvent.moduleId),
123
- purpose: column(mapping.abuseEvent.table, mapping.abuseEvent.purpose),
124
- action: column(mapping.abuseEvent.table, mapping.abuseEvent.action),
125
- scopeKind: column(mapping.abuseEvent.table, mapping.abuseEvent.scopeKind),
126
- scopeKey: column(mapping.abuseEvent.table, mapping.abuseEvent.scopeKey),
127
- commandId: column(mapping.abuseEvent.table, mapping.abuseEvent.commandId),
128
- occurredAt: column(mapping.abuseEvent.table, mapping.abuseEvent.occurredAt),
129
- retentionUntil: column(mapping.abuseEvent.table, mapping.abuseEvent.retentionUntil)
130
- });
131
- const failureColumns = (mapping) => ({
132
- moduleId: column(mapping.failureEvent.table, mapping.failureEvent.moduleId),
133
- purpose: column(mapping.failureEvent.table, mapping.failureEvent.purpose),
134
- seriesKey: column(mapping.failureEvent.table, mapping.failureEvent.seriesKey),
135
- commandId: column(mapping.failureEvent.table, mapping.failureEvent.commandId),
136
- occurredAt: column(mapping.failureEvent.table, mapping.failureEvent.occurredAt),
137
- retentionUntil: column(mapping.failureEvent.table, mapping.failureEvent.retentionUntil)
138
- });
139
- const commandColumns = (mapping) => ({
140
- moduleId: column(mapping.command.table, mapping.command.moduleId),
141
- commandId: column(mapping.command.table, mapping.command.commandId),
142
- decision: column(mapping.command.table, mapping.command.decision),
143
- retentionUntil: column(mapping.command.table, mapping.command.retentionUntil)
144
- });
145
- const scopeEntries = (keys, binding, action, policy) => {
146
- const suffix = action === "issue" ? "Issues" : "Attempts";
147
- const simple = action === "issue" ? "issues" : "attempts";
148
- const entries = [{
149
- kind: "action",
150
- key: "*",
151
- budget: policy.abuse[`action${suffix}`]
152
- }, {
153
- kind: "identifier",
154
- key: keys.identifier,
155
- budget: policy.abuse[simple]
156
- }];
157
- if (binding._tag !== "Identifier") entries.push({
158
- kind: "subject",
159
- key: keys.subject,
160
- budget: policy.abuse[`subject${suffix}`]
161
- });
162
- return entries;
163
- };
164
- const scopeCondition = (mapping, moduleId, purpose, action, entry) => {
165
- const c = abuseColumns(mapping);
166
- return sql`(select count(*) from ${mapping.abuseEvent.table} where ${c.moduleId} = ${sql.param(moduleId, c.moduleId)} and ${c.purpose} = ${sql.param(purpose, c.purpose)} and ${c.action} = ${sql.param(action, c.action)} and ${c.scopeKind} = ${sql.param(entry.kind, c.scopeKind)} and ${c.scopeKey} = ${sql.param(entry.key, c.scopeKey)} and ${c.occurredAt} >= ${mapping.d1.engineInstantMinus(entry.budget.windowMillis)}) < ${entry.budget.limit}`;
167
- };
168
- const failureCondition = (mapping, moduleId, purpose, seriesKey, policy) => {
169
- const c = failureColumns(mapping);
170
- return sql`(select count(*) from ${mapping.failureEvent.table} where ${c.moduleId} = ${sql.param(moduleId, c.moduleId)} and ${c.purpose} = ${sql.param(purpose, c.purpose)} and ${c.seriesKey} = ${sql.param(seriesKey, c.seriesKey)} and ${c.occurredAt} >= ${mapping.d1.engineInstantMinus(policy.abuse.attempts.windowMillis)}) < ${policy.maximumFailedAttempts}`;
171
- };
172
- const readScopeAdmission = Effect.fn("DrizzleD1Proof.readScopeAdmission")(function* (mapping, moduleId, purpose, action, entries, now) {
173
- const database = yield* CurrentD1PlanningDatabase;
174
- const c = abuseColumns(mapping);
175
- const admitted = [];
176
- for (const entry of entries) {
177
- const rows = yield* database.select({ total: count() }).from(mapping.abuseEvent.table).where(and(eq(c.moduleId, moduleId), eq(c.purpose, purpose), eq(c.action, action), eq(c.scopeKind, entry.kind), eq(c.scopeKey, entry.key), gte(c.occurredAt, mapping.encodeInstant(now - entry.budget.windowMillis))));
178
- if (Number(rows[0]?.total ?? 0) < entry.budget.limit) admitted.push(entry);
179
- }
180
- return admitted;
181
- });
182
- const authority = Effect.fn("DrizzleD1Proof.authority")(function* (mapping, moduleId, purpose, binding) {
183
- const database = yield* CurrentD1PlanningDatabase;
184
- let nativeSubjectId;
185
- let subjectCurrent = true;
186
- const parts = [];
187
- if (binding._tag !== "Identifier") {
188
- if (mapping.authority.subject === void 0 || mapping.authority.credential === void 0 || mapping.authority.subjectId === void 0) return yield* unavailable();
189
- nativeSubjectId = yield* mapping.authority.subjectId.toNative(binding.revision.subjectId);
190
- const subject = mapping.authority.subject;
191
- const id = column(subject.table, subject.id);
192
- const status = column(subject.table, subject.status);
193
- const revision = column(subject.table, subject.securityRevision);
194
- const subjectRow = (yield* database.select().from(subject.table).where(eq(id, nativeSubjectId)).limit(1))[0];
195
- subjectCurrent = subjectRow !== void 0 && subject.isActiveStatus(subjectRow[subject.status]) && subjectRow[subject.securityRevision] === binding.revision.securityRevision;
196
- parts.push(sql`exists(select 1 from ${subject.table} where ${id} = ${sql.param(nativeSubjectId, id)} and ${status} = ${sql.param(subject.d1ActiveStatusValue, status)} and ${revision} = ${sql.param(binding.revision.securityRevision, revision)})`);
197
- }
198
- const identifier = mapping.authority.identifier;
199
- const namespace = column(identifier.table, identifier.namespace);
200
- const value = column(identifier.table, identifier.value);
201
- const identifierRows = yield* database.select().from(identifier.table).where(and(eq(namespace, binding.identifier.namespace), eq(value, binding.identifier.value)));
202
- const input = {
203
- moduleId,
204
- purpose,
205
- binding,
206
- ...nativeSubjectId === void 0 ? {} : { nativeSubjectId }
207
- };
208
- const identifierCurrent = identifier.isCurrent(input, identifierRows);
209
- parts.push(identifier.d1CurrentCondition(input));
210
- let credentialsCurrent = true;
211
- if (binding._tag !== "Identifier") {
212
- const credential = mapping.authority.credential;
213
- const owner = column(credential.table, credential.subjectId);
214
- const id = column(credential.table, credential.credentialId);
215
- const revision = column(credential.table, credential.revision);
216
- const status = credential.status === void 0 ? void 0 : column(credential.table, credential.status);
217
- const expected = [...binding.revision.credentials].sort((a, b) => a.credentialId.localeCompare(b.credentialId));
218
- const actual = (expected.length === 0 ? [] : yield* database.select().from(credential.table).where(and(eq(owner, nativeSubjectId), inArray(id, expected.map((item) => item.credentialId))))).map((row) => ({
219
- id: row[credential.credentialId],
220
- revision: row[credential.revision],
221
- active: credential.status === void 0 || credential.isActiveStatus?.(row[credential.status]) === true
222
- })).sort((a, b) => String(a.id).localeCompare(String(b.id)));
223
- credentialsCurrent = actual.length === expected.length && actual.every((row, index) => row.active && row.id === expected[index]?.credentialId && row.revision === expected[index]?.revision);
224
- for (const expectedCredential of expected) parts.push(sql`exists(select 1 from ${credential.table} where ${owner} = ${sql.param(nativeSubjectId, owner)} and ${id} = ${sql.param(expectedCredential.credentialId, id)} and ${revision} = ${sql.param(expectedCredential.revision, revision)}${status === void 0 ? sql`` : sql` and ${status} = ${sql.param(credential.d1ActiveStatusValue, status)}`})`);
225
- }
226
- return {
227
- current: subjectCurrent && identifierCurrent && credentialsCurrent,
228
- condition: balancedD1And(...parts) ?? sql`1 = 1`
229
- };
230
- });
231
- const anchorStatements = Effect.fn(function* (mapping, moduleId, purpose, action, entries, seriesKey, seriesVersion, includeSeries) {
232
- const database = yield* CurrentD1PlanningDatabase;
233
- return [...yield* Effect.forEach(entries, Effect.fn(function* (entry) {
234
- return yield* statement(database.insert(mapping.rateScope.table).values(mapping.rateScope.encodeInsert({
235
- moduleId,
236
- purpose,
237
- action,
238
- scopeKind: entry.kind,
239
- scopeKey: entry.key
240
- })).onConflictDoNothing());
241
- })), ...includeSeries ? [yield* statement(database.insert(mapping.series.table).values(mapping.series.encodeInsert({
242
- moduleId,
243
- purpose,
244
- scopeKey: seriesKey,
245
- version: seriesVersion
246
- })).onConflictDoNothing())] : []];
247
- });
248
- const insertScopeStatements = Effect.fn(function* (mapping, moduleId, purpose, action, commandId, entries, now, retentionUntil, marker) {
249
- const database = yield* CurrentD1PlanningDatabase;
250
- return (yield* Effect.forEach(entries, Effect.fn(function* (entry) {
251
- return [yield* assertion(scopeCondition(mapping, moduleId, purpose, action, entry), marker), yield* statement(database.insert(mapping.abuseEvent.table).values(driverValues(mapping.abuseEvent.encodeInsert({
252
- moduleId,
253
- purpose,
254
- action,
255
- scopeKind: entry.kind,
256
- scopeKey: entry.key,
257
- commandId,
258
- occurredAtMillis: now,
259
- retentionUntilMillis: retentionUntil
260
- }), [[mapping.abuseEvent.occurredAt, mapping.d1.engineNow], [mapping.abuseEvent.retentionUntil, mapping.d1.engineInstantPlus(retentionUntil - now)]])))];
261
- }))).flat();
262
- });
263
- const readSeries = Effect.fn("Drizzle.readSeries")(function* (mapping, moduleId, purpose, key) {
264
- const database = yield* CurrentD1PlanningDatabase;
265
- const c = seriesColumns(mapping);
266
- return yield* database.select().from(mapping.series.table).where(and(eq(c.moduleId, moduleId), eq(c.purpose, purpose), eq(c.scopeKey, key))).limit(1);
267
- });
268
- const readGeneration = Effect.fn("Drizzle.readGeneration")(function* (mapping, moduleId, proofId) {
269
- const database = yield* CurrentD1PlanningDatabase;
270
- const c = generationColumns(mapping);
271
- return yield* database.select().from(mapping.generation.table).where(and(eq(c.moduleId, moduleId), eq(c.proofId, proofId))).limit(1);
272
- });
273
- const commandInsert = Effect.fn(function* (mapping, moduleId, commandId, kind, decision, retentionUntil, nativeRetention) {
274
- const database = yield* CurrentD1PlanningDatabase;
275
- return yield* statement(database.insert(mapping.command.table).values(driverValues(mapping.command.encodeInsert({
276
- moduleId,
277
- commandId,
278
- kind,
279
- decision,
280
- retentionUntilMillis: retentionUntil
281
- }), nativeRetention === void 0 ? [] : [[mapping.command.retentionUntil, nativeRetention]])));
282
- });
283
- const issuePlan = Effect.fn("Drizzle.issuePlan")(function* (mapping, input, prepare) {
284
- const database = yield* CurrentD1PlanningDatabase;
285
- const journal = yield* CurrentCommitJournal;
286
- const keys = mapping.scopeKeys({
287
- moduleId: input.record.moduleId,
288
- purpose: input.record.purpose,
289
- binding: input.record.binding
290
- });
291
- const current = yield* authority(mapping, input.record.moduleId, input.record.purpose, input.record.binding);
292
- const now = yield* readEngineNowMillis(mapping);
293
- const retentionUntil = now + input.policy.requestRetentionMillis;
294
- const rc = requestColumns(mapping);
295
- const existingRequest = (yield* database.select().from(mapping.request.table).where(and(eq(rc.moduleId, input.record.moduleId), eq(rc.requestId, input.record.requestId))).limit(1))[0];
296
- if (existingRequest !== void 0) {
297
- if ((yield* mapping.decodeInstant(existingRequest[mapping.request.retentionUntil])) > now) {
298
- if (existingRequest[mapping.request.fingerprint] !== input.record.fingerprint) return yield* conflict();
299
- return {
300
- receipt: prepare({
301
- _tag: "Existing",
302
- receipt: yield* mapping.request.decodeReceipt(existingRequest)
303
- }, journal),
304
- statements: []
305
- };
306
- }
307
- }
308
- const scopes = scopeEntries(keys, input.record.binding, "issue", input.policy);
309
- const initiallyAdmitted = yield* readScopeAdmission(mapping, input.record.moduleId, input.record.purpose, "issue", scopes, now);
310
- const actionOpen = initiallyAdmitted.some((entry) => entry.kind === "action");
311
- const admitted = actionOpen ? initiallyAdmitted : [];
312
- const existingSeries = actionOpen ? (yield* readSeries(mapping, input.record.moduleId, input.record.purpose, keys.series))[0] : void 0;
313
- const seriesVersion = yield* allocateVersion(mapping);
314
- const active = existingSeries?.[mapping.series.activeProofId];
315
- const activeGeneration = active === null || active === void 0 ? void 0 : (yield* readGeneration(mapping, input.record.moduleId, active))[0];
316
- if (active !== null && active !== void 0 && (activeGeneration === void 0 || activeGeneration[mapping.generation.purpose] !== input.record.purpose)) return yield* unavailable();
317
- const matchesActiveBinding = activeGeneration !== void 0 && sameBinding(yield* mapping.generation.decodeBinding(activeGeneration), input.record.binding);
318
- const replacesLiveProof = activeGeneration !== void 0 && activeGeneration[mapping.generation.state] === "active" && (yield* mapping.decodeInstant(activeGeneration[mapping.generation.expiresAt])) > now;
319
- const lastIssue = existingSeries?.[mapping.series.lastIssueAt] === null || existingSeries?.[mapping.series.lastIssueAt] === void 0 ? void 0 : yield* mapping.decodeInstant(existingSeries[mapping.series.lastIssueAt]);
320
- const allowed = current.current && input.eligible && admitted.length === scopes.length && input.record.issuedAtMillis <= now && input.record.expiresAtMillis > now && (!replacesLiveProof || matchesActiveBinding) && (input.supersedes === void 0 || input.supersedes === active) && (lastIssue === void 0 || now - lastIssue >= input.policy.abuse.resendCooldownMillis);
321
- const receipt = {
322
- requestId: input.record.requestId,
323
- reference: {
324
- proofId: input.record.proofId,
325
- purpose: input.record.purpose,
326
- keyId: input.record.verifier.keyId
327
- }
328
- };
329
- const prepared = prepare(allowed ? {
330
- _tag: "Issued",
331
- record: input.record
332
- } : {
333
- _tag: "Suppressed",
334
- receipt
335
- }, journal);
336
- const statements = [];
337
- const marker = `effect-auth-proof-guard:issue:${input.record.requestId}`;
338
- if (existingRequest !== void 0) statements.push(yield* statement(database.delete(mapping.request.table).where(and(eq(rc.moduleId, input.record.moduleId), eq(rc.requestId, input.record.requestId), lte(rc.retentionUntil, mapping.d1.engineNow)))));
339
- statements.push(yield* statement(database.insert(mapping.request.table).values(driverValues(mapping.request.encodeInsert({
340
- record: input.record,
341
- createdAtMillis: now,
342
- retentionUntilMillis: retentionUntil
343
- }), [[mapping.request.createdAt, mapping.d1.engineNow], [mapping.request.retentionUntil, mapping.d1.engineInstantPlus(input.policy.requestRetentionMillis)]]))), ...yield* anchorStatements(mapping, input.record.moduleId, input.record.purpose, "issue", actionOpen ? scopes : scopes.slice(0, 1), keys.series, seriesVersion, actionOpen), ...yield* insertScopeStatements(mapping, input.record.moduleId, input.record.purpose, "issue", input.record.requestId, allowed ? scopes : [], now, retentionUntil, marker));
344
- if (allowed) {
345
- const sc = seriesColumns(mapping);
346
- const gc = generationColumns(mapping);
347
- const replacementCondition = activeGeneration === void 0 ? sql`1 = 1` : sql`exists(select 1 from ${mapping.generation.table} where ${and(eq(gc.moduleId, input.record.moduleId), eq(gc.proofId, activeGeneration[mapping.generation.proofId]), eq(gc.version, activeGeneration[mapping.generation.version]), eq(column(mapping.generation.table, mapping.generation.binding), activeGeneration[mapping.generation.binding]), matchesActiveBinding ? sql`1 = 1` : sql`(${gc.state} <> 'active' or ${gc.expiresAt} <= ${mapping.d1.engineNow})`)})`;
348
- const seriesCondition = and(eq(sc.moduleId, input.record.moduleId), eq(sc.purpose, input.record.purpose), eq(sc.scopeKey, keys.series), active === null || active === void 0 ? or(eq(sc.activeProofId, null), sql`${sc.activeProofId} is null`) : eq(sc.activeProofId, active), lastIssue === void 0 ? sql`1 = 1` : lte(sc.lastIssueAt, mapping.d1.engineInstantMinus(input.policy.abuse.resendCooldownMillis)));
349
- statements.push(yield* assertion(and(current.condition, replacementCondition, sql`${mapping.d1.engineNowMillis} >= ${input.record.issuedAtMillis}`, sql`${mapping.d1.engineNow} < ${sql.param(mapping.encodeInstant(input.record.expiresAtMillis), generationColumns(mapping).expiresAt)}`, sql`exists(select 1 from ${mapping.series.table} where ${seriesCondition})`), marker));
350
- if (active !== null && active !== void 0) statements.push(yield* statement(database.update(mapping.generation.table).set(updateValues([[mapping.generation.state, "superseded"]])).where(and(eq(generationColumns(mapping).moduleId, input.record.moduleId), eq(generationColumns(mapping).proofId, active), eq(generationColumns(mapping).state, "active")))));
351
- statements.push(yield* statement(database.insert(mapping.generation.table).values(driverValues(mapping.generation.encodeInsert({
352
- record: input.record,
353
- seriesKey: keys.series,
354
- retentionUntilMillis: retentionUntil,
355
- state: "active",
356
- deliveryState: "new",
357
- policy: input.policy
358
- }), [[mapping.generation.retentionUntil, mapping.d1.engineInstantPlus(input.policy.requestRetentionMillis)]]))), yield* statement(database.update(mapping.series.table).set(updateValues([
359
- [mapping.series.activeProofId, input.record.proofId],
360
- [mapping.series.lastIssueAt, mapping.d1.engineNow],
361
- [mapping.series.version, seriesVersion]
362
- ])).where(and(eq(sc.moduleId, input.record.moduleId), eq(sc.purpose, input.record.purpose), eq(sc.scopeKey, keys.series)))));
363
- }
364
- return {
365
- receipt: prepared,
366
- statements,
367
- retryable: (cause) => isMappedConstraintConflict(mapping.isRequestConflict, cause) || isMappedConstraintConflict(mapping.isSeriesConflict, cause) || isGuardFailure(cause, marker)
368
- };
369
- });
370
- const attemptPlan = Effect.fn("Drizzle.attemptPlan")(function* (mapping, input, prepare) {
371
- const database = yield* CurrentD1PlanningDatabase;
372
- const journal = yield* CurrentCommitJournal;
373
- const keys = mapping.scopeKeys({
374
- moduleId: input.moduleId,
375
- purpose: input.purpose,
376
- binding: input.binding
377
- });
378
- const current = yield* authority(mapping, input.moduleId, input.purpose, input.binding);
379
- const command = commandColumns(mapping);
380
- const existingCommand = (yield* database.select().from(mapping.command.table).where(and(eq(command.moduleId, input.moduleId), eq(command.commandId, input.continuationId))).limit(1))[0];
381
- if (existingCommand !== void 0) {
382
- if (existingCommand[mapping.command.decision] === "rejected") return {
383
- receipt: prepare({ _tag: "Rejected" }, journal),
384
- statements: []
385
- };
386
- return yield* unavailable();
387
- }
388
- const now = yield* readEngineNowMillis(mapping);
389
- const scopes = scopeEntries(keys, input.binding, "attempt", input.policy);
390
- const initiallyAdmitted = yield* readScopeAdmission(mapping, input.moduleId, input.purpose, "attempt", scopes, now);
391
- const actionOpen = initiallyAdmitted.some((entry) => entry.kind === "action");
392
- const admitted = actionOpen ? initiallyAdmitted : [];
393
- const series = actionOpen ? (yield* readSeries(mapping, input.moduleId, input.purpose, keys.series))[0] : void 0;
394
- const generation = (yield* readGeneration(mapping, input.moduleId, input.proofId))[0];
395
- const fc = failureColumns(mapping);
396
- const failureRows = yield* database.select({ total: count() }).from(mapping.failureEvent.table).where(and(eq(fc.moduleId, input.moduleId), eq(fc.purpose, input.purpose), eq(fc.seriesKey, keys.series), gte(fc.occurredAt, mapping.encodeInstant(now - input.policy.abuse.attempts.windowMillis))));
397
- const failures = Number(failureRows[0]?.total ?? 0);
398
- const storedBinding = generation === void 0 ? void 0 : yield* mapping.generation.decodeBinding(generation);
399
- const expires = generation === void 0 ? void 0 : yield* mapping.decodeInstant(generation[mapping.generation.expiresAt]);
400
- const currentGeneration = generation !== void 0 && generation[mapping.generation.purpose] === input.purpose && generation[mapping.generation.state] === "active" && series?.[mapping.series.activeProofId] === input.proofId && storedBinding !== void 0 && sameBinding(storedBinding, input.binding) && expires !== void 0 && expires > now;
401
- const candidateMatches = generation !== void 0 && input.candidate !== void 0 && generation[mapping.generation.verifierKeyId] === input.candidate.keyId && generation[mapping.generation.verifierDigest] === input.candidate.digest;
402
- const accepted = current.current && currentGeneration && candidateMatches && admitted.length === scopes.length && failures < input.policy.maximumFailedAttempts;
403
- const retentionUntil = now + input.policy.requestRetentionMillis;
404
- const seriesVersion = yield* allocateVersion(mapping);
405
- const statements = [...yield* anchorStatements(mapping, input.moduleId, input.purpose, "attempt", actionOpen ? scopes : scopes.slice(0, 1), keys.series, seriesVersion, actionOpen), ...yield* insertScopeStatements(mapping, input.moduleId, input.purpose, "attempt", input.continuationId, admitted, now, retentionUntil, `effect-auth-proof-guard:attempt:${input.continuationId}`)];
406
- const marker = `effect-auth-proof-guard:attempt:${input.continuationId}`;
407
- if (!accepted) {
408
- const prepared = prepare({ _tag: "Rejected" }, journal);
409
- if (admitted.length === scopes.length && current.current && currentGeneration && !candidateMatches && failures < input.policy.maximumFailedAttempts) {
410
- const gc = generationColumns(mapping);
411
- const sc = seriesColumns(mapping);
412
- statements.push(yield* assertion(and(current.condition, sql`exists(select 1 from ${mapping.series.table} where ${sc.moduleId} = ${sql.param(input.moduleId, sc.moduleId)} and ${sc.purpose} = ${sql.param(input.purpose, sc.purpose)} and ${sc.scopeKey} = ${sql.param(keys.series, sc.scopeKey)} and ${sc.activeProofId} = ${sql.param(input.proofId, sc.activeProofId)})`, sql`exists(select 1 from ${mapping.generation.table} where ${gc.moduleId} = ${sql.param(input.moduleId, gc.moduleId)} and ${gc.proofId} = ${sql.param(input.proofId, gc.proofId)} and ${gc.state} = 'active' and ${gc.expiresAt} > ${mapping.d1.engineNow})`, failureCondition(mapping, input.moduleId, input.purpose, keys.series, input.policy)), marker), yield* statement(database.insert(mapping.failureEvent.table).values(driverValues(mapping.failureEvent.encodeInsert({
413
- moduleId: input.moduleId,
414
- purpose: input.purpose,
415
- seriesKey: keys.series,
416
- commandId: input.continuationId,
417
- occurredAtMillis: now,
418
- retentionUntilMillis: retentionUntil
419
- }), [[mapping.failureEvent.occurredAt, mapping.d1.engineNow], [mapping.failureEvent.retentionUntil, mapping.d1.engineInstantPlus(input.policy.requestRetentionMillis)]]))));
420
- }
421
- statements.push(yield* commandInsert(mapping, input.moduleId, input.continuationId, "attempt", "rejected", retentionUntil, mapping.d1.engineInstantPlus(input.policy.requestRetentionMillis)));
422
- return {
423
- receipt: prepared,
424
- statements,
425
- retryable: (cause) => isMappedConstraintConflict(mapping.isCommandConflict, cause) || isMappedConstraintConflict(mapping.isSeriesConflict, cause) || isGuardFailure(cause, marker)
426
- };
427
- }
428
- const version = yield* allocateVersion(mapping);
429
- const continuationExpires = Math.min(expires, now + input.policy.continuationLifetimeMillis);
430
- const continuation = {
431
- moduleId: input.moduleId,
432
- purpose: input.purpose,
433
- continuationId: input.continuationId,
434
- digest: input.continuationDigest,
435
- proofId: input.proofId,
436
- seriesKey: keys.series,
437
- binding: input.binding,
438
- expiresAtMillis: continuationExpires,
439
- version
440
- };
441
- const prepared = prepare({
442
- _tag: "Accepted",
443
- continuation: {
444
- continuationId: input.continuationId,
445
- purpose: input.purpose,
446
- expiresAtMillis: continuationExpires
447
- }
448
- }, journal);
449
- const gc = generationColumns(mapping);
450
- const sc = seriesColumns(mapping);
451
- statements.push(yield* assertion(and(current.condition, failureCondition(mapping, input.moduleId, input.purpose, keys.series, input.policy), sql`exists(select 1 from ${mapping.series.table} where ${sc.moduleId} = ${sql.param(input.moduleId, sc.moduleId)} and ${sc.purpose} = ${sql.param(input.purpose, sc.purpose)} and ${sc.scopeKey} = ${sql.param(keys.series, sc.scopeKey)} and ${sc.activeProofId} = ${sql.param(input.proofId, sc.activeProofId)})`, sql`exists(select 1 from ${mapping.generation.table} where ${gc.moduleId} = ${sql.param(input.moduleId, gc.moduleId)} and ${gc.proofId} = ${sql.param(input.proofId, gc.proofId)} and ${gc.purpose} = ${sql.param(input.purpose, gc.purpose)} and ${gc.state} = 'active' and ${gc.verifierKeyId} = ${sql.param(input.candidate.keyId, gc.verifierKeyId)} and ${gc.verifierDigest} = ${sql.param(input.candidate.digest, gc.verifierDigest)} and ${gc.expiresAt} > ${mapping.d1.engineNow})`), marker), yield* commandInsert(mapping, input.moduleId, input.continuationId, "attempt", "accepted", retentionUntil, mapping.d1.engineInstantPlus(input.policy.requestRetentionMillis)), yield* statement(database.update(mapping.generation.table).set(updateValues([[mapping.generation.state, "consumed"]])).where(and(eq(gc.moduleId, input.moduleId), eq(gc.proofId, input.proofId), eq(gc.state, "active")))), yield* statement(database.insert(mapping.continuation.table).values(driverValues(mapping.continuation.encodeInsert({
452
- ...continuation,
453
- retentionUntilMillis: retentionUntil
454
- }), [[mapping.continuation.retentionUntil, mapping.d1.engineInstantPlus(input.policy.requestRetentionMillis)]]))));
455
- return {
456
- receipt: prepared,
457
- statements,
458
- retryable: (cause) => isMappedConstraintConflict(mapping.isCommandConflict, cause) || isMappedConstraintConflict(mapping.isSeriesConflict, cause) || isGuardFailure(cause, marker)
459
- };
460
- });
461
- const inspectD1Completion = Effect.fn("DrizzleD1Proof.inspectCompletion")(function* (mapping, input) {
462
- const database = yield* CurrentD1PlanningDatabase;
463
- const keys = mapping.scopeKeys({
464
- moduleId: input.moduleId,
465
- purpose: input.purpose,
466
- binding: input.binding
467
- });
468
- const current = yield* authority(mapping, input.moduleId, input.purpose, input.binding);
469
- const c = continuationColumns(mapping);
470
- const row = (yield* database.select().from(mapping.continuation.table).where(and(eq(c.moduleId, input.moduleId), eq(c.continuationId, input.continuationId))).limit(1))[0];
471
- const now = yield* readEngineNowMillis(mapping);
472
- const record = row === void 0 ? void 0 : yield* mapping.continuation.decode(row);
473
- const accepted = current.current && record !== void 0 && record.moduleId === input.moduleId && record.continuationId === input.continuationId && record.purpose === input.purpose && record.digest === input.continuationDigest && record.seriesKey === keys.series && sameBinding(record.binding, input.binding) && row[mapping.continuation.consumed] === false && record.expiresAtMillis > now;
474
- const immutable = [
475
- mapping.continuation.moduleId,
476
- mapping.continuation.purpose,
477
- mapping.continuation.continuationId,
478
- mapping.continuation.digest,
479
- mapping.continuation.proofId,
480
- mapping.continuation.seriesKey,
481
- mapping.continuation.binding,
482
- mapping.continuation.expiresAt,
483
- mapping.continuation.version,
484
- mapping.continuation.retentionUntil
485
- ];
486
- const exact = row === void 0 ? sql`false` : and(...immutable.map((key) => eq(column(mapping.continuation.table, key), row[key])));
487
- return {
488
- accepted,
489
- record,
490
- row,
491
- columns: c,
492
- condition: and(current.condition, sql`exists(select 1 from ${mapping.continuation.table} where ${exact} and ${c.consumed} = ${sql.param(false, c.consumed)} and ${column(mapping.continuation.table, mapping.continuation.expiresAt)} > ${mapping.d1.engineNow})`),
493
- appliedCondition: row === void 0 ? sql`false` : sql`exists(select 1 from ${mapping.continuation.table} where ${exact} and ${c.consumed} = ${sql.param(true, c.consumed)} and ${column(mapping.continuation.table, mapping.continuation.expiresAt)} > ${mapping.d1.engineNow})`
494
- };
495
- });
496
- /** Read-only preflight plus its exact final-engine-time batch predicate. */
497
- const checkD1ProofCompletion = Effect.fn("Drizzle.checkD1ProofCompletion")(function* (mapping, input) {
498
- return yield* inspectD1Completion(mapping, input);
499
- });
500
- const completionPlan = Effect.fn("Drizzle.completionPlan")(function* (mapping, input, prepare) {
501
- const database = yield* CurrentD1PlanningDatabase;
502
- const journal = yield* CurrentCommitJournal;
503
- const inspected = yield* inspectD1Completion(mapping, input);
504
- const { accepted, record, columns: c } = inspected;
505
- const receipt = prepare(accepted ? "completed" : "rejected", journal);
506
- if (!accepted) return {
507
- receipt,
508
- statements: []
509
- };
510
- const postconditions = [yield* assertion(and(inspected.appliedCondition, sql`exists(select 1 from ${mapping.command.table} where ${column(mapping.command.table, mapping.command.moduleId)} = ${sql.param(input.moduleId, column(mapping.command.table, mapping.command.moduleId))} and ${column(mapping.command.table, mapping.command.commandId)} = ${sql.param(input.continuationDigest, column(mapping.command.table, mapping.command.commandId))} and ${column(mapping.command.table, mapping.command.kind)} = ${sql.param("complete", column(mapping.command.table, mapping.command.kind))} and ${column(mapping.command.table, mapping.command.decision)} = ${sql.param("completed", column(mapping.command.table, mapping.command.decision))} and ${column(mapping.command.table, mapping.command.retentionUntil)} = ${sql.param(mapping.encodeInstant(record.expiresAtMillis), column(mapping.command.table, mapping.command.retentionUntil))})`), `effect-auth-proof-guard:complete:${input.continuationId}`)];
511
- return {
512
- receipt,
513
- statements: [
514
- yield* assertion(inspected.condition, `effect-auth-proof-guard:complete:${input.continuationId}`),
515
- yield* statement(database.update(mapping.continuation.table).set(updateValues([[mapping.continuation.consumed, true]])).where(and(eq(c.moduleId, input.moduleId), eq(c.continuationId, input.continuationId), eq(c.digest, input.continuationDigest), eq(c.consumed, false)))),
516
- yield* commandInsert(mapping, input.moduleId, input.continuationDigest, "complete", "completed", record.expiresAtMillis),
517
- ...postconditions
518
- ],
519
- postconditions,
520
- retryable: (cause) => isMappedConstraintConflict(mapping.isCommandConflict, cause) || isGuardFailure(cause, `effect-auth-proof-guard:complete:${input.continuationId}`)
521
- };
522
- });
523
- const makeProofPlans = (mapping) => {
524
- const run = (plan) => Effect.gen(function* () {
525
- if (!validConstraints(mapping)) return yield* unavailable();
526
- return yield* plan;
527
- });
528
- return {
529
- issue: (input, prepare) => run(Effect.gen(function* () {
530
- return yield* issuePlan(mapping, input, prepare);
531
- })),
532
- attempt: (input, prepare) => run(Effect.gen(function* () {
533
- return yield* attemptPlan(mapping, input, prepare);
534
- })),
535
- complete: (input, prepare) => run(Effect.gen(function* () {
536
- return yield* completionPlan(mapping, input, prepare);
537
- })),
538
- claimDelivery: (input, prepare) => Effect.gen(function* () {
539
- const database = yield* CurrentD1PlanningDatabase;
540
- return yield* run(Effect.gen(function* () {
541
- const journal = yield* CurrentCommitJournal;
542
- const row = (yield* readGeneration(mapping, input.moduleId, input.proofId))[0];
543
- const now = yield* readEngineNowMillis(mapping);
544
- const c = generationColumns(mapping);
545
- if (row === void 0) return {
546
- receipt: prepare({ _tag: "Declined" }, journal),
547
- statements: []
548
- };
549
- const expires = yield* mapping.decodeInstant(row[mapping.generation.expiresAt]);
550
- const claimDeadline = row[mapping.generation.claimDeadline] === null || row[mapping.generation.claimDeadline] === void 0 ? void 0 : yield* mapping.decodeInstant(row[mapping.generation.claimDeadline]);
551
- const retryAt = row[mapping.generation.retryAt] === null || row[mapping.generation.retryAt] === void 0 ? void 0 : yield* mapping.decodeInstant(row[mapping.generation.retryAt]);
552
- const state = row[mapping.generation.deliveryState];
553
- const expiredClaim = state === "claimed" && claimDeadline !== void 0 && claimDeadline <= now;
554
- const effectiveState = expiredClaim ? "ambiguous" : state;
555
- if (!(row[mapping.generation.version] === input.version && row[mapping.generation.deliveryId] === input.deliveryId && row[mapping.generation.state] === "active" && expires > now && Number(row[mapping.generation.sendCount]) < input.policy.maximumDeliveryAttempts && (effectiveState === "new" || effectiveState === "ambiguous" && input.allowAmbiguousRetry && (retryAt === void 0 || retryAt <= now)))) {
556
- const statements = expiredClaim ? [yield* statement(database.update(mapping.generation.table).set(updateValues([[mapping.generation.deliveryState, "ambiguous"]])).where(and(eq(c.moduleId, input.moduleId), eq(c.proofId, input.proofId), eq(c.deliveryState, "claimed"), lte(c.claimDeadline, mapping.d1.engineNow))))] : [];
557
- return {
558
- receipt: prepare({ _tag: "Declined" }, journal),
559
- statements
560
- };
561
- }
562
- const claimVersion = yield* allocateVersion(mapping);
563
- const decision = {
564
- _tag: "Claimed",
565
- claimVersion
566
- };
567
- const condition = and(eq(c.moduleId, input.moduleId), eq(c.proofId, input.proofId), eq(c.version, input.version), eq(c.deliveryId, input.deliveryId), eq(c.state, "active"), sql`${c.expiresAt} > ${mapping.d1.engineNow}`, sql`${c.sendCount} < ${input.policy.maximumDeliveryAttempts}`, effectiveState === "new" ? eq(c.deliveryState, "new") : and(eq(c.deliveryState, "ambiguous"), or(sql`${c.retryAt} is null`, lte(c.retryAt, mapping.d1.engineNow))));
568
- return {
569
- receipt: prepare(decision, journal),
570
- statements: [yield* assertion(sql`exists(select 1 from ${mapping.generation.table} where ${condition})`, `effect-auth-proof-guard:claim:${input.proofId}`), yield* statement(database.update(mapping.generation.table).set(updateValues([
571
- [mapping.generation.sendCount, Number(row[mapping.generation.sendCount]) + 1],
572
- [mapping.generation.deliveryState, "claimed"],
573
- [mapping.generation.claimVersion, claimVersion],
574
- [mapping.generation.claimDeadline, mapping.d1.engineInstantPlus(input.policy.deliveryClaimMillis)],
575
- [mapping.generation.retryAt, mapping.d1.engineInstantPlus(input.policy.deliveryRetryMillis)]
576
- ])).where(condition))],
577
- retryable: (cause) => isGuardFailure(cause, `effect-auth-proof-guard:claim:${input.proofId}`)
578
- };
579
- }));
580
- }),
581
- settleDelivery: (input, prepare) => Effect.gen(function* () {
582
- const database = yield* CurrentD1PlanningDatabase;
583
- return yield* run(Effect.gen(function* () {
584
- const journal = yield* CurrentCommitJournal;
585
- const row = (yield* readGeneration(mapping, input.moduleId, input.proofId))[0];
586
- const receipt = prepare(void 0, journal);
587
- if (row === void 0 || row[mapping.generation.version] !== input.version || row[mapping.generation.deliveryId] !== input.deliveryId || row[mapping.generation.claimVersion] !== input.claimVersion || row[mapping.generation.deliveryState] !== "claimed") return {
588
- receipt,
589
- statements: []
590
- };
591
- const c = generationColumns(mapping);
592
- const outcome = input.outcome;
593
- const state = outcome._tag === "Accepted" ? "accepted" : outcome._tag === "DefiniteFailure" ? "failed" : "ambiguous";
594
- const values = [[mapping.generation.deliveryState, state], [mapping.generation.claimDeadline, null]];
595
- if (outcome._tag === "Ambiguous") values.push([mapping.generation.retryAt, mapping.d1.engineInstantPlus(Number(row[mapping.generation.deliveryRetryMillis]))]);
596
- if (outcome._tag === "DefiniteFailure") values.push([mapping.generation.state, "cancelled"]);
597
- const condition = and(eq(c.moduleId, input.moduleId), eq(c.proofId, input.proofId), eq(c.version, input.version), eq(c.deliveryId, input.deliveryId), eq(c.claimVersion, input.claimVersion), eq(c.deliveryState, "claimed"));
598
- const statements = [yield* statement(database.update(mapping.generation.table).set(updateValues(values)).where(condition))];
599
- if (outcome._tag === "DefiniteFailure") {
600
- const sc = seriesColumns(mapping);
601
- statements.push(yield* statement(database.update(mapping.series.table).set(updateValues([[mapping.series.activeProofId, null]])).where(and(eq(sc.moduleId, input.moduleId), eq(sc.purpose, row[mapping.generation.purpose]), eq(sc.scopeKey, row[mapping.generation.seriesKey]), eq(sc.activeProofId, input.proofId), sql`exists(select 1 from ${mapping.generation.table} where ${c.moduleId} = ${sql.param(input.moduleId, c.moduleId)} and ${c.proofId} = ${sql.param(input.proofId, c.proofId)} and ${c.version} = ${sql.param(input.version, c.version)} and ${c.deliveryId} = ${sql.param(input.deliveryId, c.deliveryId)} and ${c.claimVersion} = ${sql.param(input.claimVersion, c.claimVersion)} and ${c.deliveryState} = 'failed' and ${c.state} = 'cancelled')`))));
602
- }
603
- return {
604
- receipt,
605
- statements
606
- };
607
- }));
608
- }),
609
- cancel: (input, prepare) => Effect.gen(function* () {
610
- const database = yield* CurrentD1PlanningDatabase;
611
- return yield* run(Effect.gen(function* () {
612
- const journal = yield* CurrentCommitJournal;
613
- const keys = mapping.scopeKeys({
614
- moduleId: input.moduleId,
615
- purpose: input.purpose,
616
- binding: input.binding
617
- });
618
- const current = yield* authority(mapping, input.moduleId, input.purpose, input.binding);
619
- const series = (yield* readSeries(mapping, input.moduleId, input.purpose, keys.series))[0];
620
- const receipt = prepare(void 0, journal);
621
- const active = series?.[mapping.series.activeProofId];
622
- if (!current.current || active === null || active === void 0) return {
623
- receipt,
624
- statements: []
625
- };
626
- const generation = (yield* readGeneration(mapping, input.moduleId, active))[0];
627
- const storedBinding = generation === void 0 ? void 0 : yield* mapping.generation.decodeBinding(generation);
628
- if (storedBinding === void 0 || !sameBinding(storedBinding, input.binding)) return {
629
- receipt,
630
- statements: []
631
- };
632
- const gc = generationColumns(mapping);
633
- const sc = seriesColumns(mapping);
634
- const marker = `effect-auth-proof-guard:cancel:${active}`;
635
- return {
636
- receipt,
637
- statements: [
638
- yield* assertion(and(current.condition, sql`exists(select 1 from ${mapping.series.table} where ${sc.moduleId} = ${sql.param(input.moduleId, sc.moduleId)} and ${sc.purpose} = ${sql.param(input.purpose, sc.purpose)} and ${sc.scopeKey} = ${sql.param(keys.series, sc.scopeKey)} and ${sc.activeProofId} = ${sql.param(active, sc.activeProofId)})`, sql`exists(select 1 from ${mapping.generation.table} where ${gc.moduleId} = ${sql.param(input.moduleId, gc.moduleId)} and ${gc.proofId} = ${sql.param(active, gc.proofId)} and ${gc.state} = 'active')`), marker),
639
- yield* statement(database.update(mapping.generation.table).set(updateValues([[mapping.generation.state, "cancelled"]])).where(and(eq(gc.moduleId, input.moduleId), eq(gc.proofId, active), eq(gc.state, "active")))),
640
- yield* statement(database.update(mapping.series.table).set(updateValues([[mapping.series.activeProofId, null]])).where(and(eq(sc.moduleId, input.moduleId), eq(sc.purpose, input.purpose), eq(sc.scopeKey, keys.series), eq(sc.activeProofId, active))))
641
- ],
642
- retryable: (cause) => isGuardFailure(cause, marker)
643
- };
644
- }));
645
- }),
646
- cleanup: (input, prepare) => Effect.gen(function* () {
647
- const database = yield* CurrentD1PlanningDatabase;
648
- return yield* run(Effect.gen(function* () {
649
- const journal = yield* CurrentCommitJournal;
650
- const now = yield* readEngineNowMillis(mapping);
651
- const nativeNow = mapping.encodeInstant(now);
652
- const gc = generationColumns(mapping);
653
- const cc = continuationColumns(mapping);
654
- const rc = requestColumns(mapping);
655
- const ac = abuseColumns(mapping);
656
- const fc = failureColumns(mapping);
657
- const mc = commandColumns(mapping);
658
- const sc = seriesColumns(mapping);
659
- const rsc = scopeColumns(mapping);
660
- let remaining = input.limit;
661
- let hasMore = false;
662
- const take = (effect) => effect.pipe(Effect.map((rows) => {
663
- if (rows.length > remaining) hasMore = true;
664
- const selected = rows.slice(0, remaining);
665
- remaining -= selected.length;
666
- return selected;
667
- }));
668
- const continuations = yield* take(database.select({ continuationId: cc.continuationId }).from(mapping.continuation.table).where(and(eq(cc.moduleId, input.moduleId), lte(cc.retentionUntil, nativeNow))).limit(remaining + 1));
669
- const generations = yield* take(database.select({ proofId: gc.proofId }).from(mapping.generation.table).where(and(eq(gc.moduleId, input.moduleId), lte(gc.retentionUntil, nativeNow))).limit(remaining + 1));
670
- const requests = yield* take(database.select({ requestId: rc.requestId }).from(mapping.request.table).where(and(eq(rc.moduleId, input.moduleId), lte(rc.retentionUntil, nativeNow))).limit(remaining + 1));
671
- const abuse = yield* take(database.select({
672
- action: ac.action,
673
- scopeKind: ac.scopeKind,
674
- scopeKey: ac.scopeKey,
675
- commandId: ac.commandId
676
- }).from(mapping.abuseEvent.table).where(and(eq(ac.moduleId, input.moduleId), lte(ac.retentionUntil, nativeNow))).limit(remaining + 1));
677
- const failures = yield* take(database.select({
678
- seriesKey: fc.seriesKey,
679
- commandId: fc.commandId
680
- }).from(mapping.failureEvent.table).where(and(eq(fc.moduleId, input.moduleId), lte(fc.retentionUntil, nativeNow))).limit(remaining + 1));
681
- const commands = yield* take(database.select({ commandId: mc.commandId }).from(mapping.command.table).where(and(eq(mc.moduleId, input.moduleId), lte(mc.retentionUntil, nativeNow))).limit(remaining + 1));
682
- const series = yield* take(database.select({
683
- purpose: sc.purpose,
684
- scopeKey: sc.scopeKey
685
- }).from(mapping.series.table).where(and(eq(sc.moduleId, input.moduleId), isNull(sc.activeProofId), notExists(database.select({ one: sql`1` }).from(mapping.generation.table).where(and(eq(gc.moduleId, sc.moduleId), eq(gc.purpose, sc.purpose), eq(gc.seriesKey, sc.scopeKey)))), notExists(database.select({ one: sql`1` }).from(mapping.failureEvent.table).where(and(eq(fc.moduleId, sc.moduleId), eq(fc.purpose, sc.purpose), eq(fc.seriesKey, sc.scopeKey)))))).limit(remaining + 1));
686
- const rateScopes = yield* take(database.select({
687
- purpose: rsc.purpose,
688
- action: rsc.action,
689
- scopeKind: rsc.scopeKind,
690
- scopeKey: rsc.scopeKey
691
- }).from(mapping.rateScope.table).where(and(eq(rsc.moduleId, input.moduleId), notExists(database.select({ one: sql`1` }).from(mapping.abuseEvent.table).where(and(eq(ac.moduleId, rsc.moduleId), eq(ac.purpose, rsc.purpose), eq(ac.action, rsc.action), eq(ac.scopeKind, rsc.scopeKind), eq(ac.scopeKey, rsc.scopeKey)))))).limit(remaining + 1));
692
- const marker = `effect-auth-proof-guard:cleanup:${input.moduleId}:${now}`;
693
- const statements = [];
694
- const guardedDelete = Effect.fn(function* (condition, query) {
695
- statements.push(yield* assertion(condition, marker), yield* statement(query));
696
- });
697
- for (const row of continuations) {
698
- const condition = and(eq(cc.moduleId, input.moduleId), eq(cc.continuationId, row.continuationId), lte(cc.retentionUntil, mapping.d1.engineNow));
699
- yield* guardedDelete(sql`exists(select 1 from ${mapping.continuation.table} where ${condition})`, database.delete(mapping.continuation.table).where(condition));
700
- }
701
- for (const row of generations) {
702
- const condition = and(eq(gc.moduleId, input.moduleId), eq(gc.proofId, row.proofId), lte(gc.retentionUntil, mapping.d1.engineNow));
703
- yield* guardedDelete(sql`exists(select 1 from ${mapping.generation.table} where ${condition})`, database.update(mapping.series.table).set(updateValues([[mapping.series.activeProofId, null]])).where(and(eq(sc.moduleId, input.moduleId), eq(sc.activeProofId, row.proofId))));
704
- statements.push(yield* statement(database.delete(mapping.generation.table).where(condition)));
705
- }
706
- for (const row of requests) {
707
- const condition = and(eq(rc.moduleId, input.moduleId), eq(rc.requestId, row.requestId), lte(rc.retentionUntil, mapping.d1.engineNow));
708
- yield* guardedDelete(sql`exists(select 1 from ${mapping.request.table} where ${condition})`, database.delete(mapping.request.table).where(condition));
709
- }
710
- for (const row of abuse) {
711
- const condition = and(eq(ac.moduleId, input.moduleId), eq(ac.action, row.action), eq(ac.scopeKind, row.scopeKind), eq(ac.scopeKey, row.scopeKey), eq(ac.commandId, row.commandId), lte(ac.retentionUntil, mapping.d1.engineNow));
712
- yield* guardedDelete(sql`exists(select 1 from ${mapping.abuseEvent.table} where ${condition})`, database.delete(mapping.abuseEvent.table).where(condition));
713
- }
714
- for (const row of failures) {
715
- const condition = and(eq(fc.moduleId, input.moduleId), eq(fc.seriesKey, row.seriesKey), eq(fc.commandId, row.commandId), lte(fc.retentionUntil, mapping.d1.engineNow));
716
- yield* guardedDelete(sql`exists(select 1 from ${mapping.failureEvent.table} where ${condition})`, database.delete(mapping.failureEvent.table).where(condition));
717
- }
718
- for (const row of commands) {
719
- const condition = and(eq(mc.moduleId, input.moduleId), eq(mc.commandId, row.commandId), lte(mc.retentionUntil, mapping.d1.engineNow));
720
- yield* guardedDelete(sql`exists(select 1 from ${mapping.command.table} where ${condition})`, database.delete(mapping.command.table).where(condition));
721
- }
722
- for (const row of series) {
723
- const condition = and(eq(sc.moduleId, input.moduleId), eq(sc.purpose, row.purpose), eq(sc.scopeKey, row.scopeKey), isNull(sc.activeProofId), notExists(database.select({ one: sql`1` }).from(mapping.generation.table).where(and(eq(gc.moduleId, sc.moduleId), eq(gc.purpose, sc.purpose), eq(gc.seriesKey, sc.scopeKey)))));
724
- yield* guardedDelete(sql`exists(select 1 from ${mapping.series.table} where ${condition})`, database.delete(mapping.series.table).where(condition));
725
- }
726
- for (const row of rateScopes) {
727
- const condition = and(eq(rsc.moduleId, input.moduleId), eq(rsc.purpose, row.purpose), eq(rsc.action, row.action), eq(rsc.scopeKind, row.scopeKind), eq(rsc.scopeKey, row.scopeKey), notExists(database.select({ one: sql`1` }).from(mapping.abuseEvent.table).where(and(eq(ac.moduleId, rsc.moduleId), eq(ac.purpose, rsc.purpose), eq(ac.action, rsc.action), eq(ac.scopeKind, rsc.scopeKind), eq(ac.scopeKey, rsc.scopeKey)))));
728
- yield* guardedDelete(sql`exists(select 1 from ${mapping.rateScope.table} where ${condition})`, database.delete(mapping.rateScope.table).where(condition));
729
- }
730
- hasMore ||= generations.length > 0 || failures.length > 0 || abuse.length > 0;
731
- return {
732
- receipt: prepare({
733
- removed: input.limit - remaining,
734
- hasMore
735
- }, journal),
736
- statements,
737
- retryable: (cause) => isGuardFailure(cause, marker)
738
- };
739
- }));
740
- })
741
- };
742
- };
743
- const makeD1ProofPersistenceServices = Effect.fnUntraced(function* (mapping) {
744
- const database = yield* Database;
745
- yield* validateDrizzleStorage(mapping).pipe(Effect.provideServiceEffect(NativeDatabase, nativeDatabase(Database)), Effect.mapError(unavailable));
746
- const hooks = yield* LifecycleHooks;
747
- const plans = makeProofPlans(mapping);
748
- const run = (plan) => Effect.gen(function* () {
749
- if (yield* hasCommitScope) return yield* unavailable();
750
- return yield* executeStandalone(plan, 2);
751
- }).pipe(Effect.provideService(CurrentD1PlanningDatabase, database), Effect.provideService(LifecycleHooks, hooks));
752
- return { proofPersistence: {
753
- issue: (input, prepare) => run(plans.issue(input, prepare)).pipe(translateIssueFailure),
754
- attempt: (input, prepare) => run(plans.attempt(input, prepare)).pipe(translateFailure),
755
- complete: (input, prepare) => run(plans.complete(input, prepare)).pipe(translateFailure),
756
- claimDelivery: (input, prepare) => run(plans.claimDelivery(input, prepare)).pipe(translateFailure),
757
- settleDelivery: (input, prepare) => run(plans.settleDelivery(input, prepare)).pipe(translateFailure),
758
- cancel: (input, prepare) => run(plans.cancel(input, prepare)).pipe(translateFailure),
759
- cleanup: (input, prepare) => run(plans.cleanup(input, prepare)).pipe(translateFailure)
760
- } };
761
- });
762
- /**
763
- * Owns one proof transition plus application statements in one D1 batch. It
764
- * never replays the owner effect. A reserved guard or named race becomes
765
- * ProofUnavailable so the caller can retry the entire command with fresh secrets.
766
- */
767
- function coordinateD1ProofPersistence(acquire, options, body) {
768
- return Effect.flatMap(nativeDatabase(acquire), (database) => Effect.gen(function* () {
769
- yield* validateDrizzleStorage(options.mapping).pipe(Effect.mapError(unavailable));
770
- const hooks = yield* LifecycleHooks;
771
- if (yield* hasCommitScope) return yield* unavailable();
772
- return (yield* coordinateCommit(() => Effect.gen(function* () {
773
- const statements = [];
774
- let mutation;
775
- const nativeCollector = D1BatchStatements.of({ append: (statement) => Effect.sync(() => statements.push(statement)) });
776
- const owner = yield* makeD1Owner(unavailable()).pipe(Effect.provideService(D1BatchStatements, nativeCollector));
777
- const plans = makeProofPlans(options.mapping);
778
- const run = (plan) => coordinateCommit(() => Effect.gen(function* () {
779
- const journal = yield* CurrentCommitJournal;
780
- const planned = yield* plan;
781
- yield* owner.check;
782
- if (mutation !== void 0) return yield* unavailable();
783
- const guarded = {
784
- ...planned,
785
- journalGuard: journal.prepare(void 0)
786
- };
787
- mutation = guarded;
788
- statements.push(...guarded.statements);
789
- return guarded.receipt;
790
- }), { mode: "batch" }).pipe(Effect.map((result) => result.value), Effect.provideService(CurrentD1PlanningDatabase, database), Effect.provideService(LifecycleHooks, hooks));
791
- const provided = Context.make(ProofPersistence, {
792
- issue: (input, prepare) => owner.run(run(plans.issue(input, prepare)).pipe(translateIssueFailure)),
793
- attempt: (input, prepare) => owner.run(run(plans.attempt(input, prepare)).pipe(translateFailure)),
794
- complete: (input, prepare) => owner.run(run(plans.complete(input, prepare)).pipe(translateFailure)),
795
- claimDelivery: (input, prepare) => owner.run(run(plans.claimDelivery(input, prepare)).pipe(translateFailure)),
796
- settleDelivery: (input, prepare) => owner.run(run(plans.settleDelivery(input, prepare)).pipe(translateFailure)),
797
- cancel: (input, prepare) => owner.run(run(plans.cancel(input, prepare)).pipe(translateFailure)),
798
- cleanup: (input, prepare) => owner.run(run(plans.cleanup(input, prepare)).pipe(translateFailure))
799
- }).pipe(Context.add(D1BatchStatements, owner.collector));
800
- const value = yield* owner.close(Effect.provideContext(body, provided));
801
- if (mutation?.journalGuard !== void 0) {
802
- const status = yield* Effect.result(mutation.journalGuard.read);
803
- if (status._tag === "Success" || status.failure._tag !== "CommitPending") return yield* unavailable();
804
- }
805
- yield* database.$client.batch(statements).pipe(Effect.catchCause((cause) => Effect.failCause(Cause.map(cause, (error) => everyFailureMatches(cause, mutation?.retryable) ? unavailable() : error))), translateFailure);
806
- return value;
807
- }), { mode: "batch" }).pipe(Effect.provideService(LifecycleHooks, hooks))).value;
808
- }).pipe(Effect.provideService(NativeDatabase, database)));
809
- }
810
- /** Private compiler seam for a future same-owner D1 password-reset batch. */
811
- const compileD1ProofCompletionPlan = Effect.fn("Drizzle.compileD1ProofCompletionPlan")(function* (mapping, plan, protectedMutation, project) {
812
- const planned = yield* completionPlan(mapping, plan.input, (decision, activeJournal) => plan.prepare(decision, activeJournal, project));
813
- if (planned.statements.length === 0) return planned;
814
- const [freshGuard, ...completionStatements] = planned.statements;
815
- const marker = `effect-auth-proof-guard:protected:${plan.input.continuationId}`;
816
- return {
817
- receipt: planned.receipt,
818
- statements: [
819
- freshGuard,
820
- ...protectedMutation.statements,
821
- yield* assertion(protectedMutation.appliedCondition, marker),
822
- ...completionStatements
823
- ],
824
- postconditions: [yield* assertion(protectedMutation.appliedCondition, marker), ...planned.postconditions ?? []]
825
- };
826
- });
827
- const translateFailure = (effect) => reportPersistenceFailure(effect, (error) => Schema.is(ProofUnavailable)(error) || Schema.is(HookConfigurationError)(error)).pipe(Effect.catchCause((cause) => Effect.failCause(Cause.map(cause, () => unavailable()))));
828
- const translateIssueFailure = (effect) => reportPersistenceFailure(effect, (error) => Schema.is(ProofUnavailable)(error) || Schema.is(ProofRequestConflict)(error) || Schema.is(HookConfigurationError)(error)).pipe(Effect.catchCause((cause) => Effect.failCause(Cause.map(cause, (error) => Schema.is(ProofRequestConflict)(error) ? error : unavailable()))));
829
- const executeStandalone = (plan, retries = 2) => Effect.suspend(() => {
830
- let retryable;
831
- return coordinateCommit(() => Effect.gen(function* () {
832
- const database = yield* CurrentD1PlanningDatabase;
833
- const planned = yield* plan;
834
- retryable = planned.retryable;
835
- yield* database.$client.batch(planned.statements);
836
- return planned.receipt;
837
- }), { mode: "batch" }).pipe(Effect.map((result) => result.value)).pipe(Effect.catchCause((cause) => retries > 0 && everyFailureMatches(cause, retryable) ? executeStandalone(plan, retries - 1) : Effect.failCause(cause)));
838
- });
839
- //#endregion
840
- export { checkD1ProofCompletion, compileD1ProofCompletionPlan, coordinateD1ProofPersistence, makeD1ProofPersistenceServices };
841
-
842
- //# sourceMappingURL=d1-proofs.mjs.map