@noy-db/hub 0.3.0-pre.2 → 0.3.0-pre.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter/index.d.ts +2 -2
- package/dist/adapter/index.js +1 -1
- package/dist/aggregate/index.d.ts +3 -3
- package/dist/aggregate/index.js +4 -4
- package/dist/api-JOXUNSKP.js +20 -0
- package/dist/as/index.d.ts +4 -4
- package/dist/as/index.js +12 -6
- package/dist/at/index.d.ts +2 -2
- package/dist/attestation/index.d.ts +3 -3
- package/dist/attestation/index.js +19 -13
- package/dist/attestation/index.js.map +1 -1
- package/dist/{backup-KMJQ66MF.js → backup-MOB27UUN.js} +12 -6
- package/dist/{backup-KMJQ66MF.js.map → backup-MOB27UUN.js.map} +1 -1
- package/dist/blobs/index.d.ts +4 -4
- package/dist/blobs/index.js +11 -5
- package/dist/blobs/index.js.map +1 -1
- package/dist/bundle/index.d.ts +5 -5
- package/dist/bundle/index.js +21 -15
- package/dist/bundle/index.js.map +1 -1
- package/dist/{bundle-PwBGkhpe.d.ts → bundle-Bs13EZtX.d.ts} +1 -1
- package/dist/by/index.js +2 -2
- package/dist/cargo/index.d.ts +4 -4
- package/dist/cargo/index.js +23 -17
- package/dist/{chunk-SMXWYP24.js → chunk-3QRQOBS7.js} +3 -3
- package/dist/{chunk-QHJW5EXU.js → chunk-3Y4QLJ6K.js} +2 -2
- package/dist/{chunk-NF5JWERG.js → chunk-43ISXURO.js} +2 -2
- package/dist/{chunk-5LUY7UTV.js → chunk-4K3MQ5S3.js} +2 -2
- package/dist/{chunk-QZISFCVG.js → chunk-5CY35H55.js} +11 -9
- package/dist/{chunk-QZISFCVG.js.map → chunk-5CY35H55.js.map} +1 -1
- package/dist/chunk-5EWYUR5P.js +37 -0
- package/dist/chunk-5EWYUR5P.js.map +1 -0
- package/dist/{chunk-Y22T3KQE.js → chunk-5MRE3C4Q.js} +5 -5
- package/dist/{chunk-M6OST55S.js → chunk-5W7AOFWA.js} +2 -2
- package/dist/{chunk-AXRXJTE2.js → chunk-6HNKCKFZ.js} +7 -7
- package/dist/{chunk-UAG5KWVA.js → chunk-6RXPSMKR.js} +3 -3
- package/dist/{chunk-TJYQIGAP.js → chunk-7J7JRYXW.js} +9 -5
- package/dist/chunk-7J7JRYXW.js.map +1 -0
- package/dist/{chunk-UDRIWL7A.js → chunk-A5DYVMDR.js} +3 -3
- package/dist/chunk-AF5ZRTZ4.js +108 -0
- package/dist/chunk-AF5ZRTZ4.js.map +1 -0
- package/dist/{chunk-I3TIKTJO.js → chunk-BKGIWGCX.js} +2 -2
- package/dist/{chunk-IO6GRPT6.js → chunk-BMQOH7MM.js} +2 -2
- package/dist/{chunk-26LGBE4T.js → chunk-CPXPHQGX.js} +6 -4
- package/dist/{chunk-26LGBE4T.js.map → chunk-CPXPHQGX.js.map} +1 -1
- package/dist/{chunk-FISN7WE4.js → chunk-EWR7HL3K.js} +4 -4
- package/dist/{chunk-AQTBSL7R.js → chunk-FH52CDEW.js} +5 -5
- package/dist/chunk-G4MGYGSS.js +130 -0
- package/dist/chunk-G4MGYGSS.js.map +1 -0
- package/dist/{chunk-UV5MFVO3.js → chunk-G7RDYYTE.js} +2 -2
- package/dist/{chunk-UIU2THRG.js → chunk-GBTUANXF.js} +16 -297
- package/dist/chunk-GBTUANXF.js.map +1 -0
- package/dist/{chunk-TEILUWOI.js → chunk-GOUNIHFA.js} +10 -10
- package/dist/{chunk-LXQT4WMP.js → chunk-GQOT6QJR.js} +8 -6
- package/dist/{chunk-LXQT4WMP.js.map → chunk-GQOT6QJR.js.map} +1 -1
- package/dist/{chunk-RUEKROOS.js → chunk-GXGK22QU.js} +2 -2
- package/dist/{chunk-IELYAOGG.js → chunk-GZZL5R73.js} +4 -4
- package/dist/{chunk-JNUWZ6D3.js → chunk-H5XRIJX3.js} +7 -5
- package/dist/{chunk-JNUWZ6D3.js.map → chunk-H5XRIJX3.js.map} +1 -1
- package/dist/{chunk-CWPPNPOH.js → chunk-H7RYPVMJ.js} +2 -2
- package/dist/{chunk-5N6CZTCY.js → chunk-HBKDR7R3.js} +3 -3
- package/dist/{chunk-KXGNJJXB.js → chunk-HLUKZ36Q.js} +9 -9
- package/dist/{chunk-LMTH2RM6.js → chunk-HMXLN43G.js} +2 -2
- package/dist/{chunk-BG3SPSR4.js → chunk-HY6ZGGEC.js} +2 -2
- package/dist/{chunk-UPJNJGGA.js → chunk-K5P46KB3.js} +27 -10
- package/dist/chunk-K5P46KB3.js.map +1 -0
- package/dist/chunk-KYY7L72M.js +106 -0
- package/dist/chunk-KYY7L72M.js.map +1 -0
- package/dist/{chunk-62QYRORB.js → chunk-LIP6JWYK.js} +3 -3
- package/dist/{chunk-5TDJ56JE.js → chunk-LN22XH4B.js} +1 -1
- package/dist/chunk-LN22XH4B.js.map +1 -0
- package/dist/chunk-LP7BEXCT.js +32 -0
- package/dist/chunk-LP7BEXCT.js.map +1 -0
- package/dist/{chunk-IGUYVGGI.js → chunk-LPRPVCNY.js} +5 -5
- package/dist/{chunk-AIWULCUO.js → chunk-M66NAZA4.js} +5 -3
- package/dist/{chunk-AIWULCUO.js.map → chunk-M66NAZA4.js.map} +1 -1
- package/dist/{chunk-KVOXU4T5.js → chunk-N5YVZHCB.js} +2 -2
- package/dist/{chunk-76722EBH.js → chunk-NB47TXGP.js} +14 -12
- package/dist/{chunk-76722EBH.js.map → chunk-NB47TXGP.js.map} +1 -1
- package/dist/chunk-NO272T7Q.js +194 -0
- package/dist/chunk-NO272T7Q.js.map +1 -0
- package/dist/{chunk-SRB2XEWB.js → chunk-O2DB4C3M.js} +8 -6
- package/dist/{chunk-SRB2XEWB.js.map → chunk-O2DB4C3M.js.map} +1 -1
- package/dist/{chunk-IUEN57TV.js → chunk-OFBFAVLI.js} +6 -6
- package/dist/{chunk-MTMJVJ5W.js → chunk-OPTFANOX.js} +5 -3
- package/dist/chunk-OPTFANOX.js.map +1 -0
- package/dist/{chunk-5O3AOPDT.js → chunk-OVO2RZAE.js} +212 -439
- package/dist/chunk-OVO2RZAE.js.map +1 -0
- package/dist/{chunk-GYGWYIOZ.js → chunk-P27Z66EB.js} +7 -5
- package/dist/{chunk-GYGWYIOZ.js.map → chunk-P27Z66EB.js.map} +1 -1
- package/dist/{chunk-HCIPRAGS.js → chunk-P2LDXRGP.js} +2 -2
- package/dist/chunk-P3NGV5RV.js +41 -0
- package/dist/chunk-P3NGV5RV.js.map +1 -0
- package/dist/{chunk-5R3ERCDH.js → chunk-P3V7JTB6.js} +25 -9
- package/dist/{chunk-5R3ERCDH.js.map → chunk-P3V7JTB6.js.map} +1 -1
- package/dist/{chunk-LV7M27WM.js → chunk-P5WXDYMD.js} +8 -197
- package/dist/chunk-P5WXDYMD.js.map +1 -0
- package/dist/chunk-PGFY7IRW.js +95 -0
- package/dist/chunk-PGFY7IRW.js.map +1 -0
- package/dist/chunk-QKVILR7N.js +25 -0
- package/dist/chunk-QKVILR7N.js.map +1 -0
- package/dist/{chunk-V7RWQRG7.js → chunk-QNTEDPWP.js} +3 -3
- package/dist/{chunk-Q7SS3IME.js → chunk-RDHAGBEB.js} +3 -3
- package/dist/{chunk-EIZUR2XW.js → chunk-RTS23VIJ.js} +2 -2
- package/dist/{chunk-LFLXAY2W.js → chunk-SEQ2JI3Y.js} +9 -7
- package/dist/{chunk-LFLXAY2W.js.map → chunk-SEQ2JI3Y.js.map} +1 -1
- package/dist/{chunk-AZAOEIKW.js → chunk-SW56GSYC.js} +2 -2
- package/dist/{chunk-TA66UMI4.js → chunk-T2EGAXPM.js} +2 -2
- package/dist/{chunk-SM3AVUHC.js → chunk-T45LAT2Y.js} +2 -2
- package/dist/{chunk-SKF73JOP.js → chunk-T65UZXR6.js} +3 -3
- package/dist/{chunk-ITNUCOXM.js → chunk-TB5RNNJ4.js} +7 -5
- package/dist/{chunk-ITNUCOXM.js.map → chunk-TB5RNNJ4.js.map} +1 -1
- package/dist/chunk-TCIUO62Z.js +29 -0
- package/dist/chunk-TCIUO62Z.js.map +1 -0
- package/dist/chunk-THNJ3IKU.js +17 -0
- package/dist/chunk-THNJ3IKU.js.map +1 -0
- package/dist/chunk-TLJOJBZD.js +404 -0
- package/dist/chunk-TLJOJBZD.js.map +1 -0
- package/dist/chunk-TQ3REHVF.js +95 -0
- package/dist/chunk-TQ3REHVF.js.map +1 -0
- package/dist/{chunk-DGDI2D4M.js → chunk-TVRQ3RYH.js} +28 -7
- package/dist/chunk-TVRQ3RYH.js.map +1 -0
- package/dist/{chunk-PSMV73A5.js → chunk-TYGW5TOR.js} +7 -7
- package/dist/{chunk-ZYUC53LT.js → chunk-U23JUUPX.js} +58 -2
- package/dist/{chunk-ZYUC53LT.js.map → chunk-U23JUUPX.js.map} +1 -1
- package/dist/{chunk-3YFXJ3ZP.js → chunk-U24XHXNK.js} +2 -2
- package/dist/chunk-ULIHDPKL.js +94 -0
- package/dist/chunk-ULIHDPKL.js.map +1 -0
- package/dist/chunk-UOEWDCUX.js +69 -0
- package/dist/chunk-UOEWDCUX.js.map +1 -0
- package/dist/{chunk-WWGT2MDV.js → chunk-VAWY44JW.js} +8 -8
- package/dist/{chunk-WWGT2MDV.js.map → chunk-VAWY44JW.js.map} +1 -1
- package/dist/chunk-VFRNWE5P.js +239 -0
- package/dist/chunk-VFRNWE5P.js.map +1 -0
- package/dist/{chunk-IPB7FTQX.js → chunk-VMJ5URU7.js} +10 -8
- package/dist/chunk-VMJ5URU7.js.map +1 -0
- package/dist/{chunk-VFQGRQIH.js → chunk-VPCMJ5Z4.js} +7 -5
- package/dist/{chunk-VFQGRQIH.js.map → chunk-VPCMJ5Z4.js.map} +1 -1
- package/dist/{chunk-VCTFO5CO.js → chunk-VRPBEOWU.js} +2 -2
- package/dist/{chunk-ZCGAHGUS.js → chunk-VWGCJUTV.js} +2 -2
- package/dist/{chunk-XXYIOFUB.js → chunk-XJR3COJO.js} +5 -5
- package/dist/{chunk-PKHL44ER.js → chunk-XYYW64LB.js} +2 -2
- package/dist/{chunk-IAGBDSCS.js → chunk-YFF2RP3X.js} +2 -2
- package/dist/{chunk-MD3Y6J3L.js → chunk-Z3FZC5GV.js} +7 -5
- package/dist/{chunk-MD3Y6J3L.js.map → chunk-Z3FZC5GV.js.map} +1 -1
- package/dist/{chunk-DFEMTNPJ.js → chunk-Z5PIUYNB.js} +10 -8
- package/dist/{chunk-DFEMTNPJ.js.map → chunk-Z5PIUYNB.js.map} +1 -1
- package/dist/{chunk-WYSO2NIH.js → chunk-Z7KI4WHR.js} +2 -2
- package/dist/chunk-ZKF6HH7V.js +120 -0
- package/dist/chunk-ZKF6HH7V.js.map +1 -0
- package/dist/{chunk-I2NOIW44.js → chunk-ZKYMKF2S.js} +8 -6
- package/dist/{chunk-I2NOIW44.js.map → chunk-ZKYMKF2S.js.map} +1 -1
- package/dist/{chunk-PSHOXR6C.js → chunk-ZPHDGUZZ.js} +737 -1082
- package/dist/chunk-ZPHDGUZZ.js.map +1 -0
- package/dist/{chunk-CMGR4ZEW.js → chunk-ZROMNP7Q.js} +2 -2
- package/dist/classified/index.d.ts +17 -0
- package/dist/classified/index.js +38 -0
- package/dist/collection-facade-MKEBZDWW.js +39 -0
- package/dist/computed-BMMEFRFJ.js +11 -0
- package/dist/config-drift-KGM7ZRW4.js +24 -0
- package/dist/config-drift-KGM7ZRW4.js.map +1 -0
- package/dist/consent/index.d.ts +3 -3
- package/dist/consent/index.js +10 -4
- package/dist/consent/index.js.map +1 -1
- package/dist/crdt/index.d.ts +3 -3
- package/dist/delegation-BQNIEHZE.js +25 -0
- package/dist/derivations/index.d.ts +4 -4
- package/dist/derivations/index.js +12 -6
- package/dist/describe/index.d.ts +1 -1
- package/dist/{describe-Ccd1hS7a.d.ts → describe-C6iHNlqJ.d.ts} +19 -0
- package/dist/{dev-unlock-h0K-UZTk.d.ts → dev-unlock-Cqd5Xv5J.d.ts} +1 -1
- package/dist/{enclave-UL5LW66V.js → enclave-YN6223OG.js} +47 -18
- package/dist/executor-CBTNU5VZ.js +9 -0
- package/dist/executor-DJHNSTIR.js +9 -0
- package/dist/executor-FGISLQIN.js +21 -0
- package/dist/export-accessible-P7SLRLK3.js +23 -0
- package/dist/extract-partition-RNVSFHAB.js +36 -0
- package/dist/{fanout-sidecar-GF3DJ6KR.js → fanout-sidecar-WS22Q5WH.js} +17 -14
- package/dist/fanout-sidecar-WS22Q5WH.js.map +1 -0
- package/dist/fence-watcher-DHQ775JB.js +69 -0
- package/dist/fence-watcher-DHQ775JB.js.map +1 -0
- package/dist/find-RNBG7LBY.js +11 -0
- package/dist/forget/index.js +10 -4
- package/dist/forget/index.js.map +1 -1
- package/dist/guards/index.d.ts +4 -4
- package/dist/guards/index.js +3 -3
- package/dist/{hash-CdSr06sm.d.ts → hash-D8Q5MJLA.d.ts} +7 -2
- package/dist/history/index.d.ts +4 -4
- package/dist/history/index.js +12 -6
- package/dist/history/index.js.map +1 -1
- package/dist/i18n/index.d.ts +3 -3
- package/dist/i18n/index.js +14 -8
- package/dist/i18n/index.js.map +1 -1
- package/dist/in/index.d.ts +2 -2
- package/dist/{index-_6At2_9_.d.ts → index-D4GQe1Rx.d.ts} +1058 -49
- package/dist/{index-CGLLRtFc.d.ts → index-DRxk8q_7.d.ts} +3 -3
- package/dist/index.d.ts +60 -15
- package/dist/index.js +1081 -121
- package/dist/index.js.map +1 -1
- package/dist/indexing/index.d.ts +3 -3
- package/dist/indexing/index.js +4 -4
- package/dist/issue-W5QG53B5.js +19 -0
- package/dist/json-schema-I22JCYCG.js +44 -0
- package/dist/json-schema-I22JCYCG.js.map +1 -0
- package/dist/kernel/index.d.ts +3 -3
- package/dist/kernel/index.js +13 -7
- package/dist/lazy/index.d.ts +21 -0
- package/dist/lazy/index.js +12 -0
- package/dist/{ledger-RYI35CDS.js → ledger-KZWBKAG5.js} +12 -6
- package/dist/liberate-GMGCHIND.js +24 -0
- package/dist/link-set-UQEIYQAM.js +31 -0
- package/dist/materialized-views/index.d.ts +4 -4
- package/dist/materialized-views/index.js +16 -10
- package/dist/{mime-magic-B4RoFj3B.d.ts → mime-magic-DmwT7OzZ.d.ts} +1 -1
- package/dist/noydb-KS2O2MRI.js +60 -0
- package/dist/on/index.d.ts +2 -2
- package/dist/on/index.js +10 -4
- package/dist/overlay-views/index.d.ts +4 -4
- package/dist/overlay-views/index.js +4 -4
- package/dist/periods/index.d.ts +3 -3
- package/dist/periods/index.js +13 -7
- package/dist/pod/index.d.ts +3 -3
- package/dist/pod/index.js +12 -6
- package/dist/{policy-IXK4FVXP.js → policy-YIKUH4AD.js} +5 -5
- package/dist/portability/index.d.ts +3 -3
- package/dist/portability/index.js +8 -8
- package/dist/{public-envelope-JHDQCPSX.js → public-envelope-MRN5YYZZ.js} +4 -4
- package/dist/query/index.d.ts +2 -2
- package/dist/query/index.js +6 -6
- package/dist/register-K6DDSIXN.js +21 -0
- package/dist/registry-IMNMHWTM.js +17 -0
- package/dist/registry-K6VUQXKV.js +19 -0
- package/dist/registry-ZVO3T4M5.js +9 -0
- package/dist/registry-ZVO3T4M5.js.map +1 -0
- package/dist/request-withdrawal-EHALV66Y.js +31 -0
- package/dist/request-withdrawal-EHALV66Y.js.map +1 -0
- package/dist/reveal-TBLTFWQ2.js +38 -0
- package/dist/reveal-TBLTFWQ2.js.map +1 -0
- package/dist/revoke-MHAUAESM.js +24 -0
- package/dist/revoke-MHAUAESM.js.map +1 -0
- package/dist/sealed-record/index.d.ts +3 -3
- package/dist/sealed-record/index.js +13 -7
- package/dist/sealed-record/index.js.map +1 -1
- package/dist/session/index.d.ts +4 -4
- package/dist/session/index.js +10 -4
- package/dist/session/index.js.map +1 -1
- package/dist/shadow/index.d.ts +3 -3
- package/dist/shadow/index.js +2 -2
- package/dist/signer-PQ74YXRY.js +25 -0
- package/dist/signer-PQ74YXRY.js.map +1 -0
- package/dist/snapshots/index.d.ts +3 -3
- package/dist/snapshots/index.js +11 -5
- package/dist/snapshots/index.js.map +1 -1
- package/dist/{stale-3JWHNDIY.js → stale-7Q62KVI3.js} +2 -2
- package/dist/stale-7Q62KVI3.js.map +1 -0
- package/dist/storage-5E6YB2JY.js +21 -0
- package/dist/storage-5E6YB2JY.js.map +1 -0
- package/dist/{store-coordination-provider-3I7XWZZK.js → store-coordination-provider-JJCEMTAE.js} +3 -3
- package/dist/sync/index.d.ts +2 -2
- package/dist/sync/index.js +10 -4
- package/dist/sync/index.js.map +1 -1
- package/dist/team/index.d.ts +18 -4
- package/dist/team/index.js +24 -11
- package/dist/tiers/index.d.ts +2 -2
- package/dist/tiers/index.js +11 -5
- package/dist/to/index.d.ts +2 -2
- package/dist/to/index.js +1 -1
- package/dist/{transition-guard-DqodPNKw.d.ts → transition-guard-C4hvR-Ac.d.ts} +1 -1
- package/dist/tx/index.d.ts +3 -3
- package/dist/tx/index.js +3 -3
- package/dist/ui/index.d.ts +1 -1
- package/dist/util/index.js +1 -1
- package/dist/validators-Ctgkj5qd.d.ts +101 -0
- package/dist/{vault-diff-BtpiBvic.d.ts → vault-diff-B1Ir6EGs.d.ts} +1 -1
- package/dist/verify-YB5LQHNA.js +139 -0
- package/dist/verify-YB5LQHNA.js.map +1 -0
- package/dist/walk-5C3GPKT2.js +241 -0
- package/dist/walk-5C3GPKT2.js.map +1 -0
- package/dist/with/index.d.ts +3 -3
- package/dist/with/index.js +12 -6
- package/dist/{with-materialized-view-DMmWtYfJ.d.ts → with-materialized-view-Bp65kKdQ.d.ts} +1 -1
- package/dist/{with-overlayed-view-D_IB2nkM.d.ts → with-overlayed-view-BRhdQNrK.d.ts} +1 -1
- package/dist/{with-rollup-em2wxoHP.d.ts → with-rollup-bQRPc3y1.d.ts} +1 -1
- package/dist/withdraw-accessible-JMX2TCPX.js +28 -0
- package/dist/withdraw-accessible-JMX2TCPX.js.map +1 -0
- package/package.json +11 -3
- package/dist/api-RW3KP7WU.js +0 -14
- package/dist/chunk-5O3AOPDT.js.map +0 -1
- package/dist/chunk-5TDJ56JE.js.map +0 -1
- package/dist/chunk-DGDI2D4M.js.map +0 -1
- package/dist/chunk-IPB7FTQX.js.map +0 -1
- package/dist/chunk-LV7M27WM.js.map +0 -1
- package/dist/chunk-M2YKN37S.js +0 -524
- package/dist/chunk-M2YKN37S.js.map +0 -1
- package/dist/chunk-MTMJVJ5W.js.map +0 -1
- package/dist/chunk-PSHOXR6C.js.map +0 -1
- package/dist/chunk-TJYQIGAP.js.map +0 -1
- package/dist/chunk-UIU2THRG.js.map +0 -1
- package/dist/chunk-UPJNJGGA.js.map +0 -1
- package/dist/collection-facade-GQAOGJP2.js +0 -33
- package/dist/delegation-UL5HKLER.js +0 -19
- package/dist/executor-2FWQRLMG.js +0 -15
- package/dist/executor-QZ7BXICW.js +0 -9
- package/dist/executor-Z5ZLJVTV.js +0 -9
- package/dist/export-accessible-KRV5W4GH.js +0 -17
- package/dist/extract-partition-GLKBOXFQ.js +0 -30
- package/dist/fanout-sidecar-GF3DJ6KR.js.map +0 -1
- package/dist/issue-Y6UVIR43.js +0 -13
- package/dist/liberate-CRPZEV7O.js +0 -18
- package/dist/noydb-LDEBLNHY.js +0 -50
- package/dist/registry-45RJNWGU.js +0 -9
- package/dist/registry-5GRV5VXI.js +0 -13
- package/dist/registry-WEUCHBO4.js +0 -11
- package/dist/request-withdrawal-GBPH2FDY.js +0 -25
- package/dist/revoke-TUFRGI6S.js +0 -18
- package/dist/signer-PNKTBVF7.js +0 -19
- package/dist/withdraw-accessible-FFS46EOD.js +0 -22
- /package/dist/{api-RW3KP7WU.js.map → api-JOXUNSKP.js.map} +0 -0
- /package/dist/{chunk-SMXWYP24.js.map → chunk-3QRQOBS7.js.map} +0 -0
- /package/dist/{chunk-QHJW5EXU.js.map → chunk-3Y4QLJ6K.js.map} +0 -0
- /package/dist/{chunk-NF5JWERG.js.map → chunk-43ISXURO.js.map} +0 -0
- /package/dist/{chunk-5LUY7UTV.js.map → chunk-4K3MQ5S3.js.map} +0 -0
- /package/dist/{chunk-Y22T3KQE.js.map → chunk-5MRE3C4Q.js.map} +0 -0
- /package/dist/{chunk-M6OST55S.js.map → chunk-5W7AOFWA.js.map} +0 -0
- /package/dist/{chunk-AXRXJTE2.js.map → chunk-6HNKCKFZ.js.map} +0 -0
- /package/dist/{chunk-UAG5KWVA.js.map → chunk-6RXPSMKR.js.map} +0 -0
- /package/dist/{chunk-UDRIWL7A.js.map → chunk-A5DYVMDR.js.map} +0 -0
- /package/dist/{chunk-I3TIKTJO.js.map → chunk-BKGIWGCX.js.map} +0 -0
- /package/dist/{chunk-IO6GRPT6.js.map → chunk-BMQOH7MM.js.map} +0 -0
- /package/dist/{chunk-FISN7WE4.js.map → chunk-EWR7HL3K.js.map} +0 -0
- /package/dist/{chunk-AQTBSL7R.js.map → chunk-FH52CDEW.js.map} +0 -0
- /package/dist/{chunk-UV5MFVO3.js.map → chunk-G7RDYYTE.js.map} +0 -0
- /package/dist/{chunk-TEILUWOI.js.map → chunk-GOUNIHFA.js.map} +0 -0
- /package/dist/{chunk-RUEKROOS.js.map → chunk-GXGK22QU.js.map} +0 -0
- /package/dist/{chunk-IELYAOGG.js.map → chunk-GZZL5R73.js.map} +0 -0
- /package/dist/{chunk-CWPPNPOH.js.map → chunk-H7RYPVMJ.js.map} +0 -0
- /package/dist/{chunk-5N6CZTCY.js.map → chunk-HBKDR7R3.js.map} +0 -0
- /package/dist/{chunk-KXGNJJXB.js.map → chunk-HLUKZ36Q.js.map} +0 -0
- /package/dist/{chunk-LMTH2RM6.js.map → chunk-HMXLN43G.js.map} +0 -0
- /package/dist/{chunk-BG3SPSR4.js.map → chunk-HY6ZGGEC.js.map} +0 -0
- /package/dist/{chunk-62QYRORB.js.map → chunk-LIP6JWYK.js.map} +0 -0
- /package/dist/{chunk-IGUYVGGI.js.map → chunk-LPRPVCNY.js.map} +0 -0
- /package/dist/{chunk-KVOXU4T5.js.map → chunk-N5YVZHCB.js.map} +0 -0
- /package/dist/{chunk-IUEN57TV.js.map → chunk-OFBFAVLI.js.map} +0 -0
- /package/dist/{chunk-HCIPRAGS.js.map → chunk-P2LDXRGP.js.map} +0 -0
- /package/dist/{chunk-V7RWQRG7.js.map → chunk-QNTEDPWP.js.map} +0 -0
- /package/dist/{chunk-Q7SS3IME.js.map → chunk-RDHAGBEB.js.map} +0 -0
- /package/dist/{chunk-EIZUR2XW.js.map → chunk-RTS23VIJ.js.map} +0 -0
- /package/dist/{chunk-AZAOEIKW.js.map → chunk-SW56GSYC.js.map} +0 -0
- /package/dist/{chunk-TA66UMI4.js.map → chunk-T2EGAXPM.js.map} +0 -0
- /package/dist/{chunk-SM3AVUHC.js.map → chunk-T45LAT2Y.js.map} +0 -0
- /package/dist/{chunk-SKF73JOP.js.map → chunk-T65UZXR6.js.map} +0 -0
- /package/dist/{chunk-PSMV73A5.js.map → chunk-TYGW5TOR.js.map} +0 -0
- /package/dist/{chunk-3YFXJ3ZP.js.map → chunk-U24XHXNK.js.map} +0 -0
- /package/dist/{chunk-VCTFO5CO.js.map → chunk-VRPBEOWU.js.map} +0 -0
- /package/dist/{chunk-ZCGAHGUS.js.map → chunk-VWGCJUTV.js.map} +0 -0
- /package/dist/{chunk-XXYIOFUB.js.map → chunk-XJR3COJO.js.map} +0 -0
- /package/dist/{chunk-PKHL44ER.js.map → chunk-XYYW64LB.js.map} +0 -0
- /package/dist/{chunk-IAGBDSCS.js.map → chunk-YFF2RP3X.js.map} +0 -0
- /package/dist/{chunk-WYSO2NIH.js.map → chunk-Z7KI4WHR.js.map} +0 -0
- /package/dist/{chunk-CMGR4ZEW.js.map → chunk-ZROMNP7Q.js.map} +0 -0
- /package/dist/{collection-facade-GQAOGJP2.js.map → classified/index.js.map} +0 -0
- /package/dist/{delegation-UL5HKLER.js.map → collection-facade-MKEBZDWW.js.map} +0 -0
- /package/dist/{enclave-UL5LW66V.js.map → computed-BMMEFRFJ.js.map} +0 -0
- /package/dist/{executor-2FWQRLMG.js.map → delegation-BQNIEHZE.js.map} +0 -0
- /package/dist/{executor-QZ7BXICW.js.map → enclave-YN6223OG.js.map} +0 -0
- /package/dist/{executor-Z5ZLJVTV.js.map → executor-CBTNU5VZ.js.map} +0 -0
- /package/dist/{export-accessible-KRV5W4GH.js.map → executor-DJHNSTIR.js.map} +0 -0
- /package/dist/{extract-partition-GLKBOXFQ.js.map → executor-FGISLQIN.js.map} +0 -0
- /package/dist/{issue-Y6UVIR43.js.map → export-accessible-P7SLRLK3.js.map} +0 -0
- /package/dist/{ledger-RYI35CDS.js.map → extract-partition-RNVSFHAB.js.map} +0 -0
- /package/dist/{liberate-CRPZEV7O.js.map → find-RNBG7LBY.js.map} +0 -0
- /package/dist/{noydb-LDEBLNHY.js.map → issue-W5QG53B5.js.map} +0 -0
- /package/dist/{policy-IXK4FVXP.js.map → lazy/index.js.map} +0 -0
- /package/dist/{public-envelope-JHDQCPSX.js.map → ledger-KZWBKAG5.js.map} +0 -0
- /package/dist/{registry-45RJNWGU.js.map → liberate-GMGCHIND.js.map} +0 -0
- /package/dist/{registry-5GRV5VXI.js.map → link-set-UQEIYQAM.js.map} +0 -0
- /package/dist/{registry-WEUCHBO4.js.map → noydb-KS2O2MRI.js.map} +0 -0
- /package/dist/{request-withdrawal-GBPH2FDY.js.map → policy-YIKUH4AD.js.map} +0 -0
- /package/dist/{revoke-TUFRGI6S.js.map → public-envelope-MRN5YYZZ.js.map} +0 -0
- /package/dist/{signer-PNKTBVF7.js.map → register-K6DDSIXN.js.map} +0 -0
- /package/dist/{stale-3JWHNDIY.js.map → registry-IMNMHWTM.js.map} +0 -0
- /package/dist/{withdraw-accessible-FFS46EOD.js.map → registry-K6VUQXKV.js.map} +0 -0
- /package/dist/{store-coordination-provider-3I7XWZZK.js.map → store-coordination-provider-JJCEMTAE.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/with-party/team/magic-link-grant.ts","../src/port/with/team-strategy.ts","../src/with-party/team/rotate-recover.ts","../src/with-party/team/peer-recover.ts","../src/with-party/team/authenticators.ts"],"sourcesContent":["/**\n * Magic-link-bound cross-user delegation grants.\n *\n * This module is the **core storage + encryption layer** that lets a\n * grantor issue a tier-DEK to a user whose KEK they do not know. The\n * trust bridge is provided by the `@noy-db/on-magic-link` package:\n *\n * 1. Grantor picks a grantee identity (user id + email handle).\n * 2. Grantor mints a magic-link token (ULID) via `createMagicLinkToken`.\n * 3. Grantor derives a **content key** + a **KEK** from\n * `(serverSecret, token, vault)` using HKDF-SHA256 with separate\n * `info` tags — both callers (grantor and grantee) can derive the\n * same keys given the same inputs.\n * 4. Grantor persists a record in `_magic_link_grants/<token>`:\n * - envelope `_data` is AES-GCM encrypted under the content key\n * - the inner `wrappedDek` is AES-KW wrapped under the KEK\n * 5. Grantee receives the URL, derives the same content key + KEK,\n * loads the grant, decrypts the envelope, unwraps the tier DEK.\n *\n * ## Why a separate collection from `_delegations`\n *\n * `_delegations` envelopes are encrypted under a DEK shared across\n * every vault user (audit-visibility). External auditors / client\n * portal users have NO pre-existing keyring, so they cannot read that\n * DEK. Magic-link grants live in their own collection whose envelope\n * encryption is derived purely from the magic-link URL + server secret\n * — nothing else is required to decrypt.\n *\n * ## Batch grants\n *\n * One magic-link token may point to MULTIPLE grants (e.g. the client\n * portal case: invoices + payments + etax all share one link). Each\n * grant is persisted under a distinct record id:\n *\n * `<token>` for the single-grant / primary entry\n * `<token>:<index>` for subsequent entries\n *\n * `listMagicLinkGrants(store, vault, token)` enumerates every record\n * whose id begins with `<token>` so the claimant can materialize all\n * DEKs in one pass.\n *\n * ## Revocation\n *\n * `store.delete(vault, _magic_link_grants, <token>)` immediately\n * invalidates the link — even if the URL was captured and the server\n * secret leaked, no payload remains to decrypt.\n *\n * @module\n */\n\nimport type { NoydbStore, EncryptedEnvelope } from '../../kernel/types.js'\nimport type { UnlockedKeyring } from './keyring.js'\nimport { encrypt, openEnvelopeJson, wrapKey, unwrapKey, type EnclaveKey } from '../../kernel/enclave/index.js'\nimport { dekKey } from './tiers.js'\nimport { DelegationTargetMissingError } from '../../kernel/errors.js'\n\n/** Reserved collection holding magic-link grant envelopes. */\nexport const MAGIC_LINK_GRANTS_COLLECTION = '_magic_link_grants'\n\n/** HKDF `info` for the AES-GCM content key. Version-namespaced. */\nexport const MAGIC_LINK_CONTENT_INFO_PREFIX = 'noydb-magic-link-content-v1:'\n\n/** HKDF `info` for the AES-KW KEK. Matches `@noy-db/on-magic-link`. */\nexport const MAGIC_LINK_KEK_INFO_PREFIX = 'noydb-magic-link-v1:'\n\n// ─── Types ──────────────────────────────────────────────────────────────\n\n/**\n * Decrypted payload of a magic-link grant record. Mirrors\n * `DelegationToken` in `team/delegation.ts` but tracked separately\n * because the two flows persist under different collections + envelope\n * encryption schemes.\n */\nexport interface MagicLinkGrantPayload {\n readonly id: string\n readonly toUser: string\n readonly fromUser: string\n readonly tier: number\n /** Collection name or `null` for the vault-wide tier DEK. */\n readonly collection: string | null\n /** Optional specific record id scope. */\n readonly record?: string\n /** ISO timestamp — grant expires at this instant. */\n readonly until: string\n /** AES-KW-wrapped tier DEK, unwrap with the magic-link KEK. */\n readonly wrappedDek: string\n /** ISO timestamp the grant was issued. */\n readonly createdAt: string\n /** Optional caller-provided label (surfaced in audit UIs). */\n readonly note?: string\n}\n\nexport interface IssueMagicLinkGrantOptions {\n readonly toUser: string\n readonly tier: number\n readonly collection?: string\n readonly record?: string\n readonly until: Date | string\n readonly note?: string\n}\n\nexport interface MagicLinkGrantRecord {\n /** Store record id — `<token>` or `<token>:<index>` for batch entries. */\n readonly recordId: string\n readonly payload: MagicLinkGrantPayload\n}\n\n// ─── Key derivation ─────────────────────────────────────────────────────\n\n/**\n * Derive the AES-GCM content key from the same HKDF inputs used for\n * the magic-link KEK. Different `info` suffix → domain-separated key.\n *\n * Exported so the `@noy-db/on-magic-link` package can share the exact\n * derivation path without cross-dependency between the two modules.\n */\nexport async function deriveMagicLinkContentKey(\n serverSecret: string | Uint8Array<ArrayBuffer>,\n token: string,\n vault: string,\n): Promise<EnclaveKey> {\n const subtle = globalThis.crypto.subtle\n const ikmBytes =\n serverSecret instanceof Uint8Array\n ? serverSecret\n : new TextEncoder().encode(serverSecret)\n const tokenBytes = new TextEncoder().encode(token)\n const saltBuffer = await subtle.digest('SHA-256', tokenBytes)\n const info = new TextEncoder().encode(MAGIC_LINK_CONTENT_INFO_PREFIX + vault)\n const ikm = await subtle.importKey('raw', ikmBytes, 'HKDF', false, ['deriveKey'])\n return subtle.deriveKey(\n { name: 'HKDF', hash: 'SHA-256', salt: saltBuffer, info },\n ikm,\n { name: 'AES-GCM', length: 256 },\n false,\n ['encrypt', 'decrypt'],\n )\n}\n\n// ─── Issue ──────────────────────────────────────────────────────────────\n\n/**\n * Persist a magic-link grant record. Caller derives + provides both\n * the content key and the KEK; this function performs the wrap/encrypt\n * and writes the envelope.\n *\n * `recordId` lets the caller use either the bare token (primary grant)\n * or a suffixed id (batch entry). The writer is responsible for\n * collision-avoidance across batch entries.\n */\nexport async function writeMagicLinkGrant(\n store: NoydbStore,\n vault: string,\n grantor: UnlockedKeyring,\n contentKey: EnclaveKey,\n grantKek: EnclaveKey,\n recordId: string,\n opts: IssueMagicLinkGrantOptions,\n): Promise<MagicLinkGrantRecord> {\n const collectionName = opts.collection ?? null\n const sourceKey = collectionName\n ? dekKey(collectionName, opts.tier)\n : `__any#${opts.tier}`\n const sourceDek = grantor.deks.get(sourceKey)\n if (!sourceDek) {\n throw new DelegationTargetMissingError(\n `grantor cannot find tier ${opts.tier} DEK for ${collectionName ?? '(any)'}`,\n )\n }\n const wrappedDek = await wrapKey(sourceDek, grantKek)\n\n const until = typeof opts.until === 'string' ? opts.until : opts.until.toISOString()\n const createdAt = new Date().toISOString()\n const payload: MagicLinkGrantPayload = {\n id: recordId,\n toUser: opts.toUser,\n fromUser: grantor.userId,\n tier: opts.tier,\n collection: collectionName,\n ...(opts.record && { record: opts.record }),\n until,\n wrappedDek,\n createdAt,\n ...(opts.note && { note: opts.note }),\n }\n\n const { iv, data } = await encrypt(JSON.stringify(payload), contentKey)\n const envelope: EncryptedEnvelope = {\n _noydb: 1,\n _v: 1,\n _ts: createdAt,\n _iv: iv,\n _data: data,\n _by: grantor.userId,\n }\n await store.put(vault, MAGIC_LINK_GRANTS_COLLECTION, recordId, envelope)\n return { recordId, payload }\n}\n\n// ─── Claim ──────────────────────────────────────────────────────────────\n\n/**\n * Fetch + decrypt a single magic-link grant record by id. Returns null\n * when the record is absent OR when decryption fails (wrong server\n * secret, wrong vault, tampered envelope) — callers treat a null as\n * \"this URL is not valid for this server\".\n *\n * The returned payload's `wrappedDek` is still AES-KW-wrapped; the\n * caller unwraps it with the magic-link KEK to obtain the tier DEK.\n */\nexport async function readMagicLinkGrantRecord(\n store: NoydbStore,\n vault: string,\n contentKey: EnclaveKey,\n recordId: string,\n): Promise<MagicLinkGrantPayload | null> {\n const env = await store.get(vault, MAGIC_LINK_GRANTS_COLLECTION, recordId)\n if (!env) return null\n try {\n const json = await openEnvelopeJson(env, contentKey)\n return JSON.parse(json) as MagicLinkGrantPayload\n } catch {\n return null\n }\n}\n\n/**\n * Enumerate every grant record sharing the magic-link `token` prefix\n * (i.e. the primary `<token>` entry plus any `<token>:*` batch entries).\n * Expired grants are still returned — the caller filters on `until`.\n */\nexport async function listMagicLinkGrants(\n store: NoydbStore,\n vault: string,\n contentKey: EnclaveKey,\n token: string,\n): Promise<MagicLinkGrantPayload[]> {\n const ids = await store.list(vault, MAGIC_LINK_GRANTS_COLLECTION)\n const matching = ids.filter(id => id === token || id.startsWith(`${token}:`))\n const out: MagicLinkGrantPayload[] = []\n for (const id of matching) {\n const payload = await readMagicLinkGrantRecord(store, vault, contentKey, id)\n if (payload) out.push(payload)\n }\n return out\n}\n\n/**\n * Unwrap the tier DEK from a grant payload using the magic-link KEK.\n * Thin wrapper around `unwrapKey` — provided so the claimant can avoid\n * importing `crypto.js` directly.\n */\nexport async function unwrapMagicLinkGrant(\n payload: MagicLinkGrantPayload,\n grantKek: EnclaveKey,\n): Promise<EnclaveKey> {\n return unwrapKey(payload.wrappedDek, grantKek)\n}\n\n/**\n * Delete a magic-link grant (primary + every batch entry sharing the\n * token). Safe to call when nothing exists.\n */\nexport async function revokeMagicLinkGrant(\n store: NoydbStore,\n vault: string,\n token: string,\n): Promise<number> {\n const ids = await store.list(vault, MAGIC_LINK_GRANTS_COLLECTION)\n const matching = ids.filter(id => id === token || id.startsWith(`${token}:`))\n for (const id of matching) {\n await store.delete(vault, MAGIC_LINK_GRANTS_COLLECTION, id)\n }\n return matching.length\n}\n\n// ─── Helpers ────────────────────────────────────────────────────────────\n\n/**\n * Compose the batch-entry record id. `index === 0` → bare token.\n * Subsequent entries use `<token>:<index>` so `store.list()` can\n * enumerate them all by common prefix.\n */\nexport function magicLinkGrantRecordId(token: string, index: number): string {\n return index === 0 ? token : `${token}:${index}`\n}\n\n/**\n * True when the payload's `until` is in the past relative to `now`.\n * Kept here (rather than inlined) so the semantics stay aligned with\n * the canonical `DelegationToken` expiry check.\n */\nexport function isMagicLinkGrantExpired(\n payload: MagicLinkGrantPayload,\n now: Date = new Date(),\n): boolean {\n return payload.until <= now.toISOString()\n}\n","/**\n * Multi-user team capability contract (#267 Track A tail — the\n * keyring-grant → team split). Lives on the `/with` port (the one seam the\n * kernel spine may import statically) so `Noydb` can hold the `NO_TEAM`\n * floor default without a spine→service static import.\n *\n * The active engine (`withTeam()` in `with-party/team/active.ts`)\n * statically links the grant/revoke/rotate keyring engines from\n * `keyring.ts` — bundle-charged to consumers of the `@noy-db/hub/team`\n * subpath, never to the single-user floor. {@link NO_TEAM} (the floor\n * default) throws {@link TeamNotEnabledError}.\n *\n * `Noydb.grant` / `Noydb.revoke` / `Noydb.rotate` delegate here, passing\n * their `TeamFacade` — the facade owns the policy-gate + keyring plumbing\n * (`runGrant` / `runRevoke` / `runRotate`) and receives the engine as an\n * argument from the strategy.\n *\n * Deliberately NOT gated (single-user primitives): owner keyring creation,\n * unlock, `listUsers`, `updateUser`, passphrase rotate/recover, and the\n * `createDeedOwner` free function (no createNoydb instance to gate against —\n * the same carve-out as `liberateVault`).\n * @internal\n */\nimport type { GrantOptions, RevokeOptions, FactorProofBundle } from '../../kernel/types.js'\nimport { TeamNotEnabledError } from '../../kernel/errors.js'\nimport type { TeamFacade } from '../../with-party/team/noydb-facade.js'\n\nexport interface TeamStrategy {\n grant(team: TeamFacade, vault: string, options: GrantOptions, factors?: FactorProofBundle): Promise<void>\n revoke(team: TeamFacade, vault: string, options: RevokeOptions, factors?: FactorProofBundle): Promise<void>\n rotate(team: TeamFacade, vault: string, collections: string[]): Promise<void>\n}\n\n/**\n * No-op stub — the floor default. Every multi-user team operation throws\n * {@link TeamNotEnabledError}; opt in with `teamStrategy: withTeam()` in\n * createNoydb. @internal\n */\nexport const NO_TEAM: TeamStrategy = {\n async grant() { throw new TeamNotEnabledError() },\n async revoke() { throw new TeamNotEnabledError() },\n async rotate() { throw new TeamNotEnabledError() },\n}\n","/**\n * Tier-1 change flows — `rotatePassphrase` (user remembers old) and\n * `recoverPassphrase` (user supplies a recovery proof).\n *\n * The two flows share the post-verification half — fresh salt, fresh\n * KEK, rewrap every DEK — and differ only in how they re-derive the\n * old KEK:\n *\n * - **Rotate**: derive from the supplied `oldPassphrase`.\n * - **Recover (paper)**: unwrap from a `RecoveryCodeEntry` using a\n * user-supplied recovery code. The entry is burned on success.\n *\n * The non-paper recovery profiles (Shamir, multi-channel,\n * admin-mediated) are not yet wired — calling them throws\n * {@link RecoveryProfileNotImplementedError} with a tracking link.\n *\n * @module\n */\nimport type { NoydbStore, KeyringFile } from '../../kernel/types.js'\nimport { NOYDB_KEYRING_VERSION } from '../../kernel/types.js'\nimport {\n deriveKey,\n generateSalt,\n wrapKey,\n unwrapKey,\n bufferToBase64,\n base64ToBuffer,\n type EnclaveKey,\n} from '../../kernel/enclave/index.js'\nimport { InvalidKeyError, NoAccessError, RecoveryProfileNotImplementedError } from '../../kernel/errors.js'\nimport {\n loadPaperRecoveryEntries,\n burnPaperRecoveryEntry,\n unwrapDeksFromPaperEntry,\n loadShamirRecoveryEntries,\n unwrapDeksFromShamirEntry,\n type PaperRecoveryEntry,\n type ShamirRecoveryEntry,\n} from './recovery.js'\nimport type { ShamirRecoveryProvider } from './shamir-recovery-provider.js'\nimport { assertStrongPassphrase, type PassphrasePolicy } from '../../kernel/validation.js'\nimport type { UnlockedKeyring } from './keyring.js'\nimport { mintKeyringCanary } from './keyring.js'\nimport type { KeyringAuthenticator } from '../../kernel/types.js'\nimport type { EnrollAuthenticatorOptions } from './authenticators.js'\nimport { ValidationError } from '../../kernel/errors.js'\n\n/**\n * Context handed to a {@link SlotRewrapCeremony} when `rotatePassphrase`\n * preserves a tier-2 slot. The ceremony's job is to re-derive its\n * method-specific wrapping material (PRF assertion, PBKDF2 of the\n * password, etc.) and wrap the freshly rewrapped DEK set under\n * the new wrapping key.\n *\n * Two surfaces are exposed:\n *\n * - `newDeks` — the rewrapped (extractable) DEK set the slot will\n * wrap. This is what `mintPaperRecoveryEntry` / `enrollPassword-\n * Authenticator` / `wrapKeyringSummary` (in `@noy-db/on-webauthn`)\n * all consume; effectively the canonical input for every\n * post-Path C tier-2 ceremony.\n *\n * - `newKek` — the freshly-derived KEK (extractable for the\n * ceremony scope only). Only relevant for forward-compatibility\n * with a hypothetical future on-* package that wants to wrap the\n * KEK itself under a method-derived key. None of the shipped\n * on-* packages need this; they all operate on `newDeks`.\n *\n * The ceremony MUST preserve `oldSlot.id` and `oldSlot.method` in the\n * returned `EnrollAuthenticatorOptions`. Hub validates these — a\n * mismatch throws `ValidationError` (prevents slot-type swap mid-\n * rotation, e.g. converting a webauthn slot to a password slot under\n * cover of preservation).\n */\nexport interface SlotRewrapContext {\n readonly newKek: EnclaveKey\n readonly newDeks: Map<string, EnclaveKey>\n readonly oldSlot: KeyringAuthenticator\n}\n\n/**\n * Callback that re-enrolls one tier-2 slot during `rotatePassphrase`.\n * Returns the new slot's `EnrollAuthenticatorOptions` — same shape\n * the consumer would pass to `db.enrollAuthenticator` for a fresh\n * enrollment. Hub persists the result atomically with the rotation.\n */\nexport type SlotRewrapCeremony = (\n ctx: SlotRewrapContext,\n) => Promise<EnrollAuthenticatorOptions>\n\n/** Caller payload for {@link rotatePassphrase}. */\nexport interface RotatePassphraseInput {\n readonly oldPassphrase: string\n readonly newPassphrase: string\n readonly passphrasePolicy?: PassphrasePolicy\n readonly allowWeakPassphrase?: boolean\n /**\n * Map of slot id → re-enrolment ceremony. Slots whose id appears\n * here are PRESERVED across rotation (the ceremony re-derives the\n * method-specific wrapping under the new keyring); slots whose id\n * is absent are DROPPED (the pre-slot-ceremony behavior).\n *\n * Without this map, `rotatePassphrase` wipes every tier-2 slot. Consumers building a\n * \"rotate without losing my biometric\" flow supply ceremonies for\n * each slot they want to keep.\n *\n * If a ceremony throws, the entire rotation throws — no partial\n * state. Callers wrap individual ceremonies in try/catch + return\n * a sentinel if they want graceful degradation per slot.\n *\n * Added when slot-ceremony rewrapping landed.\n */\n readonly slotCeremonies?: { readonly [slotId: string]: SlotRewrapCeremony }\n}\n\n/**\n * Re-derive the user's KEK from `oldPassphrase`, rewrap every DEK\n * under a freshly-derived KEK from `newPassphrase`, and persist.\n *\n * Tier-2 authenticator slots are dropped UNLESS the caller supplies\n * a `slotCeremonies` map — each ceremony re-derives its\n * method-specific wrapping under the new keyring, and hub persists\n * the rewrapped slots atomically with the rotation. Slots whose id\n * isn't in the map are still dropped.\n *\n * @throws `InvalidKeyError` if `oldPassphrase` does not unwrap the keyring.\n * @throws `WeakPassphraseError` if `newPassphrase` fails the strength rule.\n * @throws `ValidationError` if a ceremony's result mismatches the\n * slot's id or method (anti-slot-swap guard).\n */\nexport async function rotatePassphrase(\n store: NoydbStore,\n vault: string,\n userId: string,\n input: RotatePassphraseInput,\n): Promise<UnlockedKeyring> {\n if (!input.allowWeakPassphrase) {\n assertStrongPassphrase(input.newPassphrase, input.passphrasePolicy)\n }\n\n const env = await store.get(vault, '_keyring', userId)\n if (!env) {\n throw new NoAccessError(`No keyring found for user \"${userId}\" in vault \"${vault}\".`)\n }\n const file = JSON.parse(env._data) as KeyringFile\n const oldSalt = base64ToBuffer(file.salt)\n const oldKek = await deriveKey(input.oldPassphrase, oldSalt)\n\n // Unwrap every DEK with the OLD KEK first — this also validates the\n // passphrase (a bad KEK throws InvalidKeyError on the first unwrap).\n const deks = new Map<string, EnclaveKey>()\n for (const [coll, wrapped] of Object.entries(file.deks)) {\n deks.set(coll, await unwrapKey(wrapped, oldKek))\n }\n\n const newSalt = generateSalt()\n const newKek = await deriveKey(input.newPassphrase, newSalt)\n\n // Rewrap with the new KEK.\n const wrappedDeks: Record<string, string> = {}\n for (const [coll, dek] of deks) {\n wrappedDeks[coll] = await wrapKey(dek, newKek)\n }\n\n // Slot rewrap. Without slotCeremonies, we drop every existing\n // slot. With a ceremony map, slots whose id appears in the map\n // are preserved; the rest are dropped.\n const oldSlots = file.authenticators ?? []\n const newSlots: KeyringAuthenticator[] = []\n if (input.slotCeremonies && oldSlots.length > 0) {\n for (const oldSlot of oldSlots) {\n const ceremony = input.slotCeremonies[oldSlot.id]\n if (!ceremony) continue // drop — not in slotCeremonies map\n\n const result = await ceremony({ newKek, newDeks: deks, oldSlot })\n\n // Anti-slot-swap guard. The ceremony MUST preserve identity —\n // a mismatch would let the consumer convert a webauthn slot to\n // a password slot mid-rotation, which would silently change\n // the security profile of the slot under cover of \"rotation.\"\n if (result.id !== oldSlot.id) {\n throw new ValidationError(\n `slotCeremonies['${oldSlot.id}'] returned id=\"${result.id}\". ` +\n 'The id must match the rotated slot — a ceremony cannot ' +\n 'change a slot\\'s identity.',\n )\n }\n if (result.method !== oldSlot.method) {\n throw new ValidationError(\n `slotCeremonies['${oldSlot.id}'] returned method=\"${result.method}\", ` +\n `expected \"${oldSlot.method}\". The method must match the rotated ` +\n 'slot — a ceremony cannot change the auth method (e.g. webauthn ' +\n '→ password) under cover of rotation.',\n )\n }\n // wrapKind absent on legacy slots / wrap-KEK enroll inputs; treat as 'kek'.\n const oldWrapKind = oldSlot.wrapKind ?? 'kek'\n const newWrapKind = result.wrapKind ?? 'kek'\n if (oldWrapKind !== newWrapKind) {\n throw new ValidationError(\n `slotCeremonies['${oldSlot.id}'] returned wrapKind=\"${newWrapKind}\", ` +\n `expected \"${oldWrapKind}\". The wrap format must match the rotated ` +\n 'slot — a ceremony cannot change the wrap shape (e.g. wrap-KEK → ' +\n 'wrap-DEKs) under cover of rotation, since that would silently ' +\n 'change the session tier produced at unlock.',\n )\n }\n\n // Build the persisted slot from the ceremony result. Mirrors\n // the same construction `enrollAuthenticator` does — wrap-DEKs\n // variants carry { wrapped_deks, iv }; wrap-KEK variants\n // carry { wrapped_kek }.\n const baseFields = {\n id: result.id,\n method: result.method,\n // Preserve original enrolled_at — rotation is rewrapping, not\n // re-enrollment. The slot's enrolment timestamp tracks when\n // the user originally added the slot, not when it was last\n // rewrapped. Forensics consumers reading enrolled_at are\n // tracking the slot's ORIGIN, not its CURRENT wrapping.\n enrolled_at: oldSlot.enrolled_at,\n enrolled_via_tier: result.enrolled_via_tier ?? oldSlot.enrolled_via_tier,\n meta: result.meta,\n } as const\n const newSlot: KeyringAuthenticator = result.wrapKind === 'deks'\n ? {\n ...baseFields,\n wrapKind: 'deks',\n wrapped_deks: result.wrapped_deks,\n iv: result.iv,\n }\n : {\n ...baseFields,\n wrapped_kek: result.wrapped_kek,\n }\n newSlots.push(newSlot)\n }\n }\n\n const canary = await mintKeyringCanary(newKek)\n const next: KeyringFile = {\n ...file,\n _noydb_keyring: NOYDB_KEYRING_VERSION,\n deks: wrappedDeks,\n salt: bufferToBase64(newSalt),\n authenticators: newSlots,\n canary,\n }\n\n await writeKeyringFile(store, vault, userId, next)\n\n return {\n userId: file.user_id,\n displayName: file.display_name,\n role: file.role,\n permissions: file.permissions,\n deks,\n kek: newKek,\n salt: newSalt,\n authenticators: newSlots,\n ...(file.export_capability !== undefined && { exportCapability: file.export_capability }),\n ...(file.import_capability !== undefined && { importCapability: file.import_capability }),\n }\n}\n\n/**\n * Caller payload for {@link recoverPassphrase}.\n *\n * `paper` and `shamir` are wired end-to-end.\n * The remaining two profiles (`multi-channel`, `admin-mediated`)\n * stay outside the union and throw\n * {@link RecoveryProfileNotImplementedError} at the runtime guard\n * when bypassed via `as unknown as RecoveryProof`.\n */\nexport type RecoveryProof =\n | { readonly profile: 'paper'; readonly payload: { readonly code: string } }\n | { readonly profile: 'shamir'; readonly payload: {\n /** Optional disambiguator when multiple Shamir entries are enrolled.\n * When omitted, hub tries each entry until one combines. */\n readonly entryId?: string\n /** K or more opaque share strings, as returned by `ShamirRecoveryProvider.splitToShares`. */\n readonly shares: ReadonlyArray<string>\n } }\n\nexport interface RecoverPassphraseInput {\n readonly newPassphrase: string\n readonly recoveryProof: RecoveryProof\n readonly passphrasePolicy?: PassphrasePolicy\n readonly allowWeakPassphrase?: boolean\n /**\n * After a successful paper-recovery, replace ALL remaining recovery\n * entries with freshly-minted ones. Defaults to `true` (defensive).\n *\n * Rationale: the user just demonstrated they had access\n * to AT LEAST one code. The remaining codes from the same printed\n * sheet may also be compromised — photographed, leaked via a\n * screen-share slip, or in the hands of whoever stole the sheet.\n * Auto-rotation closes the window without requiring consumer action.\n *\n * Set to `false` to preserve the original behavior (only the matched\n * code is burned; the rest stay valid).\n *\n * Hub-side orchestration is non-atomic with the recovery itself:\n * if the rotation step fails after a successful burn, the user\n * falls back to the pre-rotation state (remaining codes still\n * valid). Strictly safer than the previous default — a failed\n * rotation degrades gracefully rather than leaving the vault\n * locked or codes dual-existing.\n */\n readonly rotateRemainingCodes?: boolean\n /**\n * Number of fresh codes to mint when `rotateRemainingCodes` is on.\n * Defaults to the count of remaining entries POST-burn (e.g. if\n * the user enrolled 8 originally and just consumed 1, defaults to\n * 7). Pass an explicit number to mint a different count — useful\n * when the consumer wants to refresh to a target N regardless of\n * how many were left.\n */\n readonly newCodeCount?: number\n /**\n * Override the default raw-code generator. The default is hub's\n * {@link generateULID} — uppercase Crockford-Base32, 26 chars,\n * passes through `normalizePaperCode` untouched.\n *\n * Pass `() => generateRawCode()` from `@noy-db/on-recovery` when\n * the consumer prefers the Base32 + checksum format with hyphenated\n * display. The `mintPaperRecoveryEntry` helper accepts any string —\n * the generator just needs to produce a high-entropy unique value.\n */\n readonly codeGenerator?: () => string\n}\n\n/**\n * Return shape of `db.recoverPassphrase`. `newCodes` is populated when\n * `rotateRemainingCodes` was enabled and at least one entry was\n * rotated; an empty array means no rotation happened (rotation\n * disabled, or no remaining codes after burn). Show the codes to the\n * user once — they are the canonical credential for future recovery\n * and CANNOT be retrieved again.\n */\nexport interface RecoverPassphraseResult {\n readonly newCodes: readonly string[]\n}\n\n/**\n * Input for {@link Noydb.rotateRecovery} — deliberate\n * recovery-credential regeneration when the user knows their\n * passphrase but wants a fresh sheet (paper) or fresh shares\n * (shamir). Symmetric to {@link RotatePassphraseInput}.\n */\nexport type RotateRecoveryOptions =\n | {\n readonly profile: 'paper'\n /** How many fresh codes to mint. Default: existing sheet size. */\n readonly count?: number\n /** Optional code generator — see {@link RecoverPassphraseInput.codeGenerator}. */\n readonly codeGenerator?: () => string\n }\n | {\n readonly profile: 'shamir'\n /** New threshold. */\n readonly k: number\n /** New total share count. */\n readonly n: number\n /** Disambiguator when multiple Shamir entries exist; required if there are 2+. */\n readonly entryId?: string\n /** Optional updated label. */\n readonly label?: string\n }\n\n/**\n * Result of {@link Noydb.rotateRecovery}. Shape varies by profile:\n *\n * - `paper` → `{ newCodes: string[] }` (and `entryId === 'paper-batch'`)\n * - `shamir` → `{ newShares: string[], entryId }`\n *\n * `newCodes` is populated for paper rotations; `newShares` for\n * Shamir rotations. Both are show-once — the hub does not\n * retain them.\n */\nexport interface RotateRecoveryResult {\n readonly newCodes?: readonly string[]\n readonly newShares?: readonly string[]\n readonly entryId?: string\n}\n\n/**\n * Result of {@link Noydb.enrollRecovery}. Shape varies by profile:\n *\n * - `paper` → `{ entryId: 'paper-batch' }` (caller minted the\n * entries; this is a sentinel since paper enrollments are batch-shaped).\n * - `shamir` → `{ entryId, shares: string[] }` — shares are\n * show-once; the hub does not retain them.\n */\nexport interface EnrollRecoveryResult {\n readonly entryId: string\n readonly shares?: readonly string[]\n}\n\n/**\n * Input shape for {@link Noydb.enrollRecovery} and\n * {@link Noydb.openVaultAndEnrollRecovery}. Discriminated\n * union over recovery profiles.\n *\n * - `paper`: caller pre-mints entries (typically via\n * `mintPaperRecoveryEntry` or `@noy-db/on-recovery`'s\n * `generateRecoveryCodeSet`) and passes them in. The hub stores\n * them and surfaces an opaque batch id.\n * - `shamir`: hub mints the recovery secret + the shares at\n * enrollment time. The shares are returned in\n * {@link EnrollRecoveryResult.shares} (show-once); the hub never\n * retains them.\n *\n * Multi-channel and admin-mediated will be added when the respective\n * dispatch slices ship.\n */\nexport type RecoveryEnrollmentInput =\n | { readonly profile: 'paper'; readonly entries: ReadonlyArray<PaperRecoveryEntry> }\n | {\n readonly profile: 'shamir'\n readonly k: number\n readonly n: number\n readonly label?: string\n readonly entryId?: string\n }\n\n/**\n * Reset the user's passphrase using a recovery proof.\n * Supports `'paper'` and `'shamir'` profiles. The other profiles throw\n * {@link RecoveryProfileNotImplementedError}.\n *\n * On success, the used recovery entry is burned (deleted from the\n * stored set).\n */\nexport async function recoverPassphrase(\n provider: ShamirRecoveryProvider | undefined,\n store: NoydbStore,\n vault: string,\n userId: string,\n input: RecoverPassphraseInput,\n): Promise<UnlockedKeyring> {\n if (!input.allowWeakPassphrase) {\n assertStrongPassphrase(input.newPassphrase, input.passphrasePolicy)\n }\n\n // Runtime defense-in-depth: the type narrows to 'paper' | 'shamir',\n // but a consumer bypassing TS via\n // `as unknown as RecoveryProof` should still hit a clear error\n // rather than silently fall into a handler with a malformed payload.\n const profile = (input.recoveryProof as { profile: string }).profile\n if (profile === 'paper') {\n return recoverViaPaperCode(store, vault, userId, input)\n }\n if (profile === 'shamir') {\n return recoverViaShamir(provider, store, vault, userId, input)\n }\n throw new RecoveryProfileNotImplementedError(\n profile,\n 'https://github.com/vLannaAi/noy-db/issues/196',\n )\n}\n\nasync function recoverViaPaperCode(\n store: NoydbStore,\n vault: string,\n userId: string,\n input: RecoverPassphraseInput,\n): Promise<UnlockedKeyring> {\n if (input.recoveryProof.profile !== 'paper') throw new Error('unreachable')\n const { code } = input.recoveryProof.payload\n\n const env = await store.get(vault, '_keyring', userId)\n if (!env) {\n throw new NoAccessError(`No keyring found for user \"${userId}\" in vault \"${vault}\".`)\n }\n const file = JSON.parse(env._data) as KeyringFile\n\n const entries = await loadPaperRecoveryEntries(store, vault)\n if (entries.length === 0) {\n throw new NoAccessError(\n `No paper-recovery entries enrolled for vault \"${vault}\". ` +\n 'Enroll via `db.enrollRecovery({ profile: \"paper\", entries })` before relying on recovery.',\n )\n }\n\n const normalized = normalizePaperCode(code)\n let recovered: { deks: Map<string, EnclaveKey>; entry: PaperRecoveryEntry } | undefined\n for (const entry of entries) {\n try {\n const deks = await unwrapDeksFromPaperEntry(entry, normalized)\n recovered = { deks, entry }\n break\n } catch {\n // wrong code for this entry — try the next one\n }\n }\n if (!recovered) {\n throw new InvalidKeyError(\n 'Recovery code does not match any enrolled paper entry. The code may have been ' +\n 'previously used (single-use) or typed incorrectly.',\n )\n }\n\n const deks = recovered.deks\n\n // Fresh salt + KEK from the new passphrase, rewrap.\n const newSalt = generateSalt()\n const newKek = await deriveKey(input.newPassphrase, newSalt)\n const wrappedDeks: Record<string, string> = {}\n for (const [coll, dek] of deks) {\n wrappedDeks[coll] = await wrapKey(dek, newKek)\n }\n\n const canary = await mintKeyringCanary(newKek)\n const next: KeyringFile = {\n ...file,\n _noydb_keyring: NOYDB_KEYRING_VERSION,\n deks: wrappedDeks,\n salt: bufferToBase64(newSalt),\n authenticators: [], // tier-2 slots wrap old KEK, drop them\n canary,\n }\n\n // Burn first, then rewrite the keyring. The two writes are not\n // atomic — if the second fails, the safer ordering is:\n //\n // 1. Code burned, keyring untouched: user keeps their old passphrase\n // and loses one recovery code (recoverable: contact admin / use\n // another code).\n //\n // 2. Keyring rewritten, code unburned: user has rotated, but the\n // consumed code REMAINS VALID. Anyone with access to the paper\n // sheet can use it again. Security regression.\n //\n // Burning first picks (1) over (2).\n await burnPaperRecoveryEntry(store, vault, recovered.entry.codeId)\n await writeKeyringFile(store, vault, userId, next)\n\n return {\n userId: file.user_id,\n displayName: file.display_name,\n role: file.role,\n permissions: file.permissions,\n deks,\n kek: newKek,\n salt: newSalt,\n authenticators: [],\n ...(file.export_capability !== undefined && { exportCapability: file.export_capability }),\n ...(file.import_capability !== undefined && { importCapability: file.import_capability }),\n }\n}\n\n/**\n * Mirror of `@noy-db/on-recovery/parseRecoveryCode`. Inlined so the\n * hub does not gain a peer dep on on-recovery — both implementations\n * follow the same RFC 4648 Base32 + checksum format and round-trip\n * through the same KDF.\n *\n * Accepts hyphenated, lowercase, or whitespace-padded input.\n */\nfunction normalizePaperCode(input: string): string {\n return input.toUpperCase().replace(/[\\s\\-_]/g, '')\n}\n\n/**\n * Recover the user's keyring via the Shamir profile.\n *\n * 1. Decode each supplied share string into a {@link RawShare}.\n * 2. Load `_meta/recovery-shamir` entries.\n * 3. If `payload.entryId` is supplied, restrict to that entry; else\n * iterate over all entries and try each until one combines.\n * 4. For each candidate: filter shares to those whose `(k, n)`\n * match the entry's parameters, then attempt\n * `unwrapDeksFromShamirEntry`. AES-GCM auth-tag failure means\n * the combined secret doesn't match — try the next entry.\n * 5. With unwrapped DEKs: derive fresh KEK from `newPassphrase` +\n * fresh salt, rewrap, write the keyring.\n * 6. Shamir entries are NOT burned on recovery (shares reusable);\n * explicit {@link Noydb.rotateRecovery} is the refresh ceremony.\n */\nasync function recoverViaShamir(\n provider: ShamirRecoveryProvider | undefined,\n store: NoydbStore,\n vault: string,\n userId: string,\n input: RecoverPassphraseInput,\n): Promise<UnlockedKeyring> {\n if (input.recoveryProof.profile !== 'shamir') throw new Error('unreachable')\n const { entryId: requestedEntryId, shares: shareStrings } = input.recoveryProof.payload\n\n if (shareStrings.length === 0) {\n throw new ValidationError(\n 'Shamir recovery requires at least one share; received an empty array.',\n )\n }\n\n const env = await store.get(vault, '_keyring', userId)\n if (!env) {\n throw new NoAccessError(`No keyring found for user \"${userId}\" in vault \"${vault}\".`)\n }\n const file = JSON.parse(env._data) as KeyringFile\n\n const allEntries = await loadShamirRecoveryEntries(store, vault)\n if (allEntries.length === 0) {\n throw new NoAccessError(\n `No Shamir-recovery entries enrolled for vault \"${vault}\". `\n + 'Enroll via `db.enrollRecovery({ profile: \"shamir\", k, n })` before relying on recovery.',\n )\n }\n\n if (!provider) {\n throw new Error(\n \"shamir recovery requires a ShamirRecoveryProvider — pass \"\n + \"shamirRecovery: shamirRecoveryProvider() from '@noy-db/on-shamir' to createNoydb()\",\n )\n }\n\n // Restrict to a specific entry when entryId supplied.\n let candidates: ReadonlyArray<ShamirRecoveryEntry>\n if (requestedEntryId !== undefined) {\n candidates = allEntries.filter(e => e.entryId === requestedEntryId)\n if (candidates.length === 0) {\n throw new NoAccessError(\n `No Shamir-recovery entry with entryId=\"${requestedEntryId}\" found `\n + `in vault \"${vault}\". Available entries: `\n + allEntries.map(e => `\"${e.entryId}\"`).join(', '),\n )\n }\n } else {\n candidates = allEntries\n }\n\n // Try each candidate entry. Pass all share strings to the provider;\n // provider.combineShares validates and throws on mismatch — the\n // AES-GCM auth-tag is an additional guard.\n let recoveredDeks: Map<string, EnclaveKey> | undefined\n for (const entry of candidates) {\n if (shareStrings.length < entry.k) {\n // Not enough shares for this entry — could still match another.\n continue\n }\n try {\n const deks = await unwrapDeksFromShamirEntry(provider, entry, shareStrings)\n recoveredDeks = deks\n break\n } catch {\n // provider.combineShares threw (malformed/mismatched shares) or\n // AES-GCM auth-tag failure → try the next entry.\n }\n }\n\n if (!recoveredDeks) {\n // Distinguish \"below-threshold\" from \"no entry matches\" so the\n // error message is actionable.\n const minK = Math.min(...candidates.map(e => e.k))\n if (shareStrings.length < minK) {\n throw new InvalidKeyError(\n `Insufficient Shamir shares to combine: the smallest enrolled threshold is ${minK}, `\n + `but only ${shareStrings.length} share${shareStrings.length === 1 ? ' was' : 's were'} provided.`,\n )\n }\n throw new InvalidKeyError(\n 'Shamir shares do not match any enrolled entry. Possible causes: '\n + 'shares were tampered with, came from a different enrollment, '\n + 'or the entry was rotated after these shares were distributed.',\n )\n }\n\n // Mint fresh KEK from new passphrase, rewrap DEKs (mirrors paper).\n const newSalt = generateSalt()\n const newKek = await deriveKey(input.newPassphrase, newSalt)\n const wrappedDeks: Record<string, string> = {}\n for (const [coll, dek] of recoveredDeks) {\n wrappedDeks[coll] = await wrapKey(dek, newKek)\n }\n\n const canary = await mintKeyringCanary(newKek)\n const next: KeyringFile = {\n ...file,\n _noydb_keyring: NOYDB_KEYRING_VERSION,\n deks: wrappedDeks,\n salt: bufferToBase64(newSalt),\n authenticators: [], // tier-2 slots wrap old KEK, drop them on recovery\n canary,\n }\n\n // No burn: Shamir entries persist across recoveries. Explicit\n // rotateRecovery is the refresh ceremony.\n await writeKeyringFile(store, vault, userId, next)\n\n return {\n userId: file.user_id,\n displayName: file.display_name,\n role: file.role,\n permissions: file.permissions,\n deks: recoveredDeks,\n kek: newKek,\n salt: newSalt,\n authenticators: [],\n ...(file.export_capability !== undefined && { exportCapability: file.export_capability }),\n ...(file.import_capability !== undefined && { importCapability: file.import_capability }),\n }\n}\n\nasync function writeKeyringFile(\n store: NoydbStore,\n vault: string,\n userId: string,\n file: KeyringFile,\n): Promise<void> {\n const envelope = {\n _noydb: 1 as const,\n _v: 1,\n _ts: new Date().toISOString(),\n _iv: '',\n _data: JSON.stringify(file),\n }\n await store.put(vault, '_keyring', userId, envelope)\n}\n","/**\n * Atomic peer-recovery primitive.\n *\n * `recoverUser` is a SEPARATE operation from `revoke + grant`. It\n * exists because peer-recovery has different semantics than account\n * removal-then-reissue:\n *\n * 1. **Same identity preserved.** `userId`, `role`, `permissions`,\n * capability bits, user envelope (if any), policy override (if\n * any) all survive. Only the wrapping changes.\n * 2. **No key rotation.** The existing DEKs stay valid — every\n * OTHER principal in the vault keeps their access. Rotating\n * keys would invalidate every co-user's wrapping.\n * 3. **Atomic by construction.** A single `store.put` overwrites\n * `_keyring/<userId>` with the recovered file. No revoke step\n * means no partial-failure window.\n * 4. **Owner→owner natively allowed.** Two co-owners recovering\n * each other is the explicitly-intentional case (a partner\n * forgot the master phrase). The existing `canRevoke` rule that\n * blocks owner→owner is correct for `revoke` (which is account\n * *removal*) and intentionally NOT replicated here. The policy\n * gate `peer-recover-user` carries the freshness requirement.\n * 5. **Tier-2 slots dropped.** The slots wrap the OLD KEK under\n * method-derived keys; after recovery the KEK is re-derived\n * from the new temp passphrase. Match `rotatePassphrase`'s\n * precedent — the recovered user re-enrols slots after picking\n * their own phrase.\n *\n * Caller must be at least as privileged as the target. The hub\n * `db.recoverUser` method gates this with the `peer-recover-user`\n * policy gate (the `peer-recover-user` factor-proof requirement); the function below\n * enforces only the role + anti-privilege-escalation invariants.\n *\n * @module\n */\nimport type { NoydbStore, KeyringFile, Role } from '../../kernel/types.js'\nimport { NOYDB_KEYRING_VERSION } from '../../kernel/types.js'\nimport { deriveKey, generateSalt, wrapKey, bufferToBase64 } from '../../kernel/enclave/index.js'\nimport { NoAccessError, PermissionDeniedError, PrivilegeEscalationError } from '../../kernel/errors.js'\nimport { assertStrongPassphrase, type PassphrasePolicy } from '../../kernel/validation.js'\nimport type { UnlockedKeyring } from './keyring.js'\nimport { mintKeyringCanary } from './keyring.js'\n\n// FR-6: 'custodian' is deliberately ABSENT — an admin cannot peer-recover a\n// custodian (mirrors ADMIN_GRANTABLE_TARGETS: custodians are owner-managed\n// only). The owner CAN recover one (canRecover returns true for owner). As a\n// CALLER, a custodian recovers nobody (it is neither owner nor admin → false).\nconst ADMIN_RECOVERABLE_TARGETS: readonly Role[] = ['operator', 'viewer', 'client', 'admin']\n\n/**\n * Whether `callerRole` may recover `targetRole`.\n *\n * Differs from `canRevoke` (in `keyring.ts`) in one critical place:\n * **owner→owner IS allowed**. Peer recovery is the explicitly\n * intentional case (a co-owner forgot their phrase); the freshness\n * binding lives in the `peer-recover-user` policy gate, not in the\n * permission predicate.\n *\n * Admins can recover everyone they could grant (operator / viewer /\n * client / admin) but NOT owners — that boundary stays as a hard\n * structural rule even under recovery.\n */\nfunction canRecover(callerRole: Role, targetRole: Role): boolean {\n if (callerRole === 'owner') return true\n if (callerRole === 'admin') return ADMIN_RECOVERABLE_TARGETS.includes(targetRole)\n return false\n}\n\n/** Input shape for {@link recoverUser}. */\nexport interface RecoverUserOptions {\n /** Target user id whose keyring is being recovered. */\n readonly userId: string\n /**\n * Temporary passphrase under which the new keyring is wrapped.\n * The recipient should call `db.rotatePassphrase` immediately on\n * acceptance to choose their own phrase — this temp acts as a\n * single-use bridge in invite / peer-recovery flows.\n */\n readonly passphrase: string\n /** Override the target's role. Defaults to the existing target's role. */\n readonly role?: Role\n /** Override the target's display name. Defaults to existing. */\n readonly displayName?: string\n /** Validate phrase strength against the configured policy. */\n readonly validatePassphrase?: boolean\n /**\n * Skip phrase strength validation even when `validatePassphrase` is\n * set. The escape hatch matches `grant`'s shape — used when the\n * temp phrase is a high-entropy one-shot string that doesn't need\n * to satisfy the human-typeable rules.\n */\n readonly allowWeakPassphrase?: boolean\n /**\n * Optional explicit phrase policy override (passed through to\n * `assertStrongPassphrase`). Mirrors how `grant` accepts a custom\n * `PassphrasePolicy` for app-specific tightening.\n */\n readonly passphrasePolicy?: PassphrasePolicy\n}\n\n/**\n * Atomically rewrap the target user's keyring under a fresh temp\n * passphrase. Single store write; no revoke step; no key rotation.\n *\n * Caller's responsibilities (NOT enforced here):\n * - Run the `peer-recover-user` policy gate first via\n * `Noydb.checkGate` to enforce the freshness factor proof.\n * - Communicate the temp passphrase to the recipient via a secure\n * channel (URL fragment, in-person, etc.) — the hub does not\n * transport secrets.\n */\nexport async function recoverUser(\n store: NoydbStore,\n vault: string,\n callerKeyring: UnlockedKeyring,\n options: RecoverUserOptions,\n): Promise<void> {\n // 1. Load the target's existing keyring file (plaintext header).\n const env = await store.get(vault, '_keyring', options.userId)\n if (!env) {\n throw new NoAccessError(\n `recoverUser: user \"${options.userId}\" has no keyring in vault \"${vault}\".`,\n )\n }\n const target = JSON.parse(env._data) as KeyringFile\n const targetRole = options.role ?? target.role\n\n // 2. Permission check — caller must be allowed to recover this role.\n // Owner→owner natively allowed; admin→admin allowed; admin→owner blocked.\n if (!canRecover(callerKeyring.role, targetRole)) {\n throw new PermissionDeniedError(\n `Role \"${callerKeyring.role}\" cannot recover role \"${targetRole}\"`,\n )\n }\n // Also guard against role-uplift via the override — admin cannot\n // promote a target to owner under cover of recovery.\n if (!canRecover(callerKeyring.role, target.role)) {\n throw new PermissionDeniedError(\n `Role \"${callerKeyring.role}\" cannot recover role \"${target.role}\"`,\n )\n }\n\n // 3. Anti-privilege-escalation. Every collection the target had\n // access to must be in the caller's DEK set — the recoverer\n // cannot give the recovered user access to a collection the\n // recoverer themselves can't read. Mirrors `grant()`'s check.\n for (const coll of Object.keys(target.deks)) {\n if (!callerKeyring.deks.has(coll)) {\n throw new PrivilegeEscalationError(coll)\n }\n }\n\n // 4. Optional phrase strength validation (mirrors `grant` opt-in).\n if (options.validatePassphrase && !options.allowWeakPassphrase) {\n assertStrongPassphrase(options.passphrase, options.passphrasePolicy)\n }\n\n // 5. Mint a fresh salt + KEK from the temp passphrase. The DEKs\n // themselves are unchanged — only the wrapping is replaced.\n const newSalt = generateSalt()\n const newKek = await deriveKey(options.passphrase, newSalt)\n\n const wrappedDeks: Record<string, string> = {}\n for (const coll of Object.keys(target.deks)) {\n const callerDek = callerKeyring.deks.get(coll)\n if (!callerDek) {\n // Already caught by the anti-privilege-escalation loop above.\n // This branch is defensive belt-and-braces; if it ever fires,\n // the target had a collection the caller's deks Map disagrees\n // with — fail loud rather than silently dropping access.\n throw new PrivilegeEscalationError(coll)\n }\n wrappedDeks[coll] = await wrapKey(callerDek, newKek)\n }\n\n // 6. Build the recovered keyring file. Identity preserved; wrapping\n // refreshed; tier-2 slots dropped (they wrap the OLD KEK and\n // can't survive a tier-1 phrase change — same precedent as\n // rotatePassphrase). Mint a fresh canary under newKek; the\n // OLD canary on the spread `...target` would fail to verify against\n // the new KEK and trip KeyringCorruptError on next load.\n const canary = await mintKeyringCanary(newKek)\n const next: KeyringFile = {\n ...target,\n _noydb_keyring: NOYDB_KEYRING_VERSION,\n role: targetRole,\n display_name: options.displayName ?? target.display_name,\n deks: wrappedDeks,\n salt: bufferToBase64(newSalt),\n granted_by: callerKeyring.userId,\n authenticators: [],\n canary,\n }\n\n // 7. Single atomic write — overwrites the existing envelope.\n // Backend `put` is the canonical write primitive across every\n // `to-*` store; no partial-failure window between revoke + grant.\n const envelope = {\n _noydb: 1 as const,\n _v: 1,\n _ts: new Date().toISOString(),\n _iv: '',\n _data: JSON.stringify(next),\n }\n await store.put(vault, '_keyring', options.userId, envelope)\n}\n","/**\n * Tier-2 authenticator slot management.\n *\n * Each slot independently wraps the SAME KEK under a method-specific\n * derived key (LUKS pattern). Enrolling adds a slot; removing drops\n * one. Both are constant-time keyring writes — no DEK re-keying.\n *\n * The crypto for each method lives in its `@noy-db/on-*` package\n * (`on-webauthn`, `on-oidc`, `on-password`); this module accepts the\n * package's `wrapped_kek` ciphertext + `meta` payload and persists it.\n *\n * @see https://github.com/vLannaAi/noy-db-docs/blob/main/content/docs/services/session-tiers.md → Tier 2 — Authenticate\n *\n * @module\n */\nimport type { NoydbStore, KeyringAuthenticator } from '../../kernel/types.js'\nimport { NoAccessError, ValidationError } from '../../kernel/errors.js'\nimport type { UnlockedKeyring } from './keyring.js'\nimport { persistKeyring } from './keyring.js'\n\n/** Fields shared across both wrap-KEK and wrap-DEKs enroll inputs. */\ninterface EnrollAuthenticatorBase {\n readonly id: string\n readonly method: KeyringAuthenticator['method']\n /** Method-specific metadata (cred id, salt, …). */\n readonly meta: Record<string, unknown>\n /** Tier the active session held when enrolling. Defaults to 1. */\n readonly enrolled_via_tier?: 1 | 2\n}\n\n/** Wrap-KEK enroll input (WebAuthn, OIDC). */\nexport interface EnrollAuthenticatorWrappingKEKOptions extends EnrollAuthenticatorBase {\n /** Already-wrapped KEK ciphertext (base64) — produced by the on-* package. */\n readonly wrapped_kek: string\n readonly wrapKind?: 'kek'\n}\n\n/** Wrap-DEKs enroll input (password, future on-* using the unified wrap-DEKs primitive). */\nexport interface EnrollAuthenticatorWrappingDEKsOptions extends EnrollAuthenticatorBase {\n readonly wrapKind: 'deks'\n /** Base64 AES-GCM ciphertext of `{ deks: { collection: base64rawDek } }`. */\n readonly wrapped_deks: string\n /** Base64 AES-GCM IV used for the `wrapped_deks` ciphertext. */\n readonly iv: string\n}\n\n/** Discriminated union over the two enroll input shapes. */\nexport type EnrollAuthenticatorOptions =\n | EnrollAuthenticatorWrappingKEKOptions\n | EnrollAuthenticatorWrappingDEKsOptions\n\n/**\n * Append a new authenticator slot to the keyring file. Throws\n * `ValidationError` if a slot with the same id already exists — the\n * caller decides whether to remove + re-enroll.\n *\n * Accepts either wrap-KEK (WebAuthn, OIDC) or wrap-DEKs (password)\n * input. The variant is preserved verbatim into `KeyringAuthenticator`.\n */\nexport async function enrollAuthenticator(\n store: NoydbStore,\n vault: string,\n keyring: UnlockedKeyring,\n options: EnrollAuthenticatorOptions,\n): Promise<UnlockedKeyring> {\n const existing = keyring.authenticators.find((a) => a.id === options.id)\n if (existing) {\n throw new ValidationError(\n `enrollAuthenticator: slot id \"${options.id}\" already exists in vault \"${vault}\". ` +\n 'Remove the slot first or pick a unique id.',\n )\n }\n\n const base = {\n id: options.id,\n method: options.method,\n enrolled_at: new Date().toISOString(),\n enrolled_via_tier: options.enrolled_via_tier ?? 1,\n meta: options.meta,\n } as const\n\n const slot: KeyringAuthenticator = options.wrapKind === 'deks'\n ? {\n ...base,\n wrapKind: 'deks',\n wrapped_deks: options.wrapped_deks,\n iv: options.iv,\n }\n : {\n ...base,\n wrapped_kek: options.wrapped_kek,\n }\n\n const next = appendSlot(keyring, slot)\n await persistKeyring(store, vault, next)\n return next\n}\n\n/**\n * Caller payload for {@link updateAuthenticator}. Mutates only\n * `meta` — the slot's id, method, and wrap material are immutable\n * through this primitive, preserving the anti-slot-swap guard.\n *\n * `meta` is **merged** at the top level: keys absent from the patch\n * are preserved, keys present overwrite. To clear a meta key, pass\n * `null` for that key explicitly. (Same top-level merge semantics as\n * `UserApi.updateMe`, non-recursive — meta is a flat label bag.)\n */\nexport interface UpdateAuthenticatorOptions {\n readonly meta?: Record<string, unknown>\n}\n\n/**\n * Mutate a tier-2 authenticator slot's `meta` blob (slot rename,\n * label changes). The slot's `id`, `method`, and wrap material\n * (`wrapped_kek` for wrap-KEK; `wrapped_deks` + `iv` for wrap-DEKs)\n * are immutable through this entry point — the anti-slot-swap guard\n * is structural, not gate-driven, so even if the policy gate is\n * weakened a future caller cannot use this path to swap one slot's\n * crypto for another's.\n *\n * `meta` patch semantics:\n * - Top-level merge — absent keys preserved, present keys overwrite\n * - `null` value — delete that meta key\n * - Non-object values (string, number, boolean, array) — replace verbatim\n *\n * @throws `NoAccessError` when no slot with the given id exists.\n * @throws `ValidationError` when no patch field is provided.\n *\n */\nexport async function updateAuthenticator(\n store: NoydbStore,\n vault: string,\n keyring: UnlockedKeyring,\n slotId: string,\n options: UpdateAuthenticatorOptions,\n): Promise<UnlockedKeyring> {\n if (options.meta === undefined) {\n throw new ValidationError(\n `updateAuthenticator: at least one of meta must be provided ` +\n `(slotId: \"${slotId}\").`,\n )\n }\n\n const idx = keyring.authenticators.findIndex((a) => a.id === slotId)\n if (idx === -1) {\n throw new NoAccessError(\n `updateAuthenticator: slot \"${slotId}\" not found in vault \"${vault}\".`,\n )\n }\n const existing = keyring.authenticators[idx]!\n\n // Merge at the top level. Absent keys preserved (non-recursive —\n // meta is a flat label bag in practice, no consumer nests it).\n const mergedMeta: Record<string, unknown> = { ...existing.meta }\n for (const [k, v] of Object.entries(options.meta)) {\n if (v === undefined) continue // skip\n if (v === null) {\n delete mergedMeta[k]\n continue\n }\n mergedMeta[k] = v\n }\n\n // Reconstruct the slot preserving wrapKind discrimination. The\n // immutable fields (id, method, wrapped_kek / wrapped_deks + iv,\n // enrolled_at, enrolled_via_tier) all flow through ...existing.\n const next: KeyringAuthenticator = { ...existing, meta: mergedMeta }\n const nextSlots = [...keyring.authenticators]\n nextSlots[idx] = next\n\n const nextKeyring: UnlockedKeyring = {\n ...keyring,\n authenticators: nextSlots,\n }\n await persistKeyring(store, vault, nextKeyring)\n return nextKeyring\n}\n\n/**\n * Drop a slot by id. No-op if the slot doesn't exist (idempotent —\n * removing a non-existent slot is a recoverable retry, not an error).\n */\nexport async function removeAuthenticator(\n store: NoydbStore,\n vault: string,\n keyring: UnlockedKeyring,\n slotId: string,\n): Promise<UnlockedKeyring> {\n const filtered = keyring.authenticators.filter((a) => a.id !== slotId)\n if (filtered.length === keyring.authenticators.length) {\n return keyring // idempotent — nothing to do\n }\n const next: UnlockedKeyring = {\n ...keyring,\n authenticators: filtered,\n }\n await persistKeyring(store, vault, next)\n return next\n}\n\n/**\n * Look up a slot by id. Returns `undefined` when no slot matches.\n * Used by tier-2 unlock dispatchers to fetch the wrapped KEK + meta\n * before invoking the method-specific verifier.\n */\nexport function findAuthenticator(\n keyring: UnlockedKeyring,\n slotId: string,\n): KeyringAuthenticator | undefined {\n return keyring.authenticators.find((a) => a.id === slotId)\n}\n\nfunction appendSlot(\n keyring: UnlockedKeyring,\n slot: KeyringAuthenticator,\n): UnlockedKeyring {\n return {\n ...keyring,\n authenticators: [...keyring.authenticators, slot],\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDO,IAAM,+BAA+B;AAGrC,IAAM,iCAAiC;AAGvC,IAAM,6BAA6B;AAqD1C,eAAsB,0BACpB,cACA,OACA,OACqB;AACrB,QAAM,SAAS,WAAW,OAAO;AACjC,QAAM,WACJ,wBAAwB,aACpB,eACA,IAAI,YAAY,EAAE,OAAO,YAAY;AAC3C,QAAM,aAAa,IAAI,YAAY,EAAE,OAAO,KAAK;AACjD,QAAM,aAAa,MAAM,OAAO,OAAO,WAAW,UAAU;AAC5D,QAAM,OAAO,IAAI,YAAY,EAAE,OAAO,iCAAiC,KAAK;AAC5E,QAAM,MAAM,MAAM,OAAO,UAAU,OAAO,UAAU,QAAQ,OAAO,CAAC,W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MAAM;AAC3D;AAEA,SAAS,WACP,SACA,MACiB;AACjB,SAAO;AAAA,IACL,GAAG;AAAA,IACH,gBAAgB,CAAC,GAAG,QAAQ,gBAAgB,IAAI;AAAA,EAClD;AACF;","names":["deks"]}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import {
|
|
2
|
+
canonicalize,
|
|
3
|
+
derivePersistedSchema
|
|
4
|
+
} from "./chunk-ULIHDPKL.js";
|
|
5
|
+
import {
|
|
6
|
+
loadPersistedSchema,
|
|
7
|
+
savePersistedSchema
|
|
8
|
+
} from "./chunk-CPXPHQGX.js";
|
|
9
|
+
|
|
10
|
+
// src/with-shape/schema-update/delta.ts
|
|
11
|
+
function computeSchemaDelta(stored, fresh, collection) {
|
|
12
|
+
const a = stored;
|
|
13
|
+
const b = fresh;
|
|
14
|
+
const aProps = a.properties ?? {};
|
|
15
|
+
const bProps = b.properties ?? {};
|
|
16
|
+
const aReq = new Set(a.required ?? []);
|
|
17
|
+
const bReq = new Set(b.required ?? []);
|
|
18
|
+
const aKeys = Object.keys(aProps);
|
|
19
|
+
const bKeys = Object.keys(bProps);
|
|
20
|
+
const added = bKeys.filter((k) => !(k in aProps));
|
|
21
|
+
const removed = aKeys.filter((k) => !(k in bProps));
|
|
22
|
+
const changed = [];
|
|
23
|
+
for (const k of bKeys) {
|
|
24
|
+
if (!(k in aProps)) continue;
|
|
25
|
+
const shapeChanged = canonicalize(aProps[k]) !== canonicalize(bProps[k]);
|
|
26
|
+
const requiredChanged = aReq.has(k) !== bReq.has(k);
|
|
27
|
+
if (shapeChanged || requiredChanged) {
|
|
28
|
+
changed.push({ field: k, requiredChanged, shapeChanged });
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
let kind;
|
|
32
|
+
if (added.length === 0 && removed.length === 0 && changed.length === 0) {
|
|
33
|
+
kind = "none";
|
|
34
|
+
} else if (removed.length === 0 && changed.length === 0 && added.every((k) => !bReq.has(k))) {
|
|
35
|
+
kind = "additive";
|
|
36
|
+
} else {
|
|
37
|
+
kind = "non-additive";
|
|
38
|
+
}
|
|
39
|
+
return { collection, kind, added, removed, changed };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// src/with-shape/schema-update/dispatch.ts
|
|
43
|
+
async function evaluateStrategies(delta, strategies, ctx) {
|
|
44
|
+
for (const strategy of strategies) {
|
|
45
|
+
const decision = await strategy.onSchemaDelta(delta, ctx);
|
|
46
|
+
if (decision.action !== "allow") return decision;
|
|
47
|
+
}
|
|
48
|
+
return { action: "allow" };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// src/with-shape/persisted-schemas/register.ts
|
|
52
|
+
async function persistSchemaIfNeeded(opts) {
|
|
53
|
+
const fresh = await derivePersistedSchema(opts.validator);
|
|
54
|
+
const stored = await loadPersistedSchema(opts.store, opts.vault, opts.collectionName, opts.dek);
|
|
55
|
+
if (stored && isEquivalent(stored, fresh)) {
|
|
56
|
+
return { written: false, skipped: true, envelope: stored, decision: { action: "allow" } };
|
|
57
|
+
}
|
|
58
|
+
let decision = { action: "allow" };
|
|
59
|
+
const strategies = opts.strategies ?? [];
|
|
60
|
+
if (stored && strategies.length > 0 && stored.kind === fresh.kind && isPlainObject(stored.jsonSchema) && isPlainObject(fresh.jsonSchema)) {
|
|
61
|
+
const delta = computeSchemaDelta(stored.jsonSchema, fresh.jsonSchema, opts.collectionName);
|
|
62
|
+
decision = await evaluateStrategies(delta, strategies, { collection: opts.collectionName });
|
|
63
|
+
}
|
|
64
|
+
if (decision.action !== "allow") {
|
|
65
|
+
return { written: false, skipped: false, envelope: stored ?? fresh, decision };
|
|
66
|
+
}
|
|
67
|
+
const toSave = stored?.classified !== void 0 ? { ...fresh, classified: stored.classified } : fresh;
|
|
68
|
+
await savePersistedSchema(opts.store, opts.vault, opts.collectionName, opts.dek, toSave);
|
|
69
|
+
return { written: true, skipped: false, envelope: toSave, decision };
|
|
70
|
+
}
|
|
71
|
+
async function persistClassifiedMarker(opts) {
|
|
72
|
+
const stored = await loadPersistedSchema(opts.store, opts.vault, opts.collectionName, opts.dek);
|
|
73
|
+
if (stored?.classified !== void 0 && markersEqual(stored.classified, opts.marker)) return;
|
|
74
|
+
const payload = stored !== void 0 ? { ...stored, classified: opts.marker } : {
|
|
75
|
+
_noydb_schema: 1,
|
|
76
|
+
kind: "Unknown",
|
|
77
|
+
jsonSchema: null,
|
|
78
|
+
hash: null,
|
|
79
|
+
derivedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
80
|
+
classified: opts.marker
|
|
81
|
+
};
|
|
82
|
+
await savePersistedSchema(opts.store, opts.vault, opts.collectionName, opts.dek, payload);
|
|
83
|
+
}
|
|
84
|
+
function markersEqual(a, b) {
|
|
85
|
+
return sameSet(a.digestOnly, b.digestOnly) && sameSet(a.equatable, b.equatable);
|
|
86
|
+
}
|
|
87
|
+
function sameSet(a, b) {
|
|
88
|
+
if (a.length !== b.length) return false;
|
|
89
|
+
const s = new Set(a);
|
|
90
|
+
return b.every((x) => s.has(x));
|
|
91
|
+
}
|
|
92
|
+
function isPlainObject(v) {
|
|
93
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
94
|
+
}
|
|
95
|
+
function isEquivalent(a, b) {
|
|
96
|
+
if (a.kind !== b.kind) return false;
|
|
97
|
+
if (a.hash && b.hash) return a.hash === b.hash;
|
|
98
|
+
if (a.hash === null && b.hash === null) return true;
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export {
|
|
103
|
+
persistSchemaIfNeeded,
|
|
104
|
+
persistClassifiedMarker
|
|
105
|
+
};
|
|
106
|
+
//# sourceMappingURL=chunk-KYY7L72M.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/with-shape/schema-update/delta.ts","../src/with-shape/schema-update/dispatch.ts","../src/with-shape/persisted-schemas/register.ts"],"sourcesContent":["/**\n * Classify the difference between two derived JSON Schemas.\n *\n * v1 ruleset — top-level object properties + required-ness:\n * - additive ⇔ only new OPTIONAL properties (no removals, no changed\n * properties, no new required field, no required-ness flip)\n * - non-additive ⇔ any removal, any shape/type change, any required-ness\n * flip, or a new REQUIRED property\n * Deeper rules (nested objects, union widening, type narrowing) are\n * deferred. Callers only invoke this with two object schemas.\n */\nimport { canonicalize } from '../persisted-schemas/canonicalize.js'\nimport type { SchemaDelta, FieldChange } from './types.js'\n\ninterface ObjectSchema {\n readonly properties?: Record<string, unknown>\n readonly required?: readonly string[]\n}\n\nexport function computeSchemaDelta(\n stored: object,\n fresh: object,\n collection: string,\n): SchemaDelta {\n const a = stored as ObjectSchema\n const b = fresh as ObjectSchema\n const aProps = a.properties ?? {}\n const bProps = b.properties ?? {}\n const aReq = new Set(a.required ?? [])\n const bReq = new Set(b.required ?? [])\n\n const aKeys = Object.keys(aProps)\n const bKeys = Object.keys(bProps)\n\n const added = bKeys.filter(k => !(k in aProps))\n const removed = aKeys.filter(k => !(k in bProps))\n\n const changed: FieldChange[] = []\n for (const k of bKeys) {\n if (!(k in aProps)) continue\n const shapeChanged = canonicalize(aProps[k]) !== canonicalize(bProps[k])\n const requiredChanged = aReq.has(k) !== bReq.has(k)\n if (shapeChanged || requiredChanged) {\n changed.push({ field: k, requiredChanged, shapeChanged })\n }\n }\n\n let kind: SchemaDelta['kind']\n if (added.length === 0 && removed.length === 0 && changed.length === 0) {\n kind = 'none'\n } else if (\n removed.length === 0 &&\n changed.length === 0 &&\n added.every(k => !bReq.has(k))\n ) {\n kind = 'additive'\n } else {\n kind = 'non-additive'\n }\n\n return { collection, kind, added, removed, changed }\n}\n","/** Ordered strategy evaluation: first non-`allow` decision wins. */\nimport type { SchemaDelta, SchemaUpdateStrategy, UpdateContext, UpdateDecision } from './types.js'\n\nexport async function evaluateStrategies(\n delta: SchemaDelta,\n strategies: readonly SchemaUpdateStrategy[],\n ctx: UpdateContext,\n): Promise<UpdateDecision> {\n for (const strategy of strategies) {\n const decision = await strategy.onSchemaDelta(delta, ctx)\n if (decision.action !== 'allow') return decision\n }\n return { action: 'allow' }\n}\n","/**\n * Orchestrate the derive → hash → skip-or-write cycle for a collection's\n * persisted JSON Schema. Called by the Vault at collection-registration\n * time when the developer opts in via `collection({ persistJsonSchema:\n * true })`.\n *\n * Skip semantics:\n *\n * - Zod validators: skip when the new hash equals the stored hash.\n * - Non-Zod (stub envelopes have hash=null): skip when the stored\n * envelope's `kind` matches the freshly-detected kind (since there's\n * no body to compare yet — a kind change is the only signal).\n *\n * @module\n */\n\nimport { derivePersistedSchema } from './derive.js'\nimport { loadPersistedSchema, savePersistedSchema } from './storage.js'\nimport { computeSchemaDelta } from '../schema-update/delta.js'\nimport { evaluateStrategies } from '../schema-update/dispatch.js'\nimport type { SchemaUpdateStrategy, UpdateDecision } from '../schema-update/types.js'\nimport type { NoydbStore, ClassifiedMarker } from '../../kernel/types.js'\nimport type { PersistedSchemaEnvelope } from './types.js'\nimport type { EnclaveKey } from '../../kernel/enclave/index.js'\n\nexport interface PersistSchemaResult {\n /** True when a fresh envelope was written to storage. */\n readonly written: boolean\n /** True when an existing envelope matched and the write was skipped. */\n readonly skipped: boolean\n /** The envelope that was either written or matched. */\n readonly envelope: PersistedSchemaEnvelope\n /** The update-strategy decision, present when strategies ran. */\n readonly decision?: UpdateDecision\n}\n\nexport async function persistSchemaIfNeeded(opts: {\n readonly store: NoydbStore\n readonly vault: string\n readonly collectionName: string\n readonly validator: unknown\n readonly dek: EnclaveKey\n readonly strategies?: readonly SchemaUpdateStrategy[]\n}): Promise<PersistSchemaResult> {\n const fresh = await derivePersistedSchema(opts.validator)\n const stored = await loadPersistedSchema(opts.store, opts.vault, opts.collectionName, opts.dek)\n\n if (stored && isEquivalent(stored, fresh)) {\n return { written: false, skipped: true, envelope: stored, decision: { action: 'allow' } }\n }\n\n // Changed (or first registration). Run update strategies only when we\n // have a comparable JSON-Schema baseline and strategies were registered.\n let decision: UpdateDecision = { action: 'allow' }\n const strategies = opts.strategies ?? []\n if (\n stored &&\n strategies.length > 0 &&\n stored.kind === fresh.kind &&\n isPlainObject(stored.jsonSchema) &&\n isPlainObject(fresh.jsonSchema)\n ) {\n const delta = computeSchemaDelta(stored.jsonSchema, fresh.jsonSchema, opts.collectionName)\n decision = await evaluateStrategies(delta, strategies, { collection: opts.collectionName })\n }\n\n if (decision.action !== 'allow') {\n // reject (or cutover): do NOT overwrite the baseline — the\n // old schema stays the source of truth until the change is resolved.\n return { written: false, skipped: false, envelope: stored ?? fresh, decision }\n }\n\n // Preserve a previously-persisted classified marker (C-A / R10) — the schema\n // derivation knows nothing about it, so a naive overwrite here would drop the\n // config-drift guard's cross-session signal.\n const toSave: PersistedSchemaEnvelope =\n stored?.classified !== undefined ? { ...fresh, classified: stored.classified } : fresh\n await savePersistedSchema(opts.store, opts.vault, opts.collectionName, opts.dek, toSave)\n return { written: true, skipped: false, envelope: toSave, decision }\n}\n\n/**\n * Persist (or refresh) the C-A / R10 classified marker into the collection's\n * `_schemas/<collection>` record, preserving any existing derived JSON-Schema\n * body. Idempotent — a no-op when an equivalent marker is already stored.\n * Independent of `persistJsonSchema`: called on the first classified write so a\n * later naive handle can detect the drift cross-session.\n */\nexport async function persistClassifiedMarker(opts: {\n readonly store: NoydbStore\n readonly vault: string\n readonly collectionName: string\n readonly dek: EnclaveKey\n readonly marker: ClassifiedMarker\n}): Promise<void> {\n const stored = await loadPersistedSchema(opts.store, opts.vault, opts.collectionName, opts.dek)\n if (stored?.classified !== undefined && markersEqual(stored.classified, opts.marker)) return\n const payload: PersistedSchemaEnvelope =\n stored !== undefined\n ? { ...stored, classified: opts.marker }\n : {\n _noydb_schema: 1,\n kind: 'Unknown',\n jsonSchema: null,\n hash: null,\n derivedAt: new Date().toISOString(),\n classified: opts.marker,\n }\n await savePersistedSchema(opts.store, opts.vault, opts.collectionName, opts.dek, payload)\n}\n\nfunction markersEqual(a: ClassifiedMarker, b: ClassifiedMarker): boolean {\n return sameSet(a.digestOnly, b.digestOnly) && sameSet(a.equatable, b.equatable)\n}\n\nfunction sameSet(a: readonly string[], b: readonly string[]): boolean {\n if (a.length !== b.length) return false\n const s = new Set(a)\n return b.every((x) => s.has(x))\n}\n\nfunction isPlainObject(v: unknown): v is object {\n return typeof v === 'object' && v !== null && !Array.isArray(v)\n}\n\nfunction isEquivalent(a: PersistedSchemaEnvelope, b: PersistedSchemaEnvelope): boolean {\n if (a.kind !== b.kind) return false\n // Zod path: real hashes — compare directly.\n if (a.hash && b.hash) return a.hash === b.hash\n // Stub path: both have hash=null. Kind equality is the only signal we have.\n if (a.hash === null && b.hash === null) return true\n // Mixed (one has a hash, the other doesn't) — treat as changed.\n return false\n}\n"],"mappings":";;;;;;;;;;AAmBO,SAAS,mBACd,QACA,OACA,YACa;AACb,QAAM,IAAI;AACV,QAAM,IAAI;AACV,QAAM,SAAS,EAAE,cAAc,CAAC;AAChC,QAAM,SAAS,EAAE,cAAc,CAAC;AAChC,QAAM,OAAO,IAAI,IAAI,EAAE,YAAY,CAAC,CAAC;AACrC,QAAM,OAAO,IAAI,IAAI,EAAE,YAAY,CAAC,CAAC;AAErC,QAAM,QAAQ,OAAO,KAAK,MAAM;AAChC,QAAM,QAAQ,OAAO,KAAK,MAAM;AAEhC,QAAM,QAAQ,MAAM,OAAO,OAAK,EAAE,KAAK,OAAO;AAC9C,QAAM,UAAU,MAAM,OAAO,OAAK,EAAE,KAAK,OAAO;AAEhD,QAAM,UAAyB,CAAC;AAChC,aAAW,KAAK,OAAO;AACrB,QAAI,EAAE,KAAK,QAAS;AACpB,UAAM,eAAe,aAAa,OAAO,CAAC,CAAC,MAAM,aAAa,OAAO,CAAC,CAAC;AACvE,UAAM,kBAAkB,KAAK,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC;AAClD,QAAI,gBAAgB,iBAAiB;AACnC,cAAQ,KAAK,EAAE,OAAO,GAAG,iBAAiB,aAAa,CAAC;AAAA,IAC1D;AAAA,EACF;AAEA,MAAI;AACJ,MAAI,MAAM,WAAW,KAAK,QAAQ,WAAW,KAAK,QAAQ,WAAW,GA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AM,QAAO;AAE/C,SAAO;AACT;","names":[]}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
2
|
sha256Hex
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-TLJOJBZD.js";
|
|
4
4
|
import {
|
|
5
5
|
MaterializedViewCycleError,
|
|
6
6
|
MaterializedViewSourceUnknownError
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-U23JUUPX.js";
|
|
8
8
|
|
|
9
9
|
// src/with-formula/materialized-views/dependency-analyzer.ts
|
|
10
10
|
function analyzeDependencies(query) {
|
|
@@ -317,4 +317,4 @@ export {
|
|
|
317
317
|
MaterializedViewRegistry,
|
|
318
318
|
wrapDbWithPredicates
|
|
319
319
|
};
|
|
320
|
-
//# sourceMappingURL=chunk-
|
|
320
|
+
//# sourceMappingURL=chunk-LIP6JWYK.js.map
|