@tearleads/client-sdk 0.1.64 → 0.1.66

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 (646) 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 +14 -1
  113. package/data/persistence/container-contents/documentPurgePlacement.js.map +1 -1
  114. package/data/persistence/container-contents/dormantContainerMetadata.js +1 -1
  115. package/data/persistence/container-contents/dormantMetadataSweep.js +1 -1
  116. package/data/persistence/container-contents/pendingContainerCreate.js +1 -1
  117. package/data/persistence/container-contents/supersededContainerBindings.js +1 -1
  118. package/data/persistence/containers/containerPersistence.js +1 -1
  119. package/data/persistence/containers/containerSyncWatermarkPersistence.js +1 -1
  120. package/data/persistence/containers/documentContainerProjectionPersistence.js +1 -1
  121. package/data/persistence/containers/documentPlacement.js +1 -1
  122. package/data/persistence/documents/containerDocumentTombstoneHoldsPersistence.js +1 -1
  123. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js +3 -3
  124. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js.map +1 -1
  125. package/data/persistence/documents/documentDiscoveryReset.js +1 -1
  126. package/data/persistence/documents/documentDiscoveryReset.js.map +1 -1
  127. package/data/persistence/documents/documentsPersistence.js +3 -3
  128. package/data/persistence/documents/documentsPersistence.js.map +1 -1
  129. package/data/persistence/documents/internal/attachmentStagingPersistence.js +1 -1
  130. package/data/persistence/documents/internal/containerDocumentTombstoneHolds.js +1 -1
  131. package/data/persistence/documents/internal/containerDocumentTombstones.js +1 -1
  132. package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js +2 -2
  133. package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js.map +1 -1
  134. package/data/persistence/documents/internal/discardDocument.js +3 -3
  135. package/data/persistence/documents/internal/discardDocument.js.map +1 -1
  136. package/data/persistence/documents/internal/documentDeletionPersistence.js +4 -4
  137. package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
  138. package/data/persistence/documents/internal/documentMutationPersistence.js +5 -5
  139. package/data/persistence/documents/internal/documentMutationPersistence.js.map +1 -1
  140. package/data/persistence/documents/internal/documentProjectionRows.js +1 -1
  141. package/data/persistence/documents/internal/documentPullContinuationPersistence.js +1 -1
  142. package/data/persistence/documents/internal/documentRows.js +2 -2
  143. package/data/persistence/documents/internal/documentRows.js.map +1 -1
  144. package/data/persistence/documents/internal/documentSummaryQueries.js +1 -1
  145. package/data/persistence/documents/internal/ensureDocumentsSchema.js +2 -2
  146. package/data/persistence/documents/internal/hydratedAttachmentPersistence.js +1 -1
  147. package/data/persistence/documents/internal/orphanSideRows.js +2 -2
  148. package/data/persistence/documents/internal/orphanSideRows.js.map +1 -1
  149. package/data/persistence/documents/internal/pendingCreateAdoption.js +1 -1
  150. package/data/persistence/documents/internal/rowQueryPersistence.js +2 -2
  151. package/data/persistence/documents/internal/syncQueuePersistence.js +3 -3
  152. package/data/persistence/documents/internal/syncQueuePersistence.js.map +1 -1
  153. package/data/persistence/documents/types.d.ts +3 -3
  154. package/data/persistence/documents/types.js.map +1 -1
  155. package/data/persistence/{documentPurgeCheckpointPersistence.d.ts → keyingCheckpoints/documentPurgeCheckpointPersistence.d.ts} +2 -2
  156. package/data/persistence/{documentPurgeCheckpointPersistence.js → keyingCheckpoints/documentPurgeCheckpointPersistence.js} +4 -4
  157. package/data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence.js.map +1 -0
  158. package/data/persistence/{keyingCheckpointAdvancePersistence.js → keyingCheckpoints/keyingCheckpointAdvancePersistence.js} +9 -9
  159. package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js.map +1 -0
  160. package/data/persistence/{keyingCheckpointEvidence.js → keyingCheckpoints/keyingCheckpointEvidence.js} +1 -1
  161. package/data/persistence/{keyingCheckpointPersistence.js → keyingCheckpoints/keyingCheckpointPersistence.js} +5 -5
  162. package/data/persistence/keyingCheckpoints/keyingCheckpointPersistence.js.map +1 -0
  163. package/data/persistence/{locallyAcknowledgedCheckpointPersistence.d.ts → keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.d.ts} +4 -4
  164. package/data/persistence/{locallyAcknowledgedCheckpointPersistence.js → keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js} +7 -7
  165. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js.map +1 -0
  166. package/data/persistence/{organizationReplacementCheckpointPersistence.js → keyingCheckpoints/organizationReplacementCheckpointPersistence.js} +6 -6
  167. package/data/persistence/keyingCheckpoints/organizationReplacementCheckpointPersistence.js.map +1 -0
  168. package/data/persistence/{principalAuthorizationCheckpoints.js → keyingCheckpoints/principalAuthorizationCheckpoints.js} +1 -1
  169. package/data/persistence/keyingCheckpoints/principalAuthorizationCheckpoints.js.map +1 -0
  170. package/data/persistence/organizationFounderPersistence.js +2 -2
  171. package/data/persistence/organizationFounderPersistence.js.map +1 -1
  172. package/data/persistence/organizations/organizationAccessRevocationPersistence.js +3 -3
  173. package/data/persistence/organizations/organizationAccessRevocationPersistence.js.map +1 -1
  174. package/data/persistence/organizations/organizationDataUsagePersistence.js +2 -2
  175. package/data/persistence/organizations/organizationDataUsagePersistence.js.map +1 -1
  176. package/data/persistence/organizations/organizationGroupNamePersistence.js +2 -2
  177. package/data/persistence/organizations/organizationGroupNamePersistence.js.map +1 -1
  178. package/data/persistence/organizations/organizationPresentationDenialPersistence.js +2 -2
  179. package/data/persistence/organizations/organizationPresentationDenialPersistence.js.map +1 -1
  180. package/data/persistence/organizations/organizationProfileDocumentPointers.js +2 -2
  181. package/data/persistence/organizations/organizationProfileDocumentPointers.js.map +1 -1
  182. package/data/persistence/organizations/organizationProvisioningAttemptPersistence.js +1 -1
  183. package/data/persistence/organizations/organizationProvisioningAttemptPersistence.js.map +1 -1
  184. package/data/persistence/organizations/organizationReadModelGrantPersistence.js +1 -1
  185. package/data/persistence/organizations/organizationReadModelGrantPersistence.js.map +1 -1
  186. package/data/persistence/organizations/organizationReadModelMemberLoad.js +1 -1
  187. package/data/persistence/organizations/organizationReadModelMemberLoad.js.map +1 -1
  188. package/data/persistence/organizations/organizationReadModelMembershipPersistence.js +1 -1
  189. package/data/persistence/organizations/organizationReadModelMembershipPersistence.js.map +1 -1
  190. package/data/persistence/organizations/organizationReadModelPersistence.js +3 -3
  191. package/data/persistence/organizations/organizationReadModelPersistence.js.map +1 -1
  192. package/data/persistence/organizations/organizationReadModelProjection.js +1 -1
  193. package/data/persistence/organizations/organizationReadModelProjection.js.map +1 -1
  194. package/data/persistence/organizations/organizationReadModelPurge.js +3 -3
  195. package/data/persistence/organizations/organizationReadModelPurge.js.map +1 -1
  196. package/data/persistence/principalCurrentAcknowledgementPersistence.d.ts +3 -3
  197. package/data/persistence/principalCurrentAcknowledgementPersistence.js +10 -10
  198. package/data/persistence/principalCurrentAcknowledgementPersistence.js.map +1 -1
  199. package/data/persistence/{principalHistoryEvidencePersistence.d.ts → principalHistory/principalHistoryEvidencePersistence.d.ts} +4 -4
  200. package/data/persistence/{principalHistoryEvidencePersistence.js → principalHistory/principalHistoryEvidencePersistence.js} +7 -7
  201. package/data/persistence/principalHistory/principalHistoryEvidencePersistence.js.map +1 -0
  202. package/data/persistence/{principalHistoryIncompleteRetention.js → principalHistory/principalHistoryIncompleteRetention.js} +1 -1
  203. package/data/persistence/principalHistory/principalHistoryIncompleteRetention.js.map +1 -0
  204. package/data/persistence/{principalHistoryNodeRetention.js → principalHistory/principalHistoryNodeRetention.js} +4 -4
  205. package/data/persistence/principalHistory/principalHistoryNodeRetention.js.map +1 -0
  206. package/data/persistence/{principalHistoryPrefixPersistence.d.ts → principalHistory/principalHistoryPrefixPersistence.d.ts} +2 -2
  207. package/data/persistence/{principalHistoryPrefixPersistence.js → principalHistory/principalHistoryPrefixPersistence.js} +6 -6
  208. package/data/persistence/principalHistory/principalHistoryPrefixPersistence.js.map +1 -0
  209. package/data/persistence/{principalHistoryRootOwnership.js → principalHistory/principalHistoryRootOwnership.js} +1 -1
  210. package/data/persistence/principalHistory/principalHistoryRootOwnership.js.map +1 -0
  211. package/data/persistence/{principalHistoryStagePersistence.d.ts → principalHistory/principalHistoryStagePersistence.d.ts} +2 -2
  212. package/data/persistence/{principalHistoryStagePersistence.js → principalHistory/principalHistoryStagePersistence.js} +6 -6
  213. package/data/persistence/principalHistory/principalHistoryStagePersistence.js.map +1 -0
  214. package/data/persistence/{principalHistoryStageRetention.js → principalHistory/principalHistoryStageRetention.js} +2 -2
  215. package/data/persistence/principalHistory/principalHistoryStageRetention.js.map +1 -0
  216. package/data/persistence/{principalHistoryUnpublishedRetention.js → principalHistory/principalHistoryUnpublishedRetention.js} +3 -3
  217. package/data/persistence/principalHistory/principalHistoryUnpublishedRetention.js.map +1 -0
  218. package/data/persistence/{principalGrantRetirementPersistence.d.ts → principalKeys/principalGrantRetirementPersistence.d.ts} +2 -2
  219. package/data/persistence/{principalGrantRetirementPersistence.js → principalKeys/principalGrantRetirementPersistence.js} +2 -2
  220. package/data/persistence/principalKeys/principalGrantRetirementPersistence.js.map +1 -0
  221. package/data/persistence/{principalKeyEnvelopeArchivePersistence.js → principalKeys/principalKeyEnvelopeArchivePersistence.js} +3 -3
  222. package/data/persistence/principalKeys/principalKeyEnvelopeArchivePersistence.js.map +1 -0
  223. package/data/persistence/{principalKeyEnvelopeCandidates.js → principalKeys/principalKeyEnvelopeCandidates.js} +9 -9
  224. package/data/persistence/principalKeys/principalKeyEnvelopeCandidates.js.map +1 -0
  225. package/data/persistence/principalMutationJournalPersistence.d.ts +1 -1
  226. package/data/persistence/principalMutationJournalPersistence.js +1 -1
  227. package/data/persistence/principalMutationJournalPersistence.js.map +1 -1
  228. package/data/persistence/{principalPolicyBundleIntegrity.js → principalPolicy/principalPolicyBundleIntegrity.js} +3 -3
  229. package/data/persistence/principalPolicy/principalPolicyBundleIntegrity.js.map +1 -0
  230. package/data/persistence/{principalPolicyCheckpointSelection.js → principalPolicy/principalPolicyCheckpointSelection.js} +2 -2
  231. package/data/persistence/principalPolicy/principalPolicyCheckpointSelection.js.map +1 -0
  232. package/data/persistence/{principalPolicyOrganizationPersistence.js → principalPolicy/principalPolicyOrganizationPersistence.js} +2 -2
  233. package/data/persistence/principalPolicy/principalPolicyOrganizationPersistence.js.map +1 -0
  234. package/data/persistence/{principalPolicyPersistence.js → principalPolicy/principalPolicyPersistence.js} +5 -5
  235. package/data/persistence/principalPolicy/principalPolicyPersistence.js.map +1 -0
  236. package/data/persistence/{principalPolicyReferenceCheckpoint.js → principalPolicy/principalPolicyReferenceCheckpoint.js} +3 -3
  237. package/data/persistence/principalPolicy/principalPolicyReferenceCheckpoint.js.map +1 -0
  238. package/data/persistence/{principalPolicyReferenceIndexPersistence.js → principalPolicy/principalPolicyReferenceIndexPersistence.js} +4 -4
  239. package/data/persistence/principalPolicy/principalPolicyReferenceIndexPersistence.js.map +1 -0
  240. package/data/persistence/{principalPolicyReferencePersistence.js → principalPolicy/principalPolicyReferencePersistence.js} +5 -5
  241. package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js.map +1 -0
  242. package/data/persistence/{verifiedPrincipalPolicyBundle.js → principalPolicy/verifiedPrincipalPolicyBundle.js} +2 -2
  243. package/data/persistence/principalPolicy/verifiedPrincipalPolicyBundle.js.map +1 -0
  244. package/data/persistence/{verifiedPrincipalPolicyCurrent.js → principalPolicy/verifiedPrincipalPolicyCurrent.js} +2 -2
  245. package/data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent.js.map +1 -0
  246. package/data/persistence/{verifiedPrincipalPolicyRetentionPersistence.js → principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js} +1 -1
  247. package/data/persistence/principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js.map +1 -0
  248. package/data/persistence/securityIncidentPersistence.js +1 -1
  249. package/data/persistence/securityIncidentPersistence.js.map +1 -1
  250. package/data/persistence/trustedUserIdentityPinPersistence.js +1 -1
  251. package/data/persistence/verifiedManifestBundlePersistence.d.ts +1 -1
  252. package/data/persistence/verifiedManifestBundlePersistence.js +4 -4
  253. package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
  254. package/data/principals/organizationGroupRoles.js +2 -2
  255. package/data/principals/organizationGroupRoles.js.map +1 -1
  256. package/data/principals/principalHistoryPrefixProtection.js.map +1 -1
  257. package/data/principals/principalHistoryStageProtection.js.map +1 -1
  258. package/data/principals/principalPolicyCrypto.js +1 -1
  259. package/data/principals/principalPolicyCrypto.js.map +1 -1
  260. package/data/sqlite/{documentHistoryPersistence.d.ts → documentPersistence/documentHistoryPersistence.d.ts} +1 -1
  261. package/data/sqlite/{documentHistoryPersistence.js → documentPersistence/documentHistoryPersistence.js} +5 -5
  262. package/data/sqlite/documentPersistence/documentHistoryPersistence.js.map +1 -0
  263. package/data/sqlite/{documentOrphanBlobReclaims.js → documentPersistence/documentOrphanBlobReclaims.js} +1 -1
  264. package/data/sqlite/documentPersistence/documentOrphanBlobReclaims.js.map +1 -0
  265. package/data/sqlite/{documentPendingUpdatePersistence.d.ts → documentPersistence/documentPendingUpdatePersistence.d.ts} +2 -2
  266. package/data/sqlite/{documentPendingUpdatePersistence.js → documentPersistence/documentPendingUpdatePersistence.js} +2 -2
  267. package/data/sqlite/documentPersistence/documentPendingUpdatePersistence.js.map +1 -0
  268. package/data/sqlite/{documentPersistenceTypes.d.ts → documentPersistence/documentPersistenceTypes.d.ts} +2 -2
  269. package/data/sqlite/documentPersistence/documentPersistenceTypes.js.map +1 -0
  270. package/data/sqlite/{documentRecordPersistence.d.ts → documentPersistence/documentRecordPersistence.d.ts} +1 -1
  271. package/data/sqlite/{documentRecordPersistence.js → documentPersistence/documentRecordPersistence.js} +4 -4
  272. package/data/sqlite/documentPersistence/documentRecordPersistence.js.map +1 -0
  273. package/data/sqlite/{documentSyncFailurePersistence.d.ts → documentPersistence/documentSyncFailurePersistence.d.ts} +2 -2
  274. package/data/sqlite/{documentSyncFailurePersistence.js → documentPersistence/documentSyncFailurePersistence.js} +3 -3
  275. package/data/sqlite/documentPersistence/documentSyncFailurePersistence.js.map +1 -0
  276. package/data/sqlite/{documentPersistence.d.ts → documentPersistence/index.d.ts} +2 -2
  277. package/data/sqlite/{documentPersistence.js → documentPersistence/index.js} +5 -5
  278. package/data/sqlite/documentPersistence/index.js.map +1 -0
  279. package/data/sqlite/{containerSchema.d.ts → schema/containerSchema.d.ts} +1 -1
  280. package/data/sqlite/{containerSchema.js → schema/containerSchema.js} +1 -1
  281. package/data/sqlite/schema/containerSchema.js.map +1 -0
  282. package/data/sqlite/{schema.d.ts → schema/index.d.ts} +1 -1
  283. package/data/sqlite/{schema.js → schema/index.js} +3 -3
  284. package/data/sqlite/schema/index.js.map +1 -0
  285. package/data/sqlite/{organizationDataUsageSchema.js → schema/organizationDataUsageSchema.js} +1 -1
  286. package/data/sqlite/schema/organizationDataUsageSchema.js.map +1 -0
  287. package/data/sqlite/{organizationProvisioningAttemptSchema.js → schema/organizationProvisioningAttemptSchema.js} +1 -1
  288. package/data/sqlite/schema/organizationProvisioningAttemptSchema.js.map +1 -0
  289. package/data/sqlite/{organizationReadModelTableRegistry.d.ts → schema/organizationReadModelTableRegistry.d.ts} +1 -1
  290. package/data/sqlite/{organizationReadModelTableRegistry.js → schema/organizationReadModelTableRegistry.js} +1 -1
  291. package/data/sqlite/schema/organizationReadModelTableRegistry.js.map +1 -0
  292. package/data/sqlite/{principalHistoryEvidenceSchema.d.ts → schema/principalHistoryEvidenceSchema.d.ts} +1 -1
  293. package/data/sqlite/{principalHistoryEvidenceSchema.js → schema/principalHistoryEvidenceSchema.js} +2 -2
  294. package/data/sqlite/schema/principalHistoryEvidenceSchema.js.map +1 -0
  295. package/data/sqlite/{principalHistoryNodeRetentionSchema.js → schema/principalHistoryNodeRetentionSchema.js} +1 -1
  296. package/data/sqlite/schema/principalHistoryNodeRetentionSchema.js.map +1 -0
  297. package/data/sqlite/{principalHistoryRetentionSchema.js → schema/principalHistoryRetentionSchema.js} +1 -1
  298. package/data/sqlite/{principalHistoryRetentionSchema.js.map → schema/principalHistoryRetentionSchema.js.map} +1 -1
  299. package/data/sqlite/{principalHistoryStageSchema.d.ts → schema/principalHistoryStageSchema.d.ts} +1 -1
  300. package/data/sqlite/{principalHistoryStageSchema.js → schema/principalHistoryStageSchema.js} +2 -2
  301. package/data/sqlite/schema/principalHistoryStageSchema.js.map +1 -0
  302. package/data/sqlite/{principalMutationJournalSchema.d.ts → schema/principalMutationJournalSchema.d.ts} +1 -1
  303. package/data/sqlite/{principalMutationJournalSchema.js → schema/principalMutationJournalSchema.js} +1 -1
  304. package/data/sqlite/{principalMutationJournalSchema.js.map → schema/principalMutationJournalSchema.js.map} +1 -1
  305. package/data/sqlite/{principalPolicySchema.js → schema/principalPolicySchema.js} +1 -1
  306. package/data/sqlite/schema/principalPolicySchema.js.map +1 -0
  307. package/data/sqlite/{securityIncidentSchema.d.ts → schema/securityIncidentSchema.d.ts} +1 -1
  308. package/data/sqlite/{securityIncidentSchema.js → schema/securityIncidentSchema.js} +1 -1
  309. package/data/sqlite/schema/securityIncidentSchema.js.map +1 -0
  310. package/data/sqlite/{verifiedManifestBundleSchema.d.ts → schema/verifiedManifestBundleSchema.d.ts} +1 -1
  311. package/data/sqlite/{verifiedManifestBundleSchema.js → schema/verifiedManifestBundleSchema.js} +1 -1
  312. package/data/sqlite/schema/verifiedManifestBundleSchema.js.map +1 -0
  313. package/data/sqlite/sqlitePersistenceRuntime.d.ts +1 -1
  314. package/data/sqlite/sqlitePersistenceRuntime.js +1 -1
  315. package/index.d.ts +1 -1
  316. package/index.js.map +1 -1
  317. package/package.json +1 -1
  318. package/sqlite/index.d.ts +1 -1
  319. package/sqlite/index.js +1 -1
  320. package/stores/container-contents/containerContentsStore.js +3 -2
  321. package/stores/container-contents/containerContentsStore.js.map +1 -1
  322. package/stores/container-contents/index.d.ts +1 -1
  323. package/stores/container-contents/index.js.map +1 -1
  324. package/stores/container-contents/operations/purgeMoveSettlementOperation.js +71 -0
  325. package/stores/container-contents/operations/purgeMoveSettlementOperation.js.map +1 -0
  326. package/stores/documents/documentStore/history/historyRebuild.js +1 -1
  327. package/stores/documents/documentStore/history/historyRebuild.js.map +1 -1
  328. package/stores/documents/documentStore/state.js.map +1 -1
  329. package/stores/documents/documentStore/sync/syncFinalize.js +1 -1
  330. package/stores/documents/documentStore/sync/syncFinalize.js.map +1 -1
  331. package/stores/documents/documentStore/sync/syncUpdateImport.js +1 -1
  332. package/stores/documents/documentStore/sync/syncUpdateImport.js.map +1 -1
  333. package/workflows/blobs/detach.js +1 -1
  334. package/workflows/blobs/hydration/decrypt.js +1 -1
  335. package/workflows/blobs/upload/index.js +1 -1
  336. package/workflows/blobs/verification/retainedAttachmentVerification.js +1 -1
  337. package/workflows/blobs/verification/writerProjection.js +1 -1
  338. package/workflows/container-contents/container-state/create/createWithMetadata.js +2 -2
  339. package/workflows/container-contents/container-state/create/createWithMetadata.js.map +1 -1
  340. package/workflows/container-contents/container-state/moveIntentSync.js +43 -5
  341. package/workflows/container-contents/container-state/moveIntentSync.js.map +1 -1
  342. package/workflows/container-contents/container-state/purge/purgeMoveSettlement.js +119 -0
  343. package/workflows/container-contents/container-state/purge/purgeMoveSettlement.js.map +1 -0
  344. package/workflows/container-contents/container-state/purge/purgeProgress.d.ts +8 -0
  345. package/workflows/container-contents/container-state/purge/purgeProgress.js.map +1 -1
  346. package/workflows/container-contents/container-state/remote.js +1 -0
  347. package/workflows/container-contents/container-state/remote.js.map +1 -1
  348. package/workflows/container-contents/container-state/share/index.js +1 -1
  349. package/workflows/container-contents/documentLinks/index.js +1 -1
  350. package/workflows/container-contents/documentMove/documentMoveVanishedRefresh.js +1 -1
  351. package/workflows/container-contents/documentPriming/documentHydrationProbe.js +1 -1
  352. package/workflows/container-contents/documentPriming/index.js +1 -1
  353. package/workflows/container-contents/documentQueries/index.js +1 -1
  354. package/workflows/container-contents/documentQueries/sql.js +1 -1
  355. package/workflows/container-contents/info/blobInfo.js +1 -1
  356. package/workflows/container-contents/info/containerInfo.js +1 -1
  357. package/workflows/container-contents/info/documentInfo.js +1 -1
  358. package/workflows/container-contents/metadata/index.js +1 -1
  359. package/workflows/container-contents/metadata/index.js.map +1 -1
  360. package/workflows/container-contents/metadata/metadataEvents.d.ts +1 -1
  361. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js +2 -2
  362. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js.map +1 -1
  363. package/workflows/container-contents/metadata/metadataMutationPreparation.js +1 -1
  364. package/workflows/container-contents/metadata/metadataMutationPreparation.js.map +1 -1
  365. package/workflows/container-contents/metadata/metadataPullContinuationInvalidation.js +1 -1
  366. package/workflows/container-contents/metadata/metadataPullContinuationInvalidation.js.map +1 -1
  367. package/workflows/container-contents/metadata/metadataRemoteSync.d.ts +1 -1
  368. package/workflows/container-contents/metadata/metadataSyncErrors.js +1 -1
  369. package/workflows/container-contents/metadata/metadataSyncErrors.js.map +1 -1
  370. package/workflows/container-contents/metadata/metadataSyncSettlement.d.ts +1 -1
  371. package/workflows/container-contents/metadata/metadataSyncSettlement.js.map +1 -1
  372. package/workflows/container-contents/metadata/metadataTypes.d.ts +1 -1
  373. package/workflows/container-contents/metadata/metadataTypes.js.map +1 -1
  374. package/workflows/container-contents/pendingWrites/index.js +2 -2
  375. package/workflows/container-contents/pendingWrites/sources.js +1 -1
  376. package/workflows/container-contents/remoteHydration/destination/replacementBinding.js +1 -1
  377. package/workflows/container-contents/remoteHydration/destination/replacementBinding.js.map +1 -1
  378. package/workflows/container-contents/remoteHydration/reattachMetadata.js.map +1 -1
  379. package/workflows/container-contents/syncLane.d.ts +2 -0
  380. package/workflows/container-contents/syncLane.js +7 -0
  381. package/workflows/container-contents/syncLane.js.map +1 -1
  382. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +2 -2
  383. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
  384. package/workflows/containers/child/create/index.js +2 -2
  385. package/workflows/containers/child/create/index.js.map +1 -1
  386. package/workflows/containers/child/move/index.d.ts +1 -0
  387. package/workflows/containers/child/move/index.js +2 -1
  388. package/workflows/containers/child/move/index.js.map +1 -1
  389. package/workflows/containers/child/move/moveRotation.js +1 -1
  390. package/workflows/containers/child/move/moveRotation.js.map +1 -1
  391. package/workflows/containers/child/move/moveWraps.js +1 -1
  392. package/workflows/containers/child/move/moveWraps.js.map +1 -1
  393. package/workflows/containers/child/mutationSubmit.js +3 -1
  394. package/workflows/containers/child/mutationSubmit.js.map +1 -1
  395. package/workflows/containers/child/recite.js +2 -2
  396. package/workflows/containers/child/recite.js.map +1 -1
  397. package/workflows/containers/child/rotation/rotationContext.js +3 -3
  398. package/workflows/containers/child/rotation/rotationContext.js.map +1 -1
  399. package/workflows/containers/child/share/currentSharePrincipalPolicy.js +1 -1
  400. package/workflows/containers/child/share/currentSharePrincipalPolicy.js.map +1 -1
  401. package/workflows/containers/child/share/index.js +1 -1
  402. package/workflows/containers/child/share/index.js.map +1 -1
  403. package/workflows/containers/child/share/shareAncestorRepair.js +2 -2
  404. package/workflows/containers/child/share/shareAncestorRepair.js.map +1 -1
  405. package/workflows/containers/child/share/shareMaterialization.js +1 -1
  406. package/workflows/containers/child/share/sharePrincipalPolicy.js +5 -5
  407. package/workflows/containers/child/share/sharePrincipalPolicy.js.map +1 -1
  408. package/workflows/containers/index.d.ts +3 -3
  409. package/workflows/containers/index.js +2 -2
  410. package/workflows/containers/index.js.map +1 -1
  411. package/workflows/containers/writeRefusal.js +1 -1
  412. package/workflows/containers/writeRefusal.js.map +1 -1
  413. package/workflows/documents/create/createAdoption.js +1 -1
  414. package/workflows/documents/create/createResponse.js +2 -2
  415. package/workflows/documents/create/createResponse.js.map +1 -1
  416. package/workflows/documents/create/index.js +1 -1
  417. package/workflows/documents/documentMutationCommit.d.ts +1 -1
  418. package/workflows/documents/documentMutationPreparation.d.ts +1 -1
  419. package/workflows/documents/documentMutationPreparation.js +1 -1
  420. package/workflows/documents/documentMutationPreparation.js.map +1 -1
  421. package/workflows/documents/index.d.ts +5 -5
  422. package/workflows/documents/index.js +5 -5
  423. package/workflows/documents/index.js.map +1 -1
  424. package/workflows/documents/linkSet/index.js +2 -2
  425. package/workflows/documents/linkSet/index.js.map +1 -1
  426. package/workflows/documents/linkSet/linkSetAuthority.js +1 -1
  427. package/workflows/documents/linkSet/linkSetBlobRewraps.js +1 -1
  428. package/workflows/documents/linkSet/linkSetProjectionSeed.js +1 -1
  429. package/workflows/documents/linkSet/linkSetRemote.js +1 -1
  430. package/workflows/documents/linkSet/linkSetRemote.js.map +1 -1
  431. package/workflows/documents/purge/index.js +1 -1
  432. package/workflows/documents/sync/index.js +2 -2
  433. package/workflows/documents/sync/index.js.map +1 -1
  434. package/workflows/documents/sync/initialSync.js +1 -1
  435. package/workflows/documents/sync/readOnlyProjectionFailure.js +1 -1
  436. package/workflows/documents/sync/readOnlyProjectionFailure.js.map +1 -1
  437. package/workflows/documents/sync/readOnlySync.d.ts +3 -3
  438. package/workflows/documents/sync/readOnlySync.js +1 -1
  439. package/workflows/documents/sync/readOnlySync.js.map +1 -1
  440. package/workflows/documents/sync/reportDocumentSyncQuarantine.js.map +1 -1
  441. package/workflows/documents/sync/syncAttemptPlanning.js +2 -2
  442. package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -1
  443. package/workflows/documents/sync/syncAttemptState.d.ts +2 -2
  444. package/workflows/documents/sync/syncAttemptState.js.map +1 -1
  445. package/workflows/documents/sync/syncResponseResult.js +2 -2
  446. package/workflows/documents/sync/syncResponseResult.js.map +1 -1
  447. package/workflows/documents/syncFailures/index.js +1 -1
  448. package/workflows/documents/syncFailures/index.js.map +1 -1
  449. package/workflows/documents/syncFailures/syncAbandon.js.map +1 -1
  450. package/workflows/documents/syncFailures/syncFailureClassification.js +1 -1
  451. package/workflows/documents/syncFailures/syncFailureClassification.js.map +1 -1
  452. package/workflows/documents/syncPlan/syncContentKeys.d.ts +1 -1
  453. package/workflows/documents/syncPlan/syncContentKeys.js +3 -3
  454. package/workflows/documents/syncPlan/syncContentKeys.js.map +1 -1
  455. package/workflows/documents/syncPlan/syncPlanMaterial.js +2 -2
  456. package/workflows/documents/syncPlan/syncPlanMaterial.js.map +1 -1
  457. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js +2 -2
  458. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js.map +1 -1
  459. package/workflows/documents/syncRekeys/syncContainerRekeyPreparation.js +1 -1
  460. package/workflows/documents/syncRekeys/syncRecoveryRekey.d.ts +1 -1
  461. package/workflows/documents/syncRekeys/syncRecoveryRekey.js +1 -1
  462. package/workflows/organizations/currentOrganizationAuthority.js +2 -2
  463. package/workflows/organizations/currentOrganizationAuthority.js.map +1 -1
  464. package/workflows/organizations/groupMetadata/groupMetadataAccess.js +1 -1
  465. package/workflows/organizations/groupMetadata/groupMetadataAccess.js.map +1 -1
  466. package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js +1 -1
  467. package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js.map +1 -1
  468. package/workflows/organizations/groupNames/currentOrganizationGroupNames.js +1 -1
  469. package/workflows/organizations/groupNames/currentOrganizationGroupNames.js.map +1 -1
  470. package/workflows/organizations/groupNames/groupNameUniqueness.js +3 -3
  471. package/workflows/organizations/groupNames/groupNameUniqueness.js.map +1 -1
  472. package/workflows/organizations/groupNames/organizationGroupNamePolicies.js +2 -2
  473. package/workflows/organizations/groupNames/organizationGroupNamePolicies.js.map +1 -1
  474. package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js +1 -1
  475. package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js.map +1 -1
  476. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js +2 -2
  477. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js.map +1 -1
  478. package/workflows/organizations/groupPolicy/groupPolicyMutationEvidence.js +1 -1
  479. package/workflows/organizations/groupPolicy/groupPolicyMutationEvidence.js.map +1 -1
  480. package/workflows/organizations/groupPolicy/groupPolicyVerification.js +1 -1
  481. package/workflows/organizations/groupPolicy/groupPolicyVerification.js.map +1 -1
  482. package/workflows/organizations/groups/createCurrentOrganizationGroup.js +1 -1
  483. package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
  484. package/workflows/organizations/groups/deleteOrganizationGroup.js +1 -1
  485. package/workflows/organizations/groups/deleteOrganizationGroup.js.map +1 -1
  486. package/workflows/organizations/groups/organizationGroupDirectory.js +1 -1
  487. package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
  488. package/workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation.js +1 -1
  489. package/workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation.js.map +1 -1
  490. package/workflows/organizations/provisioning/organizationReplacementVerification.js +1 -1
  491. package/workflows/organizations/provisioning/organizationReplacementVerification.js.map +1 -1
  492. package/workflows/organizations/readModel/listLocalOrganizations.js +1 -1
  493. package/workflows/organizations/readModel/localReadModelDetails.js +1 -1
  494. package/workflows/organizations/readModel/localReadModelDetails.js.map +1 -1
  495. package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js +1 -1
  496. package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js.map +1 -1
  497. package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.d.ts +1 -1
  498. package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js +1 -1
  499. package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js.map +1 -1
  500. package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js +1 -1
  501. package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js.map +1 -1
  502. package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js +2 -2
  503. package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js.map +1 -1
  504. package/workflows/principals/externalAdminPolicy.js +2 -2
  505. package/workflows/principals/externalAdminPolicy.js.map +1 -1
  506. package/workflows/principals/historyRecovery/loadRecoveredPrincipalHistoryPage.js +2 -2
  507. package/workflows/principals/historyRecovery/loadRecoveredPrincipalHistoryPage.js.map +1 -1
  508. package/workflows/principals/historyRecovery/principalHistoryRecoveryPrefix.js +1 -1
  509. package/workflows/principals/historyRecovery/principalHistoryRecoveryPrefix.js.map +1 -1
  510. package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js +1 -1
  511. package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js.map +1 -1
  512. package/workflows/principals/historyRecovery/principalHistoryRecoveryStage.js +1 -1
  513. package/workflows/principals/historyRecovery/principalHistoryRecoveryStage.js.map +1 -1
  514. package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js +3 -3
  515. package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js.map +1 -1
  516. package/workflows/principals/policyCache/index.js +3 -3
  517. package/workflows/principals/policyCache/index.js.map +1 -1
  518. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js +1 -1
  519. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js.map +1 -1
  520. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js +3 -3
  521. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -1
  522. package/workflows/principals/publicHistory/publicPrincipalHistoryAuthority.js.map +1 -1
  523. package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js +2 -2
  524. package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js.map +1 -1
  525. package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js +3 -3
  526. package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js.map +1 -1
  527. package/workflows/principals/publicHistory/publicPrincipalHistoryTypes.d.ts +2 -2
  528. package/workflows/principals/publicHistory/publicPrincipalHistoryTypes.js.map +1 -1
  529. package/workflows/principals/publicHistory/publicProjectionPrincipal.js +1 -1
  530. package/workflows/principals/publicHistory/publicProjectionPrincipal.js.map +1 -1
  531. package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js +1 -1
  532. package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js.map +1 -1
  533. package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js +1 -1
  534. package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js.map +1 -1
  535. package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js +1 -1
  536. package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js.map +1 -1
  537. package/workflows/principals/recoveryOperation/principalRecoveryMemoValidity.js +1 -1
  538. package/workflows/principals/recoveryOperation/principalRecoveryMemoValidity.js.map +1 -1
  539. package/workflows/registration/persistRegistrationBootstrap.d.ts +2 -2
  540. package/workflows/registration/persistRegistrationBootstrap.js +2 -2
  541. package/workflows/registration/persistRegistrationBootstrap.js.map +1 -1
  542. package/workflows/registration/provisioningAcknowledgement.js +1 -1
  543. package/workflows/registration/provisioningAcknowledgement.js.map +1 -1
  544. package/workflows/registration/registrationPrincipalPolicyPersistence.js +1 -1
  545. package/workflows/registration/registrationPrincipalPolicyPersistence.js.map +1 -1
  546. package/workflows/sync/remoteReset.js +7 -7
  547. package/workflows/sync/remoteReset.js.map +1 -1
  548. package/workflows/sync/remoteResetAttachments.js +1 -1
  549. package/workflows/sync/remoteResetCursorScope.js +1 -1
  550. package/workflows/sync/remoteResetPlans.js +1 -1
  551. package/workflows/sync/remoteResetPrincipalScope.js +5 -5
  552. package/workflows/sync/remoteResetPrincipalScope.js.map +1 -1
  553. package/workflows/sync/remoteResetScope.js +1 -1
  554. package/data/documents/shared/containerKekPath.js.map +0 -1
  555. package/data/documents/shared/containerKekPathHistory.js.map +0 -1
  556. package/data/documents/shared/containerKekPathVerification.js.map +0 -1
  557. package/data/documents/shared/containerKekWrapping.js.map +0 -1
  558. package/data/documents/shared/documentSyncUpdateDecryption.js.map +0 -1
  559. package/data/documents/shared/documentSyncUpdateIsolation.js.map +0 -1
  560. package/data/documents/shared/keyringRebuild.js.map +0 -1
  561. package/data/documents/shared/mutationAcknowledgement.js.map +0 -1
  562. package/data/documents/shared/projection.js.map +0 -1
  563. package/data/documents/shared/projectionContentKeys.js.map +0 -1
  564. package/data/documents/shared/projectionTargets.js.map +0 -1
  565. package/data/documents/shared/syncPagination.js.map +0 -1
  566. package/data/documents/shared/syncResponseAuthorization.js.map +0 -1
  567. package/data/documents/shared/syncResponses.js.map +0 -1
  568. package/data/persistence/documentPurgeCheckpointPersistence.js.map +0 -1
  569. package/data/persistence/keyingCheckpointAdvancePersistence.js.map +0 -1
  570. package/data/persistence/keyingCheckpointPersistence.js.map +0 -1
  571. package/data/persistence/locallyAcknowledgedCheckpointPersistence.js.map +0 -1
  572. package/data/persistence/organizationReplacementCheckpointPersistence.js.map +0 -1
  573. package/data/persistence/principalAuthorizationCheckpoints.js.map +0 -1
  574. package/data/persistence/principalGrantRetirementPersistence.js.map +0 -1
  575. package/data/persistence/principalHistoryEvidencePersistence.js.map +0 -1
  576. package/data/persistence/principalHistoryIncompleteRetention.js.map +0 -1
  577. package/data/persistence/principalHistoryNodeRetention.js.map +0 -1
  578. package/data/persistence/principalHistoryPrefixPersistence.js.map +0 -1
  579. package/data/persistence/principalHistoryRootOwnership.js.map +0 -1
  580. package/data/persistence/principalHistoryStagePersistence.js.map +0 -1
  581. package/data/persistence/principalHistoryStageRetention.js.map +0 -1
  582. package/data/persistence/principalHistoryUnpublishedRetention.js.map +0 -1
  583. package/data/persistence/principalKeyEnvelopeArchivePersistence.js.map +0 -1
  584. package/data/persistence/principalKeyEnvelopeCandidates.js.map +0 -1
  585. package/data/persistence/principalPolicyBundleIntegrity.js.map +0 -1
  586. package/data/persistence/principalPolicyCheckpointSelection.js.map +0 -1
  587. package/data/persistence/principalPolicyOrganizationPersistence.js.map +0 -1
  588. package/data/persistence/principalPolicyPersistence.js.map +0 -1
  589. package/data/persistence/principalPolicyReferenceCheckpoint.js.map +0 -1
  590. package/data/persistence/principalPolicyReferenceIndexPersistence.js.map +0 -1
  591. package/data/persistence/principalPolicyReferencePersistence.js.map +0 -1
  592. package/data/persistence/verifiedPrincipalPolicyBundle.js.map +0 -1
  593. package/data/persistence/verifiedPrincipalPolicyCurrent.js.map +0 -1
  594. package/data/persistence/verifiedPrincipalPolicyRetentionPersistence.js.map +0 -1
  595. package/data/sqlite/containerSchema.js.map +0 -1
  596. package/data/sqlite/documentHistoryPersistence.js.map +0 -1
  597. package/data/sqlite/documentOrphanBlobReclaims.js.map +0 -1
  598. package/data/sqlite/documentPendingUpdatePersistence.js.map +0 -1
  599. package/data/sqlite/documentPersistence.js.map +0 -1
  600. package/data/sqlite/documentPersistenceTypes.js.map +0 -1
  601. package/data/sqlite/documentRecordPersistence.js.map +0 -1
  602. package/data/sqlite/documentSyncFailurePersistence.js.map +0 -1
  603. package/data/sqlite/organizationDataUsageSchema.js.map +0 -1
  604. package/data/sqlite/organizationProvisioningAttemptSchema.js.map +0 -1
  605. package/data/sqlite/organizationReadModelTableRegistry.js.map +0 -1
  606. package/data/sqlite/principalHistoryEvidenceSchema.js.map +0 -1
  607. package/data/sqlite/principalHistoryNodeRetentionSchema.js.map +0 -1
  608. package/data/sqlite/principalHistoryStageSchema.js.map +0 -1
  609. package/data/sqlite/principalPolicySchema.js.map +0 -1
  610. package/data/sqlite/schema.js.map +0 -1
  611. package/data/sqlite/securityIncidentSchema.js.map +0 -1
  612. package/data/sqlite/verifiedManifestBundleSchema.js.map +0 -1
  613. /package/data/documents/shared/{containerKekCurrency.js → containerKek/containerKekCurrency.js} +0 -0
  614. /package/data/documents/shared/{containerKekCurrency.js.map → containerKek/containerKekCurrency.js.map} +0 -0
  615. /package/data/documents/shared/{containerKekEntryVerification.js.map → containerKek/containerKekEntryVerification.js.map} +0 -0
  616. /package/data/documents/shared/{containerKekLogFetch.js.map → containerKek/containerKekLogFetch.js.map} +0 -0
  617. /package/data/documents/shared/{containerKekPath.d.ts → containerKek/containerKekPath.d.ts} +0 -0
  618. /package/data/documents/shared/{keyringLogWalk.js.map → containerKek/keyringLogWalk.js.map} +0 -0
  619. /package/data/documents/shared/{pullContinuation.d.ts → sync/pullContinuation.d.ts} +0 -0
  620. /package/data/documents/shared/{pullContinuation.js.map → sync/pullContinuation.js.map} +0 -0
  621. /package/data/documents/shared/{syncSubmitFailure.js → sync/syncSubmitFailure.js} +0 -0
  622. /package/data/documents/shared/{syncSubmitFailure.js.map → sync/syncSubmitFailure.js.map} +0 -0
  623. /package/data/persistence/{keyingCheckpointEvidence.js.map → keyingCheckpoints/keyingCheckpointEvidence.js.map} +0 -0
  624. /package/data/persistence/{storedPrincipalPolicyBundle.js → principalPolicy/storedPrincipalPolicyBundle.js} +0 -0
  625. /package/data/persistence/{storedPrincipalPolicyBundle.js.map → principalPolicy/storedPrincipalPolicyBundle.js.map} +0 -0
  626. /package/data/sqlite/{documentPersistenceTypes.js → documentPersistence/documentPersistenceTypes.js} +0 -0
  627. /package/data/sqlite/{containerDocumentTombstoneHoldSchema.d.ts → schema/containerDocumentTombstoneHoldSchema.d.ts} +0 -0
  628. /package/data/sqlite/{containerDocumentTombstoneHoldSchema.js → schema/containerDocumentTombstoneHoldSchema.js} +0 -0
  629. /package/data/sqlite/{containerDocumentTombstoneHoldSchema.js.map → schema/containerDocumentTombstoneHoldSchema.js.map} +0 -0
  630. /package/data/sqlite/{documentAttachmentSchema.d.ts → schema/documentAttachmentSchema.d.ts} +0 -0
  631. /package/data/sqlite/{documentAttachmentSchema.js → schema/documentAttachmentSchema.js} +0 -0
  632. /package/data/sqlite/{documentAttachmentSchema.js.map → schema/documentAttachmentSchema.js.map} +0 -0
  633. /package/data/sqlite/{documentDiscoveryEvidenceSchema.js → schema/documentDiscoveryEvidenceSchema.js} +0 -0
  634. /package/data/sqlite/{documentDiscoveryEvidenceSchema.js.map → schema/documentDiscoveryEvidenceSchema.js.map} +0 -0
  635. /package/data/sqlite/{documentPlacementIntentSchema.js → schema/documentPlacementIntentSchema.js} +0 -0
  636. /package/data/sqlite/{documentPlacementIntentSchema.js.map → schema/documentPlacementIntentSchema.js.map} +0 -0
  637. /package/data/sqlite/{localIntentSchema.d.ts → schema/localIntentSchema.d.ts} +0 -0
  638. /package/data/sqlite/{localIntentSchema.js → schema/localIntentSchema.js} +0 -0
  639. /package/data/sqlite/{localIntentSchema.js.map → schema/localIntentSchema.js.map} +0 -0
  640. /package/data/sqlite/{organizationFounderSchema.js → schema/organizationFounderSchema.js} +0 -0
  641. /package/data/sqlite/{organizationFounderSchema.js.map → schema/organizationFounderSchema.js.map} +0 -0
  642. /package/data/sqlite/{organizationReadModelSchema.js → schema/organizationReadModelSchema.js} +0 -0
  643. /package/data/sqlite/{organizationReadModelSchema.js.map → schema/organizationReadModelSchema.js.map} +0 -0
  644. /package/data/sqlite/{principalGrantRetirementSchema.js → schema/principalGrantRetirementSchema.js} +0 -0
  645. /package/data/sqlite/{principalGrantRetirementSchema.js.map → schema/principalGrantRetirementSchema.js.map} +0 -0
  646. /package/data/sqlite/{principalPolicySchema.d.ts → schema/principalPolicySchema.d.ts} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"principalMutationJournalPersistence.js","sourceRoot":"","sources":["principalMutationJournalPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,mCAAmC,EAAE,MAAM,uCAAuC,CAAC;AAC5F,OAAO,EACL,wBAAwB,EACxB,8BAA8B,GAC/B,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,iCAAiC,EAAE,MAAM,oCAAoC,CAAC;AACvF,OAAO,EA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IACF,mCAAmC,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;IAC5D,OAAO,MAAM,CAAC,MAAM,KAAK,IAAI,CAAC;AAChC,CAAC","sourcesContent":["import { and, eq } from \"drizzle-orm\";\nimport { assertProjectionVerificationCurrent } from \"../keyingProjectionVerification/types\";\nimport {\n principalMutationJournal,\n principalMutationJournalTables,\n} from \"../sqlite/principalMutationJournalSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\n\nexport type PrincipalMutationJournalRow =\n typeof principalMutationJournal.$inferSelect;\n\nexport class PendingPrincipalMutationError extends Error {\n constructor() {\n super(\n \"Resolve the pending principal mutation or explicitly abandon its retry before submitting another\",\n );\n this.name = \"PendingPrincipalMutationError\";\n }\n}\n\nexport async function loadPrincipalMutationJournal(\n execSql: ExecSql,\n scopeId: string,\n): Promise<PrincipalMutationJournalRow | null> {\n await ensureSqlTables(execSql, principalMutationJournalTables);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const [row] = await db\n .select()\n .from(principalMutationJournal)\n .where(eq(principalMutationJournal.scopeId, scopeId))\n .limit(1);\n return row ?? null;\n}\n\n/** Claim the organization lane before dispatch; never overwrite unresolved work. */\nexport async function claimPrincipalMutationJournal(input: {\n readonly execSql: ExecSql;\n readonly row: PrincipalMutationJournalRow;\n readonly stillCurrent: () => boolean;\n}): Promise<void> {\n const row = { ...input.row };\n await ensureSqlTables(input.execSql, principalMutationJournalTables);\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const result = await runtime.guardedTransaction(\n async (tx) => {\n const [existing] = await tx\n .select({ scopeId: principalMutationJournal.scopeId })\n .from(principalMutationJournal)\n .where(eq(principalMutationJournal.scopeId, row.scopeId))\n .limit(1);\n if (existing) throw new PendingPrincipalMutationError();\n await tx.insert(principalMutationJournal).values(row).run();\n },\n input.stillCurrent,\n { behavior: \"immediate\" },\n );\n assertProjectionVerificationCurrent(() => result.committed);\n}\n\n/** A late acknowledgement cannot retire another operation's journal entry. */\nexport async function clearPrincipalMutationJournal(input: {\n readonly execSql: ExecSql;\n readonly row: PrincipalMutationJournalRow;\n readonly stillCurrent: () => boolean;\n}): Promise<boolean> {\n const row = { ...input.row };\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const result = await runtime.guardedTransaction(\n async (tx) => {\n const deleted = await tx\n .delete(principalMutationJournal)\n .where(\n and(\n eq(principalMutationJournal.scopeId, row.scopeId),\n eq(principalMutationJournal.organizationId, row.organizationId),\n eq(\n principalMutationJournal.serializedRequest,\n row.serializedRequest,\n ),\n eq(principalMutationJournal.signature, row.signature),\n ),\n )\n .returning({ scopeId: principalMutationJournal.scopeId });\n return deleted.length > 0;\n },\n input.stillCurrent,\n { behavior: \"immediate\" },\n );\n assertProjectionVerificationCurrent(() => result.committed);\n return result.result === true;\n}\n"]}
1
+ {"version":3,"file":"principalMutationJournalPersistence.js","sourceRoot":"","sources":["principalMutationJournalPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,mCAAmC,EAAE,MAAM,uCAAuC,CAAC;AAC5F,OAAO,EACL,wBAAwB,EACxB,8BAA8B,GAC/B,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE,iCAAiC,EAAE,MAAM,oCAAoC,CAAC;AACvF,OAAO,EAAgB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAKpE,MAAM,OAAO,6BAA8B,SAAQ,KAAK;IACtD;QACE,KAAK,CACH,kGAAkG,CACnG,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,+BAA+B,CAAC;IAC9C,CAAC;CACF;AAED,MAAM,CAAC,KAAK,UAAU,4BAA4B,CAChD,OAAgB,EAChB,OAAe;IAEf,MAAM,eAAe,CAAC,OAAO,EAAE,8BAA8B,CAAC,CAAC;IAC/D,MA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,MAAM,CAAC,SAAS,CAAC,CAAC;AAC9D,CAAC;AAED,8EAA8E;AAC9E,MAAM,CAAC,KAAK,UAAU,6BAA6B,CAAC,KAInD;IACC,MAAM,GAAG,GAAG,EAAE,GAAG,KAAK,CAAC,GAAG,EAAE,CAAC;IAC7B,MAAM,OAAO,GAAG,iCAAiC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACjE,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,kBAAkB,CAC7C,KAAK,EAAE,EAAE,EAAE,EAAE;QACX,MAAM,OAAO,GAAG,MAAM,EAAE;aACrB,MAAM,CAAC,wBAAwB,CAAC;aAChC,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,wBAAwB,CAAC,OAAO,EAAE,GAAG,CAAC,OAAO,CAAC,EACjD,EAAE,CAAC,wBAAwB,CAAC,cAAc,EAAE,GAAG,CAAC,cAAc,CAAC,EAC/D,EAAE,CACA,wBAAwB,CAAC,iBAAiB,EAC1C,GAAG,CAAC,iBAAiB,CACtB,EACD,EAAE,CAAC,wBAAwB,CAAC,SAAS,EAAE,GAAG,CAAC,SAAS,CAAC,CACtD,CACF;aACA,SAAS,CAAC,EAAE,OAAO,EAAE,wBAAwB,CAAC,OAAO,EAAE,CAAC,CAAC;QAC5D,OAAO,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC;IAC5B,CAAC,EACD,KAAK,CAAC,YAAY,EAClB,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;IACF,mCAAmC,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;IAC5D,OAAO,MAAM,CAAC,MAAM,KAAK,IAAI,CAAC;AAChC,CAAC","sourcesContent":["import { and, eq } from \"drizzle-orm\";\nimport { assertProjectionVerificationCurrent } from \"../keyingProjectionVerification/types\";\nimport {\n principalMutationJournal,\n principalMutationJournalTables,\n} from \"../sqlite/schema/principalMutationJournalSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\n\nexport type PrincipalMutationJournalRow =\n typeof principalMutationJournal.$inferSelect;\n\nexport class PendingPrincipalMutationError extends Error {\n constructor() {\n super(\n \"Resolve the pending principal mutation or explicitly abandon its retry before submitting another\",\n );\n this.name = \"PendingPrincipalMutationError\";\n }\n}\n\nexport async function loadPrincipalMutationJournal(\n execSql: ExecSql,\n scopeId: string,\n): Promise<PrincipalMutationJournalRow | null> {\n await ensureSqlTables(execSql, principalMutationJournalTables);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const [row] = await db\n .select()\n .from(principalMutationJournal)\n .where(eq(principalMutationJournal.scopeId, scopeId))\n .limit(1);\n return row ?? null;\n}\n\n/** Claim the organization lane before dispatch; never overwrite unresolved work. */\nexport async function claimPrincipalMutationJournal(input: {\n readonly execSql: ExecSql;\n readonly row: PrincipalMutationJournalRow;\n readonly stillCurrent: () => boolean;\n}): Promise<void> {\n const row = { ...input.row };\n await ensureSqlTables(input.execSql, principalMutationJournalTables);\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const result = await runtime.guardedTransaction(\n async (tx) => {\n const [existing] = await tx\n .select({ scopeId: principalMutationJournal.scopeId })\n .from(principalMutationJournal)\n .where(eq(principalMutationJournal.scopeId, row.scopeId))\n .limit(1);\n if (existing) throw new PendingPrincipalMutationError();\n await tx.insert(principalMutationJournal).values(row).run();\n },\n input.stillCurrent,\n { behavior: \"immediate\" },\n );\n assertProjectionVerificationCurrent(() => result.committed);\n}\n\n/** A late acknowledgement cannot retire another operation's journal entry. */\nexport async function clearPrincipalMutationJournal(input: {\n readonly execSql: ExecSql;\n readonly row: PrincipalMutationJournalRow;\n readonly stillCurrent: () => boolean;\n}): Promise<boolean> {\n const row = { ...input.row };\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const result = await runtime.guardedTransaction(\n async (tx) => {\n const deleted = await tx\n .delete(principalMutationJournal)\n .where(\n and(\n eq(principalMutationJournal.scopeId, row.scopeId),\n eq(principalMutationJournal.organizationId, row.organizationId),\n eq(\n principalMutationJournal.serializedRequest,\n row.serializedRequest,\n ),\n eq(principalMutationJournal.signature, row.signature),\n ),\n )\n .returning({ scopeId: principalMutationJournal.scopeId });\n return deleted.length > 0;\n },\n input.stillCurrent,\n { behavior: \"immediate\" },\n );\n assertProjectionVerificationCurrent(() => result.committed);\n return result.result === true;\n}\n"]}
@@ -1,6 +1,6 @@
1
- import { compareCanonicalStrings, KeyingVerificationError, normalizePrincipalContainerGrants, normalizePrincipalProjectionMembers, } from "../../internal/crypto/index.js";
2
- import { isPrincipalPolicyBundleResponse } from "../../internal/validators/response/index.js";
3
- import { canonicalKeyingJsonString } from "../keying/canonicalJson.js";
1
+ import { compareCanonicalStrings, KeyingVerificationError, normalizePrincipalContainerGrants, normalizePrincipalProjectionMembers, } from "../../../internal/crypto/index.js";
2
+ import { isPrincipalPolicyBundleResponse } from "../../../internal/validators/response/index.js";
3
+ import { canonicalKeyingJsonString } from "../../keying/canonicalJson.js";
4
4
  import { storedPrincipalPolicyBundleFromJson, } from "./storedPrincipalPolicyBundle.js";
5
5
  function parseBundle(row) {
6
6
  const bundle = storedPrincipalPolicyBundleFromJson(row);
@@ -0,0 +1 @@
1
+ {"version":3,"file":"principalPolicyBundleIntegrity.js","sourceRoot":"","sources":["principalPolicyBundleIntegrity.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,uBAAuB,EACvB,iCAAiC,EACjC,mCAAmC,GACpC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,+BAA+B,EAAE,MAAM,gCAAgC,CAAC;AACjF,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EAEL,mCAAmC,GACpC,MAAM,+BAA+B,CAAC;AAEvC,SAAS,WAAW,CAClB,GAAoC;IAEpC,MAAM,MAAM,GAAG,mCAAmC,CAAC,GAAG,CAAC,CAAC;IACx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,CAAC;AAED,MAAM,UAAU,mCAAmC,CACjD,MAAuC,EACvC,QAAyC;IAEzC,IAAI,CAAC;QACH,IACE,SAAS,CAAC,eAAe,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC;YAC/C,SAAS,CAAC,eAAe,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC,CAAC,EACjD,CAAC;YACD,OAAO;QACT,CAAC;IACH,CAAC;IAAC,MAAM,CAAC;QACP,2EAA2E;QAC3E,2EAA2E;IAC7E,CAAC;IACD,MAAM,IAAI,uBAAuB,CAC/B,cAAc,EACd,mFAAmF,CACpF,CAAC;AACJ,CAAC","sourcesContent":["import {\n compareCanonicalStrings,\n KeyingVerificationError,\n normalizePrincipalContainerGrants,\n normalizePrincipalProjectionMembers,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { isPrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../../keying/canonicalJson\";\nimport {\n type StoredPrincipalPolicyBundleJson,\n storedPrincipalPolicyBundleFromJson,\n} from \"./storedPrincipalPolicyBundle\";\n\nfunction parseBundle(\n row: StoredPrincipalPolicyBundleJson,\n): PrincipalPolicyBundleResponse {\n const bundle = storedPrincipalPolicyBundleFromJson(row);\n if (!isPrincipalPolicyBundleResponse(bundle)) {\n throw new Error(\"Stored principal policy bundle is invalid\");\n }\n return bundle;\n}\n\nfunction canonical(value: unknown): string {\n return canonicalKeyingJsonString(\n value,\n \"principal policy bundle security content\",\n );\n}\n\nfunction withoutCreatedAt<T extends { readonly createdAt: string }>(\n value: T,\n): Omit<T, \"createdAt\"> {\n const { createdAt: _createdAt, ...content } = value;\n return content;\n}\n\nfunction securityContent(bundle: PrincipalPolicyBundleResponse) {\n return {\n currentMemberEnvelopes: {\n ...bundle.currentMemberEnvelopes,\n envelopes: [...bundle.currentMemberEnvelopes.envelopes].sort((a, b) =>\n compareCanonicalStrings(canonical(a), canonical(b)),\n ),\n },\n currentPayload: withoutCreatedAt(bundle.currentPayload),\n currentProjection: normalizePrincipalProjectionMembers(\n bundle.currentProjection,\n ),\n currentGrants: normalizePrincipalContainerGrants(bundle.currentGrants),\n currentState: withoutCreatedAt(bundle.currentState),\n previousStates: bundle.previousStates.map((entry) => ({\n projection: normalizePrincipalProjectionMembers(entry.projection),\n grants: normalizePrincipalContainerGrants(entry.grants),\n state: withoutCreatedAt(entry.state),\n })),\n };\n}\n\nexport function assertSameHeadPrincipalPolicyBundle(\n stored: StoredPrincipalPolicyBundleJson,\n incoming: StoredPrincipalPolicyBundleJson,\n): void {\n try {\n if (\n canonical(securityContent(parseBundle(stored))) ===\n canonical(securityContent(parseBundle(incoming)))\n ) {\n return;\n }\n } catch {\n // Invalid same-head cache content is also an integrity conflict: replacing\n // it would erase the only durable evidence that the head was inconsistent.\n }\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy bundle content conflicts with the cached bundle at the same head\",\n );\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { verifyPrincipalPolicyCheckpoint } from "../../internal/crypto/index.js";
2
- import { assertPrincipalPolicyCheckpointShape } from "./keyingCheckpointPersistence.js";
1
+ import { verifyPrincipalPolicyCheckpoint } from "../../../internal/crypto/index.js";
2
+ import { assertPrincipalPolicyCheckpointShape } from "../keyingCheckpoints/keyingCheckpointPersistence.js";
3
3
  export function principalPolicyHeadMeetsCheckpoint(head, checkpoint) {
4
4
  return (!checkpoint ||
5
5
  head.version > checkpoint.version ||
@@ -0,0 +1 @@
1
+ {"version":3,"file":"principalPolicyCheckpointSelection.js","sourceRoot":"","sources":["principalPolicyCheckpointSelection.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,+BAA+B,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,EAAE,oCAAoC,EAAE,MAAM,kDAAkD,CAAC;AAExG,MAAM,UAAU,kCAAkC,CAChD,IAA8D,EAC9D,UAA4C;IAE5C,OAAO,CACL,CAAC,UAAU;QACX,IAAI,CAAC,OAAO,GAAG,UAAU,CAAC,OAAO;QACjC,CAAC,IAAI,CAAC,OAAO,KAAK,UAAU,CAAC,OAAO;YAClC,IAAI,CAAC,SAAS,KAAK,UAAU,CAAC,SAAS,CAAC,CAC3C,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,sCAAsC,CACpD,MAAoC,EACpC,UAA4C;IAE5C,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,oCAAoC,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC;IACzD,IAAI,MAAM,CAAC,OAAO,GAAG,UAAU,CAAC,OAAO,EAAE,CAAC;QACxC,OAAO,KAAK,CAAC;IACf,CAAC;IACD,+BAA+B,CAAC;QAC9B,KAAK,EACH,iBAAiB,IAAI,MAAM;YACzB,CAAC,CAAC,MAAM,CAAC,eAAe;YACxB,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,IAAI,EAAE,CAAC;QAC5B,YAAY,EAAE,MAAM,CAAC,KAAK;QAC1B,eAAe,EAAE,UAAU;KAC5B,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type {\n PrincipalPolicyAuthorization,\n PrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport { verifyPrincipalPolicyCheckpoint } from \"@tearleads/crypto\";\nimport { assertPrincipalPolicyCheckpointShape } from \"../keyingCheckpoints/keyingCheckpointPersistence\";\n\nexport function principalPolicyHeadMeetsCheckpoint(\n head: { readonly stateHash: string; readonly version: number },\n checkpoint: PrincipalPolicyCheckpoint | null,\n): boolean {\n return (\n !checkpoint ||\n head.version > checkpoint.version ||\n (head.version === checkpoint.version &&\n head.stateHash === checkpoint.stateHash)\n );\n}\n\nexport function verifiedPrincipalPolicyMeetsCheckpoint(\n policy: PrincipalPolicyAuthorization,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): boolean {\n if (!checkpoint) {\n return true;\n }\n assertPrincipalPolicyCheckpointShape(checkpoint, policy);\n if (policy.version < checkpoint.version) {\n return false;\n }\n verifyPrincipalPolicyCheckpoint({\n chain:\n \"retainedHistory\" in policy\n ? policy.retainedHistory\n : (policy.history ?? []),\n currentState: policy.state,\n localCheckpoint: checkpoint,\n });\n return true;\n}\n"]}
@@ -1,6 +1,6 @@
1
- import { KeyingVerificationError } from "../../internal/crypto/index.js";
1
+ import { KeyingVerificationError } from "../../../internal/crypto/index.js";
2
2
  import { and, eq } from "drizzle-orm";
3
- import { principalPolicyOrganizations } from "../sqlite/schema.js";
3
+ import { principalPolicyOrganizations } from "../../sqlite/schema/index.js";
4
4
  function resolveOrganizationId(input) {
5
5
  if (input.principalType === "organization") {
6
6
  if (input.organizationId !== undefined &&
@@ -0,0 +1 @@
1
+ {"version":3,"file":"principalPolicyOrganizationPersistence.js","sourceRoot":"","sources":["principalPolicyOrganizationPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,4BAA4B,EAAE,MAAM,qBAAqB,CAAC;AASnE,SAAS,qBAAqB,CAC5B,KAAuC;IAEvC,IAAI,KAAK,CAAC,aAAa,KAAK,cAAc,EAAE,CAAC;QAC3C,IACE,KAAK,CAAC,cAAc,KAAK,SAAS;YAClC,KAAK,CAAC,cAAc,KAAK,KAAK,CAAC,WAAW,EAC1C,CAAC;YACD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,kEAAkE,CACnE,CAAC;QACJ,CAAC;QACD,OAAO,KAAK,CAAC,WAAW,CAAC;IAC3B,CAAC;IACD,IAAI,CAAC,KAAK,CAAC,cAAc,EAAE,CAAC;QAC1B,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC1E,CAAC;IACD,OAAO,KAAK,CAAC,cAAc,CAAC;AAC9B,CAAC;AAED,+EAA+E;AAC/E,MAAM,CAAC,KAAK,UAAU,8CAA8C,CAClE,EAAgC,EAChC,KAAuC;IAEvC,MAAM,cAAc,GAAG,qBAAqB,CAAC,KAAK,CAAC,CAAC;IACpD,MAAM,cAAc,GAAG,GAAG,CACxB,EAAE,CAAC,4BAA4B,CAAC,aAAa,EAAE,KAAK,CAAC,aAAa,CAAC,EACnE,EAAE,CAAC,4BAA4B,CAAC,WAAW,EAAE,KAAK,CAAC,WAAW,CAAC,CAChE,CAAC;IACF,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,EAAE;SACtB,MAAM,CAAC,EAAE,cAAc,EAAE,4BAA4B,CAAC,cAAc,EAAE,CAAC;SACvE,IAAI,CAAC,4BAA4B,CAAC;SAClC,KAAK,CAAC,cAAc,CAAC;SACrB,KAAK,CAAC,CAAC,CAAC,CAAC;IACZ,IAAI,MAAM,IAAI,MAAM,CAAC,cAAc,KAAK,cAAc,EAAE,CAAC;QACvD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,iEAAiE,CAClE,CAAC;IACJ,CAAC;IACD,MAAM,EAAE;SACL,MAAM,CAAC,4BAA4B,CAAC;SACpC,MAAM,CAAC,EAAE,GAAG,KAAK,EAAE,cAAc,EAAE,CAAC;SACpC,mBAAmB,EAAE;SACrB,GAAG,EAAE,CAAC;AACX,CAAC;AAED,MAAM,UAAU,oDAAoD,CAClE,EAAgC,EAChC,MAAyD,EACzD,cAAmC;IAEnC,OAAO,8CAA8C,CAAC,EAAE,EAAE;QACxD,cAAc;QACd,WAAW,EAAE,MAAM,CAAC,YAAY,CAAC,WAAW;QAC5C,aAAa,EAAE,MAAM,CAAC,YAAY,CAAC,aAAa;KACjD,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { PrincipalStateResponse } from \"@tearleads/validators/response\";\nimport { and, eq } from \"drizzle-orm\";\nimport { principalPolicyOrganizations } from \"../../sqlite/schema\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\n\ninterface PrincipalPolicyOrganizationInput {\n readonly organizationId?: string | undefined;\n readonly principalId: string;\n readonly principalType: PrincipalStateResponse[\"principalType\"];\n}\n\nfunction resolveOrganizationId(\n input: PrincipalPolicyOrganizationInput,\n): string {\n if (input.principalType === \"organization\") {\n if (\n input.organizationId !== undefined &&\n input.organizationId !== input.principalId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"organization policy cache ownership targets another organization\",\n );\n }\n return input.principalId;\n }\n if (!input.organizationId) {\n throw new Error(\"Group policy cache writes require an organization ID\");\n }\n return input.organizationId;\n}\n\n/** Pins cache ownership in the same transaction as the cached policy state. */\nexport async function recordPrincipalPolicyOrganizationInTransaction(\n tx: ClientSQLiteTransactionScope,\n input: PrincipalPolicyOrganizationInput,\n): Promise<void> {\n const organizationId = resolveOrganizationId(input);\n const wherePrincipal = and(\n eq(principalPolicyOrganizations.principalType, input.principalType),\n eq(principalPolicyOrganizations.principalId, input.principalId),\n );\n const [stored] = await tx\n .select({ organizationId: principalPolicyOrganizations.organizationId })\n .from(principalPolicyOrganizations)\n .where(wherePrincipal)\n .limit(1);\n if (stored && stored.organizationId !== organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"principal policy cache is already owned by another organization\",\n );\n }\n await tx\n .insert(principalPolicyOrganizations)\n .values({ ...input, organizationId })\n .onConflictDoNothing()\n .run();\n}\n\nexport function recordPrincipalPolicyBundleOrganizationInTransaction(\n tx: ClientSQLiteTransactionScope,\n bundle: { readonly currentState: PrincipalStateResponse },\n organizationId?: string | undefined,\n): Promise<void> {\n return recordPrincipalPolicyOrganizationInTransaction(tx, {\n organizationId,\n principalId: bundle.currentState.principalId,\n principalType: bundle.currentState.principalType,\n });\n}\n"]}
@@ -1,9 +1,9 @@
1
- import { KeyingVerificationError } from "../../internal/crypto/index.js";
2
- import { isPrincipalPolicyBundleResponse } from "../../internal/validators/response/index.js";
1
+ import { KeyingVerificationError } from "../../../internal/crypto/index.js";
2
+ import { isPrincipalPolicyBundleResponse } from "../../../internal/validators/response/index.js";
3
3
  import { and, asc, eq } from "drizzle-orm";
4
- import { keyingCheckpointTables, principalPolicies, principalPolicyBundleHistory, principalPolicyCheckpoints, principalPolicyTables, } from "../sqlite/schema.js";
5
- import { getClientSQLitePersistenceRuntime, } from "../sqlite/sqlitePersistenceRuntime.js";
6
- import { ensureSqlTables } from "../sqlite/sqlSchema.js";
4
+ import { keyingCheckpointTables, principalPolicies, principalPolicyBundleHistory, principalPolicyCheckpoints, principalPolicyTables, } from "../../sqlite/schema/index.js";
5
+ import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
6
+ import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
7
7
  import { assertSameHeadPrincipalPolicyBundle } from "./principalPolicyBundleIntegrity.js";
8
8
  import { recordPrincipalPolicyBundleOrganizationInTransaction, recordPrincipalPolicyOrganizationInTransaction, } from "./principalPolicyOrganizationPersistence.js";
9
9
  import { indexPrincipalPolicyBundleInTransaction } from "./principalPolicyReferenceIndexPersistence.js";
@@ -0,0 +1 @@
1
+ {"version":3,"file":"principalPolicyPersistence.js","sourceRoot":"","sources":["principalPolicyPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAK5D,OAAO,EAAE,+BAA+B,EAAE,MAAM,gCAAgC,CAAC;AACjF,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EACL,sBAAsB,EACtB,iBAAiB,EACjB,4BAA4B,EAC5B,0BAA0B,EAC1B,qBAAqB,GACtB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,EAAE,mCAAmC,EAAE,MAAM,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n PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { isPrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { and, asc, eq } from \"drizzle-orm\";\nimport {\n keyingCheckpointTables,\n principalPolicies,\n principalPolicyBundleHistory,\n principalPolicyCheckpoints,\n principalPolicyTables,\n} from \"../../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport { assertSameHeadPrincipalPolicyBundle } from \"./principalPolicyBundleIntegrity\";\nimport {\n recordPrincipalPolicyBundleOrganizationInTransaction,\n recordPrincipalPolicyOrganizationInTransaction,\n} from \"./principalPolicyOrganizationPersistence\";\nimport { indexPrincipalPolicyBundleInTransaction } from \"./principalPolicyReferenceIndexPersistence\";\nimport { storedPrincipalPolicyBundleFromJson } from \"./storedPrincipalPolicyBundle\";\n\ninterface PrincipalPolicyRow {\n principalType: \"group\" | \"organization\";\n principalId: string;\n stateHash: string;\n currentStateJson: string;\n currentPayloadJson: string;\n currentProjectionJson: string;\n currentGrantsJson: string;\n currentMemberEnvelopesJson: string;\n previousStatesJson: string;\n updatedAt: string;\n}\n\nexport interface SelectedPrincipalPolicyRow {\n principalType: string;\n principalId: string;\n stateHash: string;\n currentStateJson: string;\n currentPayloadJson: string;\n currentProjectionJson: string;\n currentGrantsJson: string;\n currentMemberEnvelopesJson: string;\n previousStatesJson: string;\n updatedAt: string;\n}\n\ninterface StoredPrincipalPolicyHead {\n readonly stateHash: string;\n readonly version: number;\n}\n\nfunction isManagedPrincipalType(\n value: string,\n): value is PrincipalStateResponse[\"principalType\"] {\n return value === \"group\" || value === \"organization\";\n}\n\nfunction parsePrincipalPolicyRow(\n row: SelectedPrincipalPolicyRow,\n): PrincipalPolicyRow | null {\n if (!isManagedPrincipalType(row.principalType)) {\n return null;\n }\n\n return {\n principalType: row.principalType,\n principalId: row.principalId,\n stateHash: row.stateHash,\n currentStateJson: row.currentStateJson,\n currentPayloadJson: row.currentPayloadJson,\n currentProjectionJson: row.currentProjectionJson,\n currentGrantsJson: row.currentGrantsJson,\n currentMemberEnvelopesJson: row.currentMemberEnvelopesJson,\n previousStatesJson: row.previousStatesJson,\n updatedAt: row.updatedAt,\n };\n}\n\nfunction parseStoredPrincipalPolicyHead(\n currentStateJson: string,\n): StoredPrincipalPolicyHead | null {\n try {\n const value: unknown = JSON.parse(currentStateJson);\n if (!value || typeof value !== \"object\") {\n return null;\n }\n const stateHash = Reflect.get(value, \"stateHash\");\n const version = Reflect.get(value, \"version\");\n return typeof stateHash === \"string\" && typeof version === \"number\"\n ? { stateHash, version }\n : null;\n } catch {\n return null;\n }\n}\n\nfunction parsePrincipalPolicyBundle(\n row: PrincipalPolicyRow,\n): PrincipalPolicyBundleResponse {\n const bundle = storedPrincipalPolicyBundleFromJson(row);\n\n if (!isPrincipalPolicyBundleResponse(bundle)) {\n throw new Error(\"Stored principal policy bundle is invalid\");\n }\n\n return bundle;\n}\n\nexport async function ensurePrincipalPolicyTables(\n execSql: ExecSql,\n): Promise<void> {\n await ensureSqlTables(execSql, principalPolicyTables);\n}\n\ntype PrincipalPolicyBundleTable =\n | typeof principalPolicies\n | typeof principalPolicyBundleHistory;\n\n/**\n * The ONE select shape for a stored principal-policy bundle row, over either\n * the mutable-head table or the retained-history table.\n */\nexport function principalPolicyBundleSelection(\n table: PrincipalPolicyBundleTable,\n) {\n return {\n principalType: table.principalType,\n principalId: table.principalId,\n stateHash: table.stateHash,\n currentStateJson: table.currentStateJson,\n currentPayloadJson: table.currentPayloadJson,\n currentProjectionJson: table.currentProjectionJson,\n currentGrantsJson: table.currentGrantsJson,\n currentMemberEnvelopesJson: table.currentMemberEnvelopesJson,\n previousStatesJson: table.previousStatesJson,\n updatedAt: table.updatedAt,\n };\n}\n\nexport async function loadPrincipalPolicyBundle(\n execSql: ExecSql,\n principalType: PrincipalStateResponse[\"principalType\"],\n principalId: string,\n): Promise<PrincipalPolicyBundleResponse | null> {\n await ensurePrincipalPolicyTables(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select(principalPolicyBundleSelection(principalPolicies))\n .from(principalPolicies)\n .where(\n and(\n eq(principalPolicies.principalType, principalType),\n eq(principalPolicies.principalId, principalId),\n ),\n )\n .limit(1);\n\n const row = rows[0] ? parsePrincipalPolicyRow(rows[0]) : null;\n return row ? parsePrincipalPolicyBundle(row) : null;\n}\n\nexport async function loadAllPrincipalPolicyBundles(\n execSql: ExecSql,\n): Promise<PrincipalPolicyBundleResponse[]> {\n await ensurePrincipalPolicyTables(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select(principalPolicyBundleSelection(principalPolicies))\n .from(principalPolicies)\n .orderBy(\n asc(principalPolicies.principalType),\n asc(principalPolicies.principalId),\n );\n const historyRows = await db\n .select(principalPolicyBundleSelection(principalPolicyBundleHistory))\n .from(principalPolicyBundleHistory)\n .orderBy(\n asc(principalPolicyBundleHistory.principalType),\n asc(principalPolicyBundleHistory.principalId),\n asc(principalPolicyBundleHistory.stateHash),\n );\n\n const bundles: PrincipalPolicyBundleResponse[] = [];\n\n for (const rawRow of [...rows, ...historyRows]) {\n const row = parsePrincipalPolicyRow(rawRow);\n\n if (!row) {\n continue;\n }\n\n bundles.push(parsePrincipalPolicyBundle(row));\n }\n\n return bundles;\n}\n\nexport async function loadPrincipalPolicyStateHash(\n execSql: ExecSql,\n principalType: PrincipalStateResponse[\"principalType\"],\n principalId: string,\n): Promise<string | null> {\n await ensurePrincipalPolicyTables(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({ stateHash: principalPolicies.stateHash })\n .from(principalPolicies)\n .where(\n and(\n eq(principalPolicies.principalType, principalType),\n eq(principalPolicies.principalId, principalId),\n ),\n )\n .limit(1);\n\n return rows[0]?.stateHash ?? null;\n}\n\nfunction policyBundleRow(\n bundle: PrincipalPolicyBundleResponse,\n updatedAt: string,\n): PrincipalPolicyRow {\n return {\n principalType: bundle.currentState.principalType,\n principalId: bundle.currentState.principalId,\n stateHash: bundle.currentState.stateHash,\n currentStateJson: JSON.stringify(bundle.currentState),\n currentPayloadJson: JSON.stringify(bundle.currentPayload),\n currentProjectionJson: JSON.stringify(bundle.currentProjection),\n currentGrantsJson: JSON.stringify(bundle.currentGrants),\n currentMemberEnvelopesJson: JSON.stringify(bundle.currentMemberEnvelopes),\n previousStatesJson: JSON.stringify(bundle.previousStates),\n updatedAt,\n };\n}\n\nfunction assertNoHeadConflict(\n incoming: StoredPrincipalPolicyHead,\n checkpoint: StoredPrincipalPolicyHead | null,\n): void {\n if (\n checkpoint &&\n incoming.version === checkpoint.version &&\n incoming.stateHash !== checkpoint.stateHash\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy bundle conflicts with the cached head at one version\",\n );\n }\n}\n\nasync function archiveOlderPolicyBundle(\n tx: ClientSQLiteTransactionScope,\n storedPolicy: SelectedPrincipalPolicyRow | undefined,\n storedHead: StoredPrincipalPolicyHead | null,\n incomingHead: StoredPrincipalPolicyHead,\n): Promise<void> {\n if (\n !storedPolicy ||\n !storedHead ||\n storedHead.version >= incomingHead.version\n ) {\n return;\n }\n const archiveRow = parsePrincipalPolicyRow(storedPolicy);\n if (!archiveRow) {\n return;\n }\n try {\n parsePrincipalPolicyBundle(archiveRow);\n await tx\n .insert(principalPolicyBundleHistory)\n .values(archiveRow)\n .onConflictDoNothing()\n .run();\n } catch {\n // A corrupt cache row is replaced, never retained as key material.\n }\n}\n\nasync function writePrincipalPolicyBundle(\n tx: ClientSQLiteTransactionScope,\n bundle: PrincipalPolicyBundleResponse,\n nextRow: PrincipalPolicyRow,\n incomingHead: StoredPrincipalPolicyHead,\n): Promise<void> {\n const wherePrincipal = and(\n eq(principalPolicies.principalType, nextRow.principalType),\n eq(principalPolicies.principalId, nextRow.principalId),\n );\n const [storedPolicy] = await tx\n .select(principalPolicyBundleSelection(principalPolicies))\n .from(principalPolicies)\n .where(wherePrincipal)\n .limit(1);\n const [durableCheckpoint] = await tx\n .select({\n stateHash: principalPolicyCheckpoints.stateHash,\n version: principalPolicyCheckpoints.version,\n })\n .from(principalPolicyCheckpoints)\n .where(\n and(\n eq(principalPolicyCheckpoints.principalType, nextRow.principalType),\n eq(principalPolicyCheckpoints.principalId, nextRow.principalId),\n ),\n )\n .limit(1);\n const storedHead = storedPolicy\n ? parseStoredPrincipalPolicyHead(storedPolicy.currentStateJson)\n : null;\n if (\n storedPolicy &&\n storedHead?.version === incomingHead.version &&\n storedHead.stateHash === incomingHead.stateHash\n ) {\n assertSameHeadPrincipalPolicyBundle(storedPolicy, nextRow);\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n return;\n }\n const [retainedPolicy] = await tx\n .select(principalPolicyBundleSelection(principalPolicyBundleHistory))\n .from(principalPolicyBundleHistory)\n .where(\n and(\n eq(principalPolicyBundleHistory.principalType, nextRow.principalType),\n eq(principalPolicyBundleHistory.principalId, nextRow.principalId),\n eq(principalPolicyBundleHistory.stateHash, nextRow.stateHash),\n ),\n )\n .limit(1);\n if (retainedPolicy) {\n assertSameHeadPrincipalPolicyBundle(retainedPolicy, nextRow);\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n }\n const effectiveHead =\n durableCheckpoint &&\n (!storedHead || durableCheckpoint.version >= storedHead.version)\n ? durableCheckpoint\n : storedHead;\n assertNoHeadConflict(incomingHead, storedHead);\n assertNoHeadConflict(incomingHead, durableCheckpoint ?? null);\n if (effectiveHead && incomingHead.version < effectiveHead.version) {\n return;\n }\n\n await archiveOlderPolicyBundle(tx, storedPolicy, storedHead, incomingHead);\n await tx\n .insert(principalPolicies)\n .values(nextRow)\n .onConflictDoUpdate({\n target: [principalPolicies.principalType, principalPolicies.principalId],\n set: nextRow,\n })\n .run();\n await tx\n .delete(principalPolicyBundleHistory)\n .where(\n and(\n eq(principalPolicyBundleHistory.principalType, nextRow.principalType),\n eq(principalPolicyBundleHistory.principalId, nextRow.principalId),\n eq(principalPolicyBundleHistory.stateHash, nextRow.stateHash),\n ),\n )\n .run();\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n}\n\nexport async function writePrincipalPolicyBundleInTransaction(\n tx: ClientSQLiteTransactionScope,\n bundle: PrincipalPolicyBundleResponse,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n await recordPrincipalPolicyBundleOrganizationInTransaction(\n tx,\n bundle,\n organizationId,\n );\n await writePrincipalPolicyBundle(\n tx,\n bundle,\n policyBundleRow(bundle, updatedAt),\n bundle.currentState,\n );\n}\n\nexport async function assertPrincipalPolicyBundleStoredInTransaction(\n tx: ClientSQLiteTransactionScope,\n bundle: PrincipalPolicyBundleResponse,\n): Promise<void> {\n const expected = policyBundleRow(bundle, bundle.currentState.createdAt);\n const [stored] = await tx\n .select(principalPolicyBundleSelection(principalPolicies))\n .from(principalPolicies)\n .where(\n and(\n eq(principalPolicies.principalType, expected.principalType),\n eq(principalPolicies.principalId, expected.principalId),\n ),\n )\n .limit(1);\n if (!stored) {\n throw new Error(\"Verified principal policy bundle was not persisted\");\n }\n assertSameHeadPrincipalPolicyBundle(stored, expected);\n}\n\nexport async function retainPrincipalPolicyBundleInTransaction(\n tx: ClientSQLiteTransactionScope,\n bundle: PrincipalPolicyBundleResponse,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n const row = policyBundleRow(bundle, updatedAt);\n await recordPrincipalPolicyOrganizationInTransaction(tx, {\n organizationId,\n principalId: row.principalId,\n principalType: row.principalType,\n });\n const [current] = await tx\n .select(principalPolicyBundleSelection(principalPolicies))\n .from(principalPolicies)\n .where(\n and(\n eq(principalPolicies.principalType, row.principalType),\n eq(principalPolicies.principalId, row.principalId),\n ),\n )\n .limit(1);\n if (current?.stateHash === row.stateHash) {\n assertSameHeadPrincipalPolicyBundle(current, row);\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n return;\n }\n const [retained] = await tx\n .select(principalPolicyBundleSelection(principalPolicyBundleHistory))\n .from(principalPolicyBundleHistory)\n .where(\n and(\n eq(principalPolicyBundleHistory.principalType, row.principalType),\n eq(principalPolicyBundleHistory.principalId, row.principalId),\n eq(principalPolicyBundleHistory.stateHash, row.stateHash),\n ),\n )\n .limit(1);\n if (retained) {\n assertSameHeadPrincipalPolicyBundle(retained, row);\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n return;\n }\n await tx.insert(principalPolicyBundleHistory).values(row).run();\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n}\n\nexport async function savePrincipalPolicyBundle(\n execSql: ExecSql,\n bundle: PrincipalPolicyBundleResponse,\n updatedAt: string,\n organizationId: string,\n options?: { stillCurrent?: (() => boolean) | undefined } | undefined,\n): Promise<void> {\n await ensureSqlTables(execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const save = (tx: ClientSQLiteTransactionScope) =>\n writePrincipalPolicyBundleInTransaction(\n tx,\n bundle,\n updatedAt,\n organizationId,\n );\n if (options?.stillCurrent) {\n await runtime.guardedTransaction(save, options.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(save, { behavior: \"immediate\" });\n}\n"]}
@@ -1,6 +1,6 @@
1
- import { KeyingVerificationError, } from "../../internal/crypto/index.js";
2
- import { principalPolicyBundleStates } from "../principals/principalPolicyStates.js";
3
- import { assertPrincipalPolicyCheckpointShape } from "./keyingCheckpointPersistence.js";
1
+ import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
2
+ import { principalPolicyBundleStates } from "../../principals/principalPolicyStates.js";
3
+ import { assertPrincipalPolicyCheckpointShape } from "../keyingCheckpoints/keyingCheckpointPersistence.js";
4
4
  export function applyPrincipalPolicyReferenceCheckpoint(bundle, checkpoint) {
5
5
  if (!checkpoint) {
6
6
  return bundle;
@@ -0,0 +1 @@
1
+ {"version":3,"file":"principalPolicyReference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AAuB,CAC/B,cAAc,EACd,4DAA4D,CAC7D,CAAC;IACJ,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { principalPolicyBundleStates } from \"../../principals/principalPolicyStates\";\nimport { assertPrincipalPolicyCheckpointShape } from \"../keyingCheckpoints/keyingCheckpointPersistence\";\n\nexport function applyPrincipalPolicyReferenceCheckpoint(\n bundle: PrincipalPolicyBundleResponse,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): PrincipalPolicyBundleResponse | null {\n if (!checkpoint) {\n return bundle;\n }\n assertPrincipalPolicyCheckpointShape(checkpoint, bundle.currentState);\n if (bundle.currentState.version < checkpoint.version) {\n return null;\n }\n if (bundle.currentState.version === checkpoint.version) {\n if (bundle.currentState.stateHash !== checkpoint.stateHash) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy head conflicts with the local checkpoint\",\n );\n }\n return bundle;\n }\n const checkpointStates = principalPolicyBundleStates(bundle).filter(\n (state) => state.version === checkpoint.version,\n );\n if (checkpointStates.length === 0) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"principal policy chain does not extend the local checkpoint\",\n );\n }\n if (\n checkpointStates.some((state) => state.stateHash !== checkpoint.stateHash)\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy chain conflicts with the local checkpoint\",\n );\n }\n return bundle;\n}\n"]}
@@ -1,8 +1,8 @@
1
- import { KeyingVerificationError } from "../../internal/crypto/index.js";
1
+ import { KeyingVerificationError } from "../../../internal/crypto/index.js";
2
2
  import { and, eq, inArray, or } from "drizzle-orm";
3
- import { principalPolicyBundleStates } from "../principals/principalPolicyStates.js";
4
- import { principalPolicyBundleReferences } from "../sqlite/schema.js";
5
- import { sqliteInsertBatchSize, sqliteRowsPerStatement, } from "../sqlite/sqliteBindBudget.js";
3
+ import { principalPolicyBundleStates } from "../../principals/principalPolicyStates.js";
4
+ import { principalPolicyBundleReferences } from "../../sqlite/schema/index.js";
5
+ import { sqliteInsertBatchSize, sqliteRowsPerStatement, } from "../../sqlite/sqliteBindBudget.js";
6
6
  const REFERENCE_INSERT_BATCH_SIZE = sqliteInsertBatchSize(principalPolicyBundleReferences);
7
7
  // Principal type and id plus the bundle version and state hash bind once.
8
8
  const REFERENCE_LOOKUP_VERSIONS = sqliteRowsPerStatement(1, 4);
@@ -0,0 +1 @@
1
+ {"version":3,"file":"principalPolicyReferenceIndexPersistence.js","sourceRoot":"","sources":["principalPolicyReferenceIndexPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,2BAA2B,EAAE,MAAM,wCAAwC,CAAC;AACrF,OAAO,EAAE,+BAA+B,EAAE,MAAM,qBAAqB,CAAC;AACtE,OAAO,EACL,qBAAqB,EACrB,sBAAsB,GACvB,MAAM,+BAA+B,CAAC;AAgBvC,MAAM,2BAA2B,GAAG,qBAAqB,CACvD,+BAA+B,CAChC,CAAC;AACF,0EAA0E;AAC1E,MAAM,yBAAyB,GAAG,sBAAsB,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AAE/D,yEAAyE;AACzE,SAAS,eAAe,CACtB,MAAsC,EACtC,GAAgC;IAEhC,OAAO,CACL,MAAM,CAAC,OAAO,KAAK,GAAG,CAAC,OAAO;QAC9B,MAAM,CAAC,SAAS,KAAK,GAAG,CAAC,SAAS;QAClC,MAAM,CAAC,QAAQ,KAAK,GAAG,CAAC,QAAQ;QAChC,MAAM,CAAC,cAAc,KAAK,GAAG,CAAC,cAAc,CAC7C,CAAC;AACJ,CAAC;AAED,oDAAoD;AACpD,SAAS,YAAY,CACnB,GAGC;IAED,OAA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CAAC,CAAC;IACJ,MAAM,MAAM,GACV,IAAI,CAAC,MAAM,KAAK,CAAC;QACf,CAAC,CAAC,EAAE;QACJ,CAAC,CAAC,MAAM,oBAAoB,CAAC,EAAE,EAAE,IAAI,EAAE;YACnC,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;SAC3C,CAAC,CAAC;IACT,IAAI,OAAO,GAAmC,IAAI,CAAC;IACnD,IAAI,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC;IAC3B,KAAK,MAAM,CAAC,KAAK,EAAE,GAAG,CAAC,IAAI,IAAI,CAAC,OAAO,EAAE,EAAE,CAAC;QAC1C,OAAO,GAAG,iBAAiB,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;QACzC,IAAI,OAAO,EAAE,CAAC;YACZ,QAAQ,GAAG,KAAK,CAAC;YACjB,MAAM;QACR,CAAC;IACH,CAAC;IACD,IAAI,CAAC,OAAO,IAAI,YAAY,KAAK,CAAC,CAAC;QACjC,OAAO,GAAG,IAAI,uBAAuB,CACnC,iBAAiB,EACjB,gEAAgE,CACjE,CAAC;IACJ,MAAM,uBAAuB,CAAC,EAAE,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,CAAC,EAAE,MAAM,CAAC,CAAC;IACnE,IAAI,OAAO;QAAE,MAAM,OAAO,CAAC;AAC7B,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { and, eq, inArray, or } from \"drizzle-orm\";\nimport { principalPolicyBundleStates } from \"../../principals/principalPolicyStates\";\nimport { principalPolicyBundleReferences } from \"../../sqlite/schema\";\nimport {\n sqliteInsertBatchSize,\n sqliteRowsPerStatement,\n} from \"../../sqlite/sqliteBindBudget\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\n\ntype PrincipalPolicyReferenceRow =\n typeof principalPolicyBundleReferences.$inferInsert;\n\ntype StoredPrincipalPolicyReference = Pick<\n typeof principalPolicyBundleReferences.$inferSelect,\n | \"version\"\n | \"stateHash\"\n | \"keyEpoch\"\n | \"keyFingerprint\"\n | \"bundleVersion\"\n | \"bundleStateHash\"\n>;\n\nconst REFERENCE_INSERT_BATCH_SIZE = sqliteInsertBatchSize(\n principalPolicyBundleReferences,\n);\n// Principal type and id plus the bundle version and state hash bind once.\nconst REFERENCE_LOOKUP_VERSIONS = sqliteRowsPerStatement(1, 4);\n\n/** The exact six-field match; the lookup already fixes the principal. */\nfunction isSameReference(\n stored: StoredPrincipalPolicyReference,\n row: PrincipalPolicyReferenceRow,\n): boolean {\n return (\n stored.version === row.version &&\n stored.stateHash === row.stateHash &&\n stored.keyEpoch === row.keyEpoch &&\n stored.keyFingerprint === row.keyFingerprint\n );\n}\n\n/** The table's primary key within one principal. */\nfunction referenceKey(\n row: Pick<\n StoredPrincipalPolicyReference,\n \"version\" | \"stateHash\" | \"keyEpoch\" | \"keyFingerprint\" | \"bundleStateHash\"\n >,\n): string {\n return JSON.stringify([\n row.version,\n row.stateHash,\n row.keyEpoch,\n row.keyFingerprint,\n row.bundleStateHash,\n ]);\n}\n\n/** Rows either equivocation check can match, read before this bundle's writes. */\nasync function loadStoredReferences(\n tx: ClientSQLiteTransactionScope,\n head: PrincipalPolicyBundleResponse[\"currentState\"],\n versions: readonly number[],\n): Promise<StoredPrincipalPolicyReference[]> {\n const stored: StoredPrincipalPolicyReference[] = [];\n for (\n let index = 0;\n index < versions.length;\n index += REFERENCE_LOOKUP_VERSIONS\n ) {\n stored.push(\n ...(await tx\n .select({\n version: principalPolicyBundleReferences.version,\n stateHash: principalPolicyBundleReferences.stateHash,\n keyEpoch: principalPolicyBundleReferences.keyEpoch,\n keyFingerprint: principalPolicyBundleReferences.keyFingerprint,\n bundleVersion: principalPolicyBundleReferences.bundleVersion,\n bundleStateHash: principalPolicyBundleReferences.bundleStateHash,\n })\n .from(principalPolicyBundleReferences)\n .where(\n and(\n eq(\n principalPolicyBundleReferences.principalType,\n head.principalType,\n ),\n eq(principalPolicyBundleReferences.principalId, head.principalId),\n inArray(\n principalPolicyBundleReferences.version,\n versions.slice(index, index + REFERENCE_LOOKUP_VERSIONS),\n ),\n or(\n eq(principalPolicyBundleReferences.bundleVersion, head.version),\n eq(\n principalPolicyBundleReferences.bundleStateHash,\n head.stateHash,\n ),\n ),\n ),\n )),\n );\n }\n return stored;\n}\n\n/**\n * Rows written earlier in the same bundle all carry its head, so neither\n * check can match them: each state's outcome depends only on stored rows.\n */\nfunction referenceConflict(\n row: PrincipalPolicyReferenceRow,\n stored: readonly StoredPrincipalPolicyReference[],\n): KeyingVerificationError | null {\n const sameReference = stored.filter((candidate) =>\n isSameReference(candidate, row),\n );\n if (\n sameReference.some(\n (candidate) =>\n candidate.bundleVersion === row.bundleVersion &&\n candidate.bundleStateHash !== row.bundleStateHash,\n )\n )\n return new KeyingVerificationError(\n \"equivocation\",\n \"principal policy reference has conflicting bundle heads at one version\",\n );\n const indexed = sameReference.find(\n (candidate) => candidate.bundleStateHash === row.bundleStateHash,\n );\n if (indexed && indexed.bundleVersion !== row.bundleVersion)\n return new KeyingVerificationError(\n \"equivocation\",\n \"principal policy reference index conflicts with the bundle head\",\n );\n return null;\n}\n\nasync function insertMissingReferences(\n tx: ClientSQLiteTransactionScope,\n rows: readonly PrincipalPolicyReferenceRow[],\n stored: readonly StoredPrincipalPolicyReference[],\n): Promise<void> {\n const present = new Set(stored.map(referenceKey));\n const missing = new Map<string, PrincipalPolicyReferenceRow>();\n for (const row of rows) {\n const key = referenceKey(row);\n if (!present.has(key) && !missing.has(key)) missing.set(key, row);\n }\n const values = [...missing.values()];\n for (\n let index = 0;\n index < values.length;\n index += REFERENCE_INSERT_BATCH_SIZE\n ) {\n await tx\n .insert(principalPolicyBundleReferences)\n .values(values.slice(index, index + REFERENCE_INSERT_BATCH_SIZE))\n .onConflictDoNothing()\n .run();\n }\n}\n\n/**\n * Index every state of a verified bundle under its head. Fails in state order\n * with the per-state checks' errors, keeping the states indexed before the\n * first failure.\n */\nexport async function indexPrincipalPolicyBundleInTransaction(\n tx: ClientSQLiteTransactionScope,\n bundle: PrincipalPolicyBundleResponse,\n): Promise<void> {\n const head = bundle.currentState;\n const states = principalPolicyBundleStates(bundle);\n const foreignIndex = states.findIndex(\n (state) =>\n state.principalType !== head.principalType ||\n state.principalId !== head.principalId,\n );\n const rows: PrincipalPolicyReferenceRow[] = (\n foreignIndex === -1 ? states : states.slice(0, foreignIndex)\n ).map((state) => ({\n principalType: state.principalType,\n principalId: state.principalId,\n version: state.version,\n stateHash: state.stateHash,\n keyEpoch: state.keyEpoch,\n keyFingerprint: state.keyFingerprint,\n bundleVersion: head.version,\n bundleStateHash: head.stateHash,\n }));\n const stored =\n rows.length === 0\n ? []\n : await loadStoredReferences(tx, head, [\n ...new Set(rows.map((row) => row.version)),\n ]);\n let failure: KeyingVerificationError | null = null;\n let accepted = rows.length;\n for (const [index, row] of rows.entries()) {\n failure = referenceConflict(row, stored);\n if (failure) {\n accepted = index;\n break;\n }\n }\n if (!failure && foreignIndex !== -1)\n failure = new KeyingVerificationError(\n \"object_mismatch\",\n \"principal policy bundle reference belongs to another principal\",\n );\n await insertMissingReferences(tx, rows.slice(0, accepted), stored);\n if (failure) throw failure;\n}\n"]}
@@ -1,9 +1,9 @@
1
- import { KeyingVerificationError, } from "../../internal/crypto/index.js";
2
- import { isPrincipalPolicyBundleResponse, isReferencedPrincipalStateResponse, } from "../../internal/validators/response/index.js";
1
+ import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
2
+ import { isPrincipalPolicyBundleResponse, isReferencedPrincipalStateResponse, } from "../../../internal/validators/response/index.js";
3
3
  import { and, eq, inArray } from "drizzle-orm";
4
- import { principalPolicyBundleContainsReference, principalPolicyBundleStates, } from "../principals/principalPolicyStates.js";
5
- import { principalPolicies, principalPolicyBundleHistory, principalPolicyBundleReferences, } from "../sqlite/schema.js";
6
- import { getClientSQLitePersistenceRuntime } from "../sqlite/sqlitePersistenceRuntime.js";
4
+ import { principalPolicyBundleContainsReference, principalPolicyBundleStates, } from "../../principals/principalPolicyStates.js";
5
+ import { principalPolicies, principalPolicyBundleHistory, principalPolicyBundleReferences, } from "../../sqlite/schema/index.js";
6
+ import { getClientSQLitePersistenceRuntime } from "../../sqlite/sqlitePersistenceRuntime.js";
7
7
  import { assertSameHeadPrincipalPolicyBundle } from "./principalPolicyBundleIntegrity.js";
8
8
  import { ensurePrincipalPolicyTables, principalPolicyBundleSelection, } from "./principalPolicyPersistence.js";
9
9
  import { applyPrincipalPolicyReferenceCheckpoint } from "./principalPolicyReferenceCheckpoint.js";
@@ -0,0 +1 @@
1
+ {"version":3,"file":"principalPolicyReferencePersistence.js","sourceRoot":"","sources":["principalPolicyReferencePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,+BAA+B,EAC/B,kCAAkC,GACnC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EACL,sCAAsC,EACtC,2BAA2B,GAC5B,MAAM,wCAAwC,CAAC;AAChD,OAAO,EACL,iBAAiB,EACjB,4BAA4B,EAC5B,+BAA+B,GAChC,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAE1F,OAAO,EAAE,mCAAmC,EAAE,MAAM,kCAAkC,CAAC;AACvF,OAAO,EACL,2BAA2B,EAC3B,8BAA8B,GAE/B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,uCAAuC,EAAE,MAAM,sCAAsC,CAAC;AAC/F,OAAO,EAAE,mCAAmC,EAAE,MAAM,+BAA+B,CAAC;AAOpF,SAAS,4BAA4B,CACnC,MAAqC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Q;QACb,CAAC,CAAC,uCAAuC,CAAC,QAAQ,EAAE,UAAU,CAAC;QAC/D,CAAC,CAAC,IAAI,CAAC;AACX,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport {\n isPrincipalPolicyBundleResponse,\n isReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { and, eq, inArray } from \"drizzle-orm\";\nimport {\n principalPolicyBundleContainsReference,\n principalPolicyBundleStates,\n} from \"../../principals/principalPolicyStates\";\nimport {\n principalPolicies,\n principalPolicyBundleHistory,\n principalPolicyBundleReferences,\n} from \"../../sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { assertSameHeadPrincipalPolicyBundle } from \"./principalPolicyBundleIntegrity\";\nimport {\n ensurePrincipalPolicyTables,\n principalPolicyBundleSelection,\n type SelectedPrincipalPolicyRow,\n} from \"./principalPolicyPersistence\";\nimport { applyPrincipalPolicyReferenceCheckpoint } from \"./principalPolicyReferenceCheckpoint\";\nimport { storedPrincipalPolicyBundleFromJson } from \"./storedPrincipalPolicyBundle\";\n\ninterface IndexedBundleHead {\n readonly bundleStateHash: string;\n readonly bundleVersion: number;\n}\n\nfunction assertUnambiguousBundleChain(\n bundle: PrincipalPolicyBundleResponse,\n): void {\n const states = principalPolicyBundleStates(bundle);\n if (states.length !== bundle.currentState.version) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"stored principal policy bundle chain length does not match its head\",\n );\n }\n const versions = new Map<number, string>();\n for (const [index, state] of states.entries()) {\n if (\n state.principalType !== bundle.currentState.principalType ||\n state.principalId !== bundle.currentState.principalId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"stored principal policy bundle chain belongs to another principal\",\n );\n }\n if (\n !Number.isInteger(state.version) ||\n state.version !== index + 1 ||\n !Number.isSafeInteger(state.keyEpoch) ||\n state.keyEpoch < 1 ||\n state.principalId.length === 0 ||\n state.stateHash.length === 0 ||\n state.keyFingerprint.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"stored principal policy bundle chain has an invalid version or epoch\",\n );\n }\n if (versions.has(state.version)) {\n const previousHash = versions.get(state.version);\n throw new KeyingVerificationError(\n previousHash === state.stateHash ? \"duplicate_entry\" : \"equivocation\",\n \"stored principal policy bundle chain repeats a version\",\n );\n }\n versions.set(state.version, state.stateHash);\n }\n}\n\nfunction parseBoundBundle(\n row: SelectedPrincipalPolicyRow,\n): PrincipalPolicyBundleResponse {\n let bundle: unknown;\n try {\n bundle = storedPrincipalPolicyBundleFromJson(row);\n } catch {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"stored principal policy bundle contains malformed JSON\",\n );\n }\n if (!isPrincipalPolicyBundleResponse(bundle)) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"stored principal policy bundle is invalid\",\n );\n }\n if (\n bundle.currentState.principalType !== row.principalType ||\n bundle.currentState.principalId !== row.principalId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"stored principal policy bundle row belongs to another principal\",\n );\n }\n if (bundle.currentState.stateHash !== row.stateHash) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"stored principal policy bundle row has a different head hash\",\n );\n }\n assertUnambiguousBundleChain(bundle);\n return bundle;\n}\n\nfunction assertIndexedBundle(\n bundle: PrincipalPolicyBundleResponse,\n indexed: IndexedBundleHead,\n reference: ReferencedPrincipalHead,\n): void {\n if (\n bundle.currentState.stateHash !== indexed.bundleStateHash ||\n bundle.currentState.version !== indexed.bundleVersion\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy reference index conflicts with its bundle head\",\n );\n }\n if (!principalPolicyBundleContainsReference(bundle, reference)) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"indexed principal policy bundle does not contain the exact reference\",\n );\n }\n}\n\nfunction addCandidate(\n candidates: Map<\n string,\n { bundle: PrincipalPolicyBundleResponse; row: SelectedPrincipalPolicyRow }\n >,\n bundle: PrincipalPolicyBundleResponse,\n row: SelectedPrincipalPolicyRow,\n): void {\n const existing = candidates.get(bundle.currentState.stateHash);\n if (existing) {\n assertSameHeadPrincipalPolicyBundle(existing.row, row);\n return;\n }\n candidates.set(bundle.currentState.stateHash, { bundle, row });\n}\n\nfunction assertCurrentDoesNotConflict(\n bundle: PrincipalPolicyBundleResponse,\n reference: ReferencedPrincipalHead,\n): void {\n if (bundle.currentState.version < reference.version) {\n return;\n }\n const stateAtReference = principalPolicyBundleStates(bundle).find(\n (state) => state.version === reference.version,\n );\n if (!stateAtReference) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"current principal policy chain omits the referenced version\",\n );\n }\n if (stateAtReference.stateHash !== reference.stateHash) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"current principal policy chain conflicts with the referenced version\",\n );\n }\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"current principal policy state does not match the exact reference\",\n );\n}\n\nfunction selectNewestCandidate(\n candidates: ReadonlyMap<\n string,\n { readonly bundle: PrincipalPolicyBundleResponse }\n >,\n): PrincipalPolicyBundleResponse | null {\n let selected: PrincipalPolicyBundleResponse | null = null;\n const stateHashByVersion = new Map<number, string>();\n for (const { bundle } of candidates.values()) {\n const existingHash = stateHashByVersion.get(bundle.currentState.version);\n if (\n existingHash !== undefined &&\n existingHash !== bundle.currentState.stateHash\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"stored principal policy bundles conflict at one version\",\n );\n }\n stateHashByVersion.set(\n bundle.currentState.version,\n bundle.currentState.stateHash,\n );\n if (\n !selected ||\n bundle.currentState.version > selected.currentState.version\n ) {\n selected = bundle;\n }\n }\n return selected;\n}\n\nfunction assertReferenceShape(reference: ReferencedPrincipalHead): void {\n if (!isReferencedPrincipalStateResponse(reference)) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy reference is malformed\",\n );\n }\n if (\n !Number.isInteger(reference.version) ||\n reference.version < 1 ||\n !Number.isSafeInteger(reference.keyEpoch) ||\n reference.keyEpoch < 1 ||\n reference.principalId.length === 0 ||\n reference.stateHash.length === 0 ||\n reference.keyFingerprint.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy reference is malformed\",\n );\n }\n}\n\nasync function loadCurrentRow(\n execSql: ExecSql,\n reference: ReferencedPrincipalHead,\n): Promise<SelectedPrincipalPolicyRow | undefined> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const [row] = await db\n .select(principalPolicyBundleSelection(principalPolicies))\n .from(principalPolicies)\n .where(\n and(\n eq(principalPolicies.principalType, reference.principalType),\n eq(principalPolicies.principalId, reference.principalId),\n ),\n )\n .limit(1);\n return row;\n}\n\nasync function loadIndexedHeads(\n execSql: ExecSql,\n reference: ReferencedPrincipalHead,\n): Promise<IndexedBundleHead[]> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n return db\n .select({\n bundleStateHash: principalPolicyBundleReferences.bundleStateHash,\n bundleVersion: principalPolicyBundleReferences.bundleVersion,\n })\n .from(principalPolicyBundleReferences)\n .where(\n and(\n eq(\n principalPolicyBundleReferences.principalType,\n reference.principalType,\n ),\n eq(principalPolicyBundleReferences.principalId, reference.principalId),\n eq(principalPolicyBundleReferences.version, reference.version),\n eq(principalPolicyBundleReferences.stateHash, reference.stateHash),\n eq(principalPolicyBundleReferences.keyEpoch, reference.keyEpoch),\n eq(\n principalPolicyBundleReferences.keyFingerprint,\n reference.keyFingerprint,\n ),\n ),\n );\n}\n\nfunction indexHeadsByHash(\n heads: readonly IndexedBundleHead[],\n): Map<string, IndexedBundleHead> {\n const stateHashByVersion = new Map<number, string>();\n for (const head of heads) {\n if (\n !Number.isInteger(head.bundleVersion) ||\n head.bundleVersion < 1 ||\n head.bundleStateHash.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy reference index is malformed\",\n );\n }\n const indexedHash = stateHashByVersion.get(head.bundleVersion);\n if (indexedHash !== undefined && indexedHash !== head.bundleStateHash) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy reference index has conflicting bundle heads at one version\",\n );\n }\n stateHashByVersion.set(head.bundleVersion, head.bundleStateHash);\n }\n return new Map(heads.map((head) => [head.bundleStateHash, head]));\n}\n\nasync function loadRetainedRows(\n execSql: ExecSql,\n reference: ReferencedPrincipalHead,\n currentRow: SelectedPrincipalPolicyRow | undefined,\n indexedByHash: ReadonlyMap<string, IndexedBundleHead>,\n): Promise<SelectedPrincipalPolicyRow[]> {\n const hashes = new Set([reference.stateHash, ...indexedByHash.keys()]);\n if (currentRow) {\n hashes.delete(currentRow.stateHash);\n }\n if (hashes.size === 0) {\n return [];\n }\n // Remote reset deliberately clears mutable heads while retaining historical\n // key material, so an index target can outlive its bundle row. Such a target\n // is only a selection hint; rows that still exist remain authoritative.\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n return db\n .select(principalPolicyBundleSelection(principalPolicyBundleHistory))\n .from(principalPolicyBundleHistory)\n .where(\n and(\n eq(principalPolicyBundleHistory.principalType, reference.principalType),\n eq(principalPolicyBundleHistory.principalId, reference.principalId),\n inArray(principalPolicyBundleHistory.stateHash, [...hashes]),\n ),\n );\n}\n\nfunction collectCandidates(\n currentRow: SelectedPrincipalPolicyRow | undefined,\n retainedRows: readonly SelectedPrincipalPolicyRow[],\n indexedByHash: ReadonlyMap<string, IndexedBundleHead>,\n reference: ReferencedPrincipalHead,\n) {\n const candidates = new Map<\n string,\n { bundle: PrincipalPolicyBundleResponse; row: SelectedPrincipalPolicyRow }\n >();\n if (currentRow) {\n const bundle = parseBoundBundle(currentRow);\n const indexed = indexedByHash.get(currentRow.stateHash);\n if (indexed) {\n assertIndexedBundle(bundle, indexed, reference);\n }\n if (principalPolicyBundleContainsReference(bundle, reference)) {\n addCandidate(candidates, bundle, currentRow);\n } else {\n assertCurrentDoesNotConflict(bundle, reference);\n }\n }\n for (const row of retainedRows) {\n const bundle = parseBoundBundle(row);\n const indexed = indexedByHash.get(row.stateHash);\n if (indexed) {\n assertIndexedBundle(bundle, indexed, reference);\n } else if (!principalPolicyBundleContainsReference(bundle, reference)) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"stored principal policy bundle head does not match the exact reference\",\n );\n }\n addCandidate(candidates, bundle, row);\n }\n return candidates;\n}\n\nexport async function loadPrincipalPolicyBundleForReference(\n execSql: ExecSql,\n reference: ReferencedPrincipalHead,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): Promise<PrincipalPolicyBundleResponse | null> {\n assertReferenceShape(reference);\n await ensurePrincipalPolicyTables(execSql);\n const [currentRow, indexedHeads] = await Promise.all([\n loadCurrentRow(execSql, reference),\n loadIndexedHeads(execSql, reference),\n ]);\n const indexedByHash = indexHeadsByHash(indexedHeads);\n const retainedRows = await loadRetainedRows(\n execSql,\n reference,\n currentRow,\n indexedByHash,\n );\n const candidates = collectCandidates(\n currentRow,\n retainedRows,\n indexedByHash,\n reference,\n );\n const selected = selectNewestCandidate(candidates);\n return selected\n ? applyPrincipalPolicyReferenceCheckpoint(selected, checkpoint)\n : null;\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { KeyingVerificationError, normalizePrincipalContainerGrants, normalizePrincipalProjectionMembers, } from "../../internal/crypto/index.js";
2
- import { canonicalKeyingJsonString } from "../keying/canonicalJson.js";
1
+ import { KeyingVerificationError, normalizePrincipalContainerGrants, normalizePrincipalProjectionMembers, } from "../../../internal/crypto/index.js";
2
+ import { canonicalKeyingJsonString } from "../../keying/canonicalJson.js";
3
3
  import { assertCurrentMatchesVerifiedPolicy } from "./verifiedPrincipalPolicyCurrent.js";
4
4
  export async function assertBundleMatchesVerifiedPolicy(input) {
5
5
  const { bundle, policy } = input;
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verifiedPrincipalPolicyB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;IACD,MAAM,kCAAkC,CAAC;QACvC,OAAO,EAAE,KAAK,CAAC,MAAM;QACrB,MAAM,EAAE,KAAK,CAAC,MAAM;KACrB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n normalizePrincipalContainerGrants,\n normalizePrincipalProjectionMembers,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../../keying/canonicalJson\";\nimport { assertCurrentMatchesVerifiedPolicy } from \"./verifiedPrincipalPolicyCurrent\";\n\nexport async function assertBundleMatchesVerifiedPolicy(input: {\n bundle: PrincipalPolicyBundleResponse;\n policy: VerifiedPrincipalPolicy;\n}): Promise<void> {\n const { bundle, policy } = input;\n const history = policy.history ?? [];\n const expectedChain = [\n ...bundle.previousStates,\n {\n state: bundle.currentState,\n projection: bundle.currentProjection,\n grants: bundle.currentGrants,\n },\n ].map((entry) => ({\n ...entry,\n projection: normalizePrincipalProjectionMembers(entry.projection),\n grants: normalizePrincipalContainerGrants(entry.grants),\n }));\n const verifiedHistory = history.map((entry) => ({\n ...entry,\n projection: normalizePrincipalProjectionMembers(entry.projection),\n grants: normalizePrincipalContainerGrants(entry.grants),\n }));\n if (\n canonicalKeyingJsonString(\n expectedChain,\n \"principal policy bundle history\",\n ) !==\n canonicalKeyingJsonString(\n verifiedHistory,\n \"verified principal policy history\",\n )\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"Verified principal policy bundle history mismatch\",\n );\n }\n await assertCurrentMatchesVerifiedPolicy({\n current: input.bundle,\n policy: input.policy,\n });\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { computePrincipalMemberEnvelopesRoot, computePrincipalStatePayloadCiphertextHash, KeyingVerificationError, normalizePrincipalContainerGrants, normalizePrincipalProjectionMembers, PrincipalMemberEnvelopeValidationError, } from "../../internal/crypto/index.js";
2
- import { canonicalKeyingJsonString } from "../keying/canonicalJson.js";
1
+ import { computePrincipalMemberEnvelopesRoot, computePrincipalStatePayloadCiphertextHash, KeyingVerificationError, normalizePrincipalContainerGrants, normalizePrincipalProjectionMembers, PrincipalMemberEnvelopeValidationError, } from "../../../internal/crypto/index.js";
2
+ import { canonicalKeyingJsonString } from "../../keying/canonicalJson.js";
3
3
  function currentMismatch(message) {
4
4
  throw new KeyingVerificationError("equivocation", message);
5
5
  }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verifiedPrincipalPolicyCurrent.js","sourceRoot":"","sources":["verifiedPrincipalPolicyCurrent.ts"],"names":[],"mappings":"AACA,OAAO,EACL,mCAAmC,EACnC,0CAA0C,EAC1C,uBAAuB,EACvB,iCAAiC,EACjC,mCAAmC,EACnC,sCAAsC,GAGvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AAMvE,SAAS,eAAe,CAAC,OAAe;IACtC,MAAM,IAAI,uBAAuB,CAAC,cAAc,EAAE,OAAO,CAAC,CAAC;AAC7D,CAAC;AAED,KAAK,UAAU,mBAAmB,CAChC,OAAmC;IAEnC,IAAI,CAAC;QACH,OAAO,MAAM,mCAAmC,CAC9C,OAAO,CAAC,sBAAsB,CAAC,SAAS,CACzC,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,sCAAsC,EAAE,CAAC;YAC5D,MAAM,IAAI,uBAAuB,CAAC,eAAe,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;QACpE,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAED,KAAK,UAAU,2BAA2B,CAAC,KAG1C;IACC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;IAClC,MAAM,WAAW,GAAG,MAAM,0CAA0C,CAClE,OAAO,CAAC,cAAc,CAAC,UAAU,CAClC,CAAC;IACF,MAAM,aAAa,GAAG,MAAM,mBAAmB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AC,SAAS,EAChD,CAAC;QACD,eAAe,CAAC,iDAAiD,CAAC,CAAC;IACrE,CAAC;IACD,IACE,yBAAyB,CACvB,OAAO,CAAC,YAAY,EACpB,gCAAgC,CACjC;QACC,yBAAyB,CACvB,MAAM,CAAC,KAAK,EACZ,iCAAiC,CAClC;QACH,yBAAyB,CACvB,mCAAmC,CAAC,OAAO,CAAC,iBAAiB,CAAC,EAC9D,qCAAqC,CACtC;YACC,yBAAyB,CACvB,mCAAmC,CAAC,MAAM,CAAC,UAAU,CAAC,EACtD,sCAAsC,CACvC;QACH,yBAAyB,CACvB,iCAAiC,CAAC,OAAO,CAAC,aAAa,CAAC,EACxD,iCAAiC,CAClC;YACC,yBAAyB,CACvB,iCAAiC,CAAC,MAAM,CAAC,MAAM,CAAC,EAChD,kCAAkC,CACnC,EACH,CAAC;QACD,eAAe,CAAC,oDAAoD,CAAC,CAAC;IACxE,CAAC;IAED,MAAM,2BAA2B,CAAC,KAAK,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n computePrincipalMemberEnvelopesRoot,\n computePrincipalStatePayloadCiphertextHash,\n KeyingVerificationError,\n normalizePrincipalContainerGrants,\n normalizePrincipalProjectionMembers,\n PrincipalMemberEnvelopeValidationError,\n type VerifiedPrincipalPolicy,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { canonicalKeyingJsonString } from \"../../keying/canonicalJson\";\n\ntype VerifiedCurrentPolicy =\n | VerifiedPrincipalPolicy\n | VerifiedPrincipalPolicyCurrent;\n\nfunction currentMismatch(message: string): never {\n throw new KeyingVerificationError(\"equivocation\", message);\n}\n\nasync function memberEnvelopesRoot(\n current: PrincipalPolicyPageCurrent,\n): Promise<string> {\n try {\n return await computePrincipalMemberEnvelopesRoot(\n current.currentMemberEnvelopes.envelopes,\n );\n } catch (error) {\n if (error instanceof PrincipalMemberEnvelopeValidationError) {\n throw new KeyingVerificationError(\"invalid_shape\", error.message);\n }\n throw error;\n }\n}\n\nasync function assertCurrentPayloadMatches(input: {\n current: PrincipalPolicyPageCurrent;\n policy: VerifiedCurrentPolicy;\n}): Promise<void> {\n const { current, policy } = input;\n const payloadHash = await computePrincipalStatePayloadCiphertextHash(\n current.currentPayload.ciphertext,\n );\n const envelopesRoot = await memberEnvelopesRoot(current);\n if (\n current.currentPayload.principalType !== policy.principalType ||\n current.currentPayload.principalId !== policy.principalId ||\n current.currentPayload.stateHash !== policy.stateHash ||\n current.currentPayload.ciphertextHash !== payloadHash ||\n policy.state.payloadCiphertextHash !== payloadHash ||\n current.currentMemberEnvelopes.principalType !== policy.principalType ||\n current.currentMemberEnvelopes.principalId !== policy.principalId ||\n current.currentMemberEnvelopes.stateHash !== policy.stateHash ||\n current.currentMemberEnvelopes.epoch !== policy.keyEpoch ||\n envelopesRoot !== policy.state.memberEnvelopesRoot\n ) {\n currentMismatch(\"Verified principal policy current payload mismatch\");\n }\n}\n\n/** Bind current wire artifacts to already verified policy evidence; never authenticate history. */\nexport async function assertCurrentMatchesVerifiedPolicy(input: {\n current: PrincipalPolicyPageCurrent;\n policy: VerifiedCurrentPolicy;\n}): Promise<void> {\n const { current, policy } = input;\n if (\n current.currentState.principalType !== policy.principalType ||\n current.currentState.principalId !== policy.principalId ||\n current.currentState.version !== policy.version ||\n current.currentState.keyEpoch !== policy.keyEpoch ||\n current.currentState.stateHash !== policy.stateHash ||\n policy.checkpoint.version !== policy.version ||\n policy.checkpoint.stateHash !== policy.stateHash\n ) {\n currentMismatch(\"Verified principal policy current head mismatch\");\n }\n if (\n canonicalKeyingJsonString(\n current.currentState,\n \"principal policy current state\",\n ) !==\n canonicalKeyingJsonString(\n policy.state,\n \"verified principal policy state\",\n ) ||\n canonicalKeyingJsonString(\n normalizePrincipalProjectionMembers(current.currentProjection),\n \"principal policy current projection\",\n ) !==\n canonicalKeyingJsonString(\n normalizePrincipalProjectionMembers(policy.projection),\n \"verified principal policy projection\",\n ) ||\n canonicalKeyingJsonString(\n normalizePrincipalContainerGrants(current.currentGrants),\n \"principal policy current grants\",\n ) !==\n canonicalKeyingJsonString(\n normalizePrincipalContainerGrants(policy.grants),\n \"verified principal policy grants\",\n )\n ) {\n currentMismatch(\"Verified principal policy current content mismatch\");\n }\n\n await assertCurrentPayloadMatches(input);\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { getClientSQLitePersistenceRuntime } from "../sqlite/sqlitePersistenceRuntime.js";
1
+ import { getClientSQLitePersistenceRuntime } from "../../sqlite/sqlitePersistenceRuntime.js";
2
2
  import { ensurePrincipalPolicyTables, retainPrincipalPolicyBundleInTransaction, } from "./principalPolicyPersistence.js";
3
3
  import { assertBundleMatchesVerifiedPolicy } from "./verifiedPrincipalPolicyBundle.js";
4
4
  /** Retains a just-verified epoch without promoting it to the mutable head. */
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verifiedPrincipalPolicyRetentionPersistence.js","sourceRoot":"","sources":["verifiedPrincipalPolicyRetentionPersistence.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAE1F,OAAO,EACL,2BAA2B,EAC3B,wCAAwC,GACzC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,iCAAiC,EAAE,MAAM,iCAAiC,CAAC;AAEpF,8EAA8E;AAC9E,MAAM,CAAC,KAAK,UAAU,mCAAmC,CAAC,KAOzD;IACC,MAAM,iCAAiC,CAAC,KAAK,CAAC,CAAC;IAC/C,MAAM,2BAA2B,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACjD,MAAM,OAAO,GAAG,iCAAiC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACjE,MAAM,MAAM,GAAG,CACb,EAAkE,EAClE,EAAE,CACF,wCAAwC,CACtC,EAAE,EACF,KAAK,CAAC,MAAM,EACZ,KAAK,CAAC,SAAS,EACf,KAAK,CAAC,cAAc,CACrB,CAAC;IACJ,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;QACvB,MAAM,OAAO,CAAC,kBAAkB,CAAC,MAAM,EAAE,KAAK,CAAC,YAAY,EAAE;YAC3D,QAAQ,EAAE,WAAW;SACtB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IACD,MAAM,OAAO,CAAC,WAAW,CAAC,MAAM,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;AAC/D,CAAC","sourcesContent":["import type { VerifiedPrincipalPolicy } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport {\n ensurePrincipalPolicyTables,\n retainPrincipalPolicyBundleInTransaction,\n} from \"./principalPolicyPersistence\";\nimport { assertBundleMatchesVerifiedPolicy } from \"./verifiedPrincipalPolicyBundle\";\n\n/** Retains a just-verified epoch without promoting it to the mutable head. */\nexport async function retainVerifiedPrincipalPolicyBundle(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n readonly policy: VerifiedPrincipalPolicy;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly updatedAt: string;\n}): Promise<void> {\n await assertBundleMatchesVerifiedPolicy(input);\n await ensurePrincipalPolicyTables(input.execSql);\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const retain = (\n tx: Parameters<typeof retainPrincipalPolicyBundleInTransaction>[0],\n ) =>\n retainPrincipalPolicyBundleInTransaction(\n tx,\n input.bundle,\n input.updatedAt,\n input.organizationId,\n );\n if (input.stillCurrent) {\n await runtime.guardedTransaction(retain, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(retain, { behavior: \"immediate\" });\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { isKeyingVerificationCode, serializeKeyingCanonicalJson, } from "../../internal/crypto/index.js";
2
2
  import { desc, eq, inArray, isNull, sql } from "drizzle-orm";
3
- import { securityIncidents, securityIncidentTable, } from "../sqlite/securityIncidentSchema.js";
3
+ import { securityIncidents, securityIncidentTable, } from "../sqlite/schema/securityIncidentSchema.js";
4
4
  import { getClientSQLitePersistenceRuntime } from "../sqlite/sqlitePersistenceRuntime.js";
5
5
  import { ensureSqlTables } from "../sqlite/sqlSchema.js";
6
6
  const SECURITY_INCIDENT_RETENTION_LIMIT = 1_000;
@@ -1 +1 @@
1
- {"version":3,"file":"securityIncidentPersistence.js","sourceRoot":"","sources":["securityIncidentPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,wBAAwB,EACxB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAK7D,OAAO,EACL,iBAAiB,EACjB,qBAAqB,GACtB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,iCAAiC,EAAE,MAAM,oCAAoC,CAAC;AACvF,OAAO,EAAgB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAepE,MAAM,iCAAiC,GAAG,KAAK,CAAC;AAEhD;;;;GAIG;AACH,SAAS,uBAAuB,CAC9B,cAA4D;IAE5D,OAAO,4BAA4B,CAAC,cAAc,IAAI,EAAE,CAAC,CAAC;AAC5D,CAAC;AAED,SAAS,mBAAmB,CAAC,KAAa;IACxC,IAAI,MAAe,CAAC;IACpB,IAAI,CAAC;QACH,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IAC7B,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QACnE,OAAO,EAAE,CAAC;IACZ,CAAC;IAC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AE,IAAI,CAAC,iBAAiB,CAAC,EAAE,CAAC,CAAC;SAC3E,KAAK,CAAC,iCAAiC,CAAC,CAAC;IAC5C,OAAO,IAAI,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC;AAC5C,CAAC","sourcesContent":["import {\n isKeyingVerificationCode,\n serializeKeyingCanonicalJson,\n} from \"@tearleads/crypto\";\nimport { desc, eq, inArray, isNull, sql } from \"drizzle-orm\";\nimport type {\n SecurityIncident,\n SecurityIncidentObjectKind,\n} from \"../shared/securityIncidents\";\nimport {\n securityIncidents,\n securityIncidentTable,\n} from \"../sqlite/securityIncidentSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\n\ninterface SecurityIncidentWrite {\n readonly trustDomain: string | null;\n readonly code: SecurityIncident[\"code\"];\n readonly operation: string;\n readonly objectKind: SecurityIncidentObjectKind;\n readonly objectId: string | null;\n readonly organizationId?: string | null | undefined;\n readonly evidenceHashes?: Readonly<Record<string, string>> | undefined;\n readonly detectedAt: string;\n readonly lastDetectedAt: string;\n readonly occurrenceCount: number;\n}\n\nconst SECURITY_INCIDENT_RETENTION_LIMIT = 1_000;\n\n/**\n * The incident id hashes this text, so it must be identical on every device:\n * code-unit key order, no locale collation, and no `Object` property-order\n * rules (which would float integer-like keys ahead of the sort).\n */\nfunction serializeEvidenceHashes(\n evidenceHashes: Readonly<Record<string, string>> | undefined,\n): string {\n return serializeKeyingCanonicalJson(evidenceHashes ?? {});\n}\n\nfunction parseEvidenceHashes(value: string): Readonly<Record<string, string>> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(value);\n } catch {\n return {};\n }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return {};\n }\n const entries: Array<[string, string]> = [];\n for (const [key, item] of Object.entries(parsed)) {\n if (key.length === 0 || typeof item !== \"string\") {\n return {};\n }\n entries.push([key, item]);\n }\n // Object.fromEntries keeps every key, including \"__proto__\", which an index\n // assignment on a plain object would silently drop.\n return Object.fromEntries(entries);\n}\n\nfunction parseVerificationCode(value: string): SecurityIncident[\"code\"] {\n if (isKeyingVerificationCode(value)) return value;\n return \"unrecognized_verification_code\";\n}\n\nfunction parseObjectKind(value: string): SecurityIncidentObjectKind {\n switch (value) {\n case \"blob\":\n case \"container\":\n case \"document\":\n case \"principal\":\n case \"user\":\n case \"unknown\":\n return value;\n default:\n return \"unknown\";\n }\n}\n\nasync function ensureSecurityIncidentTable(execSql: ExecSql): Promise<void> {\n await ensureSqlTables(execSql, [securityIncidentTable]);\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\n \"\",\n );\n}\n\nasync function deriveSecurityIncidentId(input: {\n readonly code: SecurityIncident[\"code\"];\n readonly evidenceHashes: string;\n readonly objectId: string | null;\n readonly objectKind: SecurityIncidentObjectKind;\n readonly operation: string;\n readonly organizationId: string | null;\n readonly trustDomain: string | null;\n}): Promise<string> {\n const canonicalIdentity = JSON.stringify([\n input.trustDomain,\n input.code,\n input.operation,\n input.objectKind,\n input.objectId,\n input.organizationId,\n input.evidenceHashes,\n ]);\n const digest = await crypto.subtle.digest(\n \"SHA-256\",\n new TextEncoder().encode(canonicalIdentity),\n );\n return `incident_v1_${bytesToHex(new Uint8Array(digest))}`;\n}\n\nfunction parseSecurityIncidentRow(\n row: typeof securityIncidents.$inferSelect,\n): SecurityIncident {\n return {\n ...row,\n code: parseVerificationCode(row.code),\n evidenceHashes: parseEvidenceHashes(row.evidenceHashes),\n objectKind: parseObjectKind(row.objectKind),\n trustDomain: row.trustDomain,\n };\n}\n\nexport async function appendSecurityIncident(\n execSql: ExecSql,\n incident: SecurityIncidentWrite,\n): Promise<SecurityIncident | null> {\n await ensureSecurityIncidentTable(execSql);\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const evidenceHashes = serializeEvidenceHashes(incident.evidenceHashes);\n const organizationId = incident.organizationId ?? null;\n const id = await deriveSecurityIncidentId({\n code: incident.code,\n evidenceHashes,\n objectId: incident.objectId,\n objectKind: incident.objectKind,\n operation: incident.operation,\n organizationId,\n trustDomain: incident.trustDomain,\n });\n const row = await runtime.transaction(async (tx) => {\n await tx\n .insert(securityIncidents)\n .values({\n ...incident,\n evidenceHashes,\n id,\n organizationId,\n trustDomain: incident.trustDomain,\n })\n .onConflictDoUpdate({\n target: securityIncidents.id,\n set: {\n detectedAt: sql`min(${securityIncidents.detectedAt}, ${incident.detectedAt})`,\n lastDetectedAt: sql`max(${securityIncidents.lastDetectedAt}, ${incident.lastDetectedAt})`,\n occurrenceCount: sql`${securityIncidents.occurrenceCount} + ${incident.occurrenceCount}`,\n },\n })\n .run();\n const trustDomainCondition =\n incident.trustDomain === null\n ? isNull(securityIncidents.trustDomain)\n : eq(securityIncidents.trustDomain, incident.trustDomain);\n const staleRows = await tx\n .select({ id: securityIncidents.id })\n .from(securityIncidents)\n .where(trustDomainCondition)\n .orderBy(\n desc(securityIncidents.lastDetectedAt),\n desc(securityIncidents.id),\n )\n .limit(1)\n .offset(SECURITY_INCIDENT_RETENTION_LIMIT);\n // Each call can add at most one distinct row, so deleting the single 1,001st\n // row restores the cap. A future bulk writer must delete its whole excess.\n if (staleRows.length > 0) {\n await tx\n .delete(securityIncidents)\n .where(\n inArray(\n securityIncidents.id,\n staleRows.map((staleRow) => staleRow.id),\n ),\n )\n .run();\n }\n const [storedRow] = await tx\n .select()\n .from(securityIncidents)\n .where(eq(securityIncidents.id, id))\n .limit(1);\n return storedRow;\n });\n return row ? parseSecurityIncidentRow(row) : null;\n}\n\nexport async function listSecurityIncidents(\n execSql: ExecSql,\n trustDomain: string | null,\n): Promise<SecurityIncident[]> {\n await ensureSecurityIncidentTable(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select()\n .from(securityIncidents)\n .where(\n trustDomain === null\n ? isNull(securityIncidents.trustDomain)\n : eq(securityIncidents.trustDomain, trustDomain),\n )\n .orderBy(desc(securityIncidents.lastDetectedAt), desc(securityIncidents.id))\n .limit(SECURITY_INCIDENT_RETENTION_LIMIT);\n return rows.map(parseSecurityIncidentRow);\n}\n"]}
1
+ {"version":3,"file":"securityIncidentPersistence.js","sourceRoot":"","sources":["securityIncidentPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,wBAAwB,EACxB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAK7D,OAAO,EACL,iBAAiB,EACjB,qBAAqB,GACtB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,iCAAiC,EAAE,MAAM,oCAAoC,CAAC;AACvF,OAAO,EAAgB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAepE,MAAM,iCAAiC,GAAG,KAAK,CAAC;AAEhD;;;;GAIG;AACH,SAAS,uBAAuB,CAC9B,cAA4D;IAE5D,OAAO,4BAA4B,CAAC,cAAc,IAAI,EAAE,CAAC,CAAC;AAC5D,CAAC;AAED,SAAS,mBAAmB,CAAC,KAAa;IACxC,IAAI,MAAe,CAAC;IACpB,IAAI,CAAC;QACH,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IAC7B,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QACnE,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,MAAM,OAAO,GAA4B,EAAE,CAAC;IAC5C,KAAK,MAAM,CAAC,GAAG,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QACjD,IAAI,GAAG,CAAC,MAAM,KA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{\n isKeyingVerificationCode,\n serializeKeyingCanonicalJson,\n} from \"@tearleads/crypto\";\nimport { desc, eq, inArray, isNull, sql } from \"drizzle-orm\";\nimport type {\n SecurityIncident,\n SecurityIncidentObjectKind,\n} from \"../shared/securityIncidents\";\nimport {\n securityIncidents,\n securityIncidentTable,\n} from \"../sqlite/schema/securityIncidentSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\n\ninterface SecurityIncidentWrite {\n readonly trustDomain: string | null;\n readonly code: SecurityIncident[\"code\"];\n readonly operation: string;\n readonly objectKind: SecurityIncidentObjectKind;\n readonly objectId: string | null;\n readonly organizationId?: string | null | undefined;\n readonly evidenceHashes?: Readonly<Record<string, string>> | undefined;\n readonly detectedAt: string;\n readonly lastDetectedAt: string;\n readonly occurrenceCount: number;\n}\n\nconst SECURITY_INCIDENT_RETENTION_LIMIT = 1_000;\n\n/**\n * The incident id hashes this text, so it must be identical on every device:\n * code-unit key order, no locale collation, and no `Object` property-order\n * rules (which would float integer-like keys ahead of the sort).\n */\nfunction serializeEvidenceHashes(\n evidenceHashes: Readonly<Record<string, string>> | undefined,\n): string {\n return serializeKeyingCanonicalJson(evidenceHashes ?? {});\n}\n\nfunction parseEvidenceHashes(value: string): Readonly<Record<string, string>> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(value);\n } catch {\n return {};\n }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return {};\n }\n const entries: Array<[string, string]> = [];\n for (const [key, item] of Object.entries(parsed)) {\n if (key.length === 0 || typeof item !== \"string\") {\n return {};\n }\n entries.push([key, item]);\n }\n // Object.fromEntries keeps every key, including \"__proto__\", which an index\n // assignment on a plain object would silently drop.\n return Object.fromEntries(entries);\n}\n\nfunction parseVerificationCode(value: string): SecurityIncident[\"code\"] {\n if (isKeyingVerificationCode(value)) return value;\n return \"unrecognized_verification_code\";\n}\n\nfunction parseObjectKind(value: string): SecurityIncidentObjectKind {\n switch (value) {\n case \"blob\":\n case \"container\":\n case \"document\":\n case \"principal\":\n case \"user\":\n case \"unknown\":\n return value;\n default:\n return \"unknown\";\n }\n}\n\nasync function ensureSecurityIncidentTable(execSql: ExecSql): Promise<void> {\n await ensureSqlTables(execSql, [securityIncidentTable]);\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\n \"\",\n );\n}\n\nasync function deriveSecurityIncidentId(input: {\n readonly code: SecurityIncident[\"code\"];\n readonly evidenceHashes: string;\n readonly objectId: string | null;\n readonly objectKind: SecurityIncidentObjectKind;\n readonly operation: string;\n readonly organizationId: string | null;\n readonly trustDomain: string | null;\n}): Promise<string> {\n const canonicalIdentity = JSON.stringify([\n input.trustDomain,\n input.code,\n input.operation,\n input.objectKind,\n input.objectId,\n input.organizationId,\n input.evidenceHashes,\n ]);\n const digest = await crypto.subtle.digest(\n \"SHA-256\",\n new TextEncoder().encode(canonicalIdentity),\n );\n return `incident_v1_${bytesToHex(new Uint8Array(digest))}`;\n}\n\nfunction parseSecurityIncidentRow(\n row: typeof securityIncidents.$inferSelect,\n): SecurityIncident {\n return {\n ...row,\n code: parseVerificationCode(row.code),\n evidenceHashes: parseEvidenceHashes(row.evidenceHashes),\n objectKind: parseObjectKind(row.objectKind),\n trustDomain: row.trustDomain,\n };\n}\n\nexport async function appendSecurityIncident(\n execSql: ExecSql,\n incident: SecurityIncidentWrite,\n): Promise<SecurityIncident | null> {\n await ensureSecurityIncidentTable(execSql);\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const evidenceHashes = serializeEvidenceHashes(incident.evidenceHashes);\n const organizationId = incident.organizationId ?? null;\n const id = await deriveSecurityIncidentId({\n code: incident.code,\n evidenceHashes,\n objectId: incident.objectId,\n objectKind: incident.objectKind,\n operation: incident.operation,\n organizationId,\n trustDomain: incident.trustDomain,\n });\n const row = await runtime.transaction(async (tx) => {\n await tx\n .insert(securityIncidents)\n .values({\n ...incident,\n evidenceHashes,\n id,\n organizationId,\n trustDomain: incident.trustDomain,\n })\n .onConflictDoUpdate({\n target: securityIncidents.id,\n set: {\n detectedAt: sql`min(${securityIncidents.detectedAt}, ${incident.detectedAt})`,\n lastDetectedAt: sql`max(${securityIncidents.lastDetectedAt}, ${incident.lastDetectedAt})`,\n occurrenceCount: sql`${securityIncidents.occurrenceCount} + ${incident.occurrenceCount}`,\n },\n })\n .run();\n const trustDomainCondition =\n incident.trustDomain === null\n ? isNull(securityIncidents.trustDomain)\n : eq(securityIncidents.trustDomain, incident.trustDomain);\n const staleRows = await tx\n .select({ id: securityIncidents.id })\n .from(securityIncidents)\n .where(trustDomainCondition)\n .orderBy(\n desc(securityIncidents.lastDetectedAt),\n desc(securityIncidents.id),\n )\n .limit(1)\n .offset(SECURITY_INCIDENT_RETENTION_LIMIT);\n // Each call can add at most one distinct row, so deleting the single 1,001st\n // row restores the cap. A future bulk writer must delete its whole excess.\n if (staleRows.length > 0) {\n await tx\n .delete(securityIncidents)\n .where(\n inArray(\n securityIncidents.id,\n staleRows.map((staleRow) => staleRow.id),\n ),\n )\n .run();\n }\n const [storedRow] = await tx\n .select()\n .from(securityIncidents)\n .where(eq(securityIncidents.id, id))\n .limit(1);\n return storedRow;\n });\n return row ? parseSecurityIncidentRow(row) : null;\n}\n\nexport async function listSecurityIncidents(\n execSql: ExecSql,\n trustDomain: string | null,\n): Promise<SecurityIncident[]> {\n await ensureSecurityIncidentTable(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select()\n .from(securityIncidents)\n .where(\n trustDomain === null\n ? isNull(securityIncidents.trustDomain)\n : eq(securityIncidents.trustDomain, trustDomain),\n )\n .orderBy(desc(securityIncidents.lastDetectedAt), desc(securityIncidents.id))\n .limit(SECURITY_INCIDENT_RETENTION_LIMIT);\n return rows.map(parseSecurityIncidentRow);\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { and, eq } from "drizzle-orm";
2
- import { trustedUserIdentityPins, trustedUserIdentityPinTables, } from "../sqlite/schema.js";
2
+ import { trustedUserIdentityPins, trustedUserIdentityPinTables, } from "../sqlite/schema/index.js";
3
3
  import { getClientSQLitePersistenceRuntime, } from "../sqlite/sqlitePersistenceRuntime.js";
4
4
  import { ensureSqlTables } from "../sqlite/sqlSchema.js";
5
5
  import { TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE, TRUSTED_USER_IDENTITY_FORMAT_VERSION, TRUSTED_USER_IDENTITY_SIGNING_SUITE, } from "../trustedUserIdentity/types.js";
@@ -1,8 +1,8 @@
1
1
  import type { VerifiedManifestCitations, WriterProjectionTarget } from "../../internal/api-client/index.js";
2
2
  import { type AccessManifestBundleWireResponse } from "../../internal/validators/response/index.js";
3
+ import { verifiedAccessManifestBundles as bundles } from "../sqlite/schema/verifiedManifestBundleSchema.js";
3
4
  import { type ClientSQLiteTransactionScope } from "../sqlite/sqlitePersistenceRuntime.js";
4
5
  import { type ExecSql } from "../sqlite/sqlSchema.js";
5
- import { verifiedAccessManifestBundles as bundles } from "../sqlite/verifiedManifestBundleSchema.js";
6
6
  /**
7
7
  * Bounds local bytes (a bundle is ~10–20 KB). Evicting the least recently
8
8
  * verified rows only makes a later read carry those bundles again.
@@ -2,12 +2,12 @@ import { toFingerprint } from "../../internal/crypto/index.js";
2
2
  import { isAccessManifestBundleWireResponse, } from "../../internal/validators/response/index.js";
3
3
  import { KNOWN_MANIFEST_HINT_LIMIT, MAX_CONTAINER_PATH_LENGTH, } from "../../internal/validators/util/index.js";
4
4
  import { and, asc, desc, eq, inArray, sql } from "drizzle-orm";
5
- import { containers } from "../sqlite/containerSchema.js";
6
- import { documentDiscoveryHeads, pendingDocumentDiscoveries, } from "../sqlite/documentDiscoveryEvidenceSchema.js";
7
- import { containerTables, documentContainerProjection, documentContainerProjectionTables, } from "../sqlite/schema.js";
5
+ import { containerTables, documentContainerProjection, documentContainerProjectionTables, } from "../sqlite/schema/index.js";
6
+ import { containers } from "../sqlite/schema/containerSchema.js";
7
+ import { documentDiscoveryHeads, pendingDocumentDiscoveries, } from "../sqlite/schema/documentDiscoveryEvidenceSchema.js";
8
+ import { verifiedAccessManifestBundles as bundles, verifiedManifestBundleTables, } from "../sqlite/schema/verifiedManifestBundleSchema.js";
8
9
  import { getClientSQLitePersistenceRuntime, } from "../sqlite/sqlitePersistenceRuntime.js";
9
10
  import { ensureSqlTables } from "../sqlite/sqlSchema.js";
10
- import { verifiedAccessManifestBundles as bundles, verifiedManifestBundleTables, } from "../sqlite/verifiedManifestBundleSchema.js";
11
11
  /**
12
12
  * Bounds local bytes (a bundle is ~10–20 KB). Evicting the least recently
13
13
  * verified rows only makes a later read carry those bundles again.