@tearleads/client-sdk 0.1.240 → 0.1.241

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.
@@ -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;AAE3B,OAAO,EAAE,0BAA0B,EAAE,MAAM,uCAAuC,CAAC;AACnF,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAGjD,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,CA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AAE,CACZ,SAAS,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 { DocumentContentKeyBundleResponse } from \"@tearleads/validators/response\";\nimport { resolveEventContainerPaths } from \"../../../keyingProjectionVerification\";\nimport { sortDocumentTargets } from \"../readers\";\nimport type { DocumentSyncPlan } from \"./documentSyncTypes\";\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"]}
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,MA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SAAS,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.authorizationTargets,
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,MAAM,OAAO,yCAA0C,SAAQ,KAAK;IAClE,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,2CA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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.js","sourceRoot":"","sources":["syncResponses.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,+BAA+B,EAC/B,mCAAmC,EACnC,0CAA0C,EAC1C,wCAAwC,EACxC,iBAA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AE,EAAE,CAC9B,2CAA2C,CAAC;QAC1C,wBAAwB;QACxB,IAAI;QACJ,sBAAsB,EAAE,OAAO,CAAC,sBAAsB;QACtD,MAAM;KACP,CAAC,CACH,CACF,CAAC;IAEF,OAAO,gCAAgC,CAAC;QACtC,gBAAgB,EAAE,IAAI,CAAC,sBAAsB;QAC7C,UAAU,EAAE,IAAI,CAAC,UAAU;QAC3B,kBAAkB,EAAE,IAAI,CAAC,kBAAkB;QAC3C,sBAAsB,EAAE,IAAI,CAAC,gBAAgB;KAC9C,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,sCAAsC,CAC1D,IAAsB,EACtB,QAA8B,EAC9B,OAEC;IAED,IAAI,CAAC;QACH,OAAO,MAAM,8CAA8C,CACzD,IAAI,EACJ,QAAQ,EACR,OAAO,CACR,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,yCAAyC;YAAE,MAAM,KAAK,CAAC;QAC5E,mCAAmC,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 {\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"]}
@@ -2789,12 +2789,6 @@ export declare class ApiClient extends ApiClientAreas {
2789
2789
  };
2790
2790
  updates: {
2791
2791
  accessEpoch: number;
2792
- authorizationTargets: {
2793
- containerId: string;
2794
- containerKeyEpoch: number;
2795
- containerKeyEpochId: string;
2796
- containerManifestHash: string;
2797
- }[];
2798
2792
  authorFingerprint: string;
2799
2793
  createdAt: string;
2800
2794
  documentId: string;
@@ -2804,6 +2798,12 @@ export declare class ApiClient extends ApiClientAreas {
2804
2798
  partialStartVersionVector: string;
2805
2799
  plaintextHash: string;
2806
2800
  writeHeader: Record<string, unknown>;
2801
+ authorizationTargets?: {
2802
+ containerId: string;
2803
+ containerKeyEpoch: number;
2804
+ containerKeyEpochId: string;
2805
+ containerManifestHash: string;
2806
+ }[] | undefined;
2807
2807
  checkpointKind?: "rotate_baseline" | undefined;
2808
2808
  checkpointPayloadKind?: "full_history_snapshot" | undefined;
2809
2809
  sourceVersionVector?: string | undefined;
@@ -2934,7 +2934,7 @@ export declare class ApiClient extends ApiClientAreas {
2934
2934
  linkedContainerKeyEpochIds: string[];
2935
2935
  linkedContainerManifestHashes: string[];
2936
2936
  organizationId: string;
2937
- targets: Record<string, unknown>[];
2937
+ targets?: Record<string, unknown>[] | undefined;
2938
2938
  };
2939
2939
  writeHeader: Record<string, unknown>;
2940
2940
  }[] | null>;
@@ -637,7 +637,7 @@ export declare class ApiClientContext {
637
637
  linkedContainerKeyEpochIds: string[];
638
638
  linkedContainerManifestHashes: string[];
639
639
  organizationId: string;
640
- targets: Record<string, unknown>[];
640
+ targets?: Record<string, unknown>[] | undefined;
641
641
  };
642
642
  writeHeader: Record<string, unknown>;
643
643
  }[] | null>>;
@@ -144,7 +144,7 @@ export declare class BlobArea {
144
144
  linkedContainerKeyEpochIds: string[];
145
145
  linkedContainerManifestHashes: string[];
146
146
  organizationId: string;
147
- targets: Record<string, unknown>[];
147
+ targets?: Record<string, unknown>[] | undefined;
148
148
  };
149
149
  writeHeader: Record<string, unknown>;
150
150
  }[] | null>;
@@ -315,12 +315,6 @@ export declare class DocumentArea {
315
315
  };
316
316
  updates: {
317
317
  accessEpoch: number;
318
- authorizationTargets: {
319
- containerId: string;
320
- containerKeyEpoch: number;
321
- containerKeyEpochId: string;
322
- containerManifestHash: string;
323
- }[];
324
318
  authorFingerprint: string;
325
319
  createdAt: string;
326
320
  documentId: string;
@@ -330,6 +324,12 @@ export declare class DocumentArea {
330
324
  partialStartVersionVector: string;
331
325
  plaintextHash: string;
332
326
  writeHeader: Record<string, unknown>;
327
+ authorizationTargets?: {
328
+ containerId: string;
329
+ containerKeyEpoch: number;
330
+ containerKeyEpochId: string;
331
+ containerManifestHash: string;
332
+ }[] | undefined;
333
333
  checkpointKind?: "rotate_baseline" | undefined;
334
334
  checkpointPayloadKind?: "full_history_snapshot" | undefined;
335
335
  sourceVersionVector?: string | undefined;
@@ -1401,7 +1401,7 @@ export declare const listDocumentAttachmentsOperation: Omit<{
1401
1401
  linkedContainerKeyEpochIds: string[];
1402
1402
  linkedContainerManifestHashes: string[];
1403
1403
  organizationId: string;
1404
- targets: Record<string, unknown>[];
1404
+ targets?: Record<string, unknown>[] | undefined;
1405
1405
  };
1406
1406
  writeHeader: Record<string, unknown>;
1407
1407
  }[], {
@@ -1450,7 +1450,7 @@ export declare const listDocumentAttachmentsOperation: Omit<{
1450
1450
  linkedContainerKeyEpochIds: string[];
1451
1451
  linkedContainerManifestHashes: string[];
1452
1452
  organizationId: string;
1453
- targets: Record<string, unknown>[];
1453
+ targets?: Record<string, unknown>[] | undefined;
1454
1454
  };
1455
1455
  writeHeader: Record<string, unknown>;
1456
1456
  }[]>;
@@ -464,12 +464,6 @@ export declare const documentSyncOperation: Omit<{
464
464
  };
465
465
  updates: {
466
466
  accessEpoch: number;
467
- authorizationTargets: {
468
- containerId: string;
469
- containerKeyEpoch: number;
470
- containerKeyEpochId: string;
471
- containerManifestHash: string;
472
- }[];
473
467
  authorFingerprint: string;
474
468
  createdAt: string;
475
469
  documentId: string;
@@ -479,6 +473,12 @@ export declare const documentSyncOperation: Omit<{
479
473
  partialStartVersionVector: string;
480
474
  plaintextHash: string;
481
475
  writeHeader: Record<string, unknown>;
476
+ authorizationTargets?: {
477
+ containerId: string;
478
+ containerKeyEpoch: number;
479
+ containerKeyEpochId: string;
480
+ containerManifestHash: string;
481
+ }[] | undefined;
482
482
  checkpointKind?: "rotate_baseline" | undefined;
483
483
  checkpointPayloadKind?: "full_history_snapshot" | undefined;
484
484
  sourceVersionVector?: string | undefined;
@@ -508,12 +508,6 @@ export declare const documentSyncOperation: Omit<{
508
508
  };
509
509
  updates: {
510
510
  accessEpoch: number;
511
- authorizationTargets: {
512
- containerId: string;
513
- containerKeyEpoch: number;
514
- containerKeyEpochId: string;
515
- containerManifestHash: string;
516
- }[];
517
511
  authorFingerprint: string;
518
512
  createdAt: string;
519
513
  documentId: string;
@@ -523,6 +517,12 @@ export declare const documentSyncOperation: Omit<{
523
517
  partialStartVersionVector: string;
524
518
  plaintextHash: string;
525
519
  writeHeader: Record<string, unknown>;
520
+ authorizationTargets?: {
521
+ containerId: string;
522
+ containerKeyEpoch: number;
523
+ containerKeyEpochId: string;
524
+ containerManifestHash: string;
525
+ }[] | undefined;
526
526
  checkpointKind?: "rotate_baseline" | undefined;
527
527
  checkpointPayloadKind?: "full_history_snapshot" | undefined;
528
528
  sourceVersionVector?: string | undefined;
@@ -552,12 +552,6 @@ export declare const documentSyncOperation: Omit<{
552
552
  };
553
553
  updates: {
554
554
  accessEpoch: number;
555
- authorizationTargets: {
556
- containerId: string;
557
- containerKeyEpoch: number;
558
- containerKeyEpochId: string;
559
- containerManifestHash: string;
560
- }[];
561
555
  authorFingerprint: string;
562
556
  createdAt: string;
563
557
  documentId: string;
@@ -567,6 +561,12 @@ export declare const documentSyncOperation: Omit<{
567
561
  partialStartVersionVector: string;
568
562
  plaintextHash: string;
569
563
  writeHeader: Record<string, unknown>;
564
+ authorizationTargets?: {
565
+ containerId: string;
566
+ containerKeyEpoch: number;
567
+ containerKeyEpochId: string;
568
+ containerManifestHash: string;
569
+ }[] | undefined;
570
570
  checkpointKind?: "rotate_baseline" | undefined;
571
571
  checkpointPayloadKind?: "full_history_snapshot" | undefined;
572
572
  sourceVersionVector?: string | undefined;
@@ -596,12 +596,6 @@ export declare const documentSyncOperation: Omit<{
596
596
  };
597
597
  updates: {
598
598
  accessEpoch: number;
599
- authorizationTargets: {
600
- containerId: string;
601
- containerKeyEpoch: number;
602
- containerKeyEpochId: string;
603
- containerManifestHash: string;
604
- }[];
605
599
  authorFingerprint: string;
606
600
  createdAt: string;
607
601
  documentId: string;
@@ -611,6 +605,12 @@ export declare const documentSyncOperation: Omit<{
611
605
  partialStartVersionVector: string;
612
606
  plaintextHash: string;
613
607
  writeHeader: Record<string, unknown>;
608
+ authorizationTargets?: {
609
+ containerId: string;
610
+ containerKeyEpoch: number;
611
+ containerKeyEpochId: string;
612
+ containerManifestHash: string;
613
+ }[] | undefined;
614
614
  checkpointKind?: "rotate_baseline" | undefined;
615
615
  checkpointPayloadKind?: "full_history_snapshot" | undefined;
616
616
  sourceVersionVector?: string | undefined;
@@ -387,7 +387,7 @@ export declare const BlobAttachmentSummarySchema: z.ZodType<{
387
387
  linkedContainerKeyEpochIds: string[];
388
388
  linkedContainerManifestHashes: string[];
389
389
  organizationId: string;
390
- targets: Record<string, unknown>[];
390
+ targets?: Record<string, unknown>[] | undefined;
391
391
  };
392
392
  writeHeader: Record<string, unknown>;
393
393
  }, {
@@ -436,7 +436,7 @@ export declare const BlobAttachmentSummarySchema: z.ZodType<{
436
436
  linkedContainerKeyEpochIds: string[];
437
437
  linkedContainerManifestHashes: string[];
438
438
  organizationId: string;
439
- targets: Record<string, unknown>[];
439
+ targets?: Record<string, unknown>[] | undefined;
440
440
  };
441
441
  writeHeader: Record<string, unknown>;
442
442
  }, z.core.$ZodTypeInternals<{
@@ -485,7 +485,7 @@ export declare const BlobAttachmentSummarySchema: z.ZodType<{
485
485
  linkedContainerKeyEpochIds: string[];
486
486
  linkedContainerManifestHashes: string[];
487
487
  organizationId: string;
488
- targets: Record<string, unknown>[];
488
+ targets?: Record<string, unknown>[] | undefined;
489
489
  };
490
490
  writeHeader: Record<string, unknown>;
491
491
  }, {
@@ -534,7 +534,7 @@ export declare const BlobAttachmentSummarySchema: z.ZodType<{
534
534
  linkedContainerKeyEpochIds: string[];
535
535
  linkedContainerManifestHashes: string[];
536
536
  organizationId: string;
537
- targets: Record<string, unknown>[];
537
+ targets?: Record<string, unknown>[] | undefined;
538
538
  };
539
539
  writeHeader: Record<string, unknown>;
540
540
  }>>;
@@ -585,7 +585,7 @@ export declare const ListDocumentAttachmentsResponseSchema: z.ZodCustom<{
585
585
  linkedContainerKeyEpochIds: string[];
586
586
  linkedContainerManifestHashes: string[];
587
587
  organizationId: string;
588
- targets: Record<string, unknown>[];
588
+ targets?: Record<string, unknown>[] | undefined;
589
589
  };
590
590
  writeHeader: Record<string, unknown>;
591
591
  }[], {
@@ -634,7 +634,7 @@ export declare const ListDocumentAttachmentsResponseSchema: z.ZodCustom<{
634
634
  linkedContainerKeyEpochIds: string[];
635
635
  linkedContainerManifestHashes: string[];
636
636
  organizationId: string;
637
- targets: Record<string, unknown>[];
637
+ targets?: Record<string, unknown>[] | undefined;
638
638
  };
639
639
  writeHeader: Record<string, unknown>;
640
640
  }[]>;
@@ -50,7 +50,7 @@ export const BlobContentKeyBundleResponseSchema = loosePlainObject({
50
50
  targetHash: z.string(),
51
51
  targets: arraySchema(BlobContentKeyTargetEnvelopeResponseSchema),
52
52
  });
53
- export const BlobKekTargetsResponseSchema = loosePlainObject({
53
+ const blobKekTargetsShape = {
54
54
  activeBindingIds: arraySchema(z.string()),
55
55
  blobAccessManifestHash: z.string(),
56
56
  blobId: z.string(),
@@ -60,6 +60,16 @@ export const BlobKekTargetsResponseSchema = loosePlainObject({
60
60
  linkedContainerManifestHashes: arraySchema(z.string()),
61
61
  organizationId: z.string(),
62
62
  targets: arraySchema(plainObjectSchema),
63
+ };
64
+ export const BlobKekTargetsResponseSchema = loosePlainObject(blobKekTargetsShape);
65
+ /**
66
+ * The target set a blob's write was authorized against. `targets` is omitted
67
+ * when `blobKeyTargetHash` equals the listing's current `blobKekTargets`
68
+ * hash: the reader refills it from that set and re-hashes it.
69
+ */
70
+ const BlobWriteAuthorizationResponseSchema = loosePlainObject({
71
+ ...blobKekTargetsShape,
72
+ targets: arraySchema(plainObjectSchema).optional(),
63
73
  });
64
74
  export const BlobAttachmentSummarySchema = loosePlainObject({
65
75
  bindingEvent: AccessEventBundleWireResponseSchema,
@@ -70,7 +80,7 @@ export const BlobAttachmentSummarySchema = loosePlainObject({
70
80
  documentManifestHash: z.string(),
71
81
  previousBindingId: z.string().nullable(),
72
82
  slotId: z.string(),
73
- writeAuthorization: BlobKekTargetsResponseSchema,
83
+ writeAuthorization: BlobWriteAuthorizationResponseSchema,
74
84
  writeHeader: plainObjectSchema,
75
85
  });
76
86
  export const ListDocumentAttachmentsResponseSchema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Ac;IAEd,OAAO,wCAAwC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC;AAC3E,CAAC;AAED,MAAM,UAAU,kCAAkC,CAChD,KAAc;IAEd,OAAO,sCAAsC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC;AACzE,CAAC;AAED,MAAM,UAAU,iCAAiC,CAC/C,KAAc;IAEd,OAAO,qCAAqC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC;AACxE,CAAC;AAED,MAAM,UAAU,iCAAiC,CAC/C,KAAc;IAEd,OAAO,qCAAqC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC;AACxE,CAAC;AAED,MAAM,UAAU,4BAA4B,CAC1C,KAAc;IAEd,OAAO,gCAAgC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC;AACnE,CAAC;AAED,MAAM,UAAU,8BAA8B,CAC5C,KAAc;IAEd,OAAO,kCAAkC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC;AACrE,CAAC","sourcesContent":["import { z } from \"zod\";\nimport {\n arraySchema,\n loosePlainObject,\n nonEmptyStringSchema,\n plainObjectSchema,\n positiveIntegerSchema,\n} from \"../schema\";\nimport { AccessEventBundleWireResponseSchema } from \"../util\";\nimport { MultipartBlobPartUploadSchema } from \"../util/blobTransferSchemas\";\nimport { DocumentCreateSeedResponseSchema } from \"./documentMutation\";\n\nexport const MultipartBlobStagePartSchema = loosePlainObject({\n byteLength: positiveIntegerSchema,\n etag: nonEmptyStringSchema,\n partNumber: positiveIntegerSchema,\n});\n\nexport type MultipartBlobStagePart = z.infer<\n typeof MultipartBlobStagePartSchema\n>;\n\nexport const InitiateMultipartBlobStageResponseSchema = loosePlainObject({\n organizationId: nonEmptyStringSchema,\n byteLength: positiveIntegerSchema,\n expiresAt: z.string(),\n // One upload source per requested first part, in request order.\n partUploads: arraySchema(MultipartBlobPartUploadSchema),\n sha256: nonEmptyStringSchema,\n stageId: z.string(),\n uploadedParts: arraySchema(MultipartBlobStagePartSchema),\n uploadId: z.string(),\n});\n\nexport type InitiateMultipartBlobStageResponse = z.infer<\n typeof InitiateMultipartBlobStageResponseSchema\n>;\n\nexport const MultipartBlobStageStatusResponseSchema = loosePlainObject({\n organizationId: nonEmptyStringSchema,\n byteLength: positiveIntegerSchema,\n completed: z.boolean(),\n expiresAt: z.string(),\n sha256: nonEmptyStringSchema,\n stageId: z.string(),\n uploadedParts: arraySchema(MultipartBlobStagePartSchema),\n uploadId: z.string(),\n});\n\nexport type MultipartBlobStageStatusResponse = z.infer<\n typeof MultipartBlobStageStatusResponseSchema\n>;\n\nexport const UploadMultipartBlobPartResponseSchema = loosePlainObject({\n part: MultipartBlobStagePartSchema,\n stageId: z.string(),\n uploadId: z.string(),\n});\n\nexport type UploadMultipartBlobPartResponse = z.infer<\n typeof UploadMultipartBlobPartResponseSchema\n>;\n\nexport const BlobContentKeyTargetEnvelopeResponseSchema = loosePlainObject({\n bindingId: z.string(),\n containerId: z.string(),\n containerKeyEpoch: positiveIntegerSchema,\n containerKeyEpochId: z.string(),\n containerManifestHash: z.string(),\n documentId: z.string(),\n wrappedKey: z.string(),\n wrappingMetadata: plainObjectSchema,\n});\n\nexport type BlobContentKeyTargetEnvelopeResponse = z.infer<\n typeof BlobContentKeyTargetEnvelopeResponseSchema\n>;\n\nexport const BlobContentKeyBundleResponseSchema = loosePlainObject({\n blobId: z.string(),\n contentKeyEpoch: positiveIntegerSchema,\n targetHash: z.string(),\n targets: arraySchema(BlobContentKeyTargetEnvelopeResponseSchema),\n});\n\nexport type BlobContentKeyBundleResponse = z.infer<\n typeof BlobContentKeyBundleResponseSchema\n>;\n\nexport const BlobKekTargetsResponseSchema = loosePlainObject({\n activeBindingIds: arraySchema(z.string()),\n blobAccessManifestHash: z.string(),\n blobId: z.string(),\n blobKeyTargetHash: z.string(),\n documentManifestHashes: arraySchema(z.string()),\n linkedContainerKeyEpochIds: arraySchema(z.string()),\n linkedContainerManifestHashes: arraySchema(z.string()),\n organizationId: z.string(),\n targets: arraySchema(plainObjectSchema),\n});\n\nexport type BlobKekTargetsResponse = z.infer<\n typeof BlobKekTargetsResponseSchema\n>;\n\nexport const BlobAttachmentSummarySchema = loosePlainObject({\n bindingEvent: AccessEventBundleWireResponseSchema,\n bindingId: z.string(),\n blobId: z.string(),\n blobKekTargets: BlobKekTargetsResponseSchema,\n contentKeyBundle: BlobContentKeyBundleResponseSchema,\n documentManifestHash: z.string(),\n previousBindingId: z.string().nullable(),\n slotId: z.string(),\n writeAuthorization: BlobKekTargetsResponseSchema,\n writeHeader: plainObjectSchema,\n});\n\nexport type BlobAttachmentSummary = z.infer<typeof BlobAttachmentSummarySchema>;\n\nexport const ListDocumentAttachmentsResponseSchema = arraySchema(\n BlobAttachmentSummarySchema,\n);\n\nexport type ListDocumentAttachmentsResponse = z.infer<\n typeof ListDocumentAttachmentsResponseSchema\n>;\n\n/**\n * A bind acknowledges by hash: the signed binding event's hash, the stored\n * content-key epoch, the verified write header's hash, and the hashes of the\n * server-resolved KEK target set and blob access manifest. It never echoes the\n * signed event, the content-key wraps, the write header, the KEK targets, or\n * the write authorization (which a staged upload's bind stores as exactly the\n * targets it wrapped to); the client compares each with what it signed.\n */\nexport const BlobAttachmentBindResponseSchema = loosePlainObject({\n bindingId: z.string(),\n blobAccessManifestHash: nonEmptyStringSchema,\n blobId: z.string(),\n blobKeyTargetHash: nonEmptyStringSchema,\n contentKeyEpoch: positiveIntegerSchema,\n documentId: z.string(),\n documentManifestHash: z.string(),\n eventHash: nonEmptyStringSchema,\n previousBindingId: z.string().nullable(),\n slotId: z.string(),\n writeHeaderHash: z.string(),\n /** Present exactly when the request carried `documentSync`. */\n documentSync: DocumentCreateSeedResponseSchema.optional(),\n});\n\nexport type BlobAttachmentBindResponse = z.infer<\n typeof BlobAttachmentBindResponseSchema\n>;\n\nfunction sortedUniqueStrings(values: readonly string[]): string[] {\n return [...new Set(values)].sort((left, right) =>\n left < right ? -1 : left > right ? 1 : 0,\n );\n}\n\n/**\n * The listing entry a staged upload's bind committed, rebuilt from the\n * request it acknowledged: the bind stores exactly the signed event,\n * content-key bundle, and write header the request carried, and a staged\n * blob is new, so this binding is its only one and its KEK targets and write\n * authorization are exactly the targets the bundle wraps to. Callers must\n * first have matched the acknowledgement's hashes against that request.\n */\nexport function blobAttachmentSummaryFromStagedBind(\n request: {\n readonly body: unknown;\n readonly contentKeyBundle: {\n readonly targetHash: string;\n readonly targets: readonly BlobContentKeyTargetEnvelopeResponse[];\n };\n readonly event: Record<string, unknown>;\n readonly stagedBlob: { readonly writeHeader: Record<string, unknown> };\n },\n response: BlobAttachmentBindResponse,\n): BlobAttachmentSummary {\n const { organizationId } = request.event;\n if (typeof organizationId !== \"string\") {\n throw new Error(\"Attachment bind event organization id is invalid\");\n }\n const targets = request.contentKeyBundle.targets.map((target) => ({\n bindingId: target.bindingId,\n containerId: target.containerId,\n containerKeyEpoch: target.containerKeyEpoch,\n containerKeyEpochId: target.containerKeyEpochId,\n containerManifestHash: target.containerManifestHash,\n documentId: target.documentId,\n }));\n const blobKekTargets: BlobKekTargetsResponse = {\n activeBindingIds: [response.bindingId],\n blobAccessManifestHash: response.blobAccessManifestHash,\n blobId: response.blobId,\n blobKeyTargetHash: response.blobKeyTargetHash,\n documentManifestHashes: [response.documentManifestHash],\n linkedContainerKeyEpochIds: sortedUniqueStrings(\n targets.map((target) => target.containerKeyEpochId),\n ),\n linkedContainerManifestHashes: sortedUniqueStrings(\n targets.map((target) => target.containerManifestHash),\n ),\n organizationId,\n targets,\n };\n return {\n bindingEvent: {\n body: request.body,\n event: request.event,\n eventHash: response.eventHash,\n },\n bindingId: response.bindingId,\n blobId: response.blobId,\n blobKekTargets,\n contentKeyBundle: {\n blobId: response.blobId,\n contentKeyEpoch: response.contentKeyEpoch,\n targetHash: request.contentKeyBundle.targetHash,\n targets: [...request.contentKeyBundle.targets],\n },\n documentManifestHash: response.documentManifestHash,\n previousBindingId: response.previousBindingId,\n slotId: response.slotId,\n writeAuthorization: blobKekTargets,\n writeHeader: request.stagedBlob.writeHeader,\n };\n}\n\nexport const BlobAttachmentDetachResponseSchema = loosePlainObject({\n bindingId: z.string(),\n blobId: z.string(),\n documentId: z.string(),\n slotId: z.string(),\n});\n\nexport type BlobAttachmentDetachResponse = z.infer<\n typeof BlobAttachmentDetachResponseSchema\n>;\n\nexport function isInitiateMultipartBlobStageResponse(\n value: unknown,\n): value is InitiateMultipartBlobStageResponse {\n return InitiateMultipartBlobStageResponseSchema.safeParse(value).success;\n}\n\nexport function isMultipartBlobStageStatusResponse(\n value: unknown,\n): value is MultipartBlobStageStatusResponse {\n return MultipartBlobStageStatusResponseSchema.safeParse(value).success;\n}\n\nexport function isUploadMultipartBlobPartResponse(\n value: unknown,\n): value is UploadMultipartBlobPartResponse {\n return UploadMultipartBlobPartResponseSchema.safeParse(value).success;\n}\n\nexport function isListDocumentAttachmentsResponse(\n value: unknown,\n): value is ListDocumentAttachmentsResponse {\n return ListDocumentAttachmentsResponseSchema.safeParse(value).success;\n}\n\nexport function isBlobAttachmentBindResponse(\n value: unknown,\n): value is BlobAttachmentBindResponse {\n return BlobAttachmentBindResponseSchema.safeParse(value).success;\n}\n\nexport function isBlobAttachmentDetachResponse(\n value: unknown,\n): value is BlobAttachmentDetachResponse {\n return BlobAttachmentDetachResponseSchema.safeParse(value).success;\n}\n"]}
1
+ {"version":3,"file":"blob.js","sourceRoot":"","sources":["blob.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EACL,WAAW,EACX,gBAAgB,EAChB,oBAAoB,EACpB,iBAAiB,EACjB,qBAAqB,GACtB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,mCAAmC,EAAE,MAAM,SAAS,CAAC;AAC9D,OAAO,EAAE,6BAA6B,EAAE,MAAM,6BAA6B,CAAC;AAC5E,OAAO,EAAE,gCAAgC,EAAE,M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AACzE,CAAC;AAED,MAAM,UAAU,iCAAiC,CAC/C,KAAc;IAEd,OAAO,qCAAqC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC;AACxE,CAAC;AAED,MAAM,UAAU,iCAAiC,CAC/C,KAAc;IAEd,OAAO,qCAAqC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC;AACxE,CAAC;AAED,MAAM,UAAU,4BAA4B,CAC1C,KAAc;IAEd,OAAO,gCAAgC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC;AACnE,CAAC;AAED,MAAM,UAAU,8BAA8B,CAC5C,KAAc;IAEd,OAAO,kCAAkC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC;AACrE,CAAC","sourcesContent":["import { z } from \"zod\";\nimport {\n arraySchema,\n loosePlainObject,\n nonEmptyStringSchema,\n plainObjectSchema,\n positiveIntegerSchema,\n} from \"../schema\";\nimport { AccessEventBundleWireResponseSchema } from \"../util\";\nimport { MultipartBlobPartUploadSchema } from \"../util/blobTransferSchemas\";\nimport { DocumentCreateSeedResponseSchema } from \"./documentMutation\";\n\nexport const MultipartBlobStagePartSchema = loosePlainObject({\n byteLength: positiveIntegerSchema,\n etag: nonEmptyStringSchema,\n partNumber: positiveIntegerSchema,\n});\n\nexport type MultipartBlobStagePart = z.infer<\n typeof MultipartBlobStagePartSchema\n>;\n\nexport const InitiateMultipartBlobStageResponseSchema = loosePlainObject({\n organizationId: nonEmptyStringSchema,\n byteLength: positiveIntegerSchema,\n expiresAt: z.string(),\n // One upload source per requested first part, in request order.\n partUploads: arraySchema(MultipartBlobPartUploadSchema),\n sha256: nonEmptyStringSchema,\n stageId: z.string(),\n uploadedParts: arraySchema(MultipartBlobStagePartSchema),\n uploadId: z.string(),\n});\n\nexport type InitiateMultipartBlobStageResponse = z.infer<\n typeof InitiateMultipartBlobStageResponseSchema\n>;\n\nexport const MultipartBlobStageStatusResponseSchema = loosePlainObject({\n organizationId: nonEmptyStringSchema,\n byteLength: positiveIntegerSchema,\n completed: z.boolean(),\n expiresAt: z.string(),\n sha256: nonEmptyStringSchema,\n stageId: z.string(),\n uploadedParts: arraySchema(MultipartBlobStagePartSchema),\n uploadId: z.string(),\n});\n\nexport type MultipartBlobStageStatusResponse = z.infer<\n typeof MultipartBlobStageStatusResponseSchema\n>;\n\nexport const UploadMultipartBlobPartResponseSchema = loosePlainObject({\n part: MultipartBlobStagePartSchema,\n stageId: z.string(),\n uploadId: z.string(),\n});\n\nexport type UploadMultipartBlobPartResponse = z.infer<\n typeof UploadMultipartBlobPartResponseSchema\n>;\n\nexport const BlobContentKeyTargetEnvelopeResponseSchema = loosePlainObject({\n bindingId: z.string(),\n containerId: z.string(),\n containerKeyEpoch: positiveIntegerSchema,\n containerKeyEpochId: z.string(),\n containerManifestHash: z.string(),\n documentId: z.string(),\n wrappedKey: z.string(),\n wrappingMetadata: plainObjectSchema,\n});\n\nexport type BlobContentKeyTargetEnvelopeResponse = z.infer<\n typeof BlobContentKeyTargetEnvelopeResponseSchema\n>;\n\nexport const BlobContentKeyBundleResponseSchema = loosePlainObject({\n blobId: z.string(),\n contentKeyEpoch: positiveIntegerSchema,\n targetHash: z.string(),\n targets: arraySchema(BlobContentKeyTargetEnvelopeResponseSchema),\n});\n\nexport type BlobContentKeyBundleResponse = z.infer<\n typeof BlobContentKeyBundleResponseSchema\n>;\n\nconst blobKekTargetsShape = {\n activeBindingIds: arraySchema(z.string()),\n blobAccessManifestHash: z.string(),\n blobId: z.string(),\n blobKeyTargetHash: z.string(),\n documentManifestHashes: arraySchema(z.string()),\n linkedContainerKeyEpochIds: arraySchema(z.string()),\n linkedContainerManifestHashes: arraySchema(z.string()),\n organizationId: z.string(),\n targets: arraySchema(plainObjectSchema),\n};\n\nexport const BlobKekTargetsResponseSchema =\n loosePlainObject(blobKekTargetsShape);\n\nexport type BlobKekTargetsResponse = z.infer<\n typeof BlobKekTargetsResponseSchema\n>;\n\n/**\n * The target set a blob's write was authorized against. `targets` is omitted\n * when `blobKeyTargetHash` equals the listing's current `blobKekTargets`\n * hash: the reader refills it from that set and re-hashes it.\n */\nconst BlobWriteAuthorizationResponseSchema = loosePlainObject({\n ...blobKekTargetsShape,\n targets: arraySchema(plainObjectSchema).optional(),\n});\n\nexport const BlobAttachmentSummarySchema = loosePlainObject({\n bindingEvent: AccessEventBundleWireResponseSchema,\n bindingId: z.string(),\n blobId: z.string(),\n blobKekTargets: BlobKekTargetsResponseSchema,\n contentKeyBundle: BlobContentKeyBundleResponseSchema,\n documentManifestHash: z.string(),\n previousBindingId: z.string().nullable(),\n slotId: z.string(),\n writeAuthorization: BlobWriteAuthorizationResponseSchema,\n writeHeader: plainObjectSchema,\n});\n\nexport type BlobAttachmentSummary = z.infer<typeof BlobAttachmentSummarySchema>;\n\nexport const ListDocumentAttachmentsResponseSchema = arraySchema(\n BlobAttachmentSummarySchema,\n);\n\nexport type ListDocumentAttachmentsResponse = z.infer<\n typeof ListDocumentAttachmentsResponseSchema\n>;\n\n/**\n * A bind acknowledges by hash: the signed binding event's hash, the stored\n * content-key epoch, the verified write header's hash, and the hashes of the\n * server-resolved KEK target set and blob access manifest. It never echoes the\n * signed event, the content-key wraps, the write header, the KEK targets, or\n * the write authorization (which a staged upload's bind stores as exactly the\n * targets it wrapped to); the client compares each with what it signed.\n */\nexport const BlobAttachmentBindResponseSchema = loosePlainObject({\n bindingId: z.string(),\n blobAccessManifestHash: nonEmptyStringSchema,\n blobId: z.string(),\n blobKeyTargetHash: nonEmptyStringSchema,\n contentKeyEpoch: positiveIntegerSchema,\n documentId: z.string(),\n documentManifestHash: z.string(),\n eventHash: nonEmptyStringSchema,\n previousBindingId: z.string().nullable(),\n slotId: z.string(),\n writeHeaderHash: z.string(),\n /** Present exactly when the request carried `documentSync`. */\n documentSync: DocumentCreateSeedResponseSchema.optional(),\n});\n\nexport type BlobAttachmentBindResponse = z.infer<\n typeof BlobAttachmentBindResponseSchema\n>;\n\nfunction sortedUniqueStrings(values: readonly string[]): string[] {\n return [...new Set(values)].sort((left, right) =>\n left < right ? -1 : left > right ? 1 : 0,\n );\n}\n\n/**\n * The listing entry a staged upload's bind committed, rebuilt from the\n * request it acknowledged: the bind stores exactly the signed event,\n * content-key bundle, and write header the request carried, and a staged\n * blob is new, so this binding is its only one and its KEK targets and write\n * authorization are exactly the targets the bundle wraps to. Callers must\n * first have matched the acknowledgement's hashes against that request.\n */\nexport function blobAttachmentSummaryFromStagedBind(\n request: {\n readonly body: unknown;\n readonly contentKeyBundle: {\n readonly targetHash: string;\n readonly targets: readonly BlobContentKeyTargetEnvelopeResponse[];\n };\n readonly event: Record<string, unknown>;\n readonly stagedBlob: { readonly writeHeader: Record<string, unknown> };\n },\n response: BlobAttachmentBindResponse,\n): BlobAttachmentSummary {\n const { organizationId } = request.event;\n if (typeof organizationId !== \"string\") {\n throw new Error(\"Attachment bind event organization id is invalid\");\n }\n const targets = request.contentKeyBundle.targets.map((target) => ({\n bindingId: target.bindingId,\n containerId: target.containerId,\n containerKeyEpoch: target.containerKeyEpoch,\n containerKeyEpochId: target.containerKeyEpochId,\n containerManifestHash: target.containerManifestHash,\n documentId: target.documentId,\n }));\n const blobKekTargets: BlobKekTargetsResponse = {\n activeBindingIds: [response.bindingId],\n blobAccessManifestHash: response.blobAccessManifestHash,\n blobId: response.blobId,\n blobKeyTargetHash: response.blobKeyTargetHash,\n documentManifestHashes: [response.documentManifestHash],\n linkedContainerKeyEpochIds: sortedUniqueStrings(\n targets.map((target) => target.containerKeyEpochId),\n ),\n linkedContainerManifestHashes: sortedUniqueStrings(\n targets.map((target) => target.containerManifestHash),\n ),\n organizationId,\n targets,\n };\n return {\n bindingEvent: {\n body: request.body,\n event: request.event,\n eventHash: response.eventHash,\n },\n bindingId: response.bindingId,\n blobId: response.blobId,\n blobKekTargets,\n contentKeyBundle: {\n blobId: response.blobId,\n contentKeyEpoch: response.contentKeyEpoch,\n targetHash: request.contentKeyBundle.targetHash,\n targets: [...request.contentKeyBundle.targets],\n },\n documentManifestHash: response.documentManifestHash,\n previousBindingId: response.previousBindingId,\n slotId: response.slotId,\n writeAuthorization: blobKekTargets,\n writeHeader: request.stagedBlob.writeHeader,\n };\n}\n\nexport const BlobAttachmentDetachResponseSchema = loosePlainObject({\n bindingId: z.string(),\n blobId: z.string(),\n documentId: z.string(),\n slotId: z.string(),\n});\n\nexport type BlobAttachmentDetachResponse = z.infer<\n typeof BlobAttachmentDetachResponseSchema\n>;\n\nexport function isInitiateMultipartBlobStageResponse(\n value: unknown,\n): value is InitiateMultipartBlobStageResponse {\n return InitiateMultipartBlobStageResponseSchema.safeParse(value).success;\n}\n\nexport function isMultipartBlobStageStatusResponse(\n value: unknown,\n): value is MultipartBlobStageStatusResponse {\n return MultipartBlobStageStatusResponseSchema.safeParse(value).success;\n}\n\nexport function isUploadMultipartBlobPartResponse(\n value: unknown,\n): value is UploadMultipartBlobPartResponse {\n return UploadMultipartBlobPartResponseSchema.safeParse(value).success;\n}\n\nexport function isListDocumentAttachmentsResponse(\n value: unknown,\n): value is ListDocumentAttachmentsResponse {\n return ListDocumentAttachmentsResponseSchema.safeParse(value).success;\n}\n\nexport function isBlobAttachmentBindResponse(\n value: unknown,\n): value is BlobAttachmentBindResponse {\n return BlobAttachmentBindResponseSchema.safeParse(value).success;\n}\n\nexport function isBlobAttachmentDetachResponse(\n value: unknown,\n): value is BlobAttachmentDetachResponse {\n return BlobAttachmentDetachResponseSchema.safeParse(value).success;\n}\n"]}
@@ -115,12 +115,6 @@ export declare const DocumentContentKeyBundleResponseSchema: z.ZodType<{
115
115
  export type DocumentContentKeyBundleResponse = z.infer<typeof DocumentContentKeyBundleResponseSchema>;
116
116
  export declare const DocumentSyncUpdateResponseSchema: z.ZodType<{
117
117
  accessEpoch: number;
118
- authorizationTargets: {
119
- containerId: string;
120
- containerKeyEpoch: number;
121
- containerKeyEpochId: string;
122
- containerManifestHash: string;
123
- }[];
124
118
  authorFingerprint: string;
125
119
  createdAt: string;
126
120
  documentId: string;
@@ -130,17 +124,17 @@ export declare const DocumentSyncUpdateResponseSchema: z.ZodType<{
130
124
  partialStartVersionVector: string;
131
125
  plaintextHash: string;
132
126
  writeHeader: Record<string, unknown>;
127
+ authorizationTargets?: {
128
+ containerId: string;
129
+ containerKeyEpoch: number;
130
+ containerKeyEpochId: string;
131
+ containerManifestHash: string;
132
+ }[] | undefined;
133
133
  checkpointKind?: "rotate_baseline" | undefined;
134
134
  checkpointPayloadKind?: "full_history_snapshot" | undefined;
135
135
  sourceVersionVector?: string | undefined;
136
136
  }, {
137
137
  accessEpoch: number;
138
- authorizationTargets: {
139
- containerId: string;
140
- containerKeyEpoch: number;
141
- containerKeyEpochId: string;
142
- containerManifestHash: string;
143
- }[];
144
138
  authorFingerprint: string;
145
139
  createdAt: string;
146
140
  documentId: string;
@@ -150,17 +144,17 @@ export declare const DocumentSyncUpdateResponseSchema: z.ZodType<{
150
144
  partialStartVersionVector: string;
151
145
  plaintextHash: string;
152
146
  writeHeader: Record<string, unknown>;
147
+ authorizationTargets?: {
148
+ containerId: string;
149
+ containerKeyEpoch: number;
150
+ containerKeyEpochId: string;
151
+ containerManifestHash: string;
152
+ }[] | undefined;
153
153
  checkpointKind?: "rotate_baseline" | undefined;
154
154
  checkpointPayloadKind?: "full_history_snapshot" | undefined;
155
155
  sourceVersionVector?: string | undefined;
156
156
  }, z.core.$ZodTypeInternals<{
157
157
  accessEpoch: number;
158
- authorizationTargets: {
159
- containerId: string;
160
- containerKeyEpoch: number;
161
- containerKeyEpochId: string;
162
- containerManifestHash: string;
163
- }[];
164
158
  authorFingerprint: string;
165
159
  createdAt: string;
166
160
  documentId: string;
@@ -170,17 +164,17 @@ export declare const DocumentSyncUpdateResponseSchema: z.ZodType<{
170
164
  partialStartVersionVector: string;
171
165
  plaintextHash: string;
172
166
  writeHeader: Record<string, unknown>;
167
+ authorizationTargets?: {
168
+ containerId: string;
169
+ containerKeyEpoch: number;
170
+ containerKeyEpochId: string;
171
+ containerManifestHash: string;
172
+ }[] | undefined;
173
173
  checkpointKind?: "rotate_baseline" | undefined;
174
174
  checkpointPayloadKind?: "full_history_snapshot" | undefined;
175
175
  sourceVersionVector?: string | undefined;
176
176
  }, {
177
177
  accessEpoch: number;
178
- authorizationTargets: {
179
- containerId: string;
180
- containerKeyEpoch: number;
181
- containerKeyEpochId: string;
182
- containerManifestHash: string;
183
- }[];
184
178
  authorFingerprint: string;
185
179
  createdAt: string;
186
180
  documentId: string;
@@ -190,6 +184,12 @@ export declare const DocumentSyncUpdateResponseSchema: z.ZodType<{
190
184
  partialStartVersionVector: string;
191
185
  plaintextHash: string;
192
186
  writeHeader: Record<string, unknown>;
187
+ authorizationTargets?: {
188
+ containerId: string;
189
+ containerKeyEpoch: number;
190
+ containerKeyEpochId: string;
191
+ containerManifestHash: string;
192
+ }[] | undefined;
193
193
  checkpointKind?: "rotate_baseline" | undefined;
194
194
  checkpointPayloadKind?: "full_history_snapshot" | undefined;
195
195
  sourceVersionVector?: string | undefined;
@@ -235,12 +235,6 @@ export declare const DocumentSyncResponseSchema: z.ZodType<{
235
235
  };
236
236
  updates: {
237
237
  accessEpoch: number;
238
- authorizationTargets: {
239
- containerId: string;
240
- containerKeyEpoch: number;
241
- containerKeyEpochId: string;
242
- containerManifestHash: string;
243
- }[];
244
238
  authorFingerprint: string;
245
239
  createdAt: string;
246
240
  documentId: string;
@@ -250,6 +244,12 @@ export declare const DocumentSyncResponseSchema: z.ZodType<{
250
244
  partialStartVersionVector: string;
251
245
  plaintextHash: string;
252
246
  writeHeader: Record<string, unknown>;
247
+ authorizationTargets?: {
248
+ containerId: string;
249
+ containerKeyEpoch: number;
250
+ containerKeyEpochId: string;
251
+ containerManifestHash: string;
252
+ }[] | undefined;
253
253
  checkpointKind?: "rotate_baseline" | undefined;
254
254
  checkpointPayloadKind?: "full_history_snapshot" | undefined;
255
255
  sourceVersionVector?: string | undefined;
@@ -279,12 +279,6 @@ export declare const DocumentSyncResponseSchema: z.ZodType<{
279
279
  };
280
280
  updates: {
281
281
  accessEpoch: number;
282
- authorizationTargets: {
283
- containerId: string;
284
- containerKeyEpoch: number;
285
- containerKeyEpochId: string;
286
- containerManifestHash: string;
287
- }[];
288
282
  authorFingerprint: string;
289
283
  createdAt: string;
290
284
  documentId: string;
@@ -294,6 +288,12 @@ export declare const DocumentSyncResponseSchema: z.ZodType<{
294
288
  partialStartVersionVector: string;
295
289
  plaintextHash: string;
296
290
  writeHeader: Record<string, unknown>;
291
+ authorizationTargets?: {
292
+ containerId: string;
293
+ containerKeyEpoch: number;
294
+ containerKeyEpochId: string;
295
+ containerManifestHash: string;
296
+ }[] | undefined;
297
297
  checkpointKind?: "rotate_baseline" | undefined;
298
298
  checkpointPayloadKind?: "full_history_snapshot" | undefined;
299
299
  sourceVersionVector?: string | undefined;
@@ -323,12 +323,6 @@ export declare const DocumentSyncResponseSchema: z.ZodType<{
323
323
  };
324
324
  updates: {
325
325
  accessEpoch: number;
326
- authorizationTargets: {
327
- containerId: string;
328
- containerKeyEpoch: number;
329
- containerKeyEpochId: string;
330
- containerManifestHash: string;
331
- }[];
332
326
  authorFingerprint: string;
333
327
  createdAt: string;
334
328
  documentId: string;
@@ -338,6 +332,12 @@ export declare const DocumentSyncResponseSchema: z.ZodType<{
338
332
  partialStartVersionVector: string;
339
333
  plaintextHash: string;
340
334
  writeHeader: Record<string, unknown>;
335
+ authorizationTargets?: {
336
+ containerId: string;
337
+ containerKeyEpoch: number;
338
+ containerKeyEpochId: string;
339
+ containerManifestHash: string;
340
+ }[] | undefined;
341
341
  checkpointKind?: "rotate_baseline" | undefined;
342
342
  checkpointPayloadKind?: "full_history_snapshot" | undefined;
343
343
  sourceVersionVector?: string | undefined;
@@ -367,12 +367,6 @@ export declare const DocumentSyncResponseSchema: z.ZodType<{
367
367
  };
368
368
  updates: {
369
369
  accessEpoch: number;
370
- authorizationTargets: {
371
- containerId: string;
372
- containerKeyEpoch: number;
373
- containerKeyEpochId: string;
374
- containerManifestHash: string;
375
- }[];
376
370
  authorFingerprint: string;
377
371
  createdAt: string;
378
372
  documentId: string;
@@ -382,6 +376,12 @@ export declare const DocumentSyncResponseSchema: z.ZodType<{
382
376
  partialStartVersionVector: string;
383
377
  plaintextHash: string;
384
378
  writeHeader: Record<string, unknown>;
379
+ authorizationTargets?: {
380
+ containerId: string;
381
+ containerKeyEpoch: number;
382
+ containerKeyEpochId: string;
383
+ containerManifestHash: string;
384
+ }[] | undefined;
385
385
  checkpointKind?: "rotate_baseline" | undefined;
386
386
  checkpointPayloadKind?: "full_history_snapshot" | undefined;
387
387
  sourceVersionVector?: string | undefined;
@@ -35,7 +35,7 @@ export const DocumentContentKeyBundleResponseSchema = loosePlainObject({
35
35
  });
36
36
  export const DocumentSyncUpdateResponseSchema = registerJsonSchemaRuntimeRefinements(loosePlainObject({
37
37
  accessEpoch: positiveIntegerSchema,
38
- authorizationTargets: nonEmptyArraySchema(DocumentContentKeyTargetResponseSchema),
38
+ authorizationTargets: nonEmptyArraySchema(DocumentContentKeyTargetResponseSchema).optional(),
39
39
  authorFingerprint: z.string(),
40
40
  checkpointKind: z
41
41
  .literal(DOCUMENT_SYNC_ROTATION_CHECKPOINT_KIND)
@@ -1 +1 @@
1
- {"version":3,"file":"documentSyncSchema.js","sourceRoot":"","sources":["documentSyncSchema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EACL,oCAAoC,EACpC,gDAAgD,EAChD,sCAAsC,EACtC,8CAA8C,GAC/C,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,2CAA2C,EAC3C,+CAA+C,EAC/C,+CAA+C,EAC/C,sCAAsC,EACtC,sCAAsC,GACvC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,oCAAoC,EAAE,MAAM,eAAe,CAAC;AACrE,OAAO,EACL,WAAW,EACX,2BAA2B,EAC3B,gBAAgB,EAChB,mBAAmB,EACnB,oBAAoB,EACpB,iBAAiB,EACjB,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AC,CAAC;AACzD,CAAC,CAAC,EACF;IACE,2CAA2C;IAC3C,+CAA+C;IAC/C,sCAAsC;IACtC,+CAA+C;CAChD,CACF,CAAC","sourcesContent":["import { z } from \"zod\";\nimport {\n classifyDocumentSyncCheckpointFields,\n DOCUMENT_SYNC_CHECKPOINT_FIELD_SET_ISSUE_MESSAGE,\n DOCUMENT_SYNC_ROTATION_CHECKPOINT_KIND,\n DOCUMENT_SYNC_ROTATION_CHECKPOINT_PAYLOAD_KIND,\n} from \"../documentSyncCheckpoint\";\nimport {\n documentSyncResponseCommitLsnModeRefinement,\n documentSyncResponseCommitLsnSentinelRefinement,\n documentSyncResponseHistoricalBundlesRefinement,\n documentSyncResponsePullPageRefinement,\n documentSyncResponseRotationRefinement,\n} from \"../documentSyncRefinements\";\nimport { registerJsonSchemaRuntimeRefinements } from \"../jsonSchema\";\nimport {\n arraySchema,\n boundedNonEmptyStringSchema,\n loosePlainObject,\n nonEmptyArraySchema,\n nonEmptyStringSchema,\n plainObjectSchema,\n positiveIntegerSchema,\n} from \"../schema\";\nimport {\n MAX_DOCUMENT_SYNC_OUTGOING_UPDATES,\n MAX_DOCUMENT_SYNC_PULL_CURSOR_LENGTH,\n MAX_DOCUMENT_SYNC_RESPONSE_PAGE_UPDATES,\n} from \"../util/documentSyncLimits\";\n\nexport const DocumentContentKeyTargetEnvelopeResponseSchema = loosePlainObject({\n containerId: nonEmptyStringSchema,\n containerKeyEpoch: positiveIntegerSchema,\n containerKeyEpochId: nonEmptyStringSchema,\n containerManifestHash: nonEmptyStringSchema,\n wrappedKey: nonEmptyStringSchema,\n wrappingMetadata: plainObjectSchema,\n});\n\nexport type DocumentContentKeyTargetEnvelopeResponse = z.infer<\n typeof DocumentContentKeyTargetEnvelopeResponseSchema\n>;\n\nconst DocumentContentKeyTargetResponseSchema = loosePlainObject({\n containerId: nonEmptyStringSchema,\n containerKeyEpoch: positiveIntegerSchema,\n containerKeyEpochId: nonEmptyStringSchema,\n containerManifestHash: nonEmptyStringSchema,\n});\n\nexport const DocumentKekTargetsResponseSchema = loosePlainObject({\n documentId: z.string(),\n documentKeyTargetHash: nonEmptyStringSchema,\n linkedContainerKeyEpochIds: nonEmptyArraySchema(nonEmptyStringSchema),\n linkedContainerManifestHashes: nonEmptyArraySchema(nonEmptyStringSchema),\n linkSetManifestHash: nonEmptyStringSchema,\n targets: nonEmptyArraySchema(plainObjectSchema),\n});\n\nexport type DocumentKekTargetsResponse = z.infer<\n typeof DocumentKekTargetsResponseSchema\n>;\n\nexport const DocumentContentKeyBundleResponseSchema = loosePlainObject({\n contentKeyEpoch: positiveIntegerSchema,\n documentId: z.string(),\n linkSetManifestHash: nonEmptyStringSchema,\n targetHash: nonEmptyStringSchema,\n targets: nonEmptyArraySchema(DocumentContentKeyTargetEnvelopeResponseSchema),\n});\n\nexport type DocumentContentKeyBundleResponse = z.infer<\n typeof DocumentContentKeyBundleResponseSchema\n>;\n\nexport const DocumentSyncUpdateResponseSchema =\n registerJsonSchemaRuntimeRefinements(\n loosePlainObject({\n accessEpoch: positiveIntegerSchema,\n authorizationTargets: nonEmptyArraySchema(\n DocumentContentKeyTargetResponseSchema,\n ),\n authorFingerprint: z.string(),\n checkpointKind: z\n .literal(DOCUMENT_SYNC_ROTATION_CHECKPOINT_KIND)\n .optional(),\n checkpointPayloadKind: z\n .literal(DOCUMENT_SYNC_ROTATION_CHECKPOINT_PAYLOAD_KIND)\n .optional(),\n createdAt: z.string(),\n documentId: z.string(),\n encryptedData: z.string(),\n id: z.string(),\n partialEndVersionVector: z.string(),\n partialStartVersionVector: z.string(),\n plaintextHash: nonEmptyStringSchema,\n sourceVersionVector: z.string().min(1).optional(),\n writeHeader: plainObjectSchema,\n }).superRefine((update, context) => {\n if (classifyDocumentSyncCheckpointFields(update) === \"invalid\") {\n context.addIssue({\n code: \"custom\",\n message: DOCUMENT_SYNC_CHECKPOINT_FIELD_SET_ISSUE_MESSAGE,\n });\n }\n }),\n [documentSyncResponseRotationRefinement],\n );\n\nexport type DocumentSyncUpdateResponse = z.infer<\n typeof DocumentSyncUpdateResponseSchema\n>;\n\nexport const DocumentSyncPullPageResponseSchema = loosePlainObject({\n hasMore: z.boolean(),\n nextCursor: boundedNonEmptyStringSchema(\n MAX_DOCUMENT_SYNC_PULL_CURSOR_LENGTH,\n ).nullable(),\n});\n\nexport type DocumentSyncPullPageResponse = z.infer<\n typeof DocumentSyncPullPageResponseSchema\n>;\n\nfunction contentKeyEpochOf(bundle: unknown): number | null {\n if (typeof bundle !== \"object\" || bundle === null) return null;\n const contentKeyEpoch: unknown = Reflect.get(bundle, \"contentKeyEpoch\");\n return typeof contentKeyEpoch === \"number\" ? contentKeyEpoch : null;\n}\n\n/**\n * The client already holds the current epoch's bundle, so the array holds the\n * distinct older epochs that served updates cite; the client rejects any epoch\n * not older than the one it planned against. Field issues do not stop this\n * object refinement, so it judges only epochs that parsed.\n */\nfunction addHistoricalContentKeyBundleIssues(\n response: { readonly contentKeyBundles: unknown },\n context: z.RefinementCtx,\n): void {\n if (!Array.isArray(response.contentKeyBundles)) return;\n const seenEpochs = new Set<number>();\n // forEach skips holes exactly as arraySchema's item validation does.\n response.contentKeyBundles.forEach((bundle: unknown, index: number) => {\n const contentKeyEpoch = contentKeyEpochOf(bundle);\n if (contentKeyEpoch === null) return;\n if (seenEpochs.has(contentKeyEpoch)) {\n context.addIssue({\n code: \"custom\",\n message: \"content-key bundles must be distinct epochs\",\n path: [\"contentKeyBundles\", index, \"contentKeyEpoch\"],\n });\n }\n seenEpochs.add(contentKeyEpoch);\n });\n}\n\nexport const commitLsnResponseShape = {\n commitLsn: z.string().nullable(),\n commitLsnMode: z.union([z.literal(\"tracked\"), z.literal(\"untracked\")]),\n};\n\n/** The 0/0 sentinel and the untracked mode imply each other. */\nfunction addCommitLsnIssues(\n response: {\n readonly commitLsn: string | null;\n readonly commitLsnMode: \"tracked\" | \"untracked\";\n },\n context: z.RefinementCtx,\n): void {\n if (response.commitLsnMode === \"untracked\" && response.commitLsn !== \"0/0\") {\n context.addIssue({\n code: \"custom\",\n message: \"untracked commit LSN must use the 0/0 sentinel\",\n path: [\"commitLsn\"],\n });\n }\n if (response.commitLsn === \"0/0\" && response.commitLsnMode !== \"untracked\") {\n context.addIssue({\n code: \"custom\",\n message: \"0/0 commit LSN must be declared untracked\",\n path: [\"commitLsnMode\"],\n });\n }\n}\n\nexport const DocumentSyncResponseSchema = registerJsonSchemaRuntimeRefinements(\n loosePlainObject({\n acceptedOutgoingUpdateIds: arraySchema(\n z.string(),\n MAX_DOCUMENT_SYNC_OUTGOING_UPDATES,\n ),\n ...commitLsnResponseShape,\n contentKeyBundles: arraySchema(DocumentContentKeyBundleResponseSchema),\n documentId: z.string(),\n pullPage: DocumentSyncPullPageResponseSchema,\n updates: arraySchema(\n DocumentSyncUpdateResponseSchema,\n MAX_DOCUMENT_SYNC_RESPONSE_PAGE_UPDATES,\n ),\n }).superRefine((response, context) => {\n if (\n response.pullPage !== undefined &&\n response.pullPage.hasMore !== (response.pullPage.nextCursor !== null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"pull page continuation does not match hasMore\",\n path: [\"pullPage\", \"nextCursor\"],\n });\n }\n addCommitLsnIssues(response, context);\n addHistoricalContentKeyBundleIssues(response, context);\n }),\n [\n documentSyncResponseCommitLsnModeRefinement,\n documentSyncResponseCommitLsnSentinelRefinement,\n documentSyncResponsePullPageRefinement,\n documentSyncResponseHistoricalBundlesRefinement,\n ],\n);\n\nexport type DocumentSyncResponse = z.infer<typeof DocumentSyncResponseSchema>;\n"]}
1
+ {"version":3,"file":"documentSyncSchema.js","sourceRoot":"","sources":["documentSyncSchema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EACL,oCAAoC,EACpC,gDAAgD,EAChD,sCAAsC,EACtC,8CAA8C,GAC/C,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,2CAA2C,EAC3C,+CAA+C,EAC/C,+CAA+C,EAC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CAAC;YACf,IAAI,EAAE,QAAQ;YACd,OAAO,EAAE,+CAA+C;YACxD,IAAI,EAAE,CAAC,UAAU,EAAE,YAAY,CAAC;SACjC,CAAC,CAAC;IACL,CAAC;IACD,kBAAkB,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;IACtC,mCAAmC,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;AACzD,CAAC,CAAC,EACF;IACE,2CAA2C;IAC3C,+CAA+C;IAC/C,sCAAsC;IACtC,+CAA+C;CAChD,CACF,CAAC","sourcesContent":["import { z } from \"zod\";\nimport {\n classifyDocumentSyncCheckpointFields,\n DOCUMENT_SYNC_CHECKPOINT_FIELD_SET_ISSUE_MESSAGE,\n DOCUMENT_SYNC_ROTATION_CHECKPOINT_KIND,\n DOCUMENT_SYNC_ROTATION_CHECKPOINT_PAYLOAD_KIND,\n} from \"../documentSyncCheckpoint\";\nimport {\n documentSyncResponseCommitLsnModeRefinement,\n documentSyncResponseCommitLsnSentinelRefinement,\n documentSyncResponseHistoricalBundlesRefinement,\n documentSyncResponsePullPageRefinement,\n documentSyncResponseRotationRefinement,\n} from \"../documentSyncRefinements\";\nimport { registerJsonSchemaRuntimeRefinements } from \"../jsonSchema\";\nimport {\n arraySchema,\n boundedNonEmptyStringSchema,\n loosePlainObject,\n nonEmptyArraySchema,\n nonEmptyStringSchema,\n plainObjectSchema,\n positiveIntegerSchema,\n} from \"../schema\";\nimport {\n MAX_DOCUMENT_SYNC_OUTGOING_UPDATES,\n MAX_DOCUMENT_SYNC_PULL_CURSOR_LENGTH,\n MAX_DOCUMENT_SYNC_RESPONSE_PAGE_UPDATES,\n} from \"../util/documentSyncLimits\";\n\nexport const DocumentContentKeyTargetEnvelopeResponseSchema = loosePlainObject({\n containerId: nonEmptyStringSchema,\n containerKeyEpoch: positiveIntegerSchema,\n containerKeyEpochId: nonEmptyStringSchema,\n containerManifestHash: nonEmptyStringSchema,\n wrappedKey: nonEmptyStringSchema,\n wrappingMetadata: plainObjectSchema,\n});\n\nexport type DocumentContentKeyTargetEnvelopeResponse = z.infer<\n typeof DocumentContentKeyTargetEnvelopeResponseSchema\n>;\n\nconst DocumentContentKeyTargetResponseSchema = loosePlainObject({\n containerId: nonEmptyStringSchema,\n containerKeyEpoch: positiveIntegerSchema,\n containerKeyEpochId: nonEmptyStringSchema,\n containerManifestHash: nonEmptyStringSchema,\n});\n\nexport const DocumentKekTargetsResponseSchema = loosePlainObject({\n documentId: z.string(),\n documentKeyTargetHash: nonEmptyStringSchema,\n linkedContainerKeyEpochIds: nonEmptyArraySchema(nonEmptyStringSchema),\n linkedContainerManifestHashes: nonEmptyArraySchema(nonEmptyStringSchema),\n linkSetManifestHash: nonEmptyStringSchema,\n targets: nonEmptyArraySchema(plainObjectSchema),\n});\n\nexport type DocumentKekTargetsResponse = z.infer<\n typeof DocumentKekTargetsResponseSchema\n>;\n\nexport const DocumentContentKeyBundleResponseSchema = loosePlainObject({\n contentKeyEpoch: positiveIntegerSchema,\n documentId: z.string(),\n linkSetManifestHash: nonEmptyStringSchema,\n targetHash: nonEmptyStringSchema,\n targets: nonEmptyArraySchema(DocumentContentKeyTargetEnvelopeResponseSchema),\n});\n\nexport type DocumentContentKeyBundleResponse = z.infer<\n typeof DocumentContentKeyBundleResponseSchema\n>;\n\nexport const DocumentSyncUpdateResponseSchema =\n registerJsonSchemaRuntimeRefinements(\n loosePlainObject({\n accessEpoch: positiveIntegerSchema,\n authorizationTargets: nonEmptyArraySchema(\n DocumentContentKeyTargetResponseSchema,\n ).optional(),\n authorFingerprint: z.string(),\n checkpointKind: z\n .literal(DOCUMENT_SYNC_ROTATION_CHECKPOINT_KIND)\n .optional(),\n checkpointPayloadKind: z\n .literal(DOCUMENT_SYNC_ROTATION_CHECKPOINT_PAYLOAD_KIND)\n .optional(),\n createdAt: z.string(),\n documentId: z.string(),\n encryptedData: z.string(),\n id: z.string(),\n partialEndVersionVector: z.string(),\n partialStartVersionVector: z.string(),\n plaintextHash: nonEmptyStringSchema,\n sourceVersionVector: z.string().min(1).optional(),\n writeHeader: plainObjectSchema,\n }).superRefine((update, context) => {\n if (classifyDocumentSyncCheckpointFields(update) === \"invalid\") {\n context.addIssue({\n code: \"custom\",\n message: DOCUMENT_SYNC_CHECKPOINT_FIELD_SET_ISSUE_MESSAGE,\n });\n }\n }),\n [documentSyncResponseRotationRefinement],\n );\n\nexport type DocumentSyncUpdateResponse = z.infer<\n typeof DocumentSyncUpdateResponseSchema\n>;\n\nexport const DocumentSyncPullPageResponseSchema = loosePlainObject({\n hasMore: z.boolean(),\n nextCursor: boundedNonEmptyStringSchema(\n MAX_DOCUMENT_SYNC_PULL_CURSOR_LENGTH,\n ).nullable(),\n});\n\nexport type DocumentSyncPullPageResponse = z.infer<\n typeof DocumentSyncPullPageResponseSchema\n>;\n\nfunction contentKeyEpochOf(bundle: unknown): number | null {\n if (typeof bundle !== \"object\" || bundle === null) return null;\n const contentKeyEpoch: unknown = Reflect.get(bundle, \"contentKeyEpoch\");\n return typeof contentKeyEpoch === \"number\" ? contentKeyEpoch : null;\n}\n\n/**\n * The client already holds the current epoch's bundle, so the array holds the\n * distinct older epochs that served updates cite; the client rejects any epoch\n * not older than the one it planned against. Field issues do not stop this\n * object refinement, so it judges only epochs that parsed.\n */\nfunction addHistoricalContentKeyBundleIssues(\n response: { readonly contentKeyBundles: unknown },\n context: z.RefinementCtx,\n): void {\n if (!Array.isArray(response.contentKeyBundles)) return;\n const seenEpochs = new Set<number>();\n // forEach skips holes exactly as arraySchema's item validation does.\n response.contentKeyBundles.forEach((bundle: unknown, index: number) => {\n const contentKeyEpoch = contentKeyEpochOf(bundle);\n if (contentKeyEpoch === null) return;\n if (seenEpochs.has(contentKeyEpoch)) {\n context.addIssue({\n code: \"custom\",\n message: \"content-key bundles must be distinct epochs\",\n path: [\"contentKeyBundles\", index, \"contentKeyEpoch\"],\n });\n }\n seenEpochs.add(contentKeyEpoch);\n });\n}\n\nexport const commitLsnResponseShape = {\n commitLsn: z.string().nullable(),\n commitLsnMode: z.union([z.literal(\"tracked\"), z.literal(\"untracked\")]),\n};\n\n/** The 0/0 sentinel and the untracked mode imply each other. */\nfunction addCommitLsnIssues(\n response: {\n readonly commitLsn: string | null;\n readonly commitLsnMode: \"tracked\" | \"untracked\";\n },\n context: z.RefinementCtx,\n): void {\n if (response.commitLsnMode === \"untracked\" && response.commitLsn !== \"0/0\") {\n context.addIssue({\n code: \"custom\",\n message: \"untracked commit LSN must use the 0/0 sentinel\",\n path: [\"commitLsn\"],\n });\n }\n if (response.commitLsn === \"0/0\" && response.commitLsnMode !== \"untracked\") {\n context.addIssue({\n code: \"custom\",\n message: \"0/0 commit LSN must be declared untracked\",\n path: [\"commitLsnMode\"],\n });\n }\n}\n\nexport const DocumentSyncResponseSchema = registerJsonSchemaRuntimeRefinements(\n loosePlainObject({\n acceptedOutgoingUpdateIds: arraySchema(\n z.string(),\n MAX_DOCUMENT_SYNC_OUTGOING_UPDATES,\n ),\n ...commitLsnResponseShape,\n contentKeyBundles: arraySchema(DocumentContentKeyBundleResponseSchema),\n documentId: z.string(),\n pullPage: DocumentSyncPullPageResponseSchema,\n updates: arraySchema(\n DocumentSyncUpdateResponseSchema,\n MAX_DOCUMENT_SYNC_RESPONSE_PAGE_UPDATES,\n ),\n }).superRefine((response, context) => {\n if (\n response.pullPage !== undefined &&\n response.pullPage.hasMore !== (response.pullPage.nextCursor !== null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"pull page continuation does not match hasMore\",\n path: [\"pullPage\", \"nextCursor\"],\n });\n }\n addCommitLsnIssues(response, context);\n addHistoricalContentKeyBundleIssues(response, context);\n }),\n [\n documentSyncResponseCommitLsnModeRefinement,\n documentSyncResponseCommitLsnSentinelRefinement,\n documentSyncResponsePullPageRefinement,\n documentSyncResponseHistoricalBundlesRefinement,\n ],\n);\n\nexport type DocumentSyncResponse = z.infer<typeof DocumentSyncResponseSchema>;\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tearleads/client-sdk",
3
- "version": "0.1.240",
3
+ "version": "0.1.241",
4
4
  "description": "React-free Tearleads client runtime: local SQLite persistence, keys, sync, encrypted blobs, and domain workflows.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -190,6 +190,22 @@ function attachmentBindingDocumentId(binding) {
190
190
  }
191
191
  return readRecordString(readCanonicalRecord(binding.bindingEvent.body, "Attachment binding event body"), "documentId", "Attachment binding event body");
192
192
  }
193
+ /**
194
+ * The listing omits the write's target set when its hash equals the current
195
+ * set's, so refill it from `blobKekTargets`; verification re-hashes it against
196
+ * the write authorization and the signed header. Any other omission fails.
197
+ */
198
+ function writeAuthorizationWithTargets(binding) {
199
+ const { blobKekTargets, writeAuthorization } = binding;
200
+ if (!writeAuthorization)
201
+ return undefined;
202
+ if (writeAuthorization.targets)
203
+ return { ...writeAuthorization, targets: writeAuthorization.targets };
204
+ if (!blobKekTargets ||
205
+ writeAuthorization.blobKeyTargetHash !== blobKekTargets.blobKeyTargetHash)
206
+ throw new Error("Attachment blob write authorization lacks its targets");
207
+ return { ...writeAuthorization, targets: blobKekTargets.targets };
208
+ }
193
209
  async function assertBlobWriteHeaderVerified(input) {
194
210
  if (!input.authorization || !input.binding.writeHeader) {
195
211
  throw new Error("Attachment blob lacks verified write authority");
@@ -206,7 +222,7 @@ async function assertBlobWriteHeaderVerified(input) {
206
222
  });
207
223
  const blobKekTargets = await verifiedBlobKekTargetsForBinding({
208
224
  binding: input.binding,
209
- projection: input.binding.writeAuthorization,
225
+ projection: writeAuthorizationWithTargets(input.binding),
210
226
  // The signed binding proves which slot exposes the blob now. Writer
211
227
  // authorization describes the older target set committed when the bytes
212
228
  // were written, so a later valid binding need not appear in that set.
@@ -1 +1 @@
1
- {"version":3,"file":"decrypt.js","sourceRoot":"","sources":["decrypt.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,UAAU,EACV,+BAA+B,EAC/B,6BAA6B,EAC7B,+BAA+B,EAC/B,mCA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;QAC1D,MAAM,CAAC,eAAe,KAAK,KAAK,CAAC,SAAS,CAAC,eAAe,EAC1D,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,wDAAwD,CAAC,CAAC;IAC5E,CAAC;IACD,MAAM,QAAQ,GAAG,MAAM,iBAAiB,CAAC;QACvC,uBAAuB,EAAE,YAAY;QACrC,iBAAiB,EAAE;YACjB,yBAAyB,EAAE,0BAA0B,CAAC;gBACpD,2BAA2B,EACzB,KAAK,CAAC,aAAa,CAAC,2BAA2B;gBACjD,wBAAwB,EAAE,MAAM,CAAC,wBAAwB;aAC1D,CAAC,CAAC,wBAAwB;YAC3B,cAAc;YACd,iBAAiB,EAAE,KAAK,CAAC,aAAa,CAAC,iBAAiB;SACzD;QACD,0BAA0B,EAAE,cAAc,CAAC,sBAAsB;QACjE,cAAc,EAAE;YACd,UAAU,EAAE,MAAM;YAClB,QAAQ,EAAE,KAAK,CAAC,OAAO,CAAC,MAAM;YAC9B,cAAc,EAAE,KAAK,CAAC,cAAc;SACrC;QACD,kBAAkB,EAAE,cAAc,CAAC,iBAAiB;QACpD,MAAM;QACN,eAAe,EAAE,MAAM,CAAC,gBAAgB;KACzC,CAAC,CAAC;IACH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;QACjB,MAAM,QAAQ,CAAC,KAAK,CAAC;IACvB,CAAC;AACH,CAAC","sourcesContent":["import {\n blobContentMetadataHash,\n bytesToHex,\n CONTENT_RECORD_ENCRYPTION_SUITE,\n computeBlobAccessManifestHash,\n computeBlobContentKeyTargetHash,\n computeContentRecordNonceDomainHash,\n makeVerifiedBlobKekTargets,\n verifyWriteHeader,\n} from \"@tearleads/crypto\";\nimport type { BlobKekTargetsResponse } from \"@tearleads/validators/response\";\nimport { deriveBlobContentRecordKey } from \"../../../data/blobs/attachments/crypto\";\nimport { unwrapBlobContentKey } from \"../../../data/blobs/attachments/projection\";\nimport {\n parseBlobEncryptedBytes,\n readBlobKekTarget,\n readDocumentManifestIdentity,\n sortBlobTargets,\n} from \"../../../data/blobs/attachments/readers\";\nimport { assertBlobContentKeyBundleTargetHash } from \"../../../data/blobs/attachments/responses\";\nimport type {\n BlobEncryptedBytesHeader,\n DecryptDocumentAttachmentBlobInput,\n} from \"../../../data/blobs/attachments/types\";\nimport type { BlobBytes } from \"../../../data/blobs/blobContracts\";\nimport { importContentKeyMaterial } from \"../../../data/documents/shared/contentRecordKeys\";\nimport { assertDocumentWriterProjectionConsistent } from \"../../../data/documents/shared/projection\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport {\n asWebCryptoBytes,\n readWriteHeader,\n uniqueSortedStrings,\n} from \"../../../data/documents/shared/readers\";\nimport { readCanonicalRecord } from \"../../../data/keying/canonicalJson\";\nimport type { DocumentWriterProjectionAuthorization } from \"../../../data/keyingProjectionVerification\";\nimport {\n readRecordString,\n requireProjectionUserKeyResolver,\n resolveEventContainerPaths,\n} from \"../../../data/keyingProjectionVerification\";\n\nimport { assertAttachmentBindingVerified } from \"../verification/attachmentBindingVerification\";\nimport { assertBlobWrapScopeVerified } from \"../verification/verifiedWrapScope\";\nimport { decryptBlobChunks } from \"./blobChunkDecryption\";\n\nasync function assertBlobEncryptionMetadata(input: {\n readonly contentKeyBundle: DecryptDocumentAttachmentBlobInput[\"binding\"][\"contentKeyBundle\"];\n readonly encrypted: BlobEncryptedBytesHeader;\n readonly expectedBlobId: string;\n readonly organizationId: string;\n}): Promise<void> {\n const { contentKeyBundle, encrypted, expectedBlobId, organizationId } = input;\n if (\n encrypted.blobId !== expectedBlobId ||\n encrypted.contentRecordId !== expectedBlobId\n ) {\n throw new Error(\"Blob encrypted bytes blob id mismatch\");\n }\n if (\n encrypted.contentKeyEpoch !== contentKeyBundle.contentKeyEpoch ||\n contentKeyBundle.blobId !== expectedBlobId\n ) {\n throw new Error(\"Blob encrypted bytes content-key bundle mismatch\");\n }\n await assertBlobContentKeyBundleTargetHash(contentKeyBundle);\n\n const expectedNonceDomainHash = await computeContentRecordNonceDomainHash({\n version: 1,\n organizationId,\n objectKind: \"blob\",\n objectId: expectedBlobId,\n contentKeyEpoch: encrypted.contentKeyEpoch,\n encryptionSuite: CONTENT_RECORD_ENCRYPTION_SUITE,\n contentRecordId: encrypted.contentRecordId,\n });\n if (encrypted.nonceDomainHash !== expectedNonceDomainHash) {\n throw new Error(\"Blob encrypted bytes nonce domain mismatch\");\n }\n const expectedMetadataHash = await blobContentMetadataHash({\n blobId: expectedBlobId,\n byteLength: encrypted.byteLength,\n chunkCount: encrypted.chunkCount,\n chunkSize: encrypted.chunkSize,\n contentKeyEpoch: encrypted.contentKeyEpoch,\n });\n if (encrypted.metadataHash !== expectedMetadataHash) {\n throw new Error(\"Blob encrypted bytes metadata hash mismatch\");\n }\n}\n\nexport type AttachmentBlobDecryptionInput = Omit<\n DecryptDocumentAttachmentBlobInput,\n \"encryptedBytes\"\n> & {\n encrypted: BlobEncryptedBytesHeader;\n};\n\n/** Verifies metadata and authority; the caller must still authenticate ciphertext. */\nexport async function prepareDocumentAttachmentBlobDecryption({\n binding,\n encrypted,\n expectedDocumentId,\n expectedSlotId,\n execSql,\n resolveProjectionUserKey,\n targetSecretKey,\n stillCurrent,\n warmReferencedPrincipalPolicies,\n writerProjection,\n}: AttachmentBlobDecryptionInput): Promise<{\n contentKey: Uint8Array;\n recordKey: CryptoKey;\n organizationId: string;\n}> {\n const requiredResolveProjectionUserKey = requireProjectionUserKeyResolver(\n resolveProjectionUserKey,\n \"Document attachment blob decrypt\",\n );\n const verificationOptions = projectionVerificationOptions({\n execSql,\n stillCurrent,\n warmReferencedPrincipalPolicies,\n resolveProjectionUserKey: requiredResolveProjectionUserKey,\n });\n let documentAuthorization: DocumentWriterProjectionAuthorization | undefined;\n await assertDocumentWriterProjectionConsistent(writerProjection, {\n allowStaleContentKeyBundle: true,\n execSql,\n onVerifiedAuthorization: (authorization) => {\n documentAuthorization = authorization;\n },\n ...verificationOptions,\n });\n const { documentId, organizationId } =\n readDocumentManifestIdentity(writerProjection);\n await assertBlobEncryptionMetadata({\n contentKeyBundle: binding.contentKeyBundle,\n encrypted,\n expectedBlobId: binding.blobId,\n organizationId,\n });\n await assertAttachmentBindingVerified({\n authorization: documentAuthorization,\n binding,\n expectedDocumentId,\n expectedSlotId,\n resolveProjectionUserKey: requiredResolveProjectionUserKey,\n });\n await assertBlobWriteHeaderVerified({\n authorization: documentAuthorization,\n binding,\n encrypted,\n organizationId,\n resolveProjectionUserKey: requiredResolveProjectionUserKey,\n });\n\n if (!documentAuthorization)\n throw new Error(\"Blob document authorization is unavailable\");\n assertBlobWrapScopeVerified({\n authorization: documentAuthorization,\n binding,\n documentId,\n });\n const contentKey = await unwrapBlobContentKey({\n blobId: binding.blobId,\n contentKeyBundle: binding.contentKeyBundle,\n documentId,\n encrypted,\n execSql,\n expectedBindingId: binding.bindingId,\n secretKey: targetSecretKey,\n ...verificationOptions,\n writerProjection,\n });\n const contentKeyMaterial = await importContentKeyMaterial(contentKey);\n const recordKey = await deriveBlobContentRecordKey({\n blobId: binding.blobId,\n contentKeyEpoch: encrypted.contentKeyEpoch,\n contentKeyMaterial,\n contentRecordId: encrypted.contentRecordId,\n organizationId,\n usage: \"decrypt\",\n });\n return { contentKey, recordKey, organizationId };\n}\n\nasync function decryptDocumentAttachmentBlobWithKey(\n input: DecryptDocumentAttachmentBlobInput,\n): Promise<{ bytes: BlobBytes; contentKey: Uint8Array }> {\n const encrypted = parseBlobEncryptedBytes(input.encryptedBytes);\n const context = await prepareDocumentAttachmentBlobDecryption({\n ...input,\n encrypted,\n });\n const header = readWriteHeader(\n input.binding.writeHeader,\n \"Attachment blob write header\",\n );\n const ciphertextHash = bytesToHex(\n new Uint8Array(\n await crypto.subtle.digest(\n \"SHA-256\",\n asWebCryptoBytes(input.encryptedBytes),\n ),\n ),\n );\n if (header.ciphertextHash !== ciphertextHash)\n throw new Error(\"Attachment blob write header does not match ciphertext\");\n const bytes = await decryptBlobChunks({\n ...context,\n encrypted,\n expectedBlobId: input.binding.blobId,\n });\n return { bytes, contentKey: context.contentKey };\n}\n\nexport async function decryptDocumentAttachmentBlob(\n input: DecryptDocumentAttachmentBlobInput,\n): Promise<BlobBytes> {\n return (await decryptDocumentAttachmentBlobWithKey(input)).bytes;\n}\n\nfunction assertStringSetEquals(input: {\n readonly actual: readonly string[];\n readonly expected: readonly string[];\n readonly label: string;\n}): void {\n const actual = uniqueSortedStrings(input.actual);\n const expected = uniqueSortedStrings(input.expected);\n if (\n actual.length !== expected.length ||\n actual.some((value, index) => value !== expected[index])\n ) {\n throw new Error(`${input.label} is inconsistent`);\n }\n}\n\nasync function verifiedBlobKekTargetsForBinding(input: {\n readonly binding: DecryptDocumentAttachmentBlobInput[\"binding\"];\n readonly requireBindingMembership: boolean;\n readonly projection: BlobKekTargetsResponse | undefined;\n}) {\n const { binding, projection } = input;\n if (!projection) {\n throw new Error(\"Attachment binding lacks blob KEK verification material\");\n }\n const targets = sortBlobTargets(\n projection.targets.map((target, index) =>\n readBlobKekTarget(target, `Attachment blob KEK target[${index}]`),\n ),\n );\n const targetHash = await computeBlobContentKeyTargetHash(targets);\n if (\n targetHash !== projection.blobKeyTargetHash ||\n projection.blobId !== binding.blobId\n ) {\n throw new Error(\"Attachment blob KEK target hash is inconsistent\");\n }\n if (\n input.requireBindingMembership &&\n (!projection.activeBindingIds.includes(binding.bindingId) ||\n !targets.some(\n (target) =>\n target.bindingId === binding.bindingId &&\n target.documentId === attachmentBindingDocumentId(binding),\n ))\n ) {\n throw new Error(\"Attachment binding is absent from blob KEK targets\");\n }\n assertStringSetEquals({\n actual: projection.linkedContainerManifestHashes,\n expected: targets.map((target) => target.containerManifestHash),\n label: \"Attachment blob container manifests\",\n });\n assertStringSetEquals({\n actual: projection.linkedContainerKeyEpochIds,\n expected: targets.map((target) => target.containerKeyEpochId),\n label: \"Attachment blob container KEKs\",\n });\n const accessManifestHash = await computeBlobAccessManifestHash({\n version: 1,\n blobId: projection.blobId,\n organizationId: projection.organizationId,\n activeBindingIds: projection.activeBindingIds,\n documentManifestHashes: projection.documentManifestHashes,\n linkedContainerManifestHashes: projection.linkedContainerManifestHashes,\n linkedContainerKeyEpochIds: projection.linkedContainerKeyEpochIds,\n blobKeyTargetHash: projection.blobKeyTargetHash,\n });\n if (accessManifestHash !== projection.blobAccessManifestHash) {\n throw new Error(\"Attachment blob access manifest hash is inconsistent\");\n }\n return makeVerifiedBlobKekTargets({ ...projection, targets });\n}\n\nfunction attachmentBindingDocumentId(\n binding: DecryptDocumentAttachmentBlobInput[\"binding\"],\n): string {\n if (!binding.bindingEvent) {\n throw new Error(\"Attachment binding lacks a signed event\");\n }\n return readRecordString(\n readCanonicalRecord(\n binding.bindingEvent.body,\n \"Attachment binding event body\",\n ),\n \"documentId\",\n \"Attachment binding event body\",\n );\n}\n\nasync function assertBlobWriteHeaderVerified(input: {\n readonly authorization: DocumentWriterProjectionAuthorization | undefined;\n readonly binding: DecryptDocumentAttachmentBlobInput[\"binding\"];\n readonly encrypted: BlobEncryptedBytesHeader;\n readonly organizationId: string;\n readonly resolveProjectionUserKey: ReturnType<\n typeof requireProjectionUserKeyResolver\n >;\n}): Promise<void> {\n if (!input.authorization || !input.binding.writeHeader) {\n throw new Error(\"Attachment blob lacks verified write authority\");\n }\n const header = readWriteHeader(\n input.binding.writeHeader,\n \"Attachment blob write header\",\n );\n const writer = await input.resolveProjectionUserKey(header.writerUserId);\n if (!writer) {\n throw new Error(\"Attachment blob writer identity is unavailable\");\n }\n await verifiedBlobKekTargetsForBinding({\n binding: input.binding,\n projection: input.binding.blobKekTargets,\n requireBindingMembership: true,\n });\n const blobKekTargets = await verifiedBlobKekTargetsForBinding({\n binding: input.binding,\n projection: input.binding.writeAuthorization,\n // The signed binding proves which slot exposes the blob now. Writer\n // authorization describes the older target set committed when the bytes\n // were written, so a later valid binding need not appear in that set.\n requireBindingMembership: false,\n });\n if (\n header.metadataHash !== input.encrypted.metadataHash ||\n header.contentKeyEpoch !== input.encrypted.contentKeyEpoch ||\n header.contentRecordId !== input.encrypted.contentRecordId ||\n header.nonceDomainHash !== input.encrypted.nonceDomainHash\n ) {\n throw new Error(\"Attachment blob write header does not match ciphertext\");\n }\n const verified = await verifyWriteHeader({\n authorizationMembership: \"referenced\",\n blobAuthorization: {\n authorizingContainerPaths: resolveEventContainerPaths({\n containerPathByManifestHash:\n input.authorization.containerPathByManifestHash,\n dependencyManifestHashes: header.dependencyManifestHashes,\n }).dependencyContainerPaths,\n blobKekTargets,\n principalPolicies: input.authorization.principalPolicies,\n },\n expectedAccessManifestHash: blobKekTargets.blobAccessManifestHash,\n expectedObject: {\n objectKind: \"blob\",\n objectId: input.binding.blobId,\n organizationId: input.organizationId,\n },\n expectedTargetHash: blobKekTargets.blobKeyTargetHash,\n header,\n writerPublicKey: writer.signingPublicKey,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n}\n"]}
1
+ {"version":3,"file":"decrypt.js","sourceRoot":"","sources":["decrypt.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,UAAU,EACV,+BAA+B,EAC/B,6BAA6B,EAC7B,+BAA+B,EAC/B,mCAAmC,EACnC,0BAA0B,EAC1B,iBAAiB,GAClB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,0BAA0B,EAAE,MAAM,wCAAwC,CAAC;AACpF,OAAO,EAAE,oBAAoB,EAAE,MAAM,4CAA4C,CAAC;AAClF,OAAO,EACL,uBAAuB,EACvB,iBAAiB,EACjB,4BAA4B,EAC5B,eAAe,GAChB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,oCAAoC,EAAE,MAAM,2CAA2C,CAAC;AAMjG,OAAO,EAAE,wBAAwB,EAAE,MAAM,kDAAkD,CAAC;AAC5F,OAAO,EAAE,wCAAwC,EAAE,MAAM,2CAA2C,CAAC;AACrG,OAAO,EAAE,6BAA6B,EAAE,MAAM,yEAAyE,CAAC;AACxH,OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,mBAAmB,GACpB,M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AAK,KAAK,CAAC,SAAS,CAAC,eAAe,EAC1D,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,wDAAwD,CAAC,CAAC;IAC5E,CAAC;IACD,MAAM,QAAQ,GAAG,MAAM,iBAAiB,CAAC;QACvC,uBAAuB,EAAE,YAAY;QACrC,iBAAiB,EAAE;YACjB,yBAAyB,EAAE,0BAA0B,CAAC;gBACpD,2BAA2B,EACzB,KAAK,CAAC,aAAa,CAAC,2BAA2B;gBACjD,wBAAwB,EAAE,MAAM,CAAC,wBAAwB;aAC1D,CAAC,CAAC,wBAAwB;YAC3B,cAAc;YACd,iBAAiB,EAAE,KAAK,CAAC,aAAa,CAAC,iBAAiB;SACzD;QACD,0BAA0B,EAAE,cAAc,CAAC,sBAAsB;QACjE,cAAc,EAAE;YACd,UAAU,EAAE,MAAM;YAClB,QAAQ,EAAE,KAAK,CAAC,OAAO,CAAC,MAAM;YAC9B,cAAc,EAAE,KAAK,CAAC,cAAc;SACrC;QACD,kBAAkB,EAAE,cAAc,CAAC,iBAAiB;QACpD,MAAM;QACN,eAAe,EAAE,MAAM,CAAC,gBAAgB;KACzC,CAAC,CAAC;IACH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;QACjB,MAAM,QAAQ,CAAC,KAAK,CAAC;IACvB,CAAC;AACH,CAAC","sourcesContent":["import {\n blobContentMetadataHash,\n bytesToHex,\n CONTENT_RECORD_ENCRYPTION_SUITE,\n computeBlobAccessManifestHash,\n computeBlobContentKeyTargetHash,\n computeContentRecordNonceDomainHash,\n makeVerifiedBlobKekTargets,\n verifyWriteHeader,\n} from \"@tearleads/crypto\";\nimport type { BlobKekTargetsResponse } from \"@tearleads/validators/response\";\nimport { deriveBlobContentRecordKey } from \"../../../data/blobs/attachments/crypto\";\nimport { unwrapBlobContentKey } from \"../../../data/blobs/attachments/projection\";\nimport {\n parseBlobEncryptedBytes,\n readBlobKekTarget,\n readDocumentManifestIdentity,\n sortBlobTargets,\n} from \"../../../data/blobs/attachments/readers\";\nimport { assertBlobContentKeyBundleTargetHash } from \"../../../data/blobs/attachments/responses\";\nimport type {\n BlobEncryptedBytesHeader,\n DecryptDocumentAttachmentBlobInput,\n} from \"../../../data/blobs/attachments/types\";\nimport type { BlobBytes } from \"../../../data/blobs/blobContracts\";\nimport { importContentKeyMaterial } from \"../../../data/documents/shared/contentRecordKeys\";\nimport { assertDocumentWriterProjectionConsistent } from \"../../../data/documents/shared/projection\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport {\n asWebCryptoBytes,\n readWriteHeader,\n uniqueSortedStrings,\n} from \"../../../data/documents/shared/readers\";\nimport { readCanonicalRecord } from \"../../../data/keying/canonicalJson\";\nimport type { DocumentWriterProjectionAuthorization } from \"../../../data/keyingProjectionVerification\";\nimport {\n readRecordString,\n requireProjectionUserKeyResolver,\n resolveEventContainerPaths,\n} from \"../../../data/keyingProjectionVerification\";\n\nimport { assertAttachmentBindingVerified } from \"../verification/attachmentBindingVerification\";\nimport { assertBlobWrapScopeVerified } from \"../verification/verifiedWrapScope\";\nimport { decryptBlobChunks } from \"./blobChunkDecryption\";\n\nasync function assertBlobEncryptionMetadata(input: {\n readonly contentKeyBundle: DecryptDocumentAttachmentBlobInput[\"binding\"][\"contentKeyBundle\"];\n readonly encrypted: BlobEncryptedBytesHeader;\n readonly expectedBlobId: string;\n readonly organizationId: string;\n}): Promise<void> {\n const { contentKeyBundle, encrypted, expectedBlobId, organizationId } = input;\n if (\n encrypted.blobId !== expectedBlobId ||\n encrypted.contentRecordId !== expectedBlobId\n ) {\n throw new Error(\"Blob encrypted bytes blob id mismatch\");\n }\n if (\n encrypted.contentKeyEpoch !== contentKeyBundle.contentKeyEpoch ||\n contentKeyBundle.blobId !== expectedBlobId\n ) {\n throw new Error(\"Blob encrypted bytes content-key bundle mismatch\");\n }\n await assertBlobContentKeyBundleTargetHash(contentKeyBundle);\n\n const expectedNonceDomainHash = await computeContentRecordNonceDomainHash({\n version: 1,\n organizationId,\n objectKind: \"blob\",\n objectId: expectedBlobId,\n contentKeyEpoch: encrypted.contentKeyEpoch,\n encryptionSuite: CONTENT_RECORD_ENCRYPTION_SUITE,\n contentRecordId: encrypted.contentRecordId,\n });\n if (encrypted.nonceDomainHash !== expectedNonceDomainHash) {\n throw new Error(\"Blob encrypted bytes nonce domain mismatch\");\n }\n const expectedMetadataHash = await blobContentMetadataHash({\n blobId: expectedBlobId,\n byteLength: encrypted.byteLength,\n chunkCount: encrypted.chunkCount,\n chunkSize: encrypted.chunkSize,\n contentKeyEpoch: encrypted.contentKeyEpoch,\n });\n if (encrypted.metadataHash !== expectedMetadataHash) {\n throw new Error(\"Blob encrypted bytes metadata hash mismatch\");\n }\n}\n\nexport type AttachmentBlobDecryptionInput = Omit<\n DecryptDocumentAttachmentBlobInput,\n \"encryptedBytes\"\n> & {\n encrypted: BlobEncryptedBytesHeader;\n};\n\n/** Verifies metadata and authority; the caller must still authenticate ciphertext. */\nexport async function prepareDocumentAttachmentBlobDecryption({\n binding,\n encrypted,\n expectedDocumentId,\n expectedSlotId,\n execSql,\n resolveProjectionUserKey,\n targetSecretKey,\n stillCurrent,\n warmReferencedPrincipalPolicies,\n writerProjection,\n}: AttachmentBlobDecryptionInput): Promise<{\n contentKey: Uint8Array;\n recordKey: CryptoKey;\n organizationId: string;\n}> {\n const requiredResolveProjectionUserKey = requireProjectionUserKeyResolver(\n resolveProjectionUserKey,\n \"Document attachment blob decrypt\",\n );\n const verificationOptions = projectionVerificationOptions({\n execSql,\n stillCurrent,\n warmReferencedPrincipalPolicies,\n resolveProjectionUserKey: requiredResolveProjectionUserKey,\n });\n let documentAuthorization: DocumentWriterProjectionAuthorization | undefined;\n await assertDocumentWriterProjectionConsistent(writerProjection, {\n allowStaleContentKeyBundle: true,\n execSql,\n onVerifiedAuthorization: (authorization) => {\n documentAuthorization = authorization;\n },\n ...verificationOptions,\n });\n const { documentId, organizationId } =\n readDocumentManifestIdentity(writerProjection);\n await assertBlobEncryptionMetadata({\n contentKeyBundle: binding.contentKeyBundle,\n encrypted,\n expectedBlobId: binding.blobId,\n organizationId,\n });\n await assertAttachmentBindingVerified({\n authorization: documentAuthorization,\n binding,\n expectedDocumentId,\n expectedSlotId,\n resolveProjectionUserKey: requiredResolveProjectionUserKey,\n });\n await assertBlobWriteHeaderVerified({\n authorization: documentAuthorization,\n binding,\n encrypted,\n organizationId,\n resolveProjectionUserKey: requiredResolveProjectionUserKey,\n });\n\n if (!documentAuthorization)\n throw new Error(\"Blob document authorization is unavailable\");\n assertBlobWrapScopeVerified({\n authorization: documentAuthorization,\n binding,\n documentId,\n });\n const contentKey = await unwrapBlobContentKey({\n blobId: binding.blobId,\n contentKeyBundle: binding.contentKeyBundle,\n documentId,\n encrypted,\n execSql,\n expectedBindingId: binding.bindingId,\n secretKey: targetSecretKey,\n ...verificationOptions,\n writerProjection,\n });\n const contentKeyMaterial = await importContentKeyMaterial(contentKey);\n const recordKey = await deriveBlobContentRecordKey({\n blobId: binding.blobId,\n contentKeyEpoch: encrypted.contentKeyEpoch,\n contentKeyMaterial,\n contentRecordId: encrypted.contentRecordId,\n organizationId,\n usage: \"decrypt\",\n });\n return { contentKey, recordKey, organizationId };\n}\n\nasync function decryptDocumentAttachmentBlobWithKey(\n input: DecryptDocumentAttachmentBlobInput,\n): Promise<{ bytes: BlobBytes; contentKey: Uint8Array }> {\n const encrypted = parseBlobEncryptedBytes(input.encryptedBytes);\n const context = await prepareDocumentAttachmentBlobDecryption({\n ...input,\n encrypted,\n });\n const header = readWriteHeader(\n input.binding.writeHeader,\n \"Attachment blob write header\",\n );\n const ciphertextHash = bytesToHex(\n new Uint8Array(\n await crypto.subtle.digest(\n \"SHA-256\",\n asWebCryptoBytes(input.encryptedBytes),\n ),\n ),\n );\n if (header.ciphertextHash !== ciphertextHash)\n throw new Error(\"Attachment blob write header does not match ciphertext\");\n const bytes = await decryptBlobChunks({\n ...context,\n encrypted,\n expectedBlobId: input.binding.blobId,\n });\n return { bytes, contentKey: context.contentKey };\n}\n\nexport async function decryptDocumentAttachmentBlob(\n input: DecryptDocumentAttachmentBlobInput,\n): Promise<BlobBytes> {\n return (await decryptDocumentAttachmentBlobWithKey(input)).bytes;\n}\n\nfunction assertStringSetEquals(input: {\n readonly actual: readonly string[];\n readonly expected: readonly string[];\n readonly label: string;\n}): void {\n const actual = uniqueSortedStrings(input.actual);\n const expected = uniqueSortedStrings(input.expected);\n if (\n actual.length !== expected.length ||\n actual.some((value, index) => value !== expected[index])\n ) {\n throw new Error(`${input.label} is inconsistent`);\n }\n}\n\nasync function verifiedBlobKekTargetsForBinding(input: {\n readonly binding: DecryptDocumentAttachmentBlobInput[\"binding\"];\n readonly requireBindingMembership: boolean;\n readonly projection: BlobKekTargetsResponse | undefined;\n}) {\n const { binding, projection } = input;\n if (!projection) {\n throw new Error(\"Attachment binding lacks blob KEK verification material\");\n }\n const targets = sortBlobTargets(\n projection.targets.map((target, index) =>\n readBlobKekTarget(target, `Attachment blob KEK target[${index}]`),\n ),\n );\n const targetHash = await computeBlobContentKeyTargetHash(targets);\n if (\n targetHash !== projection.blobKeyTargetHash ||\n projection.blobId !== binding.blobId\n ) {\n throw new Error(\"Attachment blob KEK target hash is inconsistent\");\n }\n if (\n input.requireBindingMembership &&\n (!projection.activeBindingIds.includes(binding.bindingId) ||\n !targets.some(\n (target) =>\n target.bindingId === binding.bindingId &&\n target.documentId === attachmentBindingDocumentId(binding),\n ))\n ) {\n throw new Error(\"Attachment binding is absent from blob KEK targets\");\n }\n assertStringSetEquals({\n actual: projection.linkedContainerManifestHashes,\n expected: targets.map((target) => target.containerManifestHash),\n label: \"Attachment blob container manifests\",\n });\n assertStringSetEquals({\n actual: projection.linkedContainerKeyEpochIds,\n expected: targets.map((target) => target.containerKeyEpochId),\n label: \"Attachment blob container KEKs\",\n });\n const accessManifestHash = await computeBlobAccessManifestHash({\n version: 1,\n blobId: projection.blobId,\n organizationId: projection.organizationId,\n activeBindingIds: projection.activeBindingIds,\n documentManifestHashes: projection.documentManifestHashes,\n linkedContainerManifestHashes: projection.linkedContainerManifestHashes,\n linkedContainerKeyEpochIds: projection.linkedContainerKeyEpochIds,\n blobKeyTargetHash: projection.blobKeyTargetHash,\n });\n if (accessManifestHash !== projection.blobAccessManifestHash) {\n throw new Error(\"Attachment blob access manifest hash is inconsistent\");\n }\n return makeVerifiedBlobKekTargets({ ...projection, targets });\n}\n\nfunction attachmentBindingDocumentId(\n binding: DecryptDocumentAttachmentBlobInput[\"binding\"],\n): string {\n if (!binding.bindingEvent) {\n throw new Error(\"Attachment binding lacks a signed event\");\n }\n return readRecordString(\n readCanonicalRecord(\n binding.bindingEvent.body,\n \"Attachment binding event body\",\n ),\n \"documentId\",\n \"Attachment binding event body\",\n );\n}\n\n/**\n * The listing omits the write's target set when its hash equals the current\n * set's, so refill it from `blobKekTargets`; verification re-hashes it against\n * the write authorization and the signed header. Any other omission fails.\n */\nfunction writeAuthorizationWithTargets(\n binding: DecryptDocumentAttachmentBlobInput[\"binding\"],\n): BlobKekTargetsResponse | undefined {\n const { blobKekTargets, writeAuthorization } = binding;\n if (!writeAuthorization) return undefined;\n if (writeAuthorization.targets)\n return { ...writeAuthorization, targets: writeAuthorization.targets };\n if (\n !blobKekTargets ||\n writeAuthorization.blobKeyTargetHash !== blobKekTargets.blobKeyTargetHash\n )\n throw new Error(\"Attachment blob write authorization lacks its targets\");\n return { ...writeAuthorization, targets: blobKekTargets.targets };\n}\n\nasync function assertBlobWriteHeaderVerified(input: {\n readonly authorization: DocumentWriterProjectionAuthorization | undefined;\n readonly binding: DecryptDocumentAttachmentBlobInput[\"binding\"];\n readonly encrypted: BlobEncryptedBytesHeader;\n readonly organizationId: string;\n readonly resolveProjectionUserKey: ReturnType<\n typeof requireProjectionUserKeyResolver\n >;\n}): Promise<void> {\n if (!input.authorization || !input.binding.writeHeader) {\n throw new Error(\"Attachment blob lacks verified write authority\");\n }\n const header = readWriteHeader(\n input.binding.writeHeader,\n \"Attachment blob write header\",\n );\n const writer = await input.resolveProjectionUserKey(header.writerUserId);\n if (!writer) {\n throw new Error(\"Attachment blob writer identity is unavailable\");\n }\n await verifiedBlobKekTargetsForBinding({\n binding: input.binding,\n projection: input.binding.blobKekTargets,\n requireBindingMembership: true,\n });\n const blobKekTargets = await verifiedBlobKekTargetsForBinding({\n binding: input.binding,\n projection: writeAuthorizationWithTargets(input.binding),\n // The signed binding proves which slot exposes the blob now. Writer\n // authorization describes the older target set committed when the bytes\n // were written, so a later valid binding need not appear in that set.\n requireBindingMembership: false,\n });\n if (\n header.metadataHash !== input.encrypted.metadataHash ||\n header.contentKeyEpoch !== input.encrypted.contentKeyEpoch ||\n header.contentRecordId !== input.encrypted.contentRecordId ||\n header.nonceDomainHash !== input.encrypted.nonceDomainHash\n ) {\n throw new Error(\"Attachment blob write header does not match ciphertext\");\n }\n const verified = await verifyWriteHeader({\n authorizationMembership: \"referenced\",\n blobAuthorization: {\n authorizingContainerPaths: resolveEventContainerPaths({\n containerPathByManifestHash:\n input.authorization.containerPathByManifestHash,\n dependencyManifestHashes: header.dependencyManifestHashes,\n }).dependencyContainerPaths,\n blobKekTargets,\n principalPolicies: input.authorization.principalPolicies,\n },\n expectedAccessManifestHash: blobKekTargets.blobAccessManifestHash,\n expectedObject: {\n objectKind: \"blob\",\n objectId: input.binding.blobId,\n organizationId: input.organizationId,\n },\n expectedTargetHash: blobKekTargets.blobKeyTargetHash,\n header,\n writerPublicKey: writer.signingPublicKey,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n}\n"]}