@noy-db/hub 0.3.0-pre.3 → 0.3.0-pre.4

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 (386) hide show
  1. package/dist/adapter/index.d.ts +2 -2
  2. package/dist/adapter/index.js +1 -1
  3. package/dist/aggregate/index.d.ts +3 -3
  4. package/dist/aggregate/index.js +4 -4
  5. package/dist/api-JOXUNSKP.js +20 -0
  6. package/dist/as/index.d.ts +4 -4
  7. package/dist/as/index.js +12 -9
  8. package/dist/at/index.d.ts +2 -2
  9. package/dist/attestation/index.d.ts +3 -3
  10. package/dist/attestation/index.js +21 -18
  11. package/dist/attestation/index.js.map +1 -1
  12. package/dist/{backup-NGRJ46SH.js → backup-MOB27UUN.js} +12 -9
  13. package/dist/{backup-NGRJ46SH.js.map → backup-MOB27UUN.js.map} +1 -1
  14. package/dist/blobs/index.d.ts +4 -4
  15. package/dist/blobs/index.js +11 -8
  16. package/dist/blobs/index.js.map +1 -1
  17. package/dist/bundle/index.d.ts +5 -5
  18. package/dist/bundle/index.js +21 -18
  19. package/dist/bundle/index.js.map +1 -1
  20. package/dist/{bundle-B-P3_Jvb.d.ts → bundle-Bs13EZtX.d.ts} +1 -1
  21. package/dist/by/index.js +2 -2
  22. package/dist/cargo/index.d.ts +4 -4
  23. package/dist/cargo/index.js +23 -20
  24. package/dist/{chunk-VBYVKOMJ.js → chunk-3QRQOBS7.js} +3 -3
  25. package/dist/{chunk-JFYIHLU3.js → chunk-3Y4QLJ6K.js} +2 -2
  26. package/dist/{chunk-BZIWKN74.js → chunk-43ISXURO.js} +2 -2
  27. package/dist/{chunk-7IP75FP2.js → chunk-4K3MQ5S3.js} +2 -2
  28. package/dist/{chunk-6DP5HBQD.js → chunk-5CY35H55.js} +9 -9
  29. package/dist/chunk-5EWYUR5P.js +37 -0
  30. package/dist/chunk-5EWYUR5P.js.map +1 -0
  31. package/dist/{chunk-2KSPDSWI.js → chunk-5MRE3C4Q.js} +5 -5
  32. package/dist/{chunk-5ZPWVNL3.js → chunk-5W7AOFWA.js} +2 -2
  33. package/dist/{chunk-PUNJAEY6.js → chunk-6HNKCKFZ.js} +7 -7
  34. package/dist/{chunk-PJDK2PPQ.js → chunk-6RXPSMKR.js} +3 -3
  35. package/dist/{chunk-Z44OY24N.js → chunk-7J7JRYXW.js} +9 -5
  36. package/dist/chunk-7J7JRYXW.js.map +1 -0
  37. package/dist/{chunk-MCJAUQGE.js → chunk-A5DYVMDR.js} +3 -3
  38. package/dist/{chunk-MIOLJG2R.js → chunk-AF5ZRTZ4.js} +5 -2
  39. package/dist/chunk-AF5ZRTZ4.js.map +1 -0
  40. package/dist/{chunk-TICO2I2O.js → chunk-BKGIWGCX.js} +2 -2
  41. package/dist/{chunk-O5DNEXQC.js → chunk-BMQOH7MM.js} +2 -2
  42. package/dist/{chunk-U6OM4E67.js → chunk-CPXPHQGX.js} +6 -6
  43. package/dist/{chunk-3UDPDRUC.js → chunk-EWR7HL3K.js} +4 -4
  44. package/dist/{chunk-CVXLJIAV.js → chunk-FH52CDEW.js} +5 -5
  45. package/dist/chunk-G4MGYGSS.js +130 -0
  46. package/dist/chunk-G4MGYGSS.js.map +1 -0
  47. package/dist/{chunk-FELHYKIO.js → chunk-G7RDYYTE.js} +2 -2
  48. package/dist/{chunk-N2FP26NH.js → chunk-GBTUANXF.js} +16 -297
  49. package/dist/chunk-GBTUANXF.js.map +1 -0
  50. package/dist/{chunk-UP6EMMDI.js → chunk-GOUNIHFA.js} +10 -10
  51. package/dist/{chunk-DHIN36UC.js → chunk-GQOT6QJR.js} +8 -8
  52. package/dist/{chunk-DGUR3CC4.js → chunk-GXGK22QU.js} +2 -2
  53. package/dist/{chunk-YTIAXSUE.js → chunk-GZZL5R73.js} +4 -4
  54. package/dist/{chunk-E4YJUNPU.js → chunk-H5XRIJX3.js} +7 -7
  55. package/dist/{chunk-DA34OEZU.js → chunk-H7RYPVMJ.js} +2 -2
  56. package/dist/{chunk-2ZORB5RW.js → chunk-HBKDR7R3.js} +3 -3
  57. package/dist/{chunk-BV7KNFJY.js → chunk-HLUKZ36Q.js} +9 -9
  58. package/dist/{chunk-ZNI3RTFV.js → chunk-HMXLN43G.js} +2 -2
  59. package/dist/{chunk-BYW7EU5L.js → chunk-HY6ZGGEC.js} +2 -2
  60. package/dist/{chunk-OVIVYAQL.js → chunk-K5P46KB3.js} +25 -10
  61. package/dist/chunk-K5P46KB3.js.map +1 -0
  62. package/dist/chunk-KYY7L72M.js +106 -0
  63. package/dist/chunk-KYY7L72M.js.map +1 -0
  64. package/dist/{chunk-5Z3RNFJC.js → chunk-LIP6JWYK.js} +3 -3
  65. package/dist/{chunk-OCDUQUAP.js → chunk-LN22XH4B.js} +1 -1
  66. package/dist/chunk-LN22XH4B.js.map +1 -0
  67. package/dist/chunk-LP7BEXCT.js +32 -0
  68. package/dist/chunk-LP7BEXCT.js.map +1 -0
  69. package/dist/{chunk-IJW6K6UX.js → chunk-LPRPVCNY.js} +5 -5
  70. package/dist/{chunk-6EVZXETK.js → chunk-M66NAZA4.js} +3 -3
  71. package/dist/{chunk-HGQG3VIP.js → chunk-N5YVZHCB.js} +2 -2
  72. package/dist/{chunk-IWVWB7BZ.js → chunk-NB47TXGP.js} +12 -12
  73. package/dist/chunk-NO272T7Q.js +194 -0
  74. package/dist/chunk-NO272T7Q.js.map +1 -0
  75. package/dist/{chunk-6OQ7NKMZ.js → chunk-O2DB4C3M.js} +6 -6
  76. package/dist/{chunk-LHYQE3BP.js → chunk-OFBFAVLI.js} +6 -6
  77. package/dist/{chunk-ZFME46HJ.js → chunk-OPTFANOX.js} +3 -3
  78. package/dist/chunk-OPTFANOX.js.map +1 -0
  79. package/dist/{chunk-5EZAJEES.js → chunk-OVO2RZAE.js} +81 -27
  80. package/dist/chunk-OVO2RZAE.js.map +1 -0
  81. package/dist/{chunk-6I2YPLAG.js → chunk-P27Z66EB.js} +7 -7
  82. package/dist/{chunk-7MHVHGQZ.js → chunk-P2LDXRGP.js} +2 -2
  83. package/dist/chunk-P3NGV5RV.js +41 -0
  84. package/dist/chunk-P3NGV5RV.js.map +1 -0
  85. package/dist/{chunk-YN66UOXT.js → chunk-P3V7JTB6.js} +25 -9
  86. package/dist/{chunk-YN66UOXT.js.map → chunk-P3V7JTB6.js.map} +1 -1
  87. package/dist/{chunk-NPVICKZE.js → chunk-P5WXDYMD.js} +8 -197
  88. package/dist/chunk-P5WXDYMD.js.map +1 -0
  89. package/dist/{chunk-CPAROOKP.js → chunk-PGFY7IRW.js} +12 -41
  90. package/dist/chunk-PGFY7IRW.js.map +1 -0
  91. package/dist/{chunk-6RASM2J4.js → chunk-QKVILR7N.js} +2 -2
  92. package/dist/{chunk-LKBLAUOB.js → chunk-QNTEDPWP.js} +3 -3
  93. package/dist/{chunk-P6UXDALK.js → chunk-RDHAGBEB.js} +3 -3
  94. package/dist/{chunk-XRE4JOEO.js → chunk-RTS23VIJ.js} +2 -2
  95. package/dist/{chunk-PYWW4KLO.js → chunk-SEQ2JI3Y.js} +9 -9
  96. package/dist/{chunk-VHEEU4ZO.js → chunk-SW56GSYC.js} +2 -2
  97. package/dist/{chunk-46YGCU6Z.js → chunk-T2EGAXPM.js} +2 -2
  98. package/dist/{chunk-LES2Z7B4.js → chunk-T45LAT2Y.js} +2 -2
  99. package/dist/{chunk-4NMFWOS2.js → chunk-T65UZXR6.js} +3 -3
  100. package/dist/{chunk-2N4MUSF3.js → chunk-TB5RNNJ4.js} +7 -7
  101. package/dist/chunk-TCIUO62Z.js +29 -0
  102. package/dist/chunk-TCIUO62Z.js.map +1 -0
  103. package/dist/chunk-THNJ3IKU.js +17 -0
  104. package/dist/chunk-THNJ3IKU.js.map +1 -0
  105. package/dist/{chunk-L4IRFTIF.js → chunk-TLJOJBZD.js} +3 -23
  106. package/dist/chunk-TLJOJBZD.js.map +1 -0
  107. package/dist/chunk-TQ3REHVF.js +95 -0
  108. package/dist/chunk-TQ3REHVF.js.map +1 -0
  109. package/dist/{chunk-NIA5VQ7G.js → chunk-TVRQ3RYH.js} +28 -9
  110. package/dist/chunk-TVRQ3RYH.js.map +1 -0
  111. package/dist/{chunk-6CNLU4TO.js → chunk-TYGW5TOR.js} +7 -7
  112. package/dist/{chunk-BLZRNHMG.js → chunk-U23JUUPX.js} +8 -1
  113. package/dist/{chunk-BLZRNHMG.js.map → chunk-U23JUUPX.js.map} +1 -1
  114. package/dist/{chunk-U5DWHU3S.js → chunk-U24XHXNK.js} +2 -2
  115. package/dist/chunk-ULIHDPKL.js +94 -0
  116. package/dist/chunk-ULIHDPKL.js.map +1 -0
  117. package/dist/chunk-UOEWDCUX.js +69 -0
  118. package/dist/chunk-UOEWDCUX.js.map +1 -0
  119. package/dist/{chunk-5A6TC3RQ.js → chunk-VAWY44JW.js} +8 -8
  120. package/dist/{chunk-5A6TC3RQ.js.map → chunk-VAWY44JW.js.map} +1 -1
  121. package/dist/{chunk-NTHKOFVL.js → chunk-VFRNWE5P.js} +52 -8
  122. package/dist/chunk-VFRNWE5P.js.map +1 -0
  123. package/dist/{chunk-4DZGZ7II.js → chunk-VMJ5URU7.js} +8 -8
  124. package/dist/chunk-VMJ5URU7.js.map +1 -0
  125. package/dist/{chunk-YDP2SA5K.js → chunk-VPCMJ5Z4.js} +5 -5
  126. package/dist/{chunk-ZAWD6O46.js → chunk-VRPBEOWU.js} +2 -2
  127. package/dist/{chunk-AY4P6PHN.js → chunk-VWGCJUTV.js} +2 -2
  128. package/dist/{chunk-IIK7W3AN.js → chunk-XJR3COJO.js} +5 -5
  129. package/dist/{chunk-ZD4D7UM6.js → chunk-XYYW64LB.js} +2 -2
  130. package/dist/{chunk-4NZCZUGL.js → chunk-YFF2RP3X.js} +2 -2
  131. package/dist/{chunk-WVIIJPTJ.js → chunk-Z3FZC5GV.js} +7 -7
  132. package/dist/{chunk-55HDKLI3.js → chunk-Z5PIUYNB.js} +8 -8
  133. package/dist/{chunk-ZRDYQZYH.js → chunk-Z7KI4WHR.js} +2 -2
  134. package/dist/chunk-ZKF6HH7V.js +120 -0
  135. package/dist/chunk-ZKF6HH7V.js.map +1 -0
  136. package/dist/{chunk-P6DN5QU7.js → chunk-ZKYMKF2S.js} +8 -8
  137. package/dist/{chunk-ADBMJDBW.js → chunk-ZPHDGUZZ.js} +445 -1077
  138. package/dist/chunk-ZPHDGUZZ.js.map +1 -0
  139. package/dist/{chunk-NMRKAGHE.js → chunk-ZROMNP7Q.js} +2 -2
  140. package/dist/classified/index.d.ts +4 -4
  141. package/dist/classified/index.js +3 -3
  142. package/dist/collection-facade-MKEBZDWW.js +39 -0
  143. package/dist/computed-BMMEFRFJ.js +11 -0
  144. package/dist/config-drift-KGM7ZRW4.js +24 -0
  145. package/dist/config-drift-KGM7ZRW4.js.map +1 -0
  146. package/dist/consent/index.d.ts +3 -3
  147. package/dist/consent/index.js +10 -7
  148. package/dist/consent/index.js.map +1 -1
  149. package/dist/crdt/index.d.ts +3 -3
  150. package/dist/delegation-BQNIEHZE.js +25 -0
  151. package/dist/derivations/index.d.ts +4 -4
  152. package/dist/derivations/index.js +12 -9
  153. package/dist/describe/index.d.ts +1 -1
  154. package/dist/{describe-0tiXAjoO.d.ts → describe-C6iHNlqJ.d.ts} +9 -0
  155. package/dist/{dev-unlock-B_s9DUWa.d.ts → dev-unlock-Cqd5Xv5J.d.ts} +1 -1
  156. package/dist/{enclave-IS7HZSQ7.js → enclave-YN6223OG.js} +21 -8
  157. package/dist/executor-CBTNU5VZ.js +9 -0
  158. package/dist/executor-DJHNSTIR.js +9 -0
  159. package/dist/executor-FGISLQIN.js +21 -0
  160. package/dist/export-accessible-P7SLRLK3.js +23 -0
  161. package/dist/extract-partition-RNVSFHAB.js +36 -0
  162. package/dist/{fanout-sidecar-DDKRG2MX.js → fanout-sidecar-WS22Q5WH.js} +12 -9
  163. package/dist/{fanout-sidecar-DDKRG2MX.js.map → fanout-sidecar-WS22Q5WH.js.map} +1 -1
  164. package/dist/fence-watcher-DHQ775JB.js +69 -0
  165. package/dist/fence-watcher-DHQ775JB.js.map +1 -0
  166. package/dist/find-RNBG7LBY.js +11 -0
  167. package/dist/forget/index.js +10 -7
  168. package/dist/forget/index.js.map +1 -1
  169. package/dist/guards/index.d.ts +4 -4
  170. package/dist/guards/index.js +3 -3
  171. package/dist/{hash-CWxn7sf6.d.ts → hash-D8Q5MJLA.d.ts} +1 -1
  172. package/dist/history/index.d.ts +4 -4
  173. package/dist/history/index.js +12 -9
  174. package/dist/history/index.js.map +1 -1
  175. package/dist/i18n/index.d.ts +3 -3
  176. package/dist/i18n/index.js +14 -11
  177. package/dist/i18n/index.js.map +1 -1
  178. package/dist/in/index.d.ts +2 -2
  179. package/dist/{index-D05bV0_g.d.ts → index-D4GQe1Rx.d.ts} +818 -49
  180. package/dist/{index-DTMUUwwW.d.ts → index-DRxk8q_7.d.ts} +3 -3
  181. package/dist/index.d.ts +46 -17
  182. package/dist/index.js +1021 -122
  183. package/dist/index.js.map +1 -1
  184. package/dist/indexing/index.d.ts +3 -3
  185. package/dist/indexing/index.js +4 -4
  186. package/dist/issue-W5QG53B5.js +19 -0
  187. package/dist/json-schema-I22JCYCG.js +44 -0
  188. package/dist/json-schema-I22JCYCG.js.map +1 -0
  189. package/dist/kernel/index.d.ts +3 -3
  190. package/dist/kernel/index.js +13 -10
  191. package/dist/lazy/index.d.ts +21 -0
  192. package/dist/lazy/index.js +12 -0
  193. package/dist/{ledger-YUAJUNFP.js → ledger-KZWBKAG5.js} +12 -9
  194. package/dist/liberate-GMGCHIND.js +24 -0
  195. package/dist/link-set-UQEIYQAM.js +31 -0
  196. package/dist/materialized-views/index.d.ts +4 -4
  197. package/dist/materialized-views/index.js +16 -13
  198. package/dist/{mime-magic-Qr_4HjP6.d.ts → mime-magic-DmwT7OzZ.d.ts} +1 -1
  199. package/dist/noydb-KS2O2MRI.js +60 -0
  200. package/dist/on/index.d.ts +2 -2
  201. package/dist/on/index.js +10 -7
  202. package/dist/overlay-views/index.d.ts +4 -4
  203. package/dist/overlay-views/index.js +4 -4
  204. package/dist/periods/index.d.ts +3 -3
  205. package/dist/periods/index.js +13 -10
  206. package/dist/pod/index.d.ts +3 -3
  207. package/dist/pod/index.js +12 -9
  208. package/dist/{policy-LRE6HTO5.js → policy-YIKUH4AD.js} +5 -5
  209. package/dist/portability/index.d.ts +3 -3
  210. package/dist/portability/index.js +8 -8
  211. package/dist/{public-envelope-WVRRUVAJ.js → public-envelope-MRN5YYZZ.js} +4 -4
  212. package/dist/query/index.d.ts +2 -2
  213. package/dist/query/index.js +6 -6
  214. package/dist/register-K6DDSIXN.js +21 -0
  215. package/dist/registry-IMNMHWTM.js +17 -0
  216. package/dist/registry-K6VUQXKV.js +19 -0
  217. package/dist/registry-ZVO3T4M5.js +9 -0
  218. package/dist/request-withdrawal-EHALV66Y.js +31 -0
  219. package/dist/request-withdrawal-EHALV66Y.js.map +1 -0
  220. package/dist/{reveal-WSUHXCSS.js → reveal-TBLTFWQ2.js} +6 -5
  221. package/dist/{reveal-WSUHXCSS.js.map → reveal-TBLTFWQ2.js.map} +1 -1
  222. package/dist/revoke-MHAUAESM.js +24 -0
  223. package/dist/revoke-MHAUAESM.js.map +1 -0
  224. package/dist/sealed-record/index.d.ts +3 -3
  225. package/dist/sealed-record/index.js +13 -10
  226. package/dist/sealed-record/index.js.map +1 -1
  227. package/dist/session/index.d.ts +4 -4
  228. package/dist/session/index.js +10 -7
  229. package/dist/session/index.js.map +1 -1
  230. package/dist/shadow/index.d.ts +3 -3
  231. package/dist/shadow/index.js +2 -2
  232. package/dist/signer-PQ74YXRY.js +25 -0
  233. package/dist/signer-PQ74YXRY.js.map +1 -0
  234. package/dist/snapshots/index.d.ts +3 -3
  235. package/dist/snapshots/index.js +11 -8
  236. package/dist/snapshots/index.js.map +1 -1
  237. package/dist/{stale-LX4BR43V.js → stale-7Q62KVI3.js} +2 -2
  238. package/dist/stale-7Q62KVI3.js.map +1 -0
  239. package/dist/storage-5E6YB2JY.js +21 -0
  240. package/dist/storage-5E6YB2JY.js.map +1 -0
  241. package/dist/{store-coordination-provider-KTRIC6PR.js → store-coordination-provider-JJCEMTAE.js} +3 -3
  242. package/dist/sync/index.d.ts +2 -2
  243. package/dist/sync/index.js +10 -7
  244. package/dist/sync/index.js.map +1 -1
  245. package/dist/team/index.d.ts +18 -4
  246. package/dist/team/index.js +24 -14
  247. package/dist/tiers/index.d.ts +2 -2
  248. package/dist/tiers/index.js +11 -8
  249. package/dist/to/index.d.ts +2 -2
  250. package/dist/to/index.js +1 -1
  251. package/dist/{transition-guard-C1Pyz8nH.d.ts → transition-guard-C4hvR-Ac.d.ts} +1 -1
  252. package/dist/tx/index.d.ts +3 -3
  253. package/dist/tx/index.js +3 -3
  254. package/dist/ui/index.d.ts +1 -1
  255. package/dist/util/index.js +1 -1
  256. package/dist/validators-Ctgkj5qd.d.ts +101 -0
  257. package/dist/{vault-diff-Fn0WeY2w.d.ts → vault-diff-B1Ir6EGs.d.ts} +1 -1
  258. package/dist/{verify-SW6J63Q2.js → verify-YB5LQHNA.js} +11 -7
  259. package/dist/{verify-SW6J63Q2.js.map → verify-YB5LQHNA.js.map} +1 -1
  260. package/dist/walk-5C3GPKT2.js +241 -0
  261. package/dist/walk-5C3GPKT2.js.map +1 -0
  262. package/dist/with/index.d.ts +3 -3
  263. package/dist/with/index.js +12 -9
  264. package/dist/{with-materialized-view-NKxs6iK5.d.ts → with-materialized-view-Bp65kKdQ.d.ts} +1 -1
  265. package/dist/{with-overlayed-view-B4fPYHwV.d.ts → with-overlayed-view-BRhdQNrK.d.ts} +1 -1
  266. package/dist/{with-rollup-Bl0sRFEt.d.ts → with-rollup-bQRPc3y1.d.ts} +1 -1
  267. package/dist/withdraw-accessible-JMX2TCPX.js +28 -0
  268. package/dist/withdraw-accessible-JMX2TCPX.js.map +1 -0
  269. package/package.json +7 -3
  270. package/dist/api-LORZ2EZU.js +0 -17
  271. package/dist/chunk-4DZGZ7II.js.map +0 -1
  272. package/dist/chunk-5EZAJEES.js.map +0 -1
  273. package/dist/chunk-ADBMJDBW.js.map +0 -1
  274. package/dist/chunk-CPAROOKP.js.map +0 -1
  275. package/dist/chunk-L4IRFTIF.js.map +0 -1
  276. package/dist/chunk-MIOLJG2R.js.map +0 -1
  277. package/dist/chunk-N2FP26NH.js.map +0 -1
  278. package/dist/chunk-NIA5VQ7G.js.map +0 -1
  279. package/dist/chunk-NPVICKZE.js.map +0 -1
  280. package/dist/chunk-NTHKOFVL.js.map +0 -1
  281. package/dist/chunk-OCDUQUAP.js.map +0 -1
  282. package/dist/chunk-OVIVYAQL.js.map +0 -1
  283. package/dist/chunk-QLQS5A7X.js +0 -524
  284. package/dist/chunk-QLQS5A7X.js.map +0 -1
  285. package/dist/chunk-Z44OY24N.js.map +0 -1
  286. package/dist/chunk-ZFME46HJ.js.map +0 -1
  287. package/dist/collection-facade-XPVRHBGU.js +0 -36
  288. package/dist/delegation-4HUHUE6T.js +0 -22
  289. package/dist/executor-ANFBCOYA.js +0 -9
  290. package/dist/executor-IKT47SH2.js +0 -9
  291. package/dist/executor-OIECZXTV.js +0 -18
  292. package/dist/export-accessible-NZWCFZHL.js +0 -20
  293. package/dist/extract-partition-52LX6RQH.js +0 -33
  294. package/dist/issue-F4SYPJGJ.js +0 -16
  295. package/dist/liberate-6LDETRIW.js +0 -21
  296. package/dist/noydb-WQNBVJIG.js +0 -54
  297. package/dist/registry-6HZ2JSQ7.js +0 -14
  298. package/dist/registry-GPXZQ7DT.js +0 -9
  299. package/dist/registry-USYD2ECC.js +0 -16
  300. package/dist/request-withdrawal-54V4L6CR.js +0 -28
  301. package/dist/revoke-JV26NTQD.js +0 -21
  302. package/dist/signer-AE56T5HE.js +0 -22
  303. package/dist/validators-Dzn7T-3x.d.ts +0 -62
  304. package/dist/withdraw-accessible-DGA4V2TP.js +0 -25
  305. /package/dist/{api-LORZ2EZU.js.map → api-JOXUNSKP.js.map} +0 -0
  306. /package/dist/{chunk-VBYVKOMJ.js.map → chunk-3QRQOBS7.js.map} +0 -0
  307. /package/dist/{chunk-JFYIHLU3.js.map → chunk-3Y4QLJ6K.js.map} +0 -0
  308. /package/dist/{chunk-BZIWKN74.js.map → chunk-43ISXURO.js.map} +0 -0
  309. /package/dist/{chunk-7IP75FP2.js.map → chunk-4K3MQ5S3.js.map} +0 -0
  310. /package/dist/{chunk-6DP5HBQD.js.map → chunk-5CY35H55.js.map} +0 -0
  311. /package/dist/{chunk-2KSPDSWI.js.map → chunk-5MRE3C4Q.js.map} +0 -0
  312. /package/dist/{chunk-5ZPWVNL3.js.map → chunk-5W7AOFWA.js.map} +0 -0
  313. /package/dist/{chunk-PUNJAEY6.js.map → chunk-6HNKCKFZ.js.map} +0 -0
  314. /package/dist/{chunk-PJDK2PPQ.js.map → chunk-6RXPSMKR.js.map} +0 -0
  315. /package/dist/{chunk-MCJAUQGE.js.map → chunk-A5DYVMDR.js.map} +0 -0
  316. /package/dist/{chunk-TICO2I2O.js.map → chunk-BKGIWGCX.js.map} +0 -0
  317. /package/dist/{chunk-O5DNEXQC.js.map → chunk-BMQOH7MM.js.map} +0 -0
  318. /package/dist/{chunk-U6OM4E67.js.map → chunk-CPXPHQGX.js.map} +0 -0
  319. /package/dist/{chunk-3UDPDRUC.js.map → chunk-EWR7HL3K.js.map} +0 -0
  320. /package/dist/{chunk-CVXLJIAV.js.map → chunk-FH52CDEW.js.map} +0 -0
  321. /package/dist/{chunk-FELHYKIO.js.map → chunk-G7RDYYTE.js.map} +0 -0
  322. /package/dist/{chunk-UP6EMMDI.js.map → chunk-GOUNIHFA.js.map} +0 -0
  323. /package/dist/{chunk-DHIN36UC.js.map → chunk-GQOT6QJR.js.map} +0 -0
  324. /package/dist/{chunk-DGUR3CC4.js.map → chunk-GXGK22QU.js.map} +0 -0
  325. /package/dist/{chunk-YTIAXSUE.js.map → chunk-GZZL5R73.js.map} +0 -0
  326. /package/dist/{chunk-E4YJUNPU.js.map → chunk-H5XRIJX3.js.map} +0 -0
  327. /package/dist/{chunk-DA34OEZU.js.map → chunk-H7RYPVMJ.js.map} +0 -0
  328. /package/dist/{chunk-2ZORB5RW.js.map → chunk-HBKDR7R3.js.map} +0 -0
  329. /package/dist/{chunk-BV7KNFJY.js.map → chunk-HLUKZ36Q.js.map} +0 -0
  330. /package/dist/{chunk-ZNI3RTFV.js.map → chunk-HMXLN43G.js.map} +0 -0
  331. /package/dist/{chunk-BYW7EU5L.js.map → chunk-HY6ZGGEC.js.map} +0 -0
  332. /package/dist/{chunk-5Z3RNFJC.js.map → chunk-LIP6JWYK.js.map} +0 -0
  333. /package/dist/{chunk-IJW6K6UX.js.map → chunk-LPRPVCNY.js.map} +0 -0
  334. /package/dist/{chunk-6EVZXETK.js.map → chunk-M66NAZA4.js.map} +0 -0
  335. /package/dist/{chunk-HGQG3VIP.js.map → chunk-N5YVZHCB.js.map} +0 -0
  336. /package/dist/{chunk-IWVWB7BZ.js.map → chunk-NB47TXGP.js.map} +0 -0
  337. /package/dist/{chunk-6OQ7NKMZ.js.map → chunk-O2DB4C3M.js.map} +0 -0
  338. /package/dist/{chunk-LHYQE3BP.js.map → chunk-OFBFAVLI.js.map} +0 -0
  339. /package/dist/{chunk-6I2YPLAG.js.map → chunk-P27Z66EB.js.map} +0 -0
  340. /package/dist/{chunk-7MHVHGQZ.js.map → chunk-P2LDXRGP.js.map} +0 -0
  341. /package/dist/{chunk-6RASM2J4.js.map → chunk-QKVILR7N.js.map} +0 -0
  342. /package/dist/{chunk-LKBLAUOB.js.map → chunk-QNTEDPWP.js.map} +0 -0
  343. /package/dist/{chunk-P6UXDALK.js.map → chunk-RDHAGBEB.js.map} +0 -0
  344. /package/dist/{chunk-XRE4JOEO.js.map → chunk-RTS23VIJ.js.map} +0 -0
  345. /package/dist/{chunk-PYWW4KLO.js.map → chunk-SEQ2JI3Y.js.map} +0 -0
  346. /package/dist/{chunk-VHEEU4ZO.js.map → chunk-SW56GSYC.js.map} +0 -0
  347. /package/dist/{chunk-46YGCU6Z.js.map → chunk-T2EGAXPM.js.map} +0 -0
  348. /package/dist/{chunk-LES2Z7B4.js.map → chunk-T45LAT2Y.js.map} +0 -0
  349. /package/dist/{chunk-4NMFWOS2.js.map → chunk-T65UZXR6.js.map} +0 -0
  350. /package/dist/{chunk-2N4MUSF3.js.map → chunk-TB5RNNJ4.js.map} +0 -0
  351. /package/dist/{chunk-6CNLU4TO.js.map → chunk-TYGW5TOR.js.map} +0 -0
  352. /package/dist/{chunk-U5DWHU3S.js.map → chunk-U24XHXNK.js.map} +0 -0
  353. /package/dist/{chunk-YDP2SA5K.js.map → chunk-VPCMJ5Z4.js.map} +0 -0
  354. /package/dist/{chunk-ZAWD6O46.js.map → chunk-VRPBEOWU.js.map} +0 -0
  355. /package/dist/{chunk-AY4P6PHN.js.map → chunk-VWGCJUTV.js.map} +0 -0
  356. /package/dist/{chunk-IIK7W3AN.js.map → chunk-XJR3COJO.js.map} +0 -0
  357. /package/dist/{chunk-ZD4D7UM6.js.map → chunk-XYYW64LB.js.map} +0 -0
  358. /package/dist/{chunk-4NZCZUGL.js.map → chunk-YFF2RP3X.js.map} +0 -0
  359. /package/dist/{chunk-WVIIJPTJ.js.map → chunk-Z3FZC5GV.js.map} +0 -0
  360. /package/dist/{chunk-55HDKLI3.js.map → chunk-Z5PIUYNB.js.map} +0 -0
  361. /package/dist/{chunk-ZRDYQZYH.js.map → chunk-Z7KI4WHR.js.map} +0 -0
  362. /package/dist/{chunk-P6DN5QU7.js.map → chunk-ZKYMKF2S.js.map} +0 -0
  363. /package/dist/{chunk-NMRKAGHE.js.map → chunk-ZROMNP7Q.js.map} +0 -0
  364. /package/dist/{collection-facade-XPVRHBGU.js.map → collection-facade-MKEBZDWW.js.map} +0 -0
  365. /package/dist/{delegation-4HUHUE6T.js.map → computed-BMMEFRFJ.js.map} +0 -0
  366. /package/dist/{enclave-IS7HZSQ7.js.map → delegation-BQNIEHZE.js.map} +0 -0
  367. /package/dist/{executor-ANFBCOYA.js.map → enclave-YN6223OG.js.map} +0 -0
  368. /package/dist/{executor-IKT47SH2.js.map → executor-CBTNU5VZ.js.map} +0 -0
  369. /package/dist/{executor-OIECZXTV.js.map → executor-DJHNSTIR.js.map} +0 -0
  370. /package/dist/{export-accessible-NZWCFZHL.js.map → executor-FGISLQIN.js.map} +0 -0
  371. /package/dist/{extract-partition-52LX6RQH.js.map → export-accessible-P7SLRLK3.js.map} +0 -0
  372. /package/dist/{issue-F4SYPJGJ.js.map → extract-partition-RNVSFHAB.js.map} +0 -0
  373. /package/dist/{ledger-YUAJUNFP.js.map → find-RNBG7LBY.js.map} +0 -0
  374. /package/dist/{liberate-6LDETRIW.js.map → issue-W5QG53B5.js.map} +0 -0
  375. /package/dist/{noydb-WQNBVJIG.js.map → lazy/index.js.map} +0 -0
  376. /package/dist/{policy-LRE6HTO5.js.map → ledger-KZWBKAG5.js.map} +0 -0
  377. /package/dist/{public-envelope-WVRRUVAJ.js.map → liberate-GMGCHIND.js.map} +0 -0
  378. /package/dist/{registry-6HZ2JSQ7.js.map → link-set-UQEIYQAM.js.map} +0 -0
  379. /package/dist/{registry-GPXZQ7DT.js.map → noydb-KS2O2MRI.js.map} +0 -0
  380. /package/dist/{registry-USYD2ECC.js.map → policy-YIKUH4AD.js.map} +0 -0
  381. /package/dist/{request-withdrawal-54V4L6CR.js.map → public-envelope-MRN5YYZZ.js.map} +0 -0
  382. /package/dist/{revoke-JV26NTQD.js.map → register-K6DDSIXN.js.map} +0 -0
  383. /package/dist/{signer-AE56T5HE.js.map → registry-IMNMHWTM.js.map} +0 -0
  384. /package/dist/{stale-LX4BR43V.js.map → registry-K6VUQXKV.js.map} +0 -0
  385. /package/dist/{withdraw-accessible-DGA4V2TP.js.map → registry-ZVO3T4M5.js.map} +0 -0
  386. /package/dist/{store-coordination-provider-KTRIC6PR.js.map → store-coordination-provider-JJCEMTAE.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/kernel/types.ts"],"sourcesContent":["/**\n * Core types — the {@link NoydbStore} interface, envelope format, roles, and\n * all configuration shapes consumed by {@link createNoydb}.\n *\n * ## What lives here\n *\n * - **{@link NoydbStore}** — the 6-method contract every backend must implement\n * (`get`, `put`, `delete`, `list`, `loadAll`, `saveAll`).\n * - **{@link EncryptedEnvelope}** — the wire format stored by backends:\n * `{ _noydb, _v, _ts, _iv, _data }`. Backends only ever see this shape.\n * - **{@link Role} / {@link Permission}** — the access-control vocabulary\n * (`owner`, `admin`, `operator`, `viewer`, `client`).\n * - **{@link NoydbOptions}** — the full configuration object passed to\n * {@link createNoydb}.\n *\n * ## Extending the store interface\n *\n * All optional store capabilities (`ping`, `listPage`, `listSince`,\n * `presencePublish`, `presenceSubscribe`, `listVaults`) are additive extensions\n * discovered via `'method' in store`. Implementing them unlocks features but\n * is never required — core always falls back to the 6-method baseline.\n *\n * @module\n */\n\nimport type { StandardSchemaV1 } from './schema.js'\nimport type { DeferredNumberingConfig } from '../with-commit/numbering/descriptor.js'\nimport type { SyncPolicy } from './sync-policy.js'\nimport type { BlobStrategy } from '../with-shape/blobs/strategy.js'\nimport type { ArchiveStrategy } from '../with-fork/archive/index.js'\nimport type { IndexStrategy } from '../with-lookup/indexing/strategy.js'\nimport type { AggregateStrategy } from '../with-lookup/aggregate/strategy.js'\nimport type { LwwMapState, RgaState, YjsState } from '../with-commit/crdt/crdt.js'\nimport type { ConsentStrategy } from '../with-audit/consent/strategy.js'\nimport type { PeriodsStrategy } from '../with-audit/periods/strategy.js'\nimport type { ShadowStrategy } from '../with-fork/shadow/strategy.js'\nimport type { TxStrategy } from '../with-commit/tx/strategy.js'\nimport type { HistoryStrategy } from '../with-commit/history/strategy.js'\nimport type { ForgetStrategy } from '../with-audit/forget/strategy.js'\nimport type { SnapshotStrategy } from '../with-fork/snapshots/strategy.js'\nimport type { AttestationStrategy } from '../with-audit/attestation/strategy.js'\nimport type { ClassifiedStrategy } from '../with-shape/classified/strategy.js'\nimport type { TiersStrategy } from '../with-audit/tiers/strategy.js'\nimport type { SealedRecordStrategy } from '../with-audit/sealed-record/strategy.js'\nimport type { PortabilityStrategy } from '../with-audit/portability/strategy.js'\nimport type { SequenceStrategy } from '../with-commit/sequence/strategy.js'\nimport type { CustodyStrategy } from '../with-party/custody/strategy.js'\nimport type { SearchStrategy } from '../with-lookup/search/strategy.js'\nimport type { CargoStrategy } from '../with-cargo/strategy.js'\nimport type { Layer } from '../with-shape/i18n/policy.js'\nimport type { I18nStrategy } from '../with-shape/i18n/strategy.js'\nimport type { SessionStrategy } from '../with-party/session/strategy.js'\nimport type { SyncStrategy } from '../with-party/team/sync-strategy.js'\nimport type { GuardStrategyHandleAny } from '../with-audit/guards/types.js'\nimport type { DerivationStrategyHandle } from '../with-formula/derivations/types.js'\nimport type { UnlockedKeyring } from '../with-party/team/keyring.js'\nimport type { PassphrasePolicy } from './validation.js'\nimport type { PublicEnvelopeSchema } from '../with-party/directory/public-envelope/types.js'\nimport type { MaterializedViewStrategyHandle } from '../with-formula/materialized-views/types.js'\nimport type { OverlayedViewStrategyHandle } from '../with-formula/overlay-views/types.js'\nimport type { SealingKeyProvider, RecipientHint } from '../with-party/team/managed-passphrase.js'\nimport type { ShamirRecoveryProvider } from '../with-party/team/shamir-recovery-provider.js'\nimport type { ObjectProjection } from '../with-shape/blobs/object-projection.js'\nimport type { CoordinationProvider } from '../port/by/types.js'\nimport type { ScriptWarning } from '../with-shape/i18n/script.js'\nimport type { MoneyDescriptor } from '../with-shape/money/descriptor.js'\nimport type { EnclaveKey } from './enclave/index.js'\n\n/** Format version for encrypted record envelopes. */\nexport const NOYDB_FORMAT_VERSION = 1 as const\n\n/** Format version for keyring files. */\nexport const NOYDB_KEYRING_VERSION = 1 as const\n\n/** Format version for backup files. */\nexport const NOYDB_BACKUP_VERSION = 1 as const\n\n/** Format version for sync metadata. */\nexport const NOYDB_SYNC_VERSION = 1 as const\n\n// ─── Roles & Permissions ───────────────────────────────────────────────\n\n/**\n * Access role assigned to a user within a vault.\n *\n * Roles control both the operations a user can perform and which DEKs\n * they receive in their keyring:\n *\n * | Role | Collections | Can grant/revoke | Can export |\n * |-------------|-----------------|:----------------:|:----------:|\n * | `owner` | all (rw) | Yes (all roles) | Yes |\n * | `admin` | all (rw) | Yes (≤ admin) | Yes |\n * | `custodian` | all (rw) | No (see below) | Yes |\n * | `operator` | explicit (rw) | No | ACL-scoped |\n * | `viewer` | all (ro) | No | Yes |\n * | `client` | explicit (ro) | No | ACL-scoped |\n *\n * **`custodian` (FR-6 sovereign custody).** Operationally admin-rank —\n * rw + access on every collection, receives all collection DEKs on grant\n * — but is *provably non-owning*: it CANNOT grant, revoke, rotate keys,\n * destructively withdraw/sever, or extract-and-sever a partition (rotate is\n * blocked in `rotateKeys`, sever in `withdrawAccessibleData`, and extract in\n * `extractPartition`). Only the (sealed Deed) **owner** may\n * mint or remove a custodian; an admin cannot. This is the inalienability\n * floor — a custodian can run the vault day-to-day yet never escalate to\n * the owner credential.\n */\nexport type Role = 'owner' | 'admin' | 'custodian' | 'operator' | 'viewer' | 'client'\n\n/**\n * Read-write or read-only access on a collection.\n * Stored per-collection in the user's keyring.\n */\nexport type Permission = 'rw' | 'ro'\n\n/**\n * Map of collection name → permission level for a user's keyring entry.\n * `'*'` is the wildcard collection matching all collections in the vault.\n */\nexport type Permissions = Record<string, Permission>\n\n// ─── Encrypted Envelope ────────────────────────────────────────────────\n\n/** The encrypted wrapper stored by stores. Stores only ever see this. */\nexport interface EncryptedEnvelope {\n readonly _noydb: typeof NOYDB_FORMAT_VERSION\n readonly _v: number\n readonly _ts: string\n readonly _iv: string\n readonly _data: string\n /** User who created this version (unencrypted metadata). */\n readonly _by?: string\n /**\n * Opaque provenance source id — which party/registry wrote this version.\n * Unencrypted; present only when the collection opts into `provenance: true`\n * and a `source` is supplied to `put()`. Off by default (zero cost).\n */\n readonly _source?: string\n /** ISO-8601 timestamp the provenance source was recorded. Present alongside `_source`. */\n readonly _sourceTs?: string\n /**\n * Hierarchical access tier. Omitted → tier 0.\n *\n * Unencrypted on purpose — the store reads it to route the envelope\n * to the right DEK slot without having to try-decrypt against every\n * tier. Only leaks the tier of each record, not any value\n * equivalence.\n */\n readonly _tier?: number\n /**\n * User id who last elevated this record. Used by\n * `demote()` to gate the reverse operation: only the original\n * elevator or an owner can demote a record back down. Cleared on\n * every successful demote so a later re-elevate requires the new\n * actor to own the demotion right.\n */\n readonly _elevatedBy?: string\n /**\n * Deterministic-encryption index. Map of field name →\n * base64 deterministic ciphertext. Present only when the collection\n * declares `deterministicFields` and the feature is acknowledged. The\n * field names are unencrypted (they're the index keys); the values\n * are AES-GCM ciphertext with an HKDF-derived deterministic IV.\n *\n * Enables blind equality search (`collection.findByDet(field,\n * value)`) without decrypting every record. Leaks equality as a known\n * side channel.\n */\n readonly _det?: Record<string, string>\n /**\n * Structural group-encryption. Map of sensitive field name →\n * per-field sealed ciphertext in `iv:data` form (same shape as a `_det`\n * slot). Present only when the collection declares `sensitive` fields and\n * at least one is present on the record. Each field is encrypted under its\n * own HKDF-derived per-field key (`deriveSealedFieldKey`, domain-separated\n * by `<collection>/sealed/<field>`), and is kept OUT of the open `_data`\n * blob — so a reader who can open `_data` still cannot see sealed fields\n * without re-deriving each field key. With no sensitive fields declared the\n * map is absent and `_data` is unchanged (byte-identical to legacy output).\n */\n readonly _sealed?: Record<string, string>\n /**\n * Verify-digest slots (classified stage 2). Map of digest-only field name →\n * AES-256-GCM `iv:data` blob sealed under the HKDF(CEK) vdig slot key with\n * AAD ['noydb-classify-vdig', collection, recordId, field]. The store sees\n * only ciphertext; only the enclave verify path can read the digest. At most\n * one of `_sealed[field]` / `_vdig[field]` exists per field (I4).\n */\n readonly _vdig?: Record<string, string>\n /**\n * Per-record content-encryption key (CEK), base64 AES-KW-wrapped under\n * the collection (or tier) DEK. Present only on records written by a\n * collection opened with `perRecordKeys: true`. When present, the body\n * (`_iv`/`_data`) is encrypted under the unwrapped CEK rather than the\n * collection DEK directly.\n *\n * Presence is the format discriminant: `_cek` absent → legacy body\n * keyed off the collection DEK (read unchanged); `_cek` present →\n * unwrap under the collection DEK, then decrypt the body under the CEK.\n *\n * The CEK is stable across every version of a record (insert mints it;\n * updates and history snapshots reuse it), so all `_history` envelopes\n * for a record carry the same `_cek`. This is the foundation for\n * per-record erasure and record-scoped sealing.\n *\n * `_det` slots are deliberately NOT keyed off the CEK — they remain\n * keyed to the collection DEK so blind-equality search keeps working\n * across records.\n */\n readonly _cek?: string\n /**\n * Debug-plaintext marker. Present only on records written by a vault opened\n * with `debugPlaintext: true` (which requires `encrypt: false`). When set,\n * the record's own fields are inlined as top-level keys on this envelope\n * (beside the reserved `_`-prefixed metadata) and `_data` is empty — so\n * native store tooling (jq, S3 console) reads the record directly. The read\n * path reconstructs the record from the non-`_` keys; the marker makes a\n * debug envelope self-describing, so a classic plaintext reader handles it too.\n */\n readonly _debug?: typeof NOYDB_FORMAT_VERSION\n}\n\n/** Spine policy for one digest-only classified field — the enclave-consumable\n * projection of a ClassifiedFieldSpec (the enclave never imports with-*). */\nexport interface VdigFieldPolicy {\n readonly normalize: 'password' | 'secret-answer'\n /** Ring size for reuse refusal; 0 = no ring. Cap 8 (spec Q4). */\n readonly notLastN: number\n readonly rotateDays?: number\n}\n\n/** Verdict-only egress of the enclave oracle (spec §3). */\nexport interface ClassifiedVerdict {\n readonly ok: boolean\n /** I1: present ONLY when ok === true — never computed for a false verdict. */\n readonly mustRotate?: true\n}\n\n/**\n * Opaque access gate for a sealed (`sensitive`) field returned by a public\n * read (the access layer). The handle carries only the per-field\n * **ciphertext** — the plaintext is never materialised into the working-set\n * cache. Call {@link Sealed.reveal} to decrypt the value on demand.\n *\n * A handle is intentionally NOT usable as `V`: it serialises to a non-leaking\n * marker (`JSON.stringify` / structured logging emit `'[sealed]'`, never the\n * value) and exposes no synchronous accessor.\n */\nexport interface Sealed<V> {\n /** Discriminant — always `true`, lets callers narrow a field to a handle. */\n readonly sealed: true\n /** Decrypt and return the underlying value. */\n reveal(): Promise<V>\n}\n\n/**\n * The shape a public read returns for a collection that declares `sensitive`\n * fields `S`: every sealed field becomes an opaque {@link Sealed} handle while\n * the rest of the record is unchanged. The `[S] extends [never]` guard collapses\n * `SealedView<T, never>` to exactly `T`, so collections with no sensitive fields\n * are unaffected — a plain `Omit<T, never>` is *not* a faithful identity for\n * generic intersection record types (it can degrade intersection-only members to\n * `unknown`), which would break consumers like the derivation/MV `_derivedFrom` /\n * `_materializedFrom` reads.\n */\nexport type SealedView<T, S extends keyof T> = [S] extends [never]\n ? T\n : Omit<T, S> & {\n readonly [K in S]: Sealed<T[K]>\n }\n\n/**\n * The type of a field-name argument to the query/scan DSL (`where`, `orderBy`,\n * …) for a collection whose sealed (`sensitive`) fields are `S`.\n *\n * Guarded so the common case is unchanged: with **no** sensitive fields\n * (`S = never`) it is exactly `string` — collections that don't opt into\n * `sensitive` keep today's permissive DSL, zero churn. Once a field is\n * declared `sensitive`, the DSL narrows to the non-sensitive field names, so\n * `where('ssn', …)` becomes a compile error. TypeScript cannot subtract a\n * literal from `string`, so refusing a sensitive name necessarily means\n * narrowing to the known field-name union — this is intentional and only\n * affects collections that opted in.\n *\n * When `Q` (the indexed-field set) is given, `where()` is additionally\n * restricted to `Q` minus any sensitive fields — the escape hatch for\n * non-indexed filters is `scan()`. `Q = never` (the default) preserves the\n * existing 2-param behaviour exactly (zero churn).\n */\nexport type QueryField<T, S extends keyof T = never, Q extends keyof T & string = never> =\n [Q] extends [never]\n ? ([S] extends [never] ? string : Exclude<keyof T & string, S>)\n : Exclude<Q, S>\n\n/**\n * The type of a field-name reference in a collection's index-declaration\n * options (`indexes`, `deterministicFields`, `textIndexes`). Same guarded\n * narrowing as {@link QueryField}: permissive `string` until a field is\n * declared `sensitive`, then the sensitive names are refused (a plaintext\n * secondary index over a sealed field defeats non-residency). Kept distinct\n * from `QueryField` so the two DSL surfaces can diverge later without coupling.\n *\n * When `Q` (the indexed-field set) is given, the `indexes` option is\n * additionally restricted to `Q` minus any sensitive fields — declaring `Q`\n * but listing a different field in `indexes` becomes a compile error.\n * `Q = never` (the default) preserves the existing 2-param behaviour.\n */\nexport type IndexFieldName<T, S extends keyof T = never, Q extends keyof T & string = never> =\n [Q] extends [never]\n ? ([S] extends [never] ? string : Exclude<keyof T & string, S>)\n : Exclude<Q, S>\n\n/**\n * Generic form of the runtime `IndexDef` (see `indexing/eager-indexes.ts`)\n * parameterised by the allowed field-name set `F`. Used to refuse `sensitive`\n * fields in the `indexes` collection option at compile time while leaving the\n * runtime `IndexDef` (string-based) untouched. `IndexDefFor<string>` is\n * structurally identical to `IndexDef`, which is why `vault.collection` can cast\n * the narrowed public option to `IndexDef[]` at the runtime boundary (through\n * `unknown`, solely to drop the `readonly`).\n * **Keep this in sync with `IndexDef`** — if `IndexDef` gains a new union member,\n * add it here too, or that boundary cast will silently admit shapes the runtime\n * machinery does not narrow.\n */\nexport type IndexDefFor<F extends string> =\n | F\n | { readonly fields: readonly F[]; readonly unique?: boolean }\n | readonly F[]\n\n/**\n * The type of the `sensitive` collection option, conditional on whether the\n * caller opted into compile-time refusal via an explicit second generic.\n * With no 2nd generic (`S = never`) it accepts any field array — runtime\n * sealing only, no compile refusal, non-breaking. With `S` given, it is\n * `readonly S[]`, which ties the runtime array to the declared sensitive\n * union so the two cannot drift.\n */\nexport type SensitiveOpt<T, S extends keyof T> = [S] extends [never]\n ? readonly (keyof T & string)[]\n : readonly S[]\n\n/**\n * The type of the `moneyFields` collection option, conditional on whether the\n * caller opted into compile-time money-field typing via the 4th generic `M`.\n * With no `M` (`M = never`) it accepts any `Record<string, MoneyDescriptor>` —\n * runtime money only, no compile-level narrowing, non-breaking. With `M` given,\n * it is `Record<M, MoneyDescriptor>`, tying the runtime map to the declared\n * money-field union so the two cannot drift.\n */\nexport type MoneyFieldsOpt<T, M extends keyof T & string = never> =\n [M] extends [never] ? Record<string, MoneyDescriptor> : Record<M, MoneyDescriptor>\n\n/**\n * Concrete {@link Sealed} handle. Holds the reveal closure (which captures the\n * field's ciphertext blob and the unseal routine) in a private field, so it is\n * invisible to `JSON.stringify`, `util.inspect`, and `Object.keys`. `toJSON`\n * returns the marker `'[sealed]'` — a handle can never leak its value through\n * serialisation or logging because the plaintext is not stored on it at all.\n */\nexport class SealedHandle<V> implements Sealed<V> {\n readonly sealed = true as const\n readonly #reveal: () => Promise<V>\n\n constructor(reveal: () => Promise<V>) {\n this.#reveal = reveal\n }\n\n reveal(): Promise<V> {\n return this.#reveal()\n }\n\n /** Non-leaking serialisation marker — never the underlying value. */\n toJSON(): string {\n return '[sealed]'\n }\n}\n\n/**\n * Handover-capable provider. Implemented additionally by asymmetric/granted\n * providers (cloud-KMS asymmetric, Azure RSA Key Vault, AWS KMS with grant).\n * Self-only providers (macOS Keychain, env-var, WebAuthn-PRF) do NOT\n * implement this — the §11.2 capability matrix lives in the type system.\n *\n * Per foundation §11.4. A function that requires recipient-target sealing\n * takes `RecipientSealer`, not `SealingKeyProvider` — the compiler rejects\n * passing a self-only provider at the spec site.\n */\nexport interface RecipientSealer {\n readonly id: string\n /** Produce hint material a sender uses to seal-for-this-recipient. */\n publishRecipientHint(): Promise<RecipientHint>\n /**\n * Seal plaintext for the recipient described by `hint`. Returns opaque\n * bytes — same contract as `SealingKeyProvider.seal()`. The bundle\n * layer base64-encodes the bytes into `SealedAutoUnlockEntry.sealed`\n * without inspecting them.\n */\n sealForRecipient(plaintext: Uint8Array, hint: RecipientHint): Promise<Uint8Array>\n}\n\n/**\n * Thin delivery envelope persisted at\n * `_sealed_cek/<collection>/<id>/<pid>`. The grantor writes one per\n * (record, recipient host) pair. `payload` is the base64 of the bytes returned\n * by {@link RecipientSealer.sealForRecipient} over a UTF-8\n * `JSON.stringify({@link SealedCekBinding})`.\n *\n * `expiresAt` is duplicated here for a cheap pre-unseal reject, but is NOT\n * authoritative — the binding inside `payload` carries the expiry the host\n * verifies after unsealing, so a tampered delivery envelope cannot extend a\n * grant.\n */\nexport interface SealedCekDeliveryEnvelope {\n /** Envelope schema version. */\n readonly v: 1\n /** Magic marker for forensics + format detection. */\n readonly _noydb_sealed_cek: 1\n /** Recipient host provider id; matches the sealer's `.id` / hint `pid`. */\n readonly pid: string\n /** base64 of the sealed {@link SealedCekBinding} bytes. */\n readonly payload: string\n /** Fast-path expiry hint (ISO 8601). Authoritative copy is inside `payload`. */\n readonly expiresAt: string\n}\n\n/**\n * The plaintext struct sealed for the recipient host. After the host unseals\n * `SealedCekDeliveryEnvelope.payload` it parses this and MUST verify:\n * - `collection` + `id` match the record envelope it is decrypting, and\n * - `expiresAt` has not passed (authoritative expiry check).\n *\n * `cek` is the base64 of the raw 32-byte AES-256-GCM record CEK.\n */\nexport interface SealedCekBinding {\n /** Collection the CEK belongs to. */\n readonly collection: string\n /** Record id the CEK belongs to. */\n readonly id: string\n /** base64 of the raw AES-256-GCM CEK bytes. */\n readonly cek: string\n /** Authoritative expiry (ISO 8601). */\n readonly expiresAt: string\n}\n\n/**\n * Placeholder returned by `getAtTier()` in `'ghost'` mode when a\n * record is at a tier the caller cannot decrypt. Record existence is\n * advertised — the id and tier are visible — but contents are\n * withheld. `canElevateFrom` lists user ids authorized to elevate\n * access for this caller when known; absent when the workflow is\n * not configured.\n */\nexport interface GhostRecord {\n readonly _ghost: true\n readonly _tier: number\n readonly canElevateFrom?: readonly string[]\n}\n\n/** Control what lower-tier reads see above their clearance. */\nexport type TierMode = 'invisibility' | 'ghost'\n\n/**\n * Event emitted when a record at a tier above the caller's inherent\n * clearance is read or written successfully (via elevation or\n * delegation). Always written to the ledger; subscribers get a\n * real-time feed.\n */\nexport interface CrossTierAccessEvent {\n readonly actor: string\n readonly collection: string\n readonly id: string\n readonly tier: number\n /** How the caller gained tier access: they elevated it, or a delegation is active. */\n readonly authorization: 'elevation' | 'delegation' | 'inherent'\n readonly op: 'get' | 'put' | 'elevate' | 'demote'\n readonly ts: string\n /**\n * When `authorization === 'elevation'`, the audit reason string the\n * caller passed to `vault.elevate(...)`. Empty for inherent /\n * delegation paths.\n */\n readonly reason?: string\n /**\n * When `authorization === 'elevation'`, the tier the caller's\n * keyring effectively held BEFORE elevation. Useful for audit\n * dashboards distinguishing \"operator elevating to 2\" from\n * \"inherent tier-2 write.\"\n */\n readonly elevatedFrom?: number\n}\n\n/**\n * A single deterministic-ciphertext index slot on an envelope. Stored\n * as `iv:data` (both base64, colon-separated) so a single string per\n * field keeps the envelope compact.\n */\nexport type DeterministicCipher = string\n\n// ─── Vault Snapshot ──────────────────────────────────────────────\n\n/** All records across all collections for a compartment. */\nexport type VaultSnapshot = Record<string, Record<string, EncryptedEnvelope>>\n\n/**\n * Result of a single page fetch via the optional `listPage` adapter extension.\n *\n * `items` carries the actual encrypted envelopes (not just ids) so the\n * caller can decrypt and emit a single record without an extra `get()`\n * round-trip per id. `nextCursor` is `null` on the final page.\n */\nexport interface ListPageResult {\n /** Encrypted envelopes for this page, in adapter-defined order. */\n items: Array<{ id: string; envelope: EncryptedEnvelope }>\n /** Opaque cursor for the next page, or `null` if this was the last page. */\n nextCursor: string | null\n}\n\n// ─── Store Interface ───────────────────────────────────────────────────\n\nexport interface NoydbStore {\n /**\n * Optional human-readable store name (e.g. 'memory', 'file', 'dynamo').\n * Used in diagnostic messages and the listPage fallback warning. Stores\n * are encouraged to set this so logs are clearer about which backend is\n * involved when something goes wrong.\n */\n name?: string\n\n /**\n * Optional declared store capabilities (CAS atomicity, native tx, blob\n * size limits, auth). Consumers that require a capability — e.g.\n * `vault.sequence().next()` needs `casAtomic` — read it here.\n */\n capabilities?: StoreCapabilities\n\n /** Get a single record. Returns null if not found. */\n get(vault: string, collection: string, id: string): Promise<EncryptedEnvelope | null>\n\n /** Put a record. Throws ConflictError if expectedVersion doesn't match. */\n put(\n vault: string,\n collection: string,\n id: string,\n envelope: EncryptedEnvelope,\n expectedVersion?: number,\n ): Promise<void>\n\n /** Delete a record. */\n delete(vault: string, collection: string, id: string): Promise<void>\n\n /** List all record IDs in a collection. */\n list(vault: string, collection: string): Promise<string[]>\n\n /** Load all records for a vault (initial hydration). */\n loadAll(vault: string): Promise<VaultSnapshot>\n\n /** Save all records for a vault (bulk write / restore). */\n saveAll(vault: string, data: VaultSnapshot): Promise<void>\n\n /** Optional connectivity check for sync engine. */\n ping?(): Promise<boolean>\n\n /**\n * The store's authoritative time as a bounded-uncertainty interval.\n * Present iff `capabilities.serverWriteTime` is true. Monotonic\n * non-decreasing across calls on a single store.\n */\n getStoreTime?(): Promise<StoreTime>\n\n /**\n * Optional: list record IDs in a collection that have `_ts` after `since`.\n * Used by partial sync (`pull({ modifiedSince })`). Stores that omit this\n * fall back to a full `loadAll` + client-side timestamp filter.\n */\n listSince?(vault: string, collection: string, since: string): Promise<string[]>\n\n /**\n * Optional pagination extension. Stores that implement `listPage` get\n * the streaming `Collection.scan()` fast path; stores that don't are\n * silently fallen back to a full `loadAll()` + slice (with a one-time\n * console.warn).\n *\n * `cursor` is opaque to the core — each store encodes its own paging\n * state (DynamoDB: base64 LastEvaluatedKey JSON; S3: ContinuationToken;\n * memory/file/browser: numeric offset of a sorted id list). Pass\n * `undefined` to start from the beginning.\n *\n * `limit` is a soft upper bound on `items.length`. Stores MAY return\n * fewer items even when more exist (e.g. if the underlying store has\n * its own page size cap), and MUST signal \"no more pages\" by returning\n * `nextCursor: null`.\n *\n * The 6-method core contract is unchanged — this is an additive\n * extension discovered via `'listPage' in adapter`.\n */\n listPage?(\n vault: string,\n collection: string,\n cursor?: string,\n limit?: number,\n ): Promise<ListPageResult>\n\n /**\n * Optional pub/sub for real-time presence.\n * Publish an encrypted payload to a presence channel.\n * Falls back to storage-based polling when absent.\n */\n presencePublish?(channel: string, payload: string): Promise<void>\n\n /**\n * Optional pub/sub for real-time presence.\n * Subscribe to a presence channel. Returns an unsubscribe function.\n * Falls back to storage-based polling when absent.\n */\n presenceSubscribe?(channel: string, callback: (payload: string) => void): () => void\n\n /**\n * Optional cross-vault enumeration extension.\n *\n * Returns the names of every top-level vault the store\n * currently stores. Used by `Noydb.listAccessibleVaults()` to\n * enumerate the universe of vaults before filtering down to\n * the ones the calling principal can actually unwrap.\n *\n * **Why this is optional:** the storage shape of compartments\n * differs across backends. Memory and file stores store\n * vaults as top-level keys / directories and can enumerate\n * them in O(1) calls. DynamoDB stores everything in a single table\n * keyed by `(compartment#collection, id)` — enumerating compartments\n * requires either a Scan (expensive, eventually consistent, leaks\n * ciphertext metadata) or a dedicated GSI that the consumer\n * provisioned. S3 needs a prefix list (cheap if enabled, ACL-sensitive\n * otherwise). Browser localStorage can scan keys by prefix.\n *\n * Stores that cannot implement `listVaults` cheaply or\n * cleanly should omit it. Core surfaces a `StoreCapabilityError`\n * with a clear message when a caller invokes\n * `listAccessibleVaults()` against a store that doesn't\n * provide this method, so consumers know to either upgrade their\n * store, provide a candidate list explicitly to `queryAcross()`,\n * or fall back to maintaining the compartment index out of band.\n *\n * **Privacy note:** `listVaults` returns *every* compartment\n * the store has, not just the ones the caller can access. The\n * existence-leak filtering (returning only compartments whose\n * keyring the caller can unwrap) happens in core, not in the\n * store. The store is trusted to know its own contents — that\n * is not a leak in the threat model. The leak the API guards\n * against is the *return value* of `listAccessibleVaults()`\n * exposing existence to a downstream observer who only sees that\n * function's output.\n *\n * The 6-method core contract is unchanged — this is an additive\n * extension discovered via `'listVaults' in store`.\n */\n listVaults?(): Promise<string[]>\n\n /**\n * Optional: generate a presigned URL for direct client download.\n * Only meaningful for object stores (S3, GCS) that support URL signing.\n * Returns a time-limited URL that fetches the encrypted envelope directly.\n * The caller must decrypt client-side (the URL returns ciphertext).\n */\n presignUrl?(vault: string, collection: string, id: string, expiresInSeconds?: number): Promise<string>\n\n /**\n * Optional: estimate current storage usage.\n * Returns `{ usedBytes, quotaBytes }` or null if the store cannot estimate.\n * Used by quota-aware routing to detect overflow conditions.\n */\n estimateUsage?(): Promise<{ usedBytes: number; quotaBytes: number } | null>\n\n /**\n * Optional multi-record atomic write.\n *\n * When present, `db.transaction(async (tx) => { ... })` uses this to\n * commit every staged op in one storage-layer transaction — either\n * all ops land or none do, regardless of which records they touch.\n * Every `TxOp.expectedVersion` (when set) must be honored atomically\n * alongside the write; any violation throws `ConflictError` and the\n * whole batch fails.\n *\n * Stores that omit this fall through to the hub's per-record OCC\n * fallback: pre-flight CAS check, then sequential `put`/`delete`\n * with best-effort unwind on mid-batch failure (see\n * `runTransaction` for the exact semantics and crash window).\n *\n * Native implementations: `to-memory` (single Map mutation),\n * `to-dynamo` (`TransactWriteItems`), `to-browser-idb` (one\n * `readwrite` transaction). File / S3 cannot implement this\n * atomically and should omit the method.\n */\n tx?(ops: readonly TxOp[]): Promise<void>\n}\n\n/**\n * A single staged operation inside a `db.transaction(fn)` commit. The\n * hub assembles `TxOp[]` from the user's `tx.collection().put/delete`\n * calls, encrypts any `record` values into `envelope`, and hands the\n * array to `NoydbStore.tx()` when the store supports atomic batch\n * writes. Stores that implement `tx()` MUST honor every\n * `expectedVersion` atomically against the stored envelope version.\n */\nexport interface TxOp {\n readonly type: 'put' | 'delete'\n readonly vault: string\n readonly collection: string\n readonly id: string\n /** Populated for `type: 'put'` — the encrypted envelope to write. */\n readonly envelope?: EncryptedEnvelope\n /** Optional per-record CAS. Mismatch must throw `ConflictError`. */\n readonly expectedVersion?: number\n}\n\n// ─── Store Factory Helper ──────────────────────────────────────────────\n\n/** Type-safe helper for creating store factories. */\nexport function createStore<TOptions>(\n factory: (options: TOptions) => NoydbStore,\n): (options: TOptions) => NoydbStore {\n return factory\n}\n\n// ─── Keyring ───────────────────────────────────────────────────────────\n\n/**\n * Interchange formats `@noy-db/as-*` packages can produce. `'*'` is a\n * wildcard granting every current + future plaintext format.\n */\nexport type ExportFormat =\n | 'xlsx'\n | 'csv'\n | 'json'\n | 'ndjson'\n | 'xml'\n | 'sql'\n | 'pdf'\n | 'blob'\n | 'zip'\n | '*'\n\n/**\n * Owner-granted export capability on a keyring.\n *\n * Two independent dimensions:\n *\n * - `plaintext` — per-format allowlist for record formatters + blob\n * extractors that emit plaintext bytes (`as-xlsx`, `as-csv`,\n * `as-blob`, `as-zip`, …). **Defaults to empty** for every role;\n * the owner/admin must positively grant per-format (or `'*'`).\n * - `bundle` — boolean for `.noydb` encrypted container export\n * (`as-noydb`). **Default policy: on for owner/admin, off for\n * operator/viewer/client** — applied when the field is absent or\n * undefined (see `hasExportCapability`).\n */\nexport interface ExportCapability {\n readonly plaintext?: readonly ExportFormat[]\n readonly bundle?: boolean\n}\n\n/**\n * Owner-granted import capability on a keyring (sibling of\n * `ExportCapability`, issue ).\n *\n * Two independent dimensions:\n *\n * - `plaintext` — per-format allowlist for `as-*` readers that ingest\n * plaintext bytes (`as-csv`, `as-json`, `as-ndjson`, `as-zip`, …).\n * Defaults to empty for every role; the owner/admin must positively\n * grant per-format (or `'*'`).\n * - `bundle` — boolean gate for `.noydb` bundle import. **Defaults to\n * `false` for every role**, including owner/admin. Import is more\n * dangerous than export (corrupts vs leaks), so the policy is\n * default-closed across the board — the owner explicitly opts a\n * keyring in via `db.grant({ importCapability: { bundle: true } })`.\n */\nexport interface ImportCapability {\n readonly plaintext?: readonly ExportFormat[]\n readonly bundle?: boolean\n}\n\n/**\n * Forward-declared on-disk shape for `VaultPolicy` — the actual policy\n * model is declared further down in this file (#9), see {@link VaultPolicy}.\n * Declared here as an `unknown`-typed map (rather than `VaultPolicy` itself)\n * so the `KeyringFile.policy` field can still round-trip foreign/older\n * documents that don't strictly satisfy the current shape.\n *\n * @internal\n */\nexport type VaultPolicyOnDisk = Record<string, unknown>\n\n/**\n * Recovery profile enrolled at vault creation.\n *\n * - `paper` — `on-recovery` codes (the standard end-to-end profile).\n * - `shamir` / `multi-channel` / `admin-mediated` — API surface ships;\n * per-profile dispatch lands in follow-up issues. Calling\n * `db.recoverPassphrase` against these throws\n * {@link RecoveryProfileNotImplementedError}.\n */\nexport type RecoveryEnrollment =\n | {\n readonly profile: 'paper'\n /** Number of single-use codes to print at enrollment. */\n readonly codes: number\n }\n | {\n readonly profile: 'shamir'\n readonly k: number\n readonly n: number\n readonly trustees: ReadonlyArray<string>\n }\n | {\n readonly profile: 'multi-channel'\n readonly email?: string\n readonly pin?: boolean\n readonly paperCodes?: number\n }\n | {\n readonly profile: 'admin-mediated'\n readonly grantorUserId: string\n }\n\n/**\n * One tier-2 authenticator slot inside a keyring file. Each slot\n * independently wraps the SAME KEK under a method-specific derived key\n * (LUKS pattern). Adding or removing a slot is a constant-time keyring\n * write — no DEK re-keying required.\n *\n * @see https://github.com/vLannaAi/noy-db-docs/blob/main/content/docs/services/session-tiers.md → Tier 2 — Authenticate (multi-slot)\n */\n/**\n * Shared fields across all authenticator slot variants. The variant\n * (`KeyringAuthenticatorWrappingKEK` vs `KeyringAuthenticatorWrappingDEKs`)\n * carries the actual wrapped material; everything below is identity +\n * metadata only.\n */\ninterface KeyringAuthenticatorBase {\n /** Caller-chosen identifier — e.g. `'webauthn-yubikey-blue'`, `'oidc-google'`, `'password'`. */\n readonly id: string\n /** Method family — selects which `@noy-db/on-*` package handles unlock. */\n readonly method: 'webauthn' | 'oidc' | 'password'\n /** ISO-8601 timestamp at which the slot was added. */\n readonly enrolled_at: string\n /**\n * Which session tier ENROLLED this slot. Tier 1 enrolls a fresh slot;\n * tier 2 may add a sibling slot when the active policy permits.\n */\n readonly enrolled_via_tier: 1 | 2\n /**\n * Method-specific metadata: WebAuthn cred id, OIDC issuer/sub, PBKDF2\n * salt for `on-password`, etc. The schema is open by design — the\n * `@noy-db/on-*` package owns the contents.\n */\n readonly meta: Record<string, unknown>\n}\n\n/**\n * Slot that wraps the KEK directly under a method-derived AES-KW key.\n * Used by ceremonies where the on-* package can produce/recover an\n * extractable KEK from its own credential — WebAuthn (PRF-derived\n * wrapping key) and split-key OIDC.\n *\n * `wrapKind` is optional/absent on older slots — those\n * legacy slots are treated as wrap-KEK by default at unlock time.\n */\nexport interface KeyringAuthenticatorWrappingKEK extends KeyringAuthenticatorBase {\n readonly wrapKind?: 'kek'\n /** Base64 wrapped-KEK ciphertext under the method-derived key. */\n readonly wrapped_kek: string\n /** XOR guard — wrap-KEK slots must NOT carry wrap-DEKs material. */\n readonly wrapped_deks?: never\n /** XOR guard — wrap-KEK slots must NOT carry wrap-DEKs material. */\n readonly iv?: never\n}\n\n/**\n * Slot that wraps the DEK set (not the KEK) under a method-derived\n * AES-GCM key — sidesteps the non-extractable-KEK constraint by\n * encrypting the serialized `{ deks: { collection: rawDekBase64 } }`\n * directly. Mirrors the format used by `mintPaperRecoveryEntry`\n * (`PaperRecoveryEntry`) and `@noy-db/on-pin`'s `PinResumeState` —\n * the unified wrap-DEKs primitive across tier-0 / tier-2 / tier-3.\n *\n * Trade-off: a slot of this kind reconstructs `UnlockedKeyring` with\n * `kek: null` after unlock. That is semantically correct for tier-2\n * (sensitive ops like `enrollAuthenticator` / `rotatePassphrase`\n * require a tier-1 unlock anyway) and matches how `@noy-db/on-pin`\n * already behaves at tier 3.\n *\n * @see `mintPaperRecoveryEntry` in `team/recovery.ts` — same shape on\n * a different on-disk path (`_meta/recovery-paper`).\n */\nexport interface KeyringAuthenticatorWrappingDEKs extends KeyringAuthenticatorBase {\n readonly wrapKind: 'deks'\n /** Base64 AES-GCM ciphertext of `{ deks: { collection: base64rawDek } }`. */\n readonly wrapped_deks: string\n /** Base64 AES-GCM IV used for the `wrapped_deks` ciphertext. */\n readonly iv: string\n /** XOR guard — wrap-DEKs slots must NOT carry wrap-KEK material. */\n readonly wrapped_kek?: never\n}\n\n/**\n * Discriminated union over the two wrap-format variants. Reads from\n * disk should always go through this type so the variant is preserved.\n *\n * Discriminator: `wrapKind`. Absent → wrap-KEK (legacy / WebAuthn /\n * OIDC). Present and `'deks'` → wrap-DEKs (password / future on-* that\n * want to sidestep extractable-KEK).\n *\n * The type-level XOR enforces \"exactly one of `wrapped_kek` /\n * `wrapped_deks` is present\" — a structural guarantee that the runtime\n * dispatch is safe.\n */\nexport type KeyringAuthenticator =\n | KeyringAuthenticatorWrappingKEK\n | KeyringAuthenticatorWrappingDEKs\n\nexport interface KeyringFile {\n readonly _noydb_keyring: typeof NOYDB_KEYRING_VERSION\n readonly user_id: string\n readonly display_name: string\n readonly role: Role\n readonly permissions: Permissions\n readonly deks: Record<string, string>\n readonly salt: string\n readonly created_at: string\n readonly granted_by: string\n /**\n * Passphrase canary — base64 AES-KW-wrapped form of a known constant\n * 256-bit value, wrapped under the keyring's KEK.\n *\n * Optional: older keyrings load with no canary and fall back to\n * the multi-DEK corruption heuristic. Newer keyrings\n * carry one and let `loadKeyring` distinguish wrong-passphrase\n * from corruption even when ALL DEKs (including a single-DEK keyring's\n * sole DEK) are corrupted.\n *\n * AES-KW is deterministic — every write site mints fresh on each\n * persist; same KEK + same constant input always produces the same\n * ciphertext, so this round-trips without state.\n */\n readonly canary?: string\n /**\n * Tier-2 authenticator slots (multi-slot keyring extension).\n * Optional / append-only: keyring files written before the\n * extension load with an empty list. Each slot independently wraps\n * the same KEK; any one of them unlocks.\n *\n * @see KeyringAuthenticator\n */\n readonly authenticators?: readonly KeyringAuthenticator[]\n /**\n * Per-keyring policy override (reserved). The on-disk format\n * accepts the field for forward compatibility with the Option C\n * merge engine deferred to a later release; v1.0 reads only the\n * vault-level `_meta/policy` document, so this field is parsed and\n * round-tripped but never enforced.\n */\n readonly policy?: VaultPolicyOnDisk\n /**\n * Optional — authorization spec capability bits. Absent on keyrings written\n * before the RFC implementation. Loading falls back to role-based\n * defaults (owner/admin get bundle-on, everyone else off).\n */\n readonly export_capability?: ExportCapability\n /**\n * Optional bundle-slot expiry. ISO-8601 timestamp; past\n * the cutoff `loadKeyring` throws `KeyringExpiredError` before any\n * DEK unwrap is attempted. Useful for time-boxed audit access:\n * \"this slot works for 30 days then becomes opaque to its holder.\"\n *\n * Absent on live keyrings written via `db.grant()` — the field is\n * meaningful for `BundleRecipient` slots produced by\n * `writePod({ recipients: [...] })`. Setting it on a live\n * keyring is allowed but unusual.\n */\n readonly expires_at?: string\n /**\n * Optional — issue import-capability bits. Absent on keyrings\n * written before landed. Loading falls back to default-closed\n * for every role and every format.\n */\n readonly import_capability?: ImportCapability\n /**\n * hierarchical access clearance. Absent → 0 (advisory;\n * the real check is whether the DEK map carries a `collection#tier`\n * entry for the requested tier). Owners and admins default to the\n * highest tier they have DEKs for at grant time.\n */\n readonly clearance?: number\n}\n\n// ─── Backup ────────────────────────────────────────────────────────────\n\nexport interface VaultBackup {\n readonly _noydb_backup: typeof NOYDB_BACKUP_VERSION\n readonly _compartment: string\n readonly _exported_at: string\n readonly _exported_by: string\n readonly keyrings: Record<string, KeyringFile>\n readonly collections: VaultSnapshot\n /**\n * Internal collections (`_ledger`, `_ledger_deltas`, `_history`, `_sync`, …)\n * captured alongside the data collections. Optional for backwards\n * compat with backups, which only stored data collections —\n * loading a backup leaves the ledger empty (and `verifyBackupIntegrity`\n * skips the chain check, surfacing only a console warning).\n */\n readonly _internal?: VaultSnapshot\n /**\n * Verifiable-backup metadata. Embeds the ledger head at\n * dump time so `load()` can cross-check that the loaded chain matches\n * exactly what was exported. A backup whose chain has been tampered\n * with — either by modifying ledger entries or by modifying data\n * envelopes that the chain references — fails this check.\n *\n * Optional for backwards compat with backups; missing means\n * \"legacy backup, load with a warning, no integrity check\".\n */\n readonly ledgerHead?: {\n /** Hex sha256 of the canonical JSON of the last ledger entry. */\n readonly hash: string\n /** Sequential index of the last ledger entry. */\n readonly index: number\n /** ISO timestamp captured at dump time. */\n readonly ts: string\n }\n}\n\n// ─── Export ────────────────────────────────────────────────────────────\n\n/**\n * Options for `Vault.exportStream()` and `Vault.exportJSON()`.\n *\n * The defaults match the most common consumer pattern: one chunk per\n * collection, no ledger metadata. Per-record streaming and ledger-head\n * inclusion are opt-in because both add structure most consumers don't\n * need.\n */\nexport interface ExportStreamOptions {\n /**\n * `'collection'` (default) yields one chunk per collection with all\n * records bundled in `chunk.records`. `'record'` yields one chunk per\n * record, useful for arbitrarily large collections that should never\n * be materialized as a single array.\n */\n readonly granularity?: 'collection' | 'record'\n\n /**\n * When `true`, every chunk includes the current compartment ledger\n * head under `chunk.ledgerHead`. The value is identical across every\n * chunk in a single export (one ledger per compartment). Forward-\n * compatible with future partition work where the head would become\n * per-partition. Default: `false`.\n */\n readonly withLedgerHead?: boolean\n /**\n * Export locale (BCP 47, e.g. `'th'`). When set, records are read at this\n * locale through the **`export` layer**: `i18nText` fields collapse to\n * the locale string (honoring each field's `export`-layer `onMissing` policy)\n * and `dictKey`/`staticDict` `<field>Label`s are resolved — a single-locale\n * export. The raw `dictionaries` snapshot is then redundant and omitted. This\n * applies to BOTH `exportStream()` and `exportJSON()`.\n *\n * Default: `undefined` — raw `{locale}` maps + the `_dictionaries` snapshot\n * (a full, all-locale backup; format packages apply their own locale strategy).\n */\n readonly resolveLabels?: string\n}\n\n/**\n * One chunk yielded by `Vault.exportStream()`.\n *\n * `granularity: 'collection'` yields one chunk per collection with the\n * full record array in `records`. `granularity: 'record'` yields one\n * chunk per record with `records` containing exactly one element — the\n * `schema` and `refs` metadata is repeated on every chunk so consumers\n * doing per-record streaming don't have to thread state across yields.\n */\nexport interface ExportChunk<T = unknown> {\n /** Collection name (no leading underscore — internal collections are filtered out). */\n readonly collection: string\n\n /**\n * Standard Schema validator attached to the collection at `collection()`\n * construction time, or `null` if no schema was provided. Surfaced so\n * downstream serializers (`@noy-db/as-*` packages, custom\n * exporters) can produce schema-aware output (typed CSV headers, XSD\n * generation, etc.) without poking at collection internals.\n */\n readonly schema: StandardSchemaV1<unknown, T> | null\n\n /**\n * Foreign-key references declared on the collection via the `refs`\n * option, as the `{ field → { target, mode } }` map produced by\n * `RefRegistry.getOutbound`. Empty object when no refs were declared.\n */\n readonly refs: Record<string, { readonly target: string; readonly mode: 'strict' | 'warn' | 'cascade' }>\n\n /**\n * Decrypted, ACL-scoped, schema-validated records. Length 1 in\n * `granularity: 'record'` mode, full collection in `granularity: 'collection'`\n * mode. Records are returned by reference from the collection's eager\n * cache where applicable — consumers must treat them as immutable.\n */\n readonly records: T[]\n\n /**\n * Dictionary snapshots for every `dictKey` field declared on this\n * collection. Captured once at stream-start and held\n * constant across all chunks within the same export — a rename\n * mid-export does not change the snapshot. `undefined` when the\n * collection has no `dictKeyFields`.\n *\n * Shape: `{ [fieldName]: { [stableKey]: { [locale]: label } } }`\n *\n * @example\n * ```ts\n * chunk.dictionaries?.status?.paid?.th // → 'ชำระแล้ว'\n * ```\n */\n readonly dictionaries?: Record<\n string, // field name\n Record<string, Record<string, string>> // stable key → locale → label\n >\n\n /**\n * Vault ledger head at export time. Present only when\n * `exportStream({ withLedgerHead: true })` was called. Identical\n * across every chunk in the same export — included on every chunk\n * for forward-compatibility with future per-partition ledgers, where\n * the value will differ per chunk.\n */\n readonly ledgerHead?: {\n readonly hash: string\n readonly index: number\n readonly ts: string\n }\n}\n\n// ─── Sync ──────────────────────────────────────────────────────────────\n\nexport interface DirtyEntry {\n readonly vault: string\n readonly collection: string\n readonly id: string\n readonly action: 'put' | 'delete'\n readonly version: number\n readonly timestamp: string\n}\n\nexport interface SyncMetadata {\n readonly _noydb_sync: typeof NOYDB_SYNC_VERSION\n readonly last_push: string | null\n readonly last_pull: string | null\n readonly dirty: DirtyEntry[]\n}\n\nexport interface Conflict {\n readonly vault: string\n readonly collection: string\n readonly id: string\n readonly local: EncryptedEnvelope\n readonly remote: EncryptedEnvelope\n readonly localVersion: number\n readonly remoteVersion: number\n /**\n * Present only when the collection uses `conflictPolicy: 'manual'`.\n * Call `resolve(winner)` to commit the winning envelope, or\n * `resolve(null)` to defer (conflict stays queued for the next sync).\n * Called synchronously inside the `sync:conflict` event handler.\n */\n readonly resolve?: (winner: EncryptedEnvelope | null) => void\n}\n\n/**\n * A same-device cross-tab write conflict: another tab overwrote a\n * document this tab had written, having diverged from an older base. Records\n * are decrypted (cross-tab handlers reconcile in plaintext). `base` is the\n * common ancestor from history, or null when history is unavailable.\n */\nexport interface WriteConflict {\n readonly vault: string\n readonly collection: string\n readonly docId: string\n readonly local: unknown\n readonly remote: unknown\n readonly base: unknown\n readonly localVersion: number\n readonly remoteVersion: number\n readonly baseVersion: number\n}\n\nexport type ConflictStrategy =\n | 'local-wins'\n | 'remote-wins'\n | 'version'\n | ((conflict: Conflict) => 'local' | 'remote')\n\n/**\n * Collection-level conflict policy.\n * Overrides the db-level `conflict` option for the specific collection.\n *\n * - `'last-writer-wins'` — higher `_ts` wins (timestamp LWW).\n * - `'first-writer-wins'` — lower `_v` wins (earlier version is preserved).\n * - `'manual'` — emits `sync:conflict` with a `resolve` callback. Call\n * `resolve(winner)` synchronously to commit or `resolve(null)` to defer.\n * - Custom fn — synchronous `(local: T, remote: T) => T`. Must be pure.\n */\nexport type ConflictPolicy<T> =\n | 'last-writer-wins'\n | 'first-writer-wins'\n | 'manual'\n | ((local: T, remote: T) => T)\n\n/**\n * Envelope-level resolver registered per collection with the SyncEngine.\n * Receives the `id` of the conflicting record and both envelopes.\n * Returns the winning envelope, or `null` to defer resolution.\n * @internal\n */\nexport type CollectionConflictResolver = (\n id: string,\n local: EncryptedEnvelope,\n remote: EncryptedEnvelope,\n) => Promise<EncryptedEnvelope | null>\n\n/** Options for targeted push operations. */\nexport interface PushOptions {\n /** Only push records belonging to these collections. Omit to push all dirty. */\n collections?: string[]\n}\n\n/** Options for targeted pull operations. */\nexport interface PullOptions {\n /** Only pull these collections. Omit to pull all. */\n collections?: string[]\n /**\n * Only pull records with `_ts` strictly after this ISO timestamp.\n * Stores that implement `listSince` use it directly; others fall back\n * to a full scan with client-side filtering.\n */\n modifiedSince?: string\n}\n\nexport interface PushResult {\n readonly pushed: number\n readonly conflicts: Conflict[]\n readonly errors: Error[]\n}\n\nexport interface PullResult {\n readonly pulled: number\n readonly conflicts: Conflict[]\n readonly errors: Error[]\n}\n\n/** Result of a sync transaction commit. */\nexport interface SyncTransactionResult {\n readonly status: 'committed' | 'conflict'\n readonly pushed: number\n readonly conflicts: Conflict[]\n}\n\nexport interface SyncStatus {\n readonly dirty: number\n readonly lastPush: string | null\n readonly lastPull: string | null\n readonly online: boolean\n}\n\n// ─── Sync Target ─────────────────────────────────────────\n\nexport type SyncTargetRole = 'sync-peer' | 'backup' | 'archive'\n\n/**\n * A sync target with role and optional per-target policy.\n *\n * | Role | Direction | Conflict resolution | Typical use |\n * |-------------|---------------|---------------------|--------------------------|\n * | `sync-peer` | Bidirectional | ConflictStrategy | DynamoDB live sync |\n * | `backup` | Push-only | N/A (receives merged)| S3 dump, Google Drive |\n * | `archive` | Push-only | N/A | IPFS, Git tags, S3 Lock |\n */\nexport interface SyncTarget {\n /** The store to sync with. */\n readonly store: NoydbStore\n /** Role determines sync direction and conflict handling. */\n readonly role: SyncTargetRole\n /** Per-target sync policy. Inherits store-category default when absent. */\n readonly policy?: SyncPolicy\n /** Human-readable label for DevTools and audit logs. */\n readonly label?: string\n}\n\n// ─── Events ────────────────────────────────────────────────────────────\n\nexport interface ChangeEvent {\n readonly vault: string\n readonly collection: string\n readonly id: string\n readonly action: 'put' | 'delete'\n}\n\nexport interface NoydbEventMap {\n 'change': ChangeEvent\n 'error': Error\n /**\n * Same-instance signal that this vault's schema-fence state changed.\n * For UI integration. Cross-client coordination goes\n * through the store, not this event.\n */\n 'schema:fence-changed': { vault: string; currentSchemaVersion: number; fenceState: 'normal' | 'draining' | 'migrating' | 'complete' }\n 'sync:push': PushResult\n 'sync:pull': PullResult\n 'sync:conflict': Conflict\n 'write:conflict': WriteConflict\n 'sync:online': void\n 'sync:offline': void\n 'sync:backup-error': { vault: string; target: string; error: Error }\n 'history:save': { vault: string; collection: string; id: string; version: number }\n 'history:prune': { vault: string; collection: string; id: string; pruned: number }\n /**\n * A non-fatal i18n script violation under `onScriptViolation: 'warn' | 'filter'`.\n * 'warn' stored the value as-is; 'filter' stripped disallowed characters\n * (the event is the only signal the stored data was mutated). 'reject'\n * throws `ScriptViolationError` and emits nothing.\n */\n 'i18n:script-violation': {\n vault: string\n collection: string\n id: string\n mode: 'warn' | 'filter'\n warning: ScriptWarning\n }\n /**\n * Emitted when a persisted-index side-car put/delete fails after the\n * main record write already succeeded. The main record is durable; the\n * index mirror may have drifted. Operators reconcile via\n * `collection.reconcileIndex(field)`.\n */\n 'index:write-partial': {\n vault: string\n collection: string\n id: string\n action: 'put' | 'delete'\n error: Error\n }\n /**\n * emitted by `Collection.ensurePersistedIndexesLoaded()`\n * once per field on first lazy-mode query when\n * `reconcileOnOpen: 'auto' | 'dry-run'` is configured. `applied` is\n * `0` in `'dry-run'` mode. `skipped` is reserved for a future\n * drift-stamp optimization that short-circuits the reconcile when\n * the mirror version matches what's on disk — currently always\n * `false` (the full reconcile runs every session).\n */\n 'index:reconciled': {\n vault: string\n collection: string\n field: string\n missing: readonly string[]\n stale: readonly string[]\n applied: number\n skipped: boolean\n }\n}\n\n// ─── Grant / Revoke ────────────────────────────────────────────────────\n\nexport interface GrantOptions {\n readonly userId: string\n readonly displayName: string\n readonly role: Role\n readonly passphrase: string\n readonly permissions?: Permissions\n /**\n * Optional `@noy-db/as-*` export capability. Omit or\n * leave undefined to apply role-based defaults (see\n * `hasExportCapability` and `ExportCapability`).\n */\n readonly exportCapability?: ExportCapability\n /**\n * Optional `@noy-db/as-*` import capability (issue ). Omit or\n * leave undefined for default-closed semantics — no plaintext format\n * is grantable until positively listed; bundle import is denied.\n */\n readonly importCapability?: ImportCapability\n /**\n * Skip phrase-format strength validation (issue #7). Defaults to\n * false — `grant()` rejects phrases that don't meet the configured\n * `PassphrasePolicy`. Test fixtures and CLI scripts pass `true`.\n */\n readonly allowWeakPassphrase?: boolean\n /**\n * Initial user-envelope payload for the new principal. Sealed under\n * the same vault DEK (the reserved `_users` collection's DEK) and\n * persisted alongside the keyring during grant.\n *\n * **Bootstrap-only.** Once the new user activates and writes their\n * own envelope, the own-only write rule kicks in — admins cannot\n * edit a teammate's envelope after activation. Use this field for\n * pre-fill at invite time (e.g. \"displayName: Bob, locale: en-US\")\n * and let the user take over from there.\n *\n * Hub does not introspect the payload; it is JSON-serialized and\n * encrypted opaquely. Apps own the schema.\n *\n * @see docs/superpowers/specs/2026-05-05-user-envelope-design.md → Lifecycle\n */\n readonly initialProfile?: unknown\n}\n\n/**\n * Caller payload for `db.updateUser`. Mutate one or more\n * identity fields on an existing keyring without rotating any keys.\n *\n * `role`, `displayName`, and `permissions` live in the plaintext header\n * of `_keyring/<userId>` (the sync engine reads them without keys).\n * Mutating them is a JSON header swap — no DEK rewrap, no KEK\n * required, no authenticator slots touched. Tier-2 slots and recovery\n * enrollments survive unchanged. Last-write-wins through the existing\n * keyring put (same concurrency story as `db.grant` / `db.revoke`).\n *\n * Top-level fields are partial-merge: absent fields are not modified.\n * `null` on `displayName` clears the field (stored as the empty string;\n * UI consumers typically render the empty case by falling back to the\n * user id). `undefined` / absent leaves the field untouched. Mirrors\n * the `null`-as-clear convention `UserApi.updateMe` uses.\n *\n * `permissions`, however, is a **full replacement** at the map level —\n * passing `{ invoices: 'rw' }` REPLACES the entire permissions map,\n * silently dropping any other entries. To partially update, read the\n * current keyring and merge: `permissions: { ...current, invoices: 'rw' }`.\n * To clear all permissions, pass `permissions: {}` explicitly.\n *\n * Role-elevation guard: the same hierarchy as `db.grant`. Admins can\n * change `admin` / `operator` / `viewer` / `client` to and from each\n * other; admins cannot promote to or demote from `owner`. Owners can\n * do anything. Non-admin callers (operator/viewer/client) cannot call\n * `db.updateUser` at all — for self-displayName changes, use\n * `vault.user.updateMe` (the user-envelope API).\n */\nexport interface UpdateUserOptions {\n readonly userId: string\n readonly role?: Role\n readonly displayName?: string | null\n readonly permissions?: Permissions\n}\n\nexport interface RevokeOptions {\n readonly userId: string\n readonly rotateKeys?: boolean\n\n /**\n * Cascade behavior when the revoked user is an admin who has granted\n * other admins.\n *\n * - `'strict'` (default) — recursively revoke every admin that the\n * target (transitively) granted. The cascade walks the\n * `granted_by` field on each keyring file and stops at non-admin\n * leaves. All affected collections are accumulated and rotated in\n * a single pass at the end, so cascade cost is O(records in\n * affected collections), not O(records × cascade depth).\n *\n * - `'warn'` — leave the descendant admins in place but emit a\n * `console.warn` listing them. Useful for diagnostic dry runs and\n * for environments where the operator wants to clean up the\n * delegation tree manually.\n *\n * No effect when the target is not an admin (operators, viewers, and\n * clients cannot grant other users, so they have no delegation\n * subtree to cascade through). Defaults to `'strict'`.\n */\n readonly cascade?: 'strict' | 'warn'\n}\n\n// ─── Cross-vault queries ──────────────────────────────\n\n/**\n * One entry returned by `Noydb.listAccessibleVaults()`. Carries\n * the compartment id and the role the calling principal holds in it,\n * so the consumer can decide how to fan out without re-checking\n * permissions per vault.\n */\nexport interface AccessibleVault {\n readonly id: string\n readonly role: Role\n}\n\n/**\n * Options for `Noydb.listAccessibleVaults()`.\n */\nexport interface ListAccessibleVaultsOptions {\n /**\n * Minimum role the caller must hold to include a vault in the\n * result. Vaults where the caller's role is strictly *below*\n * this threshold are silently excluded. Defaults to `'client'`,\n * which means \"every vault I can unwrap is returned.\" Set to\n * `'admin'` for \"vaults where I can grant/revoke,\" or\n * `'owner'` for \"vaults I own.\"\n *\n * The privilege ordering used:\n * `client (1) < viewer (2) < operator (3) < admin (4) < owner (5)`\n *\n * Note: `viewer` and `client` are conceptually peers in the ACL\n * (neither can grant), but `viewer` has read-all access while\n * `client` has only explicit-collection read. The numeric order\n * reflects \"how much can this principal see,\" not \"how much can\n * this principal modify.\"\n */\n readonly minRole?: Role\n}\n\n/**\n * Options for `Noydb.queryAcross()`.\n */\nexport interface QueryAcrossOptions {\n /**\n * Maximum number of compartments to process in parallel. Defaults\n * to `1` (sequential) — conservative because the per-compartment\n * callback typically does its own I/O and an unbounded fan-out can\n * exhaust adapter connections (DynamoDB throughput, S3 socket\n * limits, browser fetch concurrency).\n *\n * Set to `4` or `8` for cloud-backed compartments where parallelism\n * is the whole point of fanning out. Set to `1` (default) for local\n * adapters where the disk I/O serializes anyway.\n */\n readonly concurrency?: number\n /**\n * Open shards non-creatingly — a missing grant throws instead of\n * self-provisioning. Default: `true` (create iff the vault has no\n * `_keyring/*`). Pass `false` for strict open-existing semantics\n * (e.g. federation read fan-out where shards are pre-provisioned\n * and an absent grant should fail closed).\n */\n readonly create?: boolean\n}\n\n/**\n * One entry in the array returned by `Noydb.queryAcross()`. Either\n * `result` is set (callback succeeded for this compartment) or\n * `error` is set (callback threw, or compartment failed to open).\n *\n * Per-compartment errors do **not** abort the overall fan-out — every\n * compartment is given a chance to run its callback, and the\n * partition between success and failure is exposed in the return\n * value. Consumers that want fail-fast semantics can check\n * `r.error !== undefined` and short-circuit themselves.\n */\nexport type QueryAcrossResult<T> =\n | { readonly vault: string; readonly result: T; readonly error?: undefined }\n | { readonly vault: string; readonly result?: undefined; readonly error: Error }\n\n// ─── User Info ─────────────────────────────────────────────────────────\n\nexport interface UserInfo {\n readonly userId: string\n readonly displayName: string\n readonly role: Role\n readonly permissions: Permissions\n readonly createdAt: string\n readonly grantedBy: string\n}\n\n// ─── Session ───────────────────────────────────────────────\n\n/**\n * Operations that a session policy can require re-authentication for.\n * Passed as the `requireReAuthFor` array in `SessionPolicy`.\n */\nexport type ReAuthOperation = 'export' | 'grant' | 'revoke' | 'rotate' | 'changeSecret'\n\n/**\n * Session policy controlling lifetime, re-auth requirements, and\n * background-lock behavior.\n *\n * All timeout values are in milliseconds. `undefined` means \"no limit.\"\n * The policy is evaluated lazily — it does not start timers itself;\n * enforcement happens at the Noydb call site.\n */\nexport interface SessionPolicy {\n /**\n * Idle timeout in ms. If no NOYDB operation is performed for this\n * duration, the session is revoked on the next operation attempt\n * (which will throw `SessionExpiredError`). The idle clock resets\n * on every successful operation.\n *\n * Default: `undefined` (no idle timeout).\n */\n readonly idleTimeoutMs?: number\n\n /**\n * Absolute timeout in ms from session creation. After this duration\n * the session is unconditionally revoked regardless of activity.\n *\n * Default: `undefined` (no absolute timeout).\n */\n readonly absoluteTimeoutMs?: number\n\n /**\n * Operations that require the user to re-authenticate (re-enter their\n * passphrase or perform a fresh WebAuthn assertion) before proceeding,\n * even if the session is still alive.\n *\n * Common pattern: `requireReAuthFor: ['export', 'grant']` — allow\n * read/write operations in the background but demand a fresh credential\n * for high-risk mutations.\n *\n * Default: `[]` (no extra re-auth requirements).\n */\n readonly requireReAuthFor?: readonly ReAuthOperation[]\n\n /**\n * If `true`, the session is revoked when the page goes to the background\n * (visibilitychange event, `document.hidden === true`). Useful for\n * high-sensitivity deployments where leaving the tab is treated as\n * a session boundary.\n *\n * No-op in non-browser environments (Node.js, workers without document).\n * Default: `false`.\n */\n readonly lockOnBackground?: boolean\n}\n\n// ─── i18n / Locale ─────────────────────────────────────\n\n/**\n * Locale-aware read options. Pass to `Collection.get()`, `list()`,\n * `query()`, and `scan()` to trigger per-record locale resolution for\n * `dictKey` and `i18nText` fields.\n *\n * - **`locale: 'raw'`** — skip resolution for `i18nText` fields and\n * return the full `{ [locale]: string }` map. Dict key fields still\n * return the stable key (no `<field>Label` added).\n * - **`fallback`** — single locale code or ordered list. Use `'any'` as\n * the last element to fall back to any present translation.\n *\n * When neither the call-level locale nor the compartment's default locale\n * is set, reading a record with `i18nText` fields throws\n * `LocaleNotSpecifiedError`.\n */\nexport interface LocaleReadOptions {\n /**\n * The target locale code (e.g. `'th'`), or `'raw'` to return the full\n * language map without resolution.\n */\n readonly locale?: string\n /**\n * Fallback locale or ordered fallback chain. Use `'any'` as the last\n * element to fall back to any present translation.\n */\n readonly fallback?: string | readonly string[]\n /**\n * @internal — the resolution layer this read belongs to (`'read'` by\n * default). Threaded by layer-tagged read facades (guard / derivation)\n * so `applyI18nLocale` and dictKey `resolvePolicy` select that layer's\n * `onMissing` policy instead of the `'read'` policy. Not part of the\n * public read API — callers select policy via the field's `onMissing`\n * map, not by setting this.\n */\n readonly _layer?: Layer\n}\n\n// ─── plaintextTranslator hook ──────────────────────────────\n\n/**\n * Context passed to the consumer-supplied `plaintextTranslator` function.\n * The hook receives the source text plus enough metadata to route it to the\n * right translation service and record what it did.\n */\nexport interface PlaintextTranslatorContext {\n /** The plaintext string to translate. */\n readonly text: string\n /** BCP 47 source locale (the locale the text is written in). */\n readonly from: string\n /** BCP 47 target locale to translate into. */\n readonly to: string\n /** The schema field name that triggered the translation. */\n readonly field: string\n /** The collection the record is being put into. */\n readonly collection: string\n}\n\n/**\n * A consumer-supplied async function that translates a single string\n * from one locale to another. noy-db ships no built-in translator.\n *\n * **Security:** this function receives plaintext. The consumer is\n * responsible for the data policy of whatever service it calls. See\n * `NOYDB_SPEC.md § Zero-Knowledge Storage` and the `plaintextTranslator`\n * JSDoc on `NoydbOptions` for the full invariant statement.\n */\nexport type PlaintextTranslatorFn = (\n ctx: PlaintextTranslatorContext,\n) => Promise<string>\n\n/**\n * One entry in the in-process translator audit log. Cleared when\n * `db.close()` is called — same lifetime as the KEK and DEKs.\n *\n * Deliberately omits any content hash or translated-text fingerprint\n * to prevent correlation attacks on the audit trail.\n */\nexport interface TranslatorAuditEntry {\n readonly type: 'translator-invocation'\n /** Schema field name that was translated. */\n readonly field: string\n /** Collection the record belongs to. */\n readonly collection: string\n /** Source locale. */\n readonly fromLocale: string\n /** Target locale. */\n readonly toLocale: string\n /**\n * Consumer-provided translator name from\n * `NoydbOptions.plaintextTranslatorName`. Defaults to `'anonymous'`\n * when not supplied.\n */\n readonly translatorName: string\n /** ISO 8601 timestamp of the invocation. */\n readonly timestamp: string\n /**\n * `true` when the result was served from the in-process cache rather\n * than by calling the translator function. Present only on cache hits\n * so the absence of the field also communicates a cache miss.\n */\n readonly cached?: true\n}\n\n// ─── Presence ─────────────────────────────────────────────\n\n/**\n * A presence peer entry. `lastSeen` is an ISO timestamp set by core on each\n * `update()` call. Stale entries (lastSeen older than `staleMs`) are filtered\n * before delivering to the subscriber callback.\n */\nexport interface PresencePeer<P> {\n readonly userId: string\n readonly payload: P\n readonly lastSeen: string\n}\n\n// ─── CRDT ─────────────────────────────────────────────────\n\n/** Per-collection CRDT mode. */\nexport type CrdtMode = 'lww-map' | 'rga' | 'yjs'\n\nexport type CrdtState = LwwMapState | RgaState | YjsState\n\n// Re-exported from crdt.ts so consumers only need one import path.\nexport type { LwwMapState, RgaState, YjsState } from '../with-commit/crdt/crdt.js'\n\n/**\n * Seam interface. `@internal`.\n *\n * @internal\n */\nexport interface CrdtStrategy {\n buildLwwMapState(\n record: Record<string, unknown>,\n previous: LwwMapState | undefined,\n now: string,\n ): LwwMapState\n buildRgaState(\n items: readonly unknown[],\n previous: RgaState | undefined,\n idGen: () => string,\n ): RgaState\n mergeCrdtStates(local: CrdtState, remote: CrdtState): CrdtState\n resolveCrdtSnapshot(state: CrdtState): unknown\n}\n\n// ─── Blob / Attachment Store ────────────────────────\n\n/**\n * Second store shape for blob-store backends (Drive, WebDAV, Git, iCloud)\n * that operate on whole-vault bundles rather than per-record KV.\n *\n * Implement `readBundle` / `writeBundle` instead of the six-method KV\n * contract. Use `wrapBundleStore()` from `@noy-db/hub` to convert to a\n * `NoydbStore` that the rest of the API consumes transparently.\n *\n * Named `NoydbPodStore` (not `NoydbBundleAdapter`) for consistency\n * with the hub / to-* / in-* rename. Concrete implementations ship\n * in `@noy-db/to-*` packages starting in.\n */\nexport interface NoydbPodStore {\n /** Discriminant for engine auto-detection of store shape. */\n readonly kind: 'bundle'\n /** Human-readable name for diagnostics (e.g. `'drive'`, `'webdav'`). */\n readonly name?: string\n /**\n * Read the entire vault as raw bytes. Returns `null` if no bundle exists\n * yet (first open of a brand-new vault).\n */\n readBundle(vaultId: string): Promise<{ bytes: Uint8Array; version: string } | null>\n /**\n * Write the entire vault as raw bytes. `expectedVersion` is the version\n * token from the last `readBundle` (or `null` for a first write).\n * Implementations MUST reject the write if the stored version has advanced\n * past `expectedVersion` — throw `PodVersionConflictError`.\n * Returns the new version token on success.\n */\n writeBundle(\n vaultId: string,\n bytes: Uint8Array,\n expectedVersion: string | null,\n ): Promise<{ version: string }>\n /** Delete a vault bundle. Idempotent — no-op if the bundle does not exist. */\n deleteBundle(vaultId: string): Promise<void>\n /** List all vault bundles managed by this store. */\n listBundles(): Promise<Array<{ vaultId: string; version: string; size: number }>>\n}\n\n/** @deprecated Use `NoydbPodStore`. */\nexport type NoydbBundleStore = NoydbPodStore\n\n/**\n * Content-addressed blob object stored in the vault-level blob index.\n * Identified by HMAC-SHA-256(blobDEK, plaintext) — opaque to the store.\n *\n * Shared across all collections within a vault for deduplication: two\n * records that attach identical byte content reference the same `eTag`\n * and share a single set of encrypted chunks in `_blob_chunks`.\n */\nexport interface BlobObject {\n /** HMAC-SHA-256 hex of the original plaintext bytes, keyed by `_blob` DEK. */\n readonly eTag: string\n /** Original uncompressed size in bytes. */\n readonly size: number\n /** Compressed size in bytes (the payload that is actually encrypted and chunked). */\n readonly compressedSize: number\n /** Compression algorithm applied before encryption. */\n readonly compression: 'gzip' | 'none'\n /** Raw chunk size in bytes used at write time. Readers MUST use this value. */\n readonly chunkSize: number\n /** Total number of chunks written. Reader expects exactly this many. */\n readonly chunkCount: number\n /** MIME type if provided or auto-detected at upload time. */\n readonly mimeType?: string\n /** ISO timestamp of first upload. */\n readonly createdAt: string\n /** Live reference count — slots + published versions pointing to this blob. */\n readonly refCount: number\n /**\n * Base64 AES-KW-wrapped per-blob **content CEK** (wrapped under the `_blob`\n * DEK). Present on erasable-collection blobs (`perRecordKeys`): the chunks\n * are encrypted under this content CEK rather than directly under the `_blob`\n * DEK, so deleting this BlobObject at `refCount → 0` crypto-shreds the chunks\n * (they become permanently undecryptable). Absent → legacy blob, chunks\n * decrypt directly under the `_blob` DEK (read unchanged). See\n * docs/superpowers/specs/2026-06-13-per-blob-cek-design.md.\n */\n readonly _cek?: string\n /**\n * Transient migration marker. Present only while a legacy\n * blob is being migrated to a content CEK: it holds the wrapped content CEK\n * BEFORE the chunks have been re-encrypted under it. Readers **ignore**\n * `_cekPending` (they key off `_cek`), so the blob stays readable under the\n * `_blob` DEK during migration AND the content CEK survives a crash → a\n * re-run resumes and promotes `_cekPending` → `_cek`. Never set on a settled blob.\n */\n readonly _cekPending?: string\n /**\n * Hint indicating which store holds the chunk data.\n * Used by `routeStore` size-tiered routing: `'default'` for small blobs\n * stored inline (e.g. DynamoDB), `'blobs'` for large blobs in the overflow\n * store (e.g. S3). Absent when no routing is configured.\n */\n readonly storeHint?: 'default' | 'blobs'\n}\n\n/**\n * Slot record — mutable metadata linking a named slot on a record\n * to a `BlobObject` via its eTag.\n *\n * Multiple slots (even across different records) may reference the same\n * `eTag` — the underlying chunks are shared. Updating metadata creates\n * a new envelope version (`_v++`) while the blob data is unchanged.\n */\nexport interface SlotRecord {\n /**\n * Reference to the `BlobObject` in `_blob_index` (chunk-based blobs).\n * Empty string (`''`) for an `external` slot, whose bytes live in the\n * `ObjectProjection` rather than `_blob_chunks` — read `external` instead.\n */\n readonly eTag: string\n /**\n * External-projection reference. Present when the blob field is declared\n * `external`: the raw bytes live in the vault's `ObjectProjection` at `key`\n * (unencrypted), not in `_blob_chunks`. This slot record (in the encrypted\n * collection) remains the catalog entry — the anchoring invariant.\n */\n readonly external?: {\n readonly key: string\n readonly contentType?: string\n readonly public?: boolean\n /** Opaque-token backlink stamped on the object (when `backlink:'opaque-token'`). */\n readonly backlink?: string\n /**\n * Secondary metadata store synced from the object / its processing pipeline\n * (e.g. video `duration`, image `width`/`height`, arbitrary metatags).\n * Populated via `BlobSet.setExternalMeta()` — typically an AWS-side callback.\n */\n readonly meta?: Record<string, unknown>\n }\n /** User-visible filename for the slot. */\n readonly filename: string\n /** Original uncompressed size in bytes (denormalized from `BlobObject`). */\n readonly size: number\n /** MIME type. Takes precedence over the MIME type stored in `BlobObject`. */\n readonly mimeType?: string\n /** ISO timestamp of the upload that set this slot. */\n readonly uploadedAt: string\n /** User ID of the uploader, if available. */\n readonly uploadedBy?: string\n}\n\n/** Result of `BlobSet.list()` — slot record plus its named slot key. */\nexport interface SlotInfo extends SlotRecord {\n /** The slot name (key in the record's slot map). */\n readonly name: string\n}\n\n/**\n * Explicitly published version snapshot — an independent reference to a\n * blob at a specific point in time.\n */\nexport interface VersionRecord {\n /** User-defined label (e.g. `'issued-2025-01'`, `'amendment-2025-02'`). */\n readonly label: string\n /** eTag of the blob snapshot at publish time — independent of the current slot. */\n readonly eTag: string\n /** ISO timestamp when the version was published. */\n readonly publishedAt: string\n /** User ID of the publisher, if available. */\n readonly publishedBy?: string\n}\n\n/** Options for `BlobSet.put()`. */\nexport interface BlobPutOptions {\n /** MIME type hint. If omitted, auto-detected from magic bytes. */\n mimeType?: string\n /**\n * Raw chunk size in bytes. Priority: this value > store.maxBlobBytes > 256 KB.\n */\n chunkSize?: number\n /**\n * Whether to gzip-compress bytes before encrypting. Default: `true`.\n * Auto-set to `false` for pre-compressed MIME types (JPEG, PNG, ZIP, etc.).\n */\n compress?: boolean\n /** User ID to record as `uploadedBy`. Defaults to the Noydb session user. */\n uploadedBy?: string\n /**\n * User-visible filename to store on the slot. Defaults to the slot name.\n * Differs from the slot name when the caller wants a display/download name\n * (e.g. slot `attachment` holding `invoice-2024.pdf`); this is the value\n * that the L1 lexical index tokenizes for blob fields.\n */\n filename?: string\n}\n\n/** Options for `BlobSet.response()` and `BlobSet.responseVersion()`. */\nexport interface BlobResponseOptions {\n /**\n * When `true`, sets `Content-Disposition: inline; filename=\"...\"` so\n * the browser renders the file in the tab. Default (`false`) sets\n * `attachment; filename=\"...\"` which triggers a download.\n */\n inline?: boolean\n /** Override the filename in the Content-Disposition header. */\n filename?: string\n}\n\n// ─── Store Capabilities ─────────────────────────────\n\nexport type StoreAuthKind =\n | 'none'\n | 'filesystem'\n | 'api-key'\n | 'iam'\n | 'oauth'\n | 'kerberos'\n | 'browser-origin'\n\nexport interface StoreAuth {\n kind: StoreAuthKind | StoreAuthKind[]\n required: boolean\n flow: 'static' | 'oauth' | 'kerberos' | 'implicit'\n}\n\n/**\n * The store's authoritative clock as a bounded-uncertainty interval\n * (Spanner TrueTime model). True time is provably within [earliest, latest];\n * `latest - earliest` is the clock-uncertainty bound ε. Used by deferred\n * numbering to order records by store-commit-time and to commit-wait. Never\n * the client wall clock.\n */\nexport interface StoreTime {\n readonly earliest: number\n readonly latest: number\n}\n\nexport interface StoreCapabilities {\n /**\n * true — the store's expectedVersion check and write are atomic at the\n * storage layer. Two concurrent puts with the same expectedVersion will\n * produce exactly one success and one ConflictError.\n * false — check and write are separate operations with a race window.\n */\n casAtomic: boolean\n /**\n * true — the store exposes an authoritative {@link NoydbStore.getStoreTime}\n * clock and records are ordered by store-commit-time. Required for\n * `withDeferredNumbering`. Absent/false — the store cannot back deferred\n * numbering (use CAS `sequence().next()` or per-series).\n */\n serverWriteTime?: boolean\n /**\n * Advisory geographic region this store serves (e.g. `'eu'`, `'us'`).\n * Purely declarative — no behavior change for stores that omit it. The\n * federation data-residency guard compares this against a\n * `sharding.regionOf(record)` to refuse non-compliant shard placement.\n */\n region?: string\n auth: StoreAuth\n /**\n * true — the store implements {@link NoydbStore.tx} and commits\n * every op atomically at the storage layer. The hub's\n * `db.transaction(fn)` will delegate to `tx(ops)` and surface a\n * single pass/fail outcome. false (or absent) — no native\n * multi-record atomicity; the hub falls back to per-record OCC\n * with best-effort unwind on partial failure.\n */\n txAtomic?: boolean\n /**\n * Maximum raw bytes per blob chunk record.\n * `undefined` — no limit (S3, file, IDB); blob stored as single chunk.\n * `256 * 1024` — DynamoDB (400 KB item limit minus envelope overhead).\n * `5 * 1024 * 1024` — localStorage quota safety.\n */\n maxBlobBytes?: number\n}\n\n// ─── Factory Options ───────────────────────────────────────────────────\n\nexport interface NoydbOptions {\n /** The ciphertext store. Optional — defaults to the built-in `memoryStore()` (non-persistent). */\n readonly store?: NoydbStore\n /**\n * tree-shake seam — optional blob strategy. Pass `withBlobs()`\n * from `@noy-db/hub/blobs` to enable `collection.blob(id)` storage.\n * When omitted, hub's blob machinery stays out of the bundle (ESM\n * tree-shaking) and `collection.blob(id)` throws with a pointer at\n * the subpath. `BlobStrategy` is `@internal` — users only construct\n * it via the subpath factory.\n *\n * @internal\n */\n readonly blobStrategy?: BlobStrategy\n /**\n * Cold-storage archival target. `withArchive({ store })` designates a\n * second store that holds archived record envelopes. Enables\n * `vault.archive()` / `vault.restore()` / `vault.listArchived()`.\n */\n readonly archiveStrategy?: ArchiveStrategy\n /**\n * tree-shake seam — optional indexing strategy. Pass\n * `withIndexing()` from `@noy-db/hub/indexing` to enable eager-mode\n * `==/in` fast-paths, lazy-mode `.lazyQuery()`, rebuild/reconcile,\n * and auto-reconcile. When omitted, indexing code never reaches the\n * bundle; `.lazyQuery()` throws with a pointer at the subpath, and\n * eager-mode collections fall back to linear scans regardless of\n * `indexes: [...]` declarations. `IndexStrategy` is `@internal` —\n * users only construct it via the subpath factory.\n *\n * @internal\n */\n readonly indexStrategy?: IndexStrategy\n /**\n * tree-shake seam — optional aggregate strategy. Pass\n * `withAggregate()` from `@noy-db/hub/aggregate` to enable\n * `.aggregate()` and `.groupBy()` on Query. When omitted, those\n * methods throw with a pointer at the subpath; the ~886 LOC of\n * Aggregation + GroupedQuery machinery never reaches the bundle.\n * Streaming `scan().aggregate()` works independently of this\n * strategy — it doesn't use the `Aggregation` class.\n *\n * @internal\n */\n readonly aggregateStrategy?: AggregateStrategy\n /**\n * tree-shake seam — optional CRDT strategy. Required when\n * any collection is declared with `crdt: 'lww-map' | 'rga' | 'yjs'`;\n * otherwise the first put/sync-merge hitting the CRDT path throws.\n * When omitted, ~221 LOC of LWW-Map / RGA / merge helpers never\n * reach the bundle.\n *\n * @internal\n */\n readonly crdtStrategy?: CrdtStrategy\n /**\n * tree-shake seam — strategy for the collection-level hierarchical-tier\n * operations. Pass `withTiers()` from `@noy-db/hub/tiers` to enable\n * `putAtTier`/`getAtTier`/`listAtTier`/`elevate`/`demote` on collections\n * declared with `{ tiers: [...] }`. When omitted, all five throw\n * `TiersNotEnabledError` and the tier read/write/re-key engine never\n * reaches the bundle.\n *\n * @internal\n */\n readonly tiersStrategy?: TiersStrategy\n /**\n * tree-shake seam — optional consent-audit strategy. Pass\n * `withConsent()` from `@noy-db/hub/consent` to enable per-op audit\n * writes into `_consent_audit` when a consent scope is active.\n * When omitted, `vault.consentAudit()` returns `[]` and writes are\n * no-ops; the consent module's ~194 LOC never reaches the bundle.\n *\n * @internal\n */\n readonly consentStrategy?: ConsentStrategy\n /**\n * tree-shake seam — optional periods strategy. Pass\n * `withPeriods()` from `@noy-db/hub/periods` to enable\n * `vault.closePeriod()` / `.openPeriod()` / write-guard on closed\n * periods. When omitted, `vault.listPeriods()` returns `[]` and\n * the write-guard is a no-op; the ~363 LOC of period validation +\n * ledger appending stay out of the bundle.\n *\n * @internal\n */\n readonly periodsStrategy?: PeriodsStrategy\n /**\n * tree-shake seam — optional VaultFrame strategy. Pass\n * `withShadow()` from `@noy-db/hub/shadow` to enable\n * `vault.frame()`. Without it, calling `vault.frame()` throws.\n *\n * @internal\n */\n readonly shadowStrategy?: ShadowStrategy\n /**\n * tree-shake seam — optional multi-record transactions. Pass\n * `withTransactions()` from `@noy-db/hub/tx` to enable\n * `db.transaction(fn)`. Without it, calling the method throws.\n *\n * @internal\n */\n readonly txStrategy?: TxStrategy\n /**\n * tree-shake seam — optional history + ledger + time-machine.\n * Pass `withHistory()` from `@noy-db/hub/history` to enable\n * per-record version snapshots, the hash-chained audit ledger, JSON\n * Patch deltas, `vault.ledger()`, `vault.at()`, and the\n * `collection.history()` / `getVersion()` / `revert()` / `diff()` /\n * `clearHistory()` / `pruneRecordHistory()` read APIs. When omitted,\n * snapshots/prune/clear are silent no-ops, the read APIs throw with\n * a pointer at the subpath, and ~1,880 LOC stay out of the bundle.\n *\n * @internal\n */\n readonly historyStrategy?: HistoryStrategy\n /**\n * GDPR right-to-erasure. Pass `withForgetCascade({ subjects })`\n * from `@noy-db/hub/forget` to declare which collections carry erasable\n * subject data and the record field naming the data subject. Enables\n * `vault.forget(subjectId)` crypto-shred (rewrite-to-tombstone of the live\n * record + every history version → body permanently undecryptable, single\n * `op:'forget'` ledger entry, chain still verifies). Each declared\n * collection is forced to `perRecordKeys: true`. When omitted (the\n * `NO_FORGET` default), `vault.forget()` throws\n * `ForgetStrategyNotConfiguredError` and no subject-index write hooks run.\n * Requires `historyStrategy` (the ledger) for the erasure-proof entry.\n */\n readonly forgetStrategy?: ForgetStrategy\n /**\n * tree-shake seam — optional i18n strategy. Pass `withI18n()`\n * from `@noy-db/hub/i18n` to enable `i18nText`/`dictKey` field\n * resolution on reads, `i18nText` validation on writes, and\n * `vault.dictionary(name)`. When omitted, locale resolution is the\n * identity (raw values returned), the validators throw with a\n * pointer to the subpath, and ~854 LOC of dictionary + locale\n * machinery stay out of the bundle.\n *\n * @internal\n */\n readonly i18nStrategy?: I18nStrategy\n /**\n * tree-shake seam — optional session-policy strategy. Pass\n * `withSession()` from `@noy-db/hub/session` to enable\n * `sessionPolicy` validation, `PolicyEnforcer` lifecycle (idle /\n * absolute timeouts, lockOnBackground), and global session-token\n * revocation. When omitted, setting `sessionPolicy` throws at\n * `createNoydb()` time, and ~495 LOC of policy + token machinery\n * stay out of the bundle.\n *\n * @internal\n */\n readonly sessionStrategy?: SessionStrategy\n /**\n * tree-shake seam — optional sync engine + presence strategy.\n * Pass `withSync()` from `@noy-db/hub/sync` to enable\n * `db.push()` / `pull()` / replication, `db.transaction(vault)`\n * for sync-aware transactions, and `collection.presence()`. When\n * omitted, configuring `sync` / calling these surfaces throws with\n * a pointer at the subpath, and ~856 LOC of replication + presence\n * machinery stay out of the bundle. Keyring stays core; grant/\n * revoke/magic-link/delegation tree-shake via direct imports.\n *\n * @internal\n */\n readonly syncStrategy?: SyncStrategy\n /**\n * Tree-shake seam — optional snapshot-lifecycle service. Pass\n * `withSnapshots({ store })` from `@noy-db/hub/snapshots` to enable\n * `db.snapshot()`, `db.listSnapshots()`, and `db.restoreSnapshot()`.\n * When omitted, all three methods throw with a pointer at the subpath.\n */\n readonly snapshotStrategy?: SnapshotStrategy\n /**\n * Tree-shake seam — optional attestation capability. Pass\n * `withAttestation()` from `@noy-db/hub/attestation` to enable\n * `vault.issueAttestation()`, `vault.getDocumentSigningPublicKey()`,\n * `vault.revokeAttestation()`, `vault.unrevokeAttestation()`,\n * `vault.getRevokedDocIds()`, and `vault.publishRevocationList()`. When\n * omitted, all six throw `AttestationNotEnabledError` and the issue/revoke/\n * signer engines are tree-shaken out.\n */\n readonly attestationStrategy?: AttestationStrategy\n /**\n * Tree-shake seam — optional classified-field capability. Pass\n * `withClassified()` from `@noy-db/hub/classified` to enable\n * `collection.reveal()`. When omitted, `reveal()` throws\n * `ClassifiedNotEnabledError` and the reveal engine is tree-shaken out.\n */\n readonly classifiedStrategy?: ClassifiedStrategy\n /**\n * Tree-shake seam — optional sealed-record (grantor-side) capability. Pass\n * `withSealedRecord()` from `@noy-db/hub/sealed-record` to enable\n * `vault.sealRecordToHost()`, `vault.revokeSealedRecord()`, and\n * `vault.rotateRecordCek()`. When omitted, all three throw\n * `SealedRecordNotEnabledError` and the record-keys grantor engine is reached\n * only via opt-in. The host-side `openSealedRecord` opener stays ungated.\n */\n readonly sealedRecordStrategy?: SealedRecordStrategy\n /**\n * Tree-shake seam — optional portability (data-sovereignty) capability. Pass\n * `withPortability()` from `@noy-db/hub/portability` to enable the\n * `vault.user.*` export/withdrawal surface (`exportMyAccessibleData`,\n * `unilateralWithdrawal`, `requestWithdrawal`, `listWithdrawalRequests`,\n * `approveWithdrawal`, `rejectWithdrawal`). When omitted, all six throw\n * `PortabilityNotEnabledError` and the export/withdraw/request engines are\n * reached only via opt-in.\n */\n readonly portabilityStrategy?: PortabilityStrategy\n /**\n * Tree-shake seam — optional atomic-sequence capability. Pass\n * `withSequence()` from `@noy-db/hub` to enable `vault.sequence(name)`\n * (`.next()` / `.peek()` / `.seedTo()`). When omitted, `vault.sequence()`\n * throws `SequenceNotEnabledError` and the CAS `SequenceStore` engine is\n * reached only via opt-in. Deferred-numbering series (`numbering:\n * [withDeferredNumbering(...)]`) are a separate capability and stay live.\n */\n readonly sequenceStrategy?: SequenceStrategy\n /**\n * Tree-shake seam — optional sovereign-custody (FR-6) capability. Pass\n * `withCustody()` from `@noy-db/hub` to enable minting / removing a\n * `custodian` (`db.grantCustodian` / `db.revokeCustodian` and the\n * `vault.custody.*` facade) plus the `vault.custody.liberate()` ceremony.\n * When omitted, those throw `CustodyNotEnabledError` and the liberate engine\n * is reached only via opt-in. The lower-level `liberateVault` free function\n * stays ungated (it has no createNoydb instance to gate against).\n */\n readonly custodyStrategy?: CustodyStrategy\n /**\n * Tree-shake seam — optional search / retrieval capability. Pass\n * `withSearch()` from `@noy-db/hub` to enable a collection's `search`\n * / `retrieve` / `similarTo` / `warmIndex` / `flushIndex` methods and the\n * put()-time embedding-vector compute for collections declaring `embeddings`.\n * When omitted, those throw `SearchNotEnabledError` and the search/retrieval\n * engine is reached only via opt-in. Embedding compute is paired with search\n * (a vector no gated retrieval could read would be dead weight).\n */\n readonly searchStrategy?: SearchStrategy\n /**\n * Tree-shake seam — optional cargo (partition extraction) capability\n * (FR-6/FR-7). Pass `withCargo()` from `@noy-db/hub/cargo` to enable the\n * source-side `extractPartition(vault, …)` free function. When omitted, it\n * throws `CargoNotEnabledError` and the extraction crypto is reached only via\n * opt-in. The recipient-side `adoptPartition` / `decryptExtractedPartition`\n * free functions — and `diffVault` (shared import/merge infra) — operate\n * without a gated source instance and stay ungated.\n */\n readonly cargoStrategy?: CargoStrategy\n /**\n * Optional guard strategies — collection-level write guards. Each\n * handle is the output of `withGuard()` from `@noy-db/hub/guards`.\n * Multiple guards per collection are allowed; they are dispatched\n * in registration order on `collection.put()`.\n */\n readonly guardStrategies?: ReadonlyArray<GuardStrategyHandleAny>\n /**\n * Deferred-numbering series declared via `withDeferredNumbering(...)`.\n * `vault.sequence(series).next({ for })` then assigns gap-free serials at a\n * numbering pass (`vault.runNumberingPass(series)`) instead of via CAS.\n */\n readonly numbering?: ReadonlyArray<DeferredNumberingConfig>\n /**\n * Optional derivation strategies — source-to-output projections that\n * fire on `collection.put()`. Each handle is the output of\n * `withDerivation()` from `@noy-db/hub/derivations`. The vault\n * validates the derivation graph for cycles on `openVault`; a cyclic\n * graph throws `DerivationCycleError`.\n */\n readonly derivationStrategies?: ReadonlyArray<DerivationStrategyHandle>\n /**\n * Optional materialized-view strategies.\n * Each handle returned by `withMaterializedView()` from\n * `@noy-db/hub/materialized-views`. The vault runs unified cycle\n * detection across the MV + derivation graphs at `openVault`; a\n * cyclic graph throws `MaterializedViewCycleError`.\n */\n readonly materializedViewStrategies?: ReadonlyArray<MaterializedViewStrategyHandle>\n /**\n * Optional overlay strategies. Each handle returned by\n * `withOverlayedView()` from `@noy-db/hub/overlay-views`. The vault\n * validates name uniqueness + base concreteness + overlay\n * availability at `openVault`; a clash throws one of the\n * `Overlay*Error` family.\n */\n readonly overlayedViewStrategies?: ReadonlyArray<OverlayedViewStrategyHandle>\n /** Optional remote store(s) for sync. Accepts a single store, a SyncTarget, or an array. */\n readonly sync?: NoydbStore | SyncTarget | SyncTarget[]\n /** User identifier. */\n readonly user: string\n /** Passphrase for key derivation. Required unless encrypt is false or `getKeyring` is provided. */\n readonly secret?: string\n /**\n * Optional callback that returns an unlocked keyring for a given vault.\n * Use this to plug in WebAuthn / OIDC / Shamir / any unlock path that\n * produces an `UnlockedKeyring` outside the passphrase model.\n *\n * When set, `secret` MUST NOT also be set — `createNoydb` throws if both\n * are supplied. When neither is set (and `encrypt !== false`), `createNoydb`\n * also throws.\n *\n * The callback is called lazily, on the first operation that needs the\n * keyring for a given vault. Noydb caches the returned keyring per-vault\n * for the lifetime of the instance, so the callback is invoked at most\n * once per `(instance, vault)` pair (assuming the callback resolves\n * successfully). If the callback rejects, the rejection surfaces from the\n * first vault operation that triggered the unlock; subsequent operations\n * will retry the callback.\n *\n * @example\n * ```ts\n * import { createNoydb } from '@noy-db/hub'\n * import { unlockWebAuthn } from '@noy-db/on-webauthn'\n *\n * const enrollment = await loadEnrollment()\n * const db = await createNoydb({\n * store,\n * user: 'alice',\n * getKeyring: (vault) => unlockWebAuthn(enrollment),\n * })\n * ```\n *\n * Note: this callback is responsible for both the \"open existing vault\"\n * and the \"create new vault\" cases. Unlike the passphrase path, there is\n * no automatic `NoAccessError` → `createOwnerKeyring` fallback, because\n * the callback owner has the UI context to decide which path to run.\n * For first-time bootstrap, use a passphrase or recovery code, enroll\n * WebAuthn from the unlocked keyring, then swap to `getKeyring` on\n * subsequent sessions.\n */\n readonly getKeyring?: (vault: string) => Promise<UnlockedKeyring>\n /**\n * Passphrase mode. Default `'standard'`.\n *\n * - `'standard'` — the legacy flow. `secret` supplies the\n * plaintext passphrase, the user knows it, and the policy gate\n * `rotate-passphrase` is enabled.\n * - `'managed'` — rubber-hose-resistant mode. Hub generates a\n * 256-bit random passphrase at first open and seals it under\n * the provided `sealingKey`. The user never sees or types the\n * passphrase, defeating the $5-wrench attack. Mutually\n * exclusive with `secret` and `getKeyring`.\n *\n * @see https://github.com/vLannaAi/noy-db-docs/blob/main/content/docs/services/session-tiers.md → Managed-passphrase mode\n */\n readonly passphraseMode?: 'standard' | 'managed'\n /**\n * Provider that seals/unseals the auto-generated managed-mode\n * passphrase. Required when `passphraseMode === 'managed'`; ignored\n * otherwise. Implementations live in per-platform packages\n * (`@noy-db/seal-macos-keychain`, `@noy-db/seal-wincred`,\n * `@noy-db/seal-libsecret`, `@noy-db/seal-aws-kms`, …).\n */\n readonly sealingKey?: SealingKeyProvider\n /** Required to use `profile: 'shamir'` recovery. Pass\n * `shamirRecoveryProvider()` from `@noy-db/on-shamir`. */\n readonly shamirRecovery?: ShamirRecoveryProvider\n /** Auth method. Default: 'passphrase'. */\n readonly auth?: 'passphrase' | 'biometric'\n /** Enable encryption. Default: true. */\n readonly encrypt?: boolean\n /**\n * Debug-only: lay plaintext records out as directly-inspectable store\n * objects (record fields inlined beside envelope metadata, `_debug: 1`) so\n * native store tooling can read them without unwrapping `_data`. Requires\n * `encrypt: false` — combining with encryption throws `DebugPlaintextError`\n * at construction. NEVER enable for production or client data.\n */\n readonly debugPlaintext?: boolean\n /**\n * Object projection for direct-serve / external blob fields (`as-*`, e.g.\n * `@noy-db/as-aws-s3`). Blob fields declared `external` route their RAW bytes\n * to this projection as a single native object (servable from S3/CDN) instead\n * of the encrypted-chunk path; the encrypted record/slot stays the catalog.\n * Sees plaintext bytes — outside the zero-knowledge guarantee.\n */\n readonly objectStore?: ObjectProjection\n /** Conflict resolution strategy. Default: 'version'. */\n readonly conflict?: ConflictStrategy\n /**\n * Sync scheduling policy. Controls when push/pull fire.\n * Default inferred from store category: per-record → `on-change`,\n * bundle → `debounce 30s`.\n */\n readonly syncPolicy?: SyncPolicy\n /**\n * @deprecated Use `syncPolicy` instead. Kept for backward compatibility.\n * When both are supplied, `syncPolicy` takes precedence.\n */\n readonly autoSync?: boolean\n /**\n * @deprecated Use `syncPolicy` instead. Kept for backward compatibility.\n */\n readonly syncInterval?: number\n /**\n * Session timeout in ms. Clears keys after inactivity. Default: none.\n * @deprecated Use `sessionPolicy.idleTimeoutMs` instead. This field is\n * still honored for backwards compatibility but `sessionPolicy` takes\n * precedence when both are supplied.\n */\n readonly sessionTimeout?: number\n /**\n * Session policy controlling lifetime, re-auth requirements, and\n * background-lock behavior. When supplied, replaces the\n * legacy `sessionTimeout` field.\n */\n readonly sessionPolicy?: SessionPolicy\n /**\n * Validate passphrase strength against the phrase format\n * on first-time keyring creation. When\n * `true`, weak phrases throw {@link WeakPassphraseError} from\n * `createNoydb()` / `db.rotatePassphrase()`. Default: `false` for\n * back-compat; planned to flip to `true` in a future major release.\n */\n readonly validatePassphrase?: boolean\n /**\n * Vault-level policy gate document. When present, the hub\n * persists the merged policy at `_meta/policy` on first-time vault\n * creation and gates sensitive operations (`db.rotatePassphrase`,\n * `db.export*`, …) against it. Omitted ⇒ the engine uses\n * {@link PERSONAL_POLICY}. Use {@link STRICT_POLICY} for regulated\n * deployments.\n *\n * The on-disk document is the source of truth — the policy field\n * is only honored at vault creation; subsequent runs read from\n * `_meta/policy`. Use `db.updatePolicy()` to change it deliberately.\n *\n * Imported from `@noy-db/hub` as a type-only reference; the runtime\n * import lives in `policy/index.ts`.\n */\n readonly policy?: VaultPolicy\n /**\n * Mandatory recovery profile enrollment. Vaults with\n * `recover-passphrase` enabled MUST register at least one profile\n * before being production-ready, otherwise `createNoydb()` throws\n * {@link RecoveryNotEnrolledError}. Set\n * `policy.gates['recover-passphrase'].enabled = false` to\n * deliberately opt out of recovery (passphrase loss = data loss).\n *\n * The `'paper'` profile is supported end-to-end. Other\n * profiles ship the API shape and throw\n * {@link RecoveryProfileNotImplementedError} during use.\n */\n readonly recovery?: ReadonlyArray<RecoveryEnrollment>\n /**\n * When `true`, `createNoydb` rejects vaults with no recovery\n * entries persisted (per the spec's mandatory-enrollment\n * requirement). Default `false` for back-compat; planned to\n * flip to `true` in a future major release. Apps in regulated\n * environments should turn this on now.\n */\n readonly requireRecovery?: boolean\n /**\n * What to do when `openVault` finds an existing keyring in the store that\n * cannot be decrypted with the supplied credentials (`InvalidKeyError`).\n *\n * - `'error'` (default) — propagate the error. The app must prompt the user\n * to supply the correct credentials or clear both the data and auth stores.\n * - `'reset'` — delete the stale keyring and re-initialise the vault from\n * scratch using the current credentials. Use this when the data store can\n * become detached from the auth store (e.g. the user cleared the IndexedDB\n * data records but not the keyring row, or a WebAuthn credential was rotated).\n * **All previously encrypted data is unrecoverable after a reset.**\n *\n * Only applies to the passphrase (`secret`) path. When `getKeyring` is used,\n * the callback is responsible for handling stale-keyring detection itself.\n */\n readonly onInvalidKey?: 'error' | 'reset'\n /**\n * Enable the public envelope service (`https://github.com/vLannaAi/noy-db-docs/blob/main/content/docs/services/public-envelope.md`).\n * Pass `true` for the default schema (every standard field, 256 KB\n * icon cap, 200-char text cap), or a `PublicEnvelopeSchema` to\n * narrow what the owner can set. Off by default — vaults written\n * by hubs without this option carry no envelope, full stop.\n */\n readonly publicEnvelope?: true | PublicEnvelopeSchema\n /** Audit history configuration. */\n readonly history?: HistoryConfig\n /**\n * Consumer-supplied translation function for `i18nText` fields with\n * `autoTranslate: true`.\n *\n * ⚠ **`plaintextTranslator` receives unencrypted text.** Configuring\n * this hook causes plaintext to leave noy-db's zero-knowledge boundary\n * over whatever channel the consumer's implementation uses. noy-db ships\n * no built-in translator and adds no translator SDKs as dependencies.\n * The consumer chooses and owns the data policy of the external service.\n *\n * Per-field opt-in via `autoTranslate: true` on `i18nText()`. Calling\n * `put()` on a collection with `autoTranslate: true` fields while this\n * option is absent throws `TranslatorNotConfiguredError`.\n *\n * See `NOYDB_SPEC.md § Zero-Knowledge Storage` for the invariant text.\n */\n readonly plaintextTranslator?: PlaintextTranslatorFn\n /**\n * Human-readable name for the translator, recorded in the in-process\n * audit log (e.g. `'deepl-pro-with-dpa'`, `'self-hosted-llama-7b'`).\n * Defaults to `'anonymous'` when not supplied.\n */\n readonly plaintextTranslatorName?: string\n /**\n * Drain-barrier coordination transport for the schema fence.\n * When omitted, the kernel uses a {@link CoordinationProvider} backed by the\n * primary store (`StoreCoordinationProvider`), reproducing today's\n * store-polling fence behavior byte-for-byte. `@noy-db/by-tabs` /\n * `@noy-db/by-peer` inject a real-time push transport here; an external\n * orchestrator (`@klum-db/lobby`) drives it through the `Noydb` handle.\n *\n * @internal\n */\n readonly coordinationStrategy?: CoordinationProvider\n /**\n * Pre-resolved factory for the `vault.user` per-principal user-envelope\n * API. `createNoydb()` always resolves this itself (dynamically\n * importing `with-party/directory/user-envelope/api.js`) before\n * constructing `Noydb` — mirrors the {@link coordinationStrategy}\n * pre-resolve above. There is no supported way to override it; it exists\n * as an options-bag field only so `createNoydb()` can thread the\n * pre-resolved value into the constructor without a second parameter.\n *\n * @internal\n */\n readonly userApiFactory?: UserApiFactory\n /**\n * Pre-resolved factory for the `NoydbPolicy` service (vault-policy\n * read/update/bootstrap + session-policy enforcer wiring).\n * `createNoydb()` always resolves this itself (dynamically importing\n * `with-party/policy/index.js`) before constructing `Noydb` — mirrors the\n * {@link coordinationStrategy} / {@link userApiFactory} pre-resolves\n * above. There is no supported way to override it.\n *\n * @internal\n */\n readonly policyFactory?: NoydbPolicyFactory\n /**\n * Pre-resolved policy-gate engine function (`checkGate`).\n * `createNoydb()` always resolves this itself (dynamically importing\n * `with-party/policy/index.js`) before constructing `Noydb` — same\n * pre-resolve pattern as {@link policyFactory}.\n *\n * @internal\n */\n readonly policyCheckGateFn?: PolicyCheckGateFn\n /**\n * Stable id for the session that owns this instance's writers (one user's\n * writers across vaults). Tags every {@link WriterPresence} the fence\n * watcher reports. Defaults to a fresh ULID per `Noydb` instance.\n *\n * @internal\n */\n readonly sessionId?: string\n}\n\n// ─── History / Audit Trail ─────────────────────────────────────────────\n\n/** History configuration. */\nexport interface HistoryConfig {\n /** Enable history tracking. Default: true. */\n readonly enabled?: boolean\n /** Maximum history entries per record. Oldest pruned on overflow. Default: unlimited. */\n readonly maxVersions?: number\n /**\n * Participate in the vault-wide hash-chained tamper ledger. Default:\n * `true` (every write of this collection appends a ledger entry when\n * `withHistory()` is active). Set `false` to exclude this collection's\n * writes from the chain — its puts/deletes leave no ledger entry,\n * confining tamper-evidence to the collections where it carries weight.\n * Independent of `enabled`, which gates per-record snapshots. Has no\n * effect when `withHistory()` is not active (there is no ledger).\n */\n readonly ledger?: boolean\n}\n\n/** Options for querying history. */\nexport interface HistoryOptions {\n /** Start date (inclusive), ISO 8601. */\n readonly from?: string\n /** End date (inclusive), ISO 8601. */\n readonly to?: string\n /** Maximum entries to return. */\n readonly limit?: number\n}\n\n/** Options for pruning history. */\nexport interface PruneOptions {\n /** Keep only the N most recent versions. */\n readonly keepVersions?: number\n /** Delete versions older than this date, ISO 8601. */\n readonly beforeDate?: string\n}\n\n/** A decrypted history entry. */\nexport interface HistoryEntry<T> {\n readonly version: number\n readonly timestamp: string\n readonly userId: string\n readonly record: T\n}\n\n// ─── Bulk operations ──────────────────────────────────────\n\n/** Per-item options for `Collection.putMany()`. */\nexport interface PutManyItemOptions {\n /**\n * Optimistic-concurrency check: fail this item if the stored version\n * is not `expectedVersion`. Honored only in `atomic: true` mode;\n * ignored in the default best-effort loop.\n */\n readonly expectedVersion?: number\n}\n\n/**\n * Batch-level options for `Collection.putMany()` and `deleteMany()`.\n *\n * `atomic: true` switches the call from best-effort loop\n * to all-or-nothing: a pre-flight CAS check runs first, then every op\n * is executed; any mid-batch failure triggers a best-effort revert.\n * On failure in atomic mode the whole call throws — you won't get a\n * partial `PutManyResult`. On success the result mirrors the default\n * loop's shape.\n */\nexport interface PutManyOptions {\n readonly atomic?: boolean\n}\n\n/** Result of `Collection.putMany()`. */\nexport interface PutManyResult {\n /** `true` iff every entry succeeded. */\n readonly ok: boolean\n /** IDs that were successfully written. */\n readonly success: readonly string[]\n /** Entries that failed, with the error that prevented each write. */\n readonly failures: ReadonlyArray<{ readonly id: string; readonly error: Error }>\n}\n\n/** Result of `Collection.deleteMany()`. Same shape as `PutManyResult`. */\nexport interface DeleteManyResult {\n readonly ok: boolean\n readonly success: readonly string[]\n readonly failures: ReadonlyArray<{ readonly id: string; readonly error: Error }>\n}\n\n// ─── User Envelope (vault.user contract) ───────────────────────────────\n//\n// The per-principal user-envelope service's PUBLIC CONTRACT lives here in\n// the spine; the implementation (`UserApi` / `createUserApi`, storage\n// primitives) lives at `with-party/directory/user-envelope/` and is wired\n// in by `createNoydb()` via the pre-resolved `userApiFactory` option above\n// — the same dynamic-import-then-stash pattern used for the default\n// `CoordinationProvider`.\n//\n// @see docs/superpowers/specs/2026-05-05-user-envelope-design.md\n\n/**\n * Thin reader view of a user envelope. The on-disk shape is the standard\n * {@link EncryptedEnvelope}; this is what callers see after the storage\n * layer has decrypted the payload.\n *\n * Hub commits to the `keyringId` ⇔ `userId` identity and the `_v` / `_ts`\n * envelope metadata. The `data` payload is fully app-defined — hub does\n * not introspect, validate, or reserve any keys inside it.\n */\nexport interface UserEnvelope<T> {\n /** The principal id this envelope belongs to. Equals the keyring `user_id`. */\n readonly keyringId: string\n /** App-owned payload. Opaque to hub. */\n readonly data: T\n /** Optimistic-concurrency version. Increments on every write. */\n readonly _v: number\n /** ISO timestamp of the last write. */\n readonly _ts: string\n}\n\n/**\n * Recursive partial. Used for `updateMe(patch)` so callers can hand in\n * deeply-nested partial shapes and have them deep-merged onto the\n * current envelope.\n */\nexport type DeepPartial<T> = T extends object\n ? { [P in keyof T]?: DeepPartial<T[P]> }\n : T\n\n/**\n * Recursive partial with `null` allowed at every level — used by\n * `updateMe` to express deletion intent in addition to merge.\n *\n * Semantics inside `updateMe`:\n * - `undefined` (or absent key) — skip; source value preserved\n * - `null` — delete the key from the resulting envelope\n * - any other value — overwrite (deep-merge for plain objects,\n * replace for primitives / arrays)\n *\n * Matches lodash `_.merge` behavior on `null` and Firestore's\n * `FieldValue.delete()` semantics. Loosened from `DeepPartial<T>`.\n * Consumers wanting the original \"merge-only\" surface can keep\n * importing `DeepPartial` and avoid passing `null`.\n */\nexport type DeepPartialOrNull<T> = T extends object\n ? { [P in keyof T]?: DeepPartialOrNull<T[P]> | null }\n : T\n\n/** Cancel a previously-registered subscription. */\nexport type Unsubscribe = () => void\n\n/**\n * Optional factor-proof bundle threaded into gated user-envelope\n * operations. Same shape as `Noydb.checkGate(vault, gate, presented)`\n * accepts elsewhere — apps that have already presented a TOTP/email-OTP\n * for this session pass it here to satisfy tightened policies.\n */\nexport interface UserEnvelopePresented {\n readonly factors?: readonly FactorProof[]\n readonly sharedDevice?: boolean\n}\n\n/**\n * Callback used by `UserApi` to validate the active session against a\n * policy gate. Provided by the `Vault` constructor; in production this\n * delegates to `Noydb.checkGate(vault, gate, presented)`. In tests, a\n * no-op stub is fine.\n */\nexport type UserEnvelopeCheckGate = (\n gate:\n | 'edit-own-profile'\n | 'view-team-profiles'\n | 'client-unilateral-withdraw'\n | 'user-request-withdrawal'\n | 'approve-user-withdrawal',\n presented?: UserEnvelopePresented,\n) => Promise<void>\n\n/**\n * Reactive handle returned by `live()`. `current` is the most recently\n * observed value; `subscribe(cb)` fires on subsequent local writes.\n * `stop()` releases the underlying subscription.\n */\nexport interface LiveUserEnvelope<T> {\n current(): UserEnvelope<T> | null\n subscribe(cb: (env: UserEnvelope<T> | null) => void): Unsubscribe\n stop(): void\n}\n\n/**\n * The 2nd positional parameter of a {@link PortabilityStrategy} method\n * (index 1, right after the leading `vault` argument).\n */\ntype PortabilityParam1<K extends keyof PortabilityStrategy> = Parameters<PortabilityStrategy[K]>[1]\n/**\n * The 3rd positional parameter (index 2) — only present on\n * `approveWithdrawal` / `rejectWithdrawal` (requestId is index 1 there).\n */\ntype PortabilityParam2<K extends keyof PortabilityStrategy> = Parameters<PortabilityStrategy[K]>[2]\ntype PortabilityReturn<K extends keyof PortabilityStrategy> = ReturnType<PortabilityStrategy[K]>\n\n/**\n * Public `vault.user.*` API surface — the CONTRACT. The implementation\n * (`UserApi`) lives at `with-party/directory/user-envelope/api.ts` and\n * `implements` this interface; `createNoydb()` wires it in via the\n * pre-resolved {@link UserApiFactory}.\n *\n * Three families:\n * - Write-self: `me` / `updateMe` / `setMe` — always target the writer's\n * own keyringId. **Own-only write rule** is structural — no method\n * exists to write someone else's envelope.\n * - Read-anyone: `get` / `list` — read other principals' envelopes\n * (subject to `view-team-profiles` policy gate).\n * - Reactive: `subscribe` / `live` — in-process event emission on local\n * writes. Cross-instance updates land via the team/sync engine and\n * surface to subscribers when the sync diff replays through this API.\n *\n * @see docs/superpowers/specs/2026-05-05-user-envelope-design.md\n */\nexport interface VaultUserApi {\n requestWithdrawal(opts?: PortabilityParam1<'requestWithdrawal'>): PortabilityReturn<'requestWithdrawal'>\n listWithdrawalRequests(opts?: PortabilityParam1<'listWithdrawalRequests'>): PortabilityReturn<'listWithdrawalRequests'>\n approveWithdrawal(\n requestId: PortabilityParam1<'approveWithdrawal'>,\n opts?: PortabilityParam2<'approveWithdrawal'>,\n ): PortabilityReturn<'approveWithdrawal'>\n rejectWithdrawal(\n requestId: PortabilityParam1<'rejectWithdrawal'>,\n opts?: PortabilityParam2<'rejectWithdrawal'>,\n ): PortabilityReturn<'rejectWithdrawal'>\n unilateralWithdrawal(opts: PortabilityParam1<'withdrawAccessibleData'>): PortabilityReturn<'withdrawAccessibleData'>\n exportMyAccessibleData(opts?: PortabilityParam1<'exportAccessibleData'>): PortabilityReturn<'exportAccessibleData'>\n me<T = unknown>(): Promise<UserEnvelope<T> | null>\n updateMe<T extends object = Record<string, unknown>>(\n patch: DeepPartialOrNull<T>,\n presented?: UserEnvelopePresented,\n ): Promise<UserEnvelope<T>>\n setMe<T = unknown>(payload: T, presented?: UserEnvelopePresented): Promise<UserEnvelope<T>>\n getMyVisibility(): Promise<{ readonly hidden: boolean }>\n setMyVisibility(visibility: { readonly hidden: boolean }): Promise<void>\n get<T = unknown>(keyringId: string, presented?: UserEnvelopePresented): Promise<UserEnvelope<T> | null>\n list<T = unknown>(presented?: UserEnvelopePresented): Promise<UserEnvelope<T>[]>\n subscribe<T = unknown>(keyringId: string, cb: (env: UserEnvelope<T> | null) => void): Unsubscribe\n live<T = unknown>(keyringId: string): LiveUserEnvelope<T>\n}\n\n/**\n * Constructor dependencies for `UserApi` (the {@link VaultUserApi}\n * implementation). Built by `Vault`'s constructor and passed to the\n * pre-resolved {@link UserApiFactory}.\n */\nexport interface UserApiDeps {\n readonly adapter: NoydbStore\n readonly vaultName: string\n /** The writer's own keyringId. Frozen at construction time. */\n readonly writerKeyringId: string\n readonly getDek: () => Promise<EnclaveKey>\n /**\n * Policy-gate validator. When omitted, gates are skipped — useful\n * for low-level tests that exercise the storage layer directly.\n * Production paths always wire the Noydb-backed implementation.\n */\n readonly checkGate?: UserEnvelopeCheckGate\n /**\n * Noydb-backed `exportMyAccessibleData`, injected by the Vault\n * (which holds the keyring + bundle machinery). Omitted in low-level tests.\n */\n readonly exportAccessible?: (opts: PortabilityParam1<'exportAccessibleData'>) => PortabilityReturn<'exportAccessibleData'>\n /**\n * Noydb-backed `unilateralWithdrawal`, injected by the Vault.\n * Destructive — extract + dispose (delete | freeze). Omitted in low-level tests.\n */\n readonly unilateralWithdraw?: (opts: PortabilityParam1<'withdrawAccessibleData'>) => PortabilityReturn<'withdrawAccessibleData'>\n /**\n * Noydb-backed two-party withdrawal ceremony, injected by the\n * Vault. requestWithdraw = requester side; the rest = owner side.\n */\n readonly requestWithdraw?: (opts: PortabilityParam1<'requestWithdrawal'>) => PortabilityReturn<'requestWithdrawal'>\n readonly listWithdrawals?: (opts: PortabilityParam1<'listWithdrawalRequests'>) => PortabilityReturn<'listWithdrawalRequests'>\n readonly approveWithdraw?: (\n requestId: PortabilityParam1<'approveWithdrawal'>,\n opts: PortabilityParam2<'approveWithdrawal'>,\n ) => PortabilityReturn<'approveWithdrawal'>\n readonly rejectWithdraw?: (\n requestId: PortabilityParam1<'rejectWithdrawal'>,\n opts: PortabilityParam2<'rejectWithdrawal'>,\n ) => PortabilityReturn<'rejectWithdrawal'>\n}\n\n/**\n * Factory that builds the `vault.user` API implementation from its\n * dependencies. `createNoydb()` pre-resolves the real implementation\n * (`with-party/directory/user-envelope/api.js#createUserApi`) via a\n * dynamic import before constructing `Noydb`, so `Vault`'s constructor\n * can call it synchronously — the two sync `subscribe`/`live` methods on\n * `VaultUserApi` are why `vault.user` must be built synchronously.\n */\nexport type UserApiFactory = (deps: UserApiDeps) => VaultUserApi\n\n// ─── Policy gates (VaultPolicy contract) ───────────────────────────────\n//\n// Sensitive operations (rotate the passphrase, enroll an authenticator,\n// export plaintext, grant a user, …) are gated by a typed policy\n// object. The developer supplies a {@link VaultPolicy} at vault\n// creation; the hub merges it onto a built-in preset and persists the\n// merged document at `_meta/policy`.\n//\n// The CONTRACT (this section) lives here in the spine; the engine\n// (`checkGate`/`describeGate`), the presets (`PERSONAL_POLICY` /\n// `STRICT_POLICY`), storage (`loadVaultPolicy`/`saveVaultPolicy`), and the\n// `NoydbPolicy` facade implementation live at `with-party/policy/` and are\n// wired in by `createNoydb()` via the pre-resolved {@link NoydbPolicyFactory}\n// / {@link PolicyCheckGateFn} options above — the same\n// dynamic-import-then-stash pattern used for the default\n// `CoordinationProvider` / `UserApiFactory`.\n//\n// @see https://github.com/vLannaAi/noy-db-docs/blob/main/content/docs/services/session-tiers.md → Policy gates DSL\n\n/**\n * A single factor surface — the proof an actor presents at gate time.\n *\n * | Kind | Source | Off-device? |\n * |---|---|---|\n * | `totp` | RFC 6238 authenticator app (Google Auth, 1Password) | yes |\n * | `email-otp` | one-time code mailed to the user | yes |\n * | `recovery` | printable Base32 code (`@noy-db/on-recovery`) | yes (paper) |\n * | `shamir` | k-of-n threshold share (`@noy-db/on-shamir`) | yes |\n * | `webauthn-roaming` | hardware key (YubiKey, SoloKey, Titan) | yes (key portable) |\n * | `webauthn-platform` | platform passkey (Touch ID, Face ID, Hello) | no (device-bound) |\n * | `password` | tier-2 password (`@noy-db/on-password`) | no |\n * | `pin` | tier-3 quick-resume PIN (`@noy-db/on-pin`) | no |\n *\n * Off-device kinds (TOTP, email-OTP, recovery, shamir, roaming WebAuthn)\n * are the strongest factor proofs because they require something\n * separate from the device the user just unlocked. Platform / password /\n * PIN are useful for \"fresh proof of *this* user\" but don't bind across\n * devices — policies can require ANY of them or insist on a count of 2\n * to force a mix.\n *\n * `webauthn-platform`, `password`, `pin` — for consumers with no\n * off-device infrastructure (no TOTP, no email-OTP, paper recovery not\n * enrolled) who want to require \"any second factor I have wired\"\n * without losing the freshness guarantee.\n */\nexport type FactorKind =\n | 'totp'\n | 'email-otp'\n | 'recovery'\n | 'shamir'\n | 'webauthn-roaming'\n | 'webauthn-platform'\n | 'password'\n | 'pin'\n\n/**\n * One factor requirement entry. The default is \"any one of the listed\n * factors, fresh within the last 5 minutes\". Bumping `count` requires N\n * distinct fresh proofs; bumping `freshnessMs` widens the acceptance\n * window.\n */\nexport interface FactorRequirement {\n readonly anyOf: ReadonlyArray<FactorKind>\n /** Number of distinct factors required. Default 1. */\n readonly count?: number\n /** How recent each proof must be. Default 5 minutes. */\n readonly freshnessMs?: number\n}\n\n/** Soft signals layered on top of the gate verdict — never block on their own. */\nexport interface WarningRules {\n /** Behavior on shared-device tier-1 ops. `'block'` raises a `PolicyDeniedError`. */\n readonly sharedDevice?: 'warn' | 'block'\n /** Behavior on weak tier-2 (e.g. password-only) for sensitive ops. */\n readonly weakAuthenticator?: 'warn' | 'block'\n}\n\n/**\n * Policy applied to one named gate. `enabled: false` disables the\n * action entirely (useful in managed-passphrase mode where rotation is\n * impossible by construction).\n */\nexport interface GatePolicy {\n /** Minimum tier the active session must hold. */\n readonly minTier: 1 | 2 | 3\n /** Extra freshness-bound proofs required at gate time. */\n readonly factors?: ReadonlyArray<FactorRequirement>\n readonly warn?: WarningRules\n readonly enabled?: boolean\n}\n\n/**\n * Built-in gate names. App-defined gates live in the `app:*` namespace\n * and use the same engine; the engine treats unknown names with no\n * configured policy as \"no gate\" (no-op).\n */\nexport type BuiltInGateName =\n | 'rotate-passphrase'\n | 'recover-passphrase'\n | 'enroll-authenticator'\n | 'remove-authenticator'\n /**\n * Authorize a deliberate paper-recovery-code regeneration —\n * `db.rotateRecovery`. Symmetric to `rotate-passphrase` for\n * the case where the user remembers their passphrase but wants a\n * fresh sheet (lost the printout, suspect compromise of the off-site\n * copy). PERSONAL allows tier-1; STRICT requires an off-device\n * factor so a stolen unlocked laptop cannot silently mint a new\n * sheet for an attacker.\n */\n | 'rotate-recovery'\n /**\n * Authorize a meta-only mutation on an existing authenticator slot —\n * `db.updateAuthenticator`. The slot's wrap material, id, and\n * method are immutable through this gate; only the `meta` blob\n * (nicknames, method-specific labels) can change. Anti-slot-swap\n * guard is preserved structurally regardless of this gate's\n * settings.\n */\n | 'update-authenticator'\n | 'rotate-unlock'\n | 'enroll-user'\n | 'revoke-user'\n | 'export-bundle'\n | 'export-plaintext'\n | 'view-user-auth'\n /** Authorize a write to one's own user envelope. */\n | 'edit-own-profile'\n /** Authorize reading other principals' user envelopes. */\n | 'view-team-profiles'\n /**\n * Authorize an atomic peer-recovery — `db.recoverUser`.\n * Distinct from `revoke-user` because peer-recovery is intentional\n * re-issuance of someone's keyring under a temp passphrase, NOT\n * removal. Allows owner→owner natively (matches the threat model:\n * a co-owner explicitly recovering another co-owner). Ships with a\n * factor-proof default in `STRICT_POLICY` so the issuer must\n * affirmatively prove identity at the moment of recovery.\n */\n | 'peer-recover-user'\n /**\n * Authorize a post-grant identity mutation — `db.updateUser`.\n * Covers `role`, `displayName`, `permissions` changes on an existing\n * keyring. Pure plaintext-header rewrite — no DEKs touched, no KEK\n * required. The role-elevation guard inside the implementation\n * mirrors `db.grant`'s hierarchy (admin cannot promote to owner)\n * regardless of this gate's settings.\n */\n | 'update-user'\n /**\n * Authorize a non-owner's self-service **destructive** withdrawal —\n * `vault.user.unilateralWithdrawal`. The actor exports their\n * own re-keyed copy and then removes (delete-closure) or freezes the\n * source records. Because it both egresses data AND destroys the\n * firm's live copy, it MUST fail closed: undefined in a policy = denied.\n * Hosts opt in explicitly (and typically pin `minTier`/factor proofs).\n */\n | 'client-unilateral-withdraw'\n /**\n * Authorize FILING a two-party withdrawal request —\n * `vault.user.requestWithdrawal`. Non-destructive (writes a\n * pending request only); enabled by default so a read-only client can ask.\n */\n | 'user-request-withdrawal'\n /**\n * Authorize DECIDING a two-party withdrawal request (approve/reject) —\n * `vault.user.approveWithdrawal` / `rejectWithdrawal`. The approve\n * path is destructive (extract-and-dispose under firm authority), so it\n * defaults to a tier-2 floor; owner/admin role is enforced structurally.\n */\n | 'approve-user-withdrawal'\n /**\n * Authorize minting a **custodian** — `db.grantCustodian` (FR-6). The\n * custodian is the de-facto operational authority on a sealed-owner (Deed)\n * vault, so granting one is an ownership-level act: this gate MUST fail\n * closed (undefined in a policy = denied) and owner-only role is enforced\n * structurally. Hosts opt in explicitly, typically pinning factor proofs.\n */\n | 'grant-custodian'\n /**\n * Authorize the audited **Liberate** ceremony — `vault.custody.liberate`\n * (FR-6). The custodian (holding the live DEKs) claims ownership of a\n * sealed-owner vault under a recorded legal basis, minting a NEW owner\n * keyring. Destructive-of-the-old-ownership and irreversible, so it MUST\n * fail closed (undefined = denied); the caller-is-custodian check is\n * enforced structurally in the ceremony.\n */\n | 'liberate-vault'\n\n/** Either a built-in gate name or an `app:*` custom gate. */\nexport type GateName = BuiltInGateName | `app:${string}`\n\n/**\n * Top-level policy object. Persisted at `_meta/policy` once at vault\n * creation. The `passphrase` block configures the strength rules\n * applied at every passphrase ingress; `gates` configures\n * the action-level requirements.\n */\nexport interface VaultPolicy {\n readonly passphrase?: PassphrasePolicy\n readonly gates: Partial<Record<GateName, GatePolicy>>\n}\n\n/** Concrete proof an actor presents to {@link checkGate}. */\nexport interface FactorProof {\n readonly kind: FactorKind\n /** ISO-8601 timestamp the proof was minted at. Compared against `freshnessMs`. */\n readonly mintedAt?: string\n /** Method-specific payload. The engine treats it as opaque — verification is delegated. */\n readonly payload?: unknown\n}\n\n/**\n * Bundle of factor proofs + session-context flags passed to a gated\n * Noydb method. Used as the optional last parameter of every method\n * that runs through `checkGate`: `db.grant`, `db.revoke`, `db.updateUser`,\n * `db.enrollAuthenticator`, `db.removeAuthenticator`, `db.updateAuthenticator`,\n * `db.enrollWebAuthn`, `db.rotatePassphrase`, `db.recoverPassphrase`,\n * `db.recoverUser`, `db.enrollUnlock`, `db.describeUserAuth`,\n * `db.describeAllUsersAuth`.\n *\n * Previously this type was inlined at every call site as\n * `{ factors?: ReadonlyArray<FactorProof>; sharedDevice?: boolean }`\n * and parameter names alternated between `factors` and `presented`.\n * Now exported so consumers can name their helpers and so the param\n * name converges to `factors` everywhere.\n */\nexport interface FactorProofBundle {\n readonly factors?: ReadonlyArray<FactorProof>\n readonly sharedDevice?: boolean\n}\n\n/** Active session tier — what the engine compares against `gate.minTier`. */\nexport type ActiveTier = 1 | 2 | 3\n\n/**\n * Caller-supplied context for the policy engine's `checkGate`/`describeGate`.\n * Structural mirror of `with-party/policy/engine.ts`'s `CheckGateContext` —\n * duplicated here (rather than imported) because the kernel spine may not\n * statically import a with-* service; see {@link PolicyCheckGateFn}.\n */\nexport interface PolicyCheckGateContext {\n /** Tier the active session currently holds. */\n readonly activeTier: ActiveTier\n /** Proofs the actor is presenting for this gate. */\n readonly factors?: ReadonlyArray<FactorProof>\n /**\n * If the host knows the actor is on a shared device, set this to\n * `true` so the engine can apply `warn.sharedDevice` rules. Defaults\n * to `false`.\n */\n readonly sharedDevice?: boolean\n /**\n * Override `now()` for tests. Defaults to `Date.now()`.\n * @internal\n */\n readonly now?: number\n}\n\n/**\n * Structural type of the policy engine's `checkGate` function. The real\n * implementation lives at `with-party/policy/engine.ts#checkGate`;\n * `createNoydb()` pre-resolves it via a dynamic import (mirrors\n * {@link UserApiFactory}) so `Noydb.checkGate` can call it without the\n * spine statically importing the service.\n */\nexport type PolicyCheckGateFn = (\n policy: VaultPolicy,\n gate: GateName,\n context: PolicyCheckGateContext,\n) => Promise<void>\n\n/**\n * Public `NoydbPolicy` surface — the CONTRACT. The implementation\n * (`NoydbPolicy` class) lives at `with-party/policy/noydb-facade.ts`;\n * `createNoydb()` wires it in via the pre-resolved {@link NoydbPolicyFactory}.\n */\nexport interface NoydbPolicyApi {\n /**\n * Touch the policy enforcer for a vault (records activity, resets\n * idle timer). Also touches the legacy session timer. No-op if no enforcer.\n */\n touchPolicy(vault?: string): void\n /**\n * Check that a policy-guarded operation is permitted.\n * Throws `SessionPolicyError` if re-auth is required.\n */\n checkPolicyOperation(vault: string, op: ReAuthOperation): void\n /**\n * Read the active policy for a vault. Loads from `_meta/policy` on\n * first call; subsequent calls hit the in-memory cache. Throws\n * `ValidationError` if the vault has not been opened.\n */\n getPolicy(vault: string): Promise<VaultPolicy>\n /**\n * Replace the policy document at `_meta/policy` and update the\n * in-memory cache. Gated by the `enroll-user` policy (a policy\n * change is fundamentally a privilege-management action).\n */\n updatePolicy(vault: string, override: Partial<VaultPolicy>): Promise<VaultPolicy>\n /** Read or persist the vault policy at `_meta/policy` on first open. */\n bootstrapPolicy(vault: string, opts?: { skipManagedCheck?: boolean }): Promise<void>\n}\n\n/**\n * Constructor dependencies for `NoydbPolicy` (the {@link NoydbPolicyApi}\n * implementation). Everything the policy/session-policy methods touch on\n * the owning `Noydb` instance's `this.*`.\n *\n * The `policyEnforcers` map is typed structurally (rather than importing\n * `PolicyEnforcer` from `with-party/session/session-policy.ts`) so this\n * spine-resident interface never needs a with-* import; the real\n * `PolicyEnforcer` class satisfies this shape.\n */\nexport interface NoydbPolicyDeps {\n /** In-memory vault-policy cache (Noydb-resident; read/written by reference). */\n readonly policyCache: Map<string, VaultPolicy>\n /** Per-vault session-policy enforcers (Noydb-resident; read/written by reference). */\n readonly policyEnforcers: Map<string, { touch(): void; destroy(): void; checkOperation(op: ReAuthOperation): void }>\n /** The ciphertext store. */\n readonly store: NoydbStore\n /** Whether records are encrypted (`options.encrypt !== false`). */\n readonly encrypted: boolean\n /** The configured session policy, or undefined. */\n readonly sessionPolicy: SessionPolicy | undefined\n /** The developer-supplied default policy, or undefined. */\n readonly policyOption: VaultPolicy | undefined\n /** Whether the owning instance has been closed. */\n isClosed(): boolean\n /** Reset the kernel-resident idle/session timer. */\n resetSessionTimer(): void\n /** Managed-recovery enrolment check (kernel-resident; called on bootstrap). */\n assertRecoveryEnrolled(\n vault: string,\n policy: VaultPolicy,\n opts?: { skipManagedCheck?: boolean },\n ): Promise<void>\n /** Evict the keyring + vault caches when a session is revoked. */\n onSessionRevoke(vault: string): void\n}\n\n/**\n * Factory that builds the `NoydbPolicy` service implementation from its\n * dependencies. `createNoydb()` pre-resolves the real implementation\n * (`with-party/policy/noydb-facade.js#createNoydbPolicy`) via a dynamic\n * import before constructing `Noydb`, so the constructor can call it\n * synchronously — mirrors {@link UserApiFactory}.\n */\nexport type NoydbPolicyFactory = (deps: NoydbPolicyDeps) => NoydbPolicyApi\n"],"mappings":";AAqEO,IAAM,uBAAuB;AAG7B,IAAM,wBAAwB;AAG9B,IAAM,uBAAuB;AAG7B,IAAM,qBAAqB;AAyR3B,IAAM,eAAN,MAA2C;AAAA,EACvC,SAAS;AAAA,EACT;AAAA,EAET,YAAY,QAA0B;AACpC,SAAK,UAAU;AAAA,EACjB;AAAA,EAEA,SAAqB;AACnB,WAAO,KAAK,QAAQ;AAAA,EACtB;AAAA;AAAA,EAGA,SAAiB;AACf,WAAO;AAAA,EACT;AACF;AAsVO,SAAS,YACd,SACmC;AACnC,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/with-party/team/magic-link-grant.ts","../src/with-party/team/rotate-recover.ts","../src/with-party/team/peer-recover.ts","../src/with-party/team/authenticators.ts"],"sourcesContent":["/**\n * Magic-link-bound cross-user delegation grants.\n *\n * This module is the **core storage + encryption layer** that lets a\n * grantor issue a tier-DEK to a user whose KEK they do not know. The\n * trust bridge is provided by the `@noy-db/on-magic-link` package:\n *\n * 1. Grantor picks a grantee identity (user id + email handle).\n * 2. Grantor mints a magic-link token (ULID) via `createMagicLinkToken`.\n * 3. Grantor derives a **content key** + a **KEK** from\n * `(serverSecret, token, vault)` using HKDF-SHA256 with separate\n * `info` tags — both callers (grantor and grantee) can derive the\n * same keys given the same inputs.\n * 4. Grantor persists a record in `_magic_link_grants/<token>`:\n * - envelope `_data` is AES-GCM encrypted under the content key\n * - the inner `wrappedDek` is AES-KW wrapped under the KEK\n * 5. Grantee receives the URL, derives the same content key + KEK,\n * loads the grant, decrypts the envelope, unwraps the tier DEK.\n *\n * ## Why a separate collection from `_delegations`\n *\n * `_delegations` envelopes are encrypted under a DEK shared across\n * every vault user (audit-visibility). External auditors / client\n * portal users have NO pre-existing keyring, so they cannot read that\n * DEK. Magic-link grants live in their own collection whose envelope\n * encryption is derived purely from the magic-link URL + server secret\n * — nothing else is required to decrypt.\n *\n * ## Batch grants\n *\n * One magic-link token may point to MULTIPLE grants (e.g. the client\n * portal case: invoices + payments + etax all share one link). Each\n * grant is persisted under a distinct record id:\n *\n * `<token>` for the single-grant / primary entry\n * `<token>:<index>` for subsequent entries\n *\n * `listMagicLinkGrants(store, vault, token)` enumerates every record\n * whose id begins with `<token>` so the claimant can materialize all\n * DEKs in one pass.\n *\n * ## Revocation\n *\n * `store.delete(vault, _magic_link_grants, <token>)` immediately\n * invalidates the link — even if the URL was captured and the server\n * secret leaked, no payload remains to decrypt.\n *\n * @module\n */\n\nimport type { NoydbStore, EncryptedEnvelope } from '../../kernel/types.js'\nimport type { UnlockedKeyring } from './keyring.js'\nimport { encrypt, openEnvelopeJson, wrapKey, unwrapKey, type EnclaveKey } from '../../kernel/enclave/index.js'\nimport { dekKey } from './tiers.js'\nimport { DelegationTargetMissingError } from '../../kernel/errors.js'\n\n/** Reserved collection holding magic-link grant envelopes. */\nexport const MAGIC_LINK_GRANTS_COLLECTION = '_magic_link_grants'\n\n/** HKDF `info` for the AES-GCM content key. Version-namespaced. */\nexport const MAGIC_LINK_CONTENT_INFO_PREFIX = 'noydb-magic-link-content-v1:'\n\n/** HKDF `info` for the AES-KW KEK. Matches `@noy-db/on-magic-link`. */\nexport const MAGIC_LINK_KEK_INFO_PREFIX = 'noydb-magic-link-v1:'\n\n// ─── Types ──────────────────────────────────────────────────────────────\n\n/**\n * Decrypted payload of a magic-link grant record. Mirrors\n * `DelegationToken` in `team/delegation.ts` but tracked separately\n * because the two flows persist under different collections + envelope\n * encryption schemes.\n */\nexport interface MagicLinkGrantPayload {\n readonly id: string\n readonly toUser: string\n readonly fromUser: string\n readonly tier: number\n /** Collection name or `null` for the vault-wide tier DEK. */\n readonly collection: string | null\n /** Optional specific record id scope. */\n readonly record?: string\n /** ISO timestamp — grant expires at this instant. */\n readonly until: string\n /** AES-KW-wrapped tier DEK, unwrap with the magic-link KEK. */\n readonly wrappedDek: string\n /** ISO timestamp the grant was issued. */\n readonly createdAt: string\n /** Optional caller-provided label (surfaced in audit UIs). */\n readonly note?: string\n}\n\nexport interface IssueMagicLinkGrantOptions {\n readonly toUser: string\n readonly tier: number\n readonly collection?: string\n readonly record?: string\n readonly until: Date | string\n readonly note?: string\n}\n\nexport interface MagicLinkGrantRecord {\n /** Store record id — `<token>` or `<token>:<index>` for batch entries. */\n readonly recordId: string\n readonly payload: MagicLinkGrantPayload\n}\n\n// ─── Key derivation ─────────────────────────────────────────────────────\n\n/**\n * Derive the AES-GCM content key from the same HKDF inputs used for\n * the magic-link KEK. Different `info` suffix → domain-separated key.\n *\n * Exported so the `@noy-db/on-magic-link` package can share the exact\n * derivation path without cross-dependency between the two modules.\n */\nexport async function deriveMagicLinkContentKey(\n serverSecret: string | Uint8Array<ArrayBuffer>,\n token: string,\n vault: string,\n): Promise<EnclaveKey> {\n const subtle = globalThis.crypto.subtle\n const ikmBytes =\n serverSecret instanceof Uint8Array\n ? serverSecret\n : new TextEncoder().encode(serverSecret)\n const tokenBytes = new TextEncoder().encode(token)\n const saltBuffer = await subtle.digest('SHA-256', tokenBytes)\n const info = new TextEncoder().encode(MAGIC_LINK_CONTENT_INFO_PREFIX + vault)\n const ikm = await subtle.importKey('raw', ikmBytes, 'HKDF', false, ['deriveKey'])\n return subtle.deriveKey(\n { name: 'HKDF', hash: 'SHA-256', salt: saltBuffer, info },\n ikm,\n { name: 'AES-GCM', length: 256 },\n false,\n ['encrypt', 'decrypt'],\n )\n}\n\n// ─── Issue ──────────────────────────────────────────────────────────────\n\n/**\n * Persist a magic-link grant record. Caller derives + provides both\n * the content key and the KEK; this function performs the wrap/encrypt\n * and writes the envelope.\n *\n * `recordId` lets the caller use either the bare token (primary grant)\n * or a suffixed id (batch entry). The writer is responsible for\n * collision-avoidance across batch entries.\n */\nexport async function writeMagicLinkGrant(\n store: NoydbStore,\n vault: string,\n grantor: UnlockedKeyring,\n contentKey: EnclaveKey,\n grantKek: EnclaveKey,\n recordId: string,\n opts: IssueMagicLinkGrantOptions,\n): Promise<MagicLinkGrantRecord> {\n const collectionName = opts.collection ?? null\n const sourceKey = collectionName\n ? dekKey(collectionName, opts.tier)\n : `__any#${opts.tier}`\n const sourceDek = grantor.deks.get(sourceKey)\n if (!sourceDek) {\n throw new DelegationTargetMissingError(\n `grantor cannot find tier ${opts.tier} DEK for ${collectionName ?? '(any)'}`,\n )\n }\n const wrappedDek = await wrapKey(sourceDek, grantKek)\n\n const until = typeof opts.until === 'string' ? opts.until : opts.until.toISOString()\n const createdAt = new Date().toISOString()\n const payload: MagicLinkGrantPayload = {\n id: recordId,\n toUser: opts.toUser,\n fromUser: grantor.userId,\n tier: opts.tier,\n collection: collectionName,\n ...(opts.record && { record: opts.record }),\n until,\n wrappedDek,\n createdAt,\n ...(opts.note && { note: opts.note }),\n }\n\n const { iv, data } = await encrypt(JSON.stringify(payload), contentKey)\n const envelope: EncryptedEnvelope = {\n _noydb: 1,\n _v: 1,\n _ts: createdAt,\n _iv: iv,\n _data: data,\n _by: grantor.userId,\n }\n await store.put(vault, MAGIC_LINK_GRANTS_COLLECTION, recordId, envelope)\n return { recordId, payload }\n}\n\n// ─── Claim ──────────────────────────────────────────────────────────────\n\n/**\n * Fetch + decrypt a single magic-link grant record by id. Returns null\n * when the record is absent OR when decryption fails (wrong server\n * secret, wrong vault, tampered envelope) — callers treat a null as\n * \"this URL is not valid for this server\".\n *\n * The returned payload's `wrappedDek` is still AES-KW-wrapped; the\n * caller unwraps it with the magic-link KEK to obtain the tier DEK.\n */\nexport async function readMagicLinkGrantRecord(\n store: NoydbStore,\n vault: string,\n contentKey: EnclaveKey,\n recordId: string,\n): Promise<MagicLinkGrantPayload | null> {\n const env = await store.get(vault, MAGIC_LINK_GRANTS_COLLECTION, recordId)\n if (!env) return null\n try {\n const json = await openEnvelopeJson(env, contentKey)\n return JSON.parse(json) as MagicLinkGrantPayload\n } catch {\n return null\n }\n}\n\n/**\n * Enumerate every grant record sharing the magic-link `token` prefix\n * (i.e. the primary `<token>` entry plus any `<token>:*` batch entries).\n * Expired grants are still returned — the caller filters on `until`.\n */\nexport async function listMagicLinkGrants(\n store: NoydbStore,\n vault: string,\n contentKey: EnclaveKey,\n token: string,\n): Promise<MagicLinkGrantPayload[]> {\n const ids = await store.list(vault, MAGIC_LINK_GRANTS_COLLECTION)\n const matching = ids.filter(id => id === token || id.startsWith(`${token}:`))\n const out: MagicLinkGrantPayload[] = []\n for (const id of matching) {\n const payload = await readMagicLinkGrantRecord(store, vault, contentKey, id)\n if (payload) out.push(payload)\n }\n return out\n}\n\n/**\n * Unwrap the tier DEK from a grant payload using the magic-link KEK.\n * Thin wrapper around `unwrapKey` — provided so the claimant can avoid\n * importing `crypto.js` directly.\n */\nexport async function unwrapMagicLinkGrant(\n payload: MagicLinkGrantPayload,\n grantKek: EnclaveKey,\n): Promise<EnclaveKey> {\n return unwrapKey(payload.wrappedDek, grantKek)\n}\n\n/**\n * Delete a magic-link grant (primary + every batch entry sharing the\n * token). Safe to call when nothing exists.\n */\nexport async function revokeMagicLinkGrant(\n store: NoydbStore,\n vault: string,\n token: string,\n): Promise<number> {\n const ids = await store.list(vault, MAGIC_LINK_GRANTS_COLLECTION)\n const matching = ids.filter(id => id === token || id.startsWith(`${token}:`))\n for (const id of matching) {\n await store.delete(vault, MAGIC_LINK_GRANTS_COLLECTION, id)\n }\n return matching.length\n}\n\n// ─── Helpers ────────────────────────────────────────────────────────────\n\n/**\n * Compose the batch-entry record id. `index === 0` → bare token.\n * Subsequent entries use `<token>:<index>` so `store.list()` can\n * enumerate them all by common prefix.\n */\nexport function magicLinkGrantRecordId(token: string, index: number): string {\n return index === 0 ? token : `${token}:${index}`\n}\n\n/**\n * True when the payload's `until` is in the past relative to `now`.\n * Kept here (rather than inlined) so the semantics stay aligned with\n * the canonical `DelegationToken` expiry check.\n */\nexport function isMagicLinkGrantExpired(\n payload: MagicLinkGrantPayload,\n now: Date = new Date(),\n): boolean {\n return payload.until <= now.toISOString()\n}\n","/**\n * Tier-1 change flows — `rotatePassphrase` (user remembers old) and\n * `recoverPassphrase` (user supplies a recovery proof).\n *\n * The two flows share the post-verification half — fresh salt, fresh\n * KEK, rewrap every DEK — and differ only in how they re-derive the\n * old KEK:\n *\n * - **Rotate**: derive from the supplied `oldPassphrase`.\n * - **Recover (paper)**: unwrap from a `RecoveryCodeEntry` using a\n * user-supplied recovery code. The entry is burned on success.\n *\n * The non-paper recovery profiles (Shamir, multi-channel,\n * admin-mediated) are not yet wired — calling them throws\n * {@link RecoveryProfileNotImplementedError} with a tracking link.\n *\n * @module\n */\nimport type { NoydbStore, KeyringFile } from '../../kernel/types.js'\nimport { NOYDB_KEYRING_VERSION } from '../../kernel/types.js'\nimport {\n deriveKey,\n generateSalt,\n wrapKey,\n unwrapKey,\n bufferToBase64,\n base64ToBuffer,\n type EnclaveKey,\n} from '../../kernel/enclave/index.js'\nimport { InvalidKeyError, NoAccessError, RecoveryProfileNotImplementedError } from '../../kernel/errors.js'\nimport {\n loadPaperRecoveryEntries,\n burnPaperRecoveryEntry,\n unwrapDeksFromPaperEntry,\n loadShamirRecoveryEntries,\n unwrapDeksFromShamirEntry,\n type PaperRecoveryEntry,\n type ShamirRecoveryEntry,\n} from './recovery.js'\nimport type { ShamirRecoveryProvider } from './shamir-recovery-provider.js'\nimport { assertStrongPassphrase, type PassphrasePolicy } from '../../kernel/validation.js'\nimport type { UnlockedKeyring } from './keyring.js'\nimport { mintKeyringCanary } from './keyring.js'\nimport type { KeyringAuthenticator } from '../../kernel/types.js'\nimport type { EnrollAuthenticatorOptions } from './authenticators.js'\nimport { ValidationError } from '../../kernel/errors.js'\n\n/**\n * Context handed to a {@link SlotRewrapCeremony} when `rotatePassphrase`\n * preserves a tier-2 slot. The ceremony's job is to re-derive its\n * method-specific wrapping material (PRF assertion, PBKDF2 of the\n * password, etc.) and wrap the freshly rewrapped DEK set under\n * the new wrapping key.\n *\n * Two surfaces are exposed:\n *\n * - `newDeks` — the rewrapped (extractable) DEK set the slot will\n * wrap. This is what `mintPaperRecoveryEntry` / `enrollPassword-\n * Authenticator` / `wrapKeyringSummary` (in `@noy-db/on-webauthn`)\n * all consume; effectively the canonical input for every\n * post-Path C tier-2 ceremony.\n *\n * - `newKek` — the freshly-derived KEK (extractable for the\n * ceremony scope only). Only relevant for forward-compatibility\n * with a hypothetical future on-* package that wants to wrap the\n * KEK itself under a method-derived key. None of the shipped\n * on-* packages need this; they all operate on `newDeks`.\n *\n * The ceremony MUST preserve `oldSlot.id` and `oldSlot.method` in the\n * returned `EnrollAuthenticatorOptions`. Hub validates these — a\n * mismatch throws `ValidationError` (prevents slot-type swap mid-\n * rotation, e.g. converting a webauthn slot to a password slot under\n * cover of preservation).\n */\nexport interface SlotRewrapContext {\n readonly newKek: EnclaveKey\n readonly newDeks: Map<string, EnclaveKey>\n readonly oldSlot: KeyringAuthenticator\n}\n\n/**\n * Callback that re-enrolls one tier-2 slot during `rotatePassphrase`.\n * Returns the new slot's `EnrollAuthenticatorOptions` — same shape\n * the consumer would pass to `db.enrollAuthenticator` for a fresh\n * enrollment. Hub persists the result atomically with the rotation.\n */\nexport type SlotRewrapCeremony = (\n ctx: SlotRewrapContext,\n) => Promise<EnrollAuthenticatorOptions>\n\n/** Caller payload for {@link rotatePassphrase}. */\nexport interface RotatePassphraseInput {\n readonly oldPassphrase: string\n readonly newPassphrase: string\n readonly passphrasePolicy?: PassphrasePolicy\n readonly allowWeakPassphrase?: boolean\n /**\n * Map of slot id → re-enrolment ceremony. Slots whose id appears\n * here are PRESERVED across rotation (the ceremony re-derives the\n * method-specific wrapping under the new keyring); slots whose id\n * is absent are DROPPED (the pre-slot-ceremony behavior).\n *\n * Without this map, `rotatePassphrase` wipes every tier-2 slot. Consumers building a\n * \"rotate without losing my biometric\" flow supply ceremonies for\n * each slot they want to keep.\n *\n * If a ceremony throws, the entire rotation throws — no partial\n * state. Callers wrap individual ceremonies in try/catch + return\n * a sentinel if they want graceful degradation per slot.\n *\n * Added when slot-ceremony rewrapping landed.\n */\n readonly slotCeremonies?: { readonly [slotId: string]: SlotRewrapCeremony }\n}\n\n/**\n * Re-derive the user's KEK from `oldPassphrase`, rewrap every DEK\n * under a freshly-derived KEK from `newPassphrase`, and persist.\n *\n * Tier-2 authenticator slots are dropped UNLESS the caller supplies\n * a `slotCeremonies` map — each ceremony re-derives its\n * method-specific wrapping under the new keyring, and hub persists\n * the rewrapped slots atomically with the rotation. Slots whose id\n * isn't in the map are still dropped.\n *\n * @throws `InvalidKeyError` if `oldPassphrase` does not unwrap the keyring.\n * @throws `WeakPassphraseError` if `newPassphrase` fails the strength rule.\n * @throws `ValidationError` if a ceremony's result mismatches the\n * slot's id or method (anti-slot-swap guard).\n */\nexport async function rotatePassphrase(\n store: NoydbStore,\n vault: string,\n userId: string,\n input: RotatePassphraseInput,\n): Promise<UnlockedKeyring> {\n if (!input.allowWeakPassphrase) {\n assertStrongPassphrase(input.newPassphrase, input.passphrasePolicy)\n }\n\n const env = await store.get(vault, '_keyring', userId)\n if (!env) {\n throw new NoAccessError(`No keyring found for user \"${userId}\" in vault \"${vault}\".`)\n }\n const file = JSON.parse(env._data) as KeyringFile\n const oldSalt = base64ToBuffer(file.salt)\n const oldKek = await deriveKey(input.oldPassphrase, oldSalt)\n\n // Unwrap every DEK with the OLD KEK first — this also validates the\n // passphrase (a bad KEK throws InvalidKeyError on the first unwrap).\n const deks = new Map<string, EnclaveKey>()\n for (const [coll, wrapped] of Object.entries(file.deks)) {\n deks.set(coll, await unwrapKey(wrapped, oldKek))\n }\n\n const newSalt = generateSalt()\n const newKek = await deriveKey(input.newPassphrase, newSalt)\n\n // Rewrap with the new KEK.\n const wrappedDeks: Record<string, string> = {}\n for (const [coll, dek] of deks) {\n wrappedDeks[coll] = await wrapKey(dek, newKek)\n }\n\n // Slot rewrap. Without slotCeremonies, we drop every existing\n // slot. With a ceremony map, slots whose id appears in the map\n // are preserved; the rest are dropped.\n const oldSlots = file.authenticators ?? []\n const newSlots: KeyringAuthenticator[] = []\n if (input.slotCeremonies && oldSlots.length > 0) {\n for (const oldSlot of oldSlots) {\n const ceremony = input.slotCeremonies[oldSlot.id]\n if (!ceremony) continue // drop — not in slotCeremonies map\n\n const result = await ceremony({ newKek, newDeks: deks, oldSlot })\n\n // Anti-slot-swap guard. The ceremony MUST preserve identity —\n // a mismatch would let the consumer convert a webauthn slot to\n // a password slot mid-rotation, which would silently change\n // the security profile of the slot under cover of \"rotation.\"\n if (result.id !== oldSlot.id) {\n throw new ValidationError(\n `slotCeremonies['${oldSlot.id}'] returned id=\"${result.id}\". ` +\n 'The id must match the rotated slot — a ceremony cannot ' +\n 'change a slot\\'s identity.',\n )\n }\n if (result.method !== oldSlot.method) {\n throw new ValidationError(\n `slotCeremonies['${oldSlot.id}'] returned method=\"${result.method}\", ` +\n `expected \"${oldSlot.method}\". The method must match the rotated ` +\n 'slot — a ceremony cannot change the auth method (e.g. webauthn ' +\n '→ password) under cover of rotation.',\n )\n }\n // wrapKind absent on legacy slots / wrap-KEK enroll inputs; treat as 'kek'.\n const oldWrapKind = oldSlot.wrapKind ?? 'kek'\n const newWrapKind = result.wrapKind ?? 'kek'\n if (oldWrapKind !== newWrapKind) {\n throw new ValidationError(\n `slotCeremonies['${oldSlot.id}'] returned wrapKind=\"${newWrapKind}\", ` +\n `expected \"${oldWrapKind}\". The wrap format must match the rotated ` +\n 'slot — a ceremony cannot change the wrap shape (e.g. wrap-KEK → ' +\n 'wrap-DEKs) under cover of rotation, since that would silently ' +\n 'change the session tier produced at unlock.',\n )\n }\n\n // Build the persisted slot from the ceremony result. Mirrors\n // the same construction `enrollAuthenticator` does — wrap-DEKs\n // variants carry { wrapped_deks, iv }; wrap-KEK variants\n // carry { wrapped_kek }.\n const baseFields = {\n id: result.id,\n method: result.method,\n // Preserve original enrolled_at — rotation is rewrapping, not\n // re-enrollment. The slot's enrolment timestamp tracks when\n // the user originally added the slot, not when it was last\n // rewrapped. Forensics consumers reading enrolled_at are\n // tracking the slot's ORIGIN, not its CURRENT wrapping.\n enrolled_at: oldSlot.enrolled_at,\n enrolled_via_tier: result.enrolled_via_tier ?? oldSlot.enrolled_via_tier,\n meta: result.meta,\n } as const\n const newSlot: KeyringAuthenticator = result.wrapKind === 'deks'\n ? {\n ...baseFields,\n wrapKind: 'deks',\n wrapped_deks: result.wrapped_deks,\n iv: result.iv,\n }\n : {\n ...baseFields,\n wrapped_kek: result.wrapped_kek,\n }\n newSlots.push(newSlot)\n }\n }\n\n const canary = await mintKeyringCanary(newKek)\n const next: KeyringFile = {\n ...file,\n _noydb_keyring: NOYDB_KEYRING_VERSION,\n deks: wrappedDeks,\n salt: bufferToBase64(newSalt),\n authenticators: newSlots,\n canary,\n }\n\n await writeKeyringFile(store, vault, userId, next)\n\n return {\n userId: file.user_id,\n displayName: file.display_name,\n role: file.role,\n permissions: file.permissions,\n deks,\n kek: newKek,\n salt: newSalt,\n authenticators: newSlots,\n ...(file.export_capability !== undefined && { exportCapability: file.export_capability }),\n ...(file.import_capability !== undefined && { importCapability: file.import_capability }),\n }\n}\n\n/**\n * Caller payload for {@link recoverPassphrase}.\n *\n * `paper` and `shamir` are wired end-to-end.\n * The remaining two profiles (`multi-channel`, `admin-mediated`)\n * stay outside the union and throw\n * {@link RecoveryProfileNotImplementedError} at the runtime guard\n * when bypassed via `as unknown as RecoveryProof`.\n */\nexport type RecoveryProof =\n | { readonly profile: 'paper'; readonly payload: { readonly code: string } }\n | { readonly profile: 'shamir'; readonly payload: {\n /** Optional disambiguator when multiple Shamir entries are enrolled.\n * When omitted, hub tries each entry until one combines. */\n readonly entryId?: string\n /** K or more opaque share strings, as returned by `ShamirRecoveryProvider.splitToShares`. */\n readonly shares: ReadonlyArray<string>\n } }\n\nexport interface RecoverPassphraseInput {\n readonly newPassphrase: string\n readonly recoveryProof: RecoveryProof\n readonly passphrasePolicy?: PassphrasePolicy\n readonly allowWeakPassphrase?: boolean\n /**\n * After a successful paper-recovery, replace ALL remaining recovery\n * entries with freshly-minted ones. Defaults to `true` (defensive).\n *\n * Rationale: the user just demonstrated they had access\n * to AT LEAST one code. The remaining codes from the same printed\n * sheet may also be compromised — photographed, leaked via a\n * screen-share slip, or in the hands of whoever stole the sheet.\n * Auto-rotation closes the window without requiring consumer action.\n *\n * Set to `false` to preserve the original behavior (only the matched\n * code is burned; the rest stay valid).\n *\n * Hub-side orchestration is non-atomic with the recovery itself:\n * if the rotation step fails after a successful burn, the user\n * falls back to the pre-rotation state (remaining codes still\n * valid). Strictly safer than the previous default — a failed\n * rotation degrades gracefully rather than leaving the vault\n * locked or codes dual-existing.\n */\n readonly rotateRemainingCodes?: boolean\n /**\n * Number of fresh codes to mint when `rotateRemainingCodes` is on.\n * Defaults to the count of remaining entries POST-burn (e.g. if\n * the user enrolled 8 originally and just consumed 1, defaults to\n * 7). Pass an explicit number to mint a different count — useful\n * when the consumer wants to refresh to a target N regardless of\n * how many were left.\n */\n readonly newCodeCount?: number\n /**\n * Override the default raw-code generator. The default is hub's\n * {@link generateULID} — uppercase Crockford-Base32, 26 chars,\n * passes through `normalizePaperCode` untouched.\n *\n * Pass `() => generateRawCode()` from `@noy-db/on-recovery` when\n * the consumer prefers the Base32 + checksum format with hyphenated\n * display. The `mintPaperRecoveryEntry` helper accepts any string —\n * the generator just needs to produce a high-entropy unique value.\n */\n readonly codeGenerator?: () => string\n}\n\n/**\n * Return shape of `db.recoverPassphrase`. `newCodes` is populated when\n * `rotateRemainingCodes` was enabled and at least one entry was\n * rotated; an empty array means no rotation happened (rotation\n * disabled, or no remaining codes after burn). Show the codes to the\n * user once — they are the canonical credential for future recovery\n * and CANNOT be retrieved again.\n */\nexport interface RecoverPassphraseResult {\n readonly newCodes: readonly string[]\n}\n\n/**\n * Input for {@link Noydb.rotateRecovery} — deliberate\n * recovery-credential regeneration when the user knows their\n * passphrase but wants a fresh sheet (paper) or fresh shares\n * (shamir). Symmetric to {@link RotatePassphraseInput}.\n */\nexport type RotateRecoveryOptions =\n | {\n readonly profile: 'paper'\n /** How many fresh codes to mint. Default: existing sheet size. */\n readonly count?: number\n /** Optional code generator — see {@link RecoverPassphraseInput.codeGenerator}. */\n readonly codeGenerator?: () => string\n }\n | {\n readonly profile: 'shamir'\n /** New threshold. */\n readonly k: number\n /** New total share count. */\n readonly n: number\n /** Disambiguator when multiple Shamir entries exist; required if there are 2+. */\n readonly entryId?: string\n /** Optional updated label. */\n readonly label?: string\n }\n\n/**\n * Result of {@link Noydb.rotateRecovery}. Shape varies by profile:\n *\n * - `paper` → `{ newCodes: string[] }` (and `entryId === 'paper-batch'`)\n * - `shamir` → `{ newShares: string[], entryId }`\n *\n * `newCodes` is populated for paper rotations; `newShares` for\n * Shamir rotations. Both are show-once — the hub does not\n * retain them.\n */\nexport interface RotateRecoveryResult {\n readonly newCodes?: readonly string[]\n readonly newShares?: readonly string[]\n readonly entryId?: string\n}\n\n/**\n * Result of {@link Noydb.enrollRecovery}. Shape varies by profile:\n *\n * - `paper` → `{ entryId: 'paper-batch' }` (caller minted the\n * entries; this is a sentinel since paper enrollments are batch-shaped).\n * - `shamir` → `{ entryId, shares: string[] }` — shares are\n * show-once; the hub does not retain them.\n */\nexport interface EnrollRecoveryResult {\n readonly entryId: string\n readonly shares?: readonly string[]\n}\n\n/**\n * Input shape for {@link Noydb.enrollRecovery} and\n * {@link Noydb.openVaultAndEnrollRecovery}. Discriminated\n * union over recovery profiles.\n *\n * - `paper`: caller pre-mints entries (typically via\n * `mintPaperRecoveryEntry` or `@noy-db/on-recovery`'s\n * `generateRecoveryCodeSet`) and passes them in. The hub stores\n * them and surfaces an opaque batch id.\n * - `shamir`: hub mints the recovery secret + the shares at\n * enrollment time. The shares are returned in\n * {@link EnrollRecoveryResult.shares} (show-once); the hub never\n * retains them.\n *\n * Multi-channel and admin-mediated will be added when the respective\n * dispatch slices ship.\n */\nexport type RecoveryEnrollmentInput =\n | { readonly profile: 'paper'; readonly entries: ReadonlyArray<PaperRecoveryEntry> }\n | {\n readonly profile: 'shamir'\n readonly k: number\n readonly n: number\n readonly label?: string\n readonly entryId?: string\n }\n\n/**\n * Reset the user's passphrase using a recovery proof.\n * Supports `'paper'` and `'shamir'` profiles. The other profiles throw\n * {@link RecoveryProfileNotImplementedError}.\n *\n * On success, the used recovery entry is burned (deleted from the\n * stored set).\n */\nexport async function recoverPassphrase(\n provider: ShamirRecoveryProvider | undefined,\n store: NoydbStore,\n vault: string,\n userId: string,\n input: RecoverPassphraseInput,\n): Promise<UnlockedKeyring> {\n if (!input.allowWeakPassphrase) {\n assertStrongPassphrase(input.newPassphrase, input.passphrasePolicy)\n }\n\n // Runtime defense-in-depth: the type narrows to 'paper' | 'shamir',\n // but a consumer bypassing TS via\n // `as unknown as RecoveryProof` should still hit a clear error\n // rather than silently fall into a handler with a malformed payload.\n const profile = (input.recoveryProof as { profile: string }).profile\n if (profile === 'paper') {\n return recoverViaPaperCode(store, vault, userId, input)\n }\n if (profile === 'shamir') {\n return recoverViaShamir(provider, store, vault, userId, input)\n }\n throw new RecoveryProfileNotImplementedError(\n profile,\n 'https://github.com/vLannaAi/noy-db/issues/196',\n )\n}\n\nasync function recoverViaPaperCode(\n store: NoydbStore,\n vault: string,\n userId: string,\n input: RecoverPassphraseInput,\n): Promise<UnlockedKeyring> {\n if (input.recoveryProof.profile !== 'paper') throw new Error('unreachable')\n const { code } = input.recoveryProof.payload\n\n const env = await store.get(vault, '_keyring', userId)\n if (!env) {\n throw new NoAccessError(`No keyring found for user \"${userId}\" in vault \"${vault}\".`)\n }\n const file = JSON.parse(env._data) as KeyringFile\n\n const entries = await loadPaperRecoveryEntries(store, vault)\n if (entries.length === 0) {\n throw new NoAccessError(\n `No paper-recovery entries enrolled for vault \"${vault}\". ` +\n 'Enroll via `db.enrollRecovery({ profile: \"paper\", entries })` before relying on recovery.',\n )\n }\n\n const normalized = normalizePaperCode(code)\n let recovered: { deks: Map<string, EnclaveKey>; entry: PaperRecoveryEntry } | undefined\n for (const entry of entries) {\n try {\n const deks = await unwrapDeksFromPaperEntry(entry, normalized)\n recovered = { deks, entry }\n break\n } catch {\n // wrong code for this entry — try the next one\n }\n }\n if (!recovered) {\n throw new InvalidKeyError(\n 'Recovery code does not match any enrolled paper entry. The code may have been ' +\n 'previously used (single-use) or typed incorrectly.',\n )\n }\n\n const deks = recovered.deks\n\n // Fresh salt + KEK from the new passphrase, rewrap.\n const newSalt = generateSalt()\n const newKek = await deriveKey(input.newPassphrase, newSalt)\n const wrappedDeks: Record<string, string> = {}\n for (const [coll, dek] of deks) {\n wrappedDeks[coll] = await wrapKey(dek, newKek)\n }\n\n const canary = await mintKeyringCanary(newKek)\n const next: KeyringFile = {\n ...file,\n _noydb_keyring: NOYDB_KEYRING_VERSION,\n deks: wrappedDeks,\n salt: bufferToBase64(newSalt),\n authenticators: [], // tier-2 slots wrap old KEK, drop them\n canary,\n }\n\n // Burn first, then rewrite the keyring. The two writes are not\n // atomic — if the second fails, the safer ordering is:\n //\n // 1. Code burned, keyring untouched: user keeps their old passphrase\n // and loses one recovery code (recoverable: contact admin / use\n // another code).\n //\n // 2. Keyring rewritten, code unburned: user has rotated, but the\n // consumed code REMAINS VALID. Anyone with access to the paper\n // sheet can use it again. Security regression.\n //\n // Burning first picks (1) over (2).\n await burnPaperRecoveryEntry(store, vault, recovered.entry.codeId)\n await writeKeyringFile(store, vault, userId, next)\n\n return {\n userId: file.user_id,\n displayName: file.display_name,\n role: file.role,\n permissions: file.permissions,\n deks,\n kek: newKek,\n salt: newSalt,\n authenticators: [],\n ...(file.export_capability !== undefined && { exportCapability: file.export_capability }),\n ...(file.import_capability !== undefined && { importCapability: file.import_capability }),\n }\n}\n\n/**\n * Mirror of `@noy-db/on-recovery/parseRecoveryCode`. Inlined so the\n * hub does not gain a peer dep on on-recovery — both implementations\n * follow the same RFC 4648 Base32 + checksum format and round-trip\n * through the same KDF.\n *\n * Accepts hyphenated, lowercase, or whitespace-padded input.\n */\nfunction normalizePaperCode(input: string): string {\n return input.toUpperCase().replace(/[\\s\\-_]/g, '')\n}\n\n/**\n * Recover the user's keyring via the Shamir profile.\n *\n * 1. Decode each supplied share string into a {@link RawShare}.\n * 2. Load `_meta/recovery-shamir` entries.\n * 3. If `payload.entryId` is supplied, restrict to that entry; else\n * iterate over all entries and try each until one combines.\n * 4. For each candidate: filter shares to those whose `(k, n)`\n * match the entry's parameters, then attempt\n * `unwrapDeksFromShamirEntry`. AES-GCM auth-tag failure means\n * the combined secret doesn't match — try the next entry.\n * 5. With unwrapped DEKs: derive fresh KEK from `newPassphrase` +\n * fresh salt, rewrap, write the keyring.\n * 6. Shamir entries are NOT burned on recovery (shares reusable);\n * explicit {@link Noydb.rotateRecovery} is the refresh ceremony.\n */\nasync function recoverViaShamir(\n provider: ShamirRecoveryProvider | undefined,\n store: NoydbStore,\n vault: string,\n userId: string,\n input: RecoverPassphraseInput,\n): Promise<UnlockedKeyring> {\n if (input.recoveryProof.profile !== 'shamir') throw new Error('unreachable')\n const { entryId: requestedEntryId, shares: shareStrings } = input.recoveryProof.payload\n\n if (shareStrings.length === 0) {\n throw new ValidationError(\n 'Shamir recovery requires at least one share; received an empty array.',\n )\n }\n\n const env = await store.get(vault, '_keyring', userId)\n if (!env) {\n throw new NoAccessError(`No keyring found for user \"${userId}\" in vault \"${vault}\".`)\n }\n const file = JSON.parse(env._data) as KeyringFile\n\n const allEntries = await loadShamirRecoveryEntries(store, vault)\n if (allEntries.length === 0) {\n throw new NoAccessError(\n `No Shamir-recovery entries enrolled for vault \"${vault}\". `\n + 'Enroll via `db.enrollRecovery({ profile: \"shamir\", k, n })` before relying on recovery.',\n )\n }\n\n if (!provider) {\n throw new Error(\n \"shamir recovery requires a ShamirRecoveryProvider — pass \"\n + \"shamirRecovery: shamirRecoveryProvider() from '@noy-db/on-shamir' to createNoydb()\",\n )\n }\n\n // Restrict to a specific entry when entryId supplied.\n let candidates: ReadonlyArray<ShamirRecoveryEntry>\n if (requestedEntryId !== undefined) {\n candidates = allEntries.filter(e => e.entryId === requestedEntryId)\n if (candidates.length === 0) {\n throw new NoAccessError(\n `No Shamir-recovery entry with entryId=\"${requestedEntryId}\" found `\n + `in vault \"${vault}\". Available entries: `\n + allEntries.map(e => `\"${e.entryId}\"`).join(', '),\n )\n }\n } else {\n candidates = allEntries\n }\n\n // Try each candidate entry. Pass all share strings to the provider;\n // provider.combineShares validates and throws on mismatch — the\n // AES-GCM auth-tag is an additional guard.\n let recoveredDeks: Map<string, EnclaveKey> | undefined\n for (const entry of candidates) {\n if (shareStrings.length < entry.k) {\n // Not enough shares for this entry — could still match another.\n continue\n }\n try {\n const deks = await unwrapDeksFromShamirEntry(provider, entry, shareStrings)\n recoveredDeks = deks\n break\n } catch {\n // provider.combineShares threw (malformed/mismatched shares) or\n // AES-GCM auth-tag failure → try the next entry.\n }\n }\n\n if (!recoveredDeks) {\n // Distinguish \"below-threshold\" from \"no entry matches\" so the\n // error message is actionable.\n const minK = Math.min(...candidates.map(e => e.k))\n if (shareStrings.length < minK) {\n throw new InvalidKeyError(\n `Insufficient Shamir shares to combine: the smallest enrolled threshold is ${minK}, `\n + `but only ${shareStrings.length} share${shareStrings.length === 1 ? ' was' : 's were'} provided.`,\n )\n }\n throw new InvalidKeyError(\n 'Shamir shares do not match any enrolled entry. Possible causes: '\n + 'shares were tampered with, came from a different enrollment, '\n + 'or the entry was rotated after these shares were distributed.',\n )\n }\n\n // Mint fresh KEK from new passphrase, rewrap DEKs (mirrors paper).\n const newSalt = generateSalt()\n const newKek = await deriveKey(input.newPassphrase, newSalt)\n const wrappedDeks: Record<string, string> = {}\n for (const [coll, dek] of recoveredDeks) {\n wrappedDeks[coll] = await wrapKey(dek, newKek)\n }\n\n const canary = await mintKeyringCanary(newKek)\n const next: KeyringFile = {\n ...file,\n _noydb_keyring: NOYDB_KEYRING_VERSION,\n deks: wrappedDeks,\n salt: bufferToBase64(newSalt),\n authenticators: [], // tier-2 slots wrap old KEK, drop them on recovery\n canary,\n }\n\n // No burn: Shamir entries persist across recoveries. Explicit\n // rotateRecovery is the refresh ceremony.\n await writeKeyringFile(store, vault, userId, next)\n\n return {\n userId: file.user_id,\n displayName: file.display_name,\n role: file.role,\n permissions: file.permissions,\n deks: recoveredDeks,\n kek: newKek,\n salt: newSalt,\n authenticators: [],\n ...(file.export_capability !== undefined && { exportCapability: file.export_capability }),\n ...(file.import_capability !== undefined && { importCapability: file.import_capability }),\n }\n}\n\nasync function writeKeyringFile(\n store: NoydbStore,\n vault: string,\n userId: string,\n file: KeyringFile,\n): Promise<void> {\n const envelope = {\n _noydb: 1 as const,\n _v: 1,\n _ts: new Date().toISOString(),\n _iv: '',\n _data: JSON.stringify(file),\n }\n await store.put(vault, '_keyring', userId, envelope)\n}\n","/**\n * Atomic peer-recovery primitive.\n *\n * `recoverUser` is a SEPARATE operation from `revoke + grant`. It\n * exists because peer-recovery has different semantics than account\n * removal-then-reissue:\n *\n * 1. **Same identity preserved.** `userId`, `role`, `permissions`,\n * capability bits, user envelope (if any), policy override (if\n * any) all survive. Only the wrapping changes.\n * 2. **No key rotation.** The existing DEKs stay valid — every\n * OTHER principal in the vault keeps their access. Rotating\n * keys would invalidate every co-user's wrapping.\n * 3. **Atomic by construction.** A single `store.put` overwrites\n * `_keyring/<userId>` with the recovered file. No revoke step\n * means no partial-failure window.\n * 4. **Owner→owner natively allowed.** Two co-owners recovering\n * each other is the explicitly-intentional case (a partner\n * forgot the master phrase). The existing `canRevoke` rule that\n * blocks owner→owner is correct for `revoke` (which is account\n * *removal*) and intentionally NOT replicated here. The policy\n * gate `peer-recover-user` carries the freshness requirement.\n * 5. **Tier-2 slots dropped.** The slots wrap the OLD KEK under\n * method-derived keys; after recovery the KEK is re-derived\n * from the new temp passphrase. Match `rotatePassphrase`'s\n * precedent — the recovered user re-enrols slots after picking\n * their own phrase.\n *\n * Caller must be at least as privileged as the target. The hub\n * `db.recoverUser` method gates this with the `peer-recover-user`\n * policy gate (the `peer-recover-user` factor-proof requirement); the function below\n * enforces only the role + anti-privilege-escalation invariants.\n *\n * @module\n */\nimport type { NoydbStore, KeyringFile, Role } from '../../kernel/types.js'\nimport { NOYDB_KEYRING_VERSION } from '../../kernel/types.js'\nimport { deriveKey, generateSalt, wrapKey, bufferToBase64 } from '../../kernel/enclave/index.js'\nimport { NoAccessError, PermissionDeniedError, PrivilegeEscalationError } from '../../kernel/errors.js'\nimport { assertStrongPassphrase, type PassphrasePolicy } from '../../kernel/validation.js'\nimport type { UnlockedKeyring } from './keyring.js'\nimport { mintKeyringCanary } from './keyring.js'\n\n// FR-6: 'custodian' is deliberately ABSENT — an admin cannot peer-recover a\n// custodian (mirrors ADMIN_GRANTABLE_TARGETS: custodians are owner-managed\n// only). The owner CAN recover one (canRecover returns true for owner). As a\n// CALLER, a custodian recovers nobody (it is neither owner nor admin → false).\nconst ADMIN_RECOVERABLE_TARGETS: readonly Role[] = ['operator', 'viewer', 'client', 'admin']\n\n/**\n * Whether `callerRole` may recover `targetRole`.\n *\n * Differs from `canRevoke` (in `keyring.ts`) in one critical place:\n * **owner→owner IS allowed**. Peer recovery is the explicitly\n * intentional case (a co-owner forgot their phrase); the freshness\n * binding lives in the `peer-recover-user` policy gate, not in the\n * permission predicate.\n *\n * Admins can recover everyone they could grant (operator / viewer /\n * client / admin) but NOT owners — that boundary stays as a hard\n * structural rule even under recovery.\n */\nfunction canRecover(callerRole: Role, targetRole: Role): boolean {\n if (callerRole === 'owner') return true\n if (callerRole === 'admin') return ADMIN_RECOVERABLE_TARGETS.includes(targetRole)\n return false\n}\n\n/** Input shape for {@link recoverUser}. */\nexport interface RecoverUserOptions {\n /** Target user id whose keyring is being recovered. */\n readonly userId: string\n /**\n * Temporary passphrase under which the new keyring is wrapped.\n * The recipient should call `db.rotatePassphrase` immediately on\n * acceptance to choose their own phrase — this temp acts as a\n * single-use bridge in invite / peer-recovery flows.\n */\n readonly passphrase: string\n /** Override the target's role. Defaults to the existing target's role. */\n readonly role?: Role\n /** Override the target's display name. Defaults to existing. */\n readonly displayName?: string\n /** Validate phrase strength against the configured policy. */\n readonly validatePassphrase?: boolean\n /**\n * Skip phrase strength validation even when `validatePassphrase` is\n * set. The escape hatch matches `grant`'s shape — used when the\n * temp phrase is a high-entropy one-shot string that doesn't need\n * to satisfy the human-typeable rules.\n */\n readonly allowWeakPassphrase?: boolean\n /**\n * Optional explicit phrase policy override (passed through to\n * `assertStrongPassphrase`). Mirrors how `grant` accepts a custom\n * `PassphrasePolicy` for app-specific tightening.\n */\n readonly passphrasePolicy?: PassphrasePolicy\n}\n\n/**\n * Atomically rewrap the target user's keyring under a fresh temp\n * passphrase. Single store write; no revoke step; no key rotation.\n *\n * Caller's responsibilities (NOT enforced here):\n * - Run the `peer-recover-user` policy gate first via\n * `Noydb.checkGate` to enforce the freshness factor proof.\n * - Communicate the temp passphrase to the recipient via a secure\n * channel (URL fragment, in-person, etc.) — the hub does not\n * transport secrets.\n */\nexport async function recoverUser(\n store: NoydbStore,\n vault: string,\n callerKeyring: UnlockedKeyring,\n options: RecoverUserOptions,\n): Promise<void> {\n // 1. Load the target's existing keyring file (plaintext header).\n const env = await store.get(vault, '_keyring', options.userId)\n if (!env) {\n throw new NoAccessError(\n `recoverUser: user \"${options.userId}\" has no keyring in vault \"${vault}\".`,\n )\n }\n const target = JSON.parse(env._data) as KeyringFile\n const targetRole = options.role ?? target.role\n\n // 2. Permission check — caller must be allowed to recover this role.\n // Owner→owner natively allowed; admin→admin allowed; admin→owner blocked.\n if (!canRecover(callerKeyring.role, targetRole)) {\n throw new PermissionDeniedError(\n `Role \"${callerKeyring.role}\" cannot recover role \"${targetRole}\"`,\n )\n }\n // Also guard against role-uplift via the override — admin cannot\n // promote a target to owner under cover of recovery.\n if (!canRecover(callerKeyring.role, target.role)) {\n throw new PermissionDeniedError(\n `Role \"${callerKeyring.role}\" cannot recover role \"${target.role}\"`,\n )\n }\n\n // 3. Anti-privilege-escalation. Every collection the target had\n // access to must be in the caller's DEK set — the recoverer\n // cannot give the recovered user access to a collection the\n // recoverer themselves can't read. Mirrors `grant()`'s check.\n for (const coll of Object.keys(target.deks)) {\n if (!callerKeyring.deks.has(coll)) {\n throw new PrivilegeEscalationError(coll)\n }\n }\n\n // 4. Optional phrase strength validation (mirrors `grant` opt-in).\n if (options.validatePassphrase && !options.allowWeakPassphrase) {\n assertStrongPassphrase(options.passphrase, options.passphrasePolicy)\n }\n\n // 5. Mint a fresh salt + KEK from the temp passphrase. The DEKs\n // themselves are unchanged — only the wrapping is replaced.\n const newSalt = generateSalt()\n const newKek = await deriveKey(options.passphrase, newSalt)\n\n const wrappedDeks: Record<string, string> = {}\n for (const coll of Object.keys(target.deks)) {\n const callerDek = callerKeyring.deks.get(coll)\n if (!callerDek) {\n // Already caught by the anti-privilege-escalation loop above.\n // This branch is defensive belt-and-braces; if it ever fires,\n // the target had a collection the caller's deks Map disagrees\n // with — fail loud rather than silently dropping access.\n throw new PrivilegeEscalationError(coll)\n }\n wrappedDeks[coll] = await wrapKey(callerDek, newKek)\n }\n\n // 6. Build the recovered keyring file. Identity preserved; wrapping\n // refreshed; tier-2 slots dropped (they wrap the OLD KEK and\n // can't survive a tier-1 phrase change — same precedent as\n // rotatePassphrase). Mint a fresh canary under newKek; the\n // OLD canary on the spread `...target` would fail to verify against\n // the new KEK and trip KeyringCorruptError on next load.\n const canary = await mintKeyringCanary(newKek)\n const next: KeyringFile = {\n ...target,\n _noydb_keyring: NOYDB_KEYRING_VERSION,\n role: targetRole,\n display_name: options.displayName ?? target.display_name,\n deks: wrappedDeks,\n salt: bufferToBase64(newSalt),\n granted_by: callerKeyring.userId,\n authenticators: [],\n canary,\n }\n\n // 7. Single atomic write — overwrites the existing envelope.\n // Backend `put` is the canonical write primitive across every\n // `to-*` store; no partial-failure window between revoke + grant.\n const envelope = {\n _noydb: 1 as const,\n _v: 1,\n _ts: new Date().toISOString(),\n _iv: '',\n _data: JSON.stringify(next),\n }\n await store.put(vault, '_keyring', options.userId, envelope)\n}\n","/**\n * Tier-2 authenticator slot management.\n *\n * Each slot independently wraps the SAME KEK under a method-specific\n * derived key (LUKS pattern). Enrolling adds a slot; removing drops\n * one. Both are constant-time keyring writes — no DEK re-keying.\n *\n * The crypto for each method lives in its `@noy-db/on-*` package\n * (`on-webauthn`, `on-oidc`, `on-password`); this module accepts the\n * package's `wrapped_kek` ciphertext + `meta` payload and persists it.\n *\n * @see https://github.com/vLannaAi/noy-db-docs/blob/main/content/docs/services/session-tiers.md → Tier 2 — Authenticate\n *\n * @module\n */\nimport type { NoydbStore, KeyringAuthenticator } from '../../kernel/types.js'\nimport { NoAccessError, ValidationError } from '../../kernel/errors.js'\nimport type { UnlockedKeyring } from './keyring.js'\nimport { persistKeyring } from './keyring.js'\n\n/** Fields shared across both wrap-KEK and wrap-DEKs enroll inputs. */\ninterface EnrollAuthenticatorBase {\n readonly id: string\n readonly method: KeyringAuthenticator['method']\n /** Method-specific metadata (cred id, salt, …). */\n readonly meta: Record<string, unknown>\n /** Tier the active session held when enrolling. Defaults to 1. */\n readonly enrolled_via_tier?: 1 | 2\n}\n\n/** Wrap-KEK enroll input (WebAuthn, OIDC). */\nexport interface EnrollAuthenticatorWrappingKEKOptions extends EnrollAuthenticatorBase {\n /** Already-wrapped KEK ciphertext (base64) — produced by the on-* package. */\n readonly wrapped_kek: string\n readonly wrapKind?: 'kek'\n}\n\n/** Wrap-DEKs enroll input (password, future on-* using the unified wrap-DEKs primitive). */\nexport interface EnrollAuthenticatorWrappingDEKsOptions extends EnrollAuthenticatorBase {\n readonly wrapKind: 'deks'\n /** Base64 AES-GCM ciphertext of `{ deks: { collection: base64rawDek } }`. */\n readonly wrapped_deks: string\n /** Base64 AES-GCM IV used for the `wrapped_deks` ciphertext. */\n readonly iv: string\n}\n\n/** Discriminated union over the two enroll input shapes. */\nexport type EnrollAuthenticatorOptions =\n | EnrollAuthenticatorWrappingKEKOptions\n | EnrollAuthenticatorWrappingDEKsOptions\n\n/**\n * Append a new authenticator slot to the keyring file. Throws\n * `ValidationError` if a slot with the same id already exists — the\n * caller decides whether to remove + re-enroll.\n *\n * Accepts either wrap-KEK (WebAuthn, OIDC) or wrap-DEKs (password)\n * input. The variant is preserved verbatim into `KeyringAuthenticator`.\n */\nexport async function enrollAuthenticator(\n store: NoydbStore,\n vault: string,\n keyring: UnlockedKeyring,\n options: EnrollAuthenticatorOptions,\n): Promise<UnlockedKeyring> {\n const existing = keyring.authenticators.find((a) => a.id === options.id)\n if (existing) {\n throw new ValidationError(\n `enrollAuthenticator: slot id \"${options.id}\" already exists in vault \"${vault}\". ` +\n 'Remove the slot first or pick a unique id.',\n )\n }\n\n const base = {\n id: options.id,\n method: options.method,\n enrolled_at: new Date().toISOString(),\n enrolled_via_tier: options.enrolled_via_tier ?? 1,\n meta: options.meta,\n } as const\n\n const slot: KeyringAuthenticator = options.wrapKind === 'deks'\n ? {\n ...base,\n wrapKind: 'deks',\n wrapped_deks: options.wrapped_deks,\n iv: options.iv,\n }\n : {\n ...base,\n wrapped_kek: options.wrapped_kek,\n }\n\n const next = appendSlot(keyring, slot)\n await persistKeyring(store, vault, next)\n return next\n}\n\n/**\n * Caller payload for {@link updateAuthenticator}. Mutates only\n * `meta` — the slot's id, method, and wrap material are immutable\n * through this primitive, preserving the anti-slot-swap guard.\n *\n * `meta` is **merged** at the top level: keys absent from the patch\n * are preserved, keys present overwrite. To clear a meta key, pass\n * `null` for that key explicitly. (Same top-level merge semantics as\n * `UserApi.updateMe`, non-recursive — meta is a flat label bag.)\n */\nexport interface UpdateAuthenticatorOptions {\n readonly meta?: Record<string, unknown>\n}\n\n/**\n * Mutate a tier-2 authenticator slot's `meta` blob (slot rename,\n * label changes). The slot's `id`, `method`, and wrap material\n * (`wrapped_kek` for wrap-KEK; `wrapped_deks` + `iv` for wrap-DEKs)\n * are immutable through this entry point — the anti-slot-swap guard\n * is structural, not gate-driven, so even if the policy gate is\n * weakened a future caller cannot use this path to swap one slot's\n * crypto for another's.\n *\n * `meta` patch semantics:\n * - Top-level merge — absent keys preserved, present keys overwrite\n * - `null` value — delete that meta key\n * - Non-object values (string, number, boolean, array) — replace verbatim\n *\n * @throws `NoAccessError` when no slot with the given id exists.\n * @throws `ValidationError` when no patch field is provided.\n *\n */\nexport async function updateAuthenticator(\n store: NoydbStore,\n vault: string,\n keyring: UnlockedKeyring,\n slotId: string,\n options: UpdateAuthenticatorOptions,\n): Promise<UnlockedKeyring> {\n if (options.meta === undefined) {\n throw new ValidationError(\n `updateAuthenticator: at least one of meta must be provided ` +\n `(slotId: \"${slotId}\").`,\n )\n }\n\n const idx = keyring.authenticators.findIndex((a) => a.id === slotId)\n if (idx === -1) {\n throw new NoAccessError(\n `updateAuthenticator: slot \"${slotId}\" not found in vault \"${vault}\".`,\n )\n }\n const existing = keyring.authenticators[idx]!\n\n // Merge at the top level. Absent keys preserved (non-recursive —\n // meta is a flat label bag in practice, no consumer nests it).\n const mergedMeta: Record<string, unknown> = { ...existing.meta }\n for (const [k, v] of Object.entries(options.meta)) {\n if (v === undefined) continue // skip\n if (v === null) {\n delete mergedMeta[k]\n continue\n }\n mergedMeta[k] = v\n }\n\n // Reconstruct the slot preserving wrapKind discrimination. The\n // immutable fields (id, method, wrapped_kek / wrapped_deks + iv,\n // enrolled_at, enrolled_via_tier) all flow through ...existing.\n const next: KeyringAuthenticator = { ...existing, meta: mergedMeta }\n const nextSlots = [...keyring.authenticators]\n nextSlots[idx] = next\n\n const nextKeyring: UnlockedKeyring = {\n ...keyring,\n authenticators: nextSlots,\n }\n await persistKeyring(store, vault, nextKeyring)\n return nextKeyring\n}\n\n/**\n * Drop a slot by id. No-op if the slot doesn't exist (idempotent —\n * removing a non-existent slot is a recoverable retry, not an error).\n */\nexport async function removeAuthenticator(\n store: NoydbStore,\n vault: string,\n keyring: UnlockedKeyring,\n slotId: string,\n): Promise<UnlockedKeyring> {\n const filtered = keyring.authenticators.filter((a) => a.id !== slotId)\n if (filtered.length === keyring.authenticators.length) {\n return keyring // idempotent — nothing to do\n }\n const next: UnlockedKeyring = {\n ...keyring,\n authenticators: filtered,\n }\n await persistKeyring(store, vault, next)\n return next\n}\n\n/**\n * Look up a slot by id. Returns `undefined` when no slot matches.\n * Used by tier-2 unlock dispatchers to fetch the wrapped KEK + meta\n * before invoking the method-specific verifier.\n */\nexport function findAuthenticator(\n keyring: UnlockedKeyring,\n slotId: string,\n): KeyringAuthenticator | undefined {\n return keyring.authenticators.find((a) => a.id === slotId)\n}\n\nfunction appendSlot(\n keyring: UnlockedKeyring,\n slot: KeyringAuthenticator,\n): UnlockedKeyring {\n return {\n ...keyring,\n authenticators: [...keyring.authenticators, slot],\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDO,IAAM,+BAA+B;AAGrC,IAAM,iCAAiC;AAGvC,IAAM,6BAA6B;AAqD1C,eAAsB,0BACpB,cACA,OACA,OACqB;AACrB,QAAM,SAAS,WAAW,OAAO;AACjC,QAAM,WACJ,wBAAwB,aACpB,eACA,IAAI,YAAY,EAAE,OAAO,YAAY;AAC3C,QAAM,aAAa,IAAI,YAAY,EAAE,OAAO,KAAK;AACjD,QAAM,aAAa,MAAM,OAAO,OAAO,WAAW,UAAU;AAC5D,QAAM,OAAO,IAAI,YAAY,EAAE,OAAO,iCAAiC,KAAK;AAC5E,QAAM,MAAM,MAAM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