@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
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/kernel/enclave/crypto.ts"],"sourcesContent":["/**\n * Cryptographic primitives — thin wrappers around the Web Crypto API.\n *\n * ## Design principle\n *\n * **Zero npm crypto dependencies.** Every operation uses `globalThis.crypto.subtle`,\n * which is available natively in Node.js ≥ 18, all modern browsers, and\n * Deno/Bun. This avoids supply-chain risk from third-party crypto packages and\n * ensures the library stays auditable.\n *\n * ## Algorithms\n *\n * | Use case | Algorithm | Parameters |\n * |----------|-----------|------------|\n * | Key derivation | PBKDF2-SHA256 | 600,000 iterations, 32-byte salt |\n * | Record encryption | AES-256-GCM | 12-byte random IV per operation |\n * | DEK wrapping | AES-KW (RFC 3394) | 256-bit KEK |\n * | Binary encrypt | AES-256-GCM | same as record encryption |\n * | Integrity | HMAC-SHA256 | for presence channels |\n * | Content hash | SHA-256 | for ledger and bundle integrity |\n *\n * ## Key lifecycle\n *\n * ```\n * secret + salt\n * └─► deriveKey() → KEK (CryptoKey, extractable: false)\n * └─► wrapKey() → wrapped DEK bytes [stored in keyring]\n * └─► unwrapKey() → DEK (CryptoKey) [memory only during session]\n * └─► encrypt() / decrypt() → ciphertext / plaintext\n * ```\n *\n * IVs are generated fresh by {@link generateIV} on every encrypt call.\n * Reusing an IV with the same key would break GCM's authentication guarantee —\n * this function should be the only place IVs are produced.\n *\n * @module\n */\n\nimport { DecryptionError, InvalidKeyError, TamperedError, ValidationError } from '../errors.js'\n\n/**\n * **EnclaveKey** — the opaque key type at the enclave seam.\n *\n * In noy-db's reference enclave this is `CryptoKey` (the Web Crypto API's\n * key handle). A fork's enclave redefines this alias to its own key\n * representation (e.g. `type EnclaveKey = null` for a keyless HSM-backed\n * fork) — outside `kernel/enclave/**`, every consumer must treat it as\n * opaque: never construct, inspect, or serialize it directly, only pass it\n * between barrel functions (`encrypt`/`decrypt`/`wrapKey`/`unwrapKey`/…).\n */\nexport type EnclaveKey = CryptoKey\n\nconst PBKDF2_ITERATIONS = 600_000\nconst SALT_BYTES = 32\nconst IV_BYTES = 12\nconst KEY_BITS = 256\n\nconst subtle = globalThis.crypto.subtle\n\n// ─── Key Derivation ────────────────────────────────────────────────────\n\n/** Derive a KEK from a secret and salt using PBKDF2-SHA256. */\nexport async function deriveKey(\n secret: string,\n salt: Uint8Array,\n): Promise<CryptoKey> {\n return deriveKekFromMaterial(new TextEncoder().encode(secret), salt)\n}\n\n/**\n * Shared PBKDF2 → AES-KW derivation core. `material` is the raw\n * pre-KDF input bytes (a UTF-8 phrase for standard mode, an\n * AG-1-encoded 3-part structure for echo mode).\n */\nasync function deriveKekFromMaterial(\n material: Uint8Array,\n salt: Uint8Array,\n): Promise<CryptoKey> {\n const keyMaterial = await subtle.importKey('raw', material as BufferSource, 'PBKDF2', false, ['deriveKey'])\n return subtle.deriveKey(\n { name: 'PBKDF2', salt: salt as BufferSource, iterations: PBKDF2_ITERATIONS, hash: 'SHA-256' },\n keyMaterial,\n { name: 'AES-KW', length: KEY_BITS },\n false,\n ['wrapKey', 'unwrapKey'],\n )\n}\n\n/** One three-part echo secret: prompt (typed) → echo (revealed) → key (typed). */\nexport interface EchoSecretParts {\n readonly prompt: string\n readonly echo: string\n readonly key: string\n}\n\n/**\n * Domain context for the AG-1 encoding. The leading `0xFF` is the load-bearing\n * byte: it is not a legal UTF-8 lead byte, so `TextEncoder` can never emit it —\n * no string's UTF-8 encoding can equal an AG-1 encoding, whatever the string.\n */\nconst ECHO_KDF_CONTEXT = new Uint8Array([0xff, ...new TextEncoder().encode('noydb-echo-secret-v1')])\n\n/**\n * AG-1 encoding: domain context + 4-byte big-endian length prefix per\n * part. Two independent guarantees make a single typed string unable to\n * derive an echo vault's KEK (spec AG-1):\n *\n * 1. The `0xFF` context prefix — UTF-8 never produces that byte, so the\n * encoding is provably not the encoding of ANY string (not merely of\n * no separator-joined form).\n * 2. Structural length prefixes — part boundaries are key material, so\n * re-splitting the same characters changes the derived KEK.\n *\n * @throws ValidationError when any part is not a string — the single\n * chokepoint every echo KEK derivation and block mint passes through, so a\n * malformed parts object cannot be `TextEncoder`-coerced into key material.\n */\nexport function encodeEchoParts(parts: EchoSecretParts): Uint8Array {\n for (const name of ['prompt', 'echo', 'key'] as const) {\n if (typeof parts?.[name] !== 'string') {\n throw new ValidationError('echo secret parts must be three strings: prompt, echo, key')\n }\n }\n const enc = new TextEncoder()\n const segments = [parts.prompt, parts.echo, parts.key].map((p) => enc.encode(p))\n const total = ECHO_KDF_CONTEXT.length + segments.reduce((n, s) => n + 4 + s.length, 0)\n const out = new Uint8Array(total)\n out.set(ECHO_KDF_CONTEXT, 0)\n let offset = ECHO_KDF_CONTEXT.length\n for (const s of segments) {\n new DataView(out.buffer).setUint32(offset, s.length, false)\n out.set(s, offset + 4)\n offset += 4 + s.length\n }\n return out\n}\n\n/** Derive the tier-1 KEK from a 3-part echo secret (spec: KEK from ALL parts). */\nexport async function deriveEchoKey(\n parts: EchoSecretParts,\n salt: Uint8Array,\n): Promise<CryptoKey> {\n return deriveKekFromMaterial(encodeEchoParts(parts), salt)\n}\n\n/**\n * Which AES algorithm/usage a {@link deriveSecretKey} result is for:\n * `'aes-kw'` mints a key-wrapping key (`wrapKey`/`unwrapKey`, e.g. for\n * KEK derivation); `'aes-gcm'` mints a direct encrypt/decrypt key (e.g.\n * for the wrap-DEKs primitive in `with-party/team/wrapped-deks.ts`).\n */\nexport type SecretKeyUsage = 'aes-kw' | 'aes-gcm'\n\n/**\n * Derive a non-extractable AES key from a secret/credential and salt\n * via PBKDF2-SHA256, generalizing {@link deriveKey}'s AES-KW derivation to\n * also cover AES-GCM-usage keys. Callers pin their own `iterations` and\n * `keyUsage` so an existing call site's exact parameters (and thus its\n * derived-key bytes) are preserved verbatim when migrated onto this\n * shared primitive — this is call-site consolidation, not a KDF change.\n */\nexport async function deriveSecretKey(\n secret: string,\n salt: Uint8Array,\n params: { iterations: number; keyUsage: SecretKeyUsage },\n): Promise<CryptoKey> {\n const keyMaterial = await subtle.importKey(\n 'raw',\n new TextEncoder().encode(secret),\n 'PBKDF2',\n false,\n ['deriveKey'],\n )\n\n return params.keyUsage === 'aes-gcm'\n ? subtle.deriveKey(\n {\n name: 'PBKDF2',\n salt: salt as BufferSource,\n iterations: params.iterations,\n hash: 'SHA-256',\n },\n keyMaterial,\n { name: 'AES-GCM', length: KEY_BITS },\n false,\n ['encrypt', 'decrypt'],\n )\n : subtle.deriveKey(\n {\n name: 'PBKDF2',\n salt: salt as BufferSource,\n iterations: params.iterations,\n hash: 'SHA-256',\n },\n keyMaterial,\n { name: 'AES-KW', length: KEY_BITS },\n false,\n ['wrapKey', 'unwrapKey'],\n )\n}\n\n// ─── DEK Generation ────────────────────────────────────────────────────\n\n/** Generate a random AES-256-GCM data encryption key. */\nexport async function generateDEK(): Promise<CryptoKey> {\n return subtle.generateKey(\n { name: 'AES-GCM', length: KEY_BITS },\n true, // extractable — needed for AES-KW wrapping\n ['encrypt', 'decrypt'],\n )\n}\n\n// ─── Key Wrapping ──────────────────────────────────────────────────────\n\n/** Wrap (encrypt) a DEK with a KEK using AES-KW. Returns base64 string. */\nexport async function wrapKey(dek: CryptoKey, kek: CryptoKey): Promise<string> {\n const wrapped = await subtle.wrapKey('raw', dek, kek, 'AES-KW')\n return bufferToBase64(wrapped)\n}\n\n/** Unwrap (decrypt) a DEK from base64 string using a KEK. */\nexport async function unwrapKey(\n wrappedBase64: string,\n kek: CryptoKey,\n): Promise<CryptoKey> {\n try {\n return await subtle.unwrapKey(\n 'raw',\n base64ToBuffer(wrappedBase64) as BufferSource,\n kek,\n 'AES-KW',\n { name: 'AES-GCM', length: KEY_BITS },\n true,\n ['encrypt', 'decrypt'],\n )\n } catch {\n throw new InvalidKeyError()\n }\n}\n\n// ─── Per-record CEK wrapping ───────────────────────────────────────────\n\n/**\n * Derive a **dedicated** AES-KW wrapping key from a collection/tier DEK via\n * HKDF-SHA256, used to wrap/unwrap a per-record CEK.\n *\n * The collection/tier DEKs are AES-256-**GCM** keys (usages\n * `encrypt`/`decrypt`) and cannot themselves act as an AES-KW KEK. We do NOT\n * re-import the raw DEK bytes directly as an AES-KW key — that would reuse one\n * key across two primitives (AES-GCM for `_det`/presence, AES-KW for CEK\n * wrapping), violating key separation. Instead we HKDF-derive a domain-\n * separated KW key (salt `noydb-cek-wrap`), exactly as `derivePresenceKey`\n * derives a separate presence key. The derivation is deterministic, so\n * wrapping the same CEK under the same DEK always yields identical ciphertext\n * — which is what lets an update reuse a record's stable CEK and produce a\n * byte-identical `_cek`. The KW key is independent of the DEK's GCM key.\n *\n * The DEK must be extractable (it is — `generateDEK`/`unwrapKey` mint\n * extractable keys).\n */\nasync function asKwKey(dek: CryptoKey): Promise<CryptoKey> {\n const rawDek = await subtle.exportKey('raw', dek)\n const hkdfKey = await subtle.importKey('raw', rawDek, 'HKDF', false, ['deriveBits'])\n const salt = new TextEncoder().encode('noydb-cek-wrap')\n const info = new TextEncoder().encode('v1')\n const bits = await subtle.deriveBits(\n { name: 'HKDF', hash: 'SHA-256', salt, info },\n hkdfKey,\n KEY_BITS,\n )\n return subtle.importKey('raw', bits, 'AES-KW', false, ['wrapKey', 'unwrapKey'])\n}\n\n/**\n * AES-KW-wrap a per-record CEK under a collection/tier DEK. Returns base64.\n * Deterministic over `(cek, dek)`.\n */\nexport async function wrapCek(cek: CryptoKey, dek: CryptoKey): Promise<string> {\n const kw = await asKwKey(dek)\n const wrapped = await subtle.wrapKey('raw', cek, kw, 'AES-KW')\n return bufferToBase64(wrapped)\n}\n\n/**\n * Unwrap a per-record CEK from base64 under a collection/tier DEK. Throws\n * `InvalidKeyError` if the wrapped bytes do not authenticate under the DEK.\n */\nexport async function unwrapCek(wrappedBase64: string, dek: CryptoKey): Promise<CryptoKey> {\n const kw = await asKwKey(dek)\n try {\n return await subtle.unwrapKey(\n 'raw',\n base64ToBuffer(wrappedBase64) as BufferSource,\n kw,\n 'AES-KW',\n { name: 'AES-GCM', length: KEY_BITS },\n true,\n ['encrypt', 'decrypt'],\n )\n } catch {\n throw new InvalidKeyError()\n }\n}\n\n/**\n * Import a raw 32-byte AES-256-GCM record CEK (e.g. from a sealed-CEK\n * delivery binding). Non-extractable, decrypt-only — the imported key is\n * used solely to open the record's `_iv`/`_data` body under `decrypt()`.\n */\nexport async function importCek(rawKey: Uint8Array): Promise<CryptoKey> {\n return subtle.importKey('raw', rawKey as BufferSource, { name: 'AES-GCM', length: KEY_BITS }, false, ['decrypt'])\n}\n\n// ─── Encrypt / Decrypt ─────────────────────────────────────────────────\n\nexport interface EncryptResult {\n iv: string // base64\n data: string // base64\n}\n\n/**\n * Encrypt plaintext JSON string with AES-256-GCM. Fresh IV per call.\n *\n * `aad` binds the record's identity into the auth tag (#1041) — see\n * `record-aad.ts` for what is bound and why `_v` is not. A body sealed with\n * AAD can only be opened by a reader supplying the identical bytes, which is\n * what stops an untrusted store from relocating or re-tiering an envelope.\n *\n * Optional **only while the call-site sweep is in progress**. It becomes\n * mandatory once every `encrypt`/`decrypt` pair supplies it, at which point\n * the format version bumps and the reader rejects anything unbound. Until\n * then an omitted `aad` reproduces the previous, unauthenticated behaviour.\n */\nexport async function encrypt(\n plaintext: string,\n dek: CryptoKey,\n aad?: Uint8Array,\n): Promise<EncryptResult> {\n const iv = generateIV()\n const encoded = new TextEncoder().encode(plaintext)\n\n const ciphertext = await subtle.encrypt(\n {\n name: 'AES-GCM',\n iv: iv as BufferSource,\n ...(aad !== undefined && { additionalData: aad as BufferSource }),\n },\n dek,\n encoded,\n )\n\n return {\n iv: bufferToBase64(iv),\n data: bufferToBase64(ciphertext),\n }\n}\n\n/**\n * Decrypt AES-256-GCM ciphertext. Throws on wrong key or tampered data.\n *\n * `aad` must be byte-identical to what {@link encrypt} was given, or the auth\n * tag fails and this throws `TamperedError` (#1041). Note the asymmetry that\n * makes this useful: a mismatched identity is indistinguishable from a\n * corrupted body, so relocation fails **closed** rather than returning a\n * plausible record in the wrong place.\n */\nexport async function decrypt(\n ivBase64: string,\n dataBase64: string,\n dek: CryptoKey,\n aad?: Uint8Array,\n): Promise<string> {\n const iv = base64ToBuffer(ivBase64)\n const ciphertext = base64ToBuffer(dataBase64)\n\n try {\n const plaintext = await subtle.decrypt(\n {\n name: 'AES-GCM',\n iv: iv as BufferSource,\n ...(aad !== undefined && { additionalData: aad as BufferSource }),\n },\n dek,\n ciphertext as BufferSource,\n )\n return new TextDecoder().decode(plaintext)\n } catch (err) {\n if (err instanceof Error && err.name === 'OperationError') {\n throw new TamperedError(...(await classifyTagFailure(iv, ciphertext, dek, aad)))\n }\n throw new DecryptionError(\n err instanceof Error ? err.message : 'Decryption failed',\n )\n }\n}\n\n\n/**\n * Distinguish a FORMAT TRANSITION from an attack, when the enclave can (#1103).\n *\n * ## The problem\n *\n * Since #1041 switched identity AAD on, one `TamperedError` covers at least\n * four situations: legitimate pre-binding data, a store that reconstructs an\n * envelope and drops a bound field, a CEK/rotation mismatch, and actual\n * tampering. `SECURITY.md` and the subsystem docs teach the LAST reading — so a\n * user who upgrades, hits this on their own honest data, and consults the docs\n * is told their store has been compromised.\n *\n * That is a false positive on the product's central security claim, and the\n * cost is not merely a confusing message: **a tamper alarm that cries wolf is\n * one users learn to ignore.**\n *\n * ## Why the probe is sound, and why it is NOT a downgrade\n *\n * A body sealed before #1041 carries no AAD, so it opens under an empty one.\n * Retrying that way is **positive evidence** of the legacy format rather than a\n * guess: forging a body that decrypts under this DEK requires the DEK, and an\n * untrusted store does not hold one.\n *\n * ⚠️ **Classification ONLY — the plaintext is discarded and the caller still\n * throws.** That is the entire safety argument: the outcome is identical either\n * way, so this cannot become the lenient path #1041 exists to remove. A variant\n * that RETURNED the retry's plaintext would be exactly the accept-without-AAD\n * downgrade the binding was built to prevent. Do not \"optimise\" it into one.\n *\n * Note what the honest message concedes: pre-#1041 data had no authenticated\n * metadata, so a legacy record that was ALSO tampered with reads as legacy.\n * That is not a weakening — it is an accurate statement about data that\n * genuinely never carried a binding.\n */\nasync function classifyTagFailure(\n iv: Uint8Array,\n ciphertext: Uint8Array,\n dek: CryptoKey,\n aad: Uint8Array | undefined,\n): Promise<[] | [string, 'unbound-legacy-format']> {\n // Only meaningful when AAD was supplied: with none there is no second\n // interpretation to test, and the failure is a plain tag mismatch.\n if (aad === undefined) return []\n try {\n await subtle.decrypt({ name: 'AES-GCM', iv: iv as BufferSource }, dek, ciphertext as BufferSource)\n } catch {\n return [] // no benign explanation — the security alert stands\n }\n return [\n 'This record was sealed BEFORE record-identity binding (#1041) and cannot be read by this ' +\n 'version. Its body decrypts correctly under the record key, so this is a data-format ' +\n 'transition, not tampering — but it also means the record predates authenticated metadata. ' +\n 'There is no migration path; see noy-db #1100.',\n 'unbound-legacy-format',\n ]\n}\n\n// ─── Binary Encrypt / Decrypt ────────\n\n/**\n * Encrypt raw bytes with AES-256-GCM using a fresh random IV.\n * Used by the attachment store so binary blobs avoid double base64 encoding\n * (the existing `encrypt()` function calls `TextEncoder` on a string — here\n * we pass the `Uint8Array` directly to `subtle.encrypt`).\n */\nexport async function encryptBytes(\n data: Uint8Array,\n dek: CryptoKey,\n): Promise<EncryptResult> {\n const iv = generateIV()\n const ciphertext = await subtle.encrypt(\n { name: 'AES-GCM', iv: iv as BufferSource },\n dek,\n data as unknown as BufferSource,\n )\n return {\n iv: bufferToBase64(iv),\n data: bufferToBase64(ciphertext),\n }\n}\n\n/**\n * Decrypt AES-256-GCM ciphertext back to raw bytes.\n * Counterpart to `encryptBytes`. Throws `TamperedError` on auth-tag failure.\n */\nexport async function decryptBytes(\n ivBase64: string,\n dataBase64: string,\n dek: CryptoKey,\n): Promise<Uint8Array> {\n const iv = base64ToBuffer(ivBase64)\n const ciphertext = base64ToBuffer(dataBase64)\n try {\n const plaintext = await subtle.decrypt(\n { name: 'AES-GCM', iv: iv as BufferSource },\n dek,\n ciphertext as BufferSource,\n )\n return new Uint8Array(plaintext)\n } catch (err) {\n if (err instanceof Error && err.name === 'OperationError') {\n throw new TamperedError()\n }\n throw new DecryptionError(\n err instanceof Error ? err.message : 'Decryption failed',\n )\n }\n}\n\n/**\n * SHA-256 hex digest of raw bytes. Used to derive content-addressed\n * eTags for blob deduplication. Computed on plaintext bytes\n * before compression and encryption so the eTag identifies content, not\n * ciphertext, and survives re-encryption (key rotation, re-upload).\n */\nexport async function sha256Hex(data: Uint8Array): Promise<string> {\n const hash = await subtle.digest('SHA-256', data as unknown as BufferSource)\n return Array.from(new Uint8Array(hash))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n\n// ─── HMAC-SHA-256 ─────────────────────────────\n\n/**\n * Compute HMAC-SHA-256(key, data) and return hex string.\n *\n * Used to derive content-addressed eTags that are opaque to the store:\n * ```\n * eTag = hmacSha256Hex(blobDEK, plaintext)\n * ```\n *\n * Unlike a plain SHA-256, the HMAC is keyed by the vault-shared `_blob` DEK,\n * so an attacker with store access cannot pre-compute eTags for known files.\n * Deduplication still works within a vault (same key + same content = same eTag).\n */\nexport async function hmacSha256Hex(key: CryptoKey, data: Uint8Array): Promise<string> {\n // Export AES-GCM DEK raw bytes → import as HMAC key\n const rawKey = await subtle.exportKey('raw', key)\n const hmacKey = await subtle.importKey(\n 'raw',\n rawKey,\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n )\n const sig = await subtle.sign('HMAC', hmacKey, data as unknown as BufferSource)\n return Array.from(new Uint8Array(sig))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n\n// ─── AAD-aware Binary Encrypt / Decrypt ──\n\n/**\n * Encrypt raw bytes with AES-256-GCM using Additional Authenticated Data.\n *\n * The AAD binds each chunk to its parent blob and position, preventing\n * chunk reorder, substitution, and truncation attacks:\n * ```\n * AAD = UTF-8(\"{eTag}:{chunkIndex}:{chunkCount}\")\n * ```\n *\n * The AAD is NOT stored — the reader reconstructs it from `BlobObject`\n * metadata and passes it to `decryptBytesWithAAD`.\n */\nexport async function encryptBytesWithAAD(\n data: Uint8Array,\n dek: CryptoKey,\n aad: Uint8Array,\n): Promise<EncryptResult> {\n const iv = generateIV()\n const ciphertext = await subtle.encrypt(\n {\n name: 'AES-GCM',\n iv: iv as BufferSource,\n additionalData: aad as BufferSource,\n },\n dek,\n data as unknown as BufferSource,\n )\n return {\n iv: bufferToBase64(iv),\n data: bufferToBase64(ciphertext),\n }\n}\n\n/**\n * Decrypt AES-256-GCM ciphertext with AAD verification.\n *\n * If the AAD does not match the one used at encryption time (e.g. because\n * a chunk was reordered or substituted from another blob), the GCM auth\n * tag fails and this throws `TamperedError`.\n */\nexport async function decryptBytesWithAAD(\n ivBase64: string,\n dataBase64: string,\n dek: CryptoKey,\n aad: Uint8Array,\n): Promise<Uint8Array> {\n const iv = base64ToBuffer(ivBase64)\n const ciphertext = base64ToBuffer(dataBase64)\n try {\n const plaintext = await subtle.decrypt(\n {\n name: 'AES-GCM',\n iv: iv as BufferSource,\n additionalData: aad as BufferSource,\n },\n dek,\n ciphertext as BufferSource,\n )\n return new Uint8Array(plaintext)\n } catch (err) {\n if (err instanceof Error && err.name === 'OperationError') {\n throw new TamperedError()\n }\n throw new DecryptionError(\n err instanceof Error ? err.message : 'Decryption failed',\n )\n }\n}\n\n// ─── Presence Key Derivation ──────────────────────────────\n\n/**\n * Derive an AES-256-GCM presence key from a collection DEK using HKDF-SHA256.\n *\n * The presence key is domain-separated from the data DEK by the fixed salt\n * `'noydb-presence'` and the `info` = collection name. This means:\n * - The adapter never sees the presence key.\n * - Presence payloads rotate automatically when the collection DEK is rotated.\n * - Revoked users cannot derive the new presence key after a DEK rotation.\n *\n * @param dek The collection's AES-256-GCM DEK (extractable).\n * @param collectionName Used as the HKDF `info` parameter for domain separation.\n * @returns A non-extractable AES-256-GCM key suitable for presence payload encryption.\n */\nexport async function derivePresenceKey(dek: CryptoKey, collectionName: string): Promise<CryptoKey> {\n // Step 1: export DEK raw bytes\n const rawDek = await subtle.exportKey('raw', dek)\n\n // Step 2: import as HKDF key material\n const hkdfKey = await subtle.importKey(\n 'raw',\n rawDek,\n 'HKDF',\n false,\n ['deriveBits'],\n )\n\n // Step 3: derive 256 bits with salt='noydb-presence' and info=collectionName\n const salt = new TextEncoder().encode('noydb-presence')\n const info = new TextEncoder().encode(collectionName)\n const bits = await subtle.deriveBits(\n { name: 'HKDF', hash: 'SHA-256', salt, info },\n hkdfKey,\n KEY_BITS,\n )\n\n // Step 4: import derived bits as AES-GCM key\n return subtle.importKey(\n 'raw',\n bits,\n { name: 'AES-GCM', length: KEY_BITS },\n false,\n ['encrypt', 'decrypt'],\n )\n}\n\n// ─── Sealed Field Key Derivation ──────────────────────────\n\n/**\n * Derive a **per-field** AES-256-GCM key from a collection DEK using\n * HKDF-SHA256, used to encrypt a single sensitive field into its own\n * `_sealed[field]` envelope slot (structural group-encryption).\n *\n * Domain-separated from the data DEK (and from the presence/deterministic\n * channels) by the fixed salt `'noydb-sealed'` and an `info` of\n * `JSON.stringify(['noydb-sealed', collectionName, field])`. The JSON-array\n * encoding is injective — each element is separately quoted/escaped — so\n * collection `a/sealed/b` + field `c` cannot collide with collection `a` +\n * field `b/sealed/c`. Each sensitive field gets a **distinct** key, so a\n * `_sealed[a]` ciphertext does not authenticate under field `b`'s key —\n * sealed fields are cryptographically isolated from one another. The\n * collection name keeps the same field name in two collections from sharing a\n * key, mirroring how `derivePresenceKey` / `encryptDeterministic` domain-separate.\n *\n * @param dek The collection's AES-256-GCM DEK (extractable).\n * @param collectionName Part of the HKDF `info` for domain separation.\n * @param field Sensitive field name — the rest of the `info`.\n * @returns A non-extractable AES-256-GCM key for that field's sealed slot.\n */\nexport async function deriveSealedFieldKey(\n dek: CryptoKey,\n collectionName: string,\n field: string,\n): Promise<CryptoKey> {\n const rawDek = await subtle.exportKey('raw', dek)\n const hkdfKey = await subtle.importKey('raw', rawDek, 'HKDF', false, ['deriveBits'])\n const salt = new TextEncoder().encode('noydb-sealed')\n // JSON-array encoding is injective: each element is separately quoted/\n // escaped, so collection `a/sealed/b` + field `c` cannot collide with\n // collection `a` + field `b/sealed/c`.\n const info = new TextEncoder().encode(JSON.stringify(['noydb-sealed', collectionName, field]))\n const bits = await subtle.deriveBits(\n { name: 'HKDF', hash: 'SHA-256', salt, info },\n hkdfKey,\n KEY_BITS,\n )\n return subtle.importKey(\n 'raw',\n bits,\n { name: 'AES-GCM', length: KEY_BITS },\n false,\n ['encrypt', 'decrypt'],\n )\n}\n\n/**\n * Derive a per-record sealed-field key from the record's **per-record CEK**\n * rather than the collection DEK. Same HKDF construction as\n * {@link deriveSealedFieldKey} but with salt `'noydb-sealed-cek'` (distinct\n * from `'noydb-sealed'`), so a CEK-derived key can never collide with a\n * DEK-derived one for the same `{collection, field}`.\n *\n * The point: the sealed ciphertext's only key now flows from the record's CEK.\n * Dropping the record's wrapped `_cek` (crypto-shred / `forget`) makes the key\n * — and thus `_sealed[field]` — unrecoverable, giving sealed fields the same\n * erasure guarantee `_data` already has. The CEK must be extractable (it is —\n * `unwrapCek`/`generateDEK` mint extractable keys).\n *\n * @param cek The record's AES-256-GCM CEK (extractable).\n * @param collectionName Part of the HKDF `info` for domain separation.\n * @param field Sensitive field name — the rest of the `info`.\n * @returns A non-extractable AES-256-GCM key for that field's sealed slot.\n */\nexport async function deriveSealedFieldKeyFromCek(\n cek: CryptoKey,\n collectionName: string,\n field: string,\n): Promise<CryptoKey> {\n const rawCek = await subtle.exportKey('raw', cek)\n const hkdfKey = await subtle.importKey('raw', rawCek, 'HKDF', false, ['deriveBits'])\n const salt = new TextEncoder().encode('noydb-sealed-cek')\n const info = new TextEncoder().encode(JSON.stringify(['noydb-sealed-cek', collectionName, field]))\n const bits = await subtle.deriveBits(\n { name: 'HKDF', hash: 'SHA-256', salt, info },\n hkdfKey,\n KEY_BITS,\n )\n return subtle.importKey(\n 'raw',\n bits,\n { name: 'AES-GCM', length: KEY_BITS },\n false,\n ['encrypt', 'decrypt'],\n )\n}\n\n// ─── Deterministic Encryption ────────────────────────────\n\n/**\n * Derive the collection's **dedicated deterministic-index key** from its DEK\n * via HKDF-SHA256 (L-1, #554).\n *\n * `_det` slots previously encrypted under the raw collection DEK — the same\n * key `_data` uses with a *randomized*-IV regime while `_det` uses a\n * *deterministic*-IV regime. Two IV regimes on one key is avoidable hygiene\n * debt (~2^-96 theoretical collision), so the deterministic index now gets its\n * own HKDF-separated key: salt `'noydb-det'`, info\n * `JSON.stringify(['noydb-det'])` (the injective JSON-array domain tag, same\n * convention as {@link deriveSealedFieldKey}). Per-field separation still\n * comes from the `'<collection>/<field>'` context inside\n * {@link encryptDeterministic}, exactly as before.\n *\n * The derived key stays **DEK-derived (collection-level)** on purpose: `_det`\n * is carried verbatim through per-record CEK rotation (see\n * `record-keys/sealing.ts`), so its key must not depend on the CEK. It rotates\n * with the collection DEK, like the presence key.\n *\n * The key is minted **extractable** — {@link encryptDeterministic} derives its\n * per-value IV via HKDF over the raw key bytes (an `exportKey` under the\n * hood), which a non-extractable key would forbid. Same in-memory posture as\n * the DEK itself (`generateDEK` mints extractable keys).\n *\n * @param dek The collection's AES-256-GCM DEK (extractable).\n * @returns A dedicated AES-256-GCM key for the `_det` deterministic index.\n */\nexport async function deriveDeterministicKey(dek: CryptoKey): Promise<CryptoKey> {\n const rawDek = await subtle.exportKey('raw', dek)\n const hkdfKey = await subtle.importKey('raw', rawDek, 'HKDF', false, ['deriveBits'])\n const salt = new TextEncoder().encode('noydb-det')\n const info = new TextEncoder().encode(JSON.stringify(['noydb-det']))\n const bits = await subtle.deriveBits(\n { name: 'HKDF', hash: 'SHA-256', salt, info },\n hkdfKey,\n KEY_BITS,\n )\n return subtle.importKey(\n 'raw',\n bits,\n { name: 'AES-GCM', length: KEY_BITS },\n true,\n ['encrypt', 'decrypt'],\n )\n}\n\n/**\n * Derive a deterministic 12-byte IV from `{ DEK, context, plaintext }`\n * via HKDF-SHA256. Given the same three inputs, the IV is identical, so\n * `encryptDeterministic` produces the same ciphertext on every call —\n * which is precisely what enables blind equality search on encrypted\n * fields.\n *\n * **The side channel this opens.** Two records whose field value is the\n * same produce the same ciphertext. An observer with store access can\n * therefore tell which records share a value — not *what* the value is,\n * but the equivalence class. This is the well-known trade-off of\n * deterministic encryption and is why the feature is strictly opt-in\n * per field, guarded by `acknowledgeDeterministicRisk: true` at\n * collection creation.\n *\n * The context string MUST include the collection name and field name,\n * so:\n * - The same plaintext in two different fields encrypts differently\n * (no cross-field equality leak).\n * - The same plaintext in two different collections (different DEKs)\n * encrypts differently by virtue of the key, even before HKDF\n * domain separation kicks in.\n */\nasync function deriveDeterministicIV(\n dek: CryptoKey,\n context: string,\n plaintext: string,\n): Promise<Uint8Array> {\n const rawDek = await subtle.exportKey('raw', dek)\n const hkdfKey = await subtle.importKey('raw', rawDek, 'HKDF', false, ['deriveBits'])\n const salt = new TextEncoder().encode('noydb-deterministic-v1')\n const info = new TextEncoder().encode(`${context}\\x00${plaintext}`)\n const bits = await subtle.deriveBits(\n { name: 'HKDF', hash: 'SHA-256', salt, info },\n hkdfKey,\n IV_BYTES * 8,\n )\n return new Uint8Array(bits)\n}\n\n/**\n * Encrypt a plaintext string with AES-256-GCM and a deterministic,\n * HKDF-derived IV.\n *\n * The same `{ dek, context, plaintext }` triple always produces the\n * same `{ iv, data }` — call this twice and you can string-compare the\n * ciphertexts to check equality of the inputs without decrypting them.\n *\n * @param context Domain-separation string — by convention\n * `'<collection>/<field>'`. Different contexts encrypt\n * the same plaintext to different ciphertexts, so\n * `email` in collection `users` does not collide with\n * `email` in collection `customers`.\n */\nexport async function encryptDeterministic(\n plaintext: string,\n dek: CryptoKey,\n context: string,\n): Promise<EncryptResult> {\n const iv = await deriveDeterministicIV(dek, context, plaintext)\n const encoded = new TextEncoder().encode(plaintext)\n const ciphertext = await subtle.encrypt(\n { name: 'AES-GCM', iv: iv as BufferSource },\n dek,\n encoded,\n )\n return {\n iv: bufferToBase64(iv),\n data: bufferToBase64(ciphertext),\n }\n}\n\n/**\n * Counterpart to {@link encryptDeterministic}. The IV is stored\n * alongside the ciphertext (exactly like the randomized path), so\n * decrypt uses the stored IV and verifies the GCM auth tag — a tampered\n * ciphertext throws `TamperedError` just like randomized AES-GCM.\n */\nexport async function decryptDeterministic(\n ivBase64: string,\n dataBase64: string,\n dek: CryptoKey,\n): Promise<string> {\n return decrypt(ivBase64, dataBase64, dek)\n}\n\n// ─── Random Generation ─────────────────────────────────────────────────\n\n/** Generate a random 12-byte IV for AES-GCM. */\nexport function generateIV(): Uint8Array {\n return globalThis.crypto.getRandomValues(new Uint8Array(IV_BYTES))\n}\n\n/** Generate a random 32-byte salt for PBKDF2. */\nexport function generateSalt(): Uint8Array {\n return globalThis.crypto.getRandomValues(new Uint8Array(SALT_BYTES))\n}\n\n// ─── Base64 Helpers ────────────────────────────────────────────────────\n\nexport function bufferToBase64(buffer: ArrayBuffer | Uint8Array): string {\n const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer)\n let binary = ''\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]!)\n }\n return btoa(binary)\n}\n\nexport function base64ToBuffer(base64: string): Uint8Array<ArrayBuffer> {\n const binary = atob(base64)\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i)\n }\n return bytes\n}\n"],"mappings":";;;;;;;;AAoDA,IAAM,oBAAoB;AAC1B,IAAM,aAAa;AACnB,IAAM,WAAW;AACjB,IAAM,WAAW;AAEjB,IAAM,SAAS,WAAW,OAAO;AAKjC,eAAsB,UACpB,QACA,MACoB;AACpB,SAAO,sBAAsB,IAAI,YAAY,EAAE,OAAO,MAAM,GAAG,IAAI;AACrE;AAOA,eAAe,sBACb,UACA,MACoB;AACpB,QAAM,cAAc,MAAM,OAAO,UAAU,OAAO,UAA0B,UAAU,OAAO,CAAC,WAAW,CAAC;AAC1G,SAAO,OAAO;AAAA,IACZ,EAAE,MAAM,UAAU,MAA4B,YAAY,mBAAmB,MAAM,UAAU;AAAA,IAC7F;AAAA,IACA,EAAE,MAAM,UAAU,QAAQ,SAAS;AAAA,IACnC;AAAA,IACA,CAAC,WAAW,WAAW;AAAA,EACzB;AACF;AAcA,IAAM,mBAAmB,IAAI,WAAW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,SAAS,eAAe,QAAyC;AACtE,QAAM,SAAS,KAAK,MAAM;AAC1B,QAAM,QAAQ,IAAI,WAAW,OAAO,MAAM;AAC1C,WAAS,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK;AACtC,UAAM,CAAC,IAAI,OAAO,WAAW,CAAC;AAAA,EAChC;AACA,SAAO;AACT;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  OverlayIdMismatchError
3
- } from "./chunk-HNGSV2YC.js";
3
+ } from "./chunk-P7L3OQLL.js";
4
4
 
5
5
  // src/with-formula/overlay-views/virtual-collection.ts
6
6
  var OverlayedCollection = class {
@@ -206,4 +206,4 @@ var OverlayedCollection = class {
206
206
  export {
207
207
  OverlayedCollection
208
208
  };
209
- //# sourceMappingURL=chunk-OF3L2SD6.js.map
209
+ //# sourceMappingURL=chunk-W6NFONOV.js.map
@@ -1,13 +1,13 @@
1
1
  import {
2
2
  ViaGraph
3
- } from "./chunk-7TSYBD3E.js";
3
+ } from "./chunk-RSFG7XHM.js";
4
4
  import {
5
5
  sha256Hex
6
- } from "./chunk-VCETL77O.js";
6
+ } from "./chunk-VJ4B3ZXY.js";
7
7
  import {
8
8
  DerivationCycleError,
9
9
  DuplicateBehaviorNameError
10
- } from "./chunk-HNGSV2YC.js";
10
+ } from "./chunk-P7L3OQLL.js";
11
11
 
12
12
  // src/with-formula/derivations/strategy-hash.ts
13
13
  async function computeStrategyHash(source, outputKeys, derive, sources) {
@@ -172,4 +172,4 @@ var DerivationRegistry = class {
172
172
  export {
173
173
  DerivationRegistry
174
174
  };
175
- //# sourceMappingURL=chunk-NJDQ4YSV.js.map
175
+ //# sourceMappingURL=chunk-WBNXZU42.js.map
@@ -2,7 +2,7 @@ import {
2
2
  OverlayBaseIsVirtualError,
3
3
  OverlayCollectionUnavailableError,
4
4
  OverlayNameCollisionError
5
- } from "./chunk-HNGSV2YC.js";
5
+ } from "./chunk-P7L3OQLL.js";
6
6
 
7
7
  // src/with-formula/overlay-views/registry.ts
8
8
  var OverlayedViewRegistry = class {
@@ -68,4 +68,4 @@ var OverlayedViewRegistry = class {
68
68
  export {
69
69
  OverlayedViewRegistry
70
70
  };
71
- //# sourceMappingURL=chunk-FNSMZQS4.js.map
71
+ //# sourceMappingURL=chunk-WKD5ESK4.js.map
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  grant,
3
3
  revoke
4
- } from "./chunk-ERB6NDDW.js";
4
+ } from "./chunk-RKDH6L53.js";
5
5
  import {
6
6
  CustodyNotEnabledError
7
- } from "./chunk-HNGSV2YC.js";
7
+ } from "./chunk-P7L3OQLL.js";
8
8
 
9
9
  // src/with-party/custody/active.ts
10
10
  function withCustody() {
@@ -16,7 +16,7 @@ function withCustody() {
16
16
  return host._revokeCustodianImpl(revoke, vault, options, factors);
17
17
  },
18
18
  async liberate(vault, opts) {
19
- const { liberateVault } = await import("./liberate-PX4CAT5V.js");
19
+ const { liberateVault } = await import("./liberate-I6AOLWXW.js");
20
20
  return liberateVault(vault, opts);
21
21
  }
22
22
  };
@@ -74,4 +74,4 @@ export {
74
74
  withCustody,
75
75
  CustodyApi
76
76
  };
77
- //# sourceMappingURL=chunk-NKH7GSIH.js.map
77
+ //# sourceMappingURL=chunk-XGQGWZ6D.js.map
@@ -0,0 +1,190 @@
1
+ import {
2
+ isRewrappedUnder,
3
+ rewrapEnvelope
4
+ } from "./chunk-D5UDZANO.js";
5
+ import {
6
+ buildRecordEnvelope,
7
+ isTombstone,
8
+ isTombstoneShape
9
+ } from "./chunk-ZVAFJQZB.js";
10
+
11
+ // src/with-commit/history/history.ts
12
+ var HISTORY_COLLECTION = "_history";
13
+ var VERSION_PAD = 10;
14
+ function historyId(collection, recordId, version) {
15
+ return `${collection}:${recordId}:${String(version).padStart(VERSION_PAD, "0")}`;
16
+ }
17
+ function historyIdentity(collection, recordId, version) {
18
+ return { collection: HISTORY_COLLECTION, id: historyId(collection, recordId, version), version };
19
+ }
20
+ function matchesPrefix(id, collection, recordId) {
21
+ if (recordId) {
22
+ return id.startsWith(`${collection}:${recordId}:`);
23
+ }
24
+ return id.startsWith(`${collection}:`);
25
+ }
26
+ async function saveHistory(adapter, vault, collection, recordId, envelope) {
27
+ const { id } = historyIdentity(collection, recordId, envelope._v);
28
+ await adapter.put(vault, HISTORY_COLLECTION, id, envelope);
29
+ }
30
+ async function getHistory(adapter, vault, collection, recordId, options) {
31
+ const allIds = await adapter.list(vault, HISTORY_COLLECTION);
32
+ const matchingIds = allIds.filter((id) => matchesPrefix(id, collection, recordId)).sort().reverse();
33
+ const entries = [];
34
+ for (const id of matchingIds) {
35
+ const envelope = await adapter.get(vault, HISTORY_COLLECTION, id);
36
+ if (!envelope) continue;
37
+ if (options?.from && envelope._ts < options.from) continue;
38
+ if (options?.to && envelope._ts > options.to) continue;
39
+ entries.push(envelope);
40
+ if (options?.limit && entries.length >= options.limit) break;
41
+ }
42
+ return entries;
43
+ }
44
+ async function getVersionEnvelope(adapter, vault, collection, recordId, version) {
45
+ const id = historyId(collection, recordId, version);
46
+ return adapter.get(vault, HISTORY_COLLECTION, id);
47
+ }
48
+ async function pruneHistory(adapter, vault, collection, recordId, options) {
49
+ const allIds = await adapter.list(vault, HISTORY_COLLECTION);
50
+ const matchingIds = allIds.filter((id) => recordId ? matchesPrefix(id, collection, recordId) : matchesPrefix(id, collection)).sort();
51
+ let toDelete = [];
52
+ if (options.keepVersions !== void 0) {
53
+ const keep = options.keepVersions;
54
+ if (matchingIds.length > keep) {
55
+ toDelete = matchingIds.slice(0, matchingIds.length - keep);
56
+ }
57
+ }
58
+ if (options.beforeDate) {
59
+ for (const id of matchingIds) {
60
+ if (toDelete.includes(id)) continue;
61
+ const envelope = await adapter.get(vault, HISTORY_COLLECTION, id);
62
+ if (envelope && envelope._ts < options.beforeDate) {
63
+ toDelete.push(id);
64
+ }
65
+ }
66
+ }
67
+ const uniqueDeletes = [...new Set(toDelete)];
68
+ for (const id of uniqueDeletes) {
69
+ await adapter.delete(vault, HISTORY_COLLECTION, id);
70
+ }
71
+ return uniqueDeletes.length;
72
+ }
73
+ async function clearHistory(adapter, vault, collection, recordId) {
74
+ const allIds = await adapter.list(vault, HISTORY_COLLECTION);
75
+ let toDelete;
76
+ if (collection && recordId) {
77
+ toDelete = allIds.filter((id) => matchesPrefix(id, collection, recordId));
78
+ } else if (collection) {
79
+ toDelete = allIds.filter((id) => matchesPrefix(id, collection));
80
+ } else {
81
+ toDelete = allIds;
82
+ }
83
+ for (const id of toDelete) {
84
+ await adapter.delete(vault, HISTORY_COLLECTION, id);
85
+ }
86
+ return toDelete.length;
87
+ }
88
+ async function tombstoneHistory(adapter, vault, collection, recordId, actor, encrypted) {
89
+ const allIds = await adapter.list(vault, HISTORY_COLLECTION);
90
+ const matchingIds = allIds.filter((id) => matchesPrefix(id, collection, recordId));
91
+ const now = (/* @__PURE__ */ new Date()).toISOString();
92
+ let count = 0;
93
+ for (const id of matchingIds) {
94
+ const env = await adapter.get(vault, HISTORY_COLLECTION, id);
95
+ if (!env) continue;
96
+ if (isTombstone(env, encrypted)) continue;
97
+ const tombstone = buildRecordEnvelope(
98
+ { collection: HISTORY_COLLECTION, id, ...actor ? { by: actor } : {}, version: env._v },
99
+ { ts: now, iv: "", data: "" }
100
+ );
101
+ await adapter.put(vault, HISTORY_COLLECTION, id, tombstone);
102
+ count++;
103
+ }
104
+ return count;
105
+ }
106
+ async function rewrapHistory(adapter, vault, collection, recordId, fromDek, toDek, tier0Dek) {
107
+ const allIds = await adapter.list(vault, HISTORY_COLLECTION);
108
+ const matchingIds = allIds.filter((id) => matchesPrefix(id, collection, recordId));
109
+ for (const id of matchingIds) {
110
+ const env = await adapter.get(vault, HISTORY_COLLECTION, id);
111
+ if (!env) continue;
112
+ if (isTombstoneShape(env)) continue;
113
+ const identity = {
114
+ collection: HISTORY_COLLECTION,
115
+ id,
116
+ version: env._v,
117
+ ...env._tier !== void 0 ? { tier: env._tier } : {},
118
+ ...env._by !== void 0 ? { by: env._by } : {}
119
+ };
120
+ if (await isRewrappedUnder(identity, env, toDek)) continue;
121
+ let next;
122
+ try {
123
+ next = await rewrapEnvelope(identity, env, fromDek, toDek);
124
+ } catch (err) {
125
+ if (!tier0Dek) throw err;
126
+ next = await rewrapEnvelope(identity, env, tier0Dek, toDek);
127
+ }
128
+ await adapter.put(vault, HISTORY_COLLECTION, id, next);
129
+ }
130
+ }
131
+
132
+ // src/with-commit/history/strategy.ts
133
+ function notEnabled(op) {
134
+ return new Error(
135
+ `${op} requires the history strategy. Import \`{ withHistory }\` from "@noy-db/hub/history" and pass it to \`createNoydb({ historyStrategy: withHistory() })\`.`
136
+ );
137
+ }
138
+ var NO_HISTORY = {
139
+ async saveHistory() {
140
+ },
141
+ // Unreachable in practice — `saveHistory` above is a no-op, so nothing is
142
+ // ever sealed. Returns the real layout rather than a sentinel so a future
143
+ // caller that reads it without writing cannot be misled.
144
+ historyIdentity: (collection, recordId, version) => historyIdentity(collection, recordId, version),
145
+ async getHistoryEntries() {
146
+ throw notEnabled("collection.history()");
147
+ },
148
+ async getVersionEnvelope() {
149
+ throw notEnabled("collection.getVersion()");
150
+ },
151
+ async pruneHistory() {
152
+ return 0;
153
+ },
154
+ async clearHistory() {
155
+ return 0;
156
+ },
157
+ async tombstoneHistory() {
158
+ return 0;
159
+ },
160
+ async rewrapHistory() {
161
+ },
162
+ async envelopePayloadHash() {
163
+ return "";
164
+ },
165
+ computePatch() {
166
+ return [];
167
+ },
168
+ diff() {
169
+ throw notEnabled("collection.diff()");
170
+ },
171
+ buildLedger() {
172
+ return null;
173
+ },
174
+ buildVaultInstant() {
175
+ throw notEnabled("vault.at() / vault.timeMachine()");
176
+ }
177
+ };
178
+
179
+ export {
180
+ historyIdentity,
181
+ saveHistory,
182
+ getHistory,
183
+ getVersionEnvelope,
184
+ pruneHistory,
185
+ clearHistory,
186
+ tombstoneHistory,
187
+ rewrapHistory,
188
+ NO_HISTORY
189
+ };
190
+ //# sourceMappingURL=chunk-YOT7D63X.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/with-commit/history/history.ts","../src/with-commit/history/strategy.ts"],"sourcesContent":["import { buildRecordEnvelope } from '../../kernel/enclave/index.js'\nimport type { RecordIdentity } from '../../kernel/enclave/index.js'\nimport type { NoydbStore, EncryptedEnvelope, HistoryOptions, PruneOptions } from '../../kernel/types.js'\nimport { isTombstone, isTombstoneShape, rewrapEnvelope, isRewrappedUnder, type EnclaveKey } from '../../kernel/enclave/index.js'\n\n/**\n * History storage convention:\n * Collection: `_history`\n * ID format: `{collection}:{recordId}:{paddedVersion}`\n * Version is zero-padded to 10 digits for lexicographic sorting.\n */\n\nconst HISTORY_COLLECTION = '_history'\nconst VERSION_PAD = 10\n\nfunction historyId(collection: string, recordId: string, version: number): string {\n return `${collection}:${recordId}:${String(version).padStart(VERSION_PAD, '0')}`\n}\n\n/**\n * The identity a history snapshot is **sealed against** — its STORAGE location,\n * not the live record it is a copy of (#1041).\n *\n * ## Why storage, and why this is a decision rather than a detail\n *\n * A snapshot is a copy, so two identities are available: the live record\n * (`collection`/`recordId`) or where the bytes actually land\n * (`_history`/`historyId(...)`). They are not equivalent under attack.\n *\n * Binding the LIVE identity makes a snapshot's AAD **indistinguishable from the\n * live record's at the same version** — so an untrusted store could serve a\n * history entry *as the current record* and the client would accept it. It also\n * leaves entries relocatable within `_history`.\n *\n * Binding STORAGE identity closes both. The cost is that the id must be known\n * *before* the envelope is sealed, where `saveHistory` previously derived it\n * *after* (from `envelope._v`) — which is precisely the restructure this\n * function exists to make possible.\n *\n * `saveHistory` uses this too, so the sealed identity and the put location have\n * **one definition** and cannot drift apart. Changing the layout here changes\n * both at once, by construction.\n */\nexport function historyIdentity(collection: string, recordId: string, version: number): RecordIdentity {\n // The snapshot's own `_v` IS the version it preserves — the same number that\n // appears in its id. One argument feeds both, so they cannot disagree (#1093).\n return { collection: HISTORY_COLLECTION, id: historyId(collection, recordId, version), version }\n}\n\n// Unused today, kept for future history-id parsing utilities.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction parseHistoryId(id: string): { collection: string; recordId: string; version: number } | null {\n const lastColon = id.lastIndexOf(':')\n if (lastColon < 0) return null\n const versionStr = id.slice(lastColon + 1)\n const rest = id.slice(0, lastColon)\n const firstColon = rest.indexOf(':')\n if (firstColon < 0) return null\n return {\n collection: rest.slice(0, firstColon),\n recordId: rest.slice(firstColon + 1),\n version: parseInt(versionStr, 10),\n }\n}\n\nfunction matchesPrefix(id: string, collection: string, recordId?: string): boolean {\n if (recordId) {\n return id.startsWith(`${collection}:${recordId}:`)\n }\n return id.startsWith(`${collection}:`)\n}\n\n/** Save a history entry (a complete encrypted envelope snapshot). */\nexport async function saveHistory(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n envelope: EncryptedEnvelope,\n): Promise<void> {\n // Same derivation the caller sealed against — one definition, so the sealed\n // identity and the put location cannot drift (#1041).\n const { id } = historyIdentity(collection, recordId, envelope._v)\n await adapter.put(vault, HISTORY_COLLECTION, id, envelope)\n}\n\n/** Get history entries for a record, sorted newest-first. */\nexport async function getHistory(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n options?: HistoryOptions,\n): Promise<EncryptedEnvelope[]> {\n const allIds = await adapter.list(vault, HISTORY_COLLECTION)\n const matchingIds = allIds\n .filter(id => matchesPrefix(id, collection, recordId))\n .sort()\n .reverse() // newest first\n\n const entries: EncryptedEnvelope[] = []\n\n for (const id of matchingIds) {\n const envelope = await adapter.get(vault, HISTORY_COLLECTION, id)\n if (!envelope) continue\n\n // Apply time filters\n if (options?.from && envelope._ts < options.from) continue\n if (options?.to && envelope._ts > options.to) continue\n\n entries.push(envelope)\n\n if (options?.limit && entries.length >= options.limit) break\n }\n\n return entries\n}\n\n/** Get a specific version's envelope from history. */\nexport async function getVersionEnvelope(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n version: number,\n): Promise<EncryptedEnvelope | null> {\n const id = historyId(collection, recordId, version)\n return adapter.get(vault, HISTORY_COLLECTION, id)\n}\n\n/** Prune history entries. Returns the number of entries deleted. */\nexport async function pruneHistory(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string | undefined,\n options: PruneOptions,\n): Promise<number> {\n const allIds = await adapter.list(vault, HISTORY_COLLECTION)\n const matchingIds = allIds\n .filter(id => recordId ? matchesPrefix(id, collection, recordId) : matchesPrefix(id, collection))\n .sort()\n\n let toDelete: string[] = []\n\n if (options.keepVersions !== undefined) {\n // Keep only the N most recent, delete the rest\n const keep = options.keepVersions\n if (matchingIds.length > keep) {\n toDelete = matchingIds.slice(0, matchingIds.length - keep)\n }\n }\n\n if (options.beforeDate) {\n // Delete entries older than the specified date\n for (const id of matchingIds) {\n if (toDelete.includes(id)) continue\n const envelope = await adapter.get(vault, HISTORY_COLLECTION, id)\n if (envelope && envelope._ts < options.beforeDate) {\n toDelete.push(id)\n }\n }\n }\n\n // Deduplicate\n const uniqueDeletes = [...new Set(toDelete)]\n\n for (const id of uniqueDeletes) {\n await adapter.delete(vault, HISTORY_COLLECTION, id)\n }\n\n return uniqueDeletes.length\n}\n\n/** Clear all history for a vault, optionally scoped to a collection or record. */\nexport async function clearHistory(\n adapter: NoydbStore,\n vault: string,\n collection?: string,\n recordId?: string,\n): Promise<number> {\n const allIds = await adapter.list(vault, HISTORY_COLLECTION)\n let toDelete: string[]\n\n if (collection && recordId) {\n toDelete = allIds.filter(id => matchesPrefix(id, collection, recordId))\n } else if (collection) {\n toDelete = allIds.filter(id => matchesPrefix(id, collection))\n } else {\n toDelete = allIds\n }\n\n for (const id of toDelete) {\n await adapter.delete(vault, HISTORY_COLLECTION, id)\n }\n\n return toDelete.length\n}\n\n/**\n * Crypto-shred every `_history` version of a record. Each non-tombstone\n * history envelope is OVERWRITTEN in place with a tombstone\n * `{ _noydb, _v, _ts: now, _by: actor, _iv: '', _data: '' }` — dropping\n * `_iv`/`_data`/`_cek`/`_det`, so the prior ciphertext (and the wrapped CEK\n * that could decrypt it) is gone everywhere this store reaches. The version\n * counter (`_v`) is preserved so the audit trail still shows \"N versions\n * existed and were erased.\"\n *\n * Overwrite — NOT delete — so the history key itself survives as proof the\n * version existed. Already-tombstoned versions (re-run / idempotent forget)\n * are left untouched and not counted.\n *\n * Returns the number of history versions newly tombstoned.\n */\nexport async function tombstoneHistory(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n actor: string,\n encrypted: boolean,\n): Promise<number> {\n const allIds = await adapter.list(vault, HISTORY_COLLECTION)\n const matchingIds = allIds.filter(id => matchesPrefix(id, collection, recordId))\n\n const now = new Date().toISOString()\n let count = 0\n for (const id of matchingIds) {\n const env = await adapter.get(vault, HISTORY_COLLECTION, id)\n if (!env) continue\n // Already a tombstone (no body and no wrapped CEK)? Skip — idempotent.\n if (isTombstone(env, encrypted)) continue\n // `by` rides on the IDENTITY — passing it in the body went through a\n // conditional spread, which TypeScript does not excess-property-check, so\n // it was silently dropped once `_by` moved to the identity (#1041).\n const tombstone: EncryptedEnvelope = buildRecordEnvelope(\n { collection: HISTORY_COLLECTION, id, ...(actor ? { by: actor } : {}), version: env._v },\n { ts: now, iv: '', data: '' },\n )\n await adapter.put(vault, HISTORY_COLLECTION, id, tombstone)\n count++\n }\n return count\n}\n\n/**\n * Re-key every `_history` snapshot of a record from `fromDek` to `toDek`.\n * Mirrors what `rewrapBodyToDek` already does for a record's LIVE body on a\n * tier move (elevate/demote/putAtTier) — each `_history` envelope also\n * carries its own `_cek`, wrapped under the collection's tier-0 DEK at write\n * time (`record-codec.ts`), so a tier move that rewraps only the live\n * envelope leaves prior versions decryptable at rest under the tier the\n * record left. This is defense-in-depth *beneath* the read-gate\n * (`history()`/`getVersion()` already return empty for an elevated record;\n * this protects the ciphertext even if that gate is bypassed).\n *\n * Rewraps content in place — unlike `tombstoneHistory`, it does NOT blank\n * `_iv`/`_data`/`_cek` — so a subsequent `demote()` restores tier-0\n * readability. Tombstone-shaped entries (a forgotten/shredded version —\n * blanked `_data`, no `_cek`) are skipped: there is no key material left to\n * rewrap.\n *\n * **Legacy fallback.** A snapshot written before this fix stays wrapped\n * under the tier-0 DEK even after its live record has since moved tiers, so\n * a rewrap attempted with a tier-N `fromDek` fails to unwrap/decrypt. When\n * the caller supplies `tier0Dek`, a failed rewrap is retried once with\n * `tier0Dek` as `fromDek` (the only other key a pre-fix snapshot can be\n * wrapped under — history is written only by tier-0 `put()`). The output is\n * always wrapped under `toDek` regardless of which `fromDek` succeeded. A\n * rewrap that fails under BOTH keys re-throws — that is real corruption, not\n * a tier mismatch, and must not be swallowed.\n *\n * **Crash-atomicity / idempotency (#712 whole-branch-fix-3).** This loop has\n * no transaction around it: a crash after some entries have been rewritten\n * under `toDek` but before the loop finishes leaves the record's history\n * split across two keys. A retry of the SAME call must not re-fail on the\n * entries that already made it — so each entry is probed with\n * `isRewrappedUnder(env, toDek)` FIRST; a match means it's already at the\n * target key and is skipped (put nothing). This makes same-target retries\n * and demote-after-crash fully self-healing. It does NOT close every crash\n * window: a crash that lands SOME entries under `toDek` while the record's\n * NEXT move target differs from this call's `toDek` (an intermediate-tier\n * crash — e.g. elevate 0→1 crashes mid-loop, then the record is moved 1→2)\n * still finds those entries unreadable under either `fromDek` or the\n * tier-0 fallback, since `toDek` is a third key the next call never probes\n * for. That residual window is an accepted, fail-closed limitation (see\n * `.changeset/history-at-rest.md` and the design doc) — availability is\n * lost, never confidentiality.\n */\nexport async function rewrapHistory(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n fromDek: EnclaveKey,\n toDek: EnclaveKey,\n tier0Dek?: EnclaveKey,\n): Promise<void> {\n const allIds = await adapter.list(vault, HISTORY_COLLECTION)\n const matchingIds = allIds.filter(id => matchesPrefix(id, collection, recordId))\n\n for (const id of matchingIds) {\n const env = await adapter.get(vault, HISTORY_COLLECTION, id)\n if (!env) continue\n // Already a tombstone (forgotten/shredded version)? Nothing to rewrap.\n if (isTombstoneShape(env)) continue\n // #712/whole-branch-fix-3: toDek-first idempotency skip — already at the\n // target key (a same-target retry, or demote-after-crash landing back on\n // a key it already reached)? Nothing to do; put nothing.\n // In-place re-key of a `_history` entry: the address does not move, so the\n // same identity opens and re-seals it (#1041). Built from the entry itself,\n // exactly as a reader would via `recordAadFor`.\n const identity = {\n collection: HISTORY_COLLECTION, id, version: env._v,\n ...(env._tier !== undefined ? { tier: env._tier } : {}),\n ...(env._by !== undefined ? { by: env._by } : {}),\n }\n if (await isRewrappedUnder(identity, env, toDek)) continue\n\n let next: EncryptedEnvelope\n try {\n next = await rewrapEnvelope(identity, env, fromDek, toDek)\n } catch (err) {\n if (!tier0Dek) throw err\n // Legacy fallback: retry once under the tier-0 DEK. A failure here is\n // real corruption, not a tier mismatch — let it propagate.\n next = await rewrapEnvelope(identity, env, tier0Dek, toDek)\n }\n\n await adapter.put(vault, HISTORY_COLLECTION, id, next)\n }\n}\n","/**\n * Strategy seam for the optional history + ledger + time-machine\n * service. Core imports `HistoryStrategy` type-only + `NO_HISTORY`\n * stub; real implementations of `saveHistory`, `LedgerStore`,\n * `VaultInstant`, `computePatch`, `diff` etc. are only reachable via\n * `withHistory()` in `./active.ts`.\n *\n * Applications that don't track per-record versioning, don't need the\n * hash-chained audit ledger, and don't restore to past instants ship\n * none of the ~1,880 LOC behind this seam.\n *\n * Strategy contract:\n *\n * - **saveHistory / pruneHistory / clearHistory** — no-ops under\n * NO_HISTORY. Writes still succeed; no snapshot is captured.\n * - **getHistoryEntries / getVersionEnvelope / diff** — throw under\n * NO_HISTORY. These are read APIs the consumer would only call\n * after explicitly asking for history; the throw guides them to\n * `@noy-db/hub/history`.\n * - **envelopePayloadHash / computePatch** — return empty / `[]`\n * under NO_HISTORY. These are only used inside the\n * `if (this.ledger)` branch, which is itself gated by\n * `buildLedger()` returning null.\n * - **buildLedger** — returns `null` under NO_HISTORY. The Vault's\n * public `vault.ledger()` accessor throws when null.\n * - **buildVaultInstant** — throws under NO_HISTORY. `vault.at()`\n * propagates the throw.\n *\n * @internal\n */\n\nimport type {\n EncryptedEnvelope,\n NoydbStore,\n HistoryOptions,\n PruneOptions,\n} from '../../kernel/types.js'\nimport type { LedgerStore } from './ledger/store.js'\nimport type { JsonPatch } from './ledger/patch.js'\nimport type { DiffEntry } from './diff.js'\nimport type { VaultInstant, VaultEngine } from './time-machine.js'\nimport type { EnclaveKey, RecordIdentity } from '../../kernel/enclave/index.js'\nimport { historyIdentity } from './history.js'\n\n/**\n * Options accepted by `HistoryStrategy.buildLedger`. Mirrors the\n * `LedgerStore` constructor verbatim — kept in this file so `core`\n * code never imports the LedgerStore module at runtime.\n *\n * @internal\n */\nexport interface BuildLedgerOptions {\n adapter: NoydbStore\n vault: string\n encrypted: boolean\n getDEK: (collectionName: string) => Promise<EnclaveKey>\n actor: string\n}\n\n/**\n * @internal\n */\nexport interface HistoryStrategy {\n /**\n * Persist a full encrypted envelope snapshot of the prior version\n * under `_history/{collection}:{id}:{paddedVersion}`. No-op under\n * `NO_HISTORY`.\n */\n saveHistory(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n envelope: EncryptedEnvelope,\n ): Promise<void>\n\n /**\n * The identity a snapshot of `collection/recordId@version` must be **sealed\n * against** — its `_history` storage location (#1041).\n *\n * On the port because the kernel writes history snapshots but must not import\n * `with-commit` to learn its layout. Exposing it here keeps the derivation in\n * the module that owns the layout, and `saveHistory` uses the same function,\n * so the sealed identity and the put location cannot drift.\n */\n historyIdentity(collection: string, recordId: string, version: number): RecordIdentity\n\n /**\n * List history envelopes for a record, newest first. Throws under\n * `NO_HISTORY` — callers reach this via `collection.history()` /\n * `collection.getVersion()` / `collection.diff()`, which only work\n * with the strategy enabled.\n */\n getHistoryEntries(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n options?: HistoryOptions,\n ): Promise<EncryptedEnvelope[]>\n\n /**\n * Fetch a specific version's envelope. Throws under `NO_HISTORY`.\n */\n getVersionEnvelope(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n version: number,\n ): Promise<EncryptedEnvelope | null>\n\n /**\n * Prune history entries by retention rule. Returns `0` under\n * `NO_HISTORY`.\n */\n pruneHistory(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string | undefined,\n options: PruneOptions,\n ): Promise<number>\n\n /**\n * Clear all history for vault/collection/record. Returns `0` under\n * `NO_HISTORY`.\n */\n clearHistory(\n adapter: NoydbStore,\n vault: string,\n collection?: string,\n recordId?: string,\n ): Promise<number>\n\n /**\n * Crypto-shred (overwrite-to-tombstone) every `_history` version of a\n * record for GDPR erasure. Returns the number of versions newly\n * tombstoned, or `0` under `NO_HISTORY` (no history = nothing to shred).\n */\n tombstoneHistory(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n actor: string,\n encrypted: boolean,\n ): Promise<number>\n\n /**\n * Re-key every `_history` snapshot of a record from `fromDek` to `toDek`\n * on a tier move (elevate/demote/putAtTier), mirroring the live-body\n * rewrap so prior versions are not left decryptable at rest under a tier\n * the record has moved away from. Optional `tier0Dek` enables the legacy\n * fallback for snapshots written before this rewrap existed (see\n * `history.ts` for the full contract). No-op under `NO_HISTORY` (no\n * history = nothing to rewrap).\n */\n rewrapHistory(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n fromDek: EnclaveKey,\n toDek: EnclaveKey,\n tier0Dek?: EnclaveKey,\n ): Promise<void>\n\n /**\n * Compute the SHA-256 hash of an envelope's encrypted payload, used\n * by `LedgerStore.append` to track tamper-evidence. Returns the\n * empty string under `NO_HISTORY` (the call site is gated by\n * `if (this.ledger)`, so the value is never observed).\n */\n envelopePayloadHash(envelope: EncryptedEnvelope | null): Promise<string>\n\n /**\n * Compute the JSON patch from `from` → `to`. Returns `[]` under\n * `NO_HISTORY`.\n */\n computePatch(from: unknown, to: unknown): JsonPatch\n\n /**\n * Compute the typed diff between two records. Throws under\n * `NO_HISTORY` — `collection.diff()` is a history-read API.\n */\n diff(recordA: unknown, recordB: unknown): DiffEntry[]\n\n /**\n * Construct (or return null) a `LedgerStore` for the vault. Returns\n * `null` under `NO_HISTORY`; the Vault treats null as \"no ledger\n * attached\" — collection write paths skip the append branch and the\n * public `vault.ledger()` accessor throws.\n */\n buildLedger(opts: BuildLedgerOptions): LedgerStore | null\n\n /**\n * Construct a `VaultInstant` for time-machine reads. Throws under\n * `NO_HISTORY`.\n */\n buildVaultInstant(engine: VaultEngine, timestamp: string): VaultInstant\n}\n\n/**\n * Error thrown when the consumer reaches a history-gated surface\n * without opting into the strategy. The message names the offending\n * operation and points to the subpath import.\n *\n * @internal\n */\nfunction notEnabled(op: string): Error {\n return new Error(\n `${op} requires the history strategy. Import ` +\n '`{ withHistory }` from \"@noy-db/hub/history\" and pass it to ' +\n '`createNoydb({ historyStrategy: withHistory() })`.',\n )\n}\n\n/**\n * No-history stub. Snapshots and prune/clear are no-ops; reads and\n * time-machine throw with an actionable message; ledger construction\n * returns null so the write-path's `if (this.ledger)` branch is dead\n * code in the bundle.\n *\n * @internal\n */\nexport const NO_HISTORY: HistoryStrategy = {\n async saveHistory() {},\n // Unreachable in practice — `saveHistory` above is a no-op, so nothing is\n // ever sealed. Returns the real layout rather than a sentinel so a future\n // caller that reads it without writing cannot be misled.\n historyIdentity: (collection, recordId, version) => historyIdentity(collection, recordId, version),\n async getHistoryEntries() { throw notEnabled('collection.history()') },\n async getVersionEnvelope() { throw notEnabled('collection.getVersion()') },\n async pruneHistory() { return 0 },\n async clearHistory() { return 0 },\n async tombstoneHistory() { return 0 },\n async rewrapHistory() {},\n async envelopePayloadHash() { return '' },\n computePatch() { return [] },\n diff() { throw notEnabled('collection.diff()') },\n buildLedger() { return null },\n buildVaultInstant() { throw notEnabled('vault.at() / vault.timeMachine()') },\n}\n"],"mappings":";;;;;;;;;;;AAYA,IAAM,qBAAqB;AAC3B,IAAM,cAAc;AAEpB,SAAS,UAAU,YAAoB,UAAkB,SAAyB;AAChF,SAAO,GAAG,UAAU,IAAI,QAAQ,IAAI,OAAO,OAAO,EAAE,SAAS,aAAa,GAAG,CAAC;AAChF;AA0BO,SA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AAS,KAAK;AACZ,UAAI,CAAC,SAAU,OAAM;AAGrB,aAAO,MAAM,eAAe,UAAU,KAAK,UAAU,KAAK;AAAA,IAC5D;AAEA,UAAM,QAAQ,IAAI,OAAO,oBAAoB,IAAI,IAAI;AAAA,EACvD;AACF;;;ACzHA,SAAS,WAAW,IAAmB;AACrC,SAAO,IAAI;AAAA,IACT,GAAG,EAAE;AAAA,EAGP;AACF;AAUO,IAAM,aAA8B;AAAA,EACzC,MAAM,cAAc;AAAA,EAAC;AAAA;AAAA;AAAA;AAAA,EAIrB,iBAAiB,CAAC,YAAY,UAAU,YAAY,gBAAgB,YAAY,UAAU,OAAO;AAAA,EACjG,MAAM,oBAAoB;AAAE,UAAM,WAAW,sBAAsB;AAAA,EAAE;AAAA,EACrE,MAAM,qBAAqB;AAAE,UAAM,WAAW,yBAAyB;AAAA,EAAE;AAAA,EACzE,MAAM,eAAe;AAAE,WAAO;AAAA,EAAE;AAAA,EAChC,MAAM,eAAe;AAAE,WAAO;AAAA,EAAE;AAAA,EAChC,MAAM,mBAAmB;AAAE,WAAO;AAAA,EAAE;AAAA,EACpC,MAAM,gBAAgB;AAAA,EAAC;AAAA,EACvB,MAAM,sBAAsB;AAAE,WAAO;AAAA,EAAG;AAAA,EACxC,eAAe;AAAE,WAAO,CAAC;AAAA,EAAE;AAAA,EAC3B,OAAO;AAAE,UAAM,WAAW,mBAAmB;AAAA,EAAE;AAAA,EAC/C,cAAc;AAAE,WAAO;AAAA,EAAK;AAAA,EAC5B,oBAAoB;AAAE,UAAM,WAAW,kCAAkC;AAAA,EAAE;AAC7E;","names":[]}
@@ -1,12 +1,13 @@
1
1
  import {
2
+ buildRecordAad,
2
3
  openEnvelopeJson
3
- } from "./chunk-VN45YLWM.js";
4
+ } from "./chunk-D5UDZANO.js";
4
5
  import {
5
- encrypt
6
- } from "./chunk-VCETL77O.js";
6
+ buildRecordEnvelope
7
+ } from "./chunk-ZVAFJQZB.js";
7
8
  import {
8
- NOYDB_FORMAT_VERSION
9
- } from "./chunk-W5W6KHN2.js";
9
+ encrypt
10
+ } from "./chunk-VJ4B3ZXY.js";
10
11
 
11
12
  // src/with-shape/persisted-schemas/storage.ts
12
13
  var SCHEMAS_COLLECTION = "_schemas";
@@ -15,7 +16,7 @@ async function loadPersistedSchemaEntry(store, vault, collection, dek) {
15
16
  if (!envelope) return { version: 0, payload: void 0 };
16
17
  const version = envelope._v;
17
18
  try {
18
- const plaintext = await openEnvelopeJson(envelope, dek);
19
+ const plaintext = await openEnvelopeJson({ collection: SCHEMAS_COLLECTION, id: collection }, envelope, dek);
19
20
  const parsed = JSON.parse(plaintext);
20
21
  if (parsed._noydb_schema !== 1) return { version, payload: void 0 };
21
22
  return { version, payload: parsed };
@@ -28,15 +29,13 @@ async function loadPersistedSchema(store, vault, collection, dek) {
28
29
  }
29
30
  async function savePersistedSchema(store, vault, collection, dek, payload, expectedVersion) {
30
31
  const json = JSON.stringify(payload);
31
- const { iv, data } = await encrypt(json, dek);
32
32
  const baseVersion = expectedVersion ?? (await store.get(vault, SCHEMAS_COLLECTION, collection))?._v ?? 0;
33
- const env = {
34
- _noydb: NOYDB_FORMAT_VERSION,
35
- _v: baseVersion + 1,
36
- _ts: (/* @__PURE__ */ new Date()).toISOString(),
37
- _iv: iv,
38
- _data: data
39
- };
33
+ const identity = { collection: SCHEMAS_COLLECTION, id: collection, version: baseVersion + 1 };
34
+ const { iv, data } = await encrypt(json, dek, buildRecordAad(identity));
35
+ const env = buildRecordEnvelope(
36
+ identity,
37
+ { iv, data }
38
+ );
40
39
  await store.put(vault, SCHEMAS_COLLECTION, collection, env, expectedVersion);
41
40
  }
42
41
 
@@ -46,4 +45,4 @@ export {
46
45
  loadPersistedSchema,
47
46
  savePersistedSchema
48
47
  };
49
- //# sourceMappingURL=chunk-4MC5JRRX.js.map
48
+ //# sourceMappingURL=chunk-YVTADFTC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/with-shape/persisted-schemas/storage.ts"],"sourcesContent":["/**\n * Read / write the per-collection persisted-schema envelope. Mirrors the\n * standard noy-db record envelope shape and is **AES-GCM encrypted with\n * the collection's DEK** — the schema body (field names, enum values,\n * constraints) is sensitive metadata, so it gets the same encryption\n * envelope as the records it describes.\n *\n * Storage layout:\n *\n * <vault>/_schemas/<collection> → EncryptedEnvelope\n *\n * The DEK passed to {@link savePersistedSchema} / {@link loadPersistedSchema}\n * is the same key the collection uses for its records.\n *\n * @module\n */\n\nimport { buildRecordAad, buildRecordEnvelope, encrypt, openEnvelopeJson, type EnclaveKey } from '../../kernel/enclave/index.js'\nimport type { NoydbStore } from '../../kernel/types.js'\nimport type { PersistedSchemaEnvelope } from './types.js'\n\n/** Reserved collection name where persisted schemas live. */\nexport const SCHEMAS_COLLECTION = '_schemas' as const\n\n/**\n * A decrypted persisted-schema read paired with the wrapping envelope's\n * `_v`. The version is the optimistic-concurrency token: pass it back to\n * {@link savePersistedSchema} as `expectedVersion` to make the write a CAS\n * that rejects a stale put (see #583 — the `_schemas` record is shared by\n * the JSON-Schema writer and the classified-marker writer).\n */\nexport interface PersistedSchemaEntry {\n /** Wrapping envelope `_v` (0 when no record exists yet). */\n readonly version: number\n /** Decrypted payload, or `undefined` when absent/corrupt/wrong-DEK. */\n readonly payload: PersistedSchemaEnvelope | undefined\n}\n\n/**\n * Read the persisted-schema envelope for one collection together with its\n * wrapping `_v`. The version reflects the raw stored envelope even when the\n * payload cannot be decrypted/parsed (so a CAS still guards a corrupt record\n * rather than silently clobbering it).\n */\nexport async function loadPersistedSchemaEntry(\n store: NoydbStore,\n vault: string,\n collection: string,\n dek: EnclaveKey,\n): Promise<PersistedSchemaEntry> {\n const envelope = await store.get(vault, SCHEMAS_COLLECTION, collection)\n if (!envelope) return { version: 0, payload: undefined }\n const version = envelope._v\n try {\n const plaintext = await openEnvelopeJson({ collection: SCHEMAS_COLLECTION, id: collection }, envelope, dek)\n const parsed = JSON.parse(plaintext) as PersistedSchemaEnvelope\n if (parsed._noydb_schema !== 1) return { version, payload: undefined }\n return { version, payload: parsed }\n } catch {\n return { version, payload: undefined }\n }\n}\n\n/**\n * Read and decrypt the persisted-schema envelope for one collection.\n * Returns `undefined` when no envelope has been written or when decryption\n * fails (e.g. wrong DEK passed). Tolerates corrupted records — JSON parse\n * failures surface as `undefined`, mirroring `_meta/handle`'s contract.\n */\nexport async function loadPersistedSchema(\n store: NoydbStore,\n vault: string,\n collection: string,\n dek: EnclaveKey,\n): Promise<PersistedSchemaEnvelope | undefined> {\n return (await loadPersistedSchemaEntry(store, vault, collection, dek)).payload\n}\n\n/**\n * Encrypt and persist a schema envelope for one collection. Always\n * overwrites any prior write (callers gate on hash equality before calling\n * to avoid no-op writes).\n *\n * Pass `expectedVersion` — the `version` from {@link loadPersistedSchemaEntry}\n * captured at load time — to make the write an optimistic CAS: on a store with\n * `casAtomic`, `store.put` throws {@link ConflictError} when the record was\n * bumped concurrently, so a lost update on the shared `_schemas` record is\n * rejected instead of silently clobbering the other writer's field (#583).\n * When omitted, keeps the legacy unconditional last-writer-wins behaviour.\n */\nexport async function savePersistedSchema(\n store: NoydbStore,\n vault: string,\n collection: string,\n dek: EnclaveKey,\n payload: PersistedSchemaEnvelope,\n expectedVersion?: number,\n): Promise<void> {\n const json = JSON.stringify(payload)\n const baseVersion = expectedVersion ?? (await store.get(vault, SCHEMAS_COLLECTION, collection))?._v ?? 0\n const identity = { collection: SCHEMAS_COLLECTION, id: collection, version: baseVersion + 1 }\n const { iv, data } = await encrypt(json, dek, buildRecordAad(identity))\n const env = buildRecordEnvelope(\n identity,\n { iv, data },\n )\n await store.put(vault, SCHEMAS_COLLECTION, collection, env, expectedVersion)\n}\n"],"mappings":";;;;;;;;;;;;AAsBO,IAAM,qBAAqB;AAsBlC,eAAsB,yBACpB,OACA,OACA,YACA,KAC+B;AAC/B,QAAM,WAAW,MAAM,MAAM,IAAI,OAAO,oBAAoB,UAAU;AACtE,MAAI,CAAC,SAAU,QAAO,EAAE,SAAS,GAAG,SAAS,OAAU;AACvD,QAAM,UAAU,SAAS;AACzB,MAAI;AACF,UAAM,YAAY,MAAM,iBAAiB,EAAE,YAAY,oBAAoB,IAAI,WAAW,GAAG,UAAU,GAAG;AAC1G,UAAM,SAAS,KAAK,MAAM,SAAS;AACnC,QAAI,OAAO,kBAAkB,EAAG,QAAO,EAAE,SAAS,SAAS,OAAU;AACrE,WAAO,EAAE,SAAS,SAAS,OAAO;AAAA,EACpC,QAAQ;AACN,WAAO,EAAE,SAAS,SAAS,OAAU;AAAA,EACvC;AACF;AAQA,eAAsB,oBACpB,OACA,OACA,YACA,KAC8C;AAC9C,UAAQ,MAAM,yBAAyB,OAAO,OAAO,YAAY,GAAG,GAAG;AACzE;AAcA,eAAsB,oBACpB,OACA,OACA,YACA,KACA,SACA,iBACe;AACf,QAAM,OAAO,KAAK,UAAU,OAAO;AACnC,QAAM,cAAc,oBAAoB,MAAM,MAAM,IAAI,OAAO,oBAAoB,UAAU,IAAI,MAAM;AACvG,QAAM,WAAW,EAAE,YAAY,oBAAoB,IAAI,YAAY,SAAS,cAAc,EAAE;AAC5F,QAAM,EAAE,IAAI,KAAK,IAAI,MAAM,QAAQ,MAAM,KAAK,eAAe,QAAQ,CAAC;AACtE,QAAM,MAAM;AAAA,IACV;AAAA,IACA,EAAE,IAAI,KAAK;AAAA,EACb;AACA,QAAM,MAAM,IAAI,OAAO,oBAAoB,YAAY,KAAK,eAAe;AAC7E;","names":[]}
@@ -1,15 +1,16 @@
1
1
  import {
2
+ buildRecordAad,
2
3
  openEnvelopeJson
3
- } from "./chunk-VN45YLWM.js";
4
+ } from "./chunk-D5UDZANO.js";
4
5
  import {
5
- encrypt
6
- } from "./chunk-VCETL77O.js";
6
+ buildRecordEnvelope
7
+ } from "./chunk-ZVAFJQZB.js";
7
8
  import {
8
- NOYDB_FORMAT_VERSION
9
- } from "./chunk-W5W6KHN2.js";
9
+ encrypt
10
+ } from "./chunk-VJ4B3ZXY.js";
10
11
  import {
11
12
  ConflictError
12
- } from "./chunk-HNGSV2YC.js";
13
+ } from "./chunk-P7L3OQLL.js";
13
14
 
14
15
  // src/with-audit/attestation/signer.ts
15
16
  import { generateDocSigningKeyPair } from "@noy-db/attestation";
@@ -20,7 +21,7 @@ async function loadSigner(store, vault, getDEK) {
20
21
  const existing = await store.get(vault, ATTESTATIONS_COLLECTION, SIGNER_RECORD_ID);
21
22
  if (!existing) return null;
22
23
  const dek = await getDEK(ATTESTATIONS_COLLECTION);
23
- const json = await openEnvelopeJson(existing, dek);
24
+ const json = await openEnvelopeJson({ collection: ATTESTATIONS_COLLECTION, id: SIGNER_RECORD_ID }, existing, dek);
24
25
  return JSON.parse(json);
25
26
  }
26
27
  async function loadOrCreateSigner(store, vault, getDEK) {
@@ -28,14 +29,12 @@ async function loadOrCreateSigner(store, vault, getDEK) {
28
29
  if (existing) return existing;
29
30
  const dek = await getDEK(ATTESTATIONS_COLLECTION);
30
31
  const signer = await generateDocSigningKeyPair();
31
- const { iv, data } = await encrypt(JSON.stringify(signer), dek);
32
- const env = {
33
- _noydb: NOYDB_FORMAT_VERSION,
34
- _v: 1,
35
- _ts: (/* @__PURE__ */ new Date()).toISOString(),
36
- _iv: iv,
37
- _data: data
38
- };
32
+ const identity = { collection: ATTESTATIONS_COLLECTION, id: SIGNER_RECORD_ID, version: 1 };
33
+ const { iv, data } = await encrypt(JSON.stringify(signer), dek, buildRecordAad(identity));
34
+ const env = buildRecordEnvelope(
35
+ identity,
36
+ { iv, data }
37
+ );
39
38
  try {
40
39
  await store.put(vault, ATTESTATIONS_COLLECTION, SIGNER_RECORD_ID, env, 0);
41
40
  return signer;
@@ -56,4 +55,4 @@ export {
56
55
  loadSigner,
57
56
  loadOrCreateSigner
58
57
  };
59
- //# sourceMappingURL=chunk-GASWQ3XG.js.map
58
+ //# sourceMappingURL=chunk-ZBDWKPBW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/with-audit/attestation/signer.ts"],"sourcesContent":["import type { NoydbStore } from '../../kernel/types.js'\nimport { buildRecordAad, buildRecordEnvelope, encrypt, openEnvelopeJson, type EnclaveKey } from '../../kernel/enclave/index.js'\nimport { ConflictError } from '../../kernel/errors.js'\nimport { generateDocSigningKeyPair } from '@noy-db/attestation'\n\nexport const ATTESTATIONS_COLLECTION = '_attestations'\nexport const SIGNER_RECORD_ID = '_signer'\nexport const REVOKED_RECORD_ID = '_revoked'\n\nexport interface DocSigner {\n readonly keyId: string\n readonly publicKeyB64: string\n readonly privateKeyPkcs8B64: string\n}\n\n/**\n * Pure read: return the firm's persisted document-signing keypair, or `null`\n * if none has been minted yet. Never writes — callers that must NOT mint\n * (e.g. an ungated public-key getter) use this instead of `loadOrCreateSigner`.\n *\n * Stored as an encrypted record `_attestations/_signer` under the\n * `_attestations` collection DEK (resolved via `getDEK`, which is\n * AES-KW-wrapped under the owner KEK + persisted by the keyring). The KEK\n * itself is AES-KW-only and cannot AES-GCM-encrypt these bytes — hence\n * storage under a normal collection DEK.\n */\nexport async function loadSigner(\n store: NoydbStore,\n vault: string,\n getDEK: (collection: string) => Promise<EnclaveKey>,\n): Promise<DocSigner | null> {\n const existing = await store.get(vault, ATTESTATIONS_COLLECTION, SIGNER_RECORD_ID)\n if (!existing) return null\n const dek = await getDEK(ATTESTATIONS_COLLECTION)\n const json = await openEnvelopeJson({ collection: ATTESTATIONS_COLLECTION, id: SIGNER_RECORD_ID }, existing, dek)\n return JSON.parse(json) as DocSigner\n}\n\n/**\n * Lazily mint (or load) the firm's Ed25519 document-signing keypair.\n *\n * On a concurrent first-mint, two callers can both read `null` and both mint\n * distinct keypairs. The `put(…, expectedVersion: 0)` (\"must not already\n * exist\") lets exactly one win; the loser catches `ConflictError`, re-reads,\n * and returns the winner's signer — converging on a single keypair rather than\n * clobbering it or surfacing a raw conflict. (All real stores treat a missing\n * record + `ev: 0` as a no-conflict write, so the catch fires on lost-race only.)\n */\nexport async function loadOrCreateSigner(\n store: NoydbStore,\n vault: string,\n getDEK: (collection: string) => Promise<EnclaveKey>,\n): Promise<DocSigner> {\n const existing = await loadSigner(store, vault, getDEK)\n if (existing) return existing\n\n const dek = await getDEK(ATTESTATIONS_COLLECTION)\n const signer = await generateDocSigningKeyPair()\n const identity = { collection: ATTESTATIONS_COLLECTION, id: SIGNER_RECORD_ID, version: 1 }\n const { iv, data } = await encrypt(JSON.stringify(signer), dek, buildRecordAad(identity))\n const env = buildRecordEnvelope(\n identity,\n { iv, data },\n )\n try {\n await store.put(vault, ATTESTATIONS_COLLECTION, SIGNER_RECORD_ID, env, 0)\n return signer\n } catch (e) {\n if (!(e instanceof ConflictError)) throw e\n // Lost the race — another writer minted first. Adopt the winner.\n const winner = await loadSigner(store, vault, getDEK)\n if (!winner) {\n throw new ConflictError(0, 'loadOrCreateSigner: signer mint lost a concurrent race but the winning record could not be re-read.')\n }\n return winner\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAGA,SAAS,iCAAiC;AAEnC,IAAM,0BAA0B;AAChC,IAAM,mBAAmB;AACzB,IAAM,oBAAoB;AAmBjC,eAAsB,WACpB,OACA,OACA,QAC2B;AAC3B,QAAM,WAAW,MAAM,MAAM,IAAI,OAAO,yBAAyB,gBAAgB;AACjF,MAAI,CAAC,SAAU,QAAO;AACtB,QAAM,MAAM,MAAM,OAAO,uBAAuB;AAChD,QAAM,OAAO,MAAM,iBAAiB,EAAE,YAAY,yBAAyB,IAAI,iBAAiB,GAAG,UAAU,GAAG;AAChH,SAAO,KAAK,MAAM,IAAI;AACxB;AAYA,eAAsB,mBACpB,OACA,OACA,QACoB;AACpB,QAAM,WAAW,MAAM,WAAW,OAAO,OAAO,MAAM;AACtD,MAAI,SAAU,QAAO;AAErB,QAAM,MAAM,MAAM,OAAO,uBAAuB;AAChD,QAAM,SAAS,MAAM,0BAA0B;AAC/C,QAAM,WAAW,EAAE,YAAY,yBAAyB,IAAI,kBAAkB,SAAS,EAAE;AACzF,QAAM,EAAE,IAAI,KAAK,IAAI,MAAM,QAAQ,KAAK,UAAU,MAAM,GAAG,KAAK,eAAe,QAAQ,CAAC;AACxF,QAAM,MAAM;AAAA,IACV;AAAA,IACA,EAAE,IAAI,KAAK;AAAA,EACb;AACA,MAAI;AACF,UAAM,MAAM,IAAI,OAAO,yBAAyB,kBAAkB,KAAK,CAAC;AACxE,WAAO;AAAA,EACT,SAAS,GAAG;AACV,QAAI,EAAE,aAAa,eAAgB,OAAM;AAEzC,UAAM,SAAS,MAAM,WAAW,OAAO,OAAO,MAAM;AACpD,QAAI,CAAC,QAAQ;AACX,YAAM,IAAI,cAAc,GAAG,qGAAqG;AAAA,IAClI;AACA,WAAO;AAAA,EACT;AACF;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  writePod
3
- } from "./chunk-VOQW5LAM.js";
3
+ } from "./chunk-2IK6AC6A.js";
4
4
 
5
5
  // src/with-audit/portability/export-accessible.ts
6
6
  function resolveAccessibleCollections(keyring, scope, writableOnly = false) {
@@ -42,4 +42,4 @@ export {
42
42
  buildAccessibleBundle,
43
43
  exportAccessibleData
44
44
  };
45
- //# sourceMappingURL=chunk-52QYGZHH.js.map
45
+ //# sourceMappingURL=chunk-ZPMXYPBR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/with-audit/portability/export-accessible.ts"],"sourcesContent":["/**\n * `exportMyAccessibleData`: a non-owner user exports the scope they\n * can decrypt as a portable, re-keyed `.noydb` bundle. Non-destructive and\n * **always allowed** (the \"data sovereignty by construction\" property of\n * sealing-at-dimension — the firm cannot deny it) but **audited**.\n *\n * Reuses the existing bundle machinery: the access boundary is the caller's DEK\n * set (operator/client → `keyring.permissions`; owner/admin/viewer → all), so a\n * record outside the caller's keys can never enter the bundle. Re-keying to a\n * new owner reuses `writePod`'s `exportSecret` shorthand.\n */\nimport type { Vault } from '../../kernel/vault.js'\nimport type { UnlockedKeyring } from '../../with-party/team/keyring.js'\nimport { writePod } from '../../with-pod/pod.js'\n\n/**\n * Resolve the collections a caller may export/withdraw: operator/client are\n * scoped to their granted collections; owner/admin/viewer see everything\n * (`undefined` = no allowlist). A `scope.collections` sub-scope intersects the\n * granted set. `writableOnly` keeps only `rw` grants (for destructive ops).\n */\nexport function resolveAccessibleCollections(\n keyring: UnlockedKeyring,\n scope: { collections?: readonly string[] } | undefined,\n writableOnly = false,\n): string[] | undefined {\n let collections: string[] | undefined\n if (keyring.role === 'operator' || keyring.role === 'client') {\n collections = Object.entries(keyring.permissions)\n .filter(([, mode]) => !writableOnly || mode === 'rw')\n .map(([c]) => c)\n }\n if (scope?.collections) {\n const allow = new Set(scope.collections)\n collections = (collections ?? [...scope.collections]).filter((c) => allow.has(c))\n }\n return collections\n}\n\n/** Produce a (optionally re-keyed, scoped) `.noydb` bundle — no audit. */\nexport async function buildAccessibleBundle(\n vault: Vault,\n collections: string[] | undefined,\n reKey: { secret: string } | undefined,\n compression: 'auto' | 'brotli' | 'gzip' | 'none' = 'auto',\n): Promise<Uint8Array> {\n return writePod(vault, {\n compression,\n ...(collections !== undefined ? { collections } : {}),\n ...(reKey ? { exportSecret: reKey.secret } : {}),\n })\n}\n\nexport interface ExportAccessibleOptions {\n /**\n * Re-key the bundle so it is independently openable by a new owner with this\n * secret (the receiving firm / the client themselves). Omit to inherit\n * the source keyring (personal backup).\n */\n readonly reKey?: { readonly secret: string }\n /** Narrow the export to a subset of the caller's accessible collections. */\n readonly scope?: { readonly collections?: readonly string[] }\n readonly compression?: 'auto' | 'brotli' | 'gzip' | 'none'\n}\n\n/**\n * Produce a re-keyed, access-scoped `.noydb` bundle of the caller's accessible\n * data. Appends a tamper-evident audit entry (`reason: 'user-export:<userId>'`).\n */\nexport async function exportAccessibleData(\n vault: Vault,\n opts: ExportAccessibleOptions = {},\n): Promise<Uint8Array> {\n const { keyring } = vault._introspectState()\n const collections = resolveAccessibleCollections(keyring, opts.scope)\n const bytes = await buildAccessibleBundle(vault, collections, opts.reKey, opts.compression ?? 'auto')\n\n // §11.11 audit — non-destructive, always-allowed export. No-op when the vault\n // has no history/ledger strategy (avoids minting a phantom _ledger DEK).\n await vault._getLedgerOrNull()?.append({\n op: 'lifecycle',\n collection: '',\n id: '',\n version: 0,\n actor: keyring.userId,\n payloadHash: '',\n reason: `user-export:${keyring.userId}`,\n })\n\n return bytes\n}\n"],"mappings":";;;;;AAqBO,SAAS,6BACd,SACA,OACA,eAAe,OACO;AACtB,MAAI;AACJ,MAAI,QAAQ,SAAS,cAAc,QAAQ,SAAS,UAAU;AAC5D,kBAAc,OAAO,QAAQ,QAAQ,WAAW,EAC7C,OAAO,CAAC,CAAC,EAAE,IAAI,MAAM,CAAC,gBAAgB,SAAS,IAAI,EACnD,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC;AAAA,EACnB;AACA,MAAI,OAAO,aAAa;AACtB,UAAM,QAAQ,IAAI,IAAI,MAAM,WAAW;AACvC,mBAAe,eAAe,CAAC,GAAG,MAAM,WAAW,GAAG,OAAO,CAAC,MAAM,MAAM,IAAI,CAAC,CAAC;AAAA,EAClF;AACA,SAAO;AACT;AAGA,eAAsB,sBACpB,OACA,aACA,OACA,cAAmD,QAC9B;AACrB,SAAO,SAAS,OAAO;AAAA,IACrB;AAAA,IACA,GAAI,gBAAgB,SAAY,EAAE,YAAY,IAAI,CAAC;AAAA,IACnD,GAAI,QAAQ,EAAE,cAAc,MAAM,OAAO,IAAI,CAAC;AAAA,EAChD,CAAC;AACH;AAkBA,eAAsB,qBACpB,OACA,OAAgC,CAAC,GACZ;AACrB,QAAM,EAAE,QAAQ,IAAI,MAAM,iBAAiB;AAC3C,QAAM,cAAc,6BAA6B,SAAS,KAAK,KAAK;AACpE,QAAM,QAAQ,MAAM,sBAAsB,OAAO,aAAa,KAAK,OAAO,KAAK,eAAe,MAAM;AAIpG,QAAM,MAAM,iBAAiB,GAAG,OAAO;AAAA,IACrC,IAAI;AAAA,IACJ,YAAY;AAAA,IACZ,IAAI;AAAA,IACJ,SAAS;AAAA,IACT,OAAO,QAAQ;AAAA,IACf,aAAa;AAAA,IACb,QAAQ,eAAe,QAAQ,MAAM;AAAA,EACvC,CAAC;AAED,SAAO;AACT;","names":[]}