@tearleads/client-sdk 0.1.16 → 0.1.17
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/index.d.ts +1 -1
- package/client/index.js.map +1 -1
- package/client/organizations/currentPrincipalMutations.js +96 -0
- package/client/organizations/currentPrincipalMutations.js.map +1 -0
- package/client/organizations/index.d.ts +1 -1
- package/client/organizations/index.js +4 -3
- package/client/organizations/index.js.map +1 -1
- package/client/organizations/organizationGroupHistory.js +44 -0
- package/client/organizations/organizationGroupHistory.js.map +1 -0
- package/client/organizations/organizationGroupNameHydration.js +7 -1
- package/client/organizations/organizationGroupNameHydration.js.map +1 -1
- package/client/organizations/organizationGroupPresentation.d.ts +1 -0
- package/client/organizations/organizationGroupPresentation.js +16 -2
- package/client/organizations/organizationGroupPresentation.js.map +1 -1
- package/client/organizations/organizationReadModels.d.ts +1 -1
- package/client/organizations/organizationReadModels.js +11 -1
- package/client/organizations/organizationReadModels.js.map +1 -1
- package/client/organizations/organizationsTypes.d.ts +8 -5
- package/client/organizations/organizationsTypes.js.map +1 -1
- package/client/organizations/principalContainerMutations.js +2 -0
- package/client/organizations/principalContainerMutations.js.map +1 -1
- package/client/organizations/principalMutations.d.ts +4 -308
- package/client/organizations/principalMutations.js +165 -87
- package/client/organizations/principalMutations.js.map +1 -1
- package/data/persistence/principalCurrentAcknowledgementPersistence.d.ts +2 -2
- package/data/persistence/principalCurrentAcknowledgementPersistence.js +21 -14
- package/data/persistence/principalCurrentAcknowledgementPersistence.js.map +1 -1
- package/data/principals/currentPolicyReferenceResolver.js +2 -0
- package/data/principals/currentPolicyReferenceResolver.js.map +1 -0
- package/data/principals/principalHistoryScopeProtection.js +23 -0
- package/data/principals/principalHistoryScopeProtection.js.map +1 -0
- package/data/principals/principalPolicyAdminSigners.js.map +1 -1
- package/index.d.ts +1 -1
- package/index.js.map +1 -1
- package/internal/crypto/index.d.ts +1 -1
- package/internal/crypto/index.js +1 -1
- package/internal/crypto/index.js.map +1 -1
- package/internal/crypto/keying/index.d.ts +1 -0
- package/internal/crypto/keying/index.js +1 -0
- package/internal/crypto/keying/index.js.map +1 -1
- package/internal/crypto/keying/principalPolicyCurrentPredecessorReferences.d.ts +8 -0
- package/internal/crypto/keying/principalPolicyCurrentPredecessorReferences.js +46 -0
- package/internal/crypto/keying/principalPolicyCurrentPredecessorReferences.js.map +1 -0
- package/package.json +1 -1
- package/workflows/containers/child/carriedDescendantRekeys.js +9 -1
- package/workflows/containers/child/carriedDescendantRekeys.js.map +1 -1
- package/workflows/containers/child/replacementPrincipalPolicyReferences.js +19 -0
- package/workflows/containers/child/replacementPrincipalPolicyReferences.js.map +1 -0
- package/workflows/organizations/commitCurrentGroupPolicyMutation.js +72 -0
- package/workflows/organizations/commitCurrentGroupPolicyMutation.js.map +1 -0
- package/workflows/organizations/createCurrentOrganizationGroup.js +85 -0
- package/workflows/organizations/createCurrentOrganizationGroup.js.map +1 -0
- package/workflows/organizations/currentGroupMetadataAuthority.js +24 -3
- package/workflows/organizations/currentGroupMetadataAuthority.js.map +1 -1
- package/workflows/organizations/currentGroupMutationReferences.js +35 -0
- package/workflows/organizations/currentGroupMutationReferences.js.map +1 -0
- package/workflows/organizations/currentGroupPolicyMutationContext.js +79 -0
- package/workflows/organizations/currentGroupPolicyMutationContext.js.map +1 -0
- package/workflows/organizations/currentOrganizationGroupNames.js +5 -1
- package/workflows/organizations/currentOrganizationGroupNames.js.map +1 -1
- package/workflows/organizations/currentOrganizationMutationAuthority.js +16 -0
- package/workflows/organizations/currentOrganizationMutationAuthority.js.map +1 -0
- package/workflows/organizations/currentOrganizationMutationRetention.js +53 -0
- package/workflows/organizations/currentOrganizationMutationRetention.js.map +1 -0
- package/workflows/organizations/currentPrincipalMutationLease.js +38 -0
- package/workflows/organizations/currentPrincipalMutationLease.js.map +1 -0
- package/workflows/organizations/deleteCurrentOrganizationGroup.js +35 -0
- package/workflows/organizations/deleteCurrentOrganizationGroup.js.map +1 -0
- package/workflows/organizations/deleteOrganizationGroup.d.ts +1 -0
- package/workflows/organizations/deleteOrganizationGroup.js +10 -0
- package/workflows/organizations/deleteOrganizationGroup.js.map +1 -1
- package/workflows/organizations/groupCreation.d.ts +1 -0
- package/workflows/organizations/groupCreation.js +8 -0
- package/workflows/organizations/groupCreation.js.map +1 -1
- package/workflows/organizations/groupMembershipName.d.ts +1 -1
- package/workflows/organizations/groupMembershipName.js.map +1 -1
- package/workflows/organizations/groupMetadataRuntime.js +14 -9
- package/workflows/organizations/groupMetadataRuntime.js.map +1 -1
- package/workflows/organizations/groupNameUniqueness.js +1 -1
- package/workflows/organizations/groupNameUniqueness.js.map +1 -1
- package/workflows/organizations/groupPolicyHistoryPage.js +31 -0
- package/workflows/organizations/groupPolicyHistoryPage.js.map +1 -0
- package/workflows/organizations/groupPolicyMutationAcknowledgement.js +1 -0
- package/workflows/organizations/groupPolicyMutationAcknowledgement.js.map +1 -1
- package/workflows/organizations/groupPolicyMutationContext.d.ts +18 -0
- package/workflows/organizations/groupPolicyMutationContext.js +1 -1
- package/workflows/organizations/groupPolicyMutationContext.js.map +1 -1
- package/workflows/organizations/initialPrincipalCurrentPublication.js +83 -0
- package/workflows/organizations/initialPrincipalCurrentPublication.js.map +1 -0
- package/workflows/organizations/organizationGroupDirectory.js +6 -0
- package/workflows/organizations/organizationGroupDirectory.js.map +1 -1
- package/workflows/organizations/organizationGroupNames.js.map +1 -1
- package/workflows/organizations/policyHistoryTypes.d.ts +2 -0
- package/workflows/organizations/policyHistoryTypes.js.map +1 -1
- package/workflows/organizations/principalContainerRematerialization.js +12 -2
- package/workflows/organizations/principalContainerRematerialization.js.map +1 -1
- package/workflows/organizations/principalContainerRematerializationPlanning.js +1 -0
- package/workflows/organizations/principalContainerRematerializationPlanning.js.map +1 -1
- package/workflows/organizations/principalContainerRematerializationTargets.js.map +1 -1
- package/workflows/organizations/retainAcknowledgedPrincipalCurrents.d.ts +2 -0
- package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js +5 -1
- package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js.map +1 -1
- package/workflows/organizations/runtimeCurrentGroupMutation.js +85 -0
- package/workflows/organizations/runtimeCurrentGroupMutation.js.map +1 -0
- package/workflows/organizations/runtimeCurrentOrganizationMutation.js +48 -0
- package/workflows/organizations/runtimeCurrentOrganizationMutation.js.map +1 -0
- package/workflows/principals/loadRecoveredPrincipalHistoryPage.d.ts +11 -0
- package/workflows/principals/loadRecoveredPrincipalHistoryPage.js +120 -0
- package/workflows/principals/loadRecoveredPrincipalHistoryPage.js.map +1 -0
- package/workflows/principals/principalHistoryRecoveryReferences.js +8 -0
- package/workflows/principals/principalHistoryRecoveryReferences.js.map +1 -1
- package/workflows/principals/principalRecoveryDirectory.js +3 -8
- package/workflows/principals/principalRecoveryDirectory.js.map +1 -1
- package/workflows/principals/principalRecoveryLocalPreference.js +3 -2
- package/workflows/principals/principalRecoveryLocalPreference.js.map +1 -1
- package/workflows/principals/recoverCurrentOrganizationPolicy.js.map +1 -1
- package/workflows/principals/recoverPrincipalHistoryPage.js +30 -0
- package/workflows/principals/recoverPrincipalHistoryPage.js.map +1 -0
- package/workflows/principals/recoverPrincipalPolicyHistory.d.ts +2 -0
- package/workflows/principals/recoverPrincipalPolicyHistory.js +14 -2
- package/workflows/principals/recoverPrincipalPolicyHistory.js.map +1 -1
- package/workflows/principals/recoverScopedPrincipalPolicyHistory.d.ts +6 -0
- package/workflows/principals/recoverScopedPrincipalPolicyHistory.js +31 -19
- package/workflows/principals/recoverScopedPrincipalPolicyHistory.js.map +1 -1
- package/workflows/principals/runtimePolicyRecovery.js +25 -4
- package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
- package/workflows/principals/runtimePolicyWarmer.js +2 -2
- package/workflows/principals/runtimePolicyWarmer.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalContainerRematerializationPlanning.js","sourceRoot":"","sources":["principalContainerRematerializationPlanning.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"principalContainerRematerializationPlanning.js","sourceRoot":"","sources":["principalContainerRematerializationPlanning.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,6BAA6B,EAAE,MAAM,4BAA4B,CAAC;AAa3E,OAAO,EACL,0BAA0B,GAE3B,MAAM,6CAA6C,CAAC;AAmDrD,uEAAuE;AACvE,SAAS,YAAY,CAAC,KAAoB;IACxC,OAAO,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC;AAC7D,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,CAC9B,KAAoB,EACpB,MAAyC;IAEzC,MAAM,EAAE,iBAAiB,EAAE,GAAG,KAAK,CAAC;IACpC,IAAI,YAAY,CAAC,KAAK,CAAC,IAAI,6BAA6B,EAAE,CAAC;QACzD,MAAM,IAAI,KAAK,CACb,uCAAuC,6BAA6B,oBAAoB,CACzF,CAAC;IACJ,CAAC;IACD,MAAM,OAAO,GAAG,MAAM,0BAA0B,CAAC;QAC/C,SAAS,EAAE,iBAAiB,CAAC,SAAS;QACtC,MAAM,EAAE,iBAAiB,CAAC,MAAM;QAChC,OAAO,EAAE,iBAAiB,CAAC,OAAO;QAClC,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,8DAA8D;QAC9D,sDAAsD;QACtD,0BAA0B,EAAE,iBAAiB,CAAC,UAAU;QACxD,+BAA+B,EAC7B,iBAAiB,CAAC,+BAA+B;QACnD,wBAAwB,EAAE,KAAK,CAAC,wBAAwB;QACxD,OAAO,EAAE,KAAK,CAAC,YAAY;QAC3B,MAAM;QACN,YAAY,EAAE,iBAAiB,CAAC,YAAY;QAC5C,eAAe,EAAE,iBAAiB,CAAC,eAAe;QAClD,+BAA+B,EAC7B,iBAAiB,CAAC,+BAA+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,UAAU,GAAG,CAAC;QACnB,CAAC,CAAC,EAAE;QACJ,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;AAC9D,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { PrincipalContainerGrant } from \"@tearleads/crypto\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { MAX_ROTATION_CONTAINER_REKEYS } from \"@tearleads/validators/util\";\nimport type { ContainerReciteApi } from \"../../data/containers/shared/reciteApi\";\nimport type { ContainerMutationAuthor } from \"../../data/containers/shared/types\";\nimport type {\n PrincipalPolicyCache,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../data/keyingProjectionVerification\";\nimport type { createProjectionUserKeyResolver } from \"../../data/keyingProjectionVerification/userKeyResolver\";\nimport type { CurrentPolicyReferenceResolver } from \"../../data/principals/currentPolicyReferenceResolver\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../data/principals/principalPolicyEvidence\";\nimport type { SecurityIncidentReporter } from \"../../data/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport {\n planCarriedDescendantRekey,\n type SpeculativePath,\n} from \"../containers/child/carriedDescendantRekeys\";\nimport type { PlannedRematerialization } from \"./principalContainerRematerializationTargets\";\n\nexport interface RematerializationApi\n extends ContainerReciteApi,\n Pick<ApiClient, \"getContainerWriterProjectionResult\"> {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n}\n\nexport interface PrincipalContainerRematerializationInput {\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly apiClient: RematerializationApi;\n readonly author: ContainerMutationAuthor;\n readonly execSql: ExecSql;\n readonly grants: readonly PrincipalContainerGrant[];\n readonly groupId: string;\n readonly nextPolicy: PrincipalPolicyCurrentEvidence;\n readonly resolveAuthoredPolicyReferences?:\n | CurrentPolicyReferenceResolver\n | undefined;\n readonly revokedContainerId?: string | undefined;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n /** Session lifetime for best-effort work after durable acknowledgement. */\n readonly recitationStillCurrent?: (() => boolean) | undefined;\n readonly targetSecretKey: Uint8Array;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}\n\n/** What the batch has signed so far, in the order it will be submitted. */\nexport interface BatchPlanning {\n /**\n * Keys the batch minted, by epoch id. A rotation wraps its successor to the\n * group at the head this batch commits, which no store can open yet; a\n * level planned beneath it opens that epoch with the key minted here, and\n * its keyring then opens the retired epoch the level below is pinned to.\n */\n readonly knownContainerKeks: Map<string, Uint8Array>;\n readonly plans: PlannedRematerialization[];\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly rematerialization: PrincipalContainerRematerializationInput;\n readonly resolveProjectionUserKey: ReturnType<\n typeof createProjectionUserKeyResolver\n >;\n readonly rotatedAbove: SpeculativePath[];\n}\n\n/** How many rekeys the batch carries beyond its rematerializations. */\nfunction carriedCount(batch: BatchPlanning): number {\n return batch.plans.filter((entry) => entry.carried).length;\n}\n\n/**\n * Sign a rekey of `served` under the batch's rotations above it, and add it.\n * The server accepts at most `MAX_ROTATION_CONTAINER_REKEYS` carried entries;\n * past that a rematerialization below them could not be signed on a current\n * path, so the batch is refused here, before signing what the server would\n * refuse anyway, and the policy change has to wait for a lazy repair of the\n * tree. Groups granted that far apart on one chain are not a shape the SDK\n * creates.\n */\nexport async function carryLevel(\n batch: BatchPlanning,\n served: ContainerWriterProjectionResponse,\n): Promise<void> {\n const { rematerialization } = batch;\n if (carriedCount(batch) >= MAX_ROTATION_CONTAINER_REKEYS) {\n throw new Error(\n `Policy change would carry more than ${MAX_ROTATION_CONTAINER_REKEYS} descendant rekeys`,\n );\n }\n const planned = await planCarriedDescendantRekey({\n apiClient: rematerialization.apiClient,\n author: rematerialization.author,\n execSql: rematerialization.execSql,\n knownContainerKeks: batch.knownContainerKeks,\n principalPolicyCache: batch.principalPolicyCache,\n // Its path cites the policy this batch commits, so like every\n // rematerialized rotation it must cite the successor.\n replacementPrincipalPolicy: rematerialization.nextPolicy,\n resolveAuthoredPolicyReferences:\n rematerialization.resolveAuthoredPolicyReferences,\n resolveProjectionUserKey: batch.resolveProjectionUserKey,\n rotated: batch.rotatedAbove,\n served,\n stillCurrent: rematerialization.stillCurrent,\n targetSecretKey: rematerialization.targetSecretKey,\n warmReferencedPrincipalPolicies:\n rematerialization.warmReferencedPrincipalPolicies,\n });\n addPlan(batch, { carried: true, planned, rotated: planned.writerProjection });\n}\n\nexport function addPlan(\n batch: BatchPlanning,\n entry: PlannedRematerialization,\n): void {\n batch.plans.push(entry);\n if (!entry.rotated) return;\n batch.rotatedAbove.push(entry.rotated);\n const minted = entry.rotated.containerKeks.at(-1)?.containerKeyEpochId;\n if (minted) batch.knownContainerKeks.set(minted, entry.planned.containerKey);\n}\n\n/**\n * Levels of a re-rooted path pinned to an epoch the batch retires above them:\n * those strictly between the rotated ancestor the path was re-rooted on and\n * the target, parent-first, from the first stale one down. A rotation planned\n * above a target strands every level between the two, and each must be\n * re-keyed under the one above before the target can be signed. The batch\n * carries them without waiting to be told: they are proper ancestors of a\n * granted container, so the server would name them, and a refusal per level\n * is a round trip each. Anything stale above the rotated ancestor is not this\n * batch's doing and is left alone. `carryLevel` holds the count to the cap.\n */\nexport function staleLevelsAbove(\n projection: ContainerWriterProjectionResponse,\n rotatedAncestorId: string,\n): string[] {\n const keks = projection.containerKeks;\n const ancestor = keks.findIndex(\n (kek) => kek.containerId === rotatedAncestorId,\n );\n if (ancestor < 0) return [];\n const between = keks.slice(ancestor, -1);\n const firstStale = between.findIndex(\n (kek, index) =>\n index > 0 &&\n kek.parentContainerKeyEpochId !== between[index - 1]?.containerKeyEpochId,\n );\n return firstStale < 0\n ? []\n : between.slice(firstStale).map((kek) => kek.containerId);\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalContainerRematerializationTargets.js","sourceRoot":"","sources":["principalContainerRematerializationTargets.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"principalContainerRematerializationTargets.js","sourceRoot":"","sources":["principalContainerRematerializationTargets.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,6BAA6B,EAAE,MAAM,4BAA4B,CAAC;AAC3E,OAAO,EAAE,0BAA0B,EAAE,MAAM,+CAA+C,CAAC;AAO3F,OAAO,EAAE,4BAA4B,EAAE,MAAM,8DAA8D,CAAC;AAG5G,OAAO,EAAE,yCAAyC,EAAE,MAAM,qCAAqC,CAAC;AAwBhG;;;;;;GAMG;AACH,MAAM,UAAU,kCAAkC,CAOhD,KAAmB;IACnB,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC,IAAI,CACpB,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CACd,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM;QAC1D,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,aAAa,CAAC,KAAK,CAAC,UAAU,CAAC,WAAW,CAAC,CAC1E,CAAC;AACJ,CAAC;AAQD,oEAAoE;AACpE,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,SAAwB,EACxB,WAAmB;IAEnB,MAAM,UAAU,GAAG,MAAM,SAAS,CAAC,4BAA4B,CAAC,WAAW,CAAC,CAAC;IAC7E,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,MAAM,IAAI,KAAK,CACb,aAAa,WAAW,+CAA+C,CACxE,CAAC;IACJ,CAAC;IACD,IAAI,UAAU,CAAC,WAAW,KAAK,WAAW,EAAE,CAAC;QAC3C,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;IACnE,CAAC;IACD,OAAO,U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C;YACD,MAAM,CAAC,MAAM,EAAE,CAAC;YAChB,MAAM,IAAI,KAAK,CACb,aAAa,WAAW,kDAAkD,MAAM,CAAC,OAAO,EAAE,CAC3F,CAAC;QACJ,CAAC;QACD,IAAI,MAAM,CAAC,IAAI,CAAC,WAAW,KAAK,WAAW;YACzC,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;QACnE,OAAO,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC;IACtD,CAAC;IACD,OAAO;QACL,OAAO,EAAE,kCAAkC,CAAC,OAAO,CAAC;QACpD,mBAAmB;KACpB,CAAC;AACJ,CAAC;AAED,gFAAgF;AAChF,MAAM,UAAU,0BAA0B,CACxC,UAA0C;IAE1C,OAAO,IAAI,GAAG,CAAC;QACb;YACE,4BAA4B,CAAC;gBAC3B,QAAQ,EAAE,UAAU,CAAC,QAAQ;gBAC7B,cAAc,EAAE,UAAU,CAAC,KAAK,CAAC,cAAc;gBAC/C,WAAW,EAAE,UAAU,CAAC,WAAW;gBACnC,aAAa,EAAE,UAAU,CAAC,aAAa;gBACvC,SAAS,EAAE,UAAU,CAAC,SAAS;gBAC/B,OAAO,EAAE,UAAU,CAAC,OAAO;aAC5B,CAAC;YACF,UAAU;SACX;KACF,CAAC,CAAC;AACL,CAAC;AAED,kEAAkE;AAClE,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,KAGjC;IACC,MAAM,EAAE,IAAI,EAAE,GAAG,KAAK,CAAC,OAAO,CAAC;IAC/B,IAAI,CAAC,CAAC,SAAS,IAAI,IAAI,CAAC;QAAE,OAAO,IAAI,CAAC;IACtC,OAAO,yCAAyC,CAAC;QAC/C,IAAI;QACJ,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;KAC7C,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { PrincipalContainerGrant } from \"@tearleads/crypto\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { MAX_ROTATION_CONTAINER_REKEYS } from \"@tearleads/validators/util\";\nimport { isContainerNotFoundFailure } from \"../../data/containers/shared/mutationFailures\";\nimport type {\n MaterializedContainerRekeyPlan,\n MaterializedContainerRevokePlan,\n MaterializedContainerSharePlan,\n} from \"../../data/containers/shared/types\";\nimport type { PrincipalPolicyCache } from \"../../data/keyingProjectionVerification\";\nimport { referencedPrincipalPolicyKey } from \"../../data/keyingProjectionVerification/principalPolicyCache\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../data/principals/principalPolicyEvidence\";\nimport type { SpeculativePath } from \"../containers/child/carriedDescendantRekeys\";\nimport { containerWriterProjectionFromRotationPlan } from \"../containers/child/rekeyProjection\";\n\nexport type MaterializedPrincipalContainerMutationPlan =\n | MaterializedContainerRekeyPlan\n | MaterializedContainerRevokePlan\n | MaterializedContainerSharePlan;\n\n/** A plan with its container's path once accepted; null for a grant, which rotates nothing. */\nexport interface PlannedRematerialization {\n /** A descendant rekey carried for a rotation above, not a rematerialization. */\n readonly carried: boolean;\n readonly planned: MaterializedPrincipalContainerMutationPlan;\n readonly rotated: SpeculativePath | null;\n}\n\n/**\n * One container a batch signs for: a group grant it rematerializes, or a\n * descendant rekey it carries for a rotation above (`grantRow` null).\n */\nexport interface RematerializationTarget {\n readonly grantRow: PrincipalContainerGrant | null;\n readonly projection: ContainerWriterProjectionResponse;\n}\n\n/**\n * Order a batch parent-first, by served depth. A group granted on a container\n * and on one of its descendants rotates both, and the lower rotation must be\n * signed against the epoch the upper one mints in this same batch, or it\n * extends a head the batch itself retires. A carried rekey sits below the\n * rotation it rides for the same reason. Ties keep id order for stability.\n */\nexport function orderRematerializationsParentFirst<\n T extends {\n readonly projection: {\n readonly containerId: string;\n readonly path: readonly unknown[];\n };\n },\n>(batch: readonly T[]): T[] {\n return [...batch].sort(\n (left, right) =>\n left.projection.path.length - right.projection.path.length ||\n left.projection.containerId.localeCompare(right.projection.containerId),\n );\n}\n\ninterface ProjectionApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n}\n\n/** The served projection of a container the batch will sign for. */\nexport async function loadServedProjection(\n apiClient: ProjectionApi,\n containerId: string,\n): Promise<ContainerWriterProjectionResponse> {\n const projection = await apiClient.getContainerWriterProjection(containerId);\n if (!projection) {\n throw new Error(\n `Container ${containerId} could not be prepared for principal rotation`,\n );\n }\n if (projection.containerId !== containerId) {\n throw new Error(\"Served projection describes another container\");\n }\n return projection;\n}\n\n/**\n * Fetch what the batch signs for, parent-first. A named descendant the batch\n * already rematerializes is not fetched twice: its own rotation is re-planned\n * under whatever the batch carries above it. Names are a hint from the server,\n * never an authority; each is verified where it is planned.\n */\nexport async function loadRematerializationTargets(input: {\n readonly apiClient: Pick<ApiClient, \"getContainerWriterProjectionResult\">;\n readonly carriedContainerIds: readonly string[];\n readonly grants: readonly PrincipalContainerGrant[];\n}): Promise<{\n targets: RematerializationTarget[];\n retiredContainerIds: string[];\n}> {\n const grantByContainerId = new Map(\n input.grants.map((grant) => [grant.containerId, grant] as const),\n );\n const carried = [...new Set(input.carriedContainerIds)]\n .filter((containerId) => !grantByContainerId.has(containerId))\n .slice(0, MAX_ROTATION_CONTAINER_REKEYS);\n const targets: RematerializationTarget[] = [];\n const retiredContainerIds: string[] = [];\n for (const containerId of [...grantByContainerId.keys(), ...carried].sort(\n (left, right) => left.localeCompare(right),\n )) {\n const grantRow = grantByContainerId.get(containerId) ?? null;\n const result = await input.apiClient.getContainerWriterProjectionResult(\n containerId,\n { reportErrors: false },\n );\n if (!result.ok) {\n // This is only a planning hint. Keep the signed grant intact; the API\n // independently requires every live grant under the organization lock.\n if (\n grantRow &&\n result.kind === \"http\" &&\n isContainerNotFoundFailure(result)\n ) {\n retiredContainerIds.push(containerId);\n continue;\n }\n result.report();\n throw new Error(\n `Container ${containerId} could not be prepared for principal rotation: ${result.message}`,\n );\n }\n if (result.data.containerId !== containerId)\n throw new Error(\"Served projection describes another container\");\n targets.push({ grantRow, projection: result.data });\n }\n return {\n targets: orderRematerializationsParentFirst(targets),\n retiredContainerIds,\n };\n}\n\n/** An in-memory cache holding only the policy this batch is about to commit. */\nexport function seededPrincipalPolicyCache(\n nextPolicy: PrincipalPolicyCurrentEvidence,\n): PrincipalPolicyCache {\n return new Map([\n [\n referencedPrincipalPolicyKey({\n keyEpoch: nextPolicy.keyEpoch,\n keyFingerprint: nextPolicy.state.keyFingerprint,\n principalId: nextPolicy.principalId,\n principalType: nextPolicy.principalType,\n stateHash: nextPolicy.stateHash,\n version: nextPolicy.version,\n }),\n nextPolicy,\n ],\n ]);\n}\n\n/** A rematerialization's path once accepted; null for a grant. */\nexport async function rotatedPath(input: {\n readonly planned: MaterializedPrincipalContainerMutationPlan;\n readonly previousProjection: ContainerWriterProjectionResponse;\n}): Promise<SpeculativePath | null> {\n const { plan } = input.planned;\n if (!(\"keyring\" in plan)) return null;\n return containerWriterProjectionFromRotationPlan({\n plan,\n previousProjection: input.previousProjection,\n });\n}\n"]}
|
|
@@ -6,6 +6,8 @@ import type { ExecSql } from "../../data/sqlite/sqlSchema.js";
|
|
|
6
6
|
import type { RecoverPrincipalPolicyHistoryOptions } from "../principals/principalHistoryRecoveryTypes.js";
|
|
7
7
|
export type { AcknowledgedPrincipalCurrentRetirement } from "../../data/persistence/principalCurrentAcknowledgementPersistence.js";
|
|
8
8
|
export interface AcknowledgedPrincipalCurrentInput {
|
|
9
|
+
/** Only a newly authored group at version one; never skips a predecessor. */
|
|
10
|
+
readonly initialGroup?: boolean | undefined;
|
|
9
11
|
/** The same scoped protection and verification mode used to recover the predecessor. */
|
|
10
12
|
readonly recovery: Omit<RecoverPrincipalPolicyHistoryOptions, "execSql" | "organizationId" | "stillCurrent">;
|
|
11
13
|
readonly request: PutPrincipalPolicyRequest;
|
|
@@ -11,6 +11,7 @@ import { assertPrincipalHistoryVerificationMode, principalHistoryVerificationCon
|
|
|
11
11
|
import { assertAcknowledgedDirectoryBindings } from "./acknowledgedDirectoryBindings.js";
|
|
12
12
|
import { acknowledgeGroupPolicyState } from "./groupPolicyMutationAcknowledgement.js";
|
|
13
13
|
import { groupPolicyMutationHead } from "./groupPolicyMutationHead.js";
|
|
14
|
+
import { prepareInitialGroupCurrentPublication } from "./initialPrincipalCurrentPublication.js";
|
|
14
15
|
import { sealPrincipalCurrentPublication, sealPrincipalCurrentStage, } from "./principalCurrentPublicationSeal.js";
|
|
15
16
|
import { assertPrincipalPolicyReceiptArtifacts } from "./principalPolicyReceiptArtifacts.js";
|
|
16
17
|
async function restorePredecessor(options) {
|
|
@@ -122,6 +123,7 @@ export async function retainAcknowledgedPrincipalCurrents(input) {
|
|
|
122
123
|
assertProjectionVerificationCurrent(stillCurrent);
|
|
123
124
|
for (const entry of input.entries)
|
|
124
125
|
entries.push({
|
|
126
|
+
initialGroup: entry.initialGroup === true,
|
|
125
127
|
request: structuredClone(entry.request),
|
|
126
128
|
response: structuredClone(entry.response),
|
|
127
129
|
options: {
|
|
@@ -135,7 +137,9 @@ export async function retainAcknowledgedPrincipalCurrents(input) {
|
|
|
135
137
|
});
|
|
136
138
|
const publications = [];
|
|
137
139
|
for (const entry of entries)
|
|
138
|
-
publications.push(await
|
|
140
|
+
publications.push(await (entry.initialGroup
|
|
141
|
+
? prepareInitialGroupCurrentPublication
|
|
142
|
+
: preparePublication)(entry.options, entry.request, entry.response));
|
|
139
143
|
assertAcknowledgedDirectoryBindings(organizationId, entries.map(({ response }) => response));
|
|
140
144
|
await persistAcknowledgedPrincipalCurrents({
|
|
141
145
|
execSql,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retainAcknowledgedPrincipalCurrents.js","sourceRoot":"","sources":["retainAcknowledgedPrincipalCurrents.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,qCAAqC,EAErC,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,mCAAmC,EAAE,MA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,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC;SAC3D,CAAC,CAAC;QACH,OAAO,YAAY,CAAC,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC;IAClD,CAAC;YAAS,CAAC;QACT,KAAK,MAAM,KAAK,IAAI,OAAO;YAAE,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACzE,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n restorePrincipalPolicyHistoryVerifier,\n type VerifiedPrincipalPolicyCurrent,\n verifyPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyMutationResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport {\n type AcknowledgedPrincipalCurrentPublication,\n type AcknowledgedPrincipalCurrentRetirement,\n persistAcknowledgedPrincipalCurrents,\n} from \"../../data/persistence/principalCurrentAcknowledgementPersistence\";\nimport { preparePrincipalHistoryEvidencePage } from \"../../data/persistence/principalHistoryEvidencePersistence\";\nimport { loadPrincipalHistoryPrefix } from \"../../data/persistence/principalHistoryPrefixPersistence\";\nimport {\n principalHistoryEvidenceScopeId,\n principalHistoryPrefixProtection,\n} from \"../../data/principals/principalHistoryPrefixProtection\";\nimport { ownPrincipalHistoryProtection } from \"../../data/principals/principalHistoryProtection\";\nimport { parsePrincipalHistoryStageCurrent } from \"../../data/principals/principalHistoryStageProtection\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { collectPrincipalPolicySignerPublicKeys } from \"../principals/policyVerification\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"../principals/principalHistoryRecoveryTypes\";\nimport {\n assertPrincipalHistoryVerificationMode,\n principalHistoryVerificationContext,\n} from \"../principals/principalHistoryRecoveryVerification\";\nimport { assertAcknowledgedDirectoryBindings } from \"./acknowledgedDirectoryBindings\";\nimport { acknowledgeGroupPolicyState } from \"./groupPolicyMutationAcknowledgement\";\nimport { groupPolicyMutationHead } from \"./groupPolicyMutationHead\";\nimport {\n sealPrincipalCurrentPublication,\n sealPrincipalCurrentStage,\n} from \"./principalCurrentPublicationSeal\";\nimport { assertPrincipalPolicyReceiptArtifacts } from \"./principalPolicyReceiptArtifacts\";\n\nexport type { AcknowledgedPrincipalCurrentRetirement } from \"../../data/persistence/principalCurrentAcknowledgementPersistence\";\n\nexport interface AcknowledgedPrincipalCurrentInput {\n /** The same scoped protection and verification mode used to recover the predecessor. */\n readonly recovery: Omit<\n RecoverPrincipalPolicyHistoryOptions,\n \"execSql\" | \"organizationId\" | \"stillCurrent\"\n >;\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n}\n\nasync function restorePredecessor(\n options: RecoverPrincipalPolicyHistoryOptions,\n) {\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: options.organizationId,\n head: options.expectedHead,\n protection: options.protection,\n });\n const saved = await loadPrincipalHistoryPrefix(options.execSql, scopeId);\n if (!saved || saved.organizationId !== options.organizationId)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Acknowledgement requires its authenticated predecessor prefix\",\n );\n const restored = await restorePrincipalPolicyHistoryVerifier(\n {\n principalId: options.expectedHead.principalId,\n principalType: options.expectedHead.principalType,\n },\n saved.progress,\n await principalHistoryPrefixProtection(options.protection, saved),\n );\n if (!restored.ok) throw restored.error;\n const history = restored.value.finish(options.expectedHead);\n if (!history.ok) throw history.error;\n const artifacts = parsePrincipalHistoryStageCurrent({\n currentJson: saved.currentJson,\n afterVersion: saved.version - 1,\n });\n if (!artifacts)\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Acknowledged predecessor artifacts are malformed\",\n );\n const previous = await verifyPrincipalPolicyCurrent({\n current: artifacts,\n history: history.value,\n });\n if (!previous.ok) throw previous.error;\n return {\n scopeId,\n saved,\n artifacts,\n verifier: restored.value,\n previous: previous.value,\n };\n}\n\nasync function preparePublication(\n options: RecoverPrincipalPolicyHistoryOptions,\n request: PutPrincipalPolicyRequest,\n response: PrincipalPolicyMutationResponse,\n): Promise<AcknowledgedPrincipalCurrentPublication> {\n options = {\n ...options,\n protection: {\n ...options.protection,\n context: principalHistoryVerificationContext(options),\n },\n };\n const current = () => !options.signal?.aborted && options.stillCurrent();\n assertProjectionVerificationCurrent(current);\n const { scopeId, saved, artifacts, verifier, previous } =\n await restorePredecessor(options);\n const expectedHead = await groupPolicyMutationHead(request);\n assertPrincipalPolicyReceiptArtifacts({ expectedHead, request, response });\n const keys = await collectPrincipalPolicySignerPublicKeys({\n bundle: { currentState: response.currentState, previousStates: [] },\n resolveTrustedUserIdentity: options.resolveTrustedUserIdentity,\n });\n assertProjectionVerificationCurrent(current);\n if (\"error\" in keys)\n throw new KeyingVerificationError(\n keys.error === \"not-found\" ? \"missing_dependency\" : \"signer_mismatch\",\n \"Acknowledged principal signer could not be authenticated\",\n );\n const externalAuthority = await options.loadExternalAuthority?.(\n request.state.externalAuthority ? [request.state.externalAuthority] : [],\n );\n assertProjectionVerificationCurrent(current);\n const policy = await acknowledgeGroupPolicyState({\n verifiedCurrentPolicy: previous,\n expectedHead,\n request,\n response: response.currentState,\n signerPublicKeys: keys.signerPublicKeys,\n externalAuthority,\n stillCurrent: current,\n });\n const entry = {\n state: response.currentState,\n projection: response.currentProjection,\n grants: response.currentGrants,\n };\n assertPrincipalHistoryVerificationMode(options, [entry]);\n const predecessorStage = await sealPrincipalCurrentStage(\n options,\n previous.state,\n verifier,\n artifacts,\n );\n const appended = await verifier.append({\n entries: [entry],\n signerPublicKeys: keys.signerPublicKeys,\n ...(externalAuthority ? { externalAuthority } : {}),\n });\n if (!appended.ok) throw appended.error;\n const sealed = await sealPrincipalCurrentPublication(\n options,\n scopeId,\n expectedHead,\n verifier,\n response,\n );\n assertProjectionVerificationCurrent(current);\n return {\n policy,\n previousPrefixProgress: saved.progress,\n predecessorStage,\n ...sealed,\n evidence: await preparePrincipalHistoryEvidencePage({\n scopeId,\n organizationId: options.organizationId,\n entries: [entry],\n nodes: appended.value.indexNodes,\n }),\n };\n}\n\n/** Extend authenticated local progress and retain exact acknowledged artifacts atomically with pins. */\nexport async function retainAcknowledgedPrincipalCurrents(input: {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly entries: readonly AcknowledgedPrincipalCurrentInput[];\n readonly retirements?:\n | readonly AcknowledgedPrincipalCurrentRetirement[]\n | undefined;\n readonly stillCurrent: () => boolean;\n}): Promise<VerifiedPrincipalPolicyCurrent[]> {\n const execSql = input.execSql;\n const organizationId = input.organizationId;\n const stillCurrent = input.stillCurrent;\n const retirements = structuredClone(input.retirements ?? []);\n const entries: {\n request: PutPrincipalPolicyRequest;\n response: PrincipalPolicyMutationResponse;\n options: RecoverPrincipalPolicyHistoryOptions;\n }[] = [];\n try {\n assertProjectionVerificationCurrent(stillCurrent);\n for (const entry of input.entries)\n entries.push({\n request: structuredClone(entry.request),\n response: structuredClone(entry.response),\n options: {\n ...entry.recovery,\n expectedHead: structuredClone(entry.recovery.expectedHead),\n protection: ownPrincipalHistoryProtection(entry.recovery.protection),\n execSql,\n organizationId,\n stillCurrent,\n },\n });\n const publications: AcknowledgedPrincipalCurrentPublication[] = [];\n for (const entry of entries)\n publications.push(\n await preparePublication(entry.options, entry.request, entry.response),\n );\n assertAcknowledgedDirectoryBindings(\n organizationId,\n entries.map(({ response }) => response),\n );\n await persistAcknowledgedPrincipalCurrents({\n execSql,\n organizationId,\n entries: publications,\n retirements,\n stillCurrent: () =>\n stillCurrent() &&\n entries.every((entry) => !entry.options.signal?.aborted),\n });\n return publications.map(({ policy }) => policy);\n } finally {\n for (const entry of entries) entry.options.protection.localKey.fill(0);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"retainAcknowledgedP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,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,QAAQ,CAAC,CACtE,CAAC;QACJ,mCAAmC,CACjC,cAAc,EACd,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC,QAAQ,CAAC,CACxC,CAAC;QACF,MAAM,oCAAoC,CAAC;YACzC,OAAO;YACP,cAAc;YACd,OAAO,EAAE,YAAY;YACrB,WAAW;YACX,YAAY,EAAE,GAAG,EAAE,CACjB,YAAY,EAAE;gBACd,OAAO,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC;SAC3D,CAAC,CAAC;QACH,OAAO,YAAY,CAAC,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC;IAClD,CAAC;YAAS,CAAC;QACT,KAAK,MAAM,KAAK,IAAI,OAAO;YAAE,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACzE,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n restorePrincipalPolicyHistoryVerifier,\n type VerifiedPrincipalPolicyCurrent,\n verifyPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyMutationResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport {\n type AcknowledgedPrincipalCurrentPublication,\n type AcknowledgedPrincipalCurrentRetirement,\n persistAcknowledgedPrincipalCurrents,\n} from \"../../data/persistence/principalCurrentAcknowledgementPersistence\";\nimport { preparePrincipalHistoryEvidencePage } from \"../../data/persistence/principalHistoryEvidencePersistence\";\nimport { loadPrincipalHistoryPrefix } from \"../../data/persistence/principalHistoryPrefixPersistence\";\nimport {\n principalHistoryEvidenceScopeId,\n principalHistoryPrefixProtection,\n} from \"../../data/principals/principalHistoryPrefixProtection\";\nimport { ownPrincipalHistoryProtection } from \"../../data/principals/principalHistoryProtection\";\nimport { parsePrincipalHistoryStageCurrent } from \"../../data/principals/principalHistoryStageProtection\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { collectPrincipalPolicySignerPublicKeys } from \"../principals/policyVerification\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"../principals/principalHistoryRecoveryTypes\";\nimport {\n assertPrincipalHistoryVerificationMode,\n principalHistoryVerificationContext,\n} from \"../principals/principalHistoryRecoveryVerification\";\nimport { assertAcknowledgedDirectoryBindings } from \"./acknowledgedDirectoryBindings\";\nimport { acknowledgeGroupPolicyState } from \"./groupPolicyMutationAcknowledgement\";\nimport { groupPolicyMutationHead } from \"./groupPolicyMutationHead\";\nimport { prepareInitialGroupCurrentPublication } from \"./initialPrincipalCurrentPublication\";\nimport {\n sealPrincipalCurrentPublication,\n sealPrincipalCurrentStage,\n} from \"./principalCurrentPublicationSeal\";\nimport { assertPrincipalPolicyReceiptArtifacts } from \"./principalPolicyReceiptArtifacts\";\n\nexport type { AcknowledgedPrincipalCurrentRetirement } from \"../../data/persistence/principalCurrentAcknowledgementPersistence\";\n\nexport interface AcknowledgedPrincipalCurrentInput {\n /** Only a newly authored group at version one; never skips a predecessor. */\n readonly initialGroup?: boolean | undefined;\n /** The same scoped protection and verification mode used to recover the predecessor. */\n readonly recovery: Omit<\n RecoverPrincipalPolicyHistoryOptions,\n \"execSql\" | \"organizationId\" | \"stillCurrent\"\n >;\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n}\n\nasync function restorePredecessor(\n options: RecoverPrincipalPolicyHistoryOptions,\n) {\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: options.organizationId,\n head: options.expectedHead,\n protection: options.protection,\n });\n const saved = await loadPrincipalHistoryPrefix(options.execSql, scopeId);\n if (!saved || saved.organizationId !== options.organizationId)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Acknowledgement requires its authenticated predecessor prefix\",\n );\n const restored = await restorePrincipalPolicyHistoryVerifier(\n {\n principalId: options.expectedHead.principalId,\n principalType: options.expectedHead.principalType,\n },\n saved.progress,\n await principalHistoryPrefixProtection(options.protection, saved),\n );\n if (!restored.ok) throw restored.error;\n const history = restored.value.finish(options.expectedHead);\n if (!history.ok) throw history.error;\n const artifacts = parsePrincipalHistoryStageCurrent({\n currentJson: saved.currentJson,\n afterVersion: saved.version - 1,\n });\n if (!artifacts)\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Acknowledged predecessor artifacts are malformed\",\n );\n const previous = await verifyPrincipalPolicyCurrent({\n current: artifacts,\n history: history.value,\n });\n if (!previous.ok) throw previous.error;\n return {\n scopeId,\n saved,\n artifacts,\n verifier: restored.value,\n previous: previous.value,\n };\n}\n\nasync function preparePublication(\n options: RecoverPrincipalPolicyHistoryOptions,\n request: PutPrincipalPolicyRequest,\n response: PrincipalPolicyMutationResponse,\n): Promise<AcknowledgedPrincipalCurrentPublication> {\n options = {\n ...options,\n protection: {\n ...options.protection,\n context: principalHistoryVerificationContext(options),\n },\n };\n const current = () => !options.signal?.aborted && options.stillCurrent();\n assertProjectionVerificationCurrent(current);\n const { scopeId, saved, artifacts, verifier, previous } =\n await restorePredecessor(options);\n const expectedHead = await groupPolicyMutationHead(request);\n assertPrincipalPolicyReceiptArtifacts({ expectedHead, request, response });\n const keys = await collectPrincipalPolicySignerPublicKeys({\n bundle: { currentState: response.currentState, previousStates: [] },\n resolveTrustedUserIdentity: options.resolveTrustedUserIdentity,\n });\n assertProjectionVerificationCurrent(current);\n if (\"error\" in keys)\n throw new KeyingVerificationError(\n keys.error === \"not-found\" ? \"missing_dependency\" : \"signer_mismatch\",\n \"Acknowledged principal signer could not be authenticated\",\n );\n const externalAuthority = await options.loadExternalAuthority?.(\n request.state.externalAuthority ? [request.state.externalAuthority] : [],\n );\n assertProjectionVerificationCurrent(current);\n const policy = await acknowledgeGroupPolicyState({\n verifiedCurrentPolicy: previous,\n expectedHead,\n request,\n response: response.currentState,\n signerPublicKeys: keys.signerPublicKeys,\n externalAuthority,\n stillCurrent: current,\n });\n const entry = {\n state: response.currentState,\n projection: response.currentProjection,\n grants: response.currentGrants,\n };\n assertPrincipalHistoryVerificationMode(options, [entry]);\n const predecessorStage = await sealPrincipalCurrentStage(\n options,\n previous.state,\n verifier,\n artifacts,\n );\n const appended = await verifier.append({\n entries: [entry],\n signerPublicKeys: keys.signerPublicKeys,\n ...(externalAuthority ? { externalAuthority } : {}),\n });\n if (!appended.ok) throw appended.error;\n const sealed = await sealPrincipalCurrentPublication(\n options,\n scopeId,\n expectedHead,\n verifier,\n response,\n );\n assertProjectionVerificationCurrent(current);\n return {\n policy,\n previousPrefixProgress: saved.progress,\n predecessorStage,\n ...sealed,\n evidence: await preparePrincipalHistoryEvidencePage({\n scopeId,\n organizationId: options.organizationId,\n entries: [entry],\n nodes: appended.value.indexNodes,\n }),\n };\n}\n\n/** Extend authenticated local progress and retain exact acknowledged artifacts atomically with pins. */\nexport async function retainAcknowledgedPrincipalCurrents(input: {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly entries: readonly AcknowledgedPrincipalCurrentInput[];\n readonly retirements?:\n | readonly AcknowledgedPrincipalCurrentRetirement[]\n | undefined;\n readonly stillCurrent: () => boolean;\n}): Promise<VerifiedPrincipalPolicyCurrent[]> {\n const execSql = input.execSql;\n const organizationId = input.organizationId;\n const stillCurrent = input.stillCurrent;\n const retirements = structuredClone(input.retirements ?? []);\n const entries: {\n initialGroup: boolean;\n request: PutPrincipalPolicyRequest;\n response: PrincipalPolicyMutationResponse;\n options: RecoverPrincipalPolicyHistoryOptions;\n }[] = [];\n try {\n assertProjectionVerificationCurrent(stillCurrent);\n for (const entry of input.entries)\n entries.push({\n initialGroup: entry.initialGroup === true,\n request: structuredClone(entry.request),\n response: structuredClone(entry.response),\n options: {\n ...entry.recovery,\n expectedHead: structuredClone(entry.recovery.expectedHead),\n protection: ownPrincipalHistoryProtection(entry.recovery.protection),\n execSql,\n organizationId,\n stillCurrent,\n },\n });\n const publications: AcknowledgedPrincipalCurrentPublication[] = [];\n for (const entry of entries)\n publications.push(\n await (entry.initialGroup\n ? prepareInitialGroupCurrentPublication\n : preparePublication)(entry.options, entry.request, entry.response),\n );\n assertAcknowledgedDirectoryBindings(\n organizationId,\n entries.map(({ response }) => response),\n );\n await persistAcknowledgedPrincipalCurrents({\n execSql,\n organizationId,\n entries: publications,\n retirements,\n stillCurrent: () =>\n stillCurrent() &&\n entries.every((entry) => !entry.options.signal?.aborted),\n });\n return publications.map(({ policy }) => policy);\n } finally {\n for (const entry of entries) entry.options.protection.localKey.fill(0);\n }\n}\n"]}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { assertProjectionVerificationCurrent } from "../../data/keyingProjectionVerification/types.js";
|
|
2
|
+
import { scopedGroupHistoryProtection } from "../../data/principals/principalHistoryScopeProtection.js";
|
|
3
|
+
import { principalPolicyReferenceFromBundle } from "../../data/principals/principalPolicyAdminSigners.js";
|
|
4
|
+
import { resolveCurrentGroupMutationReferences } from "./currentGroupMutationReferences.js";
|
|
5
|
+
import { loadCurrentGroupPolicyMutationContext } from "./currentGroupPolicyMutationContext.js";
|
|
6
|
+
import { createCurrentPrincipalMutationLease } from "./currentPrincipalMutationLease.js";
|
|
7
|
+
import { retainAcknowledgedPrincipalCurrents, } from "./retainAcknowledgedPrincipalCurrents.js";
|
|
8
|
+
/** Keep private prefix custody inside the entire mutation and its acknowledgement. */
|
|
9
|
+
export function createRuntimeCurrentGroupMutation(runtime) {
|
|
10
|
+
const lease = createCurrentPrincipalMutationLease(runtime);
|
|
11
|
+
if (!lease)
|
|
12
|
+
return undefined;
|
|
13
|
+
return async (input, work) => {
|
|
14
|
+
input = { ...input };
|
|
15
|
+
return lease(input.stillCurrent, async ({ protection, stillCurrent, resolveCurrentPolicy, readPages, directoryRecovery, }) => {
|
|
16
|
+
const context = await loadCurrentGroupPolicyMutationContext({
|
|
17
|
+
...input,
|
|
18
|
+
execSql: runtime.infra.execSql,
|
|
19
|
+
resolveCurrentPolicy,
|
|
20
|
+
recoverPendingPrincipalMutation: (organizationId) => runtime.apiClient.recoverPendingPrincipalMutation(organizationId),
|
|
21
|
+
stillCurrent,
|
|
22
|
+
});
|
|
23
|
+
const result = await work({
|
|
24
|
+
...context,
|
|
25
|
+
resolveAuthoredPolicyReferences: (current, references) => resolveCurrentGroupMutationReferences({
|
|
26
|
+
current,
|
|
27
|
+
predecessor: context.verifiedCurrentPolicy,
|
|
28
|
+
references,
|
|
29
|
+
readPredecessorReference: context.readPredecessorReference,
|
|
30
|
+
stillCurrent: context.stillCurrent,
|
|
31
|
+
}),
|
|
32
|
+
retainAcknowledged: createCurrentMutationRetention(runtime, input, context, protection, readPages, directoryRecovery(context.organizationCurrent.current)),
|
|
33
|
+
});
|
|
34
|
+
assertProjectionVerificationCurrent(context.stillCurrent);
|
|
35
|
+
return result;
|
|
36
|
+
});
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
function createCurrentMutationRetention(runtime, input, context, protection, readPages, directoryRecovery) {
|
|
40
|
+
const common = {
|
|
41
|
+
apiClient: { getPrincipalPolicyPages: readPages },
|
|
42
|
+
resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,
|
|
43
|
+
};
|
|
44
|
+
const groupRecovery = {
|
|
45
|
+
...common,
|
|
46
|
+
expectedHead: principalPolicyReferenceFromBundle(context.currentPolicy),
|
|
47
|
+
protection: context.isOrganizationAdminsGroup
|
|
48
|
+
? protection
|
|
49
|
+
: scopedGroupHistoryProtection(protection, input.organizationId, context.adminGroupId),
|
|
50
|
+
historyVerification: context.isOrganizationAdminsGroup
|
|
51
|
+
? "direct-admins"
|
|
52
|
+
: "standard",
|
|
53
|
+
...(context.isOrganizationAdminsGroup
|
|
54
|
+
? {}
|
|
55
|
+
: { loadExternalAuthority: async () => context.externalAuthority }),
|
|
56
|
+
};
|
|
57
|
+
return async (receipt) => {
|
|
58
|
+
assertProjectionVerificationCurrent(context.stillCurrent);
|
|
59
|
+
await retainAcknowledgedPrincipalCurrents({
|
|
60
|
+
execSql: runtime.infra.execSql,
|
|
61
|
+
organizationId: input.organizationId,
|
|
62
|
+
entries: [
|
|
63
|
+
{
|
|
64
|
+
recovery: groupRecovery,
|
|
65
|
+
request: receipt.request,
|
|
66
|
+
response: receipt.response.groupPolicy,
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
recovery: directoryRecovery,
|
|
70
|
+
request: receipt.organizationRequest,
|
|
71
|
+
response: receipt.response.organizationPolicy,
|
|
72
|
+
},
|
|
73
|
+
],
|
|
74
|
+
retirements: [
|
|
75
|
+
{
|
|
76
|
+
principalId: input.groupId,
|
|
77
|
+
principalType: "group",
|
|
78
|
+
containerIds: receipt.retiredContainerIds ?? [],
|
|
79
|
+
},
|
|
80
|
+
],
|
|
81
|
+
stillCurrent: context.stillCurrent,
|
|
82
|
+
});
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
//# sourceMappingURL=runtimeCurrentGroupMutation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtimeCurrentGroupMutation.js","sourceRoot":"","sources":["runtimeCurrentGroupMutation.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AAEpG,OAAO,EAAE,4BAA4B,EAAE,MAAM,uDAAuD,CAAC;AACrG,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AAEvG,OAAO,EAAE,qCAAqC,EAAE,MAAM,kCAAkC,CAAC;AACzF,OAAO,EAAE,qCAAqC,EAAE,MAAM,qCAAqC,CAAC;AAC5F,OAAO,EAAE,mCAAmC,EAAE,MAAM,iCAAiC,CAAC;AAEtF,OAAO,EAEL,mCAAmC,GACpC,MAAM,uCAA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C,QAAQ,CAAC,kBAAkB;iBAC9C;aACF;YACD,WAAW,EAAE;gBACX;oBACE,WAAW,EAAE,KAAK,CAAC,OAAO;oBAC1B,aAAa,EAAE,OAAO;oBACtB,YAAY,EAAE,OAAO,CAAC,mBAAmB,IAAI,EAAE;iBAChD;aACF;YACD,YAAY,EAAE,OAAO,CAAC,YAAY;SACnC,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { PrincipalPolicyHistoryProgressOptions } from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { CommitOrganizationGroupPolicyResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport type { CurrentPolicyReferenceResolver } from \"../../data/principals/currentPolicyReferenceResolver\";\nimport { scopedGroupHistoryProtection } from \"../../data/principals/principalHistoryScopeProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../data/principals/principalPolicyAdminSigners\";\nimport type { PrincipalPolicyRecoveryRuntime } from \"../principals/runtimePolicyRecovery\";\nimport { resolveCurrentGroupMutationReferences } from \"./currentGroupMutationReferences\";\nimport { loadCurrentGroupPolicyMutationContext } from \"./currentGroupPolicyMutationContext\";\nimport { createCurrentPrincipalMutationLease } from \"./currentPrincipalMutationLease\";\nimport type { PrincipalMutationRecoveryApi } from \"./principalMutationJournalManagement\";\nimport {\n type AcknowledgedPrincipalCurrentInput,\n retainAcknowledgedPrincipalCurrents,\n} from \"./retainAcknowledgedPrincipalCurrents\";\n\ntype MutationRuntime = PrincipalPolicyRecoveryRuntime & {\n readonly apiClient: PrincipalPolicyRecoveryRuntime[\"apiClient\"] &\n Pick<PrincipalMutationRecoveryApi, \"recoverPendingPrincipalMutation\">;\n};\n\ntype CurrentMutationContext = Awaited<\n ReturnType<typeof loadCurrentGroupPolicyMutationContext>\n>;\n\nexport type RuntimeCurrentGroupMutationContext = CurrentMutationContext & {\n readonly resolveAuthoredPolicyReferences: CurrentPolicyReferenceResolver;\n readonly retainAcknowledged: (\n receipt: CurrentMutationReceipt,\n ) => Promise<void>;\n};\n\ninterface CurrentMutationReceipt {\n readonly request: PutPrincipalPolicyRequest;\n readonly organizationRequest: PutPrincipalPolicyRequest;\n readonly response: CommitOrganizationGroupPolicyResponse;\n readonly retiredContainerIds?: readonly string[] | undefined;\n}\n\ninterface MutationInput {\n readonly groupId: string;\n readonly organizationId: string;\n readonly signerUserId: string;\n readonly stillCurrent: () => boolean;\n}\n\n/** Keep private prefix custody inside the entire mutation and its acknowledgement. */\nexport function createRuntimeCurrentGroupMutation(runtime: MutationRuntime) {\n const lease = createCurrentPrincipalMutationLease(runtime);\n if (!lease) return undefined;\n return async <T>(\n input: MutationInput,\n work: (context: RuntimeCurrentGroupMutationContext) => Promise<T>,\n ): Promise<T> => {\n input = { ...input };\n return lease(\n input.stillCurrent,\n async ({\n protection,\n stillCurrent,\n resolveCurrentPolicy,\n readPages,\n directoryRecovery,\n }) => {\n const context = await loadCurrentGroupPolicyMutationContext({\n ...input,\n execSql: runtime.infra.execSql,\n resolveCurrentPolicy,\n recoverPendingPrincipalMutation: (organizationId) =>\n runtime.apiClient.recoverPendingPrincipalMutation(organizationId),\n stillCurrent,\n });\n const result = await work({\n ...context,\n resolveAuthoredPolicyReferences: (current, references) =>\n resolveCurrentGroupMutationReferences({\n current,\n predecessor: context.verifiedCurrentPolicy,\n references,\n readPredecessorReference: context.readPredecessorReference,\n stillCurrent: context.stillCurrent,\n }),\n retainAcknowledged: createCurrentMutationRetention(\n runtime,\n input,\n context,\n protection,\n readPages,\n directoryRecovery(context.organizationCurrent.current),\n ),\n });\n assertProjectionVerificationCurrent(context.stillCurrent);\n return result;\n },\n );\n };\n}\n\nfunction createCurrentMutationRetention(\n runtime: MutationRuntime,\n input: MutationInput,\n context: CurrentMutationContext,\n protection: PrincipalPolicyHistoryProgressOptions,\n readPages: ApiClient[\"getPrincipalPolicyPages\"],\n directoryRecovery: AcknowledgedPrincipalCurrentInput[\"recovery\"],\n) {\n const common = {\n apiClient: { getPrincipalPolicyPages: readPages },\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n };\n const groupRecovery: AcknowledgedPrincipalCurrentInput[\"recovery\"] = {\n ...common,\n expectedHead: principalPolicyReferenceFromBundle(context.currentPolicy),\n protection: context.isOrganizationAdminsGroup\n ? protection\n : scopedGroupHistoryProtection(\n protection,\n input.organizationId,\n context.adminGroupId,\n ),\n historyVerification: context.isOrganizationAdminsGroup\n ? \"direct-admins\"\n : \"standard\",\n ...(context.isOrganizationAdminsGroup\n ? {}\n : { loadExternalAuthority: async () => context.externalAuthority }),\n };\n return async (receipt: CurrentMutationReceipt): Promise<void> => {\n assertProjectionVerificationCurrent(context.stillCurrent);\n await retainAcknowledgedPrincipalCurrents({\n execSql: runtime.infra.execSql,\n organizationId: input.organizationId,\n entries: [\n {\n recovery: groupRecovery,\n request: receipt.request,\n response: receipt.response.groupPolicy,\n },\n {\n recovery: directoryRecovery,\n request: receipt.organizationRequest,\n response: receipt.response.organizationPolicy,\n },\n ],\n retirements: [\n {\n principalId: input.groupId,\n principalType: \"group\",\n containerIds: receipt.retiredContainerIds ?? [],\n },\n ],\n stillCurrent: context.stillCurrent,\n });\n };\n}\n"]}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { assertProjectionVerificationCurrent } from "../../data/keyingProjectionVerification/types.js";
|
|
2
|
+
import { advanceKeyingCheckpointsAtomically } from "../../data/persistence/keyingCheckpointAdvancePersistence.js";
|
|
3
|
+
import { loadCurrentOrganizationMutationAuthority } from "./currentOrganizationMutationAuthority.js";
|
|
4
|
+
import { createCurrentOrganizationMutationRetention } from "./currentOrganizationMutationRetention.js";
|
|
5
|
+
import { createCurrentPrincipalMutationLease } from "./currentPrincipalMutationLease.js";
|
|
6
|
+
/** Keep directory authoring and exact acknowledgement inside one private lease. */
|
|
7
|
+
export function createRuntimeCurrentOrganizationMutation(runtime) {
|
|
8
|
+
const lease = createCurrentPrincipalMutationLease(runtime);
|
|
9
|
+
if (!lease)
|
|
10
|
+
return undefined;
|
|
11
|
+
return async (input, work) => {
|
|
12
|
+
const owned = { ...input };
|
|
13
|
+
return lease(owned.stillCurrent, async ({ protection, readPages, stillCurrent, resolveCurrentPolicy, directoryRecovery, }) => {
|
|
14
|
+
const { authority } = await loadCurrentOrganizationMutationAuthority({
|
|
15
|
+
execSql: runtime.infra.execSql,
|
|
16
|
+
organizationId: owned.organizationId,
|
|
17
|
+
signerUserId: owned.signerUserId,
|
|
18
|
+
recoverPendingPrincipalMutation: (organizationId) => runtime.apiClient.recoverPendingPrincipalMutation(organizationId),
|
|
19
|
+
resolveCurrentPolicy,
|
|
20
|
+
stillCurrent,
|
|
21
|
+
});
|
|
22
|
+
const current = () => stillCurrent() && authority.stillCurrent();
|
|
23
|
+
await advanceKeyingCheckpointsAtomically({
|
|
24
|
+
access: [],
|
|
25
|
+
execSql: runtime.infra.execSql,
|
|
26
|
+
organizationId: owned.organizationId,
|
|
27
|
+
policies: [authority.directory.policy, authority.admins.policy],
|
|
28
|
+
stillCurrent: current,
|
|
29
|
+
});
|
|
30
|
+
const result = await work({
|
|
31
|
+
...authority,
|
|
32
|
+
stillCurrent: current,
|
|
33
|
+
...createCurrentOrganizationMutationRetention({
|
|
34
|
+
runtime,
|
|
35
|
+
authority,
|
|
36
|
+
protection,
|
|
37
|
+
readPages,
|
|
38
|
+
organizationId: owned.organizationId,
|
|
39
|
+
directoryRecovery: directoryRecovery(authority.directory.current),
|
|
40
|
+
stillCurrent: current,
|
|
41
|
+
}),
|
|
42
|
+
});
|
|
43
|
+
assertProjectionVerificationCurrent(current);
|
|
44
|
+
return result;
|
|
45
|
+
});
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
//# sourceMappingURL=runtimeCurrentOrganizationMutation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtimeCurrentOrgan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,CAAC,KAAK,CAAC,OAAO;gBAC9B,cAAc,EAAE,KAAK,CAAC,cAAc;gBACpC,QAAQ,EAAE,CAAC,SAAS,CAAC,SAAS,CAAC,MAAM,EAAE,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC;gBAC/D,YAAY,EAAE,OAAO;aACtB,CAAC,CAAC;YACH,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC;gBACxB,GAAG,SAAS;gBACZ,YAAY,EAAE,OAAO;gBACrB,GAAG,0CAA0C,CAAC;oBAC5C,OAAO;oBACP,SAAS;oBACT,UAAU;oBACV,SAAS;oBACT,cAAc,EAAE,KAAK,CAAC,cAAc;oBACpC,iBAAiB,EAAE,iBAAiB,CAAC,SAAS,CAAC,SAAS,CAAC,OAAO,CAAC;oBACjE,YAAY,EAAE,OAAO;iBACtB,CAAC;aACH,CAAC,CAAC;YACH,mCAAmC,CAAC,OAAO,CAAC,CAAC;YAC7C,OAAO,MAAM,CAAC;QAChB,CAAC,CACF,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { advanceKeyingCheckpointsAtomically } from \"../../data/persistence/keyingCheckpointAdvancePersistence\";\nimport type { PrincipalPolicyRecoveryRuntime } from \"../principals/runtimePolicyRecovery\";\nimport type { loadCurrentOrganizationAuthority } from \"./currentOrganizationAuthority\";\nimport { loadCurrentOrganizationMutationAuthority } from \"./currentOrganizationMutationAuthority\";\nimport { createCurrentOrganizationMutationRetention } from \"./currentOrganizationMutationRetention\";\nimport { createCurrentPrincipalMutationLease } from \"./currentPrincipalMutationLease\";\nimport type { PrincipalMutationRecoveryApi } from \"./principalMutationJournalManagement\";\n\ntype Runtime = PrincipalPolicyRecoveryRuntime & {\n readonly apiClient: PrincipalPolicyRecoveryRuntime[\"apiClient\"] &\n Pick<PrincipalMutationRecoveryApi, \"recoverPendingPrincipalMutation\">;\n};\n\ninterface Input {\n readonly organizationId: string;\n readonly signerUserId: string;\n readonly stillCurrent: () => boolean;\n}\n\ntype Authority = Awaited<ReturnType<typeof loadCurrentOrganizationAuthority>>;\n\nexport type CurrentOrganizationMutationContext = Authority &\n ReturnType<typeof createCurrentOrganizationMutationRetention>;\n\n/** Keep directory authoring and exact acknowledgement inside one private lease. */\nexport function createRuntimeCurrentOrganizationMutation(runtime: Runtime) {\n const lease = createCurrentPrincipalMutationLease(runtime);\n if (!lease) return undefined;\n return async <T>(\n input: Input,\n work: (context: CurrentOrganizationMutationContext) => Promise<T>,\n ): Promise<T> => {\n const owned = { ...input };\n return lease(\n owned.stillCurrent,\n async ({\n protection,\n readPages,\n stillCurrent,\n resolveCurrentPolicy,\n directoryRecovery,\n }) => {\n const { authority } = await loadCurrentOrganizationMutationAuthority({\n execSql: runtime.infra.execSql,\n organizationId: owned.organizationId,\n signerUserId: owned.signerUserId,\n recoverPendingPrincipalMutation: (organizationId) =>\n runtime.apiClient.recoverPendingPrincipalMutation(organizationId),\n resolveCurrentPolicy,\n stillCurrent,\n });\n const current = () => stillCurrent() && authority.stillCurrent();\n await advanceKeyingCheckpointsAtomically({\n access: [],\n execSql: runtime.infra.execSql,\n organizationId: owned.organizationId,\n policies: [authority.directory.policy, authority.admins.policy],\n stillCurrent: current,\n });\n const result = await work({\n ...authority,\n stillCurrent: current,\n ...createCurrentOrganizationMutationRetention({\n runtime,\n authority,\n protection,\n readPages,\n organizationId: owned.organizationId,\n directoryRecovery: directoryRecovery(authority.directory.current),\n stillCurrent: current,\n }),\n });\n assertProjectionVerificationCurrent(current);\n return result;\n },\n );\n };\n}\n"]}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type PrincipalPolicyStateChainEntryResponse } from "../../internal/validators/response/index.js";
|
|
2
|
+
import { type RecoverPrincipalPolicyHistoryOptions } from "./principalHistoryRecoveryTypes.js";
|
|
3
|
+
export declare const PRINCIPAL_DISPLAY_HISTORY_PAGE_SIZE = 32;
|
|
4
|
+
export interface RecoveredPrincipalHistoryPage {
|
|
5
|
+
/** Ascending entries, with the immediate predecessor kept separately for diffs. */
|
|
6
|
+
readonly entries: readonly PrincipalPolicyStateChainEntryResponse[];
|
|
7
|
+
readonly predecessor: PrincipalPolicyStateChainEntryResponse | null;
|
|
8
|
+
readonly nextBeforeVersion: number | null;
|
|
9
|
+
}
|
|
10
|
+
/** Read a bounded historical window from an already recovered, exact private root. */
|
|
11
|
+
export declare function loadRecoveredPrincipalHistoryPage(options: RecoverPrincipalPolicyHistoryOptions, beforeVersion?: number): Promise<RecoveredPrincipalHistoryPage>;
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { KeyingVerificationError, verifyPrincipalPolicyHistoryReferences, } from "../../internal/crypto/index.js";
|
|
2
|
+
import { isPrincipalPolicyStateChainEntryResponse, } from "../../internal/validators/response/index.js";
|
|
3
|
+
import { assertProjectionVerificationCurrent } from "../../data/keyingProjectionVerification/types.js";
|
|
4
|
+
import { loadPrincipalPolicyCheckpoint } from "../../data/persistence/keyingCheckpointPersistence.js";
|
|
5
|
+
import { loadPrincipalHistoryReference } from "../../data/persistence/principalHistoryEvidencePersistence.js";
|
|
6
|
+
import { principalHistoryEvidenceScopeId } from "../../data/principals/principalHistoryPrefixProtection.js";
|
|
7
|
+
import { ownPrincipalHistoryProtection } from "../../data/principals/principalHistoryProtection.js";
|
|
8
|
+
import { loadVerifiedPrincipalHistoryPrefix } from "./principalHistoryRecoveryPrefix.js";
|
|
9
|
+
import { PrincipalHistoryEvidenceUnavailableError } from "./principalHistoryRecoveryReferences.js";
|
|
10
|
+
import { PrincipalHistoryRecoveryRaceError, } from "./principalHistoryRecoveryTypes.js";
|
|
11
|
+
import { principalHistoryVerificationContext } from "./principalHistoryRecoveryVerification.js";
|
|
12
|
+
export const PRINCIPAL_DISPLAY_HISTORY_PAGE_SIZE = 32;
|
|
13
|
+
/** Read a bounded historical window from an already recovered, exact private root. */
|
|
14
|
+
export async function loadRecoveredPrincipalHistoryPage(options, beforeVersion = options.expectedHead.version + 1) {
|
|
15
|
+
const owned = {
|
|
16
|
+
...options,
|
|
17
|
+
expectedHead: structuredClone(options.expectedHead),
|
|
18
|
+
protection: ownPrincipalHistoryProtection(options.protection),
|
|
19
|
+
};
|
|
20
|
+
try {
|
|
21
|
+
return await readPage(owned, beforeVersion);
|
|
22
|
+
}
|
|
23
|
+
finally {
|
|
24
|
+
owned.protection.localKey.fill(0);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
async function readPage(options, beforeVersion) {
|
|
28
|
+
if (!Number.isSafeInteger(beforeVersion) ||
|
|
29
|
+
beforeVersion <= 1 ||
|
|
30
|
+
beforeVersion > options.expectedHead.version + 1)
|
|
31
|
+
throw new KeyingVerificationError("invalid_shape", "Principal history page cursor is outside the selected history");
|
|
32
|
+
const current = () => !options.signal?.aborted && options.stillCurrent();
|
|
33
|
+
assertProjectionVerificationCurrent(current);
|
|
34
|
+
const { scopeId, history } = await restoreReadRoot(options, current);
|
|
35
|
+
const checkpoint = await loadPrincipalPolicyCheckpoint(options.execSql, options.expectedHead.principalType, options.expectedHead.principalId);
|
|
36
|
+
if (checkpoint && checkpoint.version > options.expectedHead.version)
|
|
37
|
+
throw new PrincipalHistoryRecoveryRaceError("Principal checkpoint advanced beyond the selected display history");
|
|
38
|
+
const load = (version) => loadPageReference({
|
|
39
|
+
execSql: options.execSql,
|
|
40
|
+
scopeId,
|
|
41
|
+
history,
|
|
42
|
+
version,
|
|
43
|
+
});
|
|
44
|
+
const firstVersion = Math.max(1, beforeVersion - PRINCIPAL_DISPLAY_HISTORY_PAGE_SIZE);
|
|
45
|
+
const references = [];
|
|
46
|
+
for (let version = Math.max(1, firstVersion - 1); version < beforeVersion; version += 1) {
|
|
47
|
+
assertProjectionVerificationCurrent(current);
|
|
48
|
+
references.push(await load(version));
|
|
49
|
+
}
|
|
50
|
+
const checkpointReference = checkpoint
|
|
51
|
+
? await load(checkpoint.version)
|
|
52
|
+
: undefined;
|
|
53
|
+
if (checkpointReference &&
|
|
54
|
+
checkpointReference.reference.stateHash !== checkpoint?.stateHash)
|
|
55
|
+
throw new KeyingVerificationError("equivocation", "Principal history page conflicts with its durable checkpoint");
|
|
56
|
+
const selected = await verifyPrincipalPolicyHistoryReferences({
|
|
57
|
+
history,
|
|
58
|
+
references,
|
|
59
|
+
checkpointReference,
|
|
60
|
+
});
|
|
61
|
+
if (!selected.ok)
|
|
62
|
+
throw new PrincipalHistoryEvidenceUnavailableError(selected.error);
|
|
63
|
+
await assertDisplayCheckpointCurrent(options, checkpoint);
|
|
64
|
+
assertProjectionVerificationCurrent(current);
|
|
65
|
+
// These exact rows passed inclusion and commitment verification above. Keep
|
|
66
|
+
// their display-only server timestamps, which the private current strips.
|
|
67
|
+
const retained = references.map(({ entry }) => responseEntry(entry));
|
|
68
|
+
return {
|
|
69
|
+
entries: retained.filter(({ state }) => state.version >= firstVersion && state.version < beforeVersion),
|
|
70
|
+
predecessor: retained.find(({ state }) => state.version === firstVersion - 1) ?? null,
|
|
71
|
+
nextBeforeVersion: firstVersion > 1 ? firstVersion : null,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
async function assertDisplayCheckpointCurrent(options, checkpoint) {
|
|
75
|
+
const latest = await loadPrincipalPolicyCheckpoint(options.execSql, options.expectedHead.principalType, options.expectedHead.principalId);
|
|
76
|
+
if (latest?.version !== checkpoint?.version ||
|
|
77
|
+
latest?.stateHash !== checkpoint?.stateHash)
|
|
78
|
+
throw new PrincipalHistoryRecoveryRaceError("Principal checkpoint changed while reading display history");
|
|
79
|
+
}
|
|
80
|
+
async function loadPageReference(input) {
|
|
81
|
+
try {
|
|
82
|
+
return await loadPrincipalHistoryReference(input);
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
if (error instanceof KeyingVerificationError)
|
|
86
|
+
throw new PrincipalHistoryEvidenceUnavailableError(error);
|
|
87
|
+
throw error;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
function responseEntry(entry) {
|
|
91
|
+
if (!isPrincipalPolicyStateChainEntryResponse(entry))
|
|
92
|
+
throw new KeyingVerificationError("missing_dependency", "Principal history display metadata is unavailable");
|
|
93
|
+
return entry;
|
|
94
|
+
}
|
|
95
|
+
async function restoreReadRoot(options, current) {
|
|
96
|
+
const normalized = {
|
|
97
|
+
...options,
|
|
98
|
+
protection: {
|
|
99
|
+
...options.protection,
|
|
100
|
+
context: principalHistoryVerificationContext(options),
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
const scopeId = await principalHistoryEvidenceScopeId({
|
|
104
|
+
organizationId: options.organizationId,
|
|
105
|
+
head: options.expectedHead,
|
|
106
|
+
protection: normalized.protection,
|
|
107
|
+
});
|
|
108
|
+
const prefix = await loadVerifiedPrincipalHistoryPrefix(normalized, {
|
|
109
|
+
principalType: options.expectedHead.principalType,
|
|
110
|
+
principalId: options.expectedHead.principalId,
|
|
111
|
+
}, scopeId);
|
|
112
|
+
assertProjectionVerificationCurrent(current);
|
|
113
|
+
if (!prefix)
|
|
114
|
+
throw new KeyingVerificationError("missing_dependency", "Principal history page requires a recovered private prefix");
|
|
115
|
+
const finished = prefix.verifier.finish(options.expectedHead);
|
|
116
|
+
if (!finished.ok)
|
|
117
|
+
throw finished.error;
|
|
118
|
+
return { scopeId, history: finished.value };
|
|
119
|
+
}
|
|
120
|
+
//# sourceMappingURL=loadRecoveredPrincipalHistoryPage.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"loadRecoveredPrincipalHistoryPage.js","sourceRoot":"","sources":["loadRecoveredPrincipalHistoryPage.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAGvB,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,wCAAwC,GAEzC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,6BAA6B,EAAE,MAAM,oDAAoD,CAAC;AACnG,OA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AM,CAAC,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;IAC9D,IAAI,CAAC,QAAQ,CAAC,EAAE;QAAE,MAAM,QAAQ,CAAC,KAAK,CAAC;IACvC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,KAAK,EAAE,CAAC;AAC9C,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyHistoryReferenceProof,\n type PrincipalPolicyStateChainEntry,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport {\n isPrincipalPolicyStateChainEntryResponse,\n type PrincipalPolicyStateChainEntryResponse,\n} from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../data/persistence/keyingCheckpointPersistence\";\nimport { loadPrincipalHistoryReference } from \"../../data/persistence/principalHistoryEvidencePersistence\";\nimport { principalHistoryEvidenceScopeId } from \"../../data/principals/principalHistoryPrefixProtection\";\nimport { ownPrincipalHistoryProtection } from \"../../data/principals/principalHistoryProtection\";\nimport { loadVerifiedPrincipalHistoryPrefix } from \"./principalHistoryRecoveryPrefix\";\nimport { PrincipalHistoryEvidenceUnavailableError } from \"./principalHistoryRecoveryReferences\";\nimport {\n PrincipalHistoryRecoveryRaceError,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"./principalHistoryRecoveryTypes\";\nimport { principalHistoryVerificationContext } from \"./principalHistoryRecoveryVerification\";\n\nexport const PRINCIPAL_DISPLAY_HISTORY_PAGE_SIZE = 32;\n\nexport interface RecoveredPrincipalHistoryPage {\n /** Ascending entries, with the immediate predecessor kept separately for diffs. */\n readonly entries: readonly PrincipalPolicyStateChainEntryResponse[];\n readonly predecessor: PrincipalPolicyStateChainEntryResponse | null;\n readonly nextBeforeVersion: number | null;\n}\n\n/** Read a bounded historical window from an already recovered, exact private root. */\nexport async function loadRecoveredPrincipalHistoryPage(\n options: RecoverPrincipalPolicyHistoryOptions,\n beforeVersion = options.expectedHead.version + 1,\n): Promise<RecoveredPrincipalHistoryPage> {\n const owned = {\n ...options,\n expectedHead: structuredClone(options.expectedHead),\n protection: ownPrincipalHistoryProtection(options.protection),\n };\n try {\n return await readPage(owned, beforeVersion);\n } finally {\n owned.protection.localKey.fill(0);\n }\n}\n\nasync function readPage(\n options: RecoverPrincipalPolicyHistoryOptions,\n beforeVersion: number,\n): Promise<RecoveredPrincipalHistoryPage> {\n if (\n !Number.isSafeInteger(beforeVersion) ||\n beforeVersion <= 1 ||\n beforeVersion > options.expectedHead.version + 1\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Principal history page cursor is outside the selected history\",\n );\n const current = () => !options.signal?.aborted && options.stillCurrent();\n assertProjectionVerificationCurrent(current);\n const { scopeId, history } = await restoreReadRoot(options, current);\n const checkpoint = await loadPrincipalPolicyCheckpoint(\n options.execSql,\n options.expectedHead.principalType,\n options.expectedHead.principalId,\n );\n if (checkpoint && checkpoint.version > options.expectedHead.version)\n throw new PrincipalHistoryRecoveryRaceError(\n \"Principal checkpoint advanced beyond the selected display history\",\n );\n const load = (version: number) =>\n loadPageReference({\n execSql: options.execSql,\n scopeId,\n history,\n version,\n });\n const firstVersion = Math.max(\n 1,\n beforeVersion - PRINCIPAL_DISPLAY_HISTORY_PAGE_SIZE,\n );\n const references: PrincipalPolicyHistoryReferenceProof[] = [];\n for (\n let version = Math.max(1, firstVersion - 1);\n version < beforeVersion;\n version += 1\n ) {\n assertProjectionVerificationCurrent(current);\n references.push(await load(version));\n }\n const checkpointReference = checkpoint\n ? await load(checkpoint.version)\n : undefined;\n if (\n checkpointReference &&\n checkpointReference.reference.stateHash !== checkpoint?.stateHash\n )\n throw new KeyingVerificationError(\n \"equivocation\",\n \"Principal history page conflicts with its durable checkpoint\",\n );\n const selected = await verifyPrincipalPolicyHistoryReferences({\n history,\n references,\n checkpointReference,\n });\n if (!selected.ok)\n throw new PrincipalHistoryEvidenceUnavailableError(selected.error);\n await assertDisplayCheckpointCurrent(options, checkpoint);\n assertProjectionVerificationCurrent(current);\n // These exact rows passed inclusion and commitment verification above. Keep\n // their display-only server timestamps, which the private current strips.\n const retained = references.map(({ entry }) => responseEntry(entry));\n return {\n entries: retained.filter(\n ({ state }) =>\n state.version >= firstVersion && state.version < beforeVersion,\n ),\n predecessor:\n retained.find(({ state }) => state.version === firstVersion - 1) ?? null,\n nextBeforeVersion: firstVersion > 1 ? firstVersion : null,\n };\n}\n\nasync function assertDisplayCheckpointCurrent(\n options: RecoverPrincipalPolicyHistoryOptions,\n checkpoint: Awaited<ReturnType<typeof loadPrincipalPolicyCheckpoint>>,\n) {\n const latest = await loadPrincipalPolicyCheckpoint(\n options.execSql,\n options.expectedHead.principalType,\n options.expectedHead.principalId,\n );\n if (\n latest?.version !== checkpoint?.version ||\n latest?.stateHash !== checkpoint?.stateHash\n )\n throw new PrincipalHistoryRecoveryRaceError(\n \"Principal checkpoint changed while reading display history\",\n );\n}\n\nasync function loadPageReference(\n input: Parameters<typeof loadPrincipalHistoryReference>[0],\n) {\n try {\n return await loadPrincipalHistoryReference(input);\n } catch (error) {\n if (error instanceof KeyingVerificationError)\n throw new PrincipalHistoryEvidenceUnavailableError(error);\n throw error;\n }\n}\n\nfunction responseEntry(\n entry: PrincipalPolicyStateChainEntry,\n): PrincipalPolicyStateChainEntryResponse {\n if (!isPrincipalPolicyStateChainEntryResponse(entry))\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Principal history display metadata is unavailable\",\n );\n return entry;\n}\n\nasync function restoreReadRoot(\n options: RecoverPrincipalPolicyHistoryOptions,\n current: () => boolean,\n) {\n const normalized = {\n ...options,\n protection: {\n ...options.protection,\n context: principalHistoryVerificationContext(options),\n },\n };\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: options.organizationId,\n head: options.expectedHead,\n protection: normalized.protection,\n });\n const prefix = await loadVerifiedPrincipalHistoryPrefix(\n normalized,\n {\n principalType: options.expectedHead.principalType,\n principalId: options.expectedHead.principalId,\n },\n scopeId,\n );\n assertProjectionVerificationCurrent(current);\n if (!prefix)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Principal history page requires a recovered private prefix\",\n );\n const finished = prefix.verifier.finish(options.expectedHead);\n if (!finished.ok) throw finished.error;\n return { scopeId, history: finished.value };\n}\n"]}
|
|
@@ -22,6 +22,14 @@ async function selectReferences(input) {
|
|
|
22
22
|
version: reference.version,
|
|
23
23
|
}));
|
|
24
24
|
}
|
|
25
|
+
const versions = new Set((options.retainedReferences ?? []).map((reference) => reference.version));
|
|
26
|
+
for (const version of options.retainedVersions ?? []) {
|
|
27
|
+
if (versions.has(version))
|
|
28
|
+
continue;
|
|
29
|
+
versions.add(version);
|
|
30
|
+
assertProjectionVerificationCurrent(current);
|
|
31
|
+
references.push(await loadPrincipalHistoryReference({ ...base, version }));
|
|
32
|
+
}
|
|
25
33
|
assertProjectionVerificationCurrent(current);
|
|
26
34
|
const checkpointReference = input.checkpoint
|
|
27
35
|
? await loadPrincipalHistoryReference({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalHistoryRecoveryReferences.js","sourceRoot":"","sources":["principalHistoryRecoveryReferences.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAIvB,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,6BAA6B,EAAE,MAAM,4DAA4D,CAAC;AAC3G,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;
|
|
1
|
+
{"version":3,"file":"principalHistoryRecoveryReferences.js","sourceRoot":"","sources":["principalHistoryRecoveryReferences.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAIvB,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG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C3C,6BAA6B,CAAC,KAAK,EAAE,SAAS,CAAC,CAChD;YAED,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,kEAAkE,CACnE,CAAC;IACN,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type PrincipalPolicyHistoryReferenceProof,\n type VerifiedPrincipalPolicyHistory,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { loadPrincipalHistoryReference } from \"../../data/persistence/principalHistoryEvidencePersistence\";\nimport { principalHeadMatchesReference } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"./principalHistoryRecoveryTypes\";\n\nexport interface PrincipalHistorySelectionOptions\n extends RecoverPrincipalPolicyHistoryOptions {\n /** Internal page selection by version; every selected row still needs a private-root proof. */\n readonly retainedVersions?: readonly number[] | undefined;\n}\n\nexport class PrincipalHistoryEvidenceUnavailableError extends Error {\n constructor(readonly verificationError: KeyingVerificationError) {\n super(verificationError.message);\n this.name = \"PrincipalHistoryEvidenceUnavailableError\";\n }\n}\n\nasync function selectReferences(input: {\n readonly options: PrincipalHistorySelectionOptions;\n readonly scopeId: string;\n readonly history: VerifiedPrincipalPolicyHistory;\n readonly checkpoint: PrincipalPolicyCheckpoint | null;\n}): Promise<VerifiedPrincipalPolicyHistory> {\n const { options, scopeId, history } = input;\n const current = () => !options.signal?.aborted && options.stillCurrent();\n const base = { execSql: options.execSql, scopeId, history };\n const references: PrincipalPolicyHistoryReferenceProof[] = [];\n for (const reference of options.retainedReferences ?? []) {\n assertProjectionVerificationCurrent(current);\n references.push(\n await loadPrincipalHistoryReference({\n ...base,\n version: reference.version,\n }),\n );\n }\n const versions = new Set(\n (options.retainedReferences ?? []).map((reference) => reference.version),\n );\n for (const version of options.retainedVersions ?? []) {\n if (versions.has(version)) continue;\n versions.add(version);\n assertProjectionVerificationCurrent(current);\n references.push(await loadPrincipalHistoryReference({ ...base, version }));\n }\n assertProjectionVerificationCurrent(current);\n const checkpointReference = input.checkpoint\n ? await loadPrincipalHistoryReference({\n ...base,\n version: input.checkpoint.version,\n })\n : undefined;\n const selected = await verifyPrincipalPolicyHistoryReferences({\n history,\n references,\n checkpointReference,\n });\n if (!selected.ok) throw selected.error;\n assertProjectionVerificationCurrent(current);\n return selected.value;\n}\n\nexport async function selectRecoveredPrincipalHistory(\n input: Parameters<typeof selectReferences>[0],\n): Promise<VerifiedPrincipalPolicyHistory> {\n let selected: VerifiedPrincipalPolicyHistory;\n try {\n selected = await selectReferences(input);\n } catch (error) {\n if (error instanceof KeyingVerificationError)\n throw new PrincipalHistoryEvidenceUnavailableError(error);\n throw error;\n }\n // First authenticate the stored entry against the private root. Only then\n // compare the caller's citation, so a bad request is not treated as cache loss.\n for (const reference of input.options.retainedReferences ?? []) {\n if (\n !selected.retainedEntries.some(({ state }) =>\n principalHeadMatchesReference(state, reference),\n )\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Requested citation does not match the verified principal history\",\n );\n }\n return selected;\n}\n"]}
|