@noy-db/hub 0.2.0-pre.8 → 0.3.0-pre.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +129 -3
- package/dist/adapter/index.d.ts +5 -0
- package/dist/adapter/index.js +15 -0
- package/dist/aggregate/index.d.ts +6 -2
- package/dist/aggregate/index.js +24 -16
- package/dist/aggregate/index.js.map +1 -1
- package/dist/api-RW3KP7WU.js +14 -0
- package/dist/as/index.d.ts +7 -0
- package/dist/as/index.js +24 -0
- package/dist/at/index.d.ts +5 -0
- package/dist/at/index.js +1 -0
- package/dist/attestation/index.d.ts +15 -47
- package/dist/attestation/index.js +54 -10
- package/dist/attestation/index.js.map +1 -1
- package/dist/backup-XV3IOEGB.js +217 -0
- package/dist/backup-XV3IOEGB.js.map +1 -0
- package/dist/blobs/index.d.ts +6 -8
- package/dist/blobs/index.js +19 -12
- package/dist/blobs/index.js.map +1 -1
- package/dist/bundle/index.d.ts +16 -70
- package/dist/bundle/index.js +39 -476
- package/dist/bundle/index.js.map +1 -1
- package/dist/{ulid-BFJkYRRW.d.ts → bundle-CH-H06dp.d.ts} +31 -86
- package/dist/by/index.d.ts +1 -0
- package/dist/by/index.js +11 -0
- package/dist/cargo/index.d.ts +9 -0
- package/dist/cargo/index.js +89 -0
- package/dist/chunk-26LGBE4T.js +42 -0
- package/dist/chunk-26LGBE4T.js.map +1 -0
- package/dist/chunk-2P2HZEXU.js +233 -0
- package/dist/chunk-2P2HZEXU.js.map +1 -0
- package/dist/{chunk-K3DK3NU5.js → chunk-3YFXJ3ZP.js} +20 -5
- package/dist/chunk-3YFXJ3ZP.js.map +1 -0
- package/dist/chunk-4Q6HSHHL.js +90 -0
- package/dist/chunk-4Q6HSHHL.js.map +1 -0
- package/dist/chunk-5LUY7UTV.js +380 -0
- package/dist/chunk-5LUY7UTV.js.map +1 -0
- package/dist/chunk-5N6CZTCY.js +367 -0
- package/dist/chunk-5N6CZTCY.js.map +1 -0
- package/dist/chunk-5O3AOPDT.js +992 -0
- package/dist/chunk-5O3AOPDT.js.map +1 -0
- package/dist/chunk-5R3ERCDH.js +239 -0
- package/dist/chunk-5R3ERCDH.js.map +1 -0
- package/dist/{chunk-6774ZOQ7.js → chunk-5R5JW2JT.js} +7095 -4769
- package/dist/chunk-5R5JW2JT.js.map +1 -0
- package/dist/chunk-5TDJ56JE.js +32 -0
- package/dist/chunk-5TDJ56JE.js.map +1 -0
- package/dist/{chunk-T7JEBOGN.js → chunk-62QYRORB.js} +18 -11
- package/dist/chunk-62QYRORB.js.map +1 -0
- package/dist/{chunk-J66GRPNH.js → chunk-6S7T6WC4.js} +2 -2
- package/dist/chunk-6S7T6WC4.js.map +1 -0
- package/dist/chunk-76722EBH.js +451 -0
- package/dist/chunk-76722EBH.js.map +1 -0
- package/dist/{chunk-Z6FNBOTC.js → chunk-AIWULCUO.js} +13 -17
- package/dist/chunk-AIWULCUO.js.map +1 -0
- package/dist/{chunk-O3VZPBZG.js → chunk-AQTBSL7R.js} +47 -11
- package/dist/chunk-AQTBSL7R.js.map +1 -0
- package/dist/chunk-AURFOK3D.js +35 -0
- package/dist/chunk-AURFOK3D.js.map +1 -0
- package/dist/{chunk-53XBRIRT.js → chunk-AXRXJTE2.js} +9 -9
- package/dist/chunk-AXRXJTE2.js.map +1 -0
- package/dist/chunk-AZAOEIKW.js +155 -0
- package/dist/chunk-AZAOEIKW.js.map +1 -0
- package/dist/{chunk-HNRHLRDC.js → chunk-BG3SPSR4.js} +3 -3
- package/dist/chunk-BG3SPSR4.js.map +1 -0
- package/dist/chunk-BGIZAFY7.js +1 -0
- package/dist/chunk-CHFZDSE4.js +1 -0
- package/dist/{chunk-DJHHA6XH.js → chunk-CMGR4ZEW.js} +50 -20
- package/dist/chunk-CMGR4ZEW.js.map +1 -0
- package/dist/chunk-CWPPNPOH.js +23 -0
- package/dist/chunk-CWPPNPOH.js.map +1 -0
- package/dist/{chunk-QODLLGQ7.js → chunk-DFEMTNPJ.js} +371 -38
- package/dist/chunk-DFEMTNPJ.js.map +1 -0
- package/dist/{chunk-ZYWZWG6G.js → chunk-DGDI2D4M.js} +10 -10
- package/dist/chunk-DGDI2D4M.js.map +1 -0
- package/dist/{chunk-SYMWGEET.js → chunk-EIZUR2XW.js} +3 -3
- package/dist/chunk-EIZUR2XW.js.map +1 -0
- package/dist/{chunk-BVRYKATC.js → chunk-FISN7WE4.js} +36 -33
- package/dist/chunk-FISN7WE4.js.map +1 -0
- package/dist/chunk-GHVIKOHT.js +1 -0
- package/dist/chunk-GYGWYIOZ.js +200 -0
- package/dist/chunk-GYGWYIOZ.js.map +1 -0
- package/dist/chunk-HCIPRAGS.js +45 -0
- package/dist/chunk-HCIPRAGS.js.map +1 -0
- package/dist/{chunk-PX35GA7L.js → chunk-I2NOIW44.js} +10 -10
- package/dist/chunk-I2NOIW44.js.map +1 -0
- package/dist/{chunk-OIF6LZUR.js → chunk-I3TIKTJO.js} +3 -3
- package/dist/chunk-I3TIKTJO.js.map +1 -0
- package/dist/chunk-I7FD46FF.js +9 -0
- package/dist/chunk-I7FD46FF.js.map +1 -0
- package/dist/chunk-IAGBDSCS.js +40 -0
- package/dist/chunk-IAGBDSCS.js.map +1 -0
- package/dist/{chunk-JWRVQKRZ.js → chunk-IELYAOGG.js} +6 -18
- package/dist/chunk-IELYAOGG.js.map +1 -0
- package/dist/chunk-IGUYVGGI.js +205 -0
- package/dist/chunk-IGUYVGGI.js.map +1 -0
- package/dist/{chunk-U26HQ6KJ.js → chunk-IO6GRPT6.js} +4 -4
- package/dist/chunk-IO6GRPT6.js.map +1 -0
- package/dist/chunk-IPB7FTQX.js +273 -0
- package/dist/chunk-IPB7FTQX.js.map +1 -0
- package/dist/chunk-ITNUCOXM.js +148 -0
- package/dist/chunk-ITNUCOXM.js.map +1 -0
- package/dist/{chunk-WPLVTJ5D.js → chunk-IUEN57TV.js} +10 -10
- package/dist/chunk-IUEN57TV.js.map +1 -0
- package/dist/{chunk-DL3HWOQ5.js → chunk-JNUWZ6D3.js} +9 -9
- package/dist/chunk-JNUWZ6D3.js.map +1 -0
- package/dist/chunk-K2WCO3NX.js +1 -0
- package/dist/chunk-KVOXU4T5.js +30 -0
- package/dist/chunk-KVOXU4T5.js.map +1 -0
- package/dist/chunk-KXGNJJXB.js +135 -0
- package/dist/chunk-KXGNJJXB.js.map +1 -0
- package/dist/chunk-LB7FD65R.js +163 -0
- package/dist/chunk-LB7FD65R.js.map +1 -0
- package/dist/{chunk-22DWZL57.js → chunk-LFLXAY2W.js} +43 -218
- package/dist/chunk-LFLXAY2W.js.map +1 -0
- package/dist/chunk-LMTH2RM6.js +129 -0
- package/dist/chunk-LMTH2RM6.js.map +1 -0
- package/dist/{aggregate/index.cjs → chunk-LV7M27WM.js} +390 -219
- package/dist/chunk-LV7M27WM.js.map +1 -0
- package/dist/{chunk-PE2FR4J3.js → chunk-LXQT4WMP.js} +16 -18
- package/dist/chunk-LXQT4WMP.js.map +1 -0
- package/dist/chunk-M2YKN37S.js +524 -0
- package/dist/chunk-M2YKN37S.js.map +1 -0
- package/dist/chunk-M6OST55S.js +14 -0
- package/dist/chunk-M6OST55S.js.map +1 -0
- package/dist/{chunk-F3GDRNUT.js → chunk-MD3Y6J3L.js} +35 -69
- package/dist/chunk-MD3Y6J3L.js.map +1 -0
- package/dist/{chunk-XJFLDA7A.js → chunk-MTMJVJ5W.js} +8 -7
- package/dist/chunk-MTMJVJ5W.js.map +1 -0
- package/dist/{chunk-DFMLEQZB.js → chunk-NF5JWERG.js} +5 -10
- package/dist/chunk-NF5JWERG.js.map +1 -0
- package/dist/{chunk-DO7C2TOG.js → chunk-PKHL44ER.js} +3 -3
- package/dist/{chunk-DO7C2TOG.js.map → chunk-PKHL44ER.js.map} +1 -1
- package/dist/chunk-PSMV73A5.js +117 -0
- package/dist/chunk-PSMV73A5.js.map +1 -0
- package/dist/chunk-PY4KJPYU.js +9 -0
- package/dist/chunk-PY4KJPYU.js.map +1 -0
- package/dist/chunk-PZ5AY32C.js +10 -0
- package/dist/{chunk-DE6GKS6G.js → chunk-Q7SS3IME.js} +50 -9
- package/dist/chunk-Q7SS3IME.js.map +1 -0
- package/dist/chunk-QHJW5EXU.js +54 -0
- package/dist/chunk-QHJW5EXU.js.map +1 -0
- package/dist/{chunk-NONAAENK.js → chunk-RUEKROOS.js} +11 -4
- package/dist/chunk-RUEKROOS.js.map +1 -0
- package/dist/chunk-RUIMKQTA.js +23 -0
- package/dist/chunk-RUIMKQTA.js.map +1 -0
- package/dist/{chunk-TFBP23BX.js → chunk-SKF73JOP.js} +66 -7
- package/dist/chunk-SKF73JOP.js.map +1 -0
- package/dist/chunk-SM3AVUHC.js +42 -0
- package/dist/chunk-SM3AVUHC.js.map +1 -0
- package/dist/{chunk-ML236QKC.js → chunk-SMXWYP24.js} +5 -5
- package/dist/chunk-SMXWYP24.js.map +1 -0
- package/dist/chunk-SRB2XEWB.js +148 -0
- package/dist/chunk-SRB2XEWB.js.map +1 -0
- package/dist/chunk-SVLR4POP.js +64 -0
- package/dist/chunk-SVLR4POP.js.map +1 -0
- package/dist/chunk-TA66UMI4.js +123 -0
- package/dist/chunk-TA66UMI4.js.map +1 -0
- package/dist/chunk-TEILUWOI.js +664 -0
- package/dist/chunk-TEILUWOI.js.map +1 -0
- package/dist/chunk-TJYQIGAP.js +82 -0
- package/dist/chunk-TJYQIGAP.js.map +1 -0
- package/dist/{chunk-H2X3ISXG.js → chunk-UAG5KWVA.js} +7 -7
- package/dist/chunk-UAG5KWVA.js.map +1 -0
- package/dist/chunk-UDRIWL7A.js +382 -0
- package/dist/chunk-UDRIWL7A.js.map +1 -0
- package/dist/{chunk-2GLDA55J.js → chunk-UIU2THRG.js} +498 -133
- package/dist/chunk-UIU2THRG.js.map +1 -0
- package/dist/{chunk-3YPCK6JX.js → chunk-UPJNJGGA.js} +165 -423
- package/dist/chunk-UPJNJGGA.js.map +1 -0
- package/dist/chunk-UV5MFVO3.js +21 -0
- package/dist/chunk-UV5MFVO3.js.map +1 -0
- package/dist/{chunk-2WUSG3IT.js → chunk-V7RWQRG7.js} +5 -5
- package/dist/chunk-V7RWQRG7.js.map +1 -0
- package/dist/{chunk-VTKGMEPP.js → chunk-VCTFO5CO.js} +13 -3
- package/dist/chunk-VCTFO5CO.js.map +1 -0
- package/dist/{chunk-5T22KDPN.js → chunk-VFQGRQIH.js} +8 -8
- package/dist/chunk-VFQGRQIH.js.map +1 -0
- package/dist/{chunk-2QR2PQTT.js → chunk-VQNJ7UZL.js} +5 -3
- package/dist/chunk-VQNJ7UZL.js.map +1 -0
- package/dist/{chunk-DONMZAD2.js → chunk-WWGT2MDV.js} +43 -165
- package/dist/chunk-WWGT2MDV.js.map +1 -0
- package/dist/{chunk-EMIGCR7X.js → chunk-WXSYDNBT.js} +2 -2
- package/dist/chunk-WXSYDNBT.js.map +1 -0
- package/dist/chunk-WYSO2NIH.js +30 -0
- package/dist/chunk-WYSO2NIH.js.map +1 -0
- package/dist/chunk-XXYIOFUB.js +164 -0
- package/dist/chunk-XXYIOFUB.js.map +1 -0
- package/dist/{chunk-3BFJOWSU.js → chunk-Y22T3KQE.js} +35 -7
- package/dist/chunk-Y22T3KQE.js.map +1 -0
- package/dist/{chunk-A3JMGXPG.js → chunk-YMUGBZN2.js} +2 -2
- package/dist/chunk-YMUGBZN2.js.map +1 -0
- package/dist/{chunk-I5FOWO4J.js → chunk-ZCGAHGUS.js} +52 -73
- package/dist/chunk-ZCGAHGUS.js.map +1 -0
- package/dist/{chunk-FZU343FL.js → chunk-ZJADGNYF.js} +2 -2
- package/dist/chunk-ZJADGNYF.js.map +1 -0
- package/dist/{chunk-B6PB7JLN.js → chunk-ZYUC53LT.js} +427 -6
- package/dist/chunk-ZYUC53LT.js.map +1 -0
- package/dist/collection-facade-GQAOGJP2.js +33 -0
- package/dist/consent/index.d.ts +5 -7
- package/dist/consent/index.js +7 -5
- package/dist/consent/index.js.map +1 -1
- package/dist/crdt/index.d.ts +6 -2
- package/dist/crdt/index.js +3 -2
- package/dist/crdt/index.js.map +1 -1
- package/dist/decrypt-partition-IHtxEnTi.d.ts +21 -0
- package/dist/delegation-UL5HKLER.js +19 -0
- package/dist/derivations/index.d.ts +7 -9
- package/dist/derivations/index.js +11 -6
- package/dist/describe/index.d.ts +1 -0
- package/dist/describe/index.js +1 -0
- package/dist/describe-aBkJR2sd.d.ts +131 -0
- package/dist/{dev-unlock-p3ysikWP.d.ts → dev-unlock-C9Ro3v_O.d.ts} +1 -1
- package/dist/discriminant-BN9REW3o.d.ts +60 -0
- package/dist/enclave-UL5LW66V.js +88 -0
- package/dist/executor-2FWQRLMG.js +15 -0
- package/dist/executor-QZ7BXICW.js +9 -0
- package/dist/executor-Z5ZLJVTV.js +9 -0
- package/dist/export-accessible-KRV5W4GH.js +17 -0
- package/dist/extract-partition-GLKBOXFQ.js +30 -0
- package/dist/{fanout-sidecar-OKPMMPLG.js → fanout-sidecar-GF3DJ6KR.js} +34 -14
- package/dist/fanout-sidecar-GF3DJ6KR.js.map +1 -0
- package/dist/forget/index.d.ts +36 -0
- package/dist/forget/index.js +19 -0
- package/dist/forget/index.js.map +1 -0
- package/dist/guards/index.d.ts +13 -9
- package/dist/guards/index.js +12 -5
- package/dist/{hash-BPsYPcv_.d.cts → hash-Cp5uwiox.d.ts} +5 -1
- package/dist/history/index.d.ts +6 -8
- package/dist/history/index.js +19 -12
- package/dist/history/index.js.map +1 -1
- package/dist/i18n/index.d.ts +5 -7
- package/dist/i18n/index.js +104 -15
- package/dist/i18n/index.js.map +1 -1
- package/dist/in/index.d.ts +5 -0
- package/dist/in/index.js +1 -0
- package/dist/in/index.js.map +1 -0
- package/dist/index-B9QdHytu.d.ts +123 -0
- package/dist/index-BF9_96A5.d.ts +123 -0
- package/dist/{types-DGU60JDt.d.ts → index-BzUo1B6n.d.ts} +16306 -8352
- package/dist/index.d.ts +1088 -450
- package/dist/index.js +1165 -293
- package/dist/index.js.map +1 -1
- package/dist/indexing/index.d.ts +6 -3
- package/dist/indexing/index.js +6 -5
- package/dist/indexing/index.js.map +1 -1
- package/dist/issue-Y6UVIR43.js +13 -0
- package/dist/issue-Y6UVIR43.js.map +1 -0
- package/dist/kernel/index.d.ts +32 -0
- package/dist/kernel/index.js +53 -0
- package/dist/kernel/index.js.map +1 -0
- package/dist/{ledger-TMRZYNVJ.js → ledger-RYI35CDS.js} +12 -9
- package/dist/ledger-RYI35CDS.js.map +1 -0
- package/dist/liberate-CRPZEV7O.js +18 -0
- package/dist/liberate-CRPZEV7O.js.map +1 -0
- package/dist/materialized-views/index.d.ts +6 -19
- package/dist/materialized-views/index.js +16 -12
- package/dist/mime-magic-CGhw37_E.d.ts +103 -0
- package/dist/noydb-367AM4HT.js +50 -0
- package/dist/noydb-367AM4HT.js.map +1 -0
- package/dist/on/index.d.ts +5 -0
- package/dist/on/index.js +11 -0
- package/dist/on/index.js.map +1 -0
- package/dist/overlay-views/index.d.ts +27 -11
- package/dist/overlay-views/index.js +7 -6
- package/dist/periods/index.d.ts +5 -7
- package/dist/periods/index.js +13 -9
- package/dist/pod/index.d.ts +63 -0
- package/dist/pod/index.js +61 -0
- package/dist/pod/index.js.map +1 -0
- package/dist/policy-IXK4FVXP.js +41 -0
- package/dist/policy-IXK4FVXP.js.map +1 -0
- package/dist/portability/index.d.ts +20 -0
- package/dist/portability/index.js +43 -0
- package/dist/portability/index.js.map +1 -0
- package/dist/{public-envelope-BW6OXORV.js → public-envelope-JHDQCPSX.js} +6 -5
- package/dist/public-envelope-JHDQCPSX.js.map +1 -0
- package/dist/query/index.d.ts +5 -3
- package/dist/query/index.js +21 -13
- package/dist/read-only-facade-5ADRJVTM.js +8 -0
- package/dist/read-only-facade-5ADRJVTM.js.map +1 -0
- package/dist/registry-45RJNWGU.js +9 -0
- package/dist/registry-45RJNWGU.js.map +1 -0
- package/dist/registry-5GRV5VXI.js +13 -0
- package/dist/registry-5GRV5VXI.js.map +1 -0
- package/dist/registry-VW6P6A3J.js +8 -0
- package/dist/registry-VW6P6A3J.js.map +1 -0
- package/dist/registry-WEUCHBO4.js +11 -0
- package/dist/registry-WEUCHBO4.js.map +1 -0
- package/dist/request-withdrawal-GBPH2FDY.js +25 -0
- package/dist/request-withdrawal-GBPH2FDY.js.map +1 -0
- package/dist/revoke-TUFRGI6S.js +18 -0
- package/dist/revoke-TUFRGI6S.js.map +1 -0
- package/dist/sealed-record/index.d.ts +69 -0
- package/dist/sealed-record/index.js +65 -0
- package/dist/sealed-record/index.js.map +1 -0
- package/dist/session/index.d.ts +6 -8
- package/dist/session/index.js +7 -5
- package/dist/session/index.js.map +1 -1
- package/dist/shadow/index.d.ts +5 -7
- package/dist/shadow/index.js +4 -3
- package/dist/shadow/index.js.map +1 -1
- package/dist/{signer-72QAUSVW.js → signer-PNKTBVF7.js} +6 -5
- package/dist/signer-PNKTBVF7.js.map +1 -0
- package/dist/snapshots/index.d.ts +16 -11
- package/dist/snapshots/index.js +49 -13
- package/dist/snapshots/index.js.map +1 -1
- package/dist/{stale-6ZDBTQT7.js → stale-3JWHNDIY.js} +3 -2
- package/dist/stale-3JWHNDIY.js.map +1 -0
- package/dist/store-coordination-provider-3I7XWZZK.js +142 -0
- package/dist/store-coordination-provider-3I7XWZZK.js.map +1 -0
- package/dist/subject-index-O75wKshW.d.ts +362 -0
- package/dist/sync/index.d.ts +4 -6
- package/dist/sync/index.js +7 -6
- package/dist/sync/index.js.map +1 -1
- package/dist/team/index.d.ts +5 -7
- package/dist/team/index.js +20 -16
- package/dist/tiers/index.d.ts +5 -0
- package/dist/tiers/index.js +33 -0
- package/dist/tiers/index.js.map +1 -0
- package/dist/to/index.d.ts +5 -0
- package/dist/to/index.js +17 -0
- package/dist/to/index.js.map +1 -0
- package/dist/transition-guard-C7ol6oPw.d.ts +165 -0
- package/dist/tx/index.d.ts +23 -9
- package/dist/tx/index.js +13 -8
- package/dist/tx/index.js.map +1 -1
- package/dist/ui/index.d.ts +1 -0
- package/dist/ui/index.js +1 -0
- package/dist/ui/index.js.map +1 -0
- package/dist/ulid-DRH25k3y.d.ts +66 -0
- package/dist/ulid-PTAIMDG4.js +10 -0
- package/dist/ulid-PTAIMDG4.js.map +1 -0
- package/dist/util/index.d.ts +2 -0
- package/dist/util/index.js +7 -2
- package/dist/util/index.js.map +1 -1
- package/dist/vault-diff-B5fYNBL7.d.ts +147 -0
- package/dist/with/index.d.ts +38 -0
- package/dist/with/index.js +25 -0
- package/dist/with/index.js.map +1 -0
- package/dist/{with-materialized-view-BiasFcYx.d.ts → with-materialized-view-6p0Fk8bL.d.ts} +1 -1
- package/dist/{with-overlayed-view-CQViuko_.d.ts → with-overlayed-view-BJ6mXGMd.d.ts} +2 -3
- package/dist/with-rollup-BvQo3ROo.d.ts +47 -0
- package/dist/withdraw-accessible-FFS46EOD.js +22 -0
- package/dist/withdraw-accessible-FFS46EOD.js.map +1 -0
- package/dist/zod-HAJM7LMS.js +14763 -0
- package/dist/zod-HAJM7LMS.js.map +1 -0
- package/package.json +121 -201
- package/dist/aggregate/index.cjs.map +0 -1
- package/dist/aggregate/index.d.cts +0 -38
- package/dist/attestation/index.cjs +0 -305
- package/dist/attestation/index.cjs.map +0 -1
- package/dist/attestation/index.d.cts +0 -52
- package/dist/blobs/index.cjs +0 -1480
- package/dist/blobs/index.cjs.map +0 -1
- package/dist/blobs/index.d.cts +0 -46
- package/dist/bundle/index.cjs +0 -19104
- package/dist/bundle/index.cjs.map +0 -1
- package/dist/bundle/index.d.cts +0 -176
- package/dist/chunk-22DWZL57.js.map +0 -1
- package/dist/chunk-2GLDA55J.js.map +0 -1
- package/dist/chunk-2QR2PQTT.js.map +0 -1
- package/dist/chunk-2WUSG3IT.js.map +0 -1
- package/dist/chunk-3BFJOWSU.js.map +0 -1
- package/dist/chunk-3YPCK6JX.js.map +0 -1
- package/dist/chunk-53XBRIRT.js.map +0 -1
- package/dist/chunk-5T22KDPN.js.map +0 -1
- package/dist/chunk-5XHKQ56N.js +0 -340
- package/dist/chunk-5XHKQ56N.js.map +0 -1
- package/dist/chunk-6774ZOQ7.js.map +0 -1
- package/dist/chunk-6STK5TQP.js +0 -139
- package/dist/chunk-6STK5TQP.js.map +0 -1
- package/dist/chunk-A3JMGXPG.js.map +0 -1
- package/dist/chunk-B6PB7JLN.js.map +0 -1
- package/dist/chunk-BVRYKATC.js.map +0 -1
- package/dist/chunk-DE6GKS6G.js.map +0 -1
- package/dist/chunk-DFMLEQZB.js.map +0 -1
- package/dist/chunk-DJHHA6XH.js.map +0 -1
- package/dist/chunk-DL3HWOQ5.js.map +0 -1
- package/dist/chunk-DONMZAD2.js.map +0 -1
- package/dist/chunk-EMIGCR7X.js.map +0 -1
- package/dist/chunk-F3GDRNUT.js.map +0 -1
- package/dist/chunk-FZU343FL.js.map +0 -1
- package/dist/chunk-H2X3ISXG.js.map +0 -1
- package/dist/chunk-HNRHLRDC.js.map +0 -1
- package/dist/chunk-I5FOWO4J.js.map +0 -1
- package/dist/chunk-J66GRPNH.js.map +0 -1
- package/dist/chunk-JWRVQKRZ.js.map +0 -1
- package/dist/chunk-K3DK3NU5.js.map +0 -1
- package/dist/chunk-ML236QKC.js.map +0 -1
- package/dist/chunk-NONAAENK.js.map +0 -1
- package/dist/chunk-O3VZPBZG.js.map +0 -1
- package/dist/chunk-OIF6LZUR.js.map +0 -1
- package/dist/chunk-OQ6PIGHA.js +0 -19
- package/dist/chunk-OQ6PIGHA.js.map +0 -1
- package/dist/chunk-PE2FR4J3.js.map +0 -1
- package/dist/chunk-PP6W64Y3.js +0 -275
- package/dist/chunk-PP6W64Y3.js.map +0 -1
- package/dist/chunk-PX35GA7L.js.map +0 -1
- package/dist/chunk-QEILDE6R.js +0 -793
- package/dist/chunk-QEILDE6R.js.map +0 -1
- package/dist/chunk-QODLLGQ7.js.map +0 -1
- package/dist/chunk-RAZ4OVLL.js +0 -51
- package/dist/chunk-RAZ4OVLL.js.map +0 -1
- package/dist/chunk-SYMWGEET.js.map +0 -1
- package/dist/chunk-T7JEBOGN.js.map +0 -1
- package/dist/chunk-TFBP23BX.js.map +0 -1
- package/dist/chunk-TV3YZ35S.js +0 -90
- package/dist/chunk-TV3YZ35S.js.map +0 -1
- package/dist/chunk-U26HQ6KJ.js.map +0 -1
- package/dist/chunk-UF3BUNQZ.js +0 -1
- package/dist/chunk-UMLVJTYV.js +0 -20
- package/dist/chunk-UMLVJTYV.js.map +0 -1
- package/dist/chunk-VTKGMEPP.js.map +0 -1
- package/dist/chunk-W6EQLGMB.js +0 -100
- package/dist/chunk-W6EQLGMB.js.map +0 -1
- package/dist/chunk-WIRRPTFH.js +0 -17
- package/dist/chunk-WIRRPTFH.js.map +0 -1
- package/dist/chunk-WPLVTJ5D.js.map +0 -1
- package/dist/chunk-XJFLDA7A.js.map +0 -1
- package/dist/chunk-Z6FNBOTC.js.map +0 -1
- package/dist/chunk-ZYWZWG6G.js.map +0 -1
- package/dist/consent/index.cjs +0 -204
- package/dist/consent/index.cjs.map +0 -1
- package/dist/consent/index.d.cts +0 -25
- package/dist/crdt/index.cjs +0 -152
- package/dist/crdt/index.cjs.map +0 -1
- package/dist/crdt/index.d.cts +0 -30
- package/dist/crypto-HTZ4FJOP.js +0 -44
- package/dist/delegation-RI54P6I5.js +0 -17
- package/dist/derivations/index.cjs +0 -351
- package/dist/derivations/index.cjs.map +0 -1
- package/dist/derivations/index.d.cts +0 -72
- package/dist/dev-unlock-M4VAWNq_.d.cts +0 -263
- package/dist/executor-5PNY7LGW.js +0 -8
- package/dist/executor-B4QIYGZX.js +0 -8
- package/dist/executor-BWXXDQ7K.js +0 -11
- package/dist/fanout-sidecar-OKPMMPLG.js.map +0 -1
- package/dist/guards/index.cjs +0 -322
- package/dist/guards/index.cjs.map +0 -1
- package/dist/guards/index.d.cts +0 -31
- package/dist/hash-C1GtiOhR.d.ts +0 -63
- package/dist/history/index.cjs +0 -1222
- package/dist/history/index.cjs.map +0 -1
- package/dist/history/index.d.cts +0 -63
- package/dist/i18n/index.cjs +0 -1100
- package/dist/i18n/index.cjs.map +0 -1
- package/dist/i18n/index.d.cts +0 -39
- package/dist/index-4fBVt8j9.d.cts +0 -2387
- package/dist/index-D8I_pyJD.d.ts +0 -2387
- package/dist/index.cjs +0 -24334
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -776
- package/dist/indexing/index.cjs +0 -742
- package/dist/indexing/index.cjs.map +0 -1
- package/dist/indexing/index.d.cts +0 -36
- package/dist/issue-VGDPP4B5.js +0 -12
- package/dist/lazy-builder-7tIpFyWN.d.ts +0 -304
- package/dist/lazy-builder-wY4pMCEe.d.cts +0 -304
- package/dist/materialized-views/index.cjs +0 -854
- package/dist/materialized-views/index.cjs.map +0 -1
- package/dist/materialized-views/index.d.cts +0 -186
- package/dist/mime-magic-CBBSOkjm.d.cts +0 -50
- package/dist/mime-magic-CBBSOkjm.d.ts +0 -50
- package/dist/noydb-LZBH3XDK.js +0 -34
- package/dist/overlay-views/index.cjs +0 -359
- package/dist/overlay-views/index.cjs.map +0 -1
- package/dist/overlay-views/index.d.cts +0 -82
- package/dist/periods/index.cjs +0 -1041
- package/dist/periods/index.cjs.map +0 -1
- package/dist/periods/index.d.cts +0 -22
- package/dist/predicate-BSAGEyu5.d.cts +0 -209
- package/dist/predicate-BSAGEyu5.d.ts +0 -209
- package/dist/query/index.cjs +0 -2375
- package/dist/query/index.cjs.map +0 -1
- package/dist/query/index.d.cts +0 -3
- package/dist/read-only-facade-ITU6L7BL.js +0 -7
- package/dist/registry-3QP3YKQS.js +0 -8
- package/dist/registry-DKEXOJVO.js +0 -7
- package/dist/registry-OJIOSBV6.js +0 -10
- package/dist/registry-USRVT6YF.js +0 -8
- package/dist/revoke-JCC7N56X.js +0 -17
- package/dist/session/index.cjs +0 -495
- package/dist/session/index.cjs.map +0 -1
- package/dist/session/index.d.cts +0 -46
- package/dist/shadow/index.cjs +0 -133
- package/dist/shadow/index.cjs.map +0 -1
- package/dist/shadow/index.d.cts +0 -17
- package/dist/snapshots/index.cjs +0 -903
- package/dist/snapshots/index.cjs.map +0 -1
- package/dist/snapshots/index.d.cts +0 -21
- package/dist/store/index.cjs +0 -1083
- package/dist/store/index.cjs.map +0 -1
- package/dist/store/index.d.cts +0 -492
- package/dist/store/index.d.ts +0 -492
- package/dist/store/index.js +0 -37
- package/dist/strategy-BSxFXGzb.d.cts +0 -110
- package/dist/strategy-BSxFXGzb.d.ts +0 -110
- package/dist/strategy-DSTrsZ8t.d.cts +0 -601
- package/dist/strategy-DSTrsZ8t.d.ts +0 -601
- package/dist/sync/index.cjs +0 -1062
- package/dist/sync/index.cjs.map +0 -1
- package/dist/sync/index.d.cts +0 -43
- package/dist/team/index.cjs +0 -2798
- package/dist/team/index.cjs.map +0 -1
- package/dist/team/index.d.cts +0 -118
- package/dist/tx/index.cjs +0 -544
- package/dist/tx/index.cjs.map +0 -1
- package/dist/tx/index.d.cts +0 -21
- package/dist/types-DjunxzJa.d.cts +0 -12776
- package/dist/ulid-COREQ2RQ.js +0 -9
- package/dist/ulid-DPeuPgi3.d.cts +0 -603
- package/dist/util/index.cjs +0 -230
- package/dist/util/index.cjs.map +0 -1
- package/dist/util/index.d.cts +0 -77
- package/dist/with-derivation-Df0kMlED.d.cts +0 -13
- package/dist/with-derivation-DfOpKjFw.d.ts +0 -13
- package/dist/with-guard-0KksDtSR.d.ts +0 -18
- package/dist/with-guard-C6W5RVrH.d.cts +0 -18
- package/dist/with-materialized-view-BmDKyHrm.d.cts +0 -27
- package/dist/with-overlayed-view-CA66vhHz.d.cts +0 -13
- /package/dist/{store → adapter}/index.js.map +0 -0
- /package/dist/{chunk-UF3BUNQZ.js.map → api-RW3KP7WU.js.map} +0 -0
- /package/dist/{crypto-HTZ4FJOP.js.map → as/index.js.map} +0 -0
- /package/dist/{delegation-RI54P6I5.js.map → at/index.js.map} +0 -0
- /package/dist/{executor-5PNY7LGW.js.map → by/index.js.map} +0 -0
- /package/dist/{executor-B4QIYGZX.js.map → cargo/index.js.map} +0 -0
- /package/dist/{executor-BWXXDQ7K.js.map → chunk-BGIZAFY7.js.map} +0 -0
- /package/dist/{issue-VGDPP4B5.js.map → chunk-CHFZDSE4.js.map} +0 -0
- /package/dist/{ledger-TMRZYNVJ.js.map → chunk-GHVIKOHT.js.map} +0 -0
- /package/dist/{noydb-LZBH3XDK.js.map → chunk-K2WCO3NX.js.map} +0 -0
- /package/dist/{public-envelope-BW6OXORV.js.map → chunk-PZ5AY32C.js.map} +0 -0
- /package/dist/{read-only-facade-ITU6L7BL.js.map → collection-facade-GQAOGJP2.js.map} +0 -0
- /package/dist/{registry-3QP3YKQS.js.map → delegation-UL5HKLER.js.map} +0 -0
- /package/dist/{registry-DKEXOJVO.js.map → describe/index.js.map} +0 -0
- /package/dist/{registry-OJIOSBV6.js.map → enclave-UL5LW66V.js.map} +0 -0
- /package/dist/{registry-USRVT6YF.js.map → executor-2FWQRLMG.js.map} +0 -0
- /package/dist/{revoke-JCC7N56X.js.map → executor-QZ7BXICW.js.map} +0 -0
- /package/dist/{signer-72QAUSVW.js.map → executor-Z5ZLJVTV.js.map} +0 -0
- /package/dist/{stale-6ZDBTQT7.js.map → export-accessible-KRV5W4GH.js.map} +0 -0
- /package/dist/{ulid-COREQ2RQ.js.map → extract-partition-GLKBOXFQ.js.map} +0 -0
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
import {
|
|
2
|
-
decrypt
|
|
3
|
-
|
|
2
|
+
decrypt,
|
|
3
|
+
isTombstone
|
|
4
|
+
} from "./chunk-5O3AOPDT.js";
|
|
5
|
+
import {
|
|
6
|
+
NOYDB_FORMAT_VERSION
|
|
7
|
+
} from "./chunk-5TDJ56JE.js";
|
|
4
8
|
import {
|
|
5
9
|
ReadOnlyAtInstantError
|
|
6
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-ZYUC53LT.js";
|
|
7
11
|
|
|
8
|
-
// src/history/history.ts
|
|
12
|
+
// src/with-commit/history/history.ts
|
|
9
13
|
var HISTORY_COLLECTION = "_history";
|
|
10
14
|
var VERSION_PAD = 10;
|
|
11
15
|
function historyId(collection, recordId, version) {
|
|
@@ -79,8 +83,30 @@ async function clearHistory(adapter, vault, collection, recordId) {
|
|
|
79
83
|
}
|
|
80
84
|
return toDelete.length;
|
|
81
85
|
}
|
|
86
|
+
async function tombstoneHistory(adapter, vault, collection, recordId, actor, encrypted) {
|
|
87
|
+
const allIds = await adapter.list(vault, HISTORY_COLLECTION);
|
|
88
|
+
const matchingIds = allIds.filter((id) => matchesPrefix(id, collection, recordId));
|
|
89
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
90
|
+
let count = 0;
|
|
91
|
+
for (const id of matchingIds) {
|
|
92
|
+
const env = await adapter.get(vault, HISTORY_COLLECTION, id);
|
|
93
|
+
if (!env) continue;
|
|
94
|
+
if (isTombstone(env, encrypted)) continue;
|
|
95
|
+
const tombstone = {
|
|
96
|
+
_noydb: NOYDB_FORMAT_VERSION,
|
|
97
|
+
_v: env._v,
|
|
98
|
+
_ts: now,
|
|
99
|
+
_iv: "",
|
|
100
|
+
_data: "",
|
|
101
|
+
...actor ? { _by: actor } : {}
|
|
102
|
+
};
|
|
103
|
+
await adapter.put(vault, HISTORY_COLLECTION, id, tombstone);
|
|
104
|
+
count++;
|
|
105
|
+
}
|
|
106
|
+
return count;
|
|
107
|
+
}
|
|
82
108
|
|
|
83
|
-
// src/history/time-machine.ts
|
|
109
|
+
// src/with-commit/history/time-machine.ts
|
|
84
110
|
var VaultInstant = class {
|
|
85
111
|
constructor(engine, timestamp) {
|
|
86
112
|
this.engine = engine;
|
|
@@ -187,7 +213,7 @@ var CollectionInstant = class {
|
|
|
187
213
|
for (const e of entries) {
|
|
188
214
|
if (e.collection !== this.name || e.id !== id) continue;
|
|
189
215
|
if (e.ts > this.targetTs) break;
|
|
190
|
-
if (e.op === "amendment" || e.op === "lifecycle") continue;
|
|
216
|
+
if (e.op === "amendment" || e.op === "lifecycle" || e.op === "forget") continue;
|
|
191
217
|
latest = { op: e.op === "migration" ? "put" : e.op, version: e.version };
|
|
192
218
|
}
|
|
193
219
|
if (!latest) return null;
|
|
@@ -239,74 +265,14 @@ async function collectHistoryIds(adapter, vault, collection) {
|
|
|
239
265
|
return [...seen];
|
|
240
266
|
}
|
|
241
267
|
|
|
242
|
-
// src/history/diff.ts
|
|
243
|
-
function diff(oldObj, newObj, basePath = "") {
|
|
244
|
-
const changes = [];
|
|
245
|
-
if (oldObj === newObj) return changes;
|
|
246
|
-
if (oldObj == null && newObj != null) {
|
|
247
|
-
return [{ path: basePath || "(root)", type: "added", to: newObj }];
|
|
248
|
-
}
|
|
249
|
-
if (oldObj != null && newObj == null) {
|
|
250
|
-
return [{ path: basePath || "(root)", type: "removed", from: oldObj }];
|
|
251
|
-
}
|
|
252
|
-
if (typeof oldObj !== typeof newObj) {
|
|
253
|
-
return [{ path: basePath || "(root)", type: "changed", from: oldObj, to: newObj }];
|
|
254
|
-
}
|
|
255
|
-
if (typeof oldObj !== "object") {
|
|
256
|
-
return [{ path: basePath || "(root)", type: "changed", from: oldObj, to: newObj }];
|
|
257
|
-
}
|
|
258
|
-
if (Array.isArray(oldObj) && Array.isArray(newObj)) {
|
|
259
|
-
const maxLen = Math.max(oldObj.length, newObj.length);
|
|
260
|
-
for (let i = 0; i < maxLen; i++) {
|
|
261
|
-
const p = basePath ? `${basePath}[${i}]` : `[${i}]`;
|
|
262
|
-
if (i >= oldObj.length) {
|
|
263
|
-
changes.push({ path: p, type: "added", to: newObj[i] });
|
|
264
|
-
} else if (i >= newObj.length) {
|
|
265
|
-
changes.push({ path: p, type: "removed", from: oldObj[i] });
|
|
266
|
-
} else {
|
|
267
|
-
changes.push(...diff(oldObj[i], newObj[i], p));
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
return changes;
|
|
271
|
-
}
|
|
272
|
-
const oldRecord = oldObj;
|
|
273
|
-
const newRecord = newObj;
|
|
274
|
-
const allKeys = /* @__PURE__ */ new Set([...Object.keys(oldRecord), ...Object.keys(newRecord)]);
|
|
275
|
-
for (const key of allKeys) {
|
|
276
|
-
const p = basePath ? `${basePath}.${key}` : key;
|
|
277
|
-
if (!(key in oldRecord)) {
|
|
278
|
-
changes.push({ path: p, type: "added", to: newRecord[key] });
|
|
279
|
-
} else if (!(key in newRecord)) {
|
|
280
|
-
changes.push({ path: p, type: "removed", from: oldRecord[key] });
|
|
281
|
-
} else {
|
|
282
|
-
changes.push(...diff(oldRecord[key], newRecord[key], p));
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
return changes;
|
|
286
|
-
}
|
|
287
|
-
function formatDiff(changes) {
|
|
288
|
-
if (changes.length === 0) return "(no changes)";
|
|
289
|
-
return changes.map((c) => {
|
|
290
|
-
switch (c.type) {
|
|
291
|
-
case "added":
|
|
292
|
-
return `+ ${c.path}: ${JSON.stringify(c.to)}`;
|
|
293
|
-
case "removed":
|
|
294
|
-
return `- ${c.path}: ${JSON.stringify(c.from)}`;
|
|
295
|
-
case "changed":
|
|
296
|
-
return `~ ${c.path}: ${JSON.stringify(c.from)} \u2192 ${JSON.stringify(c.to)}`;
|
|
297
|
-
}
|
|
298
|
-
}).join("\n");
|
|
299
|
-
}
|
|
300
|
-
|
|
301
268
|
export {
|
|
302
269
|
saveHistory,
|
|
303
270
|
getHistory,
|
|
304
271
|
getVersionEnvelope,
|
|
305
272
|
pruneHistory,
|
|
306
273
|
clearHistory,
|
|
274
|
+
tombstoneHistory,
|
|
307
275
|
VaultInstant,
|
|
308
|
-
CollectionInstant
|
|
309
|
-
diff,
|
|
310
|
-
formatDiff
|
|
276
|
+
CollectionInstant
|
|
311
277
|
};
|
|
312
|
-
//# sourceMappingURL=chunk-
|
|
278
|
+
//# sourceMappingURL=chunk-MD3Y6J3L.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/with-commit/history/history.ts","../src/with-commit/history/time-machine.ts"],"sourcesContent":["import type { NoydbStore, EncryptedEnvelope, HistoryOptions, PruneOptions } from '../../kernel/types.js'\nimport { NOYDB_FORMAT_VERSION } from '../../kernel/types.js'\nimport { isTombstone } from '../../kernel/enclave/index.js'\n\n/**\n * History storage convention:\n * Collection: `_history`\n * ID format: `{collection}:{recordId}:{paddedVersion}`\n * Version is zero-padded to 10 digits for lexicographic sorting.\n */\n\nconst HISTORY_COLLECTION = '_history'\nconst VERSION_PAD = 10\n\nfunction historyId(collection: string, recordId: string, version: number): string {\n return `${collection}:${recordId}:${String(version).padStart(VERSION_PAD, '0')}`\n}\n\n// Unused today, kept for future history-id parsing utilities.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction parseHistoryId(id: string): { collection: string; recordId: string; version: number } | null {\n const lastColon = id.lastIndexOf(':')\n if (lastColon < 0) return null\n const versionStr = id.slice(lastColon + 1)\n const rest = id.slice(0, lastColon)\n const firstColon = rest.indexOf(':')\n if (firstColon < 0) return null\n return {\n collection: rest.slice(0, firstColon),\n recordId: rest.slice(firstColon + 1),\n version: parseInt(versionStr, 10),\n }\n}\n\nfunction matchesPrefix(id: string, collection: string, recordId?: string): boolean {\n if (recordId) {\n return id.startsWith(`${collection}:${recordId}:`)\n }\n return id.startsWith(`${collection}:`)\n}\n\n/** Save a history entry (a complete encrypted envelope snapshot). */\nexport async function saveHistory(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n envelope: EncryptedEnvelope,\n): Promise<void> {\n const id = historyId(collection, recordId, envelope._v)\n await adapter.put(vault, HISTORY_COLLECTION, id, envelope)\n}\n\n/** Get history entries for a record, sorted newest-first. */\nexport async function getHistory(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n options?: HistoryOptions,\n): Promise<EncryptedEnvelope[]> {\n const allIds = await adapter.list(vault, HISTORY_COLLECTION)\n const matchingIds = allIds\n .filter(id => matchesPrefix(id, collection, recordId))\n .sort()\n .reverse() // newest first\n\n const entries: EncryptedEnvelope[] = []\n\n for (const id of matchingIds) {\n const envelope = await adapter.get(vault, HISTORY_COLLECTION, id)\n if (!envelope) continue\n\n // Apply time filters\n if (options?.from && envelope._ts < options.from) continue\n if (options?.to && envelope._ts > options.to) continue\n\n entries.push(envelope)\n\n if (options?.limit && entries.length >= options.limit) break\n }\n\n return entries\n}\n\n/** Get a specific version's envelope from history. */\nexport async function getVersionEnvelope(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n version: number,\n): Promise<EncryptedEnvelope | null> {\n const id = historyId(collection, recordId, version)\n return adapter.get(vault, HISTORY_COLLECTION, id)\n}\n\n/** Prune history entries. Returns the number of entries deleted. */\nexport async function pruneHistory(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string | undefined,\n options: PruneOptions,\n): Promise<number> {\n const allIds = await adapter.list(vault, HISTORY_COLLECTION)\n const matchingIds = allIds\n .filter(id => recordId ? matchesPrefix(id, collection, recordId) : matchesPrefix(id, collection))\n .sort()\n\n let toDelete: string[] = []\n\n if (options.keepVersions !== undefined) {\n // Keep only the N most recent, delete the rest\n const keep = options.keepVersions\n if (matchingIds.length > keep) {\n toDelete = matchingIds.slice(0, matchingIds.length - keep)\n }\n }\n\n if (options.beforeDate) {\n // Delete entries older than the specified date\n for (const id of matchingIds) {\n if (toDelete.includes(id)) continue\n const envelope = await adapter.get(vault, HISTORY_COLLECTION, id)\n if (envelope && envelope._ts < options.beforeDate) {\n toDelete.push(id)\n }\n }\n }\n\n // Deduplicate\n const uniqueDeletes = [...new Set(toDelete)]\n\n for (const id of uniqueDeletes) {\n await adapter.delete(vault, HISTORY_COLLECTION, id)\n }\n\n return uniqueDeletes.length\n}\n\n/** Clear all history for a vault, optionally scoped to a collection or record. */\nexport async function clearHistory(\n adapter: NoydbStore,\n vault: string,\n collection?: string,\n recordId?: string,\n): Promise<number> {\n const allIds = await adapter.list(vault, HISTORY_COLLECTION)\n let toDelete: string[]\n\n if (collection && recordId) {\n toDelete = allIds.filter(id => matchesPrefix(id, collection, recordId))\n } else if (collection) {\n toDelete = allIds.filter(id => matchesPrefix(id, collection))\n } else {\n toDelete = allIds\n }\n\n for (const id of toDelete) {\n await adapter.delete(vault, HISTORY_COLLECTION, id)\n }\n\n return toDelete.length\n}\n\n/**\n * Crypto-shred every `_history` version of a record. Each non-tombstone\n * history envelope is OVERWRITTEN in place with a tombstone\n * `{ _noydb, _v, _ts: now, _by: actor, _iv: '', _data: '' }` — dropping\n * `_iv`/`_data`/`_cek`/`_det`, so the prior ciphertext (and the wrapped CEK\n * that could decrypt it) is gone everywhere this store reaches. The version\n * counter (`_v`) is preserved so the audit trail still shows \"N versions\n * existed and were erased.\"\n *\n * Overwrite — NOT delete — so the history key itself survives as proof the\n * version existed. Already-tombstoned versions (re-run / idempotent forget)\n * are left untouched and not counted.\n *\n * Returns the number of history versions newly tombstoned.\n */\nexport async function tombstoneHistory(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n actor: string,\n encrypted: boolean,\n): Promise<number> {\n const allIds = await adapter.list(vault, HISTORY_COLLECTION)\n const matchingIds = allIds.filter(id => matchesPrefix(id, collection, recordId))\n\n const now = new Date().toISOString()\n let count = 0\n for (const id of matchingIds) {\n const env = await adapter.get(vault, HISTORY_COLLECTION, id)\n if (!env) continue\n // Already a tombstone (no body and no wrapped CEK)? Skip — idempotent.\n if (isTombstone(env, encrypted)) continue\n const tombstone: EncryptedEnvelope = {\n _noydb: NOYDB_FORMAT_VERSION,\n _v: env._v,\n _ts: now,\n _iv: '',\n _data: '',\n ...(actor ? { _by: actor } : {}),\n }\n await adapter.put(vault, HISTORY_COLLECTION, id, tombstone)\n count++\n }\n return count\n}\n","/**\n * Time-machine queries — point-in-time reads reconstructed from the\n * existing history + ledger infrastructure.\n *\n * ## Usage\n *\n * ```ts\n * const vault = await db.openVault('acme', { passphrase })\n * const q1End = vault.at('2026-03-31T23:59:59Z')\n * const invoice = await q1End.collection<Invoice>('invoices').get('inv-001')\n * // → the record as it stood at the close of Q1 2026\n * ```\n *\n * ## How it works\n *\n * Every write path already fans out into two persistence lanes:\n *\n * 1. `saveHistory(...)` persists a **full encrypted envelope snapshot**\n * per version under the `_history` collection (one envelope per\n * version, keyed by `{collection}:{id}:{paddedVersion}`). Each\n * envelope carries its own `_ts` (the write timestamp).\n * 2. `ledger.append(...)` appends a hash-chained audit entry that\n * records the `op` (put / delete), `version`, and `ts`.\n *\n * Reconstruction at a target timestamp T is therefore:\n *\n * - Find the newest history envelope for `(collection, id)` whose\n * `_ts ≤ T` — that's the state the record was in at T.\n * - Check the ledger for any `op: 'delete'` entry for the same\n * `(collection, id)` with `entry.ts` in `(latestEnvelope._ts, T]` —\n * if present, the record was deleted before T, so return `null`.\n * - Decrypt the surviving envelope with the current collection DEK\n * (DEKs are per-collection but stable across versions — the same\n * key encrypts v1 and v15 of a record).\n *\n * No delta replay. The existing `history.ts` module already stores\n * complete snapshots; we just pick the right one.\n *\n * ## Read-only contract\n *\n * Every write method on `CollectionInstant` throws\n * {@link ReadOnlyAtInstantError}. A historical view is a *read*\n * surface — mutating the past would require either a branch/shadow\n * mechanism (tracked under shadow vaults) or a rewrite of\n * history, which breaks the ledger's tamper-evidence guarantee.\n *\n * @module\n */\nimport type { EncryptedEnvelope, NoydbStore } from '../../kernel/types.js'\nimport type { LedgerStore } from './ledger/store.js'\nimport { getHistory } from './history.js'\nimport { decrypt, type EnclaveKey } from '../../kernel/enclave/index.js'\nimport { ReadOnlyAtInstantError } from '../../kernel/errors.js'\n\n/**\n * Narrow view of a {@link Vault}'s internals that\n * {@link VaultInstant} needs. Passed in by `Vault.at()` rather than\n * constructed here so all crypto + adapter access stays inside the\n * Vault class.\n *\n * Not exported from the public barrel — consumers should get a\n * `VaultInstant` via `vault.at(ts)`, never by constructing one\n * directly.\n */\nexport interface VaultEngine {\n readonly adapter: NoydbStore\n /** Vault name (the compartment). */\n readonly name: string\n /**\n * `true` when the vault was opened with a passphrase (the normal\n * case). `false` in plaintext-mode vaults (`encrypt: false`) — in\n * that case `envelope._data` is raw JSON and we skip the DEK lookup.\n */\n readonly encrypted: boolean\n /**\n * Resolves the DEK used to decrypt a given collection's envelopes.\n * Not called when `encrypted` is false.\n */\n getDEK(collection: string): Promise<EnclaveKey>\n /**\n * Lazily-initialised ledger. We consult it to detect deletes that\n * happened between the latest history snapshot and the target\n * timestamp. `null` when history is disabled for this vault — in\n * that case time-machine reads fall back to history-only\n * reconstruction (which may miss deletes).\n */\n getLedger(): LedgerStore | null\n}\n\n/**\n * A vault at a fixed instant. Produced by `vault.at(timestamp)`.\n * Carries no session state of its own — every read is a fresh\n * lookup through the vault's adapter.\n *\n * Cheap to construct; safe to throw away. Create one per query.\n */\nexport class VaultInstant {\n constructor(\n private readonly engine: VaultEngine,\n /** Fully-resolved target timestamp (ISO-8601 UTC). */\n public readonly timestamp: string,\n ) {}\n\n /** Get a point-in-time view of a collection. */\n collection<T = unknown>(name: string): CollectionInstant<T> {\n return new CollectionInstant<T>(this.engine, this.timestamp, name)\n }\n}\n\n/**\n * A read-only collection view anchored to a past instant.\n *\n * Every write method throws {@link ReadOnlyAtInstantError} — see the\n * module docstring for why. The read surface is intentionally smaller\n * than the live {@link Collection}: `get` and `list` cover the\n * \"what did the books look like on date X\" use case without pulling\n * in the full query DSL / joins / aggregates at this stage. Follow-up\n * work tracked under.\n */\nexport class CollectionInstant<T = unknown> {\n constructor(\n private readonly engine: VaultEngine,\n private readonly targetTs: string,\n public readonly name: string,\n ) {}\n\n /**\n * Return the record as it existed at the target timestamp, or\n * `null` if the record had not been created yet or had already been\n * deleted by then.\n */\n async get(id: string): Promise<T | null> {\n const envelope = await this.resolveEnvelope(id)\n if (!envelope) return null\n const plaintext = this.engine.encrypted\n ? await decrypt(envelope._iv, envelope._data, await this.engine.getDEK(this.name))\n : envelope._data\n return JSON.parse(plaintext) as T\n }\n\n /**\n * IDs of records that existed (had at least one `put` and were not\n * subsequently deleted) at the target timestamp.\n *\n * Implemented as a linear scan over history + ledger. Performance\n * is bounded by total history size (not live-vault size), so the\n * memory-first vault-scale cap (1K–50K records × average history\n * depth) still applies.\n */\n async list(): Promise<string[]> {\n const historyIds = await collectHistoryIds(this.engine.adapter, this.engine.name, this.name)\n const liveIds = await this.engine.adapter.list(this.engine.name, this.name)\n const candidateIds = new Set<string>([...historyIds, ...liveIds])\n const alive: string[] = []\n for (const id of candidateIds) {\n const env = await this.resolveEnvelope(id)\n if (env) alive.push(id)\n }\n return alive.sort()\n }\n\n // ── write guards ───────────────────────────────────────────────────\n\n async put(_id: string, _record: T): Promise<never> {\n throw new ReadOnlyAtInstantError('put', this.targetTs)\n }\n async delete(_id: string): Promise<never> {\n throw new ReadOnlyAtInstantError('delete', this.targetTs)\n }\n async update(_id: string, _patch: Partial<T>): Promise<never> {\n throw new ReadOnlyAtInstantError('update', this.targetTs)\n }\n\n // ── internals ─────────────────────────────────────────────────────\n\n /**\n * Return the envelope that represents the record's state at\n * `targetTs`, accounting for deletes. `null` if the record didn't\n * exist at that instant.\n *\n * ## Why we use the ledger as the authoritative timeline\n *\n * The per-version history snapshots saved by `saveHistory()` do\n * carry a `_ts` field, but that timestamp is the moment the\n * snapshot was *captured* (i.e. the instant right before the\n * subsequent overwrite), not the original write time. The ledger,\n * by contrast, records `ts` at the moment of each `put` / `delete`\n * — it's the only source that tracks the real timeline. So:\n *\n * 1. Walk the ledger; find the latest entry for `(collection, id)`\n * with `ts ≤ targetTs`.\n * 2. If that entry is a `delete`, the record was gone at the\n * target instant — return null.\n * 3. Otherwise it's a `put` with a specific `version`. Load the\n * envelope for that version from history, falling back to the\n * live collection for the most recent version.\n *\n * ## Fallback when the ledger is disabled\n *\n * If the vault has history disabled, `getLedger()` returns null and\n * we fall back to comparing envelope `_ts` fields. This is\n * approximate and gets the *last write* right but may confuse the\n * intermediate versions; adopters needing accurate time-machine\n * reads should leave history enabled.\n */\n private async resolveEnvelope(id: string): Promise<EncryptedEnvelope | null> {\n const ledger = this.engine.getLedger()\n if (ledger) {\n return this.resolveViaLedger(id, ledger)\n }\n return this.resolveViaEnvelopeTs(id)\n }\n\n private async resolveViaLedger(id: string, ledger: LedgerStore): Promise<EncryptedEnvelope | null> {\n const entries = await ledger.entries()\n // Entries are already ordered by index which is the mutation order.\n let latest: { op: 'put' | 'delete'; version: number } | null = null\n for (const e of entries) {\n if (e.collection !== this.name || e.id !== id) continue\n if (e.ts > this.targetTs) break // entries are time-ordered by index\n // `amendment` + `lifecycle` entries are audit-only summaries — they\n // carry no (collection, id) tuple of their own and would never match\n // the filter above. The narrow here is a type guard, not a runtime\n // skip.\n // `forget` is a subject-erasure summary with empty (collection, id) —\n // never matches the filter above; the narrow is a type guard.\n if (e.op === 'amendment' || e.op === 'lifecycle' || e.op === 'forget') continue\n // `migration` is a record rewrite (cutover) — resolve it like a put.\n latest = { op: e.op === 'migration' ? 'put' : e.op, version: e.version }\n }\n if (!latest) return null\n if (latest.op === 'delete') return null\n return this.loadVersion(id, latest.version)\n }\n\n private async resolveViaEnvelopeTs(id: string): Promise<EncryptedEnvelope | null> {\n const history = await getHistory(\n this.engine.adapter, this.engine.name, this.name, id,\n )\n const live = await this.engine.adapter.get(this.engine.name, this.name, id)\n const byVersion = new Map<number, EncryptedEnvelope>()\n for (const e of history) byVersion.set(e._v, e)\n if (live) byVersion.set(live._v, live)\n const sorted = [...byVersion.values()].sort((a, b) =>\n a._ts < b._ts ? 1 : a._ts > b._ts ? -1 : 0,\n )\n return sorted.find((e) => e._ts <= this.targetTs) ?? null\n }\n\n /**\n * Fetch the envelope for a specific version. The live record (most\n * recent put) lives in the main collection; prior versions live in\n * `_history`. We check live first because the common case after a\n * delete is that we're trying to load the last-live version from\n * history, and skipping live for the current-version case avoids a\n * redundant lookup.\n */\n private async loadVersion(id: string, version: number): Promise<EncryptedEnvelope | null> {\n const live = await this.engine.adapter.get(this.engine.name, this.name, id)\n if (live && live._v === version) return live\n\n // Direct lookup by (collection, id, version) — avoids scanning all history.\n const historyId = `${this.name}:${id}:${String(version).padStart(10, '0')}`\n return await this.engine.adapter.get(this.engine.name, '_history', historyId)\n }\n}\n\n/**\n * Scan the `_history` collection once and collect every distinct\n * `recordId` for the given collection. History keys follow the\n * shape `<collection>:<recordId>:<paddedVersion>`; we split on the\n * last two colons (delimiter-safe because `paddedVersion` is\n * exactly 10 digits).\n */\nasync function collectHistoryIds(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n): Promise<string[]> {\n const all = await adapter.list(vault, '_history')\n const prefix = `${collection}:`\n const seen = new Set<string>()\n for (const key of all) {\n if (!key.startsWith(prefix)) continue\n const lastColon = key.lastIndexOf(':')\n if (lastColon <= prefix.length) continue\n const middle = key.slice(prefix.length, lastColon)\n seen.add(middle)\n }\n return [...seen]\n}\n"],"mappings":";;;;;;;;;;;;AAWA,IAAM,qBAAqB;AAC3B,IAAM,cAAc;AAEpB,SAAS,UAAU,YAAoB,UAAkB,SAAyB;AAChF,SAAO,GAAG,UAAU,IAAI,QAAQ,IAAI,OAAO,OAAO,EAAE,SAAS,aAAa,GAAG,CAAC;AAChF;AAkBA,SAAS,cAAc,IAAY,YAAoB,UAA4B;AACjF,MAAI,UAAU;AACZ,WAAO,GAAG,WAAW,GAAG,UAAU,IAAI,QAAQ,GAAG;AAAA,EACnD;AACA,SAAO,GAAG,WAAW,GAAG,UAAU,GAAG;AACvC;AAGA,eAAsB,YACpB,SACA,OACA,YACA,UACA,UACe;AACf,QAAM,KAAK,UAAU,YAAY,UAAU,SAAS,EAAE;AACtD,QAAM,QAAQ,IAAI,OAAO,oBAAoB,IAAI,QAAQ;AAC3D;AAGA,eAAsB,WACpB,SACA,OACA,YACA,UACA,SAC8B;AAC9B,QAAM,SAAS,MAAM,QAAQ,KAAK,OAAO,kBAAkB;AAC3D,QAAM,cAAc,OACjB,OAAO,QAAM,cAAc,IAAI,YAAY,QAAQ,CAAC,EACpD,KAAK,EACL,QAAQ;AAEX,QAAM,UAA+B,CAAC;AAEtC,aAAW,MAAM,aAAa;AAC5B,UAAM,WAAW,MAAM,QAAQ,IAAI,OAAO,oBAAoB,EAAE;AAChE,QAAI,CAAC,SAAU;AAGf,QAAI,SAAS,QAAQ,SAAS,MAAM,QAAQ,KAAM;AAClD,QAAI,SAAS,MAAM,SAAS,MAA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,MAAM,KAAK;AAAA,IAC3C;AACA,WAAO,OAAO,KAAK,CAAC,MAAM,EAAE,OAAO,KAAK,QAAQ,KAAK;AAAA,EACvD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,MAAc,YAAY,IAAY,SAAoD;AACxF,UAAM,OAAO,MAAM,KAAK,OAAO,QAAQ,IAAI,KAAK,OAAO,MAAM,KAAK,MAAM,EAAE;AAC1E,QAAI,QAAQ,KAAK,OAAO,QAAS,QAAO;AAGxC,UAAMA,aAAY,GAAG,KAAK,IAAI,IAAI,EAAE,IAAI,OAAO,OAAO,EAAE,SAAS,IAAI,GAAG,CAAC;AACzE,WAAO,MAAM,KAAK,OAAO,QAAQ,IAAI,KAAK,OAAO,MAAM,YAAYA,UAAS;AAAA,EAC9E;AACF;AASA,eAAe,kBACb,SACA,OACA,YACmB;AACnB,QAAM,MAAM,MAAM,QAAQ,KAAK,OAAO,UAAU;AAChD,QAAM,SAAS,GAAG,UAAU;AAC5B,QAAM,OAAO,oBAAI,IAAY;AAC7B,aAAW,OAAO,KAAK;AACrB,QAAI,CAAC,IAAI,WAAW,MAAM,EAAG;AAC7B,UAAM,YAAY,IAAI,YAAY,GAAG;AACrC,QAAI,aAAa,OAAO,OAAQ;AAChC,UAAM,SAAS,IAAI,MAAM,OAAO,QAAQ,SAAS;AACjD,SAAK,IAAI,MAAM;AAAA,EACjB;AACA,SAAO,CAAC,GAAG,IAAI;AACjB;","names":["historyId"]}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
2
|
generateULID
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-ZJADGNYF.js";
|
|
4
4
|
import {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
} from "./chunk-
|
|
5
|
+
encrypt,
|
|
6
|
+
openEnvelopeJson
|
|
7
|
+
} from "./chunk-5O3AOPDT.js";
|
|
8
8
|
|
|
9
|
-
// src/consent/consent.ts
|
|
9
|
+
// src/with-audit/consent/consent.ts
|
|
10
10
|
var CONSENT_AUDIT_COLLECTION = "_consent_audit";
|
|
11
11
|
async function writeConsentEntry(adapter, vault, encrypted, entry, getDEK) {
|
|
12
12
|
const id = generateULID();
|
|
@@ -52,7 +52,8 @@ async function buildEnvelope(entry, encrypted, getDEK) {
|
|
|
52
52
|
};
|
|
53
53
|
}
|
|
54
54
|
async function decryptEntry(envelope, encrypted, getDEK) {
|
|
55
|
-
|
|
55
|
+
if (!encrypted) return JSON.parse(envelope._data);
|
|
56
|
+
const json = await openEnvelopeJson(envelope, await getDEK(CONSENT_AUDIT_COLLECTION));
|
|
56
57
|
return JSON.parse(json);
|
|
57
58
|
}
|
|
58
59
|
function matchesFilter(entry, f) {
|
|
@@ -69,4 +70,4 @@ export {
|
|
|
69
70
|
writeConsentEntry,
|
|
70
71
|
loadConsentEntries
|
|
71
72
|
};
|
|
72
|
-
//# sourceMappingURL=chunk-
|
|
73
|
+
//# sourceMappingURL=chunk-MTMJVJ5W.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/with-audit/consent/consent.ts"],"sourcesContent":["/**\n * Consent boundaries — per-access audit log.\n *\n * ```ts\n * const audit = await vault.withConsent(\n * { purpose: 'quarterly-review', consentHash: '7f3a...' },\n * async () => {\n * const invoices = await vault.collection<Invoice>('invoices').list()\n * return invoices\n * },\n * )\n *\n * const log = await vault.consentAudit({ since: '2026-01-01T00:00:00Z' })\n * // → entries: { actor, purpose, consentHash, ts, op, collection, id }\n * ```\n *\n * ## Contract\n *\n * Every `get` / `put` / `delete` that happens inside a `withConsent`\n * callback writes one entry to the reserved `_consent_audit`\n * collection. Entries are encrypted with the vault's consent-audit\n * DEK (separate from per-user-collection DEKs so access-log queries\n * don't require unwrapping individual collection keys). Outside a\n * `withConsent` scope, no entries are written — consent is\n * opt-in by design (GDPR Art. 7: *demonstrable*, *specific*\n * consent).\n *\n * ## Why store the hash, not the consent text?\n *\n * The `consentHash` is the sha256 of whatever consent receipt the\n * actor presented (a signed GDPR banner click, a HIPAA authorisation\n * PDF, an API-level `X-Consent-Hash` header). Storing only the hash:\n *\n * 1. Keeps the audit log small and indexable.\n * 2. Preserves zero-knowledge at the adapter — adapters see\n * ciphertext envelopes of `{ actor, purpose, consentHash, ts,\n * op, collection, id }`, never the consent record itself.\n * 3. Lets the regulator verify a presented consent doc matches\n * the logged hash at audit time without the system ever\n * possessing the doc.\n *\n * ## Concurrency\n *\n * The consent context lives on the {@link Vault} instance. Two\n * concurrent `withConsent` calls on the same Vault would stomp each\n * other — documented limitation; adopters needing per-flight scope\n * should use separate Vault instances or an AsyncLocalStorage shim.\n *\n * @module\n */\nimport type { EncryptedEnvelope, NoydbStore } from '../../kernel/types.js'\nimport { encrypt, openEnvelopeJson, type EnclaveKey } from '../../kernel/enclave/index.js'\nimport { generateULID } from '../../with-pod/ulid.js'\n\n/** Reserved collection for consent-audit entries. */\nexport const CONSENT_AUDIT_COLLECTION = '_consent_audit'\n\n/**\n * The consent scope active for a block of work. Set via\n * `vault.withConsent()`; observed by the collection's access hooks.\n */\nexport interface ConsentContext {\n /**\n * What this access is for. Used by the audit query (`consentAudit\n * ({ purpose })`) and carried in the stored entry. Free-form; the\n * regulator or compliance tooling decides the vocabulary.\n */\n readonly purpose: string\n /**\n * Hex-encoded sha256 of whatever consent artefact the actor\n * presented. Stored as-is in each entry.\n */\n readonly consentHash: string\n}\n\n/** Access operation recorded in an audit entry. */\nexport type ConsentOp = 'get' | 'put' | 'delete'\n\n/** One consent-audit record, as decrypted for the caller. */\nexport interface ConsentAuditEntry {\n /** ULID — stable insertion-order key. */\n readonly id: string\n readonly timestamp: string\n readonly actor: string\n readonly purpose: string\n readonly consentHash: string\n readonly op: ConsentOp\n readonly collection: string\n readonly recordId: string\n}\n\n/** Filter passed to `vault.consentAudit()`. */\nexport interface ConsentAuditFilter {\n /** Only entries at or after this ISO timestamp. */\n readonly since?: string\n /** Only entries at or before this ISO timestamp. */\n readonly until?: string\n /** Match entries targeting this collection. */\n readonly collection?: string\n /** Match entries written by this actor. */\n readonly actor?: string\n /** Match entries with this purpose. */\n readonly purpose?: string\n}\n\n/**\n * Write one audit entry. Called by Vault's onAccess hook when a\n * consent context is active.\n */\nexport async function writeConsentEntry(\n adapter: NoydbStore,\n vault: string,\n encrypted: boolean,\n entry: Omit<ConsentAuditEntry, 'id' | 'timestamp'>,\n getDEK: (collection: string) => Promise<EnclaveKey>,\n): Promise<void> {\n const id = generateULID()\n const full: ConsentAuditEntry = {\n id,\n timestamp: new Date().toISOString(),\n ...entry,\n }\n const envelope = await buildEnvelope(full, encrypted, getDEK)\n await adapter.put(vault, CONSENT_AUDIT_COLLECTION, id, envelope)\n}\n\n/** Load + decrypt + filter all entries. */\nexport async function loadConsentEntries(\n adapter: NoydbStore,\n vault: string,\n encrypted: boolean,\n getDEK: (collection: string) => Promise<EnclaveKey>,\n filter: ConsentAuditFilter = {},\n): Promise<ConsentAuditEntry[]> {\n const ids = await adapter.list(vault, CONSENT_AUDIT_COLLECTION)\n const entries: ConsentAuditEntry[] = []\n\n for (const id of ids.sort()) {\n const envelope = await adapter.get(vault, CONSENT_AUDIT_COLLECTION, id)\n if (!envelope) continue\n const entry = await decryptEntry(envelope, encrypted, getDEK)\n if (!matchesFilter(entry, filter)) continue\n entries.push(entry)\n }\n return entries\n}\n\n// ── internals ──────────────────────────────────────────────────────\n\nasync function buildEnvelope(\n entry: ConsentAuditEntry,\n encrypted: boolean,\n getDEK: (collection: string) => Promise<EnclaveKey>,\n): Promise<EncryptedEnvelope> {\n const json = JSON.stringify(entry)\n if (!encrypted) {\n return {\n _noydb: 1,\n _v: 1,\n _ts: entry.timestamp,\n _iv: '',\n _data: json,\n }\n }\n const dek = await getDEK(CONSENT_AUDIT_COLLECTION)\n const { iv, data } = await encrypt(json, dek)\n return {\n _noydb: 1,\n _v: 1,\n _ts: entry.timestamp,\n _iv: iv,\n _data: data,\n }\n}\n\nasync function decryptEntry(\n envelope: EncryptedEnvelope,\n encrypted: boolean,\n getDEK: (collection: string) => Promise<EnclaveKey>,\n): Promise<ConsentAuditEntry> {\n if (!encrypted) return JSON.parse(envelope._data) as ConsentAuditEntry\n const json = await openEnvelopeJson(envelope, await getDEK(CONSENT_AUDIT_COLLECTION))\n return JSON.parse(json) as ConsentAuditEntry\n}\n\nfunction matchesFilter(entry: ConsentAuditEntry, f: ConsentAuditFilter): boolean {\n if (f.since && entry.timestamp < f.since) return false\n if (f.until && entry.timestamp > f.until) return false\n if (f.collection && entry.collection !== f.collection) return false\n if (f.actor && entry.actor !== f.actor) return false\n if (f.purpose && entry.purpose !== f.purpose) return false\n return true\n}\n"],"mappings":";;;;;;;;;AAuDO,IAAM,2BAA2B;AAsDxC,eAAsB,kBACpB,SACA,OACA,WACA,OACA,QACe;AACf,QAAM,KAAK,aAAa;AACxB,QAAM,OAA0B;AAAA,IAC9B;AAAA,IACA,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,IAClC,GAAG;AAAA,EACL;AACA,QAAM,WAAW,MAAM,cAAc,MAAM,WAAW,MAAM;AAC5D,QAAM,QAAQ,IAAI,OAAO,0BAA0B,IAAI,QAAQ;AACjE;AAGA,eAAsB,mBACpB,SACA,OACA,WACA,QACA,SAA6B,CAAC,GACA;AAC9B,QAAM,MAAM,MAAM,QAAQ,KAAK,OAAO,wBAAwB;AAC9D,QAAM,UAA+B,CAAC;AAEtC,aAAW,MAAM,IAAI,KAAK,GAAG;AAC3B,UAAM,WAAW,MAAM,QAAQ,IAAI,OAAO,0BAA0B,EAAE;AACtE,QAAI,CAAC,SAAU;AACf,UAAM,QAAQ,MAAM,aAAa,UAAU,WAAW,MAAM;AAC5D,QAAI,CAAC,cAAc,OAAO,MAAM,EAAG;AACnC,YAAQ,KAAK,KAAK;AAAA,EACpB;AACA,SAAO;AACT;AAIA,eAAe,cACb,OACA,WACA,QAC4B;AAC5B,QAAM,OAAO,KAAK,UAAU,KAAK;AACjC,MAAI,CAAC,WAAW;AACd,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,IAAI;AAAA,MACJ,KAAK,MAAM;AAAA,MACX,KAAK;AAAA,MACL,OAAO;AAAA,IACT;AAAA,EACF;AACA,QAAM,MAAM,MAAM,OAAO,wBAAwB;AACjD,QAAM,EAAE,IAAI,KAAK,IAAI,MAAM,QAAQ,MAAM,GAAG;AAC5C,SAAO;AAAA,IACL,QAAQ;AAAA,IACR,IAAI;AAAA,IACJ,KAAK,MAAM;AAAA,IACX,KAAK;AAAA,IACL,OAAO;AAAA,EACT;AACF;AAEA,eAAe,aACb,UACA,WACA,QAC4B;AAC5B,MAAI,CAAC,UAAW,QAAO,KAAK,MAAM,SAAS,KAAK;AAChD,QAAM,OAAO,MAAM,iBAAiB,UAAU,MAAM,OAAO,wBAAwB,CAAC;AACpF,SAAO,KAAK,MAAM,IAAI;AACxB;AAEA,SAAS,cAAc,OAA0B,GAAgC;AAC/E,MAAI,EAAE,SAAS,MAAM,YAAY,EAAE,MAAO,QAAO;AACjD,MAAI,EAAE,SAAS,MAAM,YAAY,EAAE,MAAO,QAAO;AACjD,MAAI,EAAE,cAAc,MAAM,eAAe,EAAE,WAAY,QAAO;AAC9D,MAAI,EAAE,SAAS,MAAM,UAAU,EAAE,MAAO,QAAO;AAC/C,MAAI,EAAE,WAAW,MAAM,YAAY,EAAE,QAAS,QAAO;AACrD,SAAO;AACT;","names":[]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
2
|
ReadOnlyFrameError
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-ZYUC53LT.js";
|
|
4
4
|
|
|
5
|
-
// src/shadow/vault-frame.ts
|
|
5
|
+
// src/with-fork/shadow/vault-frame.ts
|
|
6
6
|
var VaultFrame = class {
|
|
7
7
|
constructor(vault) {
|
|
8
8
|
this.vault = vault;
|
|
@@ -36,13 +36,8 @@ var CollectionFrame = class {
|
|
|
36
36
|
list(locale) {
|
|
37
37
|
return this.inner.list(locale);
|
|
38
38
|
}
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
* `.first()`, `.count()`, `.aggregate()` all work; the builder has
|
|
42
|
-
* no write surface of its own, so exposing it directly is safe.
|
|
43
|
-
*/
|
|
44
|
-
query(...args) {
|
|
45
|
-
return this.inner.query(...args);
|
|
39
|
+
query(predicate) {
|
|
40
|
+
return predicate !== void 0 ? this.inner.query(predicate) : this.inner.query();
|
|
46
41
|
}
|
|
47
42
|
/** History reads — allowed (history is read-only by nature). */
|
|
48
43
|
history(...args) {
|
|
@@ -76,4 +71,4 @@ export {
|
|
|
76
71
|
VaultFrame,
|
|
77
72
|
CollectionFrame
|
|
78
73
|
};
|
|
79
|
-
//# sourceMappingURL=chunk-
|
|
74
|
+
//# sourceMappingURL=chunk-NF5JWERG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/with-fork/shadow/vault-frame.ts"],"sourcesContent":["/**\n * Shadow vaults — `vault.frame()` returns a read-only view of the\n * CURRENT vault state.\n *\n * Companion to {@link VaultInstant} from `history/time-machine.ts`:\n *\n * | Type | Reads from | Use case |\n * |------|------------|----------|\n * | `VaultInstant` | past snapshots (ledger + history) | \"books on date X\" |\n * | `VaultFrame` | live vault state | screen-share / demo / audit |\n *\n * ```ts\n * const readonly = vault.frame()\n * const invoices = await readonly.collection<Invoice>('invoices').list()\n * await readonly.collection<Invoice>('invoices').put(...)\n * // → throws ReadOnlyFrameError\n * ```\n *\n * ## Contract\n *\n * Every write method on {@link CollectionFrame} throws\n * {@link ReadOnlyFrameError}. Reads delegate to the underlying\n * collection, so validation, locale handling, and caching all work\n * exactly as they do on the live collection.\n *\n * ## Security note: behaviour-enforced, not cryptographically-enforced\n *\n * A VaultFrame rejects writes by contract in the JavaScript layer.\n * It does NOT strip the DEKs from the underlying keyring — the same\n * in-memory keys that decrypt records could, in principle, encrypt\n * new writes via a hand-crafted adapter call. Cryptographic\n * enforcement (keyring variants with the write half of each DEK\n * removed) is hierarchical-access work. Use a VaultFrame to\n * prevent *accidental* writes in a read-scoped flow — do not rely on\n * it as a security boundary against a hostile caller sharing the\n * same process.\n *\n * @module\n */\nimport type { Collection } from '../../kernel/collection.js'\nimport type { Query } from '../../kernel/query/builder.js'\nimport type { Vault } from '../../kernel/vault.js'\nimport type { LocaleReadOptions } from '../../kernel/types.js'\nimport { ReadOnlyFrameError } from '../../kernel/errors.js'\n\n/**\n * A read-only view of a vault's current state. Produced by\n * `vault.frame()`. Cheap to construct; safe to throw away.\n */\nexport class VaultFrame {\n constructor(private readonly vault: Vault) {}\n\n /**\n * Get a read-only view of one collection. The returned\n * {@link CollectionFrame} delegates all reads to the underlying\n * live collection — cache, locale handling, and validation all\n * work identically to the live collection.\n */\n collection<T = unknown>(name: string): CollectionFrame<T> {\n return new CollectionFrame<T>(this.vault.collection<T>(name), name)\n }\n\n /** List all collection names visible in the underlying vault. */\n async collections(): Promise<string[]> {\n return this.vault.collections()\n }\n}\n\n/**\n * Read-only collection view. All write methods throw\n * {@link ReadOnlyFrameError}; all read methods delegate to the\n * underlying live {@link Collection}.\n */\nexport class CollectionFrame<T = unknown> {\n constructor(\n private readonly inner: Collection<T>,\n /** The underlying collection name. Captured at construction so\n * we don't need to peek into the private Collection state. */\n public readonly name: string,\n ) {}\n\n // ── reads (delegated) ──────────────────────────────────────────────\n\n get(id: string, locale?: LocaleReadOptions): Promise<T | null> {\n return this.inner.get(id, locale)\n }\n\n list(locale?: LocaleReadOptions): Promise<T[]> {\n return this.inner.list(locale)\n }\n\n /**\n * Return the chainable query builder. Terminals like `.toArray()`,\n * `.first()`, `.count()`, `.aggregate()` all work; the builder has\n * no write surface of its own, so exposing it directly is safe.\n */\n query(): Query<T>\n query(predicate: (record: T) => boolean): T[]\n query(predicate?: (record: T) => boolean): Query<T> | T[] {\n // Explicit overloads mirror Collection.query's two signatures. A\n // `Parameters<>`/`ReturnType<>` forward collapses to the *last* overload\n // only (`(predicate) => T[]`), losing the no-arg `() => Query<T>` form.\n return predicate !== undefined ? this.inner.query(predicate) : this.inner.query()\n }\n\n /** History reads — allowed (history is read-only by nature). */\n history(...args: Parameters<Collection<T>['history']>): ReturnType<Collection<T>['history']> {\n return this.inner.history(...args)\n }\n\n getVersion(id: string, version: number): Promise<T | null> {\n return this.inner.getVersion(id, version)\n }\n\n // ── write guards ──────────────────────────────────────────────────\n\n async put(_id: string, _record: T): Promise<never> {\n throw new ReadOnlyFrameError('put')\n }\n async delete(_id: string): Promise<never> {\n throw new ReadOnlyFrameError('delete')\n }\n async update(_id: string, _patch: Partial<T>): Promise<never> {\n throw new ReadOnlyFrameError('update')\n }\n async revert(_id: string, _version: number): Promise<never> {\n throw new ReadOnlyFrameError('revert')\n }\n async putMany(_entries: ReadonlyArray<readonly [string, T]>): Promise<never> {\n throw new ReadOnlyFrameError('putMany')\n }\n async deleteMany(_ids: readonly string[]): Promise<never> {\n throw new ReadOnlyFrameError('deleteMany')\n }\n}\n"],"mappings":";;;;;AAiDO,IAAM,aAAN,MAAiB;AAAA,EACtB,YAA6B,OAAc;AAAd;AAAA,EAAe;AAAA,EAAf;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQ7B,WAAwB,MAAkC;AACxD,WAAO,IAAI,gBAAmB,KAAK,MAAM,WAAc,IAAI,GAAG,IAAI;AAAA,EACpE;AAAA;AAAA,EAGA,MAAM,cAAiC;AACrC,WAAO,KAAK,MAAM,YAAY;AAAA,EAChC;AACF;AAOO,IAAM,kBAAN,MAAmC;AAAA,EACxC,YACmB,OAGD,MAChB;AAJiB;AAGD;AAAA,EACf;AAAA,EAJgB;AAAA,EAGD;AAAA;AAAA,EAKlB,IAAI,IAAY,QAA+C;AAC7D,WAAO,KAAK,MAAM,IAAI,IAAI,MAAM;AAAA,EAClC;AAAA,EAEA,KAAK,QAA0C;AAC7C,WAAO,KAAK,MAAM,KAAK,MAAM;AAAA,EAC/B;AAAA,EASA,MAAM,WAAoD;AAIxD,WAAO,cAAc,SAAY,KAAK,MAAM,MAAM,SAAS,IAAI,KAAK,MAAM,MAAM;AAAA,EAClF;AAAA;AAAA,EAGA,WAAW,MAAkF;AAC3F,WAAO,KAAK,MAAM,QAAQ,GAAG,IAAI;AAAA,EACnC;AAAA,EAEA,WAAW,IAAY,SAAoC;AACzD,WAAO,KAAK,MAAM,WAAW,IAAI,OAAO;AAAA,EAC1C;AAAA;AAAA,EAIA,MAAM,IAAI,KAAa,SAA4B;AACjD,UAAM,IAAI,mBAAmB,KAAK;AAAA,EACpC;AAAA,EACA,MAAM,OAAO,KAA6B;AACxC,UAAM,IAAI,mBAAmB,QAAQ;AAAA,EACvC;AAAA,EACA,MAAM,OAAO,KAAa,QAAoC;AAC5D,UAAM,IAAI,mBAAmB,QAAQ;AAAA,EACvC;AAAA,EACA,MAAM,OAAO,KAAa,UAAkC;AAC1D,UAAM,IAAI,mBAAmB,QAAQ;AAAA,EACvC;AAAA,EACA,MAAM,QAAQ,UAA+D;AAC3E,UAAM,IAAI,mBAAmB,SAAS;AAAA,EACxC;AAAA,EACA,MAAM,WAAW,MAAyC;AACxD,UAAM,IAAI,mBAAmB,YAAY;AAAA,EAC3C;AACF;","names":[]}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
DerivationCapExceededError,
|
|
3
3
|
DerivationOutputShapeError
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-ZYUC53LT.js";
|
|
5
5
|
|
|
6
|
-
// src/derivations/executor.ts
|
|
6
|
+
// src/with-formula/derivations/executor.ts
|
|
7
7
|
var DerivationExecutor = {
|
|
8
8
|
/**
|
|
9
9
|
* Run `derive` once, validate output shape against the spec, stamp
|
|
@@ -121,4 +121,4 @@ var DerivationExecutor = {
|
|
|
121
121
|
export {
|
|
122
122
|
DerivationExecutor
|
|
123
123
|
};
|
|
124
|
-
//# sourceMappingURL=chunk-
|
|
124
|
+
//# sourceMappingURL=chunk-PKHL44ER.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/derivations/executor.ts"],"sourcesContent":["import { DerivationCapExceededError, DerivationOutputShapeError } from '
|
|
1
|
+
{"version":3,"sources":["../src/with-formula/derivations/executor.ts"],"sourcesContent":["import { DerivationCapExceededError, DerivationOutputShapeError } from '../../kernel/errors.js'\nimport type { DerivationContext, DerivationStrategy, DerivedFromMeta } from './types.js'\n\nexport interface RunResult {\n outputs: Record<string, OutputResult>\n failed: boolean\n}\n\n/**\n * Per-output result of a strategy invocation. Discriminated by\n * `kind`:\n *\n * - `record` — the existing v1 shape: one value (or a \"skipped\"\n * marker if the output was optional and `derive` returned null).\n * - `array` — a list of `(key, value)` entries.\n * The caller diffs these against the previously-emitted key set\n * (loaded from the fanout sidecar) to compute deletes + upserts.\n */\nexport type OutputResult =\n | RecordOutputResult\n | ArrayOutputResult\n | FailedOutputResult\n\nexport interface RecordOutputResult {\n kind: 'record'\n value: Record<string, unknown>\n ok: true\n /**\n * `true` when an optional output returned `null` /\n * `undefined`. The caller deletes any previously-emitted output at\n * the same id (mirrors \"tombstone for derived data\"); a never-emitted\n * output is a silent no-op. `ok: true` because skipping is a\n * successful outcome, not a failure.\n */\n skipped?: boolean\n}\n\nexport interface ArrayOutputResult {\n kind: 'array'\n ok: true\n /** One `(key, value)` per derived row. Empty array means \"all prior outputs for this source go.\" */\n entries: ReadonlyArray<{ readonly key: string; readonly value: Record<string, unknown> }>\n}\n\nexport interface FailedOutputResult {\n kind: 'failed'\n ok: false\n error: Error\n /** Always empty on failure; present so consumers don't have to narrow. */\n value: Record<string, unknown>\n}\n\n/**\n * Stateless functions that execute a derivation strategy. Persistence\n * (encrypt + store.put) is the caller's job — typically\n * `DerivationRegistry.onSourceWrite` which iterates run() results and\n * writes each output via `Collection.put`.\n */\nexport const DerivationExecutor = {\n /**\n * Run `derive` once, validate output shape against the spec, stamp\n * `_derivedFrom` onto every output. Returns per-output success or\n * failure; throws only for shape mismatches (a contract violation).\n */\n async run<\n TSource extends Record<string, unknown>,\n TOutputs extends Record<string, Record<string, unknown> | ReadonlyArray<Record<string, unknown>>>,\n >(\n strategy: DerivationStrategy<TSource, TOutputs>,\n source: TSource & { id: string },\n sourceVersion: number,\n strategyHash: string,\n ctx: DerivationContext,\n ): Promise<RunResult> {\n const outputs: Record<string, OutputResult> = {}\n let derived: Partial<TOutputs>\n\n try {\n derived = await Promise.resolve(strategy.derive(source as TSource, ctx))\n } catch (err) {\n for (const key of Object.keys(strategy.outputs)) {\n outputs[key] = {\n kind: 'failed',\n value: {},\n ok: false,\n error: err instanceof Error ? err : new Error(String(err)),\n }\n }\n return { outputs, failed: true }\n }\n\n const meta: DerivedFromMeta = {\n source: strategy.source,\n sourceId: source.id,\n sourceVersion,\n derivedAt: new Date().toISOString(),\n strategyHash,\n }\n\n for (const key of Object.keys(strategy.outputs)) {\n const outSpec = strategy.outputs[key]\n if (!outSpec) continue\n const value = (derived as Record<string, unknown>)[key]\n\n // ── Array-shape branch ─────────────────────────────────────\n if (outSpec.shape === 'array') {\n if (value === undefined || value === null) {\n // Treat null/undefined as \"empty array\" — clears all prior\n // outputs for this (source, output) pair. The caller's\n // diff turns that into deletes.\n outputs[key] = { kind: 'array', ok: true, entries: [] }\n continue\n }\n if (!Array.isArray(value)) {\n throw new DerivationOutputShapeError(\n key,\n `shape 'array' expects an array, got ${typeof value}`,\n )\n }\n const maxFanout = outSpec.maxFanout ?? 64\n if (value.length > maxFanout) {\n throw new DerivationCapExceededError(key, value.length, maxFanout)\n }\n const entries: Array<{ key: string; value: Record<string, unknown> }> = []\n const seenKeys = new Set<string>()\n for (let i = 0; i < value.length; i++) {\n const row = value[i] as unknown\n if (row === null || typeof row !== 'object') {\n throw new DerivationOutputShapeError(\n key,\n `array member at index ${i} must be a non-null object (got ${row === null ? 'null' : typeof row})`,\n )\n }\n let derivedKey: string\n try {\n derivedKey = outSpec.key(row as Record<string, unknown>)\n } catch (err) {\n throw new DerivationOutputShapeError(\n key,\n `key extractor threw on array member at index ${i}: `\n + (err instanceof Error ? err.message : String(err)),\n )\n }\n if (typeof derivedKey !== 'string' || derivedKey.length === 0) {\n throw new DerivationOutputShapeError(\n key,\n `key extractor returned ${typeof derivedKey === 'string' ? 'empty string' : typeof derivedKey} at index ${i}; expected non-empty string`,\n )\n }\n if (seenKeys.has(derivedKey)) {\n throw new DerivationOutputShapeError(\n key,\n `duplicate key \"${derivedKey}\" in array output (index ${i}); each derived row must have a unique key within a single derive() invocation`,\n )\n }\n seenKeys.add(derivedKey)\n entries.push({\n key: derivedKey,\n value: { ...(row as Record<string, unknown>), _derivedFrom: meta },\n })\n }\n outputs[key] = { kind: 'array', ok: true, entries }\n continue\n }\n\n // ── Record-shape branch (existing v1 behavior) ─────────────\n if (value === undefined || value === null) {\n if (outSpec.optional === true) {\n // Optional output explicitly skipped. Mark for caller\n // so any prior-emitted output at this id can be deleted.\n outputs[key] = { kind: 'record', value: {}, ok: true, skipped: true }\n continue\n }\n throw new DerivationOutputShapeError(\n key,\n `expected object, got ${value === undefined ? 'undefined' : 'null'}`,\n )\n }\n if (typeof value !== 'object') {\n throw new DerivationOutputShapeError(\n key,\n `expected object, got ${typeof value}`,\n )\n }\n outputs[key] = {\n kind: 'record',\n value: { ...(value as Record<string, unknown>), _derivedFrom: meta },\n ok: true,\n }\n }\n return { outputs, failed: false }\n },\n}\n"],"mappings":";;;;;;AA0DO,IAAM,qBAAqB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMhC,MAAM,IAIJ,UACA,QACA,eACA,cACA,KACoB;AACpB,UAAM,UAAwC,CAAC;AAC/C,QAAI;AAEJ,QAAI;AACF,gBAAU,MAAM,QAAQ,QAAQ,SAAS,OAAO,QAAmB,GAAG,CAAC;AAAA,IACzE,SAAS,KAAK;AACZ,iBAAW,OAAO,OAAO,KAAK,SAAS,OAAO,GAAG;AAC/C,gBAAQ,GAAG,IAAI;AAAA,UACb,MAAM;AAAA,UACN,OAAO,CAAC;AAAA,UACR,IAAI;AAAA,UACJ,OAAO,eAAe,QAAQ,M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leBundle,
|
|
3
|
+
resolveAccessibleCollections
|
|
4
|
+
} from "./chunk-HCIPRAGS.js";
|
|
5
|
+
import {
|
|
6
|
+
sha256Hex
|
|
7
|
+
} from "./chunk-5O3AOPDT.js";
|
|
8
|
+
import {
|
|
9
|
+
NOYDB_FORMAT_VERSION
|
|
10
|
+
} from "./chunk-5TDJ56JE.js";
|
|
11
|
+
import {
|
|
12
|
+
ReadOnlyError
|
|
13
|
+
} from "./chunk-ZYUC53LT.js";
|
|
14
|
+
|
|
15
|
+
// src/with-audit/portability/withdraw-accessible.ts
|
|
16
|
+
var FROZEN_SNAPSHOTS_COLLECTION = "_frozen_snapshots";
|
|
17
|
+
var ENC = new TextEncoder();
|
|
18
|
+
function randomId() {
|
|
19
|
+
const b = globalThis.crypto.getRandomValues(new Uint8Array(12));
|
|
20
|
+
return Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
|
|
21
|
+
}
|
|
22
|
+
async function freezeSnapshotOnly(vault, collections, opts) {
|
|
23
|
+
const { name: vaultName, adapter } = vault._introspectState();
|
|
24
|
+
const closure = [];
|
|
25
|
+
for (const c of collections) {
|
|
26
|
+
for (const id of await adapter.list(vaultName, c)) closure.push({ collection: c, id });
|
|
27
|
+
}
|
|
28
|
+
const withdrawalId = opts.withdrawalId ?? `wd-${randomId()}`;
|
|
29
|
+
const snap = {};
|
|
30
|
+
for (const { collection, id } of closure) {
|
|
31
|
+
const env = await adapter.get(vaultName, collection, id);
|
|
32
|
+
if (env) (snap[collection] ??= {})[id] = env;
|
|
33
|
+
}
|
|
34
|
+
const frozenAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
35
|
+
const body = JSON.stringify({ withdrawalId, frozenAt, by: opts.actorUserId, collections: snap });
|
|
36
|
+
const sha = await sha256Hex(ENC.encode(body));
|
|
37
|
+
await adapter.put(
|
|
38
|
+
vaultName,
|
|
39
|
+
FROZEN_SNAPSHOTS_COLLECTION,
|
|
40
|
+
withdrawalId,
|
|
41
|
+
{ _noydb: NOYDB_FORMAT_VERSION, _v: 1, _ts: frozenAt, _iv: "", _data: body, _by: opts.actorUserId },
|
|
42
|
+
0
|
|
43
|
+
);
|
|
44
|
+
await vault._getLedgerOrNull()?.append({
|
|
45
|
+
op: "lifecycle",
|
|
46
|
+
collection: "",
|
|
47
|
+
id: "",
|
|
48
|
+
version: 0,
|
|
49
|
+
actor: opts.actorUserId,
|
|
50
|
+
payloadHash: "",
|
|
51
|
+
reason: `withdrawal-frozen-snapshot:${withdrawalId}:${sha}`
|
|
52
|
+
});
|
|
53
|
+
return { withdrawalId, sha256: sha, recordCount: closure.length, frozenAt };
|
|
54
|
+
}
|
|
55
|
+
async function freezeAndDeleteClosure(vault, collections, opts) {
|
|
56
|
+
const snapshot = opts.disposition === "freeze" ? await freezeSnapshotOnly(vault, collections, {
|
|
57
|
+
actorUserId: opts.actorUserId,
|
|
58
|
+
...opts.withdrawalId ? { withdrawalId: opts.withdrawalId } : {}
|
|
59
|
+
}) : void 0;
|
|
60
|
+
const { name: vaultName, adapter } = vault._introspectState();
|
|
61
|
+
for (const c of collections) {
|
|
62
|
+
for (const id of await adapter.list(vaultName, c)) {
|
|
63
|
+
await vault.collection(c).delete(id);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return snapshot;
|
|
67
|
+
}
|
|
68
|
+
async function withdrawAccessibleData(vault, opts) {
|
|
69
|
+
const { keyring } = vault._introspectState();
|
|
70
|
+
const disposition = opts.disposition ?? "delete";
|
|
71
|
+
if (keyring.role === "owner" || keyring.role === "admin") {
|
|
72
|
+
throw new ReadOnlyError(
|
|
73
|
+
"unilateralWithdrawal is the scoped self-service path; an owner/admin should use extractPartition"
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
if (keyring.role === "custodian") {
|
|
77
|
+
throw new ReadOnlyError(
|
|
78
|
+
"a custodian cannot destructively withdraw/sever; use vault.custody.liberate for an audited ownership claim"
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
if (keyring.role === "client" || keyring.role === "viewer") {
|
|
82
|
+
throw new ReadOnlyError(
|
|
83
|
+
"read-only role cannot self-serve a destructive withdrawal \u2014 use requestWithdrawal (two-party)"
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
const collections = resolveAccessibleCollections(keyring, opts.scope, true);
|
|
87
|
+
if (!collections || collections.length === 0) {
|
|
88
|
+
throw new ReadOnlyError(
|
|
89
|
+
"unilateralWithdrawal requires rw access on the withdrawn collections \u2014 use requestWithdrawal for read-only scope"
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
const bundle = await buildAccessibleBundle(vault, collections, opts.reKey);
|
|
93
|
+
const snapshot = await freezeAndDeleteClosure(vault, collections, {
|
|
94
|
+
disposition,
|
|
95
|
+
actorUserId: keyring.userId,
|
|
96
|
+
...opts.withdrawalId ? { withdrawalId: opts.withdrawalId } : {}
|
|
97
|
+
});
|
|
98
|
+
await vault._getLedgerOrNull()?.append({
|
|
99
|
+
op: "lifecycle",
|
|
100
|
+
collection: "",
|
|
101
|
+
id: "",
|
|
102
|
+
version: 0,
|
|
103
|
+
actor: keyring.userId,
|
|
104
|
+
payloadHash: "",
|
|
105
|
+
reason: `user-unilateral-withdrawal:${keyring.userId}:${disposition}:${opts.legalBasis}`
|
|
106
|
+
});
|
|
107
|
+
return snapshot ? { bundle, snapshot } : { bundle };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export {
|
|
111
|
+
FROZEN_SNAPSHOTS_COLLECTION,
|
|
112
|
+
randomId,
|
|
113
|
+
freezeSnapshotOnly,
|
|
114
|
+
freezeAndDeleteClosure,
|
|
115
|
+
withdrawAccessibleData
|
|
116
|
+
};
|
|
117
|
+
//# sourceMappingURL=chunk-PSMV73A5.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/with-audit/portability/withdraw-accessible.ts"],"sourcesContent":["/**\n * `unilateralWithdrawal`: a non-owner extracts their accessible scope\n * AND disposes of the source copy. Destructive; gated by the default-off\n * fail-closed built-in `client-unilateral-withdraw` policy (checked in the\n * UserApi wrapper).\n *\n * Two source dispositions:\n * - 'delete' — delete-closure: the records leave the source vault entirely.\n * - 'freeze' — the firm retains a cryptographically-frozen, read-only, write-once\n * snapshot (hash-pinned in the tamper-evident ledger) while the live\n * records are removed.\n *\n * Ordering guarantees no data loss: the client's re-keyed export bundle (and the\n * freeze snapshot) are produced BEFORE anything is deleted.\n *\n * The `freezeAndDeleteClosure` core is shared with the two-party approval path\n * (`request-withdrawal.ts`).\n */\nimport type { Vault } from '../../kernel/vault.js'\nimport { sha256Hex } from '../../kernel/enclave/index.js'\nimport { ReadOnlyError } from '../../kernel/errors.js'\nimport { NOYDB_FORMAT_VERSION } from '../../kernel/types.js'\nimport { resolveAccessibleCollections, buildAccessibleBundle } from './export-accessible.js'\n\nexport const FROZEN_SNAPSHOTS_COLLECTION = '_frozen_snapshots'\nconst ENC = new TextEncoder()\n\n/** 24-hex-char random id (used for withdrawal ids + request ids). */\nexport function randomId(): string {\n const b = globalThis.crypto.getRandomValues(new Uint8Array(12))\n return Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('')\n}\n\nexport interface FrozenSnapshotRef {\n readonly withdrawalId: string\n readonly sha256: string\n readonly recordCount: number\n readonly frozenAt: string\n}\n\nexport interface WithdrawAccessibleOptions {\n /** Legal/contractual basis recorded in the audit (e.g. 'gdpr-art-17'). */\n readonly legalBasis: string\n /** Re-key the exported bundle to a new owner passphrase. */\n readonly reKey?: { readonly passphrase: string }\n /** Source disposition. Default 'delete'. */\n readonly disposition?: 'delete' | 'freeze'\n readonly scope?: { readonly collections?: readonly string[] }\n /** Stable id for idempotent resume (default random). */\n readonly withdrawalId?: string\n}\n\nexport interface WithdrawResult {\n readonly bundle: Uint8Array\n readonly snapshot?: FrozenSnapshotRef\n}\n\n/**\n * Freeze a write-once, hash-pinned snapshot of the current ciphertext for\n * `collections` WITHOUT touching the live records. Returns the snapshot ref.\n *\n * This is the non-destructive core shared by two callers:\n * - `freezeAndDeleteClosure` (withdrawal, disposition `'freeze'`) — which\n * pins the snapshot and THEN delete-closures the live records.\n * - FR-6 `liberateVault` (custody) — which pins a PRE-liberation evidence\n * snapshot but PRESERVES the live data for the new owner (operational\n * continuity; liberation transfers, it does not erase).\n *\n * The snapshot put is write-once (CAS expectedVersion 0) and the ledger pin is\n * appended on success, so a crashed run re-run with the same `withdrawalId` is\n * safe. The snapshot is taken under the vault's own firm-owned DEKs — no re-key.\n */\nexport async function freezeSnapshotOnly(\n vault: Vault,\n collections: readonly string[],\n opts: { actorUserId: string; withdrawalId?: string },\n): Promise<FrozenSnapshotRef> {\n const { name: vaultName, adapter } = vault._introspectState()\n\n // Enumerate the closure (record ids per collection).\n const closure: Array<{ collection: string; id: string }> = []\n for (const c of collections) {\n for (const id of await adapter.list(vaultName, c)) closure.push({ collection: c, id })\n }\n\n const withdrawalId = opts.withdrawalId ?? `wd-${randomId()}`\n const snap: Record<string, Record<string, unknown>> = {}\n for (const { collection, id } of closure) {\n const env = await adapter.get(vaultName, collection, id)\n if (env) (snap[collection] ??= {})[id] = env\n }\n const frozenAt = new Date().toISOString()\n const body = JSON.stringify({ withdrawalId, frozenAt, by: opts.actorUserId, collections: snap })\n const sha = await sha256Hex(ENC.encode(body))\n // Write-once: expectedVersion 0 rejects an overwrite (idempotent resume).\n await adapter.put(\n vaultName,\n FROZEN_SNAPSHOTS_COLLECTION,\n withdrawalId,\n { _noydb: NOYDB_FORMAT_VERSION, _v: 1, _ts: frozenAt, _iv: '', _data: body, _by: opts.actorUserId },\n 0,\n )\n // Hash-pin into the tamper-evident ledger — makes the snapshot provably unaltered.\n await vault._getLedgerOrNull()?.append({\n op: 'lifecycle', collection: '', id: '', version: 0, actor: opts.actorUserId, payloadHash: '',\n reason: `withdrawal-frozen-snapshot:${withdrawalId}:${sha}`,\n })\n return { withdrawalId, sha256: sha, recordCount: closure.length, frozenAt }\n}\n\n/**\n * Dispose of the source records for `collections`: optionally freeze a\n * write-once hash-pinned snapshot of the original ciphertext, then\n * delete-closure the live records. Returns the snapshot ref on freeze.\n *\n * Caller MUST have produced the portable bundle FIRST — this is destructive.\n * The delete is best-effort + idempotent (re-deleting an absent record is a\n * no-op) and the snapshot put is write-once (CAS expectedVersion 0), so a\n * crashed run re-run with the same `withdrawalId` is safe.\n */\nexport async function freezeAndDeleteClosure(\n vault: Vault,\n collections: readonly string[],\n opts: { disposition: 'delete' | 'freeze'; actorUserId: string; withdrawalId?: string },\n): Promise<FrozenSnapshotRef | undefined> {\n // freeze: pin a write-once, hash-pinned snapshot BEFORE any delete. The\n // snapshot-only core is shared with FR-6 liberation (which never deletes).\n const snapshot = opts.disposition === 'freeze'\n ? await freezeSnapshotOnly(vault, collections, {\n actorUserId: opts.actorUserId,\n ...(opts.withdrawalId ? { withdrawalId: opts.withdrawalId } : {}),\n })\n : undefined\n\n // delete-closure — only after the snapshot is durable.\n const { name: vaultName, adapter } = vault._introspectState()\n for (const c of collections) {\n for (const id of await adapter.list(vaultName, c)) {\n await vault.collection(c).delete(id)\n }\n }\n\n return snapshot\n}\n\nexport async function withdrawAccessibleData(\n vault: Vault,\n opts: WithdrawAccessibleOptions,\n): Promise<WithdrawResult> {\n const { keyring } = vault._introspectState()\n const disposition = opts.disposition ?? 'delete'\n\n // Owner-class roles hold blanket authority — they use extractPartition.\n if (keyring.role === 'owner' || keyring.role === 'admin') {\n throw new ReadOnlyError(\n 'unilateralWithdrawal is the scoped self-service path; an owner/admin should use extractPartition',\n )\n }\n // FR-6: a custodian must NOT destructively SEVER the vault. It holds the DEKs\n // and operates fully, but ownership is claimed only through the audited\n // Liberate ceremony — never by a one-sided delete/freeze withdrawal. Fires\n // BEFORE the operator rw-scope path below (where a custodian would otherwise\n // be rejected with the wrong \"requires rw access\" message).\n if (keyring.role === 'custodian') {\n throw new ReadOnlyError(\n 'a custodian cannot destructively withdraw/sever; use vault.custody.liberate for an audited ownership claim',\n )\n }\n // client/viewer are read-only by construction (see hasWritePermission): a\n // destructive withdrawal they cannot self-serve — they use the two-party\n // requestWithdrawal flow where firm authority executes the delete-closure.\n if (keyring.role === 'client' || keyring.role === 'viewer') {\n throw new ReadOnlyError(\n 'read-only role cannot self-serve a destructive withdrawal — use requestWithdrawal (two-party)',\n )\n }\n // Operator path: destructive ops need rw on the whole scope.\n const collections = resolveAccessibleCollections(keyring, opts.scope, true)\n if (!collections || collections.length === 0) {\n throw new ReadOnlyError(\n 'unilateralWithdrawal requires rw access on the withdrawn collections — use requestWithdrawal for read-only scope',\n )\n }\n\n // 1. Produce the client's re-keyed portable copy FIRST (nothing destroyed yet).\n const bundle = await buildAccessibleBundle(vault, collections, opts.reKey)\n\n // 2. + 3. freeze (optional) then delete-closure.\n const snapshot = await freezeAndDeleteClosure(vault, collections, {\n disposition, actorUserId: keyring.userId, ...(opts.withdrawalId ? { withdrawalId: opts.withdrawalId } : {}),\n })\n\n // 4. audit\n await vault._getLedgerOrNull()?.append({\n op: 'lifecycle', collection: '', id: '', version: 0, actor: keyring.userId, payloadHash: '',\n reason: `user-unilateral-withdrawal:${keyring.userId}:${disposition}:${opts.legalBasis}`,\n })\n\n return snapshot ? { bundle, snapshot } : { bundle }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAwBO,IAAM,8BAA8B;AAC3C,IAAM,MAAM,IAAI,YAAY;AAGrB,SAAS,WAAmB;AACjC,QAAM,IAAI,WAAW,OAAO,gBAAgB,IAAI,WAAW,EAAE,CAAC;AAC9D,SAAO,MAAM,KAAK,GAAG,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAAE,KAAK,EAAE;AACtE;AAyCA,eAAsB,mBACpB,OACA,aACA,MAC4B;AAC5B,QAAM,EAAE,MAAM,WAAW,QAAQ,IAAI,MAAM,iBAAiB;AAG5D,QAAM,UAAqD,CAAC;AAC5D,aAAW,KAAK,aAAa;AAC3B,eAAW,MAAM,MAAM,QAAQ,KAAK,WAAW,CAAC,EAAG,SAAQ,KAAK,EAAE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|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/kernel/util/discriminant.ts"],"sourcesContent":["/**\n * Type-guard helper for narrowing discriminated-union records.\n *\n * `Collection<T>` correctly threads `T` through `get` / `query` / `scan`, but\n * accessing member-specific fields after reading from a `Collection<Union>`\n * still requires a narrowing step in application code. In regular `.ts` files\n * a simple `if (r.kind === 'IV')` block narrows correctly; in vue-tsc /\n * template contexts the inline comparison is sometimes not enough, and the\n * helper below makes the guard portable and avoids `as unknown as …` casts.\n *\n * **Usage with Collection<T>**\n *\n * ```ts\n * import { isDiscriminant } from '@noy-db/hub'\n *\n * type IV = { kind: 'IV'; invoiceNo: string; amount: number }\n * type RE = { kind: 'RE'; receiptNo: string; paidAt: string }\n * type Receipt = IV | RE | ...\n *\n * const receipts = await vault.collection<Receipt>('receipts').query().toArray()\n *\n * // Filter approach — result is IV[], invoiceNo accessible without cast:\n * const ivs = receipts.filter(r => isDiscriminant(r, 'kind', 'IV'))\n * console.log(ivs[0].invoiceNo)\n *\n * // Branch approach:\n * for (const r of receipts) {\n * if (isDiscriminant(r, 'kind', 'IV')) {\n * console.log(r.invoiceNo) // r: IV here\n * }\n * }\n * ```\n *\n * @module\n */\n\n/**\n * Type-guard for narrowing a discriminated-union record by its discriminant.\n *\n * Returns `true` when `record[key] === value`, and narrows `record` to\n * `Extract<T, Record<K, V>>` — the exact union member(s) that carry that\n * discriminant value.\n *\n * The discriminant key is a parameter (not hardcoded to `'kind'`), so this\n * works with any field name: `'kind'`, `'type'`, `'tag'`, etc.\n *\n * @example\n * const ivs = receipts.filter(r => isDiscriminant(r, 'kind', 'IV'))\n * // ivs: IV[] — invoiceNo accessible, no cast needed\n *\n * @typeParam T - The union type of the record (e.g. `Receipt`). Both type-alias\n * unions and interface-extended unions work; use a `type` alias (`type Receipt = IV | RE`) for best\n * results.\n * @typeParam K - The discriminant key (must be a key of `T`).\n * @typeParam V - The discriminant value to match. The `const` modifier ensures\n * TypeScript infers the string literal (e.g. `'IV'`), not the full union\n * `T[K]`, so the predicate resolves to the exact member type.\n */\nexport function isDiscriminant<\n T,\n K extends keyof T,\n const V extends T[K],\n>(record: T, key: K, value: V): record is Extract<T, Record<K, V>> {\n return (record as Record<PropertyKey, unknown>)[key as PropertyKey] === value\n}\n"],"mappings":";AA0DO,SAAS,eAId,QAAW,KAAQ,OAA8C;AACjE,SAAQ,OAAwC,GAAkB,MAAM;AAC1E;","names":[]}
|