@tearleads/client-sdk 0.1.57 → 0.1.59

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.
Files changed (414) hide show
  1. package/Tearleads.d.ts +2 -2
  2. package/Tearleads.js +1 -1
  3. package/Tearleads.js.map +1 -1
  4. package/client/blobs.d.ts +1 -1
  5. package/client/blobs.js.map +1 -1
  6. package/client/deviceFirst.js.map +1 -1
  7. package/client/identity.js +1 -1
  8. package/client/identity.js.map +1 -1
  9. package/client/index.d.ts +1 -1
  10. package/client/index.js +1 -1
  11. package/client/index.js.map +1 -1
  12. package/client/organizations/organizationAccessRestoration.js.map +1 -1
  13. package/client/organizations/organizationDataUsage.js.map +1 -1
  14. package/client/organizations/organizationGroupNameHydration.js.map +1 -1
  15. package/client/organizations/organizationMetadataProfileSync.js +1 -1
  16. package/client/organizations/organizationMetadataProfileSync.js.map +1 -1
  17. package/client/organizations/organizationReadModels.js.map +1 -1
  18. package/client/organizations/organizationWorkflowRuntime.js.map +1 -1
  19. package/client/rootContainerAdoption.js.map +1 -1
  20. package/client/securityIncidents.d.ts +1 -1
  21. package/client/securityIncidents.js.map +1 -1
  22. package/client/session/sessionLoginRefusal.js.map +1 -1
  23. package/client/session/sessionRootAuthority.js.map +1 -1
  24. package/client/session/sessionTypes.d.ts +1 -1
  25. package/client/session/sessionTypes.js.map +1 -1
  26. package/client/userIdentities.d.ts +1 -1
  27. package/client/userIdentities.js.map +1 -1
  28. package/client/workflowRuntime.d.ts +2 -2
  29. package/client/workflowRuntime.js.map +1 -1
  30. package/data/blobs/createBlobStore.d.ts +1 -1
  31. package/data/blobs/createBlobStore.js.map +1 -1
  32. package/data/blobs/encryptedBlobByteSource.js +1 -1
  33. package/data/blobs/encryptedBlobByteSource.js.map +1 -1
  34. package/data/blobs/encryptedBlobEnvelope.d.ts +1 -1
  35. package/data/blobs/encryptedBlobEnvelope.js +2 -2
  36. package/data/blobs/encryptedBlobEnvelope.js.map +1 -1
  37. package/data/blobs/encryptedBlobStore.d.ts +1 -1
  38. package/data/blobs/encryptedBlobStore.js +1 -1
  39. package/data/blobs/encryptedBlobStore.js.map +1 -1
  40. package/data/blobs/memoryBlobStore.d.ts +1 -1
  41. package/data/blobs/memoryBlobStore.js +1 -1
  42. package/data/blobs/memoryBlobStore.js.map +1 -1
  43. package/data/blobs/opfsBlobStore.d.ts +1 -1
  44. package/data/blobs/opfsBlobStore.js +1 -1
  45. package/data/blobs/opfsBlobStore.js.map +1 -1
  46. package/data/containers/containerMetadataDocument.js +1 -1
  47. package/data/containers/containerMetadataDocument.js.map +1 -1
  48. package/data/containers/shared/events.js +1 -1
  49. package/data/containers/shared/events.js.map +1 -1
  50. package/data/containers/shared/heldContainerHeads.js +1 -1
  51. package/data/containers/shared/heldContainerHeads.js.map +1 -1
  52. package/data/containers/shared/mutationAcknowledgement.js +1 -1
  53. package/data/containers/shared/mutationAcknowledgement.js.map +1 -1
  54. package/data/containers/shared/principalPolicies.js +1 -1
  55. package/data/containers/shared/principalPolicies.js.map +1 -1
  56. package/data/containers/shared/readers.js +2 -2
  57. package/data/containers/shared/readers.js.map +1 -1
  58. package/data/documents/attachmentContentIdentity.js +1 -1
  59. package/data/documents/attachmentContentIdentity.js.map +1 -1
  60. package/data/documents/blob/shared/blobEnvelopeStream.js.map +1 -1
  61. package/data/documents/blob/shared/blobSourceSnapshot.d.ts +1 -1
  62. package/data/documents/blob/shared/blobSourceSnapshot.js.map +1 -1
  63. package/data/documents/blob/shared/chunkedBlobCrypto.js.map +1 -1
  64. package/data/documents/blob/shared/encryptedUploadParts.js.map +1 -1
  65. package/data/documents/blob/shared/events.js +1 -1
  66. package/data/documents/blob/shared/events.js.map +1 -1
  67. package/data/documents/blob/shared/types.d.ts +2 -2
  68. package/data/documents/blob/shared/types.js.map +1 -1
  69. package/data/documents/shared/containerKekPathHistory.js +1 -1
  70. package/data/documents/shared/containerKekPathHistory.js.map +1 -1
  71. package/data/documents/shared/containerKekPathVerification.d.ts +1 -1
  72. package/data/documents/shared/containerKekPathVerification.js +1 -1
  73. package/data/documents/shared/events.js +1 -1
  74. package/data/documents/shared/events.js.map +1 -1
  75. package/data/documents/shared/manifestBundleReaders.js +2 -2
  76. package/data/documents/shared/manifestBundleReaders.js.map +1 -1
  77. package/data/documents/shared/projection.d.ts +1 -1
  78. package/data/documents/shared/projection.js +2 -2
  79. package/data/documents/shared/projection.js.map +1 -1
  80. package/data/documents/shared/projectionContentKeys.d.ts +1 -1
  81. package/data/documents/shared/readers.js +3 -3
  82. package/data/documents/shared/readers.js.map +1 -1
  83. package/data/documents/shared/stableDocumentId.js +1 -1
  84. package/data/documents/shared/stableDocumentId.js.map +1 -1
  85. package/data/documents/shared/types.d.ts +1 -1
  86. package/data/documents/shared/types.js +1 -1
  87. package/data/{keyingCanonicalJson.js → keying/canonicalJson.js} +3 -3
  88. package/data/keying/canonicalJson.js.map +1 -0
  89. package/data/keyingProjectionVerification/bundleVerification.js +1 -1
  90. package/data/keyingProjectionVerification/bundleVerification.js.map +1 -1
  91. package/data/keyingProjectionVerification/containerAncestorCitations.js +1 -1
  92. package/data/keyingProjectionVerification/containerAncestorCitations.js.map +1 -1
  93. package/data/keyingProjectionVerification/containerManifestVerification.js +1 -1
  94. package/data/keyingProjectionVerification/containerManifestVerification.js.map +1 -1
  95. package/data/keyingProjectionVerification/documentManifestVerification.js +1 -1
  96. package/data/keyingProjectionVerification/documentManifestVerification.js.map +1 -1
  97. package/data/keyingProjectionVerification/documentPurgeDocumentChainVerification.js +1 -1
  98. package/data/keyingProjectionVerification/documentPurgeDocumentChainVerification.js.map +1 -1
  99. package/data/keyingProjectionVerification/error.js +1 -1
  100. package/data/keyingProjectionVerification/error.js.map +1 -1
  101. package/data/keyingProjectionVerification/index.d.ts +9 -0
  102. package/data/{keyingProjectionVerification.js → keyingProjectionVerification/index.js} +8 -8
  103. package/data/keyingProjectionVerification/index.js.map +1 -0
  104. package/data/keyingProjectionVerification/principalPolicyCache.js +1 -1
  105. package/data/keyingProjectionVerification/principalPolicyCache.js.map +1 -1
  106. package/data/keyingProjectionVerification/principalPolicyVerification.js +1 -1
  107. package/data/keyingProjectionVerification/principalPolicyVerification.js.map +1 -1
  108. package/data/keyingProjectionVerification/readers.d.ts +1 -1
  109. package/data/keyingProjectionVerification/readers.js +3 -3
  110. package/data/keyingProjectionVerification/readers.js.map +1 -1
  111. package/data/keyingProjectionVerification/userKeyResolver.d.ts +1 -1
  112. package/data/keyingProjectionVerification/userKeyResolver.js.map +1 -1
  113. package/data/persistence/containers/containerPersistence.js +1 -1
  114. package/data/persistence/containers/containerPersistence.js.map +1 -1
  115. package/data/persistence/documents/documentDiscoveryCandidate.js +1 -1
  116. package/data/persistence/documents/documentDiscoveryCandidate.js.map +1 -1
  117. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js +1 -1
  118. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js.map +1 -1
  119. package/data/persistence/documents/internal/documentProjectionRows.js +1 -1
  120. package/data/persistence/documents/internal/documentProjectionRows.js.map +1 -1
  121. package/data/persistence/documents/internal/documentRows.js +1 -1
  122. package/data/persistence/documents/internal/documentRows.js.map +1 -1
  123. package/data/persistence/principalPolicyBundleIntegrity.js +1 -1
  124. package/data/persistence/principalPolicyBundleIntegrity.js.map +1 -1
  125. package/data/persistence/principalPolicyReferenceCheckpoint.js +1 -1
  126. package/data/persistence/principalPolicyReferenceCheckpoint.js.map +1 -1
  127. package/data/persistence/principalPolicyReferenceIndexPersistence.js +1 -1
  128. package/data/persistence/principalPolicyReferenceIndexPersistence.js.map +1 -1
  129. package/data/persistence/principalPolicyReferencePersistence.js +1 -1
  130. package/data/persistence/principalPolicyReferencePersistence.js.map +1 -1
  131. package/data/persistence/securityIncidentPersistence.js.map +1 -1
  132. package/data/persistence/verifiedPrincipalPolicyBundle.js +1 -1
  133. package/data/persistence/verifiedPrincipalPolicyBundle.js.map +1 -1
  134. package/data/persistence/verifiedPrincipalPolicyCurrent.js +1 -1
  135. package/data/persistence/verifiedPrincipalPolicyCurrent.js.map +1 -1
  136. package/data/principals/principalMutationJournal.js +1 -1
  137. package/data/principals/principalMutationJournal.js.map +1 -1
  138. package/data/{securityIncidents.d.ts → shared/securityIncidents.d.ts} +1 -1
  139. package/data/sqlite/documentRecordPersistence.js +1 -1
  140. package/data/sqlite/documentRecordPersistence.js.map +1 -1
  141. package/data/sync/crdtPeerSeed.d.ts +18 -0
  142. package/data/sync/originatedDocuments.d.ts +1 -1
  143. package/data/sync/originatedDocuments.js.map +1 -1
  144. package/data/sync/syncCoordinator.d.ts +1 -1
  145. package/data/sync/syncCoordinator.js.map +1 -1
  146. package/index.d.ts +4 -4
  147. package/index.js +2 -2
  148. package/index.js.map +1 -1
  149. package/package.json +1 -1
  150. package/stores/container-contents/backgroundHydration.js +1 -1
  151. package/stores/container-contents/backgroundHydration.js.map +1 -1
  152. package/stores/container-contents/containerContentsStore.d.ts +1 -1
  153. package/stores/container-contents/containerContentsStore.js.map +1 -1
  154. package/stores/container-contents/localRefresh.js +1 -1
  155. package/stores/container-contents/localRefresh.js.map +1 -1
  156. package/stores/container-contents/remoteContainerIngestion.js +1 -1
  157. package/stores/container-contents/remoteContainerIngestion.js.map +1 -1
  158. package/stores/container-contents/remoteWriteQueue.js +1 -1
  159. package/stores/container-contents/remoteWriteQueue.js.map +1 -1
  160. package/stores/container-contents/systemContainerHydration.js +1 -1
  161. package/stores/container-contents/systemContainerHydration.js.map +1 -1
  162. package/stores/container-contents/utils.js +1 -1
  163. package/stores/container-contents/utils.js.map +1 -1
  164. package/stores/documents/documentStore/attachmentIntents.js +1 -1
  165. package/stores/documents/documentStore/attachmentIntents.js.map +1 -1
  166. package/stores/documents/documentStore/attachmentSourceUpload.js.map +1 -1
  167. package/stores/documents/documentStore/attachmentStaging.js +1 -1
  168. package/stores/documents/documentStore/attachmentStaging.js.map +1 -1
  169. package/stores/documents/documentStore/attachmentUploadLane.js.map +1 -1
  170. package/stores/documents/documentStore/persistence.js +2 -2
  171. package/stores/documents/documentStore/persistence.js.map +1 -1
  172. package/stores/documents/documentStore/state.js +1 -1
  173. package/stores/documents/documentStore/state.js.map +1 -1
  174. package/stores/documents/documentStore/storedDocument.js +1 -1
  175. package/stores/documents/documentStore/storedDocument.js.map +1 -1
  176. package/stores/documents/documentStore/syncAttachments.js.map +1 -1
  177. package/stores/documents/documentStore.d.ts +1 -1
  178. package/stores/documents/documentStore.js.map +1 -1
  179. package/stores/documents/registry.d.ts +1 -1
  180. package/stores/documents/registry.js.map +1 -1
  181. package/stores/documents/types.d.ts +1 -1
  182. package/stores/documents/types.js.map +1 -1
  183. package/stores/local-projection/registry.d.ts +1 -1
  184. package/stores/local-projection/registry.js.map +1 -1
  185. package/sync/reconciliation/serviceTypes.d.ts +1 -1
  186. package/sync/reconciliation/serviceTypes.js.map +1 -1
  187. package/sync/reconciliation/triggers.d.ts +1 -1
  188. package/sync/reconciliation/triggers.js.map +1 -1
  189. package/workflows/blobs/attachmentBindingVerification.js +2 -2
  190. package/workflows/blobs/attachmentBindingVerification.js.map +1 -1
  191. package/workflows/blobs/blobChunkDecryption.js.map +1 -1
  192. package/workflows/blobs/decrypt.d.ts +1 -1
  193. package/workflows/blobs/decrypt.js +2 -2
  194. package/workflows/blobs/decrypt.js.map +1 -1
  195. package/workflows/blobs/detach.js +2 -2
  196. package/workflows/blobs/detach.js.map +1 -1
  197. package/workflows/blobs/hydrate.d.ts +3 -3
  198. package/workflows/blobs/hydrate.js +1 -1
  199. package/workflows/blobs/hydrate.js.map +1 -1
  200. package/workflows/blobs/hydrationResults.js.map +1 -1
  201. package/workflows/blobs/index.d.ts +2 -2
  202. package/workflows/blobs/index.js +1 -1
  203. package/workflows/blobs/index.js.map +1 -1
  204. package/workflows/blobs/multipartFirstParts.js.map +1 -1
  205. package/workflows/blobs/retainedAttachmentVerification.js +1 -1
  206. package/workflows/blobs/upload.js +3 -3
  207. package/workflows/blobs/upload.js.map +1 -1
  208. package/workflows/container-contents/container-state/createAdoption.js +1 -1
  209. package/workflows/container-contents/container-state/createAdoption.js.map +1 -1
  210. package/workflows/container-contents/container-state/createChild.js +1 -1
  211. package/workflows/container-contents/container-state/createChild.js.map +1 -1
  212. package/workflows/container-contents/container-state/createIntentSync.js +1 -1
  213. package/workflows/container-contents/container-state/createIntentSync.js.map +1 -1
  214. package/workflows/container-contents/container-state/groupGrantVerification.js +1 -1
  215. package/workflows/container-contents/container-state/moveIntentSync.js +1 -1
  216. package/workflows/container-contents/container-state/moveIntentSync.js.map +1 -1
  217. package/workflows/container-contents/container-state/purgeTreeScope.js +1 -1
  218. package/workflows/container-contents/container-state/purgeTreeScope.js.map +1 -1
  219. package/workflows/container-contents/container-state/share.js +1 -1
  220. package/workflows/container-contents/documentDiscoveryInputs.js +1 -1
  221. package/workflows/container-contents/documentDiscoveryInputs.js.map +1 -1
  222. package/workflows/container-contents/documentInfo.d.ts +1 -1
  223. package/workflows/container-contents/documentInfo.js.map +1 -1
  224. package/workflows/container-contents/documentLinks.d.ts +1 -1
  225. package/workflows/container-contents/documentLinks.js +1 -1
  226. package/workflows/container-contents/documentLinks.js.map +1 -1
  227. package/workflows/container-contents/documentMoveIntentSync.js +1 -1
  228. package/workflows/container-contents/documentMoveIntentSync.js.map +1 -1
  229. package/workflows/container-contents/documentPurge.d.ts +1 -1
  230. package/workflows/container-contents/documentPurge.js +1 -1
  231. package/workflows/container-contents/documentPurge.js.map +1 -1
  232. package/workflows/container-contents/documentQueries/rows.js +1 -1
  233. package/workflows/container-contents/documentQueries/rows.js.map +1 -1
  234. package/workflows/container-contents/metadata.d.ts +1 -1
  235. package/workflows/container-contents/metadataMutationPreparation.js +1 -1
  236. package/workflows/container-contents/metadataMutationPreparation.js.map +1 -1
  237. package/workflows/container-contents/metadataRemoteSync.d.ts +1 -1
  238. package/workflows/container-contents/metadataSyncErrors.js.map +1 -1
  239. package/workflows/container-contents/projectionKeys.d.ts +1 -1
  240. package/workflows/container-contents/syncLane.d.ts +1 -1
  241. package/workflows/container-contents/syncLane.js.map +1 -1
  242. package/workflows/containers/child/carriedDescendantRekeys.js +1 -1
  243. package/workflows/containers/child/create.d.ts +1 -1
  244. package/workflows/containers/child/create.js +2 -2
  245. package/workflows/containers/child/create.js.map +1 -1
  246. package/workflows/containers/child/createProjection.js +1 -1
  247. package/workflows/containers/child/createProjection.js.map +1 -1
  248. package/workflows/containers/child/createSubmission.d.ts +2 -2
  249. package/workflows/containers/child/createSubmission.js.map +1 -1
  250. package/workflows/containers/child/move.d.ts +2 -2
  251. package/workflows/containers/child/move.js +2 -2
  252. package/workflows/containers/child/move.js.map +1 -1
  253. package/workflows/containers/child/moveWraps.js +1 -1
  254. package/workflows/containers/child/mutationRequestCore.js +1 -1
  255. package/workflows/containers/child/mutationRequestCore.js.map +1 -1
  256. package/workflows/containers/child/mutationSubmit.js.map +1 -1
  257. package/workflows/containers/child/recite.js.map +1 -1
  258. package/workflows/containers/child/recitePlan.js +1 -1
  259. package/workflows/containers/child/recitePlan.js.map +1 -1
  260. package/workflows/containers/child/rekey.d.ts +1 -1
  261. package/workflows/containers/child/rekey.js +2 -2
  262. package/workflows/containers/child/rekey.js.map +1 -1
  263. package/workflows/containers/child/rekeyProjection.js +1 -1
  264. package/workflows/containers/child/rekeyProjection.js.map +1 -1
  265. package/workflows/containers/child/rekeyRemote.d.ts +2 -2
  266. package/workflows/containers/child/rekeyRemote.js.map +1 -1
  267. package/workflows/containers/child/revoke.d.ts +2 -2
  268. package/workflows/containers/child/revoke.js +2 -2
  269. package/workflows/containers/child/revoke.js.map +1 -1
  270. package/workflows/containers/child/rotationPrincipalPolicies.js +1 -1
  271. package/workflows/containers/child/runtimeCurrentGroupShare.js +1 -1
  272. package/workflows/containers/child/share.d.ts +2 -2
  273. package/workflows/containers/child/share.js +1 -1
  274. package/workflows/containers/child/share.js.map +1 -1
  275. package/workflows/containers/child/shareAncestorRepair.js.map +1 -1
  276. package/workflows/containers/child/shareMaterialization.d.ts +1 -1
  277. package/workflows/containers/child/sharePlanCore.d.ts +1 -1
  278. package/workflows/containers/child/sharePlanCore.js +1 -1
  279. package/workflows/containers/root/create.js +1 -1
  280. package/workflows/containers/root/create.js.map +1 -1
  281. package/workflows/containers/root/initialGroupPolicy.js +1 -1
  282. package/workflows/containers/root/initialGroupPolicy.js.map +1 -1
  283. package/workflows/documents/create.d.ts +1 -1
  284. package/workflows/documents/create.js +1 -1
  285. package/workflows/documents/documentMutationPreparation.js +1 -1
  286. package/workflows/documents/documentMutationPreparation.js.map +1 -1
  287. package/workflows/documents/historyContent.js +1 -1
  288. package/workflows/documents/historyContent.js.map +1 -1
  289. package/workflows/documents/linkSet.js +1 -1
  290. package/workflows/documents/linkSet.js.map +1 -1
  291. package/workflows/documents/linkSetAuthority.js +1 -1
  292. package/workflows/documents/linkSetBlobRewraps.js +2 -2
  293. package/workflows/documents/linkSetBlobRewraps.js.map +1 -1
  294. package/workflows/documents/linkSetRemote.d.ts +1 -1
  295. package/workflows/documents/linkSetRemote.js +1 -1
  296. package/workflows/documents/orphanBlobReclaims.js +1 -1
  297. package/workflows/documents/orphanBlobReclaims.js.map +1 -1
  298. package/workflows/documents/projectionKeys.d.ts +1 -1
  299. package/workflows/documents/purge.d.ts +1 -1
  300. package/workflows/documents/purge.js +2 -2
  301. package/workflows/documents/purge.js.map +1 -1
  302. package/workflows/documents/readOnlySync.d.ts +1 -1
  303. package/workflows/documents/readOnlySync.js +1 -1
  304. package/workflows/documents/readOnlySync.js.map +1 -1
  305. package/workflows/documents/sync.js +1 -1
  306. package/workflows/documents/syncContainerRekeyPreparation.js +1 -1
  307. package/workflows/documents/syncLane.d.ts +1 -1
  308. package/workflows/documents/syncLane.js.map +1 -1
  309. package/workflows/documents/syncPlanIdentity.js +1 -1
  310. package/workflows/documents/syncPlanIdentity.js.map +1 -1
  311. package/workflows/documents/syncRepairAccess.js +1 -1
  312. package/workflows/documents/syncSubmittedResult.js +1 -1
  313. package/workflows/organizations/authoredPrincipalPolicyWarmer.js +1 -1
  314. package/workflows/organizations/authoredPrincipalPolicyWarmer.js.map +1 -1
  315. package/workflows/organizations/containerGrantRevocation.d.ts +2 -2
  316. package/workflows/organizations/containerGrantRevocation.js.map +1 -1
  317. package/workflows/organizations/createCurrentOrganizationGroup.js.map +1 -1
  318. package/workflows/organizations/currentOrganizationGroupNames.js.map +1 -1
  319. package/workflows/organizations/currentOrganizationMutationRetention.js +1 -1
  320. package/workflows/organizations/currentOrganizationMutationRetention.js.map +1 -1
  321. package/workflows/organizations/currentPolicyMutationAcknowledgement.js +1 -1
  322. package/workflows/organizations/currentPolicyMutationAcknowledgement.js.map +1 -1
  323. package/workflows/organizations/groupCreation.d.ts +1 -1
  324. package/workflows/organizations/groupCreation.js.map +1 -1
  325. package/workflows/organizations/groupMetadataAccess.d.ts +1 -1
  326. package/workflows/organizations/groupMetadataContainerAuthority.js.map +1 -1
  327. package/workflows/organizations/groupMetadataRuntime.js.map +1 -1
  328. package/workflows/organizations/groupNameUniqueness.js.map +1 -1
  329. package/workflows/organizations/groupPolicyMutationAcknowledgement.js +1 -1
  330. package/workflows/organizations/groupPolicyMutationAcknowledgement.js.map +1 -1
  331. package/workflows/organizations/groupPolicyRequests.js.map +1 -1
  332. package/workflows/organizations/index.d.ts +0 -1
  333. package/workflows/organizations/index.js +0 -1
  334. package/workflows/organizations/index.js.map +1 -1
  335. package/workflows/organizations/loadPolicyHistoryDetails.js.map +1 -1
  336. package/workflows/organizations/organizationGroupDirectory.js.map +1 -1
  337. package/workflows/organizations/organizationProfile.js +1 -1
  338. package/workflows/organizations/organizationProfile.js.map +1 -1
  339. package/workflows/organizations/policyHistoryCache.js.map +1 -1
  340. package/workflows/organizations/principalContainerRematerialization.js +1 -1
  341. package/workflows/organizations/principalContainerRematerializationPlanning.js.map +1 -1
  342. package/workflows/organizations/principalMutationJournalManagement.js +1 -1
  343. package/workflows/organizations/principalMutationJournalManagement.js.map +1 -1
  344. package/workflows/organizations/principalMutationReceipt.js +1 -1
  345. package/workflows/organizations/principalMutationReceipt.js.map +1 -1
  346. package/workflows/organizations/principalPolicy.d.ts +1 -1
  347. package/workflows/organizations/principalPolicy.js.map +1 -1
  348. package/workflows/organizations/principalPolicyReceiptArtifacts.js +1 -1
  349. package/workflows/organizations/principalPolicyReceiptArtifacts.js.map +1 -1
  350. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.d.ts +4 -24
  351. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js +13 -133
  352. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js.map +1 -1
  353. package/workflows/organizations/rosterProfileContainer.js +1 -1
  354. package/workflows/organizations/rosterProfileContainer.js.map +1 -1
  355. package/workflows/organizations/runtimeCurrentGroupMutation.js +1 -1
  356. package/workflows/organizations/runtimeCurrentGroupMutation.js.map +1 -1
  357. package/workflows/principals/acknowledgedPrincipalCurrents.d.ts +33 -0
  358. package/workflows/principals/acknowledgedPrincipalCurrents.js +140 -0
  359. package/workflows/principals/acknowledgedPrincipalCurrents.js.map +1 -0
  360. package/workflows/{organizations → principals}/acknowledgedPrincipalPredecessor.d.ts +1 -1
  361. package/workflows/{organizations → principals}/acknowledgedPrincipalPredecessor.js +1 -1
  362. package/workflows/principals/acknowledgedPrincipalPredecessor.js.map +1 -0
  363. package/workflows/principals/index.d.ts +1 -0
  364. package/workflows/principals/index.js +1 -0
  365. package/workflows/principals/index.js.map +1 -1
  366. package/workflows/{organizations → principals}/initialPrincipalCurrentPublication.js +5 -7
  367. package/workflows/principals/initialPrincipalCurrentPublication.js.map +1 -0
  368. package/workflows/principals/policyCache.d.ts +1 -1
  369. package/workflows/principals/policyCache.js +2 -2
  370. package/workflows/principals/policyCache.js.map +1 -1
  371. package/workflows/principals/principalAcknowledgementChecks.d.ts +30 -0
  372. package/workflows/principals/principalAcknowledgementChecks.js +2 -0
  373. package/workflows/principals/principalAcknowledgementChecks.js.map +1 -0
  374. package/workflows/{organizations → principals}/principalCurrentPublicationSeal.js.map +1 -1
  375. package/workflows/{organizations → principals}/reconcileAcknowledgedPrincipalCurrent.js +2 -2
  376. package/workflows/principals/reconcileAcknowledgedPrincipalCurrent.js.map +1 -0
  377. package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
  378. package/workflows/principals/runtimePolicyWarmer.js +1 -1
  379. package/workflows/principals/runtimePolicyWarmer.js.map +1 -1
  380. package/workflows/registration/persistRegistrationBootstrap.js +1 -1
  381. package/workflows/registration/persistRegistrationBootstrap.js.map +1 -1
  382. package/workflows/runtimeInput.d.ts +3 -3
  383. package/workflows/runtimeInput.js.map +1 -1
  384. package/workflows/sync/index.d.ts +2 -1
  385. package/workflows/sync/index.js +2 -1
  386. package/workflows/sync/index.js.map +1 -1
  387. package/data/keyingCanonicalJson.js.map +0 -1
  388. package/data/keyingProjectionVerification.d.ts +0 -9
  389. package/data/keyingProjectionVerification.js.map +0 -1
  390. package/workflows/organizations/acknowledgedPrincipalPredecessor.js.map +0 -1
  391. package/workflows/organizations/initialPrincipalCurrentPublication.js.map +0 -1
  392. package/workflows/organizations/reconcileAcknowledgedPrincipalCurrent.js.map +0 -1
  393. /package/data/{blobContracts.d.ts → blobs/blobContracts.d.ts} +0 -0
  394. /package/data/{blobContracts.js → blobs/blobContracts.js} +0 -0
  395. /package/data/{blobContracts.js.map → blobs/blobContracts.js.map} +0 -0
  396. /package/data/{accessLevel.js → keying/accessLevel.js} +0 -0
  397. /package/data/{accessLevel.js.map → keying/accessLevel.js.map} +0 -0
  398. /package/data/{stableUuid.js → keying/stableUuid.js} +0 -0
  399. /package/data/{stableUuid.js.map → keying/stableUuid.js.map} +0 -0
  400. /package/data/{principalPolicyStates.js → principals/principalPolicyStates.js} +0 -0
  401. /package/data/{principalPolicyStates.js.map → principals/principalPolicyStates.js.map} +0 -0
  402. /package/data/{domainScope.d.ts → shared/domainScope.d.ts} +0 -0
  403. /package/data/{domainScope.js → shared/domainScope.js} +0 -0
  404. /package/data/{domainScope.js.map → shared/domainScope.js.map} +0 -0
  405. /package/data/{errorMessage.js → shared/errorMessage.js} +0 -0
  406. /package/data/{errorMessage.js.map → shared/errorMessage.js.map} +0 -0
  407. /package/data/{recordReaders.d.ts → shared/recordReaders.d.ts} +0 -0
  408. /package/data/{recordReaders.js → shared/recordReaders.js} +0 -0
  409. /package/data/{recordReaders.js.map → shared/recordReaders.js.map} +0 -0
  410. /package/data/{securityIncidents.js → shared/securityIncidents.js} +0 -0
  411. /package/data/{securityIncidents.js.map → shared/securityIncidents.js.map} +0 -0
  412. /package/data/{crdtPeerSeed.js → sync/crdtPeerSeed.js} +0 -0
  413. /package/data/{crdtPeerSeed.js.map → sync/crdtPeerSeed.js.map} +0 -0
  414. /package/workflows/{organizations → principals}/principalCurrentPublicationSeal.js +0 -0
@@ -7,8 +7,8 @@ import { importContentKeyMaterial } from "../../data/documents/shared/contentRec
7
7
  import { assertDocumentWriterProjectionConsistent } from "../../data/documents/shared/projection.js";
8
8
  import { asWebCryptoBytes, readWriteHeader, uniqueSortedStrings, } from "../../data/documents/shared/readers.js";
9
9
  import { projectionVerificationOptions } from "../../data/documents/shared/types.js";
10
- import { readCanonicalRecord } from "../../data/keyingCanonicalJson.js";
11
- import { readRecordString, requireProjectionUserKeyResolver, } from "../../data/keyingProjectionVerification.js";
10
+ import { readCanonicalRecord } from "../../data/keying/canonicalJson.js";
11
+ import { readRecordString, requireProjectionUserKeyResolver, } from "../../data/keyingProjectionVerification/index.js";
12
12
  import { resolveEventContainerPaths } from "../../data/keyingProjectionVerification/documentDependencyPaths.js";
13
13
  import { assertAttachmentBindingVerified } from "./attachmentBindingVerification.js";
14
14
  import { decryptBlobChunks } from "./blobChunkDecryption.js";
@@ -1 +1 @@
1
- {"version":3,"file":"decrypt.js","sourceRoot":"","sources":["decrypt.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,UAAU,EACV,+BAA+B,EAC/B,6BAA6B,EAC7B,+BAA+B,EAC/B,mCAAmC,EACnC,0BAA0B,EAC1B,iBAAiB,GAClB,MAAM,mBAAmB,CAAC;AAG3B,OAAO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,CAAC,SAAS,CAAC,eAAe,EAC1D,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,wDAAwD,CAAC,CAAC;IAC5E,CAAC;IACD,MAAM,QAAQ,GAAG,MAAM,iBAAiB,CAAC;QACvC,uBAAuB,EAAE,YAAY;QACrC,iBAAiB,EAAE;YACjB,yBAAyB,EAAE,0BAA0B,CAAC;gBACpD,2BAA2B,EACzB,KAAK,CAAC,aAAa,CAAC,2BAA2B;gBACjD,wBAAwB,EAAE,MAAM,CAAC,wBAAwB;aAC1D,CAAC,CAAC,wBAAwB;YAC3B,cAAc;YACd,iBAAiB,EAAE,KAAK,CAAC,aAAa,CAAC,iBAAiB;SACzD;QACD,0BAA0B,EAAE,cAAc,CAAC,sBAAsB;QACjE,cAAc,EAAE;YACd,UAAU,EAAE,MAAM;YAClB,QAAQ,EAAE,KAAK,CAAC,OAAO,CAAC,MAAM;YAC9B,cAAc,EAAE,KAAK,CAAC,cAAc;SACrC;QACD,kBAAkB,EAAE,cAAc,CAAC,iBAAiB;QACpD,MAAM;QACN,eAAe,EAAE,MAAM,CAAC,gBAAgB;KACzC,CAAC,CAAC;IACH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;QACjB,MAAM,QAAQ,CAAC,KAAK,CAAC;IACvB,CAAC;AACH,CAAC","sourcesContent":["import {\n blobContentMetadataHash,\n bytesToHex,\n CONTENT_RECORD_ENCRYPTION_SUITE,\n computeBlobAccessManifestHash,\n computeBlobContentKeyTargetHash,\n computeContentRecordNonceDomainHash,\n makeVerifiedBlobKekTargets,\n verifyWriteHeader,\n} from \"@tearleads/crypto\";\nimport type { BlobKekTargetsResponse } from \"@tearleads/validators/response\";\nimport type { BlobBytes } from \"../../data/blobContracts\";\nimport { deriveBlobContentRecordKey } from \"../../data/documents/blob/shared/crypto\";\nimport { unwrapBlobContentKey } from \"../../data/documents/blob/shared/projection\";\nimport {\n parseBlobEncryptedBytes,\n readBlobKekTarget,\n readDocumentManifestIdentity,\n sortBlobTargets,\n} from \"../../data/documents/blob/shared/readers\";\nimport { assertBlobContentKeyBundleTargetHash } from \"../../data/documents/blob/shared/responses\";\nimport type {\n BlobEncryptedBytesHeader,\n DecryptDocumentAttachmentBlobInput,\n} from \"../../data/documents/blob/shared/types\";\nimport { importContentKeyMaterial } from \"../../data/documents/shared/contentRecordKeys\";\nimport { assertDocumentWriterProjectionConsistent } from \"../../data/documents/shared/projection\";\nimport {\n asWebCryptoBytes,\n readWriteHeader,\n uniqueSortedStrings,\n} from \"../../data/documents/shared/readers\";\nimport { projectionVerificationOptions } from \"../../data/documents/shared/types\";\nimport { readCanonicalRecord } from \"../../data/keyingCanonicalJson\";\nimport type { DocumentWriterProjectionAuthorization } from \"../../data/keyingProjectionVerification\";\nimport {\n readRecordString,\n requireProjectionUserKeyResolver,\n} from \"../../data/keyingProjectionVerification\";\nimport { resolveEventContainerPaths } from \"../../data/keyingProjectionVerification/documentDependencyPaths\";\n\nimport { assertAttachmentBindingVerified } from \"./attachmentBindingVerification\";\nimport { decryptBlobChunks } from \"./blobChunkDecryption\";\nimport { assertBlobWrapScopeVerified } from \"./verifiedWrapScope\";\n\nasync function assertBlobEncryptionMetadata(input: {\n readonly contentKeyBundle: DecryptDocumentAttachmentBlobInput[\"binding\"][\"contentKeyBundle\"];\n readonly encrypted: BlobEncryptedBytesHeader;\n readonly expectedBlobId: string;\n readonly organizationId: string;\n}): Promise<void> {\n const { contentKeyBundle, encrypted, expectedBlobId, organizationId } = input;\n if (\n encrypted.blobId !== expectedBlobId ||\n encrypted.contentRecordId !== expectedBlobId\n ) {\n throw new Error(\"Blob encrypted bytes blob id mismatch\");\n }\n if (\n encrypted.contentKeyEpoch !== contentKeyBundle.contentKeyEpoch ||\n contentKeyBundle.blobId !== expectedBlobId\n ) {\n throw new Error(\"Blob encrypted bytes content-key bundle mismatch\");\n }\n await assertBlobContentKeyBundleTargetHash(contentKeyBundle);\n\n const expectedNonceDomainHash = await computeContentRecordNonceDomainHash({\n version: 1,\n organizationId,\n objectKind: \"blob\",\n objectId: expectedBlobId,\n contentKeyEpoch: encrypted.contentKeyEpoch,\n encryptionSuite: CONTENT_RECORD_ENCRYPTION_SUITE,\n contentRecordId: encrypted.contentRecordId,\n });\n if (encrypted.nonceDomainHash !== expectedNonceDomainHash) {\n throw new Error(\"Blob encrypted bytes nonce domain mismatch\");\n }\n const expectedMetadataHash = await blobContentMetadataHash({\n blobId: expectedBlobId,\n byteLength: encrypted.byteLength,\n chunkCount: encrypted.chunkCount,\n chunkSize: encrypted.chunkSize,\n contentKeyEpoch: encrypted.contentKeyEpoch,\n });\n if (encrypted.metadataHash !== expectedMetadataHash) {\n throw new Error(\"Blob encrypted bytes metadata hash mismatch\");\n }\n}\n\nexport type AttachmentBlobDecryptionInput = Omit<\n DecryptDocumentAttachmentBlobInput,\n \"encryptedBytes\"\n> & {\n encrypted: BlobEncryptedBytesHeader;\n};\n\n/** Verifies metadata and authority; the caller must still authenticate ciphertext. */\nexport async function prepareDocumentAttachmentBlobDecryption({\n binding,\n encrypted,\n expectedDocumentId,\n expectedSlotId,\n execSql,\n resolveProjectionUserKey,\n targetSecretKey,\n stillCurrent,\n warmReferencedPrincipalPolicies,\n writerProjection,\n}: AttachmentBlobDecryptionInput): Promise<{\n contentKey: Uint8Array;\n recordKey: CryptoKey;\n organizationId: string;\n}> {\n const requiredResolveProjectionUserKey = requireProjectionUserKeyResolver(\n resolveProjectionUserKey,\n \"Document attachment blob decrypt\",\n );\n const verificationOptions = projectionVerificationOptions({\n execSql,\n stillCurrent,\n warmReferencedPrincipalPolicies,\n resolveProjectionUserKey: requiredResolveProjectionUserKey,\n });\n let documentAuthorization: DocumentWriterProjectionAuthorization | undefined;\n await assertDocumentWriterProjectionConsistent(writerProjection, {\n allowStaleContentKeyBundle: true,\n execSql,\n onVerifiedAuthorization: (authorization) => {\n documentAuthorization = authorization;\n },\n ...verificationOptions,\n });\n const { documentId, organizationId } =\n readDocumentManifestIdentity(writerProjection);\n await assertBlobEncryptionMetadata({\n contentKeyBundle: binding.contentKeyBundle,\n encrypted,\n expectedBlobId: binding.blobId,\n organizationId,\n });\n await assertAttachmentBindingVerified({\n authorization: documentAuthorization,\n binding,\n expectedDocumentId,\n expectedSlotId,\n resolveProjectionUserKey: requiredResolveProjectionUserKey,\n });\n await assertBlobWriteHeaderVerified({\n authorization: documentAuthorization,\n binding,\n encrypted,\n organizationId,\n resolveProjectionUserKey: requiredResolveProjectionUserKey,\n });\n\n if (!documentAuthorization)\n throw new Error(\"Blob document authorization is unavailable\");\n assertBlobWrapScopeVerified({\n authorization: documentAuthorization,\n binding,\n documentId,\n });\n const contentKey = await unwrapBlobContentKey({\n blobId: binding.blobId,\n contentKeyBundle: binding.contentKeyBundle,\n documentId,\n encrypted,\n execSql,\n expectedBindingId: binding.bindingId,\n secretKey: targetSecretKey,\n ...verificationOptions,\n writerProjection,\n });\n const contentKeyMaterial = await importContentKeyMaterial(contentKey);\n const recordKey = await deriveBlobContentRecordKey({\n blobId: binding.blobId,\n contentKeyEpoch: encrypted.contentKeyEpoch,\n contentKeyMaterial,\n contentRecordId: encrypted.contentRecordId,\n organizationId,\n usage: \"decrypt\",\n });\n return { contentKey, recordKey, organizationId };\n}\n\nasync function decryptDocumentAttachmentBlobWithKey(\n input: DecryptDocumentAttachmentBlobInput,\n): Promise<{ bytes: BlobBytes; contentKey: Uint8Array }> {\n const encrypted = parseBlobEncryptedBytes(input.encryptedBytes);\n const context = await prepareDocumentAttachmentBlobDecryption({\n ...input,\n encrypted,\n });\n const header = readWriteHeader(\n input.binding.writeHeader,\n \"Attachment blob write header\",\n );\n const ciphertextHash = bytesToHex(\n new Uint8Array(\n await crypto.subtle.digest(\n \"SHA-256\",\n asWebCryptoBytes(input.encryptedBytes),\n ),\n ),\n );\n if (header.ciphertextHash !== ciphertextHash)\n throw new Error(\"Attachment blob write header does not match ciphertext\");\n const bytes = await decryptBlobChunks({\n ...context,\n encrypted,\n expectedBlobId: input.binding.blobId,\n });\n return { bytes, contentKey: context.contentKey };\n}\n\nexport async function decryptDocumentAttachmentBlob(\n input: DecryptDocumentAttachmentBlobInput,\n): Promise<BlobBytes> {\n return (await decryptDocumentAttachmentBlobWithKey(input)).bytes;\n}\n\nfunction assertStringSetEquals(input: {\n readonly actual: readonly string[];\n readonly expected: readonly string[];\n readonly label: string;\n}): void {\n const actual = uniqueSortedStrings(input.actual);\n const expected = uniqueSortedStrings(input.expected);\n if (\n actual.length !== expected.length ||\n actual.some((value, index) => value !== expected[index])\n ) {\n throw new Error(`${input.label} is inconsistent`);\n }\n}\n\nasync function verifiedBlobKekTargetsForBinding(input: {\n readonly binding: DecryptDocumentAttachmentBlobInput[\"binding\"];\n readonly requireBindingMembership: boolean;\n readonly projection: BlobKekTargetsResponse | undefined;\n}) {\n const { binding, projection } = input;\n if (!projection) {\n throw new Error(\"Attachment binding lacks blob KEK verification material\");\n }\n const targets = sortBlobTargets(\n projection.targets.map((target, index) =>\n readBlobKekTarget(target, `Attachment blob KEK target[${index}]`),\n ),\n );\n const targetHash = await computeBlobContentKeyTargetHash(targets);\n if (\n targetHash !== projection.blobKeyTargetHash ||\n projection.blobId !== binding.blobId\n ) {\n throw new Error(\"Attachment blob KEK target hash is inconsistent\");\n }\n if (\n input.requireBindingMembership &&\n (!projection.activeBindingIds.includes(binding.bindingId) ||\n !targets.some(\n (target) =>\n target.bindingId === binding.bindingId &&\n target.documentId === attachmentBindingDocumentId(binding),\n ))\n ) {\n throw new Error(\"Attachment binding is absent from blob KEK targets\");\n }\n assertStringSetEquals({\n actual: projection.linkedContainerManifestHashes,\n expected: targets.map((target) => target.containerManifestHash),\n label: \"Attachment blob container manifests\",\n });\n assertStringSetEquals({\n actual: projection.linkedContainerKeyEpochIds,\n expected: targets.map((target) => target.containerKeyEpochId),\n label: \"Attachment blob container KEKs\",\n });\n const accessManifestHash = await computeBlobAccessManifestHash({\n version: 1,\n blobId: projection.blobId,\n organizationId: projection.organizationId,\n activeBindingIds: projection.activeBindingIds,\n documentManifestHashes: projection.documentManifestHashes,\n linkedContainerManifestHashes: projection.linkedContainerManifestHashes,\n linkedContainerKeyEpochIds: projection.linkedContainerKeyEpochIds,\n blobKeyTargetHash: projection.blobKeyTargetHash,\n });\n if (accessManifestHash !== projection.blobAccessManifestHash) {\n throw new Error(\"Attachment blob access manifest hash is inconsistent\");\n }\n return makeVerifiedBlobKekTargets({ ...projection, targets });\n}\n\nfunction attachmentBindingDocumentId(\n binding: DecryptDocumentAttachmentBlobInput[\"binding\"],\n): string {\n if (!binding.bindingEvent) {\n throw new Error(\"Attachment binding lacks a signed event\");\n }\n return readRecordString(\n readCanonicalRecord(\n binding.bindingEvent.body,\n \"Attachment binding event body\",\n ),\n \"documentId\",\n \"Attachment binding event body\",\n );\n}\n\nasync function assertBlobWriteHeaderVerified(input: {\n readonly authorization: DocumentWriterProjectionAuthorization | undefined;\n readonly binding: DecryptDocumentAttachmentBlobInput[\"binding\"];\n readonly encrypted: BlobEncryptedBytesHeader;\n readonly organizationId: string;\n readonly resolveProjectionUserKey: ReturnType<\n typeof requireProjectionUserKeyResolver\n >;\n}): Promise<void> {\n if (!input.authorization || !input.binding.writeHeader) {\n throw new Error(\"Attachment blob lacks verified write authority\");\n }\n const header = readWriteHeader(\n input.binding.writeHeader,\n \"Attachment blob write header\",\n );\n const writer = await input.resolveProjectionUserKey(header.writerUserId);\n if (!writer) {\n throw new Error(\"Attachment blob writer identity is unavailable\");\n }\n await verifiedBlobKekTargetsForBinding({\n binding: input.binding,\n projection: input.binding.blobKekTargets,\n requireBindingMembership: true,\n });\n const blobKekTargets = await verifiedBlobKekTargetsForBinding({\n binding: input.binding,\n projection: input.binding.writeAuthorization,\n // The signed binding proves which slot exposes the blob now. Writer\n // authorization describes the older target set committed when the bytes\n // were written, so a later valid binding need not appear in that set.\n requireBindingMembership: false,\n });\n if (\n header.metadataHash !== input.encrypted.metadataHash ||\n header.contentKeyEpoch !== input.encrypted.contentKeyEpoch ||\n header.contentRecordId !== input.encrypted.contentRecordId ||\n header.nonceDomainHash !== input.encrypted.nonceDomainHash\n ) {\n throw new Error(\"Attachment blob write header does not match ciphertext\");\n }\n const verified = await verifyWriteHeader({\n authorizationMembership: \"referenced\",\n blobAuthorization: {\n authorizingContainerPaths: resolveEventContainerPaths({\n containerPathByManifestHash:\n input.authorization.containerPathByManifestHash,\n dependencyManifestHashes: header.dependencyManifestHashes,\n }).dependencyContainerPaths,\n blobKekTargets,\n principalPolicies: input.authorization.principalPolicies,\n },\n expectedAccessManifestHash: blobKekTargets.blobAccessManifestHash,\n expectedObject: {\n objectKind: \"blob\",\n objectId: input.binding.blobId,\n organizationId: input.organizationId,\n },\n expectedTargetHash: blobKekTargets.blobKeyTargetHash,\n header,\n writerPublicKey: writer.signingPublicKey,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n}\n"]}
1
+ {"version":3,"file":"decrypt.js","sourceRoot":"","sources":["decrypt.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,UAAU,EACV,+BAA+B,EAC/B,6BAA6B,EAC7B,+BAA+B,EAC/B,mCAAmC,EACnC,0BAA0B,EAC1B,iBAAiB,GAClB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,0BAA0B,EAAE,MAAM,yCAAyC,CAAC;AACrF,OAAO,EAAE,oBAAoB,EAAE,MAAM,6CAA6C,CAAC;AACnF,OAAO,EACL,uBAAuB,EACvB,iBAAiB,EACjB,4BAA4B,EAC5B,eAAe,GAChB,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAKlG,OAAO,EAAE,wBAAwB,EAAE,MAAM,+CAA+C,CAAC;AACzF,OAAO,EAAE,wCAAwC,EAAE,MAAM,wCAAwC,CAAC;AAClG,OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,mBAAmB,GACpB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,6BAA6B,EAAE,MAAM,mCAAmC,CAAC;AAClF,OAAO,EA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AE,MAAM;YAClB,QAAQ,EAAE,KAAK,CAAC,OAAO,CAAC,MAAM;YAC9B,cAAc,EAAE,KAAK,CAAC,cAAc;SACrC;QACD,kBAAkB,EAAE,cAAc,CAAC,iBAAiB;QACpD,MAAM;QACN,eAAe,EAAE,MAAM,CAAC,gBAAgB;KACzC,CAAC,CAAC;IACH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;QACjB,MAAM,QAAQ,CAAC,KAAK,CAAC;IACvB,CAAC;AACH,CAAC","sourcesContent":["import {\n blobContentMetadataHash,\n bytesToHex,\n CONTENT_RECORD_ENCRYPTION_SUITE,\n computeBlobAccessManifestHash,\n computeBlobContentKeyTargetHash,\n computeContentRecordNonceDomainHash,\n makeVerifiedBlobKekTargets,\n verifyWriteHeader,\n} from \"@tearleads/crypto\";\nimport type { BlobKekTargetsResponse } from \"@tearleads/validators/response\";\nimport type { BlobBytes } from \"../../data/blobs/blobContracts\";\nimport { deriveBlobContentRecordKey } from \"../../data/documents/blob/shared/crypto\";\nimport { unwrapBlobContentKey } from \"../../data/documents/blob/shared/projection\";\nimport {\n parseBlobEncryptedBytes,\n readBlobKekTarget,\n readDocumentManifestIdentity,\n sortBlobTargets,\n} from \"../../data/documents/blob/shared/readers\";\nimport { assertBlobContentKeyBundleTargetHash } from \"../../data/documents/blob/shared/responses\";\nimport type {\n BlobEncryptedBytesHeader,\n DecryptDocumentAttachmentBlobInput,\n} from \"../../data/documents/blob/shared/types\";\nimport { importContentKeyMaterial } from \"../../data/documents/shared/contentRecordKeys\";\nimport { assertDocumentWriterProjectionConsistent } from \"../../data/documents/shared/projection\";\nimport {\n asWebCryptoBytes,\n readWriteHeader,\n uniqueSortedStrings,\n} from \"../../data/documents/shared/readers\";\nimport { projectionVerificationOptions } from \"../../data/documents/shared/types\";\nimport { readCanonicalRecord } from \"../../data/keying/canonicalJson\";\nimport type { DocumentWriterProjectionAuthorization } from \"../../data/keyingProjectionVerification\";\nimport {\n readRecordString,\n requireProjectionUserKeyResolver,\n} from \"../../data/keyingProjectionVerification\";\nimport { resolveEventContainerPaths } from \"../../data/keyingProjectionVerification/documentDependencyPaths\";\n\nimport { assertAttachmentBindingVerified } from \"./attachmentBindingVerification\";\nimport { decryptBlobChunks } from \"./blobChunkDecryption\";\nimport { assertBlobWrapScopeVerified } from \"./verifiedWrapScope\";\n\nasync function assertBlobEncryptionMetadata(input: {\n readonly contentKeyBundle: DecryptDocumentAttachmentBlobInput[\"binding\"][\"contentKeyBundle\"];\n readonly encrypted: BlobEncryptedBytesHeader;\n readonly expectedBlobId: string;\n readonly organizationId: string;\n}): Promise<void> {\n const { contentKeyBundle, encrypted, expectedBlobId, organizationId } = input;\n if (\n encrypted.blobId !== expectedBlobId ||\n encrypted.contentRecordId !== expectedBlobId\n ) {\n throw new Error(\"Blob encrypted bytes blob id mismatch\");\n }\n if (\n encrypted.contentKeyEpoch !== contentKeyBundle.contentKeyEpoch ||\n contentKeyBundle.blobId !== expectedBlobId\n ) {\n throw new Error(\"Blob encrypted bytes content-key bundle mismatch\");\n }\n await assertBlobContentKeyBundleTargetHash(contentKeyBundle);\n\n const expectedNonceDomainHash = await computeContentRecordNonceDomainHash({\n version: 1,\n organizationId,\n objectKind: \"blob\",\n objectId: expectedBlobId,\n contentKeyEpoch: encrypted.contentKeyEpoch,\n encryptionSuite: CONTENT_RECORD_ENCRYPTION_SUITE,\n contentRecordId: encrypted.contentRecordId,\n });\n if (encrypted.nonceDomainHash !== expectedNonceDomainHash) {\n throw new Error(\"Blob encrypted bytes nonce domain mismatch\");\n }\n const expectedMetadataHash = await blobContentMetadataHash({\n blobId: expectedBlobId,\n byteLength: encrypted.byteLength,\n chunkCount: encrypted.chunkCount,\n chunkSize: encrypted.chunkSize,\n contentKeyEpoch: encrypted.contentKeyEpoch,\n });\n if (encrypted.metadataHash !== expectedMetadataHash) {\n throw new Error(\"Blob encrypted bytes metadata hash mismatch\");\n }\n}\n\nexport type AttachmentBlobDecryptionInput = Omit<\n DecryptDocumentAttachmentBlobInput,\n \"encryptedBytes\"\n> & {\n encrypted: BlobEncryptedBytesHeader;\n};\n\n/** Verifies metadata and authority; the caller must still authenticate ciphertext. */\nexport async function prepareDocumentAttachmentBlobDecryption({\n binding,\n encrypted,\n expectedDocumentId,\n expectedSlotId,\n execSql,\n resolveProjectionUserKey,\n targetSecretKey,\n stillCurrent,\n warmReferencedPrincipalPolicies,\n writerProjection,\n}: AttachmentBlobDecryptionInput): Promise<{\n contentKey: Uint8Array;\n recordKey: CryptoKey;\n organizationId: string;\n}> {\n const requiredResolveProjectionUserKey = requireProjectionUserKeyResolver(\n resolveProjectionUserKey,\n \"Document attachment blob decrypt\",\n );\n const verificationOptions = projectionVerificationOptions({\n execSql,\n stillCurrent,\n warmReferencedPrincipalPolicies,\n resolveProjectionUserKey: requiredResolveProjectionUserKey,\n });\n let documentAuthorization: DocumentWriterProjectionAuthorization | undefined;\n await assertDocumentWriterProjectionConsistent(writerProjection, {\n allowStaleContentKeyBundle: true,\n execSql,\n onVerifiedAuthorization: (authorization) => {\n documentAuthorization = authorization;\n },\n ...verificationOptions,\n });\n const { documentId, organizationId } =\n readDocumentManifestIdentity(writerProjection);\n await assertBlobEncryptionMetadata({\n contentKeyBundle: binding.contentKeyBundle,\n encrypted,\n expectedBlobId: binding.blobId,\n organizationId,\n });\n await assertAttachmentBindingVerified({\n authorization: documentAuthorization,\n binding,\n expectedDocumentId,\n expectedSlotId,\n resolveProjectionUserKey: requiredResolveProjectionUserKey,\n });\n await assertBlobWriteHeaderVerified({\n authorization: documentAuthorization,\n binding,\n encrypted,\n organizationId,\n resolveProjectionUserKey: requiredResolveProjectionUserKey,\n });\n\n if (!documentAuthorization)\n throw new Error(\"Blob document authorization is unavailable\");\n assertBlobWrapScopeVerified({\n authorization: documentAuthorization,\n binding,\n documentId,\n });\n const contentKey = await unwrapBlobContentKey({\n blobId: binding.blobId,\n contentKeyBundle: binding.contentKeyBundle,\n documentId,\n encrypted,\n execSql,\n expectedBindingId: binding.bindingId,\n secretKey: targetSecretKey,\n ...verificationOptions,\n writerProjection,\n });\n const contentKeyMaterial = await importContentKeyMaterial(contentKey);\n const recordKey = await deriveBlobContentRecordKey({\n blobId: binding.blobId,\n contentKeyEpoch: encrypted.contentKeyEpoch,\n contentKeyMaterial,\n contentRecordId: encrypted.contentRecordId,\n organizationId,\n usage: \"decrypt\",\n });\n return { contentKey, recordKey, organizationId };\n}\n\nasync function decryptDocumentAttachmentBlobWithKey(\n input: DecryptDocumentAttachmentBlobInput,\n): Promise<{ bytes: BlobBytes; contentKey: Uint8Array }> {\n const encrypted = parseBlobEncryptedBytes(input.encryptedBytes);\n const context = await prepareDocumentAttachmentBlobDecryption({\n ...input,\n encrypted,\n });\n const header = readWriteHeader(\n input.binding.writeHeader,\n \"Attachment blob write header\",\n );\n const ciphertextHash = bytesToHex(\n new Uint8Array(\n await crypto.subtle.digest(\n \"SHA-256\",\n asWebCryptoBytes(input.encryptedBytes),\n ),\n ),\n );\n if (header.ciphertextHash !== ciphertextHash)\n throw new Error(\"Attachment blob write header does not match ciphertext\");\n const bytes = await decryptBlobChunks({\n ...context,\n encrypted,\n expectedBlobId: input.binding.blobId,\n });\n return { bytes, contentKey: context.contentKey };\n}\n\nexport async function decryptDocumentAttachmentBlob(\n input: DecryptDocumentAttachmentBlobInput,\n): Promise<BlobBytes> {\n return (await decryptDocumentAttachmentBlobWithKey(input)).bytes;\n}\n\nfunction assertStringSetEquals(input: {\n readonly actual: readonly string[];\n readonly expected: readonly string[];\n readonly label: string;\n}): void {\n const actual = uniqueSortedStrings(input.actual);\n const expected = uniqueSortedStrings(input.expected);\n if (\n actual.length !== expected.length ||\n actual.some((value, index) => value !== expected[index])\n ) {\n throw new Error(`${input.label} is inconsistent`);\n }\n}\n\nasync function verifiedBlobKekTargetsForBinding(input: {\n readonly binding: DecryptDocumentAttachmentBlobInput[\"binding\"];\n readonly requireBindingMembership: boolean;\n readonly projection: BlobKekTargetsResponse | undefined;\n}) {\n const { binding, projection } = input;\n if (!projection) {\n throw new Error(\"Attachment binding lacks blob KEK verification material\");\n }\n const targets = sortBlobTargets(\n projection.targets.map((target, index) =>\n readBlobKekTarget(target, `Attachment blob KEK target[${index}]`),\n ),\n );\n const targetHash = await computeBlobContentKeyTargetHash(targets);\n if (\n targetHash !== projection.blobKeyTargetHash ||\n projection.blobId !== binding.blobId\n ) {\n throw new Error(\"Attachment blob KEK target hash is inconsistent\");\n }\n if (\n input.requireBindingMembership &&\n (!projection.activeBindingIds.includes(binding.bindingId) ||\n !targets.some(\n (target) =>\n target.bindingId === binding.bindingId &&\n target.documentId === attachmentBindingDocumentId(binding),\n ))\n ) {\n throw new Error(\"Attachment binding is absent from blob KEK targets\");\n }\n assertStringSetEquals({\n actual: projection.linkedContainerManifestHashes,\n expected: targets.map((target) => target.containerManifestHash),\n label: \"Attachment blob container manifests\",\n });\n assertStringSetEquals({\n actual: projection.linkedContainerKeyEpochIds,\n expected: targets.map((target) => target.containerKeyEpochId),\n label: \"Attachment blob container KEKs\",\n });\n const accessManifestHash = await computeBlobAccessManifestHash({\n version: 1,\n blobId: projection.blobId,\n organizationId: projection.organizationId,\n activeBindingIds: projection.activeBindingIds,\n documentManifestHashes: projection.documentManifestHashes,\n linkedContainerManifestHashes: projection.linkedContainerManifestHashes,\n linkedContainerKeyEpochIds: projection.linkedContainerKeyEpochIds,\n blobKeyTargetHash: projection.blobKeyTargetHash,\n });\n if (accessManifestHash !== projection.blobAccessManifestHash) {\n throw new Error(\"Attachment blob access manifest hash is inconsistent\");\n }\n return makeVerifiedBlobKekTargets({ ...projection, targets });\n}\n\nfunction attachmentBindingDocumentId(\n binding: DecryptDocumentAttachmentBlobInput[\"binding\"],\n): string {\n if (!binding.bindingEvent) {\n throw new Error(\"Attachment binding lacks a signed event\");\n }\n return readRecordString(\n readCanonicalRecord(\n binding.bindingEvent.body,\n \"Attachment binding event body\",\n ),\n \"documentId\",\n \"Attachment binding event body\",\n );\n}\n\nasync function assertBlobWriteHeaderVerified(input: {\n readonly authorization: DocumentWriterProjectionAuthorization | undefined;\n readonly binding: DecryptDocumentAttachmentBlobInput[\"binding\"];\n readonly encrypted: BlobEncryptedBytesHeader;\n readonly organizationId: string;\n readonly resolveProjectionUserKey: ReturnType<\n typeof requireProjectionUserKeyResolver\n >;\n}): Promise<void> {\n if (!input.authorization || !input.binding.writeHeader) {\n throw new Error(\"Attachment blob lacks verified write authority\");\n }\n const header = readWriteHeader(\n input.binding.writeHeader,\n \"Attachment blob write header\",\n );\n const writer = await input.resolveProjectionUserKey(header.writerUserId);\n if (!writer) {\n throw new Error(\"Attachment blob writer identity is unavailable\");\n }\n await verifiedBlobKekTargetsForBinding({\n binding: input.binding,\n projection: input.binding.blobKekTargets,\n requireBindingMembership: true,\n });\n const blobKekTargets = await verifiedBlobKekTargetsForBinding({\n binding: input.binding,\n projection: input.binding.writeAuthorization,\n // The signed binding proves which slot exposes the blob now. Writer\n // authorization describes the older target set committed when the bytes\n // were written, so a later valid binding need not appear in that set.\n requireBindingMembership: false,\n });\n if (\n header.metadataHash !== input.encrypted.metadataHash ||\n header.contentKeyEpoch !== input.encrypted.contentKeyEpoch ||\n header.contentRecordId !== input.encrypted.contentRecordId ||\n header.nonceDomainHash !== input.encrypted.nonceDomainHash\n ) {\n throw new Error(\"Attachment blob write header does not match ciphertext\");\n }\n const verified = await verifyWriteHeader({\n authorizationMembership: \"referenced\",\n blobAuthorization: {\n authorizingContainerPaths: resolveEventContainerPaths({\n containerPathByManifestHash:\n input.authorization.containerPathByManifestHash,\n dependencyManifestHashes: header.dependencyManifestHashes,\n }).dependencyContainerPaths,\n blobKekTargets,\n principalPolicies: input.authorization.principalPolicies,\n },\n expectedAccessManifestHash: blobKekTargets.blobAccessManifestHash,\n expectedObject: {\n objectKind: \"blob\",\n objectId: input.binding.blobId,\n organizationId: input.organizationId,\n },\n expectedTargetHash: blobKekTargets.blobKeyTargetHash,\n header,\n writerPublicKey: writer.signingPublicKey,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n}\n"]}
@@ -1,8 +1,8 @@
1
1
  import { signBlobAttachmentDetachEvent } from "../../data/documents/blob/shared/events.js";
2
2
  import { assertBlobAttachmentDetachResponse } from "../../data/documents/blob/shared/responses.js";
3
3
  import { authorizingContainerPathRefs } from "../../data/documents/shared/projection.js";
4
- import { readCanonicalRecord } from "../../data/keyingCanonicalJson.js";
5
- import { requireProjectionUserKeyResolver } from "../../data/keyingProjectionVerification.js";
4
+ import { readCanonicalRecord } from "../../data/keying/canonicalJson.js";
5
+ import { requireProjectionUserKeyResolver } from "../../data/keyingProjectionVerification/index.js";
6
6
  import { assertProjectionVerificationCurrent } from "../../data/keyingProjectionVerification/types.js";
7
7
  import { resolveBlobMutationWriterProjection } from "./writerProjection.js";
8
8
  export async function detachDocumentAttachment({ apiClient, author, bindingId, blobId, documentId, eventId = crypto.randomUUID(), execSql, isRemoteSyncBlocked, resolveProjectionUserKey, signedAt = new Date().toISOString(), slotId, stillCurrent, warmReferencedPrincipalPolicies, writerProjection, }) {
@@ -1 +1 @@
1
- {"version":3,"file":"detach.js","sourceRoot":"","sources":["detach.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,6BAA6B,EAAE,MAAM,yCAAyC,CAAC;AACxF,OAAO,EAAE,kCAAkC,EAAE,MAAM,4CAA4C,CAAC;AAKhG,OAAO,EAAE,4BAA4B,EAAE,MAAM,wCAAwC,CAAC;AACtF,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAE,gCAAgC,EAAE,MAAM,yCAAyC,CAAC;AAC3F,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,mCAAmC,EAAE,MAAM,oBAAoB,CAAC;AAEzE,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAAC,EAC7C,SAAS,EACT,MAAM,EACN,SAAS,EACT,MAAM,EACN,UAAU,EACV,OAAO,GAAG,MAAM,CAAC,UAAU,EAAE,EAC7B,OAAO,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,CAAC;IACD,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAElD,kCAAkC,CAAC;QACjC,SAAS;QACT,MAAM;QACN,UAAU;QACV,QAAQ;QACR,MAAM;KACP,CAAC,CAAC;IAEH,OAAO;QACL,OAAO;QACP,QAAQ;QACR,gBAAgB,EAAE,wBAAwB;KAC3C,CAAC;AACJ,CAAC","sourcesContent":["import type { BlobAttachmentDetachRequest } from \"@tearleads/validators/request\";\nimport { signBlobAttachmentDetachEvent } from \"../../data/documents/blob/shared/events\";\nimport { assertBlobAttachmentDetachResponse } from \"../../data/documents/blob/shared/responses\";\nimport type {\n DetachDocumentAttachmentInput,\n DetachDocumentAttachmentResult,\n} from \"../../data/documents/blob/shared/types\";\nimport { authorizingContainerPathRefs } from \"../../data/documents/shared/projection\";\nimport { readCanonicalRecord } from \"../../data/keyingCanonicalJson\";\nimport { requireProjectionUserKeyResolver } from \"../../data/keyingProjectionVerification\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { resolveBlobMutationWriterProjection } from \"./writerProjection\";\n\nexport async function detachDocumentAttachment({\n apiClient,\n author,\n bindingId,\n blobId,\n documentId,\n eventId = crypto.randomUUID(),\n execSql,\n isRemoteSyncBlocked,\n resolveProjectionUserKey,\n signedAt = new Date().toISOString(),\n slotId,\n stillCurrent,\n warmReferencedPrincipalPolicies,\n writerProjection,\n}: DetachDocumentAttachmentInput): Promise<DetachDocumentAttachmentResult | null> {\n const resolved = await resolveBlobMutationWriterProjection({\n apiClient,\n documentId,\n errorLabel: \"Blob attachment detach\",\n execSql,\n isRemoteSyncBlocked,\n stillCurrent,\n warmReferencedPrincipalPolicies,\n resolveProjectionUserKey: requireProjectionUserKeyResolver(\n resolveProjectionUserKey,\n \"Document attachment detach\",\n ),\n writerProjection,\n });\n if (!resolved) {\n return null;\n }\n const { manifestIdentity, writerProjection: resolvedWriterProjection } =\n resolved;\n\n const pathRefs = authorizingContainerPathRefs(resolvedWriterProjection);\n const { body, event } = await signBlobAttachmentDetachEvent({\n author,\n bindingId,\n blobId,\n documentId,\n eventId,\n manifestIdentity,\n signedAt,\n slotId,\n authorizingContainerPathRefs: pathRefs,\n });\n const request: BlobAttachmentDetachRequest = {\n event: readCanonicalRecord(event, \"Blob attachment detach event\"),\n body: readCanonicalRecord(body, \"Blob attachment detach body\"),\n authorizingContainerPathRefs: pathRefs,\n };\n assertProjectionVerificationCurrent(stillCurrent);\n const response = await apiClient.detachBlobAttachment(\n blobId,\n bindingId,\n request,\n {\n expectedPaymentRequiredOrganizationId: manifestIdentity.organizationId,\n },\n );\n if (!response) {\n return null;\n }\n assertProjectionVerificationCurrent(stillCurrent);\n\n assertBlobAttachmentDetachResponse({\n bindingId,\n blobId,\n documentId,\n response,\n slotId,\n });\n\n return {\n request,\n response,\n writerProjection: resolvedWriterProjection,\n };\n}\n"]}
1
+ {"version":3,"file":"detach.js","sourceRoot":"","sources":["detach.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,6BAA6B,EAAE,MAAM,yCAAyC,CAAC;AACxF,OAAO,EAAE,kCAAkC,EAAE,MAAM,4CAA4C,CAAC;AAKhG,OAAO,EAAE,4BAA4B,EAAE,MAAM,wCAAwC,CAAC;AACtF,OAAO,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AACtE,OAAO,EAAE,gCAAgC,EAAE,MAAM,yCAAyC,CAAC;AAC3F,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,mCAAmC,EAAE,MAAM,oBAAoB,CAAC;AAEzE,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAAC,EAC7C,SAAS,EACT,MAAM,EACN,SAAS,EACT,MAAM,EACN,UAAU,EACV,OAAO,GAAG,MAAM,CAAC,UAAU,EAAE,EAC7B,OAAO,EACP,mBAAmB,EACnB,wBAAwB,EACxB,QAAQ,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,EACnC,MAAM,EACN,YAAY,EACZ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;QACR,MAAM;KACP,CAAC,CAAC;IAEH,OAAO;QACL,OAAO;QACP,QAAQ;QACR,gBAAgB,EAAE,wBAAwB;KAC3C,CAAC;AACJ,CAAC","sourcesContent":["import type { BlobAttachmentDetachRequest } from \"@tearleads/validators/request\";\nimport { signBlobAttachmentDetachEvent } from \"../../data/documents/blob/shared/events\";\nimport { assertBlobAttachmentDetachResponse } from \"../../data/documents/blob/shared/responses\";\nimport type {\n DetachDocumentAttachmentInput,\n DetachDocumentAttachmentResult,\n} from \"../../data/documents/blob/shared/types\";\nimport { authorizingContainerPathRefs } from \"../../data/documents/shared/projection\";\nimport { readCanonicalRecord } from \"../../data/keying/canonicalJson\";\nimport { requireProjectionUserKeyResolver } from \"../../data/keyingProjectionVerification\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { resolveBlobMutationWriterProjection } from \"./writerProjection\";\n\nexport async function detachDocumentAttachment({\n apiClient,\n author,\n bindingId,\n blobId,\n documentId,\n eventId = crypto.randomUUID(),\n execSql,\n isRemoteSyncBlocked,\n resolveProjectionUserKey,\n signedAt = new Date().toISOString(),\n slotId,\n stillCurrent,\n warmReferencedPrincipalPolicies,\n writerProjection,\n}: DetachDocumentAttachmentInput): Promise<DetachDocumentAttachmentResult | null> {\n const resolved = await resolveBlobMutationWriterProjection({\n apiClient,\n documentId,\n errorLabel: \"Blob attachment detach\",\n execSql,\n isRemoteSyncBlocked,\n stillCurrent,\n warmReferencedPrincipalPolicies,\n resolveProjectionUserKey: requireProjectionUserKeyResolver(\n resolveProjectionUserKey,\n \"Document attachment detach\",\n ),\n writerProjection,\n });\n if (!resolved) {\n return null;\n }\n const { manifestIdentity, writerProjection: resolvedWriterProjection } =\n resolved;\n\n const pathRefs = authorizingContainerPathRefs(resolvedWriterProjection);\n const { body, event } = await signBlobAttachmentDetachEvent({\n author,\n bindingId,\n blobId,\n documentId,\n eventId,\n manifestIdentity,\n signedAt,\n slotId,\n authorizingContainerPathRefs: pathRefs,\n });\n const request: BlobAttachmentDetachRequest = {\n event: readCanonicalRecord(event, \"Blob attachment detach event\"),\n body: readCanonicalRecord(body, \"Blob attachment detach body\"),\n authorizingContainerPathRefs: pathRefs,\n };\n assertProjectionVerificationCurrent(stillCurrent);\n const response = await apiClient.detachBlobAttachment(\n blobId,\n bindingId,\n request,\n {\n expectedPaymentRequiredOrganizationId: manifestIdentity.organizationId,\n },\n );\n if (!response) {\n return null;\n }\n assertProjectionVerificationCurrent(stillCurrent);\n\n assertBlobAttachmentDetachResponse({\n bindingId,\n blobId,\n documentId,\n response,\n slotId,\n });\n\n return {\n request,\n response,\n writerProjection: resolvedWriterProjection,\n };\n}\n"]}
@@ -1,9 +1,9 @@
1
1
  import type { BlobBytesResponse, RequestResultOptions } from "../../internal/api-client/index.js";
2
2
  import type { BlobAttachmentSummary, DocumentWriterProjectionResponse, ListDocumentAttachmentsResponse } from "../../internal/validators/response/index.js";
3
- import type { BlobBytes } from "../../data/blobContracts.js";
3
+ import type { BlobBytes } from "../../data/blobs/blobContracts.js";
4
4
  import type { DocumentAttachment } from "../../data/documents/documentContent.js";
5
- import type { ProjectionUserKeyResolver, ReferencedPrincipalPolicyWarmer } from "../../data/keyingProjectionVerification.js";
6
- import type { SecurityIncidentReporter } from "../../data/securityIncidents.js";
5
+ import type { ProjectionUserKeyResolver, ReferencedPrincipalPolicyWarmer } from "../../data/keyingProjectionVerification/index.js";
6
+ import type { SecurityIncidentReporter } from "../../data/shared/securityIncidents.js";
7
7
  import type { ExecSql } from "../../data/sqlite/sqlSchema.js";
8
8
  interface DocumentAttachmentHydrationApi {
9
9
  evictDocumentWriterProjection?(documentId: string): void;
@@ -1,7 +1,7 @@
1
1
  import { bytesToHex } from "../../internal/crypto/index.js";
2
2
  import { runBlobTransfer } from "../../data/blobs/transferPool.js";
3
3
  import { attachmentContentSha256 } from "../../data/documents/attachmentContentIdentity.js";
4
- import { errorMessage } from "../../data/errorMessage.js";
4
+ import { errorMessage } from "../../data/shared/errorMessage.js";
5
5
  import { createAttachmentDecryptor } from "./attachmentDecryptor.js";
6
6
  import { collectHydrationResults } from "./hydrationResults.js";
7
7
  import { readAttachmentTransfer } from "./readAttachmentTransfer.js";
@@ -1 +1 @@
1
- {"version":3,"file":"hydrate.js","sourceRoot":"","sources":["hydrate.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAO/C,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAChE,OAAO,EAAE,uBAAuB,EAAE,MAAM,gDAAgD,CAAC;AAEzF,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAOvD,OAAO,EAAE,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AAClE,OAAO,EAAE,uBAAuB,EAAE,MAAM,oBAAoB,CAAC;AAC7D,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAyDlE,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;IACxE,yEAAyE;IACzE,IAAI,CAAC,e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,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 {\n BlobBytesResponse,\n RequestResultOptions,\n} from \"@tearleads/api-client\";\nimport { bytesToHex } from \"@tearleads/crypto\";\nimport type {\n BlobAttachmentSummary,\n DocumentWriterProjectionResponse,\n ListDocumentAttachmentsResponse,\n} from \"@tearleads/validators/response\";\nimport type { BlobBytes } from \"../../data/blobContracts\";\nimport { runBlobTransfer } from \"../../data/blobs/transferPool\";\nimport { attachmentContentSha256 } from \"../../data/documents/attachmentContentIdentity\";\nimport type { DocumentAttachment } from \"../../data/documents/documentContent\";\nimport { errorMessage } from \"../../data/errorMessage\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../data/keyingProjectionVerification\";\nimport type { SecurityIncidentReporter } from \"../../data/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { createAttachmentDecryptor } from \"./attachmentDecryptor\";\nimport { collectHydrationResults } from \"./hydrationResults\";\nimport { readAttachmentTransfer } from \"./readAttachmentTransfer\";\n\ninterface 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\ninterface 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\ninterface DocumentAttachmentHydrationContext {\n apiClient: DocumentAttachmentHydrationApi;\n documentId: string;\n execSql: ExecSql;\n localBlobIdBySlotId?:\n | Readonly<Record<string, string | null | undefined>>\n | undefined;\n localStorageKeyBySlotId?: Readonly<Record<string, string | undefined>>;\n log?: ((message: string) => void) | undefined;\n logPrefix?: string | 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 reportSecurityIncident?: SecurityIncidentReporter | undefined;\n targetSecretKey: Uint8Array;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\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 const logPrefix = input.logPrefix ?? \"Documents\";\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 `${logPrefix}: 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 `${logPrefix}: blob ${binding.blobId} byte length mismatch during hydration.`,\n );\n return null;\n }\n\n if (!(await hasExpectedBlobSha256(blob, encryptedBytes))) {\n log?.(\n `${logPrefix}: 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 const logPrefix = input.logPrefix ?? \"Documents\";\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 `${logPrefix}: 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 `${logPrefix}: 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 input: DocumentAttachmentHydrationContext & {\n attachments: ReadonlyArray<DocumentAttachment>;\n /** No binding target remains unchecked or unavailable in this pass. */\n onBindingsChecked?: () => void;\n },\n): Promise<HydratedDocumentAttachmentBlob[] | null> {\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 const logPrefix = input.logPrefix ?? \"Documents\";\n input.log?.(\n `${logPrefix}: 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":"AAIA,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAO/C,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAChE,OAAO,EAAE,uBAAuB,EAAE,MAAM,gDAAgD,CAAC;AAMzF,OAAO,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAG9D,OAA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K,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 {\n BlobBytesResponse,\n RequestResultOptions,\n} from \"@tearleads/api-client\";\nimport { bytesToHex } from \"@tearleads/crypto\";\nimport type {\n BlobAttachmentSummary,\n DocumentWriterProjectionResponse,\n ListDocumentAttachmentsResponse,\n} from \"@tearleads/validators/response\";\nimport type { BlobBytes } from \"../../data/blobs/blobContracts\";\nimport { runBlobTransfer } from \"../../data/blobs/transferPool\";\nimport { attachmentContentSha256 } from \"../../data/documents/attachmentContentIdentity\";\nimport type { DocumentAttachment } from \"../../data/documents/documentContent\";\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 \"./attachmentDecryptor\";\nimport { collectHydrationResults } from \"./hydrationResults\";\nimport { readAttachmentTransfer } from \"./readAttachmentTransfer\";\n\ninterface 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\ninterface 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\ninterface DocumentAttachmentHydrationContext {\n apiClient: DocumentAttachmentHydrationApi;\n documentId: string;\n execSql: ExecSql;\n localBlobIdBySlotId?:\n | Readonly<Record<string, string | null | undefined>>\n | undefined;\n localStorageKeyBySlotId?: Readonly<Record<string, string | undefined>>;\n log?: ((message: string) => void) | undefined;\n logPrefix?: string | 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 reportSecurityIncident?: SecurityIncidentReporter | undefined;\n targetSecretKey: Uint8Array;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\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 const logPrefix = input.logPrefix ?? \"Documents\";\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 `${logPrefix}: 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 `${logPrefix}: blob ${binding.blobId} byte length mismatch during hydration.`,\n );\n return null;\n }\n\n if (!(await hasExpectedBlobSha256(blob, encryptedBytes))) {\n log?.(\n `${logPrefix}: 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 const logPrefix = input.logPrefix ?? \"Documents\";\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 `${logPrefix}: 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 `${logPrefix}: 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 input: DocumentAttachmentHydrationContext & {\n attachments: ReadonlyArray<DocumentAttachment>;\n /** No binding target remains unchecked or unavailable in this pass. */\n onBindingsChecked?: () => void;\n },\n): Promise<HydratedDocumentAttachmentBlob[] | null> {\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 const logPrefix = input.logPrefix ?? \"Documents\";\n input.log?.(\n `${logPrefix}: 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 +1 @@
1
- {"version":3,"file":"hydrationResults.js","sourceRoot":"","sources":["hydrationResults.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yCAAyC,EACzC,+BAA+B,GAChC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,sCAAsC,EAAE,MAAM,+CAA+C,CAAC;AAGvG,qFAAqF;AACrF,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAAI,KAIhD;IACC,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,UAAU,CACvC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CACtC,CAAC;IACF,MAAM,MAAM,GAAQ,EAAE,CAAC;IACvB,KAAK,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,IAAI,QAAQ,CAAC,OAAO,EAAE,EAAE,CAAC;QAClD,IAAI,OAAO,CAAC,MAAM,KAAK,WAAW,EAAE,CAAC;YACnC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YAC3B,SAAS;QACX,CAAC;QACD,+BAA+B,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QAChD,sCAAsC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QACvD,MAAM,yCAAyC,CAC7C,OAAO,CAAC,MAAM,EACd,KAAK,CAAC,sBAAsB,EAC5B;YACE,SAAS,EAAE,oBAAoB;YAC/B,UAAU,EAAE,MAAM;YAClB,QAAQ,EAAE,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE,MAAM,IAAI,IAAI;SAC7C,CACF,CAAC;QACF,KAAK,CAAC,GAAG,EAAE,CAAC,2DAA2D,CAAC,CAAC;IAC3E,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import {\n reportKeyingVerificationErrorInCauseChain,\n rethrowDatabaseUnavailableError,\n} from \"../../data/keyingProjectionVerification/error\";\nimport { rethrowProjectionVerificationCancelled } from \"../../data/keyingProjectionVerification/types\";\nimport type { SecurityIncidentReporter } from \"../../data/securityIncidents\";\n\n/** One unavailable or invalid attachment does not suppress independent successes. */\nexport async function collectHydrationResults<T>(input: {\n tasks: readonly { blobId: string; run: () => Promise<T> }[];\n reportSecurityIncident?: SecurityIncidentReporter | undefined;\n log?: ((message: string) => void) | undefined;\n}): Promise<T[]> {\n const outcomes = await Promise.allSettled(\n input.tasks.map((task) => task.run()),\n );\n const values: T[] = [];\n for (const [index, outcome] of outcomes.entries()) {\n if (outcome.status === \"fulfilled\") {\n values.push(outcome.value);\n continue;\n }\n rethrowDatabaseUnavailableError(outcome.reason);\n rethrowProjectionVerificationCancelled(outcome.reason);\n await reportKeyingVerificationErrorInCauseChain(\n outcome.reason,\n input.reportSecurityIncident,\n {\n operation: \"hydrate_attachment\",\n objectKind: \"blob\",\n objectId: input.tasks[index]?.blobId ?? null,\n },\n );\n input.log?.(\"Documents: an attachment is unavailable during hydration.\");\n }\n return values;\n}\n"]}
1
+ {"version":3,"file":"hydrationResults.js","sourceRoot":"","sources":["hydrationResults.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yCAAyC,EACzC,+BAA+B,GAChC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,sCAAsC,EAAE,MAAM,+CAA+C,CAAC;AAGvG,qFAAqF;AACrF,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAAI,KAIhD;IACC,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,UAAU,CACvC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CACtC,CAAC;IACF,MAAM,MAAM,GAAQ,EAAE,CAAC;IACvB,KAAK,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,IAAI,QAAQ,CAAC,OAAO,EAAE,EAAE,CAAC;QAClD,IAAI,OAAO,CAAC,MAAM,KAAK,WAAW,EAAE,CAAC;YACnC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YAC3B,SAAS;QACX,CAAC;QACD,+BAA+B,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QAChD,sCAAsC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QACvD,MAAM,yCAAyC,CAC7C,OAAO,CAAC,MAAM,EACd,KAAK,CAAC,sBAAsB,EAC5B;YACE,SAAS,EAAE,oBAAoB;YAC/B,UAAU,EAAE,MAAM;YAClB,QAAQ,EAAE,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE,MAAM,IAAI,IAAI;SAC7C,CACF,CAAC;QACF,KAAK,CAAC,GAAG,EAAE,CAAC,2DAA2D,CAAC,CAAC;IAC3E,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import {\n reportKeyingVerificationErrorInCauseChain,\n rethrowDatabaseUnavailableError,\n} from \"../../data/keyingProjectionVerification/error\";\nimport { rethrowProjectionVerificationCancelled } from \"../../data/keyingProjectionVerification/types\";\nimport type { SecurityIncidentReporter } from \"../../data/shared/securityIncidents\";\n\n/** One unavailable or invalid attachment does not suppress independent successes. */\nexport async function collectHydrationResults<T>(input: {\n tasks: readonly { blobId: string; run: () => Promise<T> }[];\n reportSecurityIncident?: SecurityIncidentReporter | undefined;\n log?: ((message: string) => void) | undefined;\n}): Promise<T[]> {\n const outcomes = await Promise.allSettled(\n input.tasks.map((task) => task.run()),\n );\n const values: T[] = [];\n for (const [index, outcome] of outcomes.entries()) {\n if (outcome.status === \"fulfilled\") {\n values.push(outcome.value);\n continue;\n }\n rethrowDatabaseUnavailableError(outcome.reason);\n rethrowProjectionVerificationCancelled(outcome.reason);\n await reportKeyingVerificationErrorInCauseChain(\n outcome.reason,\n input.reportSecurityIncident,\n {\n operation: \"hydrate_attachment\",\n objectKind: \"blob\",\n objectId: input.tasks[index]?.blobId ?? null,\n },\n );\n input.log?.(\"Documents: an attachment is unavailable during hydration.\");\n }\n return values;\n}\n"]}
@@ -1,5 +1,5 @@
1
- export type { BlobByteSource, BlobByteSourceInput, BlobBytes, BlobStore, } from "../../data/blobContracts.js";
2
- export { blobByteSourceInputLength, createBlobByteSource, readBlobByteSource, } from "../../data/blobContracts.js";
1
+ export type { BlobByteSource, BlobByteSourceInput, BlobBytes, BlobStore, } from "../../data/blobs/blobContracts.js";
2
+ export { blobByteSourceInputLength, createBlobByteSource, readBlobByteSource, } from "../../data/blobs/blobContracts.js";
3
3
  export { createBlobStore } from "../../data/blobs/createBlobStore.js";
4
4
  export type { EncryptedBlobStoreCipher, EncryptedBlobStoreKey, EncryptedBlobStoreOptions, WrapEncryptedBlobStoreOptions, } from "../../data/blobs/encryptedBlobStore.js";
5
5
  export { createEncryptedBlobStore, createLazyEncryptedBlobStore, wrapEncryptedBlobStore, } from "../../data/blobs/encryptedBlobStore.js";
@@ -1,4 +1,4 @@
1
- export { blobByteSourceInputLength, createBlobByteSource, readBlobByteSource, } from "../../data/blobContracts.js";
1
+ export { blobByteSourceInputLength, createBlobByteSource, readBlobByteSource, } from "../../data/blobs/blobContracts.js";
2
2
  export { createBlobStore } from "../../data/blobs/createBlobStore.js";
3
3
  export { createEncryptedBlobStore, createLazyEncryptedBlobStore, wrapEncryptedBlobStore, } from "../../data/blobs/encryptedBlobStore.js";
4
4
  export { createMemoryBlobStore } from "../../data/blobs/memoryBlobStore.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,yBAAyB,EACzB,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAOnE,OAAO,EACL,wBAAwB,EACxB,4BAA4B,EAC5B,sBAAsB,GACvB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AACzE,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AAMpE,OAAO,EAAE,6BAA6B,EAAE,MAAM,WAAW,CAAC;AAC1D,OAAO,EAAE,8BAA8B,EAAE,MAAM,WAAW,CAAC;AAC3D,OAAO,EAAE,wBAAwB,EAAE,MAAM,UAAU,CAAC","sourcesContent":["export type {\n BlobByteSource,\n BlobByteSourceInput,\n BlobBytes,\n BlobStore,\n} from \"../../data/blobContracts\";\nexport {\n blobByteSourceInputLength,\n createBlobByteSource,\n readBlobByteSource,\n} from \"../../data/blobContracts\";\nexport { createBlobStore } from \"../../data/blobs/createBlobStore\";\nexport type {\n EncryptedBlobStoreCipher,\n EncryptedBlobStoreKey,\n EncryptedBlobStoreOptions,\n WrapEncryptedBlobStoreOptions,\n} from \"../../data/blobs/encryptedBlobStore\";\nexport {\n createEncryptedBlobStore,\n createLazyEncryptedBlobStore,\n wrapEncryptedBlobStore,\n} from \"../../data/blobs/encryptedBlobStore\";\nexport { createMemoryBlobStore } from \"../../data/blobs/memoryBlobStore\";\nexport { purgeOpfsBlobStore } from \"../../data/blobs/opfsBlobStore\";\nexport type {\n MultipartStageResolvedListener,\n MultipartUploadProgress,\n MultipartUploadProgressListener,\n} from \"../../data/documents/blob/shared/types\";\nexport { decryptDocumentAttachmentBlob } from \"./decrypt\";\nexport { hydrateDocumentAttachmentBlobs } from \"./hydrate\";\nexport { uploadDocumentAttachment } from \"./upload\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,yBAAyB,EACzB,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAOnE,OAAO,EACL,wBAAwB,EACxB,4BAA4B,EAC5B,sBAAsB,GACvB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AACzE,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AAMpE,OAAO,EAAE,6BAA6B,EAAE,MAAM,WAAW,CAAC;AAC1D,OAAO,EAAE,8BAA8B,EAAE,MAAM,WAAW,CAAC;AAC3D,OAAO,EAAE,wBAAwB,EAAE,MAAM,UAAU,CAAC","sourcesContent":["export type {\n BlobByteSource,\n BlobByteSourceInput,\n BlobBytes,\n BlobStore,\n} from \"../../data/blobs/blobContracts\";\nexport {\n blobByteSourceInputLength,\n createBlobByteSource,\n readBlobByteSource,\n} from \"../../data/blobs/blobContracts\";\nexport { createBlobStore } from \"../../data/blobs/createBlobStore\";\nexport type {\n EncryptedBlobStoreCipher,\n EncryptedBlobStoreKey,\n EncryptedBlobStoreOptions,\n WrapEncryptedBlobStoreOptions,\n} from \"../../data/blobs/encryptedBlobStore\";\nexport {\n createEncryptedBlobStore,\n createLazyEncryptedBlobStore,\n wrapEncryptedBlobStore,\n} from \"../../data/blobs/encryptedBlobStore\";\nexport { createMemoryBlobStore } from \"../../data/blobs/memoryBlobStore\";\nexport { purgeOpfsBlobStore } from \"../../data/blobs/opfsBlobStore\";\nexport type {\n MultipartStageResolvedListener,\n MultipartUploadProgress,\n MultipartUploadProgressListener,\n} from \"../../data/documents/blob/shared/types\";\nexport { decryptDocumentAttachmentBlob } from \"./decrypt\";\nexport { hydrateDocumentAttachmentBlobs } from \"./hydrate\";\nexport { uploadDocumentAttachment } from \"./upload\";\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"multipartFirstParts.js","sourceRoot":"","sources":["multipartFirstParts.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AAClE,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAE/C,OAAO,EACL,yBAAyB,GAG1B,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EACL,yBAAyB,EAEzB,4BAA4B,GAC7B,MAAM,+BAA+B,CAAC;AA2BvC,+DAA+D;AAC/D,MAAM,UAAU,oBAAoB,CAClC,QAAwC;IAExC,KAAK,MAAM,IAAI,IAAI,QAAQ,CAAC,MAAM,EAAE,EAAE,CAAC;QACrC,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;IACD,QAAQ,CAAC,KAAK,EAAE,CAAC;AACnB,CAAC;AAED;;;;GAIG;AACH,KAAK,UAAU,uBAAuB,CACpC,MAAc,EACd,KAAa;IAEb,MAAM,OAAO,GAAG,CAAC,MAAM,yBAAyB,CAAC,MAAM,CAAC,CAAC,CAAC;IAC1D,OAAO,OAAO,CAAC,MAAM,GAAG,KAAK,EAAE,CAAC;QAC9B,MAAM,MAAM,GAAG,4BAA4B,CAAC,MAAM,CAAC,CAAC;QACpD,IAAI,CAAC,MAAM;YAAE,MAAM;QACnB,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACvB,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAYD,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,KAAgB;IACnD,OAAO,UAAU,CACf,IAAI,UAAU,CAAC,MAAM,MAAM,CAAC,MAAM,C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M,GAAG,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IAC9C,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;IAClC,OAAO,MAAM,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;AACxE,CAAC","sourcesContent":["import { describeMultipartBlobPart } from \"@tearleads/api-client\";\nimport { bytesToHex } from \"@tearleads/crypto\";\nimport type { InitiateMultipartBlobStageResponse } from \"@tearleads/validators/response\";\nimport {\n MAX_INITIATE_PART_UPLOADS,\n type MultipartBlobPartDescriptor,\n type MultipartBlobPartUploadSource,\n} from \"@tearleads/validators/util\";\nimport type { BlobBytes } from \"../../data/blobContracts\";\nimport {\n acquireBlobTransferPermit,\n type BlobTransferPermit,\n tryAcquireBlobTransferPermit,\n} from \"../../data/blobs/transferPool\";\nimport type { BlobEncryptionPlan } from \"../../data/documents/blob/shared/crypto\";\n\nexport interface PreparedMultipartPart {\n readonly bytes: BlobBytes;\n readonly sha256: string;\n}\n\n/**\n * A first part's bytes and the transfer-pool permit that pays for them: the\n * bytes exist before their upload can start, so they hold a slot of the\n * client's byte-I/O bound until the upload that sends them releases it.\n */\nexport interface PreparedFirstPart extends PreparedMultipartPart {\n readonly permit: BlobTransferPermit;\n}\n\n/**\n * The parts a new stage's upload starts with, encrypted once up front: their\n * descriptors ride on the stage initiation, and their bytes are handed to the\n * upload workers instead of being encrypted a second time.\n */\nexport interface MultipartFirstParts {\n readonly descriptors: readonly MultipartBlobPartDescriptor[];\n readonly prepared: Map<number, PreparedFirstPart>;\n}\n\n/** Return the pool slots of first parts no upload consumed. */\nexport function releasePreparedParts(\n prepared: Map<number, PreparedFirstPart>,\n): void {\n for (const part of prepared.values()) {\n part.permit.release();\n }\n prepared.clear();\n}\n\n/**\n * One permit is awaited; more are taken only if free right now. Two uploads\n * each waiting for a second slot while holding a first could otherwise\n * deadlock the pool, since a held slot frees only when its part uploads.\n */\nasync function acquireFirstPartPermits(\n client: object,\n limit: number,\n): Promise<BlobTransferPermit[]> {\n const permits = [await acquireBlobTransferPermit(client)];\n while (permits.length < limit) {\n const permit = tryAcquireBlobTransferPermit(client);\n if (!permit) break;\n permits.push(permit);\n }\n return permits;\n}\n\n/**\n * Where each part's bytes go. Sources the stage initiation issued are used\n * once; a store that cannot sign (`api`) needs no per-part authorization at\n * all, and a part with no source authorizes just before it is sent.\n */\nexport interface MultipartPartSources {\n readonly apiTransport: boolean;\n readonly issued: Map<number, MultipartBlobPartUploadSource>;\n}\n\nexport async function sha256BytesHex(bytes: BlobBytes): Promise<string> {\n return bytesToHex(\n new Uint8Array(await crypto.subtle.digest(\"SHA-256\", bytes)),\n );\n}\n\nexport async function prepareFirstMultipartParts(\n client: object,\n encryption: BlobEncryptionPlan,\n concurrency: number,\n): Promise<MultipartFirstParts> {\n const permits = await acquireFirstPartPermits(\n client,\n Math.min(encryption.partCount, concurrency, MAX_INITIATE_PART_UPLOADS),\n );\n const descriptors: MultipartBlobPartDescriptor[] = [];\n const prepared = new Map<number, PreparedFirstPart>();\n try {\n for (const [partIndex, permit] of permits.entries()) {\n const bytes = await encryption.encryptPart(partIndex);\n if (bytes.byteLength !== encryption.getPartByteLength(partIndex)) {\n throw new Error(\n `Encrypted blob part ${partIndex + 1} byte length mismatch: expected ${encryption.getPartByteLength(partIndex).toLocaleString()}, received ${bytes.byteLength.toLocaleString()}.`,\n );\n }\n const sha256 = await sha256BytesHex(bytes);\n prepared.set(partIndex, { bytes, permit, sha256 });\n descriptors.push(describeMultipartBlobPart(partIndex + 1, bytes));\n }\n } catch (error) {\n for (const permit of permits) permit.release();\n throw error;\n }\n return { descriptors, prepared };\n}\n\n/**\n * The initiation must return exactly one source per described part, for that\n * part's number, length, and checksum, and every source of one stage must use\n * the same transport.\n */\nexport function readIssuedPartSources(\n descriptors: readonly MultipartBlobPartDescriptor[],\n stage: Pick<InitiateMultipartBlobStageResponse, \"partUploads\">,\n): MultipartPartSources {\n const issued = new Map<number, MultipartBlobPartUploadSource>();\n const kinds = new Set(stage.partUploads.map((upload) => upload.source.kind));\n const matches =\n stage.partUploads.length === descriptors.length &&\n kinds.size === 1 &&\n descriptors.every((descriptor, index) => {\n const upload = stage.partUploads[index];\n return (\n upload?.partNumber === descriptor.partNumber &&\n upload.byteLength === descriptor.byteLength &&\n upload.contentMd5 === descriptor.contentMd5\n );\n });\n if (!matches) {\n throw new Error(\n \"Multipart blob stage initiation part uploads do not match its request.\",\n );\n }\n for (const upload of stage.partUploads) {\n issued.set(upload.partNumber, upload.source);\n }\n return { apiTransport: kinds.has(\"api\"), issued };\n}\n\n/** Use each issued source once; retries and later parts authorize anew. */\nexport function takePartSource(\n sources: MultipartPartSources,\n partNumber: number,\n): MultipartBlobPartUploadSource | undefined {\n const issued = sources.issued.get(partNumber);\n sources.issued.delete(partNumber);\n return issued ?? (sources.apiTransport ? { kind: \"api\" } : undefined);\n}\n"]}
1
+ {"version":3,"file":"multipartFirstParts.js","sourceRoot":"","sources":["multipartFirstParts.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AAClE,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAE/C,OAAO,EACL,yBAAyB,GAG1B,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EACL,yBAAyB,EAEzB,4BAA4B,GAC7B,MAAM,+BAA+B,CAAC;AA2BvC,+DAA+D;AAC/D,MAAM,UAAU,oBAAoB,CAClC,QAAwC;IAExC,KAAK,MAAM,IAAI,IAAI,QAAQ,CAAC,MAAM,EAAE,EAAE,CAAC;QACrC,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;IACD,QAAQ,CAAC,KAAK,EAAE,CAAC;AACnB,CAAC;AAED;;;;GAIG;AACH,KAAK,UAAU,uBAAuB,CACpC,MAAc,EACd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CAAC;IACL,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CACb,wEAAwE,CACzE,CAAC;IACJ,CAAC;IACD,KAAK,MAAM,MAAM,IAAI,KAAK,CAAC,WAAW,EAAE,CAAC;QACvC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,UAAU,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;IAC/C,CAAC;IACD,OAAO,EAAE,YAAY,EAAE,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;AACpD,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,cAAc,CAC5B,OAA6B,EAC7B,UAAkB;IAElB,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IAC9C,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;IAClC,OAAO,MAAM,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;AACxE,CAAC","sourcesContent":["import { describeMultipartBlobPart } from \"@tearleads/api-client\";\nimport { bytesToHex } from \"@tearleads/crypto\";\nimport type { InitiateMultipartBlobStageResponse } from \"@tearleads/validators/response\";\nimport {\n MAX_INITIATE_PART_UPLOADS,\n type MultipartBlobPartDescriptor,\n type MultipartBlobPartUploadSource,\n} from \"@tearleads/validators/util\";\nimport type { BlobBytes } from \"../../data/blobs/blobContracts\";\nimport {\n acquireBlobTransferPermit,\n type BlobTransferPermit,\n tryAcquireBlobTransferPermit,\n} from \"../../data/blobs/transferPool\";\nimport type { BlobEncryptionPlan } from \"../../data/documents/blob/shared/crypto\";\n\nexport interface PreparedMultipartPart {\n readonly bytes: BlobBytes;\n readonly sha256: string;\n}\n\n/**\n * A first part's bytes and the transfer-pool permit that pays for them: the\n * bytes exist before their upload can start, so they hold a slot of the\n * client's byte-I/O bound until the upload that sends them releases it.\n */\nexport interface PreparedFirstPart extends PreparedMultipartPart {\n readonly permit: BlobTransferPermit;\n}\n\n/**\n * The parts a new stage's upload starts with, encrypted once up front: their\n * descriptors ride on the stage initiation, and their bytes are handed to the\n * upload workers instead of being encrypted a second time.\n */\nexport interface MultipartFirstParts {\n readonly descriptors: readonly MultipartBlobPartDescriptor[];\n readonly prepared: Map<number, PreparedFirstPart>;\n}\n\n/** Return the pool slots of first parts no upload consumed. */\nexport function releasePreparedParts(\n prepared: Map<number, PreparedFirstPart>,\n): void {\n for (const part of prepared.values()) {\n part.permit.release();\n }\n prepared.clear();\n}\n\n/**\n * One permit is awaited; more are taken only if free right now. Two uploads\n * each waiting for a second slot while holding a first could otherwise\n * deadlock the pool, since a held slot frees only when its part uploads.\n */\nasync function acquireFirstPartPermits(\n client: object,\n limit: number,\n): Promise<BlobTransferPermit[]> {\n const permits = [await acquireBlobTransferPermit(client)];\n while (permits.length < limit) {\n const permit = tryAcquireBlobTransferPermit(client);\n if (!permit) break;\n permits.push(permit);\n }\n return permits;\n}\n\n/**\n * Where each part's bytes go. Sources the stage initiation issued are used\n * once; a store that cannot sign (`api`) needs no per-part authorization at\n * all, and a part with no source authorizes just before it is sent.\n */\nexport interface MultipartPartSources {\n readonly apiTransport: boolean;\n readonly issued: Map<number, MultipartBlobPartUploadSource>;\n}\n\nexport async function sha256BytesHex(bytes: BlobBytes): Promise<string> {\n return bytesToHex(\n new Uint8Array(await crypto.subtle.digest(\"SHA-256\", bytes)),\n );\n}\n\nexport async function prepareFirstMultipartParts(\n client: object,\n encryption: BlobEncryptionPlan,\n concurrency: number,\n): Promise<MultipartFirstParts> {\n const permits = await acquireFirstPartPermits(\n client,\n Math.min(encryption.partCount, concurrency, MAX_INITIATE_PART_UPLOADS),\n );\n const descriptors: MultipartBlobPartDescriptor[] = [];\n const prepared = new Map<number, PreparedFirstPart>();\n try {\n for (const [partIndex, permit] of permits.entries()) {\n const bytes = await encryption.encryptPart(partIndex);\n if (bytes.byteLength !== encryption.getPartByteLength(partIndex)) {\n throw new Error(\n `Encrypted blob part ${partIndex + 1} byte length mismatch: expected ${encryption.getPartByteLength(partIndex).toLocaleString()}, received ${bytes.byteLength.toLocaleString()}.`,\n );\n }\n const sha256 = await sha256BytesHex(bytes);\n prepared.set(partIndex, { bytes, permit, sha256 });\n descriptors.push(describeMultipartBlobPart(partIndex + 1, bytes));\n }\n } catch (error) {\n for (const permit of permits) permit.release();\n throw error;\n }\n return { descriptors, prepared };\n}\n\n/**\n * The initiation must return exactly one source per described part, for that\n * part's number, length, and checksum, and every source of one stage must use\n * the same transport.\n */\nexport function readIssuedPartSources(\n descriptors: readonly MultipartBlobPartDescriptor[],\n stage: Pick<InitiateMultipartBlobStageResponse, \"partUploads\">,\n): MultipartPartSources {\n const issued = new Map<number, MultipartBlobPartUploadSource>();\n const kinds = new Set(stage.partUploads.map((upload) => upload.source.kind));\n const matches =\n stage.partUploads.length === descriptors.length &&\n kinds.size === 1 &&\n descriptors.every((descriptor, index) => {\n const upload = stage.partUploads[index];\n return (\n upload?.partNumber === descriptor.partNumber &&\n upload.byteLength === descriptor.byteLength &&\n upload.contentMd5 === descriptor.contentMd5\n );\n });\n if (!matches) {\n throw new Error(\n \"Multipart blob stage initiation part uploads do not match its request.\",\n );\n }\n for (const upload of stage.partUploads) {\n issued.set(upload.partNumber, upload.source);\n }\n return { apiTransport: kinds.has(\"api\"), issued };\n}\n\n/** Use each issued source once; retries and later parts authorize anew. */\nexport function takePartSource(\n sources: MultipartPartSources,\n partNumber: number,\n): MultipartBlobPartUploadSource | undefined {\n const issued = sources.issued.get(partNumber);\n sources.issued.delete(partNumber);\n return issued ?? (sources.apiTransport ? { kind: \"api\" } : undefined);\n}\n"]}
@@ -2,7 +2,7 @@ import { KeyingVerificationError } from "../../internal/crypto/index.js";
2
2
  import { assertBlobContentKeyBundleTargetHash } from "../../data/documents/blob/shared/responses.js";
3
3
  import { assertDocumentWriterProjectionConsistent } from "../../data/documents/shared/projection.js";
4
4
  import { projectionVerificationOptions } from "../../data/documents/shared/types.js";
5
- import { requireProjectionUserKeyResolver, } from "../../data/keyingProjectionVerification.js";
5
+ import { requireProjectionUserKeyResolver, } from "../../data/keyingProjectionVerification/index.js";
6
6
  import { assertAttachmentBindingVerified } from "./attachmentBindingVerification.js";
7
7
  import { assertBlobWrapScopeVerified } from "./verifiedWrapScope.js";
8
8
  /** Retaining an existing envelope does not propagate a key to a new recipient. */
@@ -1,5 +1,5 @@
1
1
  import { computeBlobAccessManifestHash, computeBlobContentKeyTargetHash, } from "../../internal/crypto/index.js";
2
- import { createBlobByteSource, } from "../../data/blobContracts.js";
2
+ import { createBlobByteSource, } from "../../data/blobs/blobContracts.js";
3
3
  import { prepareBlobEncryption } from "../../data/documents/blob/shared/crypto.js";
4
4
  import { signBlobAttachmentEvent, signBlobAttachmentWriteHeader, } from "../../data/documents/blob/shared/events.js";
5
5
  import { verifiedBlobWrapTargetsFromDocumentProjection, wrapBlobContentKey, } from "../../data/documents/blob/shared/projection.js";
@@ -7,8 +7,8 @@ import { assertBlobAttachmentBindResponse } from "../../data/documents/blob/shar
7
7
  import { authorizingContainerPathRefs } from "../../data/documents/shared/projection.js";
8
8
  import { uniqueSortedStrings } from "../../data/documents/shared/readers.js";
9
9
  import { projectionVerificationOptions, } from "../../data/documents/shared/types.js";
10
- import { readCanonicalRecord } from "../../data/keyingCanonicalJson.js";
11
- import { requireProjectionUserKeyResolver } from "../../data/keyingProjectionVerification.js";
10
+ import { readCanonicalRecord } from "../../data/keying/canonicalJson.js";
11
+ import { requireProjectionUserKeyResolver } from "../../data/keyingProjectionVerification/index.js";
12
12
  import { shouldRetryWithFreshProjection } from "../documents/syncFailureClassification.js";
13
13
  import { resolveMultipartUploadOptions } from "./automaticMultipartUpload.js";
14
14
  import { stageMultipartBlobAttachment } from "./multipartUpload.js";
@@ -1 +1 @@
1
- {"version":3,"file":"upload.js","sourceRoot":"","sources":["upload.ts"],"names":[],"mappings":"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xC,CAAC,8BAA8B,CAC7B,KAAK,EACL,CAAC,OAAO,EAAE,EAAE,CACV,OAAO,CAAC,UAAU,CAAC,iCAAiC,CAAC;gBACrD,OAAO,CAAC,QAAQ,CAAC,wBAAwB,CAAC,CAC7C,EACD,CAAC;YACD,MAAM,KAAK,CAAC;QACd,CAAC;QAED,2EAA2E;QAC3E,+DAA+D;QAC/D,SAAS,CAAC,6BAA6B,CAAC,UAAU,CAAC,CAAC;QACpD,QAAQ,GAAG,MAAM,aAAa,CAAC,SAAS,CAAC,CAAC;IAC5C,CAAC;IACD,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,OAAO,IAAI,CAAC;IACd,CAAC;IACD,MAAM,MAAM,GAAG,MAAM,0BAA0B,CAAC;QAC9C,SAAS;QACT,MAAM;QACN,SAAS;QACT,MAAM;QACN,eAAe;QACf,UAAU;QACV,OAAO;QACP,iBAAiB;QACjB,QAAQ;QACR,SAAS,EAAE,iBAAiB;QAC5B,mBAAmB;QACnB,eAAe;QACf,kBAAkB;QAClB,QAAQ;QACR,MAAM;KACP,CAAC,CAAC;IACH,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,MAAM;QACN,SAAS;QACT,gBAAgB,EAAE,QAAQ,CAAC,gBAAgB;QAC3C,GAAG,MAAM;KACV,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,wBAAwB,CACtC,KAAoC;IAEpC,OAAO,4BAA4B,CAAC,EAAE,GAAG,KAAK,EAAE,cAAc,EAAE,SAAS,EAAE,CAAC,CAAC;AAC/E,CAAC;AAED,kFAAkF;AAClF,MAAM,UAAU,gCAAgC,CAC9C,KAA4C;IAE5C,OAAO,4BAA4B,CAAC,KAAK,CAAC,CAAC;AAC7C,CAAC","sourcesContent":["import type {\n AccessEvent,\n AttachmentBindAccessEventBody,\n WriteHeader,\n} from \"@tearleads/crypto\";\nimport {\n computeBlobAccessManifestHash,\n computeBlobContentKeyTargetHash,\n} from \"@tearleads/crypto\";\nimport type {\n BlobAttachmentBindRequest,\n BlobContentKeyBundleRequest,\n} from \"@tearleads/validators/request\";\nimport type { BlobAttachmentBindResponse } from \"@tearleads/validators/response\";\nimport {\n type BlobByteSource,\n createBlobByteSource,\n} from \"../../data/blobContracts\";\nimport type { BlobSourceSnapshot } from \"../../data/documents/blob/shared/blobSourceSnapshot\";\nimport { prepareBlobEncryption } from \"../../data/documents/blob/shared/crypto\";\nimport {\n signBlobAttachmentEvent,\n signBlobAttachmentWriteHeader,\n} from \"../../data/documents/blob/shared/events\";\nimport {\n verifiedBlobWrapTargetsFromDocumentProjection,\n wrapBlobContentKey,\n} from \"../../data/documents/blob/shared/projection\";\nimport { assertBlobAttachmentBindResponse } from \"../../data/documents/blob/shared/responses\";\nimport type {\n BlobAttachmentApi,\n BlobAttachmentMaterial,\n MultipartStageResolvedListener,\n MultipartUploadProgressListener,\n UploadDocumentAttachmentInput,\n UploadDocumentAttachmentResult,\n} from \"../../data/documents/blob/shared/types\";\nimport { authorizingContainerPathRefs } from \"../../data/documents/shared/projection\";\nimport { uniqueSortedStrings } from \"../../data/documents/shared/readers\";\nimport {\n type DocumentCreateAuthor,\n type ProjectionVerificationOptions,\n projectionVerificationOptions,\n} from \"../../data/documents/shared/types\";\nimport { readCanonicalRecord } from \"../../data/keyingCanonicalJson\";\nimport { requireProjectionUserKeyResolver } from \"../../data/keyingProjectionVerification\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { shouldRetryWithFreshProjection } from \"../documents/syncFailureClassification\";\nimport { resolveMultipartUploadOptions } from \"./automaticMultipartUpload\";\nimport { stageMultipartBlobAttachment } from \"./multipartUpload\";\nimport { resolveBlobMutationWriterProjection } from \"./writerProjection\";\n\nasync function buildBlobAttachmentMaterial(\n input: {\n apiClient: BlobAttachmentApi;\n bindingId: string;\n blobId: string;\n contentKey: Uint8Array;\n contentKeyEpoch: number;\n documentId: string;\n execSql?: ExecSql | undefined;\n isRemoteSyncBlocked?: ((organizationId: string) => boolean) | undefined;\n nonceSeed?: Uint8Array | undefined;\n partSize: number;\n source: BlobByteSource;\n sourceSnapshot?: BlobSourceSnapshot | undefined;\n targetSecretKey: Uint8Array;\n writerProjection?: UploadDocumentAttachmentInput[\"writerProjection\"];\n } & ProjectionVerificationOptions,\n): Promise<BlobAttachmentMaterial | null> {\n const resolved = await resolveBlobMutationWriterProjection({\n apiClient: input.apiClient,\n documentId: input.documentId,\n errorLabel: \"Blob attachment\",\n execSql: input.execSql,\n isRemoteSyncBlocked: input.isRemoteSyncBlocked,\n writerProjection: input.writerProjection,\n ...projectionVerificationOptions(input),\n });\n if (!resolved) {\n return null;\n }\n const { manifestIdentity, writerProjection } = resolved;\n\n const targets = verifiedBlobWrapTargetsFromDocumentProjection({\n bindingId: input.bindingId,\n documentId: input.documentId,\n writerProjection,\n });\n const targetHash = await computeBlobContentKeyTargetHash(targets);\n const contentKeyBundle: BlobContentKeyBundleRequest = {\n contentKeyEpoch: input.contentKeyEpoch,\n targetHash,\n targets: await wrapBlobContentKey({\n blobId: input.blobId,\n contentKey: input.contentKey,\n contentKeyEpoch: input.contentKeyEpoch,\n execSql: input.execSql,\n secretKey: input.targetSecretKey,\n targets,\n writerProjection,\n ...projectionVerificationOptions(input),\n }),\n };\n const encrypted = await prepareBlobEncryption({\n blobId: input.blobId,\n chunkSize: input.partSize,\n contentKey: input.contentKey,\n contentKeyBundle,\n nonceSeed: input.nonceSeed,\n organizationId: manifestIdentity.organizationId,\n source: input.source,\n sourceSnapshot: input.sourceSnapshot,\n });\n const blobAccessManifestHash = await computeBlobAccessManifestHash({\n version: 1,\n blobId: input.blobId,\n organizationId: manifestIdentity.organizationId,\n activeBindingIds: [input.bindingId],\n documentManifestHashes: [manifestIdentity.manifestHash],\n linkedContainerManifestHashes: uniqueSortedStrings(\n targets.map((target) => target.containerManifestHash),\n ),\n linkedContainerKeyEpochIds: uniqueSortedStrings(\n targets.map((target) => target.containerKeyEpochId),\n ),\n blobKeyTargetHash: targetHash,\n });\n\n return {\n blobAccessManifestHash,\n contentKeyBundle,\n encrypted,\n manifestIdentity,\n targetHash,\n targets,\n writerProjection,\n };\n}\n\nfunction blobAttachmentBindRequest(input: {\n body: AttachmentBindAccessEventBody;\n event: AccessEvent;\n material: BlobAttachmentMaterial;\n stageId: string;\n writeHeader: WriteHeader;\n}): BlobAttachmentBindRequest {\n return {\n event: readCanonicalRecord(input.event, \"Blob attachment bind event\"),\n body: readCanonicalRecord(input.body, \"Blob attachment bind body\"),\n authorizingContainerPathRefs: authorizingContainerPathRefs(\n input.material.writerProjection,\n ),\n contentKeyBundle: input.material.contentKeyBundle,\n stagedBlob: {\n stageId: input.stageId,\n writeHeader: readCanonicalRecord(\n input.writeHeader,\n \"Blob attachment write header\",\n ),\n },\n };\n}\n\nasync function stageAndBindBlobAttachment(input: {\n apiClient: BlobAttachmentApi;\n author: DocumentCreateAuthor;\n bindingId: string;\n blobId: string;\n contentKeyEpoch: number;\n documentId: string;\n eventId: string;\n expectedBindingId: string | null;\n material: BlobAttachmentMaterial;\n multipart: NonNullable<UploadDocumentAttachmentInput[\"multipart\"]>;\n onMultipartProgress?: MultipartUploadProgressListener | undefined;\n onStageResolved?: MultipartStageResolvedListener | undefined;\n onStageUnavailable?: ((stageId: string) => Promise<void>) | undefined;\n signedAt: string;\n slotId: string;\n}): Promise<{\n request: BlobAttachmentBindRequest;\n response: BlobAttachmentBindResponse;\n sha256: string;\n byteLength: number;\n writeHeader: WriteHeader;\n writeHeaderHash: string;\n} | null> {\n const { body, event } = await signBlobAttachmentEvent({\n author: input.author,\n bindingId: input.bindingId,\n blobId: input.blobId,\n documentId: input.documentId,\n eventId: input.eventId,\n expectedBindingId: input.expectedBindingId,\n manifestIdentity: input.material.manifestIdentity,\n signedAt: input.signedAt,\n slotId: input.slotId,\n authorizingContainerPathRefs: authorizingContainerPathRefs(\n input.material.writerProjection,\n ),\n });\n const { writeHeader, writeHeaderHash } = await signBlobAttachmentWriteHeader({\n authorizingContainerPathRefs: authorizingContainerPathRefs(\n input.material.writerProjection,\n ),\n author: input.author,\n blobAccessManifestHash: input.material.blobAccessManifestHash,\n blobId: input.blobId,\n contentKeyEpoch: input.contentKeyEpoch,\n encrypted: input.material.encrypted,\n manifestIdentity: input.material.manifestIdentity,\n signedAt: input.signedAt,\n targetHash: input.material.targetHash,\n });\n const stageId = await stageMultipartBlobAttachment({\n organizationId: input.material.manifestIdentity.organizationId,\n apiClient: input.apiClient,\n encryption: input.material.encrypted,\n multipart: input.multipart,\n onMultipartProgress: input.onMultipartProgress,\n onStageResolved: input.onStageResolved,\n onStageUnavailable: input.onStageUnavailable,\n });\n if (!stageId) {\n return null;\n }\n\n const request = blobAttachmentBindRequest({\n body,\n event,\n material: input.material,\n stageId,\n writeHeader,\n });\n const response = await input.apiClient.bindBlobAttachment(\n input.blobId,\n request,\n {\n expectedPaymentRequiredOrganizationId:\n input.material.manifestIdentity.organizationId,\n },\n );\n if (!response) {\n return null;\n }\n\n await assertBlobAttachmentBindResponse({\n body,\n bindingId: input.bindingId,\n blobAccessManifestHash: input.material.blobAccessManifestHash,\n blobId: input.blobId,\n contentKeyBundle: input.material.contentKeyBundle,\n documentId: input.documentId,\n event,\n manifestIdentity: input.material.manifestIdentity,\n response,\n slotId: input.slotId,\n targetHash: input.material.targetHash,\n targets: input.material.targets,\n writeHeader,\n writeHeaderHash,\n });\n\n return {\n request,\n response,\n sha256: input.material.encrypted.sha256,\n byteLength: input.material.encrypted.byteLength,\n writeHeader,\n writeHeaderHash,\n };\n}\n\ninterface PreparedUploadDocumentAttachmentInput\n extends UploadDocumentAttachmentInput {\n readonly sourceSnapshot?: BlobSourceSnapshot | undefined;\n readonly onStageUnavailable?:\n | ((stageId: string) => Promise<void>)\n | undefined;\n}\n\nasync function uploadDocumentAttachmentImpl({\n apiClient,\n author,\n blobId = crypto.randomUUID(),\n bindingId = crypto.randomUUID(),\n bytes,\n contentKey = crypto.getRandomValues(new Uint8Array(32)),\n contentKeyEpoch = 1,\n documentId,\n eventId = crypto.randomUUID(),\n execSql,\n expectedBindingId,\n isRemoteSyncBlocked,\n nonceSeed,\n multipart,\n onMultipartProgress,\n onStageResolved,\n onStageUnavailable,\n resolveProjectionUserKey,\n signedAt = new Date().toISOString(),\n slotId,\n sourceSnapshot,\n targetSecretKey,\n warmReferencedPrincipalPolicies,\n writerProjection,\n}: PreparedUploadDocumentAttachmentInput): Promise<UploadDocumentAttachmentResult | null> {\n if (contentKey.byteLength !== 32) {\n throw new Error(\"Blob content key must be 32 bytes\");\n }\n const resolveProjectionUserKeyForUpload = requireProjectionUserKeyResolver(\n resolveProjectionUserKey,\n \"Document attachment upload\",\n );\n const resolvedMultipart = resolveMultipartUploadOptions(multipart);\n const source = createBlobByteSource(bytes);\n\n const buildMaterial = (\n freshWriterProjection: UploadDocumentAttachmentInput[\"writerProjection\"],\n ) =>\n buildBlobAttachmentMaterial({\n apiClient,\n bindingId,\n blobId,\n contentKey,\n contentKeyEpoch,\n documentId,\n execSql,\n isRemoteSyncBlocked,\n nonceSeed,\n partSize: resolvedMultipart.partSize,\n resolveProjectionUserKey: resolveProjectionUserKeyForUpload,\n source,\n sourceSnapshot,\n targetSecretKey,\n warmReferencedPrincipalPolicies,\n writerProjection: freshWriterProjection,\n });\n let material: BlobAttachmentMaterial | null;\n try {\n material = await buildMaterial(writerProjection);\n } catch (error) {\n if (\n !apiClient.evictDocumentWriterProjection ||\n !shouldRetryWithFreshProjection(\n error,\n (message) =>\n message.startsWith(\"Container writer projection KEK\") &&\n message.includes(\"could not be unwrapped\"),\n )\n ) {\n throw error;\n }\n\n // The attachment binds to this document; only its projection was stale, so\n // evict just it rather than wiping the whole projection cache.\n apiClient.evictDocumentWriterProjection(documentId);\n material = await buildMaterial(undefined);\n }\n if (!material) {\n return null;\n }\n const result = await stageAndBindBlobAttachment({\n apiClient,\n author,\n bindingId,\n blobId,\n contentKeyEpoch,\n documentId,\n eventId,\n expectedBindingId,\n material,\n multipart: resolvedMultipart,\n onMultipartProgress,\n onStageResolved,\n onStageUnavailable,\n signedAt,\n slotId,\n });\n if (!result) {\n return null;\n }\n\n return {\n blobId,\n bindingId,\n writerProjection: material.writerProjection,\n ...result,\n };\n}\n\nexport function uploadDocumentAttachment(\n input: UploadDocumentAttachmentInput,\n): Promise<UploadDocumentAttachmentResult | null> {\n return uploadDocumentAttachmentImpl({ ...input, sourceSnapshot: undefined });\n}\n\n/** Internal upload path for a source snapshot produced by `inspectBlobSource`. */\nexport function uploadPreparedDocumentAttachment(\n input: PreparedUploadDocumentAttachmentInput,\n): Promise<UploadDocumentAttachmentResult | null> {\n return uploadDocumentAttachmentImpl(input);\n}\n"]}
1
+ {"version":3,"file":"upload.js","sourceRoot":"","sources":["upload.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,6BAA6B,EAC7B,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAM3B,OAAO,EAEL,oBAAoB,GACrB,MAAM,gCAAgC,CAAC;AAExC,OAAO,EAAE,qBAAqB,EAAE,MAAM,yCAAyC,CAAC;AAChF,OAAO,EACL,uBAAuB,EACvB,6BAA6B,GAC9B,MAAM,yCAAyC,CAAC;AACjD,OAAO,EACL,6CAA6C,EAC7C,kBAAkB,GACnB,MAAM,6CAA6C,CAAC;AACrD,OAAO,EAAE,gCAAgC,EAAE,MAAM,4CAA4C,CAAC;AAS9F,OAAO,EAAE,4BAA4B,EAAE,MAAM,wCAAwC,CAAC;AACtF,OAAO,EAAE,mBAAmB,EAAE,MAAM,qCAAqC,CAAC;AAC1E,OAAO,EAGL,6BAA6B,GAC9B,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AACtE,OAAO,EAAE,gCAAgC,EAAE,MAAM,yCAAyC,CAAC;AAE3F,OAAO,EAAE,8BAA8B,EAAE,MAAM,wCAAwC,CAAC;AACxF,OAAO,EAAE,6BAA6B,EAAE,MAAM,4BAA4B,CAAC;AAC3E,OAA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,OAAO;QACL,MAAM;QACN,SAAS;QACT,gBAAgB,EAAE,QAAQ,CAAC,gBAAgB;QAC3C,GAAG,MAAM;KACV,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,wBAAwB,CACtC,KAAoC;IAEpC,OAAO,4BAA4B,CAAC,EAAE,GAAG,KAAK,EAAE,cAAc,EAAE,SAAS,EAAE,CAAC,CAAC;AAC/E,CAAC;AAED,kFAAkF;AAClF,MAAM,UAAU,gCAAgC,CAC9C,KAA4C;IAE5C,OAAO,4BAA4B,CAAC,KAAK,CAAC,CAAC;AAC7C,CAAC","sourcesContent":["import type {\n AccessEvent,\n AttachmentBindAccessEventBody,\n WriteHeader,\n} from \"@tearleads/crypto\";\nimport {\n computeBlobAccessManifestHash,\n computeBlobContentKeyTargetHash,\n} from \"@tearleads/crypto\";\nimport type {\n BlobAttachmentBindRequest,\n BlobContentKeyBundleRequest,\n} from \"@tearleads/validators/request\";\nimport type { BlobAttachmentBindResponse } from \"@tearleads/validators/response\";\nimport {\n type BlobByteSource,\n createBlobByteSource,\n} from \"../../data/blobs/blobContracts\";\nimport type { BlobSourceSnapshot } from \"../../data/documents/blob/shared/blobSourceSnapshot\";\nimport { prepareBlobEncryption } from \"../../data/documents/blob/shared/crypto\";\nimport {\n signBlobAttachmentEvent,\n signBlobAttachmentWriteHeader,\n} from \"../../data/documents/blob/shared/events\";\nimport {\n verifiedBlobWrapTargetsFromDocumentProjection,\n wrapBlobContentKey,\n} from \"../../data/documents/blob/shared/projection\";\nimport { assertBlobAttachmentBindResponse } from \"../../data/documents/blob/shared/responses\";\nimport type {\n BlobAttachmentApi,\n BlobAttachmentMaterial,\n MultipartStageResolvedListener,\n MultipartUploadProgressListener,\n UploadDocumentAttachmentInput,\n UploadDocumentAttachmentResult,\n} from \"../../data/documents/blob/shared/types\";\nimport { authorizingContainerPathRefs } from \"../../data/documents/shared/projection\";\nimport { uniqueSortedStrings } from \"../../data/documents/shared/readers\";\nimport {\n type DocumentCreateAuthor,\n type ProjectionVerificationOptions,\n projectionVerificationOptions,\n} from \"../../data/documents/shared/types\";\nimport { readCanonicalRecord } from \"../../data/keying/canonicalJson\";\nimport { requireProjectionUserKeyResolver } from \"../../data/keyingProjectionVerification\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { shouldRetryWithFreshProjection } from \"../documents/syncFailureClassification\";\nimport { resolveMultipartUploadOptions } from \"./automaticMultipartUpload\";\nimport { stageMultipartBlobAttachment } from \"./multipartUpload\";\nimport { resolveBlobMutationWriterProjection } from \"./writerProjection\";\n\nasync function buildBlobAttachmentMaterial(\n input: {\n apiClient: BlobAttachmentApi;\n bindingId: string;\n blobId: string;\n contentKey: Uint8Array;\n contentKeyEpoch: number;\n documentId: string;\n execSql?: ExecSql | undefined;\n isRemoteSyncBlocked?: ((organizationId: string) => boolean) | undefined;\n nonceSeed?: Uint8Array | undefined;\n partSize: number;\n source: BlobByteSource;\n sourceSnapshot?: BlobSourceSnapshot | undefined;\n targetSecretKey: Uint8Array;\n writerProjection?: UploadDocumentAttachmentInput[\"writerProjection\"];\n } & ProjectionVerificationOptions,\n): Promise<BlobAttachmentMaterial | null> {\n const resolved = await resolveBlobMutationWriterProjection({\n apiClient: input.apiClient,\n documentId: input.documentId,\n errorLabel: \"Blob attachment\",\n execSql: input.execSql,\n isRemoteSyncBlocked: input.isRemoteSyncBlocked,\n writerProjection: input.writerProjection,\n ...projectionVerificationOptions(input),\n });\n if (!resolved) {\n return null;\n }\n const { manifestIdentity, writerProjection } = resolved;\n\n const targets = verifiedBlobWrapTargetsFromDocumentProjection({\n bindingId: input.bindingId,\n documentId: input.documentId,\n writerProjection,\n });\n const targetHash = await computeBlobContentKeyTargetHash(targets);\n const contentKeyBundle: BlobContentKeyBundleRequest = {\n contentKeyEpoch: input.contentKeyEpoch,\n targetHash,\n targets: await wrapBlobContentKey({\n blobId: input.blobId,\n contentKey: input.contentKey,\n contentKeyEpoch: input.contentKeyEpoch,\n execSql: input.execSql,\n secretKey: input.targetSecretKey,\n targets,\n writerProjection,\n ...projectionVerificationOptions(input),\n }),\n };\n const encrypted = await prepareBlobEncryption({\n blobId: input.blobId,\n chunkSize: input.partSize,\n contentKey: input.contentKey,\n contentKeyBundle,\n nonceSeed: input.nonceSeed,\n organizationId: manifestIdentity.organizationId,\n source: input.source,\n sourceSnapshot: input.sourceSnapshot,\n });\n const blobAccessManifestHash = await computeBlobAccessManifestHash({\n version: 1,\n blobId: input.blobId,\n organizationId: manifestIdentity.organizationId,\n activeBindingIds: [input.bindingId],\n documentManifestHashes: [manifestIdentity.manifestHash],\n linkedContainerManifestHashes: uniqueSortedStrings(\n targets.map((target) => target.containerManifestHash),\n ),\n linkedContainerKeyEpochIds: uniqueSortedStrings(\n targets.map((target) => target.containerKeyEpochId),\n ),\n blobKeyTargetHash: targetHash,\n });\n\n return {\n blobAccessManifestHash,\n contentKeyBundle,\n encrypted,\n manifestIdentity,\n targetHash,\n targets,\n writerProjection,\n };\n}\n\nfunction blobAttachmentBindRequest(input: {\n body: AttachmentBindAccessEventBody;\n event: AccessEvent;\n material: BlobAttachmentMaterial;\n stageId: string;\n writeHeader: WriteHeader;\n}): BlobAttachmentBindRequest {\n return {\n event: readCanonicalRecord(input.event, \"Blob attachment bind event\"),\n body: readCanonicalRecord(input.body, \"Blob attachment bind body\"),\n authorizingContainerPathRefs: authorizingContainerPathRefs(\n input.material.writerProjection,\n ),\n contentKeyBundle: input.material.contentKeyBundle,\n stagedBlob: {\n stageId: input.stageId,\n writeHeader: readCanonicalRecord(\n input.writeHeader,\n \"Blob attachment write header\",\n ),\n },\n };\n}\n\nasync function stageAndBindBlobAttachment(input: {\n apiClient: BlobAttachmentApi;\n author: DocumentCreateAuthor;\n bindingId: string;\n blobId: string;\n contentKeyEpoch: number;\n documentId: string;\n eventId: string;\n expectedBindingId: string | null;\n material: BlobAttachmentMaterial;\n multipart: NonNullable<UploadDocumentAttachmentInput[\"multipart\"]>;\n onMultipartProgress?: MultipartUploadProgressListener | undefined;\n onStageResolved?: MultipartStageResolvedListener | undefined;\n onStageUnavailable?: ((stageId: string) => Promise<void>) | undefined;\n signedAt: string;\n slotId: string;\n}): Promise<{\n request: BlobAttachmentBindRequest;\n response: BlobAttachmentBindResponse;\n sha256: string;\n byteLength: number;\n writeHeader: WriteHeader;\n writeHeaderHash: string;\n} | null> {\n const { body, event } = await signBlobAttachmentEvent({\n author: input.author,\n bindingId: input.bindingId,\n blobId: input.blobId,\n documentId: input.documentId,\n eventId: input.eventId,\n expectedBindingId: input.expectedBindingId,\n manifestIdentity: input.material.manifestIdentity,\n signedAt: input.signedAt,\n slotId: input.slotId,\n authorizingContainerPathRefs: authorizingContainerPathRefs(\n input.material.writerProjection,\n ),\n });\n const { writeHeader, writeHeaderHash } = await signBlobAttachmentWriteHeader({\n authorizingContainerPathRefs: authorizingContainerPathRefs(\n input.material.writerProjection,\n ),\n author: input.author,\n blobAccessManifestHash: input.material.blobAccessManifestHash,\n blobId: input.blobId,\n contentKeyEpoch: input.contentKeyEpoch,\n encrypted: input.material.encrypted,\n manifestIdentity: input.material.manifestIdentity,\n signedAt: input.signedAt,\n targetHash: input.material.targetHash,\n });\n const stageId = await stageMultipartBlobAttachment({\n organizationId: input.material.manifestIdentity.organizationId,\n apiClient: input.apiClient,\n encryption: input.material.encrypted,\n multipart: input.multipart,\n onMultipartProgress: input.onMultipartProgress,\n onStageResolved: input.onStageResolved,\n onStageUnavailable: input.onStageUnavailable,\n });\n if (!stageId) {\n return null;\n }\n\n const request = blobAttachmentBindRequest({\n body,\n event,\n material: input.material,\n stageId,\n writeHeader,\n });\n const response = await input.apiClient.bindBlobAttachment(\n input.blobId,\n request,\n {\n expectedPaymentRequiredOrganizationId:\n input.material.manifestIdentity.organizationId,\n },\n );\n if (!response) {\n return null;\n }\n\n await assertBlobAttachmentBindResponse({\n body,\n bindingId: input.bindingId,\n blobAccessManifestHash: input.material.blobAccessManifestHash,\n blobId: input.blobId,\n contentKeyBundle: input.material.contentKeyBundle,\n documentId: input.documentId,\n event,\n manifestIdentity: input.material.manifestIdentity,\n response,\n slotId: input.slotId,\n targetHash: input.material.targetHash,\n targets: input.material.targets,\n writeHeader,\n writeHeaderHash,\n });\n\n return {\n request,\n response,\n sha256: input.material.encrypted.sha256,\n byteLength: input.material.encrypted.byteLength,\n writeHeader,\n writeHeaderHash,\n };\n}\n\ninterface PreparedUploadDocumentAttachmentInput\n extends UploadDocumentAttachmentInput {\n readonly sourceSnapshot?: BlobSourceSnapshot | undefined;\n readonly onStageUnavailable?:\n | ((stageId: string) => Promise<void>)\n | undefined;\n}\n\nasync function uploadDocumentAttachmentImpl({\n apiClient,\n author,\n blobId = crypto.randomUUID(),\n bindingId = crypto.randomUUID(),\n bytes,\n contentKey = crypto.getRandomValues(new Uint8Array(32)),\n contentKeyEpoch = 1,\n documentId,\n eventId = crypto.randomUUID(),\n execSql,\n expectedBindingId,\n isRemoteSyncBlocked,\n nonceSeed,\n multipart,\n onMultipartProgress,\n onStageResolved,\n onStageUnavailable,\n resolveProjectionUserKey,\n signedAt = new Date().toISOString(),\n slotId,\n sourceSnapshot,\n targetSecretKey,\n warmReferencedPrincipalPolicies,\n writerProjection,\n}: PreparedUploadDocumentAttachmentInput): Promise<UploadDocumentAttachmentResult | null> {\n if (contentKey.byteLength !== 32) {\n throw new Error(\"Blob content key must be 32 bytes\");\n }\n const resolveProjectionUserKeyForUpload = requireProjectionUserKeyResolver(\n resolveProjectionUserKey,\n \"Document attachment upload\",\n );\n const resolvedMultipart = resolveMultipartUploadOptions(multipart);\n const source = createBlobByteSource(bytes);\n\n const buildMaterial = (\n freshWriterProjection: UploadDocumentAttachmentInput[\"writerProjection\"],\n ) =>\n buildBlobAttachmentMaterial({\n apiClient,\n bindingId,\n blobId,\n contentKey,\n contentKeyEpoch,\n documentId,\n execSql,\n isRemoteSyncBlocked,\n nonceSeed,\n partSize: resolvedMultipart.partSize,\n resolveProjectionUserKey: resolveProjectionUserKeyForUpload,\n source,\n sourceSnapshot,\n targetSecretKey,\n warmReferencedPrincipalPolicies,\n writerProjection: freshWriterProjection,\n });\n let material: BlobAttachmentMaterial | null;\n try {\n material = await buildMaterial(writerProjection);\n } catch (error) {\n if (\n !apiClient.evictDocumentWriterProjection ||\n !shouldRetryWithFreshProjection(\n error,\n (message) =>\n message.startsWith(\"Container writer projection KEK\") &&\n message.includes(\"could not be unwrapped\"),\n )\n ) {\n throw error;\n }\n\n // The attachment binds to this document; only its projection was stale, so\n // evict just it rather than wiping the whole projection cache.\n apiClient.evictDocumentWriterProjection(documentId);\n material = await buildMaterial(undefined);\n }\n if (!material) {\n return null;\n }\n const result = await stageAndBindBlobAttachment({\n apiClient,\n author,\n bindingId,\n blobId,\n contentKeyEpoch,\n documentId,\n eventId,\n expectedBindingId,\n material,\n multipart: resolvedMultipart,\n onMultipartProgress,\n onStageResolved,\n onStageUnavailable,\n signedAt,\n slotId,\n });\n if (!result) {\n return null;\n }\n\n return {\n blobId,\n bindingId,\n writerProjection: material.writerProjection,\n ...result,\n };\n}\n\nexport function uploadDocumentAttachment(\n input: UploadDocumentAttachmentInput,\n): Promise<UploadDocumentAttachmentResult | null> {\n return uploadDocumentAttachmentImpl({ ...input, sourceSnapshot: undefined });\n}\n\n/** Internal upload path for a source snapshot produced by `inspectBlobSource`. */\nexport function uploadPreparedDocumentAttachment(\n input: PreparedUploadDocumentAttachmentInput,\n): Promise<UploadDocumentAttachmentResult | null> {\n return uploadDocumentAttachmentImpl(input);\n}\n"]}
@@ -1,8 +1,8 @@
1
1
  import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
2
- import { errorMessage } from "../../../data/errorMessage.js";
3
2
  import { verifiedContainerCreateManifest } from "../../../data/keyingProjectionVerification/containerCreateManifest.js";
4
3
  import { verifyContainerDestinationProjection } from "../../../data/keyingProjectionVerification/containerDestinationVerification.js";
5
4
  import { isKeyingVerificationError, reportKeyingVerificationErrorInCauseChain, } from "../../../data/keyingProjectionVerification/error.js";
5
+ import { errorMessage } from "../../../data/shared/errorMessage.js";
6
6
  import { createRuntimePrincipalPolicyWarmer } from "../../principals/runtimePolicyWarmer.js";
7
7
  import { settleContainerCreateIntent } from "./createIntentSettlement.js";
8
8
  const LABEL = "Container create conflict";