@tearleads/client-sdk 0.1.77 → 0.1.78
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/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/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
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"multipartUpload.js","sourceRoot":"","sources":["multipartUpload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAEzD,OAAO,EAAE,6BAA6B,EAAE,MAAM,4BAA4B,CAAC;AAC3E,OAAO,EACL,yBAAyB,EACzB,eAAe,GAChB,MAAM,kCAAkC,CAAC;AAQ1C,OAAO,EAIL,oBAAoB,EACpB,cAAc,EACd,cAAc,GACf,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,0BAA0B,EAC1B,kBAAkB,GACnB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAEnE,MAAM,oCAAoC,GAAG,CAAC,CAAC;AAC/C,MAAM,gCAAgC,GAAG,CAAC,CAAC;AAC3C,6EAA6E;AAC7E,8EAA8E;AAC9E,MAAM,mCAAmC,GAAG,CAAC,GAAG,IAAI,CAAC;AAarD,SAAS,WAAW,CAAC,KAAsB;IACzC,OAAO,kBAAkB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;AAC3C,CAAC;AAED,SAAS,oBAAoB,CAAC,KAI7B;IACC,MAAM,QAAQ,GAAG,GAAG,kBAAkB,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,WAAW,CAAC,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC;IAC/F,MAAM,aAAa,GAAG,EAAE,MAAM,EAAE,MAAe,EAAE,IAAI,EAAE,GAAG,QAAQ,SAAS,EAAE,CAAC;IAC9E,4EAA4E;IAC5E,+EAA+E;IAC/E,OAAO,KAAK,CAAC,SAAS,CAAC,iBAAiB,EAAE,CAAC,aAAa,CAAC;QACvD,CAAC,CAAC,aA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;IAC5E,oEAAoE;IACpE,OAAO,MAAM,CAAC,OAAO,CAAC;AACxB,CAAC","sourcesContent":["import { MAX_BLOB_CHUNK_COUNT } from \"@tearleads/crypto\";\nimport type { MultipartBlobStagePart } from \"@tearleads/validators/response\";\nimport { MAX_MULTIPART_BLOB_PART_BYTES } from \"@tearleads/validators/util\";\nimport {\n BLOB_TRANSFER_CONCURRENCY,\n runBlobTransfer,\n} from \"../../../data/blobs/transferPool\";\nimport type { BlobEncryptionPlan } from \"../../../data/documents/blob/shared/crypto\";\nimport type {\n BlobAttachmentApi,\n MultipartStageResolvedListener,\n MultipartUploadProgressListener,\n UploadDocumentAttachmentInput,\n} from \"../../../data/documents/blob/shared/types\";\nimport {\n type MultipartPartSources,\n type PreparedFirstPart,\n type PreparedMultipartPart,\n releasePreparedParts,\n sha256BytesHex,\n takePartSource,\n} from \"./multipartFirstParts\";\nimport {\n multipartApiFailureMessage,\n multipartStagePath,\n} from \"./multipartStageFailures\";\nimport { resolveMultipartStage } from \"./multipartStageResolution\";\n\nconst DEFAULT_MULTIPART_UPLOAD_CONCURRENCY = 4;\nconst MAX_MULTIPART_UPLOAD_CONCURRENCY = 4;\n// Fetch exposes no upload progress on every host. Allow a slow shared uplink\n// (8 KiB/s total, shared by every admitted part), plus setup/encryption time.\nconst MULTIPART_TRANSFER_BYTES_PER_SECOND = 8 * 1024;\n\ninterface MultipartPartCommit {\n readonly etag: string;\n readonly partNumber: number;\n}\n\ninterface MultipartPartUploadTask {\n readonly byteLength: number;\n readonly partIndex: number;\n readonly partNumber: number;\n}\n\nfunction pathSegment(value: number | string): string {\n return encodeURIComponent(String(value));\n}\n\nfunction multipartPartRequest(input: {\n readonly apiClient: BlobAttachmentApi;\n readonly partNumber: number;\n readonly stageId: string;\n}) {\n const basePath = `${multipartStagePath(input.stageId)}/parts/${pathSegment(input.partNumber)}`;\n const authorization = { method: \"POST\" as const, path: `${basePath}/upload` };\n // A successful authorization clears its previous failure. If a memory-store\n // byte request then fails, its separate transport diagnostic is authoritative.\n return input.apiClient.getRequestFailure?.(authorization)\n ? authorization\n : { method: \"PUT\" as const, path: `${basePath}/bytes` };\n}\n\nfunction normalizeMultipartUploadConcurrency(\n value: number | undefined,\n): number {\n if (value === undefined) {\n return DEFAULT_MULTIPART_UPLOAD_CONCURRENCY;\n }\n if (\n !Number.isInteger(value) ||\n value <= 0 ||\n value > MAX_MULTIPART_UPLOAD_CONCURRENCY\n ) {\n throw new Error(\n `Multipart blob upload concurrency must be between 1 and ${MAX_MULTIPART_UPLOAD_CONCURRENCY}`,\n );\n }\n\n return value;\n}\n\nfunction isMultipartPartCommit(\n part: MultipartPartCommit | undefined,\n): part is MultipartPartCommit {\n return part !== undefined;\n}\n\nasync function uploadMultipartPartTasks(input: {\n readonly apiClient: BlobAttachmentApi;\n readonly completeParts: (MultipartPartCommit | undefined)[];\n readonly concurrency: number;\n readonly encryption: BlobEncryptionPlan;\n readonly onPartUploaded?: (task: MultipartPartUploadTask) => void;\n readonly prepared: Map<number, PreparedFirstPart>;\n readonly sources: MultipartPartSources;\n readonly stageId: string;\n readonly tasks: readonly MultipartPartUploadTask[];\n readonly uploadId: string;\n}): Promise<void> {\n let failed = false;\n let firstFailure: { readonly error: unknown } | undefined;\n let nextTaskIndex = 0;\n const recordFailure = (error: unknown) => {\n failed = true;\n firstFailure ??= { error };\n };\n\n async function worker(): Promise<void> {\n while (!failed) {\n const task = input.tasks[nextTaskIndex];\n nextTaskIndex += 1;\n if (!task) {\n return;\n }\n\n try {\n // A first part already holds the pool slot its prepared bytes use.\n const heldPermit = input.prepared.get(task.partIndex)?.permit;\n await runBlobTransfer(\n input.apiClient,\n async (signal) => {\n if (failed) return;\n const aborted = () => recordFailure(signal.reason);\n signal.addEventListener(\"abort\", aborted, { once: true });\n try {\n const uploaded = await uploadMultipartPartBytes({\n apiClient: input.apiClient,\n encryption: input.encryption,\n prepared: input.prepared,\n sources: input.sources,\n stageId: input.stageId,\n task,\n uploadId: input.uploadId,\n signal,\n });\n signal.throwIfAborted();\n if (!uploaded) {\n failed = true;\n throw new Error(\n multipartApiFailureMessage({\n apiClient: input.apiClient,\n fallback: `Multipart blob part ${task.partNumber} upload failed for stage ${input.stageId}.`,\n request: multipartPartRequest({\n apiClient: input.apiClient,\n partNumber: task.partNumber,\n stageId: input.stageId,\n }),\n }),\n );\n }\n\n input.completeParts[task.partIndex] = {\n etag: uploaded.part.etag,\n partNumber: task.partNumber,\n };\n input.onPartUploaded?.(task);\n } catch (error) {\n // Publish failure before releasing the permit to a queued sibling.\n // Already-started parts still record success and drain through the join.\n recordFailure(error);\n } finally {\n signal.removeEventListener(\"abort\", aborted);\n }\n },\n 120_000 +\n Math.ceil(\n (task.byteLength * BLOB_TRANSFER_CONCURRENCY * 1000) /\n MULTIPART_TRANSFER_BYTES_PER_SECOND,\n ),\n heldPermit,\n );\n } catch (error) {\n recordFailure(error);\n }\n }\n }\n\n const workerCount = Math.min(input.concurrency, input.tasks.length);\n await Promise.all(Array.from({ length: workerCount }, () => worker()));\n if (firstFailure) {\n throw firstFailure.error;\n }\n}\n\n// A first part was encrypted once before the stage existed; hand its bytes\n// over (and release them) instead of encrypting it again.\nasync function encryptedPart(input: {\n readonly encryption: BlobEncryptionPlan;\n readonly prepared: Map<number, PreparedFirstPart>;\n readonly task: MultipartPartUploadTask;\n}): Promise<PreparedMultipartPart> {\n const prepared = input.prepared.get(input.task.partIndex);\n if (prepared) {\n input.prepared.delete(input.task.partIndex);\n return prepared;\n }\n const bytes = await input.encryption.encryptPart(input.task.partIndex);\n if (bytes.byteLength !== input.task.byteLength) {\n throw new Error(\n `Encrypted blob part ${input.task.partNumber} byte length mismatch: expected ${input.task.byteLength.toLocaleString()}, received ${bytes.byteLength.toLocaleString()}.`,\n );\n }\n return { bytes, sha256: await sha256BytesHex(bytes) };\n}\n\nasync function uploadMultipartPartBytes(input: {\n readonly apiClient: BlobAttachmentApi;\n readonly encryption: BlobEncryptionPlan;\n readonly prepared: Map<number, PreparedFirstPart>;\n readonly sources: MultipartPartSources;\n readonly stageId: string;\n readonly task: MultipartPartUploadTask;\n readonly uploadId: string;\n readonly signal: AbortSignal;\n}): ReturnType<BlobAttachmentApi[\"uploadMultipartBlobPartBytes\"]> {\n input.signal.throwIfAborted();\n const { bytes: encryptedPartBytes, sha256 } = await encryptedPart(input);\n input.signal.throwIfAborted();\n const source = takePartSource(input.sources, input.task.partNumber);\n const uploaded = await input.apiClient.uploadMultipartBlobPartBytes(\n input.stageId,\n input.task.partNumber,\n {\n byteLength: encryptedPartBytes.byteLength,\n encryptedBytes: encryptedPartBytes,\n sha256,\n ...(source === undefined ? {} : { source }),\n uploadId: input.uploadId,\n },\n { signal: input.signal },\n );\n input.signal.throwIfAborted();\n if (\n uploaded &&\n (uploaded.stageId !== input.stageId ||\n uploaded.uploadId !== input.uploadId ||\n uploaded.part.partNumber !== input.task.partNumber ||\n uploaded.part.byteLength !== input.task.byteLength)\n ) {\n throw new Error(\n `Multipart blob part ${input.task.partNumber} response does not match its request.`,\n );\n }\n return uploaded;\n}\n\nfunction uploadedPartsByPartNumber(\n parts: readonly MultipartBlobStagePart[],\n): ReadonlyMap<number, MultipartBlobStagePart> {\n return new Map(parts.map((part) => [part.partNumber, part]));\n}\n\ninterface MultipartUploadProgressState {\n bytesTotal: number;\n bytesUploaded: number;\n partsCompleted: number;\n partsTotal: number;\n}\n\ninterface MultipartPartPlan {\n completeParts: (MultipartPartCommit | undefined)[];\n progress: MultipartUploadProgressState;\n uploadTasks: MultipartPartUploadTask[];\n}\n\n/**\n * Plans encrypted part indices without materializing their bytes, reusing any\n * already-staged parts and seeding cumulative progress for resumed uploads.\n */\nfunction planMultipartParts(input: {\n encryption: BlobEncryptionPlan;\n uploadedParts: ReadonlyMap<number, MultipartBlobStagePart>;\n}): MultipartPartPlan {\n const { encryption, uploadedParts } = input;\n const completeParts: (MultipartPartCommit | undefined)[] = new Array(\n encryption.partCount,\n );\n const uploadTasks: MultipartPartUploadTask[] = [];\n const progress: MultipartUploadProgressState = {\n bytesTotal: 0,\n bytesUploaded: 0,\n partsCompleted: 0,\n partsTotal: encryption.partCount,\n };\n\n for (let partIndex = 0; partIndex < encryption.partCount; partIndex += 1) {\n const partNumber = partIndex + 1;\n const byteLength = encryption.getPartByteLength(partIndex);\n progress.bytesTotal += byteLength;\n const uploadedPart = uploadedParts.get(partNumber);\n if (uploadedPart?.byteLength === byteLength) {\n completeParts[partIndex] = {\n etag: uploadedPart.etag,\n partNumber,\n };\n progress.partsCompleted += 1;\n progress.bytesUploaded += byteLength;\n continue;\n }\n\n uploadTasks.push({\n byteLength,\n partIndex,\n partNumber,\n });\n }\n\n return { completeParts, progress, uploadTasks };\n}\n\nfunction assertMultipartPlanLimits(encryption: BlobEncryptionPlan): void {\n if (encryption.partCount > MAX_BLOB_CHUNK_COUNT) {\n throw new Error(\n `Multipart blob upload would require ${encryption.partCount.toLocaleString()} parts; the maximum is ${MAX_BLOB_CHUNK_COUNT.toLocaleString()} parts.`,\n );\n }\n for (let index = 0; index < encryption.partCount; index += 1) {\n if (encryption.getPartByteLength(index) > MAX_MULTIPART_BLOB_PART_BYTES) {\n throw new Error(\n `Encrypted blob part ${index + 1} exceeds the 32 MiB multipart part limit.`,\n );\n }\n }\n}\n\ntype StageMultipartBlobAttachmentInput = {\n readonly apiClient: BlobAttachmentApi;\n readonly encryption: BlobEncryptionPlan;\n readonly multipart: NonNullable<UploadDocumentAttachmentInput[\"multipart\"]>;\n readonly organizationId: string;\n readonly onMultipartProgress?: MultipartUploadProgressListener | undefined;\n readonly onStageResolved?: MultipartStageResolvedListener | undefined;\n readonly onStageUnavailable?:\n | ((stageId: string) => Promise<void>)\n | undefined;\n};\n\nexport async function stageMultipartBlobAttachment(\n input: StageMultipartBlobAttachmentInput,\n): Promise<string | null> {\n if (input.multipart.partSize !== input.encryption.chunkSize) {\n throw new Error(\n \"Multipart part size must match the encryption chunk size exactly.\",\n );\n }\n assertMultipartPlanLimits(input.encryption);\n const concurrency = normalizeMultipartUploadConcurrency(\n input.multipart.uploadConcurrency,\n );\n const resolved = await resolveMultipartStage({\n apiClient: input.apiClient,\n concurrency,\n encryption: input.encryption,\n multipart: input.multipart,\n organizationId: input.organizationId,\n onStageUnavailable: input.onStageUnavailable,\n });\n try {\n return await uploadResolvedMultipartStage(input, concurrency, resolved);\n } finally {\n // First parts no worker consumed (an early failure) return their slots.\n releasePreparedParts(resolved.prepared);\n }\n}\n\nasync function uploadResolvedMultipartStage(\n input: StageMultipartBlobAttachmentInput,\n concurrency: number,\n {\n prepared,\n sources,\n status,\n }: Awaited<ReturnType<typeof resolveMultipartStage>>,\n): Promise<string> {\n // Surface the stage id before any parts upload so the caller can persist it;\n // an upload interrupted mid-flight can then resume this same stage.\n await input.onStageResolved?.({\n partSize: input.encryption.chunkSize,\n stageId: status.stageId,\n });\n if (status.completed) {\n input.onMultipartProgress?.({\n bytesTotal: input.encryption.byteLength,\n bytesUploaded: input.encryption.byteLength,\n partsCompleted: input.encryption.partCount,\n partsTotal: input.encryption.partCount,\n });\n return status.stageId;\n }\n\n const { completeParts, progress, uploadTasks } = planMultipartParts({\n encryption: input.encryption,\n uploadedParts: uploadedPartsByPartNumber(status.uploadedParts),\n });\n\n const reportMultipartProgress = () => {\n input.onMultipartProgress?.({\n bytesTotal: progress.bytesTotal,\n bytesUploaded: progress.bytesUploaded,\n partsCompleted: progress.partsCompleted,\n partsTotal: progress.partsTotal,\n });\n };\n reportMultipartProgress();\n\n await uploadMultipartPartTasks({\n apiClient: input.apiClient,\n completeParts,\n concurrency,\n encryption: input.encryption,\n onPartUploaded: (task) => {\n progress.partsCompleted += 1;\n progress.bytesUploaded += task.byteLength;\n reportMultipartProgress();\n },\n prepared,\n sources,\n stageId: status.stageId,\n tasks: uploadTasks,\n uploadId: status.uploadId,\n });\n const committedParts = completeParts.filter(isMultipartPartCommit);\n if (committedParts.length !== input.encryption.partCount) {\n throw new Error(\n `Multipart blob upload incomplete for stage ${status.stageId}: committed ${committedParts.length.toLocaleString()} of ${input.encryption.partCount.toLocaleString()} parts.`,\n );\n }\n\n // Binding the attachment completes the stage: the API assembles these parts\n // and verifies the object's length and SHA-256 before promoting it.\n return status.stageId;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"multipartUpload.js","sourceRoot":"","sources":["multipartUpload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAEzD,OAAO,EAAE,6BAA6B,EAAE,MAAM,4BAA4B,CAAC;AAQ3E,OAAO,EACL,yBAAyB,EACzB,eAAe,GAChB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAIL,oBAAoB,EACpB,cAAc,EACd,cAAc,GACf,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,0BAA0B,EAC1B,kBAAkB,GACnB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAEnE,MAAM,oCAAoC,GAAG,CAAC,CAAC;AAC/C,MAAM,gCAAgC,GAAG,CAAC,CAAC;AAC3C,6EAA6E;AAC7E,8EAA8E;AAC9E,MAAM,mCAAmC,GAAG,CAAC,GAAG,IAAI,CAAC;AAarD,SAAS,WAAW,CAAC,KAAsB;IACzC,OAAO,kBAAkB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;AAC3C,CAAC;AAED,SAAS,oBAAoB,CAAC,KAI7B;IACC,MAAM,QAAQ,GAAG,GAAG,kBAAkB,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,WAAW,CAAC,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC;IAC/F,MAAM,aAAa,GAAG,EAAE,MAAM,EAAE,MAAe,EAAE,IAAI,EAAE,GAAG,QAAQ,SAAS,EAAE,CAAC;IAC9E,4EAA4E;IAC5E,+EAA+E;IAC/E,OAAO,KAAK,CAAC,SAAS,CAAC,iBAAiB,EAAE,CAAC,aAAa,CAAC;QACvD,CAAC,CAAC,aAAa;QACf,CAAC,CAAC,EAA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AAO,MAAM,CAAC,OAAO,CAAC;AACxB,CAAC","sourcesContent":["import { MAX_BLOB_CHUNK_COUNT } from \"@tearleads/crypto\";\nimport type { MultipartBlobStagePart } from \"@tearleads/validators/response\";\nimport { MAX_MULTIPART_BLOB_PART_BYTES } from \"@tearleads/validators/util\";\nimport type { BlobEncryptionPlan } from \"../../../data/blobs/attachments/crypto\";\nimport type {\n BlobAttachmentApi,\n MultipartStageResolvedListener,\n MultipartUploadProgressListener,\n UploadDocumentAttachmentInput,\n} from \"../../../data/blobs/attachments/types\";\nimport {\n BLOB_TRANSFER_CONCURRENCY,\n runBlobTransfer,\n} from \"../../../data/blobs/transferPool\";\nimport {\n type MultipartPartSources,\n type PreparedFirstPart,\n type PreparedMultipartPart,\n releasePreparedParts,\n sha256BytesHex,\n takePartSource,\n} from \"./multipartFirstParts\";\nimport {\n multipartApiFailureMessage,\n multipartStagePath,\n} from \"./multipartStageFailures\";\nimport { resolveMultipartStage } from \"./multipartStageResolution\";\n\nconst DEFAULT_MULTIPART_UPLOAD_CONCURRENCY = 4;\nconst MAX_MULTIPART_UPLOAD_CONCURRENCY = 4;\n// Fetch exposes no upload progress on every host. Allow a slow shared uplink\n// (8 KiB/s total, shared by every admitted part), plus setup/encryption time.\nconst MULTIPART_TRANSFER_BYTES_PER_SECOND = 8 * 1024;\n\ninterface MultipartPartCommit {\n readonly etag: string;\n readonly partNumber: number;\n}\n\ninterface MultipartPartUploadTask {\n readonly byteLength: number;\n readonly partIndex: number;\n readonly partNumber: number;\n}\n\nfunction pathSegment(value: number | string): string {\n return encodeURIComponent(String(value));\n}\n\nfunction multipartPartRequest(input: {\n readonly apiClient: BlobAttachmentApi;\n readonly partNumber: number;\n readonly stageId: string;\n}) {\n const basePath = `${multipartStagePath(input.stageId)}/parts/${pathSegment(input.partNumber)}`;\n const authorization = { method: \"POST\" as const, path: `${basePath}/upload` };\n // A successful authorization clears its previous failure. If a memory-store\n // byte request then fails, its separate transport diagnostic is authoritative.\n return input.apiClient.getRequestFailure?.(authorization)\n ? authorization\n : { method: \"PUT\" as const, path: `${basePath}/bytes` };\n}\n\nfunction normalizeMultipartUploadConcurrency(\n value: number | undefined,\n): number {\n if (value === undefined) {\n return DEFAULT_MULTIPART_UPLOAD_CONCURRENCY;\n }\n if (\n !Number.isInteger(value) ||\n value <= 0 ||\n value > MAX_MULTIPART_UPLOAD_CONCURRENCY\n ) {\n throw new Error(\n `Multipart blob upload concurrency must be between 1 and ${MAX_MULTIPART_UPLOAD_CONCURRENCY}`,\n );\n }\n\n return value;\n}\n\nfunction isMultipartPartCommit(\n part: MultipartPartCommit | undefined,\n): part is MultipartPartCommit {\n return part !== undefined;\n}\n\nasync function uploadMultipartPartTasks(input: {\n readonly apiClient: BlobAttachmentApi;\n readonly completeParts: (MultipartPartCommit | undefined)[];\n readonly concurrency: number;\n readonly encryption: BlobEncryptionPlan;\n readonly onPartUploaded?: (task: MultipartPartUploadTask) => void;\n readonly prepared: Map<number, PreparedFirstPart>;\n readonly sources: MultipartPartSources;\n readonly stageId: string;\n readonly tasks: readonly MultipartPartUploadTask[];\n readonly uploadId: string;\n}): Promise<void> {\n let failed = false;\n let firstFailure: { readonly error: unknown } | undefined;\n let nextTaskIndex = 0;\n const recordFailure = (error: unknown) => {\n failed = true;\n firstFailure ??= { error };\n };\n\n async function worker(): Promise<void> {\n while (!failed) {\n const task = input.tasks[nextTaskIndex];\n nextTaskIndex += 1;\n if (!task) {\n return;\n }\n\n try {\n // A first part already holds the pool slot its prepared bytes use.\n const heldPermit = input.prepared.get(task.partIndex)?.permit;\n await runBlobTransfer(\n input.apiClient,\n async (signal) => {\n if (failed) return;\n const aborted = () => recordFailure(signal.reason);\n signal.addEventListener(\"abort\", aborted, { once: true });\n try {\n const uploaded = await uploadMultipartPartBytes({\n apiClient: input.apiClient,\n encryption: input.encryption,\n prepared: input.prepared,\n sources: input.sources,\n stageId: input.stageId,\n task,\n uploadId: input.uploadId,\n signal,\n });\n signal.throwIfAborted();\n if (!uploaded) {\n failed = true;\n throw new Error(\n multipartApiFailureMessage({\n apiClient: input.apiClient,\n fallback: `Multipart blob part ${task.partNumber} upload failed for stage ${input.stageId}.`,\n request: multipartPartRequest({\n apiClient: input.apiClient,\n partNumber: task.partNumber,\n stageId: input.stageId,\n }),\n }),\n );\n }\n\n input.completeParts[task.partIndex] = {\n etag: uploaded.part.etag,\n partNumber: task.partNumber,\n };\n input.onPartUploaded?.(task);\n } catch (error) {\n // Publish failure before releasing the permit to a queued sibling.\n // Already-started parts still record success and drain through the join.\n recordFailure(error);\n } finally {\n signal.removeEventListener(\"abort\", aborted);\n }\n },\n 120_000 +\n Math.ceil(\n (task.byteLength * BLOB_TRANSFER_CONCURRENCY * 1000) /\n MULTIPART_TRANSFER_BYTES_PER_SECOND,\n ),\n heldPermit,\n );\n } catch (error) {\n recordFailure(error);\n }\n }\n }\n\n const workerCount = Math.min(input.concurrency, input.tasks.length);\n await Promise.all(Array.from({ length: workerCount }, () => worker()));\n if (firstFailure) {\n throw firstFailure.error;\n }\n}\n\n// A first part was encrypted once before the stage existed; hand its bytes\n// over (and release them) instead of encrypting it again.\nasync function encryptedPart(input: {\n readonly encryption: BlobEncryptionPlan;\n readonly prepared: Map<number, PreparedFirstPart>;\n readonly task: MultipartPartUploadTask;\n}): Promise<PreparedMultipartPart> {\n const prepared = input.prepared.get(input.task.partIndex);\n if (prepared) {\n input.prepared.delete(input.task.partIndex);\n return prepared;\n }\n const bytes = await input.encryption.encryptPart(input.task.partIndex);\n if (bytes.byteLength !== input.task.byteLength) {\n throw new Error(\n `Encrypted blob part ${input.task.partNumber} byte length mismatch: expected ${input.task.byteLength.toLocaleString()}, received ${bytes.byteLength.toLocaleString()}.`,\n );\n }\n return { bytes, sha256: await sha256BytesHex(bytes) };\n}\n\nasync function uploadMultipartPartBytes(input: {\n readonly apiClient: BlobAttachmentApi;\n readonly encryption: BlobEncryptionPlan;\n readonly prepared: Map<number, PreparedFirstPart>;\n readonly sources: MultipartPartSources;\n readonly stageId: string;\n readonly task: MultipartPartUploadTask;\n readonly uploadId: string;\n readonly signal: AbortSignal;\n}): ReturnType<BlobAttachmentApi[\"uploadMultipartBlobPartBytes\"]> {\n input.signal.throwIfAborted();\n const { bytes: encryptedPartBytes, sha256 } = await encryptedPart(input);\n input.signal.throwIfAborted();\n const source = takePartSource(input.sources, input.task.partNumber);\n const uploaded = await input.apiClient.uploadMultipartBlobPartBytes(\n input.stageId,\n input.task.partNumber,\n {\n byteLength: encryptedPartBytes.byteLength,\n encryptedBytes: encryptedPartBytes,\n sha256,\n ...(source === undefined ? {} : { source }),\n uploadId: input.uploadId,\n },\n { signal: input.signal },\n );\n input.signal.throwIfAborted();\n if (\n uploaded &&\n (uploaded.stageId !== input.stageId ||\n uploaded.uploadId !== input.uploadId ||\n uploaded.part.partNumber !== input.task.partNumber ||\n uploaded.part.byteLength !== input.task.byteLength)\n ) {\n throw new Error(\n `Multipart blob part ${input.task.partNumber} response does not match its request.`,\n );\n }\n return uploaded;\n}\n\nfunction uploadedPartsByPartNumber(\n parts: readonly MultipartBlobStagePart[],\n): ReadonlyMap<number, MultipartBlobStagePart> {\n return new Map(parts.map((part) => [part.partNumber, part]));\n}\n\ninterface MultipartUploadProgressState {\n bytesTotal: number;\n bytesUploaded: number;\n partsCompleted: number;\n partsTotal: number;\n}\n\ninterface MultipartPartPlan {\n completeParts: (MultipartPartCommit | undefined)[];\n progress: MultipartUploadProgressState;\n uploadTasks: MultipartPartUploadTask[];\n}\n\n/**\n * Plans encrypted part indices without materializing their bytes, reusing any\n * already-staged parts and seeding cumulative progress for resumed uploads.\n */\nfunction planMultipartParts(input: {\n encryption: BlobEncryptionPlan;\n uploadedParts: ReadonlyMap<number, MultipartBlobStagePart>;\n}): MultipartPartPlan {\n const { encryption, uploadedParts } = input;\n const completeParts: (MultipartPartCommit | undefined)[] = new Array(\n encryption.partCount,\n );\n const uploadTasks: MultipartPartUploadTask[] = [];\n const progress: MultipartUploadProgressState = {\n bytesTotal: 0,\n bytesUploaded: 0,\n partsCompleted: 0,\n partsTotal: encryption.partCount,\n };\n\n for (let partIndex = 0; partIndex < encryption.partCount; partIndex += 1) {\n const partNumber = partIndex + 1;\n const byteLength = encryption.getPartByteLength(partIndex);\n progress.bytesTotal += byteLength;\n const uploadedPart = uploadedParts.get(partNumber);\n if (uploadedPart?.byteLength === byteLength) {\n completeParts[partIndex] = {\n etag: uploadedPart.etag,\n partNumber,\n };\n progress.partsCompleted += 1;\n progress.bytesUploaded += byteLength;\n continue;\n }\n\n uploadTasks.push({\n byteLength,\n partIndex,\n partNumber,\n });\n }\n\n return { completeParts, progress, uploadTasks };\n}\n\nfunction assertMultipartPlanLimits(encryption: BlobEncryptionPlan): void {\n if (encryption.partCount > MAX_BLOB_CHUNK_COUNT) {\n throw new Error(\n `Multipart blob upload would require ${encryption.partCount.toLocaleString()} parts; the maximum is ${MAX_BLOB_CHUNK_COUNT.toLocaleString()} parts.`,\n );\n }\n for (let index = 0; index < encryption.partCount; index += 1) {\n if (encryption.getPartByteLength(index) > MAX_MULTIPART_BLOB_PART_BYTES) {\n throw new Error(\n `Encrypted blob part ${index + 1} exceeds the 32 MiB multipart part limit.`,\n );\n }\n }\n}\n\ntype StageMultipartBlobAttachmentInput = {\n readonly apiClient: BlobAttachmentApi;\n readonly encryption: BlobEncryptionPlan;\n readonly multipart: NonNullable<UploadDocumentAttachmentInput[\"multipart\"]>;\n readonly organizationId: string;\n readonly onMultipartProgress?: MultipartUploadProgressListener | undefined;\n readonly onStageResolved?: MultipartStageResolvedListener | undefined;\n readonly onStageUnavailable?:\n | ((stageId: string) => Promise<void>)\n | undefined;\n};\n\nexport async function stageMultipartBlobAttachment(\n input: StageMultipartBlobAttachmentInput,\n): Promise<string | null> {\n if (input.multipart.partSize !== input.encryption.chunkSize) {\n throw new Error(\n \"Multipart part size must match the encryption chunk size exactly.\",\n );\n }\n assertMultipartPlanLimits(input.encryption);\n const concurrency = normalizeMultipartUploadConcurrency(\n input.multipart.uploadConcurrency,\n );\n const resolved = await resolveMultipartStage({\n apiClient: input.apiClient,\n concurrency,\n encryption: input.encryption,\n multipart: input.multipart,\n organizationId: input.organizationId,\n onStageUnavailable: input.onStageUnavailable,\n });\n try {\n return await uploadResolvedMultipartStage(input, concurrency, resolved);\n } finally {\n // First parts no worker consumed (an early failure) return their slots.\n releasePreparedParts(resolved.prepared);\n }\n}\n\nasync function uploadResolvedMultipartStage(\n input: StageMultipartBlobAttachmentInput,\n concurrency: number,\n {\n prepared,\n sources,\n status,\n }: Awaited<ReturnType<typeof resolveMultipartStage>>,\n): Promise<string> {\n // Surface the stage id before any parts upload so the caller can persist it;\n // an upload interrupted mid-flight can then resume this same stage.\n await input.onStageResolved?.({\n partSize: input.encryption.chunkSize,\n stageId: status.stageId,\n });\n if (status.completed) {\n input.onMultipartProgress?.({\n bytesTotal: input.encryption.byteLength,\n bytesUploaded: input.encryption.byteLength,\n partsCompleted: input.encryption.partCount,\n partsTotal: input.encryption.partCount,\n });\n return status.stageId;\n }\n\n const { completeParts, progress, uploadTasks } = planMultipartParts({\n encryption: input.encryption,\n uploadedParts: uploadedPartsByPartNumber(status.uploadedParts),\n });\n\n const reportMultipartProgress = () => {\n input.onMultipartProgress?.({\n bytesTotal: progress.bytesTotal,\n bytesUploaded: progress.bytesUploaded,\n partsCompleted: progress.partsCompleted,\n partsTotal: progress.partsTotal,\n });\n };\n reportMultipartProgress();\n\n await uploadMultipartPartTasks({\n apiClient: input.apiClient,\n completeParts,\n concurrency,\n encryption: input.encryption,\n onPartUploaded: (task) => {\n progress.partsCompleted += 1;\n progress.bytesUploaded += task.byteLength;\n reportMultipartProgress();\n },\n prepared,\n sources,\n stageId: status.stageId,\n tasks: uploadTasks,\n uploadId: status.uploadId,\n });\n const committedParts = completeParts.filter(isMultipartPartCommit);\n if (committedParts.length !== input.encryption.partCount) {\n throw new Error(\n `Multipart blob upload incomplete for stage ${status.stageId}: committed ${committedParts.length.toLocaleString()} of ${input.encryption.partCount.toLocaleString()} parts.`,\n );\n }\n\n // Binding the attachment completes the stage: the API assembles these parts\n // and verifies the object's length and SHA-256 before promoting it.\n return status.stageId;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attachmentBindingVerification.js","sourceRoot":"","sources":["attachmentBindingVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,iBAAiB,EACjB,mBAAmB,GACpB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAGL,eAAe,EACf,gBAAgB,EAChB,uBAAuB,EACvB,0BAA0B,GAC3B,MAAM,4CAA4C,CAAC;AAEpD,MAAM,CAAC,KAAK,UAAU,+BAA+B,CAAC,KAarD;IACC,IAAI,CAAC,KAAK,CAAC,aAAa,EAAE,CAAC;QACzB,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC1E,CAAC;IACD,IACE,CAAC,KAAK,CAAC,OAAO,CAAC,YAAY;QAC3B,CAAC,KAAK,CAAC,OAAO,CAAC,oBAAoB;QACnC,KAAK,CAAC,OAAO,CAAC,iBAAiB,KAAK,SAAS,EAC7C,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;IAC3E,CAAC;IACD,MAAM,WAAW,GAAG,mBAAmB,CACrC,KAAK,CAAC,OAAO,CAAC,YAAY,EAC1B,iCAAiC,CAClC,CAAC;IACF,MAAM,KAAK,GAAG,eAAe,CAC3B,uBAAuB,CACrB,WAAW,EACX,OAAO,EACP,iCAAiC,CAClC,EACD,0BAA0B,CAC3B,CAAC;IACF,MAAM,MAAM,GAAG,MAAM,KAAK,CAAC,wBAAwB,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IACxE,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,IAAI,KAAK,CAAC,mDAAmD,CAAC,CAAC;IACvE,CAAC;IACD,MAAM,gBAAgB,GAAG,KAAK,C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AW,EACX,iCAAiC,CAClC,KAAK,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC,SAAS,EACpC,CAAC;QACD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,uDAAuD,CACxD,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n verifyAttachmentBindingEvent,\n} from \"@tearleads/crypto\";\nimport type { DecryptDocumentAttachmentBlobInput } from \"../../../data/
|
|
1
|
+
{"version":3,"file":"attachmentBindingVerification.js","sourceRoot":"","sources":["attachmentBindingVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,iBAAiB,EACjB,mBAAmB,GACpB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAGL,eAAe,EACf,gBAAgB,EAChB,uBAAuB,EACvB,0BAA0B,GAC3B,MAAM,4CAA4C,CAAC;AAEpD,MAAM,CAAC,KAAK,UAAU,+BAA+B,CAAC,KAarD;IACC,IAAI,CAAC,KAAK,CAAC,aAAa,EAAE,CAAC;QACzB,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC1E,CAAC;IACD,IACE,CAAC,KAAK,CAAC,OAAO,CAAC,YAAY;QAC3B,CAAC,KAAK,CAAC,OAAO,CAAC,oBAAoB;QACnC,KAAK,CAAC,OAAO,CAAC,iBAAiB,KAAK,SAAS,EAC7C,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;IAC3E,CAAC;IACD,MAAM,WAAW,GAAG,mBAAmB,CACrC,KAAK,CAAC,OAAO,CAAC,YAAY,EAC1B,iCAAiC,CAClC,CAAC;IACF,MAAM,KAAK,GAAG,eAAe,CAC3B,uBAAuB,CACrB,WAAW,EACX,OAAO,EACP,iCAAiC,CAClC,EACD,0BAA0B,CAC3B,CAAC;IACF,MAAM,MAAM,GAAG,MAAM,KAAK,CAAC,wBA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CAAC,EAAE,EAAE,CAAC;QACjB,MAAM,QAAQ,CAAC,KAAK,CAAC;IACvB,CAAC;IACD,IACE,QAAQ,CAAC,KAAK,CAAC,MAAM,KAAK,KAAK,CAAC,cAAc;QAC9C,gBAAgB,CACd,WAAW,EACX,WAAW,EACX,iCAAiC,CAClC,KAAK,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC,SAAS,EACpC,CAAC;QACD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,uDAAuD,CACxD,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n verifyAttachmentBindingEvent,\n} from \"@tearleads/crypto\";\nimport type { DecryptDocumentAttachmentBlobInput } from \"../../../data/blobs/attachments/types\";\nimport {\n readCanonicalJson,\n readCanonicalRecord,\n} from \"../../../data/keying/canonicalJson\";\nimport {\n type DocumentWriterProjectionAuthorization,\n type ProjectionUserKeyResolver,\n readAccessEvent,\n readRecordString,\n readRequiredRecordValue,\n resolveEventContainerPaths,\n} from \"../../../data/keyingProjectionVerification\";\n\nexport async function assertAttachmentBindingVerified(input: {\n readonly authorization: DocumentWriterProjectionAuthorization | undefined;\n readonly binding: Pick<\n DecryptDocumentAttachmentBlobInput[\"binding\"],\n | \"bindingEvent\"\n | \"documentManifestHash\"\n | \"previousBindingId\"\n | \"bindingId\"\n | \"blobId\"\n >;\n readonly expectedDocumentId: string;\n readonly expectedSlotId: string;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n}): Promise<void> {\n if (!input.authorization) {\n throw new Error(\"Attachment binding lacks verified document authority\");\n }\n if (\n !input.binding.bindingEvent ||\n !input.binding.documentManifestHash ||\n input.binding.previousBindingId === undefined\n ) {\n throw new Error(\"Attachment binding lacks signed verification material\");\n }\n const eventBundle = readCanonicalRecord(\n input.binding.bindingEvent,\n \"Attachment binding event bundle\",\n );\n const event = readAccessEvent(\n readRequiredRecordValue(\n eventBundle,\n \"event\",\n \"Attachment binding event bundle\",\n ),\n \"Attachment binding event\",\n );\n const signer = await input.resolveProjectionUserKey(event.signerUserId);\n if (!signer) {\n throw new Error(\"Attachment binding signer identity is unavailable\");\n }\n const documentManifest = input.authorization.documentManifestByHash.get(\n input.binding.documentManifestHash,\n );\n if (!documentManifest) {\n throw new Error(\"Attachment binding document manifest is unverified\");\n }\n const { dependencyContainerPaths } = resolveEventContainerPaths({\n containerPathByManifestHash:\n input.authorization.containerPathByManifestHash,\n dependencyManifestHashes: event.dependencyManifestHashes.filter(\n (hash) => hash !== input.binding.documentManifestHash,\n ),\n });\n const verified = await verifyAttachmentBindingEvent({\n authorizationMembership: \"referenced\",\n authorizingContainerPaths: dependencyContainerPaths,\n body: readCanonicalJson(\n readRequiredRecordValue(\n eventBundle,\n \"body\",\n \"Attachment binding event bundle\",\n ),\n \"Attachment binding event body\",\n ),\n documentManifest,\n event,\n expectedBindingId: input.binding.bindingId,\n expectedBlobId: input.binding.blobId,\n expectedDocumentId: input.expectedDocumentId,\n expectedDocumentManifestHash: input.binding.documentManifestHash,\n expectedPreviousBindingId: input.binding.previousBindingId,\n principalPolicies: input.authorization.principalPolicies,\n signerPublicKey: signer.signingPublicKey,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n if (\n verified.value.slotId !== input.expectedSlotId ||\n readRecordString(\n eventBundle,\n \"eventHash\",\n \"Attachment binding event bundle\",\n ) !== verified.value.event.eventHash\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Attachment binding slot or event hash is inconsistent\",\n );\n }\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { AES_GCM_TAG_BYTES, blobChunkPlaintextByteLength, bytesToHex, } from "../../../internal/crypto/index.js";
|
|
2
|
-
import { createBlobEnvelopeStream } from "../../../data/
|
|
2
|
+
import { createBlobEnvelopeStream } from "../../../data/blobs/attachments/blobEnvelopeStream.js";
|
|
3
3
|
import { assertEqualBytes, readWriteHeader, } from "../../../data/documents/shared/readers.js";
|
|
4
4
|
import { decryptBlobChunk } from "../hydration/blobChunkDecryption.js";
|
|
5
5
|
import { prepareDocumentAttachmentBlobDecryption } from "../hydration/decrypt.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attachmentKeyAuthenticator.js","sourceRoot":"","sources":["attachmentKeyAuthenticator.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EACjB,4BAA4B,EAC5B,UAAU,GACX,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,wBAAwB,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"attachmentKeyAuthenticator.js","sourceRoot":"","sources":["attachmentKeyAuthenticator.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EACjB,4BAA4B,EAC5B,UAAU,GACX,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,wBAAwB,EAAE,MAAM,oDAAoD,CAAC;AAK9F,OAAO,EACL,gBAAgB,EAChB,eAAe,GAChB,MAAM,wCAAwC,CAAC;AAEhD,OAAO,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAC;AACpE,OAAO,EAAE,uCAAuC,EAAE,MAAM,sBAAsB,CAAC;AAC/E,OAAO,EAAE,2BAA2B,EAAE,MAAM,uBAAuB,CAAC;AAapE,MAAM,iBAAiB,GAAG,CACxB,GAA+B,EAC/B,UAAkB,EAClB,EAAE,CACF,2BAA2B,CACzB,GAAG,EACH,UAAU,EACV,uCAAuC,CACxC,CAAC;AAEJ,KAAK,UAAU,yBAAyB,CACtC,GAA+B,EAC/B,KAAyB,EACzB,SAAsB;IAEtB,MAAM,IAAI,GAAG,MAAM,GAAG,CAAC,YAAY,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IAC1D,IAAI,CAAC,IAAI;QACP,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;IACxE,MAAM,IAAI,GAAG,IAAI,QAAQ,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC;I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} from \"@tearleads/crypto\";\nimport { createBlobEnvelopeStream } from \"../../../data/blobs/attachments/blobEnvelopeStream\";\nimport type {\n BlobEncryptedBytesHeader,\n DecryptDocumentAttachmentBlobInput,\n} from \"../../../data/blobs/attachments/types\";\nimport {\n assertEqualBytes,\n readWriteHeader,\n} from \"../../../data/documents/shared/readers\";\nimport type { DocumentLinkSetMutationApi } from \"../../../data/documents/shared/types\";\nimport { decryptBlobChunk } from \"../hydration/blobChunkDecryption\";\nimport { prepareDocumentAttachmentBlobDecryption } from \"../hydration/decrypt\";\nimport { createAttachmentProofReader } from \"./attachmentDecryptor\";\n\ntype AttachmentKeyInput = Omit<\n DecryptDocumentAttachmentBlobInput,\n \"encryptedBytes\"\n>;\ntype VerifiedKey = {\n ciphertextHash: string;\n encrypted: BlobEncryptedBytesHeader;\n contentKey: Uint8Array;\n};\ntype ProofReader = ReturnType<typeof createProofReader>;\n\nconst createProofReader = (\n api: DocumentLinkSetMutationApi,\n documentId: string,\n) =>\n createAttachmentProofReader(\n api,\n documentId,\n prepareDocumentAttachmentBlobDecryption,\n );\n\nasync function authenticateAttachmentKey(\n api: DocumentLinkSetMutationApi,\n input: AttachmentKeyInput,\n readProof: ProofReader,\n): Promise<VerifiedKey> {\n const blob = await api.getBlobBytes(input.binding.blobId);\n if (!blob)\n throw new Error(\"Attachment ciphertext is unavailable for relinking\");\n const body = new Response(blob.encryptedBytes).body;\n if (!body) throw new Error(\"Attachment ciphertext stream is unavailable\");\n const source = createBlobEnvelopeStream(body);\n try {\n const encrypted = await source.readHeader();\n // A missing citation can refresh the proof before consuming ciphertext.\n const context = await readProof({ ...input, encrypted });\n for (let index = 0; index < encrypted.chunkCount; index++) {\n const plaintextByteLength = blobChunkPlaintextByteLength({\n chunkCount: encrypted.chunkCount,\n chunkIndex: index,\n chunkSize: encrypted.chunkSize,\n plaintextByteLength: encrypted.byteLength,\n });\n const ciphertext = await source.read(\n plaintextByteLength + AES_GCM_TAG_BYTES,\n );\n await decryptBlobChunk({\n ...context,\n encrypted,\n expectedBlobId: input.binding.blobId,\n chunk: { ciphertext, index, plaintextByteLength },\n });\n }\n const header = readWriteHeader(\n input.binding.writeHeader,\n \"Attachment blob write header\",\n );\n if (bytesToHex(await source.finish()) !== header.ciphertextHash)\n throw new Error(\"Attachment blob write header does not match ciphertext\");\n return {\n encrypted,\n contentKey: context.contentKey,\n ciphertextHash: header.ciphertextHash,\n };\n } finally {\n await source.close();\n }\n}\n\n/** Shared blobs retain only authenticated keys and metadata, never their bytes. */\nexport function createAttachmentKeyAuthenticator(\n api: DocumentLinkSetMutationApi,\n documentId: string,\n) {\n const readProof = createProofReader(api, documentId);\n const authenticated = new Map<string, Promise<VerifiedKey>>();\n return async (input: AttachmentKeyInput): Promise<Uint8Array> => {\n const existing = authenticated.get(input.binding.blobId);\n if (!existing) {\n const pending = authenticateAttachmentKey(api, input, readProof);\n authenticated.set(input.binding.blobId, pending);\n return (await pending).contentKey;\n }\n const cached = await existing;\n const context = await readProof({ ...input, encrypted: cached.encrypted });\n if (\n readWriteHeader(input.binding.writeHeader, \"Attachment blob write header\")\n .ciphertextHash !== cached.ciphertextHash\n )\n throw new Error(\"Attachment blob write header does not match ciphertext\");\n assertEqualBytes(\n context.contentKey,\n cached.contentKey,\n \"Attachment bindings contain conflicting blob keys\",\n );\n return cached.contentKey;\n };\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { KeyingVerificationError } from "../../../internal/crypto/index.js";
|
|
2
|
-
import { assertBlobContentKeyBundleTargetHash } from "../../../data/
|
|
2
|
+
import { assertBlobContentKeyBundleTargetHash } from "../../../data/blobs/attachments/responses.js";
|
|
3
3
|
import { assertDocumentWriterProjectionConsistent } from "../../../data/documents/shared/projection/index.js";
|
|
4
4
|
import { projectionVerificationOptions } from "../../../data/documents/shared/types.js";
|
|
5
5
|
import { requireProjectionUserKeyResolver, } from "../../../data/keyingProjectionVerification/index.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retainedAttachmentVerification.js","sourceRoot":"","sources":["retainedAttachmentVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,oCAAoC,EAAE,MAAM
|
|
1
|
+
{"version":3,"file":"retainedAttachmentVerification.js","sourceRoot":"","sources":["retainedAttachmentVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,2CAA2C,CAAC;AAEjG,OAAO,EAAE,wCAAwC,EAAE,MAAM,2CAA2C,CAAC;AACrG,OAAO,EAAE,6BAA6B,EAAE,MAAM,sCAAsC,CAAC;AACrF,OAAO,EAEL,gCAAgC,GACjC,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,+BAA+B,EAAE,MAAM,iCAAiC,CAAC;AAClF,OAAO,EAAE,2BAA2B,EAAE,MAAM,qBAAqB,CAAC;AAElE,kFAAkF;AAClF,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC5C,KAGC;IAED,MAAM,wBAAwB,GAAG,gCAAgC,CAC/D,KAAK,CAAC,wBAAwB,EAC9B,2BAA2B,CAC5B,CAAC;IACF,IAAI,aAAgE,CAAC;IACrE,MAAM,wCAAwC,CAAC,KAAK,CAAC,gBAAgB,EAAE;QACrE,0BAA0B,EAAE,IAAI;QAChC,GAAG,6BAA6B,CAAC;YAC/B,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,YAAY,EAAE,KAAK,CAAC,YAAY;YAChC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;YACtE,wBAAwB;SACzB,CAAC;QACF,uBAAuB,EAAE,CAAC,KAAK,EAAE,EAAE;YACjC,aAAa,GAAG,KAAK,CAAC;QACxB,CAAC;KACF,CAAC,CAAC;IACH,IAAI,KAAK,CAAC,OAAO,CAAC,gBAAgB,CAAC,MAAM,KAAK,KAAK,CAAC,OAAO,CAAC,MAAM;QAChE,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,+CAA+C,CAChD,CAAC;IACJ,MAAM,oCAAoC,CAAC,KAAK,CAAC,OAAO,CAAC,gBAAgB,CAAC,CAAC;IAC3E,MAAM,+BAA+B,CAAC;QACpC,GAAG,KAAK;QACR,aAAa;QACb,wBAAwB;KACzB,CAAC,CAAC;IACH,IAAI,CAAC,aAAa;QAAE,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;IAC3E,2BAA2B,CAAC;QAC1B,aAAa;QACb,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,UAAU,EAAE,KAAK,CAAC,kBAAkB;KACrC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { assertBlobContentKeyBundleTargetHash } from \"../../../data/blobs/attachments/responses\";\nimport type { DecryptDocumentAttachmentBlobInput } from \"../../../data/blobs/attachments/types\";\nimport { assertDocumentWriterProjectionConsistent } from \"../../../data/documents/shared/projection\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/types\";\nimport {\n type DocumentWriterProjectionAuthorization,\n requireProjectionUserKeyResolver,\n} from \"../../../data/keyingProjectionVerification\";\nimport { assertAttachmentBindingVerified } from \"./attachmentBindingVerification\";\nimport { assertBlobWrapScopeVerified } from \"./verifiedWrapScope\";\n\n/** Retaining an existing envelope does not propagate a key to a new recipient. */\nexport async function verifyRetainedAttachment(\n input: Omit<\n DecryptDocumentAttachmentBlobInput,\n \"encryptedBytes\" | \"targetSecretKey\"\n >,\n): Promise<void> {\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Retained attachment scope\",\n );\n let authorization: DocumentWriterProjectionAuthorization | undefined;\n await assertDocumentWriterProjectionConsistent(input.writerProjection, {\n allowStaleContentKeyBundle: true,\n ...projectionVerificationOptions({\n execSql: input.execSql,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n resolveProjectionUserKey,\n }),\n onVerifiedAuthorization: (value) => {\n authorization = value;\n },\n });\n if (input.binding.contentKeyBundle.blobId !== input.binding.blobId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Retained attachment bundle names another blob\",\n );\n await assertBlobContentKeyBundleTargetHash(input.binding.contentKeyBundle);\n await assertAttachmentBindingVerified({\n ...input,\n authorization,\n resolveProjectionUserKey,\n });\n if (!authorization) throw new Error(\"Attachment authority is unavailable\");\n assertBlobWrapScopeVerified({\n authorization,\n binding: input.binding,\n documentId: input.expectedDocumentId,\n });\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { readDocumentManifestIdentity } from "../../../data/
|
|
1
|
+
import { readDocumentManifestIdentity } from "../../../data/blobs/attachments/readers.js";
|
|
2
2
|
import { assertDocumentWriterProjectionConsistent } from "../../../data/documents/shared/projection/index.js";
|
|
3
3
|
import { projectionVerificationOptions, } from "../../../data/documents/shared/types.js";
|
|
4
4
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writerProjection.js","sourceRoot":"","sources":["writerProjection.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,4BAA4B,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"writerProjection.js","sourceRoot":"","sources":["writerProjection.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,4BAA4B,EAAE,MAAM,yCAAyC,CAAC;AAKvF,OAAO,EAAE,wCAAwC,EAAE,MAAM,2CAA2C,CAAC;AACrG,OAAO,EAEL,6BAA6B,GAC9B,MAAM,sCAAsC,CAAC;AAG9C;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,mCAAmC,CACvD,KAQiC;IAKjC,MAAM,gBAAgB,GACpB,KAAK,CAAC,gBAAgB;QACtB,CAAC,MAAM,KAAK,CAAC,SAAS,CAAC,2BAA2B,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC;IACxE,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACtB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,wCAAwC,CAAC,gBAAgB,EAAE;QAC/D,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,GAAG,6BAA6B,CAAC,KAAK,CAAC;KACxC,CAAC,CAAC;IACH,MAAM,gBAAgB,GAAG,4BAA4B,CAAC,gBAAgB,CAAC,CAAC;IACxE,IAAI,gBAAgB,CAAC,UAAU,KAAK,KAAK,CAAC,UAAU,EAAE,CAAC;QACrD,MAAM,IAAI,KAAK,CACb,GAAG,KAAK,CAAC,UAAU,2CAA2C,CAC/D,CAAC;IACJ,CAAC;IACD,IAAI,KAAK,CAAC,mBAAmB,EAAE,CAAC,gBAAgB,CAAC,cAAc,CAAC,EAAE,CAAC;QACjE,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,CAAC;AAChD,CAAC","sourcesContent":["import type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { readDocumentManifestIdentity } from \"../../../data/blobs/attachments/readers\";\nimport type {\n BlobAttachmentApi,\n DocumentManifestIdentity,\n} from \"../../../data/blobs/attachments/types\";\nimport { assertDocumentWriterProjectionConsistent } from \"../../../data/documents/shared/projection\";\nimport {\n type ProjectionVerificationOptions,\n projectionVerificationOptions,\n} from \"../../../data/documents/shared/types\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\n\n/**\n * Shared prologue for blob attachment mutations (upload/detach): resolve the\n * document writer projection, verify its consistency, confirm it targets the\n * mutated document, and gate on a blocked organization. Returns null when the\n * projection is unavailable or the organization's remote sync is blocked.\n */\nexport async function resolveBlobMutationWriterProjection(\n input: {\n apiClient: Pick<BlobAttachmentApi, \"getDocumentWriterProjection\">;\n documentId: string;\n /** Prefix for the wrong-document error, e.g. \"Blob attachment detach\". */\n errorLabel: string;\n execSql?: ExecSql | undefined;\n isRemoteSyncBlocked?: ((organizationId: string) => boolean) | undefined;\n writerProjection?: DocumentWriterProjectionResponse | undefined;\n } & ProjectionVerificationOptions,\n): Promise<{\n manifestIdentity: DocumentManifestIdentity;\n writerProjection: DocumentWriterProjectionResponse;\n} | null> {\n const writerProjection =\n input.writerProjection ??\n (await input.apiClient.getDocumentWriterProjection(input.documentId));\n if (!writerProjection) {\n return null;\n }\n\n await assertDocumentWriterProjectionConsistent(writerProjection, {\n execSql: input.execSql,\n ...projectionVerificationOptions(input),\n });\n const manifestIdentity = readDocumentManifestIdentity(writerProjection);\n if (manifestIdentity.documentId !== input.documentId) {\n throw new Error(\n `${input.errorLabel} writer projection targets wrong document`,\n );\n }\n if (input.isRemoteSyncBlocked?.(manifestIdentity.organizationId)) {\n return null;\n }\n\n return { manifestIdentity, writerProjection };\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"blobSourceSnapshot.js","sourceRoot":"","sources":["blobSourceSnapshot.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,4BAA4B,EAC5B,UAAU,EACV,qBAAqB,EACrB,uBAAuB,EACvB,sBAAsB,GACvB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAKxD,KAAK,UAAU,SAAS,CAAC,KAAiB;IACxC,OAAO,UAAU,CACf,IAAI,UAAU,CACZ,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,gBAAgB,CAAC,KAAK,CAAC,CAAC,CAC/D,CACF,CAAC;AACJ,CAAC;AAED,SAAS,sBAAsB,CAAC,UAAkB;IAChD,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,UAAU,CAAC,IAAI,UAAU,GAAG,CAAC,EAAE,CAAC;QACxD,MAAM,IAAI,KAAK,CACb,6DAA6D,CAC9D,CAAC;IACJ,CAAC;AACH,CAAC;AAED,KAAK,UAAU,oBAAoB,CAAC,KAInC;IACC,MAAM,KAAK,GAAG,MAAM,KAAK,CA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QACT,MAAM,EAAE,UAAU,CAAC,UAAU,CAAC,MAAM,EAAE,CAAC;KACxC,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAAC,KAIjD;IACC,MAAM,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;IAC/C,IAAI,MAAM,CAAC,UAAU,KAAK,QAAQ,CAAC,UAAU,EAAE,CAAC;QAC9C,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAC;IACtE,CAAC;IACD,MAAM,UAAU,GAAG,qBAAqB,CACtC,QAAQ,CAAC,UAAU,EACnB,QAAQ,CAAC,SAAS,CACnB,CAAC;IACF,MAAM,UAAU,GAAG,4BAA4B,CAAC;QAC9C,UAAU;QACV,UAAU;QACV,SAAS,EAAE,QAAQ,CAAC,SAAS;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,EACrB,8BAA8B,EAC9B,mCAAmC,EACnC,cAAc,EACd,uBAAuB,EACvB,iBAAiB,EACjB,0BAA0B,EAC1B,sBAAsB,GACvB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAGpD,OAAO,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAC1E,OAAO,EACL,gCAAgC,EAChC,gBAAgB,EAChB,0BAA0B,GAC3B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAEL,iBAAiB,EACjB,2BAA2B,GAC5B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,0BAA0B,EAAE,MAAM,wBAAwB,CAAC;AAGpE,MAAM,CAAC,MAAM,6BAA6B,GAAG,qBAAqB,CAAC;AA4BnE,KAAK,UAAU,2BAA2B,CACxC,KAAiC,EACjC,QAA4B;IAE5B,MAAM,SAAS,GAAG,sBAAsB,CACtC,KAAK,CAAC,SAAS,IAAI,6BAA6B,CACjD,CAAC;IACF,MAAM,mBAAmB,GAAG,KAAK,CAAC,MAAM,CAAC,UAAU,CAAC;IACpD,MAA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ytesToHex,\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,K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Q,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,SAAS,GACb,IAAI,CAAC,SAAS,KAAK,iBAAiB;QAClC,CAAC,CAAC,2BAA2B;QAC7B,CAAC,CAAC,6BAA6B,CAAC;IACpC,MAAM,aAAa,GAAwB;QACzC,OAAO,EAAE,CAAC;QACV,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,SAAS,EAAE,IAAI,CAAC,SAAS;QACzB,UAAU,EAAE,MAAM;QAClB,QAAQ,EAAE,KAAK,CAAC,MAAM;QACtB,cAAc,EAAE,KAAK,CAAC,gBAAgB,CAAC,cAAc;QACrD,oBAAoB,EAAE,IAAI;QAC1B,wBAAwB,EAAE,mBAAmB,CAAC;YAC5C,KAAK,CAAC,gBAAgB,CAAC,YAAY;YACnC,GAAG,KAAK,CAAC,4BAA4B,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CACrD,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,YAAY,CAAC,CACpC;SACF,CAAC;QACF,QAAQ,EAAE,MAAM,0BAA0B,CACxC,iBAAiB,CAAC,IAAI,EAAE,SAAS,CAAC,CACnC;QACD,YAAY,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ION_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"],"names":[],"mappings":"AAAA,OAAO,EACL,2BAA2B,EAE3B,cAAc,GACf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAMpD,OAAO,EAAE,4BAA4B,EAAE,MAAM,6EAA6E,CAAC;AAE3H,OAAO,EAAE,6BAA6B,EAAE,MAAM,gDAAgD,CAAC;AAC/F,OAAO,EACL,0CAA0C,EAC1C,sBAAsB,EACtB,2BAA2B,GAC5B,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,6BAA6B,EAAE,MAAM,+CAA+C,CAAC;AAC9F,OAAO,EACL,gBAAgB,EAChB,kCAAkC,GACnC,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAEL,6BAA6B,GAC9B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAG5C,SAAS,cAAc,CACrB,KAAgD,EAChD,OAA4C;IAE5C,OAAO,eAAe,CACpB,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;QACvB,SAAS,EAAE,KAAK,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AAgB,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","sourceRoot":"","sources":["readers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,EAAE,aAAa,IAAI,aAAa,EAAE,MAAM,qCAAqC,CAAC;AAGrF,OAAO,EACL,yBAAyB,EACzB,gBAAgB,EAChB,WAAW,GACZ,MAAM,sBAAsB,CAAC;AAO9B,SAAS,SAAS,CAAC,MAA4B;IAC7C,OAAO;QACL,MAAM,CAAC,SAAS;QAChB,MAAM,CAAC,UAAU;QACjB,MAAM,CAAC,WAAW;QAClB,MAAM,CAAC,qBAAqB;QAC5B,MAAM,CAAC,mBAAmB;QAC1B,MAAM,CAAC,MAAM,CAAC,iBAAiB,CAAC;KACjC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACd,CAAC;AAED,MAAM,UAAU,eAAe,CAC7B,OAAqB;IAErB,OAAO,WAAW,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;AACzC,CAAC;AAED,MAAM,UAAU,4BAA4B,CAC1C,gBAAkD;IAElD,MAAM,EAAE,gBAAgB,EAAE,GAAG,gBAAgB,CAAC;IAC9C,IAA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C,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 \"containerKeyEpoch\",\n label,\n ),\n };\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"responses.js","sourceRoot":"","sources":["responses.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,sBAAsB,EACtB,+BAA+B,GAEhC,MAAM,mBAAmB,CAAC;AAM3B,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC/E,OAAO,EACL,yBAAyB,EACzB,iBAAiB,EACjB,eAAe,GAChB,MAAM,WAAW,CAAC;AAGnB,MAAM,CAAC,KAAK,UAAU,oCAAoC,CACxD,MAAmC;IAEnC,MAAM,UAAU,GAAG,MAAM,+BAA+B,CACtD,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAC9C,CAAC;IACF,IAAI,UAAU,KAAK,MAAM,CAAC,UAAU,EAAE,CAAC;QACrC,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;IACnE,CAAC;AACH,CAAC;AAED,SAAS,8BAA8B,CACrC,MAAmC;IAEnC,OAAO;QACL,eAAe,EAAE,MAAM,CAAC,eA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KAAK,CAAC,WAAW,EAAE,8BAA8B,CAAC;QACvE,KAAK,CAAC,QAAQ,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM;QACtC,KAAK,CAAC,QAAQ,CAAC,SAAS,KAAK,KAAK,CAAC,SAAS;QAC5C,KAAK,CAAC,QAAQ,CAAC,UAAU,KAAK,KAAK,CAAC,UAAU;QAC9C,KAAK,CAAC,QAAQ,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM;QACtC,KAAK,CAAC,QAAQ,CAAC,cAAc,CAAC,sBAAsB;YAClD,KAAK,CAAC,sBAAsB;QAC9B,CAAC,KAAK,CAAC,QAAQ,CAAC,kBAAkB;QAClC,kBAAkB,CAChB,KAAK,CAAC,QAAQ,CAAC,kBAAkB,EACjC,mDAAmD,CACpD;YACC,kBAAkB,CAChB,KAAK,CAAC,QAAQ,CAAC,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
|