@noy-db/hub 0.2.0-pre.1 → 0.2.0-pre.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aggregate/index.cjs.map +1 -1
- package/dist/aggregate/index.js +2 -2
- package/dist/attestation/index.cjs +305 -0
- package/dist/attestation/index.cjs.map +1 -0
- package/dist/attestation/index.d.cts +52 -0
- package/dist/attestation/index.d.ts +52 -0
- package/dist/attestation/index.js +36 -0
- package/dist/attestation/index.js.map +1 -0
- package/dist/blobs/index.cjs.map +1 -1
- package/dist/blobs/index.d.cts +4 -3
- package/dist/blobs/index.d.ts +4 -3
- package/dist/blobs/index.js +10 -8
- package/dist/blobs/index.js.map +1 -1
- package/dist/bundle/index.cjs +17940 -129
- package/dist/bundle/index.cjs.map +1 -1
- package/dist/bundle/index.d.cts +172 -3
- package/dist/bundle/index.d.ts +172 -3
- package/dist/bundle/index.js +533 -5
- package/dist/bundle/index.js.map +1 -1
- package/dist/{chunk-CBAHB2BF.js → chunk-2EYC3WDT.js} +7 -70
- package/dist/chunk-2EYC3WDT.js.map +1 -0
- package/dist/{chunk-P7EQ2S5O.js → chunk-2XLVPKXG.js} +2 -2
- package/dist/chunk-4OQWR46B.js +79 -0
- package/dist/chunk-4OQWR46B.js.map +1 -0
- package/dist/{chunk-23TTQXVO.js → chunk-4UBOTYP5.js} +2 -2
- package/dist/chunk-4X2S7PBF.js +251 -0
- package/dist/chunk-4X2S7PBF.js.map +1 -0
- package/dist/{chunk-MKSA2V7A.js → chunk-5YHWBPOT.js} +2 -2
- package/dist/{chunk-DYBQG5PQ.js → chunk-6S3LLAQ5.js} +2 -2
- package/dist/{chunk-UA4RI7OT.js → chunk-74JEQFMT.js} +5 -5
- package/dist/chunk-75QDHSE4.js +59 -0
- package/dist/chunk-75QDHSE4.js.map +1 -0
- package/dist/chunk-A6SWRXUQ.js +118 -0
- package/dist/chunk-A6SWRXUQ.js.map +1 -0
- package/dist/{chunk-UZXLQCHP.js → chunk-BFI3RS42.js} +2 -2
- package/dist/{chunk-EGQYGYIU.js → chunk-EMEX37ZN.js} +2 -2
- package/dist/{chunk-PEULZC6M.js → chunk-EPK6A3WJ.js} +8 -1
- package/dist/chunk-EPK6A3WJ.js.map +1 -0
- package/dist/{chunk-VMIO4IXG.js → chunk-FBMXWVGP.js} +6 -229
- package/dist/chunk-FBMXWVGP.js.map +1 -0
- package/dist/{chunk-ZNOEIM6Y.js → chunk-FCDO7UAO.js} +2 -2
- package/dist/{chunk-5SCJ5UEF.js → chunk-FS7A4XNF.js} +3 -3
- package/dist/{chunk-YS3POABP.js → chunk-FXQYZNOW.js} +1 -1
- package/dist/chunk-FXQYZNOW.js.map +1 -0
- package/dist/{chunk-SIZWEV2Y.js → chunk-G7PAZ3TD.js} +4 -4
- package/dist/{chunk-SIZWEV2Y.js.map → chunk-G7PAZ3TD.js.map} +1 -1
- package/dist/{chunk-537VFZTR.js → chunk-GAUBWHAF.js} +4 -4
- package/dist/{chunk-FCXOFQAJ.js → chunk-GD3BGKAR.js} +2 -2
- package/dist/{chunk-DPMFBCV6.js → chunk-GDTCGIPX.js} +2 -2
- package/dist/{chunk-DPMFBCV6.js.map → chunk-GDTCGIPX.js.map} +1 -1
- package/dist/{chunk-6HPZY4ON.js → chunk-GVXBHCZ2.js} +8 -3
- package/dist/chunk-GVXBHCZ2.js.map +1 -0
- package/dist/{chunk-HB3Z2GCR.js → chunk-HGZ7DC5H.js} +2 -2
- package/dist/{chunk-MIQHZESA.js → chunk-IS5HWQO7.js} +5 -5
- package/dist/{chunk-MIQHZESA.js.map → chunk-IS5HWQO7.js.map} +1 -1
- package/dist/{chunk-5DWL3JBF.js → chunk-K5PVGKE4.js} +2 -2
- package/dist/{chunk-NIOHFJPJ.js → chunk-KMI2NBBF.js} +7 -119
- package/dist/chunk-KMI2NBBF.js.map +1 -0
- package/dist/{chunk-XGSOTWYX.js → chunk-KYKMKLJ6.js} +2 -2
- package/dist/chunk-LOL725S4.js +233 -0
- package/dist/chunk-LOL725S4.js.map +1 -0
- package/dist/{chunk-4TFSM22V.js → chunk-LS3JLEIB.js} +4 -4
- package/dist/{chunk-2AXFIYHT.js → chunk-NCO2JGKK.js} +1 -1
- package/dist/chunk-NCO2JGKK.js.map +1 -0
- package/dist/{chunk-Z72JH4KG.js → chunk-NGSPBLLE.js} +4 -34
- package/dist/chunk-NGSPBLLE.js.map +1 -0
- package/dist/{chunk-OMLIZL2P.js → chunk-NSLTPGEN.js} +2 -2
- package/dist/{chunk-7H6DOO3E.js → chunk-P6256WTJ.js} +211 -36
- package/dist/chunk-P6256WTJ.js.map +1 -0
- package/dist/{chunk-KESP7GOK.js → chunk-QAU5HM6Q.js} +3 -3
- package/dist/{chunk-34YSDCDP.js → chunk-SAVQ6E2O.js} +2 -2
- package/dist/chunk-T6HQMVML.js +9960 -0
- package/dist/chunk-T6HQMVML.js.map +1 -0
- package/dist/{chunk-PA6R5ZCI.js → chunk-TLFUDXVV.js} +4 -4
- package/dist/{chunk-WCA2NROQ.js → chunk-UOF74WQY.js} +2 -2
- package/dist/chunk-UVPGJXVO.js +83 -0
- package/dist/chunk-UVPGJXVO.js.map +1 -0
- package/dist/{chunk-DYECX3IX.js → chunk-WRLHNG6H.js} +2 -2
- package/dist/{chunk-ADQ5MQ54.js → chunk-YDLAFP36.js} +71 -1
- package/dist/chunk-YDLAFP36.js.map +1 -0
- package/dist/{chunk-I6MX32UC.js → chunk-YK72A4IT.js} +4 -4
- package/dist/chunk-YL2DR3HY.js +36 -0
- package/dist/chunk-YL2DR3HY.js.map +1 -0
- package/dist/{chunk-RD5LYKD6.js → chunk-ZC2AAE6J.js} +2 -2
- package/dist/chunk-ZUMGGHRB.js +57 -0
- package/dist/chunk-ZUMGGHRB.js.map +1 -0
- package/dist/consent/index.cjs.map +1 -1
- package/dist/consent/index.d.cts +4 -3
- package/dist/consent/index.d.ts +4 -3
- package/dist/consent/index.js +3 -3
- package/dist/{crypto-A7FRXYHC.js → crypto-H2Y3DDFW.js} +3 -3
- package/dist/{delegation-YBA4X4JN.js → delegation-QSC7G5QC.js} +5 -5
- package/dist/derivations/index.cjs.map +1 -1
- package/dist/derivations/index.d.cts +5 -4
- package/dist/derivations/index.d.ts +5 -4
- package/dist/derivations/index.js +4 -4
- package/dist/{dev-unlock-D9s-loPr.d.ts → dev-unlock-Cf2B7Kih.d.ts} +1 -1
- package/dist/{dev-unlock-DRwVSy2S.d.cts → dev-unlock-De3mjQWv.d.cts} +1 -1
- package/dist/executor-BZKFZVRC.js +8 -0
- package/dist/executor-GFZFDQXV.js +8 -0
- package/dist/executor-KT2IOZVP.js +11 -0
- package/dist/{fanout-sidecar-VJ52RIEY.js → fanout-sidecar-NRBWSLRK.js} +2 -2
- package/dist/guards/index.cjs +7 -0
- package/dist/guards/index.cjs.map +1 -1
- package/dist/guards/index.d.cts +5 -4
- package/dist/guards/index.d.ts +5 -4
- package/dist/guards/index.js +4 -4
- package/dist/{hash-DXXXusyk.d.ts → hash-gVn_uKhp.d.ts} +1 -1
- package/dist/{hash-DtRih9MQ.d.cts → hash-vBCB0-Ps.d.cts} +1 -1
- package/dist/history/index.cjs +2 -2
- package/dist/history/index.cjs.map +1 -1
- package/dist/history/index.d.cts +5 -4
- package/dist/history/index.d.ts +5 -4
- package/dist/history/index.js +6 -6
- package/dist/i18n/index.cjs.map +1 -1
- package/dist/i18n/index.d.cts +4 -3
- package/dist/i18n/index.d.ts +4 -3
- package/dist/i18n/index.js +14 -12
- package/dist/i18n/index.js.map +1 -1
- package/dist/{index-CNwA-B6-.d.ts → index-BF1B2HB9.d.ts} +53 -1
- package/dist/{index-CmVgTkqk.d.cts → index-DVkvrgpm.d.cts} +53 -1
- package/dist/index.cjs +1780 -64
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +34 -12
- package/dist/index.d.ts +34 -12
- package/dist/index.js +160 -8804
- package/dist/index.js.map +1 -1
- package/dist/indexing/index.cjs.map +1 -1
- package/dist/indexing/index.js +2 -2
- package/dist/issue-BAJ7ZB4S.js +12 -0
- package/dist/{ledger-3TXNP47J.js → ledger-WOEJUYTP.js} +6 -6
- package/dist/materialized-views/index.cjs.map +1 -1
- package/dist/materialized-views/index.d.cts +6 -5
- package/dist/materialized-views/index.d.ts +6 -5
- package/dist/materialized-views/index.js +6 -6
- package/dist/noydb-XNQSKXGO.js +34 -0
- package/dist/overlay-views/index.cjs.map +1 -1
- package/dist/overlay-views/index.d.cts +5 -4
- package/dist/overlay-views/index.d.ts +5 -4
- package/dist/overlay-views/index.js +6 -4
- package/dist/periods/index.cjs.map +1 -1
- package/dist/periods/index.d.cts +4 -3
- package/dist/periods/index.d.ts +4 -3
- package/dist/periods/index.js +6 -6
- package/dist/{public-envelope-PY6NKFLI.js → public-envelope-OHQ5UZFM.js} +4 -4
- package/dist/query/index.cjs.map +1 -1
- package/dist/query/index.d.cts +1 -1
- package/dist/query/index.d.ts +1 -1
- package/dist/query/index.js +3 -3
- package/dist/registry-2IEARCGT.js +7 -0
- package/dist/{registry-3L3N3PTG.js → registry-CDHASH73.js} +3 -3
- package/dist/registry-EMGLZGR6.js +8 -0
- package/dist/registry-NQALYR77.js +8 -0
- package/dist/registry-NQALYR77.js.map +1 -0
- package/dist/revoke-7JOVLZFD.js +17 -0
- package/dist/revoke-7JOVLZFD.js.map +1 -0
- package/dist/session/index.cjs.map +1 -1
- package/dist/session/index.d.cts +5 -4
- package/dist/session/index.d.ts +5 -4
- package/dist/session/index.js +3 -3
- package/dist/shadow/index.cjs.map +1 -1
- package/dist/shadow/index.d.cts +4 -3
- package/dist/shadow/index.d.ts +4 -3
- package/dist/shadow/index.js +2 -2
- package/dist/signer-M4K5HBLD.js +18 -0
- package/dist/signer-M4K5HBLD.js.map +1 -0
- package/dist/{stale-HSC5YO2O.js → stale-PAGCS4K5.js} +2 -2
- package/dist/stale-PAGCS4K5.js.map +1 -0
- package/dist/store/index.cjs.map +1 -1
- package/dist/store/index.d.cts +4 -3
- package/dist/store/index.d.ts +4 -3
- package/dist/store/index.js +2 -2
- package/dist/sync/index.cjs.map +1 -1
- package/dist/sync/index.d.cts +3 -2
- package/dist/sync/index.d.ts +3 -2
- package/dist/sync/index.js +4 -4
- package/dist/team/index.cjs.map +1 -1
- package/dist/team/index.d.cts +4 -3
- package/dist/team/index.d.ts +4 -3
- package/dist/team/index.js +13 -11
- package/dist/tx/index.cjs +81 -1
- package/dist/tx/index.cjs.map +1 -1
- package/dist/tx/index.d.cts +5 -4
- package/dist/tx/index.d.ts +5 -4
- package/dist/tx/index.js +56 -3
- package/dist/tx/index.js.map +1 -1
- package/dist/{types-C4lwMKKF.d.cts → types-CSLcfytP.d.cts} +644 -5
- package/dist/{types-DW9RGSSs.d.ts → types-D9eB0Rvh.d.ts} +644 -5
- package/dist/{index-4agOpzqd.d.ts → ulid-CG2YvAbg.d.cts} +51 -33
- package/dist/{index-hdFvZkBP.d.cts → ulid-CiM2OAeM.d.ts} +51 -33
- package/dist/util/index.cjs.map +1 -1
- package/dist/util/index.js +1 -1
- package/dist/{with-derivation-g-pGoMzL.d.ts → with-derivation-Bzpj6UTv.d.ts} +1 -1
- package/dist/{with-derivation-C8LDlV7t.d.cts → with-derivation-DWajFh4K.d.cts} +1 -1
- package/dist/{with-guard-jI1x9Z3k.d.cts → with-guard-DF_Ul3DT.d.cts} +1 -1
- package/dist/{with-guard-DWOCK4Ca.d.ts → with-guard-DR7U-l4v.d.ts} +1 -1
- package/dist/{with-materialized-view-DcTx4H3j.d.cts → with-materialized-view-_piodoIz.d.cts} +1 -1
- package/dist/{with-materialized-view-DaKR-N6J.d.ts → with-materialized-view-qtoJ3xKJ.d.ts} +1 -1
- package/dist/{with-overlayed-view-N7jYuNOS.d.ts → with-overlayed-view-DFaRfgMr.d.ts} +1 -1
- package/dist/{with-overlayed-view-D-6oWAgM.d.cts → with-overlayed-view-DwzCKxn2.d.cts} +1 -1
- package/package.json +15 -3
- package/dist/chunk-2AXFIYHT.js.map +0 -1
- package/dist/chunk-6HPZY4ON.js.map +0 -1
- package/dist/chunk-7H6DOO3E.js.map +0 -1
- package/dist/chunk-ADQ5MQ54.js.map +0 -1
- package/dist/chunk-CBAHB2BF.js.map +0 -1
- package/dist/chunk-NIOHFJPJ.js.map +0 -1
- package/dist/chunk-PEULZC6M.js.map +0 -1
- package/dist/chunk-VMIO4IXG.js.map +0 -1
- package/dist/chunk-YS3POABP.js.map +0 -1
- package/dist/chunk-Z72JH4KG.js.map +0 -1
- package/dist/executor-7E3VFGW7.js +0 -11
- package/dist/executor-CEWX2FQI.js +0 -8
- package/dist/executor-X4SQ3ZLC.js +0 -8
- package/dist/registry-O47PUPSY.js +0 -8
- package/dist/registry-RFGGMVNJ.js +0 -7
- package/dist/registry-WLLMODKN.js +0 -8
- /package/dist/{chunk-P7EQ2S5O.js.map → chunk-2XLVPKXG.js.map} +0 -0
- /package/dist/{chunk-23TTQXVO.js.map → chunk-4UBOTYP5.js.map} +0 -0
- /package/dist/{chunk-MKSA2V7A.js.map → chunk-5YHWBPOT.js.map} +0 -0
- /package/dist/{chunk-DYBQG5PQ.js.map → chunk-6S3LLAQ5.js.map} +0 -0
- /package/dist/{chunk-UA4RI7OT.js.map → chunk-74JEQFMT.js.map} +0 -0
- /package/dist/{chunk-UZXLQCHP.js.map → chunk-BFI3RS42.js.map} +0 -0
- /package/dist/{chunk-EGQYGYIU.js.map → chunk-EMEX37ZN.js.map} +0 -0
- /package/dist/{chunk-ZNOEIM6Y.js.map → chunk-FCDO7UAO.js.map} +0 -0
- /package/dist/{chunk-5SCJ5UEF.js.map → chunk-FS7A4XNF.js.map} +0 -0
- /package/dist/{chunk-537VFZTR.js.map → chunk-GAUBWHAF.js.map} +0 -0
- /package/dist/{chunk-FCXOFQAJ.js.map → chunk-GD3BGKAR.js.map} +0 -0
- /package/dist/{chunk-HB3Z2GCR.js.map → chunk-HGZ7DC5H.js.map} +0 -0
- /package/dist/{chunk-5DWL3JBF.js.map → chunk-K5PVGKE4.js.map} +0 -0
- /package/dist/{chunk-XGSOTWYX.js.map → chunk-KYKMKLJ6.js.map} +0 -0
- /package/dist/{chunk-4TFSM22V.js.map → chunk-LS3JLEIB.js.map} +0 -0
- /package/dist/{chunk-OMLIZL2P.js.map → chunk-NSLTPGEN.js.map} +0 -0
- /package/dist/{chunk-KESP7GOK.js.map → chunk-QAU5HM6Q.js.map} +0 -0
- /package/dist/{chunk-34YSDCDP.js.map → chunk-SAVQ6E2O.js.map} +0 -0
- /package/dist/{chunk-PA6R5ZCI.js.map → chunk-TLFUDXVV.js.map} +0 -0
- /package/dist/{chunk-WCA2NROQ.js.map → chunk-UOF74WQY.js.map} +0 -0
- /package/dist/{chunk-DYECX3IX.js.map → chunk-WRLHNG6H.js.map} +0 -0
- /package/dist/{chunk-I6MX32UC.js.map → chunk-YK72A4IT.js.map} +0 -0
- /package/dist/{chunk-RD5LYKD6.js.map → chunk-ZC2AAE6J.js.map} +0 -0
- /package/dist/{crypto-A7FRXYHC.js.map → crypto-H2Y3DDFW.js.map} +0 -0
- /package/dist/{delegation-YBA4X4JN.js.map → delegation-QSC7G5QC.js.map} +0 -0
- /package/dist/{executor-7E3VFGW7.js.map → executor-BZKFZVRC.js.map} +0 -0
- /package/dist/{executor-CEWX2FQI.js.map → executor-GFZFDQXV.js.map} +0 -0
- /package/dist/{executor-X4SQ3ZLC.js.map → executor-KT2IOZVP.js.map} +0 -0
- /package/dist/{fanout-sidecar-VJ52RIEY.js.map → fanout-sidecar-NRBWSLRK.js.map} +0 -0
- /package/dist/{ledger-3TXNP47J.js.map → issue-BAJ7ZB4S.js.map} +0 -0
- /package/dist/{public-envelope-PY6NKFLI.js.map → ledger-WOEJUYTP.js.map} +0 -0
- /package/dist/{registry-3L3N3PTG.js.map → noydb-XNQSKXGO.js.map} +0 -0
- /package/dist/{registry-O47PUPSY.js.map → public-envelope-OHQ5UZFM.js.map} +0 -0
- /package/dist/{registry-RFGGMVNJ.js.map → registry-2IEARCGT.js.map} +0 -0
- /package/dist/{registry-WLLMODKN.js.map → registry-CDHASH73.js.map} +0 -0
- /package/dist/{stale-HSC5YO2O.js.map → registry-EMGLZGR6.js.map} +0 -0
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
import {
|
|
6
6
|
DanglingReferenceError,
|
|
7
7
|
JoinTooLargeError
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-YDLAFP36.js";
|
|
9
9
|
|
|
10
10
|
// src/query/join.ts
|
|
11
11
|
var DEFAULT_JOIN_MAX_ROWS = 5e4;
|
|
@@ -1364,4 +1364,4 @@ export {
|
|
|
1364
1364
|
executePlan,
|
|
1365
1365
|
ScanBuilder
|
|
1366
1366
|
};
|
|
1367
|
-
//# sourceMappingURL=chunk-
|
|
1367
|
+
//# sourceMappingURL=chunk-4UBOTYP5.js.map
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import {
|
|
2
|
+
NOYDB_FORMAT_VERSION
|
|
3
|
+
} from "./chunk-FXQYZNOW.js";
|
|
4
|
+
import {
|
|
5
|
+
decrypt,
|
|
6
|
+
encrypt
|
|
7
|
+
} from "./chunk-UOF74WQY.js";
|
|
8
|
+
|
|
9
|
+
// src/persisted-schemas/storage.ts
|
|
10
|
+
var SCHEMAS_COLLECTION = "_schemas";
|
|
11
|
+
async function loadPersistedSchema(store, vault, collection, dek) {
|
|
12
|
+
const envelope = await store.get(vault, SCHEMAS_COLLECTION, collection);
|
|
13
|
+
if (!envelope) return void 0;
|
|
14
|
+
try {
|
|
15
|
+
const plaintext = await decrypt(envelope._iv, envelope._data, dek);
|
|
16
|
+
const parsed = JSON.parse(plaintext);
|
|
17
|
+
if (parsed._noydb_schema !== 1) return void 0;
|
|
18
|
+
return parsed;
|
|
19
|
+
} catch {
|
|
20
|
+
return void 0;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
async function savePersistedSchema(store, vault, collection, dek, payload) {
|
|
24
|
+
const json = JSON.stringify(payload);
|
|
25
|
+
const { iv, data } = await encrypt(json, dek);
|
|
26
|
+
const prior = await store.get(vault, SCHEMAS_COLLECTION, collection);
|
|
27
|
+
const env = {
|
|
28
|
+
_noydb: NOYDB_FORMAT_VERSION,
|
|
29
|
+
_v: (prior?._v ?? 0) + 1,
|
|
30
|
+
_ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
31
|
+
_iv: iv,
|
|
32
|
+
_data: data
|
|
33
|
+
};
|
|
34
|
+
await store.put(vault, SCHEMAS_COLLECTION, collection, env);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// src/team/managed-passphrase.ts
|
|
38
|
+
var MemorySealingKeyProvider = class {
|
|
39
|
+
id;
|
|
40
|
+
fingerprint;
|
|
41
|
+
keyBytes;
|
|
42
|
+
constructor(opts) {
|
|
43
|
+
this.id = opts.id;
|
|
44
|
+
const encoded = new TextEncoder().encode(opts.id);
|
|
45
|
+
let h = 0;
|
|
46
|
+
for (let i = 0; i < encoded.length; i++) {
|
|
47
|
+
h = h * 31 + encoded[i] >>> 0;
|
|
48
|
+
}
|
|
49
|
+
this.fingerprint = new Uint8Array([
|
|
50
|
+
h >>> 24 & 255,
|
|
51
|
+
h >>> 16 & 255,
|
|
52
|
+
h >>> 8 & 255,
|
|
53
|
+
h & 255
|
|
54
|
+
]);
|
|
55
|
+
this.keyBytes = new Uint8Array(16);
|
|
56
|
+
for (let i = 0; i < 16; i++) {
|
|
57
|
+
this.keyBytes[i] = this.fingerprint[i % 4] ^ i * 17;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
async seal(passphrase) {
|
|
61
|
+
const out = new Uint8Array(4 + passphrase.length);
|
|
62
|
+
out.set(this.fingerprint, 0);
|
|
63
|
+
for (let i = 0; i < passphrase.length; i++) {
|
|
64
|
+
out[4 + i] = passphrase[i] ^ this.keyBytes[i % 16];
|
|
65
|
+
}
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
async unseal(sealed) {
|
|
69
|
+
if (sealed.length < 4) {
|
|
70
|
+
throw new Error("MemorySealingKeyProvider: sealed input too short");
|
|
71
|
+
}
|
|
72
|
+
for (let i = 0; i < 4; i++) {
|
|
73
|
+
if (sealed[i] !== this.fingerprint[i]) {
|
|
74
|
+
throw new Error(
|
|
75
|
+
`MemorySealingKeyProvider("${this.id}"): provider-id mismatch on unseal (sealed bytes were produced by a different provider)`
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const body = sealed.subarray(4);
|
|
80
|
+
const out = new Uint8Array(body.length);
|
|
81
|
+
for (let i = 0; i < body.length; i++) {
|
|
82
|
+
out[i] = body[i] ^ this.keyBytes[i % 16];
|
|
83
|
+
}
|
|
84
|
+
return out;
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
var MemoryRecipientSealer = class {
|
|
88
|
+
id;
|
|
89
|
+
keypair;
|
|
90
|
+
constructor(opts) {
|
|
91
|
+
this.id = opts.id;
|
|
92
|
+
this.keypair = crypto.subtle.generateKey(
|
|
93
|
+
{ name: "RSA-OAEP", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" },
|
|
94
|
+
true,
|
|
95
|
+
["encrypt", "decrypt"]
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
async publishRecipientHint() {
|
|
99
|
+
const { publicKey } = await this.keypair;
|
|
100
|
+
const spki = await crypto.subtle.exportKey("spki", publicKey);
|
|
101
|
+
const pem = "-----BEGIN PUBLIC KEY-----\n" + bytesToBase64(new Uint8Array(spki)).match(/.{1,64}/g).join("\n") + "\n-----END PUBLIC KEY-----\n";
|
|
102
|
+
return { v: 1, pid: this.id, alg: "rsa-oaep-sha256", material: { publicKeyPem: pem } };
|
|
103
|
+
}
|
|
104
|
+
async sealForRecipient(plaintext, hint) {
|
|
105
|
+
if (hint.v !== 1) {
|
|
106
|
+
throw new Error(`MemoryRecipientSealer.sealForRecipient: unsupported hint.v ${String(hint.v)} (expected 1)`);
|
|
107
|
+
}
|
|
108
|
+
if (hint.alg !== "rsa-oaep-sha256") {
|
|
109
|
+
throw new Error(`MemoryRecipientSealer.sealForRecipient: unsupported hint.alg '${String(hint.alg)}' (expected 'rsa-oaep-sha256')`);
|
|
110
|
+
}
|
|
111
|
+
const pem = hint.material["publicKeyPem"];
|
|
112
|
+
if (typeof pem !== "string") {
|
|
113
|
+
throw new Error("MemoryRecipientSealer.sealForRecipient: hint.material.publicKeyPem missing or not a string");
|
|
114
|
+
}
|
|
115
|
+
const b64 = pem.replace(/-----BEGIN PUBLIC KEY-----/, "").replace(/-----END PUBLIC KEY-----/, "").replace(/\s+/g, "");
|
|
116
|
+
const spki = base64ToBytes(b64);
|
|
117
|
+
const recipientPub = await crypto.subtle.importKey(
|
|
118
|
+
"spki",
|
|
119
|
+
spki,
|
|
120
|
+
{ name: "RSA-OAEP", hash: "SHA-256" },
|
|
121
|
+
false,
|
|
122
|
+
["encrypt"]
|
|
123
|
+
);
|
|
124
|
+
const cekBytes = crypto.getRandomValues(new Uint8Array(32));
|
|
125
|
+
const cek = await crypto.subtle.importKey("raw", cekBytes, "AES-GCM", false, ["encrypt"]);
|
|
126
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
127
|
+
const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv }, cek, plaintext));
|
|
128
|
+
const wrapped = new Uint8Array(await crypto.subtle.encrypt({ name: "RSA-OAEP" }, recipientPub, cekBytes));
|
|
129
|
+
cekBytes.fill(0);
|
|
130
|
+
if (wrapped.length !== 256) {
|
|
131
|
+
throw new Error(`MemoryRecipientSealer.sealForRecipient: expected 256-byte RSA-OAEP wrap, got ${wrapped.length}`);
|
|
132
|
+
}
|
|
133
|
+
const out = new Uint8Array(1 + 256 + 12 + ct.length);
|
|
134
|
+
out[0] = 1;
|
|
135
|
+
out.set(wrapped, 1);
|
|
136
|
+
out.set(iv, 1 + 256);
|
|
137
|
+
out.set(ct, 1 + 256 + 12);
|
|
138
|
+
return out;
|
|
139
|
+
}
|
|
140
|
+
async seal(plaintext) {
|
|
141
|
+
const hint = await this.publishRecipientHint();
|
|
142
|
+
return this.sealForRecipient(plaintext, hint);
|
|
143
|
+
}
|
|
144
|
+
async unseal(bytes) {
|
|
145
|
+
if (bytes.length < 1 + 256 + 12 + 16) {
|
|
146
|
+
throw new Error("MemoryRecipientSealer.unseal: sealed input too short");
|
|
147
|
+
}
|
|
148
|
+
if (bytes[0] !== 1) {
|
|
149
|
+
throw new Error(`MemoryRecipientSealer.unseal: unknown TLV version ${bytes[0]}`);
|
|
150
|
+
}
|
|
151
|
+
const wrapped = bytes.subarray(1, 1 + 256);
|
|
152
|
+
const iv = bytes.subarray(1 + 256, 1 + 256 + 12);
|
|
153
|
+
const ct = bytes.subarray(1 + 256 + 12);
|
|
154
|
+
const { privateKey } = await this.keypair;
|
|
155
|
+
const cekBytes = new Uint8Array(await crypto.subtle.decrypt({ name: "RSA-OAEP" }, privateKey, wrapped));
|
|
156
|
+
const cek = await crypto.subtle.importKey("raw", cekBytes, "AES-GCM", false, ["decrypt"]);
|
|
157
|
+
const pt = new Uint8Array(await crypto.subtle.decrypt({ name: "AES-GCM", iv }, cek, ct));
|
|
158
|
+
cekBytes.fill(0);
|
|
159
|
+
return pt;
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
var SEALED_PASSPHRASE_RECORD_ID = "sealed-passphrase";
|
|
163
|
+
function bytesToBase64(bytes) {
|
|
164
|
+
let binary = "";
|
|
165
|
+
for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
|
|
166
|
+
return btoa(binary);
|
|
167
|
+
}
|
|
168
|
+
function base64ToBytes(b64) {
|
|
169
|
+
const binary = atob(b64);
|
|
170
|
+
const out = new Uint8Array(binary.length);
|
|
171
|
+
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
|
172
|
+
return out;
|
|
173
|
+
}
|
|
174
|
+
function parseSealedEnvelope(raw) {
|
|
175
|
+
if (typeof raw !== "object" || raw === null) return void 0;
|
|
176
|
+
const r = raw;
|
|
177
|
+
if (r._noydb_sealed !== 1) return void 0;
|
|
178
|
+
if (r.v === 1 && typeof r.pid === "string" && typeof r.payload === "string") {
|
|
179
|
+
return {
|
|
180
|
+
_noydb_sealed: 1,
|
|
181
|
+
providerId: r.pid,
|
|
182
|
+
sealed: base64ToBytes(r.payload)
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
if (typeof r.providerId === "string" && typeof r.sealed === "string") {
|
|
186
|
+
return {
|
|
187
|
+
_noydb_sealed: 1,
|
|
188
|
+
providerId: r.providerId,
|
|
189
|
+
sealed: base64ToBytes(r.sealed)
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
return void 0;
|
|
193
|
+
}
|
|
194
|
+
async function saveSealedPassphrase(store, vault, payload) {
|
|
195
|
+
const persisted = {
|
|
196
|
+
v: 1,
|
|
197
|
+
_noydb_sealed: 1,
|
|
198
|
+
pid: payload.providerId,
|
|
199
|
+
payload: bytesToBase64(payload.sealed)
|
|
200
|
+
};
|
|
201
|
+
const prior = await store.get(vault, "_meta", SEALED_PASSPHRASE_RECORD_ID);
|
|
202
|
+
const env = {
|
|
203
|
+
_noydb: NOYDB_FORMAT_VERSION,
|
|
204
|
+
_v: (prior?._v ?? 0) + 1,
|
|
205
|
+
_ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
206
|
+
// AES-GCM bypassed — the sealing layer is the security boundary.
|
|
207
|
+
_iv: "",
|
|
208
|
+
_data: JSON.stringify(persisted)
|
|
209
|
+
};
|
|
210
|
+
await store.put(vault, "_meta", SEALED_PASSPHRASE_RECORD_ID, env);
|
|
211
|
+
}
|
|
212
|
+
async function loadSealedPassphrase(store, vault) {
|
|
213
|
+
const envelope = await store.get(vault, "_meta", SEALED_PASSPHRASE_RECORD_ID);
|
|
214
|
+
if (!envelope) return void 0;
|
|
215
|
+
try {
|
|
216
|
+
return parseSealedEnvelope(JSON.parse(envelope._data));
|
|
217
|
+
} catch {
|
|
218
|
+
return void 0;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
async function resolveManagedSecret(store, vault, provider) {
|
|
222
|
+
const existing = await loadSealedPassphrase(store, vault);
|
|
223
|
+
if (existing) {
|
|
224
|
+
if (existing.providerId !== provider.id) {
|
|
225
|
+
throw new Error(
|
|
226
|
+
`Managed-mode vault "${vault}" was sealed under provider id "${existing.providerId}" but the current SealingKeyProvider is "${provider.id}". Pass the same provider that originally enrolled the vault, or treat this as a fresh enrollment and clear \`_meta/sealed-passphrase\` first.`
|
|
227
|
+
);
|
|
228
|
+
}
|
|
229
|
+
const plaintext = await provider.unseal(existing.sealed);
|
|
230
|
+
return bytesToBase64(plaintext);
|
|
231
|
+
}
|
|
232
|
+
const random = new Uint8Array(32);
|
|
233
|
+
globalThis.crypto.getRandomValues(random);
|
|
234
|
+
const sealed = await provider.seal(random);
|
|
235
|
+
await saveSealedPassphrase(store, vault, { providerId: provider.id, sealed });
|
|
236
|
+
return bytesToBase64(random);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
export {
|
|
240
|
+
SCHEMAS_COLLECTION,
|
|
241
|
+
loadPersistedSchema,
|
|
242
|
+
savePersistedSchema,
|
|
243
|
+
MemorySealingKeyProvider,
|
|
244
|
+
MemoryRecipientSealer,
|
|
245
|
+
SEALED_PASSPHRASE_RECORD_ID,
|
|
246
|
+
parseSealedEnvelope,
|
|
247
|
+
saveSealedPassphrase,
|
|
248
|
+
loadSealedPassphrase,
|
|
249
|
+
resolveManagedSecret
|
|
250
|
+
};
|
|
251
|
+
//# sourceMappingURL=chunk-4X2S7PBF.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/persisted-schemas/storage.ts","../src/team/managed-passphrase.ts"],"sourcesContent":["/**\n * Read / write the per-collection persisted-schema envelope. Mirrors the\n * standard noy-db record envelope shape and is **AES-GCM encrypted with\n * the collection's DEK** — the schema body (field names, enum values,\n * constraints) is sensitive metadata, so it gets the same encryption\n * envelope as the records it describes.\n *\n * Storage layout:\n *\n * <vault>/_schemas/<collection> → EncryptedEnvelope\n *\n * The DEK passed to {@link savePersistedSchema} / {@link loadPersistedSchema}\n * is the same key the collection uses for its records.\n *\n * @module\n */\n\nimport { encrypt, decrypt } from '../crypto.js'\nimport { NOYDB_FORMAT_VERSION } from '../types.js'\nimport type { NoydbStore, EncryptedEnvelope } from '../types.js'\nimport type { PersistedSchemaEnvelope } from './types.js'\n\n/** Reserved collection name where persisted schemas live. */\nexport const SCHEMAS_COLLECTION = '_schemas' as const\n\n/**\n * Read and decrypt the persisted-schema envelope for one collection.\n * Returns `undefined` when no envelope has been written or when decryption\n * fails (e.g. wrong DEK passed). Tolerates corrupted records — JSON parse\n * failures surface as `undefined`, mirroring `_meta/handle`'s contract.\n */\nexport async function loadPersistedSchema(\n store: NoydbStore,\n vault: string,\n collection: string,\n dek: CryptoKey,\n): Promise<PersistedSchemaEnvelope | undefined> {\n const envelope = await store.get(vault, SCHEMAS_COLLECTION, collection)\n if (!envelope) return undefined\n try {\n const plaintext = await decrypt(envelope._iv, envelope._data, dek)\n const parsed = JSON.parse(plaintext) as PersistedSchemaEnvelope\n if (parsed._noydb_schema !== 1) return undefined\n return parsed\n } catch {\n return undefined\n }\n}\n\n/**\n * Encrypt and persist a schema envelope for one collection. Always\n * overwrites any prior write (callers gate on hash equality before calling\n * to avoid no-op writes).\n */\nexport async function savePersistedSchema(\n store: NoydbStore,\n vault: string,\n collection: string,\n dek: CryptoKey,\n payload: PersistedSchemaEnvelope,\n): Promise<void> {\n const json = JSON.stringify(payload)\n const { iv, data } = await encrypt(json, dek)\n const prior = await store.get(vault, SCHEMAS_COLLECTION, collection)\n const env: EncryptedEnvelope = {\n _noydb: NOYDB_FORMAT_VERSION,\n _v: (prior?._v ?? 0) + 1,\n _ts: new Date().toISOString(),\n _iv: iv,\n _data: data,\n }\n await store.put(vault, SCHEMAS_COLLECTION, collection, env)\n}\n","/**\n * Managed-passphrase mode — issue #14, rubber-hose-resistant vaults.\n *\n * A vault mode where the passphrase is machine-generated and never\n * exposed to the user, sealed under a developer-provided\n * {@link SealingKeyProvider} (macOS Keychain, Windows Credential\n * Manager, libsecret, AWS KMS, …). The user has no secret to give\n * up to coercion — they can't reveal what they don't know.\n *\n * ## Components in this file\n *\n * - {@link SealingKeyProvider} — the interface concrete providers\n * implement. Provider implementations live OUTSIDE hub (per-\n * platform packages).\n * - {@link MemorySealingKeyProvider} — in-memory test provider; uses\n * a deterministic per-instance \"key\" so two providers with\n * different ids cannot unseal each other's outputs.\n * - {@link RecipientHint} — public material a sender uses to seal\n * plaintext for a specific recipient; published by\n * {@link RecipientSealer.publishRecipientHint} and transported\n * out-of-band to the sender before bundle writes.\n * - {@link RecipientSealer} — interface for asymmetric/granted\n * providers that support recipient-target sealing (RSA-OAEP,\n * cloud-KMS asymmetric, etc.); distinct from self-only\n * {@link SealingKeyProvider} (macOS Keychain, WebAuthn-PRF).\n * - {@link MemoryRecipientSealer} — in-process reference\n * implementation of both `RecipientSealer` and\n * `SealingKeyProvider` using real WebCrypto RSA-OAEP + AES-GCM;\n * safe for tests and same-process sender/recipient scenarios.\n * - {@link loadSealedPassphrase} / {@link saveSealedPassphrase} —\n * plaintext envelope storage at `_meta/sealed-passphrase`.\n * Mirrors the `_meta/handle` and `_meta/public-envelope` AES-\n * GCM-bypassed patterns. The sealing layer (provider's job)\n * is the security boundary; hub doesn't have a key to encrypt\n * with at this layer — that's the whole point of the design.\n * - {@link resolveManagedSecret} — orchestrates the \"generate +\n * seal + persist on first open; unseal on reopen\" flow.\n * Returns the plaintext passphrase string that the rest of the\n * `createNoydb` keyring path consumes.\n *\n * Slice 1 of #14. Deferred to follow-ups:\n * - Block `rotate-passphrase` policy gate under managed mode.\n * - Mandatory strong-recovery enforcement (depends on #10).\n * - Recovery flow under managed mode (generates fresh sealed phrase).\n *\n * @see docs/subsystems/session-tiers.md → Managed-passphrase mode\n *\n * @module\n */\n\nimport type { NoydbStore, EncryptedEnvelope } from '../types.js'\nimport { NOYDB_FORMAT_VERSION } from '../types.js'\n\n/**\n * The contract concrete providers (per-platform key stores) implement\n * to seal and unseal a hub-generated random passphrase. The plaintext\n * passphrase NEVER leaves hub-controlled memory in unsealed form —\n * the provider receives the bytes, returns opaque sealed bytes, and\n * later reverses the operation. Hub treats the sealed bytes as\n * fully opaque.\n *\n * Implementations live OUTSIDE `@noy-db/hub` (separate packages\n * per the issue's \"Concrete providers (live outside hub)\" note):\n *\n * | Platform | Package (TBD) | Backing |\n * |---|---|---|\n * | macOS | `@noy-db/seal-macos-keychain` | Security.framework |\n * | Windows | `@noy-db/seal-wincred` | Credential Manager |\n * | Linux | `@noy-db/seal-libsecret` | libsecret / secret-service |\n * | Cloud / server | `@noy-db/seal-aws-kms` | AWS KMS Decrypt |\n */\nexport interface SealingKeyProvider {\n /**\n * Non-sensitive identifier disclosed in the persisted envelope.\n * Surfaced to consumers via `loadSealedPassphrase().providerId` so\n * a vault opened with the wrong provider class can detect the\n * mismatch and surface a clear error. NOT secret — fine to log.\n *\n * Suggested format: `<family>:<scope>` — e.g. `macos-keychain:com.acme.app`,\n * `aws-kms:arn:aws:kms:us-east-1:123:key/abc`. The hub never\n * parses this; it's purely audit metadata.\n */\n readonly id: string\n\n /** Seal raw passphrase bytes. Output bytes are opaque to hub. */\n seal(passphrase: Uint8Array): Promise<Uint8Array>\n\n /**\n * Reverse {@link seal}. MUST throw on tamper, wrong-provider, or\n * any other failure — hub treats a thrown error as \"this provider\n * cannot unlock this vault\" and surfaces it to the caller.\n */\n unseal(sealed: Uint8Array): Promise<Uint8Array>\n}\n\n/**\n * In-memory test provider. NOT secure — uses a deterministic\n * per-instance \"key\" (16-byte SHA-256 of `id`) XOR'd over the\n * passphrase plus a 4-byte provider-id fingerprint prefix. The XOR is\n * sufficient to make different `id` values produce mutually-unsealable\n * outputs (the contract tests for that), but offers ZERO real\n * confidentiality — never use outside tests.\n *\n * Replace with a real platform provider in production.\n */\nexport class MemorySealingKeyProvider implements SealingKeyProvider {\n readonly id: string\n private readonly fingerprint: Uint8Array\n private readonly keyBytes: Uint8Array\n\n constructor(opts: { id: string }) {\n this.id = opts.id\n // Deterministic 4-byte fingerprint of the provider id, prepended\n // to every sealed output so we can detect \"wrong provider\" at\n // unseal time without leaking anything sensitive about either\n // provider's actual key material.\n const encoded = new TextEncoder().encode(opts.id)\n let h = 0\n for (let i = 0; i < encoded.length; i++) {\n h = (h * 31 + encoded[i]!) >>> 0\n }\n this.fingerprint = new Uint8Array([\n (h >>> 24) & 0xff, (h >>> 16) & 0xff, (h >>> 8) & 0xff, h & 0xff,\n ])\n // Deterministic 16-byte \"key\" derived from the id by repeating\n // the fingerprint with offsets. Good enough for the XOR-stream\n // test cipher; never confuse this with real key derivation.\n this.keyBytes = new Uint8Array(16)\n for (let i = 0; i < 16; i++) {\n this.keyBytes[i] = this.fingerprint[i % 4]! ^ (i * 17)\n }\n }\n\n async seal(passphrase: Uint8Array): Promise<Uint8Array> {\n const out = new Uint8Array(4 + passphrase.length)\n out.set(this.fingerprint, 0)\n for (let i = 0; i < passphrase.length; i++) {\n out[4 + i] = passphrase[i]! ^ this.keyBytes[i % 16]!\n }\n return out\n }\n\n async unseal(sealed: Uint8Array): Promise<Uint8Array> {\n if (sealed.length < 4) {\n throw new Error('MemorySealingKeyProvider: sealed input too short')\n }\n for (let i = 0; i < 4; i++) {\n if (sealed[i] !== this.fingerprint[i]) {\n throw new Error(\n `MemorySealingKeyProvider(\"${this.id}\"): provider-id mismatch on unseal `\n + '(sealed bytes were produced by a different provider)',\n )\n }\n }\n const body = sealed.subarray(4)\n const out = new Uint8Array(body.length)\n for (let i = 0; i < body.length; i++) {\n out[i] = body[i]! ^ this.keyBytes[i % 16]!\n }\n return out\n }\n}\n\n/**\n * Public material a sender uses to seal-for-this-recipient. Published by\n * a recipient's RecipientSealer; transported to the sender out-of-band\n * (email, S3, in-app message). The sender obtains the hint, supplies it\n * to writeNoydbBundle's sealedCredentials.perUser[userId].hint, and the\n * hub seals each user's credential against it. Per foundation §11.4.\n */\nexport type RecipientHint = {\n readonly v: 1\n /** Recipient's provider id; matches the SealedAutoUnlockEntry.pid they'll unseal under. */\n readonly pid: string\n /** Algorithm the sender uses to produce the seal. Slice 1 ships RSA-OAEP-SHA256 only. */\n readonly alg: 'rsa-oaep-sha256'\n /** Public material — alg-specific. For 'rsa-oaep-sha256': { publicKeyPem: string }. */\n readonly material: Readonly<Record<string, unknown>>\n}\n\n/**\n * Handover-capable provider. Implemented additionally by asymmetric/granted\n * providers (cloud-KMS asymmetric, Azure RSA Key Vault, AWS KMS with grant).\n * Self-only providers (macOS Keychain, env-var, WebAuthn-PRF) do NOT\n * implement this — the §11.2 capability matrix lives in the type system.\n *\n * Per foundation §11.4. A function that requires recipient-target sealing\n * takes `RecipientSealer`, not `SealingKeyProvider` — the compiler rejects\n * passing a self-only provider at the spec site.\n */\nexport interface RecipientSealer {\n readonly id: string\n /** Produce hint material a sender uses to seal-for-this-recipient. */\n publishRecipientHint(): Promise<RecipientHint>\n /**\n * Seal plaintext for the recipient described by `hint`. Returns opaque\n * bytes — same contract as `SealingKeyProvider.seal()`. The bundle\n * layer base64-encodes the bytes into `SealedAutoUnlockEntry.sealed`\n * without inspecting them.\n */\n sealForRecipient(plaintext: Uint8Array, hint: RecipientHint): Promise<Uint8Array>\n}\n\n/**\n * Reference implementation of `RecipientSealer` + `SealingKeyProvider`.\n * Uses WebCrypto RSA-OAEP-SHA256 (2048-bit) to wrap a fresh 32-byte\n * AES-GCM CEK, AES-GCM-encrypts plaintext under it, and packs the\n * result into a self-describing TLV:\n *\n * byte 0 : version (0x01)\n * bytes 1..256 : RSA-OAEP-wrapped CEK (fixed 256 bytes at RSA-2048)\n * bytes 257..268: AES-GCM IV (12 bytes)\n * bytes 269.. : AES-GCM ciphertext ‖ 16-byte tag\n *\n * Implements BOTH interfaces. `seal(plaintext)` (self-target) is just\n * `sealForRecipient(plaintext, this own hint)` — same TLV. Convenient\n * for tests where one provider plays both ends. Real cloud providers\n * (`at-aws-kms`, etc.) will pick their own internal layouts; the only\n * contract is round-trip identity.\n *\n * SAFE for production within its scope — the cryptography is real\n * (RSA-OAEP + AES-GCM via WebCrypto), but the keypair lives in-process\n * and is regenerated on every construction. Not suitable as a managed\n * keychain; use it for tests and for shipping bundles where the\n * recipient instance lives in the same process as the sender (rare).\n */\nexport class MemoryRecipientSealer implements SealingKeyProvider, RecipientSealer {\n readonly id: string\n private readonly keypair: Promise<CryptoKeyPair>\n\n constructor(opts: { id: string }) {\n this.id = opts.id\n this.keypair = crypto.subtle.generateKey(\n { name: 'RSA-OAEP', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' },\n true,\n ['encrypt', 'decrypt'],\n )\n }\n\n async publishRecipientHint(): Promise<RecipientHint> {\n const { publicKey } = await this.keypair\n const spki = await crypto.subtle.exportKey('spki', publicKey)\n const pem = '-----BEGIN PUBLIC KEY-----\\n'\n + bytesToBase64(new Uint8Array(spki)).match(/.{1,64}/g)!.join('\\n')\n + '\\n-----END PUBLIC KEY-----\\n'\n return { v: 1, pid: this.id, alg: 'rsa-oaep-sha256', material: { publicKeyPem: pem } }\n }\n\n async sealForRecipient(plaintext: Uint8Array, hint: RecipientHint): Promise<Uint8Array> {\n if (hint.v !== 1) {\n throw new Error(`MemoryRecipientSealer.sealForRecipient: unsupported hint.v ${String(hint.v)} (expected 1)`)\n }\n if (hint.alg !== 'rsa-oaep-sha256') {\n throw new Error(`MemoryRecipientSealer.sealForRecipient: unsupported hint.alg '${String(hint.alg)}' (expected 'rsa-oaep-sha256')`)\n }\n const pem = hint.material['publicKeyPem']\n if (typeof pem !== 'string') {\n throw new Error('MemoryRecipientSealer.sealForRecipient: hint.material.publicKeyPem missing or not a string')\n }\n // Parse PEM → SPKI bytes.\n const b64 = pem.replace(/-----BEGIN PUBLIC KEY-----/, '').replace(/-----END PUBLIC KEY-----/, '').replace(/\\s+/g, '')\n const spki = base64ToBytes(b64)\n const recipientPub = await crypto.subtle.importKey(\n 'spki', spki as BufferSource,\n { name: 'RSA-OAEP', hash: 'SHA-256' },\n false, ['encrypt'],\n )\n // Mint fresh CEK + IV, AES-GCM encrypt plaintext.\n const cekBytes = crypto.getRandomValues(new Uint8Array(32))\n const cek = await crypto.subtle.importKey('raw', cekBytes as BufferSource, 'AES-GCM', false, ['encrypt'])\n const iv = crypto.getRandomValues(new Uint8Array(12))\n const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv: iv as BufferSource }, cek, plaintext as BufferSource))\n // RSA-OAEP-wrap the CEK bytes.\n const wrapped = new Uint8Array(await crypto.subtle.encrypt({ name: 'RSA-OAEP' }, recipientPub, cekBytes as BufferSource))\n cekBytes.fill(0)\n if (wrapped.length !== 256) {\n throw new Error(`MemoryRecipientSealer.sealForRecipient: expected 256-byte RSA-OAEP wrap, got ${wrapped.length}`)\n }\n // TLV layout.\n const out = new Uint8Array(1 + 256 + 12 + ct.length)\n out[0] = 0x01\n out.set(wrapped, 1)\n out.set(iv, 1 + 256)\n out.set(ct, 1 + 256 + 12)\n return out\n }\n\n async seal(plaintext: Uint8Array): Promise<Uint8Array> {\n const hint = await this.publishRecipientHint()\n return this.sealForRecipient(plaintext, hint)\n }\n\n async unseal(bytes: Uint8Array): Promise<Uint8Array> {\n if (bytes.length < 1 + 256 + 12 + 16) {\n throw new Error('MemoryRecipientSealer.unseal: sealed input too short')\n }\n if (bytes[0] !== 0x01) {\n throw new Error(`MemoryRecipientSealer.unseal: unknown TLV version ${bytes[0]}`)\n }\n const wrapped = bytes.subarray(1, 1 + 256)\n const iv = bytes.subarray(1 + 256, 1 + 256 + 12)\n const ct = bytes.subarray(1 + 256 + 12)\n const { privateKey } = await this.keypair\n const cekBytes = new Uint8Array(await crypto.subtle.decrypt({ name: 'RSA-OAEP' }, privateKey, wrapped as BufferSource))\n const cek = await crypto.subtle.importKey('raw', cekBytes as BufferSource, 'AES-GCM', false, ['decrypt'])\n const pt = new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: iv as BufferSource }, cek, ct as BufferSource))\n cekBytes.fill(0)\n return pt\n }\n}\n\n// ─── Persisted envelope ────────────────────────────────────────────────\n\n/** Reserved id for the managed-passphrase envelope under `_meta`. */\nexport const SEALED_PASSPHRASE_RECORD_ID = 'sealed-passphrase' as const\n\n/** Plaintext payload stored inside the `_meta/sealed-passphrase` envelope. */\nexport interface SealedPassphrase {\n readonly _noydb_sealed: 1\n readonly providerId: string\n /** Sealed bytes. Base64-encoded on the wire; decoded on load. */\n readonly sealed: Uint8Array\n}\n\n/**\n * Wire-format envelope persisted at `_meta/sealed-passphrase` for\n * managed-mode vaults. The provider produces raw sealed bytes via\n * {@link SealingKeyProvider.seal}; this wrapper carries the dispatch\n * metadata hub needs to pick the right provider on the unseal path.\n *\n * Stability boundary: once shipped, the wire format only grows by\n * adding optional fields. See the at-* sealing dimension foundation\n * doc, §11.9.1.\n *\n * v1 shape (this release): `{ v: 1, _noydb_sealed: 1, pid, payload }`.\n *\n * Legacy shape (pre.14, pre.15): `{ _noydb_sealed: 1, providerId, sealed }`\n * — accepted on read for backwards compatibility; never produced on\n * write going forward.\n */\nexport interface SealedEnvelope {\n /** Envelope schema version. v1 is the shape shipped in pre.16. */\n readonly v: 1\n /** Magic marker for forensics + legacy-shape detection. */\n readonly _noydb_sealed: 1\n /** Matches the producing provider's `.id`. Dispatch key on unseal. */\n readonly pid: string\n /** Sealed bytes from the provider, base64-encoded on the wire. */\n readonly payload: string\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n let binary = ''\n for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]!)\n return btoa(binary)\n}\n\nfunction base64ToBytes(b64: string): Uint8Array {\n const binary = atob(b64)\n const out = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i)\n return out\n}\n\n/**\n * Parse a `_meta/sealed-passphrase` `_data` JSON string into the\n * in-memory {@link SealedPassphrase} representation. Accepts both:\n *\n * 1. v1 wire format `{ v: 1, _noydb_sealed: 1, pid, payload }` —\n * the shape produced from pre.16 onward.\n * 2. Legacy wire format `{ _noydb_sealed: 1, providerId, sealed }` —\n * the shape produced in pre.14/pre.15. Read-only; never written\n * going forward.\n *\n * Returns `undefined` for any input that doesn't match either shape,\n * so callers can fall back to \"no managed-mode envelope present.\"\n *\n * @internal — exported only for the migration safety-net test suite.\n */\nexport function parseSealedEnvelope(raw: unknown): SealedPassphrase | undefined {\n if (typeof raw !== 'object' || raw === null) return undefined\n const r = raw as Record<string, unknown>\n if (r._noydb_sealed !== 1) return undefined\n\n // v1 shape — preferred.\n if (\n r.v === 1\n && typeof r.pid === 'string'\n && typeof r.payload === 'string'\n ) {\n return {\n _noydb_sealed: 1,\n providerId: r.pid,\n sealed: base64ToBytes(r.payload),\n }\n }\n\n // Legacy shape — pre.14 / pre.15. Accept on read for compat.\n if (\n typeof r.providerId === 'string'\n && typeof r.sealed === 'string'\n ) {\n return {\n _noydb_sealed: 1,\n providerId: r.providerId,\n sealed: base64ToBytes(r.sealed),\n }\n }\n\n return undefined\n}\n\nexport async function saveSealedPassphrase(\n store: NoydbStore,\n vault: string,\n payload: { readonly providerId: string; readonly sealed: Uint8Array },\n): Promise<void> {\n const persisted: SealedEnvelope = {\n v: 1,\n _noydb_sealed: 1,\n pid: payload.providerId,\n payload: bytesToBase64(payload.sealed),\n }\n const prior = await store.get(vault, '_meta', SEALED_PASSPHRASE_RECORD_ID)\n const env: EncryptedEnvelope = {\n _noydb: NOYDB_FORMAT_VERSION,\n _v: (prior?._v ?? 0) + 1,\n _ts: new Date().toISOString(),\n // AES-GCM bypassed — the sealing layer is the security boundary.\n _iv: '',\n _data: JSON.stringify(persisted),\n }\n await store.put(vault, '_meta', SEALED_PASSPHRASE_RECORD_ID, env)\n}\n\nexport async function loadSealedPassphrase(\n store: NoydbStore,\n vault: string,\n): Promise<SealedPassphrase | undefined> {\n const envelope = await store.get(vault, '_meta', SEALED_PASSPHRASE_RECORD_ID)\n if (!envelope) return undefined\n try {\n return parseSealedEnvelope(JSON.parse(envelope._data))\n } catch {\n return undefined\n }\n}\n\n// ─── createNoydb orchestration ─────────────────────────────────────────\n\n/**\n * Resolve the effective plaintext passphrase string for a managed-mode\n * vault. Two paths:\n *\n * 1. **First open (no envelope persisted):** generate a 256-bit random\n * via `crypto.getRandomValues`, base64-encode for use as a\n * passphrase string, seal the underlying bytes under the\n * provider, persist `_meta/sealed-passphrase`, return the\n * base64 string.\n *\n * 2. **Reopen (envelope exists):** read + unseal + decode → return.\n * A different provider whose `seal` output disagrees on the\n * stored bytes throws here, surfaced as a clear error.\n *\n * The returned string is the same shape that `secret:` would take in\n * standard mode — the rest of the keyring path consumes it\n * unchanged.\n *\n * @internal — called from `createNoydb` / `getKeyringInternal`.\n */\nexport async function resolveManagedSecret(\n store: NoydbStore,\n vault: string,\n provider: SealingKeyProvider,\n): Promise<string> {\n const existing = await loadSealedPassphrase(store, vault)\n if (existing) {\n if (existing.providerId !== provider.id) {\n throw new Error(\n `Managed-mode vault \"${vault}\" was sealed under provider id `\n + `\"${existing.providerId}\" but the current SealingKeyProvider is `\n + `\"${provider.id}\". Pass the same provider that originally enrolled `\n + 'the vault, or treat this as a fresh enrollment and clear '\n + '`_meta/sealed-passphrase` first.',\n )\n }\n const plaintext = await provider.unseal(existing.sealed)\n return bytesToBase64(plaintext)\n }\n\n // First open: mint a 256-bit random, seal, persist.\n const random = new Uint8Array(32)\n globalThis.crypto.getRandomValues(random)\n const sealed = await provider.seal(random)\n await saveSealedPassphrase(store, vault, { providerId: provider.id, sealed })\n return bytesToBase64(random)\n}\n"],"mappings":";;;;;;;;;AAuBO,IAAM,qBAAqB;AAQlC,eAAsB,oBACpB,OACA,OACA,YACA,KAC8C;AAC9C,QAAM,WAAW,MAAM,MAAM,IAAI,OAAO,oBAAoB,UAAU;AACtE,MAAI,CAAC,SAAU,QAAO;AACtB,MAAI;AACF,UAAM,YAAY,MAAM,QAAQ,SAAS,KAAK,SAAS,OAAO,GAAG;AAC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AM,MAAM,IAAI,OAAO,SAAS,6BAA6B,GAAG;AAClE;AAEA,eAAsB,qBACpB,OACA,OACuC;AACvC,QAAM,WAAW,MAAM,MAAM,IAAI,OAAO,SAAS,2BAA2B;AAC5E,MAAI,CAAC,SAAU,QAAO;AACtB,MAAI;AACF,WAAO,oBAAoB,KAAK,MAAM,SAAS,KAAK,CAAC;AAAA,EACvD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAwBA,eAAsB,qBACpB,OACA,OACA,UACiB;AACjB,QAAM,WAAW,MAAM,qBAAqB,OAAO,KAAK;AACxD,MAAI,UAAU;AACZ,QAAI,SAAS,eAAe,SAAS,IAAI;AACvC,YAAM,IAAI;AAAA,QACR,uBAAuB,KAAK,mCACtB,SAAS,UAAU,4CACnB,SAAS,EAAE;AAAA,MAGnB;AAAA,IACF;AACA,UAAM,YAAY,MAAM,SAAS,OAAO,SAAS,MAAM;AACvD,WAAO,cAAc,SAAS;AAAA,EAChC;AAGA,QAAM,SAAS,IAAI,WAAW,EAAE;AAChC,aAAW,OAAO,gBAAgB,MAAM;AACxC,QAAM,SAAS,MAAM,SAAS,KAAK,MAAM;AACzC,QAAM,qBAAqB,OAAO,OAAO,EAAE,YAAY,SAAS,IAAI,OAAO,CAAC;AAC5E,SAAO,cAAc,MAAM;AAC7B;","names":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
ValidationError
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-YDLAFP36.js";
|
|
4
4
|
|
|
5
5
|
// src/guards/with-guard.ts
|
|
6
6
|
function withGuard(strategy) {
|
|
@@ -16,4 +16,4 @@ function withGuard(strategy) {
|
|
|
16
16
|
export {
|
|
17
17
|
withGuard
|
|
18
18
|
};
|
|
19
|
-
//# sourceMappingURL=chunk-
|
|
19
|
+
//# sourceMappingURL=chunk-5YHWBPOT.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
TierNotGrantedError
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-YDLAFP36.js";
|
|
4
4
|
|
|
5
5
|
// src/team/tiers.ts
|
|
6
6
|
function dekKey(collection, tier) {
|
|
@@ -31,4 +31,4 @@ export {
|
|
|
31
31
|
effectiveClearance,
|
|
32
32
|
assertTierAccess
|
|
33
33
|
};
|
|
34
|
-
//# sourceMappingURL=chunk-
|
|
34
|
+
//# sourceMappingURL=chunk-6S3LLAQ5.js.map
|
|
@@ -3,18 +3,18 @@ import {
|
|
|
3
3
|
hashEntry,
|
|
4
4
|
paddedIndex,
|
|
5
5
|
sha256Hex
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-NCO2JGKK.js";
|
|
7
7
|
import {
|
|
8
8
|
NOYDB_FORMAT_VERSION
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-FXQYZNOW.js";
|
|
10
10
|
import {
|
|
11
11
|
decrypt,
|
|
12
12
|
encrypt
|
|
13
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-UOF74WQY.js";
|
|
14
14
|
import {
|
|
15
15
|
ConflictError,
|
|
16
16
|
LedgerContentionError
|
|
17
|
-
} from "./chunk-
|
|
17
|
+
} from "./chunk-YDLAFP36.js";
|
|
18
18
|
|
|
19
19
|
// src/history/ledger/patch.ts
|
|
20
20
|
function computePatch(prev, next) {
|
|
@@ -683,4 +683,4 @@ export {
|
|
|
683
683
|
LEDGER_DELTAS_COLLECTION,
|
|
684
684
|
LedgerStore
|
|
685
685
|
};
|
|
686
|
-
//# sourceMappingURL=chunk-
|
|
686
|
+
//# sourceMappingURL=chunk-74JEQFMT.js.map
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ATTESTATIONS_COLLECTION,
|
|
3
|
+
loadOrCreateSigner
|
|
4
|
+
} from "./chunk-ZUMGGHRB.js";
|
|
5
|
+
import {
|
|
6
|
+
generateULID
|
|
7
|
+
} from "./chunk-FZU343FL.js";
|
|
8
|
+
import {
|
|
9
|
+
NOYDB_FORMAT_VERSION
|
|
10
|
+
} from "./chunk-FXQYZNOW.js";
|
|
11
|
+
import {
|
|
12
|
+
encrypt
|
|
13
|
+
} from "./chunk-UOF74WQY.js";
|
|
14
|
+
import {
|
|
15
|
+
AttestationError
|
|
16
|
+
} from "./chunk-YDLAFP36.js";
|
|
17
|
+
|
|
18
|
+
// src/attestation/issue.ts
|
|
19
|
+
import {
|
|
20
|
+
computeFieldHashes,
|
|
21
|
+
signPayloadCore,
|
|
22
|
+
encodeQr,
|
|
23
|
+
bytesToB64url
|
|
24
|
+
} from "@noy-db/attestation";
|
|
25
|
+
async function issueAttestationCore(ctx, args) {
|
|
26
|
+
if (ctx.role !== "owner") {
|
|
27
|
+
throw new AttestationError(`issueAttestation requires the 'owner' role; caller is '${ctx.role}'. Issuing a signed attestation is the firm's identity operation.`);
|
|
28
|
+
}
|
|
29
|
+
const src = await ctx.readRecord(args.collection, args.id);
|
|
30
|
+
if (!src) throw new AttestationError(`issueAttestation: source record '${args.collection}/${args.id}' not found.`);
|
|
31
|
+
const dek = await ctx.getDEK();
|
|
32
|
+
const signer = await loadOrCreateSigner(ctx.store, ctx.vault, () => Promise.resolve(dek));
|
|
33
|
+
const saltB64 = bytesToB64url(crypto.getRandomValues(new Uint8Array(16)));
|
|
34
|
+
let fieldHashes;
|
|
35
|
+
try {
|
|
36
|
+
fieldHashes = await computeFieldHashes(saltB64, args.fieldSchema, src.record);
|
|
37
|
+
} catch (e) {
|
|
38
|
+
throw new AttestationError(`issueAttestation: ${e.message}`);
|
|
39
|
+
}
|
|
40
|
+
const docId = generateULID();
|
|
41
|
+
const sig = await signPayloadCore({ v: 1, docId, salt: saltB64, keyId: signer.keyId, fieldHashes }, signer.privateKeyPkcs8B64);
|
|
42
|
+
const payload = { v: 1, docId, salt: saltB64, alg: "ed25519", keyId: signer.keyId, fieldHashes, sig };
|
|
43
|
+
const index = {
|
|
44
|
+
docId,
|
|
45
|
+
issuedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
46
|
+
keyId: signer.keyId,
|
|
47
|
+
fieldPaths: args.fieldSchema.fields.map((f) => f.path),
|
|
48
|
+
sourceRefs: [{ collection: args.collection, id: args.id, version: src.version }]
|
|
49
|
+
};
|
|
50
|
+
const { iv, data } = await encrypt(JSON.stringify(index), dek);
|
|
51
|
+
const env = { _noydb: NOYDB_FORMAT_VERSION, _v: 1, _ts: index.issuedAt, _iv: iv, _data: data };
|
|
52
|
+
await ctx.store.put(ctx.vault, ATTESTATIONS_COLLECTION, docId, env);
|
|
53
|
+
return { docId, qr: encodeQr(payload), payload, keyId: signer.keyId, publicKeyB64: signer.publicKeyB64 };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export {
|
|
57
|
+
issueAttestationCore
|
|
58
|
+
};
|
|
59
|
+
//# sourceMappingURL=chunk-75QDHSE4.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/attestation/issue.ts"],"sourcesContent":["import type { NoydbStore, EncryptedEnvelope } from '../types.js'\nimport { NOYDB_FORMAT_VERSION } from '../types.js'\nimport { encrypt } from '../crypto.js'\nimport { AttestationError } from '../errors.js'\nimport { generateULID } from '../bundle/ulid.js'\nimport { loadOrCreateSigner, ATTESTATIONS_COLLECTION } from './signer.js'\nimport {\n computeFieldHashes, signPayloadCore, encodeQr, bytesToB64url,\n type AttestationFieldSchema, type QrPayload,\n} from '@noy-db/attestation'\n\n/** Everything issueAttestationCore needs from the Vault, injected for testability. */\nexport interface IssueContext {\n readonly store: NoydbStore\n readonly vault: string\n readonly role: string\n /** The _attestations collection DEK (AES-KW-wrapped under KEK by the keyring). */\n getDEK(): Promise<CryptoKey>\n /** Decrypted source record + its envelope version, or null if absent. */\n readRecord(collection: string, id: string): Promise<{ record: Record<string, unknown>; version: number } | null>\n}\n\nexport interface IssueArgs {\n readonly collection: string\n readonly id: string\n readonly fieldSchema: AttestationFieldSchema\n}\nexport interface IssueResult {\n readonly docId: string\n readonly qr: string\n readonly payload: QrPayload\n readonly keyId: string\n readonly publicKeyB64: string\n}\n\nexport async function issueAttestationCore(ctx: IssueContext, args: IssueArgs): Promise<IssueResult> {\n if (ctx.role !== 'owner') {\n throw new AttestationError(`issueAttestation requires the 'owner' role; caller is '${ctx.role}'. Issuing a signed attestation is the firm's identity operation.`)\n }\n const src = await ctx.readRecord(args.collection, args.id)\n if (!src) throw new AttestationError(`issueAttestation: source record '${args.collection}/${args.id}' not found.`)\n\n const dek = await ctx.getDEK()\n // ONE signer implementation, from signer.ts. Lazily minted + persisted.\n const signer = await loadOrCreateSigner(ctx.store, ctx.vault, () => Promise.resolve(dek))\n\n const saltB64 = bytesToB64url(crypto.getRandomValues(new Uint8Array(16)))\n let fieldHashes: string[]\n try {\n fieldHashes = await computeFieldHashes(saltB64, args.fieldSchema, src.record)\n } catch (e) {\n throw new AttestationError(`issueAttestation: ${(e as Error).message}`)\n }\n const docId = generateULID()\n\n const sig = await signPayloadCore({ v: 1, docId, salt: saltB64, keyId: signer.keyId, fieldHashes }, signer.privateKeyPkcs8B64)\n const payload: QrPayload = { v: 1, docId, salt: saltB64, alg: 'ed25519', keyId: signer.keyId, fieldHashes, sig }\n\n const index = {\n docId, issuedAt: new Date().toISOString(), keyId: signer.keyId,\n fieldPaths: args.fieldSchema.fields.map((f) => f.path),\n sourceRefs: [{ collection: args.collection, id: args.id, version: src.version }],\n }\n const { iv, data } = await encrypt(JSON.stringify(index), dek)\n const env: EncryptedEnvelope = { _noydb: NOYDB_FORMAT_VERSION, _v: 1, _ts: index.issuedAt, _iv: iv, _data: data }\n await ctx.store.put(ctx.vault, ATTESTATIONS_COLLECTION, docId, env)\n\n return { docId, qr: encodeQr(payload), payload, keyId: signer.keyId, publicKeyB64: signer.publicKeyB64 }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAMA;AAAA,EACE;AAAA,EAAoB;AAAA,EAAiB;AAAA,EAAU;AAAA,OAE1C;AA0BP,e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QAAM,MAAyB,EAAE,QAAQ,sBAAsB,IAAI,GAAG,KAAK,MAAM,UAAU,KAAK,IAAI,OAAO,KAAK;AAChH,QAAM,IAAI,MAAM,IAAI,IAAI,OAAO,yBAAyB,OAAO,GAAG;AAElE,SAAO,EAAE,OAAO,IAAI,SAAS,OAAO,GAAG,SAAS,OAAO,OAAO,OAAO,cAAc,OAAO,aAAa;AACzG;","names":[]}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import {
|
|
2
|
+
LocaleNotSpecifiedError,
|
|
3
|
+
MissingTranslationError
|
|
4
|
+
} from "./chunk-YDLAFP36.js";
|
|
5
|
+
|
|
6
|
+
// src/i18n/core.ts
|
|
7
|
+
function i18nText(options) {
|
|
8
|
+
return { _noydbI18nText: true, options };
|
|
9
|
+
}
|
|
10
|
+
function isI18nTextDescriptor(x) {
|
|
11
|
+
return typeof x === "object" && x !== null && x._noydbI18nText === true;
|
|
12
|
+
}
|
|
13
|
+
function validateI18nTextValue(value, field, descriptor) {
|
|
14
|
+
const { options } = descriptor;
|
|
15
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
16
|
+
throw new MissingTranslationError(
|
|
17
|
+
field,
|
|
18
|
+
options.languages,
|
|
19
|
+
`Field "${field}" must be a { [locale]: string } map, got ${typeof value}.`
|
|
20
|
+
);
|
|
21
|
+
}
|
|
22
|
+
const map = value;
|
|
23
|
+
for (const [locale, v] of Object.entries(map)) {
|
|
24
|
+
if (typeof v !== "string") {
|
|
25
|
+
throw new MissingTranslationError(
|
|
26
|
+
field,
|
|
27
|
+
[locale],
|
|
28
|
+
`Field "${field}": locale "${locale}" must be a string, got ${typeof v}.`
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const { required } = options;
|
|
33
|
+
if (required === "all") {
|
|
34
|
+
const missing = options.languages.filter(
|
|
35
|
+
(lang) => !(lang in map) || map[lang] === ""
|
|
36
|
+
);
|
|
37
|
+
if (missing.length > 0) {
|
|
38
|
+
throw new MissingTranslationError(
|
|
39
|
+
field,
|
|
40
|
+
missing,
|
|
41
|
+
`Field "${field}" requires all declared languages. Missing: ${missing.join(", ")}.`
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
} else if (required === "any") {
|
|
45
|
+
const present = options.languages.some(
|
|
46
|
+
(lang) => lang in map && map[lang] !== ""
|
|
47
|
+
);
|
|
48
|
+
if (!present) {
|
|
49
|
+
throw new MissingTranslationError(
|
|
50
|
+
field,
|
|
51
|
+
options.languages,
|
|
52
|
+
`Field "${field}" requires at least one declared language. None present.`
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
} else {
|
|
56
|
+
const requiredList = required;
|
|
57
|
+
const missing = requiredList.filter(
|
|
58
|
+
(lang) => !(lang in map) || map[lang] === ""
|
|
59
|
+
);
|
|
60
|
+
if (missing.length > 0) {
|
|
61
|
+
throw new MissingTranslationError(
|
|
62
|
+
field,
|
|
63
|
+
missing,
|
|
64
|
+
`Field "${field}" requires: ${requiredList.join(", ")}. Missing: ${missing.join(", ")}.`
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
function resolveI18nText(value, locale, fallback, field) {
|
|
70
|
+
if (locale === "raw") {
|
|
71
|
+
return value;
|
|
72
|
+
}
|
|
73
|
+
if (!locale) {
|
|
74
|
+
throw new LocaleNotSpecifiedError(field ?? "<unknown>");
|
|
75
|
+
}
|
|
76
|
+
if (value[locale] !== void 0 && value[locale] !== "") {
|
|
77
|
+
return value[locale];
|
|
78
|
+
}
|
|
79
|
+
const chain = Array.isArray(fallback) ? fallback : fallback ? [fallback] : [];
|
|
80
|
+
for (const fb of chain) {
|
|
81
|
+
if (fb === "any") {
|
|
82
|
+
const any = Object.values(value).find((v) => v !== "");
|
|
83
|
+
if (any !== void 0) return any;
|
|
84
|
+
} else if (value[fb] !== void 0 && value[fb] !== "") {
|
|
85
|
+
return value[fb];
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
throw new LocaleNotSpecifiedError(
|
|
89
|
+
field ?? "<unknown>",
|
|
90
|
+
`No translation available for locale "${locale}"` + (chain.length > 0 ? ` or fallback chain [${chain.join(", ")}]` : "") + "."
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
function applyI18nLocale(record, i18nFields, locale, fallback) {
|
|
94
|
+
const fieldNames = Object.keys(i18nFields);
|
|
95
|
+
if (fieldNames.length === 0) return record;
|
|
96
|
+
const result = { ...record };
|
|
97
|
+
for (const field of fieldNames) {
|
|
98
|
+
const raw = result[field];
|
|
99
|
+
if (raw === void 0 || raw === null) continue;
|
|
100
|
+
if (typeof raw !== "object" || Array.isArray(raw)) continue;
|
|
101
|
+
result[field] = resolveI18nText(
|
|
102
|
+
raw,
|
|
103
|
+
locale,
|
|
104
|
+
fallback,
|
|
105
|
+
field
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
return result;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export {
|
|
112
|
+
i18nText,
|
|
113
|
+
isI18nTextDescriptor,
|
|
114
|
+
validateI18nTextValue,
|
|
115
|
+
resolveI18nText,
|
|
116
|
+
applyI18nLocale
|
|
117
|
+
};
|
|
118
|
+
//# sourceMappingURL=chunk-A6SWRXUQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/i18n/core.ts"],"sourcesContent":["/**\n * i18nText schema type —\n *\n * `i18nText({ languages, required })` creates a descriptor for a\n * multi-language content field whose value is stored as a\n * `{ [locale]: string }` map (e.g. `{ en: 'Consulting', th: 'ที่ปรึกษา' }`).\n *\n * On put, the descriptor validates that required languages are present.\n * On read (when a `locale` option is passed), the map is collapsed to the\n * caller's locale string via the fallback chain.\n *\n * Design decisions\n * ────────────────\n *\n * **Descriptor pattern (not a Zod type).**\n * `i18nText()` returns a plain descriptor object used in the collection's\n * `i18nFields` option — same pattern as `ref()` / `dictKey()`. This keeps\n * `@noy-db/core` at zero runtime dependencies and avoids Zod v3 field-type\n * constraints. TypeScript inference is handled via the descriptor's type.\n *\n * **Enforcement at the collection boundary.**\n * The `required` option is checked by `Collection.put()` via the compartment's\n * registered `i18nFields`. Failed validation throws `MissingTranslationError`\n * — a distinct class from `SchemaValidationError` so callers can tell\n * \"wrong shape\" from \"missing translations\".\n *\n * **Resolution is post-decryption.**\n * Locale resolution happens AFTER `decryptRecord()`, as a pure in-memory\n * transform. No additional crypto work is needed. The resolved record is\n * returned in place of the stored one, with i18nText fields replaced by\n * their locale-resolved strings.\n *\n * **`locale: 'raw'`.**\n * Passing `{ locale: 'raw' }` skips resolution and returns the full\n * `{ [locale]: string }` map — useful for bilingual exports, admin UIs,\n * and any context where all translations must be visible at once.\n *\n * **Out of scope.**\n * Pluralization, RTL rendering, date/number formatting, per-locale CRDT\n * merging.\n */\n\nimport { MissingTranslationError, LocaleNotSpecifiedError } from '../errors.js'\n\n// ─── i18nText descriptor ───────────────────────────────────────────────\n\n/**\n * Options for `i18nText()`.\n *\n * `languages` declares the full set of supported locales. `required`\n * controls which must be present on every `put()`.\n *\n * `autoTranslate` is the per-field opt-in for the `plaintextTranslator`\n * hook. When `true` and a `plaintextTranslator` is configured\n * on `createNoydb()`, missing translations are generated before `put()`.\n * Default: `false`.\n */\nexport interface I18nTextOptions {\n /** All supported locale codes (BCP 47). */\n readonly languages: readonly string[]\n /**\n * Which locales must be present on every `put()`.\n *\n * - `'all'` — every declared language must be present.\n * - `'any'` — at least one declared language must be present.\n * - `string[]` — listed locales are required; others are optional.\n */\n readonly required: 'all' | 'any' | readonly string[]\n /**\n * Per-field opt-in for the `plaintextTranslator` hook.\n * When `true`, missing required translations are auto-generated\n * before `put()` if a translator is configured. Default: `false`.\n */\n readonly autoTranslate?: boolean\n}\n\n/**\n * Descriptor returned by `i18nText()`. Attach to the collection's\n * `i18nFields` option:\n *\n * ```ts\n * const lineItems = company.collection<LineItem>('line-items', {\n * i18nFields: {\n * description: i18nText({ languages: ['en', 'th'], required: 'all' }),\n * },\n * })\n * ```\n */\nexport interface I18nTextDescriptor {\n readonly _noydbI18nText: true\n readonly options: I18nTextOptions\n}\n\n/**\n * Create an `I18nTextDescriptor` for a multi-language content field.\n *\n * @param options Language list + enforcement mode.\n *\n * @example\n * ```ts\n * i18nText({ languages: ['en', 'th'], required: 'all' })\n * i18nText({ languages: ['en', 'th'], required: ['th'], autoTranslate: true })\n * ```\n */\nexport function i18nText(options: I18nTextOptions): I18nTextDescriptor {\n return { _noydbI18nText: true, options }\n}\n\n/** Runtime predicate for detecting an `I18nTextDescriptor`. */\nexport function isI18nTextDescriptor(x: unknown): x is I18nTextDescriptor {\n return (\n typeof x === 'object' &&\n x !== null &&\n (x as { _noydbI18nText?: unknown })._noydbI18nText === true\n )\n}\n\n// ─── Validation helpers ────────────────────────────────────────────────\n\n/**\n * Validate that a value is a valid `{ [locale]: string }` map and that\n * all required locales are present. Throws `MissingTranslationError`\n * when the required constraint is violated.\n *\n * Called by `Collection.put()` for each registered `i18nField`.\n *\n * @param value The raw field value from the record being put.\n * @param field The field name (used in the thrown error message).\n * @param descriptor The `i18nText()` descriptor for this field.\n */\nexport function validateI18nTextValue(\n value: unknown,\n field: string,\n descriptor: I18nTextDescriptor,\n): void {\n const { options } = descriptor\n\n // Must be a non-null object\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new MissingTranslationError(\n field,\n options.languages,\n `Field \"${field}\" must be a { [locale]: string } map, got ${typeof value}.`,\n )\n }\n\n const map = value as Record<string, unknown>\n\n // All values must be strings\n for (const [locale, v] of Object.entries(map)) {\n if (typeof v !== 'string') {\n throw new MissingTranslationError(\n field,\n [locale],\n `Field \"${field}\": locale \"${locale}\" must be a string, got ${typeof v}.`,\n )\n }\n }\n\n // Check required constraint\n const { required } = options\n if (required === 'all') {\n const missing = options.languages.filter(\n (lang) => !(lang in map) || map[lang] === '',\n )\n if (missing.length > 0) {\n throw new MissingTranslationError(\n field,\n missing,\n `Field \"${field}\" requires all declared languages. Missing: ${missing.join(', ')}.`,\n )\n }\n } else if (required === 'any') {\n const present = options.languages.some(\n (lang) => lang in map && map[lang] !== '',\n )\n if (!present) {\n throw new MissingTranslationError(\n field,\n options.languages,\n `Field \"${field}\" requires at least one declared language. None present.`,\n )\n }\n } else {\n // string[] — named required locales; TypeScript narrows required to readonly string[]\n const requiredList = required\n const missing = requiredList.filter(\n (lang) => !(lang in map) || map[lang] === '',\n )\n if (missing.length > 0) {\n throw new MissingTranslationError(\n field,\n missing,\n `Field \"${field}\" requires: ${requiredList.join(', ')}. Missing: ${missing.join(', ')}.`,\n )\n }\n }\n}\n\n// ─── Locale resolution ─────────────────────────────────────────────────\n\n/**\n * Resolve an i18nText value (`{ [locale]: string }` map) to a string\n * for the given locale.\n *\n * @param value The stored locale map.\n * @param locale The requested locale code, or `'raw'` to return the map.\n * @param fallback Single locale or ordered list; use `'any'` as the last\n * element to fall back to any available translation.\n * @param field Field name used in `LocaleNotSpecifiedError` messages.\n * @returns The resolved string, OR the original map when `locale === 'raw'`.\n */\nexport function resolveI18nText(\n value: Record<string, string>,\n locale: string,\n fallback?: string | readonly string[],\n field?: string,\n): string | Record<string, string> {\n if (locale === 'raw') {\n return value\n }\n\n if (!locale) {\n throw new LocaleNotSpecifiedError(field ?? '<unknown>')\n }\n\n // Primary locale\n if (value[locale] !== undefined && value[locale] !== '') {\n return value[locale]\n }\n\n // Fallback chain\n const chain: readonly string[] = Array.isArray(fallback)\n ? fallback\n : fallback\n ? [fallback]\n : []\n\n for (const fb of chain) {\n if (fb === 'any') {\n const any = Object.values(value).find((v) => v !== '')\n if (any !== undefined) return any\n } else if (value[fb] !== undefined && value[fb] !== '') {\n return value[fb]\n }\n }\n\n throw new LocaleNotSpecifiedError(\n field ?? '<unknown>',\n `No translation available for locale \"${locale}\"` +\n (chain.length > 0 ? ` or fallback chain [${chain.join(', ')}]` : '') +\n '.',\n )\n}\n\n/**\n * Apply locale resolution to a single record, in-place over a copy.\n *\n * For each field registered as an `i18nText` descriptor:\n * - If `locale === 'raw'`, the field value is left as the stored map.\n * - Otherwise, the field value is replaced with the resolved string.\n *\n * Records that are not plain objects (null, array, primitives) are\n * returned unchanged.\n *\n * @param record The decrypted record.\n * @param i18nFields Map of field name → `I18nTextDescriptor`.\n * @param locale The requested locale (or `'raw'`).\n * @param fallback Fallback chain (optional).\n */\nexport function applyI18nLocale(\n record: Record<string, unknown>,\n i18nFields: Record<string, I18nTextDescriptor>,\n locale: string,\n fallback?: string | readonly string[],\n): Record<string, unknown> {\n const fieldNames = Object.keys(i18nFields)\n if (fieldNames.length === 0) return record\n\n const result = { ...record }\n\n for (const field of fieldNames) {\n const raw = result[field]\n if (raw === undefined || raw === null) continue\n if (typeof raw !== 'object' || Array.isArray(raw)) continue\n\n result[field] = resolveI18nText(\n raw as Record<string, string>,\n locale,\n fallback,\n field,\n )\n }\n\n return result\n}\n"],"mappings":";;;;;;AAwGO,SAAS,SAAS,SAA8C;AACrE,SAAO,EAAE,gBAAgB,MAAM,QAAQ;AACzC;AAGO,SAAS,qBAAqB,GAAqC;AACxE,SACE,OAAO,MAAM,YACb,MAAM,QACL,EAAmC,mBAAmB;AAE3D;AAeO,SAAS,sBACd,OACA,OACA,YACM;AACN,QAAM,EAAE,QAAQ,IAAI;AAGpB,MAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GAAG;AACvE,UAAM,IAAI;AAAA,MACR;AAAA,MACA,QAAQ;AAAA,MACR,UAAU,KAAK,6CAA6C,OAAO,KAAK;AAAA,IAC1E;AAAA,EACF;AAEA,QAAM,MAAM;AAGZ,aAAW,CAAC,QAAQ,CAAC,KAAK,OAAO,QAAQ,GAAG,GAAG;AAC7C,QAAI,OAAO,MAAM,UAAU;AACzB,YAAM,IAAI;AAAA,QACR;AAAA,QACA,CAAC,MAAM;AAAA,QACP,UAAU,KAAK,cAAc,MAAM,2BAA2B,OAAO,CAAC;AAAA,MACxE;AAAA,IACF;AAAA,EACF;AAGA,QAAM,EAA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,QAAI,OAAO,OAAO;AAChB,YAAM,MAAM,OAAO,OAAO,KAAK,EAAE,KAAK,CAAC,MAAM,MAAM,EAAE;AACrD,UAAI,QAAQ,OAAW,QAAO;AAAA,IAChC,WAAW,MAAM,EAAE,MAAM,UAAa,MAAM,EAAE,MAAM,IAAI;AACtD,aAAO,MAAM,EAAE;AAAA,IACjB;AAAA,EACF;AAEA,QAAM,IAAI;AAAA,IACR,SAAS;AAAA,IACT,wCAAwC,MAAM,OAC3C,MAAM,SAAS,IAAI,uBAAuB,MAAM,KAAK,IAAI,CAAC,MAAM,MACjE;AAAA,EACJ;AACF;AAiBO,SAAS,gBACd,QACA,YACA,QACA,UACyB;AACzB,QAAM,aAAa,OAAO,KAAK,UAAU;AACzC,MAAI,WAAW,WAAW,EAAG,QAAO;AAEpC,QAAM,SAAS,EAAE,GAAG,OAAO;AAE3B,aAAW,SAAS,YAAY;AAC9B,UAAM,MAAM,OAAO,KAAK;AACxB,QAAI,QAAQ,UAAa,QAAQ,KAAM;AACvC,QAAI,OAAO,QAAQ,YAAY,MAAM,QAAQ,GAAG,EAAG;AAEnD,WAAO,KAAK,IAAI;AAAA,MACd;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
|
|
@@ -30,7 +30,7 @@ async function resolveStaleMVOnRead(accessor, outputCollection) {
|
|
|
30
30
|
continue;
|
|
31
31
|
}
|
|
32
32
|
if (executor === null) {
|
|
33
|
-
({ MaterializedViewExecutor: executor } = await import("./executor-
|
|
33
|
+
({ MaterializedViewExecutor: executor } = await import("./executor-KT2IOZVP.js"));
|
|
34
34
|
}
|
|
35
35
|
await executor.refresh(reg, {
|
|
36
36
|
getCollection: (n) => accessor.getCollection(n),
|
|
@@ -50,4 +50,4 @@ export {
|
|
|
50
50
|
resolveStaleMVOnRead,
|
|
51
51
|
clearMVStale
|
|
52
52
|
};
|
|
53
|
-
//# sourceMappingURL=chunk-
|
|
53
|
+
//# sourceMappingURL=chunk-BFI3RS42.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
ValidationError
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-YDLAFP36.js";
|
|
4
4
|
|
|
5
5
|
// src/derivations/with-derivation.ts
|
|
6
6
|
function withDerivation(spec) {
|
|
@@ -48,4 +48,4 @@ function withDerivation(spec) {
|
|
|
48
48
|
export {
|
|
49
49
|
withDerivation
|
|
50
50
|
};
|
|
51
|
-
//# sourceMappingURL=chunk-
|
|
51
|
+
//# sourceMappingURL=chunk-EMEX37ZN.js.map
|