@noy-db/hub 0.6.0 → 0.7.0-pre.1

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 (442) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/README.md +1 -1
  3. package/codemods/0.4.0-pre.json +24 -0
  4. package/codemods/0.6.0-pre.json +18 -0
  5. package/codemods/0.7.0-pre.json +294 -0
  6. package/dist/api-EQYRTZO2.js +20 -0
  7. package/dist/as/index.js +146 -0
  8. package/dist/as/index.js.map +1 -0
  9. package/dist/at/index.js +23 -0
  10. package/dist/attestation/index.js +18 -18
  11. package/dist/{backup-VL4GRIEW.js → backup-Z7ZBTAQ6.js} +12 -12
  12. package/dist/blobs/index.js +13 -13
  13. package/dist/broker/index.js +12 -12
  14. package/dist/by/index.js +11 -0
  15. package/dist/cargo/index.js +35 -31
  16. package/dist/{chunk-JKATP6OE.js → chunk-225O5CXQ.js} +2 -2
  17. package/dist/{chunk-XINT4VJA.js → chunk-2GXEQUEX.js} +2 -2
  18. package/dist/chunk-2GXEQUEX.js.map +1 -0
  19. package/dist/{chunk-CXPOG3ZY.js → chunk-2LPVI4PX.js} +8 -8
  20. package/dist/{chunk-2J5IT37K.js → chunk-3L2MVE36.js} +5 -5
  21. package/dist/{chunk-HOPNIR5R.js → chunk-3QARDAYW.js} +2 -2
  22. package/dist/{chunk-JYPRZWCZ.js → chunk-3SMSERQU.js} +169 -135
  23. package/dist/chunk-3SMSERQU.js.map +1 -0
  24. package/dist/{chunk-HSJBJIB2.js → chunk-467SKJ65.js} +4 -4
  25. package/dist/{chunk-YCGLAANM.js → chunk-4A4TYISP.js} +2 -2
  26. package/dist/{chunk-2CBFYXJX.js → chunk-4G25SDQL.js} +4 -4
  27. package/dist/{chunk-5LZZQMIC.js → chunk-4LPF226H.js} +5 -5
  28. package/dist/{chunk-GANFIM2M.js → chunk-4ZPE6SKS.js} +3 -3
  29. package/dist/{chunk-65JXA63J.js → chunk-5263OEM3.js} +2 -2
  30. package/dist/{chunk-FNYCT27B.js → chunk-57JTHWLQ.js} +4 -4
  31. package/dist/{chunk-5IHGJHWC.js → chunk-5ACAVJUI.js} +2 -2
  32. package/dist/{chunk-3OE2QNSM.js → chunk-5AFMP532.js} +6 -6
  33. package/dist/{chunk-J6I5VR6P.js → chunk-5W7YXFV5.js} +8 -8
  34. package/dist/chunk-5W7YXFV5.js.map +1 -0
  35. package/dist/{chunk-7ZGPQOFV.js → chunk-6EW2UCVF.js} +3 -3
  36. package/dist/{chunk-GCU42IG7.js → chunk-6FOGTKBY.js} +7 -7
  37. package/dist/chunk-6FOGTKBY.js.map +1 -0
  38. package/dist/{chunk-36CEG6CM.js → chunk-7LYUJNU3.js} +2 -2
  39. package/dist/{chunk-D6SXRMZZ.js → chunk-A2YW5EMU.js} +5 -5
  40. package/dist/{chunk-OQMCFHUX.js → chunk-AB5P32RE.js} +2 -2
  41. package/dist/{chunk-JMJSCI7U.js → chunk-ALB64CZM.js} +7 -7
  42. package/dist/{chunk-RPRASGEY.js → chunk-ALUNQEBY.js} +2 -2
  43. package/dist/{chunk-LC6NE4IQ.js → chunk-CBRS2NEK.js} +2 -11
  44. package/dist/chunk-CBRS2NEK.js.map +1 -0
  45. package/dist/{chunk-W3HAIN6U.js → chunk-CN6B5PEN.js} +5 -5
  46. package/dist/{chunk-JIHWBKMQ.js → chunk-DBNYPLWY.js} +3 -3
  47. package/dist/{chunk-ZJUZOJVW.js → chunk-DFAUMLD7.js} +5 -5
  48. package/dist/{chunk-S6PJ6ZKE.js → chunk-DKWPJOYH.js} +2 -2
  49. package/dist/{chunk-MPKP6L5E.js → chunk-E6YA6UAP.js} +2 -2
  50. package/dist/{chunk-LIR2DJWP.js → chunk-F23WQK3G.js} +9 -9
  51. package/dist/chunk-F23WQK3G.js.map +1 -0
  52. package/dist/{chunk-S7PM7Z4K.js → chunk-F7ZFRPGQ.js} +2 -2
  53. package/dist/{chunk-CKKN25P2.js → chunk-FOG7YEJP.js} +3 -3
  54. package/dist/{chunk-AJGGBXWA.js → chunk-GK4DRVUD.js} +6 -6
  55. package/dist/chunk-GK4DRVUD.js.map +1 -0
  56. package/dist/{chunk-4ATF4BLF.js → chunk-H36KSN6X.js} +7 -7
  57. package/dist/{chunk-BMU2DS3S.js → chunk-H3VG6XBC.js} +12 -171
  58. package/dist/chunk-H3VG6XBC.js.map +1 -0
  59. package/dist/{chunk-YTUFV7U7.js → chunk-H4M7ADXY.js} +10 -10
  60. package/dist/chunk-H4M7ADXY.js.map +1 -0
  61. package/dist/{chunk-QQRRKO7W.js → chunk-H7HP56F6.js} +5 -5
  62. package/dist/{chunk-RJZQ2PVD.js → chunk-HM4JSXX2.js} +3 -3
  63. package/dist/{chunk-3YGUHUJA.js → chunk-HTGRQZFB.js} +3 -3
  64. package/dist/{chunk-JXHNUYQO.js → chunk-IESNYJXZ.js} +6 -6
  65. package/dist/{chunk-ZYZJLYNS.js → chunk-ISSU3OH6.js} +7 -7
  66. package/dist/{chunk-OCJ3JA4O.js → chunk-J4MN6XIU.js} +2 -2
  67. package/dist/{chunk-HWI7GHJZ.js → chunk-J4UJ5FRV.js} +4 -4
  68. package/dist/{chunk-Z3BZXPRO.js → chunk-JBIV4FLR.js} +1 -1
  69. package/dist/chunk-JBIV4FLR.js.map +1 -0
  70. package/dist/{chunk-QVXZFJBU.js → chunk-JVLSU7S2.js} +2 -2
  71. package/dist/{chunk-7Q3RHOA5.js → chunk-KDJGJR7F.js} +2 -2
  72. package/dist/{chunk-PJX72ICF.js → chunk-KN4W2OQ4.js} +7 -7
  73. package/dist/chunk-KN4W2OQ4.js.map +1 -0
  74. package/dist/{chunk-M7WBE3OR.js → chunk-L6GTLZRK.js} +5 -5
  75. package/dist/{chunk-2ZT4INZ4.js → chunk-LF6DMX4C.js} +3 -3
  76. package/dist/chunk-LFUID7OW.js +163 -0
  77. package/dist/chunk-LFUID7OW.js.map +1 -0
  78. package/dist/{chunk-4K6BIMLF.js → chunk-LKFKXS5K.js} +2 -2
  79. package/dist/{chunk-POFYIGQ2.js → chunk-LR4Z47QD.js} +3 -3
  80. package/dist/{chunk-LUYPYCHY.js → chunk-MTBXJAS4.js} +4 -4
  81. package/dist/{chunk-FX3UIDCS.js → chunk-N4CNVSUF.js} +2 -2
  82. package/dist/{chunk-FU5VYEYK.js → chunk-NLKLXXTO.js} +2 -2
  83. package/dist/{chunk-YYV53EHO.js → chunk-OPXR4PB2.js} +2 -2
  84. package/dist/{chunk-5F7BZAGV.js → chunk-OWLVBOWO.js} +10 -10
  85. package/dist/{chunk-6NR36UNB.js → chunk-P6ASQOZR.js} +2 -2
  86. package/dist/{chunk-5ATC6UT4.js → chunk-PCQDY6QN.js} +6 -6
  87. package/dist/{chunk-EQOTJL76.js → chunk-PGFKIOR3.js} +3 -3
  88. package/dist/{chunk-D2YFQ7XG.js → chunk-POS53FG6.js} +2 -2
  89. package/dist/{chunk-ZY6P7M52.js → chunk-PQ6Z2TAP.js} +2 -2
  90. package/dist/{chunk-5OT4G5N5.js → chunk-PUJTKLPL.js} +3 -3
  91. package/dist/{chunk-64WHKBMP.js → chunk-QGJ4XIA7.js} +8 -8
  92. package/dist/{chunk-DECNV4QK.js → chunk-QHJKK77B.js} +6 -6
  93. package/dist/{chunk-JHYKSMVX.js → chunk-QI5NWLVW.js} +7 -7
  94. package/dist/{chunk-BZ3WMOYX.js → chunk-RC4BROYR.js} +3 -3
  95. package/dist/{chunk-IWQPYT6S.js → chunk-RDHUZ674.js} +4 -4
  96. package/dist/{chunk-UJ4Z67UQ.js → chunk-RK7N4OQ5.js} +1 -1
  97. package/dist/chunk-RK7N4OQ5.js.map +1 -0
  98. package/dist/{chunk-EHW7NLGD.js → chunk-S2VG3ABP.js} +3 -3
  99. package/dist/chunk-S2VG3ABP.js.map +1 -0
  100. package/dist/{chunk-7OBIBPCV.js → chunk-S35S77YU.js} +10 -10
  101. package/dist/{chunk-22GR3O4J.js → chunk-SHILAQH5.js} +2 -2
  102. package/dist/{chunk-WPZ5FVAS.js → chunk-T3PHCEN4.js} +3 -3
  103. package/dist/{chunk-GKTW3KLV.js → chunk-TOV6VMHF.js} +5 -5
  104. package/dist/chunk-TOV6VMHF.js.map +1 -0
  105. package/dist/{chunk-6RH7PRTL.js → chunk-TVIFAHZR.js} +6 -6
  106. package/dist/chunk-UBSFPGVJ.js +1 -0
  107. package/dist/{chunk-323MN67Z.js → chunk-UCUALOSM.js} +2 -2
  108. package/dist/{chunk-B4CRUZPR.js → chunk-VAG47QHV.js} +2 -2
  109. package/dist/{chunk-QH47SQLD.js → chunk-VFIWDPXZ.js} +3 -3
  110. package/dist/{chunk-K6CPIK3R.js → chunk-VTG7327U.js} +4 -4
  111. package/dist/chunk-VTG7327U.js.map +1 -0
  112. package/dist/{chunk-ONPVHX2Y.js → chunk-W5LHQXZU.js} +2 -2
  113. package/dist/{chunk-ZIMQDXTQ.js → chunk-WK5FSW7T.js} +8 -8
  114. package/dist/{chunk-PFWE7FJG.js → chunk-WLLUM35R.js} +2 -2
  115. package/dist/{chunk-IWKCJCLP.js → chunk-X62MEF2O.js} +5 -5
  116. package/dist/chunk-X62MEF2O.js.map +1 -0
  117. package/dist/{chunk-XPEPMK4Y.js → chunk-X67FCULK.js} +5 -5
  118. package/dist/chunk-X67FCULK.js.map +1 -0
  119. package/dist/{chunk-C3XWJCG7.js → chunk-XDVVBETV.js} +2 -2
  120. package/dist/chunk-XDVVBETV.js.map +1 -0
  121. package/dist/chunk-XJ3FEKEY.js +15 -0
  122. package/dist/chunk-XJ3FEKEY.js.map +1 -0
  123. package/dist/{chunk-EV2TDHQZ.js → chunk-XSN63FUS.js} +2 -2
  124. package/dist/{chunk-OR2FYRYR.js → chunk-XVU7J43V.js} +2 -2
  125. package/dist/{chunk-DNKVKO7K.js → chunk-Y6GZ2P4M.js} +2 -2
  126. package/dist/{chunk-ATY3ZASK.js → chunk-YCSM3GZU.js} +2 -2
  127. package/dist/{chunk-RDB66EKD.js → chunk-YMLQBZFJ.js} +6 -6
  128. package/dist/{chunk-EHRIDNZX.js → chunk-YPSOHDNC.js} +2 -2
  129. package/dist/{chunk-KM6ZXG7U.js → chunk-YXA2TCTZ.js} +4 -4
  130. package/dist/{chunk-TKBB62DN.js → chunk-Z2PWOSCJ.js} +2 -2
  131. package/dist/{chunk-S2I5MYSA.js → chunk-Z2WK53N6.js} +42 -15
  132. package/dist/chunk-Z2WK53N6.js.map +1 -0
  133. package/dist/{chunk-5O5ZSW7N.js → chunk-Z7ZXZL6Y.js} +2 -2
  134. package/dist/{chunk-2ZCWHCLF.js → chunk-ZO252Q5S.js} +6 -6
  135. package/dist/classified/index.js +5 -5
  136. package/dist/{classified-marker-AZDSDG6V.js → classified-marker-BSQHU4JT.js} +3 -3
  137. package/dist/collection-facade-LG3NYZVB.js +45 -0
  138. package/dist/{computed-VG2PCM4L.js → computed-ASBNTLOK.js} +3 -3
  139. package/dist/consent/index.js +9 -9
  140. package/dist/cover/index.js +9 -9
  141. package/dist/custody/index.js +12 -12
  142. package/dist/{dead-filter-JNQNB3TA.js → dead-filter-QKU56XTQ.js} +2 -2
  143. package/dist/debug/index.js +1 -1
  144. package/dist/{delegation-5F36DRDH.js → delegation-XWRPYODW.js} +11 -11
  145. package/dist/derivations/index.js +12 -12
  146. package/dist/derive-CXHCY46K.js +22 -0
  147. package/dist/directory/index.js +10 -10
  148. package/dist/{dispatch-3ZA733EY.js → dispatch-4AP4PUZU.js} +18 -18
  149. package/dist/{dispatch-TNM5CRLZ.js → dispatch-VR4LRXZ7.js} +5 -5
  150. package/dist/{enclave-Y2ALNDRD.js → enclave-NYPT7WA7.js} +9 -9
  151. package/dist/executor-3KFRQETS.js +29 -0
  152. package/dist/executor-AFHQYRAU.js +9 -0
  153. package/dist/executor-YYDW6XQI.js +9 -0
  154. package/dist/export-accessible-BX2ILB4C.js +23 -0
  155. package/dist/extract-partition-UPOVITFI.js +38 -0
  156. package/dist/{fanout-sidecar-3QZU7ZZX.js → fanout-sidecar-IWP3R4RC.js} +9 -9
  157. package/dist/{fence-watcher-DHQ775JB.js → fence-watcher-ZVSMLKQD.js} +1 -1
  158. package/dist/fence-watcher-ZVSMLKQD.js.map +1 -0
  159. package/dist/find-SZBL2HPB.js +11 -0
  160. package/dist/forget/index.js +9 -9
  161. package/dist/guards/index.js +7 -7
  162. package/dist/history/index.js +13 -13
  163. package/dist/i18n/index.js +14 -14
  164. package/dist/index.d.ts +5 -5
  165. package/dist/index.js +134 -131
  166. package/dist/index.js.map +1 -1
  167. package/dist/indexing/index.js +2 -2
  168. package/dist/introspection/index.js +12 -11
  169. package/dist/issue-G53NB6EW.js +19 -0
  170. package/dist/kernel/collection-config.d.ts +9 -9
  171. package/dist/kernel/collection.d.ts +1 -1
  172. package/dist/kernel/errors.d.ts +2 -2
  173. package/dist/kernel/noydb.d.ts +6 -6
  174. package/dist/kernel/secret-mode.d.ts +1 -1
  175. package/dist/kernel/types.d.ts +34 -15
  176. package/dist/kernel/vault.d.ts +12 -3
  177. package/dist/kernel/via/compose.d.ts +3 -3
  178. package/dist/kernel/via/index.d.ts +4 -4
  179. package/dist/kernel/via/pipeline.d.ts +6 -6
  180. package/dist/kernel/via/reconcile.d.ts +2 -2
  181. package/dist/kernel/via/taint-binding.d.ts +3 -3
  182. package/dist/{ledger-MQIIOTZB.js → ledger-T5K4P2D7.js} +11 -11
  183. package/dist/liberate-VEOZRESE.js +25 -0
  184. package/dist/{link-set-5PJBBR63.js → link-set-76JZ6YB4.js} +11 -11
  185. package/dist/{managed-secret-ETDG6AAE.js → managed-secret-6YC32VXG.js} +12 -12
  186. package/dist/materialized-views/index.js +25 -25
  187. package/dist/{migrate-cek-V3VDRV24.js → migrate-cek-LBRKYUZZ.js} +2 -2
  188. package/dist/money/index.js +4 -4
  189. package/dist/noydb-4VV2ZGLZ.js +86 -0
  190. package/dist/on/index.js +1 -0
  191. package/dist/overlay-views/index.js +4 -4
  192. package/dist/periods/index.js +12 -12
  193. package/dist/pod/index.js +58 -57
  194. package/dist/{pod-handle-AZ3CXY5Y.js → pod-handle-P6DPBM5U.js} +9 -9
  195. package/dist/policy/index.js +10 -10
  196. package/dist/port/as/active.d.ts +10 -0
  197. package/dist/port/as/index.d.ts +32 -0
  198. package/dist/port/as/types.d.ts +113 -0
  199. package/dist/port/at/index.d.ts +37 -0
  200. package/dist/port/by/default-provider.d.ts +3 -3
  201. package/dist/port/by/index.d.ts +32 -10
  202. package/dist/port/by/types.d.ts +29 -11
  203. package/dist/port/on/index.d.ts +50 -0
  204. package/dist/port/with/computed-strategy.d.ts +1 -1
  205. package/dist/port/with/device-seal-strategy.d.ts +2 -2
  206. package/dist/port/with/formats-strategy.d.ts +76 -0
  207. package/dist/port/with/strategies.d.ts +11 -5
  208. package/dist/portability/index.js +8 -8
  209. package/dist/{post-register-QCJYRMIK.js → post-register-53O7AJRZ.js} +6 -6
  210. package/dist/query/index.js +3 -3
  211. package/dist/reduce/index.js +4 -4
  212. package/dist/register-6TCBR6XD.js +32 -0
  213. package/dist/registry-DH2L4O2V.js +18 -0
  214. package/dist/registry-IWFMXCHX.js +9 -0
  215. package/dist/registry-Q3FG3OAX.js +9 -0
  216. package/dist/registry-YC3IFG3A.js +19 -0
  217. package/dist/request-withdrawal-NM5VYR6F.js +31 -0
  218. package/dist/{reveal-W7BKZSUP.js → reveal-XBIMHAXR.js} +6 -6
  219. package/dist/revoke-MJNYWO72.js +24 -0
  220. package/dist/satellites/index.js +1 -1
  221. package/dist/schema-update/index.js +2 -2
  222. package/dist/sealed-record/index.js +12 -12
  223. package/dist/search/index.js +4 -4
  224. package/dist/{seed-55FPOMYP.js → seed-NSNIGYXE.js} +12 -12
  225. package/dist/sequence/index.js +9 -9
  226. package/dist/session/index.js +9 -9
  227. package/dist/shadow/index.js +2 -2
  228. package/dist/signer-6XVS2AU3.js +25 -0
  229. package/dist/snapshots/index.js +10 -10
  230. package/dist/{stale-TH7SSVRV.js → stale-MCS46TFO.js} +10 -10
  231. package/dist/stale-MCS46TFO.js.map +1 -0
  232. package/dist/storage-ZXUT476I.js +23 -0
  233. package/dist/storage-ZXUT476I.js.map +1 -0
  234. package/dist/{store-coordination-provider-R27VRD6K.js → store-coordination-provider-6FM26VQM.js} +14 -13
  235. package/dist/store-coordination-provider-6FM26VQM.js.map +1 -0
  236. package/dist/sync/index.js +10 -10
  237. package/dist/team/index.js +17 -17
  238. package/dist/tiers/index.js +11 -11
  239. package/dist/to/index.js +1 -1
  240. package/dist/transactions/index.js +3 -3
  241. package/dist/util/index.js +1 -1
  242. package/dist/vault-diff-FE5J35NJ.js +9 -0
  243. package/dist/vault-diff-FE5J35NJ.js.map +1 -0
  244. package/dist/vault-head/index.js +8 -8
  245. package/dist/{verify-M5LQH43C.js → verify-WYOFLSNA.js} +5 -5
  246. package/dist/via/blob/binding.d.ts +6 -6
  247. package/dist/via/classified/binding.d.ts +9 -9
  248. package/dist/via/computed/binding.d.ts +2 -2
  249. package/dist/via/i18n/binding.d.ts +4 -4
  250. package/dist/via/lookup/binding.d.ts +5 -5
  251. package/dist/via/lookup/index.d.ts +1 -1
  252. package/dist/via/lookup/snapshot.d.ts +1 -1
  253. package/dist/via/money/binding.d.ts +3 -3
  254. package/dist/via/money/normalize.d.ts +1 -1
  255. package/dist/via/money/where.d.ts +3 -3
  256. package/dist/walk-JNEOYCAU.js +21 -0
  257. package/dist/walk-JNEOYCAU.js.map +1 -0
  258. package/dist/with-cargo/adopt-partition.d.ts +6 -6
  259. package/dist/with-cargo/floor.d.ts +1 -1
  260. package/dist/with-cargo/index.d.ts +1 -1
  261. package/dist/with-party/team/deed.d.ts +4 -4
  262. package/dist/with-party/team/device-seal.d.ts +5 -5
  263. package/dist/with-party/team/echo-ceremony.d.ts +2 -2
  264. package/dist/with-party/team/echo-secret.d.ts +4 -4
  265. package/dist/with-party/team/index.d.ts +2 -2
  266. package/dist/with-party/team/keyring.d.ts +2 -2
  267. package/dist/with-party/team/managed-secret.d.ts +21 -11
  268. package/dist/with-party/team/noydb-facade.d.ts +2 -2
  269. package/dist/with-party/team/{shamir-recovery-provider.d.ts → noydb-shamir.d.ts} +1 -1
  270. package/dist/with-party/team/recovery.d.ts +3 -3
  271. package/dist/with-party/team/rotate-recover.d.ts +5 -5
  272. package/dist/with-pod/format.d.ts +1 -1
  273. package/dist/with-pod/pod.d.ts +6 -6
  274. package/dist/with-shape/introspection/describe.d.ts +2 -2
  275. package/dist/with-shape/schema-update/fence-controller.d.ts +4 -4
  276. package/dist/with-shape/schema-update/fence-watcher.d.ts +4 -4
  277. package/dist/with-shape/schema-update/store-coordination-provider.d.ts +7 -6
  278. package/dist/withdraw-accessible-ILTSXTIE.js +28 -0
  279. package/dist/withdraw-accessible-ILTSXTIE.js.map +1 -0
  280. package/package.json +23 -5
  281. package/dist/api-6X2VLZ7J.js +0 -20
  282. package/dist/chunk-AJGGBXWA.js.map +0 -1
  283. package/dist/chunk-BMU2DS3S.js.map +0 -1
  284. package/dist/chunk-C3XWJCG7.js.map +0 -1
  285. package/dist/chunk-EHW7NLGD.js.map +0 -1
  286. package/dist/chunk-GCU42IG7.js.map +0 -1
  287. package/dist/chunk-GKTW3KLV.js.map +0 -1
  288. package/dist/chunk-IWKCJCLP.js.map +0 -1
  289. package/dist/chunk-J6I5VR6P.js.map +0 -1
  290. package/dist/chunk-JYPRZWCZ.js.map +0 -1
  291. package/dist/chunk-K6CPIK3R.js.map +0 -1
  292. package/dist/chunk-LC6NE4IQ.js.map +0 -1
  293. package/dist/chunk-LIR2DJWP.js.map +0 -1
  294. package/dist/chunk-PJX72ICF.js.map +0 -1
  295. package/dist/chunk-S2I5MYSA.js.map +0 -1
  296. package/dist/chunk-UJ4Z67UQ.js.map +0 -1
  297. package/dist/chunk-XINT4VJA.js.map +0 -1
  298. package/dist/chunk-XPEPMK4Y.js.map +0 -1
  299. package/dist/chunk-YTUFV7U7.js.map +0 -1
  300. package/dist/chunk-Z3BZXPRO.js.map +0 -1
  301. package/dist/collection-facade-WSUAYFJ4.js +0 -45
  302. package/dist/derive-MPOGZ4NR.js +0 -22
  303. package/dist/executor-BBEEUFO3.js +0 -9
  304. package/dist/executor-G6G3YEWR.js +0 -9
  305. package/dist/executor-ZUTUMTPA.js +0 -29
  306. package/dist/export-accessible-S3KEB763.js +0 -23
  307. package/dist/extract-partition-KVCTSUVE.js +0 -38
  308. package/dist/fence-watcher-DHQ775JB.js.map +0 -1
  309. package/dist/find-V4FN5ITT.js +0 -11
  310. package/dist/issue-5CFBWBRX.js +0 -19
  311. package/dist/liberate-LW7OKVBH.js +0 -25
  312. package/dist/noydb-LFDRMYZ5.js +0 -85
  313. package/dist/register-JBOEHTVX.js +0 -32
  314. package/dist/registry-5DYHQFJS.js +0 -9
  315. package/dist/registry-EANV44W2.js +0 -9
  316. package/dist/registry-J25H6VB4.js +0 -19
  317. package/dist/registry-R23SQUQH.js +0 -18
  318. package/dist/request-withdrawal-KQ4W4UT5.js +0 -31
  319. package/dist/revoke-H3VSTAIE.js +0 -24
  320. package/dist/signer-53AQ3BU2.js +0 -25
  321. package/dist/storage-WSF7ZKTL.js +0 -23
  322. package/dist/store-coordination-provider-R27VRD6K.js.map +0 -1
  323. package/dist/walk-NABCHDZN.js +0 -21
  324. package/dist/withdraw-accessible-VCINIG6V.js +0 -28
  325. /package/dist/{api-6X2VLZ7J.js.map → api-EQYRTZO2.js.map} +0 -0
  326. /package/dist/{collection-facade-WSUAYFJ4.js.map → at/index.js.map} +0 -0
  327. /package/dist/{backup-VL4GRIEW.js.map → backup-Z7ZBTAQ6.js.map} +0 -0
  328. /package/dist/{computed-VG2PCM4L.js.map → by/index.js.map} +0 -0
  329. /package/dist/{chunk-JKATP6OE.js.map → chunk-225O5CXQ.js.map} +0 -0
  330. /package/dist/{chunk-CXPOG3ZY.js.map → chunk-2LPVI4PX.js.map} +0 -0
  331. /package/dist/{chunk-2J5IT37K.js.map → chunk-3L2MVE36.js.map} +0 -0
  332. /package/dist/{chunk-HOPNIR5R.js.map → chunk-3QARDAYW.js.map} +0 -0
  333. /package/dist/{chunk-HSJBJIB2.js.map → chunk-467SKJ65.js.map} +0 -0
  334. /package/dist/{chunk-YCGLAANM.js.map → chunk-4A4TYISP.js.map} +0 -0
  335. /package/dist/{chunk-2CBFYXJX.js.map → chunk-4G25SDQL.js.map} +0 -0
  336. /package/dist/{chunk-5LZZQMIC.js.map → chunk-4LPF226H.js.map} +0 -0
  337. /package/dist/{chunk-GANFIM2M.js.map → chunk-4ZPE6SKS.js.map} +0 -0
  338. /package/dist/{chunk-65JXA63J.js.map → chunk-5263OEM3.js.map} +0 -0
  339. /package/dist/{chunk-FNYCT27B.js.map → chunk-57JTHWLQ.js.map} +0 -0
  340. /package/dist/{chunk-5IHGJHWC.js.map → chunk-5ACAVJUI.js.map} +0 -0
  341. /package/dist/{chunk-3OE2QNSM.js.map → chunk-5AFMP532.js.map} +0 -0
  342. /package/dist/{chunk-7ZGPQOFV.js.map → chunk-6EW2UCVF.js.map} +0 -0
  343. /package/dist/{chunk-36CEG6CM.js.map → chunk-7LYUJNU3.js.map} +0 -0
  344. /package/dist/{chunk-D6SXRMZZ.js.map → chunk-A2YW5EMU.js.map} +0 -0
  345. /package/dist/{chunk-OQMCFHUX.js.map → chunk-AB5P32RE.js.map} +0 -0
  346. /package/dist/{chunk-JMJSCI7U.js.map → chunk-ALB64CZM.js.map} +0 -0
  347. /package/dist/{chunk-RPRASGEY.js.map → chunk-ALUNQEBY.js.map} +0 -0
  348. /package/dist/{chunk-W3HAIN6U.js.map → chunk-CN6B5PEN.js.map} +0 -0
  349. /package/dist/{chunk-JIHWBKMQ.js.map → chunk-DBNYPLWY.js.map} +0 -0
  350. /package/dist/{chunk-ZJUZOJVW.js.map → chunk-DFAUMLD7.js.map} +0 -0
  351. /package/dist/{chunk-S6PJ6ZKE.js.map → chunk-DKWPJOYH.js.map} +0 -0
  352. /package/dist/{chunk-MPKP6L5E.js.map → chunk-E6YA6UAP.js.map} +0 -0
  353. /package/dist/{chunk-S7PM7Z4K.js.map → chunk-F7ZFRPGQ.js.map} +0 -0
  354. /package/dist/{chunk-CKKN25P2.js.map → chunk-FOG7YEJP.js.map} +0 -0
  355. /package/dist/{chunk-4ATF4BLF.js.map → chunk-H36KSN6X.js.map} +0 -0
  356. /package/dist/{chunk-QQRRKO7W.js.map → chunk-H7HP56F6.js.map} +0 -0
  357. /package/dist/{chunk-RJZQ2PVD.js.map → chunk-HM4JSXX2.js.map} +0 -0
  358. /package/dist/{chunk-3YGUHUJA.js.map → chunk-HTGRQZFB.js.map} +0 -0
  359. /package/dist/{chunk-JXHNUYQO.js.map → chunk-IESNYJXZ.js.map} +0 -0
  360. /package/dist/{chunk-ZYZJLYNS.js.map → chunk-ISSU3OH6.js.map} +0 -0
  361. /package/dist/{chunk-OCJ3JA4O.js.map → chunk-J4MN6XIU.js.map} +0 -0
  362. /package/dist/{chunk-HWI7GHJZ.js.map → chunk-J4UJ5FRV.js.map} +0 -0
  363. /package/dist/{chunk-QVXZFJBU.js.map → chunk-JVLSU7S2.js.map} +0 -0
  364. /package/dist/{chunk-7Q3RHOA5.js.map → chunk-KDJGJR7F.js.map} +0 -0
  365. /package/dist/{chunk-M7WBE3OR.js.map → chunk-L6GTLZRK.js.map} +0 -0
  366. /package/dist/{chunk-2ZT4INZ4.js.map → chunk-LF6DMX4C.js.map} +0 -0
  367. /package/dist/{chunk-4K6BIMLF.js.map → chunk-LKFKXS5K.js.map} +0 -0
  368. /package/dist/{chunk-POFYIGQ2.js.map → chunk-LR4Z47QD.js.map} +0 -0
  369. /package/dist/{chunk-LUYPYCHY.js.map → chunk-MTBXJAS4.js.map} +0 -0
  370. /package/dist/{chunk-FX3UIDCS.js.map → chunk-N4CNVSUF.js.map} +0 -0
  371. /package/dist/{chunk-FU5VYEYK.js.map → chunk-NLKLXXTO.js.map} +0 -0
  372. /package/dist/{chunk-YYV53EHO.js.map → chunk-OPXR4PB2.js.map} +0 -0
  373. /package/dist/{chunk-5F7BZAGV.js.map → chunk-OWLVBOWO.js.map} +0 -0
  374. /package/dist/{chunk-6NR36UNB.js.map → chunk-P6ASQOZR.js.map} +0 -0
  375. /package/dist/{chunk-5ATC6UT4.js.map → chunk-PCQDY6QN.js.map} +0 -0
  376. /package/dist/{chunk-EQOTJL76.js.map → chunk-PGFKIOR3.js.map} +0 -0
  377. /package/dist/{chunk-D2YFQ7XG.js.map → chunk-POS53FG6.js.map} +0 -0
  378. /package/dist/{chunk-ZY6P7M52.js.map → chunk-PQ6Z2TAP.js.map} +0 -0
  379. /package/dist/{chunk-5OT4G5N5.js.map → chunk-PUJTKLPL.js.map} +0 -0
  380. /package/dist/{chunk-64WHKBMP.js.map → chunk-QGJ4XIA7.js.map} +0 -0
  381. /package/dist/{chunk-DECNV4QK.js.map → chunk-QHJKK77B.js.map} +0 -0
  382. /package/dist/{chunk-JHYKSMVX.js.map → chunk-QI5NWLVW.js.map} +0 -0
  383. /package/dist/{chunk-BZ3WMOYX.js.map → chunk-RC4BROYR.js.map} +0 -0
  384. /package/dist/{chunk-IWQPYT6S.js.map → chunk-RDHUZ674.js.map} +0 -0
  385. /package/dist/{chunk-7OBIBPCV.js.map → chunk-S35S77YU.js.map} +0 -0
  386. /package/dist/{chunk-22GR3O4J.js.map → chunk-SHILAQH5.js.map} +0 -0
  387. /package/dist/{chunk-WPZ5FVAS.js.map → chunk-T3PHCEN4.js.map} +0 -0
  388. /package/dist/{chunk-6RH7PRTL.js.map → chunk-TVIFAHZR.js.map} +0 -0
  389. /package/dist/{derive-MPOGZ4NR.js.map → chunk-UBSFPGVJ.js.map} +0 -0
  390. /package/dist/{chunk-323MN67Z.js.map → chunk-UCUALOSM.js.map} +0 -0
  391. /package/dist/{chunk-B4CRUZPR.js.map → chunk-VAG47QHV.js.map} +0 -0
  392. /package/dist/{chunk-QH47SQLD.js.map → chunk-VFIWDPXZ.js.map} +0 -0
  393. /package/dist/{chunk-ONPVHX2Y.js.map → chunk-W5LHQXZU.js.map} +0 -0
  394. /package/dist/{chunk-ZIMQDXTQ.js.map → chunk-WK5FSW7T.js.map} +0 -0
  395. /package/dist/{chunk-PFWE7FJG.js.map → chunk-WLLUM35R.js.map} +0 -0
  396. /package/dist/{chunk-EV2TDHQZ.js.map → chunk-XSN63FUS.js.map} +0 -0
  397. /package/dist/{chunk-OR2FYRYR.js.map → chunk-XVU7J43V.js.map} +0 -0
  398. /package/dist/{chunk-DNKVKO7K.js.map → chunk-Y6GZ2P4M.js.map} +0 -0
  399. /package/dist/{chunk-ATY3ZASK.js.map → chunk-YCSM3GZU.js.map} +0 -0
  400. /package/dist/{chunk-RDB66EKD.js.map → chunk-YMLQBZFJ.js.map} +0 -0
  401. /package/dist/{chunk-EHRIDNZX.js.map → chunk-YPSOHDNC.js.map} +0 -0
  402. /package/dist/{chunk-KM6ZXG7U.js.map → chunk-YXA2TCTZ.js.map} +0 -0
  403. /package/dist/{chunk-TKBB62DN.js.map → chunk-Z2PWOSCJ.js.map} +0 -0
  404. /package/dist/{chunk-5O5ZSW7N.js.map → chunk-Z7ZXZL6Y.js.map} +0 -0
  405. /package/dist/{chunk-2ZCWHCLF.js.map → chunk-ZO252Q5S.js.map} +0 -0
  406. /package/dist/{classified-marker-AZDSDG6V.js.map → classified-marker-BSQHU4JT.js.map} +0 -0
  407. /package/dist/{enclave-Y2ALNDRD.js.map → collection-facade-LG3NYZVB.js.map} +0 -0
  408. /package/dist/{executor-BBEEUFO3.js.map → computed-ASBNTLOK.js.map} +0 -0
  409. /package/dist/{dead-filter-JNQNB3TA.js.map → dead-filter-QKU56XTQ.js.map} +0 -0
  410. /package/dist/{delegation-5F36DRDH.js.map → delegation-XWRPYODW.js.map} +0 -0
  411. /package/dist/{executor-G6G3YEWR.js.map → derive-CXHCY46K.js.map} +0 -0
  412. /package/dist/{dispatch-3ZA733EY.js.map → dispatch-4AP4PUZU.js.map} +0 -0
  413. /package/dist/{dispatch-TNM5CRLZ.js.map → dispatch-VR4LRXZ7.js.map} +0 -0
  414. /package/dist/{executor-ZUTUMTPA.js.map → enclave-NYPT7WA7.js.map} +0 -0
  415. /package/dist/{export-accessible-S3KEB763.js.map → executor-3KFRQETS.js.map} +0 -0
  416. /package/dist/{extract-partition-KVCTSUVE.js.map → executor-AFHQYRAU.js.map} +0 -0
  417. /package/dist/{find-V4FN5ITT.js.map → executor-YYDW6XQI.js.map} +0 -0
  418. /package/dist/{issue-5CFBWBRX.js.map → export-accessible-BX2ILB4C.js.map} +0 -0
  419. /package/dist/{ledger-MQIIOTZB.js.map → extract-partition-UPOVITFI.js.map} +0 -0
  420. /package/dist/{fanout-sidecar-3QZU7ZZX.js.map → fanout-sidecar-IWP3R4RC.js.map} +0 -0
  421. /package/dist/{liberate-LW7OKVBH.js.map → find-SZBL2HPB.js.map} +0 -0
  422. /package/dist/{link-set-5PJBBR63.js.map → issue-G53NB6EW.js.map} +0 -0
  423. /package/dist/{managed-secret-ETDG6AAE.js.map → ledger-T5K4P2D7.js.map} +0 -0
  424. /package/dist/{noydb-LFDRMYZ5.js.map → liberate-VEOZRESE.js.map} +0 -0
  425. /package/dist/{register-JBOEHTVX.js.map → link-set-76JZ6YB4.js.map} +0 -0
  426. /package/dist/{registry-5DYHQFJS.js.map → managed-secret-6YC32VXG.js.map} +0 -0
  427. /package/dist/{migrate-cek-V3VDRV24.js.map → migrate-cek-LBRKYUZZ.js.map} +0 -0
  428. /package/dist/{registry-EANV44W2.js.map → noydb-4VV2ZGLZ.js.map} +0 -0
  429. /package/dist/{registry-J25H6VB4.js.map → on/index.js.map} +0 -0
  430. /package/dist/{pod-handle-AZ3CXY5Y.js.map → pod-handle-P6DPBM5U.js.map} +0 -0
  431. /package/dist/{post-register-QCJYRMIK.js.map → post-register-53O7AJRZ.js.map} +0 -0
  432. /package/dist/{registry-R23SQUQH.js.map → register-6TCBR6XD.js.map} +0 -0
  433. /package/dist/{request-withdrawal-KQ4W4UT5.js.map → registry-DH2L4O2V.js.map} +0 -0
  434. /package/dist/{revoke-H3VSTAIE.js.map → registry-IWFMXCHX.js.map} +0 -0
  435. /package/dist/{signer-53AQ3BU2.js.map → registry-Q3FG3OAX.js.map} +0 -0
  436. /package/dist/{stale-TH7SSVRV.js.map → registry-YC3IFG3A.js.map} +0 -0
  437. /package/dist/{storage-WSF7ZKTL.js.map → request-withdrawal-NM5VYR6F.js.map} +0 -0
  438. /package/dist/{reveal-W7BKZSUP.js.map → reveal-XBIMHAXR.js.map} +0 -0
  439. /package/dist/{walk-NABCHDZN.js.map → revoke-MJNYWO72.js.map} +0 -0
  440. /package/dist/{seed-55FPOMYP.js.map → seed-NSNIGYXE.js.map} +0 -0
  441. /package/dist/{withdraw-accessible-VCINIG6V.js.map → signer-6XVS2AU3.js.map} +0 -0
  442. /package/dist/{verify-M5LQH43C.js.map → verify-WYOFLSNA.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/port/with/i18n-strategy.ts","../src/kernel/paths.ts","../src/via/i18n/policy.ts","../src/via/i18n/script.ts","../src/via/i18n/binding.ts","../src/via/i18n/core.ts"],"sourcesContent":["/**\n * i18n strategy seam (#623 Task 7 — moved out of `via/i18n/strategy.ts`\n * and `via/i18n/dictionary.ts`, precedent: `port/with/lazy-strategy.ts`).\n * Lives on the `/with` port (the one seam the kernel spine may import\n * statically) so `Collection`/`Vault` can hold the `NO_I18N` default and the\n * two reserved-name/brand predicates without a spine→service static import.\n *\n * Core imports `I18nStrategy` type-only + `NO_I18N` stub; real\n * `applyI18nLocale` / `validateI18nTextValue` / `DictionaryHandle` are only\n * reachable via `withI18n()` in `via/i18n/active.ts`.\n *\n * Solo apps that don't use `i18nText()` fields, don't declare `dictKey()`\n * fields, and don't open a `vault.dictionary(...)` handle ship none of the\n * ~854 LOC behind this seam.\n *\n * Behavior under NO_I18N:\n *\n * - **applyI18nLocale** — returns the record unchanged. Apps without\n * any i18n descriptors never observe a difference; apps that\n * *did* declare i18nText/dictKey fields without opting into the\n * strategy still get raw values back (locale resolution silently\n * skipped). The validators below ensure the misconfiguration is\n * caught at write time instead.\n * - **validateI18nTextValue** — throws when called. Only fires when\n * a collection declared `i18nFields`; if you declared the field,\n * you must opt in.\n * - **buildDictionaryHandle** — throws when called. Only fires when\n * user code calls `vault.dictionary(...)`.\n *\n * #650 Task 1 (via-lookup extraction, phase D): the real\n * `buildDictionaryHandle` (in `via/i18n/active.ts`) now delegates to\n * `withLookup().buildLookupHandle` (`via/lookup/active.ts`) — same\n * handle (`LookupHandle`, aliased as `DictionaryHandle`), new home. This\n * interface's shape is unchanged.\n *\n * @internal\n */\n\nimport type { NoydbStore } from '../../kernel/types.js'\nimport type { LedgerStore } from '../../with-commit/history/ledger/store.js'\nimport type { UnlockedKeyring } from '../../with-party/team/keyring.js'\nimport type { NoydbEventEmitter } from '../../kernel/events.js'\nimport type { I18nTextDescriptor } from '../../via/i18n/core.js'\nimport type { Layer } from '../../via/i18n/policy.js'\nimport type { ScriptWarning } from '../../via/i18n/script.js'\nimport type { DictKeyDescriptor, DictionaryHandle, DictionaryOptions, StaticDictDescriptor } from '../../via/i18n/dictionary.js'\nimport type { ViaCryptoCtx } from '../../kernel/via/index.js'\nimport type { EncryptedEnvelope } from '../../kernel/types.js'\n\n/**\n * Options accepted by `I18nStrategy.buildDictionaryHandle`. Mirrors\n * the `DictionaryHandle` constructor verbatim — kept here so core\n * code never imports the dictionary module at runtime.\n *\n * @internal\n */\nexport interface BuildDictionaryHandleOptions<Keys extends string = string> {\n adapter: NoydbStore\n compartmentName: string\n dictionaryName: string\n keyring: UnlockedKeyring\n /**\n * The `reservedEnvelopes('_dict_')` capability (#629 Task 4) — DictionaryHandle's\n * sanctioned crypto door onto its `_dict_<name>` collection. Bound by the\n * Vault to its own `getDEK`, the same per-collection-name DEK resolver\n * every other collection uses.\n */\n reservedEnvelopes: ReturnType<ViaCryptoCtx['reservedEnvelopes']>\n encrypted: boolean\n ledger: LedgerStore | undefined\n options: DictionaryOptions\n findAndUpdateReferences:\n | ((\n dictionaryName: string,\n oldKey: string,\n newKey: string,\n ) => Promise<void>)\n | undefined\n emitter: NoydbEventEmitter\n /**\n * Used by the active strategy to satisfy the generic-key parameter\n * on the returned handle. The NO_I18N stub never reads it.\n */\n // marker generic — runtime sees no value\n _keyMarker?: Keys\n /** #650 Task 4 (#647) — choke-point participation hooks, passed through to `buildLookupHandle`. */\n onDirty?: ((collection: string, id: string, action: 'put' | 'delete', version: number) => Promise<void>) | undefined\n onRecordMutated?: ((collection: string, id: string, action: 'put' | 'delete', version: number) => Promise<void>) | undefined\n /**\n * #647 fix wave 1 — mints a version-ordered delete-marker envelope, passed through to\n * `buildLookupHandle`. See `port/with/lookup-strategy.ts`'s `BuildLookupHandleOptions` doc\n * comment for why this is injected rather than imported by the handle itself.\n */\n buildDeleteMarker: (identity: { collection: string; id: string }, version: number, actor: string) => EncryptedEnvelope\n /** #650 Task 5 (#648) — the real reference check, passed through to `buildLookupHandle`. */\n checkReferencesOnDelete?: ((key: string) => Promise<unknown>) | undefined\n}\n\n/**\n * @internal\n */\nexport interface I18nStrategy {\n /**\n * Resolve `i18nText` fields on a record to the requested locale and\n * return a new object. Returns the input unchanged under\n * `NO_I18N`.\n */\n applyI18nLocale(\n record: Record<string, unknown>,\n fields: Record<string, I18nTextDescriptor>,\n locale: string,\n fallback?: string | readonly string[],\n layer?: Layer,\n ): Record<string, unknown>\n\n /**\n * Validate that an i18nText field's value satisfies its descriptor\n * (required locales present, etc.). Throws under `NO_I18N` —\n * declaring i18nFields without opting in is a misconfiguration.\n */\n validateI18nTextValue(\n value: unknown,\n field: string,\n descriptor: I18nTextDescriptor,\n ): void\n\n /**\n * Enforce per-locale script constraints over an i18nText value map\n * (write-time). Returns the (possibly filtered) value plus any\n * non-fatal warnings. Returns the value unchanged when the field has\n * no `script` option, or under `NO_I18N`.\n */\n enforceScript(\n value: Record<string, unknown>,\n field: string,\n descriptor: I18nTextDescriptor,\n exempt?: ReadonlySet<string>,\n ): { value: Record<string, unknown>; warnings: ScriptWarning[] }\n\n /**\n * Per-field locales that are unchanged round-tripped densify fills (exempt\n * from write-time script enforcement). Empty under NO_I18N.\n */\n computeExemptFills(\n prior: Record<string, unknown> | undefined,\n incoming: Record<string, unknown>,\n fields: Record<string, I18nTextDescriptor>,\n ): Map<string, Set<string>>\n\n /**\n * Eager-fill empty i18n slots from each field's substitute chain and record\n * provenance in `record['_i18nFilled']`. Mutates `record`. No-op under\n * NO_I18N.\n */\n densify(\n record: Record<string, unknown>,\n prior: Record<string, unknown> | undefined,\n fields: Record<string, I18nTextDescriptor>,\n ): void\n\n /**\n * Construct a typed `DictionaryHandle` for the named dictionary.\n * Throws under `NO_I18N`.\n */\n buildDictionaryHandle<Keys extends string = string>(\n opts: BuildDictionaryHandleOptions<Keys>,\n ): DictionaryHandle<Keys>\n}\n\nfunction notEnabled(op: string): Error {\n return new Error(\n `${op} requires the i18n strategy. Import ` +\n '`{ withI18n }` from \"@noy-db/hub/i18n\" and pass it to ' +\n '`createNoydb({ i18nStrategy: withI18n() })`.',\n )\n}\n\n/**\n * No-i18n stub. Locale resolution is the identity; validation and\n * dictionary construction throw with an actionable pointer.\n *\n * @internal\n */\nexport const NO_I18N: I18nStrategy = {\n applyI18nLocale(record) { return record },\n validateI18nTextValue() { throw notEnabled('i18nText field validation') },\n enforceScript(value) { return { value, warnings: [] } },\n computeExemptFills() { return new Map<string, Set<string>>() },\n densify() {},\n buildDictionaryHandle() { throw notEnabled('vault.dictionary()') },\n}\n\n/**\n * Return true when a collection name is a reserved dictionary collection\n * (the `_dict_*` prefix). Mirrors `DICT_COLLECTION_PREFIX` — now on\n * `via/lookup/handle.ts` (#650 Task 1), re-exported from\n * `via/i18n/dictionary.ts` for compat — duplicated here (not\n * imported) so this port has no VALUE dependency back on the feature; keep\n * the two in sync if the prefix ever changes.\n */\nexport function isDictCollectionName(name: string): boolean {\n return name.startsWith('_dict_')\n}\n\n/** Runtime predicate for detecting a StaticDictDescriptor. */\nexport function isStaticDictDescriptor(x: unknown): x is StaticDictDescriptor {\n return (\n typeof x === 'object' &&\n x !== null &&\n (x as { _noydbStaticDict?: unknown })._noydbStaticDict === true\n )\n}\n\n/**\n * Runtime predicate for detecting an I18nTextDescriptor. Pure tag check —\n * moved here (#623 Task 11) alongside `isStaticDictDescriptor` so\n * `kernel/via/compose.ts` (`mergeViaFields`'s descriptor-shape classification)\n * can reach it through the port instead of importing `via/i18n/core.js`\n * directly. Re-exported from that module for compat with existing importers.\n */\nexport function isI18nTextDescriptor(x: unknown): x is I18nTextDescriptor {\n return (\n typeof x === 'object' &&\n x !== null &&\n (x as { _noydbI18nText?: unknown })._noydbI18nText === true\n )\n}\n\n/**\n * Runtime predicate for detecting a DictKeyDescriptor. Pure tag check —\n * moved here (#623 Task 11) for the same reason as `isI18nTextDescriptor`\n * above. Re-exported from `via/i18n/dictionary.js` for compat with\n * existing importers.\n */\nexport function isDictKeyDescriptor(x: unknown): x is DictKeyDescriptor {\n return (\n typeof x === 'object' &&\n x !== null &&\n (x as { _noydbDictKey?: unknown })._noydbDictKey === true\n )\n}\n\n/**\n * Type-only re-exports (#623 Task 8) — the kernel spine (collection.ts,\n * collection-config.ts, vault.ts, types.ts) imports these descriptor/handle\n * types through the port instead of reaching into `via/i18n/*`\n * directly, so `src/kernel/**` carries no via-i18n specifier at all.\n * `isolatedModules: true` erases these at build time — no runtime coupling.\n */\nexport type { I18nTextDescriptor } from '../../via/i18n/core.js'\nexport type { DictKeyDescriptor, DictionaryHandle, DictionaryOptions, StaticDictDescriptor } from '../../via/i18n/dictionary.js'\nexport type { Layer } from '../../via/i18n/policy.js'\nexport type { ScriptWarning } from '../../via/i18n/script.js'\n","/**\n * Generic dotted-path / `[]`-wildcard record helpers. Kernel-owned:\n * these carry zero i18n logic — they were extracted out of\n * `via/i18n/core.ts` (Task 7, #623) so kernel call-sites (put-time\n * validation, densify) can import them without a spine→service edge.\n *\n * @internal\n */\n\n/**\n * Return all leaf values at `path`, expanding `[].` array wildcards.\n *\n * - `'name'` → `[obj.name]`\n * - `'address.lineOne'` → `[obj.address.lineOne]`\n * - `'contacts[].title'` → `[obj.contacts[0].title, obj.contacts[1].title, …]`\n *\n * Returns an empty array when the path does not resolve (missing key,\n * wrong type, etc.). Used by `enforceI18nOnPut` to validate nested fields.\n */\nexport function getAtPath(obj: Record<string, unknown>, path: string): unknown[] {\n const arrayIdx = path.indexOf('[].')\n if (arrayIdx !== -1) {\n const arrayKey = path.slice(0, arrayIdx)\n const restPath = path.slice(arrayIdx + 3)\n const arr = obj[arrayKey]\n if (!Array.isArray(arr)) return []\n return arr.flatMap(item => {\n if (!item || typeof item !== 'object' || Array.isArray(item)) return []\n return getAtPath(item as Record<string, unknown>, restPath)\n })\n }\n const dotIdx = path.indexOf('.')\n if (dotIdx !== -1) {\n const head = path.slice(0, dotIdx)\n const rest = path.slice(dotIdx + 1)\n const nested = obj[head]\n if (!nested || typeof nested !== 'object' || Array.isArray(nested)) return []\n return getAtPath(nested as Record<string, unknown>, rest)\n }\n const val = obj[path]\n return val !== undefined ? [val] : []\n}\n\n/**\n * Mutate `obj` in-place, setting `value` at the nested `path`.\n * Supports dot notation (`'address.lineOne'`) but not array wildcards —\n * auto-translate on `contacts[].title` style paths is not supported.\n */\nexport function setAtPathInPlace(\n obj: Record<string, unknown>,\n path: string,\n value: unknown,\n): void {\n const dotIdx = path.indexOf('.')\n if (dotIdx !== -1) {\n const head = path.slice(0, dotIdx)\n const rest = path.slice(dotIdx + 1)\n const nested = obj[head]\n if (!nested || typeof nested !== 'object' || Array.isArray(nested)) return\n setAtPathInPlace(nested as Record<string, unknown>, rest, value)\n return\n }\n obj[path] = value\n}\n","/**\n * Per-layer i18n resolution policy.\n *\n * `onMissing` governs what happens when a multilingual field is resolved\n * to a target locale that is absent. It may be a single scalar policy or\n * a per-layer map, so a field can be lenient at the app read boundary but\n * strict inside a materialized view.\n *\n * Effective policy for layer `λ`:\n *\n * ```\n * explicit(λ) = typeof onMissing === 'object' ? onMissing[λ] : undefined\n * scalar = typeof onMissing === 'string' ? onMissing : undefined\n * policy(λ) = explicit(λ) ?? layerDefault(λ) ?? scalar ?? 'throw'\n * ```\n *\n * - `layerDefault('guard') = 'substitute'` — guards are lenient unless\n * EXPLICITLY overridden; they never inherit a scalar policy (a guard\n * reading a display value must not hard-fail on a missing locale).\n * - every other layer has no default, so it inherits the scalar, else\n * falls back to `'throw'` (today's behavior — zero breaking change).\n *\n * @public\n */\nexport type OnMissing = 'substitute' | 'null' | 'throw'\n\n/**\n * The contexts in which a multilingual field is resolved. Each can carry\n * its own `onMissing` policy.\n *\n * - `read` — ordinary app reads (`get`/`list`/query projection).\n * - `guard` — a guard callback reading a value.\n * - `join` — a joined record expanded onto a row.\n * - `mv` — materialized-view input.\n * - `derivation` — derivation input.\n * - `export` — bundle/cover export.\n */\nexport type Layer = 'read' | 'guard' | 'join' | 'mv' | 'derivation' | 'export'\n\n/** Field-level policy: a single scalar, or a per-layer map. */\nexport type OnMissingPolicy = OnMissing | Partial<Record<Layer, OnMissing>>\n\n/**\n * Resolve the effective `OnMissing` for a layer from a field's declared\n * policy. See module docs for the resolution rule.\n */\nexport function resolvePolicy(\n onMissing: OnMissingPolicy | undefined,\n layer: Layer,\n): OnMissing {\n const explicit =\n onMissing && typeof onMissing === 'object' ? onMissing[layer] : undefined\n const scalar = typeof onMissing === 'string' ? onMissing : undefined\n const layerDefault: OnMissing | undefined =\n layer === 'guard' ? 'substitute' : undefined\n return explicit ?? layerDefault ?? scalar ?? 'throw'\n}\n","/**\n * Per-locale script enforcement for `i18nText` fields (write-time).\n *\n * Each locale slot's string is validated against an allowed set of\n * Unicode scripts. `'auto'` infers the set from the locale code with\n * **asymmetric Latin tolerance**: every non-Latin-script locale\n * also allows `Latin`, because proper names and addresses in those\n * locales routinely embed Latin brand/building/technical names — while\n * Latin-script locales do NOT allow other scripts, so the common error\n * (e.g. Thai text dumped into an `en` slot) is still caught.\n *\n * The always-on baseline is `Common` (digits, punctuation), `Inherited`\n * and `Mark` (combining diacritics, joiners, harakat, tone marks), and\n * whitespace — so Latin digits and in-script combining marks never\n * false-reject.\n *\n * @public\n */\nimport { ScriptViolationError } from '../../kernel/errors.js'\nimport type { I18nTextDescriptor } from './core.js'\n\n/** Locales whose base language is written in the Latin script. */\nconst LATIN_BASE = new Set([\n 'en', 'fr', 'de', 'es', 'it', 'pt', 'nl', 'sv', 'no', 'da', 'fi', 'is',\n 'pl', 'cs', 'sk', 'hu', 'ro', 'hr', 'sl', 'et', 'lv', 'lt', 'tr', 'vi',\n 'id', 'ms', 'tl', 'sw', 'af', 'ca', 'gl', 'eu', 'cy', 'ga',\n])\n\n/** Base-language → primary (non-Latin) scripts. Latin is appended by inferScripts. */\nconst SCRIPT_TABLE: Record<string, readonly string[]> = {\n th: ['Thai'],\n ko: ['Hangul', 'Han'],\n ja: ['Han', 'Hiragana', 'Katakana'],\n zh: ['Han'],\n ar: ['Arabic'],\n fa: ['Arabic'],\n ur: ['Arabic'],\n ru: ['Cyrillic'],\n uk: ['Cyrillic'],\n bg: ['Cyrillic'],\n sr: ['Cyrillic'],\n he: ['Hebrew'],\n el: ['Greek'],\n hi: ['Devanagari'],\n ta: ['Tamil'],\n km: ['Khmer'],\n lo: ['Lao'],\n my: ['Myanmar'],\n}\n\n/** Map a BCP-47 script subtag (e.g. `Latn`, `Cyrl`) to allowed scripts. */\nconst SUBTAG_SCRIPTS: Record<string, readonly string[]> = {\n Latn: ['Latin'],\n Cyrl: ['Cyrillic', 'Latin'],\n Hans: ['Han', 'Latin'],\n Hant: ['Han', 'Latin'],\n Thai: ['Thai', 'Latin'],\n Arab: ['Arabic', 'Latin'],\n}\n\n/**\n * Infer the allowed Unicode scripts for a BCP-47 locale, with asymmetric\n * Latin tolerance. A script subtag (`th-Latn`) wins over the base\n * language. Unknown locales default to `['Latin']`.\n */\nexport function inferScripts(locale: string): readonly string[] {\n const parts = locale.split('-')\n const subtag = parts.find((t) => /^[A-Z][a-z]{3}$/.test(t))\n if (subtag && SUBTAG_SCRIPTS[subtag]) return SUBTAG_SCRIPTS[subtag]\n\n const base = (parts[0] ?? '').toLowerCase()\n if (LATIN_BASE.has(base)) return ['Latin']\n const primary = SCRIPT_TABLE[base]\n if (primary) return [...primary, 'Latin'] // asymmetric Latin tolerance\n return ['Latin']\n}\n\n/** Resolve the allowed scripts for a field's locale slot. */\nfunction allowedFor(descriptor: I18nTextDescriptor, locale: string): readonly string[] {\n const script = descriptor.options.script\n if (script && script !== 'auto') {\n const explicit = script[locale]\n if (explicit) return explicit\n }\n return inferScripts(locale)\n}\n\n/** Always-allowed baseline character classes (besides the named scripts). */\nconst BASELINE = String.raw`\\p{White_Space}\\p{Script=Common}\\p{Script=Inherited}\\p{Mark}`\n\n/** Build a whole-string matcher for the allowed scripts. */\nfunction fullMatcher(scripts: readonly string[]): RegExp {\n const cls = scripts.map((s) => `\\\\p{Script=${s}}`).join('')\n return new RegExp(`^[${BASELINE}${cls}]*$`, 'u')\n}\n\n/** Build a single-character matcher (for sampling / stripping). */\nfunction charMatcher(scripts: readonly string[]): RegExp {\n const cls = scripts.map((s) => `\\\\p{Script=${s}}`).join('')\n return new RegExp(`[${BASELINE}${cls}]`, 'u')\n}\n\n/** Collect a short sample of characters that violate the allowed scripts. */\nfunction offendingSample(str: string, scripts: readonly string[]): string {\n const ok = charMatcher(scripts)\n const bad: string[] = []\n for (const ch of str) {\n if (!ok.test(ch)) bad.push(ch)\n if (bad.length >= 8) break\n }\n return bad.join('')\n}\n\n/** Remove characters that violate the allowed scripts. */\nfunction stripDisallowed(str: string, scripts: readonly string[]): string {\n const ok = charMatcher(scripts)\n let out = ''\n for (const ch of str) if (ok.test(ch)) out += ch\n return out\n}\n\n/** A non-fatal script violation recorded under `'filter'`/`'warn'` modes. */\nexport interface ScriptWarning {\n readonly field: string\n readonly locale: string\n readonly expected: readonly string[]\n readonly sample: string\n}\n\n/**\n * Enforce a field's script constraint over an i18nText value map.\n *\n * - No `script` option ⇒ returns the value unchanged.\n * - `onScriptViolation: 'reject'` (default) ⇒ throws {@link ScriptViolationError}.\n * - `'filter'` ⇒ returns a copy with disallowed characters stripped + warnings.\n * - `'warn'` ⇒ returns the value unchanged + warnings.\n */\nexport function enforceScript(\n value: Record<string, unknown>,\n field: string,\n descriptor: I18nTextDescriptor,\n exempt?: ReadonlySet<string>,\n): { value: Record<string, unknown>; warnings: ScriptWarning[] } {\n const opt = descriptor.options\n if (!opt.script) return { value, warnings: [] }\n\n const mode = opt.onScriptViolation ?? 'reject'\n const warnings: ScriptWarning[] = []\n let out = value\n\n for (const [locale, raw] of Object.entries(value)) {\n if (exempt?.has(locale)) continue\n if (typeof raw !== 'string') continue\n const allowed = allowedFor(descriptor, locale)\n if (fullMatcher(allowed).test(raw)) continue\n\n const sample = offendingSample(raw, allowed)\n if (mode === 'reject') {\n throw new ScriptViolationError(field, locale, allowed, sample)\n }\n warnings.push({ field, locale, expected: allowed, sample })\n if (mode === 'filter') {\n if (out === value) out = { ...value }\n out[locale] = stripDisallowed(raw, allowed)\n }\n }\n\n return { value: out, warnings }\n}\n","/**\n * The i18n `ViaBinding` — wires the i18n engine (auto-translate/script\n * enforcement/validation/densify on write; locale + dict-label presentation\n * on read) into the kernel's generic Via port. Mirrors\n * `via/money/binding.ts`'s #553 static-link pattern.\n *\n * LIVE (#623 Task 8 wired the cutover): `i18nBinding()`/`linkI18nVia()` are\n * the real put/read path for every i18n-declaring collection —\n * `collection.ts`'s `_putInternal`/`applyLocaleToRecord` (the call sites\n * this file's bodies were moved/adapted from) now delegate their i18n\n * stages to `this.via.encodeWrite`/`this.via.present` instead of running\n * the hand-wired i18n logic inline.\n *\n * `i18nText()`, `dictKey()`, `staticDict()` each call {@link linkI18nVia}\n * first — the same #553 pattern `money()` uses.\n */\nimport type { ViaBinding, ViaWriteCtx, ViaReadCtx } from '../../kernel/via/index.js'\nimport { installViaBinder } from '../../kernel/via/index.js'\nimport type { I18nTextDescriptor } from './core.js'\nimport { stripI18nFilled } from './core.js'\nimport type { DictKeyDescriptor, StaticDictDescriptor } from './dictionary.js'\nimport type { I18nStrategy } from '../../port/with/i18n-strategy.js'\nimport { isStaticDictDescriptor } from '../../port/with/i18n-strategy.js'\nimport { resolvePolicy, type Layer } from './policy.js'\nimport { getAtPath, setAtPathInPlace } from '../../kernel/paths.js'\nimport { TranslatorNotConfiguredError, LocaleNotSpecifiedError } from '../../kernel/errors.js'\n\n/**\n * Config a collection's i18n declarations resolve to — the binding's\n * construction input. Fields are loosely typed (`unknown`) at this seam\n * because the kernel's `ViaBinder` contract is opaque-config-in; the\n * concrete i18n types are applied inside the binding's own functions.\n */\nexport interface I18nViaConfig {\n i18nFields?: Record<string, unknown> // I18nTextDescriptor map\n dictKeyFields?: Record<string, unknown> // DictKeyDescriptor | StaticDictDescriptor map\n i18nDensifyFields?: Record<string, unknown> // I18nTextDescriptor subset (densifyOnWrite: true)\n strategy: unknown // I18nStrategy (real or NO_I18N)\n defaultLocale?: string\n autoTranslateHook?: (...args: unknown[]) => Promise<string>\n dictLabelResolver?: (...args: unknown[]) => Promise<string | undefined>\n i18nPutValidator?: (record: unknown) => void // the vault-built closure (unchanged wiring)\n collectionName: string\n}\n\n// ─── write pipeline ─────────────────────────────────────────────────────\n\n/**\n * Auto-translate missing i18nText translations. Runs BEFORE i18n\n * validation so translated values satisfy the required-locale constraint.\n * Throws `TranslatorNotConfiguredError` when a field has\n * `autoTranslate: true` but no hook was configured. Mutates `record`\n * in place (mirrors `collection.ts:1830-1874`).\n */\nasync function runI18nAutoTranslate(\n record: Record<string, unknown>,\n i18nFields: Record<string, I18nTextDescriptor>,\n cfg: I18nViaConfig,\n): Promise<void> {\n for (const [field, descriptor] of Object.entries(i18nFields)) {\n if (!descriptor.options.autoTranslate) continue\n // getAtPath returns [] for array-wildcard paths — auto-translate on\n // 'contacts[].field' style paths is not supported; skip silently.\n const leafValues = getAtPath(record, field)\n if (leafValues.length !== 1) continue\n const value = leafValues[0]\n if (!value || typeof value !== 'object' || Array.isArray(value)) continue\n const map = value as Record<string, string>\n // Determine which locales need translation. For 'all', translate all\n // declared languages that are missing. For 'any', only translate if\n // none are present. For string[], translate the listed required ones.\n const { languages, required } = descriptor.options\n const missing: string[] = languages.filter(\n (lang) => !(lang in map) || map[lang] === '',\n )\n if (missing.length === 0) continue\n // Find a source locale (first present non-empty value)\n const sourceLocale = languages.find((l) => l in map && map[l] !== '')\n if (!sourceLocale) continue\n if (!cfg.autoTranslateHook) {\n throw new TranslatorNotConfiguredError(field, cfg.collectionName)\n }\n // Only translate locales that are actually needed\n const toTranslate =\n required === 'any'\n ? [] // 'any' is already satisfied since sourceLocale exists\n : required === 'all'\n ? missing\n : missing.filter((l) => required.includes(l))\n const translated = { ...map }\n for (const targetLocale of toTranslate) {\n translated[targetLocale] = await cfg.autoTranslateHook(\n map[sourceLocale]!,\n sourceLocale,\n targetLocale,\n field,\n cfg.collectionName,\n )\n }\n setAtPathInPlace(record, field, translated)\n }\n}\n\n/**\n * i18nText script enforcement — runs AFTER auto-translate (so generated\n * values are checked too). Throws `ScriptViolationError` (from inside\n * `strategy.enforceScript`) under the default 'reject'; 'filter' strips\n * disallowed chars in place; 'warn' leaves the value unchanged. Mirrors\n * `collection.ts:1896-1927`.\n */\nfunction runI18nScriptEnforcement(\n record: Record<string, unknown>,\n i18nFields: Record<string, I18nTextDescriptor>,\n strategy: I18nStrategy,\n exemptFills: Map<string, Set<string>> | undefined,\n ctx: ViaWriteCtx,\n cfg: I18nViaConfig,\n): void {\n for (const [field, descriptor] of Object.entries(i18nFields)) {\n if (!descriptor.options.script) continue\n for (const leaf of getAtPath(record, field)) {\n if (!leaf || typeof leaf !== 'object' || Array.isArray(leaf)) continue\n const leafMap = leaf as Record<string, unknown>\n const { value: cleaned, warnings } = strategy.enforceScript(\n leafMap,\n field,\n descriptor,\n exemptFills?.get(field),\n )\n if (cleaned !== leafMap) Object.assign(leafMap, cleaned)\n // enforceScript only returns warnings under 'warn'/'filter' ('reject'\n // throws first), so this guard never fires — it makes that invariant\n // explicit and keeps `mode` off the optional-undefined type.\n const mode = descriptor.options.onScriptViolation\n if (mode === 'warn' || mode === 'filter') {\n for (const w of warnings) {\n // Exact original payload shape (collection.ts:1916-1922 pre-cutover).\n ctx.emit('i18n:script-violation', {\n vault: ctx.vault,\n collection: cfg.collectionName,\n id: ctx.id,\n mode,\n warning: w,\n })\n }\n }\n }\n }\n}\n\n/**\n * `encodeWrite` — translate → script → validate → densify, in the EXACT\n * order `_putInternal` runs them today (seam-map Part 2, stages 7-11).\n */\nasync function runI18nWriteStages(\n record: Record<string, unknown>,\n ctx: ViaWriteCtx,\n cfg: I18nViaConfig,\n): Promise<Record<string, unknown>> {\n const i18nFields = cfg.i18nFields as Record<string, I18nTextDescriptor> | undefined\n const i18nDensifyFields = cfg.i18nDensifyFields as Record<string, I18nTextDescriptor> | undefined\n const strategy = cfg.strategy as I18nStrategy\n\n // 1. Auto-translate.\n if (i18nFields) {\n await runI18nAutoTranslate(record, i18nFields, cfg)\n }\n\n // 2. densifyOnWrite: read prior fills so a round-tripped derived copy is\n // exempt from script enforcement and can be refreshed. Read once here,\n // reused by densify() below. `ctx.prior()` resolves the real prior\n // record (collection.ts wires it to `resolveDensifyPrior`, #623 Task 8).\n let densifyPrior: Record<string, unknown> | undefined\n let exemptFills: Map<string, Set<string>> | undefined\n if (i18nDensifyFields) {\n densifyPrior = (await ctx.prior()) ?? undefined\n exemptFills = strategy.computeExemptFills(densifyPrior, record, i18nDensifyFields)\n }\n\n // 3. Script enforcement.\n if (i18nFields) {\n runI18nScriptEnforcement(record, i18nFields, strategy, exemptFills, ctx, cfg)\n }\n\n // 4. i18nText validation — AFTER auto-translate + script so the record is\n // trustworthy. Throws MissingTranslationError when required translations\n // are absent. The vault-built closure (unchanged wiring).\n cfg.i18nPutValidator?.(record)\n\n // 5. Eager-fill empty slots + record provenance. Runs AFTER the authored\n // gates (required + script) so only authored slots are validated.\n if (i18nDensifyFields) {\n strategy.densify(record, densifyPrior, i18nDensifyFields)\n }\n\n return record\n}\n\n// ─── read pipeline ──────────────────────────────────────────────────────\n\n/**\n * `present` — i18nText locale resolution + dictKey/staticDict label\n * resolution + `_i18nFilled` stripping. Adapted from\n * `applyLocaleToRecord`'s i18n+dict+strip portions (`collection.ts:4184-\n * 4301`) — the money-decode portion of that method is a separate binding\n * (`via/money`) and is NOT this function's concern.\n */\nasync function runI18nPresent(\n record: Record<string, unknown>,\n ctx: ViaReadCtx,\n cfg: I18nViaConfig,\n): Promise<Record<string, unknown>> {\n const i18nFields = cfg.i18nFields as Record<string, I18nTextDescriptor> | undefined\n const dictKeyFields = cfg.dictKeyFields as Record<string, DictKeyDescriptor | StaticDictDescriptor> | undefined\n const strategy = cfg.strategy as I18nStrategy\n const hasI18n = i18nFields !== undefined && Object.keys(i18nFields).length > 0\n const hasDict = dictKeyFields !== undefined && Object.keys(dictKeyFields).length > 0\n if (!hasI18n && !hasDict) return record\n\n const locale = typeof ctx.locale === 'string' ? ctx.locale : undefined\n const fallback = ctx.fallback as string | readonly string[] | undefined\n const layer = ctx.layer as Layer\n\n let result = record\n\n // i18nText / dictKey resolution require an active locale — EXCEPT a\n // static dict declaring a `displayLocale`, which resolves its\n // `<field>Label` even under a locale-less read (the hybrid hinge). Only\n // this second gate relaxes, and ONLY for static-display fields — folding\n // `hasI18n` in here would let an i18nText-only collection fall through to\n // applyI18nLocale(…, undefined) on a locale-less read, breaking the\n // raw-{th,en}-map invariant.\n const hasStaticDisplay =\n hasDict &&\n dictKeyFields !== undefined &&\n Object.values(dictKeyFields).some(\n (d) => isStaticDictDescriptor(d) && d.displayLocale !== undefined,\n )\n\n // Strip the internal densify marker even when no locale is active\n // (applyI18nLocale, which normally strips it, is skipped on this path).\n // Non-mutating: never touches the cached/stored record object.\n if (!locale && !hasStaticDisplay) return stripI18nFilled(result)\n\n // 1. i18nText resolution — guarded on `locale`, because the relaxed gate\n // above can now be entered with `locale === undefined` (static-display).\n // The layer selects the field's per-layer `onMissing` policy inside\n // applyI18nLocale.\n if (locale && hasI18n && i18nFields) {\n result = strategy.applyI18nLocale(result, i18nFields, locale, fallback, layer)\n }\n\n // 2. dictKey / staticDict label resolution\n if (hasDict && dictKeyFields && cfg.dictLabelResolver && locale !== 'raw') {\n const withLabels = { ...result }\n const resolver = cfg.dictLabelResolver\n for (const [field, desc] of Object.entries(dictKeyFields)) {\n // dictKey default policy is 'null' (omit/null on miss) — today's\n // behavior — unless the field declares onMissing. 'substitute'\n // walks the declared substitute chain (passed as the resolver's\n // fallback); 'throw' raises LocaleNotSpecifiedError.\n const policy = desc.onMissing ? resolvePolicy(desc.onMissing, layer) : 'null'\n const fieldFallback =\n policy === 'substitute'\n ? (fallback ?? desc.substitute)\n : fallback\n // Per-field effective locale: a static dict falls back to its\n // `displayLocale` when no locale is active (the hybrid hinge); a\n // plain dictKey with no displayLocale gets `undefined` → its\n // <field>Label is omitted on a locale-less read (today's behavior).\n const effLocale =\n locale ??\n (isStaticDictDescriptor(desc) ? desc.displayLocale : undefined)\n // Resolve one key → label | null, honoring the policy. With no\n // effective locale there is nothing to resolve against.\n const resolveKey = async (key: string): Promise<string | null> => {\n if (!effLocale) {\n if (policy === 'throw') {\n throw new LocaleNotSpecifiedError(\n field,\n `dictKey \"${field}\": no locale active to resolve key \"${key}\".`,\n )\n }\n return null\n }\n const label = await resolver(desc.name, key, effLocale, fieldFallback)\n if (label === undefined) {\n if (policy === 'throw') {\n throw new LocaleNotSpecifiedError(\n field,\n `dictKey \"${field}\": no label for key \"${key}\" in locale \"${effLocale}\".`,\n )\n }\n return null\n }\n return label\n }\n\n if (field.includes('[].')) {\n // Wildcard path `arrayKey[].leaf`: add a per-element sibling\n // `<leaf>Label`. Single level + simple leaf.\n const parts = field.split('[].')\n const arrayKey = parts[0]!\n const leaf = parts[1]\n if (!leaf || leaf.includes('.')) continue\n const arr = (withLabels as Record<string, unknown>)[arrayKey]\n if (!Array.isArray(arr)) continue\n const labelKey = `${leaf}Label`\n ;(withLabels as Record<string, unknown>)[arrayKey] = await Promise.all(\n arr.map(async (el) => {\n if (!el || typeof el !== 'object' || Array.isArray(el)) return el\n const k = (el as Record<string, unknown>)[leaf]\n if (typeof k !== 'string') return el\n return { ...(el as Record<string, unknown>), [labelKey]: await resolveKey(k) }\n }),\n )\n continue\n }\n\n const val = result[field]\n if (Array.isArray(val)) {\n // Array-of-keys → [{ key, label }] pair objects (key preserved).\n withLabels[`${field}Label`] = await Promise.all(\n val.map(async (k) => ({\n key: k,\n label: typeof k === 'string' ? await resolveKey(k) : null,\n })),\n )\n } else if (typeof val === 'string') {\n const label = await resolveKey(val)\n // Scalar under 'null'/default omits the label key (today's\n // behavior); 'substitute' returns a value; 'throw' threw above.\n if (label !== null) withLabels[`${field}Label`] = label\n }\n }\n result = withLabels\n }\n\n // Final guard: the locale-less static-display path skips\n // applyI18nLocale's strip, so ensure the densify marker never leaks here\n // either. Non-mutating (no-op when absent or already stripped above).\n return stripI18nFilled(result)\n}\n\n// ─── introspection ──────────────────────────────────────────────────────\n\nfunction buildI18nDescribeFragment(cfg: I18nViaConfig): Record<string, unknown> {\n return {\n i18nFields: cfg.i18nFields ? Object.keys(cfg.i18nFields) : [],\n dictKeyFields: cfg.dictKeyFields ? Object.keys(cfg.dictKeyFields) : [],\n ...(cfg.defaultLocale !== undefined ? { defaultLocale: cfg.defaultLocale } : {}),\n }\n}\n\n// ─── binding ────────────────────────────────────────────────────────────\n\nexport function i18nBinding(cfg: I18nViaConfig): ViaBinding {\n return {\n brand: 'i18n',\n posture: { encryptedAtRest: 'envelope', queryable: 'full', exportable: true, forgettable: true },\n // DictionaryHandle's `_dict_*` reserved collections (#629 Task 4) — the\n // codec boundary's `reservedEnvelopes` door may address any collection\n // name under this prefix.\n reservedPrefixes: ['_dict_'],\n covers: (field) =>\n (cfg.i18nFields !== undefined && field in cfg.i18nFields)\n || (cfg.dictKeyFields !== undefined && field in cfg.dictKeyFields),\n encodeWrite: async (record, ctx) => runI18nWriteStages(record, ctx, cfg),\n present: async (record, ctx) => runI18nPresent(record, ctx, cfg),\n describeFragment: () => buildI18nDescribeFragment(cfg),\n }\n}\n\nexport function linkI18nVia(): void {\n installViaBinder('i18n', (c) => i18nBinding(c as I18nViaConfig))\n}\n","/**\n * i18nText schema type —\n *\n * `i18nText({ languages, required })` creates a descriptor for a\n * multi-language content field whose value is stored as a\n * `{ [locale]: string }` map (e.g. `{ en: 'Consulting', th: 'ที่ปรึกษา' }`).\n *\n * On put, the descriptor validates that required languages are present.\n * On read (when a `locale` option is passed), the map is collapsed to the\n * caller's locale string via the fallback chain.\n *\n * Design decisions\n * ────────────────\n *\n * **Descriptor pattern (not a Zod type).**\n * `i18nText()` returns a plain descriptor object used in the collection's\n * `i18nFields` option — same pattern as `ref()` / `dictKey()`. This keeps\n * `@noy-db/core` at zero runtime dependencies and avoids Zod v3 field-type\n * constraints. TypeScript inference is handled via the descriptor's type.\n *\n * **Enforcement at the collection boundary.**\n * The `required` option is checked by `Collection.put()` via the compartment's\n * registered `i18nFields`. Failed validation throws `MissingTranslationError`\n * — a distinct class from `SchemaValidationError` so callers can tell\n * \"wrong shape\" from \"missing translations\".\n *\n * **Resolution is post-decryption.**\n * Locale resolution happens AFTER `decryptRecord()`, as a pure in-memory\n * transform. No additional crypto work is needed. The resolved record is\n * returned in place of the stored one, with i18nText fields replaced by\n * their locale-resolved strings.\n *\n * **`locale: 'raw'`.**\n * Passing `{ locale: 'raw' }` skips resolution and returns the full\n * `{ [locale]: string }` map — useful for bilingual exports, admin UIs,\n * and any context where all translations must be visible at once.\n *\n * **Out of scope.**\n * Pluralization, RTL rendering, date/number formatting, per-locale CRDT\n * merging.\n */\n\nimport { MissingTranslationError, LocaleNotSpecifiedError } from '../../kernel/errors.js'\nimport type { OnMissing, OnMissingPolicy, Layer } from './policy.js'\nimport { resolvePolicy } from './policy.js'\nimport { inferScripts } from './script.js'\nimport { linkI18nVia } from './binding.js'\n\n// ─── I18nMap type helper ───────────────────────────────────────────────\n\n/** Flatten an intersection into a single object literal for nicer hovers. */\ntype Prettify<T> = { [K in keyof T]: T[K] } & {}\n\n/**\n * The stored shape of a multilingual field, inferred from its `required`\n * mode — so the compiler forces you to handle an absent optional locale\n * (`string | undefined`) instead of silently yielding `undefined`.\n *\n * Mirrors `i18nText({ languages, required })`:\n * - `'all'` (default) — every locale required: `{ th: string; en: string }`\n * - `'any'` — every locale optional: `{ th?: string; en?: string }`\n * (the \"at least one present\" guarantee is runtime-only — not expressible\n * in TypeScript — so each key is optional)\n * - `readonly L[]` — listed locales required, the rest optional:\n * `I18nMap<'th'|'en', ['th']>` → `{ th: string; en?: string }`\n *\n * @example\n * ```ts\n * type Lang = 'th' | 'en'\n * interface Contact {\n * name: I18nMap<Lang, 'any'> // { th?: string; en?: string }\n * legalName: I18nMap<Lang, ['th']> // { th: string; en?: string }\n * slug: I18nMap<Lang> // { th: string; en: string }\n * }\n * ```\n *\n * @public\n */\nexport type I18nMap<\n Langs extends string,\n Required extends 'all' | 'any' | readonly Langs[] = 'all',\n> = Required extends 'all'\n ? Record<Langs, string>\n : Required extends 'any'\n ? Partial<Record<Langs, string>>\n : Required extends readonly (infer R extends Langs)[]\n ? Prettify<Record<R, string> & Partial<Record<Exclude<Langs, R>, string>>>\n : never\n\n// ─── i18nText descriptor ───────────────────────────────────────────────\n\n/**\n * Options for `i18nText()`.\n *\n * `languages` declares the full set of supported locales. `required`\n * controls which must be present on every `put()`.\n *\n * `autoTranslate` is the per-field opt-in for the `plaintextTranslator`\n * hook. When `true` and a `plaintextTranslator` is configured\n * on `createNoydb()`, missing translations are generated before `put()`.\n * Default: `false`.\n */\nexport interface I18nTextOptions {\n /** All supported locale codes (BCP 47). */\n readonly languages: readonly string[]\n /**\n * Which locales must be present on every `put()`.\n *\n * - `'all'` — every declared language must be present.\n * - `'any'` — at least one declared language must be present.\n * - `string[]` — listed locales are required; others are optional.\n */\n readonly required: 'all' | 'any' | readonly string[]\n /**\n * Per-field opt-in for the `plaintextTranslator` hook.\n * When `true`, missing required translations are auto-generated\n * before `put()` if a translator is configured. Default: `false`.\n */\n readonly autoTranslate?: boolean\n /**\n * What to do when this field is resolved to a locale that is absent.\n * A single policy, or a per-layer map (read/guard/join/mv/derivation/\n * export). Default `'throw'` — today's behavior, zero breaking change.\n * See {@link OnMissingPolicy}.\n *\n * NOTE (current wiring): ALL layers are enforced — `read` (`get`/`list`),\n * `guard`, `derivation`, `mv`, `join`, `export`. Guard / derivation\n * `ctx.vault` reads resolve under their own layer policy (`guard` defaults to\n * the lenient `'substitute'`). The `mv` layer fires for materialized views\n * that declare `{ i18nLocale, i18nFields }` — UNION (group-key i18n fields\n * resolve before the unified-row bucketing) and query-form (resolved in\n * `GroupedReduction.run` before `groupAndReduce`); grouping a raw i18n field\n * without a locale throws. The `join` layer resolves a joined right-side i18n\n * field to the query locale (`toArray({ locale })` or the vault default; raw\n * when locale-less). The `export` layer fires for\n * `exportStream`/`exportJSON({ resolveLabels })` — records collapse to the\n * export locale.\n */\n readonly onMissing?: OnMissingPolicy\n /**\n * Ordered preferred-substitute locales used when `onMissing` resolves\n * to `'substitute'` and the target locale is absent. `'any'` as an\n * element means \"first non-empty value\". A caller-supplied `fallback`\n * at read time takes precedence over this declared list.\n */\n readonly substitute?: readonly string[]\n /**\n * Smart-substitute. When `true`, a missing-locale `substitute` walk that\n * misses the explicit chain prefers the available locale whose script is\n * nearest the target (same script, then Latin) rather than an arbitrary value\n * — e.g. a missing Thai label prefers another Thai (or Latin) translation over\n * an unreadable script. Default `false` (legacy first-non-empty behavior).\n */\n readonly smartSubstitute?: boolean\n /**\n * Per-locale script enforcement (write-time). `'auto'` infers the\n * allowed Unicode scripts per locale (asymmetric Latin tolerance); an\n * object overrides per slot. Absent ⇒ no check. See `./script.ts`.\n */\n readonly script?: 'auto' | Partial<Record<string, readonly string[]>>\n /**\n * What to do when a slot's value contains characters outside its\n * allowed script set. Default `'reject'`.\n */\n readonly onScriptViolation?: 'reject' | 'filter' | 'warn'\n /**\n * Eager-fill empty locale slots from the substitute chain at\n * write time, recording provenance in the internal `_i18nFilled` marker.\n * Mutually exclusive with an EXPLICIT `'throw'` onMissing policy (densify\n * fills every hole, so a throw would be unreachable). Without an explicit\n * `substitute`, fills from `'any'` (first non-empty). Default absent.\n */\n readonly densifyOnWrite?: boolean\n}\n\n/**\n * Descriptor returned by `i18nText()`. Attach to the collection's\n * `i18nFields` option:\n *\n * ```ts\n * const lineItems = company.collection<LineItem>('line-items', {\n * i18nFields: {\n * description: i18nText({ languages: ['en', 'th'], required: 'all' }),\n * },\n * })\n * ```\n */\nexport interface I18nTextDescriptor {\n readonly _noydbI18nText: true\n /** Via port brand marker — lets an `I18nTextDescriptor` satisfy the kernel's opaque `ViaDescriptor` (#623 Task 9). */\n readonly _viaBrand: 'i18n'\n readonly options: I18nTextOptions\n}\n\n/**\n * Create an `I18nTextDescriptor` for a multi-language content field.\n *\n * @param options Language list + enforcement mode.\n *\n * @example\n * ```ts\n * i18nText({ languages: ['en', 'th'], required: 'all' })\n * i18nText({ languages: ['en', 'th'], required: ['th'], autoTranslate: true })\n * ```\n */\nexport function i18nText(options: I18nTextOptions): I18nTextDescriptor {\n // The declaration is the Via binding's opt-in unit (#553): constructing\n // a descriptor statically links the i18n binding into the kernel's Via\n // port, so every later kernel consultation finds it already installed.\n linkI18nVia()\n if (options.densifyOnWrite === true && hasThrowPolicy(options.onMissing)) {\n throw new Error(\n `i18nText: densifyOnWrite cannot be combined with an explicit onMissing 'throw' ` +\n `policy — densify fills every empty slot, so a 'throw' would be unreachable. ` +\n `Remove the 'throw' policy or disable densifyOnWrite.`,\n )\n }\n return { _noydbI18nText: true, _viaBrand: 'i18n', options }\n}\n\n/** True when `onMissing` declares `'throw'` for any layer (scalar or per-layer). */\nfunction hasThrowPolicy(onMissing: OnMissingPolicy | undefined): boolean {\n if (onMissing === undefined) return false\n if (typeof onMissing === 'string') return onMissing === 'throw'\n return Object.values(onMissing).includes('throw')\n}\n\n// `isI18nTextDescriptor` now lives on the kernel port (#623 Task 11,\n// port/with/i18n-strategy.ts, alongside `isStaticDictDescriptor`) —\n// re-exported here for compat with existing importers of this module.\nexport { isI18nTextDescriptor } from '../../port/with/i18n-strategy.js'\n\n// ─── Validation helpers ────────────────────────────────────────────────\n\n/**\n * Validate that a value is a valid `{ [locale]: string }` map and that\n * all required locales are present. Throws `MissingTranslationError`\n * when the required constraint is violated.\n *\n * Called by `Collection.put()` for each registered `i18nField`.\n *\n * @param value The raw field value from the record being put.\n * @param field The field name (used in the thrown error message).\n * @param descriptor The `i18nText()` descriptor for this field.\n */\nexport function validateI18nTextValue(\n value: unknown,\n field: string,\n descriptor: I18nTextDescriptor,\n): void {\n const { options } = descriptor\n\n // Must be a non-null object\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new MissingTranslationError(\n field,\n options.languages,\n `Field \"${field}\" must be a { [locale]: string } map, got ${typeof value}.`,\n )\n }\n\n const map = value as Record<string, unknown>\n\n // All values must be strings\n for (const [locale, v] of Object.entries(map)) {\n if (typeof v !== 'string') {\n throw new MissingTranslationError(\n field,\n [locale],\n `Field \"${field}\": locale \"${locale}\" must be a string, got ${typeof v}.`,\n )\n }\n }\n\n // Check required constraint\n const { required } = options\n if (required === 'all') {\n const missing = options.languages.filter(\n (lang) => !(lang in map) || map[lang] === '',\n )\n if (missing.length > 0) {\n throw new MissingTranslationError(\n field,\n missing,\n `Field \"${field}\" requires all declared languages. Missing: ${missing.join(', ')}.`,\n )\n }\n } else if (required === 'any') {\n const present = options.languages.some(\n (lang) => lang in map && map[lang] !== '',\n )\n if (!present) {\n throw new MissingTranslationError(\n field,\n options.languages,\n `Field \"${field}\" requires at least one declared language. None present.`,\n )\n }\n } else {\n // string[] — named required locales; TypeScript narrows required to readonly string[]\n const requiredList = required\n const missing = requiredList.filter(\n (lang) => !(lang in map) || map[lang] === '',\n )\n if (missing.length > 0) {\n throw new MissingTranslationError(\n field,\n missing,\n `Field \"${field}\" requires: ${requiredList.join(', ')}. Missing: ${missing.join(', ')}.`,\n )\n }\n }\n}\n\n// ─── Locale resolution ─────────────────────────────────────────────────\n\n/**\n * Resolve an i18nText value (`{ [locale]: string }` map) to a string\n * for the given locale.\n *\n * @param value The stored locale map.\n * @param locale The requested locale code, or `'raw'` to return the map.\n * @param fallback Single locale or ordered list; use `'any'` as the last\n * element to fall back to any available translation.\n * @param field Field name used in `LocaleNotSpecifiedError` messages.\n * @returns The resolved string, OR the original map when `locale === 'raw'`.\n */\n/** Options for the policy-aware form of {@link resolveI18nText}. */\nexport interface ResolveI18nOptions {\n /** Effective policy for the resolution layer. Default `'throw'`. */\n readonly policy?: OnMissing\n /** Declared substitute chain; applied only under policy `'substitute'`. */\n readonly substitute?: readonly string[]\n /**\n * Smart-substitute. When `true` and policy is `'substitute'`, after the\n * explicit chain misses, pick the available locale whose script is nearest the\n * target (same script first, then Latin's broad readability) instead of an\n * arbitrary value. Default `false`.\n */\n readonly smartSubstitute?: boolean\n}\n\n/** Normalize a single-or-list fallback into an array. */\nfunction toChain(fallback: string | readonly string[] | undefined): readonly string[] {\n return Array.isArray(fallback) ? fallback : fallback ? [fallback as string] : []\n}\n\n/** Walk a chain, returning the first non-empty value (or `'any'` match). */\nfunction pickFromChain(\n value: Record<string, string>,\n chain: readonly string[],\n): string | undefined {\n for (const fb of chain) {\n if (fb === 'any') {\n const any = Object.values(value).find((v) => v !== '')\n if (any !== undefined) return any\n } else if (value[fb] !== undefined && value[fb] !== '') {\n return value[fb]\n }\n }\n return undefined\n}\n\n// Legacy 4-arg form: can only throw or return — never null. Keeps every\n// existing call site's type unchanged (default policy is 'throw').\nexport function resolveI18nText(\n value: Record<string, string>,\n locale: string,\n fallback?: string | readonly string[],\n field?: string,\n): string | Record<string, string>\n// Policy-aware form: may return null under 'null'/'substitute' policies.\nexport function resolveI18nText(\n value: Record<string, string>,\n locale: string,\n fallback: string | readonly string[] | undefined,\n field: string | undefined,\n opts: ResolveI18nOptions,\n): string | Record<string, string> | null\nexport function resolveI18nText(\n value: Record<string, string>,\n locale: string,\n fallback?: string | readonly string[],\n field?: string,\n opts?: ResolveI18nOptions,\n): string | Record<string, string> | null {\n if (locale === 'raw') {\n return value\n }\n\n if (!locale) {\n throw new LocaleNotSpecifiedError(field ?? '<unknown>')\n }\n\n // Primary locale\n if (value[locale] !== undefined && value[locale] !== '') {\n return value[locale]\n }\n\n const policy: OnMissing = opts?.policy ?? 'throw'\n\n // Caller-supplied fallback ALWAYS applies first (backward compat +\n // explicit read-time override), regardless of policy.\n const callerChain = toChain(fallback)\n const callerHit = pickFromChain(value, callerChain)\n if (callerHit !== undefined) return callerHit\n\n // Declared substitute applies ONLY under policy 'substitute'.\n if (policy === 'substitute') {\n const subHit = pickFromChain(value, toChain(opts?.substitute))\n if (subHit !== undefined) return subHit\n // Smart-substitute: after the explicit chain, prefer the script-nearest\n // available locale over an arbitrary first-non-empty value.\n if (opts?.smartSubstitute) {\n const smartHit = pickNearestScript(value, locale)\n if (smartHit !== undefined) return smartHit\n }\n }\n\n // Exhausted.\n if (policy === 'throw') {\n throw new LocaleNotSpecifiedError(\n field ?? '<unknown>',\n `No translation available for locale \"${locale}\"` +\n (callerChain.length > 0 ? ` or fallback chain [${callerChain.join(', ')}]` : '') +\n '.',\n )\n }\n return null\n}\n\n/**\n * Smart-substitute: among the non-empty locales in `value`, pick the one\n * whose primary script is nearest the target `locale` — same script first, then\n * Latin (broadly readable), then any other — so a missing Thai label falls back\n * to another Thai (or Latin) value rather than, say, an Arabic one. First-seen\n * wins on ties. Returns the value string, or `undefined` when `value` has no\n * non-empty entry.\n */\nfunction pickNearestScript(value: Record<string, string>, target: string): string | undefined {\n const targetScript = inferScripts(target)[0] ?? 'Latin'\n let best: { score: number; v: string } | undefined\n for (const [loc, v] of Object.entries(value)) {\n if (typeof v !== 'string' || v === '') continue\n const s = inferScripts(loc)[0] ?? 'Latin'\n const score = s === targetScript ? 0 : s === 'Latin' ? 1 : 2\n if (best === undefined || score < best.score) best = { score, v }\n if (score === 0) break // nothing beats a same-script match\n }\n return best?.v\n}\n\n// ─── Path helpers (nested i18nFields like 'address.lineOne') ──────────\n\n// `getAtPath`/`setAtPathInPlace` are generic dotted-path/[]-wildcard record\n// helpers, not i18n logic — moved to `kernel/paths.ts` (Task 7, #623).\n// `getAtPath` re-exported here for compat with existing importers of this\n// module (embeddings/descriptor.ts, search/build-docs.ts); `setAtPathInPlace`\n// is not re-exported — its only consumer (via-i18n/binding.ts) imports it\n// directly from kernel/paths.ts.\nexport { getAtPath } from '../../kernel/paths.js'\n\n/** Recursively resolve i18nText at a single path within a record copy. */\nfunction applyAtPath(\n obj: Record<string, unknown>,\n path: string,\n locale: string,\n fallback: string | readonly string[] | undefined,\n opts: ResolveI18nOptions,\n): Record<string, unknown> {\n const arrayIdx = path.indexOf('[].')\n if (arrayIdx !== -1) {\n const arrayKey = path.slice(0, arrayIdx)\n const restPath = path.slice(arrayIdx + 3)\n const arr = obj[arrayKey]\n if (!Array.isArray(arr)) return obj\n return {\n ...obj,\n [arrayKey]: arr.map(item => {\n if (!item || typeof item !== 'object' || Array.isArray(item)) return item\n return applyAtPath(item as Record<string, unknown>, restPath, locale, fallback, opts)\n }),\n }\n }\n const dotIdx = path.indexOf('.')\n if (dotIdx !== -1) {\n const head = path.slice(0, dotIdx)\n const rest = path.slice(dotIdx + 1)\n const nested = obj[head]\n if (!nested || typeof nested !== 'object' || Array.isArray(nested)) return obj\n return {\n ...obj,\n [head]: applyAtPath(nested as Record<string, unknown>, rest, locale, fallback, opts),\n }\n }\n const raw = obj[path]\n if (raw === undefined || raw === null) return obj\n if (typeof raw !== 'object' || Array.isArray(raw)) return obj\n return {\n ...obj,\n [path]: resolveI18nText(raw as Record<string, string>, locale, fallback, path, opts),\n }\n}\n\n/**\n * Apply locale resolution to a single record, returning a new copy.\n *\n * For each field registered as an `i18nText` descriptor:\n * - If `locale === 'raw'`, the field value is left as the stored map.\n * - Otherwise, the field value is replaced with the resolved string.\n *\n * Field paths support dot notation (`'address.lineOne'`) and array\n * wildcards (`'contacts[].title'`). Top-level fields work as before.\n *\n * @param record The decrypted record.\n * @param i18nFields Map of field path → `I18nTextDescriptor`.\n * @param locale The requested locale (or `'raw'`).\n * @param fallback Fallback chain (optional).\n * @param layer Resolution layer (default `'read'`). Each field's\n * `onMissing` policy is resolved for this layer, so the\n * same record resolves leniently on a get but strictly\n * inside an mv/derivation.\n */\nexport function applyI18nLocale(\n record: Record<string, unknown>,\n i18nFields: Record<string, I18nTextDescriptor>,\n locale: string,\n fallback?: string | readonly string[],\n layer: Layer = 'read',\n): Record<string, unknown> {\n const fieldNames = Object.keys(i18nFields)\n if (fieldNames.length === 0) return record\n\n let result = record\n\n for (const [field, descriptor] of Object.entries(i18nFields)) {\n const { onMissing, substitute, smartSubstitute } = descriptor.options\n const opts: ResolveI18nOptions = {\n policy: resolvePolicy(onMissing, layer),\n ...(substitute !== undefined ? { substitute } : {}),\n ...(smartSubstitute ? { smartSubstitute } : {}),\n }\n result = applyAtPath(result, field, locale, fallback, opts)\n }\n\n // The internal densify provenance marker never leaves the store.\n result = stripI18nFilled(result)\n\n return result\n}\n\n/**\n * Sync i18n-text-only present-for-join dressing — the exact `join`-layer\n * partial application `kernel/query/join.ts` used to import and call\n * directly before #626's retirement (#650 Task 6): fixes `fallback`\n * `undefined` and `layer` `'join'`. `via/lookup/snapshot.ts`'s\n * `buildPresentForJoin` composes this with the lookup-label half to build\n * the `JoinableSource.presentForJoin` hook the join executor now calls\n * instead of reaching into this module.\n */\nexport function presentI18nForJoin(\n record: Record<string, unknown>,\n i18nFields: Record<string, I18nTextDescriptor>,\n locale: string,\n): Record<string, unknown> {\n return applyI18nLocale(record, i18nFields, locale, undefined, 'join')\n}\n\n/**\n * Remove the internal densify provenance marker (`_i18nFilled`) from a\n * read-facing record. NON-mutating: returns the same object when the\n * marker is absent, otherwise a shallow copy without the marker.\n *\n * MUST be applied on every user-facing read return — even locale-less ones,\n * which bypass {@link applyI18nLocale}. MUST NOT be applied on the internal\n * prior-read path (decryptRecord / resolveDensifyPrior), where densify needs\n * the marker.\n */\nexport function stripI18nFilled<T extends Record<string, unknown>>(record: T): T {\n if (!Object.prototype.hasOwnProperty.call(record, '_i18nFilled')) return record\n const rest: T = { ...record }\n delete (rest as Record<string, unknown>)._i18n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KAAK,UAAU;AACzC,MAAI,WAAW,WAAW,EAAG,QAAO;AAEpC,MAAI,SAAS;AAEb,aAAW,CAAC,OAAO,UAAU,KAAK,OAAO,QAAQ,UAAU,GAAG;AAC5D,UAAM,EAAE,WAAW,YAAY,gBAAgB,IAAI,WAAW;AAC9D,UAAM,OAA2B;AAAA,MAC/B,QAAQ,cAAc,WAAW,KAAK;AAAA,MACtC,GAAI,eAAe,SAAY,EAAE,WAAW,IAAI,CAAC;AAAA,MACjD,GAAI,kBAAkB,EAAE,gBAAgB,IAAI,CAAC;AAAA,IAC/C;AACA,aAAS,YAAY,QAAQ,OAAO,QAAQ,UAAU,IAAI;AAAA,EAC5D;AAGA,WAAS,gBAAgB,MAAM;AAE/B,SAAO;AACT;AAWO,SAAS,mBACd,QACA,YACA,QACyB;AACzB,SAAO,gBAAgB,QAAQ,YAAY,QAAQ,QAAW,MAAM;AACtE;AAYO,SAAS,gBAAmD,QAAc;AAC/E,MAAI,CAAC,OAAO,UAAU,eAAe,KAAK,QAAQ,aAAa,EAAG,QAAO;AACzE,QAAM,OAAU,EAAE,GAAG,OAAO;AAC5B,SAAQ,KAAiC;AACzC,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/port/with/team-strategy.ts","../src/with-party/team/wrapped-deks.ts","../src/with-party/team/recovery.ts","../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/auth-introspection/index.ts","../src/with-party/team/authenticators.ts"],"sourcesContent":["/**\n * Multi-user team capability contract (#267 Track A tail — the\n * keyring-grant → team split). Lives on the `/with` port (the one seam the\n * kernel spine may import statically) so `Noydb` can hold the `NO_TEAM`\n * floor default without a spine→service static import.\n *\n * The active engine (`withTeam()` in `with-party/team/active.ts`)\n * statically links the grant/revoke/rotate keyring engines from\n * `keyring.ts` — bundle-charged to consumers of the `@noy-db/hub/team`\n * subpath, never to the single-user floor. {@link NO_TEAM} (the floor\n * default) throws {@link TeamNotEnabledError}.\n *\n * `Noydb.grant` / `Noydb.revoke` / `Noydb.rotate` delegate here, passing\n * their `TeamFacade` — the facade owns the policy-gate + keyring plumbing\n * (`runGrant` / `runRevoke` / `runRotate`) and receives the engine as an\n * argument from the strategy.\n *\n * Deliberately NOT gated (single-user primitives): owner keyring creation,\n * unlock, `listUsers`, `updateUser`, secret rotate/recover, and the\n * `createDeedOwner` free function (no createNoydb instance to gate against —\n * the same carve-out as `liberateVault`).\n * @internal\n */\nimport type { GrantOptions, RevokeOptions, FactorProofBundle } from '../../kernel/types.js'\nimport type { RotateResult, RosterVerifyResult, QuarantineResult } from '../../with-party/team/keyring.js'\nimport { TeamNotEnabledError } from '../../kernel/errors.js'\nimport type { TeamFacade } from '../../with-party/team/noydb-facade.js'\n\nexport interface TeamStrategy {\n grant(team: TeamFacade, vault: string, options: GrantOptions, factors?: FactorProofBundle): Promise<void>\n revoke(team: TeamFacade, vault: string, options: RevokeOptions, factors?: FactorProofBundle): Promise<void>\n rotate(team: TeamFacade, vault: string, collections: string[]): Promise<RotateResult>\n /** #1121 — read-only sweep naming every `_keyring` file that fails authentication. */\n verifyRoster(team: TeamFacade, vault: string): Promise<RosterVerifyResult>\n /** #1121 — remove an unauthenticatable `_keyring` file and re-key behind it. */\n quarantineKeyring(team: TeamFacade, vault: string, userId: string, factors?: FactorProofBundle): Promise<QuarantineResult>\n}\n\n/**\n * No-op stub — the floor default. Every multi-user team operation throws\n * {@link TeamNotEnabledError}; opt in with `teamStrategy: withTeam()` in\n * createNoydb. @internal\n */\nexport const NO_TEAM: TeamStrategy = {\n async grant() { throw new TeamNotEnabledError() },\n async revoke() { throw new TeamNotEnabledError() },\n async rotate() { throw new TeamNotEnabledError() },\n async verifyRoster() { throw new TeamNotEnabledError() },\n async quarantineKeyring() { throw new TeamNotEnabledError() },\n}\n","/**\n * **Wrap-DEKs primitive** — a single canonical shape for the\n * pattern of \"serialize a DEK set, encrypt it under a credential-derived\n * AES-GCM key.\" Used by:\n *\n * - **tier-0** — paper recovery entries (`_meta/recovery-paper`),\n * credential = the printed code.\n * - **tier-2** — password authenticator slots (`KeyringFile.authenticators`,\n * `wrapKind: 'deks'`), credential = the user's password.\n *\n * **Not** used by `@noy-db/on-pin` — tier-3 wraps the DEK set under\n * the same conceptual pattern but at **100,000 PBKDF2 iterations**\n * (vs the 600,000 here), because the protection window for a PIN\n * slot is short (idle-timeout-bounded, typically 15 min) and 600k\n * iterations would make every PIN-resume noticeably slow. The wire\n * formats are deliberately incompatible. See `@noy-db/on-pin`'s\n * `PIN_PBKDF2_ITERATIONS` and the threat-model rationale in its\n * module docstring.\n *\n * Previously, the same crypto lived in two places: `mintPaperRecoveryEntry`\n * (in `team/recovery.ts`) and `enrollPasswordAuthenticator` (in\n * `@noy-db/on-password`). Both functions did identical work — PBKDF2\n * the credential, AES-GCM-encrypt the JSON-serialized DEK set — but\n * their implementations had drifted apart enough that fixing a bug\n * in one wouldn't fix the other.\n *\n * This module owns the canonical implementation. Consumers compose:\n *\n * - `mintPaperRecoveryEntry` is now a thin wrapper that calls\n * `mintWrappedDeksBlob` and adds `{ codeId, enrolledAt }`.\n * - `enrollPasswordAuthenticator` calls `mintWrappedDeksBlob` and\n * wraps the result in the slot envelope.\n *\n * @module\n */\n\nimport { deriveSecretKey, type EnclaveKey } from '../../kernel/enclave/index.js'\n\nconst PBKDF2_ITERATIONS = 600_000\nconst SALT_BYTES = 32\nconst IV_BYTES = 12\n\nconst subtle = globalThis.crypto.subtle\n\n// ─── Type ──────────────────────────────────────────────────────────────\n\n/**\n * The wrap-DEKs primitive — a serialized + AES-GCM-encrypted DEK set\n * keyed under a credential-derived key.\n *\n * All three fields are base64-encoded so the blob is JSON-safe and\n * round-trips through `_meta/*` envelopes (which carry plaintext\n * JSON in `_data`).\n *\n * Composition: `PaperRecoveryEntry extends WrappedDeksBlob` plus\n * `{ codeId, enrolledAt }`. `KeyringAuthenticatorWrappingDEKs`\n * carries the same three fields with `salt` stored in `meta` for\n * slot-format back-compat (defers moving it to top-level).\n */\nexport interface WrappedDeksBlob {\n /** Base64 PBKDF2 salt for the credential-derived wrapping key. */\n readonly salt: string\n /** Base64 AES-GCM IV used for the `wrappedDeks` ciphertext. */\n readonly iv: string\n /** Base64 AES-GCM ciphertext of `{ deks: { collection: base64rawDek } }`. */\n readonly wrappedDeks: string\n}\n\n// ─── Mint ──────────────────────────────────────────────────────────────\n\n/**\n * Mint a fresh `WrappedDeksBlob` from a DEK set + a string credential.\n *\n * Generates a random salt + IV, derives a 256-bit AES-GCM key via\n * PBKDF2-SHA256(credential, salt, 600K), serializes the DEK set as\n * `{ deks: { coll: rawBase64 } }`, and AES-GCM-encrypts.\n *\n * The `credential` is the user-typed string (recovery code, password,\n * PIN). Caller normalization rules apply (e.g. paper\n * recovery uppercase-strips the code before reaching this function).\n *\n * @param deks - DEK set to wrap. Each DEK must be exportable via\n * `subtle.exportKey('raw', dek)` (the hub mints DEKs\n * this way; consumers feeding non-extractable keys\n * will get `InvalidAccessError` from WebCrypto).\n * @param credential - String input the consumer minted (paper code,\n * password, PIN). Treated as opaque bytes by PBKDF2.\n */\nexport async function mintWrappedDeksBlob(\n deks: Map<string, EnclaveKey>,\n credential: string,\n): Promise<WrappedDeksBlob> {\n const salt = crypto.getRandomValues(new Uint8Array(SALT_BYTES))\n const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES))\n const wrappingKey = await deriveWrappingKey(credential, salt)\n\n // Serialize the DEK set as JSON `{ deks: { collection: base64 } }`.\n const exported: Record<string, string> = {}\n for (const [coll, dek] of deks) {\n const raw = await subtle.exportKey('raw', dek)\n exported[coll] = bytesToBase64(new Uint8Array(raw))\n }\n const plaintext = new TextEncoder().encode(JSON.stringify({ deks: exported }))\n const ciphertext = await subtle.encrypt(\n { name: 'AES-GCM', iv: iv as BufferSource },\n wrappingKey,\n plaintext as BufferSource,\n )\n\n return {\n salt: bytesToBase64(salt),\n iv: bytesToBase64(iv),\n wrappedDeks: bytesToBase64(new Uint8Array(ciphertext)),\n }\n}\n\n// ─── Unwrap ────────────────────────────────────────────────────────────\n\n/**\n * Reverse of {@link mintWrappedDeksBlob}. Re-derives the wrapping key\n * from the credential + stored salt, AES-GCM-decrypts the wrapped DEK\n * set, and re-imports each DEK as an extractable AES-GCM CryptoKey.\n *\n * Throws (AES-GCM auth tag failure) when the credential doesn't\n * match the blob. Callers iterating over multiple blobs (e.g. paper\n * recovery's \"try every entry until one matches\") should catch.\n */\nexport async function unwrapDeksFromBlob(\n blob: WrappedDeksBlob,\n credential: string,\n): Promise<Map<string, EnclaveKey>> {\n const wrappingKey = await deriveWrappingKey(credential, base64ToBytes(blob.salt))\n const plaintext = await subtle.decrypt(\n { name: 'AES-GCM', iv: base64ToBytes(blob.iv) as BufferSource },\n wrappingKey,\n base64ToBytes(blob.wrappedDeks) as BufferSource,\n )\n const parsed = JSON.parse(new TextDecoder().decode(plaintext)) as { deks: Record<string, string> }\n const deks = new Map<string, EnclaveKey>()\n for (const [coll, b64] of Object.entries(parsed.deks)) {\n const raw = base64ToBytes(b64)\n const key = await subtle.importKey(\n 'raw',\n raw as BufferSource,\n { name: 'AES-GCM', length: 256 },\n true,\n ['encrypt', 'decrypt'],\n )\n deks.set(coll, key)\n }\n return deks\n}\n\n// ─── Internals ─────────────────────────────────────────────────────────\n\nasync function deriveWrappingKey(credential: string, salt: Uint8Array): Promise<CryptoKey> {\n return deriveSecretKey(credential, salt, { iterations: PBKDF2_ITERATIONS, keyUsage: 'aes-gcm' })\n}\n\nfunction bytesToBase64(b: Uint8Array): string {\n let s = ''\n for (const x of b) s += String.fromCharCode(x)\n return btoa(s)\n}\n\nfunction base64ToBytes(b64: string): Uint8Array {\n const s = atob(b64)\n const out = new Uint8Array(s.length)\n for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i)\n return out\n}\n","/**\n * Recovery profile persistence + dispatch.\n *\n * Wires the **paper** profile end-to-end through\n * `@noy-db/on-recovery`. The other three profiles (Shamir,\n * multi-channel, admin-mediated) ship the API surface and throw\n * {@link RecoveryProfileNotImplementedError} during use; per-profile\n * dispatch lands in follow-up issues.\n *\n * Storage layout:\n *\n * ```\n * _meta/recovery-paper — JSON { entries: RecoveryCodeEntry[] } produced by `on-recovery`.\n * _meta/recovery-shamir — reserved\n * _meta/recovery-multi — reserved\n * _meta/recovery-admin — reserved\n * ```\n *\n * Like `_meta/policy` and `_meta/handle`, the documents are plain JSON\n * with empty `_iv` — the recovery-code wrapping is what protects the\n * KEK; the entries themselves are inert without the user's code.\n *\n * @module\n */\nimport type { NoydbStore } from '../../kernel/types.js'\nimport { buildRecordEnvelope } from '../../kernel/enclave/index.js'\nimport type { EnclaveKey } from '../../kernel/enclave/index.js'\nimport {\n mintWrappedDeksBlob,\n unwrapDeksFromBlob,\n type WrappedDeksBlob,\n} from './wrapped-deks.js'\nimport type { ShamirRecoveryProvider } from './shamir-recovery-provider.js'\n\n/**\n * One paper recovery code as persisted in `_meta/recovery-paper`.\n *\n * The hub's KEK is intentionally non-extractable (see `crypto.ts`),\n * so the recovery entry can't AES-KW-wrap the KEK directly. Instead\n * we wrap a serialized DEK set: the entry holds the AES-GCM\n * ciphertext of `{ deks: { collection: rawDekBase64 } }`. Recovery\n * deserializes the DEK set, then mints a fresh KEK from the new\n * secret and rewraps the DEKs under it.\n *\n * This is the same pattern `@noy-db/on-pin` uses for tier-3 quick\n * resume — the cryptographic guarantee is identical (AES-GCM with a\n * PBKDF2-derived key), and it sidesteps the non-extractable-KEK\n * constraint cleanly.\n *\n * Type-level composition: `PaperRecoveryEntry extends\n * WrappedDeksBlob` — the three crypto fields (`salt`, `iv`,\n * `wrappedDeks`) come from the shared primitive; `codeId` and\n * `enrolledAt` are paper-recovery's own metadata. Wire format\n * unchanged.\n */\nexport interface PaperRecoveryEntry extends WrappedDeksBlob {\n readonly codeId: string\n readonly enrolledAt: string\n}\n\nexport interface PaperRecoveryDoc {\n readonly _noydb_recovery: 1\n readonly profile: 'paper'\n readonly entries: ReadonlyArray<PaperRecoveryEntry>\n}\n\nconst PAPER_DOC_ID = 'recovery-paper'\n\n/** Read the paper-recovery entries. Returns empty array when absent. */\nexport async function loadPaperRecoveryEntries(\n store: NoydbStore,\n vault: string,\n): Promise<ReadonlyArray<PaperRecoveryEntry>> {\n const env = await store.get(vault, '_meta', PAPER_DOC_ID)\n if (!env) return []\n try {\n const doc = JSON.parse(env._data) as PaperRecoveryDoc\n if (doc.profile !== 'paper' || !Array.isArray(doc.entries)) return []\n return doc.entries\n } catch {\n return []\n }\n}\n\n/** Replace the paper-recovery entries (used after burn-on-recovery). */\nexport async function savePaperRecoveryEntries(\n store: NoydbStore,\n vault: string,\n entries: ReadonlyArray<PaperRecoveryEntry>,\n): Promise<void> {\n const doc: PaperRecoveryDoc = {\n _noydb_recovery: 1,\n profile: 'paper',\n entries,\n }\n const envelope = buildRecordEnvelope(\n { collection: '_meta', id: PAPER_DOC_ID, version: 1 },\n { iv: '', data: JSON.stringify(doc) },\n )\n await store.put(vault, '_meta', PAPER_DOC_ID, envelope)\n}\n\n/** Drop a single paper-recovery entry (burn-on-use). */\nexport async function burnPaperRecoveryEntry(\n store: NoydbStore,\n vault: string,\n codeId: string,\n): Promise<void> {\n const entries = await loadPaperRecoveryEntries(store, vault)\n const remaining = entries.filter((e) => e.codeId !== codeId)\n await savePaperRecoveryEntries(store, vault, remaining)\n}\n\n/** Whether at least one recovery profile has any enrolled entries. */\nexport async function hasRecoveryEnrolled(\n store: NoydbStore,\n vault: string,\n): Promise<boolean> {\n const paper = await loadPaperRecoveryEntries(store, vault)\n if (paper.length > 0) return true\n const shamir = await loadShamirRecoveryEntries(store, vault)\n return shamir.length > 0\n}\n\n/**\n * Whether at least one **strong** recovery profile is enrolled.\n *\n * \"Strong\" excludes paper-alone — under managed-secret mode the\n * user has no memorized secret, so a stolen/lost paper sheet\n * would be a single point of total loss. Strong profiles today:\n *\n * - `shamir` (k-of-n threshold; survives loss of up to n-k shares)\n * - `multi-channel` (when shipped — follow-up slice)\n * - `admin-mediated` (when shipped — follow-up slice)\n *\n * Managed mode requires this check to pass before `openVault` returns.\n */\nexport async function hasStrongRecoveryEnrolled(\n store: NoydbStore,\n vault: string,\n): Promise<boolean> {\n const shamir = await loadShamirRecoveryEntries(store, vault)\n return shamir.length > 0\n // When multi-channel / admin-mediated land, extend this check.\n}\n\n// ─── Shamir recovery ─────────────────────────────────────────────────────\n\n/**\n * One Shamir-recovery entry as persisted in `_meta/recovery-shamir`.\n *\n * Like {@link PaperRecoveryEntry}, the entry composes\n * {@link WrappedDeksBlob} (DEKs wrapped under a fresh ephemeral\n * recovery secret) with profile-specific metadata. Unlike paper, the\n * \"credential\" was never visible to the user — it was 32 random\n * bytes split into N Shamir shares at enrollment. The shares ARE\n * the credential; the user holds them, the hub never sees them\n * again after `enrollRecovery` returns.\n *\n * The recovery secret is base64-encoded and\n * passed as the `credential` arg to\n * {@link mintWrappedDeksBlob} / {@link unwrapDeksFromBlob}. The\n * PBKDF2 round over high-entropy input is harmless overhead — it\n * keeps the shared primitive unchanged while letting Shamir reuse\n * the same wrapping pipeline as paper.\n */\nexport interface ShamirRecoveryEntry extends WrappedDeksBlob {\n /** Stable id for this entry. Allows multiple Shamir splits to coexist. */\n readonly entryId: string\n /** Threshold — minimum shares to reconstruct. */\n readonly k: number\n /** Total shares minted at enrollment. */\n readonly n: number\n /** x-coordinates of the n minted shares. Informational. Omitted as of 0.2\n * (string-level provider doesn't expose share x-coords); kept optional so\n * pre-0.2 entries still read. */\n readonly xCoords?: ReadonlyArray<number>\n /** ISO timestamp. */\n readonly enrolledAt: string\n /** Optional caller-supplied label (e.g., \"2-of-3 board escrow\"). */\n readonly label?: string\n}\n\nexport interface ShamirRecoveryDoc {\n readonly _noydb_recovery: 1\n readonly profile: 'shamir'\n readonly entries: ReadonlyArray<ShamirRecoveryEntry>\n}\n\nconst SHAMIR_DOC_ID = 'recovery-shamir'\n\n/** Read the Shamir-recovery entries. Returns empty array when absent. */\nexport async function loadShamirRecoveryEntries(\n store: NoydbStore,\n vault: string,\n): Promise<ReadonlyArray<ShamirRecoveryEntry>> {\n const env = await store.get(vault, '_meta', SHAMIR_DOC_ID)\n if (!env) return []\n try {\n const doc = JSON.parse(env._data) as ShamirRecoveryDoc\n if (doc.profile !== 'shamir' || !Array.isArray(doc.entries)) return []\n return doc.entries\n } catch {\n return []\n }\n}\n\n/** Replace the Shamir-recovery entries (used by enrollment and rotation). */\nexport async function saveShamirRecoveryEntries(\n store: NoydbStore,\n vault: string,\n entries: ReadonlyArray<ShamirRecoveryEntry>,\n): Promise<void> {\n const doc: ShamirRecoveryDoc = {\n _noydb_recovery: 1,\n profile: 'shamir',\n entries,\n }\n const envelope = buildRecordEnvelope(\n { collection: '_meta', id: SHAMIR_DOC_ID, version: 1 },\n { iv: '', data: JSON.stringify(doc) },\n )\n await store.put(vault, '_meta', SHAMIR_DOC_ID, envelope)\n}\n\n/**\n * Mint a fresh Shamir recovery entry from a DEK set.\n *\n * 1. Generates a 32-byte recovery secret.\n * 2. Wraps the DEK set under that secret via\n * {@link mintWrappedDeksBlob} (the recovery secret is base64-\n * encoded as the credential string — PBKDF2 over high-entropy\n * input is harmless overhead).\n * 3. Splits the recovery secret via Shamir into `n` shares with\n * threshold `k`.\n * 4. Zeros the in-memory recovery secret after wrapping + splitting.\n *\n * Returns:\n * - `entry` — the {@link ShamirRecoveryEntry} to persist.\n * - `shareStrings` — the `n` Base32-encoded share strings to\n * return to the caller. The HUB MUST NOT PERSIST THESE; once\n * returned they are the user's responsibility.\n *\n * @param deks - DEK set to wrap.\n * @param entryId - Stable id for this entry (caller-supplied or\n * hub-generated).\n * @param k - Threshold (>= 2).\n * @param n - Total shares (k <= n <= 255).\n * @param label - Optional caller label.\n */\nexport async function mintShamirRecoveryEntry(\n provider: ShamirRecoveryProvider,\n deks: Map<string, EnclaveKey>,\n entryId: string,\n k: number,\n n: number,\n label?: string,\n): Promise<{ entry: ShamirRecoveryEntry; shareStrings: string[] }> {\n const recoverySecret = crypto.getRandomValues(new Uint8Array(32))\n try {\n const credential = bytesToBase64(recoverySecret)\n const blob = await mintWrappedDeksBlob(deks, credential)\n const shareStrings = provider.splitToShares(recoverySecret, k, n)\n const entry: ShamirRecoveryEntry = {\n ...blob, entryId, k, n,\n enrolledAt: new Date().toISOString(),\n ...(label !== undefined && { label }),\n }\n return { entry, shareStrings }\n } finally {\n recoverySecret.fill(0)\n }\n}\n\n/**\n * Decrypt a Shamir recovery entry to recover the raw DEK set.\n *\n * Combines K or more `shares`, reconstructs the recovery secret,\n * unwraps the DEKs via {@link unwrapDeksFromBlob}.\n *\n * Throws (AES-GCM auth-tag mismatch) when the shares don't combine\n * to the secret originally used to mint the entry — typically\n * because they came from a different enrollment or were tampered\n * with. Callers iterating multiple entries should catch.\n */\nexport async function unwrapDeksFromShamirEntry(\n provider: ShamirRecoveryProvider,\n entry: ShamirRecoveryEntry,\n shareStrings: readonly string[],\n): Promise<Map<string, EnclaveKey>> {\n if (shareStrings.length < entry.k) {\n throw new Error(\n `Insufficient shares: this Shamir entry needs ${entry.k} of ${entry.n}, `\n + `but ${shareStrings.length} were provided.`,\n )\n }\n const secret = provider.combineShares(shareStrings)\n try {\n return await unwrapDeksFromBlob(entry, bytesToBase64(secret))\n } finally {\n secret.fill(0)\n }\n}\n\nfunction bytesToBase64(b: Uint8Array): string {\n let s = ''\n for (const x of b) s += String.fromCharCode(x)\n return btoa(s)\n}\n\n/**\n * Generate one paper-recovery entry from an unlocked DEK set.\n *\n * Returns the serializable entry (persisted via\n * {@link savePaperRecoveryEntries}). The recovery flow unwraps the\n * DEK set, then mints a fresh KEK from the user's new secret.\n *\n * Thin wrapper over {@link mintWrappedDeksBlob} — the crypto\n * lives in the shared primitive; this function just adds paper-\n * recovery's own metadata (`codeId`, `enrolledAt`).\n *\n * @param deks Map of collection-name → DEK (extractable).\n * @param code The plaintext recovery code (caller-supplied;\n * pair this with `@noy-db/on-recovery`'s code\n * generator/parser if available).\n * @param codeId Stable id used by `burnPaperRecoveryEntry`.\n */\nexport async function mintPaperRecoveryEntry(\n deks: Map<string, EnclaveKey>,\n code: string,\n codeId: string,\n): Promise<PaperRecoveryEntry> {\n const blob = await mintWrappedDeksBlob(deks, code)\n return {\n ...blob,\n codeId,\n enrolledAt: new Date().toISOString(),\n }\n}\n\n/**\n * Decrypt a recovery entry to recover the raw DEK set. Used by the\n * `recoverSecret` flow after the user's code has been parsed.\n *\n * Thin wrapper over {@link unwrapDeksFromBlob}.\n *\n * @throws when the code does not match the entry (AES-GCM auth tag fail).\n */\nexport async function unwrapDeksFromPaperEntry(\n entry: PaperRecoveryEntry,\n code: string,\n): Promise<Map<string, EnclaveKey>> {\n return unwrapDeksFromBlob(entry, code)\n}\n\n// The crypto helpers (deriveRecoveryWrappingKey, bytesToBase64,\n// base64ToBytes) live in the canonical wrap-DEKs primitive at\n// `./wrapped-deks.ts` and are reached via\n// `mintWrappedDeksBlob` / `unwrapDeksFromBlob`.\n","/**\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 } from '../../kernel/types.js'\nimport type { UnlockedKeyring } from './keyring.js'\nimport { buildRecordAad, buildRecordEnvelope, 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 identity = { collection: MAGIC_LINK_GRANTS_COLLECTION, id: recordId, by: grantor.userId, version: 1 }\n const { iv, data } = await encrypt(JSON.stringify(payload), contentKey, buildRecordAad(identity))\n const envelope = buildRecordEnvelope(\n identity,\n { ts: createdAt, iv, data},\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({ collection: MAGIC_LINK_GRANTS_COLLECTION, id: recordId }, 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 — `rotateSecret` (user remembers old) and\n * `recoverSecret` (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 `oldSecret`.\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, KeyringEchoBlock } from '../../kernel/types.js'\nimport { NOYDB_KEYRING_VERSION } from '../../kernel/types.js'\nimport {\n buildRecordEnvelope,\n deriveKey,\n deriveEchoKey,\n generateSalt,\n wrapKey,\n unwrapKey,\n bufferToBase64,\n base64ToBuffer,\n type EnclaveKey,\n type EchoSecretParts,\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 {\n assertStrongSecret,\n assertStrongEchoSecret,\n type SecretPolicy,\n type EchoSecretPolicy,\n} from '../../kernel/validation.js'\nimport type { UnlockedKeyring } from './keyring.js'\nimport { mintKeyringCanary, deriveKekForKeyring, readKeyringFile } from './keyring.js'\nimport { assertRosterAuthenticated, mintRosterTag } from './roster-tag.js'\nimport { ROSTER_KEY_ID } from '../../kernel/constants.js'\nimport { buildEchoBlock } from './echo-secret.js'\nimport type { DeviceSealProvider } from './device-seal.js'\nimport type { KeyringAuthenticator } from '../../kernel/types.js'\nimport type { EnrollAuthenticatorOptions } from './authenticators.js'\nimport { ValidationError } from '../../kernel/errors.js'\n\n/**\n * Echo-enrollment knobs for a rotation whose NEW secret is 3-part (spec #940).\n *\n * Deliberately NOT exported: it is reachable structurally through\n * {@link RotateSecretInput.echoOptions}, and exporting it would mean adding it\n * to the team + root barrels for a type consumers never need to name.\n */\ninterface RotateEchoOptions {\n /**\n * Device-local sealer for the reveal blob. Present ⇒ `reveal: 'sealed'`;\n * absent ⇒ `reveal: 'portable'`. Mirrors\n * {@link CreateOwnerKeyringOptions.deviceSeal}.\n */\n readonly deviceSeal?: DeviceSealProvider\n /** Optional display hint for the masked echo. */\n readonly maskHint?: string\n}\n\n/**\n * The `echo` field for the keyring file a tier-1 change is about to write.\n *\n * Every write site rebuilds the persisted file WITHOUT the old block (a\n * `{ ...file }` spread would carry it) and then re-attaches whatever the NEW\n * secret's shape demands:\n *\n * - parts ⇒ a FRESH block (the standard→echo upgrade, and the re-mint on an\n * echo→echo rotation — the old block's verifiers are bound to the old parts).\n * - string ⇒ `{}`, i.e. no block at all (the echo→standard downgrade).\n *\n * Getting this wrong bricks the keyring: a stale block makes\n * `deriveKekForKeyring` demand the echo ceremony and derive via the echo KDF,\n * while the DEKs sit wrapped under a string-derived KEK — neither the old parts\n * nor the new string can open it.\n */\nasync function echoFieldForNewSecret(\n newSecret: string | EchoSecretParts,\n echoOptions?: RotateEchoOptions,\n): Promise<{ echo?: KeyringEchoBlock }> {\n if (typeof newSecret === 'string') return {}\n return {\n echo: await buildEchoBlock(\n newSecret,\n echoOptions?.deviceSeal\n ? { kind: 'sealed', deviceSeal: echoOptions.deviceSeal }\n : { kind: 'portable' },\n echoOptions?.maskHint,\n ),\n }\n}\n\n/** Derive the KEK for a freshly-chosen tier-1 secret, dispatching on its shape. */\nasync function deriveKekForNewSecret(\n newSecret: string | EchoSecretParts,\n salt: Uint8Array,\n): Promise<EnclaveKey> {\n return typeof newSecret === 'string'\n ? deriveKey(newSecret, salt)\n : deriveEchoKey(newSecret, salt)\n}\n\n/** Strength gate for a freshly-chosen tier-1 secret, dispatching on its shape. */\nfunction assertStrongNewSecret(\n newSecret: string | EchoSecretParts,\n secretPolicy?: SecretPolicy,\n echoSecretPolicy?: EchoSecretPolicy,\n): void {\n if (typeof newSecret === 'string') assertStrongSecret(newSecret, secretPolicy)\n else assertStrongEchoSecret(newSecret, echoSecretPolicy)\n}\n\n/**\n * Context handed to a {@link SlotRewrapCeremony} when `rotateSecret`\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 `rotateSecret`.\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 rotateSecret}. */\nexport interface RotateSecretInput {\n /**\n * The secret currently opening the keyring — a string for a standard\n * keyring, the 3-part {@link EchoSecretParts} for an echo one. The shape\n * must MATCH the stored keyring: `deriveKekForKeyring` refuses a string on\n * an echo keyring (`EchoCeremonyRequiredError`, AG-1) and parts on a\n * standard one (`ValidationError`).\n */\n readonly oldSecret: string | EchoSecretParts\n /**\n * The secret to rotate TO. Its shape — independent of `oldSecret`'s —\n * decides the keyring's mode after rotation: parts enroll an `echo` block\n * (standard→echo upgrade, or a re-mint on echo→echo), a string removes any\n * existing one (echo→standard downgrade).\n */\n readonly newSecret: string | EchoSecretParts\n /**\n * Strength-policy knobs applied when `newSecret` is a STRING. Ignored\n * for 3-part {@link EchoSecretParts} — see `echoSecretPolicy` for the\n * parts-path counterpart.\n */\n readonly secretPolicy?: SecretPolicy\n /**\n * Strength-policy knobs applied when `newSecret` is 3-part\n * {@link EchoSecretParts} (prompt / combined floors). Ignored for a\n * string `newSecret` — see `secretPolicy` for the string-path\n * counterpart.\n */\n readonly echoSecretPolicy?: EchoSecretPolicy\n readonly allowWeakSecret?: boolean\n /**\n * Echo-enrollment knobs for the block minted when `newSecret` is 3-part.\n * Ignored for a string `newSecret` (no block is written).\n */\n readonly echoOptions?: RotateEchoOptions\n /**\n * Explicit confirmation for an echo→standard rotation. When the stored\n * keyring has an `echo` block AND `newSecret` is a plain string, the\n * rotation is a security-posture downgrade — and that shape is decided\n * purely by argument shape, so it must be opted into explicitly. Without\n * this flag such a rotation throws `ValidationError` BEFORE any write\n * (and before deriving the new KEK). Upgrades (string→parts) and\n * same-mode rotations (string→string, parts→parts) never require it.\n */\n readonly allowModeDowngrade?: 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, `rotateSecret` 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 `oldSecret`, rewrap every DEK\n * under a freshly-derived KEK from `newSecret`, 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 * Either secret may be a string or 3-part {@link EchoSecretParts}; the two\n * shapes are independent, so a rotation doubles as the standard↔echo\n * upgrade/downgrade ceremony (spec #940).\n *\n * @throws `InvalidKeyError` if `oldSecret` does not unwrap the keyring.\n * @throws `EchoCeremonyRequiredError` if `oldSecret` is a string but the\n * keyring is an echo keyring.\n * @throws `WeakSecretError` if `newSecret` 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 rotateSecret(\n store: NoydbStore,\n vault: string,\n userId: string,\n input: RotateSecretInput,\n): Promise<UnlockedKeyring> {\n if (!input.allowWeakSecret) {\n assertStrongNewSecret(input.newSecret, input.secretPolicy, input.echoSecretPolicy)\n }\n\n const found = await readKeyringFile(store, vault, userId)\n if (!found) {\n throw new NoAccessError(`No keyring found for user \"${userId}\" in vault \"${vault}\".`)\n }\n const { file } = found\n const oldSalt = base64ToBuffer(file.salt)\n // Dispatches on the STORED keyring's mode, so a string presented to an echo\n // keyring (or parts to a standard one) is refused before any unwrap.\n const oldKek = await deriveKekForKeyring(file, input.oldSecret, oldSalt)\n\n // Unwrap every DEK with the OLD KEK first — this also validates the\n // secret (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 // #1096 — this function returns an `UnlockedKeyring` whose `role` and\n // `permissions` come from the plaintext header, so it must authenticate the\n // roster like `loadKeyring` does. Checked BEFORE anything is written: a\n // forged roster must be refused, not rewrapped under a fresh secret and\n // thereby blessed.\n await assertRosterAuthenticated(file, deks, userId)\n\n // Echo→standard is a security-posture downgrade decided by argument shape\n // alone — require explicit opt-in, and refuse before deriving the new KEK\n // or writing anything.\n if (file.echo !== undefined && typeof input.newSecret === 'string' && !input.allowModeDowngrade) {\n throw new ValidationError(\n 'Rotating an echo-secret keyring to a plain string secret is a security-posture downgrade — pass allowModeDowngrade: true to confirm.',\n )\n }\n\n const newSalt = generateSalt()\n const newKek = await deriveKekForNewSecret(input.newSecret, 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 // Drop the OLD echo block explicitly — a `{ ...file }` spread would carry it\n // across a downgrade and miss it on an upgrade. See echoFieldForNewSecret.\n // eslint-disable-next-line @typescript-eslint/no-unused-vars -- excluded from ...carried\n const { echo: _staleEcho, ...carried } = file\n // #1115/#1126 — RESTAMP. This is a read-modify-write of a file whose roster\n // tag now covers the DEK key SET, and the rebuild replaces `deks` wholesale.\n // Carrying the old tag across leaves the vault unopenable the moment the\n // recovered set differs from the one the tag was minted over, and fragile\n // even when it does not.\n const rebuilt = {\n ...carried,\n _noydb_keyring: NOYDB_KEYRING_VERSION,\n deks: wrappedDeks,\n salt: bufferToBase64(newSalt),\n authenticators: newSlots,\n canary,\n ...(await echoFieldForNewSecret(input.newSecret, input.echoOptions)),\n }\n const next: KeyringFile = {\n ...rebuilt,\n roster_tag: await mintRosterTag(rebuilt, requireRecoveredRosterKey(deks)),\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 recoverSecret}.\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 RecoverSecretInput {\n /**\n * The secret to recover TO. As in {@link RotateSecretInput}, the shape\n * decides the recovered keyring's mode: 3-part {@link EchoSecretParts}\n * enroll a fresh (always PORTABLE) `echo` block, a string leaves the\n * keyring standard and removes any block the old one carried.\n *\n * Recovery deliberately has no `echoOptions` counterpart — a device seal\n * would bind the reveal blob to the device running the recovery, which is\n * not necessarily the device the user will unlock from. Seal it afterwards\n * with an explicit `rotateSecret`.\n *\n * A string `newSecret` on a previously-echo keyring performs the same\n * echo→standard downgrade as `rotateSecret`, but WITHOUT an\n * `allowModeDowngrade` gate — recovery is already a proof-gated reset\n * ceremony (a valid recovery code/shares), so the shape-alone check\n * `rotateSecret` needs is redundant here by design.\n */\n readonly newSecret: string | EchoSecretParts\n readonly recoveryProof: RecoveryProof\n /**\n * Strength-policy knobs applied when `newSecret` is a STRING. Ignored\n * for 3-part {@link EchoSecretParts} — see `echoSecretPolicy` for the\n * parts-path counterpart.\n */\n readonly secretPolicy?: SecretPolicy\n /**\n * Strength-policy knobs applied when `newSecret` is 3-part\n * {@link EchoSecretParts} (prompt / combined floors). Ignored for a\n * string `newSecret` — see `secretPolicy` for the string-path\n * counterpart.\n */\n readonly echoSecretPolicy?: EchoSecretPolicy\n readonly allowWeakSecret?: 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.recoverSecret`. `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 RecoverSecretResult {\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 * secret but wants a fresh sheet (paper) or fresh shares\n * (shamir). Symmetric to {@link RotateSecretInput}.\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 RecoverSecretInput.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 secret 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 recoverSecret(\n provider: ShamirRecoveryProvider | undefined,\n store: NoydbStore,\n vault: string,\n userId: string,\n input: RecoverSecretInput,\n): Promise<UnlockedKeyring> {\n if (!input.allowWeakSecret) {\n assertStrongNewSecret(input.newSecret, input.secretPolicy, input.echoSecretPolicy)\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: RecoverSecretInput,\n): Promise<UnlockedKeyring> {\n if (input.recoveryProof.profile !== 'paper') throw new Error('unreachable')\n const { code } = input.recoveryProof.payload\n\n const found = await readKeyringFile(store, vault, userId)\n if (!found) {\n throw new NoAccessError(`No keyring found for user \"${userId}\" in vault \"${vault}\".`)\n }\n const { file } = found\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.team.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 // #1096 — same as the rotateSecret path: the returned keyring's authority\n // comes from the plaintext header. The roster key rides the paper entry's\n // wrapped-DEK blob, so it is in reach here even though no KEK ever is.\n await assertRosterAuthenticated(file, deks, userId)\n\n // Fresh salt + KEK from the new secret, rewrap.\n const newSalt = generateSalt()\n const newKek = await deriveKekForNewSecret(input.newSecret, 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 // Explicit rebuild — the old echo block must not ride the spread. See\n // echoFieldForNewSecret.\n // eslint-disable-next-line @typescript-eslint/no-unused-vars -- excluded from ...carried\n const { echo: _staleEcho, ...carried } = file\n // #1115/#1126 — RESTAMP, same reason as the other rebuild sites.\n const rebuilt = {\n ...carried,\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 ...(await echoFieldForNewSecret(input.newSecret)),\n }\n const next: KeyringFile = {\n ...rebuilt,\n roster_tag: await mintRosterTag(rebuilt, requireRecoveredRosterKey(deks)),\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 secret\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 `newSecret` +\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: RecoverSecretInput,\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 found = await readKeyringFile(store, vault, userId)\n if (!found) {\n throw new NoAccessError(`No keyring found for user \"${userId}\" in vault \"${vault}\".`)\n }\n const { file } = found\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.team.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 // #1096 — mirrors paper: authenticate the roster before rewrapping it under\n // a fresh secret. The roster key rides the Shamir entry's wrapped-DEK blob.\n await assertRosterAuthenticated(file, recoveredDeks, userId)\n\n // Mint fresh KEK from new secret, rewrap DEKs (mirrors paper).\n const newSalt = generateSalt()\n const newKek = await deriveKekForNewSecret(input.newSecret, 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 // Explicit rebuild — the old echo block must not ride the spread. See\n // echoFieldForNewSecret.\n // eslint-disable-next-line @typescript-eslint/no-unused-vars -- excluded from ...carried\n const { echo: _staleEcho, ...carried } = file\n // #1115/#1126 — RESTAMP, same reason as the paper path above.\n const rebuilt = {\n ...carried,\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 ...(await echoFieldForNewSecret(input.newSecret)),\n }\n const next: KeyringFile = {\n ...rebuilt,\n roster_tag: await mintRosterTag(rebuilt, requireRecoveredRosterKey(recoveredDeks)),\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 = buildRecordEnvelope(\n { collection: '_keyring', id: userId, version: 1 },\n { iv: '', data: JSON.stringify(file) },\n )\n await store.put(vault, '_keyring', userId, envelope)\n}\n\n/**\n * The roster key out of a RECOVERED DEK map. Recovery rebuilds the keyring file\n * from scratch, so it must restamp — and it can, because the roster key travels\n * inside the recovered set like any other `_`-prefixed slot.\n *\n * Throws rather than skipping the restamp: a recovery that cannot produce a\n * verifiable tag has produced a file nobody can open, and failing here says so\n * instead of writing it.\n */\nfunction requireRecoveredRosterKey(deks: Map<string, EnclaveKey>): EnclaveKey {\n const key = deks.get(ROSTER_KEY_ID)\n if (!key) {\n throw new ValidationError(\n `recoverSecret: the recovered DEK set carries no \"${ROSTER_KEY_ID}\" entry, so the rebuilt ` +\n 'keyring could not be re-signed. The recovery material predates the authenticated roster ' +\n 'and the vault must be re-seeded.',\n )\n }\n return key\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 secret. Match `rotateSecret`'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 { buildRecordEnvelope, deriveKey, generateSalt, wrapKey, bufferToBase64 } from '../../kernel/enclave/index.js'\nimport { NoAccessError, PermissionDeniedError, PrivilegeEscalationError } from '../../kernel/errors.js'\nimport { assertStrongSecret, type SecretPolicy } from '../../kernel/validation.js'\nimport type { UnlockedKeyring } from './keyring.js'\nimport { mintKeyringCanary, readKeyringFile, requireRosterKey } from './keyring.js'\nimport { mintRosterTag, assertRosterTagValid } from './roster-tag.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 secret under which the new keyring is wrapped.\n * The recipient should call `db.rotateSecret` 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 secret: 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 validateSecret?: boolean\n /**\n * Skip phrase strength validation even when `validateSecret` 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 allowWeakSecret?: boolean\n /**\n * Optional explicit phrase policy override (passed through to\n * `assertStrongSecret`). Mirrors how `grant` accepts a custom\n * `SecretPolicy` for app-specific tightening.\n */\n readonly secretPolicy?: SecretPolicy\n}\n\n/**\n * Atomically rewrap the target user's keyring under a fresh temp\n * secret. 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 secret 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 found = await readKeyringFile(store, vault, options.userId)\n if (!found) {\n throw new NoAccessError(\n `recoverUser: user \"${options.userId}\" has no keyring in vault \"${vault}\".`,\n )\n }\n const target = found.file\n\n // #1096 — verify BEFORE anything reads this file, because the very next line\n // adopts `target.role` as the recovered role. The attack is self-triggering:\n // a store forges a member's role, that member is locked out at load, and the\n // admin's natural remedy IS recovery — which without this check would rewrap\n // the forged authority under a fresh secret and stamp it genuine.\n const rosterKey = requireRosterKey(callerKeyring, 'recoverUser')\n await assertRosterTagValid(target, rosterKey, options.userId)\n\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.validateSecret && !options.allowWeakSecret) {\n assertStrongSecret(options.secret, options.secretPolicy)\n }\n\n\n // 5. Mint a fresh salt + KEK from the temp secret. The DEKs\n // themselves are unchanged — only the wrapping is replaced.\n const newSalt = generateSalt()\n const newKek = await deriveKey(options.secret, 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 // rotateSecret). 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 //\n // An echo block on the target is dropped for the same reason\n // (spec #940): `options.secret` is a STRING, so the rewrapped DEKs sit\n // under a string-derived KEK. Carrying the block over would make\n // `deriveKekForKeyring` demand the echo ceremony and derive via the echo\n // KDF — bricking the keyring for old parts AND new temp alike. The\n // recovered user therefore gets a STANDARD keyring; picking the echo\n // shape back up is their own `rotateSecret` away (peer recovery is a\n // single-use bridge, and widening `RecoverUserOptions.secret` to 3-part\n // parts would mean transporting three secrets over the out-of-band\n // channel — deliberately out of scope).\n const canary = await mintKeyringCanary(newKek)\n // eslint-disable-next-line @typescript-eslint/no-unused-vars -- excluded from ...carried\n const { echo: _staleEcho, ...carried } = target\n const edited: KeyringFile = {\n ...carried,\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 // #1096 — a restamp is REQUIRED here, not merely uniform: `granted_by`\n // becomes the recoverer and `role` may change, so the carried tag no longer\n // describes the file. The recovered user's own copy of the roster key was\n // re-wrapped into `wrappedDeks` above (it is one of the target's DEKs), so\n // they can verify this on first unlock with the temp secret.\n const next: KeyringFile = {\n ...edited,\n roster_tag: await mintRosterTag(edited, rosterKey),\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 = buildRecordEnvelope(\n { collection: '_keyring', id: options.userId, version: 1 },\n { iv: '', data: JSON.stringify(next) },\n )\n await store.put(vault, '_keyring', options.userId, envelope)\n}\n","/**\n * Authentication introspection.\n *\n * Three surfaces over the configured tier model and the actual\n * per-user enrollment state:\n *\n * 1. **Vault-wide English summary** — {@link describeAuthConfig}.\n * 2. **Vault-wide Mermaid diagram** — {@link diagramAuthConfig}.\n * 3. **Per-user introspection** — {@link describeUserAuth}, gated by\n * the `view-user-auth` policy gate (off by default).\n *\n * The per-user surface is held to a strict allowlist — fields not on\n * the allowlist are dropped, never rendered. The negative test in\n * `auth-introspection.test.ts` exercises the allowlist by feeding a\n * contrived keyring with fake \"secret\" fields and asserting that none\n * of them appear in the output.\n *\n * @module\n */\nimport type { NoydbStore, KeyringFile, KeyringAuthenticator, VaultPolicy, GatePolicy } from '../../kernel/types.js'\nimport { loadVaultPolicy } from '../policy/storage.js'\nimport { loadPaperRecoveryEntries } from '../team/recovery.js'\n\n/** Vault-wide English summary of the configured authentication graph. */\nexport async function describeAuthConfig(\n store: NoydbStore,\n vault: string,\n): Promise<string> {\n const policy = (await loadVaultPolicy(store, vault)) ?? defaultPolicySnapshot()\n const recoveryProfiles = await listRecoveryProfilesEnrolled(store, vault)\n\n const lines: string[] = []\n lines.push(`Vault \"${vault}\" — three-tier authentication`)\n lines.push('')\n lines.push('Tier 1 — Secret (master)')\n lines.push(` Phrase format: ${policy.secret?.minWords ?? 6}+ words, lowercase letters, ≥${policy.secret?.minWordLength ?? 3} chars/word`)\n lines.push(' Strength validator: enforced (override available for tests only)')\n lines.push('')\n lines.push('Tier 2 — Authenticate (routine login)')\n lines.push(' Allowed methods: WebAuthn (passkey), OIDC, Password')\n lines.push(' Slots per user: unlimited')\n lines.push('')\n lines.push('Tier 3 — Unlock (quick resume)')\n lines.push(' Method: PIN (per-app configurable)')\n lines.push('')\n lines.push(`Recovery profiles enrolled: ${recoveryProfiles.length === 0 ? 'none' : recoveryProfiles.join(', ')}`)\n lines.push('Managed-secret mode: off (post-1.0)')\n lines.push('')\n lines.push('Sensitive-action gates:')\n for (const [gate, gp] of Object.entries(policy.gates) as Array<[string, GatePolicy]>) {\n lines.push(` ${gate} — ${describeGatePolicy(gp)}`)\n }\n return lines.join('\\n')\n}\n\n/**\n * Render the vault's auth graph as Mermaid `flowchart TB` source. The\n * caller pipes this through Mermaid (CLI or browser) to get an SVG.\n */\nexport async function diagramAuthConfig(\n store: NoydbStore,\n vault: string,\n): Promise<string> {\n const policy = (await loadVaultPolicy(store, vault)) ?? defaultPolicySnapshot()\n const lines: string[] = []\n lines.push('flowchart TB')\n lines.push(` vault[\"Vault: ${escapeMermaid(vault)}\"]`)\n lines.push(' tier1[\"Tier 1<br/>Secret\"]')\n lines.push(' tier2[\"Tier 2<br/>Multi-slot Authenticate\"]')\n lines.push(' tier3[\"Tier 3<br/>PIN / Quick-resume\"]')\n lines.push(' vault --> tier1')\n lines.push(' tier1 --> tier2')\n lines.push(' tier2 --> tier3')\n for (const [gateName, gp] of Object.entries(policy.gates) as Array<[string, GatePolicy]>) {\n if (gp.enabled === false) continue\n const id = sanitizeId(gateName)\n const label = `${gateName}<br/>tier ≥ ${gp.minTier}`\n lines.push(` ${id}[\"${escapeMermaid(label)}\"]`)\n const tierNode = gp.minTier === 1 ? 'tier1' : gp.minTier === 2 ? 'tier2' : 'tier3'\n lines.push(` ${tierNode} --> ${id}`)\n }\n return lines.join('\\n')\n}\n\n/**\n * Render the per-user enrollment summary. Returns an empty\n * (non-throwing) string when the user has no keyring file — never\n * confirms or denies the existence of the user from the document\n * alone.\n *\n * Sanitization is strict: only the slot list, enrollment dates, and\n * recovery-profile counts are rendered. WebAuthn cred ids, OIDC\n * subject ids, password hashes, recovery codes, TOTP secrets — all\n * dropped at the allowlist boundary, not redacted.\n */\nexport async function describeUserAuth(\n store: NoydbStore,\n vault: string,\n userId: string,\n): Promise<string> {\n const env = await store.get(vault, '_keyring', userId)\n if (!env) return ''\n // #1096 — DELIBERATELY UNVERIFIED. This is a key-free plaintext-header\n // reader (no KEK, no DEKs, so no roster key to verify a `roster_tag` with).\n // The `role` reported here is therefore what the STORE says, not what an\n // authorised editor wrote. Safe because this is descriptive output, never an\n // authorisation input — do not let it become one.\n const file = JSON.parse(env._data) as KeyringFile\n\n const lines: string[] = []\n lines.push(\n `User: ${file.user_id} (joined ${file.created_at.slice(0, 10)}, role: ${file.role})`,\n )\n lines.push('')\n lines.push('Tier 2 enrollments:')\n if (!file.authenticators || file.authenticators.length === 0) {\n lines.push(' (none enrolled)')\n } else {\n for (const slot of file.authenticators) {\n lines.push(` - ${describeSlot(slot)}`)\n }\n }\n return lines.join('\\n')\n}\n\n/** Bulk variant for owner dashboards. */\nexport async function describeAllUsersAuth(\n store: NoydbStore,\n vault: string,\n): Promise<Array<{ userId: string; description: string }>> {\n const ids = await store.list(vault, '_keyring')\n const results: Array<{ userId: string; description: string }> = []\n for (const userId of ids) {\n const description = await describeUserAuth(store, vault, userId)\n if (description !== '') results.push({ userId, description })\n }\n return results\n}\n\n// ─── Helpers ───────────────────────────────────────────────────────────\n\nconst SLOT_FIELD_ALLOWLIST: ReadonlyArray<keyof KeyringAuthenticator> = [\n 'id',\n 'method',\n 'enrolled_at',\n 'enrolled_via_tier',\n] as const\n\nfunction describeSlot(slot: KeyringAuthenticator): string {\n // Project to the allowlist FIRST — never read meta/wrapped_kek into\n // any user-facing string. The allowlist is the only path values\n // take to the renderer; off-allowlist fields are dropped, not redacted.\n const sanitized: Partial<KeyringAuthenticator> = {}\n for (const key of SLOT_FIELD_ALLOWLIST) {\n if (key in slot) {\n // @ts-expect-error narrow assignment from allowlist iteration\n sanitized[key] = slot[key]\n }\n }\n const date = (sanitized.enrolled_at ?? '').slice(0, 10)\n return `${sanitized.method ?? '?'} (id=${sanitized.id ?? '?'}, enrolled ${date}, via tier ${sanitized.enrolled_via_tier ?? '?'})`\n}\n\nfunction describeGatePolicy(gp: GatePolicy): string {\n if (gp.enabled === false) return 'disabled'\n const parts: string[] = []\n parts.push(`tier ${gp.minTier}`)\n if (gp.factors && gp.factors.length > 0) {\n for (const f of gp.factors) {\n parts.push(`+ ${f.count ?? 1}× ${f.anyOf.join('|')}`)\n }\n }\n if (gp.warn?.sharedDevice === 'block') parts.push('block-on-shared-device')\n return parts.join(' ')\n}\n\nfunction defaultPolicySnapshot(): VaultPolicy {\n return {\n secret: { minWords: 6, minWordLength: 3, rejectRepeatedAdjacent: true },\n gates: {},\n }\n}\n\nasync function listRecoveryProfilesEnrolled(\n store: NoydbStore,\n vault: string,\n): Promise<ReadonlyArray<string>> {\n const enrolled: string[] = []\n const paper = await loadPaperRecoveryEntries(store, vault)\n if (paper.length > 0) enrolled.push(`paper (${paper.length} codes)`)\n return enrolled\n}\n\nfunction escapeMermaid(s: string): string {\n return s.replace(/\"/g, '\\\\\"').replace(/\\n/g, ' ')\n}\n\nfunction sanitizeId(s: string): string {\n return s.replace(/[^a-zA-Z0-9]/g, '_')\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CO,IAAM,UAAwB;AAAA,EACnC,MAAM,QAAQ;AAAE,UAAM,IAAI,oBAAoB;AAAA,EAAE;AAAA,EAChD,MAAM,SAAS;AAAE,UAAM,IAAI,oBAAoB;AAAA,EAAE;AAAA,EACjD,MAAM,SAAS;AAAE,UAAM,IA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