@tearleads/client-sdk 0.1.109 → 0.1.110
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/data/blobs/attachments/events.js +2 -3
- package/data/blobs/attachments/events.js.map +1 -1
- package/data/containers/shared/events.js +3 -4
- package/data/containers/shared/events.js.map +1 -1
- package/data/documents/shared/containerKek/containerKekPathHistory.js +3 -3
- package/data/documents/shared/containerKek/containerKekPathHistory.js.map +1 -1
- package/data/documents/shared/events.js +4 -4
- package/data/documents/shared/events.js.map +1 -1
- package/data/keying/canonicalJson.js +3 -65
- package/data/keying/canonicalJson.js.map +1 -1
- package/data/keyingProjectionVerification/checkpoints/bundleVerification.js +3 -3
- package/data/keyingProjectionVerification/checkpoints/bundleVerification.js.map +1 -1
- package/data/keyingProjectionVerification/checkpoints/verifiedBundleBytes.js +2 -3
- package/data/keyingProjectionVerification/checkpoints/verifiedBundleBytes.js.map +1 -1
- package/data/keyingProjectionVerification/container/containerManifestVerification.js +3 -3
- package/data/keyingProjectionVerification/container/containerManifestVerification.js.map +1 -1
- package/data/keyingProjectionVerification/document/documentManifestVerification.js +2 -3
- package/data/keyingProjectionVerification/document/documentManifestVerification.js.map +1 -1
- package/data/keyingProjectionVerification/documentPurge/documentPurgeDocumentChainVerification.js +2 -3
- package/data/keyingProjectionVerification/documentPurge/documentPurgeDocumentChainVerification.js.map +1 -1
- package/data/keyingProjectionVerification/readers.js +3 -3
- package/data/keyingProjectionVerification/readers.js.map +1 -1
- package/internal/crypto/index.d.ts +1 -1
- package/internal/crypto/index.js +1 -1
- package/internal/crypto/index.js.map +1 -1
- package/internal/crypto/keying/canonicalJsonGuard.d.ts +3 -0
- package/internal/crypto/keying/canonicalJsonGuard.js +60 -0
- package/internal/crypto/keying/canonicalJsonGuard.js.map +1 -0
- package/internal/crypto/keying/index.d.ts +1 -0
- package/internal/crypto/keying/index.js +1 -0
- package/internal/crypto/keying/index.js.map +1 -1
- package/package.json +1 -1
- package/workflows/blobs/verification/attachmentBindingVerification.js +3 -3
- package/workflows/blobs/verification/attachmentBindingVerification.js.map +1 -1
- package/workflows/containers/root/create.js +3 -3
- package/workflows/containers/root/create.js.map +1 -1
- package/workflows/documents/linkSet/linkSetBlobRewraps.js +2 -3
- package/workflows/documents/linkSet/linkSetBlobRewraps.js.map +1 -1
- package/workflows/documents/purge/index.js +3 -3
- package/workflows/documents/purge/index.js.map +1 -1
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { isPlainObject } from "../../validators/isPlainObject.js";
|
|
2
|
+
function isCanonicalJsonScalar(value) {
|
|
3
|
+
return (value === null ||
|
|
4
|
+
typeof value === "string" ||
|
|
5
|
+
typeof value === "boolean" ||
|
|
6
|
+
(typeof value === "number" && Number.isFinite(value)));
|
|
7
|
+
}
|
|
8
|
+
function pushCanonicalJsonChildren(value, active, pending) {
|
|
9
|
+
if (Array.isArray(value)) {
|
|
10
|
+
if (active.has(value)) {
|
|
11
|
+
return false;
|
|
12
|
+
}
|
|
13
|
+
active.add(value);
|
|
14
|
+
pending.push({ leave: value });
|
|
15
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
16
|
+
if (!(index in value)) {
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
pending.push({ value: value[index] });
|
|
20
|
+
}
|
|
21
|
+
return true;
|
|
22
|
+
}
|
|
23
|
+
if (!isPlainObject(value) || active.has(value)) {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
active.add(value);
|
|
27
|
+
pending.push({ leave: value });
|
|
28
|
+
for (const key of Object.keys(value)) {
|
|
29
|
+
pending.push({ value: Reflect.get(value, key) });
|
|
30
|
+
}
|
|
31
|
+
return true;
|
|
32
|
+
}
|
|
33
|
+
export function isKeyingCanonicalJson(value) {
|
|
34
|
+
const pending = [{ value }];
|
|
35
|
+
const active = new WeakSet();
|
|
36
|
+
while (pending.length > 0) {
|
|
37
|
+
const frame = pending.pop();
|
|
38
|
+
if (!frame) {
|
|
39
|
+
break;
|
|
40
|
+
}
|
|
41
|
+
if (frame.leave) {
|
|
42
|
+
active.delete(frame.leave);
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
if (isCanonicalJsonScalar(frame.value)) {
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
if (!pushCanonicalJsonChildren(frame.value, active, pending)) {
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return true;
|
|
53
|
+
}
|
|
54
|
+
export function readKeyingCanonicalJson(value, label) {
|
|
55
|
+
if (!isKeyingCanonicalJson(value)) {
|
|
56
|
+
throw new Error(`${label} must be canonical JSON`);
|
|
57
|
+
}
|
|
58
|
+
return value;
|
|
59
|
+
}
|
|
60
|
+
//# sourceMappingURL=canonicalJsonGuard.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"canonicalJsonGuard.js","sourceRoot":"","sources":["canonicalJsonGuard.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qCAAqC,CAAC;AAepE,SAAS,qBAAqB,CAAC,KAAc;IAC3C,OAAO,CACL,KAAK,KAAK,IAAI;QACd,OAAO,KAAK,KAAK,QAAQ;QACzB,OAAO,KAAK,KAAK,SAAS;QAC1B,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CACtD,CAAC;AACJ,CAAC;AAED,SAAS,yBAAyB,CAChC,KAAc,EACd,MAAuB,EACvB,OAA6B;IAE7B,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACzB,IAAI,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC;YACtB,OAAO,KAAK,CAAC;QACf,CAAC;QACD,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAClB,OAAO,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,C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,CAAC,KAAK,CAAC,CAAC;YAC3B,SAAS;QACX,CAAC;QAED,IAAI,qBAAqB,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC;YACvC,SAAS;QACX,CAAC;QAED,IAAI,CAAC,yBAAyB,CAAC,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC;YAC7D,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC;AAED,MAAM,UAAU,uBAAuB,CACrC,KAAc,EACd,KAAa;IAEb,IAAI,CAAC,qBAAqB,CAAC,KAAK,CAAC,EAAE,CAAC;QAClC,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,yBAAyB,CAAC,CAAC;IACrD,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { isPlainObject } from \"@tearleads/validators/isPlainObject\";\nimport type { KeyingCanonicalJson } from \"./types\";\n\n/*\n * Shape guard shared by the API and the client SDK for untrusted values that\n * become KeyingCanonicalJson: finite scalars, dense arrays, and plain objects,\n * with no reference cycles. It checks shape only; serializeKeyingCanonicalJson\n * still rejects negative zero, ill-formed Unicode, and undefined properties.\n */\n\ninterface CanonicalJsonFrame {\n readonly leave?: object;\n readonly value?: unknown;\n}\n\nfunction isCanonicalJsonScalar(value: unknown): boolean {\n return (\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"boolean\" ||\n (typeof value === \"number\" && Number.isFinite(value))\n );\n}\n\nfunction pushCanonicalJsonChildren(\n value: unknown,\n active: WeakSet<object>,\n pending: CanonicalJsonFrame[],\n): boolean {\n if (Array.isArray(value)) {\n if (active.has(value)) {\n return false;\n }\n active.add(value);\n pending.push({ leave: value });\n for (let index = 0; index < value.length; index += 1) {\n if (!(index in value)) {\n return false;\n }\n pending.push({ value: value[index] });\n }\n return true;\n }\n\n if (!isPlainObject(value) || active.has(value)) {\n return false;\n }\n active.add(value);\n pending.push({ leave: value });\n for (const key of Object.keys(value)) {\n pending.push({ value: Reflect.get(value, key) });\n }\n return true;\n}\n\nexport function isKeyingCanonicalJson(\n value: unknown,\n): value is KeyingCanonicalJson {\n const pending: CanonicalJsonFrame[] = [{ value }];\n const active = new WeakSet<object>();\n\n while (pending.length > 0) {\n const frame = pending.pop();\n if (!frame) {\n break;\n }\n\n if (frame.leave) {\n active.delete(frame.leave);\n continue;\n }\n\n if (isCanonicalJsonScalar(frame.value)) {\n continue;\n }\n\n if (!pushCanonicalJsonChildren(frame.value, active, pending)) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function readKeyingCanonicalJson(\n value: unknown,\n label: string,\n): KeyingCanonicalJson {\n if (!isKeyingCanonicalJson(value)) {\n throw new Error(`${label} must be canonical JSON`);\n }\n\n return value;\n}\n"]}
|
|
@@ -2,6 +2,7 @@ export * from "./accessEvent.js";
|
|
|
2
2
|
export * from "./accessManifestSnapshot.js";
|
|
3
3
|
export { ACCESS_MANIFEST_VERIFICATION_REVISION } from "./accessManifestVerificationRevision.js";
|
|
4
4
|
export * from "./canonical.js";
|
|
5
|
+
export { isKeyingCanonicalJson, readKeyingCanonicalJson, } from "./canonicalJsonGuard.js";
|
|
5
6
|
export * from "./checkpoints.js";
|
|
6
7
|
export * from "./containerAccess.js";
|
|
7
8
|
export { MAX_CONTAINER_RECITATION_EPOCH } from "./containerAccessReciteBody.js";
|
|
@@ -2,6 +2,7 @@ export * from "./accessEvent.js";
|
|
|
2
2
|
export * from "./accessManifestSnapshot.js";
|
|
3
3
|
export { ACCESS_MANIFEST_VERIFICATION_REVISION } from "./accessManifestVerificationRevision.js";
|
|
4
4
|
export * from "./canonical.js";
|
|
5
|
+
export { isKeyingCanonicalJson, readKeyingCanonicalJson, } from "./canonicalJsonGuard.js";
|
|
5
6
|
export * from "./checkpoints.js";
|
|
6
7
|
export * from "./containerAccess.js";
|
|
7
8
|
export { MAX_CONTAINER_RECITATION_EPOCH } from "./containerAccessReciteBody.js";
|
|
@@ -1 +1 @@
|
|
|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AiC,GAClC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,uCAAuC,EAAE,MAAM,8BAA8B,CAAC;AAEvF,OAAO,EAAE,sCAAsC,EAAE,MAAM,oCAAoC,CAAC;AAQ5F,OAAO,EAAE,kCAAkC,EAAE,MAAM,+BAA+B,CAAC;AACnF,OAAO,EACL,kCAAkC,GAEnC,MAAM,4BAA4B,CAAC;AAKpC,OAAO,EACL,oCAAoC,EACpC,0CAA0C,GAC3C,MAAM,6BAA6B,CAAC;AACrC,cAAc,gBAAgB,CAAC;AAC/B,OAAO,EAGL,kCAAkC,EAClC,gCAAgC,GACjC,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,6BAA6B,EAC7B,kCAAkC,EAClC,gCAAgC,GACjC,MAAM,oBAAoB,CAAC;AAC5B,cAAc,SAAS,CAAC;AACxB,OAAO,EACL,wBAAwB,EACxB,yBAAyB,GAC1B,MAAM,qBAAqB,CAAC;AAC7B,cAAc,eAAe,CAAC","sourcesContent":["export * from \"./accessEvent\";\nexport * from \"./accessManifestSnapshot\";\nexport { ACCESS_MANIFEST_VERIFICATION_REVISION } from \"./accessManifestVerificationRevision\";\nexport * from \"./canonical\";\nexport * from \"./checkpoints\";\nexport * from \"./containerAccess\";\nexport { MAX_CONTAINER_RECITATION_EPOCH } from \"./containerAccessReciteBody\";\nexport * from \"./containerKek\";\nexport {\n assertSealedContainerKekKeyringLength,\n CONTAINER_KEK_KEYRING_ENTRY_BYTES,\n CONTAINER_KEK_KEYRING_FORMAT_VERSION,\n CONTAINER_KEK_KEYRING_HEADER_BYTES,\n computeContainerKekKeyringHash,\n expectedSealedContainerKekKeyringBytes,\n normalizeContainerKekKeyring,\n openContainerKekKeyring,\n sealContainerKekKeyring,\n verifyContainerKekKeyringEntry,\n} from \"./containerKekKeyring\";\nexport {\n computeContainerKekPredecessorBridgeHash,\n createContainerKekPredecessorBridge,\n normalizeContainerKekPredecessorBridge,\n unwrapContainerKekPredecessorBridge,\n} from \"./containerKekPredecessor\";\nexport {\n deriveContainerKekWrappingPublicKey,\n unwrapContainerKekParentWrap,\n} from \"./containerKekWrapping\";\nexport { resolveContainerStatePathUserAccessLevel } from \"./containerPathAccess\";\nexport * from \"./documentAccess\";\nexport {\n type DocumentPurgeAccessEventBody,\n normalizeDocumentPurgeAccessEventBody,\n type VerifyDocumentPurgeEventInput,\n verifyDocumentPurgeEvent,\n} from \"./documentPurge\";\nexport * from \"./principalPolicy\";\nexport { verifyPrincipalPolicyBundleAgainstHistory } from \"./principalPolicyBundleHistory\";\nexport {\n type PrincipalPolicyCurrent,\n type VerifiedPrincipalPolicyCurrent,\n verifyPrincipalPolicyCurrent,\n} from \"./principalPolicyCurrent\";\nexport { verifyPrincipalPolicyCurrentMutation } from \"./principalPolicyCurrentMutation\";\nexport { selectPrincipalPolicyCurrentPredecessorReferences } from \"./principalPolicyCurrentPredecessorReferences\";\nexport { verifyPrincipalPolicyCurrentSuccessor } from \"./principalPolicyCurrentSuccessor\";\nexport type {\n PrincipalPolicyExternalAuthority,\n PrincipalPolicyExternalAuthorityState,\n} from \"./principalPolicyExternalAuthorityTypes\";\nexport {\n createPrincipalPolicyHistoryVerifier,\n restorePrincipalPolicyHistoryVerifier,\n} from \"./principalPolicyHistory\";\nexport type { PrincipalHistoryIndexNode } from \"./principalPolicyHistoryIndex\";\nexport {\n createPrincipalHistoryIndexProof,\n principalHistoryIndexLeaf,\n resolvePrincipalHistoryIndexProof,\n} from \"./principalPolicyHistoryIndex\";\nexport { PRINCIPAL_HISTORY_VERIFICATION_REVISION } from \"./principalPolicyHistoryPage\";\nexport type { PrincipalPolicyHistoryReferenceProof } from \"./principalPolicyHistoryReferences\";\nexport { verifyPrincipalPolicyHistoryReferences } from \"./principalPolicyHistoryReferences\";\nexport type {\n PrincipalPolicyHistoryInput,\n PrincipalPolicyHistoryPage,\n PrincipalPolicyHistoryProgressOptions,\n PrincipalPolicyHistoryVerifier,\n VerifiedPrincipalPolicyHistory,\n} from \"./principalPolicyHistoryTypes\";\nexport { PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT } from \"./principalPolicyHistoryTypes\";\nexport {\n selectPrincipalPolicyAuthorization,\n type VerifiedPrincipalPolicySelection,\n} from \"./principalPolicySelection\";\nexport type {\n PrincipalPolicyTransitionMismatch,\n PrincipalPolicyTransitionMismatchCode,\n} from \"./principalPolicyTransition\";\nexport {\n getPrincipalPolicyTransitionMismatch,\n getPrincipalPolicyTransitionMismatchReason,\n} from \"./principalPolicyTransition\";\nexport * from \"./transparency\";\nexport {\n type VerifyTransparencyConsistencyProofInput,\n type VerifyTransparencyInclusionProofInput,\n verifyTransparencyConsistencyProof,\n verifyTransparencyInclusionProof,\n} from \"./transparencyProofs\";\nexport {\n computeTransparencyMerkleRoot,\n createTransparencyConsistencyProof,\n createTransparencyInclusionProof,\n} from \"./transparencyTree\";\nexport * from \"./types\";\nexport {\n isKeyingVerificationCode,\n KEYING_VERIFICATION_CODES,\n} from \"./verificationError\";\nexport * from \"./writeHeader\";\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,cAAc,eAAe,CAAC;AAC9B,cAAc,0BAA0B,CAAC;AACzC,OAAO,EAAE,qCAAqC,EAAE,MAAM,sCAAsC,CAAC;AAC7F,cAAc,aAAa,CAAC;AAC5B,OAAO,EACL,qBAAqB,EACrB,uBAAuB,GACxB,MAAM,sBAAsB,CAAC;AAC9B,cAAc,eAAe,CAAC;AAC9B,cAAc,mBAAmB,CAAC;AAClC,OAAO,EAAE,8BAA8B,EAAE,MAAM,6BAA6B,CAAC;AAC7E,cAAc,gBAAgB,CAAC;AAC/B,OAAO,EACL,qCAAqC,EACrC,iCAAiC,EACjC,oCAAoC,EACpC,kCAAkC,EAClC,8BAA8B,EAC9B,sCAAsC,EACtC,4BAA4B,EAC5B,uBAAuB,EACvB,uBAAuB,EACvB,8BAA8B,GAC/B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,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,EACL,wBAAwB,EACxB,yBAAyB,GAC1B,MAAM,qBAAqB,CAAC;AAC7B,cAAc,eAAe,CAAC","sourcesContent":["export * from \"./accessEvent\";\nexport * from \"./accessManifestSnapshot\";\nexport { ACCESS_MANIFEST_VERIFICATION_REVISION } from \"./accessManifestVerificationRevision\";\nexport * from \"./canonical\";\nexport {\n isKeyingCanonicalJson,\n readKeyingCanonicalJson,\n} from \"./canonicalJsonGuard\";\nexport * from \"./checkpoints\";\nexport * from \"./containerAccess\";\nexport { MAX_CONTAINER_RECITATION_EPOCH } from \"./containerAccessReciteBody\";\nexport * from \"./containerKek\";\nexport {\n assertSealedContainerKekKeyringLength,\n CONTAINER_KEK_KEYRING_ENTRY_BYTES,\n CONTAINER_KEK_KEYRING_FORMAT_VERSION,\n CONTAINER_KEK_KEYRING_HEADER_BYTES,\n computeContainerKekKeyringHash,\n expectedSealedContainerKekKeyringBytes,\n normalizeContainerKekKeyring,\n openContainerKekKeyring,\n sealContainerKekKeyring,\n verifyContainerKekKeyringEntry,\n} from \"./containerKekKeyring\";\nexport {\n computeContainerKekPredecessorBridgeHash,\n createContainerKekPredecessorBridge,\n normalizeContainerKekPredecessorBridge,\n unwrapContainerKekPredecessorBridge,\n} from \"./containerKekPredecessor\";\nexport {\n deriveContainerKekWrappingPublicKey,\n unwrapContainerKekParentWrap,\n} from \"./containerKekWrapping\";\nexport { resolveContainerStatePathUserAccessLevel } from \"./containerPathAccess\";\nexport * from \"./documentAccess\";\nexport {\n type DocumentPurgeAccessEventBody,\n normalizeDocumentPurgeAccessEventBody,\n type VerifyDocumentPurgeEventInput,\n verifyDocumentPurgeEvent,\n} from \"./documentPurge\";\nexport * from \"./principalPolicy\";\nexport { verifyPrincipalPolicyBundleAgainstHistory } from \"./principalPolicyBundleHistory\";\nexport {\n type PrincipalPolicyCurrent,\n type VerifiedPrincipalPolicyCurrent,\n verifyPrincipalPolicyCurrent,\n} from \"./principalPolicyCurrent\";\nexport { verifyPrincipalPolicyCurrentMutation } from \"./principalPolicyCurrentMutation\";\nexport { selectPrincipalPolicyCurrentPredecessorReferences } from \"./principalPolicyCurrentPredecessorReferences\";\nexport { verifyPrincipalPolicyCurrentSuccessor } from \"./principalPolicyCurrentSuccessor\";\nexport type {\n PrincipalPolicyExternalAuthority,\n PrincipalPolicyExternalAuthorityState,\n} from \"./principalPolicyExternalAuthorityTypes\";\nexport {\n createPrincipalPolicyHistoryVerifier,\n restorePrincipalPolicyHistoryVerifier,\n} from \"./principalPolicyHistory\";\nexport type { PrincipalHistoryIndexNode } from \"./principalPolicyHistoryIndex\";\nexport {\n createPrincipalHistoryIndexProof,\n principalHistoryIndexLeaf,\n resolvePrincipalHistoryIndexProof,\n} from \"./principalPolicyHistoryIndex\";\nexport { PRINCIPAL_HISTORY_VERIFICATION_REVISION } from \"./principalPolicyHistoryPage\";\nexport type { PrincipalPolicyHistoryReferenceProof } from \"./principalPolicyHistoryReferences\";\nexport { verifyPrincipalPolicyHistoryReferences } from \"./principalPolicyHistoryReferences\";\nexport type {\n PrincipalPolicyHistoryInput,\n PrincipalPolicyHistoryPage,\n PrincipalPolicyHistoryProgressOptions,\n PrincipalPolicyHistoryVerifier,\n VerifiedPrincipalPolicyHistory,\n} from \"./principalPolicyHistoryTypes\";\nexport { PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT } from \"./principalPolicyHistoryTypes\";\nexport {\n selectPrincipalPolicyAuthorization,\n type VerifiedPrincipalPolicySelection,\n} from \"./principalPolicySelection\";\nexport type {\n PrincipalPolicyTransitionMismatch,\n PrincipalPolicyTransitionMismatchCode,\n} from \"./principalPolicyTransition\";\nexport {\n getPrincipalPolicyTransitionMismatch,\n getPrincipalPolicyTransitionMismatchReason,\n} from \"./principalPolicyTransition\";\nexport * from \"./transparency\";\nexport {\n type VerifyTransparencyConsistencyProofInput,\n type VerifyTransparencyInclusionProofInput,\n verifyTransparencyConsistencyProof,\n verifyTransparencyInclusionProof,\n} from \"./transparencyProofs\";\nexport {\n computeTransparencyMerkleRoot,\n createTransparencyConsistencyProof,\n createTransparencyInclusionProof,\n} from \"./transparencyTree\";\nexport * from \"./types\";\nexport {\n isKeyingVerificationCode,\n KEYING_VERIFICATION_CODES,\n} from \"./verificationError\";\nexport * from \"./writeHeader\";\n"]}
|
package/package.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { KeyingVerificationError, verifyAttachmentBindingEvent, } from "../../../internal/crypto/index.js";
|
|
2
|
-
import {
|
|
1
|
+
import { KeyingVerificationError, readKeyingCanonicalJson, verifyAttachmentBindingEvent, } from "../../../internal/crypto/index.js";
|
|
2
|
+
import { readCanonicalRecord } from "../../../data/keying/canonicalJson.js";
|
|
3
3
|
import { readAccessEvent, readRecordString, readRequiredRecordValue, resolveEventContainerPaths, } from "../../../data/keyingProjectionVerification/index.js";
|
|
4
4
|
export async function assertAttachmentBindingVerified(input) {
|
|
5
5
|
if (!input.authorization) {
|
|
@@ -27,7 +27,7 @@ export async function assertAttachmentBindingVerified(input) {
|
|
|
27
27
|
const verified = await verifyAttachmentBindingEvent({
|
|
28
28
|
authorizationMembership: "referenced",
|
|
29
29
|
authorizingContainerPaths: dependencyContainerPaths,
|
|
30
|
-
body:
|
|
30
|
+
body: readKeyingCanonicalJson(readRequiredRecordValue(eventBundle, "body", "Attachment binding event bundle"), "Attachment binding event body"),
|
|
31
31
|
documentManifest,
|
|
32
32
|
event,
|
|
33
33
|
expectedBindingId: input.binding.bindingId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attachmentBindingVerification.js","sourceRoot":"","sources":["attachmentBindingVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,
|
|
1
|
+
{"version":3,"file":"attachmentBindingVerification.js","sourceRoot":"","sources":["attachmentBindingVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,uBAAuB,EACvB,4BAA4B,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leads/crypto\";\nimport type { DecryptDocumentAttachmentBlobInput } from \"../../../data/blobs/attachments/types\";\nimport { readCanonicalRecord } from \"../../../data/keying/canonicalJson\";\nimport {\n type DocumentWriterProjectionAuthorization,\n type ProjectionUserKeyResolver,\n readAccessEvent,\n readRecordString,\n readRequiredRecordValue,\n resolveEventContainerPaths,\n} from \"../../../data/keyingProjectionVerification\";\n\nexport async function assertAttachmentBindingVerified(input: {\n readonly authorization: DocumentWriterProjectionAuthorization | undefined;\n readonly binding: Pick<\n DecryptDocumentAttachmentBlobInput[\"binding\"],\n | \"bindingEvent\"\n | \"documentManifestHash\"\n | \"previousBindingId\"\n | \"bindingId\"\n | \"blobId\"\n >;\n readonly expectedDocumentId: string;\n readonly expectedSlotId: string;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n}): Promise<void> {\n if (!input.authorization) {\n throw new Error(\"Attachment binding lacks verified document authority\");\n }\n if (\n !input.binding.bindingEvent ||\n !input.binding.documentManifestHash ||\n input.binding.previousBindingId === undefined\n ) {\n throw new Error(\"Attachment binding lacks signed verification material\");\n }\n const eventBundle = readCanonicalRecord(\n input.binding.bindingEvent,\n \"Attachment binding event bundle\",\n );\n const event = readAccessEvent(\n readRequiredRecordValue(\n eventBundle,\n \"event\",\n \"Attachment binding event bundle\",\n ),\n \"Attachment binding event\",\n );\n const signer = await input.resolveProjectionUserKey(event.signerUserId);\n if (!signer) {\n throw new Error(\"Attachment binding signer identity is unavailable\");\n }\n const documentManifest = input.authorization.documentManifestByHash.get(\n input.binding.documentManifestHash,\n );\n if (!documentManifest) {\n throw new Error(\"Attachment binding document manifest is unverified\");\n }\n const { dependencyContainerPaths } = resolveEventContainerPaths({\n containerPathByManifestHash:\n input.authorization.containerPathByManifestHash,\n dependencyManifestHashes: event.dependencyManifestHashes.filter(\n (hash) => hash !== input.binding.documentManifestHash,\n ),\n });\n const verified = await verifyAttachmentBindingEvent({\n authorizationMembership: \"referenced\",\n authorizingContainerPaths: dependencyContainerPaths,\n body: readKeyingCanonicalJson(\n readRequiredRecordValue(\n eventBundle,\n \"body\",\n \"Attachment binding event bundle\",\n ),\n \"Attachment binding event body\",\n ),\n documentManifest,\n event,\n expectedBindingId: input.binding.bindingId,\n expectedBlobId: input.binding.blobId,\n expectedDocumentId: input.expectedDocumentId,\n expectedDocumentManifestHash: input.binding.documentManifestHash,\n expectedPreviousBindingId: input.binding.previousBindingId,\n principalPolicies: input.authorization.principalPolicies,\n signerPublicKey: signer.signingPublicKey,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n if (\n verified.value.slotId !== input.expectedSlotId ||\n readRecordString(\n eventBundle,\n \"eventHash\",\n \"Attachment binding event bundle\",\n ) !== verified.value.event.eventHash\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Attachment binding slot or event hash is inconsistent\",\n );\n }\n}\n"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { computeContainerKekRecipientTargetHash, computeContainerKeyEpochHash, deriveContainerKekWrappingPublicKey, normalizeContainerAccessEventBody, } from "../../../internal/crypto/index.js";
|
|
1
|
+
import { computeContainerKekRecipientTargetHash, computeContainerKeyEpochHash, deriveContainerKekWrappingPublicKey, normalizeContainerAccessEventBody, readKeyingCanonicalJson, } from "../../../internal/crypto/index.js";
|
|
2
2
|
import { buildContainerCreateBody, buildContainerCreateKeyEpoch, deriveContainerCreateManifest, resolveContainerKekEpochId, signContainerCreateEvent, } from "../../../data/containers/shared/events.js";
|
|
3
3
|
import { principalPolicyRef } from "../../../data/containers/shared/principalPolicies.js";
|
|
4
4
|
import { wrapContainerKeyToManagedPrincipal, wrapContainerKeyToRootUser, } from "../../../data/containers/shared/projection.js";
|
|
5
|
-
import {
|
|
5
|
+
import { readCanonicalRecord, readCanonicalRecords, } from "../../../data/keying/canonicalJson.js";
|
|
6
6
|
import { principalHeadFromInitialGroupPolicy } from "./initialGroupPolicy.js";
|
|
7
7
|
function buildRootContainerCreateBody(input) {
|
|
8
8
|
const baseBody = buildContainerCreateBody({
|
|
@@ -155,7 +155,7 @@ function rootKeyMaterial(key) {
|
|
|
155
155
|
return material;
|
|
156
156
|
}
|
|
157
157
|
function normalizedRootCreateBody(input) {
|
|
158
|
-
const body = normalizeContainerAccessEventBody(
|
|
158
|
+
const body = normalizeContainerAccessEventBody(readKeyingCanonicalJson(buildRootContainerCreateBody(input), "Root create body"));
|
|
159
159
|
if (body.eventType !== "container.create")
|
|
160
160
|
throw new Error("Expected root creation body");
|
|
161
161
|
return body;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create.js","sourceRoot":"","sources":["create.ts"],"names":[],"mappings":"AASA,OAAO,EACL,sCAAsC,EACtC,4BAA4B,EAC5B,mCAAmC,EACnC,iCAAiC,GAClC,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EACL,wBAAwB,EACxB,4BAA4B,EAC5B,6BAA6B,EAC7B,0BAA0B,EAC1B,wBAAwB,GACzB,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,kBAAkB,EAAE,MAAM,mDAAmD,CAAC;AACvF,OAAO,EACL,kCAAkC,EAClC,0BAA0B,GAC3B,MAAM,4CAA4C,CAAC;AAMpD,OAAO,EACL,iBAAiB,EACjB,mBAAmB,EACnB,oBAAoB,GACrB,MAAM,oCAAoC,CAAC;AAE5C,OAAO,EAAE,mCAAmC,EAAE,MAAM,sBAAsB,CAAC;AAE3E,SAAS,4BAA4B,CAAC,KAQrC;IACC,MAAM,QAAQ,GAAG,wBAAwB,CAAC;QACxC,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;QAC9C,qBAAqB,EAAE,KAAK,CAAC,qBAAqB;QAClD,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,iBAAiB,EAAE,IAAI;QACvB,kBAAkB,EAAE,IAAI;KACzB,CAAC,CAAC;IACH,IAAI,KAAK,CAAC,oBAAoB,EAAE,CAAC;QAC/B,OAAO;YACL,GAAG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ACrB,kCAAkC,CACnC;gBACD,KAAK,EAAE,oBAAoB,CAAC,IAAI,CAAC,KAAK,EAAE,sBAAsB,CAAC;aAChE;SACF;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n AccessEvent,\n AccessManifest,\n ContainerCreateAccessEventBody,\n ContainerGrantPrincipalHead,\n ContainerKeyEpoch,\n ContainerKeyWrap,\n ContainerUserRecipientKey,\n} from \"@tearleads/crypto\";\nimport {\n computeContainerKekRecipientTargetHash,\n computeContainerKeyEpochHash,\n deriveContainerKekWrappingPublicKey,\n normalizeContainerAccessEventBody,\n} from \"@tearleads/crypto\";\nimport type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type {\n ContainerMutationRequest,\n CreateOrganizationGroupRequest,\n} from \"@tearleads/validators/request\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n buildContainerCreateBody,\n buildContainerCreateKeyEpoch,\n deriveContainerCreateManifest,\n resolveContainerKekEpochId,\n signContainerCreateEvent,\n} from \"../../../data/containers/shared/events\";\nimport { principalPolicyRef } from \"../../../data/containers/shared/principalPolicies\";\nimport {\n wrapContainerKeyToManagedPrincipal,\n wrapContainerKeyToRootUser,\n} from \"../../../data/containers/shared/projection\";\nimport type {\n ContainerCreatePlan,\n ContainerMutationAuthor,\n MaterializedContainerCreatePlan,\n} from \"../../../data/containers/shared/types\";\nimport {\n readCanonicalJson,\n readCanonicalRecord,\n readCanonicalRecords,\n} from \"../../../data/keying/canonicalJson\";\n\nimport { principalHeadFromInitialGroupPolicy } from \"./initialGroupPolicy\";\n\nfunction buildRootContainerCreateBody(input: {\n author: ContainerMutationAuthor;\n managedPrincipalHead: ContainerGrantPrincipalHead | null;\n containerKeyEpochId: string;\n containerKeyPublicKey: string;\n metadataDocumentId: string;\n memberHead: ContainerGrantPrincipalHead | null;\n systemSlot: ContainerSystemSlot | null;\n}): ContainerCreateAccessEventBody {\n const baseBody = buildContainerCreateBody({\n systemSlot: input.systemSlot,\n containerKeyEpochId: input.containerKeyEpochId,\n containerKeyPublicKey: input.containerKeyPublicKey,\n metadataDocumentId: input.metadataDocumentId,\n parentContainerId: null,\n parentManifestHash: null,\n });\n if (input.managedPrincipalHead) {\n return {\n ...baseBody,\n directGrants: [\n {\n accessLevel: \"admin\",\n subjectId: input.managedPrincipalHead.principalId,\n subjectType: input.managedPrincipalHead.principalType,\n },\n ...(input.memberHead\n ? [\n {\n accessLevel: \"read\" as const,\n subjectId: input.memberHead.principalId,\n subjectType: \"group\" as const,\n },\n ]\n : []),\n ],\n referencedPrincipalHeads: [\n input.managedPrincipalHead,\n ...(input.memberHead ? [input.memberHead] : []),\n ],\n };\n }\n\n return {\n ...baseBody,\n directGrants: [\n {\n accessLevel: \"admin\",\n subjectId: input.author.signerUserId,\n subjectType: \"user\",\n },\n ],\n };\n}\n\nfunction buildRootContainerCreateRequest(input: {\n body: ContainerCreateAccessEventBody;\n event: AccessEvent;\n keyEpoch: ContainerKeyEpoch;\n manifest: AccessManifest;\n manifestHash: string;\n principalPolicyRefs: ContainerMutationRequest[\"principalPolicyRefs\"];\n userRecipientKeys: readonly ContainerUserRecipientKey[];\n wraps: readonly ContainerKeyWrap[];\n}): ContainerMutationRequest {\n return {\n event: readCanonicalRecord(input.event, \"Container root create event\"),\n body: readCanonicalRecord(input.body, \"Container root create body\"),\n expectedManifestHash: input.manifestHash,\n manifest: readCanonicalRecord(\n input.manifest,\n \"Container root create manifest\",\n ),\n previousManifestRef: null,\n parentContainerPathRefs: [],\n principalPolicyRefs: input.principalPolicyRefs,\n keyEpoch: readCanonicalRecord(\n input.keyEpoch,\n \"Container root create key epoch\",\n ),\n predecessorBridge: null,\n keyring: null,\n wraps: readCanonicalRecords(input.wraps, \"Container root create wraps\"),\n userRecipientKeys: readCanonicalRecords(\n input.userRecipientKeys,\n \"Container root create user recipient keys\",\n ),\n };\n}\n\nasync function rootManagedPrincipalHead(\n group: CreateOrganizationGroupRequest | null,\n): Promise<ContainerGrantPrincipalHead | null> {\n return group\n ? principalHeadFromInitialGroupPolicy({\n principalId: group.groupId,\n policy: group.initialGroupPolicy,\n })\n : null;\n}\n\nasync function deriveRootCreateArtifacts(input: {\n author: ContainerMutationAuthor;\n body: ContainerCreateAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n metadataDocumentId: string;\n signedAt: string | undefined;\n}) {\n if (!input.body.containerKeyPublicKey)\n throw new Error(\"Root container public key is missing\");\n const { event, eventHash } = await signContainerCreateEvent({\n author: input.author,\n body: input.body,\n containerId: input.containerId,\n eventId: crypto.randomUUID(),\n // A root container belongs to the creator's own organization.\n organizationId: input.author.organizationId,\n parentPath: [],\n signedAt: input.signedAt ?? new Date().toISOString(),\n });\n const { manifest, manifestHash, state } = await deriveContainerCreateManifest(\n {\n systemSlot: input.body.systemSlot,\n containerId: input.containerId,\n containerKeyEpochId: input.containerKeyEpochId,\n containerKeyPublicKey: input.body.containerKeyPublicKey,\n directGrants: input.body.directGrants,\n eventHash,\n metadataDocumentId: input.metadataDocumentId,\n // A root container belongs to the creator's own organization.\n organizationId: input.author.organizationId,\n parentContainerId: null,\n parentManifestHash: null,\n referencedPrincipalHeads: input.body.referencedPrincipalHeads,\n },\n );\n const keyEpoch = buildContainerCreateKeyEpoch({\n containerId: input.containerId,\n containerKeyEpochId: input.containerKeyEpochId,\n eventHash,\n manifestHash,\n parentContainerKeyEpochId: null,\n });\n return { event, eventHash, keyEpoch, manifest, manifestHash, state };\n}\n\nasync function wrapRootContainerKeyForPlan(input: {\n adminGroup: CreateOrganizationGroupRequest | null;\n containerKey: Uint8Array;\n containerKeyEpochId: string;\n manifestHash: string;\n managedPrincipalHead: ContainerGrantPrincipalHead | null;\n recipientEncapsulationPublicKey: Uint8Array;\n userId: string;\n}) {\n if (input.adminGroup && input.managedPrincipalHead) {\n return {\n ...(await wrapContainerKeyToManagedPrincipal({\n containerKey: input.containerKey,\n containerKeyEpochId: input.containerKeyEpochId,\n manifestHash: input.manifestHash,\n principalEncapsulationPublicKey:\n input.adminGroup.initialGroupPolicy.state.encapsulationPublicKey,\n principalHead: input.managedPrincipalHead,\n })),\n userRecipientKey: null,\n };\n }\n\n return wrapContainerKeyToRootUser({\n containerKey: input.containerKey,\n containerKeyEpochId: input.containerKeyEpochId,\n manifestHash: input.manifestHash,\n recipientEncapsulationPublicKey: input.recipientEncapsulationPublicKey,\n userId: input.userId,\n });\n}\n\nasync function wrapRootContainerRecipients(\n input: Parameters<typeof wrapRootContainerKeyForPlan>[0] & {\n memberGroup: CreateOrganizationGroupRequest | null;\n memberHead: ContainerGrantPrincipalHead | null;\n },\n) {\n const root = await wrapRootContainerKeyForPlan(input);\n const member =\n input.memberGroup && input.memberHead\n ? await wrapContainerKeyToManagedPrincipal({\n ...input,\n principalEncapsulationPublicKey:\n input.memberGroup.initialGroupPolicy.state.encapsulationPublicKey,\n principalHead: input.memberHead,\n })\n : null;\n return {\n recipientTargets: [\n root.recipientTarget,\n ...(member ? [member.recipientTarget] : []),\n ],\n wraps: [root.wrap, ...(member ? [member.wrap] : [])],\n userRecipientKeys: root.userRecipientKey ? [root.userRecipientKey] : [],\n };\n}\n\nfunction rootKeyMaterial(key?: Uint8Array): Uint8Array {\n const material = key ?? crypto.getRandomValues(new Uint8Array(32));\n if (material.byteLength !== 32)\n throw new Error(\"Container KEK material must be 32 bytes\");\n return material;\n}\n\nfunction normalizedRootCreateBody(\n input: Parameters<typeof buildRootContainerCreateBody>[0],\n): ContainerCreateAccessEventBody {\n const body = normalizeContainerAccessEventBody(\n readCanonicalJson(buildRootContainerCreateBody(input), \"Root create body\"),\n );\n if (body.eventType !== \"container.create\")\n throw new Error(\"Expected root creation body\");\n return body;\n}\n\nexport async function buildRootContainerCreatePlan(input: {\n adminGroup?: CreateOrganizationGroupRequest | undefined;\n memberGroup?: CreateOrganizationGroupRequest | undefined;\n systemSlot?: ContainerSystemSlot | undefined;\n author: ContainerMutationAuthor;\n containerId: string;\n containerKey?: Uint8Array | undefined;\n metadataDocumentId: string;\n recipientEncapsulationPublicKey: Uint8Array;\n signedAt?: string | undefined;\n}): Promise<MaterializedContainerCreatePlan> {\n const containerKey = rootKeyMaterial(input.containerKey);\n const adminGroup = input.adminGroup ?? null;\n const managedPrincipalHead = await rootManagedPrincipalHead(adminGroup);\n const memberHead = await rootManagedPrincipalHead(input.memberGroup ?? null);\n if (input.memberGroup && !adminGroup)\n throw new Error(\"Members root grant requires Admins authority\");\n const containerKeyEpochId = await resolveContainerKekEpochId({\n containerId: input.containerId,\n keyEpoch: 1,\n keyMaterial: containerKey,\n });\n const body = normalizedRootCreateBody({\n containerKeyPublicKey: await deriveContainerKekWrappingPublicKey({\n containerId: input.containerId,\n keyMaterial: containerKey,\n }),\n memberHead,\n systemSlot: input.systemSlot ?? null,\n author: input.author,\n containerKeyEpochId,\n managedPrincipalHead,\n metadataDocumentId: input.metadataDocumentId,\n });\n const { event, eventHash, keyEpoch, manifest, manifestHash, state } =\n await deriveRootCreateArtifacts({\n author: input.author,\n body,\n containerId: input.containerId,\n containerKeyEpochId,\n metadataDocumentId: input.metadataDocumentId,\n signedAt: input.signedAt,\n });\n const { recipientTargets, wraps, userRecipientKeys } =\n await wrapRootContainerRecipients({\n memberGroup: input.memberGroup ?? null,\n memberHead,\n adminGroup,\n containerKey,\n containerKeyEpochId,\n manifestHash,\n managedPrincipalHead,\n recipientEncapsulationPublicKey: input.recipientEncapsulationPublicKey,\n userId: input.author.signerUserId,\n });\n const keyTargetHash =\n await computeContainerKekRecipientTargetHash(recipientTargets);\n const keyEpochHash = await computeContainerKeyEpochHash(keyEpoch);\n const plan: ContainerCreatePlan = {\n body,\n containerId: input.containerId,\n containerKeyEpochId,\n event,\n eventHash,\n keyEpoch,\n keyEpochHash,\n keyTargetHash,\n manifest,\n manifestHash,\n metadataDocumentId: input.metadataDocumentId,\n parentContainerId: null,\n parentManifestHash: null,\n recipientTargets,\n request: buildRootContainerCreateRequest({\n body,\n event,\n keyEpoch,\n manifest,\n manifestHash,\n principalPolicyRefs: [managedPrincipalHead, memberHead]\n .filter((head) => head !== null)\n .map(principalPolicyRef),\n userRecipientKeys,\n wraps,\n }),\n state,\n wraps,\n };\n\n return { containerKey, plan };\n}\n\nexport function rootContainerWriterProjectionFromCreatePlan(\n plan: ContainerCreatePlan,\n): ContainerWriterProjectionResponse {\n return {\n policyEvidence: {\n organization: null,\n organizationPayloads: [],\n groups: [],\n },\n containerId: plan.containerId,\n organizationId: plan.state.organizationId,\n path: [\n {\n event: {\n event: readCanonicalRecord(plan.event, \"Container root event\"),\n body: readCanonicalRecord(plan.body, \"Container root body\"),\n eventHash: plan.eventHash,\n },\n manifest: readCanonicalRecord(plan.manifest, \"Container root manifest\"),\n manifestHash: plan.manifestHash,\n state: readCanonicalRecord(plan.state, \"Container root state\"),\n },\n ],\n containerKeks: [\n {\n containerId: plan.containerId,\n accessManifestHash: plan.manifestHash,\n containerKeyEpochId: plan.containerKeyEpochId,\n containerKeyEpoch: plan.keyEpoch.keyEpoch,\n keyEpoch: readCanonicalRecord(\n plan.keyEpoch,\n \"Container root key epoch\",\n ),\n keyEpochHash: plan.keyEpochHash,\n keyTargetHash: plan.keyTargetHash,\n containerManifestHistory: [],\n parentContainerKeyEpochId: null,\n keyring: null,\n recipientTargets: readCanonicalRecords(\n plan.recipientTargets,\n \"Container root recipient targets\",\n ),\n wraps: readCanonicalRecords(plan.wraps, \"Container root wraps\"),\n },\n ],\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"create.js","sourceRoot":"","sources":["create.ts"],"names":[],"mappings":"AASA,OAAO,EACL,sCAAsC,EACtC,4BAA4B,EAC5B,mCAAmC,EACnC,iCAAiC,EACjC,uBAAuB,GACxB,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EACL,wBAAwB,EACxB,4BAA4B,EAC5B,6BAA6B,EAC7B,0BAA0B,EAC1B,wBAAwB,GACzB,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,kBAAkB,EAAE,MAAM,mDAAmD,CAAC;AACvF,OAAO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AAmB,CAAC,IAAI,CAAC,KAAK,EAAE,sBAAsB,CAAC;aAC/D;SACF;QACD,aAAa,EAAE;YACb;gBACE,WAAW,EAAE,IAAI,CAAC,WAAW;gBAC7B,kBAAkB,EAAE,IAAI,CAAC,YAAY;gBACrC,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;gBAC7C,iBAAiB,EAAE,IAAI,CAAC,QAAQ,CAAC,QAAQ;gBACzC,QAAQ,EAAE,mBAAmB,CAC3B,IAAI,CAAC,QAAQ,EACb,0BAA0B,CAC3B;gBACD,YAAY,EAAE,IAAI,CAAC,YAAY;gBAC/B,aAAa,EAAE,IAAI,CAAC,aAAa;gBACjC,wBAAwB,EAAE,EAAE;gBAC5B,yBAAyB,EAAE,IAAI;gBAC/B,OAAO,EAAE,IAAI;gBACb,gBAAgB,EAAE,oBAAoB,CACpC,IAAI,CAAC,gBAAgB,EACrB,kCAAkC,CACnC;gBACD,KAAK,EAAE,oBAAoB,CAAC,IAAI,CAAC,KAAK,EAAE,sBAAsB,CAAC;aAChE;SACF;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n AccessEvent,\n AccessManifest,\n ContainerCreateAccessEventBody,\n ContainerGrantPrincipalHead,\n ContainerKeyEpoch,\n ContainerKeyWrap,\n ContainerUserRecipientKey,\n} from \"@tearleads/crypto\";\nimport {\n computeContainerKekRecipientTargetHash,\n computeContainerKeyEpochHash,\n deriveContainerKekWrappingPublicKey,\n normalizeContainerAccessEventBody,\n readKeyingCanonicalJson,\n} from \"@tearleads/crypto\";\nimport type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type {\n ContainerMutationRequest,\n CreateOrganizationGroupRequest,\n} from \"@tearleads/validators/request\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n buildContainerCreateBody,\n buildContainerCreateKeyEpoch,\n deriveContainerCreateManifest,\n resolveContainerKekEpochId,\n signContainerCreateEvent,\n} from \"../../../data/containers/shared/events\";\nimport { principalPolicyRef } from \"../../../data/containers/shared/principalPolicies\";\nimport {\n wrapContainerKeyToManagedPrincipal,\n wrapContainerKeyToRootUser,\n} from \"../../../data/containers/shared/projection\";\nimport type {\n ContainerCreatePlan,\n ContainerMutationAuthor,\n MaterializedContainerCreatePlan,\n} from \"../../../data/containers/shared/types\";\nimport {\n readCanonicalRecord,\n readCanonicalRecords,\n} from \"../../../data/keying/canonicalJson\";\n\nimport { principalHeadFromInitialGroupPolicy } from \"./initialGroupPolicy\";\n\nfunction buildRootContainerCreateBody(input: {\n author: ContainerMutationAuthor;\n managedPrincipalHead: ContainerGrantPrincipalHead | null;\n containerKeyEpochId: string;\n containerKeyPublicKey: string;\n metadataDocumentId: string;\n memberHead: ContainerGrantPrincipalHead | null;\n systemSlot: ContainerSystemSlot | null;\n}): ContainerCreateAccessEventBody {\n const baseBody = buildContainerCreateBody({\n systemSlot: input.systemSlot,\n containerKeyEpochId: input.containerKeyEpochId,\n containerKeyPublicKey: input.containerKeyPublicKey,\n metadataDocumentId: input.metadataDocumentId,\n parentContainerId: null,\n parentManifestHash: null,\n });\n if (input.managedPrincipalHead) {\n return {\n ...baseBody,\n directGrants: [\n {\n accessLevel: \"admin\",\n subjectId: input.managedPrincipalHead.principalId,\n subjectType: input.managedPrincipalHead.principalType,\n },\n ...(input.memberHead\n ? [\n {\n accessLevel: \"read\" as const,\n subjectId: input.memberHead.principalId,\n subjectType: \"group\" as const,\n },\n ]\n : []),\n ],\n referencedPrincipalHeads: [\n input.managedPrincipalHead,\n ...(input.memberHead ? [input.memberHead] : []),\n ],\n };\n }\n\n return {\n ...baseBody,\n directGrants: [\n {\n accessLevel: \"admin\",\n subjectId: input.author.signerUserId,\n subjectType: \"user\",\n },\n ],\n };\n}\n\nfunction buildRootContainerCreateRequest(input: {\n body: ContainerCreateAccessEventBody;\n event: AccessEvent;\n keyEpoch: ContainerKeyEpoch;\n manifest: AccessManifest;\n manifestHash: string;\n principalPolicyRefs: ContainerMutationRequest[\"principalPolicyRefs\"];\n userRecipientKeys: readonly ContainerUserRecipientKey[];\n wraps: readonly ContainerKeyWrap[];\n}): ContainerMutationRequest {\n return {\n event: readCanonicalRecord(input.event, \"Container root create event\"),\n body: readCanonicalRecord(input.body, \"Container root create body\"),\n expectedManifestHash: input.manifestHash,\n manifest: readCanonicalRecord(\n input.manifest,\n \"Container root create manifest\",\n ),\n previousManifestRef: null,\n parentContainerPathRefs: [],\n principalPolicyRefs: input.principalPolicyRefs,\n keyEpoch: readCanonicalRecord(\n input.keyEpoch,\n \"Container root create key epoch\",\n ),\n predecessorBridge: null,\n keyring: null,\n wraps: readCanonicalRecords(input.wraps, \"Container root create wraps\"),\n userRecipientKeys: readCanonicalRecords(\n input.userRecipientKeys,\n \"Container root create user recipient keys\",\n ),\n };\n}\n\nasync function rootManagedPrincipalHead(\n group: CreateOrganizationGroupRequest | null,\n): Promise<ContainerGrantPrincipalHead | null> {\n return group\n ? principalHeadFromInitialGroupPolicy({\n principalId: group.groupId,\n policy: group.initialGroupPolicy,\n })\n : null;\n}\n\nasync function deriveRootCreateArtifacts(input: {\n author: ContainerMutationAuthor;\n body: ContainerCreateAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n metadataDocumentId: string;\n signedAt: string | undefined;\n}) {\n if (!input.body.containerKeyPublicKey)\n throw new Error(\"Root container public key is missing\");\n const { event, eventHash } = await signContainerCreateEvent({\n author: input.author,\n body: input.body,\n containerId: input.containerId,\n eventId: crypto.randomUUID(),\n // A root container belongs to the creator's own organization.\n organizationId: input.author.organizationId,\n parentPath: [],\n signedAt: input.signedAt ?? new Date().toISOString(),\n });\n const { manifest, manifestHash, state } = await deriveContainerCreateManifest(\n {\n systemSlot: input.body.systemSlot,\n containerId: input.containerId,\n containerKeyEpochId: input.containerKeyEpochId,\n containerKeyPublicKey: input.body.containerKeyPublicKey,\n directGrants: input.body.directGrants,\n eventHash,\n metadataDocumentId: input.metadataDocumentId,\n // A root container belongs to the creator's own organization.\n organizationId: input.author.organizationId,\n parentContainerId: null,\n parentManifestHash: null,\n referencedPrincipalHeads: input.body.referencedPrincipalHeads,\n },\n );\n const keyEpoch = buildContainerCreateKeyEpoch({\n containerId: input.containerId,\n containerKeyEpochId: input.containerKeyEpochId,\n eventHash,\n manifestHash,\n parentContainerKeyEpochId: null,\n });\n return { event, eventHash, keyEpoch, manifest, manifestHash, state };\n}\n\nasync function wrapRootContainerKeyForPlan(input: {\n adminGroup: CreateOrganizationGroupRequest | null;\n containerKey: Uint8Array;\n containerKeyEpochId: string;\n manifestHash: string;\n managedPrincipalHead: ContainerGrantPrincipalHead | null;\n recipientEncapsulationPublicKey: Uint8Array;\n userId: string;\n}) {\n if (input.adminGroup && input.managedPrincipalHead) {\n return {\n ...(await wrapContainerKeyToManagedPrincipal({\n containerKey: input.containerKey,\n containerKeyEpochId: input.containerKeyEpochId,\n manifestHash: input.manifestHash,\n principalEncapsulationPublicKey:\n input.adminGroup.initialGroupPolicy.state.encapsulationPublicKey,\n principalHead: input.managedPrincipalHead,\n })),\n userRecipientKey: null,\n };\n }\n\n return wrapContainerKeyToRootUser({\n containerKey: input.containerKey,\n containerKeyEpochId: input.containerKeyEpochId,\n manifestHash: input.manifestHash,\n recipientEncapsulationPublicKey: input.recipientEncapsulationPublicKey,\n userId: input.userId,\n });\n}\n\nasync function wrapRootContainerRecipients(\n input: Parameters<typeof wrapRootContainerKeyForPlan>[0] & {\n memberGroup: CreateOrganizationGroupRequest | null;\n memberHead: ContainerGrantPrincipalHead | null;\n },\n) {\n const root = await wrapRootContainerKeyForPlan(input);\n const member =\n input.memberGroup && input.memberHead\n ? await wrapContainerKeyToManagedPrincipal({\n ...input,\n principalEncapsulationPublicKey:\n input.memberGroup.initialGroupPolicy.state.encapsulationPublicKey,\n principalHead: input.memberHead,\n })\n : null;\n return {\n recipientTargets: [\n root.recipientTarget,\n ...(member ? [member.recipientTarget] : []),\n ],\n wraps: [root.wrap, ...(member ? [member.wrap] : [])],\n userRecipientKeys: root.userRecipientKey ? [root.userRecipientKey] : [],\n };\n}\n\nfunction rootKeyMaterial(key?: Uint8Array): Uint8Array {\n const material = key ?? crypto.getRandomValues(new Uint8Array(32));\n if (material.byteLength !== 32)\n throw new Error(\"Container KEK material must be 32 bytes\");\n return material;\n}\n\nfunction normalizedRootCreateBody(\n input: Parameters<typeof buildRootContainerCreateBody>[0],\n): ContainerCreateAccessEventBody {\n const body = normalizeContainerAccessEventBody(\n readKeyingCanonicalJson(\n buildRootContainerCreateBody(input),\n \"Root create body\",\n ),\n );\n if (body.eventType !== \"container.create\")\n throw new Error(\"Expected root creation body\");\n return body;\n}\n\nexport async function buildRootContainerCreatePlan(input: {\n adminGroup?: CreateOrganizationGroupRequest | undefined;\n memberGroup?: CreateOrganizationGroupRequest | undefined;\n systemSlot?: ContainerSystemSlot | undefined;\n author: ContainerMutationAuthor;\n containerId: string;\n containerKey?: Uint8Array | undefined;\n metadataDocumentId: string;\n recipientEncapsulationPublicKey: Uint8Array;\n signedAt?: string | undefined;\n}): Promise<MaterializedContainerCreatePlan> {\n const containerKey = rootKeyMaterial(input.containerKey);\n const adminGroup = input.adminGroup ?? null;\n const managedPrincipalHead = await rootManagedPrincipalHead(adminGroup);\n const memberHead = await rootManagedPrincipalHead(input.memberGroup ?? null);\n if (input.memberGroup && !adminGroup)\n throw new Error(\"Members root grant requires Admins authority\");\n const containerKeyEpochId = await resolveContainerKekEpochId({\n containerId: input.containerId,\n keyEpoch: 1,\n keyMaterial: containerKey,\n });\n const body = normalizedRootCreateBody({\n containerKeyPublicKey: await deriveContainerKekWrappingPublicKey({\n containerId: input.containerId,\n keyMaterial: containerKey,\n }),\n memberHead,\n systemSlot: input.systemSlot ?? null,\n author: input.author,\n containerKeyEpochId,\n managedPrincipalHead,\n metadataDocumentId: input.metadataDocumentId,\n });\n const { event, eventHash, keyEpoch, manifest, manifestHash, state } =\n await deriveRootCreateArtifacts({\n author: input.author,\n body,\n containerId: input.containerId,\n containerKeyEpochId,\n metadataDocumentId: input.metadataDocumentId,\n signedAt: input.signedAt,\n });\n const { recipientTargets, wraps, userRecipientKeys } =\n await wrapRootContainerRecipients({\n memberGroup: input.memberGroup ?? null,\n memberHead,\n adminGroup,\n containerKey,\n containerKeyEpochId,\n manifestHash,\n managedPrincipalHead,\n recipientEncapsulationPublicKey: input.recipientEncapsulationPublicKey,\n userId: input.author.signerUserId,\n });\n const keyTargetHash =\n await computeContainerKekRecipientTargetHash(recipientTargets);\n const keyEpochHash = await computeContainerKeyEpochHash(keyEpoch);\n const plan: ContainerCreatePlan = {\n body,\n containerId: input.containerId,\n containerKeyEpochId,\n event,\n eventHash,\n keyEpoch,\n keyEpochHash,\n keyTargetHash,\n manifest,\n manifestHash,\n metadataDocumentId: input.metadataDocumentId,\n parentContainerId: null,\n parentManifestHash: null,\n recipientTargets,\n request: buildRootContainerCreateRequest({\n body,\n event,\n keyEpoch,\n manifest,\n manifestHash,\n principalPolicyRefs: [managedPrincipalHead, memberHead]\n .filter((head) => head !== null)\n .map(principalPolicyRef),\n userRecipientKeys,\n wraps,\n }),\n state,\n wraps,\n };\n\n return { containerKey, plan };\n}\n\nexport function rootContainerWriterProjectionFromCreatePlan(\n plan: ContainerCreatePlan,\n): ContainerWriterProjectionResponse {\n return {\n policyEvidence: {\n organization: null,\n organizationPayloads: [],\n groups: [],\n },\n containerId: plan.containerId,\n organizationId: plan.state.organizationId,\n path: [\n {\n event: {\n event: readCanonicalRecord(plan.event, \"Container root event\"),\n body: readCanonicalRecord(plan.body, \"Container root body\"),\n eventHash: plan.eventHash,\n },\n manifest: readCanonicalRecord(plan.manifest, \"Container root manifest\"),\n manifestHash: plan.manifestHash,\n state: readCanonicalRecord(plan.state, \"Container root state\"),\n },\n ],\n containerKeks: [\n {\n containerId: plan.containerId,\n accessManifestHash: plan.manifestHash,\n containerKeyEpochId: plan.containerKeyEpochId,\n containerKeyEpoch: plan.keyEpoch.keyEpoch,\n keyEpoch: readCanonicalRecord(\n plan.keyEpoch,\n \"Container root key epoch\",\n ),\n keyEpochHash: plan.keyEpochHash,\n keyTargetHash: plan.keyTargetHash,\n containerManifestHistory: [],\n parentContainerKeyEpochId: null,\n keyring: null,\n recipientTargets: readCanonicalRecords(\n plan.recipientTargets,\n \"Container root recipient targets\",\n ),\n wraps: readCanonicalRecords(plan.wraps, \"Container root wraps\"),\n },\n ],\n };\n}\n"]}
|
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
import { BLOB_CONTENT_KEY_WRAP_SUITE, wrapContentKey, } from "../../../internal/crypto/index.js";
|
|
1
|
+
import { BLOB_CONTENT_KEY_WRAP_SUITE, readKeyingCanonicalJson, wrapContentKey, } from "../../../internal/crypto/index.js";
|
|
2
2
|
import { bytesToBase64 } from "../../../internal/encoding/index.js";
|
|
3
3
|
import { deriveDocumentTargetFromProjection, unwrapContainerKekPath, } from "../../../data/documents/shared/projection/index.js";
|
|
4
4
|
import { assertEqualBytes, targetKey, } from "../../../data/documents/shared/readers.js";
|
|
5
5
|
import { projectionVerificationOptions } from "../../../data/documents/shared/types.js";
|
|
6
|
-
import { readCanonicalJson } from "../../../data/keying/canonicalJson.js";
|
|
7
6
|
import { requireProjectionUserKeyResolver } from "../../../data/keyingProjectionVerification/index.js";
|
|
8
7
|
import { ProjectionDependencyUnavailableError } from "../../../data/keyingProjectionVerification/dependencyUnavailable.js";
|
|
9
8
|
import { documentContainerProjections } from "../../../data/keyingProjectionVerification/document/documentContainerProjections.js";
|
|
@@ -49,7 +48,7 @@ export async function prepareDocumentLinkBlobRewraps(input) {
|
|
|
49
48
|
return {
|
|
50
49
|
...previous,
|
|
51
50
|
...target,
|
|
52
|
-
wrappingMetadata:
|
|
51
|
+
wrappingMetadata: readKeyingCanonicalJson(previous.wrappingMetadata, "Attachment wrap metadata"),
|
|
53
52
|
};
|
|
54
53
|
const kek = keks.get(targetKey(target));
|
|
55
54
|
if (!kek)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"linkSetBlobRewraps.js","sourceRoot":"","sources":["linkSetBlob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,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import {\n BLOB_CONTENT_KEY_WRAP_SUITE,\n type DocumentContentKeyTarget,\n type DocumentLinkAccessEventBody,\n wrapContentKey,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n BlobAttachmentSummary,\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n deriveDocumentTargetFromProjection,\n unwrapContainerKekPath,\n} from \"../../../data/documents/shared/projection\";\nimport {\n assertEqualBytes,\n targetKey,\n} from \"../../../data/documents/shared/readers\";\nimport type {\n DocumentLinkSetMutationApi,\n ProjectionVerificationOptions,\n} from \"../../../data/documents/shared/types\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/types\";\nimport { readCanonicalJson } from \"../../../data/keying/canonicalJson\";\nimport { requireProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { documentContainerProjections } from \"../../../data/keyingProjectionVerification/document/documentContainerProjections\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { createAttachmentProofReader } from \"../../blobs/verification/attachmentDecryptor\";\nimport { createAttachmentKeyAuthenticator } from \"../../blobs/verification/attachmentKeyAuthenticator\";\nimport { verifyRetainedAttachment } from \"../../blobs/verification/retainedAttachmentVerification\";\n\ninterface BlobRewrap {\n blobId: string;\n contentKeyEpoch: number;\n targets: DocumentLinkAccessEventBody[\"blobRewraps\"][number][\"targets\"][number][];\n}\n\n/** Authenticate the existing bytes before propagating their DEK to a new scope. */\nexport async function prepareDocumentLinkBlobRewraps(\n input: {\n apiClient: DocumentLinkSetMutationApi;\n execSql: ExecSql;\n targetContainerProjection: ContainerWriterProjectionResponse;\n targetSecretKey: Uint8Array;\n targets: readonly DocumentContentKeyTarget[];\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<DocumentLinkAccessEventBody[\"blobRewraps\"]> {\n const documentId = input.writerProjection.documentId;\n const bindings = await input.apiClient.listDocumentAttachments(documentId);\n // The API refuses the link unless every active binding is rewrapped, so an\n // unavailable listing (offline, or a 409 while a bind is mid-flight) is a\n // retryable availability failure of this mutation, not integrity evidence.\n if (!bindings)\n throw new ProjectionDependencyUnavailableError(\n \"Document attachments are unavailable for relinking\",\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (bindings.length === 0) return [];\n const keks = await collectRelinkKeks(input);\n const authenticateKey = createAttachmentKeyAuthenticator(\n input.apiClient,\n documentId,\n );\n const verifyRetained = createAttachmentProofReader(\n input.apiClient,\n documentId,\n verifyRetainedAttachment,\n );\n const rewrapByBlob = new Map<string, BlobRewrap>();\n for (const binding of bindings) {\n const verification = {\n binding,\n expectedDocumentId: documentId,\n expectedSlotId: binding.slotId,\n execSql: input.execSql,\n resolveProjectionUserKey: requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Attachment relink\",\n ),\n targetSecretKey: input.targetSecretKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n writerProjection: input.writerProjection,\n };\n const needsKey = input.targets.some(\n (target) => !retainedTarget(binding, target, documentId),\n );\n const contentKey = needsKey ? await authenticateKey(verification) : null;\n if (!needsKey) await verifyRetained(verification);\n const targets = await Promise.all(\n input.targets.map(async (target) => {\n const previous = retainedTarget(binding, target, documentId);\n if (previous)\n return {\n ...previous,\n ...target,\n wrappingMetadata: readCanonicalJson(\n previous.wrappingMetadata,\n \"Attachment wrap metadata\",\n ),\n };\n const kek = keks.get(targetKey(target));\n if (!kek)\n throw new Error(\n \"Attachment destination is not a verified current container head\",\n );\n if (!contentKey)\n throw new Error(\"Attachment content key is unavailable\");\n return wrapBlobKeyForTarget({\n binding,\n contentKey,\n documentId,\n kek,\n target,\n });\n }),\n );\n const rewrap = rewrapByBlob.get(binding.blobId) ?? {\n blobId: binding.blobId,\n contentKeyEpoch: binding.contentKeyBundle.contentKeyEpoch,\n targets: [],\n };\n if (rewrap.contentKeyEpoch !== binding.contentKeyBundle.contentKeyEpoch)\n throw new Error(\"Attachment content epoch changed during relinking\");\n rewrap.targets.push(...targets);\n rewrapByBlob.set(binding.blobId, rewrap);\n assertProjectionVerificationCurrent(input.stillCurrent);\n }\n return [...rewrapByBlob.values()].sort(compareBlobIds);\n}\n\nasync function wrapBlobKeyForTarget(input: {\n binding: BlobAttachmentSummary;\n contentKey: Uint8Array;\n documentId: string;\n kek: Uint8Array;\n target: DocumentContentKeyTarget;\n}) {\n const { binding, target } = input;\n const wrapped = await wrapContentKey(input.contentKey, input.kek, {\n kind: \"Blob\",\n objectId: binding.blobId,\n contentKeyEpoch: binding.contentKeyBundle.contentKeyEpoch,\n containerId: target.containerId,\n containerKeyEpochId: target.containerKeyEpochId,\n });\n return {\n ...target,\n bindingId: binding.bindingId,\n documentId: input.documentId,\n wrappedKey: bytesToBase64(wrapped.ciphertext),\n wrappingMetadata: {\n suite: BLOB_CONTENT_KEY_WRAP_SUITE,\n iv: bytesToBase64(wrapped.iv),\n },\n };\n}\n\nfunction retainedTarget(\n binding: BlobAttachmentSummary,\n target: DocumentContentKeyTarget,\n documentId: string,\n) {\n return binding.contentKeyBundle.targets.find(\n (candidate) =>\n candidate.bindingId === binding.bindingId &&\n candidate.documentId === documentId &&\n candidate.containerId === target.containerId &&\n candidate.containerKeyEpochId === target.containerKeyEpochId,\n );\n}\n\nasync function collectRelinkKeks(\n input: Parameters<typeof prepareDocumentLinkBlobRewraps>[0],\n): Promise<Map<string, Uint8Array>> {\n const keks = new Map<string, Uint8Array>();\n for (const projection of [\n ...documentContainerProjections(input.writerProjection),\n input.targetContainerProjection,\n ]) {\n const keys = await unwrapContainerKekPath({\n projection,\n secretKey: input.targetSecretKey,\n execSql: input.execSql,\n ...projectionVerificationOptions(input),\n });\n // Every node of this verified path has a current signed head. Historical\n // keyring entries may open source bytes, but never enter the destination map.\n for (const [index, head] of projection.containerKeks.entries()) {\n const target = deriveDocumentTargetFromProjection({\n ...projection,\n containerId: head.containerId,\n path: projection.path.slice(0, index + 1),\n containerKeks: projection.containerKeks.slice(0, index + 1),\n });\n const key = keys.get(target.containerKeyEpochId);\n // A direct child grantee need not possess any ancestor secret.\n if (!key) continue;\n const id = targetKey(target);\n const previous = keks.get(id);\n if (previous)\n assertEqualBytes(\n previous,\n key,\n \"Attachment link projections contain conflicting KEKs\",\n );\n keks.set(id, key);\n }\n }\n return keks;\n}\n\nfunction compareBlobIds(a: { blobId: string }, b: { blobId: string }): number {\n return a.blobId < b.blobId ? -1 : a.blobId > b.blobId ? 1 : 0;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"linkSetBlobRewraps.js","sourceRoot":"","sources":["linkSetBlobRewraps.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,2BAA2B,EAG3B,uBAAuB,EACvB,cAAc,GACf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAMpD,OAAO,EACL,kCAAkC,EAClC,sBAAsB,GACvB,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACL,gBAAgB,EAChB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAKhD,OAAO,EAAE,6BAA6B,EAAE,MAAM,sCAAsC,CAAC;AACrF,OAAO,EAAE,gCAAgC,EAAE,MAAM,4CAA4C,CAAC;AAC9F,OAAO,EAAE,oCAAoC,EAAE,MAAM,kEAAkE,CAAC;AACxH,OAAO,EAAE,4BAA4B,EAAE,MAAM,kFAAkF,CAAC;AAChI,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AAEvG,OAAO,EAAE,2BAA2B,EAAE,MAAM,8CAA8C,CAAC;AAC3F,OAAO,EAAE,gCAAgC,EAAE,MAAM,qDAAqD,CAAC;AACvG,OAAO,EAAE,w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MAAM,CAAC,CAAC;YAC7B,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;YAC9B,IAAI,QAAQ;gBACV,gBAAgB,CACd,QAAQ,EACR,GAAG,EACH,sDAAsD,CACvD,CAAC;YACJ,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC;QACpB,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,cAAc,CAAC,CAAqB,EAAE,CAAqB;IAClE,OAAO,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import {\n BLOB_CONTENT_KEY_WRAP_SUITE,\n type DocumentContentKeyTarget,\n type DocumentLinkAccessEventBody,\n readKeyingCanonicalJson,\n wrapContentKey,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n BlobAttachmentSummary,\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n deriveDocumentTargetFromProjection,\n unwrapContainerKekPath,\n} from \"../../../data/documents/shared/projection\";\nimport {\n assertEqualBytes,\n targetKey,\n} from \"../../../data/documents/shared/readers\";\nimport type {\n DocumentLinkSetMutationApi,\n ProjectionVerificationOptions,\n} from \"../../../data/documents/shared/types\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/types\";\nimport { requireProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { documentContainerProjections } from \"../../../data/keyingProjectionVerification/document/documentContainerProjections\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { createAttachmentProofReader } from \"../../blobs/verification/attachmentDecryptor\";\nimport { createAttachmentKeyAuthenticator } from \"../../blobs/verification/attachmentKeyAuthenticator\";\nimport { verifyRetainedAttachment } from \"../../blobs/verification/retainedAttachmentVerification\";\n\ninterface BlobRewrap {\n blobId: string;\n contentKeyEpoch: number;\n targets: DocumentLinkAccessEventBody[\"blobRewraps\"][number][\"targets\"][number][];\n}\n\n/** Authenticate the existing bytes before propagating their DEK to a new scope. */\nexport async function prepareDocumentLinkBlobRewraps(\n input: {\n apiClient: DocumentLinkSetMutationApi;\n execSql: ExecSql;\n targetContainerProjection: ContainerWriterProjectionResponse;\n targetSecretKey: Uint8Array;\n targets: readonly DocumentContentKeyTarget[];\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<DocumentLinkAccessEventBody[\"blobRewraps\"]> {\n const documentId = input.writerProjection.documentId;\n const bindings = await input.apiClient.listDocumentAttachments(documentId);\n // The API refuses the link unless every active binding is rewrapped, so an\n // unavailable listing (offline, or a 409 while a bind is mid-flight) is a\n // retryable availability failure of this mutation, not integrity evidence.\n if (!bindings)\n throw new ProjectionDependencyUnavailableError(\n \"Document attachments are unavailable for relinking\",\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (bindings.length === 0) return [];\n const keks = await collectRelinkKeks(input);\n const authenticateKey = createAttachmentKeyAuthenticator(\n input.apiClient,\n documentId,\n );\n const verifyRetained = createAttachmentProofReader(\n input.apiClient,\n documentId,\n verifyRetainedAttachment,\n );\n const rewrapByBlob = new Map<string, BlobRewrap>();\n for (const binding of bindings) {\n const verification = {\n binding,\n expectedDocumentId: documentId,\n expectedSlotId: binding.slotId,\n execSql: input.execSql,\n resolveProjectionUserKey: requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Attachment relink\",\n ),\n targetSecretKey: input.targetSecretKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n writerProjection: input.writerProjection,\n };\n const needsKey = input.targets.some(\n (target) => !retainedTarget(binding, target, documentId),\n );\n const contentKey = needsKey ? await authenticateKey(verification) : null;\n if (!needsKey) await verifyRetained(verification);\n const targets = await Promise.all(\n input.targets.map(async (target) => {\n const previous = retainedTarget(binding, target, documentId);\n if (previous)\n return {\n ...previous,\n ...target,\n wrappingMetadata: readKeyingCanonicalJson(\n previous.wrappingMetadata,\n \"Attachment wrap metadata\",\n ),\n };\n const kek = keks.get(targetKey(target));\n if (!kek)\n throw new Error(\n \"Attachment destination is not a verified current container head\",\n );\n if (!contentKey)\n throw new Error(\"Attachment content key is unavailable\");\n return wrapBlobKeyForTarget({\n binding,\n contentKey,\n documentId,\n kek,\n target,\n });\n }),\n );\n const rewrap = rewrapByBlob.get(binding.blobId) ?? {\n blobId: binding.blobId,\n contentKeyEpoch: binding.contentKeyBundle.contentKeyEpoch,\n targets: [],\n };\n if (rewrap.contentKeyEpoch !== binding.contentKeyBundle.contentKeyEpoch)\n throw new Error(\"Attachment content epoch changed during relinking\");\n rewrap.targets.push(...targets);\n rewrapByBlob.set(binding.blobId, rewrap);\n assertProjectionVerificationCurrent(input.stillCurrent);\n }\n return [...rewrapByBlob.values()].sort(compareBlobIds);\n}\n\nasync function wrapBlobKeyForTarget(input: {\n binding: BlobAttachmentSummary;\n contentKey: Uint8Array;\n documentId: string;\n kek: Uint8Array;\n target: DocumentContentKeyTarget;\n}) {\n const { binding, target } = input;\n const wrapped = await wrapContentKey(input.contentKey, input.kek, {\n kind: \"Blob\",\n objectId: binding.blobId,\n contentKeyEpoch: binding.contentKeyBundle.contentKeyEpoch,\n containerId: target.containerId,\n containerKeyEpochId: target.containerKeyEpochId,\n });\n return {\n ...target,\n bindingId: binding.bindingId,\n documentId: input.documentId,\n wrappedKey: bytesToBase64(wrapped.ciphertext),\n wrappingMetadata: {\n suite: BLOB_CONTENT_KEY_WRAP_SUITE,\n iv: bytesToBase64(wrapped.iv),\n },\n };\n}\n\nfunction retainedTarget(\n binding: BlobAttachmentSummary,\n target: DocumentContentKeyTarget,\n documentId: string,\n) {\n return binding.contentKeyBundle.targets.find(\n (candidate) =>\n candidate.bindingId === binding.bindingId &&\n candidate.documentId === documentId &&\n candidate.containerId === target.containerId &&\n candidate.containerKeyEpochId === target.containerKeyEpochId,\n );\n}\n\nasync function collectRelinkKeks(\n input: Parameters<typeof prepareDocumentLinkBlobRewraps>[0],\n): Promise<Map<string, Uint8Array>> {\n const keks = new Map<string, Uint8Array>();\n for (const projection of [\n ...documentContainerProjections(input.writerProjection),\n input.targetContainerProjection,\n ]) {\n const keys = await unwrapContainerKekPath({\n projection,\n secretKey: input.targetSecretKey,\n execSql: input.execSql,\n ...projectionVerificationOptions(input),\n });\n // Every node of this verified path has a current signed head. Historical\n // keyring entries may open source bytes, but never enter the destination map.\n for (const [index, head] of projection.containerKeks.entries()) {\n const target = deriveDocumentTargetFromProjection({\n ...projection,\n containerId: head.containerId,\n path: projection.path.slice(0, index + 1),\n containerKeks: projection.containerKeks.slice(0, index + 1),\n });\n const key = keys.get(target.containerKeyEpochId);\n // A direct child grantee need not possess any ancestor secret.\n if (!key) continue;\n const id = targetKey(target);\n const previous = keks.get(id);\n if (previous)\n assertEqualBytes(\n previous,\n key,\n \"Attachment link projections contain conflicting KEKs\",\n );\n keks.set(id, key);\n }\n }\n return keks;\n}\n\nfunction compareBlobIds(a: { blobId: string }, b: { blobId: string }): number {\n return a.blobId < b.blobId ? -1 : a.blobId > b.blobId ? 1 : 0;\n}\n"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { computeAccessEventBodyHash, KeyingVerificationError, signAccessEvent, } from "../../../internal/crypto/index.js";
|
|
1
|
+
import { computeAccessEventBodyHash, KeyingVerificationError, readKeyingCanonicalJson, signAccessEvent, } from "../../../internal/crypto/index.js";
|
|
2
2
|
import { DOCUMENT_NOT_FOUND_ERROR_CODE, } from "../../../internal/validators/response/index.js";
|
|
3
3
|
import { containerPathRefs, readLinkedContainerIdsFromDocumentManifest, } from "../../../data/documents/shared/projection/index.js";
|
|
4
4
|
import { assertDocumentManifestBundleConsistent, readManifestContainerId, } from "../../../data/documents/shared/readers.js";
|
|
5
|
-
import {
|
|
5
|
+
import { readCanonicalRecord } from "../../../data/keying/canonicalJson.js";
|
|
6
6
|
import { verifyDocumentPurgeProof, verifyDocumentPurgeProofBaseline, verifyDocumentWriterProjection, } from "../../../data/keyingProjectionVerification/index.js";
|
|
7
7
|
import { ProjectionDependencyUnavailableError } from "../../../data/keyingProjectionVerification/dependencyUnavailable.js";
|
|
8
8
|
import { documentContainerProjections } from "../../../data/keyingProjectionVerification/document/documentContainerProjections.js";
|
|
@@ -88,7 +88,7 @@ export async function buildDocumentPurgeRequest(input) {
|
|
|
88
88
|
organizationId: input.author.organizationId,
|
|
89
89
|
previousManifestHash: input.writerProjection.documentManifest.manifestHash,
|
|
90
90
|
dependencyManifestHashes: authorizingContainerManifestHashes,
|
|
91
|
-
bodyHash: await computeAccessEventBodyHash(
|
|
91
|
+
bodyHash: await computeAccessEventBodyHash(readKeyingCanonicalJson(body, "Document purge body")),
|
|
92
92
|
signerUserId: input.author.signerUserId,
|
|
93
93
|
signerDeviceId: input.author.signerDeviceId,
|
|
94
94
|
signerKeyFingerprint: input.author.signerKeyFingerprint,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,0BAA0B,EAE1B,uBAAuB,EACvB,eAAe,GAEhB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,6BAA6B,GAI9B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,iBAAiB,EACjB,0CAA0C,GAC3C,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACL,sCAAsC,EACtC,uBAAuB,GACxB,MAAM,wCAAwC,CAAC;AAKhD,OAAO,EACL,iBAAiB,EACjB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AsB,EAAE,KAAK,CAAC,MAAM,CAAC,cAAc;QACnD,KAAK,EAAE,QAAQ;QACf,cAAc,EAAE,KAAK,CAAC,wBAAwB;QAC9C,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;KACvE,CAAC,CAAC;IACH,MAAM,KAAK,CAAC,eAAe,CAAC;QAC1B,gBAAgB,EAAE,QAAQ,CAAC,iBAAiB;KAC7C,CAAC,CAAC;IACH,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n computeAccessEventBodyHash,\n type DocumentPurgeAccessEventBody,\n KeyingVerificationError,\n signAccessEvent,\n type UnsignedAccessEvent,\n} from \"@tearleads/crypto\";\nimport type { DocumentPurgeRequest } from \"@tearleads/validators/request\";\nimport {\n DOCUMENT_NOT_FOUND_ERROR_CODE,\n type DocumentPurgeProofResponse,\n type DocumentPurgeResponse,\n type DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n containerPathRefs,\n readLinkedContainerIdsFromDocumentManifest,\n} from \"../../../data/documents/shared/projection\";\nimport {\n assertDocumentManifestBundleConsistent,\n readManifestContainerId,\n} from \"../../../data/documents/shared/readers\";\nimport type {\n DocumentCreateAuthor,\n DocumentSyncApi,\n} from \"../../../data/documents/shared/types\";\nimport {\n readCanonicalJson,\n readCanonicalRecord,\n} from \"../../../data/keying/canonicalJson\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../../data/keyingProjectionVerification\";\nimport {\n verifyDocumentPurgeProof,\n verifyDocumentPurgeProofBaseline,\n verifyDocumentWriterProjection,\n} from \"../../../data/keyingProjectionVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { documentContainerProjections } from \"../../../data/keyingProjectionVerification/document/documentContainerProjections\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n assertSubtreePurgePath,\n type SubtreePurgeRoot,\n} from \"./subtreePurgeScope\";\n\ninterface DocumentPurgeApi {\n getDocumentPurgeProof(\n documentId: string,\n options?: {\n readonly documentCheckpointManifestHash?: string;\n },\n requestOptions?: {\n readonly expectedPaymentRequiredOrganizationId?: string;\n },\n ): Promise<DocumentPurgeProofResponse | null>;\n getDocumentWriterProjectionResult: NonNullable<\n DocumentSyncApi[\"getDocumentWriterProjectionResult\"]\n >;\n purgeDocument(\n documentId: string,\n request: DocumentPurgeRequest,\n options?: {\n readonly expectedPaymentRequiredOrganizationId?: string;\n },\n ): Promise<DocumentPurgeResponse | null>;\n}\n\nconst REMOTE_DOCUMENT_ALREADY_PURGED = Symbol(\"remoteDocumentAlreadyPurged\");\n\nasync function loadAuthenticatedDocumentPurgeProof(input: {\n readonly apiClient: Pick<DocumentSyncApi, \"getDocumentPurgeProof\">;\n readonly documentId: string;\n readonly execSql: ExecSql;\n readonly expectedOrganizationId: string;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): Promise<DocumentPurgeProofResponse | null> {\n if (!input.apiClient.getDocumentPurgeProof) {\n throw new ProjectionDependencyUnavailableError(\n \"Remote document deletion is missing a purge-proof endpoint\",\n );\n }\n const initialProof = await input.apiClient.getDocumentPurgeProof(\n input.documentId,\n undefined,\n {\n expectedPaymentRequiredOrganizationId: input.expectedOrganizationId,\n },\n );\n if (!initialProof) {\n // ApiClient returns null for transport, HTTP and response-shape failures.\n // Even after a deletion hint, absence cannot prove signed-data tampering.\n // Keep local data and defer deletion until an actual proof verifies.\n return null;\n }\n await verifyDocumentPurgeProofBaseline({\n execSql: input.execSql,\n expectedDocumentId: input.documentId,\n expectedOrganizationId: input.expectedOrganizationId,\n proof: initialProof,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n // The current API returns complete history to recorded readers. Otherwise\n // its terminal snapshot needs an exact local pin; a floor refetch cannot\n // grant missing observation authority.\n return initialProof;\n}\n\nasync function resolveDocumentPurgeWriterProjection(input: {\n readonly apiClient: DocumentPurgeApi;\n readonly documentId: string;\n}): Promise<\n | DocumentWriterProjectionResponse\n | typeof REMOTE_DOCUMENT_ALREADY_PURGED\n | null\n> {\n const result = await input.apiClient.getDocumentWriterProjectionResult(\n input.documentId,\n { reportErrors: false },\n );\n if (result.ok) {\n return result.data;\n }\n if (result.status === 404 && result.code === DOCUMENT_NOT_FOUND_ERROR_CODE) {\n return REMOTE_DOCUMENT_ALREADY_PURGED;\n }\n result.report();\n return null;\n}\n\nexport async function buildDocumentPurgeRequest(input: {\n readonly author: DocumentCreateAuthor;\n readonly expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n readonly eventId?: string | undefined;\n readonly signedAt?: string | undefined;\n readonly writerProjection: DocumentWriterProjectionResponse;\n}): Promise<DocumentPurgeRequest> {\n const identity = await assertDocumentManifestBundleConsistent({\n bundle: input.writerProjection.documentManifest,\n label: \"Document purge predecessor\",\n });\n if (identity.documentId !== input.writerProjection.documentId) {\n throw new Error(\"Document purge projection identity mismatch\");\n }\n if (identity.organizationId !== input.author.organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document purge author organization mismatch\",\n );\n }\n const linkedContainerIds = readLinkedContainerIdsFromDocumentManifest(\n input.writerProjection,\n );\n if (linkedContainerIds.length !== 1) {\n throw new Error(\"Document purge requires exactly one linked container\");\n }\n const [containerId] = linkedContainerIds;\n const authorizingProjection = documentContainerProjections(\n input.writerProjection,\n ).find((projection) => {\n const leaf = projection.path.at(-1);\n return leaf && readManifestContainerId(leaf) === containerId;\n });\n const containerManifestHash =\n authorizingProjection?.path.at(-1)?.manifestHash;\n if (!authorizingProjection || !containerId || !containerManifestHash) {\n throw new Error(\"Document purge authorization path is unavailable\");\n }\n assertSubtreePurgePath(authorizingProjection.path, input.expectedSubtreeRoot);\n const authorizingContainerManifestHashes = authorizingProjection.path.map(\n (bundle) => bundle.manifestHash,\n );\n const body: DocumentPurgeAccessEventBody = {\n authorizingContainerManifestHashes,\n containerId,\n containerManifestHash,\n documentManifestHash: input.writerProjection.documentManifest.manifestHash,\n eventType: \"document.purge\",\n };\n const unsignedEvent: UnsignedAccessEvent = {\n version: 1,\n eventId: input.eventId ?? crypto.randomUUID(),\n eventType: \"document.purge\",\n objectKind: \"document\",\n objectId: input.writerProjection.documentId,\n organizationId: input.author.organizationId,\n previousManifestHash: input.writerProjection.documentManifest.manifestHash,\n dependencyManifestHashes: authorizingContainerManifestHashes,\n bodyHash: await computeAccessEventBodyHash(\n readCanonicalJson(body, \"Document purge body\"),\n ),\n signerUserId: input.author.signerUserId,\n signerDeviceId: input.author.signerDeviceId,\n signerKeyFingerprint: input.author.signerKeyFingerprint,\n signedAt: input.signedAt ?? new Date().toISOString(),\n };\n const event = await signAccessEvent(\n unsignedEvent,\n input.author.signerPrivateKey,\n );\n\n return {\n authorizingContainerPathRefs: containerPathRefs(authorizingProjection.path),\n body: readCanonicalRecord(body, \"Document purge body\"),\n event: readCanonicalRecord(event, \"Document purge event\"),\n };\n}\n\nexport function createVerifiedRemoteDocumentDeletionHandler(input: {\n readonly apiClient: Pick<DocumentSyncApi, \"getDocumentPurgeProof\">;\n readonly execSql: ExecSql;\n readonly expectedOrganizationId: string;\n readonly onVerifiedDeletion: (input: {\n readonly commitPurgeProof: (transactionExecSql: ExecSql) => Promise<void>;\n readonly documentId: string;\n }) => Promise<void> | void;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): (deleted: { readonly documentId: string }) => Promise<void> {\n return async ({ documentId }) => {\n const proof = await loadAuthenticatedDocumentPurgeProof({\n apiClient: input.apiClient,\n documentId,\n execSql: input.execSql,\n expectedOrganizationId: input.expectedOrganizationId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n if (!proof) {\n throw new ProjectionDependencyUnavailableError(\n \"Remote document deletion is missing its signed purge proof\",\n );\n }\n const verified = await verifyDocumentPurgeProof({\n execSql: input.execSql,\n expectedDocumentId: documentId,\n expectedOrganizationId: input.expectedOrganizationId,\n proof,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n await input.onVerifiedDeletion({\n commitPurgeProof: verified.commitCheckpoints,\n documentId,\n });\n };\n}\n\nexport async function purgeRemoteDocument(input: {\n readonly beforeSubmit?: (() => Promise<boolean>) | undefined;\n readonly apiClient: DocumentPurgeApi;\n readonly author: DocumentCreateAuthor;\n readonly documentId: string;\n readonly expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n readonly execSql: ExecSql;\n readonly onVerifiedPurge: (input: {\n readonly commitPurgeProof: (transactionExecSql: ExecSql) => Promise<void>;\n }) => Promise<void> | void;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): Promise<DocumentPurgeResponse | null> {\n const writerProjection = await resolveDocumentPurgeWriterProjection({\n apiClient: input.apiClient,\n documentId: input.documentId,\n });\n if (!writerProjection) {\n return null;\n }\n if (writerProjection === REMOTE_DOCUMENT_ALREADY_PURGED) {\n const proof = await loadAuthenticatedDocumentPurgeProof({\n apiClient: input.apiClient,\n documentId: input.documentId,\n execSql: input.execSql,\n expectedOrganizationId: input.author.organizationId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n if (!proof) {\n throw new ProjectionDependencyUnavailableError(\n \"Purged remote document is missing its signed purge proof\",\n );\n }\n const verified = await verifyDocumentPurgeProof({\n execSql: input.execSql,\n expectedDocumentId: input.documentId,\n expectedOrganizationId: input.author.organizationId,\n proof,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n await input.onVerifiedPurge({\n commitPurgeProof: verified.commitCheckpoints,\n });\n return { ...proof, reclaimedBlobStorageKeys: [] };\n }\n await verifyDocumentWriterProjection({\n execSql: input.execSql,\n projection: writerProjection,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const request = await buildDocumentPurgeRequest({\n author: input.author,\n expectedSubtreeRoot: input.expectedSubtreeRoot,\n writerProjection,\n });\n if (input.beforeSubmit && !(await input.beforeSubmit())) return null;\n if (input.stillCurrent?.() === false) return null;\n const response = await input.apiClient.purgeDocument(\n input.documentId,\n request,\n {\n expectedPaymentRequiredOrganizationId: input.author.organizationId,\n },\n );\n if (!response) {\n return null;\n }\n const verified = await verifyDocumentPurgeProof({\n execSql: input.execSql,\n expectedDocumentId: input.documentId,\n expectedOrganizationId: input.author.organizationId,\n proof: response,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n await input.onVerifiedPurge({\n commitPurgeProof: verified.commitCheckpoints,\n });\n return response;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,0BAA0B,EAE1B,uBAAuB,EACvB,uBAAuB,EACvB,eAAe,GAEhB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,6BAA6B,GAI9B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,iBAAiB,EACjB,0CA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Q,GAAG,MAAM,wBAAwB,CAAC;QAC9C,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,kBAAkB,EAAE,KAAK,CAAC,UAAU;QACpC,sBAAsB,EAAE,KAAK,CAAC,MAAM,CAAC,cAAc;QACnD,KAAK,EAAE,QAAQ;QACf,cAAc,EAAE,KAAK,CAAC,wBAAwB;QAC9C,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;KACvE,CAAC,CAAC;IACH,MAAM,KAAK,CAAC,eAAe,CAAC;QAC1B,gBAAgB,EAAE,QAAQ,CAAC,iBAAiB;KAC7C,CAAC,CAAC;IACH,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n computeAccessEventBodyHash,\n type DocumentPurgeAccessEventBody,\n KeyingVerificationError,\n readKeyingCanonicalJson,\n signAccessEvent,\n type UnsignedAccessEvent,\n} from \"@tearleads/crypto\";\nimport type { DocumentPurgeRequest } from \"@tearleads/validators/request\";\nimport {\n DOCUMENT_NOT_FOUND_ERROR_CODE,\n type DocumentPurgeProofResponse,\n type DocumentPurgeResponse,\n type DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n containerPathRefs,\n readLinkedContainerIdsFromDocumentManifest,\n} from \"../../../data/documents/shared/projection\";\nimport {\n assertDocumentManifestBundleConsistent,\n readManifestContainerId,\n} from \"../../../data/documents/shared/readers\";\nimport type {\n DocumentCreateAuthor,\n DocumentSyncApi,\n} from \"../../../data/documents/shared/types\";\nimport { readCanonicalRecord } from \"../../../data/keying/canonicalJson\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../../data/keyingProjectionVerification\";\nimport {\n verifyDocumentPurgeProof,\n verifyDocumentPurgeProofBaseline,\n verifyDocumentWriterProjection,\n} from \"../../../data/keyingProjectionVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { documentContainerProjections } from \"../../../data/keyingProjectionVerification/document/documentContainerProjections\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n assertSubtreePurgePath,\n type SubtreePurgeRoot,\n} from \"./subtreePurgeScope\";\n\ninterface DocumentPurgeApi {\n getDocumentPurgeProof(\n documentId: string,\n options?: {\n readonly documentCheckpointManifestHash?: string;\n },\n requestOptions?: {\n readonly expectedPaymentRequiredOrganizationId?: string;\n },\n ): Promise<DocumentPurgeProofResponse | null>;\n getDocumentWriterProjectionResult: NonNullable<\n DocumentSyncApi[\"getDocumentWriterProjectionResult\"]\n >;\n purgeDocument(\n documentId: string,\n request: DocumentPurgeRequest,\n options?: {\n readonly expectedPaymentRequiredOrganizationId?: string;\n },\n ): Promise<DocumentPurgeResponse | null>;\n}\n\nconst REMOTE_DOCUMENT_ALREADY_PURGED = Symbol(\"remoteDocumentAlreadyPurged\");\n\nasync function loadAuthenticatedDocumentPurgeProof(input: {\n readonly apiClient: Pick<DocumentSyncApi, \"getDocumentPurgeProof\">;\n readonly documentId: string;\n readonly execSql: ExecSql;\n readonly expectedOrganizationId: string;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): Promise<DocumentPurgeProofResponse | null> {\n if (!input.apiClient.getDocumentPurgeProof) {\n throw new ProjectionDependencyUnavailableError(\n \"Remote document deletion is missing a purge-proof endpoint\",\n );\n }\n const initialProof = await input.apiClient.getDocumentPurgeProof(\n input.documentId,\n undefined,\n {\n expectedPaymentRequiredOrganizationId: input.expectedOrganizationId,\n },\n );\n if (!initialProof) {\n // ApiClient returns null for transport, HTTP and response-shape failures.\n // Even after a deletion hint, absence cannot prove signed-data tampering.\n // Keep local data and defer deletion until an actual proof verifies.\n return null;\n }\n await verifyDocumentPurgeProofBaseline({\n execSql: input.execSql,\n expectedDocumentId: input.documentId,\n expectedOrganizationId: input.expectedOrganizationId,\n proof: initialProof,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n // The current API returns complete history to recorded readers. Otherwise\n // its terminal snapshot needs an exact local pin; a floor refetch cannot\n // grant missing observation authority.\n return initialProof;\n}\n\nasync function resolveDocumentPurgeWriterProjection(input: {\n readonly apiClient: DocumentPurgeApi;\n readonly documentId: string;\n}): Promise<\n | DocumentWriterProjectionResponse\n | typeof REMOTE_DOCUMENT_ALREADY_PURGED\n | null\n> {\n const result = await input.apiClient.getDocumentWriterProjectionResult(\n input.documentId,\n { reportErrors: false },\n );\n if (result.ok) {\n return result.data;\n }\n if (result.status === 404 && result.code === DOCUMENT_NOT_FOUND_ERROR_CODE) {\n return REMOTE_DOCUMENT_ALREADY_PURGED;\n }\n result.report();\n return null;\n}\n\nexport async function buildDocumentPurgeRequest(input: {\n readonly author: DocumentCreateAuthor;\n readonly expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n readonly eventId?: string | undefined;\n readonly signedAt?: string | undefined;\n readonly writerProjection: DocumentWriterProjectionResponse;\n}): Promise<DocumentPurgeRequest> {\n const identity = await assertDocumentManifestBundleConsistent({\n bundle: input.writerProjection.documentManifest,\n label: \"Document purge predecessor\",\n });\n if (identity.documentId !== input.writerProjection.documentId) {\n throw new Error(\"Document purge projection identity mismatch\");\n }\n if (identity.organizationId !== input.author.organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document purge author organization mismatch\",\n );\n }\n const linkedContainerIds = readLinkedContainerIdsFromDocumentManifest(\n input.writerProjection,\n );\n if (linkedContainerIds.length !== 1) {\n throw new Error(\"Document purge requires exactly one linked container\");\n }\n const [containerId] = linkedContainerIds;\n const authorizingProjection = documentContainerProjections(\n input.writerProjection,\n ).find((projection) => {\n const leaf = projection.path.at(-1);\n return leaf && readManifestContainerId(leaf) === containerId;\n });\n const containerManifestHash =\n authorizingProjection?.path.at(-1)?.manifestHash;\n if (!authorizingProjection || !containerId || !containerManifestHash) {\n throw new Error(\"Document purge authorization path is unavailable\");\n }\n assertSubtreePurgePath(authorizingProjection.path, input.expectedSubtreeRoot);\n const authorizingContainerManifestHashes = authorizingProjection.path.map(\n (bundle) => bundle.manifestHash,\n );\n const body: DocumentPurgeAccessEventBody = {\n authorizingContainerManifestHashes,\n containerId,\n containerManifestHash,\n documentManifestHash: input.writerProjection.documentManifest.manifestHash,\n eventType: \"document.purge\",\n };\n const unsignedEvent: UnsignedAccessEvent = {\n version: 1,\n eventId: input.eventId ?? crypto.randomUUID(),\n eventType: \"document.purge\",\n objectKind: \"document\",\n objectId: input.writerProjection.documentId,\n organizationId: input.author.organizationId,\n previousManifestHash: input.writerProjection.documentManifest.manifestHash,\n dependencyManifestHashes: authorizingContainerManifestHashes,\n bodyHash: await computeAccessEventBodyHash(\n readKeyingCanonicalJson(body, \"Document purge body\"),\n ),\n signerUserId: input.author.signerUserId,\n signerDeviceId: input.author.signerDeviceId,\n signerKeyFingerprint: input.author.signerKeyFingerprint,\n signedAt: input.signedAt ?? new Date().toISOString(),\n };\n const event = await signAccessEvent(\n unsignedEvent,\n input.author.signerPrivateKey,\n );\n\n return {\n authorizingContainerPathRefs: containerPathRefs(authorizingProjection.path),\n body: readCanonicalRecord(body, \"Document purge body\"),\n event: readCanonicalRecord(event, \"Document purge event\"),\n };\n}\n\nexport function createVerifiedRemoteDocumentDeletionHandler(input: {\n readonly apiClient: Pick<DocumentSyncApi, \"getDocumentPurgeProof\">;\n readonly execSql: ExecSql;\n readonly expectedOrganizationId: string;\n readonly onVerifiedDeletion: (input: {\n readonly commitPurgeProof: (transactionExecSql: ExecSql) => Promise<void>;\n readonly documentId: string;\n }) => Promise<void> | void;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): (deleted: { readonly documentId: string }) => Promise<void> {\n return async ({ documentId }) => {\n const proof = await loadAuthenticatedDocumentPurgeProof({\n apiClient: input.apiClient,\n documentId,\n execSql: input.execSql,\n expectedOrganizationId: input.expectedOrganizationId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n if (!proof) {\n throw new ProjectionDependencyUnavailableError(\n \"Remote document deletion is missing its signed purge proof\",\n );\n }\n const verified = await verifyDocumentPurgeProof({\n execSql: input.execSql,\n expectedDocumentId: documentId,\n expectedOrganizationId: input.expectedOrganizationId,\n proof,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n await input.onVerifiedDeletion({\n commitPurgeProof: verified.commitCheckpoints,\n documentId,\n });\n };\n}\n\nexport async function purgeRemoteDocument(input: {\n readonly beforeSubmit?: (() => Promise<boolean>) | undefined;\n readonly apiClient: DocumentPurgeApi;\n readonly author: DocumentCreateAuthor;\n readonly documentId: string;\n readonly expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n readonly execSql: ExecSql;\n readonly onVerifiedPurge: (input: {\n readonly commitPurgeProof: (transactionExecSql: ExecSql) => Promise<void>;\n }) => Promise<void> | void;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): Promise<DocumentPurgeResponse | null> {\n const writerProjection = await resolveDocumentPurgeWriterProjection({\n apiClient: input.apiClient,\n documentId: input.documentId,\n });\n if (!writerProjection) {\n return null;\n }\n if (writerProjection === REMOTE_DOCUMENT_ALREADY_PURGED) {\n const proof = await loadAuthenticatedDocumentPurgeProof({\n apiClient: input.apiClient,\n documentId: input.documentId,\n execSql: input.execSql,\n expectedOrganizationId: input.author.organizationId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n if (!proof) {\n throw new ProjectionDependencyUnavailableError(\n \"Purged remote document is missing its signed purge proof\",\n );\n }\n const verified = await verifyDocumentPurgeProof({\n execSql: input.execSql,\n expectedDocumentId: input.documentId,\n expectedOrganizationId: input.author.organizationId,\n proof,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n await input.onVerifiedPurge({\n commitPurgeProof: verified.commitCheckpoints,\n });\n return { ...proof, reclaimedBlobStorageKeys: [] };\n }\n await verifyDocumentWriterProjection({\n execSql: input.execSql,\n projection: writerProjection,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const request = await buildDocumentPurgeRequest({\n author: input.author,\n expectedSubtreeRoot: input.expectedSubtreeRoot,\n writerProjection,\n });\n if (input.beforeSubmit && !(await input.beforeSubmit())) return null;\n if (input.stillCurrent?.() === false) return null;\n const response = await input.apiClient.purgeDocument(\n input.documentId,\n request,\n {\n expectedPaymentRequiredOrganizationId: input.author.organizationId,\n },\n );\n if (!response) {\n return null;\n }\n const verified = await verifyDocumentPurgeProof({\n execSql: input.execSql,\n expectedDocumentId: input.documentId,\n expectedOrganizationId: input.author.organizationId,\n proof: response,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n await input.onVerifiedPurge({\n commitPurgeProof: verified.commitCheckpoints,\n });\n return response;\n}\n"]}
|