@tearleads/client-sdk 0.1.225 → 0.1.226
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/client/organizations/principalContainerMutations.js.map +1 -1
- package/client/organizations/recipientAdmission.js +1 -1
- package/client/organizations/recipientAdmission.js.map +1 -1
- package/client/organizations/rosterAdmissionEvidence.js +1 -1
- package/client/organizations/rosterAdmissionEvidence.js.map +1 -1
- package/data/containers/shared/authorAccess.d.ts +1 -1
- package/data/containers/shared/authorAccess.js.map +1 -1
- package/data/containers/shared/heldContainerHeads.js.map +1 -1
- package/data/containers/shared/principalPolicies.js.map +1 -1
- package/data/containers/shared/types.d.ts +1 -1
- package/data/containers/shared/types.js.map +1 -1
- package/data/keyingProjectionVerification/checkpoints/accessManifestCheckpointEnforcement.js.map +1 -1
- package/data/keyingProjectionVerification/checkpoints/checkpointContext.d.ts +1 -1
- package/data/keyingProjectionVerification/checkpoints/checkpointContext.js.map +1 -1
- package/data/keyingProjectionVerification/container/containerProjectionVerification.d.ts +1 -1
- package/data/keyingProjectionVerification/container/containerProjectionVerification.js.map +1 -1
- package/data/keyingProjectionVerification/documentPurge/documentPurgePrincipalEvidence.js +1 -1
- package/data/keyingProjectionVerification/documentPurge/documentPurgePrincipalEvidence.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicy/mergeProjectionPolicyEvidence.js +1 -1
- package/data/keyingProjectionVerification/principalPolicy/mergeProjectionPolicyEvidence.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js +2 -2
- package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicy/principalPolicySigners.js +2 -2
- package/data/keyingProjectionVerification/principalPolicy/principalPolicySigners.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.d.ts +1 -1
- package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js +4 -4
- package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js.map +1 -1
- package/data/keyingProjectionVerification/types.d.ts +1 -1
- package/data/keyingProjectionVerification/types.js.map +1 -1
- package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js +1 -1
- package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js.map +1 -1
- package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js +1 -1
- package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js.map +1 -1
- package/data/persistence/keyingCheckpoints/organizationReplacementCheckpointPersistence.js +1 -1
- package/data/persistence/keyingCheckpoints/organizationReplacementCheckpointPersistence.js.map +1 -1
- package/data/persistence/organizationFounderPersistence.js +1 -1
- package/data/persistence/organizationFounderPersistence.js.map +1 -1
- package/data/persistence/principalCurrentAcknowledgementPersistence.js +1 -1
- package/data/persistence/principalCurrentAcknowledgementPersistence.js.map +1 -1
- package/data/persistence/principalPolicy/heldPrincipalState.js +1 -1
- package/data/persistence/principalPolicy/heldPrincipalState.js.map +1 -1
- package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js +1 -1
- package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js.map +1 -1
- package/data/persistence/principalPolicy/principalPolicyBundleRepository.js.map +1 -1
- package/data/persistence/principalPolicy/principalPolicyReferenceCheckpoint.js +1 -1
- package/data/persistence/principalPolicy/principalPolicyReferenceCheckpoint.js.map +1 -1
- package/data/persistence/principalPolicy/principalPolicyReferenceIndexPersistence.js +1 -1
- package/data/persistence/principalPolicy/principalPolicyReferenceIndexPersistence.js.map +1 -1
- package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js +1 -1
- package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js.map +1 -1
- package/data/principals/organizationGroupRoles.js +1 -1
- package/data/principals/organizationGroupRoles.js.map +1 -1
- package/package.json +1 -1
- package/workflows/containers/child/create/index.js.map +1 -1
- package/workflows/containers/child/move/moveRequest.js.map +1 -1
- package/workflows/containers/child/move/moveWraps.js.map +1 -1
- package/workflows/containers/child/mutationRequestCore.js.map +1 -1
- package/workflows/containers/child/mutationSubmit.d.ts +1 -1
- package/workflows/containers/child/mutationSubmit.js.map +1 -1
- package/workflows/containers/child/recitePlan.js.map +1 -1
- package/workflows/containers/child/rekey/carriedDescendantRekeys.d.ts +1 -1
- package/workflows/containers/child/rekey/carriedDescendantRekeys.js.map +1 -1
- package/workflows/containers/child/rekey/index.d.ts +1 -1
- package/workflows/containers/child/rekey/index.js.map +1 -1
- package/workflows/containers/child/revoke.d.ts +1 -1
- package/workflows/containers/child/revoke.js.map +1 -1
- package/workflows/containers/child/rotation/replacementPrincipalPolicyReferences.js.map +1 -1
- package/workflows/containers/child/rotation/rotationPrincipalPolicies.js.map +1 -1
- package/workflows/containers/child/rotation/rotationWraps.js.map +1 -1
- package/workflows/containers/child/share/sharePlanCore.d.ts +1 -1
- package/workflows/containers/child/share/sharePlanCore.js.map +1 -1
- package/workflows/containers/rematerialization/authoredPrincipalPolicyWarmer.js +1 -1
- package/workflows/containers/rematerialization/authoredPrincipalPolicyWarmer.js.map +1 -1
- package/workflows/containers/rematerialization/principalContainerRematerializationPlanning.js.map +1 -1
- package/workflows/containers/rematerialization/principalContainerRematerializationTargets.js.map +1 -1
- package/workflows/documents/linkSet/linkSetAuthority.js.map +1 -1
- package/workflows/organizations/currentOrganizationAuthority.d.ts +1 -1
- package/workflows/organizations/currentOrganizationAuthority.js +1 -1
- package/workflows/organizations/currentOrganizationAuthority.js.map +1 -1
- package/workflows/organizations/groupMetadata/currentGroupMetadataAuthority.js +1 -1
- package/workflows/organizations/groupMetadata/currentGroupMetadataAuthority.js.map +1 -1
- package/workflows/organizations/groupMetadata/groupMetadataBinding.js.map +1 -1
- package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js +2 -2
- package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js.map +1 -1
- package/workflows/organizations/groupMetadata/groupMetadataRootBinding.js +2 -2
- package/workflows/organizations/groupMetadata/groupMetadataRootBinding.js.map +1 -1
- package/workflows/organizations/groupNames/groupNameUniqueness.js +2 -2
- package/workflows/organizations/groupNames/groupNameUniqueness.js.map +1 -1
- package/workflows/organizations/groupNames/organizationGroupNamePolicies.js +2 -2
- package/workflows/organizations/groupNames/organizationGroupNamePolicies.js.map +1 -1
- package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js +1 -1
- package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js.map +1 -1
- package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js +1 -1
- package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js.map +1 -1
- package/workflows/organizations/groupPolicy/groupPolicyRequests.js +1 -1
- package/workflows/organizations/groupPolicy/groupPolicyRequests.js.map +1 -1
- package/workflows/organizations/groupPolicy/groupPolicyVerification.js +1 -1
- package/workflows/organizations/groupPolicy/groupPolicyVerification.js.map +1 -1
- package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js +1 -1
- package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js.map +1 -1
- package/workflows/organizations/groupShare/sharePrincipalPolicy.js +2 -2
- package/workflows/organizations/groupShare/sharePrincipalPolicy.js.map +1 -1
- package/workflows/organizations/groups/createCurrentOrganizationGroup.js +1 -1
- package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
- package/workflows/organizations/groups/organizationGroupDirectory.js +1 -1
- package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
- package/workflows/organizations/memberships/leaveRequestMembersEvidence.js +1 -1
- package/workflows/organizations/memberships/leaveRequestMembersEvidence.js.map +1 -1
- package/workflows/organizations/policyHistory/organizationPolicyHistoryDetails.js.map +1 -1
- package/workflows/organizations/policyHistory/organizationPolicyHistoryVerification.js +1 -1
- package/workflows/organizations/policyHistory/organizationPolicyHistoryVerification.js.map +1 -1
- package/workflows/organizations/principalMutations/acknowledgedDirectoryBindings.js +1 -1
- package/workflows/organizations/principalMutations/acknowledgedDirectoryBindings.js.map +1 -1
- package/workflows/organizations/principalMutations/currentOrganizationMutationAuthority.js +1 -1
- package/workflows/organizations/principalMutations/currentOrganizationMutationAuthority.js.map +1 -1
- package/workflows/organizations/principalMutations/currentOrganizationMutationRetention.js +1 -1
- package/workflows/organizations/principalMutations/currentOrganizationMutationRetention.js.map +1 -1
- package/workflows/organizations/principalMutations/runtimeCurrentGroupMutation.js +1 -1
- package/workflows/organizations/principalMutations/runtimeCurrentGroupMutation.js.map +1 -1
- package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js +1 -1
- package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js.map +1 -1
- package/workflows/organizations/principalPolicy/principalPolicyRecipients.js +1 -1
- package/workflows/organizations/principalPolicy/principalPolicyRecipients.js.map +1 -1
- package/workflows/organizations/principalPolicy/principalPolicyRequest.js +1 -1
- package/workflows/organizations/principalPolicy/principalPolicyRequest.js.map +1 -1
- package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js +2 -2
- package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js.map +1 -1
- package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js +1 -1
- package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js.map +1 -1
- package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js +1 -1
- package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js.map +1 -1
- package/workflows/principals/externalAdminPolicy.d.ts +1 -1
- package/workflows/principals/externalAdminPolicy.js +2 -2
- package/workflows/principals/externalAdminPolicy.js.map +1 -1
- package/workflows/principals/historyRecovery/principalHistoryRecoveryAuthority.js +1 -1
- package/workflows/principals/historyRecovery/principalHistoryRecoveryAuthority.js.map +1 -1
- package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js +1 -1
- package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js.map +1 -1
- package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js +1 -1
- package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js.map +1 -1
- package/workflows/principals/historyRecovery/recoverScopedPrincipalPolicyHistory.js +1 -1
- package/workflows/principals/historyRecovery/recoverScopedPrincipalPolicyHistory.js.map +1 -1
- package/workflows/principals/policyCache/index.js +1 -1
- package/workflows/principals/policyCache/index.js.map +1 -1
- package/workflows/principals/policyCache/principalPolicyCacheValidation.js +1 -1
- package/workflows/principals/policyCache/principalPolicyCacheValidation.js.map +1 -1
- package/workflows/principals/policyCache/principalPolicyOrganizationScope.js +2 -2
- package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -1
- package/workflows/principals/policyVerification.js +1 -1
- package/workflows/principals/policyVerification.js.map +1 -1
- package/workflows/principals/principalPolicyService.js +1 -1
- package/workflows/principals/principalPolicyService.js.map +1 -1
- package/workflows/principals/publicHistory/publicPrincipalHistoryAuthority.js +1 -1
- package/workflows/principals/publicHistory/publicPrincipalHistoryAuthority.js.map +1 -1
- package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js +1 -1
- package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js.map +1 -1
- package/workflows/principals/publicHistory/publicProjectionDirectory.js +1 -1
- package/workflows/principals/publicHistory/publicProjectionDirectory.js.map +1 -1
- package/workflows/principals/publicHistory/publicProjectionPrincipal.js +1 -1
- package/workflows/principals/publicHistory/publicProjectionPrincipal.js.map +1 -1
- package/workflows/principals/publicHistory/recoverProjectionPolicyHistory.js +1 -1
- package/workflows/principals/publicHistory/recoverProjectionPolicyHistory.js.map +1 -1
- package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js +2 -2
- package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js.map +1 -1
- package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js +1 -1
- package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js.map +1 -1
- package/workflows/principals/recoveryOperation/principalRecoveryDirectory.d.ts +1 -1
- package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js +1 -1
- package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js.map +1 -1
- package/workflows/principals/recoveryOperation/principalRecoveryLocalPreference.js +1 -1
- package/workflows/principals/recoveryOperation/principalRecoveryLocalPreference.js.map +1 -1
- package/workflows/principals/recoveryOperation/principalRecoveryMemo.js +1 -1
- package/workflows/principals/recoveryOperation/principalRecoveryMemo.js.map +1 -1
- package/workflows/registration/organizationProvisioning.js +2 -2
- package/workflows/registration/organizationProvisioning.js.map +1 -1
- package/workflows/registration/provisionedPrincipalHistory.js +1 -1
- package/workflows/registration/provisionedPrincipalHistory.js.map +1 -1
- package/workflows/registration/registrationAccessHeadPersistence.js +1 -1
- package/workflows/registration/registrationAccessHeadPersistence.js.map +1 -1
- /package/data/persistence/{principalKeys → principalContracts}/principalGrantRetirementPersistence.js +0 -0
- /package/data/persistence/{principalKeys → principalContracts}/principalGrantRetirementPersistence.js.map +0 -0
- /package/data/{principals → principalContracts}/organizationAuthorityDescriptor.d.ts +0 -0
- /package/data/{principals → principalContracts}/organizationAuthorityDescriptor.js +0 -0
- /package/data/{principals → principalContracts}/organizationAuthorityDescriptor.js.map +0 -0
- /package/data/{principals → principalContracts}/principalIdentityCommitments.js +0 -0
- /package/data/{principals → principalContracts}/principalIdentityCommitments.js.map +0 -0
- /package/data/{principals → principalContracts}/principalPolicyAdminSigners.js +0 -0
- /package/data/{principals → principalContracts}/principalPolicyAdminSigners.js.map +0 -0
- /package/data/{principals → principalContracts}/principalPolicyEvidence.d.ts +0 -0
- /package/data/{principals → principalContracts}/principalPolicyEvidence.js +0 -0
- /package/data/{principals → principalContracts}/principalPolicyEvidence.js.map +0 -0
- /package/data/{principals → principalContracts}/principalPolicyStates.js +0 -0
- /package/data/{principals → principalContracts}/principalPolicyStates.js.map +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalPolicyCacheValidation.js","sourceRoot":"","sources":["principalPolicyCacheValidation.ts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B;gBAC5D,MAAM,EAAE,KAAK,CAAC,MAAM;gBACpB,iBAAiB,EAAE,KAAK,CAAC,SAAS;gBAClC,eAAe,EAAE,KAAK,CAAC,eAAe;gBACtC,gBAAgB,EAAE,gBAAgB,CAAC,gBAAgB;aACpD,CAAC,EACF,CAAC;gBACD,MAAM,IAAI,oCAAoC,CAC5C,6CAA6C,CAC9C,CAAC;YACJ,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC;QACD,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,gBAAgB,EAAE,gBAAgB,CAAC,gBAAgB;KACpD,CAAC,CAAC;IACL,IAAI,CAAC,QAAQ,CAAC,EAAE;QAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAC,KAAK,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;IAC9D,OAAO;QACL,mBAAmB,EAAE,uBAAuB;YAC1C,CAAC,CAAC,MAAM,KAAK,CAAC,uBAAuB,EAAE;YACvC,CAAC,CAAC,IAAI;QACR,EAAE,EAAE,IAAI;QACR,MAAM,EAAE,QAAQ,CAAC,KAAK;KACvB,CAAC;AACJ,CAAC","sourcesContent":["import {\n type KeyingVerificationCode,\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport {\n externalAuthorityCouldAuthorize,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../../data/principals/principalPolicyAdminSigners\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { VerifiedExternalAdminPolicy } from \"../externalAdminPolicy\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n type PrincipalPolicySignerPublicKeyLoadErrorCode,\n principalPolicyStates,\n} from \"../policyVerification\";\n\ninterface PrincipalPolicyValidationFailure {\n readonly code: KeyingVerificationCode;\n readonly message: string;\n}\n\nfunction getBundleReferenceFailure(\n reference: ReferencedPrincipalStateResponse,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n const states = principalPolicyStates(bundle);\n const hasReferencedPrincipal = states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId,\n );\n if (!hasReferencedPrincipal) {\n return {\n code: \"object_mismatch\",\n message: \"bundle principal does not match referenced principal\",\n };\n }\n if (\n !states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId &&\n state.version === reference.version &&\n state.keyEpoch === reference.keyEpoch &&\n state.stateHash === reference.stateHash &&\n state.keyFingerprint === reference.keyFingerprint,\n )\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"bundle chain does not contain referenced principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.principalType !==\n bundle.currentState.principalType ||\n bundle.currentMemberEnvelopes.principalId !==\n bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"member envelope principal does not match current principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.stateHash !== bundle.currentState.stateHash\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope state hash does not match current principal\",\n };\n }\n if (bundle.currentMemberEnvelopes.epoch !== bundle.currentState.keyEpoch) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope epoch does not match current principal\",\n };\n }\n if (\n bundle.currentPayload.principalType !== bundle.currentState.principalType ||\n bundle.currentPayload.principalId !== bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"payload principal does not match current principal\",\n };\n }\n if (bundle.currentPayload.stateHash !== bundle.currentState.stateHash) {\n return {\n code: \"hash_mismatch\",\n message: \"payload state hash does not match current principal\",\n };\n }\n return null;\n}\n\nfunction getCheckpointFailure(\n checkpoint: PrincipalPolicyCheckpoint | null,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n if (!checkpoint) {\n return null;\n }\n const current = bundle.currentState;\n if (current.version < checkpoint.version) {\n return {\n code: \"rollback\",\n message: \"principal policy state is older than the local checkpoint\",\n };\n }\n if (\n current.version === checkpoint.version &&\n current.stateHash !== checkpoint.stateHash\n ) {\n return {\n code: \"equivocation\",\n message: \"principal policy state conflicts with the local checkpoint\",\n };\n }\n if (current.version === checkpoint.version) {\n return null;\n }\n const checkpointState = principalPolicyStates(bundle).find(\n (state) => state.version === checkpoint.version,\n );\n return checkpointState?.stateHash === checkpoint.stateHash\n ? null\n : {\n code: \"stale_predecessor\",\n message: \"principal policy chain does not extend the local checkpoint\",\n };\n}\n\nfunction signerPublicKeyLoadFailure(\n code: PrincipalPolicySignerPublicKeyLoadErrorCode,\n): PrincipalPolicyValidationFailure {\n switch (code) {\n case \"fingerprint-mismatch\":\n return {\n code: \"signer_mismatch\",\n message: \"signer key fingerprint does not match state signer\",\n };\n case \"not-found\":\n // The identity source throws for transport failures, so an absent\n // signer here is the server asserting the cited user does not exist.\n return {\n code: \"missing_dependency\",\n message: \"signer identity is unknown to the server\",\n };\n }\n}\n\nfunction verificationError(\n failure: PrincipalPolicyValidationFailure,\n): KeyingVerificationError {\n return new KeyingVerificationError(failure.code, failure.message);\n}\n\nexport async function validatePrincipalPolicyBundleForCache(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>;\n readonly localCheckpoint: PrincipalPolicyCheckpoint | null;\n readonly reference: ReferencedPrincipalStateResponse;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** The cache operation's lifetime, checked inside every pin write. */\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<\n | {\n readonly externalAdminPolicy: VerifiedExternalAdminPolicy | null;\n readonly ok: true;\n readonly policy: VerifiedPrincipalPolicy;\n }\n | { readonly error: KeyingVerificationError; readonly ok: false }\n> {\n const referenceFailure = getBundleReferenceFailure(\n input.reference,\n input.bundle,\n );\n if (referenceFailure) {\n return { error: verificationError(referenceFailure), ok: false };\n }\n const checkpointFailure = getCheckpointFailure(\n input.localCheckpoint,\n input.bundle,\n );\n if (checkpointFailure) {\n return { error: verificationError(checkpointFailure), ok: false };\n }\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: input.bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n return {\n error: verificationError(\n signerPublicKeyLoadFailure(signerPublicKeys.error),\n ),\n ok: false,\n };\n }\n\n let usedExternalAdminPolicy = false;\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle: input.bundle,\n expectedReference: input.reference,\n loadExternalAuthority: async () => {\n usedExternalAdminPolicy = true;\n const authority = (await input.loadExternalAdminPolicy())\n ?.externalAuthority;\n if (authority) return authority;\n // The loader returns null when the organization's Admins policy could\n // not be fetched, and an honest server always serves it. When that\n // evidence is all the chain lacks, the gap is availability, not a\n // refused signer, so it must not surface as an incident. A chain no\n // evidence could authorize keeps its unauthorized refusal.\n if (\n await externalAuthorityCouldAuthorize({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n bundle: input.bundle,\n expectedReference: input.reference,\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n })\n ) {\n throw new ProjectionDependencyUnavailableError(\n \"Organization Admins evidence is unavailable\",\n );\n }\n return null;\n },\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) return { error: verified.error, ok: false };\n return {\n externalAdminPolicy: usedExternalAdminPolicy\n ? await input.loadExternalAdminPolicy()\n : null,\n ok: true,\n policy: verified.value,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"principalPolicyCacheValidation.js","sourceRoot":"","sources":["principalPolicyCacheValidation.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,G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pB,iBAAiB,EAAE,KAAK,CAAC,SAAS;gBAClC,eAAe,EAAE,KAAK,CAAC,eAAe;gBACtC,gBAAgB,EAAE,gBAAgB,CAAC,gBAAgB;aACpD,CAAC,EACF,CAAC;gBACD,MAAM,IAAI,oCAAoC,CAC5C,6CAA6C,CAC9C,CAAC;YACJ,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC;QACD,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,gBAAgB,EAAE,gBAAgB,CAAC,gBAAgB;KACpD,CAAC,CAAC;IACL,IAAI,CAAC,QAAQ,CAAC,EAAE;QAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAC,KAAK,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;IAC9D,OAAO;QACL,mBAAmB,EAAE,uBAAuB;YAC1C,CAAC,CAAC,MAAM,KAAK,CAAC,uBAAuB,EAAE;YACvC,CAAC,CAAC,IAAI;QACR,EAAE,EAAE,IAAI;QACR,MAAM,EAAE,QAAQ,CAAC,KAAK;KACvB,CAAC;AACJ,CAAC","sourcesContent":["import {\n type KeyingVerificationCode,\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport {\n externalAuthorityCouldAuthorize,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { VerifiedExternalAdminPolicy } from \"../externalAdminPolicy\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n type PrincipalPolicySignerPublicKeyLoadErrorCode,\n principalPolicyStates,\n} from \"../policyVerification\";\n\ninterface PrincipalPolicyValidationFailure {\n readonly code: KeyingVerificationCode;\n readonly message: string;\n}\n\nfunction getBundleReferenceFailure(\n reference: ReferencedPrincipalStateResponse,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n const states = principalPolicyStates(bundle);\n const hasReferencedPrincipal = states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId,\n );\n if (!hasReferencedPrincipal) {\n return {\n code: \"object_mismatch\",\n message: \"bundle principal does not match referenced principal\",\n };\n }\n if (\n !states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId &&\n state.version === reference.version &&\n state.keyEpoch === reference.keyEpoch &&\n state.stateHash === reference.stateHash &&\n state.keyFingerprint === reference.keyFingerprint,\n )\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"bundle chain does not contain referenced principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.principalType !==\n bundle.currentState.principalType ||\n bundle.currentMemberEnvelopes.principalId !==\n bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"member envelope principal does not match current principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.stateHash !== bundle.currentState.stateHash\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope state hash does not match current principal\",\n };\n }\n if (bundle.currentMemberEnvelopes.epoch !== bundle.currentState.keyEpoch) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope epoch does not match current principal\",\n };\n }\n if (\n bundle.currentPayload.principalType !== bundle.currentState.principalType ||\n bundle.currentPayload.principalId !== bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"payload principal does not match current principal\",\n };\n }\n if (bundle.currentPayload.stateHash !== bundle.currentState.stateHash) {\n return {\n code: \"hash_mismatch\",\n message: \"payload state hash does not match current principal\",\n };\n }\n return null;\n}\n\nfunction getCheckpointFailure(\n checkpoint: PrincipalPolicyCheckpoint | null,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n if (!checkpoint) {\n return null;\n }\n const current = bundle.currentState;\n if (current.version < checkpoint.version) {\n return {\n code: \"rollback\",\n message: \"principal policy state is older than the local checkpoint\",\n };\n }\n if (\n current.version === checkpoint.version &&\n current.stateHash !== checkpoint.stateHash\n ) {\n return {\n code: \"equivocation\",\n message: \"principal policy state conflicts with the local checkpoint\",\n };\n }\n if (current.version === checkpoint.version) {\n return null;\n }\n const checkpointState = principalPolicyStates(bundle).find(\n (state) => state.version === checkpoint.version,\n );\n return checkpointState?.stateHash === checkpoint.stateHash\n ? null\n : {\n code: \"stale_predecessor\",\n message: \"principal policy chain does not extend the local checkpoint\",\n };\n}\n\nfunction signerPublicKeyLoadFailure(\n code: PrincipalPolicySignerPublicKeyLoadErrorCode,\n): PrincipalPolicyValidationFailure {\n switch (code) {\n case \"fingerprint-mismatch\":\n return {\n code: \"signer_mismatch\",\n message: \"signer key fingerprint does not match state signer\",\n };\n case \"not-found\":\n // The identity source throws for transport failures, so an absent\n // signer here is the server asserting the cited user does not exist.\n return {\n code: \"missing_dependency\",\n message: \"signer identity is unknown to the server\",\n };\n }\n}\n\nfunction verificationError(\n failure: PrincipalPolicyValidationFailure,\n): KeyingVerificationError {\n return new KeyingVerificationError(failure.code, failure.message);\n}\n\nexport async function validatePrincipalPolicyBundleForCache(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>;\n readonly localCheckpoint: PrincipalPolicyCheckpoint | null;\n readonly reference: ReferencedPrincipalStateResponse;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** The cache operation's lifetime, checked inside every pin write. */\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<\n | {\n readonly externalAdminPolicy: VerifiedExternalAdminPolicy | null;\n readonly ok: true;\n readonly policy: VerifiedPrincipalPolicy;\n }\n | { readonly error: KeyingVerificationError; readonly ok: false }\n> {\n const referenceFailure = getBundleReferenceFailure(\n input.reference,\n input.bundle,\n );\n if (referenceFailure) {\n return { error: verificationError(referenceFailure), ok: false };\n }\n const checkpointFailure = getCheckpointFailure(\n input.localCheckpoint,\n input.bundle,\n );\n if (checkpointFailure) {\n return { error: verificationError(checkpointFailure), ok: false };\n }\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: input.bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n return {\n error: verificationError(\n signerPublicKeyLoadFailure(signerPublicKeys.error),\n ),\n ok: false,\n };\n }\n\n let usedExternalAdminPolicy = false;\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle: input.bundle,\n expectedReference: input.reference,\n loadExternalAuthority: async () => {\n usedExternalAdminPolicy = true;\n const authority = (await input.loadExternalAdminPolicy())\n ?.externalAuthority;\n if (authority) return authority;\n // The loader returns null when the organization's Admins policy could\n // not be fetched, and an honest server always serves it. When that\n // evidence is all the chain lacks, the gap is availability, not a\n // refused signer, so it must not surface as an incident. A chain no\n // evidence could authorize keeps its unauthorized refusal.\n if (\n await externalAuthorityCouldAuthorize({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n bundle: input.bundle,\n expectedReference: input.reference,\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n })\n ) {\n throw new ProjectionDependencyUnavailableError(\n \"Organization Admins evidence is unavailable\",\n );\n }\n return null;\n },\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) return { error: verified.error, ok: false };\n return {\n externalAdminPolicy: usedExternalAdminPolicy\n ? await input.loadExternalAdminPolicy()\n : null,\n ok: true,\n policy: verified.value,\n };\n}\n"]}
|
|
@@ -2,8 +2,8 @@ import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
|
|
|
2
2
|
import { principalPolicyHeadMeetsCheckpoint } from "../../../data/keyingProjectionVerification/index.js";
|
|
3
3
|
import { KeyingCheckpointRepository } from "../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
|
|
4
4
|
import { PrincipalPolicyBundleRepository } from "../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
|
|
5
|
-
import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, } from "../../../data/
|
|
6
|
-
import { verifyOrganizationAdminPolicy } from "../../../data/
|
|
5
|
+
import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
|
|
6
|
+
import { verifyOrganizationAdminPolicy } from "../../../data/principalContracts/principalPolicyAdminSigners.js";
|
|
7
7
|
import { collectPrincipalPolicySignerPublicKeys, publishVerifiedPrincipalPolicy, } from "../policyVerification.js";
|
|
8
8
|
export function directoryBindsGroupReference(directory, policy, reference) {
|
|
9
9
|
const head = directory?.descriptor.groupHeads.find((head) => head.principalId === reference.principalId);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalPolicyOrganizationScope.js","sourceRoot":"","sources":["principalPolicyOrganizationScope.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,kCAAkC,EAAE,MAAM,4CAA4C,CAAC;AAChG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAEL,oCAAoC,EACpC,6BAA6B,GAC9B,MAAM,
|
|
1
|
+
{"version":3,"file":"principalPolicyOrganizationScope.js","sourceRoot":"","sources":["principalPolicyOrganizationScope.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,kCAAkC,EAAE,MAAM,4CAA4C,CAAC;AAChG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EA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AE,KAAK,CAAC,YAAY;SACjC,CAAC,CAAC;QACH,IAAI,UAA2C,CAAC;QAChD,IAAI,CAAC;YACH,UAAU,GAAG,oCAAoC,CAC/C,MAAM,CAAC,cAAc,CAAC,UAAU,CACjC,CAAC;QACJ,CAAC;QAAC,MAAM,CAAC;YACP,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,2CAA2C,CAC5C,CAAC;QACJ,CAAC;QACD,IAAI,UAAU,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;YACpD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,6CAA6C,CAC9C,CAAC;QACJ,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,KAAK,EAAE,UAAU,EAAE,CAAC;IACxD,CAAC,CAAC;IACF,OAAO,CAAC,MAAM,EAAE,EAAE;QAChB,IAAI,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAC/B,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;YACvB,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAC5B,CAAC;QACD,OAAO,OAAO,CAAC;IACjB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { principalPolicyHeadMeetsCheckpoint } from \"../../../data/keyingProjectionVerification\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n type OrganizationAuthorityDescriptor,\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport { verifyOrganizationAdminPolicy } from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"../currentPrincipalPolicyReader\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n publishVerifiedPrincipalPolicy,\n} from \"../policyVerification\";\n\nexport interface VerifiedPolicyDirectory {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n readonly descriptor: OrganizationAuthorityDescriptor;\n}\n\nexport type PolicyDirectoryLoader = (\n remote: boolean,\n) => Promise<VerifiedPolicyDirectory | null>;\n\nexport function directoryBindsGroupReference(\n directory: VerifiedPolicyDirectory | null,\n policy: VerifiedPrincipalPolicy,\n reference: ReferencedPrincipalHead,\n): boolean {\n const head = directory?.descriptor.groupHeads.find(\n (head) => head.principalId === reference.principalId,\n );\n // A newer directory head authenticates its verified predecessors too.\n // Requiring equality with a historical manifest citation bricks old reads.\n return (\n !!head &&\n head.version >= reference.version &&\n head.version === policy.version &&\n [policy.state, ...(policy.history ?? []).map((entry) => entry.state)].some(\n (state) => principalHeadMatchesReference(state, head),\n )\n );\n}\n\ntype StoredPolicyBundle = PrincipalPolicyBundleResponse | null;\n\nfunction bundleMeetingCheckpoint(\n bundle: StoredPolicyBundle,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): StoredPolicyBundle {\n return bundle &&\n principalPolicyHeadMeetsCheckpoint(bundle.currentState, checkpoint)\n ? bundle\n : null;\n}\n\nfunction assertSignerFingerprintMatches(error: string): void {\n if (error === \"fingerprint-mismatch\")\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"organization directory signer fingerprint does not match\",\n );\n}\n\nexport function createPolicyDirectoryLoader(input: {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): PolicyDirectoryLoader {\n const memo = new Map<boolean, Promise<VerifiedPolicyDirectory | null>>();\n const load = async (\n remote: boolean,\n ): Promise<VerifiedPolicyDirectory | null> => {\n const checkpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\"organization\", input.organizationId);\n let bundle = remote\n ? null\n : await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundle(\"organization\", input.organizationId);\n bundle = bundleMeetingCheckpoint(bundle, checkpoint);\n bundle ??= await input.currentPolicyReader.getCurrentPrincipalPolicy(\n \"organization\",\n input.organizationId,\n );\n if (!bundle) return null;\n const signers = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signers) {\n assertSignerFingerprintMatches(signers.error);\n return null;\n }\n const verified = await verifyOrganizationAdminPolicy({\n bundle,\n localCheckpoint: checkpoint,\n organizationId: input.organizationId,\n signerPublicKeys: signers.signerPublicKeys,\n });\n if (!verified.ok) throw verified.error;\n await publishVerifiedPrincipalPolicy({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n let descriptor: OrganizationAuthorityDescriptor;\n try {\n descriptor = parseOrganizationAuthorityDescriptor(\n bundle.currentPayload.ciphertext,\n );\n } catch {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"organization directory payload is invalid\",\n );\n }\n if (descriptor.organizationId !== input.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"organization directory scope does not match\",\n );\n return { bundle, policy: verified.value, descriptor };\n };\n return (remote) => {\n let pending = memo.get(remote);\n if (!pending) {\n pending = load(remote);\n memo.set(remote, pending);\n }\n return pending;\n };\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { computeUserIdentityBundleFingerprint, } from "../../internal/crypto/index.js";
|
|
2
2
|
import { assertProjectionVerificationCurrent } from "../../data/keyingProjectionVerification/types.js";
|
|
3
|
-
import { publishVerifiedPolicyBundle, withUnauthenticatedPolicyIdentities, } from "../../data/
|
|
3
|
+
import { publishVerifiedPolicyBundle, withUnauthenticatedPolicyIdentities, } from "../../data/principalContracts/principalIdentityCommitments.js";
|
|
4
4
|
import { requireTrustedUserIdentityResolver, } from "../../data/trustedUserIdentity/index.js";
|
|
5
5
|
export function principalPolicyStates(bundle) {
|
|
6
6
|
return [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"policyVerification.js","sourceRoot":"","sources":["policyVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,GAGrC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EACL,2BAA2B,EAC3B,mCAAmC,GACpC,MAAM,oDAAoD,CAAC;AAC5D,OAAO,EACL,kCAAkC,GAGnC,MAAM,gCAAgC,CAAC;AAMxC,MAAM,UAAU,qBAAqB,CACnC,MAGC;IAED,OAAO;QACL,GAAG,MAAM,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC;QACpD,MAAM,CAAC,YAAY;KACpB,CAAC;AACJ,CAAC;AAED,SAAS,cAAc,CAAC,KAGvB;IACC,OAAO,GAAG,KAAK,CAAC,YAAY,IAAI,KAAK,CAAC,kBAAkB,EAAE,CAAC;AAC7D,CAAC;AAED,0EAA0E;AAC1E,MAAM,iBAAiB;IACA;IAArB,YAAqB,IAAiD;QAAjD,SAAI,GAAJ,IAAI,CAA6C;IAAG,CAAC;CAC3E;AAUD,KAAK,UAAU,iBAAiB,CAAC,KAGhC;IACC,MAAM,SAAS,GAAG,MAAM,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;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E,OAAO,CAAC,0BAA0B;QAC9D,aAAa,EAAE,GAAG,EAAE,CAAC,mCAAmC,CAAC,YAAY,CAAC;KACvE,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n computeUserIdentityBundleFingerprint,\n type PrincipalPolicySignerPublicKey,\n type PrincipalProjectionMember,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport {\n publishVerifiedPolicyBundle,\n withUnauthenticatedPolicyIdentities,\n} from \"../../data/principals/principalIdentityCommitments\";\nimport {\n requireTrustedUserIdentityResolver,\n type StagedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n} from \"../../data/trustedUserIdentity\";\n\nexport type PrincipalPolicySignerPublicKeyLoadErrorCode =\n | \"fingerprint-mismatch\"\n | \"not-found\";\n\nexport function principalPolicyStates(\n bundle: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"previousStates\"\n >,\n): PrincipalPolicyBundleResponse[\"currentState\"][] {\n return [\n ...bundle.previousStates.map((entry) => entry.state),\n bundle.currentState,\n ];\n}\n\nfunction signerCacheKey(input: {\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n}): string {\n return `${input.signerUserId}:${input.signingFingerprint}`;\n}\n\n/** A signer refusal ends collection before any commitment is compared. */\nclass SignerLoadRefusal {\n constructor(readonly code: PrincipalPolicySignerPublicKeyLoadErrorCode) {}\n}\n\ninterface TrustedSigner {\n readonly identity: NonNullable<\n Awaited<ReturnType<StagedUserIdentityResolver>>\n >;\n readonly publicKey: PrincipalPolicySignerPublicKey;\n bundleFingerprint?: Promise<string>;\n}\n\nasync function loadTrustedSigner(input: {\n readonly resolve: StagedUserIdentityResolver;\n readonly state: PrincipalPolicyBundleResponse[\"currentState\"];\n}): Promise<TrustedSigner> {\n const signerKey = await input.resolve(input.state.signerUserId);\n\n if (!signerKey) {\n throw new SignerLoadRefusal(\"not-found\");\n }\n\n if (\n signerKey.signingKeyFingerprint !== input.state.signerUserKeyFingerprint\n ) {\n throw new SignerLoadRefusal(\"fingerprint-mismatch\");\n }\n\n return {\n identity: signerKey,\n publicKey: {\n userId: input.state.signerUserId,\n signingKeyFingerprint: input.state.signerUserKeyFingerprint,\n signingPublicKey: signerKey.signingPublicKey,\n },\n };\n}\n\ntype SignedProjection = {\n readonly version: number;\n readonly stateHash: string;\n readonly projection: readonly PrincipalProjectionMember[];\n};\n\n/**\n * The signer's identity as its predecessor's signed projection committed it,\n * when the state links to that predecessor: an unlinked entry is left for the\n * chain verifier to refuse as disconnected.\n */\nfunction committedSignerBundle(\n state: PrincipalPolicyBundleResponse[\"currentState\"],\n predecessors: ReadonlyMap<number, SignedProjection>,\n): string | undefined {\n const predecessor = predecessors.get(state.version - 1);\n if (!predecessor || predecessor.stateHash !== state.prevStateHash)\n return undefined;\n return predecessor.projection.find(\n (member) => member.userId === state.signerUserId,\n )?.identityBundleFingerprint;\n}\n\nexport async function collectPrincipalPolicySignerPublicKeys(input: {\n readonly bundle: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"previousStates\" | \"currentProjection\"\n >;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /**\n * A paged history's last accepted state, which authorizes the page's first\n * signer by user ID: that signer must be the identity it committed.\n */\n readonly predecessor?: SignedProjection | null;\n}): Promise<\n | { readonly signerPublicKeys: PrincipalPolicySignerPublicKey[] }\n | { readonly error: PrincipalPolicySignerPublicKeyLoadErrorCode }\n> {\n const states = principalPolicyStates(input.bundle);\n const predecessors = new Map<number, SignedProjection>(\n [\n ...(input.predecessor ? [input.predecessor] : []),\n ...input.bundle.previousStates.map((entry) => ({\n version: entry.state.version,\n stateHash: entry.state.stateHash,\n projection: entry.projection,\n })),\n ].map((entry) => [entry.version, entry]),\n );\n try {\n // Signatures are checked after collection: first-sight signers and\n // members are compared, but only a verified selection pins them.\n return await withUnauthenticatedPolicyIdentities(\n {\n signerUserIds: states.map((state) => state.signerUserId),\n projections: [\n ...input.bundle.previousStates.map((entry) => entry.projection),\n input.bundle.currentProjection,\n ],\n resolveTrustedUserIdentity: requireTrustedUserIdentityResolver(\n input.resolveTrustedUserIdentity,\n ),\n },\n async (resolve) => {\n const signers = new Map<string, TrustedSigner>();\n for (const state of states) {\n const cacheKey = signerCacheKey({\n signerUserId: state.signerUserId,\n signingFingerprint: state.signerUserKeyFingerprint,\n });\n let signer = signers.get(cacheKey);\n if (!signer) {\n signer = await loadTrustedSigner({ resolve, state });\n signers.set(cacheKey, signer);\n }\n const committed = committedSignerBundle(state, predecessors);\n if (committed === undefined) continue;\n signer.bundleFingerprint ??= computeUserIdentityBundleFingerprint(\n signer.identity,\n );\n if ((await signer.bundleFingerprint) !== committed)\n throw new SignerLoadRefusal(\"fingerprint-mismatch\");\n }\n return {\n signerPublicKeys: Array.from(\n signers.values(),\n (signer) => signer.publicKey,\n ),\n };\n },\n );\n } catch (error) {\n if (error instanceof SignerLoadRefusal) return { error: error.code };\n throw error;\n }\n}\n\n/**\n * Pin the signers and members of a bundle the caller has just verified, so\n * the first sights signer collection staged become durable only now. Call it\n * after every successful verification of a collected bundle.\n */\nexport function publishVerifiedPrincipalPolicy(input: {\n readonly bundle: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"previousStates\" | \"currentProjection\"\n >;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly assertCurrent?: (() => void) | undefined;\n /** The operation's lifetime, checked inside every pin write. */\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<void> {\n const { stillCurrent } = input;\n return publishVerifiedPolicyBundle(\n input.bundle,\n requireTrustedUserIdentityResolver(input.resolveTrustedUserIdentity),\n input.assertCurrent ??\n (stillCurrent\n ? () => assertProjectionVerificationCurrent(stillCurrent)\n : undefined),\n );\n}\n\n/** Pin one recovery's just-verified current state, within its lifetime. */\nexport function publishVerifiedCurrent(\n options: { readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver },\n current: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"currentProjection\"\n >,\n stillCurrent: () => boolean,\n): Promise<void> {\n return publishVerifiedPrincipalPolicy({\n bundle: { ...current, previousStates: [] },\n resolveTrustedUserIdentity: options.resolveTrustedUserIdentity,\n assertCurrent: () => assertProjectionVerificationCurrent(stillCurrent),\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"policyVerification.js","sourceRoot":"","sources":["policyVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,GAGrC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EACL,2BAA2B,EAC3B,mCAAmC,GACpC,MAAM,4DAA4D,CAAC;AACpE,OAAO,EACL,kCAAkC,GAGnC,MAAM,gCAAgC,CAAC;AAMxC,MAAM,UAAU,qBAAqB,CACnC,MAGC;IAED,OAAO;QACL,GAAG,MAAM,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC;QACpD,MAAM,CAAC,YAAY;KACpB,CAAC;AACJ,CAAC;AAED,SAAS,cAAc,CAAC,KAGvB;IACC,OAAO,GAAG,KAAK,CAAC,YAAY,IAAI,KAAK,CAAC,kBAAkB,EAAE,CAAC;AAC7D,CAAC;AAED,0EAA0E;AAC1E,MAAM,iBAAiB;IACA;IAArB,YAAqB,IAAiD;QAAjD,SAAI,GAAJ,IAAI,CAA6C;IAAG,CAAC;CAC3E;AAUD,KAAK,UAAU,iBAAiB,CAAC,KAGhC;IACC,MAAM,SAAS,GAAG,MAAM,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IAEhE,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,MAAM,IAAI,iBAAiB,CAAC,WAAW,CAAC,CAAC;IAC3C,CAAC;IAED,IACE,SAAS,CAAC,qBAAqB,K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eUserIdentityBundleFingerprint,\n type PrincipalPolicySignerPublicKey,\n type PrincipalProjectionMember,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport {\n publishVerifiedPolicyBundle,\n withUnauthenticatedPolicyIdentities,\n} from \"../../data/principalContracts/principalIdentityCommitments\";\nimport {\n requireTrustedUserIdentityResolver,\n type StagedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n} from \"../../data/trustedUserIdentity\";\n\nexport type PrincipalPolicySignerPublicKeyLoadErrorCode =\n | \"fingerprint-mismatch\"\n | \"not-found\";\n\nexport function principalPolicyStates(\n bundle: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"previousStates\"\n >,\n): PrincipalPolicyBundleResponse[\"currentState\"][] {\n return [\n ...bundle.previousStates.map((entry) => entry.state),\n bundle.currentState,\n ];\n}\n\nfunction signerCacheKey(input: {\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n}): string {\n return `${input.signerUserId}:${input.signingFingerprint}`;\n}\n\n/** A signer refusal ends collection before any commitment is compared. */\nclass SignerLoadRefusal {\n constructor(readonly code: PrincipalPolicySignerPublicKeyLoadErrorCode) {}\n}\n\ninterface TrustedSigner {\n readonly identity: NonNullable<\n Awaited<ReturnType<StagedUserIdentityResolver>>\n >;\n readonly publicKey: PrincipalPolicySignerPublicKey;\n bundleFingerprint?: Promise<string>;\n}\n\nasync function loadTrustedSigner(input: {\n readonly resolve: StagedUserIdentityResolver;\n readonly state: PrincipalPolicyBundleResponse[\"currentState\"];\n}): Promise<TrustedSigner> {\n const signerKey = await input.resolve(input.state.signerUserId);\n\n if (!signerKey) {\n throw new SignerLoadRefusal(\"not-found\");\n }\n\n if (\n signerKey.signingKeyFingerprint !== input.state.signerUserKeyFingerprint\n ) {\n throw new SignerLoadRefusal(\"fingerprint-mismatch\");\n }\n\n return {\n identity: signerKey,\n publicKey: {\n userId: input.state.signerUserId,\n signingKeyFingerprint: input.state.signerUserKeyFingerprint,\n signingPublicKey: signerKey.signingPublicKey,\n },\n };\n}\n\ntype SignedProjection = {\n readonly version: number;\n readonly stateHash: string;\n readonly projection: readonly PrincipalProjectionMember[];\n};\n\n/**\n * The signer's identity as its predecessor's signed projection committed it,\n * when the state links to that predecessor: an unlinked entry is left for the\n * chain verifier to refuse as disconnected.\n */\nfunction committedSignerBundle(\n state: PrincipalPolicyBundleResponse[\"currentState\"],\n predecessors: ReadonlyMap<number, SignedProjection>,\n): string | undefined {\n const predecessor = predecessors.get(state.version - 1);\n if (!predecessor || predecessor.stateHash !== state.prevStateHash)\n return undefined;\n return predecessor.projection.find(\n (member) => member.userId === state.signerUserId,\n )?.identityBundleFingerprint;\n}\n\nexport async function collectPrincipalPolicySignerPublicKeys(input: {\n readonly bundle: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"previousStates\" | \"currentProjection\"\n >;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /**\n * A paged history's last accepted state, which authorizes the page's first\n * signer by user ID: that signer must be the identity it committed.\n */\n readonly predecessor?: SignedProjection | null;\n}): Promise<\n | { readonly signerPublicKeys: PrincipalPolicySignerPublicKey[] }\n | { readonly error: PrincipalPolicySignerPublicKeyLoadErrorCode }\n> {\n const states = principalPolicyStates(input.bundle);\n const predecessors = new Map<number, SignedProjection>(\n [\n ...(input.predecessor ? [input.predecessor] : []),\n ...input.bundle.previousStates.map((entry) => ({\n version: entry.state.version,\n stateHash: entry.state.stateHash,\n projection: entry.projection,\n })),\n ].map((entry) => [entry.version, entry]),\n );\n try {\n // Signatures are checked after collection: first-sight signers and\n // members are compared, but only a verified selection pins them.\n return await withUnauthenticatedPolicyIdentities(\n {\n signerUserIds: states.map((state) => state.signerUserId),\n projections: [\n ...input.bundle.previousStates.map((entry) => entry.projection),\n input.bundle.currentProjection,\n ],\n resolveTrustedUserIdentity: requireTrustedUserIdentityResolver(\n input.resolveTrustedUserIdentity,\n ),\n },\n async (resolve) => {\n const signers = new Map<string, TrustedSigner>();\n for (const state of states) {\n const cacheKey = signerCacheKey({\n signerUserId: state.signerUserId,\n signingFingerprint: state.signerUserKeyFingerprint,\n });\n let signer = signers.get(cacheKey);\n if (!signer) {\n signer = await loadTrustedSigner({ resolve, state });\n signers.set(cacheKey, signer);\n }\n const committed = committedSignerBundle(state, predecessors);\n if (committed === undefined) continue;\n signer.bundleFingerprint ??= computeUserIdentityBundleFingerprint(\n signer.identity,\n );\n if ((await signer.bundleFingerprint) !== committed)\n throw new SignerLoadRefusal(\"fingerprint-mismatch\");\n }\n return {\n signerPublicKeys: Array.from(\n signers.values(),\n (signer) => signer.publicKey,\n ),\n };\n },\n );\n } catch (error) {\n if (error instanceof SignerLoadRefusal) return { error: error.code };\n throw error;\n }\n}\n\n/**\n * Pin the signers and members of a bundle the caller has just verified, so\n * the first sights signer collection staged become durable only now. Call it\n * after every successful verification of a collected bundle.\n */\nexport function publishVerifiedPrincipalPolicy(input: {\n readonly bundle: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"previousStates\" | \"currentProjection\"\n >;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly assertCurrent?: (() => void) | undefined;\n /** The operation's lifetime, checked inside every pin write. */\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<void> {\n const { stillCurrent } = input;\n return publishVerifiedPolicyBundle(\n input.bundle,\n requireTrustedUserIdentityResolver(input.resolveTrustedUserIdentity),\n input.assertCurrent ??\n (stillCurrent\n ? () => assertProjectionVerificationCurrent(stillCurrent)\n : undefined),\n );\n}\n\n/** Pin one recovery's just-verified current state, within its lifetime. */\nexport function publishVerifiedCurrent(\n options: { readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver },\n current: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"currentProjection\"\n >,\n stillCurrent: () => boolean,\n): Promise<void> {\n return publishVerifiedPrincipalPolicy({\n bundle: { ...current, previousStates: [] },\n resolveTrustedUserIdentity: options.resolveTrustedUserIdentity,\n assertCurrent: () => assertProjectionVerificationCurrent(stillCurrent),\n });\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { rethrowKeyingVerificationError } from "../../data/keyingProjectionVerification/error.js";
|
|
2
2
|
import { assertProjectionVerificationCurrent, isProjectionVerificationCancelledError, } from "../../data/keyingProjectionVerification/types.js";
|
|
3
|
+
import { principalPolicyReferenceFromBundle } from "../../data/principalContracts/principalPolicyAdminSigners.js";
|
|
3
4
|
import { directoryHistoryProtection } from "../../data/principals/principalHistoryScopeProtection.js";
|
|
4
|
-
import { principalPolicyReferenceFromBundle } from "../../data/principals/principalPolicyAdminSigners.js";
|
|
5
5
|
import { ProjectionDependencyUnavailableError } from "../../data/shared/dependencyUnavailable.js";
|
|
6
6
|
import { errorMessage } from "../../data/shared/errorMessage.js";
|
|
7
7
|
import { apiPrincipalPolicyPageReader, } from "./principalPolicyHistoryReader.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalPolicyService.js","sourceRoot":"","sources":["principalPolicyService.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,8BAA8B,EAAE,MAAM,+CAA+C,CAAC;AAC/F,OAAO,EACL,mCAAmC,EACnC,sCAAsC,GAEvC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,0BAA0B,EAAE,MAAM,uDAAuD,CAAC;AACnG,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AACvG,OAAO,EAAE,oCAAoC,EAAE,MAAM,yCAAyC,CAAC;AAC/F,OAAO,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAG9D,OAAO,EACL,4BAA4B,GAE7B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,oCAAoC,GAGrC,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,qCAAqC,EAAE,MAAM,mCAAmC,CAAC;AAc1F,MAAM,UAAU,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AG,GAAG,EAAE,CAAC,MAAM,IAAI,YAAY,EAAE,IAAI,aAAa,EAAE,CAAC;QACvE,IAAI,CAAC;YACH,mCAAmC,CAAC,YAAY,CAAC,CAAC;YAClD,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC;gBACxB,UAAU;gBACV,YAAY;gBACZ,oBAAoB;gBACpB,aAAa;gBACb,iBAAiB,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;oBAC/B,aAAa;oBACb,YAAY,EAAE,kCAAkC,CAAC,OAAO,CAAC;oBACzD,UAAU,EAAE,0BAA0B,CAAC,UAAU,CAAC;oBAClD,0BAA0B,EAAE,QAAQ,CAAC,0BAA0B;iBAChE,CAAC;aACH,CAAC,CAAC;YACH,mCAAmC,CAAC,YAAY,CAAC,CAAC;YAClD,OAAO,MAAM,CAAC;QAChB,CAAC;gBAAS,CAAC;YACT,MAAM,GAAG,KAAK,CAAC;QACjB,CAAC;IACH,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport type { PrincipalPolicyHistoryProgressOptions } from \"@tearleads/crypto\";\nimport { rethrowKeyingVerificationError } from \"../../data/keyingProjectionVerification/error\";\nimport {\n assertProjectionVerificationCurrent,\n isProjectionVerificationCancelledError,\n type ReferencedPrincipalPolicyWarmer,\n} from \"../../data/keyingProjectionVerification/types\";\nimport { directoryHistoryProtection } from \"../../data/principals/principalHistoryScopeProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../data/principals/principalPolicyAdminSigners\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/shared/dependencyUnavailable\";\nimport { errorMessage } from \"../../data/shared/errorMessage\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { AcknowledgedPrincipalCurrentInput } from \"./acknowledgements/acknowledgedPrincipalCurrents\";\nimport {\n apiPrincipalPolicyPageReader,\n type PrincipalPolicyPageReader,\n} from \"./principalPolicyHistoryReader\";\nimport {\n createPrincipalPolicyCurrentResolver,\n type PrincipalPolicyCollaborators,\n type PrincipalPolicyCurrentResolver,\n} from \"./runtimePolicyRecovery\";\nimport { createProjectionPolicyHistoryResolver } from \"./runtimeProjectionPolicyRecovery\";\n\ntype PolicyResolver = NonNullable<\n ReferencedPrincipalPolicyWarmer[\"resolveReference\"]\n>;\n\n/**\n * The token of one reconciliation pass or user workflow. Every warmer created\n * with it shares one authenticated directory view, discovered once; the view\n * dies with the token, an organization hint, a durable pin past it, or the end\n * of its producing lease. Mint one at the pass or workflow root.\n */\nexport type PrincipalPolicyOperation = object;\n\nexport function createPrincipalPolicyOperation(): PrincipalPolicyOperation {\n return {};\n}\n\nexport interface PrincipalPolicyWarmerOptions {\n readonly preferLocalCurrent?: boolean;\n readonly operation?: PrincipalPolicyOperation | undefined;\n}\n\n/** A runtime snapshot carrying the policy service its producer bound, and its executor. */\nexport interface PrincipalPolicyRuntime {\n readonly infra: { readonly execSql: ExecSql };\n readonly principalPolicies: PrincipalPolicyService;\n}\n\nlet collaboratorsOf: (\n service: PrincipalPolicyService,\n) => PrincipalPolicyCollaborators;\n\n/**\n * Principal Policy: recovers, verifies, and prefetches the principal policy\n * evidence that projections cite. One instance binds one runtime snapshot's\n * API client, executor, online state, reporter, logger, trusted-identity\n * resolver, and the history-protection lease that snapshot bound; every view\n * derived from the snapshot shares it. The collaborators sit in a private\n * field, so a public runtime view carrying the service exposes no custody.\n */\nexport class PrincipalPolicyService {\n readonly #policies: PrincipalPolicyCollaborators;\n\n static {\n collaboratorsOf = (service) => service.#policies;\n }\n\n constructor(collaborators: PrincipalPolicyCollaborators) {\n this.#policies = collaborators;\n }\n\n /** Undefined without history custody or a paged history reader. */\n createCurrentPolicyResolver(): PrincipalPolicyCurrentResolver | undefined {\n return createPrincipalPolicyCurrentResolver(this.#policies);\n }\n\n /** Undefined without history custody or a projection history reader. */\n createProjectionHistoryResolver(): ReferencedPrincipalPolicyWarmer[\"resolveProjectionHistory\"] {\n return createProjectionPolicyHistoryResolver(this.#policies);\n }\n\n /**\n * One warmer serves one workflow operation: either the `operation` its root\n * minted, or a fresh one of its own. Its projection collections share one\n * authenticated directory view per operation. Prefetch is best-effort; exact\n * resolution still rejects unavailable evidence.\n */\n createWarmer(\n options: PrincipalPolicyWarmerOptions = {},\n ): ReferencedPrincipalPolicyWarmer {\n const resolve = this.createCurrentPolicyResolver();\n const operation = options.operation ?? createPrincipalPolicyOperation();\n const resolveReference: PolicyResolver = async (input) => {\n if (!resolve)\n throw new ProjectionDependencyUnavailableError(\n \"Principal policies require private paged recovery\",\n );\n return resolve({\n ...input,\n recoveryBatch: input.recoveryBatch ?? operation,\n preferLocalCurrent: options.preferLocalCurrent,\n });\n };\n const policies = this.#policies;\n return Object.assign(\n (input: Parameters<ReferencedPrincipalPolicyWarmer>[0]) =>\n prefetchReferences(policies, resolveReference, input),\n {\n resolveReference,\n resolveProjectionHistory: this.createProjectionHistoryResolver(),\n },\n );\n }\n}\n\nasync function prefetchReferences(\n policies: PrincipalPolicyCollaborators,\n resolve: PolicyResolver,\n input: Parameters<ReferencedPrincipalPolicyWarmer>[0],\n): Promise<void> {\n for (const reference of input.references) {\n try {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const resolved = await resolve({ ...input, reference });\n assertProjectionVerificationCurrent(resolved.stillCurrent);\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return;\n // Recovery already reports signature/authority failures. Keep them fatal.\n rethrowKeyingVerificationError(error);\n policies.util.log?.(\n `Principal policy prefetch: ${reference.principalId}: ${errorMessage(error)}`,\n );\n }\n }\n}\n\nexport interface CurrentPrincipalMutationLeaseContext {\n readonly protection: PrincipalPolicyHistoryProgressOptions;\n readonly stillCurrent: () => boolean;\n readonly resolveCurrentPolicy: PrincipalPolicyCurrentResolver;\n readonly historyReader: PrincipalPolicyPageReader;\n readonly directoryRecovery: (\n current: PrincipalPolicyPageCurrent,\n ) => AcknowledgedPrincipalCurrentInput[\"recovery\"];\n}\n\nexport type CurrentPrincipalMutationLease = <T>(\n callerCurrent: () => boolean,\n work: (context: CurrentPrincipalMutationLeaseContext) => Promise<T>,\n) => Promise<T>;\n\n/**\n * One lifetime fence and private custody boundary for every current-policy\n * mutation. It hands the snapshot's private history protection to `work`, so\n * it stays off the class and out of the package root: a public runtime view\n * carrying the service cannot reach it.\n */\nexport function createCurrentPrincipalMutationLease(\n service: PrincipalPolicyService,\n): CurrentPrincipalMutationLease | undefined {\n const policies = collaboratorsOf(service);\n const lease = policies.withPrincipalHistoryProtection;\n const resolveCurrentPolicy = createPrincipalPolicyCurrentResolver(policies);\n const historyReader = apiPrincipalPolicyPageReader(policies.apiClient);\n if (!lease || !resolveCurrentPolicy || !historyReader) return undefined;\n return async <T>(\n callerCurrent: () => boolean,\n work: (context: CurrentPrincipalMutationLeaseContext) => Promise<T>,\n ): Promise<T> =>\n lease(async ({ protection, stillCurrent: leaseCurrent }) => {\n let active = true;\n const stillCurrent = () => active && leaseCurrent() && callerCurrent();\n try {\n assertProjectionVerificationCurrent(stillCurrent);\n const result = await work({\n protection,\n stillCurrent,\n resolveCurrentPolicy,\n historyReader,\n directoryRecovery: (current) => ({\n historyReader,\n expectedHead: principalPolicyReferenceFromBundle(current),\n protection: directoryHistoryProtection(protection),\n resolveTrustedUserIdentity: policies.resolveTrustedUserIdentity,\n }),\n });\n assertProjectionVerificationCurrent(stillCurrent);\n return result;\n } finally {\n active = false;\n }\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"principalPolicyService.js","sourceRoot":"","sources":["principalPolicyService.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,8BAA8B,EAAE,MAAM,+CAA+C,CAAC;AAC/F,OAAO,EACL,mCAAmC,EACnC,sCAAsC,GAEvC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,kCAAkC,EAAE,MAAM,2DAA2D,CAAC;AAC/G,OAAO,EAAE,0BAA0B,EAAE,MAAM,uDAAuD,CAAC;AACnG,OAAO,EAAE,oCAAoC,EAAE,MA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C,oBAAoB,IAAI,CAAC,aAAa;QAAE,OAAO,SAAS,CAAC;IACxE,OAAO,KAAK,EACV,aAA4B,EAC5B,IAAmE,EACvD,EAAE,CACd,KAAK,CAAC,KAAK,EAAE,EAAE,UAAU,EAAE,YAAY,EAAE,YAAY,EAAE,EAAE,EAAE;QACzD,IAAI,MAAM,GAAG,IAAI,CAAC;QAClB,MAAM,YAAY,GAAG,GAAG,EAAE,CAAC,MAAM,IAAI,YAAY,EAAE,IAAI,aAAa,EAAE,CAAC;QACvE,IAAI,CAAC;YACH,mCAAmC,CAAC,YAAY,CAAC,CAAC;YAClD,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC;gBACxB,UAAU;gBACV,YAAY;gBACZ,oBAAoB;gBACpB,aAAa;gBACb,iBAAiB,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;oBAC/B,aAAa;oBACb,YAAY,EAAE,kCAAkC,CAAC,OAAO,CAAC;oBACzD,UAAU,EAAE,0BAA0B,CAAC,UAAU,CAAC;oBAClD,0BAA0B,EAAE,QAAQ,CAAC,0BAA0B;iBAChE,CAAC;aACH,CAAC,CAAC;YACH,mCAAmC,CAAC,YAAY,CAAC,CAAC;YAClD,OAAO,MAAM,CAAC;QAChB,CAAC;gBAAS,CAAC;YACT,MAAM,GAAG,KAAK,CAAC;QACjB,CAAC;IACH,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport type { PrincipalPolicyHistoryProgressOptions } from \"@tearleads/crypto\";\nimport { rethrowKeyingVerificationError } from \"../../data/keyingProjectionVerification/error\";\nimport {\n assertProjectionVerificationCurrent,\n isProjectionVerificationCancelledError,\n type ReferencedPrincipalPolicyWarmer,\n} from \"../../data/keyingProjectionVerification/types\";\nimport { principalPolicyReferenceFromBundle } from \"../../data/principalContracts/principalPolicyAdminSigners\";\nimport { directoryHistoryProtection } from \"../../data/principals/principalHistoryScopeProtection\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/shared/dependencyUnavailable\";\nimport { errorMessage } from \"../../data/shared/errorMessage\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { AcknowledgedPrincipalCurrentInput } from \"./acknowledgements/acknowledgedPrincipalCurrents\";\nimport {\n apiPrincipalPolicyPageReader,\n type PrincipalPolicyPageReader,\n} from \"./principalPolicyHistoryReader\";\nimport {\n createPrincipalPolicyCurrentResolver,\n type PrincipalPolicyCollaborators,\n type PrincipalPolicyCurrentResolver,\n} from \"./runtimePolicyRecovery\";\nimport { createProjectionPolicyHistoryResolver } from \"./runtimeProjectionPolicyRecovery\";\n\ntype PolicyResolver = NonNullable<\n ReferencedPrincipalPolicyWarmer[\"resolveReference\"]\n>;\n\n/**\n * The token of one reconciliation pass or user workflow. Every warmer created\n * with it shares one authenticated directory view, discovered once; the view\n * dies with the token, an organization hint, a durable pin past it, or the end\n * of its producing lease. Mint one at the pass or workflow root.\n */\nexport type PrincipalPolicyOperation = object;\n\nexport function createPrincipalPolicyOperation(): PrincipalPolicyOperation {\n return {};\n}\n\nexport interface PrincipalPolicyWarmerOptions {\n readonly preferLocalCurrent?: boolean;\n readonly operation?: PrincipalPolicyOperation | undefined;\n}\n\n/** A runtime snapshot carrying the policy service its producer bound, and its executor. */\nexport interface PrincipalPolicyRuntime {\n readonly infra: { readonly execSql: ExecSql };\n readonly principalPolicies: PrincipalPolicyService;\n}\n\nlet collaboratorsOf: (\n service: PrincipalPolicyService,\n) => PrincipalPolicyCollaborators;\n\n/**\n * Principal Policy: recovers, verifies, and prefetches the principal policy\n * evidence that projections cite. One instance binds one runtime snapshot's\n * API client, executor, online state, reporter, logger, trusted-identity\n * resolver, and the history-protection lease that snapshot bound; every view\n * derived from the snapshot shares it. The collaborators sit in a private\n * field, so a public runtime view carrying the service exposes no custody.\n */\nexport class PrincipalPolicyService {\n readonly #policies: PrincipalPolicyCollaborators;\n\n static {\n collaboratorsOf = (service) => service.#policies;\n }\n\n constructor(collaborators: PrincipalPolicyCollaborators) {\n this.#policies = collaborators;\n }\n\n /** Undefined without history custody or a paged history reader. */\n createCurrentPolicyResolver(): PrincipalPolicyCurrentResolver | undefined {\n return createPrincipalPolicyCurrentResolver(this.#policies);\n }\n\n /** Undefined without history custody or a projection history reader. */\n createProjectionHistoryResolver(): ReferencedPrincipalPolicyWarmer[\"resolveProjectionHistory\"] {\n return createProjectionPolicyHistoryResolver(this.#policies);\n }\n\n /**\n * One warmer serves one workflow operation: either the `operation` its root\n * minted, or a fresh one of its own. Its projection collections share one\n * authenticated directory view per operation. Prefetch is best-effort; exact\n * resolution still rejects unavailable evidence.\n */\n createWarmer(\n options: PrincipalPolicyWarmerOptions = {},\n ): ReferencedPrincipalPolicyWarmer {\n const resolve = this.createCurrentPolicyResolver();\n const operation = options.operation ?? createPrincipalPolicyOperation();\n const resolveReference: PolicyResolver = async (input) => {\n if (!resolve)\n throw new ProjectionDependencyUnavailableError(\n \"Principal policies require private paged recovery\",\n );\n return resolve({\n ...input,\n recoveryBatch: input.recoveryBatch ?? operation,\n preferLocalCurrent: options.preferLocalCurrent,\n });\n };\n const policies = this.#policies;\n return Object.assign(\n (input: Parameters<ReferencedPrincipalPolicyWarmer>[0]) =>\n prefetchReferences(policies, resolveReference, input),\n {\n resolveReference,\n resolveProjectionHistory: this.createProjectionHistoryResolver(),\n },\n );\n }\n}\n\nasync function prefetchReferences(\n policies: PrincipalPolicyCollaborators,\n resolve: PolicyResolver,\n input: Parameters<ReferencedPrincipalPolicyWarmer>[0],\n): Promise<void> {\n for (const reference of input.references) {\n try {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const resolved = await resolve({ ...input, reference });\n assertProjectionVerificationCurrent(resolved.stillCurrent);\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return;\n // Recovery already reports signature/authority failures. Keep them fatal.\n rethrowKeyingVerificationError(error);\n policies.util.log?.(\n `Principal policy prefetch: ${reference.principalId}: ${errorMessage(error)}`,\n );\n }\n }\n}\n\nexport interface CurrentPrincipalMutationLeaseContext {\n readonly protection: PrincipalPolicyHistoryProgressOptions;\n readonly stillCurrent: () => boolean;\n readonly resolveCurrentPolicy: PrincipalPolicyCurrentResolver;\n readonly historyReader: PrincipalPolicyPageReader;\n readonly directoryRecovery: (\n current: PrincipalPolicyPageCurrent,\n ) => AcknowledgedPrincipalCurrentInput[\"recovery\"];\n}\n\nexport type CurrentPrincipalMutationLease = <T>(\n callerCurrent: () => boolean,\n work: (context: CurrentPrincipalMutationLeaseContext) => Promise<T>,\n) => Promise<T>;\n\n/**\n * One lifetime fence and private custody boundary for every current-policy\n * mutation. It hands the snapshot's private history protection to `work`, so\n * it stays off the class and out of the package root: a public runtime view\n * carrying the service cannot reach it.\n */\nexport function createCurrentPrincipalMutationLease(\n service: PrincipalPolicyService,\n): CurrentPrincipalMutationLease | undefined {\n const policies = collaboratorsOf(service);\n const lease = policies.withPrincipalHistoryProtection;\n const resolveCurrentPolicy = createPrincipalPolicyCurrentResolver(policies);\n const historyReader = apiPrincipalPolicyPageReader(policies.apiClient);\n if (!lease || !resolveCurrentPolicy || !historyReader) return undefined;\n return async <T>(\n callerCurrent: () => boolean,\n work: (context: CurrentPrincipalMutationLeaseContext) => Promise<T>,\n ): Promise<T> =>\n lease(async ({ protection, stillCurrent: leaseCurrent }) => {\n let active = true;\n const stillCurrent = () => active && leaseCurrent() && callerCurrent();\n try {\n assertProjectionVerificationCurrent(stillCurrent);\n const result = await work({\n protection,\n stillCurrent,\n resolveCurrentPolicy,\n historyReader,\n directoryRecovery: (current) => ({\n historyReader,\n expectedHead: principalPolicyReferenceFromBundle(current),\n protection: directoryHistoryProtection(protection),\n resolveTrustedUserIdentity: policies.resolveTrustedUserIdentity,\n }),\n });\n assertProjectionVerificationCurrent(stillCurrent);\n return result;\n } finally {\n active = false;\n }\n });\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { KeyingVerificationError, serializeKeyingCanonicalJson, } from "../../../internal/crypto/index.js";
|
|
2
2
|
import { isReferencedPrincipalStateResponse } from "../../../internal/validators/response/index.js";
|
|
3
|
-
import { principalHeadMatchesReference } from "../../../data/
|
|
3
|
+
import { principalHeadMatchesReference } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
|
|
4
4
|
/** The greatest cited Admins head commits to the lineage of every earlier citation. */
|
|
5
5
|
export function publicHistoryAuthorityReference(previous, references) {
|
|
6
6
|
return references.reduce((head, reference) => !head || reference.version > head.version ? reference : head, previous);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"publicPrincipalHistoryAuthority.js","sourceRoot":"","sources":["publicPrincipalHistoryAuthority.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,kCAAkC,EAAE,MAAM,gCAAgC,CAAC;AAEpF,OAAO,EAAE,6BAA6B,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"publicPrincipalHistoryAuthority.js","sourceRoot":"","sources":["publicPrincipalHistoryAuthority.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,kCAAkC,EAAE,MAAM,gCAAgC,CAAC;AAEpF,OAAO,EAAE,6BAA6B,EAAE,MAAM,kEAAkE,CAAC;AAGjH,uFAAuF;AACvF,MAAM,UAAU,+BAA+B,CAC7C,QAAwC,EACxC,UAA8C;IAE9C,OAAO,UAAU,CAAC,MAAM,CACtB,CAAC,IAAI,EAAE,SAAS,EAAE,EAAE,CAClB,CAAC,IAAI,IAAI,SAAS,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,EAC9D,QAAQ,CACT,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,0BAA0B,CACxC,SAAyC;IAEzC,OAAO,4BAA4B,CAAC,SAAS,CAA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AS,CAAC,CAC/C,CACJ;QAED,MAAM,IAAI,uBAAuB,CAC/B,mBAAmB,EACnB,mEAAmE,CACpE,CAAC;IACJ,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAClD,KAAoC,EACpC,SAAyC,EACzC,iBAAgD,IAAI;IAEpD,IAAI,CAAC;QACH,IAAI,SAAS;YAAE,MAAM,0BAA0B,CAAC,KAAK,EAAE,CAAC,SAAS,CAAC,EAAE,IAAI,CAAC,CAAC;IAC5E,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,uBAAuB;YAC1C,MAAM,IAAI,sCAAsC,CAAC,KAAK,EAAE,cAAc,CAAC,CAAC;QAC1E,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAED,+EAA+E;AAC/E,MAAM,OAAO,sCAAuC,SAAQ,KAAK;IAEpD;IACA;IAFX,YACW,iBAA0C,EAC1C,cAA6C;QAEtD,KAAK,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;QAHxB,sBAAiB,GAAjB,iBAAiB,CAAyB;QAC1C,mBAAc,GAAd,cAAc,CAA+B;QAGtD,IAAI,CAAC,IAAI,GAAG,wCAAwC,CAAC;IACvD,CAAC;CACF","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n serializeKeyingCanonicalJson,\n} from \"@tearleads/crypto\";\nimport { isReferencedPrincipalStateResponse } from \"@tearleads/validators/response\";\nimport type { PrincipalHistoryPrefix } from \"../../../data/persistence/principalHistory/principalHistoryPrefixPersistence\";\nimport { principalHeadMatchesReference } from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport type { PublicPrincipalHistoryOptions } from \"./publicPrincipalHistoryTypes\";\n\n/** The greatest cited Admins head commits to the lineage of every earlier citation. */\nexport function publicHistoryAuthorityReference(\n previous: ReferencedPrincipalHead | null,\n references: readonly ReferencedPrincipalHead[],\n) {\n return references.reduce<ReferencedPrincipalHead | null>(\n (head, reference) =>\n !head || reference.version > head.version ? reference : head,\n previous,\n );\n}\n\nexport function publicHistoryAuthorityJson(\n reference: ReferencedPrincipalHead | null,\n) {\n return serializeKeyingCanonicalJson(reference ? { ...reference } : null);\n}\n\nexport function parsePublicHistoryAuthority(\n input: PublicPrincipalHistoryOptions,\n json: string,\n): ReferencedPrincipalHead | null | undefined {\n try {\n const value: unknown = JSON.parse(json);\n if (value === null) return null;\n if (\n isReferencedPrincipalStateResponse(value) &&\n value.principalType === \"group\" &&\n value.principalId === input.authorityGroupId\n )\n return value;\n } catch {\n /* Invalid disposable metadata cannot restore verified progress. */\n }\n return undefined;\n}\n\nexport async function loadPublicHistoryAuthority(\n input: PublicPrincipalHistoryOptions,\n references: readonly ReferencedPrincipalHead[],\n cachedPrefix = false,\n) {\n if (!references.length) return undefined;\n const authority = await input.loadExternalAuthority?.(\n references,\n cachedPrefix,\n );\n if (\n authority &&\n (authority.currentHead.principalId !== input.authorityGroupId ||\n authority.states.some(\n ({ head }) => head.principalId !== input.authorityGroupId,\n ))\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Authority callback differs from the directory binding\",\n );\n if (\n references.some(\n (reference) =>\n !authority?.states.some(({ head }) =>\n principalHeadMatchesReference(head, reference),\n ),\n )\n )\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"Public history authority differs from its verified Admins lineage\",\n );\n return authority;\n}\n\nexport async function validatePublicHistoryAuthority(\n input: PublicPrincipalHistoryOptions,\n reference: ReferencedPrincipalHead | null,\n rejectedPrefix: PrincipalHistoryPrefix | null = null,\n): Promise<void> {\n try {\n if (reference) await loadPublicHistoryAuthority(input, [reference], true);\n } catch (error) {\n if (error instanceof KeyingVerificationError)\n throw new PublicHistoryAuthorityUnavailableError(error, rejectedPrefix);\n throw error;\n }\n}\n\n/** Only cache restoration can request a replay after an authority mismatch. */\nexport class PublicHistoryAuthorityUnavailableError extends Error {\n constructor(\n readonly verificationError: KeyingVerificationError,\n readonly rejectedPrefix: PrincipalHistoryPrefix | null,\n ) {\n super(verificationError.message);\n this.name = \"PublicHistoryAuthorityUnavailableError\";\n }\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createPrincipalPolicyHistoryVerifier, KeyingVerificationError, restorePrincipalPolicyHistoryVerifier, serializeKeyingCanonicalJson, verifyPrincipalPolicyHistoryReferences, } from "../../../internal/crypto/index.js";
|
|
2
2
|
import { isReferencedPrincipalStateResponse } from "../../../internal/validators/response/index.js";
|
|
3
3
|
import { PrincipalHistoryRepository } from "../../../data/persistence/principalHistory/principalHistoryRepository.js";
|
|
4
|
-
import { principalHeadMatchesReference } from "../../../data/
|
|
4
|
+
import { principalHeadMatchesReference } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
|
|
5
5
|
import { principalHistoryEvidenceScopeId, principalHistoryPrefixProtection, } from "../../../data/principals/principalHistoryPrefixProtection.js";
|
|
6
6
|
import { principalHistoryStageId, principalHistoryStageProtection, } from "../../../data/principals/principalHistoryStageProtection.js";
|
|
7
7
|
import { PublicHistoryAuthorityUnavailableError, parsePublicHistoryAuthority, publicHistoryAuthorityJson, validatePublicHistoryAuthority, } from "./publicPrincipalHistoryAuthority.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"publicPrincipalHistoryProgress.js","sourceRoot":"","sources":["publicPrincipalHistoryProgress.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,EACvB,qCAAqC,EACrC,4BAA4B,EAE5B,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,kCAAkC,EAAE,MAAM,gCAAgC,CAAC;AAEpF,OAAO,EAAE,0BAA0B,EAAE,MAAM,uEAAuE,CAAC;AACnH,OAAO,EAAE,6BAA6B,EAAE,MAAM,0DAA0D,CAAC;AACzG,OAAO,EACL,+BAA+B,EAC/B,gCAAgC,GACjC,MAAM,2DAA2D,CAAC;AACnE,OAAO,E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AAM,IAAI,0BAA0B,CAClC,KAAK,CAAC,OAAO,CACd,CAAC,4BAA4B,CAAC,QAAQ,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;AACjE,CAAC","sourcesContent":["import {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n restorePrincipalPolicyHistoryVerifier,\n serializeKeyingCanonicalJson,\n type VerifiedPrincipalPolicyHistory,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport { isReferencedPrincipalStateResponse } from \"@tearleads/validators/response\";\nimport type { PrincipalHistoryPrefix } from \"../../../data/persistence/principalHistory/principalHistoryPrefixPersistence\";\nimport { PrincipalHistoryRepository } from \"../../../data/persistence/principalHistory/principalHistoryRepository\";\nimport { principalHeadMatchesReference } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport {\n principalHistoryEvidenceScopeId,\n principalHistoryPrefixProtection,\n} from \"../../../data/principals/principalHistoryPrefixProtection\";\nimport {\n principalHistoryStageId,\n principalHistoryStageProtection,\n} from \"../../../data/principals/principalHistoryStageProtection\";\nimport {\n PublicHistoryAuthorityUnavailableError,\n parsePublicHistoryAuthority,\n publicHistoryAuthorityJson,\n validatePublicHistoryAuthority,\n} from \"./publicPrincipalHistoryAuthority\";\nimport type {\n PublicPrincipalHistoryOptions,\n PublicPrincipalHistoryProgress,\n} from \"./publicPrincipalHistoryTypes\";\n\nfunction parsedJsonOrNull(json: string): unknown {\n try {\n return JSON.parse(json);\n } catch {\n return null;\n }\n}\n\nasync function restorePublicPrefix(\n input: PublicPrincipalHistoryOptions,\n scopeId: string,\n id: string,\n prefix: PrincipalHistoryPrefix | null,\n): Promise<PublicPrincipalHistoryProgress | null> {\n const head = input.source.head;\n const historyInput = {\n principalType: head.principalType,\n principalId: head.principalId,\n };\n const current = () => !input.signal?.aborted && input.stillCurrent();\n if (prefix) {\n const authorityReference = parsePublicHistoryAuthority(\n input,\n prefix.currentJson,\n );\n const prefixHead = parsedJsonOrNull(prefix.headJson);\n if (\n prefix.organizationId === input.organizationId &&\n authorityReference !== undefined &&\n isReferencedPrincipalStateResponse(prefixHead) &&\n prefixHead.principalId === head.principalId &&\n prefixHead.principalType === head.principalType &&\n prefixHead.version === prefix.version\n ) {\n const restored = await restorePrincipalPolicyHistoryVerifier(\n historyInput,\n prefix.progress,\n await principalHistoryPrefixProtection(input.protection, prefix),\n );\n if (restored.ok && restored.value.finish(prefixHead).ok) {\n await validatePublicHistoryAuthority(input, authorityReference, prefix);\n return {\n id,\n scopeId,\n verifier: restored.value,\n completedHead: prefixHead.version >= head.version ? prefixHead : null,\n afterVersion: Math.min(prefixHead.version, head.version - 1),\n saved: null,\n cachedPrefix: prefix,\n authorityReference,\n };\n }\n }\n if (!input.offline)\n await new PrincipalHistoryRepository(\n input.execSql,\n ).discardPrincipalHistoryPrefix({\n prefix,\n stillCurrent: current,\n });\n }\n return null;\n}\n\ntype RestoredVerifier = Awaited<\n ReturnType<typeof restorePrincipalPolicyHistoryVerifier>\n>;\n\n/** A restored verifier is reusable when a completed stage still finishes. */\nfunction finishesSavedHistory(\n restored: RestoredVerifier,\n complete: boolean,\n head: PublicPrincipalHistoryOptions[\"source\"][\"head\"],\n): restored is Extract<RestoredVerifier, { ok: true }> {\n return restored.ok && (!complete || restored.value.finish(head).ok);\n}\n\nexport async function restorePublicPrincipalHistoryProgress(\n input: PublicPrincipalHistoryOptions,\n allowReuse: boolean,\n): Promise<PublicPrincipalHistoryProgress> {\n const head = input.source.head;\n const historyInput = {\n principalType: head.principalType,\n principalId: head.principalId,\n };\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: input.organizationId,\n head,\n protection: input.protection,\n });\n const id = await principalHistoryStageId(\n input.organizationId,\n head,\n input.protection.context,\n );\n const current = () => !input.signal?.aborted && input.stillCurrent();\n const saved = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryStage(id);\n if (saved) {\n const authorityReference = parsePublicHistoryAuthority(\n input,\n saved.currentJson,\n );\n if (\n allowReuse &&\n saved.organizationId === input.organizationId &&\n authorityReference !== undefined\n ) {\n const restored = await restorePrincipalPolicyHistoryVerifier(\n historyInput,\n saved.progress,\n await principalHistoryStageProtection(input.protection, head, saved),\n );\n if (finishesSavedHistory(restored, saved.complete, head)) {\n await validatePublicHistoryAuthority(input, authorityReference);\n return {\n id,\n scopeId,\n verifier: restored.value,\n completedHead: saved.complete ? head : null,\n afterVersion: saved.afterVersion,\n saved,\n cachedPrefix: null,\n authorityReference,\n };\n }\n }\n if (!input.offline)\n await new PrincipalHistoryRepository(\n input.execSql,\n ).discardPrincipalHistoryStage(saved, current);\n }\n const prefix = allowReuse\n ? await restorePublicPrefix(\n input,\n scopeId,\n id,\n await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryPrefix(scopeId),\n )\n : null;\n if (prefix) return prefix;\n return {\n id,\n scopeId,\n verifier: createPrincipalPolicyHistoryVerifier(historyInput),\n completedHead: null,\n afterVersion: 0,\n saved: null,\n cachedPrefix: null,\n authorityReference: null,\n };\n}\n\n/** A resumed stage may finish after the reader that rejected the prefix exits. */\nasync function rejectedCompletedPrefix(\n input: PublicPrincipalHistoryOptions,\n progress: PublicPrincipalHistoryProgress,\n history: VerifiedPrincipalPolicyHistory,\n): Promise<PrincipalHistoryPrefix | null> {\n const candidate = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryPrefix(progress.scopeId);\n if (!candidate || candidate.version <= history.currentEntry.state.version)\n return null;\n try {\n const cached = await restorePublicPrefix(\n input,\n progress.scopeId,\n progress.id,\n candidate,\n );\n if (!cached?.completedHead) return null;\n const finished = cached.verifier.finish(cached.completedHead);\n if (!finished.ok) throw finished.error;\n const proof = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryReference({\n scopeId: progress.scopeId,\n history: finished.value,\n version: input.source.head.version,\n });\n const verified = await verifyPrincipalPolicyHistoryReferences({\n history: finished.value,\n references: [proof],\n });\n if (!verified.ok) throw verified.error;\n return principalHeadMatchesReference(proof.entry.state, input.source.head)\n ? null\n : candidate;\n } catch (error) {\n if (\n error instanceof KeyingVerificationError ||\n error instanceof PublicHistoryAuthorityUnavailableError\n )\n return candidate;\n throw error;\n }\n}\n\nexport async function publishPublicPrincipalHistoryPrefix(\n input: PublicPrincipalHistoryOptions,\n progress: PublicPrincipalHistoryProgress,\n history: VerifiedPrincipalPolicyHistory,\n rejectedPrefix: PrincipalHistoryPrefix | null,\n): Promise<void> {\n const state = history.currentEntry.state;\n const head = {\n principalType: state.principalType,\n principalId: state.principalId,\n version: state.version,\n stateHash: state.stateHash,\n keyEpoch: state.keyEpoch,\n keyFingerprint: state.keyFingerprint,\n };\n const prefix = {\n scopeId: progress.scopeId,\n organizationId: input.organizationId,\n version: head.version,\n headJson: serializeKeyingCanonicalJson(head),\n currentJson: publicHistoryAuthorityJson(progress.authorityReference),\n };\n const sealed = await progress.verifier.exportProgress(\n await principalHistoryPrefixProtection(input.protection, prefix),\n );\n if (!sealed.ok) throw sealed.error;\n const rejected =\n rejectedPrefix ??\n (progress.cachedPrefix\n ? null\n : await rejectedCompletedPrefix(input, progress, history));\n const stillCurrent = () => !input.signal?.aborted && input.stillCurrent();\n await new PrincipalHistoryRepository(\n input.execSql,\n ).savePrincipalHistoryPrefix({\n indexRootHash: history.indexRootHash,\n prefix: { ...prefix, progress: sealed.value },\n stillCurrent,\n rejectedPrefix: rejected,\n });\n if (progress.saved)\n await new PrincipalHistoryRepository(\n input.execSql,\n ).discardPrincipalHistoryStage(progress.saved, stillCurrent);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"publicPrincipalHistoryProgress.js","sourceRoot":"","sources":["publicPrincipalHistoryProgress.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,EACvB,qCAAqC,EACrC,4BAA4B,EAE5B,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,kCAAkC,EAAE,MAAM,gCAAgC,CAAC;AAEpF,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,aAAa;QACpC,MAAM,EAAE,EAAE,GAAG,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,KAAK,EAAE;QAC7C,YAAY;QACZ,cAAc,EAAE,QAAQ;KACzB,CAAC,CAAC;IACH,IAAI,QAAQ,CAAC,KAAK;QAChB,MAAM,IAAI,0BAA0B,CAClC,KAAK,CAAC,OAAO,CACd,CAAC,4BAA4B,CAAC,QAAQ,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;AACjE,CAAC","sourcesContent":["import {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n restorePrincipalPolicyHistoryVerifier,\n serializeKeyingCanonicalJson,\n type VerifiedPrincipalPolicyHistory,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport { isReferencedPrincipalStateResponse } from \"@tearleads/validators/response\";\nimport type { PrincipalHistoryPrefix } from \"../../../data/persistence/principalHistory/principalHistoryPrefixPersistence\";\nimport { PrincipalHistoryRepository } from \"../../../data/persistence/principalHistory/principalHistoryRepository\";\nimport { principalHeadMatchesReference } from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport {\n principalHistoryEvidenceScopeId,\n principalHistoryPrefixProtection,\n} from \"../../../data/principals/principalHistoryPrefixProtection\";\nimport {\n principalHistoryStageId,\n principalHistoryStageProtection,\n} from \"../../../data/principals/principalHistoryStageProtection\";\nimport {\n PublicHistoryAuthorityUnavailableError,\n parsePublicHistoryAuthority,\n publicHistoryAuthorityJson,\n validatePublicHistoryAuthority,\n} from \"./publicPrincipalHistoryAuthority\";\nimport type {\n PublicPrincipalHistoryOptions,\n PublicPrincipalHistoryProgress,\n} from \"./publicPrincipalHistoryTypes\";\n\nfunction parsedJsonOrNull(json: string): unknown {\n try {\n return JSON.parse(json);\n } catch {\n return null;\n }\n}\n\nasync function restorePublicPrefix(\n input: PublicPrincipalHistoryOptions,\n scopeId: string,\n id: string,\n prefix: PrincipalHistoryPrefix | null,\n): Promise<PublicPrincipalHistoryProgress | null> {\n const head = input.source.head;\n const historyInput = {\n principalType: head.principalType,\n principalId: head.principalId,\n };\n const current = () => !input.signal?.aborted && input.stillCurrent();\n if (prefix) {\n const authorityReference = parsePublicHistoryAuthority(\n input,\n prefix.currentJson,\n );\n const prefixHead = parsedJsonOrNull(prefix.headJson);\n if (\n prefix.organizationId === input.organizationId &&\n authorityReference !== undefined &&\n isReferencedPrincipalStateResponse(prefixHead) &&\n prefixHead.principalId === head.principalId &&\n prefixHead.principalType === head.principalType &&\n prefixHead.version === prefix.version\n ) {\n const restored = await restorePrincipalPolicyHistoryVerifier(\n historyInput,\n prefix.progress,\n await principalHistoryPrefixProtection(input.protection, prefix),\n );\n if (restored.ok && restored.value.finish(prefixHead).ok) {\n await validatePublicHistoryAuthority(input, authorityReference, prefix);\n return {\n id,\n scopeId,\n verifier: restored.value,\n completedHead: prefixHead.version >= head.version ? prefixHead : null,\n afterVersion: Math.min(prefixHead.version, head.version - 1),\n saved: null,\n cachedPrefix: prefix,\n authorityReference,\n };\n }\n }\n if (!input.offline)\n await new PrincipalHistoryRepository(\n input.execSql,\n ).discardPrincipalHistoryPrefix({\n prefix,\n stillCurrent: current,\n });\n }\n return null;\n}\n\ntype RestoredVerifier = Awaited<\n ReturnType<typeof restorePrincipalPolicyHistoryVerifier>\n>;\n\n/** A restored verifier is reusable when a completed stage still finishes. */\nfunction finishesSavedHistory(\n restored: RestoredVerifier,\n complete: boolean,\n head: PublicPrincipalHistoryOptions[\"source\"][\"head\"],\n): restored is Extract<RestoredVerifier, { ok: true }> {\n return restored.ok && (!complete || restored.value.finish(head).ok);\n}\n\nexport async function restorePublicPrincipalHistoryProgress(\n input: PublicPrincipalHistoryOptions,\n allowReuse: boolean,\n): Promise<PublicPrincipalHistoryProgress> {\n const head = input.source.head;\n const historyInput = {\n principalType: head.principalType,\n principalId: head.principalId,\n };\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: input.organizationId,\n head,\n protection: input.protection,\n });\n const id = await principalHistoryStageId(\n input.organizationId,\n head,\n input.protection.context,\n );\n const current = () => !input.signal?.aborted && input.stillCurrent();\n const saved = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryStage(id);\n if (saved) {\n const authorityReference = parsePublicHistoryAuthority(\n input,\n saved.currentJson,\n );\n if (\n allowReuse &&\n saved.organizationId === input.organizationId &&\n authorityReference !== undefined\n ) {\n const restored = await restorePrincipalPolicyHistoryVerifier(\n historyInput,\n saved.progress,\n await principalHistoryStageProtection(input.protection, head, saved),\n );\n if (finishesSavedHistory(restored, saved.complete, head)) {\n await validatePublicHistoryAuthority(input, authorityReference);\n return {\n id,\n scopeId,\n verifier: restored.value,\n completedHead: saved.complete ? head : null,\n afterVersion: saved.afterVersion,\n saved,\n cachedPrefix: null,\n authorityReference,\n };\n }\n }\n if (!input.offline)\n await new PrincipalHistoryRepository(\n input.execSql,\n ).discardPrincipalHistoryStage(saved, current);\n }\n const prefix = allowReuse\n ? await restorePublicPrefix(\n input,\n scopeId,\n id,\n await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryPrefix(scopeId),\n )\n : null;\n if (prefix) return prefix;\n return {\n id,\n scopeId,\n verifier: createPrincipalPolicyHistoryVerifier(historyInput),\n completedHead: null,\n afterVersion: 0,\n saved: null,\n cachedPrefix: null,\n authorityReference: null,\n };\n}\n\n/** A resumed stage may finish after the reader that rejected the prefix exits. */\nasync function rejectedCompletedPrefix(\n input: PublicPrincipalHistoryOptions,\n progress: PublicPrincipalHistoryProgress,\n history: VerifiedPrincipalPolicyHistory,\n): Promise<PrincipalHistoryPrefix | null> {\n const candidate = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryPrefix(progress.scopeId);\n if (!candidate || candidate.version <= history.currentEntry.state.version)\n return null;\n try {\n const cached = await restorePublicPrefix(\n input,\n progress.scopeId,\n progress.id,\n candidate,\n );\n if (!cached?.completedHead) return null;\n const finished = cached.verifier.finish(cached.completedHead);\n if (!finished.ok) throw finished.error;\n const proof = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryReference({\n scopeId: progress.scopeId,\n history: finished.value,\n version: input.source.head.version,\n });\n const verified = await verifyPrincipalPolicyHistoryReferences({\n history: finished.value,\n references: [proof],\n });\n if (!verified.ok) throw verified.error;\n return principalHeadMatchesReference(proof.entry.state, input.source.head)\n ? null\n : candidate;\n } catch (error) {\n if (\n error instanceof KeyingVerificationError ||\n error instanceof PublicHistoryAuthorityUnavailableError\n )\n return candidate;\n throw error;\n }\n}\n\nexport async function publishPublicPrincipalHistoryPrefix(\n input: PublicPrincipalHistoryOptions,\n progress: PublicPrincipalHistoryProgress,\n history: VerifiedPrincipalPolicyHistory,\n rejectedPrefix: PrincipalHistoryPrefix | null,\n): Promise<void> {\n const state = history.currentEntry.state;\n const head = {\n principalType: state.principalType,\n principalId: state.principalId,\n version: state.version,\n stateHash: state.stateHash,\n keyEpoch: state.keyEpoch,\n keyFingerprint: state.keyFingerprint,\n };\n const prefix = {\n scopeId: progress.scopeId,\n organizationId: input.organizationId,\n version: head.version,\n headJson: serializeKeyingCanonicalJson(head),\n currentJson: publicHistoryAuthorityJson(progress.authorityReference),\n };\n const sealed = await progress.verifier.exportProgress(\n await principalHistoryPrefixProtection(input.protection, prefix),\n );\n if (!sealed.ok) throw sealed.error;\n const rejected =\n rejectedPrefix ??\n (progress.cachedPrefix\n ? null\n : await rejectedCompletedPrefix(input, progress, history));\n const stillCurrent = () => !input.signal?.aborted && input.stillCurrent();\n await new PrincipalHistoryRepository(\n input.execSql,\n ).savePrincipalHistoryPrefix({\n indexRootHash: history.indexRootHash,\n prefix: { ...prefix, progress: sealed.value },\n stillCurrent,\n rejectedPrefix: rejected,\n });\n if (progress.saved)\n await new PrincipalHistoryRepository(\n input.execSql,\n ).discardPrincipalHistoryStage(progress.saved, stillCurrent);\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { computePrincipalStatePayloadCiphertextHash, } from "../../../internal/crypto/index.js";
|
|
2
|
-
import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, } from "../../../data/
|
|
2
|
+
import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
|
|
3
3
|
import { rejectPublicProjection, selectPublicProjectionPrincipal, } from "./publicProjectionPrincipal.js";
|
|
4
4
|
export async function publicProjectionDirectoryBindings(evidence, organization) {
|
|
5
5
|
const policies = await selectPublicProjectionPrincipal(organization);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"publicProjectionDirectory.js","sourceRoot":"","sources":["publicProjectionDirectory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,0CAA0C,GAE3C,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,oCAAoC,EACpC,6BAA6B,GAC9B,MAAM,
|
|
1
|
+
{"version":3,"file":"publicProjectionDirectory.js","sourceRoot":"","sources":["publicProjectionDirectory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,0CAA0C,GAE3C,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,oCAAoC,EACpC,6BAA6B,GAC9B,MAAM,kEAAkE,CAAC;AAC1E,OAAO,EAEL,sBAAsB,EACtB,+BAA+B,GAChC,MAAM,6BAA6B,CAAC;AAErC,MAAM,CAAC,KAAK,UAAU,iCAAiC,CACrD,QAA0C,EAC1C,YAAuC;IAEvC,MAAM,QAAQ,GAAG,MAAM,+BAA+B,CAAC,YAAY,CAAC,CAAC;IACrE,MAAM,OAAO,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,eAAe,CAAC,CAAC;IACrE,MAAM,WAAW,GAAG,EAAE,CAAC;IACvB,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,KAAK,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,QAAQ,CAAC,oBAAoB,EAAE,CAAC;QACnE,MAAM,KAAK,GA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CAA+C,CAAC,CAAC;QAC1E,MAAM,SAAS,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAC/C,SAAS,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CACjC,6BAA6B,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,CACjD,CACF,CAAC;QACF,MAAM,SAAS,GAAG,SAAS,EAAE,UAAU,CAAC,IAAI,CAC1C,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,WAAW,KAAK,SAAS,CAAC,YAAY,CACtD,CAAC;QACF,IAAI,CAAC,SAAS;YACZ,sBAAsB,CAAC,iDAAiD,CAAC,CAAC;QAC5E,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,EAAE,EAAE,SAAS,EAAE,CAAC,CAAC;IACvD,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n computePrincipalStatePayloadCiphertextHash,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { ProjectionPolicyEvidenceResponse } from \"@tearleads/validators/response\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport {\n type PublicProjectionPrincipal,\n rejectPublicProjection,\n selectPublicProjectionPrincipal,\n} from \"./publicProjectionPrincipal\";\n\nexport async function publicProjectionDirectoryBindings(\n evidence: ProjectionPolicyEvidenceResponse,\n organization: PublicProjectionPrincipal,\n) {\n const policies = await selectPublicProjectionPrincipal(organization);\n const entries = policies.flatMap((policy) => policy.retainedHistory);\n const descriptors = [];\n const seen = new Set<string>();\n for (const { reference, payload } of evidence.organizationPayloads) {\n const state = entries.find(({ state }) =>\n principalHeadMatchesReference(state, reference),\n )?.state;\n if (\n !state ||\n reference.version > organization.options.source.head.version ||\n payload.principalType !== \"organization\" ||\n payload.principalId !== organization.options.organizationId ||\n payload.stateHash !== state.stateHash ||\n seen.has(state.stateHash)\n )\n rejectPublicProjection(\"directory payload scope is invalid\");\n seen.add(state.stateHash);\n const hash = await computePrincipalStatePayloadCiphertextHash(\n payload.ciphertext,\n );\n if (hash !== payload.ciphertextHash || hash !== state.payloadCiphertextHash)\n rejectPublicProjection(\"directory payload differs from its signed hash\");\n const descriptor = parseOrganizationAuthorityDescriptor(payload.ciphertext);\n if (descriptor.organizationId !== organization.options.organizationId)\n rejectPublicProjection(\"directory belongs to another organization\");\n descriptors.push(descriptor);\n }\n const bindings = new Map<string, { adminHead: ReferencedPrincipalHead }>();\n for (const source of evidence.groups) {\n if (\n source.head.principalType !== \"group\" ||\n bindings.has(source.head.principalId)\n )\n rejectPublicProjection(\"group sources have invalid or repeated scopes\");\n const directory = descriptors.find((candidate) =>\n candidate.groupHeads.some((head) =>\n principalHeadMatchesReference(head, source.head),\n ),\n );\n const adminHead = directory?.groupHeads.find(\n (head) => head.principalId === directory.adminGroupId,\n );\n if (!adminHead)\n rejectPublicProjection(\"group source lacks its signed directory binding\");\n bindings.set(source.head.principalId, { adminHead });\n }\n return bindings;\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
|
|
2
2
|
import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
|
|
3
3
|
import { KeyingCheckpointRepository } from "../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
|
|
4
|
-
import { assertSelectedPolicyCommitments } from "../../../data/
|
|
4
|
+
import { assertSelectedPolicyCommitments } from "../../../data/principalContracts/principalIdentityCommitments.js";
|
|
5
5
|
import { PrincipalHistoryEvidenceUnavailableError } from "../historyRecovery/principalHistoryRecoveryReferences.js";
|
|
6
6
|
import { recoverPublicPrincipalHistory } from "./recoverPublicPrincipalHistory.js";
|
|
7
7
|
import { selectPublicPrincipalHistory } from "./selectPublicPrincipalHistory.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"publicProjectionPrincipal.js","sourceRoot":"","sources":["publicProjectionPrincipal.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,+BAA+B,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"publicProjectionPrincipal.js","sourceRoot":"","sources":["publicProjectionPrincipal.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,+BAA+B,EAAE,MAAM,+DAA+D,CAAC;AAChH,OAAO,EAAE,wCAAwC,EAAE,MAAM,uDAAuD,CAAC;AAKjH,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAAE,4BAA4B,EAAE,MAAM,gCAAgC,CAAC;AAS9E,uFAAuF;AACvF,MAAM,CAAC,KAAK,UAAU,+BAA+B,CACnD,SAAoC,EACpC,aAAiD,SAAS,CAAC,UAAU;IAErE,MAAM,EAAE,OAAO,EAAE,GAAG,SAAS,CAAC;IAC9B,MAAM,OAAO,GAAG,GAAG,EAAE,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC;IACzE,mCAAmC,CAAC,OAAO,CAAC,CAAC;IAC7C,MAAM,UAAU,GAAG,MAAM,IAAI,0BAA0B,CACrD,OAAO,CAAC,OAAO,CAChB,CAAC,6BAA6B,CAC7B,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,aAAa,EACjC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,CA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AC,aAAa;QACxD,IAAI,CAAC,WAAW,KAAK,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,CACvD,CAAC;IACF,IAAI,QAAQ,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC;QACrE,sBAAsB,CAAC,2CAA2C,CAAC,CAAC;IACtE,MAAM,SAAS,GAAG;QAChB,OAAO;QACP,UAAU,EAAE,eAAe,CAAC,QAAQ,CAAC;QACrC,SAAS,EAAE,MAAM,6BAA6B,CAAC,OAAO,CAAC;QACvD,QAAQ,EAAE,KAAK;KAChB,CAAC;IACF,MAAM,+BAA+B,CAAC,SAAS,CAAC,CAAC;IACjD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,MAAM,UAAU,sBAAsB,CAAC,OAAe;IACpD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,8BAA8B,OAAO,EAAE,CACxC,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { assertSelectedPolicyCommitments } from \"../../../data/principalContracts/principalIdentityCommitments\";\nimport { PrincipalHistoryEvidenceUnavailableError } from \"../historyRecovery/principalHistoryRecoveryReferences\";\nimport type {\n PublicPrincipalHistoryOptions,\n RecoveredPublicPrincipalHistory,\n} from \"./publicPrincipalHistoryTypes\";\nimport { recoverPublicPrincipalHistory } from \"./recoverPublicPrincipalHistory\";\nimport { selectPublicPrincipalHistory } from \"./selectPublicPrincipalHistory\";\n\nexport interface PublicProjectionPrincipal {\n readonly options: PublicPrincipalHistoryOptions;\n readonly references: readonly ReferencedPrincipalHead[];\n recovered: RecoveredPublicPrincipalHistory;\n replayed: boolean;\n}\n\n/** The source head and every citation remain bound independently of a newer prefix. */\nexport async function selectPublicProjectionPrincipal(\n principal: PublicProjectionPrincipal,\n references: readonly ReferencedPrincipalHead[] = principal.references,\n) {\n const { options } = principal;\n const current = () => !options.signal?.aborted && options.stillCurrent();\n assertProjectionVerificationCurrent(current);\n const checkpoint = await new KeyingCheckpointRepository(\n options.execSql,\n ).loadPrincipalPolicyCheckpoint(\n options.source.head.principalType,\n options.source.head.principalId,\n );\n let policies: Awaited<ReturnType<typeof selectPublicPrincipalHistory>>;\n try {\n policies = await selectPublicPrincipalHistory({\n execSql: options.execSql,\n recovered: principal.recovered,\n references: [options.source.head, ...references],\n checkpoint,\n deferCheckpointCheck: options.historicalProof,\n includeGenesis: options.source.head.principalType === \"organization\",\n stillCurrent: current,\n });\n } catch (error) {\n if (!(error instanceof PrincipalHistoryEvidenceUnavailableError))\n throw error;\n if (options.offline || principal.replayed) throw error.verificationError;\n principal.replayed = true;\n principal.recovered = await recoverPublicPrincipalHistory({\n ...options,\n replay: true,\n });\n return selectPublicProjectionPrincipal(principal, references);\n }\n await assertSelectedPolicyCommitments(\n policies,\n options.resolveTrustedUserIdentity,\n () => assertProjectionVerificationCurrent(current),\n );\n assertProjectionVerificationCurrent(current);\n return policies;\n}\n\nexport async function recoverPublicProjectionPrincipal(\n options: PublicPrincipalHistoryOptions,\n references: readonly ReferencedPrincipalHead[],\n): Promise<PublicProjectionPrincipal> {\n const selected = references.filter(\n (head) =>\n head.principalType === options.source.head.principalType &&\n head.principalId === options.source.head.principalId,\n );\n if (selected.some((head) => head.version > options.source.head.version))\n rejectPublicProjection(\"citation exceeds its supplied source head\");\n const principal = {\n options,\n references: structuredClone(selected),\n recovered: await recoverPublicPrincipalHistory(options),\n replayed: false,\n };\n await selectPublicProjectionPrincipal(principal);\n return principal;\n}\n\nexport function rejectPublicProjection(message: string): never {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `Public projection history: ${message}`,\n );\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
|
|
2
2
|
import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
|
|
3
|
-
import { principalHeadMatchesReference } from "../../../data/
|
|
3
|
+
import { principalHeadMatchesReference } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
|
|
4
4
|
import { publicProjectionDirectoryBindings } from "./publicProjectionDirectory.js";
|
|
5
5
|
import { recoverPublicProjectionPrincipal, rejectPublicProjection, selectPublicProjectionPrincipal, } from "./publicProjectionPrincipal.js";
|
|
6
6
|
function assertSourceCoverage(evidence, references) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"recoverProjectionPolicyHistory.js","sourceRoot":"","sources":["recoverProjectionPolicyHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,6BAA6B,EAAE,MAAM,0DAA0D,CAAC;AAEzG,OAAO,EAAE,iCAAiC,EAAE,MAAM,6BAA6B,CAAC;AAChF,OAAO,EAEL,gCAAgC,EAChC,sBAAsB,EACtB,+BAA+B,GAChC,MAAM,6BAA6B,CAAC;AAerC,SAAS,oBAAoB,CAC3B,QAA0C,EAC1C,UAA8C;IAE9C,MAAM,OAAO,GAAG,CAAC,QAAQ,CAAC,YAAY,EAAE,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC;IAC5D,KAAK,MAAM,SAAS,IAAI,UAAU;QAChC,IACE,CAAC,OAAO,CAAC,IAAI,CACX,CAAC,MAAM,EAAE,EAAE,CACT,MAAM;YACN,MAAM,CAAC,IAAI,CAAC,aAAa,KAAK,SAAS,CAAC,aAAa;YACrD,MAAM,CAAC,IAAI,CAAC,WAAW,KAAK,SAAS,CAAC,WAAW;YACjD,MAAM,CAAC,IAAI,CAAC,OAAO,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AAC,WAAW,CAAC,CAAC;QACtD,MAAM,MAAM,GAAG,OAAO,IAAI,UAAU,CAAC,GAAG,CAAC,OAAO,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC;QACxE,IAAI,CAAC,MAAM;YAAE,sBAAsB,CAAC,oCAAoC,CAAC,CAAC;QAC1E,UAAU,CAAC,GAAG,CACZ,MAAM,CAAC,IAAI,CAAC,WAAW,EACvB,MAAM,gCAAgC,CACpC;YACE,GAAG,KAAK;YACR,MAAM;YACN,gBAAgB,EAAE,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW;YACxD,qBAAqB,EAAE,CAAC,UAAU,EAAE,YAAY,EAAE,EAAE,CAClD,iBAAiB,CAAC,MAAM,EAAE,UAAU,EAAE,YAAY,CAAC;SACtD,EACD,KAAK,CAAC,UAAU,CACjB,CACF,CAAC;IACJ,CAAC;IACD,MAAM,QAAQ,GAAuC,EAAE,CAAC;IACxD,KAAK,MAAM,SAAS,IAAI,CAAC,YAAY,EAAE,GAAG,UAAU,CAAC,MAAM,EAAE,CAAC;QAC5D,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,+BAA+B,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;IACvE,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyExternalAuthority,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport type { ProjectionPolicyEvidenceResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { principalHeadMatchesReference } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport type { PublicPrincipalHistoryOptions } from \"./publicPrincipalHistoryTypes\";\nimport { publicProjectionDirectoryBindings } from \"./publicProjectionDirectory\";\nimport {\n type PublicProjectionPrincipal,\n recoverPublicProjectionPrincipal,\n rejectPublicProjection,\n selectPublicProjectionPrincipal,\n} from \"./publicProjectionPrincipal\";\n\nexport interface ProjectionPolicyHistoryRecoveryOptions\n extends Omit<\n PublicPrincipalHistoryOptions,\n | \"source\"\n | \"loadExternalAuthority\"\n | \"strictAdmins\"\n | \"authorityGroupId\"\n | \"replay\"\n > {\n readonly evidence: ProjectionPolicyEvidenceResponse;\n readonly references: readonly ReferencedPrincipalHead[];\n}\n\nfunction assertSourceCoverage(\n evidence: ProjectionPolicyEvidenceResponse,\n references: readonly ReferencedPrincipalHead[],\n): void {\n const sources = [evidence.organization, ...evidence.groups];\n for (const reference of references)\n if (\n !sources.some(\n (source) =>\n source &&\n source.head.principalType === reference.principalType &&\n source.head.principalId === reference.principalId &&\n source.head.version >= reference.version,\n )\n )\n rejectPublicProjection(\"required citation has no covering source\");\n}\n\nasync function externalAuthority(\n admins: PublicProjectionPrincipal,\n references: readonly ReferencedPrincipalHead[],\n cachedPrefix = false,\n): Promise<PrincipalPolicyExternalAuthority | undefined> {\n const head = admins.options.source.head;\n if (!references.length) return undefined;\n if (\n cachedPrefix &&\n references.some((reference) => reference.version > head.version)\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Cached group history requires a newer Admins source\",\n );\n if (\n references.some(\n (reference) =>\n reference.principalId !== head.principalId ||\n reference.version > head.version,\n )\n )\n rejectPublicProjection(\n \"external authority exceeds the bound Admins source\",\n );\n const policies = await selectPublicProjectionPrincipal(admins, references);\n const states = new Map(\n policies.flatMap((policy) =>\n // Only this page's citations and the bound source head are authority for\n // this verification step. A retained newer prefix is not another citation.\n policy.retainedHistory\n .filter(({ state }) =>\n [head, ...references].some((reference) =>\n principalHeadMatchesReference(state, reference),\n ),\n )\n .map(\n ({ state, projection }) =>\n [\n state.version,\n {\n head: {\n principalType: \"group\" as const,\n principalId: state.principalId,\n version: state.version,\n stateHash: state.stateHash,\n keyEpoch: state.keyEpoch,\n keyFingerprint: state.keyFingerprint,\n },\n projection,\n },\n ] as const,\n ),\n ),\n );\n return {\n currentHead: { ...head, principalType: \"group\" },\n states: [...states.values()],\n };\n}\n\n/** Public authorization only; no current-policy cache or checkpoint is written. */\nexport async function recoverProjectionPolicyHistory(\n input: ProjectionPolicyHistoryRecoveryOptions,\n): Promise<VerifiedPrincipalPolicySelection[]> {\n assertProjectionVerificationCurrent(\n () => !input.signal?.aborted && input.stillCurrent(),\n );\n input = { ...input, references: structuredClone(input.references) };\n const evidence = structuredClone(input.evidence);\n assertSourceCoverage(evidence, input.references);\n if (!evidence.organization) {\n if (evidence.groups.length || evidence.organizationPayloads.length)\n rejectPublicProjection(\"group evidence requires organization history\");\n return [];\n }\n if (evidence.organization.head.principalType !== \"organization\")\n rejectPublicProjection(\"organization source has the wrong principal type\");\n const organization = await recoverPublicProjectionPrincipal(\n {\n ...input,\n source: evidence.organization,\n },\n [\n ...input.references,\n ...evidence.organizationPayloads.map(({ reference }) => reference),\n ],\n );\n const bindings = await publicProjectionDirectoryBindings(\n evidence,\n organization,\n );\n const principals = new Map<string, PublicProjectionPrincipal>();\n const adminHeads = [...bindings.values()].map(({ adminHead }) => adminHead);\n for (const adminId of new Set(adminHeads.map((head) => head.principalId))) {\n const source = evidence.groups.find(\n (group) => group.head.principalId === adminId,\n );\n if (!source) rejectPublicProjection(\"signed Admins source is missing\");\n principals.set(\n adminId,\n await recoverPublicProjectionPrincipal(\n { ...input, source, strictAdmins: true },\n [...input.references, ...adminHeads],\n ),\n );\n }\n for (const source of evidence.groups) {\n if (principals.has(source.head.principalId)) continue;\n const binding = bindings.get(source.head.principalId);\n const admins = binding && principals.get(binding.adminHead.principalId);\n if (!admins) rejectPublicProjection(\"verified Admins history is missing\");\n principals.set(\n source.head.principalId,\n await recoverPublicProjectionPrincipal(\n {\n ...input,\n source,\n authorityGroupId: admins.options.source.head.principalId,\n loadExternalAuthority: (references, cachedPrefix) =>\n externalAuthority(admins, references, cachedPrefix),\n },\n input.references,\n ),\n );\n }\n const policies: VerifiedPrincipalPolicySelection[] = [];\n for (const principal of [organization, ...principals.values()])\n policies.push(...(await selectPublicProjectionPrincipal(principal)));\n return policies;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"recoverProjectionPolicyHistory.js","sourceRoot":"","sources":["recoverProjectionPolicyHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,6BAA6B,EAAE,MAAM,kEAAkE,CAAC;AAEjH,OAAO,EAAE,iCAAiC,EAAE,MAAM,6BAA6B,CAAC;AAChF,OAAO,EAEL,gCAAgC,EAChC,sBAAsB,EACtB,+BAA+B,GAChC,MAAM,6BAA6B,CAAC;AAerC,SAAS,oBAAoB,CAC3B,QAA0C,EAC1C,UAA8C;IAE9C,MAAM,OAAO,GAAG,CAAC,QAAQ,CAAC,YAAY,EAAE,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC;IAC5D,KAAK,MAAM,SAAS,IAAI,UAAU;QAChC,IACE,CAAC,OAAO,CAAC,IAAI,CACX,CAAC,MAAM,EAAE,EAAE,CACT,MAAM;YACN,MAAM,CAAC,IAAI,CAAC,aAAa,KAAK,SAAS,CAAC,aAAa;YACrD,MAAM,CAAC,IAAI,CAAC,WAAW,KAAK,SAAS,CAAC,WAAW;YACjD,MAAM,CAAC,IAAI,CAAC,OAAO,IAAI,SAAS,CAAC,OAAO,CAC3C;YAED,sBAAsB,CAAC,0CAA0C,CAAC,CAAC;AACzE,CAAC;AAED,KAAK,UAAU,iBAAiB,CAC9B,MAAiC,EACjC,UAA8C,EAC9C,YAAY,GAAG,KAAK;IAEpB,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC;IACxC,IAAI,CAAC,UAAU,CAAC,MAAM;QAAE,OAAO,SAAS,CAAC;IACzC,IACE,YAAY;QACZ,UAAU,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,S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WAAW;YACxD,qBAAqB,EAAE,CAAC,UAAU,EAAE,YAAY,EAAE,EAAE,CAClD,iBAAiB,CAAC,MAAM,EAAE,UAAU,EAAE,YAAY,CAAC;SACtD,EACD,KAAK,CAAC,UAAU,CACjB,CACF,CAAC;IACJ,CAAC;IACD,MAAM,QAAQ,GAAuC,EAAE,CAAC;IACxD,KAAK,MAAM,SAAS,IAAI,CAAC,YAAY,EAAE,GAAG,UAAU,CAAC,MAAM,EAAE,CAAC;QAC5D,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,+BAA+B,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;IACvE,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyExternalAuthority,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport type { ProjectionPolicyEvidenceResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { principalHeadMatchesReference } from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport type { PublicPrincipalHistoryOptions } from \"./publicPrincipalHistoryTypes\";\nimport { publicProjectionDirectoryBindings } from \"./publicProjectionDirectory\";\nimport {\n type PublicProjectionPrincipal,\n recoverPublicProjectionPrincipal,\n rejectPublicProjection,\n selectPublicProjectionPrincipal,\n} from \"./publicProjectionPrincipal\";\n\nexport interface ProjectionPolicyHistoryRecoveryOptions\n extends Omit<\n PublicPrincipalHistoryOptions,\n | \"source\"\n | \"loadExternalAuthority\"\n | \"strictAdmins\"\n | \"authorityGroupId\"\n | \"replay\"\n > {\n readonly evidence: ProjectionPolicyEvidenceResponse;\n readonly references: readonly ReferencedPrincipalHead[];\n}\n\nfunction assertSourceCoverage(\n evidence: ProjectionPolicyEvidenceResponse,\n references: readonly ReferencedPrincipalHead[],\n): void {\n const sources = [evidence.organization, ...evidence.groups];\n for (const reference of references)\n if (\n !sources.some(\n (source) =>\n source &&\n source.head.principalType === reference.principalType &&\n source.head.principalId === reference.principalId &&\n source.head.version >= reference.version,\n )\n )\n rejectPublicProjection(\"required citation has no covering source\");\n}\n\nasync function externalAuthority(\n admins: PublicProjectionPrincipal,\n references: readonly ReferencedPrincipalHead[],\n cachedPrefix = false,\n): Promise<PrincipalPolicyExternalAuthority | undefined> {\n const head = admins.options.source.head;\n if (!references.length) return undefined;\n if (\n cachedPrefix &&\n references.some((reference) => reference.version > head.version)\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Cached group history requires a newer Admins source\",\n );\n if (\n references.some(\n (reference) =>\n reference.principalId !== head.principalId ||\n reference.version > head.version,\n )\n )\n rejectPublicProjection(\n \"external authority exceeds the bound Admins source\",\n );\n const policies = await selectPublicProjectionPrincipal(admins, references);\n const states = new Map(\n policies.flatMap((policy) =>\n // Only this page's citations and the bound source head are authority for\n // this verification step. A retained newer prefix is not another citation.\n policy.retainedHistory\n .filter(({ state }) =>\n [head, ...references].some((reference) =>\n principalHeadMatchesReference(state, reference),\n ),\n )\n .map(\n ({ state, projection }) =>\n [\n state.version,\n {\n head: {\n principalType: \"group\" as const,\n principalId: state.principalId,\n version: state.version,\n stateHash: state.stateHash,\n keyEpoch: state.keyEpoch,\n keyFingerprint: state.keyFingerprint,\n },\n projection,\n },\n ] as const,\n ),\n ),\n );\n return {\n currentHead: { ...head, principalType: \"group\" },\n states: [...states.values()],\n };\n}\n\n/** Public authorization only; no current-policy cache or checkpoint is written. */\nexport async function recoverProjectionPolicyHistory(\n input: ProjectionPolicyHistoryRecoveryOptions,\n): Promise<VerifiedPrincipalPolicySelection[]> {\n assertProjectionVerificationCurrent(\n () => !input.signal?.aborted && input.stillCurrent(),\n );\n input = { ...input, references: structuredClone(input.references) };\n const evidence = structuredClone(input.evidence);\n assertSourceCoverage(evidence, input.references);\n if (!evidence.organization) {\n if (evidence.groups.length || evidence.organizationPayloads.length)\n rejectPublicProjection(\"group evidence requires organization history\");\n return [];\n }\n if (evidence.organization.head.principalType !== \"organization\")\n rejectPublicProjection(\"organization source has the wrong principal type\");\n const organization = await recoverPublicProjectionPrincipal(\n {\n ...input,\n source: evidence.organization,\n },\n [\n ...input.references,\n ...evidence.organizationPayloads.map(({ reference }) => reference),\n ],\n );\n const bindings = await publicProjectionDirectoryBindings(\n evidence,\n organization,\n );\n const principals = new Map<string, PublicProjectionPrincipal>();\n const adminHeads = [...bindings.values()].map(({ adminHead }) => adminHead);\n for (const adminId of new Set(adminHeads.map((head) => head.principalId))) {\n const source = evidence.groups.find(\n (group) => group.head.principalId === adminId,\n );\n if (!source) rejectPublicProjection(\"signed Admins source is missing\");\n principals.set(\n adminId,\n await recoverPublicProjectionPrincipal(\n { ...input, source, strictAdmins: true },\n [...input.references, ...adminHeads],\n ),\n );\n }\n for (const source of evidence.groups) {\n if (principals.has(source.head.principalId)) continue;\n const binding = bindings.get(source.head.principalId);\n const admins = binding && principals.get(binding.adminHead.principalId);\n if (!admins) rejectPublicProjection(\"verified Admins history is missing\");\n principals.set(\n source.head.principalId,\n await recoverPublicProjectionPrincipal(\n {\n ...input,\n source,\n authorityGroupId: admins.options.source.head.principalId,\n loadExternalAuthority: (references, cachedPrefix) =>\n externalAuthority(admins, references, cachedPrefix),\n },\n input.references,\n ),\n );\n }\n const policies: VerifiedPrincipalPolicySelection[] = [];\n for (const principal of [organization, ...principals.values()])\n policies.push(...(await selectPublicProjectionPrincipal(principal)));\n return policies;\n}\n"]}
|
|
@@ -3,9 +3,9 @@ import { isPrincipalPolicySnapshotPage, } from "../../../internal/validators/res
|
|
|
3
3
|
import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
|
|
4
4
|
import { PrincipalHistoryRepository } from "../../../data/persistence/principalHistory/principalHistoryRepository.js";
|
|
5
5
|
import { PrincipalPolicyBundleRepository } from "../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
|
|
6
|
-
import { principalHeadMatchesReference } from "../../../data/
|
|
6
|
+
import { principalHeadMatchesReference } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
|
|
7
|
+
import { publishAuthenticatedSigners } from "../../../data/principalContracts/principalIdentityCommitments.js";
|
|
7
8
|
import { ownPrincipalHistoryProtection } from "../../../data/principals/principalHistoryProtection.js";
|
|
8
|
-
import { publishAuthenticatedSigners } from "../../../data/principals/principalIdentityCommitments.js";
|
|
9
9
|
import { PrincipalPolicyHistoryReadError } from "../historyRecovery/principalHistoryRecoveryTypes.js";
|
|
10
10
|
import { initialHeldHeadState, transitionHeldHeadState, } from "./heldHeadStateMachine.js";
|
|
11
11
|
import { PublicHistoryAuthorityUnavailableError } from "./publicPrincipalHistoryAuthority.js";
|