@noy-db/hub 0.6.0-pre.2 → 0.6.0-pre.20

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 (490) hide show
  1. package/codemods/0.4.0-pre.json +699 -0
  2. package/codemods/0.6.0-pre.json +211 -0
  3. package/dist/api-Z5VHH24A.js +20 -0
  4. package/dist/attestation/index.js +19 -19
  5. package/dist/{backup-YYBE5RPC.js → backup-K62BFMYK.js} +36 -18
  6. package/dist/backup-K62BFMYK.js.map +1 -0
  7. package/dist/blobs/index.js +13 -13
  8. package/dist/broker/index.js +12 -12
  9. package/dist/cargo/index.js +33 -33
  10. package/dist/{chunk-FDX7OWWI.js → chunk-2E2MKBMI.js} +2 -2
  11. package/dist/{chunk-VOQW5LAM.js → chunk-2IK6AC6A.js} +102 -71
  12. package/dist/chunk-2IK6AC6A.js.map +1 -0
  13. package/dist/{chunk-EDXAQ6JI.js → chunk-32O2N2CH.js} +87 -34
  14. package/dist/chunk-32O2N2CH.js.map +1 -0
  15. package/dist/{chunk-W5W6KHN2.js → chunk-3Y4OFWQJ.js} +1 -1
  16. package/dist/chunk-3Y4OFWQJ.js.map +1 -0
  17. package/dist/{chunk-7G6VDWXB.js → chunk-437FDIHO.js} +3 -3
  18. package/dist/chunk-437FDIHO.js.map +1 -0
  19. package/dist/{chunk-3FSX6LDG.js → chunk-47ZFULEZ.js} +8 -3
  20. package/dist/{chunk-3FSX6LDG.js.map → chunk-47ZFULEZ.js.map} +1 -1
  21. package/dist/{chunk-ZJADGNYF.js → chunk-4AOERLTV.js} +1 -1
  22. package/dist/chunk-4AOERLTV.js.map +1 -0
  23. package/dist/{chunk-MWKDOHEF.js → chunk-4HVTRHSA.js} +17 -10
  24. package/dist/chunk-4HVTRHSA.js.map +1 -0
  25. package/dist/{chunk-V5KYPBUR.js → chunk-5BS6IQZZ.js} +11 -14
  26. package/dist/chunk-5BS6IQZZ.js.map +1 -0
  27. package/dist/{chunk-LWSJG3LI.js → chunk-5EJQNA26.js} +7 -3
  28. package/dist/chunk-5EJQNA26.js.map +1 -0
  29. package/dist/{chunk-7F4DBNSP.js → chunk-5J5TTSGW.js} +3 -3
  30. package/dist/{chunk-BTVYJWSN.js → chunk-5JT4Y5UE.js} +10 -10
  31. package/dist/{chunk-C2OOEM57.js → chunk-6S466CMQ.js} +92 -35
  32. package/dist/chunk-6S466CMQ.js.map +1 -0
  33. package/dist/{chunk-PY7CI6L5.js → chunk-6TXUVKPG.js} +516 -263
  34. package/dist/chunk-6TXUVKPG.js.map +1 -0
  35. package/dist/{chunk-7NXHMW6Y.js → chunk-7RCZ436O.js} +2 -2
  36. package/dist/{chunk-DG27IUVI.js → chunk-A3NTKHDB.js} +2 -2
  37. package/dist/{chunk-CCZJJ4I2.js → chunk-A4K5GLE6.js} +4 -4
  38. package/dist/{chunk-CEJWMBXO.js → chunk-APV42WPR.js} +2 -2
  39. package/dist/{chunk-4HDYQL3J.js → chunk-AQF7JSQR.js} +2 -2
  40. package/dist/{chunk-KUDZVJKQ.js → chunk-BP4I7IBK.js} +2 -2
  41. package/dist/{chunk-4UVDI4XE.js → chunk-BTNKPDZM.js} +4 -4
  42. package/dist/{chunk-HVQGCKY4.js → chunk-C7WJNVJG.js} +2 -2
  43. package/dist/{chunk-WYZ5MYUA.js → chunk-CV7WXCZD.js} +44 -42
  44. package/dist/chunk-CV7WXCZD.js.map +1 -0
  45. package/dist/{chunk-KCQX65FU.js → chunk-CVYXIN5B.js} +3 -3
  46. package/dist/{chunk-VN45YLWM.js → chunk-D5UDZANO.js} +255 -132
  47. package/dist/chunk-D5UDZANO.js.map +1 -0
  48. package/dist/{chunk-AR2JDFAE.js → chunk-DJ23QZIN.js} +2 -2
  49. package/dist/{chunk-PJNTR2NV.js → chunk-DKYEVHZH.js} +7 -10
  50. package/dist/chunk-DKYEVHZH.js.map +1 -0
  51. package/dist/{chunk-SZ2K3MHL.js → chunk-DYASJSKI.js} +8 -11
  52. package/dist/{chunk-SZ2K3MHL.js.map → chunk-DYASJSKI.js.map} +1 -1
  53. package/dist/{chunk-G5APARUV.js → chunk-E6VDPBE3.js} +13 -15
  54. package/dist/chunk-E6VDPBE3.js.map +1 -0
  55. package/dist/{chunk-A67356IR.js → chunk-EG6AQBYW.js} +33 -8
  56. package/dist/chunk-EG6AQBYW.js.map +1 -0
  57. package/dist/{chunk-PVU7LW5L.js → chunk-EJIVFOOQ.js} +6 -6
  58. package/dist/{chunk-VRA4Q7DA.js → chunk-F5AJZC3U.js} +35 -47
  59. package/dist/chunk-F5AJZC3U.js.map +1 -0
  60. package/dist/{chunk-VMCCGUQB.js → chunk-GDGTIWB4.js} +2 -2
  61. package/dist/{chunk-FUHKW252.js → chunk-GILI76SU.js} +2 -2
  62. package/dist/{chunk-35EBKWQU.js → chunk-GT72D4FO.js} +4 -4
  63. package/dist/{chunk-PRDRGL73.js → chunk-GYUCRDAU.js} +17 -14
  64. package/dist/chunk-GYUCRDAU.js.map +1 -0
  65. package/dist/{chunk-JRCYZEHU.js → chunk-HGJC7I5F.js} +2 -2
  66. package/dist/{chunk-TOAIYQJR.js → chunk-HJRTFXAA.js} +7 -10
  67. package/dist/chunk-HJRTFXAA.js.map +1 -0
  68. package/dist/chunk-HK67PX4J.js +27 -0
  69. package/dist/chunk-HK67PX4J.js.map +1 -0
  70. package/dist/{chunk-JXIDGFKS.js → chunk-HTHRCGWP.js} +4 -2
  71. package/dist/chunk-HTHRCGWP.js.map +1 -0
  72. package/dist/{chunk-AHLJSVRL.js → chunk-HTMQBBF3.js} +5 -7
  73. package/dist/chunk-HTMQBBF3.js.map +1 -0
  74. package/dist/{chunk-ZNACADFG.js → chunk-ICCRAPWD.js} +4 -4
  75. package/dist/chunk-ICCRAPWD.js.map +1 -0
  76. package/dist/{chunk-66W5OOCX.js → chunk-IOURTXTM.js} +52 -65
  77. package/dist/chunk-IOURTXTM.js.map +1 -0
  78. package/dist/{chunk-MZ5ZFO2D.js → chunk-IPDS2TYW.js} +84 -112
  79. package/dist/chunk-IPDS2TYW.js.map +1 -0
  80. package/dist/{chunk-UIBGXRDD.js → chunk-JHO6FGZX.js} +25 -31
  81. package/dist/chunk-JHO6FGZX.js.map +1 -0
  82. package/dist/{chunk-YAWK6AWF.js → chunk-JIF3IBRK.js} +2 -2
  83. package/dist/{chunk-HNHCQ556.js → chunk-KBOPY6W2.js} +2 -2
  84. package/dist/{chunk-UHXCLPGC.js → chunk-KDX6VEYV.js} +2 -2
  85. package/dist/chunk-KDX6VEYV.js.map +1 -0
  86. package/dist/{chunk-W3TVWF6N.js → chunk-KM6YR5XF.js} +2 -2
  87. package/dist/{chunk-3737A6EA.js → chunk-KUXTWVAR.js} +75 -18
  88. package/dist/chunk-KUXTWVAR.js.map +1 -0
  89. package/dist/chunk-L2XQ776M.js +123 -0
  90. package/dist/chunk-L2XQ776M.js.map +1 -0
  91. package/dist/{chunk-E6427JU2.js → chunk-L6FSZFG7.js} +18 -2
  92. package/dist/chunk-L6FSZFG7.js.map +1 -0
  93. package/dist/{chunk-5PR33AC4.js → chunk-M4IKEOJS.js} +20 -17
  94. package/dist/chunk-M4IKEOJS.js.map +1 -0
  95. package/dist/{chunk-6HFM7EIT.js → chunk-MNMYHZVU.js} +2 -2
  96. package/dist/{chunk-NIVEDYJZ.js → chunk-MNUTPZRQ.js} +31 -49
  97. package/dist/chunk-MNUTPZRQ.js.map +1 -0
  98. package/dist/{chunk-VV4NSB7P.js → chunk-MQXYR65M.js} +15 -24
  99. package/dist/chunk-MQXYR65M.js.map +1 -0
  100. package/dist/{chunk-QD724WDJ.js → chunk-N2HKBESK.js} +4 -4
  101. package/dist/{chunk-Z45YRGFO.js → chunk-N7YAQKAO.js} +2 -2
  102. package/dist/{chunk-DMQCLZ4Z.js → chunk-NH2MST6J.js} +2 -2
  103. package/dist/{chunk-TAGFGKHP.js → chunk-NRNTXBHT.js} +7 -10
  104. package/dist/chunk-NRNTXBHT.js.map +1 -0
  105. package/dist/{chunk-I6SDX7WX.js → chunk-NYSD43OE.js} +16 -22
  106. package/dist/chunk-NYSD43OE.js.map +1 -0
  107. package/dist/{chunk-I4F6PKUK.js → chunk-ODVIFBAQ.js} +16 -17
  108. package/dist/chunk-ODVIFBAQ.js.map +1 -0
  109. package/dist/{chunk-26JMGSSC.js → chunk-OIIAXFKM.js} +4 -4
  110. package/dist/chunk-OIIAXFKM.js.map +1 -0
  111. package/dist/{chunk-HXGUIPQB.js → chunk-OQLYMBJI.js} +3 -3
  112. package/dist/{chunk-RKKORO4M.js → chunk-OWGEHDT2.js} +10 -10
  113. package/dist/chunk-OWGEHDT2.js.map +1 -0
  114. package/dist/{chunk-HNGSV2YC.js → chunk-P7L3OQLL.js} +25 -10
  115. package/dist/chunk-P7L3OQLL.js.map +1 -0
  116. package/dist/{chunk-MSWYQLMQ.js → chunk-PG6PFMDC.js} +2 -2
  117. package/dist/{chunk-E7OBCBXS.js → chunk-PNAIDIP7.js} +13 -16
  118. package/dist/chunk-PNAIDIP7.js.map +1 -0
  119. package/dist/{chunk-GLKDWWNO.js → chunk-PZSS7MUM.js} +16 -14
  120. package/dist/chunk-PZSS7MUM.js.map +1 -0
  121. package/dist/{chunk-WKPJXWKR.js → chunk-QPIUFRUC.js} +3 -3
  122. package/dist/{chunk-JIUVJ4M7.js → chunk-REL4OLWW.js} +2 -2
  123. package/dist/{chunk-ERB6NDDW.js → chunk-RKDH6L53.js} +134 -33
  124. package/dist/chunk-RKDH6L53.js.map +1 -0
  125. package/dist/{chunk-VW6ZZGCG.js → chunk-RNSC2ARR.js} +3 -3
  126. package/dist/{chunk-WLYIROCJ.js → chunk-RORE2GX2.js} +2 -2
  127. package/dist/{chunk-TDJPS3T2.js → chunk-RQY5UWEL.js} +24 -19
  128. package/dist/chunk-RQY5UWEL.js.map +1 -0
  129. package/dist/{chunk-7TSYBD3E.js → chunk-RSFG7XHM.js} +2 -2
  130. package/dist/{chunk-FAXZQ5UF.js → chunk-S55DBWRC.js} +2 -2
  131. package/dist/{chunk-WHJKIZS7.js → chunk-SA77BQ7F.js} +27 -149
  132. package/dist/chunk-SA77BQ7F.js.map +1 -0
  133. package/dist/{chunk-747LRSOO.js → chunk-SFD2LL7G.js} +2 -2
  134. package/dist/{chunk-P7OG2ETF.js → chunk-SG3OQCRG.js} +3 -3
  135. package/dist/{chunk-55LKVALY.js → chunk-T7IR4N2S.js} +1 -3
  136. package/dist/chunk-T7IR4N2S.js.map +1 -0
  137. package/dist/{chunk-EP7VPR7Y.js → chunk-TC6MBEGH.js} +11 -8
  138. package/dist/chunk-TC6MBEGH.js.map +1 -0
  139. package/dist/{chunk-HFQ6LGIO.js → chunk-TENLCGYD.js} +12 -10
  140. package/dist/{chunk-HFQ6LGIO.js.map → chunk-TENLCGYD.js.map} +1 -1
  141. package/dist/{chunk-WQDTCJ6W.js → chunk-VEX2BQVX.js} +3 -3
  142. package/dist/{chunk-7VHY5E3X.js → chunk-VH2W6BOG.js} +7 -7
  143. package/dist/chunk-VHVMJWM6.js +201 -0
  144. package/dist/chunk-VHVMJWM6.js.map +1 -0
  145. package/dist/{chunk-VCETL77O.js → chunk-VJ4B3ZXY.js} +27 -7
  146. package/dist/chunk-VJ4B3ZXY.js.map +1 -0
  147. package/dist/{chunk-OF3L2SD6.js → chunk-W6NFONOV.js} +2 -2
  148. package/dist/{chunk-NJDQ4YSV.js → chunk-WBNXZU42.js} +4 -4
  149. package/dist/{chunk-FNSMZQS4.js → chunk-WKD5ESK4.js} +2 -2
  150. package/dist/{chunk-NKH7GSIH.js → chunk-XGQGWZ6D.js} +4 -4
  151. package/dist/chunk-YOT7D63X.js +190 -0
  152. package/dist/chunk-YOT7D63X.js.map +1 -0
  153. package/dist/{chunk-4MC5JRRX.js → chunk-YVTADFTC.js} +14 -15
  154. package/dist/chunk-YVTADFTC.js.map +1 -0
  155. package/dist/{chunk-GASWQ3XG.js → chunk-ZBDWKPBW.js} +15 -16
  156. package/dist/chunk-ZBDWKPBW.js.map +1 -0
  157. package/dist/{chunk-52QYGZHH.js → chunk-ZPMXYPBR.js} +2 -2
  158. package/dist/chunk-ZPMXYPBR.js.map +1 -0
  159. package/dist/chunk-ZVAFJQZB.js +66 -0
  160. package/dist/chunk-ZVAFJQZB.js.map +1 -0
  161. package/dist/{chunk-VJFMXYKP.js → chunk-ZWKF3CD3.js} +2 -2
  162. package/dist/{chunk-I4ZAO7F7.js → chunk-ZXW3X3DQ.js} +7 -11
  163. package/dist/chunk-ZXW3X3DQ.js.map +1 -0
  164. package/dist/classified/index.js +5 -5
  165. package/dist/{classified-marker-FTOX7Q5L.js → classified-marker-PMDG3O36.js} +3 -3
  166. package/dist/collection-facade-ZJK5EB33.js +45 -0
  167. package/dist/{computed-6G5M3UPH.js → computed-UHCBRILW.js} +3 -3
  168. package/dist/consent/index.js +10 -10
  169. package/dist/cover/index.js +10 -3
  170. package/dist/custody/index.js +11 -11
  171. package/dist/{dead-filter-ENRIOQIE.js → dead-filter-777VWDER.js} +2 -2
  172. package/dist/debug/index.js +1 -1
  173. package/dist/{delegation-SSEPLXXO.js → delegation-4R5DU23X.js} +24 -23
  174. package/dist/delegation-4R5DU23X.js.map +1 -0
  175. package/dist/derivations/index.js +12 -12
  176. package/dist/derive-3WAS2G5T.js +22 -0
  177. package/dist/directory/index.js +10 -10
  178. package/dist/{dispatch-BDVGYC6X.js → dispatch-3EN6YCCS.js} +18 -18
  179. package/dist/{dispatch-RE74SH6L.js → dispatch-ASL257KG.js} +5 -5
  180. package/dist/{enclave-52VUXNRL.js → enclave-ZJS5R5RH.js} +25 -9
  181. package/dist/executor-GPM6DNWV.js +9 -0
  182. package/dist/executor-LJSMZ4IB.js +9 -0
  183. package/dist/executor-SHUVRZUJ.js +29 -0
  184. package/dist/export-accessible-GNY6DC6U.js +23 -0
  185. package/dist/extract-partition-BG3AF4NZ.js +38 -0
  186. package/dist/{fanout-sidecar-DTBIDOWF.js → fanout-sidecar-TFPWDOME.js} +18 -27
  187. package/dist/fanout-sidecar-TFPWDOME.js.map +1 -0
  188. package/dist/find-KX6OKHDP.js +11 -0
  189. package/dist/forget/index.js +9 -9
  190. package/dist/guards/index.js +4 -4
  191. package/dist/history/index.js +23 -20
  192. package/dist/history/index.js.map +1 -1
  193. package/dist/i18n/index.js +14 -14
  194. package/dist/index.d.ts +32 -15
  195. package/dist/index.js +183 -191
  196. package/dist/index.js.map +1 -1
  197. package/dist/indexing/index.js +2 -2
  198. package/dist/introspection/index.js +11 -11
  199. package/dist/issue-PAUM7NCX.js +19 -0
  200. package/dist/kernel/enclave/crypto.d.ts +24 -4
  201. package/dist/kernel/enclave/index.d.ts +8 -2
  202. package/dist/kernel/enclave/record-aad.d.ts +131 -0
  203. package/dist/kernel/enclave/record-envelope.d.ts +76 -0
  204. package/dist/kernel/enclave/record-keys/envelope-body.d.ts +34 -2
  205. package/dist/kernel/enclave/record-keys/lifecycle.d.ts +22 -5
  206. package/dist/kernel/enclave/record-keys/record-codec.d.ts +47 -14
  207. package/dist/kernel/enclave/record-keys/rekey.d.ts +68 -0
  208. package/dist/kernel/enclave/record-keys/tombstone.d.ts +3 -2
  209. package/dist/kernel/errors.d.ts +23 -11
  210. package/dist/kernel/merge-authority.d.ts +25 -0
  211. package/dist/kernel/noydb.d.ts +9 -3
  212. package/dist/kernel/query/builder.d.ts +15 -2
  213. package/dist/kernel/query/join.d.ts +27 -0
  214. package/dist/kernel/sync-policy.d.ts +0 -2
  215. package/dist/kernel/tier-visibility.d.ts +15 -0
  216. package/dist/kernel/types.d.ts +125 -6
  217. package/dist/kernel/vault.d.ts +21 -17
  218. package/dist/kernel/via/index.d.ts +11 -2
  219. package/dist/{ledger-4WJL66BW.js → ledger-62CEPRPX.js} +11 -11
  220. package/dist/liberate-I6AOLWXW.js +24 -0
  221. package/dist/{link-set-N4ZPV6E6.js → link-set-ZRYNUHN3.js} +11 -11
  222. package/dist/{managed-secret-OTHS64IF.js → managed-secret-T2WB4O47.js} +11 -3
  223. package/dist/materialized-views/index.js +22 -21
  224. package/dist/money/index.js +12 -8
  225. package/dist/noydb-SS6EN7TK.js +84 -0
  226. package/dist/overlay-views/index.js +4 -4
  227. package/dist/periods/index.js +22 -12
  228. package/dist/pod/index.js +75 -86
  229. package/dist/pod-handle-UPLXOGIK.js +41 -0
  230. package/dist/pod-handle-UPLXOGIK.js.map +1 -0
  231. package/dist/policy/index.js +11 -4
  232. package/dist/port/to/index.d.ts +4 -4
  233. package/dist/port/to/locator.d.ts +54 -8
  234. package/dist/port/with/i18n-strategy.d.ts +4 -1
  235. package/dist/port/with/lookup-strategy.d.ts +4 -1
  236. package/dist/port/with/merge-authority.d.ts +52 -0
  237. package/dist/port/with/service-bus.d.ts +0 -4
  238. package/dist/port/with/strategies.d.ts +2 -0
  239. package/dist/portability/index.js +8 -8
  240. package/dist/{post-register-ZAG2CAIY.js → post-register-J4DEVNXK.js} +6 -6
  241. package/dist/query/index.js +3 -3
  242. package/dist/reduce/index.js +4 -4
  243. package/dist/register-UPD4GKBC.js +32 -0
  244. package/dist/registry-7KX2HWFS.js +18 -0
  245. package/dist/registry-PKYYEHEW.js +9 -0
  246. package/dist/registry-XHCYMD34.js +19 -0
  247. package/dist/registry-XIRTZHPC.js +9 -0
  248. package/dist/request-withdrawal-XZSESWZV.js +31 -0
  249. package/dist/{reveal-CMOJY4VO.js → reveal-525XWQU2.js} +6 -6
  250. package/dist/revoke-QI7YHQ2B.js +24 -0
  251. package/dist/satellites/index.js +1 -1
  252. package/dist/schema-update/index.js +2 -2
  253. package/dist/sealed-record/index.js +20 -13
  254. package/dist/sealed-record/index.js.map +1 -1
  255. package/dist/search/index.js +4 -4
  256. package/dist/{seed-UK4QRIUN.js → seed-SGIF3EN4.js} +19 -22
  257. package/dist/seed-SGIF3EN4.js.map +1 -0
  258. package/dist/sequence/index.js +9 -9
  259. package/dist/session/index.js +10 -10
  260. package/dist/shadow/index.js +2 -2
  261. package/dist/share-link/index.js +1 -1
  262. package/dist/signer-BZWDPGGN.js +25 -0
  263. package/dist/snapshots/index.js +10 -10
  264. package/dist/snapshots/index.js.map +1 -1
  265. package/dist/{stale-ZWXSOWJI.js → stale-PQYPVCER.js} +10 -10
  266. package/dist/storage-MJHKNQRO.js +23 -0
  267. package/dist/{store-coordination-provider-PB6QZ57W.js → store-coordination-provider-TFHZLKHG.js} +18 -12
  268. package/dist/store-coordination-provider-TFHZLKHG.js.map +1 -0
  269. package/dist/sync/index.js +11 -11
  270. package/dist/team/index.js +15 -14
  271. package/dist/tiers/index.js +11 -10
  272. package/dist/to/index.js +17 -9
  273. package/dist/to/index.js.map +1 -1
  274. package/dist/transactions/index.js +4 -4
  275. package/dist/{ulid-PTAIMDG4.js → ulid-VQW6ERQN.js} +2 -2
  276. package/dist/util/index.js +1 -1
  277. package/dist/vault-head/index.js +115 -0
  278. package/dist/vault-head/index.js.map +1 -0
  279. package/dist/{verify-RO5RTZOJ.js → verify-J6DEOXP3.js} +5 -5
  280. package/dist/via/lookup/handle.d.ts +4 -1
  281. package/dist/via/money/exact.d.ts +44 -0
  282. package/dist/via/money/index.d.ts +2 -0
  283. package/dist/via/money/normalize.d.ts +20 -0
  284. package/dist/walk-BX4NSB5L.js +21 -0
  285. package/dist/with-audit/guards/immutable-guard.d.ts +14 -0
  286. package/dist/with-audit/periods/active.d.ts +28 -1
  287. package/dist/with-audit/periods/index.d.ts +4 -2
  288. package/dist/with-audit/periods/periods.d.ts +161 -6
  289. package/dist/with-audit/periods/strategy.d.ts +14 -5
  290. package/dist/with-audit/periods/vault-facade.d.ts +89 -10
  291. package/dist/with-audit/periods/window.d.ts +10 -0
  292. package/dist/with-audit/sealed-record/index.d.ts +13 -0
  293. package/dist/with-audit/tiers/index.d.ts +17 -2
  294. package/dist/with-cargo/adopt-partition.d.ts +1 -1
  295. package/dist/with-cargo/extract-partition.d.ts +1 -1
  296. package/dist/with-cargo/index.d.ts +2 -2
  297. package/dist/with-commit/history/history.d.ts +26 -0
  298. package/dist/with-commit/history/index.d.ts +2 -1
  299. package/dist/with-commit/history/ledger/store.d.ts +7 -1
  300. package/dist/with-commit/history/strategy.d.ts +11 -1
  301. package/dist/with-commit/numbering/index.d.ts +0 -5
  302. package/dist/with-commit/vault-head/active.d.ts +2 -0
  303. package/dist/with-commit/vault-head/head.d.ts +28 -0
  304. package/dist/with-commit/vault-head/index.d.ts +10 -0
  305. package/dist/with-commit/vault-head/strategy.d.ts +127 -0
  306. package/dist/with-commit/vault-head/verify.d.ts +90 -0
  307. package/dist/with-formula/materialized-views/types.d.ts +52 -0
  308. package/dist/with-party/directory/cover/storage.d.ts +0 -8
  309. package/dist/with-party/directory/storage.d.ts +0 -11
  310. package/dist/with-party/directory/visibility.d.ts +0 -21
  311. package/dist/with-party/policy/storage.d.ts +0 -10
  312. package/dist/with-party/team/index.d.ts +1 -1
  313. package/dist/with-party/team/keyring.d.ts +17 -3
  314. package/dist/with-party/team/tiers.d.ts +2 -1
  315. package/dist/with-pod/format.d.ts +10 -12
  316. package/dist/with-pod/index.d.ts +10 -10
  317. package/dist/with-pod/open.d.ts +2 -2
  318. package/dist/with-pod/pod-handle.d.ts +19 -0
  319. package/dist/with-pod/pod-store.d.ts +0 -8
  320. package/dist/with-pod/{bundle.d.ts → pod.d.ts} +26 -19
  321. package/dist/with-pod/ulid.d.ts +1 -1
  322. package/dist/with-shape/introspection/index.d.ts +1 -0
  323. package/dist/with-sync/engine.d.ts +54 -5
  324. package/dist/with-sync/strategy.d.ts +3 -0
  325. package/dist/withdraw-accessible-K4CPMH4C.js +28 -0
  326. package/package.json +12 -5
  327. package/dist/api-WVY3H3YH.js +0 -20
  328. package/dist/backup-YYBE5RPC.js.map +0 -1
  329. package/dist/bundle-handle-JEUWU2SJ.js +0 -36
  330. package/dist/bundle-handle-JEUWU2SJ.js.map +0 -1
  331. package/dist/chunk-26JMGSSC.js.map +0 -1
  332. package/dist/chunk-3737A6EA.js.map +0 -1
  333. package/dist/chunk-4MC5JRRX.js.map +0 -1
  334. package/dist/chunk-52QYGZHH.js.map +0 -1
  335. package/dist/chunk-55LKVALY.js.map +0 -1
  336. package/dist/chunk-5PR33AC4.js.map +0 -1
  337. package/dist/chunk-66W5OOCX.js.map +0 -1
  338. package/dist/chunk-7G6VDWXB.js.map +0 -1
  339. package/dist/chunk-A67356IR.js.map +0 -1
  340. package/dist/chunk-AFHQATY4.js +0 -47
  341. package/dist/chunk-AFHQATY4.js.map +0 -1
  342. package/dist/chunk-AHLJSVRL.js.map +0 -1
  343. package/dist/chunk-C2OOEM57.js.map +0 -1
  344. package/dist/chunk-DIMKRG2E.js +0 -131
  345. package/dist/chunk-DIMKRG2E.js.map +0 -1
  346. package/dist/chunk-E6427JU2.js.map +0 -1
  347. package/dist/chunk-E7OBCBXS.js.map +0 -1
  348. package/dist/chunk-EDXAQ6JI.js.map +0 -1
  349. package/dist/chunk-EP7VPR7Y.js.map +0 -1
  350. package/dist/chunk-ERB6NDDW.js.map +0 -1
  351. package/dist/chunk-G5APARUV.js.map +0 -1
  352. package/dist/chunk-GASWQ3XG.js.map +0 -1
  353. package/dist/chunk-GLKDWWNO.js.map +0 -1
  354. package/dist/chunk-HNGSV2YC.js.map +0 -1
  355. package/dist/chunk-I4F6PKUK.js.map +0 -1
  356. package/dist/chunk-I4ZAO7F7.js.map +0 -1
  357. package/dist/chunk-I6SDX7WX.js.map +0 -1
  358. package/dist/chunk-JXIDGFKS.js.map +0 -1
  359. package/dist/chunk-LWSJG3LI.js.map +0 -1
  360. package/dist/chunk-MWKDOHEF.js.map +0 -1
  361. package/dist/chunk-MZ5ZFO2D.js.map +0 -1
  362. package/dist/chunk-NIVEDYJZ.js.map +0 -1
  363. package/dist/chunk-NWCGDAV6.js +0 -45
  364. package/dist/chunk-NWCGDAV6.js.map +0 -1
  365. package/dist/chunk-PJNTR2NV.js.map +0 -1
  366. package/dist/chunk-PRDRGL73.js.map +0 -1
  367. package/dist/chunk-PY7CI6L5.js.map +0 -1
  368. package/dist/chunk-RKKORO4M.js.map +0 -1
  369. package/dist/chunk-TAGFGKHP.js.map +0 -1
  370. package/dist/chunk-TDJPS3T2.js.map +0 -1
  371. package/dist/chunk-TOAIYQJR.js.map +0 -1
  372. package/dist/chunk-UHXCLPGC.js.map +0 -1
  373. package/dist/chunk-UIBGXRDD.js.map +0 -1
  374. package/dist/chunk-V5KYPBUR.js.map +0 -1
  375. package/dist/chunk-VCETL77O.js.map +0 -1
  376. package/dist/chunk-VN45YLWM.js.map +0 -1
  377. package/dist/chunk-VOQW5LAM.js.map +0 -1
  378. package/dist/chunk-VRA4Q7DA.js.map +0 -1
  379. package/dist/chunk-VV4NSB7P.js.map +0 -1
  380. package/dist/chunk-W5W6KHN2.js.map +0 -1
  381. package/dist/chunk-WHJKIZS7.js.map +0 -1
  382. package/dist/chunk-WYZ5MYUA.js.map +0 -1
  383. package/dist/chunk-ZJADGNYF.js.map +0 -1
  384. package/dist/chunk-ZNACADFG.js.map +0 -1
  385. package/dist/collection-facade-QN5ULWYC.js +0 -45
  386. package/dist/delegation-SSEPLXXO.js.map +0 -1
  387. package/dist/derive-6V3PIZF7.js +0 -22
  388. package/dist/executor-CYJQLKKI.js +0 -9
  389. package/dist/executor-FHHLXO4Y.js +0 -28
  390. package/dist/executor-S4QIKEHW.js +0 -9
  391. package/dist/export-accessible-PE5AYKZR.js +0 -23
  392. package/dist/extract-partition-X2L26O6A.js +0 -38
  393. package/dist/fanout-sidecar-DTBIDOWF.js.map +0 -1
  394. package/dist/find-RBBYKXI7.js +0 -11
  395. package/dist/issue-RNU55YOF.js +0 -19
  396. package/dist/liberate-PX4CAT5V.js +0 -24
  397. package/dist/noydb-YPSEGK32.js +0 -83
  398. package/dist/register-TMD6YRCX.js +0 -32
  399. package/dist/registry-CZVINVQH.js +0 -9
  400. package/dist/registry-FVLDWQKT.js +0 -18
  401. package/dist/registry-IKUR2MXD.js +0 -9
  402. package/dist/registry-JET4HBLY.js +0 -19
  403. package/dist/request-withdrawal-RH55LNZL.js +0 -31
  404. package/dist/revoke-R5TBYVA6.js +0 -24
  405. package/dist/seed-UK4QRIUN.js.map +0 -1
  406. package/dist/signer-AGALOXOO.js +0 -25
  407. package/dist/storage-N7LB275C.js +0 -23
  408. package/dist/store-coordination-provider-PB6QZ57W.js.map +0 -1
  409. package/dist/walk-OCUHCYJ6.js +0 -21
  410. package/dist/with-pod/bundle-handle.d.ts +0 -9
  411. package/dist/withdraw-accessible-QQNWM5BO.js +0 -28
  412. /package/dist/{api-WVY3H3YH.js.map → api-Z5VHH24A.js.map} +0 -0
  413. /package/dist/{chunk-FDX7OWWI.js.map → chunk-2E2MKBMI.js.map} +0 -0
  414. /package/dist/{chunk-7F4DBNSP.js.map → chunk-5J5TTSGW.js.map} +0 -0
  415. /package/dist/{chunk-BTVYJWSN.js.map → chunk-5JT4Y5UE.js.map} +0 -0
  416. /package/dist/{chunk-7NXHMW6Y.js.map → chunk-7RCZ436O.js.map} +0 -0
  417. /package/dist/{chunk-DG27IUVI.js.map → chunk-A3NTKHDB.js.map} +0 -0
  418. /package/dist/{chunk-CCZJJ4I2.js.map → chunk-A4K5GLE6.js.map} +0 -0
  419. /package/dist/{chunk-CEJWMBXO.js.map → chunk-APV42WPR.js.map} +0 -0
  420. /package/dist/{chunk-4HDYQL3J.js.map → chunk-AQF7JSQR.js.map} +0 -0
  421. /package/dist/{chunk-KUDZVJKQ.js.map → chunk-BP4I7IBK.js.map} +0 -0
  422. /package/dist/{chunk-4UVDI4XE.js.map → chunk-BTNKPDZM.js.map} +0 -0
  423. /package/dist/{chunk-HVQGCKY4.js.map → chunk-C7WJNVJG.js.map} +0 -0
  424. /package/dist/{chunk-KCQX65FU.js.map → chunk-CVYXIN5B.js.map} +0 -0
  425. /package/dist/{chunk-AR2JDFAE.js.map → chunk-DJ23QZIN.js.map} +0 -0
  426. /package/dist/{chunk-PVU7LW5L.js.map → chunk-EJIVFOOQ.js.map} +0 -0
  427. /package/dist/{chunk-VMCCGUQB.js.map → chunk-GDGTIWB4.js.map} +0 -0
  428. /package/dist/{chunk-FUHKW252.js.map → chunk-GILI76SU.js.map} +0 -0
  429. /package/dist/{chunk-35EBKWQU.js.map → chunk-GT72D4FO.js.map} +0 -0
  430. /package/dist/{chunk-JRCYZEHU.js.map → chunk-HGJC7I5F.js.map} +0 -0
  431. /package/dist/{chunk-YAWK6AWF.js.map → chunk-JIF3IBRK.js.map} +0 -0
  432. /package/dist/{chunk-HNHCQ556.js.map → chunk-KBOPY6W2.js.map} +0 -0
  433. /package/dist/{chunk-W3TVWF6N.js.map → chunk-KM6YR5XF.js.map} +0 -0
  434. /package/dist/{chunk-6HFM7EIT.js.map → chunk-MNMYHZVU.js.map} +0 -0
  435. /package/dist/{chunk-QD724WDJ.js.map → chunk-N2HKBESK.js.map} +0 -0
  436. /package/dist/{chunk-Z45YRGFO.js.map → chunk-N7YAQKAO.js.map} +0 -0
  437. /package/dist/{chunk-DMQCLZ4Z.js.map → chunk-NH2MST6J.js.map} +0 -0
  438. /package/dist/{chunk-HXGUIPQB.js.map → chunk-OQLYMBJI.js.map} +0 -0
  439. /package/dist/{chunk-MSWYQLMQ.js.map → chunk-PG6PFMDC.js.map} +0 -0
  440. /package/dist/{chunk-WKPJXWKR.js.map → chunk-QPIUFRUC.js.map} +0 -0
  441. /package/dist/{chunk-JIUVJ4M7.js.map → chunk-REL4OLWW.js.map} +0 -0
  442. /package/dist/{chunk-VW6ZZGCG.js.map → chunk-RNSC2ARR.js.map} +0 -0
  443. /package/dist/{chunk-WLYIROCJ.js.map → chunk-RORE2GX2.js.map} +0 -0
  444. /package/dist/{chunk-7TSYBD3E.js.map → chunk-RSFG7XHM.js.map} +0 -0
  445. /package/dist/{chunk-FAXZQ5UF.js.map → chunk-S55DBWRC.js.map} +0 -0
  446. /package/dist/{chunk-747LRSOO.js.map → chunk-SFD2LL7G.js.map} +0 -0
  447. /package/dist/{chunk-P7OG2ETF.js.map → chunk-SG3OQCRG.js.map} +0 -0
  448. /package/dist/{chunk-WQDTCJ6W.js.map → chunk-VEX2BQVX.js.map} +0 -0
  449. /package/dist/{chunk-7VHY5E3X.js.map → chunk-VH2W6BOG.js.map} +0 -0
  450. /package/dist/{chunk-OF3L2SD6.js.map → chunk-W6NFONOV.js.map} +0 -0
  451. /package/dist/{chunk-NJDQ4YSV.js.map → chunk-WBNXZU42.js.map} +0 -0
  452. /package/dist/{chunk-FNSMZQS4.js.map → chunk-WKD5ESK4.js.map} +0 -0
  453. /package/dist/{chunk-NKH7GSIH.js.map → chunk-XGQGWZ6D.js.map} +0 -0
  454. /package/dist/{chunk-VJFMXYKP.js.map → chunk-ZWKF3CD3.js.map} +0 -0
  455. /package/dist/{classified-marker-FTOX7Q5L.js.map → classified-marker-PMDG3O36.js.map} +0 -0
  456. /package/dist/{collection-facade-QN5ULWYC.js.map → collection-facade-ZJK5EB33.js.map} +0 -0
  457. /package/dist/{computed-6G5M3UPH.js.map → computed-UHCBRILW.js.map} +0 -0
  458. /package/dist/{dead-filter-ENRIOQIE.js.map → dead-filter-777VWDER.js.map} +0 -0
  459. /package/dist/{derive-6V3PIZF7.js.map → derive-3WAS2G5T.js.map} +0 -0
  460. /package/dist/{dispatch-BDVGYC6X.js.map → dispatch-3EN6YCCS.js.map} +0 -0
  461. /package/dist/{dispatch-RE74SH6L.js.map → dispatch-ASL257KG.js.map} +0 -0
  462. /package/dist/{enclave-52VUXNRL.js.map → enclave-ZJS5R5RH.js.map} +0 -0
  463. /package/dist/{executor-CYJQLKKI.js.map → executor-GPM6DNWV.js.map} +0 -0
  464. /package/dist/{executor-FHHLXO4Y.js.map → executor-LJSMZ4IB.js.map} +0 -0
  465. /package/dist/{executor-S4QIKEHW.js.map → executor-SHUVRZUJ.js.map} +0 -0
  466. /package/dist/{export-accessible-PE5AYKZR.js.map → export-accessible-GNY6DC6U.js.map} +0 -0
  467. /package/dist/{extract-partition-X2L26O6A.js.map → extract-partition-BG3AF4NZ.js.map} +0 -0
  468. /package/dist/{find-RBBYKXI7.js.map → find-KX6OKHDP.js.map} +0 -0
  469. /package/dist/{issue-RNU55YOF.js.map → issue-PAUM7NCX.js.map} +0 -0
  470. /package/dist/{ledger-4WJL66BW.js.map → ledger-62CEPRPX.js.map} +0 -0
  471. /package/dist/{liberate-PX4CAT5V.js.map → liberate-I6AOLWXW.js.map} +0 -0
  472. /package/dist/{link-set-N4ZPV6E6.js.map → link-set-ZRYNUHN3.js.map} +0 -0
  473. /package/dist/{managed-secret-OTHS64IF.js.map → managed-secret-T2WB4O47.js.map} +0 -0
  474. /package/dist/{noydb-YPSEGK32.js.map → noydb-SS6EN7TK.js.map} +0 -0
  475. /package/dist/{post-register-ZAG2CAIY.js.map → post-register-J4DEVNXK.js.map} +0 -0
  476. /package/dist/{register-TMD6YRCX.js.map → register-UPD4GKBC.js.map} +0 -0
  477. /package/dist/{registry-CZVINVQH.js.map → registry-7KX2HWFS.js.map} +0 -0
  478. /package/dist/{registry-FVLDWQKT.js.map → registry-PKYYEHEW.js.map} +0 -0
  479. /package/dist/{registry-IKUR2MXD.js.map → registry-XHCYMD34.js.map} +0 -0
  480. /package/dist/{registry-JET4HBLY.js.map → registry-XIRTZHPC.js.map} +0 -0
  481. /package/dist/{request-withdrawal-RH55LNZL.js.map → request-withdrawal-XZSESWZV.js.map} +0 -0
  482. /package/dist/{reveal-CMOJY4VO.js.map → reveal-525XWQU2.js.map} +0 -0
  483. /package/dist/{revoke-R5TBYVA6.js.map → revoke-QI7YHQ2B.js.map} +0 -0
  484. /package/dist/{signer-AGALOXOO.js.map → signer-BZWDPGGN.js.map} +0 -0
  485. /package/dist/{stale-ZWXSOWJI.js.map → stale-PQYPVCER.js.map} +0 -0
  486. /package/dist/{storage-N7LB275C.js.map → storage-MJHKNQRO.js.map} +0 -0
  487. /package/dist/{ulid-PTAIMDG4.js.map → ulid-VQW6ERQN.js.map} +0 -0
  488. /package/dist/{verify-RO5RTZOJ.js.map → verify-J6DEOXP3.js.map} +0 -0
  489. /package/dist/{walk-OCUHCYJ6.js.map → walk-BX4NSB5L.js.map} +0 -0
  490. /package/dist/{withdraw-accessible-QQNWM5BO.js.map → withdraw-accessible-K4CPMH4C.js.map} +0 -0
@@ -1,14 +1,15 @@
1
1
  import {
2
+ buildRecordAad,
2
3
  openEnvelopeJson
3
- } from "./chunk-VN45YLWM.js";
4
+ } from "./chunk-D5UDZANO.js";
5
+ import {
6
+ buildRecordEnvelope
7
+ } from "./chunk-ZVAFJQZB.js";
4
8
  import {
5
9
  encrypt,
6
10
  hmacSha256Hex,
7
11
  sha256Hex
8
- } from "./chunk-VCETL77O.js";
9
- import {
10
- NOYDB_FORMAT_VERSION
11
- } from "./chunk-W5W6KHN2.js";
12
+ } from "./chunk-VJ4B3ZXY.js";
12
13
 
13
14
  // src/with-audit/forget/strategy.ts
14
15
  var NO_FORGET = { subjects: {} };
@@ -43,17 +44,18 @@ async function readRefs(adapter, vault, getDEK, encrypted, key) {
43
44
  if (!env || !env._data) return [];
44
45
  if (!encrypted) return parseRefs(env._data);
45
46
  const dek = await getDEK(SUBJECT_INDEX_COLLECTION);
46
- const json = await openEnvelopeJson(env, dek);
47
+ const json = await openEnvelopeJson({ collection: SUBJECT_INDEX_COLLECTION, id: key }, env, dek);
47
48
  return parseRefs(json);
48
49
  }
49
50
  async function writeRefs(adapter, vault, getDEK, encrypted, key, refs) {
51
+ const identity = { collection: SUBJECT_INDEX_COLLECTION, id: key, version: 1 };
50
52
  let env;
51
53
  if (!encrypted) {
52
- env = { _noydb: NOYDB_FORMAT_VERSION, _v: 1, _ts: (/* @__PURE__ */ new Date()).toISOString(), _iv: "", _data: JSON.stringify(refs) };
54
+ env = buildRecordEnvelope(identity, { iv: "", data: JSON.stringify(refs) });
53
55
  } else {
54
56
  const dek = await getDEK(SUBJECT_INDEX_COLLECTION);
55
- const { iv, data } = await encrypt(serializeRefs(refs), dek);
56
- env = { _noydb: NOYDB_FORMAT_VERSION, _v: 1, _ts: (/* @__PURE__ */ new Date()).toISOString(), _iv: iv, _data: data };
57
+ const { iv, data } = await encrypt(serializeRefs(refs), dek, buildRecordAad(identity));
58
+ env = buildRecordEnvelope(identity, { iv, data });
57
59
  }
58
60
  await adapter.put(vault, SUBJECT_INDEX_COLLECTION, key, env);
59
61
  }
@@ -147,4 +149,4 @@ export {
147
149
  coerceSubjectId,
148
150
  readDottedPath
149
151
  };
150
- //# sourceMappingURL=chunk-HFQ6LGIO.js.map
152
+ //# sourceMappingURL=chunk-TENLCGYD.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/with-audit/forget/strategy.ts","../src/with-audit/forget/subject-index.ts"],"sourcesContent":["/**\n * `withForget` — declaration surface for GDPR right-to-erasure via\n * per-record CEK crypto-shred.\n *\n * This file holds only the *declaration* shape and the disabled sentinel.\n * The actual erasure machinery lives in:\n * - `subject-index.ts` — the encrypted `_subject_index` reserved collection\n * - `vault.ts` `forget()` — the per-record tombstone + ledger flow\n * - `collection.ts` `_writeTombstone` — the envelope rewrite\n *\n * A `ForgetStrategy` declares which collections carry erasable subject data\n * and the (dotted-path) field on each record that names the data subject.\n * Declaring a collection here ALSO forces `perRecordKeys: true` for it (a\n * shred can only erase a record whose body is keyed off a per-record CEK),\n * so adopters opt into the CEK foundation transitively.\n *\n * @module\n */\nimport type { LedgerEntry } from '../../with-commit/history/ledger/entry.js'\n\n/**\n * User-supplied declaration passed to {@link withForget}. Maps a\n * collection name to the record field (dotted path supported, e.g.\n * `'billing.buyerId'`) that identifies the data subject for erasure.\n *\n * ```ts\n * withForget({ subjects: { invoices: 'buyerId', contacts: 'id' } })\n * ```\n */\nexport interface SubjectDeclaration {\n readonly subjects: Record<string, string>\n /**\n * #633 — opt-in: gate the vault-level `_sealed_cek` and blob purges on\n * per-collection via declarations instead of running them unconditionally\n * for every forgotten ref. Default `false`/absent = today's unconditional\n * behavior (byte-identical). See `purge-scope.ts` for the partition logic\n * and the `scopedPurgeResidue` skip-reporting this enables.\n *\n * **Footgun:** a bare `sensitive: [...]` collection — no `classifiedFields`\n * (no classified via binder compiled in) — counts as UNDECLARED for the\n * sealed-CEK arm. Under `scopedPurge: true`, its `_sealed_cek` host-delivery\n * envelopes are SKIPPED, not purged (reported via `scopedPurgeResidue`,\n * reason `'skipped-undeclared-sealed-cek'`) even if that collection called\n * `sealRecordToHost()` — the sealed CEK stays recoverable by that granted\n * host until purged. Add a `classifiedFields` binding to close the gap, or\n * leave `scopedPurge` off/false for the unconditional (always-purged) default.\n * The declaration signal is session-local: a declared collection never opened\n * (with its config) before `forget()` in this session counts as UNDECLARED —\n * open it first, or its entries are skipped-and-reported.\n */\n readonly scopedPurge?: boolean\n}\n\n/**\n * Resolved forget strategy threaded through Noydb → every Vault. Carries\n * the same `subjects` map the user declared. `NO_FORGET` (empty map) is the\n * off-by-default sentinel; `vault.forget()` throws\n * `ForgetStrategyNotConfiguredError` when the map is empty.\n */\nexport interface ForgetStrategy {\n /** Collection → subject-field (dotted path). Empty under `NO_FORGET`. */\n readonly subjects: Readonly<Record<string, string>>\n /** #633 — see {@link SubjectDeclaration.scopedPurge}. */\n readonly scopedPurge?: boolean\n}\n\n/**\n * Disabled sentinel — no collections declare a subject field. `vault.forget()`\n * refuses with `ForgetStrategyNotConfiguredError`; no write hooks register; no\n * collection is forced into `perRecordKeys`. Non-adopters pay nothing.\n */\nexport const NO_FORGET: ForgetStrategy = { subjects: {} }\n\n// The `withForget` factory lives in `active.ts` (canonical\n// strategy.ts/active.ts/index.ts split); this file holds only the\n// declaration shape + disabled sentinel.\n\n/**\n * The outcome of a `vault.forget(subjectId)` call.\n *\n * `unmigratedRecords` lists `collection:id` pairs that were tombstoned but\n * whose body had NOT been migrated to a per-record CEK at shred time (legacy\n * body still under the shared collection DEK). Those records are tombstoned\n * (live envelope + history stripped) but their pre-shred ciphertext, if it\n * leaked into a backup before migration, remains decryptable under the\n * collection DEK — so erasure-completeness is NOT guaranteed for them. Run\n * the per-record-CEK migration pass, then re-forget, to close the gap.\n *\n * Blob attachments: a shredded record's **erasable** blobs (on a\n * `perRecordKeys` collection) are crypto-shredded inline — `blobsShredded`\n * counts those taken to refCount 0 (BlobObject deleted → chunks permanently\n * undecryptable), `blobsRetainedShared` counts those still referenced by\n * another record (shared content legitimately persists for its other owner).\n * `blobResidueCollections` now lists only collections with blobs that could\n * NOT be crypto-shredded: **legacy** blobs (no per-blob `_cek`, chunks under\n * the shared `_blob` DEK — migrate them), or a session without the blob\n * service loaded. An all-erasable subject yields an empty residue list.\n */\nexport interface ForgetResult {\n /** The subject id passed to `forget()`. Echoed for caller convenience. */\n readonly subject: string\n /** Count of live records rewritten to a tombstone. */\n readonly recordsShredded: number\n /** Count of `_history` envelopes tombstoned across all shredded records. */\n readonly historyVersionsShredded: number\n /** Distinct collections that had at least one record shredded. */\n readonly collections: readonly string[]\n /** `collection:id` pairs shredded while still un-migrated (see type docs). */\n readonly unmigratedRecords: readonly string[]\n /** Count of erasable blobs crypto-shredded (refCount → 0, BlobObject deleted). */\n readonly blobsShredded: number\n /** Count of erasable blobs retained because still referenced elsewhere (shared). */\n readonly blobsRetainedShared: number\n /** Collections with blobs that could NOT be crypto-shredded — legacy (no `_cek`) or blobs disabled (see type docs). */\n readonly blobResidueCollections: readonly string[]\n /**\n * Count of persisted `_idx/<field>/<recordId>` index side-cars hard-deleted\n * across the shredded records. These live under the retained\n * collection DEK, so crypto-shred alone would leave the indexed field VALUES\n * readable — `forget()` must delete them.\n */\n readonly indexPostingsPurged: number\n /**\n * `collection:id:field` entries whose persisted `_idx` side-car could NOT be\n * deleted — index residue that still leaks the indexed value under the\n * retained collection DEK. Non-empty means erasure is INCOMPLETE: retry, or\n * purge the side-car out of band.\n */\n readonly indexResidue: readonly string[]\n /**\n * Count of `_sealed[field]` slots dropped from the live store across the\n * shredded records. For slots written under `sensitive` +\n * `perRecordKeys` (the current path), the key derives off the per-record CEK,\n * so tombstoning the record — which drops `_cek` and `_sealed` — also\n * crypto-shreds the value. A legacy slot (written before per-record CEKs) keys\n * off the collection DEK instead, so dropping it removes it from the live store but a\n * pre-forget backup remains recoverable by a DEK holder (same caveat `_data`\n * carries); migrate by re-`put`ting before forgetting for full crypto-shred.\n */\n readonly sealedFieldsShredded: number\n /** Count of `_sealed_cek` host-delivery envelopes deleted (#H-1). A record sealed to an\n * at-* host via sealRecordToHost persists its raw CEK there; forget() must destroy them. */\n readonly sealedCekEnvelopesPurged: number\n /** `collection:id` whose `_sealed_cek` purge failed (residue — the host-recoverable CEK may survive). */\n readonly sealedCekResidue: readonly string[]\n /** `collection:id:field` sealed slots that were DEK-derived (legacy, written before per-record CEKs) and thus NOT crypto-shredded\n * by dropping `_cek` — the collection DEK is retained, so synced/backup copies stay decryptable (#M-1). */\n readonly sealedResidue: readonly string[]\n /** Count of `_ledger_deltas` rows hard-deleted across the shredded records (#734) — the\n * erasure twin of #729's elevate-side purge. Entry metadata (that the record was mutated,\n * at which version/timestamp/actor) is retained; only the plaintext delta content is removed. */\n readonly ledgerDeltasPurged: number\n /** `collection:id` refs whose `_ledger_deltas` purge failed — plaintext delta residue still\n * readable under the retained ledger DEK. Non-empty means erasure is INCOMPLETE. */\n readonly ledgerDeltaResidue: readonly string[]\n /** The single `op:'forget'` ledger entry appended for this erasure. */\n readonly ledgerEntry: LedgerEntry\n /** #622 — record-grain derived artifacts (MV rows, per-record derived copies) erased\n * because their source subject was forgotten. Overlay outputs are intentionally out of\n * scope here — an overlay is always sourced from an MV, never directly from a subject\n * collection, so the personal-data-bearing MV rows it reads are already erased above. */\n readonly derivedRecordsErased: number\n /** #622 — aggregate-grain targets (rollups) recomputed without the forgotten contribution. */\n readonly derivedAggregatesRecomputed: number\n /** #622 — `collection:id` derived writes SKIPPED because the target period is frozen\n * (recompute deferred; the aggregate retains the forgotten contribution — audited). */\n readonly derivedResidueFrozen: readonly string[]\n /** #650 Task 5 (#648) — referencing records tombstoned via a `'ref'` edge's `cascade` policy. */\n readonly lookupReferencesCascaded: number\n /** #650 Task 5 (#648) — referencing fields cleared via a `'ref'` edge's `nullify` policy. */\n readonly lookupReferencesNullified: number\n /** #650 Task 5 review (Important fix) — `'ref'` edges whose compare-key could NOT be resolved,\n * even from the LIVE pre-shred backing row — cascade/nullify propagation was SKIPPED for these.\n * Always empty in the ordinary case; non-empty means the skip is reported, never silent. */\n readonly lookupReferencesResidue: readonly string[]\n /** #633 — scoped-purge skip notices (opt-in `scopedPurge`, see {@link SubjectDeclaration}).\n * Always empty under the unconditional default. Non-empty means a `_sealed_cek` entry or a\n * blob scan was skipped for an undeclared collection — reported, never a silent skip. */\n readonly scopedPurgeResidue: readonly ScopedPurgeResidueNotice[]\n /** #776/#782/#785 — `collection:id` MV-output rows that survived erasure invalidation (eager\n * tombstone leg AND lazy/manual `invalidateMVAtRest`) despite belonging to the forgotten\n * subject, because the `_materializedFrom` ownership stamp could NOT be decoded (undecodable\n * under the collection's default DEK — e.g. elevated above tier 0 on a tiered output\n * collection; ownership unconfirmed — could be a plain user record on a same-collection\n * partition MV). Never erased, but surfaced here rather than silently skipped (the #724\n * posture). Non-empty means the row may still hold the forgotten/pre-elevation contribution,\n * decryptable by tier-holders. */\n readonly derivedResidueUndecodable: readonly string[]\n /** #782/#785 — `collection:id` MV-output rows that DID decode and stamp-match via\n * `_materializedFrom`, but whose erasure was declined by the #718 tier-elevation gate\n * (`_internalDelete` returned false). Ownership CONFIRMED here — a real silent survival,\n * not a stamp-mismatch skip — surfaced rather than dropped. Non-empty means a live,\n * tier-holder-decryptable copy of the forgotten contribution was deliberately retained. */\n readonly derivedResidueDeclined: readonly string[]\n}\n\n/** #633 — the two `scopedPurgeResidue` skip reasons. Single source of truth: `purge-scope.ts`\n * (the port-internal partition helpers) imports this rather than redeclaring it. */\nexport type ScopedPurgeResidueReason = 'skipped-undeclared-sealed-cek' | 'skipped-undeclared-blob-scan'\n\n/** #633 — one `ForgetResult.scopedPurgeResidue` entry: an undeclared collection's sealed-CEK\n * entries left unpurged, or its blob scan skipped entirely, under `scopedPurge`. `count` is the\n * number of `_sealed_cek` entries left in place (sealed-cek reason) or the number of refs whose\n * blob scan was skipped (blob-scan reason) — aggregated per collection across the whole call. */\nexport interface ScopedPurgeResidueNotice {\n readonly reason: ScopedPurgeResidueReason\n readonly collection: string\n readonly count: number\n}\n","/**\n * The encrypted subject index.\n *\n * GDPR crypto-shred needs to answer \"which records belong to data subject\n * X?\" portably (the index must travel with the vault/bundle) WITHOUT leaking\n * subject-equivalence to the store. The rejected alternative — an unencrypted\n * subject tag in envelope metadata — would let anyone with store access see\n * which records share a subject. Instead we keep a reserved `_subject_index`\n * collection, encrypted under its OWN DEK (`getDEK('_subject_index')`):\n *\n * - record id = `HMAC-SHA256(indexDEK, subjectId)` (M-2). A bare\n * `sha256Hex(subjectId)` would be offline-computable: an attacker with\n * store access and a candidate list (emails / customer ids are low-entropy)\n * could dictionary the hash to confirm \"subject X is present here.\" Keying\n * the id with the vault-only index DEK removes that capability — without the\n * DEK the id cannot be derived. (Legacy entries written before M-2 used the\n * bare sha256 id; the read/remove paths dual-look-up both forms.)\n * - record body = AES-GCM(JSON `{ r: [{ collection, id }], p }`) under the\n * index DEK, where `p` pads the plaintext to a bucketed length so the\n * ciphertext `_data` length does not leak the approximate record count.\n * Legacy bodies were a bare `[{ collection, id }]` array; reads accept both.\n *\n * ## Concurrency (RISK #3 — known v1 limitation)\n *\n * `addSubjectRef` / `removeSubjectRef` are read-modify-write with no CAS. The\n * design assumes a SINGLE WRITER (the noy-db single-process write model). Two\n * concurrent writers racing on the SAME subject can lose an entry (last-write\n * wins on the ref list). This is documented, not fixed in v1:\n * `rebuildSubjectIndex` performs a full scan to recover a correct index from\n * the canonical records, so a lost ref is recoverable. A CAS-backed index is\n * deferred to a later slice.\n *\n * @module\n */\nimport { encrypt, openEnvelopeJson, hmacSha256Hex, sha256Hex, type EnclaveKey } from '../../kernel/enclave/index.js'\nimport type { NoydbStore, EncryptedEnvelope } from '../../kernel/types.js'\nimport { NOYDB_FORMAT_VERSION } from '../../kernel/types.js'\n\n/** Reserved collection holding the encrypted subject → records index. */\nexport const SUBJECT_INDEX_COLLECTION = '_subject_index'\n\n/**\n * Bucket (bytes) the encrypted ref-list plaintext is padded up to, so the\n * ciphertext `_data` length leaks only `count` rounded up to a bucket — not the\n * exact record count. 256 keeps small subjects (the common case) indistinguishable.\n */\nconst REF_LIST_BUCKET = 256\n\n/** A single record reference held in a subject's index entry. */\nexport interface SubjectRef {\n readonly collection: string\n readonly id: string\n}\n\ntype GetDEK = (collectionName: string) => Promise<EnclaveKey>\n\n/** SHA-256 hex of a UTF-8 string. The LEGACY (pre-M-2) subject-index key. */\nasync function sha256HexString(input: string): Promise<string> {\n return sha256Hex(new TextEncoder().encode(input))\n}\n\n/**\n * The subject-index record id(s) to consult for a subject, most-current first.\n *\n * - Encrypted vault: the PRIMARY id is `HMAC-SHA256(indexDEK, subjectId)` (M-2)\n * — not offline-computable. The LEGACY `sha256Hex(subjectId)` id is also\n * returned so reads/removes still find entries written before M-2 (dual-lookup).\n * - Plaintext/debug vault: no DEK to key with, so the only id is the legacy\n * sha256 form (unchanged behaviour — plaintext mode is not zero-knowledge anyway).\n */\nasync function subjectKeys(getDEK: GetDEK, encrypted: boolean, subjectId: string): Promise<string[]> {\n const legacy = await sha256HexString(subjectId)\n if (!encrypted) return [legacy]\n const dek = await getDEK(SUBJECT_INDEX_COLLECTION)\n const keyed = await hmacSha256Hex(dek, new TextEncoder().encode(subjectId))\n return keyed === legacy ? [keyed] : [keyed, legacy]\n}\n\n/** The id new writes land under (keyed when encrypted, else legacy sha256). */\nasync function primarySubjectKey(getDEK: GetDEK, encrypted: boolean, subjectId: string): Promise<string> {\n return (await subjectKeys(getDEK, encrypted, subjectId))[0]!\n}\n\n/** Parse a stored ref-list body: new padded `{ r, p }` wrapper OR legacy bare array. */\nfunction parseRefs(json: string): SubjectRef[] {\n const parsed = JSON.parse(json) as SubjectRef[] | { r: SubjectRef[] }\n return Array.isArray(parsed) ? parsed : parsed.r\n}\n\n/** Serialize + pad the ref list to a bucket boundary (encrypted vaults only). */\nfunction serializeRefs(refs: SubjectRef[]): string {\n const base = JSON.stringify({ r: refs, p: '' })\n const pad = Math.ceil(base.length / REF_LIST_BUCKET) * REF_LIST_BUCKET - base.length\n return JSON.stringify({ r: refs, p: ' '.repeat(pad) })\n}\n\n/** Read + decrypt the ref list at a SINGLE index key. Returns `[]` when absent. */\nasync function readRefs(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n key: string,\n): Promise<SubjectRef[]> {\n const env = await adapter.get(vault, SUBJECT_INDEX_COLLECTION, key)\n if (!env || !env._data) return []\n if (!encrypted) return parseRefs(env._data)\n const dek = await getDEK(SUBJECT_INDEX_COLLECTION)\n const json = await openEnvelopeJson(env, dek)\n return parseRefs(json)\n}\n\n/** Encrypt + write a ref list for a subject under its derived key. */\nasync function writeRefs(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n key: string,\n refs: SubjectRef[],\n): Promise<void> {\n let env: EncryptedEnvelope\n if (!encrypted) {\n // Plaintext/debug vault: keep the legacy bare-array form (no padding needed).\n env = { _noydb: NOYDB_FORMAT_VERSION, _v: 1, _ts: new Date().toISOString(), _iv: '', _data: JSON.stringify(refs) }\n } else {\n const dek = await getDEK(SUBJECT_INDEX_COLLECTION)\n const { iv, data } = await encrypt(serializeRefs(refs), dek)\n env = { _noydb: NOYDB_FORMAT_VERSION, _v: 1, _ts: new Date().toISOString(), _iv: iv, _data: data }\n }\n await adapter.put(vault, SUBJECT_INDEX_COLLECTION, key, env)\n}\n\n/**\n * Add a `{ collection, id }` ref to a subject's index entry (idempotent —\n * a duplicate ref is not appended). Read-modify-write; see the concurrency\n * note in the module docstring.\n */\nexport async function addSubjectRef(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n subjectId: string,\n ref: SubjectRef,\n): Promise<void> {\n const key = await primarySubjectKey(getDEK, encrypted, subjectId)\n const refs = await readRefs(adapter, vault, getDEK, encrypted, key)\n if (refs.some((r) => r.collection === ref.collection && r.id === ref.id)) return\n refs.push(ref)\n await writeRefs(adapter, vault, getDEK, encrypted, key, refs)\n}\n\n/**\n * Remove a `{ collection, id }` ref from a subject's index entry. When the\n * last ref is removed the (now empty) entry is deleted so the store holds no\n * residual key for an erased subject.\n */\nexport async function removeSubjectRef(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n subjectId: string,\n ref: SubjectRef,\n): Promise<void> {\n // Dual-lookup: drop the ref from BOTH the keyed (M-2) and the legacy sha256\n // entry, so a pre-M-2 subject is still fully erased.\n for (const key of await subjectKeys(getDEK, encrypted, subjectId)) {\n const refs = await readRefs(adapter, vault, getDEK, encrypted, key)\n const next = refs.filter((r) => !(r.collection === ref.collection && r.id === ref.id))\n if (next.length === refs.length) continue\n if (next.length === 0) {\n await adapter.delete(vault, SUBJECT_INDEX_COLLECTION, key)\n } else {\n await writeRefs(adapter, vault, getDEK, encrypted, key, next)\n }\n }\n}\n\n/**\n * Look up every record ref for a subject. Returns `[]` when none exist. Unions\n * the keyed (M-2) and legacy sha256 entries (dual-lookup), deduplicated, so a\n * subject indexed before M-2 is still fully found.\n */\nexport async function lookupSubject(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n subjectId: string,\n): Promise<SubjectRef[]> {\n const keys = await subjectKeys(getDEK, encrypted, subjectId)\n const seen = new Set<string>()\n const out: SubjectRef[] = []\n for (const key of keys) {\n for (const ref of await readRefs(adapter, vault, getDEK, encrypted, key)) {\n const dedup = `${ref.collection}\\u0000${ref.id}`\n if (seen.has(dedup)) continue\n seen.add(dedup)\n out.push(ref)\n }\n }\n return out\n}\n\n/**\n * Rebuild the entire subject index from the canonical records (the recovery\n * path for the documented read-modify-write race). Scans each declared\n * collection, reads `record[subjectField]` (dotted path), and rewrites the\n * index from scratch. Tombstoned (already-shredded) records contribute no\n * ref — their body is gone, so they cannot be re-indexed.\n *\n * `decodeRecord` decrypts an envelope to a plain object (or returns null for\n * a tombstone / unreadable record); supplied by the caller so this module\n * stays free of Collection internals.\n */\nexport async function rebuildSubjectIndex(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n subjects: Readonly<Record<string, string>>,\n decodeRecord: (collection: string, id: string, env: EncryptedEnvelope) => Promise<Record<string, unknown> | null>,\n): Promise<number> {\n // Drop every existing index entry first so removed refs don't linger.\n const existing = await adapter.list(vault, SUBJECT_INDEX_COLLECTION)\n for (const k of existing) {\n await adapter.delete(vault, SUBJECT_INDEX_COLLECTION, k)\n }\n\n // subjectId → refs, accumulated across all declared collections.\n const bySubject = new Map<string, SubjectRef[]>()\n for (const [collection, field] of Object.entries(subjects)) {\n const ids = await adapter.list(vault, collection)\n for (const id of ids) {\n if (id.startsWith('_')) continue\n const env = await adapter.get(vault, collection, id)\n if (!env || !env._data) continue // missing or tombstone\n const record = await decodeRecord(collection, id, env)\n if (record === null) continue\n const subjectValue = readDottedPath(record, field)\n if (subjectValue === undefined || subjectValue === null) continue\n const subjectId = coerceSubjectId(subjectValue)\n const list = bySubject.get(subjectId) ?? []\n list.push({ collection, id })\n bySubject.set(subjectId, list)\n }\n }\n\n let entries = 0\n for (const [subjectId, refs] of bySubject) {\n const key = await primarySubjectKey(getDEK, encrypted, subjectId)\n await writeRefs(adapter, vault, getDEK, encrypted, key, refs)\n entries++\n }\n return entries\n}\n\n/**\n * Coerce a read subject-field value to a stable string id. Primitives use\n * their natural string form; objects/arrays are JSON-stringified so structural\n * subjects still get a deterministic key (avoids the `[object Object]` trap).\n */\nexport function coerceSubjectId(value: unknown): string {\n if (typeof value === 'string') return value\n if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {\n return String(value)\n }\n return JSON.stringify(value)\n}\n\n/** Read a (possibly dotted) field path from a plain record. */\nexport function readDottedPath(record: Record<string, unknown>, field: string): unknown {\n if (!field.includes('.')) return record[field]\n let cursor: unknown = record\n for (const segment of field.split('.')) {\n if (cursor === null || cursor === undefined) return undefined\n cursor = (cursor as Record<string, unknown>)[segment]\n }\n return cursor\n}\n"],"mappings":";;;;;;;;;;;;;AAuEO,IAAM,YAA4B,EAAE,UAAU,CAAC,EAAE;;;ACh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1C,WAAK,KAAK,EAAE,YAAY,GAAG,CAAC;AAC5B,gBAAU,IAAI,WAAW,IAAI;AAAA,IAC/B;AAAA,EACF;AAEA,MAAI,UAAU;AACd,aAAW,CAAC,WAAW,IAAI,KAAK,WAAW;AACzC,UAAM,MAAM,MAAM,kBAAkB,QAAQ,WAAW,SAAS;AAChE,UAAM,UAAU,SAAS,OAAO,QAAQ,WAAW,KAAK,IAAI;AAC5D;AAAA,EACF;AACA,SAAO;AACT;AAOO,SAAS,gBAAgB,OAAwB;AACtD,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,MAAI,OAAO,UAAU,YAAY,OAAO,UAAU,aAAa,OAAO,UAAU,UAAU;AACxF,WAAO,OAAO,KAAK;AAAA,EACrB;AACA,SAAO,KAAK,UAAU,KAAK;AAC7B;AAGO,SAAS,eAAe,QAAiC,OAAwB;AACtF,MAAI,CAAC,MAAM,SAAS,GAAG,EAAG,QAAO,OAAO,KAAK;AAC7C,MAAI,SAAkB;AACtB,aAAW,WAAW,MAAM,MAAM,GAAG,GAAG;AACtC,QAAI,WAAW,QAAQ,WAAW,OAAW,QAAO;AACpD,aAAU,OAAmC,OAAO;AAAA,EACtD;AACA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/with-audit/forget/strategy.ts","../src/with-audit/forget/subject-index.ts"],"sourcesContent":["/**\n * `withForget` — declaration surface for GDPR right-to-erasure via\n * per-record CEK crypto-shred.\n *\n * This file holds only the *declaration* shape and the disabled sentinel.\n * The actual erasure machinery lives in:\n * - `subject-index.ts` — the encrypted `_subject_index` reserved collection\n * - `vault.ts` `forget()` — the per-record tombstone + ledger flow\n * - `collection.ts` `_writeTombstone` — the envelope rewrite\n *\n * A `ForgetStrategy` declares which collections carry erasable subject data\n * and the (dotted-path) field on each record that names the data subject.\n * Declaring a collection here ALSO forces `perRecordKeys: true` for it (a\n * shred can only erase a record whose body is keyed off a per-record CEK),\n * so adopters opt into the CEK foundation transitively.\n *\n * @module\n */\nimport type { LedgerEntry } from '../../with-commit/history/ledger/entry.js'\n\n/**\n * User-supplied declaration passed to {@link withForget}. Maps a\n * collection name to the record field (dotted path supported, e.g.\n * `'billing.buyerId'`) that identifies the data subject for erasure.\n *\n * ```ts\n * withForget({ subjects: { invoices: 'buyerId', contacts: 'id' } })\n * ```\n */\nexport interface SubjectDeclaration {\n readonly subjects: Record<string, string>\n /**\n * #633 — opt-in: gate the vault-level `_sealed_cek` and blob purges on\n * per-collection via declarations instead of running them unconditionally\n * for every forgotten ref. Default `false`/absent = today's unconditional\n * behavior (byte-identical). See `purge-scope.ts` for the partition logic\n * and the `scopedPurgeResidue` skip-reporting this enables.\n *\n * **Footgun:** a bare `sensitive: [...]` collection — no `classifiedFields`\n * (no classified via binder compiled in) — counts as UNDECLARED for the\n * sealed-CEK arm. Under `scopedPurge: true`, its `_sealed_cek` host-delivery\n * envelopes are SKIPPED, not purged (reported via `scopedPurgeResidue`,\n * reason `'skipped-undeclared-sealed-cek'`) even if that collection called\n * `sealRecordToHost()` — the sealed CEK stays recoverable by that granted\n * host until purged. Add a `classifiedFields` binding to close the gap, or\n * leave `scopedPurge` off/false for the unconditional (always-purged) default.\n * The declaration signal is session-local: a declared collection never opened\n * (with its config) before `forget()` in this session counts as UNDECLARED —\n * open it first, or its entries are skipped-and-reported.\n */\n readonly scopedPurge?: boolean\n}\n\n/**\n * Resolved forget strategy threaded through Noydb → every Vault. Carries\n * the same `subjects` map the user declared. `NO_FORGET` (empty map) is the\n * off-by-default sentinel; `vault.forget()` throws\n * `ForgetStrategyNotConfiguredError` when the map is empty.\n */\nexport interface ForgetStrategy {\n /** Collection → subject-field (dotted path). Empty under `NO_FORGET`. */\n readonly subjects: Readonly<Record<string, string>>\n /** #633 — see {@link SubjectDeclaration.scopedPurge}. */\n readonly scopedPurge?: boolean\n}\n\n/**\n * Disabled sentinel — no collections declare a subject field. `vault.forget()`\n * refuses with `ForgetStrategyNotConfiguredError`; no write hooks register; no\n * collection is forced into `perRecordKeys`. Non-adopters pay nothing.\n */\nexport const NO_FORGET: ForgetStrategy = { subjects: {} }\n\n// The `withForget` factory lives in `active.ts` (canonical\n// strategy.ts/active.ts/index.ts split); this file holds only the\n// declaration shape + disabled sentinel.\n\n/**\n * The outcome of a `vault.forget(subjectId)` call.\n *\n * `unmigratedRecords` lists `collection:id` pairs that were tombstoned but\n * whose body had NOT been migrated to a per-record CEK at shred time (legacy\n * body still under the shared collection DEK). Those records are tombstoned\n * (live envelope + history stripped) but their pre-shred ciphertext, if it\n * leaked into a backup before migration, remains decryptable under the\n * collection DEK — so erasure-completeness is NOT guaranteed for them. Run\n * the per-record-CEK migration pass, then re-forget, to close the gap.\n *\n * Blob attachments: a shredded record's **erasable** blobs (on a\n * `perRecordKeys` collection) are crypto-shredded inline — `blobsShredded`\n * counts those taken to refCount 0 (BlobObject deleted → chunks permanently\n * undecryptable), `blobsRetainedShared` counts those still referenced by\n * another record (shared content legitimately persists for its other owner).\n * `blobResidueCollections` now lists only collections with blobs that could\n * NOT be crypto-shredded: **legacy** blobs (no per-blob `_cek`, chunks under\n * the shared `_blob` DEK — migrate them), or a session without the blob\n * service loaded. An all-erasable subject yields an empty residue list.\n */\nexport interface ForgetResult {\n /** The subject id passed to `forget()`. Echoed for caller convenience. */\n readonly subject: string\n /** Count of live records rewritten to a tombstone. */\n readonly recordsShredded: number\n /** Count of `_history` envelopes tombstoned across all shredded records. */\n readonly historyVersionsShredded: number\n /** Distinct collections that had at least one record shredded. */\n readonly collections: readonly string[]\n /** `collection:id` pairs shredded while still un-migrated (see type docs). */\n readonly unmigratedRecords: readonly string[]\n /** Count of erasable blobs crypto-shredded (refCount → 0, BlobObject deleted). */\n readonly blobsShredded: number\n /** Count of erasable blobs retained because still referenced elsewhere (shared). */\n readonly blobsRetainedShared: number\n /** Collections with blobs that could NOT be crypto-shredded — legacy (no `_cek`) or blobs disabled (see type docs). */\n readonly blobResidueCollections: readonly string[]\n /**\n * Count of persisted `_idx/<field>/<recordId>` index side-cars hard-deleted\n * across the shredded records. These live under the retained\n * collection DEK, so crypto-shred alone would leave the indexed field VALUES\n * readable — `forget()` must delete them.\n */\n readonly indexPostingsPurged: number\n /**\n * `collection:id:field` entries whose persisted `_idx` side-car could NOT be\n * deleted — index residue that still leaks the indexed value under the\n * retained collection DEK. Non-empty means erasure is INCOMPLETE: retry, or\n * purge the side-car out of band.\n */\n readonly indexResidue: readonly string[]\n /**\n * Count of `_sealed[field]` slots dropped from the live store across the\n * shredded records. For slots written under `sensitive` +\n * `perRecordKeys` (the current path), the key derives off the per-record CEK,\n * so tombstoning the record — which drops `_cek` and `_sealed` — also\n * crypto-shreds the value. A legacy slot (written before per-record CEKs) keys\n * off the collection DEK instead, so dropping it removes it from the live store but a\n * pre-forget backup remains recoverable by a DEK holder (same caveat `_data`\n * carries); migrate by re-`put`ting before forgetting for full crypto-shred.\n */\n readonly sealedFieldsShredded: number\n /** Count of `_sealed_cek` host-delivery envelopes deleted (#H-1). A record sealed to an\n * at-* host via sealRecordToHost persists its raw CEK there; forget() must destroy them. */\n readonly sealedCekEnvelopesPurged: number\n /** `collection:id` whose `_sealed_cek` purge failed (residue — the host-recoverable CEK may survive). */\n readonly sealedCekResidue: readonly string[]\n /** `collection:id:field` sealed slots that were DEK-derived (legacy, written before per-record CEKs) and thus NOT crypto-shredded\n * by dropping `_cek` — the collection DEK is retained, so synced/backup copies stay decryptable (#M-1). */\n readonly sealedResidue: readonly string[]\n /** Count of `_ledger_deltas` rows hard-deleted across the shredded records (#734) — the\n * erasure twin of #729's elevate-side purge. Entry metadata (that the record was mutated,\n * at which version/timestamp/actor) is retained; only the plaintext delta content is removed. */\n readonly ledgerDeltasPurged: number\n /** `collection:id` refs whose `_ledger_deltas` purge failed — plaintext delta residue still\n * readable under the retained ledger DEK. Non-empty means erasure is INCOMPLETE. */\n readonly ledgerDeltaResidue: readonly string[]\n /** The single `op:'forget'` ledger entry appended for this erasure. */\n readonly ledgerEntry: LedgerEntry\n /** #622 — record-grain derived artifacts (MV rows, per-record derived copies) erased\n * because their source subject was forgotten. Overlay outputs are intentionally out of\n * scope here — an overlay is always sourced from an MV, never directly from a subject\n * collection, so the personal-data-bearing MV rows it reads are already erased above. */\n readonly derivedRecordsErased: number\n /** #622 — aggregate-grain targets (rollups) recomputed without the forgotten contribution. */\n readonly derivedAggregatesRecomputed: number\n /** #622 — `collection:id` derived writes SKIPPED because the target period is frozen\n * (recompute deferred; the aggregate retains the forgotten contribution — audited). */\n readonly derivedResidueFrozen: readonly string[]\n /** #650 Task 5 (#648) — referencing records tombstoned via a `'ref'` edge's `cascade` policy. */\n readonly lookupReferencesCascaded: number\n /** #650 Task 5 (#648) — referencing fields cleared via a `'ref'` edge's `nullify` policy. */\n readonly lookupReferencesNullified: number\n /** #650 Task 5 review (Important fix) — `'ref'` edges whose compare-key could NOT be resolved,\n * even from the LIVE pre-shred backing row — cascade/nullify propagation was SKIPPED for these.\n * Always empty in the ordinary case; non-empty means the skip is reported, never silent. */\n readonly lookupReferencesResidue: readonly string[]\n /** #633 — scoped-purge skip notices (opt-in `scopedPurge`, see {@link SubjectDeclaration}).\n * Always empty under the unconditional default. Non-empty means a `_sealed_cek` entry or a\n * blob scan was skipped for an undeclared collection — reported, never a silent skip. */\n readonly scopedPurgeResidue: readonly ScopedPurgeResidueNotice[]\n /** #776/#782/#785 — `collection:id` MV-output rows that survived erasure invalidation (eager\n * tombstone leg AND lazy/manual `invalidateMVAtRest`) despite belonging to the forgotten\n * subject, because the `_materializedFrom` ownership stamp could NOT be decoded (undecodable\n * under the collection's default DEK — e.g. elevated above tier 0 on a tiered output\n * collection; ownership unconfirmed — could be a plain user record on a same-collection\n * partition MV). Never erased, but surfaced here rather than silently skipped (the #724\n * posture). Non-empty means the row may still hold the forgotten/pre-elevation contribution,\n * decryptable by tier-holders. */\n readonly derivedResidueUndecodable: readonly string[]\n /** #782/#785 — `collection:id` MV-output rows that DID decode and stamp-match via\n * `_materializedFrom`, but whose erasure was declined by the #718 tier-elevation gate\n * (`_internalDelete` returned false). Ownership CONFIRMED here — a real silent survival,\n * not a stamp-mismatch skip — surfaced rather than dropped. Non-empty means a live,\n * tier-holder-decryptable copy of the forgotten contribution was deliberately retained. */\n readonly derivedResidueDeclined: readonly string[]\n}\n\n/** #633 — the two `scopedPurgeResidue` skip reasons. Single source of truth: `purge-scope.ts`\n * (the port-internal partition helpers) imports this rather than redeclaring it. */\nexport type ScopedPurgeResidueReason = 'skipped-undeclared-sealed-cek' | 'skipped-undeclared-blob-scan'\n\n/** #633 — one `ForgetResult.scopedPurgeResidue` entry: an undeclared collection's sealed-CEK\n * entries left unpurged, or its blob scan skipped entirely, under `scopedPurge`. `count` is the\n * number of `_sealed_cek` entries left in place (sealed-cek reason) or the number of refs whose\n * blob scan was skipped (blob-scan reason) — aggregated per collection across the whole call. */\nexport interface ScopedPurgeResidueNotice {\n readonly reason: ScopedPurgeResidueReason\n readonly collection: string\n readonly count: number\n}\n","/**\n * The encrypted subject index.\n *\n * GDPR crypto-shred needs to answer \"which records belong to data subject\n * X?\" portably (the index must travel with the vault/bundle) WITHOUT leaking\n * subject-equivalence to the store. The rejected alternative — an unencrypted\n * subject tag in envelope metadata — would let anyone with store access see\n * which records share a subject. Instead we keep a reserved `_subject_index`\n * collection, encrypted under its OWN DEK (`getDEK('_subject_index')`):\n *\n * - record id = `HMAC-SHA256(indexDEK, subjectId)` (M-2). A bare\n * `sha256Hex(subjectId)` would be offline-computable: an attacker with\n * store access and a candidate list (emails / customer ids are low-entropy)\n * could dictionary the hash to confirm \"subject X is present here.\" Keying\n * the id with the vault-only index DEK removes that capability — without the\n * DEK the id cannot be derived. (Legacy entries written before M-2 used the\n * bare sha256 id; the read/remove paths dual-look-up both forms.)\n * - record body = AES-GCM(JSON `{ r: [{ collection, id }], p }`) under the\n * index DEK, where `p` pads the plaintext to a bucketed length so the\n * ciphertext `_data` length does not leak the approximate record count.\n * Legacy bodies were a bare `[{ collection, id }]` array; reads accept both.\n *\n * ## Concurrency (RISK #3 — known v1 limitation)\n *\n * `addSubjectRef` / `removeSubjectRef` are read-modify-write with no CAS. The\n * design assumes a SINGLE WRITER (the noy-db single-process write model). Two\n * concurrent writers racing on the SAME subject can lose an entry (last-write\n * wins on the ref list). This is documented, not fixed in v1:\n * `rebuildSubjectIndex` performs a full scan to recover a correct index from\n * the canonical records, so a lost ref is recoverable. A CAS-backed index is\n * deferred to a later slice.\n *\n * @module\n */\nimport { buildRecordAad, buildRecordEnvelope, encrypt, openEnvelopeJson, hmacSha256Hex, sha256Hex, type EnclaveKey } from '../../kernel/enclave/index.js'\nimport type { NoydbStore, EncryptedEnvelope } from '../../kernel/types.js'\n\n/** Reserved collection holding the encrypted subject → records index. */\nexport const SUBJECT_INDEX_COLLECTION = '_subject_index'\n\n/**\n * Bucket (bytes) the encrypted ref-list plaintext is padded up to, so the\n * ciphertext `_data` length leaks only `count` rounded up to a bucket — not the\n * exact record count. 256 keeps small subjects (the common case) indistinguishable.\n */\nconst REF_LIST_BUCKET = 256\n\n/** A single record reference held in a subject's index entry. */\nexport interface SubjectRef {\n readonly collection: string\n readonly id: string\n}\n\ntype GetDEK = (collectionName: string) => Promise<EnclaveKey>\n\n/** SHA-256 hex of a UTF-8 string. The LEGACY (pre-M-2) subject-index key. */\nasync function sha256HexString(input: string): Promise<string> {\n return sha256Hex(new TextEncoder().encode(input))\n}\n\n/**\n * The subject-index record id(s) to consult for a subject, most-current first.\n *\n * - Encrypted vault: the PRIMARY id is `HMAC-SHA256(indexDEK, subjectId)` (M-2)\n * — not offline-computable. The LEGACY `sha256Hex(subjectId)` id is also\n * returned so reads/removes still find entries written before M-2 (dual-lookup).\n * - Plaintext/debug vault: no DEK to key with, so the only id is the legacy\n * sha256 form (unchanged behaviour — plaintext mode is not zero-knowledge anyway).\n */\nasync function subjectKeys(getDEK: GetDEK, encrypted: boolean, subjectId: string): Promise<string[]> {\n const legacy = await sha256HexString(subjectId)\n if (!encrypted) return [legacy]\n const dek = await getDEK(SUBJECT_INDEX_COLLECTION)\n const keyed = await hmacSha256Hex(dek, new TextEncoder().encode(subjectId))\n return keyed === legacy ? [keyed] : [keyed, legacy]\n}\n\n/** The id new writes land under (keyed when encrypted, else legacy sha256). */\nasync function primarySubjectKey(getDEK: GetDEK, encrypted: boolean, subjectId: string): Promise<string> {\n return (await subjectKeys(getDEK, encrypted, subjectId))[0]!\n}\n\n/** Parse a stored ref-list body: new padded `{ r, p }` wrapper OR legacy bare array. */\nfunction parseRefs(json: string): SubjectRef[] {\n const parsed = JSON.parse(json) as SubjectRef[] | { r: SubjectRef[] }\n return Array.isArray(parsed) ? parsed : parsed.r\n}\n\n/** Serialize + pad the ref list to a bucket boundary (encrypted vaults only). */\nfunction serializeRefs(refs: SubjectRef[]): string {\n const base = JSON.stringify({ r: refs, p: '' })\n const pad = Math.ceil(base.length / REF_LIST_BUCKET) * REF_LIST_BUCKET - base.length\n return JSON.stringify({ r: refs, p: ' '.repeat(pad) })\n}\n\n/** Read + decrypt the ref list at a SINGLE index key. Returns `[]` when absent. */\nasync function readRefs(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n key: string,\n): Promise<SubjectRef[]> {\n const env = await adapter.get(vault, SUBJECT_INDEX_COLLECTION, key)\n if (!env || !env._data) return []\n if (!encrypted) return parseRefs(env._data)\n const dek = await getDEK(SUBJECT_INDEX_COLLECTION)\n const json = await openEnvelopeJson({ collection: SUBJECT_INDEX_COLLECTION, id: key }, env, dek)\n return parseRefs(json)\n}\n\n/** Encrypt + write a ref list for a subject under its derived key. */\nasync function writeRefs(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n key: string,\n refs: SubjectRef[],\n): Promise<void> {\n const identity = { collection: SUBJECT_INDEX_COLLECTION, id: key, version: 1 }\n let env: EncryptedEnvelope\n if (!encrypted) {\n // Plaintext/debug vault: keep the bare-array form (no padding needed).\n env = buildRecordEnvelope(identity, { iv: '', data: JSON.stringify(refs) })\n } else {\n const dek = await getDEK(SUBJECT_INDEX_COLLECTION)\n const { iv, data } = await encrypt(serializeRefs(refs), dek, buildRecordAad(identity))\n env = buildRecordEnvelope(identity, { iv, data })\n }\n await adapter.put(vault, SUBJECT_INDEX_COLLECTION, key, env)\n}\n\n/**\n * Add a `{ collection, id }` ref to a subject's index entry (idempotent —\n * a duplicate ref is not appended). Read-modify-write; see the concurrency\n * note in the module docstring.\n */\nexport async function addSubjectRef(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n subjectId: string,\n ref: SubjectRef,\n): Promise<void> {\n const key = await primarySubjectKey(getDEK, encrypted, subjectId)\n const refs = await readRefs(adapter, vault, getDEK, encrypted, key)\n if (refs.some((r) => r.collection === ref.collection && r.id === ref.id)) return\n refs.push(ref)\n await writeRefs(adapter, vault, getDEK, encrypted, key, refs)\n}\n\n/**\n * Remove a `{ collection, id }` ref from a subject's index entry. When the\n * last ref is removed the (now empty) entry is deleted so the store holds no\n * residual key for an erased subject.\n */\nexport async function removeSubjectRef(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n subjectId: string,\n ref: SubjectRef,\n): Promise<void> {\n // Dual-lookup: drop the ref from BOTH the keyed (M-2) and the legacy sha256\n // entry, so a pre-M-2 subject is still fully erased.\n for (const key of await subjectKeys(getDEK, encrypted, subjectId)) {\n const refs = await readRefs(adapter, vault, getDEK, encrypted, key)\n const next = refs.filter((r) => !(r.collection === ref.collection && r.id === ref.id))\n if (next.length === refs.length) continue\n if (next.length === 0) {\n await adapter.delete(vault, SUBJECT_INDEX_COLLECTION, key)\n } else {\n await writeRefs(adapter, vault, getDEK, encrypted, key, next)\n }\n }\n}\n\n/**\n * Look up every record ref for a subject. Returns `[]` when none exist. Unions\n * the keyed (M-2) and legacy sha256 entries (dual-lookup), deduplicated, so a\n * subject indexed before M-2 is still fully found.\n */\nexport async function lookupSubject(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n subjectId: string,\n): Promise<SubjectRef[]> {\n const keys = await subjectKeys(getDEK, encrypted, subjectId)\n const seen = new Set<string>()\n const out: SubjectRef[] = []\n for (const key of keys) {\n for (const ref of await readRefs(adapter, vault, getDEK, encrypted, key)) {\n const dedup = `${ref.collection}\\u0000${ref.id}`\n if (seen.has(dedup)) continue\n seen.add(dedup)\n out.push(ref)\n }\n }\n return out\n}\n\n/**\n * Rebuild the entire subject index from the canonical records (the recovery\n * path for the documented read-modify-write race). Scans each declared\n * collection, reads `record[subjectField]` (dotted path), and rewrites the\n * index from scratch. Tombstoned (already-shredded) records contribute no\n * ref — their body is gone, so they cannot be re-indexed.\n *\n * `decodeRecord` decrypts an envelope to a plain object (or returns null for\n * a tombstone / unreadable record); supplied by the caller so this module\n * stays free of Collection internals.\n */\nexport async function rebuildSubjectIndex(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n subjects: Readonly<Record<string, string>>,\n decodeRecord: (collection: string, id: string, env: EncryptedEnvelope) => Promise<Record<string, unknown> | null>,\n): Promise<number> {\n // Drop every existing index entry first so removed refs don't linger.\n const existing = await adapter.list(vault, SUBJECT_INDEX_COLLECTION)\n for (const k of existing) {\n await adapter.delete(vault, SUBJECT_INDEX_COLLECTION, k)\n }\n\n // subjectId → refs, accumulated across all declared collections.\n const bySubject = new Map<string, SubjectRef[]>()\n for (const [collection, field] of Object.entries(subjects)) {\n const ids = await adapter.list(vault, collection)\n for (const id of ids) {\n if (id.startsWith('_')) continue\n const env = await adapter.get(vault, collection, id)\n if (!env || !env._data) continue // missing or tombstone\n const record = await decodeRecord(collection, id, env)\n if (record === null) continue\n const subjectValue = readDottedPath(record, field)\n if (subjectValue === undefined || subjectValue === null) continue\n const subjectId = coerceSubjectId(subjectValue)\n const list = bySubject.get(subjectId) ?? []\n list.push({ collection, id })\n bySubject.set(subjectId, list)\n }\n }\n\n let entries = 0\n for (const [subjectId, refs] of bySubject) {\n const key = await primarySubjectKey(getDEK, encrypted, subjectId)\n await writeRefs(adapter, vault, getDEK, encrypted, key, refs)\n entries++\n }\n return entries\n}\n\n/**\n * Coerce a read subject-field value to a stable string id. Primitives use\n * their natural string form; objects/arrays are JSON-stringified so structural\n * subjects still get a deterministic key (avoids the `[object Object]` trap).\n */\nexport function coerceSubjectId(value: unknown): string {\n if (typeof value === 'string') return value\n if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {\n return String(value)\n }\n return JSON.stringify(value)\n}\n\n/** Read a (possibly dotted) field path from a plain record. */\nexport function readDottedPath(record: Record<string, unknown>, field: string): unknown {\n if (!field.includes('.')) return record[field]\n let cursor: unknown = record\n for (const segment of field.split('.')) {\n if (cursor === null || cursor === undefined) return undefined\n cursor = (cursor as Record<string, unknown>)[segment]\n }\n return cursor\n}\n"],"mappings":";;;;;;;;;;;;;;AAuEO,IAAM,YAA4B,EAAE,UAAU,CAAC,EAAE;;;ACjCjD,IAAM,2BAA2B;AAOxC,IAAM,kBAAkB;AAWxB,eAAe,gBAAgB,OAAgC;AAC7D,SAAO,UAAU,IAAI,YAAY,EAAE,OAAO,KAAK,CAAC;AAClD;AAWA,eAAe,YAAY,QAAgB,WAAoB,WAAsC;AACnG,QAAM,SAAS,MAAM,gBAAgB,SAAS;AAC9C,MAAI,CAAC,UAAW,QAAO,CAAC,MAAM;AAC9B,QAAM,MAAM,MAAM,OAAO,wBAAwB;AACjD,QAAM,QAAQ,MAAM,cAAc,KAAK,IAAI,YAAY,EAAE,OAAO,SAAS,CAAC;AAC1E,SAAO,UAAU,SAAS,CAAC,KAAK,IAAI,CAAC,OAAO,MAAM;AACpD;AAGA,eAAe,kBAAkB,QAAgB,WAAoB,WAAoC;AACvG,UAAQ,MAAM,YAAY,QAAQ,WAAW,SAAS,GAAG,CAAC;AAC5D;AAGA,SAAS,UAAU,MAA4B;AAC7C,QAAM,SAAS,KAAK,MAAM,IAAI;AAC9B,SAAO,MAAM,QAAQ,MAAM,IAAI,SAAS,OAAO;AACjD;AAGA,SAAS,c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G;AACtC,QAAI,WAAW,QAAQ,WAAW,OAAW,QAAO;AACpD,aAAU,OAAmC,OAAO;AAAA,EACtD;AACA,SAAO;AACT;","names":[]}
@@ -8,14 +8,14 @@ import {
8
8
  rotateKeys,
9
9
  verifyPrompt,
10
10
  verifyTypedEcho
11
- } from "./chunk-ERB6NDDW.js";
11
+ } from "./chunk-RKDH6L53.js";
12
12
  import {
13
13
  NoAccessError,
14
14
  NoydbError,
15
15
  ValidationError,
16
16
  WrongEchoError,
17
17
  WrongPromptError
18
- } from "./chunk-HNGSV2YC.js";
18
+ } from "./chunk-P7L3OQLL.js";
19
19
 
20
20
  // src/with-party/team/echo-ceremony.ts
21
21
  async function beginEchoUnlock(store, vault, opts) {
@@ -114,4 +114,4 @@ export {
114
114
  MemoryDeviceSealProvider,
115
115
  withTeam
116
116
  };
117
- //# sourceMappingURL=chunk-WQDTCJ6W.js.map
117
+ //# sourceMappingURL=chunk-VEX2BQVX.js.map
@@ -7,28 +7,28 @@ import {
7
7
  deriveSchemaManifest,
8
8
  loadSchemaManifestEntry,
9
9
  saveSchemaManifest
10
- } from "./chunk-G5APARUV.js";
10
+ } from "./chunk-E6VDPBE3.js";
11
11
  import {
12
12
  MANIFEST_COLLECTION
13
13
  } from "./chunk-EPFF7LOX.js";
14
14
  import {
15
15
  loadFence,
16
16
  saveFence
17
- } from "./chunk-TOAIYQJR.js";
17
+ } from "./chunk-HJRTFXAA.js";
18
18
  import {
19
19
  derivePersistedSchema
20
- } from "./chunk-Z45YRGFO.js";
20
+ } from "./chunk-N7YAQKAO.js";
21
21
  import {
22
22
  loadPersistedSchemaEntry,
23
23
  savePersistedSchema
24
- } from "./chunk-4MC5JRRX.js";
24
+ } from "./chunk-YVTADFTC.js";
25
25
  import {
26
26
  envelopePayloadHash
27
- } from "./chunk-VW6ZZGCG.js";
27
+ } from "./chunk-RNSC2ARR.js";
28
28
  import {
29
29
  ManifestConflictError,
30
30
  isConflictError
31
- } from "./chunk-HNGSV2YC.js";
31
+ } from "./chunk-P7L3OQLL.js";
32
32
 
33
33
  // src/with-shape/persisted-schemas/field-ids.ts
34
34
  var BASE32URL_ALPHABET = "abcdefghijklmnopqrstuvwxyz234567";
@@ -257,4 +257,4 @@ export {
257
257
  persistClassifiedMarker,
258
258
  persistSatelliteMarker
259
259
  };
260
- //# sourceMappingURL=chunk-7VHY5E3X.js.map
260
+ //# sourceMappingURL=chunk-VH2W6BOG.js.map
@@ -0,0 +1,201 @@
1
+ import {
2
+ PERIODS_COLLECTION
3
+ } from "./chunk-HTHRCGWP.js";
4
+ import {
5
+ canonicalJson,
6
+ sha256Hex
7
+ } from "./chunk-RNSC2ARR.js";
8
+ import {
9
+ isDeleteMarker
10
+ } from "./chunk-ZVAFJQZB.js";
11
+ import {
12
+ PeriodClosedError,
13
+ ValidationError
14
+ } from "./chunk-P7L3OQLL.js";
15
+
16
+ // src/with-audit/periods/periods.ts
17
+ function resolveReopenState(events) {
18
+ let lastReopen;
19
+ let reclosedAfter;
20
+ let reopenCount = 0;
21
+ for (const e of events) {
22
+ if (e.op === "reopen") {
23
+ lastReopen = e;
24
+ reclosedAfter = void 0;
25
+ reopenCount++;
26
+ } else if (lastReopen !== void 0) {
27
+ reclosedAfter = e.at;
28
+ }
29
+ }
30
+ if (!lastReopen) return { reopenCount };
31
+ return {
32
+ reopenedAt: lastReopen.at,
33
+ reopenedBy: lastReopen.by,
34
+ ...lastReopen.until !== void 0 && { reopenedUntil: lastReopen.until },
35
+ ...lastReopen.reason !== void 0 && { reopenReason: lastReopen.reason },
36
+ ...reclosedAfter !== void 0 && { reclosedAt: reclosedAfter },
37
+ reopenCount
38
+ };
39
+ }
40
+ function isEffectivelyReopened(period, nowIso) {
41
+ if (period.reopenedAt === void 0) return false;
42
+ if (period.reclosedAt !== void 0 && period.reclosedAt >= period.reopenedAt) return false;
43
+ if (period.reopenedUntil !== void 0 && nowIso > period.reopenedUntil) return false;
44
+ return true;
45
+ }
46
+ function resolvePeriodKey(name, partition) {
47
+ if (!partition || partition.length === 0) return name;
48
+ const parts = partition.map((p) => {
49
+ if (typeof p === "number" && !Number.isFinite(p)) {
50
+ throw new ValidationError(`period partition component must be a finite number, got ${p}`);
51
+ }
52
+ const s = String(p);
53
+ if (s === "") {
54
+ throw new ValidationError("period partition component must not be empty");
55
+ }
56
+ return encodeURIComponent(s);
57
+ });
58
+ return `${name}\0${parts.join("/")}`;
59
+ }
60
+ function samePartition(a, b) {
61
+ const x = a ?? [];
62
+ const y = b ?? [];
63
+ if (x.length !== y.length) return false;
64
+ return x.every((v, i) => String(v) === String(y[i]));
65
+ }
66
+ async function loadPeriods(adapter, vault, decrypt) {
67
+ const ids = await adapter.list(vault, PERIODS_COLLECTION);
68
+ const records = [];
69
+ for (const id of ids) {
70
+ const env = await adapter.get(vault, PERIODS_COLLECTION, id);
71
+ if (env) records.push(await decrypt(id, env));
72
+ }
73
+ records.sort((a, b) => a.closedAt.localeCompare(b.closedAt));
74
+ return records;
75
+ }
76
+ async function chainAnchor(records, partition) {
77
+ const inTimeline = records.filter((p) => samePartition(p.partition, partition));
78
+ const last = inTimeline[inTimeline.length - 1];
79
+ if (!last) return { priorPeriodHash: "" };
80
+ const hash = await sha256Hex(canonicalJson(last));
81
+ return { priorPeriodName: last.name, priorPeriodHash: hash };
82
+ }
83
+ function assertTsWritable(existing, incomingRecord, closedPeriods, scope) {
84
+ const partitionOf = (r) => {
85
+ if (!r || !scope?.resolve) return void 0;
86
+ return scope.resolve(scope.collection, r);
87
+ };
88
+ const existingRecord = existing?.record ?? null;
89
+ const existingPartition = partitionOf(existingRecord);
90
+ const incomingPartition = partitionOf(incomingRecord);
91
+ const now = (/* @__PURE__ */ new Date()).toISOString();
92
+ for (const p of closedPeriods) {
93
+ if (p.kind !== "closed") continue;
94
+ if (isEffectivelyReopened(p, now)) continue;
95
+ if (p.dateField) {
96
+ const checkRecord = (label, r, recordPartition) => {
97
+ if (!r) return;
98
+ if (!samePartition(recordPartition, p.partition)) return;
99
+ const v = r[p.dateField];
100
+ if (typeof v === "string" && v <= p.endDate) {
101
+ throw new PeriodClosedError(p.name, p.endDate, `${label}[${p.dateField}]=${v}`);
102
+ }
103
+ };
104
+ checkRecord("existing", existingRecord, existingPartition);
105
+ checkRecord("incoming", incomingRecord, incomingPartition);
106
+ continue;
107
+ }
108
+ if (!samePartition(existingPartition, p.partition)) continue;
109
+ const existingTs = existing?.ts ?? null;
110
+ if (existingTs !== null && existingTs <= p.endDate) {
111
+ throw new PeriodClosedError(p.name, p.endDate, existingTs);
112
+ }
113
+ }
114
+ }
115
+ function validatePeriodName(name, existing, partition) {
116
+ if (name.length === 0) {
117
+ throw new ValidationError("Period name cannot be empty.");
118
+ }
119
+ resolvePeriodKey(name, partition);
120
+ if (existing.some((p) => p.name === name && samePartition(p.partition, partition))) {
121
+ const where = partition && partition.length > 0 ? ` in partition [${partition.join(", ")}]` : "";
122
+ throw new ValidationError(`Period "${name}" already exists${where}.`);
123
+ }
124
+ }
125
+ async function appendPeriodLedgerEntry(ledger, actor, envelope, name, collection = PERIODS_COLLECTION) {
126
+ if (!ledger) return;
127
+ const { envelopePayloadHash } = await import("./ledger-62CEPRPX.js");
128
+ await ledger.append({
129
+ op: "put",
130
+ collection,
131
+ id: name,
132
+ version: envelope._v,
133
+ actor,
134
+ payloadHash: await envelopePayloadHash(envelope)
135
+ });
136
+ }
137
+ async function purgeMarkersOn(store, vault, before, collections) {
138
+ const snapshot = await store.loadAll(vault);
139
+ let removed = 0;
140
+ for (const [coll, records] of Object.entries(snapshot)) {
141
+ if (collections && !collections.includes(coll)) continue;
142
+ for (const [id, env] of Object.entries(records)) {
143
+ if (isDeleteMarker(env) && env._ts < before) {
144
+ await store.delete(vault, coll, id);
145
+ removed++;
146
+ }
147
+ }
148
+ }
149
+ return removed;
150
+ }
151
+
152
+ // src/with-audit/periods/active.ts
153
+ function withPeriods(options) {
154
+ const subjects = options?.subjects;
155
+ const partitionOf = subjects ? (collection, record) => subjects[collection]?.(record) : void 0;
156
+ return {
157
+ loadPeriods,
158
+ chainAnchor,
159
+ assertTsWritable,
160
+ validatePeriodName,
161
+ appendPeriodLedgerEntry,
162
+ ...partitionOf !== void 0 && { partitionOf }
163
+ };
164
+ }
165
+
166
+ // src/with-audit/periods/strategy.ts
167
+ var NOT_ENABLED = new Error(
168
+ 'Accounting periods require the periods strategy. Import `{ withPeriods }` from "@noy-db/hub/periods" and pass it to `createNoydb({ periodsStrategy: withPeriods() })`.'
169
+ );
170
+ var NO_PERIODS = {
171
+ async loadPeriods() {
172
+ return [];
173
+ },
174
+ async chainAnchor() {
175
+ return { priorPeriodHash: "" };
176
+ },
177
+ assertTsWritable() {
178
+ },
179
+ validatePeriodName() {
180
+ throw NOT_ENABLED;
181
+ },
182
+ async appendPeriodLedgerEntry() {
183
+ throw NOT_ENABLED;
184
+ }
185
+ };
186
+
187
+ export {
188
+ NO_PERIODS,
189
+ resolveReopenState,
190
+ isEffectivelyReopened,
191
+ resolvePeriodKey,
192
+ samePartition,
193
+ loadPeriods,
194
+ chainAnchor,
195
+ assertTsWritable,
196
+ validatePeriodName,
197
+ appendPeriodLedgerEntry,
198
+ purgeMarkersOn,
199
+ withPeriods
200
+ };
201
+ //# sourceMappingURL=chunk-VHVMJWM6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/with-audit/periods/periods.ts","../src/with-audit/periods/active.ts","../src/with-audit/periods/strategy.ts"],"sourcesContent":["/**\n * Accounting-period closure + opening.\n *\n * A closed period seals every record whose envelope `_ts` is at or\n * before the period's `endDate`: further writes (`put` / `delete`)\n * against such records throw {@link PeriodClosedError}. The period\n * itself is stored as a record in the reserved `_periods` collection\n * and written through the normal ledger-instrumented path, so every\n * closure appends a tamper-evident entry to the vault's hash chain.\n *\n * ## Closure model\n *\n * ```\n * vault.closePeriod({ name: 'FY2026-Q1', endDate: '2026-03-31' })\n * └─► PeriodRecord written to _periods/<name>\n * ├─ priorPeriodName / priorPeriodHash — chain to last close\n * ├─ closedAt / closedBy — provenance\n * └─ normal ledger append fires (LedgerStore.append)\n * ```\n *\n * Enforcement (`assertTsWritable`) is vault-local: the Vault caches\n * the list of closed periods on first read and consults that cache in\n * the `Collection.put` / `.delete` path via the `periodGuard` hook.\n *\n * ## Opening model\n *\n * ```\n * vault.openPeriod({\n * name: 'FY2026-Q2',\n * startDate: '2026-04-01',\n * fromPeriod: 'FY2026-Q1',\n * carryForward: async (priorView) => Record<string, Record<string, unknown>>,\n * })\n * ```\n *\n * `carryForward` receives a read-only `VaultInstant` anchored at the\n * prior period's `endDate` (built via `vault.at(endDate)`) so the\n * callback can compute closing aggregates from the sealed state. The\n * returned `{ [collectionName]: { [id]: record } }` map is written\n * before the new `PeriodRecord` lands — opening balances materialise\n * as normal records with fresh timestamps that fall outside every\n * closed period.\n *\n * ## Freeze\n *\n * ```\n * vault.freezePeriod('FY2026-Q1')\n * └─► physically purges delete markers whose write-time falls inside\n * the closed period's window (via the #589 `_purgeDeleteMarkers`\n * seam), then records the fact:\n * ├─ PeriodFreezeRecord written to _period_freezes/<name>\n * └─ normal ledger append fires (LedgerStore.append)\n * ```\n *\n * The chained `_periods/<name>` record is never mutated — `frozenAt` /\n * `frozenBy` / `purgedMarkerCount` are merged onto the returned\n * `PeriodRecord` at read time from the companion, so a tamper with the\n * freeze can never break the inter-period hash chain. Freezing is\n * terminal (a closed period, once frozen, stays frozen) and idempotent\n * (a second call is a no-op that returns the same merged record without\n * re-purging or re-appending a ledger entry). Freeze does NOT purge\n * forget-tombstones (GDPR crypto-shred erasure evidence), `_history`\n * versions, or live records — the delete-markers-only seam leaves all\n * three untouched by construction.\n *\n * Freeze purges the LOCAL adapter only. On a synced vault, markers already\n * pushed to sync targets survive there, and a later pull re-imports them\n * (benign — they still read deleted, but the space isn't reclaimed). A\n * re-imported marker keeps its original `_ts` (inside the already-frozen\n * period's window), so — like any late-booked delete — it is reclaimed by\n * the NEXT period's freeze, whose window covers it; freeze stays terminal\n * and does NOT re-purge an already-frozen period (#611). Sweeping the sync\n * targets themselves is a cross-target-purge concern deferred to the\n * cold-archival spec. Purging re-opens the #589 resurrection window for a\n * peer offline since before the cutoff, which is why the closed period is\n * the operator-asserted safe-point that gates the call.\n *\n * A period whose purge window has not fully elapsed cannot be frozen —\n * `freezePeriod` throws rather than purge markers for deletes that may not\n * have converged yet (#610).\n *\n * ## Archive\n *\n * ```\n * vault.archivePeriod('FY2026-Q1')\n * └─► relocates the closed period's in-window records (those with\n * `_ts < periodExclusiveUpperBound(endDate)`) from the hot store to\n * the configured cold tier (routeStore's `cold` route), then records:\n * ├─ PeriodArchiveRecord written to _period_archives/<name>\n * └─ a ledger entry attributed to _period_archives\n * ```\n *\n * Archival is NON-DESTRUCTIVE: routeStore reads fall through to the cold\n * tier on a hot miss, so an archived record still reads normally. It is\n * therefore gated only on `closed` (not `frozen`) — it does not re-open the\n * #589 resurrection window and needs no convergence safe-point. Freeze\n * (purge markers) and archive (relocate records) are independent and compose\n * in either order. Like freeze, archival keeps the chained `_periods/<name>`\n * record byte-immutable (state lives in the companion) and is idempotent.\n *\n * Bounds by write-time `_ts`, NOT business date: the store tier sees only\n * encrypted envelopes. A record with an in-period business date but a later\n * `_ts` (late-booked) archives at the NEXT period's archive — the same rule\n * freeze uses for late-booked delete markers. Requires a `routeStore` with a\n * cold route (`age: { cold }`); throws otherwise.\n *\n * Read cost: with `withLazy()` (per-id reads) archived records are truly\n * cold — fetched from cold only on access. In the default hydrated mode,\n * `loadAll` merges the cold store, so archived records still load into RAM\n * on vault open (hot-tier STORAGE is reclaimed; RAM is not). Summaries\n * (`_`-prefixed) always stay hot.\n *\n * ## Target-purge\n *\n * ```\n * vault.purgePeriodTargets('FY2026-Q1')\n * └─► sweeps delete markers (`_ts < periodExclusiveUpperBound(endDate)`) off\n * the vault's PUSH-ONLY sync targets (backup/archive roles), then records:\n * ├─ PeriodTargetPurgeRecord written to _period_target_purges/<name>\n * └─ a ledger entry attributed to _period_target_purges\n * ```\n *\n * Extends freeze's local marker purge to the vault's own remote sinks.\n * `sync-peer` (bidirectional) targets are SKIPPED: purging a marker there\n * re-opens the #589 resurrection window for a client offline before the\n * cutoff, an assertion no single vault can verify. Backup/archive targets are\n * push-only — never pulled from into convergence — so sweeping their markers\n * is safe. Requires the period be frozen first (closed → frozen →\n * target-purged) so the local safe-point is already established. Idempotent\n * once run; a vault with no push-only targets writes no companion and is\n * re-runnable (so a target added later is still swept). Single-vault only —\n * fleet-wide purge across sovereign vaults is klum's concern over\n * `@noy-db/hub/cargo`.\n *\n * ## Not covered\n *\n * - Partial re-opening of a closed period. If an auditor needs to\n * make a correction inside a sealed period, the sanctioned path is\n * a compensating entry in the NEW period, not an unlock of the\n * old one.\n * - Automatic period rollover. `closePeriod` / `openPeriod` are\n * deliberately explicit operator calls so the caller decides when\n * the boundary lands.\n *\n * @module\n */\n\nimport type { NoydbStore, EncryptedEnvelope } from '../../kernel/types.js'\nimport type { LedgerStore } from '../../with-commit/history/ledger/index.js'\nimport { sha256Hex, canonicalJson } from '../../with-commit/history/ledger/index.js'\nimport { isDeleteMarker } from '../../kernel/enclave/index.js'\nimport { PeriodClosedError, ValidationError } from '../../kernel/errors.js'\n\n// The reserved collection names + `periodExclusiveUpperBound` moved to the\n// dependency-light `window.ts` so the sync engine's period-scoped pull (#807)\n// can import them without this module's ledger imports; re-exported here so\n// every existing import path keeps working.\nexport {\n PERIODS_COLLECTION,\n PERIOD_FREEZES_COLLECTION,\n PERIOD_ARCHIVES_COLLECTION,\n PERIOD_TARGET_PURGES_COLLECTION,\n PERIOD_REOPENS_COLLECTION,\n periodExclusiveUpperBound,\n} from './window.js'\nimport { PERIODS_COLLECTION } from './window.js'\n\n/**\n * Companion record recording that a closed period was frozen (its delete\n * markers physically purged). Stored in {@link PERIOD_FREEZES_COLLECTION},\n * keyed by period name — kept OFF the hash-chained `_periods/<name>` record so\n * freeze never alters the inter-period chain.\n */\nexport interface PeriodFreezeRecord {\n readonly period: string\n readonly frozenAt: string\n readonly frozenBy: string\n readonly purgedMarkerCount: number\n}\n\n/**\n * Companion record noting that a closed period was cold-archived (its\n * in-window records physically relocated hot → cold). Stored in\n * {@link PERIOD_ARCHIVES_COLLECTION}, keyed by period name — kept OFF the\n * hash-chained `_periods/<name>` record so archive never alters the chain.\n */\nexport interface PeriodArchiveRecord {\n readonly period: string\n readonly archivedAt: string\n readonly archivedBy: string\n readonly archivedRecordCount: number\n}\n\n/** Per-target count of delete markers purged off one push-only sync target (#615). */\nexport interface TargetPurgeCount {\n readonly label?: string\n readonly role: 'backup' | 'archive'\n readonly purgedCount: number\n}\n\n/**\n * One entry in a period's append-only reopen/reclose log (#1022).\n *\n * Real accounting close is a three-state lifecycle — open / closed / reopened\n * — not a one-way door. A month gets closed, a missing invoice arrives or a\n * filing is rejected, the month is reopened, corrected, and reclosed. The audit\n * value is not the ability to write again; it is the chain being able to say\n * *closed at T1, reopened at T2 by U, reclosed at T3*.\n */\nexport interface PeriodReopenEvent {\n readonly op: 'reopen' | 'reclose'\n /** ISO timestamp the event was recorded. */\n readonly at: string\n /** userId of the keyring that performed it. */\n readonly by: string\n /**\n * `reopen` only — ISO instant after which the period re-seals on its own,\n * with nobody acting. Absent means the window stays open until an explicit\n * `reclosePeriod`.\n */\n readonly until?: string\n /** Free-text justification, carried verbatim into the audit trail. */\n readonly reason?: string\n}\n\n/**\n * Companion holding a period's reopen/reclose history (#1022). Stored in\n * {@link PERIOD_REOPENS_COLLECTION}, keyed by the period's storage key — kept\n * OFF the hash-chained `_periods/<name>` record for the same reason freeze and\n * archive are: reopening must never rewrite the close, or the chain that proves\n * the close happened is the very thing the reopen destroys.\n *\n * `events` is APPEND-ONLY. Where the other companions are single-shot and\n * idempotent, this one accumulates, because the cycle repeats.\n */\nexport interface PeriodReopenRecord {\n readonly period: string\n readonly partition?: PeriodPartition\n readonly events: readonly PeriodReopenEvent[]\n}\n\n/**\n * Collapse an append-only reopen log into the return-only fields merged onto a\n * {@link PeriodRecord} on read.\n *\n * Expiry is deliberately NOT resolved here: `reopenedUntil` is carried through\n * verbatim and compared against the clock at write-guard time, so a bounded\n * window re-seals on its own without anything having to run.\n *\n * @internal\n */\nexport function resolveReopenState(events: readonly PeriodReopenEvent[]): {\n reopenedAt?: string\n reopenedBy?: string\n reopenedUntil?: string\n reopenReason?: string\n reclosedAt?: string\n reopenCount: number\n} {\n let lastReopen: PeriodReopenEvent | undefined\n let reclosedAfter: string | undefined\n let reopenCount = 0\n for (const e of events) {\n if (e.op === 'reopen') {\n lastReopen = e\n reclosedAfter = undefined\n reopenCount++\n } else if (lastReopen !== undefined) {\n reclosedAfter = e.at\n }\n }\n if (!lastReopen) return { reopenCount }\n return {\n reopenedAt: lastReopen.at,\n reopenedBy: lastReopen.by,\n ...(lastReopen.until !== undefined && { reopenedUntil: lastReopen.until }),\n ...(lastReopen.reason !== undefined && { reopenReason: lastReopen.reason }),\n ...(reclosedAfter !== undefined && { reclosedAt: reclosedAfter }),\n reopenCount,\n }\n}\n\n/**\n * Is this period writable right now on account of a reopen? (#1022)\n *\n * Three ways to be sealed again: never reopened, explicitly reclosed after the\n * last reopen, or a bounded window that has elapsed. The clock is read by the\n * caller and passed in, so the guard and any diagnostic agree on one instant.\n *\n * @internal\n */\nexport function isEffectivelyReopened(period: PeriodRecord, nowIso: string): boolean {\n if (period.reopenedAt === undefined) return false\n if (period.reclosedAt !== undefined && period.reclosedAt >= period.reopenedAt) return false\n if (period.reopenedUntil !== undefined && nowIso > period.reopenedUntil) return false\n return true\n}\n\n/**\n * Companion record noting that a closed+frozen period's delete markers were\n * swept off the vault's push-only sync targets (#615). Stored in\n * {@link PERIOD_TARGET_PURGES_COLLECTION}, keyed by period name — kept OFF the\n * hash-chained `_periods/<name>` record so target-purge never alters the chain.\n */\nexport interface PeriodTargetPurgeRecord {\n readonly period: string\n readonly purgedAt: string\n readonly purgedBy: string\n readonly targets: readonly TargetPurgeCount[]\n}\n\n/**\n * Scope tuple for a period timeline (#1005).\n *\n * Identical in shape and semantics to `SequenceOptions.partition`: a\n * partitioned timeline is always disjoint from any unpartitioned one, and from\n * every other tuple. `['acme', 'vat']` and `['acme', 'wht']` are two\n * independent close calendars for the same subject — which is the whole point,\n * since sub-ledgers for one legal entity and one month routinely close on\n * different statutory deadlines.\n */\nexport type PeriodPartition = readonly (string | number)[]\n\n/**\n * Resolve the `_periods` storage key for a (name, partition) pair.\n *\n * Deliberately the same encoding as `resolveSequenceKey`: `name` verbatim when\n * unpartitioned, else `${name}\\x00${parts}` with each component\n * `encodeURIComponent`d and `'/'`-joined. The null-byte separator cannot occur\n * in a period name, so a partitioned key never collides with an unpartitioned\n * one; URI-encoding keeps `['a/b']` distinct from `['a','b']`.\n *\n * @throws {ValidationError} on an empty component or a non-finite number.\n * @internal\n */\nexport function resolvePeriodKey(name: string, partition?: PeriodPartition): string {\n if (!partition || partition.length === 0) return name\n const parts = partition.map((p) => {\n if (typeof p === 'number' && !Number.isFinite(p)) {\n throw new ValidationError(`period partition component must be a finite number, got ${p}`)\n }\n const s = String(p)\n if (s === '') {\n throw new ValidationError('period partition component must not be empty')\n }\n return encodeURIComponent(s)\n })\n return `${name}\\x00${parts.join('/')}`\n}\n\n/**\n * Do two partitions denote the same timeline? Absent and empty both mean \"the\n * unpartitioned timeline\", so they compare equal.\n *\n * @internal\n */\nexport function samePartition(a?: PeriodPartition, b?: PeriodPartition): boolean {\n const x = a ?? []\n const y = b ?? []\n if (x.length !== y.length) return false\n return x.every((v, i) => String(v) === String(y[i]))\n}\n\n/**\n * Resolves a record to the timeline that governs it. Supplied by\n * `withPeriods({ subjects })`; returns `undefined` for any collection with no\n * mapping, which is what keeps an unconfigured vault on the single vault-wide\n * timeline it has always had.\n *\n * @internal\n */\nexport type PartitionResolver = (\n collection: string,\n record: Record<string, unknown>,\n) => PeriodPartition | undefined\n\n/**\n * Stored record for one closed or opened accounting period. One entry\n * per period, keyed by `name` in the reserved `_periods` collection.\n *\n * The hash chain between periods is computed at read time by\n * `loadPeriods()` — each record carries the name + hash of its\n * predecessor so a tamper with any period's record breaks the chain\n * into the next one, the same way the ledger's `prevHash` works.\n */\nexport interface PeriodRecord {\n /**\n * Human-readable name (e.g., `'FY2026-Q1'`). Unique per PARTITION — two\n * timelines may each carry a `'2026-06'`, which is the normal case when one\n * vault serves several subjects (#1005). Unique per vault when unpartitioned.\n */\n readonly name: string\n /**\n * The timeline this period belongs to. Absent = the vault-wide timeline.\n * Two periods with the same `name` and different `partition` are unrelated:\n * separate hash chains, separate close state, and the write guard applies\n * each only to records that resolve to its own tuple.\n */\n readonly partition?: PeriodPartition\n /**\n * Role discriminator. A period is `'closed'` from the moment its\n * `closedAt` is recorded; `'opened'` marks a period whose opening\n * entries have been carried forward via {@link openPeriod}. Many\n * workflows will produce one opened period per closed period (the\n * opened one is the SUCCESSOR — its `startDate` equals the prior\n * `endDate + 1 day`).\n */\n readonly kind: 'closed' | 'opened'\n /** ISO date — inclusive upper bound for records belonging to this period. */\n readonly endDate: string\n /** ISO date — lower bound (present on opened periods only). */\n readonly startDate?: string\n /**\n * Record field carrying the business date (e.g. `'date'` on an\n * invoice, `'paidAt'` on a payment). The guard compares\n * `record[dateField]` against `endDate` — NOT the envelope `_ts`.\n * Accounting entries booked late (business date `2026-01-15`,\n * write-time `2026-04-22`) still get sealed when Q1 closes at\n * `2026-03-31` because the comparison uses the business date.\n *\n * Optional for backwards compat. When absent, the guard falls back\n * to envelope `_ts` — that's a write-time seal, appropriate for\n * content that doesn't carry a logical business date (e.g. system\n * settings) but almost never right for accounting ledgers.\n */\n readonly dateField?: string\n /** ISO timestamp recorded at `closePeriod()` / `openPeriod()` call time. */\n readonly closedAt: string\n /** userId of the keyring that invoked the close/open. */\n readonly closedBy: string\n /** Name of the prior period this one chains to, if any. */\n readonly priorPeriodName?: string\n /** sha256(canonicalJson(priorPeriod)) — empty for the first period. */\n readonly priorPeriodHash: string\n /**\n * Opened periods only — the names of the collections whose\n * carry-forward aggregates were written by {@link openPeriod}.\n * Recorded for auditability so a future `verifyPeriodChain()` can\n * cross-check the opening balances against the closing snapshot.\n */\n readonly openingCollections?: readonly string[]\n /** #604 return-only — merged from the `_period_freezes/<name>` companion on\n * read; NEVER written into the stored `_periods/<name>` record (would break\n * the hash chain). Absent = not yet frozen. */\n readonly frozenAt?: string\n readonly frozenBy?: string\n readonly purgedMarkerCount?: number\n /** #613 return-only — merged from the `_period_archives/<name>` companion on\n * read; NEVER written into the stored `_periods/<name>` record. Absent = not\n * yet archived. */\n readonly archivedAt?: string\n readonly archivedBy?: string\n readonly archivedRecordCount?: number\n /** #615 return-only — merged from the `_period_target_purges/<name>` companion\n * on read; NEVER written into the stored `_periods/<name>` record. Absent =\n * target-purge not yet run (or the vault has no push-only targets). */\n readonly targetsPurgedAt?: string\n readonly targetsPurgedBy?: string\n readonly targetsPurged?: readonly TargetPurgeCount[]\n /** #1022 return-only — collapsed from the `_period_reopens/<key>` append-only\n * log on read; NEVER written into the stored `_periods/<name>` record, so a\n * reopen cannot disturb the inter-period hash chain. Absent = never reopened.\n * `reclosedAt` present (and >= `reopenedAt`) means the window was closed\n * again explicitly; `reopenedUntil` in the past means it lapsed on its own.\n * Use {@link isEffectivelyReopened} rather than reading these directly. */\n readonly reopenedAt?: string\n readonly reopenedBy?: string\n readonly reopenedUntil?: string\n readonly reopenReason?: string\n readonly reclosedAt?: string\n /** How many times this period has been reopened, ever. */\n readonly reopenCount?: number\n}\n\n/** Options for `vault.closePeriod()`. */\nexport interface ClosePeriodOptions {\n /** Human-readable name. Must not collide with an existing period. */\n readonly name: string\n /**\n * Inclusive upper cutoff. A record is sealed when its\n * `record[dateField]` (or, if absent, the envelope `_ts`) is at or\n * before this ISO timestamp.\n */\n readonly endDate: string\n /**\n * Record field carrying the business date used for period\n * membership. Recommended for accounting workflows — e.g. an\n * invoice booked late (write-time after close) is still sealed\n * when its `invoice.date` falls inside the closed period.\n *\n * Omit to use envelope `_ts` (write-time seal). This fallback\n * rarely matches real-world accounting semantics; prefer passing\n * an explicit `dateField`.\n */\n readonly dateField?: string\n /**\n * Close only this timeline (#1005). Omit for the vault-wide timeline.\n *\n * ```ts\n * vault.closePeriod({\n * name: '2026-06', endDate: '2026-06-30', dateField: 'issuedAt',\n * partition: [clientId, 'vat'],\n * })\n * ```\n *\n * Which records the resulting seal applies to is decided by the\n * `subjects` map passed to `withPeriods()` — without one, no record ever\n * resolves to a partition and a partitioned close seals nothing.\n */\n readonly partition?: PeriodPartition\n}\n\n/** Options for `vault.openPeriod()`. */\nexport interface OpenPeriodOptions<TCollections = Record<string, Record<string, unknown>>> {\n /** Human-readable name for the new period. Must be unique. */\n readonly name: string\n /**\n * The timeline to open in. Must match the partition of `fromPeriod` — a\n * period cannot chain across timelines, since each carries its own hash\n * chain (#1005).\n */\n readonly partition?: PeriodPartition\n /** ISO lower bound of the new period (usually prior `endDate + 1 day`). */\n readonly startDate: string\n /**\n * Name of the prior CLOSED period this one chains from. The prior\n * period's record is verified to exist and to be `kind: 'closed'`;\n * its `endDate` is made available to the `carryForward` callback.\n */\n readonly fromPeriod: string\n /**\n * Receives a read-only facade over the vault's CURRENT state,\n * plus the prior period's `endDate`. Accounting semantics: after\n * a period closes, records with `record[dateField] <= endDate`\n * are frozen — current state equals closing state, so a caller\n * can compute closing balances by querying the live collection\n * with a `where('date', '<=', priorEndDate)` filter.\n *\n * Returns opening-balance records keyed by collection name.\n * Example:\n *\n * ```ts\n * carryForward: async (ctx) => {\n * const closing = await ctx.collection<Journal>('journal')\n * .query().where('date', '<=', ctx.priorEndDate).toArray()\n * const opening: Record<string, Journal> = {}\n * for (const entry of closing) {\n * opening[`OB-${entry.id}`] = { ...entry, date: '2026-04-01' }\n * }\n * return { journal: opening }\n * }\n * ```\n */\n readonly carryForward: (\n ctx: CarryForwardContext,\n ) => Promise<TCollections> | TCollections\n}\n\n/**\n * Context passed to `OpenPeriodOptions.carryForward`. Exposes a\n * read-only subset of the live vault (`collection(name).get/list`)\n * plus the prior period's `endDate` so business-date filters can\n * be built by the caller.\n *\n * Writes go via the return value, not via the facade — the\n * `collection()` here is deliberately restricted to reads.\n */\nexport interface CarryForwardContext {\n /** The prior period's `endDate` — the boundary of the closing snapshot. */\n readonly priorEndDate: string\n /** Read-only collection facade over current vault state. */\n collection<T = unknown>(name: string): ReadOnlyCollection<T>\n}\n\n/** Minimum read surface exposed to `carryForward`. */\nexport interface ReadOnlyCollection<T> {\n get(id: string): Promise<T | null>\n list(): Promise<T[]>\n}\n\n/**\n * Load every period record currently stored on the adapter.\n * Decrypting is the caller's responsibility (we return plain records\n * so the vault can use its own `_periods` DEK).\n *\n * @internal — called by Vault methods that need the closed-period\n * cache. Not part of the public API surface.\n */\nexport async function loadPeriods(\n adapter: NoydbStore,\n vault: string,\n decrypt: (id: string, envelope: EncryptedEnvelope) => Promise<PeriodRecord>,\n): Promise<PeriodRecord[]> {\n const ids = await adapter.list(vault, PERIODS_COLLECTION)\n const records: PeriodRecord[] = []\n for (const id of ids) {\n const env = await adapter.get(vault, PERIODS_COLLECTION, id)\n if (env) records.push(await decrypt(id, env))\n }\n // Stable order by closedAt so chain verification is reproducible.\n records.sort((a, b) => a.closedAt.localeCompare(b.closedAt))\n return records\n}\n\n/**\n * Given the current ordered period list, pick the last entry that\n * belongs to the hash chain — used as the `priorPeriodHash` anchor\n * for the next closure/opening.\n *\n * @internal\n */\nexport async function chainAnchor(\n records: readonly PeriodRecord[],\n partition?: PeriodPartition,\n): Promise<{ priorPeriodName?: string; priorPeriodHash: string }> {\n // #1005 — each timeline carries its OWN chain. Anchoring a partitioned close\n // to whatever happened to be written last vault-wide would interleave\n // unrelated subjects into one chain, so verifying client A's June would\n // depend on client B never having closed in between.\n const inTimeline = records.filter((p) => samePartition(p.partition, partition))\n const last = inTimeline[inTimeline.length - 1]\n if (!last) return { priorPeriodHash: '' }\n const hash = await sha256Hex(canonicalJson(last as unknown as Record<string, unknown>))\n return { priorPeriodName: last.name, priorPeriodHash: hash }\n}\n\n/**\n * Throw `PeriodClosedError` if the record being touched falls within\n * any closed period.\n *\n * Three signals, evaluated per period:\n *\n * 1. If the period declares a `dateField`, the guard reads\n * `record[dateField]` on BOTH the existing (prior) record AND the\n * incoming (new) record. Either comparing `<= endDate` triggers\n * the error — callers cannot slide a record into a closed period\n * by editing its date field.\n * 2. If the period has no `dateField`, the guard falls back to the\n * envelope `_ts` of the existing record. Fresh inserts (no\n * existing envelope) pass.\n * 3. For a delete, only the existing side is checked.\n *\n * @internal\n */\nexport function assertTsWritable(\n existing: { ts: string | null; record: Record<string, unknown> | null } | null,\n incomingRecord: Record<string, unknown> | null,\n closedPeriods: readonly PeriodRecord[],\n scope?: { collection: string; resolve?: PartitionResolver },\n): void {\n // #1005 — a period only governs records that resolve to ITS timeline. With no\n // resolver (the default `withPeriods()`), nothing resolves to a partition, so\n // every record sits on the vault-wide timeline exactly as before and a\n // partitioned period governs nothing.\n const partitionOf = (r: Record<string, unknown> | null): PeriodPartition | undefined => {\n if (!r || !scope?.resolve) return undefined\n return scope.resolve(scope.collection, r)\n }\n const existingRecord = existing?.record ?? null\n const existingPartition = partitionOf(existingRecord)\n const incomingPartition = partitionOf(incomingRecord)\n // One instant for the whole check, so a bounded reopen window cannot expire\n // between two periods in the same loop and seal a write half-way.\n const now = new Date().toISOString()\n\n for (const p of closedPeriods) {\n if (p.kind !== 'closed') continue\n // #1022 — a reopened period is writable again. This is the ONLY thing a\n // reopen does: it withdraws the period's veto. It cannot grant a write that\n // some other gate forbids, because the guard bus ANDs every handler and\n // record-level guards are registered ahead of this one.\n if (isEffectivelyReopened(p, now)) continue\n if (p.dateField) {\n const checkRecord = (\n label: string,\n r: Record<string, unknown> | null,\n recordPartition: PeriodPartition | undefined,\n ): void => {\n if (!r) return\n // Both sides are checked under their OWN partition, which is what stops\n // a write from sliding a record either INTO or OUT OF a sealed\n // timeline by rewriting the fields the subject mapping reads.\n if (!samePartition(recordPartition, p.partition)) return\n const v = r[p.dateField!]\n if (typeof v === 'string' && v <= p.endDate) {\n throw new PeriodClosedError(p.name, p.endDate, `${label}[${p.dateField}]=${v}`)\n }\n }\n checkRecord('existing', existingRecord, existingPartition)\n checkRecord('incoming', incomingRecord, incomingPartition)\n continue\n }\n // Fallback: write-time seal via envelope _ts. Scoped by the EXISTING\n // record's partition — `_ts` belongs to the stored envelope, so the\n // incoming side has no write-time of its own to compare.\n if (!samePartition(existingPartition, p.partition)) continue\n const existingTs = existing?.ts ?? null\n if (existingTs !== null && existingTs <= p.endDate) {\n throw new PeriodClosedError(p.name, p.endDate, existingTs)\n }\n }\n}\n\n/**\n * Sanity-check a proposed period name + endDate against existing\n * records. Shared by closePeriod / openPeriod so the two pathways\n * produce identical diagnostics.\n *\n * @internal\n */\nexport function validatePeriodName(\n name: string,\n existing: readonly PeriodRecord[],\n partition?: PeriodPartition,\n): void {\n if (name.length === 0) {\n throw new ValidationError('Period name cannot be empty.')\n }\n // Validates the components as a side effect — an empty or non-finite\n // component must be rejected at the call, not encoded into a storage key.\n resolvePeriodKey(name, partition)\n // #1005 — uniqueness is per TIMELINE. `'2026-06'` in `['A','vat']` does not\n // collide with `'2026-06'` in `['B','vat']`.\n if (existing.some((p) => p.name === name && samePartition(p.partition, partition))) {\n const where = partition && partition.length > 0\n ? ` in partition [${partition.join(', ')}]`\n : ''\n throw new ValidationError(`Period \"${name}\" already exists${where}.`)\n }\n}\n\n/**\n * Wire a reserved-collection ledger append for a period record. The\n * period itself is stored via the adapter as an encrypted envelope;\n * the ledger entry is a normal `put` with the period's payloadHash,\n * so period closures inherit the chain's tamper-evidence.\n *\n * @internal\n */\nexport async function appendPeriodLedgerEntry(\n ledger: LedgerStore | null,\n actor: string,\n envelope: EncryptedEnvelope,\n name: string,\n collection: string = PERIODS_COLLECTION,\n): Promise<void> {\n if (!ledger) return\n const { envelopePayloadHash } = await import('../../with-commit/history/ledger/index.js')\n await ledger.append({\n op: 'put',\n collection,\n id: name,\n version: envelope._v,\n actor,\n payloadHash: await envelopePayloadHash(envelope),\n })\n}\n\n/**\n * @internal #615. Sweep delete markers with `_ts < before` off ANY store\n * (the vault's local adapter, or a push-only sync target). Returns the count\n * removed. Shared by `vault._purgeDeleteMarkers` (local) and\n * `vault._purgePeriodTargets` (push-only targets).\n */\nexport async function purgeMarkersOn(\n store: NoydbStore,\n vault: string,\n before: string,\n collections?: string[],\n): Promise<number> {\n const snapshot = await store.loadAll(vault)\n let removed = 0\n for (const [coll, records] of Object.entries(snapshot)) {\n if (collections && !collections.includes(coll)) continue\n for (const [id, env] of Object.entries(records)) {\n if (isDeleteMarker(env) && env._ts < before) {\n await store.delete(vault, coll, id)\n removed++\n }\n }\n }\n return removed\n}\n","/**\n * Active periods strategy factory. Only reachable through the\n * `@noy-db/hub/periods` subpath.\n */\n\nimport {\n loadPeriods,\n chainAnchor,\n assertTsWritable,\n validatePeriodName,\n appendPeriodLedgerEntry,\n} from './periods.js'\nimport type { PeriodPartition, PartitionResolver } from './periods.js'\nimport type { PeriodsStrategy } from './strategy.js'\n\n/** Options for {@link withPeriods}. */\nexport interface WithPeriodsOptions {\n /**\n * Maps a collection to the timeline each of its records belongs to (#1005) —\n * the answer to \"which close calendar governs THIS record\".\n *\n * ```ts\n * withPeriods({\n * subjects: { receipts: (r) => [r.clientId, layerOf(r)] },\n * })\n * ```\n *\n * Same shape as `withForget({ subjects })`, which answers the same question\n * for erasure. A collection with no entry — and every collection when\n * `subjects` is omitted entirely — stays on the vault-wide timeline, so an\n * existing vault behaves exactly as it did before partitions existed.\n *\n * Return `undefined` from a mapper to put an individual record back on the\n * vault-wide timeline (e.g. a record that predates the field the mapping\n * reads).\n */\n readonly subjects?: Readonly<\n Record<string, (record: Record<string, unknown>) => PeriodPartition | undefined>\n >\n}\n\n/**\n * Build the default periods strategy. Pass into\n * `createNoydb({ periodsStrategy: withPeriods() })` to enable\n * `vault.closePeriod()` / `vault.openPeriod()` / write-guards.\n *\n * Pass `subjects` to run more than one close calendar in a single vault — see\n * {@link WithPeriodsOptions.subjects}.\n */\nexport function withPeriods(options?: WithPeriodsOptions): PeriodsStrategy {\n const subjects = options?.subjects\n const partitionOf: PartitionResolver | undefined = subjects\n ? (collection, record) => subjects[collection]?.(record)\n : undefined\n\n return {\n loadPeriods,\n chainAnchor,\n assertTsWritable,\n validatePeriodName,\n appendPeriodLedgerEntry,\n ...(partitionOf !== undefined && { partitionOf }),\n }\n}\n","/**\n * Strategy seam for the optional accounting-periods service. Core\n * imports `PeriodsStrategy` type-only + `NO_PERIODS` stub; the real\n * `loadPeriods` / `chainAnchor` / `assertTsWritable` /\n * `validatePeriodName` / `appendPeriodLedgerEntry` functions are\n * only reachable via `withPeriods()` in `./active.ts`.\n *\n * Applications that never call `vault.closePeriod()` /\n * `vault.openPeriod()` ship none of the ~363 LOC.\n *\n * @internal\n */\n\nimport type { EncryptedEnvelope, NoydbStore } from '../../kernel/types.js'\nimport type { LedgerStore } from '../../with-commit/history/ledger/store.js'\nimport type { PeriodRecord, PeriodPartition, PartitionResolver } from './periods.js'\n\n/**\n * @internal\n */\nexport interface PeriodsStrategy {\n loadPeriods(\n adapter: NoydbStore,\n vault: string,\n decrypt: (id: string, envelope: EncryptedEnvelope) => Promise<PeriodRecord>,\n ): Promise<PeriodRecord[]>\n chainAnchor(records: readonly PeriodRecord[], partition?: PeriodPartition): Promise<{\n priorPeriodName?: string\n priorPeriodHash: string\n }>\n assertTsWritable(\n existing: { ts: string | null; record: Record<string, unknown> | null } | null,\n incoming: Record<string, unknown> | null,\n periods: readonly PeriodRecord[],\n scope?: { collection: string; resolve?: PartitionResolver },\n ): void\n validatePeriodName(\n name: string,\n existing: readonly PeriodRecord[],\n partition?: PeriodPartition,\n ): void\n /**\n * Record → timeline resolver built from `withPeriods({ subjects })` (#1005).\n * `undefined` when the caller configured no subjects, which keeps every\n * record on the vault-wide timeline.\n */\n readonly partitionOf?: PartitionResolver\n appendPeriodLedgerEntry(\n ledger: LedgerStore | null,\n actor: string,\n envelope: EncryptedEnvelope,\n periodName: string,\n collection?: string,\n ): Promise<void>\n}\n\n/**\n * No-periods stub. `loadPeriods` returns `[]`; the write-guards do\n * nothing (vaults without closed periods never reject writes);\n * `validatePeriodName` / `appendPeriodLedgerEntry` throw because\n * those paths are only reached when the user explicitly called\n * `closePeriod()` / `openPeriod()` — if they did that without the\n * strategy, they need to wire it.\n *\n * @internal\n */\nconst NOT_ENABLED = new Error(\n 'Accounting periods require the periods strategy. Import ' +\n '`{ withPeriods }` from \"@noy-db/hub/periods\" and pass it to ' +\n '`createNoydb({ periodsStrategy: withPeriods() })`.',\n)\n\nexport const NO_PERIODS: PeriodsStrategy = {\n async loadPeriods() { return [] },\n async chainAnchor() { return { priorPeriodHash: '' } },\n assertTsWritable() {},\n validatePeriodName() { throw NOT_ENABLED },\n async appendPeriodLedgerEntry() { throw NOT_ENABLED },\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA2PO,SAAS,mBAAmB,QAOjC;AACA,MAAI;AACJ,MAAI;AACJ,MAAI,cAAc;AAClB,aAAW,KAAK,QAAQ;AACtB,QAAI,EAAE,OAAO,UAAU;AACrB,mBAAa;AACb,sBAAgB;AAChB;AAAA,IACF,WAAW,eAAe,QAAW;AACnC,sBAAgB,EAAE;AAAA,IACpB;AAAA,EACF;AACA,MAAI,CAAC,WAAY,QAAO,EAAE,YAAY;AACtC,SAAO;AAAA,IACL,YAAY,WAAW;AAAA,IACvB,YAAY,WAAW;AAAA,IACvB,GAAI,WAAW,UAAU,UAAa,EAAE,eAAe,WAAW,MAAM;AAAA,IACxE,GAAI,WAAW,WAAW,UAAa,EAAE,cAAc,WAAW,OAAO;AAAA,IACzE,GAAI,kBAAkB,UAAa,EAAE,YAAY,cAAc;AAAA,IAC/D;AAAA,EACF;AACF;AAWO,SAAS,sBAAsB,QAAsB,QAAyB;AACnF,MAAI,OAAO,eAAe,OAAW,QAAO;AAC5C,MAAI,OAAO,eAAe,UAAa,OAAO,cAAc,OAAO,WAAY,QAAO;AACtF,MAAI,OAAO,kBAAkB,UAAa,SAAS,OAAO,cAAe,QAAO;AAChF,SAAO;AACT;AAuCO,SAAS,iBAAiB,MAAc,WAAqC;AAClF,MAA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AAa,EAAE,YAAY;AAAA,EACjD;AACF;;;ACGA,IAAM,cAAc,IAAI;AAAA,EACtB;AAGF;AAEO,IAAM,aAA8B;AAAA,EACzC,MAAM,cAAc;AAAE,WAAO,CAAC;AAAA,EAAE;AAAA,EAChC,MAAM,cAAc;AAAE,WAAO,EAAE,iBAAiB,GAAG;AAAA,EAAE;AAAA,EACrD,mBAAmB;AAAA,EAAC;AAAA,EACpB,qBAAqB;AAAE,UAAM;AAAA,EAAY;AAAA,EACzC,MAAM,0BAA0B;AAAE,UAAM;AAAA,EAAY;AACtD;","names":[]}
@@ -3,7 +3,7 @@ import {
3
3
  InvalidKeyError,
4
4
  TamperedError,
5
5
  ValidationError
6
- } from "./chunk-HNGSV2YC.js";
6
+ } from "./chunk-P7L3OQLL.js";
7
7
 
8
8
  // src/kernel/enclave/crypto.ts
9
9
  var PBKDF2_ITERATIONS = 6e5;
@@ -142,11 +142,15 @@ async function unwrapCek(wrappedBase64, dek) {
142
142
  async function importCek(rawKey) {
143
143
  return subtle.importKey("raw", rawKey, { name: "AES-GCM", length: KEY_BITS }, false, ["decrypt"]);
144
144
  }
145
- async function encrypt(plaintext, dek) {
145
+ async function encrypt(plaintext, dek, aad) {
146
146
  const iv = generateIV();
147
147
  const encoded = new TextEncoder().encode(plaintext);
148
148
  const ciphertext = await subtle.encrypt(
149
- { name: "AES-GCM", iv },
149
+ {
150
+ name: "AES-GCM",
151
+ iv,
152
+ ...aad !== void 0 && { additionalData: aad }
153
+ },
150
154
  dek,
151
155
  encoded
152
156
  );
@@ -155,25 +159,41 @@ async function encrypt(plaintext, dek) {
155
159
  data: bufferToBase64(ciphertext)
156
160
  };
157
161
  }
158
- async function decrypt(ivBase64, dataBase64, dek) {
162
+ async function decrypt(ivBase64, dataBase64, dek, aad) {
159
163
  const iv = base64ToBuffer(ivBase64);
160
164
  const ciphertext = base64ToBuffer(dataBase64);
161
165
  try {
162
166
  const plaintext = await subtle.decrypt(
163
- { name: "AES-GCM", iv },
167
+ {
168
+ name: "AES-GCM",
169
+ iv,
170
+ ...aad !== void 0 && { additionalData: aad }
171
+ },
164
172
  dek,
165
173
  ciphertext
166
174
  );
167
175
  return new TextDecoder().decode(plaintext);
168
176
  } catch (err) {
169
177
  if (err instanceof Error && err.name === "OperationError") {
170
- throw new TamperedError();
178
+ throw new TamperedError(...await classifyTagFailure(iv, ciphertext, dek, aad));
171
179
  }
172
180
  throw new DecryptionError(
173
181
  err instanceof Error ? err.message : "Decryption failed"
174
182
  );
175
183
  }
176
184
  }
185
+ async function classifyTagFailure(iv, ciphertext, dek, aad) {
186
+ if (aad === void 0) return [];
187
+ try {
188
+ await subtle.decrypt({ name: "AES-GCM", iv }, dek, ciphertext);
189
+ } catch {
190
+ return [];
191
+ }
192
+ return [
193
+ "This record was sealed BEFORE record-identity binding (#1041) and cannot be read by this version. Its body decrypts correctly under the record key, so this is a data-format transition, not tampering \u2014 but it also means the record predates authenticated metadata. There is no migration path; see noy-db #1100.",
194
+ "unbound-legacy-format"
195
+ ];
196
+ }
177
197
  async function encryptBytes(data, dek) {
178
198
  const iv = generateIV();
179
199
  const ciphertext = await subtle.encrypt(
@@ -419,4 +439,4 @@ export {
419
439
  bufferToBase64,
420
440
  base64ToBuffer
421
441
  };
422
- //# sourceMappingURL=chunk-VCETL77O.js.map
442
+ //# sourceMappingURL=chunk-VJ4B3ZXY.js.map