@tearleads/client-sdk 0.1.77 → 0.1.79
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/blob/shared → blobs/attachments}/blobEnvelopeStream.js +1 -1
- package/data/{documents/blob/shared → blobs/attachments}/blobEnvelopeStream.js.map +1 -1
- package/data/blobs/attachments/blobRecordCrypto.d.ts +26 -0
- package/data/{documents/blob/shared → blobs/attachments}/blobRecordCrypto.js +2 -2
- package/data/{documents/blob/shared → blobs/attachments}/blobSourceSnapshot.d.ts +1 -1
- package/data/{documents/blob/shared → blobs/attachments}/blobSourceSnapshot.js +2 -2
- package/data/blobs/attachments/blobSourceSnapshot.js.map +1 -0
- package/data/blobs/attachments/chunkedBlobCrypto.d.ts +17 -0
- package/data/{documents/blob/shared → blobs/attachments}/chunkedBlobCrypto.js +3 -3
- package/data/blobs/attachments/chunkedBlobCrypto.js.map +1 -0
- package/data/blobs/attachments/crypto.d.ts +3 -0
- package/data/blobs/attachments/encryptedUploadParts.js.map +1 -0
- package/data/{documents/blob/shared → blobs/attachments}/events.js +3 -3
- package/data/blobs/attachments/events.js.map +1 -0
- package/data/{documents/blob/shared → blobs/attachments}/projection.js +8 -8
- package/data/blobs/attachments/projection.js.map +1 -0
- package/data/{documents/blob/shared → blobs/attachments}/readers.js +3 -3
- package/data/blobs/attachments/readers.js.map +1 -0
- package/data/{documents/blob/shared → blobs/attachments}/responses.js +2 -2
- package/data/blobs/attachments/responses.js.map +1 -0
- package/data/{documents/blob/shared → blobs/attachments}/types.d.ts +8 -8
- package/data/blobs/attachments/types.js.map +1 -0
- package/data/{sync → documents/shared/sync}/documentSyncOutgoingBatch.d.ts +1 -1
- package/data/{sync → documents/shared/sync}/documentSyncOutgoingBatch.js +1 -1
- package/package.json +1 -1
- package/stores/documents/documentStore/attachmentUpload/attachmentSourceUpload.js +1 -2
- package/stores/documents/documentStore/attachmentUpload/attachmentSourceUpload.js.map +1 -1
- package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -1
- package/workflows/blobs/detach.js +2 -2
- package/workflows/blobs/detach.js.map +1 -1
- package/workflows/blobs/hydration/blobChunkDecryption.js +1 -1
- package/workflows/blobs/hydration/blobChunkDecryption.js.map +1 -1
- package/workflows/blobs/hydration/decrypt.d.ts +1 -1
- package/workflows/blobs/hydration/decrypt.js +4 -4
- package/workflows/blobs/hydration/decrypt.js.map +1 -1
- package/workflows/blobs/index.d.ts +3 -1
- package/workflows/blobs/index.js +3 -0
- package/workflows/blobs/index.js.map +1 -1
- package/workflows/blobs/upload/automaticMultipartUpload.js +1 -1
- package/workflows/blobs/upload/automaticMultipartUpload.js.map +1 -1
- package/workflows/blobs/upload/index.d.ts +2 -2
- package/workflows/blobs/upload/index.js +4 -4
- package/workflows/blobs/upload/index.js.map +1 -1
- package/workflows/blobs/upload/multipartFirstParts.js.map +1 -1
- package/workflows/blobs/upload/multipartStageFailures.js.map +1 -1
- package/workflows/blobs/upload/multipartStageResolution.js.map +1 -1
- package/workflows/blobs/upload/multipartUpload.js.map +1 -1
- package/workflows/blobs/verification/attachmentBindingVerification.js.map +1 -1
- package/workflows/blobs/verification/attachmentKeyAuthenticator.js +1 -1
- package/workflows/blobs/verification/attachmentKeyAuthenticator.js.map +1 -1
- package/workflows/blobs/verification/retainedAttachmentVerification.js +1 -1
- package/workflows/blobs/verification/retainedAttachmentVerification.js.map +1 -1
- package/workflows/blobs/verification/writerProjection.js +1 -1
- package/workflows/blobs/verification/writerProjection.js.map +1 -1
- package/workflows/documents/index.d.ts +1 -1
- package/workflows/documents/index.js +1 -1
- package/workflows/documents/index.js.map +1 -1
- package/workflows/documents/sync/readOnlySync.js +1 -1
- package/workflows/documents/sync/readOnlySync.js.map +1 -1
- package/workflows/documents/sync/syncAttemptPlanning.js +1 -1
- package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -1
- package/workflows/documents/syncPlan/syncPlanMaterial.js +1 -1
- package/workflows/documents/syncPlan/syncPlanMaterial.js.map +1 -1
- package/workflows/documents/syncPlan/syncPlanRequestBounds.js +1 -1
- package/workflows/documents/syncPlan/syncPlanRequestBounds.js.map +1 -1
- package/data/documents/blob/shared/blobSourceSnapshot.js.map +0 -1
- package/data/documents/blob/shared/chunkedBlobCrypto.js.map +0 -1
- package/data/documents/blob/shared/encryptedUploadParts.js.map +0 -1
- package/data/documents/blob/shared/events.js.map +0 -1
- package/data/documents/blob/shared/projection.js.map +0 -1
- package/data/documents/blob/shared/readers.js.map +0 -1
- package/data/documents/blob/shared/responses.js.map +0 -1
- package/data/documents/blob/shared/types.js.map +0 -1
- /package/data/{documents/blob/shared → blobs/attachments}/blobRecordCrypto.js.map +0 -0
- /package/data/{documents/blob/shared → blobs/attachments}/crypto.js +0 -0
- /package/data/{documents/blob/shared → blobs/attachments}/crypto.js.map +0 -0
- /package/data/{documents/blob/shared → blobs/attachments}/encryptedUploadParts.js +0 -0
- /package/data/{documents/blob/shared → blobs/attachments}/types.js +0 -0
- /package/data/{sync → documents/shared/sync}/documentSyncOutgoingBatch.js.map +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncPlanMaterial.js","sourceRoot":"","sources":["syncPlanMaterial.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,kBAAkB,EAClB,qBAAqB,EACrB,sBAAsB,EACtB,mBAAmB,GACpB,MAAM,iBAAiB,CAAC;AAMzB,OAAO,EAAE,sCAAsC,EAAE,MAAM,gCAAgC,CAAC;AACxF,OAAO,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAC;AACjF,OAAO,EAAE,6BAA6B,EAAE,MAAM,kEAAkE,CAAC;AACjH,OAAO,EACL,wCAAwC,EACxC,4BAA4B,EAC5B,oCAAoC,EACpC,mCAAmC,EACnC,mCAAmC,EACnC,+BAA+B,EAC/B,kCAAkC,GACnC,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAAE,sCAAsC,EAAE,MAAM,wCAAwC,CAAC;AAOhG,OAAO,EAAE,6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UAAU;QAC5B,QAAQ,EAAE,KAAK,CAAC,QAAQ;KACzB,CAAC,CAAC;IACH,OAAO,oCAAoC,CAAC;QAC1C,QAAQ;QACR,QAAQ;QACR,mBAAmB;QACnB,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;KACzC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n VerifiedContainerAccessManifest,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport {\n emptyVersionVector,\n getImportBlobMetadata,\n satisfiesVersionVector,\n versionVectorsEqual,\n} from \"@tearleads/loro\";\nimport type {\n DocumentCreateResponse,\n DocumentSyncResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { documentKekTargetsFromContentKeyBundle } from \"@tearleads/validators/response\";\nimport { createPendingUpdateFields } from \"../../../data/documents/documentSync\";\nimport { assertDocumentKekPathsCurrent } from \"../../../data/documents/shared/containerKek/containerKekCurrency\";\nimport {\n assertDocumentWriterProjectionConsistent,\n authorizingContainerPathRefs,\n buildRotatedDocumentContentKeyBundle,\n ContainerKekHistoryUnavailableError,\n collectContainerKeksForDocumentSync,\n DocumentHistoryUnavailableError,\n unwrapDocumentContentKeyFromBundle,\n} from \"../../../data/documents/shared/projection\";\nimport { assertDocumentManifestBundleConsistent } from \"../../../data/documents/shared/readers\";\nimport type {\n BuildDocumentSyncPlanInput,\n DocumentCreateAuthor,\n MaterializedDocumentSyncPlan,\n ProjectionVerificationOptions,\n} from \"../../../data/documents/shared/types\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/types\";\nimport type { DocumentWriterProjectionAuthorization } from \"../../../data/keyingProjectionVerification\";\nimport type { PendingUpdateRecord } from \"../../../data/sqlite/documentPersistence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { selectDocumentSyncOutgoingBatch } from \"../../../data/sync/documentSyncOutgoingBatch\";\nimport {\n type DocumentSyncTraceEmitter,\n traceCheckpointRegeneration,\n traceHealBlocked,\n traceHealPlanned,\n traceStaleBundle,\n traceStaleRead,\n} from \"../sync/syncTrace\";\nimport { prepareDocumentOutgoingUpdates } from \"./syncContentKeys\";\nimport { buildDocumentSyncPlan } from \"./syncPlanIdentity\";\nimport { finalizeMaterializedDocumentSyncPlan } from \"./syncPlanProjection\";\n\n/**\n * Builds the rotation baseline that anchors a stale-bundle heal: a full\n * history snapshot of the local document, re-encrypted under the fresh\n * content key so every current member (including post-rotation newcomers)\n * has an efficient current-epoch redirect. Predecessor KEKs remain the\n * correctness path when no covering baseline exists.\n */\nasync function buildStaleRecoveryBaselinePendingUpdate(\n buildRotationSnapshot: (() => Promise<Uint8Array | null>) | undefined,\n): Promise<PendingUpdateRecord> {\n const snapshot = buildRotationSnapshot ? await buildRotationSnapshot() : null;\n if (!snapshot) {\n throw new Error(\n \"Document content-key bundle is stale and no rotation snapshot is available to heal it\",\n );\n }\n const metadata = getImportBlobMetadata(snapshot);\n if (\n metadata.mode !== \"snapshot\" ||\n !versionVectorsEqual(\n metadata.partialStartVersionVector,\n emptyVersionVector(),\n )\n ) {\n throw new Error(\n \"Document stale-bundle recovery requires a full-history rotation snapshot\",\n );\n }\n const pendingFields = createPendingUpdateFields(\n snapshot,\n metadata.partialEndVersionVector,\n );\n if (!pendingFields) {\n throw new Error(\"Document stale-bundle recovery snapshot is empty\");\n }\n\n return {\n id: crypto.randomUUID(),\n ...pendingFields,\n };\n}\n\n/**\n * Resolves the content material a sync plan encrypts and carries. A stale\n * bundle names predecessor KEK targets while the document's current targets\n * name successor epochs, so it splits by intent: a write-bearing pass heals\n * the document with a FRESH content key at the next epoch, anchored by a\n * covering rotation baseline, while a read-only pass keeps the stale pair and\n * unwraps it through predecessor KEKs so the server can settle a complete pull.\n */\n/**\n * The manifest bundle a stale read-only plan must pair with: the one the\n * stale content-key bundle actually references. A stale bundle normally\n * still carries the current link-set manifest hash (KEK rotations do not\n * advance the document manifest), but the projection consistency check\n * defensively admits a bundle lagging the head as long as it appears in the\n * manifest history — pair with that historical bundle so the plan's own\n * identity checks hold.\n */\nfunction staleBundleDocumentManifest(\n writerProjection: DocumentWriterProjectionResponse,\n): DocumentCreateResponse[\"accessManifest\"] {\n const { contentKeyBundle, documentManifest } = writerProjection;\n if (contentKeyBundle.linkSetManifestHash === documentManifest.manifestHash) {\n return documentManifest;\n }\n const historicalManifest = writerProjection.documentManifestHistory.find(\n (bundle) => bundle.manifestHash === contentKeyBundle.linkSetManifestHash,\n );\n if (!historicalManifest) {\n throw new Error(\n \"Document stale bundle manifest is missing from the projection history\",\n );\n }\n return historicalManifest;\n}\n\n/**\n * Settling a superseded checkpoint deletes its queue row, so the fresh\n * baseline must PROVABLY subsume it — assumed coverage would silently drop\n * any ops the checkpoint alone carried.\n */\nfunction assertRecoveryBaselineCoversCheckpoints(\n recoveryBaseline: PendingUpdateRecord,\n checkpoints: readonly PendingUpdateRecord[],\n): void {\n for (const checkpoint of checkpoints) {\n if (\n !satisfiesVersionVector(\n recoveryBaseline.partialEndVersionVector,\n checkpoint.partialEndVersionVector,\n )\n ) {\n throw new Error(\n \"Document stale-bundle recovery snapshot does not cover a queued rotation checkpoint\",\n );\n }\n }\n}\n\ninterface ResolvedSyncPlanContentMaterial {\n contentKey: Uint8Array;\n contentKeyBundle: DocumentCreateResponse[\"contentKeyBundle\"];\n documentKekTargets: DocumentSyncResponse[\"documentKekTargets\"];\n documentManifest: DocumentCreateResponse[\"accessManifest\"];\n healedStaleContentKeyBundle: boolean;\n heldBackPendingUpdateIds: readonly string[];\n pendingUpdates: readonly PendingUpdateRecord[];\n staleRecoveryBaselineUpdateId?: string;\n}\n\nasync function resolveStaleHealMaterial(\n input: Parameters<typeof buildMaterializedDocumentSyncPlan>[0],\n containerKeksByEpochId: ReadonlyMap<string, Uint8Array>,\n pendingUpdates: readonly PendingUpdateRecord[],\n): Promise<ResolvedSyncPlanContentMaterial> {\n const contentKey = crypto.getRandomValues(new Uint8Array(32));\n // A rotation checkpoint left in the queue by an interrupted earlier\n // recovery is superseded by the fresh covering baseline built below:\n // submitting it alongside would trip the server's covering-baseline gate,\n // and resubmitting it after the heal could become the latest baseline at\n // the healed epoch and mask the covering one. Hold it out of the request;\n // on heal success its id is reported settled (the committed baseline\n // subsumes its full-history content) so the queue row is removed.\n //\n // A heal whose OWN baseline does not cover the committed frontier is\n // rejected by that same gate and surfaces as a terminal queue failure.\n // This write-bearing pass does not pull first. A device missing committed\n // history can independently rematerialize it through predecessor KEKs on a\n // read-only pass, then retry with a covering snapshot. The coverage proof\n // prevents a partial local view from becoming the redirect baseline.\n const ordinaryPendingUpdates = pendingUpdates.filter(\n (update) => update.sourceVersionVector == null,\n );\n const heldBackCheckpoints = pendingUpdates.filter(\n (update) => update.sourceVersionVector != null,\n );\n const recoveryBaseline = await buildStaleRecoveryBaselinePendingUpdate(\n input.buildRotationSnapshot,\n );\n const selectedOrdinaryPendingUpdates = selectDocumentSyncOutgoingBatch(\n ordinaryPendingUpdates,\n {\n reservedDataCharacters: recoveryBaseline.updateData.length,\n reservedUpdateCount: 1,\n },\n );\n assertRecoveryBaselineCoversCheckpoints(\n recoveryBaseline,\n heldBackCheckpoints,\n );\n const staleEpoch = input.writerProjection.contentKeyBundle.contentKeyEpoch;\n const contentKeyBundle = await buildRotatedDocumentContentKeyBundle({\n containerKeksByEpochId,\n contentKey,\n writerProjection: input.writerProjection,\n });\n traceHealPlanned(input.onSyncTrace, {\n documentId: input.writerProjection.documentId,\n fromEpoch: staleEpoch,\n heldBack: heldBackCheckpoints.length,\n toEpoch: contentKeyBundle.contentKeyEpoch,\n updates: selectedOrdinaryPendingUpdates.length,\n });\n return {\n contentKey,\n contentKeyBundle,\n documentKekTargets: input.writerProjection.documentKekTargets,\n documentManifest: input.writerProjection.documentManifest,\n healedStaleContentKeyBundle: true,\n heldBackPendingUpdateIds: heldBackCheckpoints.map((update) => update.id),\n pendingUpdates: [recoveryBaseline, ...selectedOrdinaryPendingUpdates],\n staleRecoveryBaselineUpdateId: recoveryBaseline.id,\n };\n}\n\n/**\n * Reactive repair for a healthy-projection pass whose queued rotation\n * checkpoint the server rejected via the covering-baseline gate (a leftover\n * from an interrupted recovery, a heal whose ack was lost, or a lost heal\n * race). Queued checkpoints normally pass through untouched — reset and\n * rotation flows legitimately submit them — but a rejected one would strand\n * the whole queue, and committing it could shrink redirect coverage. Replace\n * the stale checkpoints with one freshly regenerated covering baseline and\n * settle them on success (coverage proven above).\n */\nasync function resolveCheckpointRegenerationMaterial(\n input: Parameters<typeof buildMaterializedDocumentSyncPlan>[0],\n base: ResolvedSyncPlanContentMaterial,\n pendingUpdates: readonly PendingUpdateRecord[],\n): Promise<ResolvedSyncPlanContentMaterial> {\n const ordinaryPendingUpdates = pendingUpdates.filter(\n (update) => update.sourceVersionVector == null,\n );\n const queuedCheckpoints = pendingUpdates.filter(\n (update) => update.sourceVersionVector != null,\n );\n const recoveryBaseline = await buildStaleRecoveryBaselinePendingUpdate(\n input.buildRotationSnapshot,\n );\n const selectedOrdinaryPendingUpdates = selectDocumentSyncOutgoingBatch(\n ordinaryPendingUpdates,\n {\n reservedDataCharacters: recoveryBaseline.updateData.length,\n reservedUpdateCount: 1,\n },\n );\n assertRecoveryBaselineCoversCheckpoints(recoveryBaseline, queuedCheckpoints);\n traceCheckpointRegeneration(input.onSyncTrace, {\n checkpoints: queuedCheckpoints.length,\n documentId: input.writerProjection.documentId,\n updates: selectedOrdinaryPendingUpdates.length,\n });\n return {\n ...base,\n heldBackPendingUpdateIds: queuedCheckpoints.map((update) => update.id),\n pendingUpdates: [recoveryBaseline, ...selectedOrdinaryPendingUpdates],\n staleRecoveryBaselineUpdateId: recoveryBaseline.id,\n };\n}\n\nasync function resolveSyncPlanContentMaterial(\n input: Parameters<typeof buildMaterializedDocumentSyncPlan>[0],\n collectedKeks: Awaited<\n ReturnType<typeof collectContainerKeksForDocumentSync>\n >,\n): Promise<ResolvedSyncPlanContentMaterial> {\n const allPendingUpdates = input.pendingUpdates ?? [];\n if (allPendingUpdates.length > 0 || input.regenerateQueuedCheckpoints) {\n assertDocumentKekPathsCurrent(input.writerProjection);\n }\n const staleContentKeyBundle =\n input.writerProjection.contentKeyBundleStale === true;\n\n if (staleContentKeyBundle && allPendingUpdates.length > 0) {\n traceStaleBundle(input.onSyncTrace, {\n documentId: input.writerProjection.documentId,\n epoch: input.writerProjection.contentKeyBundle.contentKeyEpoch,\n pending: allPendingUpdates.length,\n });\n return resolveStaleHealMaterial(\n input,\n collectedKeks.keksByEpochId,\n allPendingUpdates,\n );\n }\n\n const pendingUpdates = selectDocumentSyncOutgoingBatch(allPendingUpdates);\n\n if (staleContentKeyBundle) {\n traceStaleRead(input.onSyncTrace, {\n documentId: input.writerProjection.documentId,\n epoch: input.writerProjection.contentKeyBundle.contentKeyEpoch,\n });\n // Current access includes every predecessor KEK. If damaged history makes\n // this old bundle unreachable, preserve the bridge-integrity failure: this\n // read actually needs that historical epoch and cannot safely continue.\n let staleContentKey: Uint8Array;\n try {\n staleContentKey = await unwrapDocumentContentKeyFromBundle(\n input.writerProjection.contentKeyBundle,\n input.writerProjection.documentId,\n collectedKeks.keksByEpochId,\n collectedKeks.predecessorFailuresByEpochId,\n collectedKeks.unattributedPredecessorFailuresByContainerId,\n );\n } catch (error) {\n if (error instanceof DocumentHistoryUnavailableError) {\n if (\n input.historyMode !== \"raw\" ||\n !(error.historyCause instanceof ContainerKekHistoryUnavailableError)\n ) {\n throw error;\n }\n }\n // A stale bundle can predate the requester's current authorizing links.\n // Keep the read-only pass alive; served updates that need this absent key\n // remain undecryptable until a spanning member heals the bundle.\n staleContentKey = new Uint8Array();\n }\n return {\n contentKey: staleContentKey,\n contentKeyBundle: input.writerProjection.contentKeyBundle,\n documentKekTargets: documentKekTargetsFromContentKeyBundle(\n input.writerProjection.contentKeyBundle,\n ),\n documentManifest: staleBundleDocumentManifest(input.writerProjection),\n healedStaleContentKeyBundle: false,\n heldBackPendingUpdateIds: [],\n pendingUpdates,\n };\n }\n\n const normalMaterial: ResolvedSyncPlanContentMaterial = {\n contentKey: await unwrapDocumentContentKeyFromBundle(\n input.writerProjection.contentKeyBundle,\n input.writerProjection.documentId,\n collectedKeks.keksByEpochId,\n collectedKeks.predecessorFailuresByEpochId,\n collectedKeks.unattributedPredecessorFailuresByContainerId,\n ),\n contentKeyBundle: input.writerProjection.contentKeyBundle,\n documentKekTargets: input.writerProjection.documentKekTargets,\n documentManifest: input.writerProjection.documentManifest,\n healedStaleContentKeyBundle: false,\n heldBackPendingUpdateIds: [],\n pendingUpdates,\n };\n if (\n input.regenerateQueuedCheckpoints === true &&\n allPendingUpdates.some((update) => update.sourceVersionVector != null)\n ) {\n return resolveCheckpointRegenerationMaterial(\n input,\n normalMaterial,\n allPendingUpdates,\n );\n }\n\n return normalMaterial;\n}\n\nexport async function buildMaterializedDocumentSyncPlan(\n input: {\n author: DocumentCreateAuthor;\n /**\n * Supplies a full-history Loro snapshot of the local document when a\n * stale content-key bundle must be healed, or when a leftover queued\n * rotation checkpoint must be regenerated as a covering baseline.\n * Without it those passes fail with a descriptive error instead.\n */\n buildRotationSnapshot?: (() => Promise<Uint8Array | null>) | undefined;\n containerRekeys?: BuildDocumentSyncPlanInput[\"containerRekeys\"];\n execSql?: ExecSql | undefined;\n historyMode?: \"raw\" | undefined;\n inlineRekeyCommitId?: string | undefined;\n localVersionVector: string | null;\n minLsn?: string | undefined;\n pullCursor?: string | undefined;\n /** Clipboard-safe trace sink (see syncTrace.ts); never receives content. */\n onSyncTrace?: DocumentSyncTraceEmitter | undefined;\n pendingUpdates?: readonly PendingUpdateRecord[] | undefined;\n persistVerificationCheckpoints?: boolean | undefined;\n /**\n * Replace queued rotation checkpoints with a freshly regenerated covering\n * baseline instead of passing them through. Set by the sync loop after\n * the server rejected a pass via the covering-baseline gate.\n */\n regenerateQueuedCheckpoints?: boolean | undefined;\n signedAt?: string | undefined;\n targetSecretKey: Uint8Array;\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<MaterializedDocumentSyncPlan> {\n // Reuse verification across consistency and unwrap passes; unwrap still\n // binds the key material independently.\n const verifiedByHash = new Map<string, VerifiedContainerAccessManifest>();\n const principalPolicyCache = new Map<string, VerifiedPrincipalPolicy>();\n let writerAuthorization: DocumentWriterProjectionAuthorization | undefined;\n await assertDocumentWriterProjectionConsistent(input.writerProjection, {\n allowStaleContentKeyBundle: true,\n execSql: input.execSql,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n onVerifiedAuthorization: (authorization) => {\n writerAuthorization = authorization;\n },\n principalPolicyCache,\n verifiedByHash,\n ...projectionVerificationOptions(input),\n });\n const collectedKeks = await collectContainerKeksForDocumentSync({\n execSql: input.execSql,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n principalPolicyCache,\n secretKey: input.targetSecretKey,\n verifiedByHash,\n writerProjection: input.writerProjection,\n ...projectionVerificationOptions(input),\n });\n const documentId = input.writerProjection.documentId;\n const manifestIdentity = await assertDocumentManifestBundleConsistent({\n bundle: input.writerProjection.documentManifest,\n label: \"Document sync manifest\",\n });\n let material: ResolvedSyncPlanContentMaterial;\n try {\n material = await resolveSyncPlanContentMaterial(input, collectedKeks);\n } catch (error) {\n // Only a stale-bundle HEAL (write-bearing) or a checkpoint regeneration\n // counts as a blocked recovery; an ordinary pass or a stale READ failing\n // here must not read as one in a support report. Enumerated reason only;\n // unknown errors emit nothing (fail closed).\n if (\n (input.writerProjection.contentKeyBundleStale === true &&\n (input.pendingUpdates ?? []).length > 0) ||\n input.regenerateQueuedCheckpoints === true\n ) {\n traceHealBlocked(input.onSyncTrace, {\n documentId: input.writerProjection.documentId,\n error,\n });\n }\n throw error;\n }\n const {\n contentKey,\n contentKeyBundle,\n documentKekTargets,\n documentManifest,\n pendingUpdates,\n } = material;\n const outgoingUpdates = await prepareDocumentOutgoingUpdates({\n contentKey,\n contentKeyEpoch: contentKeyBundle.contentKeyEpoch,\n documentId,\n organizationId: manifestIdentity.organizationId,\n pendingUpdates,\n });\n const basePlan = await buildDocumentSyncPlan({\n author: {\n ...input.author,\n organizationId: manifestIdentity.organizationId,\n },\n authorizingContainerPathRefs: authorizingContainerPathRefs(\n input.writerProjection,\n ),\n containerRekeys: input.containerRekeys,\n contentKeyBundle,\n documentId,\n documentKekTargets,\n documentManifest,\n historyMode: input.historyMode,\n inlineRekeyCommitId: input.inlineRekeyCommitId,\n localVersionVector: input.localVersionVector,\n minLsn: input.minLsn,\n outgoingUpdates,\n pullCursor: input.pullCursor,\n signedAt: input.signedAt,\n });\n return finalizeMaterializedDocumentSyncPlan({\n basePlan,\n material,\n writerAuthorization,\n writerProjection: input.writerProjection,\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"syncPlanMaterial.js","sourceRoot":"","sources":["syncPlanMaterial.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,kBAAkB,EAClB,qBAAqB,EACrB,sBAAsB,EACtB,mBAAmB,GACpB,MAAM,iBAAiB,CAAC;AAMzB,OAAO,EAAE,sCAAsC,EAAE,MAAM,gCAAgC,CAAC;AACxF,OAAO,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAC;AACjF,OAAO,EAAE,6BAA6B,EAAE,MAAM,kEAAkE,CAAC;AACjH,OAAO,EACL,wCAAwC,EACxC,4BAA4B,EAC5B,oCAAoC,EACpC,mCAAmC,EACnC,mCAAmC,EACnC,+BAA+B,EAC/B,kCAAkC,GACnC,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAAE,sCAAsC,EAAE,MAAM,wCAAwC,CAAC;AAChG,OAAO,EAAE,+BAA+B,EAAE,MAAM,+DAA+D,CAAC;AAOhH,OAAO,EAAE,6BAA6B,EAAE,MAAM,sCAAsC,CAAC;AAIrF,OAAO,EAEL,2BAA2B,EAC3B,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,cAAc,GACf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,8BAA8B,EAAE,MAAM,mBAAmB,CAAC;AACnE,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC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YACD,gBAAgB,CAAC,KAAK,CAAC,WAAW,EAAE;gBAClC,UAAU,EAAE,KAAK,CAAC,gBAAgB,CAAC,UAAU;gBAC7C,KAAK;aACN,CAAC,CAAC;QACL,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;IACD,MAAM,EACJ,UAAU,EACV,gBAAgB,EAChB,kBAAkB,EAClB,gBAAgB,EAChB,cAAc,GACf,GAAG,QAAQ,CAAC;IACb,MAAM,eAAe,GAAG,MAAM,8BAA8B,CAAC;QAC3D,UAAU;QACV,eAAe,EAAE,gBAAgB,CAAC,eAAe;QACjD,UAAU;QACV,cAAc,EAAE,gBAAgB,CAAC,cAAc;QAC/C,cAAc;KACf,CAAC,CAAC;IACH,MAAM,QAAQ,GAAG,MAAM,qBAAqB,CAAC;QAC3C,MAAM,EAAE;YACN,GAAG,KAAK,CAAC,MAAM;YACf,cAAc,EAAE,gBAAgB,CAAC,cAAc;SAChD;QACD,4BAA4B,EAAE,4BAA4B,CACxD,KAAK,CAAC,gBAAgB,CACvB;QACD,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,gBAAgB;QAChB,UAAU;QACV,kBAAkB;QAClB,gBAAgB;QAChB,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;QAC9C,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,eAAe;QACf,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,QAAQ,EAAE,KAAK,CAAC,QAAQ;KACzB,CAAC,CAAC;IACH,OAAO,oCAAoC,CAAC;QAC1C,QAAQ;QACR,QAAQ;QACR,mBAAmB;QACnB,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;KACzC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n VerifiedContainerAccessManifest,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport {\n emptyVersionVector,\n getImportBlobMetadata,\n satisfiesVersionVector,\n versionVectorsEqual,\n} from \"@tearleads/loro\";\nimport type {\n DocumentCreateResponse,\n DocumentSyncResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { documentKekTargetsFromContentKeyBundle } from \"@tearleads/validators/response\";\nimport { createPendingUpdateFields } from \"../../../data/documents/documentSync\";\nimport { assertDocumentKekPathsCurrent } from \"../../../data/documents/shared/containerKek/containerKekCurrency\";\nimport {\n assertDocumentWriterProjectionConsistent,\n authorizingContainerPathRefs,\n buildRotatedDocumentContentKeyBundle,\n ContainerKekHistoryUnavailableError,\n collectContainerKeksForDocumentSync,\n DocumentHistoryUnavailableError,\n unwrapDocumentContentKeyFromBundle,\n} from \"../../../data/documents/shared/projection\";\nimport { assertDocumentManifestBundleConsistent } from \"../../../data/documents/shared/readers\";\nimport { selectDocumentSyncOutgoingBatch } from \"../../../data/documents/shared/sync/documentSyncOutgoingBatch\";\nimport type {\n BuildDocumentSyncPlanInput,\n DocumentCreateAuthor,\n MaterializedDocumentSyncPlan,\n ProjectionVerificationOptions,\n} from \"../../../data/documents/shared/types\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/types\";\nimport type { DocumentWriterProjectionAuthorization } from \"../../../data/keyingProjectionVerification\";\nimport type { PendingUpdateRecord } from \"../../../data/sqlite/documentPersistence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n type DocumentSyncTraceEmitter,\n traceCheckpointRegeneration,\n traceHealBlocked,\n traceHealPlanned,\n traceStaleBundle,\n traceStaleRead,\n} from \"../sync/syncTrace\";\nimport { prepareDocumentOutgoingUpdates } from \"./syncContentKeys\";\nimport { buildDocumentSyncPlan } from \"./syncPlanIdentity\";\nimport { finalizeMaterializedDocumentSyncPlan } from \"./syncPlanProjection\";\n\n/**\n * Builds the rotation baseline that anchors a stale-bundle heal: a full\n * history snapshot of the local document, re-encrypted under the fresh\n * content key so every current member (including post-rotation newcomers)\n * has an efficient current-epoch redirect. Predecessor KEKs remain the\n * correctness path when no covering baseline exists.\n */\nasync function buildStaleRecoveryBaselinePendingUpdate(\n buildRotationSnapshot: (() => Promise<Uint8Array | null>) | undefined,\n): Promise<PendingUpdateRecord> {\n const snapshot = buildRotationSnapshot ? await buildRotationSnapshot() : null;\n if (!snapshot) {\n throw new Error(\n \"Document content-key bundle is stale and no rotation snapshot is available to heal it\",\n );\n }\n const metadata = getImportBlobMetadata(snapshot);\n if (\n metadata.mode !== \"snapshot\" ||\n !versionVectorsEqual(\n metadata.partialStartVersionVector,\n emptyVersionVector(),\n )\n ) {\n throw new Error(\n \"Document stale-bundle recovery requires a full-history rotation snapshot\",\n );\n }\n const pendingFields = createPendingUpdateFields(\n snapshot,\n metadata.partialEndVersionVector,\n );\n if (!pendingFields) {\n throw new Error(\"Document stale-bundle recovery snapshot is empty\");\n }\n\n return {\n id: crypto.randomUUID(),\n ...pendingFields,\n };\n}\n\n/**\n * Resolves the content material a sync plan encrypts and carries. A stale\n * bundle names predecessor KEK targets while the document's current targets\n * name successor epochs, so it splits by intent: a write-bearing pass heals\n * the document with a FRESH content key at the next epoch, anchored by a\n * covering rotation baseline, while a read-only pass keeps the stale pair and\n * unwraps it through predecessor KEKs so the server can settle a complete pull.\n */\n/**\n * The manifest bundle a stale read-only plan must pair with: the one the\n * stale content-key bundle actually references. A stale bundle normally\n * still carries the current link-set manifest hash (KEK rotations do not\n * advance the document manifest), but the projection consistency check\n * defensively admits a bundle lagging the head as long as it appears in the\n * manifest history — pair with that historical bundle so the plan's own\n * identity checks hold.\n */\nfunction staleBundleDocumentManifest(\n writerProjection: DocumentWriterProjectionResponse,\n): DocumentCreateResponse[\"accessManifest\"] {\n const { contentKeyBundle, documentManifest } = writerProjection;\n if (contentKeyBundle.linkSetManifestHash === documentManifest.manifestHash) {\n return documentManifest;\n }\n const historicalManifest = writerProjection.documentManifestHistory.find(\n (bundle) => bundle.manifestHash === contentKeyBundle.linkSetManifestHash,\n );\n if (!historicalManifest) {\n throw new Error(\n \"Document stale bundle manifest is missing from the projection history\",\n );\n }\n return historicalManifest;\n}\n\n/**\n * Settling a superseded checkpoint deletes its queue row, so the fresh\n * baseline must PROVABLY subsume it — assumed coverage would silently drop\n * any ops the checkpoint alone carried.\n */\nfunction assertRecoveryBaselineCoversCheckpoints(\n recoveryBaseline: PendingUpdateRecord,\n checkpoints: readonly PendingUpdateRecord[],\n): void {\n for (const checkpoint of checkpoints) {\n if (\n !satisfiesVersionVector(\n recoveryBaseline.partialEndVersionVector,\n checkpoint.partialEndVersionVector,\n )\n ) {\n throw new Error(\n \"Document stale-bundle recovery snapshot does not cover a queued rotation checkpoint\",\n );\n }\n }\n}\n\ninterface ResolvedSyncPlanContentMaterial {\n contentKey: Uint8Array;\n contentKeyBundle: DocumentCreateResponse[\"contentKeyBundle\"];\n documentKekTargets: DocumentSyncResponse[\"documentKekTargets\"];\n documentManifest: DocumentCreateResponse[\"accessManifest\"];\n healedStaleContentKeyBundle: boolean;\n heldBackPendingUpdateIds: readonly string[];\n pendingUpdates: readonly PendingUpdateRecord[];\n staleRecoveryBaselineUpdateId?: string;\n}\n\nasync function resolveStaleHealMaterial(\n input: Parameters<typeof buildMaterializedDocumentSyncPlan>[0],\n containerKeksByEpochId: ReadonlyMap<string, Uint8Array>,\n pendingUpdates: readonly PendingUpdateRecord[],\n): Promise<ResolvedSyncPlanContentMaterial> {\n const contentKey = crypto.getRandomValues(new Uint8Array(32));\n // A rotation checkpoint left in the queue by an interrupted earlier\n // recovery is superseded by the fresh covering baseline built below:\n // submitting it alongside would trip the server's covering-baseline gate,\n // and resubmitting it after the heal could become the latest baseline at\n // the healed epoch and mask the covering one. Hold it out of the request;\n // on heal success its id is reported settled (the committed baseline\n // subsumes its full-history content) so the queue row is removed.\n //\n // A heal whose OWN baseline does not cover the committed frontier is\n // rejected by that same gate and surfaces as a terminal queue failure.\n // This write-bearing pass does not pull first. A device missing committed\n // history can independently rematerialize it through predecessor KEKs on a\n // read-only pass, then retry with a covering snapshot. The coverage proof\n // prevents a partial local view from becoming the redirect baseline.\n const ordinaryPendingUpdates = pendingUpdates.filter(\n (update) => update.sourceVersionVector == null,\n );\n const heldBackCheckpoints = pendingUpdates.filter(\n (update) => update.sourceVersionVector != null,\n );\n const recoveryBaseline = await buildStaleRecoveryBaselinePendingUpdate(\n input.buildRotationSnapshot,\n );\n const selectedOrdinaryPendingUpdates = selectDocumentSyncOutgoingBatch(\n ordinaryPendingUpdates,\n {\n reservedDataCharacters: recoveryBaseline.updateData.length,\n reservedUpdateCount: 1,\n },\n );\n assertRecoveryBaselineCoversCheckpoints(\n recoveryBaseline,\n heldBackCheckpoints,\n );\n const staleEpoch = input.writerProjection.contentKeyBundle.contentKeyEpoch;\n const contentKeyBundle = await buildRotatedDocumentContentKeyBundle({\n containerKeksByEpochId,\n contentKey,\n writerProjection: input.writerProjection,\n });\n traceHealPlanned(input.onSyncTrace, {\n documentId: input.writerProjection.documentId,\n fromEpoch: staleEpoch,\n heldBack: heldBackCheckpoints.length,\n toEpoch: contentKeyBundle.contentKeyEpoch,\n updates: selectedOrdinaryPendingUpdates.length,\n });\n return {\n contentKey,\n contentKeyBundle,\n documentKekTargets: input.writerProjection.documentKekTargets,\n documentManifest: input.writerProjection.documentManifest,\n healedStaleContentKeyBundle: true,\n heldBackPendingUpdateIds: heldBackCheckpoints.map((update) => update.id),\n pendingUpdates: [recoveryBaseline, ...selectedOrdinaryPendingUpdates],\n staleRecoveryBaselineUpdateId: recoveryBaseline.id,\n };\n}\n\n/**\n * Reactive repair for a healthy-projection pass whose queued rotation\n * checkpoint the server rejected via the covering-baseline gate (a leftover\n * from an interrupted recovery, a heal whose ack was lost, or a lost heal\n * race). Queued checkpoints normally pass through untouched — reset and\n * rotation flows legitimately submit them — but a rejected one would strand\n * the whole queue, and committing it could shrink redirect coverage. Replace\n * the stale checkpoints with one freshly regenerated covering baseline and\n * settle them on success (coverage proven above).\n */\nasync function resolveCheckpointRegenerationMaterial(\n input: Parameters<typeof buildMaterializedDocumentSyncPlan>[0],\n base: ResolvedSyncPlanContentMaterial,\n pendingUpdates: readonly PendingUpdateRecord[],\n): Promise<ResolvedSyncPlanContentMaterial> {\n const ordinaryPendingUpdates = pendingUpdates.filter(\n (update) => update.sourceVersionVector == null,\n );\n const queuedCheckpoints = pendingUpdates.filter(\n (update) => update.sourceVersionVector != null,\n );\n const recoveryBaseline = await buildStaleRecoveryBaselinePendingUpdate(\n input.buildRotationSnapshot,\n );\n const selectedOrdinaryPendingUpdates = selectDocumentSyncOutgoingBatch(\n ordinaryPendingUpdates,\n {\n reservedDataCharacters: recoveryBaseline.updateData.length,\n reservedUpdateCount: 1,\n },\n );\n assertRecoveryBaselineCoversCheckpoints(recoveryBaseline, queuedCheckpoints);\n traceCheckpointRegeneration(input.onSyncTrace, {\n checkpoints: queuedCheckpoints.length,\n documentId: input.writerProjection.documentId,\n updates: selectedOrdinaryPendingUpdates.length,\n });\n return {\n ...base,\n heldBackPendingUpdateIds: queuedCheckpoints.map((update) => update.id),\n pendingUpdates: [recoveryBaseline, ...selectedOrdinaryPendingUpdates],\n staleRecoveryBaselineUpdateId: recoveryBaseline.id,\n };\n}\n\nasync function resolveSyncPlanContentMaterial(\n input: Parameters<typeof buildMaterializedDocumentSyncPlan>[0],\n collectedKeks: Awaited<\n ReturnType<typeof collectContainerKeksForDocumentSync>\n >,\n): Promise<ResolvedSyncPlanContentMaterial> {\n const allPendingUpdates = input.pendingUpdates ?? [];\n if (allPendingUpdates.length > 0 || input.regenerateQueuedCheckpoints) {\n assertDocumentKekPathsCurrent(input.writerProjection);\n }\n const staleContentKeyBundle =\n input.writerProjection.contentKeyBundleStale === true;\n\n if (staleContentKeyBundle && allPendingUpdates.length > 0) {\n traceStaleBundle(input.onSyncTrace, {\n documentId: input.writerProjection.documentId,\n epoch: input.writerProjection.contentKeyBundle.contentKeyEpoch,\n pending: allPendingUpdates.length,\n });\n return resolveStaleHealMaterial(\n input,\n collectedKeks.keksByEpochId,\n allPendingUpdates,\n );\n }\n\n const pendingUpdates = selectDocumentSyncOutgoingBatch(allPendingUpdates);\n\n if (staleContentKeyBundle) {\n traceStaleRead(input.onSyncTrace, {\n documentId: input.writerProjection.documentId,\n epoch: input.writerProjection.contentKeyBundle.contentKeyEpoch,\n });\n // Current access includes every predecessor KEK. If damaged history makes\n // this old bundle unreachable, preserve the bridge-integrity failure: this\n // read actually needs that historical epoch and cannot safely continue.\n let staleContentKey: Uint8Array;\n try {\n staleContentKey = await unwrapDocumentContentKeyFromBundle(\n input.writerProjection.contentKeyBundle,\n input.writerProjection.documentId,\n collectedKeks.keksByEpochId,\n collectedKeks.predecessorFailuresByEpochId,\n collectedKeks.unattributedPredecessorFailuresByContainerId,\n );\n } catch (error) {\n if (error instanceof DocumentHistoryUnavailableError) {\n if (\n input.historyMode !== \"raw\" ||\n !(error.historyCause instanceof ContainerKekHistoryUnavailableError)\n ) {\n throw error;\n }\n }\n // A stale bundle can predate the requester's current authorizing links.\n // Keep the read-only pass alive; served updates that need this absent key\n // remain undecryptable until a spanning member heals the bundle.\n staleContentKey = new Uint8Array();\n }\n return {\n contentKey: staleContentKey,\n contentKeyBundle: input.writerProjection.contentKeyBundle,\n documentKekTargets: documentKekTargetsFromContentKeyBundle(\n input.writerProjection.contentKeyBundle,\n ),\n documentManifest: staleBundleDocumentManifest(input.writerProjection),\n healedStaleContentKeyBundle: false,\n heldBackPendingUpdateIds: [],\n pendingUpdates,\n };\n }\n\n const normalMaterial: ResolvedSyncPlanContentMaterial = {\n contentKey: await unwrapDocumentContentKeyFromBundle(\n input.writerProjection.contentKeyBundle,\n input.writerProjection.documentId,\n collectedKeks.keksByEpochId,\n collectedKeks.predecessorFailuresByEpochId,\n collectedKeks.unattributedPredecessorFailuresByContainerId,\n ),\n contentKeyBundle: input.writerProjection.contentKeyBundle,\n documentKekTargets: input.writerProjection.documentKekTargets,\n documentManifest: input.writerProjection.documentManifest,\n healedStaleContentKeyBundle: false,\n heldBackPendingUpdateIds: [],\n pendingUpdates,\n };\n if (\n input.regenerateQueuedCheckpoints === true &&\n allPendingUpdates.some((update) => update.sourceVersionVector != null)\n ) {\n return resolveCheckpointRegenerationMaterial(\n input,\n normalMaterial,\n allPendingUpdates,\n );\n }\n\n return normalMaterial;\n}\n\nexport async function buildMaterializedDocumentSyncPlan(\n input: {\n author: DocumentCreateAuthor;\n /**\n * Supplies a full-history Loro snapshot of the local document when a\n * stale content-key bundle must be healed, or when a leftover queued\n * rotation checkpoint must be regenerated as a covering baseline.\n * Without it those passes fail with a descriptive error instead.\n */\n buildRotationSnapshot?: (() => Promise<Uint8Array | null>) | undefined;\n containerRekeys?: BuildDocumentSyncPlanInput[\"containerRekeys\"];\n execSql?: ExecSql | undefined;\n historyMode?: \"raw\" | undefined;\n inlineRekeyCommitId?: string | undefined;\n localVersionVector: string | null;\n minLsn?: string | undefined;\n pullCursor?: string | undefined;\n /** Clipboard-safe trace sink (see syncTrace.ts); never receives content. */\n onSyncTrace?: DocumentSyncTraceEmitter | undefined;\n pendingUpdates?: readonly PendingUpdateRecord[] | undefined;\n persistVerificationCheckpoints?: boolean | undefined;\n /**\n * Replace queued rotation checkpoints with a freshly regenerated covering\n * baseline instead of passing them through. Set by the sync loop after\n * the server rejected a pass via the covering-baseline gate.\n */\n regenerateQueuedCheckpoints?: boolean | undefined;\n signedAt?: string | undefined;\n targetSecretKey: Uint8Array;\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<MaterializedDocumentSyncPlan> {\n // Reuse verification across consistency and unwrap passes; unwrap still\n // binds the key material independently.\n const verifiedByHash = new Map<string, VerifiedContainerAccessManifest>();\n const principalPolicyCache = new Map<string, VerifiedPrincipalPolicy>();\n let writerAuthorization: DocumentWriterProjectionAuthorization | undefined;\n await assertDocumentWriterProjectionConsistent(input.writerProjection, {\n allowStaleContentKeyBundle: true,\n execSql: input.execSql,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n onVerifiedAuthorization: (authorization) => {\n writerAuthorization = authorization;\n },\n principalPolicyCache,\n verifiedByHash,\n ...projectionVerificationOptions(input),\n });\n const collectedKeks = await collectContainerKeksForDocumentSync({\n execSql: input.execSql,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n principalPolicyCache,\n secretKey: input.targetSecretKey,\n verifiedByHash,\n writerProjection: input.writerProjection,\n ...projectionVerificationOptions(input),\n });\n const documentId = input.writerProjection.documentId;\n const manifestIdentity = await assertDocumentManifestBundleConsistent({\n bundle: input.writerProjection.documentManifest,\n label: \"Document sync manifest\",\n });\n let material: ResolvedSyncPlanContentMaterial;\n try {\n material = await resolveSyncPlanContentMaterial(input, collectedKeks);\n } catch (error) {\n // Only a stale-bundle HEAL (write-bearing) or a checkpoint regeneration\n // counts as a blocked recovery; an ordinary pass or a stale READ failing\n // here must not read as one in a support report. Enumerated reason only;\n // unknown errors emit nothing (fail closed).\n if (\n (input.writerProjection.contentKeyBundleStale === true &&\n (input.pendingUpdates ?? []).length > 0) ||\n input.regenerateQueuedCheckpoints === true\n ) {\n traceHealBlocked(input.onSyncTrace, {\n documentId: input.writerProjection.documentId,\n error,\n });\n }\n throw error;\n }\n const {\n contentKey,\n contentKeyBundle,\n documentKekTargets,\n documentManifest,\n pendingUpdates,\n } = material;\n const outgoingUpdates = await prepareDocumentOutgoingUpdates({\n contentKey,\n contentKeyEpoch: contentKeyBundle.contentKeyEpoch,\n documentId,\n organizationId: manifestIdentity.organizationId,\n pendingUpdates,\n });\n const basePlan = await buildDocumentSyncPlan({\n author: {\n ...input.author,\n organizationId: manifestIdentity.organizationId,\n },\n authorizingContainerPathRefs: authorizingContainerPathRefs(\n input.writerProjection,\n ),\n containerRekeys: input.containerRekeys,\n contentKeyBundle,\n documentId,\n documentKekTargets,\n documentManifest,\n historyMode: input.historyMode,\n inlineRekeyCommitId: input.inlineRekeyCommitId,\n localVersionVector: input.localVersionVector,\n minLsn: input.minLsn,\n outgoingUpdates,\n pullCursor: input.pullCursor,\n signedAt: input.signedAt,\n });\n return finalizeMaterializedDocumentSyncPlan({\n basePlan,\n material,\n writerAuthorization,\n writerProjection: input.writerProjection,\n });\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { limitDocumentSyncRequestBytes } from "../../../data/sync/documentSyncOutgoingBatch.js";
|
|
1
|
+
import { limitDocumentSyncRequestBytes } from "../../../data/documents/shared/sync/documentSyncOutgoingBatch.js";
|
|
2
2
|
export function boundDocumentSyncPlanRequest(plan, requiredOutgoingUpdateId) {
|
|
3
3
|
const request = limitDocumentSyncRequestBytes(plan.request, {
|
|
4
4
|
requiredOutgoingUpdateId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncPlanRequestBounds.js","sourceRoot":"","sources":["syncPlanRequestBounds.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"syncPlanRequestBounds.js","sourceRoot":"","sources":["syncPlanRequestBounds.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,6BAA6B,EAAE,MAAM,+DAA+D,CAAC;AAW9G,MAAM,UAAU,4BAA4B,CAC1C,IAA0C,EAC1C,wBAA4C;IAE5C,MAAM,OAAO,GAAG,6BAA6B,CAAC,IAAI,CAAC,OAAO,EAAE;QAC1D,wBAAwB;KACzB,CAAC,CAAC;IACH,OAAO,OAAO,KAAK,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,CAAC;AAChE,CAAC;AAED,MAAM,UAAU,4BAA4B,CAC1C,QAA0B,EAC1B,IAA0C,EAC1C,gBAAkE;IAElE,OAAO;QACL,UAAU,EAAE,QAAQ,CAAC,UAAU;QAC/B,2BAA2B,EAAE,QAAQ,CAAC,2BAA2B;QACjE,wBAAwB,EAAE,QAAQ,CAAC,wBAAwB;QAC3D,IAAI;QACJ,gBAAgB;QAChB,GAAG,CAAC,QAAQ,CAAC,6BAA6B,KAAK,SAAS;YACtD,CAAC,CAAC,EAAE;YACJ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,gCAAgC,CAC9C,gBAA8C,EAC9C,QAA8B;IAE9B,MAAM,kBAAkB,GAAG,gBAAgB,CAAC,6BAA6B,CAAC;IAC1E,OAAO,CACL,kBAAkB,KAAK,SAAS;QAChC,QAAQ,CAAC,yBAAyB,CAAC,QAAQ,CAAC,kBAAkB,CAAC,CAChE,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,gCAAgC,CAC9C,gBAA8C,EAC9C,QAA8B;IAE9B,OAAO,gCAAgC,CAAC,gBAAgB,EAAE,QAAQ,CAAC;QACjE,CAAC,CAAC,gBAAgB,CAAC,wBAAwB;QAC3C,CAAC,CAAC,EAAE,CAAC;AACT,CAAC","sourcesContent":["import type { DocumentSyncResponse } from \"@tearleads/validators/response\";\nimport { limitDocumentSyncRequestBytes } from \"../../../data/documents/shared/sync/documentSyncOutgoingBatch\";\nimport type { MaterializedDocumentSyncPlan } from \"../../../data/documents/shared/types\";\nimport type { PendingUpdateRecord } from \"../../../data/sqlite/documentPersistence\";\n\ninterface SyncPlanMaterial {\n readonly contentKey: Uint8Array;\n readonly healedStaleContentKeyBundle: boolean;\n readonly heldBackPendingUpdateIds: readonly string[];\n readonly staleRecoveryBaselineUpdateId?: string | undefined;\n}\n\nexport function boundDocumentSyncPlanRequest(\n plan: MaterializedDocumentSyncPlan[\"plan\"],\n requiredOutgoingUpdateId: string | undefined,\n): MaterializedDocumentSyncPlan[\"plan\"] {\n const request = limitDocumentSyncRequestBytes(plan.request, {\n requiredOutgoingUpdateId,\n });\n return request === plan.request ? plan : { ...plan, request };\n}\n\nexport function materializedDocumentSyncPlan(\n material: SyncPlanMaterial,\n plan: MaterializedDocumentSyncPlan[\"plan\"],\n writerProjection: MaterializedDocumentSyncPlan[\"writerProjection\"],\n): MaterializedDocumentSyncPlan {\n return {\n contentKey: material.contentKey,\n healedStaleContentKeyBundle: material.healedStaleContentKeyBundle,\n heldBackPendingUpdateIds: material.heldBackPendingUpdateIds,\n plan,\n writerProjection,\n ...(material.staleRecoveryBaselineUpdateId === undefined\n ? {}\n : {\n staleRecoveryBaselineUpdateId: material.staleRecoveryBaselineUpdateId,\n }),\n };\n}\n\nexport function recoverablePendingUpdates(\n pendingUpdates: readonly PendingUpdateRecord[],\n materializedPlan: MaterializedDocumentSyncPlan,\n): PendingUpdateRecord[] {\n const submittedIds = new Set(\n materializedPlan.plan.request.outgoingUpdates.map((update) => update.id),\n );\n const recoverableIds = new Set([\n ...submittedIds,\n ...materializedPlan.heldBackPendingUpdateIds,\n ]);\n return pendingUpdates.filter((update) => recoverableIds.has(update.id));\n}\n\nexport function hasDeferredPendingUpdatesAfterSubmit(input: {\n acceptedRecoveryBaseline: boolean;\n exhaustedPendingUpdateCount: number;\n pendingUpdateIds: readonly string[];\n rekeyedPendingUpdateIds: readonly string[];\n settledPendingUpdateIds: readonly string[];\n}): boolean {\n if (input.exhaustedPendingUpdateCount > 0) {\n return false;\n }\n\n const madeDurableProgress =\n input.acceptedRecoveryBaseline ||\n input.settledPendingUpdateIds.length > 0 ||\n input.rekeyedPendingUpdateIds.length > 0;\n if (!madeDurableProgress) {\n return false;\n }\n\n const settledPendingUpdateIds = new Set(input.settledPendingUpdateIds);\n return (\n input.rekeyedPendingUpdateIds.length > 0 ||\n input.pendingUpdateIds.some(\n (updateId) => !settledPendingUpdateIds.has(updateId),\n )\n );\n}\n\nexport function responseAcceptedRecoveryBaseline(\n materializedPlan: MaterializedDocumentSyncPlan,\n response: DocumentSyncResponse,\n): boolean {\n const recoveryBaselineId = materializedPlan.staleRecoveryBaselineUpdateId;\n return (\n recoveryBaselineId !== undefined &&\n response.acceptedOutgoingUpdateIds.includes(recoveryBaselineId)\n );\n}\n\nexport function acceptedHeldBackPendingUpdateIds(\n materializedPlan: MaterializedDocumentSyncPlan,\n response: DocumentSyncResponse,\n): readonly string[] {\n return responseAcceptedRecoveryBaseline(materializedPlan, response)\n ? materializedPlan.heldBackPendingUpdateIds\n : [];\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-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;QAC7B,mBAAmB,EAAE,QAAQ,CAAC,UAAU;KACzC,CAAC,CAAC;IACH,MAAM,KAAK,GAAG,MAAM,oBAAoB,CAAC;QACvC,UAAU;QACV,MAAM,EAAE,UAAU,GAAG,QAAQ,CAAC,SAAS;QACvC,MAAM;KACP,CAAC,CAAC;IACH,IAAI,CAAC,MAAM,SAAS,CAAC,KAAK,CAAC,CAAC,KAAK,QAAQ,CAAC,WAAW,CAAC,UAAU,CAAC,EAAE,CAAC;QAClE,MAAM,IAAI,KAAK,CACb,wBAAwB,UAAU,kCAAkC,CACrE,CAAC;IACJ,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import {\n blobChunkPlaintextByteLength,\n bytesToHex,\n computeBlobChunkCount,\n createIncrementalSha256,\n normalizeBlobChunkSize,\n} from \"@tearleads/crypto\";\nimport type { BlobByteSource, BlobBytes } from \"../../../blobs/blobContracts\";\nimport { asWebCryptoBytes } from \"../../shared/readers\";\nimport type { BlobSourceSnapshot } from \"./types\";\n\nexport type { BlobSourceSnapshot } from \"./types\";\n\nasync function sha256Hex(bytes: Uint8Array): Promise<string> {\n return bytesToHex(\n new Uint8Array(\n await crypto.subtle.digest(\"SHA-256\", asWebCryptoBytes(bytes)),\n ),\n );\n}\n\nfunction assertSourceByteLength(byteLength: number): void {\n if (!Number.isSafeInteger(byteLength) || byteLength < 0) {\n throw new Error(\n \"Blob source byte length must be a non-negative safe integer\",\n );\n }\n}\n\nasync function readExactSourceBytes(input: {\n readonly byteLength: number;\n readonly offset: number;\n readonly source: BlobByteSource;\n}): Promise<BlobBytes> {\n const bytes = await input.source.read(input.offset, input.byteLength);\n if (bytes.byteLength !== input.byteLength) {\n throw new Error(\"Blob source returned an unexpected byte length\");\n }\n const copy = new Uint8Array(bytes.byteLength);\n copy.set(bytes);\n return copy;\n}\n\nexport async function inspectBlobSource(\n source: BlobByteSource,\n chunkSize: number,\n): Promise<BlobSourceSnapshot> {\n assertSourceByteLength(source.byteLength);\n normalizeBlobChunkSize(chunkSize);\n const chunkCount = computeBlobChunkCount(source.byteLength, chunkSize);\n const chunkSha256: string[] = [];\n const objectHash = createIncrementalSha256();\n\n for (let chunkIndex = 0; chunkIndex < chunkCount; chunkIndex += 1) {\n const byteLength = blobChunkPlaintextByteLength({\n chunkCount,\n chunkIndex,\n chunkSize,\n plaintextByteLength: source.byteLength,\n });\n const bytes = await readExactSourceBytes({\n byteLength,\n offset: chunkIndex * chunkSize,\n source,\n });\n objectHash.update(bytes);\n chunkSha256.push(await sha256Hex(bytes));\n }\n\n return {\n byteLength: source.byteLength,\n chunkSha256,\n chunkSize,\n sha256: bytesToHex(objectHash.digest()),\n };\n}\n\nexport async function readVerifiedBlobSourceChunk(input: {\n readonly chunkIndex: number;\n readonly snapshot: BlobSourceSnapshot;\n readonly source: BlobByteSource;\n}): Promise<BlobBytes> {\n const { chunkIndex, snapshot, source } = input;\n if (source.byteLength !== snapshot.byteLength) {\n throw new Error(\"Blob source byte length changed after inspection\");\n }\n const chunkCount = computeBlobChunkCount(\n snapshot.byteLength,\n snapshot.chunkSize,\n );\n const byteLength = blobChunkPlaintextByteLength({\n chunkCount,\n chunkIndex,\n chunkSize: snapshot.chunkSize,\n plaintextByteLength: snapshot.byteLength,\n });\n const bytes = await readExactSourceBytes({\n byteLength,\n offset: chunkIndex * snapshot.chunkSize,\n source,\n });\n if ((await sha256Hex(bytes)) !== snapshot.chunkSha256[chunkIndex]) {\n throw new Error(\n `Blob plaintext chunk ${chunkIndex} changed after source inspection`,\n );\n }\n return bytes;\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"chunkedBlobCrypto.js","sourceRoot":"","sources":["chunkedBlobCrypto.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EACjB,cAAc,EACd,qBAAqB,EACrB,2BAA2B,EAC3B,4BAA4B,EAC5B,uBAAuB,EACvB,UAAU,EACV,+BAA+B,EAC/B,qBAAqB,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CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;IAC7E,MAAM,OAAO,GAAG,MAAM,2BAA2B,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;IACnE,IACE,QAAQ,CAAC,UAAU,KAAK,OAAO,CAAC,mBAAmB;QACnD,QAAQ,CAAC,SAAS,KAAK,OAAO,CAAC,SAAS,EACxC,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;IAC3E,CAAC;IACD,MAAM,MAAM,GAAG,MAAM,qBAAqB,CAAC,KAAK,CAAC,MAAM,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;IAC5E,OAAO,wBAAwB,CAAC;QAC9B,OAAO;QACP,MAAM;QACN,QAAQ;QACR,MAAM,EAAE,KAAK,CAAC,MAAM;KACrB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n AES_256_KEY_BYTES,\n AES_GCM_TAG_BYTES,\n assertAesGcmIv,\n BLOB_CHUNK_SIZE_BYTES,\n BLOB_ENCRYPTED_BYTES_FORMAT,\n BLOB_ENCRYPTED_BYTES_VERSION,\n blobContentMetadataHash,\n bytesToHex,\n CONTENT_RECORD_ENCRYPTION_SUITE,\n computeBlobChunkCount,\n computeBlobEncryptedByteLength,\n computeContentRecordNonceDomainHash,\n createAesGcmIv,\n createIncrementalSha256,\n deriveBlobChunkIv,\n encodeBlobEnvelopeV2Header,\n normalizeBlobChunkSize,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type { BlobContentKeyBundleRequest } from \"@tearleads/validators/request\";\nimport type { BlobByteSource, BlobBytes } from \"../../../blobs/blobContracts\";\nimport { importContentKeyMaterial } from \"../../shared/contentRecordKeys\";\nimport {\n contentRecordAdditionalDataBytes,\n deriveBlobBaseIv,\n deriveBlobContentRecordKey,\n} from \"./blobRecordCrypto\";\nimport {\n type BlobSourceSnapshot,\n inspectBlobSource,\n readVerifiedBlobSourceChunk,\n} from \"./blobSourceSnapshot\";\nimport { createEncryptedUploadParts } from \"./encryptedUploadParts\";\nimport type { BlobEncryptionPlan } from \"./types\";\n\nexport const DEFAULT_BLOB_CHUNK_SIZE_BYTES = BLOB_CHUNK_SIZE_BYTES;\n\ninterface PrepareBlobEncryptionInput {\n readonly blobId: string;\n readonly chunkSize?: number | undefined;\n readonly contentKey: Uint8Array;\n readonly contentKeyBundle: BlobContentKeyBundleRequest;\n readonly nonceSeed?: Uint8Array | undefined;\n readonly organizationId: string;\n readonly source: BlobByteSource;\n readonly sourceSnapshot?: BlobSourceSnapshot | undefined;\n}\n\ninterface BlobEncryptionContext {\n readonly baseIv: BlobBytes;\n readonly blobId: string;\n readonly chunkSize: number;\n readonly contentKeyEpoch: number;\n readonly contentRecordId: string;\n readonly headerBytes: BlobBytes;\n readonly metadataHash: string;\n readonly nonceDomainHash: string;\n readonly organizationId: string;\n readonly partCount: number;\n readonly plaintextByteLength: number;\n readonly recordKey: CryptoKey;\n}\n\nasync function createBlobEncryptionContext(\n input: PrepareBlobEncryptionInput,\n snapshot: BlobSourceSnapshot,\n): Promise<BlobEncryptionContext> {\n const chunkSize = normalizeBlobChunkSize(\n input.chunkSize ?? DEFAULT_BLOB_CHUNK_SIZE_BYTES,\n );\n const plaintextByteLength = input.source.byteLength;\n const partCount = computeBlobChunkCount(plaintextByteLength, chunkSize);\n const contentRecordId = input.blobId;\n const { contentKeyEpoch } = input.contentKeyBundle;\n const nonceSeed = new Uint8Array(input.nonceSeed ?? createAesGcmIv());\n const baseIv = await deriveBlobBaseIv({\n chunkSize,\n nonceSeed,\n plaintextSha256: snapshot.sha256,\n });\n\n const [nonceDomainHash, metadataHash] = await Promise.all([\n computeContentRecordNonceDomainHash({\n version: 1,\n organizationId: input.organizationId,\n objectKind: \"blob\",\n objectId: input.blobId,\n contentKeyEpoch,\n encryptionSuite: CONTENT_RECORD_ENCRYPTION_SUITE,\n contentRecordId,\n }),\n blobContentMetadataHash({\n blobId: input.blobId,\n byteLength: plaintextByteLength,\n chunkCount: partCount,\n chunkSize,\n contentKeyEpoch,\n }),\n ]);\n const contentKeyMaterial = await importContentKeyMaterial(input.contentKey);\n const recordKey = await deriveBlobContentRecordKey({\n blobId: input.blobId,\n contentKeyEpoch,\n contentKeyMaterial,\n contentRecordId,\n organizationId: input.organizationId,\n usage: \"encrypt\",\n });\n return {\n baseIv,\n blobId: input.blobId,\n chunkSize,\n contentKeyEpoch,\n contentRecordId,\n headerBytes: encodeBlobEnvelopeV2Header({\n blobId: input.blobId,\n byteLength: plaintextByteLength,\n chunkCount: partCount,\n chunkSize,\n contentKeyEpoch,\n contentRecordId,\n encryptionSuite: CONTENT_RECORD_ENCRYPTION_SUITE,\n format: BLOB_ENCRYPTED_BYTES_FORMAT,\n iv: bytesToBase64(baseIv),\n metadataHash,\n nonceDomainHash,\n version: BLOB_ENCRYPTED_BYTES_VERSION,\n }),\n metadataHash,\n nonceDomainHash,\n organizationId: input.organizationId,\n partCount,\n plaintextByteLength,\n recordKey,\n };\n}\n\nasync function encryptBlobChunk(\n context: BlobEncryptionContext,\n chunkIndex: number,\n plaintext: BlobBytes,\n): Promise<BlobBytes> {\n return new Uint8Array(\n await crypto.subtle.encrypt(\n {\n name: \"AES-GCM\",\n iv: deriveBlobChunkIv(context.baseIv, chunkIndex),\n additionalData: contentRecordAdditionalDataBytes({\n blobId: context.blobId,\n chunkCount: context.partCount,\n chunkIndex,\n chunkPlaintextByteLength: plaintext.byteLength,\n chunkSize: context.chunkSize,\n contentKeyEpoch: context.contentKeyEpoch,\n contentRecordId: context.contentRecordId,\n metadataHash: context.metadataHash,\n nonceDomainHash: context.nonceDomainHash,\n organizationId: context.organizationId,\n plaintextByteLength: context.plaintextByteLength,\n }),\n },\n context.recordKey,\n plaintext,\n ),\n );\n}\n\nasync function runEncryptionHashPass(\n source: BlobByteSource,\n snapshot: BlobSourceSnapshot,\n context: BlobEncryptionContext,\n): Promise<string> {\n const objectHash = createIncrementalSha256();\n objectHash.update(context.headerBytes);\n for (let chunkIndex = 0; chunkIndex < context.partCount; chunkIndex += 1) {\n const plaintext = await readVerifiedBlobSourceChunk({\n chunkIndex,\n snapshot,\n source,\n });\n objectHash.update(await encryptBlobChunk(context, chunkIndex, plaintext));\n }\n return bytesToHex(objectHash.digest());\n}\n\nfunction createBlobEncryptionPlan(input: {\n readonly context: BlobEncryptionContext;\n readonly sha256: string;\n readonly snapshot: BlobSourceSnapshot;\n readonly source: BlobByteSource;\n}): BlobEncryptionPlan {\n const { context, sha256, snapshot, source } = input;\n const byteLength = computeBlobEncryptedByteLength({\n chunkCount: context.partCount,\n headerByteLength: context.headerBytes.byteLength,\n plaintextByteLength: context.plaintextByteLength,\n });\n return {\n byteLength,\n chunkSize: context.chunkSize,\n metadataHash: context.metadataHash,\n plaintextByteLength: context.plaintextByteLength,\n plaintextSha256: snapshot.sha256,\n sha256,\n ...createEncryptedUploadParts({\n byteLength,\n chunkSize: context.chunkSize + AES_GCM_TAG_BYTES,\n header: context.headerBytes,\n async encryptChunk(chunkIndex) {\n const plaintext = await readVerifiedBlobSourceChunk({\n chunkIndex,\n snapshot,\n source,\n });\n return encryptBlobChunk(context, chunkIndex, plaintext);\n },\n }),\n };\n}\n\nexport async function prepareBlobEncryption(\n input: PrepareBlobEncryptionInput,\n): Promise<BlobEncryptionPlan> {\n if (input.contentKey.byteLength !== AES_256_KEY_BYTES) {\n throw new Error(\"Blob content key must be 32 bytes\");\n }\n if (input.nonceSeed) {\n assertAesGcmIv(input.nonceSeed, \"Blob nonce seed is invalid\");\n }\n const chunkSize = normalizeBlobChunkSize(\n input.chunkSize ?? DEFAULT_BLOB_CHUNK_SIZE_BYTES,\n );\n const snapshot =\n input.sourceSnapshot ?? (await inspectBlobSource(input.source, chunkSize));\n const context = await createBlobEncryptionContext(input, snapshot);\n if (\n snapshot.byteLength !== context.plaintextByteLength ||\n snapshot.chunkSize !== context.chunkSize\n ) {\n throw new Error(\"Blob source snapshot does not match encryption layout\");\n }\n const sha256 = await runEncryptionHashPass(input.source, snapshot, context);\n return createBlobEncryptionPlan({\n context,\n sha256,\n snapshot,\n source: input.source,\n });\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"encryptedUploadParts.js","sourceRoot":"","sources":["encryptedUploadParts.ts"],"names":[],"mappings":"AAEA,sFAAsF;AACtF,MAAM,UAAU,0BAA0B,CAAC,KAK1C;IACC,6EAA6E;IAC7E,gFAAgF;IAChF,MAAM,QAAQ,GAAG,KAAK,CAAC,SAAS,GAAG,KAAK,CAAC,MAAM,CAAC,UAAU,CAAC;IAC3D,MAAM,SAAS,GAAG,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,GAAG,QAAQ,CAAC,CAAC;IACzD,SAAS,iBAAiB,CAAC,KAAa;QACtC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,IAAI,KAAK,IAAI,SAAS,EAAE,CAAC;YAChE,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;QAChE,CAAC;QACD,OAAO,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,KAAK,CAAC,UAAU,GAAG,KAAK,GAAG,QAAQ,CAAC,CAAC;IACjE,CAAC;IACD,OAAO;QACL,SAAS;QACT,iBAAiB;QACjB,KAAK,CAAC,WAAW,CAAC,KAAa;YAC7B,MAAM,MAAM,GAAG,IAAI,UAAU,CAAC,iBAAiB,CAAC,KAAK,CAAC,CAAC,CAAC;YACxD,MAAM,KAAK,GAAG,KAAK,GAAG,QAAQ,CAAC;YAC/B,MAAM,GAAG,GAAG,KAAK,GAAG,MAAM,CAAC,UAAU,CAAC;YACtC,IAAI,KAAK,GAAG,KAAK,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC;gBACpC,MAAM,CAAC,GAAG,CACR,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CACrE,CAAC;YACJ,CAAC;YACD,IAAI,QAAQ,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;YACxD,OAAO,QAAQ,GAAG,GAAG,EAAE,CAAC;gBACtB,MAAM,UAAU,GAAG,IAAI,CAAC,KAAK,CAC3B,CAAC,QAAQ,GAAG,KAAK,CAAC,MAAM,CAAC,UAAU,CAAC,GAAG,KAAK,CAAC,SAAS,CACvD,CAAC;gBACF,MAAM,UAAU,GACd,KAAK,CAAC,MAAM,CAAC,UAAU,GAAG,UAAU,GAAG,KAAK,CAAC,SAAS,CAAC;gBACzD,sEAAsE;gBACtE,yEAAyE;gBACzE,uEAAuE;gBACvE,MAAM,KAAK,GAAG,MAAM,KAAK,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC;gBACnD,MAAM,MAAM,GAAG,QAAQ,GAAG,UAAU,CAAC;gBACrC,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,UAAU,GAAG,MAAM,EAAE,GAAG,GAAG,QAAQ,CAAC,CAAC;gBACnE,IAAI,MAAM,IAAI,CAAC;oBACb,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;gBACrE,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,EAAE,QAAQ,GAAG,KAAK,CAAC,CAAC;gBACtE,QAAQ,IAAI,MAAM,CAAC;YACrB,CAAC;YACD,OAAO,MAAM,CAAC;QAChB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { BlobBytes } from \"../../../blobs/blobContracts\";\n\n/** Repartition the envelope without changing its encryption or buffering the file. */\nexport function createEncryptedUploadParts(input: {\n readonly byteLength: number;\n readonly chunkSize: number;\n readonly header: BlobBytes;\n readonly encryptChunk: (index: number) => Promise<BlobBytes>;\n}) {\n // Including the header in the fixed transport size keeps even a maximum-size\n // envelope within 10,000 parts. R2 requires equal sizes for all nonfinal parts.\n const partSize = input.chunkSize + input.header.byteLength;\n const partCount = Math.ceil(input.byteLength / partSize);\n function getPartByteLength(index: number): number {\n if (!Number.isInteger(index) || index < 0 || index >= partCount) {\n throw new Error(\"Blob encryption part index is out of range\");\n }\n return Math.min(partSize, input.byteLength - index * partSize);\n }\n return {\n partCount,\n getPartByteLength,\n async encryptPart(index: number): Promise<BlobBytes> {\n const output = new Uint8Array(getPartByteLength(index));\n const start = index * partSize;\n const end = start + output.byteLength;\n if (start < input.header.byteLength) {\n output.set(\n input.header.subarray(start, Math.min(end, input.header.byteLength)),\n );\n }\n let position = Math.max(start, input.header.byteLength);\n while (position < end) {\n const chunkIndex = Math.floor(\n (position - input.header.byteLength) / input.chunkSize,\n );\n const chunkStart =\n input.header.byteLength + chunkIndex * input.chunkSize;\n // Adjacent transport parts can re-read and re-encrypt a shared chunk.\n // Independent calls keep memory bounded during concurrent upload/resume;\n // the tradeoff is up to two encryptions per chunk in this upload pass.\n const chunk = await input.encryptChunk(chunkIndex);\n const offset = position - chunkStart;\n const length = Math.min(chunk.byteLength - offset, end - position);\n if (length <= 0)\n throw new Error(\"Encrypted blob chunk is shorter than its layout\");\n output.set(chunk.subarray(offset, offset + length), position - start);\n position += length;\n }\n return output;\n },\n };\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"events.js","sourceRoot":"","sources":["events.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,+BAA+B,EAC/B,0BAA0B,EAC1B,mCAAmC,EACnC,sBAAsB,EACtB,eAAe,EACf,eAAe,GAGhB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAI3D,KAAK,UAAU,2BAA2B,CAGxC,IAAU,EACV,KAOC;IAED,MAAM,SAA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ACrD,UAAU,EAAE,MAAM;YAClB,QAAQ,EAAE,KAAK,CAAC,MAAM;YACtB,eAAe,EAAE,KAAK,CAAC,eAAe;YACtC,eAAe,EAAE,+BAA+B;YAChD,eAAe,EAAE,KAAK,CAAC,MAAM;SAC9B,CAAC;QACF,YAAY,EAAE,KAAK,CAAC,SAAS,CAAC,YAAY;QAC1C,cAAc,EAAE,KAAK,CAAC,SAAS,CAAC,MAAM;QACtC,YAAY,EAAE,KAAK,CAAC,MAAM,CAAC,YAAY;QACvC,cAAc,EAAE,KAAK,CAAC,MAAM,CAAC,cAAc;QAC3C,oBAAoB,EAAE,KAAK,CAAC,MAAM,CAAC,oBAAoB;QACvD,QAAQ,EAAE,KAAK,CAAC,QAAQ;KACzB,EACD,KAAK,CAAC,MAAM,CAAC,gBAAgB,CAC9B,CAAC;IAEF,OAAO;QACL,WAAW;QACX,eAAe,EAAE,MAAM,sBAAsB,CAAC,WAAW,CAAC;KAC3D,CAAC;AACJ,CAAC","sourcesContent":["import {\n type AccessEvent,\n type AttachmentBindAccessEventBody,\n type AttachmentDetachAccessEventBody,\n CONTENT_RECORD_ENCRYPTION_SUITE,\n computeAccessEventBodyHash,\n computeContentRecordNonceDomainHash,\n computeWriteHeaderHash,\n signAccessEvent,\n signWriteHeader,\n type UnsignedAccessEvent,\n type WriteHeader,\n} from \"@tearleads/crypto\";\nimport type { ContainerManifestRef } from \"@tearleads/validators/request\";\nimport { readCanonicalJson } from \"../../../keying/canonicalJson\";\nimport { uniqueSortedStrings } from \"../../shared/readers\";\nimport type { DocumentCreateAuthor } from \"../../shared/types\";\nimport type { BlobEncryptionPlan, DocumentManifestIdentity } from \"./types\";\n\nasync function signBlobAttachmentBodyEvent<\n Body extends AttachmentBindAccessEventBody | AttachmentDetachAccessEventBody,\n>(\n body: Body,\n input: {\n author: DocumentCreateAuthor;\n blobId: string;\n eventId: string;\n manifestIdentity: DocumentManifestIdentity;\n signedAt: string;\n authorizingContainerPathRefs: readonly (readonly ContainerManifestRef[])[];\n },\n): Promise<{ body: Body; event: AccessEvent }> {\n const bodyLabel =\n body.eventType === \"attachment.bind\"\n ? \"Blob attachment bind body\"\n : \"Blob attachment detach body\";\n const unsignedEvent: UnsignedAccessEvent = {\n version: 1,\n eventId: input.eventId,\n eventType: body.eventType,\n objectKind: \"blob\",\n objectId: input.blobId,\n organizationId: input.manifestIdentity.organizationId,\n previousManifestHash: null,\n dependencyManifestHashes: uniqueSortedStrings([\n input.manifestIdentity.manifestHash,\n ...input.authorizingContainerPathRefs.flatMap((path) =>\n path.map((ref) => ref.manifestHash),\n ),\n ]),\n bodyHash: await computeAccessEventBodyHash(\n readCanonicalJson(body, bodyLabel),\n ),\n signerUserId: input.author.signerUserId,\n signerDeviceId: input.author.signerDeviceId,\n signerKeyFingerprint: input.author.signerKeyFingerprint,\n signedAt: input.signedAt,\n };\n\n return {\n body,\n event: await signAccessEvent(unsignedEvent, input.author.signerPrivateKey),\n };\n}\n\nexport async function signBlobAttachmentEvent(input: {\n author: DocumentCreateAuthor;\n bindingId: string;\n blobId: string;\n documentId: string;\n eventId: string;\n expectedBindingId: string | null;\n manifestIdentity: DocumentManifestIdentity;\n signedAt: string;\n slotId: string;\n authorizingContainerPathRefs: readonly (readonly ContainerManifestRef[])[];\n}): Promise<{ body: AttachmentBindAccessEventBody; event: AccessEvent }> {\n return signBlobAttachmentBodyEvent(\n {\n eventType: \"attachment.bind\",\n bindingId: input.bindingId,\n blobId: input.blobId,\n documentId: input.documentId,\n slotId: input.slotId,\n expectedBindingId: input.expectedBindingId,\n documentManifestHash: input.manifestIdentity.manifestHash,\n },\n input,\n );\n}\n\nexport async function signBlobAttachmentDetachEvent(input: {\n author: DocumentCreateAuthor;\n bindingId: string;\n blobId: string;\n documentId: string;\n eventId: string;\n manifestIdentity: DocumentManifestIdentity;\n signedAt: string;\n slotId: string;\n authorizingContainerPathRefs: readonly (readonly ContainerManifestRef[])[];\n}): Promise<{ body: AttachmentDetachAccessEventBody; event: AccessEvent }> {\n return signBlobAttachmentBodyEvent(\n {\n eventType: \"attachment.detach\",\n bindingId: input.bindingId,\n blobId: input.blobId,\n documentId: input.documentId,\n slotId: input.slotId,\n documentManifestHash: input.manifestIdentity.manifestHash,\n },\n input,\n );\n}\n\nexport async function signBlobAttachmentWriteHeader(input: {\n authorizingContainerPathRefs: readonly (readonly ContainerManifestRef[])[];\n author: DocumentCreateAuthor;\n blobAccessManifestHash: string;\n blobId: string;\n contentKeyEpoch: number;\n encrypted: BlobEncryptionPlan;\n manifestIdentity: DocumentManifestIdentity;\n signedAt: string;\n targetHash: string;\n}): Promise<{ writeHeader: WriteHeader; writeHeaderHash: string }> {\n const writeHeader = await signWriteHeader(\n {\n version: 1,\n dependencyManifestHashes: uniqueSortedStrings(\n input.authorizingContainerPathRefs.flatMap((path) =>\n path.map((ref) => ref.manifestHash),\n ),\n ),\n organizationId: input.manifestIdentity.organizationId,\n objectKind: \"blob\",\n objectId: input.blobId,\n accessManifestHash: input.blobAccessManifestHash,\n contentKeyEpoch: input.contentKeyEpoch,\n targetHash: input.targetHash,\n encryptionSuite: CONTENT_RECORD_ENCRYPTION_SUITE,\n contentRecordId: input.blobId,\n nonceDomainHash: await computeContentRecordNonceDomainHash({\n version: 1,\n organizationId: input.manifestIdentity.organizationId,\n objectKind: \"blob\",\n objectId: input.blobId,\n contentKeyEpoch: input.contentKeyEpoch,\n encryptionSuite: CONTENT_RECORD_ENCRYPTION_SUITE,\n contentRecordId: input.blobId,\n }),\n metadataHash: input.encrypted.metadataHash,\n ciphertextHash: input.encrypted.sha256,\n writerUserId: input.author.signerUserId,\n writerDeviceId: input.author.signerDeviceId,\n writerKeyFingerprint: input.author.signerKeyFingerprint,\n signedAt: input.signedAt,\n },\n input.author.signerPrivateKey,\n );\n\n return {\n writeHeader,\n writeHeaderHash: await computeWriteHeaderHash(writeHeader),\n };\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"projection.js","sourceRoot":"","sources":["projection.ts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C,CAAC,CAAC;IACH,IAAI,UAAU,GAAsB,IAAI,CAAC;IACzC,MAAM,iBAAiB,GAAG,KAAK,CAAC,gBAAgB,CAAC,OAAO,CAAC,MAAM,CAC7D,CAAC,QAAQ,EAAE,EAAE,CACX,QAAQ,CAAC,SAAS,KAAK,KAAK,CAAC,iBAAiB;QAC9C,QAAQ,CAAC,UAAU,KAAK,KAAK,CAAC,UAAU,CAC3C,CAAC;IAEF,IAAI,iBAAiB,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACnC,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC1E,CAAC;IAED,KAAK,MAAM,QAAQ,IAAI,iBAAiB,EAAE,CAAC;QACzC,MAAM,YAAY,GAAG,aAAa,CAAC,GAAG,CAAC,QAAQ,CAAC,mBAAmB,CAAC,CAAC;QACrE,IAAI,CAAC,YAAY,EAAE,CAAC;YAClB,SAAS;QACX,CAAC;QACD,MAAM,SAAS,GAAG,MAAM,0BAA0B,CAAC;YACjD,MAAM,EAAE,KAAK,CAAC,MAAM;YACpB,YAAY;YACZ,eAAe,EAAE,KAAK,CAAC,gBAAgB,CAAC,eAAe;YACvD,QAAQ;SACT,CAAC,CAAC;QACH,IAAI,UAAU,EAAE,CAAC;YACf,gBAAgB,CACd,UAAU,EACV,SAAS,EACT,qDAAqD,CACtD,CAAC;YACF,SAAS;QACX,CAAC;QACD,UAAU,GAAG,SAAS,CAAC;IACzB,CAAC;IAED,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;IAC7D,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["import {\n BLOB_CONTENT_KEY_WRAP_SUITE,\n type DocumentContentKeyTarget,\n wrapContentKey,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type { BlobContentKeyTargetEnvelopeRequest } from \"@tearleads/validators/request\";\nimport type {\n BlobContentKeyBundleResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { documentContainerProjections } from \"../../../keyingProjectionVerification/document/documentContainerProjections\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport { assertDocumentKekPathsCurrent } from \"../../shared/containerKek/containerKekCurrency\";\nimport {\n readLinkedContainerIdsFromDocumentManifest,\n unwrapContainerKekPath,\n verifiedDocumentWrapTargets,\n} from \"../../shared/projection\";\nimport { unwrapContentKeyTargetForKind } from \"../../shared/projection/projectionContentKeys\";\nimport {\n assertEqualBytes,\n normalizeDocumentKekTargetResponse,\n} from \"../../shared/readers\";\nimport {\n type ProjectionVerificationOptions,\n projectionVerificationOptions,\n} from \"../../shared/types\";\nimport { sortBlobTargets } from \"./readers\";\nimport type { BlobContentKeyTarget, BlobEncryptedBytesHeader } from \"./types\";\n\nfunction blobTargetsFor(\n input: { bindingId: string; documentId: string },\n targets: readonly DocumentContentKeyTarget[],\n): BlobContentKeyTarget[] {\n return sortBlobTargets(\n targets.map((target) => ({\n bindingId: input.bindingId,\n documentId: input.documentId,\n ...target,\n })),\n );\n}\n\n/**\n * The targets a blob content key may be wrapped to: the verified current\n * heads of the document's linked containers. The server list only names which\n * containers a bundle must cover.\n */\nexport function verifiedBlobWrapTargetsFromDocumentProjection(input: {\n bindingId: string;\n documentId: string;\n writerProjection: DocumentWriterProjectionResponse;\n}): BlobContentKeyTarget[] {\n return blobTargetsFor(\n input,\n verifiedDocumentWrapTargets({\n linkedContainerIds: readLinkedContainerIdsFromDocumentManifest(\n input.writerProjection,\n ),\n serverTargets: normalizeDocumentKekTargetResponse(\n input.writerProjection.documentKekTargets,\n ),\n writerProjection: input.writerProjection,\n }),\n );\n}\n\n// Not collectContainerKeksForDocumentSync: the blob upload retry classifier\n// keys on the bare \"Container writer projection KEK… could not be unwrapped\"\n// message, which the sync collector would wrap with document-sync context.\nasync function collectContainerKeks(\n input: {\n execSql?: ExecSql | undefined;\n secretKey: Uint8Array;\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<ReadonlyMap<string, Uint8Array>> {\n const keksByEpochId = new Map<string, Uint8Array>();\n\n for (const projection of documentContainerProjections(\n input.writerProjection,\n )) {\n const projectionKeks = await unwrapContainerKekPath({\n execSql: input.execSql,\n projection,\n secretKey: input.secretKey,\n ...projectionVerificationOptions(input),\n });\n\n for (const [containerKeyEpochId, keyMaterial] of projectionKeks) {\n const existing = keksByEpochId.get(containerKeyEpochId);\n if (existing) {\n assertEqualBytes(\n existing,\n keyMaterial,\n \"Blob writer projection contains conflicting container KEKs\",\n );\n continue;\n }\n keksByEpochId.set(containerKeyEpochId, keyMaterial);\n }\n }\n\n return keksByEpochId;\n}\n\nexport async function wrapBlobContentKey(\n input: {\n blobId: string;\n contentKey: Uint8Array;\n contentKeyEpoch: number;\n execSql?: ExecSql | undefined;\n secretKey: Uint8Array;\n targets: readonly BlobContentKeyTarget[];\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<BlobContentKeyTargetEnvelopeRequest[]> {\n assertDocumentKekPathsCurrent(\n input.writerProjection,\n new Set(input.targets.map((target) => target.containerId)),\n );\n const keksByEpochId = await collectContainerKeks({\n execSql: input.execSql,\n secretKey: input.secretKey,\n writerProjection: input.writerProjection,\n ...projectionVerificationOptions(input),\n });\n\n return Promise.all(\n input.targets.map(async (target) => {\n const targetKek = keksByEpochId.get(target.containerKeyEpochId);\n if (!targetKek) {\n throw new Error(\n `Blob target KEK could not be unwrapped for ${target.containerKeyEpochId}`,\n );\n }\n\n const wrapped = await wrapContentKey(input.contentKey, targetKek, {\n kind: \"Blob\",\n objectId: input.blobId,\n contentKeyEpoch: input.contentKeyEpoch,\n containerId: target.containerId,\n containerKeyEpochId: target.containerKeyEpochId,\n });\n return {\n ...target,\n wrappedKey: bytesToBase64(wrapped.ciphertext),\n wrappingMetadata: {\n suite: BLOB_CONTENT_KEY_WRAP_SUITE,\n iv: bytesToBase64(wrapped.iv),\n },\n };\n }),\n );\n}\n\nasync function unwrapBlobContentKeyTarget(input: {\n blobId: string;\n containerKek: Uint8Array;\n contentKeyEpoch: number;\n envelope: BlobContentKeyTargetEnvelopeRequest;\n}): Promise<Uint8Array> {\n return unwrapContentKeyTargetForKind({\n containerKek: input.containerKek,\n contentKeyEpoch: input.contentKeyEpoch,\n envelope: input.envelope,\n kind: \"Blob\",\n objectId: input.blobId,\n });\n}\n\nexport async function unwrapBlobContentKey(\n input: {\n /** The blob being read; its wraps must be sealed to it. */\n blobId: string;\n contentKeyBundle: BlobContentKeyBundleResponse;\n documentId: string;\n encrypted: BlobEncryptedBytesHeader;\n execSql?: ExecSql | undefined;\n expectedBindingId: string;\n secretKey: Uint8Array;\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<Uint8Array> {\n const keksByEpochId = await collectContainerKeks({\n execSql: input.execSql,\n secretKey: input.secretKey,\n writerProjection: input.writerProjection,\n ...projectionVerificationOptions(input),\n });\n let contentKey: Uint8Array | null = null;\n const attachmentTargets = input.contentKeyBundle.targets.filter(\n (envelope) =>\n envelope.bindingId === input.expectedBindingId &&\n envelope.documentId === input.documentId,\n );\n\n if (attachmentTargets.length === 0) {\n throw new Error(\"Blob content-key bundle is missing attachment target\");\n }\n\n for (const envelope of attachmentTargets) {\n const containerKek = keksByEpochId.get(envelope.containerKeyEpochId);\n if (!containerKek) {\n continue;\n }\n const unwrapped = await unwrapBlobContentKeyTarget({\n blobId: input.blobId,\n containerKek,\n contentKeyEpoch: input.contentKeyBundle.contentKeyEpoch,\n envelope,\n });\n if (contentKey) {\n assertEqualBytes(\n contentKey,\n unwrapped,\n \"Blob content-key targets unwrap to conflicting keys\",\n );\n continue;\n }\n contentKey = unwrapped;\n }\n\n if (!contentKey) {\n throw new Error(\"Blob content key could not be unwrapped\");\n }\n return contentKey;\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"readers.js","sourceRo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AU,uBAAuB,CACrC,cAAuC;IAEvC,OAAO,mBAAmB,CAAC,cAAc,CAAC,CAAC;AAC7C,CAAC;AAED,MAAM,UAAU,yBAAyB,CACvC,QAA6C;IAE7C,OAAO;QACL,SAAS,EAAE,QAAQ,CAAC,SAAS;QAC7B,UAAU,EAAE,QAAQ,CAAC,UAAU;QAC/B,WAAW,EAAE,QAAQ,CAAC,WAAW;QACjC,qBAAqB,EAAE,QAAQ,CAAC,qBAAqB;QACrD,mBAAmB,EAAE,QAAQ,CAAC,mBAAmB;QACjD,iBAAiB,EAAE,QAAQ,CAAC,iBAAiB;KAC9C,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,iBAAiB,CAC/B,KAA8B,EAC9B,KAAa;IAEb,OAAO;QACL,SAAS,EAAE,gBAAgB,CAAC,KAAK,EAAE,WAAW,EAAE,KAAK,CAAC;QACtD,UAAU,EAAE,gBAAgB,CAAC,KAAK,EAAE,YAAY,EAAE,KAAK,CAAC;QACxD,WAAW,EAAE,gBAAgB,CAAC,KAAK,EAAE,aAAa,EAAE,KAAK,CAAC;QAC1D,qBAAqB,EAAE,gBAAgB,CACrC,KAAK,EACL,uBAAuB,EACvB,KAAK,CACN;QACD,mBAAmB,EAAE,gBAAgB,CAAC,KAAK,EAAE,qBAAqB,EAAE,KAAK,CAAC;QAC1E,iBAAiB,EAAE,yBAAyB,CAC1C,KAAK,EACL,mBAAmB,EACnB,KAAK,CACN;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { parseBlobEnvelopeV2 } from \"@tearleads/crypto\";\nimport { isPlainObject as isPlainRecord } from \"@tearleads/validators/isPlainObject\";\nimport type { BlobContentKeyTargetEnvelopeRequest } from \"@tearleads/validators/request\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n readRecordPositiveInteger,\n readRecordString,\n sortTargets,\n} from \"../../shared/readers\";\nimport type {\n BlobContentKeyTarget,\n BlobEncryptedBytesRecord,\n DocumentManifestIdentity,\n} from \"./types\";\n\nfunction targetKey(target: BlobContentKeyTarget): string {\n return [\n target.bindingId,\n target.documentId,\n target.containerId,\n target.containerManifestHash,\n target.containerKeyEpochId,\n String(target.containerKeyEpoch),\n ].join(\":\");\n}\n\nexport function sortBlobTargets<T extends BlobContentKeyTarget>(\n targets: readonly T[],\n): T[] {\n return sortTargets(targets, targetKey);\n}\n\nexport function readDocumentManifestIdentity(\n writerProjection: DocumentWriterProjectionResponse,\n): DocumentManifestIdentity {\n const { documentManifest } = writerProjection;\n if (!isPlainRecord(documentManifest.state)) {\n throw new Error(\"Document writer projection manifest state is invalid\");\n }\n\n const documentId = readRecordString(\n documentManifest.state,\n \"documentId\",\n \"Document writer projection manifest state\",\n );\n if (documentId !== writerProjection.documentId) {\n throw new Error(\"Document writer projection document id is inconsistent\");\n }\n\n return {\n documentId,\n manifestHash: documentManifest.manifestHash,\n organizationId: readRecordString(\n documentManifest.state,\n \"organizationId\",\n \"Document writer projection manifest state\",\n ),\n };\n}\n\nexport function parseBlobEncryptedBytes(\n encryptedBytes: Uint8Array<ArrayBuffer>,\n): BlobEncryptedBytesRecord {\n return parseBlobEnvelopeV2(encryptedBytes);\n}\n\nexport function contentKeyTargetReference(\n envelope: BlobContentKeyTargetEnvelopeRequest,\n): BlobContentKeyTarget {\n return {\n bindingId: envelope.bindingId,\n documentId: envelope.documentId,\n containerId: envelope.containerId,\n containerManifestHash: envelope.containerManifestHash,\n containerKeyEpochId: envelope.containerKeyEpochId,\n containerKeyEpoch: envelope.containerKeyEpoch,\n };\n}\n\nexport function readBlobKekTarget(\n value: Record<string, unknown>,\n label: string,\n): BlobContentKeyTarget {\n return {\n bindingId: readRecordString(value, \"bindingId\", label),\n documentId: readRecordString(value, \"documentId\", label),\n containerId: readRecordString(value, \"containerId\", label),\n containerManifestHash: readRecordString(\n value,\n \"containerManifestHash\",\n label,\n ),\n containerKeyEpochId: readRecordString(value, \"containerKeyEpochId\", label),\n containerKeyEpoch: readRecordPositiveInteger(\n value,\n \"containerKe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C,cAAc,EAC7B,2CAA2C,CAC5C;QACH,KAAK,CAAC,QAAQ,CAAC,eAAe,KAAK,KAAK,CAAC,eAAe,EACxD,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;IACzE,CAAC;IAED,MAAM,uCAAuC,CAAC,KAAK,CAAC,CAAC;AACvD,CAAC;AAED,MAAM,UAAU,kCAAkC,CAAC,KAMlD;IACC,IACE,KAAK,CAAC,QAAQ,CAAC,SAAS,KAAK,KAAK,CAAC,SAAS;QAC5C,KAAK,CAAC,QAAQ,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM;QACtC,KAAK,CAAC,QAAQ,CAAC,UAAU,KAAK,KAAK,CAAC,UAAU;QAC9C,KAAK,CAAC,QAAQ,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM,EACtC,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;IAC3E,CAAC;AACH,CAAC","sourcesContent":["import {\n type AccessEvent,\n type AttachmentBindAccessEventBody,\n computeAccessEventHash,\n computeBlobContentKeyTargetHash,\n type WriteHeader,\n} from \"@tearleads/crypto\";\nimport type { BlobContentKeyBundleRequest } from \"@tearleads/validators/request\";\nimport type {\n BlobAttachmentBindResponse,\n BlobAttachmentDetachResponse,\n} from \"@tearleads/validators/response\";\nimport { serializeCanonical, uniqueSortedStrings } from \"../../shared/readers\";\nimport {\n contentKeyTargetReference,\n readBlobKekTarget,\n sortBlobTargets,\n} from \"./readers\";\nimport type { BlobContentKeyTarget, DocumentManifestIdentity } from \"./types\";\n\nexport async function assertBlobContentKeyBundleTargetHash(\n bundle: BlobContentKeyBundleRequest,\n): Promise<void> {\n const targetHash = await computeBlobContentKeyTargetHash(\n bundle.targets.map(contentKeyTargetReference),\n );\n if (targetHash !== bundle.targetHash) {\n throw new Error(\"Blob content-key target hash is not canonical\");\n }\n}\n\nfunction normalizedBlobContentKeyBundle(\n bundle: BlobContentKeyBundleRequest,\n): BlobContentKeyBundleRequest {\n return {\n contentKeyEpoch: bundle.contentKeyEpoch,\n targetHash: bundle.targetHash,\n targets: sortBlobTargets(bundle.targets),\n };\n}\n\nfunction assertStringSetsEqual(input: {\n actual: readonly string[];\n expected: readonly string[];\n message: 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.message);\n }\n}\n\nasync function assertBlobAttachmentBindResponseTargets(input: {\n bindingId: string;\n blobId: string;\n contentKeyBundle: BlobContentKeyBundleRequest;\n manifestIdentity: DocumentManifestIdentity;\n response: BlobAttachmentBindResponse;\n targetHash: string;\n targets: readonly BlobContentKeyTarget[];\n}): Promise<void> {\n if (input.response.contentKeyBundle.blobId !== input.blobId) {\n throw new Error(\"Blob attachment bind response blob id mismatch\");\n }\n\n const responseContentKeyBundle = normalizedBlobContentKeyBundle({\n contentKeyEpoch: input.response.contentKeyBundle.contentKeyEpoch,\n targetHash: input.response.contentKeyBundle.targetHash,\n targets: input.response.contentKeyBundle.targets,\n });\n await assertBlobContentKeyBundleTargetHash(responseContentKeyBundle);\n if (\n serializeCanonical(\n responseContentKeyBundle,\n \"Blob attachment bind response content-key bundle\",\n ) !==\n serializeCanonical(\n normalizedBlobContentKeyBundle(input.contentKeyBundle),\n \"Blob attachment bind request content-key bundle\",\n )\n ) {\n throw new Error(\n \"Blob attachment bind response content-key bundle mismatch\",\n );\n }\n\n const responseTargets = sortBlobTargets(\n input.response.blobKekTargets.targets.map((target, index) =>\n readBlobKekTarget(\n target,\n `Blob attachment bind response KEK target[${index}]`,\n ),\n ),\n );\n const expectedTargets = sortBlobTargets(input.targets);\n if (\n serializeCanonical(\n responseTargets,\n \"Blob attachment bind response KEK targets\",\n ) !==\n serializeCanonical(\n expectedTargets,\n \"Blob attachment bind request KEK targets\",\n )\n ) {\n throw new Error(\"Blob attachment bind response KEK targets mismatch\");\n }\n\n if (\n input.response.blobKekTargets.blobId !== input.blobId ||\n input.response.blobKekTargets.organizationId !==\n input.manifestIdentity.organizationId ||\n input.response.blobKekTargets.blobKeyTargetHash !== input.targetHash\n ) {\n throw new Error(\"Blob attachment bind response KEK summary mismatch\");\n }\n assertStringSetsEqual({\n actual: input.response.blobKekTargets.activeBindingIds,\n expected: [input.bindingId],\n message: \"Blob attachment bind response active bindings mismatch\",\n });\n assertStringSetsEqual({\n actual: input.response.blobKekTargets.documentManifestHashes,\n expected: [input.manifestIdentity.manifestHash],\n message: \"Blob attachment bind response document manifests mismatch\",\n });\n assertStringSetsEqual({\n actual: input.response.blobKekTargets.linkedContainerManifestHashes,\n expected: expectedTargets.map((target) => target.containerManifestHash),\n message: \"Blob attachment bind response container manifests mismatch\",\n });\n assertStringSetsEqual({\n actual: input.response.blobKekTargets.linkedContainerKeyEpochIds,\n expected: expectedTargets.map((target) => target.containerKeyEpochId),\n message: \"Blob attachment bind response container KEKs mismatch\",\n });\n}\n\nexport async function assertBlobAttachmentBindResponse(input: {\n body: AttachmentBindAccessEventBody;\n bindingId: string;\n blobAccessManifestHash: string;\n blobId: string;\n contentKeyBundle: BlobContentKeyBundleRequest;\n documentId: string;\n event: AccessEvent;\n manifestIdentity: DocumentManifestIdentity;\n response: BlobAttachmentBindResponse;\n slotId: string;\n targetHash: string;\n targets: readonly BlobContentKeyTarget[];\n writeHeader: WriteHeader;\n writeHeaderHash: string;\n}): Promise<void> {\n // This boundary is used only by the staged upload workflow: those bytes were\n // written under the same target set the bind response acknowledges. A future\n // SDK re-bind workflow must instead accept the blob's historical write\n // authorization, which can legitimately differ from the new binding set.\n if (\n !input.response.bindingEvent ||\n input.response.documentManifestHash !==\n input.manifestIdentity.manifestHash ||\n input.response.previousBindingId !== input.body.expectedBindingId ||\n serializeCanonical(\n input.response.bindingEvent.body,\n \"Blob attachment bind response event body\",\n ) !== serializeCanonical(input.body, \"Blob attachment bind request body\") ||\n serializeCanonical(\n input.response.bindingEvent.event,\n \"Blob attachment bind response event\",\n ) !==\n serializeCanonical(input.event, \"Blob attachment bind request event\") ||\n input.response.bindingEvent.eventHash !==\n (await computeAccessEventHash(input.event)) ||\n !input.response.writeHeader ||\n serializeCanonical(\n input.response.writeHeader,\n \"Blob attachment bind response write header\",\n ) !==\n serializeCanonical(input.writeHeader, \"Blob attachment write header\") ||\n input.response.blobId !== input.blobId ||\n input.response.bindingId !== input.bindingId ||\n input.response.documentId !== input.documentId ||\n input.response.slotId !== input.slotId ||\n input.response.blobKekTargets.blobAccessManifestHash !==\n input.blobAccessManifestHash ||\n !input.response.writeAuthorization ||\n serializeCanonical(\n input.response.writeAuthorization,\n \"Blob attachment bind response write authorization\",\n ) !==\n serializeCanonical(\n input.response.blobKekTargets,\n \"Blob attachment bind response KEK targets\",\n ) ||\n input.response.writeHeaderHash !== input.writeHeaderHash\n ) {\n throw new Error(\"Blob attachment bind response did not match request\");\n }\n\n await assertBlobAttachmentBindResponseTargets(input);\n}\n\nexport function assertBlobAttachmentDetachResponse(input: {\n bindingId: string;\n blobId: string;\n documentId: string;\n response: BlobAttachmentDetachResponse;\n slotId: string;\n}): void {\n if (\n input.response.bindingId !== input.bindingId ||\n input.response.blobId !== input.blobId ||\n input.response.documentId !== input.documentId ||\n input.response.slotId !== input.slotId\n ) {\n throw new Error(\"Blob attachment detach response did not match request\");\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AAqCA,MAAM,CAAC,MAAM,mCAAmC,GAC9C,wCAAwC,CAAC;AAC3C,MAAM,CAAC,MAAM,8BAA8B,GACzC,mCAAmC,CAAC;AACtC,MAAM,CAAC,MAAM,gCAAgC,GAC3C,qCAAqC,CAAC;AACxC,MAAM,CAAC,MAAM,6BAA6B,GACxC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,yCAAyC,CAAC,CAAC;AACtE,MAAM,CAAC,MAAM,YAAY,GAAG,IAAI,WAAW,EAAE,CAAC","sourcesContent":["import type {\n RequestFailureKind,\n RequestResultOptions,\n UploadMultipartBlobPartBytesRequest,\n} from \"@tearleads/api-client\";\nimport type {\n BlobContentKeyTarget,\n BlobEnvelopeHeaderRecord,\n BlobEnvelopeRecord,\n WriteHeader,\n} from \"@tearleads/crypto\";\nimport type {\n BlobAttachmentBindRequest,\n BlobAttachmentDetachRequest,\n BlobContentKeyBundleRequest,\n InitiateMultipartBlobStageRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n BlobAttachmentBindResponse,\n BlobAttachmentDetachResponse,\n BlobAttachmentSummary,\n DocumentWriterProjectionResponse,\n InitiateMultipartBlobStageResponse,\n MultipartBlobStageStatusResponse,\n UploadMultipartBlobPartResponse,\n} from \"@tearleads/validators/response\";\nimport type {\n BlobByteSourceInput,\n BlobBytes,\n} from \"../../../blobs/blobContracts\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../../keyingProjectionVerification\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport type { DocumentCreateAuthor } from \"../../shared/types\";\n\nexport const BLOB_CONTENT_RECORD_KEY_INFO_DOMAIN =\n \"tearleads.blob.content-record-key-info\";\nexport const BLOB_CONTENT_RECORD_AAD_DOMAIN =\n \"tearleads.blob.content-record-aad\";\nexport const BLOB_CONTENT_RECORD_NONCE_DOMAIN =\n \"tearleads.blob.content-record-nonce\";\nexport const BLOB_CONTENT_RECORD_HKDF_SALT: Uint8Array<ArrayBuffer> =\n new TextEncoder().encode(\"tearleads.blob.content-record-hkdf-salt\");\nexport const TEXT_ENCODER = new TextEncoder();\n\nexport interface BlobAttachmentRequestOptions {\n readonly expectedPaymentRequiredOrganizationId?: string | undefined;\n}\n\nexport interface BlobAttachmentApi {\n bindBlobAttachment(\n blobId: string,\n input: BlobAttachmentBindRequest,\n options?: BlobAttachmentRequestOptions,\n ): Promise<BlobAttachmentBindResponse | null>;\n clearWriterProjectionCaches?(): void;\n evictDocumentWriterProjection?(documentId: string): void;\n getRequestFailure?(input: {\n method: \"DELETE\" | \"GET\" | \"POST\" | \"PUT\";\n path: string;\n }): {\n readonly code?: string | undefined;\n readonly kind: RequestFailureKind;\n readonly message: string;\n readonly status: number | null;\n } | null;\n getDocumentWriterProjection(\n documentId: string,\n ): Promise<DocumentWriterProjectionResponse | null>;\n getMultipartBlobStage(\n stageId: string,\n ): Promise<MultipartBlobStageStatusResponse | null>;\n initiateMultipartBlobStage(\n input: InitiateMultipartBlobStageRequest,\n ): Promise<InitiateMultipartBlobStageResponse | null>;\n uploadMultipartBlobPartBytes(\n stageId: string,\n partNumber: number,\n input: UploadMultipartBlobPartBytesRequest,\n options?: RequestResultOptions,\n ): Promise<UploadMultipartBlobPartResponse | null>;\n}\n\nexport interface BlobAttachmentDetachApi {\n detachBlobAttachment(\n blobId: string,\n bindingId: string,\n input: BlobAttachmentDetachRequest,\n options?: BlobAttachmentRequestOptions,\n ): Promise<BlobAttachmentDetachResponse | null>;\n getDocumentWriterProjection(\n documentId: string,\n ): Promise<DocumentWriterProjectionResponse | null>;\n}\n\nexport type { BlobContentKeyTarget };\n\n/**\n * Aliases of the crypto parser's own types. The parser is shared with the API,\n * so restating these shapes here would let the two drift apart silently.\n */\nexport type BlobEncryptedBytesRecord = BlobEnvelopeRecord;\n\n/**\n * The envelope as the header establishes it. Streaming readers hold this\n * before any ciphertext is read, so it has no `chunks`: an empty array there\n * would read as an empty object rather than an unread one.\n */\nexport type BlobEncryptedBytesHeader = BlobEnvelopeHeaderRecord;\n\nexport type BlobEncryptedChunk = BlobEnvelopeRecord[\"chunks\"][number];\n\nexport interface BlobSourceSnapshot {\n readonly byteLength: number;\n readonly chunkSha256: readonly string[];\n readonly chunkSize: number;\n readonly sha256: string;\n}\n\nexport interface BlobEncryptionPlan {\n readonly byteLength: number;\n readonly chunkSize: number;\n readonly metadataHash: string;\n readonly partCount: number;\n readonly plaintextByteLength: number;\n readonly plaintextSha256: string;\n readonly sha256: string;\n encryptPart(index: number): Promise<BlobBytes>;\n getPartByteLength(index: number): number;\n}\n\nexport interface DocumentManifestIdentity {\n documentId: string;\n manifestHash: string;\n organizationId: string;\n}\n\nexport interface BlobAttachmentMaterial {\n blobAccessManifestHash: string;\n contentKeyBundle: BlobContentKeyBundleRequest;\n encrypted: BlobEncryptionPlan;\n manifestIdentity: DocumentManifestIdentity;\n targetHash: string;\n targets: BlobContentKeyTarget[];\n writerProjection: DocumentWriterProjectionResponse;\n}\n\n/**\n * Progress for an in-flight multipart blob upload.\n */\nexport interface MultipartUploadProgress {\n readonly bytesTotal: number;\n readonly bytesUploaded: number;\n readonly partsCompleted: number;\n readonly partsTotal: number;\n}\n\nexport type MultipartUploadProgressListener = (\n progress: MultipartUploadProgress,\n) => void;\n\n/**\n * Fires once a multipart stage has been opened (or resumed), with its id and\n * plaintext chunk size. Callers persist both so a later attempt can reproduce\n * the same encrypted parts and resume instead of orphaning the partial upload.\n */\nexport type MultipartStageResolvedListener = (input: {\n readonly partSize: number;\n readonly stageId: string;\n}) => void | Promise<void>;\n\nexport interface UploadDocumentAttachmentInput {\n apiClient: BlobAttachmentApi;\n author: DocumentCreateAuthor;\n blobId?: string | undefined;\n bindingId?: string | undefined;\n bytes: BlobByteSourceInput;\n contentKey?: Uint8Array | undefined;\n contentKeyEpoch?: number | undefined;\n documentId: string;\n eventId?: string | undefined;\n execSql: ExecSql;\n expectedBindingId: string | null;\n isRemoteSyncBlocked?: ((organizationId: string) => boolean) | undefined;\n // A persisted nonce seed. The plaintext digest derives the envelope IV from\n // it, then each chunk derives a unique IV. Same-source retries reproduce the\n // encrypted parts; changed bytes cannot reuse their AES-GCM nonces.\n nonceSeed?: Uint8Array | undefined;\n multipart?: MultipartBlobUploadOptions | undefined;\n onMultipartProgress?: MultipartUploadProgressListener | undefined;\n onStageResolved?: MultipartStageResolvedListener | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n signedAt?: string | undefined;\n slotId: string;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n writerProjection?: DocumentWriterProjectionResponse | undefined;\n}\n\nexport interface MultipartBlobUploadOptions {\n /** Exactly 5 MiB per plaintext encryption chunk; transport parts include envelope overhead. */\n readonly partSize: number;\n // The id of a previously opened stage to resume. When set, the upload refetches\n // that stage and skips parts the server already has instead of opening a new\n // one; if the stage is gone (expired), it falls back to a fresh stage.\n readonly resumeStageId?: string | undefined;\n readonly uploadConcurrency?: number | undefined;\n}\n\nexport interface UploadDocumentAttachmentResult {\n blobId: string;\n bindingId: string;\n request: BlobAttachmentBindRequest;\n response: BlobAttachmentBindResponse;\n sha256: string;\n byteLength: number;\n writeHeader: WriteHeader;\n writeHeaderHash: string;\n writerProjection: DocumentWriterProjectionResponse;\n}\n\nexport interface DetachDocumentAttachmentInput {\n apiClient: BlobAttachmentDetachApi;\n author: DocumentCreateAuthor;\n bindingId: string;\n blobId: string;\n documentId: string;\n eventId?: string | undefined;\n execSql: ExecSql;\n isRemoteSyncBlocked?: ((organizationId: string) => boolean) | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n signedAt?: string | undefined;\n slotId: string;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n writerProjection?: DocumentWriterProjectionResponse | undefined;\n}\n\nexport interface DetachDocumentAttachmentResult {\n request: BlobAttachmentDetachRequest;\n response: BlobAttachmentDetachResponse;\n writerProjection: DocumentWriterProjectionResponse;\n}\n\nexport interface DecryptDocumentAttachmentBlobInput {\n binding: BlobAttachmentSummary;\n encryptedBytes: BlobBytes;\n expectedDocumentId: string;\n expectedSlotId: string;\n execSql: ExecSql;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n targetSecretKey: Uint8Array;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n writerProjection: DocumentWriterProjectionResponse;\n}\n"]}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|