@noy-db/hub 0.9.0-pre.0 → 0.9.0-pre.2
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.
- package/CHANGELOG.md +39 -0
- package/dist/api-H4B7ZQXP.js +18 -0
- package/dist/as/index.js +10 -10
- package/dist/at/index.js +8 -8
- package/dist/attestation/index.js +18 -18
- package/dist/{backup-7RKNZMQO.js → backup-E3GBMNDA.js} +92 -31
- package/dist/backup-E3GBMNDA.js.map +1 -0
- package/dist/blobs/index.js +12 -12
- package/dist/broker/index.js +13 -13
- package/dist/by/index.js +2 -2
- package/dist/capsule/contract.js +6 -6
- package/dist/capsule/enclave-aes/crypto.d.ts +18 -0
- package/dist/capsule/enclave-aes/index.d.ts +2 -2
- package/dist/capsule/enclave-aes/index.js +14 -8
- package/dist/capsule/enclave-aes/index.js.map +1 -1
- package/dist/capsule/index.d.ts +1 -1
- package/dist/{capsule-57BDK7LG.js → capsule-YQKQZPH7.js} +14 -8
- package/dist/cargo/index.js +35 -35
- package/dist/{chunk-AJFPAHMW.js → chunk-27NCEPKM.js} +3 -3
- package/dist/{chunk-PGC35KXE.js → chunk-2IASHJPS.js} +2 -2
- package/dist/{chunk-NYJBYVBG.js → chunk-2ODEFG6K.js} +4 -4
- package/dist/{chunk-7BMOS4JQ.js → chunk-2QH3I7QC.js} +11 -11
- package/dist/{chunk-VSUQI5Q6.js → chunk-2RH5SEY7.js} +16 -2
- package/dist/chunk-2RH5SEY7.js.map +1 -0
- package/dist/{chunk-IVMFIKNA.js → chunk-2T2TGRWE.js} +6 -6
- package/dist/{chunk-G66YXUTY.js → chunk-35CNOVQE.js} +3 -3
- package/dist/{chunk-OJU67C23.js → chunk-3EXQXOQ2.js} +4 -4
- package/dist/{chunk-BJH77UY2.js → chunk-4KYKRYRT.js} +2 -2
- package/dist/{chunk-RDOEOPOI.js → chunk-4N4OIVK3.js} +5 -5
- package/dist/{chunk-WHOKGHJ3.js → chunk-4WLI37WK.js} +7 -7
- package/dist/{chunk-RNACRT5H.js → chunk-52ZFNK46.js} +2 -2
- package/dist/{chunk-CB4467G3.js → chunk-5A3HOTP5.js} +33 -7
- package/dist/chunk-5A3HOTP5.js.map +1 -0
- package/dist/{chunk-QDHHHI5Q.js → chunk-5SMCBPJ2.js} +5 -5
- package/dist/{chunk-EMAWOGVH.js → chunk-654RE5YC.js} +3 -3
- package/dist/{chunk-FZXRLNJO.js → chunk-6BEBWHNL.js} +3 -3
- package/dist/{chunk-EUD3HQM4.js → chunk-6WEPFEMJ.js} +4 -4
- package/dist/{chunk-YFFMPZPY.js → chunk-6WIFF46H.js} +2 -2
- package/dist/{chunk-ZVSKSUGI.js → chunk-7C7OF26T.js} +5 -5
- package/dist/{chunk-QXJXG7DN.js → chunk-7IV7GVOS.js} +5 -5
- package/dist/{chunk-MQ7YWBQ5.js → chunk-7JRLCP2J.js} +2 -2
- package/dist/{chunk-QSHATAXJ.js → chunk-7ONMS7QI.js} +2 -2
- package/dist/{chunk-JBMMWYOH.js → chunk-7UHLO4ZN.js} +35 -2
- package/dist/chunk-7UHLO4ZN.js.map +1 -0
- package/dist/{chunk-6WS35E6X.js → chunk-A52BK5AY.js} +2 -2
- package/dist/{chunk-GOJQ5DZA.js → chunk-AI35LNWQ.js} +4 -4
- package/dist/chunk-AI35LNWQ.js.map +1 -0
- package/dist/{chunk-XXQ5XIYY.js → chunk-AMSSAOOB.js} +2 -2
- package/dist/{chunk-3V6LZHUO.js → chunk-AYOQZJDB.js} +2 -2
- package/dist/{chunk-DL6BZKP3.js → chunk-B3B6HV5S.js} +2 -2
- package/dist/{chunk-5XONHAFD.js → chunk-B6EWMGFX.js} +2 -2
- package/dist/{chunk-6Y5E4SJU.js → chunk-BMAXBTYH.js} +5 -5
- package/dist/{chunk-LGGIFKJP.js → chunk-BNYDOF2Q.js} +4 -4
- package/dist/{chunk-XXNWU5QZ.js → chunk-BQJ5ORU5.js} +2 -2
- package/dist/{chunk-Z3ZXVB2Y.js → chunk-BSEPI3HD.js} +12 -12
- package/dist/chunk-BSEPI3HD.js.map +1 -0
- package/dist/{chunk-BYHCKX73.js → chunk-CLOSXHR4.js} +3 -3
- package/dist/{chunk-5HNW4ZTA.js → chunk-CSAN22QG.js} +6 -6
- package/dist/{chunk-TZYTMZZY.js → chunk-DL4GCSTS.js} +10 -10
- package/dist/{chunk-EA4VDI5D.js → chunk-DYIR6RC3.js} +4 -4
- package/dist/{chunk-PUBI455O.js → chunk-EPPAEGH5.js} +2 -2
- package/dist/{chunk-2A56DSRI.js → chunk-EQ6C2ZPT.js} +17 -51
- package/dist/chunk-EQ6C2ZPT.js.map +1 -0
- package/dist/{chunk-BNFNQNEP.js → chunk-F7X7MPK4.js} +2 -2
- package/dist/{chunk-SNM7LSYG.js → chunk-FUHUGKDN.js} +4 -4
- package/dist/{chunk-72XBVN4J.js → chunk-FVKQ5QUC.js} +2 -2
- package/dist/chunk-FVKQ5QUC.js.map +1 -0
- package/dist/{chunk-D4V5JJAK.js → chunk-GHMINSER.js} +4 -4
- package/dist/{chunk-APFFJN5T.js → chunk-GLSCL74M.js} +31 -34
- package/dist/chunk-GLSCL74M.js.map +1 -0
- package/dist/{chunk-XKBTJGFP.js → chunk-GU6QXHPZ.js} +3 -3
- package/dist/chunk-GU6QXHPZ.js.map +1 -0
- package/dist/{chunk-QGFEBNHO.js → chunk-GZISWBCJ.js} +4 -4
- package/dist/{chunk-OM3SEDI4.js → chunk-HTRLQ4ZZ.js} +4 -4
- package/dist/{chunk-SWXLZ4HX.js → chunk-ICHHNI5E.js} +8 -8
- package/dist/{chunk-K673OO6B.js → chunk-ID4ZBC3X.js} +4 -4
- package/dist/{chunk-H3YM66EI.js → chunk-IF2M43G4.js} +2 -2
- package/dist/{chunk-QGSNJD3B.js → chunk-IFUYLIEY.js} +2 -2
- package/dist/{chunk-D5A3GCZ4.js → chunk-IPF5ORDI.js} +3 -3
- package/dist/{delegation-ONLM4JFI.js → chunk-JQMEXCUZ.js} +59 -16
- package/dist/chunk-JQMEXCUZ.js.map +1 -0
- package/dist/{chunk-TFWFPZRU.js → chunk-K5JNK63R.js} +11 -11
- package/dist/{chunk-TFWFPZRU.js.map → chunk-K5JNK63R.js.map} +1 -1
- package/dist/{chunk-BVF3SXD7.js → chunk-KBIS64X4.js} +5 -5
- package/dist/chunk-L4UL4IAR.js +55 -0
- package/dist/chunk-L4UL4IAR.js.map +1 -0
- package/dist/{chunk-RIZTZJX6.js → chunk-LJ744WXU.js} +2 -2
- package/dist/{chunk-XITHENBI.js → chunk-LMC5L3MM.js} +7 -7
- package/dist/{chunk-XITHENBI.js.map → chunk-LMC5L3MM.js.map} +1 -1
- package/dist/{chunk-L5A3KR7R.js → chunk-LUQBG637.js} +3 -3
- package/dist/{chunk-6QLCS7ET.js → chunk-LZN6DTFI.js} +2 -2
- package/dist/{chunk-NIXRB5BP.js → chunk-MMWX5OT5.js} +2 -2
- package/dist/{chunk-JA25QG5M.js → chunk-N6EWQ5VB.js} +622 -119
- package/dist/chunk-N6EWQ5VB.js.map +1 -0
- package/dist/{chunk-UOZOWN73.js → chunk-ND6S2DKC.js} +2 -2
- package/dist/{chunk-WFWFXDNS.js → chunk-NHEKQWFI.js} +2 -2
- package/dist/{chunk-2ZFD2UJC.js → chunk-NIUHKKMM.js} +9 -9
- package/dist/{chunk-XA34THLF.js → chunk-NK4LGBGQ.js} +4 -4
- package/dist/{chunk-JSWKVZCR.js → chunk-NUZ7ROUZ.js} +2 -2
- package/dist/{chunk-DHU2AQ6T.js → chunk-O3NGOHXQ.js} +2 -2
- package/dist/{chunk-ZBUAX4EF.js → chunk-O6VOR4NH.js} +2 -2
- package/dist/{chunk-JZ4EDEIP.js → chunk-ODBOHPZU.js} +3 -3
- package/dist/{chunk-5UUJE4FP.js → chunk-OK44MD3C.js} +2 -2
- package/dist/{chunk-ECGXA4LT.js → chunk-OR3OHKU6.js} +2 -2
- package/dist/{chunk-ZWF3EWZA.js → chunk-P6FATPXQ.js} +2 -2
- package/dist/{chunk-PCYPXLEX.js → chunk-PBEHTFUG.js} +6 -6
- package/dist/{chunk-7CT6SX4M.js → chunk-PFHDQY5L.js} +3 -3
- package/dist/{chunk-PTJY5R3O.js → chunk-PIO6NW7O.js} +2 -2
- package/dist/{chunk-TMIJAR2X.js → chunk-PREYKC76.js} +3 -3
- package/dist/{chunk-ZHQJAV6D.js → chunk-PU5ZEV65.js} +2 -2
- package/dist/{chunk-UNSQZSZP.js → chunk-PWAMX5KU.js} +2 -2
- package/dist/{chunk-GETUTTZU.js → chunk-PZN76MMV.js} +4 -4
- package/dist/{chunk-ABU6A4Z5.js → chunk-Q4DBU5RM.js} +2 -2
- package/dist/{chunk-2WJKJZSO.js → chunk-QHG7GQKM.js} +2 -2
- package/dist/{chunk-UAKY6E4N.js → chunk-QNOWNCZS.js} +2 -2
- package/dist/{chunk-JPSL5GIZ.js → chunk-QQLXKDGC.js} +3 -3
- package/dist/{chunk-45VHWE4C.js → chunk-QVUMKG3Z.js} +271 -69
- package/dist/chunk-QVUMKG3Z.js.map +1 -0
- package/dist/{chunk-OK57EATL.js → chunk-R4GLRJ55.js} +2 -2
- package/dist/{chunk-B65CC6Z6.js → chunk-RF5WDM25.js} +2 -2
- package/dist/{chunk-G46JSSVX.js → chunk-RKBCUP5D.js} +7 -7
- package/dist/{chunk-GCUMOKTN.js → chunk-S2ORTQGS.js} +3 -3
- package/dist/{chunk-MRJDLXI3.js → chunk-SVXFCCSX.js} +8 -8
- package/dist/{chunk-BUE7R3B5.js → chunk-SXPLIRQH.js} +2 -2
- package/dist/{chunk-5LMCVBMY.js → chunk-T5EXREMW.js} +5 -5
- package/dist/{chunk-PT2YCQVK.js → chunk-TBVDI3LY.js} +4 -4
- package/dist/{chunk-BMHQHH7Q.js → chunk-TLIFNRU5.js} +2 -2
- package/dist/{chunk-YKGJ44Z7.js → chunk-TU6ZJTYT.js} +3 -3
- package/dist/{chunk-FSQNGPHH.js → chunk-U277K5GR.js} +612 -175
- package/dist/chunk-U277K5GR.js.map +1 -0
- package/dist/{chunk-55P6OBB7.js → chunk-U43RSPPX.js} +2 -2
- package/dist/{chunk-K7RW7FI4.js → chunk-UADW5NOU.js} +5 -5
- package/dist/{chunk-GRS2HIV6.js → chunk-UMV5GBTJ.js} +2 -2
- package/dist/{chunk-4UIP3QNW.js → chunk-UNAMWK2Q.js} +2 -2
- package/dist/{chunk-J4KAPKBJ.js → chunk-UORWAG7K.js} +2 -2
- package/dist/{chunk-V55JASXO.js → chunk-UQRKAM2R.js} +3 -3
- package/dist/{chunk-2ELOCEXE.js → chunk-URGHKZPL.js} +1 -1
- package/dist/chunk-URGHKZPL.js.map +1 -0
- package/dist/{chunk-ZMVSKYTJ.js → chunk-VLRY2UH4.js} +10 -10
- package/dist/{chunk-SPPOUJLN.js → chunk-VZFTON37.js} +2 -2
- package/dist/{chunk-CAD7N6HQ.js → chunk-WIUH6EJ7.js} +10 -10
- package/dist/chunk-WIUH6EJ7.js.map +1 -0
- package/dist/{chunk-YQFBH5ZJ.js → chunk-WQUIJPN4.js} +3 -3
- package/dist/{chunk-4J3MNVVX.js → chunk-WRLWEYHY.js} +7 -1
- package/dist/{chunk-4J3MNVVX.js.map → chunk-WRLWEYHY.js.map} +1 -1
- package/dist/{chunk-NZULV7LK.js → chunk-WVQDY3UM.js} +4 -4
- package/dist/{chunk-3Y5JLSXS.js → chunk-X5RGG3ZW.js} +2 -2
- package/dist/{chunk-PFCTSXHU.js → chunk-X6Z2SIRF.js} +2 -2
- package/dist/{chunk-UHFGK6YA.js → chunk-XQGKS4OW.js} +3 -3
- package/dist/{chunk-L2F3CFCH.js → chunk-Y22JWHCP.js} +4 -4
- package/dist/{chunk-C53ER7AG.js → chunk-YVA6UPRN.js} +2 -2
- package/dist/{chunk-226V6XXJ.js → chunk-Z2KP6PNF.js} +6 -6
- package/dist/{chunk-G5EDYVSE.js → chunk-ZK2WT532.js} +5 -5
- package/dist/{chunk-SFCD6OU7.js → chunk-ZNVBCKMV.js} +2 -2
- package/dist/{chunk-BU2ABHFW.js → chunk-ZOFNZLAA.js} +4 -4
- package/dist/{chunk-X2RP4TO5.js → chunk-ZVJKHGE5.js} +7 -7
- package/dist/classified/index.js +5 -5
- package/dist/{classified-marker-KHDOYIJB.js → classified-marker-7HXDMYHI.js} +3 -3
- package/dist/collection-facade-V63BEBGU.js +41 -0
- package/dist/{computed-XMFTHAXV.js → computed-LZLSYOPG.js} +3 -3
- package/dist/consent/index.js +8 -8
- package/dist/cover/index.js +8 -8
- package/dist/custody/index.js +12 -12
- package/dist/{dead-filter-CXV5NS67.js → dead-filter-PZIJ4F4G.js} +10 -10
- package/dist/debug/index.js +7 -7
- package/dist/delegation-7SSGIETH.js +26 -0
- package/dist/derivations/index.js +22 -22
- package/dist/derive-IMI3BMDS.js +20 -0
- package/dist/directory/index.js +9 -9
- package/dist/{dispatch-2MQFMEGY.js → dispatch-4BUYPWMJ.js} +19 -19
- package/dist/{dispatch-OFDA4WQV.js → dispatch-KOPDDPEQ.js} +5 -5
- package/dist/executor-7SY3M6TZ.js +8 -0
- package/dist/executor-SNHW4ELF.js +35 -0
- package/dist/executor-Z3IKK7G3.js +8 -0
- package/dist/export-accessible-O7DIVFUO.js +22 -0
- package/dist/extract-partition-ELZEJKXM.js +35 -0
- package/dist/{fanout-sidecar-BO67PCPO.js → fanout-sidecar-FYDRL7F3.js} +8 -8
- package/dist/find-KWB2RYWJ.js +10 -0
- package/dist/forget/index.js +8 -8
- package/dist/guards/index.js +4 -4
- package/dist/history/index.js +15 -13
- package/dist/history/index.js.map +1 -1
- package/dist/i18n/index.js +13 -13
- package/dist/index.d.ts +3 -2
- package/dist/index.js +111 -107
- package/dist/index.js.map +1 -1
- package/dist/indexing/index.js +5 -5
- package/dist/introspection/index.js +10 -10
- package/dist/issue-5ZHXK4HJ.js +19 -0
- package/dist/kernel/collection.d.ts +85 -6
- package/dist/kernel/constants.d.ts +7 -0
- package/dist/kernel/errors.d.ts +9 -0
- package/dist/kernel/merge-authority.d.ts +5 -1
- package/dist/kernel/noydb.d.ts +116 -21
- package/dist/kernel/rejection-seal.d.ts +13 -0
- package/dist/kernel/sync-wiring.d.ts +55 -0
- package/dist/kernel/types.d.ts +366 -8
- package/dist/kernel/vault.d.ts +39 -5
- package/dist/{ledger-MSJGWKGW.js → ledger-UFJCB6T5.js} +10 -10
- package/dist/liberate-OEOSNNFH.js +25 -0
- package/dist/{link-set-QXXSPPHL.js → link-set-KMUBFN2L.js} +10 -10
- package/dist/{managed-secret-VSK7ANQI.js → managed-secret-H5WYSJ46.js} +9 -9
- package/dist/materialized-views/index.js +25 -25
- package/dist/{migrate-cek-GEBFYBDC.js → migrate-cek-SPESQAAO.js} +2 -2
- package/dist/money/index.js +5 -5
- package/dist/noydb-QDZ4QIKO.js +100 -0
- package/dist/on/index.js +12 -12
- package/dist/overlay-views/index.js +4 -4
- package/dist/periods/index.js +11 -11
- package/dist/pod/index.js +66 -64
- package/dist/{pod-handle-YE7CT66T.js → pod-handle-GJLCOUGK.js} +8 -8
- package/dist/policy/index.js +9 -9
- package/dist/port/at/index.d.ts +1 -1
- package/dist/port/by/index.d.ts +1 -1
- package/dist/port/on/index.d.ts +1 -1
- package/dist/port/with/admission-authority.d.ts +34 -0
- package/dist/port/with/broker-strategy.d.ts +10 -0
- package/dist/port/with/rejection-courier.d.ts +37 -0
- package/dist/port/with/restore-host.d.ts +33 -0
- package/dist/port/with/service-bus.d.ts +18 -0
- package/dist/port/with/team-strategy.d.ts +2 -2
- package/dist/port/with/write-hooks.d.ts +2 -0
- package/dist/portability/index.js +8 -8
- package/dist/{post-register-QC5TEAW3.js → post-register-2AC2STHC.js} +6 -6
- package/dist/query/all/index.js +15 -15
- package/dist/query/index.js +7 -7
- package/dist/query/live/index.js +7 -7
- package/dist/query/reduce/index.js +10 -10
- package/dist/query/relate/index.js +9 -9
- package/dist/reduce/index.js +8 -8
- package/dist/register-PIORIMMR.js +30 -0
- package/dist/registry-BIMICFUH.js +23 -0
- package/dist/registry-JGWLW53D.js +35 -0
- package/dist/registry-SELCBYEQ.js +8 -0
- package/dist/registry-W327UNYH.js +8 -0
- package/dist/request-withdrawal-K3SXXODI.js +28 -0
- package/dist/restore-to-OOPKLAPU.js +66 -0
- package/dist/restore-to-OOPKLAPU.js.map +1 -0
- package/dist/{reveal-YQTRNQFH.js → reveal-UAPBG743.js} +7 -7
- package/dist/revoke-6AFVXTWF.js +24 -0
- package/dist/satellites/index.js +1 -1
- package/dist/schema-update/index.js +2 -2
- package/dist/sealed-record/index.js +11 -11
- package/dist/search/index.js +4 -4
- package/dist/{seed-JMQTRKRE.js → seed-BVYDPVIW.js} +33 -18
- package/dist/seed-BVYDPVIW.js.map +1 -0
- package/dist/sequence/index.js +8 -8
- package/dist/session/index.js +8 -8
- package/dist/shadow/index.js +2 -2
- package/dist/signer-TW5MAQJP.js +23 -0
- package/dist/snapshots/index.js +9 -9
- package/dist/{stale-SKV33PBU.js → stale-CROGJBIJ.js} +9 -9
- package/dist/storage-SO2L2Z5J.js +21 -0
- package/dist/{store-coordination-provider-Z6HKPOGM.js → store-coordination-provider-2YD2PTTP.js} +9 -9
- package/dist/sync/index.js +16 -16
- package/dist/sync/index.js.map +1 -1
- package/dist/team/index.js +15 -15
- package/dist/tiers/index.js +10 -10
- package/dist/to/index.js +2 -2
- package/dist/transactions/index.js +3 -3
- package/dist/util/index.js +1 -1
- package/dist/vault-head/index.js +7 -7
- package/dist/{verify-KWQIWLGH.js → verify-QWO5UKD6.js} +7 -7
- package/dist/walk-3KEOL7BY.js +20 -0
- package/dist/with-audit/guards/types.d.ts +2 -0
- package/dist/with-audit/tiers/index.d.ts +5 -5
- package/dist/with-commit/history/history.d.ts +16 -0
- package/dist/with-commit/history/restore-to.d.ts +40 -0
- package/dist/with-party/broker/seed.d.ts +4 -0
- package/dist/with-party/custody/strategy.d.ts +2 -2
- package/dist/with-party/team/delegation.d.ts +41 -11
- package/dist/with-party/team/index.d.ts +2 -0
- package/dist/with-party/team/keyring.d.ts +133 -3
- package/dist/with-party/team/managed-secret.d.ts +1 -1
- package/dist/with-party/team/noydb-facade.d.ts +14 -2
- package/dist/with-party/team/roster-tag.d.ts +1 -1
- package/dist/with-pod/backup.d.ts +9 -17
- package/dist/with-sync/active.d.ts +28 -1
- package/dist/with-sync/engine.d.ts +59 -2
- package/dist/with-sync/index.d.ts +1 -0
- package/dist/with-sync/reserved-mirror.d.ts +27 -4
- package/dist/with-sync/strategy.d.ts +2 -0
- package/dist/withdraw-accessible-OZU525ND.js +25 -0
- package/dist/withdraw-accessible-OZU525ND.js.map +1 -0
- package/package.json +3 -3
- package/dist/api-MSJXVYQG.js +0 -18
- package/dist/backup-7RKNZMQO.js.map +0 -1
- package/dist/chunk-2A56DSRI.js.map +0 -1
- package/dist/chunk-2ELOCEXE.js.map +0 -1
- package/dist/chunk-45VHWE4C.js.map +0 -1
- package/dist/chunk-72XBVN4J.js.map +0 -1
- package/dist/chunk-APFFJN5T.js.map +0 -1
- package/dist/chunk-CAD7N6HQ.js.map +0 -1
- package/dist/chunk-CB4467G3.js.map +0 -1
- package/dist/chunk-FSQNGPHH.js.map +0 -1
- package/dist/chunk-GOJQ5DZA.js.map +0 -1
- package/dist/chunk-JA25QG5M.js.map +0 -1
- package/dist/chunk-JBMMWYOH.js.map +0 -1
- package/dist/chunk-VSUQI5Q6.js.map +0 -1
- package/dist/chunk-XKBTJGFP.js.map +0 -1
- package/dist/chunk-Z3ZXVB2Y.js.map +0 -1
- package/dist/collection-facade-LZIF7GWD.js +0 -41
- package/dist/delegation-ONLM4JFI.js.map +0 -1
- package/dist/derive-3YSIS36W.js +0 -20
- package/dist/executor-E6YDJ7YA.js +0 -8
- package/dist/executor-NJX3YQQ4.js +0 -35
- package/dist/executor-WWM3DD4P.js +0 -8
- package/dist/export-accessible-RLHU5G4W.js +0 -22
- package/dist/extract-partition-QII2EDCS.js +0 -35
- package/dist/find-6M7GYDUZ.js +0 -10
- package/dist/issue-LPEEEMPP.js +0 -19
- package/dist/liberate-LEKDYKTC.js +0 -25
- package/dist/noydb-F2AUF6KL.js +0 -98
- package/dist/register-SN72QALV.js +0 -30
- package/dist/registry-253FF7C6.js +0 -35
- package/dist/registry-3AZWQTDT.js +0 -23
- package/dist/registry-7UEBTHWG.js +0 -8
- package/dist/registry-IVJ67NFQ.js +0 -8
- package/dist/request-withdrawal-UKVJZKX2.js +0 -28
- package/dist/revoke-G2KXJQA5.js +0 -24
- package/dist/seed-JMQTRKRE.js.map +0 -1
- package/dist/signer-IUIYR3CX.js +0 -23
- package/dist/storage-NPBYP2SM.js +0 -21
- package/dist/walk-F4OLXI5H.js +0 -20
- package/dist/withdraw-accessible-ZKPLZ66E.js +0 -25
- /package/dist/{api-MSJXVYQG.js.map → api-H4B7ZQXP.js.map} +0 -0
- /package/dist/{capsule-57BDK7LG.js.map → capsule-YQKQZPH7.js.map} +0 -0
- /package/dist/{chunk-AJFPAHMW.js.map → chunk-27NCEPKM.js.map} +0 -0
- /package/dist/{chunk-PGC35KXE.js.map → chunk-2IASHJPS.js.map} +0 -0
- /package/dist/{chunk-NYJBYVBG.js.map → chunk-2ODEFG6K.js.map} +0 -0
- /package/dist/{chunk-7BMOS4JQ.js.map → chunk-2QH3I7QC.js.map} +0 -0
- /package/dist/{chunk-IVMFIKNA.js.map → chunk-2T2TGRWE.js.map} +0 -0
- /package/dist/{chunk-G66YXUTY.js.map → chunk-35CNOVQE.js.map} +0 -0
- /package/dist/{chunk-OJU67C23.js.map → chunk-3EXQXOQ2.js.map} +0 -0
- /package/dist/{chunk-BJH77UY2.js.map → chunk-4KYKRYRT.js.map} +0 -0
- /package/dist/{chunk-RDOEOPOI.js.map → chunk-4N4OIVK3.js.map} +0 -0
- /package/dist/{chunk-WHOKGHJ3.js.map → chunk-4WLI37WK.js.map} +0 -0
- /package/dist/{chunk-RNACRT5H.js.map → chunk-52ZFNK46.js.map} +0 -0
- /package/dist/{chunk-QDHHHI5Q.js.map → chunk-5SMCBPJ2.js.map} +0 -0
- /package/dist/{chunk-EMAWOGVH.js.map → chunk-654RE5YC.js.map} +0 -0
- /package/dist/{chunk-FZXRLNJO.js.map → chunk-6BEBWHNL.js.map} +0 -0
- /package/dist/{chunk-EUD3HQM4.js.map → chunk-6WEPFEMJ.js.map} +0 -0
- /package/dist/{chunk-YFFMPZPY.js.map → chunk-6WIFF46H.js.map} +0 -0
- /package/dist/{chunk-ZVSKSUGI.js.map → chunk-7C7OF26T.js.map} +0 -0
- /package/dist/{chunk-QXJXG7DN.js.map → chunk-7IV7GVOS.js.map} +0 -0
- /package/dist/{chunk-MQ7YWBQ5.js.map → chunk-7JRLCP2J.js.map} +0 -0
- /package/dist/{chunk-QSHATAXJ.js.map → chunk-7ONMS7QI.js.map} +0 -0
- /package/dist/{chunk-6WS35E6X.js.map → chunk-A52BK5AY.js.map} +0 -0
- /package/dist/{chunk-XXQ5XIYY.js.map → chunk-AMSSAOOB.js.map} +0 -0
- /package/dist/{chunk-3V6LZHUO.js.map → chunk-AYOQZJDB.js.map} +0 -0
- /package/dist/{chunk-DL6BZKP3.js.map → chunk-B3B6HV5S.js.map} +0 -0
- /package/dist/{chunk-5XONHAFD.js.map → chunk-B6EWMGFX.js.map} +0 -0
- /package/dist/{chunk-6Y5E4SJU.js.map → chunk-BMAXBTYH.js.map} +0 -0
- /package/dist/{chunk-LGGIFKJP.js.map → chunk-BNYDOF2Q.js.map} +0 -0
- /package/dist/{chunk-XXNWU5QZ.js.map → chunk-BQJ5ORU5.js.map} +0 -0
- /package/dist/{chunk-BYHCKX73.js.map → chunk-CLOSXHR4.js.map} +0 -0
- /package/dist/{chunk-5HNW4ZTA.js.map → chunk-CSAN22QG.js.map} +0 -0
- /package/dist/{chunk-TZYTMZZY.js.map → chunk-DL4GCSTS.js.map} +0 -0
- /package/dist/{chunk-EA4VDI5D.js.map → chunk-DYIR6RC3.js.map} +0 -0
- /package/dist/{chunk-PUBI455O.js.map → chunk-EPPAEGH5.js.map} +0 -0
- /package/dist/{chunk-BNFNQNEP.js.map → chunk-F7X7MPK4.js.map} +0 -0
- /package/dist/{chunk-SNM7LSYG.js.map → chunk-FUHUGKDN.js.map} +0 -0
- /package/dist/{chunk-D4V5JJAK.js.map → chunk-GHMINSER.js.map} +0 -0
- /package/dist/{chunk-QGFEBNHO.js.map → chunk-GZISWBCJ.js.map} +0 -0
- /package/dist/{chunk-OM3SEDI4.js.map → chunk-HTRLQ4ZZ.js.map} +0 -0
- /package/dist/{chunk-SWXLZ4HX.js.map → chunk-ICHHNI5E.js.map} +0 -0
- /package/dist/{chunk-K673OO6B.js.map → chunk-ID4ZBC3X.js.map} +0 -0
- /package/dist/{chunk-H3YM66EI.js.map → chunk-IF2M43G4.js.map} +0 -0
- /package/dist/{chunk-QGSNJD3B.js.map → chunk-IFUYLIEY.js.map} +0 -0
- /package/dist/{chunk-D5A3GCZ4.js.map → chunk-IPF5ORDI.js.map} +0 -0
- /package/dist/{chunk-BVF3SXD7.js.map → chunk-KBIS64X4.js.map} +0 -0
- /package/dist/{chunk-RIZTZJX6.js.map → chunk-LJ744WXU.js.map} +0 -0
- /package/dist/{chunk-L5A3KR7R.js.map → chunk-LUQBG637.js.map} +0 -0
- /package/dist/{chunk-6QLCS7ET.js.map → chunk-LZN6DTFI.js.map} +0 -0
- /package/dist/{chunk-NIXRB5BP.js.map → chunk-MMWX5OT5.js.map} +0 -0
- /package/dist/{chunk-UOZOWN73.js.map → chunk-ND6S2DKC.js.map} +0 -0
- /package/dist/{chunk-WFWFXDNS.js.map → chunk-NHEKQWFI.js.map} +0 -0
- /package/dist/{chunk-2ZFD2UJC.js.map → chunk-NIUHKKMM.js.map} +0 -0
- /package/dist/{chunk-XA34THLF.js.map → chunk-NK4LGBGQ.js.map} +0 -0
- /package/dist/{chunk-JSWKVZCR.js.map → chunk-NUZ7ROUZ.js.map} +0 -0
- /package/dist/{chunk-DHU2AQ6T.js.map → chunk-O3NGOHXQ.js.map} +0 -0
- /package/dist/{chunk-ZBUAX4EF.js.map → chunk-O6VOR4NH.js.map} +0 -0
- /package/dist/{chunk-JZ4EDEIP.js.map → chunk-ODBOHPZU.js.map} +0 -0
- /package/dist/{chunk-5UUJE4FP.js.map → chunk-OK44MD3C.js.map} +0 -0
- /package/dist/{chunk-ECGXA4LT.js.map → chunk-OR3OHKU6.js.map} +0 -0
- /package/dist/{chunk-ZWF3EWZA.js.map → chunk-P6FATPXQ.js.map} +0 -0
- /package/dist/{chunk-PCYPXLEX.js.map → chunk-PBEHTFUG.js.map} +0 -0
- /package/dist/{chunk-7CT6SX4M.js.map → chunk-PFHDQY5L.js.map} +0 -0
- /package/dist/{chunk-PTJY5R3O.js.map → chunk-PIO6NW7O.js.map} +0 -0
- /package/dist/{chunk-TMIJAR2X.js.map → chunk-PREYKC76.js.map} +0 -0
- /package/dist/{chunk-ZHQJAV6D.js.map → chunk-PU5ZEV65.js.map} +0 -0
- /package/dist/{chunk-UNSQZSZP.js.map → chunk-PWAMX5KU.js.map} +0 -0
- /package/dist/{chunk-GETUTTZU.js.map → chunk-PZN76MMV.js.map} +0 -0
- /package/dist/{chunk-ABU6A4Z5.js.map → chunk-Q4DBU5RM.js.map} +0 -0
- /package/dist/{chunk-2WJKJZSO.js.map → chunk-QHG7GQKM.js.map} +0 -0
- /package/dist/{chunk-UAKY6E4N.js.map → chunk-QNOWNCZS.js.map} +0 -0
- /package/dist/{chunk-JPSL5GIZ.js.map → chunk-QQLXKDGC.js.map} +0 -0
- /package/dist/{chunk-OK57EATL.js.map → chunk-R4GLRJ55.js.map} +0 -0
- /package/dist/{chunk-B65CC6Z6.js.map → chunk-RF5WDM25.js.map} +0 -0
- /package/dist/{chunk-G46JSSVX.js.map → chunk-RKBCUP5D.js.map} +0 -0
- /package/dist/{chunk-GCUMOKTN.js.map → chunk-S2ORTQGS.js.map} +0 -0
- /package/dist/{chunk-MRJDLXI3.js.map → chunk-SVXFCCSX.js.map} +0 -0
- /package/dist/{chunk-BUE7R3B5.js.map → chunk-SXPLIRQH.js.map} +0 -0
- /package/dist/{chunk-5LMCVBMY.js.map → chunk-T5EXREMW.js.map} +0 -0
- /package/dist/{chunk-PT2YCQVK.js.map → chunk-TBVDI3LY.js.map} +0 -0
- /package/dist/{chunk-BMHQHH7Q.js.map → chunk-TLIFNRU5.js.map} +0 -0
- /package/dist/{chunk-YKGJ44Z7.js.map → chunk-TU6ZJTYT.js.map} +0 -0
- /package/dist/{chunk-55P6OBB7.js.map → chunk-U43RSPPX.js.map} +0 -0
- /package/dist/{chunk-K7RW7FI4.js.map → chunk-UADW5NOU.js.map} +0 -0
- /package/dist/{chunk-GRS2HIV6.js.map → chunk-UMV5GBTJ.js.map} +0 -0
- /package/dist/{chunk-4UIP3QNW.js.map → chunk-UNAMWK2Q.js.map} +0 -0
- /package/dist/{chunk-J4KAPKBJ.js.map → chunk-UORWAG7K.js.map} +0 -0
- /package/dist/{chunk-V55JASXO.js.map → chunk-UQRKAM2R.js.map} +0 -0
- /package/dist/{chunk-ZMVSKYTJ.js.map → chunk-VLRY2UH4.js.map} +0 -0
- /package/dist/{chunk-SPPOUJLN.js.map → chunk-VZFTON37.js.map} +0 -0
- /package/dist/{chunk-YQFBH5ZJ.js.map → chunk-WQUIJPN4.js.map} +0 -0
- /package/dist/{chunk-NZULV7LK.js.map → chunk-WVQDY3UM.js.map} +0 -0
- /package/dist/{chunk-3Y5JLSXS.js.map → chunk-X5RGG3ZW.js.map} +0 -0
- /package/dist/{chunk-PFCTSXHU.js.map → chunk-X6Z2SIRF.js.map} +0 -0
- /package/dist/{chunk-UHFGK6YA.js.map → chunk-XQGKS4OW.js.map} +0 -0
- /package/dist/{chunk-L2F3CFCH.js.map → chunk-Y22JWHCP.js.map} +0 -0
- /package/dist/{chunk-C53ER7AG.js.map → chunk-YVA6UPRN.js.map} +0 -0
- /package/dist/{chunk-226V6XXJ.js.map → chunk-Z2KP6PNF.js.map} +0 -0
- /package/dist/{chunk-G5EDYVSE.js.map → chunk-ZK2WT532.js.map} +0 -0
- /package/dist/{chunk-SFCD6OU7.js.map → chunk-ZNVBCKMV.js.map} +0 -0
- /package/dist/{chunk-BU2ABHFW.js.map → chunk-ZOFNZLAA.js.map} +0 -0
- /package/dist/{chunk-X2RP4TO5.js.map → chunk-ZVJKHGE5.js.map} +0 -0
- /package/dist/{classified-marker-KHDOYIJB.js.map → classified-marker-7HXDMYHI.js.map} +0 -0
- /package/dist/{collection-facade-LZIF7GWD.js.map → collection-facade-V63BEBGU.js.map} +0 -0
- /package/dist/{computed-XMFTHAXV.js.map → computed-LZLSYOPG.js.map} +0 -0
- /package/dist/{dead-filter-CXV5NS67.js.map → dead-filter-PZIJ4F4G.js.map} +0 -0
- /package/dist/{derive-3YSIS36W.js.map → delegation-7SSGIETH.js.map} +0 -0
- /package/dist/{executor-E6YDJ7YA.js.map → derive-IMI3BMDS.js.map} +0 -0
- /package/dist/{dispatch-2MQFMEGY.js.map → dispatch-4BUYPWMJ.js.map} +0 -0
- /package/dist/{dispatch-OFDA4WQV.js.map → dispatch-KOPDDPEQ.js.map} +0 -0
- /package/dist/{executor-NJX3YQQ4.js.map → executor-7SY3M6TZ.js.map} +0 -0
- /package/dist/{executor-WWM3DD4P.js.map → executor-SNHW4ELF.js.map} +0 -0
- /package/dist/{export-accessible-RLHU5G4W.js.map → executor-Z3IKK7G3.js.map} +0 -0
- /package/dist/{extract-partition-QII2EDCS.js.map → export-accessible-O7DIVFUO.js.map} +0 -0
- /package/dist/{find-6M7GYDUZ.js.map → extract-partition-ELZEJKXM.js.map} +0 -0
- /package/dist/{fanout-sidecar-BO67PCPO.js.map → fanout-sidecar-FYDRL7F3.js.map} +0 -0
- /package/dist/{issue-LPEEEMPP.js.map → find-KWB2RYWJ.js.map} +0 -0
- /package/dist/{ledger-MSJGWKGW.js.map → issue-5ZHXK4HJ.js.map} +0 -0
- /package/dist/{liberate-LEKDYKTC.js.map → ledger-UFJCB6T5.js.map} +0 -0
- /package/dist/{link-set-QXXSPPHL.js.map → liberate-OEOSNNFH.js.map} +0 -0
- /package/dist/{managed-secret-VSK7ANQI.js.map → link-set-KMUBFN2L.js.map} +0 -0
- /package/dist/{noydb-F2AUF6KL.js.map → managed-secret-H5WYSJ46.js.map} +0 -0
- /package/dist/{migrate-cek-GEBFYBDC.js.map → migrate-cek-SPESQAAO.js.map} +0 -0
- /package/dist/{register-SN72QALV.js.map → noydb-QDZ4QIKO.js.map} +0 -0
- /package/dist/{pod-handle-YE7CT66T.js.map → pod-handle-GJLCOUGK.js.map} +0 -0
- /package/dist/{post-register-QC5TEAW3.js.map → post-register-2AC2STHC.js.map} +0 -0
- /package/dist/{registry-253FF7C6.js.map → register-PIORIMMR.js.map} +0 -0
- /package/dist/{registry-3AZWQTDT.js.map → registry-BIMICFUH.js.map} +0 -0
- /package/dist/{registry-7UEBTHWG.js.map → registry-JGWLW53D.js.map} +0 -0
- /package/dist/{registry-IVJ67NFQ.js.map → registry-SELCBYEQ.js.map} +0 -0
- /package/dist/{request-withdrawal-UKVJZKX2.js.map → registry-W327UNYH.js.map} +0 -0
- /package/dist/{revoke-G2KXJQA5.js.map → request-withdrawal-K3SXXODI.js.map} +0 -0
- /package/dist/{reveal-YQTRNQFH.js.map → reveal-UAPBG743.js.map} +0 -0
- /package/dist/{signer-IUIYR3CX.js.map → revoke-6AFVXTWF.js.map} +0 -0
- /package/dist/{stale-SKV33PBU.js.map → signer-TW5MAQJP.js.map} +0 -0
- /package/dist/{storage-NPBYP2SM.js.map → stale-CROGJBIJ.js.map} +0 -0
- /package/dist/{walk-F4OLXI5H.js.map → storage-SO2L2Z5J.js.map} +0 -0
- /package/dist/{store-coordination-provider-Z6HKPOGM.js.map → store-coordination-provider-2YD2PTTP.js.map} +0 -0
- /package/dist/{verify-KWQIWLGH.js.map → verify-QWO5UKD6.js.map} +0 -0
- /package/dist/{withdraw-accessible-ZKPLZ66E.js.map → walk-3KEOL7BY.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
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, RevokeResult, 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<RevokeResult>\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 {\n deriveSecretKey,\n generateSalt,\n encryptBytes,\n decryptBytes,\n bufferToBase64,\n base64ToBuffer,\n exportDekSet,\n importDekSet,\n type EnclaveKey,\n} from '../../capsule/index.js'\nimport { InvalidKeyError, TamperedError } from '../../kernel/errors.js'\n\nconst PBKDF2_ITERATIONS = 600_000\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. Serialized through the enclave's\n * `exportDekSet` door (the hub mints DEKs extractable;\n * consumers feeding non-extractable keys will get\n * `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 = generateSalt()\n const wrappingKey = await deriveWrappingKey(credential, salt)\n\n // Serialize the DEK set as JSON `{ deks: { collection: base64 } }`.\n const plaintext = new TextEncoder().encode(JSON.stringify({ deks: await exportDekSet(deks) }))\n const { iv, data } = await encryptBytes(plaintext, wrappingKey)\n\n return { salt: bufferToBase64(salt), iv, wrappedDeks: data }\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, base64ToBuffer(blob.salt))\n let plaintext: Uint8Array\n try {\n plaintext = await decryptBytes(blob.iv, blob.wrappedDeks, wrappingKey)\n } catch (e) {\n // The barrel reports an AEAD failure as TamperedError — which means\n // exactly \"did not authenticate under THIS key\" and is the enclave's to\n // throw (lanna-db #4). Here the key was derived from a user-supplied\n // credential, so the overwhelmingly likely cause is a wrong recovery code\n // / password / share set, and saying \"tampered\" is the misdiagnosis\n // #1288 reported. Translate to the class whose contract already reads\n // \"wrong secret or corrupted keyring\"; on-password does the same one\n // layer up. Anything else propagates untouched.\n if (e instanceof TamperedError) {\n throw new InvalidKeyError('Wrapped DEK set did not open — the credential does not match this blob, or the blob is corrupted')\n }\n throw e\n }\n const parsed = JSON.parse(new TextDecoder().decode(plaintext)) as { deks: Record<string, string> }\n return importDekSet(parsed.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","/**\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, bufferToBase64, generateRecoverySecret } from '../../capsule/index.js'\nimport type { EnclaveKey } from '../../capsule/index.js'\nimport {\n mintWrappedDeksBlob,\n unwrapDeksFromBlob,\n type WrappedDeksBlob,\n} from './wrapped-deks.js'\nimport type { NoydbShamir } from './noydb-shamir.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: NoydbShamir,\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 = generateRecoverySecret()\n try {\n const credential = bufferToBase64(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: NoydbShamir,\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, bufferToBase64(secret))\n } finally {\n secret.fill(0)\n }\n}\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 wrap crypto lives in the canonical wrap-DEKs primitive at\n// `./wrapped-deks.ts` and is reached via\n// `mintWrappedDeksBlob` / `unwrapDeksFromBlob`; base64 comes from the\n// enclave barrel.\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, sha256Bytes, hkdfAesGcmKey, type EnclaveKey } from '../../capsule/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/**\n * HKDF `info` for the AES-KW KEK. Matches `@noy-db/on-magic-link`.\n *\n * No importer inside hub, and that is not a defect: this is one half of a\n * CROSS-PACKAGE protocol constant. The satellite derives the same KEK from\n * the same string, so the value has to be stated here to be reviewable\n * against it. Deleting it would leave the wire format pinned in one repo\n * only (#55).\n *\n * @seam\n */\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 ikmBytes =\n serverSecret instanceof Uint8Array\n ? serverSecret\n : new TextEncoder().encode(serverSecret)\n const salt = await sha256Bytes(new TextEncoder().encode(token))\n const info = new TextEncoder().encode(MAGIC_LINK_CONTENT_INFO_PREFIX + vault)\n return hkdfAesGcmKey(ikmBytes, salt, info)\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 // ⛔ COLLECTION-WIDE IS NOT SUPPORTED HERE, and after core#56 the reason is\n // specific to this function rather than shared with `issueDelegation`.\n //\n // A magic-link grant wraps ONE source DEK under ONE derived grant KEK. \"Every\n // collection\" needs one wrapped DEK PER COLLECTION, because each collection\n // has its own tier DEK — measured, `docs#1` and `ledger#1` are different\n // keys. `issueDelegation` now expresses that with a `wrappedDeks` MAP; this\n // record shape carries a single `wrappedDek` and cannot.\n //\n // ⚠️ The wildcard slot `__any#<tier>` this branch used to read is GONE. It\n // could never have worked: one key cannot decrypt two collections, so a\n // wildcard accepted at the gate would pass the check and then fail\n // decryption. Do not reintroduce it here.\n //\n // The real consumer is `@noy-db/on-magic-link`'s `issueMagicLinkDelegation()`\n // in the `on` repo, so this message is the only thing telling them which side\n // the fault is on and what the supported shape is.\n if (!collectionName) {\n throw new DelegationTargetMissingError(\n opts.toUser,\n `writeMagicLinkGrant({ collection: undefined }) — a magic-link grant carries a ` +\n `single wrapped DEK and cannot express \"every collection\", because each ` +\n `collection has its own tier-${opts.tier} DEK. Pass an explicit \\`collection\\`, ` +\n `or use a collection-wide delegation token (core#56).`,\n )\n }\n const sourceDek = grantor.deks.get(dekKey(collectionName, opts.tier))\n if (!sourceDek) {\n throw new DelegationTargetMissingError(\n opts.toUser,\n `grantor holds no tier-${opts.tier} DEK for collection \"${collectionName}\", ` +\n `so there is nothing to grant. Obtain the tier grant first.`,\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 deriveKey,\n deriveEchoKey,\n generateSalt,\n wrapKey,\n unwrapKey,\n bufferToBase64,\n base64ToBuffer,\n type EnclaveKey,\n type EchoSecretParts,\n} from '../../capsule/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 { NoydbShamir } from './noydb-shamir.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, writeKeyringFile, basisOf } from './keyring.js'\nimport { assertRosterAuthenticated, mintRosterTag } from './roster-tag.js'\nimport { stampAuthority } from './roster-tag.js'\nimport { ROSTER_KEY_ID } from '../../kernel/constants.js'\nimport { buildEchoBlock } from './echo-secret.js'\nimport type { NoydbDeviceSeal } 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?: NoydbDeviceSeal\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 // #1097 — stamped BEFORE the tag is minted, so it lands inside the\n // authenticated canonical and a store can neither edit nor strip it.\n const withEpoch = stampAuthority(rebuilt, found?.file.roster_epoch)\n const next: KeyringFile = {\n ...withEpoch,\n roster_tag: await mintRosterTag(withEpoch, requireRecoveredRosterKey(deks)),\n }\n\n await writeKeyringFile(store, vault, userId, next, basisOf(found))\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 `NoydbShamir.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: NoydbShamir | 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/noy-db/core/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 // #1097 — stamped BEFORE the tag is minted, so it lands inside the\n // authenticated canonical and a store can neither edit nor strip it.\n const withEpoch = stampAuthority(rebuilt, found?.file.roster_epoch)\n const next: KeyringFile = {\n ...withEpoch,\n roster_tag: await mintRosterTag(withEpoch, 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, basisOf(found))\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: NoydbShamir | 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 NoydbShamir — 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 // #1097 — stamped BEFORE the tag is minted, so it lands inside the\n // authenticated canonical and a store can neither edit nor strip it.\n const withEpoch = stampAuthority(rebuilt, file.roster_epoch)\n const next: KeyringFile = {\n ...withEpoch,\n roster_tag: await mintRosterTag(withEpoch, 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, basisOf(found))\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\n// core#132 — the local copy of `writeKeyringFile` was DELETED here. It was\n// byte-identical to `keyring.ts`'s, comment included, so hardening one left the\n// other unprotected under a name a reader would assume was shared. Imported now.\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, generateDEK } from '../../capsule/index.js'\nimport { BROKER_MEMBER_COLLECTION } from './reserved-secret-collections.js'\nimport { INBOX_KEY_ID } from '../../kernel/constants.js'\nimport { mintInboxKey, inboxSlots } from './keyring.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'\nimport { stampAuthority } 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 // core#73 — `_broker_member` is the one DEK a keyring holds that its\n // grantor never did: minted per grantee at grant time. It is not carried\n // over (the caller cannot unwrap it) but MINTED AFRESH below, and the\n // kernel re-enrols the member with the broker host under the new key.\n // core#96 — `_inbox_key` is the same kind of key (per member, minted at\n // grant, never the grantor's); a fresh inbox pair is minted below. A DEK\n // still in the target's undrained inbox is one they were handed and may\n // hold: it goes straight into the recovered file, under the new KEK.\n const carriedSlots = [...Object.keys(target.deks), ...inboxSlots(target)]\n for (const coll of carriedSlots) {\n if (coll === BROKER_MEMBER_COLLECTION || coll === INBOX_KEY_ID) continue\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 if (targetRole !== 'owner' && targetRole !== 'admin') {\n wrappedDeks[BROKER_MEMBER_COLLECTION] = await wrapKey(await generateDEK(), newKek) // core#73\n }\n const inbox = await mintInboxKey(newKek) // core#96\n wrappedDeks[INBOX_KEY_ID] = inbox.wrappedInboxKey\n for (const coll of carriedSlots) {\n if (coll === BROKER_MEMBER_COLLECTION || coll === INBOX_KEY_ID) continue\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 (core#96: the inbox was folded into `wrappedDeks`, the pair is re-minted)\n const { echo: _staleEcho, inbox: _drainedInbox, ...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 inbox_key: inbox.inboxKey,\n }\n // #1097 — stamped BEFORE the tag is minted, so it lands inside the\n // authenticated canonical and a store can neither edit nor strip it.\n const withEpoch = stampAuthority(edited, target.roster_epoch)\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 ...withEpoch,\n roster_tag: await mintRosterTag(withEpoch, 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 // core#132 — CAS on the file this recovery was computed from (read at\n // `found` above). A peer recovery races any concurrent admin edit to the\n // same member, and losing that race used to be silent.\n const base = found?.envelope._v ?? 0\n const envelope = buildRecordEnvelope(\n { collection: '_keyring', id: options.userId, version: base + 1 },\n { iv: '', data: JSON.stringify(next) },\n )\n await store.put(vault, '_keyring', options.userId, envelope, found ? base : undefined)\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/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, rotateKeys, NON_ROTATABLE_SLOTS } from './keyring.js'\nimport { rotateSecret, type SlotRewrapCeremony } from './rotate-recover.js'\nimport type { RotateSecretInput } from './rotate-recover.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 assertSlotListVisible(keyring, 'enrollAuthenticator', vault)\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 assertSlotListVisible(keyring, 'updateAuthenticator', vault)\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 * Refuse any slot-list decision taken from a keyring that cannot be\n * persisted (#1426).\n *\n * `UnlockedKeyring.authenticators` is a snapshot, and a tier-3\n * PIN-resumed / session-restored keyring carries an EMPTY one\n * alongside `kek === null` — not because the vault has no slots, but\n * because that session never unwrapped the KEK and so never read\n * them. Deciding \"the slot isn't there\" from that snapshot answers a\n * question the session cannot see the answer to.\n *\n * `persistKeyring` already refuses a null KEK, so every write path\n * here ends in a throw regardless. What this guard buys is that the\n * throw happens BEFORE the decision instead of after it — otherwise\n * `removeAuthenticator` short-circuits on the empty list and returns\n * a successful no-op, and `updateAuthenticator` reports the slot as\n * \"not found\" when the truthful answer is \"not visible from here\".\n *\n * Same class as the `echo` / `granted_by` / `expires_at` carry-forward\n * comments in `persistKeyring`: an UnlockedKeyring is a partial view,\n * and treating an absent field as a known-empty one silently destroys\n * or misreports state.\n */\nfunction assertSlotListVisible(\n keyring: UnlockedKeyring,\n op: string,\n vault: string,\n): void {\n if (keyring.kek) return\n throw new ValidationError(\n `${op}: keyring.kek is null, so the authenticator slot list for vault ` +\n `\"${vault}\" is not readable from this session and no slot decision can ` +\n 'be made. This typically means the keyring was opened via tier-3 PIN ' +\n 'resume, session restore, or a wrap-DEKs tier-2 unlock. Re-authenticate ' +\n 'at tier 1 (secret) before enrolling, updating or removing a slot.',\n )\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 *\n * ⛔ **THIS HIDES A CREDENTIAL. IT DOES NOT REVOKE ONE.** (#1445) The slot\n * leaves the keyring file and nothing else happens — no key material moves. A\n * slot blob captured before removal, or cached by an honest client earlier in\n * the same session, still unwraps the FULL LIVE DEK SET and reads every record,\n * for as long as those DEKs remain current.\n *\n * That is not a leak in one `on-*` package. `@noy-db/on-password`'s\n * `unwrapDeksWithPassword` and `@noy-db/on-webauthn`'s `unwrapKeyringSummary`\n * both carry the DEK map inside the blob and need no store, no keyring and no\n * network — the blob authenticates itself. A membership check inside a verifier\n * cannot close it, because a blob holder calls the primitive directly and never\n * reaches the verifier.\n *\n * ⭐ To actually revoke, see {@link revokeAuthenticator} — removal, then a DEK\n * rotation, then a re-wrap of the slots that stay. Every step is required and\n * the reasons are measured, not assumed; read that doc before assembling the\n * sequence by hand.\n *\n * ⚠️ Idempotency is only sound when the slot list is actually\n * visible — see {@link assertSlotListVisible} (#1426).\n *\n * @throws `ValidationError` when the session cannot see the slot list.\n */\nexport async function removeAuthenticator(\n store: NoydbStore,\n vault: string,\n keyring: UnlockedKeyring,\n slotId: string,\n): Promise<UnlockedKeyring> {\n assertSlotListVisible(keyring, 'removeAuthenticator', vault)\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\n/** Inputs for {@link revokeAuthenticator}. */\nexport interface RevokeAuthenticatorOptions {\n /** The slot to revoke. */\n readonly slotId: string\n /**\n * The vault owner's CURRENT secret. Passed as both `oldSecret` and\n * `newSecret` to `rotateSecret`, which accepts them being equal — measured,\n * so revoking one credential does not force everyone onto a new phrase.\n */\n readonly secret: RotateSecretInput['oldSecret']\n /**\n * A re-wrap ceremony for EVERY slot that stays, keyed by slot id.\n *\n * ⛔ A slot with no ceremony is DROPPED, not preserved — that is\n * `rotateSecret`'s existing behaviour (#29 / PR5: \"without `slotCeremonies`,\n * rotation drops every slot\"), and it is the honest outcome, because after\n * step 2 its blob wraps DEKs that no longer exist. Supplying one requires\n * that credential to be present: the password for `on-password`, a live\n * assertion for `on-webauthn`. There is no way around that — re-wrapping a\n * credential is the credential's own operation.\n */\n readonly slotCeremonies?: { readonly [slotId: string]: SlotRewrapCeremony }\n}\n\n/**\n * Actually revoke an authenticator slot: remove it, mint fresh DEKs, and\n * re-wrap the slots that stay (#1445).\n *\n * ## Why this is three steps and not one\n *\n * Each was measured, because the composition looks obvious and the obvious\n * compositions do not work:\n *\n * 1. **{@link removeAuthenticator}** hides the slot. On its own it revokes\n * nothing — the captured blob carries its own DEKs.\n * 2. **`rotateKeys`** is the step that revokes. It is the ONLY one that calls\n * `generateDEK()`. Measured: a collection's DEK is byte-identical across a\n * `rotateSecret` and different across a `rotateKeys`.\n * ⚠️ `rotateSecret` alone does NOT revoke, however it reads:\n * it unwraps every DEK with the old KEK and rewraps THE SAME KEY MATERIAL\n * under the new one. A captured blob holds DEK VALUES and records are\n * encrypted with DEKs, so rewrapping them changes nothing the holder needs.\n * 3. **`rotateSecret` with `slotCeremonies`** re-wraps the remaining slots\n * around the new DEKs. Without it they survive step 2 BYTE-IDENTICAL\n * (measured: `rotateKeys` never touches `authenticators[]`) and therefore\n * silently wrap keys that no longer exist — every other credential in the\n * vault dies quietly. This step is what makes the operation safe for\n * everyone who was not being revoked.\n *\n * ⭐ Neither primitive is sufficient alone and they are not interchangeable:\n * `rotateKeys` mints keys but cannot re-wrap slots; `rotateSecret` re-wraps\n * slots but cannot mint keys.\n *\n * ## Cost\n *\n * Step 2 re-encrypts every record in every affected collection, and every\n * remaining credential holder must be present for step 3. This is expensive on\n * purpose: it is what revocation costs when the credential is a bearer token.\n *\n * @throws `ValidationError` when the session cannot see the slot list\n * ({@link assertSlotListVisible}) — a tier-1 unlock is required, and #1432\n * guarantees the KEK rotation needs is present at this point.\n */\nexport async function revokeAuthenticator(\n store: NoydbStore,\n vault: string,\n keyring: UnlockedKeyring,\n options: RevokeAuthenticatorOptions,\n): Promise<UnlockedKeyring> {\n // 1. Hide it. Also runs the #1426 visibility guard, so everything below is\n // reached only from a session that can actually see (and persist) slots.\n const next = await removeAuthenticator(store, vault, keyring, options.slotId)\n\n // 2. Mint fresh DEKs — the step that revokes.\n // The set is derived from the DEK map the way `revoke` derives its own,\n // minus the reserved slots that are KEYS rather than collections —\n // {@link NON_ROTATABLE_SLOTS}, the one list. `rotateKeys` throws on each if\n // named explicitly, so they are dropped here at the site that gathers them\n // implicitly. ⛔ This was a hand-copied pair (roster key, blob root) and it\n // broke the day the list grew (core#65's inbox key), which is why the list\n // now lives in one place.\n const collections = new Set(next.deks.keys())\n for (const slot of NON_ROTATABLE_SLOTS) collections.delete(slot)\n if (collections.size > 0) {\n await rotateKeys(store, vault, next, { collections: [...collections] })\n }\n\n // 3. Re-wrap the slots that stay, around the DEKs step 2 just minted.\n // `oldSecret === newSecret` is accepted (measured), so this re-wraps\n // without forcing a phrase change. A slot with no ceremony is dropped —\n // see `slotCeremonies`.\n return rotateSecret(store, vault, next.userId, {\n oldSecret: options.secret,\n newSecret: options.secret,\n ...(options.slotCeremonies !== undefined && { slotCeremonies: options.slotCeremonies }),\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,IAAI,oBAAoB;AAAA,EAAE;AAAA,EACjD,MAAM,eAAe;AAAE,UAAM,IAAI,oBAAoB;AAAA,EAAE;AAAA,EACvD,MAAM,oBAAoB;AAAE,UAAM,IAAI,oBAAoB;AAAA,EAAE;AAC9D;;;ACAA,IAAM,oBAAoB;AA8C1B,eAAsB,oBACpB,M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ACkC;AAClC,SAAO,QAAQ,eAAe,KAAK,CAAC,MAAM,EAAE,OAAO,MAAM;AAC3D;AAEA,SAAS,WACP,SACA,MACiB;AACjB,SAAO;AAAA,IACL,GAAG;AAAA,IACH,gBAAgB,CAAC,GAAG,QAAQ,gBAAgB,IAAI;AAAA,EAClD;AACF;AAiEA,eAAsB,oBACpB,OACA,OACA,SACA,SAC0B;AAG1B,QAAM,OAAO,MAAM,oBAAoB,OAAO,OAAO,SAAS,QAAQ,MAAM;AAU5E,QAAM,cAAc,IAAI,IAAI,KAAK,KAAK,KAAK,CAAC;AAC5C,aAAW,QAAQ,oBAAqB,aAAY,OAAO,IAAI;AAC/D,MAAI,YAAY,OAAO,GAAG;AACxB,UAAM,WAAW,OAAO,OAAO,MAAM,EAAE,aAAa,CAAC,GAAG,WAAW,EAAE,CAAC;AAAA,EACxE;AAMA,SAAO,aAAa,OAAO,OAAO,KAAK,QAAQ;AAAA,IAC7C,WAAW,QAAQ;AAAA,IACnB,WAAW,QAAQ;AAAA,IACnB,GAAI,QAAQ,mBAAmB,UAAa,EAAE,gBAAgB,QAAQ,eAAe;AAAA,EACvF,CAAC;AACH;","names":["deks"]}
|
|
@@ -10,7 +10,7 @@ import {
|
|
|
10
10
|
importTransferKey,
|
|
11
11
|
recipientUnwrap,
|
|
12
12
|
recipientWrap
|
|
13
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-WRLWEYHY.js";
|
|
14
14
|
|
|
15
15
|
// src/with-party/team/managed-secret.ts
|
|
16
16
|
var MemorySealer = class {
|
|
@@ -42,7 +42,7 @@ var MemorySealer = class {
|
|
|
42
42
|
* says `unseal` MUST throw on tamper, and a double that silently returns
|
|
43
43
|
* corrupted bytes is not modelling the contract it stands in for. Without
|
|
44
44
|
* it, every managed-mode test ran against a provider that could not fail
|
|
45
|
-
* the way a real one must (found by @noy-db/
|
|
45
|
+
* the way a real one must (found by @noy-db/ports/at).
|
|
46
46
|
*/
|
|
47
47
|
tag(cipher) {
|
|
48
48
|
let a = 2654435769;
|
|
@@ -249,4 +249,4 @@ export {
|
|
|
249
249
|
loadSealedSecret,
|
|
250
250
|
resolveManagedSecret
|
|
251
251
|
};
|
|
252
|
-
//# sourceMappingURL=chunk-
|
|
252
|
+
//# sourceMappingURL=chunk-GU6QXHPZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/with-party/team/managed-secret.ts"],"sourcesContent":["/**\n * Managed-secret mode — rubber-hose-resistant vaults.\n *\n * A vault mode where the secret is machine-generated and never\n * exposed to the user, sealed under a developer-provided\n * {@link NoydbSealer} (macOS Keychain, Windows Credential\n * Manager, libsecret, AWS KMS, …). The user has no secret to give\n * up to coercion — they can't reveal what they don't know.\n *\n * ## Components in this file\n *\n * - {@link NoydbSealer} — the interface concrete providers\n * implement. Provider implementations live OUTSIDE hub (per-\n * platform packages).\n * - {@link MemorySealer} — in-memory test provider; uses\n * a deterministic per-instance \"key\" so two providers with\n * different ids cannot unseal each other's outputs.\n * - {@link RecipientHint} — public material a sender uses to seal\n * plaintext for a specific recipient; published by\n * {@link RecipientSealer.publishRecipientHint} and transported\n * out-of-band to the sender before bundle writes.\n * - {@link RecipientSealer} — interface for asymmetric/granted\n * providers that support recipient-target sealing (RSA-OAEP,\n * cloud-KMS asymmetric, etc.); distinct from self-only\n * {@link NoydbSealer} (macOS Keychain, WebAuthn-PRF).\n * - {@link MemoryRecipientSealer} — in-process reference\n * implementation of both `RecipientSealer` and\n * `NoydbSealer` using real WebCrypto RSA-OAEP + AES-GCM;\n * safe for tests and same-process sender/recipient scenarios.\n * - {@link loadSealedSecret} / {@link saveSealedSecret} —\n * plaintext envelope storage at `_meta/sealed-secret`.\n * Mirrors the `_meta/handle` and `_meta/public-envelope` AES-\n * GCM-bypassed patterns. The sealing layer (provider's job)\n * is the security boundary; hub doesn't have a key to encrypt\n * with at this layer — that's the whole point of the design.\n * - {@link resolveManagedSecret} — orchestrates the \"generate +\n * seal + persist on first open; unseal on reopen\" flow.\n * Returns the plaintext secret string that the rest of the\n * `createNoydb` keyring path consumes.\n *\n * Deferred to follow-ups:\n * - Block `rotate-secret` policy gate under managed mode.\n * - Mandatory strong-recovery enforcement.\n * - Recovery flow under managed mode (generates fresh sealed phrase).\n *\n * @see https://github.com/noy-db/docs/blob/main/content/docs/services/session-tiers.md → Managed-secret mode\n *\n * @module\n */\n\nimport {\n buildRecordEnvelope,\n importTransferKey,\n encryptBytes,\n decryptBytes,\n bufferToBase64,\n base64ToBuffer,\n generateRecipientKeyPair,\n exportRecipientPublicKeySpki,\n importRecipientPublicKeySpki,\n recipientWrap,\n recipientUnwrap,\n type EnclaveKeyPair,\n} from '../../capsule/index.js'\nimport type { NoydbStore, RecipientSealer } from '../../kernel/types.js'\n\n/**\n * The contract concrete providers (per-platform key stores) implement\n * to seal and unseal a hub-generated random secret. The plaintext\n * secret NEVER leaves hub-controlled memory in unsealed form —\n * the provider receives the bytes, returns opaque sealed bytes, and\n * later reverses the operation. Hub treats the sealed bytes as\n * fully opaque.\n *\n * Implementations live OUTSIDE `@noy-db/hub` (separate packages\n * per the issue's \"Concrete providers (live outside hub)\" note):\n *\n * | Platform | Package (TBD) | Backing |\n * |---|---|---|\n * | macOS | `@noy-db/seal-macos-keychain` | Security.framework |\n * | Windows | `@noy-db/seal-wincred` | Credential Manager |\n * | Linux | `@noy-db/seal-libsecret` | libsecret / secret-service |\n * | Cloud / server | `@noy-db/seal-aws-kms` | AWS KMS Decrypt |\n */\nexport interface NoydbSealer {\n /**\n * Non-sensitive identifier disclosed in the persisted envelope.\n * Surfaced to consumers via `loadSealedSecret().providerId` so\n * a vault opened with the wrong provider class can detect the\n * mismatch and surface a clear error. NOT secret — fine to log.\n *\n * Suggested format: `<family>:<scope>` — e.g. `macos-keychain:com.acme.app`,\n * `aws-kms:arn:aws:kms:us-east-1:123:key/abc`. The hub never\n * parses this; it's purely audit metadata.\n */\n readonly id: string\n\n /** Seal raw secret bytes. Output bytes are opaque to hub. */\n seal(secret: Uint8Array): Promise<Uint8Array>\n\n /**\n * Reverse {@link seal}. MUST throw on tamper, wrong-provider, or\n * any other failure — hub treats a thrown error as \"this provider\n * cannot unlock this vault\" and surfaces it to the caller.\n */\n unseal(sealed: Uint8Array): Promise<Uint8Array>\n}\n\n/**\n * In-memory test provider. NOT secure — uses a deterministic\n * per-instance \"key\" (16-byte SHA-256 of `id`) XOR'd over the\n * secret plus a 4-byte provider-id fingerprint prefix. The XOR is\n * sufficient to make different `id` values produce mutually-unsealable\n * outputs (the contract tests for that), but offers ZERO real\n * confidentiality — never use outside tests.\n *\n * Replace with a real platform provider in production.\n */\nexport class MemorySealer implements NoydbSealer {\n readonly id: string\n private readonly fingerprint: Uint8Array\n private readonly keyBytes: Uint8Array\n\n constructor(opts: { id: string }) {\n this.id = opts.id\n // Deterministic 4-byte fingerprint of the provider id, prepended\n // to every sealed output so we can detect \"wrong provider\" at\n // unseal time without leaking anything sensitive about either\n // provider's actual key material.\n const encoded = new TextEncoder().encode(opts.id)\n let h = 0\n for (let i = 0; i < encoded.length; i++) {\n h = (h * 31 + encoded[i]!) >>> 0\n }\n this.fingerprint = new Uint8Array([\n (h >>> 24) & 0xff, (h >>> 16) & 0xff, (h >>> 8) & 0xff, h & 0xff,\n ])\n // Deterministic 16-byte \"key\" derived from the id by repeating\n // the fingerprint with offsets. Good enough for the XOR-stream\n // test cipher; never confuse this with real key derivation.\n this.keyBytes = new Uint8Array(16)\n for (let i = 0; i < 16; i++) {\n this.keyBytes[i] = this.fingerprint[i % 4]! ^ (i * 17)\n }\n }\n\n /**\n * Deterministic 4-byte integrity tag over the ciphertext, keyed by the\n * same derived bytes. NOT a MAC and not forgery-resistant — a real\n * provider authenticates with its backend. It exists because the contract\n * says `unseal` MUST throw on tamper, and a double that silently returns\n * corrupted bytes is not modelling the contract it stands in for. Without\n * it, every managed-mode test ran against a provider that could not fail\n * the way a real one must (found by @noy-db/ports/at).\n */\n private tag(cipher: Uint8Array): Uint8Array {\n let a = 0x9e3779b9\n for (let i = 0; i < cipher.length; i++) {\n a = ((a ^ (cipher[i]! ^ this.keyBytes[i % 16]!)) * 0x01000193) >>> 0\n }\n return new Uint8Array([(a >>> 24) & 0xff, (a >>> 16) & 0xff, (a >>> 8) & 0xff, a & 0xff])\n }\n\n async seal(secret: Uint8Array): Promise<Uint8Array> {\n const cipher = new Uint8Array(secret.length)\n for (let i = 0; i < secret.length; i++) {\n cipher[i] = secret[i]! ^ this.keyBytes[i % 16]!\n }\n const out = new Uint8Array(8 + secret.length)\n out.set(this.fingerprint, 0)\n out.set(this.tag(cipher), 4)\n out.set(cipher, 8)\n return out\n }\n\n async unseal(sealed: Uint8Array): Promise<Uint8Array> {\n if (sealed.length < 8) {\n throw new Error('MemorySealer: sealed input too short')\n }\n for (let i = 0; i < 4; i++) {\n if (sealed[i] !== this.fingerprint[i]) {\n throw new Error(\n `MemorySealer(\"${this.id}\"): provider-id mismatch on unseal `\n + '(sealed bytes were produced by a different provider)',\n )\n }\n }\n const cipher = sealed.subarray(8)\n const expected = this.tag(cipher)\n for (let i = 0; i < 4; i++) {\n if (sealed[4 + i] !== expected[i]) {\n throw new Error(\n `MemorySealer(\"${this.id}\"): integrity check failed on unseal `\n + '(the sealed bytes were modified after sealing)',\n )\n }\n }\n const out = new Uint8Array(cipher.length)\n for (let i = 0; i < cipher.length; i++) {\n out[i] = cipher[i]! ^ this.keyBytes[i % 16]!\n }\n return out\n }\n}\n\n/**\n * Public material a sender uses to seal-for-this-recipient. Published by\n * a recipient's RecipientSealer; transported to the sender out-of-band\n * (email, S3, in-app message). The sender obtains the hint, supplies it\n * to writePod's sealedCredentials.perUser[userId].hint, and the\n * hub seals each user's credential against it. Per foundation §11.4.\n */\nexport type RecipientHint = {\n readonly v: 1\n /** Recipient's provider id; matches the SealedAutoUnlockEntry.pid they'll unseal under. */\n readonly pid: string\n /** Algorithm the sender uses to produce the seal. Slice 1 ships RSA-OAEP-SHA256 only. */\n readonly alg: 'rsa-oaep-sha256'\n /** Public material — alg-specific. For 'rsa-oaep-sha256': { publicKeyPem: string }. */\n readonly material: Readonly<Record<string, unknown>>\n}\n\n// Hoisted to kernel/types.ts (C3 — enclave self-containment: sealing.ts\n// consumes this as a spine-owned contract type). Re-exported here so existing\n// importers of this module are unaffected.\nexport type { RecipientSealer } from '../../kernel/types.js'\n\n/**\n * Shared RSA-OAEP-SHA256 + AES-GCM seal in the canonical recipient-target\n * TLV wire format. Mints a fresh 32-byte CEK, AES-GCM-encrypts `plaintext`\n * under it, RSA-OAEP-SHA256-wraps the CEK to `publicKeyPem`, and packs:\n *\n * byte 0 : version (0x01)\n * bytes 1..256 : RSA-OAEP-wrapped CEK (fixed 256 bytes at RSA-2048)\n * bytes 257..268: AES-GCM IV (12 bytes)\n * bytes 269.. : AES-GCM ciphertext ‖ 16-byte tag\n *\n * This is the single source of truth for the wire format — both\n * {@link MemoryRecipientSealer} and external sealers (e.g. `@noy-db/at-aws-kms`'s\n * asymmetric-KMS recipient sealer) call it so a blob sealed by one unseals\n * by the other. WebCrypto RSA-OAEP/SHA-256 here is wire-compatible with\n * AWS KMS `RSAES_OAEP_SHA_256` (both RSAES-OAEP, SHA-256 hash, MGF1-SHA256,\n * empty label).\n *\n * @public — re-exported from the hub barrel for external sealer packages.\n */\nexport async function sealRsaOaepTlv(plaintext: Uint8Array, publicKeyPem: string): Promise<Uint8Array> {\n // Parse PEM → SPKI bytes.\n const b64 = publicKeyPem.replace(/-----BEGIN PUBLIC KEY-----/, '').replace(/-----END PUBLIC KEY-----/, '').replace(/\\s+/g, '')\n const recipientPub = await importRecipientPublicKeySpki(base64ToBytes(b64))\n // Mint fresh CEK, AES-GCM encrypt plaintext.\n const cekBytes = crypto.getRandomValues(new Uint8Array(32))\n const cek = await importTransferKey(cekBytes)\n const { iv: ivB64, data } = await encryptBytes(plaintext, cek)\n const iv = base64ToBuffer(ivB64)\n const ct = base64ToBuffer(data)\n // RSA-OAEP-wrap the CEK bytes.\n const wrapped = await recipientWrap(recipientPub, cekBytes)\n cekBytes.fill(0)\n if (wrapped.length !== 256) {\n throw new Error(`sealRsaOaepTlv: expected 256-byte RSA-OAEP wrap, got ${wrapped.length}`)\n }\n // TLV layout.\n const out = new Uint8Array(1 + 256 + 12 + ct.length)\n out[0] = 0x01\n out.set(wrapped, 1)\n out.set(iv, 1 + 256)\n out.set(ct, 1 + 256 + 12)\n return out\n}\n\n/**\n * Parse a {@link sealRsaOaepTlv} blob into its three segments without\n * decrypting. The `wrapped` CEK is RSA-OAEP-SHA256 ciphertext over a\n * 32-byte CEK — the unwrap step is pluggable: {@link MemoryRecipientSealer}\n * decrypts it with a local RSA private key; `@noy-db/at-aws-kms` hands it to\n * KMS `Decrypt`. After unwrapping, pass the CEK + `iv` + `ct` to\n * {@link aesGcmOpen}.\n *\n * @public — re-exported from the hub barrel for external sealer packages.\n */\nexport function parseRsaOaepTlv(bytes: Uint8Array): { wrapped: Uint8Array; iv: Uint8Array; ct: Uint8Array } {\n if (bytes.length < 1 + 256 + 12 + 16) {\n throw new Error('parseRsaOaepTlv: sealed input too short')\n }\n if (bytes[0] !== 0x01) {\n throw new Error(`parseRsaOaepTlv: unknown TLV version ${bytes[0]}`)\n }\n return {\n wrapped: bytes.subarray(1, 1 + 256),\n iv: bytes.subarray(1 + 256, 1 + 256 + 12),\n ct: bytes.subarray(1 + 256 + 12),\n }\n}\n\n/**\n * AES-GCM-decrypt the `ct` segment of a {@link parseRsaOaepTlv} result under\n * the unwrapped 32-byte CEK and its `iv`. Throws on a bad tag (tamper) — the\n * same authenticated-decryption guarantee the TLV relies on.\n *\n * @public — re-exported from the hub barrel for external sealer packages.\n */\nexport async function aesGcmOpen(cekBytes: Uint8Array, iv: Uint8Array, ct: Uint8Array): Promise<Uint8Array> {\n const cek = await importTransferKey(cekBytes)\n return decryptBytes(bufferToBase64(iv), bufferToBase64(ct), cek)\n}\n\n/**\n * Reference implementation of `RecipientSealer` + `NoydbSealer`.\n * Uses WebCrypto RSA-OAEP-SHA256 (2048-bit) to wrap a fresh 32-byte\n * AES-GCM CEK, AES-GCM-encrypts plaintext under it, and packs the\n * result into a self-describing TLV:\n *\n * byte 0 : version (0x01)\n * bytes 1..256 : RSA-OAEP-wrapped CEK (fixed 256 bytes at RSA-2048)\n * bytes 257..268: AES-GCM IV (12 bytes)\n * bytes 269.. : AES-GCM ciphertext ‖ 16-byte tag\n *\n * Implements BOTH interfaces. `seal(plaintext)` (self-target) is just\n * `sealForRecipient(plaintext, this own hint)` — same TLV. Convenient\n * for tests where one provider plays both ends. Real cloud providers\n * (`at-aws-kms`, etc.) will pick their own internal layouts; the only\n * contract is round-trip identity.\n *\n * SAFE for production within its scope — the cryptography is real\n * (RSA-OAEP + AES-GCM via WebCrypto), but the keypair lives in-process\n * and is regenerated on every construction. Not suitable as a managed\n * keychain; use it for tests and for shipping bundles where the\n * recipient instance lives in the same process as the sender (rare).\n */\nexport class MemoryRecipientSealer implements NoydbSealer, RecipientSealer {\n readonly id: string\n private readonly keypair: Promise<EnclaveKeyPair>\n\n constructor(opts: { id: string }) {\n this.id = opts.id\n this.keypair = generateRecipientKeyPair()\n }\n\n async publishRecipientHint(): Promise<RecipientHint> {\n const spki = await exportRecipientPublicKeySpki(await this.keypair)\n const pem = '-----BEGIN PUBLIC KEY-----\\n'\n + bytesToBase64(spki).match(/.{1,64}/g)!.join('\\n')\n + '\\n-----END PUBLIC KEY-----\\n'\n return { v: 1, pid: this.id, alg: 'rsa-oaep-sha256', material: { publicKeyPem: pem } }\n }\n\n async sealForRecipient(plaintext: Uint8Array, hint: RecipientHint): Promise<Uint8Array> {\n if (hint.v !== 1) {\n throw new Error(`MemoryRecipientSealer.sealForRecipient: unsupported hint.v ${String(hint.v)} (expected 1)`)\n }\n if (hint.alg !== 'rsa-oaep-sha256') {\n throw new Error(`MemoryRecipientSealer.sealForRecipient: unsupported hint.alg '${String(hint.alg)}' (expected 'rsa-oaep-sha256')`)\n }\n const pem = hint.material['publicKeyPem']\n if (typeof pem !== 'string') {\n throw new Error('MemoryRecipientSealer.sealForRecipient: hint.material.publicKeyPem missing or not a string')\n }\n return sealRsaOaepTlv(plaintext, pem)\n }\n\n async seal(plaintext: Uint8Array): Promise<Uint8Array> {\n const hint = await this.publishRecipientHint()\n return this.sealForRecipient(plaintext, hint)\n }\n\n async unseal(bytes: Uint8Array): Promise<Uint8Array> {\n const { wrapped, iv, ct } = parseRsaOaepTlv(bytes)\n // Local RSA-OAEP-SHA256 unwrap of the CEK — the pluggable step external\n // sealers replace with KMS Decrypt.\n const cekBytes = await recipientUnwrap(await this.keypair, wrapped)\n const pt = await aesGcmOpen(cekBytes, iv, ct)\n cekBytes.fill(0)\n return pt\n }\n}\n\n// ─── Persisted envelope ────────────────────────────────────────────────\n\n/** Reserved id for the managed-secret envelope under `_meta`. */\nexport const SEALED_SECRET_RECORD_ID = 'sealed-secret' as const\n\n/** Plaintext payload stored inside the `_meta/sealed-secret` envelope. */\nexport interface SealedSecret {\n readonly _noydb_sealed: 1\n readonly providerId: string\n /** Sealed bytes. Base64-encoded on the wire; decoded on load. */\n readonly sealed: Uint8Array\n}\n\n/**\n * Wire-format envelope persisted at `_meta/sealed-secret` for\n * managed-mode vaults. The provider produces raw sealed bytes via\n * {@link NoydbSealer.seal}; this wrapper carries the dispatch\n * metadata hub needs to pick the right provider on the unseal path.\n *\n * Stability boundary: once shipped, the wire format only grows by\n * adding optional fields. See the at-* sealing dimension foundation\n * doc, §11.9.1.\n *\n * v1 shape (this release): `{ v: 1, _noydb_sealed: 1, pid, payload }`.\n *\n * Legacy shape (earlier releases): `{ _noydb_sealed: 1, providerId, sealed }`\n * — accepted on read for backwards compatibility; never produced on\n * write going forward.\n */\nexport interface SealedEnvelope {\n /** Envelope schema version. v1 is the current shape. */\n readonly v: 1\n /** Magic marker for forensics + legacy-shape detection. */\n readonly _noydb_sealed: 1\n /** Matches the producing provider's `.id`. Dispatch key on unseal. */\n readonly pid: string\n /** Sealed bytes from the provider, base64-encoded on the wire. */\n readonly payload: string\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n let binary = ''\n for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]!)\n return btoa(binary)\n}\n\nfunction base64ToBytes(b64: string): Uint8Array {\n const binary = atob(b64)\n const out = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i)\n return out\n}\n\n/**\n * Parse a `_meta/sealed-secret` `_data` JSON string into the\n * in-memory {@link SealedSecret} representation. Accepts both:\n *\n * 1. v1 wire format `{ v: 1, _noydb_sealed: 1, pid, payload }` —\n * the current shape.\n * 2. Legacy wire format `{ _noydb_sealed: 1, providerId, sealed }` —\n * read-only; never written\n * going forward.\n *\n * Returns `undefined` for any input that doesn't match either shape,\n * so callers can fall back to \"no managed-mode envelope present.\"\n *\n * @internal — exported only for the migration safety-net test suite.\n */\nexport function parseSealedEnvelope(raw: unknown): SealedSecret | undefined {\n if (typeof raw !== 'object' || raw === null) return undefined\n const r = raw as Record<string, unknown>\n if (r._noydb_sealed !== 1) return undefined\n\n // v1 shape — preferred.\n if (\n r.v === 1\n && typeof r.pid === 'string'\n && typeof r.payload === 'string'\n ) {\n return {\n _noydb_sealed: 1,\n providerId: r.pid,\n sealed: base64ToBytes(r.payload),\n }\n }\n\n // Legacy shape — earlier releases. Accept on read for compat.\n if (\n typeof r.providerId === 'string'\n && typeof r.sealed === 'string'\n ) {\n return {\n _noydb_sealed: 1,\n providerId: r.providerId,\n sealed: base64ToBytes(r.sealed),\n }\n }\n\n return undefined\n}\n\nexport async function saveSealedSecret(\n store: NoydbStore,\n vault: string,\n payload: { readonly providerId: string; readonly sealed: Uint8Array },\n): Promise<void> {\n const persisted: SealedEnvelope = {\n v: 1,\n _noydb_sealed: 1,\n pid: payload.providerId,\n payload: bytesToBase64(payload.sealed),\n }\n const prior = await store.get(vault, '_meta', SEALED_SECRET_RECORD_ID)\n const env = buildRecordEnvelope(\n { collection: '_meta', id: SEALED_SECRET_RECORD_ID, version: (prior?._v ?? 0) + 1 },\n // AES-GCM bypassed — the sealing layer is the security boundary.\n { iv: '', data: JSON.stringify(persisted) },\n )\n await store.put(vault, '_meta', SEALED_SECRET_RECORD_ID, env)\n}\n\nexport async function loadSealedSecret(\n store: NoydbStore,\n vault: string,\n): Promise<SealedSecret | undefined> {\n const envelope = await store.get(vault, '_meta', SEALED_SECRET_RECORD_ID)\n if (!envelope) return undefined\n try {\n return parseSealedEnvelope(JSON.parse(envelope._data ?? ''))\n } catch {\n return undefined\n }\n}\n\n// ─── createNoydb orchestration ─────────────────────────────────────────\n\n/**\n * Resolve the effective plaintext secret string for a managed-mode\n * vault. Two paths:\n *\n * 1. **First open (no envelope persisted):** generate a 256-bit random\n * via `crypto.getRandomValues`, base64-encode for use as a\n * secret string, seal the underlying bytes under the\n * provider, persist `_meta/sealed-secret`, return the\n * base64 string.\n *\n * 2. **Reopen (envelope exists):** read + unseal + decode → return.\n * A different provider whose `seal` output disagrees on the\n * stored bytes throws here, surfaced as a clear error.\n *\n * The returned string is the same shape that `secret:` would take in\n * standard mode — the rest of the keyring path consumes it\n * unchanged.\n *\n * @internal — called from `createNoydb` / `getKeyringInternal`.\n */\nexport async function resolveManagedSecret(\n store: NoydbStore,\n vault: string,\n provider: NoydbSealer,\n): Promise<string> {\n const existing = await loadSealedSecret(store, vault)\n if (existing) {\n if (existing.providerId !== provider.id) {\n throw new Error(\n `Managed-mode vault \"${vault}\" was sealed under provider id `\n + `\"${existing.providerId}\" but the current NoydbSealer is `\n + `\"${provider.id}\". Pass the same provider that originally enrolled `\n + 'the vault, or treat this as a fresh enrollment and clear '\n + '`_meta/sealed-secret` first.',\n )\n }\n const plaintext = await provider.unseal(existing.sealed)\n return bytesToBase64(plaintext)\n }\n\n // First open: mint a 256-bit random, seal, persist.\n const random = new Uint8Array(32)\n globalThis.crypto.getRandomValues(random)\n const sealed = await provider.seal(random)\n await saveSealedSecret(store, vault, { providerId: provider.id, sealed })\n return bytesToBase64(random)\n}\n"],"mappings":";;;;;;;;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AA,EACT;AACF;AAwBA,eAAsB,qBACpB,OACA,OACA,UACiB;AACjB,QAAM,WAAW,MAAM,iBAAiB,OAAO,KAAK;AACpD,MAAI,UAAU;AACZ,QAAI,SAAS,eAAe,SAAS,IAAI;AACvC,YAAM,IAAI;AAAA,QACR,uBAAuB,KAAK,mCACtB,SAAS,UAAU,qCACnB,SAAS,EAAE;AAAA,MAGnB;AAAA,IACF;AACA,UAAM,YAAY,MAAM,SAAS,OAAO,SAAS,MAAM;AACvD,WAAO,cAAc,SAAS;AAAA,EAChC;AAGA,QAAM,SAAS,IAAI,WAAW,EAAE;AAChC,aAAW,OAAO,gBAAgB,MAAM;AACxC,QAAM,SAAS,MAAM,SAAS,KAAK,MAAM;AACzC,QAAM,iBAAiB,OAAO,OAAO,EAAE,YAAY,SAAS,IAAI,OAAO,CAAC;AACxE,SAAO,cAAc,MAAM;AAC7B;","names":[]}
|
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
import {
|
|
2
2
|
splitAroundJoins
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-7C7OF26T.js";
|
|
4
4
|
import {
|
|
5
5
|
evaluateClause,
|
|
6
6
|
hasFnClause,
|
|
7
7
|
normalizeMatches,
|
|
8
8
|
normalizeSubqueryOperand
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-SXPLIRQH.js";
|
|
10
10
|
import {
|
|
11
11
|
FieldNotQueryableError,
|
|
12
12
|
QueryExtensionMissingError
|
|
13
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-2RH5SEY7.js";
|
|
14
14
|
|
|
15
15
|
// src/kernel/query/scan-builder.ts
|
|
16
16
|
var DEFAULT_SCAN_PAGE_SIZE = 100;
|
|
@@ -190,4 +190,4 @@ for (const [method, subpath] of SCAN_EXTENSION_METHODS) {
|
|
|
190
190
|
export {
|
|
191
191
|
ScanBuilder
|
|
192
192
|
};
|
|
193
|
-
//# sourceMappingURL=chunk-
|
|
193
|
+
//# sourceMappingURL=chunk-GZISWBCJ.js.map
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
2
|
normalizeForVerify
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-EPPAEGH5.js";
|
|
4
4
|
import {
|
|
5
5
|
NOYDB_FORMAT_VERSION,
|
|
6
6
|
SealedHandle
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-URGHKZPL.js";
|
|
8
8
|
import {
|
|
9
9
|
ClassifiedConfigError,
|
|
10
10
|
DebugReservedFieldError,
|
|
@@ -12,7 +12,7 @@ import {
|
|
|
12
12
|
RecordCekNotFoundError,
|
|
13
13
|
SchemaValidationError,
|
|
14
14
|
ValidationError
|
|
15
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-2RH5SEY7.js";
|
|
16
16
|
|
|
17
17
|
// src/capsule/plumbing/record-aad.ts
|
|
18
18
|
var SCHEME = "noydb-aad/2";
|
|
@@ -1372,4 +1372,4 @@ export {
|
|
|
1372
1372
|
makeCapsule,
|
|
1373
1373
|
ctEqualTags
|
|
1374
1374
|
};
|
|
1375
|
-
//# sourceMappingURL=chunk-
|
|
1375
|
+
//# sourceMappingURL=chunk-HTRLQ4ZZ.js.map
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
2
|
SCHEMAS_COLLECTION
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-IF2M43G4.js";
|
|
4
4
|
import {
|
|
5
5
|
assemblePodContainer,
|
|
6
6
|
buildExtractedPartitionWrapper
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-4N4OIVK3.js";
|
|
8
8
|
import {
|
|
9
9
|
BLOB_CHUNKS_COLLECTION,
|
|
10
10
|
BLOB_COLLECTION,
|
|
@@ -12,7 +12,7 @@ import {
|
|
|
12
12
|
BLOB_INTENT_COLLECTION,
|
|
13
13
|
BLOB_SLOTS_PREFIX,
|
|
14
14
|
BLOB_VERSIONS_PREFIX
|
|
15
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-7IV7GVOS.js";
|
|
16
16
|
import {
|
|
17
17
|
generateULID
|
|
18
18
|
} from "./chunk-4AOERLTV.js";
|
|
@@ -23,7 +23,7 @@ import {
|
|
|
23
23
|
canonicalJson,
|
|
24
24
|
envelopePayloadHash,
|
|
25
25
|
hashEntry
|
|
26
|
-
} from "./chunk-
|
|
26
|
+
} from "./chunk-QHG7GQKM.js";
|
|
27
27
|
import {
|
|
28
28
|
base64ToBuffer,
|
|
29
29
|
bufferToBase64,
|
|
@@ -43,13 +43,13 @@ import {
|
|
|
43
43
|
unwrapCek,
|
|
44
44
|
wrapCek,
|
|
45
45
|
writeEnvelopeBody
|
|
46
|
-
} from "./chunk-
|
|
46
|
+
} from "./chunk-WRLWEYHY.js";
|
|
47
47
|
import {
|
|
48
48
|
NOYDB_BACKUP_VERSION
|
|
49
|
-
} from "./chunk-
|
|
49
|
+
} from "./chunk-URGHKZPL.js";
|
|
50
50
|
import {
|
|
51
51
|
PartitionExtractionError
|
|
52
|
-
} from "./chunk-
|
|
52
|
+
} from "./chunk-2RH5SEY7.js";
|
|
53
53
|
|
|
54
54
|
// src/with-cargo/walk-closure.ts
|
|
55
55
|
async function walkClosure(vault, opts) {
|
|
@@ -490,4 +490,4 @@ export {
|
|
|
490
490
|
extractPartition,
|
|
491
491
|
extractPartitionCore
|
|
492
492
|
};
|
|
493
|
-
//# sourceMappingURL=chunk-
|
|
493
|
+
//# sourceMappingURL=chunk-ICHHNI5E.js.map
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import {
|
|
2
2
|
installViaBinder
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-PIO6NW7O.js";
|
|
4
4
|
import {
|
|
5
5
|
SealedHandle
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-URGHKZPL.js";
|
|
7
7
|
import {
|
|
8
8
|
ClassifiedConfigError,
|
|
9
9
|
ClassifiedNotEnabledError
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-2RH5SEY7.js";
|
|
11
11
|
|
|
12
12
|
// src/via/classified/descriptor.ts
|
|
13
13
|
function isClassifiedFieldSpec(x) {
|
|
@@ -270,4 +270,4 @@ export {
|
|
|
270
270
|
enforceClassifiedWrite,
|
|
271
271
|
NO_CLASSIFIED
|
|
272
272
|
};
|
|
273
|
-
//# sourceMappingURL=chunk-
|
|
273
|
+
//# sourceMappingURL=chunk-ID4ZBC3X.js.map
|
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
buildRecordEnvelope,
|
|
4
4
|
encrypt,
|
|
5
5
|
openEnvelopeJson
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-WRLWEYHY.js";
|
|
7
7
|
|
|
8
8
|
// src/with-shape/persisted-schemas/storage.ts
|
|
9
9
|
var SCHEMAS_COLLECTION = "_schemas";
|
|
@@ -41,4 +41,4 @@ export {
|
|
|
41
41
|
loadPersistedSchema,
|
|
42
42
|
savePersistedSchema
|
|
43
43
|
};
|
|
44
|
-
//# sourceMappingURL=chunk-
|
|
44
|
+
//# sourceMappingURL=chunk-IF2M43G4.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
CargoNotEnabledError
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-2RH5SEY7.js";
|
|
4
4
|
|
|
5
5
|
// src/with-cargo/strategy.ts
|
|
6
6
|
var NO_CARGO = {
|
|
@@ -12,4 +12,4 @@ var NO_CARGO = {
|
|
|
12
12
|
export {
|
|
13
13
|
NO_CARGO
|
|
14
14
|
};
|
|
15
|
-
//# sourceMappingURL=chunk-
|
|
15
|
+
//# sourceMappingURL=chunk-IFUYLIEY.js.map
|
|
@@ -5,10 +5,10 @@ import {
|
|
|
5
5
|
generateSigningKeyPair,
|
|
6
6
|
openEnvelopeJson,
|
|
7
7
|
sha256Hex
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-WRLWEYHY.js";
|
|
9
9
|
import {
|
|
10
10
|
ConflictError
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-2RH5SEY7.js";
|
|
12
12
|
|
|
13
13
|
// src/with-audit/attestation/signer.ts
|
|
14
14
|
var ATTESTATIONS_COLLECTION = "_attestations";
|
|
@@ -54,4 +54,4 @@ export {
|
|
|
54
54
|
loadSigner,
|
|
55
55
|
loadOrCreateSigner
|
|
56
56
|
};
|
|
57
|
-
//# sourceMappingURL=chunk-
|
|
57
|
+
//# sourceMappingURL=chunk-IPF5ORDI.js.map
|