@noy-db/hub 0.6.0-pre.2 → 0.6.0-pre.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5234 -0
- package/codemods/0.4.0-pre.json +699 -0
- package/codemods/0.6.0-pre.json +211 -0
- package/dist/api-EYNT6KGS.js +20 -0
- package/dist/attestation/index.js +19 -19
- package/dist/{backup-YYBE5RPC.js → backup-FSC36VWC.js} +36 -18
- package/dist/backup-FSC36VWC.js.map +1 -0
- package/dist/blobs/index.js +13 -13
- package/dist/broker/index.js +12 -12
- package/dist/cargo/index.js +33 -33
- package/dist/{chunk-35EBKWQU.js → chunk-2LFOMUEA.js} +4 -4
- package/dist/{chunk-OF3L2SD6.js → chunk-32B7VCKU.js} +2 -2
- package/dist/{chunk-MSWYQLMQ.js → chunk-3B6S6RSI.js} +2 -2
- package/dist/{chunk-PJNTR2NV.js → chunk-3ENNPCIW.js} +7 -10
- package/dist/chunk-3ENNPCIW.js.map +1 -0
- package/dist/{chunk-7F4DBNSP.js → chunk-3O72ZD2E.js} +3 -3
- package/dist/{chunk-FNSMZQS4.js → chunk-3PMFMUFX.js} +2 -2
- package/dist/{chunk-WQDTCJ6W.js → chunk-45YHJ3GV.js} +11 -3
- package/dist/{chunk-WQDTCJ6W.js.map → chunk-45YHJ3GV.js.map} +1 -1
- package/dist/{chunk-NIVEDYJZ.js → chunk-4A34KWOU.js} +31 -49
- package/dist/chunk-4A34KWOU.js.map +1 -0
- package/dist/{chunk-ZJADGNYF.js → chunk-4AOERLTV.js} +1 -1
- package/dist/chunk-4AOERLTV.js.map +1 -0
- package/dist/{chunk-EDXAQ6JI.js → chunk-4N5Q23KV.js} +87 -34
- package/dist/chunk-4N5Q23KV.js.map +1 -0
- package/dist/{chunk-VV4NSB7P.js → chunk-4OQZNXQG.js} +15 -24
- package/dist/chunk-4OQZNXQG.js.map +1 -0
- package/dist/{chunk-FAXZQ5UF.js → chunk-4RAS6HN6.js} +2 -2
- package/dist/{chunk-C2OOEM57.js → chunk-4YL2LMXK.js} +92 -35
- package/dist/chunk-4YL2LMXK.js.map +1 -0
- package/dist/{chunk-EP7VPR7Y.js → chunk-5Q7AJ7DN.js} +11 -8
- package/dist/chunk-5Q7AJ7DN.js.map +1 -0
- package/dist/{chunk-VMCCGUQB.js → chunk-6JPGVL7X.js} +2 -2
- package/dist/{chunk-PRDRGL73.js → chunk-6KTVJ5ZZ.js} +17 -14
- package/dist/chunk-6KTVJ5ZZ.js.map +1 -0
- package/dist/{chunk-4MC5JRRX.js → chunk-6WO62AJW.js} +14 -15
- package/dist/chunk-6WO62AJW.js.map +1 -0
- package/dist/{chunk-WLYIROCJ.js → chunk-6YD5SYQS.js} +2 -2
- package/dist/{chunk-YAWK6AWF.js → chunk-7KAE7CQ2.js} +2 -2
- package/dist/{chunk-MWKDOHEF.js → chunk-7LNE2N2V.js} +17 -10
- package/dist/chunk-7LNE2N2V.js.map +1 -0
- package/dist/{chunk-5PR33AC4.js → chunk-7PJ3BKHS.js} +20 -17
- package/dist/chunk-7PJ3BKHS.js.map +1 -0
- package/dist/{chunk-JXIDGFKS.js → chunk-A4TOGAUW.js} +4 -2
- package/dist/chunk-A4TOGAUW.js.map +1 -0
- package/dist/{chunk-VCETL77O.js → chunk-AU3AUJIZ.js} +27 -7
- package/dist/chunk-AU3AUJIZ.js.map +1 -0
- package/dist/{chunk-NKH7GSIH.js → chunk-AUPSEJ7O.js} +4 -4
- package/dist/{chunk-CCZJJ4I2.js → chunk-B6IYATME.js} +4 -4
- package/dist/{chunk-WYZ5MYUA.js → chunk-BAHOV5I5.js} +44 -42
- package/dist/chunk-BAHOV5I5.js.map +1 -0
- package/dist/{chunk-G5APARUV.js → chunk-BEZDLIDG.js} +13 -15
- package/dist/chunk-BEZDLIDG.js.map +1 -0
- package/dist/{chunk-ERB6NDDW.js → chunk-CAGI4LLJ.js} +427 -72
- package/dist/chunk-CAGI4LLJ.js.map +1 -0
- package/dist/{chunk-4UVDI4XE.js → chunk-CLAHBPOI.js} +4 -4
- package/dist/{chunk-HNGSV2YC.js → chunk-CWM4GQD2.js} +39 -10
- package/dist/chunk-CWM4GQD2.js.map +1 -0
- package/dist/{chunk-HVQGCKY4.js → chunk-D3R7Q4QK.js} +2 -2
- package/dist/{chunk-I4F6PKUK.js → chunk-DIZ6HM7Q.js} +16 -17
- package/dist/chunk-DIZ6HM7Q.js.map +1 -0
- package/dist/{chunk-ZNACADFG.js → chunk-DVRZYAGT.js} +4 -4
- package/dist/chunk-DVRZYAGT.js.map +1 -0
- package/dist/{chunk-P7OG2ETF.js → chunk-DXKLLKME.js} +3 -3
- package/dist/{chunk-TDJPS3T2.js → chunk-E5SC6ENM.js} +24 -19
- package/dist/chunk-E5SC6ENM.js.map +1 -0
- package/dist/{chunk-26JMGSSC.js → chunk-EES37S2V.js} +4 -4
- package/dist/chunk-EES37S2V.js.map +1 -0
- package/dist/{chunk-JIUVJ4M7.js → chunk-EKEIEJL6.js} +2 -2
- package/dist/{chunk-GASWQ3XG.js → chunk-ESKIAXO2.js} +15 -16
- package/dist/chunk-ESKIAXO2.js.map +1 -0
- package/dist/{chunk-TOAIYQJR.js → chunk-FFSQFH6D.js} +7 -10
- package/dist/chunk-FFSQFH6D.js.map +1 -0
- package/dist/{chunk-DG27IUVI.js → chunk-FS7NTGCJ.js} +2 -2
- package/dist/{chunk-V5KYPBUR.js → chunk-FW7NGYLT.js} +11 -14
- package/dist/chunk-FW7NGYLT.js.map +1 -0
- package/dist/{chunk-52QYGZHH.js → chunk-GBBDFE6C.js} +2 -2
- package/dist/chunk-GBBDFE6C.js.map +1 -0
- package/dist/{chunk-HXGUIPQB.js → chunk-GQXFOAYZ.js} +3 -3
- package/dist/{chunk-BTVYJWSN.js → chunk-GTHVPVAR.js} +10 -10
- package/dist/{chunk-DMQCLZ4Z.js → chunk-GWO2IDAB.js} +2 -2
- package/dist/{chunk-6HFM7EIT.js → chunk-H3G4I3PN.js} +2 -2
- package/dist/chunk-HK67PX4J.js +27 -0
- package/dist/chunk-HK67PX4J.js.map +1 -0
- package/dist/{chunk-E7OBCBXS.js → chunk-HQSPF5IY.js} +22 -18
- package/dist/chunk-HQSPF5IY.js.map +1 -0
- package/dist/{chunk-VJFMXYKP.js → chunk-HR5R5JOM.js} +2 -2
- package/dist/{chunk-FDX7OWWI.js → chunk-HYYVT2KZ.js} +2 -2
- package/dist/{chunk-JRCYZEHU.js → chunk-I6QKB7MT.js} +2 -2
- package/dist/{chunk-MZ5ZFO2D.js → chunk-ICDHUUMQ.js} +84 -112
- package/dist/chunk-ICDHUUMQ.js.map +1 -0
- package/dist/{chunk-W5W6KHN2.js → chunk-IGNJOJEP.js} +1 -1
- package/dist/chunk-IGNJOJEP.js.map +1 -0
- package/dist/{chunk-KUDZVJKQ.js → chunk-IJ46VCWD.js} +2 -2
- package/dist/{chunk-4HDYQL3J.js → chunk-INMHEMXX.js} +2 -2
- package/dist/{chunk-66W5OOCX.js → chunk-JLYQQNY4.js} +52 -65
- package/dist/chunk-JLYQQNY4.js.map +1 -0
- package/dist/{chunk-UHXCLPGC.js → chunk-JNMTN5D5.js} +2 -2
- package/dist/chunk-JNMTN5D5.js.map +1 -0
- package/dist/{chunk-I4ZAO7F7.js → chunk-JWMBG5S3.js} +7 -11
- package/dist/chunk-JWMBG5S3.js.map +1 -0
- package/dist/chunk-KRVS7YWY.js +123 -0
- package/dist/chunk-KRVS7YWY.js.map +1 -0
- package/dist/{chunk-AR2JDFAE.js → chunk-KV6JM2IA.js} +2 -2
- package/dist/{chunk-PVU7LW5L.js → chunk-KX57HODD.js} +6 -6
- package/dist/{chunk-PY7CI6L5.js → chunk-LGFTOU27.js} +553 -275
- package/dist/chunk-LGFTOU27.js.map +1 -0
- package/dist/chunk-LN7P6MZB.js +190 -0
- package/dist/chunk-LN7P6MZB.js.map +1 -0
- package/dist/{chunk-UIBGXRDD.js → chunk-LX46B56Q.js} +25 -31
- package/dist/chunk-LX46B56Q.js.map +1 -0
- package/dist/{chunk-CEJWMBXO.js → chunk-LXECF2ZR.js} +2 -2
- package/dist/{chunk-7VHY5E3X.js → chunk-MSLPDFK2.js} +7 -7
- package/dist/{chunk-I6SDX7WX.js → chunk-MZTUTEHP.js} +16 -22
- package/dist/chunk-MZTUTEHP.js.map +1 -0
- package/dist/{chunk-VRA4Q7DA.js → chunk-NCCEDL2K.js} +55 -48
- package/dist/chunk-NCCEDL2K.js.map +1 -0
- package/dist/{chunk-HNHCQ556.js → chunk-NR2SUJ3H.js} +2 -2
- package/dist/{chunk-AHLJSVRL.js → chunk-NW4TY6VC.js} +5 -7
- package/dist/chunk-NW4TY6VC.js.map +1 -0
- package/dist/{chunk-RKKORO4M.js → chunk-O742QBZZ.js} +10 -10
- package/dist/chunk-O742QBZZ.js.map +1 -0
- package/dist/{chunk-VN45YLWM.js → chunk-OHOKBMTM.js} +343 -132
- package/dist/chunk-OHOKBMTM.js.map +1 -0
- package/dist/{chunk-W3TVWF6N.js → chunk-OIBEJN5H.js} +2 -2
- package/dist/{chunk-QD724WDJ.js → chunk-OMYCSTXL.js} +4 -4
- package/dist/{chunk-Z45YRGFO.js → chunk-ONVD6GBY.js} +2 -2
- package/dist/{chunk-TAGFGKHP.js → chunk-OTHHO3KI.js} +7 -10
- package/dist/chunk-OTHHO3KI.js.map +1 -0
- package/dist/{chunk-3737A6EA.js → chunk-P2MR5UNE.js} +75 -18
- package/dist/chunk-P2MR5UNE.js.map +1 -0
- package/dist/chunk-PENPHA45.js +66 -0
- package/dist/chunk-PENPHA45.js.map +1 -0
- package/dist/{chunk-3FSX6LDG.js → chunk-PPCOKVFA.js} +8 -3
- package/dist/{chunk-3FSX6LDG.js.map → chunk-PPCOKVFA.js.map} +1 -1
- package/dist/{chunk-VOQW5LAM.js → chunk-QSIEL6TL.js} +102 -71
- package/dist/chunk-QSIEL6TL.js.map +1 -0
- package/dist/chunk-RFO4UXKQ.js +201 -0
- package/dist/chunk-RFO4UXKQ.js.map +1 -0
- package/dist/{chunk-KCQX65FU.js → chunk-RKCRPPNB.js} +3 -3
- package/dist/{chunk-7TSYBD3E.js → chunk-RSXQNFGO.js} +2 -2
- package/dist/{chunk-SZ2K3MHL.js → chunk-S56VYR4Q.js} +8 -11
- package/dist/{chunk-SZ2K3MHL.js.map → chunk-S56VYR4Q.js.map} +1 -1
- package/dist/{chunk-7NXHMW6Y.js → chunk-SYS46BL7.js} +2 -2
- package/dist/{chunk-55LKVALY.js → chunk-T7IR4N2S.js} +1 -3
- package/dist/chunk-T7IR4N2S.js.map +1 -0
- package/dist/{chunk-A67356IR.js → chunk-T7JGWTES.js} +33 -8
- package/dist/chunk-T7JGWTES.js.map +1 -0
- package/dist/{chunk-WHJKIZS7.js → chunk-TDSN2O2V.js} +27 -149
- package/dist/chunk-TDSN2O2V.js.map +1 -0
- package/dist/{chunk-747LRSOO.js → chunk-TMBSPLUG.js} +2 -2
- package/dist/{chunk-LWSJG3LI.js → chunk-TQPASLY4.js} +7 -3
- package/dist/chunk-TQPASLY4.js.map +1 -0
- package/dist/{chunk-WKPJXWKR.js → chunk-TX5MKAHA.js} +3 -3
- package/dist/{chunk-HFQ6LGIO.js → chunk-U27Y4DJZ.js} +12 -10
- package/dist/{chunk-HFQ6LGIO.js.map → chunk-U27Y4DJZ.js.map} +1 -1
- package/dist/{chunk-E6427JU2.js → chunk-VVSOPRUE.js} +18 -2
- package/dist/chunk-VVSOPRUE.js.map +1 -0
- package/dist/{chunk-7G6VDWXB.js → chunk-WVE6YKMX.js} +3 -3
- package/dist/chunk-WVE6YKMX.js.map +1 -0
- package/dist/{chunk-GLKDWWNO.js → chunk-YALD3SST.js} +16 -14
- package/dist/chunk-YALD3SST.js.map +1 -0
- package/dist/{chunk-NJDQ4YSV.js → chunk-YKXZHUOW.js} +4 -4
- package/dist/{chunk-VW6ZZGCG.js → chunk-ZLHHE5XZ.js} +3 -3
- package/dist/{chunk-FUHKW252.js → chunk-ZZXLB6AS.js} +2 -2
- package/dist/classified/index.js +5 -5
- package/dist/{classified-marker-FTOX7Q5L.js → classified-marker-NA6HUV33.js} +3 -3
- package/dist/collection-facade-VBM35WAH.js +45 -0
- package/dist/{computed-6G5M3UPH.js → computed-GSTLWSY5.js} +3 -3
- package/dist/consent/index.js +10 -10
- package/dist/cover/index.js +10 -3
- package/dist/custody/index.js +11 -11
- package/dist/{dead-filter-ENRIOQIE.js → dead-filter-UALP5DJX.js} +2 -2
- package/dist/debug/index.js +1 -1
- package/dist/{delegation-SSEPLXXO.js → delegation-JLNXM7KH.js} +24 -23
- package/dist/delegation-JLNXM7KH.js.map +1 -0
- package/dist/derivations/index.js +12 -12
- package/dist/derive-YUO3TQYN.js +22 -0
- package/dist/directory/index.js +10 -10
- package/dist/{dispatch-RE74SH6L.js → dispatch-4ZHLSFZQ.js} +5 -5
- package/dist/{dispatch-BDVGYC6X.js → dispatch-77CB75KB.js} +18 -18
- package/dist/{enclave-52VUXNRL.js → enclave-O4NOROCJ.js} +27 -9
- package/dist/executor-CZDXBXKE.js +29 -0
- package/dist/executor-DVJAWN3B.js +9 -0
- package/dist/executor-VRLG4TQJ.js +9 -0
- package/dist/export-accessible-UXSMG7AB.js +23 -0
- package/dist/extract-partition-TVY7AMKH.js +38 -0
- package/dist/{fanout-sidecar-DTBIDOWF.js → fanout-sidecar-NLQ7QAYW.js} +18 -27
- package/dist/fanout-sidecar-NLQ7QAYW.js.map +1 -0
- package/dist/find-WSARMJBW.js +11 -0
- package/dist/forget/index.js +9 -9
- package/dist/guards/index.js +7 -7
- package/dist/history/index.js +23 -20
- package/dist/history/index.js.map +1 -1
- package/dist/i18n/index.js +14 -14
- package/dist/index.d.ts +33 -15
- package/dist/index.js +187 -191
- package/dist/index.js.map +1 -1
- package/dist/indexing/index.js +2 -2
- package/dist/introspection/index.js +11 -11
- package/dist/issue-3JNJNPT3.js +19 -0
- package/dist/kernel/constants.d.ts +18 -0
- package/dist/kernel/enclave/crypto.d.ts +24 -4
- package/dist/kernel/enclave/index.d.ts +9 -2
- package/dist/kernel/enclave/record-aad.d.ts +131 -0
- package/dist/kernel/enclave/record-envelope.d.ts +76 -0
- package/dist/kernel/enclave/record-keys/envelope-body.d.ts +34 -2
- package/dist/kernel/enclave/record-keys/lifecycle.d.ts +22 -5
- package/dist/kernel/enclave/record-keys/record-codec.d.ts +47 -14
- package/dist/kernel/enclave/record-keys/rekey-blob.d.ts +88 -0
- package/dist/kernel/enclave/record-keys/rekey.d.ts +68 -0
- package/dist/kernel/enclave/record-keys/tombstone.d.ts +3 -2
- package/dist/kernel/errors.d.ts +71 -12
- package/dist/kernel/merge-authority.d.ts +25 -0
- package/dist/kernel/noydb.d.ts +27 -4
- package/dist/kernel/query/builder.d.ts +15 -2
- package/dist/kernel/query/join.d.ts +27 -0
- package/dist/kernel/sync-policy.d.ts +0 -2
- package/dist/kernel/tier-visibility.d.ts +15 -0
- package/dist/kernel/types.d.ts +145 -12
- package/dist/kernel/vault.d.ts +22 -18
- package/dist/kernel/via/index.d.ts +11 -2
- package/dist/{ledger-4WJL66BW.js → ledger-MVPNG5OS.js} +11 -11
- package/dist/liberate-4LOJOLDT.js +24 -0
- package/dist/{link-set-N4ZPV6E6.js → link-set-3POMQR3I.js} +11 -11
- package/dist/{managed-secret-OTHS64IF.js → managed-secret-IARIJJ7Q.js} +11 -3
- package/dist/materialized-views/index.js +22 -21
- package/dist/migrate-cek-XM2ETTZW.js +19 -0
- package/dist/migrate-cek-XM2ETTZW.js.map +1 -0
- package/dist/money/index.js +12 -8
- package/dist/noydb-IRILUDED.js +84 -0
- package/dist/overlay-views/index.js +4 -4
- package/dist/periods/index.js +22 -12
- package/dist/pod/index.js +75 -86
- package/dist/pod-handle-MELERCKU.js +41 -0
- package/dist/pod-handle-MELERCKU.js.map +1 -0
- package/dist/policy/index.js +11 -4
- package/dist/port/to/index.d.ts +4 -4
- package/dist/port/to/locator.d.ts +54 -8
- package/dist/port/with/i18n-strategy.d.ts +4 -1
- package/dist/port/with/lookup-strategy.d.ts +4 -1
- package/dist/port/with/merge-authority.d.ts +52 -0
- package/dist/port/with/service-bus.d.ts +0 -4
- package/dist/port/with/strategies.d.ts +2 -0
- package/dist/port/with/team-strategy.d.ts +5 -1
- package/dist/portability/index.js +8 -8
- package/dist/{post-register-ZAG2CAIY.js → post-register-Z5T7FY45.js} +6 -6
- package/dist/query/index.js +3 -3
- package/dist/reduce/index.js +4 -4
- package/dist/register-UZ37QPDB.js +32 -0
- package/dist/registry-ETJNA7PO.js +9 -0
- package/dist/registry-F7U6KSLX.js +9 -0
- package/dist/registry-L4ELKX6C.js +18 -0
- package/dist/registry-SDT5LIGO.js +19 -0
- package/dist/request-withdrawal-PVFEYX57.js +31 -0
- package/dist/{reveal-CMOJY4VO.js → reveal-DQ2E3QAZ.js} +6 -6
- package/dist/revoke-YXY6SHUH.js +24 -0
- package/dist/satellites/index.js +1 -1
- package/dist/schema-update/index.js +2 -2
- package/dist/sealed-record/index.js +20 -13
- package/dist/sealed-record/index.js.map +1 -1
- package/dist/search/index.js +4 -4
- package/dist/{seed-UK4QRIUN.js → seed-DZ4ORU5N.js} +19 -22
- package/dist/seed-DZ4ORU5N.js.map +1 -0
- package/dist/sequence/index.js +9 -9
- package/dist/session/index.js +10 -10
- package/dist/shadow/index.js +2 -2
- package/dist/share-link/index.js +1 -1
- package/dist/signer-Q7XQBMPA.js +25 -0
- package/dist/snapshots/index.js +10 -10
- package/dist/snapshots/index.js.map +1 -1
- package/dist/{stale-ZWXSOWJI.js → stale-NI7SAXAZ.js} +10 -10
- package/dist/storage-3VNGSHXS.js +23 -0
- package/dist/{store-coordination-provider-PB6QZ57W.js → store-coordination-provider-TYKNR3OU.js} +18 -12
- package/dist/store-coordination-provider-TYKNR3OU.js.map +1 -0
- package/dist/sync/index.js +11 -11
- package/dist/team/index.js +15 -14
- package/dist/tiers/index.js +11 -10
- package/dist/to/index.js +17 -9
- package/dist/to/index.js.map +1 -1
- package/dist/transactions/index.js +4 -4
- package/dist/{ulid-PTAIMDG4.js → ulid-VQW6ERQN.js} +2 -2
- package/dist/util/index.js +1 -1
- package/dist/vault-head/index.js +115 -0
- package/dist/vault-head/index.js.map +1 -0
- package/dist/{verify-RO5RTZOJ.js → verify-6J2YLKSO.js} +5 -5
- package/dist/via/lookup/handle.d.ts +4 -1
- package/dist/via/money/exact.d.ts +44 -0
- package/dist/via/money/index.d.ts +2 -0
- package/dist/via/money/normalize.d.ts +20 -0
- package/dist/walk-WRA7RAPY.js +21 -0
- package/dist/with-audit/guards/immutable-guard.d.ts +14 -0
- package/dist/with-audit/periods/active.d.ts +28 -1
- package/dist/with-audit/periods/index.d.ts +4 -2
- package/dist/with-audit/periods/periods.d.ts +161 -6
- package/dist/with-audit/periods/strategy.d.ts +14 -5
- package/dist/with-audit/periods/vault-facade.d.ts +89 -10
- package/dist/with-audit/periods/window.d.ts +10 -0
- package/dist/with-audit/sealed-record/index.d.ts +13 -0
- package/dist/with-audit/tiers/index.d.ts +17 -2
- package/dist/with-cargo/adopt-partition.d.ts +1 -1
- package/dist/with-cargo/extract-partition.d.ts +1 -1
- package/dist/with-cargo/index.d.ts +2 -2
- package/dist/with-commit/history/history.d.ts +26 -0
- package/dist/with-commit/history/index.d.ts +2 -1
- package/dist/with-commit/history/ledger/store.d.ts +7 -1
- package/dist/with-commit/history/strategy.d.ts +11 -1
- package/dist/with-commit/numbering/index.d.ts +0 -5
- package/dist/with-commit/vault-head/active.d.ts +2 -0
- package/dist/with-commit/vault-head/head.d.ts +28 -0
- package/dist/with-commit/vault-head/index.d.ts +10 -0
- package/dist/with-commit/vault-head/strategy.d.ts +127 -0
- package/dist/with-commit/vault-head/verify.d.ts +90 -0
- package/dist/with-formula/materialized-views/types.d.ts +52 -0
- package/dist/with-party/directory/cover/storage.d.ts +0 -8
- package/dist/with-party/directory/storage.d.ts +0 -11
- package/dist/with-party/directory/visibility.d.ts +0 -21
- package/dist/with-party/policy/storage.d.ts +0 -10
- package/dist/with-party/team/index.d.ts +1 -1
- package/dist/with-party/team/keyring.d.ts +149 -3
- package/dist/with-party/team/noydb-facade.d.ts +5 -1
- package/dist/with-party/team/roster-tag.d.ts +101 -0
- package/dist/with-party/team/tiers.d.ts +2 -1
- package/dist/with-pod/format.d.ts +10 -12
- package/dist/with-pod/index.d.ts +10 -10
- package/dist/with-pod/open.d.ts +2 -2
- package/dist/with-pod/pod-handle.d.ts +19 -0
- package/dist/with-pod/pod-store.d.ts +0 -8
- package/dist/with-pod/{bundle.d.ts → pod.d.ts} +26 -19
- package/dist/with-pod/ulid.d.ts +1 -1
- package/dist/with-shape/blobs/blob-set.d.ts +2 -2
- package/dist/with-shape/introspection/index.d.ts +1 -0
- package/dist/with-sync/engine.d.ts +54 -5
- package/dist/with-sync/strategy.d.ts +3 -0
- package/dist/withdraw-accessible-4JTDFRFZ.js +28 -0
- package/package.json +13 -5
- package/dist/api-WVY3H3YH.js +0 -20
- package/dist/backup-YYBE5RPC.js.map +0 -1
- package/dist/bundle-handle-JEUWU2SJ.js +0 -36
- package/dist/bundle-handle-JEUWU2SJ.js.map +0 -1
- package/dist/chunk-26JMGSSC.js.map +0 -1
- package/dist/chunk-3737A6EA.js.map +0 -1
- package/dist/chunk-4MC5JRRX.js.map +0 -1
- package/dist/chunk-52QYGZHH.js.map +0 -1
- package/dist/chunk-55LKVALY.js.map +0 -1
- package/dist/chunk-5PR33AC4.js.map +0 -1
- package/dist/chunk-66W5OOCX.js.map +0 -1
- package/dist/chunk-7G6VDWXB.js.map +0 -1
- package/dist/chunk-A67356IR.js.map +0 -1
- package/dist/chunk-AFHQATY4.js +0 -47
- package/dist/chunk-AFHQATY4.js.map +0 -1
- package/dist/chunk-AHLJSVRL.js.map +0 -1
- package/dist/chunk-C2OOEM57.js.map +0 -1
- package/dist/chunk-DIMKRG2E.js +0 -131
- package/dist/chunk-DIMKRG2E.js.map +0 -1
- package/dist/chunk-E6427JU2.js.map +0 -1
- package/dist/chunk-E7OBCBXS.js.map +0 -1
- package/dist/chunk-EDXAQ6JI.js.map +0 -1
- package/dist/chunk-EP7VPR7Y.js.map +0 -1
- package/dist/chunk-ERB6NDDW.js.map +0 -1
- package/dist/chunk-G5APARUV.js.map +0 -1
- package/dist/chunk-GASWQ3XG.js.map +0 -1
- package/dist/chunk-GLKDWWNO.js.map +0 -1
- package/dist/chunk-HNGSV2YC.js.map +0 -1
- package/dist/chunk-I4F6PKUK.js.map +0 -1
- package/dist/chunk-I4ZAO7F7.js.map +0 -1
- package/dist/chunk-I6SDX7WX.js.map +0 -1
- package/dist/chunk-JXIDGFKS.js.map +0 -1
- package/dist/chunk-LWSJG3LI.js.map +0 -1
- package/dist/chunk-MWKDOHEF.js.map +0 -1
- package/dist/chunk-MZ5ZFO2D.js.map +0 -1
- package/dist/chunk-NIVEDYJZ.js.map +0 -1
- package/dist/chunk-NWCGDAV6.js +0 -45
- package/dist/chunk-NWCGDAV6.js.map +0 -1
- package/dist/chunk-PJNTR2NV.js.map +0 -1
- package/dist/chunk-PRDRGL73.js.map +0 -1
- package/dist/chunk-PY7CI6L5.js.map +0 -1
- package/dist/chunk-RKKORO4M.js.map +0 -1
- package/dist/chunk-TAGFGKHP.js.map +0 -1
- package/dist/chunk-TDJPS3T2.js.map +0 -1
- package/dist/chunk-TOAIYQJR.js.map +0 -1
- package/dist/chunk-UHXCLPGC.js.map +0 -1
- package/dist/chunk-UIBGXRDD.js.map +0 -1
- package/dist/chunk-V5KYPBUR.js.map +0 -1
- package/dist/chunk-VCETL77O.js.map +0 -1
- package/dist/chunk-VN45YLWM.js.map +0 -1
- package/dist/chunk-VOQW5LAM.js.map +0 -1
- package/dist/chunk-VRA4Q7DA.js.map +0 -1
- package/dist/chunk-VV4NSB7P.js.map +0 -1
- package/dist/chunk-W5W6KHN2.js.map +0 -1
- package/dist/chunk-WHJKIZS7.js.map +0 -1
- package/dist/chunk-WYZ5MYUA.js.map +0 -1
- package/dist/chunk-ZJADGNYF.js.map +0 -1
- package/dist/chunk-ZNACADFG.js.map +0 -1
- package/dist/collection-facade-QN5ULWYC.js +0 -45
- package/dist/delegation-SSEPLXXO.js.map +0 -1
- package/dist/derive-6V3PIZF7.js +0 -22
- package/dist/executor-CYJQLKKI.js +0 -9
- package/dist/executor-FHHLXO4Y.js +0 -28
- package/dist/executor-S4QIKEHW.js +0 -9
- package/dist/export-accessible-PE5AYKZR.js +0 -23
- package/dist/extract-partition-X2L26O6A.js +0 -38
- package/dist/fanout-sidecar-DTBIDOWF.js.map +0 -1
- package/dist/find-RBBYKXI7.js +0 -11
- package/dist/issue-RNU55YOF.js +0 -19
- package/dist/liberate-PX4CAT5V.js +0 -24
- package/dist/noydb-YPSEGK32.js +0 -83
- package/dist/register-TMD6YRCX.js +0 -32
- package/dist/registry-CZVINVQH.js +0 -9
- package/dist/registry-FVLDWQKT.js +0 -18
- package/dist/registry-IKUR2MXD.js +0 -9
- package/dist/registry-JET4HBLY.js +0 -19
- package/dist/request-withdrawal-RH55LNZL.js +0 -31
- package/dist/revoke-R5TBYVA6.js +0 -24
- package/dist/seed-UK4QRIUN.js.map +0 -1
- package/dist/signer-AGALOXOO.js +0 -25
- package/dist/storage-N7LB275C.js +0 -23
- package/dist/store-coordination-provider-PB6QZ57W.js.map +0 -1
- package/dist/walk-OCUHCYJ6.js +0 -21
- package/dist/with-pod/bundle-handle.d.ts +0 -9
- package/dist/withdraw-accessible-QQNWM5BO.js +0 -28
- /package/dist/{api-WVY3H3YH.js.map → api-EYNT6KGS.js.map} +0 -0
- /package/dist/{chunk-35EBKWQU.js.map → chunk-2LFOMUEA.js.map} +0 -0
- /package/dist/{chunk-OF3L2SD6.js.map → chunk-32B7VCKU.js.map} +0 -0
- /package/dist/{chunk-MSWYQLMQ.js.map → chunk-3B6S6RSI.js.map} +0 -0
- /package/dist/{chunk-7F4DBNSP.js.map → chunk-3O72ZD2E.js.map} +0 -0
- /package/dist/{chunk-FNSMZQS4.js.map → chunk-3PMFMUFX.js.map} +0 -0
- /package/dist/{chunk-FAXZQ5UF.js.map → chunk-4RAS6HN6.js.map} +0 -0
- /package/dist/{chunk-VMCCGUQB.js.map → chunk-6JPGVL7X.js.map} +0 -0
- /package/dist/{chunk-WLYIROCJ.js.map → chunk-6YD5SYQS.js.map} +0 -0
- /package/dist/{chunk-YAWK6AWF.js.map → chunk-7KAE7CQ2.js.map} +0 -0
- /package/dist/{chunk-NKH7GSIH.js.map → chunk-AUPSEJ7O.js.map} +0 -0
- /package/dist/{chunk-CCZJJ4I2.js.map → chunk-B6IYATME.js.map} +0 -0
- /package/dist/{chunk-4UVDI4XE.js.map → chunk-CLAHBPOI.js.map} +0 -0
- /package/dist/{chunk-HVQGCKY4.js.map → chunk-D3R7Q4QK.js.map} +0 -0
- /package/dist/{chunk-P7OG2ETF.js.map → chunk-DXKLLKME.js.map} +0 -0
- /package/dist/{chunk-JIUVJ4M7.js.map → chunk-EKEIEJL6.js.map} +0 -0
- /package/dist/{chunk-DG27IUVI.js.map → chunk-FS7NTGCJ.js.map} +0 -0
- /package/dist/{chunk-HXGUIPQB.js.map → chunk-GQXFOAYZ.js.map} +0 -0
- /package/dist/{chunk-BTVYJWSN.js.map → chunk-GTHVPVAR.js.map} +0 -0
- /package/dist/{chunk-DMQCLZ4Z.js.map → chunk-GWO2IDAB.js.map} +0 -0
- /package/dist/{chunk-6HFM7EIT.js.map → chunk-H3G4I3PN.js.map} +0 -0
- /package/dist/{chunk-VJFMXYKP.js.map → chunk-HR5R5JOM.js.map} +0 -0
- /package/dist/{chunk-FDX7OWWI.js.map → chunk-HYYVT2KZ.js.map} +0 -0
- /package/dist/{chunk-JRCYZEHU.js.map → chunk-I6QKB7MT.js.map} +0 -0
- /package/dist/{chunk-KUDZVJKQ.js.map → chunk-IJ46VCWD.js.map} +0 -0
- /package/dist/{chunk-4HDYQL3J.js.map → chunk-INMHEMXX.js.map} +0 -0
- /package/dist/{chunk-AR2JDFAE.js.map → chunk-KV6JM2IA.js.map} +0 -0
- /package/dist/{chunk-PVU7LW5L.js.map → chunk-KX57HODD.js.map} +0 -0
- /package/dist/{chunk-CEJWMBXO.js.map → chunk-LXECF2ZR.js.map} +0 -0
- /package/dist/{chunk-7VHY5E3X.js.map → chunk-MSLPDFK2.js.map} +0 -0
- /package/dist/{chunk-HNHCQ556.js.map → chunk-NR2SUJ3H.js.map} +0 -0
- /package/dist/{chunk-W3TVWF6N.js.map → chunk-OIBEJN5H.js.map} +0 -0
- /package/dist/{chunk-QD724WDJ.js.map → chunk-OMYCSTXL.js.map} +0 -0
- /package/dist/{chunk-Z45YRGFO.js.map → chunk-ONVD6GBY.js.map} +0 -0
- /package/dist/{chunk-KCQX65FU.js.map → chunk-RKCRPPNB.js.map} +0 -0
- /package/dist/{chunk-7TSYBD3E.js.map → chunk-RSXQNFGO.js.map} +0 -0
- /package/dist/{chunk-7NXHMW6Y.js.map → chunk-SYS46BL7.js.map} +0 -0
- /package/dist/{chunk-747LRSOO.js.map → chunk-TMBSPLUG.js.map} +0 -0
- /package/dist/{chunk-WKPJXWKR.js.map → chunk-TX5MKAHA.js.map} +0 -0
- /package/dist/{chunk-NJDQ4YSV.js.map → chunk-YKXZHUOW.js.map} +0 -0
- /package/dist/{chunk-VW6ZZGCG.js.map → chunk-ZLHHE5XZ.js.map} +0 -0
- /package/dist/{chunk-FUHKW252.js.map → chunk-ZZXLB6AS.js.map} +0 -0
- /package/dist/{classified-marker-FTOX7Q5L.js.map → classified-marker-NA6HUV33.js.map} +0 -0
- /package/dist/{collection-facade-QN5ULWYC.js.map → collection-facade-VBM35WAH.js.map} +0 -0
- /package/dist/{computed-6G5M3UPH.js.map → computed-GSTLWSY5.js.map} +0 -0
- /package/dist/{dead-filter-ENRIOQIE.js.map → dead-filter-UALP5DJX.js.map} +0 -0
- /package/dist/{derive-6V3PIZF7.js.map → derive-YUO3TQYN.js.map} +0 -0
- /package/dist/{dispatch-RE74SH6L.js.map → dispatch-4ZHLSFZQ.js.map} +0 -0
- /package/dist/{dispatch-BDVGYC6X.js.map → dispatch-77CB75KB.js.map} +0 -0
- /package/dist/{enclave-52VUXNRL.js.map → enclave-O4NOROCJ.js.map} +0 -0
- /package/dist/{executor-CYJQLKKI.js.map → executor-CZDXBXKE.js.map} +0 -0
- /package/dist/{executor-FHHLXO4Y.js.map → executor-DVJAWN3B.js.map} +0 -0
- /package/dist/{executor-S4QIKEHW.js.map → executor-VRLG4TQJ.js.map} +0 -0
- /package/dist/{export-accessible-PE5AYKZR.js.map → export-accessible-UXSMG7AB.js.map} +0 -0
- /package/dist/{extract-partition-X2L26O6A.js.map → extract-partition-TVY7AMKH.js.map} +0 -0
- /package/dist/{find-RBBYKXI7.js.map → find-WSARMJBW.js.map} +0 -0
- /package/dist/{issue-RNU55YOF.js.map → issue-3JNJNPT3.js.map} +0 -0
- /package/dist/{ledger-4WJL66BW.js.map → ledger-MVPNG5OS.js.map} +0 -0
- /package/dist/{liberate-PX4CAT5V.js.map → liberate-4LOJOLDT.js.map} +0 -0
- /package/dist/{link-set-N4ZPV6E6.js.map → link-set-3POMQR3I.js.map} +0 -0
- /package/dist/{managed-secret-OTHS64IF.js.map → managed-secret-IARIJJ7Q.js.map} +0 -0
- /package/dist/{noydb-YPSEGK32.js.map → noydb-IRILUDED.js.map} +0 -0
- /package/dist/{post-register-ZAG2CAIY.js.map → post-register-Z5T7FY45.js.map} +0 -0
- /package/dist/{register-TMD6YRCX.js.map → register-UZ37QPDB.js.map} +0 -0
- /package/dist/{registry-CZVINVQH.js.map → registry-ETJNA7PO.js.map} +0 -0
- /package/dist/{registry-FVLDWQKT.js.map → registry-F7U6KSLX.js.map} +0 -0
- /package/dist/{registry-IKUR2MXD.js.map → registry-L4ELKX6C.js.map} +0 -0
- /package/dist/{registry-JET4HBLY.js.map → registry-SDT5LIGO.js.map} +0 -0
- /package/dist/{request-withdrawal-RH55LNZL.js.map → request-withdrawal-PVFEYX57.js.map} +0 -0
- /package/dist/{reveal-CMOJY4VO.js.map → reveal-DQ2E3QAZ.js.map} +0 -0
- /package/dist/{revoke-R5TBYVA6.js.map → revoke-YXY6SHUH.js.map} +0 -0
- /package/dist/{signer-AGALOXOO.js.map → signer-Q7XQBMPA.js.map} +0 -0
- /package/dist/{stale-ZWXSOWJI.js.map → stale-NI7SAXAZ.js.map} +0 -0
- /package/dist/{storage-N7LB275C.js.map → storage-3VNGSHXS.js.map} +0 -0
- /package/dist/{ulid-PTAIMDG4.js.map → ulid-VQW6ERQN.js.map} +0 -0
- /package/dist/{verify-RO5RTZOJ.js.map → verify-6J2YLKSO.js.map} +0 -0
- /package/dist/{walk-OCUHCYJ6.js.map → walk-WRA7RAPY.js.map} +0 -0
- /package/dist/{withdraw-accessible-QQNWM5BO.js.map → withdraw-accessible-4JTDFRFZ.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/with-pod/format.ts","../src/with-pod/signature.ts","../src/with-pod/pod.ts"],"sourcesContent":["/**\n * `.noydb` container format — byte layout, header schema, validators.\n *\n *. Wraps a `vault.dump()` JSON string in a thin\n * binary container with a magic-byte prefix, a minimum-disclosure\n * unencrypted header, and a compressed body.\n *\n * **Byte layout** (read in order from offset 0):\n *\n * ```\n * +--------+--------+--------+--------+\n * | N=78 | D=68 | B=66 | 1=49 | Magic 'NDB1' (4 bytes)\n * +--------+--------+--------+--------+\n * | flags | compr | header_length (uint32 BE) |\n * +--------+--------+--------+--------+--------+--------+--------+\n * | header_length bytes of UTF-8 JSON header ...\n * +--------+--------+\n * | compressed body bytes ...\n * ```\n *\n * Total fixed prefix before the header JSON is **10 bytes**:\n * - 4 bytes magic\n * - 1 byte flags\n * - 1 byte compression algorithm\n * - 4 bytes header length (uint32 big-endian)\n *\n * **Why a binary container** at all? `vault.dump()` already\n * produces a JSON string with encrypted records inside. Wrapping it\n * again seems redundant — but the wrap is what makes the file safe\n * to drop into cloud storage (Drive, Dropbox, iCloud) without\n * leaking the vault name and exporter identity through the\n * cloud's metadata API. The minimum-disclosure header is the only\n * thing visible without downloading and decompressing the body.\n * The dump JSON inside the body still contains the original\n * metadata, but that's only readable by someone who already has the\n * file bytes — the same person who could read the encrypted records\n * with the right secret.\n *\n * **Why minimum disclosure** in the header? Because consumers will\n * inevitably store these in services where the filename, file size,\n * and any unencrypted metadata are indexed for search. A field like\n * `vault: \"Acme Corp\"` would let an attacker (or a curious\n * cloud admin) enumerate which compartments exist and who exported\n * them, even with zero access to the encrypted body. The header\n * carries only what's needed to identify the file as a NOYDB\n * bundle and verify its integrity — nothing about the contents.\n */\n\nimport type { Cover } from '../with-party/directory/cover/types.js'\nimport type { Redirect } from './redirect.js'\n\n/** Magic bytes 'NDB1' (ASCII) — `NoyDB 1` — identifying a NOYDB pod (`.noydb` container). */\nexport const NOYDB_POD_MAGIC = new Uint8Array([0x4e, 0x44, 0x42, 0x31])\n\n/** Total fixed prefix before the header JSON: 4+1+1+4 bytes. */\nexport const NOYDB_POD_PREFIX_BYTES = 10\n\n/** Current bundle format version. Bumped on layout changes. Default for unsigned pods. */\nexport const NOYDB_POD_FORMAT_VERSION = 1\n\n/** Format version for pods carrying a header signature (`sig`/`keyId`/`sigAlg`). */\nexport const NOYDB_POD_FORMAT_VERSION_SIGNED = 2\n\n/**\n * Bitfield interpretation of the flags byte.\n *\n * Bit 0 — body is compressed (0 = raw, 1 = compressed)\n * Bit 1 — header carries an integrity hash over the body bytes\n * Bits 2-7 — reserved, must be 0 in\n */\nexport const FLAG_COMPRESSED = 0b0000_0001\nexport const FLAG_HAS_INTEGRITY_HASH = 0b0000_0010\n\n/**\n * Compression algorithm encoding for the byte at offset 5.\n *\n * `none` is admitted for round-trip testing and for callers that\n * want to bundle without compression (e.g. when piping into a\n * separately compressed transport). `gzip` is the universally\n * available baseline (Node 18+, all modern browsers). `brotli` is\n * preferred when the runtime supports it — typically 30-50% smaller\n * for JSON payloads — but Node 22+ / Chrome 124+ / Firefox 122+\n * are required, so the writer feature-detects at runtime and falls\n * back to gzip. The reader must handle all three.\n */\nexport const COMPRESSION_NONE = 0\nexport const COMPRESSION_GZIP = 1\nexport const COMPRESSION_BROTLI = 2\n\nexport type CompressionAlgo = 0 | 1 | 2\n\n/**\n * The unencrypted header carried in every `.noydb` bundle.\n *\n * **Minimum-disclosure rules:** these are the ONLY allowed keys.\n * Any other key in a parsed header causes\n * `validatePodHeaderFields` to throw. The set is kept short to\n * minimize attack surface from cloud-storage metadata indexing —\n * see the file-level doc comment for the rationale.\n *\n * Forbidden in particular:\n * - `vault` / `_compartment` — would leak the tenant name\n * - `exporter` / `_exported_by` — would leak user identity\n * - `timestamp` / `_exported_at` — would leak activity timing\n * - `kdfParams` / salt fields — would leak crypto config that\n * could narrow brute-force search space\n * - any field starting with `_` (reserved by the dump format)\n */\nexport interface NoydbPodHeader {\n /** Bundle format version — bumped on layout changes. */\n readonly formatVersion: number\n /**\n * Opaque ULID identifier — generated once per vault and\n * stable across re-exports of the same vault. Does not\n * leak any information about contents (the timestamp prefix is\n * just monotonicity for sortability, not exporter activity —\n * see `bundle/ulid.ts` for the design notes).\n */\n readonly handle: string\n /** Compressed body length in bytes. Lets readers verify completeness without decompressing. */\n readonly bodyBytes: number\n /** SHA-256 of the compressed body bytes (lowercase hex). Lets readers verify integrity without decompressing. */\n readonly bodySha256: string\n /**\n * Owner-curated cover (`https://github.com/vLannaAi/noy-db-docs/blob/main/content/docs/services/public-envelope.md`).\n * Optional — present only when the source vault has a\n * `_meta/public-envelope` document AND the writer's hub is opted\n * into the feature. Treat as **untrusted hint**; the body's\n * encrypted contents remain the source of truth.\n *\n * The JSON key keeps its frozen wire name `publicEnvelope` (#799\n * renamed only the developer surface — existing bundles stay\n * readable byte-for-byte).\n *\n * The cover deliberately widens the minimum-disclosure rule\n * for explicit, owner-curated label fields (name, icon, …). Every\n * other unknown header key still rejects at parse time.\n */\n readonly publicEnvelope?: Cover\n /**\n * Auto-unlock material indicator. When present, the bundle\n * body wraps the dump JSON in a structure carrying per-user\n * secrets — either plaintext (`'unsealed'`, public-by-design)\n * or sealed under a `SealingKeyProvider` (`'sealed'`, requires\n * matching provider on the recipient side).\n *\n * Visible pre-decompression so cloud listing UIs can warn before\n * download: \"this bundle opens itself for anyone holding the file\"\n * (unsealed) or \"this bundle is sealed for a specific provider\"\n * (sealed).\n *\n * Absent → the body is a raw `vault.dump()` JSON string (the\n * the legacy shape; back-compatible).\n */\n readonly autoUnlock?: 'unsealed' | 'sealed'\n /**\n * Bundle's role in the source → destination lifecycle.\n * - omitted / 'snapshot' (default): backup/copy of an existing vault.\n * - 'extracted-partition': re-keyed projection awaiting adoption.\n */\n readonly bundleKind?: 'snapshot' | 'extracted-partition'\n /**\n * Transfer-seal INDICATOR — metadata only, no payload (the\n * sealed DEKs live in the body). Present iff\n * bundleKind === 'extracted-partition'.\n */\n readonly transferSeal?: {\n readonly v: 1\n readonly alg: 'aes-256-gcm-pre-shared'\n readonly sealId: string\n }\n /**\n * Non-secret 16-hex-char fingerprint identifying the signing key\n * used for `sig`. A hash prefix, not the key itself — discloses no\n * crypto config, safe under minimum-disclosure. Present iff `sig`\n * and `sigAlg` are also present (all-or-nothing 3-tuple), and only\n * on `formatVersion === 2` headers.\n */\n readonly keyId?: string\n /**\n * Signature authenticating the rest of the header (base64url,\n * no padding). Verifies the header wasn't tampered with in\n * transit/storage — see `with-pod/signature.ts`. Part of the\n * sig/keyId/sigAlg 3-tuple.\n */\n readonly sig?: string\n /**\n * Signature algorithm for `sig`. Named `sigAlg` (not `alg`) to\n * avoid confusion with `transferSeal.alg`. Part of the\n * sig/keyId/sigAlg 3-tuple.\n */\n readonly sigAlg?: 'ed25519'\n /**\n * Engine version range that wrote (and can read) this pod, e.g.\n * `'^0.5.0'`. Discloses only a semver range — no timestamps, no\n * identities — so a version-skew triage step (open a decade-old\n * pod → route to a version-matched read-only player instead of a\n * hard failure) or a landing page can branch before any library\n * code runs. Safe under minimum-disclosure: a range says nothing\n * about who wrote the pod or when.\n */\n readonly engineRange?: string\n /**\n * Declared unlock method(s), e.g. `['password', 'webauthn']`. Lets\n * a landing/player present the right unlock UI pre-library, and is\n * ALL a shared connection pod may disclose about its bootstrap\n * (auth method + endpoint class). Safe under minimum-disclosure: it\n * names a method family, not a credential, key, or identity.\n *\n * The member set mirrors the `@noy-db/on-*` package family\n * (`on-password`, `on-webauthn`, `on-oidc`, `on-totp`,\n * `on-email-otp`, `on-magic-link`, `on-pin`, `on-recovery`,\n * `on-shamir`) — the top-level \"which on-* package to load\" method\n * name, not the finer-grained `FactorKind` used by policy gates\n * (which splits WebAuthn into `webauthn-roaming` /\n * `webauthn-platform` for factor-proof freshness). `on-threat` is\n * excluded — it's a lockout/duress helper, not an unlock method a\n * landing page would present.\n */\n readonly unlockMethods?: readonly UnlockMethod[]\n /**\n * App-manifest presence flag. Lets a landing fork between\n * \"orphan pod → read-only browse\" and \"linked app → launch flow\"\n * without reading the body. Safe under minimum-disclosure: a\n * boolean, not the app's identity or contents.\n */\n readonly hasApp?: boolean\n /**\n * Artifact species hint for dispatcher branching, cloud tooling,\n * and the share-flow guard that warns when a data-bearing pod is\n * shared where a pointer was intended. An \"orphan\" pod is derived\n * (`species: 'full'` + `hasApp: false`), not a separate species.\n * Safe under minimum-disclosure: a coarse artifact-shape label, not\n * contents or identity.\n */\n readonly species?: 'full' | 'connection' | 'snapshot' | 'redirect' | 'group'\n /**\n * Whether the app pointer (if any) is disclosed pre-auth. Default\n * is `'private'` by product decision (recorded in #942) — absence\n * means private by convention; this field is never auto-injected,\n * only an author's explicit opt-in writes `'public'`. Safe under\n * minimum-disclosure: a disclosure-policy flag, not the pointer\n * itself.\n */\n readonly pointerMode?: 'public' | 'private'\n /**\n * Signed \"this moved, go there\" pointer (#944). Carried in the\n * PLAINTEXT header (not the encrypted body) so a dispatcher can follow\n * it pre-auth — no secret, no decompression. Structurally validated\n * here (shape only); the record's OWN signature is a separate\n * verification step (`verifyRedirect`) since a parser has no\n * `trustedKeys`. `readPodRedirect` returns this field UNVERIFIED.\n */\n readonly redirect?: Redirect\n}\n\n/**\n * Declared unlock method names — mirrors the `@noy-db/on-*` package\n * family (see `unlockMethods` doc comment on `NoydbPodHeader`).\n */\nexport type UnlockMethod =\n | 'password'\n | 'webauthn'\n | 'oidc'\n | 'totp'\n | 'email-otp'\n | 'magic-link'\n | 'pin'\n | 'recovery'\n | 'shamir'\n\n\n/**\n * Allowlist of header keys. Any key not in this set is forbidden\n * and causes `validatePodHeaderFields` to throw. Kept as a Set for\n * O(1) lookup; the validator iterates over the parsed header and\n * checks each key against this set.\n */\nconst ALLOWED_HEADER_KEYS: ReadonlySet<string> = new Set([\n 'formatVersion',\n 'handle',\n 'bodyBytes',\n 'bodySha256',\n 'publicEnvelope',\n 'autoUnlock',\n 'bundleKind',\n 'transferSeal',\n 'sig',\n 'keyId',\n 'sigAlg',\n 'engineRange',\n 'unlockMethods',\n 'hasApp',\n 'species',\n 'pointerMode',\n 'redirect',\n])\n\n/** Valid `unlockMethods` member values — see `UnlockMethod`. */\nconst UNLOCK_METHODS: ReadonlySet<string> = new Set([\n 'password',\n 'webauthn',\n 'oidc',\n 'totp',\n 'email-otp',\n 'magic-link',\n 'pin',\n 'recovery',\n 'shamir',\n])\n\n/** Valid `species` values — see `NoydbPodHeader.species`. */\nconst POD_SPECIES: ReadonlySet<string> = new Set([\n 'full',\n 'connection',\n 'snapshot',\n 'redirect',\n 'group',\n])\n\n/** Valid `redirect.reason` values — see `Redirect['reason']`. */\nconst REDIRECT_REASONS: ReadonlySet<string> = new Set([\n 'moved',\n 'release',\n 'tombstone',\n 'repoint',\n])\n\n/**\n * Validate a parsed bundle header. Throws on any deviation from\n * the minimum-disclosure schema:\n *\n * - Missing required field\n * - Wrong type for any field\n * - Any extra key not in `ALLOWED_HEADER_KEYS`\n * - Unsupported `formatVersion`\n * - Negative or non-integer `bodyBytes`\n * - Malformed `handle` (must be 26-char Crockford base32)\n * - Malformed `bodySha256` (must be 64-char lowercase hex)\n *\n * The error messages name the offending field so consumers can\n * fix the producer rather than the reader.\n */\nexport function validatePodHeaderFields(\n parsed: unknown,\n): asserts parsed is NoydbPodHeader {\n if (parsed === null || typeof parsed !== 'object') {\n throw new Error(\n `.noydb bundle header must be a JSON object, got ${parsed === null ? 'null' : typeof parsed}`,\n )\n }\n // Disallow any unknown key — minimum disclosure means we reject\n // forward-compat extension keys at the format layer; new fields\n // require a format version bump and a new validator.\n for (const key of Object.keys(parsed)) {\n if (!ALLOWED_HEADER_KEYS.has(key)) {\n throw new Error(\n `.noydb bundle header contains forbidden key \"${key}\". ` +\n `Only minimum-disclosure fields are allowed: ` +\n `${[...ALLOWED_HEADER_KEYS].join(', ')}.`,\n )\n }\n }\n const h = parsed as Record<string, unknown>\n if (\n typeof h['formatVersion'] !== 'number' ||\n (h['formatVersion'] !== NOYDB_POD_FORMAT_VERSION && h['formatVersion'] !== NOYDB_POD_FORMAT_VERSION_SIGNED)\n ) {\n throw new Error(\n `.noydb bundle header.formatVersion must be ${NOYDB_POD_FORMAT_VERSION} or ${NOYDB_POD_FORMAT_VERSION_SIGNED}, ` +\n `got ${String(h['formatVersion'])}. The reader does not support ` +\n `forward-compat versions; upgrade the reader to handle newer bundles.`,\n )\n }\n if (typeof h['handle'] !== 'string' || !/^[0-9A-HJKMNP-TV-Z]{26}$/.test(h['handle'])) {\n throw new Error(\n `.noydb bundle header.handle must be a 26-character Crockford base32 ULID, ` +\n `got ${typeof h['handle'] === 'string' ? `\"${h['handle']}\"` : String(h['handle'])}.`,\n )\n }\n if (typeof h['bodyBytes'] !== 'number' || !Number.isInteger(h['bodyBytes']) || h['bodyBytes'] < 0) {\n throw new Error(\n `.noydb bundle header.bodyBytes must be a non-negative integer, ` +\n `got ${String(h['bodyBytes'])}.`,\n )\n }\n if (typeof h['bodySha256'] !== 'string' || !/^[0-9a-f]{64}$/.test(h['bodySha256'])) {\n throw new Error(\n `.noydb bundle header.bodySha256 must be a 64-character lowercase hex string, ` +\n `got ${typeof h['bodySha256'] === 'string' ? `\"${h['bodySha256']}\"` : String(h['bodySha256'])}.`,\n )\n }\n if (h['publicEnvelope'] !== undefined) {\n const env = h['publicEnvelope']\n if (env === null || typeof env !== 'object' || Array.isArray(env)) {\n throw new Error(\n `.noydb bundle header.publicEnvelope must be a JSON object when present, got ${typeof env}.`,\n )\n }\n const e = env as Record<string, unknown>\n if (e['_noydb_public'] !== 1) {\n throw new Error(\n `.noydb bundle header.publicEnvelope._noydb_public must be 1, got ${String(e['_noydb_public'])}.`,\n )\n }\n if (typeof e['version'] !== 'number' || !Number.isInteger(e['version']) || e['version'] < 1) {\n throw new Error(\n `.noydb bundle header.publicEnvelope.version must be a positive integer, got ${String(e['version'])}.`,\n )\n }\n }\n if (h['autoUnlock'] !== undefined) {\n if (h['autoUnlock'] !== 'unsealed' && h['autoUnlock'] !== 'sealed') {\n const got = typeof h['autoUnlock'] === 'string' ? `\"${h['autoUnlock']}\"` : typeof h['autoUnlock']\n throw new Error(\n `.noydb bundle header.autoUnlock must be 'unsealed' or 'sealed' when present, got ${got}.`,\n )\n }\n }\n if (h['bundleKind'] !== undefined) {\n if (h['bundleKind'] !== 'snapshot' && h['bundleKind'] !== 'extracted-partition') {\n const got = typeof h['bundleKind'] === 'string' ? `\"${h['bundleKind']}\"` : typeof h['bundleKind']\n throw new Error(\n `.noydb bundle header.bundleKind must be 'snapshot' or 'extracted-partition' when present, got ${got}.`,\n )\n }\n }\n if (h['transferSeal'] !== undefined) {\n const ts = h['transferSeal']\n if (ts === null || typeof ts !== 'object' || Array.isArray(ts)) {\n throw new Error(`.noydb bundle header.transferSeal must be a JSON object when present, got ${typeof ts}.`)\n }\n const t = ts as Record<string, unknown>\n if (t['v'] !== 1) {\n throw new Error(`.noydb bundle header.transferSeal.v must be 1, got ${String(t['v'])}.`)\n }\n if (t['alg'] !== 'aes-256-gcm-pre-shared') {\n throw new Error(`.noydb bundle header.transferSeal.alg must be 'aes-256-gcm-pre-shared', got ${String(t['alg'])}.`)\n }\n if (typeof t['sealId'] !== 'string' || t['sealId'].length === 0) {\n throw new Error(`.noydb bundle header.transferSeal.sealId must be a non-empty string, got ${String(t['sealId'])}.`)\n }\n }\n if (h['keyId'] !== undefined) {\n if (typeof h['keyId'] !== 'string' || !/^[0-9a-f]{16}$/.test(h['keyId'])) {\n throw new Error(\n `.noydb bundle header.keyId must be a 16-character lowercase hex fingerprint, ` +\n `got ${typeof h['keyId'] === 'string' ? `\"${h['keyId']}\"` : typeof h['keyId']}.`,\n )\n }\n }\n if (h['sig'] !== undefined) {\n if (typeof h['sig'] !== 'string' || h['sig'].length === 0 || !/^[A-Za-z0-9_-]+$/.test(h['sig'])) {\n throw new Error(\n `.noydb bundle header.sig must be a non-empty base64url string, ` +\n `got ${typeof h['sig'] === 'string' ? `\"${h['sig']}\"` : typeof h['sig']}.`,\n )\n }\n }\n if (h['sigAlg'] !== undefined) {\n if (h['sigAlg'] !== 'ed25519') {\n const got = typeof h['sigAlg'] === 'string' ? `\"${h['sigAlg']}\"` : typeof h['sigAlg']\n throw new Error(`.noydb bundle header.sigAlg must be 'ed25519' when present, got ${got}.`)\n }\n }\n if (h['engineRange'] !== undefined) {\n if (typeof h['engineRange'] !== 'string' || h['engineRange'].length === 0) {\n throw new Error(\n `.noydb bundle header.engineRange must be a string when present, ` +\n `got ${typeof h['engineRange']}.`,\n )\n }\n }\n if (h['unlockMethods'] !== undefined) {\n const methods = h['unlockMethods']\n if (!Array.isArray(methods)) {\n throw new Error(\n `.noydb bundle header.unlockMethods must be an array when present, got ${typeof methods}.`,\n )\n }\n for (let i = 0; i < methods.length; i++) {\n if (!UNLOCK_METHODS.has(methods[i])) {\n throw new Error(\n `.noydb bundle header.unlockMethods[${i}] must be one of: ` +\n `${[...UNLOCK_METHODS].join(', ')}, got ${String(methods[i])}.`,\n )\n }\n }\n }\n if (h['hasApp'] !== undefined) {\n if (typeof h['hasApp'] !== 'boolean') {\n throw new Error(\n `.noydb bundle header.hasApp must be a boolean when present, got ${typeof h['hasApp']}.`,\n )\n }\n }\n if (h['species'] !== undefined) {\n if (!POD_SPECIES.has(h['species'] as string)) {\n const got = typeof h['species'] === 'string' ? `\"${h['species']}\"` : typeof h['species']\n throw new Error(\n `.noydb bundle header.species must be one of: ${[...POD_SPECIES].join(', ')}, got ${got}.`,\n )\n }\n }\n if (h['pointerMode'] !== undefined) {\n if (h['pointerMode'] !== 'public' && h['pointerMode'] !== 'private') {\n const got = typeof h['pointerMode'] === 'string' ? `\"${h['pointerMode']}\"` : typeof h['pointerMode']\n throw new Error(`.noydb bundle header.pointerMode must be 'public' or 'private' when present, got ${got}.`)\n }\n }\n if (h['redirect'] !== undefined) {\n const r = h['redirect']\n if (r === null || typeof r !== 'object' || Array.isArray(r)) {\n throw new Error(`.noydb bundle header.redirect must be a JSON object when present, got ${typeof r}.`)\n }\n const rec = r as Record<string, unknown>\n if (rec['v'] !== 1) {\n throw new Error(`.noydb bundle header.redirect.v must be 1, got ${String(rec['v'])}.`)\n }\n if (typeof rec['target'] !== 'string' || rec['target'].length === 0) {\n throw new Error(\n `.noydb bundle header.redirect.target must be a non-empty string, got ${String(rec['target'])}.`,\n )\n }\n if (!REDIRECT_REASONS.has(rec['reason'] as string)) {\n throw new Error(\n `.noydb bundle header.redirect.reason must be one of: ${[...REDIRECT_REASONS].join(', ')}, got ${String(rec['reason'])}.`,\n )\n }\n if (typeof rec['issuedBy'] !== 'string' || !/^[0-9a-f]{16}$/.test(rec['issuedBy'])) {\n throw new Error(\n `.noydb bundle header.redirect.issuedBy must be a 16-character lowercase hex fingerprint, ` +\n `got ${typeof rec['issuedBy'] === 'string' ? `\"${rec['issuedBy']}\"` : typeof rec['issuedBy']}.`,\n )\n }\n if (typeof rec['sig'] !== 'string' || rec['sig'].length === 0 || !/^[A-Za-z0-9_-]+$/.test(rec['sig'])) {\n throw new Error(\n `.noydb bundle header.redirect.sig must be a non-empty base64url string, ` +\n `got ${typeof rec['sig'] === 'string' ? `\"${rec['sig']}\"` : typeof rec['sig']}.`,\n )\n }\n }\n // Cross-field invariant: the seal indicator and the extracted-partition\n // kind imply each other. An extracted partition is unlocked via its\n // transfer seal; a seal without the kind is a malformed header.\n const isExtracted = h['bundleKind'] === 'extracted-partition'\n const hasSeal = h['transferSeal'] !== undefined\n if (hasSeal && !isExtracted) {\n throw new Error(\n `.noydb bundle header.transferSeal requires bundleKind === 'extracted-partition'.`,\n )\n }\n if (isExtracted && !hasSeal) {\n throw new Error(\n `.noydb bundle header with bundleKind === 'extracted-partition' must carry a transferSeal indicator.`,\n )\n }\n // An extracted partition's unlock path IS the transfer seal. A parallel\n // autoUnlock credential would create two unlock paths and weaken the\n // one-time-seal guarantee. Reject the combination.\n if (isExtracted && h['autoUnlock'] !== undefined) {\n throw new Error(\n `.noydb bundle header cannot carry both autoUnlock and bundleKind === 'extracted-partition' — `\n + `an extracted partition is unlocked via its transfer seal, not an auto-credential.`,\n )\n }\n // Cross-field invariant: sig/keyId/sigAlg authenticate the header as a\n // unit — a partial tuple (e.g. sig without keyId) is a malformed or\n // truncated signature, not a valid unsigned header. Signed headers also\n // require formatVersion 2 so older readers refuse them instead of\n // silently ignoring the signature.\n const sigFieldsPresent = [h['sig'], h['keyId'], h['sigAlg']].filter((v) => v !== undefined).length\n if (sigFieldsPresent > 0 && sigFieldsPresent < 3) {\n throw new Error(\n `.noydb bundle header.sig, .keyId, and .sigAlg must be present together or not at all ` +\n `(got ${sigFieldsPresent} of 3).`,\n )\n }\n if (sigFieldsPresent === 3 && h['formatVersion'] !== NOYDB_POD_FORMAT_VERSION_SIGNED) {\n throw new Error(\n `.noydb bundle header with sig/keyId/sigAlg must have formatVersion === ${NOYDB_POD_FORMAT_VERSION_SIGNED}, ` +\n `got ${String(h['formatVersion'])}.`,\n )\n }\n}\n\n/**\n * Encode a header object to UTF-8 JSON bytes after validating\n * minimum disclosure. Used by the writer to serialize the header\n * region of the container.\n */\nexport function encodePodHeader(header: NoydbPodHeader): Uint8Array {\n validatePodHeaderFields(header)\n // Stable key ordering — JSON.stringify with no replacer uses\n // insertion order, which is fine here because we control the\n // object construction. Stable ordering means two bundles with\n // identical contents produce byte-identical headers.\n const json = JSON.stringify({\n formatVersion: header.formatVersion,\n handle: header.handle,\n bodyBytes: header.bodyBytes,\n bodySha256: header.bodySha256,\n ...(header.publicEnvelope !== undefined ? { publicEnvelope: header.publicEnvelope } : {}),\n ...(header.autoUnlock !== undefined ? { autoUnlock: header.autoUnlock } : {}),\n ...(header.bundleKind !== undefined ? { bundleKind: header.bundleKind } : {}),\n ...(header.transferSeal !== undefined ? { transferSeal: header.transferSeal } : {}),\n // Encode order here is the WIRE-byte contract only — it does NOT\n // affect the signature. The signer (Task 4/5) signs the header\n // object via canonicalJson, which re-sorts keys independent of\n // this insertion order.\n ...(header.sig !== undefined ? { sig: header.sig } : {}),\n ...(header.keyId !== undefined ? { keyId: header.keyId } : {}),\n ...(header.sigAlg !== undefined ? { sigAlg: header.sigAlg } : {}),\n ...(header.engineRange !== undefined ? { engineRange: header.engineRange } : {}),\n ...(header.unlockMethods !== undefined ? { unlockMethods: header.unlockMethods } : {}),\n ...(header.hasApp !== undefined ? { hasApp: header.hasApp } : {}),\n ...(header.species !== undefined ? { species: header.species } : {}),\n ...(header.pointerMode !== undefined ? { pointerMode: header.pointerMode } : {}),\n ...(header.redirect !== undefined ? { redirect: header.redirect } : {}),\n })\n return new TextEncoder().encode(json)\n}\n\n/**\n * Parse a bundle header from its UTF-8 JSON bytes. Throws on\n * invalid JSON or any minimum-disclosure violation.\n */\nexport function decodePodHeader(bytes: Uint8Array): NoydbPodHeader {\n const json = new TextDecoder('utf-8', { fatal: true }).decode(bytes)\n let parsed: unknown\n try {\n parsed = JSON.parse(json)\n } catch (err) {\n throw new Error(\n `.noydb bundle header is not valid JSON: ${(err as Error).message}`,\n )\n }\n validatePodHeaderFields(parsed)\n return parsed\n}\n\n/**\n * Read a uint32 from `bytes` at `offset` in big-endian byte order.\n * No bounds check — callers must guarantee `offset + 4 <= bytes.length`.\n * Used to decode the header length field; kept inline so the parser\n * doesn't depend on DataView allocation per call.\n */\nexport function readUint32BE(bytes: Uint8Array, offset: number): number {\n return (\n (bytes[offset]! << 24 >>> 0) +\n (bytes[offset + 1]! << 16) +\n (bytes[offset + 2]! << 8) +\n bytes[offset + 3]!\n )\n}\n\n/**\n * Write a uint32 to `bytes` at `offset` in big-endian byte order.\n * No bounds check — callers must guarantee `offset + 4 <= bytes.length`.\n */\nexport function writeUint32BE(bytes: Uint8Array, offset: number, value: number): void {\n bytes[offset] = (value >>> 24) & 0xff\n bytes[offset + 1] = (value >>> 16) & 0xff\n bytes[offset + 2] = (value >>> 8) & 0xff\n bytes[offset + 3] = value & 0xff\n}\n\n/**\n * Verify the magic prefix of a bundle. Returns true if the first\n * 4 bytes match `NDB1`. Used by readers as a fast file-type check\n * before any further parsing.\n */\nexport function hasNoydbPodMagic(bytes: Uint8Array): boolean {\n if (bytes.length < NOYDB_POD_MAGIC.length) return false\n for (let i = 0; i < NOYDB_POD_MAGIC.length; i++) {\n if (bytes[i] !== NOYDB_POD_MAGIC[i]) return false\n }\n return true\n}\n","/**\n * The ONE signing convention for the noy-db family — pod header, the\n * Redirect record (#944), and manifest writes (#941) all sign through\n * this module rather than inventing their own scheme.\n *\n * Convention: `canonicalJson(payload minus sig)` → `utf8` → Ed25519, over\n * the published `@noy-db/attestation` primitives. The caller is\n * responsible for excluding the `sig` field from `payload` before\n * signing/verifying — this module never strips it for you, so a payload\n * that still carries a stray field (or `undefined`) fails loudly via\n * `canonicalJson` rather than silently signing the wrong bytes.\n *\n * No pod/vault imports here — this is a family-wide primitive.\n */\nimport { canonicalJson, ed25519Sign, ed25519Verify, utf8 } from '@noy-db/attestation'\n\nexport const POD_SIG_ALG = 'ed25519' as const\n\n/** The exact bytes a signature covers: utf8(canonicalJson(payload)). Exported for cross-checking. */\nexport function signedBytes(payload: Record<string, unknown>): Uint8Array {\n return utf8(canonicalJson(payload))\n}\n\n/**\n * Sign an arbitrary canonical record. `payload` MUST already exclude any\n * `sig` field.\n */\nexport async function signRecord(privateKeyPkcs8B64: string, payload: Record<string, unknown>): Promise<string> {\n return ed25519Sign(privateKeyPkcs8B64, signedBytes(payload))\n}\n\n/**\n * Verify. `payload` is the record WITHOUT `sig`. Fails closed (false) on\n * any malformed input.\n */\nexport async function verifyRecord(publicKeyB64: string, sig: string, payload: Record<string, unknown>): Promise<boolean> {\n return ed25519Verify(publicKeyB64, sig, signedBytes(payload))\n}\n","/**\n * `.noydb` container primitives — write, read, header-only read.\n *\n *. Wraps a `vault.dump()` JSON string in the\n * binary container described in `format.ts`.\n *\n * **Three primitives:**\n *\n * - `writePod(vault, opts?)` — produces the\n * full container bytes ready to write to disk or upload\n * - `readPodHeader(bytes)` — parses just the header\n * without decompressing the body, fast file-type and\n * metadata read for cloud listing UIs\n * - `readPod(bytes)` — full read: validates magic,\n * header, integrity hash, and decompresses the body to\n * return the original `dump()` JSON string for use with\n * `vault.load()`\n *\n * **Compression strategy:** brotli when available (Node 22+,\n * Chrome 124+, Firefox 122+), gzip fallback elsewhere. The\n * algorithm choice is encoded in the format byte at offset 5,\n * so readers handle either transparently. Brotli wins ~30-50%\n * on JSON payloads with repeated keys (which vault dumps\n * are).\n *\n * **Why split read/load?** `readPod` returns the\n * *unwrapped JSON string*, not a Vault object. The caller\n * is responsible for piping that JSON into\n * `vault.load(json, secret)`. Splitting the layers\n * keeps the bundle module free of any crypto/secret\n * concerns — it's purely a format layer. The same `readPod`\n * call can also feed verification tools, format inspectors, or\n * archive utilities that don't care about decryption.\n */\n\nimport {\n COMPRESSION_BROTLI,\n COMPRESSION_GZIP,\n COMPRESSION_NONE,\n FLAG_COMPRESSED,\n FLAG_HAS_INTEGRITY_HASH,\n NOYDB_POD_FORMAT_VERSION,\n NOYDB_POD_FORMAT_VERSION_SIGNED,\n NOYDB_POD_MAGIC,\n NOYDB_POD_PREFIX_BYTES,\n decodePodHeader,\n encodePodHeader,\n hasNoydbPodMagic,\n readUint32BE,\n writeUint32BE,\n type CompressionAlgo,\n type NoydbPodHeader,\n type UnlockMethod,\n} from './format.js'\nimport { signRecord, verifyRecord } from './signature.js'\nimport type { Redirect } from './redirect.js'\nimport type { DocSigner } from '../with-audit/attestation/signer.js'\nimport { sha256Hex as sha256HexBytes } from '../kernel/enclave/index.js'\nimport { PodIntegrityError, PodSealMismatchError, ValidationError } from '../kernel/errors.js'\nimport type { Vault } from '../kernel/vault.js'\nimport type { PodRecipient } from '../with-party/team/keyring.js'\nimport { pickLocale } from '../with-party/directory/cover/storage.js'\nimport type { Cover } from '../with-party/directory/cover/types.js'\nimport type { SealingKeyProvider, RecipientSealer, RecipientHint } from '../with-party/team/managed-secret.js'\n\n// ─── Auto-credential types ────────────────────────────────────────────────────\n\n/**\n * The credential kinds that can be bundled for auto-unlock.\n * WebAuthn is intentionally excluded — it is hardware-bound and\n * cannot be embedded as a portable credential.\n */\nexport type AutoCredentialKind = 'secret' | 'password' | 'pin'\n\n/**\n * A typed credential for auto-unlock. Carries the credential `kind`\n * alongside the plaintext `value`, so consumers can dispatch the\n * correct login/prefill path rather than treating all credentials\n * as secrets.\n *\n * `bundle.ts` is a pure format layer — it carries the credential\n * without interpreting it. The consumer is responsible for\n * dispatching on `kind`.\n */\nexport interface AutoCredential {\n readonly kind: AutoCredentialKind\n readonly value: string\n}\n\n/**\n * Options accepted by `writePod`.\n *\n * - `compression: 'auto'` (default) — try brotli, fall back to gzip\n * - `compression: 'brotli'` — force brotli, throw if unsupported\n * - `compression: 'gzip'` — force gzip\n * - `compression: 'none'` — no compression (round-trip testing only)\n *\n * **Slice filtering:**\n * - `collections` — allowlist of collection names to include. Internal\n * collections (keyrings, ledger) and excluded user collections are\n * dropped from the bundle. Records inside included collections are\n * carried through verbatim.\n * - `since` — only records whose envelope `_ts` is on/after the given\n * instant survive. Operates on the unencrypted envelope timestamp,\n * so plaintext access to records is not required.\n *\n * Both filters intersect (AND). When neither is provided the bundle is\n * a whole-vault snapshot, identical to today's behaviour.\n */\nexport interface WritePodOptions {\n readonly compression?: 'auto' | 'brotli' | 'gzip' | 'none'\n /** Allowlist of user-collection names to include. */\n readonly collections?: readonly string[]\n /**\n * Drop records whose envelope `_ts` is strictly older than this\n * instant. Accepts a `Date` or any ISO-8601 string parseable by\n * `new Date()`.\n */\n readonly since?: Date | string\n /**\n * Plaintext-pipeline record predicate. Decrypts each record\n * with the vault's per-collection DEK, runs the predicate, and\n * keeps the original ciphertext for survivors (no re-encrypt —\n * preserves zero-knowledge cleanly). Records the predicate returns\n * `false` for are dropped from the bundle.\n *\n * Async predicates are supported. Mutating the record from inside\n * the predicate is undefined behaviour.\n */\n readonly where?: (\n record: unknown,\n ctx: { collection: string; id: string },\n ) => boolean | Promise<boolean>\n /**\n * Hierarchical-tier ceiling. Records whose envelope `_tier`\n * is strictly greater than this number are dropped. Operates on the\n * envelope `_tier` (no decryption needed) — vault.exportStream is\n * referenced in the issue body for symmetry, but the tier value\n * lives on the unencrypted envelope. Vault without tiers is a no-op.\n */\n readonly tierAtMost?: number\n /**\n * Single-recipient re-keying shorthand. When set, the\n * bundle's keyring is replaced with one freshly-derived entry sealed\n * with this secret. The recipient inherits the source keyring's\n * userId, role, and permissions. Mutually exclusive with `recipients`.\n */\n readonly exportSecret?: string\n /**\n * Multi-recipient re-keying. Replaces the bundle's keyring\n * map with one slot per recipient, each sealed with its own\n * secret. DEKs are unwrapped from the source keyring once and\n * re-wrapped per recipient — record ciphertext is unchanged.\n *\n * Mutually exclusive with `exportSecret`. When neither is set,\n * the bundle inherits the source keyring as-is (today's behaviour,\n * suited to personal backup-and-restore).\n */\n readonly recipients?: readonly PodRecipient[]\n /**\n * Auto-unlock — unsealed per-user credentials.\n *\n * Generalises `autoSecrets` to support any bundleable credential\n * kind (`secret` | `password` | `pin`).\n *\n * Public-by-design: anyone holding the bundle bytes can read these\n * plaintext credentials. Use for demo data, sample vaults,\n * prospect onboarding.\n *\n * The `policy: 'public-by-design'` discriminant is mandatory. A\n * bare `{ perUser }` without it is rejected at write time — the\n * safety net against a careless call against a production vault.\n *\n * Mutually exclusive with `sealedCredentials`, `autoSecrets`,\n * and `sealedSecrets`.\n */\n readonly autoCredentials?: {\n readonly policy: 'public-by-design'\n readonly perUser: Record<string, AutoCredential>\n }\n /**\n * Auto-unlock — per-user credentials sealed under a\n * {@link SealingKeyProvider}.\n *\n * Generalises `sealedSecrets` to support any bundleable\n * credential kind (`secret` | `password` | `pin`).\n *\n * The hub seals each user's plaintext credential under `provider`\n * and embeds the resulting sealed envelopes in the bundle. The\n * recipient must hold a provider with a matching `pid` (i.e.,\n * `provider.id`) to auto-unseal on import.\n *\n * `mode: 'self-target'` — sender and recipient share the same\n * provider identity (same iCloud Keychain entry, same\n * MDM-provisioned bundle id, same KMS account, etc.).\n *\n * `mode: 'recipient-target'` — asymmetric sealing via a\n * {@link RecipientSealer}. Each user entry carries a\n * `credential` and a `hint` (the recipient's public material).\n * The bundle can only be unsealed by the holder of the matching\n * private key.\n *\n * Mutually exclusive with `autoCredentials`, `autoSecrets`,\n * and `sealedSecrets`.\n */\n readonly sealedCredentials?:\n | {\n readonly mode: 'self-target'\n readonly provider: SealingKeyProvider\n readonly perUser: Record<string, AutoCredential>\n }\n | {\n readonly mode: 'recipient-target'\n readonly provider: RecipientSealer\n readonly perUser: Record<string, { readonly credential: AutoCredential; readonly hint: RecipientHint }>\n }\n /**\n * @deprecated Use `autoCredentials` instead.\n *\n * Auto-unlock — unsealed per-user secrets.\n *\n * Public-by-design: anyone holding the bundle bytes can read these\n * plaintext credentials. Use for demo data, sample vaults,\n * prospect onboarding.\n *\n * The `policy: 'public-by-design'` discriminant is mandatory. A\n * bare `{ perUser }` without it is rejected at write time — the\n * safety net against a careless call against a production vault.\n *\n * Mutually exclusive with `autoCredentials`, `sealedCredentials`,\n * and `sealedSecrets`.\n */\n readonly autoSecrets?: {\n readonly policy: 'public-by-design'\n readonly perUser: Record<string, string>\n }\n /**\n * @deprecated Use `sealedCredentials` instead.\n *\n * Auto-unlock — per-user secrets sealed under a\n * {@link SealingKeyProvider} (self-target only).\n *\n * The hub seals each user's plaintext secret under `provider`\n * and embeds the resulting sealed envelopes in the bundle. The\n * recipient must hold a provider with a matching `pid` (i.e.,\n * `provider.id`) to auto-unseal on import.\n *\n * `mode: 'self-target'` is the only mode for `sealedSecrets` — sender\n * and recipient share the same provider identity (same iCloud Keychain\n * entry, same MDM-provisioned bundle id, same KMS account, etc.).\n * For recipient-target sealing via the `RecipientSealer` interface,\n * use `sealedCredentials` with `mode: 'recipient-target'` (§11.4).\n *\n * Mutually exclusive with `autoCredentials`, `sealedCredentials`,\n * and `autoSecrets`.\n */\n readonly sealedSecrets?: {\n readonly mode: 'self-target'\n readonly provider: SealingKeyProvider\n readonly perUser: Record<string, string>\n }\n /**\n * Pod-header signing control (#943).\n *\n * - omitted (default) — sign the header iff the source vault has a\n * persisted document signer (`vault._loadPodSigner()` returns\n * non-null). A vault that never minted a signer produces an\n * unsigned `formatVersion: 1` header, exactly as before.\n * - `false` — never sign, even if a signer is persisted.\n * - an explicit {@link DocSigner} — sign with the supplied keypair\n * without touching the vault's persisted signer (test / advanced\n * injection). Does not mint or persist anything.\n *\n * Signing NEVER mints a signer as a side effect of export: an absent\n * signer means an unsigned pod, not an on-the-fly key generation.\n */\n readonly sign?: false | DocSigner\n /**\n * Header L2 fields (#942) — pre-auth dispatch metadata written verbatim\n * into the pod header. See `NoydbPodHeader` for the disclosure rationale\n * of each. All optional; absence produces a legacy-shaped header exactly\n * as before.\n */\n readonly engineRange?: string\n readonly unlockMethods?: readonly UnlockMethod[]\n readonly hasApp?: boolean\n readonly species?: 'full' | 'connection' | 'snapshot' | 'redirect' | 'group'\n readonly pointerMode?: 'public' | 'private'\n /**\n * Signed \"this moved, go there\" pointer (#944), written verbatim into\n * the plaintext header. Pass an already-signed {@link Redirect}\n * (mint one via `signRedirect`) — `writePod` does not sign it for you.\n */\n readonly redirect?: Redirect\n}\n\n\n/**\n * Every key `writePod` reads, in declaration order (#991).\n *\n * A pod is a wire artifact, so an option this list doesn't name is refused\n * rather than ignored: a dropped write option produces a structurally valid\n * bundle that is missing something, and the defect surfaces later — in\n * whoever imports it — with nothing left to trace it back to.\n *\n * `bundle-option-keys.test.ts` parses `WritePodOptions` out of this file and\n * fails if the two ever drift, so adding an option is enough; you do not have\n * to remember to update this list, only to keep the interface shape parseable.\n *\n * @internal\n */\nexport const WRITE_POD_OPTION_KEYS = [\n 'compression',\n 'collections',\n 'since',\n 'where',\n 'tierAtMost',\n 'exportSecret',\n 'recipients',\n 'autoCredentials',\n 'sealedCredentials',\n 'autoSecrets',\n 'sealedSecrets',\n 'sign',\n 'engineRange',\n 'unlockMethods',\n 'hasApp',\n 'species',\n 'pointerMode',\n 'redirect',\n] as const satisfies readonly (keyof WritePodOptions)[]\n\n/**\n * Write options that were renamed away, mapped to what replaced them.\n *\n * These get a better message than a bare unknown key: `autoPassphrases` →\n * `autoSecrets` (§3) → `autoCredentials` (#215) is two hops, and a caller\n * arriving from `0.3.0` has no way to guess the far end.\n */\nconst RETIRED_WRITE_POD_OPTIONS: Readonly<Record<string, string>> = {\n autoPassphrases: 'autoCredentials',\n sealedPassphrases: 'sealedCredentials',\n exportPassphrase: 'exportSecret',\n}\n\n/**\n * Refuse any option key `writePod` does not read.\n *\n * Keys explicitly set to `undefined` pass — spreading a partially-built\n * options object is a normal call shape and carries no intent.\n */\nfunction assertKnownWritePodOptions(opts: WritePodOptions): void {\n const known = new Set<string>(WRITE_POD_OPTION_KEYS)\n for (const [key, value] of Object.entries(opts)) {\n if (value === undefined || known.has(key)) continue\n const replacement = RETIRED_WRITE_POD_OPTIONS[key]\n throw new Error(\n replacement !== undefined\n ? `writePod: \\`${key}\\` was renamed to \\`${replacement}\\`. `\n + 'Passing the old key would have written a pod without that '\n + 'slot — see the 0.4.0-pre migration note.'\n : `writePod: unknown option \\`${key}\\`. Options are not ignored — a `\n + 'dropped write option produces a pod that is silently missing '\n + `something. Known keys: ${WRITE_POD_OPTION_KEYS.join(', ')}.`,\n )\n }\n}\n\n/**\n * Result returned by `readPod`. The caller is expected to\n * pass `dumpJson` into `vault.load(json, secret)` to\n * actually restore a vault. Splitting the layers keeps the\n * bundle module free of crypto concerns — see file-level docs.\n */\nexport interface PodReadResult {\n readonly header: NoydbPodHeader\n readonly dumpJson: string\n /**\n * Auto-unlock material. Present only when\n * the header's `autoUnlock` flag is set AND the body's wrapped\n * structure survived parsing. Values are typed credentials — either\n * delivered plain (`kind: 'unsealed'`) or unsealed at read time\n * using one of the supplied `sealingProviders` (`kind: 'sealed'`).\n *\n * Consumers dispatch on `cred.kind` to choose the correct login /\n * prefill path. Pre-0.2 bundles (bare string entries) are coerced\n * to `{ kind: 'secret', value }` on read for back-compat.\n *\n * For `kind: 'sealed'` bundles read without `sealingProviders`, the\n * `value` field is the raw base64 sealed bytes — opaque to the\n * consumer until unsealed elsewhere.\n */\n readonly autoUnlock?: {\n readonly kind: 'unsealed' | 'sealed'\n readonly perUser: Record<string, AutoCredential>\n }\n}\n\n/**\n * Sealed credential entry as it appears in the bundle body's\n * `_autoUnlock.perUser` map when the bundle was written with\n * `sealedCredentials` (or the deprecated `sealedSecrets`).\n * Provider's sealed output is base64-encoded; the `pid` is the\n * dispatch key matched against recipient-supplied\n * `SealingKeyProvider.id`. The `kind` carries the plaintext-tier\n * metadata so the consumer can dispatch on credential type without\n * unsealing first.\n *\n * Back-compat: `kind` is absent in older bundles — readers must\n * default to `'secret'` when not present.\n */\ninterface SealedAutoUnlockEntry {\n readonly pid: string\n readonly sealed: string\n readonly alg: 'aes-256-gcm'\n readonly kind?: AutoCredentialKind\n /**\n * Recipient-target only: the RecipientHint the sender used to seal.\n * Carried for recipient verifiability (\"yes this was sealed against\n * my published hint\"). Self-target entries omit it. Pre-0.2 readers\n * ignore unknown fields, so this is back-compatible.\n */\n readonly hint?: RecipientHint\n}\n\n/**\n * Discriminated wrapper carried in the bundle body when the header's\n * `autoUnlock` flag is set. Without the flag, the body is the raw\n * `vault.dump()` JSON string.\n *\n * Back-compat: older bundles carry bare `string` values in the\n * unsealed `perUser` map. Readers must coerce those to\n * `{ kind: 'secret', value }`.\n */\ninterface AutoUnlockBody {\n readonly _noydb_bundle_body: 1\n readonly dump: string\n readonly _autoUnlock:\n | { readonly kind: 'unsealed'; readonly perUser: Record<string, AutoCredential | string> }\n | { readonly kind: 'sealed'; readonly perUser: Record<string, SealedAutoUnlockEntry> }\n}\n\n/**\n * Options accepted by {@link readPod} for the\n * auto-unlock paths. Without these the reader behaves exactly as before\n * (header parsed; body returned as `dumpJson`).\n */\nexport interface ReadPodOptions {\n /**\n * Recipient-side sealing providers used to unseal entries from\n * `sealedSecrets`. The reader picks the one whose `.id`\n * matches each entry's `pid`. Multiple providers may be supplied\n * (different users may seal under different identities).\n *\n * When unset and the bundle carries sealed envelopes, the\n * `autoUnlock.perUser` map remains the SEALED entries unmodified\n * — callers can inspect them or unseal elsewhere.\n */\n readonly sealingProviders?: readonly SealingKeyProvider[]\n /**\n * Opt-in trial mode for unsealing — when an entry's `pid` doesn't\n * match a registered provider, try each provider whose alg\n * matches. Default `false` (strict-pid dispatch per foundation\n * §11.9.2). Surfaces extra credential prompts; use deliberately.\n */\n readonly attemptUnsealAcrossProviders?: boolean\n}\n\n// ─── Auto-unlock helpers ──────────────────────────────────────────────────────\n\n/**\n * Internal normalized form of the auto-unlock options, computed once\n * from the four public-facing fields (autoCredentials, sealedCredentials,\n * autoSecrets, sealedSecrets). Callers work against this shape\n * so the build + validate paths share a single normalizer.\n */\ninterface NormalizedAutoUnlock {\n readonly mode: 'unsealed' | 'sealed-self' | 'sealed-recipient'\n readonly provider?: SealingKeyProvider | RecipientSealer\n readonly perUser: Record<string, AutoCredential>\n /** Present only for `sealed-recipient`. Same key set as `perUser`. */\n readonly hints?: Record<string, RecipientHint>\n}\n\n/**\n * Coerce a `Record<string, string>` (legacy secret-only map) into\n * a `Record<string, AutoCredential>` by tagging each entry as\n * `kind: 'secret'`. Used by the normalizer to promote the deprecated\n * `autoSecrets`/`sealedSecrets` sugar.\n */\nfunction toAutoCredentials(m: Record<string, string>): Record<string, AutoCredential> {\n return Object.fromEntries(\n Object.entries(m).map(([u, value]) => [u, { kind: 'secret' as const, value }]),\n )\n}\n\n/**\n * Normalize the four auto-unlock option fields into a single\n * `NormalizedAutoUnlock` (or `null` when none is set). Enforces mutual\n * exclusion — exactly one of the four may be present. Promotes the\n * deprecated sugar fields to `AutoCredential` shape.\n *\n * Does NOT validate field-level constraints (policy marker, perUser\n * length, mode, provider presence, kind allowlist) — those are checked\n * in `validateAutoUnlockOptions` after normalization.\n */\nfunction normalizeAutoUnlock(opts: WritePodOptions): NormalizedAutoUnlock | null {\n const set = [\n opts.autoCredentials,\n opts.sealedCredentials,\n opts.autoSecrets,\n opts.sealedSecrets,\n ].filter(v => v !== undefined).length\n if (set === 0) return null\n if (set > 1) {\n throw new ValidationError(\n 'writePod: only one of autoCredentials / sealedCredentials / '\n + 'autoSecrets / sealedSecrets may be set.',\n )\n }\n if (opts.autoCredentials !== undefined) {\n return { mode: 'unsealed', perUser: opts.autoCredentials.perUser }\n }\n if (opts.autoSecrets !== undefined) {\n return { mode: 'unsealed', perUser: toAutoCredentials(opts.autoSecrets.perUser) }\n }\n if (opts.sealedCredentials !== undefined) {\n if (opts.sealedCredentials.mode === 'recipient-target') {\n const perUser: Record<string, AutoCredential> = {}\n const hints: Record<string, RecipientHint> = {}\n for (const [userId, entry] of Object.entries(opts.sealedCredentials.perUser)) {\n perUser[userId] = entry.credential\n hints[userId] = entry.hint\n }\n return { mode: 'sealed-recipient', provider: opts.sealedCredentials.provider, perUser, hints }\n }\n return { mode: 'sealed-self', provider: opts.sealedCredentials.provider, perUser: opts.sealedCredentials.perUser }\n }\n // sealedSecrets — only remaining option\n return {\n mode: 'sealed-self',\n provider: opts.sealedSecrets!.provider,\n perUser: toAutoCredentials(opts.sealedSecrets!.perUser),\n }\n}\n\n/**\n * Validate the auto-unlock options and return the resulting header\n * `autoUnlock` value (or null when no auto-unlock requested).\n *\n * Takes the pre-computed `NormalizedAutoUnlock` so the caller (i.e.\n * `writePod`) can pass the same object to `buildAutoUnlockWrapper`\n * without a second `normalizeAutoUnlock` call.\n *\n * Validation per spec (§3):\n * - (mutual exclusion already enforced by normalizeAutoUnlock)\n * - unsealed path: `policy: 'public-by-design'` marker required\n * - non-empty `perUser` maps\n * - sealed path: provider present; both `mode: 'self-target'` and `mode: 'recipient-target'` accepted; recipient-target requires a `RecipientSealer` provider and per-user `hint` (§11.4)\n * - every AutoCredential.kind ∈ {secret, password, pin}\n * (WebAuthn is hardware-bound and cannot be bundled)\n *\n * Throws {@link ValidationError} on any violation.\n */\nfunction validateAutoUnlockOptions(\n opts: WritePodOptions,\n normalized: NormalizedAutoUnlock | null,\n): 'unsealed' | 'sealed' | null {\n if (normalized === null) return null\n\n const VALID_KINDS: ReadonlySet<string> = new Set(['secret', 'password', 'pin'])\n\n // Validate every credential kind before any further checks.\n for (const [userId, cred] of Object.entries(normalized.perUser)) {\n if (!VALID_KINDS.has(cred.kind)) {\n throw new ValidationError(\n `writePod: credential for user '${userId}' has unsupported kind '${cred.kind}'. `\n + 'auto-unlock supports secret/password/pin only; WebAuthn is hardware-bound '\n + 'and cannot be bundled.',\n )\n }\n }\n\n if (normalized.mode === 'unsealed') {\n // Read the policy marker from whichever active option carries it.\n const policy = opts.autoCredentials?.policy ?? opts.autoSecrets?.policy\n if (policy !== 'public-by-design') {\n throw new ValidationError(\n 'writePod: `autoCredentials` (or `autoSecrets`) requires '\n + '`policy: \"public-by-design\"`. '\n + 'This is an explicit opt-in marker — bundling plaintext credentials is '\n + 'safe only when those credentials are intended to be public (demo data, '\n + 'sample vaults). For production credentials, use `sealedCredentials` instead.',\n )\n }\n const userCount = Object.keys(normalized.perUser).length\n if (userCount === 0) {\n throw new ValidationError(\n 'writePod: `autoCredentials.perUser` (or `autoSecrets.perUser`) '\n + 'must have at least one entry.',\n )\n }\n return 'unsealed'\n }\n\n // Sealed path — branch on mode.\n if (normalized.mode === 'sealed-recipient') {\n const provider = normalized.provider\n if (provider === undefined || typeof (provider as RecipientSealer).publishRecipientHint !== 'function'\n || typeof (provider as RecipientSealer).sealForRecipient !== 'function') {\n throw new ValidationError(\n 'writePod: `sealedCredentials.provider` for mode \\'recipient-target\\' must be a '\n + 'RecipientSealer (publishRecipientHint + sealForRecipient). Self-only providers '\n + '(MemorySealingKeyProvider, at-macos-keychain, etc.) do not satisfy this contract.',\n )\n }\n const hints = normalized.hints\n if (hints === undefined) {\n throw new Error('unreachable — sealed-recipient normalization must populate hints')\n }\n for (const userId of Object.keys(normalized.perUser)) {\n const hint = hints[userId]\n if (hint === undefined) {\n throw new ValidationError(\n `writePod: \\`sealedCredentials.perUser['${userId}']\\` missing required \\`hint\\` for mode 'recipient-target'.`,\n )\n }\n if (hint.v !== 1) {\n throw new ValidationError(\n `writePod: \\`sealedCredentials.perUser['${userId}'].hint.v\\` must be 1 (got ${String(hint.v)}).`,\n )\n }\n if (typeof hint.pid !== 'string' || hint.pid.length === 0) {\n throw new ValidationError(\n `writePod: \\`sealedCredentials.perUser['${userId}'].hint.pid\\` must be a non-empty string identifying the recipient.`,\n )\n }\n if (hint.alg !== 'rsa-oaep-sha256') {\n throw new ValidationError(\n `writePod: \\`sealedCredentials.perUser['${userId}'].hint.alg\\` must be 'rsa-oaep-sha256' in slice 1 (got '${String(hint.alg)}').`,\n )\n }\n // Note: hint.pid identifies the recipient, not the sender — no pid===sender.id check here.\n // The sender holds a RecipientSealer that calls sealForRecipient(plaintext, hint);\n // the hint's pid is the dispatch key on the reader side (matched against recipient providers).\n }\n const userCount = Object.keys(normalized.perUser).length\n if (userCount === 0) {\n throw new ValidationError(\n 'writePod: `sealedCredentials.perUser` must have at least one entry.',\n )\n }\n return 'sealed'\n }\n\n // mode === 'sealed-self'\n const selfTargetMode = opts.sealedCredentials?.mode ?? opts.sealedSecrets?.mode\n if (selfTargetMode !== 'self-target') {\n throw new ValidationError(\n `writePod: \\`sealedCredentials.mode\\` (or \\`sealedSecrets.mode\\`) must be `\n + `'self-target' or 'recipient-target' (got '${String(selfTargetMode)}').`,\n )\n }\n if (normalized.provider === undefined) {\n throw new ValidationError(\n 'writePod: `sealedCredentials.provider` (or `sealedSecrets.provider`) '\n + 'is required (a `SealingKeyProvider`).',\n )\n }\n const userCount = Object.keys(normalized.perUser).length\n if (userCount === 0) {\n throw new ValidationError(\n 'writePod: `sealedCredentials.perUser` (or `sealedSecrets.perUser`) '\n + 'must have at least one entry.',\n )\n }\n return 'sealed'\n}\n\n/**\n * Build the body wrapper carrying the dump + `_autoUnlock` blob.\n * Takes the pre-computed `NormalizedAutoUnlock` so both validate and\n * build work off the same normalized form (no double-normalize).\n */\nasync function buildAutoUnlockWrapper(\n dumpJson: string,\n normalized: NormalizedAutoUnlock,\n): Promise<AutoUnlockBody> {\n if (normalized.mode === 'unsealed') {\n return {\n _noydb_bundle_body: 1,\n dump: dumpJson,\n _autoUnlock: {\n kind: 'unsealed',\n perUser: { ...normalized.perUser },\n },\n }\n }\n // Sealed path — branch on mode.\n const provider = normalized.provider\n if (provider === undefined) {\n throw new Error('unreachable — validation should have caught this')\n }\n const sealedPerUser: Record<string, SealedAutoUnlockEntry> = {}\n const encoder = new TextEncoder()\n\n if (normalized.mode === 'sealed-recipient') {\n const recipientSealer = provider as RecipientSealer\n const hints = normalized.hints\n if (hints === undefined) {\n throw new Error('unreachable — sealed-recipient normalization must populate hints')\n }\n for (const [userId, cred] of Object.entries(normalized.perUser)) {\n const hint = hints[userId]!\n const sealed = await recipientSealer.sealForRecipient(encoder.encode(cred.value), hint)\n sealedPerUser[userId] = {\n pid: hint.pid, // use the recipient's pid, not the sender's\n sealed: bytesToBase64(sealed),\n alg: 'aes-256-gcm',\n kind: cred.kind,\n hint,\n }\n }\n } else {\n // mode === 'sealed-self'\n const selfSealer = provider as SealingKeyProvider\n for (const [userId, cred] of Object.entries(normalized.perUser)) {\n const sealed = await selfSealer.seal(encoder.encode(cred.value))\n sealedPerUser[userId] = {\n pid: selfSealer.id,\n sealed: bytesToBase64(sealed),\n alg: 'aes-256-gcm',\n kind: cred.kind,\n }\n }\n }\n\n return {\n _noydb_bundle_body: 1,\n dump: dumpJson,\n _autoUnlock: { kind: 'sealed', perUser: sealedPerUser },\n }\n}\n\n/**\n * Parse the body bytes when the header signaled an auto-unlock.\n * Returns the inner `dump` JSON string + the `_autoUnlock` blob;\n * throws if the wrapper structure is malformed.\n */\nfunction parseAutoUnlockBody(bodyString: string): { dump: string; blob: AutoUnlockBody['_autoUnlock'] } {\n let parsed: unknown\n try {\n parsed = JSON.parse(bodyString)\n } catch (err) {\n throw new PodIntegrityError(\n 'header declared autoUnlock but body could not be parsed as JSON wrapper: '\n + (err instanceof Error ? err.message : String(err)),\n )\n }\n if (typeof parsed !== 'object' || parsed === null) {\n throw new PodIntegrityError('autoUnlock body is not a JSON object')\n }\n const obj = parsed as Record<string, unknown>\n if (obj['_noydb_bundle_body'] !== 1) {\n throw new PodIntegrityError(\n 'autoUnlock body missing `_noydb_bundle_body: 1` discriminator',\n )\n }\n if (typeof obj['dump'] !== 'string') {\n throw new PodIntegrityError('autoUnlock body must carry a string `dump` field')\n }\n const blob = obj['_autoUnlock']\n if (typeof blob !== 'object' || blob === null) {\n throw new PodIntegrityError('autoUnlock body missing `_autoUnlock` blob')\n }\n const blobObj = blob as Record<string, unknown>\n const kind = blobObj['kind']\n if (kind !== 'unsealed' && kind !== 'sealed') {\n throw new PodIntegrityError(\n `autoUnlock blob has invalid kind ${String(kind)}; expected 'unsealed' or 'sealed'`,\n )\n }\n return {\n dump: obj['dump'],\n blob: blob as AutoUnlockBody['_autoUnlock'],\n }\n}\n\n/**\n * Transfer-seal payload. The destination DEKs, exported to raw\n * bytes and AES-256-GCM-sealed *as a set* under the one-time transfer\n * key. `adoptPartition` unseals this; `createOwnerOnAdoptedPartition`\n * re-wraps the raw DEKs under the recipient's KEK.\n */\nexport interface TransferSealPayload {\n readonly v: 1\n readonly alg: 'aes-256-gcm-pre-shared'\n readonly sealId: string\n /** base64(AES-256-GCM(transferKey, JSON of { collection: base64(rawDEK) })) — iv ‖ ct ‖ tag. */\n readonly payload: string\n}\n\n/**\n * Body wrapper for an extracted, transfer-sealed partition.\n * Sibling to {@link AutoUnlockBody}; selected by `header.bundleKind ===\n * 'extracted-partition'`. The inner `dump` is a re-keyed projection with\n * an empty `keyrings` map.\n */\nexport interface ExtractedPartitionBody {\n readonly _noydb_bundle_body: 1\n readonly dump: string\n readonly _transferSeal: TransferSealPayload\n}\n\nexport function buildExtractedPartitionWrapper(\n dumpJson: string,\n seal: TransferSealPayload,\n): ExtractedPartitionBody {\n return { _noydb_bundle_body: 1, dump: dumpJson, _transferSeal: seal }\n}\n\nexport function parseExtractedPartitionBody(\n bodyString: string,\n): { dump: string; seal: TransferSealPayload } {\n let parsed: unknown\n try {\n parsed = JSON.parse(bodyString)\n } catch (err) {\n throw new PodIntegrityError(\n 'header declared extracted-partition but body could not be parsed as JSON wrapper: '\n + (err instanceof Error ? err.message : String(err)),\n )\n }\n if (typeof parsed !== 'object' || parsed === null) {\n throw new PodIntegrityError('extracted-partition body is not a JSON object')\n }\n const obj = parsed as Record<string, unknown>\n if (obj['_noydb_bundle_body'] !== 1) {\n throw new PodIntegrityError(\n 'extracted-partition body missing `_noydb_bundle_body: 1` discriminator',\n )\n }\n if (typeof obj['dump'] !== 'string') {\n throw new PodIntegrityError('extracted-partition body must carry a string `dump` field')\n }\n const seal = obj['_transferSeal']\n if (typeof seal !== 'object' || seal === null) {\n throw new PodIntegrityError('extracted-partition body missing `_transferSeal` blob')\n }\n const s = seal as Record<string, unknown>\n if (s['v'] !== 1 || s['alg'] !== 'aes-256-gcm-pre-shared'\n || typeof s['sealId'] !== 'string' || typeof s['payload'] !== 'string') {\n throw new PodIntegrityError('extracted-partition `_transferSeal` blob is malformed')\n }\n return { dump: obj['dump'], seal: seal as TransferSealPayload }\n}\n\n/**\n * Coerce an unsealed perUser entry to `AutoCredential`. Older bundles\n * store bare strings; newer bundles store `{ kind, value }` objects.\n */\nfunction coerceUnsealed(entry: AutoCredential | string): AutoCredential {\n if (typeof entry === 'string') return { kind: 'secret', value: entry }\n return entry\n}\n\n/**\n * Resolve the `_autoUnlock` blob into a typed per-user credential map.\n *\n * - For `kind: 'unsealed'`: pass through, coercing pre-0.2 bare strings\n * to `{ kind: 'secret', value }`.\n * - For `kind: 'sealed'`: pick a `SealingKeyProvider` from\n * `opts.sealingProviders` whose `.id` matches each entry's `pid`;\n * unseal to `AutoCredential`. When no provider matches AND strict mode\n * (default), throw `PodSealMismatchError`. With\n * `attemptUnsealAcrossProviders: true`, try each provider whose\n * `alg` matches the envelope.\n * Exception: if an unmatched entry carries a `hint` field (recipient-target\n * entries), it passes through as `{ kind, value: base64sealed }` rather than\n * throwing — multi-recipient bundles have N-1 unmatched entries from each\n * recipient's perspective, and the consumer is expected to ignore entries\n * not addressed to them.\n * - When `sealingProviders` is unset entirely on a `'sealed'` bundle,\n * pass through the SEALED entries as `{ kind, value: base64sealed }` —\n * the caller can inspect or unseal elsewhere.\n *\n * Pre-0.2 sealed entries missing `kind` default to `'secret'`.\n */\nasync function resolveAutoUnlock(\n blob: AutoUnlockBody['_autoUnlock'],\n opts: ReadPodOptions,\n): Promise<{ kind: 'unsealed' | 'sealed'; perUser: Record<string, AutoCredential> }> {\n if (blob.kind === 'unsealed') {\n const resolved: Record<string, AutoCredential> = {}\n for (const [userId, entry] of Object.entries(blob.perUser)) {\n resolved[userId] = coerceUnsealed(entry)\n }\n return { kind: 'unsealed', perUser: resolved }\n }\n // Sealed path.\n if (opts.sealingProviders === undefined || opts.sealingProviders.length === 0) {\n // Inspection mode — pass the sealed payload through as a typed\n // credential whose `value` is the opaque base64 sealed bytes.\n // The caller is signalled by `kind: 'sealed'` on the outer result.\n const passthrough: Record<string, AutoCredential> = {}\n for (const [userId, entry] of Object.entries(blob.perUser)) {\n passthrough[userId] = { kind: entry.kind ?? 'secret', value: entry.sealed }\n }\n return { kind: 'sealed', perUser: passthrough }\n }\n const providersByPid = new Map<string, SealingKeyProvider>()\n for (const p of opts.sealingProviders) providersByPid.set(p.id, p)\n\n const decoder = new TextDecoder()\n const unsealedMap: Record<string, AutoCredential> = {}\n\n for (const [userId, entry] of Object.entries(blob.perUser)) {\n const credKind: AutoCredentialKind = entry.kind ?? 'secret'\n const provider = providersByPid.get(entry.pid)\n if (provider === undefined) {\n if (opts.attemptUnsealAcrossProviders === true) {\n // Try each provider; first that succeeds wins.\n let opened: string | null = null\n for (const candidate of opts.sealingProviders) {\n try {\n const plaintextBytes = await candidate.unseal(base64ToBytes(entry.sealed))\n opened = decoder.decode(plaintextBytes)\n break\n } catch {\n // try next\n }\n }\n if (opened === null) {\n if (entry.hint !== undefined) {\n // Recipient-target entry not addressed to any held key — pass through sealed.\n // Other recipients' entries in a multi-recipient bundle are opaque to us.\n unsealedMap[userId] = { kind: credKind, value: entry.sealed }\n continue\n }\n throw new PodSealMismatchError(userId, entry.pid)\n }\n unsealedMap[userId] = { kind: credKind, value: opened }\n continue\n }\n if (entry.hint !== undefined) {\n // Recipient-target entry not addressed to any held key — pass through sealed.\n // Multi-recipient bundles deliberately seal each user's entry under their own\n // public key; a reader holding only alice's key will not match bob's pid.\n unsealedMap[userId] = { kind: credKind, value: entry.sealed }\n continue\n }\n throw new PodSealMismatchError(userId, entry.pid)\n }\n const plaintextBytes = await provider.unseal(base64ToBytes(entry.sealed))\n unsealedMap[userId] = { kind: credKind, value: decoder.decode(plaintextBytes) }\n }\n return { kind: 'sealed', perUser: unsealedMap }\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n let binary = ''\n for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]!)\n return btoa(binary)\n}\n\nfunction base64ToBytes(b64: string): Uint8Array {\n const binary = atob(b64)\n const out = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i)\n return out\n}\n\n/**\n * Detect whether the runtime's `CompressionStream` supports brotli.\n *\n * Brotli requires Node 22+ / Chrome 124+ / Firefox 122+. The\n * detection runs the `CompressionStream` constructor in a\n * try/catch — unsupported formats throw `TypeError` synchronously,\n * making this a safe one-shot check that we cache for the\n * lifetime of the process.\n */\nlet cachedBrotliSupport: boolean | null = null\nfunction supportsBrotliCompression(): boolean {\n if (cachedBrotliSupport !== null) return cachedBrotliSupport\n try {\n new CompressionStream('br' as CompressionFormat)\n cachedBrotliSupport = true\n } catch {\n cachedBrotliSupport = false\n }\n return cachedBrotliSupport\n}\n\n/** Test-only: reset the brotli detection cache between tests. */\nexport function resetBrotliSupportCache(): void {\n cachedBrotliSupport = null\n}\n\n/**\n * Pick the compression algorithm and the corresponding format byte\n * from a user option. Throws if the user explicitly requests brotli\n * on a runtime that doesn't support it — a silent fallback would\n * make the produced bundle smaller-than-expected and confuse\n * size-bound tests.\n */\nfunction selectCompression(option: WritePodOptions['compression']): {\n format: CompressionAlgo\n streamFormat: CompressionFormat | null\n} {\n const choice = option ?? 'auto'\n if (choice === 'none') return { format: COMPRESSION_NONE, streamFormat: null }\n if (choice === 'gzip') return { format: COMPRESSION_GZIP, streamFormat: 'gzip' }\n if (choice === 'brotli') {\n if (!supportsBrotliCompression()) {\n throw new Error(\n `writePod({ compression: 'brotli' }) is not supported on this ` +\n `runtime. Brotli requires Node 22+, Chrome 124+, or Firefox 122+. ` +\n `Use { compression: 'auto' } to fall back to gzip silently, or ` +\n `{ compression: 'gzip' } to be explicit.`,\n )\n }\n return { format: COMPRESSION_BROTLI, streamFormat: 'br' as CompressionFormat }\n }\n // 'auto' — prefer brotli, fall back to gzip\n if (supportsBrotliCompression()) {\n return { format: COMPRESSION_BROTLI, streamFormat: 'br' as CompressionFormat }\n }\n return { format: COMPRESSION_GZIP, streamFormat: 'gzip' }\n}\n\n/**\n * Pump a Uint8Array through a CompressionStream / DecompressionStream\n * and collect the output. Both APIs are universally available in\n * Node 18+ and modern browsers; the only variance is which\n * formats they support, handled by `selectCompression` above.\n *\n * Implementation: build a single-chunk ReadableStream from the\n * input, pipe through the transform, then drain the resulting\n * ReadableStream into a single concatenated Uint8Array. This is\n * O(N) memory in the input + output sizes, which is fine for the\n * dump-sized payloads (typically <50MB) targets.\n */\nasync function pumpThroughStream(\n input: Uint8Array,\n stream: CompressionStream | DecompressionStream,\n): Promise<Uint8Array> {\n const readable = new Blob([input as BlobPart]).stream().pipeThrough(stream)\n const reader = readable.getReader()\n const chunks: Uint8Array[] = []\n let total = 0\n for (;;) {\n const { value, done } = await reader.read()\n if (done) break\n if (value) {\n chunks.push(value as Uint8Array)\n total += value.length\n }\n }\n const out = new Uint8Array(total)\n let offset = 0\n for (const chunk of chunks) {\n out.set(chunk, offset)\n offset += chunk.length\n }\n return out\n}\n\n/**\n * SHA-256 hex digest of `bytes`. Used for the bundle integrity\n * hash carried in the header. Web Crypto API only — no Node\n * crypto module, no third-party hash library.\n *\n * The output format is lowercase hex (64 chars for SHA-256). The\n * format validator pins this — uppercase or mixed-case digests\n * are rejected, so the writer and reader agree on canonicalization.\n */\nasync function sha256Hex(bytes: Uint8Array): Promise<string> {\n // Copy into a fresh ArrayBuffer-backed Uint8Array. The\n // underlying buffer of `bytes` may be SharedArrayBuffer (e.g.\n // from a worker), which `subtle.digest` rejects via TypeScript's\n // BufferSource type. Allocating a fresh ArrayBuffer-backed view\n // sidesteps the type narrowing and is portable across all\n // runtimes — the copy cost is O(N) but bundle bodies are\n // typically <50MB, well below the threshold where the copy\n // matters.\n const copy = new Uint8Array(bytes.length)\n copy.set(bytes)\n return sha256HexBytes(copy)\n}\n\n/**\n * Concatenate any number of Uint8Arrays into a single new buffer.\n * Used to assemble the final bundle from its prefix + header +\n * body parts.\n */\nfunction concatBytes(parts: readonly Uint8Array[]): Uint8Array {\n let total = 0\n for (const p of parts) total += p.length\n const out = new Uint8Array(total)\n let offset = 0\n for (const p of parts) {\n out.set(p, offset)\n offset += p.length\n }\n return out\n}\n\n/**\n * Replace the bundle's keyrings with freshly built recipient slots,\n * one per supplied recipient. No-op when neither `exportSecret`\n * nor `recipients` is set — the source keyring is inherited as-is.\n *\n * The single-secret shorthand creates a one-recipient list whose\n * id, role, and permissions inherit from the source vault — useful\n * for \"back up to a different secret\" without changing role\n * semantics. The multi-recipient form wraps each slot independently\n * with its declared role + permissions.\n *\n * @internal\n */\nasync function applyRecipientRewrap(\n vault: Vault,\n dumpJson: string,\n opts: WritePodOptions,\n): Promise<string> {\n if (opts.exportSecret === undefined && opts.recipients === undefined) {\n return dumpJson\n }\n\n const recipients: readonly PodRecipient[] =\n opts.recipients ?? [\n {\n id: vault.userId,\n secret: opts.exportSecret as string,\n role: vault.role,\n },\n ]\n\n const recipientKeyrings = await vault.buildBundleRecipientKeyrings(recipients)\n\n const backup = JSON.parse(dumpJson) as { keyrings: unknown; [k: string]: unknown }\n backup.keyrings = recipientKeyrings\n return JSON.stringify(backup)\n}\n\n/**\n * Apply opt-in slice filters to a vault dump JSON string. Filters that\n * narrow the bundle without crossing the encryption boundary — both\n * operate on metadata (collection name, envelope `_ts`) and never need\n * to decrypt records. When neither filter is set, the dump is returned\n * unchanged so the no-arg path stays a pure passthrough.\n *\n * Internal-collection filtering: when a `collections` allowlist is\n * provided, the bundle still carries `_internal` (ledger entries) and\n * the keyrings — they're necessary for the receiver to verify and\n * unlock the bundle. The allowlist applies to the user-collection\n * map only.\n *\n * @internal\n */\nfunction applySliceFilters(\n dumpJson: string,\n opts: WritePodOptions,\n): string {\n const collectionsFilter = opts.collections\n ? new Set(opts.collections)\n : null\n const sinceMs =\n opts.since !== undefined ? new Date(opts.since).getTime() : null\n if (collectionsFilter === null && sinceMs === null) return dumpJson\n\n // Parse, prune, re-serialize. The dump shape is stable\n // (VaultBackup) so this is a one-off allocation; for vaults beyond\n // the documented 1K–50K target a streaming variant would be a\n // follow-up, but the simple parse path keeps the slice path\n // type-safe and trivially auditable.\n const backup = JSON.parse(dumpJson) as {\n collections?: Record<string, Record<string, { _ts?: string }>>\n [k: string]: unknown\n }\n\n if (backup.collections && typeof backup.collections === 'object') {\n const next: Record<string, Record<string, unknown>> = {}\n for (const [name, records] of Object.entries(backup.collections)) {\n if (collectionsFilter && !collectionsFilter.has(name)) continue\n if (sinceMs === null) {\n next[name] = records\n continue\n }\n const kept: Record<string, unknown> = {}\n for (const [id, env] of Object.entries(records)) {\n const envTs = env._ts ? new Date(env._ts).getTime() : NaN\n if (Number.isFinite(envTs) && envTs >= sinceMs) {\n kept[id] = env\n }\n }\n next[name] = kept\n }\n backup.collections = next as typeof backup.collections\n }\n\n return JSON.stringify(backup)\n}\n\n/**\n * Unconditionally drop satellite-collection records whose base row is dead\n * (absent or tombstoned — existence.ts rule 1) from a vault dump. Unlike\n * `applySliceFilters` / `applyPlaintextFilters`, this isn't opt-in: a\n * satellite envelope that outlived its base is dead ciphertext (plus its\n * wrapped keys) that should never leave the vault in a `.noydb` backup\n * (#591 Task 10 — closes the last enumerated existence-authority surface).\n *\n * Pairing info comes from the persisted `_schemas/<name>` marker rather\n * than the in-memory `SatelliteRegistry` — that registry is private to\n * `Vault` and the bundle-export path only has `Vault._introspectState()`\n * (adapter + vault name + per-collection DEK accessor), so it reads the\n * marker instead of widening the kernel's surface. See\n * `with-shape/satellites/dead-filter.ts`.\n *\n * No-ops (returns `dumpJson` unchanged) when the vault has no detectable\n * satellite collections at all, so vaults that never use satellites pay\n * no extra parse/reserialize cost. Also no-ops when `vault` doesn't\n * implement `_introspectState()` at all — some call sites pass a minimal\n * duck-typed vault-like object for unit tests (e.g.\n * `snapshots.test.ts`'s `makeMockVault`, which implements only\n * `getPodHandle`/`dump`/`load`/`getCover`); a real `Vault`\n * always implements it.\n *\n * @internal\n */\nasync function applySatelliteLivenessFilter(\n vault: Vault,\n dumpJson: string,\n): Promise<string> {\n const backup = JSON.parse(dumpJson) as {\n collections?: Record<string, Record<string, unknown>>\n [k: string]: unknown\n }\n if (!backup.collections || typeof backup.collections !== 'object') return dumpJson\n if (typeof vault._introspectState !== 'function') return dumpJson\n\n const { adapter, name, getDEK } = vault._introspectState()\n const { liveBaseIdSetsForBundle } = await import('../with-shape/satellites/dead-filter.js')\n const satLive = await liveBaseIdSetsForBundle(adapter, name, Object.keys(backup.collections), getDEK)\n if (satLive.size === 0) return dumpJson\n\n const next: Record<string, Record<string, unknown>> = {}\n for (const [collName, records] of Object.entries(backup.collections)) {\n const live = satLive.get(collName)\n if (!live) { next[collName] = records; continue }\n const kept: Record<string, unknown> = {}\n for (const [id, env] of Object.entries(records)) {\n if (live.has(id)) kept[id] = env\n }\n next[collName] = kept\n }\n backup.collections = next\n return JSON.stringify(backup)\n}\n\n/**\n * Apply opt-in plaintext-tier filters\n * to a vault dump. Operates BEFORE `applySliceFilters` so the metadata\n * pass sees the trimmed record set.\n *\n * The filter never re-encrypts: surviving records carry their original\n * envelope unchanged. Failing records are dropped from the\n * `collections` map. Internal collections (ledger, deltas) and the\n * keyrings map are untouched.\n *\n * @internal\n */\nasync function applyPlaintextFilters(\n vault: Vault,\n dumpJson: string,\n opts: WritePodOptions,\n): Promise<string> {\n if (opts.where === undefined && opts.tierAtMost === undefined) {\n return dumpJson\n }\n\n type Env = { _ts?: string; _tier?: number; _iv: string; _data: string }\n const backup = JSON.parse(dumpJson) as {\n collections?: Record<string, Record<string, Env>>\n [k: string]: unknown\n }\n if (!backup.collections || typeof backup.collections !== 'object') {\n return dumpJson\n }\n\n const tierCeiling = opts.tierAtMost\n const where = opts.where\n\n const next: Record<string, Record<string, Env>> = {}\n for (const [collName, records] of Object.entries(backup.collections)) {\n const kept: Record<string, Env> = {}\n for (const [id, env] of Object.entries(records)) {\n // Tier ceiling — runs FIRST so we don't waste a decrypt on\n // records about to be dropped anyway. Envelope tier defaults to\n // 0 when absent (matches Vault's tier-0 conventions).\n if (tierCeiling !== undefined) {\n const tier = env._tier ?? 0\n if (tier > tierCeiling) continue\n }\n // Plaintext predicate — decrypt, run, keep on truthy. Errors\n // from inside the predicate propagate (callers want to see why\n // their filter blew up rather than getting a silent passthrough).\n if (where !== undefined) {\n const record = await vault._decryptEnvelopeForBundleFilter(\n env as never,\n collName,\n id,\n )\n const ok = await where(record, { collection: collName, id })\n if (!ok) continue\n }\n kept[id] = env\n }\n next[collName] = kept\n }\n backup.collections = next\n return JSON.stringify(backup)\n}\n\n/**\n * Write a `.noydb` bundle for the given vault.\n *\n * Pipeline:\n * 1. Resolve or create the compartment's stable bundle handle\n * via `vault.getPodHandle()` — same handle on\n * every export from the same vault instance, so cloud\n * adapters can use it as a primary key.\n * 2. `vault.dump()` → JSON string with encrypted records\n * inside.\n * 3. UTF-8 encode the dump string.\n * 4. Compress (brotli if available, gzip fallback by default).\n * 5. Compute SHA-256 of the compressed body for integrity.\n * 6. Build the minimum-disclosure header from format version,\n * handle, body length, body sha.\n * 7. Serialize: magic (4) + flags (1) + algo (1) + headerLen (4)\n * + header JSON (N) + compressed body (M).\n *\n * The output is a single `Uint8Array`. Consumers writing to disk\n * pass it to `fs.writeFile`; consumers uploading to cloud storage\n * pass it as the request body. The `@noy-db/file` adapter wraps\n * this with a `saveBundle(path, vault)` helper.\n */\n/**\n * Assemble the final `.noydb` container bytes from a body JSON string +\n * header extras. Shared by `writePod` and `extractPartition`\n * so both producers go through one compress/hash/prefix path.\n *\n * @internal\n */\nexport async function assemblePodContainer(opts: {\n handle: string\n bodyJsonStr: string\n compression: WritePodOptions['compression']\n /** Header fields beyond the always-present four. */\n headerExtras?: Partial<Pick<NoydbPodHeader,\n | 'publicEnvelope' | 'autoUnlock' | 'bundleKind' | 'transferSeal'\n | 'engineRange' | 'unlockMethods' | 'hasApp' | 'species' | 'pointerMode' | 'redirect'\n >>\n /**\n * When present, the assembled header is signed (#943): the header is\n * bumped to `formatVersion: 2` and carries the sig/keyId/sigAlg tuple.\n * Absent → an unsigned `formatVersion: 1` header (partitions, and pods\n * from vaults without a signer, stay unsigned).\n */\n signer?: DocSigner\n}): Promise<Uint8Array> {\n const dumpBytes = new TextEncoder().encode(opts.bodyJsonStr)\n const { format, streamFormat } = selectCompression(opts.compression)\n const body = streamFormat === null\n ? dumpBytes\n : await pumpThroughStream(dumpBytes, new CompressionStream(streamFormat))\n const bodySha256 = await sha256Hex(body)\n\n const header: NoydbPodHeader = {\n formatVersion: NOYDB_POD_FORMAT_VERSION,\n handle: opts.handle,\n bodyBytes: body.length,\n bodySha256,\n ...(opts.headerExtras?.publicEnvelope !== undefined ? { publicEnvelope: opts.headerExtras.publicEnvelope } : {}),\n ...(opts.headerExtras?.autoUnlock !== undefined ? { autoUnlock: opts.headerExtras.autoUnlock } : {}),\n ...(opts.headerExtras?.bundleKind !== undefined ? { bundleKind: opts.headerExtras.bundleKind } : {}),\n ...(opts.headerExtras?.transferSeal !== undefined ? { transferSeal: opts.headerExtras.transferSeal } : {}),\n ...(opts.headerExtras?.engineRange !== undefined ? { engineRange: opts.headerExtras.engineRange } : {}),\n ...(opts.headerExtras?.unlockMethods !== undefined ? { unlockMethods: opts.headerExtras.unlockMethods } : {}),\n ...(opts.headerExtras?.hasApp !== undefined ? { hasApp: opts.headerExtras.hasApp } : {}),\n ...(opts.headerExtras?.species !== undefined ? { species: opts.headerExtras.species } : {}),\n ...(opts.headerExtras?.pointerMode !== undefined ? { pointerMode: opts.headerExtras.pointerMode } : {}),\n ...(opts.headerExtras?.redirect !== undefined ? { redirect: opts.headerExtras.redirect } : {}),\n }\n // Header signing (#943): sign the header object as it will stand at\n // formatVersion 2 WITH keyId + sigAlg but WITHOUT `sig`, then attach the\n // resulting 3-tuple + bump the version. `signRecord`/`canonicalJson`\n // throw on any `undefined`, so the signed payload is built with only the\n // fields actually present (spread of the header carries no undefined\n // keys). Only produce formatVersion 2 WHEN signing — an unsigned pod\n // stays formatVersion 1 with no sig fields.\n const signed: NoydbPodHeader = opts.signer === undefined\n ? header\n : await (async (s: DocSigner): Promise<NoydbPodHeader> => {\n const toSign = { ...header, formatVersion: NOYDB_POD_FORMAT_VERSION_SIGNED, keyId: s.keyId, sigAlg: 'ed25519' as const }\n const sig = await signRecord(s.privateKeyPkcs8B64, toSign)\n return { ...toSign, sig }\n })(opts.signer)\n const headerBytes = encodePodHeader(signed)\n\n const prefix = new Uint8Array(NOYDB_POD_PREFIX_BYTES)\n prefix.set(NOYDB_POD_MAGIC, 0)\n prefix[4] = (streamFormat === null ? 0 : FLAG_COMPRESSED) | FLAG_HAS_INTEGRITY_HASH\n prefix[5] = format\n writeUint32BE(prefix, 6, headerBytes.length)\n\n return concatBytes([prefix, headerBytes, body])\n}\n\nexport async function writePod(\n vault: Vault,\n opts: WritePodOptions = {},\n): Promise<Uint8Array> {\n assertKnownWritePodOptions(opts)\n if (opts.exportSecret !== undefined && opts.recipients !== undefined) {\n throw new Error(\n 'writePod: pass either exportSecret or recipients, not both',\n )\n }\n\n // Auto-unlock: normalize once, validate + build from the\n // same NormalizedAutoUnlock object so there's no double-normalize call.\n const normalizedAutoUnlock = normalizeAutoUnlock(opts)\n const autoUnlockMode = validateAutoUnlockOptions(opts, normalizedAutoUnlock)\n\n const handle = await vault.getPodHandle()\n const dumpJson = await vault.dump()\n\n // Satellite existence-authority filter (#591 Task 10) — unconditional,\n // runs before every other filter so dead-ciphertext satellite records\n // never reach recipient rewrap or the opt-in filters below.\n const satelliteFiltered = await applySatelliteLivenessFilter(vault, dumpJson)\n\n // Re-keying: when caller supplied recipients (or the single-recipient\n // shorthand), substitute the bundle's `keyrings` map with freshly\n // built recipient slots before slice filters run.\n const rekeyed = await applyRecipientRewrap(vault, satelliteFiltered, opts)\n // Plaintext-tier filters run BEFORE\n // the metadata-only slice — that way the metadata pass sees the\n // already-trimmed record set and the two filter chains compose\n // cleanly.\n const plainFiltered = await applyPlaintextFilters(vault, rekeyed, opts)\n const filtered = applySliceFilters(plainFiltered, opts)\n\n // If no auto-unlock requested, body remains the raw dump JSON.\n // Otherwise build the wrapped body containing the\n // dump + `_autoUnlock` blob and serialize.\n const bodyJsonStr = normalizedAutoUnlock === null\n ? filtered\n : JSON.stringify(await buildAutoUnlockWrapper(filtered, normalizedAutoUnlock))\n // Snapshot the source vault's cover into the header when one is\n // persisted. `Vault.getCover` tolerates a missing document and\n // returns undefined, which we propagate as \"no cover in the\n // header.\" Vaults without a `_meta/public-envelope` document\n // (the frozen wire name) produce minimum-disclosure headers\n // exactly like before, preserving back-compat.\n const cover = await vault.getCover()\n\n // Resolve the header signer (#943): explicit `false` disables signing;\n // an explicit DocSigner is used verbatim (no vault touch); otherwise fall\n // back to the vault's persisted signer, which is `null` (unsigned) when\n // none was ever minted — export never mints one.\n const signer = opts.sign === false\n ? undefined\n : opts.sign !== undefined\n ? opts.sign\n : (await vault._loadPodSigner()) ?? undefined\n\n return assemblePodContainer({\n handle,\n bodyJsonStr,\n compression: opts.compression,\n headerExtras: {\n // `publicEnvelope` is the frozen wire key for the cover (#799).\n ...(cover !== undefined ? { publicEnvelope: cover } : {}),\n ...(autoUnlockMode !== null ? { autoUnlock: autoUnlockMode } : {}),\n // Header L2 fields (#942) — passed through verbatim from opts.\n ...(opts.engineRange !== undefined ? { engineRange: opts.engineRange } : {}),\n ...(opts.unlockMethods !== undefined ? { unlockMethods: opts.unlockMethods } : {}),\n ...(opts.hasApp !== undefined ? { hasApp: opts.hasApp } : {}),\n ...(opts.species !== undefined ? { species: opts.species } : {}),\n ...(opts.pointerMode !== undefined ? { pointerMode: opts.pointerMode } : {}),\n ...(opts.redirect !== undefined ? { redirect: opts.redirect } : {}),\n },\n ...(signer !== undefined ? { signer } : {}),\n })\n}\n\n\n/**\n * Internal helper shared by both readers — parses just the prefix\n * + header region of a bundle without touching the body. Returns\n * the parsed header plus the offset where the body starts and the\n * compression algorithm needed to decompress it.\n *\n * Throws on any format violation: missing/invalid magic, truncated\n * prefix, header length larger than the file, or unknown\n * compression algorithm.\n */\nfunction parsePrefixAndHeader(bytes: Uint8Array): {\n header: NoydbPodHeader\n bodyOffset: number\n algo: CompressionAlgo\n flags: number\n} {\n if (!hasNoydbPodMagic(bytes)) {\n throw new Error(\n `Not a .noydb bundle: missing 'NDB1' magic prefix. The first 4 bytes ` +\n `are ${[...bytes.slice(0, 4)].map((b) => b.toString(16).padStart(2, '0')).join(' ')}.`,\n )\n }\n if (bytes.length < NOYDB_POD_PREFIX_BYTES) {\n throw new Error(\n `Truncated .noydb bundle: file is only ${bytes.length} bytes, ` +\n `which is less than the ${NOYDB_POD_PREFIX_BYTES}-byte fixed prefix.`,\n )\n }\n const flags = bytes[4]!\n const algo = bytes[5]!\n if (algo !== COMPRESSION_NONE && algo !== COMPRESSION_GZIP && algo !== COMPRESSION_BROTLI) {\n throw new Error(\n `.noydb bundle declares unknown compression algorithm ${algo}. ` +\n `Known values: 0 (none), 1 (gzip), 2 (brotli).`,\n )\n }\n const headerLength = readUint32BE(bytes, 6)\n const bodyOffset = NOYDB_POD_PREFIX_BYTES + headerLength\n if (bodyOffset > bytes.length) {\n throw new Error(\n `Truncated .noydb bundle: declared header length ${headerLength} ` +\n `would extend past end of file (${bytes.length} bytes).`,\n )\n }\n const headerBytes = bytes.slice(NOYDB_POD_PREFIX_BYTES, bodyOffset)\n const header = decodePodHeader(headerBytes)\n return { header, bodyOffset, algo: algo as CompressionAlgo, flags }\n}\n\n/**\n * Read just the bundle header — no body decompression, no\n * integrity verification. Intended for cloud-listing UIs that want\n * to show the handle and size before downloading the full body.\n *\n * Returns the same `NoydbPodHeader` shape as the writer, with\n * minimum-disclosure validation already applied.\n *\n * **Cost** — O(prefix + header bytes). The header is normally well\n * under 1 KB, but may grow to roughly 256 KB when a `publicEnvelope`\n * with an inline icon is present. Cloud-listing UIs that previously\n * assumed sub-KB header reads should account for this when sizing\n * range requests against bundles that may carry icons.\n */\nexport function readPodHeader(bytes: Uint8Array): NoydbPodHeader {\n return parsePrefixAndHeader(bytes).header\n}\n\n\n/**\n * Outcome of {@link verifyPodHeader}.\n *\n * - `verified` — the header carried a sig-tuple, its `keyId` is in\n * `trustedKeys`, and the signature checks out over the canonical\n * header bytes.\n * - `unsigned` — the header carried no signature (a legacy v1 pod, or a\n * v2 pod written with `{ sign: false }`). Not an error; just unauthenticated.\n * - `untrusted` — the header is signed but its `keyId` is not one the\n * caller trusts. The signature was NOT checked.\n * - `tampered` — the header is signed by a trusted key but the signature\n * does not verify: the signed bytes were altered, or the mapped public\n * key is not the one that actually signed.\n */\nexport interface PodVerifyResult {\n readonly status: 'verified' | 'unsigned' | 'untrusted' | 'tampered'\n /** The header's `keyId`, present whenever the header carried a sig-tuple. */\n readonly keyId?: string\n}\n\n/**\n * Authenticate a pod header (#943) — a pure, dependency-free, WebCrypto-only\n * verifier. Given only the raw pod bytes and a `trustedKeys` map\n * (`keyId → publicKeyB64` the caller already trusts), it reports whether the\n * header was signed by a trusted document signer.\n *\n * Pairs with the signing half in `assemblePodContainer`/`writePod`: the\n * signed payload is the final wire header with `sig` removed, so verification\n * reconstructs it by stripping EXACTLY the `sig` field — `keyId`, `sigAlg`,\n * and every other header field stay in the verified payload.\n *\n * No store, enclave, or vault dependency — reachable from a static page with\n * only the pod bytes, the trusted-key map, and `globalThis.crypto`.\n *\n * SECURITY — authenticity is not integrity. A `verified` result proves the\n * header (which includes the *claimed* `bodySha256`) is signed by a trusted\n * key; it does NOT prove the body matches that hash. To trust the pod's\n * BODY you MUST also confirm the body hashes to `header.bodySha256` — call\n * `readPod`, which throws `PodIntegrityError` on mismatch. A `verified`\n * header paired with a swapped body is caught only by that integrity check.\n * This function stays body-free by design so a static page can authenticate a\n * header without decompressing the body; composing the two checks is the\n * caller's responsibility. See `docs/subsystems/pod-signature.md`.\n */\nexport async function verifyPodHeader(\n bytes: Uint8Array,\n trustedKeys: Readonly<Record<string, string>>,\n): Promise<PodVerifyResult> {\n const { header } = parsePrefixAndHeader(bytes)\n\n // No signature tuple → unsigned, regardless of formatVersion. The format\n // layer guarantees sig/keyId/sigAlg are all-or-nothing, so any one being\n // absent means the header is unsigned.\n if (header.sig === undefined || header.keyId === undefined || header.sigAlg === undefined) {\n return { status: 'unsigned' }\n }\n\n const publicKeyB64 = trustedKeys[header.keyId]\n if (publicKeyB64 === undefined) {\n return { status: 'untrusted', keyId: header.keyId }\n }\n\n // Reconstruct the signed payload: the FINAL wire header minus EXACTLY `sig`.\n const payload: Record<string, unknown> = { ...header }\n delete payload['sig']\n\n const ok = await verifyRecord(publicKeyB64, header.sig, payload)\n return { status: ok ? 'verified' : 'tampered', keyId: header.keyId }\n}\n\n/**\n * Read just the bundle's cover (`https://github.com/vLannaAi/noy-db-docs/blob/main/content/docs/services/public-envelope.md`)\n * — without verifying the body or even parsing the dump JSON. Pass\n * the raw bundle bytes; receive the owner-curated metadata or\n * `undefined` if the bundle was written without one.\n *\n * Locale-resolves any `name` / `description` map fields when `locale`\n * is supplied. Omitting `locale` returns the raw cover.\n *\n * Same security caveat as the on-vault read path — the cover is an\n * **untrusted hint** in v1; the encrypted body remains\n * the source of truth for vault contents.\n */\nexport function readPodCover(\n bytes: Uint8Array,\n opts: { readonly locale?: string } = {},\n): Cover | undefined {\n const header = parsePrefixAndHeader(bytes).header\n const env = header.publicEnvelope\n if (!env) return undefined\n if (opts.locale === undefined) return env\n return {\n ...env,\n ...(env.name !== undefined ? { name: pickLocale(env.name, opts.locale, env.defaultLocale) } : {}),\n ...(env.description !== undefined ? { description: pickLocale(env.description, opts.locale, env.defaultLocale) } : {}),\n }\n}\n\n/**\n * Read just the bundle's Redirect record (#944) — without verifying the\n * body or even parsing the dump JSON. Pass the raw bundle bytes; receive\n * the header's `redirect` field or `undefined` if the bundle was written\n * without one.\n *\n * The record is returned UNVERIFIED: `validatePodHeaderFields` only checks\n * its shape at parse time (a parser has no `trustedKeys`). Callers that\n * intend to follow the redirect MUST separately call `verifyRedirect`\n * (`redirect.js`) before trusting `target`.\n */\nexport function readPodRedirect(bytes: Uint8Array): Redirect | undefined {\n return parsePrefixAndHeader(bytes).header.redirect\n}\n\n/**\n * Read a full `.noydb` bundle: validate magic + header, verify\n * integrity hash over the body bytes, decompress, and return the\n * original `vault.dump()` JSON string ready to pass to\n * `vault.load()`.\n *\n * Throws `PodIntegrityError` if the body's actual SHA-256 does\n * not match the value declared in the header. Distinct from a\n * format error so consumers can pattern-match in catch blocks\n * (corrupted-in-transit vs malformed-by-producer).\n *\n * Note: this function does NOT take a secret. The dump JSON\n * inside the body still contains encrypted records — restoring\n * the vault requires `vault.load(dumpJson, secret)`\n * after this call. Splitting the layers keeps the bundle module\n * free of crypto concerns and lets the same code feed format\n * inspectors that never decrypt anything.\n */\nexport async function readPod(\n bytes: Uint8Array,\n opts: ReadPodOptions = {},\n): Promise<PodReadResult> {\n const { header, bodyOffset, algo } = parsePrefixAndHeader(bytes)\n const body = bytes.slice(bodyOffset)\n\n // Length check before hash check — a length mismatch is the\n // cheapest tamper signal and produces a more actionable error.\n if (body.length !== header.bodyBytes) {\n throw new PodIntegrityError(\n `body length ${body.length} does not match header.bodyBytes ` +\n `${header.bodyBytes}. The bundle was truncated or padded ` +\n `between write and read.`,\n )\n }\n\n const actualSha = await sha256Hex(body)\n if (actualSha !== header.bodySha256) {\n throw new PodIntegrityError(\n `body sha256 ${actualSha} does not match header.bodySha256 ` +\n `${header.bodySha256}. The bundle bytes were modified between ` +\n `write and read — refuse to decompress.`,\n )\n }\n\n let dumpBytes: Uint8Array\n if (algo === COMPRESSION_NONE) {\n dumpBytes = body\n } else {\n const streamFormat: CompressionFormat =\n algo === COMPRESSION_BROTLI ? ('br' as CompressionFormat) : 'gzip'\n try {\n dumpBytes = await pumpThroughStream(body, new DecompressionStream(streamFormat))\n } catch (err) {\n throw new PodIntegrityError(\n `decompression failed: ${(err as Error).message}. The bundle ` +\n `passed the integrity hash but the body is not valid ` +\n `${streamFormat} data — likely a producer bug.`,\n )\n }\n }\n\n const bodyString = new TextDecoder('utf-8', { fatal: true }).decode(dumpBytes)\n\n // When the header signals auto-unlock, the body is a\n // JSON wrapper carrying the dump string + the auto-unlock blob.\n // When absent, the body IS the raw dump JSON.\n if (header.autoUnlock === undefined) {\n return { header, dumpJson: bodyString }\n }\n const { dump, blob } = parseAutoUnlockBody(bodyString)\n const autoUnlock = await resolveAutoUnlock(blob, opts)\n return { header, dumpJson: dump, autoUnlock }\n}\n\n"],"mappings":";;;;;;;;;;;;;AAoDO,IAAM,kBAAkB,IAAI,WAAW,CAAC,IAAM,IAAM,IAAM,EAAI,CAAC;AAG/D,IAAM,yBAAyB;AAG/B,IAAM,2BAA2B;A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QAAM,YAAY,MAAMA,WAAU,IAAI;AACtC,MAAI,cAAc,OAAO,YAAY;AACnC,UAAM,IAAI;AAAA,MACR,eAAe,SAAS,qCACnB,OAAO,UAAU;AAAA,IAExB;AAAA,EACF;AAEA,MAAI;AACJ,MAAI,SAAS,kBAAkB;AAC7B,gBAAY;AAAA,EACd,OAAO;AACL,UAAM,eACJ,SAAS,qBAAsB,OAA6B;AAC9D,QAAI;AACF,kBAAY,MAAM,kBAAkB,MAAM,IAAI,oBAAoB,YAAY,CAAC;AAAA,IACjF,SAAS,KAAK;AACZ,YAAM,IAAI;AAAA,QACR,yBAA0B,IAAc,OAAO,oEAE1C,YAAY;AAAA,MACnB;AAAA,IACF;AAAA,EACF;AAEA,QAAM,aAAa,IAAI,YAAY,SAAS,EAAE,OAAO,KAAK,CAAC,EAAE,OAAO,SAAS;AAK7E,MAAI,OAAO,eAAe,QAAW;AACnC,WAAO,EAAE,QAAQ,UAAU,WAAW;AAAA,EACxC;AACA,QAAM,EAAE,MAAM,KAAK,IAAI,oBAAoB,UAAU;AACrD,QAAM,aAAa,MAAM,kBAAkB,MAAM,IAAI;AACrD,SAAO,EAAE,QAAQ,UAAU,MAAM,WAAW;AAC9C;","names":["userCount","plaintextBytes","sha256Hex"]}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import {
|
|
2
|
+
PERIODS_COLLECTION
|
|
3
|
+
} from "./chunk-A4TOGAUW.js";
|
|
4
|
+
import {
|
|
5
|
+
canonicalJson,
|
|
6
|
+
sha256Hex
|
|
7
|
+
} from "./chunk-ZLHHE5XZ.js";
|
|
8
|
+
import {
|
|
9
|
+
isDeleteMarker
|
|
10
|
+
} from "./chunk-PENPHA45.js";
|
|
11
|
+
import {
|
|
12
|
+
PeriodClosedError,
|
|
13
|
+
ValidationError
|
|
14
|
+
} from "./chunk-CWM4GQD2.js";
|
|
15
|
+
|
|
16
|
+
// src/with-audit/periods/periods.ts
|
|
17
|
+
function resolveReopenState(events) {
|
|
18
|
+
let lastReopen;
|
|
19
|
+
let reclosedAfter;
|
|
20
|
+
let reopenCount = 0;
|
|
21
|
+
for (const e of events) {
|
|
22
|
+
if (e.op === "reopen") {
|
|
23
|
+
lastReopen = e;
|
|
24
|
+
reclosedAfter = void 0;
|
|
25
|
+
reopenCount++;
|
|
26
|
+
} else if (lastReopen !== void 0) {
|
|
27
|
+
reclosedAfter = e.at;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
if (!lastReopen) return { reopenCount };
|
|
31
|
+
return {
|
|
32
|
+
reopenedAt: lastReopen.at,
|
|
33
|
+
reopenedBy: lastReopen.by,
|
|
34
|
+
...lastReopen.until !== void 0 && { reopenedUntil: lastReopen.until },
|
|
35
|
+
...lastReopen.reason !== void 0 && { reopenReason: lastReopen.reason },
|
|
36
|
+
...reclosedAfter !== void 0 && { reclosedAt: reclosedAfter },
|
|
37
|
+
reopenCount
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
function isEffectivelyReopened(period, nowIso) {
|
|
41
|
+
if (period.reopenedAt === void 0) return false;
|
|
42
|
+
if (period.reclosedAt !== void 0 && period.reclosedAt >= period.reopenedAt) return false;
|
|
43
|
+
if (period.reopenedUntil !== void 0 && nowIso > period.reopenedUntil) return false;
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
46
|
+
function resolvePeriodKey(name, partition) {
|
|
47
|
+
if (!partition || partition.length === 0) return name;
|
|
48
|
+
const parts = partition.map((p) => {
|
|
49
|
+
if (typeof p === "number" && !Number.isFinite(p)) {
|
|
50
|
+
throw new ValidationError(`period partition component must be a finite number, got ${p}`);
|
|
51
|
+
}
|
|
52
|
+
const s = String(p);
|
|
53
|
+
if (s === "") {
|
|
54
|
+
throw new ValidationError("period partition component must not be empty");
|
|
55
|
+
}
|
|
56
|
+
return encodeURIComponent(s);
|
|
57
|
+
});
|
|
58
|
+
return `${name}\0${parts.join("/")}`;
|
|
59
|
+
}
|
|
60
|
+
function samePartition(a, b) {
|
|
61
|
+
const x = a ?? [];
|
|
62
|
+
const y = b ?? [];
|
|
63
|
+
if (x.length !== y.length) return false;
|
|
64
|
+
return x.every((v, i) => String(v) === String(y[i]));
|
|
65
|
+
}
|
|
66
|
+
async function loadPeriods(adapter, vault, decrypt) {
|
|
67
|
+
const ids = await adapter.list(vault, PERIODS_COLLECTION);
|
|
68
|
+
const records = [];
|
|
69
|
+
for (const id of ids) {
|
|
70
|
+
const env = await adapter.get(vault, PERIODS_COLLECTION, id);
|
|
71
|
+
if (env) records.push(await decrypt(id, env));
|
|
72
|
+
}
|
|
73
|
+
records.sort((a, b) => a.closedAt.localeCompare(b.closedAt));
|
|
74
|
+
return records;
|
|
75
|
+
}
|
|
76
|
+
async function chainAnchor(records, partition) {
|
|
77
|
+
const inTimeline = records.filter((p) => samePartition(p.partition, partition));
|
|
78
|
+
const last = inTimeline[inTimeline.length - 1];
|
|
79
|
+
if (!last) return { priorPeriodHash: "" };
|
|
80
|
+
const hash = await sha256Hex(canonicalJson(last));
|
|
81
|
+
return { priorPeriodName: last.name, priorPeriodHash: hash };
|
|
82
|
+
}
|
|
83
|
+
function assertTsWritable(existing, incomingRecord, closedPeriods, scope) {
|
|
84
|
+
const partitionOf = (r) => {
|
|
85
|
+
if (!r || !scope?.resolve) return void 0;
|
|
86
|
+
return scope.resolve(scope.collection, r);
|
|
87
|
+
};
|
|
88
|
+
const existingRecord = existing?.record ?? null;
|
|
89
|
+
const existingPartition = partitionOf(existingRecord);
|
|
90
|
+
const incomingPartition = partitionOf(incomingRecord);
|
|
91
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
92
|
+
for (const p of closedPeriods) {
|
|
93
|
+
if (p.kind !== "closed") continue;
|
|
94
|
+
if (isEffectivelyReopened(p, now)) continue;
|
|
95
|
+
if (p.dateField) {
|
|
96
|
+
const checkRecord = (label, r, recordPartition) => {
|
|
97
|
+
if (!r) return;
|
|
98
|
+
if (!samePartition(recordPartition, p.partition)) return;
|
|
99
|
+
const v = r[p.dateField];
|
|
100
|
+
if (typeof v === "string" && v <= p.endDate) {
|
|
101
|
+
throw new PeriodClosedError(p.name, p.endDate, `${label}[${p.dateField}]=${v}`);
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
checkRecord("existing", existingRecord, existingPartition);
|
|
105
|
+
checkRecord("incoming", incomingRecord, incomingPartition);
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
if (!samePartition(existingPartition, p.partition)) continue;
|
|
109
|
+
const existingTs = existing?.ts ?? null;
|
|
110
|
+
if (existingTs !== null && existingTs <= p.endDate) {
|
|
111
|
+
throw new PeriodClosedError(p.name, p.endDate, existingTs);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
function validatePeriodName(name, existing, partition) {
|
|
116
|
+
if (name.length === 0) {
|
|
117
|
+
throw new ValidationError("Period name cannot be empty.");
|
|
118
|
+
}
|
|
119
|
+
resolvePeriodKey(name, partition);
|
|
120
|
+
if (existing.some((p) => p.name === name && samePartition(p.partition, partition))) {
|
|
121
|
+
const where = partition && partition.length > 0 ? ` in partition [${partition.join(", ")}]` : "";
|
|
122
|
+
throw new ValidationError(`Period "${name}" already exists${where}.`);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
async function appendPeriodLedgerEntry(ledger, actor, envelope, name, collection = PERIODS_COLLECTION) {
|
|
126
|
+
if (!ledger) return;
|
|
127
|
+
const { envelopePayloadHash } = await import("./ledger-MVPNG5OS.js");
|
|
128
|
+
await ledger.append({
|
|
129
|
+
op: "put",
|
|
130
|
+
collection,
|
|
131
|
+
id: name,
|
|
132
|
+
version: envelope._v,
|
|
133
|
+
actor,
|
|
134
|
+
payloadHash: await envelopePayloadHash(envelope)
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
async function purgeMarkersOn(store, vault, before, collections) {
|
|
138
|
+
const snapshot = await store.loadAll(vault);
|
|
139
|
+
let removed = 0;
|
|
140
|
+
for (const [coll, records] of Object.entries(snapshot)) {
|
|
141
|
+
if (collections && !collections.includes(coll)) continue;
|
|
142
|
+
for (const [id, env] of Object.entries(records)) {
|
|
143
|
+
if (isDeleteMarker(env) && env._ts < before) {
|
|
144
|
+
await store.delete(vault, coll, id);
|
|
145
|
+
removed++;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return removed;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// src/with-audit/periods/active.ts
|
|
153
|
+
function withPeriods(options) {
|
|
154
|
+
const subjects = options?.subjects;
|
|
155
|
+
const partitionOf = subjects ? (collection, record) => subjects[collection]?.(record) : void 0;
|
|
156
|
+
return {
|
|
157
|
+
loadPeriods,
|
|
158
|
+
chainAnchor,
|
|
159
|
+
assertTsWritable,
|
|
160
|
+
validatePeriodName,
|
|
161
|
+
appendPeriodLedgerEntry,
|
|
162
|
+
...partitionOf !== void 0 && { partitionOf }
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// src/with-audit/periods/strategy.ts
|
|
167
|
+
var NOT_ENABLED = new Error(
|
|
168
|
+
'Accounting periods require the periods strategy. Import `{ withPeriods }` from "@noy-db/hub/periods" and pass it to `createNoydb({ periodsStrategy: withPeriods() })`.'
|
|
169
|
+
);
|
|
170
|
+
var NO_PERIODS = {
|
|
171
|
+
async loadPeriods() {
|
|
172
|
+
return [];
|
|
173
|
+
},
|
|
174
|
+
async chainAnchor() {
|
|
175
|
+
return { priorPeriodHash: "" };
|
|
176
|
+
},
|
|
177
|
+
assertTsWritable() {
|
|
178
|
+
},
|
|
179
|
+
validatePeriodName() {
|
|
180
|
+
throw NOT_ENABLED;
|
|
181
|
+
},
|
|
182
|
+
async appendPeriodLedgerEntry() {
|
|
183
|
+
throw NOT_ENABLED;
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
export {
|
|
188
|
+
NO_PERIODS,
|
|
189
|
+
resolveReopenState,
|
|
190
|
+
isEffectivelyReopened,
|
|
191
|
+
resolvePeriodKey,
|
|
192
|
+
samePartition,
|
|
193
|
+
loadPeriods,
|
|
194
|
+
chainAnchor,
|
|
195
|
+
assertTsWritable,
|
|
196
|
+
validatePeriodName,
|
|
197
|
+
appendPeriodLedgerEntry,
|
|
198
|
+
purgeMarkersOn,
|
|
199
|
+
withPeriods
|
|
200
|
+
};
|
|
201
|
+
//# sourceMappingURL=chunk-RFO4UXKQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/with-audit/periods/periods.ts","../src/with-audit/periods/active.ts","../src/with-audit/periods/strategy.ts"],"sourcesContent":["/**\n * Accounting-period closure + opening.\n *\n * A closed period seals every record whose envelope `_ts` is at or\n * before the period's `endDate`: further writes (`put` / `delete`)\n * against such records throw {@link PeriodClosedError}. The period\n * itself is stored as a record in the reserved `_periods` collection\n * and written through the normal ledger-instrumented path, so every\n * closure appends a tamper-evident entry to the vault's hash chain.\n *\n * ## Closure model\n *\n * ```\n * vault.closePeriod({ name: 'FY2026-Q1', endDate: '2026-03-31' })\n * └─► PeriodRecord written to _periods/<name>\n * ├─ priorPeriodName / priorPeriodHash — chain to last close\n * ├─ closedAt / closedBy — provenance\n * └─ normal ledger append fires (LedgerStore.append)\n * ```\n *\n * Enforcement (`assertTsWritable`) is vault-local: the Vault caches\n * the list of closed periods on first read and consults that cache in\n * the `Collection.put` / `.delete` path via the `periodGuard` hook.\n *\n * ## Opening model\n *\n * ```\n * vault.openPeriod({\n * name: 'FY2026-Q2',\n * startDate: '2026-04-01',\n * fromPeriod: 'FY2026-Q1',\n * carryForward: async (priorView) => Record<string, Record<string, unknown>>,\n * })\n * ```\n *\n * `carryForward` receives a read-only `VaultInstant` anchored at the\n * prior period's `endDate` (built via `vault.at(endDate)`) so the\n * callback can compute closing aggregates from the sealed state. The\n * returned `{ [collectionName]: { [id]: record } }` map is written\n * before the new `PeriodRecord` lands — opening balances materialise\n * as normal records with fresh timestamps that fall outside every\n * closed period.\n *\n * ## Freeze\n *\n * ```\n * vault.freezePeriod('FY2026-Q1')\n * └─► physically purges delete markers whose write-time falls inside\n * the closed period's window (via the #589 `_purgeDeleteMarkers`\n * seam), then records the fact:\n * ├─ PeriodFreezeRecord written to _period_freezes/<name>\n * └─ normal ledger append fires (LedgerStore.append)\n * ```\n *\n * The chained `_periods/<name>` record is never mutated — `frozenAt` /\n * `frozenBy` / `purgedMarkerCount` are merged onto the returned\n * `PeriodRecord` at read time from the companion, so a tamper with the\n * freeze can never break the inter-period hash chain. Freezing is\n * terminal (a closed period, once frozen, stays frozen) and idempotent\n * (a second call is a no-op that returns the same merged record without\n * re-purging or re-appending a ledger entry). Freeze does NOT purge\n * forget-tombstones (GDPR crypto-shred erasure evidence), `_history`\n * versions, or live records — the delete-markers-only seam leaves all\n * three untouched by construction.\n *\n * Freeze purges the LOCAL adapter only. On a synced vault, markers already\n * pushed to sync targets survive there, and a later pull re-imports them\n * (benign — they still read deleted, but the space isn't reclaimed). A\n * re-imported marker keeps its original `_ts` (inside the already-frozen\n * period's window), so — like any late-booked delete — it is reclaimed by\n * the NEXT period's freeze, whose window covers it; freeze stays terminal\n * and does NOT re-purge an already-frozen period (#611). Sweeping the sync\n * targets themselves is a cross-target-purge concern deferred to the\n * cold-archival spec. Purging re-opens the #589 resurrection window for a\n * peer offline since before the cutoff, which is why the closed period is\n * the operator-asserted safe-point that gates the call.\n *\n * A period whose purge window has not fully elapsed cannot be frozen —\n * `freezePeriod` throws rather than purge markers for deletes that may not\n * have converged yet (#610).\n *\n * ## Archive\n *\n * ```\n * vault.archivePeriod('FY2026-Q1')\n * └─► relocates the closed period's in-window records (those with\n * `_ts < periodExclusiveUpperBound(endDate)`) from the hot store to\n * the configured cold tier (routeStore's `cold` route), then records:\n * ├─ PeriodArchiveRecord written to _period_archives/<name>\n * └─ a ledger entry attributed to _period_archives\n * ```\n *\n * Archival is NON-DESTRUCTIVE: routeStore reads fall through to the cold\n * tier on a hot miss, so an archived record still reads normally. It is\n * therefore gated only on `closed` (not `frozen`) — it does not re-open the\n * #589 resurrection window and needs no convergence safe-point. Freeze\n * (purge markers) and archive (relocate records) are independent and compose\n * in either order. Like freeze, archival keeps the chained `_periods/<name>`\n * record byte-immutable (state lives in the companion) and is idempotent.\n *\n * Bounds by write-time `_ts`, NOT business date: the store tier sees only\n * encrypted envelopes. A record with an in-period business date but a later\n * `_ts` (late-booked) archives at the NEXT period's archive — the same rule\n * freeze uses for late-booked delete markers. Requires a `routeStore` with a\n * cold route (`age: { cold }`); throws otherwise.\n *\n * Read cost: with `withLazy()` (per-id reads) archived records are truly\n * cold — fetched from cold only on access. In the default hydrated mode,\n * `loadAll` merges the cold store, so archived records still load into RAM\n * on vault open (hot-tier STORAGE is reclaimed; RAM is not). Summaries\n * (`_`-prefixed) always stay hot.\n *\n * ## Target-purge\n *\n * ```\n * vault.purgePeriodTargets('FY2026-Q1')\n * └─► sweeps delete markers (`_ts < periodExclusiveUpperBound(endDate)`) off\n * the vault's PUSH-ONLY sync targets (backup/archive roles), then records:\n * ├─ PeriodTargetPurgeRecord written to _period_target_purges/<name>\n * └─ a ledger entry attributed to _period_target_purges\n * ```\n *\n * Extends freeze's local marker purge to the vault's own remote sinks.\n * `sync-peer` (bidirectional) targets are SKIPPED: purging a marker there\n * re-opens the #589 resurrection window for a client offline before the\n * cutoff, an assertion no single vault can verify. Backup/archive targets are\n * push-only — never pulled from into convergence — so sweeping their markers\n * is safe. Requires the period be frozen first (closed → frozen →\n * target-purged) so the local safe-point is already established. Idempotent\n * once run; a vault with no push-only targets writes no companion and is\n * re-runnable (so a target added later is still swept). Single-vault only —\n * fleet-wide purge across sovereign vaults is klum's concern over\n * `@noy-db/hub/cargo`.\n *\n * ## Not covered\n *\n * - Partial re-opening of a closed period. If an auditor needs to\n * make a correction inside a sealed period, the sanctioned path is\n * a compensating entry in the NEW period, not an unlock of the\n * old one.\n * - Automatic period rollover. `closePeriod` / `openPeriod` are\n * deliberately explicit operator calls so the caller decides when\n * the boundary lands.\n *\n * @module\n */\n\nimport type { NoydbStore, EncryptedEnvelope } from '../../kernel/types.js'\nimport type { LedgerStore } from '../../with-commit/history/ledger/index.js'\nimport { sha256Hex, canonicalJson } from '../../with-commit/history/ledger/index.js'\nimport { isDeleteMarker } from '../../kernel/enclave/index.js'\nimport { PeriodClosedError, ValidationError } from '../../kernel/errors.js'\n\n// The reserved collection names + `periodExclusiveUpperBound` moved to the\n// dependency-light `window.ts` so the sync engine's period-scoped pull (#807)\n// can import them without this module's ledger imports; re-exported here so\n// every existing import path keeps working.\nexport {\n PERIODS_COLLECTION,\n PERIOD_FREEZES_COLLECTION,\n PERIOD_ARCHIVES_COLLECTION,\n PERIOD_TARGET_PURGES_COLLECTION,\n PERIOD_REOPENS_COLLECTION,\n periodExclusiveUpperBound,\n} from './window.js'\nimport { PERIODS_COLLECTION } from './window.js'\n\n/**\n * Companion record recording that a closed period was frozen (its delete\n * markers physically purged). Stored in {@link PERIOD_FREEZES_COLLECTION},\n * keyed by period name — kept OFF the hash-chained `_periods/<name>` record so\n * freeze never alters the inter-period chain.\n */\nexport interface PeriodFreezeRecord {\n readonly period: string\n readonly frozenAt: string\n readonly frozenBy: string\n readonly purgedMarkerCount: number\n}\n\n/**\n * Companion record noting that a closed period was cold-archived (its\n * in-window records physically relocated hot → cold). Stored in\n * {@link PERIOD_ARCHIVES_COLLECTION}, keyed by period name — kept OFF the\n * hash-chained `_periods/<name>` record so archive never alters the chain.\n */\nexport interface PeriodArchiveRecord {\n readonly period: string\n readonly archivedAt: string\n readonly archivedBy: string\n readonly archivedRecordCount: number\n}\n\n/** Per-target count of delete markers purged off one push-only sync target (#615). */\nexport interface TargetPurgeCount {\n readonly label?: string\n readonly role: 'backup' | 'archive'\n readonly purgedCount: number\n}\n\n/**\n * One entry in a period's append-only reopen/reclose log (#1022).\n *\n * Real accounting close is a three-state lifecycle — open / closed / reopened\n * — not a one-way door. A month gets closed, a missing invoice arrives or a\n * filing is rejected, the month is reopened, corrected, and reclosed. The audit\n * value is not the ability to write again; it is the chain being able to say\n * *closed at T1, reopened at T2 by U, reclosed at T3*.\n */\nexport interface PeriodReopenEvent {\n readonly op: 'reopen' | 'reclose'\n /** ISO timestamp the event was recorded. */\n readonly at: string\n /** userId of the keyring that performed it. */\n readonly by: string\n /**\n * `reopen` only — ISO instant after which the period re-seals on its own,\n * with nobody acting. Absent means the window stays open until an explicit\n * `reclosePeriod`.\n */\n readonly until?: string\n /** Free-text justification, carried verbatim into the audit trail. */\n readonly reason?: string\n}\n\n/**\n * Companion holding a period's reopen/reclose history (#1022). Stored in\n * {@link PERIOD_REOPENS_COLLECTION}, keyed by the period's storage key — kept\n * OFF the hash-chained `_periods/<name>` record for the same reason freeze and\n * archive are: reopening must never rewrite the close, or the chain that proves\n * the close happened is the very thing the reopen destroys.\n *\n * `events` is APPEND-ONLY. Where the other companions are single-shot and\n * idempotent, this one accumulates, because the cycle repeats.\n */\nexport interface PeriodReopenRecord {\n readonly period: string\n readonly partition?: PeriodPartition\n readonly events: readonly PeriodReopenEvent[]\n}\n\n/**\n * Collapse an append-only reopen log into the return-only fields merged onto a\n * {@link PeriodRecord} on read.\n *\n * Expiry is deliberately NOT resolved here: `reopenedUntil` is carried through\n * verbatim and compared against the clock at write-guard time, so a bounded\n * window re-seals on its own without anything having to run.\n *\n * @internal\n */\nexport function resolveReopenState(events: readonly PeriodReopenEvent[]): {\n reopenedAt?: string\n reopenedBy?: string\n reopenedUntil?: string\n reopenReason?: string\n reclosedAt?: string\n reopenCount: number\n} {\n let lastReopen: PeriodReopenEvent | undefined\n let reclosedAfter: string | undefined\n let reopenCount = 0\n for (const e of events) {\n if (e.op === 'reopen') {\n lastReopen = e\n reclosedAfter = undefined\n reopenCount++\n } else if (lastReopen !== undefined) {\n reclosedAfter = e.at\n }\n }\n if (!lastReopen) return { reopenCount }\n return {\n reopenedAt: lastReopen.at,\n reopenedBy: lastReopen.by,\n ...(lastReopen.until !== undefined && { reopenedUntil: lastReopen.until }),\n ...(lastReopen.reason !== undefined && { reopenReason: lastReopen.reason }),\n ...(reclosedAfter !== undefined && { reclosedAt: reclosedAfter }),\n reopenCount,\n }\n}\n\n/**\n * Is this period writable right now on account of a reopen? (#1022)\n *\n * Three ways to be sealed again: never reopened, explicitly reclosed after the\n * last reopen, or a bounded window that has elapsed. The clock is read by the\n * caller and passed in, so the guard and any diagnostic agree on one instant.\n *\n * @internal\n */\nexport function isEffectivelyReopened(period: PeriodRecord, nowIso: string): boolean {\n if (period.reopenedAt === undefined) return false\n if (period.reclosedAt !== undefined && period.reclosedAt >= period.reopenedAt) return false\n if (period.reopenedUntil !== undefined && nowIso > period.reopenedUntil) return false\n return true\n}\n\n/**\n * Companion record noting that a closed+frozen period's delete markers were\n * swept off the vault's push-only sync targets (#615). Stored in\n * {@link PERIOD_TARGET_PURGES_COLLECTION}, keyed by period name — kept OFF the\n * hash-chained `_periods/<name>` record so target-purge never alters the chain.\n */\nexport interface PeriodTargetPurgeRecord {\n readonly period: string\n readonly purgedAt: string\n readonly purgedBy: string\n readonly targets: readonly TargetPurgeCount[]\n}\n\n/**\n * Scope tuple for a period timeline (#1005).\n *\n * Identical in shape and semantics to `SequenceOptions.partition`: a\n * partitioned timeline is always disjoint from any unpartitioned one, and from\n * every other tuple. `['acme', 'vat']` and `['acme', 'wht']` are two\n * independent close calendars for the same subject — which is the whole point,\n * since sub-ledgers for one legal entity and one month routinely close on\n * different statutory deadlines.\n */\nexport type PeriodPartition = readonly (string | number)[]\n\n/**\n * Resolve the `_periods` storage key for a (name, partition) pair.\n *\n * Deliberately the same encoding as `resolveSequenceKey`: `name` verbatim when\n * unpartitioned, else `${name}\\x00${parts}` with each component\n * `encodeURIComponent`d and `'/'`-joined. The null-byte separator cannot occur\n * in a period name, so a partitioned key never collides with an unpartitioned\n * one; URI-encoding keeps `['a/b']` distinct from `['a','b']`.\n *\n * @throws {ValidationError} on an empty component or a non-finite number.\n * @internal\n */\nexport function resolvePeriodKey(name: string, partition?: PeriodPartition): string {\n if (!partition || partition.length === 0) return name\n const parts = partition.map((p) => {\n if (typeof p === 'number' && !Number.isFinite(p)) {\n throw new ValidationError(`period partition component must be a finite number, got ${p}`)\n }\n const s = String(p)\n if (s === '') {\n throw new ValidationError('period partition component must not be empty')\n }\n return encodeURIComponent(s)\n })\n return `${name}\\x00${parts.join('/')}`\n}\n\n/**\n * Do two partitions denote the same timeline? Absent and empty both mean \"the\n * unpartitioned timeline\", so they compare equal.\n *\n * @internal\n */\nexport function samePartition(a?: PeriodPartition, b?: PeriodPartition): boolean {\n const x = a ?? []\n const y = b ?? []\n if (x.length !== y.length) return false\n return x.every((v, i) => String(v) === String(y[i]))\n}\n\n/**\n * Resolves a record to the timeline that governs it. Supplied by\n * `withPeriods({ subjects })`; returns `undefined` for any collection with no\n * mapping, which is what keeps an unconfigured vault on the single vault-wide\n * timeline it has always had.\n *\n * @internal\n */\nexport type PartitionResolver = (\n collection: string,\n record: Record<string, unknown>,\n) => PeriodPartition | undefined\n\n/**\n * Stored record for one closed or opened accounting period. One entry\n * per period, keyed by `name` in the reserved `_periods` collection.\n *\n * The hash chain between periods is computed at read time by\n * `loadPeriods()` — each record carries the name + hash of its\n * predecessor so a tamper with any period's record breaks the chain\n * into the next one, the same way the ledger's `prevHash` works.\n */\nexport interface PeriodRecord {\n /**\n * Human-readable name (e.g., `'FY2026-Q1'`). Unique per PARTITION — two\n * timelines may each carry a `'2026-06'`, which is the normal case when one\n * vault serves several subjects (#1005). Unique per vault when unpartitioned.\n */\n readonly name: string\n /**\n * The timeline this period belongs to. Absent = the vault-wide timeline.\n * Two periods with the same `name` and different `partition` are unrelated:\n * separate hash chains, separate close state, and the write guard applies\n * each only to records that resolve to its own tuple.\n */\n readonly partition?: PeriodPartition\n /**\n * Role discriminator. A period is `'closed'` from the moment its\n * `closedAt` is recorded; `'opened'` marks a period whose opening\n * entries have been carried forward via {@link openPeriod}. Many\n * workflows will produce one opened period per closed period (the\n * opened one is the SUCCESSOR — its `startDate` equals the prior\n * `endDate + 1 day`).\n */\n readonly kind: 'closed' | 'opened'\n /** ISO date — inclusive upper bound for records belonging to this period. */\n readonly endDate: string\n /** ISO date — lower bound (present on opened periods only). */\n readonly startDate?: string\n /**\n * Record field carrying the business date (e.g. `'date'` on an\n * invoice, `'paidAt'` on a payment). The guard compares\n * `record[dateField]` against `endDate` — NOT the envelope `_ts`.\n * Accounting entries booked late (business date `2026-01-15`,\n * write-time `2026-04-22`) still get sealed when Q1 closes at\n * `2026-03-31` because the comparison uses the business date.\n *\n * Optional for backwards compat. When absent, the guard falls back\n * to envelope `_ts` — that's a write-time seal, appropriate for\n * content that doesn't carry a logical business date (e.g. system\n * settings) but almost never right for accounting ledgers.\n */\n readonly dateField?: string\n /** ISO timestamp recorded at `closePeriod()` / `openPeriod()` call time. */\n readonly closedAt: string\n /** userId of the keyring that invoked the close/open. */\n readonly closedBy: string\n /** Name of the prior period this one chains to, if any. */\n readonly priorPeriodName?: string\n /** sha256(canonicalJson(priorPeriod)) — empty for the first period. */\n readonly priorPeriodHash: string\n /**\n * Opened periods only — the names of the collections whose\n * carry-forward aggregates were written by {@link openPeriod}.\n * Recorded for auditability so a future `verifyPeriodChain()` can\n * cross-check the opening balances against the closing snapshot.\n */\n readonly openingCollections?: readonly string[]\n /** #604 return-only — merged from the `_period_freezes/<name>` companion on\n * read; NEVER written into the stored `_periods/<name>` record (would break\n * the hash chain). Absent = not yet frozen. */\n readonly frozenAt?: string\n readonly frozenBy?: string\n readonly purgedMarkerCount?: number\n /** #613 return-only — merged from the `_period_archives/<name>` companion on\n * read; NEVER written into the stored `_periods/<name>` record. Absent = not\n * yet archived. */\n readonly archivedAt?: string\n readonly archivedBy?: string\n readonly archivedRecordCount?: number\n /** #615 return-only — merged from the `_period_target_purges/<name>` companion\n * on read; NEVER written into the stored `_periods/<name>` record. Absent =\n * target-purge not yet run (or the vault has no push-only targets). */\n readonly targetsPurgedAt?: string\n readonly targetsPurgedBy?: string\n readonly targetsPurged?: readonly TargetPurgeCount[]\n /** #1022 return-only — collapsed from the `_period_reopens/<key>` append-only\n * log on read; NEVER written into the stored `_periods/<name>` record, so a\n * reopen cannot disturb the inter-period hash chain. Absent = never reopened.\n * `reclosedAt` present (and >= `reopenedAt`) means the window was closed\n * again explicitly; `reopenedUntil` in the past means it lapsed on its own.\n * Use {@link isEffectivelyReopened} rather than reading these directly. */\n readonly reopenedAt?: string\n readonly reopenedBy?: string\n readonly reopenedUntil?: string\n readonly reopenReason?: string\n readonly reclosedAt?: string\n /** How many times this period has been reopened, ever. */\n readonly reopenCount?: number\n}\n\n/** Options for `vault.closePeriod()`. */\nexport interface ClosePeriodOptions {\n /** Human-readable name. Must not collide with an existing period. */\n readonly name: string\n /**\n * Inclusive upper cutoff. A record is sealed when its\n * `record[dateField]` (or, if absent, the envelope `_ts`) is at or\n * before this ISO timestamp.\n */\n readonly endDate: string\n /**\n * Record field carrying the business date used for period\n * membership. Recommended for accounting workflows — e.g. an\n * invoice booked late (write-time after close) is still sealed\n * when its `invoice.date` falls inside the closed period.\n *\n * Omit to use envelope `_ts` (write-time seal). This fallback\n * rarely matches real-world accounting semantics; prefer passing\n * an explicit `dateField`.\n */\n readonly dateField?: string\n /**\n * Close only this timeline (#1005). Omit for the vault-wide timeline.\n *\n * ```ts\n * vault.closePeriod({\n * name: '2026-06', endDate: '2026-06-30', dateField: 'issuedAt',\n * partition: [clientId, 'vat'],\n * })\n * ```\n *\n * Which records the resulting seal applies to is decided by the\n * `subjects` map passed to `withPeriods()` — without one, no record ever\n * resolves to a partition and a partitioned close seals nothing.\n */\n readonly partition?: PeriodPartition\n}\n\n/** Options for `vault.openPeriod()`. */\nexport interface OpenPeriodOptions<TCollections = Record<string, Record<string, unknown>>> {\n /** Human-readable name for the new period. Must be unique. */\n readonly name: string\n /**\n * The timeline to open in. Must match the partition of `fromPeriod` — a\n * period cannot chain across timelines, since each carries its own hash\n * chain (#1005).\n */\n readonly partition?: PeriodPartition\n /** ISO lower bound of the new period (usually prior `endDate + 1 day`). */\n readonly startDate: string\n /**\n * Name of the prior CLOSED period this one chains from. The prior\n * period's record is verified to exist and to be `kind: 'closed'`;\n * its `endDate` is made available to the `carryForward` callback.\n */\n readonly fromPeriod: string\n /**\n * Receives a read-only facade over the vault's CURRENT state,\n * plus the prior period's `endDate`. Accounting semantics: after\n * a period closes, records with `record[dateField] <= endDate`\n * are frozen — current state equals closing state, so a caller\n * can compute closing balances by querying the live collection\n * with a `where('date', '<=', priorEndDate)` filter.\n *\n * Returns opening-balance records keyed by collection name.\n * Example:\n *\n * ```ts\n * carryForward: async (ctx) => {\n * const closing = await ctx.collection<Journal>('journal')\n * .query().where('date', '<=', ctx.priorEndDate).toArray()\n * const opening: Record<string, Journal> = {}\n * for (const entry of closing) {\n * opening[`OB-${entry.id}`] = { ...entry, date: '2026-04-01' }\n * }\n * return { journal: opening }\n * }\n * ```\n */\n readonly carryForward: (\n ctx: CarryForwardContext,\n ) => Promise<TCollections> | TCollections\n}\n\n/**\n * Context passed to `OpenPeriodOptions.carryForward`. Exposes a\n * read-only subset of the live vault (`collection(name).get/list`)\n * plus the prior period's `endDate` so business-date filters can\n * be built by the caller.\n *\n * Writes go via the return value, not via the facade — the\n * `collection()` here is deliberately restricted to reads.\n */\nexport interface CarryForwardContext {\n /** The prior period's `endDate` — the boundary of the closing snapshot. */\n readonly priorEndDate: string\n /** Read-only collection facade over current vault state. */\n collection<T = unknown>(name: string): ReadOnlyCollection<T>\n}\n\n/** Minimum read surface exposed to `carryForward`. */\nexport interface ReadOnlyCollection<T> {\n get(id: string): Promise<T | null>\n list(): Promise<T[]>\n}\n\n/**\n * Load every period record currently stored on the adapter.\n * Decrypting is the caller's responsibility (we return plain records\n * so the vault can use its own `_periods` DEK).\n *\n * @internal — called by Vault methods that need the closed-period\n * cache. Not part of the public API surface.\n */\nexport async function loadPeriods(\n adapter: NoydbStore,\n vault: string,\n decrypt: (id: string, envelope: EncryptedEnvelope) => Promise<PeriodRecord>,\n): Promise<PeriodRecord[]> {\n const ids = await adapter.list(vault, PERIODS_COLLECTION)\n const records: PeriodRecord[] = []\n for (const id of ids) {\n const env = await adapter.get(vault, PERIODS_COLLECTION, id)\n if (env) records.push(await decrypt(id, env))\n }\n // Stable order by closedAt so chain verification is reproducible.\n records.sort((a, b) => a.closedAt.localeCompare(b.closedAt))\n return records\n}\n\n/**\n * Given the current ordered period list, pick the last entry that\n * belongs to the hash chain — used as the `priorPeriodHash` anchor\n * for the next closure/opening.\n *\n * @internal\n */\nexport async function chainAnchor(\n records: readonly PeriodRecord[],\n partition?: PeriodPartition,\n): Promise<{ priorPeriodName?: string; priorPeriodHash: string }> {\n // #1005 — each timeline carries its OWN chain. Anchoring a partitioned close\n // to whatever happened to be written last vault-wide would interleave\n // unrelated subjects into one chain, so verifying client A's June would\n // depend on client B never having closed in between.\n const inTimeline = records.filter((p) => samePartition(p.partition, partition))\n const last = inTimeline[inTimeline.length - 1]\n if (!last) return { priorPeriodHash: '' }\n const hash = await sha256Hex(canonicalJson(last as unknown as Record<string, unknown>))\n return { priorPeriodName: last.name, priorPeriodHash: hash }\n}\n\n/**\n * Throw `PeriodClosedError` if the record being touched falls within\n * any closed period.\n *\n * Three signals, evaluated per period:\n *\n * 1. If the period declares a `dateField`, the guard reads\n * `record[dateField]` on BOTH the existing (prior) record AND the\n * incoming (new) record. Either comparing `<= endDate` triggers\n * the error — callers cannot slide a record into a closed period\n * by editing its date field.\n * 2. If the period has no `dateField`, the guard falls back to the\n * envelope `_ts` of the existing record. Fresh inserts (no\n * existing envelope) pass.\n * 3. For a delete, only the existing side is checked.\n *\n * @internal\n */\nexport function assertTsWritable(\n existing: { ts: string | null; record: Record<string, unknown> | null } | null,\n incomingRecord: Record<string, unknown> | null,\n closedPeriods: readonly PeriodRecord[],\n scope?: { collection: string; resolve?: PartitionResolver },\n): void {\n // #1005 — a period only governs records that resolve to ITS timeline. With no\n // resolver (the default `withPeriods()`), nothing resolves to a partition, so\n // every record sits on the vault-wide timeline exactly as before and a\n // partitioned period governs nothing.\n const partitionOf = (r: Record<string, unknown> | null): PeriodPartition | undefined => {\n if (!r || !scope?.resolve) return undefined\n return scope.resolve(scope.collection, r)\n }\n const existingRecord = existing?.record ?? null\n const existingPartition = partitionOf(existingRecord)\n const incomingPartition = partitionOf(incomingRecord)\n // One instant for the whole check, so a bounded reopen window cannot expire\n // between two periods in the same loop and seal a write half-way.\n const now = new Date().toISOString()\n\n for (const p of closedPeriods) {\n if (p.kind !== 'closed') continue\n // #1022 — a reopened period is writable again. This is the ONLY thing a\n // reopen does: it withdraws the period's veto. It cannot grant a write that\n // some other gate forbids, because the guard bus ANDs every handler and\n // record-level guards are registered ahead of this one.\n if (isEffectivelyReopened(p, now)) continue\n if (p.dateField) {\n const checkRecord = (\n label: string,\n r: Record<string, unknown> | null,\n recordPartition: PeriodPartition | undefined,\n ): void => {\n if (!r) return\n // Both sides are checked under their OWN partition, which is what stops\n // a write from sliding a record either INTO or OUT OF a sealed\n // timeline by rewriting the fields the subject mapping reads.\n if (!samePartition(recordPartition, p.partition)) return\n const v = r[p.dateField!]\n if (typeof v === 'string' && v <= p.endDate) {\n throw new PeriodClosedError(p.name, p.endDate, `${label}[${p.dateField}]=${v}`)\n }\n }\n checkRecord('existing', existingRecord, existingPartition)\n checkRecord('incoming', incomingRecord, incomingPartition)\n continue\n }\n // Fallback: write-time seal via envelope _ts. Scoped by the EXISTING\n // record's partition — `_ts` belongs to the stored envelope, so the\n // incoming side has no write-time of its own to compare.\n if (!samePartition(existingPartition, p.partition)) continue\n const existingTs = existing?.ts ?? null\n if (existingTs !== null && existingTs <= p.endDate) {\n throw new PeriodClosedError(p.name, p.endDate, existingTs)\n }\n }\n}\n\n/**\n * Sanity-check a proposed period name + endDate against existing\n * records. Shared by closePeriod / openPeriod so the two pathways\n * produce identical diagnostics.\n *\n * @internal\n */\nexport function validatePeriodName(\n name: string,\n existing: readonly PeriodRecord[],\n partition?: PeriodPartition,\n): void {\n if (name.length === 0) {\n throw new ValidationError('Period name cannot be empty.')\n }\n // Validates the components as a side effect — an empty or non-finite\n // component must be rejected at the call, not encoded into a storage key.\n resolvePeriodKey(name, partition)\n // #1005 — uniqueness is per TIMELINE. `'2026-06'` in `['A','vat']` does not\n // collide with `'2026-06'` in `['B','vat']`.\n if (existing.some((p) => p.name === name && samePartition(p.partition, partition))) {\n const where = partition && partition.length > 0\n ? ` in partition [${partition.join(', ')}]`\n : ''\n throw new ValidationError(`Period \"${name}\" already exists${where}.`)\n }\n}\n\n/**\n * Wire a reserved-collection ledger append for a period record. The\n * period itself is stored via the adapter as an encrypted envelope;\n * the ledger entry is a normal `put` with the period's payloadHash,\n * so period closures inherit the chain's tamper-evidence.\n *\n * @internal\n */\nexport async function appendPeriodLedgerEntry(\n ledger: LedgerStore | null,\n actor: string,\n envelope: EncryptedEnvelope,\n name: string,\n collection: string = PERIODS_COLLECTION,\n): Promise<void> {\n if (!ledger) return\n const { envelopePayloadHash } = await import('../../with-commit/history/ledger/index.js')\n await ledger.append({\n op: 'put',\n collection,\n id: name,\n version: envelope._v,\n actor,\n payloadHash: await envelopePayloadHash(envelope),\n })\n}\n\n/**\n * @internal #615. Sweep delete markers with `_ts < before` off ANY store\n * (the vault's local adapter, or a push-only sync target). Returns the count\n * removed. Shared by `vault._purgeDeleteMarkers` (local) and\n * `vault._purgePeriodTargets` (push-only targets).\n */\nexport async function purgeMarkersOn(\n store: NoydbStore,\n vault: string,\n before: string,\n collections?: string[],\n): Promise<number> {\n const snapshot = await store.loadAll(vault)\n let removed = 0\n for (const [coll, records] of Object.entries(snapshot)) {\n if (collections && !collections.includes(coll)) continue\n for (const [id, env] of Object.entries(records)) {\n if (isDeleteMarker(env) && env._ts < before) {\n await store.delete(vault, coll, id)\n removed++\n }\n }\n }\n return removed\n}\n","/**\n * Active periods strategy factory. Only reachable through the\n * `@noy-db/hub/periods` subpath.\n */\n\nimport {\n loadPeriods,\n chainAnchor,\n assertTsWritable,\n validatePeriodName,\n appendPeriodLedgerEntry,\n} from './periods.js'\nimport type { PeriodPartition, PartitionResolver } from './periods.js'\nimport type { PeriodsStrategy } from './strategy.js'\n\n/** Options for {@link withPeriods}. */\nexport interface WithPeriodsOptions {\n /**\n * Maps a collection to the timeline each of its records belongs to (#1005) —\n * the answer to \"which close calendar governs THIS record\".\n *\n * ```ts\n * withPeriods({\n * subjects: { receipts: (r) => [r.clientId, layerOf(r)] },\n * })\n * ```\n *\n * Same shape as `withForget({ subjects })`, which answers the same question\n * for erasure. A collection with no entry — and every collection when\n * `subjects` is omitted entirely — stays on the vault-wide timeline, so an\n * existing vault behaves exactly as it did before partitions existed.\n *\n * Return `undefined` from a mapper to put an individual record back on the\n * vault-wide timeline (e.g. a record that predates the field the mapping\n * reads).\n */\n readonly subjects?: Readonly<\n Record<string, (record: Record<string, unknown>) => PeriodPartition | undefined>\n >\n}\n\n/**\n * Build the default periods strategy. Pass into\n * `createNoydb({ periodsStrategy: withPeriods() })` to enable\n * `vault.closePeriod()` / `vault.openPeriod()` / write-guards.\n *\n * Pass `subjects` to run more than one close calendar in a single vault — see\n * {@link WithPeriodsOptions.subjects}.\n */\nexport function withPeriods(options?: WithPeriodsOptions): PeriodsStrategy {\n const subjects = options?.subjects\n const partitionOf: PartitionResolver | undefined = subjects\n ? (collection, record) => subjects[collection]?.(record)\n : undefined\n\n return {\n loadPeriods,\n chainAnchor,\n assertTsWritable,\n validatePeriodName,\n appendPeriodLedgerEntry,\n ...(partitionOf !== undefined && { partitionOf }),\n }\n}\n","/**\n * Strategy seam for the optional accounting-periods service. Core\n * imports `PeriodsStrategy` type-only + `NO_PERIODS` stub; the real\n * `loadPeriods` / `chainAnchor` / `assertTsWritable` /\n * `validatePeriodName` / `appendPeriodLedgerEntry` functions are\n * only reachable via `withPeriods()` in `./active.ts`.\n *\n * Applications that never call `vault.closePeriod()` /\n * `vault.openPeriod()` ship none of the ~363 LOC.\n *\n * @internal\n */\n\nimport type { EncryptedEnvelope, NoydbStore } from '../../kernel/types.js'\nimport type { LedgerStore } from '../../with-commit/history/ledger/store.js'\nimport type { PeriodRecord, PeriodPartition, PartitionResolver } from './periods.js'\n\n/**\n * @internal\n */\nexport interface PeriodsStrategy {\n loadPeriods(\n adapter: NoydbStore,\n vault: string,\n decrypt: (id: string, envelope: EncryptedEnvelope) => Promise<PeriodRecord>,\n ): Promise<PeriodRecord[]>\n chainAnchor(records: readonly PeriodRecord[], partition?: PeriodPartition): Promise<{\n priorPeriodName?: string\n priorPeriodHash: string\n }>\n assertTsWritable(\n existing: { ts: string | null; record: Record<string, unknown> | null } | null,\n incoming: Record<string, unknown> | null,\n periods: readonly PeriodRecord[],\n scope?: { collection: string; resolve?: PartitionResolver },\n ): void\n validatePeriodName(\n name: string,\n existing: readonly PeriodRecord[],\n partition?: PeriodPartition,\n ): void\n /**\n * Record → timeline resolver built from `withPeriods({ subjects })` (#1005).\n * `undefined` when the caller configured no subjects, which keeps every\n * record on the vault-wide timeline.\n */\n readonly partitionOf?: PartitionResolver\n appendPeriodLedgerEntry(\n ledger: LedgerStore | null,\n actor: string,\n envelope: EncryptedEnvelope,\n periodName: string,\n collection?: string,\n ): Promise<void>\n}\n\n/**\n * No-periods stub. `loadPeriods` returns `[]`; the write-guards do\n * nothing (vaults without closed periods never reject writes);\n * `validatePeriodName` / `appendPeriodLedgerEntry` throw because\n * those paths are only reached when the user explicitly called\n * `closePeriod()` / `openPeriod()` — if they did that without the\n * strategy, they need to wire it.\n *\n * @internal\n */\nconst NOT_ENABLED = new Error(\n 'Accounting periods require the periods strategy. Import ' +\n '`{ withPeriods }` from \"@noy-db/hub/periods\" and pass it to ' +\n '`createNoydb({ periodsStrategy: withPeriods() })`.',\n)\n\nexport const NO_PERIODS: PeriodsStrategy = {\n async loadPeriods() { return [] },\n async chainAnchor() { return { priorPeriodHash: '' } },\n assertTsWritable() {},\n validatePeriodName() { throw NOT_ENABLED },\n async appendPeriodLedgerEntry() { throw NOT_ENABLED },\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA2PO,SAAS,mBAAmB,QAOjC;AAC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