@tearleads/client-sdk 0.1.260 → 0.1.261
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.
|
@@ -41,7 +41,9 @@ export interface DocumentAttachmentHydrationApi {
|
|
|
41
41
|
evictDocumentWriterProjection?(documentId: string): void;
|
|
42
42
|
getBlobBytes(blobId: string, options?: RequestResultOptions): Promise<BlobBytesResponse | null>;
|
|
43
43
|
getDocumentWriterProjection(documentId: string): Promise<DocumentWriterProjectionResponse | null>;
|
|
44
|
-
listDocumentAttachments(documentId: string
|
|
44
|
+
listDocumentAttachments(documentId: string, options?: {
|
|
45
|
+
readonly refresh?: boolean;
|
|
46
|
+
}): Promise<ListDocumentAttachmentsResponse | null>;
|
|
45
47
|
}
|
|
46
48
|
export type { BlobContentKeyTarget };
|
|
47
49
|
/**
|
|
@@ -1 +1 @@
|
|
|
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 BlobBytesResponse,\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 DocumentSyncRequest,\n InitiateMultipartBlobStageRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n BlobAttachmentBindResponse,\n BlobAttachmentDetachResponse,\n BlobAttachmentSummary,\n DocumentWriterProjectionResponse,\n InitiateMultipartBlobStageResponse,\n ListDocumentAttachmentsResponse,\n MultipartBlobStageStatusResponse,\n UploadMultipartBlobPartResponse,\n} from \"@tearleads/validators/response\";\nimport type { DocumentCreateAuthor } from \"../../documents/shared/types\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../keyingProjectionVerification\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type { BlobByteSourceInput, BlobBytes } from \"../blobContracts\";\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 stillCurrent?: (() => boolean) | undefined;\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 options?: RequestResultOptions,\n ): Promise<MultipartBlobStageStatusResponse | null>;\n initiateMultipartBlobStage(\n input: InitiateMultipartBlobStageRequest,\n options?: RequestResultOptions,\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 interface DocumentAttachmentHydrationApi {\n evictDocumentWriterProjection?(documentId: string): void;\n getBlobBytes(\n blobId: string,\n options?: RequestResultOptions,\n ): Promise<BlobBytesResponse | null>;\n getDocumentWriterProjection(\n documentId: string,\n ): Promise<DocumentWriterProjectionResponse | null>;\n listDocumentAttachments(\n documentId: string,\n ): Promise<ListDocumentAttachmentsResponse | 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\n/** One upload; the service supplies the API, executor, and secret key. */\nexport interface UploadDocumentAttachmentRequest {\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 /**\n * The document's deferred first update for the bind to commit after its\n * binding. A bind refused with it is sent once more without it, and the\n * caller's queued row then syncs on its own.\n */\n documentSync?: DocumentSyncRequest | undefined;\n eventId?: string | undefined;\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 stillCurrent?: (() => boolean) | undefined;\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\n/** One detach; the service supplies the API and executor. */\nexport interface DetachDocumentAttachmentRequest {\n author: DocumentCreateAuthor;\n bindingId: string;\n blobId: string;\n documentId: string;\n eventId?: string | undefined;\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\n/** One decrypt; the service supplies the executor and its secret key. */\nexport type DecryptDocumentAttachmentBlobRequest = Omit<\n DecryptDocumentAttachmentBlobInput,\n \"execSql\" | \"targetSecretKey\"\n>;\n"]}
|
|
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 BlobBytesResponse,\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 DocumentSyncRequest,\n InitiateMultipartBlobStageRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n BlobAttachmentBindResponse,\n BlobAttachmentDetachResponse,\n BlobAttachmentSummary,\n DocumentWriterProjectionResponse,\n InitiateMultipartBlobStageResponse,\n ListDocumentAttachmentsResponse,\n MultipartBlobStageStatusResponse,\n UploadMultipartBlobPartResponse,\n} from \"@tearleads/validators/response\";\nimport type { DocumentCreateAuthor } from \"../../documents/shared/types\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../keyingProjectionVerification\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type { BlobByteSourceInput, BlobBytes } from \"../blobContracts\";\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 stillCurrent?: (() => boolean) | undefined;\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 options?: RequestResultOptions,\n ): Promise<MultipartBlobStageStatusResponse | null>;\n initiateMultipartBlobStage(\n input: InitiateMultipartBlobStageRequest,\n options?: RequestResultOptions,\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 interface DocumentAttachmentHydrationApi {\n evictDocumentWriterProjection?(documentId: string): void;\n getBlobBytes(\n blobId: string,\n options?: RequestResultOptions,\n ): Promise<BlobBytesResponse | null>;\n getDocumentWriterProjection(\n documentId: string,\n ): Promise<DocumentWriterProjectionResponse | null>;\n listDocumentAttachments(\n documentId: string,\n options?: { readonly refresh?: boolean },\n ): Promise<ListDocumentAttachmentsResponse | 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\n/** One upload; the service supplies the API, executor, and secret key. */\nexport interface UploadDocumentAttachmentRequest {\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 /**\n * The document's deferred first update for the bind to commit after its\n * binding. A bind refused with it is sent once more without it, and the\n * caller's queued row then syncs on its own.\n */\n documentSync?: DocumentSyncRequest | undefined;\n eventId?: string | undefined;\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 stillCurrent?: (() => boolean) | undefined;\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\n/** One detach; the service supplies the API and executor. */\nexport interface DetachDocumentAttachmentRequest {\n author: DocumentCreateAuthor;\n bindingId: string;\n blobId: string;\n documentId: string;\n eventId?: string | undefined;\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\n/** One decrypt; the service supplies the executor and its secret key. */\nexport type DecryptDocumentAttachmentBlobRequest = Omit<\n DecryptDocumentAttachmentBlobInput,\n \"execSql\" | \"targetSecretKey\"\n>;\n"]}
|
package/package.json
CHANGED
|
@@ -141,7 +141,9 @@ export async function hydrateDocumentAttachmentBlobs(blobs, request) {
|
|
|
141
141
|
reportSecurityIncident: blobs.reportSecurityIncident,
|
|
142
142
|
targetSecretKey: requireEncapsulationSecretKey(blobs, "Document attachment hydration"),
|
|
143
143
|
};
|
|
144
|
-
|
|
144
|
+
// The writer can bind a file after publishing its document. An earlier
|
|
145
|
+
// cached list cannot tell a reader whether the file is now available.
|
|
146
|
+
const attachmentBindings = await input.apiClient.listDocumentAttachments(input.documentId, { refresh: true });
|
|
145
147
|
if (!attachmentBindings) {
|
|
146
148
|
return null;
|
|
147
149
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hydrate.js","sourceRoot":"","sources":["hydrate.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAK/C,OAAO,EAAE,uBAAuB,EAAE,MAAM,+CAA+C,CAAC;AACxF,OAAO,EAEL,6BAA6B,GAC9B,MAAM,+CAA+C,CAAC;AAGvD,OAAO,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAMnE,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AAGjE,OAAO,EAAE,yBAAyB,EAAE,MAAM,qCAAqC,CAAC;AAChF,OAAO,EAAE,uBAAuB,EAAE,MAAM,oBAAoB,CAAC;AAC7D,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAqDlE,SAAS,yBAAyB,CAChC,UAA8B,EAC9B,OAA8B;IAE9B,OAAO,IAAI,CAAC,SAAS,CAAC;QACpB,UAAU,CAAC,MAAM;QACjB,OAAO,CAAC,SAAS;QACjB,UAAU,CAAC,aAAa;KACzB,CAAC,CAAC;AACL,CAAC;AAiBD,KAAK,UAAU,qBAAqB,CAClC,IAAuB,EACvB,cAAuC;IAEvC,MAAM,UAAU,GAAG,IAAI,UAAU,CAC/B,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,c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,GAAG,MAAM,KAAK,CAAC,SAAS,CAAC,2BAA2B,CACxE,KAAK,CAAC,UAAU,CACjB,CAAC;IACF,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACtB,KAAK,CAAC,GAAG,EAAE,CACT,sDAAsD,KAAK,CAAC,UAAU,+BAA+B,CACtG,CAAC;QACF,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,MAAM,iBAAiB,GAAG,yBAAyB,CACjD,KAAK,CAAC,SAAS,EACf,KAAK,CAAC,UAAU,CACjB,CAAC;IACF,MAAM,QAAQ,GAAG,MAAM,uBAAuB,CAAC;QAC7C,GAAG,KAAK;QACR,KAAK,EAAE,WAAW,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;YAClC,MAAM,EAAE,MAAM,CAAC,OAAO,CAAC,MAAM;YAC7B,GAAG,EAAE,GAAG,EAAE,CACR,mCAAmC,CAAC;gBAClC,GAAG,KAAK;gBACR,iBAAiB;gBACjB,MAAM;gBACN,gBAAgB;aACjB,CAAC;SACL,CAAC,CAAC;KACJ,CAAC,CAAC;IACH,MAAM,QAAQ,GAAG,QAAQ,CAAC,MAAM,CAC9B,CAAC,IAAI,EAA0C,EAAE,CAAC,IAAI,KAAK,IAAI,CAChE,CAAC;IACF,IAAI,QAAQ,CAAC,MAAM,KAAK,gBAAgB,CAAC,MAAM;QAAE,KAAK,CAAC,iBAAiB,EAAE,EAAE,CAAC;IAC7E,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import type { BlobBytesResponse } from \"@tearleads/api-client\";\nimport { bytesToHex } from \"@tearleads/crypto\";\nimport type {\n BlobAttachmentSummary,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { attachmentContentSha256 } from \"../../../data/blobs/attachmentContentIdentity\";\nimport {\n type BlobAttachmentCollaborators,\n requireEncapsulationSecretKey,\n} from \"../../../data/blobs/attachments/collaborators\";\nimport type { DocumentAttachmentHydrationApi } from \"../../../data/blobs/attachments/types\";\nimport type { BlobBytes } from \"../../../data/blobs/blobContracts\";\nimport { runBlobTransfer } from \"../../../data/blobs/transferPool\";\nimport type { DocumentAttachment } from \"../../../data/documents\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../../data/keyingProjectionVerification\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { createAttachmentDecryptor } from \"../verification/attachmentDecryptor\";\nimport { collectHydrationResults } from \"./hydrationResults\";\nimport { readAttachmentTransfer } from \"./readAttachmentTransfer\";\n\nexport interface HydratedDocumentAttachmentBlob {\n attachment: DocumentAttachment;\n binding: BlobAttachmentSummary;\n bytes: BlobBytes;\n /** Plaintext digest of `bytes`. */\n contentSha256: string;\n /**\n * The served binding is validly signed but its plaintext digest differs\n * from the digest the document content records for the slot. Set only when\n * the slot held no local bytes: the bind and the content update carrying\n * its digest are two server writes, and an uploader lost between them must\n * not leave the attachment permanently invisible. Never a security incident;\n * an honest crash window is indistinguishable from a served rollback.\n */\n intentMismatch: boolean;\n storageKey: string;\n}\n\n/** One hydration pass; the service supplies the API, executor, and key. */\nexport interface HydrateDocumentAttachmentBlobsRequest {\n attachments: ReadonlyArray<DocumentAttachment>;\n documentId: string;\n localBlobIdBySlotId?:\n | Readonly<Record<string, string | null | undefined>>\n | undefined;\n localStorageKeyBySlotId?: Readonly<Record<string, string | undefined>>;\n /** No binding target remains unchecked or unavailable in this pass. */\n onBindingsChecked?: (() => void) | undefined;\n /**\n * Served bindings already downloaded and refused for a held copy, keyed per\n * (slot, binding, intent). Populated here; a later pass skips the download\n * until the binding or the document intent changes.\n */\n rejectedServedBindings?: Set<string> | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}\n\ninterface DocumentAttachmentHydrationContext\n extends Omit<\n HydrateDocumentAttachmentBlobsRequest,\n \"attachments\" | \"onBindingsChecked\"\n > {\n apiClient: DocumentAttachmentHydrationApi;\n execSql: ExecSql;\n log?: ((message: string) => void) | undefined;\n reportSecurityIncident?: SecurityIncidentReporter | undefined;\n targetSecretKey: Uint8Array;\n}\n\nfunction servedBindingRejectionKey(\n attachment: DocumentAttachment,\n binding: BlobAttachmentSummary,\n): string {\n return JSON.stringify([\n attachment.slotId,\n binding.bindingId,\n attachment.contentSha256,\n ]);\n}\n\ninterface DocumentAttachmentHydrationTarget {\n attachment: DocumentAttachment;\n binding: BlobAttachmentSummary;\n}\n\ninterface LoadedDocumentAttachmentBlob\n extends DocumentAttachmentHydrationTarget {\n encryptedBytes: Uint8Array<ArrayBuffer>;\n}\n\ninterface LoadedDocumentAttachmentBlobBytes {\n blobId: string;\n encryptedBytes: Uint8Array<ArrayBuffer>;\n}\n\nasync function hasExpectedBlobSha256(\n blob: BlobBytesResponse,\n encryptedBytes: Uint8Array<ArrayBuffer>,\n): Promise<boolean> {\n const blobDigest = new Uint8Array(\n await crypto.subtle.digest(\"SHA-256\", encryptedBytes),\n );\n\n return bytesToHex(blobDigest) === blob.sha256;\n}\n\nfunction shouldHydrateAttachment(input: {\n attachment: DocumentAttachment;\n binding: BlobAttachmentSummary;\n localBlobIdBySlotId:\n | Readonly<Record<string, string | null | undefined>>\n | undefined;\n localStorageKeyBySlotId:\n | Readonly<Record<string, string | undefined>>\n | undefined;\n rejectedServedBindings: ReadonlySet<string> | undefined;\n}): boolean {\n const slotId = input.attachment.slotId;\n const localStorageKey = input.localStorageKeyBySlotId?.[slotId];\n // An empty slot always hydrates: a rejection only ever protected a held\n // copy, so once that copy is gone the served binding is shown (flagged).\n if (!localStorageKey) {\n return true;\n }\n if (\n input.rejectedServedBindings?.has(\n servedBindingRejectionKey(input.attachment, input.binding),\n )\n ) {\n return false;\n }\n\n const localBlobId = input.localBlobIdBySlotId?.[slotId];\n return localBlobId !== null && localBlobId !== input.binding.blobId;\n}\n\nasync function loadDocumentAttachmentBlob(\n input: DocumentAttachmentHydrationContext & {\n binding: BlobAttachmentSummary;\n signal: AbortSignal;\n progress: () => void;\n },\n): Promise<LoadedDocumentAttachmentBlobBytes | null> {\n const { apiClient, binding, log } = input;\n if (input.stillCurrent?.() === false) return null;\n input.signal.throwIfAborted();\n const blob = await apiClient.getBlobBytes(binding.blobId, {\n signal: input.signal,\n });\n if (!blob) {\n return null;\n }\n\n let encryptedBytes: Uint8Array<ArrayBuffer>;\n try {\n encryptedBytes = await readAttachmentTransfer(\n blob,\n input.signal,\n input.progress,\n );\n } catch (error) {\n log?.(\n `Documents: blob ${binding.blobId} failed to stream during hydration: ${errorMessage(\n error,\n )}`,\n );\n return null;\n }\n\n if (encryptedBytes.byteLength !== blob.byteLength) {\n log?.(\n `Documents: blob ${binding.blobId} byte length mismatch during hydration.`,\n );\n return null;\n }\n\n if (!(await hasExpectedBlobSha256(blob, encryptedBytes))) {\n log?.(\n `Documents: blob ${binding.blobId} sha256 mismatch during hydration.`,\n );\n return null;\n }\n\n input.signal.throwIfAborted();\n return {\n blobId: binding.blobId,\n encryptedBytes,\n };\n}\n\nasync function loadUniqueDocumentAttachmentBlobs(\n input: DocumentAttachmentHydrationContext & {\n hydrationTargets: ReadonlyArray<DocumentAttachmentHydrationTarget>;\n },\n): Promise<ReadonlyMap<string, LoadedDocumentAttachmentBlobBytes>> {\n const targetsByBlobId = new Map<string, DocumentAttachmentHydrationTarget>();\n for (const target of input.hydrationTargets) {\n if (!targetsByBlobId.has(target.binding.blobId)) {\n targetsByBlobId.set(target.binding.blobId, target);\n }\n }\n\n const loadedBlobs = await collectHydrationResults({\n ...input,\n tasks: Array.from(targetsByBlobId.values()).map((target) => ({\n blobId: target.binding.blobId,\n run: () =>\n runBlobTransfer(input.apiClient, (signal, progress) =>\n loadDocumentAttachmentBlob({\n ...input,\n binding: target.binding,\n signal,\n progress,\n }),\n ),\n })),\n });\n\n return new Map(\n loadedBlobs.flatMap((loaded) =>\n loaded ? [[loaded.blobId, loaded] as const] : [],\n ),\n );\n}\n\nfunction applyLoadedBlobBytesToHydrationTargets(\n hydrationTargets: ReadonlyArray<DocumentAttachmentHydrationTarget>,\n loadedBlobsByBlobId: ReadonlyMap<string, LoadedDocumentAttachmentBlobBytes>,\n): LoadedDocumentAttachmentBlob[] {\n return hydrationTargets.flatMap((target) => {\n const loaded = loadedBlobsByBlobId.get(target.binding.blobId);\n return loaded\n ? [\n {\n ...target,\n encryptedBytes: loaded.encryptedBytes,\n },\n ]\n : [];\n });\n}\n\nasync function decryptLoadedDocumentAttachmentBlob(\n input: DocumentAttachmentHydrationContext & {\n loaded: LoadedDocumentAttachmentBlob;\n decryptAttachment: ReturnType<typeof createAttachmentDecryptor>;\n writerProjection: DocumentWriterProjectionResponse;\n },\n): Promise<HydratedDocumentAttachmentBlob | null> {\n const bytes = await input.decryptAttachment({\n binding: input.loaded.binding,\n encryptedBytes: input.loaded.encryptedBytes,\n expectedDocumentId: input.documentId,\n expectedSlotId: input.loaded.attachment.slotId,\n execSql: input.execSql,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n targetSecretKey: input.targetSecretKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n writerProjection: input.writerProjection,\n });\n\n const { attachment, binding } = input.loaded;\n const contentSha256 = await attachmentContentSha256(bytes);\n const intentMismatch = contentSha256 !== attachment.contentSha256;\n if (intentMismatch && input.localStorageKeyBySlotId?.[attachment.slotId]) {\n // Never replace a held copy with bytes the document does not record.\n input.rejectedServedBindings?.add(\n servedBindingRejectionKey(attachment, binding),\n );\n input.log?.(\n \"Documents: served attachment bytes differ from the current document content; keeping the held copy.\",\n );\n return null;\n }\n if (intentMismatch) {\n input.log?.(\n \"Documents: served attachment bytes differ from the current document content; showing them flagged.\",\n );\n }\n return {\n attachment,\n binding,\n bytes,\n contentSha256,\n intentMismatch,\n storageKey: `blob-${binding.blobId}`,\n };\n}\n\nexport async function hydrateDocumentAttachmentBlobs(\n blobs: BlobAttachmentCollaborators,\n request: HydrateDocumentAttachmentBlobsRequest,\n): Promise<HydratedDocumentAttachmentBlob[] | null> {\n const input = {\n ...request,\n apiClient: blobs.api,\n execSql: blobs.execSql,\n log: blobs.log,\n reportSecurityIncident: blobs.reportSecurityIncident,\n targetSecretKey: requireEncapsulationSecretKey(\n blobs,\n \"Document attachment hydration\",\n ),\n };\n const attachmentBindings = await input.apiClient.listDocumentAttachments(\n input.documentId,\n );\n if (!attachmentBindings) {\n return null;\n }\n\n const bindingBySlotId = new Map(\n attachmentBindings.map((binding) => [binding.slotId, binding]),\n );\n const hydrationTargets: DocumentAttachmentHydrationTarget[] =\n input.attachments.flatMap((attachment) => {\n const binding = bindingBySlotId.get(attachment.slotId);\n return binding &&\n shouldHydrateAttachment({\n attachment,\n binding,\n localBlobIdBySlotId: input.localBlobIdBySlotId,\n localStorageKeyBySlotId: input.localStorageKeyBySlotId,\n rejectedServedBindings: input.rejectedServedBindings,\n })\n ? [{ attachment, binding }]\n : [];\n });\n if (hydrationTargets.length === 0) {\n input.onBindingsChecked?.();\n return [];\n }\n\n const loadedBlobs = applyLoadedBlobBytesToHydrationTargets(\n hydrationTargets,\n await loadUniqueDocumentAttachmentBlobs({\n ...input,\n hydrationTargets,\n }),\n );\n if (loadedBlobs.length === 0) {\n return [];\n }\n\n const writerProjection = await input.apiClient.getDocumentWriterProjection(\n input.documentId,\n );\n if (!writerProjection) {\n input.log?.(\n `Documents: cannot hydrate attachments for document ${input.documentId} without a writer projection.`,\n );\n return [];\n }\n\n const decryptAttachment = createAttachmentDecryptor(\n input.apiClient,\n input.documentId,\n );\n const hydrated = await collectHydrationResults({\n ...input,\n tasks: loadedBlobs.map((loaded) => ({\n blobId: loaded.binding.blobId,\n run: () =>\n decryptLoadedDocumentAttachmentBlob({\n ...input,\n decryptAttachment,\n loaded,\n writerProjection,\n }),\n })),\n });\n const complete = hydrated.filter(\n (item): item is HydratedDocumentAttachmentBlob => item !== null,\n );\n if (complete.length === hydrationTargets.length) input.onBindingsChecked?.();\n return complete;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"hydrate.js","sourceRoot":"","sources":["hydrate.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAK/C,OAAO,EAAE,uBAAuB,EAAE,MAAM,+CAA+C,CAAC;AACxF,OAAO,EAEL,6BAA6B,GAC9B,MAAM,+CAA+C,CAAC;AAGvD,OAAO,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAMnE,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AAGjE,OAAO,EAAE,yBAAyB,EAAE,MAAM,qCAAqC,CAAC;AAChF,OAAO,EAAE,uBAAuB,EAAE,MAAM,oBAAoB,CAAC;AAC7D,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAqDlE,SAAS,yBAAyB,CAChC,UAA8B,EAC9B,OAA8B;IAE9B,OAAO,IAAI,CAAC,SAAS,CAAC;QACpB,UAAU,CAAC,MAAM;QACjB,OAAO,CAAC,SAAS;QACjB,UAAU,CAAC,aAAa;KACzB,CAAC,CAAC;AACL,CAAC;AAiBD,KAAK,UAAU,qBAAqB,CAClC,IAAuB,EACvB,cAAuC;IAEvC,MAAM,UAAU,GAAG,IAAI,UAAU,CAC/B,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,cAAc,CAAC,CACtD,CAAC;IAEF,OAAO,UAAU,CAAC,UAAU,CAAC,KAAK,IAAI,CAAC,MAAM,CAAC;AAChD,CAAC;AAED,SAAS,uBAAuB,CAAC,KAUhC;IACC,MAAM,MAAM,GAAG,KAAK,CAAC,UAAU,CAAC,MAAM,CAAC;IACvC,MAAM,eAAe,GAAG,KAAK,CAAC,uBAAuB,EAAE,CAAC,MAAM,CAAC,CAAC;IAChE,wEAAwE;I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CAAC;IACZ,CAAC;IAED,MAAM,iBAAiB,GAAG,yBAAyB,CACjD,KAAK,CAAC,SAAS,EACf,KAAK,CAAC,UAAU,CACjB,CAAC;IACF,MAAM,QAAQ,GAAG,MAAM,uBAAuB,CAAC;QAC7C,GAAG,KAAK;QACR,KAAK,EAAE,WAAW,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;YAClC,MAAM,EAAE,MAAM,CAAC,OAAO,CAAC,MAAM;YAC7B,GAAG,EAAE,GAAG,EAAE,CACR,mCAAmC,CAAC;gBAClC,GAAG,KAAK;gBACR,iBAAiB;gBACjB,MAAM;gBACN,gBAAgB;aACjB,CAAC;SACL,CAAC,CAAC;KACJ,CAAC,CAAC;IACH,MAAM,QAAQ,GAAG,QAAQ,CAAC,MAAM,CAC9B,CAAC,IAAI,EAA0C,EAAE,CAAC,IAAI,KAAK,IAAI,CAChE,CAAC;IACF,IAAI,QAAQ,CAAC,MAAM,KAAK,gBAAgB,CAAC,MAAM;QAAE,KAAK,CAAC,iBAAiB,EAAE,EAAE,CAAC;IAC7E,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import type { BlobBytesResponse } from \"@tearleads/api-client\";\nimport { bytesToHex } from \"@tearleads/crypto\";\nimport type {\n BlobAttachmentSummary,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { attachmentContentSha256 } from \"../../../data/blobs/attachmentContentIdentity\";\nimport {\n type BlobAttachmentCollaborators,\n requireEncapsulationSecretKey,\n} from \"../../../data/blobs/attachments/collaborators\";\nimport type { DocumentAttachmentHydrationApi } from \"../../../data/blobs/attachments/types\";\nimport type { BlobBytes } from \"../../../data/blobs/blobContracts\";\nimport { runBlobTransfer } from \"../../../data/blobs/transferPool\";\nimport type { DocumentAttachment } from \"../../../data/documents\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../../data/keyingProjectionVerification\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { createAttachmentDecryptor } from \"../verification/attachmentDecryptor\";\nimport { collectHydrationResults } from \"./hydrationResults\";\nimport { readAttachmentTransfer } from \"./readAttachmentTransfer\";\n\nexport interface HydratedDocumentAttachmentBlob {\n attachment: DocumentAttachment;\n binding: BlobAttachmentSummary;\n bytes: BlobBytes;\n /** Plaintext digest of `bytes`. */\n contentSha256: string;\n /**\n * The served binding is validly signed but its plaintext digest differs\n * from the digest the document content records for the slot. Set only when\n * the slot held no local bytes: the bind and the content update carrying\n * its digest are two server writes, and an uploader lost between them must\n * not leave the attachment permanently invisible. Never a security incident;\n * an honest crash window is indistinguishable from a served rollback.\n */\n intentMismatch: boolean;\n storageKey: string;\n}\n\n/** One hydration pass; the service supplies the API, executor, and key. */\nexport interface HydrateDocumentAttachmentBlobsRequest {\n attachments: ReadonlyArray<DocumentAttachment>;\n documentId: string;\n localBlobIdBySlotId?:\n | Readonly<Record<string, string | null | undefined>>\n | undefined;\n localStorageKeyBySlotId?: Readonly<Record<string, string | undefined>>;\n /** No binding target remains unchecked or unavailable in this pass. */\n onBindingsChecked?: (() => void) | undefined;\n /**\n * Served bindings already downloaded and refused for a held copy, keyed per\n * (slot, binding, intent). Populated here; a later pass skips the download\n * until the binding or the document intent changes.\n */\n rejectedServedBindings?: Set<string> | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}\n\ninterface DocumentAttachmentHydrationContext\n extends Omit<\n HydrateDocumentAttachmentBlobsRequest,\n \"attachments\" | \"onBindingsChecked\"\n > {\n apiClient: DocumentAttachmentHydrationApi;\n execSql: ExecSql;\n log?: ((message: string) => void) | undefined;\n reportSecurityIncident?: SecurityIncidentReporter | undefined;\n targetSecretKey: Uint8Array;\n}\n\nfunction servedBindingRejectionKey(\n attachment: DocumentAttachment,\n binding: BlobAttachmentSummary,\n): string {\n return JSON.stringify([\n attachment.slotId,\n binding.bindingId,\n attachment.contentSha256,\n ]);\n}\n\ninterface DocumentAttachmentHydrationTarget {\n attachment: DocumentAttachment;\n binding: BlobAttachmentSummary;\n}\n\ninterface LoadedDocumentAttachmentBlob\n extends DocumentAttachmentHydrationTarget {\n encryptedBytes: Uint8Array<ArrayBuffer>;\n}\n\ninterface LoadedDocumentAttachmentBlobBytes {\n blobId: string;\n encryptedBytes: Uint8Array<ArrayBuffer>;\n}\n\nasync function hasExpectedBlobSha256(\n blob: BlobBytesResponse,\n encryptedBytes: Uint8Array<ArrayBuffer>,\n): Promise<boolean> {\n const blobDigest = new Uint8Array(\n await crypto.subtle.digest(\"SHA-256\", encryptedBytes),\n );\n\n return bytesToHex(blobDigest) === blob.sha256;\n}\n\nfunction shouldHydrateAttachment(input: {\n attachment: DocumentAttachment;\n binding: BlobAttachmentSummary;\n localBlobIdBySlotId:\n | Readonly<Record<string, string | null | undefined>>\n | undefined;\n localStorageKeyBySlotId:\n | Readonly<Record<string, string | undefined>>\n | undefined;\n rejectedServedBindings: ReadonlySet<string> | undefined;\n}): boolean {\n const slotId = input.attachment.slotId;\n const localStorageKey = input.localStorageKeyBySlotId?.[slotId];\n // An empty slot always hydrates: a rejection only ever protected a held\n // copy, so once that copy is gone the served binding is shown (flagged).\n if (!localStorageKey) {\n return true;\n }\n if (\n input.rejectedServedBindings?.has(\n servedBindingRejectionKey(input.attachment, input.binding),\n )\n ) {\n return false;\n }\n\n const localBlobId = input.localBlobIdBySlotId?.[slotId];\n return localBlobId !== null && localBlobId !== input.binding.blobId;\n}\n\nasync function loadDocumentAttachmentBlob(\n input: DocumentAttachmentHydrationContext & {\n binding: BlobAttachmentSummary;\n signal: AbortSignal;\n progress: () => void;\n },\n): Promise<LoadedDocumentAttachmentBlobBytes | null> {\n const { apiClient, binding, log } = input;\n if (input.stillCurrent?.() === false) return null;\n input.signal.throwIfAborted();\n const blob = await apiClient.getBlobBytes(binding.blobId, {\n signal: input.signal,\n });\n if (!blob) {\n return null;\n }\n\n let encryptedBytes: Uint8Array<ArrayBuffer>;\n try {\n encryptedBytes = await readAttachmentTransfer(\n blob,\n input.signal,\n input.progress,\n );\n } catch (error) {\n log?.(\n `Documents: blob ${binding.blobId} failed to stream during hydration: ${errorMessage(\n error,\n )}`,\n );\n return null;\n }\n\n if (encryptedBytes.byteLength !== blob.byteLength) {\n log?.(\n `Documents: blob ${binding.blobId} byte length mismatch during hydration.`,\n );\n return null;\n }\n\n if (!(await hasExpectedBlobSha256(blob, encryptedBytes))) {\n log?.(\n `Documents: blob ${binding.blobId} sha256 mismatch during hydration.`,\n );\n return null;\n }\n\n input.signal.throwIfAborted();\n return {\n blobId: binding.blobId,\n encryptedBytes,\n };\n}\n\nasync function loadUniqueDocumentAttachmentBlobs(\n input: DocumentAttachmentHydrationContext & {\n hydrationTargets: ReadonlyArray<DocumentAttachmentHydrationTarget>;\n },\n): Promise<ReadonlyMap<string, LoadedDocumentAttachmentBlobBytes>> {\n const targetsByBlobId = new Map<string, DocumentAttachmentHydrationTarget>();\n for (const target of input.hydrationTargets) {\n if (!targetsByBlobId.has(target.binding.blobId)) {\n targetsByBlobId.set(target.binding.blobId, target);\n }\n }\n\n const loadedBlobs = await collectHydrationResults({\n ...input,\n tasks: Array.from(targetsByBlobId.values()).map((target) => ({\n blobId: target.binding.blobId,\n run: () =>\n runBlobTransfer(input.apiClient, (signal, progress) =>\n loadDocumentAttachmentBlob({\n ...input,\n binding: target.binding,\n signal,\n progress,\n }),\n ),\n })),\n });\n\n return new Map(\n loadedBlobs.flatMap((loaded) =>\n loaded ? [[loaded.blobId, loaded] as const] : [],\n ),\n );\n}\n\nfunction applyLoadedBlobBytesToHydrationTargets(\n hydrationTargets: ReadonlyArray<DocumentAttachmentHydrationTarget>,\n loadedBlobsByBlobId: ReadonlyMap<string, LoadedDocumentAttachmentBlobBytes>,\n): LoadedDocumentAttachmentBlob[] {\n return hydrationTargets.flatMap((target) => {\n const loaded = loadedBlobsByBlobId.get(target.binding.blobId);\n return loaded\n ? [\n {\n ...target,\n encryptedBytes: loaded.encryptedBytes,\n },\n ]\n : [];\n });\n}\n\nasync function decryptLoadedDocumentAttachmentBlob(\n input: DocumentAttachmentHydrationContext & {\n loaded: LoadedDocumentAttachmentBlob;\n decryptAttachment: ReturnType<typeof createAttachmentDecryptor>;\n writerProjection: DocumentWriterProjectionResponse;\n },\n): Promise<HydratedDocumentAttachmentBlob | null> {\n const bytes = await input.decryptAttachment({\n binding: input.loaded.binding,\n encryptedBytes: input.loaded.encryptedBytes,\n expectedDocumentId: input.documentId,\n expectedSlotId: input.loaded.attachment.slotId,\n execSql: input.execSql,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n targetSecretKey: input.targetSecretKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n writerProjection: input.writerProjection,\n });\n\n const { attachment, binding } = input.loaded;\n const contentSha256 = await attachmentContentSha256(bytes);\n const intentMismatch = contentSha256 !== attachment.contentSha256;\n if (intentMismatch && input.localStorageKeyBySlotId?.[attachment.slotId]) {\n // Never replace a held copy with bytes the document does not record.\n input.rejectedServedBindings?.add(\n servedBindingRejectionKey(attachment, binding),\n );\n input.log?.(\n \"Documents: served attachment bytes differ from the current document content; keeping the held copy.\",\n );\n return null;\n }\n if (intentMismatch) {\n input.log?.(\n \"Documents: served attachment bytes differ from the current document content; showing them flagged.\",\n );\n }\n return {\n attachment,\n binding,\n bytes,\n contentSha256,\n intentMismatch,\n storageKey: `blob-${binding.blobId}`,\n };\n}\n\nexport async function hydrateDocumentAttachmentBlobs(\n blobs: BlobAttachmentCollaborators,\n request: HydrateDocumentAttachmentBlobsRequest,\n): Promise<HydratedDocumentAttachmentBlob[] | null> {\n const input = {\n ...request,\n apiClient: blobs.api,\n execSql: blobs.execSql,\n log: blobs.log,\n reportSecurityIncident: blobs.reportSecurityIncident,\n targetSecretKey: requireEncapsulationSecretKey(\n blobs,\n \"Document attachment hydration\",\n ),\n };\n // The writer can bind a file after publishing its document. An earlier\n // cached list cannot tell a reader whether the file is now available.\n const attachmentBindings = await input.apiClient.listDocumentAttachments(\n input.documentId,\n { refresh: true },\n );\n if (!attachmentBindings) {\n return null;\n }\n\n const bindingBySlotId = new Map(\n attachmentBindings.map((binding) => [binding.slotId, binding]),\n );\n const hydrationTargets: DocumentAttachmentHydrationTarget[] =\n input.attachments.flatMap((attachment) => {\n const binding = bindingBySlotId.get(attachment.slotId);\n return binding &&\n shouldHydrateAttachment({\n attachment,\n binding,\n localBlobIdBySlotId: input.localBlobIdBySlotId,\n localStorageKeyBySlotId: input.localStorageKeyBySlotId,\n rejectedServedBindings: input.rejectedServedBindings,\n })\n ? [{ attachment, binding }]\n : [];\n });\n if (hydrationTargets.length === 0) {\n input.onBindingsChecked?.();\n return [];\n }\n\n const loadedBlobs = applyLoadedBlobBytesToHydrationTargets(\n hydrationTargets,\n await loadUniqueDocumentAttachmentBlobs({\n ...input,\n hydrationTargets,\n }),\n );\n if (loadedBlobs.length === 0) {\n return [];\n }\n\n const writerProjection = await input.apiClient.getDocumentWriterProjection(\n input.documentId,\n );\n if (!writerProjection) {\n input.log?.(\n `Documents: cannot hydrate attachments for document ${input.documentId} without a writer projection.`,\n );\n return [];\n }\n\n const decryptAttachment = createAttachmentDecryptor(\n input.apiClient,\n input.documentId,\n );\n const hydrated = await collectHydrationResults({\n ...input,\n tasks: loadedBlobs.map((loaded) => ({\n blobId: loaded.binding.blobId,\n run: () =>\n decryptLoadedDocumentAttachmentBlob({\n ...input,\n decryptAttachment,\n loaded,\n writerProjection,\n }),\n })),\n });\n const complete = hydrated.filter(\n (item): item is HydratedDocumentAttachmentBlob => item !== null,\n );\n if (complete.length === hydrationTargets.length) input.onBindingsChecked?.();\n return complete;\n}\n"]}
|