@tearleads/client-sdk 0.1.239 → 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.
- package/data/documents/shared/sync/syncResponseAuthorization.js +12 -1
- package/data/documents/shared/sync/syncResponseAuthorization.js.map +1 -1
- package/data/documents/shared/sync/syncResponses.js +2 -2
- package/data/documents/shared/sync/syncResponses.js.map +1 -1
- package/data/documents/shared/types.d.ts +5 -1
- package/data/documents/shared/types.js.map +1 -1
- package/data/persistence/documents/documentAttachmentPresence.js +44 -0
- package/data/persistence/documents/documentAttachmentPresence.js.map +1 -0
- package/internal/api-client/ApiClient.d.ts +7 -7
- package/internal/api-client/client/apiClientContext.d.ts +1 -1
- package/internal/api-client/client/blobs.d.ts +1 -1
- package/internal/api-client/client/documents.d.ts +6 -6
- package/internal/validators/operation/attachments.d.ts +2 -2
- package/internal/validators/operation/containerMutations.d.ts +16 -16
- package/internal/validators/operation/documentMutations.d.ts +20 -20
- package/internal/validators/operation/documentSync.d.ts +24 -24
- package/internal/validators/response/blob.d.ts +6 -6
- package/internal/validators/response/blob.js +12 -2
- package/internal/validators/response/blob.js.map +1 -1
- package/internal/validators/response/containerMutationError.d.ts +2 -2
- package/internal/validators/response/documentMutationError.d.ts +3 -2
- package/internal/validators/response/documentMutationError.js +5 -0
- package/internal/validators/response/documentMutationError.js.map +1 -1
- package/internal/validators/response/documentSyncSchema.d.ts +48 -48
- package/internal/validators/response/documentSyncSchema.js +1 -1
- package/internal/validators/response/documentSyncSchema.js.map +1 -1
- package/package.json +1 -1
- package/workflows/blobs/hydration/decrypt.js +17 -1
- package/workflows/blobs/hydration/decrypt.js.map +1 -1
- package/workflows/documents/linkSet/linkSetBlobRewraps.d.ts +10 -4
- package/workflows/documents/linkSet/linkSetBlobRewraps.js +23 -11
- package/workflows/documents/linkSet/linkSetBlobRewraps.js.map +1 -1
- package/workflows/documents/linkSet/linkSetLegMachine.js +74 -0
- package/workflows/documents/linkSet/linkSetLegMachine.js.map +1 -0
- package/workflows/documents/linkSet/linkSetRemote.d.ts +4 -4
- package/workflows/documents/linkSet/linkSetRemote.js +96 -52
- package/workflows/documents/linkSet/linkSetRemote.js.map +1 -1
|
@@ -1,6 +1,17 @@
|
|
|
1
1
|
import { computeDocumentContentKeyTargetHash, makeVerifiedDocumentKekTargets, } from "../../../../internal/crypto/index.js";
|
|
2
2
|
import { resolveEventContainerPaths } from "../../../keyingProjectionVerification/index.js";
|
|
3
|
-
import { sortDocumentTargets } from "../readers.js";
|
|
3
|
+
import { sortDocumentTargets, targetEnvelopeReference } from "../readers.js";
|
|
4
|
+
/**
|
|
5
|
+
* The update's authorization target set. The server omits it when the signed
|
|
6
|
+
* header commits to the target hash this sync expected, which is the set the
|
|
7
|
+
* plan holds, so refill it from the plan. `documentWriteAuthorizationForHeader`
|
|
8
|
+
* re-hashes it against the signed `targetHash`, so an omission for any other
|
|
9
|
+
* hash fails closed.
|
|
10
|
+
*/
|
|
11
|
+
export function authorizationTargetsForUpdate(update, plan) {
|
|
12
|
+
return (update.authorizationTargets ??
|
|
13
|
+
plan.sourceContentKeyBundle.targets.map(targetEnvelopeReference));
|
|
14
|
+
}
|
|
4
15
|
export async function documentWriteAuthorizationForHeader(input) {
|
|
5
16
|
const source = input.plan.documentWriterAuthorization;
|
|
6
17
|
if (!source) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncResponseAuthorization.js","sourceRoot":"","sources":["syncResponseAuthorization.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mCAAmC,EAEnC,8BAA8B,GAC/B,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"syncResponseAuthorization.js","sourceRoot":"","sources":["syncResponseAuthorization.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mCAAmC,EAEnC,8BAA8B,GAC/B,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EAAE,0BAA0B,EAAE,MAAM,uCAAuC,CAAC;AACnF,OAAO,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QACvC,0BAA0B,EAAE,OAAO,CAAC,GAAG,CACrC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,mBAAmB,CACvC;QACD,6BAA6B,EAAE,OAAO,CAAC,GAAG,CACxC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,qBAAqB,CACzC;QACD,mBAAmB,EAAE,KAAK,CAAC,YAAY;QACvC,OAAO;KACR,CAAC,CAAC;IACH,OAAO;QACL,yBAAyB;QACzB,kBAAkB;QAClB,gBAAgB;QAChB,iBAAiB,EAAE,MAAM,CAAC,iBAAiB;KAC5C,CAAC;AACJ,CAAC","sourcesContent":["import {\n computeDocumentContentKeyTargetHash,\n type DocumentContentKeyTarget,\n makeVerifiedDocumentKekTargets,\n} from \"@tearleads/crypto\";\nimport type {\n DocumentContentKeyBundleResponse,\n DocumentSyncResponse,\n} from \"@tearleads/validators/response\";\nimport { resolveEventContainerPaths } from \"../../../keyingProjectionVerification\";\nimport { sortDocumentTargets, targetEnvelopeReference } from \"../readers\";\nimport type { DocumentSyncPlan } from \"./documentSyncTypes\";\n\n/**\n * The update's authorization target set. The server omits it when the signed\n * header commits to the target hash this sync expected, which is the set the\n * plan holds, so refill it from the plan. `documentWriteAuthorizationForHeader`\n * re-hashes it against the signed `targetHash`, so an omission for any other\n * hash fails closed.\n */\nexport function authorizationTargetsForUpdate(\n update: Pick<DocumentSyncResponse[\"updates\"][number], \"authorizationTargets\">,\n plan: Pick<DocumentSyncPlan, \"sourceContentKeyBundle\">,\n): DocumentContentKeyTarget[] {\n return (\n update.authorizationTargets ??\n plan.sourceContentKeyBundle.targets.map(targetEnvelopeReference)\n );\n}\n\nexport async function documentWriteAuthorizationForHeader(input: {\n readonly allowMissingAuthorization: boolean;\n readonly dependencyManifestHashes: readonly string[];\n readonly authorizationTargets: readonly DocumentContentKeyTarget[];\n readonly contentKeyBundle: DocumentContentKeyBundleResponse;\n readonly manifestHash: string;\n readonly plan: Pick<\n DocumentSyncPlan,\n \"documentId\" | \"organizationId\" | \"documentWriterAuthorization\"\n >;\n readonly targetHash: string;\n}) {\n const source = input.plan.documentWriterAuthorization;\n if (!source) {\n if (input.allowMissingAuthorization) {\n return null;\n }\n throw new Error(\n \"Document sync response lacks verified writer-authorization material\",\n );\n }\n const documentManifest = source.documentManifestByHash.get(\n input.manifestHash,\n );\n if (!documentManifest) {\n throw new Error(\n \"Document sync response write manifest is not in verified history\",\n );\n }\n if (input.contentKeyBundle.documentId !== input.plan.documentId) {\n throw new Error(\n \"Document sync response content-key bundle belongs to another document\",\n );\n }\n\n const targets = sortDocumentTargets(input.authorizationTargets);\n if (\n (await computeDocumentContentKeyTargetHash(targets)) !== input.targetHash\n ) {\n throw new Error(\"Document sync response write targets are not canonical\");\n }\n const linkedContainerIds = new Set(documentManifest.state.linkedContainerIds);\n if (\n targets.length !== linkedContainerIds.size ||\n targets.some((target) => !linkedContainerIds.has(target.containerId))\n ) {\n throw new Error(\n \"Document sync response write targets do not match the signed link set\",\n );\n }\n\n const { dependencyContainerPaths } = resolveEventContainerPaths({\n containerPathByManifestHash: source.containerPathByManifestHash,\n dependencyManifestHashes: input.dependencyManifestHashes,\n });\n // A writer needs one committed target, and can be unable to read another\n // linked container. Validate the targets that are cited without inventing\n // paths for uncited targets or dropping signed ancestor evidence.\n for (const target of targets) {\n const path = dependencyContainerPaths.find(\n (candidate) =>\n candidate.at(-1)?.manifestHash === target.containerManifestHash,\n );\n if (!path) continue;\n const leaf = path.at(-1);\n if (\n !leaf ||\n leaf.state.containerId !== target.containerId ||\n leaf.state.organizationId !== input.plan.organizationId ||\n leaf.state.containerKeyEpochId !== target.containerKeyEpochId\n ) {\n throw new Error(\n \"Document sync response write target lacks a verified container path\",\n );\n }\n }\n const authorizingContainerPaths = dependencyContainerPaths;\n const documentKekTargets = makeVerifiedDocumentKekTargets({\n documentId: input.contentKeyBundle.documentId,\n documentKeyTargetHash: input.targetHash,\n linkedContainerKeyEpochIds: targets.map(\n (target) => target.containerKeyEpochId,\n ),\n linkedContainerManifestHashes: targets.map(\n (target) => target.containerManifestHash,\n ),\n linkSetManifestHash: input.manifestHash,\n targets,\n });\n return {\n authorizingContainerPaths,\n documentKekTargets,\n documentManifest,\n principalPolicies: source.principalPolicies,\n };\n}\n"]}
|
|
@@ -5,7 +5,7 @@ import { parseWalLsn } from "../../../../internal/validators/util/index.js";
|
|
|
5
5
|
import { throwKeyingVerificationShapeFailure } from "../../../keyingProjectionVerification/error.js";
|
|
6
6
|
import { readRecordPositiveInteger, readRecordString, readWriteHeader, serializedPersistedDocumentState, } from "../readers.js";
|
|
7
7
|
export { submitDocumentSync } from "./syncPagination.js";
|
|
8
|
-
import { documentWriteAuthorizationForHeader } from "./syncResponseAuthorization.js";
|
|
8
|
+
import { authorizationTargetsForUpdate, documentWriteAuthorizationForHeader, } from "./syncResponseAuthorization.js";
|
|
9
9
|
// Remote-primary databases without a portable WAL position use the zero LSN
|
|
10
10
|
// as an explicit "checkpoint not tracked" sentinel. It is accepted only when
|
|
11
11
|
// the response declares that mode, letting a local record carrying a checkpoint
|
|
@@ -139,7 +139,7 @@ async function assertDocumentSyncResponseWriteHeaderSignature(input) {
|
|
|
139
139
|
}
|
|
140
140
|
const documentAuthorization = await documentWriteAuthorizationForHeader({
|
|
141
141
|
allowMissingAuthorization: isAcceptedOutgoingSyncUpdate(plan, update),
|
|
142
|
-
authorizationTargets: update
|
|
142
|
+
authorizationTargets: authorizationTargetsForUpdate(update, plan),
|
|
143
143
|
dependencyManifestHashes: header.dependencyManifestHashes,
|
|
144
144
|
contentKeyBundle: input.contentKeyBundle,
|
|
145
145
|
manifestHash: header.accessManifestHash,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncResponses.js","sourceRoot":"","sources":["syncResponses.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,+BAA+B,EAC/B,mCAAmC,EACnC,0CAA0C,EAC1C,wCAAwC,EACxC,iBAAiB,GAElB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,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AE,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 { 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,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,EACL,6BAA6B,EAC7B,mCAAmC,GACpC,MAAM,6BAA6B,CAAC;AAGrC,4EAA4E;AAC5E,6EAA6E;AAC7E,gFAAgF;AAChF,8EAA8E;AAC9E,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O,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"]}
|
|
@@ -126,10 +126,14 @@ type DocumentLinkSetMutationResult = {
|
|
|
126
126
|
readonly ok: true;
|
|
127
127
|
} | (DocumentLinkSetMutationFailure & {
|
|
128
128
|
readonly ok: false;
|
|
129
|
+
/** The host report a `reportErrors: false` request withheld. */
|
|
130
|
+
readonly report?: (() => void) | undefined;
|
|
129
131
|
});
|
|
130
132
|
export interface DocumentLinkSetMutationApi {
|
|
131
133
|
getBlobBytes(blobId: string): Promise<BlobBytesResponse | null>;
|
|
132
|
-
listDocumentAttachments(documentId: string
|
|
134
|
+
listDocumentAttachments(documentId: string, options?: {
|
|
135
|
+
readonly refresh?: boolean;
|
|
136
|
+
}): Promise<ListDocumentAttachmentsResponse | null>;
|
|
133
137
|
getContainerWriterProjection(containerId: string): Promise<ContainerWriterProjectionResponse | null>;
|
|
134
138
|
getContainerWriterProjectionResult(containerId: string, options?: DocumentSyncRequestResultOptions | undefined): Promise<{
|
|
135
139
|
readonly data: ContainerWriterProjectionResponse;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AA2BA,MAAM,CAAC,MAAM,qCAAqC,GAChD,gCAAgC,CAAC;AACnC,MAAM,CAAC,MAAM,uCAAuC,GAClD,4CAA4C,CAAC;AAC/C,MAAM,CAAC,MAAM,sDAAsD,GACjE,2DAA2D,CAAC;AAC9D,MAAM,CAAC,MAAM,kCAAkC,GAC7C,uCAAuC,CAAC;AAC1C,MAAM,CAAC,MAAM,iCAAiC,GAC5C,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,6CAA6C,CAAC,CAAC;AAC1E,MAAM,CAAC,MAAM,8BAA8B,GAAG,IAAI,GAAG,CAAC;IACpD,YAAY;IACZ,iBAAiB;IACjB,iBAAiB;IACjB,iBAAiB;IACjB,QAAQ;IACR,IAAI;IACJ,cAAc;IACd,iBAAiB;IACjB,SAAS;CACV,CAAC,CAAC;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,IAAI,WAAW,EAAE,CAAC","sourcesContent":["import type { BlobBytesResponse } from \"@tearleads/api-client\";\nimport type {\n AccessEvent,\n AccessManifest,\n DocumentContentKeyTarget,\n DocumentLinkAccessEventBody,\n DocumentLinkSetManifestState,\n DocumentUnlinkAccessEventBody,\n} from \"@tearleads/crypto\";\nimport type {\n ContainerManifestRef,\n DocumentContentKeyTargetEnvelope,\n DocumentCreateRequest,\n DocumentLinkSetMutationRequest,\n DocumentSyncRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentCreateResponse,\n DocumentLinkSetMutationResponse,\n DocumentWriterProjectionResponse,\n ListDocumentAttachmentsResponse,\n} from \"@tearleads/validators/response\";\nimport type { ContainerMutationAuthor } from \"../../containers/shared/types\";\nimport type { DocumentRecord } from \"../../persistence/documents/records\";\nimport type { DocumentSyncSubmitFailure } from \"./sync/syncSubmitFailure\";\n\nexport const DOCUMENT_ENCRYPTED_LORO_UPDATE_FORMAT =\n \"tearleads.document.loro-update\";\nexport const DOCUMENT_CONTENT_RECORD_KEY_INFO_DOMAIN =\n \"tearleads.document.content-record-key-info\";\nexport const DOCUMENT_CONTENT_RECORD_PLAINTEXT_HASH_KEY_INFO_DOMAIN =\n \"tearleads.document.content-record-plaintext-hash-key-info\";\nexport const DOCUMENT_CONTENT_RECORD_AAD_DOMAIN =\n \"tearleads.document.content-record-aad\";\nexport const DOCUMENT_CONTENT_RECORD_HKDF_SALT: Uint8Array<ArrayBuffer> =\n new TextEncoder().encode(\"tearleads.document.content-record-hkdf-salt\");\nexport const DOCUMENT_ENCRYPTED_UPDATE_KEYS = new Set([\n \"ciphertext\",\n \"contentKeyEpoch\",\n \"contentRecordId\",\n \"encryptionSuite\",\n \"format\",\n \"iv\",\n \"metadataHash\",\n \"nonceDomainHash\",\n \"version\",\n]);\nexport const TEXT_ENCODER = new TextEncoder();\n\nexport type DocumentCreateAuthor = ContainerMutationAuthor;\n\nexport interface BuildDocumentCreatePlanInput {\n author: DocumentCreateAuthor;\n containerProjection: ContainerWriterProjectionResponse;\n contentKeyEpoch?: number;\n documentId?: string;\n eventId?: string;\n signedAt?: string;\n targetEnvelopes: readonly DocumentContentKeyTargetEnvelope[];\n}\n\nexport interface DocumentCreatePlan {\n body: DocumentLinkAccessEventBody;\n documentId: string;\n event: AccessEvent;\n eventHash: string;\n manifest: AccessManifest;\n manifestHash: string;\n request: DocumentCreateRequest;\n state: DocumentLinkSetManifestState;\n targetHash: string;\n targets: DocumentContentKeyTarget[];\n}\n\nexport interface MaterializedDocumentCreatePlan {\n contentKey: Uint8Array;\n plan: DocumentCreatePlan;\n}\n\nexport interface DocumentCreateApi {\n // Lets idempotent create inspect an expected already-exists conflict.\n createDocumentResult(\n input: DocumentCreateRequest,\n options?: DocumentSyncRequestResultOptions | undefined,\n ): Promise<\n | {\n readonly data: DocumentCreateResponse;\n readonly ok: true;\n }\n | DocumentSyncSubmitFailure\n >;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n // Result-returning variant used by the create path so a terminal projection\n // fetch failure (e.g. a 402 billing block or a 403 after access revocation)\n // can be persisted to the write queue instead of collapsing to a silent\n // null.\n getContainerWriterProjectionResult(\n containerId: string,\n options?: DocumentSyncRequestResultOptions | undefined,\n ): Promise<\n | {\n readonly data: ContainerWriterProjectionResponse;\n readonly ok: true;\n }\n | DocumentSyncSubmitFailure\n >;\n // Needed to adopt an existing remote document on a create conflict: the\n // committed manifest, content-key bundle and KEK targets are refetched here\n // (the create response that carried them was lost).\n getDocumentWriterProjection(\n documentId: string,\n ): Promise<DocumentWriterProjectionResponse | null>;\n evictContainerWriterProjection(containerId: string): void;\n primeDocumentWriterProjection(\n documentId: string,\n projection: DocumentWriterProjectionResponse,\n ): void;\n}\n\nexport interface CreateRemoteDocumentResult {\n contentKey: Uint8Array;\n /** The requested `deferredSeedUpdate`, signed but unsent, for a bind. */\n deferredSeed?: DocumentSyncRequest | undefined;\n documentId: string;\n persistedState: PersistedDocumentCreateState;\n // `plan` and `response` are absent when the result was adopted from an\n // existing remote document on a create conflict: there is no fresh create\n // response, and the local plan does not match the committed manifest (the\n // first attempt used a different content key). Consumers read only\n // documentId/writerProjection/persistedState.\n plan?: DocumentCreatePlan | undefined;\n response?: DocumentCreateResponse | undefined;\n writerProjection: DocumentWriterProjectionResponse;\n}\n\nexport type DocumentLinkSetMutationOperation = \"link\" | \"unlink\";\nexport type DocumentLinkSetMutationBody =\n | DocumentLinkAccessEventBody\n | DocumentUnlinkAccessEventBody;\n\nexport interface DocumentLinkSetTargetState {\n readonly currentTargets: readonly DocumentContentKeyTarget[];\n readonly linkedContainerIds: readonly string[];\n readonly target: DocumentContentKeyTarget;\n readonly targets: readonly DocumentContentKeyTarget[];\n}\n\nexport interface BuildDocumentLinkSetMutationPlanInput {\n blobRewraps: DocumentLinkAccessEventBody[\"blobRewraps\"];\n author: DocumentCreateAuthor;\n contentKeyEpoch: number;\n eventId?: string | undefined;\n operation: DocumentLinkSetMutationOperation;\n signedAt?: string | undefined;\n targetContainerProjection: ContainerWriterProjectionResponse;\n targetEnvelopes: readonly DocumentContentKeyTargetEnvelope[];\n writerProjection: DocumentWriterProjectionResponse;\n}\n\nexport interface DocumentLinkSetMutationPlan {\n body: DocumentLinkSetMutationBody;\n contentKeyEpoch: number;\n documentId: string;\n event: AccessEvent;\n eventHash: string;\n manifest: AccessManifest;\n manifestHash: string;\n operation: DocumentLinkSetMutationOperation;\n request: DocumentLinkSetMutationRequest;\n state: DocumentLinkSetManifestState;\n targetHash: string;\n targets: DocumentContentKeyTarget[];\n}\n\nexport interface MaterializedDocumentLinkSetMutationPlan {\n contentKey: Uint8Array;\n contentKeyRotated: boolean;\n plan: DocumentLinkSetMutationPlan;\n}\n\nexport interface DocumentLinkSetEventPlan {\n authorizingContainerPathRefs: ContainerManifestRef[][];\n body: DocumentLinkSetMutationBody;\n event: AccessEvent;\n eventHash: string;\n}\n\n/**\n * What a failed link-set mutation could tell the caller: the HTTP status (or\n * null for network/local failures) and a short message. Threaded up to the\n * move-intent queue so a permission failure reads as one, instead of the\n * generic \"rejected or unavailable\".\n */\nexport type DocumentLinkSetMutationFailure = Pick<\n DocumentSyncSubmitFailure,\n \"code\" | \"message\" | \"status\"\n>;\n\nexport type DocumentLinkSetFailureHandler = (\n failure: DocumentLinkSetMutationFailure,\n) => void;\n\n/**\n * `prove` pulls and verifies the document's full history. `reuse` returns the\n * store's last completed proof while the same local document still sits at\n * that proof's version vector, and proves otherwise; only a caller the server\n * re-checks (an unlink's rotation baseline) may reuse.\n */\nexport type DocumentRotationProofMode = \"prove\" | \"reuse\";\n\ntype DocumentLinkSetMutationResult =\n | { readonly data: DocumentLinkSetMutationResponse; readonly ok: true }\n | (DocumentLinkSetMutationFailure & { readonly ok: false });\n\nexport interface DocumentLinkSetMutationApi {\n getBlobBytes(blobId: string): Promise<BlobBytesResponse | null>;\n listDocumentAttachments(\n documentId: string,\n ): Promise<ListDocumentAttachmentsResponse | null>;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n getContainerWriterProjectionResult(\n containerId: string,\n options?: DocumentSyncRequestResultOptions | undefined,\n ): Promise<\n | {\n readonly data: ContainerWriterProjectionResponse;\n readonly ok: true;\n }\n | DocumentSyncSubmitFailure\n >;\n getDocumentWriterProjection(\n documentId: string,\n ): Promise<DocumentWriterProjectionResponse | null>;\n getDocumentWriterProjectionResult(\n documentId: string,\n options?: DocumentSyncRequestResultOptions | undefined,\n ): Promise<\n | {\n readonly data: DocumentWriterProjectionResponse;\n readonly ok: true;\n }\n | DocumentSyncSubmitFailure\n >;\n primeDocumentWriterProjection(\n documentId: string,\n projection: DocumentWriterProjectionResponse,\n ): void;\n linkDocumentResult(\n documentId: string,\n input: DocumentLinkSetMutationRequest,\n options?: DocumentSyncRequestResultOptions,\n ): Promise<DocumentLinkSetMutationResult>;\n unlinkDocumentResult(\n documentId: string,\n input: DocumentLinkSetMutationRequest,\n options?: DocumentSyncRequestResultOptions,\n ): Promise<DocumentLinkSetMutationResult>;\n}\n\nexport interface RelinkRemoteDocumentResult {\n contentKey: Uint8Array;\n contentKeyRotated: boolean;\n documentId: string;\n linkedContainerIds: readonly string[];\n persistedState: PersistedDocumentCreateState;\n plan: DocumentLinkSetMutationPlan;\n response: DocumentLinkSetMutationResponse;\n}\n\nexport interface DocumentSyncRequestResultOptions {\n readonly expectedPaymentRequiredOrganizationId?: string | undefined;\n readonly reportErrors?: boolean | undefined;\n}\n\nexport type DocumentWriterPublicKeyResolver = (input: {\n writerSigningKeyFingerprint: string;\n writerUserId: string;\n}) => Promise<Uint8Array | null>;\n\nexport type PersistedDocumentCreateState = Pick<\n DocumentRecord,\n | \"documentId\"\n | \"contentKeyBundle\"\n | \"documentKekTargets\"\n | \"documentManifestBundle\"\n>;\n\nexport type PersistedDocumentSyncState = PersistedDocumentCreateState;\n\nexport interface UnwrappedContainerKek {\n containerId: string;\n /**\n * Null for keyring-recovered historical keys, which carry key material and\n * the epoch id committing to it but no epoch record to hash.\n *\n * Such a key still satisfies a parent wrap: the epoch-record fingerprint is\n * a selector for choosing among envelopes, not the security boundary, so a\n * null hash falls back to selecting on the epoch id while AEAD authenticates\n * (see `containerKekPath.ts`). That is what lets a descendant pinned to a\n * rotated parent be opened rather than stranded.\n */\n keyEpochHash: string | null;\n keyMaterial: Uint8Array;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AA2BA,MAAM,CAAC,MAAM,qCAAqC,GAChD,gCAAgC,CAAC;AACnC,MAAM,CAAC,MAAM,uCAAuC,GAClD,4CAA4C,CAAC;AAC/C,MAAM,CAAC,MAAM,sDAAsD,GACjE,2DAA2D,CAAC;AAC9D,MAAM,CAAC,MAAM,kCAAkC,GAC7C,uCAAuC,CAAC;AAC1C,MAAM,CAAC,MAAM,iCAAiC,GAC5C,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,6CAA6C,CAAC,CAAC;AAC1E,MAAM,CAAC,MAAM,8BAA8B,GAAG,IAAI,GAAG,CAAC;IACpD,YAAY;IACZ,iBAAiB;IACjB,iBAAiB;IACjB,iBAAiB;IACjB,QAAQ;IACR,IAAI;IACJ,cAAc;IACd,iBAAiB;IACjB,SAAS;CACV,CAAC,CAAC;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,IAAI,WAAW,EAAE,CAAC","sourcesContent":["import type { BlobBytesResponse } from \"@tearleads/api-client\";\nimport type {\n AccessEvent,\n AccessManifest,\n DocumentContentKeyTarget,\n DocumentLinkAccessEventBody,\n DocumentLinkSetManifestState,\n DocumentUnlinkAccessEventBody,\n} from \"@tearleads/crypto\";\nimport type {\n ContainerManifestRef,\n DocumentContentKeyTargetEnvelope,\n DocumentCreateRequest,\n DocumentLinkSetMutationRequest,\n DocumentSyncRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentCreateResponse,\n DocumentLinkSetMutationResponse,\n DocumentWriterProjectionResponse,\n ListDocumentAttachmentsResponse,\n} from \"@tearleads/validators/response\";\nimport type { ContainerMutationAuthor } from \"../../containers/shared/types\";\nimport type { DocumentRecord } from \"../../persistence/documents/records\";\nimport type { DocumentSyncSubmitFailure } from \"./sync/syncSubmitFailure\";\n\nexport const DOCUMENT_ENCRYPTED_LORO_UPDATE_FORMAT =\n \"tearleads.document.loro-update\";\nexport const DOCUMENT_CONTENT_RECORD_KEY_INFO_DOMAIN =\n \"tearleads.document.content-record-key-info\";\nexport const DOCUMENT_CONTENT_RECORD_PLAINTEXT_HASH_KEY_INFO_DOMAIN =\n \"tearleads.document.content-record-plaintext-hash-key-info\";\nexport const DOCUMENT_CONTENT_RECORD_AAD_DOMAIN =\n \"tearleads.document.content-record-aad\";\nexport const DOCUMENT_CONTENT_RECORD_HKDF_SALT: Uint8Array<ArrayBuffer> =\n new TextEncoder().encode(\"tearleads.document.content-record-hkdf-salt\");\nexport const DOCUMENT_ENCRYPTED_UPDATE_KEYS = new Set([\n \"ciphertext\",\n \"contentKeyEpoch\",\n \"contentRecordId\",\n \"encryptionSuite\",\n \"format\",\n \"iv\",\n \"metadataHash\",\n \"nonceDomainHash\",\n \"version\",\n]);\nexport const TEXT_ENCODER = new TextEncoder();\n\nexport type DocumentCreateAuthor = ContainerMutationAuthor;\n\nexport interface BuildDocumentCreatePlanInput {\n author: DocumentCreateAuthor;\n containerProjection: ContainerWriterProjectionResponse;\n contentKeyEpoch?: number;\n documentId?: string;\n eventId?: string;\n signedAt?: string;\n targetEnvelopes: readonly DocumentContentKeyTargetEnvelope[];\n}\n\nexport interface DocumentCreatePlan {\n body: DocumentLinkAccessEventBody;\n documentId: string;\n event: AccessEvent;\n eventHash: string;\n manifest: AccessManifest;\n manifestHash: string;\n request: DocumentCreateRequest;\n state: DocumentLinkSetManifestState;\n targetHash: string;\n targets: DocumentContentKeyTarget[];\n}\n\nexport interface MaterializedDocumentCreatePlan {\n contentKey: Uint8Array;\n plan: DocumentCreatePlan;\n}\n\nexport interface DocumentCreateApi {\n // Lets idempotent create inspect an expected already-exists conflict.\n createDocumentResult(\n input: DocumentCreateRequest,\n options?: DocumentSyncRequestResultOptions | undefined,\n ): Promise<\n | {\n readonly data: DocumentCreateResponse;\n readonly ok: true;\n }\n | DocumentSyncSubmitFailure\n >;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n // Result-returning variant used by the create path so a terminal projection\n // fetch failure (e.g. a 402 billing block or a 403 after access revocation)\n // can be persisted to the write queue instead of collapsing to a silent\n // null.\n getContainerWriterProjectionResult(\n containerId: string,\n options?: DocumentSyncRequestResultOptions | undefined,\n ): Promise<\n | {\n readonly data: ContainerWriterProjectionResponse;\n readonly ok: true;\n }\n | DocumentSyncSubmitFailure\n >;\n // Needed to adopt an existing remote document on a create conflict: the\n // committed manifest, content-key bundle and KEK targets are refetched here\n // (the create response that carried them was lost).\n getDocumentWriterProjection(\n documentId: string,\n ): Promise<DocumentWriterProjectionResponse | null>;\n evictContainerWriterProjection(containerId: string): void;\n primeDocumentWriterProjection(\n documentId: string,\n projection: DocumentWriterProjectionResponse,\n ): void;\n}\n\nexport interface CreateRemoteDocumentResult {\n contentKey: Uint8Array;\n /** The requested `deferredSeedUpdate`, signed but unsent, for a bind. */\n deferredSeed?: DocumentSyncRequest | undefined;\n documentId: string;\n persistedState: PersistedDocumentCreateState;\n // `plan` and `response` are absent when the result was adopted from an\n // existing remote document on a create conflict: there is no fresh create\n // response, and the local plan does not match the committed manifest (the\n // first attempt used a different content key). Consumers read only\n // documentId/writerProjection/persistedState.\n plan?: DocumentCreatePlan | undefined;\n response?: DocumentCreateResponse | undefined;\n writerProjection: DocumentWriterProjectionResponse;\n}\n\nexport type DocumentLinkSetMutationOperation = \"link\" | \"unlink\";\nexport type DocumentLinkSetMutationBody =\n | DocumentLinkAccessEventBody\n | DocumentUnlinkAccessEventBody;\n\nexport interface DocumentLinkSetTargetState {\n readonly currentTargets: readonly DocumentContentKeyTarget[];\n readonly linkedContainerIds: readonly string[];\n readonly target: DocumentContentKeyTarget;\n readonly targets: readonly DocumentContentKeyTarget[];\n}\n\nexport interface BuildDocumentLinkSetMutationPlanInput {\n blobRewraps: DocumentLinkAccessEventBody[\"blobRewraps\"];\n author: DocumentCreateAuthor;\n contentKeyEpoch: number;\n eventId?: string | undefined;\n operation: DocumentLinkSetMutationOperation;\n signedAt?: string | undefined;\n targetContainerProjection: ContainerWriterProjectionResponse;\n targetEnvelopes: readonly DocumentContentKeyTargetEnvelope[];\n writerProjection: DocumentWriterProjectionResponse;\n}\n\nexport interface DocumentLinkSetMutationPlan {\n body: DocumentLinkSetMutationBody;\n contentKeyEpoch: number;\n documentId: string;\n event: AccessEvent;\n eventHash: string;\n manifest: AccessManifest;\n manifestHash: string;\n operation: DocumentLinkSetMutationOperation;\n request: DocumentLinkSetMutationRequest;\n state: DocumentLinkSetManifestState;\n targetHash: string;\n targets: DocumentContentKeyTarget[];\n}\n\nexport interface MaterializedDocumentLinkSetMutationPlan {\n contentKey: Uint8Array;\n contentKeyRotated: boolean;\n plan: DocumentLinkSetMutationPlan;\n}\n\nexport interface DocumentLinkSetEventPlan {\n authorizingContainerPathRefs: ContainerManifestRef[][];\n body: DocumentLinkSetMutationBody;\n event: AccessEvent;\n eventHash: string;\n}\n\n/**\n * What a failed link-set mutation could tell the caller: the HTTP status (or\n * null for network/local failures) and a short message. Threaded up to the\n * move-intent queue so a permission failure reads as one, instead of the\n * generic \"rejected or unavailable\".\n */\nexport type DocumentLinkSetMutationFailure = Pick<\n DocumentSyncSubmitFailure,\n \"code\" | \"message\" | \"status\"\n>;\n\nexport type DocumentLinkSetFailureHandler = (\n failure: DocumentLinkSetMutationFailure,\n) => void;\n\n/**\n * `prove` pulls and verifies the document's full history. `reuse` returns the\n * store's last completed proof while the same local document still sits at\n * that proof's version vector, and proves otherwise; only a caller the server\n * re-checks (an unlink's rotation baseline) may reuse.\n */\nexport type DocumentRotationProofMode = \"prove\" | \"reuse\";\n\ntype DocumentLinkSetMutationResult =\n | { readonly data: DocumentLinkSetMutationResponse; readonly ok: true }\n | (DocumentLinkSetMutationFailure & {\n readonly ok: false;\n /** The host report a `reportErrors: false` request withheld. */\n readonly report?: (() => void) | undefined;\n });\n\nexport interface DocumentLinkSetMutationApi {\n getBlobBytes(blobId: string): Promise<BlobBytesResponse | null>;\n listDocumentAttachments(\n documentId: string,\n options?: { readonly refresh?: boolean },\n ): Promise<ListDocumentAttachmentsResponse | null>;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n getContainerWriterProjectionResult(\n containerId: string,\n options?: DocumentSyncRequestResultOptions | undefined,\n ): Promise<\n | {\n readonly data: ContainerWriterProjectionResponse;\n readonly ok: true;\n }\n | DocumentSyncSubmitFailure\n >;\n getDocumentWriterProjection(\n documentId: string,\n ): Promise<DocumentWriterProjectionResponse | null>;\n getDocumentWriterProjectionResult(\n documentId: string,\n options?: DocumentSyncRequestResultOptions | undefined,\n ): Promise<\n | {\n readonly data: DocumentWriterProjectionResponse;\n readonly ok: true;\n }\n | DocumentSyncSubmitFailure\n >;\n primeDocumentWriterProjection(\n documentId: string,\n projection: DocumentWriterProjectionResponse,\n ): void;\n linkDocumentResult(\n documentId: string,\n input: DocumentLinkSetMutationRequest,\n options?: DocumentSyncRequestResultOptions,\n ): Promise<DocumentLinkSetMutationResult>;\n unlinkDocumentResult(\n documentId: string,\n input: DocumentLinkSetMutationRequest,\n options?: DocumentSyncRequestResultOptions,\n ): Promise<DocumentLinkSetMutationResult>;\n}\n\nexport interface RelinkRemoteDocumentResult {\n contentKey: Uint8Array;\n contentKeyRotated: boolean;\n documentId: string;\n linkedContainerIds: readonly string[];\n persistedState: PersistedDocumentCreateState;\n plan: DocumentLinkSetMutationPlan;\n response: DocumentLinkSetMutationResponse;\n}\n\nexport interface DocumentSyncRequestResultOptions {\n readonly expectedPaymentRequiredOrganizationId?: string | undefined;\n readonly reportErrors?: boolean | undefined;\n}\n\nexport type DocumentWriterPublicKeyResolver = (input: {\n writerSigningKeyFingerprint: string;\n writerUserId: string;\n}) => Promise<Uint8Array | null>;\n\nexport type PersistedDocumentCreateState = Pick<\n DocumentRecord,\n | \"documentId\"\n | \"contentKeyBundle\"\n | \"documentKekTargets\"\n | \"documentManifestBundle\"\n>;\n\nexport type PersistedDocumentSyncState = PersistedDocumentCreateState;\n\nexport interface UnwrappedContainerKek {\n containerId: string;\n /**\n * Null for keyring-recovered historical keys, which carry key material and\n * the epoch id committing to it but no epoch record to hash.\n *\n * Such a key still satisfies a parent wrap: the epoch-record fingerprint is\n * a selector for choosing among envelopes, not the security boundary, so a\n * null hash falls back to selecting on the epoch id while AEAD authenticates\n * (see `containerKekPath.ts`). That is what lets a descendant pinned to a\n * rotated parent be opened rather than stranded.\n */\n keyEpochHash: string | null;\n keyMaterial: Uint8Array;\n}\n"]}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { and, eq, inArray } from "drizzle-orm";
|
|
2
|
+
import { DOCUMENTS_APP_KIND } from "../../documents/documentConstants.js";
|
|
3
|
+
import { documentAttachmentBlobProjection, documentPendingAttachments, } from "../../sqlite/schema/documentAttachmentSchema.js";
|
|
4
|
+
import { documents } from "../../sqlite/schema/documentRecordSchema.js";
|
|
5
|
+
import { getClientSQLitePersistenceRuntime } from "../../sqlite/sqlitePersistenceRuntime.js";
|
|
6
|
+
import { ensureDocumentsSchema } from "./internal/ensureDocumentsSchema.js";
|
|
7
|
+
/**
|
|
8
|
+
* Whether this device's local view of a server document may include an active
|
|
9
|
+
* attachment binding. It is false only when the device holds the document and
|
|
10
|
+
* no attachment row names it: no held or downloaded copy, no slot detached
|
|
11
|
+
* locally whose remote detach is still queued, and no pending upload. A
|
|
12
|
+
* document the device does not hold as a `documents` record is answered true,
|
|
13
|
+
* since it has no view.
|
|
14
|
+
*
|
|
15
|
+
* Callers may skip the server's attachment listing on false, because the
|
|
16
|
+
* server re-checks the binding frontier at commit and refuses a stale view.
|
|
17
|
+
*/
|
|
18
|
+
export async function documentMayHaveAttachments(execSql, documentId) {
|
|
19
|
+
await ensureDocumentsSchema(execSql);
|
|
20
|
+
const { db } = getClientSQLitePersistenceRuntime(execSql);
|
|
21
|
+
const records = await db
|
|
22
|
+
.select({ localId: documents.localId })
|
|
23
|
+
.from(documents)
|
|
24
|
+
// `documents_app_document_idx` serves this lookup. Other app kinds (a
|
|
25
|
+
// container's metadata document) find no row and keep listing.
|
|
26
|
+
.where(and(eq(documents.appKind, DOCUMENTS_APP_KIND), eq(documents.documentId, documentId)));
|
|
27
|
+
if (records.length === 0)
|
|
28
|
+
return true;
|
|
29
|
+
const localIds = records.map((record) => record.localId);
|
|
30
|
+
const [held] = await db
|
|
31
|
+
.select({ localId: documentAttachmentBlobProjection.localId })
|
|
32
|
+
.from(documentAttachmentBlobProjection)
|
|
33
|
+
.where(inArray(documentAttachmentBlobProjection.localId, localIds))
|
|
34
|
+
.limit(1);
|
|
35
|
+
if (held)
|
|
36
|
+
return true;
|
|
37
|
+
const [pending] = await db
|
|
38
|
+
.select({ localId: documentPendingAttachments.localId })
|
|
39
|
+
.from(documentPendingAttachments)
|
|
40
|
+
.where(inArray(documentPendingAttachments.localId, localIds))
|
|
41
|
+
.limit(1);
|
|
42
|
+
return pending !== undefined;
|
|
43
|
+
}
|
|
44
|
+
//# sourceMappingURL=documentAttachmentPresence.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"documentAttachmentPresence.js","sourceRoot":"","sources":["documentAttachmentPresence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,kBAAkB,EAAE,MAAM,mCAAmC,CAAC;AACvE,OAAO,EACL,gCAAgC,EAChC,0BAA0B,GAC3B,MAAM,8CAA8C,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,MAAM,0CAA0C,CAAC;AACrE,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAE1F,OAAO,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AAEzE;;;;;;;;;;GAUG;AACH,MAAM,CAAC,KAAK,UAAU,0BAA0B,CAC9C,OAAgB,EAChB,UAAkB;IAElB,MAAM,qBAAqB,CAAC,OAAO,CAAC,CAAC;IACrC,MAAM,EAAE,EAAE,EAAE,GAAG,iCAAiC,CAAC,OAAO,CAAC,CAAC;IAC1D,MAAM,OAAO,GAAG,MAAM,EAAE;SACrB,MAAM,CAAC,EAAE,OAAO,EAAE,SAAS,CAAC,OAAO,EAAE,CAAC;SACtC,IAAI,CAAC,SAAS,CAAC;QAChB,sEAAsE;QACtE,+DAA+D;SAC9D,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,kBAAkB,CAAC,EACzC,EAAE,CAAC,SAAS,CAAC,UAAU,EAAE,UAAU,CAAC,CACrC,CACF,CAAC;IACJ,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IACtC,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IACzD,MAAM,CAAC,IAAI,CAAC,GAAG,MAAM,EAAE;SACpB,MAAM,CAAC,EAAE,OAAO,EAAE,gCAAgC,CAAC,OAAO,EAAE,CAAC;SAC7D,IAAI,CAAC,gCAAgC,CAAC;SACtC,KAAK,CAAC,OAAO,CAAC,gCAAgC,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;SAClE,KAAK,CAAC,CAAC,CAAC,CAAC;IACZ,IAAI,IAAI;QAAE,OAAO,IAAI,CAAC;IACtB,MAAM,CAAC,OAAO,CAAC,GAAG,MAAM,EAAE;SACvB,MAAM,CAAC,EAAE,OAAO,EAAE,0BAA0B,CAAC,OAAO,EAAE,CAAC;SACvD,IAAI,CAAC,0BAA0B,CAAC;SAChC,KAAK,CAAC,OAAO,CAAC,0BAA0B,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;SAC5D,KAAK,CAAC,CAAC,CAAC,CAAC;IACZ,OAAO,OAAO,KAAK,SAAS,CAAC;AAC/B,CAAC","sourcesContent":["import { and, eq, inArray } from \"drizzle-orm\";\nimport { DOCUMENTS_APP_KIND } from \"../../documents/documentConstants\";\nimport {\n documentAttachmentBlobProjection,\n documentPendingAttachments,\n} from \"../../sqlite/schema/documentAttachmentSchema\";\nimport { documents } from \"../../sqlite/schema/documentRecordSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { ensureDocumentsSchema } from \"./internal/ensureDocumentsSchema\";\n\n/**\n * Whether this device's local view of a server document may include an active\n * attachment binding. It is false only when the device holds the document and\n * no attachment row names it: no held or downloaded copy, no slot detached\n * locally whose remote detach is still queued, and no pending upload. A\n * document the device does not hold as a `documents` record is answered true,\n * since it has no view.\n *\n * Callers may skip the server's attachment listing on false, because the\n * server re-checks the binding frontier at commit and refuses a stale view.\n */\nexport async function documentMayHaveAttachments(\n execSql: ExecSql,\n documentId: string,\n): Promise<boolean> {\n await ensureDocumentsSchema(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const records = await db\n .select({ localId: documents.localId })\n .from(documents)\n // `documents_app_document_idx` serves this lookup. Other app kinds (a\n // container's metadata document) find no row and keep listing.\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n eq(documents.documentId, documentId),\n ),\n );\n if (records.length === 0) return true;\n const localIds = records.map((record) => record.localId);\n const [held] = await db\n .select({ localId: documentAttachmentBlobProjection.localId })\n .from(documentAttachmentBlobProjection)\n .where(inArray(documentAttachmentBlobProjection.localId, localIds))\n .limit(1);\n if (held) return true;\n const [pending] = await db\n .select({ localId: documentPendingAttachments.localId })\n .from(documentPendingAttachments)\n .where(inArray(documentPendingAttachments.localId, localIds))\n .limit(1);\n return pending !== undefined;\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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
1453
|
+
targets?: Record<string, unknown>[] | undefined;
|
|
1454
1454
|
};
|
|
1455
1455
|
writeHeader: Record<string, unknown>;
|
|
1456
1456
|
}[]>;
|