@tearleads/client-sdk 0.1.240 → 0.1.242
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/documents/shared/sync/syncResponseAuthorization.js +12 -1
- package/data/documents/shared/sync/syncResponseAuthorization.js.map +1 -1
- package/data/documents/shared/sync/syncResponses.js +2 -2
- package/data/documents/shared/sync/syncResponses.js.map +1 -1
- package/data/keyingProjectionVerification/checkpoints/checkpointContext.js +12 -3
- package/data/keyingProjectionVerification/checkpoints/checkpointContext.js.map +1 -1
- package/data/keyingProjectionVerification/checkpoints/verifiedBundleBytes.js +73 -8
- package/data/keyingProjectionVerification/checkpoints/verifiedBundleBytes.js.map +1 -1
- package/data/keyingProjectionVerification/container/containerAncestorCitations.js +20 -4
- package/data/keyingProjectionVerification/container/containerAncestorCitations.js.map +1 -1
- package/data/keyingProjectionVerification/container/containerManifestVerification.js +43 -32
- package/data/keyingProjectionVerification/container/containerManifestVerification.js.map +1 -1
- package/data/keyingProjectionVerification/container/containerSignedParentReference.js +129 -0
- package/data/keyingProjectionVerification/container/containerSignedParentReference.js.map +1 -0
- package/data/keyingProjectionVerification/document/documentManifestVerification.js +28 -7
- package/data/keyingProjectionVerification/document/documentManifestVerification.js.map +1 -1
- package/data/persistence/verifiedCitations/bundleCitationRows.js.map +1 -1
- package/data/persistence/verifiedCitations/citationCollection.js +2 -2
- package/data/persistence/verifiedCitations/citationCollection.js.map +1 -1
- package/data/persistence/verifiedManifestBundlePersistence.d.ts +3 -2
- package/data/persistence/verifiedManifestBundlePersistence.js +1 -1
- package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
- package/internal/api-client/ApiClient.d.ts +7 -7
- package/internal/api-client/client/apiClientContext.d.ts +1 -1
- package/internal/api-client/client/blobs.d.ts +1 -1
- package/internal/api-client/client/documents.d.ts +6 -6
- package/internal/api-client/verifiedManifestCitations.d.ts +4 -3
- package/internal/api-client/verifiedManifestCitations.js +3 -3
- package/internal/api-client/verifiedManifestCitations.js.map +1 -1
- package/internal/validators/operation/attachments.d.ts +2 -2
- package/internal/validators/operation/documentSync.d.ts +24 -24
- package/internal/validators/operation/writerProjections.d.ts +8 -8
- package/internal/validators/response/blob.d.ts +6 -6
- package/internal/validators/response/blob.js +12 -2
- package/internal/validators/response/blob.js.map +1 -1
- package/internal/validators/response/container.d.ts +4 -4
- package/internal/validators/response/documentMutation.d.ts +4 -4
- package/internal/validators/response/documentSyncSchema.d.ts +48 -48
- package/internal/validators/response/documentSyncSchema.js +1 -1
- package/internal/validators/response/documentSyncSchema.js.map +1 -1
- package/internal/validators/response/manifestBundleReferences.js +4 -3
- package/internal/validators/response/manifestBundleReferences.js.map +1 -1
- package/internal/validators/response/writerProjectionWire.d.ts +4 -4
- package/internal/validators/response/writerProjectionWire.js +8 -5
- package/internal/validators/response/writerProjectionWire.js.map +1 -1
- package/internal/validators/util/index.d.ts +1 -0
- package/internal/validators/util/index.js +1 -0
- package/internal/validators/util/index.js.map +1 -1
- package/internal/validators/util/servedManifestBundle.d.ts +71 -0
- package/internal/validators/util/servedManifestBundle.js +100 -0
- package/internal/validators/util/servedManifestBundle.js.map +1 -0
- package/package.json +1 -1
- package/workflows/blobs/hydration/decrypt.js +17 -1
- package/workflows/blobs/hydration/decrypt.js.map +1 -1
|
@@ -1,6 +1,17 @@
|
|
|
1
1
|
import { computeDocumentContentKeyTargetHash, makeVerifiedDocumentKekTargets, } from "../../../../internal/crypto/index.js";
|
|
2
2
|
import { resolveEventContainerPaths } from "../../../keyingProjectionVerification/index.js";
|
|
3
|
-
import { sortDocumentTargets } from "../readers.js";
|
|
3
|
+
import { sortDocumentTargets, targetEnvelopeReference } from "../readers.js";
|
|
4
|
+
/**
|
|
5
|
+
* The update's authorization target set. The server omits it when the signed
|
|
6
|
+
* header commits to the target hash this sync expected, which is the set the
|
|
7
|
+
* plan holds, so refill it from the plan. `documentWriteAuthorizationForHeader`
|
|
8
|
+
* re-hashes it against the signed `targetHash`, so an omission for any other
|
|
9
|
+
* hash fails closed.
|
|
10
|
+
*/
|
|
11
|
+
export function authorizationTargetsForUpdate(update, plan) {
|
|
12
|
+
return (update.authorizationTargets ??
|
|
13
|
+
plan.sourceContentKeyBundle.targets.map(targetEnvelopeReference));
|
|
14
|
+
}
|
|
4
15
|
export async function documentWriteAuthorizationForHeader(input) {
|
|
5
16
|
const source = input.plan.documentWriterAuthorization;
|
|
6
17
|
if (!source) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncResponseAuthorization.js","sourceRoot":"","sources":["syncResponseAuthorization.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mCAAmC,EAEnC,8BAA8B,GAC/B,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"syncResponseAuthorization.js","sourceRoot":"","sources":["syncResponseAuthorization.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mCAAmC,EAEnC,8BAA8B,GAC/B,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EAAE,0BAA0B,EAAE,MAAM,uCAAuC,CAAC;AACnF,OAAO,EAAE,mBAAmB,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AAG1E;;;;;;GAMG;AACH,MAAM,UAAU,6BAA6B,CAC3C,MAA6E,EAC7E,IAAsD;IAEtD,OAAO,CACL,MAAM,CAAC,oBAAoB;QAC3B,IAAI,CAAC,sBAAsB,CAAC,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC,CACjE,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,mCAAmC,CAAC,KAWzD;IACC,MAAM,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,2BAA2B,CAAC;IACtD,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,IAAI,KAAK,CAAC,yBAAyB,EAAE,CAAC;YACpC,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,IAAI,KAAK,CACb,qEAAqE,CACtE,CAAC;IACJ,CAAC;IACD,MAAM,g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,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,YAAY,KAAK,MAAM,CAAC,qBAAqB,CAClE,CAAC;QACF,IAAI,CAAC,IAAI;YAAE,SAAS;QACpB,MAAM,IAAI,GAAG,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QACzB,IACE,CAAC,IAAI;YACL,IAAI,CAAC,KAAK,CAAC,WAAW,KAAK,MAAM,CAAC,WAAW;YAC7C,IAAI,CAAC,KAAK,CAAC,cAAc,KAAK,KAAK,CAAC,IAAI,CAAC,cAAc;YACvD,IAAI,CAAC,KAAK,CAAC,mBAAmB,KAAK,MAAM,CAAC,mBAAmB,EAC7D,CAAC;YACD,MAAM,IAAI,KAAK,CACb,qEAAqE,CACtE,CAAC;QACJ,CAAC;IACH,CAAC;IACD,MAAM,yBAAyB,GAAG,wBAAwB,CAAC;IAC3D,MAAM,kBAAkB,GAAG,8BAA8B,CAAC;QACxD,UAAU,EAAE,KAAK,CAAC,gBAAgB,CAAC,UAAU;QAC7C,qBAAqB,EAAE,KAAK,CAAC,UAAU;QACvC,0BAA0B,EAAE,OAAO,CAAC,GAAG,CACrC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,mBAAmB,CACvC;QACD,6BAA6B,EAAE,OAAO,CAAC,GAAG,CACxC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,qBAAqB,CACzC;QACD,mBAAmB,EAAE,KAAK,CAAC,YAAY;QACvC,OAAO;KACR,CAAC,CAAC;IACH,OAAO;QACL,yBAAyB;QACzB,kBAAkB;QAClB,gBAAgB;QAChB,iBAAiB,EAAE,MAAM,CAAC,iBAAiB;KAC5C,CAAC;AACJ,CAAC","sourcesContent":["import {\n computeDocumentContentKeyTargetHash,\n type DocumentContentKeyTarget,\n makeVerifiedDocumentKekTargets,\n} from \"@tearleads/crypto\";\nimport type {\n DocumentContentKeyBundleResponse,\n DocumentSyncResponse,\n} from \"@tearleads/validators/response\";\nimport { resolveEventContainerPaths } from \"../../../keyingProjectionVerification\";\nimport { sortDocumentTargets, targetEnvelopeReference } from \"../readers\";\nimport type { DocumentSyncPlan } from \"./documentSyncTypes\";\n\n/**\n * The update's authorization target set. The server omits it when the signed\n * header commits to the target hash this sync expected, which is the set the\n * plan holds, so refill it from the plan. `documentWriteAuthorizationForHeader`\n * re-hashes it against the signed `targetHash`, so an omission for any other\n * hash fails closed.\n */\nexport function authorizationTargetsForUpdate(\n update: Pick<DocumentSyncResponse[\"updates\"][number], \"authorizationTargets\">,\n plan: Pick<DocumentSyncPlan, \"sourceContentKeyBundle\">,\n): DocumentContentKeyTarget[] {\n return (\n update.authorizationTargets ??\n plan.sourceContentKeyBundle.targets.map(targetEnvelopeReference)\n );\n}\n\nexport async function documentWriteAuthorizationForHeader(input: {\n readonly allowMissingAuthorization: boolean;\n readonly dependencyManifestHashes: readonly string[];\n readonly authorizationTargets: readonly DocumentContentKeyTarget[];\n readonly contentKeyBundle: DocumentContentKeyBundleResponse;\n readonly manifestHash: string;\n readonly plan: Pick<\n DocumentSyncPlan,\n \"documentId\" | \"organizationId\" | \"documentWriterAuthorization\"\n >;\n readonly targetHash: string;\n}) {\n const source = input.plan.documentWriterAuthorization;\n if (!source) {\n if (input.allowMissingAuthorization) {\n return null;\n }\n throw new Error(\n \"Document sync response lacks verified writer-authorization material\",\n );\n }\n const documentManifest = source.documentManifestByHash.get(\n input.manifestHash,\n );\n if (!documentManifest) {\n throw new Error(\n \"Document sync response write manifest is not in verified history\",\n );\n }\n if (input.contentKeyBundle.documentId !== input.plan.documentId) {\n throw new Error(\n \"Document sync response content-key bundle belongs to another document\",\n );\n }\n\n const targets = sortDocumentTargets(input.authorizationTargets);\n if (\n (await computeDocumentContentKeyTargetHash(targets)) !== input.targetHash\n ) {\n throw new Error(\"Document sync response write targets are not canonical\");\n }\n const linkedContainerIds = new Set(documentManifest.state.linkedContainerIds);\n if (\n targets.length !== linkedContainerIds.size ||\n targets.some((target) => !linkedContainerIds.has(target.containerId))\n ) {\n throw new Error(\n \"Document sync response write targets do not match the signed link set\",\n );\n }\n\n const { dependencyContainerPaths } = resolveEventContainerPaths({\n containerPathByManifestHash: source.containerPathByManifestHash,\n dependencyManifestHashes: input.dependencyManifestHashes,\n });\n // A writer needs one committed target, and can be unable to read another\n // linked container. Validate the targets that are cited without inventing\n // paths for uncited targets or dropping signed ancestor evidence.\n for (const target of targets) {\n const path = dependencyContainerPaths.find(\n (candidate) =>\n candidate.at(-1)?.manifestHash === target.containerManifestHash,\n );\n if (!path) continue;\n const leaf = path.at(-1);\n if (\n !leaf ||\n leaf.state.containerId !== target.containerId ||\n leaf.state.organizationId !== input.plan.organizationId ||\n leaf.state.containerKeyEpochId !== target.containerKeyEpochId\n ) {\n throw new Error(\n \"Document sync response write target lacks a verified container path\",\n );\n }\n }\n const authorizingContainerPaths = dependencyContainerPaths;\n const documentKekTargets = makeVerifiedDocumentKekTargets({\n documentId: input.contentKeyBundle.documentId,\n documentKeyTargetHash: input.targetHash,\n linkedContainerKeyEpochIds: targets.map(\n (target) => target.containerKeyEpochId,\n ),\n linkedContainerManifestHashes: targets.map(\n (target) => target.containerManifestHash,\n ),\n linkSetManifestHash: input.manifestHash,\n targets,\n });\n return {\n authorizingContainerPaths,\n documentKekTargets,\n documentManifest,\n principalPolicies: source.principalPolicies,\n };\n}\n"]}
|
|
@@ -5,7 +5,7 @@ import { parseWalLsn } from "../../../../internal/validators/util/index.js";
|
|
|
5
5
|
import { throwKeyingVerificationShapeFailure } from "../../../keyingProjectionVerification/error.js";
|
|
6
6
|
import { readRecordPositiveInteger, readRecordString, readWriteHeader, serializedPersistedDocumentState, } from "../readers.js";
|
|
7
7
|
export { submitDocumentSync } from "./syncPagination.js";
|
|
8
|
-
import { documentWriteAuthorizationForHeader } from "./syncResponseAuthorization.js";
|
|
8
|
+
import { authorizationTargetsForUpdate, documentWriteAuthorizationForHeader, } from "./syncResponseAuthorization.js";
|
|
9
9
|
// Remote-primary databases without a portable WAL position use the zero LSN
|
|
10
10
|
// as an explicit "checkpoint not tracked" sentinel. It is accepted only when
|
|
11
11
|
// the response declares that mode, letting a local record carrying a checkpoint
|
|
@@ -139,7 +139,7 @@ async function assertDocumentSyncResponseWriteHeaderSignature(input) {
|
|
|
139
139
|
}
|
|
140
140
|
const documentAuthorization = await documentWriteAuthorizationForHeader({
|
|
141
141
|
allowMissingAuthorization: isAcceptedOutgoingSyncUpdate(plan, update),
|
|
142
|
-
authorizationTargets: update
|
|
142
|
+
authorizationTargets: authorizationTargetsForUpdate(update, plan),
|
|
143
143
|
dependencyManifestHashes: header.dependencyManifestHashes,
|
|
144
144
|
contentKeyBundle: input.contentKeyBundle,
|
|
145
145
|
manifestHash: header.accessManifestHash,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncResponses.js","sourceRoot":"","sources":["syncResponses.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,+BAA+B,EAC/B,mCAAmC,EACnC,0CAA0C,EAC1C,wCAAwC,EACxC,iBAAiB,GAElB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,IAAI,aAAa,EAAE,MAAM,qCAAqC,CAAC;AACrF,OAAO,EACL,6BAA6B,EAC7B,yBAAyB,GAG1B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AACzD,OAAO,EAAE,mCAAmC,EAAE,MAAM,6CAA6C,CAAC;AAClG,OAAO,EACL,yBAAyB,EACzB,gBAAgB,EAChB,eAAe,EACf,gCAAgC,GACjC,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAOtD,OAAO,EAAE,mCAAmC,EAAE,MAAM,6BAA6B,CAAC;AAGlF,4EAA4E;AAC5E,6EAA6E;AAC7E,gFAAgF;AAChF,8EAA8E;AAC9E,gFAAgF;AAChF,+EAA+E;AAC/E,MAAM,oBAAoB,GAAG,KAAK,CAAC;AAEnC,MA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,CAAC,KAAK,CAAC,CAAC;IAC7C,CAAC;AACH,CAAC;AAED,MAAM,UAAU,+BAA+B,CAC7C,OAAkC;IAElC,OAAO,CACL,OAAO,CAAC,MAAM,KAAK,GAAG;QACtB,OAAO,CAAC,IAAI,KAAK,yBAAyB,CAAC,UAAU,CACtD,CAAC;AACJ,CAAC;AAED,6EAA6E;AAC7E,6EAA6E;AAC7E,oEAAoE;AACpE,2CAA2C;AAC3C,MAAM,UAAU,oCAAoC,CAClD,OAAkC;IAElC,OAAO,CACL,OAAO,CAAC,MAAM,KAAK,GAAG,IAAI,OAAO,CAAC,IAAI,KAAK,6BAA6B,CACzE,CAAC;AACJ,CAAC","sourcesContent":["import {\n CONTENT_RECORD_ENCRYPTION_SUITE,\n computeContentRecordNonceDomainHash,\n computeDocumentContentRecordCiphertextHash,\n computeDocumentContentRecordMetadataHash,\n verifyWriteHeader,\n type WriteHeader,\n} from \"@tearleads/crypto\";\nimport { isPlainObject as isPlainRecord } from \"@tearleads/validators/isPlainObject\";\nimport {\n DOCUMENT_NOT_FOUND_ERROR_CODE,\n DOCUMENT_SYNC_ERROR_CODES,\n type DocumentContentKeyBundleResponse,\n type DocumentSyncResponse,\n} from \"@tearleads/validators/response\";\nimport { parseWalLsn } from \"@tearleads/validators/util\";\nimport { throwKeyingVerificationShapeFailure } from \"../../../keyingProjectionVerification/error\";\nimport {\n readRecordPositiveInteger,\n readRecordString,\n readWriteHeader,\n serializedPersistedDocumentState,\n} from \"../readers\";\n\nexport { submitDocumentSync } from \"./syncPagination\";\n\nimport type {\n DocumentWriterPublicKeyResolver,\n PersistedDocumentSyncState,\n} from \"../types\";\nimport type { DocumentSyncPlan } from \"./documentSyncTypes\";\nimport { documentWriteAuthorizationForHeader } from \"./syncResponseAuthorization\";\nimport type { DocumentSyncSubmitFailure } from \"./syncSubmitFailure\";\n\n// Remote-primary databases without a portable WAL position use the zero LSN\n// as an explicit \"checkpoint not tracked\" sentinel. It is accepted only when\n// the response declares that mode, letting a local record carrying a checkpoint\n// from another backend move to that primary without weakening tracked checks.\n// This protects against replica lag, not a server that falsely declares its own\n// consistency capability; the authenticated server remains the source of data.\nconst UNTRACKED_COMMIT_LSN = \"0/0\";\n\nexport class DocumentSyncResponseUpdateContentKeyError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"DocumentSyncResponseUpdateContentKeyError\";\n }\n}\n\nfunction assertAcceptedOutgoingUpdateIdsMatchPlan(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n): void {\n const expected = plan.request.outgoingUpdates.map((update) => update.id);\n const accepted = response.acceptedOutgoingUpdateIds;\n const expectedSorted = [...expected].sort();\n const acceptedSorted = [...accepted].sort();\n if (\n expectedSorted.length !== acceptedSorted.length ||\n expectedSorted.some((id, index) => id !== acceptedSorted[index])\n ) {\n throw new Error(\"Document sync response accepted update mismatch\");\n }\n}\n\nasync function assertDocumentSyncResponseUpdateMatchesPlan(input: {\n contentKeyBundlesByEpoch: ReadonlyMap<\n number,\n DocumentContentKeyBundleResponse\n >;\n plan: DocumentSyncPlan;\n update: DocumentSyncResponse[\"updates\"][number];\n resolveWriterPublicKey: DocumentWriterPublicKeyResolver;\n}): Promise<void> {\n const { plan, update } = input;\n if (update.documentId !== plan.documentId) {\n throw new Error(\"Document sync response update document mismatch\");\n }\n const header = readWriteHeader(\n update.writeHeader,\n \"Document sync response write header\",\n );\n await assertDocumentSyncResponseUpdateHashes({ update });\n const contentKeyBundle = assertDocumentSyncResponseUpdateContentKeyBundle({\n contentKeyBundlesByEpoch: input.contentKeyBundlesByEpoch,\n header,\n plan,\n });\n assertDocumentSyncResponseWriteHeaderFields({ header, plan, update });\n await assertDocumentSyncResponseNonceDomain({ header, plan });\n await assertDocumentSyncResponseWriteHeaderSignature({\n header,\n contentKeyBundle,\n plan,\n resolveWriterPublicKey: input.resolveWriterPublicKey,\n update,\n });\n}\n\nfunction assertDocumentSyncResponseUpdateContentKeyBundle(input: {\n contentKeyBundlesByEpoch: ReadonlyMap<\n number,\n DocumentContentKeyBundleResponse\n >;\n header: WriteHeader;\n plan: DocumentSyncPlan;\n}): DocumentContentKeyBundleResponse {\n const { header, plan } = input;\n if (header.contentKeyEpoch > plan.contentKeyEpoch) {\n throw new DocumentSyncResponseUpdateContentKeyError(\n \"Document sync response includes a future content-key epoch\",\n );\n }\n\n const bundle = input.contentKeyBundlesByEpoch.get(header.contentKeyEpoch);\n if (!bundle) {\n throw new DocumentSyncResponseUpdateContentKeyError(\n \"Document sync response content-key bundle missing\",\n );\n }\n if (\n bundle.documentId !== plan.documentId ||\n bundle.contentKeyEpoch !== header.contentKeyEpoch\n ) {\n throw new Error(\"Document sync response content-key bundle mismatch\");\n }\n return bundle;\n}\n\nasync function assertDocumentSyncResponseUpdateHashes(input: {\n update: DocumentSyncResponse[\"updates\"][number];\n}): Promise<void> {\n const { update } = input;\n const ciphertextHash = await computeDocumentContentRecordCiphertextHash(\n update.encryptedData,\n );\n if (\n ciphertextHash !==\n readRecordString(update.writeHeader, \"ciphertextHash\", \"write header\")\n ) {\n throw new Error(\"Document sync response ciphertext hash mismatch\");\n }\n const metadataHash = await computeDocumentContentRecordMetadataHash({\n ...(update.checkpointKind === undefined\n ? {}\n : { checkpointKind: update.checkpointKind }),\n ...(update.checkpointPayloadKind === undefined\n ? {}\n : { checkpointPayloadKind: update.checkpointPayloadKind }),\n documentId: update.documentId,\n partialEndVersionVector: update.partialEndVersionVector,\n partialStartVersionVector: update.partialStartVersionVector,\n plaintextHash: update.plaintextHash,\n ...(update.sourceVersionVector === undefined\n ? {}\n : { sourceVersionVector: update.sourceVersionVector }),\n updateId: update.id,\n });\n if (\n metadataHash !==\n readRecordString(update.writeHeader, \"metadataHash\", \"write header\")\n ) {\n throw new Error(\"Document sync response metadata hash mismatch\");\n }\n}\n\nfunction assertDocumentSyncResponseWriteHeaderFields(input: {\n header: WriteHeader;\n plan: DocumentSyncPlan;\n update: DocumentSyncResponse[\"updates\"][number];\n}): void {\n const { header, plan, update } = input;\n const mustMatchCurrentBoundary = isAcceptedOutgoingSyncUpdate(plan, update);\n\n if (\n header.version !== 1 ||\n header.objectKind !== \"document\" ||\n header.objectId !== plan.documentId ||\n header.organizationId !== plan.organizationId ||\n header.encryptionSuite !== CONTENT_RECORD_ENCRYPTION_SUITE ||\n header.writerKeyFingerprint !== update.authorFingerprint ||\n (mustMatchCurrentBoundary &&\n (header.contentKeyEpoch !== plan.contentKeyEpoch ||\n header.accessManifestHash !== plan.expectedLinkSetManifestHash ||\n header.targetHash !== plan.expectedTargetHash))\n ) {\n throw new Error(\"Document sync response write header mismatch\");\n }\n}\n\nfunction isAcceptedOutgoingSyncUpdate(\n plan: DocumentSyncPlan,\n update: DocumentSyncResponse[\"updates\"][number],\n): boolean {\n return plan.request.outgoingUpdates.some(\n (outgoingUpdate) => outgoingUpdate.id === update.id,\n );\n}\n\nasync function assertDocumentSyncResponseNonceDomain(input: {\n header: WriteHeader;\n plan: DocumentSyncPlan;\n}): Promise<void> {\n const { header, plan } = input;\n const nonceDomainHash = await computeContentRecordNonceDomainHash({\n version: 1,\n organizationId: plan.organizationId,\n objectKind: \"document\",\n objectId: plan.documentId,\n contentKeyEpoch: header.contentKeyEpoch,\n encryptionSuite: CONTENT_RECORD_ENCRYPTION_SUITE,\n contentRecordId: header.contentRecordId,\n });\n if (nonceDomainHash !== header.nonceDomainHash) {\n throw new Error(\"Document sync response nonce domain mismatch\");\n }\n}\n\nasync function assertDocumentSyncResponseWriteHeaderSignature(input: {\n contentKeyBundle: DocumentContentKeyBundleResponse;\n header: WriteHeader;\n plan: DocumentSyncPlan;\n resolveWriterPublicKey: DocumentWriterPublicKeyResolver;\n update: DocumentSyncResponse[\"updates\"][number];\n}): Promise<void> {\n const { header, plan, update } = input;\n const writerPublicKey = await input.resolveWriterPublicKey({\n writerSigningKeyFingerprint: header.writerKeyFingerprint,\n writerUserId: header.writerUserId,\n });\n if (!writerPublicKey) {\n throw new Error(\"Document sync response writer public key missing\");\n }\n\n const documentAuthorization = await documentWriteAuthorizationForHeader({\n allowMissingAuthorization: isAcceptedOutgoingSyncUpdate(plan, update),\n authorizationTargets: update.authorizationTargets,\n dependencyManifestHashes: header.dependencyManifestHashes,\n contentKeyBundle: input.contentKeyBundle,\n manifestHash: header.accessManifestHash,\n plan,\n targetHash: header.targetHash,\n });\n const verified = await verifyWriteHeader({\n authorizationMembership: \"referenced\",\n expectedAccessManifestHash: documentAuthorization\n ? header.accessManifestHash\n : plan.expectedLinkSetManifestHash,\n expectedObject: {\n objectKind: \"document\",\n objectId: plan.documentId,\n organizationId: plan.organizationId,\n },\n header,\n ...(documentAuthorization ? { documentAuthorization } : {}),\n expectedTargetHash: documentAuthorization\n ? header.targetHash\n : plan.expectedTargetHash,\n writerPublicKey,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n}\n\nfunction assertDocumentSyncCommitCheckpointMatchesPlan(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n): void {\n if (\n response.commitLsnMode === \"untracked\" &&\n response.commitLsn !== UNTRACKED_COMMIT_LSN\n ) {\n throw new Error(\n \"Document sync response untracked commit LSN must use the 0/0 sentinel\",\n );\n }\n if (\n response.commitLsn === UNTRACKED_COMMIT_LSN &&\n response.commitLsnMode !== \"untracked\"\n ) {\n throw new Error(\n \"Document sync response 0/0 commit LSN must be declared untracked\",\n );\n }\n if (response.commitLsn !== null) {\n parseWalLsn(response.commitLsn, \"Document sync response commit LSN\");\n }\n if (plan.minLsn === undefined) {\n return;\n }\n const minLsn = parseWalLsn(\n plan.minLsn,\n \"Document sync requested minimum LSN\",\n );\n if (response.commitLsn === null) {\n throw new Error(\"Document sync response commit LSN is missing\");\n }\n if (\n !(\n response.commitLsn === UNTRACKED_COMMIT_LSN &&\n response.commitLsnMode === \"untracked\"\n ) &&\n parseWalLsn(response.commitLsn, \"Document sync response commit LSN\") <\n minLsn\n ) {\n throw new Error(\"Document sync response commit LSN is stale\");\n }\n}\n\nfunction documentSyncManifestEpoch(plan: DocumentSyncPlan): number {\n if (!isPlainRecord(plan.documentManifest.state)) {\n throw new Error(\"Document sync manifest state is invalid\");\n }\n\n return readRecordPositiveInteger(\n plan.documentManifest.state,\n \"epoch\",\n \"Document sync manifest state\",\n );\n}\n\n// The one load-bearing epoch check: no returned update may claim an\n// accessEpoch newer than the current manifest epoch.\nfunction assertDocumentSyncAccessEpochsNotInFuture(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n): void {\n const currentAccessEpoch = documentSyncManifestEpoch(plan);\n for (const update of response.updates) {\n if (update.accessEpoch > currentAccessEpoch) {\n throw new Error(\"Document sync response includes a future access epoch\");\n }\n }\n}\n\ntype DocumentSyncContentKeyBundle =\n DocumentSyncResponse[\"contentKeyBundles\"][number];\n\nfunction documentSyncContentKeyBundlesByEpoch(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n): ReadonlyMap<number, DocumentSyncContentKeyBundle> {\n const currentBundle = plan.sourceContentKeyBundle;\n const bundleByEpoch = new Map<number, DocumentSyncContentKeyBundle>([\n [currentBundle.contentKeyEpoch, currentBundle],\n ]);\n\n // The client already holds the current epoch's bundle; the response\n // carries each older epoch its updates cite, once.\n for (const bundle of response.contentKeyBundles) {\n if (bundle.documentId !== plan.documentId) {\n throw new Error(\n \"Document sync response content-key bundle document mismatch\",\n );\n }\n if (\n !Number.isInteger(bundle.contentKeyEpoch) ||\n bundle.contentKeyEpoch <= 0 ||\n bundle.contentKeyEpoch > currentBundle.contentKeyEpoch\n ) {\n throw new Error(\n \"Document sync response content-key bundle epoch mismatch\",\n );\n }\n if (bundleByEpoch.has(bundle.contentKeyEpoch)) {\n throw new Error(\"Document sync response repeats a content-key epoch\");\n }\n bundleByEpoch.set(bundle.contentKeyEpoch, bundle);\n }\n\n return bundleByEpoch;\n}\n\nasync function persistedDocumentSyncStateFromResponseInternal(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n options: {\n resolveWriterPublicKey: DocumentWriterPublicKeyResolver;\n },\n): Promise<PersistedDocumentSyncState> {\n if (response.documentId !== plan.documentId) {\n throw new Error(\"Document sync response document id mismatch\");\n }\n const contentKeyBundlesByEpoch = documentSyncContentKeyBundlesByEpoch(\n plan,\n response,\n );\n // The request names the planned bundle and targets as its expectations and\n // the server refuses any other pair, so the plan's copies are what it served.\n assertAcceptedOutgoingUpdateIdsMatchPlan(plan, response);\n assertDocumentSyncCommitCheckpointMatchesPlan(plan, response);\n assertDocumentSyncAccessEpochsNotInFuture(plan, response);\n\n await Promise.all(\n response.updates.map((update) =>\n assertDocumentSyncResponseUpdateMatchesPlan({\n contentKeyBundlesByEpoch,\n plan,\n resolveWriterPublicKey: options.resolveWriterPublicKey,\n update,\n }),\n ),\n );\n\n return serializedPersistedDocumentState({\n contentKeyBundle: plan.sourceContentKeyBundle,\n documentId: plan.documentId,\n documentKekTargets: plan.documentKekTargets,\n documentManifestBundle: plan.documentManifest,\n });\n}\n\nexport async function persistedDocumentSyncStateFromResponse(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n options: {\n resolveWriterPublicKey: DocumentWriterPublicKeyResolver;\n },\n): Promise<PersistedDocumentSyncState> {\n try {\n return await persistedDocumentSyncStateFromResponseInternal(\n plan,\n response,\n options,\n );\n } catch (error) {\n if (error instanceof DocumentSyncResponseUpdateContentKeyError) throw error;\n throwKeyingVerificationShapeFailure(error);\n }\n}\n\nexport function isRetryableDocumentSyncConflict(\n failure: DocumentSyncSubmitFailure,\n): boolean {\n return (\n failure.status === 409 &&\n failure.code === DOCUMENT_SYNC_ERROR_CODES.stateStale\n );\n}\n\n// The wipe gate is deliberately strict — coded 404s only, which is the right\n// failure mode for a destructive action. A bare 404 proves nothing about the\n// document: proxy/tunnel error pages, deploy-skew route misses, and\n// container-level lookups all produce one.\nexport function isUpstreamDeletedDocumentSyncFailure(\n failure: DocumentSyncSubmitFailure,\n): boolean {\n return (\n failure.status === 404 && failure.code === DOCUMENT_NOT_FOUND_ERROR_CODE\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"syncResponses.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entRecordNonceDomainHash,\n computeDocumentContentRecordCiphertextHash,\n computeDocumentContentRecordMetadataHash,\n verifyWriteHeader,\n type WriteHeader,\n} from \"@tearleads/crypto\";\nimport { isPlainObject as isPlainRecord } from \"@tearleads/validators/isPlainObject\";\nimport {\n DOCUMENT_NOT_FOUND_ERROR_CODE,\n DOCUMENT_SYNC_ERROR_CODES,\n type DocumentContentKeyBundleResponse,\n type DocumentSyncResponse,\n} from \"@tearleads/validators/response\";\nimport { parseWalLsn } from \"@tearleads/validators/util\";\nimport { throwKeyingVerificationShapeFailure } from \"../../../keyingProjectionVerification/error\";\nimport {\n readRecordPositiveInteger,\n readRecordString,\n readWriteHeader,\n serializedPersistedDocumentState,\n} from \"../readers\";\n\nexport { submitDocumentSync } from \"./syncPagination\";\n\nimport type {\n DocumentWriterPublicKeyResolver,\n PersistedDocumentSyncState,\n} from \"../types\";\nimport type { DocumentSyncPlan } from \"./documentSyncTypes\";\nimport {\n authorizationTargetsForUpdate,\n documentWriteAuthorizationForHeader,\n} from \"./syncResponseAuthorization\";\nimport type { DocumentSyncSubmitFailure } from \"./syncSubmitFailure\";\n\n// Remote-primary databases without a portable WAL position use the zero LSN\n// as an explicit \"checkpoint not tracked\" sentinel. It is accepted only when\n// the response declares that mode, letting a local record carrying a checkpoint\n// from another backend move to that primary without weakening tracked checks.\n// This protects against replica lag, not a server that falsely declares its own\n// consistency capability; the authenticated server remains the source of data.\nconst UNTRACKED_COMMIT_LSN = \"0/0\";\n\nexport class DocumentSyncResponseUpdateContentKeyError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"DocumentSyncResponseUpdateContentKeyError\";\n }\n}\n\nfunction assertAcceptedOutgoingUpdateIdsMatchPlan(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n): void {\n const expected = plan.request.outgoingUpdates.map((update) => update.id);\n const accepted = response.acceptedOutgoingUpdateIds;\n const expectedSorted = [...expected].sort();\n const acceptedSorted = [...accepted].sort();\n if (\n expectedSorted.length !== acceptedSorted.length ||\n expectedSorted.some((id, index) => id !== acceptedSorted[index])\n ) {\n throw new Error(\"Document sync response accepted update mismatch\");\n }\n}\n\nasync function assertDocumentSyncResponseUpdateMatchesPlan(input: {\n contentKeyBundlesByEpoch: ReadonlyMap<\n number,\n DocumentContentKeyBundleResponse\n >;\n plan: DocumentSyncPlan;\n update: DocumentSyncResponse[\"updates\"][number];\n resolveWriterPublicKey: DocumentWriterPublicKeyResolver;\n}): Promise<void> {\n const { plan, update } = input;\n if (update.documentId !== plan.documentId) {\n throw new Error(\"Document sync response update document mismatch\");\n }\n const header = readWriteHeader(\n update.writeHeader,\n \"Document sync response write header\",\n );\n await assertDocumentSyncResponseUpdateHashes({ update });\n const contentKeyBundle = assertDocumentSyncResponseUpdateContentKeyBundle({\n contentKeyBundlesByEpoch: input.contentKeyBundlesByEpoch,\n header,\n plan,\n });\n assertDocumentSyncResponseWriteHeaderFields({ header, plan, update });\n await assertDocumentSyncResponseNonceDomain({ header, plan });\n await assertDocumentSyncResponseWriteHeaderSignature({\n header,\n contentKeyBundle,\n plan,\n resolveWriterPublicKey: input.resolveWriterPublicKey,\n update,\n });\n}\n\nfunction assertDocumentSyncResponseUpdateContentKeyBundle(input: {\n contentKeyBundlesByEpoch: ReadonlyMap<\n number,\n DocumentContentKeyBundleResponse\n >;\n header: WriteHeader;\n plan: DocumentSyncPlan;\n}): DocumentContentKeyBundleResponse {\n const { header, plan } = input;\n if (header.contentKeyEpoch > plan.contentKeyEpoch) {\n throw new DocumentSyncResponseUpdateContentKeyError(\n \"Document sync response includes a future content-key epoch\",\n );\n }\n\n const bundle = input.contentKeyBundlesByEpoch.get(header.contentKeyEpoch);\n if (!bundle) {\n throw new DocumentSyncResponseUpdateContentKeyError(\n \"Document sync response content-key bundle missing\",\n );\n }\n if (\n bundle.documentId !== plan.documentId ||\n bundle.contentKeyEpoch !== header.contentKeyEpoch\n ) {\n throw new Error(\"Document sync response content-key bundle mismatch\");\n }\n return bundle;\n}\n\nasync function assertDocumentSyncResponseUpdateHashes(input: {\n update: DocumentSyncResponse[\"updates\"][number];\n}): Promise<void> {\n const { update } = input;\n const ciphertextHash = await computeDocumentContentRecordCiphertextHash(\n update.encryptedData,\n );\n if (\n ciphertextHash !==\n readRecordString(update.writeHeader, \"ciphertextHash\", \"write header\")\n ) {\n throw new Error(\"Document sync response ciphertext hash mismatch\");\n }\n const metadataHash = await computeDocumentContentRecordMetadataHash({\n ...(update.checkpointKind === undefined\n ? {}\n : { checkpointKind: update.checkpointKind }),\n ...(update.checkpointPayloadKind === undefined\n ? {}\n : { checkpointPayloadKind: update.checkpointPayloadKind }),\n documentId: update.documentId,\n partialEndVersionVector: update.partialEndVersionVector,\n partialStartVersionVector: update.partialStartVersionVector,\n plaintextHash: update.plaintextHash,\n ...(update.sourceVersionVector === undefined\n ? {}\n : { sourceVersionVector: update.sourceVersionVector }),\n updateId: update.id,\n });\n if (\n metadataHash !==\n readRecordString(update.writeHeader, \"metadataHash\", \"write header\")\n ) {\n throw new Error(\"Document sync response metadata hash mismatch\");\n }\n}\n\nfunction assertDocumentSyncResponseWriteHeaderFields(input: {\n header: WriteHeader;\n plan: DocumentSyncPlan;\n update: DocumentSyncResponse[\"updates\"][number];\n}): void {\n const { header, plan, update } = input;\n const mustMatchCurrentBoundary = isAcceptedOutgoingSyncUpdate(plan, update);\n\n if (\n header.version !== 1 ||\n header.objectKind !== \"document\" ||\n header.objectId !== plan.documentId ||\n header.organizationId !== plan.organizationId ||\n header.encryptionSuite !== CONTENT_RECORD_ENCRYPTION_SUITE ||\n header.writerKeyFingerprint !== update.authorFingerprint ||\n (mustMatchCurrentBoundary &&\n (header.contentKeyEpoch !== plan.contentKeyEpoch ||\n header.accessManifestHash !== plan.expectedLinkSetManifestHash ||\n header.targetHash !== plan.expectedTargetHash))\n ) {\n throw new Error(\"Document sync response write header mismatch\");\n }\n}\n\nfunction isAcceptedOutgoingSyncUpdate(\n plan: DocumentSyncPlan,\n update: DocumentSyncResponse[\"updates\"][number],\n): boolean {\n return plan.request.outgoingUpdates.some(\n (outgoingUpdate) => outgoingUpdate.id === update.id,\n );\n}\n\nasync function assertDocumentSyncResponseNonceDomain(input: {\n header: WriteHeader;\n plan: DocumentSyncPlan;\n}): Promise<void> {\n const { header, plan } = input;\n const nonceDomainHash = await computeContentRecordNonceDomainHash({\n version: 1,\n organizationId: plan.organizationId,\n objectKind: \"document\",\n objectId: plan.documentId,\n contentKeyEpoch: header.contentKeyEpoch,\n encryptionSuite: CONTENT_RECORD_ENCRYPTION_SUITE,\n contentRecordId: header.contentRecordId,\n });\n if (nonceDomainHash !== header.nonceDomainHash) {\n throw new Error(\"Document sync response nonce domain mismatch\");\n }\n}\n\nasync function assertDocumentSyncResponseWriteHeaderSignature(input: {\n contentKeyBundle: DocumentContentKeyBundleResponse;\n header: WriteHeader;\n plan: DocumentSyncPlan;\n resolveWriterPublicKey: DocumentWriterPublicKeyResolver;\n update: DocumentSyncResponse[\"updates\"][number];\n}): Promise<void> {\n const { header, plan, update } = input;\n const writerPublicKey = await input.resolveWriterPublicKey({\n writerSigningKeyFingerprint: header.writerKeyFingerprint,\n writerUserId: header.writerUserId,\n });\n if (!writerPublicKey) {\n throw new Error(\"Document sync response writer public key missing\");\n }\n\n const documentAuthorization = await documentWriteAuthorizationForHeader({\n allowMissingAuthorization: isAcceptedOutgoingSyncUpdate(plan, update),\n authorizationTargets: authorizationTargetsForUpdate(update, plan),\n dependencyManifestHashes: header.dependencyManifestHashes,\n contentKeyBundle: input.contentKeyBundle,\n manifestHash: header.accessManifestHash,\n plan,\n targetHash: header.targetHash,\n });\n const verified = await verifyWriteHeader({\n authorizationMembership: \"referenced\",\n expectedAccessManifestHash: documentAuthorization\n ? header.accessManifestHash\n : plan.expectedLinkSetManifestHash,\n expectedObject: {\n objectKind: \"document\",\n objectId: plan.documentId,\n organizationId: plan.organizationId,\n },\n header,\n ...(documentAuthorization ? { documentAuthorization } : {}),\n expectedTargetHash: documentAuthorization\n ? header.targetHash\n : plan.expectedTargetHash,\n writerPublicKey,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n}\n\nfunction assertDocumentSyncCommitCheckpointMatchesPlan(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n): void {\n if (\n response.commitLsnMode === \"untracked\" &&\n response.commitLsn !== UNTRACKED_COMMIT_LSN\n ) {\n throw new Error(\n \"Document sync response untracked commit LSN must use the 0/0 sentinel\",\n );\n }\n if (\n response.commitLsn === UNTRACKED_COMMIT_LSN &&\n response.commitLsnMode !== \"untracked\"\n ) {\n throw new Error(\n \"Document sync response 0/0 commit LSN must be declared untracked\",\n );\n }\n if (response.commitLsn !== null) {\n parseWalLsn(response.commitLsn, \"Document sync response commit LSN\");\n }\n if (plan.minLsn === undefined) {\n return;\n }\n const minLsn = parseWalLsn(\n plan.minLsn,\n \"Document sync requested minimum LSN\",\n );\n if (response.commitLsn === null) {\n throw new Error(\"Document sync response commit LSN is missing\");\n }\n if (\n !(\n response.commitLsn === UNTRACKED_COMMIT_LSN &&\n response.commitLsnMode === \"untracked\"\n ) &&\n parseWalLsn(response.commitLsn, \"Document sync response commit LSN\") <\n minLsn\n ) {\n throw new Error(\"Document sync response commit LSN is stale\");\n }\n}\n\nfunction documentSyncManifestEpoch(plan: DocumentSyncPlan): number {\n if (!isPlainRecord(plan.documentManifest.state)) {\n throw new Error(\"Document sync manifest state is invalid\");\n }\n\n return readRecordPositiveInteger(\n plan.documentManifest.state,\n \"epoch\",\n \"Document sync manifest state\",\n );\n}\n\n// The one load-bearing epoch check: no returned update may claim an\n// accessEpoch newer than the current manifest epoch.\nfunction assertDocumentSyncAccessEpochsNotInFuture(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n): void {\n const currentAccessEpoch = documentSyncManifestEpoch(plan);\n for (const update of response.updates) {\n if (update.accessEpoch > currentAccessEpoch) {\n throw new Error(\"Document sync response includes a future access epoch\");\n }\n }\n}\n\ntype DocumentSyncContentKeyBundle =\n DocumentSyncResponse[\"contentKeyBundles\"][number];\n\nfunction documentSyncContentKeyBundlesByEpoch(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n): ReadonlyMap<number, DocumentSyncContentKeyBundle> {\n const currentBundle = plan.sourceContentKeyBundle;\n const bundleByEpoch = new Map<number, DocumentSyncContentKeyBundle>([\n [currentBundle.contentKeyEpoch, currentBundle],\n ]);\n\n // The client already holds the current epoch's bundle; the response\n // carries each older epoch its updates cite, once.\n for (const bundle of response.contentKeyBundles) {\n if (bundle.documentId !== plan.documentId) {\n throw new Error(\n \"Document sync response content-key bundle document mismatch\",\n );\n }\n if (\n !Number.isInteger(bundle.contentKeyEpoch) ||\n bundle.contentKeyEpoch <= 0 ||\n bundle.contentKeyEpoch > currentBundle.contentKeyEpoch\n ) {\n throw new Error(\n \"Document sync response content-key bundle epoch mismatch\",\n );\n }\n if (bundleByEpoch.has(bundle.contentKeyEpoch)) {\n throw new Error(\"Document sync response repeats a content-key epoch\");\n }\n bundleByEpoch.set(bundle.contentKeyEpoch, bundle);\n }\n\n return bundleByEpoch;\n}\n\nasync function persistedDocumentSyncStateFromResponseInternal(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n options: {\n resolveWriterPublicKey: DocumentWriterPublicKeyResolver;\n },\n): Promise<PersistedDocumentSyncState> {\n if (response.documentId !== plan.documentId) {\n throw new Error(\"Document sync response document id mismatch\");\n }\n const contentKeyBundlesByEpoch = documentSyncContentKeyBundlesByEpoch(\n plan,\n response,\n );\n // The request names the planned bundle and targets as its expectations and\n // the server refuses any other pair, so the plan's copies are what it served.\n assertAcceptedOutgoingUpdateIdsMatchPlan(plan, response);\n assertDocumentSyncCommitCheckpointMatchesPlan(plan, response);\n assertDocumentSyncAccessEpochsNotInFuture(plan, response);\n\n await Promise.all(\n response.updates.map((update) =>\n assertDocumentSyncResponseUpdateMatchesPlan({\n contentKeyBundlesByEpoch,\n plan,\n resolveWriterPublicKey: options.resolveWriterPublicKey,\n update,\n }),\n ),\n );\n\n return serializedPersistedDocumentState({\n contentKeyBundle: plan.sourceContentKeyBundle,\n documentId: plan.documentId,\n documentKekTargets: plan.documentKekTargets,\n documentManifestBundle: plan.documentManifest,\n });\n}\n\nexport async function persistedDocumentSyncStateFromResponse(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n options: {\n resolveWriterPublicKey: DocumentWriterPublicKeyResolver;\n },\n): Promise<PersistedDocumentSyncState> {\n try {\n return await persistedDocumentSyncStateFromResponseInternal(\n plan,\n response,\n options,\n );\n } catch (error) {\n if (error instanceof DocumentSyncResponseUpdateContentKeyError) throw error;\n throwKeyingVerificationShapeFailure(error);\n }\n}\n\nexport function isRetryableDocumentSyncConflict(\n failure: DocumentSyncSubmitFailure,\n): boolean {\n return (\n failure.status === 409 &&\n failure.code === DOCUMENT_SYNC_ERROR_CODES.stateStale\n );\n}\n\n// The wipe gate is deliberately strict — coded 404s only, which is the right\n// failure mode for a destructive action. A bare 404 proves nothing about the\n// document: proxy/tunnel error pages, deploy-skew route misses, and\n// container-level lookups all produce one.\nexport function isUpstreamDeletedDocumentSyncFailure(\n failure: DocumentSyncSubmitFailure,\n): boolean {\n return (\n failure.status === 404 && failure.code === DOCUMENT_NOT_FOUND_ERROR_CODE\n );\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
|
|
2
2
|
import { containerKekWireLevel, } from "../../../internal/validators/response/index.js";
|
|
3
|
+
import { toServedAccessManifestBundle } from "../../../internal/validators/util/index.js";
|
|
3
4
|
import { PrincipalAuthorizationCheckpointUnavailableError } from "../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints.js";
|
|
4
5
|
import { ProjectionDependencyUnavailableError } from "../../shared/dependencyUnavailable.js";
|
|
5
6
|
import { projectionLifetimeGuard } from "../projectionLifetimes.js";
|
|
@@ -37,10 +38,18 @@ export function observeAccessManifestCheckpoints(context, input) {
|
|
|
37
38
|
export function observeVerifiedProjectionBundles(context, bundlesByHash, verifiedByHash) {
|
|
38
39
|
for (const [manifestHash, bundle] of bundlesByHash) {
|
|
39
40
|
const verified = verifiedByHash.get(manifestHash);
|
|
41
|
+
if (!verified)
|
|
42
|
+
continue;
|
|
40
43
|
// A cache hit verifies the hash, not these bytes: store only bytes that
|
|
41
|
-
// a fresh verification accepted, so a citation never replays others.
|
|
42
|
-
|
|
43
|
-
|
|
44
|
+
// a fresh verification accepted, so a citation never replays others. One
|
|
45
|
+
// copy is compared and stored, taken before persistence awaits, so no
|
|
46
|
+
// later read of the projection's object can reach storage.
|
|
47
|
+
const snapshot = structuredClone(bundle);
|
|
48
|
+
if (matchesVerifiedBundleBytes(verified, snapshot))
|
|
49
|
+
context.verifiedBundles.push({
|
|
50
|
+
bundle: toServedAccessManifestBundle(snapshot),
|
|
51
|
+
checkpoint: verified.checkpoint,
|
|
52
|
+
});
|
|
44
53
|
}
|
|
45
54
|
}
|
|
46
55
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkpointContext.js","sourceRoot":"","sources":["checkpointContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAGL,qBAAqB,GACtB,MAAM,gCAAgC,CAAC;AAExC,OAAO,EAAE,gDAAgD,EAAE,MAAM,uEAAuE,CAAC;AAGzI,OAAO,EAAE,oCAAoC,EAAE,MAAM,oCAAoC,CAAC;AAE1F,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EACL,mCAAmC,GAEpC,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,gCAAgC,EAChC,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,8BAA8B,EAAE,MAAM,sBAAsB,CAAC;AACtE,OAAO,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AAmBnE,MAAM,UAAU,iCAAiC,CAAC,KAIjD;IACC,IAAI,OAAO,KAAK,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CAAC;IACD,MAAM,2BAA2B,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAClD,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO;IAC7C,MAAM,cAAc,GAClB,OAAO,CAAC,cAAc;QACtB,OAAO,CAAC,kBAAkB,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,cAAc,CAAC;IACtD,IAAI,cAAc,KAAK,SAAS;QAAE,OAAO;IACzC,IAAI,CAAC;QACH,8BAA8B,CAAC;YAC7B,cAAc;YACd,OAAO,EAAE,KAAK,CAAC,OAAO,IAAI,OAAO,CAAC,OAAO;YACzC,KAAK,EAAE,OAAO,CAAC,kBAAkB;YACjC,QAAQ,EAAE,OAAO,CAAC,QAAQ;SAC3B,CAAC,CAAC;IACL,CAAC;IAAC,MAAM,CAAC;QACP,wEAAwE;QACxE,sEAAsE;IACxE,CAAC;AACH,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedContainerAccessManifest,\n type VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport {\n type AccessManifestBundleWireResponse,\n type ContainerKeyingPathResponse,\n containerKekWireLevel,\n} from \"@tearleads/validators/response\";\nimport type { DocumentPurgeCheckpoint } from \"../../persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { PrincipalAuthorizationCheckpointUnavailableError } from \"../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints\";\nimport type { VerifiedManifestBundle } from \"../../persistence/verifiedManifestBundlePersistence\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../principalContracts/principalPolicyEvidence\";\nimport { ProjectionDependencyUnavailableError } from \"../../shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { projectionLifetimeGuard } from \"../projectionLifetimes\";\nimport {\n assertProjectionVerificationCurrent,\n type OpenPrincipalPolicyBundleReader,\n} from \"../types\";\nimport {\n enforceAccessManifestCheckpoints,\n validateAccessManifestCheckpoints,\n} from \"./accessManifestCheckpointEnforcement\";\nimport { rememberVerifiedContainerHeads } from \"./heldContainerHeads\";\nimport { matchesVerifiedBundleBytes } from \"./verifiedBundleBytes\";\n\nexport interface ProjectionCheckpointContext {\n readonly heldContainerHeads: VerifiedContainerAccessManifest[];\n readonly execSql: ExecSql;\n // The caller's principal policy bundle store, opened per executor.\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n // Local checkpoints read during this verification, one read per object.\n readonly localCheckpoints: Map<string, AccessManifestCheckpoint | null>;\n organizationId?: string | undefined;\n readonly policies: PrincipalPolicyCheckpointEvidence[];\n readonly authorizationPolicies: VerifiedPrincipalPolicySelection[];\n // Served bundles whose manifests verified, and KEK levels of verified\n // paths, stored at finalization.\n readonly verifiedBundles: VerifiedManifestBundle[];\n readonly verifiedHeads: VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: VerifiedAccessManifestCheckpointEvidence[];\n}\n\nexport function createProjectionCheckpointContext(input: {\n readonly execSql: ExecSql;\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n readonly organizationId?: string | undefined;\n}): ProjectionCheckpointContext {\n if (typeof input.execSql !== \"function\") {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Projection verification requires durable keying checkpoint storage\",\n );\n }\n\n return {\n heldContainerHeads: [],\n execSql: input.execSql,\n openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,\n localCheckpoints: new Map(),\n organizationId: input.organizationId,\n policies: [],\n authorizationPolicies: [],\n verifiedBundles: [],\n verifiedHeads: [],\n verifiedManifests: [],\n };\n}\n\nexport function observeAccessManifestCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n },\n): void {\n context.verifiedHeads.push(...input.verifiedHeads);\n context.verifiedManifests.push(...input.verifiedManifests);\n}\n\n/**\n * Records each served bundle whose manifest this verification produced, so\n * the transaction finalizing the checkpoints also stores it for later\n * citation. A bundle the projection carried but verification never reached\n * is skipped.\n */\nexport function observeVerifiedProjectionBundles(\n context: ProjectionCheckpointContext,\n bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>,\n verifiedByHash: ReadonlyMap<\n string,\n { readonly checkpoint: AccessManifestCheckpoint }\n >,\n): void {\n for (const [manifestHash, bundle] of bundlesByHash) {\n const verified = verifiedByHash.get(manifestHash);\n // A cache hit verifies the hash, not these bytes: store only bytes that\n // a fresh verification accepted, so a citation never replays others.\n if (verified && matchesVerifiedBundleBytes(verified, bundle))\n context.verifiedBundles.push({ bundle, checkpoint: verified.checkpoint });\n }\n}\n\n/**\n * Records every KEK level of paths this verification accepted in full, so\n * the finalizing transaction stores them for later citation by digest. A\n * cited level is refilled from these bytes only when the API's current\n * level has the same digest, and is verified again like a served one.\n */\nexport function observeVerifiedKekLevels(\n context: ProjectionCheckpointContext,\n paths: readonly ContainerKeyingPathResponse[],\n): void {\n for (const path of paths)\n for (const kek of path.containerKeks)\n context.verifiedBundles.push({\n kekLevel: containerKekWireLevel(kek),\n organizationId: path.organizationId,\n });\n}\n\nexport function observePrincipalPolicy(\n context: ProjectionCheckpointContext,\n policy: PrincipalPolicyCheckpointEvidence,\n organizationId?: string | undefined,\n): void {\n if (\n organizationId !== undefined &&\n context.organizationId !== undefined &&\n context.organizationId !== organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"projection checkpoint batch crosses organization ownership\",\n );\n }\n context.organizationId ??= organizationId;\n context.policies.push(policy);\n}\n\nexport async function commitProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await enforceAccessManifestCheckpoints({\n documentPurgeCheckpoint: input?.documentPurgeCheckpoint,\n execSql: input?.execSql ?? context.execSql,\n organizationId: context.organizationId,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\n/** Validates against the latest durable pins without persisting new heads. */\nasync function validateProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await validateAccessManifestCheckpoints({\n execSql: input?.execSql ?? context.execSql,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\nexport async function finalizeProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly execSql?: ExecSql | undefined;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n if (input.persistVerificationCheckpoints === false) {\n await validateProjectionCheckpoints(context, input);\n return;\n }\n await commitProjectionCheckpoints(context, input);\n if (input.stillCurrent?.() === false) return;\n const organizationId =\n context.organizationId ??\n context.heldContainerHeads[0]?.state.organizationId;\n if (organizationId === undefined) return;\n try {\n rememberVerifiedContainerHeads({\n organizationId,\n execSql: input.execSql ?? context.execSql,\n heads: context.heldContainerHeads,\n policies: context.policies,\n });\n } catch {\n // Checkpoints are already committed. Optional re-citation evidence must\n // never change successful verification into a caller-visible refusal.\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"checkpointContext.js","sourceRoot":"","sources":["checkpointContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAGL,qBAAqB,GACtB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,4BAA4B,EAAE,MAAM,4BAA4B,CAAC;AAE1E,OAAO,EAAE,gDAAgD,EAAE,MAAM,uEAAuE,CAAC;AAGzI,OAAO,EAAE,oCAAoC,EAAE,MAAM,oCAAoC,CAAC;AAE1F,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EACL,mCAAmC,GAEpC,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,gCAAgC,EAChC,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,8BAA8B,EAAE,MAAM,sBAAsB,CAAC;AACtE,OAAO,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AAmBnE,MAAM,UAAU,iCAAiC,CAAC,KAIjD;IACC,IAAI,OAAO,KAAK,CAAC,OAAO,KAAK,UAAU,EAAE,CAAC;QACxC,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,oEAAoE,CACrE,CAAC;IACJ,CAAC;IAED,OAAO;QACL,kBAAkB,EAAE,EAAE;QACtB,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;QACtE,gBAAgB,EAAE,IAAI,GAAG,EAAE;QAC3B,cAA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,MAAM,cAAc,GAClB,OAAO,CAAC,cAAc;QACtB,OAAO,CAAC,kBAAkB,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,cAAc,CAAC;IACtD,IAAI,cAAc,KAAK,SAAS;QAAE,OAAO;IACzC,IAAI,CAAC;QACH,8BAA8B,CAAC;YAC7B,cAAc;YACd,OAAO,EAAE,KAAK,CAAC,OAAO,IAAI,OAAO,CAAC,OAAO;YACzC,KAAK,EAAE,OAAO,CAAC,kBAAkB;YACjC,QAAQ,EAAE,OAAO,CAAC,QAAQ;SAC3B,CAAC,CAAC;IACL,CAAC;IAAC,MAAM,CAAC;QACP,wEAAwE;QACxE,sEAAsE;IACxE,CAAC;AACH,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedContainerAccessManifest,\n type VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport {\n type AccessManifestBundleWireResponse,\n type ContainerKeyingPathResponse,\n containerKekWireLevel,\n} from \"@tearleads/validators/response\";\nimport { toServedAccessManifestBundle } from \"@tearleads/validators/util\";\nimport type { DocumentPurgeCheckpoint } from \"../../persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { PrincipalAuthorizationCheckpointUnavailableError } from \"../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints\";\nimport type { VerifiedManifestBundle } from \"../../persistence/verifiedManifestBundlePersistence\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../principalContracts/principalPolicyEvidence\";\nimport { ProjectionDependencyUnavailableError } from \"../../shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { projectionLifetimeGuard } from \"../projectionLifetimes\";\nimport {\n assertProjectionVerificationCurrent,\n type OpenPrincipalPolicyBundleReader,\n} from \"../types\";\nimport {\n enforceAccessManifestCheckpoints,\n validateAccessManifestCheckpoints,\n} from \"./accessManifestCheckpointEnforcement\";\nimport { rememberVerifiedContainerHeads } from \"./heldContainerHeads\";\nimport { matchesVerifiedBundleBytes } from \"./verifiedBundleBytes\";\n\nexport interface ProjectionCheckpointContext {\n readonly heldContainerHeads: VerifiedContainerAccessManifest[];\n readonly execSql: ExecSql;\n // The caller's principal policy bundle store, opened per executor.\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n // Local checkpoints read during this verification, one read per object.\n readonly localCheckpoints: Map<string, AccessManifestCheckpoint | null>;\n organizationId?: string | undefined;\n readonly policies: PrincipalPolicyCheckpointEvidence[];\n readonly authorizationPolicies: VerifiedPrincipalPolicySelection[];\n // Served bundles whose manifests verified, and KEK levels of verified\n // paths, stored at finalization.\n readonly verifiedBundles: VerifiedManifestBundle[];\n readonly verifiedHeads: VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: VerifiedAccessManifestCheckpointEvidence[];\n}\n\nexport function createProjectionCheckpointContext(input: {\n readonly execSql: ExecSql;\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n readonly organizationId?: string | undefined;\n}): ProjectionCheckpointContext {\n if (typeof input.execSql !== \"function\") {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Projection verification requires durable keying checkpoint storage\",\n );\n }\n\n return {\n heldContainerHeads: [],\n execSql: input.execSql,\n openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,\n localCheckpoints: new Map(),\n organizationId: input.organizationId,\n policies: [],\n authorizationPolicies: [],\n verifiedBundles: [],\n verifiedHeads: [],\n verifiedManifests: [],\n };\n}\n\nexport function observeAccessManifestCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n },\n): void {\n context.verifiedHeads.push(...input.verifiedHeads);\n context.verifiedManifests.push(...input.verifiedManifests);\n}\n\n/**\n * Records each served bundle whose manifest this verification produced, so\n * the transaction finalizing the checkpoints also stores it for later\n * citation. A bundle the projection carried but verification never reached\n * is skipped.\n */\nexport function observeVerifiedProjectionBundles(\n context: ProjectionCheckpointContext,\n bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>,\n verifiedByHash: ReadonlyMap<\n string,\n { readonly checkpoint: AccessManifestCheckpoint }\n >,\n): void {\n for (const [manifestHash, bundle] of bundlesByHash) {\n const verified = verifiedByHash.get(manifestHash);\n if (!verified) continue;\n // A cache hit verifies the hash, not these bytes: store only bytes that\n // a fresh verification accepted, so a citation never replays others. One\n // copy is compared and stored, taken before persistence awaits, so no\n // later read of the projection's object can reach storage.\n const snapshot = structuredClone(bundle);\n if (matchesVerifiedBundleBytes(verified, snapshot))\n context.verifiedBundles.push({\n bundle: toServedAccessManifestBundle(snapshot),\n checkpoint: verified.checkpoint,\n });\n }\n}\n\n/**\n * Records every KEK level of paths this verification accepted in full, so\n * the finalizing transaction stores them for later citation by digest. A\n * cited level is refilled from these bytes only when the API's current\n * level has the same digest, and is verified again like a served one.\n */\nexport function observeVerifiedKekLevels(\n context: ProjectionCheckpointContext,\n paths: readonly ContainerKeyingPathResponse[],\n): void {\n for (const path of paths)\n for (const kek of path.containerKeks)\n context.verifiedBundles.push({\n kekLevel: containerKekWireLevel(kek),\n organizationId: path.organizationId,\n });\n}\n\nexport function observePrincipalPolicy(\n context: ProjectionCheckpointContext,\n policy: PrincipalPolicyCheckpointEvidence,\n organizationId?: string | undefined,\n): void {\n if (\n organizationId !== undefined &&\n context.organizationId !== undefined &&\n context.organizationId !== organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"projection checkpoint batch crosses organization ownership\",\n );\n }\n context.organizationId ??= organizationId;\n context.policies.push(policy);\n}\n\nexport async function commitProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await enforceAccessManifestCheckpoints({\n documentPurgeCheckpoint: input?.documentPurgeCheckpoint,\n execSql: input?.execSql ?? context.execSql,\n organizationId: context.organizationId,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\n/** Validates against the latest durable pins without persisting new heads. */\nasync function validateProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await validateAccessManifestCheckpoints({\n execSql: input?.execSql ?? context.execSql,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\nexport async function finalizeProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly execSql?: ExecSql | undefined;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n if (input.persistVerificationCheckpoints === false) {\n await validateProjectionCheckpoints(context, input);\n return;\n }\n await commitProjectionCheckpoints(context, input);\n if (input.stillCurrent?.() === false) return;\n const organizationId =\n context.organizationId ??\n context.heldContainerHeads[0]?.state.organizationId;\n if (organizationId === undefined) return;\n try {\n rememberVerifiedContainerHeads({\n organizationId,\n execSql: input.execSql ?? context.execSql,\n heads: context.heldContainerHeads,\n policies: context.policies,\n });\n } catch {\n // Checkpoints are already committed. Optional re-citation evidence must\n // never change successful verification into a caller-visible refusal.\n }\n}\n"]}
|
|
@@ -1,26 +1,91 @@
|
|
|
1
|
-
import { readKeyingCanonicalJson, serializeKeyingCanonicalJson, } from "../../../internal/crypto/index.js";
|
|
2
|
-
// The exact
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
1
|
+
import { KeyingVerificationError, readKeyingCanonicalJson, serializeKeyingCanonicalJson, } from "../../../internal/crypto/index.js";
|
|
2
|
+
// The exact bundle each manifest was verified from (signed event, body,
|
|
3
|
+
// manifest and the completed state), keyed by the verified result. A later
|
|
4
|
+
// projection can hit the same verified hash with different bytes or a
|
|
5
|
+
// different completed state; only what was itself verified may answer from
|
|
6
|
+
// the cache or be stored for citation (in its served form).
|
|
6
7
|
const verifiedBundleBytes = new WeakMap();
|
|
7
8
|
function canonicalBytes(bundle) {
|
|
8
9
|
try {
|
|
9
|
-
return serializeKeyingCanonicalJson(readKeyingCanonicalJson(
|
|
10
|
+
return serializeKeyingCanonicalJson(readKeyingCanonicalJson({
|
|
11
|
+
event: bundle.event,
|
|
12
|
+
manifest: bundle.manifest,
|
|
13
|
+
manifestHash: bundle.manifestHash,
|
|
14
|
+
state: bundle.state,
|
|
15
|
+
}, "Verified manifest bundle"));
|
|
10
16
|
}
|
|
11
17
|
catch {
|
|
12
18
|
return null;
|
|
13
19
|
}
|
|
14
20
|
}
|
|
21
|
+
/** Plain-data equality that keeps distinctions JSON cannot carry (`-0`). */
|
|
22
|
+
function sameData(left, right) {
|
|
23
|
+
if (typeof left !== "object" || left === null)
|
|
24
|
+
return Object.is(left, right);
|
|
25
|
+
if (typeof right !== "object" || right === null)
|
|
26
|
+
return false;
|
|
27
|
+
if (Array.isArray(left) !== Array.isArray(right))
|
|
28
|
+
return false;
|
|
29
|
+
const keys = Object.keys(left);
|
|
30
|
+
return (keys.length === Object.keys(right).length &&
|
|
31
|
+
keys.every((key) => Object.hasOwn(right, key) &&
|
|
32
|
+
sameData(Reflect.get(left, key), Reflect.get(right, key))));
|
|
33
|
+
}
|
|
15
34
|
/** Remember the bundle a fresh verification accepted for `verified`. */
|
|
16
35
|
export function recordVerifiedBundleBytes(verified, bundle) {
|
|
17
36
|
const bytes = canonicalBytes(bundle);
|
|
18
37
|
if (bytes !== null)
|
|
19
38
|
verifiedBundleBytes.set(verified, bytes);
|
|
20
39
|
}
|
|
21
|
-
|
|
40
|
+
// Bundles frozen here after they matched a verified result. A frozen bundle
|
|
41
|
+
// of plain data can no longer change, so every later comparison against the
|
|
42
|
+
// same result is answered without serializing it again, and a caller reading
|
|
43
|
+
// it reads exactly the bytes verification accepted.
|
|
44
|
+
const frozenMatches = new WeakMap();
|
|
45
|
+
/** Whether every value under `value` is a plain data property. */
|
|
46
|
+
function isPlainData(value) {
|
|
47
|
+
if (typeof value !== "object" || value === null)
|
|
48
|
+
return true;
|
|
49
|
+
return Object.values(Object.getOwnPropertyDescriptors(value)).every((descriptor) => "value" in descriptor && isPlainData(descriptor.value));
|
|
50
|
+
}
|
|
51
|
+
function deepFreeze(value) {
|
|
52
|
+
if (typeof value !== "object" || value === null)
|
|
53
|
+
return;
|
|
54
|
+
Object.freeze(value);
|
|
55
|
+
for (const child of Object.values(value))
|
|
56
|
+
deepFreeze(child);
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Whether `bundle` is byte-identical to the one `verified` came from. A
|
|
60
|
+
* plain-data bundle that matches is frozen, so it stays the verified copy.
|
|
61
|
+
*/
|
|
22
62
|
export function matchesVerifiedBundleBytes(verified, bundle) {
|
|
63
|
+
if (frozenMatches.get(bundle) === verified)
|
|
64
|
+
return true;
|
|
23
65
|
const recorded = verifiedBundleBytes.get(verified);
|
|
24
|
-
|
|
66
|
+
const matches = recorded !== undefined && recorded === canonicalBytes(bundle);
|
|
67
|
+
if (matches && isPlainData(bundle)) {
|
|
68
|
+
deepFreeze(bundle);
|
|
69
|
+
frozenMatches.set(bundle, verified);
|
|
70
|
+
}
|
|
71
|
+
return matches;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Verification checks a copy taken before its first await; the caller reads
|
|
75
|
+
* the bundle it passed, so on return that bundle must still be the copy
|
|
76
|
+
* verification accepted.
|
|
77
|
+
*/
|
|
78
|
+
export function assertUnchangedSinceVerification(verified, bundle, label, snapshot) {
|
|
79
|
+
// A bundle that could not be serialized was never recorded (nor stored for
|
|
80
|
+
// citation): it must equal the copy verification checked, and it is frozen
|
|
81
|
+
// all the same, so it stays that copy.
|
|
82
|
+
const unchanged = verifiedBundleBytes.has(verified)
|
|
83
|
+
? matchesVerifiedBundleBytes(verified, bundle)
|
|
84
|
+
: snapshot !== undefined && sameData(bundle, snapshot);
|
|
85
|
+
if (unchanged && !verifiedBundleBytes.has(verified) && isPlainData(bundle))
|
|
86
|
+
deepFreeze(bundle);
|
|
87
|
+
if (!unchanged) {
|
|
88
|
+
throw new KeyingVerificationError("hash_mismatch", `${label} changed while it was verified`);
|
|
89
|
+
}
|
|
25
90
|
}
|
|
26
91
|
//# sourceMappingURL=verifiedBundleBytes.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"verifiedBundleBytes.js","sourceRoot":"","sources":["verifiedBundleBytes.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"verifiedBundleBytes.js","sourceRoot":"","sources":["verifiedBundleBytes.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,uBAAuB,EACvB,4BAA4B,GAC7B,MAAM,mBAAmB,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nD,MAAM,OAAO,GAAG,QAAQ,KAAK,SAAS,IAAI,QAAQ,KAAK,cAAc,CAAC,MAAM,CAAC,CAAC;IAC9E,IAAI,OAAO,IAAI,WAAW,CAAC,MAAM,CAAC,EAAE,CAAC;QACnC,UAAU,CAAC,MAAM,CAAC,CAAC;QACnB,aAAa,CAAC,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IACtC,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,gCAAgC,CAC9C,QAAgB,EAChB,MAAwC,EACxC,KAAa,EACb,QAA2C;IAE3C,2EAA2E;IAC3E,2EAA2E;IAC3E,uCAAuC;IACvC,MAAM,SAAS,GAAG,mBAAmB,CAAC,GAAG,CAAC,QAAQ,CAAC;QACjD,CAAC,CAAC,0BAA0B,CAAC,QAAQ,EAAE,MAAM,CAAC;QAC9C,CAAC,CAAC,QAAQ,KAAK,SAAS,IAAI,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IACzD,IAAI,SAAS,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,WAAW,CAAC,MAAM,CAAC;QACxE,UAAU,CAAC,MAAM,CAAC,CAAC;IACrB,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,GAAG,KAAK,gCAAgC,CACzC,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n readKeyingCanonicalJson,\n serializeKeyingCanonicalJson,\n} from \"@tearleads/crypto\";\nimport type { AccessManifestBundleWireResponse } from \"@tearleads/validators/response\";\n\n// The exact bundle each manifest was verified from (signed event, body,\n// manifest and the completed state), keyed by the verified result. A later\n// projection can hit the same verified hash with different bytes or a\n// different completed state; only what was itself verified may answer from\n// the cache or be stored for citation (in its served form).\nconst verifiedBundleBytes = new WeakMap<object, string>();\n\nfunction canonicalBytes(\n bundle: AccessManifestBundleWireResponse,\n): string | null {\n try {\n return serializeKeyingCanonicalJson(\n readKeyingCanonicalJson(\n {\n event: bundle.event,\n manifest: bundle.manifest,\n manifestHash: bundle.manifestHash,\n state: bundle.state,\n },\n \"Verified manifest bundle\",\n ),\n );\n } catch {\n return null;\n }\n}\n\n/** Plain-data equality that keeps distinctions JSON cannot carry (`-0`). */\nfunction sameData(left: unknown, right: unknown): boolean {\n if (typeof left !== \"object\" || left === null) return Object.is(left, right);\n if (typeof right !== \"object\" || right === null) return false;\n if (Array.isArray(left) !== Array.isArray(right)) return false;\n const keys = Object.keys(left);\n return (\n keys.length === Object.keys(right).length &&\n keys.every(\n (key) =>\n Object.hasOwn(right, key) &&\n sameData(Reflect.get(left, key), Reflect.get(right, key)),\n )\n );\n}\n\n/** Remember the bundle a fresh verification accepted for `verified`. */\nexport function recordVerifiedBundleBytes(\n verified: object,\n bundle: AccessManifestBundleWireResponse,\n): void {\n const bytes = canonicalBytes(bundle);\n if (bytes !== null) verifiedBundleBytes.set(verified, bytes);\n}\n\n// Bundles frozen here after they matched a verified result. A frozen bundle\n// of plain data can no longer change, so every later comparison against the\n// same result is answered without serializing it again, and a caller reading\n// it reads exactly the bytes verification accepted.\nconst frozenMatches = new WeakMap<object, object>();\n\n/** Whether every value under `value` is a plain data property. */\nfunction isPlainData(value: unknown): boolean {\n if (typeof value !== \"object\" || value === null) return true;\n return Object.values(Object.getOwnPropertyDescriptors(value)).every(\n (descriptor) => \"value\" in descriptor && isPlainData(descriptor.value),\n );\n}\n\nfunction deepFreeze(value: unknown): void {\n if (typeof value !== \"object\" || value === null) return;\n Object.freeze(value);\n for (const child of Object.values(value)) deepFreeze(child);\n}\n\n/**\n * Whether `bundle` is byte-identical to the one `verified` came from. A\n * plain-data bundle that matches is frozen, so it stays the verified copy.\n */\nexport function matchesVerifiedBundleBytes(\n verified: object,\n bundle: AccessManifestBundleWireResponse,\n): boolean {\n if (frozenMatches.get(bundle) === verified) return true;\n const recorded = verifiedBundleBytes.get(verified);\n const matches = recorded !== undefined && recorded === canonicalBytes(bundle);\n if (matches && isPlainData(bundle)) {\n deepFreeze(bundle);\n frozenMatches.set(bundle, verified);\n }\n return matches;\n}\n\n/**\n * Verification checks a copy taken before its first await; the caller reads\n * the bundle it passed, so on return that bundle must still be the copy\n * verification accepted.\n */\nexport function assertUnchangedSinceVerification(\n verified: object,\n bundle: AccessManifestBundleWireResponse,\n label: string,\n snapshot?: AccessManifestBundleWireResponse,\n): void {\n // A bundle that could not be serialized was never recorded (nor stored for\n // citation): it must equal the copy verification checked, and it is frozen\n // all the same, so it stays that copy.\n const unchanged = verifiedBundleBytes.has(verified)\n ? matchesVerifiedBundleBytes(verified, bundle)\n : snapshot !== undefined && sameData(bundle, snapshot);\n if (unchanged && !verifiedBundleBytes.has(verified) && isPlainData(bundle))\n deepFreeze(bundle);\n if (!unchanged) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n `${label} changed while it was verified`,\n );\n }\n}\n"]}
|
|
@@ -1,9 +1,21 @@
|
|
|
1
1
|
import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
|
|
2
2
|
import { readCanonicalRecord } from "../../keying/canonicalJson.js";
|
|
3
|
+
import { matchesVerifiedBundleBytes } from "../checkpoints/verifiedBundleBytes.js";
|
|
3
4
|
import { readKeyingVerificationShape } from "../error.js";
|
|
4
|
-
import {
|
|
5
|
+
import { readRecordString } from "../readers.js";
|
|
6
|
+
/**
|
|
7
|
+
* The container a served bundle's manifest names, before it verifies. The
|
|
8
|
+
* manifest hash commits to it, and verification binds it to the signed event
|
|
9
|
+
* and the derived state, so a selection made here is checked there.
|
|
10
|
+
*/
|
|
5
11
|
function bundleContainerId(bundle, label) {
|
|
6
|
-
return readKeyingVerificationShape(() =>
|
|
12
|
+
return readKeyingVerificationShape(() => {
|
|
13
|
+
const manifest = readCanonicalRecord(bundle.manifest, `${label} manifest`);
|
|
14
|
+
return readRecordString(manifest, "objectKind", `${label} manifest`) ===
|
|
15
|
+
"container"
|
|
16
|
+
? readRecordString(manifest, "objectId", `${label} manifest`)
|
|
17
|
+
: null;
|
|
18
|
+
});
|
|
7
19
|
}
|
|
8
20
|
function citedContainerId(input, manifestHash) {
|
|
9
21
|
const verified = input.verifiedByHash.get(manifestHash);
|
|
@@ -24,10 +36,14 @@ function citedManifestHashForContainer(input, cited, containerId) {
|
|
|
24
36
|
return manifestHash;
|
|
25
37
|
}
|
|
26
38
|
async function resolveCitedManifest(input, manifestHash, containerId) {
|
|
39
|
+
// The cache answers only for the bytes it verified (a match is frozen, so
|
|
40
|
+
// each ancestor is serialized once however many descendants cite it); a
|
|
41
|
+
// served ancestor that differs is verified as a cold device would.
|
|
27
42
|
const verified = input.verifiedByHash.get(manifestHash);
|
|
28
|
-
if (verified)
|
|
29
|
-
return verified;
|
|
30
43
|
const bundle = input.bundlesByHash.get(manifestHash);
|
|
44
|
+
if (verified && (!bundle || matchesVerifiedBundleBytes(verified, bundle))) {
|
|
45
|
+
return verified;
|
|
46
|
+
}
|
|
31
47
|
if (!bundle) {
|
|
32
48
|
throw new KeyingVerificationError("missing_dependency", `${input.label} cites a head of container ${containerId} that the projection does not serve`);
|
|
33
49
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"containerAncestorCitations.js","sourceRoot":"","sources":["containerAncestorCitations.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAAE,2BAA2B,EAAE,MAAM,UAAU,CAAC;AACvD,OAAO,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AAuCtD,SAAS,iBAAiB,CACxB,MAAwC,EACxC,KAAa;IAEb,OAAO,2BAA2B,CAAC,GAAG,EAAE,CACtC,wBAAwB,CACtB,mBAAmB,CAAC,MAAM,CAAC,KAAK,EAAE,GAAG,KAAK,QAAQ,CAAC,EACnD,aAAa,E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,EAAE,CAAC;gBACrD,2BAA2B,CAAC,KAAK,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC;YACtD,CAAC;QACH,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,yCAAyC,CAAC,KAKzD;IACC,MAAM,SAAS,GAAG,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,wBAAwB,CAAC;IAClE,KAAK,MAAM,MAAM,IAAI,KAAK,CAAC,eAAe,EAAE,CAAC;QAC3C,MAAM,WAAW,GAAG,MAAM,CAAC,KAAK,CAAC,WAAW,CAAC;QAC7C,MAAM,KAAK,GAAG,iBAAiB,CAAC;YAC9B,KAAK,EAAE,SAAS;YAChB,WAAW;YACX,KAAK,EAAE,KAAK,CAAC,KAAK;YAClB,cAAc,EAAE,KAAK,CAAC,cAAc;SACrC,CAAC,CAAC;QACH,IAAI,CAAC,KAAK,IAAI,YAAY,CAAC,KAAK,CAAC,cAAc,EAAE,MAAM,EAAE,KAAK,CAAC;YAAE,SAAS;QAC1E,MAAM,IAAI,uBAAuB,CAC/B,UAAU,EACV,GAAG,KAAK,CAAC,KAAK,uCAAuC,WAAW,qDAAqD,CACtH,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type VerifiedAccessEvent,\n type VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport type { AccessManifestBundleWireResponse } from \"@tearleads/validators/response\";\nimport { readCanonicalRecord } from \"../../keying/canonicalJson\";\nimport { readKeyingVerificationShape } from \"../error\";\nimport { readRecordNullableString } from \"../readers\";\n\n/**\n * A container manifest pins the parent manifest it was created or moved\n * under, and successors inherit that pin, so the pin says nothing about the\n * ancestor heads a later grant, revoke, or rekey was actually authorized\n * under. Those heads are in the event: every container event signs the\n * manifest hashes of the path it was committed against, and the API refuses\n * an event whose citations are not the current heads at commit time. So a\n * head's authorization path is rebuilt here from its citations, root to\n * parent, and the signer is checked against those heads rather than against\n * whatever path the server pairs with the manifest.\n *\n * A head must also cite, for every ancestor, a head that is or descends from\n * the head an earlier signed statement already established, so an ancestor\n * head one signed statement established can never be rolled back or forked\n * away for a later one.\n *\n * As with principal policies, a successor new to a device need not cite the\n * authority's served current head. An honest server serves a\n * child head citing the ancestor head that was current when it was\n * committed, signed by a member since revoked at that ancestor, and refusing\n * that shape would leave every device holding the child unable to supersede\n * it. What can be refused is the opposite disagreement: a served current\n * ancestor head that does not descend from a head the child's signed event\n * proves exists is a stale or forked ancestor, whatever the server calls\n * current.\n */\n\ninterface CitedAncestorResolutionInput {\n readonly bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>;\n readonly label: string;\n readonly verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n readonly verifyHistoryBundle: (\n bundle: AccessManifestBundleWireResponse,\n label: string,\n ) => Promise<VerifiedContainerAccessManifest>;\n}\n\nfunction bundleContainerId(\n bundle: AccessManifestBundleWireResponse,\n label: string,\n): string | null {\n return readKeyingVerificationShape(() =>\n readRecordNullableString(\n readCanonicalRecord(bundle.state, `${label} state`),\n \"containerId\",\n `${label} state`,\n ),\n );\n}\n\nfunction citedContainerId(\n input: CitedLineageInput,\n manifestHash: string,\n): string | null {\n const verified = input.verifiedByHash.get(manifestHash);\n if (verified) return verified.state.containerId;\n const bundle = input.bundlesByHash.get(manifestHash);\n return bundle ? bundleContainerId(bundle, input.label) : null;\n}\n\nfunction citedManifestHashForContainer(\n input: CitedAncestorResolutionInput,\n cited: readonly string[],\n containerId: string,\n): string {\n const hashes = cited.filter(\n (manifestHash) => citedContainerId(input, manifestHash) === containerId,\n );\n const [manifestHash] = hashes;\n if (manifestHash === undefined) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n `${input.label} does not cite a served head of its parent container ${containerId}`,\n );\n }\n if (hashes.length > 1) {\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n `${input.label} cites more than one head of container ${containerId}`,\n );\n }\n return manifestHash;\n}\n\nasync function resolveCitedManifest(\n input: CitedAncestorResolutionInput,\n manifestHash: string,\n containerId: string,\n): Promise<VerifiedContainerAccessManifest> {\n const verified = input.verifiedByHash.get(manifestHash);\n if (verified) return verified;\n const bundle = input.bundlesByHash.get(manifestHash);\n if (!bundle) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n `${input.label} cites a head of container ${containerId} that the projection does not serve`,\n );\n }\n return input.verifyHistoryBundle(\n bundle,\n `${input.label} cited ancestor ${containerId}`,\n );\n}\n\n/**\n * The ancestor path, root first, that a container event cites, ending at the\n * head of `parentContainerId`. Empty for a root container.\n */\nexport async function resolveCitedAncestorPath(\n input: CitedAncestorResolutionInput & {\n readonly event: VerifiedAccessEvent;\n readonly parentContainerId: string | null;\n },\n): Promise<VerifiedContainerAccessManifest[]> {\n const cited = input.event.event.dependencyManifestHashes;\n const chain: VerifiedContainerAccessManifest[] = [];\n const seen = new Set<string>();\n let containerId = input.parentContainerId;\n while (containerId !== null) {\n if (seen.has(containerId)) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `${input.label} cited ancestors form a cycle at ${containerId}`,\n );\n }\n seen.add(containerId);\n const ancestor = await resolveCitedManifest(\n input,\n citedManifestHashForContainer(input, cited, containerId),\n containerId,\n );\n chain.unshift(ancestor);\n containerId = ancestor.state.parentContainerId;\n }\n return chain;\n}\n\n/** What the lineage rules read: the served and the verified bundles. */\nexport type CitedLineageInput = Pick<\n CitedAncestorResolutionInput,\n \"bundlesByHash\" | \"label\" | \"verifiedByHash\"\n>;\n\n/**\n * The verified head of `containerId` among the cited hashes, if any. Reads\n * verified manifests only: a cited hash the pass has not verified is not a\n * head to reason about, and every caller runs after the cited ancestor path\n * resolved and verified the chain. An event cites one head per container,\n * so a second verified one is a served citation set that was tampered with,\n * not a choice to make.\n */\nexport function verifiedCitedHead(input: {\n readonly cited: readonly string[];\n readonly containerId: string;\n readonly label: string;\n readonly verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n}): VerifiedContainerAccessManifest | undefined {\n let found: VerifiedContainerAccessManifest | undefined;\n for (const manifestHash of input.cited) {\n const verified = input.verifiedByHash.get(manifestHash);\n if (verified?.state.containerId !== input.containerId) continue;\n if (found && found.manifestHash !== verified.manifestHash) {\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n `${input.label} cites more than one head of container ${input.containerId}`,\n );\n }\n found = verified;\n }\n return found;\n}\n\n/**\n * Whether `head` is `floor` or descends from it through verified\n * predecessors. Epochs alone would let a same-epoch fork signed under an\n * older head pass; lineage cannot be forged without the chain. Every\n * predecessor of a verified manifest was verified with it, so a hop that is\n * not in the verified set means the chain was not served.\n */\nfunction descendsFrom(\n verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>,\n head: VerifiedContainerAccessManifest,\n floor: VerifiedContainerAccessManifest,\n): boolean {\n let current: VerifiedContainerAccessManifest | undefined = head;\n while (current && current.state.epoch >= floor.state.epoch) {\n if (current.manifestHash === floor.manifestHash) return true;\n const previousHash: string | null = current.state.previousManifestHash;\n current =\n previousHash === null ? undefined : verifiedByHash.get(previousHash);\n }\n return false;\n}\n\n/** The cited head must be the established head or descend from it. */\nfunction assertCitedHeadDescendsFrom(\n input: CitedLineageInput,\n cited: VerifiedContainerAccessManifest,\n floor: VerifiedContainerAccessManifest,\n): void {\n if (descendsFrom(input.verifiedByHash, cited, floor)) return;\n throw new KeyingVerificationError(\n \"rollback\",\n `${input.label} cites a head of container ${cited.state.containerId} that does not descend from the head an earlier signed statement already proved current`,\n );\n}\n\n/**\n * A head must not cite a head of any ancestor that does not descend from the\n * head an earlier signed statement already established: the manifest before\n * it cited that ancestor, the previous manifest's own pin when this is its\n * parent, or a cited child of that ancestor was created or moved under it and\n * cited it. Ancestors no statement establishes are skipped.\n */\nexport function assertCitedAncestorsDoNotRegress(\n input: CitedLineageInput & {\n readonly citedAncestors: readonly VerifiedContainerAccessManifest[];\n readonly previousManifest: VerifiedContainerAccessManifest | null;\n },\n): void {\n const previous = input.previousManifest;\n const previousCited = previous?.event.event.dependencyManifestHashes ?? [];\n input.citedAncestors.forEach((ancestor, index) => {\n const containerId = ancestor.state.containerId;\n const citedChild = input.citedAncestors[index + 1] ?? previous;\n const floors = [\n verifiedCitedHead({\n cited: previousCited,\n containerId,\n label: input.label,\n verifiedByHash: input.verifiedByHash,\n }),\n ...(citedChild\n ? [\n input.verifiedByHash.get(citedChild.state.parentManifestHash ?? \"\"),\n verifiedCitedHead({\n cited: citedChild.event.event.dependencyManifestHashes,\n containerId,\n label: input.label,\n verifiedByHash: input.verifiedByHash,\n }),\n ]\n : []),\n ];\n for (const floor of floors) {\n if (floor && floor.state.containerId === containerId) {\n assertCitedHeadDescendsFrom(input, ancestor, floor);\n }\n }\n });\n}\n\n/**\n * Every served current ancestor head must be, or descend through verified\n * predecessors from, the head of that container the head's signed event\n * cites. A served head older than the cited one, or a same-epoch fork of it,\n * is a rollback the signature proves: the cited head exists. A served head\n * newer than the cited one is the ordinary lag of a descendant behind its\n * ancestors, and an ancestor the head does not cite at all joined the path\n * when an ancestor between them moved; neither is refused.\n */\nexport function assertServedAncestorsDescendFromCitations(input: {\n readonly head: VerifiedContainerAccessManifest;\n readonly label: string;\n readonly servedAncestors: readonly VerifiedContainerAccessManifest[];\n readonly verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n}): void {\n const citations = input.head.event.event.dependencyManifestHashes;\n for (const served of input.servedAncestors) {\n const containerId = served.state.containerId;\n const cited = verifiedCitedHead({\n cited: citations,\n containerId,\n label: input.label,\n verifiedByHash: input.verifiedByHash,\n });\n if (!cited || descendsFrom(input.verifiedByHash, served, cited)) continue;\n throw new KeyingVerificationError(\n \"rollback\",\n `${input.label} cites a head of ancestor container ${containerId} that the served current head does not descend from`,\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"containerAncestorCitations.js","sourceRoot":"","sources":["containerAncestorCitations.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAGxB,MAAM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,EAAE,KAAK,CAAC,KAAK;YAClB,cAAc,EAAE,KAAK,CAAC,cAAc;SACrC,CAAC,CAAC;QACH,IAAI,CAAC,KAAK,IAAI,YAAY,CAAC,KAAK,CAAC,cAAc,EAAE,MAAM,EAAE,KAAK,CAAC;YAAE,SAAS;QAC1E,MAAM,IAAI,uBAAuB,CAC/B,UAAU,EACV,GAAG,KAAK,CAAC,KAAK,uCAAuC,WAAW,qDAAqD,CACtH,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type VerifiedAccessEvent,\n type VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport type { AccessManifestBundleWireResponse } from \"@tearleads/validators/response\";\nimport { readCanonicalRecord } from \"../../keying/canonicalJson\";\nimport { matchesVerifiedBundleBytes } from \"../checkpoints/verifiedBundleBytes\";\nimport { readKeyingVerificationShape } from \"../error\";\nimport { readRecordString } from \"../readers\";\n\n/**\n * A container manifest pins the parent manifest it was created or moved\n * under, and successors inherit that pin, so the pin says nothing about the\n * ancestor heads a later grant, revoke, or rekey was actually authorized\n * under. Those heads are in the event: every container event signs the\n * manifest hashes of the path it was committed against, and the API refuses\n * an event whose citations are not the current heads at commit time. So a\n * head's authorization path is rebuilt here from its citations, root to\n * parent, and the signer is checked against those heads rather than against\n * whatever path the server pairs with the manifest.\n *\n * A head must also cite, for every ancestor, a head that is or descends from\n * the head an earlier signed statement already established, so an ancestor\n * head one signed statement established can never be rolled back or forked\n * away for a later one.\n *\n * As with principal policies, a successor new to a device need not cite the\n * authority's served current head. An honest server serves a\n * child head citing the ancestor head that was current when it was\n * committed, signed by a member since revoked at that ancestor, and refusing\n * that shape would leave every device holding the child unable to supersede\n * it. What can be refused is the opposite disagreement: a served current\n * ancestor head that does not descend from a head the child's signed event\n * proves exists is a stale or forked ancestor, whatever the server calls\n * current.\n */\n\ninterface CitedAncestorResolutionInput {\n readonly bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>;\n readonly label: string;\n readonly verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n readonly verifyHistoryBundle: (\n bundle: AccessManifestBundleWireResponse,\n label: string,\n ) => Promise<VerifiedContainerAccessManifest>;\n}\n\n/**\n * The container a served bundle's manifest names, before it verifies. The\n * manifest hash commits to it, and verification binds it to the signed event\n * and the derived state, so a selection made here is checked there.\n */\nfunction bundleContainerId(\n bundle: AccessManifestBundleWireResponse,\n label: string,\n): string | null {\n return readKeyingVerificationShape(() => {\n const manifest = readCanonicalRecord(bundle.manifest, `${label} manifest`);\n return readRecordString(manifest, \"objectKind\", `${label} manifest`) ===\n \"container\"\n ? readRecordString(manifest, \"objectId\", `${label} manifest`)\n : null;\n });\n}\n\nfunction citedContainerId(\n input: CitedLineageInput,\n manifestHash: string,\n): string | null {\n const verified = input.verifiedByHash.get(manifestHash);\n if (verified) return verified.state.containerId;\n const bundle = input.bundlesByHash.get(manifestHash);\n return bundle ? bundleContainerId(bundle, input.label) : null;\n}\n\nfunction citedManifestHashForContainer(\n input: CitedAncestorResolutionInput,\n cited: readonly string[],\n containerId: string,\n): string {\n const hashes = cited.filter(\n (manifestHash) => citedContainerId(input, manifestHash) === containerId,\n );\n const [manifestHash] = hashes;\n if (manifestHash === undefined) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n `${input.label} does not cite a served head of its parent container ${containerId}`,\n );\n }\n if (hashes.length > 1) {\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n `${input.label} cites more than one head of container ${containerId}`,\n );\n }\n return manifestHash;\n}\n\nasync function resolveCitedManifest(\n input: CitedAncestorResolutionInput,\n manifestHash: string,\n containerId: string,\n): Promise<VerifiedContainerAccessManifest> {\n // The cache answers only for the bytes it verified (a match is frozen, so\n // each ancestor is serialized once however many descendants cite it); a\n // served ancestor that differs is verified as a cold device would.\n const verified = input.verifiedByHash.get(manifestHash);\n const bundle = input.bundlesByHash.get(manifestHash);\n if (verified && (!bundle || matchesVerifiedBundleBytes(verified, bundle))) {\n return verified;\n }\n if (!bundle) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n `${input.label} cites a head of container ${containerId} that the projection does not serve`,\n );\n }\n return input.verifyHistoryBundle(\n bundle,\n `${input.label} cited ancestor ${containerId}`,\n );\n}\n\n/**\n * The ancestor path, root first, that a container event cites, ending at the\n * head of `parentContainerId`. Empty for a root container.\n */\nexport async function resolveCitedAncestorPath(\n input: CitedAncestorResolutionInput & {\n readonly event: VerifiedAccessEvent;\n readonly parentContainerId: string | null;\n },\n): Promise<VerifiedContainerAccessManifest[]> {\n const cited = input.event.event.dependencyManifestHashes;\n const chain: VerifiedContainerAccessManifest[] = [];\n const seen = new Set<string>();\n let containerId = input.parentContainerId;\n while (containerId !== null) {\n if (seen.has(containerId)) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `${input.label} cited ancestors form a cycle at ${containerId}`,\n );\n }\n seen.add(containerId);\n const ancestor = await resolveCitedManifest(\n input,\n citedManifestHashForContainer(input, cited, containerId),\n containerId,\n );\n chain.unshift(ancestor);\n containerId = ancestor.state.parentContainerId;\n }\n return chain;\n}\n\n/** What the lineage rules read: the served and the verified bundles. */\nexport type CitedLineageInput = Pick<\n CitedAncestorResolutionInput,\n \"bundlesByHash\" | \"label\" | \"verifiedByHash\"\n>;\n\n/**\n * The verified head of `containerId` among the cited hashes, if any. Reads\n * verified manifests only: a cited hash the pass has not verified is not a\n * head to reason about, and every caller runs after the cited ancestor path\n * resolved and verified the chain. An event cites one head per container,\n * so a second verified one is a served citation set that was tampered with,\n * not a choice to make.\n */\nexport function verifiedCitedHead(input: {\n readonly cited: readonly string[];\n readonly containerId: string;\n readonly label: string;\n readonly verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n}): VerifiedContainerAccessManifest | undefined {\n let found: VerifiedContainerAccessManifest | undefined;\n for (const manifestHash of input.cited) {\n const verified = input.verifiedByHash.get(manifestHash);\n if (verified?.state.containerId !== input.containerId) continue;\n if (found && found.manifestHash !== verified.manifestHash) {\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n `${input.label} cites more than one head of container ${input.containerId}`,\n );\n }\n found = verified;\n }\n return found;\n}\n\n/**\n * Whether `head` is `floor` or descends from it through verified\n * predecessors. Epochs alone would let a same-epoch fork signed under an\n * older head pass; lineage cannot be forged without the chain. Every\n * predecessor of a verified manifest was verified with it, so a hop that is\n * not in the verified set means the chain was not served.\n */\nfunction descendsFrom(\n verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>,\n head: VerifiedContainerAccessManifest,\n floor: VerifiedContainerAccessManifest,\n): boolean {\n let current: VerifiedContainerAccessManifest | undefined = head;\n while (current && current.state.epoch >= floor.state.epoch) {\n if (current.manifestHash === floor.manifestHash) return true;\n const previousHash: string | null = current.state.previousManifestHash;\n current =\n previousHash === null ? undefined : verifiedByHash.get(previousHash);\n }\n return false;\n}\n\n/** The cited head must be the established head or descend from it. */\nfunction assertCitedHeadDescendsFrom(\n input: CitedLineageInput,\n cited: VerifiedContainerAccessManifest,\n floor: VerifiedContainerAccessManifest,\n): void {\n if (descendsFrom(input.verifiedByHash, cited, floor)) return;\n throw new KeyingVerificationError(\n \"rollback\",\n `${input.label} cites a head of container ${cited.state.containerId} that does not descend from the head an earlier signed statement already proved current`,\n );\n}\n\n/**\n * A head must not cite a head of any ancestor that does not descend from the\n * head an earlier signed statement already established: the manifest before\n * it cited that ancestor, the previous manifest's own pin when this is its\n * parent, or a cited child of that ancestor was created or moved under it and\n * cited it. Ancestors no statement establishes are skipped.\n */\nexport function assertCitedAncestorsDoNotRegress(\n input: CitedLineageInput & {\n readonly citedAncestors: readonly VerifiedContainerAccessManifest[];\n readonly previousManifest: VerifiedContainerAccessManifest | null;\n },\n): void {\n const previous = input.previousManifest;\n const previousCited = previous?.event.event.dependencyManifestHashes ?? [];\n input.citedAncestors.forEach((ancestor, index) => {\n const containerId = ancestor.state.containerId;\n const citedChild = input.citedAncestors[index + 1] ?? previous;\n const floors = [\n verifiedCitedHead({\n cited: previousCited,\n containerId,\n label: input.label,\n verifiedByHash: input.verifiedByHash,\n }),\n ...(citedChild\n ? [\n input.verifiedByHash.get(citedChild.state.parentManifestHash ?? \"\"),\n verifiedCitedHead({\n cited: citedChild.event.event.dependencyManifestHashes,\n containerId,\n label: input.label,\n verifiedByHash: input.verifiedByHash,\n }),\n ]\n : []),\n ];\n for (const floor of floors) {\n if (floor && floor.state.containerId === containerId) {\n assertCitedHeadDescendsFrom(input, ancestor, floor);\n }\n }\n });\n}\n\n/**\n * Every served current ancestor head must be, or descend through verified\n * predecessors from, the head of that container the head's signed event\n * cites. A served head older than the cited one, or a same-epoch fork of it,\n * is a rollback the signature proves: the cited head exists. A served head\n * newer than the cited one is the ordinary lag of a descendant behind its\n * ancestors, and an ancestor the head does not cite at all joined the path\n * when an ancestor between them moved; neither is refused.\n */\nexport function assertServedAncestorsDescendFromCitations(input: {\n readonly head: VerifiedContainerAccessManifest;\n readonly label: string;\n readonly servedAncestors: readonly VerifiedContainerAccessManifest[];\n readonly verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n}): void {\n const citations = input.head.event.event.dependencyManifestHashes;\n for (const served of input.servedAncestors) {\n const containerId = served.state.containerId;\n const cited = verifiedCitedHead({\n cited: citations,\n containerId,\n label: input.label,\n verifiedByHash: input.verifiedByHash,\n });\n if (!cited || descendsFrom(input.verifiedByHash, served, cited)) continue;\n throw new KeyingVerificationError(\n \"rollback\",\n `${input.label} cites a head of ancestor container ${containerId} that the served current head does not descend from`,\n );\n }\n}\n"]}
|