@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.
- package/client/organizations/organizationAccessRestoration.js +1 -1
- package/data/containers/shared/mutationAcknowledgement.js +1 -1
- package/data/containers/shared/mutationAcknowledgement.js.map +1 -1
- package/data/documents/blob/shared/projection.js +3 -3
- package/data/documents/blob/shared/projection.js.map +1 -1
- package/data/documents/shared/{containerKekCurrency.d.ts → containerKek/containerKekCurrency.d.ts} +1 -1
- package/data/documents/shared/{containerKekEntryVerification.js → containerKek/containerKekEntryVerification.js} +1 -1
- package/data/documents/shared/{containerKekLogFetch.d.ts → containerKek/containerKekLogFetch.d.ts} +1 -1
- package/data/documents/shared/{containerKekLogFetch.js → containerKek/containerKekLogFetch.js} +1 -1
- package/data/documents/shared/{containerKekPath.js → containerKek/containerKekPath.js} +3 -3
- package/data/documents/shared/containerKek/containerKekPath.js.map +1 -0
- package/data/documents/shared/{containerKekPathHistory.d.ts → containerKek/containerKekPathHistory.d.ts} +3 -3
- package/data/documents/shared/{containerKekPathHistory.js → containerKek/containerKekPathHistory.js} +4 -4
- package/data/documents/shared/containerKek/containerKekPathHistory.js.map +1 -0
- package/data/documents/shared/{containerKekPathVerification.d.ts → containerKek/containerKekPathVerification.d.ts} +5 -5
- package/data/documents/shared/{containerKekPathVerification.js → containerKek/containerKekPathVerification.js} +2 -2
- package/data/documents/shared/containerKek/containerKekPathVerification.js.map +1 -0
- package/data/documents/shared/{containerKekWrapping.js → containerKek/containerKekWrapping.js} +3 -3
- package/data/documents/shared/containerKek/containerKekWrapping.js.map +1 -0
- package/data/documents/shared/{keyringLogWalk.d.ts → containerKek/keyringLogWalk.d.ts} +2 -2
- package/data/documents/shared/{keyringLogWalk.js → containerKek/keyringLogWalk.js} +1 -1
- package/data/documents/shared/{keyringRebuild.d.ts → containerKek/keyringRebuild.d.ts} +3 -3
- package/data/documents/shared/{keyringRebuild.js → containerKek/keyringRebuild.js} +3 -3
- package/data/documents/shared/containerKek/keyringRebuild.js.map +1 -0
- package/data/documents/shared/crypto.js +2 -2
- package/data/documents/shared/crypto.js.map +1 -1
- package/data/documents/shared/events.js +1 -1
- package/data/documents/shared/{projection.d.ts → projection/index.d.ts} +7 -7
- package/data/documents/shared/{projection.js → projection/index.js} +9 -9
- package/data/documents/shared/projection/index.js.map +1 -0
- package/data/documents/shared/{projectionContentKeys.d.ts → projection/projectionContentKeys.d.ts} +6 -6
- package/data/documents/shared/{projectionContentKeys.js → projection/projectionContentKeys.js} +9 -9
- package/data/documents/shared/projection/projectionContentKeys.js.map +1 -0
- package/data/documents/shared/{projectionTargets.d.ts → projection/projectionTargets.d.ts} +4 -4
- package/data/documents/shared/{projectionTargets.js → projection/projectionTargets.js} +3 -3
- package/data/documents/shared/projection/projectionTargets.js.map +1 -0
- package/data/documents/shared/responses.d.ts +1 -1
- package/data/documents/shared/responses.js +1 -1
- package/data/documents/shared/responses.js.map +1 -1
- package/data/documents/shared/{documentSyncUpdateDecryption.js → sync/documentSyncUpdateDecryption.js} +10 -10
- package/data/documents/shared/sync/documentSyncUpdateDecryption.js.map +1 -0
- package/data/documents/shared/{documentSyncUpdateIsolation.d.ts → sync/documentSyncUpdateIsolation.d.ts} +3 -3
- package/data/documents/shared/{documentSyncUpdateIsolation.js → sync/documentSyncUpdateIsolation.js} +1 -1
- package/data/documents/shared/sync/documentSyncUpdateIsolation.js.map +1 -0
- package/data/documents/shared/{mutationAcknowledgement.js → sync/mutationAcknowledgement.js} +1 -1
- package/data/documents/shared/sync/mutationAcknowledgement.js.map +1 -0
- package/data/documents/shared/{pullContinuation.js → sync/pullContinuation.js} +1 -1
- package/data/documents/shared/{syncPagination.d.ts → sync/syncPagination.d.ts} +2 -2
- package/data/documents/shared/{syncPagination.js → sync/syncPagination.js} +1 -1
- package/data/documents/shared/sync/syncPagination.js.map +1 -0
- package/data/documents/shared/{syncResponseAuthorization.js → sync/syncResponseAuthorization.js} +3 -3
- package/data/documents/shared/sync/syncResponseAuthorization.js.map +1 -0
- package/data/documents/shared/{syncResponses.d.ts → sync/syncResponses.d.ts} +2 -2
- package/data/documents/shared/{syncResponses.js → sync/syncResponses.js} +6 -6
- package/data/documents/shared/sync/syncResponses.js.map +1 -0
- package/data/documents/shared/{syncSubmitFailure.d.ts → sync/syncSubmitFailure.d.ts} +1 -1
- package/data/documents/shared/types.d.ts +3 -3
- package/data/documents/shared/types.js.map +1 -1
- package/data/keyingProjectionVerification/checkpoints/accessManifestCheckpointEnforcement.js +1 -1
- package/data/keyingProjectionVerification/checkpoints/accessManifestCheckpointEnforcement.js.map +1 -1
- package/data/keyingProjectionVerification/checkpoints/checkpointContext.d.ts +1 -1
- package/data/keyingProjectionVerification/checkpoints/checkpointContext.js +1 -1
- package/data/keyingProjectionVerification/checkpoints/checkpointContext.js.map +1 -1
- package/data/keyingProjectionVerification/checkpoints/manifestCheckpointVerification.js +1 -1
- package/data/keyingProjectionVerification/checkpoints/manifestCheckpointVerification.js.map +1 -1
- package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js +4 -4
- package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js.map +1 -1
- package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointEnforcement.js +1 -1
- package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointEnforcement.js.map +1 -1
- package/data/keyingProjectionVerification/documentPurge/documentPurgePolicyCheckpoints.js +1 -1
- package/data/keyingProjectionVerification/documentPurge/documentPurgePolicyCheckpoints.js.map +1 -1
- package/data/keyingProjectionVerification/documentPurge/documentPurgePolicyCurrency.js +1 -1
- package/data/keyingProjectionVerification/documentPurge/documentPurgePolicyCurrency.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js +3 -3
- package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js +4 -4
- package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicy/resolvedPrincipalPolicy.js +2 -2
- package/data/keyingProjectionVerification/principalPolicy/resolvedPrincipalPolicy.js.map +1 -1
- package/data/persistence/container-contents/containerContentsPersistence.js +3 -3
- package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerContentsPersistenceTypes.d.ts +2 -2
- package/data/persistence/container-contents/containerContentsPersistenceTypes.js.map +1 -1
- package/data/persistence/container-contents/containerCreateIntentSettlement.js +1 -1
- package/data/persistence/container-contents/containerDeletionPersistence.js +2 -2
- package/data/persistence/container-contents/containerDocumentReassignment.js +2 -2
- package/data/persistence/container-contents/containerDocumentReassignment.js.map +1 -1
- package/data/persistence/container-contents/containerHydrationPersistence.js +3 -3
- package/data/persistence/container-contents/containerHydrationPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerIntentPersistence.js +1 -1
- package/data/persistence/container-contents/containerMetadataMutationPersistence.js +5 -5
- package/data/persistence/container-contents/containerMetadataMutationPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerMetadataPullContinuationPersistence.js +1 -1
- package/data/persistence/container-contents/containerMetadataRows.js +3 -3
- package/data/persistence/container-contents/containerMetadataRows.js.map +1 -1
- package/data/persistence/container-contents/containerMoveAbandonPersistence.js +1 -1
- package/data/persistence/container-contents/containerMoveIntentRows.js +1 -1
- package/data/persistence/container-contents/containerPendingUpdatePersistence.js +3 -3
- package/data/persistence/container-contents/containerPendingUpdatePersistence.js.map +1 -1
- package/data/persistence/container-contents/containerRebindPersistence.js +1 -1
- package/data/persistence/container-contents/containerReconcilePersistence.js +2 -2
- package/data/persistence/container-contents/containerRecoveryPersistence.js +1 -1
- package/data/persistence/container-contents/containerRemovalWork.js +3 -3
- package/data/persistence/container-contents/containerRemovalWork.js.map +1 -1
- package/data/persistence/container-contents/containerStructuralRepair.js +1 -1
- package/data/persistence/container-contents/documentLinkRemovalRepair.js +2 -2
- package/data/persistence/container-contents/documentLinkRemovalRepair.js.map +1 -1
- package/data/persistence/container-contents/documentMoveIntentPersistence.js +2 -2
- package/data/persistence/container-contents/documentMoveIntentPersistence.js.map +1 -1
- package/data/persistence/container-contents/documentPlacementIntentEnqueue.js +2 -2
- package/data/persistence/container-contents/documentPlacementIntentEnqueue.js.map +1 -1
- package/data/persistence/container-contents/documentPurgePlacement.js +14 -1
- package/data/persistence/container-contents/documentPurgePlacement.js.map +1 -1
- package/data/persistence/container-contents/dormantContainerMetadata.js +1 -1
- package/data/persistence/container-contents/dormantMetadataSweep.js +1 -1
- package/data/persistence/container-contents/pendingContainerCreate.js +1 -1
- package/data/persistence/container-contents/supersededContainerBindings.js +1 -1
- package/data/persistence/containers/containerPersistence.js +1 -1
- package/data/persistence/containers/containerSyncWatermarkPersistence.js +1 -1
- package/data/persistence/containers/documentContainerProjectionPersistence.js +1 -1
- package/data/persistence/containers/documentPlacement.js +1 -1
- package/data/persistence/documents/containerDocumentTombstoneHoldsPersistence.js +1 -1
- package/data/persistence/documents/documentDiscoveryEvidencePersistence.js +3 -3
- package/data/persistence/documents/documentDiscoveryEvidencePersistence.js.map +1 -1
- package/data/persistence/documents/documentDiscoveryReset.js +1 -1
- package/data/persistence/documents/documentDiscoveryReset.js.map +1 -1
- package/data/persistence/documents/documentsPersistence.js +3 -3
- package/data/persistence/documents/documentsPersistence.js.map +1 -1
- package/data/persistence/documents/internal/attachmentStagingPersistence.js +1 -1
- package/data/persistence/documents/internal/containerDocumentTombstoneHolds.js +1 -1
- package/data/persistence/documents/internal/containerDocumentTombstones.js +1 -1
- package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js +2 -2
- package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js.map +1 -1
- package/data/persistence/documents/internal/discardDocument.js +3 -3
- package/data/persistence/documents/internal/discardDocument.js.map +1 -1
- package/data/persistence/documents/internal/documentDeletionPersistence.js +4 -4
- package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
- package/data/persistence/documents/internal/documentMutationPersistence.js +5 -5
- package/data/persistence/documents/internal/documentMutationPersistence.js.map +1 -1
- package/data/persistence/documents/internal/documentProjectionRows.js +1 -1
- package/data/persistence/documents/internal/documentPullContinuationPersistence.js +1 -1
- package/data/persistence/documents/internal/documentRows.js +2 -2
- package/data/persistence/documents/internal/documentRows.js.map +1 -1
- package/data/persistence/documents/internal/documentSummaryQueries.js +1 -1
- package/data/persistence/documents/internal/ensureDocumentsSchema.js +2 -2
- package/data/persistence/documents/internal/hydratedAttachmentPersistence.js +1 -1
- package/data/persistence/documents/internal/orphanSideRows.js +2 -2
- package/data/persistence/documents/internal/orphanSideRows.js.map +1 -1
- package/data/persistence/documents/internal/pendingCreateAdoption.js +1 -1
- package/data/persistence/documents/internal/rowQueryPersistence.js +2 -2
- package/data/persistence/documents/internal/syncQueuePersistence.js +3 -3
- package/data/persistence/documents/internal/syncQueuePersistence.js.map +1 -1
- package/data/persistence/documents/types.d.ts +3 -3
- package/data/persistence/documents/types.js.map +1 -1
- package/data/persistence/{documentPurgeCheckpointPersistence.d.ts → keyingCheckpoints/documentPurgeCheckpointPersistence.d.ts} +2 -2
- package/data/persistence/{documentPurgeCheckpointPersistence.js → keyingCheckpoints/documentPurgeCheckpointPersistence.js} +4 -4
- package/data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence.js.map +1 -0
- package/data/persistence/{keyingCheckpointAdvancePersistence.js → keyingCheckpoints/keyingCheckpointAdvancePersistence.js} +9 -9
- package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js.map +1 -0
- package/data/persistence/{keyingCheckpointEvidence.js → keyingCheckpoints/keyingCheckpointEvidence.js} +1 -1
- package/data/persistence/{keyingCheckpointPersistence.js → keyingCheckpoints/keyingCheckpointPersistence.js} +5 -5
- package/data/persistence/keyingCheckpoints/keyingCheckpointPersistence.js.map +1 -0
- package/data/persistence/{locallyAcknowledgedCheckpointPersistence.d.ts → keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.d.ts} +4 -4
- package/data/persistence/{locallyAcknowledgedCheckpointPersistence.js → keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js} +7 -7
- package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js.map +1 -0
- package/data/persistence/{organizationReplacementCheckpointPersistence.js → keyingCheckpoints/organizationReplacementCheckpointPersistence.js} +6 -6
- package/data/persistence/keyingCheckpoints/organizationReplacementCheckpointPersistence.js.map +1 -0
- package/data/persistence/{principalAuthorizationCheckpoints.js → keyingCheckpoints/principalAuthorizationCheckpoints.js} +1 -1
- package/data/persistence/keyingCheckpoints/principalAuthorizationCheckpoints.js.map +1 -0
- package/data/persistence/organizationFounderPersistence.js +2 -2
- package/data/persistence/organizationFounderPersistence.js.map +1 -1
- package/data/persistence/organizations/organizationAccessRevocationPersistence.js +3 -3
- package/data/persistence/organizations/organizationAccessRevocationPersistence.js.map +1 -1
- package/data/persistence/organizations/organizationDataUsagePersistence.js +2 -2
- package/data/persistence/organizations/organizationDataUsagePersistence.js.map +1 -1
- package/data/persistence/organizations/organizationGroupNamePersistence.js +2 -2
- package/data/persistence/organizations/organizationGroupNamePersistence.js.map +1 -1
- package/data/persistence/organizations/organizationPresentationDenialPersistence.js +2 -2
- package/data/persistence/organizations/organizationPresentationDenialPersistence.js.map +1 -1
- package/data/persistence/organizations/organizationProfileDocumentPointers.js +2 -2
- package/data/persistence/organizations/organizationProfileDocumentPointers.js.map +1 -1
- package/data/persistence/organizations/organizationProvisioningAttemptPersistence.js +1 -1
- package/data/persistence/organizations/organizationProvisioningAttemptPersistence.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelGrantPersistence.js +1 -1
- package/data/persistence/organizations/organizationReadModelGrantPersistence.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelMemberLoad.js +1 -1
- package/data/persistence/organizations/organizationReadModelMemberLoad.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelMembershipPersistence.js +1 -1
- package/data/persistence/organizations/organizationReadModelMembershipPersistence.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelPersistence.js +3 -3
- package/data/persistence/organizations/organizationReadModelPersistence.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelProjection.js +1 -1
- package/data/persistence/organizations/organizationReadModelProjection.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelPurge.js +3 -3
- package/data/persistence/organizations/organizationReadModelPurge.js.map +1 -1
- package/data/persistence/principalCurrentAcknowledgementPersistence.d.ts +3 -3
- package/data/persistence/principalCurrentAcknowledgementPersistence.js +10 -10
- package/data/persistence/principalCurrentAcknowledgementPersistence.js.map +1 -1
- package/data/persistence/{principalHistoryEvidencePersistence.d.ts → principalHistory/principalHistoryEvidencePersistence.d.ts} +4 -4
- package/data/persistence/{principalHistoryEvidencePersistence.js → principalHistory/principalHistoryEvidencePersistence.js} +7 -7
- package/data/persistence/principalHistory/principalHistoryEvidencePersistence.js.map +1 -0
- package/data/persistence/{principalHistoryIncompleteRetention.js → principalHistory/principalHistoryIncompleteRetention.js} +1 -1
- package/data/persistence/principalHistory/principalHistoryIncompleteRetention.js.map +1 -0
- package/data/persistence/{principalHistoryNodeRetention.js → principalHistory/principalHistoryNodeRetention.js} +4 -4
- package/data/persistence/principalHistory/principalHistoryNodeRetention.js.map +1 -0
- package/data/persistence/{principalHistoryPrefixPersistence.d.ts → principalHistory/principalHistoryPrefixPersistence.d.ts} +2 -2
- package/data/persistence/{principalHistoryPrefixPersistence.js → principalHistory/principalHistoryPrefixPersistence.js} +6 -6
- package/data/persistence/principalHistory/principalHistoryPrefixPersistence.js.map +1 -0
- package/data/persistence/{principalHistoryRootOwnership.js → principalHistory/principalHistoryRootOwnership.js} +1 -1
- package/data/persistence/principalHistory/principalHistoryRootOwnership.js.map +1 -0
- package/data/persistence/{principalHistoryStagePersistence.d.ts → principalHistory/principalHistoryStagePersistence.d.ts} +2 -2
- package/data/persistence/{principalHistoryStagePersistence.js → principalHistory/principalHistoryStagePersistence.js} +6 -6
- package/data/persistence/principalHistory/principalHistoryStagePersistence.js.map +1 -0
- package/data/persistence/{principalHistoryStageRetention.js → principalHistory/principalHistoryStageRetention.js} +2 -2
- package/data/persistence/principalHistory/principalHistoryStageRetention.js.map +1 -0
- package/data/persistence/{principalHistoryUnpublishedRetention.js → principalHistory/principalHistoryUnpublishedRetention.js} +3 -3
- package/data/persistence/principalHistory/principalHistoryUnpublishedRetention.js.map +1 -0
- package/data/persistence/{principalGrantRetirementPersistence.d.ts → principalKeys/principalGrantRetirementPersistence.d.ts} +2 -2
- package/data/persistence/{principalGrantRetirementPersistence.js → principalKeys/principalGrantRetirementPersistence.js} +2 -2
- package/data/persistence/principalKeys/principalGrantRetirementPersistence.js.map +1 -0
- package/data/persistence/{principalKeyEnvelopeArchivePersistence.js → principalKeys/principalKeyEnvelopeArchivePersistence.js} +3 -3
- package/data/persistence/principalKeys/principalKeyEnvelopeArchivePersistence.js.map +1 -0
- package/data/persistence/{principalKeyEnvelopeCandidates.js → principalKeys/principalKeyEnvelopeCandidates.js} +9 -9
- package/data/persistence/principalKeys/principalKeyEnvelopeCandidates.js.map +1 -0
- package/data/persistence/principalMutationJournalPersistence.d.ts +1 -1
- package/data/persistence/principalMutationJournalPersistence.js +1 -1
- package/data/persistence/principalMutationJournalPersistence.js.map +1 -1
- package/data/persistence/{principalPolicyBundleIntegrity.js → principalPolicy/principalPolicyBundleIntegrity.js} +3 -3
- package/data/persistence/principalPolicy/principalPolicyBundleIntegrity.js.map +1 -0
- package/data/persistence/{principalPolicyCheckpointSelection.js → principalPolicy/principalPolicyCheckpointSelection.js} +2 -2
- package/data/persistence/principalPolicy/principalPolicyCheckpointSelection.js.map +1 -0
- package/data/persistence/{principalPolicyOrganizationPersistence.js → principalPolicy/principalPolicyOrganizationPersistence.js} +2 -2
- package/data/persistence/principalPolicy/principalPolicyOrganizationPersistence.js.map +1 -0
- package/data/persistence/{principalPolicyPersistence.js → principalPolicy/principalPolicyPersistence.js} +5 -5
- package/data/persistence/principalPolicy/principalPolicyPersistence.js.map +1 -0
- package/data/persistence/{principalPolicyReferenceCheckpoint.js → principalPolicy/principalPolicyReferenceCheckpoint.js} +3 -3
- package/data/persistence/principalPolicy/principalPolicyReferenceCheckpoint.js.map +1 -0
- package/data/persistence/{principalPolicyReferenceIndexPersistence.js → principalPolicy/principalPolicyReferenceIndexPersistence.js} +4 -4
- package/data/persistence/principalPolicy/principalPolicyReferenceIndexPersistence.js.map +1 -0
- package/data/persistence/{principalPolicyReferencePersistence.js → principalPolicy/principalPolicyReferencePersistence.js} +5 -5
- package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js.map +1 -0
- package/data/persistence/{verifiedPrincipalPolicyBundle.js → principalPolicy/verifiedPrincipalPolicyBundle.js} +2 -2
- package/data/persistence/principalPolicy/verifiedPrincipalPolicyBundle.js.map +1 -0
- package/data/persistence/{verifiedPrincipalPolicyCurrent.js → principalPolicy/verifiedPrincipalPolicyCurrent.js} +2 -2
- package/data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent.js.map +1 -0
- package/data/persistence/{verifiedPrincipalPolicyRetentionPersistence.js → principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js} +1 -1
- package/data/persistence/principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js.map +1 -0
- package/data/persistence/securityIncidentPersistence.js +1 -1
- package/data/persistence/securityIncidentPersistence.js.map +1 -1
- package/data/persistence/trustedUserIdentityPinPersistence.js +1 -1
- package/data/persistence/verifiedManifestBundlePersistence.d.ts +1 -1
- package/data/persistence/verifiedManifestBundlePersistence.js +4 -4
- package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
- package/data/principals/organizationGroupRoles.js +2 -2
- package/data/principals/organizationGroupRoles.js.map +1 -1
- package/data/principals/principalHistoryPrefixProtection.js.map +1 -1
- package/data/principals/principalHistoryStageProtection.js.map +1 -1
- package/data/principals/principalPolicyCrypto.js +1 -1
- package/data/principals/principalPolicyCrypto.js.map +1 -1
- package/data/sqlite/{documentHistoryPersistence.d.ts → documentPersistence/documentHistoryPersistence.d.ts} +1 -1
- package/data/sqlite/{documentHistoryPersistence.js → documentPersistence/documentHistoryPersistence.js} +5 -5
- package/data/sqlite/documentPersistence/documentHistoryPersistence.js.map +1 -0
- package/data/sqlite/{documentOrphanBlobReclaims.js → documentPersistence/documentOrphanBlobReclaims.js} +1 -1
- package/data/sqlite/documentPersistence/documentOrphanBlobReclaims.js.map +1 -0
- package/data/sqlite/{documentPendingUpdatePersistence.d.ts → documentPersistence/documentPendingUpdatePersistence.d.ts} +2 -2
- package/data/sqlite/{documentPendingUpdatePersistence.js → documentPersistence/documentPendingUpdatePersistence.js} +2 -2
- package/data/sqlite/documentPersistence/documentPendingUpdatePersistence.js.map +1 -0
- package/data/sqlite/{documentPersistenceTypes.d.ts → documentPersistence/documentPersistenceTypes.d.ts} +2 -2
- package/data/sqlite/documentPersistence/documentPersistenceTypes.js.map +1 -0
- package/data/sqlite/{documentRecordPersistence.d.ts → documentPersistence/documentRecordPersistence.d.ts} +1 -1
- package/data/sqlite/{documentRecordPersistence.js → documentPersistence/documentRecordPersistence.js} +4 -4
- package/data/sqlite/documentPersistence/documentRecordPersistence.js.map +1 -0
- package/data/sqlite/{documentSyncFailurePersistence.d.ts → documentPersistence/documentSyncFailurePersistence.d.ts} +2 -2
- package/data/sqlite/{documentSyncFailurePersistence.js → documentPersistence/documentSyncFailurePersistence.js} +3 -3
- package/data/sqlite/documentPersistence/documentSyncFailurePersistence.js.map +1 -0
- package/data/sqlite/{documentPersistence.d.ts → documentPersistence/index.d.ts} +2 -2
- package/data/sqlite/{documentPersistence.js → documentPersistence/index.js} +5 -5
- package/data/sqlite/documentPersistence/index.js.map +1 -0
- package/data/sqlite/{containerSchema.d.ts → schema/containerSchema.d.ts} +1 -1
- package/data/sqlite/{containerSchema.js → schema/containerSchema.js} +1 -1
- package/data/sqlite/schema/containerSchema.js.map +1 -0
- package/data/sqlite/{schema.d.ts → schema/index.d.ts} +1 -1
- package/data/sqlite/{schema.js → schema/index.js} +3 -3
- package/data/sqlite/schema/index.js.map +1 -0
- package/data/sqlite/{organizationDataUsageSchema.js → schema/organizationDataUsageSchema.js} +1 -1
- package/data/sqlite/schema/organizationDataUsageSchema.js.map +1 -0
- package/data/sqlite/{organizationProvisioningAttemptSchema.js → schema/organizationProvisioningAttemptSchema.js} +1 -1
- package/data/sqlite/schema/organizationProvisioningAttemptSchema.js.map +1 -0
- package/data/sqlite/{organizationReadModelTableRegistry.d.ts → schema/organizationReadModelTableRegistry.d.ts} +1 -1
- package/data/sqlite/{organizationReadModelTableRegistry.js → schema/organizationReadModelTableRegistry.js} +1 -1
- package/data/sqlite/schema/organizationReadModelTableRegistry.js.map +1 -0
- package/data/sqlite/{principalHistoryEvidenceSchema.d.ts → schema/principalHistoryEvidenceSchema.d.ts} +1 -1
- package/data/sqlite/{principalHistoryEvidenceSchema.js → schema/principalHistoryEvidenceSchema.js} +2 -2
- package/data/sqlite/schema/principalHistoryEvidenceSchema.js.map +1 -0
- package/data/sqlite/{principalHistoryNodeRetentionSchema.js → schema/principalHistoryNodeRetentionSchema.js} +1 -1
- package/data/sqlite/schema/principalHistoryNodeRetentionSchema.js.map +1 -0
- package/data/sqlite/{principalHistoryRetentionSchema.js → schema/principalHistoryRetentionSchema.js} +1 -1
- package/data/sqlite/{principalHistoryRetentionSchema.js.map → schema/principalHistoryRetentionSchema.js.map} +1 -1
- package/data/sqlite/{principalHistoryStageSchema.d.ts → schema/principalHistoryStageSchema.d.ts} +1 -1
- package/data/sqlite/{principalHistoryStageSchema.js → schema/principalHistoryStageSchema.js} +2 -2
- package/data/sqlite/schema/principalHistoryStageSchema.js.map +1 -0
- package/data/sqlite/{principalMutationJournalSchema.d.ts → schema/principalMutationJournalSchema.d.ts} +1 -1
- package/data/sqlite/{principalMutationJournalSchema.js → schema/principalMutationJournalSchema.js} +1 -1
- package/data/sqlite/{principalMutationJournalSchema.js.map → schema/principalMutationJournalSchema.js.map} +1 -1
- package/data/sqlite/{principalPolicySchema.js → schema/principalPolicySchema.js} +1 -1
- package/data/sqlite/schema/principalPolicySchema.js.map +1 -0
- package/data/sqlite/{securityIncidentSchema.d.ts → schema/securityIncidentSchema.d.ts} +1 -1
- package/data/sqlite/{securityIncidentSchema.js → schema/securityIncidentSchema.js} +1 -1
- package/data/sqlite/schema/securityIncidentSchema.js.map +1 -0
- package/data/sqlite/{verifiedManifestBundleSchema.d.ts → schema/verifiedManifestBundleSchema.d.ts} +1 -1
- package/data/sqlite/{verifiedManifestBundleSchema.js → schema/verifiedManifestBundleSchema.js} +1 -1
- package/data/sqlite/schema/verifiedManifestBundleSchema.js.map +1 -0
- package/data/sqlite/sqlitePersistenceRuntime.d.ts +1 -1
- package/data/sqlite/sqlitePersistenceRuntime.js +1 -1
- package/index.d.ts +1 -1
- package/index.js.map +1 -1
- package/package.json +1 -1
- package/sqlite/index.d.ts +1 -1
- package/sqlite/index.js +1 -1
- package/stores/container-contents/containerContentsStore.js +3 -2
- package/stores/container-contents/containerContentsStore.js.map +1 -1
- package/stores/container-contents/index.d.ts +1 -1
- package/stores/container-contents/index.js.map +1 -1
- package/stores/container-contents/operations/purgeMoveSettlementOperation.js +71 -0
- package/stores/container-contents/operations/purgeMoveSettlementOperation.js.map +1 -0
- package/stores/documents/documentStore/history/historyRebuild.js +1 -1
- package/stores/documents/documentStore/history/historyRebuild.js.map +1 -1
- package/stores/documents/documentStore/state.js.map +1 -1
- package/stores/documents/documentStore/sync/syncFinalize.js +1 -1
- package/stores/documents/documentStore/sync/syncFinalize.js.map +1 -1
- package/stores/documents/documentStore/sync/syncUpdateImport.js +1 -1
- package/stores/documents/documentStore/sync/syncUpdateImport.js.map +1 -1
- package/workflows/blobs/detach.js +1 -1
- package/workflows/blobs/hydration/decrypt.js +1 -1
- package/workflows/blobs/upload/index.js +1 -1
- package/workflows/blobs/verification/retainedAttachmentVerification.js +1 -1
- package/workflows/blobs/verification/writerProjection.js +1 -1
- package/workflows/container-contents/container-state/create/createWithMetadata.js +2 -2
- package/workflows/container-contents/container-state/create/createWithMetadata.js.map +1 -1
- package/workflows/container-contents/container-state/moveIntentSync.js +43 -5
- package/workflows/container-contents/container-state/moveIntentSync.js.map +1 -1
- package/workflows/container-contents/container-state/purge/purgeMoveSettlement.js +119 -0
- package/workflows/container-contents/container-state/purge/purgeMoveSettlement.js.map +1 -0
- package/workflows/container-contents/container-state/purge/purgeProgress.d.ts +8 -0
- package/workflows/container-contents/container-state/purge/purgeProgress.js.map +1 -1
- package/workflows/container-contents/container-state/remote.js +1 -0
- package/workflows/container-contents/container-state/remote.js.map +1 -1
- package/workflows/container-contents/container-state/share/index.js +1 -1
- package/workflows/container-contents/documentLinks/index.js +1 -1
- package/workflows/container-contents/documentMove/documentMoveVanishedRefresh.js +1 -1
- package/workflows/container-contents/documentPriming/documentHydrationProbe.js +1 -1
- package/workflows/container-contents/documentPriming/index.js +1 -1
- package/workflows/container-contents/documentQueries/index.js +1 -1
- package/workflows/container-contents/documentQueries/sql.js +1 -1
- package/workflows/container-contents/info/blobInfo.js +1 -1
- package/workflows/container-contents/info/containerInfo.js +1 -1
- package/workflows/container-contents/info/documentInfo.js +1 -1
- package/workflows/container-contents/metadata/index.js +1 -1
- package/workflows/container-contents/metadata/index.js.map +1 -1
- package/workflows/container-contents/metadata/metadataEvents.d.ts +1 -1
- package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js +2 -2
- package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js.map +1 -1
- package/workflows/container-contents/metadata/metadataMutationPreparation.js +1 -1
- package/workflows/container-contents/metadata/metadataMutationPreparation.js.map +1 -1
- package/workflows/container-contents/metadata/metadataPullContinuationInvalidation.js +1 -1
- package/workflows/container-contents/metadata/metadataPullContinuationInvalidation.js.map +1 -1
- package/workflows/container-contents/metadata/metadataRemoteSync.d.ts +1 -1
- package/workflows/container-contents/metadata/metadataSyncErrors.js +1 -1
- package/workflows/container-contents/metadata/metadataSyncErrors.js.map +1 -1
- package/workflows/container-contents/metadata/metadataSyncSettlement.d.ts +1 -1
- package/workflows/container-contents/metadata/metadataSyncSettlement.js.map +1 -1
- package/workflows/container-contents/metadata/metadataTypes.d.ts +1 -1
- package/workflows/container-contents/metadata/metadataTypes.js.map +1 -1
- package/workflows/container-contents/pendingWrites/index.js +2 -2
- package/workflows/container-contents/pendingWrites/sources.js +1 -1
- package/workflows/container-contents/remoteHydration/destination/replacementBinding.js +1 -1
- package/workflows/container-contents/remoteHydration/destination/replacementBinding.js.map +1 -1
- package/workflows/container-contents/remoteHydration/reattachMetadata.js.map +1 -1
- package/workflows/container-contents/syncLane.d.ts +2 -0
- package/workflows/container-contents/syncLane.js +7 -0
- package/workflows/container-contents/syncLane.js.map +1 -1
- package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +2 -2
- package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
- package/workflows/containers/child/create/index.js +2 -2
- package/workflows/containers/child/create/index.js.map +1 -1
- package/workflows/containers/child/move/index.d.ts +1 -0
- package/workflows/containers/child/move/index.js +2 -1
- package/workflows/containers/child/move/index.js.map +1 -1
- package/workflows/containers/child/move/moveRotation.js +1 -1
- package/workflows/containers/child/move/moveRotation.js.map +1 -1
- package/workflows/containers/child/move/moveWraps.js +1 -1
- package/workflows/containers/child/move/moveWraps.js.map +1 -1
- package/workflows/containers/child/mutationSubmit.js +3 -1
- package/workflows/containers/child/mutationSubmit.js.map +1 -1
- package/workflows/containers/child/recite.js +2 -2
- package/workflows/containers/child/recite.js.map +1 -1
- package/workflows/containers/child/rotation/rotationContext.js +3 -3
- package/workflows/containers/child/rotation/rotationContext.js.map +1 -1
- package/workflows/containers/child/share/currentSharePrincipalPolicy.js +1 -1
- package/workflows/containers/child/share/currentSharePrincipalPolicy.js.map +1 -1
- package/workflows/containers/child/share/index.js +1 -1
- package/workflows/containers/child/share/index.js.map +1 -1
- package/workflows/containers/child/share/shareAncestorRepair.js +2 -2
- package/workflows/containers/child/share/shareAncestorRepair.js.map +1 -1
- package/workflows/containers/child/share/shareMaterialization.js +1 -1
- package/workflows/containers/child/share/sharePrincipalPolicy.js +5 -5
- package/workflows/containers/child/share/sharePrincipalPolicy.js.map +1 -1
- package/workflows/containers/index.d.ts +3 -3
- package/workflows/containers/index.js +2 -2
- package/workflows/containers/index.js.map +1 -1
- package/workflows/containers/writeRefusal.js +1 -1
- package/workflows/containers/writeRefusal.js.map +1 -1
- package/workflows/documents/create/createAdoption.js +1 -1
- package/workflows/documents/create/createResponse.js +2 -2
- package/workflows/documents/create/createResponse.js.map +1 -1
- package/workflows/documents/create/index.js +1 -1
- package/workflows/documents/documentMutationCommit.d.ts +1 -1
- package/workflows/documents/documentMutationPreparation.d.ts +1 -1
- package/workflows/documents/documentMutationPreparation.js +1 -1
- package/workflows/documents/documentMutationPreparation.js.map +1 -1
- package/workflows/documents/index.d.ts +5 -5
- package/workflows/documents/index.js +5 -5
- package/workflows/documents/index.js.map +1 -1
- package/workflows/documents/linkSet/index.js +2 -2
- package/workflows/documents/linkSet/index.js.map +1 -1
- package/workflows/documents/linkSet/linkSetAuthority.js +1 -1
- package/workflows/documents/linkSet/linkSetBlobRewraps.js +1 -1
- package/workflows/documents/linkSet/linkSetProjectionSeed.js +1 -1
- package/workflows/documents/linkSet/linkSetRemote.js +1 -1
- package/workflows/documents/linkSet/linkSetRemote.js.map +1 -1
- package/workflows/documents/purge/index.js +1 -1
- package/workflows/documents/sync/index.js +2 -2
- package/workflows/documents/sync/index.js.map +1 -1
- package/workflows/documents/sync/initialSync.js +1 -1
- package/workflows/documents/sync/readOnlyProjectionFailure.js +1 -1
- package/workflows/documents/sync/readOnlyProjectionFailure.js.map +1 -1
- package/workflows/documents/sync/readOnlySync.d.ts +3 -3
- package/workflows/documents/sync/readOnlySync.js +1 -1
- package/workflows/documents/sync/readOnlySync.js.map +1 -1
- package/workflows/documents/sync/reportDocumentSyncQuarantine.js.map +1 -1
- package/workflows/documents/sync/syncAttemptPlanning.js +2 -2
- package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -1
- package/workflows/documents/sync/syncAttemptState.d.ts +2 -2
- package/workflows/documents/sync/syncAttemptState.js.map +1 -1
- package/workflows/documents/sync/syncResponseResult.js +2 -2
- package/workflows/documents/sync/syncResponseResult.js.map +1 -1
- package/workflows/documents/syncFailures/index.js +1 -1
- package/workflows/documents/syncFailures/index.js.map +1 -1
- package/workflows/documents/syncFailures/syncAbandon.js.map +1 -1
- package/workflows/documents/syncFailures/syncFailureClassification.js +1 -1
- package/workflows/documents/syncFailures/syncFailureClassification.js.map +1 -1
- package/workflows/documents/syncPlan/syncContentKeys.d.ts +1 -1
- package/workflows/documents/syncPlan/syncContentKeys.js +3 -3
- package/workflows/documents/syncPlan/syncContentKeys.js.map +1 -1
- package/workflows/documents/syncPlan/syncPlanMaterial.js +2 -2
- package/workflows/documents/syncPlan/syncPlanMaterial.js.map +1 -1
- package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js +2 -2
- package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js.map +1 -1
- package/workflows/documents/syncRekeys/syncContainerRekeyPreparation.js +1 -1
- package/workflows/documents/syncRekeys/syncRecoveryRekey.d.ts +1 -1
- package/workflows/documents/syncRekeys/syncRecoveryRekey.js +1 -1
- package/workflows/organizations/currentOrganizationAuthority.js +2 -2
- package/workflows/organizations/currentOrganizationAuthority.js.map +1 -1
- package/workflows/organizations/groupMetadata/groupMetadataAccess.js +1 -1
- package/workflows/organizations/groupMetadata/groupMetadataAccess.js.map +1 -1
- package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js +1 -1
- package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js.map +1 -1
- package/workflows/organizations/groupNames/currentOrganizationGroupNames.js +1 -1
- package/workflows/organizations/groupNames/currentOrganizationGroupNames.js.map +1 -1
- package/workflows/organizations/groupNames/groupNameUniqueness.js +3 -3
- package/workflows/organizations/groupNames/groupNameUniqueness.js.map +1 -1
- package/workflows/organizations/groupNames/organizationGroupNamePolicies.js +2 -2
- package/workflows/organizations/groupNames/organizationGroupNamePolicies.js.map +1 -1
- package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js +1 -1
- package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js.map +1 -1
- package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js +2 -2
- package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js.map +1 -1
- package/workflows/organizations/groupPolicy/groupPolicyMutationEvidence.js +1 -1
- package/workflows/organizations/groupPolicy/groupPolicyMutationEvidence.js.map +1 -1
- package/workflows/organizations/groupPolicy/groupPolicyVerification.js +1 -1
- package/workflows/organizations/groupPolicy/groupPolicyVerification.js.map +1 -1
- package/workflows/organizations/groups/createCurrentOrganizationGroup.js +1 -1
- package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
- package/workflows/organizations/groups/deleteOrganizationGroup.js +1 -1
- package/workflows/organizations/groups/deleteOrganizationGroup.js.map +1 -1
- package/workflows/organizations/groups/organizationGroupDirectory.js +1 -1
- package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
- package/workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation.js +1 -1
- package/workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation.js.map +1 -1
- package/workflows/organizations/provisioning/organizationReplacementVerification.js +1 -1
- package/workflows/organizations/provisioning/organizationReplacementVerification.js.map +1 -1
- package/workflows/organizations/readModel/listLocalOrganizations.js +1 -1
- package/workflows/organizations/readModel/localReadModelDetails.js +1 -1
- package/workflows/organizations/readModel/localReadModelDetails.js.map +1 -1
- package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js +1 -1
- package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js.map +1 -1
- package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.d.ts +1 -1
- package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js +1 -1
- package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js.map +1 -1
- package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js +1 -1
- package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js.map +1 -1
- package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js +2 -2
- package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js.map +1 -1
- package/workflows/principals/externalAdminPolicy.js +2 -2
- package/workflows/principals/externalAdminPolicy.js.map +1 -1
- package/workflows/principals/historyRecovery/loadRecoveredPrincipalHistoryPage.js +2 -2
- package/workflows/principals/historyRecovery/loadRecoveredPrincipalHistoryPage.js.map +1 -1
- package/workflows/principals/historyRecovery/principalHistoryRecoveryPrefix.js +1 -1
- package/workflows/principals/historyRecovery/principalHistoryRecoveryPrefix.js.map +1 -1
- package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js +1 -1
- package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js.map +1 -1
- package/workflows/principals/historyRecovery/principalHistoryRecoveryStage.js +1 -1
- package/workflows/principals/historyRecovery/principalHistoryRecoveryStage.js.map +1 -1
- package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js +3 -3
- package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js.map +1 -1
- package/workflows/principals/policyCache/index.js +3 -3
- package/workflows/principals/policyCache/index.js.map +1 -1
- package/workflows/principals/policyCache/principalPolicyCacheAdvance.js +1 -1
- package/workflows/principals/policyCache/principalPolicyCacheAdvance.js.map +1 -1
- package/workflows/principals/policyCache/principalPolicyOrganizationScope.js +3 -3
- package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -1
- package/workflows/principals/publicHistory/publicPrincipalHistoryAuthority.js.map +1 -1
- package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js +2 -2
- package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js.map +1 -1
- package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js +3 -3
- package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js.map +1 -1
- package/workflows/principals/publicHistory/publicPrincipalHistoryTypes.d.ts +2 -2
- package/workflows/principals/publicHistory/publicPrincipalHistoryTypes.js.map +1 -1
- package/workflows/principals/publicHistory/publicProjectionPrincipal.js +1 -1
- package/workflows/principals/publicHistory/publicProjectionPrincipal.js.map +1 -1
- package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js +1 -1
- package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js.map +1 -1
- package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js +1 -1
- package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js.map +1 -1
- package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js +1 -1
- package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js.map +1 -1
- package/workflows/principals/recoveryOperation/principalRecoveryMemoValidity.js +1 -1
- package/workflows/principals/recoveryOperation/principalRecoveryMemoValidity.js.map +1 -1
- package/workflows/registration/persistRegistrationBootstrap.d.ts +2 -2
- package/workflows/registration/persistRegistrationBootstrap.js +2 -2
- package/workflows/registration/persistRegistrationBootstrap.js.map +1 -1
- package/workflows/registration/provisioningAcknowledgement.js +1 -1
- package/workflows/registration/provisioningAcknowledgement.js.map +1 -1
- package/workflows/registration/registrationPrincipalPolicyPersistence.js +1 -1
- package/workflows/registration/registrationPrincipalPolicyPersistence.js.map +1 -1
- package/workflows/sync/remoteReset.js +7 -7
- package/workflows/sync/remoteReset.js.map +1 -1
- package/workflows/sync/remoteResetAttachments.js +1 -1
- package/workflows/sync/remoteResetCursorScope.js +1 -1
- package/workflows/sync/remoteResetPlans.js +1 -1
- package/workflows/sync/remoteResetPrincipalScope.js +5 -5
- package/workflows/sync/remoteResetPrincipalScope.js.map +1 -1
- package/workflows/sync/remoteResetScope.js +1 -1
- package/data/documents/shared/containerKekPath.js.map +0 -1
- package/data/documents/shared/containerKekPathHistory.js.map +0 -1
- package/data/documents/shared/containerKekPathVerification.js.map +0 -1
- package/data/documents/shared/containerKekWrapping.js.map +0 -1
- package/data/documents/shared/documentSyncUpdateDecryption.js.map +0 -1
- package/data/documents/shared/documentSyncUpdateIsolation.js.map +0 -1
- package/data/documents/shared/keyringRebuild.js.map +0 -1
- package/data/documents/shared/mutationAcknowledgement.js.map +0 -1
- package/data/documents/shared/projection.js.map +0 -1
- package/data/documents/shared/projectionContentKeys.js.map +0 -1
- package/data/documents/shared/projectionTargets.js.map +0 -1
- package/data/documents/shared/syncPagination.js.map +0 -1
- package/data/documents/shared/syncResponseAuthorization.js.map +0 -1
- package/data/documents/shared/syncResponses.js.map +0 -1
- package/data/persistence/documentPurgeCheckpointPersistence.js.map +0 -1
- package/data/persistence/keyingCheckpointAdvancePersistence.js.map +0 -1
- package/data/persistence/keyingCheckpointPersistence.js.map +0 -1
- package/data/persistence/locallyAcknowledgedCheckpointPersistence.js.map +0 -1
- package/data/persistence/organizationReplacementCheckpointPersistence.js.map +0 -1
- package/data/persistence/principalAuthorizationCheckpoints.js.map +0 -1
- package/data/persistence/principalGrantRetirementPersistence.js.map +0 -1
- package/data/persistence/principalHistoryEvidencePersistence.js.map +0 -1
- package/data/persistence/principalHistoryIncompleteRetention.js.map +0 -1
- package/data/persistence/principalHistoryNodeRetention.js.map +0 -1
- package/data/persistence/principalHistoryPrefixPersistence.js.map +0 -1
- package/data/persistence/principalHistoryRootOwnership.js.map +0 -1
- package/data/persistence/principalHistoryStagePersistence.js.map +0 -1
- package/data/persistence/principalHistoryStageRetention.js.map +0 -1
- package/data/persistence/principalHistoryUnpublishedRetention.js.map +0 -1
- package/data/persistence/principalKeyEnvelopeArchivePersistence.js.map +0 -1
- package/data/persistence/principalKeyEnvelopeCandidates.js.map +0 -1
- package/data/persistence/principalPolicyBundleIntegrity.js.map +0 -1
- package/data/persistence/principalPolicyCheckpointSelection.js.map +0 -1
- package/data/persistence/principalPolicyOrganizationPersistence.js.map +0 -1
- package/data/persistence/principalPolicyPersistence.js.map +0 -1
- package/data/persistence/principalPolicyReferenceCheckpoint.js.map +0 -1
- package/data/persistence/principalPolicyReferenceIndexPersistence.js.map +0 -1
- package/data/persistence/principalPolicyReferencePersistence.js.map +0 -1
- package/data/persistence/verifiedPrincipalPolicyBundle.js.map +0 -1
- package/data/persistence/verifiedPrincipalPolicyCurrent.js.map +0 -1
- package/data/persistence/verifiedPrincipalPolicyRetentionPersistence.js.map +0 -1
- package/data/sqlite/containerSchema.js.map +0 -1
- package/data/sqlite/documentHistoryPersistence.js.map +0 -1
- package/data/sqlite/documentOrphanBlobReclaims.js.map +0 -1
- package/data/sqlite/documentPendingUpdatePersistence.js.map +0 -1
- package/data/sqlite/documentPersistence.js.map +0 -1
- package/data/sqlite/documentPersistenceTypes.js.map +0 -1
- package/data/sqlite/documentRecordPersistence.js.map +0 -1
- package/data/sqlite/documentSyncFailurePersistence.js.map +0 -1
- package/data/sqlite/organizationDataUsageSchema.js.map +0 -1
- package/data/sqlite/organizationProvisioningAttemptSchema.js.map +0 -1
- package/data/sqlite/organizationReadModelTableRegistry.js.map +0 -1
- package/data/sqlite/principalHistoryEvidenceSchema.js.map +0 -1
- package/data/sqlite/principalHistoryNodeRetentionSchema.js.map +0 -1
- package/data/sqlite/principalHistoryStageSchema.js.map +0 -1
- package/data/sqlite/principalPolicySchema.js.map +0 -1
- package/data/sqlite/schema.js.map +0 -1
- package/data/sqlite/securityIncidentSchema.js.map +0 -1
- package/data/sqlite/verifiedManifestBundleSchema.js.map +0 -1
- /package/data/documents/shared/{containerKekCurrency.js → containerKek/containerKekCurrency.js} +0 -0
- /package/data/documents/shared/{containerKekCurrency.js.map → containerKek/containerKekCurrency.js.map} +0 -0
- /package/data/documents/shared/{containerKekEntryVerification.js.map → containerKek/containerKekEntryVerification.js.map} +0 -0
- /package/data/documents/shared/{containerKekLogFetch.js.map → containerKek/containerKekLogFetch.js.map} +0 -0
- /package/data/documents/shared/{containerKekPath.d.ts → containerKek/containerKekPath.d.ts} +0 -0
- /package/data/documents/shared/{keyringLogWalk.js.map → containerKek/keyringLogWalk.js.map} +0 -0
- /package/data/documents/shared/{pullContinuation.d.ts → sync/pullContinuation.d.ts} +0 -0
- /package/data/documents/shared/{pullContinuation.js.map → sync/pullContinuation.js.map} +0 -0
- /package/data/documents/shared/{syncSubmitFailure.js → sync/syncSubmitFailure.js} +0 -0
- /package/data/documents/shared/{syncSubmitFailure.js.map → sync/syncSubmitFailure.js.map} +0 -0
- /package/data/persistence/{keyingCheckpointEvidence.js.map → keyingCheckpoints/keyingCheckpointEvidence.js.map} +0 -0
- /package/data/persistence/{storedPrincipalPolicyBundle.js → principalPolicy/storedPrincipalPolicyBundle.js} +0 -0
- /package/data/persistence/{storedPrincipalPolicyBundle.js.map → principalPolicy/storedPrincipalPolicyBundle.js.map} +0 -0
- /package/data/sqlite/{documentPersistenceTypes.js → documentPersistence/documentPersistenceTypes.js} +0 -0
- /package/data/sqlite/{containerDocumentTombstoneHoldSchema.d.ts → schema/containerDocumentTombstoneHoldSchema.d.ts} +0 -0
- /package/data/sqlite/{containerDocumentTombstoneHoldSchema.js → schema/containerDocumentTombstoneHoldSchema.js} +0 -0
- /package/data/sqlite/{containerDocumentTombstoneHoldSchema.js.map → schema/containerDocumentTombstoneHoldSchema.js.map} +0 -0
- /package/data/sqlite/{documentAttachmentSchema.d.ts → schema/documentAttachmentSchema.d.ts} +0 -0
- /package/data/sqlite/{documentAttachmentSchema.js → schema/documentAttachmentSchema.js} +0 -0
- /package/data/sqlite/{documentAttachmentSchema.js.map → schema/documentAttachmentSchema.js.map} +0 -0
- /package/data/sqlite/{documentDiscoveryEvidenceSchema.js → schema/documentDiscoveryEvidenceSchema.js} +0 -0
- /package/data/sqlite/{documentDiscoveryEvidenceSchema.js.map → schema/documentDiscoveryEvidenceSchema.js.map} +0 -0
- /package/data/sqlite/{documentPlacementIntentSchema.js → schema/documentPlacementIntentSchema.js} +0 -0
- /package/data/sqlite/{documentPlacementIntentSchema.js.map → schema/documentPlacementIntentSchema.js.map} +0 -0
- /package/data/sqlite/{localIntentSchema.d.ts → schema/localIntentSchema.d.ts} +0 -0
- /package/data/sqlite/{localIntentSchema.js → schema/localIntentSchema.js} +0 -0
- /package/data/sqlite/{localIntentSchema.js.map → schema/localIntentSchema.js.map} +0 -0
- /package/data/sqlite/{organizationFounderSchema.js → schema/organizationFounderSchema.js} +0 -0
- /package/data/sqlite/{organizationFounderSchema.js.map → schema/organizationFounderSchema.js.map} +0 -0
- /package/data/sqlite/{organizationReadModelSchema.js → schema/organizationReadModelSchema.js} +0 -0
- /package/data/sqlite/{organizationReadModelSchema.js.map → schema/organizationReadModelSchema.js.map} +0 -0
- /package/data/sqlite/{principalGrantRetirementSchema.js → schema/principalGrantRetirementSchema.js} +0 -0
- /package/data/sqlite/{principalGrantRetirementSchema.js.map → schema/principalGrantRetirementSchema.js.map} +0 -0
- /package/data/sqlite/{principalPolicySchema.d.ts → schema/principalPolicySchema.d.ts} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"projectionContentKeys.js","sourceRoot":"","sources":["projectionContentKeys.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,mCAAmC,EACnC,+BAA+B,EAC/B,wBAAwB,EACxB,gBAAgB,EAEhB,cAAc,GACf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAQpD,OAAO,EAAE,4BAA4B,EAAE,MAAM,0EAA0E,CAAC;AACxH,OAAO,EAAE,uCAAuC,EAAE,MAAM,0CAA0C,CAAC;AAEnG,OAAO,EACL,6BAA6B,EAC7B,6BAA6B,GAC9B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,sBAAsB,EACtB,yCAAyC,GAC1C,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,mCAAmC,EAAE,MAAM,2BAA2B,CAAC;AAChF,OAAO,EACL,2BAA2B,EAC3B,2BAA2B,EAC3B,0CAA0C,EAC1C,2BAA2B,GAC5B,MAAM,qBAAqB,CAAC;AAC7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E,aAAa,CAAC,OAAO,CAAC,UAAU,CAAC;YAC7C,gBAAgB,EAAE;gBAChB,KAAK,EAAE,+BAA+B;gBACtC,EAAE,EAAE,aAAa,CAAC,OAAO,CAAC,EAAE,CAAC;aAC9B;SACF,CAAC,CAAC;IACL,CAAC;IAED,OAAO;QACL,eAAe;QACf,UAAU,EAAE,gBAAgB,CAAC,UAAU;QACvC,mBAAmB,EAAE,kBAAkB,CAAC,mBAAmB;QAC3D,UAAU,EAAE,kBAAkB,CAAC,qBAAqB;QACpD,OAAO,EAAE,SAAS;KACnB,CAAC;AACJ,CAAC","sourcesContent":["import {\n ContentKeyEnvelopeError,\n type ContentKeyEnvelopeKind,\n computeDocumentContentKeyTargetHash,\n DOCUMENT_CONTENT_KEY_WRAP_SUITE,\n decodeContentKeyEnvelope,\n unwrapContentKey,\n type VerifiedContainerAccessManifest,\n wrapContentKey,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type { DocumentContentKeyTargetEnvelope } from \"@tearleads/validators/request\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentContentKeyBundleResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyCache } from \"../../keyingProjectionVerification\";\nimport { documentContainerProjections } from \"../../keyingProjectionVerification/document/documentContainerProjections\";\nimport { throwKeyingVerificationErrorWithContext } from \"../../keyingProjectionVerification/error\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport {\n assertContainerKekPathCurrent,\n assertDocumentKekPathsCurrent,\n} from \"./containerKekCurrency\";\nimport {\n unwrapContainerKekPath,\n unwrapContainerKekPathWithHistoryFailures,\n} from \"./containerKekPath\";\nimport { ContainerKekHistoryUnavailableError } from \"./containerKekPathHistory\";\nimport {\n deriveDocumentCreateTargets,\n describeProjectionTargetKek,\n readLinkedContainerIdsFromDocumentManifest,\n verifiedDocumentWrapTargets,\n} from \"./projectionTargets\";\nimport {\n assertEqualBytes,\n describeDocumentTargetKek,\n normalizeDocumentKekTargetResponse,\n sortDocumentTargets,\n targetEnvelopeReference,\n} from \"./readers\";\nimport type { ProjectionVerificationOptions } from \"./types\";\nimport { projectionVerificationOptions } from \"./types\";\n\nfunction getOnlyDocumentCreateTarget(\n projection: ContainerWriterProjectionResponse,\n) {\n const target = deriveDocumentCreateTargets(projection)[0];\n if (!target) {\n throw new Error(\"Document create target is unavailable\");\n }\n return target;\n}\n\nexport async function wrapDocumentContentKeyForCreate(\n input: {\n contentKey: Uint8Array;\n contentKeyEpoch: number;\n documentId: string;\n execSql?: ExecSql | undefined;\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n persistVerificationCheckpoints?: boolean | undefined;\n projection: ContainerWriterProjectionResponse;\n secretKey: Uint8Array;\n } & ProjectionVerificationOptions,\n): Promise<DocumentContentKeyTargetEnvelope[]> {\n assertContainerKekPathCurrent(input.projection.containerKeks);\n const keksByEpochId = await unwrapContainerKekPath({\n execSql: input.execSql,\n knownContainerKeks: input.knownContainerKeks,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n projection: input.projection,\n secretKey: input.secretKey,\n ...projectionVerificationOptions(input),\n });\n const target = getOnlyDocumentCreateTarget(input.projection);\n const targetKek = keksByEpochId.get(target.containerKeyEpochId);\n if (!targetKek) {\n throw new Error(\"Document create target KEK could not be unwrapped\");\n }\n\n const wrapped = await wrapContentKey(input.contentKey, targetKek, {\n kind: \"Document\",\n objectId: input.documentId,\n contentKeyEpoch: input.contentKeyEpoch,\n containerId: target.containerId,\n containerKeyEpochId: target.containerKeyEpochId,\n });\n\n return [\n {\n ...target,\n wrappedKey: bytesToBase64(wrapped.ciphertext),\n wrappingMetadata: {\n suite: DOCUMENT_CONTENT_KEY_WRAP_SUITE,\n iv: bytesToBase64(wrapped.iv),\n },\n },\n ];\n}\n\nexport async function unwrapContentKeyTargetForKind(input: {\n containerKek: Uint8Array;\n /** The content-key epoch of the bundle the envelope was served in. */\n contentKeyEpoch: number;\n /** Wraps a decode or decrypt failure with this message. */\n decryptErrorMessage?: string | undefined;\n envelope: {\n containerId: string;\n containerKeyEpochId: string;\n wrappedKey: string;\n wrappingMetadata?: unknown;\n };\n kind: ContentKeyEnvelopeKind;\n /** The document or blob the caller is reading, never read from the bundle. */\n objectId: string;\n}): Promise<Uint8Array> {\n // Reading, not submitting: the suite still binds the envelope to its object\n // kind, but an unrecognized extra metadata key is ignored rather than making\n // an otherwise decryptable envelope permanently unreadable. The AEAD tag is\n // what authenticates the recovered key, bound to the object, content-key\n // epoch and target it was sealed for. The KEK stays out of the decoder.\n try {\n return await unwrapContentKey(\n decodeContentKeyEnvelope({\n envelope: input.envelope,\n kind: input.kind,\n origin: \"stored\",\n }),\n input.containerKek,\n {\n kind: input.kind,\n objectId: input.objectId,\n contentKeyEpoch: input.contentKeyEpoch,\n containerId: input.envelope.containerId,\n containerKeyEpochId: input.envelope.containerKeyEpochId,\n },\n );\n } catch (error) {\n if (!input.decryptErrorMessage) throw error;\n // Keep the structural diagnostic; the wrapper only adds which target it\n // was, which the decoder cannot know.\n const detail =\n error instanceof ContentKeyEnvelopeError ? `: ${error.message}` : \"\";\n throw new Error(`${input.decryptErrorMessage}${detail}`, { cause: error });\n }\n}\n\nexport async function unwrapDocumentContentKeyTarget(input: {\n containerKek: Uint8Array;\n contentKeyEpoch: number;\n documentId: string;\n envelope: DocumentContentKeyTargetEnvelope;\n}): Promise<Uint8Array> {\n return unwrapContentKeyTargetForKind({\n containerKek: input.containerKek,\n contentKeyEpoch: input.contentKeyEpoch,\n decryptErrorMessage: `Document content-key target for container ${input.envelope.containerId} at epoch ${input.envelope.containerKeyEpochId} could not be unwrapped`,\n envelope: input.envelope,\n kind: \"Document\",\n objectId: input.documentId,\n });\n}\n\ninterface CollectedContainerKeks {\n readonly keksByEpochId: ReadonlyMap<string, Uint8Array>;\n readonly predecessorFailuresByEpochId: ReadonlyMap<string, Error>;\n readonly unattributedPredecessorFailuresByContainerId: ReadonlyMap<\n string,\n Error\n >;\n}\n\nexport class DocumentHistoryUnavailableError extends Error {\n constructor(readonly historyCause: unknown) {\n super(\n historyCause instanceof Error\n ? historyCause.message\n : \"Document history key is unavailable\",\n );\n this.name = \"DocumentHistoryUnavailableError\";\n }\n}\n\n/** No verified target or predecessor path can supply this content key. */\nexport class DocumentContentKeyUnavailableError extends Error {\n constructor() {\n super(\"Document content key could not be unwrapped\");\n this.name = \"DocumentContentKeyUnavailableError\";\n }\n}\n\nfunction preferredPredecessorFailure(\n failures: readonly Error[],\n): Error | undefined {\n return (\n failures.find(\n (failure) => !(failure instanceof ContainerKekHistoryUnavailableError),\n ) ?? failures[0]\n );\n}\n\nfunction recordPreferredPredecessorFailure(\n failures: Map<string, Error>,\n key: string,\n failure: Error,\n): void {\n const existing = failures.get(key);\n const preferred = preferredPredecessorFailure(\n existing ? [existing, failure] : [failure],\n );\n if (preferred) failures.set(key, preferred);\n}\n\nexport async function collectContainerKeksForDocumentSync(\n input: {\n execSql?: ExecSql | undefined;\n persistVerificationCheckpoints?: boolean | undefined;\n principalPolicyCache?: PrincipalPolicyCache | undefined;\n secretKey: Uint8Array;\n verifiedByHash?: Map<string, VerifiedContainerAccessManifest> | undefined;\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<CollectedContainerKeks> {\n const keksByEpochId = new Map<string, Uint8Array>();\n const predecessorFailuresByEpochId = new Map<string, Error>();\n const unattributedPredecessorFailuresByContainerId = new Map<string, Error>();\n\n for (const projection of documentContainerProjections(\n input.writerProjection,\n )) {\n let projectionKeks: Awaited<\n ReturnType<typeof unwrapContainerKekPathWithHistoryFailures>\n >;\n try {\n projectionKeks = await unwrapContainerKekPathWithHistoryFailures({\n execSql: input.execSql,\n knownContainerKeks: keksByEpochId,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n principalPolicyCache: input.principalPolicyCache,\n projection,\n secretKey: input.secretKey,\n verifiedByHash: input.verifiedByHash,\n ...projectionVerificationOptions(input),\n });\n } catch (error) {\n throwKeyingVerificationErrorWithContext(\n error,\n `Document authorizing container KEK path could not be unwrapped for ${describeProjectionTargetKek(projection)}`,\n );\n }\n for (const [\n containerKeyEpochId,\n failure,\n ] of projectionKeks.predecessorFailuresByEpochId) {\n recordPreferredPredecessorFailure(\n predecessorFailuresByEpochId,\n containerKeyEpochId,\n failure,\n );\n }\n for (const [\n containerId,\n failure,\n ] of projectionKeks.unattributedPredecessorFailuresByContainerId) {\n recordPreferredPredecessorFailure(\n unattributedPredecessorFailuresByContainerId,\n containerId,\n failure,\n );\n }\n for (const [\n containerKeyEpochId,\n keyMaterial,\n ] of projectionKeks.keksByEpochId) {\n const existing = keksByEpochId.get(containerKeyEpochId);\n if (existing) {\n assertEqualBytes(\n existing,\n keyMaterial,\n \"Document writer projection contains conflicting container KEKs\",\n );\n continue;\n }\n keksByEpochId.set(containerKeyEpochId, keyMaterial);\n }\n }\n\n return {\n keksByEpochId,\n predecessorFailuresByEpochId,\n unattributedPredecessorFailuresByContainerId,\n };\n}\n\nexport async function unwrapDocumentContentKeyFromBundle(\n bundle: DocumentContentKeyBundleResponse,\n /** The document being read; its wraps must be sealed to it. */\n documentId: string,\n containerKeksByEpochId: ReadonlyMap<string, Uint8Array>,\n predecessorFailuresByEpochId: ReadonlyMap<string, Error> = new Map(),\n unattributedPredecessorFailuresByContainerId: ReadonlyMap<\n string,\n Error\n > = new Map(),\n): Promise<Uint8Array> {\n const canonicalTargetHash = await computeDocumentContentKeyTargetHash(\n sortDocumentTargets(bundle.targets.map(targetEnvelopeReference)),\n );\n if (canonicalTargetHash !== bundle.targetHash) {\n throw new Error(\"Document content-key bundle target hash is not canonical\");\n }\n if (bundle.documentId !== documentId) {\n throw new Error(\"Document content-key bundle names another document\");\n }\n let contentKey: Uint8Array | null = null;\n const predecessorFailures: Error[] = [];\n\n for (const envelope of bundle.targets) {\n const containerKek = containerKeksByEpochId.get(\n envelope.containerKeyEpochId,\n );\n if (!containerKek) {\n const predecessorFailure =\n predecessorFailuresByEpochId.get(envelope.containerKeyEpochId) ??\n unattributedPredecessorFailuresByContainerId.get(envelope.containerId);\n if (predecessorFailure) predecessorFailures.push(predecessorFailure);\n continue;\n }\n const unwrapped = await unwrapDocumentContentKeyTarget({\n containerKek,\n contentKeyEpoch: bundle.contentKeyEpoch,\n documentId,\n envelope,\n });\n if (contentKey) {\n assertEqualBytes(\n contentKey,\n unwrapped,\n \"Document content-key targets unwrap to conflicting keys\",\n );\n continue;\n }\n contentKey = unwrapped;\n }\n\n if (!contentKey) {\n const predecessorFailure = preferredPredecessorFailure(predecessorFailures);\n if (predecessorFailure !== undefined) {\n throw new DocumentHistoryUnavailableError(predecessorFailure);\n }\n throw new DocumentContentKeyUnavailableError();\n }\n if (contentKey.byteLength !== 32) {\n throw new Error(\"Document content key must be 32 bytes\");\n }\n\n return contentKey;\n}\n\nexport async function unwrapDocumentContentKeyFromWriterProjection(\n input: {\n execSql?: ExecSql | undefined;\n principalPolicyCache?: PrincipalPolicyCache | undefined;\n secretKey: Uint8Array;\n verifiedByHash?: Map<string, VerifiedContainerAccessManifest> | undefined;\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<Uint8Array> {\n const collectedKeks = await collectContainerKeksForDocumentSync(input);\n\n return unwrapDocumentContentKeyFromBundle(\n input.writerProjection.contentKeyBundle,\n input.writerProjection.documentId,\n collectedKeks.keksByEpochId,\n collectedKeks.predecessorFailuresByEpochId,\n collectedKeks.unattributedPredecessorFailuresByContainerId,\n );\n}\n\n/**\n * Builds the healing bundle for a stale content-key bundle: wraps a FRESH\n * content key to the projection's CURRENT KEK targets at the next\n * content-key epoch. A current reader can recover the stale bundle through\n * the container predecessor chain; the fresh key is still required so a\n * holder revoked by the container rotation cannot decrypt future updates.\n * Recovery re-encrypts a full-history snapshot under that fresh key.\n *\n * Like every content-key rotation (unlink included), this requires the KEK\n * of EVERY linked-container target: all envelopes in a bundle must wrap the\n * same key, so an inaccessible target's envelope can neither be carried\n * forward (it wraps the old key) nor fabricated. A writer authorized through\n * only a subset of a multi-container link set fails here with a named target\n * and leaves the heal to a member who spans all of them.\n */\nexport async function buildRotatedDocumentContentKeyBundle(input: {\n containerKeksByEpochId: ReadonlyMap<string, Uint8Array>;\n contentKey: Uint8Array;\n writerProjection: DocumentWriterProjectionResponse;\n}): Promise<DocumentContentKeyBundleResponse> {\n assertDocumentKekPathsCurrent(input.writerProjection);\n const { contentKeyBundle, documentKekTargets } = input.writerProjection;\n // The server list names the linked containers; each envelope's epoch comes\n // from the verified authorizing-path leaf for that container.\n const targets = verifiedDocumentWrapTargets({\n linkedContainerIds: readLinkedContainerIdsFromDocumentManifest(\n input.writerProjection,\n ),\n serverTargets: normalizeDocumentKekTargetResponse(documentKekTargets),\n writerProjection: input.writerProjection,\n });\n const envelopes: DocumentContentKeyBundleResponse[\"targets\"] = [];\n const contentKeyEpoch = contentKeyBundle.contentKeyEpoch + 1;\n\n for (const target of targets) {\n const containerKek = input.containerKeksByEpochId.get(\n target.containerKeyEpochId,\n );\n if (!containerKek) {\n throw new Error(\n `Document content-key re-wrap KEK is unavailable for ${describeDocumentTargetKek(target)}`,\n );\n }\n const wrapped = await wrapContentKey(input.contentKey, containerKek, {\n kind: \"Document\",\n objectId: contentKeyBundle.documentId,\n contentKeyEpoch,\n containerId: target.containerId,\n containerKeyEpochId: target.containerKeyEpochId,\n });\n envelopes.push({\n ...target,\n wrappedKey: bytesToBase64(wrapped.ciphertext),\n wrappingMetadata: {\n suite: DOCUMENT_CONTENT_KEY_WRAP_SUITE,\n iv: bytesToBase64(wrapped.iv),\n },\n });\n }\n\n return {\n contentKeyEpoch,\n documentId: contentKeyBundle.documentId,\n linkSetManifestHash: documentKekTargets.linkSetManifestHash,\n targetHash: documentKekTargets.documentKeyTargetHash,\n targets: envelopes,\n };\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"projectionTargets.js","sourceRoot":"","sources":["projectionTargets.ts"],"names":[],"mappings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AAiB,CAC/B,IAAyC;IAEzC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE;QACzB,MAAM,WAAW,GAAG,uBAAuB,CAAC,MAAM,CAAC,CAAC;QACpD,IAAI,CAAC,WAAW,EAAE,CAAC;YACjB,MAAM,IAAI,KAAK,CAAC,mDAAmD,CAAC,CAAC;QACvE,CAAC;QACD,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,CAAC,YAAY,EAAE,CAAC;IAC5D,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,4BAA4B,CAC1C,gBAAkD;IAElD,OAAO,gBAAgB,CAAC,yBAAyB,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CACnE,iBAAiB,CAAC,UAAU,CAAC,IAAI,CAAC,CACnC,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,sCAAsC,CAAC,KAItD;IACC,MAAM,KAAK,GAAG,KAAK,CAAC,gBAAgB,CAAC,yBAAyB,CAAC,MAAM,CACnE,CAAC,UAAU,EAAE,EAAE,CACb,KAAK,CAAC,SAAS,KAAK,MAAM;QAC1B,yBAAyB,CAAC,UAAU,CAAC,KAAK,KAAK,CAAC,iBAAiB,CACpE,CAAC;IACF,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACvB,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;IACrE,CAAC;IAED,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,iBAAiB,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC;AACvE,CAAC","sourcesContent":["import {\n type DocumentContentKeyTarget,\n KeyingVerificationError,\n} from \"@tearleads/crypto\";\nimport { isPlainObject as isPlainRecord } from \"@tearleads/validators/isPlainObject\";\nimport type {\n ContainerManifestRef,\n DocumentContentKeyTargetEnvelope,\n} from \"@tearleads/validators/request\";\nimport type {\n ContainerKeyingPathResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n describeDocumentTargetKek,\n normalizeDocumentKekTargetResponse,\n readManifestContainerId,\n serializeCanonical,\n sortDocumentTargets,\n targetEnvelopeReference,\n targetKey,\n uniqueSortedStrings,\n} from \"./readers\";\nimport type { DocumentLinkSetMutationOperation } from \"./types\";\n\nexport function deriveDocumentCreateTargets(\n projection: ContainerKeyingPathResponse,\n): DocumentContentKeyTarget[] {\n const targetIndex = projection.path.length - 1;\n const targetManifest = projection.path[targetIndex];\n if (!targetManifest) {\n throw new Error(\"Container writer projection path is empty\");\n }\n\n if (readManifestContainerId(targetManifest) !== projection.containerId) {\n throw new Error(\"Container writer projection target path is inconsistent\");\n }\n\n const targetKek = projection.containerKeks[targetIndex];\n if (!targetKek) {\n throw new Error(\"Container writer projection target KEK is unavailable\");\n }\n if (targetKek.containerId !== projection.containerId) {\n throw new Error(\"Container writer projection target KEK is inconsistent\");\n }\n if (targetKek.accessManifestHash !== targetManifest.manifestHash) {\n throw new Error(\"Container writer projection target KEK is stale\");\n }\n\n return [\n {\n containerId: targetKek.containerId,\n containerManifestHash: targetKek.accessManifestHash,\n containerKeyEpochId: targetKek.containerKeyEpochId,\n containerKeyEpoch: targetKek.containerKeyEpoch,\n },\n ];\n}\n\nexport function mergeTargetEnvelopes(\n targets: readonly DocumentContentKeyTarget[],\n envelopes: readonly DocumentContentKeyTargetEnvelope[],\n): DocumentContentKeyTargetEnvelope[] {\n const expectedByKey = new Map(\n targets.map((target) => [targetKey(target), target]),\n );\n const envelopeByKey = new Map<string, DocumentContentKeyTargetEnvelope>();\n\n for (const envelope of envelopes) {\n const key = targetKey(envelope);\n if (!expectedByKey.has(key)) {\n throw new Error(\"Document content-key target envelope is unexpected\");\n }\n if (envelopeByKey.has(key)) {\n throw new Error(\"Document content-key target envelope is duplicated\");\n }\n if (envelope.wrappedKey.length === 0) {\n throw new Error(\"Document content-key target envelope is empty\");\n }\n if (!isPlainRecord(envelope.wrappingMetadata)) {\n throw new Error(\n \"Document content-key target wrapping metadata must be an object\",\n );\n }\n envelopeByKey.set(key, envelope);\n }\n\n return sortDocumentTargets(targets).map((target) => {\n const envelope = envelopeByKey.get(targetKey(target));\n if (!envelope) {\n throw new Error(\"Document content-key target envelope is missing\");\n }\n return envelope;\n });\n}\n\nfunction projectionLeafContainerId(\n projection: ContainerKeyingPathResponse,\n): string | null {\n const leafBundle = projection.path.at(-1);\n return leafBundle ? readManifestContainerId(leafBundle) : null;\n}\n\nexport function describeProjectionTargetKek(\n projection: ContainerKeyingPathResponse,\n): string {\n const targetKek = projection.containerKeks.at(-1);\n const containerId =\n projectionLeafContainerId(projection) ??\n targetKek?.containerId ??\n projection.containerId;\n return targetKek\n ? `container ${containerId} epoch ${targetKek.containerKeyEpochId}`\n : `container ${containerId}`;\n}\n\nexport function deriveDocumentTargetFromProjection(\n projection: ContainerKeyingPathResponse,\n): DocumentContentKeyTarget {\n const target = deriveDocumentCreateTargets(projection)[0];\n if (!target) {\n throw new Error(\"Document target projection is unavailable\");\n }\n return target;\n}\n\nexport function readLinkedContainerIdsFromDocumentManifest(\n writerProjection: DocumentWriterProjectionResponse,\n): string[] {\n const state = writerProjection.documentManifest.state;\n const linkedContainerIds = isPlainRecord(state)\n ? Reflect.get(state, \"linkedContainerIds\")\n : undefined;\n if (\n !Array.isArray(linkedContainerIds) ||\n linkedContainerIds.some(\n (containerId) =>\n typeof containerId !== \"string\" || containerId.length === 0,\n )\n ) {\n throw new Error(\"Document link-set state is invalid\");\n }\n\n return uniqueSortedStrings(linkedContainerIds);\n}\n\n/**\n * The targets a content-key (re)wrap may address. The server's KEK target list\n * only says which linked containers the bundle must cover; the epoch each\n * envelope lands on comes from that container's verified authorizing-path\n * leaf, never from the server row. A listed epoch that is not the linked\n * container's verified current head — a predecessor a revoked member still\n * holds, or another container's epoch — therefore fails before any wrap, as\n * does a container listed twice. A linked container with no authorizing path\n * is an availability gap, not tampering: its KEK is simply unavailable here.\n */\nexport function verifiedDocumentWrapTargets(input: {\n linkedContainerIds: readonly string[];\n serverTargets: readonly DocumentContentKeyTarget[];\n writerProjection: DocumentWriterProjectionResponse;\n}): DocumentContentKeyTarget[] {\n const verifiedByKey = new Map<string, DocumentContentKeyTarget>();\n const verifiedContainerIds = new Set<string>();\n for (const projection of input.writerProjection.authorizingContainerPaths) {\n const target = deriveDocumentTargetFromProjection(projection);\n verifiedByKey.set(targetKey(target), target);\n verifiedContainerIds.add(target.containerId);\n }\n\n const containerIds = input.serverTargets.map((target) => target.containerId);\n if (new Set(containerIds).size !== containerIds.length) {\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n \"Document content-key targets name a linked container more than once\",\n );\n }\n const linkedContainerIds = uniqueSortedStrings(input.linkedContainerIds);\n const sortedContainerIds = uniqueSortedStrings(containerIds);\n if (\n sortedContainerIds.length !== linkedContainerIds.length ||\n sortedContainerIds.some((id, index) => id !== linkedContainerIds[index])\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document content-key targets do not match the linked containers\",\n );\n }\n\n return sortDocumentTargets(\n input.serverTargets.map((target) => {\n const verified = verifiedByKey.get(targetKey(target));\n if (verified) {\n return verified;\n }\n if (!verifiedContainerIds.has(target.containerId)) {\n throw new Error(\n `Document content-key re-wrap KEK is unavailable for ${describeDocumentTargetKek(target)}`,\n );\n }\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `Document content-key target is not the verified head of ${describeDocumentTargetKek(target)}`,\n );\n }),\n );\n}\n\nexport function currentDocumentTargets(\n writerProjection: DocumentWriterProjectionResponse,\n): DocumentContentKeyTarget[] {\n const targets = normalizeDocumentKekTargetResponse(\n writerProjection.documentKekTargets,\n );\n const bundleTargets = sortDocumentTargets(\n writerProjection.contentKeyBundle.targets.map(targetEnvelopeReference),\n );\n\n if (\n serializeCanonical(targets, \"KEK targets\") !==\n serializeCanonical(bundleTargets, \"content-key targets\")\n ) {\n throw new Error(\"Document link-set content-key targets mismatch\");\n }\n\n return targets;\n}\n\n/**\n * Reduce a single container path (root→leaf chain) to {containerId,\n * manifestHash} references. The server already stores each manifest and resolves\n * it from its own store, so a write echoes only the hashes instead of\n * re-embedding the full signed bundles it received in the writer projection.\n */\nexport function containerPathRefs(\n path: ContainerKeyingPathResponse[\"path\"],\n): ContainerManifestRef[] {\n return path.map((bundle) => {\n const containerId = readManifestContainerId(bundle);\n if (!containerId) {\n throw new Error(\"Container path manifest is missing a container id\");\n }\n return { containerId, manifestHash: bundle.manifestHash };\n });\n}\n\nexport function authorizingContainerPathRefs(\n writerProjection: DocumentWriterProjectionResponse,\n): ContainerManifestRef[][] {\n return writerProjection.authorizingContainerPaths.map((projection) =>\n containerPathRefs(projection.path),\n );\n}\n\nexport function authorizingContainerPathRefsForLinkSet(input: {\n operation: DocumentLinkSetMutationOperation;\n targetContainerId: string;\n writerProjection: DocumentWriterProjectionResponse;\n}): ContainerManifestRef[][] {\n const paths = input.writerProjection.authorizingContainerPaths.filter(\n (projection) =>\n input.operation === \"link\" ||\n projectionLeafContainerId(projection) !== input.targetContainerId,\n );\n if (paths.length === 0) {\n throw new Error(\"Document link-set authorizing paths are missing\");\n }\n\n return paths.map((projection) => containerPathRefs(projection.path));\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"syncPagination.js","sourceRoot":"","sources":["syncPagination.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAezD,OAAO,EAAE,kCAAkC,EAAE,MAAM,oBAAoB,CAAC;AAExE,MAAM,OAAO,wCAAyC,SAAQ,KAAK;IACjE,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,0CAA0C,CAAC;IACzD,CAAC;CACF;AAmBD,MAAM,UAAU,oBAAoB,CAClC,QAA8B;IAE9B,MAAM,MAAM,GAAG,eAAe,CAAC,QAAQ,CAAC,CAAC,UAAU,CAAC;IACpD,IAAI,MAAM,KAAK,IA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CAAC,CAAC;IACH,IAAI,UAAU,KAAK,IAAI,IAAI,IAAI,CAAC,QAAQ,CAAC,SAAS,KAAK,IAAI,EAAE,CAAC;QAC5D,MAAM,IAAI,wCAAwC,CAChD,2DAA2D,CAC5D,CAAC;IACJ,CAAC;IACD,IAAI,UAAU,KAAK,IAAI,IAAI,UAAU,KAAK,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC;QACxE,MAAM,IAAI,wCAAwC,CAChD,mDAAmD,CACpD,CAAC;IACJ,CAAC;IACD,OAAO;QACL,EAAE,EAAE,IAAI;QACR,YAAY,EAAE,UAAU,KAAK,IAAI;QACjC,QAAQ,EAAE,IAAI,CAAC,QAAQ;KACxB,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,kBAAkB,CAAC,KAIxC;IACC,OAAO,sBAAsB,CAAC;QAC5B,qBAAqB,EAAE,KAAK,CAAC,qBAAqB;QAClD,IAAI,EAAE,KAAK,CAAC,IAAI;QAChB,MAAM,EAAE,KAAK,IAAI,EAAE;YACjB,MAAM,MAAM,GAAG,MAAM,KAAK,CAAC,SAAS,CAAC,kBAAkB,CACrD,KAAK,CAAC,IAAI,CAAC,UAAU,EACrB,KAAK,CAAC,IAAI,CAAC,OAAO,EAClB;gBACE,qCAAqC,EAAE,KAAK,CAAC,IAAI,CAAC,cAAc;gBAChE,YAAY,EAAE,KAAK;aACpB,CACF,CAAC;YACF,OAAO,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC;QAClE,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { DocumentSyncResponse } from \"@tearleads/validators/response\";\nimport { parseWalLsn } from \"@tearleads/validators/util\";\nimport type {\n DocumentSyncCommitLsnMode,\n DocumentSyncPullContinuation,\n} from \"./pullContinuation\";\nimport type {\n DocumentSyncApi,\n DocumentSyncPlan,\n DocumentSyncSubmitFailure,\n} from \"./types\";\n\nexport type {\n DocumentSyncCommitLsnMode,\n DocumentSyncPullContinuation,\n} from \"./pullContinuation\";\nexport { documentSyncPullContinuationsEqual } from \"./pullContinuation\";\n\nexport class InvalidDocumentSyncPullContinuationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"InvalidDocumentSyncPullContinuationError\";\n }\n}\n\ntype DocumentSyncPageSubmission =\n | {\n readonly ok: true;\n readonly response: DocumentSyncResponse;\n }\n | DocumentSyncSubmitFailure\n | null;\n\ntype DocumentSyncSubmission =\n | {\n readonly ok: true;\n readonly pullComplete: boolean;\n readonly response: DocumentSyncResponse;\n }\n | DocumentSyncSubmitFailure\n | null;\n\nexport function readPullContinuation(\n response: DocumentSyncResponse,\n): DocumentSyncPullContinuation | null {\n const cursor = requirePullPage(response).nextCursor;\n if (cursor === null) return null;\n if (response.commitLsn === null) {\n throw new Error(\n \"Document sync pull continuation is missing its checkpoint\",\n );\n }\n return {\n commitLsn: response.commitLsn,\n commitLsnMode: response.commitLsnMode,\n cursor,\n };\n}\n\nexport function resolvePullContinuationMinLsn(\n continuation: DocumentSyncPullContinuation | undefined,\n fallback: string | undefined,\n): string | undefined {\n if (!continuation) return fallback;\n if (continuation.commitLsnMode === \"untracked\" || fallback === undefined) {\n return continuation.commitLsn;\n }\n return parseWalLsn(continuation.commitLsn) >= parseWalLsn(fallback)\n ? continuation.commitLsn\n : fallback;\n}\n\nfunction assertPageCheckpoint(input: {\n readonly minLsn: string | undefined;\n readonly nextCursor: string | null;\n readonly response: DocumentSyncResponse;\n}): void {\n if (input.response.commitLsnMode === \"untracked\") {\n if (input.response.commitLsn !== \"0/0\") {\n throw new InvalidDocumentSyncPullContinuationError(\n \"Document sync continuation untracked LSN is invalid\",\n );\n }\n return;\n }\n if (input.response.commitLsn === null) {\n if (input.minLsn === undefined && input.nextCursor === null) return;\n throw new InvalidDocumentSyncPullContinuationError(\n \"Document sync pull continuation is missing its checkpoint\",\n );\n }\n let responseLsn: bigint;\n try {\n responseLsn = parseWalLsn(input.response.commitLsn);\n } catch {\n throw new InvalidDocumentSyncPullContinuationError(\n \"Document sync continuation commit LSN is invalid\",\n );\n }\n if (input.minLsn === undefined) return;\n let minimumLsn: bigint;\n try {\n minimumLsn = parseWalLsn(input.minLsn);\n } catch {\n throw new InvalidDocumentSyncPullContinuationError(\n \"Document sync minimum commit LSN is invalid\",\n );\n }\n if (responseLsn < minimumLsn) {\n throw new InvalidDocumentSyncPullContinuationError(\n \"Document sync continuation commit LSN regressed\",\n );\n }\n}\n\nfunction requirePullPage(response: DocumentSyncResponse) {\n if (response.pullPage === undefined) {\n throw new Error(\"Document sync response is missing pull page metadata\");\n }\n return response.pullPage;\n}\n\nasync function submitDocumentSyncPage(input: {\n readonly expectedCommitLsnMode?: DocumentSyncCommitLsnMode | undefined;\n readonly plan: DocumentSyncPlan;\n readonly submit: () => Promise<DocumentSyncPageSubmission>;\n}): Promise<DocumentSyncSubmission> {\n const page = await input.submit();\n if (!page?.ok) return page;\n if (\n input.expectedCommitLsnMode !== undefined &&\n page.response.commitLsnMode !== input.expectedCommitLsnMode\n ) {\n throw new InvalidDocumentSyncPullContinuationError(\n \"Document sync continuation commit LSN mode changed\",\n );\n }\n const nextCursor = requirePullPage(page.response).nextCursor;\n assertPageCheckpoint({\n minLsn: input.plan.request.minLsn,\n nextCursor,\n response: page.response,\n });\n if (nextCursor !== null && page.response.commitLsn === null) {\n throw new InvalidDocumentSyncPullContinuationError(\n \"Document sync pull continuation is missing its checkpoint\",\n );\n }\n if (nextCursor !== null && nextCursor === input.plan.request.pullCursor) {\n throw new InvalidDocumentSyncPullContinuationError(\n \"Document sync continuation cursor did not advance\",\n );\n }\n return {\n ok: true,\n pullComplete: nextCursor === null,\n response: page.response,\n };\n}\n\nexport async function submitDocumentSync(input: {\n apiClient: DocumentSyncApi;\n expectedCommitLsnMode?: DocumentSyncCommitLsnMode | undefined;\n plan: DocumentSyncPlan;\n}): Promise<DocumentSyncSubmission> {\n return submitDocumentSyncPage({\n expectedCommitLsnMode: input.expectedCommitLsnMode,\n plan: input.plan,\n submit: async () => {\n const result = await input.apiClient.syncDocumentResult(\n input.plan.documentId,\n input.plan.request,\n {\n expectedPaymentRequiredOrganizationId: input.plan.organizationId,\n reportErrors: false,\n },\n );\n return result.ok ? { ok: true, response: result.data } : result;\n },\n });\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"syncResponseAuthorization.js","sourceRoot":"","sources":["syncResponseAuthorization.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mCAAmC,EAEnC,8BAA8B,GAC/B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,0BAA0B,EAAE,MAAM,qEAAqE,CAAC;AACjH,OAAO,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAGhD,MAAM,CAAC,KAAK,UAAU,mCAAmC,CAAC,KAWzD;IACC,MAAM,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,2BAA2B,CAAC;IACtD,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,IAAI,KAAK,CAAC,yBAAyB,EAAE,CAAC;YACpC,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,IAAI,KAAK,CACb,qEAAqE,CACtE,CAAC;IACJ,CAAC;IACD,MAAM,gBAAgB,GAAG,MAAM,CAAC,sBAAsB,CAAC,GAAG,CACxD,KAAK,CAAC,YAAY,CACnB,CAAC;IACF,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACtB,MAAM,IAAI,KAAK,CACb,kEAAkE,CACnE,CAAC;IACJ,CAAC;IACD,IAAI,KAAK,CAAC,gBAAgB,CAAC,UAAU,KAAK,KAAK,CAAC,IAAI,CAAC,UAAU,EAAE,CAAC;QAChE,MAAM,IAAI,KAAK,CACb,uEAAuE,CACxE,CAAC;IACJ,CAAC;IAED,MAAM,OAAO,GAAG,mBAAmB,CAAC,KAAK,CAAC,o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AmB,KAAK,MAAM,CAAC,mBAAmB,EAC7D,CAAC;YACD,MAAM,IAAI,KAAK,CACb,qEAAqE,CACtE,CAAC;QACJ,CAAC;IACH,CAAC;IACD,MAAM,yBAAyB,GAAG,wBAAwB,CAAC;IAC3D,MAAM,kBAAkB,GAAG,8BAA8B,CAAC;QACxD,UAAU,EAAE,KAAK,CAAC,gBAAgB,CAAC,UAAU;QAC7C,qBAAqB,EAAE,KAAK,CAAC,UAAU;QACvC,0BAA0B,EAAE,OAAO,CAAC,GAAG,CACrC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,mBAAmB,CACvC;QACD,6BAA6B,EAAE,OAAO,CAAC,GAAG,CACxC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,qBAAqB,CACzC;QACD,mBAAmB,EAAE,KAAK,CAAC,YAAY;QACvC,OAAO;KACR,CAAC,CAAC;IACH,OAAO;QACL,yBAAyB;QACzB,kBAAkB;QAClB,gBAAgB;QAChB,iBAAiB,EAAE,MAAM,CAAC,iBAAiB;KAC5C,CAAC;AACJ,CAAC","sourcesContent":["import {\n computeDocumentContentKeyTargetHash,\n type DocumentContentKeyTarget,\n makeVerifiedDocumentKekTargets,\n} from \"@tearleads/crypto\";\nimport type { DocumentSyncResponse } from \"@tearleads/validators/response\";\nimport { resolveEventContainerPaths } from \"../../keyingProjectionVerification/document/documentDependencyPaths\";\nimport { sortDocumentTargets } from \"./readers\";\nimport type { DocumentSyncPlan } from \"./types\";\n\nexport async function documentWriteAuthorizationForHeader(input: {\n readonly allowMissingAuthorization: boolean;\n readonly dependencyManifestHashes: readonly string[];\n readonly authorizationTargets: readonly DocumentContentKeyTarget[];\n readonly contentKeyBundle: DocumentSyncResponse[\"contentKeyBundle\"];\n readonly manifestHash: string;\n readonly plan: Pick<\n DocumentSyncPlan,\n \"documentId\" | \"organizationId\" | \"documentWriterAuthorization\"\n >;\n readonly targetHash: string;\n}) {\n const source = input.plan.documentWriterAuthorization;\n if (!source) {\n if (input.allowMissingAuthorization) {\n return null;\n }\n throw new Error(\n \"Document sync response lacks verified writer-authorization material\",\n );\n }\n const documentManifest = source.documentManifestByHash.get(\n input.manifestHash,\n );\n if (!documentManifest) {\n throw new Error(\n \"Document sync response write manifest is not in verified history\",\n );\n }\n if (input.contentKeyBundle.documentId !== input.plan.documentId) {\n throw new Error(\n \"Document sync response content-key bundle belongs to another document\",\n );\n }\n\n const targets = sortDocumentTargets(input.authorizationTargets);\n if (\n (await computeDocumentContentKeyTargetHash(targets)) !== input.targetHash\n ) {\n throw new Error(\"Document sync response write targets are not canonical\");\n }\n const linkedContainerIds = new Set(documentManifest.state.linkedContainerIds);\n if (\n targets.length !== linkedContainerIds.size ||\n targets.some((target) => !linkedContainerIds.has(target.containerId))\n ) {\n throw new Error(\n \"Document sync response write targets do not match the signed link set\",\n );\n }\n\n const { dependencyContainerPaths } = resolveEventContainerPaths({\n containerPathByManifestHash: source.containerPathByManifestHash,\n dependencyManifestHashes: input.dependencyManifestHashes,\n });\n // A writer needs one committed target, and can be unable to read another\n // linked container. Validate the targets that are cited without inventing\n // paths for uncited targets or dropping signed ancestor evidence.\n for (const target of targets) {\n const path = dependencyContainerPaths.find(\n (candidate) =>\n candidate.at(-1)?.manifestHash === target.containerManifestHash,\n );\n if (!path) continue;\n const leaf = path.at(-1);\n if (\n !leaf ||\n leaf.state.containerId !== target.containerId ||\n leaf.state.organizationId !== input.plan.organizationId ||\n leaf.state.containerKeyEpochId !== target.containerKeyEpochId\n ) {\n throw new Error(\n \"Document sync response write target lacks a verified container path\",\n );\n }\n }\n const authorizingContainerPaths = dependencyContainerPaths;\n const documentKekTargets = makeVerifiedDocumentKekTargets({\n documentId: input.contentKeyBundle.documentId,\n documentKeyTargetHash: input.targetHash,\n linkedContainerKeyEpochIds: targets.map(\n (target) => target.containerKeyEpochId,\n ),\n linkedContainerManifestHashes: targets.map(\n (target) => target.containerManifestHash,\n ),\n linkSetManifestHash: input.manifestHash,\n targets,\n });\n return {\n authorizingContainerPaths,\n documentKekTargets,\n documentManifest,\n principalPolicies: source.principalPolicies,\n };\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"syncResponses.js","sourceRoot":"","sources":["syncResponses.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,+BAA+B,EAC/B,mCAAmC,EACnC,0CAA0C,EAC1C,wCAAwC,EACxC,iBAAiB,GAElB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,IAAI,aAAa,EAAE,MAAM,qCAAqC,CAAC;AACrF,OAAO,EACL,6BAA6B,EAC7B,yBAAyB,GAE1B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AACzD,OAAO,EAAE,mCAAmC,EAAE,MAAM,0CAA0C,CAAC;AAC/F,OAAO,EACL,yBAAyB,EACzB,gBAAgB,EAChB,eAAe,EACf,kBAAkB,EAClB,gCAAgC,GACjC,MAAM,WAAW,CAAC;AAEnB,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAEtD,OAAO,EAAE,mCAAmC,EAAE,MAAM,6BAA6B,CAAC;AAQlF,4EAA4E;AAC5E,6EAA6E;AAC7E,gFAAgF;AAChF,8EAA8E;AAC9E,gFAAgF;AAChF,+EAA+E;AAC/E,MAAM,oBAAoB,GAAG,KAAK,CAAC;AAEnC,MAAM,OAAO,yCAA0C,SAAQ,KAAK;IAClE,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,2CAA2C,CAAC;IAC1D,CAAC;CACF;AAED,SAAS,wCAAwC,CAC/C,IAAsB,EACtB,QAA8B;IAE9B,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;IACzE,MAAM,QAAQ,GAAG,QAAQ,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E,mCAAmC,CAAC,KAAK,CAAC,CAAC;IAC7C,CAAC;AACH,CAAC;AAED,MAAM,UAAU,+BAA+B,CAC7C,OAAkC;IAElC,OAAO,CACL,OAAO,CAAC,MAAM,KAAK,GAAG;QACtB,OAAO,CAAC,IAAI,KAAK,yBAAyB,CAAC,UAAU,CACtD,CAAC;AACJ,CAAC;AAED,6EAA6E;AAC7E,6EAA6E;AAC7E,oEAAoE;AACpE,2CAA2C;AAC3C,MAAM,UAAU,oCAAoC,CAClD,OAAkC;IAElC,OAAO,CACL,OAAO,CAAC,MAAM,KAAK,GAAG,IAAI,OAAO,CAAC,IAAI,KAAK,6BAA6B,CACzE,CAAC;AACJ,CAAC","sourcesContent":["import {\n CONTENT_RECORD_ENCRYPTION_SUITE,\n computeContentRecordNonceDomainHash,\n computeDocumentContentRecordCiphertextHash,\n computeDocumentContentRecordMetadataHash,\n verifyWriteHeader,\n type WriteHeader,\n} from \"@tearleads/crypto\";\nimport { isPlainObject as isPlainRecord } from \"@tearleads/validators/isPlainObject\";\nimport {\n DOCUMENT_NOT_FOUND_ERROR_CODE,\n DOCUMENT_SYNC_ERROR_CODES,\n type DocumentSyncResponse,\n} from \"@tearleads/validators/response\";\nimport { parseWalLsn } from \"@tearleads/validators/util\";\nimport { throwKeyingVerificationShapeFailure } from \"../../keyingProjectionVerification/error\";\nimport {\n readRecordPositiveInteger,\n readRecordString,\n readWriteHeader,\n serializeCanonical,\n serializedPersistedDocumentState,\n} from \"./readers\";\n\nexport { submitDocumentSync } from \"./syncPagination\";\n\nimport { documentWriteAuthorizationForHeader } from \"./syncResponseAuthorization\";\nimport type {\n DocumentSyncPlan,\n DocumentSyncSubmitFailure,\n DocumentWriterPublicKeyResolver,\n PersistedDocumentSyncState,\n} from \"./types\";\n\n// Remote-primary databases without a portable WAL position use the zero LSN\n// as an explicit \"checkpoint not tracked\" sentinel. It is accepted only when\n// the response declares that mode, letting a local record carrying a checkpoint\n// from another backend move to that primary without weakening tracked checks.\n// This protects against replica lag, not a server that falsely declares its own\n// consistency capability; the authenticated server remains the source of data.\nconst UNTRACKED_COMMIT_LSN = \"0/0\";\n\nexport class DocumentSyncResponseUpdateContentKeyError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"DocumentSyncResponseUpdateContentKeyError\";\n }\n}\n\nfunction assertAcceptedOutgoingUpdateIdsMatchPlan(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n): void {\n const expected = plan.request.outgoingUpdates.map((update) => update.id);\n const accepted = response.acceptedOutgoingUpdateIds;\n const expectedSorted = [...expected].sort();\n const acceptedSorted = [...accepted].sort();\n if (\n expectedSorted.length !== acceptedSorted.length ||\n expectedSorted.some((id, index) => id !== acceptedSorted[index])\n ) {\n throw new Error(\"Document sync response accepted update mismatch\");\n }\n}\n\nasync function assertDocumentSyncResponseUpdateMatchesPlan(input: {\n contentKeyBundlesByEpoch: ReadonlyMap<\n number,\n DocumentSyncResponse[\"contentKeyBundle\"]\n >;\n plan: DocumentSyncPlan;\n update: DocumentSyncResponse[\"updates\"][number];\n resolveWriterPublicKey: DocumentWriterPublicKeyResolver;\n}): Promise<void> {\n const { plan, update } = input;\n if (update.documentId !== plan.documentId) {\n throw new Error(\"Document sync response update document mismatch\");\n }\n const header = readWriteHeader(\n update.writeHeader,\n \"Document sync response write header\",\n );\n await assertDocumentSyncResponseUpdateHashes({ update });\n const contentKeyBundle = assertDocumentSyncResponseUpdateContentKeyBundle({\n contentKeyBundlesByEpoch: input.contentKeyBundlesByEpoch,\n header,\n plan,\n });\n assertDocumentSyncResponseWriteHeaderFields({ header, plan, update });\n await assertDocumentSyncResponseNonceDomain({ header, plan });\n await assertDocumentSyncResponseWriteHeaderSignature({\n header,\n contentKeyBundle,\n plan,\n resolveWriterPublicKey: input.resolveWriterPublicKey,\n update,\n });\n}\n\nfunction assertDocumentSyncResponseUpdateContentKeyBundle(input: {\n contentKeyBundlesByEpoch: ReadonlyMap<\n number,\n DocumentSyncResponse[\"contentKeyBundle\"]\n >;\n header: WriteHeader;\n plan: DocumentSyncPlan;\n}): DocumentSyncResponse[\"contentKeyBundle\"] {\n const { header, plan } = input;\n if (header.contentKeyEpoch > plan.contentKeyEpoch) {\n throw new DocumentSyncResponseUpdateContentKeyError(\n \"Document sync response includes a future content-key epoch\",\n );\n }\n\n const bundle = input.contentKeyBundlesByEpoch.get(header.contentKeyEpoch);\n if (!bundle) {\n throw new DocumentSyncResponseUpdateContentKeyError(\n \"Document sync response content-key bundle missing\",\n );\n }\n if (\n bundle.documentId !== plan.documentId ||\n bundle.contentKeyEpoch !== header.contentKeyEpoch\n ) {\n throw new Error(\"Document sync response content-key bundle mismatch\");\n }\n return bundle;\n}\n\nasync function assertDocumentSyncResponseUpdateHashes(input: {\n update: DocumentSyncResponse[\"updates\"][number];\n}): Promise<void> {\n const { update } = input;\n const ciphertextHash = await computeDocumentContentRecordCiphertextHash(\n update.encryptedData,\n );\n if (\n ciphertextHash !==\n readRecordString(update.writeHeader, \"ciphertextHash\", \"write header\")\n ) {\n throw new Error(\"Document sync response ciphertext hash mismatch\");\n }\n const metadataHash = await computeDocumentContentRecordMetadataHash({\n ...(update.checkpointKind === undefined\n ? {}\n : { checkpointKind: update.checkpointKind }),\n ...(update.checkpointPayloadKind === undefined\n ? {}\n : { checkpointPayloadKind: update.checkpointPayloadKind }),\n documentId: update.documentId,\n partialEndVersionVector: update.partialEndVersionVector,\n partialStartVersionVector: update.partialStartVersionVector,\n plaintextHash: update.plaintextHash,\n ...(update.sourceVersionVector === undefined\n ? {}\n : { sourceVersionVector: update.sourceVersionVector }),\n updateId: update.id,\n });\n if (\n metadataHash !==\n readRecordString(update.writeHeader, \"metadataHash\", \"write header\")\n ) {\n throw new Error(\"Document sync response metadata hash mismatch\");\n }\n}\n\nfunction assertDocumentSyncResponseWriteHeaderFields(input: {\n header: WriteHeader;\n plan: DocumentSyncPlan;\n update: DocumentSyncResponse[\"updates\"][number];\n}): void {\n const { header, plan, update } = input;\n const mustMatchCurrentBoundary = isAcceptedOutgoingSyncUpdate(plan, update);\n\n if (\n header.version !== 1 ||\n header.objectKind !== \"document\" ||\n header.objectId !== plan.documentId ||\n header.organizationId !== plan.organizationId ||\n header.encryptionSuite !== CONTENT_RECORD_ENCRYPTION_SUITE ||\n header.writerKeyFingerprint !== update.authorFingerprint ||\n (mustMatchCurrentBoundary &&\n (header.contentKeyEpoch !== plan.contentKeyEpoch ||\n header.accessManifestHash !== plan.expectedLinkSetManifestHash ||\n header.targetHash !== plan.expectedTargetHash))\n ) {\n throw new Error(\"Document sync response write header mismatch\");\n }\n}\n\nfunction isAcceptedOutgoingSyncUpdate(\n plan: DocumentSyncPlan,\n update: DocumentSyncResponse[\"updates\"][number],\n): boolean {\n return plan.request.outgoingUpdates.some(\n (outgoingUpdate) => outgoingUpdate.id === update.id,\n );\n}\n\nasync function assertDocumentSyncResponseNonceDomain(input: {\n header: WriteHeader;\n plan: DocumentSyncPlan;\n}): Promise<void> {\n const { header, plan } = input;\n const nonceDomainHash = await computeContentRecordNonceDomainHash({\n version: 1,\n organizationId: plan.organizationId,\n objectKind: \"document\",\n objectId: plan.documentId,\n contentKeyEpoch: header.contentKeyEpoch,\n encryptionSuite: CONTENT_RECORD_ENCRYPTION_SUITE,\n contentRecordId: header.contentRecordId,\n });\n if (nonceDomainHash !== header.nonceDomainHash) {\n throw new Error(\"Document sync response nonce domain mismatch\");\n }\n}\n\nasync function assertDocumentSyncResponseWriteHeaderSignature(input: {\n contentKeyBundle: DocumentSyncResponse[\"contentKeyBundle\"];\n header: WriteHeader;\n plan: DocumentSyncPlan;\n resolveWriterPublicKey: DocumentWriterPublicKeyResolver;\n update: DocumentSyncResponse[\"updates\"][number];\n}): Promise<void> {\n const { header, plan, update } = input;\n const writerPublicKey = await input.resolveWriterPublicKey({\n writerSigningKeyFingerprint: header.writerKeyFingerprint,\n writerUserId: header.writerUserId,\n });\n if (!writerPublicKey) {\n throw new Error(\"Document sync response writer public key missing\");\n }\n\n const documentAuthorization = await documentWriteAuthorizationForHeader({\n allowMissingAuthorization: isAcceptedOutgoingSyncUpdate(plan, update),\n authorizationTargets: update.authorizationTargets,\n dependencyManifestHashes: header.dependencyManifestHashes,\n contentKeyBundle: input.contentKeyBundle,\n manifestHash: header.accessManifestHash,\n plan,\n targetHash: header.targetHash,\n });\n const verified = await verifyWriteHeader({\n authorizationMembership: \"referenced\",\n expectedAccessManifestHash: documentAuthorization\n ? header.accessManifestHash\n : plan.expectedLinkSetManifestHash,\n expectedObject: {\n objectKind: \"document\",\n objectId: plan.documentId,\n organizationId: plan.organizationId,\n },\n header,\n ...(documentAuthorization ? { documentAuthorization } : {}),\n expectedTargetHash: documentAuthorization\n ? header.targetHash\n : plan.expectedTargetHash,\n writerPublicKey,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n}\n\nfunction assertDocumentSyncCommitCheckpointMatchesPlan(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n): void {\n if (\n response.commitLsnMode === \"untracked\" &&\n response.commitLsn !== UNTRACKED_COMMIT_LSN\n ) {\n throw new Error(\n \"Document sync response untracked commit LSN must use the 0/0 sentinel\",\n );\n }\n if (\n response.commitLsn === UNTRACKED_COMMIT_LSN &&\n response.commitLsnMode !== \"untracked\"\n ) {\n throw new Error(\n \"Document sync response 0/0 commit LSN must be declared untracked\",\n );\n }\n if (response.commitLsn !== null) {\n parseWalLsn(response.commitLsn, \"Document sync response commit LSN\");\n }\n if (plan.minLsn === undefined) {\n return;\n }\n const minLsn = parseWalLsn(\n plan.minLsn,\n \"Document sync requested minimum LSN\",\n );\n if (response.commitLsn === null) {\n throw new Error(\"Document sync response commit LSN is missing\");\n }\n if (\n !(\n response.commitLsn === UNTRACKED_COMMIT_LSN &&\n response.commitLsnMode === \"untracked\"\n ) &&\n parseWalLsn(response.commitLsn, \"Document sync response commit LSN\") <\n minLsn\n ) {\n throw new Error(\"Document sync response commit LSN is stale\");\n }\n}\n\nfunction documentSyncManifestEpoch(plan: DocumentSyncPlan): number {\n if (!isPlainRecord(plan.documentManifest.state)) {\n throw new Error(\"Document sync manifest state is invalid\");\n }\n\n return readRecordPositiveInteger(\n plan.documentManifest.state,\n \"epoch\",\n \"Document sync manifest state\",\n );\n}\n\n// The one load-bearing epoch check: no returned update may claim an\n// accessEpoch newer than the current manifest epoch.\nfunction assertDocumentSyncAccessEpochsNotInFuture(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n): void {\n const currentAccessEpoch = documentSyncManifestEpoch(plan);\n for (const update of response.updates) {\n if (update.accessEpoch > currentAccessEpoch) {\n throw new Error(\"Document sync response includes a future access epoch\");\n }\n }\n}\n\nfunction contentKeyBundleCanonical(\n bundle: DocumentSyncResponse[\"contentKeyBundle\"],\n): string {\n return serializeCanonical(bundle, \"content-key bundle\");\n}\n\nfunction documentSyncContentKeyBundlesByEpoch(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n): ReadonlyMap<number, DocumentSyncResponse[\"contentKeyBundle\"]> {\n if (\n contentKeyBundleCanonical(response.contentKeyBundle) !==\n contentKeyBundleCanonical(plan.sourceContentKeyBundle)\n ) {\n throw new Error(\"Document sync response content-key bundle mismatch\");\n }\n\n const bundleByEpoch = new Map<\n number,\n DocumentSyncResponse[\"contentKeyBundle\"]\n >();\n const bundles = [response.contentKeyBundle, ...response.contentKeyBundles];\n\n for (const bundle of bundles) {\n if (bundle.documentId !== plan.documentId) {\n throw new Error(\n \"Document sync response content-key bundle document mismatch\",\n );\n }\n if (\n !Number.isInteger(bundle.contentKeyEpoch) ||\n bundle.contentKeyEpoch <= 0\n ) {\n throw new Error(\n \"Document sync response content-key bundle epoch mismatch\",\n );\n }\n\n // The current epoch travels only as contentKeyBundle; the array carries\n // each older epoch once.\n if (bundleByEpoch.has(bundle.contentKeyEpoch)) {\n throw new Error(\"Document sync response repeats a content-key epoch\");\n }\n bundleByEpoch.set(bundle.contentKeyEpoch, bundle);\n }\n\n return bundleByEpoch;\n}\n\nasync function persistedDocumentSyncStateFromResponseInternal(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n options: {\n resolveWriterPublicKey: DocumentWriterPublicKeyResolver;\n },\n): Promise<PersistedDocumentSyncState> {\n if (response.documentId !== plan.documentId) {\n throw new Error(\"Document sync response document id mismatch\");\n }\n const contentKeyBundlesByEpoch = documentSyncContentKeyBundlesByEpoch(\n plan,\n response,\n );\n if (\n serializeCanonical(response.documentKekTargets, \"KEK targets\") !==\n serializeCanonical(plan.documentKekTargets, \"KEK targets\")\n ) {\n throw new Error(\"Document sync response KEK target mismatch\");\n }\n assertAcceptedOutgoingUpdateIdsMatchPlan(plan, response);\n assertDocumentSyncCommitCheckpointMatchesPlan(plan, response);\n assertDocumentSyncAccessEpochsNotInFuture(plan, response);\n\n await Promise.all(\n response.updates.map((update) =>\n assertDocumentSyncResponseUpdateMatchesPlan({\n contentKeyBundlesByEpoch,\n plan,\n resolveWriterPublicKey: options.resolveWriterPublicKey,\n update,\n }),\n ),\n );\n\n return serializedPersistedDocumentState({\n contentKeyBundle: response.contentKeyBundle,\n documentId: plan.documentId,\n documentKekTargets: response.documentKekTargets,\n documentManifestBundle: plan.documentManifest,\n });\n}\n\nexport async function persistedDocumentSyncStateFromResponse(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n options: {\n resolveWriterPublicKey: DocumentWriterPublicKeyResolver;\n },\n): Promise<PersistedDocumentSyncState> {\n try {\n return await persistedDocumentSyncStateFromResponseInternal(\n plan,\n response,\n options,\n );\n } catch (error) {\n if (error instanceof DocumentSyncResponseUpdateContentKeyError) throw error;\n throwKeyingVerificationShapeFailure(error);\n }\n}\n\nexport function isRetryableDocumentSyncConflict(\n failure: DocumentSyncSubmitFailure,\n): boolean {\n return (\n failure.status === 409 &&\n failure.code === DOCUMENT_SYNC_ERROR_CODES.stateStale\n );\n}\n\n// The wipe gate is deliberately strict — coded 404s only, which is the right\n// failure mode for a destructive action. A bare 404 proves nothing about the\n// document: proxy/tunnel error pages, deploy-skew route misses, and\n// container-level lookups all produce one.\nexport function isUpstreamDeletedDocumentSyncFailure(\n failure: DocumentSyncSubmitFailure,\n): boolean {\n return (\n failure.status === 404 && failure.code === DOCUMENT_NOT_FOUND_ERROR_CODE\n );\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"documentPurgeCheckpointPersistence.js","sourceRoot":"","sources":["documentPurgeCheckpointPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACjC,OAAO,EACL,wBAAwB,EACxB,sBAAsB,GACvB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAE,iCAAiC,EAAE,MAAM,oCAAoC,CAAC;AACvF,OAAO,EAAgB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AASpE,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAC/C,OAAgB,EAChB,UAAkB;IAElB,MAAM,eAAe,CAAC,OAAO,EAAE,sBAAsB,CAAC,CAAC;IACvD,MAAM,CAAC,GAAG,CAAC,GAAG,MAAM,iCAAiC,CAAC,OAAO,CAAC;SAC3D,EAAE,CAAC,MAAM,CAAC;QACT,UAAU,EAAE,wBAAwB,CAAC,UAAU;QAC/C,oBAAoB,EAAE,wBAAwB,CAAC,oBAAoB;QACnE,cAAc,EAAE,wBAAwB,CAAC,cAAc;QACvD,cAAc,EAAE,wBAAwB,CAAC,cAAc;KACxD,CAAC;SACD,IAAI,CAAC,wBAAwB,CAAC;SAC9B,KAAK,CAAC,EAAE,CAAC,wBAAwB,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;SAC1D,KAAK,CAAC,CAAC,CAAC,CAAC;IACZ,OAAO,GAAG,IAAI,IAAI,CAAC;AACrB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,yCAAyC,CAC7D,EAAgC,EAChC,UAAmC,EACnC,SAAiB;IAEjB,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,EAAE;SACtB,MAAM,CAAC;QACN,oBAAoB,EAAE,wBAAwB,CAAC,oBAAoB;QACnE,cAAc,EAAE,wBAAwB,CAAC,cAAc;QACvD,cAAc,EAAE,wBAAwB,CAAC,cAAc;KACxD,CAAC;SACD,IAAI,CAAC,wBAAwB,CAAC;SAC9B,KAAK,CAAC,EAAE,CAAC,wBAAwB,CAAC,UAAU,EAAE,UAAU,CAAC,UAAU,CAAC,CAAC;SACrE,KAAK,CAAC,CAAC,CAAC,CAAC;IACZ,IAAI,MAAM,EAAE,CAAC;QACX,IACE,MAAM,CAAC,oBAAoB,KAAK,UAAU,CAAC,oBAAoB;YAC/D,MAAM,CAAC,cAAc,KAAK,UAAU,CAAC,cAAc;YACnD,MAAM,CAAC,cAAc,KAAK,UAAU,CAAC,cAAc,EACnD,CAAC;YACD,MAAM,IAAI,uBAAuB,CAC/B,cAAc,EACd,sEAAsE,CACvE,CAAC;QACJ,CAAC;QACD,OAAO;IACT,CAAC;IACD,MAAM,EAAE;SACL,MAAM,CAAC,wBAAwB,CAAC;SAChC,MAAM,CAAC,EAAE,GAAG,UAAU,EAAE,SAAS,EAAE,CAAC;SACpC,GAAG,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { eq } from \"drizzle-orm\";\nimport {\n documentPurgeCheckpoints,\n keyingCheckpointTables,\n} from \"../sqlite/schema\";\nimport type { ClientSQLiteTransactionScope } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\n\nexport interface DocumentPurgeCheckpoint {\n readonly documentId: string;\n readonly documentManifestHash: string;\n readonly organizationId: string;\n readonly purgeEventHash: string;\n}\n\nexport async function loadDocumentPurgeCheckpoint(\n execSql: ExecSql,\n documentId: string,\n): Promise<DocumentPurgeCheckpoint | null> {\n await ensureSqlTables(execSql, keyingCheckpointTables);\n const [row] = await getClientSQLitePersistenceRuntime(execSql)\n .db.select({\n documentId: documentPurgeCheckpoints.documentId,\n documentManifestHash: documentPurgeCheckpoints.documentManifestHash,\n organizationId: documentPurgeCheckpoints.organizationId,\n purgeEventHash: documentPurgeCheckpoints.purgeEventHash,\n })\n .from(documentPurgeCheckpoints)\n .where(eq(documentPurgeCheckpoints.documentId, documentId))\n .limit(1);\n return row ?? null;\n}\n\nexport async function storeDocumentPurgeCheckpointInTransaction(\n tx: ClientSQLiteTransactionScope,\n checkpoint: DocumentPurgeCheckpoint,\n updatedAt: string,\n): Promise<void> {\n const [stored] = await tx\n .select({\n documentManifestHash: documentPurgeCheckpoints.documentManifestHash,\n organizationId: documentPurgeCheckpoints.organizationId,\n purgeEventHash: documentPurgeCheckpoints.purgeEventHash,\n })\n .from(documentPurgeCheckpoints)\n .where(eq(documentPurgeCheckpoints.documentId, checkpoint.documentId))\n .limit(1);\n if (stored) {\n if (\n stored.documentManifestHash !== checkpoint.documentManifestHash ||\n stored.organizationId !== checkpoint.organizationId ||\n stored.purgeEventHash !== checkpoint.purgeEventHash\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"Document purge checkpoint conflicts with the verified terminal event\",\n );\n }\n return;\n }\n await tx\n .insert(documentPurgeCheckpoints)\n .values({ ...checkpoint, updatedAt })\n .run();\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"keyingCheckpointAdvancePersistence.js","sourceRoot":"","sources":["keyingCheckpointAdvancePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,uBAAuB,EAKvB,mCAAmC,EACnC,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAEL,iCAAiC,GAClC,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAgB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACpE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;IACT,CAAC;IACD,MAAM,OAAO,CAAC,WAAW,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n type AnyVerifiedPrincipalPolicy,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedPrincipalPolicy,\n type VerifiedPrincipalPolicyCurrent,\n type VerifiedPrincipalPolicySelection,\n verifyAccessManifestLocalCheckpoint,\n verifyPrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport {\n keyingCheckpointTables,\n principalPolicyTables,\n} from \"../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport { verifiedManifestBundleTables } from \"../sqlite/verifiedManifestBundleSchema\";\nimport {\n type DocumentPurgeCheckpoint,\n storeDocumentPurgeCheckpointInTransaction,\n} from \"./documentPurgeCheckpointPersistence\";\nimport { validateAccessManifestCheckpointEvidence } from \"./keyingCheckpointEvidence\";\nimport {\n accessManifestObjectKey,\n loadStoredAccessManifestCheckpoint,\n loadStoredPrincipalPolicyCheckpoint,\n principalPolicyKey,\n upsertAccessManifestCheckpointInTransaction,\n upsertPrincipalPolicyCheckpointInTransaction,\n} from \"./keyingCheckpointPersistence\";\nimport { validatePrincipalAuthorizationCheckpoints } from \"./principalAuthorizationCheckpoints\";\nimport { assertContainerNotRetired } from \"./principalGrantRetirementPersistence\";\nimport {\n assertPrincipalPolicyBundleStoredInTransaction,\n writePrincipalPolicyBundleInTransaction,\n} from \"./principalPolicyPersistence\";\nimport {\n type VerifiedManifestBundle,\n type VerifiedManifestBundleRow,\n verifiedManifestBundleRows,\n writeVerifiedManifestBundlesInTransaction,\n} from \"./verifiedManifestBundlePersistence\";\nimport { assertBundleMatchesVerifiedPolicy } from \"./verifiedPrincipalPolicyBundle\";\n\nexport interface AccessManifestCheckpointAdvance {\n readonly head: VerifiedAccessManifestCheckpointEvidence;\n readonly predecessors: readonly VerifiedAccessManifestCheckpointEvidence[];\n}\n\ntype CheckpointPolicy =\n | AnyVerifiedPrincipalPolicy\n | VerifiedPrincipalPolicyCurrent;\n\ninterface KeyingCheckpointValidationInput {\n readonly access: readonly AccessManifestCheckpointAdvance[];\n readonly execSql: ExecSql;\n readonly policies: readonly CheckpointPolicy[];\n readonly authorizationPolicies?:\n | readonly VerifiedPrincipalPolicySelection[]\n | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n /**\n * Bundles this projection verified. They are stored for later citation in\n * the same transaction, so they commit only with the batch they verified.\n */\n readonly verifiedBundles?: readonly VerifiedManifestBundle[] | undefined;\n}\n\ninterface VerifiedPrincipalPolicyBundleEntry {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n}\n\ninterface PendingAccessCheckpoint {\n readonly checkpoint: AccessManifestCheckpoint;\n}\n\nfunction validateAccessAdvance(\n advance: AccessManifestCheckpointAdvance,\n localCheckpoint: AccessManifestCheckpoint | null,\n): PendingAccessCheckpoint {\n const current = {\n ...advance.head.checkpoint,\n previousManifestHash: advance.head.manifest.previousManifestHash,\n };\n const predecessors = [...advance.predecessors].sort(\n (left, right) => left.checkpoint.epoch - right.checkpoint.epoch,\n );\n\n if (localCheckpoint && current.epoch <= localCheckpoint.epoch) {\n verifyAccessManifestLocalCheckpoint({\n current,\n localCheckpoint,\n checkpointPredecessors: undefined,\n });\n }\n\n validateAccessManifestCheckpointEvidence({\n head: advance.head,\n predecessors,\n localCheckpoint,\n });\n\n verifyAccessManifestLocalCheckpoint({\n current,\n localCheckpoint,\n checkpointPredecessors: predecessors.filter(\n (manifest) =>\n localCheckpoint !== null &&\n manifest.checkpoint.epoch > localCheckpoint.epoch &&\n manifest.checkpoint.epoch < current.epoch,\n ),\n });\n\n return {\n checkpoint: advance.head.checkpoint,\n };\n}\n\nasync function validateAccessAdvances(\n tx: ClientSQLiteTransactionScope,\n advances: readonly AccessManifestCheckpointAdvance[],\n): Promise<Map<string, PendingAccessCheckpoint>> {\n const pending = new Map<string, PendingAccessCheckpoint>();\n\n for (const advance of advances) {\n await assertContainerNotRetired(tx, advance.head.checkpoint);\n const key = accessManifestObjectKey(advance.head.checkpoint);\n if (pending.has(key)) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `projection declares multiple access checkpoint heads for ${key}`,\n );\n }\n const localCheckpoint = await loadStoredAccessManifestCheckpoint(\n tx,\n advance.head.checkpoint,\n );\n pending.set(key, validateAccessAdvance(advance, localCheckpoint));\n }\n\n return pending;\n}\n\nfunction extendsObservedPolicy(\n head: CheckpointPolicy,\n candidate: CheckpointPolicy,\n): boolean {\n const history =\n \"retainedHistory\" in head ? head.retainedHistory : head.history;\n return (\n history?.some(\n ({ state }) =>\n state.principalType === candidate.principalType &&\n state.principalId === candidate.principalId &&\n state.version === candidate.version &&\n state.stateHash === candidate.stateHash,\n ) ?? false\n );\n}\n\nasync function validatePolicyAdvances(\n tx: ClientSQLiteTransactionScope,\n policies: readonly CheckpointPolicy[],\n): Promise<Map<string, CheckpointPolicy>> {\n const policiesByPrincipal = new Map<string, CheckpointPolicy[]>();\n for (const policy of policies) {\n const key = principalPolicyKey(policy);\n const candidates = policiesByPrincipal.get(key) ?? [];\n candidates.push(policy);\n policiesByPrincipal.set(key, candidates);\n }\n\n const pending = new Map<string, CheckpointPolicy>();\n for (const key of [...policiesByPrincipal.keys()].sort()) {\n const candidates = policiesByPrincipal.get(key) ?? [];\n const maxVersion = Math.max(...candidates.map((policy) => policy.version));\n const heads = candidates.filter((policy) => policy.version === maxVersion);\n const head = heads[0];\n if (!head) {\n continue;\n }\n if (heads.some((candidate) => candidate.stateHash !== head.stateHash)) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `principal policy declares conflicting heads for ${key}`,\n );\n }\n for (const candidate of candidates) {\n if (candidate.version === head.version) {\n continue;\n }\n if (!extendsObservedPolicy(head, candidate)) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n `principal policy head does not extend observed state for ${key}`,\n );\n }\n }\n\n const localCheckpoint = await loadStoredPrincipalPolicyCheckpoint(tx, head);\n verifyPrincipalPolicyCheckpoint({\n chain:\n \"retainedHistory\" in head ? head.retainedHistory : (head.history ?? []),\n currentState: head.state,\n localCheckpoint,\n });\n pending.set(key, head);\n }\n\n return pending;\n}\n\nasync function writeAccessCheckpoints(\n tx: ClientSQLiteTransactionScope,\n pending: ReadonlyMap<string, PendingAccessCheckpoint>,\n updatedAt: string,\n): Promise<void> {\n for (const { checkpoint } of pending.values()) {\n await upsertAccessManifestCheckpointInTransaction(\n tx,\n checkpoint,\n updatedAt,\n );\n }\n}\n\nasync function writePolicyCheckpoints(\n tx: ClientSQLiteTransactionScope,\n pending: ReadonlyMap<string, CheckpointPolicy>,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n for (const policy of pending.values()) {\n await upsertPrincipalPolicyCheckpointInTransaction(\n tx,\n policy.checkpoint,\n updatedAt,\n organizationId,\n );\n }\n}\n\n/**\n * Digests the verified bundles and ensures every table the batch touches,\n * all before its transaction begins.\n */\nasync function prepareKeyingCheckpointBatch(\n input: KeyingCheckpointValidationInput,\n): Promise<VerifiedManifestBundleRow[]> {\n const bundleRows = await verifiedManifestBundleRows(\n input.verifiedBundles ?? [],\n );\n await ensureSqlTables(input.execSql, [\n ...(input.policies.length > 0 ||\n (input.authorizationPolicies?.length ?? 0) > 0\n ? principalPolicyTables\n : []),\n ...keyingCheckpointTables,\n ...(bundleRows.length > 0 ? verifiedManifestBundleTables : []),\n ]);\n return bundleRows;\n}\n\n/**\n * Re-checks verified candidates against durable pins without advancing them.\n * Only the verified bundles' citation rows are written.\n */\nexport async function validateKeyingCheckpointsAtomically(\n input: KeyingCheckpointValidationInput,\n): Promise<void> {\n const bundleRows = await prepareKeyingCheckpointBatch(input);\n const verifiedAt = new Date().toISOString();\n const validate = async (tx: ClientSQLiteTransactionScope) => {\n await validateAccessAdvances(tx, input.access);\n await validatePolicyAdvances(tx, input.policies);\n await validatePrincipalAuthorizationCheckpoints(\n tx,\n input.authorizationPolicies ?? [],\n );\n await writeVerifiedManifestBundlesInTransaction(tx, bundleRows, verifiedAt);\n };\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n if (input.stillCurrent) {\n await runtime.guardedTransaction(validate, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(validate, { behavior: \"immediate\" });\n}\n\n/**\n * Re-check every verified projection candidate against the latest durable pins\n * and advance the complete batch atomically. Signature verification and remote\n * fetching happen before this short transaction; only checkpoint comparison\n * and persistence, with the batch's verified bundles, are serialized here.\n */\nexport async function advanceKeyingCheckpointsAtomically(\n input: KeyingCheckpointValidationInput & {\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly organizationId?: string | undefined;\n },\n): Promise<void> {\n const bundleRows = await prepareKeyingCheckpointBatch(input);\n const updatedAt = new Date().toISOString();\n\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const advance = async (tx: ClientSQLiteTransactionScope) => {\n const access = await validateAccessAdvances(tx, input.access);\n const policies = await validatePolicyAdvances(tx, input.policies);\n await validatePrincipalAuthorizationCheckpoints(\n tx,\n input.authorizationPolicies ?? [],\n );\n\n await writeAccessCheckpoints(tx, access, updatedAt);\n await writePolicyCheckpoints(tx, policies, updatedAt, input.organizationId);\n if (input.documentPurgeCheckpoint) {\n await storeDocumentPurgeCheckpointInTransaction(\n tx,\n input.documentPurgeCheckpoint,\n updatedAt,\n );\n }\n await writeVerifiedManifestBundlesInTransaction(tx, bundleRows, updatedAt);\n };\n if (input.stillCurrent) {\n await runtime.guardedTransaction(advance, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(advance, { behavior: \"immediate\" });\n}\n\n/**\n * Persists each verified full policy bundle together with its durable head.\n * This prevents a crash or bundle-write failure from leaving a checkpoint\n * without the exact same-head payload and member-envelope evidence.\n */\nexport async function persistVerifiedPrincipalPolicyBundlesAtomically(input: {\n readonly entries: readonly VerifiedPrincipalPolicyBundleEntry[];\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly updatedAt: string;\n}): Promise<void> {\n const seen = new Set<string>();\n for (const entry of input.entries) {\n const key = principalPolicyKey(entry.policy);\n if (seen.has(key)) {\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n `verified policy bundle batch repeats ${key}`,\n );\n }\n seen.add(key);\n }\n await Promise.all(\n input.entries.map((entry) => assertBundleMatchesVerifiedPolicy(entry)),\n );\n await ensureSqlTables(input.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const persist = async (tx: ClientSQLiteTransactionScope) => {\n const policies = await validatePolicyAdvances(\n tx,\n input.entries.map((entry) => entry.policy),\n );\n for (const entry of input.entries) {\n await writePrincipalPolicyBundleInTransaction(\n tx,\n entry.bundle,\n input.updatedAt,\n input.organizationId,\n );\n await assertPrincipalPolicyBundleStoredInTransaction(tx, entry.bundle);\n }\n await writePolicyCheckpoints(\n tx,\n policies,\n input.updatedAt,\n input.organizationId,\n );\n for (const policy of policies.values()) {\n const checkpoint = await loadStoredPrincipalPolicyCheckpoint(tx, policy);\n if (\n !checkpoint ||\n checkpoint.version !== policy.version ||\n checkpoint.stateHash !== policy.stateHash\n ) {\n throw new Error(\n \"Verified principal policy checkpoint was not persisted\",\n );\n }\n }\n };\n if (input.stillCurrent) {\n await runtime.guardedTransaction(persist, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(persist, { behavior: \"immediate\" });\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"keyingCheckpointPersistence.js","sour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{\n AccessManifestCheckpoint,\n AccessObjectKind,\n ManagedPrincipalKind,\n PrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { and, eq } from \"drizzle-orm\";\nimport {\n accessManifestCheckpoints,\n keyingCheckpointTables,\n principalPolicyCheckpoints,\n} from \"../sqlite/schema\";\nimport {\n type ClientSQLiteDatabase,\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport { recordPrincipalPolicyOrganizationInTransaction } from \"./principalPolicyOrganizationPersistence\";\n\ntype CheckpointHandle = ClientSQLiteDatabase | ClientSQLiteTransactionScope;\n\ntype AccessManifestCheckpointIdentity = Pick<\n AccessManifestCheckpoint,\n \"objectKind\" | \"organizationId\" | \"objectId\"\n>;\n\ntype PrincipalPolicyCheckpointIdentity = Pick<\n PrincipalPolicyCheckpoint,\n \"principalType\" | \"principalId\"\n>;\n\n/** One key format per checkpoint identity, shared by every batch validator. */\nexport function accessManifestObjectKey(\n identity: AccessManifestCheckpointIdentity,\n): string {\n return JSON.stringify([\n identity.objectKind,\n identity.organizationId,\n identity.objectId,\n ]);\n}\n\nexport function principalPolicyKey(\n identity: PrincipalPolicyCheckpointIdentity,\n): string {\n return JSON.stringify([identity.principalType, identity.principalId]);\n}\n\nasync function loadAccessManifestCheckpointRow(\n handle: CheckpointHandle,\n identity: AccessManifestCheckpointIdentity,\n): Promise<Pick<AccessManifestCheckpoint, \"epoch\" | \"manifestHash\"> | null> {\n const rows = await handle\n .select({\n epoch: accessManifestCheckpoints.epoch,\n manifestHash: accessManifestCheckpoints.manifestHash,\n })\n .from(accessManifestCheckpoints)\n .where(\n and(\n eq(accessManifestCheckpoints.objectKind, identity.objectKind),\n eq(accessManifestCheckpoints.organizationId, identity.organizationId),\n eq(accessManifestCheckpoints.objectId, identity.objectId),\n ),\n )\n .limit(1);\n return rows[0] ?? null;\n}\n\nasync function loadPrincipalPolicyCheckpointRow(\n handle: CheckpointHandle,\n identity: PrincipalPolicyCheckpointIdentity,\n): Promise<Pick<PrincipalPolicyCheckpoint, \"version\" | \"stateHash\"> | null> {\n const rows = await handle\n .select({\n version: principalPolicyCheckpoints.version,\n stateHash: principalPolicyCheckpoints.stateHash,\n })\n .from(principalPolicyCheckpoints)\n .where(\n and(\n eq(principalPolicyCheckpoints.principalType, identity.principalType),\n eq(principalPolicyCheckpoints.principalId, identity.principalId),\n ),\n )\n .limit(1);\n return rows[0] ?? null;\n}\n\n/**\n * A loaded checkpoint row merged back with the identity it was looked up by —\n * the full checkpoint shape every comparison consumes.\n */\nexport async function loadStoredAccessManifestCheckpoint(\n handle: CheckpointHandle,\n checkpoint: AccessManifestCheckpoint,\n): Promise<AccessManifestCheckpoint | null> {\n const row = await loadAccessManifestCheckpointRow(handle, checkpoint);\n return row ? { ...checkpoint, ...row } : null;\n}\n\nexport async function loadStoredPrincipalPolicyCheckpoint(\n handle: CheckpointHandle,\n identity: PrincipalPolicyCheckpointIdentity,\n): Promise<PrincipalPolicyCheckpoint | null> {\n const row = await loadPrincipalPolicyCheckpointRow(handle, identity);\n return row\n ? {\n principalType: identity.principalType,\n principalId: identity.principalId,\n ...row,\n }\n : null;\n}\n\nexport async function upsertAccessManifestCheckpointInTransaction(\n tx: ClientSQLiteTransactionScope,\n checkpoint: AccessManifestCheckpoint,\n updatedAt: string,\n): Promise<void> {\n const row = { ...checkpoint, updatedAt };\n await tx\n .insert(accessManifestCheckpoints)\n .values(row)\n .onConflictDoUpdate({\n target: [\n accessManifestCheckpoints.objectKind,\n accessManifestCheckpoints.organizationId,\n accessManifestCheckpoints.objectId,\n ],\n set: row,\n })\n .run();\n}\n\nexport async function upsertPrincipalPolicyCheckpointInTransaction(\n tx: ClientSQLiteTransactionScope,\n checkpoint: PrincipalPolicyCheckpoint,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n await recordPrincipalPolicyOrganizationInTransaction(tx, {\n organizationId,\n principalId: checkpoint.principalId,\n principalType: checkpoint.principalType,\n });\n const row = { ...checkpoint, updatedAt };\n await tx\n .insert(principalPolicyCheckpoints)\n .values(row)\n .onConflictDoUpdate({\n target: [\n principalPolicyCheckpoints.principalType,\n principalPolicyCheckpoints.principalId,\n ],\n set: row,\n })\n .run();\n}\n\n// Lazily create the checkpoint tables on first access. Every load/save below\n// calls this, so the tables exist on demand; it is intentionally module-private\n// (no caller outside this file needs it, and exporting it tripped knip).\nasync function ensureKeyingCheckpointTables(execSql: ExecSql): Promise<void> {\n await ensureSqlTables(execSql, keyingCheckpointTables);\n}\n\nexport async function loadAccessManifestCheckpoint(\n execSql: ExecSql,\n objectKind: AccessObjectKind,\n organizationId: string,\n objectId: string,\n): Promise<AccessManifestCheckpoint | null> {\n await ensureKeyingCheckpointTables(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const row = await loadAccessManifestCheckpointRow(db, {\n objectKind,\n organizationId,\n objectId,\n });\n\n return row ? { objectKind, objectId, organizationId, ...row } : null;\n}\n\nexport async function loadPrincipalPolicyCheckpoint(\n execSql: ExecSql,\n principalType: ManagedPrincipalKind,\n principalId: string,\n): Promise<PrincipalPolicyCheckpoint | null> {\n await ensureKeyingCheckpointTables(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const row = await loadPrincipalPolicyCheckpointRow(db, {\n principalType,\n principalId,\n });\n\n return row ? { principalType, principalId, ...row } : null;\n}\n/**\n * The shared shape/ownership guard every checkpoint comparison runs before\n * trusting a durable pin: the pin must belong to the compared principal and\n * carry a well-formed version and hash.\n */\nexport function assertPrincipalPolicyCheckpointShape(\n checkpoint: PrincipalPolicyCheckpoint,\n head: PrincipalPolicyCheckpointIdentity,\n): void {\n if (\n checkpoint.principalType !== head.principalType ||\n checkpoint.principalId !== head.principalId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"principal policy checkpoint belongs to another principal\",\n );\n }\n if (\n !Number.isInteger(checkpoint.version) ||\n checkpoint.version < 1 ||\n checkpoint.stateHash.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy checkpoint is malformed\",\n );\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"locallyAcknowledgedCheckpointPersistence.js","sourceRoot":"","sources":["locallyAcknowledgedCheckpointPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,oCAAoC,EACpC,uBAAuB,EAGvB,mCAAmC,EACnC,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAEL,iCAAiC,GAClC,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAgB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,EACL,uBAAuB,EACvB,kCAAkC,EAClC,mCAAmC,EACnC,kBAAkB,EAClB,2CAA2C,EAC3C,4CAA4C,GAC7C,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAEL,yBAAyB,EACzB,8BAA8B,GAC/B,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EACL,wCAAwC,EACxC,uCAAuC,GACxC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,iCAAiC,EAAE,MAAM,iCAAiC,CAAC;AAOpF,MAAM,UAAU,iCAAiC,CAAC,IAGjD;IACC,OAAO;QACL,UAAU,EAAE,oCAAoC,CAAC;YAC/C,QAAQ,EAAE,IAAI,CAAC,QAAQ;YACvB,YAAY,EAAE,IAAI,CAAC,YAAY;SAChC,CAAC;QACF,oBAAoB,EAAE,IAAI,CAAC,QAAQ,CAAC,oBAAoB;KACzD,CAAC;AACJ,CAAC;AAED,SAAS,wBAAwB,CAC/B,IAA2C,EAC3C,eAAgD;IAEhD,IAAI,CAAC,eAAe,EAAE,CAAC;QACrB,IAAI,IAAI,CA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AAC,SAAS,EACf,KAAK,CAAC,cAAc,CACrB,CAAC;YACJ,CAAC;QACH,CAAC;QACD,KAAK,MAAM,EAAE,MAAM,EAAE,IAAI,KAAK,CAAC,OAAO,EAAE,CAAC;YACvC,MAAM,4CAA4C,CAChD,EAAE,EACF,MAAM,CAAC,UAAU,EACjB,KAAK,CAAC,SAAS,EACf,KAAK,CAAC,cAAc,CACrB,CAAC;QACJ,CAAC;IACH,CAAC,CAAC;IACF,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;QACvB,MAAM,OAAO,CAAC,kBAAkB,CAAC,KAAK,EAAE,KAAK,CAAC,YAAY,EAAE;YAC1D,QAAQ,EAAE,WAAW;SACtB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IACD,MAAM,OAAO,CAAC,WAAW,CAAC,KAAK,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;AAC9D,CAAC;AAED,oFAAoF;AACpF,MAAM,UAAU,gDAAgD,CAAC,KAMhE;IACC,OAAO,uCAAuC,CAAC;QAC7C,GAAG,KAAK;QACR,SAAS,EAAE,SAAS;KACrB,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,+CAA+C,CAC7D,KAKC;IAED,OAAO,gDAAgD,CAAC;QACtD,OAAO,EAAE,CAAC,KAAK,CAAC;QAChB,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,SAAS,EAAE,KAAK,CAAC,SAAS;KAC3B,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,+CAA+C,CAAC,KAS/D;IACC,OAAO,uCAAuC,CAAC;QAC7C,GAAG,KAAK;QACR,SAAS,EAAE,SAAS;KACrB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n type AccessManifest,\n type AccessManifestCheckpoint,\n accessManifestCheckpointFromManifest,\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type VerifiedPrincipalPolicy,\n verifyAccessManifestLocalCheckpoint,\n verifyPrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport {\n keyingCheckpointTables,\n principalPolicyTables,\n} from \"../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport {\n accessManifestObjectKey,\n loadStoredAccessManifestCheckpoint,\n loadStoredPrincipalPolicyCheckpoint,\n principalPolicyKey,\n upsertAccessManifestCheckpointInTransaction,\n upsertPrincipalPolicyCheckpointInTransaction,\n} from \"./keyingCheckpointPersistence\";\nimport {\n type AcknowledgedPrincipalGrantRetirements,\n assertContainerNotRetired,\n storePrincipalGrantRetirements,\n} from \"./principalGrantRetirementPersistence\";\nimport {\n retainPrincipalPolicyBundleInTransaction,\n writePrincipalPolicyBundleInTransaction,\n} from \"./principalPolicyPersistence\";\nimport { assertBundleMatchesVerifiedPolicy } from \"./verifiedPrincipalPolicyBundle\";\n\nexport interface LocallyAcknowledgedAccessManifestHead {\n readonly checkpoint: AccessManifestCheckpoint;\n readonly previousManifestHash: string | null;\n}\n\nexport function locallyAuthoredAccessManifestHead(plan: {\n readonly manifest: AccessManifest;\n readonly manifestHash: string;\n}): LocallyAcknowledgedAccessManifestHead {\n return {\n checkpoint: accessManifestCheckpointFromManifest({\n manifest: plan.manifest,\n manifestHash: plan.manifestHash,\n }),\n previousManifestHash: plan.manifest.previousManifestHash,\n };\n}\n\nfunction validateAcknowledgedHead(\n head: LocallyAcknowledgedAccessManifestHead,\n localCheckpoint: AccessManifestCheckpoint | null,\n): void {\n if (!localCheckpoint) {\n if (head.checkpoint.epoch !== 1 || head.previousManifestHash !== null) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"locally acknowledged access manifest does not begin at epoch 1\",\n );\n }\n return;\n }\n\n verifyAccessManifestLocalCheckpoint({\n checkpointPredecessors: [],\n current: {\n ...head.checkpoint,\n previousManifestHash: head.previousManifestHash,\n },\n localCheckpoint,\n });\n}\n\nasync function validateAcknowledgedHeads(\n tx: ClientSQLiteTransactionScope,\n heads: readonly LocallyAcknowledgedAccessManifestHead[],\n): Promise<Map<string, AccessManifestCheckpoint>> {\n const pending = new Map<string, AccessManifestCheckpoint>();\n for (const head of heads) {\n await assertContainerNotRetired(tx, head.checkpoint);\n const key = accessManifestObjectKey(head.checkpoint);\n if (pending.has(key)) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `locally acknowledged batch contains multiple heads for ${key}`,\n );\n }\n validateAcknowledgedHead(\n head,\n await loadStoredAccessManifestCheckpoint(tx, head.checkpoint),\n );\n pending.set(key, head.checkpoint);\n }\n return pending;\n}\n\nasync function writeAcknowledgedHeads(\n tx: ClientSQLiteTransactionScope,\n pending: ReadonlyMap<string, AccessManifestCheckpoint>,\n updatedAt: string,\n): Promise<void> {\n for (const checkpoint of pending.values()) {\n await upsertAccessManifestCheckpointInTransaction(\n tx,\n checkpoint,\n updatedAt,\n );\n }\n}\n\n/**\n * Commits only heads authored and signed by this client after an exact remote\n * acknowledgement check. Every non-initial head must directly extend the\n * latest durable pin; arbitrary remote projections must use the verified\n * projection checkpoint path instead.\n */\nexport async function advanceLocallyAcknowledgedAccessManifestHeadsAtomically(input: {\n readonly execSql: ExecSql;\n readonly heads: readonly LocallyAcknowledgedAccessManifestHead[];\n /** Optional optimistic read dependencies, checked inside the write transaction. */\n readonly expectedAccessManifestCheckpoints?: readonly AccessManifestCheckpoint[];\n readonly expectedPrincipalPolicyCheckpoints?: readonly PrincipalPolicyCheckpoint[];\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<boolean> {\n await ensureSqlTables(input.execSql, keyingCheckpointTables);\n const updatedAt = new Date().toISOString();\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const acknowledge = async (tx: ClientSQLiteTransactionScope) => {\n for (const expected of input.expectedAccessManifestCheckpoints ?? []) {\n const current = await loadStoredAccessManifestCheckpoint(tx, expected);\n if (\n current?.epoch !== expected.epoch ||\n current.manifestHash !== expected.manifestHash\n ) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"A re-citation container checkpoint changed before acknowledgement\",\n );\n }\n }\n for (const expected of input.expectedPrincipalPolicyCheckpoints ?? []) {\n const current = await loadStoredPrincipalPolicyCheckpoint(tx, expected);\n if (\n current?.version !== expected.version ||\n current.stateHash !== expected.stateHash\n ) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"A re-citation principal policy checkpoint changed before acknowledgement\",\n );\n }\n }\n const pending = await validateAcknowledgedHeads(tx, input.heads);\n await writeAcknowledgedHeads(tx, pending, updatedAt);\n };\n if (input.stillCurrent) {\n return (\n await runtime.guardedTransaction(acknowledge, input.stillCurrent, {\n behavior: \"immediate\",\n })\n ).committed;\n }\n await runtime.transaction(acknowledge, { behavior: \"immediate\" });\n return true;\n}\n\nfunction validateAcknowledgedPolicy(\n policy: VerifiedPrincipalPolicy,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): void {\n verifyPrincipalPolicyCheckpoint({\n chain: policy.history ?? [],\n currentState: policy.state,\n localCheckpoint: checkpoint,\n });\n if (!checkpoint && policy.version !== 1) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"locally acknowledged principal policy does not begin at version 1\",\n );\n }\n if (checkpoint && policy.version > checkpoint.version + 1) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"locally acknowledged principal policy does not directly extend the durable checkpoint\",\n );\n }\n}\n\ninterface LocallyAcknowledgedPrincipalPolicyBundle {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n}\n\nfunction assertUniqueAcknowledgedPolicies(\n entries: readonly LocallyAcknowledgedPrincipalPolicyBundle[],\n): void {\n const seen = new Set<string>();\n for (const { policy } of entries) {\n const key = principalPolicyKey(policy);\n if (seen.has(key)) {\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n `locally acknowledged policy batch repeats ${key}`,\n );\n }\n seen.add(key);\n }\n}\n\nasync function storeAcknowledgedPrincipalPolicyBundles(input: {\n readonly retiredContainers?:\n | AcknowledgedPrincipalGrantRetirements\n | undefined;\n readonly entries: readonly LocallyAcknowledgedPrincipalPolicyBundle[];\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n readonly placement: \"current\" | \"history\";\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly updatedAt: string;\n}): Promise<void> {\n assertUniqueAcknowledgedPolicies(input.entries);\n await Promise.all(\n input.entries.map((entry) => assertBundleMatchesVerifiedPolicy(entry)),\n );\n await ensureSqlTables(input.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const store = async (tx: ClientSQLiteTransactionScope) => {\n for (const { policy } of input.entries) {\n validateAcknowledgedPolicy(\n policy,\n await loadStoredPrincipalPolicyCheckpoint(tx, policy),\n );\n }\n if (input.retiredContainers)\n await storePrincipalGrantRetirements(\n tx,\n input.retiredContainers,\n input.entries.map(({ policy }) => policy),\n input.organizationId,\n );\n for (const entry of input.entries) {\n if (input.placement === \"current\") {\n await writePrincipalPolicyBundleInTransaction(\n tx,\n entry.bundle,\n input.updatedAt,\n input.organizationId,\n );\n } else {\n await retainPrincipalPolicyBundleInTransaction(\n tx,\n entry.bundle,\n input.updatedAt,\n input.organizationId,\n );\n }\n }\n for (const { policy } of input.entries) {\n await upsertPrincipalPolicyCheckpointInTransaction(\n tx,\n policy.checkpoint,\n input.updatedAt,\n input.organizationId,\n );\n }\n };\n if (input.stillCurrent) {\n await runtime.guardedTransaction(store, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(store, { behavior: \"immediate\" });\n}\n\n/** Atomically pins and caches exact full policy bundles acknowledged by the API. */\nexport function persistLocallyAcknowledgedPrincipalPolicyBundles(input: {\n readonly entries: readonly LocallyAcknowledgedPrincipalPolicyBundle[];\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly updatedAt: string;\n}): Promise<void> {\n return storeAcknowledgedPrincipalPolicyBundles({\n ...input,\n placement: \"current\",\n });\n}\n\nexport function persistLocallyAcknowledgedPrincipalPolicyBundle(\n input: LocallyAcknowledgedPrincipalPolicyBundle & {\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly updatedAt: string;\n },\n): Promise<void> {\n return persistLocallyAcknowledgedPrincipalPolicyBundles({\n entries: [input],\n execSql: input.execSql,\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n updatedAt: input.updatedAt,\n });\n}\n\nexport function retainLocallyAcknowledgedPrincipalPolicyBundles(input: {\n readonly retiredContainers?:\n | AcknowledgedPrincipalGrantRetirements\n | undefined;\n readonly entries: readonly LocallyAcknowledgedPrincipalPolicyBundle[];\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly updatedAt: string;\n}): Promise<void> {\n return storeAcknowledgedPrincipalPolicyBundles({\n ...input,\n placement: \"history\",\n });\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"organizationReplacementCheckpointPersistence.js","sourceRoot":"","sources":["organizationReplacementCheckpointPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,iCAAiC,EAAE,MAAM,oCAAoC,CAAC;AACvF,OAAO,EAAgB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,EACL,kCAAkC,EAClC,mCAAmC,EACnC,2CAA2C,EAC3C,4CAA4C,GAC7C,M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B,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC;QAC1C,MAAM,UAAU,GAAG,MAAM,kCAAkC,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC;QACtE,IACE,UAAU,EAAE,KAAK,KAAK,CAAC;YACvB,UAAU,CAAC,YAAY,KAAK,IAAI,CAAC,YAAY;YAE7C,MAAM,IAAI,uBAAuB,CAC/B,cAAc,EACd,8DAA8D,CAC/D,CAAC;QACJ,IAAI,CAAC,UAAU;YACb,MAAM,2CAA2C,CAAC,EAAE,EAAE,IAAI,EAAE,SAAS,CAAC,CAAC;QACzE,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;YACnC,MAAM,8CAA8C,CAAC,EAAE,EAAE;gBACvD,WAAW,EAAE,SAAS,CAAC,WAAW;gBAClC,aAAa,EAAE,SAAS,CAAC,aAAa;gBACtC,cAAc;aACf,CAAC,CAAC;YACH,MAAM,MAAM,GAAG,MAAM,mCAAmC,CAAC,EAAE,EAAE,SAAS,CAAC,CAAC;YACxE,IAAI,MAAM,EAAE,OAAO,KAAK,CAAC,IAAI,MAAM,CAAC,SAAS,KAAK,SAAS,CAAC,SAAS;gBACnE,MAAM,IAAI,uBAAuB,CAC/B,cAAc,EACd,gEAAgE,CACjE,CAAC;YACJ,IAAI,CAAC,MAAM;gBACT,MAAM,4CAA4C,CAChD,EAAE,EACF,SAAS,EACT,SAAS,EACT,cAAc,CACf,CAAC;QACN,CAAC;IACH,CAAC,EACD,KAAK,CAAC,YAAY,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,EAClC,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;IACF,OAAO,MAAM,CAAC,SAAS,CAAC;AAC1B,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type VerifiedOrganizationReplacementAuthorization,\n} from \"@tearleads/crypto\";\nimport {\n keyingCheckpointTables,\n principalPolicyTables,\n} from \"../sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport {\n loadStoredAccessManifestCheckpoint,\n loadStoredPrincipalPolicyCheckpoint,\n upsertAccessManifestCheckpointInTransaction,\n upsertPrincipalPolicyCheckpointInTransaction,\n} from \"./keyingCheckpointPersistence\";\nimport { assertContainerNotRetired } from \"./principalGrantRetirementPersistence\";\nimport { recordPrincipalPolicyOrganizationInTransaction } from \"./principalPolicyOrganizationPersistence\";\n\n/**\n * A verified authorization from this identity also authenticates the winning\n * device's genesis. Seed first-sight pins before adopting its IDs; retain any\n * later observations rather than rolling them back to the provisioning epoch.\n */\nexport async function persistOrganizationReplacementCheckpoints(input: {\n readonly authorization: VerifiedOrganizationReplacementAuthorization;\n readonly execSql: ExecSql;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<boolean> {\n const authorization = input.authorization;\n const organizationId = authorization.organizationId;\n const root: AccessManifestCheckpoint = {\n objectKind: \"container\",\n objectId: authorization.rootContainerId,\n organizationId,\n epoch: 1,\n manifestHash: authorization.rootManifestHash,\n };\n const principals: PrincipalPolicyCheckpoint[] = [\n {\n principalType: \"organization\",\n principalId: organizationId,\n version: 1,\n stateHash: authorization.organizationStateHash,\n },\n {\n principalType: \"group\",\n principalId: authorization.adminGroupId,\n version: 1,\n stateHash: authorization.adminGroupStateHash,\n },\n {\n principalType: \"group\",\n principalId: authorization.memberGroupId,\n version: 1,\n stateHash: authorization.memberGroupStateHash,\n },\n ];\n await ensureSqlTables(input.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const result = await runtime.guardedTransaction(\n async (tx) => {\n const updatedAt = new Date().toISOString();\n await assertContainerNotRetired(tx, root);\n const storedRoot = await loadStoredAccessManifestCheckpoint(tx, root);\n if (\n storedRoot?.epoch === 1 &&\n storedRoot.manifestHash !== root.manifestHash\n )\n throw new KeyingVerificationError(\n \"equivocation\",\n \"Replacement root conflicts with its local genesis checkpoint\",\n );\n if (!storedRoot)\n await upsertAccessManifestCheckpointInTransaction(tx, root, updatedAt);\n for (const principal of principals) {\n await recordPrincipalPolicyOrganizationInTransaction(tx, {\n principalId: principal.principalId,\n principalType: principal.principalType,\n organizationId,\n });\n const stored = await loadStoredPrincipalPolicyCheckpoint(tx, principal);\n if (stored?.version === 1 && stored.stateHash !== principal.stateHash)\n throw new KeyingVerificationError(\n \"equivocation\",\n \"Replacement policy conflicts with its local genesis checkpoint\",\n );\n if (!stored)\n await upsertPrincipalPolicyCheckpointInTransaction(\n tx,\n principal,\n updatedAt,\n organizationId,\n );\n }\n },\n input.stillCurrent ?? (() => true),\n { behavior: \"immediate\" },\n );\n return result.committed;\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"principalAuthorizationCheckpoints.js","sourceRoot":"","sources":["principalAuthorizationCheckpoints.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAGvB,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+BAA+B,CAAC;AAEpF,MAAM,OAAO,gDAAiD,SAAQ,uBAAuB;IAC3F;QACE,KAAK,CACH,oBAAoB,EACpB,sEAAsE,CACvE,CAAC;IACJ,CAAC;CACF;AAED,6FAA6F;AAC7F,MAAM,CAAC,KAAK,UAAU,yCAAyC,CAC7D,EAAgC,EAChC,QAGG;IAEH,KAAK,MAAM,MAAM,IAAI,QAAQ,EAAE,CAAC;QAC9B,MAAM,UAAU,GAAG,MAAM,mCAAmC,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC;QACzE,IAAI,CAAC,UAAU;YAAE,SAAS;QAC1B,MAAM,YAAY,GAAG,QAAQ,CAAC,MAAM,CAClC,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,aAAa,KAAK,MAAM,CAAC,aAAa;YAC5C,KAAK,CAAC,WAAW,KAAK,MAAM,CAAC,WAAW;YACxC,KAAK,CAAC,SAAS,KAAK,MAAM,CAAC,SAAS,CACvC,CAAC;QACF,MAAM,KAAK,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC;QACrE,IACE,UAAU,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO;YACnC,CAAC,UAAU,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO;gBAClC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,KAAK,UAAU,CAAC,OAAO,CAAC,CAAC;YAEnE,MAAM,IAAI,gDAAgD,EAAE,CAAC;QAC/D,+BAA+B,CAAC;YAC9B,KAAK;YACL,YAAY,EAAE,MAAM,CAAC,KAAK;YAC1B,eAAe,EAAE,UAAU;SAC5B,CAAC,CAAC;IACL,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type VerifiedPrincipalPolicyCurrent,\n type VerifiedPrincipalPolicySelection,\n verifyPrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport type { ClientSQLiteTransactionScope } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { loadStoredPrincipalPolicyCheckpoint } from \"./keyingCheckpointPersistence\";\n\nexport class PrincipalAuthorizationCheckpointUnavailableError extends KeyingVerificationError {\n constructor() {\n super(\n \"missing_dependency\",\n \"Public authorization cannot connect to the latest durable checkpoint\",\n );\n }\n}\n\n/** Validate public evidence or a verified private ancestry bridge without admitting pins. */\nexport async function validatePrincipalAuthorizationCheckpoints(\n tx: ClientSQLiteTransactionScope,\n policies: readonly (\n | VerifiedPrincipalPolicySelection\n | VerifiedPrincipalPolicyCurrent\n )[],\n): Promise<void> {\n for (const policy of policies) {\n const checkpoint = await loadStoredPrincipalPolicyCheckpoint(tx, policy);\n if (!checkpoint) continue;\n const matchingHead = policies.filter(\n (other) =>\n other.principalType === policy.principalType &&\n other.principalId === policy.principalId &&\n other.stateHash === policy.stateHash,\n );\n const chain = matchingHead.flatMap((other) => other.retainedHistory);\n if (\n checkpoint.version > policy.version ||\n (checkpoint.version < policy.version &&\n !chain.some(({ state }) => state.version === checkpoint.version))\n )\n throw new PrincipalAuthorizationCheckpointUnavailableError();\n verifyPrincipalPolicyCheckpoint({\n chain,\n currentState: policy.state,\n localCheckpoint: checkpoint,\n });\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"principalGrantRetirementPersistence.js","sourceRoot":"","sources":["principalGrantRetirementPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,yBAAyB,EAAE,MAAM,0CAA0C,CAAC;AASrF,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAClD,EAAgC,EAChC,UAAiD,EACjD,QAGG,EACH,cAAkC;IAElC,IACE,CAAC,QAAQ,CAAC,IAAI,CACZ,CAAC,MAAM,EAAE,EAAE,CACT,MAAM,CAAC,WAAW,KAAK,UAAU,CAAC,MAAM,CAAC,WAAW;QACpD,MAAM,CAAC,aAAa,KAAK,UAAU,CAAC,MAAM,CAAC,aAAa;QACxD,MAAM,CAAC,SAAS,KAAK,UAAU,CAAC,MAAM,CAAC,SAAS,CACnD,EACD,CAAC;QACD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,mDAAmD,CACpD,CAAC;IACJ,CAAC;IACD,MAAM,OAAO,GACX,iBAAiB,IAAI,UAAU,CAAC,MAAM;QACpC,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,eAAe;QACnC,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,OAAO,CAAC;IAChC,MAAM,QAAQ,GAAG,OAAO,EAAE,I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,IAAI,CAAC,yBAAyB,CAAC;SAC/B,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,yBAAyB,CAAC,cAAc,EAAE,UAAU,CAAC,cAAc,CAAC,EACvE,EAAE,CAAC,yBAAyB,CAAC,WAAW,EAAE,UAAU,CAAC,QAAQ,CAAC,CAC/D,CACF;SACA,KAAK,CAAC,CAAC,CAAC,CAAC;IACZ,IAAI,OAAO;QACT,MAAM,IAAI,uBAAuB,CAC/B,cAAc,EACd,aAAa,UAAU,CAAC,QAAQ,wCAAwC,CACzE,CAAC;AACN,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type VerifiedPrincipalPolicy,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { and, eq } from \"drizzle-orm\";\nimport { principalGrantRetirements } from \"../sqlite/principalGrantRetirementSchema\";\nimport type { ClientSQLiteTransactionScope } from \"../sqlite/sqlitePersistenceRuntime\";\n\nexport interface AcknowledgedPrincipalGrantRetirements {\n readonly containerIds: readonly string[];\n readonly organizationId: string;\n readonly policy: VerifiedPrincipalPolicy | VerifiedPrincipalPolicyCurrent;\n}\n\nexport async function storePrincipalGrantRetirements(\n tx: ClientSQLiteTransactionScope,\n retirement: AcknowledgedPrincipalGrantRetirements,\n policies: readonly (\n | VerifiedPrincipalPolicy\n | VerifiedPrincipalPolicyCurrent\n )[],\n organizationId: string | undefined,\n): Promise<void> {\n if (\n !policies.some(\n (policy) =>\n policy.principalId === retirement.policy.principalId &&\n policy.principalType === retirement.policy.principalType &&\n policy.stateHash === retirement.policy.stateHash,\n )\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Retirement must accompany its acknowledged policy\",\n );\n }\n const history =\n \"retainedHistory\" in retirement.policy\n ? retirement.policy.retainedHistory\n : retirement.policy.history;\n const previous = history?.find(\n (entry) => entry.state.stateHash === retirement.policy.state.prevStateHash,\n );\n const granted = new Set(\n [...retirement.policy.grants, ...(previous?.grants ?? [])].map(\n (grant) => grant.containerId,\n ),\n );\n if (\n retirement.organizationId !== organizationId ||\n retirement.containerIds.some((id) => !granted.has(id))\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Retirement must match the acknowledged organization and signed grants\",\n );\n }\n for (const containerId of new Set(retirement.containerIds)) {\n await tx\n .insert(principalGrantRetirements)\n .values({\n organizationId: retirement.organizationId,\n containerId,\n principalId: retirement.policy.principalId,\n policyStateHash: retirement.policy.stateHash,\n })\n .onConflictDoNothing()\n .run();\n }\n}\n\nexport async function assertContainerNotRetired(\n tx: ClientSQLiteTransactionScope,\n checkpoint: AccessManifestCheckpoint,\n): Promise<void> {\n if (checkpoint.objectKind !== \"container\") return;\n const [retired] = await tx\n .select({ containerId: principalGrantRetirements.containerId })\n .from(principalGrantRetirements)\n .where(\n and(\n eq(principalGrantRetirements.organizationId, checkpoint.organizationId),\n eq(principalGrantRetirements.containerId, checkpoint.objectId),\n ),\n )\n .limit(1);\n if (retired)\n throw new KeyingVerificationError(\n \"equivocation\",\n `Container ${checkpoint.objectId} was retired during principal rotation`,\n );\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"principalHistoryEvidencePersistence.js","sourceRoot":"","sources":["principalHistoryEvidencePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,uBAAuB,EACvB,kCAAkC,EAGlC,yBAAyB,EAEzB,iCAAiC,GAElC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,wCAAwC,GAEzC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EACL,uBAAuB,EACvB,8BAA8B,EAC9B,qBAAqB,GACtB,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACnE,OAAO,EAEL,iCAAiC,GAClC,MAAM,oCAAoC,CAAC;AAC5C,OAAO,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ACpB,+CAA+C,CAChD,CAAC;IACJ,MAAM,SAAS,GAAG,KAAK,CAAC,iBAAiB,IAAI;QAC3C,aAAa,EAAE,KAAK,CAAC,KAAK,CAAC,aAAa;QACxC,WAAW,EAAE,KAAK,CAAC,KAAK,CAAC,WAAW;QACpC,OAAO,EAAE,KAAK,CAAC,KAAK,CAAC,OAAO;QAC5B,QAAQ,EAAE,KAAK,CAAC,KAAK,CAAC,QAAQ;QAC9B,SAAS,EAAE,KAAK,CAAC,KAAK,CAAC,SAAS;QAChC,cAAc,EAAE,KAAK,CAAC,KAAK,CAAC,cAAc;KAC3C,CAAC;IACF,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,CAAC,KAAK,EAAE,CAAC;AACrD,CAAC","sourcesContent":["import {\n compareCanonicalStrings,\n KeyingVerificationError,\n PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT,\n type PrincipalHistoryIndexNode,\n type PrincipalPolicyHistoryReferenceProof,\n principalHistoryIndexLeaf,\n type ReferencedPrincipalHead,\n resolvePrincipalHistoryIndexProof,\n type VerifiedPrincipalPolicyHistory,\n} from \"@tearleads/crypto\";\nimport {\n isPrincipalPolicyStateChainEntryResponse,\n type PrincipalPolicyStateChainEntryResponse,\n} from \"@tearleads/validators/response\";\nimport { and, eq } from \"drizzle-orm\";\nimport {\n principalHistoryEntries,\n principalHistoryEvidenceTables,\n principalHistoryNodes,\n} from \"../sqlite/principalHistoryEvidenceSchema\";\nimport { sqliteInsertBatchSize } from \"../sqlite/sqliteBindBudget\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../sqlite/sqlitePersistenceRuntime\";\nimport { excludedValue } from \"../sqlite/sqliteUpsert\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport { writePrincipalHistoryNodes } from \"./principalHistoryNodeRetention\";\n\nconst ENTRY_WRITE_BATCH_SIZE = sqliteInsertBatchSize(principalHistoryEntries);\n\nexport interface PrincipalHistoryEvidencePage {\n readonly indexRootHash: string;\n readonly scopeId: string;\n readonly organizationId: string;\n readonly entries: readonly {\n readonly leafHash: string;\n readonly entryJson: string;\n }[];\n readonly nodes: readonly PrincipalHistoryIndexNode[];\n}\n\n/** Prepare only a page accepted by the signature/authorization verifier. */\nexport async function preparePrincipalHistoryEvidencePage(input: {\n readonly indexRootHash: string;\n readonly scopeId: string;\n readonly organizationId: string;\n readonly entries: readonly PrincipalPolicyStateChainEntryResponse[];\n readonly nodes: readonly PrincipalHistoryIndexNode[];\n}): Promise<PrincipalHistoryEvidencePage> {\n if (\n input.entries.length > PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT ||\n input.nodes.length > 2 * PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Principal evidence page exceeds its batch budget\",\n );\n const owned = structuredClone(input);\n return {\n ...owned,\n entries: await Promise.all(\n owned.entries.map(async (entry) => ({\n leafHash: await principalHistoryIndexLeaf(entry.state),\n entryJson: JSON.stringify(entry),\n })),\n ),\n };\n}\n\n/** Publish in the same guarded transaction as the accepted page's progress. */\nexport async function writePrincipalHistoryEvidencePage(\n tx: ClientSQLiteTransactionScope,\n page: PrincipalHistoryEvidencePage,\n): Promise<void> {\n const scope = { scopeId: page.scopeId, organizationId: page.organizationId };\n // A repeated leaf keeps its last entry, as sequential upserts would.\n const entries = new Map(\n page.entries.map((entry) => [\n entry.leafHash,\n { ...scope, leafHash: entry.leafHash, entryJson: entry.entryJson },\n ]),\n );\n const rows = [...entries.values()].sort((a, b) =>\n compareCanonicalStrings(a.leafHash, b.leafHash),\n );\n for (let index = 0; index < rows.length; index += ENTRY_WRITE_BATCH_SIZE)\n await tx\n .insert(principalHistoryEntries)\n .values(rows.slice(index, index + ENTRY_WRITE_BATCH_SIZE))\n .onConflictDoUpdate({\n target: [\n principalHistoryEntries.scopeId,\n principalHistoryEntries.leafHash,\n ],\n set: {\n organizationId: excludedValue(principalHistoryEntries.organizationId),\n entryJson: excludedValue(principalHistoryEntries.entryJson),\n },\n })\n .run();\n await writePrincipalHistoryNodes(\n tx,\n scope,\n [...page.nodes].sort((a, b) => compareCanonicalStrings(a.hash, b.hash)),\n );\n}\n\n/** Returns untrusted material. The caller must verify it against the issued root. */\nexport async function loadPrincipalHistoryReference(input: {\n readonly execSql: ExecSql;\n readonly scopeId: string;\n readonly history: VerifiedPrincipalPolicyHistory;\n readonly version: number;\n readonly expectedReference?: ReferencedPrincipalHead | undefined;\n}): Promise<PrincipalPolicyHistoryReferenceProof> {\n await ensureSqlTables(input.execSql, principalHistoryEvidenceTables);\n const { db } = getClientSQLitePersistenceRuntime(input.execSql);\n const resolved = await resolvePrincipalHistoryIndexProof({\n rootHash: input.history.indexRootHash,\n treeSize: input.history.currentEntry.state.version,\n version: input.version,\n readNode: async (hash) => {\n const [row] = await db\n .select()\n .from(principalHistoryNodes)\n .where(\n and(\n eq(principalHistoryNodes.scopeId, input.scopeId),\n eq(principalHistoryNodes.hash, hash),\n ),\n )\n .limit(1);\n return row ?? null;\n },\n });\n const [row] = await db\n .select()\n .from(principalHistoryEntries)\n .where(\n and(\n eq(principalHistoryEntries.scopeId, input.scopeId),\n eq(principalHistoryEntries.leafHash, resolved.leafHash),\n ),\n )\n .limit(1);\n let entry: unknown;\n try {\n entry = row ? JSON.parse(row.entryJson) : null;\n } catch {\n entry = null;\n }\n if (!isPrincipalPolicyStateChainEntryResponse(entry))\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Principal history entry is missing or corrupt\",\n );\n const reference = input.expectedReference ?? {\n principalType: entry.state.principalType,\n principalId: entry.state.principalId,\n version: entry.state.version,\n keyEpoch: entry.state.keyEpoch,\n stateHash: entry.state.stateHash,\n keyFingerprint: entry.state.keyFingerprint,\n };\n return { reference, entry, proof: resolved.proof };\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"principalHistoryIncompleteRetention.js","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AC,EAAE,CAAC,CAAC;IACzC,KAAK,MAAM,EAAE,IAAI,GAAG;QAAE,MAAM,2BAA2B,CAAC,EAAE,EAAE,SAAS,EAAE,EAAE,CAAC,CAAC;IAC3E,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO;IAC7B,MAAM,EAAE;SACL,MAAM,CAAC,sBAAsB,CAAC;SAC9B,KAAK,CAAC,OAAO,CAAC,sBAAsB,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC;SAC9C,GAAG,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { and, asc, desc, eq, inArray, ne } from \"drizzle-orm\";\nimport { principalHistoryStages } from \"../sqlite/principalHistoryStageSchema\";\nimport type { ClientSQLiteTransactionScope } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { releasePrincipalHistoryRoot } from \"./principalHistoryRootOwnership\";\n\nconst INCOMPLETE_STAGE_LIMIT = 8;\nconst RECLAIM_BATCH_LIMIT = 16;\n\n/** Disposable work only: completed artifacts and trust pins are unaffected. */\nexport async function reclaimIncompletePrincipalHistoryStages(\n tx: ClientSQLiteTransactionScope,\n current: {\n readonly id: string;\n readonly scopeId: string;\n readonly organizationId: string;\n readonly complete: boolean;\n },\n) {\n const obsolete = await tx\n .select({ id: principalHistoryStages.id })\n .from(principalHistoryStages)\n .where(\n and(\n eq(principalHistoryStages.scopeId, current.scopeId),\n eq(principalHistoryStages.organizationId, current.organizationId),\n eq(principalHistoryStages.complete, false),\n ne(principalHistoryStages.id, current.id),\n ),\n )\n .orderBy(\n desc(principalHistoryStages.touchedAt),\n asc(principalHistoryStages.id),\n )\n // The writer always keeps its own stage, even when recency hints tie.\n .offset(INCOMPLETE_STAGE_LIMIT - (current.complete ? 0 : 1))\n .limit(RECLAIM_BATCH_LIMIT);\n const ids = obsolete.map(({ id }) => id);\n for (const id of ids) await releasePrincipalHistoryRoot(tx, `stage:${id}`);\n if (ids.length === 0) return;\n await tx\n .delete(principalHistoryStages)\n .where(inArray(principalHistoryStages.id, ids))\n .run();\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"principalHistoryNodeRetention.js","sourceRoot":"","sources":["principalHistoryNodeRetention.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,qBAAqB,EAAE,MAAM,0CAA0C,CAAC;AACjF,OAAO,EAAE,8BAA8B,EAAE,MAAM,+CAA+C,CAAC;AAC/F,OAAO,EACL,qBAAqB,EACrB,sBAAsB,GACvB,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EACL,sCAAsC,GAEvC,MAAM,iCAAiC,CAAC;AAKzC,MAAM,0BAA0B,GAAG,qBAAqB,CACtD,8BAA8B,CAC/B,CAAC;AACF,MAAM,qBAAqB,GAAG,qBAAqB,CAAC,qBAAqB,CAAC,CAAC;AAC3E,sCAAsC;AACtC,MAAM,sBAAsB,GAAG,sBAAsB,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AAE5D,SAAS,OAAO,CAAI,KAAmB,EAAE,IAAY;IACnD,MAAM,MAAM,GAAU,EAAE,CAAC;IACzB,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,KAAK,CAAC,MAAM,EAAE,KAAK,IAAI,IAAI;QACrD,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC,CAAC,CAAC;IAChD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,KAAK,UAAU,kBAAkB,CAC/B,EAAgC,EAChC,KAAgC,EAChC,MAAyB,EACzB,IAAuD;IAEvD,MAAM,OAAO,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC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,CACD,EAAE,CAAC,qBAAqB,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,EAChD,EAAE,CAAC,qBAAqB,CAAC,cAAc,EAAE,KAAK,CAAC,cAAc,CAAC,EAC9D,EAAE,CAAC,qBAAqB,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,CAC1C,CACF;iBACA,GAAG,EAAE,CAAC;YACT,MAAM,EAAE;iBACL,MAAM,CAAC,8BAA8B,CAAC;iBACtC,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,8BAA8B,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,EACzD,EAAE,CAAC,8BAA8B,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,CACnD,CACF;iBACA,GAAG,EAAE,CAAC;YACT,KAAK,MAAM,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,SAAS,CAAC;gBAChD,IAAI,IAAI;oBAAE,MAAM,sCAAsC,CAAC,EAAE,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;YAC1E,SAAS,IAAI,CAAC,CAAC;QACjB,CAAC;IACH,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import type { PrincipalHistoryIndexNode } from \"@tearleads/crypto\";\nimport { and, asc, eq, inArray } from \"drizzle-orm\";\nimport { principalHistoryNodes } from \"../sqlite/principalHistoryEvidenceSchema\";\nimport { principalHistoryNodeReferences } from \"../sqlite/principalHistoryNodeRetentionSchema\";\nimport {\n sqliteInsertBatchSize,\n sqliteRowsPerStatement,\n} from \"../sqlite/sqliteBindBudget\";\nimport type { ClientSQLiteTransactionScope } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { excludedValue } from \"../sqlite/sqliteUpsert\";\nimport {\n decrementPrincipalHistoryNodeReference,\n type PrincipalHistoryNodeScope,\n} from \"./principalHistoryRootOwnership\";\n\ntype PrincipalHistoryNodeReference =\n typeof principalHistoryNodeReferences.$inferSelect;\n\nconst REFERENCE_WRITE_BATCH_SIZE = sqliteInsertBatchSize(\n principalHistoryNodeReferences,\n);\nconst NODE_WRITE_BATCH_SIZE = sqliteInsertBatchSize(principalHistoryNodes);\n// The scope id binds once per lookup.\nconst HASH_LOOKUP_BATCH_SIZE = sqliteRowsPerStatement(1, 1);\n\nfunction batches<T>(items: readonly T[], size: number): T[][] {\n const result: T[][] = [];\n for (let index = 0; index < items.length; index += size)\n result.push(items.slice(index, index + size));\n return result;\n}\n\nasync function loadNodeReferences(\n tx: ClientSQLiteTransactionScope,\n scope: PrincipalHistoryNodeScope,\n hashes: readonly string[],\n into: Map<string, PrincipalHistoryNodeReference | null>,\n): Promise<void> {\n const missing = [...new Set(hashes)].filter((hash) => !into.has(hash));\n for (const batch of batches(missing, HASH_LOOKUP_BATCH_SIZE)) {\n for (const hash of batch) into.set(hash, null);\n const rows = await tx\n .select()\n .from(principalHistoryNodeReferences)\n .where(\n and(\n eq(principalHistoryNodeReferences.scopeId, scope.scopeId),\n inArray(principalHistoryNodeReferences.hash, batch),\n ),\n );\n for (const row of rows) into.set(row.hash, row);\n }\n}\n\nasync function loadStoredNodeHashes(\n tx: ClientSQLiteTransactionScope,\n scope: PrincipalHistoryNodeScope,\n hashes: readonly string[],\n): Promise<Set<string>> {\n const stored = new Set<string>();\n for (const batch of batches([...new Set(hashes)], HASH_LOOKUP_BATCH_SIZE)) {\n const rows = await tx\n .select({ hash: principalHistoryNodes.hash })\n .from(principalHistoryNodes)\n .where(\n and(\n eq(principalHistoryNodes.scopeId, scope.scopeId),\n inArray(principalHistoryNodes.hash, batch),\n ),\n );\n for (const row of rows) stored.add(row.hash);\n }\n return stored;\n}\n\n/**\n * Replays the per-node edge bookkeeping in memory: increment inserts or adds\n * one, decrement floors at zero within the scope's organization, and an edge\n * change keeps the count while marking nodes first stored here as managed.\n */\nfunction replayNodeEdges(\n scope: PrincipalHistoryNodeScope,\n nodes: readonly PrincipalHistoryIndexNode[],\n loaded: ReadonlyMap<string, PrincipalHistoryNodeReference | null>,\n storedNodeHashes: Set<string>,\n): Map<string, PrincipalHistoryNodeReference | null> {\n const references = new Map(loaded);\n const read = (hash: string) => {\n const reference = references.get(hash);\n if (reference === undefined)\n throw new Error(\"Principal history node reference was not loaded\");\n return reference;\n };\n const increment = (hash: string) => {\n const reference = read(hash);\n references.set(\n hash,\n reference\n ? { ...reference, referenceCount: reference.referenceCount + 1 }\n : {\n ...scope,\n hash,\n referenceCount: 1,\n managed: false,\n leftHash: null,\n rightHash: null,\n },\n );\n };\n const decrement = (hash: string) => {\n const reference = read(hash);\n if (reference?.organizationId === scope.organizationId)\n references.set(hash, {\n ...reference,\n referenceCount: Math.max(reference.referenceCount - 1, 0),\n });\n };\n for (const node of nodes) {\n const previous = read(node.hash);\n if (\n previous?.leftHash !== node.leftHash ||\n previous.rightHash !== node.rightHash\n ) {\n const managed = previous?.managed || !storedNodeHashes.has(node.hash);\n increment(node.leftHash);\n increment(node.rightHash);\n const current = read(node.hash);\n references.set(node.hash, {\n ...(current ?? {\n ...scope,\n hash: node.hash,\n referenceCount: previous?.referenceCount ?? 0,\n }),\n leftHash: node.leftHash,\n rightHash: node.rightHash,\n managed,\n });\n for (const hash of [previous?.leftHash, previous?.rightHash])\n if (hash) decrement(hash);\n }\n storedNodeHashes.add(node.hash);\n }\n return references;\n}\n\nfunction isSameNodeReference(\n left: PrincipalHistoryNodeReference,\n right: PrincipalHistoryNodeReference,\n): boolean {\n return (\n left.organizationId === right.organizationId &&\n left.referenceCount === right.referenceCount &&\n left.managed === right.managed &&\n left.leftHash === right.leftHash &&\n left.rightHash === right.rightHash\n );\n}\n\n/**\n * Register edges and store proof nodes in the given order, with the same\n * result as recording each node's edges and then upserting it. Reads the\n * touched liveness rows once, replays the bookkeeping, and writes the changed\n * rows and the nodes as multi-row upserts.\n */\nexport async function writePrincipalHistoryNodes(\n tx: ClientSQLiteTransactionScope,\n scope: PrincipalHistoryNodeScope,\n nodes: readonly PrincipalHistoryIndexNode[],\n): Promise<void> {\n if (nodes.length === 0) return;\n const loaded = new Map<string, PrincipalHistoryNodeReference | null>();\n await loadNodeReferences(\n tx,\n scope,\n nodes.flatMap((node) => [node.hash, node.leftHash, node.rightHash]),\n loaded,\n );\n // An edge change releases the stored row's previous children.\n await loadNodeReferences(\n tx,\n scope,\n nodes.flatMap((node) => {\n const stored = loaded.get(node.hash);\n return [stored?.leftHash, stored?.rightHash].filter(\n (hash): hash is string => Boolean(hash),\n );\n }),\n loaded,\n );\n const replayed = replayNodeEdges(\n scope,\n nodes,\n loaded,\n await loadStoredNodeHashes(\n tx,\n scope,\n nodes.map((node) => node.hash),\n ),\n );\n const changed = [...replayed].flatMap(([hash, reference]) => {\n const before = loaded.get(hash);\n return reference && !(before && isSameNodeReference(before, reference))\n ? [reference]\n : [];\n });\n for (const batch of batches(changed, REFERENCE_WRITE_BATCH_SIZE))\n await tx\n .insert(principalHistoryNodeReferences)\n .values(batch)\n .onConflictDoUpdate({\n target: [\n principalHistoryNodeReferences.scopeId,\n principalHistoryNodeReferences.hash,\n ],\n set: {\n referenceCount: excludedValue(\n principalHistoryNodeReferences.referenceCount,\n ),\n managed: excludedValue(principalHistoryNodeReferences.managed),\n leftHash: excludedValue(principalHistoryNodeReferences.leftHash),\n rightHash: excludedValue(principalHistoryNodeReferences.rightHash),\n },\n })\n .run();\n const nodeRows = new Map(\n nodes.map((node) => [\n node.hash,\n {\n ...scope,\n hash: node.hash,\n leftHash: node.leftHash,\n rightHash: node.rightHash,\n },\n ]),\n );\n for (const batch of batches([...nodeRows.values()], NODE_WRITE_BATCH_SIZE))\n await tx\n .insert(principalHistoryNodes)\n .values(batch)\n .onConflictDoUpdate({\n target: [principalHistoryNodes.scopeId, principalHistoryNodes.hash],\n set: {\n organizationId: excludedValue(principalHistoryNodes.organizationId),\n leftHash: excludedValue(principalHistoryNodes.leftHash),\n rightHash: excludedValue(principalHistoryNodes.rightHash),\n },\n })\n .run();\n}\n\n/** A bounded cascade releases only managed proof nodes with no live incoming edge. */\nexport async function reclaimPrincipalHistoryNodes(\n tx: ClientSQLiteTransactionScope,\n scope: PrincipalHistoryNodeScope,\n): Promise<number> {\n let reclaimed = 0;\n while (reclaimed < 64) {\n const obsolete = await tx\n .select()\n .from(principalHistoryNodeReferences)\n .where(\n and(\n eq(principalHistoryNodeReferences.scopeId, scope.scopeId),\n eq(\n principalHistoryNodeReferences.organizationId,\n scope.organizationId,\n ),\n eq(principalHistoryNodeReferences.managed, true),\n eq(principalHistoryNodeReferences.referenceCount, 0),\n ),\n )\n .orderBy(asc(principalHistoryNodeReferences.hash))\n .limit(64 - reclaimed);\n if (obsolete.length === 0) break;\n for (const node of obsolete) {\n await tx\n .delete(principalHistoryNodes)\n .where(\n and(\n eq(principalHistoryNodes.scopeId, scope.scopeId),\n eq(principalHistoryNodes.organizationId, scope.organizationId),\n eq(principalHistoryNodes.hash, node.hash),\n ),\n )\n .run();\n await tx\n .delete(principalHistoryNodeReferences)\n .where(\n and(\n eq(principalHistoryNodeReferences.scopeId, scope.scopeId),\n eq(principalHistoryNodeReferences.hash, node.hash),\n ),\n )\n .run();\n for (const hash of [node.leftHash, node.rightHash])\n if (hash) await decrementPrincipalHistoryNodeReference(tx, scope, hash);\n reclaimed += 1;\n }\n }\n return reclaimed;\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"principalHistoryPrefixPersistence.js","sourceRoot":"","sources":["principalHistoryPrefixPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,mCAAmC,EAAE,MAAM,uCAAuC,CAAC;AAC5F,OAAO,EACL,8BAA8B,EAC9B,wBAAwB,GACzB,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,2BAA2B,EAAE,MAAM,uCAAuC,CAAC;AACpF,OAAO,EAAE,iCAAiC,EAAE,MAAM,oCAAoC,CAAC;AACvF,OAAO,EAAgB,eAAe,EAAE,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O,EAAE,CAAC,CAAC;QAClE,MAAM,EAAE;aACL,MAAM,CAAC,wBAAwB,CAAC;aAChC,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,wBAAwB,CAAC,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC,EACpD,EAAE,CAAC,wBAAwB,CAAC,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAC,CACvD,CACF;aACA,GAAG,EAAE,CAAC;IACX,CAAC,EACD,KAAK,CAAC,YAAY,EAClB,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;IACF,mCAAmC,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;AAC9D,CAAC","sourcesContent":["import { and, eq } from \"drizzle-orm\";\nimport { assertProjectionVerificationCurrent } from \"../keyingProjectionVerification/types\";\nimport {\n principalHistoryEvidenceTables,\n principalHistoryPrefixes,\n} from \"../sqlite/principalHistoryEvidenceSchema\";\nimport { principalHistoryStageTables } from \"../sqlite/principalHistoryStageSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport { reclaimPrincipalHistoryNodes } from \"./principalHistoryNodeRetention\";\nimport {\n releasePrincipalHistoryRoot,\n retainPrincipalHistoryRoot,\n} from \"./principalHistoryRootOwnership\";\nimport { reclaimCompletedPrincipalHistoryStages } from \"./principalHistoryStageRetention\";\nimport { archivePrincipalHistoryKeyEnvelopes } from \"./principalKeyEnvelopeArchivePersistence\";\n\nexport type PrincipalHistoryPrefix =\n typeof principalHistoryPrefixes.$inferSelect;\n\nexport async function loadPrincipalHistoryPrefix(\n execSql: ExecSql,\n scopeId: string,\n) {\n await ensureSqlTables(execSql, principalHistoryEvidenceTables);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const [prefix] = await db\n .select()\n .from(principalHistoryPrefixes)\n .where(eq(principalHistoryPrefixes.scopeId, scopeId))\n .limit(1);\n return prefix ?? null;\n}\n\n/**\n * Preserve identical completed progress; this sink does not authenticate hints.\n * Callers must discard an unreadable prefix or identify it with rejectedPrefix\n * before publishing a repair of the same head and current artifacts.\n */\nexport async function savePrincipalHistoryPrefix(input: {\n readonly execSql: ExecSql;\n readonly prefix: PrincipalHistoryPrefix;\n readonly indexRootHash: string;\n readonly stillCurrent: () => boolean;\n readonly rejectedPrefix?: PrincipalHistoryPrefix | null;\n}): Promise<void> {\n const prefix = { ...input.prefix };\n const indexRootHash = input.indexRootHash;\n const rejected = input.rejectedPrefix ? { ...input.rejectedPrefix } : null;\n await ensureSqlTables(input.execSql, [\n ...principalHistoryEvidenceTables,\n ...principalHistoryStageTables,\n ]);\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const result = await runtime.guardedTransaction(\n async (tx) => {\n const [previous] = await tx\n .select()\n .from(principalHistoryPrefixes)\n .where(eq(principalHistoryPrefixes.scopeId, prefix.scopeId))\n .limit(1);\n const replacesRejected =\n previous &&\n rejected?.scopeId === previous.scopeId &&\n rejected.progress === previous.progress;\n if (previous && previous.version > prefix.version && !replacesRejected)\n return;\n if (\n previous &&\n previous.version === prefix.version &&\n previous.organizationId === prefix.organizationId &&\n previous.headJson === prefix.headJson &&\n previous.currentJson === prefix.currentJson &&\n !replacesRejected\n ) {\n // Resealing an unchanged prefix would invalidate an acknowledgement's\n // progress CAS even though its authenticated predecessor is unchanged.\n // Still refresh authenticated root ownership and retention below.\n // Reuse authenticates this opaque progress; rejected hints are removed\n // or explicitly replaced before repair can rely on the new prefix.\n prefix.progress = previous.progress;\n }\n if (previous) await archivePrincipalHistoryKeyEnvelopes(tx, previous);\n await archivePrincipalHistoryKeyEnvelopes(tx, prefix);\n await tx\n .insert(principalHistoryPrefixes)\n .values(prefix)\n .onConflictDoUpdate({\n target: principalHistoryPrefixes.scopeId,\n set: prefix,\n })\n .run();\n await reclaimCompletedPrincipalHistoryStages(tx, prefix);\n await retainPrincipalHistoryRoot(tx, {\n id: `prefix:${prefix.scopeId}`,\n scopeId: prefix.scopeId,\n organizationId: prefix.organizationId,\n rootHash: indexRootHash,\n });\n await reclaimPrincipalHistoryNodes(tx, prefix);\n },\n input.stillCurrent,\n { behavior: \"immediate\" },\n );\n assertProjectionVerificationCurrent(() => result.committed);\n}\n\n/** Invalid hints are disposable, but a losing reader must preserve a newer hint. */\nexport async function discardPrincipalHistoryPrefix(input: {\n readonly execSql: ExecSql;\n readonly prefix: PrincipalHistoryPrefix;\n readonly stillCurrent: () => boolean;\n}): Promise<void> {\n const prefix = { ...input.prefix };\n await ensureSqlTables(input.execSql, principalHistoryEvidenceTables);\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const result = await runtime.guardedTransaction(\n async (tx) => {\n const [current] = await tx\n .select({ progress: principalHistoryPrefixes.progress })\n .from(principalHistoryPrefixes)\n .where(eq(principalHistoryPrefixes.scopeId, prefix.scopeId))\n .limit(1);\n if (current?.progress !== prefix.progress) return;\n await releasePrincipalHistoryRoot(tx, `prefix:${prefix.scopeId}`);\n await tx\n .delete(principalHistoryPrefixes)\n .where(\n and(\n eq(principalHistoryPrefixes.scopeId, prefix.scopeId),\n eq(principalHistoryPrefixes.progress, prefix.progress),\n ),\n )\n .run();\n },\n input.stillCurrent,\n { behavior: \"immediate\" },\n );\n assertProjectionVerificationCurrent(() => result.committed);\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"principalHistoryRootOwnership.js","sourceRoot":"","sources":["principalHistoryRootOwnership.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EACL,8BAA8B,EAC9B,0BAA0B,GAC3B,MAAM,+CAA+C,CAAC;AASvD,MAAM,CAAC,KAAK,UAAU,sCAAsC,CAC1D,EAAgC,EAChC,KAAgC,EAChC,IAAY;IAEZ,MAAM,EAAE;SACL,MAAM,CAAC,8BAA8B,CAAC;SACtC,M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K,KAAK,CAAC,cAAc;QAChD,QAAQ,CAAC,QAAQ,KAAK,KAAK,CAAC,QAAQ;QAEpC,OAAO;IACT,MAAM,sCAAsC,CAAC,EAAE,EAAE,KAAK,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC;IACxE,MAAM,EAAE;SACL,MAAM,CAAC,0BAA0B,CAAC;SAClC,MAAM,CAAC,KAAK,CAAC;SACb,kBAAkB,CAAC;QAClB,MAAM,EAAE,0BAA0B,CAAC,EAAE;QACrC,GAAG,EAAE,KAAK;KACX,CAAC;SACD,GAAG,EAAE,CAAC;IACT,IAAI,QAAQ;QACV,MAAM,sCAAsC,CAC1C,EAAE,EACF,QAAQ,EACR,QAAQ,CAAC,QAAQ,CAClB,CAAC;AACN,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAC/C,EAAgC,EAChC,EAAU;IAEV,MAAM,CAAC,QAAQ,CAAC,GAAG,MAAM,EAAE;SACxB,MAAM,EAAE;SACR,IAAI,CAAC,0BAA0B,CAAC;SAChC,KAAK,CAAC,EAAE,CAAC,0BAA0B,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;SAC5C,KAAK,CAAC,CAAC,CAAC,CAAC;IACZ,IAAI,CAAC,QAAQ;QAAE,OAAO;IACtB,MAAM,EAAE;SACL,MAAM,CAAC,0BAA0B,CAAC;SAClC,KAAK,CAAC,EAAE,CAAC,0BAA0B,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;SAC5C,GAAG,EAAE,CAAC;IACT,MAAM,sCAAsC,CAAC,EAAE,EAAE,QAAQ,EAAE,QAAQ,CAAC,QAAQ,CAAC,CAAC;AAChF,CAAC","sourcesContent":["import { and, eq, sql } from \"drizzle-orm\";\nimport {\n principalHistoryNodeReferences,\n principalHistoryRootOwners,\n} from \"../sqlite/principalHistoryNodeRetentionSchema\";\nimport type { ClientSQLiteTransactionScope } from \"../sqlite/sqlitePersistenceRuntime\";\n\nexport interface PrincipalHistoryNodeScope {\n /** Evidence scope hashes include organizationId; one scope belongs to one organization. */\n readonly scopeId: string;\n readonly organizationId: string;\n}\n\nexport async function incrementPrincipalHistoryNodeReference(\n tx: ClientSQLiteTransactionScope,\n scope: PrincipalHistoryNodeScope,\n hash: string,\n) {\n await tx\n .insert(principalHistoryNodeReferences)\n .values({\n ...scope,\n hash,\n referenceCount: 1,\n managed: false,\n leftHash: null,\n rightHash: null,\n })\n .onConflictDoUpdate({\n target: [\n principalHistoryNodeReferences.scopeId,\n principalHistoryNodeReferences.hash,\n ],\n set: {\n referenceCount: sql`${principalHistoryNodeReferences.referenceCount} + 1`,\n },\n })\n .run();\n}\n\nexport async function decrementPrincipalHistoryNodeReference(\n tx: ClientSQLiteTransactionScope,\n scope: PrincipalHistoryNodeScope,\n hash: string,\n) {\n await tx\n .update(principalHistoryNodeReferences)\n .set({\n referenceCount: sql`max(${principalHistoryNodeReferences.referenceCount} - 1, 0)`,\n })\n .where(\n and(\n eq(principalHistoryNodeReferences.scopeId, scope.scopeId),\n eq(principalHistoryNodeReferences.organizationId, scope.organizationId),\n eq(principalHistoryNodeReferences.hash, hash),\n ),\n )\n .run();\n}\n\n/** Caller commits ownership together with the exact saved progress it describes. */\nexport async function retainPrincipalHistoryRoot(\n tx: ClientSQLiteTransactionScope,\n input: PrincipalHistoryNodeScope & {\n readonly id: string;\n readonly rootHash: string;\n },\n) {\n const [previous] = await tx\n .select()\n .from(principalHistoryRootOwners)\n .where(eq(principalHistoryRootOwners.id, input.id))\n .limit(1);\n if (\n previous?.scopeId === input.scopeId &&\n previous.organizationId === input.organizationId &&\n previous.rootHash === input.rootHash\n )\n return;\n await incrementPrincipalHistoryNodeReference(tx, input, input.rootHash);\n await tx\n .insert(principalHistoryRootOwners)\n .values(input)\n .onConflictDoUpdate({\n target: principalHistoryRootOwners.id,\n set: input,\n })\n .run();\n if (previous)\n await decrementPrincipalHistoryNodeReference(\n tx,\n previous,\n previous.rootHash,\n );\n}\n\nexport async function releasePrincipalHistoryRoot(\n tx: ClientSQLiteTransactionScope,\n id: string,\n) {\n const [previous] = await tx\n .select()\n .from(principalHistoryRootOwners)\n .where(eq(principalHistoryRootOwners.id, id))\n .limit(1);\n if (!previous) return;\n await tx\n .delete(principalHistoryRootOwners)\n .where(eq(principalHistoryRootOwners.id, id))\n .run();\n await decrementPrincipalHistoryNodeReference(tx, previous, previous.rootHash);\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"principalHistoryStagePersistence.js","sourceRoot":"","sources":["principalHistoryStagePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,mCAAmC,EAAE,MAAM,uCAAuC,CAAC;AAC5F,OAAO,EAAE,8BAA8B,EAAE,MAAM,0CAA0C,CAAC;AAC1F,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EACL,sBAAsB,EACtB,2BAA2B,GAC5B,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,iCAAiC,EAAE,MAAM,oCAAoC,CAAC;AACvF,OAAO,EAAgB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,uCAAuC,EAAE,MAAM,uCAAuC,CAAC;AAChG,OAAO,EAAE,4BAA4B,EAAE,MAAM,iCAAiC,CAAC;AAC/E,OAAO,EACL,2BAA2B,EAC3B,0BAA0B,GAC3B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,wCAAwC,EAAE,MAAM,wCAAwC,CAAC;AAQlG,MAAM,4BAA4B,GAAG;IACnC,EAAE,EAAE,sBAAsB,CAAC,EAAE;IAC7B,cAAc,EAAE,sBAAsB,CAAC,cAAc;IACrD,WAAW,EAAE,sBAAsB,CAAC,WAAW;IAC/C,YAAY,EAAE,sBAAsB,CAAC,YAAY;IACjD,QAAQ,EAAE,sB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ProjectionVerificationCurrent } from \"../keyingProjectionVerification/types\";\nimport { principalHistoryEvidenceTables } from \"../sqlite/principalHistoryEvidenceSchema\";\nimport { principalHistoryNodeRetentionTables } from \"../sqlite/principalHistoryNodeRetentionSchema\";\nimport {\n principalHistoryStages,\n principalHistoryStageTables,\n} from \"../sqlite/principalHistoryStageSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport {\n type PrincipalHistoryEvidencePage,\n writePrincipalHistoryEvidencePage,\n} from \"./principalHistoryEvidencePersistence\";\nimport { reclaimIncompletePrincipalHistoryStages } from \"./principalHistoryIncompleteRetention\";\nimport { reclaimPrincipalHistoryNodes } from \"./principalHistoryNodeRetention\";\nimport {\n releasePrincipalHistoryRoot,\n retainPrincipalHistoryRoot,\n} from \"./principalHistoryRootOwnership\";\nimport { reclaimUnpublishedPrincipalHistoryStages } from \"./principalHistoryUnpublishedRetention\";\n\n/** A stage's verification work; its retention hints are written by persistence. */\nexport type PrincipalHistoryStage = Omit<\n typeof principalHistoryStages.$inferSelect,\n \"scopeId\" | \"touchedAt\"\n>;\n\nconst principalHistoryStageColumns = {\n id: principalHistoryStages.id,\n organizationId: principalHistoryStages.organizationId,\n currentJson: principalHistoryStages.currentJson,\n afterVersion: principalHistoryStages.afterVersion,\n complete: principalHistoryStages.complete,\n progress: principalHistoryStages.progress,\n};\n\nclass PrincipalHistoryStageChangedError extends Error {\n readonly code = \"principal_history_stage_changed\";\n constructor() {\n super(\n \"Another operation changed the saved principal history; resume from its current state\",\n );\n this.name = \"PrincipalHistoryStageChangedError\";\n }\n}\n\nexport async function loadPrincipalHistoryStage(\n execSql: ExecSql,\n id: string,\n): Promise<PrincipalHistoryStage | null> {\n await ensureSqlTables(execSql, principalHistoryStageTables);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const [row] = await db\n .select(principalHistoryStageColumns)\n .from(principalHistoryStages)\n .where(eq(principalHistoryStages.id, id))\n .limit(1);\n return row ?? null;\n}\n\n/** Publish accepted entries and index nodes atomically with authenticated progress. */\nexport async function savePrincipalHistoryStage(input: {\n readonly execSql: ExecSql;\n readonly stage: PrincipalHistoryStage;\n readonly evidence: PrincipalHistoryEvidencePage;\n readonly previousProgress: string | null;\n readonly stillCurrent: () => boolean;\n}): Promise<void> {\n const evidence = structuredClone(input.evidence);\n const stage = { ...input.stage, scopeId: evidence.scopeId };\n await ensureSqlTables(input.execSql, [\n ...principalHistoryStageTables,\n ...principalHistoryEvidenceTables,\n ]);\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const saved = await runtime.guardedTransaction(\n async (tx) => {\n const [previous] = await tx\n .select({ progress: principalHistoryStages.progress })\n .from(principalHistoryStages)\n .where(eq(principalHistoryStages.id, stage.id))\n .limit(1);\n if ((previous?.progress ?? null) !== input.previousProgress)\n throw new PrincipalHistoryStageChangedError();\n await writePrincipalHistoryEvidencePage(tx, evidence);\n const row = { ...stage, touchedAt: Date.now() };\n await tx\n .insert(principalHistoryStages)\n .values(row)\n .onConflictDoUpdate({ target: principalHistoryStages.id, set: row })\n .run();\n await retainPrincipalHistoryRoot(tx, {\n id: `stage:${stage.id}`,\n scopeId: evidence.scopeId,\n organizationId: stage.organizationId,\n rootHash: evidence.indexRootHash,\n });\n await reclaimIncompletePrincipalHistoryStages(tx, stage);\n await reclaimUnpublishedPrincipalHistoryStages(tx, stage);\n await reclaimPrincipalHistoryNodes(tx, evidence);\n },\n input.stillCurrent,\n { behavior: \"immediate\" },\n );\n assertProjectionVerificationCurrent(() => saved.committed);\n}\n\nexport async function discardPrincipalHistoryStage(\n execSql: ExecSql,\n stage: PrincipalHistoryStage,\n stillCurrent: () => boolean,\n) {\n await ensureSqlTables(execSql, [\n ...principalHistoryStageTables,\n ...principalHistoryNodeRetentionTables,\n ]);\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const discarded = await runtime.guardedTransaction(\n async (db) => {\n const [current] = await db\n .select({ progress: principalHistoryStages.progress })\n .from(principalHistoryStages)\n .where(eq(principalHistoryStages.id, stage.id))\n .limit(1);\n if (current?.progress !== stage.progress) return;\n await releasePrincipalHistoryRoot(db, `stage:${stage.id}`);\n await db\n .delete(principalHistoryStages)\n .where(\n and(\n eq(principalHistoryStages.id, stage.id),\n eq(principalHistoryStages.progress, stage.progress),\n ),\n )\n .run();\n },\n stillCurrent,\n { behavior: \"immediate\" },\n );\n assertProjectionVerificationCurrent(() => discarded.committed);\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"principalHistoryStageRetention.js","sourceRoot":"","sources":["principalHistoryStageRetention.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,sBAAsB,EAAE,MAAM,uCAAuC,CAAC;AAE/E,OAAO,EAAE,2BAA2B,EAAE,MAAM,iCAAiC,CAAC;AAC9E,OAAO,EAAE,mCAAmC,EAAE,MAAM,0CAA0C,CAAC;AAE/F,4EAA4E;AAC5E,MAAM,CAAC,MAAM,qCAAqC,GAAG,EAAE,CAAC;AAExD,8EAA8E;AAC9E,MAAM,CAAC,KAAK,UAAU,0BAA0B,CAC9C,EAAgC,EAChC,KAAwD;IAExD,MAAM,EAAE;SACL,MAAM,CAAC,sBAAsB,CAAC;SAC9B,GAAG,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC;SACtD,KAAK,CAAC,EAAE,CAAC,sBAAsB,CAAC,EAAE,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;SAC9C,GAAG,EAAE,CAAC;AACX,CAAC;AAED,+EAA+E;AAC/E,MAAM,CAAC,KAAK,UAAU,sCAAsC,CAC1D,EAAgC,EAChC,MAIC;IAED,MAAM,QAAQ,GAAG,MA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H,CAAC","sourcesContent":["import { and, asc, desc, eq, lt } from \"drizzle-orm\";\nimport { principalHistoryStages } from \"../sqlite/principalHistoryStageSchema\";\nimport type { ClientSQLiteTransactionScope } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { releasePrincipalHistoryRoot } from \"./principalHistoryRootOwnership\";\nimport { archivePrincipalHistoryKeyEnvelopes } from \"./principalKeyEnvelopeArchivePersistence\";\n\n/** Each publication reclaims at most this many obsolete completed heads. */\nexport const PRINCIPAL_HISTORY_STAGE_RECLAIM_LIMIT = 16;\n\n/** Mark a stored stage as just used by a writer for its principal history. */\nexport async function touchPrincipalHistoryStage(\n tx: ClientSQLiteTransactionScope,\n input: { readonly id: string; readonly scopeId: string },\n) {\n await tx\n .update(principalHistoryStages)\n .set({ scopeId: input.scopeId, touchedAt: Date.now() })\n .where(eq(principalHistoryStages.id, input.id))\n .run();\n}\n\n/** The prefix and its key candidates must be published in this transaction. */\nexport async function reclaimCompletedPrincipalHistoryStages(\n tx: ClientSQLiteTransactionScope,\n prefix: {\n readonly scopeId: string;\n readonly organizationId: string;\n readonly version: number;\n },\n) {\n const obsolete = await tx\n .select({\n stage: {\n id: principalHistoryStages.id,\n organizationId: principalHistoryStages.organizationId,\n currentJson: principalHistoryStages.currentJson,\n afterVersion: principalHistoryStages.afterVersion,\n },\n })\n .from(principalHistoryStages)\n .where(\n and(\n eq(principalHistoryStages.scopeId, prefix.scopeId),\n eq(principalHistoryStages.organizationId, prefix.organizationId),\n eq(principalHistoryStages.complete, true),\n lt(principalHistoryStages.afterVersion, prefix.version),\n ),\n )\n .orderBy(\n desc(principalHistoryStages.afterVersion),\n desc(principalHistoryStages.touchedAt),\n asc(principalHistoryStages.id),\n )\n // Keep the current completed head and its newest completed predecessor.\n // This also preserves the prefix-only predecessor restored after an ack.\n .offset(2)\n .limit(PRINCIPAL_HISTORY_STAGE_RECLAIM_LIMIT);\n for (const { stage } of obsolete) {\n await releasePrincipalHistoryRoot(tx, `stage:${stage.id}`);\n await archivePrincipalHistoryKeyEnvelopes(tx, {\n ...stage,\n version: stage.afterVersion + 1,\n });\n await tx\n .delete(principalHistoryStages)\n .where(eq(principalHistoryStages.id, stage.id))\n .run();\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"principalHistoryUnpublishedRetention.js","sourceRoot":"","sources":["principalHistoryUnpublishedRetention.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC1E,OAAO,EAAE,wBAAwB,EAAE,MAAM,0CAA0C,CAAC;AACpF,OAAO,EAAE,sBAAsB,EAAE,MAAM,uCAAuC,CAAC;AAE/E,OAAO,EAAE,2BAA2B,EAAE,MAAM,iCAAiC,CAAC;AAC9E,OAAO,EAAE,qCAAqC,EAAE,MAAM,kCAAkC,CAAC;AACzF,OAAO,EAAE,mCAAmC,EAAE,MAAM,0CAA0C,CAAC;AAE/F,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAShC,SAAS,uBAAuB,CAAC,OAAwB;IACvD,OAAO,GAAG,CACR,EAAE,CAAC,sBAAsB,CAAC,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,EACnD,EAAE,CAAC,sBAAsB,CAAC,cAAc,EAAE,OAAO,CAAC,cAAc,CAAC,EACjE,EAAE,CAAC,sBAAsB,CAAC,QAAQ,EAAE,IAAI,CAAC,CAC1C,CAAC;AACJ,CAAC;AAED,KAAK,UAAU,wBAAwB,CACrC,EAAgC,EAChC,OAAwB;IAExB,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,EAAE;SACtB,MAAM,CAAC,EAAE,OAAO,EAAE,wBAAwB,CAAC,OAAO,EAAE,CAAC;SACrD,IAAI,CAAC,wBAAwB,CAAC;SAC9B,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,wBAAwB,CAAC,OAAO,EAAE,OAA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EAAE,sBAAsB,CAAC,YAAY;SAClD;KACF,CAAC;SACD,IAAI,CAAC,sBAAsB,CAAC;SAC5B,KAAK,CACJ,GAAG,CACD,uBAAuB,CAAC,OAAO,CAAC,EAChC,UAAU,CAAC,sBAAsB,CAAC,EAAE,EAAE,YAAY,CAAC,CACpD,CACF;QACD,wEAAwE;SACvE,OAAO,CACN,IAAI,CAAC,sBAAsB,CAAC,SAAS,CAAC,EACtC,GAAG,CAAC,sBAAsB,CAAC,EAAE,CAAC,CAC/B;SACA,MAAM,CAAC,qBAAqB,GAAG,YAAY,CAAC,MAAM,CAAC;SACnD,KAAK,CAAC,qCAAqC,CAAC,CAAC;IAChD,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO;IAClC,KAAK,MAAM,EAAE,KAAK,EAAE,IAAI,QAAQ;QAC9B,MAAM,mCAAmC,CAAC,EAAE,EAAE;YAC5C,GAAG,KAAK;YACR,OAAO,EAAE,KAAK,CAAC,YAAY,GAAG,CAAC;SAChC,CAAC,CAAC;IACL,MAAM,GAAG,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAClD,KAAK,MAAM,EAAE,IAAI,GAAG;QAAE,MAAM,2BAA2B,CAAC,EAAE,EAAE,SAAS,EAAE,EAAE,CAAC,CAAC;IAC3E,MAAM,EAAE;SACL,MAAM,CAAC,sBAAsB,CAAC;SAC9B,KAAK,CAAC,OAAO,CAAC,sBAAsB,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC;SAC9C,GAAG,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { and, asc, desc, eq, inArray, lt, notInArray } from \"drizzle-orm\";\nimport { principalHistoryPrefixes } from \"../sqlite/principalHistoryEvidenceSchema\";\nimport { principalHistoryStages } from \"../sqlite/principalHistoryStageSchema\";\nimport type { ClientSQLiteTransactionScope } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { releasePrincipalHistoryRoot } from \"./principalHistoryRootOwnership\";\nimport { PRINCIPAL_HISTORY_STAGE_RECLAIM_LIMIT } from \"./principalHistoryStageRetention\";\nimport { archivePrincipalHistoryKeyEnvelopes } from \"./principalKeyEnvelopeArchivePersistence\";\n\nconst COMPLETED_STAGE_LIMIT = 8;\n\ninterface CompletedWriter {\n readonly id: string;\n readonly scopeId: string;\n readonly organizationId: string;\n readonly complete: boolean;\n}\n\nfunction matchingCompletedStages(current: CompletedWriter) {\n return and(\n eq(principalHistoryStages.scopeId, current.scopeId),\n eq(principalHistoryStages.organizationId, current.organizationId),\n eq(principalHistoryStages.complete, true),\n );\n}\n\nasync function protectedPublishedStages(\n tx: ClientSQLiteTransactionScope,\n current: CompletedWriter,\n) {\n const [prefix] = await tx\n .select({ version: principalHistoryPrefixes.version })\n .from(principalHistoryPrefixes)\n .where(\n and(\n eq(principalHistoryPrefixes.scopeId, current.scopeId),\n eq(principalHistoryPrefixes.organizationId, current.organizationId),\n ),\n )\n .limit(1);\n if (!prefix) return [];\n return tx\n .select({ id: principalHistoryStages.id })\n .from(principalHistoryStages)\n .where(\n and(\n matchingCompletedStages(current),\n lt(principalHistoryStages.afterVersion, prefix.version),\n ),\n )\n .orderBy(\n desc(principalHistoryStages.afterVersion),\n desc(principalHistoryStages.touchedAt),\n asc(principalHistoryStages.id),\n )\n .limit(2);\n}\n\n/** Bound completed attempts even when current-artifact verification never publishes. */\nexport async function reclaimUnpublishedPrincipalHistoryStages(\n tx: ClientSQLiteTransactionScope,\n current: CompletedWriter,\n) {\n if (!current.complete) return;\n const published = await protectedPublishedStages(tx, current);\n const protectedIds = [\n ...new Set([current.id, ...published.map(({ id }) => id)]),\n ];\n const obsolete = await tx\n .select({\n stage: {\n id: principalHistoryStages.id,\n organizationId: principalHistoryStages.organizationId,\n currentJson: principalHistoryStages.currentJson,\n afterVersion: principalHistoryStages.afterVersion,\n },\n })\n .from(principalHistoryStages)\n .where(\n and(\n matchingCompletedStages(current),\n notInArray(principalHistoryStages.id, protectedIds),\n ),\n )\n // The existing \"incomplete\" index also covers completed scoped recency.\n .orderBy(\n desc(principalHistoryStages.touchedAt),\n asc(principalHistoryStages.id),\n )\n .offset(COMPLETED_STAGE_LIMIT - protectedIds.length)\n .limit(PRINCIPAL_HISTORY_STAGE_RECLAIM_LIMIT);\n if (obsolete.length === 0) return;\n for (const { stage } of obsolete)\n await archivePrincipalHistoryKeyEnvelopes(tx, {\n ...stage,\n version: stage.afterVersion + 1,\n });\n const ids = obsolete.map(({ stage }) => stage.id);\n for (const id of ids) await releasePrincipalHistoryRoot(tx, `stage:${id}`);\n await tx\n .delete(principalHistoryStages)\n .where(inArray(principalHistoryStages.id, ids))\n .run();\n}\n"]}
|