@tearleads/client-sdk 0.1.57 → 0.1.59
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Tearleads.d.ts +2 -2
- package/Tearleads.js +1 -1
- package/Tearleads.js.map +1 -1
- package/client/blobs.d.ts +1 -1
- package/client/blobs.js.map +1 -1
- package/client/deviceFirst.js.map +1 -1
- package/client/identity.js +1 -1
- package/client/identity.js.map +1 -1
- package/client/index.d.ts +1 -1
- package/client/index.js +1 -1
- package/client/index.js.map +1 -1
- package/client/organizations/organizationAccessRestoration.js.map +1 -1
- package/client/organizations/organizationDataUsage.js.map +1 -1
- package/client/organizations/organizationGroupNameHydration.js.map +1 -1
- package/client/organizations/organizationMetadataProfileSync.js +1 -1
- package/client/organizations/organizationMetadataProfileSync.js.map +1 -1
- package/client/organizations/organizationReadModels.js.map +1 -1
- package/client/organizations/organizationWorkflowRuntime.js.map +1 -1
- package/client/rootContainerAdoption.js.map +1 -1
- package/client/securityIncidents.d.ts +1 -1
- package/client/securityIncidents.js.map +1 -1
- package/client/session/sessionLoginRefusal.js.map +1 -1
- package/client/session/sessionRootAuthority.js.map +1 -1
- package/client/session/sessionTypes.d.ts +1 -1
- package/client/session/sessionTypes.js.map +1 -1
- package/client/userIdentities.d.ts +1 -1
- package/client/userIdentities.js.map +1 -1
- package/client/workflowRuntime.d.ts +2 -2
- package/client/workflowRuntime.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/index.d.ts +4 -4
- package/index.js +2 -2
- package/index.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/currentOrganizationMutationRetention.js +1 -1
- package/workflows/organizations/currentOrganizationMutationRetention.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/index.d.ts +0 -1
- package/workflows/organizations/index.js +0 -1
- package/workflows/organizations/index.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/retainAcknowledgedPrincipalCurrents.d.ts +4 -24
- package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js +13 -133
- package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js.map +1 -1
- package/workflows/organizations/rosterProfileContainer.js +1 -1
- package/workflows/organizations/rosterProfileContainer.js.map +1 -1
- package/workflows/organizations/runtimeCurrentGroupMutation.js +1 -1
- package/workflows/organizations/runtimeCurrentGroupMutation.js.map +1 -1
- package/workflows/principals/acknowledgedPrincipalCurrents.d.ts +33 -0
- package/workflows/principals/acknowledgedPrincipalCurrents.js +140 -0
- package/workflows/principals/acknowledgedPrincipalCurrents.js.map +1 -0
- package/workflows/{organizations → principals}/acknowledgedPrincipalPredecessor.d.ts +1 -1
- package/workflows/{organizations → principals}/acknowledgedPrincipalPredecessor.js +1 -1
- package/workflows/principals/acknowledgedPrincipalPredecessor.js.map +1 -0
- package/workflows/principals/index.d.ts +1 -0
- package/workflows/principals/index.js +1 -0
- package/workflows/principals/index.js.map +1 -1
- package/workflows/{organizations → principals}/initialPrincipalCurrentPublication.js +5 -7
- package/workflows/principals/initialPrincipalCurrentPublication.js.map +1 -0
- 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/principalAcknowledgementChecks.d.ts +30 -0
- package/workflows/principals/principalAcknowledgementChecks.js +2 -0
- package/workflows/principals/principalAcknowledgementChecks.js.map +1 -0
- package/workflows/{organizations → principals}/principalCurrentPublicationSeal.js.map +1 -1
- package/workflows/{organizations → principals}/reconcileAcknowledgedPrincipalCurrent.js +2 -2
- package/workflows/principals/reconcileAcknowledgedPrincipalCurrent.js.map +1 -0
- 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/data/keyingCanonicalJson.js.map +0 -1
- package/data/keyingProjectionVerification.d.ts +0 -9
- package/data/keyingProjectionVerification.js.map +0 -1
- package/workflows/organizations/acknowledgedPrincipalPredecessor.js.map +0 -1
- package/workflows/organizations/initialPrincipalCurrentPublication.js.map +0 -1
- package/workflows/organizations/reconcileAcknowledgedPrincipalCurrent.js.map +0 -1
- /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
- /package/workflows/{organizations → principals}/principalCurrentPublicationSeal.js +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalPolicyVerification.js","sourceRoot":"","sources":["principalPolicyVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAGvB,aAAa,EAEb,2BAA2B,GAC5B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,6BAA6B,EAAE,MAAM,4CAA4C,CAAC;AAC3F,OAAO,EACL,kCAAkC,EAClC,sCAAsC,GACvC,MAAM,mDAAmD,CAAC;AAC3D,OAAO,EAAE,yBAAyB,EAAE,MAAM,2CAA2C,CAAC;AACtF,OAAO,EAAE,qCAAqC,EAAE,MAAM,oDAAoD,CAAC;AAC3G,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EACL,oCAAoC,EACpC,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,+CAA+C,CAAC;AACvD,OAAO,EACL,kCAAkC,EAClC,kC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AC,CACH,CACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicySignerPublicKey,\n type ReferencedPrincipalHead,\n toFingerprint,\n type VerifiedPrincipalPolicy,\n verifyPrincipalPolicyBundle,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { loadPrincipalPolicyCheckpoint } from \"../persistence/keyingCheckpointPersistence\";\nimport {\n principalPolicyHeadMeetsCheckpoint,\n verifiedPrincipalPolicyMeetsCheckpoint,\n} from \"../persistence/principalPolicyCheckpointSelection\";\nimport { loadPrincipalPolicyBundle } from \"../persistence/principalPolicyPersistence\";\nimport { loadPrincipalPolicyBundleForReference } from \"../persistence/principalPolicyReferencePersistence\";\nimport { principalPolicyBundleStates } from \"../principalPolicyStates\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../principals/organizationAuthorityDescriptor\";\nimport {\n organizationAdminExternalAuthority,\n principalPolicyReferenceFromBundle,\n verifyOrganizationAdminPolicy,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../principals/principalPolicyAdminSigners\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../principals/principalPolicyEvidence\";\nimport {\n observePrincipalPolicy,\n type ProjectionCheckpointContext,\n} from \"./checkpointContext\";\nimport { ProjectionDependencyUnavailableError } from \"./dependencyUnavailable\";\nimport { rethrowProjectionVerificationBoundaryError } from \"./error\";\nimport {\n filterUncachedPrincipalPolicyReferences,\n referencedPrincipalPolicyKey,\n verifiedPrincipalPolicyContainsReference,\n} from \"./principalPolicyCache\";\nimport { resolveReferencedPrincipalPolicy } from \"./resolvedPrincipalPolicy\";\nimport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"./types\";\nimport {\n assertProjectionVerificationCurrent,\n generationGuardedPrincipalPolicyWarmer,\n} from \"./types\";\n\nfunction principalPolicyReferenceLabel(\n reference: ReferencedPrincipalHead,\n): string {\n return `${reference.principalType}:${reference.principalId}@${reference.version}`;\n}\n\n/**\n * A referenced principal policy is not in the local store and warming could\n * not fetch it this pass — a transient cold-cache condition, typical for a\n * member whose access arrives via a group policy the device has not hydrated\n * yet. Sync passes discriminate on this type to defer the affected container\n * and retry on a later trigger, rather than failing the whole pass.\n */\nexport class PrincipalPolicyNotCachedError extends Error {\n constructor(referenceLabel: string) {\n super(`Principal policy ${referenceLabel} is not cached`);\n this.name = \"PrincipalPolicyNotCachedError\";\n }\n}\n\nexport function isPrincipalPolicyNotCachedError(error: unknown): boolean {\n return (\n error instanceof PrincipalPolicyNotCachedError ||\n (error instanceof Error && error.name === \"PrincipalPolicyNotCachedError\")\n );\n}\n\nasync function collectPrincipalPolicySignerPublicKeys(input: {\n bundle: PrincipalPolicyBundleResponse;\n label: string;\n resolveUserKey: ProjectionUserKeyResolver;\n}): Promise<PrincipalPolicySignerPublicKey[]> {\n const signerPublicKeysByKey = new Map<\n string,\n PrincipalPolicySignerPublicKey\n >();\n\n for (const state of principalPolicyBundleStates(input.bundle)) {\n const cacheKey = `${state.signerUserId}:${state.signerUserKeyFingerprint}`;\n if (signerPublicKeysByKey.has(cacheKey)) {\n continue;\n }\n\n const signerKey = await input.resolveUserKey(state.signerUserId);\n if (!signerKey) {\n throw new ProjectionDependencyUnavailableError(\n `${input.label} signer key could not be resolved for ${state.signerUserId}`,\n );\n }\n\n const signingKeyFingerprint = await toFingerprint(\n signerKey.signingPublicKey,\n );\n if (signingKeyFingerprint !== state.signerUserKeyFingerprint) {\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n `${input.label} signer key fingerprint mismatch`,\n );\n }\n\n signerPublicKeysByKey.set(cacheKey, {\n userId: state.signerUserId,\n signingKeyFingerprint,\n signingPublicKey: signerKey.signingPublicKey,\n });\n }\n\n return [...signerPublicKeysByKey.values()];\n}\n\ntype OrganizationAdminPolicyInput = {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n resolveUserKey: ProjectionUserKeyResolver;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n};\n\nasync function loadOrganizationPolicyForVerification(\n input: OrganizationAdminPolicyInput,\n): Promise<\n | {\n bundle: PrincipalPolicyBundleResponse;\n localCheckpoint: Awaited<\n ReturnType<typeof loadPrincipalPolicyCheckpoint>\n >;\n }\n | undefined\n> {\n const execSql = input.checkpointContext.execSql;\n let bundle = await loadPrincipalPolicyBundle(\n execSql,\n \"organization\",\n input.organizationId,\n );\n if (!bundle) {\n return undefined;\n }\n let localCheckpoint = await loadPrincipalPolicyCheckpoint(\n execSql,\n \"organization\",\n input.organizationId,\n );\n if (\n !principalPolicyHeadMeetsCheckpoint(bundle.currentState, localCheckpoint) &&\n input.warmReferencedPrincipalPolicies\n ) {\n await input.warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: [principalPolicyReferenceFromBundle(bundle)],\n });\n bundle = await loadPrincipalPolicyBundle(\n execSql,\n \"organization\",\n input.organizationId,\n );\n localCheckpoint = await loadPrincipalPolicyCheckpoint(\n execSql,\n \"organization\",\n input.organizationId,\n );\n if (!bundle) {\n return undefined;\n }\n }\n\n return { bundle, localCheckpoint };\n}\n\nfunction assertReservedAdminsPolicyShape(\n policy: VerifiedPrincipalPolicy,\n): void {\n const history = policy.history ?? [{ projection: policy.projection }];\n if (\n history.some(\n (entry) =>\n entry.projection.length === 0 ||\n entry.projection.some((member) => member.role !== \"admin\"),\n )\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"reserved Admins policy must contain only direct admin users\",\n );\n }\n}\n\nasync function verifyOrganizationAdminsPolicy(input: {\n adminGroupId: string;\n execSql: ProjectionCheckpointContext[\"execSql\"];\n expectedHead: ReferencedPrincipalHead;\n resolveUserKey: ProjectionUserKeyResolver;\n}): Promise<VerifiedPrincipalPolicy | undefined> {\n const adminBundle = await loadPrincipalPolicyBundle(\n input.execSql,\n \"group\",\n input.adminGroupId,\n );\n if (!adminBundle) {\n return undefined;\n }\n if (\n !principalHeadMatchesReference(\n principalPolicyReferenceFromBundle(adminBundle),\n input.expectedHead,\n )\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"Admins policy does not match the signed organization directory\",\n );\n }\n const adminCheckpoint = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n \"group\",\n input.adminGroupId,\n );\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: adminBundle,\n label: `Admins policy ${input.adminGroupId}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified = await verifyPrincipalPolicyBundle({\n bundle: adminBundle,\n expectedReference: input.expectedHead,\n localCheckpoint: adminCheckpoint,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n assertReservedAdminsPolicyShape(verified.value);\n return verified.value;\n}\n\nasync function loadOrganizationExternalAuthority(\n input: OrganizationAdminPolicyInput,\n): Promise<ReturnType<typeof organizationAdminExternalAuthority> | null> {\n const organizationPolicy = await loadOrganizationPolicyForVerification(input);\n if (!organizationPolicy) {\n return null;\n }\n\n try {\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: organizationPolicy.bundle,\n label: `Organization policy ${input.organizationId}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified = await verifyOrganizationAdminPolicy({\n bundle: organizationPolicy.bundle,\n localCheckpoint: organizationPolicy.localCheckpoint,\n organizationId: input.organizationId,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n const descriptor = parseOrganizationAuthorityDescriptor(\n organizationPolicy.bundle.currentPayload.ciphertext,\n );\n if (descriptor.organizationId !== input.organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"organization authority descriptor scope does not match\",\n );\n }\n const verifiedAdmins = await verifyOrganizationAdminsPolicy({\n adminGroupId: descriptor.adminGroupId,\n execSql: input.checkpointContext.execSql,\n expectedHead: requireOrganizationGroupHead(\n descriptor,\n descriptor.adminGroupId,\n ),\n resolveUserKey: input.resolveUserKey,\n });\n if (!verifiedAdmins) {\n return null;\n }\n observePrincipalPolicy(\n input.checkpointContext,\n verified.value,\n input.organizationId,\n );\n observePrincipalPolicy(\n input.checkpointContext,\n verifiedAdmins,\n input.organizationId,\n );\n return organizationAdminExternalAuthority(verifiedAdmins);\n } catch (error) {\n rethrowProjectionVerificationBoundaryError(error);\n if (error instanceof KeyingVerificationError) {\n throw error;\n }\n return null;\n }\n}\n\nasync function verifyReferencedPrincipalPolicy(input: {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n principalPolicyCache: PrincipalPolicyCache;\n reference: ReferencedPrincipalHead;\n stillCurrent?: (() => boolean) | undefined;\n resolveUserKey: ProjectionUserKeyResolver;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence> {\n // Scoped recovery carries organization, dependency and lifetime bindings.\n // A bare policy cache entry cannot replace those bindings.\n const recovered = await resolveReferencedPrincipalPolicy(input);\n if (recovered) return recovered;\n const cacheKey = referencedPrincipalPolicyKey(input.reference);\n const cachedPolicy = input.principalPolicyCache.get(cacheKey);\n const execSql = input.checkpointContext.execSql;\n const localCheckpoint = await loadPrincipalPolicyCheckpoint(\n execSql,\n input.reference.principalType,\n input.reference.principalId,\n );\n if (cachedPolicy && !(\"retainedHistory\" in cachedPolicy)) {\n if (\n !verifiedPrincipalPolicyContainsReference(cachedPolicy, input.reference)\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"in-memory principal policy cache does not match its exact reference\",\n );\n }\n if (verifiedPrincipalPolicyMeetsCheckpoint(cachedPolicy, localCheckpoint)) {\n observePrincipalPolicy(\n input.checkpointContext,\n cachedPolicy,\n input.organizationId,\n );\n return cachedPolicy;\n }\n }\n\n const referenceLabel = principalPolicyReferenceLabel(input.reference);\n let bundle = await loadPrincipalPolicyBundleForReference(\n execSql,\n input.reference,\n localCheckpoint,\n );\n if (!bundle && input.warmReferencedPrincipalPolicies) {\n // The reference is not cached locally — the common case for a member who\n // gained access via another org's group grant and never hydrated that\n // group's policy. Fetch+verify+persist it, then re-read from the cache.\n await input.warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: [input.reference],\n });\n bundle = await loadPrincipalPolicyBundleForReference(\n execSql,\n input.reference,\n localCheckpoint,\n );\n }\n if (!bundle) {\n throw new PrincipalPolicyNotCachedError(referenceLabel);\n }\n\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n label: `Principal policy ${referenceLabel}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle,\n expectedReference: input.reference,\n loadExternalAuthority: () =>\n loadOrganizationExternalAuthority({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies:\n input.warmReferencedPrincipalPolicies,\n }),\n localCheckpoint,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n\n observePrincipalPolicy(\n input.checkpointContext,\n verified.value,\n input.organizationId,\n );\n input.principalPolicyCache.set(cacheKey, verified.value);\n return verified.value;\n}\n\nexport async function collectReferencedPrincipalPolicies(input: {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n principalPolicyCache: PrincipalPolicyCache;\n references: readonly ReferencedPrincipalHead[];\n resolveUserKey: ProjectionUserKeyResolver;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence[]> {\n const warmReferencedPrincipalPolicies =\n generationGuardedPrincipalPolicyWarmer(\n input.warmReferencedPrincipalPolicies,\n input.stillCurrent,\n );\n const uniqueReferences = new Map<string, ReferencedPrincipalHead>();\n for (const reference of input.references) {\n uniqueReferences.set(referencedPrincipalPolicyKey(reference), reference);\n }\n\n const references = [...uniqueReferences.values()];\n // Warm every missing reference in one batched fetch before verifying, so a\n // path that references several uncached policies makes a single round of\n // requests rather than one per reference.\n if (\n warmReferencedPrincipalPolicies &&\n !warmReferencedPrincipalPolicies.resolveReference\n ) {\n const uncached = await filterUncachedPrincipalPolicyReferences({\n execSql: input.checkpointContext.execSql,\n principalPolicyCache: input.principalPolicyCache,\n references,\n });\n if (uncached.length > 0) {\n assertProjectionVerificationCurrent(input.stillCurrent);\n await warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: uncached,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n }\n }\n\n // The warmer's operation shares one recovery view across its collections.\n return Promise.all(\n references.map((reference) =>\n verifyReferencedPrincipalPolicy({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n principalPolicyCache: input.principalPolicyCache,\n reference,\n stillCurrent: input.stillCurrent,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies,\n }),\n ),\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"principalPolicyVerification.js","sourceRoot":"","sources":["principalPolicyVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAGvB,aAAa,EAEb,2BAA2B,GAC5B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,6BAA6B,EAAE,MAAM,4CAA4C,CAAC;AAC3F,OAAO,EACL,kCAAkC,EAClC,sCAAsC,GACvC,MAAM,mDAAmD,CAAC;AAC3D,OAAO,EAAE,yBAAyB,EAAE,MAAM,2CAA2C,CAAC;AACtF,OAAO,EAAE,qCAAqC,EAAE,MAAM,oDAAoD,CAAC;AAC3G,OAAO,EACL,oCAAoC,EACpC,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,+CAA+C,CAAC;AACvD,OAAO,EACL,kCAAkC,EAClC,kCAAkC,EAClC,6BAA6B,EAC7B,yDAAyD,GAC1D,MAAM,2CAA2C,CAAC;AAEnD,OAAO,EAAE,2BAA2B,EAAE,MAAM,qCAAqC,CAAC;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ipalPolicySignerPublicKey,\n type ReferencedPrincipalHead,\n toFingerprint,\n type VerifiedPrincipalPolicy,\n verifyPrincipalPolicyBundle,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { loadPrincipalPolicyCheckpoint } from \"../persistence/keyingCheckpointPersistence\";\nimport {\n principalPolicyHeadMeetsCheckpoint,\n verifiedPrincipalPolicyMeetsCheckpoint,\n} from \"../persistence/principalPolicyCheckpointSelection\";\nimport { loadPrincipalPolicyBundle } from \"../persistence/principalPolicyPersistence\";\nimport { loadPrincipalPolicyBundleForReference } from \"../persistence/principalPolicyReferencePersistence\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../principals/organizationAuthorityDescriptor\";\nimport {\n organizationAdminExternalAuthority,\n principalPolicyReferenceFromBundle,\n verifyOrganizationAdminPolicy,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../principals/principalPolicyAdminSigners\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../principals/principalPolicyEvidence\";\nimport { principalPolicyBundleStates } from \"../principals/principalPolicyStates\";\nimport {\n observePrincipalPolicy,\n type ProjectionCheckpointContext,\n} from \"./checkpointContext\";\nimport { ProjectionDependencyUnavailableError } from \"./dependencyUnavailable\";\nimport { rethrowProjectionVerificationBoundaryError } from \"./error\";\nimport {\n filterUncachedPrincipalPolicyReferences,\n referencedPrincipalPolicyKey,\n verifiedPrincipalPolicyContainsReference,\n} from \"./principalPolicyCache\";\nimport { resolveReferencedPrincipalPolicy } from \"./resolvedPrincipalPolicy\";\nimport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"./types\";\nimport {\n assertProjectionVerificationCurrent,\n generationGuardedPrincipalPolicyWarmer,\n} from \"./types\";\n\nfunction principalPolicyReferenceLabel(\n reference: ReferencedPrincipalHead,\n): string {\n return `${reference.principalType}:${reference.principalId}@${reference.version}`;\n}\n\n/**\n * A referenced principal policy is not in the local store and warming could\n * not fetch it this pass — a transient cold-cache condition, typical for a\n * member whose access arrives via a group policy the device has not hydrated\n * yet. Sync passes discriminate on this type to defer the affected container\n * and retry on a later trigger, rather than failing the whole pass.\n */\nexport class PrincipalPolicyNotCachedError extends Error {\n constructor(referenceLabel: string) {\n super(`Principal policy ${referenceLabel} is not cached`);\n this.name = \"PrincipalPolicyNotCachedError\";\n }\n}\n\nexport function isPrincipalPolicyNotCachedError(error: unknown): boolean {\n return (\n error instanceof PrincipalPolicyNotCachedError ||\n (error instanceof Error && error.name === \"PrincipalPolicyNotCachedError\")\n );\n}\n\nasync function collectPrincipalPolicySignerPublicKeys(input: {\n bundle: PrincipalPolicyBundleResponse;\n label: string;\n resolveUserKey: ProjectionUserKeyResolver;\n}): Promise<PrincipalPolicySignerPublicKey[]> {\n const signerPublicKeysByKey = new Map<\n string,\n PrincipalPolicySignerPublicKey\n >();\n\n for (const state of principalPolicyBundleStates(input.bundle)) {\n const cacheKey = `${state.signerUserId}:${state.signerUserKeyFingerprint}`;\n if (signerPublicKeysByKey.has(cacheKey)) {\n continue;\n }\n\n const signerKey = await input.resolveUserKey(state.signerUserId);\n if (!signerKey) {\n throw new ProjectionDependencyUnavailableError(\n `${input.label} signer key could not be resolved for ${state.signerUserId}`,\n );\n }\n\n const signingKeyFingerprint = await toFingerprint(\n signerKey.signingPublicKey,\n );\n if (signingKeyFingerprint !== state.signerUserKeyFingerprint) {\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n `${input.label} signer key fingerprint mismatch`,\n );\n }\n\n signerPublicKeysByKey.set(cacheKey, {\n userId: state.signerUserId,\n signingKeyFingerprint,\n signingPublicKey: signerKey.signingPublicKey,\n });\n }\n\n return [...signerPublicKeysByKey.values()];\n}\n\ntype OrganizationAdminPolicyInput = {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n resolveUserKey: ProjectionUserKeyResolver;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n};\n\nasync function loadOrganizationPolicyForVerification(\n input: OrganizationAdminPolicyInput,\n): Promise<\n | {\n bundle: PrincipalPolicyBundleResponse;\n localCheckpoint: Awaited<\n ReturnType<typeof loadPrincipalPolicyCheckpoint>\n >;\n }\n | undefined\n> {\n const execSql = input.checkpointContext.execSql;\n let bundle = await loadPrincipalPolicyBundle(\n execSql,\n \"organization\",\n input.organizationId,\n );\n if (!bundle) {\n return undefined;\n }\n let localCheckpoint = await loadPrincipalPolicyCheckpoint(\n execSql,\n \"organization\",\n input.organizationId,\n );\n if (\n !principalPolicyHeadMeetsCheckpoint(bundle.currentState, localCheckpoint) &&\n input.warmReferencedPrincipalPolicies\n ) {\n await input.warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: [principalPolicyReferenceFromBundle(bundle)],\n });\n bundle = await loadPrincipalPolicyBundle(\n execSql,\n \"organization\",\n input.organizationId,\n );\n localCheckpoint = await loadPrincipalPolicyCheckpoint(\n execSql,\n \"organization\",\n input.organizationId,\n );\n if (!bundle) {\n return undefined;\n }\n }\n\n return { bundle, localCheckpoint };\n}\n\nfunction assertReservedAdminsPolicyShape(\n policy: VerifiedPrincipalPolicy,\n): void {\n const history = policy.history ?? [{ projection: policy.projection }];\n if (\n history.some(\n (entry) =>\n entry.projection.length === 0 ||\n entry.projection.some((member) => member.role !== \"admin\"),\n )\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"reserved Admins policy must contain only direct admin users\",\n );\n }\n}\n\nasync function verifyOrganizationAdminsPolicy(input: {\n adminGroupId: string;\n execSql: ProjectionCheckpointContext[\"execSql\"];\n expectedHead: ReferencedPrincipalHead;\n resolveUserKey: ProjectionUserKeyResolver;\n}): Promise<VerifiedPrincipalPolicy | undefined> {\n const adminBundle = await loadPrincipalPolicyBundle(\n input.execSql,\n \"group\",\n input.adminGroupId,\n );\n if (!adminBundle) {\n return undefined;\n }\n if (\n !principalHeadMatchesReference(\n principalPolicyReferenceFromBundle(adminBundle),\n input.expectedHead,\n )\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"Admins policy does not match the signed organization directory\",\n );\n }\n const adminCheckpoint = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n \"group\",\n input.adminGroupId,\n );\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: adminBundle,\n label: `Admins policy ${input.adminGroupId}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified = await verifyPrincipalPolicyBundle({\n bundle: adminBundle,\n expectedReference: input.expectedHead,\n localCheckpoint: adminCheckpoint,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n assertReservedAdminsPolicyShape(verified.value);\n return verified.value;\n}\n\nasync function loadOrganizationExternalAuthority(\n input: OrganizationAdminPolicyInput,\n): Promise<ReturnType<typeof organizationAdminExternalAuthority> | null> {\n const organizationPolicy = await loadOrganizationPolicyForVerification(input);\n if (!organizationPolicy) {\n return null;\n }\n\n try {\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: organizationPolicy.bundle,\n label: `Organization policy ${input.organizationId}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified = await verifyOrganizationAdminPolicy({\n bundle: organizationPolicy.bundle,\n localCheckpoint: organizationPolicy.localCheckpoint,\n organizationId: input.organizationId,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n const descriptor = parseOrganizationAuthorityDescriptor(\n organizationPolicy.bundle.currentPayload.ciphertext,\n );\n if (descriptor.organizationId !== input.organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"organization authority descriptor scope does not match\",\n );\n }\n const verifiedAdmins = await verifyOrganizationAdminsPolicy({\n adminGroupId: descriptor.adminGroupId,\n execSql: input.checkpointContext.execSql,\n expectedHead: requireOrganizationGroupHead(\n descriptor,\n descriptor.adminGroupId,\n ),\n resolveUserKey: input.resolveUserKey,\n });\n if (!verifiedAdmins) {\n return null;\n }\n observePrincipalPolicy(\n input.checkpointContext,\n verified.value,\n input.organizationId,\n );\n observePrincipalPolicy(\n input.checkpointContext,\n verifiedAdmins,\n input.organizationId,\n );\n return organizationAdminExternalAuthority(verifiedAdmins);\n } catch (error) {\n rethrowProjectionVerificationBoundaryError(error);\n if (error instanceof KeyingVerificationError) {\n throw error;\n }\n return null;\n }\n}\n\nasync function verifyReferencedPrincipalPolicy(input: {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n principalPolicyCache: PrincipalPolicyCache;\n reference: ReferencedPrincipalHead;\n stillCurrent?: (() => boolean) | undefined;\n resolveUserKey: ProjectionUserKeyResolver;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence> {\n // Scoped recovery carries organization, dependency and lifetime bindings.\n // A bare policy cache entry cannot replace those bindings.\n const recovered = await resolveReferencedPrincipalPolicy(input);\n if (recovered) return recovered;\n const cacheKey = referencedPrincipalPolicyKey(input.reference);\n const cachedPolicy = input.principalPolicyCache.get(cacheKey);\n const execSql = input.checkpointContext.execSql;\n const localCheckpoint = await loadPrincipalPolicyCheckpoint(\n execSql,\n input.reference.principalType,\n input.reference.principalId,\n );\n if (cachedPolicy && !(\"retainedHistory\" in cachedPolicy)) {\n if (\n !verifiedPrincipalPolicyContainsReference(cachedPolicy, input.reference)\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"in-memory principal policy cache does not match its exact reference\",\n );\n }\n if (verifiedPrincipalPolicyMeetsCheckpoint(cachedPolicy, localCheckpoint)) {\n observePrincipalPolicy(\n input.checkpointContext,\n cachedPolicy,\n input.organizationId,\n );\n return cachedPolicy;\n }\n }\n\n const referenceLabel = principalPolicyReferenceLabel(input.reference);\n let bundle = await loadPrincipalPolicyBundleForReference(\n execSql,\n input.reference,\n localCheckpoint,\n );\n if (!bundle && input.warmReferencedPrincipalPolicies) {\n // The reference is not cached locally — the common case for a member who\n // gained access via another org's group grant and never hydrated that\n // group's policy. Fetch+verify+persist it, then re-read from the cache.\n await input.warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: [input.reference],\n });\n bundle = await loadPrincipalPolicyBundleForReference(\n execSql,\n input.reference,\n localCheckpoint,\n );\n }\n if (!bundle) {\n throw new PrincipalPolicyNotCachedError(referenceLabel);\n }\n\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n label: `Principal policy ${referenceLabel}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle,\n expectedReference: input.reference,\n loadExternalAuthority: () =>\n loadOrganizationExternalAuthority({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies:\n input.warmReferencedPrincipalPolicies,\n }),\n localCheckpoint,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n\n observePrincipalPolicy(\n input.checkpointContext,\n verified.value,\n input.organizationId,\n );\n input.principalPolicyCache.set(cacheKey, verified.value);\n return verified.value;\n}\n\nexport async function collectReferencedPrincipalPolicies(input: {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n principalPolicyCache: PrincipalPolicyCache;\n references: readonly ReferencedPrincipalHead[];\n resolveUserKey: ProjectionUserKeyResolver;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence[]> {\n const warmReferencedPrincipalPolicies =\n generationGuardedPrincipalPolicyWarmer(\n input.warmReferencedPrincipalPolicies,\n input.stillCurrent,\n );\n const uniqueReferences = new Map<string, ReferencedPrincipalHead>();\n for (const reference of input.references) {\n uniqueReferences.set(referencedPrincipalPolicyKey(reference), reference);\n }\n\n const references = [...uniqueReferences.values()];\n // Warm every missing reference in one batched fetch before verifying, so a\n // path that references several uncached policies makes a single round of\n // requests rather than one per reference.\n if (\n warmReferencedPrincipalPolicies &&\n !warmReferencedPrincipalPolicies.resolveReference\n ) {\n const uncached = await filterUncachedPrincipalPolicyReferences({\n execSql: input.checkpointContext.execSql,\n principalPolicyCache: input.principalPolicyCache,\n references,\n });\n if (uncached.length > 0) {\n assertProjectionVerificationCurrent(input.stillCurrent);\n await warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: uncached,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n }\n }\n\n // The warmer's operation shares one recovery view across its collections.\n return Promise.all(\n references.map((reference) =>\n verifyReferencedPrincipalPolicy({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n principalPolicyCache: input.principalPolicyCache,\n reference,\n stillCurrent: input.stillCurrent,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies,\n }),\n ),\n );\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { readRecordNullableString, readRecordString, readRequiredRecordValue, } from "../recordReaders.js";
|
|
1
|
+
export { readRecordNullableString, readRecordString, readRequiredRecordValue, } from "../shared/recordReaders.js";
|
|
2
2
|
import type { AccessEvent, AccessManifest, ContainerKekRecipientTarget, ContainerKeyEpoch, ContainerKeyWrap, DocumentLinkAccessEventBody, DocumentUnlinkAccessEventBody } from "../../internal/crypto/index.js";
|
|
3
3
|
export declare function readAccessEvent(value: unknown, label: string): AccessEvent;
|
|
4
4
|
export declare function readAccessManifest(value: unknown, label: string): AccessManifest;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { normalizeDocumentAccessEventBody } from "../../internal/crypto/index.js";
|
|
2
|
-
export { readRecordNullableString, readRecordString, readRequiredRecordValue, } from "../recordReaders.js";
|
|
3
|
-
import { readCanonicalJson, readCanonicalRecord } from "../
|
|
4
|
-
import { readRecordNullableString, readRecordPositiveInteger, readRecordString, readRequiredRecordValue, readStringArray, } from "../recordReaders.js";
|
|
2
|
+
export { readRecordNullableString, readRecordString, readRequiredRecordValue, } from "../shared/recordReaders.js";
|
|
3
|
+
import { readCanonicalJson, readCanonicalRecord, } from "../keying/canonicalJson.js";
|
|
4
|
+
import { readRecordNullableString, readRecordPositiveInteger, readRecordString, readRequiredRecordValue, readStringArray, } from "../shared/recordReaders.js";
|
|
5
5
|
import { readKeyingVerificationShape } from "./error.js";
|
|
6
6
|
function isAccessEventType(value) {
|
|
7
7
|
return (value === "attachment.bind" ||
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"readers.js","sourceRoot":"","sources":["readers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gCAAgC,EAAE,MAAM,mBAAmB,CAAC;AAErE,OAAO,EACL,wBAAwB,EACxB,gBAAgB,EAChB,uBAAuB,GACxB,MAAM,kBAAkB,CAAC;AAW1B,OAAO,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAChF,OAAO,EACL,wBAAwB,EACxB,yBAAyB,EACzB,gBAAgB,EAChB,uBAAuB,EACvB,eAAe,GAChB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,2BAA2B,EAAE,MAAM,SAAS,CAAC;AAEtD,SAAS,iBAAiB,CAAC,KAAc;IACvC,OAAO,CACL,KAAK,KAAK,iBAAiB;QAC3B,KAAK,KAAK,mBAAmB;QAC7B,KAAK,KAAK,kBAAkB;QAC5B,KAAK,KAAK,iBAAiB;QAC3B,KAAK,KAAK,gBAAgB;QAC1B,KAAK,KAAK,iBAAiB;QAC3B,KAAK,KAAK,kBAAkB;QAC5B,KAAK,KAAK,kBAAkB;QAC5B,KAAK,KAAK,eAAe;QACzB,KAAK,KAAK,gBAAgB;QAC1B,KAAK,KAAK,iBAAiB,CAC5B,CAAC;AACJ,CAAC;AAED,SAAS,kBAAkB,CACzB,KAAc;IAEd,OAAO,KAAK,KAAK,MAAM,IAAI,KAAK,KAAK,WAAW,IAAI,KAAK,KAAK,UAAU,CAAC;AAC3E,CAAC;AAED,SAAS,eAAe,CAC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K,CACN,CAAC;QACF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,EAAE,CAAC;YACpC,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,2BAA2B,CAAC,CAAC;QACvD,CAAC;QAED,OAAO;YACL,aAAa;YACb,WAAW,EAAE,gBAAgB,CAAC,MAAM,EAAE,aAAa,EAAE,KAAK,CAAC;YAC3D,mBAAmB,EAAE,gBAAgB,CACnC,MAAM,EACN,qBAAqB,EACrB,KAAK,CACN;YACD,uBAAuB,EAAE,gBAAgB,CACvC,MAAM,EACN,yBAAyB,EACzB,KAAK,CACN;SACF,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,2BAA2B,CACzC,KAAc,EACd,KAAa;IAEb,OAAO,2BAA2B,CAAC,GAAG,EAAE,CACtC,gCAAgC,CAAC,iBAAiB,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAClE,CAAC;AACJ,CAAC","sourcesContent":["import { normalizeDocumentAccessEventBody } from \"@tearleads/crypto\";\n\nexport {\n readRecordNullableString,\n readRecordString,\n readRequiredRecordValue,\n} from \"../recordReaders\";\n\nimport type {\n AccessEvent,\n AccessManifest,\n ContainerKekRecipientTarget,\n ContainerKeyEpoch,\n ContainerKeyWrap,\n DocumentLinkAccessEventBody,\n DocumentUnlinkAccessEventBody,\n} from \"@tearleads/crypto\";\nimport { readCanonicalJson, readCanonicalRecord } from \"../keyingCanonicalJson\";\nimport {\n readRecordNullableString,\n readRecordPositiveInteger,\n readRecordString,\n readRequiredRecordValue,\n readStringArray,\n} from \"../recordReaders\";\nimport { readKeyingVerificationShape } from \"./error\";\n\nfunction isAccessEventType(value: unknown): value is AccessEvent[\"eventType\"] {\n return (\n value === \"attachment.bind\" ||\n value === \"attachment.detach\" ||\n value === \"container.create\" ||\n value === \"container.grant\" ||\n value === \"container.move\" ||\n value === \"container.rekey\" ||\n value === \"container.recite\" ||\n value === \"container.revoke\" ||\n value === \"document.link\" ||\n value === \"document.purge\" ||\n value === \"document.unlink\"\n );\n}\n\nfunction isAccessObjectKind(\n value: unknown,\n): value is AccessEvent[\"objectKind\"] {\n return value === \"blob\" || value === \"container\" || value === \"document\";\n}\n\nfunction isRecipientKind(\n value: unknown,\n): value is ContainerKekRecipientTarget[\"recipientKind\"] {\n return value === \"container\" || value === \"group\" || value === \"user\";\n}\n\nexport function readAccessEvent(value: unknown, label: string): AccessEvent {\n return readKeyingVerificationShape(() => readAccessEventShape(value, label));\n}\n\nfunction readAccessEventShape(value: unknown, label: string): AccessEvent {\n const record = readCanonicalRecord(value, label);\n const eventType = readRequiredRecordValue(record, \"eventType\", label);\n const objectKind = readRequiredRecordValue(record, \"objectKind\", label);\n if (!isAccessEventType(eventType)) {\n throw new Error(`${label}.eventType is invalid`);\n }\n if (!isAccessObjectKind(objectKind)) {\n throw new Error(`${label}.objectKind is invalid`);\n }\n if (readRecordPositiveInteger(record, \"version\", label) !== 1) {\n throw new Error(`${label}.version must be 1`);\n }\n\n return {\n version: 1,\n eventId: readRecordString(record, \"eventId\", label),\n eventType,\n objectKind,\n objectId: readRecordString(record, \"objectId\", label),\n organizationId: readRecordString(record, \"organizationId\", label),\n previousManifestHash: readRecordNullableString(\n record,\n \"previousManifestHash\",\n label,\n ),\n dependencyManifestHashes: readStringArray(\n readRequiredRecordValue(record, \"dependencyManifestHashes\", label),\n `${label}.dependencyManifestHashes`,\n ),\n bodyHash: readRecordString(record, \"bodyHash\", label),\n signerUserId: readRecordString(record, \"signerUserId\", label),\n signerDeviceId: readRecordString(record, \"signerDeviceId\", label),\n signerKeyFingerprint: readRecordString(\n record,\n \"signerKeyFingerprint\",\n label,\n ),\n signedAt: readRecordString(record, \"signedAt\", label),\n signature: readRecordString(record, \"signature\", label),\n };\n}\n\nexport function readAccessManifest(\n value: unknown,\n label: string,\n): AccessManifest {\n return readKeyingVerificationShape(() =>\n readAccessManifestShape(value, label),\n );\n}\n\nfunction readAccessManifestShape(\n value: unknown,\n label: string,\n): AccessManifest {\n const record = readCanonicalRecord(value, label);\n const objectKind = readRequiredRecordValue(record, \"objectKind\", label);\n if (!isAccessObjectKind(objectKind)) {\n throw new Error(`${label}.objectKind is invalid`);\n }\n if (readRecordPositiveInteger(record, \"version\", label) !== 1) {\n throw new Error(`${label}.version must be 1`);\n }\n const referencedPrincipalHeads = readRequiredRecordValue(\n record,\n \"referencedPrincipalHeads\",\n label,\n );\n if (!Array.isArray(referencedPrincipalHeads)) {\n throw new Error(`${label}.referencedPrincipalHeads must be an array`);\n }\n\n return {\n version: 1,\n objectKind,\n objectId: readRecordString(record, \"objectId\", label),\n organizationId: readRecordString(record, \"organizationId\", label),\n epoch: readRecordPositiveInteger(record, \"epoch\", label),\n previousManifestHash: readRecordNullableString(\n record,\n \"previousManifestHash\",\n label,\n ),\n eventHash: readRecordString(record, \"eventHash\", label),\n structuralHash: readRecordString(record, \"structuralHash\", label),\n grantRoot: readRecordString(record, \"grantRoot\", label),\n referencedPrincipalHeads: referencedPrincipalHeads.map((head, index) => {\n const headRecord = readCanonicalRecord(\n head,\n `${label}.referencedPrincipalHeads[${index}]`,\n );\n const principalType = readRequiredRecordValue(\n headRecord,\n \"principalType\",\n `${label}.referencedPrincipalHeads[${index}]`,\n );\n if (principalType !== \"group\" && principalType !== \"organization\") {\n throw new Error(\n `${label}.referencedPrincipalHeads[${index}].principalType is invalid`,\n );\n }\n return {\n principalType,\n principalId: readRecordString(\n headRecord,\n \"principalId\",\n `${label}.referencedPrincipalHeads[${index}]`,\n ),\n version: readRecordPositiveInteger(\n headRecord,\n \"version\",\n `${label}.referencedPrincipalHeads[${index}]`,\n ),\n keyEpoch: readRecordPositiveInteger(\n headRecord,\n \"keyEpoch\",\n `${label}.referencedPrincipalHeads[${index}]`,\n ),\n stateHash: readRecordString(\n headRecord,\n \"stateHash\",\n `${label}.referencedPrincipalHeads[${index}]`,\n ),\n keyFingerprint: readRecordString(\n headRecord,\n \"keyFingerprint\",\n `${label}.referencedPrincipalHeads[${index}]`,\n ),\n };\n }),\n keyTargetHash: readRecordString(record, \"keyTargetHash\", label),\n };\n}\n\nexport function readContainerKeyEpoch(\n value: unknown,\n label: string,\n): ContainerKeyEpoch {\n return readKeyingVerificationShape(() => {\n const record = readCanonicalRecord(value, label);\n\n return {\n id: readRecordString(record, \"id\", label),\n containerId: readRecordString(record, \"containerId\", label),\n keyEpoch: readRecordPositiveInteger(record, \"keyEpoch\", label),\n accessManifestHash: readRecordString(record, \"accessManifestHash\", label),\n parentContainerKeyEpochId: readRecordNullableString(\n record,\n \"parentContainerKeyEpochId\",\n label,\n ),\n createdByEventHash: readRecordString(record, \"createdByEventHash\", label),\n createdByManifestHash: readRecordString(\n record,\n \"createdByManifestHash\",\n label,\n ),\n };\n });\n}\n\nexport function readContainerKeyWrap(\n value: unknown,\n label: string,\n): ContainerKeyWrap {\n return readKeyingVerificationShape(() => {\n const record = readCanonicalRecord(value, label);\n const recipientKind = readRequiredRecordValue(\n record,\n \"recipientKind\",\n label,\n );\n if (!isRecipientKind(recipientKind)) {\n throw new Error(`${label}.recipientKind is invalid`);\n }\n\n return {\n containerKeyEpochId: readRecordString(\n record,\n \"containerKeyEpochId\",\n label,\n ),\n recipientKind,\n recipientId: readRecordString(record, \"recipientId\", label),\n recipientKeyEpochId: readRecordString(\n record,\n \"recipientKeyEpochId\",\n label,\n ),\n recipientKeyFingerprint: readRecordString(\n record,\n \"recipientKeyFingerprint\",\n label,\n ),\n kemCipherText: readRecordString(record, \"kemCipherText\", label),\n wrappedKey: readRecordString(record, \"wrappedKey\", label),\n wrapManifestHash: readRecordString(record, \"wrapManifestHash\", label),\n };\n });\n}\n\nexport function readContainerKekRecipientTarget(\n value: unknown,\n label: string,\n): ContainerKekRecipientTarget {\n return readKeyingVerificationShape(() => {\n const record = readCanonicalRecord(value, label);\n const recipientKind = readRequiredRecordValue(\n record,\n \"recipientKind\",\n label,\n );\n if (!isRecipientKind(recipientKind)) {\n throw new Error(`${label}.recipientKind is invalid`);\n }\n\n return {\n recipientKind,\n recipientId: readRecordString(record, \"recipientId\", label),\n recipientKeyEpochId: readRecordString(\n record,\n \"recipientKeyEpochId\",\n label,\n ),\n recipientKeyFingerprint: readRecordString(\n record,\n \"recipientKeyFingerprint\",\n label,\n ),\n };\n });\n}\n\nexport function readDocumentAccessEventBody(\n value: unknown,\n label: string,\n): DocumentLinkAccessEventBody | DocumentUnlinkAccessEventBody {\n return readKeyingVerificationShape(() =>\n normalizeDocumentAccessEventBody(readCanonicalJson(value, label)),\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"readers.js","sourceRoot":"","sources":["readers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gCAAgC,EAAE,MAAM,mBAAmB,CAAC;AAErE,OAAO,EACL,wBAAwB,EACxB,gBAAgB,EAChB,uBAAuB,GACxB,MAAM,yBAAyB,CAAC;AAWjC,OAAO,EACL,iBAAiB,EACjB,mBAAmB,GACpB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACL,wBAAwB,EACxB,yBAAyB,EACzB,gBAAgB,EAChB,uBAAuB,EACvB,eAAe,GAChB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,2BAA2B,EAAE,MAAM,SAAS,CAAC;AAEtD,SAAS,iBAAiB,CAAC,KAAc;IACvC,OAAO,CACL,KAAK,KAAK,iBAAiB;QAC3B,KAAK,KAAK,mBAAmB;QAC7B,KAAK,KAAK,kBAAkB;QAC5B,KAAK,KAAK,iBAAiB;QAC3B,KAAK,KAAK,gBAAgB;QAC1B,KAAK,KAAK,iBAAiB;QAC3B,KAAK,KAAK,kBAAkB;QAC5B,KAAK,KAAK,kBAAkB;QAC5B,KAAK,KAAK,eAAe;QACzB,KAAK,KAAK,gBAAgB;QAC1B,KAAK,KAAK,iBAAiB,CAC5B,CAAC;AACJ,CAAC;AAED,SAAS,kBAAkB,CACzB,KAAc;IAEd,OAAO,KAAK,KAAK,MAAM,IAAI,KAAK,KAAK,WAAW,IAAI,KAAK,KAAK,UAAU,CAAC;AAC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3C,MAAM,EACN,eAAe,EACf,KAAK,CACN,CAAC;QACF,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,EAAE,CAAC;YACpC,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,2BAA2B,CAAC,CAAC;QACvD,CAAC;QAED,OAAO;YACL,aAAa;YACb,WAAW,EAAE,gBAAgB,CAAC,MAAM,EAAE,aAAa,EAAE,KAAK,CAAC;YAC3D,mBAAmB,EAAE,gBAAgB,CACnC,MAAM,EACN,qBAAqB,EACrB,KAAK,CACN;YACD,uBAAuB,EAAE,gBAAgB,CACvC,MAAM,EACN,yBAAyB,EACzB,KAAK,CACN;SACF,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,2BAA2B,CACzC,KAAc,EACd,KAAa;IAEb,OAAO,2BAA2B,CAAC,GAAG,EAAE,CACtC,gCAAgC,CAAC,iBAAiB,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAClE,CAAC;AACJ,CAAC","sourcesContent":["import { normalizeDocumentAccessEventBody } from \"@tearleads/crypto\";\n\nexport {\n readRecordNullableString,\n readRecordString,\n readRequiredRecordValue,\n} from \"../shared/recordReaders\";\n\nimport type {\n AccessEvent,\n AccessManifest,\n ContainerKekRecipientTarget,\n ContainerKeyEpoch,\n ContainerKeyWrap,\n DocumentLinkAccessEventBody,\n DocumentUnlinkAccessEventBody,\n} from \"@tearleads/crypto\";\nimport {\n readCanonicalJson,\n readCanonicalRecord,\n} from \"../keying/canonicalJson\";\nimport {\n readRecordNullableString,\n readRecordPositiveInteger,\n readRecordString,\n readRequiredRecordValue,\n readStringArray,\n} from \"../shared/recordReaders\";\nimport { readKeyingVerificationShape } from \"./error\";\n\nfunction isAccessEventType(value: unknown): value is AccessEvent[\"eventType\"] {\n return (\n value === \"attachment.bind\" ||\n value === \"attachment.detach\" ||\n value === \"container.create\" ||\n value === \"container.grant\" ||\n value === \"container.move\" ||\n value === \"container.rekey\" ||\n value === \"container.recite\" ||\n value === \"container.revoke\" ||\n value === \"document.link\" ||\n value === \"document.purge\" ||\n value === \"document.unlink\"\n );\n}\n\nfunction isAccessObjectKind(\n value: unknown,\n): value is AccessEvent[\"objectKind\"] {\n return value === \"blob\" || value === \"container\" || value === \"document\";\n}\n\nfunction isRecipientKind(\n value: unknown,\n): value is ContainerKekRecipientTarget[\"recipientKind\"] {\n return value === \"container\" || value === \"group\" || value === \"user\";\n}\n\nexport function readAccessEvent(value: unknown, label: string): AccessEvent {\n return readKeyingVerificationShape(() => readAccessEventShape(value, label));\n}\n\nfunction readAccessEventShape(value: unknown, label: string): AccessEvent {\n const record = readCanonicalRecord(value, label);\n const eventType = readRequiredRecordValue(record, \"eventType\", label);\n const objectKind = readRequiredRecordValue(record, \"objectKind\", label);\n if (!isAccessEventType(eventType)) {\n throw new Error(`${label}.eventType is invalid`);\n }\n if (!isAccessObjectKind(objectKind)) {\n throw new Error(`${label}.objectKind is invalid`);\n }\n if (readRecordPositiveInteger(record, \"version\", label) !== 1) {\n throw new Error(`${label}.version must be 1`);\n }\n\n return {\n version: 1,\n eventId: readRecordString(record, \"eventId\", label),\n eventType,\n objectKind,\n objectId: readRecordString(record, \"objectId\", label),\n organizationId: readRecordString(record, \"organizationId\", label),\n previousManifestHash: readRecordNullableString(\n record,\n \"previousManifestHash\",\n label,\n ),\n dependencyManifestHashes: readStringArray(\n readRequiredRecordValue(record, \"dependencyManifestHashes\", label),\n `${label}.dependencyManifestHashes`,\n ),\n bodyHash: readRecordString(record, \"bodyHash\", label),\n signerUserId: readRecordString(record, \"signerUserId\", label),\n signerDeviceId: readRecordString(record, \"signerDeviceId\", label),\n signerKeyFingerprint: readRecordString(\n record,\n \"signerKeyFingerprint\",\n label,\n ),\n signedAt: readRecordString(record, \"signedAt\", label),\n signature: readRecordString(record, \"signature\", label),\n };\n}\n\nexport function readAccessManifest(\n value: unknown,\n label: string,\n): AccessManifest {\n return readKeyingVerificationShape(() =>\n readAccessManifestShape(value, label),\n );\n}\n\nfunction readAccessManifestShape(\n value: unknown,\n label: string,\n): AccessManifest {\n const record = readCanonicalRecord(value, label);\n const objectKind = readRequiredRecordValue(record, \"objectKind\", label);\n if (!isAccessObjectKind(objectKind)) {\n throw new Error(`${label}.objectKind is invalid`);\n }\n if (readRecordPositiveInteger(record, \"version\", label) !== 1) {\n throw new Error(`${label}.version must be 1`);\n }\n const referencedPrincipalHeads = readRequiredRecordValue(\n record,\n \"referencedPrincipalHeads\",\n label,\n );\n if (!Array.isArray(referencedPrincipalHeads)) {\n throw new Error(`${label}.referencedPrincipalHeads must be an array`);\n }\n\n return {\n version: 1,\n objectKind,\n objectId: readRecordString(record, \"objectId\", label),\n organizationId: readRecordString(record, \"organizationId\", label),\n epoch: readRecordPositiveInteger(record, \"epoch\", label),\n previousManifestHash: readRecordNullableString(\n record,\n \"previousManifestHash\",\n label,\n ),\n eventHash: readRecordString(record, \"eventHash\", label),\n structuralHash: readRecordString(record, \"structuralHash\", label),\n grantRoot: readRecordString(record, \"grantRoot\", label),\n referencedPrincipalHeads: referencedPrincipalHeads.map((head, index) => {\n const headRecord = readCanonicalRecord(\n head,\n `${label}.referencedPrincipalHeads[${index}]`,\n );\n const principalType = readRequiredRecordValue(\n headRecord,\n \"principalType\",\n `${label}.referencedPrincipalHeads[${index}]`,\n );\n if (principalType !== \"group\" && principalType !== \"organization\") {\n throw new Error(\n `${label}.referencedPrincipalHeads[${index}].principalType is invalid`,\n );\n }\n return {\n principalType,\n principalId: readRecordString(\n headRecord,\n \"principalId\",\n `${label}.referencedPrincipalHeads[${index}]`,\n ),\n version: readRecordPositiveInteger(\n headRecord,\n \"version\",\n `${label}.referencedPrincipalHeads[${index}]`,\n ),\n keyEpoch: readRecordPositiveInteger(\n headRecord,\n \"keyEpoch\",\n `${label}.referencedPrincipalHeads[${index}]`,\n ),\n stateHash: readRecordString(\n headRecord,\n \"stateHash\",\n `${label}.referencedPrincipalHeads[${index}]`,\n ),\n keyFingerprint: readRecordString(\n headRecord,\n \"keyFingerprint\",\n `${label}.referencedPrincipalHeads[${index}]`,\n ),\n };\n }),\n keyTargetHash: readRecordString(record, \"keyTargetHash\", label),\n };\n}\n\nexport function readContainerKeyEpoch(\n value: unknown,\n label: string,\n): ContainerKeyEpoch {\n return readKeyingVerificationShape(() => {\n const record = readCanonicalRecord(value, label);\n\n return {\n id: readRecordString(record, \"id\", label),\n containerId: readRecordString(record, \"containerId\", label),\n keyEpoch: readRecordPositiveInteger(record, \"keyEpoch\", label),\n accessManifestHash: readRecordString(record, \"accessManifestHash\", label),\n parentContainerKeyEpochId: readRecordNullableString(\n record,\n \"parentContainerKeyEpochId\",\n label,\n ),\n createdByEventHash: readRecordString(record, \"createdByEventHash\", label),\n createdByManifestHash: readRecordString(\n record,\n \"createdByManifestHash\",\n label,\n ),\n };\n });\n}\n\nexport function readContainerKeyWrap(\n value: unknown,\n label: string,\n): ContainerKeyWrap {\n return readKeyingVerificationShape(() => {\n const record = readCanonicalRecord(value, label);\n const recipientKind = readRequiredRecordValue(\n record,\n \"recipientKind\",\n label,\n );\n if (!isRecipientKind(recipientKind)) {\n throw new Error(`${label}.recipientKind is invalid`);\n }\n\n return {\n containerKeyEpochId: readRecordString(\n record,\n \"containerKeyEpochId\",\n label,\n ),\n recipientKind,\n recipientId: readRecordString(record, \"recipientId\", label),\n recipientKeyEpochId: readRecordString(\n record,\n \"recipientKeyEpochId\",\n label,\n ),\n recipientKeyFingerprint: readRecordString(\n record,\n \"recipientKeyFingerprint\",\n label,\n ),\n kemCipherText: readRecordString(record, \"kemCipherText\", label),\n wrappedKey: readRecordString(record, \"wrappedKey\", label),\n wrapManifestHash: readRecordString(record, \"wrapManifestHash\", label),\n };\n });\n}\n\nexport function readContainerKekRecipientTarget(\n value: unknown,\n label: string,\n): ContainerKekRecipientTarget {\n return readKeyingVerificationShape(() => {\n const record = readCanonicalRecord(value, label);\n const recipientKind = readRequiredRecordValue(\n record,\n \"recipientKind\",\n label,\n );\n if (!isRecipientKind(recipientKind)) {\n throw new Error(`${label}.recipientKind is invalid`);\n }\n\n return {\n recipientKind,\n recipientId: readRecordString(record, \"recipientId\", label),\n recipientKeyEpochId: readRecordString(\n record,\n \"recipientKeyEpochId\",\n label,\n ),\n recipientKeyFingerprint: readRecordString(\n record,\n \"recipientKeyFingerprint\",\n label,\n ),\n };\n });\n}\n\nexport function readDocumentAccessEventBody(\n value: unknown,\n label: string,\n): DocumentLinkAccessEventBody | DocumentUnlinkAccessEventBody {\n return readKeyingVerificationShape(() =>\n normalizeDocumentAccessEventBody(readCanonicalJson(value, label)),\n );\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { ProjectionUserKeyResolver } from "../keyingProjectionVerification.js";
|
|
2
1
|
import { type TrustedUserIdentityResolver } from "../trustedUserIdentity/index.js";
|
|
2
|
+
import type { ProjectionUserKeyResolver } from "./types.js";
|
|
3
3
|
interface ProjectionUserKeyRuntime {
|
|
4
4
|
readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;
|
|
5
5
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"userKeyResolver.js","sourceRoot":"","sources":["userKeyResolver.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"userKeyResolver.js","sourceRoot":"","sources":["userKeyResolver.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kCAAkC,GAEnC,MAAM,wBAAwB,CAAC;AAOhC,MAAM,UAAU,+BAA+B,CAC7C,OAAiC;IAEjC,MAAM,0BAA0B,GAAG,kCAAkC,CACnE,OAAO,CAAC,0BAA0B,CACnC,CAAC;IACF,MAAM,KAAK,GAAG,IAAI,GAAG,EAA6C,CAAC;IAEnE,OAAO,KAAK,EAAE,MAAM,EAAE,EAAE;QACtB,IAAI,MAAM,GAAG,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAC/B,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,MAAM,GAAG,0BAA0B,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;gBACnE,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;gBACrB,MAAM,KAAK,CAAC;YACd,CAAC,CAAC,CAAC;YACH,KAAK,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAC5B,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n requireTrustedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n} from \"../trustedUserIdentity\";\nimport type { ProjectionUserKey, ProjectionUserKeyResolver } from \"./types\";\n\ninterface ProjectionUserKeyRuntime {\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\nexport function createProjectionUserKeyResolver(\n runtime: ProjectionUserKeyRuntime,\n): ProjectionUserKeyResolver {\n const resolveTrustedUserIdentity = requireTrustedUserIdentityResolver(\n runtime.resolveTrustedUserIdentity,\n );\n const cache = new Map<string, Promise<ProjectionUserKey | null>>();\n\n return async (userId) => {\n let cached = cache.get(userId);\n if (!cached) {\n cached = resolveTrustedUserIdentity(userId).catch((error: unknown) => {\n cache.delete(userId);\n throw error;\n });\n cache.set(userId, cached);\n }\n\n return cached;\n };\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { isContainerSystemSlot, } from "../../../internal/validators/containerSystemSlot.js";
|
|
2
2
|
import { asc, eq, inArray, sql } from "drizzle-orm";
|
|
3
|
-
import { DEFAULT_EFFECTIVE_ACCESS_LEVEL, normalizeEffectiveAccessLevel, } from "../../accessLevel.js";
|
|
3
|
+
import { DEFAULT_EFFECTIVE_ACCESS_LEVEL, normalizeEffectiveAccessLevel, } from "../../keying/accessLevel.js";
|
|
4
4
|
import { containers, containerTables } from "../../sqlite/schema.js";
|
|
5
5
|
import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
|
|
6
6
|
import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
|
|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AC;IAE5C,OAAO,IAAI,GAAG,CACZ,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE;QACnB,MAAM,WAAW,GAAG,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;QACpC,IAAI,CAAC,GAAG,CAAC,EAAE,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACxC,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,OAAO,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,WAAW,CAAC,CAAC,CAAC;IACjC,CAAC,CAAC,CACH,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,aAAa,CACjC,OAAgB,EAChB,MAAuB;IAEvB,MAAM,cAAc,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IAEhD,MAAM,iCAAiC,CAAC,OAAO,CAAC,CAAC,WAAW,CAAC,KAAK,EAAE,EAAE,EAAE,EAAE;QACxE,MAAM,iBAAiB,CAAC;YACtB,MAAM;YACN,EAAE;YACF,cAAc;SACf,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,EAAgC,EAChC,GAA0B;IAE1B,MAAM,SAAS,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC;IAC3C,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC3B,OAAO;IACT,CAAC;IACD,MAAM,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,EAAE,SAAS,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC;AAC7E,CAAC","sourcesContent":["import type { ContainerAccessLevel } from \"@tearleads/crypto\";\nimport {\n type ContainerSystemSlot,\n isContainerSystemSlot,\n} from \"@tearleads/validators/containerSystemSlot\";\nimport { asc, eq, inArray, sql } from \"drizzle-orm\";\nimport {\n DEFAULT_EFFECTIVE_ACCESS_LEVEL,\n normalizeEffectiveAccessLevel,\n} from \"../../accessLevel\";\nimport { containers, containerTables } from \"../../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\n\nexport interface ContainerRecord {\n createdAt?: string | null;\n effectiveAccessLevel?: ContainerAccessLevel | null;\n id: string;\n organizationId: string;\n parentId: string | null;\n metadataDocumentId: string | null;\n systemSlot?: ContainerSystemSlot | null;\n name: string;\n icon: string | null;\n localCreatedAt?: string | null;\n localUpdatedAt?: string | null;\n serverCreatedAt?: string | null;\n serverUpdatedAt?: string | null;\n updatedAt?: string | null;\n}\n\ninterface ContainerRecordWithTimestampDefaults extends ContainerRecord {\n createdAt: string | null;\n localCreatedAt: string;\n localUpdatedAt: string;\n serverCreatedAt: string | null;\n serverUpdatedAt: string | null;\n updatedAt: string | null;\n}\n\nexport function ensureContainerTables(execSql: ExecSql): Promise<void> {\n return ensureSqlTables(execSql, containerTables);\n}\n\n// The ONE display-name fallback: a decrypted metadata name names the container;\n// without one the root reads '/' and everything else 'Untitled'.\nconst containerDisplayName = sql<string>`COALESCE(\n ${containers.displayName},\n CASE WHEN ${containers.parentId} IS NULL THEN '/' ELSE 'Untitled' END\n )`;\n\ninterface SelectedContainerRecord {\n effectiveAccessLevel: string | null;\n id: string | null;\n organizationId: string;\n parentId: string | null;\n metadataDocumentId: string | null;\n systemSlot: string | null;\n name: string;\n icon: string | null;\n localCreatedAt: string;\n localUpdatedAt: string;\n serverCreatedAt: string | null;\n serverUpdatedAt: string | null;\n}\n\nfunction toDisplayContainerRecord(record: ContainerRecord): ContainerRecord {\n return {\n ...record,\n createdAt: record.serverCreatedAt ?? record.localCreatedAt ?? null,\n updatedAt: record.serverUpdatedAt ?? record.localUpdatedAt ?? null,\n };\n}\n\nfunction applyContainerTimestampDefaults(\n record: ContainerRecord,\n localUpdatedAt: string,\n): ContainerRecordWithTimestampDefaults {\n const hasServerTimestamps =\n record.serverCreatedAt !== undefined ||\n record.serverUpdatedAt !== undefined;\n const localCreatedAt =\n record.localCreatedAt ??\n (!hasServerTimestamps ? record.createdAt : null) ??\n localUpdatedAt;\n const serverCreatedAt = record.serverCreatedAt ?? null;\n const serverUpdatedAt = record.serverUpdatedAt ?? null;\n\n return {\n ...record,\n createdAt: serverCreatedAt ?? localCreatedAt,\n localCreatedAt,\n localUpdatedAt,\n serverCreatedAt,\n serverUpdatedAt,\n updatedAt: serverUpdatedAt ?? localUpdatedAt,\n };\n}\n\nfunction mapSelectedContainerRecord(\n row: SelectedContainerRecord,\n): ContainerRecord {\n const systemSlot = isContainerSystemSlot(row.systemSlot)\n ? row.systemSlot\n : null;\n\n return toDisplayContainerRecord({\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n row.effectiveAccessLevel,\n ),\n id: String(row.id ?? \"\"),\n organizationId: row.organizationId,\n parentId: row.parentId,\n metadataDocumentId: row.metadataDocumentId,\n systemSlot,\n name: row.name,\n icon: row.icon && row.icon.length > 0 ? row.icon : null,\n localCreatedAt: row.localCreatedAt,\n localUpdatedAt: row.localUpdatedAt,\n serverCreatedAt: row.serverCreatedAt,\n serverUpdatedAt: row.serverUpdatedAt,\n });\n}\n\nexport async function saveContainerRows(input: {\n tx: ClientSQLiteTransactionScope;\n record: ContainerRecord;\n localUpdatedAt: string;\n}): Promise<ContainerRecord> {\n const { record, tx, localUpdatedAt } = input;\n const nextRecord = applyContainerTimestampDefaults(record, localUpdatedAt);\n const containerRow = {\n effectiveAccessLevel:\n nextRecord.effectiveAccessLevel ?? DEFAULT_EFFECTIVE_ACCESS_LEVEL,\n id: nextRecord.id,\n organizationId: nextRecord.organizationId,\n parentId: nextRecord.parentId,\n metadataDocumentId: nextRecord.metadataDocumentId,\n systemSlot: nextRecord.systemSlot ?? null,\n displayName: nextRecord.name,\n icon: nextRecord.icon,\n localCreatedAt: nextRecord.localCreatedAt,\n localUpdatedAt,\n serverCreatedAt: nextRecord.serverCreatedAt,\n serverUpdatedAt: nextRecord.serverUpdatedAt,\n };\n await tx\n .insert(containers)\n .values(containerRow)\n .onConflictDoUpdate({\n target: containers.id,\n set: {\n organizationId: containerRow.organizationId,\n parentId: containerRow.parentId,\n metadataDocumentId: containerRow.metadataDocumentId,\n systemSlot: containerRow.systemSlot,\n displayName: containerRow.displayName,\n icon: containerRow.icon,\n effectiveAccessLevel: containerRow.effectiveAccessLevel,\n localUpdatedAt: containerRow.localUpdatedAt,\n serverCreatedAt:\n record.serverCreatedAt === undefined\n ? sql`${containers.serverCreatedAt}`\n : containerRow.serverCreatedAt,\n serverUpdatedAt:\n record.serverUpdatedAt === undefined\n ? sql`${containers.serverUpdatedAt}`\n : containerRow.serverUpdatedAt,\n },\n })\n .run();\n\n return nextRecord;\n}\n\nexport async function loadContainers(\n execSql: ExecSql,\n): Promise<ContainerRecord[]> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({\n effectiveAccessLevel: containers.effectiveAccessLevel,\n id: containers.id,\n organizationId: containers.organizationId,\n parentId: containers.parentId,\n metadataDocumentId: containers.metadataDocumentId,\n systemSlot: containers.systemSlot,\n name: containerDisplayName,\n icon: containers.icon,\n localCreatedAt: containers.localCreatedAt,\n localUpdatedAt: containers.localUpdatedAt,\n serverCreatedAt: containers.serverCreatedAt,\n serverUpdatedAt: containers.serverUpdatedAt,\n })\n .from(containers)\n .orderBy(asc(sql`${containerDisplayName} COLLATE NOCASE`));\n\n return rows.map((row) => mapSelectedContainerRecord(row));\n}\n\nexport async function loadContainerById(\n execSql: ExecSql,\n containerId: string,\n): Promise<ContainerRecord | null> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({\n effectiveAccessLevel: containers.effectiveAccessLevel,\n id: containers.id,\n organizationId: containers.organizationId,\n parentId: containers.parentId,\n metadataDocumentId: containers.metadataDocumentId,\n systemSlot: containers.systemSlot,\n name: containerDisplayName,\n icon: containers.icon,\n localCreatedAt: containers.localCreatedAt,\n localUpdatedAt: containers.localUpdatedAt,\n serverCreatedAt: containers.serverCreatedAt,\n serverUpdatedAt: containers.serverUpdatedAt,\n })\n .from(containers)\n .where(eq(containers.id, containerId))\n .limit(1);\n\n return rows[0] ? mapSelectedContainerRecord(rows[0]) : null;\n}\n\nexport async function loadContainerDisplayNamesByIds(\n execSql: ExecSql,\n ids: ReadonlyArray<string>,\n): Promise<Map<string, string>> {\n const uniqueIds = Array.from(new Set(ids));\n if (uniqueIds.length === 0) {\n return new Map();\n }\n\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({\n id: containers.id,\n name: containerDisplayName,\n })\n .from(containers)\n .where(inArray(containers.id, uniqueIds));\n\n return new Map(\n rows.flatMap((row) => {\n const displayName = row.name.trim();\n if (!row.id || displayName.length === 0) {\n return [];\n }\n\n return [[row.id, displayName]];\n }),\n );\n}\n\nexport async function saveContainer(\n execSql: ExecSql,\n record: ContainerRecord,\n): Promise<void> {\n const localUpdatedAt = new Date().toISOString();\n\n await getClientSQLitePersistenceRuntime(execSql).transaction(async (tx) => {\n await saveContainerRows({\n record,\n tx,\n localUpdatedAt,\n });\n });\n}\n\n/**\n * The container-row half of the delete cascade, statement-only so callers\n * can compose it inside one atomic transaction.\n */\nexport async function deleteContainerRowsInTransaction(\n tx: ClientSQLiteTransactionScope,\n ids: ReadonlyArray<string>,\n): Promise<void> {\n const uniqueIds = Array.from(new Set(ids));\n if (uniqueIds.length === 0) {\n return;\n }\n await tx.delete(containers).where(inArray(containers.id, uniqueIds)).run();\n}\n"]}
|
|
1
|
+
{"version":3,"file":"containerPersistence.js","sourceRoot":"","sources":["containerPersistence.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,qBAAqB,GACtB,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAAE,GAAG,EAAE,EAAE,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,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACxC,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,OAAO,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,WAAW,CAAC,CAAC,CAAC;IACjC,CAAC,CAAC,CACH,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,aAAa,CACjC,OAAgB,EAChB,MAAuB;IAEvB,MAAM,cAAc,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IAEhD,MAAM,iCAAiC,CAAC,OAAO,CAAC,CAAC,WAAW,CAAC,KAAK,EAAE,EAAE,EAAE,EAAE;QACxE,MAAM,iBAAiB,CAAC;YACtB,MAAM;YACN,EAAE;YACF,cAAc;SACf,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,EAAgC,EAChC,GAA0B;IAE1B,MAAM,SAAS,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC;IAC3C,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC3B,OAAO;IACT,CAAC;IACD,MAAM,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,EAAE,SAAS,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC;AAC7E,CAAC","sourcesContent":["import type { ContainerAccessLevel } from \"@tearleads/crypto\";\nimport {\n type ContainerSystemSlot,\n isContainerSystemSlot,\n} from \"@tearleads/validators/containerSystemSlot\";\nimport { asc, eq, inArray, sql } from \"drizzle-orm\";\nimport {\n DEFAULT_EFFECTIVE_ACCESS_LEVEL,\n normalizeEffectiveAccessLevel,\n} from \"../../keying/accessLevel\";\nimport { containers, containerTables } from \"../../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\n\nexport interface ContainerRecord {\n createdAt?: string | null;\n effectiveAccessLevel?: ContainerAccessLevel | null;\n id: string;\n organizationId: string;\n parentId: string | null;\n metadataDocumentId: string | null;\n systemSlot?: ContainerSystemSlot | null;\n name: string;\n icon: string | null;\n localCreatedAt?: string | null;\n localUpdatedAt?: string | null;\n serverCreatedAt?: string | null;\n serverUpdatedAt?: string | null;\n updatedAt?: string | null;\n}\n\ninterface ContainerRecordWithTimestampDefaults extends ContainerRecord {\n createdAt: string | null;\n localCreatedAt: string;\n localUpdatedAt: string;\n serverCreatedAt: string | null;\n serverUpdatedAt: string | null;\n updatedAt: string | null;\n}\n\nexport function ensureContainerTables(execSql: ExecSql): Promise<void> {\n return ensureSqlTables(execSql, containerTables);\n}\n\n// The ONE display-name fallback: a decrypted metadata name names the container;\n// without one the root reads '/' and everything else 'Untitled'.\nconst containerDisplayName = sql<string>`COALESCE(\n ${containers.displayName},\n CASE WHEN ${containers.parentId} IS NULL THEN '/' ELSE 'Untitled' END\n )`;\n\ninterface SelectedContainerRecord {\n effectiveAccessLevel: string | null;\n id: string | null;\n organizationId: string;\n parentId: string | null;\n metadataDocumentId: string | null;\n systemSlot: string | null;\n name: string;\n icon: string | null;\n localCreatedAt: string;\n localUpdatedAt: string;\n serverCreatedAt: string | null;\n serverUpdatedAt: string | null;\n}\n\nfunction toDisplayContainerRecord(record: ContainerRecord): ContainerRecord {\n return {\n ...record,\n createdAt: record.serverCreatedAt ?? record.localCreatedAt ?? null,\n updatedAt: record.serverUpdatedAt ?? record.localUpdatedAt ?? null,\n };\n}\n\nfunction applyContainerTimestampDefaults(\n record: ContainerRecord,\n localUpdatedAt: string,\n): ContainerRecordWithTimestampDefaults {\n const hasServerTimestamps =\n record.serverCreatedAt !== undefined ||\n record.serverUpdatedAt !== undefined;\n const localCreatedAt =\n record.localCreatedAt ??\n (!hasServerTimestamps ? record.createdAt : null) ??\n localUpdatedAt;\n const serverCreatedAt = record.serverCreatedAt ?? null;\n const serverUpdatedAt = record.serverUpdatedAt ?? null;\n\n return {\n ...record,\n createdAt: serverCreatedAt ?? localCreatedAt,\n localCreatedAt,\n localUpdatedAt,\n serverCreatedAt,\n serverUpdatedAt,\n updatedAt: serverUpdatedAt ?? localUpdatedAt,\n };\n}\n\nfunction mapSelectedContainerRecord(\n row: SelectedContainerRecord,\n): ContainerRecord {\n const systemSlot = isContainerSystemSlot(row.systemSlot)\n ? row.systemSlot\n : null;\n\n return toDisplayContainerRecord({\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n row.effectiveAccessLevel,\n ),\n id: String(row.id ?? \"\"),\n organizationId: row.organizationId,\n parentId: row.parentId,\n metadataDocumentId: row.metadataDocumentId,\n systemSlot,\n name: row.name,\n icon: row.icon && row.icon.length > 0 ? row.icon : null,\n localCreatedAt: row.localCreatedAt,\n localUpdatedAt: row.localUpdatedAt,\n serverCreatedAt: row.serverCreatedAt,\n serverUpdatedAt: row.serverUpdatedAt,\n });\n}\n\nexport async function saveContainerRows(input: {\n tx: ClientSQLiteTransactionScope;\n record: ContainerRecord;\n localUpdatedAt: string;\n}): Promise<ContainerRecord> {\n const { record, tx, localUpdatedAt } = input;\n const nextRecord = applyContainerTimestampDefaults(record, localUpdatedAt);\n const containerRow = {\n effectiveAccessLevel:\n nextRecord.effectiveAccessLevel ?? DEFAULT_EFFECTIVE_ACCESS_LEVEL,\n id: nextRecord.id,\n organizationId: nextRecord.organizationId,\n parentId: nextRecord.parentId,\n metadataDocumentId: nextRecord.metadataDocumentId,\n systemSlot: nextRecord.systemSlot ?? null,\n displayName: nextRecord.name,\n icon: nextRecord.icon,\n localCreatedAt: nextRecord.localCreatedAt,\n localUpdatedAt,\n serverCreatedAt: nextRecord.serverCreatedAt,\n serverUpdatedAt: nextRecord.serverUpdatedAt,\n };\n await tx\n .insert(containers)\n .values(containerRow)\n .onConflictDoUpdate({\n target: containers.id,\n set: {\n organizationId: containerRow.organizationId,\n parentId: containerRow.parentId,\n metadataDocumentId: containerRow.metadataDocumentId,\n systemSlot: containerRow.systemSlot,\n displayName: containerRow.displayName,\n icon: containerRow.icon,\n effectiveAccessLevel: containerRow.effectiveAccessLevel,\n localUpdatedAt: containerRow.localUpdatedAt,\n serverCreatedAt:\n record.serverCreatedAt === undefined\n ? sql`${containers.serverCreatedAt}`\n : containerRow.serverCreatedAt,\n serverUpdatedAt:\n record.serverUpdatedAt === undefined\n ? sql`${containers.serverUpdatedAt}`\n : containerRow.serverUpdatedAt,\n },\n })\n .run();\n\n return nextRecord;\n}\n\nexport async function loadContainers(\n execSql: ExecSql,\n): Promise<ContainerRecord[]> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({\n effectiveAccessLevel: containers.effectiveAccessLevel,\n id: containers.id,\n organizationId: containers.organizationId,\n parentId: containers.parentId,\n metadataDocumentId: containers.metadataDocumentId,\n systemSlot: containers.systemSlot,\n name: containerDisplayName,\n icon: containers.icon,\n localCreatedAt: containers.localCreatedAt,\n localUpdatedAt: containers.localUpdatedAt,\n serverCreatedAt: containers.serverCreatedAt,\n serverUpdatedAt: containers.serverUpdatedAt,\n })\n .from(containers)\n .orderBy(asc(sql`${containerDisplayName} COLLATE NOCASE`));\n\n return rows.map((row) => mapSelectedContainerRecord(row));\n}\n\nexport async function loadContainerById(\n execSql: ExecSql,\n containerId: string,\n): Promise<ContainerRecord | null> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({\n effectiveAccessLevel: containers.effectiveAccessLevel,\n id: containers.id,\n organizationId: containers.organizationId,\n parentId: containers.parentId,\n metadataDocumentId: containers.metadataDocumentId,\n systemSlot: containers.systemSlot,\n name: containerDisplayName,\n icon: containers.icon,\n localCreatedAt: containers.localCreatedAt,\n localUpdatedAt: containers.localUpdatedAt,\n serverCreatedAt: containers.serverCreatedAt,\n serverUpdatedAt: containers.serverUpdatedAt,\n })\n .from(containers)\n .where(eq(containers.id, containerId))\n .limit(1);\n\n return rows[0] ? mapSelectedContainerRecord(rows[0]) : null;\n}\n\nexport async function loadContainerDisplayNamesByIds(\n execSql: ExecSql,\n ids: ReadonlyArray<string>,\n): Promise<Map<string, string>> {\n const uniqueIds = Array.from(new Set(ids));\n if (uniqueIds.length === 0) {\n return new Map();\n }\n\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({\n id: containers.id,\n name: containerDisplayName,\n })\n .from(containers)\n .where(inArray(containers.id, uniqueIds));\n\n return new Map(\n rows.flatMap((row) => {\n const displayName = row.name.trim();\n if (!row.id || displayName.length === 0) {\n return [];\n }\n\n return [[row.id, displayName]];\n }),\n );\n}\n\nexport async function saveContainer(\n execSql: ExecSql,\n record: ContainerRecord,\n): Promise<void> {\n const localUpdatedAt = new Date().toISOString();\n\n await getClientSQLitePersistenceRuntime(execSql).transaction(async (tx) => {\n await saveContainerRows({\n record,\n tx,\n localUpdatedAt,\n });\n });\n}\n\n/**\n * The container-row half of the delete cascade, statement-only so callers\n * can compose it inside one atomic transaction.\n */\nexport async function deleteContainerRowsInTransaction(\n tx: ClientSQLiteTransactionScope,\n ids: ReadonlyArray<string>,\n): Promise<void> {\n const uniqueIds = Array.from(new Set(ids));\n if (uniqueIds.length === 0) {\n return;\n }\n await tx.delete(containers).where(inArray(containers.id, uniqueIds)).run();\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { isPlainObject } from "../../../internal/validators/isPlainObject.js";
|
|
2
|
-
import { readRecordValue } from "../../recordReaders.js";
|
|
2
|
+
import { readRecordValue } from "../../shared/recordReaders.js";
|
|
3
3
|
function isStringArray(value) {
|
|
4
4
|
return (Array.isArray(value) && value.every((item) => typeof item === "string"));
|
|
5
5
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentDiscoveryCandidate.js","sourceRoot":"","sources":["documentDiscoveryCandidate.ts"],"names":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,OAAO;YACjB,KAAK,KAAK,MAAM;YAChB,KAAK,KAAK,OAAO,CAAC;QACpB,aAAa,CAAC,eAAe,CAAC,KAAK,EAAE,oBAAoB,CAAC,CAAC;QAC3D,aAAa,CAAC,eAAe,CAAC,KAAK,EAAE,oBAAoB,CAAC,CAAC,CAC5D,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,4BAA4B,CAC1C,IAAY;IAEZ,MAAM,KAAK,GAAY,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACxC,IAAI,CAAC,6BAA6B,CAAC,KAAK,CAAC;QACvC,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;IACpE,4EAA4E;IAC5E,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { isPlainObject } from \"@tearleads/validators/isPlainObject\";\nimport type { DiscoveredDocumentInput } from \"../../documents/documentSummary\";\nimport { readRecordValue } from \"../../shared/recordReaders\";\n\nexport interface DiscoveredDocumentCandidate extends DiscoveredDocumentInput {\n readonly listedContainerIds: readonly string[];\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return (\n Array.isArray(value) && value.every((item) => typeof item === \"string\")\n );\n}\n\nexport function isDiscoveredDocumentCandidate(\n value: unknown,\n): value is DiscoveredDocumentCandidate {\n if (!isPlainObject(value)) return false;\n const level = readRecordValue(value, \"effectiveAccessLevel\");\n const hash = readRecordValue(value, \"accessStateHash\");\n const epoch = readRecordValue(value, \"accessEpoch\");\n return (\n typeof readRecordValue(value, \"documentId\") === \"string\" &&\n typeof readRecordValue(value, \"containerId\") === \"string\" &&\n typeof readRecordValue(value, \"createdAt\") === \"string\" &&\n typeof epoch === \"number\" &&\n Number.isSafeInteger(epoch) &&\n epoch > 0 &&\n (hash === undefined || hash === null || typeof hash === \"string\") &&\n (level === undefined ||\n level === \"admin\" ||\n level === \"read\" ||\n level === \"write\") &&\n isStringArray(readRecordValue(value, \"linkedContainerIds\")) &&\n isStringArray(readRecordValue(value, \"listedContainerIds\"))\n );\n}\n\nexport function readStoredDiscoveryCandidate(\n json: string,\n): DiscoveredDocumentCandidate {\n const value: unknown = JSON.parse(json);\n if (!isDiscoveredDocumentCandidate(value))\n throw new Error(\"Stored document discovery candidate is invalid\");\n // Preserve property order: acknowledgements compare the exact stored input.\n return value;\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { and, asc, eq, inArray, lte, min, sql } from "drizzle-orm";
|
|
2
2
|
import { uniqueSortedStrings } from "../../documents/shared/readers.js";
|
|
3
|
-
import { readStringArray } from "../../recordReaders.js";
|
|
3
|
+
import { readStringArray } from "../../shared/recordReaders.js";
|
|
4
4
|
import { documentDiscoveryHeads, documentDiscoverySequence, pendingDocumentDiscoveries, } from "../../sqlite/documentDiscoveryEvidenceSchema.js";
|
|
5
5
|
import { accessManifestCheckpoints, documentContainerProjectionTables, } from "../../sqlite/schema.js";
|
|
6
6
|
import { getClientSQLitePersistenceRuntime } from "../../sqlite/sqlitePersistenceRuntime.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentDiscoveryEvidencePersistence.js","sourceRoot":"","sources":["documentDiscoveryEvidencePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AACnE,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EACL,sBAAsB,EACtB,yBAAyB,EACzB,0BAA0B,GAC3B,MAAM,8CAA8C,CAAC;AACtD,OAAO,EACL,yBAAyB,EACzB,iCAAiC,GAClC,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAC1F,OAAO,EAEL,eAAe,EACf,wBAAwB,GACzB,MAAM,wBAAwB,CAAC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Ac,CAAC;YAChD,GAAG,EAAE,GAAG;YACR,QAAQ,EAAE,GAAG,CAAC,KAAK,CAAC,WAAW,EAAE,IAAI,CAAC,WAAW,CAAC;SACnD,CAAC;aACD,GAAG,EAAE,CAAC;IACX,CAAC;AACH,CAAC;AAED,MAAM,UAAU,oCAAoC,CAClD,OAAgB,EAChB,GAAG,GAAG,IAAI,CAAC,GAAG;IAEd,OAAO,IAAI,iCAAiC,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AAC7D,CAAC","sourcesContent":["import { and, asc, eq, inArray, lte, min, sql } from \"drizzle-orm\";\nimport { uniqueSortedStrings } from \"../../documents/shared/readers\";\nimport { readStringArray } from \"../../recordReaders\";\nimport {\n documentDiscoveryHeads,\n documentDiscoverySequence,\n pendingDocumentDiscoveries,\n} from \"../../sqlite/documentDiscoveryEvidenceSchema\";\nimport {\n accessManifestCheckpoints,\n documentContainerProjectionTables,\n} from \"../../sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../sqlite/sqlSchema\";\nimport { loadDocumentPurgeCheckpoint } from \"../documentPurgeCheckpointPersistence\";\nimport { heldTombstoneRetryDelayMs } from \"./containerDocumentTombstoneHoldsPersistence\";\n\nimport {\n type DiscoveredDocumentCandidate,\n isDiscoveredDocumentCandidate,\n readStoredDiscoveryCandidate,\n} from \"./documentDiscoveryCandidate\";\n\nimport { isDocumentDiscoveryGenerationCurrent } from \"./documentDiscoveryReset\";\n\nexport type { DiscoveredDocumentCandidate } from \"./documentDiscoveryCandidate\";\nexport interface CachedDiscoveryHead {\n readonly organizationId: string | null;\n readonly accessEpoch: number;\n readonly accessStateHash?: string;\n readonly linkedContainerIds: readonly string[];\n}\ninterface RemovedDiscoveryPlacement {\n readonly containerId: string;\n readonly documentId: string;\n}\nexport interface DocumentDiscoveryEvidenceStore {\n begin(): Promise<number>;\n isCurrent(generation: number): Promise<boolean>;\n stage(\n inputs: readonly DiscoveredDocumentCandidate[],\n generation: number,\n removed?: readonly RemovedDiscoveryPlacement[],\n ): Promise<boolean>;\n pending(\n containerIds: readonly string[],\n limit: number,\n ): Promise<readonly DiscoveredDocumentCandidate[]>;\n defer(input: DiscoveredDocumentCandidate, generation: number): Promise<void>;\n acknowledge(\n inputs: readonly DiscoveredDocumentCandidate[],\n generation: number,\n ): Promise<void>;\n hasPending(containerIds: readonly string[]): Promise<boolean>;\n retryDelay(containerIds: readonly string[]): Promise<number | null>;\n loadHead(\n documentId: string,\n manifestHash: string | null | undefined,\n ): Promise<CachedDiscoveryHead | null>;\n saveHead(\n documentId: string,\n head: CachedDiscoveryHead,\n generation: number,\n ): Promise<boolean>;\n}\n\nconst pending = pendingDocumentDiscoveries;\nconst heads = documentDiscoveryHeads;\nconst ID_BATCH_SIZE = 400;\nconst batches = (ids: readonly string[]) =>\n Array.from({ length: Math.ceil(ids.length / ID_BATCH_SIZE) }, (_, i) =>\n ids.slice(i * ID_BATCH_SIZE, (i + 1) * ID_BATCH_SIZE),\n );\nconst identity = (input: DiscoveredDocumentCandidate) =>\n and(\n eq(pending.containerId, input.containerId),\n eq(pending.documentId, input.documentId),\n eq(pending.inputJson, JSON.stringify(input)),\n );\n\nclass SqlDocumentDiscoveryEvidenceStore\n implements DocumentDiscoveryEvidenceStore\n{\n constructor(\n private readonly execSql: ExecSql,\n private readonly now: () => number,\n ) {}\n\n private read = async () => {\n await ensureSqlTables(this.execSql, documentContainerProjectionTables);\n return getClientSQLitePersistenceRuntime(this.execSql).db;\n };\n private write = async <T>(\n operation: (\n db: ReturnType<typeof getClientSQLitePersistenceRuntime>[\"db\"],\n ) => Promise<T>,\n ) =>\n runSerializedSqlMutation(this.execSql, async (locked) => {\n await ensureSqlTables(locked, documentContainerProjectionTables);\n return operation(getClientSQLitePersistenceRuntime(locked).db);\n });\n begin = async () => {\n let generation = 0;\n await this.write(async (db) => {\n const [row] = await db\n .insert(documentDiscoverySequence)\n .values({ id: \"requests\", generation: 1 })\n .onConflictDoUpdate({\n target: documentDiscoverySequence.id,\n set: {\n generation: sql`${documentDiscoverySequence.generation} + 1`,\n },\n })\n .returning({ generation: documentDiscoverySequence.generation });\n if (!row || !Number.isSafeInteger(row.generation))\n throw new Error(\"Document discovery generation is exhausted\");\n generation = row.generation;\n });\n return generation;\n };\n isCurrent = async (generation: number) =>\n isDocumentDiscoveryGenerationCurrent(await this.read(), generation);\n stage = (\n inputs: readonly DiscoveredDocumentCandidate[],\n generation: number,\n removed: readonly RemovedDiscoveryPlacement[] = [],\n ) => {\n return this.write(async (db) => {\n if (!(await isDocumentDiscoveryGenerationCurrent(db, generation)))\n return false;\n if (inputs.length === 0 && removed.length === 0) return true;\n await db.transaction(async (tx) => {\n for (const input of inputs) {\n if (!isDiscoveredDocumentCandidate(input)) continue;\n for (const containerId of input.listedContainerIds) {\n const rowInput = {\n ...input,\n containerId,\n listedContainerIds: [containerId],\n };\n const inputJson = JSON.stringify(rowInput);\n await tx\n .insert(pending)\n .values({\n containerId,\n documentId: input.documentId,\n accessEpoch: input.accessEpoch,\n generation,\n inputJson,\n retryAt: 0,\n })\n .onConflictDoUpdate({\n target: [pending.containerId, pending.documentId],\n set: {\n accessEpoch: input.accessEpoch,\n generation,\n inputJson,\n retryAt: sql`case when ${pending.inputJson} = ${inputJson} then ${pending.retryAt} else 0 end`,\n attempts: sql`case when ${pending.inputJson} = ${inputJson} then ${pending.attempts} else 0 end`,\n },\n setWhere: lte(pending.generation, generation),\n })\n .run();\n }\n }\n // These are untrusted, unapplied hints only. Removing an existing local\n // placement still requires the separate signed tombstone evidence gate.\n for (const row of removed) {\n await tx\n .delete(pending)\n .where(\n and(\n eq(pending.containerId, row.containerId),\n eq(pending.documentId, row.documentId),\n lte(pending.generation, generation),\n ),\n )\n .run();\n }\n });\n return true;\n });\n };\n pending = async (containerIds: readonly string[], limit: number) => {\n const db = await this.read();\n const result: DiscoveredDocumentCandidate[] = [];\n for (const batch of batches(containerIds)) {\n if (result.length >= limit) break;\n const rows = await db\n .select({ inputJson: pending.inputJson })\n .from(pending)\n .where(\n and(\n inArray(pending.containerId, [...batch]),\n lte(pending.retryAt, this.now()),\n ),\n )\n .orderBy(asc(pending.retryAt), asc(pending.documentId))\n .limit(limit - result.length);\n result.push(\n ...rows.map((row) => readStoredDiscoveryCandidate(row.inputJson)),\n );\n }\n return result;\n };\n defer = (input: DiscoveredDocumentCandidate, generation: number) =>\n this.write(async (db) => {\n if (!(await isDocumentDiscoveryGenerationCurrent(db, generation))) return;\n const [row] = await db\n .select({ attempts: pending.attempts })\n .from(pending)\n .where(identity(input))\n .limit(1);\n if (!row) return;\n const attempts = Math.min(row.attempts + 1, 8);\n await db\n .update(pending)\n .set({\n attempts,\n retryAt: this.now() + heldTombstoneRetryDelayMs(attempts),\n })\n .where(identity(input))\n .run();\n });\n acknowledge = (\n inputs: readonly DiscoveredDocumentCandidate[],\n generation: number,\n ) =>\n this.write(async (db) => {\n if (!(await isDocumentDiscoveryGenerationCurrent(db, generation))) return;\n await db.transaction(async (tx) => {\n for (const input of inputs)\n await tx.delete(pending).where(identity(input)).run();\n });\n });\n hasPending = async (containerIds: readonly string[]) => {\n const db = await this.read();\n for (const batch of batches(containerIds)) {\n if (\n (\n await db\n .select({ documentId: pending.documentId })\n .from(pending)\n .where(inArray(pending.containerId, [...batch]))\n .limit(1)\n ).length\n )\n return true;\n }\n return false;\n };\n retryDelay = async (containerIds: readonly string[]) => {\n const db = await this.read();\n let due: number | null = null;\n for (const batch of batches(containerIds)) {\n const [row] = await db\n .select({ due: min(pending.retryAt) })\n .from(pending)\n .where(inArray(pending.containerId, [...batch]));\n if (row?.due !== null && row?.due !== undefined)\n due = Math.min(due ?? row.due, row.due);\n }\n return due === null ? null : Math.max(0, due - this.now());\n };\n loadHead = async (\n documentId: string,\n manifestHash: string | null | undefined,\n ) => {\n if (await loadDocumentPurgeCheckpoint(this.execSql, documentId))\n return {\n organizationId: null,\n accessEpoch: Number.MAX_SAFE_INTEGER,\n linkedContainerIds: [],\n };\n if (!manifestHash) return null;\n const db = await this.read();\n const [row] = await db\n .select()\n .from(heads)\n .where(\n and(\n eq(heads.documentId, documentId),\n eq(heads.manifestHash, manifestHash),\n ),\n )\n .limit(1);\n if (!row) return null;\n // A different verifier (for example tombstone removal) can advance the\n // signed checkpoint without updating documents.accessEpoch or this cache.\n // Old-organization pins survive recovery; only the cached signed head's\n // organization can authorize reuse. Missing pins require full verification.\n const checkpoints = await db\n .select()\n .from(accessManifestCheckpoints)\n .where(\n and(\n eq(accessManifestCheckpoints.objectKind, \"document\"),\n eq(accessManifestCheckpoints.objectId, documentId),\n eq(accessManifestCheckpoints.organizationId, row.organizationId),\n ),\n )\n .limit(1);\n if (\n checkpoints.length !== 1 ||\n checkpoints[0]?.manifestHash !== row.manifestHash ||\n checkpoints[0]?.epoch !== row.accessEpoch\n )\n return null;\n return {\n organizationId: row.organizationId,\n accessEpoch: row.accessEpoch,\n accessStateHash: row.manifestHash,\n linkedContainerIds: readStringArray(\n JSON.parse(row.linksJson),\n \"stored discovery links\",\n ),\n };\n };\n saveHead = (\n documentId: string,\n head: CachedDiscoveryHead,\n generation: number,\n ) =>\n this.write(async (db) => {\n if (\n !head.accessStateHash ||\n !head.organizationId ||\n !(await isDocumentDiscoveryGenerationCurrent(db, generation))\n )\n return false;\n const row = {\n documentId,\n organizationId: head.organizationId,\n manifestHash: head.accessStateHash,\n accessEpoch: head.accessEpoch,\n linksJson: JSON.stringify(head.linkedContainerIds),\n };\n await db\n .insert(heads)\n .values(row)\n .onConflictDoUpdate({\n target: [heads.documentId, heads.organizationId],\n set: row,\n setWhere: lte(heads.accessEpoch, head.accessEpoch),\n })\n .run();\n return true;\n });\n}\n\n/**\n * A document head this client signed, already checked against the server's\n * create acknowledgement and pinned as its access-manifest checkpoint in the\n * same transaction. It is the same signed head a discovery projection would\n * verify, so it seeds the exact-head cache; `loadHead` still reuses it only\n * while that checkpoint matches.\n */\nexport interface AuthoredDiscoveryHead {\n readonly documentId: string;\n readonly organizationId: string;\n readonly accessEpoch: number;\n readonly accessStateHash: string;\n readonly linkedContainerIds: readonly string[];\n}\n\n/** Writes authored heads inside the caller's serialized write transaction. */\nexport async function primeAuthoredDocumentDiscoveryHeads(\n execSql: ExecSql,\n authored: readonly AuthoredDiscoveryHead[],\n): Promise<void> {\n const db = getClientSQLitePersistenceRuntime(execSql).db;\n for (const head of authored) {\n const row = {\n documentId: head.documentId,\n organizationId: head.organizationId,\n manifestHash: head.accessStateHash,\n accessEpoch: head.accessEpoch,\n linksJson: JSON.stringify(uniqueSortedStrings(head.linkedContainerIds)),\n };\n await db\n .insert(heads)\n .values(row)\n .onConflictDoUpdate({\n target: [heads.documentId, heads.organizationId],\n set: row,\n setWhere: lte(heads.accessEpoch, head.accessEpoch),\n })\n .run();\n }\n}\n\nexport function createDocumentDiscoveryEvidenceStore(\n execSql: ExecSql,\n now = Date.now,\n): DocumentDiscoveryEvidenceStore {\n return new SqlDocumentDiscoveryEvidenceStore(execSql, now);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"documentDiscoveryEvidencePersistence.js","sourceRoot":"","sources":["documentDiscoveryEvidencePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AACnE,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EACL,sBAAsB,EACtB,yBAAyB,EACzB,0BAA0B,GAC3B,MAAM,8CAA8C,CAAC;AACtD,OAAO,EACL,yBAAyB,EACzB,iCAAiC,GAClC,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAC1F,OAAO,EAEL,eAAe,EACf,wBAAwB,GAC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U,EAAE,KAAK,CAAC,cAAc,CAAC;YAChD,GAAG,EAAE,GAAG;YACR,QAAQ,EAAE,GAAG,CAAC,KAAK,CAAC,WAAW,EAAE,IAAI,CAAC,WAAW,CAAC;SACnD,CAAC;aACD,GAAG,EAAE,CAAC;IACX,CAAC;AACH,CAAC;AAED,MAAM,UAAU,oCAAoC,CAClD,OAAgB,EAChB,GAAG,GAAG,IAAI,CAAC,GAAG;IAEd,OAAO,IAAI,iCAAiC,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AAC7D,CAAC","sourcesContent":["import { and, asc, eq, inArray, lte, min, sql } from \"drizzle-orm\";\nimport { uniqueSortedStrings } from \"../../documents/shared/readers\";\nimport { readStringArray } from \"../../shared/recordReaders\";\nimport {\n documentDiscoveryHeads,\n documentDiscoverySequence,\n pendingDocumentDiscoveries,\n} from \"../../sqlite/documentDiscoveryEvidenceSchema\";\nimport {\n accessManifestCheckpoints,\n documentContainerProjectionTables,\n} from \"../../sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../sqlite/sqlSchema\";\nimport { loadDocumentPurgeCheckpoint } from \"../documentPurgeCheckpointPersistence\";\nimport { heldTombstoneRetryDelayMs } from \"./containerDocumentTombstoneHoldsPersistence\";\n\nimport {\n type DiscoveredDocumentCandidate,\n isDiscoveredDocumentCandidate,\n readStoredDiscoveryCandidate,\n} from \"./documentDiscoveryCandidate\";\n\nimport { isDocumentDiscoveryGenerationCurrent } from \"./documentDiscoveryReset\";\n\nexport type { DiscoveredDocumentCandidate } from \"./documentDiscoveryCandidate\";\nexport interface CachedDiscoveryHead {\n readonly organizationId: string | null;\n readonly accessEpoch: number;\n readonly accessStateHash?: string;\n readonly linkedContainerIds: readonly string[];\n}\ninterface RemovedDiscoveryPlacement {\n readonly containerId: string;\n readonly documentId: string;\n}\nexport interface DocumentDiscoveryEvidenceStore {\n begin(): Promise<number>;\n isCurrent(generation: number): Promise<boolean>;\n stage(\n inputs: readonly DiscoveredDocumentCandidate[],\n generation: number,\n removed?: readonly RemovedDiscoveryPlacement[],\n ): Promise<boolean>;\n pending(\n containerIds: readonly string[],\n limit: number,\n ): Promise<readonly DiscoveredDocumentCandidate[]>;\n defer(input: DiscoveredDocumentCandidate, generation: number): Promise<void>;\n acknowledge(\n inputs: readonly DiscoveredDocumentCandidate[],\n generation: number,\n ): Promise<void>;\n hasPending(containerIds: readonly string[]): Promise<boolean>;\n retryDelay(containerIds: readonly string[]): Promise<number | null>;\n loadHead(\n documentId: string,\n manifestHash: string | null | undefined,\n ): Promise<CachedDiscoveryHead | null>;\n saveHead(\n documentId: string,\n head: CachedDiscoveryHead,\n generation: number,\n ): Promise<boolean>;\n}\n\nconst pending = pendingDocumentDiscoveries;\nconst heads = documentDiscoveryHeads;\nconst ID_BATCH_SIZE = 400;\nconst batches = (ids: readonly string[]) =>\n Array.from({ length: Math.ceil(ids.length / ID_BATCH_SIZE) }, (_, i) =>\n ids.slice(i * ID_BATCH_SIZE, (i + 1) * ID_BATCH_SIZE),\n );\nconst identity = (input: DiscoveredDocumentCandidate) =>\n and(\n eq(pending.containerId, input.containerId),\n eq(pending.documentId, input.documentId),\n eq(pending.inputJson, JSON.stringify(input)),\n );\n\nclass SqlDocumentDiscoveryEvidenceStore\n implements DocumentDiscoveryEvidenceStore\n{\n constructor(\n private readonly execSql: ExecSql,\n private readonly now: () => number,\n ) {}\n\n private read = async () => {\n await ensureSqlTables(this.execSql, documentContainerProjectionTables);\n return getClientSQLitePersistenceRuntime(this.execSql).db;\n };\n private write = async <T>(\n operation: (\n db: ReturnType<typeof getClientSQLitePersistenceRuntime>[\"db\"],\n ) => Promise<T>,\n ) =>\n runSerializedSqlMutation(this.execSql, async (locked) => {\n await ensureSqlTables(locked, documentContainerProjectionTables);\n return operation(getClientSQLitePersistenceRuntime(locked).db);\n });\n begin = async () => {\n let generation = 0;\n await this.write(async (db) => {\n const [row] = await db\n .insert(documentDiscoverySequence)\n .values({ id: \"requests\", generation: 1 })\n .onConflictDoUpdate({\n target: documentDiscoverySequence.id,\n set: {\n generation: sql`${documentDiscoverySequence.generation} + 1`,\n },\n })\n .returning({ generation: documentDiscoverySequence.generation });\n if (!row || !Number.isSafeInteger(row.generation))\n throw new Error(\"Document discovery generation is exhausted\");\n generation = row.generation;\n });\n return generation;\n };\n isCurrent = async (generation: number) =>\n isDocumentDiscoveryGenerationCurrent(await this.read(), generation);\n stage = (\n inputs: readonly DiscoveredDocumentCandidate[],\n generation: number,\n removed: readonly RemovedDiscoveryPlacement[] = [],\n ) => {\n return this.write(async (db) => {\n if (!(await isDocumentDiscoveryGenerationCurrent(db, generation)))\n return false;\n if (inputs.length === 0 && removed.length === 0) return true;\n await db.transaction(async (tx) => {\n for (const input of inputs) {\n if (!isDiscoveredDocumentCandidate(input)) continue;\n for (const containerId of input.listedContainerIds) {\n const rowInput = {\n ...input,\n containerId,\n listedContainerIds: [containerId],\n };\n const inputJson = JSON.stringify(rowInput);\n await tx\n .insert(pending)\n .values({\n containerId,\n documentId: input.documentId,\n accessEpoch: input.accessEpoch,\n generation,\n inputJson,\n retryAt: 0,\n })\n .onConflictDoUpdate({\n target: [pending.containerId, pending.documentId],\n set: {\n accessEpoch: input.accessEpoch,\n generation,\n inputJson,\n retryAt: sql`case when ${pending.inputJson} = ${inputJson} then ${pending.retryAt} else 0 end`,\n attempts: sql`case when ${pending.inputJson} = ${inputJson} then ${pending.attempts} else 0 end`,\n },\n setWhere: lte(pending.generation, generation),\n })\n .run();\n }\n }\n // These are untrusted, unapplied hints only. Removing an existing local\n // placement still requires the separate signed tombstone evidence gate.\n for (const row of removed) {\n await tx\n .delete(pending)\n .where(\n and(\n eq(pending.containerId, row.containerId),\n eq(pending.documentId, row.documentId),\n lte(pending.generation, generation),\n ),\n )\n .run();\n }\n });\n return true;\n });\n };\n pending = async (containerIds: readonly string[], limit: number) => {\n const db = await this.read();\n const result: DiscoveredDocumentCandidate[] = [];\n for (const batch of batches(containerIds)) {\n if (result.length >= limit) break;\n const rows = await db\n .select({ inputJson: pending.inputJson })\n .from(pending)\n .where(\n and(\n inArray(pending.containerId, [...batch]),\n lte(pending.retryAt, this.now()),\n ),\n )\n .orderBy(asc(pending.retryAt), asc(pending.documentId))\n .limit(limit - result.length);\n result.push(\n ...rows.map((row) => readStoredDiscoveryCandidate(row.inputJson)),\n );\n }\n return result;\n };\n defer = (input: DiscoveredDocumentCandidate, generation: number) =>\n this.write(async (db) => {\n if (!(await isDocumentDiscoveryGenerationCurrent(db, generation))) return;\n const [row] = await db\n .select({ attempts: pending.attempts })\n .from(pending)\n .where(identity(input))\n .limit(1);\n if (!row) return;\n const attempts = Math.min(row.attempts + 1, 8);\n await db\n .update(pending)\n .set({\n attempts,\n retryAt: this.now() + heldTombstoneRetryDelayMs(attempts),\n })\n .where(identity(input))\n .run();\n });\n acknowledge = (\n inputs: readonly DiscoveredDocumentCandidate[],\n generation: number,\n ) =>\n this.write(async (db) => {\n if (!(await isDocumentDiscoveryGenerationCurrent(db, generation))) return;\n await db.transaction(async (tx) => {\n for (const input of inputs)\n await tx.delete(pending).where(identity(input)).run();\n });\n });\n hasPending = async (containerIds: readonly string[]) => {\n const db = await this.read();\n for (const batch of batches(containerIds)) {\n if (\n (\n await db\n .select({ documentId: pending.documentId })\n .from(pending)\n .where(inArray(pending.containerId, [...batch]))\n .limit(1)\n ).length\n )\n return true;\n }\n return false;\n };\n retryDelay = async (containerIds: readonly string[]) => {\n const db = await this.read();\n let due: number | null = null;\n for (const batch of batches(containerIds)) {\n const [row] = await db\n .select({ due: min(pending.retryAt) })\n .from(pending)\n .where(inArray(pending.containerId, [...batch]));\n if (row?.due !== null && row?.due !== undefined)\n due = Math.min(due ?? row.due, row.due);\n }\n return due === null ? null : Math.max(0, due - this.now());\n };\n loadHead = async (\n documentId: string,\n manifestHash: string | null | undefined,\n ) => {\n if (await loadDocumentPurgeCheckpoint(this.execSql, documentId))\n return {\n organizationId: null,\n accessEpoch: Number.MAX_SAFE_INTEGER,\n linkedContainerIds: [],\n };\n if (!manifestHash) return null;\n const db = await this.read();\n const [row] = await db\n .select()\n .from(heads)\n .where(\n and(\n eq(heads.documentId, documentId),\n eq(heads.manifestHash, manifestHash),\n ),\n )\n .limit(1);\n if (!row) return null;\n // A different verifier (for example tombstone removal) can advance the\n // signed checkpoint without updating documents.accessEpoch or this cache.\n // Old-organization pins survive recovery; only the cached signed head's\n // organization can authorize reuse. Missing pins require full verification.\n const checkpoints = await db\n .select()\n .from(accessManifestCheckpoints)\n .where(\n and(\n eq(accessManifestCheckpoints.objectKind, \"document\"),\n eq(accessManifestCheckpoints.objectId, documentId),\n eq(accessManifestCheckpoints.organizationId, row.organizationId),\n ),\n )\n .limit(1);\n if (\n checkpoints.length !== 1 ||\n checkpoints[0]?.manifestHash !== row.manifestHash ||\n checkpoints[0]?.epoch !== row.accessEpoch\n )\n return null;\n return {\n organizationId: row.organizationId,\n accessEpoch: row.accessEpoch,\n accessStateHash: row.manifestHash,\n linkedContainerIds: readStringArray(\n JSON.parse(row.linksJson),\n \"stored discovery links\",\n ),\n };\n };\n saveHead = (\n documentId: string,\n head: CachedDiscoveryHead,\n generation: number,\n ) =>\n this.write(async (db) => {\n if (\n !head.accessStateHash ||\n !head.organizationId ||\n !(await isDocumentDiscoveryGenerationCurrent(db, generation))\n )\n return false;\n const row = {\n documentId,\n organizationId: head.organizationId,\n manifestHash: head.accessStateHash,\n accessEpoch: head.accessEpoch,\n linksJson: JSON.stringify(head.linkedContainerIds),\n };\n await db\n .insert(heads)\n .values(row)\n .onConflictDoUpdate({\n target: [heads.documentId, heads.organizationId],\n set: row,\n setWhere: lte(heads.accessEpoch, head.accessEpoch),\n })\n .run();\n return true;\n });\n}\n\n/**\n * A document head this client signed, already checked against the server's\n * create acknowledgement and pinned as its access-manifest checkpoint in the\n * same transaction. It is the same signed head a discovery projection would\n * verify, so it seeds the exact-head cache; `loadHead` still reuses it only\n * while that checkpoint matches.\n */\nexport interface AuthoredDiscoveryHead {\n readonly documentId: string;\n readonly organizationId: string;\n readonly accessEpoch: number;\n readonly accessStateHash: string;\n readonly linkedContainerIds: readonly string[];\n}\n\n/** Writes authored heads inside the caller's serialized write transaction. */\nexport async function primeAuthoredDocumentDiscoveryHeads(\n execSql: ExecSql,\n authored: readonly AuthoredDiscoveryHead[],\n): Promise<void> {\n const db = getClientSQLitePersistenceRuntime(execSql).db;\n for (const head of authored) {\n const row = {\n documentId: head.documentId,\n organizationId: head.organizationId,\n manifestHash: head.accessStateHash,\n accessEpoch: head.accessEpoch,\n linksJson: JSON.stringify(uniqueSortedStrings(head.linkedContainerIds)),\n };\n await db\n .insert(heads)\n .values(row)\n .onConflictDoUpdate({\n target: [heads.documentId, heads.organizationId],\n set: row,\n setWhere: lte(heads.accessEpoch, head.accessEpoch),\n })\n .run();\n }\n}\n\nexport function createDocumentDiscoveryEvidenceStore(\n execSql: ExecSql,\n now = Date.now,\n): DocumentDiscoveryEvidenceStore {\n return new SqlDocumentDiscoveryEvidenceStore(execSql, now);\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { and, eq } from "drizzle-orm";
|
|
2
|
-
import { normalizeEffectiveAccessLevel } from "../../../accessLevel.js";
|
|
3
2
|
import { DEFAULT_DOCUMENT_KIND } from "../../../documents/documentConstants.js";
|
|
4
3
|
import { deriveStoredDocumentTitle, getUntitledDocumentTitle, } from "../../../documents/documentKinds.js";
|
|
4
|
+
import { normalizeEffectiveAccessLevel } from "../../../keying/accessLevel.js";
|
|
5
5
|
import { documentProjection, documents } from "../../../sqlite/schema.js";
|
|
6
6
|
import { DOCUMENTS_APP_KIND } from "./constants.js";
|
|
7
7
|
// Deliberately excludes the projected text (`documentProjectionText`): the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentProjectionRows.js","sourceRoot":"","sources":["documentProjectionRows.ts"],"names":[],"mappings":"AAAA,OAAO,EAA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AAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,yBAAyB,CAAC,GAAG,EAAE,IAAI,IAAI,EAAE,CAAC,CAAC;AACpD,CAAC;AAED,MAAM,UAAU,sBAAsB,CACpC,GAAoD;IAEpD,OAAO,GAAG,EAAE,SAAS,IAAI,EAAE,CAAC;AAC9B,CAAC","sourcesContent":["import { and, eq } from \"drizzle-orm\";\nimport { DEFAULT_DOCUMENT_KIND } from \"../../../documents/documentConstants\";\nimport {\n deriveStoredDocumentTitle,\n getUntitledDocumentTitle,\n type StoredDocumentKind,\n} from \"../../../documents/documentKinds\";\nimport type { DocumentSummary } from \"../../../documents/documentSummary\";\nimport { normalizeEffectiveAccessLevel } from \"../../../keying/accessLevel\";\nimport { documentProjection, documents } from \"../../../sqlite/schema\";\nimport type { StoredDocumentRecord } from \"../types\";\nimport { DOCUMENTS_APP_KIND } from \"./constants\";\n\ninterface SelectedDocumentProjection {\n localId: string | null;\n documentId: string | null;\n containerId: string | null;\n documentKind: StoredDocumentKind;\n title: string;\n updatedAt: string;\n accessStateHash: string | null;\n effectiveAccessLevel: string | null;\n}\n\ninterface SelectedDocumentProjectionDetail {\n text: string | null;\n containerId: string | null;\n documentKind: StoredDocumentKind;\n title: string;\n}\n\ninterface SelectedDocumentProjectionTimestamp {\n documentKind?: StoredDocumentKind;\n text?: string | null;\n title?: string;\n updatedAt: string;\n}\n\n// Deliberately excludes the projected text (`documentProjectionText`): the\n// title fallback is derived at write time, so summary listings never need to\n// haul content-sized values through the worker.\nexport const documentSummarySelection = {\n localId: documentProjection.localId,\n documentId: documentProjection.documentId,\n containerId: documentProjection.containerId,\n documentKind: documentProjection.documentKind,\n title: documentProjection.title,\n updatedAt: documentProjection.updatedAt,\n accessStateHash: documents.accessStateHash,\n effectiveAccessLevel: documents.effectiveAccessLevel,\n};\n\nexport const documentSummaryJoin = and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n eq(documents.localId, documentProjection.localId),\n);\n\nexport function mapDocumentSummary(\n row: SelectedDocumentProjection,\n): DocumentSummary {\n return {\n accessStateHash: row.accessStateHash,\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n row.effectiveAccessLevel,\n ),\n id: row.localId ?? \"\",\n containerId: row.containerId,\n documentKind: row.documentKind,\n documentId: row.documentId,\n title: getProjectionTitle(row),\n updatedAt: row.updatedAt,\n };\n}\n\nexport function toDocumentSummary(\n record: StoredDocumentRecord,\n updatedAt: string,\n): DocumentSummary {\n return {\n accessStateHash: record.accessStateHash ?? null,\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n record.effectiveAccessLevel,\n ),\n id: record.id,\n containerId: record.containerId,\n documentKind: record.documentKind ?? DEFAULT_DOCUMENT_KIND,\n documentId: record.documentId,\n title: record.title ?? deriveStoredDocumentTitle(record.text),\n updatedAt,\n };\n}\n\nexport function getProjectionText(\n row:\n | SelectedDocumentProjectionDetail\n | SelectedDocumentProjectionTimestamp\n | undefined,\n): string {\n return row?.text ?? \"\";\n}\n\nexport function getProjectionContainerId(\n row: SelectedDocumentProjectionDetail | undefined,\n): string | null {\n return row?.containerId ?? null;\n}\n\nexport function getProjectionDocumentKind(\n row:\n | SelectedDocumentProjectionDetail\n | SelectedDocumentProjectionTimestamp\n | undefined,\n): StoredDocumentKind {\n return row?.documentKind ?? DEFAULT_DOCUMENT_KIND;\n}\n\nexport function getProjectionTitle(\n row:\n | SelectedDocumentProjectionDetail\n | SelectedDocumentProjectionTimestamp\n | undefined,\n): string {\n const title = row?.title ?? \"\";\n if (\n title.length > 0 &&\n title !== getUntitledDocumentTitle(DEFAULT_DOCUMENT_KIND)\n ) {\n return title;\n }\n\n return deriveStoredDocumentTitle(row?.text ?? \"\");\n}\n\nexport function getProjectionUpdatedAt(\n row: SelectedDocumentProjectionTimestamp | undefined,\n): string {\n return row?.updatedAt ?? \"\";\n}\n"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { and, eq, lte } from "drizzle-orm";
|
|
2
|
-
import { normalizeEffectiveAccessLevel } from "../../../accessLevel.js";
|
|
3
2
|
import { DEFAULT_DOCUMENT_KIND } from "../../../documents/documentConstants.js";
|
|
4
3
|
import { deriveStoredDocumentTitle } from "../../../documents/documentKinds.js";
|
|
5
4
|
import { serializeDocumentSyncPullContinuation } from "../../../documents/shared/pullContinuation.js";
|
|
5
|
+
import { normalizeEffectiveAccessLevel } from "../../../keying/accessLevel.js";
|
|
6
6
|
import { documentProjection, documentProjectionText, documents, } from "../../../sqlite/schema.js";
|
|
7
7
|
import { getClientSQLitePersistenceRuntime, } from "../../../sqlite/sqlitePersistenceRuntime.js";
|
|
8
8
|
import { DOCUMENTS_APP_KIND } from "./constants.js";
|