@tearleads/client-sdk 0.1.58 → 0.1.60
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/Tearleads.d.ts +17 -17
- package/Tearleads.js +15 -15
- package/Tearleads.js.map +1 -1
- package/client/{blobs.d.ts → blobs/index.d.ts} +1 -1
- package/client/{blobs.js → blobs/index.js} +3 -3
- package/client/blobs/index.js.map +1 -0
- package/client/{containerDocumentDiscovery.js → containerContents/documentDiscovery.js} +11 -11
- package/client/containerContents/documentDiscovery.js.map +1 -0
- package/client/{containerContents.d.ts → containerContents/index.d.ts} +13 -13
- package/client/{containerContents.js → containerContents/index.js} +18 -18
- package/client/containerContents/index.js.map +1 -0
- package/client/{containerContentsTypes.d.ts → containerContents/types.d.ts} +14 -14
- package/client/containerContents/types.js +2 -0
- package/client/containerContents/types.js.map +1 -0
- package/client/{deviceFirst.d.ts → deviceFirst/index.d.ts} +7 -7
- package/client/{deviceFirst.js → deviceFirst/index.js} +11 -11
- package/client/deviceFirst/index.js.map +1 -0
- package/client/{reconciledDocumentContentPull.js → deviceFirst/reconciledDocumentContentPull.js} +1 -1
- package/client/deviceFirst/reconciledDocumentContentPull.js.map +1 -0
- package/client/{documents.d.ts → documents/index.d.ts} +5 -5
- package/client/{documents.js → documents/index.js} +5 -5
- package/client/documents/index.js.map +1 -0
- package/client/{identity.d.ts → identity/index.d.ts} +2 -2
- package/client/{identity.js → identity/index.js} +5 -5
- package/client/identity/index.js.map +1 -0
- package/client/{identityKeyPackage.d.ts → identity/keyPackage.d.ts} +1 -1
- package/client/{identityKeyPackage.js → identity/keyPackage.js} +4 -4
- package/client/identity/keyPackage.js.map +1 -0
- package/client/{userIdentities.d.ts → identity/userIdentities.d.ts} +2 -2
- package/client/{userIdentities.js → identity/userIdentities.js} +4 -4
- package/client/identity/userIdentities.js.map +1 -0
- package/client/index.d.ts +18 -18
- package/client/index.js +9 -9
- package/client/index.js.map +1 -1
- package/client/organizations/currentPrincipalMutations.js.map +1 -1
- package/client/organizations/index.d.ts +2 -2
- package/client/organizations/index.js.map +1 -1
- package/client/organizations/organizationAccessRestoration.js.map +1 -1
- package/client/organizations/organizationDataUsage.d.ts +1 -1
- package/client/organizations/organizationDataUsage.js.map +1 -1
- package/client/organizations/organizationGroupNameHydration.js.map +1 -1
- package/client/organizations/organizationGroupPresentation.d.ts +1 -1
- package/client/organizations/organizationGroupPresentation.js.map +1 -1
- package/client/organizations/organizationMetadataProfileSync.js +1 -1
- package/client/organizations/organizationMetadataProfileSync.js.map +1 -1
- package/client/organizations/organizationReadModels.d.ts +1 -1
- package/client/organizations/organizationReadModels.js.map +1 -1
- package/client/organizations/organizationWorkflowRuntime.js.map +1 -1
- package/client/organizations/organizationsTypes.d.ts +1 -1
- package/client/organizations/organizationsTypes.js.map +1 -1
- package/client/organizations/principalContainerMutations.js.map +1 -1
- package/client/organizations/principalMutationRecovery.d.ts +1 -1
- package/client/organizations/principalMutationRecovery.js.map +1 -1
- package/client/organizations/principalMutationScope.js.map +1 -1
- package/client/organizations/principalMutations.d.ts +2 -2
- package/client/organizations/principalMutations.js.map +1 -1
- package/client/root/index.d.ts +1 -1
- package/client/root/index.js.map +1 -1
- package/client/{database.d.ts → runtime/database.d.ts} +1 -1
- package/client/{database.js → runtime/database.js} +1 -1
- package/client/runtime/database.js.map +1 -0
- package/client/{principalHistoryProtection.d.ts → runtime/principalHistoryProtection.d.ts} +1 -1
- package/client/{principalHistoryProtection.js → runtime/principalHistoryProtection.js} +2 -2
- package/client/runtime/principalHistoryProtection.js.map +1 -0
- package/client/{principalMutationApi.d.ts → runtime/principalMutationApi.d.ts} +4 -4
- package/client/{principalMutationApi.js → runtime/principalMutationApi.js} +2 -2
- package/client/runtime/principalMutationApi.js.map +1 -0
- package/client/{principalMutationDispatch.js → runtime/principalMutationDispatch.js} +2 -2
- package/client/runtime/principalMutationDispatch.js.map +1 -0
- package/client/runtime/rootContainerAdoption.js.map +1 -0
- package/client/{workflowRuntime.d.ts → runtime/workflowRuntime.d.ts} +12 -12
- package/client/{workflowRuntime.js → runtime/workflowRuntime.js} +5 -5
- package/client/runtime/workflowRuntime.js.map +1 -0
- package/client/{securityIncidents.d.ts → securityIncidents/index.d.ts} +3 -3
- package/client/{securityIncidents.js → securityIncidents/index.js} +5 -5
- package/client/securityIncidents/index.js.map +1 -0
- package/client/session/index.js +1 -1
- package/client/session/index.js.map +1 -1
- package/client/session/sessionIdentityTrust.d.ts +1 -1
- package/client/session/sessionLoginRefusal.js.map +1 -1
- package/client/session/sessionOrganizationCreation.js.map +1 -1
- package/client/session/sessionPurgeRecovery.js.map +1 -1
- package/client/session/sessionRootAuthority.js.map +1 -1
- package/client/session/sessionTypes.d.ts +3 -3
- package/client/session/sessionTypes.js.map +1 -1
- package/data/blobs/createBlobStore.d.ts +1 -1
- package/data/blobs/createBlobStore.js.map +1 -1
- package/data/blobs/encryptedBlobByteSource.js +1 -1
- package/data/blobs/encryptedBlobByteSource.js.map +1 -1
- package/data/blobs/encryptedBlobEnvelope.d.ts +1 -1
- package/data/blobs/encryptedBlobEnvelope.js +2 -2
- package/data/blobs/encryptedBlobEnvelope.js.map +1 -1
- package/data/blobs/encryptedBlobStore.d.ts +1 -1
- package/data/blobs/encryptedBlobStore.js +1 -1
- package/data/blobs/encryptedBlobStore.js.map +1 -1
- package/data/blobs/memoryBlobStore.d.ts +1 -1
- package/data/blobs/memoryBlobStore.js +1 -1
- package/data/blobs/memoryBlobStore.js.map +1 -1
- package/data/blobs/opfsBlobStore.d.ts +1 -1
- package/data/blobs/opfsBlobStore.js +1 -1
- package/data/blobs/opfsBlobStore.js.map +1 -1
- package/data/containers/containerMetadataDocument.js +1 -1
- package/data/containers/containerMetadataDocument.js.map +1 -1
- package/data/containers/shared/events.js +1 -1
- package/data/containers/shared/events.js.map +1 -1
- package/data/containers/shared/heldContainerHeads.js +1 -1
- package/data/containers/shared/heldContainerHeads.js.map +1 -1
- package/data/containers/shared/mutationAcknowledgement.js +1 -1
- package/data/containers/shared/mutationAcknowledgement.js.map +1 -1
- package/data/containers/shared/principalPolicies.js +1 -1
- package/data/containers/shared/principalPolicies.js.map +1 -1
- package/data/containers/shared/readers.js +2 -2
- package/data/containers/shared/readers.js.map +1 -1
- package/data/documents/attachmentContentIdentity.js +1 -1
- package/data/documents/attachmentContentIdentity.js.map +1 -1
- package/data/documents/blob/shared/blobEnvelopeStream.js.map +1 -1
- package/data/documents/blob/shared/blobSourceSnapshot.d.ts +1 -1
- package/data/documents/blob/shared/blobSourceSnapshot.js.map +1 -1
- package/data/documents/blob/shared/chunkedBlobCrypto.js.map +1 -1
- package/data/documents/blob/shared/encryptedUploadParts.js.map +1 -1
- package/data/documents/blob/shared/events.js +1 -1
- package/data/documents/blob/shared/events.js.map +1 -1
- package/data/documents/blob/shared/types.d.ts +2 -2
- package/data/documents/blob/shared/types.js.map +1 -1
- package/data/documents/shared/containerKekPathHistory.js +1 -1
- package/data/documents/shared/containerKekPathHistory.js.map +1 -1
- package/data/documents/shared/containerKekPathVerification.d.ts +1 -1
- package/data/documents/shared/containerKekPathVerification.js +1 -1
- package/data/documents/shared/events.js +1 -1
- package/data/documents/shared/events.js.map +1 -1
- package/data/documents/shared/manifestBundleReaders.js +2 -2
- package/data/documents/shared/manifestBundleReaders.js.map +1 -1
- package/data/documents/shared/projection.d.ts +1 -1
- package/data/documents/shared/projection.js +2 -2
- package/data/documents/shared/projection.js.map +1 -1
- package/data/documents/shared/projectionContentKeys.d.ts +1 -1
- package/data/documents/shared/readers.js +3 -3
- package/data/documents/shared/readers.js.map +1 -1
- package/data/documents/shared/stableDocumentId.js +1 -1
- package/data/documents/shared/stableDocumentId.js.map +1 -1
- package/data/documents/shared/types.d.ts +1 -1
- package/data/documents/shared/types.js +1 -1
- package/data/{keyingCanonicalJson.js → keying/canonicalJson.js} +3 -3
- package/data/keying/canonicalJson.js.map +1 -0
- package/data/keyingProjectionVerification/bundleVerification.js +1 -1
- package/data/keyingProjectionVerification/bundleVerification.js.map +1 -1
- package/data/keyingProjectionVerification/containerAncestorCitations.js +1 -1
- package/data/keyingProjectionVerification/containerAncestorCitations.js.map +1 -1
- package/data/keyingProjectionVerification/containerManifestVerification.js +1 -1
- package/data/keyingProjectionVerification/containerManifestVerification.js.map +1 -1
- package/data/keyingProjectionVerification/documentManifestVerification.js +1 -1
- package/data/keyingProjectionVerification/documentManifestVerification.js.map +1 -1
- package/data/keyingProjectionVerification/documentPurgeDocumentChainVerification.js +1 -1
- package/data/keyingProjectionVerification/documentPurgeDocumentChainVerification.js.map +1 -1
- package/data/keyingProjectionVerification/error.js +1 -1
- package/data/keyingProjectionVerification/error.js.map +1 -1
- package/data/keyingProjectionVerification/index.d.ts +9 -0
- package/data/{keyingProjectionVerification.js → keyingProjectionVerification/index.js} +8 -8
- package/data/keyingProjectionVerification/index.js.map +1 -0
- package/data/keyingProjectionVerification/principalPolicyCache.js +1 -1
- package/data/keyingProjectionVerification/principalPolicyCache.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicyVerification.js +1 -1
- package/data/keyingProjectionVerification/principalPolicyVerification.js.map +1 -1
- package/data/keyingProjectionVerification/readers.d.ts +1 -1
- package/data/keyingProjectionVerification/readers.js +3 -3
- package/data/keyingProjectionVerification/readers.js.map +1 -1
- package/data/keyingProjectionVerification/userKeyResolver.d.ts +1 -1
- package/data/keyingProjectionVerification/userKeyResolver.js.map +1 -1
- package/data/persistence/containers/containerPersistence.js +1 -1
- package/data/persistence/containers/containerPersistence.js.map +1 -1
- package/data/persistence/documents/documentDiscoveryCandidate.js +1 -1
- package/data/persistence/documents/documentDiscoveryCandidate.js.map +1 -1
- package/data/persistence/documents/documentDiscoveryEvidencePersistence.js +1 -1
- package/data/persistence/documents/documentDiscoveryEvidencePersistence.js.map +1 -1
- package/data/persistence/documents/internal/documentProjectionRows.js +1 -1
- package/data/persistence/documents/internal/documentProjectionRows.js.map +1 -1
- package/data/persistence/documents/internal/documentRows.js +1 -1
- package/data/persistence/documents/internal/documentRows.js.map +1 -1
- package/data/persistence/principalPolicyBundleIntegrity.js +1 -1
- package/data/persistence/principalPolicyBundleIntegrity.js.map +1 -1
- package/data/persistence/principalPolicyReferenceCheckpoint.js +1 -1
- package/data/persistence/principalPolicyReferenceCheckpoint.js.map +1 -1
- package/data/persistence/principalPolicyReferenceIndexPersistence.js +1 -1
- package/data/persistence/principalPolicyReferenceIndexPersistence.js.map +1 -1
- package/data/persistence/principalPolicyReferencePersistence.js +1 -1
- package/data/persistence/principalPolicyReferencePersistence.js.map +1 -1
- package/data/persistence/securityIncidentPersistence.js.map +1 -1
- package/data/persistence/verifiedPrincipalPolicyBundle.js +1 -1
- package/data/persistence/verifiedPrincipalPolicyBundle.js.map +1 -1
- package/data/persistence/verifiedPrincipalPolicyCurrent.js +1 -1
- package/data/persistence/verifiedPrincipalPolicyCurrent.js.map +1 -1
- package/data/principals/principalMutationJournal.js +1 -1
- package/data/principals/principalMutationJournal.js.map +1 -1
- package/data/{securityIncidents.d.ts → shared/securityIncidents.d.ts} +1 -1
- package/data/sqlite/documentRecordPersistence.js +1 -1
- package/data/sqlite/documentRecordPersistence.js.map +1 -1
- package/data/sync/crdtPeerSeed.d.ts +18 -0
- package/data/sync/originatedDocuments.d.ts +1 -1
- package/data/sync/originatedDocuments.js.map +1 -1
- package/data/sync/syncCoordinator.d.ts +1 -1
- package/data/sync/syncCoordinator.js.map +1 -1
- package/package.json +1 -1
- package/stores/container-contents/backgroundHydration.js +1 -1
- package/stores/container-contents/backgroundHydration.js.map +1 -1
- package/stores/container-contents/containerContentsStore.d.ts +1 -1
- package/stores/container-contents/containerContentsStore.js.map +1 -1
- package/stores/container-contents/localRefresh.js +1 -1
- package/stores/container-contents/localRefresh.js.map +1 -1
- package/stores/container-contents/remoteContainerIngestion.js +1 -1
- package/stores/container-contents/remoteContainerIngestion.js.map +1 -1
- package/stores/container-contents/remoteWriteQueue.js +1 -1
- package/stores/container-contents/remoteWriteQueue.js.map +1 -1
- package/stores/container-contents/systemContainerHydration.js +1 -1
- package/stores/container-contents/systemContainerHydration.js.map +1 -1
- package/stores/container-contents/utils.js +1 -1
- package/stores/container-contents/utils.js.map +1 -1
- package/stores/documents/documentStore/attachmentIntents.js +1 -1
- package/stores/documents/documentStore/attachmentIntents.js.map +1 -1
- package/stores/documents/documentStore/attachmentSourceUpload.js.map +1 -1
- package/stores/documents/documentStore/attachmentStaging.js +1 -1
- package/stores/documents/documentStore/attachmentStaging.js.map +1 -1
- package/stores/documents/documentStore/attachmentUploadLane.js.map +1 -1
- package/stores/documents/documentStore/persistence.js +2 -2
- package/stores/documents/documentStore/persistence.js.map +1 -1
- package/stores/documents/documentStore/state.js +1 -1
- package/stores/documents/documentStore/state.js.map +1 -1
- package/stores/documents/documentStore/storedDocument.js +1 -1
- package/stores/documents/documentStore/storedDocument.js.map +1 -1
- package/stores/documents/documentStore/syncAttachments.js.map +1 -1
- package/stores/documents/documentStore.d.ts +1 -1
- package/stores/documents/documentStore.js.map +1 -1
- package/stores/documents/registry.d.ts +1 -1
- package/stores/documents/registry.js.map +1 -1
- package/stores/documents/types.d.ts +1 -1
- package/stores/documents/types.js.map +1 -1
- package/stores/local-projection/registry.d.ts +1 -1
- package/stores/local-projection/registry.js.map +1 -1
- package/sync/reconciliation/serviceTypes.d.ts +1 -1
- package/sync/reconciliation/serviceTypes.js.map +1 -1
- package/sync/reconciliation/triggers.d.ts +1 -1
- package/sync/reconciliation/triggers.js.map +1 -1
- package/workflows/blobs/attachmentBindingVerification.js +2 -2
- package/workflows/blobs/attachmentBindingVerification.js.map +1 -1
- package/workflows/blobs/blobChunkDecryption.js.map +1 -1
- package/workflows/blobs/decrypt.d.ts +1 -1
- package/workflows/blobs/decrypt.js +2 -2
- package/workflows/blobs/decrypt.js.map +1 -1
- package/workflows/blobs/detach.js +2 -2
- package/workflows/blobs/detach.js.map +1 -1
- package/workflows/blobs/hydrate.d.ts +3 -3
- package/workflows/blobs/hydrate.js +1 -1
- package/workflows/blobs/hydrate.js.map +1 -1
- package/workflows/blobs/hydrationResults.js.map +1 -1
- package/workflows/blobs/index.d.ts +2 -2
- package/workflows/blobs/index.js +1 -1
- package/workflows/blobs/index.js.map +1 -1
- package/workflows/blobs/multipartFirstParts.js.map +1 -1
- package/workflows/blobs/retainedAttachmentVerification.js +1 -1
- package/workflows/blobs/upload.js +3 -3
- package/workflows/blobs/upload.js.map +1 -1
- package/workflows/container-contents/container-state/createAdoption.js +1 -1
- package/workflows/container-contents/container-state/createAdoption.js.map +1 -1
- package/workflows/container-contents/container-state/createChild.js +1 -1
- package/workflows/container-contents/container-state/createChild.js.map +1 -1
- package/workflows/container-contents/container-state/createIntentSync.js +1 -1
- package/workflows/container-contents/container-state/createIntentSync.js.map +1 -1
- package/workflows/container-contents/container-state/groupGrantVerification.js +1 -1
- package/workflows/container-contents/container-state/moveIntentSync.js +1 -1
- package/workflows/container-contents/container-state/moveIntentSync.js.map +1 -1
- package/workflows/container-contents/container-state/purgeTreeScope.js +1 -1
- package/workflows/container-contents/container-state/purgeTreeScope.js.map +1 -1
- package/workflows/container-contents/container-state/share.js +1 -1
- package/workflows/container-contents/documentDiscoveryInputs.js +1 -1
- package/workflows/container-contents/documentDiscoveryInputs.js.map +1 -1
- package/workflows/container-contents/documentInfo.d.ts +1 -1
- package/workflows/container-contents/documentInfo.js.map +1 -1
- package/workflows/container-contents/documentLinks.d.ts +1 -1
- package/workflows/container-contents/documentLinks.js +1 -1
- package/workflows/container-contents/documentLinks.js.map +1 -1
- package/workflows/container-contents/documentMoveIntentSync.js +1 -1
- package/workflows/container-contents/documentMoveIntentSync.js.map +1 -1
- package/workflows/container-contents/documentPurge.d.ts +1 -1
- package/workflows/container-contents/documentPurge.js +1 -1
- package/workflows/container-contents/documentPurge.js.map +1 -1
- package/workflows/container-contents/documentQueries/rows.js +1 -1
- package/workflows/container-contents/documentQueries/rows.js.map +1 -1
- package/workflows/container-contents/metadata.d.ts +1 -1
- package/workflows/container-contents/metadataMutationPreparation.js +1 -1
- package/workflows/container-contents/metadataMutationPreparation.js.map +1 -1
- package/workflows/container-contents/metadataRemoteSync.d.ts +1 -1
- package/workflows/container-contents/metadataSyncErrors.js.map +1 -1
- package/workflows/container-contents/projectionKeys.d.ts +1 -1
- package/workflows/container-contents/syncLane.d.ts +1 -1
- package/workflows/container-contents/syncLane.js.map +1 -1
- package/workflows/containers/child/carriedDescendantRekeys.js +1 -1
- package/workflows/containers/child/create.d.ts +1 -1
- package/workflows/containers/child/create.js +2 -2
- package/workflows/containers/child/create.js.map +1 -1
- package/workflows/containers/child/createProjection.js +1 -1
- package/workflows/containers/child/createProjection.js.map +1 -1
- package/workflows/containers/child/createSubmission.d.ts +2 -2
- package/workflows/containers/child/createSubmission.js.map +1 -1
- package/workflows/containers/child/move.d.ts +2 -2
- package/workflows/containers/child/move.js +2 -2
- package/workflows/containers/child/move.js.map +1 -1
- package/workflows/containers/child/moveWraps.js +1 -1
- package/workflows/containers/child/mutationRequestCore.js +1 -1
- package/workflows/containers/child/mutationRequestCore.js.map +1 -1
- package/workflows/containers/child/mutationSubmit.js.map +1 -1
- package/workflows/containers/child/recite.js.map +1 -1
- package/workflows/containers/child/recitePlan.js +1 -1
- package/workflows/containers/child/recitePlan.js.map +1 -1
- package/workflows/containers/child/rekey.d.ts +1 -1
- package/workflows/containers/child/rekey.js +2 -2
- package/workflows/containers/child/rekey.js.map +1 -1
- package/workflows/containers/child/rekeyProjection.js +1 -1
- package/workflows/containers/child/rekeyProjection.js.map +1 -1
- package/workflows/containers/child/rekeyRemote.d.ts +2 -2
- package/workflows/containers/child/rekeyRemote.js.map +1 -1
- package/workflows/containers/child/revoke.d.ts +2 -2
- package/workflows/containers/child/revoke.js +2 -2
- package/workflows/containers/child/revoke.js.map +1 -1
- package/workflows/containers/child/rotationPrincipalPolicies.js +1 -1
- package/workflows/containers/child/runtimeCurrentGroupShare.js +1 -1
- package/workflows/containers/child/share.d.ts +2 -2
- package/workflows/containers/child/share.js +1 -1
- package/workflows/containers/child/share.js.map +1 -1
- package/workflows/containers/child/shareAncestorRepair.js.map +1 -1
- package/workflows/containers/child/shareMaterialization.d.ts +1 -1
- package/workflows/containers/child/sharePlanCore.d.ts +1 -1
- package/workflows/containers/child/sharePlanCore.js +1 -1
- package/workflows/containers/root/create.js +1 -1
- package/workflows/containers/root/create.js.map +1 -1
- package/workflows/containers/root/initialGroupPolicy.js +1 -1
- package/workflows/containers/root/initialGroupPolicy.js.map +1 -1
- package/workflows/documents/create.d.ts +1 -1
- package/workflows/documents/create.js +1 -1
- package/workflows/documents/documentMutationPreparation.js +1 -1
- package/workflows/documents/documentMutationPreparation.js.map +1 -1
- package/workflows/documents/historyContent.js +1 -1
- package/workflows/documents/historyContent.js.map +1 -1
- package/workflows/documents/linkSet.js +1 -1
- package/workflows/documents/linkSet.js.map +1 -1
- package/workflows/documents/linkSetAuthority.js +1 -1
- package/workflows/documents/linkSetBlobRewraps.js +2 -2
- package/workflows/documents/linkSetBlobRewraps.js.map +1 -1
- package/workflows/documents/linkSetRemote.d.ts +1 -1
- package/workflows/documents/linkSetRemote.js +1 -1
- package/workflows/documents/orphanBlobReclaims.js +1 -1
- package/workflows/documents/orphanBlobReclaims.js.map +1 -1
- package/workflows/documents/projectionKeys.d.ts +1 -1
- package/workflows/documents/purge.d.ts +1 -1
- package/workflows/documents/purge.js +2 -2
- package/workflows/documents/purge.js.map +1 -1
- package/workflows/documents/readOnlySync.d.ts +1 -1
- package/workflows/documents/readOnlySync.js +1 -1
- package/workflows/documents/readOnlySync.js.map +1 -1
- package/workflows/documents/sync.js +1 -1
- package/workflows/documents/syncContainerRekeyPreparation.js +1 -1
- package/workflows/documents/syncLane.d.ts +1 -1
- package/workflows/documents/syncLane.js.map +1 -1
- package/workflows/documents/syncPlanIdentity.js +1 -1
- package/workflows/documents/syncPlanIdentity.js.map +1 -1
- package/workflows/documents/syncRepairAccess.js +1 -1
- package/workflows/documents/syncSubmittedResult.js +1 -1
- package/workflows/organizations/authoredPrincipalPolicyWarmer.js +1 -1
- package/workflows/organizations/authoredPrincipalPolicyWarmer.js.map +1 -1
- package/workflows/organizations/containerGrantRevocation.d.ts +2 -2
- package/workflows/organizations/containerGrantRevocation.js.map +1 -1
- package/workflows/organizations/createCurrentOrganizationGroup.js.map +1 -1
- package/workflows/organizations/currentOrganizationGroupNames.js.map +1 -1
- package/workflows/organizations/currentPolicyMutationAcknowledgement.js +1 -1
- package/workflows/organizations/currentPolicyMutationAcknowledgement.js.map +1 -1
- package/workflows/organizations/groupCreation.d.ts +1 -1
- package/workflows/organizations/groupCreation.js.map +1 -1
- package/workflows/organizations/groupMetadataAccess.d.ts +1 -1
- package/workflows/organizations/groupMetadataContainerAuthority.js.map +1 -1
- package/workflows/organizations/groupMetadataRuntime.js.map +1 -1
- package/workflows/organizations/groupNameUniqueness.js.map +1 -1
- package/workflows/organizations/groupPolicyMutationAcknowledgement.js +1 -1
- package/workflows/organizations/groupPolicyMutationAcknowledgement.js.map +1 -1
- package/workflows/organizations/groupPolicyRequests.js.map +1 -1
- package/workflows/organizations/loadPolicyHistoryDetails.js.map +1 -1
- package/workflows/organizations/organizationGroupDirectory.js.map +1 -1
- package/workflows/organizations/organizationProfile.js +1 -1
- package/workflows/organizations/organizationProfile.js.map +1 -1
- package/workflows/organizations/policyHistoryCache.js.map +1 -1
- package/workflows/organizations/principalContainerRematerialization.js +1 -1
- package/workflows/organizations/principalContainerRematerializationPlanning.js.map +1 -1
- package/workflows/organizations/principalMutationJournalManagement.js +1 -1
- package/workflows/organizations/principalMutationJournalManagement.js.map +1 -1
- package/workflows/organizations/principalMutationReceipt.js +1 -1
- package/workflows/organizations/principalMutationReceipt.js.map +1 -1
- package/workflows/organizations/principalPolicy.d.ts +1 -1
- package/workflows/organizations/principalPolicy.js.map +1 -1
- package/workflows/organizations/principalPolicyReceiptArtifacts.js +1 -1
- package/workflows/organizations/principalPolicyReceiptArtifacts.js.map +1 -1
- package/workflows/organizations/rosterProfileContainer.js +1 -1
- package/workflows/organizations/rosterProfileContainer.js.map +1 -1
- package/workflows/principals/policyCache.d.ts +1 -1
- package/workflows/principals/policyCache.js +2 -2
- package/workflows/principals/policyCache.js.map +1 -1
- package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
- package/workflows/principals/runtimePolicyWarmer.js +1 -1
- package/workflows/principals/runtimePolicyWarmer.js.map +1 -1
- package/workflows/registration/persistRegistrationBootstrap.js +1 -1
- package/workflows/registration/persistRegistrationBootstrap.js.map +1 -1
- package/workflows/runtimeInput.d.ts +3 -3
- package/workflows/runtimeInput.js.map +1 -1
- package/workflows/sync/index.d.ts +2 -1
- package/workflows/sync/index.js +2 -1
- package/workflows/sync/index.js.map +1 -1
- package/client/blobs.js.map +0 -1
- package/client/containerContents.js.map +0 -1
- package/client/containerContentsTypes.js +0 -2
- package/client/containerContentsTypes.js.map +0 -1
- package/client/containerDocumentDiscovery.js.map +0 -1
- package/client/database.js.map +0 -1
- package/client/deviceFirst.js.map +0 -1
- package/client/documents.js.map +0 -1
- package/client/identity.js.map +0 -1
- package/client/identityKeyPackage.js.map +0 -1
- package/client/principalHistoryProtection.js.map +0 -1
- package/client/principalMutationApi.js.map +0 -1
- package/client/principalMutationDispatch.js.map +0 -1
- package/client/reconciledDocumentContentPull.js.map +0 -1
- package/client/rootContainerAdoption.js.map +0 -1
- package/client/securityIncidents.js.map +0 -1
- package/client/userIdentities.js.map +0 -1
- package/client/workflowRuntime.js.map +0 -1
- package/data/keyingCanonicalJson.js.map +0 -1
- package/data/keyingProjectionVerification.d.ts +0 -9
- package/data/keyingProjectionVerification.js.map +0 -1
- /package/client/{fileSaver.d.ts → host/fileSaver.d.ts} +0 -0
- /package/client/{fileSaver.js → host/fileSaver.js} +0 -0
- /package/client/{fileSaver.js.map → host/fileSaver.js.map} +0 -0
- /package/client/{logger.d.ts → host/logger.d.ts} +0 -0
- /package/client/{logger.js → host/logger.js} +0 -0
- /package/client/{logger.js.map → host/logger.js.map} +0 -0
- /package/client/{apiVersion.d.ts → runtime/apiVersion.d.ts} +0 -0
- /package/client/{apiVersion.js → runtime/apiVersion.js} +0 -0
- /package/client/{apiVersion.js.map → runtime/apiVersion.js.map} +0 -0
- /package/client/{events.d.ts → runtime/events.d.ts} +0 -0
- /package/client/{events.js → runtime/events.js} +0 -0
- /package/client/{events.js.map → runtime/events.js.map} +0 -0
- /package/client/{listenerSet.js → runtime/listenerSet.js} +0 -0
- /package/client/{listenerSet.js.map → runtime/listenerSet.js.map} +0 -0
- /package/client/{network.d.ts → runtime/network.d.ts} +0 -0
- /package/client/{network.js → runtime/network.js} +0 -0
- /package/client/{network.js.map → runtime/network.js.map} +0 -0
- /package/client/{principalMutationDeadline.js → runtime/principalMutationDeadline.js} +0 -0
- /package/client/{principalMutationDeadline.js.map → runtime/principalMutationDeadline.js.map} +0 -0
- /package/client/{rootContainerAdoption.js → runtime/rootContainerAdoption.js} +0 -0
- /package/client/{syncBillingGate.d.ts → runtime/syncBillingGate.d.ts} +0 -0
- /package/client/{syncBillingGate.js → runtime/syncBillingGate.js} +0 -0
- /package/client/{syncBillingGate.js.map → runtime/syncBillingGate.js.map} +0 -0
- /package/data/{blobContracts.d.ts → blobs/blobContracts.d.ts} +0 -0
- /package/data/{blobContracts.js → blobs/blobContracts.js} +0 -0
- /package/data/{blobContracts.js.map → blobs/blobContracts.js.map} +0 -0
- /package/data/{accessLevel.js → keying/accessLevel.js} +0 -0
- /package/data/{accessLevel.js.map → keying/accessLevel.js.map} +0 -0
- /package/data/{stableUuid.js → keying/stableUuid.js} +0 -0
- /package/data/{stableUuid.js.map → keying/stableUuid.js.map} +0 -0
- /package/data/{principalPolicyStates.js → principals/principalPolicyStates.js} +0 -0
- /package/data/{principalPolicyStates.js.map → principals/principalPolicyStates.js.map} +0 -0
- /package/data/{domainScope.d.ts → shared/domainScope.d.ts} +0 -0
- /package/data/{domainScope.js → shared/domainScope.js} +0 -0
- /package/data/{domainScope.js.map → shared/domainScope.js.map} +0 -0
- /package/data/{errorMessage.js → shared/errorMessage.js} +0 -0
- /package/data/{errorMessage.js.map → shared/errorMessage.js.map} +0 -0
- /package/data/{recordReaders.d.ts → shared/recordReaders.d.ts} +0 -0
- /package/data/{recordReaders.js → shared/recordReaders.js} +0 -0
- /package/data/{recordReaders.js.map → shared/recordReaders.js.map} +0 -0
- /package/data/{securityIncidents.js → shared/securityIncidents.js} +0 -0
- /package/data/{securityIncidents.js.map → shared/securityIncidents.js.map} +0 -0
- /package/data/{crdtPeerSeed.js → sync/crdtPeerSeed.js} +0 -0
- /package/data/{crdtPeerSeed.js.map → sync/crdtPeerSeed.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"share.js","sourceRoot":"","sources":["share.ts"],"names":[],"mappings":"AAgBA,OAAO,EACL,sCAAsC,EACtC,wCAAwC,EAGxC,gCAAgC,GACjC,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,uCAAuC,EAAE,MAAM,iEAAiE,CAAC;AAC1H,OAAO,EAAE,yBAAyB,EAAE,MAAM,sDAAsD,CAAC;AAGjG,OAAO,EACL,kCAAkC,GAEnC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,yBAAyB,EAAE,MAAM,yCAAyC,CAAC;AACpF,OAAO,EAAE,oCAAoC,EAAE,MAAM,qDAAqD,CAAC;AAC3G,OAAO,EAAE,+CAA+C,EAAE,MAAM,yDAAyD,CAAC;AAC1H,OAAO,EAAE,kCAAkC,EAAE,MAAM,qCAAqC,CAAC;AAEzF,OAAO,EACL,mCAAmC,EACnC,4BAA4B,GAC7B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,mCAAmC,EAAE,MAAM,wBAAwB,CAAC;AAC7E,OAAO,EACL,4BAA4B,EAE5B,qCAAqC,GACtC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAE3D,MAAM,oCAAqC,SAAQ,KAAK;CAAG;AAE3D,KAAK,UAAU,8BAA8B,CAC3C,KAAgE;IAEhE,OAAO,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C,MAAM,EAAE,GAAG,EAAE,CACX,4BAA4B,CAAC,GAAG,EAAE,CAChC,KAAK,CAAC,SAAS,CAAC,cAAc,CAC5B,KAAK,CAAC,WAAW,EACjB,gBAAgB,CAAC,IAAI,CAAC,OAAO,EAC7B;YACE,qCAAqC,EAAE,KAAK,CAAC,MAAM,CAAC,cAAc;SACnE,CACF,CACF;KACJ,CAAC,CAAC;IACH,IAAI,CAAC,MAAM;QAAE,OAAO,IAAI,CAAC;IAEzB,2EAA2E;IAC3E,yEAAyE;IACzE,0EAA0E;IAC1E,sDAAsD;IACtD,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK,EAAE,CAAC;QACrC,MAAM,yBAAyB,CAC7B,KAAK,CAAC,OAAO,EACb,uBAAuB,CAAC,MAAM,EAC9B,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,EACxB,KAAK,CAAC,MAAM,CAAC,cAAc,EAC3B,EAAE,YAAY,EAAE,KAAK,CAAC,YAAY,EAAE,CACrC,CAAC;IACJ,CAAC;IACD,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IAElD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type {\n ContainerAccessLevel,\n SigningKeyPair,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n ContainerMutationResponse,\n ContainerWriterProjectionResponse,\n PrincipalPolicyBundleResponse,\n} from \"@tearleads/validators/response\";\nimport type {\n ContainerMutationAuthor,\n ContainerShareApi,\n ContainerSharePlan,\n MaterializedContainerSharePlan,\n} from \"../../../data/containers/shared/types\";\nimport {\n isProjectionVerificationCancelledError,\n nullOnProjectionVerificationCancellation,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n requireProjectionUserKeyResolver,\n} from \"../../../data/keyingProjectionVerification\";\nimport { principalPolicyCacheForVerifiedPolicies } from \"../../../data/keyingProjectionVerification/principalPolicyCache\";\nimport { savePrincipalPolicyBundle } from \"../../../data/persistence/principalPolicyPersistence\";\nimport type { SecurityIncidentReporter } from \"../../../data/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n requireTrustedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n} from \"../../../data/trustedUserIdentity\";\nimport { createGroupMetadataAccess } from \"../../organizations/groupMetadataAccess\";\nimport { createGroupMetadataContainerVerifier } from \"../../organizations/groupMetadataContainerAuthority\";\nimport { preparePrincipalContainerRematerializationBatch } from \"../../organizations/principalContainerRematerialization\";\nimport { setOrganizationGroupContainerGrant } from \"../../organizations/principalPolicy\";\nimport type { GroupPolicyNameReader } from \"../../organizations/principalPolicyRequest\";\nimport {\n submitAcknowledgedContainerMutation,\n submitPlainContainerMutation,\n} from \"./mutationSubmit\";\nimport { buildMaterializedContainerSharePlan } from \"./shareMaterialization\";\nimport {\n advanceVerifiedSharePolicies,\n type ContainerManagedPrincipalShareApi,\n loadVerifiedGroupSharePrincipalPolicy,\n} from \"./sharePrincipalPolicy\";\nimport { resolveShareProjection } from \"./shareProjection\";\n\nclass ContainerShareGenerationExpiredError extends Error {}\n\nasync function buildCurrentContainerSharePlan(\n input: Parameters<typeof buildMaterializedContainerSharePlan>[0],\n): Promise<MaterializedContainerSharePlan | null> {\n return nullOnProjectionVerificationCancellation(() =>\n buildMaterializedContainerSharePlan(input),\n );\n}\n\nexport async function shareRemoteContainer(input: {\n reportSecurityIncident: SecurityIncidentReporter;\n accessLevel: ContainerAccessLevel;\n apiClient: ContainerShareApi;\n author: ContainerMutationAuthor;\n containerId: string;\n eventId?: string | undefined;\n execSql: ExecSql;\n previousProjection?: ContainerWriterProjectionResponse | undefined;\n recipientUserId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n signedAt?: string | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<{\n containerKey: Uint8Array;\n plan: ContainerSharePlan;\n response: ContainerMutationResponse;\n} | null> {\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote container share\",\n );\n const resolveTrustedUserIdentity = requireTrustedUserIdentityResolver(\n input.resolveTrustedUserIdentity,\n );\n const recipientIdentity = await resolveTrustedUserIdentity(\n input.recipientUserId,\n );\n if (!recipientIdentity || input.stillCurrent?.() === false) {\n return null;\n }\n const previousProjection = await resolveShareProjection(\n input,\n resolveProjectionUserKey,\n );\n if (!previousProjection) return null;\n\n const materializedPlan = await buildCurrentContainerSharePlan({\n accessLevel: input.accessLevel,\n author: input.author,\n eventId: input.eventId,\n execSql: input.execSql,\n previousProjection,\n recipient: {\n recipientEncapsulationPublicKey: recipientIdentity.encapsulationPublicKey,\n subjectId: input.recipientUserId,\n subjectType: \"user\",\n },\n resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n if (!materializedPlan) return null;\n return submitAcknowledgedContainerMutation({\n reportSecurityIncident: input.reportSecurityIncident,\n recitationPolicies: [],\n apiClient: input.apiClient,\n author: input.author,\n containerKey: materializedPlan.containerKey,\n execSql: input.execSql,\n plan: materializedPlan.plan,\n stillCurrent: input.stillCurrent,\n submit: () =>\n submitPlainContainerMutation(() =>\n input.apiClient.shareContainer(\n input.containerId,\n materializedPlan.plan.request,\n {\n expectedPaymentRequiredOrganizationId: input.author.organizationId,\n },\n ),\n ),\n });\n}\n\ninterface RemoteContainerGroupShareInput {\n reportSecurityIncident: SecurityIncidentReporter;\n accessLevel: ContainerAccessLevel;\n apiClient: ContainerManagedPrincipalShareApi;\n author: ContainerMutationAuthor;\n containerId: string;\n eventId?: string | undefined;\n execSql: ExecSql;\n /**\n * The display name the user chose the group by, checked against the name\n * committed in the verified group policy so a relabeled read-model row\n * cannot redirect the share onto another group. `null` is reserved for the\n * grant-preserving re-wrap: a share that would mint a new grant without a\n * name is refused.\n */\n expectedGroupName: string | null;\n readEncryptedName?: GroupPolicyNameReader | undefined;\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n previousProjection?: ContainerWriterProjectionResponse | undefined;\n recipientGroupId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n signedAt?: string | undefined;\n signingKeyPair?: SigningKeyPair | null | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}\n\ninterface RemoteContainerGroupShareResult {\n containerKey: Uint8Array;\n plan: ContainerSharePlan;\n response: ContainerMutationResponse;\n}\n\nfunction isMaterializedContainerSharePlan(\n value: Awaited<\n ReturnType<typeof preparePrincipalContainerRematerializationBatch>\n >[\"plans\"][number],\n): value is MaterializedContainerSharePlan {\n return value.plan.body.eventType === \"container.grant\";\n}\n\nasync function prepareMissingGroupGrantMutations(input: {\n currentPolicy: PrincipalPolicyBundleResponse;\n nextPolicy: VerifiedPrincipalPolicy;\n shareInput: RemoteContainerGroupShareInput;\n}) {\n const { currentPolicy, nextPolicy, shareInput } = input;\n return preparePrincipalContainerRematerializationBatch({\n reportSecurityIncident: shareInput.reportSecurityIncident,\n apiClient: shareInput.apiClient,\n author: shareInput.author,\n execSql: shareInput.execSql,\n grants: [\n ...new Map(\n [...currentPolicy.currentGrants, ...nextPolicy.grants].map(\n (grant) => [grant.containerId, grant] as const,\n ),\n ).values(),\n ],\n groupId: shareInput.recipientGroupId,\n nextPolicy,\n resolveTrustedUserIdentity: shareInput.resolveTrustedUserIdentity,\n stillCurrent: shareInput.stillCurrent,\n targetSecretKey: shareInput.targetSecretKey,\n warmReferencedPrincipalPolicies: shareInput.warmReferencedPrincipalPolicies,\n });\n}\n\nasync function commitMissingGroupGrantPolicy(\n input: RemoteContainerGroupShareInput,\n): Promise<{\n preparedTarget: Awaited<\n ReturnType<typeof preparePrincipalContainerRematerializationBatch>\n >;\n storedPolicy: Awaited<ReturnType<typeof setOrganizationGroupContainerGrant>>;\n} | null> {\n const signingKeyPair = input.signingKeyPair;\n if (!signingKeyPair) {\n throw new Error(\n \"Container group share requires principal policy signing context\",\n );\n }\n const policyApi = {\n recoverPendingPrincipalMutation:\n input.apiClient.recoverPendingPrincipalMutation?.bind(input.apiClient),\n commitOrganizationGroupPolicy:\n input.apiClient.commitOrganizationGroupPolicy.bind(input.apiClient),\n getCurrentPrincipalPolicy: input.apiClient.getCurrentPrincipalPolicy.bind(\n input.apiClient,\n ),\n };\n let preparedTarget:\n | Awaited<\n ReturnType<typeof preparePrincipalContainerRematerializationBatch>\n >\n | undefined;\n try {\n const storedPolicy = await setOrganizationGroupContainerGrant({\n accessLevel: input.accessLevel,\n apiClient: policyApi,\n assertCanCommit: () => {\n if (input.stillCurrent?.() === false) {\n throw new ContainerShareGenerationExpiredError();\n }\n },\n containerId: input.containerId,\n execSql: input.execSql,\n groupId: input.recipientGroupId,\n organizationId: input.author.organizationId,\n prepareContainerMutations: async ({ currentPolicy, nextPolicy }) => {\n preparedTarget = await prepareMissingGroupGrantMutations({\n currentPolicy,\n nextPolicy,\n shareInput: input,\n });\n return preparedTarget;\n },\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n signerUserId: input.author.signerUserId,\n signingFingerprint: input.author.signerKeyFingerprint,\n signingKeyPair,\n });\n if (!preparedTarget) {\n throw new Error(\"Container group share preparation is incomplete\");\n }\n return { preparedTarget, storedPolicy };\n } catch (error) {\n if (\n error instanceof ContainerShareGenerationExpiredError ||\n isProjectionVerificationCancelledError(error)\n ) {\n return null;\n }\n throw error;\n }\n}\n\nasync function commitMissingGroupGrant(\n input: RemoteContainerGroupShareInput,\n): Promise<RemoteContainerGroupShareResult | null> {\n if (!input.signingKeyPair) {\n throw new Error(\n \"Container group share requires principal policy signing context\",\n );\n }\n if (input.stillCurrent?.() === false) return null;\n const committed = await commitMissingGroupGrantPolicy(input);\n if (!committed) return null;\n const { preparedTarget, storedPolicy } = committed;\n const targetIndex = preparedTarget?.plans.findIndex(\n (planned) => planned.plan.containerId === input.containerId,\n );\n const response =\n targetIndex === undefined || targetIndex < 0\n ? undefined\n : storedPolicy.containerMutations[targetIndex];\n const targetPlan =\n targetIndex === undefined || targetIndex < 0\n ? undefined\n : preparedTarget?.plans[targetIndex];\n if (\n !targetPlan ||\n !response ||\n !isMaterializedContainerSharePlan(targetPlan)\n ) {\n throw new Error(\"Container group share acknowledgement is incomplete\");\n }\n return {\n containerKey: targetPlan.containerKey,\n plan: targetPlan.plan,\n response,\n };\n}\n\n// Only a re-wrap of an existing signed grant may run without the chosen name;\n// minting a grant is exactly the operation the name binding protects.\nfunction assertGrantMintNamed(expectedGroupName: string | null): void {\n if (expectedGroupName === null) {\n throw new Error(\n \"Minting a group grant requires the chosen group name; only a re-wrap of an existing signed grant may omit it\",\n );\n }\n}\n\nfunction loadShareGroupPolicy(input: RemoteContainerGroupShareInput) {\n return loadVerifiedGroupSharePrincipalPolicy({\n apiClient: input.apiClient,\n execSql: input.execSql,\n expectedGroupName: input.expectedGroupName ?? undefined,\n readEncryptedName:\n input.readEncryptedName ??\n createGroupMetadataAccess({\n ...input,\n organizationId: input.author.organizationId,\n verifyMetadataContainer: createGroupMetadataContainerVerifier({\n ...input,\n organizationId: input.author.organizationId,\n stillCurrent: input.stillCurrent ?? (() => true),\n }),\n }).readName,\n groupId: input.recipientGroupId,\n organizationId: input.author.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n}\n\nexport async function shareRemoteContainerWithGroup(\n input: RemoteContainerGroupShareInput,\n): Promise<RemoteContainerGroupShareResult | null> {\n if (input.stillCurrent?.() === false) return null;\n await input.apiClient.recoverPendingPrincipalMutation?.(\n input.author.organizationId,\n );\n if (input.stillCurrent?.() === false) return null;\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote container share\",\n );\n const previousProjection = await resolveShareProjection(\n input,\n resolveProjectionUserKey,\n );\n if (!previousProjection) return null;\n const verifiedPrincipalPolicy = await loadShareGroupPolicy(input);\n if (input.stillCurrent?.() === false) return null;\n await advanceVerifiedSharePolicies(\n input.execSql,\n verifiedPrincipalPolicy,\n input.stillCurrent,\n );\n if (input.stillCurrent?.() === false) return null;\n\n const signedGrant = verifiedPrincipalPolicy.policy.grants.find(\n (grant) => grant.containerId === input.containerId,\n );\n if (!signedGrant || signedGrant.accessLevel !== input.accessLevel) {\n assertGrantMintNamed(input.expectedGroupName);\n return commitMissingGroupGrant(input);\n }\n\n const materializedPlan = await buildCurrentContainerSharePlan({\n accessLevel: input.accessLevel,\n author: input.author,\n eventId: input.eventId,\n execSql: input.execSql,\n knownContainerKeks: input.knownContainerKeks,\n principalPolicyCache: principalPolicyCacheForVerifiedPolicies(\n verifiedPrincipalPolicy.checkpointPolicies,\n ),\n previousProjection,\n recipient: {\n principalPolicy: verifiedPrincipalPolicy.policy,\n subjectId: input.recipientGroupId,\n subjectType: \"group\",\n },\n resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n if (!materializedPlan) return null;\n const result = await submitAcknowledgedContainerMutation({\n reportSecurityIncident: input.reportSecurityIncident,\n recitationPolicies: verifiedPrincipalPolicy.checkpointPolicies,\n apiClient: input.apiClient,\n author: input.author,\n containerKey: materializedPlan.containerKey,\n execSql: input.execSql,\n plan: materializedPlan.plan,\n stillCurrent: input.stillCurrent,\n submit: () =>\n submitPlainContainerMutation(() =>\n input.apiClient.shareContainer(\n input.containerId,\n materializedPlan.plan.request,\n {\n expectedPaymentRequiredOrganizationId: input.author.organizationId,\n },\n ),\n ),\n });\n if (!result) return null;\n\n // Keep the previously cached group epoch available until the old container\n // wrap has been unwrapped and the replacement has committed. Root has no\n // parent fallback, so caching the rotated policy any earlier destroys the\n // only local path to the KEK that must be re-wrapped.\n if (input.stillCurrent?.() !== false) {\n await savePrincipalPolicyBundle(\n input.execSql,\n verifiedPrincipalPolicy.bundle,\n new Date().toISOString(),\n input.author.organizationId,\n { stillCurrent: input.stillCurrent },\n );\n }\n if (input.stillCurrent?.() === false) return null;\n\n return result;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"share.js","sourceRoot":"","sources":["share.ts"],"names":[],"mappings":"AAgBA,OAAO,EACL,sCAAsC,EACtC,wCAAwC,EAGxC,gCAAgC,GACjC,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,uCAAuC,EAAE,MAAM,iEAAiE,CAAC;AAC1H,OAAO,EAAE,yBAAyB,EAAE,MAAM,sDAAsD,CAAC;AAGjG,OAAO,EACL,kCAAkC,GAEnC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,yBAAyB,EAAE,MAAM,yCAAyC,CAAC;AACpF,OAAO,EAAE,oCAAoC,EAAE,MAAM,qDAAqD,CAAC;AAC3G,OAAO,EAAE,+CAA+C,EAAE,MAAM,yDAAyD,CAAC;AAC1H,OAAO,EAAE,kCAAkC,EAAE,MAAM,qCAAqC,CAAC;AAEzF,OAAO,EACL,mCAAmC,EACnC,4BAA4B,GAC7B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,mCAAmC,EAAE,MAAM,wBAAwB,CAAC;AAC7E,OAAO,EACL,4BAA4B,EAE5B,qCAAqC,GACtC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAE3D,MAAM,oCAAqC,SAAQ,KAAK;CAAG;AAE3D,KAAK,UAAU,8BAA8B,CAC3C,KAAgE;IAEhE,OAAO,wCAAwC,CAAC,GAAG,EAAE,CACnD,mCAAmC,CAAC,KAAK,CAAC,CAC3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KAAK,CAAC,SAAS,CAAC,cAAc,CAC5B,KAAK,CAAC,WAAW,EACjB,gBAAgB,CAAC,IAAI,CAAC,OAAO,EAC7B;YACE,qCAAqC,EAAE,KAAK,CAAC,MAAM,CAAC,cAAc;SACnE,CACF,CACF;KACJ,CAAC,CAAC;IACH,IAAI,CAAC,MAAM;QAAE,OAAO,IAAI,CAAC;IAEzB,2EAA2E;IAC3E,yEAAyE;IACzE,0EAA0E;IAC1E,sDAAsD;IACtD,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK,EAAE,CAAC;QACrC,MAAM,yBAAyB,CAC7B,KAAK,CAAC,OAAO,EACb,uBAAuB,CAAC,MAAM,EAC9B,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,EACxB,KAAK,CAAC,MAAM,CAAC,cAAc,EAC3B,EAAE,YAAY,EAAE,KAAK,CAAC,YAAY,EAAE,CACrC,CAAC;IACJ,CAAC;IACD,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IAElD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type {\n ContainerAccessLevel,\n SigningKeyPair,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n ContainerMutationResponse,\n ContainerWriterProjectionResponse,\n PrincipalPolicyBundleResponse,\n} from \"@tearleads/validators/response\";\nimport type {\n ContainerMutationAuthor,\n ContainerShareApi,\n ContainerSharePlan,\n MaterializedContainerSharePlan,\n} from \"../../../data/containers/shared/types\";\nimport {\n isProjectionVerificationCancelledError,\n nullOnProjectionVerificationCancellation,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n requireProjectionUserKeyResolver,\n} from \"../../../data/keyingProjectionVerification\";\nimport { principalPolicyCacheForVerifiedPolicies } from \"../../../data/keyingProjectionVerification/principalPolicyCache\";\nimport { savePrincipalPolicyBundle } from \"../../../data/persistence/principalPolicyPersistence\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n requireTrustedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n} from \"../../../data/trustedUserIdentity\";\nimport { createGroupMetadataAccess } from \"../../organizations/groupMetadataAccess\";\nimport { createGroupMetadataContainerVerifier } from \"../../organizations/groupMetadataContainerAuthority\";\nimport { preparePrincipalContainerRematerializationBatch } from \"../../organizations/principalContainerRematerialization\";\nimport { setOrganizationGroupContainerGrant } from \"../../organizations/principalPolicy\";\nimport type { GroupPolicyNameReader } from \"../../organizations/principalPolicyRequest\";\nimport {\n submitAcknowledgedContainerMutation,\n submitPlainContainerMutation,\n} from \"./mutationSubmit\";\nimport { buildMaterializedContainerSharePlan } from \"./shareMaterialization\";\nimport {\n advanceVerifiedSharePolicies,\n type ContainerManagedPrincipalShareApi,\n loadVerifiedGroupSharePrincipalPolicy,\n} from \"./sharePrincipalPolicy\";\nimport { resolveShareProjection } from \"./shareProjection\";\n\nclass ContainerShareGenerationExpiredError extends Error {}\n\nasync function buildCurrentContainerSharePlan(\n input: Parameters<typeof buildMaterializedContainerSharePlan>[0],\n): Promise<MaterializedContainerSharePlan | null> {\n return nullOnProjectionVerificationCancellation(() =>\n buildMaterializedContainerSharePlan(input),\n );\n}\n\nexport async function shareRemoteContainer(input: {\n reportSecurityIncident: SecurityIncidentReporter;\n accessLevel: ContainerAccessLevel;\n apiClient: ContainerShareApi;\n author: ContainerMutationAuthor;\n containerId: string;\n eventId?: string | undefined;\n execSql: ExecSql;\n previousProjection?: ContainerWriterProjectionResponse | undefined;\n recipientUserId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n signedAt?: string | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<{\n containerKey: Uint8Array;\n plan: ContainerSharePlan;\n response: ContainerMutationResponse;\n} | null> {\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote container share\",\n );\n const resolveTrustedUserIdentity = requireTrustedUserIdentityResolver(\n input.resolveTrustedUserIdentity,\n );\n const recipientIdentity = await resolveTrustedUserIdentity(\n input.recipientUserId,\n );\n if (!recipientIdentity || input.stillCurrent?.() === false) {\n return null;\n }\n const previousProjection = await resolveShareProjection(\n input,\n resolveProjectionUserKey,\n );\n if (!previousProjection) return null;\n\n const materializedPlan = await buildCurrentContainerSharePlan({\n accessLevel: input.accessLevel,\n author: input.author,\n eventId: input.eventId,\n execSql: input.execSql,\n previousProjection,\n recipient: {\n recipientEncapsulationPublicKey: recipientIdentity.encapsulationPublicKey,\n subjectId: input.recipientUserId,\n subjectType: \"user\",\n },\n resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n if (!materializedPlan) return null;\n return submitAcknowledgedContainerMutation({\n reportSecurityIncident: input.reportSecurityIncident,\n recitationPolicies: [],\n apiClient: input.apiClient,\n author: input.author,\n containerKey: materializedPlan.containerKey,\n execSql: input.execSql,\n plan: materializedPlan.plan,\n stillCurrent: input.stillCurrent,\n submit: () =>\n submitPlainContainerMutation(() =>\n input.apiClient.shareContainer(\n input.containerId,\n materializedPlan.plan.request,\n {\n expectedPaymentRequiredOrganizationId: input.author.organizationId,\n },\n ),\n ),\n });\n}\n\ninterface RemoteContainerGroupShareInput {\n reportSecurityIncident: SecurityIncidentReporter;\n accessLevel: ContainerAccessLevel;\n apiClient: ContainerManagedPrincipalShareApi;\n author: ContainerMutationAuthor;\n containerId: string;\n eventId?: string | undefined;\n execSql: ExecSql;\n /**\n * The display name the user chose the group by, checked against the name\n * committed in the verified group policy so a relabeled read-model row\n * cannot redirect the share onto another group. `null` is reserved for the\n * grant-preserving re-wrap: a share that would mint a new grant without a\n * name is refused.\n */\n expectedGroupName: string | null;\n readEncryptedName?: GroupPolicyNameReader | undefined;\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n previousProjection?: ContainerWriterProjectionResponse | undefined;\n recipientGroupId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n signedAt?: string | undefined;\n signingKeyPair?: SigningKeyPair | null | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}\n\ninterface RemoteContainerGroupShareResult {\n containerKey: Uint8Array;\n plan: ContainerSharePlan;\n response: ContainerMutationResponse;\n}\n\nfunction isMaterializedContainerSharePlan(\n value: Awaited<\n ReturnType<typeof preparePrincipalContainerRematerializationBatch>\n >[\"plans\"][number],\n): value is MaterializedContainerSharePlan {\n return value.plan.body.eventType === \"container.grant\";\n}\n\nasync function prepareMissingGroupGrantMutations(input: {\n currentPolicy: PrincipalPolicyBundleResponse;\n nextPolicy: VerifiedPrincipalPolicy;\n shareInput: RemoteContainerGroupShareInput;\n}) {\n const { currentPolicy, nextPolicy, shareInput } = input;\n return preparePrincipalContainerRematerializationBatch({\n reportSecurityIncident: shareInput.reportSecurityIncident,\n apiClient: shareInput.apiClient,\n author: shareInput.author,\n execSql: shareInput.execSql,\n grants: [\n ...new Map(\n [...currentPolicy.currentGrants, ...nextPolicy.grants].map(\n (grant) => [grant.containerId, grant] as const,\n ),\n ).values(),\n ],\n groupId: shareInput.recipientGroupId,\n nextPolicy,\n resolveTrustedUserIdentity: shareInput.resolveTrustedUserIdentity,\n stillCurrent: shareInput.stillCurrent,\n targetSecretKey: shareInput.targetSecretKey,\n warmReferencedPrincipalPolicies: shareInput.warmReferencedPrincipalPolicies,\n });\n}\n\nasync function commitMissingGroupGrantPolicy(\n input: RemoteContainerGroupShareInput,\n): Promise<{\n preparedTarget: Awaited<\n ReturnType<typeof preparePrincipalContainerRematerializationBatch>\n >;\n storedPolicy: Awaited<ReturnType<typeof setOrganizationGroupContainerGrant>>;\n} | null> {\n const signingKeyPair = input.signingKeyPair;\n if (!signingKeyPair) {\n throw new Error(\n \"Container group share requires principal policy signing context\",\n );\n }\n const policyApi = {\n recoverPendingPrincipalMutation:\n input.apiClient.recoverPendingPrincipalMutation?.bind(input.apiClient),\n commitOrganizationGroupPolicy:\n input.apiClient.commitOrganizationGroupPolicy.bind(input.apiClient),\n getCurrentPrincipalPolicy: input.apiClient.getCurrentPrincipalPolicy.bind(\n input.apiClient,\n ),\n };\n let preparedTarget:\n | Awaited<\n ReturnType<typeof preparePrincipalContainerRematerializationBatch>\n >\n | undefined;\n try {\n const storedPolicy = await setOrganizationGroupContainerGrant({\n accessLevel: input.accessLevel,\n apiClient: policyApi,\n assertCanCommit: () => {\n if (input.stillCurrent?.() === false) {\n throw new ContainerShareGenerationExpiredError();\n }\n },\n containerId: input.containerId,\n execSql: input.execSql,\n groupId: input.recipientGroupId,\n organizationId: input.author.organizationId,\n prepareContainerMutations: async ({ currentPolicy, nextPolicy }) => {\n preparedTarget = await prepareMissingGroupGrantMutations({\n currentPolicy,\n nextPolicy,\n shareInput: input,\n });\n return preparedTarget;\n },\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n signerUserId: input.author.signerUserId,\n signingFingerprint: input.author.signerKeyFingerprint,\n signingKeyPair,\n });\n if (!preparedTarget) {\n throw new Error(\"Container group share preparation is incomplete\");\n }\n return { preparedTarget, storedPolicy };\n } catch (error) {\n if (\n error instanceof ContainerShareGenerationExpiredError ||\n isProjectionVerificationCancelledError(error)\n ) {\n return null;\n }\n throw error;\n }\n}\n\nasync function commitMissingGroupGrant(\n input: RemoteContainerGroupShareInput,\n): Promise<RemoteContainerGroupShareResult | null> {\n if (!input.signingKeyPair) {\n throw new Error(\n \"Container group share requires principal policy signing context\",\n );\n }\n if (input.stillCurrent?.() === false) return null;\n const committed = await commitMissingGroupGrantPolicy(input);\n if (!committed) return null;\n const { preparedTarget, storedPolicy } = committed;\n const targetIndex = preparedTarget?.plans.findIndex(\n (planned) => planned.plan.containerId === input.containerId,\n );\n const response =\n targetIndex === undefined || targetIndex < 0\n ? undefined\n : storedPolicy.containerMutations[targetIndex];\n const targetPlan =\n targetIndex === undefined || targetIndex < 0\n ? undefined\n : preparedTarget?.plans[targetIndex];\n if (\n !targetPlan ||\n !response ||\n !isMaterializedContainerSharePlan(targetPlan)\n ) {\n throw new Error(\"Container group share acknowledgement is incomplete\");\n }\n return {\n containerKey: targetPlan.containerKey,\n plan: targetPlan.plan,\n response,\n };\n}\n\n// Only a re-wrap of an existing signed grant may run without the chosen name;\n// minting a grant is exactly the operation the name binding protects.\nfunction assertGrantMintNamed(expectedGroupName: string | null): void {\n if (expectedGroupName === null) {\n throw new Error(\n \"Minting a group grant requires the chosen group name; only a re-wrap of an existing signed grant may omit it\",\n );\n }\n}\n\nfunction loadShareGroupPolicy(input: RemoteContainerGroupShareInput) {\n return loadVerifiedGroupSharePrincipalPolicy({\n apiClient: input.apiClient,\n execSql: input.execSql,\n expectedGroupName: input.expectedGroupName ?? undefined,\n readEncryptedName:\n input.readEncryptedName ??\n createGroupMetadataAccess({\n ...input,\n organizationId: input.author.organizationId,\n verifyMetadataContainer: createGroupMetadataContainerVerifier({\n ...input,\n organizationId: input.author.organizationId,\n stillCurrent: input.stillCurrent ?? (() => true),\n }),\n }).readName,\n groupId: input.recipientGroupId,\n organizationId: input.author.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n}\n\nexport async function shareRemoteContainerWithGroup(\n input: RemoteContainerGroupShareInput,\n): Promise<RemoteContainerGroupShareResult | null> {\n if (input.stillCurrent?.() === false) return null;\n await input.apiClient.recoverPendingPrincipalMutation?.(\n input.author.organizationId,\n );\n if (input.stillCurrent?.() === false) return null;\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote container share\",\n );\n const previousProjection = await resolveShareProjection(\n input,\n resolveProjectionUserKey,\n );\n if (!previousProjection) return null;\n const verifiedPrincipalPolicy = await loadShareGroupPolicy(input);\n if (input.stillCurrent?.() === false) return null;\n await advanceVerifiedSharePolicies(\n input.execSql,\n verifiedPrincipalPolicy,\n input.stillCurrent,\n );\n if (input.stillCurrent?.() === false) return null;\n\n const signedGrant = verifiedPrincipalPolicy.policy.grants.find(\n (grant) => grant.containerId === input.containerId,\n );\n if (!signedGrant || signedGrant.accessLevel !== input.accessLevel) {\n assertGrantMintNamed(input.expectedGroupName);\n return commitMissingGroupGrant(input);\n }\n\n const materializedPlan = await buildCurrentContainerSharePlan({\n accessLevel: input.accessLevel,\n author: input.author,\n eventId: input.eventId,\n execSql: input.execSql,\n knownContainerKeks: input.knownContainerKeks,\n principalPolicyCache: principalPolicyCacheForVerifiedPolicies(\n verifiedPrincipalPolicy.checkpointPolicies,\n ),\n previousProjection,\n recipient: {\n principalPolicy: verifiedPrincipalPolicy.policy,\n subjectId: input.recipientGroupId,\n subjectType: \"group\",\n },\n resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n if (!materializedPlan) return null;\n const result = await submitAcknowledgedContainerMutation({\n reportSecurityIncident: input.reportSecurityIncident,\n recitationPolicies: verifiedPrincipalPolicy.checkpointPolicies,\n apiClient: input.apiClient,\n author: input.author,\n containerKey: materializedPlan.containerKey,\n execSql: input.execSql,\n plan: materializedPlan.plan,\n stillCurrent: input.stillCurrent,\n submit: () =>\n submitPlainContainerMutation(() =>\n input.apiClient.shareContainer(\n input.containerId,\n materializedPlan.plan.request,\n {\n expectedPaymentRequiredOrganizationId: input.author.organizationId,\n },\n ),\n ),\n });\n if (!result) return null;\n\n // Keep the previously cached group epoch available until the old container\n // wrap has been unwrapped and the replacement has committed. Root has no\n // parent fallback, so caching the rotated policy any earlier destroys the\n // only local path to the KEK that must be re-wrapped.\n if (input.stillCurrent?.() !== false) {\n await savePrincipalPolicyBundle(\n input.execSql,\n verifiedPrincipalPolicy.bundle,\n new Date().toISOString(),\n input.author.organizationId,\n { stillCurrent: input.stillCurrent },\n );\n }\n if (input.stillCurrent?.() === false) return null;\n\n return result;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shareAncestorRepair.js","sourceRoot":"","sources":["shareAncestorRepair.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,0BAA0B,EAAE,MAAM,8CAA8C,CAAC;AAM1F,OAAO,EAAE,mCAAmC,EAAE,MAAM,qDAAqD,CAAC;AAC1G,OAAO,EAAE,kCAAkC,EAAE,MAAM,iDAAiD,CAAC;AAOrG,OAAO,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAC;AAErD,SAAS,kBAAkB,CACzB,UAA6C;IAE7C,MAAM,YAAY,GAAG,OAAO,CAAC,GAAG,CAC9B,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EACrC,cAAc,CACf,CAAC;IACF,OAAO,KAAK,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,YAAY,CAAC,MAAM,GAAG,CAAC,CAAC;AAChE,CAAC;AAED,oFAAoF;AACpF,SAAS,iBAAiB,CACxB,UAA6C;IAE7C,MAAM,IAAI,GAAG,UAAU,CAAC,aAAa,CAAC;IACtC,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC,MAAM,EAAE,KAAK,IAAI,CAAC,EAAE,CAAC;QACpD,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC;QACxB,IACE,GAAG;YACH,GAAG,CAAC,yBAAyB,KAAK,IAAI,CAAC,KAAK,GAAG,CAAC,CAAC,EAAE,mBAAmB,EACtE,CAAC;YACD,OAAO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CAAC,KAAK,CAAC,SAAS,CAAC,EAAE;oBACtE,CAAC,CAAC,EAAE,CAAC;aACR;YACD,MAAM,EAAE,KAAK,CAAC,MAAM;YACpB,WAAW,EAAE,YAAY;YACzB,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,sBAAsB,EAAE,KAAK,CAAC,sBAAsB;YACpD,wBAAwB,EAAE,KAAK,CAAC,wBAAwB;YACxD,YAAY,EAAE,KAAK,CAAC,YAAY;YAChC,eAAe,EAAE,KAAK,CAAC,eAAe;YACtC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;SACvE,CAAC,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;YAC1B,MAAM,UAAU,GACd,KAAK,YAAY,0BAA0B;gBAC3C,KAAK,YAAY,kCAAkC,CAAC;YACtD,IAAI,UAAU,IAAI,aAAa;gBAAE,OAAO,IAAI,CAAC;YAC7C,MAAM,UAAU;gBACd,CAAC,CAAC,IAAI,mCAAmC,CAAC,YAAY,CAAC;gBACvD,CAAC,CAAC,KAAK,CAAC;QACZ,CAAC,CAAC,CAAC;QACH,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;YAAE,OAAO,IAAI,CAAC;QAClD,IAAI,CAAC,QAAQ;YAAE,OAAO,aAAa,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC;QACxD,MAAM,SAAS,GAAG,MAAM,KAAK,CAAC,SAAS,CAAC,4BAA4B,CAClE,KAAK,CAAC,WAAW,CAClB,CAAC;QACF,IAAI,CAAC,SAAS;YAAE,OAAO,IAAI,CAAC;QAC5B,UAAU,GAAG,SAAS,CAAC;IACzB,CAAC;IACD,OAAO,iBAAiB,CAAC,UAAU,CAAC,KAAK,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC;AACpE,CAAC","sourcesContent":["import type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { ContainerAuthorAccessError } from \"../../../data/containers/shared/authorAccess\";\nimport type {\n ContainerMutationAuthor,\n ContainerRekeyApi,\n ContainerShareApi,\n} from \"../../../data/containers/shared/types\";\nimport { ContainerKekRepairInaccessibleError } from \"../../../data/documents/shared/containerKekCurrency\";\nimport { ContainerKekTargetUnreachableError } from \"../../../data/documents/shared/containerKekPath\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../../data/keyingProjectionVerification\";\nimport type { SecurityIncidentReporter } from \"../../../data/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { rekeyRemoteContainer } from \"./rekeyRemote\";\n\nfunction carriesDirectGrant(\n projection: ContainerWriterProjectionResponse,\n): boolean {\n const directGrants = Reflect.get(\n Object(projection.path.at(-1)?.state),\n \"directGrants\",\n );\n return Array.isArray(directGrants) && directGrants.length > 0;\n}\n\n/** The first level on the path, the container included, pinning a retired epoch. */\nfunction firstStaleLevelId(\n projection: ContainerWriterProjectionResponse,\n): string | null {\n const keks = projection.containerKeks;\n for (let index = 1; index < keks.length; index += 1) {\n const kek = keks[index];\n if (\n kek &&\n kek.parentContainerKeyEpochId !== keks[index - 1]?.containerKeyEpochId\n ) {\n return kek.containerId;\n }\n }\n return null;\n}\n\n/**\n * Repair a stale path down to and including a container before granting on it\n * (#2340).\n *\n * A chain with no grant beneath it may sit lazily stale after an ancestor\n * rotation, since nobody's writes depend on it. The first grant changes that:\n * its grantee could never re-key the levels above its container, so the server\n * refuses a first grant below a stale chain. The container's own edge must be\n * current too, because a grant cites the parent's current epoch and the\n * container's key epoch has to pin it. The sharer administers the container\n * through a grant at or above it, and the levels above that grant are already\n * current, so every stale level here is one the sharer can re-key. These\n * repairs are standalone and need not be atomic with the grant: a repair never\n * strands anyone.\n *\n * Every share does this, not only a first grant, which is all the server\n * insists on. A container that already carries a grant is stale only past the\n * carried-rekey cap, and its grantees are then parked behind exactly these\n * levels; the sharer is already here and able.\n */\nexport async function projectionWithCurrentAncestors(input: {\n apiClient: ContainerShareApi &\n Partial<Pick<ContainerRekeyApi, \"rekeyContainer\" | \"rekeyContainerResult\">>;\n author: ContainerMutationAuthor;\n containerId: string;\n execSql: ExecSql;\n previousProjection: ContainerWriterProjectionResponse;\n reportSecurityIncident: SecurityIncidentReporter;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<ContainerWriterProjectionResponse | null> {\n const { rekeyContainer, rekeyContainerResult } = input.apiClient;\n let projection = input.previousProjection;\n // Each round repairs one level, and a path has a bounded number of them.\n for (let round = 0; round < projection.containerKeks.length; round += 1) {\n const staleLevelId = firstStaleLevelId(projection);\n if (staleLevelId === null) return projection;\n if (!rekeyContainer) {\n // Not a repair someone else owes: the adapter simply cannot make one.\n throw new Error(\n \"Container share must re-key a stale path, which needs rekeyContainer\",\n );\n }\n // This sharer may be unable to re-key a level above a container that\n // already carries a grant, stale past the carried-rekey cap. The server\n // asks a current chain only of a first grant, so it decides rather than\n // this blocking a grant it would accept.\n const serverDecides =\n staleLevelId !== input.containerId && carriesDirectGrant(projection);\n const repaired = await rekeyRemoteContainer({\n apiClient: {\n getContainerWriterProjection: (containerId) =>\n input.apiClient.getContainerWriterProjection(containerId),\n reciteContainer: (...args) => input.apiClient.reciteContainer(...args),\n rekeyContainer: rekeyContainer.bind(input.apiClient),\n ...(rekeyContainerResult\n ? { rekeyContainerResult: rekeyContainerResult.bind(input.apiClient) }\n : {}),\n },\n author: input.author,\n containerId: staleLevelId,\n execSql: input.execSql,\n reportSecurityIncident: input.reportSecurityIncident,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n }).catch((error: unknown) => {\n const outOfReach =\n error instanceof ContainerAuthorAccessError ||\n error instanceof ContainerKekTargetUnreachableError;\n if (outOfReach && serverDecides) return null;\n throw outOfReach\n ? new ContainerKekRepairInaccessibleError(staleLevelId)\n : error;\n });\n if (input.stillCurrent?.() === false) return null;\n if (!repaired) return serverDecides ? projection : null;\n const refreshed = await input.apiClient.getContainerWriterProjection(\n input.containerId,\n );\n if (!refreshed) return null;\n projection = refreshed;\n }\n return firstStaleLevelId(projection) === null ? projection : null;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"shareAncestorRepair.js","sourceRoot":"","sources":["shareAncestorRepair.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,0BAA0B,EAAE,MAAM,8CAA8C,CAAC;AAM1F,OAAO,EAAE,mCAAmC,EAAE,MAAM,qDAAqD,CAAC;AAC1G,OAAO,EAAE,kCAAkC,EAAE,MAAM,iDAAiD,CAAC;AAOrG,OAAO,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAC;AAErD,SAAS,kBAAkB,CACzB,UAA6C;IAE7C,MAAM,YAAY,GAAG,OAAO,CAAC,GAAG,CAC9B,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EACrC,cAAc,CACf,CAAC;IACF,OAAO,KAAK,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,YAAY,CAAC,MAAM,GAAG,CAAC,CAAC;AAChE,CAAC;AAED,oFAAoF;AACpF,SAAS,iBAAiB,CACxB,UAA6C;IAE7C,MAAM,IAAI,GAAG,UAAU,CAAC,aAAa,CAAC;IACtC,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC,MAAM,EAAE,KAAK,IAAI,CAAC,EAAE,CAAC;QACpD,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC;QACxB,IACE,GAAG;YACH,GAAG,CAAC,yBAAyB,KAAK,IAAI,CAAC,KAAK,GAAG,CAAC,CAAC,EAAE,mBAAmB,EACtE,CAAC;YAC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,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,EAAE;oBACtE,CAAC,CAAC,EAAE,CAAC;aACR;YACD,MAAM,EAAE,KAAK,CAAC,MAAM;YACpB,WAAW,EAAE,YAAY;YACzB,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,sBAAsB,EAAE,KAAK,CAAC,sBAAsB;YACpD,wBAAwB,EAAE,KAAK,CAAC,wBAAwB;YACxD,YAAY,EAAE,KAAK,CAAC,YAAY;YAChC,eAAe,EAAE,KAAK,CAAC,eAAe;YACtC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;SACvE,CAAC,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;YAC1B,MAAM,UAAU,GACd,KAAK,YAAY,0BAA0B;gBAC3C,KAAK,YAAY,kCAAkC,CAAC;YACtD,IAAI,UAAU,IAAI,aAAa;gBAAE,OAAO,IAAI,CAAC;YAC7C,MAAM,UAAU;gBACd,CAAC,CAAC,IAAI,mCAAmC,CAAC,YAAY,CAAC;gBACvD,CAAC,CAAC,KAAK,CAAC;QACZ,CAAC,CAAC,CAAC;QACH,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;YAAE,OAAO,IAAI,CAAC;QAClD,IAAI,CAAC,QAAQ;YAAE,OAAO,aAAa,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC;QACxD,MAAM,SAAS,GAAG,MAAM,KAAK,CAAC,SAAS,CAAC,4BAA4B,CAClE,KAAK,CAAC,WAAW,CAClB,CAAC;QACF,IAAI,CAAC,SAAS;YAAE,OAAO,IAAI,CAAC;QAC5B,UAAU,GAAG,SAAS,CAAC;IACzB,CAAC;IACD,OAAO,iBAAiB,CAAC,UAAU,CAAC,KAAK,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC;AACpE,CAAC","sourcesContent":["import type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { ContainerAuthorAccessError } from \"../../../data/containers/shared/authorAccess\";\nimport type {\n ContainerMutationAuthor,\n ContainerRekeyApi,\n ContainerShareApi,\n} from \"../../../data/containers/shared/types\";\nimport { ContainerKekRepairInaccessibleError } from \"../../../data/documents/shared/containerKekCurrency\";\nimport { ContainerKekTargetUnreachableError } from \"../../../data/documents/shared/containerKekPath\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../../data/keyingProjectionVerification\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { rekeyRemoteContainer } from \"./rekeyRemote\";\n\nfunction carriesDirectGrant(\n projection: ContainerWriterProjectionResponse,\n): boolean {\n const directGrants = Reflect.get(\n Object(projection.path.at(-1)?.state),\n \"directGrants\",\n );\n return Array.isArray(directGrants) && directGrants.length > 0;\n}\n\n/** The first level on the path, the container included, pinning a retired epoch. */\nfunction firstStaleLevelId(\n projection: ContainerWriterProjectionResponse,\n): string | null {\n const keks = projection.containerKeks;\n for (let index = 1; index < keks.length; index += 1) {\n const kek = keks[index];\n if (\n kek &&\n kek.parentContainerKeyEpochId !== keks[index - 1]?.containerKeyEpochId\n ) {\n return kek.containerId;\n }\n }\n return null;\n}\n\n/**\n * Repair a stale path down to and including a container before granting on it\n * (#2340).\n *\n * A chain with no grant beneath it may sit lazily stale after an ancestor\n * rotation, since nobody's writes depend on it. The first grant changes that:\n * its grantee could never re-key the levels above its container, so the server\n * refuses a first grant below a stale chain. The container's own edge must be\n * current too, because a grant cites the parent's current epoch and the\n * container's key epoch has to pin it. The sharer administers the container\n * through a grant at or above it, and the levels above that grant are already\n * current, so every stale level here is one the sharer can re-key. These\n * repairs are standalone and need not be atomic with the grant: a repair never\n * strands anyone.\n *\n * Every share does this, not only a first grant, which is all the server\n * insists on. A container that already carries a grant is stale only past the\n * carried-rekey cap, and its grantees are then parked behind exactly these\n * levels; the sharer is already here and able.\n */\nexport async function projectionWithCurrentAncestors(input: {\n apiClient: ContainerShareApi &\n Partial<Pick<ContainerRekeyApi, \"rekeyContainer\" | \"rekeyContainerResult\">>;\n author: ContainerMutationAuthor;\n containerId: string;\n execSql: ExecSql;\n previousProjection: ContainerWriterProjectionResponse;\n reportSecurityIncident: SecurityIncidentReporter;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<ContainerWriterProjectionResponse | null> {\n const { rekeyContainer, rekeyContainerResult } = input.apiClient;\n let projection = input.previousProjection;\n // Each round repairs one level, and a path has a bounded number of them.\n for (let round = 0; round < projection.containerKeks.length; round += 1) {\n const staleLevelId = firstStaleLevelId(projection);\n if (staleLevelId === null) return projection;\n if (!rekeyContainer) {\n // Not a repair someone else owes: the adapter simply cannot make one.\n throw new Error(\n \"Container share must re-key a stale path, which needs rekeyContainer\",\n );\n }\n // This sharer may be unable to re-key a level above a container that\n // already carries a grant, stale past the carried-rekey cap. The server\n // asks a current chain only of a first grant, so it decides rather than\n // this blocking a grant it would accept.\n const serverDecides =\n staleLevelId !== input.containerId && carriesDirectGrant(projection);\n const repaired = await rekeyRemoteContainer({\n apiClient: {\n getContainerWriterProjection: (containerId) =>\n input.apiClient.getContainerWriterProjection(containerId),\n reciteContainer: (...args) => input.apiClient.reciteContainer(...args),\n rekeyContainer: rekeyContainer.bind(input.apiClient),\n ...(rekeyContainerResult\n ? { rekeyContainerResult: rekeyContainerResult.bind(input.apiClient) }\n : {}),\n },\n author: input.author,\n containerId: staleLevelId,\n execSql: input.execSql,\n reportSecurityIncident: input.reportSecurityIncident,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n }).catch((error: unknown) => {\n const outOfReach =\n error instanceof ContainerAuthorAccessError ||\n error instanceof ContainerKekTargetUnreachableError;\n if (outOfReach && serverDecides) return null;\n throw outOfReach\n ? new ContainerKekRepairInaccessibleError(staleLevelId)\n : error;\n });\n if (input.stillCurrent?.() === false) return null;\n if (!repaired) return serverDecides ? projection : null;\n const refreshed = await input.apiClient.getContainerWriterProjection(\n input.containerId,\n );\n if (!refreshed) return null;\n projection = refreshed;\n }\n return firstStaleLevelId(projection) === null ? projection : null;\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { ContainerAccessLevel } from "../../../internal/crypto/index.js";
|
|
2
2
|
import type { ContainerWriterProjectionResponse } from "../../../internal/validators/response/index.js";
|
|
3
3
|
import type { ContainerMutationAuthor, MaterializedContainerSharePlan } from "../../../data/containers/shared/types.js";
|
|
4
|
-
import type { PrincipalPolicyCache, ProjectionUserKeyResolver, ReferencedPrincipalPolicyWarmer } from "../../../data/keyingProjectionVerification.js";
|
|
4
|
+
import type { PrincipalPolicyCache, ProjectionUserKeyResolver, ReferencedPrincipalPolicyWarmer } from "../../../data/keyingProjectionVerification/index.js";
|
|
5
5
|
import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
|
|
6
6
|
import { type ContainerShareRecipient } from "./sharePlanCore.js";
|
|
7
7
|
interface BuildMaterializedContainerSharePlanInput {
|
|
@@ -2,7 +2,7 @@ import { type AccessEvent, type AccessManifest, type ContainerAccessManifestStat
|
|
|
2
2
|
import type { AccessManifestBundleWire } from "../../../internal/validators/request/index.js";
|
|
3
3
|
import type { ContainerKekResponse, ContainerWriterProjectionResponse } from "../../../internal/validators/response/index.js";
|
|
4
4
|
import type { ContainerSharePlan, MaterializedContainerSharePlan } from "../../../data/containers/shared/types.js";
|
|
5
|
-
import { type PrincipalPolicyCache, type ProjectionUserKeyResolver, type ReferencedPrincipalPolicyWarmer } from "../../../data/keyingProjectionVerification.js";
|
|
5
|
+
import { type PrincipalPolicyCache, type ProjectionUserKeyResolver, type ReferencedPrincipalPolicyWarmer } from "../../../data/keyingProjectionVerification/index.js";
|
|
6
6
|
import type { PrincipalPolicyCurrentEvidence } from "../../../data/principals/principalPolicyEvidence.js";
|
|
7
7
|
import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
|
|
8
8
|
export type ContainerShareRecipient = {
|
|
@@ -2,7 +2,7 @@ import { computeAccessManifestHash, deriveContainerAccessManifest, } from "../..
|
|
|
2
2
|
import { uniquePrincipalPolicies } from "../../../data/containers/shared/principalPolicies.js";
|
|
3
3
|
import { asContainerManifestBundle, containerManifestRef, getParentKekForTarget, readContainerState, } from "../../../data/containers/shared/projection.js";
|
|
4
4
|
import { readContainerKekRecipientTargets, readContainerKeyEpoch, } from "../../../data/containers/shared/readers.js";
|
|
5
|
-
import { collectContainerWriterProjectionPrincipalPolicies, } from "../../../data/keyingProjectionVerification.js";
|
|
5
|
+
import { collectContainerWriterProjectionPrincipalPolicies, } from "../../../data/keyingProjectionVerification/index.js";
|
|
6
6
|
import { containerMutationRequestCore, previousPathRequestFields, readCanonicalRecordOrNull, } from "./mutationRequestCore.js";
|
|
7
7
|
function grantKey(grant) {
|
|
8
8
|
return `${grant.subjectType}:${grant.subjectId}`;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { computeContainerKekRecipientTargetHash, computeContainerKeyEpochHash, deriveContainerKekWrappingPublicKey, normalizeContainerAccessEventBody, } from "../../../internal/crypto/index.js";
|
|
2
2
|
import { buildContainerCreateBody, buildContainerCreateKeyEpoch, deriveContainerCreateManifest, resolveContainerKekEpochId, signContainerCreateEvent, } from "../../../data/containers/shared/events.js";
|
|
3
3
|
import { wrapContainerKeyToManagedPrincipal, wrapContainerKeyToRootUser, } from "../../../data/containers/shared/projection.js";
|
|
4
|
-
import { readCanonicalJson, readCanonicalRecord, readCanonicalRecords, } from "../../../data/
|
|
4
|
+
import { readCanonicalJson, readCanonicalRecord, readCanonicalRecords, } from "../../../data/keying/canonicalJson.js";
|
|
5
5
|
import { principalHeadFromInitialGroupPolicy, principalPolicyRecordFromInitialGroupPolicy, } from "./initialGroupPolicy.js";
|
|
6
6
|
function buildRootContainerCreateBody(input) {
|
|
7
7
|
const baseBody = buildContainerCreateBody({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create.js","sourceRoot":"","sources":["create.ts"],"names":[],"mappings":"AASA,OAAO,EACL,sCAAsC,EACtC,4BAA4B,EAC5B,mCAAmC,EACnC,iCAAiC,GAClC,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EACL,wBAAwB,EACxB,4BAA4B,EAC5B,6BAA6B,EAC7B,0BAA0B,EAC1B,wBAAwB,GACzB,MAAM,wCAAwC,CAAC;AAChD,OAAO,EACL,kCAAkC,EAClC,0BAA0B,GAC3B,MAAM,4CAA4C,CAAC;AAMpD,OAAO,EACL,iBAAiB,EACjB,mBAAmB,EACnB,oBAAoB,GACrB,MAAM,mCAAmC,CAAC;AAE3C,OAAO,EACL,mCAAmC,EACnC,2CAA2C,GAC5C,MAAM,sBAAsB,CAAC;AAE9B,SAAS,4BAA4B,CAAC,KAQrC;IACC,MAAM,QAAQ,GAAG,wBAAwB,CAAC;QACxC,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;QAC9C,qBAAqB,EAAE,KAAK,CAAC,qBAAqB;QAClD,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,iBAAiB,EAAE,IAAI;QACvB,kBAAkB,EAAE,IAAI;KACzB,CAAC,CAAC;IACH,IAAI,KAAK,CAAC,oBAAoB,EAAE,CAAC;QAC/B,OAAO;YACL,GAAG,QAAQ;YACX,YAAY,EAAE;gBACZ;oBACE,WAAW,EAAE,OAAO;oBACpB,SAAS,EAAE,KAAK,CAAC,oBAAoB,CAAC,WAAW;oBACjD,WAAW,EAAE,KAAK,CAAC,oBAAoB,CAAC,aAAa;iBACtD;gBACD,GAAG,CAAC,KAAK,CAAC,UAAU;oBAClB,CAAC,CAAC;wBACE;4BACE,WA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AC/B,OAAO,EAAE,IAAI;gBACb,gBAAgB,EAAE,oBAAoB,CACpC,IAAI,CAAC,gBAAgB,EACrB,kCAAkC,CACnC;gBACD,KAAK,EAAE,oBAAoB,CAAC,IAAI,CAAC,KAAK,EAAE,sBAAsB,CAAC;aAChE;SACF;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n AccessEvent,\n AccessManifest,\n ContainerCreateAccessEventBody,\n ContainerGrantPrincipalHead,\n ContainerKeyEpoch,\n ContainerKeyWrap,\n ContainerUserRecipientKey,\n} from \"@tearleads/crypto\";\nimport {\n computeContainerKekRecipientTargetHash,\n computeContainerKeyEpochHash,\n deriveContainerKekWrappingPublicKey,\n normalizeContainerAccessEventBody,\n} from \"@tearleads/crypto\";\nimport type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type {\n ContainerMutationRequest,\n CreateOrganizationGroupRequest,\n} from \"@tearleads/validators/request\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n buildContainerCreateBody,\n buildContainerCreateKeyEpoch,\n deriveContainerCreateManifest,\n resolveContainerKekEpochId,\n signContainerCreateEvent,\n} from \"../../../data/containers/shared/events\";\nimport {\n wrapContainerKeyToManagedPrincipal,\n wrapContainerKeyToRootUser,\n} from \"../../../data/containers/shared/projection\";\nimport type {\n ContainerCreatePlan,\n ContainerMutationAuthor,\n MaterializedContainerCreatePlan,\n} from \"../../../data/containers/shared/types\";\nimport {\n readCanonicalJson,\n readCanonicalRecord,\n readCanonicalRecords,\n} from \"../../../data/keyingCanonicalJson\";\n\nimport {\n principalHeadFromInitialGroupPolicy,\n principalPolicyRecordFromInitialGroupPolicy,\n} from \"./initialGroupPolicy\";\n\nfunction buildRootContainerCreateBody(input: {\n author: ContainerMutationAuthor;\n managedPrincipalHead: ContainerGrantPrincipalHead | null;\n containerKeyEpochId: string;\n containerKeyPublicKey: string;\n metadataDocumentId: string;\n memberHead: ContainerGrantPrincipalHead | null;\n systemSlot: ContainerSystemSlot | null;\n}): ContainerCreateAccessEventBody {\n const baseBody = buildContainerCreateBody({\n systemSlot: input.systemSlot,\n containerKeyEpochId: input.containerKeyEpochId,\n containerKeyPublicKey: input.containerKeyPublicKey,\n metadataDocumentId: input.metadataDocumentId,\n parentContainerId: null,\n parentManifestHash: null,\n });\n if (input.managedPrincipalHead) {\n return {\n ...baseBody,\n directGrants: [\n {\n accessLevel: \"admin\",\n subjectId: input.managedPrincipalHead.principalId,\n subjectType: input.managedPrincipalHead.principalType,\n },\n ...(input.memberHead\n ? [\n {\n accessLevel: \"read\" as const,\n subjectId: input.memberHead.principalId,\n subjectType: \"group\" as const,\n },\n ]\n : []),\n ],\n referencedPrincipalHeads: [\n input.managedPrincipalHead,\n ...(input.memberHead ? [input.memberHead] : []),\n ],\n };\n }\n\n return {\n ...baseBody,\n directGrants: [\n {\n accessLevel: \"admin\",\n subjectId: input.author.signerUserId,\n subjectType: \"user\",\n },\n ],\n };\n}\n\nfunction buildRootContainerCreateRequest(input: {\n body: ContainerCreateAccessEventBody;\n event: AccessEvent;\n keyEpoch: ContainerKeyEpoch;\n manifest: AccessManifest;\n manifestHash: string;\n principalPolicies: readonly Record<string, unknown>[];\n userRecipientKeys: readonly ContainerUserRecipientKey[];\n wraps: readonly ContainerKeyWrap[];\n}): ContainerMutationRequest {\n return {\n event: readCanonicalRecord(input.event, \"Container root create event\"),\n body: readCanonicalRecord(input.body, \"Container root create body\"),\n expectedManifestHash: input.manifestHash,\n manifest: readCanonicalRecord(\n input.manifest,\n \"Container root create manifest\",\n ),\n previousManifestRef: null,\n parentContainerPathRefs: [],\n principalPolicies: readCanonicalRecords(\n input.principalPolicies,\n \"Container root create principal policies\",\n ),\n keyEpoch: readCanonicalRecord(\n input.keyEpoch,\n \"Container root create key epoch\",\n ),\n predecessorBridge: null,\n keyring: null,\n wraps: readCanonicalRecords(input.wraps, \"Container root create wraps\"),\n userRecipientKeys: readCanonicalRecords(\n input.userRecipientKeys,\n \"Container root create user recipient keys\",\n ),\n };\n}\n\nasync function buildRootManagedPrincipalContext(\n adminGroup: CreateOrganizationGroupRequest | null,\n): Promise<{\n managedPrincipalHead: ContainerGrantPrincipalHead | null;\n managedPrincipalPolicies: Record<string, unknown>[];\n}> {\n if (!adminGroup) {\n return {\n managedPrincipalHead: null,\n managedPrincipalPolicies: [],\n };\n }\n\n const managedPrincipalHead = await principalHeadFromInitialGroupPolicy({\n principalId: adminGroup.groupId,\n policy: adminGroup.initialGroupPolicy,\n });\n\n return {\n managedPrincipalHead,\n managedPrincipalPolicies: [\n principalPolicyRecordFromInitialGroupPolicy({\n head: managedPrincipalHead,\n policy: adminGroup.initialGroupPolicy,\n }),\n ],\n };\n}\n\nasync function deriveRootCreateArtifacts(input: {\n author: ContainerMutationAuthor;\n body: ContainerCreateAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n metadataDocumentId: string;\n signedAt: string | undefined;\n}) {\n if (!input.body.containerKeyPublicKey)\n throw new Error(\"Root container public key is missing\");\n const { event, eventHash } = await signContainerCreateEvent({\n author: input.author,\n body: input.body,\n containerId: input.containerId,\n eventId: crypto.randomUUID(),\n // A root container belongs to the creator's own organization.\n organizationId: input.author.organizationId,\n parentPath: [],\n signedAt: input.signedAt ?? new Date().toISOString(),\n });\n const { manifest, manifestHash, state } = await deriveContainerCreateManifest(\n {\n systemSlot: input.body.systemSlot,\n containerId: input.containerId,\n containerKeyEpochId: input.containerKeyEpochId,\n containerKeyPublicKey: input.body.containerKeyPublicKey,\n directGrants: input.body.directGrants,\n eventHash,\n metadataDocumentId: input.metadataDocumentId,\n // A root container belongs to the creator's own organization.\n organizationId: input.author.organizationId,\n parentContainerId: null,\n parentManifestHash: null,\n referencedPrincipalHeads: input.body.referencedPrincipalHeads,\n },\n );\n const keyEpoch = buildContainerCreateKeyEpoch({\n containerId: input.containerId,\n containerKeyEpochId: input.containerKeyEpochId,\n eventHash,\n manifestHash,\n parentContainerKeyEpochId: null,\n });\n return { event, eventHash, keyEpoch, manifest, manifestHash, state };\n}\n\nasync function wrapRootContainerKeyForPlan(input: {\n adminGroup: CreateOrganizationGroupRequest | null;\n containerKey: Uint8Array;\n containerKeyEpochId: string;\n manifestHash: string;\n managedPrincipalHead: ContainerGrantPrincipalHead | null;\n recipientEncapsulationPublicKey: Uint8Array;\n userId: string;\n}) {\n if (input.adminGroup && input.managedPrincipalHead) {\n return {\n ...(await wrapContainerKeyToManagedPrincipal({\n containerKey: input.containerKey,\n containerKeyEpochId: input.containerKeyEpochId,\n manifestHash: input.manifestHash,\n principalEncapsulationPublicKey:\n input.adminGroup.initialGroupPolicy.state.encapsulationPublicKey,\n principalHead: input.managedPrincipalHead,\n })),\n userRecipientKey: null,\n };\n }\n\n return wrapContainerKeyToRootUser({\n containerKey: input.containerKey,\n containerKeyEpochId: input.containerKeyEpochId,\n manifestHash: input.manifestHash,\n recipientEncapsulationPublicKey: input.recipientEncapsulationPublicKey,\n userId: input.userId,\n });\n}\n\nasync function wrapRootContainerRecipients(\n input: Parameters<typeof wrapRootContainerKeyForPlan>[0] & {\n memberGroup: CreateOrganizationGroupRequest | null;\n memberHead: ContainerGrantPrincipalHead | null;\n },\n) {\n const root = await wrapRootContainerKeyForPlan(input);\n const member =\n input.memberGroup && input.memberHead\n ? await wrapContainerKeyToManagedPrincipal({\n ...input,\n principalEncapsulationPublicKey:\n input.memberGroup.initialGroupPolicy.state.encapsulationPublicKey,\n principalHead: input.memberHead,\n })\n : null;\n return {\n recipientTargets: [\n root.recipientTarget,\n ...(member ? [member.recipientTarget] : []),\n ],\n wraps: [root.wrap, ...(member ? [member.wrap] : [])],\n userRecipientKeys: root.userRecipientKey ? [root.userRecipientKey] : [],\n };\n}\n\nfunction rootKeyMaterial(key?: Uint8Array): Uint8Array {\n const material = key ?? crypto.getRandomValues(new Uint8Array(32));\n if (material.byteLength !== 32)\n throw new Error(\"Container KEK material must be 32 bytes\");\n return material;\n}\n\nfunction normalizedRootCreateBody(\n input: Parameters<typeof buildRootContainerCreateBody>[0],\n): ContainerCreateAccessEventBody {\n const body = normalizeContainerAccessEventBody(\n readCanonicalJson(buildRootContainerCreateBody(input), \"Root create body\"),\n );\n if (body.eventType !== \"container.create\")\n throw new Error(\"Expected root creation body\");\n return body;\n}\n\nexport async function buildRootContainerCreatePlan(input: {\n adminGroup?: CreateOrganizationGroupRequest | undefined;\n memberGroup?: CreateOrganizationGroupRequest | undefined;\n systemSlot?: ContainerSystemSlot | undefined;\n author: ContainerMutationAuthor;\n containerId: string;\n containerKey?: Uint8Array | undefined;\n metadataDocumentId: string;\n recipientEncapsulationPublicKey: Uint8Array;\n signedAt?: string | undefined;\n}): Promise<MaterializedContainerCreatePlan> {\n const containerKey = rootKeyMaterial(input.containerKey);\n const adminGroup = input.adminGroup ?? null;\n const { managedPrincipalHead, managedPrincipalPolicies } =\n await buildRootManagedPrincipalContext(adminGroup);\n\n const member = await buildRootManagedPrincipalContext(\n input.memberGroup ?? null,\n );\n if (input.memberGroup && !adminGroup)\n throw new Error(\"Members root grant requires Admins authority\");\n managedPrincipalPolicies.push(...member.managedPrincipalPolicies);\n const containerKeyEpochId = await resolveContainerKekEpochId({\n containerId: input.containerId,\n keyEpoch: 1,\n keyMaterial: containerKey,\n });\n const body = normalizedRootCreateBody({\n containerKeyPublicKey: await deriveContainerKekWrappingPublicKey({\n containerId: input.containerId,\n keyMaterial: containerKey,\n }),\n memberHead: member.managedPrincipalHead,\n systemSlot: input.systemSlot ?? null,\n author: input.author,\n containerKeyEpochId,\n managedPrincipalHead,\n metadataDocumentId: input.metadataDocumentId,\n });\n const { event, eventHash, keyEpoch, manifest, manifestHash, state } =\n await deriveRootCreateArtifacts({\n author: input.author,\n body,\n containerId: input.containerId,\n containerKeyEpochId,\n metadataDocumentId: input.metadataDocumentId,\n signedAt: input.signedAt,\n });\n const { recipientTargets, wraps, userRecipientKeys } =\n await wrapRootContainerRecipients({\n memberGroup: input.memberGroup ?? null,\n memberHead: member.managedPrincipalHead,\n adminGroup,\n containerKey,\n containerKeyEpochId,\n manifestHash,\n managedPrincipalHead,\n recipientEncapsulationPublicKey: input.recipientEncapsulationPublicKey,\n userId: input.author.signerUserId,\n });\n const keyTargetHash =\n await computeContainerKekRecipientTargetHash(recipientTargets);\n const keyEpochHash = await computeContainerKeyEpochHash(keyEpoch);\n const plan: ContainerCreatePlan = {\n body,\n containerId: input.containerId,\n containerKeyEpochId,\n event,\n eventHash,\n keyEpoch,\n keyEpochHash,\n keyTargetHash,\n manifest,\n manifestHash,\n metadataDocumentId: input.metadataDocumentId,\n parentContainerId: null,\n parentManifestHash: null,\n recipientTargets,\n request: buildRootContainerCreateRequest({\n body,\n event,\n keyEpoch,\n manifest,\n manifestHash,\n principalPolicies: managedPrincipalPolicies,\n userRecipientKeys,\n wraps,\n }),\n state,\n wraps,\n };\n\n return { containerKey, plan };\n}\n\nexport function rootContainerWriterProjectionFromCreatePlan(\n plan: ContainerCreatePlan,\n): ContainerWriterProjectionResponse {\n return {\n policyEvidence: {\n organization: null,\n organizationPayloads: [],\n groups: [],\n },\n containerId: plan.containerId,\n organizationId: plan.state.organizationId,\n path: [\n {\n event: {\n event: readCanonicalRecord(plan.event, \"Container root event\"),\n body: readCanonicalRecord(plan.body, \"Container root body\"),\n eventHash: plan.eventHash,\n },\n manifest: readCanonicalRecord(plan.manifest, \"Container root manifest\"),\n manifestHash: plan.manifestHash,\n state: readCanonicalRecord(plan.state, \"Container root state\"),\n },\n ],\n containerKeks: [\n {\n containerId: plan.containerId,\n accessManifestHash: plan.manifestHash,\n containerKeyEpochId: plan.containerKeyEpochId,\n containerKeyEpoch: plan.keyEpoch.keyEpoch,\n keyEpoch: readCanonicalRecord(\n plan.keyEpoch,\n \"Container root key epoch\",\n ),\n keyEpochHash: plan.keyEpochHash,\n keyTargetHash: plan.keyTargetHash,\n containerManifestHistory: [],\n parentContainerKeyEpochId: null,\n keyring: null,\n recipientTargets: readCanonicalRecords(\n plan.recipientTargets,\n \"Container root recipient targets\",\n ),\n wraps: readCanonicalRecords(plan.wraps, \"Container root wraps\"),\n },\n ],\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"create.js","sourceRoot":"","sources":["create.ts"],"names":[],"mappings":"AASA,OAAO,EACL,sCAAsC,EACtC,4BAA4B,EAC5B,mCAAmC,EACnC,iCAAiC,GAClC,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EACL,wBAAwB,EACxB,4BAA4B,EAC5B,6BAA6B,EAC7B,0BAA0B,EAC1B,wBAAwB,GACzB,MAAM,wCAAwC,CAAC;AAChD,OAAO,EACL,kCAAkC,EAClC,0BAA0B,GAC3B,MAAM,4CAA4C,CAAC;AAMpD,OAAO,EACL,iBAAiB,EACjB,mBAAmB,EACnB,oBAAoB,GACrB,MAAM,oCAAoC,CAAC;AAE5C,OAAO,EACL,mCAAmC,EACnC,2CAA2C,GAC5C,MAAM,sBAAsB,CAAC;AAE9B,SAAS,4BAA4B,CAAC,KAQrC;IACC,MAAM,QAAQ,GAAG,wBAAwB,CAAC;QACxC,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;QAC9C,qBAAqB,EAAE,KAAK,CAAC,qBAAqB;QAClD,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,iBAAiB,EAAE,IAAI;QACvB,kBAAkB,EAAE,IAAI;KACzB,CAAC,CAAC;IACH,IAAI,KAAK,CAAC,oBAAoB,EAAE,CAAC;QAC/B,OAAO;YACL,GAAG,QAAQ;YACX,YAAY,EAAE;gBACZ;oBACE,WAAW,EAAE,OAAO;oBACpB,SAAS,EAAE,KAAK,CAAC,oBAAoB,CAAC,WAAW;oBACjD,WAAW,EAAE,KAAK,CAAC,oBAAoB,CAAC,aAAa;iBACtD;gBACD,GAAG,CAAC,KAAK,CAAC,UAAU;oBAClB,CAAC,CAAC;wBACE;4BACE,WAAW,EAAE,MAAe;4BAC5B,SAAS,EAAE,KAAK,CAAC,UAAU,CAAC,WAAW;4BACvC,WAAW,EAAE,O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CAAkC,CACnC;gBACD,KAAK,EAAE,oBAAoB,CAAC,IAAI,CAAC,KAAK,EAAE,sBAAsB,CAAC;aAChE;SACF;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n AccessEvent,\n AccessManifest,\n ContainerCreateAccessEventBody,\n ContainerGrantPrincipalHead,\n ContainerKeyEpoch,\n ContainerKeyWrap,\n ContainerUserRecipientKey,\n} from \"@tearleads/crypto\";\nimport {\n computeContainerKekRecipientTargetHash,\n computeContainerKeyEpochHash,\n deriveContainerKekWrappingPublicKey,\n normalizeContainerAccessEventBody,\n} from \"@tearleads/crypto\";\nimport type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type {\n ContainerMutationRequest,\n CreateOrganizationGroupRequest,\n} from \"@tearleads/validators/request\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n buildContainerCreateBody,\n buildContainerCreateKeyEpoch,\n deriveContainerCreateManifest,\n resolveContainerKekEpochId,\n signContainerCreateEvent,\n} from \"../../../data/containers/shared/events\";\nimport {\n wrapContainerKeyToManagedPrincipal,\n wrapContainerKeyToRootUser,\n} from \"../../../data/containers/shared/projection\";\nimport type {\n ContainerCreatePlan,\n ContainerMutationAuthor,\n MaterializedContainerCreatePlan,\n} from \"../../../data/containers/shared/types\";\nimport {\n readCanonicalJson,\n readCanonicalRecord,\n readCanonicalRecords,\n} from \"../../../data/keying/canonicalJson\";\n\nimport {\n principalHeadFromInitialGroupPolicy,\n principalPolicyRecordFromInitialGroupPolicy,\n} from \"./initialGroupPolicy\";\n\nfunction buildRootContainerCreateBody(input: {\n author: ContainerMutationAuthor;\n managedPrincipalHead: ContainerGrantPrincipalHead | null;\n containerKeyEpochId: string;\n containerKeyPublicKey: string;\n metadataDocumentId: string;\n memberHead: ContainerGrantPrincipalHead | null;\n systemSlot: ContainerSystemSlot | null;\n}): ContainerCreateAccessEventBody {\n const baseBody = buildContainerCreateBody({\n systemSlot: input.systemSlot,\n containerKeyEpochId: input.containerKeyEpochId,\n containerKeyPublicKey: input.containerKeyPublicKey,\n metadataDocumentId: input.metadataDocumentId,\n parentContainerId: null,\n parentManifestHash: null,\n });\n if (input.managedPrincipalHead) {\n return {\n ...baseBody,\n directGrants: [\n {\n accessLevel: \"admin\",\n subjectId: input.managedPrincipalHead.principalId,\n subjectType: input.managedPrincipalHead.principalType,\n },\n ...(input.memberHead\n ? [\n {\n accessLevel: \"read\" as const,\n subjectId: input.memberHead.principalId,\n subjectType: \"group\" as const,\n },\n ]\n : []),\n ],\n referencedPrincipalHeads: [\n input.managedPrincipalHead,\n ...(input.memberHead ? [input.memberHead] : []),\n ],\n };\n }\n\n return {\n ...baseBody,\n directGrants: [\n {\n accessLevel: \"admin\",\n subjectId: input.author.signerUserId,\n subjectType: \"user\",\n },\n ],\n };\n}\n\nfunction buildRootContainerCreateRequest(input: {\n body: ContainerCreateAccessEventBody;\n event: AccessEvent;\n keyEpoch: ContainerKeyEpoch;\n manifest: AccessManifest;\n manifestHash: string;\n principalPolicies: readonly Record<string, unknown>[];\n userRecipientKeys: readonly ContainerUserRecipientKey[];\n wraps: readonly ContainerKeyWrap[];\n}): ContainerMutationRequest {\n return {\n event: readCanonicalRecord(input.event, \"Container root create event\"),\n body: readCanonicalRecord(input.body, \"Container root create body\"),\n expectedManifestHash: input.manifestHash,\n manifest: readCanonicalRecord(\n input.manifest,\n \"Container root create manifest\",\n ),\n previousManifestRef: null,\n parentContainerPathRefs: [],\n principalPolicies: readCanonicalRecords(\n input.principalPolicies,\n \"Container root create principal policies\",\n ),\n keyEpoch: readCanonicalRecord(\n input.keyEpoch,\n \"Container root create key epoch\",\n ),\n predecessorBridge: null,\n keyring: null,\n wraps: readCanonicalRecords(input.wraps, \"Container root create wraps\"),\n userRecipientKeys: readCanonicalRecords(\n input.userRecipientKeys,\n \"Container root create user recipient keys\",\n ),\n };\n}\n\nasync function buildRootManagedPrincipalContext(\n adminGroup: CreateOrganizationGroupRequest | null,\n): Promise<{\n managedPrincipalHead: ContainerGrantPrincipalHead | null;\n managedPrincipalPolicies: Record<string, unknown>[];\n}> {\n if (!adminGroup) {\n return {\n managedPrincipalHead: null,\n managedPrincipalPolicies: [],\n };\n }\n\n const managedPrincipalHead = await principalHeadFromInitialGroupPolicy({\n principalId: adminGroup.groupId,\n policy: adminGroup.initialGroupPolicy,\n });\n\n return {\n managedPrincipalHead,\n managedPrincipalPolicies: [\n principalPolicyRecordFromInitialGroupPolicy({\n head: managedPrincipalHead,\n policy: adminGroup.initialGroupPolicy,\n }),\n ],\n };\n}\n\nasync function deriveRootCreateArtifacts(input: {\n author: ContainerMutationAuthor;\n body: ContainerCreateAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n metadataDocumentId: string;\n signedAt: string | undefined;\n}) {\n if (!input.body.containerKeyPublicKey)\n throw new Error(\"Root container public key is missing\");\n const { event, eventHash } = await signContainerCreateEvent({\n author: input.author,\n body: input.body,\n containerId: input.containerId,\n eventId: crypto.randomUUID(),\n // A root container belongs to the creator's own organization.\n organizationId: input.author.organizationId,\n parentPath: [],\n signedAt: input.signedAt ?? new Date().toISOString(),\n });\n const { manifest, manifestHash, state } = await deriveContainerCreateManifest(\n {\n systemSlot: input.body.systemSlot,\n containerId: input.containerId,\n containerKeyEpochId: input.containerKeyEpochId,\n containerKeyPublicKey: input.body.containerKeyPublicKey,\n directGrants: input.body.directGrants,\n eventHash,\n metadataDocumentId: input.metadataDocumentId,\n // A root container belongs to the creator's own organization.\n organizationId: input.author.organizationId,\n parentContainerId: null,\n parentManifestHash: null,\n referencedPrincipalHeads: input.body.referencedPrincipalHeads,\n },\n );\n const keyEpoch = buildContainerCreateKeyEpoch({\n containerId: input.containerId,\n containerKeyEpochId: input.containerKeyEpochId,\n eventHash,\n manifestHash,\n parentContainerKeyEpochId: null,\n });\n return { event, eventHash, keyEpoch, manifest, manifestHash, state };\n}\n\nasync function wrapRootContainerKeyForPlan(input: {\n adminGroup: CreateOrganizationGroupRequest | null;\n containerKey: Uint8Array;\n containerKeyEpochId: string;\n manifestHash: string;\n managedPrincipalHead: ContainerGrantPrincipalHead | null;\n recipientEncapsulationPublicKey: Uint8Array;\n userId: string;\n}) {\n if (input.adminGroup && input.managedPrincipalHead) {\n return {\n ...(await wrapContainerKeyToManagedPrincipal({\n containerKey: input.containerKey,\n containerKeyEpochId: input.containerKeyEpochId,\n manifestHash: input.manifestHash,\n principalEncapsulationPublicKey:\n input.adminGroup.initialGroupPolicy.state.encapsulationPublicKey,\n principalHead: input.managedPrincipalHead,\n })),\n userRecipientKey: null,\n };\n }\n\n return wrapContainerKeyToRootUser({\n containerKey: input.containerKey,\n containerKeyEpochId: input.containerKeyEpochId,\n manifestHash: input.manifestHash,\n recipientEncapsulationPublicKey: input.recipientEncapsulationPublicKey,\n userId: input.userId,\n });\n}\n\nasync function wrapRootContainerRecipients(\n input: Parameters<typeof wrapRootContainerKeyForPlan>[0] & {\n memberGroup: CreateOrganizationGroupRequest | null;\n memberHead: ContainerGrantPrincipalHead | null;\n },\n) {\n const root = await wrapRootContainerKeyForPlan(input);\n const member =\n input.memberGroup && input.memberHead\n ? await wrapContainerKeyToManagedPrincipal({\n ...input,\n principalEncapsulationPublicKey:\n input.memberGroup.initialGroupPolicy.state.encapsulationPublicKey,\n principalHead: input.memberHead,\n })\n : null;\n return {\n recipientTargets: [\n root.recipientTarget,\n ...(member ? [member.recipientTarget] : []),\n ],\n wraps: [root.wrap, ...(member ? [member.wrap] : [])],\n userRecipientKeys: root.userRecipientKey ? [root.userRecipientKey] : [],\n };\n}\n\nfunction rootKeyMaterial(key?: Uint8Array): Uint8Array {\n const material = key ?? crypto.getRandomValues(new Uint8Array(32));\n if (material.byteLength !== 32)\n throw new Error(\"Container KEK material must be 32 bytes\");\n return material;\n}\n\nfunction normalizedRootCreateBody(\n input: Parameters<typeof buildRootContainerCreateBody>[0],\n): ContainerCreateAccessEventBody {\n const body = normalizeContainerAccessEventBody(\n readCanonicalJson(buildRootContainerCreateBody(input), \"Root create body\"),\n );\n if (body.eventType !== \"container.create\")\n throw new Error(\"Expected root creation body\");\n return body;\n}\n\nexport async function buildRootContainerCreatePlan(input: {\n adminGroup?: CreateOrganizationGroupRequest | undefined;\n memberGroup?: CreateOrganizationGroupRequest | undefined;\n systemSlot?: ContainerSystemSlot | undefined;\n author: ContainerMutationAuthor;\n containerId: string;\n containerKey?: Uint8Array | undefined;\n metadataDocumentId: string;\n recipientEncapsulationPublicKey: Uint8Array;\n signedAt?: string | undefined;\n}): Promise<MaterializedContainerCreatePlan> {\n const containerKey = rootKeyMaterial(input.containerKey);\n const adminGroup = input.adminGroup ?? null;\n const { managedPrincipalHead, managedPrincipalPolicies } =\n await buildRootManagedPrincipalContext(adminGroup);\n\n const member = await buildRootManagedPrincipalContext(\n input.memberGroup ?? null,\n );\n if (input.memberGroup && !adminGroup)\n throw new Error(\"Members root grant requires Admins authority\");\n managedPrincipalPolicies.push(...member.managedPrincipalPolicies);\n const containerKeyEpochId = await resolveContainerKekEpochId({\n containerId: input.containerId,\n keyEpoch: 1,\n keyMaterial: containerKey,\n });\n const body = normalizedRootCreateBody({\n containerKeyPublicKey: await deriveContainerKekWrappingPublicKey({\n containerId: input.containerId,\n keyMaterial: containerKey,\n }),\n memberHead: member.managedPrincipalHead,\n systemSlot: input.systemSlot ?? null,\n author: input.author,\n containerKeyEpochId,\n managedPrincipalHead,\n metadataDocumentId: input.metadataDocumentId,\n });\n const { event, eventHash, keyEpoch, manifest, manifestHash, state } =\n await deriveRootCreateArtifacts({\n author: input.author,\n body,\n containerId: input.containerId,\n containerKeyEpochId,\n metadataDocumentId: input.metadataDocumentId,\n signedAt: input.signedAt,\n });\n const { recipientTargets, wraps, userRecipientKeys } =\n await wrapRootContainerRecipients({\n memberGroup: input.memberGroup ?? null,\n memberHead: member.managedPrincipalHead,\n adminGroup,\n containerKey,\n containerKeyEpochId,\n manifestHash,\n managedPrincipalHead,\n recipientEncapsulationPublicKey: input.recipientEncapsulationPublicKey,\n userId: input.author.signerUserId,\n });\n const keyTargetHash =\n await computeContainerKekRecipientTargetHash(recipientTargets);\n const keyEpochHash = await computeContainerKeyEpochHash(keyEpoch);\n const plan: ContainerCreatePlan = {\n body,\n containerId: input.containerId,\n containerKeyEpochId,\n event,\n eventHash,\n keyEpoch,\n keyEpochHash,\n keyTargetHash,\n manifest,\n manifestHash,\n metadataDocumentId: input.metadataDocumentId,\n parentContainerId: null,\n parentManifestHash: null,\n recipientTargets,\n request: buildRootContainerCreateRequest({\n body,\n event,\n keyEpoch,\n manifest,\n manifestHash,\n principalPolicies: managedPrincipalPolicies,\n userRecipientKeys,\n wraps,\n }),\n state,\n wraps,\n };\n\n return { containerKey, plan };\n}\n\nexport function rootContainerWriterProjectionFromCreatePlan(\n plan: ContainerCreatePlan,\n): ContainerWriterProjectionResponse {\n return {\n policyEvidence: {\n organization: null,\n organizationPayloads: [],\n groups: [],\n },\n containerId: plan.containerId,\n organizationId: plan.state.organizationId,\n path: [\n {\n event: {\n event: readCanonicalRecord(plan.event, \"Container root event\"),\n body: readCanonicalRecord(plan.body, \"Container root body\"),\n eventHash: plan.eventHash,\n },\n manifest: readCanonicalRecord(plan.manifest, \"Container root manifest\"),\n manifestHash: plan.manifestHash,\n state: readCanonicalRecord(plan.state, \"Container root state\"),\n },\n ],\n containerKeks: [\n {\n containerId: plan.containerId,\n accessManifestHash: plan.manifestHash,\n containerKeyEpochId: plan.containerKeyEpochId,\n containerKeyEpoch: plan.keyEpoch.keyEpoch,\n keyEpoch: readCanonicalRecord(\n plan.keyEpoch,\n \"Container root key epoch\",\n ),\n keyEpochHash: plan.keyEpochHash,\n keyTargetHash: plan.keyTargetHash,\n containerManifestHistory: [],\n parentContainerKeyEpochId: null,\n keyring: null,\n recipientTargets: readCanonicalRecords(\n plan.recipientTargets,\n \"Container root recipient targets\",\n ),\n wraps: readCanonicalRecords(plan.wraps, \"Container root wraps\"),\n },\n ],\n };\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { computePrincipalStateHash } from "../../../internal/crypto/index.js";
|
|
2
|
-
import { readCanonicalRecord } from "../../../data/
|
|
2
|
+
import { readCanonicalRecord } from "../../../data/keying/canonicalJson.js";
|
|
3
3
|
export async function principalHeadFromInitialGroupPolicy(input) {
|
|
4
4
|
return {
|
|
5
5
|
principalType: "group",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"initialGroupPolicy.js","sourceRoot":"","sources":["initialGroupPolicy.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AAE9D,OAAO,EAAE,mBAAmB,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"initialGroupPolicy.js","sourceRoot":"","sources":["initialGroupPolicy.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AAE9D,OAAO,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AAUzE,MAAM,CAAC,KAAK,UAAU,mCAAmC,CACvD,KAAqC;IAErC,OAAO;QACL,aAAa,EAAE,OAAO;QACtB,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO;QACnC,QAAQ,EAAE,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ;QACrC,SAAS,EAAE,MAAM,yBAAyB,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC;QAC9D,cAAc,EAAE,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,cAAc;KAClD,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,2CAA2C,CAAC,KAG3D;IACC,MAAM,EAAE,IAAI,EAAE,GAAG,KAAK,CAAC;IAEvB,OAAO,mBAAmB,CACxB;QACE,aAAa,EAAE,IAAI,CAAC,aAAa;QACjC,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,OAAO,EAAE,IAAI,CAAC,OAAO;QACrB,QAAQ,EAAE,IAAI,CAAC,QAAQ;QACvB,SAAS,EAAE,IAAI,CAAC,SAAS;QACzB,KAAK,EAAE;YACL,GAAG,KAAK,CAAC,MAAM,CAAC,KAAK;YACrB,SAAS,EAAE,IAAI,CAAC,SAAS;SAC1B;QACD,UAAU,EAAE,KAAK,CAAC,MAAM,CAAC,UAAU;QACnC,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,MAAM;QAC3B,UAAU,EAAE;YACV,aAAa,EAAE,IAAI,CAAC,aAAa;YACjC,WAAW,EAAE,IAAI,CAAC,WAAW;YAC7B,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,SAAS,EAAE,IAAI,CAAC,SAAS;SAC1B;KACF,EACD,kCAAkC,CACnC,CAAC;AACJ,CAAC","sourcesContent":["import type {\n ContainerGrantPrincipalHead,\n ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { computePrincipalStateHash } from \"@tearleads/crypto\";\nimport type { CreateOrganizationGroupRequest } from \"@tearleads/validators/request\";\nimport { readCanonicalRecord } from \"../../../data/keying/canonicalJson\";\n\ntype InitialManagedPrincipalPolicy =\n CreateOrganizationGroupRequest[\"initialGroupPolicy\"];\n\ninterface RootManagedPrincipalGrantInput {\n readonly principalId: string;\n readonly policy: InitialManagedPrincipalPolicy;\n}\n\nexport async function principalHeadFromInitialGroupPolicy(\n input: RootManagedPrincipalGrantInput,\n): Promise<ContainerGrantPrincipalHead> {\n return {\n principalType: \"group\",\n principalId: input.principalId,\n version: input.policy.state.version,\n keyEpoch: input.policy.state.keyEpoch,\n stateHash: await computePrincipalStateHash(input.policy.state),\n keyFingerprint: input.policy.state.keyFingerprint,\n };\n}\n\nexport function principalPolicyRecordFromInitialGroupPolicy(input: {\n readonly head: ReferencedPrincipalHead;\n readonly policy: InitialManagedPrincipalPolicy;\n}): Record<string, unknown> {\n const { head } = input;\n\n return readCanonicalRecord(\n {\n principalType: head.principalType,\n principalId: head.principalId,\n version: head.version,\n keyEpoch: head.keyEpoch,\n stateHash: head.stateHash,\n state: {\n ...input.policy.state,\n stateHash: head.stateHash,\n },\n projection: input.policy.projection,\n grants: input.policy.grants,\n checkpoint: {\n principalType: head.principalType,\n principalId: head.principalId,\n version: head.version,\n stateHash: head.stateHash,\n },\n },\n \"Initial managed principal policy\",\n );\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type ContainerWriterProjectionResponse, type DocumentCreateResponse } from "../../internal/validators/response/index.js";
|
|
2
2
|
import type { CreateRemoteDocumentResult, DocumentCreateApi, DocumentCreateAuthor, MaterializedDocumentCreatePlan, ProjectionVerificationOptions } from "../../data/documents/shared/types.js";
|
|
3
|
-
import type { ProjectionUserKeyResolver, ReferencedPrincipalPolicyWarmer } from "../../data/keyingProjectionVerification.js";
|
|
3
|
+
import type { ProjectionUserKeyResolver, ReferencedPrincipalPolicyWarmer } from "../../data/keyingProjectionVerification/index.js";
|
|
4
4
|
import type { ExecSql } from "../../data/sqlite/sqlSchema.js";
|
|
5
5
|
import type { DocumentCreateTerminalFailureHandler } from "./createProjectionFetch.js";
|
|
6
6
|
export declare function buildMaterializedDocumentCreatePlan(input: {
|
|
@@ -3,7 +3,7 @@ import { assertContainerAuthorAccess } from "../../data/containers/shared/author
|
|
|
3
3
|
import { buildDocumentCreatePlan } from "../../data/documents/shared/events.js";
|
|
4
4
|
import { wrapDocumentContentKeyForCreate } from "../../data/documents/shared/projection.js";
|
|
5
5
|
import { projectionVerificationOptions } from "../../data/documents/shared/types.js";
|
|
6
|
-
import { collectContainerWriterProjectionPrincipalPolicies, nullOnProjectionVerificationCancellation, requireProjectionUserKeyResolver, } from "../../data/keyingProjectionVerification.js";
|
|
6
|
+
import { collectContainerWriterProjectionPrincipalPolicies, nullOnProjectionVerificationCancellation, requireProjectionUserKeyResolver, } from "../../data/keyingProjectionVerification/index.js";
|
|
7
7
|
import { isContainerCreatePending } from "../../data/persistence/container-contents/pendingContainerCreate.js";
|
|
8
8
|
import { recordDocumentAuthorAccessFailure } from "./authorAccessFailure.js";
|
|
9
9
|
import { adoptExistingRemoteDocument } from "./createAdoption.js";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { mergeVersionVectors, satisfiesVersionVector } from "../../internal/loro/index.js";
|
|
2
|
-
import { canWriteEffectiveAccessLevel } from "../../data/accessLevel.js";
|
|
3
2
|
import { documentSyncPullContinuationsEqual, } from "../../data/documents/shared/syncPagination.js";
|
|
3
|
+
import { canWriteEffectiveAccessLevel } from "../../data/keying/accessLevel.js";
|
|
4
4
|
import { mergePersistedDocumentHistory } from "./historyContent.js";
|
|
5
5
|
function sameNullableDocumentValue(left, right) {
|
|
6
6
|
return (left ?? null) === (right ?? null);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentMutationPreparation.js","sourceRoot":"","sources":["documentMutationPreparation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAC9E,OAAO,EAAE,4BAA4B,EAAE,MAAM,wBAAwB,CAAC;AACtE,OAAO,EAEL,kCAAkC,GACnC,MAAM,4CAA4C,CAAC;AAMpD,OAAO,EAAE,6BAA6B,EAAE,MAAM,kBAAkB,CAAC;AAyBjE,SAAS,yBAAyB,CAChC,IAA+B,EAC/B,KAAgC;IAEhC,OAAO,CAAC,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC;AAC5C,CAAC;AAED,MAAM,UAAU,kCAAkC,CAChD,OAAoC,EACpC,QAA8B;IAE9B,OAAO,CACL,OAAO,KAAK,IAAI;QAChB,OAAO,CAAC,EAAE,KAAK,QAAQ,CAAC,EAAE;QAC1B,OAAO,CAAC,UAAU,KAAK,QAAQ,CAAC,UAAU;QAC1C,OAAO,CAAC,WAAW,KAAK,QAAQ,CAAC,WAAW;QAC5C,OAAO,CAAC,WAAW,KAAK,QAAQ,CAAC,WAAW;QAC5C,yBAAyB,CACvB,OAAO,CAAC,e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,EAAE,IAAI,EAAE,sBAAsB,EAAE,IAAI,EAAE;YACpE,CAAC,CAAC,0BAA0B,CACxB,qBAAqB,EACrB,KAAK,CAAC,iBAAiB,CACxB,CAAC;IACV,MAAM,uBAAuB,GAAG,8BAA8B,CAC5D,KAAK,EACL,oBAAoB,CACrB,CAAC;IAEF,IAAI,uBAAuB,IAAI,sBAAsB,EAAE,CAAC;QACtD,MAAM,6BAA6B,CAAC;YAClC,GAAG,EAAE,KAAK,CAAC,UAAU;YACrB,OAAO;YACP,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,WAAW,EAAE,KAAK,CAAC,WAAW;SAC/B,CAAC,CAAC;IACL,CAAC;IACD,MAAM,aAAa,GAAG,0BAA0B;QAC9C,CAAC,CAAC,EAAE;QACJ,CAAC,CAAC,uBAAuB,IAAI,oBAAoB;YAC/C,CAAC,CAAC,sBAAsB,CAAC,KAAK,EAAE,oBAAoB,CAAC;YACrD,CAAC,CAAC,KAAK,CAAC;IACZ,MAAM,sBAAsB,GAAG,uBAAuB,CAAC,aAAa,CAAC;QACnE,CAAC,CAAC,SAAS;QACX,CAAC,CAAC,MAAM,KAAK,CAAC,WAAW,CAAC,qBAAqB,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;IAC1E,OAAO;QACL,kBAAkB;QAClB,qBAAqB;QACrB,0BAA0B;QAC1B,aAAa,EACX,sBAAsB,KAAK,SAAS;YAClC,CAAC,CAAC,aAAa;YACf,CAAC,CAAC,EAAE,GAAG,aAAa,EAAE,WAAW,EAAE,sBAAsB,CAAC,WAAW,EAAE;QAC3E,sBAAsB;KACvB,CAAC;AACJ,CAAC","sourcesContent":["import { mergeVersionVectors, satisfiesVersionVector } from \"@tearleads/loro\";\nimport { canWriteEffectiveAccessLevel } from \"../../data/accessLevel\";\nimport {\n type DocumentSyncPullContinuation,\n documentSyncPullContinuationsEqual,\n} from \"../../data/documents/shared/syncPagination\";\nimport type {\n DocumentsPersistence,\n StoredDocumentRecord,\n} from \"../../data/persistence/documents/documentsPersistence\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { mergePersistedDocumentHistory } from \"./historyContent\";\n\nexport interface ExpectedDocumentSyncState {\n pullContinuation: DocumentSyncPullContinuation | null;\n record: StoredDocumentRecord;\n}\n\nexport interface PrepareDocumentMutationInput {\n currentDoc: Parameters<typeof mergePersistedDocumentHistory>[0][\"doc\"];\n currentRecord: StoredDocumentRecord | null;\n expectedSyncState?: ExpectedDocumentSyncState | undefined;\n historyCheckpoint?:\n | {\n coveredTailIds: readonly string[];\n endVersionVector: string;\n pruneCoveredLocalState: boolean;\n snapshot: string;\n }\n | undefined;\n historyUpdateOrigin?: \"local\" | \"remote\" | undefined;\n historyUpdates?: readonly string[] | undefined;\n localId: string;\n persistence: DocumentsPersistence;\n}\n\nfunction sameNullableDocumentValue(\n left: string | null | undefined,\n right: string | null | undefined,\n): boolean {\n return (left ?? null) === (right ?? null);\n}\n\nexport function documentSyncSecurityContextMatches(\n current: StoredDocumentRecord | null,\n expected: StoredDocumentRecord,\n): boolean {\n return (\n current !== null &&\n current.id === expected.id &&\n current.documentId === expected.documentId &&\n current.containerId === expected.containerId &&\n current.accessEpoch === expected.accessEpoch &&\n sameNullableDocumentValue(\n current.accessStateHash,\n expected.accessStateHash,\n ) &&\n (current.effectiveAccessLevel ?? null) ===\n (expected.effectiveAccessLevel ?? null) &&\n sameNullableDocumentValue(\n current.contentKeyBundle,\n expected.contentKeyBundle,\n ) &&\n sameNullableDocumentValue(\n current.documentKekTargets,\n expected.documentKekTargets,\n ) &&\n sameNullableDocumentValue(\n current.documentManifestBundle,\n expected.documentManifestBundle,\n )\n );\n}\n\nfunction patchSpecifiesContainer(\n patch: Partial<StoredDocumentRecord>,\n): boolean {\n return Object.hasOwn(patch, \"containerId\");\n}\n\nfunction documentSyncStateDiffers(\n current: StoredDocumentRecord,\n cached: StoredDocumentRecord,\n): boolean {\n return (\n !sameNullableDocumentValue(current.lastCommitLsn, cached.lastCommitLsn) ||\n current.snapshotEndVersion !== cached.snapshotEndVersion ||\n !sameNullableDocumentValue(\n current.pendingBaseVersion,\n cached.pendingBaseVersion,\n ) ||\n !documentSyncPullContinuationsEqual(\n current.pullContinuation,\n cached.pullContinuation,\n ) ||\n Boolean(current.pullContinuationRecoveryRequired) !==\n Boolean(cached.pullContinuationRecoveryRequired)\n );\n}\n\nfunction mergeMutationFrontiers(\n patch: Partial<StoredDocumentRecord>,\n durableRecord: StoredDocumentRecord,\n): Partial<StoredDocumentRecord> {\n const nextPatch = { ...patch };\n if (patch.snapshotEndVersion !== undefined) {\n nextPatch.snapshotEndVersion = mergeVersionVectors([\n durableRecord.snapshotEndVersion,\n patch.snapshotEndVersion,\n ]);\n }\n if (\n patch.pendingBaseVersion !== undefined &&\n patch.pendingBaseVersion !== null &&\n durableRecord.pendingBaseVersion\n ) {\n nextPatch.pendingBaseVersion = mergeVersionVectors([\n durableRecord.pendingBaseVersion,\n patch.pendingBaseVersion,\n ]);\n }\n return nextPatch;\n}\n\nfunction ordinarySaveNeedsHistoryRebase(\n input: PrepareDocumentMutationInput,\n durableRecord: StoredDocumentRecord | null,\n): boolean {\n if (\n input.expectedSyncState !== undefined ||\n durableRecord === null ||\n input.currentRecord === null\n ) {\n return false;\n }\n const cachedPendingBase = input.currentRecord.pendingBaseVersion;\n const durableCoversCachedPendingBase =\n !cachedPendingBase ||\n (durableRecord.pendingBaseVersion !== null &&\n durableRecord.pendingBaseVersion !== undefined &&\n satisfiesVersionVector(\n durableRecord.pendingBaseVersion,\n cachedPendingBase,\n ));\n return (\n durableRecord.id === input.currentRecord.id &&\n durableRecord.documentId === input.currentRecord.documentId &&\n satisfiesVersionVector(\n durableRecord.snapshotEndVersion,\n input.currentRecord.snapshotEndVersion,\n ) &&\n durableCoversCachedPendingBase &&\n documentSyncStateDiffers(durableRecord, input.currentRecord)\n );\n}\n\nfunction ordinarySaveIdentityWasReplaced(\n input: PrepareDocumentMutationInput,\n durableRecord: StoredDocumentRecord | null,\n): boolean {\n return (\n input.expectedSyncState === undefined &&\n input.currentRecord !== null &&\n durableRecord !== null &&\n (durableRecord.id !== input.currentRecord.id ||\n durableRecord.documentId !== input.currentRecord.documentId)\n );\n}\n\nfunction ordinarySaveWriteAccessWasRevoked(\n input: PrepareDocumentMutationInput,\n durableRecord: StoredDocumentRecord | null,\n): boolean {\n return (\n input.expectedSyncState === undefined &&\n input.currentRecord !== null &&\n durableRecord !== null &&\n canWriteEffectiveAccessLevel(input.currentRecord.effectiveAccessLevel) &&\n !canWriteEffectiveAccessLevel(durableRecord.effectiveAccessLevel)\n );\n}\n\nfunction recoveryGenerationWasSuperseded(\n input: PrepareDocumentMutationInput,\n durableRecord: StoredDocumentRecord | null,\n): boolean {\n return (\n input.currentRecord !== null &&\n durableRecord !== null &&\n (input.currentRecord.recoveryGeneration ?? 0) !==\n (durableRecord.recoveryGeneration ?? 0)\n );\n}\n\nfunction resolveSyncSettlementState(\n current: StoredDocumentRecord | null,\n expected: ExpectedDocumentSyncState | undefined,\n): { pullContinuationSuperseded: boolean; securityContextMatches: boolean } {\n if (!expected) {\n return { pullContinuationSuperseded: false, securityContextMatches: true };\n }\n const securityContextMatches = documentSyncSecurityContextMatches(\n current,\n expected.record,\n );\n const contentFrontiersMatch =\n sameNullableDocumentValue(\n current?.lastCommitLsn,\n expected.record.lastCommitLsn,\n ) &&\n current?.snapshotEndVersion === expected.record.snapshotEndVersion &&\n sameNullableDocumentValue(\n current?.pendingBaseVersion,\n expected.record.pendingBaseVersion,\n );\n const recoveryStateMatches =\n Boolean(current?.pullContinuationRecoveryRequired) ===\n Boolean(expected.record.pullContinuationRecoveryRequired) &&\n (current?.recoveryGeneration ?? 0) ===\n (expected.record.recoveryGeneration ?? 0);\n return {\n pullContinuationSuperseded:\n !securityContextMatches ||\n !contentFrontiersMatch ||\n !recoveryStateMatches ||\n !documentSyncPullContinuationsEqual(\n current?.pullContinuation,\n expected.pullContinuation,\n ),\n securityContextMatches,\n };\n}\n\nexport async function prepareDocumentMutation(\n input: PrepareDocumentMutationInput,\n execSql: ExecSql,\n patch: Partial<StoredDocumentRecord>,\n) {\n const durableCurrentRecord = await input.persistence.loadDocument(\n execSql,\n input.localId,\n );\n const creationSuperseded =\n input.currentRecord === null && durableCurrentRecord !== null;\n const mutationCurrentRecord = durableCurrentRecord ?? input.currentRecord;\n const identityWasReplaced = ordinarySaveIdentityWasReplaced(\n input,\n durableCurrentRecord,\n );\n const writeAccessWasRevoked = ordinarySaveWriteAccessWasRevoked(\n input,\n durableCurrentRecord,\n );\n const recoveryWasSuperseded = recoveryGenerationWasSuperseded(\n input,\n durableCurrentRecord,\n );\n const { pullContinuationSuperseded, securityContextMatches } =\n creationSuperseded || identityWasReplaced || writeAccessWasRevoked\n ? { pullContinuationSuperseded: true, securityContextMatches: false }\n : recoveryWasSuperseded\n ? { pullContinuationSuperseded: true, securityContextMatches: true }\n : resolveSyncSettlementState(\n mutationCurrentRecord,\n input.expectedSyncState,\n );\n const ordinarySaveNeedsRebase = ordinarySaveNeedsHistoryRebase(\n input,\n durableCurrentRecord,\n );\n\n if (ordinarySaveNeedsRebase && securityContextMatches) {\n await mergePersistedDocumentHistory({\n doc: input.currentDoc,\n execSql,\n localId: input.localId,\n persistence: input.persistence,\n });\n }\n const mutationPatch = pullContinuationSuperseded\n ? {}\n : ordinarySaveNeedsRebase && durableCurrentRecord\n ? mergeMutationFrontiers(patch, durableCurrentRecord)\n : patch;\n const authoritativeContainer = patchSpecifiesContainer(mutationPatch)\n ? undefined\n : await input.persistence.loadDocumentContainer(execSql, input.localId);\n return {\n creationSuperseded,\n mutationCurrentRecord,\n pullContinuationSuperseded,\n resolvedPatch:\n authoritativeContainer === undefined\n ? mutationPatch\n : { ...mutationPatch, containerId: authoritativeContainer.containerId },\n securityContextMatches,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"documentMutationPreparation.js","sourceRoot":"","sources":["documentMutationPreparation.ts"],"names":[],"mappings":"AAAA,OAAO,EA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CAAC,KAAK,EAAE,oBAAoB,CAAC;YACrD,CAAC,CAAC,KAAK,CAAC;IACZ,MAAM,sBAAsB,GAAG,uBAAuB,CAAC,aAAa,CAAC;QACnE,CAAC,CAAC,SAAS;QACX,CAAC,CAAC,MAAM,KAAK,CAAC,WAAW,CAAC,qBAAqB,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;IAC1E,OAAO;QACL,kBAAkB;QAClB,qBAAqB;QACrB,0BAA0B;QAC1B,aAAa,EACX,sBAAsB,KAAK,SAAS;YAClC,CAAC,CAAC,aAAa;YACf,CAAC,CAAC,EAAE,GAAG,aAAa,EAAE,WAAW,EAAE,sBAAsB,CAAC,WAAW,EAAE;QAC3E,sBAAsB;KACvB,CAAC;AACJ,CAAC","sourcesContent":["import { mergeVersionVectors, satisfiesVersionVector } from \"@tearleads/loro\";\nimport {\n type DocumentSyncPullContinuation,\n documentSyncPullContinuationsEqual,\n} from \"../../data/documents/shared/syncPagination\";\nimport { canWriteEffectiveAccessLevel } from \"../../data/keying/accessLevel\";\nimport type {\n DocumentsPersistence,\n StoredDocumentRecord,\n} from \"../../data/persistence/documents/documentsPersistence\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { mergePersistedDocumentHistory } from \"./historyContent\";\n\nexport interface ExpectedDocumentSyncState {\n pullContinuation: DocumentSyncPullContinuation | null;\n record: StoredDocumentRecord;\n}\n\nexport interface PrepareDocumentMutationInput {\n currentDoc: Parameters<typeof mergePersistedDocumentHistory>[0][\"doc\"];\n currentRecord: StoredDocumentRecord | null;\n expectedSyncState?: ExpectedDocumentSyncState | undefined;\n historyCheckpoint?:\n | {\n coveredTailIds: readonly string[];\n endVersionVector: string;\n pruneCoveredLocalState: boolean;\n snapshot: string;\n }\n | undefined;\n historyUpdateOrigin?: \"local\" | \"remote\" | undefined;\n historyUpdates?: readonly string[] | undefined;\n localId: string;\n persistence: DocumentsPersistence;\n}\n\nfunction sameNullableDocumentValue(\n left: string | null | undefined,\n right: string | null | undefined,\n): boolean {\n return (left ?? null) === (right ?? null);\n}\n\nexport function documentSyncSecurityContextMatches(\n current: StoredDocumentRecord | null,\n expected: StoredDocumentRecord,\n): boolean {\n return (\n current !== null &&\n current.id === expected.id &&\n current.documentId === expected.documentId &&\n current.containerId === expected.containerId &&\n current.accessEpoch === expected.accessEpoch &&\n sameNullableDocumentValue(\n current.accessStateHash,\n expected.accessStateHash,\n ) &&\n (current.effectiveAccessLevel ?? null) ===\n (expected.effectiveAccessLevel ?? null) &&\n sameNullableDocumentValue(\n current.contentKeyBundle,\n expected.contentKeyBundle,\n ) &&\n sameNullableDocumentValue(\n current.documentKekTargets,\n expected.documentKekTargets,\n ) &&\n sameNullableDocumentValue(\n current.documentManifestBundle,\n expected.documentManifestBundle,\n )\n );\n}\n\nfunction patchSpecifiesContainer(\n patch: Partial<StoredDocumentRecord>,\n): boolean {\n return Object.hasOwn(patch, \"containerId\");\n}\n\nfunction documentSyncStateDiffers(\n current: StoredDocumentRecord,\n cached: StoredDocumentRecord,\n): boolean {\n return (\n !sameNullableDocumentValue(current.lastCommitLsn, cached.lastCommitLsn) ||\n current.snapshotEndVersion !== cached.snapshotEndVersion ||\n !sameNullableDocumentValue(\n current.pendingBaseVersion,\n cached.pendingBaseVersion,\n ) ||\n !documentSyncPullContinuationsEqual(\n current.pullContinuation,\n cached.pullContinuation,\n ) ||\n Boolean(current.pullContinuationRecoveryRequired) !==\n Boolean(cached.pullContinuationRecoveryRequired)\n );\n}\n\nfunction mergeMutationFrontiers(\n patch: Partial<StoredDocumentRecord>,\n durableRecord: StoredDocumentRecord,\n): Partial<StoredDocumentRecord> {\n const nextPatch = { ...patch };\n if (patch.snapshotEndVersion !== undefined) {\n nextPatch.snapshotEndVersion = mergeVersionVectors([\n durableRecord.snapshotEndVersion,\n patch.snapshotEndVersion,\n ]);\n }\n if (\n patch.pendingBaseVersion !== undefined &&\n patch.pendingBaseVersion !== null &&\n durableRecord.pendingBaseVersion\n ) {\n nextPatch.pendingBaseVersion = mergeVersionVectors([\n durableRecord.pendingBaseVersion,\n patch.pendingBaseVersion,\n ]);\n }\n return nextPatch;\n}\n\nfunction ordinarySaveNeedsHistoryRebase(\n input: PrepareDocumentMutationInput,\n durableRecord: StoredDocumentRecord | null,\n): boolean {\n if (\n input.expectedSyncState !== undefined ||\n durableRecord === null ||\n input.currentRecord === null\n ) {\n return false;\n }\n const cachedPendingBase = input.currentRecord.pendingBaseVersion;\n const durableCoversCachedPendingBase =\n !cachedPendingBase ||\n (durableRecord.pendingBaseVersion !== null &&\n durableRecord.pendingBaseVersion !== undefined &&\n satisfiesVersionVector(\n durableRecord.pendingBaseVersion,\n cachedPendingBase,\n ));\n return (\n durableRecord.id === input.currentRecord.id &&\n durableRecord.documentId === input.currentRecord.documentId &&\n satisfiesVersionVector(\n durableRecord.snapshotEndVersion,\n input.currentRecord.snapshotEndVersion,\n ) &&\n durableCoversCachedPendingBase &&\n documentSyncStateDiffers(durableRecord, input.currentRecord)\n );\n}\n\nfunction ordinarySaveIdentityWasReplaced(\n input: PrepareDocumentMutationInput,\n durableRecord: StoredDocumentRecord | null,\n): boolean {\n return (\n input.expectedSyncState === undefined &&\n input.currentRecord !== null &&\n durableRecord !== null &&\n (durableRecord.id !== input.currentRecord.id ||\n durableRecord.documentId !== input.currentRecord.documentId)\n );\n}\n\nfunction ordinarySaveWriteAccessWasRevoked(\n input: PrepareDocumentMutationInput,\n durableRecord: StoredDocumentRecord | null,\n): boolean {\n return (\n input.expectedSyncState === undefined &&\n input.currentRecord !== null &&\n durableRecord !== null &&\n canWriteEffectiveAccessLevel(input.currentRecord.effectiveAccessLevel) &&\n !canWriteEffectiveAccessLevel(durableRecord.effectiveAccessLevel)\n );\n}\n\nfunction recoveryGenerationWasSuperseded(\n input: PrepareDocumentMutationInput,\n durableRecord: StoredDocumentRecord | null,\n): boolean {\n return (\n input.currentRecord !== null &&\n durableRecord !== null &&\n (input.currentRecord.recoveryGeneration ?? 0) !==\n (durableRecord.recoveryGeneration ?? 0)\n );\n}\n\nfunction resolveSyncSettlementState(\n current: StoredDocumentRecord | null,\n expected: ExpectedDocumentSyncState | undefined,\n): { pullContinuationSuperseded: boolean; securityContextMatches: boolean } {\n if (!expected) {\n return { pullContinuationSuperseded: false, securityContextMatches: true };\n }\n const securityContextMatches = documentSyncSecurityContextMatches(\n current,\n expected.record,\n );\n const contentFrontiersMatch =\n sameNullableDocumentValue(\n current?.lastCommitLsn,\n expected.record.lastCommitLsn,\n ) &&\n current?.snapshotEndVersion === expected.record.snapshotEndVersion &&\n sameNullableDocumentValue(\n current?.pendingBaseVersion,\n expected.record.pendingBaseVersion,\n );\n const recoveryStateMatches =\n Boolean(current?.pullContinuationRecoveryRequired) ===\n Boolean(expected.record.pullContinuationRecoveryRequired) &&\n (current?.recoveryGeneration ?? 0) ===\n (expected.record.recoveryGeneration ?? 0);\n return {\n pullContinuationSuperseded:\n !securityContextMatches ||\n !contentFrontiersMatch ||\n !recoveryStateMatches ||\n !documentSyncPullContinuationsEqual(\n current?.pullContinuation,\n expected.pullContinuation,\n ),\n securityContextMatches,\n };\n}\n\nexport async function prepareDocumentMutation(\n input: PrepareDocumentMutationInput,\n execSql: ExecSql,\n patch: Partial<StoredDocumentRecord>,\n) {\n const durableCurrentRecord = await input.persistence.loadDocument(\n execSql,\n input.localId,\n );\n const creationSuperseded =\n input.currentRecord === null && durableCurrentRecord !== null;\n const mutationCurrentRecord = durableCurrentRecord ?? input.currentRecord;\n const identityWasReplaced = ordinarySaveIdentityWasReplaced(\n input,\n durableCurrentRecord,\n );\n const writeAccessWasRevoked = ordinarySaveWriteAccessWasRevoked(\n input,\n durableCurrentRecord,\n );\n const recoveryWasSuperseded = recoveryGenerationWasSuperseded(\n input,\n durableCurrentRecord,\n );\n const { pullContinuationSuperseded, securityContextMatches } =\n creationSuperseded || identityWasReplaced || writeAccessWasRevoked\n ? { pullContinuationSuperseded: true, securityContextMatches: false }\n : recoveryWasSuperseded\n ? { pullContinuationSuperseded: true, securityContextMatches: true }\n : resolveSyncSettlementState(\n mutationCurrentRecord,\n input.expectedSyncState,\n );\n const ordinarySaveNeedsRebase = ordinarySaveNeedsHistoryRebase(\n input,\n durableCurrentRecord,\n );\n\n if (ordinarySaveNeedsRebase && securityContextMatches) {\n await mergePersistedDocumentHistory({\n doc: input.currentDoc,\n execSql,\n localId: input.localId,\n persistence: input.persistence,\n });\n }\n const mutationPatch = pullContinuationSuperseded\n ? {}\n : ordinarySaveNeedsRebase && durableCurrentRecord\n ? mergeMutationFrontiers(patch, durableCurrentRecord)\n : patch;\n const authoritativeContainer = patchSpecifiesContainer(mutationPatch)\n ? undefined\n : await input.persistence.loadDocumentContainer(execSql, input.localId);\n return {\n creationSuperseded,\n mutationCurrentRecord,\n pullContinuationSuperseded,\n resolvedPatch:\n authoritativeContainer === undefined\n ? mutationPatch\n : { ...mutationPatch, containerId: authoritativeContainer.containerId },\n securityContextMatches,\n };\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { base64ToBytes } from "../../internal/encoding/index.js";
|
|
2
2
|
import { createDocument, getImportBlobMetadata, importSnapshot, importUpdates, } from "../../internal/loro/index.js";
|
|
3
|
-
import { getScopedPeerSeed } from "../../data/crdtPeerSeed.js";
|
|
4
3
|
import { DOCUMENTS_APP_KIND, } from "../../data/persistence/documents/documentsPersistence.js";
|
|
4
|
+
import { getScopedPeerSeed } from "../../data/sync/crdtPeerSeed.js";
|
|
5
5
|
/**
|
|
6
6
|
* Import durable-history tail rows into a document. Rotation baselines travel
|
|
7
7
|
* through the tail as snapshot-mode blobs, which importUpdates would silently
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"historyContent.js","sourceRoot":"","sources":["historyContent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,cAAc,EACd,qBAAqB,EACrB,cAAc,EACd,aAAa,GACd,MAAM,iBAAiB,CAAC;AAC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C,QAAQ,CAAC,CAAC,CAAC;IAC7D,CAAC;IACD,gCAAgC,CAC9B,KAAK,CAAC,GAAG,EACT,OAAO,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,CACvD,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,4BAA4B,CAAC,KAIlD;IACC,MAAM,OAAO,GAAG,MAAM,KAAK,CAAC,WAAW,CAAC,uBAAuB,CAC7D,KAAK,CAAC,OAAO,EACb,KAAK,CAAC,OAAO,CACd,CAAC;IACF,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,GAAG,GAAG,MAAM,cAAc,CAAC,MAAM,iBAAiB,CAAC,kBAAkB,CAAC,CAAC,CAAC;IAC9E,sEAAsE;IACtE,yDAAyD;IACzD,IAAI,OAAO,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAChC,cAAc,CAAC,GAAG,EAAE,aAAa,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC;IACvD,CAAC;IACD,gCAAgC,CAC9B,GAAG,EACH,OAAO,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,CACvD,CAAC;IACF,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import { base64ToBytes } from \"@tearleads/encoding\";\nimport {\n createDocument,\n getImportBlobMetadata,\n importSnapshot,\n importUpdates,\n} from \"@tearleads/loro\";\nimport {\n DOCUMENTS_APP_KIND,\n type DocumentsPersistence,\n} from \"../../data/persistence/documents/documentsPersistence\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { getScopedPeerSeed } from \"../../data/sync/crdtPeerSeed\";\n\n/**\n * Import durable-history tail rows into a document. Rotation baselines travel\n * through the tail as snapshot-mode blobs, which importUpdates would silently\n * ignore — import them individually.\n */\nexport function importDocumentHistoryTailUpdates(\n doc: Parameters<typeof importSnapshot>[0],\n tailUpdates: readonly string[],\n): void {\n const ordinaryUpdates: Uint8Array[] = [];\n for (const encoded of tailUpdates) {\n const bytes = base64ToBytes(encoded);\n if (getImportBlobMetadata(bytes).mode === \"snapshot\") {\n importSnapshot(doc, bytes);\n } else {\n ordinaryUpdates.push(bytes);\n }\n }\n if (ordinaryUpdates.length > 0) {\n importUpdates(doc, ordinaryUpdates);\n }\n}\n\n/** Merge the latest durable checkpoint and tail into an already-live pane. */\nexport async function mergePersistedDocumentHistory(input: {\n doc: Parameters<typeof importSnapshot>[0];\n execSql: ExecSql;\n localId: string;\n persistence: DocumentsPersistence;\n}): Promise<void> {\n const history = await input.persistence.loadHistoryRestoreState(\n input.execSql,\n input.localId,\n );\n if (!history) return;\n if (history.snapshot.length > 0) {\n importSnapshot(input.doc, base64ToBytes(history.snapshot));\n }\n importDocumentHistoryTailUpdates(\n input.doc,\n history.tailUpdates.map((update) => update.updateData),\n );\n}\n\n/**\n * Load a persisted document's content into a fresh detached document from the\n * durable full-history state (checkpoint + tail) — the only persisted content\n * source. Returns null when the document has no checkpoint yet (a discovered\n * shell that has not hydrated). For store-less readers (diagnostics, profile\n * lookups); the document store restores through its own initialization path.\n */\nexport async function loadPersistedDocumentContent(input: {\n execSql: ExecSql;\n localId: string;\n persistence: DocumentsPersistence;\n}): Promise<Awaited<ReturnType<typeof createDocument>> | null> {\n const history = await input.persistence.loadHistoryRestoreState(\n input.execSql,\n input.localId,\n );\n if (!history) {\n return null;\n }\n\n const doc = await createDocument(await getScopedPeerSeed(DOCUMENTS_APP_KIND));\n // A tail-only state (crash before the birth checkpoint landed) has an\n // empty snapshot; the tail rows alone carry the content.\n if (history.snapshot.length > 0) {\n importSnapshot(doc, base64ToBytes(history.snapshot));\n }\n importDocumentHistoryTailUpdates(\n doc,\n history.tailUpdates.map((update) => update.updateData),\n );\n return doc;\n}\n"]}
|
|
@@ -7,7 +7,7 @@ import { buildDocumentLinkSetEventPlan } from "../../data/documents/shared/event
|
|
|
7
7
|
import { assertDocumentWriterProjectionConsistent, collectContainerKeksForDocumentSync, containerPathRefs, currentDocumentTargets, deriveDocumentTargetFromProjection, mergeTargetEnvelopes, readLinkedContainerIdsFromDocumentManifest, unwrapContainerKekPath, unwrapDocumentContentKeyFromWriterProjection, verifiedDocumentWrapTargets, } from "../../data/documents/shared/projection.js";
|
|
8
8
|
import { assertDocumentManifestBundleConsistent, describeDocumentTargetKek, sortDocumentTargets, targetKey, uniqueSortedStrings, } from "../../data/documents/shared/readers.js";
|
|
9
9
|
import { projectionVerificationOptions, } from "../../data/documents/shared/types.js";
|
|
10
|
-
import { readCanonicalRecord } from "../../data/
|
|
10
|
+
import { readCanonicalRecord } from "../../data/keying/canonicalJson.js";
|
|
11
11
|
import { assertDocumentLinkAuthorAccess, verifyDocumentLinkSetCurrentPolicies, } from "./linkSetAuthority.js";
|
|
12
12
|
import { assertSubtreePurgePath, } from "./subtreePurgeScope.js";
|
|
13
13
|
function deriveDocumentLinkSetTargetState(input) {
|