@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":"recoverPublicPrincipalHistory.js","sourceRoot":"","sources":["recoverPublicPrincipalHist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0E;IAC1E,oCAAoC,CAAC;QACnC,aAAa,EAAE,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,aAAa;QAChD,WAAW,EAAE,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW;QAC5C,kBAAkB,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC;KAC1C,CAAC,CAAC;IACH,MAAM,UAAU,GAAG,6BAA6B,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IACrE,UAAU,CAAC,OAAO,GAAG,4BAA4B,CAAC;QAChD,2CAA2C;QAC3C,UAAU,CAAC,OAAO;QAClB,OAAO,CAAC,YAAY,KAAK,IAAI;QAC7B,OAAO,CAAC,gBAAgB,IAAI,IAAI;KACjC,CAAC,CAAC;IACH,MAAM,KAAK,GAAG;QACZ,GAAG,OAAO;QACV,MAAM,EAAE,eAAe,CAAC,OAAO,CAAC,MAAM,CAAC;QACvC,UAAU;KACX,CAAC;IACF,IAAI,CAAC;QACH,OAAO,MAAM,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC;IACvD,CAAC;YAAS,CAAC;QACT,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAC9B,CAAC;AACH,CAAC","sourcesContent":["import {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n type PrincipalPolicyHistoryReferenceProof,\n serializeKeyingCanonicalJson,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport {\n isPrincipalPolicySnapshotPage,\n type PrincipalPolicySnapshotPage,\n type PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryPrefix } from \"../../../data/persistence/principalHistory/principalHistoryPrefixPersistence\";\nimport { PrincipalHistoryRepository } from \"../../../data/persistence/principalHistory/principalHistoryRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { principalHeadMatchesReference } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { ownPrincipalHistoryProtection } from \"../../../data/principals/principalHistoryProtection\";\nimport { publishAuthenticatedSigners } from \"../../../data/principals/principalIdentityCommitments\";\nimport { PrincipalPolicyHistoryReadError } from \"../historyRecovery/principalHistoryRecoveryTypes\";\nimport {\n type HeldHeadState,\n initialHeldHeadState,\n transitionHeldHeadState,\n} from \"./heldHeadStateMachine\";\nimport { PublicHistoryAuthorityUnavailableError } from \"./publicPrincipalHistoryAuthority\";\nimport {\n appendPublicPrincipalHistoryPage,\n PublicPrincipalHistoryPrefixDisconnectedError,\n} from \"./publicPrincipalHistoryPage\";\nimport {\n publishPublicPrincipalHistoryPrefix,\n restorePublicPrincipalHistoryProgress,\n} from \"./publicPrincipalHistoryProgress\";\nimport type {\n PublicPrincipalHistoryOptions,\n PublicPrincipalHistoryProgress,\n RecoveredPublicPrincipalHistory,\n} from \"./publicPrincipalHistoryTypes\";\n\n/** The attempt's held-head machine; written only through its transition. */\ninterface HeldHeadCell {\n state: HeldHeadState;\n}\n\nfunction assertPage(\n input: PublicPrincipalHistoryOptions,\n page: PrincipalPolicySnapshotPage,\n after: number,\n): void {\n if (\n !isPrincipalPolicySnapshotPage(page) ||\n !principalHeadMatchesReference(page.currentState, input.source.head) ||\n page.historyPage.afterVersion !== after\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history page does not match its requested head and cursor\",\n );\n const through = after + page.previousStates.length;\n if (\n page.previousStates.some(\n ({ state }, index) => state.version !== after + index + 1,\n ) ||\n through >= input.source.head.version ||\n (page.historyPage.nextAfterVersion === null\n ? through !== input.source.head.version - 1\n : through <= after || page.historyPage.nextAfterVersion !== through)\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Public history page has a gap or invalid continuation\",\n );\n}\n\n/**\n * A held copy of the head replaces only its download; the final page appends\n * and checks it exactly as a served state.\n */\nasync function loadHeldHead(\n input: PublicPrincipalHistoryOptions,\n held: HeldHeadCell,\n): Promise<PrincipalStateResponse | undefined> {\n const knownCurrentState =\n held.state.status === \"eligible\"\n ? ((await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadHeldPrincipalState(input.source.head)) ?? undefined)\n : undefined;\n held.state = transitionHeldHeadState(held.state, {\n type: knownCurrentState ? \"heldLoaded\" : \"heldMissing\",\n });\n return knownCurrentState;\n}\n\nasync function readPublicPages(\n input: PublicPrincipalHistoryOptions,\n initial: PublicPrincipalHistoryProgress,\n held: HeldHeadCell,\n) {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n let progress = initial;\n let lastPage: PrincipalPolicySnapshotPage | undefined;\n // Completed progress already verified every signed entry through the cited\n // head; a read pinned to that head could only repeat it or refuse.\n if (!input.offline && !progress.completedHead) {\n const knownCurrentState = await loadHeldHead(input, held);\n for await (const result of input.historyReader.getProjectionPolicyHistoryPages(\n input.source,\n {\n afterVersion: progress.afterVersion,\n knownCurrentState,\n signal: input.signal,\n },\n )) {\n assertProjectionVerificationCurrent(current);\n if (!result.ok) throw new PrincipalPolicyHistoryReadError(result);\n const page = result.data;\n assertPage(input, page, progress.afterVersion);\n if (progress.completedHead)\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Completed public history returned additional entries\",\n );\n progress = await appendPublicPrincipalHistoryPage(input, progress, page);\n lastPage = page;\n }\n if (lastPage?.historyPage.nextAfterVersion !== null)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Public history transport did not complete\",\n );\n }\n return { progress, lastPage };\n}\n\nfunction finishPublicProgress(progress: PublicPrincipalHistoryProgress) {\n if (!progress.completedHead)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Completed public history is unavailable\",\n );\n const finished = progress.verifier.finish(progress.completedHead);\n if (!finished.ok) throw finished.error;\n return finished.value;\n}\n\n/** The last page's current state must extend the same verified history. */\nasync function verifyLastPageCurrent(\n history: ReturnType<typeof finishPublicProgress>,\n proof: PrincipalPolicyHistoryReferenceProof,\n lastPage: Awaited<ReturnType<typeof readPublicPages>>[\"lastPage\"],\n): Promise<void> {\n if (!lastPage) return;\n const currentProof = {\n ...proof,\n entry: {\n state: lastPage.currentState,\n projection: lastPage.currentProjection,\n grants: lastPage.currentGrants,\n },\n };\n const checked = await verifyPrincipalPolicyHistoryReferences({\n history,\n references: [currentProof],\n });\n if (!checked.ok) throw checked.error;\n}\n\n// A signed cached candidate need not belong to this requested chain. Only\n// reused progress permits one replay; a fresh disconnected chain fails.\nfunction replaysReusedProgress(\n mayReplay: boolean,\n initial: { readonly afterVersion: number },\n): boolean {\n return mayReplay && initial.afterVersion > 0;\n}\n\nasync function recoverAttempt(\n input: PublicPrincipalHistoryOptions,\n allowReuse: boolean,\n rejectedPrefix: PrincipalHistoryPrefix | null,\n held: HeldHeadCell,\n): Promise<RecoveredPublicPrincipalHistory> {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n assertProjectionVerificationCurrent(current);\n const mayReplay = allowReuse && !input.offline;\n const initial = await restorePublicPrincipalHistoryProgress(\n input,\n allowReuse,\n );\n let pages: Awaited<ReturnType<typeof readPublicPages>>;\n try {\n pages = await readPublicPages(input, initial, held);\n } catch (error) {\n if (!(error instanceof PublicPrincipalHistoryPrefixDisconnectedError))\n throw error;\n if (replaysReusedProgress(mayReplay, initial))\n return recover(input, false, initial.cachedPrefix);\n throw error.verificationError;\n }\n const { progress, lastPage } = pages;\n const history = finishPublicProgress(progress);\n let proof: PrincipalPolicyHistoryReferenceProof;\n try {\n proof = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryReference({\n scopeId: progress.scopeId,\n history,\n version: input.source.head.version,\n });\n const selected = await verifyPrincipalPolicyHistoryReferences({\n history,\n references: [proof],\n });\n if (!selected.ok) throw selected.error;\n } catch (error) {\n if (error instanceof KeyingVerificationError && mayReplay)\n return recover(input, false, initial.cachedPrefix);\n throw error;\n }\n // Public prefixes memoize signatures; they are not admitted trust pins. A\n // rejected projection may have left a valid but unrelated signed candidate.\n // Rebuild the requested chain once online; callers still check durable pins\n // and object authority before accepting it. Never reuse a mismatch offline.\n if (!principalHeadMatchesReference(proof.entry.state, input.source.head)) {\n if (mayReplay) return recover(input, false, initial.cachedPrefix);\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history source differs from the verified prefix\",\n );\n }\n await verifyLastPageCurrent(history, proof, lastPage);\n // The chain now reaches its source head: pin the signers it accepted.\n await publishAuthenticatedSigners(\n history.signers,\n input.resolveTrustedUserIdentity,\n () => assertProjectionVerificationCurrent(current),\n );\n assertProjectionVerificationCurrent(current);\n if (!input.offline)\n await publishPublicPrincipalHistoryPrefix(\n input,\n progress,\n history,\n rejectedPrefix,\n );\n assertProjectionVerificationCurrent(current);\n return { scopeId: progress.scopeId, history };\n}\n\nasync function recover(\n input: PublicPrincipalHistoryOptions,\n allowReuse = true,\n rejectedPrefix: PrincipalHistoryPrefix | null = null,\n useHeldState = true,\n): Promise<RecoveredPublicPrincipalHistory> {\n // A replay distrusts local material, so it reads the served head as well.\n const held: HeldHeadCell = {\n state: initialHeldHeadState(useHeldState && allowReuse),\n };\n try {\n return await recoverAttempt(input, allowReuse, rejectedPrefix, held);\n } catch (error) {\n // A held head copy only saves its download; one the verifier rejects must\n // not block recovery, so read the served copy once instead.\n if (\n held.state.status === \"heldSent\" &&\n error instanceof KeyingVerificationError\n )\n return recover(input, allowReuse, rejectedPrefix, false);\n if (!(error instanceof PublicHistoryAuthorityUnavailableError)) throw error;\n if (allowReuse && !input.offline)\n return recoverAttempt(input, false, error.rejectedPrefix, {\n state: initialHeldHeadState(false),\n });\n throw error.verificationError;\n }\n}\n\n/** Private-key-backed public history recovery; never admits a current policy pin. */\nexport async function recoverPublicPrincipalHistory(\n options: PublicPrincipalHistoryOptions,\n): Promise<RecoveredPublicPrincipalHistory> {\n if (\n !options.organizationId ||\n (options.historicalProof !== undefined &&\n typeof options.historicalProof !== \"boolean\") ||\n (options.offline !== undefined && typeof options.offline !== \"boolean\") ||\n (options.strictAdmins !== undefined &&\n typeof options.strictAdmins !== \"boolean\") ||\n (options.strictAdmins &&\n (options.source.head.principalType !== \"group\" ||\n options.loadExternalAuthority))\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Invalid public history verification scope\",\n );\n if (\n options.source.head.principalType === \"organization\" &&\n options.source.head.principalId !== options.organizationId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public organization history is outside its scope\",\n );\n // Validate the caller's pinned head before any cache or transport access.\n createPrincipalPolicyHistoryVerifier({\n principalType: options.source.head.principalType,\n principalId: options.source.head.principalId,\n retainedReferences: [options.source.head],\n });\n const protection = ownPrincipalHistoryProtection(options.protection);\n protection.context = serializeKeyingCanonicalJson([\n \"tearleads.sdk.public-principal-history.v2\",\n protection.context,\n options.strictAdmins === true,\n options.authorityGroupId ?? null,\n ]);\n const input = {\n ...options,\n source: structuredClone(options.source),\n protection,\n };\n try {\n return await recover(input, options.replay !== true);\n } finally {\n protection.localKey.fill(0);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"recoverPublicPrincipalHistory.js","sourceRoot":"","sources":["recoverPublicPrincipalHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,EAEvB,4BAA4B,EAC5B,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,6BAA6B,GAG9B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AAEvG,OAAO,EAAE,0BAA0B,EAAE,MAAM,uEAAuE,CAAC;AACnH,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAAE,6BAA6B,EAAE,MAAM,kEAAkE,CAAC;AACjH,OAAO,EAAE,2BAA2B,EAAE,MAAM,+DAA+D,CAAC;AAC5G,OAAO,EAAE,6BAA6B,EAAE,MAAM,qDAAqD,CAAC;AAC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G;QACZ,GAAG,OAAO;QACV,MAAM,EAAE,eAAe,CAAC,OAAO,CAAC,MAAM,CAAC;QACvC,UAAU;KACX,CAAC;IACF,IAAI,CAAC;QACH,OAAO,MAAM,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC;IACvD,CAAC;YAAS,CAAC;QACT,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAC9B,CAAC;AACH,CAAC","sourcesContent":["import {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n type PrincipalPolicyHistoryReferenceProof,\n serializeKeyingCanonicalJson,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport {\n isPrincipalPolicySnapshotPage,\n type PrincipalPolicySnapshotPage,\n type PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryPrefix } from \"../../../data/persistence/principalHistory/principalHistoryPrefixPersistence\";\nimport { PrincipalHistoryRepository } from \"../../../data/persistence/principalHistory/principalHistoryRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { principalHeadMatchesReference } from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport { publishAuthenticatedSigners } from \"../../../data/principalContracts/principalIdentityCommitments\";\nimport { ownPrincipalHistoryProtection } from \"../../../data/principals/principalHistoryProtection\";\nimport { PrincipalPolicyHistoryReadError } from \"../historyRecovery/principalHistoryRecoveryTypes\";\nimport {\n type HeldHeadState,\n initialHeldHeadState,\n transitionHeldHeadState,\n} from \"./heldHeadStateMachine\";\nimport { PublicHistoryAuthorityUnavailableError } from \"./publicPrincipalHistoryAuthority\";\nimport {\n appendPublicPrincipalHistoryPage,\n PublicPrincipalHistoryPrefixDisconnectedError,\n} from \"./publicPrincipalHistoryPage\";\nimport {\n publishPublicPrincipalHistoryPrefix,\n restorePublicPrincipalHistoryProgress,\n} from \"./publicPrincipalHistoryProgress\";\nimport type {\n PublicPrincipalHistoryOptions,\n PublicPrincipalHistoryProgress,\n RecoveredPublicPrincipalHistory,\n} from \"./publicPrincipalHistoryTypes\";\n\n/** The attempt's held-head machine; written only through its transition. */\ninterface HeldHeadCell {\n state: HeldHeadState;\n}\n\nfunction assertPage(\n input: PublicPrincipalHistoryOptions,\n page: PrincipalPolicySnapshotPage,\n after: number,\n): void {\n if (\n !isPrincipalPolicySnapshotPage(page) ||\n !principalHeadMatchesReference(page.currentState, input.source.head) ||\n page.historyPage.afterVersion !== after\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history page does not match its requested head and cursor\",\n );\n const through = after + page.previousStates.length;\n if (\n page.previousStates.some(\n ({ state }, index) => state.version !== after + index + 1,\n ) ||\n through >= input.source.head.version ||\n (page.historyPage.nextAfterVersion === null\n ? through !== input.source.head.version - 1\n : through <= after || page.historyPage.nextAfterVersion !== through)\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Public history page has a gap or invalid continuation\",\n );\n}\n\n/**\n * A held copy of the head replaces only its download; the final page appends\n * and checks it exactly as a served state.\n */\nasync function loadHeldHead(\n input: PublicPrincipalHistoryOptions,\n held: HeldHeadCell,\n): Promise<PrincipalStateResponse | undefined> {\n const knownCurrentState =\n held.state.status === \"eligible\"\n ? ((await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadHeldPrincipalState(input.source.head)) ?? undefined)\n : undefined;\n held.state = transitionHeldHeadState(held.state, {\n type: knownCurrentState ? \"heldLoaded\" : \"heldMissing\",\n });\n return knownCurrentState;\n}\n\nasync function readPublicPages(\n input: PublicPrincipalHistoryOptions,\n initial: PublicPrincipalHistoryProgress,\n held: HeldHeadCell,\n) {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n let progress = initial;\n let lastPage: PrincipalPolicySnapshotPage | undefined;\n // Completed progress already verified every signed entry through the cited\n // head; a read pinned to that head could only repeat it or refuse.\n if (!input.offline && !progress.completedHead) {\n const knownCurrentState = await loadHeldHead(input, held);\n for await (const result of input.historyReader.getProjectionPolicyHistoryPages(\n input.source,\n {\n afterVersion: progress.afterVersion,\n knownCurrentState,\n signal: input.signal,\n },\n )) {\n assertProjectionVerificationCurrent(current);\n if (!result.ok) throw new PrincipalPolicyHistoryReadError(result);\n const page = result.data;\n assertPage(input, page, progress.afterVersion);\n if (progress.completedHead)\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Completed public history returned additional entries\",\n );\n progress = await appendPublicPrincipalHistoryPage(input, progress, page);\n lastPage = page;\n }\n if (lastPage?.historyPage.nextAfterVersion !== null)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Public history transport did not complete\",\n );\n }\n return { progress, lastPage };\n}\n\nfunction finishPublicProgress(progress: PublicPrincipalHistoryProgress) {\n if (!progress.completedHead)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Completed public history is unavailable\",\n );\n const finished = progress.verifier.finish(progress.completedHead);\n if (!finished.ok) throw finished.error;\n return finished.value;\n}\n\n/** The last page's current state must extend the same verified history. */\nasync function verifyLastPageCurrent(\n history: ReturnType<typeof finishPublicProgress>,\n proof: PrincipalPolicyHistoryReferenceProof,\n lastPage: Awaited<ReturnType<typeof readPublicPages>>[\"lastPage\"],\n): Promise<void> {\n if (!lastPage) return;\n const currentProof = {\n ...proof,\n entry: {\n state: lastPage.currentState,\n projection: lastPage.currentProjection,\n grants: lastPage.currentGrants,\n },\n };\n const checked = await verifyPrincipalPolicyHistoryReferences({\n history,\n references: [currentProof],\n });\n if (!checked.ok) throw checked.error;\n}\n\n// A signed cached candidate need not belong to this requested chain. Only\n// reused progress permits one replay; a fresh disconnected chain fails.\nfunction replaysReusedProgress(\n mayReplay: boolean,\n initial: { readonly afterVersion: number },\n): boolean {\n return mayReplay && initial.afterVersion > 0;\n}\n\nasync function recoverAttempt(\n input: PublicPrincipalHistoryOptions,\n allowReuse: boolean,\n rejectedPrefix: PrincipalHistoryPrefix | null,\n held: HeldHeadCell,\n): Promise<RecoveredPublicPrincipalHistory> {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n assertProjectionVerificationCurrent(current);\n const mayReplay = allowReuse && !input.offline;\n const initial = await restorePublicPrincipalHistoryProgress(\n input,\n allowReuse,\n );\n let pages: Awaited<ReturnType<typeof readPublicPages>>;\n try {\n pages = await readPublicPages(input, initial, held);\n } catch (error) {\n if (!(error instanceof PublicPrincipalHistoryPrefixDisconnectedError))\n throw error;\n if (replaysReusedProgress(mayReplay, initial))\n return recover(input, false, initial.cachedPrefix);\n throw error.verificationError;\n }\n const { progress, lastPage } = pages;\n const history = finishPublicProgress(progress);\n let proof: PrincipalPolicyHistoryReferenceProof;\n try {\n proof = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryReference({\n scopeId: progress.scopeId,\n history,\n version: input.source.head.version,\n });\n const selected = await verifyPrincipalPolicyHistoryReferences({\n history,\n references: [proof],\n });\n if (!selected.ok) throw selected.error;\n } catch (error) {\n if (error instanceof KeyingVerificationError && mayReplay)\n return recover(input, false, initial.cachedPrefix);\n throw error;\n }\n // Public prefixes memoize signatures; they are not admitted trust pins. A\n // rejected projection may have left a valid but unrelated signed candidate.\n // Rebuild the requested chain once online; callers still check durable pins\n // and object authority before accepting it. Never reuse a mismatch offline.\n if (!principalHeadMatchesReference(proof.entry.state, input.source.head)) {\n if (mayReplay) return recover(input, false, initial.cachedPrefix);\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history source differs from the verified prefix\",\n );\n }\n await verifyLastPageCurrent(history, proof, lastPage);\n // The chain now reaches its source head: pin the signers it accepted.\n await publishAuthenticatedSigners(\n history.signers,\n input.resolveTrustedUserIdentity,\n () => assertProjectionVerificationCurrent(current),\n );\n assertProjectionVerificationCurrent(current);\n if (!input.offline)\n await publishPublicPrincipalHistoryPrefix(\n input,\n progress,\n history,\n rejectedPrefix,\n );\n assertProjectionVerificationCurrent(current);\n return { scopeId: progress.scopeId, history };\n}\n\nasync function recover(\n input: PublicPrincipalHistoryOptions,\n allowReuse = true,\n rejectedPrefix: PrincipalHistoryPrefix | null = null,\n useHeldState = true,\n): Promise<RecoveredPublicPrincipalHistory> {\n // A replay distrusts local material, so it reads the served head as well.\n const held: HeldHeadCell = {\n state: initialHeldHeadState(useHeldState && allowReuse),\n };\n try {\n return await recoverAttempt(input, allowReuse, rejectedPrefix, held);\n } catch (error) {\n // A held head copy only saves its download; one the verifier rejects must\n // not block recovery, so read the served copy once instead.\n if (\n held.state.status === \"heldSent\" &&\n error instanceof KeyingVerificationError\n )\n return recover(input, allowReuse, rejectedPrefix, false);\n if (!(error instanceof PublicHistoryAuthorityUnavailableError)) throw error;\n if (allowReuse && !input.offline)\n return recoverAttempt(input, false, error.rejectedPrefix, {\n state: initialHeldHeadState(false),\n });\n throw error.verificationError;\n }\n}\n\n/** Private-key-backed public history recovery; never admits a current policy pin. */\nexport async function recoverPublicPrincipalHistory(\n options: PublicPrincipalHistoryOptions,\n): Promise<RecoveredPublicPrincipalHistory> {\n if (\n !options.organizationId ||\n (options.historicalProof !== undefined &&\n typeof options.historicalProof !== \"boolean\") ||\n (options.offline !== undefined && typeof options.offline !== \"boolean\") ||\n (options.strictAdmins !== undefined &&\n typeof options.strictAdmins !== \"boolean\") ||\n (options.strictAdmins &&\n (options.source.head.principalType !== \"group\" ||\n options.loadExternalAuthority))\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Invalid public history verification scope\",\n );\n if (\n options.source.head.principalType === \"organization\" &&\n options.source.head.principalId !== options.organizationId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public organization history is outside its scope\",\n );\n // Validate the caller's pinned head before any cache or transport access.\n createPrincipalPolicyHistoryVerifier({\n principalType: options.source.head.principalType,\n principalId: options.source.head.principalId,\n retainedReferences: [options.source.head],\n });\n const protection = ownPrincipalHistoryProtection(options.protection);\n protection.context = serializeKeyingCanonicalJson([\n \"tearleads.sdk.public-principal-history.v2\",\n protection.context,\n options.strictAdmins === true,\n options.authorityGroupId ?? null,\n ]);\n const input = {\n ...options,\n source: structuredClone(options.source),\n protection,\n };\n try {\n return await recover(input, options.replay !== true);\n } finally {\n protection.localKey.fill(0);\n }\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { KeyingVerificationError, PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT, selectPrincipalPolicyAuthorization, verifyPrincipalPolicyCheckpoint, verifyPrincipalPolicyHistoryReferences, } from "../../../internal/crypto/index.js";
|
|
2
2
|
import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.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 { PrincipalHistoryEvidenceUnavailableError } from "../historyRecovery/principalHistoryRecoveryReferences.js";
|
|
6
6
|
async function selectBatch(input, versions, checkpointReference) {
|
|
7
7
|
assertProjectionVerificationCurrent(input.stillCurrent);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"selectPublicPrincipalHistory.js","sourceRoot":"","sources":["selectPublicPrincipalHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,kCAAkC,EAIlC,kCAAkC,EAElC,+BAA+B,EAC/B,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,0BAA0B,EAAE,MAAM,uEAAuE,CAAC;AACnH,OAAO,EAAE,6BAA6B,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"selectPublicPrincipalHistory.js","sourceRoot":"","sources":["selectPublicPrincipalHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,E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,CAAC;QACF,MAAM,QAAQ,GAAG,MAAM,WAAW,CAAC,KAAK,EAAE,KAAK,EAAE,mBAAmB,CAAC,CAAC,KAAK,CACzE,CAAC,KAAc,EAAE,EAAE;YACjB,IAAI,KAAK,YAAY,uBAAuB;gBAC1C,MAAM,IAAI,wCAAwC,CAAC,KAAK,CAAC,CAAC;YAC5D,MAAM,KAAK,CAAC;QACd,CAAC,CACF,CAAC;QACF,uBAAuB,CAAC,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,QAAQ,EAAE,UAAU,CAAC,CAAC;QACxE,MAAM,MAAM,GAAG,MAAM,kCAAkC,CAAC,QAAQ,CAAC,CAAC;QAClE,IAAI,CAAC,MAAM,CAAC,EAAE;YAAE,MAAM,MAAM,CAAC,KAAK,CAAC;QACnC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAC9B,CAAC;IACD,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IACxD,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT,\n type PrincipalPolicyCheckpoint,\n type PrincipalPolicyHistoryReferenceProof,\n type ReferencedPrincipalHead,\n selectPrincipalPolicyAuthorization,\n type VerifiedPrincipalPolicySelection,\n verifyPrincipalPolicyCheckpoint,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { PrincipalHistoryRepository } from \"../../../data/persistence/principalHistory/principalHistoryRepository\";\nimport { principalHeadMatchesReference } from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { PrincipalHistoryEvidenceUnavailableError } from \"../historyRecovery/principalHistoryRecoveryReferences\";\nimport type { RecoveredPublicPrincipalHistory } from \"./publicPrincipalHistoryTypes\";\n\ninterface PublicHistorySelectionInput {\n readonly execSql: ExecSql;\n readonly recovered: RecoveredPublicPrincipalHistory;\n readonly references: readonly ReferencedPrincipalHead[];\n readonly checkpoint: PrincipalPolicyCheckpoint | null;\n readonly deferCheckpointCheck?: boolean | undefined;\n readonly includeGenesis?: boolean;\n readonly stillCurrent: () => boolean;\n}\n\nasync function selectBatch(\n input: PublicHistorySelectionInput,\n versions: readonly number[],\n checkpointReference: PrincipalPolicyHistoryReferenceProof | undefined,\n) {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const proofs = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryReferences({\n ...input.recovered,\n versions,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n const selected = await verifyPrincipalPolicyHistoryReferences({\n history: input.recovered.history,\n references: proofs,\n checkpointReference,\n });\n if (!selected.ok) throw selected.error;\n return selected.value;\n}\n\nasync function loadCheckpointProof(\n input: PublicHistorySelectionInput,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): Promise<PrincipalPolicyHistoryReferenceProof | undefined> {\n let checkpointReference: PrincipalPolicyHistoryReferenceProof | undefined;\n try {\n if (checkpoint)\n checkpointReference = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryReference({\n ...input.recovered,\n version: checkpoint.version,\n });\n } catch (error) {\n if (error instanceof KeyingVerificationError)\n throw new PrincipalHistoryEvidenceUnavailableError(error);\n throw error;\n }\n return checkpointReference;\n}\n\nfunction checkSelectedReferences(\n input: PublicHistorySelectionInput,\n references: readonly ReferencedPrincipalHead[],\n batch: readonly number[],\n selected: Awaited<ReturnType<typeof selectBatch>>,\n checkpoint: PrincipalPolicyCheckpoint | null,\n) {\n // Authenticate the disposable proof before comparing caller citations or pins.\n for (const reference of references.filter(({ version }) =>\n batch.includes(version),\n ))\n if (\n !selected.retainedEntries.some(({ state }) =>\n principalHeadMatchesReference(state, reference),\n )\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history citation differs from its verified entry\",\n );\n if (!input.deferCheckpointCheck)\n verifyPrincipalPolicyCheckpoint({\n chain: selected.retainedEntries.map((entry) => ({\n ...entry,\n projection: [...entry.projection],\n grants: [...entry.grants],\n })),\n currentState: selected.currentEntry.state,\n localCheckpoint: checkpoint,\n });\n}\n\n/** Select bounded proof batches without admitting or advancing durable pins. */\nexport async function selectPublicPrincipalHistory(\n input: PublicHistorySelectionInput,\n): Promise<VerifiedPrincipalPolicySelection[]> {\n const references = structuredClone(input.references);\n const checkpoint = input.checkpoint && { ...input.checkpoint };\n const head = input.recovered.history.currentEntry.state;\n if (\n !input.deferCheckpointCheck &&\n checkpoint &&\n checkpoint.version > head.version\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Public history cannot connect to the newer durable checkpoint\",\n );\n if (\n references.some(\n (reference) =>\n reference.principalType !== head.principalType ||\n reference.principalId !== head.principalId ||\n reference.version > head.version,\n )\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history reference is outside the verified prefix\",\n );\n const versions = [\n ...new Set([\n ...(input.includeGenesis ? [1] : []),\n ...references.map(({ version }) => version),\n head.version,\n ]),\n ];\n const policies: VerifiedPrincipalPolicySelection[] = [];\n const checkpointReference = await loadCheckpointProof(\n input,\n checkpoint && checkpoint.version <= head.version ? checkpoint : null,\n );\n for (\n let offset = 0;\n offset < versions.length;\n offset += PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT\n ) {\n const batch = versions.slice(\n offset,\n offset + PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT,\n );\n const selected = await selectBatch(input, batch, checkpointReference).catch(\n (error: unknown) => {\n if (error instanceof KeyingVerificationError)\n throw new PrincipalHistoryEvidenceUnavailableError(error);\n throw error;\n },\n );\n checkSelectedReferences(input, references, batch, selected, checkpoint);\n const policy = await selectPrincipalPolicyAuthorization(selected);\n if (!policy.ok) throw policy.error;\n policies.push(policy.value);\n }\n assertProjectionVerificationCurrent(input.stillCurrent);\n return policies;\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type ReferencedPrincipalHead } from "../../../internal/crypto/index.js";
|
|
2
|
-
import { type OrganizationAuthorityDescriptor } from "../../../data/
|
|
2
|
+
import { type OrganizationAuthorityDescriptor } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
|
|
3
3
|
import { type RecoveredPrincipalPolicyHistory, type RecoverPrincipalPolicyHistoryOptions } from "../historyRecovery/principalHistoryRecoveryTypes.js";
|
|
4
4
|
export type PrincipalRecoveryContext = Omit<RecoverPrincipalPolicyHistoryOptions, "expectedHead" | "retainedReferences" | "historyVerification" | "loadExternalAuthority">;
|
|
5
5
|
export interface RecoveredPolicyDirectory extends RecoveredPrincipalPolicyHistory {
|
|
@@ -2,7 +2,7 @@ import { KeyingVerificationError, verifyPrincipalPolicyHistoryReferences, } from
|
|
|
2
2
|
import { isPrincipalPolicyPageResponse, isPrincipalPolicyUnchangedResponse, } from "../../../internal/validators/response/index.js";
|
|
3
3
|
import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
|
|
4
4
|
import { PrincipalHistoryRepository } from "../../../data/persistence/principalHistory/principalHistoryRepository.js";
|
|
5
|
-
import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, } from "../../../data/
|
|
5
|
+
import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
|
|
6
6
|
import { principalHistoryEvidenceScopeId } from "../../../data/principals/principalHistoryPrefixProtection.js";
|
|
7
7
|
import { directoryHistoryProtection } from "../../../data/principals/principalHistoryScopeProtection.js";
|
|
8
8
|
import { loadVerifiedPrincipalHistoryPrefix } from "../historyRecovery/principalHistoryRecoveryPrefix.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalRecoveryDirectory.js","sourceRoot":"","sources":["principalRecoveryDirectory.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,EAEvB,sCAAsC,GACvC,MAAM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SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,OAAO,KAAK,CAAC,CAAC;YACzE,CAAC,CAAC,UAAU;YACZ,CAAC,CAAC,CAAC,SAAS,CAAC,OAAO,CAAC,EAAE,GAAG,UAAU,CAAC;KACxC,CAAC,CAAC;IACH,IAAI,UAA2C,CAAC;IAChD,IAAI,CAAC;QACH,UAAU,GAAG,oCAAoC,CAC/C,SAAS,CAAC,OAAO,CAAC,cAAc,CAAC,UAAU,CAC5C,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,2CAA2C,CAC5C,CAAC;IACJ,CAAC;IACD,IAAI,UAAU,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;QACpD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,6CAA6C,CAC9C,CAAC;IACJ,OAAO,EAAE,GAAG,SAAS,EAAE,UAAU,EAAE,CAAC;AACtC,CAAC","sourcesContent":["import type { RequestSuccess } from \"@tearleads/api-client\";\nimport {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport {\n isPrincipalPolicyPageResponse,\n isPrincipalPolicyUnchangedResponse,\n type PrincipalPolicyPageResponse,\n} from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { PrincipalHistoryRepository } from \"../../../data/persistence/principalHistory/principalHistoryRepository\";\nimport {\n type OrganizationAuthorityDescriptor,\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { principalHistoryEvidenceScopeId } from \"../../../data/principals/principalHistoryPrefixProtection\";\nimport { directoryHistoryProtection } from \"../../../data/principals/principalHistoryScopeProtection\";\nimport { loadVerifiedPrincipalHistoryPrefix } from \"../historyRecovery/principalHistoryRecoveryPrefix\";\nimport {\n PrincipalPolicyHistoryReadError,\n type RecoveredPrincipalPolicyHistory,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"../historyRecovery/principalHistoryRecoveryTypes\";\nimport { recoverPrincipalPolicyHistory } from \"../historyRecovery/recoverPrincipalPolicyHistory\";\nimport { reusePrincipalDiscoveryPage } from \"./principalRecoveryDiscoveryPage\";\n\nexport type PrincipalRecoveryContext = Omit<\n RecoverPrincipalPolicyHistoryOptions,\n | \"expectedHead\"\n | \"retainedReferences\"\n | \"historyVerification\"\n | \"loadExternalAuthority\"\n>;\n\nexport interface RecoveredPolicyDirectory\n extends RecoveredPrincipalPolicyHistory {\n readonly descriptor: OrganizationAuthorityDescriptor;\n}\n\nexport class PrincipalRecoveryDirectoryAdvanced extends Error {}\n\nfunction exactHead(state: ReferencedPrincipalHead): ReferencedPrincipalHead {\n return {\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}\n\ninterface DiscoveredDirectoryHead {\n readonly head: ReferencedPrincipalHead;\n readonly genesis: ReferencedPrincipalHead;\n readonly historyReader: PrincipalRecoveryContext[\"historyReader\"];\n}\n\nfunction assertDiscoveryCurrent(input: PrincipalRecoveryContext): void {\n assertProjectionVerificationCurrent(\n () => !input.signal?.aborted && input.stillCurrent(),\n );\n}\n\n/**\n * The directory head and genesis this device has completely authenticated,\n * from its protected verified prefix, or null when it holds none.\n */\nasync function loadHeldDirectoryHead(\n input: PrincipalRecoveryContext,\n): Promise<Omit<DiscoveredDirectoryHead, \"historyReader\"> | null> {\n const principal = {\n principalType: \"organization\" as const,\n principalId: input.organizationId,\n };\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: input.organizationId,\n head: principal,\n protection: input.protection,\n });\n const prefix = await loadVerifiedPrincipalHistoryPrefix(\n input,\n principal,\n scopeId,\n );\n if (!prefix) return null;\n const history = prefix.verifier.finish(prefix.head);\n if (!history.ok) throw history.error;\n const genesis = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryReference({\n scopeId,\n history: history.value,\n version: 1,\n });\n const selected = await verifyPrincipalPolicyHistoryReferences({\n history: history.value,\n references: [genesis],\n });\n if (!selected.ok) throw selected.error;\n return { head: exactHead(prefix.head), genesis: genesis.reference };\n}\n\n/** Disposable local evidence never refuses an online discovery; it reads fully. */\nasync function loadHeldDirectoryHeadOnline(input: PrincipalRecoveryContext) {\n try {\n return await loadHeldDirectoryHead(input);\n } catch {\n assertDiscoveryCurrent(input);\n return null;\n }\n}\n\nfunction discoveredPage(\n input: PrincipalRecoveryContext,\n result: RequestSuccess<PrincipalPolicyPageResponse>,\n): DiscoveredDirectoryHead {\n const state = result.data.currentState;\n const first = result.data.previousStates[0]?.state ?? state;\n if (\n first.version !== 1 ||\n first.principalType !== \"organization\" ||\n first.principalId !== input.organizationId\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization directory discovery requires genesis\",\n );\n return {\n historyReader: reusePrincipalDiscoveryPage(input.historyReader, result),\n genesis: exactHead(first),\n // The requested identity, never the page's: discovery picks only a pin.\n head: {\n principalType: \"organization\",\n principalId: input.organizationId,\n version: state.version,\n stateHash: state.stateHash,\n keyEpoch: state.keyEpoch,\n keyFingerprint: state.keyFingerprint,\n },\n };\n}\n\n/**\n * Ask whether the held head is still live. An `unchanged` reply naming exactly\n * that head reuses it; recovery then authenticates the held artifacts again\n * and reloads the checkpoint. Any other reply that is not a page leaves the\n * caller to read the first page unconditionally.\n */\nasync function discoverConditionally(\n input: PrincipalRecoveryContext,\n discover: NonNullable<\n PrincipalRecoveryContext[\"historyReader\"][\"getPrincipalPolicyDiscovery\"]\n >,\n): Promise<DiscoveredDirectoryHead | null> {\n const held = await loadHeldDirectoryHeadOnline(input);\n assertDiscoveryCurrent(input);\n const result = await discover(\"organization\", input.organizationId, {\n signal: input.signal,\n ifHead: held?.head,\n });\n if (!result.ok) throw new PrincipalPolicyHistoryReadError(result);\n assertDiscoveryCurrent(input);\n const reply = result.data;\n if (isPrincipalPolicyUnchangedResponse(reply))\n return held && principalHeadMatchesReference(reply.head, held.head)\n ? { ...held, historyReader: input.historyReader }\n : null;\n // Anything but the strict bare head must be a page; otherwise read again.\n return isPrincipalPolicyPageResponse(reply)\n ? discoveredPage(input, { ok: true, data: reply })\n : null;\n}\n\n/** An unverified discovery read chooses a pin; recovery must authenticate it. */\nasync function discoverDirectoryHead(\n input: PrincipalRecoveryContext,\n): Promise<DiscoveredDirectoryHead> {\n assertDiscoveryCurrent(input);\n if (input.offline) {\n const held = await loadHeldDirectoryHead(input);\n if (!held)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization directory is unavailable offline\",\n );\n return { ...held, historyReader: input.historyReader };\n }\n const discover = input.historyReader.getPrincipalPolicyDiscovery;\n const conditional = discover\n ? await discoverConditionally(input, discover)\n : null;\n if (conditional) return conditional;\n for await (const result of input.historyReader.getPrincipalPolicyPages(\n \"organization\",\n input.organizationId,\n { signal: input.signal },\n )) {\n if (!result.ok) throw new PrincipalPolicyHistoryReadError(result);\n assertDiscoveryCurrent(input);\n return discoveredPage(input, result);\n }\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization directory head is unavailable\",\n );\n}\n\nexport async function recoverPolicyDirectory(\n input: PrincipalRecoveryContext,\n references: readonly ReferencedPrincipalHead[],\n selected?: RecoveredPolicyDirectory,\n): Promise<RecoveredPolicyDirectory> {\n const scoped = {\n ...input,\n protection: directoryHistoryProtection(input.protection),\n };\n const {\n head: expectedHead,\n genesis,\n historyReader,\n } = selected\n ? {\n head: exactHead(selected.policy.state),\n genesis: selected.policy.retainedHistory[0]?.state,\n historyReader: input.historyReader,\n }\n : await discoverDirectoryHead(scoped);\n if (genesis?.version !== 1)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization directory recovery requires verified genesis\",\n );\n if (references.some((reference) => reference.version > expectedHead.version))\n throw new PrincipalRecoveryDirectoryAdvanced();\n const recovered = await recoverPrincipalPolicyHistory({\n ...scoped,\n historyReader,\n expectedHead,\n retainedReferences: references.some((reference) => reference.version === 1)\n ? references\n : [exactHead(genesis), ...references],\n });\n let descriptor: OrganizationAuthorityDescriptor;\n try {\n descriptor = parseOrganizationAuthorityDescriptor(\n recovered.current.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 { ...recovered, descriptor };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"principalRecoveryDirectory.js","sourceRoot":"","sources":["principalRecoveryDirectory.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,EAEvB,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,6BAA6B,EAC7B,kCAAkC,GAEnC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,0BAA0B,EAAE,MAAM,uEAAuE,CAAC;AACnH,OAAO,EAEL,oCAAoC,EACpC,6BAA6B,GAC9B,MAAM,kEAAkE,CAAC;AAC1E,OAAO,EAAE,+BAA+B,EAAE,MAAM,2DAA2D,CAAC;AAC5G,OAAO,EAAE,0BAA0B,EAAE,MAAM,0DAA0D,CAAC;AACtG,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AACvG,OAAO,EACL,+BAA+B,GAGhC,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EAAE,6BAA6B,EAAE,MAAM,kDAAkD,CAAC;AACjG,OAAO,EAAE,2BAA2B,EAAE,MAAM,kCAAkC,CAAC;AAe/E,MAAM,OAAO,kCAAmC,SAAQ,KAAK;CAAG;AAEhE,SAAS,SAAS,CAAC,KAA8B;IAC/C,OAAO;QACL,aAAa,EAAE,KAAK,CAAC,aAAa;QAClC,WAAW,EAAE,K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,KAAK;YAClD,aAAa,EAAE,KAAK,CAAC,aAAa;SACnC;QACH,CAAC,CAAC,MAAM,qBAAqB,CAAC,MAAM,CAAC,CAAC;IACxC,IAAI,OAAO,EAAE,OAAO,KAAK,CAAC;QACxB,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,2DAA2D,CAC5D,CAAC;IACJ,IAAI,UAAU,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,OAAO,GAAG,YAAY,CAAC,OAAO,CAAC;QAC1E,MAAM,IAAI,kCAAkC,EAAE,CAAC;IACjD,MAAM,SAAS,GAAG,MAAM,6BAA6B,CAAC;QACpD,GAAG,MAAM;QACT,aAAa;QACb,YAAY;QACZ,kBAAkB,EAAE,UAAU,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,OAAO,KAAK,CAAC,CAAC;YACzE,CAAC,CAAC,UAAU;YACZ,CAAC,CAAC,CAAC,SAAS,CAAC,OAAO,CAAC,EAAE,GAAG,UAAU,CAAC;KACxC,CAAC,CAAC;IACH,IAAI,UAA2C,CAAC;IAChD,IAAI,CAAC;QACH,UAAU,GAAG,oCAAoC,CAC/C,SAAS,CAAC,OAAO,CAAC,cAAc,CAAC,UAAU,CAC5C,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,2CAA2C,CAC5C,CAAC;IACJ,CAAC;IACD,IAAI,UAAU,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;QACpD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,6CAA6C,CAC9C,CAAC;IACJ,OAAO,EAAE,GAAG,SAAS,EAAE,UAAU,EAAE,CAAC;AACtC,CAAC","sourcesContent":["import type { RequestSuccess } from \"@tearleads/api-client\";\nimport {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport {\n isPrincipalPolicyPageResponse,\n isPrincipalPolicyUnchangedResponse,\n type PrincipalPolicyPageResponse,\n} from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { PrincipalHistoryRepository } from \"../../../data/persistence/principalHistory/principalHistoryRepository\";\nimport {\n type OrganizationAuthorityDescriptor,\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport { principalHistoryEvidenceScopeId } from \"../../../data/principals/principalHistoryPrefixProtection\";\nimport { directoryHistoryProtection } from \"../../../data/principals/principalHistoryScopeProtection\";\nimport { loadVerifiedPrincipalHistoryPrefix } from \"../historyRecovery/principalHistoryRecoveryPrefix\";\nimport {\n PrincipalPolicyHistoryReadError,\n type RecoveredPrincipalPolicyHistory,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"../historyRecovery/principalHistoryRecoveryTypes\";\nimport { recoverPrincipalPolicyHistory } from \"../historyRecovery/recoverPrincipalPolicyHistory\";\nimport { reusePrincipalDiscoveryPage } from \"./principalRecoveryDiscoveryPage\";\n\nexport type PrincipalRecoveryContext = Omit<\n RecoverPrincipalPolicyHistoryOptions,\n | \"expectedHead\"\n | \"retainedReferences\"\n | \"historyVerification\"\n | \"loadExternalAuthority\"\n>;\n\nexport interface RecoveredPolicyDirectory\n extends RecoveredPrincipalPolicyHistory {\n readonly descriptor: OrganizationAuthorityDescriptor;\n}\n\nexport class PrincipalRecoveryDirectoryAdvanced extends Error {}\n\nfunction exactHead(state: ReferencedPrincipalHead): ReferencedPrincipalHead {\n return {\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}\n\ninterface DiscoveredDirectoryHead {\n readonly head: ReferencedPrincipalHead;\n readonly genesis: ReferencedPrincipalHead;\n readonly historyReader: PrincipalRecoveryContext[\"historyReader\"];\n}\n\nfunction assertDiscoveryCurrent(input: PrincipalRecoveryContext): void {\n assertProjectionVerificationCurrent(\n () => !input.signal?.aborted && input.stillCurrent(),\n );\n}\n\n/**\n * The directory head and genesis this device has completely authenticated,\n * from its protected verified prefix, or null when it holds none.\n */\nasync function loadHeldDirectoryHead(\n input: PrincipalRecoveryContext,\n): Promise<Omit<DiscoveredDirectoryHead, \"historyReader\"> | null> {\n const principal = {\n principalType: \"organization\" as const,\n principalId: input.organizationId,\n };\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: input.organizationId,\n head: principal,\n protection: input.protection,\n });\n const prefix = await loadVerifiedPrincipalHistoryPrefix(\n input,\n principal,\n scopeId,\n );\n if (!prefix) return null;\n const history = prefix.verifier.finish(prefix.head);\n if (!history.ok) throw history.error;\n const genesis = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryReference({\n scopeId,\n history: history.value,\n version: 1,\n });\n const selected = await verifyPrincipalPolicyHistoryReferences({\n history: history.value,\n references: [genesis],\n });\n if (!selected.ok) throw selected.error;\n return { head: exactHead(prefix.head), genesis: genesis.reference };\n}\n\n/** Disposable local evidence never refuses an online discovery; it reads fully. */\nasync function loadHeldDirectoryHeadOnline(input: PrincipalRecoveryContext) {\n try {\n return await loadHeldDirectoryHead(input);\n } catch {\n assertDiscoveryCurrent(input);\n return null;\n }\n}\n\nfunction discoveredPage(\n input: PrincipalRecoveryContext,\n result: RequestSuccess<PrincipalPolicyPageResponse>,\n): DiscoveredDirectoryHead {\n const state = result.data.currentState;\n const first = result.data.previousStates[0]?.state ?? state;\n if (\n first.version !== 1 ||\n first.principalType !== \"organization\" ||\n first.principalId !== input.organizationId\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization directory discovery requires genesis\",\n );\n return {\n historyReader: reusePrincipalDiscoveryPage(input.historyReader, result),\n genesis: exactHead(first),\n // The requested identity, never the page's: discovery picks only a pin.\n head: {\n principalType: \"organization\",\n principalId: input.organizationId,\n version: state.version,\n stateHash: state.stateHash,\n keyEpoch: state.keyEpoch,\n keyFingerprint: state.keyFingerprint,\n },\n };\n}\n\n/**\n * Ask whether the held head is still live. An `unchanged` reply naming exactly\n * that head reuses it; recovery then authenticates the held artifacts again\n * and reloads the checkpoint. Any other reply that is not a page leaves the\n * caller to read the first page unconditionally.\n */\nasync function discoverConditionally(\n input: PrincipalRecoveryContext,\n discover: NonNullable<\n PrincipalRecoveryContext[\"historyReader\"][\"getPrincipalPolicyDiscovery\"]\n >,\n): Promise<DiscoveredDirectoryHead | null> {\n const held = await loadHeldDirectoryHeadOnline(input);\n assertDiscoveryCurrent(input);\n const result = await discover(\"organization\", input.organizationId, {\n signal: input.signal,\n ifHead: held?.head,\n });\n if (!result.ok) throw new PrincipalPolicyHistoryReadError(result);\n assertDiscoveryCurrent(input);\n const reply = result.data;\n if (isPrincipalPolicyUnchangedResponse(reply))\n return held && principalHeadMatchesReference(reply.head, held.head)\n ? { ...held, historyReader: input.historyReader }\n : null;\n // Anything but the strict bare head must be a page; otherwise read again.\n return isPrincipalPolicyPageResponse(reply)\n ? discoveredPage(input, { ok: true, data: reply })\n : null;\n}\n\n/** An unverified discovery read chooses a pin; recovery must authenticate it. */\nasync function discoverDirectoryHead(\n input: PrincipalRecoveryContext,\n): Promise<DiscoveredDirectoryHead> {\n assertDiscoveryCurrent(input);\n if (input.offline) {\n const held = await loadHeldDirectoryHead(input);\n if (!held)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization directory is unavailable offline\",\n );\n return { ...held, historyReader: input.historyReader };\n }\n const discover = input.historyReader.getPrincipalPolicyDiscovery;\n const conditional = discover\n ? await discoverConditionally(input, discover)\n : null;\n if (conditional) return conditional;\n for await (const result of input.historyReader.getPrincipalPolicyPages(\n \"organization\",\n input.organizationId,\n { signal: input.signal },\n )) {\n if (!result.ok) throw new PrincipalPolicyHistoryReadError(result);\n assertDiscoveryCurrent(input);\n return discoveredPage(input, result);\n }\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization directory head is unavailable\",\n );\n}\n\nexport async function recoverPolicyDirectory(\n input: PrincipalRecoveryContext,\n references: readonly ReferencedPrincipalHead[],\n selected?: RecoveredPolicyDirectory,\n): Promise<RecoveredPolicyDirectory> {\n const scoped = {\n ...input,\n protection: directoryHistoryProtection(input.protection),\n };\n const {\n head: expectedHead,\n genesis,\n historyReader,\n } = selected\n ? {\n head: exactHead(selected.policy.state),\n genesis: selected.policy.retainedHistory[0]?.state,\n historyReader: input.historyReader,\n }\n : await discoverDirectoryHead(scoped);\n if (genesis?.version !== 1)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization directory recovery requires verified genesis\",\n );\n if (references.some((reference) => reference.version > expectedHead.version))\n throw new PrincipalRecoveryDirectoryAdvanced();\n const recovered = await recoverPrincipalPolicyHistory({\n ...scoped,\n historyReader,\n expectedHead,\n retainedReferences: references.some((reference) => reference.version === 1)\n ? references\n : [exactHead(genesis), ...references],\n });\n let descriptor: OrganizationAuthorityDescriptor;\n try {\n descriptor = parseOrganizationAuthorityDescriptor(\n recovered.current.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 { ...recovered, descriptor };\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 { PrincipalHistoryRecoveryRaceError } from "../historyRecovery/principalHistoryRecoveryTypes.js";
|
|
5
5
|
import { recoverWithPrincipalOutageFallback } from "./principalRecoveryOutage.js";
|
|
6
6
|
/** Reuse exact current artifacts, or a proved historical page within a newer prefix. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalRecoveryLocalPreference.js","sourceRoot":"","sources":["principalRecoveryLocalPreference.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,6BAA6B,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"principalRecoveryLocalPreference.js","sourceRoot":"","sources":["principalRecoveryLocalPreference.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,6BAA6B,EAAE,MAAM,kEAAkE,CAAC;AACjH,OAAO,EAAE,iCAAiC,EAAE,MAAM,kDAAkD,CAAC;AAKrG,OAAO,EAAE,kCAAkC,EAAE,MAAM,2BAA2B,CAAC;AAE/E,wFAAwF;AACxF,MAAM,CAAC,KAAK,UAAU,mCAAmC,CACvD,OAA2C,EAC3C,OAAmD,EACnD,kBAA2B,EAC3B,wBAAwB,GAAG,KAAK;IAEhC,IAAI,kBAAkB,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;QAC3C,IAAI,CAAC;YACH,MAAM,KAAK,GAAG,MAAM,OAAO,CAAC;gBAC1B,GAAG,OAAO;gBACV,OAAO,EAAE,IAAI;aACd,CAAC,CAAC;YACH,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;YAC1D,IACE,wBAAwB;gBACxB,OAAO,CAAC,WAAW;gBACnB,6BAA6B,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,SAAS,CAAC;gBAEpE,OAAO,KAAK,CAAC;QACjB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;YAC1D,IACE,CAAC,CAAC,KAAK,YAAY,iCAAiC,CAAC;gBACrD,CAAC,CACC,KAAK,YAAY,uBAAuB;oBACxC,KAAK,CAAC,IAAI,KAAK,oBAAoB,CACpC;gBAED,MAAM,KAAK,CAAC;QAChB,CAAC;IACH,CAAC;IACD,OAAO,kCAAkC,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;AAC9D,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { principalHeadMatchesReference } from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport { PrincipalHistoryRecoveryRaceError } from \"../historyRecovery/principalHistoryRecoveryTypes\";\nimport type {\n RecoverScopedPrincipalPolicyHistoryOptions,\n ScopedPrincipalPolicyRecoveryBatch,\n} from \"../historyRecovery/recoverScopedPrincipalPolicyHistory\";\nimport { recoverWithPrincipalOutageFallback } from \"./principalRecoveryOutage\";\n\n/** Reuse exact current artifacts, or a proved historical page within a newer prefix. */\nexport async function recoverWithPrincipalLocalPreference(\n recover: ScopedPrincipalPolicyRecoveryBatch,\n options: RecoverScopedPrincipalPolicyHistoryOptions,\n preferLocalCurrent: boolean,\n allowHistoricalReference = false,\n) {\n if (preferLocalCurrent && !options.offline) {\n try {\n const local = await recover({\n ...options,\n offline: true,\n });\n assertProjectionVerificationCurrent(options.stillCurrent);\n if (\n allowHistoricalReference ||\n options.historyPage ||\n principalHeadMatchesReference(local.policy.state, options.reference)\n )\n return local;\n } catch (error) {\n assertProjectionVerificationCurrent(options.stillCurrent);\n if (\n !(error instanceof PrincipalHistoryRecoveryRaceError) &&\n !(\n error instanceof KeyingVerificationError &&\n error.code === \"missing_dependency\"\n )\n )\n throw error;\n }\n }\n return recoverWithPrincipalOutageFallback(recover, options);\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { KeyingVerificationError, serializeKeyingCanonicalJson, } 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 { recoverPrincipalPolicyHistory } from "../historyRecovery/recoverPrincipalPolicyHistory.js";
|
|
5
5
|
import { recoverPolicyDirectory, } from "./principalRecoveryDirectory.js";
|
|
6
6
|
import { adminsMemoValidity, directoryMemoValidity, } from "./principalRecoveryMemoValidity.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalRecoveryMemo.js","sourceRoot":"","sources":["principalRecoveryMemo.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,6BAA6B,EAAE,MAAM,0DAA0D,CAAC;AAEzG,OAAO,EAAE,6BAA6B,EAAE,MAAM,kDAAkD,CAAC;AACjG,OAAO,EAGL,sBAAsB,GACvB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,kBAAkB,EAClB,qBAAqB,GAEtB,MAAM,iCAAiC,CAAC;AAwBzC,2EAA2E;AAC3E,SAAS,SAAS,CAChB,KAAmB,EACnB,QAA0C;IAE1C,OAAO,KAAK,CAAC,KAAK,KAAK,QAAQ,CAAC,KAAK,EAAE,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;AAClE,CAAC;AAED,SAAS,KAAK,CACZ,IAAyB,EACzB,GAAW,EACX,OAA8B;IAE9B,IAAI,IAAI,EAAE,GAAG,CAAC,GAAG,CAAC,KAAK,OAAO;QAAE,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AACnD,CAAC;AAED;;;;;;;GAOG;AACH,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,MAAM,QAAQ,GAAG,IAAI,EAAE,WAAW,CAAC,GAAG,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC,CAAC;YACjE,IACE,IAAI;gBACJ,QAAQ;gBACR,UAAU,CAAC,MAAM,GAAG,CAAC;gBACrB,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,aAAa,CAAC;gBAEpC,4EAA4E;gBAC5E,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,aAAa,EAAE,QAAQ,CAAC,CAAC;YAChD,OAAO,KAAK,CAAC;QACf,CAAC;QACD,MAAM,EAAE,KAAK,EACX,YAAqC,EACrC,qBAAyD,EAAE,EAC3D,EAAE,CACF,KAAK,CACH,MAAM,kBAAkB,CACtB,KAAK,EACL,IAAI,EAAE,MAAM,EACZ,KAAK,EACL,YAAY,EACZ,kBAAkB,CACnB,CACF;KACJ,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n serializeKeyingCanonicalJson,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { principalHeadMatchesReference } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport type { RecoveredPrincipalPolicyHistory } from \"../historyRecovery/principalHistoryRecoveryTypes\";\nimport { recoverPrincipalPolicyHistory } from \"../historyRecovery/recoverPrincipalPolicyHistory\";\nimport {\n type PrincipalRecoveryContext,\n type RecoveredPolicyDirectory,\n recoverPolicyDirectory,\n} from \"./principalRecoveryDirectory\";\nimport {\n adminsMemoValidity,\n directoryMemoValidity,\n type PrincipalRecoveryMemoValidity,\n} from \"./principalRecoveryMemoValidity\";\n\ninterface MemoEntry<T> {\n readonly value: T;\n /** The producing call's private lease and caller lifetime. */\n readonly stillCurrent: () => boolean;\n /** Organization hint epoch observed before the reads that produced value. */\n readonly epoch: number;\n}\n\ntype Memo<T> = Map<string, Promise<MemoEntry<T>>>;\n\n/** A value handed out with every lifetime it depends on. */\ninterface Leased<T> {\n readonly value: T;\n /** The consumer's lifetime and every producer lifetime behind value. */\n readonly stillCurrent: () => boolean;\n}\n\nexport interface PrincipalRecoveryMemo {\n readonly directories: Memo<RecoveredPolicyDirectory>;\n readonly admins: Memo<RecoveredPrincipalPolicyHistory>;\n}\n\n/** Synchronous: no hint and no lease end since the entry's reads began. */\nfunction entryLive<T>(\n entry: MemoEntry<T>,\n validity: PrincipalRecoveryMemoValidity<T>,\n): boolean {\n return entry.epoch === validity.epoch() && entry.stillCurrent();\n}\n\nfunction evict<T>(\n memo: Memo<T> | undefined,\n key: string,\n pending: Promise<MemoEntry<T>>,\n): void {\n if (memo?.get(key) === pending) memo.delete(key);\n}\n\n/**\n * Return a live entry, evicting one whose producer lease ended, that predates\n * an organization hint, or that a durable pin has moved past. Liveness is\n * checked again after every await, so a hint or lease end during the pin\n * reads also evicts. The caller rechecks synchronously before use. A pin read\n * is a snapshot; a pin that advances later is caught by the checkpoint reload\n * in recovery, the caller's checkpoint refresh, and atomic admission.\n */\nasync function reusableEntry<T>(\n memo: Memo<T> | undefined,\n key: string,\n validity: PrincipalRecoveryMemoValidity<T>,\n): Promise<\n { entry: MemoEntry<T>; pending: Promise<MemoEntry<T>> } | undefined\n> {\n const pending = memo?.get(key);\n if (!pending) return undefined;\n const entry = await pending.catch(() => undefined);\n if (\n entry &&\n entryLive(entry, validity) &&\n (await validity.covers(entry.value)) &&\n entryLive(entry, validity)\n )\n return { entry, pending };\n evict(memo, key, pending);\n return undefined;\n}\n\n/**\n * Share authenticated results within one workflow operation. A later caller\n * never receives a result whose producer lease ended, that predates an\n * organization hint, or that a durable pin has moved past; it recovers again.\n * A result derived from a reused source keeps the source's epoch, so a hint\n * that arrives before it is stored still evicts it. Every value is handed out\n * with the consumer's lifetime and its producer's, so a producer that expires\n * after hand-out still invalidates the consumer's use.\n */\nasync function memoPrincipalRecovery<T>(\n memo: Memo<T> | undefined,\n key: string,\n stillCurrent: () => boolean,\n validity: PrincipalRecoveryMemoValidity<T>,\n sourceEpoch: number | undefined,\n work: () => Promise<T>,\n): Promise<Leased<T>> {\n assertProjectionVerificationCurrent(stillCurrent);\n const reused = await reusableEntry(memo, key, validity);\n if (reused) {\n const { entry } = reused;\n if (entryLive(entry, validity)) {\n assertProjectionVerificationCurrent(stillCurrent);\n return {\n value: entry.value,\n stillCurrent: () => stillCurrent() && entry.stillCurrent(),\n };\n }\n evict(memo, key, reused.pending);\n }\n // Observed before work starts its reads; a derived result keeps its source's.\n const epoch = sourceEpoch ?? validity.epoch();\n const pending = work().then((value) => ({ value, stillCurrent, epoch }));\n memo?.set(key, pending);\n const result = await pending.catch((error: unknown) => {\n evict(memo, key, pending);\n throw error;\n });\n // A hint during production leaves this caller's in-flight view, never a\n // stored one: the stale epoch would evict it anyway.\n if (result.epoch !== validity.epoch()) evict(memo, key, pending);\n assertProjectionVerificationCurrent(result.stillCurrent);\n assertProjectionVerificationCurrent(stillCurrent);\n // stillCurrent already includes the lifetime of a derived value's source.\n return { value: result.value, stillCurrent };\n}\n\nfunction fallsBackOnline(\n input: PrincipalRecoveryContext,\n error: unknown,\n): boolean {\n return (\n !input.offline &&\n error instanceof KeyingVerificationError &&\n error.code === \"missing_dependency\"\n );\n}\n\nasync function readMemoizedAdmins(\n input: PrincipalRecoveryContext,\n memo: Memo<RecoveredPrincipalPolicyHistory> | undefined,\n scope: readonly (string | boolean)[],\n expectedHead: ReferencedPrincipalHead,\n retainedReferences: readonly ReferencedPrincipalHead[],\n) {\n // Every recovered Current already retains its own exact head.\n const references = retainedReferences.filter(\n (reference) => !principalHeadMatchesReference(expectedHead, reference),\n );\n const key = (selected: readonly ReferencedPrincipalHead[]) =>\n serializeKeyingCanonicalJson([\n ...scope,\n { ...expectedHead },\n selected.map((reference) => ({ ...reference })),\n ]);\n const validity = adminsMemoValidity(input, expectedHead);\n const known = (await reusableEntry(memo, key([]), validity))?.entry;\n const sourceCurrent = known?.stillCurrent ?? (() => true);\n const current = () =>\n !input.signal?.aborted && input.stillCurrent() && sourceCurrent();\n return memoPrincipalRecovery(\n memo,\n key(references),\n current,\n validity,\n known?.epoch,\n async () => {\n const options = {\n ...input,\n expectedHead,\n retainedReferences,\n historyVerification: \"direct-admins\" as const,\n stillCurrent: current,\n };\n if (known) {\n try {\n // A freshly verified exact head only needs local proofs for additional\n // citations; their signature and private-root checks still run.\n return await recoverPrincipalPolicyHistory({\n ...options,\n offline: true,\n });\n } catch (error) {\n assertProjectionVerificationCurrent(current);\n if (!fallsBackOnline(input, error)) throw error;\n }\n }\n return recoverPrincipalPolicyHistory(options);\n },\n );\n}\n\nasync function readMemoizedDirectory(\n input: PrincipalRecoveryContext,\n memo: Memo<RecoveredPolicyDirectory> | undefined,\n key: (references: readonly ReferencedPrincipalHead[]) => string,\n references: readonly ReferencedPrincipalHead[],\n) {\n const validity = directoryMemoValidity(input);\n const known =\n references.length > 0\n ? (await reusableEntry(memo, key([]), validity))?.entry\n : undefined;\n const sourceCurrent = known?.stillCurrent ?? (() => true);\n const current = () =>\n !input.signal?.aborted && input.stillCurrent() && sourceCurrent();\n return memoPrincipalRecovery(\n memo,\n key(references),\n current,\n validity,\n known?.epoch,\n async () => {\n if (!known) return recoverPolicyDirectory(input, references);\n try {\n // Add authenticated historical citations to this operation's exact\n // directory view. A newer private prefix must not silently replace it.\n return await recoverPolicyDirectory(\n { ...input, offline: true, stillCurrent: current },\n references,\n known.value,\n );\n } catch (error) {\n assertProjectionVerificationCurrent(current);\n if (!fallsBackOnline(input, error)) throw error;\n }\n return recoverPolicyDirectory(\n { ...input, stillCurrent: current },\n references,\n known.value,\n );\n },\n );\n}\n\nexport function createPrincipalRecoveryReader(\n input: PrincipalRecoveryContext,\n memo?: PrincipalRecoveryMemo,\n) {\n const scope = [\n input.organizationId,\n input.protection.context,\n input.offline === true,\n ];\n const directoryKey = (references: readonly ReferencedPrincipalHead[]) =>\n serializeKeyingCanonicalJson([\n ...scope,\n references.map((reference) => ({ ...reference })),\n ]);\n // Every lifetime behind a value this reader handed out; its caller must\n // keep checking them at the point of use.\n const lifetimes: (() => boolean)[] = [];\n const lease = <T>(leased: Leased<T>): T => {\n lifetimes.push(leased.stillCurrent);\n return leased.value;\n };\n return {\n stillCurrent: () => lifetimes.every((current) => current()),\n directory: async (references: readonly ReferencedPrincipalHead[]) => {\n const value = lease(\n await readMemoizedDirectory(\n input,\n memo?.directories,\n directoryKey,\n references,\n ),\n );\n // Retaining extra citations does not prevent this authenticated directory\n // from satisfying a later read with no selected historical references.\n const unselectedKey = directoryKey([]);\n const selected = memo?.directories.get(directoryKey(references));\n if (\n memo &&\n selected &&\n references.length > 0 &&\n !memo.directories.has(unselectedKey)\n )\n // The alias keeps the original lease and validity; either ending evicts it.\n memo.directories.set(unselectedKey, selected);\n return value;\n },\n admins: async (\n expectedHead: ReferencedPrincipalHead,\n retainedReferences: readonly ReferencedPrincipalHead[] = [],\n ) =>\n lease(\n await readMemoizedAdmins(\n input,\n memo?.admins,\n scope,\n expectedHead,\n retainedReferences,\n ),\n ),\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"principalRecoveryMemo.js","sourceRoot":"","sources":["principalRecoveryMemo.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,6BAA6B,EAAE,MAAM,kEAAkE,CAAC;AAEjH,OAAO,EAAE,6BAA6B,EAAE,MAAM,kDAAkD,CAAC;AACjG,OAAO,EAGL,sBAAsB,GACvB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,kBAAkB,EAClB,qBAAqB,GAEtB,MAAM,iCAAiC,CAAC;AAwBzC,2EAA2E;AAC3E,SAAS,SAAS,CAChB,KAAmB,EACnB,QAA0C;IAE1C,OAAO,KAAK,CAAC,KAAK,KAAK,QAAQ,CAAC,KAAK,EAAE,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC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AClE,MAAM,KAAK,GAAG,KAAK,CACjB,MAAM,qBAAqB,CACzB,KAAK,EACL,IAAI,EAAE,WAAW,EACjB,YAAY,EACZ,UAAU,CACX,CACF,CAAC;YACF,0EAA0E;YAC1E,uEAAuE;YACvE,MAAM,aAAa,GAAG,YAAY,CAAC,EAAE,CAAC,CAAC;YACvC,MAAM,QAAQ,GAAG,IAAI,EAAE,WAAW,CAAC,GAAG,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC,CAAC;YACjE,IACE,IAAI;gBACJ,QAAQ;gBACR,UAAU,CAAC,MAAM,GAAG,CAAC;gBACrB,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,aAAa,CAAC;gBAEpC,4EAA4E;gBAC5E,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,aAAa,EAAE,QAAQ,CAAC,CAAC;YAChD,OAAO,KAAK,CAAC;QACf,CAAC;QACD,MAAM,EAAE,KAAK,EACX,YAAqC,EACrC,qBAAyD,EAAE,EAC3D,EAAE,CACF,KAAK,CACH,MAAM,kBAAkB,CACtB,KAAK,EACL,IAAI,EAAE,MAAM,EACZ,KAAK,EACL,YAAY,EACZ,kBAAkB,CACnB,CACF;KACJ,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n serializeKeyingCanonicalJson,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { principalHeadMatchesReference } from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport type { RecoveredPrincipalPolicyHistory } from \"../historyRecovery/principalHistoryRecoveryTypes\";\nimport { recoverPrincipalPolicyHistory } from \"../historyRecovery/recoverPrincipalPolicyHistory\";\nimport {\n type PrincipalRecoveryContext,\n type RecoveredPolicyDirectory,\n recoverPolicyDirectory,\n} from \"./principalRecoveryDirectory\";\nimport {\n adminsMemoValidity,\n directoryMemoValidity,\n type PrincipalRecoveryMemoValidity,\n} from \"./principalRecoveryMemoValidity\";\n\ninterface MemoEntry<T> {\n readonly value: T;\n /** The producing call's private lease and caller lifetime. */\n readonly stillCurrent: () => boolean;\n /** Organization hint epoch observed before the reads that produced value. */\n readonly epoch: number;\n}\n\ntype Memo<T> = Map<string, Promise<MemoEntry<T>>>;\n\n/** A value handed out with every lifetime it depends on. */\ninterface Leased<T> {\n readonly value: T;\n /** The consumer's lifetime and every producer lifetime behind value. */\n readonly stillCurrent: () => boolean;\n}\n\nexport interface PrincipalRecoveryMemo {\n readonly directories: Memo<RecoveredPolicyDirectory>;\n readonly admins: Memo<RecoveredPrincipalPolicyHistory>;\n}\n\n/** Synchronous: no hint and no lease end since the entry's reads began. */\nfunction entryLive<T>(\n entry: MemoEntry<T>,\n validity: PrincipalRecoveryMemoValidity<T>,\n): boolean {\n return entry.epoch === validity.epoch() && entry.stillCurrent();\n}\n\nfunction evict<T>(\n memo: Memo<T> | undefined,\n key: string,\n pending: Promise<MemoEntry<T>>,\n): void {\n if (memo?.get(key) === pending) memo.delete(key);\n}\n\n/**\n * Return a live entry, evicting one whose producer lease ended, that predates\n * an organization hint, or that a durable pin has moved past. Liveness is\n * checked again after every await, so a hint or lease end during the pin\n * reads also evicts. The caller rechecks synchronously before use. A pin read\n * is a snapshot; a pin that advances later is caught by the checkpoint reload\n * in recovery, the caller's checkpoint refresh, and atomic admission.\n */\nasync function reusableEntry<T>(\n memo: Memo<T> | undefined,\n key: string,\n validity: PrincipalRecoveryMemoValidity<T>,\n): Promise<\n { entry: MemoEntry<T>; pending: Promise<MemoEntry<T>> } | undefined\n> {\n const pending = memo?.get(key);\n if (!pending) return undefined;\n const entry = await pending.catch(() => undefined);\n if (\n entry &&\n entryLive(entry, validity) &&\n (await validity.covers(entry.value)) &&\n entryLive(entry, validity)\n )\n return { entry, pending };\n evict(memo, key, pending);\n return undefined;\n}\n\n/**\n * Share authenticated results within one workflow operation. A later caller\n * never receives a result whose producer lease ended, that predates an\n * organization hint, or that a durable pin has moved past; it recovers again.\n * A result derived from a reused source keeps the source's epoch, so a hint\n * that arrives before it is stored still evicts it. Every value is handed out\n * with the consumer's lifetime and its producer's, so a producer that expires\n * after hand-out still invalidates the consumer's use.\n */\nasync function memoPrincipalRecovery<T>(\n memo: Memo<T> | undefined,\n key: string,\n stillCurrent: () => boolean,\n validity: PrincipalRecoveryMemoValidity<T>,\n sourceEpoch: number | undefined,\n work: () => Promise<T>,\n): Promise<Leased<T>> {\n assertProjectionVerificationCurrent(stillCurrent);\n const reused = await reusableEntry(memo, key, validity);\n if (reused) {\n const { entry } = reused;\n if (entryLive(entry, validity)) {\n assertProjectionVerificationCurrent(stillCurrent);\n return {\n value: entry.value,\n stillCurrent: () => stillCurrent() && entry.stillCurrent(),\n };\n }\n evict(memo, key, reused.pending);\n }\n // Observed before work starts its reads; a derived result keeps its source's.\n const epoch = sourceEpoch ?? validity.epoch();\n const pending = work().then((value) => ({ value, stillCurrent, epoch }));\n memo?.set(key, pending);\n const result = await pending.catch((error: unknown) => {\n evict(memo, key, pending);\n throw error;\n });\n // A hint during production leaves this caller's in-flight view, never a\n // stored one: the stale epoch would evict it anyway.\n if (result.epoch !== validity.epoch()) evict(memo, key, pending);\n assertProjectionVerificationCurrent(result.stillCurrent);\n assertProjectionVerificationCurrent(stillCurrent);\n // stillCurrent already includes the lifetime of a derived value's source.\n return { value: result.value, stillCurrent };\n}\n\nfunction fallsBackOnline(\n input: PrincipalRecoveryContext,\n error: unknown,\n): boolean {\n return (\n !input.offline &&\n error instanceof KeyingVerificationError &&\n error.code === \"missing_dependency\"\n );\n}\n\nasync function readMemoizedAdmins(\n input: PrincipalRecoveryContext,\n memo: Memo<RecoveredPrincipalPolicyHistory> | undefined,\n scope: readonly (string | boolean)[],\n expectedHead: ReferencedPrincipalHead,\n retainedReferences: readonly ReferencedPrincipalHead[],\n) {\n // Every recovered Current already retains its own exact head.\n const references = retainedReferences.filter(\n (reference) => !principalHeadMatchesReference(expectedHead, reference),\n );\n const key = (selected: readonly ReferencedPrincipalHead[]) =>\n serializeKeyingCanonicalJson([\n ...scope,\n { ...expectedHead },\n selected.map((reference) => ({ ...reference })),\n ]);\n const validity = adminsMemoValidity(input, expectedHead);\n const known = (await reusableEntry(memo, key([]), validity))?.entry;\n const sourceCurrent = known?.stillCurrent ?? (() => true);\n const current = () =>\n !input.signal?.aborted && input.stillCurrent() && sourceCurrent();\n return memoPrincipalRecovery(\n memo,\n key(references),\n current,\n validity,\n known?.epoch,\n async () => {\n const options = {\n ...input,\n expectedHead,\n retainedReferences,\n historyVerification: \"direct-admins\" as const,\n stillCurrent: current,\n };\n if (known) {\n try {\n // A freshly verified exact head only needs local proofs for additional\n // citations; their signature and private-root checks still run.\n return await recoverPrincipalPolicyHistory({\n ...options,\n offline: true,\n });\n } catch (error) {\n assertProjectionVerificationCurrent(current);\n if (!fallsBackOnline(input, error)) throw error;\n }\n }\n return recoverPrincipalPolicyHistory(options);\n },\n );\n}\n\nasync function readMemoizedDirectory(\n input: PrincipalRecoveryContext,\n memo: Memo<RecoveredPolicyDirectory> | undefined,\n key: (references: readonly ReferencedPrincipalHead[]) => string,\n references: readonly ReferencedPrincipalHead[],\n) {\n const validity = directoryMemoValidity(input);\n const known =\n references.length > 0\n ? (await reusableEntry(memo, key([]), validity))?.entry\n : undefined;\n const sourceCurrent = known?.stillCurrent ?? (() => true);\n const current = () =>\n !input.signal?.aborted && input.stillCurrent() && sourceCurrent();\n return memoPrincipalRecovery(\n memo,\n key(references),\n current,\n validity,\n known?.epoch,\n async () => {\n if (!known) return recoverPolicyDirectory(input, references);\n try {\n // Add authenticated historical citations to this operation's exact\n // directory view. A newer private prefix must not silently replace it.\n return await recoverPolicyDirectory(\n { ...input, offline: true, stillCurrent: current },\n references,\n known.value,\n );\n } catch (error) {\n assertProjectionVerificationCurrent(current);\n if (!fallsBackOnline(input, error)) throw error;\n }\n return recoverPolicyDirectory(\n { ...input, stillCurrent: current },\n references,\n known.value,\n );\n },\n );\n}\n\nexport function createPrincipalRecoveryReader(\n input: PrincipalRecoveryContext,\n memo?: PrincipalRecoveryMemo,\n) {\n const scope = [\n input.organizationId,\n input.protection.context,\n input.offline === true,\n ];\n const directoryKey = (references: readonly ReferencedPrincipalHead[]) =>\n serializeKeyingCanonicalJson([\n ...scope,\n references.map((reference) => ({ ...reference })),\n ]);\n // Every lifetime behind a value this reader handed out; its caller must\n // keep checking them at the point of use.\n const lifetimes: (() => boolean)[] = [];\n const lease = <T>(leased: Leased<T>): T => {\n lifetimes.push(leased.stillCurrent);\n return leased.value;\n };\n return {\n stillCurrent: () => lifetimes.every((current) => current()),\n directory: async (references: readonly ReferencedPrincipalHead[]) => {\n const value = lease(\n await readMemoizedDirectory(\n input,\n memo?.directories,\n directoryKey,\n references,\n ),\n );\n // Retaining extra citations does not prevent this authenticated directory\n // from satisfying a later read with no selected historical references.\n const unselectedKey = directoryKey([]);\n const selected = memo?.directories.get(directoryKey(references));\n if (\n memo &&\n selected &&\n references.length > 0 &&\n !memo.directories.has(unselectedKey)\n )\n // The alias keeps the original lease and validity; either ending evicts it.\n memo.directories.set(unselectedKey, selected);\n return value;\n },\n admins: async (\n expectedHead: ReferencedPrincipalHead,\n retainedReferences: readonly ReferencedPrincipalHead[] = [],\n ) =>\n lease(\n await readMemoizedAdmins(\n input,\n memo?.admins,\n scope,\n expectedHead,\n retainedReferences,\n ),\n ),\n };\n}\n"]}
|
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
// through this module.
|
|
4
4
|
import { buildPrincipalStateSigningInput, generateKemSeedAndKeyPair, signPrincipalState, toFingerprint, wrapDekForRecipients, } from "../../internal/crypto/index.js";
|
|
5
5
|
import { bytesToBase64 } from "../../internal/encoding/index.js";
|
|
6
|
-
import { encodeOrganizationAuthorityDescriptor } from "../../data/
|
|
7
|
-
import { createPrincipalProjectionMember } from "../../data/
|
|
6
|
+
import { encodeOrganizationAuthorityDescriptor } from "../../data/principalContracts/organizationAuthorityDescriptor.js";
|
|
7
|
+
import { createPrincipalProjectionMember } from "../../data/principalContracts/principalIdentityCommitments.js";
|
|
8
8
|
import { resolveDocumentCreateAuthor } from "../documents/index.js";
|
|
9
9
|
import { groupPolicyMutationHead } from "../organizations/groupPolicy/groupPolicyMutationHead.js";
|
|
10
10
|
import { buildInitialGroupPolicyRequest, buildInitialMemberGroupPolicyRequest, } from "../organizations/principalPolicy/index.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"organizationProvisioning.js","sourceRoot":"","sources":["organizationProvisioning.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,6EAA6E;AAC7E,uBAAuB;AACvB,OAAO,EACL,+BAA+B,EAE/B,yBAAyB,EAGzB,kBAAkB,EAClB,aAAa,EACb,oBAAoB,GACrB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAKpD,OAAO,EAAE,qCAAqC,EAAE,MAAM,uDAAuD,CAAC;AAC9G,OAAO,EAAE,+BAA+B,EAAE,MAAM,oDAAoD,CAAC;AACrG,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAE,uBAAuB,EAAE,MAAM,sDAAsD,CAAC;AAC/F,OAAO,EACL,8BAA8B,EAC9B,oCAAoC,GACrC,MAAM,kCAAkC,CAAC;AAE1C,OAAO,EACL,yCAAyC,EACzC,4BAA4B,EAC5B,kCAAkC,EAClC,oCAAoC,GAErC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,kCAAkC,EAAE,MAAM,yBAAyB,CAAC;AAG7E,OAAO,EAAE,oCAAoC,EAAE,MAAM,uCAAuC,CAAC;AAoC7F,MAAM,CAAC,KAAK,UAAU,qCAAqC,CAAC,KAS3D;IACC,MAAM,eAAe,GAAG,yBAAyB,EAAE,CAAC;IACpD,MAAM,wBAAwB,GAAG,MAAM,aAAa,CAClD,KAAK,CAAC,cAAc,CAAC,gBAAgB,CACtC,CAAC;IACF,MAAM,+BAA+B,GAAG,MAAM,a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e,EAAE,KAAK,CAAC,oBAAoB,CAAC,SAAS;KACtD,CAAC,CAAC;IACH,MAAM,sBAAsB,GAAG,MAAM,kCAAkC,CAAC;QACtE,MAAM;QACN,sBAAsB,EAAE,KAAK,CAAC,oBAAoB,CAAC,SAAS;QAC5D,iBAAiB;QACjB,qBAAqB,EAAE,KAAK,CAAC,qBAAqB;QAClD,aAAa;QACb,uBAAuB;QACvB,eAAe,EAAE,KAAK,CAAC,oBAAoB,CAAC,SAAS;KACtD,CAAC,CAAC;IACH,MAAM,6BAA6B,GACjC,MAAM,yCAAyC,CAAC;QAC9C,MAAM;QACN,WAAW,EAAE,+BAA+B;QAC5C,iBAAiB;QACjB,kBAAkB;QAClB,uBAAuB,EAAE,KAAK,CAAC,uBAAuB;QACtD,aAAa;QACb,uBAAuB;QACvB,eAAe,EAAE,KAAK,CAAC,oBAAoB,CAAC,SAAS;KACtD,CAAC,CAAC;IACL,MAAM,yBAAyB,GAAG,MAAM,OAAO,CAAC,GAAG,CACjD,CAAC,KAAK,CAAC,2BAA2B,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CACrD,oCAAoC,CAAC;QACnC,MAAM;QACN,iBAAiB;QACjB,aAAa;QACb,uBAAuB;QACvB,iBAAiB,EAAE,KAAK,CAAC,cAAc,CAAC,iBAAiB;QACzD,IAAI;QACJ,eAAe,EAAE,KAAK,CAAC,oBAAoB,CAAC,SAAS;KACtD,CAAC,CACH,CACF,CAAC;IAEF,OAAO;QACL,wBAAwB,EAAE,IAAI;QAC9B,SAAS;QACT,iBAAiB;QACjB,kBAAkB;QAClB,yBAAyB;QACzB,oBAAoB,EAAE,aAAa,CAAC,IAAI,CAAC,OAAO;QAChD,cAAc;QACd,6BAA6B;QAC7B,aAAa;QACb,oBAAoB;QACpB,2BAA2B;QAC3B,sBAAsB;QACtB,yBAAyB;KAC1B,CAAC;AACJ,CAAC","sourcesContent":["// Registration and additional-organization creation build and persist an\n// organization's founding policies, system containers, and profile documents\n// through this module.\nimport {\n buildPrincipalStateSigningInput,\n type EncapsulationKeyPair,\n generateKemSeedAndKeyPair,\n type ReferencedPrincipalHead,\n type SigningKeyPair,\n signPrincipalState,\n toFingerprint,\n wrapDekForRecipients,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n CreateOrganizationGroupRequest,\n RegistrationRequest,\n} from \"@tearleads/validators/request\";\nimport { encodeOrganizationAuthorityDescriptor } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport { createPrincipalProjectionMember } from \"../../data/principals/principalIdentityCommitments\";\nimport { resolveDocumentCreateAuthor } from \"../documents\";\nimport { groupPolicyMutationHead } from \"../organizations/groupPolicy/groupPolicyMutationHead\";\nimport {\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n} from \"../organizations/principalPolicy\";\nimport type { OrganizationProvisioningArtifacts } from \"./organizationProvisioningArtifacts\";\nimport {\n buildInitialOrganizationMetadataBootstrap,\n buildInitialRootProvisioning,\n buildInitialRosterProfileBootstrap,\n buildInitialSystemContainerBootstrap,\n type ProvisionedSystemContainerSpec,\n} from \"./provisioningBootstrapBuilders\";\nimport { createInitialRootMetadataBootstrap } from \"./rootMetadataBootstrap\";\n\nexport type { OrganizationProvisioningArtifacts } from \"./organizationProvisioningArtifacts\";\nexport { persistOrganizationProvisioningState } from \"./organizationProvisioningPersistence\";\nexport type { ProvisionedSystemContainerSpec } from \"./provisioningBootstrapBuilders\";\n\ninterface OrganizationProvisioningPrincipalPolicies {\n initialAdminGroup: CreateOrganizationGroupRequest;\n initialMemberGroup: CreateOrganizationGroupRequest;\n initialOrganizationPolicy: RegistrationRequest[\"initialOrganizationPolicy\"];\n organizationId: string;\n signingFingerprint: string;\n}\n\n/**\n * The freshly built provisioning artifacts, shared by registration and\n * additional-organization creation. `registerIdentity` generates a new\n * `userId`; creating an additional organization reuses the caller's existing\n * one. Everything here is derived purely from the caller's key material, so it\n * is identical for both flows.\n */\nexport interface OrganizationProvisioningArtifactsInput {\n identityTrustDomain: string;\n encapsulationKeyPair: EncapsulationKeyPair;\n organizationProfileName?: string | undefined;\n /**\n * App-owned system containers to provision atomically with the organization\n * (e.g. a trash bin). Omitted/empty leaves the org with only the roster and\n * organization-metadata system containers.\n */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n rootContainerId: string;\n rosterProfileNickname?: string | undefined;\n signingKeyPair: SigningKeyPair;\n userId: string;\n}\n\nexport async function buildInitialOrganizationPolicyRequest(input: {\n identityTrustDomain: string;\n adminGroupId: string;\n groupHeads: readonly ReferencedPrincipalHead[];\n encapsulationPublicKey: Uint8Array;\n memberGroupId: string;\n organizationId: string;\n signingKeyPair: SigningKeyPair;\n userId: string;\n}): Promise<RegistrationRequest[\"initialOrganizationPolicy\"]> {\n const organizationKem = generateKemSeedAndKeyPair();\n const signerUserKeyFingerprint = await toFingerprint(\n input.signingKeyPair.signingPublicKey,\n );\n const userEncapsulationKeyFingerprint = await toFingerprint(\n input.encapsulationPublicKey,\n );\n const projection = [\n await createPrincipalProjectionMember(\n {\n userId: input.userId,\n identityTrustDomain: input.identityTrustDomain,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n encapsulationPublicKey: input.encapsulationPublicKey,\n },\n \"admin\",\n ),\n ];\n const payloadCiphertext = encodeOrganizationAuthorityDescriptor({\n version: 2,\n organizationId: input.organizationId,\n adminGroupId: input.adminGroupId,\n memberGroupId: input.memberGroupId,\n groupHeads: input.groupHeads.map((head) => {\n if (head.principalType !== \"group\") {\n throw new Error(\"Organization directory can contain only group heads\");\n }\n return { ...head, principalType: \"group\" };\n }),\n });\n const [memberEnvelope] = await wrapDekForRecipients(\n organizationKem.secretKey,\n [input.encapsulationPublicKey],\n );\n\n if (!memberEnvelope) {\n throw new Error(\"Failed to wrap organization key for registering user\");\n }\n const memberEnvelopes = [\n {\n userId: input.userId,\n memberKeyFingerprint: userEncapsulationKeyFingerprint,\n kemCipherText: bytesToBase64(memberEnvelope.kemCipherText),\n wrappedKey: bytesToBase64(memberEnvelope.wrappedKey),\n },\n ];\n const state = await signPrincipalState(\n await buildPrincipalStateSigningInput({\n principalType: \"organization\",\n principalId: input.organizationId,\n version: 1,\n prevStateHash: null,\n keyEpoch: 1,\n encapsulationPublicKey: bytesToBase64(organizationKem.publicKey),\n keyFingerprint: await toFingerprint(organizationKem.publicKey),\n members: [{ userId: input.userId }],\n memberEnvelopes,\n projection,\n grants: [],\n payloadCiphertext,\n externalAuthority: null,\n signedAt: new Date().toISOString(),\n signerUserId: input.userId,\n signerUserKeyFingerprint,\n }),\n input.signingKeyPair.signingPrivateKey,\n );\n\n return {\n state,\n encryptedPayload: {\n cipherSuite: \"aes-256-gcm\",\n ciphertext: payloadCiphertext,\n ciphertextHash: state.payloadCiphertextHash,\n },\n projection,\n grants: [],\n memberEnvelopes,\n };\n}\n\nasync function createOrganizationPrincipalPolicies(input: {\n identityTrustDomain: string;\n encapsulationKeyPair: EncapsulationKeyPair;\n organizationMetadataContainerId: string;\n rootContainerId: string;\n signingKeyPair: SigningKeyPair;\n userId: string;\n}): Promise<OrganizationProvisioningPrincipalPolicies> {\n const organizationId = crypto.randomUUID();\n const signingFingerprint = await toFingerprint(\n input.signingKeyPair.signingPublicKey,\n );\n const initialAdminGroup = await buildInitialGroupPolicyRequest({\n identityTrustDomain: input.identityTrustDomain,\n creatorEncapsulationKeyPair: input.encapsulationKeyPair,\n groupId: crypto.randomUUID(),\n grants: [\n { containerId: input.rootContainerId, accessLevel: \"admin\" },\n {\n containerId: input.organizationMetadataContainerId,\n accessLevel: \"admin\",\n },\n ],\n name: \"Admins\",\n builtinRole: \"admins\",\n signerUserId: input.userId,\n signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const initialMemberGroup = await buildInitialMemberGroupPolicyRequest({\n identityTrustDomain: input.identityTrustDomain,\n creatorEncapsulationKeyPair: input.encapsulationKeyPair,\n groupId: crypto.randomUUID(),\n grants: [\n {\n containerId: input.organizationMetadataContainerId,\n accessLevel: \"read\",\n },\n ],\n signerUserId: input.userId,\n signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const initialOrganizationPolicy = await buildInitialOrganizationPolicyRequest(\n {\n identityTrustDomain: input.identityTrustDomain,\n adminGroupId: initialAdminGroup.groupId,\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n groupHeads: await Promise.all([\n groupPolicyMutationHead(initialAdminGroup.initialGroupPolicy),\n groupPolicyMutationHead(initialMemberGroup.initialGroupPolicy),\n ]),\n memberGroupId: initialMemberGroup.groupId,\n organizationId,\n signingKeyPair: input.signingKeyPair,\n userId: input.userId,\n },\n );\n\n return {\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n organizationId,\n signingFingerprint,\n };\n}\n\nfunction requireOrganizationProvisioningAuthor(input: {\n readonly organizationId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly userId: string;\n}) {\n const author = resolveDocumentCreateAuthor({\n auth: { organizationId: input.organizationId, userId: input.userId },\n crypto: {\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n },\n });\n if (!author) {\n throw new Error(\n `Organization provisioning document author context is unavailable for user ${input.userId} in organization ${input.organizationId}.`,\n );\n }\n return author;\n}\n\n/** Builds the signed artifacts shared by registration and org creation. */\nexport async function buildOrganizationProvisioningArtifacts(\n input: OrganizationProvisioningArtifactsInput,\n): Promise<OrganizationProvisioningArtifacts> {\n const bootstrap = await createInitialRootMetadataBootstrap(\n input.rootContainerId,\n );\n const organizationMetadataContainerId = crypto.randomUUID();\n const {\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n organizationId,\n signingFingerprint,\n } = await createOrganizationPrincipalPolicies({\n ...input,\n organizationMetadataContainerId,\n });\n const author = requireOrganizationProvisioningAuthor({\n organizationId,\n signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n userId: input.userId,\n });\n\n const {\n rootContainer,\n rootContainerProjection,\n rootMetadataDocument,\n rootMetadataDocumentRequest,\n } = await buildInitialRootProvisioning({\n adminGroup: initialAdminGroup,\n author,\n bootstrap,\n recipientEncapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n rootContainerId: input.rootContainerId,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n });\n const rosterProfileBootstrap = await buildInitialRosterProfileBootstrap({\n author,\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n initialAdminGroup,\n rosterProfileNickname: input.rosterProfileNickname,\n rootContainer,\n rootContainerProjection,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n });\n const organizationMetadataBootstrap =\n await buildInitialOrganizationMetadataBootstrap({\n author,\n containerId: organizationMetadataContainerId,\n initialAdminGroup,\n initialMemberGroup,\n organizationProfileName: input.organizationProfileName,\n rootContainer,\n rootContainerProjection,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n });\n const systemContainerBootstraps = await Promise.all(\n (input.provisionedSystemContainers ?? []).map((spec) =>\n buildInitialSystemContainerBootstrap({\n author,\n initialAdminGroup,\n rootContainer,\n rootContainerProjection,\n signingPrivateKey: input.signingKeyPair.signingPrivateKey,\n spec,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n }),\n ),\n );\n\n return {\n replacementAuthorization: null,\n bootstrap,\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n initialRootContainer: rootContainer.plan.request,\n organizationId,\n organizationMetadataBootstrap,\n rootContainer,\n rootMetadataDocument,\n rootMetadataDocumentRequest,\n rosterProfileBootstrap,\n systemContainerBootstraps,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"organizationProvisioning.js","sourceRoot":"","sources":["organizationProvisioning.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,6EAA6E;AAC7E,uBAAuB;AACvB,OAAO,EACL,+BAA+B,EAE/B,yBAAyB,EAGzB,kBAAkB,EAClB,aAAa,EACb,oBAAoB,GACrB,MAAM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CAAC,uBAAuB;QACtD,aAAa;QACb,uBAAuB;QACvB,eAAe,EAAE,KAAK,CAAC,oBAAoB,CAAC,SAAS;KACtD,CAAC,CAAC;IACL,MAAM,yBAAyB,GAAG,MAAM,OAAO,CAAC,GAAG,CACjD,CAAC,KAAK,CAAC,2BAA2B,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CACrD,oCAAoC,CAAC;QACnC,MAAM;QACN,iBAAiB;QACjB,aAAa;QACb,uBAAuB;QACvB,iBAAiB,EAAE,KAAK,CAAC,cAAc,CAAC,iBAAiB;QACzD,IAAI;QACJ,eAAe,EAAE,KAAK,CAAC,oBAAoB,CAAC,SAAS;KACtD,CAAC,CACH,CACF,CAAC;IAEF,OAAO;QACL,wBAAwB,EAAE,IAAI;QAC9B,SAAS;QACT,iBAAiB;QACjB,kBAAkB;QAClB,yBAAyB;QACzB,oBAAoB,EAAE,aAAa,CAAC,IAAI,CAAC,OAAO;QAChD,cAAc;QACd,6BAA6B;QAC7B,aAAa;QACb,oBAAoB;QACpB,2BAA2B;QAC3B,sBAAsB;QACtB,yBAAyB;KAC1B,CAAC;AACJ,CAAC","sourcesContent":["// Registration and additional-organization creation build and persist an\n// organization's founding policies, system containers, and profile documents\n// through this module.\nimport {\n buildPrincipalStateSigningInput,\n type EncapsulationKeyPair,\n generateKemSeedAndKeyPair,\n type ReferencedPrincipalHead,\n type SigningKeyPair,\n signPrincipalState,\n toFingerprint,\n wrapDekForRecipients,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n CreateOrganizationGroupRequest,\n RegistrationRequest,\n} from \"@tearleads/validators/request\";\nimport { encodeOrganizationAuthorityDescriptor } from \"../../data/principalContracts/organizationAuthorityDescriptor\";\nimport { createPrincipalProjectionMember } from \"../../data/principalContracts/principalIdentityCommitments\";\nimport { resolveDocumentCreateAuthor } from \"../documents\";\nimport { groupPolicyMutationHead } from \"../organizations/groupPolicy/groupPolicyMutationHead\";\nimport {\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n} from \"../organizations/principalPolicy\";\nimport type { OrganizationProvisioningArtifacts } from \"./organizationProvisioningArtifacts\";\nimport {\n buildInitialOrganizationMetadataBootstrap,\n buildInitialRootProvisioning,\n buildInitialRosterProfileBootstrap,\n buildInitialSystemContainerBootstrap,\n type ProvisionedSystemContainerSpec,\n} from \"./provisioningBootstrapBuilders\";\nimport { createInitialRootMetadataBootstrap } from \"./rootMetadataBootstrap\";\n\nexport type { OrganizationProvisioningArtifacts } from \"./organizationProvisioningArtifacts\";\nexport { persistOrganizationProvisioningState } from \"./organizationProvisioningPersistence\";\nexport type { ProvisionedSystemContainerSpec } from \"./provisioningBootstrapBuilders\";\n\ninterface OrganizationProvisioningPrincipalPolicies {\n initialAdminGroup: CreateOrganizationGroupRequest;\n initialMemberGroup: CreateOrganizationGroupRequest;\n initialOrganizationPolicy: RegistrationRequest[\"initialOrganizationPolicy\"];\n organizationId: string;\n signingFingerprint: string;\n}\n\n/**\n * The freshly built provisioning artifacts, shared by registration and\n * additional-organization creation. `registerIdentity` generates a new\n * `userId`; creating an additional organization reuses the caller's existing\n * one. Everything here is derived purely from the caller's key material, so it\n * is identical for both flows.\n */\nexport interface OrganizationProvisioningArtifactsInput {\n identityTrustDomain: string;\n encapsulationKeyPair: EncapsulationKeyPair;\n organizationProfileName?: string | undefined;\n /**\n * App-owned system containers to provision atomically with the organization\n * (e.g. a trash bin). Omitted/empty leaves the org with only the roster and\n * organization-metadata system containers.\n */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n rootContainerId: string;\n rosterProfileNickname?: string | undefined;\n signingKeyPair: SigningKeyPair;\n userId: string;\n}\n\nexport async function buildInitialOrganizationPolicyRequest(input: {\n identityTrustDomain: string;\n adminGroupId: string;\n groupHeads: readonly ReferencedPrincipalHead[];\n encapsulationPublicKey: Uint8Array;\n memberGroupId: string;\n organizationId: string;\n signingKeyPair: SigningKeyPair;\n userId: string;\n}): Promise<RegistrationRequest[\"initialOrganizationPolicy\"]> {\n const organizationKem = generateKemSeedAndKeyPair();\n const signerUserKeyFingerprint = await toFingerprint(\n input.signingKeyPair.signingPublicKey,\n );\n const userEncapsulationKeyFingerprint = await toFingerprint(\n input.encapsulationPublicKey,\n );\n const projection = [\n await createPrincipalProjectionMember(\n {\n userId: input.userId,\n identityTrustDomain: input.identityTrustDomain,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n encapsulationPublicKey: input.encapsulationPublicKey,\n },\n \"admin\",\n ),\n ];\n const payloadCiphertext = encodeOrganizationAuthorityDescriptor({\n version: 2,\n organizationId: input.organizationId,\n adminGroupId: input.adminGroupId,\n memberGroupId: input.memberGroupId,\n groupHeads: input.groupHeads.map((head) => {\n if (head.principalType !== \"group\") {\n throw new Error(\"Organization directory can contain only group heads\");\n }\n return { ...head, principalType: \"group\" };\n }),\n });\n const [memberEnvelope] = await wrapDekForRecipients(\n organizationKem.secretKey,\n [input.encapsulationPublicKey],\n );\n\n if (!memberEnvelope) {\n throw new Error(\"Failed to wrap organization key for registering user\");\n }\n const memberEnvelopes = [\n {\n userId: input.userId,\n memberKeyFingerprint: userEncapsulationKeyFingerprint,\n kemCipherText: bytesToBase64(memberEnvelope.kemCipherText),\n wrappedKey: bytesToBase64(memberEnvelope.wrappedKey),\n },\n ];\n const state = await signPrincipalState(\n await buildPrincipalStateSigningInput({\n principalType: \"organization\",\n principalId: input.organizationId,\n version: 1,\n prevStateHash: null,\n keyEpoch: 1,\n encapsulationPublicKey: bytesToBase64(organizationKem.publicKey),\n keyFingerprint: await toFingerprint(organizationKem.publicKey),\n members: [{ userId: input.userId }],\n memberEnvelopes,\n projection,\n grants: [],\n payloadCiphertext,\n externalAuthority: null,\n signedAt: new Date().toISOString(),\n signerUserId: input.userId,\n signerUserKeyFingerprint,\n }),\n input.signingKeyPair.signingPrivateKey,\n );\n\n return {\n state,\n encryptedPayload: {\n cipherSuite: \"aes-256-gcm\",\n ciphertext: payloadCiphertext,\n ciphertextHash: state.payloadCiphertextHash,\n },\n projection,\n grants: [],\n memberEnvelopes,\n };\n}\n\nasync function createOrganizationPrincipalPolicies(input: {\n identityTrustDomain: string;\n encapsulationKeyPair: EncapsulationKeyPair;\n organizationMetadataContainerId: string;\n rootContainerId: string;\n signingKeyPair: SigningKeyPair;\n userId: string;\n}): Promise<OrganizationProvisioningPrincipalPolicies> {\n const organizationId = crypto.randomUUID();\n const signingFingerprint = await toFingerprint(\n input.signingKeyPair.signingPublicKey,\n );\n const initialAdminGroup = await buildInitialGroupPolicyRequest({\n identityTrustDomain: input.identityTrustDomain,\n creatorEncapsulationKeyPair: input.encapsulationKeyPair,\n groupId: crypto.randomUUID(),\n grants: [\n { containerId: input.rootContainerId, accessLevel: \"admin\" },\n {\n containerId: input.organizationMetadataContainerId,\n accessLevel: \"admin\",\n },\n ],\n name: \"Admins\",\n builtinRole: \"admins\",\n signerUserId: input.userId,\n signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const initialMemberGroup = await buildInitialMemberGroupPolicyRequest({\n identityTrustDomain: input.identityTrustDomain,\n creatorEncapsulationKeyPair: input.encapsulationKeyPair,\n groupId: crypto.randomUUID(),\n grants: [\n {\n containerId: input.organizationMetadataContainerId,\n accessLevel: \"read\",\n },\n ],\n signerUserId: input.userId,\n signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const initialOrganizationPolicy = await buildInitialOrganizationPolicyRequest(\n {\n identityTrustDomain: input.identityTrustDomain,\n adminGroupId: initialAdminGroup.groupId,\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n groupHeads: await Promise.all([\n groupPolicyMutationHead(initialAdminGroup.initialGroupPolicy),\n groupPolicyMutationHead(initialMemberGroup.initialGroupPolicy),\n ]),\n memberGroupId: initialMemberGroup.groupId,\n organizationId,\n signingKeyPair: input.signingKeyPair,\n userId: input.userId,\n },\n );\n\n return {\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n organizationId,\n signingFingerprint,\n };\n}\n\nfunction requireOrganizationProvisioningAuthor(input: {\n readonly organizationId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly userId: string;\n}) {\n const author = resolveDocumentCreateAuthor({\n auth: { organizationId: input.organizationId, userId: input.userId },\n crypto: {\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n },\n });\n if (!author) {\n throw new Error(\n `Organization provisioning document author context is unavailable for user ${input.userId} in organization ${input.organizationId}.`,\n );\n }\n return author;\n}\n\n/** Builds the signed artifacts shared by registration and org creation. */\nexport async function buildOrganizationProvisioningArtifacts(\n input: OrganizationProvisioningArtifactsInput,\n): Promise<OrganizationProvisioningArtifacts> {\n const bootstrap = await createInitialRootMetadataBootstrap(\n input.rootContainerId,\n );\n const organizationMetadataContainerId = crypto.randomUUID();\n const {\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n organizationId,\n signingFingerprint,\n } = await createOrganizationPrincipalPolicies({\n ...input,\n organizationMetadataContainerId,\n });\n const author = requireOrganizationProvisioningAuthor({\n organizationId,\n signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n userId: input.userId,\n });\n\n const {\n rootContainer,\n rootContainerProjection,\n rootMetadataDocument,\n rootMetadataDocumentRequest,\n } = await buildInitialRootProvisioning({\n adminGroup: initialAdminGroup,\n author,\n bootstrap,\n recipientEncapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n rootContainerId: input.rootContainerId,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n });\n const rosterProfileBootstrap = await buildInitialRosterProfileBootstrap({\n author,\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n initialAdminGroup,\n rosterProfileNickname: input.rosterProfileNickname,\n rootContainer,\n rootContainerProjection,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n });\n const organizationMetadataBootstrap =\n await buildInitialOrganizationMetadataBootstrap({\n author,\n containerId: organizationMetadataContainerId,\n initialAdminGroup,\n initialMemberGroup,\n organizationProfileName: input.organizationProfileName,\n rootContainer,\n rootContainerProjection,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n });\n const systemContainerBootstraps = await Promise.all(\n (input.provisionedSystemContainers ?? []).map((spec) =>\n buildInitialSystemContainerBootstrap({\n author,\n initialAdminGroup,\n rootContainer,\n rootContainerProjection,\n signingPrivateKey: input.signingKeyPair.signingPrivateKey,\n spec,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n }),\n ),\n );\n\n return {\n replacementAuthorization: null,\n bootstrap,\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n initialRootContainer: rootContainer.plan.request,\n organizationId,\n organizationMetadataBootstrap,\n rootContainer,\n rootMetadataDocument,\n rootMetadataDocumentRequest,\n rosterProfileBootstrap,\n systemContainerBootstraps,\n };\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { assertProjectionVerificationCurrent } from "../../data/keyingProjectionVerification/types.js";
|
|
2
|
-
import { principalPolicyReferenceFromBundle } from "../../data/
|
|
2
|
+
import { principalPolicyReferenceFromBundle } from "../../data/principalContracts/principalPolicyAdminSigners.js";
|
|
3
3
|
import { getOrCreatePrincipalPolicyCoordinator } from "../../data/principals/principalPolicyCoordinator.js";
|
|
4
4
|
import { createPrincipalCurrentRecoveryBatch } from "../principals/recoveryOperation/principalCurrentRecoveryBatch.js";
|
|
5
5
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provisionedPrincipalHistory.js","sourceRoot":"","sources":["provisionedPrincipalHistory.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AAEpG,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AACvG,OAAO,EAAE,qCAAqC,EAAE,MAAM,kDAAkD,CAAC;AAOzG,OAAO,EAAE,mCAAmC,EAAE,MAAM,+DA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AS,CAAC;IAC/D,IAAI,CAAC,OAAO,IAAI,CAAC,KAAK;QAAE,OAAO;IAC/B,MAAM,0BAA0B,GAAgC,KAAK,EACnE,YAAY,EACZ,EAAE;QACF,IAAI,YAAY,KAAK,KAAK,CAAC,MAAM;YAAE,OAAO,IAAI,CAAC;QAC/C,mCAAmC,CAAC,YAAY,CAAC,CAAC;QAClD,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,kBAAkB,CAAC,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;QACzE,mCAAmC,CAAC,YAAY,CAAC,CAAC;QAClD,OAAO,QAAQ,EAAE,qBAAqB,KAAK,kBAAkB;YAC3D,CAAC,CAAC,QAAQ;YACV,CAAC,CAAC,IAAI,CAAC;IACX,CAAC,CAAC;IACF,MAAM,qCAAqC,CAAC,OAAO,CAAC,CAAC,aAAa,CAChE,KAAK,CAAC,cAAc,EACpB,GAAG,EAAE,CACH,KAAK,CAAC,CAAC,EAAE,UAAU,EAAE,YAAY,EAAE,EAAE,EAAE,CACrC,gCAAgC,CAAC;QAC/B,OAAO;QACP,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,UAAU;QACV,0BAA0B;QAC1B,wDAAwD;QACxD,YAAY,EAAE,GAAG,EAAE,CAAC,YAAY,EAAE,IAAI,YAAY,EAAE;KACrD,CAAC,CACH,CACJ,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicyHistoryProgressOptions } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../data/principals/principalPolicyAdminSigners\";\nimport { getOrCreatePrincipalPolicyCoordinator } from \"../../data/principals/principalPolicyCoordinator\";\nimport type { ExecSql, ExecSqlClientLike } from \"../../data/sqlite/sqlSchema\";\nimport type {\n TrustedUserIdentity,\n TrustedUserIdentityResolver,\n} from \"../../data/trustedUserIdentity\";\nimport type { PrincipalPolicyPageReader } from \"../principals/principalPolicyHistoryReader\";\nimport { createPrincipalCurrentRecoveryBatch } from \"../principals/recoveryOperation/principalCurrentRecoveryBatch\";\n\n/** The version-1 policies a provisioning request signed and its response acknowledged. */\ninterface ProvisionedPrincipalPolicies {\n readonly adminGroup: PrincipalPolicyBundleResponse;\n readonly memberGroup: PrincipalPolicyBundleResponse;\n readonly organization: PrincipalPolicyBundleResponse;\n}\n\n/**\n * Records verified recovery progress for an organization's founding policy\n * heads, so the device's first scoped recovery of them needs no history read.\n * It is bound to the provisioning scope: the database the bootstrap committed\n * to and the identity that signed it. Failure leaves the online path.\n */\nexport type ProvisionedPrincipalHistoryPrimer = (input: {\n /** The database client the provisioning bootstrap committed to. */\n readonly database: ExecSqlClientLike;\n /** Whether the identity that provisioned is still the active one. */\n readonly isCurrent: () => boolean;\n readonly organizationId: string;\n readonly policies: ProvisionedPrincipalPolicies;\n readonly userId: string;\n}) => Promise<void>;\n\n/**\n * Serves only the acknowledged initial heads, each complete in one page. The\n * ordinary verifier still checks every signature, the directory binding and\n * strict Admins rules before any progress is saved.\n */\nfunction provisionedPolicyPages(\n policies: ProvisionedPrincipalPolicies,\n): PrincipalPolicyPageReader {\n const bundles = [\n policies.organization,\n policies.adminGroup,\n policies.memberGroup,\n ];\n return {\n async *getPrincipalPolicyPages(principalType, principalId, options = {}) {\n const bundle = bundles.find(\n ({ currentState }) =>\n currentState.principalType === principalType &&\n currentState.principalId === principalId,\n );\n if (\n !bundle ||\n options.resume !== undefined ||\n (options.afterVersion ?? 0) !== 0 ||\n (options.stateHash !== undefined &&\n options.stateHash !== bundle.currentState.stateHash)\n )\n throw new Error(\n \"Provisioned principal history holds only the acknowledged initial heads\",\n );\n yield {\n ok: true,\n data: {\n ...structuredClone(bundle),\n historyPage: { afterVersion: 0, nextAfterVersion: null },\n },\n };\n },\n };\n}\n\nasync function primeProvisionedPrincipalHistory(input: {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly policies: ProvisionedPrincipalPolicies;\n readonly protection: PrincipalPolicyHistoryProgressOptions;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent: () => boolean;\n}): Promise<void> {\n const { recover } = createPrincipalCurrentRecoveryBatch();\n const options = {\n historyReader: provisionedPolicyPages(input.policies),\n execSql: input.execSql,\n offline: false,\n organizationId: input.organizationId,\n protection: input.protection,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n };\n // Scoped recovery of each group also completes the directory and strict\n // Admins stages; Members reuses them through the shared batch.\n for (const group of [input.policies.adminGroup, input.policies.memberGroup])\n await recover({\n ...options,\n reference: principalPolicyReferenceFromBundle(group),\n });\n}\n\n/** The runtime seams priming reads; none of them writes durable state. */\nexport interface ProvisionedPrincipalHistoryRuntime {\n readonly bindLease: () => PrincipalHistoryProtectionLease | undefined;\n /** The runtime executor, only while `database` is its ready database. */\n readonly execSqlFor: (database: ExecSqlClientLike) => ExecSql | null;\n readonly logError: (message: string | Error, cause?: unknown) => void;\n /** Read-only: the identity the trust store already pins for a user. */\n readonly loadPinnedIdentity: (\n execSql: ExecSql,\n userId: string,\n ) => Promise<TrustedUserIdentity | null>;\n readonly signingFingerprint: () => string | null;\n}\n\n/**\n * Binds priming to the exact provisioning scope, captured before any await:\n * the bootstrap's database and runtime executor, the identity whose key signed\n * the founding states, and a protection lease for that identity. Every later\n * step, and every progress write inside its transaction, rechecks that scope,\n * so a switched identity or database aborts priming without a durable write.\n * Priming never writes a trust pin; it only reads the founder's existing one.\n */\nexport function createProvisionedPrincipalHistoryPrimer(\n runtime: ProvisionedPrincipalHistoryRuntime,\n): ProvisionedPrincipalHistoryPrimer {\n return async (input) => {\n try {\n await primeInProvisioningScope(runtime, input);\n } catch (error) {\n runtime.logError(\n \"Provisioned principal history was not primed; recovery reads it online\",\n error,\n );\n }\n };\n}\n\nasync function primeInProvisioningScope(\n runtime: ProvisionedPrincipalHistoryRuntime,\n input: Parameters<ProvisionedPrincipalHistoryPrimer>[0],\n): Promise<void> {\n // Everything below is captured synchronously, before the first await.\n const founderFingerprint =\n input.policies.organization.currentState.signerUserKeyFingerprint;\n const execSql = runtime.execSqlFor(input.database);\n const scopeCurrent = () =>\n execSql !== null &&\n input.isCurrent() &&\n runtime.execSqlFor(input.database) === execSql &&\n runtime.signingFingerprint() === founderFingerprint;\n const lease = scopeCurrent() ? runtime.bindLease() : undefined;\n if (!execSql || !lease) return;\n const resolveTrustedUserIdentity: TrustedUserIdentityResolver = async (\n signerUserId,\n ) => {\n if (signerUserId !== input.userId) return null;\n assertProjectionVerificationCurrent(scopeCurrent);\n const identity = await runtime.loadPinnedIdentity(execSql, input.userId);\n assertProjectionVerificationCurrent(scopeCurrent);\n return identity?.signingKeyFingerprint === founderFingerprint\n ? identity\n : null;\n };\n await getOrCreatePrincipalPolicyCoordinator(execSql).queueRecovery(\n input.organizationId,\n () =>\n lease(({ protection, stillCurrent }) =>\n primeProvisionedPrincipalHistory({\n execSql,\n organizationId: input.organizationId,\n policies: input.policies,\n protection,\n resolveTrustedUserIdentity,\n // Progress writes check this inside their transactions.\n stillCurrent: () => stillCurrent() && scopeCurrent(),\n }),\n ),\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"provisionedPrincipalHistory.js","sourceRoot":"","sources":["provisionedPrincipalHistory.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,kCAAkC,EAAE,MAAM,2DAA2D,CAAC;AAE/G,OAAO,EAAE,qCAAqC,EAAE,MAAM,kDAAkD,CAAC;AAOzG,OAAO,EAAE,mCAAmC,EAAE,MAAM,+DAA+D,CAAC;AAyBpH;;;;GAIG;AACH,SAAS,sBAAsB,CAC7B,QAAsC;IAEtC,MAAM,OAA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BAA0B,GAAgC,KAAK,EACnE,YAAY,EACZ,EAAE;QACF,IAAI,YAAY,KAAK,KAAK,CAAC,MAAM;YAAE,OAAO,IAAI,CAAC;QAC/C,mCAAmC,CAAC,YAAY,CAAC,CAAC;QAClD,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,kBAAkB,CAAC,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;QACzE,mCAAmC,CAAC,YAAY,CAAC,CAAC;QAClD,OAAO,QAAQ,EAAE,qBAAqB,KAAK,kBAAkB;YAC3D,CAAC,CAAC,QAAQ;YACV,CAAC,CAAC,IAAI,CAAC;IACX,CAAC,CAAC;IACF,MAAM,qCAAqC,CAAC,OAAO,CAAC,CAAC,aAAa,CAChE,KAAK,CAAC,cAAc,EACpB,GAAG,EAAE,CACH,KAAK,CAAC,CAAC,EAAE,UAAU,EAAE,YAAY,EAAE,EAAE,EAAE,CACrC,gCAAgC,CAAC;QAC/B,OAAO;QACP,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,UAAU;QACV,0BAA0B;QAC1B,wDAAwD;QACxD,YAAY,EAAE,GAAG,EAAE,CAAC,YAAY,EAAE,IAAI,YAAY,EAAE;KACrD,CAAC,CACH,CACJ,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicyHistoryProgressOptions } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { principalPolicyReferenceFromBundle } from \"../../data/principalContracts/principalPolicyAdminSigners\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport { getOrCreatePrincipalPolicyCoordinator } from \"../../data/principals/principalPolicyCoordinator\";\nimport type { ExecSql, ExecSqlClientLike } from \"../../data/sqlite/sqlSchema\";\nimport type {\n TrustedUserIdentity,\n TrustedUserIdentityResolver,\n} from \"../../data/trustedUserIdentity\";\nimport type { PrincipalPolicyPageReader } from \"../principals/principalPolicyHistoryReader\";\nimport { createPrincipalCurrentRecoveryBatch } from \"../principals/recoveryOperation/principalCurrentRecoveryBatch\";\n\n/** The version-1 policies a provisioning request signed and its response acknowledged. */\ninterface ProvisionedPrincipalPolicies {\n readonly adminGroup: PrincipalPolicyBundleResponse;\n readonly memberGroup: PrincipalPolicyBundleResponse;\n readonly organization: PrincipalPolicyBundleResponse;\n}\n\n/**\n * Records verified recovery progress for an organization's founding policy\n * heads, so the device's first scoped recovery of them needs no history read.\n * It is bound to the provisioning scope: the database the bootstrap committed\n * to and the identity that signed it. Failure leaves the online path.\n */\nexport type ProvisionedPrincipalHistoryPrimer = (input: {\n /** The database client the provisioning bootstrap committed to. */\n readonly database: ExecSqlClientLike;\n /** Whether the identity that provisioned is still the active one. */\n readonly isCurrent: () => boolean;\n readonly organizationId: string;\n readonly policies: ProvisionedPrincipalPolicies;\n readonly userId: string;\n}) => Promise<void>;\n\n/**\n * Serves only the acknowledged initial heads, each complete in one page. The\n * ordinary verifier still checks every signature, the directory binding and\n * strict Admins rules before any progress is saved.\n */\nfunction provisionedPolicyPages(\n policies: ProvisionedPrincipalPolicies,\n): PrincipalPolicyPageReader {\n const bundles = [\n policies.organization,\n policies.adminGroup,\n policies.memberGroup,\n ];\n return {\n async *getPrincipalPolicyPages(principalType, principalId, options = {}) {\n const bundle = bundles.find(\n ({ currentState }) =>\n currentState.principalType === principalType &&\n currentState.principalId === principalId,\n );\n if (\n !bundle ||\n options.resume !== undefined ||\n (options.afterVersion ?? 0) !== 0 ||\n (options.stateHash !== undefined &&\n options.stateHash !== bundle.currentState.stateHash)\n )\n throw new Error(\n \"Provisioned principal history holds only the acknowledged initial heads\",\n );\n yield {\n ok: true,\n data: {\n ...structuredClone(bundle),\n historyPage: { afterVersion: 0, nextAfterVersion: null },\n },\n };\n },\n };\n}\n\nasync function primeProvisionedPrincipalHistory(input: {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly policies: ProvisionedPrincipalPolicies;\n readonly protection: PrincipalPolicyHistoryProgressOptions;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent: () => boolean;\n}): Promise<void> {\n const { recover } = createPrincipalCurrentRecoveryBatch();\n const options = {\n historyReader: provisionedPolicyPages(input.policies),\n execSql: input.execSql,\n offline: false,\n organizationId: input.organizationId,\n protection: input.protection,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n };\n // Scoped recovery of each group also completes the directory and strict\n // Admins stages; Members reuses them through the shared batch.\n for (const group of [input.policies.adminGroup, input.policies.memberGroup])\n await recover({\n ...options,\n reference: principalPolicyReferenceFromBundle(group),\n });\n}\n\n/** The runtime seams priming reads; none of them writes durable state. */\nexport interface ProvisionedPrincipalHistoryRuntime {\n readonly bindLease: () => PrincipalHistoryProtectionLease | undefined;\n /** The runtime executor, only while `database` is its ready database. */\n readonly execSqlFor: (database: ExecSqlClientLike) => ExecSql | null;\n readonly logError: (message: string | Error, cause?: unknown) => void;\n /** Read-only: the identity the trust store already pins for a user. */\n readonly loadPinnedIdentity: (\n execSql: ExecSql,\n userId: string,\n ) => Promise<TrustedUserIdentity | null>;\n readonly signingFingerprint: () => string | null;\n}\n\n/**\n * Binds priming to the exact provisioning scope, captured before any await:\n * the bootstrap's database and runtime executor, the identity whose key signed\n * the founding states, and a protection lease for that identity. Every later\n * step, and every progress write inside its transaction, rechecks that scope,\n * so a switched identity or database aborts priming without a durable write.\n * Priming never writes a trust pin; it only reads the founder's existing one.\n */\nexport function createProvisionedPrincipalHistoryPrimer(\n runtime: ProvisionedPrincipalHistoryRuntime,\n): ProvisionedPrincipalHistoryPrimer {\n return async (input) => {\n try {\n await primeInProvisioningScope(runtime, input);\n } catch (error) {\n runtime.logError(\n \"Provisioned principal history was not primed; recovery reads it online\",\n error,\n );\n }\n };\n}\n\nasync function primeInProvisioningScope(\n runtime: ProvisionedPrincipalHistoryRuntime,\n input: Parameters<ProvisionedPrincipalHistoryPrimer>[0],\n): Promise<void> {\n // Everything below is captured synchronously, before the first await.\n const founderFingerprint =\n input.policies.organization.currentState.signerUserKeyFingerprint;\n const execSql = runtime.execSqlFor(input.database);\n const scopeCurrent = () =>\n execSql !== null &&\n input.isCurrent() &&\n runtime.execSqlFor(input.database) === execSql &&\n runtime.signingFingerprint() === founderFingerprint;\n const lease = scopeCurrent() ? runtime.bindLease() : undefined;\n if (!execSql || !lease) return;\n const resolveTrustedUserIdentity: TrustedUserIdentityResolver = async (\n signerUserId,\n ) => {\n if (signerUserId !== input.userId) return null;\n assertProjectionVerificationCurrent(scopeCurrent);\n const identity = await runtime.loadPinnedIdentity(execSql, input.userId);\n assertProjectionVerificationCurrent(scopeCurrent);\n return identity?.signingKeyFingerprint === founderFingerprint\n ? identity\n : null;\n };\n await getOrCreatePrincipalPolicyCoordinator(execSql).queueRecovery(\n input.organizationId,\n () =>\n lease(({ protection, stillCurrent }) =>\n primeProvisionedPrincipalHistory({\n execSql,\n organizationId: input.organizationId,\n policies: input.policies,\n protection,\n resolveTrustedUserIdentity,\n // Progress writes check this inside their transactions.\n stillCurrent: () => stillCurrent() && scopeCurrent(),\n }),\n ),\n );\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { KeyingVerificationError, verifyAccessManifestLocalCheckpoint, } from "../../internal/crypto/index.js";
|
|
2
2
|
import { accessManifestObjectKey, loadStoredAccessManifestCheckpoint, } from "../../data/persistence/keyingCheckpoints/keyingCheckpointPersistence.js";
|
|
3
3
|
import { KeyingCheckpointRepository } from "../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
|
|
4
|
-
import { assertContainerNotRetired } from "../../data/persistence/
|
|
4
|
+
import { assertContainerNotRetired } from "../../data/persistence/principalContracts/principalGrantRetirementPersistence.js";
|
|
5
5
|
import { keyingCheckpointTables } from "../../data/sqlite/schema/keyingCheckpointSchema.js";
|
|
6
6
|
import { getClientSQLitePersistenceRuntime } from "../../data/sqlite/sqlitePersistenceRuntime.js";
|
|
7
7
|
import { ensureSqlTables } from "../../data/sqlite/sqlSchema.js";
|