@tearleads/client-sdk 0.1.64 → 0.1.65

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 (622) hide show
  1. package/client/organizations/organizationAccessRestoration.js +1 -1
  2. package/data/containers/shared/mutationAcknowledgement.js +1 -1
  3. package/data/containers/shared/mutationAcknowledgement.js.map +1 -1
  4. package/data/documents/blob/shared/projection.js +3 -3
  5. package/data/documents/blob/shared/projection.js.map +1 -1
  6. package/data/documents/shared/{containerKekCurrency.d.ts → containerKek/containerKekCurrency.d.ts} +1 -1
  7. package/data/documents/shared/{containerKekEntryVerification.js → containerKek/containerKekEntryVerification.js} +1 -1
  8. package/data/documents/shared/{containerKekLogFetch.d.ts → containerKek/containerKekLogFetch.d.ts} +1 -1
  9. package/data/documents/shared/{containerKekLogFetch.js → containerKek/containerKekLogFetch.js} +1 -1
  10. package/data/documents/shared/{containerKekPath.js → containerKek/containerKekPath.js} +3 -3
  11. package/data/documents/shared/containerKek/containerKekPath.js.map +1 -0
  12. package/data/documents/shared/{containerKekPathHistory.d.ts → containerKek/containerKekPathHistory.d.ts} +3 -3
  13. package/data/documents/shared/{containerKekPathHistory.js → containerKek/containerKekPathHistory.js} +4 -4
  14. package/data/documents/shared/containerKek/containerKekPathHistory.js.map +1 -0
  15. package/data/documents/shared/{containerKekPathVerification.d.ts → containerKek/containerKekPathVerification.d.ts} +5 -5
  16. package/data/documents/shared/{containerKekPathVerification.js → containerKek/containerKekPathVerification.js} +2 -2
  17. package/data/documents/shared/containerKek/containerKekPathVerification.js.map +1 -0
  18. package/data/documents/shared/{containerKekWrapping.js → containerKek/containerKekWrapping.js} +3 -3
  19. package/data/documents/shared/containerKek/containerKekWrapping.js.map +1 -0
  20. package/data/documents/shared/{keyringLogWalk.d.ts → containerKek/keyringLogWalk.d.ts} +2 -2
  21. package/data/documents/shared/{keyringLogWalk.js → containerKek/keyringLogWalk.js} +1 -1
  22. package/data/documents/shared/{keyringRebuild.d.ts → containerKek/keyringRebuild.d.ts} +3 -3
  23. package/data/documents/shared/{keyringRebuild.js → containerKek/keyringRebuild.js} +3 -3
  24. package/data/documents/shared/containerKek/keyringRebuild.js.map +1 -0
  25. package/data/documents/shared/crypto.js +2 -2
  26. package/data/documents/shared/crypto.js.map +1 -1
  27. package/data/documents/shared/events.js +1 -1
  28. package/data/documents/shared/{projection.d.ts → projection/index.d.ts} +7 -7
  29. package/data/documents/shared/{projection.js → projection/index.js} +9 -9
  30. package/data/documents/shared/projection/index.js.map +1 -0
  31. package/data/documents/shared/{projectionContentKeys.d.ts → projection/projectionContentKeys.d.ts} +6 -6
  32. package/data/documents/shared/{projectionContentKeys.js → projection/projectionContentKeys.js} +9 -9
  33. package/data/documents/shared/projection/projectionContentKeys.js.map +1 -0
  34. package/data/documents/shared/{projectionTargets.d.ts → projection/projectionTargets.d.ts} +4 -4
  35. package/data/documents/shared/{projectionTargets.js → projection/projectionTargets.js} +3 -3
  36. package/data/documents/shared/projection/projectionTargets.js.map +1 -0
  37. package/data/documents/shared/responses.d.ts +1 -1
  38. package/data/documents/shared/responses.js +1 -1
  39. package/data/documents/shared/responses.js.map +1 -1
  40. package/data/documents/shared/{documentSyncUpdateDecryption.js → sync/documentSyncUpdateDecryption.js} +10 -10
  41. package/data/documents/shared/sync/documentSyncUpdateDecryption.js.map +1 -0
  42. package/data/documents/shared/{documentSyncUpdateIsolation.d.ts → sync/documentSyncUpdateIsolation.d.ts} +3 -3
  43. package/data/documents/shared/{documentSyncUpdateIsolation.js → sync/documentSyncUpdateIsolation.js} +1 -1
  44. package/data/documents/shared/sync/documentSyncUpdateIsolation.js.map +1 -0
  45. package/data/documents/shared/{mutationAcknowledgement.js → sync/mutationAcknowledgement.js} +1 -1
  46. package/data/documents/shared/sync/mutationAcknowledgement.js.map +1 -0
  47. package/data/documents/shared/{pullContinuation.js → sync/pullContinuation.js} +1 -1
  48. package/data/documents/shared/{syncPagination.d.ts → sync/syncPagination.d.ts} +2 -2
  49. package/data/documents/shared/{syncPagination.js → sync/syncPagination.js} +1 -1
  50. package/data/documents/shared/sync/syncPagination.js.map +1 -0
  51. package/data/documents/shared/{syncResponseAuthorization.js → sync/syncResponseAuthorization.js} +3 -3
  52. package/data/documents/shared/sync/syncResponseAuthorization.js.map +1 -0
  53. package/data/documents/shared/{syncResponses.d.ts → sync/syncResponses.d.ts} +2 -2
  54. package/data/documents/shared/{syncResponses.js → sync/syncResponses.js} +6 -6
  55. package/data/documents/shared/sync/syncResponses.js.map +1 -0
  56. package/data/documents/shared/{syncSubmitFailure.d.ts → sync/syncSubmitFailure.d.ts} +1 -1
  57. package/data/documents/shared/types.d.ts +3 -3
  58. package/data/documents/shared/types.js.map +1 -1
  59. package/data/keyingProjectionVerification/checkpoints/accessManifestCheckpointEnforcement.js +1 -1
  60. package/data/keyingProjectionVerification/checkpoints/accessManifestCheckpointEnforcement.js.map +1 -1
  61. package/data/keyingProjectionVerification/checkpoints/checkpointContext.d.ts +1 -1
  62. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js +1 -1
  63. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js.map +1 -1
  64. package/data/keyingProjectionVerification/checkpoints/manifestCheckpointVerification.js +1 -1
  65. package/data/keyingProjectionVerification/checkpoints/manifestCheckpointVerification.js.map +1 -1
  66. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js +4 -4
  67. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js.map +1 -1
  68. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointEnforcement.js +1 -1
  69. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointEnforcement.js.map +1 -1
  70. package/data/keyingProjectionVerification/documentPurge/documentPurgePolicyCheckpoints.js +1 -1
  71. package/data/keyingProjectionVerification/documentPurge/documentPurgePolicyCheckpoints.js.map +1 -1
  72. package/data/keyingProjectionVerification/documentPurge/documentPurgePolicyCurrency.js +1 -1
  73. package/data/keyingProjectionVerification/documentPurge/documentPurgePolicyCurrency.js.map +1 -1
  74. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js +3 -3
  75. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js.map +1 -1
  76. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js +4 -4
  77. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js.map +1 -1
  78. package/data/keyingProjectionVerification/principalPolicy/resolvedPrincipalPolicy.js +2 -2
  79. package/data/keyingProjectionVerification/principalPolicy/resolvedPrincipalPolicy.js.map +1 -1
  80. package/data/persistence/container-contents/containerContentsPersistence.js +3 -3
  81. package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
  82. package/data/persistence/container-contents/containerContentsPersistenceTypes.d.ts +2 -2
  83. package/data/persistence/container-contents/containerContentsPersistenceTypes.js.map +1 -1
  84. package/data/persistence/container-contents/containerCreateIntentSettlement.js +1 -1
  85. package/data/persistence/container-contents/containerDeletionPersistence.js +2 -2
  86. package/data/persistence/container-contents/containerDocumentReassignment.js +2 -2
  87. package/data/persistence/container-contents/containerDocumentReassignment.js.map +1 -1
  88. package/data/persistence/container-contents/containerHydrationPersistence.js +3 -3
  89. package/data/persistence/container-contents/containerHydrationPersistence.js.map +1 -1
  90. package/data/persistence/container-contents/containerIntentPersistence.js +1 -1
  91. package/data/persistence/container-contents/containerMetadataMutationPersistence.js +5 -5
  92. package/data/persistence/container-contents/containerMetadataMutationPersistence.js.map +1 -1
  93. package/data/persistence/container-contents/containerMetadataPullContinuationPersistence.js +1 -1
  94. package/data/persistence/container-contents/containerMetadataRows.js +3 -3
  95. package/data/persistence/container-contents/containerMetadataRows.js.map +1 -1
  96. package/data/persistence/container-contents/containerMoveAbandonPersistence.js +1 -1
  97. package/data/persistence/container-contents/containerMoveIntentRows.js +1 -1
  98. package/data/persistence/container-contents/containerPendingUpdatePersistence.js +3 -3
  99. package/data/persistence/container-contents/containerPendingUpdatePersistence.js.map +1 -1
  100. package/data/persistence/container-contents/containerRebindPersistence.js +1 -1
  101. package/data/persistence/container-contents/containerReconcilePersistence.js +2 -2
  102. package/data/persistence/container-contents/containerRecoveryPersistence.js +1 -1
  103. package/data/persistence/container-contents/containerRemovalWork.js +3 -3
  104. package/data/persistence/container-contents/containerRemovalWork.js.map +1 -1
  105. package/data/persistence/container-contents/containerStructuralRepair.js +1 -1
  106. package/data/persistence/container-contents/documentLinkRemovalRepair.js +2 -2
  107. package/data/persistence/container-contents/documentLinkRemovalRepair.js.map +1 -1
  108. package/data/persistence/container-contents/documentMoveIntentPersistence.js +2 -2
  109. package/data/persistence/container-contents/documentMoveIntentPersistence.js.map +1 -1
  110. package/data/persistence/container-contents/documentPlacementIntentEnqueue.js +2 -2
  111. package/data/persistence/container-contents/documentPlacementIntentEnqueue.js.map +1 -1
  112. package/data/persistence/container-contents/documentPurgePlacement.js +1 -1
  113. package/data/persistence/container-contents/dormantContainerMetadata.js +1 -1
  114. package/data/persistence/container-contents/dormantMetadataSweep.js +1 -1
  115. package/data/persistence/container-contents/pendingContainerCreate.js +1 -1
  116. package/data/persistence/container-contents/supersededContainerBindings.js +1 -1
  117. package/data/persistence/containers/containerPersistence.js +1 -1
  118. package/data/persistence/containers/containerSyncWatermarkPersistence.js +1 -1
  119. package/data/persistence/containers/documentContainerProjectionPersistence.js +1 -1
  120. package/data/persistence/containers/documentPlacement.js +1 -1
  121. package/data/persistence/documents/containerDocumentTombstoneHoldsPersistence.js +1 -1
  122. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js +3 -3
  123. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js.map +1 -1
  124. package/data/persistence/documents/documentDiscoveryReset.js +1 -1
  125. package/data/persistence/documents/documentDiscoveryReset.js.map +1 -1
  126. package/data/persistence/documents/documentsPersistence.js +3 -3
  127. package/data/persistence/documents/documentsPersistence.js.map +1 -1
  128. package/data/persistence/documents/internal/attachmentStagingPersistence.js +1 -1
  129. package/data/persistence/documents/internal/containerDocumentTombstoneHolds.js +1 -1
  130. package/data/persistence/documents/internal/containerDocumentTombstones.js +1 -1
  131. package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js +2 -2
  132. package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js.map +1 -1
  133. package/data/persistence/documents/internal/discardDocument.js +3 -3
  134. package/data/persistence/documents/internal/discardDocument.js.map +1 -1
  135. package/data/persistence/documents/internal/documentDeletionPersistence.js +4 -4
  136. package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
  137. package/data/persistence/documents/internal/documentMutationPersistence.js +5 -5
  138. package/data/persistence/documents/internal/documentMutationPersistence.js.map +1 -1
  139. package/data/persistence/documents/internal/documentProjectionRows.js +1 -1
  140. package/data/persistence/documents/internal/documentPullContinuationPersistence.js +1 -1
  141. package/data/persistence/documents/internal/documentRows.js +2 -2
  142. package/data/persistence/documents/internal/documentRows.js.map +1 -1
  143. package/data/persistence/documents/internal/documentSummaryQueries.js +1 -1
  144. package/data/persistence/documents/internal/ensureDocumentsSchema.js +2 -2
  145. package/data/persistence/documents/internal/hydratedAttachmentPersistence.js +1 -1
  146. package/data/persistence/documents/internal/orphanSideRows.js +2 -2
  147. package/data/persistence/documents/internal/orphanSideRows.js.map +1 -1
  148. package/data/persistence/documents/internal/pendingCreateAdoption.js +1 -1
  149. package/data/persistence/documents/internal/rowQueryPersistence.js +2 -2
  150. package/data/persistence/documents/internal/syncQueuePersistence.js +3 -3
  151. package/data/persistence/documents/internal/syncQueuePersistence.js.map +1 -1
  152. package/data/persistence/documents/types.d.ts +3 -3
  153. package/data/persistence/documents/types.js.map +1 -1
  154. package/data/persistence/{documentPurgeCheckpointPersistence.d.ts → keyingCheckpoints/documentPurgeCheckpointPersistence.d.ts} +2 -2
  155. package/data/persistence/{documentPurgeCheckpointPersistence.js → keyingCheckpoints/documentPurgeCheckpointPersistence.js} +4 -4
  156. package/data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence.js.map +1 -0
  157. package/data/persistence/{keyingCheckpointAdvancePersistence.js → keyingCheckpoints/keyingCheckpointAdvancePersistence.js} +9 -9
  158. package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js.map +1 -0
  159. package/data/persistence/{keyingCheckpointEvidence.js → keyingCheckpoints/keyingCheckpointEvidence.js} +1 -1
  160. package/data/persistence/{keyingCheckpointPersistence.js → keyingCheckpoints/keyingCheckpointPersistence.js} +5 -5
  161. package/data/persistence/keyingCheckpoints/keyingCheckpointPersistence.js.map +1 -0
  162. package/data/persistence/{locallyAcknowledgedCheckpointPersistence.d.ts → keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.d.ts} +4 -4
  163. package/data/persistence/{locallyAcknowledgedCheckpointPersistence.js → keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js} +7 -7
  164. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js.map +1 -0
  165. package/data/persistence/{organizationReplacementCheckpointPersistence.js → keyingCheckpoints/organizationReplacementCheckpointPersistence.js} +6 -6
  166. package/data/persistence/keyingCheckpoints/organizationReplacementCheckpointPersistence.js.map +1 -0
  167. package/data/persistence/{principalAuthorizationCheckpoints.js → keyingCheckpoints/principalAuthorizationCheckpoints.js} +1 -1
  168. package/data/persistence/keyingCheckpoints/principalAuthorizationCheckpoints.js.map +1 -0
  169. package/data/persistence/organizationFounderPersistence.js +2 -2
  170. package/data/persistence/organizationFounderPersistence.js.map +1 -1
  171. package/data/persistence/organizations/organizationAccessRevocationPersistence.js +3 -3
  172. package/data/persistence/organizations/organizationAccessRevocationPersistence.js.map +1 -1
  173. package/data/persistence/organizations/organizationDataUsagePersistence.js +2 -2
  174. package/data/persistence/organizations/organizationDataUsagePersistence.js.map +1 -1
  175. package/data/persistence/organizations/organizationGroupNamePersistence.js +2 -2
  176. package/data/persistence/organizations/organizationGroupNamePersistence.js.map +1 -1
  177. package/data/persistence/organizations/organizationPresentationDenialPersistence.js +2 -2
  178. package/data/persistence/organizations/organizationPresentationDenialPersistence.js.map +1 -1
  179. package/data/persistence/organizations/organizationProfileDocumentPointers.js +2 -2
  180. package/data/persistence/organizations/organizationProfileDocumentPointers.js.map +1 -1
  181. package/data/persistence/organizations/organizationProvisioningAttemptPersistence.js +1 -1
  182. package/data/persistence/organizations/organizationProvisioningAttemptPersistence.js.map +1 -1
  183. package/data/persistence/organizations/organizationReadModelGrantPersistence.js +1 -1
  184. package/data/persistence/organizations/organizationReadModelGrantPersistence.js.map +1 -1
  185. package/data/persistence/organizations/organizationReadModelMemberLoad.js +1 -1
  186. package/data/persistence/organizations/organizationReadModelMemberLoad.js.map +1 -1
  187. package/data/persistence/organizations/organizationReadModelMembershipPersistence.js +1 -1
  188. package/data/persistence/organizations/organizationReadModelMembershipPersistence.js.map +1 -1
  189. package/data/persistence/organizations/organizationReadModelPersistence.js +3 -3
  190. package/data/persistence/organizations/organizationReadModelPersistence.js.map +1 -1
  191. package/data/persistence/organizations/organizationReadModelProjection.js +1 -1
  192. package/data/persistence/organizations/organizationReadModelProjection.js.map +1 -1
  193. package/data/persistence/organizations/organizationReadModelPurge.js +3 -3
  194. package/data/persistence/organizations/organizationReadModelPurge.js.map +1 -1
  195. package/data/persistence/principalCurrentAcknowledgementPersistence.d.ts +3 -3
  196. package/data/persistence/principalCurrentAcknowledgementPersistence.js +10 -10
  197. package/data/persistence/principalCurrentAcknowledgementPersistence.js.map +1 -1
  198. package/data/persistence/{principalHistoryEvidencePersistence.d.ts → principalHistory/principalHistoryEvidencePersistence.d.ts} +4 -4
  199. package/data/persistence/{principalHistoryEvidencePersistence.js → principalHistory/principalHistoryEvidencePersistence.js} +7 -7
  200. package/data/persistence/principalHistory/principalHistoryEvidencePersistence.js.map +1 -0
  201. package/data/persistence/{principalHistoryIncompleteRetention.js → principalHistory/principalHistoryIncompleteRetention.js} +1 -1
  202. package/data/persistence/principalHistory/principalHistoryIncompleteRetention.js.map +1 -0
  203. package/data/persistence/{principalHistoryNodeRetention.js → principalHistory/principalHistoryNodeRetention.js} +4 -4
  204. package/data/persistence/principalHistory/principalHistoryNodeRetention.js.map +1 -0
  205. package/data/persistence/{principalHistoryPrefixPersistence.d.ts → principalHistory/principalHistoryPrefixPersistence.d.ts} +2 -2
  206. package/data/persistence/{principalHistoryPrefixPersistence.js → principalHistory/principalHistoryPrefixPersistence.js} +6 -6
  207. package/data/persistence/principalHistory/principalHistoryPrefixPersistence.js.map +1 -0
  208. package/data/persistence/{principalHistoryRootOwnership.js → principalHistory/principalHistoryRootOwnership.js} +1 -1
  209. package/data/persistence/principalHistory/principalHistoryRootOwnership.js.map +1 -0
  210. package/data/persistence/{principalHistoryStagePersistence.d.ts → principalHistory/principalHistoryStagePersistence.d.ts} +2 -2
  211. package/data/persistence/{principalHistoryStagePersistence.js → principalHistory/principalHistoryStagePersistence.js} +6 -6
  212. package/data/persistence/principalHistory/principalHistoryStagePersistence.js.map +1 -0
  213. package/data/persistence/{principalHistoryStageRetention.js → principalHistory/principalHistoryStageRetention.js} +2 -2
  214. package/data/persistence/principalHistory/principalHistoryStageRetention.js.map +1 -0
  215. package/data/persistence/{principalHistoryUnpublishedRetention.js → principalHistory/principalHistoryUnpublishedRetention.js} +3 -3
  216. package/data/persistence/principalHistory/principalHistoryUnpublishedRetention.js.map +1 -0
  217. package/data/persistence/{principalGrantRetirementPersistence.d.ts → principalKeys/principalGrantRetirementPersistence.d.ts} +2 -2
  218. package/data/persistence/{principalGrantRetirementPersistence.js → principalKeys/principalGrantRetirementPersistence.js} +2 -2
  219. package/data/persistence/principalKeys/principalGrantRetirementPersistence.js.map +1 -0
  220. package/data/persistence/{principalKeyEnvelopeArchivePersistence.js → principalKeys/principalKeyEnvelopeArchivePersistence.js} +3 -3
  221. package/data/persistence/principalKeys/principalKeyEnvelopeArchivePersistence.js.map +1 -0
  222. package/data/persistence/{principalKeyEnvelopeCandidates.js → principalKeys/principalKeyEnvelopeCandidates.js} +9 -9
  223. package/data/persistence/principalKeys/principalKeyEnvelopeCandidates.js.map +1 -0
  224. package/data/persistence/principalMutationJournalPersistence.d.ts +1 -1
  225. package/data/persistence/principalMutationJournalPersistence.js +1 -1
  226. package/data/persistence/principalMutationJournalPersistence.js.map +1 -1
  227. package/data/persistence/{principalPolicyBundleIntegrity.js → principalPolicy/principalPolicyBundleIntegrity.js} +3 -3
  228. package/data/persistence/principalPolicy/principalPolicyBundleIntegrity.js.map +1 -0
  229. package/data/persistence/{principalPolicyCheckpointSelection.js → principalPolicy/principalPolicyCheckpointSelection.js} +2 -2
  230. package/data/persistence/principalPolicy/principalPolicyCheckpointSelection.js.map +1 -0
  231. package/data/persistence/{principalPolicyOrganizationPersistence.js → principalPolicy/principalPolicyOrganizationPersistence.js} +2 -2
  232. package/data/persistence/principalPolicy/principalPolicyOrganizationPersistence.js.map +1 -0
  233. package/data/persistence/{principalPolicyPersistence.js → principalPolicy/principalPolicyPersistence.js} +5 -5
  234. package/data/persistence/principalPolicy/principalPolicyPersistence.js.map +1 -0
  235. package/data/persistence/{principalPolicyReferenceCheckpoint.js → principalPolicy/principalPolicyReferenceCheckpoint.js} +3 -3
  236. package/data/persistence/principalPolicy/principalPolicyReferenceCheckpoint.js.map +1 -0
  237. package/data/persistence/{principalPolicyReferenceIndexPersistence.js → principalPolicy/principalPolicyReferenceIndexPersistence.js} +4 -4
  238. package/data/persistence/principalPolicy/principalPolicyReferenceIndexPersistence.js.map +1 -0
  239. package/data/persistence/{principalPolicyReferencePersistence.js → principalPolicy/principalPolicyReferencePersistence.js} +5 -5
  240. package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js.map +1 -0
  241. package/data/persistence/{verifiedPrincipalPolicyBundle.js → principalPolicy/verifiedPrincipalPolicyBundle.js} +2 -2
  242. package/data/persistence/principalPolicy/verifiedPrincipalPolicyBundle.js.map +1 -0
  243. package/data/persistence/{verifiedPrincipalPolicyCurrent.js → principalPolicy/verifiedPrincipalPolicyCurrent.js} +2 -2
  244. package/data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent.js.map +1 -0
  245. package/data/persistence/{verifiedPrincipalPolicyRetentionPersistence.js → principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js} +1 -1
  246. package/data/persistence/principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js.map +1 -0
  247. package/data/persistence/securityIncidentPersistence.js +1 -1
  248. package/data/persistence/securityIncidentPersistence.js.map +1 -1
  249. package/data/persistence/trustedUserIdentityPinPersistence.js +1 -1
  250. package/data/persistence/verifiedManifestBundlePersistence.d.ts +1 -1
  251. package/data/persistence/verifiedManifestBundlePersistence.js +4 -4
  252. package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
  253. package/data/principals/organizationGroupRoles.js +2 -2
  254. package/data/principals/organizationGroupRoles.js.map +1 -1
  255. package/data/principals/principalHistoryPrefixProtection.js.map +1 -1
  256. package/data/principals/principalHistoryStageProtection.js.map +1 -1
  257. package/data/principals/principalPolicyCrypto.js +1 -1
  258. package/data/principals/principalPolicyCrypto.js.map +1 -1
  259. package/data/sqlite/{documentHistoryPersistence.d.ts → documentPersistence/documentHistoryPersistence.d.ts} +1 -1
  260. package/data/sqlite/{documentHistoryPersistence.js → documentPersistence/documentHistoryPersistence.js} +5 -5
  261. package/data/sqlite/documentPersistence/documentHistoryPersistence.js.map +1 -0
  262. package/data/sqlite/{documentOrphanBlobReclaims.js → documentPersistence/documentOrphanBlobReclaims.js} +1 -1
  263. package/data/sqlite/documentPersistence/documentOrphanBlobReclaims.js.map +1 -0
  264. package/data/sqlite/{documentPendingUpdatePersistence.d.ts → documentPersistence/documentPendingUpdatePersistence.d.ts} +2 -2
  265. package/data/sqlite/{documentPendingUpdatePersistence.js → documentPersistence/documentPendingUpdatePersistence.js} +2 -2
  266. package/data/sqlite/documentPersistence/documentPendingUpdatePersistence.js.map +1 -0
  267. package/data/sqlite/{documentPersistenceTypes.d.ts → documentPersistence/documentPersistenceTypes.d.ts} +2 -2
  268. package/data/sqlite/documentPersistence/documentPersistenceTypes.js.map +1 -0
  269. package/data/sqlite/{documentRecordPersistence.d.ts → documentPersistence/documentRecordPersistence.d.ts} +1 -1
  270. package/data/sqlite/{documentRecordPersistence.js → documentPersistence/documentRecordPersistence.js} +4 -4
  271. package/data/sqlite/documentPersistence/documentRecordPersistence.js.map +1 -0
  272. package/data/sqlite/{documentSyncFailurePersistence.d.ts → documentPersistence/documentSyncFailurePersistence.d.ts} +2 -2
  273. package/data/sqlite/{documentSyncFailurePersistence.js → documentPersistence/documentSyncFailurePersistence.js} +3 -3
  274. package/data/sqlite/documentPersistence/documentSyncFailurePersistence.js.map +1 -0
  275. package/data/sqlite/{documentPersistence.d.ts → documentPersistence/index.d.ts} +2 -2
  276. package/data/sqlite/{documentPersistence.js → documentPersistence/index.js} +5 -5
  277. package/data/sqlite/documentPersistence/index.js.map +1 -0
  278. package/data/sqlite/{containerSchema.d.ts → schema/containerSchema.d.ts} +1 -1
  279. package/data/sqlite/{containerSchema.js → schema/containerSchema.js} +1 -1
  280. package/data/sqlite/schema/containerSchema.js.map +1 -0
  281. package/data/sqlite/{schema.d.ts → schema/index.d.ts} +1 -1
  282. package/data/sqlite/{schema.js → schema/index.js} +3 -3
  283. package/data/sqlite/schema/index.js.map +1 -0
  284. package/data/sqlite/{organizationDataUsageSchema.js → schema/organizationDataUsageSchema.js} +1 -1
  285. package/data/sqlite/schema/organizationDataUsageSchema.js.map +1 -0
  286. package/data/sqlite/{organizationProvisioningAttemptSchema.js → schema/organizationProvisioningAttemptSchema.js} +1 -1
  287. package/data/sqlite/schema/organizationProvisioningAttemptSchema.js.map +1 -0
  288. package/data/sqlite/{organizationReadModelTableRegistry.d.ts → schema/organizationReadModelTableRegistry.d.ts} +1 -1
  289. package/data/sqlite/{organizationReadModelTableRegistry.js → schema/organizationReadModelTableRegistry.js} +1 -1
  290. package/data/sqlite/schema/organizationReadModelTableRegistry.js.map +1 -0
  291. package/data/sqlite/{principalHistoryEvidenceSchema.d.ts → schema/principalHistoryEvidenceSchema.d.ts} +1 -1
  292. package/data/sqlite/{principalHistoryEvidenceSchema.js → schema/principalHistoryEvidenceSchema.js} +2 -2
  293. package/data/sqlite/schema/principalHistoryEvidenceSchema.js.map +1 -0
  294. package/data/sqlite/{principalHistoryNodeRetentionSchema.js → schema/principalHistoryNodeRetentionSchema.js} +1 -1
  295. package/data/sqlite/schema/principalHistoryNodeRetentionSchema.js.map +1 -0
  296. package/data/sqlite/{principalHistoryRetentionSchema.js → schema/principalHistoryRetentionSchema.js} +1 -1
  297. package/data/sqlite/{principalHistoryRetentionSchema.js.map → schema/principalHistoryRetentionSchema.js.map} +1 -1
  298. package/data/sqlite/{principalHistoryStageSchema.d.ts → schema/principalHistoryStageSchema.d.ts} +1 -1
  299. package/data/sqlite/{principalHistoryStageSchema.js → schema/principalHistoryStageSchema.js} +2 -2
  300. package/data/sqlite/schema/principalHistoryStageSchema.js.map +1 -0
  301. package/data/sqlite/{principalMutationJournalSchema.d.ts → schema/principalMutationJournalSchema.d.ts} +1 -1
  302. package/data/sqlite/{principalMutationJournalSchema.js → schema/principalMutationJournalSchema.js} +1 -1
  303. package/data/sqlite/{principalMutationJournalSchema.js.map → schema/principalMutationJournalSchema.js.map} +1 -1
  304. package/data/sqlite/{principalPolicySchema.js → schema/principalPolicySchema.js} +1 -1
  305. package/data/sqlite/schema/principalPolicySchema.js.map +1 -0
  306. package/data/sqlite/{securityIncidentSchema.d.ts → schema/securityIncidentSchema.d.ts} +1 -1
  307. package/data/sqlite/{securityIncidentSchema.js → schema/securityIncidentSchema.js} +1 -1
  308. package/data/sqlite/schema/securityIncidentSchema.js.map +1 -0
  309. package/data/sqlite/{verifiedManifestBundleSchema.d.ts → schema/verifiedManifestBundleSchema.d.ts} +1 -1
  310. package/data/sqlite/{verifiedManifestBundleSchema.js → schema/verifiedManifestBundleSchema.js} +1 -1
  311. package/data/sqlite/schema/verifiedManifestBundleSchema.js.map +1 -0
  312. package/data/sqlite/sqlitePersistenceRuntime.d.ts +1 -1
  313. package/data/sqlite/sqlitePersistenceRuntime.js +1 -1
  314. package/package.json +1 -1
  315. package/sqlite/index.d.ts +1 -1
  316. package/sqlite/index.js +1 -1
  317. package/stores/documents/documentStore/history/historyRebuild.js +1 -1
  318. package/stores/documents/documentStore/history/historyRebuild.js.map +1 -1
  319. package/stores/documents/documentStore/state.js.map +1 -1
  320. package/stores/documents/documentStore/sync/syncFinalize.js +1 -1
  321. package/stores/documents/documentStore/sync/syncFinalize.js.map +1 -1
  322. package/stores/documents/documentStore/sync/syncUpdateImport.js +1 -1
  323. package/stores/documents/documentStore/sync/syncUpdateImport.js.map +1 -1
  324. package/workflows/blobs/detach.js +1 -1
  325. package/workflows/blobs/hydration/decrypt.js +1 -1
  326. package/workflows/blobs/upload/index.js +1 -1
  327. package/workflows/blobs/verification/retainedAttachmentVerification.js +1 -1
  328. package/workflows/blobs/verification/writerProjection.js +1 -1
  329. package/workflows/container-contents/container-state/create/createWithMetadata.js +2 -2
  330. package/workflows/container-contents/container-state/create/createWithMetadata.js.map +1 -1
  331. package/workflows/container-contents/container-state/share/index.js +1 -1
  332. package/workflows/container-contents/documentLinks/index.js +1 -1
  333. package/workflows/container-contents/documentMove/documentMoveVanishedRefresh.js +1 -1
  334. package/workflows/container-contents/documentPriming/documentHydrationProbe.js +1 -1
  335. package/workflows/container-contents/documentPriming/index.js +1 -1
  336. package/workflows/container-contents/documentQueries/index.js +1 -1
  337. package/workflows/container-contents/documentQueries/sql.js +1 -1
  338. package/workflows/container-contents/info/blobInfo.js +1 -1
  339. package/workflows/container-contents/info/containerInfo.js +1 -1
  340. package/workflows/container-contents/info/documentInfo.js +1 -1
  341. package/workflows/container-contents/metadata/index.js +1 -1
  342. package/workflows/container-contents/metadata/index.js.map +1 -1
  343. package/workflows/container-contents/metadata/metadataEvents.d.ts +1 -1
  344. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js +2 -2
  345. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js.map +1 -1
  346. package/workflows/container-contents/metadata/metadataMutationPreparation.js +1 -1
  347. package/workflows/container-contents/metadata/metadataMutationPreparation.js.map +1 -1
  348. package/workflows/container-contents/metadata/metadataPullContinuationInvalidation.js +1 -1
  349. package/workflows/container-contents/metadata/metadataPullContinuationInvalidation.js.map +1 -1
  350. package/workflows/container-contents/metadata/metadataRemoteSync.d.ts +1 -1
  351. package/workflows/container-contents/metadata/metadataSyncErrors.js +1 -1
  352. package/workflows/container-contents/metadata/metadataSyncErrors.js.map +1 -1
  353. package/workflows/container-contents/metadata/metadataSyncSettlement.d.ts +1 -1
  354. package/workflows/container-contents/metadata/metadataSyncSettlement.js.map +1 -1
  355. package/workflows/container-contents/metadata/metadataTypes.d.ts +1 -1
  356. package/workflows/container-contents/metadata/metadataTypes.js.map +1 -1
  357. package/workflows/container-contents/pendingWrites/index.js +2 -2
  358. package/workflows/container-contents/pendingWrites/sources.js +1 -1
  359. package/workflows/container-contents/remoteHydration/destination/replacementBinding.js +1 -1
  360. package/workflows/container-contents/remoteHydration/destination/replacementBinding.js.map +1 -1
  361. package/workflows/container-contents/remoteHydration/reattachMetadata.js.map +1 -1
  362. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +2 -2
  363. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
  364. package/workflows/containers/child/create/index.js +2 -2
  365. package/workflows/containers/child/create/index.js.map +1 -1
  366. package/workflows/containers/child/move/index.js +1 -1
  367. package/workflows/containers/child/move/moveRotation.js +1 -1
  368. package/workflows/containers/child/move/moveRotation.js.map +1 -1
  369. package/workflows/containers/child/move/moveWraps.js +1 -1
  370. package/workflows/containers/child/move/moveWraps.js.map +1 -1
  371. package/workflows/containers/child/recite.js +2 -2
  372. package/workflows/containers/child/recite.js.map +1 -1
  373. package/workflows/containers/child/rotation/rotationContext.js +3 -3
  374. package/workflows/containers/child/rotation/rotationContext.js.map +1 -1
  375. package/workflows/containers/child/share/currentSharePrincipalPolicy.js +1 -1
  376. package/workflows/containers/child/share/currentSharePrincipalPolicy.js.map +1 -1
  377. package/workflows/containers/child/share/index.js +1 -1
  378. package/workflows/containers/child/share/index.js.map +1 -1
  379. package/workflows/containers/child/share/shareAncestorRepair.js +2 -2
  380. package/workflows/containers/child/share/shareAncestorRepair.js.map +1 -1
  381. package/workflows/containers/child/share/shareMaterialization.js +1 -1
  382. package/workflows/containers/child/share/sharePrincipalPolicy.js +5 -5
  383. package/workflows/containers/child/share/sharePrincipalPolicy.js.map +1 -1
  384. package/workflows/containers/index.d.ts +3 -3
  385. package/workflows/containers/index.js +2 -2
  386. package/workflows/containers/index.js.map +1 -1
  387. package/workflows/containers/writeRefusal.js +1 -1
  388. package/workflows/containers/writeRefusal.js.map +1 -1
  389. package/workflows/documents/create/createAdoption.js +1 -1
  390. package/workflows/documents/create/createResponse.js +2 -2
  391. package/workflows/documents/create/createResponse.js.map +1 -1
  392. package/workflows/documents/create/index.js +1 -1
  393. package/workflows/documents/documentMutationCommit.d.ts +1 -1
  394. package/workflows/documents/documentMutationPreparation.d.ts +1 -1
  395. package/workflows/documents/documentMutationPreparation.js +1 -1
  396. package/workflows/documents/documentMutationPreparation.js.map +1 -1
  397. package/workflows/documents/index.d.ts +5 -5
  398. package/workflows/documents/index.js +5 -5
  399. package/workflows/documents/index.js.map +1 -1
  400. package/workflows/documents/linkSet/index.js +2 -2
  401. package/workflows/documents/linkSet/index.js.map +1 -1
  402. package/workflows/documents/linkSet/linkSetAuthority.js +1 -1
  403. package/workflows/documents/linkSet/linkSetBlobRewraps.js +1 -1
  404. package/workflows/documents/linkSet/linkSetProjectionSeed.js +1 -1
  405. package/workflows/documents/linkSet/linkSetRemote.js +1 -1
  406. package/workflows/documents/linkSet/linkSetRemote.js.map +1 -1
  407. package/workflows/documents/purge/index.js +1 -1
  408. package/workflows/documents/sync/index.js +2 -2
  409. package/workflows/documents/sync/index.js.map +1 -1
  410. package/workflows/documents/sync/initialSync.js +1 -1
  411. package/workflows/documents/sync/readOnlyProjectionFailure.js +1 -1
  412. package/workflows/documents/sync/readOnlyProjectionFailure.js.map +1 -1
  413. package/workflows/documents/sync/readOnlySync.d.ts +3 -3
  414. package/workflows/documents/sync/readOnlySync.js +1 -1
  415. package/workflows/documents/sync/readOnlySync.js.map +1 -1
  416. package/workflows/documents/sync/reportDocumentSyncQuarantine.js.map +1 -1
  417. package/workflows/documents/sync/syncAttemptPlanning.js +2 -2
  418. package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -1
  419. package/workflows/documents/sync/syncAttemptState.d.ts +2 -2
  420. package/workflows/documents/sync/syncAttemptState.js.map +1 -1
  421. package/workflows/documents/sync/syncResponseResult.js +2 -2
  422. package/workflows/documents/sync/syncResponseResult.js.map +1 -1
  423. package/workflows/documents/syncFailures/index.js +1 -1
  424. package/workflows/documents/syncFailures/index.js.map +1 -1
  425. package/workflows/documents/syncFailures/syncAbandon.js.map +1 -1
  426. package/workflows/documents/syncFailures/syncFailureClassification.js +1 -1
  427. package/workflows/documents/syncFailures/syncFailureClassification.js.map +1 -1
  428. package/workflows/documents/syncPlan/syncContentKeys.d.ts +1 -1
  429. package/workflows/documents/syncPlan/syncContentKeys.js +3 -3
  430. package/workflows/documents/syncPlan/syncContentKeys.js.map +1 -1
  431. package/workflows/documents/syncPlan/syncPlanMaterial.js +2 -2
  432. package/workflows/documents/syncPlan/syncPlanMaterial.js.map +1 -1
  433. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js +2 -2
  434. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js.map +1 -1
  435. package/workflows/documents/syncRekeys/syncContainerRekeyPreparation.js +1 -1
  436. package/workflows/documents/syncRekeys/syncRecoveryRekey.d.ts +1 -1
  437. package/workflows/documents/syncRekeys/syncRecoveryRekey.js +1 -1
  438. package/workflows/organizations/currentOrganizationAuthority.js +2 -2
  439. package/workflows/organizations/currentOrganizationAuthority.js.map +1 -1
  440. package/workflows/organizations/groupMetadata/groupMetadataAccess.js +1 -1
  441. package/workflows/organizations/groupMetadata/groupMetadataAccess.js.map +1 -1
  442. package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js +1 -1
  443. package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js.map +1 -1
  444. package/workflows/organizations/groupNames/currentOrganizationGroupNames.js +1 -1
  445. package/workflows/organizations/groupNames/currentOrganizationGroupNames.js.map +1 -1
  446. package/workflows/organizations/groupNames/groupNameUniqueness.js +3 -3
  447. package/workflows/organizations/groupNames/groupNameUniqueness.js.map +1 -1
  448. package/workflows/organizations/groupNames/organizationGroupNamePolicies.js +2 -2
  449. package/workflows/organizations/groupNames/organizationGroupNamePolicies.js.map +1 -1
  450. package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js +1 -1
  451. package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js.map +1 -1
  452. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js +2 -2
  453. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js.map +1 -1
  454. package/workflows/organizations/groupPolicy/groupPolicyMutationEvidence.js +1 -1
  455. package/workflows/organizations/groupPolicy/groupPolicyMutationEvidence.js.map +1 -1
  456. package/workflows/organizations/groupPolicy/groupPolicyVerification.js +1 -1
  457. package/workflows/organizations/groupPolicy/groupPolicyVerification.js.map +1 -1
  458. package/workflows/organizations/groups/createCurrentOrganizationGroup.js +1 -1
  459. package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
  460. package/workflows/organizations/groups/deleteOrganizationGroup.js +1 -1
  461. package/workflows/organizations/groups/deleteOrganizationGroup.js.map +1 -1
  462. package/workflows/organizations/groups/organizationGroupDirectory.js +1 -1
  463. package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
  464. package/workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation.js +1 -1
  465. package/workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation.js.map +1 -1
  466. package/workflows/organizations/provisioning/organizationReplacementVerification.js +1 -1
  467. package/workflows/organizations/provisioning/organizationReplacementVerification.js.map +1 -1
  468. package/workflows/organizations/readModel/listLocalOrganizations.js +1 -1
  469. package/workflows/organizations/readModel/localReadModelDetails.js +1 -1
  470. package/workflows/organizations/readModel/localReadModelDetails.js.map +1 -1
  471. package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js +1 -1
  472. package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js.map +1 -1
  473. package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.d.ts +1 -1
  474. package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js +1 -1
  475. package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js.map +1 -1
  476. package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js +1 -1
  477. package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js.map +1 -1
  478. package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js +2 -2
  479. package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js.map +1 -1
  480. package/workflows/principals/externalAdminPolicy.js +2 -2
  481. package/workflows/principals/externalAdminPolicy.js.map +1 -1
  482. package/workflows/principals/historyRecovery/loadRecoveredPrincipalHistoryPage.js +2 -2
  483. package/workflows/principals/historyRecovery/loadRecoveredPrincipalHistoryPage.js.map +1 -1
  484. package/workflows/principals/historyRecovery/principalHistoryRecoveryPrefix.js +1 -1
  485. package/workflows/principals/historyRecovery/principalHistoryRecoveryPrefix.js.map +1 -1
  486. package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js +1 -1
  487. package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js.map +1 -1
  488. package/workflows/principals/historyRecovery/principalHistoryRecoveryStage.js +1 -1
  489. package/workflows/principals/historyRecovery/principalHistoryRecoveryStage.js.map +1 -1
  490. package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js +3 -3
  491. package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js.map +1 -1
  492. package/workflows/principals/policyCache/index.js +3 -3
  493. package/workflows/principals/policyCache/index.js.map +1 -1
  494. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js +1 -1
  495. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js.map +1 -1
  496. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js +3 -3
  497. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -1
  498. package/workflows/principals/publicHistory/publicPrincipalHistoryAuthority.js.map +1 -1
  499. package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js +2 -2
  500. package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js.map +1 -1
  501. package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js +3 -3
  502. package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js.map +1 -1
  503. package/workflows/principals/publicHistory/publicPrincipalHistoryTypes.d.ts +2 -2
  504. package/workflows/principals/publicHistory/publicPrincipalHistoryTypes.js.map +1 -1
  505. package/workflows/principals/publicHistory/publicProjectionPrincipal.js +1 -1
  506. package/workflows/principals/publicHistory/publicProjectionPrincipal.js.map +1 -1
  507. package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js +1 -1
  508. package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js.map +1 -1
  509. package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js +1 -1
  510. package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js.map +1 -1
  511. package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js +1 -1
  512. package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js.map +1 -1
  513. package/workflows/principals/recoveryOperation/principalRecoveryMemoValidity.js +1 -1
  514. package/workflows/principals/recoveryOperation/principalRecoveryMemoValidity.js.map +1 -1
  515. package/workflows/registration/persistRegistrationBootstrap.d.ts +2 -2
  516. package/workflows/registration/persistRegistrationBootstrap.js +2 -2
  517. package/workflows/registration/persistRegistrationBootstrap.js.map +1 -1
  518. package/workflows/registration/provisioningAcknowledgement.js +1 -1
  519. package/workflows/registration/provisioningAcknowledgement.js.map +1 -1
  520. package/workflows/registration/registrationPrincipalPolicyPersistence.js +1 -1
  521. package/workflows/registration/registrationPrincipalPolicyPersistence.js.map +1 -1
  522. package/workflows/sync/remoteReset.js +7 -7
  523. package/workflows/sync/remoteReset.js.map +1 -1
  524. package/workflows/sync/remoteResetAttachments.js +1 -1
  525. package/workflows/sync/remoteResetCursorScope.js +1 -1
  526. package/workflows/sync/remoteResetPlans.js +1 -1
  527. package/workflows/sync/remoteResetPrincipalScope.js +5 -5
  528. package/workflows/sync/remoteResetPrincipalScope.js.map +1 -1
  529. package/workflows/sync/remoteResetScope.js +1 -1
  530. package/data/documents/shared/containerKekPath.js.map +0 -1
  531. package/data/documents/shared/containerKekPathHistory.js.map +0 -1
  532. package/data/documents/shared/containerKekPathVerification.js.map +0 -1
  533. package/data/documents/shared/containerKekWrapping.js.map +0 -1
  534. package/data/documents/shared/documentSyncUpdateDecryption.js.map +0 -1
  535. package/data/documents/shared/documentSyncUpdateIsolation.js.map +0 -1
  536. package/data/documents/shared/keyringRebuild.js.map +0 -1
  537. package/data/documents/shared/mutationAcknowledgement.js.map +0 -1
  538. package/data/documents/shared/projection.js.map +0 -1
  539. package/data/documents/shared/projectionContentKeys.js.map +0 -1
  540. package/data/documents/shared/projectionTargets.js.map +0 -1
  541. package/data/documents/shared/syncPagination.js.map +0 -1
  542. package/data/documents/shared/syncResponseAuthorization.js.map +0 -1
  543. package/data/documents/shared/syncResponses.js.map +0 -1
  544. package/data/persistence/documentPurgeCheckpointPersistence.js.map +0 -1
  545. package/data/persistence/keyingCheckpointAdvancePersistence.js.map +0 -1
  546. package/data/persistence/keyingCheckpointPersistence.js.map +0 -1
  547. package/data/persistence/locallyAcknowledgedCheckpointPersistence.js.map +0 -1
  548. package/data/persistence/organizationReplacementCheckpointPersistence.js.map +0 -1
  549. package/data/persistence/principalAuthorizationCheckpoints.js.map +0 -1
  550. package/data/persistence/principalGrantRetirementPersistence.js.map +0 -1
  551. package/data/persistence/principalHistoryEvidencePersistence.js.map +0 -1
  552. package/data/persistence/principalHistoryIncompleteRetention.js.map +0 -1
  553. package/data/persistence/principalHistoryNodeRetention.js.map +0 -1
  554. package/data/persistence/principalHistoryPrefixPersistence.js.map +0 -1
  555. package/data/persistence/principalHistoryRootOwnership.js.map +0 -1
  556. package/data/persistence/principalHistoryStagePersistence.js.map +0 -1
  557. package/data/persistence/principalHistoryStageRetention.js.map +0 -1
  558. package/data/persistence/principalHistoryUnpublishedRetention.js.map +0 -1
  559. package/data/persistence/principalKeyEnvelopeArchivePersistence.js.map +0 -1
  560. package/data/persistence/principalKeyEnvelopeCandidates.js.map +0 -1
  561. package/data/persistence/principalPolicyBundleIntegrity.js.map +0 -1
  562. package/data/persistence/principalPolicyCheckpointSelection.js.map +0 -1
  563. package/data/persistence/principalPolicyOrganizationPersistence.js.map +0 -1
  564. package/data/persistence/principalPolicyPersistence.js.map +0 -1
  565. package/data/persistence/principalPolicyReferenceCheckpoint.js.map +0 -1
  566. package/data/persistence/principalPolicyReferenceIndexPersistence.js.map +0 -1
  567. package/data/persistence/principalPolicyReferencePersistence.js.map +0 -1
  568. package/data/persistence/verifiedPrincipalPolicyBundle.js.map +0 -1
  569. package/data/persistence/verifiedPrincipalPolicyCurrent.js.map +0 -1
  570. package/data/persistence/verifiedPrincipalPolicyRetentionPersistence.js.map +0 -1
  571. package/data/sqlite/containerSchema.js.map +0 -1
  572. package/data/sqlite/documentHistoryPersistence.js.map +0 -1
  573. package/data/sqlite/documentOrphanBlobReclaims.js.map +0 -1
  574. package/data/sqlite/documentPendingUpdatePersistence.js.map +0 -1
  575. package/data/sqlite/documentPersistence.js.map +0 -1
  576. package/data/sqlite/documentPersistenceTypes.js.map +0 -1
  577. package/data/sqlite/documentRecordPersistence.js.map +0 -1
  578. package/data/sqlite/documentSyncFailurePersistence.js.map +0 -1
  579. package/data/sqlite/organizationDataUsageSchema.js.map +0 -1
  580. package/data/sqlite/organizationProvisioningAttemptSchema.js.map +0 -1
  581. package/data/sqlite/organizationReadModelTableRegistry.js.map +0 -1
  582. package/data/sqlite/principalHistoryEvidenceSchema.js.map +0 -1
  583. package/data/sqlite/principalHistoryNodeRetentionSchema.js.map +0 -1
  584. package/data/sqlite/principalHistoryStageSchema.js.map +0 -1
  585. package/data/sqlite/principalPolicySchema.js.map +0 -1
  586. package/data/sqlite/schema.js.map +0 -1
  587. package/data/sqlite/securityIncidentSchema.js.map +0 -1
  588. package/data/sqlite/verifiedManifestBundleSchema.js.map +0 -1
  589. /package/data/documents/shared/{containerKekCurrency.js → containerKek/containerKekCurrency.js} +0 -0
  590. /package/data/documents/shared/{containerKekCurrency.js.map → containerKek/containerKekCurrency.js.map} +0 -0
  591. /package/data/documents/shared/{containerKekEntryVerification.js.map → containerKek/containerKekEntryVerification.js.map} +0 -0
  592. /package/data/documents/shared/{containerKekLogFetch.js.map → containerKek/containerKekLogFetch.js.map} +0 -0
  593. /package/data/documents/shared/{containerKekPath.d.ts → containerKek/containerKekPath.d.ts} +0 -0
  594. /package/data/documents/shared/{keyringLogWalk.js.map → containerKek/keyringLogWalk.js.map} +0 -0
  595. /package/data/documents/shared/{pullContinuation.d.ts → sync/pullContinuation.d.ts} +0 -0
  596. /package/data/documents/shared/{pullContinuation.js.map → sync/pullContinuation.js.map} +0 -0
  597. /package/data/documents/shared/{syncSubmitFailure.js → sync/syncSubmitFailure.js} +0 -0
  598. /package/data/documents/shared/{syncSubmitFailure.js.map → sync/syncSubmitFailure.js.map} +0 -0
  599. /package/data/persistence/{keyingCheckpointEvidence.js.map → keyingCheckpoints/keyingCheckpointEvidence.js.map} +0 -0
  600. /package/data/persistence/{storedPrincipalPolicyBundle.js → principalPolicy/storedPrincipalPolicyBundle.js} +0 -0
  601. /package/data/persistence/{storedPrincipalPolicyBundle.js.map → principalPolicy/storedPrincipalPolicyBundle.js.map} +0 -0
  602. /package/data/sqlite/{documentPersistenceTypes.js → documentPersistence/documentPersistenceTypes.js} +0 -0
  603. /package/data/sqlite/{containerDocumentTombstoneHoldSchema.d.ts → schema/containerDocumentTombstoneHoldSchema.d.ts} +0 -0
  604. /package/data/sqlite/{containerDocumentTombstoneHoldSchema.js → schema/containerDocumentTombstoneHoldSchema.js} +0 -0
  605. /package/data/sqlite/{containerDocumentTombstoneHoldSchema.js.map → schema/containerDocumentTombstoneHoldSchema.js.map} +0 -0
  606. /package/data/sqlite/{documentAttachmentSchema.d.ts → schema/documentAttachmentSchema.d.ts} +0 -0
  607. /package/data/sqlite/{documentAttachmentSchema.js → schema/documentAttachmentSchema.js} +0 -0
  608. /package/data/sqlite/{documentAttachmentSchema.js.map → schema/documentAttachmentSchema.js.map} +0 -0
  609. /package/data/sqlite/{documentDiscoveryEvidenceSchema.js → schema/documentDiscoveryEvidenceSchema.js} +0 -0
  610. /package/data/sqlite/{documentDiscoveryEvidenceSchema.js.map → schema/documentDiscoveryEvidenceSchema.js.map} +0 -0
  611. /package/data/sqlite/{documentPlacementIntentSchema.js → schema/documentPlacementIntentSchema.js} +0 -0
  612. /package/data/sqlite/{documentPlacementIntentSchema.js.map → schema/documentPlacementIntentSchema.js.map} +0 -0
  613. /package/data/sqlite/{localIntentSchema.d.ts → schema/localIntentSchema.d.ts} +0 -0
  614. /package/data/sqlite/{localIntentSchema.js → schema/localIntentSchema.js} +0 -0
  615. /package/data/sqlite/{localIntentSchema.js.map → schema/localIntentSchema.js.map} +0 -0
  616. /package/data/sqlite/{organizationFounderSchema.js → schema/organizationFounderSchema.js} +0 -0
  617. /package/data/sqlite/{organizationFounderSchema.js.map → schema/organizationFounderSchema.js.map} +0 -0
  618. /package/data/sqlite/{organizationReadModelSchema.js → schema/organizationReadModelSchema.js} +0 -0
  619. /package/data/sqlite/{organizationReadModelSchema.js.map → schema/organizationReadModelSchema.js.map} +0 -0
  620. /package/data/sqlite/{principalGrantRetirementSchema.js → schema/principalGrantRetirementSchema.js} +0 -0
  621. /package/data/sqlite/{principalGrantRetirementSchema.js.map → schema/principalGrantRetirementSchema.js.map} +0 -0
  622. /package/data/sqlite/{principalPolicySchema.d.ts → schema/principalPolicySchema.d.ts}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AAK,CAAC,sDAAsD,CAAC,CAAC;QAC1E,CAAC;QACD,KAAK,CAAC,IAAI,CACR,GAAG,CAAC,MAAM,sBAAsB,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,cAAc,EAAE,CAAC,CAAC,CAC1E,CAAC;IACJ,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,0BAA0B,CACxC,SAGG;IAEH,OAAO,SAAS,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,EAAE,EAAE;QAC1C,uCAAuC,CACrC,IAAI,EACJ,eAAe,CAAC,QAAQ,EAAE,iBAAiB,CAAC,CAC7C,CAAC;QACF,OAAO;YACL,UAAU,EAAE,IAAI,CAAC,UAAU;YAC3B,cAAc,EAAE,IAAI,CAAC,KAAK,CAAC,cAAc;YACzC,WAAW,EAAE,IAAI,CAAC,KAAK,CAAC,KAAK;YAC7B,eAAe,EAAE,IAAI,CAAC,YAAY;YAClC,kBAAkB,EAAE,IAAI,CAAC,KAAK,CAAC,kBAAkB;SAClD,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n ContainerCreateWithMetadataDocumentResponse,\n DocumentCreateResponse,\n OrganizationProvisioningResponse,\n} from \"@tearleads/validators/response\";\nimport { locallyAcknowledgedContainerMutationHead } from \"../../data/containers/shared/mutationAcknowledgement\";\nimport { assertDocumentCreateResponseMatchesPlan } from \"../../data/documents/shared/responses\";\nimport type { AuthoredDiscoveryHead } from \"../../data/persistence/documents/documentDiscoveryEvidencePersistence\";\nimport {\n type LocallyAcknowledgedAccessManifestHead,\n locallyAuthoredAccessManifestHead,\n} from \"../../data/persistence/locallyAcknowledgedCheckpointPersistence\";\n\ntype ContainerPlan = Parameters<\n typeof locallyAcknowledgedContainerMutationHead\n>[0][\"plan\"];\ntype DocumentPlan = Parameters<\n typeof assertDocumentCreateResponseMatchesPlan\n>[0];\n\ninterface ProvisioningContainerArtifact {\n readonly containerPlan: ContainerPlan;\n readonly metadataDocumentPlan: DocumentPlan;\n}\n\nfunction requireResponse<T>(value: T | undefined, label: string): T {\n if (!value) {\n throw new Error(`Organization provisioning response is missing ${label}`);\n }\n return value;\n}\n\nfunction assertId(\n actual: string | undefined,\n expected: string,\n label: string,\n): void {\n if (actual !== expected) {\n throw new Error(`Organization provisioning response ${label} mismatch`);\n }\n}\n\nfunction assertProvisioningIdentity(input: {\n expectedOrganizationId: string;\n expectedUserId: string;\n response: OrganizationProvisioningResponse;\n rootContainerPlan: ContainerPlan;\n rootMetadataDocumentPlan: DocumentPlan;\n}): void {\n const { response, rootContainerPlan, rootMetadataDocumentPlan } = input;\n if (\n response.userId !== input.expectedUserId ||\n response.organizationId !== input.expectedOrganizationId ||\n response.rootContainerId !== rootContainerPlan.containerId ||\n response.rootMetadataDocumentId !== rootMetadataDocumentPlan.documentId ||\n response.rootMetadataAccessEpoch !== rootContainerPlan.manifest.epoch ||\n response.rootMetadataAccessStateHash !== rootContainerPlan.manifestHash\n ) {\n throw new Error(\"Organization provisioning response identity mismatch\");\n }\n}\n\nasync function containerArtifactHeads(input: {\n artifact: ProvisioningContainerArtifact;\n response: ContainerCreateWithMetadataDocumentResponse;\n}): Promise<LocallyAcknowledgedAccessManifestHead[]> {\n assertDocumentCreateResponseMatchesPlan(\n input.artifact.metadataDocumentPlan,\n input.response.metadataDocument,\n );\n return [\n await locallyAcknowledgedContainerMutationHead({\n plan: input.artifact.containerPlan,\n response: input.response.container,\n }),\n locallyAuthoredAccessManifestHead(input.artifact.metadataDocumentPlan),\n ];\n}\n\nfunction documentHead(input: {\n plan: DocumentPlan;\n response: DocumentCreateResponse;\n}): LocallyAcknowledgedAccessManifestHead {\n assertDocumentCreateResponseMatchesPlan(input.plan, input.response);\n return locallyAuthoredAccessManifestHead(input.plan);\n}\n\nexport async function provisioningAcknowledgedAccessHeads(input: {\n expectedOrganizationId: string;\n expectedUserId: string;\n organizationMetadata: ProvisioningContainerArtifact;\n organizationProfileDocumentPlan: DocumentPlan;\n response: OrganizationProvisioningResponse;\n rootContainerPlan: ContainerPlan;\n rootMetadataDocumentPlan: DocumentPlan;\n rosterProfile: ProvisioningContainerArtifact;\n rosterProfileDocumentPlan: DocumentPlan;\n systemContainers: readonly ProvisioningContainerArtifact[];\n}): Promise<LocallyAcknowledgedAccessManifestHead[]> {\n assertProvisioningIdentity(input);\n const response = input.response;\n assertDocumentCreateResponseMatchesPlan(\n input.rootMetadataDocumentPlan,\n response.rootMetadataDocument,\n );\n const rosterContainer = requireResponse(\n response.rosterProfileContainer,\n \"roster profile container\",\n );\n const rosterDocument = requireResponse(\n response.rosterProfileDocument,\n \"roster profile document\",\n );\n const organizationContainer = requireResponse(\n response.organizationMetadataContainer,\n \"organization metadata container\",\n );\n const organizationDocument = requireResponse(\n response.organizationProfileDocument,\n \"organization profile document\",\n );\n assertId(\n response.rosterProfileContainerId,\n input.rosterProfile.containerPlan.containerId,\n \"roster profile container id\",\n );\n assertId(\n response.rosterProfileDocumentId,\n input.rosterProfileDocumentPlan.documentId,\n \"roster profile document id\",\n );\n assertId(\n response.organizationMetadataContainerId,\n input.organizationMetadata.containerPlan.containerId,\n \"organization metadata container id\",\n );\n assertId(\n response.organizationProfileDocumentId,\n input.organizationProfileDocumentPlan.documentId,\n \"organization profile document id\",\n );\n\n const systemResponses = response.systemContainers;\n if (systemResponses.length !== input.systemContainers.length) {\n throw new Error(\n \"Organization provisioning response system container count mismatch\",\n );\n }\n const heads: LocallyAcknowledgedAccessManifestHead[] = [\n locallyAuthoredAccessManifestHead(input.rootContainerPlan),\n locallyAuthoredAccessManifestHead(input.rootMetadataDocumentPlan),\n ...(await containerArtifactHeads({\n artifact: input.rosterProfile,\n response: rosterContainer,\n })),\n documentHead({\n plan: input.rosterProfileDocumentPlan,\n response: rosterDocument,\n }),\n ...(await containerArtifactHeads({\n artifact: input.organizationMetadata,\n response: organizationContainer,\n })),\n documentHead({\n plan: input.organizationProfileDocumentPlan,\n response: organizationDocument,\n }),\n ];\n for (const [index, artifact] of input.systemContainers.entries()) {\n const systemResponse = systemResponses[index];\n if (!systemResponse) {\n throw new Error(\"Organization provisioning system response is missing\");\n }\n heads.push(\n ...(await containerArtifactHeads({ artifact, response: systemResponse })),\n );\n }\n return heads;\n}\n\n/**\n * The signed heads of the seeded profile documents, for the discovery head\n * cache. Each plan was checked against its create acknowledgement by\n * {@link provisioningAcknowledgedAccessHeads}; checking again here keeps the\n * cache entry bound to exactly the head the server returned.\n */\nexport function provisioningDiscoveryHeads(\n documents: readonly {\n plan: DocumentPlan;\n response: DocumentCreateResponse | undefined;\n }[],\n): AuthoredDiscoveryHead[] {\n return documents.map(({ plan, response }) => {\n assertDocumentCreateResponseMatchesPlan(\n plan,\n requireResponse(response, \"seeded document\"),\n );\n return {\n documentId: plan.documentId,\n organizationId: plan.state.organizationId,\n accessEpoch: plan.state.epoch,\n accessStateHash: plan.manifestHash,\n linkedContainerIds: plan.state.linkedContainerIds,\n };\n });\n}\n"]}
1
+ {"version":3,"file":"provisioningAcknowledgement.js","sourceRoot":"","sources":["provisioningAcknowledgement.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,wCAAwC,EAAE,MAAM,sDAAsD,CAAC;AAChH,OAAO,EAAE,uCAAuC,EAAE,MAAM,uCAAuC,CAAC;AAEhG,OAAO,EAEL,iCAAiC,GAClC,MAAM,mFAAmF,CAAC;AAc3F,SAAS,eAAe,CAAI,KAAoB,EAAE,KAAa;IAC7D,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,MAAM,IAAI,KAAK,CAAC,iDAAiD,KAAK,EAAE,CAAC,CAAC;IAC5E,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,QAAQ,CACf,MAA0B,EAC1B,QAAgB,EAChB,KAAa;IAEb,IAAI,MAAM,KAAK,QAAQ,EAAE,CAAC;QACxB,MAAM,IAAI,KAAK,CAAC,sCAAsC,KAAK,WAAW,CAAC,CAAC;IAC1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,YAAY;YAClC,kBAAkB,EAAE,IAAI,CAAC,KAAK,CAAC,kBAAkB;SAClD,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n ContainerCreateWithMetadataDocumentResponse,\n DocumentCreateResponse,\n OrganizationProvisioningResponse,\n} from \"@tearleads/validators/response\";\nimport { locallyAcknowledgedContainerMutationHead } from \"../../data/containers/shared/mutationAcknowledgement\";\nimport { assertDocumentCreateResponseMatchesPlan } from \"../../data/documents/shared/responses\";\nimport type { AuthoredDiscoveryHead } from \"../../data/persistence/documents/documentDiscoveryEvidencePersistence\";\nimport {\n type LocallyAcknowledgedAccessManifestHead,\n locallyAuthoredAccessManifestHead,\n} from \"../../data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence\";\n\ntype ContainerPlan = Parameters<\n typeof locallyAcknowledgedContainerMutationHead\n>[0][\"plan\"];\ntype DocumentPlan = Parameters<\n typeof assertDocumentCreateResponseMatchesPlan\n>[0];\n\ninterface ProvisioningContainerArtifact {\n readonly containerPlan: ContainerPlan;\n readonly metadataDocumentPlan: DocumentPlan;\n}\n\nfunction requireResponse<T>(value: T | undefined, label: string): T {\n if (!value) {\n throw new Error(`Organization provisioning response is missing ${label}`);\n }\n return value;\n}\n\nfunction assertId(\n actual: string | undefined,\n expected: string,\n label: string,\n): void {\n if (actual !== expected) {\n throw new Error(`Organization provisioning response ${label} mismatch`);\n }\n}\n\nfunction assertProvisioningIdentity(input: {\n expectedOrganizationId: string;\n expectedUserId: string;\n response: OrganizationProvisioningResponse;\n rootContainerPlan: ContainerPlan;\n rootMetadataDocumentPlan: DocumentPlan;\n}): void {\n const { response, rootContainerPlan, rootMetadataDocumentPlan } = input;\n if (\n response.userId !== input.expectedUserId ||\n response.organizationId !== input.expectedOrganizationId ||\n response.rootContainerId !== rootContainerPlan.containerId ||\n response.rootMetadataDocumentId !== rootMetadataDocumentPlan.documentId ||\n response.rootMetadataAccessEpoch !== rootContainerPlan.manifest.epoch ||\n response.rootMetadataAccessStateHash !== rootContainerPlan.manifestHash\n ) {\n throw new Error(\"Organization provisioning response identity mismatch\");\n }\n}\n\nasync function containerArtifactHeads(input: {\n artifact: ProvisioningContainerArtifact;\n response: ContainerCreateWithMetadataDocumentResponse;\n}): Promise<LocallyAcknowledgedAccessManifestHead[]> {\n assertDocumentCreateResponseMatchesPlan(\n input.artifact.metadataDocumentPlan,\n input.response.metadataDocument,\n );\n return [\n await locallyAcknowledgedContainerMutationHead({\n plan: input.artifact.containerPlan,\n response: input.response.container,\n }),\n locallyAuthoredAccessManifestHead(input.artifact.metadataDocumentPlan),\n ];\n}\n\nfunction documentHead(input: {\n plan: DocumentPlan;\n response: DocumentCreateResponse;\n}): LocallyAcknowledgedAccessManifestHead {\n assertDocumentCreateResponseMatchesPlan(input.plan, input.response);\n return locallyAuthoredAccessManifestHead(input.plan);\n}\n\nexport async function provisioningAcknowledgedAccessHeads(input: {\n expectedOrganizationId: string;\n expectedUserId: string;\n organizationMetadata: ProvisioningContainerArtifact;\n organizationProfileDocumentPlan: DocumentPlan;\n response: OrganizationProvisioningResponse;\n rootContainerPlan: ContainerPlan;\n rootMetadataDocumentPlan: DocumentPlan;\n rosterProfile: ProvisioningContainerArtifact;\n rosterProfileDocumentPlan: DocumentPlan;\n systemContainers: readonly ProvisioningContainerArtifact[];\n}): Promise<LocallyAcknowledgedAccessManifestHead[]> {\n assertProvisioningIdentity(input);\n const response = input.response;\n assertDocumentCreateResponseMatchesPlan(\n input.rootMetadataDocumentPlan,\n response.rootMetadataDocument,\n );\n const rosterContainer = requireResponse(\n response.rosterProfileContainer,\n \"roster profile container\",\n );\n const rosterDocument = requireResponse(\n response.rosterProfileDocument,\n \"roster profile document\",\n );\n const organizationContainer = requireResponse(\n response.organizationMetadataContainer,\n \"organization metadata container\",\n );\n const organizationDocument = requireResponse(\n response.organizationProfileDocument,\n \"organization profile document\",\n );\n assertId(\n response.rosterProfileContainerId,\n input.rosterProfile.containerPlan.containerId,\n \"roster profile container id\",\n );\n assertId(\n response.rosterProfileDocumentId,\n input.rosterProfileDocumentPlan.documentId,\n \"roster profile document id\",\n );\n assertId(\n response.organizationMetadataContainerId,\n input.organizationMetadata.containerPlan.containerId,\n \"organization metadata container id\",\n );\n assertId(\n response.organizationProfileDocumentId,\n input.organizationProfileDocumentPlan.documentId,\n \"organization profile document id\",\n );\n\n const systemResponses = response.systemContainers;\n if (systemResponses.length !== input.systemContainers.length) {\n throw new Error(\n \"Organization provisioning response system container count mismatch\",\n );\n }\n const heads: LocallyAcknowledgedAccessManifestHead[] = [\n locallyAuthoredAccessManifestHead(input.rootContainerPlan),\n locallyAuthoredAccessManifestHead(input.rootMetadataDocumentPlan),\n ...(await containerArtifactHeads({\n artifact: input.rosterProfile,\n response: rosterContainer,\n })),\n documentHead({\n plan: input.rosterProfileDocumentPlan,\n response: rosterDocument,\n }),\n ...(await containerArtifactHeads({\n artifact: input.organizationMetadata,\n response: organizationContainer,\n })),\n documentHead({\n plan: input.organizationProfileDocumentPlan,\n response: organizationDocument,\n }),\n ];\n for (const [index, artifact] of input.systemContainers.entries()) {\n const systemResponse = systemResponses[index];\n if (!systemResponse) {\n throw new Error(\"Organization provisioning system response is missing\");\n }\n heads.push(\n ...(await containerArtifactHeads({ artifact, response: systemResponse })),\n );\n }\n return heads;\n}\n\n/**\n * The signed heads of the seeded profile documents, for the discovery head\n * cache. Each plan was checked against its create acknowledgement by\n * {@link provisioningAcknowledgedAccessHeads}; checking again here keeps the\n * cache entry bound to exactly the head the server returned.\n */\nexport function provisioningDiscoveryHeads(\n documents: readonly {\n plan: DocumentPlan;\n response: DocumentCreateResponse | undefined;\n }[],\n): AuthoredDiscoveryHead[] {\n return documents.map(({ plan, response }) => {\n assertDocumentCreateResponseMatchesPlan(\n plan,\n requireResponse(response, \"seeded document\"),\n );\n return {\n documentId: plan.documentId,\n organizationId: plan.state.organizationId,\n accessEpoch: plan.state.epoch,\n accessStateHash: plan.manifestHash,\n linkedContainerIds: plan.state.linkedContainerIds,\n };\n });\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { computePrincipalStateHash, makeVerifiedPrincipalPolicy, } from "../../internal/crypto/index.js";
2
- import { persistLocallyAcknowledgedPrincipalPolicyBundles } from "../../data/persistence/locallyAcknowledgedCheckpointPersistence.js";
2
+ import { persistLocallyAcknowledgedPrincipalPolicyBundles } from "../../data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js";
3
3
  async function principalPolicyBundleFromInitialRequest(principalType, principalId, policy) {
4
4
  const createdAt = new Date().toISOString();
5
5
  const stateHash = await computePrincipalStateHash(policy.state);
@@ -1 +1 @@
1
- {"version":3,"file":"registrationPrincipalPolicyPersistence.js","sourceRoot":"","sources":["registrationPrincipalPolicyPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,2BAA2B,GAE5B,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EAAE,gDAAgD,EAAE,MAAM,iEAAiE,CAAC;AAGnI,KAAK,UAAU,uCAAuC,CACpD,aAAuC,EACvC,WAAmB,EACnB,MAAiC;IAEjC,MAAM,SAAS,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IAC3C,MAAM,SAAS,GAAG,MAAM,yBAAyB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAEhE,OAAO;QACL,YAAY,EAAE,EAAE,GAAG,MAAM,CAAC,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE;QACvD,cAAc,EAAE;YACd,aAAa;YACb,WAAW;YACX,SAAS;YACT,GAAG,MAAM,CAAC,gBAAgB;YAC1B,SAAS;SACV;QACD,aAAa,EAAE,MAAM,CAAC,MAAM;QAC5B,iBAAiB,EAAE,MAAM,CAAC,UAAU;QACpC,sBAAsB,EAAE;YACtB,aAAa;YACb,WAAW;YACX,SAAS;YACT,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,QAAQ;YAC5B,SAAS,EAAE,MAAM,CAAC,eAAe;SAClC;Q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AW;YAC5C,OAAO,EAAE,MAAM,CAAC,YAAY,CAAC,OAAO;YACpC,SAAS,EAAE,MAAM,CAAC,YAAY,CAAC,SAAS;SACzC;KACF,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,oCAAoC,CAAC,KAK1D;IACC,MAAM,gDAAgD,CAAC;QACrD,OAAO,EAAE,CAAC,KAAK,CAAC,UAAU,EAAE,KAAK,CAAC,WAAW,EAAE,KAAK,CAAC,YAAY,CAAC,CAAC,GAAG,CACpE,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;YACX,MAAM;YACN,MAAM,EAAE,iCAAiC,CAAC,MAAM,CAAC;SAClD,CAAC,CACH;QACD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,cAAc,EAAE,KAAK,CAAC,YAAY,CAAC,YAAY,CAAC,WAAW;QAC3D,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;KACpC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n computePrincipalStateHash,\n makeVerifiedPrincipalPolicy,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n CreateOrganizationGroupRequest,\n PutPrincipalPolicyRequest,\n RegistrationRequest,\n} from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { persistLocallyAcknowledgedPrincipalPolicyBundles } from \"../../data/persistence/locallyAcknowledgedCheckpointPersistence\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\n\nasync function principalPolicyBundleFromInitialRequest(\n principalType: \"group\" | \"organization\",\n principalId: string,\n policy: PutPrincipalPolicyRequest,\n): Promise<PrincipalPolicyBundleResponse> {\n const createdAt = new Date().toISOString();\n const stateHash = await computePrincipalStateHash(policy.state);\n\n return {\n currentState: { ...policy.state, stateHash, createdAt },\n currentPayload: {\n principalType,\n principalId,\n stateHash,\n ...policy.encryptedPayload,\n createdAt,\n },\n currentGrants: policy.grants,\n currentProjection: policy.projection,\n currentMemberEnvelopes: {\n principalType,\n principalId,\n stateHash,\n epoch: policy.state.keyEpoch,\n envelopes: policy.memberEnvelopes,\n },\n previousStates: [],\n };\n}\n\nexport async function principalPolicyBundleFromInitialGroupRequest(\n input: CreateOrganizationGroupRequest,\n): Promise<PrincipalPolicyBundleResponse> {\n return principalPolicyBundleFromInitialRequest(\n \"group\",\n input.groupId,\n input.initialGroupPolicy,\n );\n}\n\nexport async function principalPolicyBundleFromInitialOrganizationRequest(\n input: RegistrationRequest[\"initialOrganizationPolicy\"],\n): Promise<PrincipalPolicyBundleResponse> {\n return principalPolicyBundleFromInitialRequest(\n \"organization\",\n input.state.principalId,\n input,\n );\n}\n\nexport async function verifiedPrincipalPolicyFromInitialGroupRequest(\n input: CreateOrganizationGroupRequest,\n): Promise<VerifiedPrincipalPolicy> {\n const bundle = await principalPolicyBundleFromInitialGroupRequest(input);\n\n return verifiedPrincipalPolicyFromBundle(bundle);\n}\n\nfunction verifiedPrincipalPolicyFromBundle(\n bundle: PrincipalPolicyBundleResponse,\n): VerifiedPrincipalPolicy {\n return makeVerifiedPrincipalPolicy({\n principalType: bundle.currentState.principalType,\n principalId: bundle.currentState.principalId,\n version: bundle.currentState.version,\n keyEpoch: bundle.currentState.keyEpoch,\n stateHash: bundle.currentState.stateHash,\n state: bundle.currentState,\n projection: bundle.currentProjection,\n grants: bundle.currentGrants,\n history: [\n ...bundle.previousStates,\n {\n state: bundle.currentState,\n projection: bundle.currentProjection,\n grants: bundle.currentGrants,\n },\n ],\n checkpoint: {\n principalType: bundle.currentState.principalType,\n principalId: bundle.currentState.principalId,\n version: bundle.currentState.version,\n stateHash: bundle.currentState.stateHash,\n },\n });\n}\n\nexport async function persistRegistrationPrincipalPolicies(input: {\n readonly adminGroup: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly memberGroup: PrincipalPolicyBundleResponse;\n readonly organization: PrincipalPolicyBundleResponse;\n}): Promise<void> {\n await persistLocallyAcknowledgedPrincipalPolicyBundles({\n entries: [input.adminGroup, input.memberGroup, input.organization].map(\n (bundle) => ({\n bundle,\n policy: verifiedPrincipalPolicyFromBundle(bundle),\n }),\n ),\n execSql: input.execSql,\n organizationId: input.organization.currentState.principalId,\n updatedAt: new Date().toISOString(),\n });\n}\n"]}
1
+ {"version":3,"file":"registrationPrincipalPolicyPersistence.js","sourceRoot":"","sources":["registrationPrincipalPolicyPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,2BAA2B,GAE5B,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EAAE,gDAAgD,EAAE,MAAM,mFAAmF,CAAC;AAGrJ,KAAK,UAAU,uCAAuC,CACpD,aAAuC,EACvC,WAAmB,EACnB,MAAiC;IAEjC,MAAM,SAAS,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IAC3C,MAAM,SAAS,GAAG,MAAM,yBAAyB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAEhE,OAAO;QACL,YAAY,EAAE,EAAE,GAAG,MAAM,CAAC,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE;QACvD,cAAc,EAAE;YACd,aAAa;YACb,WAAW;YACX,SAAS;YACT,GAAG,MAAM,CAAC,gBAAgB;YAC1B,SAAS;SACV;QACD,aAAa,EAAE,MAAM,CAAC,MAAM;QAC5B,iBAAiB,EAAE,MAAM,CAAC,UAAU;QACpC,sBAAsB,EAAE;YACtB,aAAa;YACb,WAAW;YACX,SAAS;YACT,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,QAAQ;YAC5B,SAAS,EAAE,MAAM,CAAC,eAAe;SAClC;QACD,cAAc,EAAE,EAAE;KACnB,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,4CAA4C,CAChE,KAAqC;IAErC,OAAO,uCAAuC,CAC5C,OAAO,EACP,KAAK,CAAC,OAAO,EACb,KAAK,CAAC,kBAAkB,CACzB,CAAC;AACJ,CAAC;AA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CAAC;QACrD,OAAO,EAAE,CAAC,KAAK,CAAC,UAAU,EAAE,KAAK,CAAC,WAAW,EAAE,KAAK,CAAC,YAAY,CAAC,CAAC,GAAG,CACpE,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;YACX,MAAM;YACN,MAAM,EAAE,iCAAiC,CAAC,MAAM,CAAC;SAClD,CAAC,CACH;QACD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,cAAc,EAAE,KAAK,CAAC,YAAY,CAAC,YAAY,CAAC,WAAW;QAC3D,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;KACpC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n computePrincipalStateHash,\n makeVerifiedPrincipalPolicy,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n CreateOrganizationGroupRequest,\n PutPrincipalPolicyRequest,\n RegistrationRequest,\n} from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { persistLocallyAcknowledgedPrincipalPolicyBundles } from \"../../data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\n\nasync function principalPolicyBundleFromInitialRequest(\n principalType: \"group\" | \"organization\",\n principalId: string,\n policy: PutPrincipalPolicyRequest,\n): Promise<PrincipalPolicyBundleResponse> {\n const createdAt = new Date().toISOString();\n const stateHash = await computePrincipalStateHash(policy.state);\n\n return {\n currentState: { ...policy.state, stateHash, createdAt },\n currentPayload: {\n principalType,\n principalId,\n stateHash,\n ...policy.encryptedPayload,\n createdAt,\n },\n currentGrants: policy.grants,\n currentProjection: policy.projection,\n currentMemberEnvelopes: {\n principalType,\n principalId,\n stateHash,\n epoch: policy.state.keyEpoch,\n envelopes: policy.memberEnvelopes,\n },\n previousStates: [],\n };\n}\n\nexport async function principalPolicyBundleFromInitialGroupRequest(\n input: CreateOrganizationGroupRequest,\n): Promise<PrincipalPolicyBundleResponse> {\n return principalPolicyBundleFromInitialRequest(\n \"group\",\n input.groupId,\n input.initialGroupPolicy,\n );\n}\n\nexport async function principalPolicyBundleFromInitialOrganizationRequest(\n input: RegistrationRequest[\"initialOrganizationPolicy\"],\n): Promise<PrincipalPolicyBundleResponse> {\n return principalPolicyBundleFromInitialRequest(\n \"organization\",\n input.state.principalId,\n input,\n );\n}\n\nexport async function verifiedPrincipalPolicyFromInitialGroupRequest(\n input: CreateOrganizationGroupRequest,\n): Promise<VerifiedPrincipalPolicy> {\n const bundle = await principalPolicyBundleFromInitialGroupRequest(input);\n\n return verifiedPrincipalPolicyFromBundle(bundle);\n}\n\nfunction verifiedPrincipalPolicyFromBundle(\n bundle: PrincipalPolicyBundleResponse,\n): VerifiedPrincipalPolicy {\n return makeVerifiedPrincipalPolicy({\n principalType: bundle.currentState.principalType,\n principalId: bundle.currentState.principalId,\n version: bundle.currentState.version,\n keyEpoch: bundle.currentState.keyEpoch,\n stateHash: bundle.currentState.stateHash,\n state: bundle.currentState,\n projection: bundle.currentProjection,\n grants: bundle.currentGrants,\n history: [\n ...bundle.previousStates,\n {\n state: bundle.currentState,\n projection: bundle.currentProjection,\n grants: bundle.currentGrants,\n },\n ],\n checkpoint: {\n principalType: bundle.currentState.principalType,\n principalId: bundle.currentState.principalId,\n version: bundle.currentState.version,\n stateHash: bundle.currentState.stateHash,\n },\n });\n}\n\nexport async function persistRegistrationPrincipalPolicies(input: {\n readonly adminGroup: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly memberGroup: PrincipalPolicyBundleResponse;\n readonly organization: PrincipalPolicyBundleResponse;\n}): Promise<void> {\n await persistLocallyAcknowledgedPrincipalPolicyBundles({\n entries: [input.adminGroup, input.memberGroup, input.organization].map(\n (bundle) => ({\n bundle,\n policy: verifiedPrincipalPolicyFromBundle(bundle),\n }),\n ),\n execSql: input.execSql,\n organizationId: input.organization.currentState.principalId,\n updatedAt: new Date().toISOString(),\n });\n}\n"]}
@@ -2,15 +2,15 @@ import { and, eq, inArray, or } from "drizzle-orm";
2
2
  import { recordSupersededContainerBindingsInTransaction } from "../../data/persistence/container-contents/supersededContainerBindings.js";
3
3
  import { deleteDocumentPlacementRowsByContainerIds, deleteDocumentPlacementRowsByDocumentIds, } from "../../data/persistence/containers/documentContainerProjectionPersistence.js";
4
4
  import { clearDocumentDiscoveryEvidenceOnRemoteReset } from "../../data/persistence/documents/documentDiscoveryReset.js";
5
- import { queuedUpdateRow, unqueueDocumentScopesInTransaction, } from "../../data/sqlite/documentPendingUpdatePersistence.js";
6
- import { documentIntentLinkTargets } from "../../data/sqlite/documentPlacementIntentSchema.js";
7
- import { CLEARED_DOCUMENT_SYNC_FAILURE } from "../../data/sqlite/documentSyncFailurePersistence.js";
8
- import { organizationDataUsageSnapshots } from "../../data/sqlite/organizationDataUsageSchema.js";
9
- import { organizationPresentationDenials, organizationReadModelContainerGrants, organizationReadModelDirectoryUsers, organizationReadModelGroupMembers, organizationReadModelGroups, organizationReadModelRequesters, organizationReadModelState, } from "../../data/sqlite/organizationReadModelSchema.js";
10
- import { clientSqlTables, containerHydrationTombstones, containers, documentAttachmentBlobProjection, documentHistoryUpdates, documentPendingAttachments, documentProjection, documents, dormantContainerMetadata, dormantMetadataSweepRequests, inContainerIntentLanes, inLocalIntentLane, LOCAL_INTENT_LANES, localIntents, } from "../../data/sqlite/schema.js";
5
+ import { queuedUpdateRow, unqueueDocumentScopesInTransaction, } from "../../data/sqlite/documentPersistence/documentPendingUpdatePersistence.js";
6
+ import { CLEARED_DOCUMENT_SYNC_FAILURE } from "../../data/sqlite/documentPersistence/documentSyncFailurePersistence.js";
7
+ import { clientSqlTables, containerHydrationTombstones, containers, documentAttachmentBlobProjection, documentHistoryUpdates, documentPendingAttachments, documentProjection, documents, dormantContainerMetadata, dormantMetadataSweepRequests, inContainerIntentLanes, inLocalIntentLane, LOCAL_INTENT_LANES, localIntents, } from "../../data/sqlite/schema/index.js";
8
+ import { documentIntentLinkTargets } from "../../data/sqlite/schema/documentPlacementIntentSchema.js";
9
+ import { organizationDataUsageSnapshots } from "../../data/sqlite/schema/organizationDataUsageSchema.js";
10
+ import { organizationPresentationDenials, organizationReadModelContainerGrants, organizationReadModelDirectoryUsers, organizationReadModelGroupMembers, organizationReadModelGroups, organizationReadModelRequesters, organizationReadModelState, } from "../../data/sqlite/schema/organizationReadModelSchema.js";
11
+ import { verifiedAccessManifestBundles } from "../../data/sqlite/schema/verifiedManifestBundleSchema.js";
11
12
  import { getClientSQLitePersistenceRuntime, } from "../../data/sqlite/sqlitePersistenceRuntime.js";
12
13
  import { ensureSqlTables } from "../../data/sqlite/sqlTableSchema.js";
13
- import { verifiedAccessManifestBundles } from "../../data/sqlite/verifiedManifestBundleSchema.js";
14
14
  import { runOrganizationPresentationReset } from "../organizations/readModel/organizationPresentationAccessState.js";
15
15
  import { clearResetPendingAttachments } from "./remoteResetAttachments.js";
16
16
  import { remoteResetBatches } from "./remoteResetBatches.js";
@@ -1 +1 @@
1
- {"version":3,"file":"remoteReset.js","sourceRoot":"","sources":["remoteReset.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,8CAA8C,EAAE,MAAM,uEAAuE,CAAC;AACvI,OAAO,EACL,yCAAyC,EACzC,wCAAwC,GACzC,MAAM,0EAA0E,CAAC;AAClF,OAAO,EAAE,2CAA2C,EAAE,MAAM,yDAAyD,CAAC;AACtH,OAAO,EACL,eAAe,EACf,kCAAkC,GACnC,MAAM,oDAAoD,CAAC;AAC5D,OAAO,EAAE,yBAAyB,EAAE,MAAM,iDAAiD,CAAC;AAC5F,OAAO,EAAE,6BAA6B,EAAE,MAAM,kDAAkD,CAAC;AACjG,OAAO,EAAE,8BAA8B,EAAE,MAAM,+CAA+C,CAAC;AAC/F,OAAO,EACL,+BAA+B,EAC/B,oCAAoC,EACpC,mCAAmC,EACnC,iCAAi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uB,EACvB,SAAuC;IAEvC,OAAO,gCAAgC,CACrC,OAAO,EACP,KAAK,CAAC,cAAc,EACpB,KAAK,IAAI,EAAE;QACT,MAAM,eAAe,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC;QAChD,MAAM,OAAO,GAAG,iCAAiC,CAAC,OAAO,CAAC,CAAC;QAC3D,MAAM,kBAAkB,GAAG,KAAK,EAAE,EAAgC,EAAE,EAAE;YACpE,IAAI,SAAS,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC;gBAC9B,MAAM,IAAI,KAAK,CACb,qDAAqD,CACtD,CAAC;YACJ,CAAC;YACD,MAAM,QAAQ,GAAG,MAAM,2BAA2B,CAChD,EAAE,EACF,KAAK,CAAC,cAAc,CACrB,CAAC;YACF,MAAM,KAAK,GAAG,MAAM,eAAe,CAAC,EAAE,EAAE,QAAQ,CAAC,YAAY,CAAC,CAAC;YAC/D,OAAO,iCAAiC,CAAC;gBACvC,KAAK;gBACL,KAAK;gBACL,QAAQ;gBACR,EAAE;aACH,CAAC,CAAC;QACL,CAAC,CAAC;QACF,IAAI,CAAC,SAAS,EAAE,CAAC;YACf,OAAO,OAAO,CAAC,WAAW,CAAC,kBAAkB,CAAC,CAAC;QACjD,CAAC;QACD,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,kBAAkB,CAC9C,kBAAkB,EAClB,SAAS,CACV,CAAC;QACF,IAAI,CAAC,OAAO,CAAC,SAAS,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC;YAC1C,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;QACzE,CAAC;QACD,OAAO,OAAO,CAAC,MAAM,CAAC;IACxB,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { and, eq, inArray, or } from \"drizzle-orm\";\nimport { recordSupersededContainerBindingsInTransaction } from \"../../data/persistence/container-contents/supersededContainerBindings\";\nimport {\n deleteDocumentPlacementRowsByContainerIds,\n deleteDocumentPlacementRowsByDocumentIds,\n} from \"../../data/persistence/containers/documentContainerProjectionPersistence\";\nimport { clearDocumentDiscoveryEvidenceOnRemoteReset } from \"../../data/persistence/documents/documentDiscoveryReset\";\nimport {\n queuedUpdateRow,\n unqueueDocumentScopesInTransaction,\n} from \"../../data/sqlite/documentPendingUpdatePersistence\";\nimport { documentIntentLinkTargets } from \"../../data/sqlite/documentPlacementIntentSchema\";\nimport { CLEARED_DOCUMENT_SYNC_FAILURE } from \"../../data/sqlite/documentSyncFailurePersistence\";\nimport { organizationDataUsageSnapshots } from \"../../data/sqlite/organizationDataUsageSchema\";\nimport {\n organizationPresentationDenials,\n organizationReadModelContainerGrants,\n organizationReadModelDirectoryUsers,\n organizationReadModelGroupMembers,\n organizationReadModelGroups,\n organizationReadModelRequesters,\n organizationReadModelState,\n} from \"../../data/sqlite/organizationReadModelSchema\";\nimport {\n clientSqlTables,\n containerHydrationTombstones,\n containers,\n documentAttachmentBlobProjection,\n documentHistoryUpdates,\n documentPendingAttachments,\n documentProjection,\n documents,\n dormantContainerMetadata,\n dormantMetadataSweepRequests,\n inContainerIntentLanes,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../data/sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../data/sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { ensureSqlTables } from \"../../data/sqlite/sqlTableSchema\";\nimport { verifiedAccessManifestBundles } from \"../../data/sqlite/verifiedManifestBundleSchema\";\nimport { runOrganizationPresentationReset } from \"../organizations/readModel/organizationPresentationAccessState\";\nimport { clearResetPendingAttachments } from \"./remoteResetAttachments\";\nimport { remoteResetBatches } from \"./remoteResetBatches\";\nimport { clearRemoteResetSyncCursors } from \"./remoteResetCursorScope\";\nimport {\n buildResetPlans,\n type ResetAttachmentUpload,\n type ResetDocumentUpdate,\n} from \"./remoteResetPlans\";\nimport { clearRemoteResetPrincipalRows } from \"./remoteResetPrincipalScope\";\nimport {\n type RemoteResetInput,\n type RemoteSyncStateSnapshot,\n readRemoteSyncStateSnapshot,\n} from \"./remoteResetScope\";\n\nexport type {\n RemoteResetInput,\n RemoteResetReplacement,\n} from \"./remoteResetScope\";\n\nconst CONTAINER_CREATE_INTENT_TYPE = \"container.create\";\n\nexport interface ClearRemoteSyncStateResult {\n readonly clearedContainerCreateIntentCount: number;\n readonly clearedContainerMoveIntentCount: number;\n readonly clearedDocumentMoveIntentCount: number;\n readonly clearedPrincipalPolicyCount: number;\n readonly clearedSyncCursorCount: number;\n readonly queuedAttachmentUploadCount: number;\n readonly queuedContainerCreateCount: number;\n readonly queuedDocumentUpdateCount: number;\n readonly resetContainerCount: number;\n readonly resetDocumentCount: number;\n}\n\nasync function clearOrganizationPresentationRows(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<void> {\n for (const table of [\n organizationDataUsageSnapshots,\n organizationReadModelContainerGrants,\n organizationReadModelGroupMembers,\n organizationReadModelDirectoryUsers,\n organizationReadModelGroups,\n organizationReadModelRequesters,\n organizationReadModelState,\n organizationPresentationDenials,\n ] as const) {\n await tx\n .delete(table)\n .where(eq(table.organizationId, organizationId))\n .run();\n }\n}\n\ninterface ScopedRemoteRowsInput {\n attachmentUploads: readonly ResetAttachmentUpload[];\n organizationId: string;\n snapshot: RemoteSyncStateSnapshot;\n tx: ClientSQLiteTransactionScope;\n}\n\nasync function clearScopedContainerRows(\n input: ScopedRemoteRowsInput,\n): Promise<void> {\n for (const containerBatch of remoteResetBatches(\n input.snapshot.containerIds,\n )) {\n await deleteDocumentPlacementRowsByContainerIds(input.tx, containerBatch);\n await input.tx\n .delete(localIntents)\n .where(\n and(\n inContainerIntentLanes(),\n inArray(localIntents.subjectId, containerBatch),\n ),\n )\n .run();\n await input.tx\n .delete(containerHydrationTombstones)\n .where(inArray(containerHydrationTombstones.containerId, containerBatch))\n .run();\n }\n}\n\nasync function clearScopedDocumentRows(\n input: ScopedRemoteRowsInput,\n): Promise<void> {\n const { snapshot, tx } = input;\n for (const documentIdBatch of remoteResetBatches(snapshot.oldDocumentIds)) {\n await deleteDocumentPlacementRowsByDocumentIds(tx, documentIdBatch);\n }\n await clearResetPendingAttachments({\n attachmentUploads: input.attachmentUploads,\n documentLocalIds: snapshot.documentLocalIds,\n tx,\n });\n for (const localIdBatch of remoteResetBatches(snapshot.documentLocalIds)) {\n const placementIntents = and(\n inLocalIntentLane(LOCAL_INTENT_LANES.documentPlacement),\n inArray(localIntents.localId, localIdBatch),\n );\n await tx\n .delete(documentIntentLinkTargets)\n .where(\n inArray(\n documentIntentLinkTargets.intentId,\n tx\n .select({ id: localIntents.id })\n .from(localIntents)\n .where(placementIntents),\n ),\n )\n .run();\n await tx.delete(localIntents).where(placementIntents).run();\n }\n // Sync failures clear with the document columns in resetRemoteColumns.\n for (const documentBatch of remoteResetBatches(snapshot.documentRows)) {\n await unqueueDocumentScopesInTransaction(tx, documentBatch);\n }\n}\n\nasync function clearScopedRemoteRows(\n input: ScopedRemoteRowsInput,\n): Promise<void> {\n const { organizationId, tx } = input;\n await clearOrganizationPresentationRows(tx, organizationId);\n for (const table of [\n dormantContainerMetadata,\n dormantMetadataSweepRequests,\n verifiedAccessManifestBundles,\n ] as const) {\n await tx\n .delete(table)\n .where(eq(table.organizationId, organizationId))\n .run();\n }\n await clearDocumentDiscoveryEvidenceOnRemoteReset(tx, {\n containerIds: input.snapshot.containerIds,\n documentIds: input.snapshot.oldDocumentIds,\n });\n await clearRemoteResetPrincipalRows(input);\n await clearScopedContainerRows(input);\n await clearScopedDocumentRows(input);\n await clearRemoteResetSyncCursors({\n containerIds: input.snapshot.containerIds,\n tx,\n });\n}\n\nasync function resetRemoteColumns(input: {\n now: string;\n reset: RemoteResetInput;\n snapshot: RemoteSyncStateSnapshot;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const { now, reset, snapshot, tx } = input;\n for (const row of snapshot.documentRows) {\n await tx\n .update(documents)\n .set({\n accessEpoch: 1,\n accessStateHash: null,\n contentKeyBundle: null,\n documentId: null,\n documentKekTargets: null,\n documentManifestBundle: null,\n lastCommitLsn: null,\n pullContinuation: null,\n recoveryDocumentId: row.documentId ?? row.recoveryDocumentId,\n ...CLEARED_DOCUMENT_SYNC_FAILURE,\n updatedAt: now,\n })\n .where(\n and(\n eq(documents.appKind, row.appKind),\n eq(documents.localId, row.localId),\n ),\n )\n .run();\n }\n for (const localIdBatch of remoteResetBatches(snapshot.documentLocalIds)) {\n await tx\n .update(documentProjection)\n .set({\n documentId: null,\n organizationId:\n reset.replacement?.organizationId ?? reset.organizationId,\n })\n .where(inArray(documentProjection.localId, localIdBatch))\n .run();\n }\n // Replacement re-homes folders under their ids; the purged organization\n // can never bind them again on this device.\n for (const containerIds of reset.replacement\n ? remoteResetBatches(snapshot.containerIds)\n : []) {\n await recordSupersededContainerBindingsInTransaction(tx, {\n containerIds,\n organizationId: reset.organizationId,\n supersededAt: now,\n });\n }\n for (const row of snapshot.containerRows) {\n await tx\n .update(containers)\n .set({\n metadataDocumentId: null,\n organizationId:\n reset.replacement?.organizationId ?? reset.organizationId,\n parentId:\n reset.replacement && row.parentId === null\n ? reset.replacement.rootContainerId\n : row.parentId,\n serverCreatedAt: null,\n serverUpdatedAt: null,\n ...(reset.replacement ? { systemSlot: null } : {}),\n localUpdatedAt: now,\n })\n .where(eq(containers.id, row.id))\n .run();\n }\n}\n\nasync function queueResetDocumentUpdates(input: {\n documentUpdates: readonly ResetDocumentUpdate[];\n now: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n for (const updateBatch of remoteResetBatches(input.documentUpdates)) {\n await input.tx\n .insert(documentHistoryUpdates)\n .values(\n updateBatch.map((update) =>\n queuedUpdateRow({\n createdAt: input.now,\n origin: \"outbox\",\n pendingUpdate: update,\n scope: update,\n updateId: crypto.randomUUID(),\n }),\n ),\n )\n .run();\n }\n}\n\nasync function queueResetContainerCreates(input: {\n now: string;\n reset: RemoteResetInput;\n snapshot: RemoteSyncStateSnapshot;\n tx: ClientSQLiteTransactionScope;\n}): Promise<number> {\n const rows = input.snapshot.containerRows.flatMap((row) => {\n const parentId =\n row.parentId ?? input.reset.replacement?.rootContainerId ?? null;\n return parentId ? [{ id: row.id, parentId }] : [];\n });\n if (rows.length === 0) return 0;\n for (const rowBatch of remoteResetBatches(rows)) {\n await input.tx\n .insert(localIntents)\n .values(\n rowBatch.map((row) => ({\n id: crypto.randomUUID(),\n lane: LOCAL_INTENT_LANES.containerCreate,\n subjectId: row.id,\n targetContainerId: row.parentId,\n intentType: CONTAINER_CREATE_INTENT_TYPE,\n syncStatus: \"pending\" as const,\n remoteContainerId: null,\n remoteMetadataAccessStateHash: null,\n remoteMetadataDocumentId: null,\n lastError: null,\n createdAt: input.now,\n updatedAt: input.now,\n })),\n )\n .run();\n }\n return rows.length;\n}\n\nasync function queueResetAttachmentUploads(input: {\n attachmentUploads: readonly ResetAttachmentUpload[];\n now: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n for (const attachmentBatch of remoteResetBatches(input.attachmentUploads)) {\n await input.tx\n .insert(documentPendingAttachments)\n .values(\n attachmentBatch.map((attachment) => ({\n ...attachment,\n createdAt: input.now,\n })),\n )\n .run();\n await input.tx\n .delete(documentAttachmentBlobProjection)\n .where(\n or(\n ...attachmentBatch.map((attachment) =>\n and(\n eq(documentAttachmentBlobProjection.localId, attachment.localId),\n eq(documentAttachmentBlobProjection.slotId, attachment.slotId),\n ),\n ),\n ),\n )\n .run();\n }\n}\n\nasync function clearRemoteSyncStateInTransaction(input: {\n plans: Awaited<ReturnType<typeof buildResetPlans>>;\n reset: RemoteResetInput;\n snapshot: RemoteSyncStateSnapshot;\n tx: ClientSQLiteTransactionScope;\n}): Promise<ClearRemoteSyncStateResult> {\n const now = new Date().toISOString();\n const { snapshot } = input;\n await clearScopedRemoteRows({\n attachmentUploads: input.plans.attachmentUploads,\n organizationId: input.reset.organizationId,\n snapshot,\n tx: input.tx,\n });\n await resetRemoteColumns({ now, reset: input.reset, snapshot, tx: input.tx });\n await queueResetDocumentUpdates({\n documentUpdates: input.plans.documentUpdates,\n now,\n tx: input.tx,\n });\n const queuedContainerCreateCount = await queueResetContainerCreates({\n now,\n reset: input.reset,\n snapshot,\n tx: input.tx,\n });\n await queueResetAttachmentUploads({\n attachmentUploads: input.plans.attachmentUploads,\n now,\n tx: input.tx,\n });\n return {\n clearedContainerCreateIntentCount:\n snapshot.clearedContainerCreateIntentCount,\n clearedContainerMoveIntentCount: snapshot.clearedContainerMoveIntentCount,\n clearedDocumentMoveIntentCount: snapshot.clearedDocumentMoveIntentCount,\n clearedPrincipalPolicyCount: snapshot.clearedPrincipalPolicyCount,\n clearedSyncCursorCount: snapshot.clearedSyncCursorCount,\n queuedAttachmentUploadCount: input.plans.attachmentUploads.length,\n queuedContainerCreateCount,\n queuedDocumentUpdateCount: input.plans.documentUpdates.length,\n resetContainerCount: snapshot.containerRows.length,\n resetDocumentCount: snapshot.documentRows.length,\n };\n}\n\nexport async function clearRemoteSyncState(\n execSql: ExecSql,\n reset: RemoteResetInput,\n canCommit?: (() => boolean) | undefined,\n): Promise<ClearRemoteSyncStateResult> {\n return runOrganizationPresentationReset(\n execSql,\n reset.organizationId,\n async () => {\n await ensureSqlTables(execSql, clientSqlTables);\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const resetInTransaction = async (tx: ClientSQLiteTransactionScope) => {\n if (canCommit && !canCommit()) {\n throw new Error(\n \"Remote sync reset aborted: session identity changed\",\n );\n }\n const snapshot = await readRemoteSyncStateSnapshot(\n tx,\n reset.organizationId,\n );\n const plans = await buildResetPlans(tx, snapshot.documentRows);\n return clearRemoteSyncStateInTransaction({\n plans,\n reset,\n snapshot,\n tx,\n });\n };\n if (!canCommit) {\n return runtime.transaction(resetInTransaction);\n }\n const outcome = await runtime.guardedTransaction(\n resetInTransaction,\n canCommit,\n );\n if (!outcome.committed || !outcome.result) {\n throw new Error(\"Remote sync reset aborted: session identity changed\");\n }\n return out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BACL,KAAK;gBACL,QAAQ;gBACR,EAAE;aACH,CAAC,CAAC;QACL,CAAC,CAAC;QACF,IAAI,CAAC,SAAS,EAAE,CAAC;YACf,OAAO,OAAO,CAAC,WAAW,CAAC,kBAAkB,CAAC,CAAC;QACjD,CAAC;QACD,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,kBAAkB,CAC9C,kBAAkB,EAClB,SAAS,CACV,CAAC;QACF,IAAI,CAAC,OAAO,CAAC,SAAS,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC;YAC1C,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;QACzE,CAAC;QACD,OAAO,OAAO,CAAC,MAAM,CAAC;IACxB,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { and, eq, inArray, or } from \"drizzle-orm\";\nimport { recordSupersededContainerBindingsInTransaction } from \"../../data/persistence/container-contents/supersededContainerBindings\";\nimport {\n deleteDocumentPlacementRowsByContainerIds,\n deleteDocumentPlacementRowsByDocumentIds,\n} from \"../../data/persistence/containers/documentContainerProjectionPersistence\";\nimport { clearDocumentDiscoveryEvidenceOnRemoteReset } from \"../../data/persistence/documents/documentDiscoveryReset\";\nimport {\n queuedUpdateRow,\n unqueueDocumentScopesInTransaction,\n} from \"../../data/sqlite/documentPersistence/documentPendingUpdatePersistence\";\nimport { CLEARED_DOCUMENT_SYNC_FAILURE } from \"../../data/sqlite/documentPersistence/documentSyncFailurePersistence\";\nimport {\n clientSqlTables,\n containerHydrationTombstones,\n containers,\n documentAttachmentBlobProjection,\n documentHistoryUpdates,\n documentPendingAttachments,\n documentProjection,\n documents,\n dormantContainerMetadata,\n dormantMetadataSweepRequests,\n inContainerIntentLanes,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../data/sqlite/schema\";\nimport { documentIntentLinkTargets } from \"../../data/sqlite/schema/documentPlacementIntentSchema\";\nimport { organizationDataUsageSnapshots } from \"../../data/sqlite/schema/organizationDataUsageSchema\";\nimport {\n organizationPresentationDenials,\n organizationReadModelContainerGrants,\n organizationReadModelDirectoryUsers,\n organizationReadModelGroupMembers,\n organizationReadModelGroups,\n organizationReadModelRequesters,\n organizationReadModelState,\n} from \"../../data/sqlite/schema/organizationReadModelSchema\";\nimport { verifiedAccessManifestBundles } from \"../../data/sqlite/schema/verifiedManifestBundleSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../data/sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { ensureSqlTables } from \"../../data/sqlite/sqlTableSchema\";\nimport { runOrganizationPresentationReset } from \"../organizations/readModel/organizationPresentationAccessState\";\nimport { clearResetPendingAttachments } from \"./remoteResetAttachments\";\nimport { remoteResetBatches } from \"./remoteResetBatches\";\nimport { clearRemoteResetSyncCursors } from \"./remoteResetCursorScope\";\nimport {\n buildResetPlans,\n type ResetAttachmentUpload,\n type ResetDocumentUpdate,\n} from \"./remoteResetPlans\";\nimport { clearRemoteResetPrincipalRows } from \"./remoteResetPrincipalScope\";\nimport {\n type RemoteResetInput,\n type RemoteSyncStateSnapshot,\n readRemoteSyncStateSnapshot,\n} from \"./remoteResetScope\";\n\nexport type {\n RemoteResetInput,\n RemoteResetReplacement,\n} from \"./remoteResetScope\";\n\nconst CONTAINER_CREATE_INTENT_TYPE = \"container.create\";\n\nexport interface ClearRemoteSyncStateResult {\n readonly clearedContainerCreateIntentCount: number;\n readonly clearedContainerMoveIntentCount: number;\n readonly clearedDocumentMoveIntentCount: number;\n readonly clearedPrincipalPolicyCount: number;\n readonly clearedSyncCursorCount: number;\n readonly queuedAttachmentUploadCount: number;\n readonly queuedContainerCreateCount: number;\n readonly queuedDocumentUpdateCount: number;\n readonly resetContainerCount: number;\n readonly resetDocumentCount: number;\n}\n\nasync function clearOrganizationPresentationRows(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<void> {\n for (const table of [\n organizationDataUsageSnapshots,\n organizationReadModelContainerGrants,\n organizationReadModelGroupMembers,\n organizationReadModelDirectoryUsers,\n organizationReadModelGroups,\n organizationReadModelRequesters,\n organizationReadModelState,\n organizationPresentationDenials,\n ] as const) {\n await tx\n .delete(table)\n .where(eq(table.organizationId, organizationId))\n .run();\n }\n}\n\ninterface ScopedRemoteRowsInput {\n attachmentUploads: readonly ResetAttachmentUpload[];\n organizationId: string;\n snapshot: RemoteSyncStateSnapshot;\n tx: ClientSQLiteTransactionScope;\n}\n\nasync function clearScopedContainerRows(\n input: ScopedRemoteRowsInput,\n): Promise<void> {\n for (const containerBatch of remoteResetBatches(\n input.snapshot.containerIds,\n )) {\n await deleteDocumentPlacementRowsByContainerIds(input.tx, containerBatch);\n await input.tx\n .delete(localIntents)\n .where(\n and(\n inContainerIntentLanes(),\n inArray(localIntents.subjectId, containerBatch),\n ),\n )\n .run();\n await input.tx\n .delete(containerHydrationTombstones)\n .where(inArray(containerHydrationTombstones.containerId, containerBatch))\n .run();\n }\n}\n\nasync function clearScopedDocumentRows(\n input: ScopedRemoteRowsInput,\n): Promise<void> {\n const { snapshot, tx } = input;\n for (const documentIdBatch of remoteResetBatches(snapshot.oldDocumentIds)) {\n await deleteDocumentPlacementRowsByDocumentIds(tx, documentIdBatch);\n }\n await clearResetPendingAttachments({\n attachmentUploads: input.attachmentUploads,\n documentLocalIds: snapshot.documentLocalIds,\n tx,\n });\n for (const localIdBatch of remoteResetBatches(snapshot.documentLocalIds)) {\n const placementIntents = and(\n inLocalIntentLane(LOCAL_INTENT_LANES.documentPlacement),\n inArray(localIntents.localId, localIdBatch),\n );\n await tx\n .delete(documentIntentLinkTargets)\n .where(\n inArray(\n documentIntentLinkTargets.intentId,\n tx\n .select({ id: localIntents.id })\n .from(localIntents)\n .where(placementIntents),\n ),\n )\n .run();\n await tx.delete(localIntents).where(placementIntents).run();\n }\n // Sync failures clear with the document columns in resetRemoteColumns.\n for (const documentBatch of remoteResetBatches(snapshot.documentRows)) {\n await unqueueDocumentScopesInTransaction(tx, documentBatch);\n }\n}\n\nasync function clearScopedRemoteRows(\n input: ScopedRemoteRowsInput,\n): Promise<void> {\n const { organizationId, tx } = input;\n await clearOrganizationPresentationRows(tx, organizationId);\n for (const table of [\n dormantContainerMetadata,\n dormantMetadataSweepRequests,\n verifiedAccessManifestBundles,\n ] as const) {\n await tx\n .delete(table)\n .where(eq(table.organizationId, organizationId))\n .run();\n }\n await clearDocumentDiscoveryEvidenceOnRemoteReset(tx, {\n containerIds: input.snapshot.containerIds,\n documentIds: input.snapshot.oldDocumentIds,\n });\n await clearRemoteResetPrincipalRows(input);\n await clearScopedContainerRows(input);\n await clearScopedDocumentRows(input);\n await clearRemoteResetSyncCursors({\n containerIds: input.snapshot.containerIds,\n tx,\n });\n}\n\nasync function resetRemoteColumns(input: {\n now: string;\n reset: RemoteResetInput;\n snapshot: RemoteSyncStateSnapshot;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const { now, reset, snapshot, tx } = input;\n for (const row of snapshot.documentRows) {\n await tx\n .update(documents)\n .set({\n accessEpoch: 1,\n accessStateHash: null,\n contentKeyBundle: null,\n documentId: null,\n documentKekTargets: null,\n documentManifestBundle: null,\n lastCommitLsn: null,\n pullContinuation: null,\n recoveryDocumentId: row.documentId ?? row.recoveryDocumentId,\n ...CLEARED_DOCUMENT_SYNC_FAILURE,\n updatedAt: now,\n })\n .where(\n and(\n eq(documents.appKind, row.appKind),\n eq(documents.localId, row.localId),\n ),\n )\n .run();\n }\n for (const localIdBatch of remoteResetBatches(snapshot.documentLocalIds)) {\n await tx\n .update(documentProjection)\n .set({\n documentId: null,\n organizationId:\n reset.replacement?.organizationId ?? reset.organizationId,\n })\n .where(inArray(documentProjection.localId, localIdBatch))\n .run();\n }\n // Replacement re-homes folders under their ids; the purged organization\n // can never bind them again on this device.\n for (const containerIds of reset.replacement\n ? remoteResetBatches(snapshot.containerIds)\n : []) {\n await recordSupersededContainerBindingsInTransaction(tx, {\n containerIds,\n organizationId: reset.organizationId,\n supersededAt: now,\n });\n }\n for (const row of snapshot.containerRows) {\n await tx\n .update(containers)\n .set({\n metadataDocumentId: null,\n organizationId:\n reset.replacement?.organizationId ?? reset.organizationId,\n parentId:\n reset.replacement && row.parentId === null\n ? reset.replacement.rootContainerId\n : row.parentId,\n serverCreatedAt: null,\n serverUpdatedAt: null,\n ...(reset.replacement ? { systemSlot: null } : {}),\n localUpdatedAt: now,\n })\n .where(eq(containers.id, row.id))\n .run();\n }\n}\n\nasync function queueResetDocumentUpdates(input: {\n documentUpdates: readonly ResetDocumentUpdate[];\n now: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n for (const updateBatch of remoteResetBatches(input.documentUpdates)) {\n await input.tx\n .insert(documentHistoryUpdates)\n .values(\n updateBatch.map((update) =>\n queuedUpdateRow({\n createdAt: input.now,\n origin: \"outbox\",\n pendingUpdate: update,\n scope: update,\n updateId: crypto.randomUUID(),\n }),\n ),\n )\n .run();\n }\n}\n\nasync function queueResetContainerCreates(input: {\n now: string;\n reset: RemoteResetInput;\n snapshot: RemoteSyncStateSnapshot;\n tx: ClientSQLiteTransactionScope;\n}): Promise<number> {\n const rows = input.snapshot.containerRows.flatMap((row) => {\n const parentId =\n row.parentId ?? input.reset.replacement?.rootContainerId ?? null;\n return parentId ? [{ id: row.id, parentId }] : [];\n });\n if (rows.length === 0) return 0;\n for (const rowBatch of remoteResetBatches(rows)) {\n await input.tx\n .insert(localIntents)\n .values(\n rowBatch.map((row) => ({\n id: crypto.randomUUID(),\n lane: LOCAL_INTENT_LANES.containerCreate,\n subjectId: row.id,\n targetContainerId: row.parentId,\n intentType: CONTAINER_CREATE_INTENT_TYPE,\n syncStatus: \"pending\" as const,\n remoteContainerId: null,\n remoteMetadataAccessStateHash: null,\n remoteMetadataDocumentId: null,\n lastError: null,\n createdAt: input.now,\n updatedAt: input.now,\n })),\n )\n .run();\n }\n return rows.length;\n}\n\nasync function queueResetAttachmentUploads(input: {\n attachmentUploads: readonly ResetAttachmentUpload[];\n now: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n for (const attachmentBatch of remoteResetBatches(input.attachmentUploads)) {\n await input.tx\n .insert(documentPendingAttachments)\n .values(\n attachmentBatch.map((attachment) => ({\n ...attachment,\n createdAt: input.now,\n })),\n )\n .run();\n await input.tx\n .delete(documentAttachmentBlobProjection)\n .where(\n or(\n ...attachmentBatch.map((attachment) =>\n and(\n eq(documentAttachmentBlobProjection.localId, attachment.localId),\n eq(documentAttachmentBlobProjection.slotId, attachment.slotId),\n ),\n ),\n ),\n )\n .run();\n }\n}\n\nasync function clearRemoteSyncStateInTransaction(input: {\n plans: Awaited<ReturnType<typeof buildResetPlans>>;\n reset: RemoteResetInput;\n snapshot: RemoteSyncStateSnapshot;\n tx: ClientSQLiteTransactionScope;\n}): Promise<ClearRemoteSyncStateResult> {\n const now = new Date().toISOString();\n const { snapshot } = input;\n await clearScopedRemoteRows({\n attachmentUploads: input.plans.attachmentUploads,\n organizationId: input.reset.organizationId,\n snapshot,\n tx: input.tx,\n });\n await resetRemoteColumns({ now, reset: input.reset, snapshot, tx: input.tx });\n await queueResetDocumentUpdates({\n documentUpdates: input.plans.documentUpdates,\n now,\n tx: input.tx,\n });\n const queuedContainerCreateCount = await queueResetContainerCreates({\n now,\n reset: input.reset,\n snapshot,\n tx: input.tx,\n });\n await queueResetAttachmentUploads({\n attachmentUploads: input.plans.attachmentUploads,\n now,\n tx: input.tx,\n });\n return {\n clearedContainerCreateIntentCount:\n snapshot.clearedContainerCreateIntentCount,\n clearedContainerMoveIntentCount: snapshot.clearedContainerMoveIntentCount,\n clearedDocumentMoveIntentCount: snapshot.clearedDocumentMoveIntentCount,\n clearedPrincipalPolicyCount: snapshot.clearedPrincipalPolicyCount,\n clearedSyncCursorCount: snapshot.clearedSyncCursorCount,\n queuedAttachmentUploadCount: input.plans.attachmentUploads.length,\n queuedContainerCreateCount,\n queuedDocumentUpdateCount: input.plans.documentUpdates.length,\n resetContainerCount: snapshot.containerRows.length,\n resetDocumentCount: snapshot.documentRows.length,\n };\n}\n\nexport async function clearRemoteSyncState(\n execSql: ExecSql,\n reset: RemoteResetInput,\n canCommit?: (() => boolean) | undefined,\n): Promise<ClearRemoteSyncStateResult> {\n return runOrganizationPresentationReset(\n execSql,\n reset.organizationId,\n async () => {\n await ensureSqlTables(execSql, clientSqlTables);\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const resetInTransaction = async (tx: ClientSQLiteTransactionScope) => {\n if (canCommit && !canCommit()) {\n throw new Error(\n \"Remote sync reset aborted: session identity changed\",\n );\n }\n const snapshot = await readRemoteSyncStateSnapshot(\n tx,\n reset.organizationId,\n );\n const plans = await buildResetPlans(tx, snapshot.documentRows);\n return clearRemoteSyncStateInTransaction({\n plans,\n reset,\n snapshot,\n tx,\n });\n };\n if (!canCommit) {\n return runtime.transaction(resetInTransaction);\n }\n const outcome = await runtime.guardedTransaction(\n resetInTransaction,\n canCommit,\n );\n if (!outcome.committed || !outcome.result) {\n throw new Error(\"Remote sync reset aborted: session identity changed\");\n }\n return outcome.result;\n },\n );\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { inArray } from "drizzle-orm";
2
2
  import { queueDocumentAttachmentStorageKeys } from "../../data/persistence/documents/internal/orphanSideRows.js";
3
- import { documentPendingAttachments } from "../../data/sqlite/schema.js";
3
+ import { documentPendingAttachments } from "../../data/sqlite/schema/index.js";
4
4
  import { remoteResetBatches } from "./remoteResetBatches.js";
5
5
  /** Delete reset-scoped pending rows without abandoning dropped local bytes. */
6
6
  export async function clearResetPendingAttachments(input) {
@@ -1,5 +1,5 @@
1
1
  import { and, eq, inArray, or } from "drizzle-orm";
2
- import { containerSyncWatermarks } from "../../data/sqlite/schema.js";
2
+ import { containerSyncWatermarks } from "../../data/sqlite/schema/index.js";
3
3
  import { remoteResetBatches } from "./remoteResetBatches.js";
4
4
  const CONTAINER_DOCUMENTS_LANE = "container_documents";
5
5
  const CONTAINER_PARENT_LANE = "container_parent";
@@ -3,7 +3,7 @@ import { and, eq, ne, or, sql } from "drizzle-orm";
3
3
  import { getDocumentAttachments, } from "../../data/documents/documentContent.js";
4
4
  import { createPendingUpdateFields } from "../../data/documents/documentSync.js";
5
5
  import { DOCUMENTS_APP_KIND } from "../../data/persistence/documents/documentsPersistence.js";
6
- import { documentAttachmentBlobProjection, documentHistoryCheckpoints, documentHistoryUpdates, documentPendingAttachments, documents, } from "../../data/sqlite/schema.js";
6
+ import { documentAttachmentBlobProjection, documentHistoryCheckpoints, documentHistoryUpdates, documentPendingAttachments, documents, } from "../../data/sqlite/schema/index.js";
7
7
  import { importDocumentHistoryTailUpdates } from "../documents/historyContent.js";
8
8
  import { remoteResetBatches } from "./remoteResetBatches.js";
9
9
  function historyScopeKey(appKind, localId) {
@@ -1,9 +1,9 @@
1
1
  import { and, eq, or } from "drizzle-orm";
2
- import { principalHistoryEntries, principalHistoryNodes, principalHistoryPrefixes, } from "../../data/sqlite/principalHistoryEvidenceSchema.js";
3
- import { principalHistoryNodeReferences, principalHistoryRootOwners, } from "../../data/sqlite/principalHistoryNodeRetentionSchema.js";
4
- import { principalKeyEnvelopeArchive } from "../../data/sqlite/principalHistoryRetentionSchema.js";
5
- import { principalHistoryStages } from "../../data/sqlite/principalHistoryStageSchema.js";
6
- import { principalPolicies, principalPolicyBundleHistory, principalPolicyBundleReferences, principalPolicyCheckpoints, principalPolicyOrganizations, } from "../../data/sqlite/schema.js";
2
+ import { principalPolicies, principalPolicyBundleHistory, principalPolicyBundleReferences, principalPolicyCheckpoints, principalPolicyOrganizations, } from "../../data/sqlite/schema/index.js";
3
+ import { principalHistoryEntries, principalHistoryNodes, principalHistoryPrefixes, } from "../../data/sqlite/schema/principalHistoryEvidenceSchema.js";
4
+ import { principalHistoryNodeReferences, principalHistoryRootOwners, } from "../../data/sqlite/schema/principalHistoryNodeRetentionSchema.js";
5
+ import { principalKeyEnvelopeArchive } from "../../data/sqlite/schema/principalHistoryRetentionSchema.js";
6
+ import { principalHistoryStages } from "../../data/sqlite/schema/principalHistoryStageSchema.js";
7
7
  import { remoteResetBatches } from "./remoteResetBatches.js";
8
8
  /** Current cache writes atomically pin ownership; reset never backfills it. */
9
9
  export async function loadRemoteResetPrincipalScope(tx, organizationId) {
@@ -1 +1 @@
1
- {"version":3,"file":"remoteResetPrincipalScope.js","sourceRoot":"","sources":["remoteResetPrincipalScope.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EACL,uBAAuB,EACvB,qBAAqB,EACrB,wBAAwB,GACzB,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EACL,8BAA8B,EAC9B,0BAA0B,GAC3B,MAAM,uDAAuD,CAAC;AAC/D,OAAO,EAAE,2BAA2B,EAAE,MAAM,mDAAmD,CAAC;AAChG,OAAO,EAAE,sBAAsB,EAAE,MAAM,+CAA+C,CAAC;AACvF,OAAO,EACL,iBAAiB,EACjB,4BAA4B,EAC5B,+BAA+B,EAC/B,0BAA0B,EAC1B,4BAA4B,GAC7B,MAAM,0BAA0B,CAAC;AAElC,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAY1D,+EAA+E;AAC/E,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,EAAgC,EAChC,cAAsB;IAKtB,MAAM,CAAC,UAAU,EAAE,YAAY,EAAE,aAAa,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;QAClE,EAAE;aACC,MAAM,CAAC;YACN,EAAE,EAAE,iBAAiB,CAAC,WAAW;YACjC,IAAI,EAAE,iBAAiB,CAAC,aAAa;SACtC,CAAC;aACD,IAAI,CAAC,iBAAiB,CAAC;QAC1B,OAAO,CAAC,GAAG,CACT;YACE,4BAA4B;YAC5B,+BAA+B;YAC/B,0BAA0B;SAC3B,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CACd,EAAE;aACC,cAAc,CAAC,E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,CAAC,sBAAsB,CAAC;SAC9B,KAAK,CAAC,EAAE,CAAC,sBAAsB,CAAC,cAAc,EAAE,KAAK,CAAC,cAAc,CAAC,CAAC;SACtE,GAAG,EAAE,CAAC;IACT,KAAK,MAAM,cAAc,IAAI,kBAAkB,CAC7C,KAAK,CAAC,QAAQ,CAAC,aAAa,CAC7B,EAAE,CAAC;QACF,KAAK,MAAM,KAAK,IAAI;YAClB,iBAAiB;YACjB,4BAA4B;YAC5B,+BAA+B;SACvB,EAAE,CAAC;YACX,MAAM,KAAK,CAAC,EAAE;iBACX,MAAM,CAAC,KAAK,CAAC;iBACb,KAAK,CACJ,EAAE,CACA,GAAG,cAAc,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAClC,GAAG,CACD,EAAE,CAAC,KAAK,CAAC,aAAa,EAAE,SAAS,CAAC,aAAa,CAAC,EAChD,EAAE,CAAC,KAAK,CAAC,WAAW,EAAE,SAAS,CAAC,WAAW,CAAC,CAC7C,CACF,CACF,CACF;iBACA,GAAG,EAAE,CAAC;QACX,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { and, eq, or } from \"drizzle-orm\";\nimport {\n principalHistoryEntries,\n principalHistoryNodes,\n principalHistoryPrefixes,\n} from \"../../data/sqlite/principalHistoryEvidenceSchema\";\nimport {\n principalHistoryNodeReferences,\n principalHistoryRootOwners,\n} from \"../../data/sqlite/principalHistoryNodeRetentionSchema\";\nimport { principalKeyEnvelopeArchive } from \"../../data/sqlite/principalHistoryRetentionSchema\";\nimport { principalHistoryStages } from \"../../data/sqlite/principalHistoryStageSchema\";\nimport {\n principalPolicies,\n principalPolicyBundleHistory,\n principalPolicyBundleReferences,\n principalPolicyCheckpoints,\n principalPolicyOrganizations,\n} from \"../../data/sqlite/schema\";\nimport type { ClientSQLiteTransactionScope } from \"../../data/sqlite/sqlitePersistenceRuntime\";\nimport { remoteResetBatches } from \"./remoteResetBatches\";\n\nexport interface RemoteResetPrincipalKey {\n readonly principalId: string;\n readonly principalType: \"group\" | \"organization\";\n}\n\ninterface PrincipalRow {\n readonly id: string;\n readonly type: string;\n}\n\n/** Current cache writes atomically pin ownership; reset never backfills it. */\nexport async function loadRemoteResetPrincipalScope(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<{\n readonly policyRows: readonly PrincipalRow[];\n readonly principalKeys: readonly RemoteResetPrincipalKey[];\n}> {\n const [policyRows, retainedRows, ownershipRows] = await Promise.all([\n tx\n .select({\n id: principalPolicies.principalId,\n type: principalPolicies.principalType,\n })\n .from(principalPolicies),\n Promise.all(\n [\n principalPolicyBundleHistory,\n principalPolicyBundleReferences,\n principalPolicyCheckpoints,\n ].map((table) =>\n tx\n .selectDistinct({ id: table.principalId, type: table.principalType })\n .from(table),\n ),\n ),\n tx\n .select({\n organizationId: principalPolicyOrganizations.organizationId,\n principalId: principalPolicyOrganizations.principalId,\n principalType: principalPolicyOrganizations.principalType,\n })\n .from(principalPolicyOrganizations),\n ]);\n const owners = new Map(\n ownershipRows.map((row) => [\n `${row.principalType}\\0${row.principalId}`,\n row.organizationId,\n ]),\n );\n for (const row of [...policyRows, ...retainedRows.flat()]) {\n const owner = owners.get(`${row.type}\\0${row.id}`);\n if (row.type === \"group\" && !owner) {\n throw new Error(\n \"Unowned group policy cache requires a local database reset before organization purge\",\n );\n }\n if (row.type !== \"group\" && row.type !== \"organization\") {\n throw new Error(\"Principal policy cache has an invalid principal type\");\n }\n if (\n row.type === \"organization\" &&\n owner !== undefined &&\n owner !== row.id\n ) {\n throw new Error(\n \"Organization policy cache ownership does not match its identity\",\n );\n }\n }\n const keys = new Map<string, RemoteResetPrincipalKey>();\n keys.set(`organization\\0${organizationId}`, {\n principalId: organizationId,\n principalType: \"organization\",\n });\n for (const row of ownershipRows) {\n if (row.principalType !== \"group\" && row.principalType !== \"organization\") {\n throw new Error(\n \"Principal policy cache ownership has an invalid principal type\",\n );\n }\n if (!row.organizationId) {\n throw new Error(\n \"Principal policy cache ownership requires a local database reset\",\n );\n }\n if (row.organizationId !== organizationId) continue;\n keys.set(`${row.principalType}\\0${row.principalId}`, {\n principalId: row.principalId,\n principalType: row.principalType,\n });\n }\n return { policyRows, principalKeys: [...keys.values()] };\n}\n\n// Trust checkpoints and their ownership survive reset. Clearing cached bundles\n// must not turn a previously observed principal or object into first sight.\nexport async function clearRemoteResetPrincipalRows(input: {\n organizationId: string;\n snapshot: { principalKeys: readonly RemoteResetPrincipalKey[] };\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n for (const table of [\n principalHistoryNodeReferences,\n principalHistoryRootOwners,\n principalHistoryEntries,\n principalHistoryNodes,\n principalHistoryPrefixes,\n principalKeyEnvelopeArchive,\n ])\n await input.tx\n .delete(table)\n .where(eq(table.organizationId, input.organizationId))\n .run();\n await input.tx\n .delete(principalHistoryStages)\n .where(eq(principalHistoryStages.organizationId, input.organizationId))\n .run();\n for (const principalBatch of remoteResetBatches(\n input.snapshot.principalKeys,\n )) {\n for (const table of [\n principalPolicies,\n principalPolicyBundleHistory,\n principalPolicyBundleReferences,\n ] as const) {\n await input.tx\n .delete(table)\n .where(\n or(\n ...principalBatch.map((principal) =>\n and(\n eq(table.principalType, principal.principalType),\n eq(table.principalId, principal.principalId),\n ),\n ),\n ),\n )\n .run();\n }\n }\n}\n"]}
1
+ {"version":3,"file":"remoteResetPrincipalScope.js","sourceRoot":"","sources":["remoteResetPrincipalScope.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EACL,iBAAiB,EACjB,4BAA4B,EAC5B,+BAA+B,EAC/B,0BAA0B,EAC1B,4BAA4B,GAC7B,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,uBAAuB,EACvB,qBAAqB,EACrB,wBAAwB,GACzB,MAAM,yDAAyD,CAAC;AACjE,OAAO,EACL,8BAA8B,EAC9B,0BAA0B,GAC3B,MAAM,8DAA8D,CAAC;AACtE,O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CAC7C,CACF,CACF,CACF;iBACA,GAAG,EAAE,CAAC;QACX,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { and, eq, or } from \"drizzle-orm\";\nimport {\n principalPolicies,\n principalPolicyBundleHistory,\n principalPolicyBundleReferences,\n principalPolicyCheckpoints,\n principalPolicyOrganizations,\n} from \"../../data/sqlite/schema\";\nimport {\n principalHistoryEntries,\n principalHistoryNodes,\n principalHistoryPrefixes,\n} from \"../../data/sqlite/schema/principalHistoryEvidenceSchema\";\nimport {\n principalHistoryNodeReferences,\n principalHistoryRootOwners,\n} from \"../../data/sqlite/schema/principalHistoryNodeRetentionSchema\";\nimport { principalKeyEnvelopeArchive } from \"../../data/sqlite/schema/principalHistoryRetentionSchema\";\nimport { principalHistoryStages } from \"../../data/sqlite/schema/principalHistoryStageSchema\";\nimport type { ClientSQLiteTransactionScope } from \"../../data/sqlite/sqlitePersistenceRuntime\";\nimport { remoteResetBatches } from \"./remoteResetBatches\";\n\nexport interface RemoteResetPrincipalKey {\n readonly principalId: string;\n readonly principalType: \"group\" | \"organization\";\n}\n\ninterface PrincipalRow {\n readonly id: string;\n readonly type: string;\n}\n\n/** Current cache writes atomically pin ownership; reset never backfills it. */\nexport async function loadRemoteResetPrincipalScope(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<{\n readonly policyRows: readonly PrincipalRow[];\n readonly principalKeys: readonly RemoteResetPrincipalKey[];\n}> {\n const [policyRows, retainedRows, ownershipRows] = await Promise.all([\n tx\n .select({\n id: principalPolicies.principalId,\n type: principalPolicies.principalType,\n })\n .from(principalPolicies),\n Promise.all(\n [\n principalPolicyBundleHistory,\n principalPolicyBundleReferences,\n principalPolicyCheckpoints,\n ].map((table) =>\n tx\n .selectDistinct({ id: table.principalId, type: table.principalType })\n .from(table),\n ),\n ),\n tx\n .select({\n organizationId: principalPolicyOrganizations.organizationId,\n principalId: principalPolicyOrganizations.principalId,\n principalType: principalPolicyOrganizations.principalType,\n })\n .from(principalPolicyOrganizations),\n ]);\n const owners = new Map(\n ownershipRows.map((row) => [\n `${row.principalType}\\0${row.principalId}`,\n row.organizationId,\n ]),\n );\n for (const row of [...policyRows, ...retainedRows.flat()]) {\n const owner = owners.get(`${row.type}\\0${row.id}`);\n if (row.type === \"group\" && !owner) {\n throw new Error(\n \"Unowned group policy cache requires a local database reset before organization purge\",\n );\n }\n if (row.type !== \"group\" && row.type !== \"organization\") {\n throw new Error(\"Principal policy cache has an invalid principal type\");\n }\n if (\n row.type === \"organization\" &&\n owner !== undefined &&\n owner !== row.id\n ) {\n throw new Error(\n \"Organization policy cache ownership does not match its identity\",\n );\n }\n }\n const keys = new Map<string, RemoteResetPrincipalKey>();\n keys.set(`organization\\0${organizationId}`, {\n principalId: organizationId,\n principalType: \"organization\",\n });\n for (const row of ownershipRows) {\n if (row.principalType !== \"group\" && row.principalType !== \"organization\") {\n throw new Error(\n \"Principal policy cache ownership has an invalid principal type\",\n );\n }\n if (!row.organizationId) {\n throw new Error(\n \"Principal policy cache ownership requires a local database reset\",\n );\n }\n if (row.organizationId !== organizationId) continue;\n keys.set(`${row.principalType}\\0${row.principalId}`, {\n principalId: row.principalId,\n principalType: row.principalType,\n });\n }\n return { policyRows, principalKeys: [...keys.values()] };\n}\n\n// Trust checkpoints and their ownership survive reset. Clearing cached bundles\n// must not turn a previously observed principal or object into first sight.\nexport async function clearRemoteResetPrincipalRows(input: {\n organizationId: string;\n snapshot: { principalKeys: readonly RemoteResetPrincipalKey[] };\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n for (const table of [\n principalHistoryNodeReferences,\n principalHistoryRootOwners,\n principalHistoryEntries,\n principalHistoryNodes,\n principalHistoryPrefixes,\n principalKeyEnvelopeArchive,\n ])\n await input.tx\n .delete(table)\n .where(eq(table.organizationId, input.organizationId))\n .run();\n await input.tx\n .delete(principalHistoryStages)\n .where(eq(principalHistoryStages.organizationId, input.organizationId))\n .run();\n for (const principalBatch of remoteResetBatches(\n input.snapshot.principalKeys,\n )) {\n for (const table of [\n principalPolicies,\n principalPolicyBundleHistory,\n principalPolicyBundleReferences,\n ] as const) {\n await input.tx\n .delete(table)\n .where(\n or(\n ...principalBatch.map((principal) =>\n and(\n eq(table.principalType, principal.principalType),\n eq(table.principalId, principal.principalId),\n ),\n ),\n ),\n )\n .run();\n }\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { eq } from "drizzle-orm";
2
- import { containerSyncWatermarks, containers, documentContainerProjection, documentProjection, documents, dormantContainerMetadata, LOCAL_INTENT_LANES, localIntents, } from "../../data/sqlite/schema.js";
2
+ import { containerSyncWatermarks, containers, documentContainerProjection, documentProjection, documents, dormantContainerMetadata, LOCAL_INTENT_LANES, localIntents, } from "../../data/sqlite/schema/index.js";
3
3
  import { isRemoteResetSyncCursor } from "./remoteResetCursorScope.js";
4
4
  import { loadRemoteResetPrincipalScope, } from "./remoteResetPrincipalScope.js";
5
5
  function principalKeyOfRow(row) {
@@ -1 +0,0 @@
1
- {"version":3,"file":"containerKekPath.js","sourceRoot":"","sources":["containerKekPath.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,aAAa,IAAI,aAAa,EAAE,MAAM,qCAAqC,CAAC;AAErF,OAAO,EAAE,uCAAuC,EAAE,MAAM,wCAAwC,CAAC;AAEjG,OAAO,EACL,4CAA4C,EAC5C,uCAAuC,EACvC,kBAAkB,EAClB,iCAAiC,GAClC,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAEL,gCAAgC,GACjC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,6BAA6B,EAC7B,gCAAgC,GACjC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,yBAAyB,EACzB,uBAAuB,EACvB,wBAAwB,EACxB,yBAAyB,EACzB,gBAAgB,GACjB,MAAM,WAAW,CAAC;AAGnB,SAAS,8BAA8B,CACrC,UAA6C,EAC7C,KAAa;IAEb,MAAM,QAAQ,GAAG,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;I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AAwB,CACtB,4BAA4B,EAC5B,4CAA4C,EAC5C,cAAc,CACf,CAAC;QACJ,CAAC;IACH,CAAC;IAED,MAAM,oBAAoB,GAAG,IAAI,GAAG,EAAsB,CAAC;IAC3D,KAAK,MAAM,CAAC,mBAAmB,EAAE,GAAG,CAAC,IAAI,aAAa,EAAE,CAAC;QACvD,oBAAoB,CAAC,GAAG,CAAC,mBAAmB,EAAE,GAAG,CAAC,WAAW,CAAC,CAAC;IACjE,CAAC;IACD,wBAAwB,CAAC;QACvB,oBAAoB;QACpB,4BAA4B;QAC5B,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,4CAA4C;KAC7C,CAAC,CAAC;IACH,OAAO;QACL,aAAa,EAAE,oBAAoB;QACnC,4BAA4B;QAC5B,4CAA4C;KAC7C,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,KAAkC;IAElC,OAAO,CAAC,MAAM,yCAAyC,CAAC,KAAK,CAAC,CAAC,CAAC,aAAa,CAAC;AAChF,CAAC","sourcesContent":["import type {\n ContainerKeyWrap,\n VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport { isPlainObject as isPlainRecord } from \"@tearleads/validators/isPlainObject\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { unwrapKeyEnvelopesWithPrincipalPolicies } from \"../../principals/principalPolicyCrypto\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport {\n assertUnwrappedContainerKekMatchesMaterialId,\n projectedUnreachablePredecessorEpochIds,\n projectionKekLabel,\n unwrapKeyringContainerKeksAtIndex,\n} from \"./containerKekPathHistory\";\nimport {\n type UnwrapContainerKekPathInput,\n verifyContainerKekPathProjection,\n} from \"./containerKekPathVerification\";\nimport {\n assertSignedWrappingPublicKey,\n unwrapContainerKekFromParentWrap,\n} from \"./containerKekWrapping\";\nimport {\n normalizeContainerKeyWrap,\n readManifestContainerId,\n readRecordNullableString,\n readRecordPositiveInteger,\n readRecordString,\n} from \"./readers\";\nimport type { UnwrappedContainerKek } from \"./types\";\n\nfunction assertProjectionKekMatchesPath(\n projection: ContainerWriterProjectionResponse,\n index: number,\n): void {\n const manifest = projection.path[index];\n const kek = projection.containerKeks[index];\n if (!manifest || !kek) {\n throw new Error(\"Container writer projection path and KEKs are incomplete\");\n }\n if (readManifestContainerId(manifest) !== kek.containerId) {\n throw new Error(`${projectionKekLabel(index)} container is inconsistent`);\n }\n if (kek.accessManifestHash !== manifest.manifestHash) {\n throw new Error(`${projectionKekLabel(index)} manifest is stale`);\n }\n if (!isPlainRecord(kek.keyEpoch)) {\n throw new Error(`${projectionKekLabel(index)} key epoch is invalid`);\n }\n if (\n readRecordString(kek.keyEpoch, \"id\", projectionKekLabel(index)) !==\n kek.containerKeyEpochId ||\n readRecordString(kek.keyEpoch, \"containerId\", projectionKekLabel(index)) !==\n kek.containerId ||\n readRecordPositiveInteger(\n kek.keyEpoch,\n \"keyEpoch\",\n projectionKekLabel(index),\n ) !== kek.containerKeyEpoch ||\n readRecordNullableString(\n kek.keyEpoch,\n \"parentContainerKeyEpochId\",\n projectionKekLabel(index),\n ) !== kek.parentContainerKeyEpochId\n ) {\n throw new Error(`${projectionKekLabel(index)} key epoch is inconsistent`);\n }\n}\n\nasync function unwrapContainerKekFromPrincipalWraps(input: {\n execSql?: ExecSql | undefined;\n secretKey: Uint8Array;\n wraps: readonly ContainerKeyWrap[];\n}): Promise<Uint8Array | null> {\n const envelopes = input.wraps\n .filter((wrap) => wrap.recipientKind !== \"container\")\n .map((wrap) => ({\n keyFingerprint: wrap.recipientKeyFingerprint,\n kemCipherText: wrap.kemCipherText,\n wrappedKey: wrap.wrappedKey,\n }));\n if (envelopes.length === 0) {\n return null;\n }\n\n try {\n return await unwrapKeyEnvelopesWithPrincipalPolicies({\n envelopes,\n execSql: input.execSql,\n secretKey: input.secretKey,\n });\n } catch {\n return null;\n }\n}\n\n/**\n * Admits caller-supplied keys that the projection also names.\n *\n * The projection match is deliberate: a seeded key is trusted only once its\n * epoch is one this projection actually carries, which is what makes the\n * material-id check below meaningful. Production seeds this with the epoch it\n * just minted (see `registerIdentity`), never with recovered history — history\n * arrives through the sealed keyring on each path instead, and is shared across\n * authorizing paths through the common `keksByEpochId` map.\n */\nasync function seedKnownContainerKeks(input: {\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n projection: ContainerWriterProjectionResponse;\n}): Promise<Map<string, UnwrappedContainerKek>> {\n const keksByEpochId = new Map<string, UnwrappedContainerKek>();\n\n for (const [containerKeyEpochId, keyMaterial] of input.knownContainerKeks ??\n new Map<string, Uint8Array>()) {\n const projected = findProjectedContainerKek(\n input.projection,\n containerKeyEpochId,\n );\n if (!projected) {\n continue;\n }\n await assertUnwrappedContainerKekMatchesMaterialId({\n label: projected.label,\n kek: projected.kek,\n keyMaterial,\n });\n await assertSignedWrappingPublicKey(\n input.projection,\n projected.index,\n keyMaterial,\n );\n keksByEpochId.set(containerKeyEpochId, {\n containerId: projected.kek.containerId,\n keyEpochHash: projected.kek.keyEpochHash,\n keyMaterial,\n });\n }\n\n return keksByEpochId;\n}\n\nfunction findProjectedContainerKek(\n projection: ContainerWriterProjectionResponse,\n containerKeyEpochId: string,\n) {\n for (const [index, current] of projection.containerKeks.entries()) {\n if (current.containerKeyEpochId === containerKeyEpochId) {\n return { index, kek: current, label: projectionKekLabel(index) };\n }\n }\n return null;\n}\n\nfunction successorKeyMaterial(\n keksByEpochId: ReadonlyMap<string, UnwrappedContainerKek>,\n kek: Pick<\n ContainerWriterProjectionResponse[\"containerKeks\"][number],\n \"containerKeyEpochId\"\n >,\n unwrapped: Uint8Array | null,\n): Uint8Array | null {\n return keksByEpochId.get(kek.containerKeyEpochId)?.keyMaterial ?? unwrapped;\n}\n\nasync function unwrapContainerKekAtIndex(input: {\n readonly execSql?: ExecSql | undefined;\n readonly index: number;\n readonly keksByEpochId: Map<string, UnwrappedContainerKek>;\n readonly projection: ContainerWriterProjectionResponse;\n readonly secretKey: Uint8Array;\n readonly verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n readonly verifyBridgeCommitment: boolean;\n}): Promise<{\n readonly containerId: string;\n readonly error: Error;\n readonly unreachableEpochIds: readonly string[];\n} | null> {\n assertProjectionKekMatchesPath(input.projection, input.index);\n const kek = input.projection.containerKeks[input.index];\n const currentManifest = input.projection.path[input.index];\n if (!kek || !currentManifest) {\n throw new Error(`${projectionKekLabel(input.index)} is missing`);\n }\n\n const wraps: ContainerKeyWrap[] = [];\n for (const rawWrap of kek.wraps) {\n const wrap = normalizeContainerKeyWrap(rawWrap);\n if (wrap.containerKeyEpochId === kek.containerKeyEpochId) {\n wraps.push(wrap);\n }\n }\n if (wraps.length !== kek.wraps.length) {\n throw new Error(`${projectionKekLabel(input.index)} contains a stale wrap`);\n }\n\n const unwrapped =\n (await unwrapContainerKekFromPrincipalWraps({\n execSql: input.execSql,\n secretKey: input.secretKey,\n wraps,\n })) ??\n (await unwrapContainerKekFromParentWrap({\n label: projectionKekLabel(input.index),\n parentContainerKeyEpochId: kek.parentContainerKeyEpochId,\n parentKeksByEpochId: input.keksByEpochId,\n wraps,\n }));\n\n if (unwrapped) {\n await assertUnwrappedContainerKekMatchesMaterialId({\n label: projectionKekLabel(input.index),\n kek,\n keyMaterial: unwrapped,\n });\n await assertSignedWrappingPublicKey(\n input.projection,\n input.index,\n unwrapped,\n );\n input.keksByEpochId.set(kek.containerKeyEpochId, {\n containerId: kek.containerId,\n keyEpochHash: kek.keyEpochHash,\n keyMaterial: unwrapped,\n });\n }\n\n try {\n // Open the keyring immediately so descendants pinned to an older parent\n // epoch can still unwrap during the same path walk.\n await unwrapKeyringContainerKeksAtIndex({\n currentManifest,\n index: input.index,\n kek,\n keksByEpochId: input.keksByEpochId,\n successorKeyMaterial: successorKeyMaterial(\n input.keksByEpochId,\n kek,\n unwrapped,\n ),\n verifiedByHash: input.verifiedByHash,\n verifyKeyringCommitment: input.verifyBridgeCommitment,\n });\n return null;\n } catch (error) {\n // Historical keyring damage must not discard an independently verified\n // current KEK. If the target still cannot be reached, the caller\n // surfaces this integrity error; the bridge log remains the recovery\n // path for the orphaned epochs.\n return {\n containerId: kek.containerId,\n error:\n error instanceof Error\n ? error\n : new Error(\"Container predecessor KEK recovery failed\", {\n cause: error,\n }),\n unreachableEpochIds: projectedUnreachablePredecessorEpochIds({\n kek,\n keksByEpochId: input.keksByEpochId,\n }),\n };\n }\n}\n\ninterface UnwrappedContainerKekPathResult {\n readonly keksByEpochId: ReadonlyMap<string, Uint8Array>;\n readonly predecessorFailuresByEpochId: ReadonlyMap<string, Error>;\n readonly unattributedPredecessorFailuresByContainerId: ReadonlyMap<\n string,\n Error\n >;\n}\n\nfunction recordPredecessorFailure(\n failuresByEpochId: Map<string, Error>,\n unattributedFailuresByContainerId: Map<string, Error>,\n failure: NonNullable<Awaited<ReturnType<typeof unwrapContainerKekAtIndex>>>,\n): void {\n if (failure.unreachableEpochIds.length === 0) {\n if (!unattributedFailuresByContainerId.has(failure.containerId)) {\n unattributedFailuresByContainerId.set(failure.containerId, failure.error);\n }\n return;\n }\n for (const containerKeyEpochId of failure.unreachableEpochIds) {\n if (!failuresByEpochId.has(containerKeyEpochId)) {\n failuresByEpochId.set(containerKeyEpochId, failure.error);\n }\n }\n}\n\n/**\n * No wrap on the path opens the target for this reader, and no recorded\n * history failure explains it: the reader simply holds no key here. Distinct\n * from keyring damage, which rethrows the underlying integrity error instead.\n */\nexport class ContainerKekTargetUnreachableError extends Error {\n constructor(\n readonly containerId: string,\n label: string,\n ) {\n super(`${label} could not be unwrapped`);\n this.name = \"ContainerKekTargetUnreachableError\";\n }\n}\n\nfunction assertTargetKekUnwrapped(input: {\n readonly keyMaterialByEpochId: ReadonlyMap<string, Uint8Array>;\n readonly predecessorFailuresByEpochId: ReadonlyMap<string, Error>;\n readonly projection: ContainerWriterProjectionResponse;\n readonly unattributedPredecessorFailuresByContainerId: ReadonlyMap<\n string,\n Error\n >;\n}): void {\n const targetKek = input.projection.containerKeks.at(-1);\n if (\n !targetKek ||\n input.keyMaterialByEpochId.has(targetKek.containerKeyEpochId)\n ) {\n return;\n }\n for (\n let index = input.projection.containerKeks.length - 1;\n index >= 0;\n index -= 1\n ) {\n const pathKek = input.projection.containerKeks[index];\n if (!pathKek) {\n continue;\n }\n const predecessorFailure =\n input.predecessorFailuresByEpochId.get(pathKek.containerKeyEpochId) ??\n (pathKek.parentContainerKeyEpochId\n ? input.predecessorFailuresByEpochId.get(\n pathKek.parentContainerKeyEpochId,\n )\n : undefined) ??\n input.unattributedPredecessorFailuresByContainerId.get(\n pathKek.containerId,\n );\n if (predecessorFailure) {\n throw predecessorFailure;\n }\n }\n throw new ContainerKekTargetUnreachableError(\n targetKek.containerId,\n projectionKekLabel(input.projection.containerKeks.length - 1),\n );\n}\n\nexport async function unwrapContainerKekPathWithHistoryFailures(\n rawInput: UnwrapContainerKekPathInput,\n): Promise<UnwrappedContainerKekPathResult> {\n // Kept for the keyring checks, which anchor to the verified lineage.\n const input = {\n ...rawInput,\n verifiedByHash:\n rawInput.verifiedByHash ??\n new Map<string, VerifiedContainerAccessManifest>(),\n };\n await verifyContainerKekPathProjection(input);\n\n const keksByEpochId = await seedKnownContainerKeks({\n knownContainerKeks: input.knownContainerKeks,\n projection: input.projection,\n });\n const predecessorFailuresByEpochId = new Map<string, Error>();\n const unattributedPredecessorFailuresByContainerId = new Map<string, Error>();\n\n for (\n let index = 0;\n index < input.projection.containerKeks.length;\n index += 1\n ) {\n const currentFailure = await unwrapContainerKekAtIndex({\n execSql: input.execSql,\n index,\n keksByEpochId,\n projection: input.projection,\n secretKey: input.secretKey,\n verifiedByHash: input.verifiedByHash,\n verifyBridgeCommitment: input.trustedLocalProjection !== true,\n });\n if (currentFailure) {\n recordPredecessorFailure(\n predecessorFailuresByEpochId,\n unattributedPredecessorFailuresByContainerId,\n currentFailure,\n );\n }\n }\n\n const keyMaterialByEpochId = new Map<string, Uint8Array>();\n for (const [containerKeyEpochId, kek] of keksByEpochId) {\n keyMaterialByEpochId.set(containerKeyEpochId, kek.keyMaterial);\n }\n assertTargetKekUnwrapped({\n keyMaterialByEpochId,\n predecessorFailuresByEpochId,\n projection: input.projection,\n unattributedPredecessorFailuresByContainerId,\n });\n return {\n keksByEpochId: keyMaterialByEpochId,\n predecessorFailuresByEpochId,\n unattributedPredecessorFailuresByContainerId,\n };\n}\n\nexport async function unwrapContainerKekPath(\n input: UnwrapContainerKekPathInput,\n): Promise<ReadonlyMap<string, Uint8Array>> {\n return (await unwrapContainerKekPathWithHistoryFailures(input)).keksByEpochId;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"containerKekPathHistory.js","sourceRoot":"","sources":["containerKekPathHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,8BAA8B,EAC9B,6BAA6B,EAC7B,wBAAwB,EACxB,uBAAuB,EACvB,iCAAiC,EACjC,4BAA4B,EAC5B,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,iBAAiB,EACjB,mBAAmB,GACpB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,qBAAqB,EAAE,MAAM,4CAA4C,CAAC;AACnF,OAAO,EAAE,yBAAyB,EAAE,MAAM,iCAAiC,CAAC;AAC5E,OAAO,EAAE,uBAAuB,EAAE,MAAM,WAAW,CAAC;AAMpD,2FAA2F;AAC3F,MAAM,OAAO,mCAAoC,SAAQ,KAAK;IAC5D,YAAY,KAAa;QACvB,KAAK,CAAC,GAAG,KAAK,qBAAqB,CAAC,CAAC;QACrC,IAAI,CAAC,IAAI,GAAG,qCAAqC,CAAC;IACpD,CAAC;CACF;AAED,MAAM,UAAU,kBAAkB,CAAC,KAAa;IAC9C,OAAO,mCAAmC,KAAK,GAAG,CAAC;AACrD,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,4CAA4C,CAAC,KAOlE;IACC,IAAI,CAAC,wBAAwB,CAAC,KAAK,CAAC,GAAG,CAAC,mBAAmB,CAAC,E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AAK,CAAC,aAAa,CAAC,GAAG,CAAC,mBAAmB,CAAC,CACvE,CAAC;AACJ,CAAC","sourcesContent":["import {\n computeContainerKekKeyringHash,\n computeContainerKekMaterialId,\n isContainerKekMaterialId,\n KeyingVerificationError,\n normalizeContainerAccessEventBody,\n normalizeContainerKekKeyring,\n openContainerKekKeyring,\n type VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n readCanonicalJson,\n readCanonicalRecord,\n} from \"../../keying/canonicalJson\";\nimport { readContainerKeyEpoch } from \"../../keyingProjectionVerification/readers\";\nimport { verifyContainerKekEntries } from \"./containerKekEntryVerification\";\nimport { readManifestContainerId } from \"./readers\";\nimport type { UnwrappedContainerKek } from \"./types\";\n\ntype ProjectionKek = ContainerWriterProjectionResponse[\"containerKeks\"][number];\ntype VerifiedManifests = ReadonlyMap<string, VerifiedContainerAccessManifest>;\n\n/** The projection proves a predecessor existed, but no retained keyring can recover it. */\nexport class ContainerKekHistoryUnavailableError extends Error {\n constructor(label: string) {\n super(`${label} keyring is missing`);\n this.name = \"ContainerKekHistoryUnavailableError\";\n }\n}\n\nexport function projectionKekLabel(index: number): string {\n return `Container writer projection KEK[${index}]`;\n}\n\nexport async function assertUnwrappedContainerKekMatchesMaterialId(input: {\n label: string;\n keyMaterial: Uint8Array;\n kek: Pick<\n ProjectionKek,\n \"containerId\" | \"containerKeyEpoch\" | \"containerKeyEpochId\"\n >;\n}): Promise<void> {\n if (!isContainerKekMaterialId(input.kek.containerKeyEpochId)) {\n throw new Error(\n `${input.label} KEK epoch id does not commit to key material`,\n );\n }\n const expectedId = await computeContainerKekMaterialId({\n containerId: input.kek.containerId,\n keyEpoch: input.kek.containerKeyEpoch,\n keyMaterial: input.keyMaterial,\n });\n if (expectedId !== input.kek.containerKeyEpochId) {\n throw new Error(\n `${input.label} KEK material does not match committed epoch id`,\n );\n }\n}\n\nfunction sameContainerManifestHistory(kek: ProjectionKek) {\n return kek.containerManifestHistory.filter(\n (bundle) => readManifestContainerId(bundle) === kek.containerId,\n );\n}\n\n/**\n * Proves the served keyring is the one the rotation that minted the current\n * epoch committed to in its signed event body.\n */\nasync function assertKeyringCommitment(input: {\n currentManifest: ContainerWriterProjectionResponse[\"path\"][number];\n index: number;\n kek: ProjectionKek;\n keyring: ReturnType<typeof normalizeContainerKekKeyring>;\n}): Promise<void> {\n const rotationManifestHash = readContainerKeyEpoch(\n input.kek.keyEpoch,\n `${projectionKekLabel(input.index)} key epoch`,\n ).accessManifestHash;\n const rotationManifest =\n rotationManifestHash === input.currentManifest.manifestHash\n ? input.currentManifest\n : sameContainerManifestHistory(input.kek).find(\n (bundle) => bundle.manifestHash === rotationManifestHash,\n );\n if (!rotationManifest) {\n throw new Error(\n `${projectionKekLabel(input.index)} keyring signer is missing`,\n );\n }\n const eventBundle = readCanonicalRecord(\n rotationManifest.event,\n `${projectionKekLabel(input.index)} keyring event`,\n );\n const eventBody = normalizeContainerAccessEventBody(\n readCanonicalJson(\n Reflect.get(eventBundle, \"body\"),\n `${projectionKekLabel(input.index)} keyring event body`,\n ),\n );\n if (\n (eventBody.eventType !== \"container.move\" &&\n eventBody.eventType !== \"container.rekey\" &&\n eventBody.eventType !== \"container.revoke\") ||\n eventBody.keyringHash !==\n (await computeContainerKekKeyringHash(input.keyring))\n ) {\n throw new Error(\n `${projectionKekLabel(input.index)} keyring does not match its signed event`,\n );\n }\n}\n\nasync function openVerifiedKeyringEntries(input: {\n currentManifest: ContainerWriterProjectionResponse[\"path\"][number];\n index: number;\n kek: ProjectionKek;\n successorKeyMaterial: Uint8Array;\n verifiedByHash: VerifiedManifests;\n verifyKeyringCommitment: boolean;\n}): Promise<Awaited<ReturnType<typeof openContainerKekKeyring>>> {\n const { kek } = input;\n const keyring = normalizeContainerKekKeyring(kek.keyring);\n if (\n keyring.containerId !== kek.containerId ||\n keyring.containerKeyEpochId !== kek.containerKeyEpochId\n ) {\n throw new Error(\n `${projectionKekLabel(input.index)} keyring is inconsistent`,\n );\n }\n if (input.verifyKeyringCommitment) {\n await assertKeyringCommitment({\n currentManifest: input.currentManifest,\n index: input.index,\n kek,\n keyring,\n });\n }\n\n let entries: Awaited<ReturnType<typeof openContainerKekKeyring>>;\n try {\n entries = await openContainerKekKeyring({\n keyEpoch: kek.containerKeyEpoch,\n keyring,\n successorContainerKey: input.successorKeyMaterial,\n });\n } catch (error) {\n if (error instanceof KeyingVerificationError) {\n throw error;\n }\n // Label opaque AEAD failures; structural verification errors already\n // carry their own diagnosis.\n throw new Error(\n `${projectionKekLabel(input.index)} keyring could not be opened`,\n { cause: error },\n );\n }\n // Per-entry material-id verification proves an entry's key matches the id\n // it declares, but a poisoned keyring can declare a self-consistent FAKE\n // id — fresh key, matching commitment — for an epoch the container never\n // had. Anchor every entry the projection can name to the epoch id its\n // signed history actually committed; anything else is a forged epoch.\n await verifyContainerKekEntries(kek.containerId, entries);\n\n // Every epoch id the signed manifest history names must be present in the\n // keyring. A forged entry can be self-consistent, but it cannot also make\n // the real epoch id — which a signed state already named — disappear.\n const entryEpochIds = new Set(\n entries.map((entry) => entry.containerKeyEpochId),\n );\n const signedEpochIds = signedHistoryEpochIds({\n headManifestHash: input.currentManifest.manifestHash,\n kek,\n verifiedByHash: input.verifiedByHash,\n });\n for (const historicalEpochId of signedEpochIds) {\n if (!entryEpochIds.has(historicalEpochId)) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n `${projectionKekLabel(input.index)} keyring omits an epoch its manifest history commits to`,\n );\n }\n }\n return entries;\n}\n\n/**\n * Epoch ids named by verified historical manifest states for this container.\n * Those states are signed, so an id they name is an epoch the container\n * provably had — and a keyring that omits it in favor of a forged id for the\n * same position is detectable even when no epoch RECORD was shipped.\n */\nexport function manifestHistoryEpochIds(kek: ProjectionKek): Set<string> {\n const epochIds = new Set<string>();\n for (const bundle of sameContainerManifestHistory(kek)) {\n const state = readCanonicalRecord(\n bundle.state,\n \"Container writer projection historical manifest state\",\n );\n const containerKeyEpochId = Reflect.get(state, \"containerKeyEpochId\");\n if (\n typeof containerKeyEpochId === \"string\" &&\n containerKeyEpochId !== kek.containerKeyEpochId\n ) {\n epochIds.add(containerKeyEpochId);\n }\n }\n return epochIds;\n}\n\n/**\n * The epoch ids this KEK's own history names, plus every one its head's\n * verified lineage names wherever the projection served it. Verification pools\n * every KEK's history, so a server can serve a container's older manifests\n * under another KEK; walking the lineage keeps a forged keyring id from passing\n * because the real id it displaces moved (#2365 finding 32). The walk stops at\n * the first manifest verification did not record, so it only ever adds ids.\n */\nexport function signedHistoryEpochIds(input: {\n readonly headManifestHash: string;\n readonly kek: ProjectionKek;\n readonly verifiedByHash: VerifiedManifests;\n}): Set<string> {\n const epochIds = manifestHistoryEpochIds(input.kek);\n const visited = new Set<string>();\n let current = input.verifiedByHash.get(input.headManifestHash);\n while (\n current &&\n current.state.containerId === input.kek.containerId &&\n !visited.has(current.manifestHash)\n ) {\n visited.add(current.manifestHash);\n const epochId = current.state.containerKeyEpochId;\n if (epochId !== null && epochId !== input.kek.containerKeyEpochId) {\n epochIds.add(epochId);\n }\n const previousHash = current.state.previousManifestHash;\n current =\n previousHash === null\n ? undefined\n : input.verifiedByHash.get(previousHash);\n }\n return epochIds;\n}\n\nfunction admitKeyringEntry(input: {\n entry: Awaited<ReturnType<typeof openContainerKekKeyring>>[number];\n index: number;\n kek: ProjectionKek;\n keksByEpochId: Map<string, UnwrappedContainerKek>;\n}): void {\n const { entry, kek } = input;\n const cached = input.keksByEpochId.get(entry.containerKeyEpochId);\n if (cached) {\n if (cached.containerId !== kek.containerId) {\n throw new Error(\n `${projectionKekLabel(input.index)} cached historical KEK is inconsistent`,\n );\n }\n return;\n }\n input.keksByEpochId.set(entry.containerKeyEpochId, {\n containerId: kek.containerId,\n // A keyring entry is key material plus the epoch id that commits to it —\n // there is no epoch record, so no fingerprint. Selection falls back to the\n // epoch id and AEAD authenticates; the commitment check above is what\n // makes the material itself trustworthy.\n keyEpochHash: null,\n keyMaterial: entry.keyMaterial,\n });\n}\n\n/**\n * Opens the sealed keyring for one path index and admits every entry into\n * `keksByEpochId` after verifying it against the material-id commitment its\n * ordinal position implies (entry i is key epoch i + 1). No chain walk:\n * one decrypt yields the container's complete retained history, and entry\n * verification is independent per entry.\n */\nexport async function unwrapKeyringContainerKeksAtIndex(input: {\n currentManifest: ContainerWriterProjectionResponse[\"path\"][number];\n index: number;\n kek: ProjectionKek;\n keksByEpochId: Map<string, UnwrappedContainerKek>;\n successorKeyMaterial: Uint8Array | null;\n /** Every manifest projection verification recorded; anchors the keyring. */\n verifiedByHash: VerifiedManifests;\n verifyKeyringCommitment: boolean;\n}): Promise<void> {\n const { kek, successorKeyMaterial } = input;\n if (!successorKeyMaterial) {\n return;\n }\n\n if (kek.keyring === null) {\n if (kek.containerKeyEpoch !== 1) {\n throw new ContainerKekHistoryUnavailableError(\n projectionKekLabel(input.index),\n );\n }\n return;\n }\n\n const entries = await openVerifiedKeyringEntries({\n currentManifest: input.currentManifest,\n index: input.index,\n kek,\n successorKeyMaterial,\n verifiedByHash: input.verifiedByHash,\n verifyKeyringCommitment: input.verifyKeyringCommitment,\n });\n for (const entry of entries) {\n admitKeyringEntry({\n entry,\n index: input.index,\n kek,\n keksByEpochId: input.keksByEpochId,\n });\n }\n}\n\n/**\n * Epoch ids this projection implies exist but that were not recovered —\n * used to attribute history failures to the material they orphan.\n */\nexport function projectedUnreachablePredecessorEpochIds(input: {\n kek: ProjectionKek;\n keksByEpochId: ReadonlyMap<string, UnwrappedContainerKek>;\n}): string[] {\n const projectedEpochIds = new Set<string>();\n for (const bundle of sameContainerManifestHistory(input.kek)) {\n const state = readCanonicalRecord(\n bundle.state,\n \"Container writer projection historical manifest state\",\n );\n const containerKeyEpochId = Reflect.get(state, \"containerKeyEpochId\");\n if (typeof containerKeyEpochId === \"string\") {\n projectedEpochIds.add(containerKeyEpochId);\n }\n }\n projectedEpochIds.delete(input.kek.containerKeyEpochId);\n return [...projectedEpochIds].filter(\n (containerKeyEpochId) => !input.keksByEpochId.has(containerKeyEpochId),\n );\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"containerKekPathVerification.js","sourceRoot":"","sources":["containerKekPathVerification.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,iDAAiD,GAElD,MAAM,oCAAoC,CAAC;AAG5C,OAAO,EAAE,yBAAyB,EAAE,MAAM,SAAS,CAAC;AAYpD,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,KAAkC;IAElC,IAAI,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,KAAK,KAAK,CAAC,UAAU,CAAC,aAAa,CAAC,MAAM,EAAE,CAAC;QAC3E,MAAM,IAAI,KAAK,CACb,4DAA4D,CAC7D,CAAC;IACJ,CAAC;IACD,MAAM,wBAAwB,GAAG,yBAAyB,CACxD,KAAK,EACL,sBAAsB,CACvB,CAAC;IACF,IACE,KAAK,CAAC,sBAAsB,KAAK,IAAI;QACrC,wBAAwB,KAAK,IAAI,EACjC,CAAC;QACD,OAAO;IACT,CAAC;IAED,MAAM,iDAAiD,CAAC;QACtD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,8BAA8B,EAAE,KAAK,CAAC,8BAA8B;QACpE,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,cAAc,EAAE,wBAAwB;QACxC,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;KACvE,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { VerifiedContainerAccessManifest } from \"@tearleads/crypto\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n collectContainerWriterProjectionPrincipalPolicies,\n type PrincipalPolicyCache,\n} from \"../../keyingProjectionVerification\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type { ProjectionVerificationOptions } from \"./types\";\nimport { resolveProjectionVerifier } from \"./types\";\n\nexport type UnwrapContainerKekPathInput = {\n execSql?: ExecSql | undefined;\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n persistVerificationCheckpoints?: boolean | undefined;\n principalPolicyCache?: PrincipalPolicyCache | undefined;\n projection: ContainerWriterProjectionResponse;\n secretKey: Uint8Array;\n verifiedByHash?: Map<string, VerifiedContainerAccessManifest> | undefined;\n} & ProjectionVerificationOptions;\n\nexport async function verifyContainerKekPathProjection(\n input: UnwrapContainerKekPathInput,\n): Promise<void> {\n if (input.projection.path.length !== input.projection.containerKeks.length) {\n throw new Error(\n \"Container writer projection path and KEKs are inconsistent\",\n );\n }\n const resolveProjectionUserKey = resolveProjectionVerifier(\n input,\n \"Container KEK unwrap\",\n );\n if (\n input.trustedLocalProjection === true ||\n resolveProjectionUserKey === null\n ) {\n return;\n }\n\n await collectContainerWriterProjectionPrincipalPolicies({\n execSql: input.execSql,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n principalPolicyCache: input.principalPolicyCache,\n projection: input.projection,\n resolveUserKey: resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n verifiedByHash: input.verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"containerKekWrapping.js","sourceRoot":"","sources":["containerKekWrapping.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,mCAAmC,EACnC,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,IAAI,aAAa,EAAE,MAAM,qCAAqC,CAAC;AAErF,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAAE,uBAAuB,EAAE,MAAM,WAAW,CAAC;AAGpD,MAAM,CAAC,KAAK,UAAU,gCAAgC,CAAC,KAKtD;IACC,IAAI,CAAC,KAAK,CAAC,yBAAyB,EAAE,CAA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MAAM,QAAQ,GAAG,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACxC,IAAI,CAAC,QAAQ,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,KAAK,CAAC;QAC7C,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;IACnD,MAAM,WAAW,GAAG,uBAAuB,CAAC,QAAQ,CAAC,CAAC;IACtD,IAAI,CAAC,WAAW;QAAE,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;IACtE,MAAM,SAAS,GAAG,MAAM,mCAAmC,CAAC;QAC1D,WAAW;QACX,WAAW;KACZ,CAAC,CAAC;IACH,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,EAAE,uBAAuB,CAAC,KAAK,SAAS,EAAE,CAAC;QACvE,MAAM,IAAI,KAAK,CACb,GAAG,kBAAkB,CAAC,KAAK,CAAC,kDAAkD,CAC/E,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import {\n type ContainerKeyWrap,\n deriveContainerKekWrappingPublicKey,\n unwrapContainerKekParentWrap,\n} from \"@tearleads/crypto\";\nimport { isPlainObject as isPlainRecord } from \"@tearleads/validators/isPlainObject\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { projectionKekLabel } from \"./containerKekPathHistory\";\nimport { readManifestContainerId } from \"./readers\";\nimport type { UnwrappedContainerKek } from \"./types\";\n\nexport async function unwrapContainerKekFromParentWrap(input: {\n label: string;\n parentContainerKeyEpochId: string | null;\n parentKeksByEpochId: ReadonlyMap<string, UnwrappedContainerKek>;\n wraps: readonly ContainerKeyWrap[];\n}): Promise<Uint8Array | null> {\n if (!input.parentContainerKeyEpochId) {\n return null;\n }\n\n const parentKek = input.parentKeksByEpochId.get(\n input.parentContainerKeyEpochId,\n );\n if (!parentKek) {\n return null;\n }\n\n // The epoch-record fingerprint is a SELECTOR for picking the right envelope\n // among several, not the security boundary — the AEAD tag below is what\n // authenticates the parent key. Keyring-recovered historical KEKs carry no\n // epoch record (only the material and the epoch id that commits to it), so\n // for those the epoch id alone selects and decryption authenticates.\n //\n // Without this, an ancestor rotation would strand every descendant still\n // pinned to the predecessor epoch: opening the descendant requires the\n // parent's historical KEK, and that is exactly the key a lazy rekey needs in\n // order to materialize a post-rotation epoch. A cold client would have no\n // way back in.\n const parentWrap = input.wraps.find(\n (wrap) =>\n wrap.recipientKind === \"container\" &&\n wrap.recipientId === parentKek.containerId &&\n wrap.recipientKeyEpochId === input.parentContainerKeyEpochId &&\n (parentKek.keyEpochHash === null ||\n wrap.recipientKeyFingerprint === parentKek.keyEpochHash),\n );\n if (!parentWrap) {\n return null;\n }\n\n try {\n return await unwrapContainerKekParentWrap({\n parentContainerId: parentKek.containerId,\n parentKeyMaterial: parentKek.keyMaterial,\n kemCipherText: parentWrap.kemCipherText,\n wrappedKey: parentWrap.wrappedKey,\n });\n } catch (error) {\n throw new Error(`${input.label} parent wrap could not be unwrapped`, {\n cause: error,\n });\n }\n}\n\nexport async function assertSignedWrappingPublicKey(\n projection: ContainerWriterProjectionResponse,\n index: number,\n keyMaterial: Uint8Array,\n): Promise<void> {\n const manifest = projection.path[index];\n if (!manifest || !isPlainRecord(manifest.state))\n throw new Error(\"Container manifest is missing\");\n const containerId = readManifestContainerId(manifest);\n if (!containerId) throw new Error(\"Container manifest ID is missing\");\n const publicKey = await deriveContainerKekWrappingPublicKey({\n containerId,\n keyMaterial,\n });\n if (Reflect.get(manifest.state, \"containerKeyPublicKey\") !== publicKey) {\n throw new Error(\n `${projectionKekLabel(index)} wrapping public key does not match KEK material`,\n );\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"documentSyncUpdateDecryption.js","sourceRoot":"","sources":["documentSyncUpdateDecryption.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,+BAA+B,EAC/B,mCAAmC,EACnC,0CAA0C,EAC1C,wCAAwC,GACzC,MAAM,mBAAmB,CAAC;AAC3B,OA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KAAK,CAAC,MAAM,CAAC,EAAE;QACnB,uBAAuB,EAAE,KAAK,CAAC,MAAM,CAAC,uBAAuB;QAC7D,yBAAyB,EAAE,KAAK,CAAC,MAAM,CAAC,yBAAyB;QACjE,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,mBAAmB,KAAK,SAAS;YAChD,CAAC,CAAC,EAAE;YACJ,CAAC,CAAC,EAAE,mBAAmB,EAAE,KAAK,CAAC,MAAM,CAAC,mBAAmB,EAAE,CAAC;QAC9D,UAAU;KACX,CAAC;AACJ,CAAC","sourcesContent":["import {\n assertAesGcmIv,\n CONTENT_RECORD_ENCRYPTION_SUITE,\n computeContentRecordNonceDomainHash,\n computeDocumentContentRecordCiphertextHash,\n computeDocumentContentRecordMetadataHash,\n} from \"@tearleads/crypto\";\nimport { base64ToBytes } from \"@tearleads/encoding\";\nimport { versionVectorsEqual } from \"@tearleads/loro\";\nimport { isPlainObject as isPlainRecord } from \"@tearleads/validators/isPlainObject\";\nimport type { DocumentSyncResponse } from \"@tearleads/validators/response\";\nimport { contentRecordAdditionalDataBytes } from \"./contentRecordAdditionalData\";\nimport {\n deriveDocumentContentRecordKey,\n deriveDocumentPlaintextHashKey,\n} from \"./contentRecordKeys\";\nimport { isolateDocumentSyncUpdateError } from \"./documentSyncUpdateIsolation\";\nimport { assertDecryptedDocumentUpdateMetadata } from \"./documentUpdateIntegrity\";\nimport { assertDocumentUpdatePlaintextHash } from \"./plaintextHash\";\nimport {\n assertOnlyRecordKeys,\n asWebCryptoBytes,\n readRecordPositiveInteger,\n readRecordString,\n readWriteHeader,\n} from \"./readers\";\nimport {\n type DecryptedDocumentSyncUpdate,\n DOCUMENT_ENCRYPTED_LORO_UPDATE_FORMAT,\n DOCUMENT_ENCRYPTED_UPDATE_KEYS,\n type ParsedDocumentEncryptedUpdate,\n} from \"./types\";\n\ntype SyncResponseUpdate = DocumentSyncResponse[\"updates\"][number];\n\nfunction parseDocumentEncryptedUpdate(\n encryptedData: string,\n): ParsedDocumentEncryptedUpdate {\n let value: unknown;\n try {\n value = JSON.parse(encryptedData);\n } catch {\n throw new Error(\"Document encrypted update is invalid JSON\");\n }\n if (!isPlainRecord(value)) {\n throw new Error(\"Document encrypted update must be an object\");\n }\n assertOnlyRecordKeys(\n value,\n DOCUMENT_ENCRYPTED_UPDATE_KEYS,\n \"Document encrypted update\",\n );\n if (\n readRecordString(value, \"format\", \"Document encrypted update\") !==\n DOCUMENT_ENCRYPTED_LORO_UPDATE_FORMAT\n ) {\n throw new Error(\"Document encrypted update format is invalid\");\n }\n const version = readRecordPositiveInteger(\n value,\n \"version\",\n \"Document encrypted update\",\n );\n if (version !== 1) {\n throw new Error(\n `Document encrypted update version ${version} is invalid; expected 1`,\n );\n }\n if (\n readRecordString(value, \"encryptionSuite\", \"Document encrypted update\") !==\n CONTENT_RECORD_ENCRYPTION_SUITE\n ) {\n throw new Error(\"Document encrypted update suite is invalid\");\n }\n\n const iv = base64ToBytes(\n readRecordString(value, \"iv\", \"Document encrypted update\"),\n );\n assertAesGcmIv(iv, \"Document encrypted update IV is invalid\");\n return {\n ciphertext: base64ToBytes(\n readRecordString(value, \"ciphertext\", \"Document encrypted update\"),\n ),\n contentKeyEpoch: readRecordPositiveInteger(\n value,\n \"contentKeyEpoch\",\n \"Document encrypted update\",\n ),\n contentRecordId: readRecordString(\n value,\n \"contentRecordId\",\n \"Document encrypted update\",\n ),\n metadataHash: readRecordString(\n value,\n \"metadataHash\",\n \"Document encrypted update\",\n ),\n nonceDomainHash: readRecordString(\n value,\n \"nonceDomainHash\",\n \"Document encrypted update\",\n ),\n iv,\n };\n}\n\nasync function assertDocumentEncryptedUpdateMatchesHeader(input: {\n contentKeyEpoch: number;\n documentId: string;\n encrypted: ParsedDocumentEncryptedUpdate;\n encryptedData: string;\n organizationId: string;\n update: SyncResponseUpdate;\n}): Promise<void> {\n const { encrypted, update } = input;\n const hasCheckpointMetadata =\n update.checkpointKind !== undefined ||\n update.checkpointPayloadKind !== undefined ||\n update.sourceVersionVector !== undefined;\n if (\n hasCheckpointMetadata &&\n (update.checkpointKind !== \"rotate_baseline\" ||\n update.checkpointPayloadKind !== \"full_history_snapshot\" ||\n !update.sourceVersionVector ||\n !versionVectorsEqual(\n update.sourceVersionVector,\n update.partialEndVersionVector,\n ))\n ) {\n throw new Error(\"Document rotation checkpoint metadata mismatch\");\n }\n if (encrypted.contentKeyEpoch !== input.contentKeyEpoch) {\n throw new Error(\"Document encrypted update content-key epoch mismatch\");\n }\n if (update.documentId !== input.documentId) {\n throw new Error(\"Document encrypted update document id mismatch\");\n }\n if (\n encrypted.contentRecordId !==\n readRecordString(update.writeHeader, \"contentRecordId\", \"write header\")\n ) {\n throw new Error(\"Document encrypted update content record mismatch\");\n }\n\n const metadataHash = await computeDocumentContentRecordMetadataHash({\n ...(update.checkpointKind === undefined\n ? {}\n : { checkpointKind: update.checkpointKind }),\n ...(update.checkpointPayloadKind === undefined\n ? {}\n : { checkpointPayloadKind: update.checkpointPayloadKind }),\n documentId: input.documentId,\n partialEndVersionVector: update.partialEndVersionVector,\n partialStartVersionVector: update.partialStartVersionVector,\n plaintextHash: update.plaintextHash,\n ...(update.sourceVersionVector === undefined\n ? {}\n : { sourceVersionVector: update.sourceVersionVector }),\n updateId: update.id,\n });\n if (\n encrypted.metadataHash !== metadataHash ||\n encrypted.metadataHash !==\n readRecordString(update.writeHeader, \"metadataHash\", \"write header\")\n ) {\n throw new Error(\"Document encrypted update metadata hash mismatch\");\n }\n\n const nonceDomainHash = await computeContentRecordNonceDomainHash({\n version: 1,\n organizationId: input.organizationId,\n objectKind: \"document\",\n objectId: input.documentId,\n contentKeyEpoch: input.contentKeyEpoch,\n encryptionSuite: CONTENT_RECORD_ENCRYPTION_SUITE,\n contentRecordId: encrypted.contentRecordId,\n });\n if (\n encrypted.nonceDomainHash !== nonceDomainHash ||\n encrypted.nonceDomainHash !==\n readRecordString(update.writeHeader, \"nonceDomainHash\", \"write header\")\n ) {\n throw new Error(\"Document encrypted update nonce domain mismatch\");\n }\n const ciphertextHash = await computeDocumentContentRecordCiphertextHash(\n input.encryptedData,\n );\n if (\n ciphertextHash !==\n readRecordString(update.writeHeader, \"ciphertextHash\", \"write header\")\n ) {\n throw new Error(\"Document encrypted update ciphertext hash mismatch\");\n }\n}\n\nasync function verifiedEncryptedSyncUpdate(input: {\n contentKeyEpoch: number;\n documentId: string;\n organizationId: string;\n update: SyncResponseUpdate;\n}): Promise<ParsedDocumentEncryptedUpdate> {\n try {\n const encrypted = parseDocumentEncryptedUpdate(input.update.encryptedData);\n await assertDocumentEncryptedUpdateMatchesHeader({\n encrypted,\n encryptedData: input.update.encryptedData,\n ...input,\n });\n return encrypted;\n } catch (error) {\n throw isolateDocumentSyncUpdateError({\n cause: error,\n responseUpdate: input.update,\n stage: \"encrypted_record\",\n updateId: input.update.id,\n });\n }\n}\n\n/** Verifies the encrypted record's structure and every binding to its header. */\nexport async function assertDocumentSyncUpdateEncryptedRecord(\n update: SyncResponseUpdate,\n): Promise<void> {\n let contentKeyEpoch: number;\n let documentId: string;\n let organizationId: string;\n try {\n const header = readWriteHeader(\n update.writeHeader,\n \"Document sync response write header\",\n );\n if (header.objectKind !== \"document\") {\n throw new Error(\"Document sync response write header kind mismatch\");\n }\n contentKeyEpoch = header.contentKeyEpoch;\n documentId = header.objectId;\n organizationId = header.organizationId;\n } catch (error) {\n throw isolateDocumentSyncUpdateError({\n cause: error,\n responseUpdate: update,\n stage: \"write_header\",\n updateId: update.id,\n });\n }\n await verifiedEncryptedSyncUpdate({\n contentKeyEpoch,\n documentId,\n organizationId,\n update,\n });\n}\n\nasync function decryptPayload(input: {\n contentKeyEpoch: number;\n contentKeyMaterial: CryptoKey;\n documentId: string;\n encrypted: ParsedDocumentEncryptedUpdate;\n organizationId: string;\n update: SyncResponseUpdate;\n}): Promise<{ plaintextHashKey: CryptoKey; updateData: Uint8Array }> {\n try {\n const keyInput = {\n contentKeyMaterial: input.contentKeyMaterial,\n contentKeyEpoch: input.contentKeyEpoch,\n contentRecordId: input.encrypted.contentRecordId,\n documentId: input.documentId,\n organizationId: input.organizationId,\n };\n const [recordKey, plaintextHashKey] = await Promise.all([\n deriveDocumentContentRecordKey({ ...keyInput, usage: \"decrypt\" }),\n deriveDocumentPlaintextHashKey(keyInput),\n ]);\n const updateData = new Uint8Array(\n await crypto.subtle.decrypt(\n {\n name: \"AES-GCM\",\n iv: asWebCryptoBytes(input.encrypted.iv),\n additionalData: contentRecordAdditionalDataBytes({\n contentKeyEpoch: input.contentKeyEpoch,\n contentRecordId: input.encrypted.contentRecordId,\n documentId: input.documentId,\n metadataHash: input.encrypted.metadataHash,\n nonceDomainHash: input.encrypted.nonceDomainHash,\n organizationId: input.organizationId,\n }),\n },\n recordKey,\n asWebCryptoBytes(input.encrypted.ciphertext),\n ),\n );\n return { plaintextHashKey, updateData };\n } catch (error) {\n throw isolateDocumentSyncUpdateError({\n cause: error,\n responseUpdate: input.update,\n stage: \"decrypt\",\n updateId: input.update.id,\n });\n }\n}\n\nexport async function decryptDocumentSyncUpdate(input: {\n contentKeyEpoch: number;\n contentKeyMaterial: CryptoKey;\n documentId: string;\n organizationId: string;\n update: SyncResponseUpdate;\n}): Promise<DecryptedDocumentSyncUpdate> {\n const encrypted = await verifiedEncryptedSyncUpdate(input);\n const { plaintextHashKey, updateData } = await decryptPayload({\n ...input,\n encrypted,\n });\n try {\n await assertDocumentUpdatePlaintextHash(\n updateData,\n input.update.plaintextHash,\n plaintextHashKey,\n );\n } catch (error) {\n throw isolateDocumentSyncUpdateError({\n cause: error,\n responseUpdate: input.update,\n stage: \"plaintext_integrity\",\n updateId: input.update.id,\n });\n }\n try {\n assertDecryptedDocumentUpdateMetadata(updateData, input.update);\n } catch (error) {\n throw isolateDocumentSyncUpdateError({\n cause: error,\n responseUpdate: input.update,\n stage: \"loro_metadata\",\n updateId: input.update.id,\n });\n }\n return {\n ...(input.update.checkpointKind === undefined\n ? {}\n : { checkpointKind: input.update.checkpointKind }),\n ...(input.update.checkpointPayloadKind === undefined\n ? {}\n : { checkpointPayloadKind: input.update.checkpointPayloadKind }),\n id: input.update.id,\n partialEndVersionVector: input.update.partialEndVersionVector,\n partialStartVersionVector: input.update.partialStartVersionVector,\n ...(input.update.sourceVersionVector === undefined\n ? {}\n : { sourceVersionVector: input.update.sourceVersionVector }),\n updateData,\n };\n}\n"]}