@noy-db/hub 0.6.0-pre.2 → 0.6.0-pre.21
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 +5234 -0
- package/codemods/0.4.0-pre.json +699 -0
- package/codemods/0.6.0-pre.json +211 -0
- package/dist/api-EYNT6KGS.js +20 -0
- package/dist/attestation/index.js +19 -19
- package/dist/{backup-YYBE5RPC.js → backup-FSC36VWC.js} +36 -18
- package/dist/backup-FSC36VWC.js.map +1 -0
- package/dist/blobs/index.js +13 -13
- package/dist/broker/index.js +12 -12
- package/dist/cargo/index.js +33 -33
- package/dist/{chunk-35EBKWQU.js → chunk-2LFOMUEA.js} +4 -4
- package/dist/{chunk-OF3L2SD6.js → chunk-32B7VCKU.js} +2 -2
- package/dist/{chunk-MSWYQLMQ.js → chunk-3B6S6RSI.js} +2 -2
- package/dist/{chunk-PJNTR2NV.js → chunk-3ENNPCIW.js} +7 -10
- package/dist/chunk-3ENNPCIW.js.map +1 -0
- package/dist/{chunk-7F4DBNSP.js → chunk-3O72ZD2E.js} +3 -3
- package/dist/{chunk-FNSMZQS4.js → chunk-3PMFMUFX.js} +2 -2
- package/dist/{chunk-WQDTCJ6W.js → chunk-45YHJ3GV.js} +11 -3
- package/dist/{chunk-WQDTCJ6W.js.map → chunk-45YHJ3GV.js.map} +1 -1
- package/dist/{chunk-NIVEDYJZ.js → chunk-4A34KWOU.js} +31 -49
- package/dist/chunk-4A34KWOU.js.map +1 -0
- package/dist/{chunk-ZJADGNYF.js → chunk-4AOERLTV.js} +1 -1
- package/dist/chunk-4AOERLTV.js.map +1 -0
- package/dist/{chunk-EDXAQ6JI.js → chunk-4N5Q23KV.js} +87 -34
- package/dist/chunk-4N5Q23KV.js.map +1 -0
- package/dist/{chunk-VV4NSB7P.js → chunk-4OQZNXQG.js} +15 -24
- package/dist/chunk-4OQZNXQG.js.map +1 -0
- package/dist/{chunk-FAXZQ5UF.js → chunk-4RAS6HN6.js} +2 -2
- package/dist/{chunk-C2OOEM57.js → chunk-4YL2LMXK.js} +92 -35
- package/dist/chunk-4YL2LMXK.js.map +1 -0
- package/dist/{chunk-EP7VPR7Y.js → chunk-5Q7AJ7DN.js} +11 -8
- package/dist/chunk-5Q7AJ7DN.js.map +1 -0
- package/dist/{chunk-VMCCGUQB.js → chunk-6JPGVL7X.js} +2 -2
- package/dist/{chunk-PRDRGL73.js → chunk-6KTVJ5ZZ.js} +17 -14
- package/dist/chunk-6KTVJ5ZZ.js.map +1 -0
- package/dist/{chunk-4MC5JRRX.js → chunk-6WO62AJW.js} +14 -15
- package/dist/chunk-6WO62AJW.js.map +1 -0
- package/dist/{chunk-WLYIROCJ.js → chunk-6YD5SYQS.js} +2 -2
- package/dist/{chunk-YAWK6AWF.js → chunk-7KAE7CQ2.js} +2 -2
- package/dist/{chunk-MWKDOHEF.js → chunk-7LNE2N2V.js} +17 -10
- package/dist/chunk-7LNE2N2V.js.map +1 -0
- package/dist/{chunk-5PR33AC4.js → chunk-7PJ3BKHS.js} +20 -17
- package/dist/chunk-7PJ3BKHS.js.map +1 -0
- package/dist/{chunk-JXIDGFKS.js → chunk-A4TOGAUW.js} +4 -2
- package/dist/chunk-A4TOGAUW.js.map +1 -0
- package/dist/{chunk-VCETL77O.js → chunk-AU3AUJIZ.js} +27 -7
- package/dist/chunk-AU3AUJIZ.js.map +1 -0
- package/dist/{chunk-NKH7GSIH.js → chunk-AUPSEJ7O.js} +4 -4
- package/dist/{chunk-CCZJJ4I2.js → chunk-B6IYATME.js} +4 -4
- package/dist/{chunk-WYZ5MYUA.js → chunk-BAHOV5I5.js} +44 -42
- package/dist/chunk-BAHOV5I5.js.map +1 -0
- package/dist/{chunk-G5APARUV.js → chunk-BEZDLIDG.js} +13 -15
- package/dist/chunk-BEZDLIDG.js.map +1 -0
- package/dist/{chunk-ERB6NDDW.js → chunk-CAGI4LLJ.js} +427 -72
- package/dist/chunk-CAGI4LLJ.js.map +1 -0
- package/dist/{chunk-4UVDI4XE.js → chunk-CLAHBPOI.js} +4 -4
- package/dist/{chunk-HNGSV2YC.js → chunk-CWM4GQD2.js} +39 -10
- package/dist/chunk-CWM4GQD2.js.map +1 -0
- package/dist/{chunk-HVQGCKY4.js → chunk-D3R7Q4QK.js} +2 -2
- package/dist/{chunk-I4F6PKUK.js → chunk-DIZ6HM7Q.js} +16 -17
- package/dist/chunk-DIZ6HM7Q.js.map +1 -0
- package/dist/{chunk-ZNACADFG.js → chunk-DVRZYAGT.js} +4 -4
- package/dist/chunk-DVRZYAGT.js.map +1 -0
- package/dist/{chunk-P7OG2ETF.js → chunk-DXKLLKME.js} +3 -3
- package/dist/{chunk-TDJPS3T2.js → chunk-E5SC6ENM.js} +24 -19
- package/dist/chunk-E5SC6ENM.js.map +1 -0
- package/dist/{chunk-26JMGSSC.js → chunk-EES37S2V.js} +4 -4
- package/dist/chunk-EES37S2V.js.map +1 -0
- package/dist/{chunk-JIUVJ4M7.js → chunk-EKEIEJL6.js} +2 -2
- package/dist/{chunk-GASWQ3XG.js → chunk-ESKIAXO2.js} +15 -16
- package/dist/chunk-ESKIAXO2.js.map +1 -0
- package/dist/{chunk-TOAIYQJR.js → chunk-FFSQFH6D.js} +7 -10
- package/dist/chunk-FFSQFH6D.js.map +1 -0
- package/dist/{chunk-DG27IUVI.js → chunk-FS7NTGCJ.js} +2 -2
- package/dist/{chunk-V5KYPBUR.js → chunk-FW7NGYLT.js} +11 -14
- package/dist/chunk-FW7NGYLT.js.map +1 -0
- package/dist/{chunk-52QYGZHH.js → chunk-GBBDFE6C.js} +2 -2
- package/dist/chunk-GBBDFE6C.js.map +1 -0
- package/dist/{chunk-HXGUIPQB.js → chunk-GQXFOAYZ.js} +3 -3
- package/dist/{chunk-BTVYJWSN.js → chunk-GTHVPVAR.js} +10 -10
- package/dist/{chunk-DMQCLZ4Z.js → chunk-GWO2IDAB.js} +2 -2
- package/dist/{chunk-6HFM7EIT.js → chunk-H3G4I3PN.js} +2 -2
- package/dist/chunk-HK67PX4J.js +27 -0
- package/dist/chunk-HK67PX4J.js.map +1 -0
- package/dist/{chunk-E7OBCBXS.js → chunk-HQSPF5IY.js} +22 -18
- package/dist/chunk-HQSPF5IY.js.map +1 -0
- package/dist/{chunk-VJFMXYKP.js → chunk-HR5R5JOM.js} +2 -2
- package/dist/{chunk-FDX7OWWI.js → chunk-HYYVT2KZ.js} +2 -2
- package/dist/{chunk-JRCYZEHU.js → chunk-I6QKB7MT.js} +2 -2
- package/dist/{chunk-MZ5ZFO2D.js → chunk-ICDHUUMQ.js} +84 -112
- package/dist/chunk-ICDHUUMQ.js.map +1 -0
- package/dist/{chunk-W5W6KHN2.js → chunk-IGNJOJEP.js} +1 -1
- package/dist/chunk-IGNJOJEP.js.map +1 -0
- package/dist/{chunk-KUDZVJKQ.js → chunk-IJ46VCWD.js} +2 -2
- package/dist/{chunk-4HDYQL3J.js → chunk-INMHEMXX.js} +2 -2
- package/dist/{chunk-66W5OOCX.js → chunk-JLYQQNY4.js} +52 -65
- package/dist/chunk-JLYQQNY4.js.map +1 -0
- package/dist/{chunk-UHXCLPGC.js → chunk-JNMTN5D5.js} +2 -2
- package/dist/chunk-JNMTN5D5.js.map +1 -0
- package/dist/{chunk-I4ZAO7F7.js → chunk-JWMBG5S3.js} +7 -11
- package/dist/chunk-JWMBG5S3.js.map +1 -0
- package/dist/chunk-KRVS7YWY.js +123 -0
- package/dist/chunk-KRVS7YWY.js.map +1 -0
- package/dist/{chunk-AR2JDFAE.js → chunk-KV6JM2IA.js} +2 -2
- package/dist/{chunk-PVU7LW5L.js → chunk-KX57HODD.js} +6 -6
- package/dist/{chunk-PY7CI6L5.js → chunk-LGFTOU27.js} +553 -275
- package/dist/chunk-LGFTOU27.js.map +1 -0
- package/dist/chunk-LN7P6MZB.js +190 -0
- package/dist/chunk-LN7P6MZB.js.map +1 -0
- package/dist/{chunk-UIBGXRDD.js → chunk-LX46B56Q.js} +25 -31
- package/dist/chunk-LX46B56Q.js.map +1 -0
- package/dist/{chunk-CEJWMBXO.js → chunk-LXECF2ZR.js} +2 -2
- package/dist/{chunk-7VHY5E3X.js → chunk-MSLPDFK2.js} +7 -7
- package/dist/{chunk-I6SDX7WX.js → chunk-MZTUTEHP.js} +16 -22
- package/dist/chunk-MZTUTEHP.js.map +1 -0
- package/dist/{chunk-VRA4Q7DA.js → chunk-NCCEDL2K.js} +55 -48
- package/dist/chunk-NCCEDL2K.js.map +1 -0
- package/dist/{chunk-HNHCQ556.js → chunk-NR2SUJ3H.js} +2 -2
- package/dist/{chunk-AHLJSVRL.js → chunk-NW4TY6VC.js} +5 -7
- package/dist/chunk-NW4TY6VC.js.map +1 -0
- package/dist/{chunk-RKKORO4M.js → chunk-O742QBZZ.js} +10 -10
- package/dist/chunk-O742QBZZ.js.map +1 -0
- package/dist/{chunk-VN45YLWM.js → chunk-OHOKBMTM.js} +343 -132
- package/dist/chunk-OHOKBMTM.js.map +1 -0
- package/dist/{chunk-W3TVWF6N.js → chunk-OIBEJN5H.js} +2 -2
- package/dist/{chunk-QD724WDJ.js → chunk-OMYCSTXL.js} +4 -4
- package/dist/{chunk-Z45YRGFO.js → chunk-ONVD6GBY.js} +2 -2
- package/dist/{chunk-TAGFGKHP.js → chunk-OTHHO3KI.js} +7 -10
- package/dist/chunk-OTHHO3KI.js.map +1 -0
- package/dist/{chunk-3737A6EA.js → chunk-P2MR5UNE.js} +75 -18
- package/dist/chunk-P2MR5UNE.js.map +1 -0
- package/dist/chunk-PENPHA45.js +66 -0
- package/dist/chunk-PENPHA45.js.map +1 -0
- package/dist/{chunk-3FSX6LDG.js → chunk-PPCOKVFA.js} +8 -3
- package/dist/{chunk-3FSX6LDG.js.map → chunk-PPCOKVFA.js.map} +1 -1
- package/dist/{chunk-VOQW5LAM.js → chunk-QSIEL6TL.js} +102 -71
- package/dist/chunk-QSIEL6TL.js.map +1 -0
- package/dist/chunk-RFO4UXKQ.js +201 -0
- package/dist/chunk-RFO4UXKQ.js.map +1 -0
- package/dist/{chunk-KCQX65FU.js → chunk-RKCRPPNB.js} +3 -3
- package/dist/{chunk-7TSYBD3E.js → chunk-RSXQNFGO.js} +2 -2
- package/dist/{chunk-SZ2K3MHL.js → chunk-S56VYR4Q.js} +8 -11
- package/dist/{chunk-SZ2K3MHL.js.map → chunk-S56VYR4Q.js.map} +1 -1
- package/dist/{chunk-7NXHMW6Y.js → chunk-SYS46BL7.js} +2 -2
- package/dist/{chunk-55LKVALY.js → chunk-T7IR4N2S.js} +1 -3
- package/dist/chunk-T7IR4N2S.js.map +1 -0
- package/dist/{chunk-A67356IR.js → chunk-T7JGWTES.js} +33 -8
- package/dist/chunk-T7JGWTES.js.map +1 -0
- package/dist/{chunk-WHJKIZS7.js → chunk-TDSN2O2V.js} +27 -149
- package/dist/chunk-TDSN2O2V.js.map +1 -0
- package/dist/{chunk-747LRSOO.js → chunk-TMBSPLUG.js} +2 -2
- package/dist/{chunk-LWSJG3LI.js → chunk-TQPASLY4.js} +7 -3
- package/dist/chunk-TQPASLY4.js.map +1 -0
- package/dist/{chunk-WKPJXWKR.js → chunk-TX5MKAHA.js} +3 -3
- package/dist/{chunk-HFQ6LGIO.js → chunk-U27Y4DJZ.js} +12 -10
- package/dist/{chunk-HFQ6LGIO.js.map → chunk-U27Y4DJZ.js.map} +1 -1
- package/dist/{chunk-E6427JU2.js → chunk-VVSOPRUE.js} +18 -2
- package/dist/chunk-VVSOPRUE.js.map +1 -0
- package/dist/{chunk-7G6VDWXB.js → chunk-WVE6YKMX.js} +3 -3
- package/dist/chunk-WVE6YKMX.js.map +1 -0
- package/dist/{chunk-GLKDWWNO.js → chunk-YALD3SST.js} +16 -14
- package/dist/chunk-YALD3SST.js.map +1 -0
- package/dist/{chunk-NJDQ4YSV.js → chunk-YKXZHUOW.js} +4 -4
- package/dist/{chunk-VW6ZZGCG.js → chunk-ZLHHE5XZ.js} +3 -3
- package/dist/{chunk-FUHKW252.js → chunk-ZZXLB6AS.js} +2 -2
- package/dist/classified/index.js +5 -5
- package/dist/{classified-marker-FTOX7Q5L.js → classified-marker-NA6HUV33.js} +3 -3
- package/dist/collection-facade-VBM35WAH.js +45 -0
- package/dist/{computed-6G5M3UPH.js → computed-GSTLWSY5.js} +3 -3
- package/dist/consent/index.js +10 -10
- package/dist/cover/index.js +10 -3
- package/dist/custody/index.js +11 -11
- package/dist/{dead-filter-ENRIOQIE.js → dead-filter-UALP5DJX.js} +2 -2
- package/dist/debug/index.js +1 -1
- package/dist/{delegation-SSEPLXXO.js → delegation-JLNXM7KH.js} +24 -23
- package/dist/delegation-JLNXM7KH.js.map +1 -0
- package/dist/derivations/index.js +12 -12
- package/dist/derive-YUO3TQYN.js +22 -0
- package/dist/directory/index.js +10 -10
- package/dist/{dispatch-RE74SH6L.js → dispatch-4ZHLSFZQ.js} +5 -5
- package/dist/{dispatch-BDVGYC6X.js → dispatch-77CB75KB.js} +18 -18
- package/dist/{enclave-52VUXNRL.js → enclave-O4NOROCJ.js} +27 -9
- package/dist/executor-CZDXBXKE.js +29 -0
- package/dist/executor-DVJAWN3B.js +9 -0
- package/dist/executor-VRLG4TQJ.js +9 -0
- package/dist/export-accessible-UXSMG7AB.js +23 -0
- package/dist/extract-partition-TVY7AMKH.js +38 -0
- package/dist/{fanout-sidecar-DTBIDOWF.js → fanout-sidecar-NLQ7QAYW.js} +18 -27
- package/dist/fanout-sidecar-NLQ7QAYW.js.map +1 -0
- package/dist/find-WSARMJBW.js +11 -0
- package/dist/forget/index.js +9 -9
- package/dist/guards/index.js +7 -7
- package/dist/history/index.js +23 -20
- package/dist/history/index.js.map +1 -1
- package/dist/i18n/index.js +14 -14
- package/dist/index.d.ts +33 -15
- package/dist/index.js +187 -191
- package/dist/index.js.map +1 -1
- package/dist/indexing/index.js +2 -2
- package/dist/introspection/index.js +11 -11
- package/dist/issue-3JNJNPT3.js +19 -0
- package/dist/kernel/constants.d.ts +18 -0
- package/dist/kernel/enclave/crypto.d.ts +24 -4
- package/dist/kernel/enclave/index.d.ts +9 -2
- package/dist/kernel/enclave/record-aad.d.ts +131 -0
- package/dist/kernel/enclave/record-envelope.d.ts +76 -0
- package/dist/kernel/enclave/record-keys/envelope-body.d.ts +34 -2
- package/dist/kernel/enclave/record-keys/lifecycle.d.ts +22 -5
- package/dist/kernel/enclave/record-keys/record-codec.d.ts +47 -14
- package/dist/kernel/enclave/record-keys/rekey-blob.d.ts +88 -0
- package/dist/kernel/enclave/record-keys/rekey.d.ts +68 -0
- package/dist/kernel/enclave/record-keys/tombstone.d.ts +3 -2
- package/dist/kernel/errors.d.ts +71 -12
- package/dist/kernel/merge-authority.d.ts +25 -0
- package/dist/kernel/noydb.d.ts +27 -4
- package/dist/kernel/query/builder.d.ts +15 -2
- package/dist/kernel/query/join.d.ts +27 -0
- package/dist/kernel/sync-policy.d.ts +0 -2
- package/dist/kernel/tier-visibility.d.ts +15 -0
- package/dist/kernel/types.d.ts +145 -12
- package/dist/kernel/vault.d.ts +22 -18
- package/dist/kernel/via/index.d.ts +11 -2
- package/dist/{ledger-4WJL66BW.js → ledger-MVPNG5OS.js} +11 -11
- package/dist/liberate-4LOJOLDT.js +24 -0
- package/dist/{link-set-N4ZPV6E6.js → link-set-3POMQR3I.js} +11 -11
- package/dist/{managed-secret-OTHS64IF.js → managed-secret-IARIJJ7Q.js} +11 -3
- package/dist/materialized-views/index.js +22 -21
- package/dist/migrate-cek-XM2ETTZW.js +19 -0
- package/dist/migrate-cek-XM2ETTZW.js.map +1 -0
- package/dist/money/index.js +12 -8
- package/dist/noydb-IRILUDED.js +84 -0
- package/dist/overlay-views/index.js +4 -4
- package/dist/periods/index.js +22 -12
- package/dist/pod/index.js +75 -86
- package/dist/pod-handle-MELERCKU.js +41 -0
- package/dist/pod-handle-MELERCKU.js.map +1 -0
- package/dist/policy/index.js +11 -4
- package/dist/port/to/index.d.ts +4 -4
- package/dist/port/to/locator.d.ts +54 -8
- package/dist/port/with/i18n-strategy.d.ts +4 -1
- package/dist/port/with/lookup-strategy.d.ts +4 -1
- package/dist/port/with/merge-authority.d.ts +52 -0
- package/dist/port/with/service-bus.d.ts +0 -4
- package/dist/port/with/strategies.d.ts +2 -0
- package/dist/port/with/team-strategy.d.ts +5 -1
- package/dist/portability/index.js +8 -8
- package/dist/{post-register-ZAG2CAIY.js → post-register-Z5T7FY45.js} +6 -6
- package/dist/query/index.js +3 -3
- package/dist/reduce/index.js +4 -4
- package/dist/register-UZ37QPDB.js +32 -0
- package/dist/registry-ETJNA7PO.js +9 -0
- package/dist/registry-F7U6KSLX.js +9 -0
- package/dist/registry-L4ELKX6C.js +18 -0
- package/dist/registry-SDT5LIGO.js +19 -0
- package/dist/request-withdrawal-PVFEYX57.js +31 -0
- package/dist/{reveal-CMOJY4VO.js → reveal-DQ2E3QAZ.js} +6 -6
- package/dist/revoke-YXY6SHUH.js +24 -0
- package/dist/satellites/index.js +1 -1
- package/dist/schema-update/index.js +2 -2
- package/dist/sealed-record/index.js +20 -13
- package/dist/sealed-record/index.js.map +1 -1
- package/dist/search/index.js +4 -4
- package/dist/{seed-UK4QRIUN.js → seed-DZ4ORU5N.js} +19 -22
- package/dist/seed-DZ4ORU5N.js.map +1 -0
- package/dist/sequence/index.js +9 -9
- package/dist/session/index.js +10 -10
- package/dist/shadow/index.js +2 -2
- package/dist/share-link/index.js +1 -1
- package/dist/signer-Q7XQBMPA.js +25 -0
- package/dist/snapshots/index.js +10 -10
- package/dist/snapshots/index.js.map +1 -1
- package/dist/{stale-ZWXSOWJI.js → stale-NI7SAXAZ.js} +10 -10
- package/dist/storage-3VNGSHXS.js +23 -0
- package/dist/{store-coordination-provider-PB6QZ57W.js → store-coordination-provider-TYKNR3OU.js} +18 -12
- package/dist/store-coordination-provider-TYKNR3OU.js.map +1 -0
- package/dist/sync/index.js +11 -11
- package/dist/team/index.js +15 -14
- package/dist/tiers/index.js +11 -10
- package/dist/to/index.js +17 -9
- package/dist/to/index.js.map +1 -1
- package/dist/transactions/index.js +4 -4
- package/dist/{ulid-PTAIMDG4.js → ulid-VQW6ERQN.js} +2 -2
- package/dist/util/index.js +1 -1
- package/dist/vault-head/index.js +115 -0
- package/dist/vault-head/index.js.map +1 -0
- package/dist/{verify-RO5RTZOJ.js → verify-6J2YLKSO.js} +5 -5
- package/dist/via/lookup/handle.d.ts +4 -1
- package/dist/via/money/exact.d.ts +44 -0
- package/dist/via/money/index.d.ts +2 -0
- package/dist/via/money/normalize.d.ts +20 -0
- package/dist/walk-WRA7RAPY.js +21 -0
- package/dist/with-audit/guards/immutable-guard.d.ts +14 -0
- package/dist/with-audit/periods/active.d.ts +28 -1
- package/dist/with-audit/periods/index.d.ts +4 -2
- package/dist/with-audit/periods/periods.d.ts +161 -6
- package/dist/with-audit/periods/strategy.d.ts +14 -5
- package/dist/with-audit/periods/vault-facade.d.ts +89 -10
- package/dist/with-audit/periods/window.d.ts +10 -0
- package/dist/with-audit/sealed-record/index.d.ts +13 -0
- package/dist/with-audit/tiers/index.d.ts +17 -2
- package/dist/with-cargo/adopt-partition.d.ts +1 -1
- package/dist/with-cargo/extract-partition.d.ts +1 -1
- package/dist/with-cargo/index.d.ts +2 -2
- package/dist/with-commit/history/history.d.ts +26 -0
- package/dist/with-commit/history/index.d.ts +2 -1
- package/dist/with-commit/history/ledger/store.d.ts +7 -1
- package/dist/with-commit/history/strategy.d.ts +11 -1
- package/dist/with-commit/numbering/index.d.ts +0 -5
- package/dist/with-commit/vault-head/active.d.ts +2 -0
- package/dist/with-commit/vault-head/head.d.ts +28 -0
- package/dist/with-commit/vault-head/index.d.ts +10 -0
- package/dist/with-commit/vault-head/strategy.d.ts +127 -0
- package/dist/with-commit/vault-head/verify.d.ts +90 -0
- package/dist/with-formula/materialized-views/types.d.ts +52 -0
- package/dist/with-party/directory/cover/storage.d.ts +0 -8
- package/dist/with-party/directory/storage.d.ts +0 -11
- package/dist/with-party/directory/visibility.d.ts +0 -21
- package/dist/with-party/policy/storage.d.ts +0 -10
- package/dist/with-party/team/index.d.ts +1 -1
- package/dist/with-party/team/keyring.d.ts +149 -3
- package/dist/with-party/team/noydb-facade.d.ts +5 -1
- package/dist/with-party/team/roster-tag.d.ts +101 -0
- package/dist/with-party/team/tiers.d.ts +2 -1
- package/dist/with-pod/format.d.ts +10 -12
- package/dist/with-pod/index.d.ts +10 -10
- package/dist/with-pod/open.d.ts +2 -2
- package/dist/with-pod/pod-handle.d.ts +19 -0
- package/dist/with-pod/pod-store.d.ts +0 -8
- package/dist/with-pod/{bundle.d.ts → pod.d.ts} +26 -19
- package/dist/with-pod/ulid.d.ts +1 -1
- package/dist/with-shape/blobs/blob-set.d.ts +2 -2
- package/dist/with-shape/introspection/index.d.ts +1 -0
- package/dist/with-sync/engine.d.ts +54 -5
- package/dist/with-sync/strategy.d.ts +3 -0
- package/dist/withdraw-accessible-4JTDFRFZ.js +28 -0
- package/package.json +13 -5
- package/dist/api-WVY3H3YH.js +0 -20
- package/dist/backup-YYBE5RPC.js.map +0 -1
- package/dist/bundle-handle-JEUWU2SJ.js +0 -36
- package/dist/bundle-handle-JEUWU2SJ.js.map +0 -1
- package/dist/chunk-26JMGSSC.js.map +0 -1
- package/dist/chunk-3737A6EA.js.map +0 -1
- package/dist/chunk-4MC5JRRX.js.map +0 -1
- package/dist/chunk-52QYGZHH.js.map +0 -1
- package/dist/chunk-55LKVALY.js.map +0 -1
- package/dist/chunk-5PR33AC4.js.map +0 -1
- package/dist/chunk-66W5OOCX.js.map +0 -1
- package/dist/chunk-7G6VDWXB.js.map +0 -1
- package/dist/chunk-A67356IR.js.map +0 -1
- package/dist/chunk-AFHQATY4.js +0 -47
- package/dist/chunk-AFHQATY4.js.map +0 -1
- package/dist/chunk-AHLJSVRL.js.map +0 -1
- package/dist/chunk-C2OOEM57.js.map +0 -1
- package/dist/chunk-DIMKRG2E.js +0 -131
- package/dist/chunk-DIMKRG2E.js.map +0 -1
- package/dist/chunk-E6427JU2.js.map +0 -1
- package/dist/chunk-E7OBCBXS.js.map +0 -1
- package/dist/chunk-EDXAQ6JI.js.map +0 -1
- package/dist/chunk-EP7VPR7Y.js.map +0 -1
- package/dist/chunk-ERB6NDDW.js.map +0 -1
- package/dist/chunk-G5APARUV.js.map +0 -1
- package/dist/chunk-GASWQ3XG.js.map +0 -1
- package/dist/chunk-GLKDWWNO.js.map +0 -1
- package/dist/chunk-HNGSV2YC.js.map +0 -1
- package/dist/chunk-I4F6PKUK.js.map +0 -1
- package/dist/chunk-I4ZAO7F7.js.map +0 -1
- package/dist/chunk-I6SDX7WX.js.map +0 -1
- package/dist/chunk-JXIDGFKS.js.map +0 -1
- package/dist/chunk-LWSJG3LI.js.map +0 -1
- package/dist/chunk-MWKDOHEF.js.map +0 -1
- package/dist/chunk-MZ5ZFO2D.js.map +0 -1
- package/dist/chunk-NIVEDYJZ.js.map +0 -1
- package/dist/chunk-NWCGDAV6.js +0 -45
- package/dist/chunk-NWCGDAV6.js.map +0 -1
- package/dist/chunk-PJNTR2NV.js.map +0 -1
- package/dist/chunk-PRDRGL73.js.map +0 -1
- package/dist/chunk-PY7CI6L5.js.map +0 -1
- package/dist/chunk-RKKORO4M.js.map +0 -1
- package/dist/chunk-TAGFGKHP.js.map +0 -1
- package/dist/chunk-TDJPS3T2.js.map +0 -1
- package/dist/chunk-TOAIYQJR.js.map +0 -1
- package/dist/chunk-UHXCLPGC.js.map +0 -1
- package/dist/chunk-UIBGXRDD.js.map +0 -1
- package/dist/chunk-V5KYPBUR.js.map +0 -1
- package/dist/chunk-VCETL77O.js.map +0 -1
- package/dist/chunk-VN45YLWM.js.map +0 -1
- package/dist/chunk-VOQW5LAM.js.map +0 -1
- package/dist/chunk-VRA4Q7DA.js.map +0 -1
- package/dist/chunk-VV4NSB7P.js.map +0 -1
- package/dist/chunk-W5W6KHN2.js.map +0 -1
- package/dist/chunk-WHJKIZS7.js.map +0 -1
- package/dist/chunk-WYZ5MYUA.js.map +0 -1
- package/dist/chunk-ZJADGNYF.js.map +0 -1
- package/dist/chunk-ZNACADFG.js.map +0 -1
- package/dist/collection-facade-QN5ULWYC.js +0 -45
- package/dist/delegation-SSEPLXXO.js.map +0 -1
- package/dist/derive-6V3PIZF7.js +0 -22
- package/dist/executor-CYJQLKKI.js +0 -9
- package/dist/executor-FHHLXO4Y.js +0 -28
- package/dist/executor-S4QIKEHW.js +0 -9
- package/dist/export-accessible-PE5AYKZR.js +0 -23
- package/dist/extract-partition-X2L26O6A.js +0 -38
- package/dist/fanout-sidecar-DTBIDOWF.js.map +0 -1
- package/dist/find-RBBYKXI7.js +0 -11
- package/dist/issue-RNU55YOF.js +0 -19
- package/dist/liberate-PX4CAT5V.js +0 -24
- package/dist/noydb-YPSEGK32.js +0 -83
- package/dist/register-TMD6YRCX.js +0 -32
- package/dist/registry-CZVINVQH.js +0 -9
- package/dist/registry-FVLDWQKT.js +0 -18
- package/dist/registry-IKUR2MXD.js +0 -9
- package/dist/registry-JET4HBLY.js +0 -19
- package/dist/request-withdrawal-RH55LNZL.js +0 -31
- package/dist/revoke-R5TBYVA6.js +0 -24
- package/dist/seed-UK4QRIUN.js.map +0 -1
- package/dist/signer-AGALOXOO.js +0 -25
- package/dist/storage-N7LB275C.js +0 -23
- package/dist/store-coordination-provider-PB6QZ57W.js.map +0 -1
- package/dist/walk-OCUHCYJ6.js +0 -21
- package/dist/with-pod/bundle-handle.d.ts +0 -9
- package/dist/withdraw-accessible-QQNWM5BO.js +0 -28
- /package/dist/{api-WVY3H3YH.js.map → api-EYNT6KGS.js.map} +0 -0
- /package/dist/{chunk-35EBKWQU.js.map → chunk-2LFOMUEA.js.map} +0 -0
- /package/dist/{chunk-OF3L2SD6.js.map → chunk-32B7VCKU.js.map} +0 -0
- /package/dist/{chunk-MSWYQLMQ.js.map → chunk-3B6S6RSI.js.map} +0 -0
- /package/dist/{chunk-7F4DBNSP.js.map → chunk-3O72ZD2E.js.map} +0 -0
- /package/dist/{chunk-FNSMZQS4.js.map → chunk-3PMFMUFX.js.map} +0 -0
- /package/dist/{chunk-FAXZQ5UF.js.map → chunk-4RAS6HN6.js.map} +0 -0
- /package/dist/{chunk-VMCCGUQB.js.map → chunk-6JPGVL7X.js.map} +0 -0
- /package/dist/{chunk-WLYIROCJ.js.map → chunk-6YD5SYQS.js.map} +0 -0
- /package/dist/{chunk-YAWK6AWF.js.map → chunk-7KAE7CQ2.js.map} +0 -0
- /package/dist/{chunk-NKH7GSIH.js.map → chunk-AUPSEJ7O.js.map} +0 -0
- /package/dist/{chunk-CCZJJ4I2.js.map → chunk-B6IYATME.js.map} +0 -0
- /package/dist/{chunk-4UVDI4XE.js.map → chunk-CLAHBPOI.js.map} +0 -0
- /package/dist/{chunk-HVQGCKY4.js.map → chunk-D3R7Q4QK.js.map} +0 -0
- /package/dist/{chunk-P7OG2ETF.js.map → chunk-DXKLLKME.js.map} +0 -0
- /package/dist/{chunk-JIUVJ4M7.js.map → chunk-EKEIEJL6.js.map} +0 -0
- /package/dist/{chunk-DG27IUVI.js.map → chunk-FS7NTGCJ.js.map} +0 -0
- /package/dist/{chunk-HXGUIPQB.js.map → chunk-GQXFOAYZ.js.map} +0 -0
- /package/dist/{chunk-BTVYJWSN.js.map → chunk-GTHVPVAR.js.map} +0 -0
- /package/dist/{chunk-DMQCLZ4Z.js.map → chunk-GWO2IDAB.js.map} +0 -0
- /package/dist/{chunk-6HFM7EIT.js.map → chunk-H3G4I3PN.js.map} +0 -0
- /package/dist/{chunk-VJFMXYKP.js.map → chunk-HR5R5JOM.js.map} +0 -0
- /package/dist/{chunk-FDX7OWWI.js.map → chunk-HYYVT2KZ.js.map} +0 -0
- /package/dist/{chunk-JRCYZEHU.js.map → chunk-I6QKB7MT.js.map} +0 -0
- /package/dist/{chunk-KUDZVJKQ.js.map → chunk-IJ46VCWD.js.map} +0 -0
- /package/dist/{chunk-4HDYQL3J.js.map → chunk-INMHEMXX.js.map} +0 -0
- /package/dist/{chunk-AR2JDFAE.js.map → chunk-KV6JM2IA.js.map} +0 -0
- /package/dist/{chunk-PVU7LW5L.js.map → chunk-KX57HODD.js.map} +0 -0
- /package/dist/{chunk-CEJWMBXO.js.map → chunk-LXECF2ZR.js.map} +0 -0
- /package/dist/{chunk-7VHY5E3X.js.map → chunk-MSLPDFK2.js.map} +0 -0
- /package/dist/{chunk-HNHCQ556.js.map → chunk-NR2SUJ3H.js.map} +0 -0
- /package/dist/{chunk-W3TVWF6N.js.map → chunk-OIBEJN5H.js.map} +0 -0
- /package/dist/{chunk-QD724WDJ.js.map → chunk-OMYCSTXL.js.map} +0 -0
- /package/dist/{chunk-Z45YRGFO.js.map → chunk-ONVD6GBY.js.map} +0 -0
- /package/dist/{chunk-KCQX65FU.js.map → chunk-RKCRPPNB.js.map} +0 -0
- /package/dist/{chunk-7TSYBD3E.js.map → chunk-RSXQNFGO.js.map} +0 -0
- /package/dist/{chunk-7NXHMW6Y.js.map → chunk-SYS46BL7.js.map} +0 -0
- /package/dist/{chunk-747LRSOO.js.map → chunk-TMBSPLUG.js.map} +0 -0
- /package/dist/{chunk-WKPJXWKR.js.map → chunk-TX5MKAHA.js.map} +0 -0
- /package/dist/{chunk-NJDQ4YSV.js.map → chunk-YKXZHUOW.js.map} +0 -0
- /package/dist/{chunk-VW6ZZGCG.js.map → chunk-ZLHHE5XZ.js.map} +0 -0
- /package/dist/{chunk-FUHKW252.js.map → chunk-ZZXLB6AS.js.map} +0 -0
- /package/dist/{classified-marker-FTOX7Q5L.js.map → classified-marker-NA6HUV33.js.map} +0 -0
- /package/dist/{collection-facade-QN5ULWYC.js.map → collection-facade-VBM35WAH.js.map} +0 -0
- /package/dist/{computed-6G5M3UPH.js.map → computed-GSTLWSY5.js.map} +0 -0
- /package/dist/{dead-filter-ENRIOQIE.js.map → dead-filter-UALP5DJX.js.map} +0 -0
- /package/dist/{derive-6V3PIZF7.js.map → derive-YUO3TQYN.js.map} +0 -0
- /package/dist/{dispatch-RE74SH6L.js.map → dispatch-4ZHLSFZQ.js.map} +0 -0
- /package/dist/{dispatch-BDVGYC6X.js.map → dispatch-77CB75KB.js.map} +0 -0
- /package/dist/{enclave-52VUXNRL.js.map → enclave-O4NOROCJ.js.map} +0 -0
- /package/dist/{executor-CYJQLKKI.js.map → executor-CZDXBXKE.js.map} +0 -0
- /package/dist/{executor-FHHLXO4Y.js.map → executor-DVJAWN3B.js.map} +0 -0
- /package/dist/{executor-S4QIKEHW.js.map → executor-VRLG4TQJ.js.map} +0 -0
- /package/dist/{export-accessible-PE5AYKZR.js.map → export-accessible-UXSMG7AB.js.map} +0 -0
- /package/dist/{extract-partition-X2L26O6A.js.map → extract-partition-TVY7AMKH.js.map} +0 -0
- /package/dist/{find-RBBYKXI7.js.map → find-WSARMJBW.js.map} +0 -0
- /package/dist/{issue-RNU55YOF.js.map → issue-3JNJNPT3.js.map} +0 -0
- /package/dist/{ledger-4WJL66BW.js.map → ledger-MVPNG5OS.js.map} +0 -0
- /package/dist/{liberate-PX4CAT5V.js.map → liberate-4LOJOLDT.js.map} +0 -0
- /package/dist/{link-set-N4ZPV6E6.js.map → link-set-3POMQR3I.js.map} +0 -0
- /package/dist/{managed-secret-OTHS64IF.js.map → managed-secret-IARIJJ7Q.js.map} +0 -0
- /package/dist/{noydb-YPSEGK32.js.map → noydb-IRILUDED.js.map} +0 -0
- /package/dist/{post-register-ZAG2CAIY.js.map → post-register-Z5T7FY45.js.map} +0 -0
- /package/dist/{register-TMD6YRCX.js.map → register-UZ37QPDB.js.map} +0 -0
- /package/dist/{registry-CZVINVQH.js.map → registry-ETJNA7PO.js.map} +0 -0
- /package/dist/{registry-FVLDWQKT.js.map → registry-F7U6KSLX.js.map} +0 -0
- /package/dist/{registry-IKUR2MXD.js.map → registry-L4ELKX6C.js.map} +0 -0
- /package/dist/{registry-JET4HBLY.js.map → registry-SDT5LIGO.js.map} +0 -0
- /package/dist/{request-withdrawal-RH55LNZL.js.map → request-withdrawal-PVFEYX57.js.map} +0 -0
- /package/dist/{reveal-CMOJY4VO.js.map → reveal-DQ2E3QAZ.js.map} +0 -0
- /package/dist/{revoke-R5TBYVA6.js.map → revoke-YXY6SHUH.js.map} +0 -0
- /package/dist/{signer-AGALOXOO.js.map → signer-Q7XQBMPA.js.map} +0 -0
- /package/dist/{stale-ZWXSOWJI.js.map → stale-NI7SAXAZ.js.map} +0 -0
- /package/dist/{storage-N7LB275C.js.map → storage-3VNGSHXS.js.map} +0 -0
- /package/dist/{ulid-PTAIMDG4.js.map → ulid-VQW6ERQN.js.map} +0 -0
- /package/dist/{verify-RO5RTZOJ.js.map → verify-6J2YLKSO.js.map} +0 -0
- /package/dist/{walk-OCUHCYJ6.js.map → walk-WRA7RAPY.js.map} +0 -0
- /package/dist/{withdraw-accessible-QQNWM5BO.js.map → withdraw-accessible-4JTDFRFZ.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/with-party/team/roster-tag.ts","../src/kernel/validation.ts","../src/with-party/team/echo-secret.ts","../src/with-party/team/reserved-secret-collections.ts","../src/with-party/team/keyring.ts"],"sourcesContent":["/**\n * #1096 — the authenticated half of a `_keyring` file's AUTHORITY.\n *\n * A `_keyring` file is stored plaintext (`_iv: ''`) so admins can edit a\n * member's authority without holding that member's credential. That means\n * `role`/`permissions` were authenticated by NOTHING — a hostile store could\n * promote a viewer to admin by editing one word (proven in\n * `__tests__/keyring-replay-escalation.test.ts`).\n *\n * The fix is a vault-wide ROSTER KEY, carried as a reserved DEK-map entry\n * (`deks['_roster']`, see `ROSTER_KEY_ID`) so it reaches every member through\n * the channels a DEK already travels — grant's `_`-prefix propagation,\n * `persistKeyring`, the wrapped-DEKs recovery blob, `peer-recover`, pod\n * recipient slots — and a `roster_tag`: AES-GCM of the canonical authority\n * fields under that key. Every roster EDITOR holds the key (constraint:\n * admins edit authority they don't hold the target's credential for) — which\n * is what sets the bound below.\n *\n * `user_id` is inside the canonical string so a genuine tag cannot be\n * transplanted onto another member's file.\n *\n * ## What \"authority half\" does NOT cover\n *\n * The canonical string is exactly {@link RosterAuthorityFields} — the fields a\n * privilege decision reads. Other plaintext fields are deliberately excluded\n * and REMAIN FORGEABLE by the store: `display_name` (cosmetic), `policy`\n * (round-tripped, never enforced at v1.0), `echo` and `authenticators` (each\n * authenticated by its own wrapped key material — a forged one fails to\n * unlock rather than granting anything), plus `created_at` / `salt` /\n * `_noydb_keyring`. Adding a field to the tag means adding it to\n * `rosterCanonical`; nothing else here is a claim about it.\n *\n * ## The bound\n *\n * This stops the STORE, which holds no keys. It deliberately does NOT stop a\n * malicious MEMBER: every roster editor must hold the roster key, so anyone\n * who legitimately holds it can forge any authority field for any member.\n * That bound must be stated in `SECURITY.md` (tracked as part of the #1096\n * PR) — it is not written there yet.\n */\nimport type { KeyringFile } from '../../kernel/types.js'\nimport type { EnclaveKey } from '../../kernel/enclave/index.js'\nimport { encrypt, decrypt } from '../../kernel/enclave/index.js'\nimport { ROSTER_KEY_ID } from '../../kernel/constants.js'\nimport { KeyringTamperedError } from '../../kernel/errors.js'\n\nexport interface RosterTag { readonly iv: string; readonly data: string }\n\nexport type RosterAuthorityFields = Pick<KeyringFile,\n 'user_id' | 'role' | 'permissions' | 'granted_by' | 'expires_at' | 'export_capability' | 'import_capability'>\n\n/** Stable stringify — sorts object keys recursively so key order never splits the tag. */\nfunction stable(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(stable).join(',')}]`\n if (value !== null && typeof value === 'object') {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([k, v]) => `${JSON.stringify(k)}:${stable(v)}`)\n return `{${entries.join(',')}}`\n }\n return JSON.stringify(value) ?? 'null'\n}\n\nexport function rosterCanonical(file: RosterAuthorityFields): string {\n return stable({\n user_id: file.user_id,\n role: file.role,\n permissions: file.permissions,\n granted_by: file.granted_by,\n expires_at: file.expires_at ?? null,\n export_capability: file.export_capability ?? null,\n import_capability: file.import_capability ?? null,\n })\n}\n\nexport async function mintRosterTag(file: RosterAuthorityFields, rosterKey: EnclaveKey): Promise<RosterTag> {\n return encrypt(rosterCanonical(file), rosterKey)\n}\n\n/**\n * false on decrypt failure OR canonical mismatch — never throws.\n *\n * `null` is accepted alongside `undefined` because the tag arrives from\n * JSON a store controls: `\"roster_tag\": null` is a shape the type system\n * says is impossible and the wire permits.\n */\nexport async function verifyRosterTag(\n file: RosterAuthorityFields,\n tag: RosterTag | undefined | null,\n rosterKey: EnclaveKey,\n): Promise<boolean> {\n if (tag == null) return false\n try {\n return (await decrypt(tag.iv, tag.data, rosterKey)) === rosterCanonical(file)\n } catch {\n return false\n }\n}\n\n/**\n * #1096 — THE CHOKEPOINT. Verify a keyring file's plaintext AUTHORITY half\n * against the roster key carried in its own, already-unwrapped, DEK set.\n * Throws {@link KeyringTamperedError}; returns silently when the roster is\n * authentic.\n *\n * **Every path that builds an `UnlockedKeyring` from a `KeyringFile` must call\n * this — not just `loadKeyring`.** A tier-2 unlock that reconstructs\n * `role`/`permissions` from the plaintext header without it accepts exactly\n * the forgery tier-1 refuses, and the vault is only as strong as its weakest\n * unlock path. That is not hypothetical: the wrap-DEKs password path shipped\n * in this state until it was caught in review.\n *\n * Deliberately says nothing about the canary. The canary proves the KEK, and\n * tier-2 paths have no KEK to prove — the roster key they hold comes from the\n * slot's own wrapped-DEK blob, which is authenticated by its own AES-GCM tag.\n * Callers that DO hold a KEK check the canary separately, before this.\n *\n * @param deks the caller's UNWRAPPED DEK set — a roster key here is proof of\n * possession, so this must never be handed a map built from unverified input.\n */\nexport async function assertRosterAuthenticated(\n file: KeyringFile,\n deks: ReadonlyMap<string, EnclaveKey>,\n userId: string,\n): Promise<void> {\n const rosterKey = deks.get(ROSTER_KEY_ID)\n if (rosterKey === undefined) {\n // Absence is an alarm, not a skip: deleting a wrapped DEK needs no key, so\n // \"verify only when a key is present\" would let a store opt out entirely.\n throw new KeyringTamperedError({ userId, reason: 'roster-key-missing' })\n }\n await assertRosterTagValid(file, rosterKey, userId)\n}\n\n/**\n * #1096 — VERIFY BEFORE YOU TRUST, and especially before you RESTAMP.\n *\n * The sibling of {@link assertRosterAuthenticated} for the other half of the\n * problem. That one guards paths that *unlock* a keyring; this one guards paths\n * that **read another member's file** — because the roster key is vault-wide, a\n * caller holding it can verify any member's tag, not just their own.\n *\n * Every read-modify-write on a member's roster must call this **before** the\n * modify. A flow that reads a forged file, edits one field and restamps does\n * not merely tolerate the forgery — it **launders** it, converting a file\n * `loadKeyring` refuses into one it accepts, under a genuine tag. `revoke`\n * calls into such a flow unconditionally, so without this a single forged\n * member plus any later revocation anywhere in the vault is a complete bypass.\n *\n * Fail-closed, deliberately: a forged member's file aborts the operation rather\n * than being skipped. Skipping would complete the revoke while leaving the\n * forgery in place, and an untrusted store can already refuse writes — so the\n * availability it costs was never guaranteed, while the integrity it buys is\n * the point of the mechanism.\n */\nexport async function assertRosterTagValid(\n file: KeyringFile,\n rosterKey: EnclaveKey,\n userId: string,\n): Promise<void> {\n if (!(await verifyRosterTag(file, file.roster_tag, rosterKey))) {\n throw new KeyringTamperedError({\n userId,\n reason: file.roster_tag == null ? 'roster-tag-missing' : 'roster-tag-mismatch',\n })\n }\n}\n","/**\n * Secret validation — phrase format (per the three-tier session-tiers\n * design, locked 2026-05-04).\n *\n * Secrets are **phrases**: multiple simple words, easy to remember,\n * structurally constrained so a weak choice cannot silently collapse the\n * security floor. The format is intentionally narrow: lowercase letters\n * and single spaces only, no punctuation, no symbols, no digits.\n *\n * - Default minimum: 6 words (~77 bits with the 7,776-word EFF list).\n * - Strict minimum: 8 words (~103 bits).\n * - Per-word minimum: 3 characters (excludes \"a\", \"is\", \"of\").\n * - Adjacent repeats rejected (\"the the\").\n *\n * The hub runs validation default-on at every secret ingress\n * (`createOwnerKeyring`, `grant`, `rotateSecret`); test fixtures and\n * CLI scripts override via `{ allowWeakSecret: true }`.\n *\n * @module\n */\nimport { NoydbError, ValidationError } from './errors.js'\n\n/** All reasons a phrase can be rejected. */\nexport type WeakSecretReason =\n | 'empty'\n | 'invalid-chars'\n | 'leading-or-trailing-space'\n | 'double-space'\n | 'too-few-words'\n | 'word-too-short'\n | 'repeated-adjacent'\n\n/** Per-vault knobs. Aligns with `VaultPolicy.secret`. */\nexport interface SecretPolicy {\n /** Minimum number of words. Default 6. Strict policy uses 8. */\n readonly minWords?: number\n /** Minimum characters per word. Default 3. */\n readonly minWordLength?: number\n /** Reject adjacent identical words (\"the the\"). Default true. */\n readonly rejectRepeatedAdjacent?: boolean\n /**\n * Override the default character-class rule (`/^[a-z]+( [a-z]+)*$/`).\n *\n * The hub's strict default is lowercase-letters-and-single-spaces\n * because that's what the EFF wordlist generator emits and what\n * most attacker password lists are keyed on. Use this knob to allow\n * digits, uppercase, hyphens, or non-Latin scripts when the\n * consumer's audience needs them — e.g.:\n *\n * ```ts\n * // Thai + English mix with digits permitted\n * pattern: /^[\\p{L}0-9 ]+( [\\p{L}0-9 ]+)*$/u\n *\n * // Allow uppercase + hyphens (secret-with-hyphens style)\n * pattern: /^[A-Za-z]+([- ][A-Za-z]+)*$/\n * ```\n *\n * The OTHER structural rules still apply (min-words split by space,\n * min-word-length, repeated-adjacent, leading/trailing whitespace,\n * double-space). For non-space-delimited word semantics, use\n * {@link customValidator} instead.\n *\n */\n readonly pattern?: RegExp\n /**\n * Replace ALL validation entirely with a custom function. When set,\n * none of the other SecretPolicy fields apply — the consumer\n * owns every rule (word splitting, character classes, entropy\n * thresholds, allowlist/denylist). Use sparingly; this is the\n * escape hatch for domain-specific phrase formats:\n *\n * - Localized wordlists with non-space word boundaries\n * - BIP-39 seed phrases (24 words, fixed wordlist, etc.)\n * - Organization-specific HR password policies\n *\n * The returned `SecretValidationResult` is what\n * {@link assertStrongSecret} dispatches on — `ok: true` accepts;\n * `ok: false` throws `WeakSecretError` with the supplied reason.\n *\n */\n readonly customValidator?: (phrase: string) => SecretValidationResult\n}\n\n/** Result of a check. Discriminated union — compile-time exhaustive. */\nexport type SecretValidationResult =\n | { readonly ok: true; readonly words: number }\n | {\n readonly ok: false\n readonly reason: WeakSecretReason\n readonly minimum?: number\n readonly got?: number\n }\n\n/**\n * Thrown by `assertStrongSecret()` and by every hub ingress\n * point (`createOwnerKeyring`, `grant`, `rotateSecret`) when a\n * supplied phrase fails the structural rules above.\n */\nexport class WeakSecretError extends NoydbError {\n readonly reason: WeakSecretReason\n readonly suggestion: string\n constructor(reason: WeakSecretReason, suggestion: string) {\n super('WEAK_SECRET', `Weak secret (${reason}). ${suggestion}`)\n this.name = 'WeakSecretError'\n this.reason = reason\n this.suggestion = suggestion\n }\n}\n\nconst DEFAULT_MIN_WORDS = 6\nconst DEFAULT_MIN_WORD_LENGTH = 3\n\nconst SUGGESTIONS: Record<WeakSecretReason, string> = {\n empty: 'Provide a phrase of at least 6 lowercase words separated by single spaces.',\n 'invalid-chars':\n 'Use only lowercase letters [a-z] and single spaces. No punctuation, symbols, digits, or uppercase.',\n 'leading-or-trailing-space': 'Trim leading and trailing spaces.',\n 'double-space': 'Use exactly one space between words.',\n 'too-few-words':\n 'Use at least 6 words by default (8 under strict policy). Example: \"correct horse battery staple printer toaster\".',\n 'word-too-short': 'Each word must be at least 3 characters. Drop short fillers like \"a\", \"is\", \"of\".',\n 'repeated-adjacent': 'Avoid repeating the same word twice in a row.',\n}\n\n/**\n * Inspect a phrase against the format rules and return a structured\n * verdict. Never throws — callers either branch on `ok` or pass the\n * result to {@link assertStrongSecret} for the throwing flavour.\n */\nexport function validateSecret(\n s: string,\n opts?: SecretPolicy,\n): SecretValidationResult {\n // Escape hatch: customValidator owns the entire decision. None of\n // the structural rules below run when this is set — the consumer is\n // responsible for the full validation contract.\n if (opts?.customValidator) {\n return opts.customValidator(s)\n }\n\n const minWords = opts?.minWords ?? DEFAULT_MIN_WORDS\n const minWordLength = opts?.minWordLength ?? DEFAULT_MIN_WORD_LENGTH\n const rejectRepeated = opts?.rejectRepeatedAdjacent ?? true\n\n if (s.length === 0) {\n return { ok: false, reason: 'empty' }\n }\n\n if (s !== s.trim()) {\n return { ok: false, reason: 'leading-or-trailing-space' }\n }\n\n if (s.includes(' ')) {\n return { ok: false, reason: 'double-space' }\n }\n\n // The default character class is lowercase-letters-and-spaces;\n // consumers can override via SecretPolicy.pattern (e.g. to\n // allow digits, uppercase, or non-Latin scripts). Word splitting\n // below remains space-based — for non-space word semantics the\n // consumer should use customValidator instead.\n const charPattern = opts?.pattern ?? /^[a-z]+( [a-z]+)*$/\n if (!charPattern.test(s)) {\n return { ok: false, reason: 'invalid-chars' }\n }\n\n const words = s.split(' ')\n\n if (words.length < minWords) {\n return { ok: false, reason: 'too-few-words', minimum: minWords, got: words.length }\n }\n\n for (const w of words) {\n if (w.length < minWordLength) {\n return { ok: false, reason: 'word-too-short', minimum: minWordLength, got: w.length }\n }\n }\n\n if (rejectRepeated) {\n for (let i = 1; i < words.length; i++) {\n if (words[i] === words[i - 1]) {\n return { ok: false, reason: 'repeated-adjacent' }\n }\n }\n }\n\n return { ok: true, words: words.length }\n}\n\n/**\n * Throw {@link WeakSecretError} when the phrase fails. Used by\n * `createOwnerKeyring`, `grant`, and `rotateSecret` at ingress.\n *\n * Pass `{ allowWeakSecret: true }` to bypass — intended for test\n * fixtures, CLI scripts, and dev environments. The override never\n * loosens the cryptographic key derivation; it only relaxes the\n * structural-strength gate.\n */\nexport function assertStrongSecret(\n s: string,\n opts?: SecretPolicy & { allowWeakSecret?: boolean },\n): void {\n if (opts?.allowWeakSecret) return\n const result = validateSecret(s, opts)\n if (result.ok) return\n throw new WeakSecretError(result.reason, SUGGESTIONS[result.reason])\n}\n\n/**\n * Estimate the entropy of a phrase, given the EFF 7,776-word list as\n * the assumed wordlist. ~12.9 bits per word.\n *\n * Returns 0 for any input that fails the phrase format — character-class\n * estimates aren't comparable to phrase entropy, and surfacing 0 makes\n * weak inputs visible in any UI that displays an entropy meter.\n */\nexport function estimateEntropy(secret: string): number {\n const result = validateSecret(secret)\n if (!result.ok) return 0\n return Math.round(result.words * Math.log2(7776))\n}\n\n/**\n * Internal compatibility shim. Older code paths used the throwing\n * `validateSecret(s)` directly; some still do via re-exports. Routes\n * to the new `assertStrongSecret` so the contract holds for both\n * shapes during the transition. New code should call\n * {@link assertStrongSecret} directly.\n *\n * @internal\n */\nexport function legacyAssertSecret(s: string): void {\n try {\n assertStrongSecret(s)\n } catch (err) {\n if (err instanceof WeakSecretError) {\n throw new ValidationError(err.message)\n }\n throw err\n }\n}\n\n/** Dedicated floors for the echo mode's three parts (spec resolved Q1/Q5). */\nexport interface EchoSecretPolicy {\n /** Floor for the typed prompt — the brute-forceable-in-isolation part. */\n readonly prompt?: SecretPolicy\n /** Policy for the combined parts (defaults to the standard whole-secret rules). */\n readonly combined?: SecretPolicy\n}\n\nexport const DEFAULT_ECHO_PROMPT_MIN_WORDS = 3\n/**\n * Default per-word character floor for echo-mode validation (prompt AND\n * combined checks). Relaxed to 1 from the standard 3-char floor\n * ({@link DEFAULT_MIN_WORD_LENGTH}) — echo secrets are natural-language\n * sentences (spec #940's canonical example is Italian), and Romance\n * languages are full of 2-letter function words (\"mi\", \"da\", \"al\") that\n * the standard floor would otherwise reject even though the combined\n * secret is plenty strong. Word-COUNT floors (prompt 3, combined 6) are\n * unchanged — this only relaxes per-word length.\n */\nexport const DEFAULT_ECHO_MIN_WORD_LENGTH = 1\n\n/** Which of `validateEchoSecret`'s three internal checks produced a result. */\ntype EchoSecretCheck = 'empty' | 'prompt' | 'combined'\n\n/**\n * `validateEchoSecret` plus which check produced the result — lets\n * `assertStrongEchoSecret` pick the prompt-specific suggestion without\n * re-running `validateSecret` on the failure path. Internal: NOT\n * package-exported (the public `validateEchoSecret`/`SecretValidationResult`\n * contract stays exactly as before).\n */\nfunction validateEchoSecretDetailed(\n parts: { readonly prompt: string; readonly echo: string; readonly key: string },\n opts?: EchoSecretPolicy,\n): { readonly result: SecretValidationResult; readonly failedCheck: EchoSecretCheck } {\n // Trimmed: a whitespace-only part carries no secret material, so it is\n // 'empty' rather than a confusing spacing complaint.\n for (const part of [parts.prompt, parts.echo, parts.key]) {\n if (part.trim().length === 0) return { result: { ok: false, reason: 'empty' }, failedCheck: 'empty' }\n }\n // Field-by-field construction (not a spread of `opts?.prompt`) so an\n // explicit `{ prompt: { minWords: undefined } }` override falls back to\n // the ECHO prompt default (3) rather than reintroducing `undefined` as\n // an own property that would then hit `validateSecret`'s STANDARD\n // default (6) — a spread copies an explicit-`undefined` key verbatim and\n // clobbers the default set here. Each optional field is included only\n // when actually set (`exactOptionalPropertyTypes`).\n const promptPolicy: SecretPolicy = {\n minWords: opts?.prompt?.minWords ?? DEFAULT_ECHO_PROMPT_MIN_WORDS,\n minWordLength: opts?.prompt?.minWordLength ?? DEFAULT_ECHO_MIN_WORD_LENGTH,\n ...(opts?.prompt?.rejectRepeatedAdjacent !== undefined\n && { rejectRepeatedAdjacent: opts.prompt.rejectRepeatedAdjacent }),\n ...(opts?.prompt?.pattern !== undefined && { pattern: opts.prompt.pattern }),\n ...(opts?.prompt?.customValidator !== undefined && { customValidator: opts.prompt.customValidator }),\n }\n const promptResult = validateSecret(parts.prompt, promptPolicy)\n if (!promptResult.ok) return { result: promptResult, failedCheck: 'prompt' }\n // Same field-by-field construction as promptPolicy above (not a spread of\n // `opts?.combined`) so the combined check's minWordLength defaults to the\n // echo floor too, while minWords keeps the standard whole-secret default\n // (6) when the caller doesn't override it.\n const combinedPolicy: SecretPolicy = {\n ...(opts?.combined?.minWords !== undefined && { minWords: opts.combined.minWords }),\n minWordLength: opts?.combined?.minWordLength ?? DEFAULT_ECHO_MIN_WORD_LENGTH,\n ...(opts?.combined?.rejectRepeatedAdjacent !== undefined\n && { rejectRepeatedAdjacent: opts.combined.rejectRepeatedAdjacent }),\n ...(opts?.combined?.pattern !== undefined && { pattern: opts.combined.pattern }),\n ...(opts?.combined?.customValidator !== undefined && { customValidator: opts.combined.customValidator }),\n }\n const combinedResult = validateSecret(`${parts.prompt} ${parts.echo} ${parts.key}`, combinedPolicy)\n return { result: combinedResult, failedCheck: 'combined' }\n}\n\n/** Validate a 3-part echo secret. Never throws. */\nexport function validateEchoSecret(\n parts: { readonly prompt: string; readonly echo: string; readonly key: string },\n opts?: EchoSecretPolicy,\n): SecretValidationResult {\n return validateEchoSecretDetailed(parts, opts).result\n}\n\n/**\n * Suggestion copy for a failure that came from the PROMPT's dedicated floor.\n * The generic `SUGGESTIONS` copy quotes the 6-word whole-secret floor, which\n * misdirects an owner whose prompt only has to clear 3 words.\n */\nfunction promptSuggestion(reason: WeakSecretReason, minWords: number): string {\n if (reason === 'too-few-words') {\n return `The prompt (the part you type first) must be at least ${minWords} words. Example: \"sono chiamato vicio\".`\n }\n return `The prompt (the part you type first) is the problem. ${SUGGESTIONS[reason]}`\n}\n\n/** Throwing form of {@link validateEchoSecret}. */\nexport function assertStrongEchoSecret(\n parts: { readonly prompt: string; readonly echo: string; readonly key: string },\n opts?: EchoSecretPolicy & { allowWeakSecret?: boolean },\n): void {\n if (opts?.allowWeakSecret) return\n const { result, failedCheck } = validateEchoSecretDetailed(parts, opts)\n if (result.ok) return\n\n const promptMinWords = opts?.prompt?.minWords ?? DEFAULT_ECHO_PROMPT_MIN_WORDS\n const suggestion = failedCheck === 'prompt'\n ? promptSuggestion(result.reason, promptMinWords)\n : SUGGESTIONS[result.reason]\n\n throw new WeakSecretError(result.reason, suggestion)\n}\n","/**\n * Echo-block builders + verifiers (spec\n * design-history/2026-08-02-echo-secret-design.md, #940).\n *\n * Builds and verifies the on-keyring {@link KeyringEchoBlock} declaration\n * for the 3-part echo ceremony (prompt → echo → key). This module owns:\n *\n * - Minting the prompt/echo canary verifiers (the \"canary trick\": AES-KW\n * wrap a constant 32-byte key under `deriveSecretKey(part, salt, …)`;\n * verify = unwrap succeeds).\n * - Building the reveal blob per the hybrid reveal policy (spec decision\n * 4): `portable` (AES-GCM under the prompt, own salt), `sealed`\n * (opaque to hub, unsealed only by the enrolling device's\n * {@link DeviceSealProvider}), or `none`.\n * - Resolving the echo for display (`resolveEchoReveal`, `null` ⇒\n * degraded typed-echo path) and verifying a typed echo\n * (`verifyTypedEcho`) for that degraded path.\n *\n * Deriving the actual KEK from all three parts together is\n * `deriveEchoKey`/`encodeEchoParts` (`kernel/enclave/crypto.ts`) — a\n * separate concern from this module's per-part verifiers.\n *\n * Known, accepted disclosure: `prompt_verifier` and `echo_verifier` are\n * offline brute-force oracles for anyone holding the keyring file (600K\n * PBKDF2 per guess), and the `sealed` reveal blob is unpadded so its length\n * discloses the echo's UTF-8 byte length — see the threat model in\n * `design-history/2026-08-02-echo-secret-design.md`.\n *\n * @module\n */\n\nimport {\n deriveSecretKey,\n generateSalt,\n generateIV,\n wrapKey,\n bufferToBase64,\n base64ToBuffer,\n encodeEchoParts,\n type EchoSecretParts,\n} from '../../kernel/enclave/index.js'\nimport type { KeyringEchoBlock } from '../../kernel/types.js'\nimport type { DeviceSealProvider } from './device-seal.js'\nimport { WrongPromptError } from '../../kernel/errors.js'\n\n/** Same iteration floor as the KEK (spec resolved question 1). */\nexport const ECHO_KDF_ITERATIONS = 600_000\n\nconst VERIFIER_PLAINTEXT = new Uint8Array(32).fill(0x5a)\nconst subtle = globalThis.crypto.subtle\n\nasync function getVerifierKey(): Promise<CryptoKey> {\n return subtle.importKey('raw', VERIFIER_PLAINTEXT as BufferSource, { name: 'AES-GCM' }, true, ['encrypt'])\n}\n\nasync function mintVerifier(part: string, salt: Uint8Array): Promise<string> {\n const kek = await deriveSecretKey(part, salt, { iterations: ECHO_KDF_ITERATIONS, keyUsage: 'aes-kw' })\n return wrapKey(await getVerifierKey(), kek)\n}\n\n/**\n * `saltB64` and `verifier` are both decoded INSIDE the guarded region so a\n * tampered/corrupt base64 salt or verifier surfaces as `false`, not a raw\n * `DOMException` (InvalidCharacterError) escaping to the caller.\n */\nasync function checkVerifier(verifier: string, part: string, saltB64: string): Promise<boolean> {\n try {\n const kek = await deriveSecretKey(part, base64ToBuffer(saltB64), { iterations: ECHO_KDF_ITERATIONS, keyUsage: 'aes-kw' })\n await subtle.unwrapKey('raw', base64ToBuffer(verifier) as BufferSource, kek, 'AES-KW', { name: 'AES-GCM' }, false, ['encrypt'])\n return true\n } catch {\n return false\n }\n}\n\nexport type EchoRevealChoice =\n | { readonly kind: 'portable' }\n | { readonly kind: 'sealed'; readonly deviceSeal: DeviceSealProvider }\n | { readonly kind: 'none' }\n\n/** Build the on-keyring echo declaration for a fresh enrollment. */\nexport async function buildEchoBlock(\n parts: EchoSecretParts,\n reveal: EchoRevealChoice,\n maskHint?: string,\n): Promise<KeyringEchoBlock> {\n // Validate the 3-part shape through the SAME chokepoint the KEK derivation\n // uses (result deliberately discarded — only its guard is wanted here). A\n // malformed parts object would otherwise be TextEncoder-coerced below and\n // mint verifiers that no owner-derivable KEK matches.\n encodeEchoParts(parts)\n const promptSalt = generateSalt()\n const echoSalt = generateSalt()\n let revealField: KeyringEchoBlock['reveal']\n if (reveal.kind === 'portable') {\n const blobSalt = generateSalt()\n const iv = generateIV()\n const gcmKey = await deriveSecretKey(parts.prompt, blobSalt, { iterations: ECHO_KDF_ITERATIONS, keyUsage: 'aes-gcm' })\n const ct = new Uint8Array(\n await subtle.encrypt({ name: 'AES-GCM', iv: iv as BufferSource }, gcmKey, new TextEncoder().encode(parts.echo)),\n )\n revealField = { kind: 'portable', blob: bufferToBase64(ct), iv: bufferToBase64(iv), salt: bufferToBase64(blobSalt) }\n } else if (reveal.kind === 'sealed') {\n const sealed = await reveal.deviceSeal.seal(new TextEncoder().encode(parts.echo))\n revealField = { kind: 'sealed', blob: bufferToBase64(sealed), provider_hint: reveal.deviceSeal.id }\n } else {\n revealField = { kind: 'none' }\n }\n return {\n v: 1,\n prompt_salt: bufferToBase64(promptSalt),\n prompt_verifier: await mintVerifier(parts.prompt, promptSalt),\n echo_salt: bufferToBase64(echoSalt),\n echo_verifier: await mintVerifier(parts.echo, echoSalt),\n reveal: revealField,\n ...(maskHint !== undefined ? { mask_hint: maskHint } : {}),\n }\n}\n\nexport async function verifyPrompt(block: KeyringEchoBlock, prompt: string): Promise<boolean> {\n return checkVerifier(block.prompt_verifier, prompt, block.prompt_salt)\n}\n\n/**\n * Resolve the echo for display. `null` ⇒ degraded path: the player\n * must ask the owner to TYPE the echo (verify via {@link verifyTypedEcho}).\n * Callers MUST verify the prompt first — this assumes it.\n *\n * @throws WrongPromptError when the prompt cannot open the portable reveal\n * (callers should verifyPrompt first for a boolean check).\n */\nexport async function resolveEchoReveal(\n block: KeyringEchoBlock,\n prompt: string,\n deviceSeal?: DeviceSealProvider,\n): Promise<string | null> {\n if (block.reveal.kind === 'portable') {\n try {\n const gcmKey = await deriveSecretKey(prompt, base64ToBuffer(block.reveal.salt), {\n iterations: ECHO_KDF_ITERATIONS,\n keyUsage: 'aes-gcm',\n })\n const plain = await subtle.decrypt(\n { name: 'AES-GCM', iv: base64ToBuffer(block.reveal.iv) as BufferSource },\n gcmKey,\n base64ToBuffer(block.reveal.blob) as BufferSource,\n )\n return new TextDecoder().decode(plain)\n } catch {\n // Wrong prompt (or corrupt salt/iv/blob) — a wrong prompt must NOT\n // silently degrade to the typed-echo path, that would weaken mutual\n // auth. Surface a typed error instead of the raw DOMException.\n throw new WrongPromptError()\n }\n }\n if (block.reveal.kind === 'sealed' && deviceSeal !== undefined) {\n if (deviceSeal.id !== block.reveal.provider_hint) {\n // Legitimate foreign-device-with-its-own-provider case (spec's\n // degradation matrix) — degrade to the typed-echo path rather than\n // attempting (and failing) an unseal under the wrong provider.\n return null\n }\n // Same provider id: a thrown error here is a genuine tamper/wrong-device\n // anomaly and must surface, not be silently masked.\n const plain = await deviceSeal.unseal(base64ToBuffer(block.reveal.blob))\n return new TextDecoder().decode(plain)\n }\n return null\n}\n\nexport async function verifyTypedEcho(block: KeyringEchoBlock, echo: string): Promise<boolean> {\n return checkVerifier(block.echo_verifier, echo, block.echo_salt)\n}\n","/**\n * Secret-bearing reserved collections — the `_`-prefixed reserved collections\n * whose record CONTENTS are directly-usable secrets (transport OAuth tokens,\n * connection strings, API keys), as opposed to the *operational* reserved\n * collections (`_ledger`, `_history`, `_sync`, …) whose contents are metadata\n * (collection names, record ids, ciphertext hashes).\n *\n * This distinction matters at two trust-boundary seams:\n *\n * 1. `vault.collection()` — a secret-bearing reserved name must never be\n * reachable through the generic public collection handle. It is served\n * ONLY by its dedicated, role-gated API (e.g. `_sync_credentials` →\n * `getCredential`/`putCredential`, which enforce owner/admin access).\n *\n * 2. `grant()` DEK propagation — a sub-admin grantee (operator, viewer,\n * client, custodian) must NOT receive a secret-bearing collection's DEK.\n * Operational reserved DEKs still propagate to every role (grantees must\n * write ledger/history entries on every mutation), but handing a\n * sub-admin the `_sync_credentials` DEK would let them decrypt the firm's\n * transport secrets — a plaintext leak, not a metadata leak.\n *\n * Kept dependency-free so both the kernel (`vault.ts`) and the team layer\n * (`keyring.ts`) can import it without an import cycle.\n */\n\n/** Reserved collection holding per-adapter sync transport secrets. */\nexport const SYNC_CREDENTIALS_COLLECTION = '_sync_credentials'\n\n/**\n * Reserved (pre-allocated) name for the future credential broker (#479).\n * Not yet implemented — reserved now so that neither the public collection\n * handle nor grant propagation can ever expose it before its dedicated,\n * role-gated API lands.\n */\nexport const BROKER_COLLECTION = '_broker'\n\n/**\n * The set of reserved collection names whose record contents are\n * directly-usable secrets. Membership here means: never served via\n * `vault.collection()`, never propagated to sub-admin grantees.\n */\nexport const SECRET_BEARING_RESERVED_COLLECTIONS: ReadonlySet<string> = new Set([\n SYNC_CREDENTIALS_COLLECTION,\n BROKER_COLLECTION,\n])\n\n/** True when `name` is a secret-bearing reserved collection. */\nexport function isSecretBearingReservedCollection(name: string): boolean {\n return SECRET_BEARING_RESERVED_COLLECTIONS.has(name)\n}\n","import type { NoydbStore, KeyringFile, KeyringAuthenticator, Role, Permissions, GrantOptions, RevokeOptions, UpdateUserOptions, UserInfo, EncryptedEnvelope, ExportCapability, ExportFormat, ImportCapability, VaultPolicyOnDisk, UserEnvelope } from '../../kernel/types.js'\nimport { NOYDB_KEYRING_VERSION } from '../../kernel/types.js'\nimport { USER_ENVELOPE_COLLECTION, ROSTER_KEY_ID } from '../../kernel/constants.js'\nimport {\n buildRecordEnvelope,\n deriveKey,\n deriveEchoKey,\n generateDEK,\n generateSalt,\n wrapKey,\n unwrapKey,\n rekeyEnvelopeIfNeeded,\n rekeyBlobSet,\n bufferToBase64,\n base64ToBuffer,\n type EnclaveKey,\n type EchoSecretParts,\n} from '../../kernel/enclave/index.js'\nimport { NoAccessError, PermissionDeniedError, PrivilegeEscalationError, KeyringExpiredError, KeyringCorruptError, KeyringTamperedError, InvalidKeyError, ValidationError, DirectoryDisabledError, EchoCeremonyRequiredError } from '../../kernel/errors.js'\nimport type { KeyringTamperedReason } from '../../kernel/errors.js'\nimport { mintRosterTag, assertRosterAuthenticated, assertRosterTagValid } from './roster-tag.js'\nimport { readDirectoryConfig } from '../directory/storage.js'\nimport { readUserVisibility, deleteUserVisibility } from '../directory/visibility.js'\nimport {\n assertStrongSecret,\n assertStrongEchoSecret,\n type SecretPolicy,\n type EchoSecretPolicy,\n} from '../../kernel/validation.js'\nimport { buildEchoBlock } from './echo-secret.js'\nimport type { DeviceSealProvider } from './device-seal.js'\nimport {\n saveUserEnvelope,\n loadUserEnvelope as loadUserEnvelopeFn,\n deleteUserEnvelope,\n} from '../directory/user-envelope/index.js'\nimport { isSecretBearingReservedCollection } from './reserved-secret-collections.js'\n\n// ─── Roles that can grant/revoke ───────────────────────────────────────\n\n/**\n * Roles that an `admin` is allowed to grant and revoke.\n *\n * Includes `'admin'` itself: the model bottlenecked all admin\n * onboarding through the single `owner` principal, which made lateral\n * delegation impossible and left a single-owner bus-factor risk\n * unresolved even when multiple trusted humans existed. opens up\n * admin↔admin lateral delegation, with two guardrails:\n *\n * 1. **No privilege escalation.** Enforced in `grant()`: every DEK\n * wrapped into the new admin's keyring must be present in the\n * grantor's own DEK set. Today this is structurally trivially\n * true (admin grants always inherit the full caller DEK set),\n * but the check is wired in so future per-collection admin scoping\n * cannot accidentally bypass it. See `PrivilegeEscalationError`.\n *\n * 2. **Cascade on revoke.** Enforced in `revoke()`: when an admin is\n * revoked, every admin they (transitively) granted is either\n * revoked too (`cascade: 'strict'`, default) or left in place with\n * a console warning (`cascade: 'warn'`). The walk uses the\n * `granted_by` field on each keyring file as the parent pointer.\n */\n// FR-6: 'custodian' is deliberately ABSENT here. An admin must not be able\n// to mint (or revoke) a custodian — only the (sealed Deed) owner can, because\n// the custodian is the de-facto operational authority and granting one is an\n// ownership-level act. `canGrant(admin, 'custodian')` therefore returns false.\nconst ADMIN_GRANTABLE_TARGETS: readonly Role[] = ['operator', 'viewer', 'client', 'admin']\n\nfunction canGrant(callerRole: Role, targetRole: Role): boolean {\n if (callerRole === 'owner') return true\n // FR-6: a custodian can never grant — it holds the DEKs to OPERATE the\n // vault but no authority to widen the principal set. Explicit + fail-safe\n // (it would also fall through to `return false`, but spell it out).\n if (callerRole === 'custodian') return false\n if (callerRole === 'admin') return ADMIN_GRANTABLE_TARGETS.includes(targetRole)\n return false\n}\n\nfunction canRevoke(callerRole: Role, targetRole: Role): boolean {\n if (targetRole === 'owner') return false // owner cannot be revoked\n if (callerRole === 'owner') return true\n // FR-6: a custodian can never revoke — same non-owning rationale as canGrant.\n if (callerRole === 'custodian') return false\n if (callerRole === 'admin') return ADMIN_GRANTABLE_TARGETS.includes(targetRole)\n return false\n}\n\n/**\n * Whether `callerRole` can mutate a keyring whose role is (or becomes)\n * `targetRole`. Used by `updateKeyringIdentity`.\n *\n * Mirrors `canGrant`'s hierarchy: admins manage admin/operator/viewer/\n * client laterally; admins cannot create or destroy `owner`-shaped\n * keyrings. Owner can do anything.\n *\n * Both the OLD role and the NEW role must satisfy this check —\n * otherwise admin could elevate themselves (`admin → owner`) or demote\n * an owner (`owner → admin`) under cover of \"update.\"\n */\nfunction canUpdateRole(callerRole: Role, targetRole: Role): boolean {\n if (callerRole === 'owner') return true\n if (callerRole === 'admin') return ADMIN_GRANTABLE_TARGETS.includes(targetRole)\n return false\n}\n\n// ─── Unlocked Keyring ──────────────────────────────────────────────────\n\n/** In-memory representation of an unlocked keyring. */\nexport interface UnlockedKeyring {\n readonly userId: string\n readonly displayName: string\n readonly role: Role\n readonly permissions: Permissions\n readonly deks: Map<string, EnclaveKey>\n /**\n * Unwrapped counterpart of {@link KeyringFile.pending_deks} — an\n * uncommitted rotation (#1074). Empty in the normal state.\n */\n readonly pendingDeks?: Map<string, EnclaveKey> | undefined\n /**\n * The KEK, when this keyring was unlocked via tier 1 (secret) or\n * a wrap-KEK tier-2 method (WebAuthn / OIDC). `null` when the\n * keyring was opened via:\n *\n * - Unencrypted mode (no KEK exists)\n * - Tier-3 PIN quick-resume (`@noy-db/on-pin`)\n * - Wrap-DEKs tier-2 unlock (`@noy-db/on-password`'s\n * `verifyPasswordSlot`)\n * - Session-state restore (`session/session.ts`)\n * - Dev-unlock fixture (`session/dev-unlock.ts`)\n *\n * Consumers performing tier-1 operations that need the KEK\n * (DEK rewrap, keyring persist, delegation issue/unwrap) must\n * null-check and throw a clear error if absent — re-authenticate\n * at tier 1 first to recover the KEK.\n *\n * Tightened from `EnclaveKey` to `EnclaveKey | null`; the runtime\n * contract has always allowed null, the type now matches reality.\n */\n readonly kek: EnclaveKey | null\n readonly salt: Uint8Array\n /**\n * Debug-plaintext layout flag. Set only on the plaintext keyring created\n * in `encrypt: false` + `debugPlaintext: true` mode — it lives here\n * because its lifecycle is identical to the plaintext keyring's (no\n * encrypted vault ever has it, so this never widens the encrypted surface).\n * When true, user-collection records are written with their fields inlined\n * beside the envelope metadata (`_debug: 1`) so native store tooling can\n * read them without unwrapping `_data`.\n */\n readonly debugPlaintext?: boolean\n /**\n * `@noy-db/as-*` export capability. Absent when the\n * keyring was written before this RFC landed — role-based defaults\n * apply via `hasExportCapability`.\n */\n readonly exportCapability?: ExportCapability\n /**\n * `@noy-db/as-*` import capability. Absent when the\n * keyring was written before the import-capability extension\n * landed — default-closed semantics\n * apply via `hasImportCapability` (no plaintext format granted, no\n * bundle import granted, regardless of role).\n */\n readonly importCapability?: ImportCapability\n /**\n * Tier-2 authenticator slots — readonly snapshot loaded from the\n * keyring file. Mutations go through `enrollAuthenticator` /\n * `removeAuthenticator`, which write back via\n * `persistKeyring`. Always defined; loads with an empty array for\n * keyrings written before the multi-slot extension landed.\n */\n readonly authenticators: readonly KeyringAuthenticator[]\n /**\n * Reserved per-keyring policy override (forward-compat for Option C\n * — see {@link VaultPolicyOnDisk}). v1.0 round-trips this field but\n * never enforces it; the gate engine uses `_meta/policy` only.\n */\n readonly policy?: VaultPolicyOnDisk\n}\n\n// ─── Secret canary ─────────────────────────────────────────────────\n//\n// The canary is a fixed 256-bit AES-GCM key (32 zero bytes), wrapped\n// under the keyring's KEK with AES-KW. Because AES-KW is deterministic\n// (RFC 3394 fixed IV), wrapping the same constant under the same KEK\n// always yields the same ciphertext — so every write site can mint\n// fresh on each persist without round-tripping a `canary` field\n// through UnlockedKeyring.\n//\n// On load, the canary unwraps cleanly iff the KEK is correct AND the\n// canary bytes on disk are intact. Combined with each-DEK try/catch,\n// this distinguishes wrong-secret (canary fails AND every DEK fails)\n// from corruption (canary succeeds OR at least one DEK succeeds) —\n// closing the all-DEKs-corrupt and single-DEK ambiguities that the\n// pre-canary heuristic left open.\n\nconst CANARY_PLAINTEXT_BYTES = new Uint8Array(32)\nlet canaryKeyPromise: Promise<EnclaveKey> | null = null\n\nfunction getCanaryKey(): Promise<EnclaveKey> {\n if (canaryKeyPromise === null) {\n canaryKeyPromise = globalThis.crypto.subtle.importKey(\n 'raw',\n CANARY_PLAINTEXT_BYTES as BufferSource,\n { name: 'AES-GCM', length: 256 },\n true, // extractable so AES-KW can wrap it\n ['encrypt', 'decrypt'],\n )\n }\n return canaryKeyPromise\n}\n\n/** Mint a fresh wrapped-canary string. Deterministic for a given KEK. */\nexport async function mintKeyringCanary(kek: EnclaveKey): Promise<string> {\n const canaryKey = await getCanaryKey()\n return wrapKey(canaryKey, kek)\n}\n\n/** Try to unwrap the canary. Returns true iff KEK + canary bytes are intact. */\nasync function verifyKeyringCanary(wrappedCanary: string, kek: EnclaveKey): Promise<boolean> {\n try {\n await unwrapKey(wrappedCanary, kek)\n return true\n } catch {\n return false\n }\n}\n\n// ─── Roster key (#1096) ────────────────────────────────────────────\n//\n// The vault-wide key that authenticates each keyring file's plaintext\n// AUTHORITY half. It lives in the DEK map under `ROSTER_KEY_ID` rather\n// than in a field of its own, so it reaches every member through the\n// channels a DEK already travels — grant's `_`-prefix propagation,\n// `persistKeyring`, the wrapped-DEKs recovery blob, `peer-recover`, pod\n// recipient slots, session tokens.\n\n/**\n * The vault roster key held by this keyring, or `null` when the keyring\n * carries none.\n *\n * Null is expected on the resume-style paths (`kek: null` sessions, tier-3\n * PIN resume, plaintext mode) — none of which may write a keyring file.\n * Every stamping site null-guards this exactly as it guards `kek`: minting a\n * file without a verifiable `roster_tag` would be worse than refusing, since\n * it is indistinguishable on the next load from a store having stripped it.\n */\nexport function rosterKeyOf(keyring: UnlockedKeyring): EnclaveKey | null {\n return keyring.deks.get(ROSTER_KEY_ID) ?? null\n}\n\n/**\n * Shared wording for the stamping-site guards — mirrors the `kek` guard's shape.\n * Exported so every roster-stamping site in the hub raises ONE error with one\n * wording, rather than each hand-copying it (`peer-recover`, `liberate`).\n */\nexport function requireRosterKey(keyring: UnlockedKeyring, fn: string): EnclaveKey {\n const rosterKey = rosterKeyOf(keyring)\n if (!rosterKey) {\n throw new ValidationError(\n `${fn}: caller keyring has no vault roster key — cannot stamp a roster tag. ` +\n 'This typically means the keyring was opened via tier-3 PIN resume, ' +\n 'session restore, or a wrap-DEKs tier-2 unlock. Re-authenticate at ' +\n 'tier 1 (secret) before writing a keyring.',\n )\n }\n return rosterKey\n}\n\n// ─── Load / Create ─────────────────────────────────────────────────────\n\n/** Options for {@link loadKeyring} (#846b). */\nexport interface LoadKeyringOptions {\n /** The user whose keyring to unlock. */\n readonly userId: string\n /**\n * That user's secret — a single string for a standard keyring, or the\n * structured 3-part {@link EchoSecretParts} for an echo keyring (spec\n * #940, AG-1: a single string can never unlock an echo keyring).\n */\n readonly secret: string | EchoSecretParts\n}\n\n/**\n * KDF dispatch for tier-1 unlock (spec #940). An echo keyring accepts\n * ONLY structured parts (AG-1 — no single string is key-equivalent);\n * a standard keyring accepts only a string.\n */\nexport async function deriveKekForKeyring(\n file: KeyringFile,\n secret: string | EchoSecretParts,\n salt: Uint8Array,\n): Promise<EnclaveKey> {\n if (file.echo !== undefined) {\n if (typeof secret === 'string') throw new EchoCeremonyRequiredError()\n return deriveEchoKey(secret, salt)\n }\n if (typeof secret !== 'string') {\n throw new ValidationError('This keyring uses a standard secret — pass a string, not echo parts.')\n }\n return deriveKey(secret, salt)\n}\n\n// ─── Raw keyring reads (#951) ───────────────────────────────────────────\n//\n// Single sanctioned reader of a keyring file's `_data`, plus the fetch+parse\n// and expiry-gate wrappers built on it. Every keyring.ts / echo-ceremony.ts\n// call site that used to inline `JSON.parse(env._data) as KeyringFile`\n// (each with its own missing-row semantics — throw / skip / continue) now\n// goes through `readKeyringFile`, which stays neutral on the missing-row\n// case (`undefined`) and lets each caller keep its own decision.\n\n/** Parse a raw keyring envelope. Single sanctioned reader of `_data` for keyring files. */\nexport function parseKeyringEnvelope(envelope: EncryptedEnvelope): KeyringFile {\n return JSON.parse(envelope._data) as KeyringFile\n}\n\n/** Fetch + parse a user's keyring file; undefined when the row is missing. */\nexport async function readKeyringFile(\n store: NoydbStore,\n vault: string,\n userId: string,\n): Promise<{ readonly envelope: EncryptedEnvelope; readonly file: KeyringFile } | undefined> {\n const envelope = await store.get(vault, '_keyring', userId)\n if (!envelope) return undefined\n return { envelope, file: parseKeyringEnvelope(envelope) }\n}\n\n/**\n * Shared expiry gate — refuse to unwrap an expired slot. Call before any\n * KEK derivation so an expired slot doesn't leak timing on the secret.\n * Comparison uses Date.parse → ms-since-epoch; an unparseable expires_at is\n * treated as \"no expiry\" so a malformed value can't silently lock users out\n * (it'll surface in tests).\n */\nexport function assertKeyringNotExpired(file: KeyringFile): void {\n if (file.expires_at !== undefined) {\n const cutoff = Date.parse(file.expires_at)\n if (Number.isFinite(cutoff) && Date.now() >= cutoff) {\n throw new KeyringExpiredError({ userId: file.user_id, expiresAt: file.expires_at })\n }\n }\n}\n\n/** Load and unlock a user's keyring for a vault. */\nexport async function loadKeyring(\n store: NoydbStore,\n vault: string,\n opts: LoadKeyringOptions,\n): Promise<UnlockedKeyring> {\n const { userId, secret } = opts\n const found = await readKeyringFile(store, vault, userId)\n\n if (!found) {\n throw new NoAccessError(`No keyring found for user \"${userId}\" in vault \"${vault}\"`)\n }\n\n const { file: keyringFile } = found\n\n // #1096 — the expiry gate MOVED below roster verification. `expires_at` is a\n // plaintext field, so gating on it first let a store forge a past date and\n // choose the error the user sees: `KeyringExpiredError` (\"your access ran\n // out\") instead of `KeyringTamperedError` (\"your store is attacking you\").\n // Fail-closed either way, but it is a lockout an operator would spend the\n // afternoon re-granting rather than investigating.\n //\n // The old ordering's rationale — skip the KDF for an expired slot so it\n // \"doesn't leak timing on the secret\" — does not survive the trade: PBKDF2\n // costs the same whether or not the secret is right, so the early exit\n // revealed expiry, not secret correctness. Doing the derivation costs an\n // expired slot 600K iterations and buys an honest error.\n\n const salt = base64ToBuffer(keyringFile.salt)\n const kek = await deriveKekForKeyring(keyringFile, secret, salt)\n\n // Verify the canary first when present. A canary success proves the\n // KEK is correct independent of any DEK byte — so subsequent DEK\n // unwrap failures are unambiguously corruption, not wrong-pass. A\n // canary failure with at least one DEK success indicates the KEK\n // is correct but the canary itself is corrupt.\n //\n // #1096 — the canary is REQUIRED. `=== undefined` stays reachable at\n // runtime despite the required type: this object was parsed from JSON a\n // store controls. No-legacy policy means an absent canary is not an old\n // file, it is a store stripping the field to escape verification.\n if (keyringFile.canary === undefined) {\n throw new KeyringTamperedError({ userId, reason: 'canary-missing' })\n }\n const canaryOk = await verifyKeyringCanary(keyringFile.canary, kek)\n\n // Unwrap each DEK independently — collect successes and failures.\n const deks = new Map<string, EnclaveKey>()\n const failedCollections: string[] = []\n let firstUnwrapError: unknown = null\n for (const [collName, wrappedDek] of Object.entries(keyringFile.deks)) {\n try {\n const dek = await unwrapKey(wrappedDek, kek)\n deks.set(collName, dek)\n } catch (err) {\n failedCollections.push(collName)\n if (firstUnwrapError === null) firstUnwrapError = err\n }\n }\n\n // #1074 — unwrap any uncommitted rotation key. Deliberately NOT folded into\n // `failedCollections`: a pending DEK that fails to unwrap means the\n // interrupted rotation cannot be resumed, which is worth surfacing on its own\n // terms, but it must not make an otherwise-healthy keyring read as corrupt.\n const pendingDeks = new Map<string, EnclaveKey>()\n for (const [collName, wrapped] of Object.entries(keyringFile.pending_deks ?? {})) {\n try {\n pendingDeks.set(collName, await unwrapKey(wrapped, kek))\n } catch {\n // Unresumable; `deks` still holds the pre-rotation key, so the records\n // the interrupted run had not reached remain readable.\n }\n }\n\n if (canaryOk) {\n // KEK proven correct by the canary. Any DEK failure is corruption.\n if (failedCollections.length > 0) {\n throw new KeyringCorruptError({ failedCollections, intactCount: deks.size })\n }\n } else {\n // Canary failed. If any DEK unwrapped, KEK is correct → canary bytes\n // are corrupted (rare; reported under the '_canary' sentinel).\n if (deks.size > 0) {\n throw new KeyringCorruptError({\n failedCollections: [...failedCollections, '_canary'],\n intactCount: deks.size,\n })\n }\n // Canary failed AND no DEK unwrapped — wrong KEK (or whole-file\n // corruption). Surface the original InvalidKeyError so\n // onInvalidKey: 'reset' can fire its documented recovery path.\n throw firstUnwrapError instanceof Error ? firstUnwrapError : new InvalidKeyError()\n }\n\n // #1096 — ROSTER AUTHENTICATION. Deliberately AFTER the key epilogue: a\n // plain wrong secret must keep reporting as InvalidKeyError and must never\n // be announced to the user as an attack. Past this point the KEK is proven\n // correct and every DEK unwrapped, so anything wrong with the plaintext\n // authority half is the store's doing.\n //\n // Absence is an error, not a skip. The alternative — verify only when a\n // tag is present — lets a store opt out of the whole mechanism by deleting\n // a plaintext field, which is precisely the power this closes.\n // A present-but-damaged roster entry already threw as KeyringCorruptError\n // above, so `roster-key-missing` from here means genuinely absent.\n await assertRosterAuthenticated(keyringFile, deks, userId)\n\n // Now that `expires_at` is known to be the value an authorised editor wrote,\n // an expiry is genuinely an expiry. See the note at the top of this function.\n assertKeyringNotExpired(keyringFile)\n\n return {\n userId: keyringFile.user_id,\n displayName: keyringFile.display_name,\n role: keyringFile.role,\n permissions: keyringFile.permissions,\n deks,\n pendingDeks,\n kek,\n salt,\n authenticators: keyringFile.authenticators ?? [],\n ...(keyringFile.export_capability !== undefined && { exportCapability: keyringFile.export_capability }),\n ...(keyringFile.import_capability !== undefined && { importCapability: keyringFile.import_capability }),\n ...(keyringFile.policy !== undefined && { policy: keyringFile.policy }),\n }\n}\n\n/**\n * Open-policy pre-gate: decide create-vs-fail-closed **before** any\n * vault write. `openVault` must not self-provision an owner keyring into a\n * vault held by other principals; create-on-open is allowed only for a\n * genuinely-new vault (no `_keyring/*` at all). Capability-free — one\n * `store.list`. Returns when the open may proceed (the caller is a member, or\n * the vault is genuinely-new and `create` is allowed, in which case the caller\n * falls through to the normal `createOwnerKeyring` path); throws `NoAccessError`\n * otherwise. Placed before managed-secret secret resolution (which persists\n * on first open), so a fail-closed open writes nothing.\n */\nexport async function assertKeyringOpenAllowed(\n store: NoydbStore,\n vault: string,\n userId: string,\n create: boolean,\n): Promise<void> {\n const keyringUsers = await store.list(vault, '_keyring')\n if (keyringUsers.includes(userId)) return // caller is a member → load existing\n if (!create) {\n throw new NoAccessError(`Vault \"${vault}\" not opened: create disabled and no keyring for \"${userId}\".`)\n }\n if (keyringUsers.length > 0) {\n throw new NoAccessError(\n `No keyring for user \"${userId}\" in vault \"${vault}\" (held by other principals) — refusing to self-provision.`,\n )\n }\n // empty → genuinely-new vault → caller proceeds to the create path\n}\n\n/**\n * Options for {@link createOwnerKeyring} (#846b). The `SecretPolicy` knobs are\n * flattened into the same bag rather than nested, so `assertStrongSecret` can\n * take `opts` directly.\n */\nexport interface CreateOwnerKeyringOptions extends SecretPolicy {\n /** The owner to create. */\n readonly userId: string\n /**\n * The owner's secret — a plain string for a standard keyring, or the\n * structured 3-part {@link EchoSecretParts} to enroll an echo keyring\n * (spec #940). The shape alone selects the KDF and whether an `echo`\n * block is written.\n */\n readonly secret: string | EchoSecretParts\n /** Gate creation on the phrase-format strength rules. Default false. */\n readonly validate?: boolean\n /** Escape hatch for fixtures and migrations — skips the strength gate. */\n readonly allowWeakSecret?: boolean\n /**\n * Echo enrollment only: device-local sealer for the reveal blob. Present\n * ⇒ `reveal: 'sealed'` (attacker-B resistance); absent ⇒ `reveal:\n * 'portable'` (spec resolved question 4). Ignored for a string secret.\n */\n readonly deviceSeal?: DeviceSealProvider\n /** Echo enrollment only: optional display hint for the masked echo. */\n readonly echoMaskHint?: string\n /**\n * Echo enrollment only: strength-policy knobs for the 3-part secret's\n * prompt / combined floors — the parts-path counterpart of the\n * flattened `SecretPolicy` fields this options bag already extends\n * (those apply to a STRING secret via `assertStrongSecret`; this\n * applies to {@link EchoSecretParts} via `assertStrongEchoSecret`).\n * Ignored for a string secret.\n */\n readonly echoSecretPolicy?: EchoSecretPolicy\n}\n\n/**\n * Create the initial owner keyring for a new vault.\n *\n * Pass `{ validate: true }` (or any `SecretPolicy` knob) to gate creation\n * on the phrase-format strength rules — `Noydb` threads this from\n * `NoydbOptions.validateSecret`. Direct callers (CLI, scripts,\n * test fixtures) opt in explicitly.\n */\nexport async function createOwnerKeyring(\n store: NoydbStore,\n vault: string,\n opts: CreateOwnerKeyringOptions,\n): Promise<UnlockedKeyring> {\n const { userId, secret } = opts\n if (opts.validate && !opts.allowWeakSecret) {\n // `buildEchoBlock` only type-validates the 3-part secret via the\n // `encodeEchoParts` chokepoint — the STRENGTH gate for it still has to\n // fire here, exactly like `assertStrongSecret` does for a string.\n if (typeof secret === 'string') assertStrongSecret(secret, opts)\n else {\n assertStrongEchoSecret(secret, {\n ...opts.echoSecretPolicy,\n ...(opts.allowWeakSecret !== undefined && { allowWeakSecret: opts.allowWeakSecret }),\n })\n }\n }\n const salt = generateSalt()\n const kek = typeof secret === 'string'\n ? await deriveKey(secret, salt)\n : await deriveEchoKey(secret, salt)\n\n // Eager-provision the _users DEK at owner creation. This guarantees\n // every subsequent grant inherits it via the existing\n // collName.startsWith('_') propagation in grant() — so multi-principal\n // user-envelope reads (alice reading bob's profile) work for new\n // vaults without any per-keyring DEK rotation. Pre-existing vaults\n // get the DEK lazily on first vault.user.* access (which only\n // materializes a single-principal DEK that won't propagate\n // retroactively — that's the documented \"lazy creation for\n // pre-existing keyrings\" rollout note in the spec).\n const userEnvelopeDek = await generateDEK()\n const wrappedUserEnvelopeDek = await wrapKey(userEnvelopeDek, kek)\n // #1096 — the vault's roster key is minted exactly here, once, and reaches\n // every later member through grant's `_`-prefix DEK propagation.\n const rosterKey = await generateDEK()\n const wrappedRosterKey = await wrapKey(rosterKey, kek)\n const canary = await mintKeyringCanary(kek)\n\n const authority = {\n user_id: userId,\n display_name: userId,\n role: 'owner' as const,\n permissions: {},\n granted_by: userId,\n }\n const keyringFile: KeyringFile = {\n _noydb_keyring: NOYDB_KEYRING_VERSION,\n ...authority,\n deks: {\n [USER_ENVELOPE_COLLECTION]: wrappedUserEnvelopeDek,\n [ROSTER_KEY_ID]: wrappedRosterKey,\n },\n salt: bufferToBase64(salt),\n created_at: new Date().toISOString(),\n canary,\n roster_tag: await mintRosterTag(authority, rosterKey),\n // The presence of this block is what makes the keyring an echo keyring —\n // `deriveKekForKeyring` reads it to refuse a single-string unlock (AG-1).\n ...(typeof secret !== 'string'\n ? {\n echo: await buildEchoBlock(\n secret,\n opts.deviceSeal ? { kind: 'sealed', deviceSeal: opts.deviceSeal } : { kind: 'portable' },\n opts.echoMaskHint,\n ),\n }\n : {}),\n }\n\n await writeKeyringFile(store, vault, userId, keyringFile)\n\n return {\n userId,\n displayName: userId,\n role: 'owner',\n permissions: {},\n deks: new Map([\n [USER_ENVELOPE_COLLECTION, userEnvelopeDek],\n [ROSTER_KEY_ID, rosterKey],\n ]),\n kek,\n salt,\n authenticators: [],\n }\n}\n\n// ─── Grant ─────────────────────────────────────────────────────────────\n\n/** Grant access to a new user. Caller must have grant privilege. */\nexport async function grant(\n store: NoydbStore,\n vault: string,\n callerKeyring: UnlockedKeyring,\n options: GrantOptions,\n): Promise<void> {\n if (!callerKeyring.kek) {\n throw new ValidationError(\n 'grant: caller keyring has no KEK — tier-2 wrap-DEKs and tier-3 PIN-resume ' +\n 'sessions cannot grant access to other users. Re-authenticate at tier 1 ' +\n '(secret) before granting.',\n )\n }\n const callerRosterKey = requireRosterKey(callerKeyring, 'grant')\n\n if (!canGrant(callerKeyring.role, options.role)) {\n throw new PermissionDeniedError(\n `Role \"${callerKeyring.role}\" cannot grant role \"${options.role}\"`,\n )\n }\n\n // PRESENCE check — distinct from, and unskippable by, the strength check\n // below. `GrantOptions.secret` is a required field, so only an untypechecked\n // call site can omit it (a build script outside the typecheck project, a\n // stale `passphrase` key surviving the 0.4.0-pre rename). Before #1004 that\n // call derived a KEK from `undefined`, minted a real keyring slot, and\n // surfaced as `InvalidKeyError` whenever the grantee first tried to unlock —\n // arbitrarily far from the call that caused it. Fail at the grant instead.\n // `allowWeakSecret` deliberately does NOT skip this: it waives the strength\n // POLICY, not the existence of a secret.\n const secret: unknown = options.secret\n if (typeof secret !== 'string' || secret.trim() === '') {\n throw new ValidationError(\n `grant: \\`secret\\` is required and must be a non-empty string (got ${\n secret === undefined ? 'undefined' : typeof secret === 'string' ? 'an empty string' : typeof secret\n }). The grantee's key is derived from it, so a missing secret produces a ` +\n 'keyring slot nobody can unlock. Note the 0.4.0-pre rename: the option is ' +\n '`secret`, not `passphrase`.',\n )\n }\n\n // Optional strength validation — opt-in via grant({ validateSecret: true })\n // or via the calling Noydb's NoydbOptions.validateSecret flag.\n // The override `allowWeakSecret: true` skips even when validate is on.\n if (\n (options as { validateSecret?: boolean }).validateSecret &&\n !options.allowWeakSecret\n ) {\n assertStrongSecret(options.secret)\n }\n\n // Determine which collections the new user gets access to\n const permissions = resolvePermissions(options.role, options.permissions)\n\n // Derive the new user's KEK from their secret\n const newSalt = generateSalt()\n const newKek = await deriveKey(options.secret, newSalt)\n\n // Only owner and admin may ever hold a secret-bearing reserved DEK\n // (`_sync_credentials`, `_broker`) — they are the roles the dedicated\n // credential API admits. Every other grantee (custodian, viewer, operator,\n // client) is excluded, even from the \"wrap ALL\" branches below: a custodian\n // operates the DATA but must never read the firm's transport secrets (see\n // `requireAdminAccess` in sync-credentials.ts), and handing any sub-admin\n // one of these DEKs is a plaintext leak, not a metadata leak.\n const granteeMayHoldSecrets =\n options.role === 'owner' || options.role === 'admin'\n\n // A grantee's DEKs can only ever be wrapped HERE, at grant time: wrapping\n // needs the grantee's KEK, which is derived from a secret the vault never\n // stores, so there is no later moment at which a newly-minted collection DEK\n // could be back-filled into an existing keyring. #1004: granting\n // `{ invoices: 'rw' }` before `invoices` existed therefore wrapped nothing\n // and left a permanently blind slot. Mint the DEK now so the grant is\n // honoured whichever order the caller works in.\n //\n // Only for collections that do not exist yet. If a collection HAS records\n // and the grantor still lacks its DEK, minting would fabricate a key that\n // decrypts nothing AND would hand the anti-privilege-escalation check below\n // a DEK the grantor never legitimately held — turning a structural guarantee\n // into a no-op. Leave those unwrapped and let the read path deny.\n let mintedForGrant = false\n for (const collName of Object.keys(permissions)) {\n // `'*'` is a marker, not a collection — minting a DEK for it would create a\n // literal `*` collection and cover nothing (#1010).\n if (collName === PERMISSION_WILDCARD) continue\n if (isSecretBearingReservedCollection(collName) && !granteeMayHoldSecrets) continue\n if (callerKeyring.deks.has(collName)) continue\n if (await collectionHasRecords(store, vault, collName)) continue\n callerKeyring.deks.set(collName, await generateDEK())\n mintedForGrant = true\n }\n // Only when we actually minted: the grantor's own keyring file has to record\n // the new DEK, or their next write to that collection would mint a SECOND,\n // different one and orphan the copy we are about to wrap for the grantee.\n if (mintedForGrant) await persistKeyring(store, vault, callerKeyring)\n\n // Wrap the appropriate DEKs with the new user's KEK\n const wrappedDeks: Record<string, string> = {}\n for (const collName of Object.keys(permissions)) {\n if (collName === PERMISSION_WILDCARD) continue\n // Never hand a secret-bearing reserved DEK to a sub-admin, even if the\n // grantor explicitly names it in `permissions` — that path is served\n // only by the owner/admin-gated credential API, not per-collection grants.\n if (isSecretBearingReservedCollection(collName) && !granteeMayHoldSecrets) continue\n const dek = callerKeyring.deks.get(collName)\n if (dek) {\n wrappedDeks[collName] = await wrapKey(dek, newKek)\n }\n }\n\n // For owner/admin/custodian/viewer roles, wrap ALL known DEKs.\n // FR-6: a custodian operates EVERY collection, so — like admin — it must\n // receive every collection DEK on grant. Without this branch a custodian\n // could neither read nor write and the role would be inert.\n // #1010 — `permissions: { '*': ... }` puts a permission-scoped grantee on the\n // same footing as the whole-vault roles: every DEK the grantor holds. Note the\n // inherent limit the caller must know about — this covers the collections that\n // exist NOW. A wildcard cannot enumerate collections created later, and a DEK\n // can only ever be wrapped at grant time, so a later collection needs a\n // re-grant (the read path says so explicitly).\n if (\n options.role === 'owner' ||\n options.role === 'admin' ||\n options.role === 'custodian' ||\n options.role === 'viewer' ||\n permissionsAreWildcard(options.permissions)\n ) {\n for (const [collName, dek] of callerKeyring.deks) {\n if (collName in wrappedDeks) continue\n if (isSecretBearingReservedCollection(collName) && !granteeMayHoldSecrets) continue\n wrappedDeks[collName] = await wrapKey(dek, newKek)\n }\n }\n\n // For ALL roles, propagate system-prefixed collection DEKs\n // (`_ledger`, `_history`, `_sync`, …). These are internal collections\n // that any user with access to the vault must be able to\n // read and write — for example, the hash-chained ledger writes\n // an entry on every put/delete, so operators and clients with write\n // access to a single data collection still need the `_ledger` DEK.\n //\n // Trade-off: a granted user can decrypt every system-collection\n // entry, including ones they would not otherwise have access to\n // (e.g., an operator on `invoices` can read ledger entries for\n // mutations in `salaries`). This is a metadata leak, not a\n // plaintext leak — the ledger entries record collection names,\n // record ids, and ciphertext hashes, but never plaintext records.\n // Per-collection ledger DEKs are tracked as a follow-up.\n //\n // EXCEPTION — secret-bearing reserved collections (`_sync_credentials`,\n // `_broker`) whose record CONTENTS are directly-usable secrets are NOT\n // propagated to sub-admin grantees. Unlike the operational collections\n // above, handing an operator/viewer/client/custodian one of these DEKs\n // IS a plaintext leak (the firm's transport OAuth tokens). Only owner and\n // admin — the roles the dedicated `getCredential`/`putCredential` API\n // admits — receive them, so the legit admin-reads-existing-credential\n // flow (which needs the DEK to decrypt, not regenerate) still works.\n for (const [collName, dek] of callerKeyring.deks) {\n if (!collName.startsWith('_') || collName in wrappedDeks) continue\n if (isSecretBearingReservedCollection(collName) && !granteeMayHoldSecrets) continue\n wrappedDeks[collName] = await wrapKey(dek, newKek)\n }\n\n // Anti-privilege-escalation check. Every DEK we just\n // wrapped into the new keyring must come from the caller's own DEK\n // set — the grantor cannot give the grantee access to a collection\n // they themselves can't read. Today this is structurally trivially\n // satisfied because every wrapped DEK was looked up in\n // `callerKeyring.deks` above, but the explicit check is wired in\n // so a future change (per-collection admin scoping, escrow-based\n // re-wrapping, etc.) cannot accidentally let a widening grant\n // through. See `PrivilegeEscalationError` for the rationale.\n for (const collName of Object.keys(wrappedDeks)) {\n if (!callerKeyring.deks.has(collName)) {\n throw new PrivilegeEscalationError(collName)\n }\n }\n\n const canary = await mintKeyringCanary(newKek)\n const authority = {\n user_id: options.userId,\n display_name: options.displayName,\n role: options.role,\n permissions,\n granted_by: callerKeyring.userId,\n ...(options.exportCapability !== undefined && { export_capability: options.exportCapability }),\n ...(options.importCapability !== undefined && { import_capability: options.importCapability }),\n }\n const keyringFile: KeyringFile = {\n _noydb_keyring: NOYDB_KEYRING_VERSION,\n ...authority,\n deks: wrappedDeks,\n salt: bufferToBase64(newSalt),\n created_at: new Date().toISOString(),\n canary,\n // The grantee's own copy of the roster key rode in via the `_`-prefix\n // propagation loop above, so they can verify this tag on first unlock.\n roster_tag: await mintRosterTag(authority, callerRosterKey),\n }\n\n await writeKeyringFile(store, vault, options.userId, keyringFile)\n\n // User envelope bootstrap. Seeded with `options.initialProfile` if\n // provided, otherwise an empty `{}`. Encrypted with the caller's\n // _users DEK — which is the same DEK that was wrapped into the new\n // keyring's `wrappedDeks[USER_ENVELOPE_COLLECTION]` above (system-\n // collection propagation), so the new user can decrypt it on first\n // open. Skipped silently if the caller has no _users DEK (pre-feature\n // vault upgrade path — documented \"lazy creation for pre-existing\n // keyrings\" in the spec).\n const userEnvelopeDek = callerKeyring.deks.get(USER_ENVELOPE_COLLECTION)\n if (userEnvelopeDek) {\n const initialPayload = options.initialProfile ?? {}\n await saveUserEnvelope(\n store,\n vault,\n options.userId,\n initialPayload,\n userEnvelopeDek,\n )\n }\n}\n\n// ─── Revoke ────────────────────────────────────────────────────────────\n\n/**\n * Walk every keyring in the vault to find admins that the given\n * `rootUserId` (transitively) granted, via the `granted_by` parent\n * pointer recorded on each keyring file.\n *\n * Returns the set of descendant admin user-ids in DFS order, NOT\n * including the root itself. Non-admin descendants are excluded\n * because operators/viewers/clients cannot grant other users — they\n * are leaves in the delegation tree and cleaning them up is the\n * caller's job (or the next rotate, since they'd lose key access\n * anyway when the cascading admin's collections rotate).\n *\n * The walk uses a visited set keyed by user-id so cycles introduced\n * by re-grants (admin-A revoked, then re-granted later by admin-B who\n * was originally granted by A) terminate cleanly.\n */\nasync function findAdminDescendants(\n store: NoydbStore,\n vault: string,\n rootUserId: string,\n rosterKey: EnclaveKey,\n): Promise<string[]> {\n const allUserIds = await store.list(vault, '_keyring')\n\n // Build a map: parentUserId → child KeyringFiles. We only ever\n // descend into admins, so non-admin children are skipped at the\n // edge level rather than after a recursive call.\n const childrenByParent = new Map<string, string[]>()\n for (const userId of allUserIds) {\n const found = await readKeyringFile(store, vault, userId)\n if (!found) continue\n const kf = found.file\n // #1096 — the two fields this walk steers on, `role` and `granted_by`, are\n // both plaintext. A forged `granted_by` re-parents a descendant admin out\n // of the cascade so a revoke silently leaves them in place; a forged `role`\n // hides them from the walk entirely. Verify every file before reading\n // either — this is the graph the whole cascade is computed from.\n await assertRosterTagValid(kf, rosterKey, userId)\n // Only admins can grant, so only admins have a delegation subtree to\n // cascade. FR-6: a custodian is intentionally EXCLUDED here — it cannot\n // grant (canGrant(custodian,*) === false), so it is never a cascade root\n // and never a descendant edge. Treating it as an admin-descendant would\n // wrongly sweep it into an admin's revoke cascade.\n if (kf.role !== 'admin') continue // only admins can grant — leaves are uninteresting\n if (kf.user_id === rootUserId) continue // self-edges are noise\n const list = childrenByParent.get(kf.granted_by) ?? []\n list.push(kf.user_id)\n childrenByParent.set(kf.granted_by, list)\n }\n\n const visited = new Set<string>()\n const order: string[] = []\n const stack: string[] = [...(childrenByParent.get(rootUserId) ?? [])]\n while (stack.length > 0) {\n const next = stack.pop()!\n if (visited.has(next)) continue\n visited.add(next)\n order.push(next)\n for (const grandchild of childrenByParent.get(next) ?? []) {\n if (!visited.has(grandchild)) stack.push(grandchild)\n }\n }\n return order\n}\n\n/** Revoke a user's access. Optionally rotate keys for affected collections. */\nexport async function revoke(\n store: NoydbStore,\n vault: string,\n callerKeyring: UnlockedKeyring,\n options: RevokeOptions,\n): Promise<void> {\n // Load the target's keyring to check their role\n const targetFound = await readKeyringFile(store, vault, options.userId)\n if (!targetFound) {\n // #1077 — the entry may be absent because a PREVIOUS revoke deleted it and\n // then failed during rotation. `revoke()` deletes first and rotates second,\n // with no transaction, so that window is reachable by any store error.\n //\n // Throwing here is what made the state dangerous: the operator retries,\n // sees \"has no keyring\", reads it as \"already revoked, nothing to do\", and\n // stops — while the keys were never rotated. The failure was silent\n // precisely because it looked like success.\n //\n // An uncommitted rotation on the caller's own keyring is the evidence that\n // this happened (`pending_deks`, #1074). Resume it rather than reporting a\n // not-found: finishing the interrupted job is what the operator asked for,\n // and it makes retrying `revoke()` idempotent instead of misleading.\n const pending = [...(callerKeyring.pendingDeks?.keys() ?? [])]\n if (pending.length > 0) {\n await rotateKeys(store, vault, callerKeyring, { collections: pending })\n return\n }\n throw new NoAccessError(`User \"${options.userId}\" has no keyring in vault \"${vault}\"`)\n }\n\n const targetKeyring = targetFound.file\n\n // #1096 — `canRevoke` below consumes `targetKeyring.role`, and the cascade\n // walk consumes `granted_by` from every keyring in the vault. Both come from\n // the plaintext header, so verify before either is trusted.\n const callerRosterKey = requireRosterKey(callerKeyring, 'revoke')\n await assertRosterTagValid(targetKeyring, callerRosterKey, options.userId)\n\n if (!canRevoke(callerKeyring.role, targetKeyring.role)) {\n throw new PermissionDeniedError(\n `Role \"${callerKeyring.role}\" cannot revoke role \"${targetKeyring.role}\"`,\n )\n }\n\n // Cascade-on-revoke. Only meaningful when the target is\n // an admin — operators/viewers/clients cannot grant other users so\n // they have no delegation subtree to walk.\n const cascadeMode = options.cascade ?? 'strict'\n const usersToRevoke: string[] = [options.userId]\n const affectedCollections = new Set(Object.keys(targetKeyring.deks))\n\n if (targetKeyring.role === 'admin') {\n const descendants = await findAdminDescendants(store, vault, options.userId, callerRosterKey)\n if (descendants.length > 0) {\n if (cascadeMode === 'warn') {\n // Diagnostic mode: leave the descendants in place but make\n // them visible. The owner / a different admin can clean up\n // manually. The single console.warn is intentionally noisy\n // (a list, not a count) so the operator sees exactly which\n // keyrings will become orphans.\n console.warn(\n `[noy-db] revoke(${options.userId}): cascade='warn' — leaving ` +\n `${descendants.length} descendant admin(s) in place: ` +\n `${descendants.join(', ')}. These admins were granted by the revoked user ` +\n `(transitively) and will become orphans in the delegation tree.`,\n )\n } else {\n // Strict mode (default): pull every descendant into the\n // revoke set. We collect their affected collections too so\n // the single rotation pass at the end covers everything.\n for (const userId of descendants) {\n const descFound = await readKeyringFile(store, vault, userId)\n if (!descFound) continue\n // Re-read, so re-verify: the walk above proved a file at one moment,\n // this is a second fetch from the same untrusted store.\n await assertRosterTagValid(descFound.file, callerRosterKey, userId)\n usersToRevoke.push(userId)\n for (const c of Object.keys(descFound.file.deks)) affectedCollections.add(c)\n }\n }\n }\n }\n\n // Delete every keyring in the revoke set. Order doesn't matter\n // because each keyring file is independent on disk; we don't have\n // referential integrity to maintain across deletes.\n for (const userId of usersToRevoke) {\n await store.delete(vault, '_keyring', userId)\n // Cascade-delete the principal's user envelope. Idempotent — no\n // error when the envelope was never written (e.g. the user was\n // granted but never authenticated to write their own profile).\n await deleteUserEnvelope(store, vault, userId)\n // Also drop the visibility sidecar at `_meta/visibility/<userId>`.\n // If the same `userId` is re-granted later (rare for humans,\n // possible for service accounts and test fixtures), the new\n // principal must start with a fresh visibility state instead of\n // silently inheriting the revoked user's `hidden` flag.\n await deleteUserVisibility(store, vault, userId)\n }\n\n // Single rotation pass at the end. The cost is O(records in\n // affected collections), NOT O(records × cascade depth) — every\n // descendant's collections were unioned into `affectedCollections`\n // before we got here, so the rotation re-encrypts each affected\n // record exactly once regardless of how deep the cascade went.\n //\n // #1043 — this is UNCONDITIONAL, and it is what makes revocation mean\n // anything. Revocation's first act is `store.delete(vault, '_keyring',\n // userId)`, and the store is untrusted by design: it can simply decline.\n // The revoked member's old keyring file is authentic — it unwraps under\n // their own KEK and its canary verifies — so nothing in `loadKeyring` can\n // tell it is stale. Rotation is the only step the store cannot suppress,\n // because it re-keys the records themselves. A probe confirmed both halves:\n // with rotation the revoked member is locked out entirely; without it,\n // revocation is a complete no-op and they keep reading data written after\n // they were revoked.\n // #1096 — the set above is derived from DEK-map keys, so it picks up the\n // reserved roster key, which is not a collection and must never be rotated\n // (see the refusal in `rotateKeys`). Dropped here, at the one site that\n // gathers it implicitly, so `rotateKeys` can stay loud about explicit asks.\n affectedCollections.delete(ROSTER_KEY_ID)\n if (affectedCollections.size > 0) {\n const { unverified } = await rotateKeys(store, vault, callerKeyring, {\n collections: [...affectedCollections],\n })\n // #1114 — `revoke` resolves to void, so without this the quarantine would\n // be the one thing a rotation reports that nobody can hear. Noisy and\n // itemised on purpose, matching the `cascade: 'warn'` warning above: the\n // operator needs the names, because each one is a member who is now locked\n // out of the vault by a file only an out-of-band repair can fix.\n if (unverified.length > 0) {\n console.warn(\n `[noy-db] revoke(${options.userId}): ${unverified.length} member(s) were SKIPPED by the ` +\n `rotation because their keyring failed roster authentication: ` +\n `${unverified.map((u) => `${u.userId} (${u.reason})`).join(', ')}. ` +\n 'The revocation itself completed. Those members cannot open the vault and did not ' +\n 'receive the rotated keys; their keyring files need repair or removal (noy-db#1114).',\n )\n }\n }\n}\n\n// ─── Roster diagnostics + quarantine (#1121) ───────────────────────────\n\n/** What {@link verifyRoster} found. */\nexport interface RosterVerifyResult {\n /**\n * How many `_keyring` files were examined.\n *\n * Reported first, and deliberately: \"nothing unverified\" is equally true of a\n * sweep that examined nothing, and a roster check that silently covered zero\n * members would look identical to a healthy vault. Same lesson as the vault\n * head's `no-expectations` verdict (#1101).\n */\n readonly checked: number\n /** The files that failed authentication, and why. */\n readonly unverified: ReadonlyArray<{\n readonly userId: string\n readonly reason: KeyringTamperedReason\n }>\n}\n\n/**\n * Verify every `_keyring` file in the vault, without touching any of them.\n *\n * Before this there was no way to learn WHICH file was unverifiable except by\n * trial: a member's own unlock failed, `revoke` of that member failed, and\n * (before #1114) every rotation failed too — all with the same error, none\n * naming the file. Read-only and side-effect free, so it is safe to run when\n * something is already wrong.\n */\n/**\n * Read a keyring file for AUDIT rather than for use (#1121).\n *\n * `readKeyringFile` does a bare `JSON.parse`, which is right everywhere it is\n * used to OPEN a keyring — a file that will not parse cannot be honoured, and\n * throwing is the honest outcome. It is wrong for the two tools built to deal\n * with files that are already broken: a truncated `_data` made `verifyRoster`\n * throw instead of reporting, and made the one file most in need of quarantine\n * the one file quarantine could not touch.\n */\nasync function readKeyringForAudit(\n store: NoydbStore,\n vault: string,\n userId: string,\n): Promise<{ file: KeyringFile } | { unparseable: true } | undefined> {\n const envelope = await store.get(vault, '_keyring', userId)\n if (!envelope) return undefined\n try {\n return { file: parseKeyringEnvelope(envelope) }\n } catch {\n return { unparseable: true }\n }\n}\n\nexport async function verifyRoster(\n store: NoydbStore,\n vault: string,\n callerKeyring: UnlockedKeyring,\n): Promise<RosterVerifyResult> {\n const rosterKey = requireRosterKey(callerKeyring, 'verifyRoster')\n const unverified: Array<{ userId: string; reason: KeyringTamperedReason }> = []\n let checked = 0\n\n for (const userId of await store.list(vault, '_keyring')) {\n const found = await readKeyringForAudit(store, vault, userId)\n if (!found) continue // raced with a delete; not this function's business\n checked += 1\n if ('unparseable' in found) {\n unverified.push({ userId, reason: 'unparseable' })\n continue\n }\n try {\n await assertRosterTagValid(found.file, rosterKey, userId)\n } catch (err) {\n // Only the tamper verdict is a finding. Anything else is a real failure\n // and must not be reported as a roster problem.\n if (!(err instanceof KeyringTamperedError)) throw err\n unverified.push({ userId, reason: err.details.reason })\n }\n }\n\n return { checked, unverified }\n}\n\n/** What {@link quarantineKeyring} did. */\nexport interface QuarantineResult {\n readonly userId: string\n /** Why the file could not be authenticated — the justification for removing it. */\n readonly reason: KeyringTamperedReason\n /** Collections re-keyed as part of the removal. */\n readonly rotated: readonly string[]\n /**\n * (member, collection) pairs whose access the rotation dropped — the OTHER\n * members, who must be re-granted.\n *\n * Passed through from `rotateKeys` rather than discarded, because a\n * quarantine rotates broadly (see the scope note on the function) and so\n * de-provisions more people than the one being removed. An operator who is\n * not told this discovers it as unrelated `NoAccessError`s later.\n */\n readonly needsRegrant: RotateResult['needsRegrant']\n /**\n * OTHER members whose own files also failed authentication, found while\n * rotating. One forged file is rarely the only one, and the operator is\n * already holding the tool for them.\n */\n readonly alsoUnverified: RotateResult['unverified']\n}\n\n/**\n * Remove a `_keyring` file that cannot be authenticated, and re-key behind it\n * (#1121).\n *\n * ## Why this is not a flag on `revoke`\n *\n * `revoke` reads the target's own `role` to decide whether the caller may\n * revoke them, so it cannot act on a file it will not trust — which left a\n * forged file removable only by editing the store by hand. Relaxing `revoke`\n * conditionally would grow the safe path a parameter that turns it into the\n * dangerous one; ADR 0003's standing rule is that if the implementation needs\n * to weaken a guard, the design is wrong. This is a separate operation with its\n * own contract, so `revoke`'s invariant stays absolute and the dangerous act is\n * named at the call site rather than hidden in an option bag.\n *\n * ## The two properties that keep it from being a backdoor\n *\n * 1. **It refuses a file that verifies.** Otherwise it would delete any keyring\n * while ignoring `canRevoke` — including an owner's, which `revoke` protects\n * unconditionally.\n * 2. **Because of (1) it can safely ignore the claimed `role` — and it must.**\n * `canRevoke` refuses any target whose role reads `owner`, so a store that\n * forged `\"role\":\"owner\"` onto its victim would otherwise make them\n * permanently unremovable. Consulting the forged field is exactly the\n * mistake this operation exists to avoid.\n *\n * Owner-only: the narrowest role that can always act, and quarantine\n * deliberately consumes NO field of the file it is removing.\n *\n * ## Why it rotates, and why the scope comes from the CALLER\n *\n * Deleting the file is not a revocation — the store may decline the delete, and\n * the member may already hold unwrapped DEKs. So this rotates, exactly as\n * `revoke` does. The scope is every collection the CALLER holds, not the\n * target's DEK map: that map is unauthenticated (#1115), so deriving the scope\n * from it would let the store choose which collections survive a quarantine.\n *\n * ⚠️ **That is the security-correct scope, and it is NOT free.** An earlier\n * draft of this comment called over-rotating \"the safe direction\"; a review\n * probe disproved it. Rotation re-keys `store.list(vault, <name>)` plus the\n * derived refs `rotateKeys` knows about, so a DEK slot whose ciphertext lives\n * under a *different* collection name — `_blob`, whose data sits in\n * `_blob_index`/`_blob_chunks`, and the `collection#tier` slots — is re-keyed\n * without its data being re-encrypted, and that data then fails to open. That\n * gap belongs to `rotateKeys` (it is reachable through an ordinary `revoke` of\n * a whole-vault grantee, with no quarantine involved) and is filed as #1122,\n * but a quarantine takes the maximal scope *unconditionally*, so it meets the\n * gap every time rather than occasionally. Until that is fixed, treat a\n * quarantine as an emergency operation with a real blast radius, and read\n * `needsRegrant` afterwards.\n */\nexport async function quarantineKeyring(\n store: NoydbStore,\n vault: string,\n callerKeyring: UnlockedKeyring,\n userId: string,\n): Promise<QuarantineResult> {\n if (callerKeyring.role !== 'owner') {\n throw new PermissionDeniedError(\n `Role \"${callerKeyring.role}\" cannot quarantine a keyring — quarantine is owner-only, ` +\n 'because it removes a file whose own authority claims cannot be trusted.',\n )\n }\n if (userId === callerKeyring.userId) {\n throw new ValidationError(\n 'quarantineKeyring: refusing to quarantine the calling keyring. Removing your own ' +\n 'keyring and rotating behind it would leave the vault with no reachable owner.',\n )\n }\n\n const rosterKey = requireRosterKey(callerKeyring, 'quarantineKeyring')\n const found = await readKeyringForAudit(store, vault, userId)\n if (!found) {\n // #1077's window, reached the same way: this deletes first and rotates\n // second with no transaction, so a store error in between leaves the file\n // gone and the keys un-rotated. Throwing not-found on the retry is what\n // makes that state dangerous — the operator reads it as \"already done\" and\n // stops, while the rotation never finished. An uncommitted rotation on the\n // caller's own keyring (`pending_deks`, #1074) is the evidence, so resume\n // it and make the retry idempotent instead of misleading. Same handling as\n // `revoke`; the remedy must not be \"call a different function\".\n const pending = [...(callerKeyring.pendingDeks?.keys() ?? [])]\n if (pending.length > 0) {\n const resumed = await rotateKeys(store, vault, callerKeyring, { collections: pending })\n return {\n userId,\n reason: 'roster-tag-mismatch',\n rotated: pending,\n needsRegrant: resumed.needsRegrant,\n alsoUnverified: resumed.unverified,\n }\n }\n throw new NoAccessError(`No keyring found for user \"${userId}\" in vault \"${vault}\"`)\n }\n\n let reason: KeyringTamperedReason | null = null\n if ('unparseable' in found) {\n reason = 'unparseable'\n } else {\n try {\n await assertRosterTagValid(found.file, rosterKey, userId)\n } catch (err) {\n if (!(err instanceof KeyringTamperedError)) throw err\n reason = err.details.reason\n }\n }\n if (reason === null) {\n throw new ValidationError(\n `quarantineKeyring: the keyring for \"${userId}\" authenticates correctly, so it is not a ` +\n 'quarantine case — use revoke() instead. Quarantine bypasses the role checks revoke ' +\n 'performs, so it is restricted to files that genuinely fail authentication.',\n )\n }\n\n await store.delete(vault, '_keyring', userId)\n await deleteUserEnvelope(store, vault, userId)\n await deleteUserVisibility(store, vault, userId)\n\n const rotated = [...callerKeyring.deks.keys()].filter((c) => c !== ROSTER_KEY_ID)\n const result = rotated.length > 0\n ? await rotateKeys(store, vault, callerKeyring, { collections: rotated })\n : { needsRegrant: [], unverified: [] }\n\n return {\n userId,\n reason,\n rotated,\n needsRegrant: result.needsRegrant,\n alsoUnverified: result.unverified,\n }\n}\n\n// ─── Update User ───────────────────────────────────────────────────────\n\n/**\n * Mutate `role`, `displayName`, and/or `permissions` on an existing\n * keyring. Pure plaintext-header rewrite — no DEK rewrap, no KEK\n * required, no authenticator slots touched. Tier-2 enrollments and\n * recovery codes survive the operation.\n *\n * Role-elevation guard: BOTH the old role AND the new role must\n * satisfy `canUpdateRole(callerRole, _)`. This blocks the two\n * privilege-escalation shapes:\n * - admin elevates someone (or themselves) to owner\n * - admin demotes an owner to a role they then control\n *\n * Owner is always allowed. Admin manages admin / operator / viewer /\n * client laterally.\n *\n * Identity preserved: same userId, same DEK wrappings. Last-write-wins\n * through the standard keyring put (same concurrency story as `grant`\n * and `revoke`).\n *\n * @throws `NoAccessError` when no keyring exists for the target.\n * @throws `PermissionDeniedError` when the role hierarchy rejects.\n * @throws `ValidationError` when the diff is empty (nothing to update).\n *\n */\nexport async function updateKeyringIdentity(\n store: NoydbStore,\n vault: string,\n callerKeyring: UnlockedKeyring,\n options: UpdateUserOptions,\n): Promise<void> {\n if (\n options.role === undefined &&\n options.displayName === undefined &&\n options.permissions === undefined\n ) {\n throw new ValidationError(\n `updateUser: at least one of role / displayName / permissions must be provided ` +\n `(userId: \"${options.userId}\").`,\n )\n }\n\n const found = await readKeyringFile(store, vault, options.userId)\n if (!found) {\n throw new NoAccessError(\n `updateUser: user \"${options.userId}\" has no keyring in vault \"${vault}\".`,\n )\n }\n const target = found.file\n\n // #1096 — verify BEFORE the guards below, not just before the restamp. The\n // role-elevation checks consume `target.role`, so a forged one does not only\n // get laundered into the output — it decides whether this edit is permitted\n // at all. Every field not named in `options` is also carried through the\n // spread, so an unverified read would authenticate forgeries nobody touched.\n const rosterKey = requireRosterKey(callerKeyring, 'updateKeyringIdentity')\n await assertRosterTagValid(target, rosterKey, options.userId)\n\n // Role-elevation guard. The OLD role must be one this caller is\n // allowed to manage, AND the NEW role (if changing) must be too.\n // Two-sided check: blocks admin→owner promotion (new side) and\n // demoting an owner (old side).\n if (!canUpdateRole(callerKeyring.role, target.role)) {\n throw new PermissionDeniedError(\n `Role \"${callerKeyring.role}\" cannot update a keyring with role \"${target.role}\"`,\n )\n }\n if (\n options.role !== undefined &&\n options.role !== target.role &&\n !canUpdateRole(callerKeyring.role, options.role)\n ) {\n throw new PermissionDeniedError(\n `Role \"${callerKeyring.role}\" cannot promote target to role \"${options.role}\"`,\n )\n }\n\n // This function exists to edit another member's AUTHORITY without holding\n // their credential, which is exactly the power a hostile store was helping\n // itself to. The caller's own roster key (verified against `target` above)\n // is what re-authenticates the result; the target's canary rides the spread\n // untouched.\n const edited: KeyringFile = {\n ...target,\n ...(options.role !== undefined && { role: options.role }),\n ...(options.displayName !== undefined && {\n // null clears the field (stored as \"\"); a string sets it.\n display_name: options.displayName ?? '',\n }),\n ...(options.permissions !== undefined && { permissions: options.permissions }),\n }\n const next: KeyringFile = { ...edited, roster_tag: await mintRosterTag(edited, rosterKey) }\n\n await writeKeyringFile(store, vault, options.userId, next)\n}\n\n// ─── Key Rotation ──────────────────────────────────────────────────────\n\n/**\n * Rotate DEKs for specified collections:\n * 1. Generate new DEKs\n * 2. Re-encrypt all records in affected collections\n * 3. Re-wrap new DEKs for all remaining users\n */\n/**\n * What a DEK rotation leaves behind (#854).\n *\n * A member's DEKs are wrapped under that member's KEK, and a KEK derives only\n * from that member's secret — so the caller cannot re-wrap a fresh DEK for\n * anyone else. That is the zero-knowledge property working as designed, but it\n * means rotation necessarily DROPS the rotated collections from every other\n * member's keyring rather than re-keying them.\n *\n * `needsRegrant` names exactly who lost what, so the caller can re-run\n * `grant()` instead of discovering the access loss later.\n */\nexport interface RotateResult {\n /** (member, collection) pairs whose access was dropped by the rotation. */\n readonly needsRegrant: ReadonlyArray<{ readonly userId: string; readonly collection: string }>\n /**\n * Members skipped because their `_keyring` file failed roster verification\n * (#1114).\n *\n * Rotation hands a member re-wrapped DEKs, so skipping one gives them\n * **less**, never more: the file is left untouched and its wrappings for the\n * rotated collections go stale. That is the same fail-closed end state as\n * `needsRegrant`, but it needs a different remedy and so gets a different\n * field — a `needsRegrant` entry is fixed by `grant()`, whereas one of these\n * is a file that no longer authenticates and cannot be repaired by granting\n * over it.\n *\n * Before this existed, one such file threw and took `revoke` and\n * `rotateKeys` down vault-wide — the two operations most needed when a\n * roster is suspect.\n */\n readonly unverified: ReadonlyArray<{\n readonly userId: string\n readonly reason: KeyringTamperedReason\n }>\n}\n\n/** Options for {@link rotateKeys} (#846b — was a bare `string[]`). */\nexport interface RotateKeysOptions {\n /** Collections whose DEKs are re-minted. */\n readonly collections: readonly string[]\n}\n\n/**\n * Collections whose envelopes are sealed under **another** collection's DEK\n * (#1108).\n *\n * ## The defect this closes\n *\n * `rotateKeys` re-keys by collection NAME, which silently assumes DEK-name and\n * collection-name are 1:1. They are not. A history snapshot lives in\n * `_history` but is sealed under its **source** collection's DEK, and\n * `_ledger_deltas` is sealed under the `_ledger` DEK. So a revocation rotated\n * the live records and left their prior versions readable under the key the\n * revoked member walked away with — for a history-enabled collection, that is\n * substantially its whole content.\n *\n * Measured before the fix: a revoked member's retained `docs` DEK opened the\n * live record (no) and `_history/docs:d1:…` (YES).\n *\n * ## Why the layouts are duplicated here rather than imported\n *\n * `with-party` has never imported `with-commit` or `with-shape` and this is not\n * the change that should start — `with-shape/blobs/blob-set.ts` already imports\n * `with-party/team/tiers.js`, so the reverse edge would close a cycle. The id\n * layouts below are copied deliberately, with their owners named, and the\n * **invariant test is what keeps them honest**: after a revocation, no retained\n * key may open any envelope. That test does not consult this table, so a\n * service that adds a further such surface fails there rather than passing\n * quietly here.\n *\n * ## The blob surfaces (#1122)\n *\n * `_blob` was the same defect one layer worse: the slot is `_blob` and every\n * byte it protects is filed under `_blob_index` / `_blob_chunks`, so rotating\n * it re-encrypted NOTHING and made the vault's blobs permanently unreadable —\n * reachable through an ordinary `revoke`, since a whole-vault grantee holds\n * `_blob`. Those two are not in this table because they cannot be re-keyed by\n * the generic per-envelope helper (chunks use a bespoke AAD, and the index body\n * carries wrapped per-blob CEKs); {@link rekeyBlobSet} handles them and\n * `rotateKeys` calls it for the `_blob` slot.\n *\n * What IS in this table is the other half: the three per-collection blob\n * surfaces sealed under the OWNING collection's DEK rather than under `_blob`.\n */\nconst HISTORY_COLLECTION = '_history' // owner: with-commit/history/history.ts\nconst LEDGER_COLLECTION = '_ledger' // owner: with-commit/history/ledger/constants.ts\nconst LEDGER_DELTAS_COLLECTION = '_ledger_deltas' // ditto\nconst BLOB_COLLECTION = '_blob' // owner: with-shape/blobs/blob-set.ts\nconst BLOB_SLOTS_PREFIX = '_blob_slots_' // ditto — `_blob_slots_<collection>`\nconst BLOB_VERSIONS_PREFIX = '_blob_versions_' // ditto — `_blob_versions_<collection>`\nconst BLOB_INTENT_COLLECTION = '_blob_intent' // owner: with-shape/blobs/blob-intent.ts\n\n/** `store.list` on a collection that may not exist yet. */\nasync function listOrEmpty(store: NoydbStore, vault: string, collection: string): Promise<string[]> {\n try { return await store.list(vault, collection) } catch { return [] }\n}\n\n/**\n * Envelopes sealed under `rotated`'s DEK but stored under a different\n * collection — the refs {@link rotateKeys} must re-key alongside the collection\n * itself.\n */\nasync function derivedRefsFor(\n store: NoydbStore,\n vault: string,\n rotated: string,\n): Promise<Array<{ collection: string; id: string }>> {\n const out: Array<{ collection: string; id: string }> = []\n\n // `_history` snapshot ids are `${collection}:${recordId}:${paddedVersion}`,\n // and each is sealed under `${collection}`'s DEK. Reserved collections have\n // no history of their own, so only user collections contribute.\n if (!rotated.startsWith('_')) {\n for (const id of await listOrEmpty(store, vault, HISTORY_COLLECTION)) {\n if (id.startsWith(`${rotated}:`)) out.push({ collection: HISTORY_COLLECTION, id })\n }\n }\n\n // Every `_ledger_deltas` entry is sealed under the `_ledger` DEK.\n if (rotated === LEDGER_COLLECTION) {\n for (const id of await listOrEmpty(store, vault, LEDGER_DELTAS_COLLECTION)) {\n out.push({ collection: LEDGER_DELTAS_COLLECTION, id })\n }\n }\n\n // #1122 — the per-collection blob surfaces. A slot map and a version record\n // are sealed under the OWNING collection's DEK (`dekKey(collection, tier)`),\n // not under `_blob`, and a `_blob_intent` marker under that collection's\n // tier-0 DEK. All three use the ordinary record AAD, so the generic\n // per-envelope helper re-keys them; only `_blob_index`/`_blob_chunks` need\n // `rekeyBlobSet`. Reserved collections own none of these.\n if (!rotated.startsWith('_')) {\n for (const id of await listOrEmpty(store, vault, `${BLOB_SLOTS_PREFIX}${rotated}`)) {\n out.push({ collection: `${BLOB_SLOTS_PREFIX}${rotated}`, id })\n }\n for (const id of await listOrEmpty(store, vault, `${BLOB_VERSIONS_PREFIX}${rotated}`)) {\n out.push({ collection: `${BLOB_VERSIONS_PREFIX}${rotated}`, id })\n }\n // Marker ids are `${collection}::${recordId}` — the `::` separator is\n // refused in record ids at the blob write surface, so the prefix is\n // unambiguous.\n for (const id of await listOrEmpty(store, vault, BLOB_INTENT_COLLECTION)) {\n if (id.startsWith(`${rotated}::`)) out.push({ collection: BLOB_INTENT_COLLECTION, id })\n }\n }\n\n return out\n}\n\nexport async function rotateKeys(\n store: NoydbStore,\n vault: string,\n callerKeyring: UnlockedKeyring,\n opts: RotateKeysOptions,\n): Promise<RotateResult> {\n // #1096 — the roster key is NOT rotatable, and this refusal is load-bearing.\n //\n // Rotating it would mint a fresh roster key for the caller and then DROP the\n // entry from every other member's file (rotation cannot re-wrap for a member\n // whose KEK it cannot derive) — so the next `loadKeyring` for every remaining\n // member would throw `roster-key-missing` and the whole vault would be\n // unopenable. It also buys nothing: the roster tag defends against the STORE,\n // which never holds a key, and explicitly not against a member who has\n // already walked away with one.\n //\n // THROWN, not silently dropped. `revoke` — the one caller that could pass it\n // implicitly, since it derives its set from `Object.keys(target.deks)` —\n // filters it out at source instead. So anything arriving here named it, and\n // a caller that asks to rotate the roster key has a mistaken model of what\n // rotation does; swallowing that would hide the mistake rather than fix it.\n const { collections } = opts\n if (collections.includes(ROSTER_KEY_ID)) {\n throw new ValidationError(\n `rotateKeys: \"${ROSTER_KEY_ID}\" is the vault roster key, not a collection, and cannot be ` +\n 'rotated — doing so would strip it from every other member and leave the vault unopenable. ' +\n 'Remove it from `collections`.',\n )\n }\n // FR-6: re-keying is an owner-only meta-capability. A custodian operates the\n // vault fully but must NOT rotate — rotation would let it mint fresh DEKs and\n // strip the sealed owner's access, breaking the inalienability floor.\n if (callerKeyring.role === 'custodian') {\n throw new PermissionDeniedError(\n 'custodian cannot rotate keys (FR-6: re-key is an owner-only meta-capability; use the Deed owner)',\n )\n }\n const callerRosterKey = requireRosterKey(callerKeyring, 'rotateKeys')\n // Generate new DEKs for each affected collection\n // #1074 part 2 — RESUME. A pending DEK means a previous rotation of this\n // collection was interrupted after persisting its key but before committing.\n // Reuse it: minting a fresh one would strand every record the interrupted run\n // already moved, since nothing would hold the key they were sealed under.\n //\n // This is what makes `rotateKeys` its own resume path — re-running it after a\n // crash finishes the job rather than starting a second, incompatible one.\n const newDeks = new Map<string, EnclaveKey>()\n for (const collName of collections) {\n newDeks.set(collName, callerKeyring.pendingDeks?.get(collName) ?? await generateDEK())\n }\n\n // Persist the new DEKs BEFORE rewriting a single record. This is the whole\n // fix: previously the key existed only in memory until after the loop, so any\n // interruption left already-rewritten records sealed under a key that was\n // never saved — permanently unreadable, not merely un-migrated.\n //\n // `deks` still holds the OLD key here, so reads during the window continue to\n // work for records the loop has not reached. Records it HAS reached are\n // unreadable until the rotation is resumed — degraded, but recoverable, which\n // is the property that was missing.\n // `pendingDeks` is optional on the public `UnlockedKeyring` — absent simply\n // means no rotation is in flight — so materialise it on first use rather than\n // forcing every constructor of the type to write an empty map.\n const pending = callerKeyring.pendingDeks ?? new Map<string, EnclaveKey>()\n ;(callerKeyring as { pendingDeks?: Map<string, EnclaveKey> }).pendingDeks = pending\n for (const [collName, newDek] of newDeks) {\n pending.set(collName, newDek)\n }\n await persistKeyring(store, vault, callerKeyring)\n\n // Re-encrypt all records in affected collections\n //\n // FORWARD REQUIREMENT (not implemented here — DEK rotation predates\n // perRecordKeys/classified fields): a future perRecordKeys-aware DEK\n // rotation MUST DROP `_bidx` here rather than carry it forward. `_bidx` is\n // rooted in the (soon-to-be-dead) old DEK; a stale tag surviving under the\n // new DEK is unreturnable garbage (no key can ever re-derive it to match a\n // query again) that still LEAKS the old equality partition. Unlike\n // `rotateRecordCek` (record-keys/sealing.ts), which carries `_bidx`\n // verbatim because it is CEK-rotation-only and the DEK is unchanged, a DEK\n // rotation changes the root the tag is derived from, so index coverage can\n // only regrow per-record, the next time each record is `put()` under the\n // new DEK.\n //\n // #1074 — CRASH-SAFETY HAZARD, still open, and the scope is GENERAL.\n //\n // This was previously filed as D-5 and described narrowly: \"in a mixed\n // collection, if a later record throws\". That framing understated it and is\n // why it sat. The hazard applies to ANY interruption of this loop — a thrown\n // error, a process kill, a lost connection — because the new DEK exists only\n // in memory until `persistKeyring` runs AFTER every record is rewritten.\n // Interrupt it and the already-rewritten records are sealed under a DEK that\n // was never persisted: permanently unreadable, not merely un-migrated.\n //\n // Fixed separately (see #1074): the new DEK must be persisted BEFORE the loop\n // so a resume can find it. Doing that needs the keyring to hold two\n // generations transiently, so it is its own change rather than part of this\n // one. What IS fixed here is everything the loop does to a record it reaches.\n for (const collName of collections) {\n const oldDek = callerKeyring.deks.get(collName)\n const newDek = newDeks.get(collName)!\n if (!oldDek) continue\n\n // #1122 — `_blob` protects data filed under NO collection of its own.\n // Its ciphertext lives in `_blob_index` and `_blob_chunks`, in shapes the\n // per-envelope helper below cannot open (a bespoke chunk AAD, and wrapped\n // per-blob CEKs inside the index body), so it gets its own enclave routine.\n // Before this, rotating `_blob` minted a key, re-encrypted nothing, and\n // destroyed every blob in the vault — through an ordinary `revoke`.\n //\n // Tier slots too: an elevated record's blob metadata is sealed under\n // `dekKey('_blob', tier)` — `_blob#<tier>` — and filed in that same\n // `_blob_index`, so membership there is by DEK, not by name. The other keys\n // the caller holds are passed so an entry belonging to a DIFFERENT blob\n // slot is recognised as that slot's business rather than mistaken for a\n // damaged record; an entry no held key opens is genuinely damaged and\n // throws, as `rekeyEnvelopeIfNeeded` does.\n if (collName === BLOB_COLLECTION || collName.startsWith(`${BLOB_COLLECTION}#`)) {\n const others: EnclaveKey[] = []\n for (const [name, dek] of callerKeyring.deks) if (name !== collName) others.push(dek)\n for (const [name, dek] of newDeks) if (name !== collName) others.push(dek)\n await rekeyBlobSet(store, vault, oldDek, newDek, others)\n }\n\n // The collection's own records, PLUS every envelope sealed under this DEK\n // but filed elsewhere (#1108). Both go through the same helper, so the\n // resume property holds for derived surfaces too: `rekeyEnvelopeIfNeeded`\n // returns null for anything already under `newDek`.\n const refs: Array<{ collection: string; id: string }> = [\n ...(await store.list(vault, collName)).map((id) => ({ collection: collName, id })),\n ...(await derivedRefsFor(store, vault, collName)),\n ]\n for (const ref of refs) {\n const { collection: refColl, id } = ref\n const envelope = await store.get(vault, refColl, id)\n if (!envelope || !envelope._iv) continue\n\n // #1074 — one enclave helper does the whole per-record rotation:\n // carries every slot except `_bidx`, and re-wraps a per-record CEK\n // instead of trying to decrypt its body under the DEK. Both were wrong\n // inline here, and `enclave-body-only` is why they moved — envelope\n // surgery belongs in the enclave, where the guard can see it.\n // Returns null when this record is already under `newDek` — the\n // resumed-rotation case. A record readable under NEITHER key rethrows\n // rather than being skipped: walking silently past unreadable records\n // would turn a loud failure into permanent quiet loss.\n const newEnvelope = await rekeyEnvelopeIfNeeded({ collection: refColl, id }, envelope, oldDek, newDek)\n if (newEnvelope !== null) await store.put(vault, refColl, id, newEnvelope)\n }\n }\n\n // COMMIT (#1074 part 2). Every record is now under the new key, so promote\n // it and clear the pending marker. A keyring that still carries `pending_deks`\n // after this point means the rotation did not reach here.\n for (const [collName, newDek] of newDeks) {\n callerKeyring.deks.set(collName, newDek)\n callerKeyring.pendingDeks?.delete(collName)\n }\n await persistKeyring(store, vault, callerKeyring)\n\n // Drop the rotated collections from every OTHER member's keyring.\n //\n // The old comment here said these were \"re-wrapped\", which is what\n // `Noydb.rotate`'s jsdoc promised too — but re-wrapping is impossible and\n // always was (#854). See the note below.\n const needsRegrant: Array<{ userId: string; collection: string }> = []\n const unverified: Array<{ userId: string; reason: KeyringTamperedReason }> = []\n const userIds = await store.list(vault, '_keyring')\n for (const userId of userIds) {\n if (userId === callerKeyring.userId) continue\n\n const userFound = await readKeyringFile(store, vault, userId)\n if (!userFound) continue\n\n const userKeyringFile = userFound.file\n // #1096 — VERIFY BEFORE RESTAMPING. This loop edits and re-signs a file it\n // read from an untrusted store, so without this it would take a forged\n // roster that `loadKeyring` refuses and hand it back a GENUINE tag. And\n // `revoke` calls this unconditionally, so one forged member plus any later\n // revocation anywhere in the vault would be a complete bypass.\n //\n // #1114 — SKIP the member rather than failing the rotation. Throwing here\n // meant one bad file froze `revoke` and `rotateKeys` for the whole vault,\n // including the revoke that would have removed it. Skipping is safe\n // precisely HERE, and the reason is directional: this loop's effect on a\n // member is to hand them re-wrapped DEKs, so declining to process one gives\n // them LESS. Their file is not restamped (nothing laundered) and not\n // re-wrapped (no new key), leaving the same fail-closed end state rotation\n // already produces for a member it cannot re-wrap for (#854).\n //\n // Only the tamper verdict is caught. Any other failure is still fatal —\n // \"skip on error\" would quietly convert a bug into a silent no-rotation,\n // which is the shape of defect this subsystem keeps finding.\n try {\n await assertRosterTagValid(userKeyringFile, callerRosterKey, userId)\n } catch (err) {\n if (!(err instanceof KeyringTamperedError)) throw err\n unverified.push({ userId, reason: err.details.reason })\n continue\n }\n // A user's DEKs are wrapped with that user's KEK, and a KEK derives only\n // from the user's secret — the caller can never derive another user's\n // KEK, so re-wrapping the new DEKs for them is impossible. Rotation\n // therefore REMOVES the rotated collections' DEK entries (and permissions)\n // from each remaining user's keyring: secure (revoked keys are gone) but\n // the owner must re-run grant() for those users/collections.\n\n const updatedDeks = { ...userKeyringFile.deks }\n const updatedPermissions = { ...userKeyringFile.permissions }\n for (const collName of collections) {\n // Report only what the member actually held — a user who never had the\n // collection does not \"need a re-grant\".\n if (collName in updatedDeks || collName in updatedPermissions) {\n needsRegrant.push({ userId, collection: collName })\n }\n delete updatedDeks[collName]\n delete updatedPermissions[collName]\n }\n\n // #1096 — `permissions` is an authority field, so narrowing it here\n // invalidates the member's existing roster tag. Restamp with the caller's\n // roster key (same key: it is vault-wide).\n const edited: KeyringFile = {\n ...userKeyringFile,\n deks: updatedDeks,\n permissions: updatedPermissions,\n }\n const updatedKeyring: KeyringFile = {\n ...edited,\n roster_tag: await mintRosterTag(edited, callerRosterKey),\n }\n\n await writeKeyringFile(store, vault, userId, updatedKeyring)\n }\n\n return { needsRegrant, unverified }\n}\n\n// ─── Change Secret ─────────────────────────────────────────────────────\n\n/** Options for {@link changeSecret} (#846b). */\nexport interface ChangeSecretOptions extends SecretPolicy {\n /** The replacement secret. */\n readonly newSecret: string\n /** Escape hatch for fixtures and migrations — skips the strength gate. */\n readonly allowWeakSecret?: boolean\n}\n\n/**\n * Change the user's secret. Re-wraps every DEK under the new KEK.\n *\n * Validates the new secret against the strength rules unless\n * `allowWeakSecret: true` is passed. Mirrors `rotateSecret`'s\n * default-on validation contract.\n *\n * `db.team.rotateSecret()` adds a `checkGate('rotate-secret')` step\n * on top of this primitive and additionally requires the OLD secret\n * for re-derivation; `changeSecret` reuses the cached unlocked KEK so\n * the OLD secret is not retyped.\n */\nexport async function changeSecret(\n store: NoydbStore,\n vault: string,\n keyring: UnlockedKeyring,\n opts: ChangeSecretOptions,\n): Promise<UnlockedKeyring> {\n // An echo keyring rotates via `rotateSecret` only — `changeSecret`\n // rebuilds the keyring file literal below and would silently DROP the\n // `echo` block, permanently losing the ceremony. Guard on the file as\n // persisted (not `keyring`, which carries no echo info) before any\n // derivation.\n const existingFound = await readKeyringFile(store, vault, keyring.userId)\n // #1096 — verified before ANY of it is consumed: the echo guard below steers\n // on it, and the carry-forward further down re-signs it.\n if (existingFound) {\n await assertRosterTagValid(existingFound.file, requireRosterKey(keyring, 'changeSecret'), keyring.userId)\n }\n if (existingFound && existingFound.file.echo !== undefined) throw new EchoCeremonyRequiredError()\n\n const { newSecret } = opts\n if (!opts.allowWeakSecret) {\n assertStrongSecret(newSecret, opts)\n }\n const newSalt = generateSalt()\n const newKek = await deriveKey(newSecret, newSalt)\n\n // Re-wrap all DEKs with the new KEK\n const wrappedDeks: Record<string, string> = {}\n for (const [collName, dek] of keyring.deks) {\n wrappedDeks[collName] = await wrapKey(dek, newKek)\n }\n\n // #1096 — the roster key is one of `keyring.deks`, so it was re-wrapped\n // under the new KEK by the loop above and travels with the secret change.\n const rosterKey = requireRosterKey(keyring, 'changeSecret')\n const canary = await mintKeyringCanary(newKek)\n // Carry the ORIGIN + capability fields forward, exactly as `persistKeyring`\n // does. `UnlockedKeyring` carries none of them, so rebuilding the file from\n // it re-parented `granted_by` to the holder themselves — collapsing the admin\n // delegation subtree — and silently dropped a time-boxed grant and both\n // capability bits. #1096 turns each of those from a quiet erasure into an\n // AUTHENTICATED one, since the tag below now signs whatever is left.\n const existingAuthority = existingFound?.file\n const keptGrantedBy = existingAuthority?.granted_by ?? keyring.userId\n const authority = {\n user_id: keyring.userId,\n display_name: keyring.displayName,\n role: keyring.role,\n permissions: keyring.permissions,\n granted_by: keptGrantedBy,\n ...(existingAuthority?.expires_at !== undefined && { expires_at: existingAuthority.expires_at }),\n ...(existingAuthority?.export_capability !== undefined && { export_capability: existingAuthority.export_capability }),\n ...(existingAuthority?.import_capability !== undefined && { import_capability: existingAuthority.import_capability }),\n }\n const keyringFile: KeyringFile = {\n _noydb_keyring: NOYDB_KEYRING_VERSION,\n ...authority,\n deks: wrappedDeks,\n salt: bufferToBase64(newSalt),\n created_at: new Date().toISOString(),\n canary,\n roster_tag: await mintRosterTag(authority, rosterKey),\n }\n\n await writeKeyringFile(store, vault, keyring.userId, keyringFile)\n\n return {\n userId: keyring.userId,\n displayName: keyring.displayName,\n role: keyring.role,\n permissions: keyring.permissions,\n deks: keyring.deks, // Same DEKs, different wrapping\n kek: newKek,\n salt: newSalt,\n // Tier-2 slots are NOT preserved through `changeSecret` —\n // each slot wraps the OLD KEK, so the new keyring has no\n // authenticator slots until the user re-enrolls. The higher-level\n // `db.team.rotateSecret()` preserves slots by rewrapping the\n // KEK reference, not the KEK itself.\n authenticators: [],\n ...(keyring.policy !== undefined && { policy: keyring.policy }),\n }\n}\n\n// ─── Bundle recipients ──────────────────────────────────────────\n\n/**\n * Echo-mode recipient secret (spec #940). A pod slot may embed the reveal\n * (`'portable'`, default) or omit it (`'none'`) — `'sealed'` is\n * live-device-only and unavailable here: `writePod` has no device context\n * to seal the reveal blob against.\n */\nexport interface EchoRecipientSecret extends EchoSecretParts {\n readonly reveal?: 'portable' | 'none'\n}\n\n/**\n * Recipient slot in a re-keyed `.noydb` bundle. Each slot becomes its\n * own keyring file inside the bundle, sealed with its own secret.\n * Same role/permission semantics as `db.grant()` but no store side\n * effect — the slot only exists inside the bundle bytes.\n *\n * @public\n */\nexport interface PodRecipient {\n /** User id stamped onto the keyring file in the bundle. */\n readonly id: string\n /** Optional display name. Defaults to `id`. */\n readonly displayName?: string\n /**\n * Secret the recipient will type to unlock — a plain string for a\n * standard keyring, or the structured 3-part {@link EchoRecipientSecret}\n * to embed an echo keyring so the anti-phishing ceremony travels with\n * the pod (spec #940).\n */\n readonly secret: string | EchoRecipientSecret\n /** Role on the destination vault. Defaults to `'viewer'`. */\n readonly role?: Role\n /**\n * Per-collection permissions. When omitted, role defaults apply.\n * Restricting permissions here ALSO restricts which DEKs are wrapped\n * into the slot — a slot with `{ invoices: 'ro' }` cannot decrypt\n * other collections even though their ciphertext sits in the bundle.\n */\n readonly permissions?: Permissions\n /**\n * Optional `as-*` export grants on the destination vault.\n * Mirrors the `exportCapability` field on a live keyring.\n */\n readonly exportCapability?: ExportCapability\n /**\n * Optional `as-*` import grants on the destination vault.\n * Mirrors the `importCapability` field on a live keyring.\n * Default-closed: no plaintext format granted, no bundle import.\n */\n readonly importCapability?: ImportCapability\n /**\n * Optional bundle-slot expiry. ISO-8601 timestamp; past the\n * cutoff this slot's keyring refuses to load with\n * `KeyringExpiredError`. Time-boxed audit access pattern: \"this\n * slot works for 30 days then becomes opaque to its holder.\"\n */\n readonly expiresAt?: string\n}\n\n/**\n * Build a `KeyringFile` for one bundle recipient, given the source\n * vault's unwrapped DEKs. Mirrors `grant()` minus the store write —\n * the produced file is meant to be embedded in the bundle's\n * `keyrings` map, never persisted to the source vault.\n *\n * Privilege-escalation check still runs: every DEK wrapped into the\n * recipient's keyring must come from the source's own DEK set.\n *\n * @internal\n */\nexport async function buildRecipientKeyringFile(\n callerKeyring: UnlockedKeyring,\n recipient: PodRecipient,\n): Promise<KeyringFile> {\n if (!callerKeyring.kek) {\n throw new ValidationError(\n 'buildRecipientKeyringFile: caller keyring has no KEK — tier-2 wrap-DEKs ' +\n 'and tier-3 PIN-resume sessions cannot create bundle recipients. ' +\n 'Re-authenticate at tier 1 (secret) before building a bundle.',\n )\n }\n const rosterKey = requireRosterKey(callerKeyring, 'buildRecipientKeyringFile')\n\n const role: Role = recipient.role ?? 'viewer'\n const permissions = resolvePermissions(role, recipient.permissions)\n\n const newSalt = generateSalt()\n const newKek = typeof recipient.secret === 'string'\n ? await deriveKey(recipient.secret, newSalt)\n : await deriveEchoKey(recipient.secret, newSalt)\n\n const wrappedDeks: Record<string, string> = {}\n\n // Collections the recipient was explicitly granted permission to.\n for (const collName of Object.keys(permissions)) {\n const dek = callerKeyring.deks.get(collName)\n if (dek) {\n wrappedDeks[collName] = await wrapKey(dek, newKek)\n }\n }\n\n // owner / admin / custodian / viewer: wrap every known DEK (matches grant).\n // FR-6: a custodian recipient operates every collection, so it receives all\n // DEKs just like admin (kept in lockstep with grant()'s all-DEKs branch).\n if (role === 'owner' || role === 'admin' || role === 'custodian' || role === 'viewer') {\n for (const [collName, dek] of callerKeyring.deks) {\n if (!(collName in wrappedDeks)) {\n wrappedDeks[collName] = await wrapKey(dek, newKek)\n }\n }\n }\n\n // Always propagate system-prefixed collection DEKs (`_ledger`, etc.) —\n // the recipient needs them to verify the bundle on import.\n for (const [collName, dek] of callerKeyring.deks) {\n if (collName.startsWith('_') && !(collName in wrappedDeks)) {\n wrappedDeks[collName] = await wrapKey(dek, newKek)\n }\n }\n\n // Anti-privilege-escalation: every wrapped DEK must come from the\n // caller's own DEK set. Belt-and-braces with the lookups above.\n for (const collName of Object.keys(wrappedDeks)) {\n if (!callerKeyring.deks.has(collName)) {\n throw new PrivilegeEscalationError(collName)\n }\n }\n\n const canary = await mintKeyringCanary(newKek)\n const authority = {\n user_id: recipient.id,\n display_name: recipient.displayName ?? recipient.id,\n role,\n permissions,\n granted_by: callerKeyring.userId,\n ...(recipient.exportCapability !== undefined\n ? { export_capability: recipient.exportCapability }\n : {}),\n ...(recipient.importCapability !== undefined\n ? { import_capability: recipient.importCapability }\n : {}),\n ...(recipient.expiresAt !== undefined\n ? { expires_at: recipient.expiresAt }\n : {}),\n }\n return {\n _noydb_keyring: NOYDB_KEYRING_VERSION,\n ...authority,\n deks: wrappedDeks,\n salt: bufferToBase64(newSalt),\n created_at: new Date().toISOString(),\n canary,\n // The recipient's copy of the roster key rode in via the `_`-prefix\n // propagation loop above, so the slot verifies on first unlock.\n roster_tag: await mintRosterTag(authority, rosterKey),\n // The presence of this block is what makes the recipient's slot an\n // echo keyring — mirrors `createOwnerKeyring`'s same dance so the\n // ceremony (prompt → echo → key) travels with the pod, not just a\n // live owner keyring.\n ...(typeof recipient.secret !== 'string'\n ? { echo: await buildEchoBlock(recipient.secret, { kind: recipient.secret.reveal ?? 'portable' }) }\n : {}),\n }\n}\n\n// ─── List Users ────────────────────────────────────────────────────────\n\n/** List all users with access to a vault. */\nexport async function listUsers(\n store: NoydbStore,\n vault: string,\n): Promise<UserInfo[]> {\n // #1096 — DELIBERATELY UNVERIFIED. `role` and `permissions` below come\n // straight from the plaintext header, so a hostile store can misreport them\n // in a directory listing. Not verified because this is a display surface with\n // no caller keyring in scope, and every ENFORCEMENT path (loadKeyring, grant,\n // revoke, updateUser, recover, tier-2 unlock) verifies independently. If this\n // output ever feeds an authorisation decision, that stops being true.\n const userIds = await store.list(vault, '_keyring')\n const users: UserInfo[] = []\n\n for (const userId of userIds) {\n const found = await readKeyringFile(store, vault, userId)\n if (!found) continue\n const kf = found.file\n users.push({\n userId: kf.user_id,\n displayName: kf.display_name,\n role: kf.role,\n permissions: kf.permissions,\n createdAt: kf.created_at,\n grantedBy: kf.granted_by,\n })\n }\n\n return users\n}\n\n/**\n * Optional filter knobs for {@link listUsersWithEnvelopes}.\n *\n * - `includeHidden` — when true, principals with `_meta/visibility/<id>`\n * set to `{ hidden: true }` are returned alongside everyone else.\n * Requires `owner` or `admin` callerRole; lower roles get\n * {@link import('../../kernel/errors.js').PermissionDeniedError}.\n */\nexport interface ListUsersOptions {\n readonly includeHidden?: boolean\n}\n\n/**\n * Joined enumeration: every keyring + its `_users/<keyringId>`\n * envelope side by side. Convenience for admin UIs that want to\n * render team-member lists with profile data (\"Bob — operator —\n * 'Bob the Auditor' avatar X locale fr-FR\") in a single pass.\n *\n * `userEnvelopeDek` is the vault's `_users` collection DEK\n * (`vault.getDEK('_users')`); used to decrypt every envelope.\n *\n * `callerRole` drives the directory-visibility checks:\n *\n * - When the vault's `_meta/directory` document has `enabled: false`,\n * only `owner` and `admin` callers may enumerate; anyone else gets\n * {@link import('../../kernel/errors.js').DirectoryDisabledError}.\n * - Principals with `_meta/visibility/<id>` set to `{ hidden: true }`\n * are filtered out by default. `owner`/`admin` callers can pass\n * `{ includeHidden: true }` to see them; lower roles passing that\n * option get `PermissionDeniedError`.\n *\n * Honest caveat: these filters are a UX hint, not a security\n * boundary. The keyring file is still listed at `_keyring/*` and the\n * envelope ciphertext at `_users/*`. A caller with direct store access\n * — or a caller that calls this function with `callerRole: 'owner'`\n * unconditionally — sees every principal. The protection is only as\n * strong as the role the calling layer passes in. The hub-level wrapper\n * on `Vault` sources `callerRole` from the unlocked keyring's `role`\n * field, which is signed-by-construction (it lives in the user's own\n * keyring file). See `https://github.com/vLannaAi/noy-db-docs/blob/main/content/docs/services/user-envelope.md` →\n * \"Directory visibility\".\n *\n * Principals without a persisted envelope (legacy keyrings predating\n * the user-envelope feature) come back with `envelope: null`. The\n * caller chooses how to render — usually \"fall back to keyring's\n * `displayName`\".\n *\n * Order matches `listUsers()` (store-defined; sort if you need a\n * stable display order).\n */\nexport async function listUsersWithEnvelopes<T = unknown>(\n store: NoydbStore,\n vault: string,\n userEnvelopeDek: EnclaveKey,\n callerRole: Role,\n options: ListUsersOptions = {},\n): Promise<Array<{ user: UserInfo; envelope: UserEnvelope<T> | null }>> {\n // FR-6: custodian is INTENTIONALLY treated as NON-privileged here (SAFER\n // default — review flag). Directory-privilege is a team-MANAGEMENT capability\n // (bypassing the visibility toggle + listing hidden principals); a custodian\n // is non-owning and cannot grant/revoke, so it should not see the hidden\n // team membership. It still gets the normal (non-hidden) directory view.\n // #1096 — DELIBERATELY UNVERIFIED. `role` and `permissions` below come\n // straight from the plaintext header, so a hostile store can misreport them\n // in a directory listing. Not verified because this is a display surface with\n // no caller keyring in scope, and every ENFORCEMENT path (loadKeyring, grant,\n // revoke, updateUser, recover, tier-2 unlock) verifies independently. If this\n // output ever feeds an authorisation decision, that stops being true.\n const isPrivileged = callerRole === 'owner' || callerRole === 'admin'\n\n // 1. Vault-level directory toggle.\n const dirConfig = await readDirectoryConfig(store, vault)\n if (dirConfig?.enabled === false && !isPrivileged) {\n throw new DirectoryDisabledError(vault)\n }\n\n // 2. `includeHidden` requires admin/owner.\n if (options.includeHidden && !isPrivileged) {\n throw new PermissionDeniedError(\n 'Permission denied — listUsersWithEnvelopes({ includeHidden: true }) requires owner or admin role',\n )\n }\n\n const users = await listUsers(store, vault)\n const out: Array<{ user: UserInfo; envelope: UserEnvelope<T> | null }> = []\n for (const user of users) {\n if (!options.includeHidden) {\n const visibility = await readUserVisibility(store, vault, user.userId)\n if (visibility?.hidden) continue\n }\n const envelope = await loadUserEnvelopeFn<T>(\n store,\n vault,\n user.userId,\n userEnvelopeDek,\n )\n out.push({ user, envelope })\n }\n return out\n}\n\n\n// ─── DEK Management ────────────────────────────────────────────────────\n\n/** Ensure a DEK exists for a collection. Generates one if new. */\n/**\n * Does this collection already hold persisted records?\n *\n * The one question that separates \"I am creating this collection\" from \"I was\n * never given the key to this collection\" (#1004). Kept deliberately narrow:\n * it asks the store, not the schema registry, because the store is the only\n * authority on what ciphertext actually exists.\n */\nasync function collectionHasRecords(\n store: NoydbStore,\n vault: string,\n collectionName: string,\n): Promise<boolean> {\n const ids = await store.list(vault, collectionName)\n return ids.length > 0\n}\n\n/**\n * Re-read this principal's persisted keyring and adopt the DEK for one\n * collection if it has appeared there since this handle unlocked (#1010).\n *\n * Returns the DEK (also caching it into `keyring.deks`) or `null` when the\n * persisted keyring genuinely does not carry it. Only ever called on the\n * miss path, so an up-to-date handle never pays for it.\n *\n * @internal\n */\nasync function reloadPersistedDEK(\n store: NoydbStore,\n vault: string,\n keyring: UnlockedKeyring,\n collectionName: string,\n): Promise<EnclaveKey | null> {\n if (!keyring.kek) return null\n const found = await readKeyringFile(store, vault, keyring.userId)\n const wrapped = found?.file.deks[collectionName]\n if (wrapped === undefined) return null\n try {\n const dek = await unwrapKey(wrapped, keyring.kek)\n keyring.deks.set(collectionName, dek)\n return dek\n } catch {\n // A DEK that will not unwrap under this KEK is corruption, not access —\n // fall through to the caller's denial rather than masking it as success.\n return null\n }\n}\n\nexport async function ensureCollectionDEK(\n store: NoydbStore,\n vault: string,\n keyring: UnlockedKeyring,\n): Promise<(collectionName: string) => Promise<EnclaveKey>> {\n // Dedupe concurrent first-time DEK creates per collection. Without\n // this, two concurrent `getDEK('foo')` calls both pass the `existing`\n // check (the Map is empty), both generate fresh DEKs, and the second\n // `set` overwrites the first — making any envelope encrypted with\n // the discarded DEK fail to decrypt later (TamperedError on read).\n // Pre-existing race exposed by the multi-writer ledger work.\n const inFlight = new Map<string, Promise<EnclaveKey>>()\n return async (collectionName: string): Promise<EnclaveKey> => {\n const existing = keyring.deks.get(collectionName)\n if (existing) return existing\n const pending = inFlight.get(collectionName)\n if (pending) return pending\n\n const promise = (async () => {\n // #1004 — minting on a DEK miss is only correct when the caller is\n // ENTITLED to the collection (they are creating it, or they were granted\n // it and it did not exist at grant time). For an unentitled caller the\n // miss IS the denial, and minting fabricated a key that decrypts none of\n // the stored envelopes — so the denial re-emerged from the enclave as an\n // AES-GCM tag failure, i.e. `TamperedError`, the signal reserved for\n // genuine ciphertext corruption. In a zero-knowledge design the DEK is\n // the access control, so an unentitled miss is exactly `NoAccessError`.\n //\n // Entitlement is read straight off the keyring — no store round-trip, so\n // the authorized mint path costs exactly what it did before.\n //\n // System collections (`_ledger`, `_meta`, `_history`, the fanout\n // sidecars …) are exempt: their DEKs are propagated to every role at\n // grant time and they are minted lazily by machinery running on behalf\n // of a user who may hold no explicit permission for them. They are never\n // addressable by user code, so nothing is being protected by denying\n // here — only internal writes would break.\n if (!collectionName.startsWith('_')) {\n if (!hasAccess(keyring, collectionName)) {\n throw new NoAccessError(\n `No access — user does not have a key for collection \"${collectionName}\". ` +\n 'Grant them this collection in `permissions` to give them one.',\n )\n }\n // #1010 — the ENTITLED half of the same defect. Being allowed to read a\n // collection is not the same as holding its key: a grant only ever\n // wraps the DEKs that exist at grant time, and re-wrapping later is\n // impossible because it needs the grantee's KEK, derived from a secret\n // the vault never stores. So a principal granted BEFORE a collection\n // existed is entitled to it and has no key for it — and minting one\n // here produced a key that decrypts nothing, resurfacing as\n // `TamperedError`. This is reachable for every whole-vault role\n // (`admin`, `viewer`, `custodian`) and for a `'*'` wildcard grantee.\n //\n // Costs one `list()`, and only on this path: an entitled principal\n // whose keyring is missing a DEK. Creating a genuinely new collection\n // finds no records and mints exactly as before.\n if (await collectionHasRecords(store, vault, collectionName)) {\n // Before denying: the in-memory keyring may simply be STALE. A DEK is\n // minted lazily by whichever handle first touches a collection and\n // persisted to the keyring file — so a second live handle for the\n // SAME principal (a second tab, a second `createNoydb` over one\n // store) that was opened before the collection existed holds a\n // keyring snapshot without it. That principal is not unauthorized;\n // their own key is already on disk. Re-read it.\n //\n // This is what separates \"my snapshot is behind\" from \"I was granted\n // before this collection existed\": only the latter finds nothing.\n const refreshed = await reloadPersistedDEK(store, vault, keyring, collectionName)\n if (refreshed) return refreshed\n throw new NoAccessError(\n `No access — user \"${keyring.userId}\" is entitled to collection \"${collectionName}\" ` +\n 'but holds no key for it, because the collection was created AFTER their grant. ' +\n 'A collection DEK can only be wrapped at grant time (wrapping needs the grantee\\'s ' +\n 'secret, which the vault never stores), so this cannot be back-filled — re-grant ' +\n 'the user to give them the key.',\n )\n }\n }\n const dek = await generateDEK()\n keyring.deks.set(collectionName, dek)\n await persistKeyring(store, vault, keyring)\n return dek\n })()\n inFlight.set(collectionName, promise)\n try {\n return await promise\n } finally {\n inFlight.delete(collectionName)\n }\n }\n}\n\n// ─── Permission Checks ─────────────────────────────────────────────────\n\n/**\n * The `Permissions` catch-all key (#1010). `Permissions` has always documented\n * `'*'` as \"the wildcard collection matching all collections in the vault\", but\n * nothing expanded it — a grantee handed the documented catch-all got no keys\n * at all. It is honoured in three places, and they must agree: the DEK wrapping\n * in `grant()`, and both permission checks below.\n */\nexport const PERMISSION_WILDCARD = '*'\n\n/** Does this permission map hand over the whole vault? */\nexport function permissionsAreWildcard(permissions: Permissions | undefined): boolean {\n return permissions !== undefined && PERMISSION_WILDCARD in permissions\n}\n\n/** Check if a user has write permission for a collection. */\nexport function hasWritePermission(keyring: UnlockedKeyring, collectionName: string): boolean {\n // FR-6: custodian writes every collection (admin-level operational rw).\n if (keyring.role === 'owner' || keyring.role === 'admin' || keyring.role === 'custodian') return true\n if (keyring.role === 'viewer' || keyring.role === 'client') return false\n if (keyring.permissions[PERMISSION_WILDCARD] === 'rw') return true\n return keyring.permissions[collectionName] === 'rw'\n}\n\n/** Check if a user has any access to a collection. */\nexport function hasAccess(keyring: UnlockedKeyring, collectionName: string): boolean {\n // FR-6: custodian reads every collection (admin-level operational access).\n if (\n keyring.role === 'owner' ||\n keyring.role === 'admin' ||\n keyring.role === 'custodian' ||\n keyring.role === 'viewer'\n )\n return true\n if (PERMISSION_WILDCARD in keyring.permissions) return true\n return collectionName in keyring.permissions\n}\n\n// ─── Helpers ───────────────────────────────────────────────────────────\n\n/** Persist a keyring file to the store. */\nexport async function persistKeyring(\n store: NoydbStore,\n vault: string,\n keyring: UnlockedKeyring,\n): Promise<void> {\n if (!keyring.kek) {\n throw new ValidationError(\n 'persistKeyring: keyring.kek is null — cannot wrap DEKs without the KEK. ' +\n 'This typically means the keyring was opened via tier-3 PIN resume, ' +\n 'session restore, or a wrap-DEKs tier-2 unlock. Re-authenticate at ' +\n 'tier 1 (secret) before persisting.',\n )\n }\n const rosterKey = requireRosterKey(keyring, 'persistKeyring')\n // Carry the `echo` block forward (#940). This function rebuilds the file\n // from the `UnlockedKeyring`, which deliberately carries no echo info (same\n // rationale as the `changeSecret` guard), so it has to be read back off the\n // persisted file — otherwise the first DEK-provisioning write would drop it\n // and silently degrade an echo keyring into a standard one that no secret\n // shape can open (the KEK stays echo-derived).\n const existingFound = await readKeyringFile(store, vault, keyring.userId)\n // #1096 — narrower than the read-modify-restamp sites, but the same shape:\n // every field carried forward below comes from a fresh, unverified re-read,\n // and the tag minted at the bottom would authenticate whatever came back.\n // (Absent on a first write, which is not a forgery — nothing to verify.)\n if (existingFound) await assertRosterTagValid(existingFound.file, rosterKey, keyring.userId)\n const existingEcho = existingFound?.file.echo\n // Same carry-forward rationale as `echo`, for two fields that describe the\n // keyring's ORIGIN rather than its current contents. `UnlockedKeyring` does\n // not carry either, so rebuilding the file from it defaulted `granted_by` to\n // the holder themselves and stamped a fresh `created_at` — meaning any\n // DEK-provisioning write silently re-parented the holder to themselves and\n // collapsed the admin delegation subtree that `granted_by` encodes.\n const existingGrantedBy = existingFound?.file.granted_by\n const existingCreatedAt = existingFound?.file.created_at\n // Third field of the same class, and #1096 raised the stakes on it.\n // `UnlockedKeyring` does not carry `expires_at`, so rebuilding the file from\n // it silently CLEARED a bundle slot's expiry on any DEK-provisioning write —\n // turning a time-boxed audit grant into a permanent one. Worse now: the\n // roster tag would be stamped over the cleared value, so the erasure would\n // come out authenticated.\n const existingExpiresAt = existingFound?.file.expires_at\n\n const wrappedDeks: Record<string, string> = {}\n for (const [collName, dek] of keyring.deks) {\n wrappedDeks[collName] = await wrapKey(dek, keyring.kek)\n }\n // #1074 — an uncommitted rotation's key must survive a crash, so it is\n // persisted under its own field rather than mixed into `deks`, which would\n // make readers treat it as current before any record had moved.\n const wrappedPending: Record<string, string> = {}\n for (const [collName, dek] of keyring.pendingDeks ?? []) {\n wrappedPending[collName] = await wrapKey(dek, keyring.kek)\n }\n const canary = await mintKeyringCanary(keyring.kek)\n\n // #1096 — build the authority half first and stamp from exactly that\n // object, so the tag covers precisely what is persisted rather than a\n // hand-copied restatement of it.\n const authority = {\n user_id: keyring.userId,\n display_name: keyring.displayName,\n role: keyring.role,\n permissions: keyring.permissions,\n granted_by: existingGrantedBy ?? keyring.userId,\n ...(existingExpiresAt !== undefined && { expires_at: existingExpiresAt }),\n ...(keyring.exportCapability !== undefined && { export_capability: keyring.exportCapability }),\n ...(keyring.importCapability !== undefined && { import_capability: keyring.importCapability }),\n }\n const keyringFile: KeyringFile = {\n _noydb_keyring: NOYDB_KEYRING_VERSION,\n ...authority,\n deks: wrappedDeks,\n ...(Object.keys(wrappedPending).length > 0 ? { pending_deks: wrappedPending } : {}),\n salt: bufferToBase64(keyring.salt),\n created_at: existingCreatedAt ?? new Date().toISOString(),\n canary,\n roster_tag: await mintRosterTag(authority, rosterKey),\n ...(keyring.authenticators.length > 0 && { authenticators: keyring.authenticators }),\n ...(keyring.policy !== undefined && { policy: keyring.policy }),\n ...(existingEcho !== undefined && { echo: existingEcho }),\n }\n\n await writeKeyringFile(store, vault, keyring.userId, keyringFile)\n}\n\n// ─── Export capability ──────────────────────────────────────\n\n/**\n * Role-based default policy for the encrypted-bundle capability.\n *\n * Applied when `keyring.exportCapability` is absent or\n * `exportCapability.bundle` is undefined:\n *\n * - `owner` / `admin` → `true` (happy-path backup without friction)\n * - `operator` / `viewer` / `client` → `false` (explicit grant required)\n *\n * Rationale: a bundle is inert without the KEK, so an owner backing up\n * their own vault doesn't need friction; a non-admin role producing a\n * bundle for an external party does, because the bundle outlives\n * keyring revocation.\n */\nfunction defaultBundleCapability(role: Role): boolean {\n // FR-6: custodian is INTENTIONALLY not in the default-true set (SAFER\n // default — review flag). A bundle is an external artifact that outlives\n // keyring revocation; the owner can still grant a custodian\n // `exportCapability.bundle = true` explicitly when an offline backup is\n // part of the custody contract. Defaulting it off keeps a custodian from\n // silently minting a revocation-surviving copy of the whole vault.\n return role === 'owner' || role === 'admin'\n}\n\n/**\n * Check whether a keyring is authorised for a given `@noy-db/as-*`\n * export tier.\n *\n * - `tier: 'plaintext'` — returns true iff `exportCapability.plaintext`\n * contains the requested `format` or the `'*'` wildcard. Default for\n * every role is empty — no grant, no plaintext export.\n * - `tier: 'bundle'` — returns `exportCapability.bundle` if present, or\n * the role-based default otherwise (owner/admin → true, else false).\n *\n * `@noy-db/as-*` packages MUST call this before invoking the underlying\n * export primitive. Rogue forks that skip the check are caught by code\n * review — the single-entry-point contract is a convention, not a\n * runtime invariant. Vault-level gated wrappers\n * (`vault.exportRecords` / `exportBlobs` / `writeBundle`) will land in a\n * follow-up PR to enforce at the primitive level.\n */\nexport function hasExportCapability(\n keyring: UnlockedKeyring,\n tier: 'plaintext',\n format: ExportFormat,\n): boolean\nexport function hasExportCapability(\n keyring: UnlockedKeyring,\n tier: 'bundle',\n): boolean\nexport function hasExportCapability(\n keyring: UnlockedKeyring,\n tier: 'plaintext' | 'bundle',\n format?: ExportFormat,\n): boolean {\n const cap = keyring.exportCapability\n if (tier === 'plaintext') {\n const allowed = cap?.plaintext ?? []\n return allowed.includes('*') || (format !== undefined && allowed.includes(format))\n }\n // tier === 'bundle'\n return cap?.bundle ?? defaultBundleCapability(keyring.role)\n}\n\n/**\n * Same-shape inspector for an `ExportCapability` value that isn't yet\n * attached to a keyring (e.g. for previewing a grant before applying).\n * Role must be supplied separately so bundle defaults can be computed.\n */\nexport function evaluateExportCapability(\n capability: ExportCapability | undefined,\n role: Role,\n tier: 'plaintext',\n format: ExportFormat,\n): boolean\nexport function evaluateExportCapability(\n capability: ExportCapability | undefined,\n role: Role,\n tier: 'bundle',\n): boolean\nexport function evaluateExportCapability(\n capability: ExportCapability | undefined,\n role: Role,\n tier: 'plaintext' | 'bundle',\n format?: ExportFormat,\n): boolean {\n if (tier === 'plaintext') {\n const allowed = capability?.plaintext ?? []\n return allowed.includes('*') || (format !== undefined && allowed.includes(format))\n }\n return capability?.bundle ?? defaultBundleCapability(role)\n}\n\n// ─── Import capability (issue ) ────────────────────────────────────\n\n/**\n * Check whether a keyring is authorised for a given `@noy-db/as-*`\n * import tier (issue ).\n *\n * - `tier: 'plaintext'` — true iff `importCapability.plaintext`\n * contains the requested `format` or the `'*'` wildcard.\n * - `tier: 'bundle'` — true iff `importCapability.bundle === true`.\n *\n * **Default-closed for every role on every dimension** — including\n * owner. Import is more dangerous than export (corrupts vs leaks), so\n * the policy refuses to assume intent. Owners must positively grant\n * the capability via `vault.grant({ importCapability: ... })`.\n */\nexport function hasImportCapability(\n keyring: UnlockedKeyring,\n tier: 'plaintext',\n format: ExportFormat,\n): boolean\nexport function hasImportCapability(\n keyring: UnlockedKeyring,\n tier: 'bundle',\n): boolean\nexport function hasImportCapability(\n keyring: UnlockedKeyring,\n tier: 'plaintext' | 'bundle',\n format?: ExportFormat,\n): boolean {\n const cap = keyring.importCapability\n if (tier === 'plaintext') {\n const allowed = cap?.plaintext ?? []\n return allowed.includes('*') || (format !== undefined && allowed.includes(format))\n }\n // tier === 'bundle' — closed default for every role\n return cap?.bundle === true\n}\n\n/**\n * Same-shape inspector for an `ImportCapability` value that isn't yet\n * attached to a keyring (e.g. previewing a grant before applying).\n * `role` is accepted for symmetry with `evaluateExportCapability` even\n * though the import policy ignores it — bundle defaults are\n * role-agnostic and closed.\n */\nexport function evaluateImportCapability(\n capability: ImportCapability | undefined,\n role: Role,\n tier: 'plaintext',\n format: ExportFormat,\n): boolean\nexport function evaluateImportCapability(\n capability: ImportCapability | undefined,\n role: Role,\n tier: 'bundle',\n): boolean\nexport function evaluateImportCapability(\n capability: ImportCapability | undefined,\n _role: Role,\n tier: 'plaintext' | 'bundle',\n format?: ExportFormat,\n): boolean {\n if (tier === 'plaintext') {\n const allowed = capability?.plaintext ?? []\n return allowed.includes('*') || (format !== undefined && allowed.includes(format))\n }\n return capability?.bundle === true\n}\n\nfunction resolvePermissions(role: Role, explicit?: Permissions): Permissions {\n // FR-6: custodian is full-access-by-role (hasAccess/hasWritePermission\n // short-circuit on the role), so — like admin — its permissions map is\n // empty. Returning {} also prevents a caller-supplied `permissions` from\n // accidentally NARROWING a custodian below its role guarantee.\n if (role === 'owner' || role === 'admin' || role === 'custodian' || role === 'viewer') return {}\n return explicit ?? {}\n}\n\nasync function writeKeyringFile(\n store: NoydbStore,\n vault: string,\n userId: string,\n keyringFile: KeyringFile,\n): Promise<void> {\n const envelope = buildRecordEnvelope(\n { collection: '_keyring', id: userId, version: 1 },\n { iv: '', data: JSON.stringify(keyringFile) },\n )\n await store.put(vault, '_keyring', userId, envelope)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,SAAS,OAAO,OAAwB;AACtC,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,IAAI,MAAM,IAAI,MAAM,EAAE,KAAK,GAAG,CAAC;AAChE,MAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;AAC/C,UAAM,UAAU,OAAO,QAAQ,KAAgC,EAC5D,OAAO,CAAC,CAAC,EAAE,CAAC,MAAM,MAAM,MAAS,EACjC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,MAAO,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,CAAE,EAC/C,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,GAAG,KAAK,UAAU,CAAC,CAAC,IAAI,OAAO,CAAC,CAAC,EAAE;AACtD,WAAO,IAAI,QAAQ,KAAK,GAAG,CAAC;AAAA,EAC9B;AACA,SAAO,KAAK,UAAU,KAAK,KAAK;AAClC;AAEO,SAAS,gBAAgB,MAAqC;AACnE,SAAO,OAAO;AAAA,IACZ,SAAS,KAAK;AAAA,IACd,MAAM,KAAK;AAAA,IACX,aAAa,KAAK;AAAA,IAClB,YAAY,KAAK;AAAA,IACjB,YAAY,KAAK,c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AAa;AACxB,UAAM,UAAU,KAAK,aAAa,CAAC;AACnC,WAAO,QAAQ,SAAS,GAAG,KAAM,WAAW,UAAa,QAAQ,SAAS,MAAM;AAAA,EAClF;AAEA,SAAO,KAAK,WAAW;AACzB;AAoBO,SAAS,yBACd,YACA,OACA,MACA,QACS;AACT,MAAI,SAAS,aAAa;AACxB,UAAM,UAAU,YAAY,aAAa,CAAC;AAC1C,WAAO,QAAQ,SAAS,GAAG,KAAM,WAAW,UAAa,QAAQ,SAAS,MAAM;AAAA,EAClF;AACA,SAAO,YAAY,WAAW;AAChC;AAEA,SAAS,mBAAmB,MAAY,UAAqC;AAK3E,MAAI,SAAS,WAAW,SAAS,WAAW,SAAS,eAAe,SAAS,SAAU,QAAO,CAAC;AAC/F,SAAO,YAAY,CAAC;AACtB;AAEA,eAAe,iBACb,OACA,OACA,QACA,aACe;AACf,QAAM,WAAW;AAAA,IACf,EAAE,YAAY,YAAY,IAAI,QAAQ,SAAS,EAAE;AAAA,IACjD,EAAE,IAAI,IAAI,MAAM,KAAK,UAAU,WAAW,EAAE;AAAA,EAC9C;AACA,QAAM,MAAM,IAAI,OAAO,YAAY,QAAQ,QAAQ;AACrD;","names":[]}
|
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
import {
|
|
2
2
|
generateULID
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-4AOERLTV.js";
|
|
4
4
|
import {
|
|
5
5
|
base64ToBuffer,
|
|
6
6
|
bufferToBase64
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-AU3AUJIZ.js";
|
|
8
8
|
import {
|
|
9
9
|
SessionExpiredError,
|
|
10
10
|
SessionNotFoundError,
|
|
11
11
|
SessionPolicyError,
|
|
12
12
|
ValidationError
|
|
13
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-CWM4GQD2.js";
|
|
14
14
|
|
|
15
15
|
// src/with-party/session/session.ts
|
|
16
16
|
var subtle = globalThis.crypto.subtle;
|
|
@@ -364,4 +364,4 @@ export {
|
|
|
364
364
|
clearDevUnlock,
|
|
365
365
|
isDevUnlockActive
|
|
366
366
|
};
|
|
367
|
-
//# sourceMappingURL=chunk-
|
|
367
|
+
//# sourceMappingURL=chunk-CLAHBPOI.js.map
|