@tearleads/client-sdk 0.1.15 → 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/Tearleads.d.ts +2 -0
- package/client/Tearleads.js +1 -0
- package/client/Tearleads.js.map +1 -1
- 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 +4 -42
- package/client/organizations/index.js +17 -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 +14 -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 +50 -0
- package/client/organizations/organizationsTypes.js +2 -0
- package/client/organizations/organizationsTypes.js.map +1 -0
- package/client/organizations/principalContainerMutations.js +2 -0
- package/client/organizations/principalContainerMutations.js.map +1 -1
- package/client/organizations/principalMutationRecovery.d.ts +16 -0
- package/client/organizations/principalMutationRecovery.js +23 -0
- package/client/organizations/principalMutationRecovery.js.map +1 -0
- package/client/organizations/principalMutationScope.js +7 -2
- package/client/organizations/principalMutationScope.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/client/principalMutationApi.d.ts +24 -0
- package/client/principalMutationApi.js +108 -0
- package/client/principalMutationApi.js.map +1 -0
- package/client/principalMutationDeadline.js +23 -0
- package/client/principalMutationDeadline.js.map +1 -0
- package/client/workflowRuntime.d.ts +3 -1
- package/client/workflowRuntime.js +44 -5
- package/client/workflowRuntime.js.map +1 -1
- package/data/persistence/principalCurrentAcknowledgementPersistence.d.ts +27 -0
- package/data/persistence/principalCurrentAcknowledgementPersistence.js +116 -0
- package/data/persistence/principalCurrentAcknowledgementPersistence.js.map +1 -0
- package/data/persistence/principalGrantRetirementPersistence.d.ts +3 -3
- package/data/persistence/principalGrantRetirementPersistence.js +4 -1
- package/data/persistence/principalGrantRetirementPersistence.js.map +1 -1
- package/data/persistence/principalKeyEnvelopeCandidates.js +12 -1
- package/data/persistence/principalKeyEnvelopeCandidates.js.map +1 -1
- package/data/persistence/principalMutationJournalPersistence.d.ts +19 -0
- package/data/persistence/principalMutationJournalPersistence.js +53 -0
- package/data/persistence/principalMutationJournalPersistence.js.map +1 -0
- package/data/persistence/verifiedPrincipalPolicyBundle.js +7 -51
- package/data/persistence/verifiedPrincipalPolicyBundle.js.map +1 -1
- package/data/persistence/verifiedPrincipalPolicyCurrent.js +56 -0
- package/data/persistence/verifiedPrincipalPolicyCurrent.js.map +1 -0
- 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/principalMutationJournal.d.ts +26 -0
- package/data/principals/principalMutationJournal.js +90 -0
- package/data/principals/principalMutationJournal.js.map +1 -0
- package/data/principals/principalMutationJournalRecord.d.ts +8 -0
- package/data/principals/principalMutationJournalRecord.js +25 -0
- package/data/principals/principalMutationJournalRecord.js.map +1 -0
- package/data/principals/principalPolicyAdminSigners.js.map +1 -1
- package/data/sqlite/principalHistoryStageSchema.js +3 -0
- package/data/sqlite/principalHistoryStageSchema.js.map +1 -1
- package/data/sqlite/principalMutationJournalSchema.d.ts +85 -0
- package/data/sqlite/principalMutationJournalSchema.js +13 -0
- package/data/sqlite/principalMutationJournalSchema.js.map +1 -0
- package/data/sqlite/schema.d.ts +83 -0
- package/data/sqlite/schema.js +3 -0
- package/data/sqlite/schema.js.map +1 -1
- package/index.d.ts +3 -3
- package/index.js +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 +3 -0
- package/internal/crypto/keying/index.js +3 -0
- package/internal/crypto/keying/index.js.map +1 -1
- package/internal/crypto/keying/principalPolicyCurrent.d.ts +1 -1
- package/internal/crypto/keying/principalPolicyCurrent.js +3 -3
- package/internal/crypto/keying/principalPolicyCurrent.js.map +1 -1
- package/internal/crypto/keying/principalPolicyCurrentEvidence.js +16 -0
- package/internal/crypto/keying/principalPolicyCurrentEvidence.js.map +1 -0
- package/internal/crypto/keying/principalPolicyCurrentMutation.d.ts +10 -0
- package/internal/crypto/keying/principalPolicyCurrentMutation.js +51 -0
- package/internal/crypto/keying/principalPolicyCurrentMutation.js.map +1 -0
- 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/internal/crypto/keying/principalPolicyCurrentSuccessor.d.ts +10 -0
- package/internal/crypto/keying/principalPolicyCurrentSuccessor.js +60 -0
- package/internal/crypto/keying/principalPolicyCurrentSuccessor.js.map +1 -0
- package/internal/crypto/keying/principalPolicyHistory.js +4 -1
- package/internal/crypto/keying/principalPolicyHistory.js.map +1 -1
- package/internal/crypto/keying/principalPolicyHistoryReferences.js +1 -1
- package/internal/crypto/keying/principalPolicyHistoryReferences.js.map +1 -1
- package/internal/crypto/keying/principalPolicyHistoryTypes.d.ts +5 -2
- package/internal/crypto/keying/principalPolicyHistoryTypes.js +6 -3
- package/internal/crypto/keying/principalPolicyHistoryTypes.js.map +1 -1
- 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/containers/child/share.js +4 -0
- package/workflows/containers/child/share.js.map +1 -1
- package/workflows/containers/child/sharePrincipalPolicy.d.ts +1 -0
- package/workflows/containers/child/sharePrincipalPolicy.js.map +1 -1
- package/workflows/organizations/acknowledgedDirectoryBindings.js +18 -0
- package/workflows/organizations/acknowledgedDirectoryBindings.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 +53 -0
- package/workflows/organizations/currentGroupMetadataAuthority.js.map +1 -0
- 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/currentOrganizationAuthority.js +88 -0
- package/workflows/organizations/currentOrganizationAuthority.js.map +1 -0
- package/workflows/organizations/currentOrganizationGroupNames.js +72 -0
- package/workflows/organizations/currentOrganizationGroupNames.js.map +1 -0
- 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/currentPolicyMutationAcknowledgement.js +65 -0
- package/workflows/organizations/currentPolicyMutationAcknowledgement.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 +11 -0
- package/workflows/organizations/deleteOrganizationGroup.js.map +1 -1
- package/workflows/organizations/groupCreation.d.ts +1 -0
- package/workflows/organizations/groupCreation.js +9 -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/groupMetadataAccess.d.ts +2 -2
- package/workflows/organizations/groupMetadataAccess.js +1 -1
- package/workflows/organizations/groupMetadataAccess.js.map +1 -1
- package/workflows/organizations/groupMetadataBinding.js.map +1 -1
- package/workflows/organizations/groupMetadataContainerAuthority.js +2 -47
- package/workflows/organizations/groupMetadataContainerAuthority.js.map +1 -1
- package/workflows/organizations/groupMetadataRootBinding.js +51 -0
- package/workflows/organizations/groupMetadataRootBinding.js.map +1 -0
- package/workflows/organizations/groupMetadataRuntime.js +26 -10
- package/workflows/organizations/groupMetadataRuntime.js.map +1 -1
- package/workflows/organizations/groupMutationAuthorization.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 +10 -75
- package/workflows/organizations/groupPolicyMutationAcknowledgement.js.map +1 -1
- package/workflows/organizations/groupPolicyMutationContext.d.ts +23 -13
- package/workflows/organizations/groupPolicyMutationContext.js +2 -1
- package/workflows/organizations/groupPolicyMutationContext.js.map +1 -1
- package/workflows/organizations/groupPolicyMutationEvidence.d.ts +26 -0
- package/workflows/organizations/groupPolicyMutationEvidence.js +64 -0
- package/workflows/organizations/groupPolicyMutationEvidence.js.map +1 -0
- package/workflows/organizations/groupPolicyMutationHead.js.map +1 -1
- package/workflows/organizations/groupPolicyRequests.js +69 -63
- package/workflows/organizations/groupPolicyRequests.js.map +1 -1
- package/workflows/organizations/index.d.ts +6 -0
- package/workflows/organizations/index.js +5 -0
- package/workflows/organizations/index.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 +7 -0
- 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/principalCurrentPublicationSeal.js +51 -0
- package/workflows/organizations/principalCurrentPublicationSeal.js.map +1 -0
- package/workflows/organizations/principalMutationJournalLane.js +26 -0
- package/workflows/organizations/principalMutationJournalLane.js.map +1 -0
- package/workflows/organizations/principalMutationJournalManagement.d.ts +26 -0
- package/workflows/organizations/principalMutationJournalManagement.js +104 -0
- package/workflows/organizations/principalMutationJournalManagement.js.map +1 -0
- package/workflows/organizations/principalMutationJournalSession.d.ts +26 -0
- package/workflows/organizations/principalMutationJournalSession.js +85 -0
- package/workflows/organizations/principalMutationJournalSession.js.map +1 -0
- package/workflows/organizations/principalMutationReceipt.js +21 -0
- package/workflows/organizations/principalMutationReceipt.js.map +1 -0
- package/workflows/organizations/principalPolicyReceiptArtifacts.js +74 -0
- package/workflows/organizations/principalPolicyReceiptArtifacts.js.map +1 -0
- package/workflows/organizations/principalPolicyRequest.d.ts +5 -4
- package/workflows/organizations/principalPolicyRequest.js.map +1 -1
- package/workflows/organizations/retainAcknowledgedPrincipalCurrents.d.ts +23 -0
- package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js +159 -0
- package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js.map +1 -0
- 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/principalCurrentRecoveryBatch.js +14 -0
- package/workflows/principals/principalCurrentRecoveryBatch.js.map +1 -0
- package/workflows/principals/principalHistoryRecoveryReferences.js +8 -0
- package/workflows/principals/principalHistoryRecoveryReferences.js.map +1 -1
- package/workflows/principals/principalRecoveryDirectory.d.ts +1 -1
- package/workflows/principals/principalRecoveryDirectory.js +32 -12
- package/workflows/principals/principalRecoveryDirectory.js.map +1 -1
- package/workflows/principals/principalRecoveryDiscoveryPage.js +36 -0
- package/workflows/principals/principalRecoveryDiscoveryPage.js.map +1 -0
- package/workflows/principals/principalRecoveryLocalPreference.js +29 -0
- package/workflows/principals/principalRecoveryLocalPreference.js.map +1 -0
- package/workflows/principals/principalRecoveryMemo.d.ts +16 -0
- package/workflows/principals/principalRecoveryMemo.js +88 -16
- package/workflows/principals/principalRecoveryMemo.js.map +1 -1
- package/workflows/principals/recoverCurrentOrganizationPolicy.js +33 -0
- package/workflows/principals/recoverCurrentOrganizationPolicy.js.map +1 -0
- 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 +8 -1
- package/workflows/principals/recoverScopedPrincipalPolicyHistory.js +30 -20
- package/workflows/principals/recoverScopedPrincipalPolicyHistory.js.map +1 -1
- package/workflows/principals/runtimePolicyRecovery.js +36 -9
- 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":"carriedDescendantRekeys.js","sourceRoot":"","sources":["carriedDescendantRekeys.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,6BAA6B,EAAE,MAAM,4BAA4B,CAAC;AAM3E,OAAO,EAIL,+BAA+B,GAChC,MAAM,4CAA4C,CAAC;AAEpD,OAAO,EAAE,mCAAmC,EAAE,MAAM,SAAS,CAAC;AAC9D,OAAO,EAAE,+BAA+B,EAAE,MAAM,mBAAmB,CAAC;AAkCpE;;;;;;GAMG;AACH,MAAM,UAAU,uBAAuB,CACrC,MAAyC,EACzC,gBAA4C;IAK5C,IAAI,OAAO,GAA2B,IAAI,CAAC;IAC3C,IAAI,YAAY,GAAG,CAAC,CAAC,CAAC;IACtB,KAAK,MAAM,WAAW,IAAI,gBAAgB,EAAE,CAAC;QAC3C,MAAM,WAAW,GAAG,WAAW,CAAC,aAAa,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,WAAW,CAAC;QAClE,IAAI,WAAW,KAAK,MAAM,CAAC,WAAW;YAAE,SAAS;QACjD,MAAM,KAAK,GAAG,MAAM,CAAC,aAAa,CAAC,SAAS,CAC1C,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,WAAW,KAAK,WAAW,CACzC,CAAC;QACF,IAAI,KAAK,GAAG,YAAY,EAAE,CAAC;YACzB,OAAO,G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C,GAAG,KAAK;YACR,kBAAkB;YAClB,OAAO,EAAE,gBAAgB;YACzB,MAAM;SACP,CAAC,CAAC;QACH,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;QACzB,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACjB,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;QAC7C,kBAAkB,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,mBAAmB,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;IAC3E,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import type { VerifiedPrincipalPolicy } from \"@tearleads/crypto\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { MAX_ROTATION_CONTAINER_REKEYS } from \"@tearleads/validators/util\";\nimport type {\n ContainerMutationAuthor,\n ContainerRekeyApi,\n MaterializedContainerRekeyPlan,\n} from \"../../../data/containers/shared/types\";\nimport {\n type PrincipalPolicyCache,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n verifyContainerWriterProjection,\n} from \"../../../data/keyingProjectionVerification\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { buildMaterializedContainerRekeyPlan } from \"./rekey\";\nimport { rebaseContainerWriterProjection } from \"./rekeyProjection\";\n\n/** What a rotation needs in hand to sign the descendant rekeys it must carry. */\nexport interface CarriedRekeyPlanningInput {\n readonly apiClient: Pick<ContainerRekeyApi, \"getContainerWriterProjection\">;\n readonly author: ContainerMutationAuthor;\n readonly execSql: ExecSql;\n /**\n * Keys the batch minted and has yet to commit, by epoch id. A rotation's\n * successor is wrapped to recipients at heads the batch itself commits, so\n * no wrap on a re-rooted path opens it for the signer before then; the key\n * the signer just minted does, and its keyring then opens what sits below.\n */\n readonly knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n /**\n * Verified policies the batch itself commits, which the rebased paths cite\n * before any store holds them; and the one each carried rekey cites anew.\n */\n readonly principalPolicyCache?: PrincipalPolicyCache | undefined;\n readonly replacementPrincipalPolicy?: VerifiedPrincipalPolicy | undefined;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly targetSecretKey: Uint8Array;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}\n\n/** A rotated container's own path once its batch is accepted. */\nexport type SpeculativePath = Pick<\n ContainerWriterProjectionResponse,\n \"containerKeks\" | \"organizationId\" | \"path\" | \"policyEvidence\"\n>;\n\n/**\n * Re-root a served projection on the deepest not-yet-accepted proper ancestor\n * among `speculativePaths`. Each carried plan's own path was built the same\n * way, so the deepest one already holds every speculative level above it. The\n * container's own path, when the batch rotates it too, is not an ancestor: the\n * caller is re-planning that rotation, and it extends what sits above.\n */\nexport function rebaseOnDeepestAncestor(\n served: ContainerWriterProjectionResponse,\n speculativePaths: readonly SpeculativePath[],\n): {\n ancestor: SpeculativePath;\n projection: ContainerWriterProjectionResponse;\n} | null {\n let deepest: SpeculativePath | null = null;\n let deepestIndex = -1;\n for (const speculative of speculativePaths) {\n const containerId = speculative.containerKeks.at(-1)?.containerId;\n if (containerId === served.containerId) continue;\n const index = served.containerKeks.findIndex(\n (kek) => kek.containerId === containerId,\n );\n if (index > deepestIndex) {\n deepest = speculative;\n deepestIndex = index;\n }\n }\n if (!deepest) return null;\n const projection = rebaseContainerWriterProjection(served, deepest);\n return projection ? { ancestor: deepest, projection } : null;\n}\n\n/**\n * Sign one carried rekey against the path its batch will leave behind. The\n * served projection is fetched by the caller; here it is verified, must sit\n * below one of the rotated containers and in that container's organization,\n * and is signed only if this signer holds its key and write access — which a\n * member able to rotate the ancestor always does, since both inherit downward.\n */\nexport async function planCarriedDescendantRekey(\n input: CarriedRekeyPlanningInput & {\n readonly rotated: readonly SpeculativePath[];\n readonly served: ContainerWriterProjectionResponse;\n },\n): Promise<MaterializedContainerRekeyPlan> {\n // Pin the served head before signing beyond it. The batch is acknowledged\n // against the latest durable pin, and a carried rekey is always past epoch\n // 1, so a device that never pinned this container would otherwise reject\n // its own batch after the server had committed it.\n await verifyContainerWriterProjection({\n execSql: input.execSql,\n principalPolicyCache: input.principalPolicyCache,\n projection: input.served,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const rebased = rebaseOnDeepestAncestor(input.served, input.rotated);\n if (!rebased) {\n throw new Error(\n \"Carried descendant rekey is not below the rotated container\",\n );\n }\n // A batch locks whatever organizations it names, so the server holds each\n // to the rule on its own; a carried rekey belongs to the rotation it rides.\n if (input.served.organizationId !== rebased.ancestor.organizationId) {\n throw new Error(\n \"Carried descendant rekey is outside the rotated container's organization\",\n );\n }\n return buildMaterializedContainerRekeyPlan({\n author: {\n ...input.author,\n organizationId: rebased.ancestor.organizationId,\n },\n execSql: input.execSql,\n knownContainerKeks: input.knownContainerKeks,\n // Nothing here is acknowledged yet: pins move only with the batch.\n persistVerificationCheckpoints: false,\n previousProjection: rebased.projection,\n principalPolicyCache: input.principalPolicyCache,\n replacementPrincipalPolicy: input.replacementPrincipalPolicy,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n}\n\n/**\n * Sign the descendant rekeys a rotation must commit with (#2340). The server\n * refuses a rotation that would leave a level above a directly granted\n * container pinned to a retired epoch, because the grantee could never re-key\n * that level itself and its writes would wait on another device. It names the\n * levels; this signs them, parent-first, each against the path the batch will\n * leave behind rather than the one currently served.\n *\n * `requiredContainerIds` is a hint, never an authority: each container is\n * fetched and verified here, and refused unless it sits below a rotation.\n */\nexport async function planCarriedDescendantRekeys(\n input: CarriedRekeyPlanningInput & {\n readonly requiredContainerIds: readonly string[];\n /** Each rotated container's own path once the batch is accepted. */\n readonly rotated: readonly SpeculativePath[];\n },\n): Promise<MaterializedContainerRekeyPlan[]> {\n const plans: MaterializedContainerRekeyPlan[] = [];\n const speculativePaths: SpeculativePath[] = [...input.rotated];\n const knownContainerKeks = new Map(input.knownContainerKeks);\n const planned = new Set<string>();\n for (const containerId of input.requiredContainerIds) {\n if (plans.length >= MAX_ROTATION_CONTAINER_REKEYS) break;\n if (planned.has(containerId)) continue;\n const served =\n await input.apiClient.getContainerWriterProjection(containerId);\n if (!served) {\n throw new Error(\"Carried descendant rekey projection is unavailable\");\n }\n if (served.containerId !== containerId) {\n throw new Error(\"Carried descendant rekey targets another container\");\n }\n const plan = await planCarriedDescendantRekey({\n ...input,\n knownContainerKeks,\n rotated: speculativePaths,\n served,\n });\n planned.add(containerId);\n plans.push(plan);\n speculativePaths.push(plan.writerProjection);\n knownContainerKeks.set(plan.plan.containerKeyEpochId, plan.containerKey);\n }\n return plans;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"carriedDescendantRekeys.js","sourceRoot":"","sources":["carriedDescendantRekeys.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,6BAA6B,EAAE,MAAM,4BAA4B,CAAC;AAM3E,OAAO,EAIL,+BAA+B,GAChC,MAAM,4CAA4C,CAAC;AAIpD,OAAO,EAAE,mCAAmC,EAAE,MAAM,SAAS,CAAC;AAC9D,OAAO,EAAE,+BAA+B,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,EAAE,0CAA0C,EAAE,MAAM,wCAAwC,CAAC;AAuCpG;;;;;;GAMG;AACH,MAAM,UAAU,uBAAuB,CACrC,MAAyC,EACzC,gBAA4C;IAK5C,IAAI,OAAO,GAA2B,IAAI,CAAC;IAC3C,IAAI,YAAY,GAAG,CAAC,CAAC,CAAC;IACtB,KAAK,MAAM,WAAW,IAAI,gBAAgB,EAAE,CAAC;QAC3C,MAAM,WAAW,GAAG,WAAW,CAAC,aAAa,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,E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KAAK,CAAC,oBAAoB,EAAE,CAAC;QACrD,IAAI,KAAK,CAAC,MAAM,IAAI,6BAA6B;YAAE,MAAM;QACzD,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC;YAAE,SAAS;QACvC,MAAM,MAAM,GACV,MAAM,KAAK,CAAC,SAAS,CAAC,4BAA4B,CAAC,WAAW,CAAC,CAAC;QAClE,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;QACxE,CAAC;QACD,IAAI,MAAM,CAAC,WAAW,KAAK,WAAW,EAAE,CAAC;YACvC,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;QACxE,CAAC;QACD,MAAM,IAAI,GAAG,MAAM,0BAA0B,CAAC;YAC5C,GAAG,KAAK;YACR,kBAAkB;YAClB,OAAO,EAAE,gBAAgB;YACzB,MAAM;SACP,CAAC,CAAC;QACH,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;QACzB,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACjB,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;QAC7C,kBAAkB,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,mBAAmB,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;IAC3E,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { MAX_ROTATION_CONTAINER_REKEYS } from \"@tearleads/validators/util\";\nimport type {\n ContainerMutationAuthor,\n ContainerRekeyApi,\n MaterializedContainerRekeyPlan,\n} from \"../../../data/containers/shared/types\";\nimport {\n type PrincipalPolicyCache,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n verifyContainerWriterProjection,\n} from \"../../../data/keyingProjectionVerification\";\nimport type { CurrentPolicyReferenceResolver } from \"../../../data/principals/currentPolicyReferenceResolver\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../../data/principals/principalPolicyEvidence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { buildMaterializedContainerRekeyPlan } from \"./rekey\";\nimport { rebaseContainerWriterProjection } from \"./rekeyProjection\";\nimport { selectReplacementPrincipalPolicyReferences } from \"./replacementPrincipalPolicyReferences\";\n\n/** What a rotation needs in hand to sign the descendant rekeys it must carry. */\nexport interface CarriedRekeyPlanningInput {\n readonly apiClient: Pick<ContainerRekeyApi, \"getContainerWriterProjection\">;\n readonly author: ContainerMutationAuthor;\n readonly execSql: ExecSql;\n /**\n * Keys the batch minted and has yet to commit, by epoch id. A rotation's\n * successor is wrapped to recipients at heads the batch itself commits, so\n * no wrap on a re-rooted path opens it for the signer before then; the key\n * the signer just minted does, and its keyring then opens what sits below.\n */\n readonly knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n /**\n * Verified policies the batch itself commits, which the rebased paths cite\n * before any store holds them; and the one each carried rekey cites anew.\n */\n readonly principalPolicyCache?: PrincipalPolicyCache | undefined;\n readonly replacementPrincipalPolicy?:\n | PrincipalPolicyCurrentEvidence\n | undefined;\n readonly resolveAuthoredPolicyReferences?:\n | CurrentPolicyReferenceResolver\n | undefined;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly targetSecretKey: Uint8Array;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}\n\n/** A rotated container's own path once its batch is accepted. */\nexport type SpeculativePath = Pick<\n ContainerWriterProjectionResponse,\n \"containerKeks\" | \"organizationId\" | \"path\" | \"policyEvidence\"\n>;\n\n/**\n * Re-root a served projection on the deepest not-yet-accepted proper ancestor\n * among `speculativePaths`. Each carried plan's own path was built the same\n * way, so the deepest one already holds every speculative level above it. The\n * container's own path, when the batch rotates it too, is not an ancestor: the\n * caller is re-planning that rotation, and it extends what sits above.\n */\nexport function rebaseOnDeepestAncestor(\n served: ContainerWriterProjectionResponse,\n speculativePaths: readonly SpeculativePath[],\n): {\n ancestor: SpeculativePath;\n projection: ContainerWriterProjectionResponse;\n} | null {\n let deepest: SpeculativePath | null = null;\n let deepestIndex = -1;\n for (const speculative of speculativePaths) {\n const containerId = speculative.containerKeks.at(-1)?.containerId;\n if (containerId === served.containerId) continue;\n const index = served.containerKeks.findIndex(\n (kek) => kek.containerId === containerId,\n );\n if (index > deepestIndex) {\n deepest = speculative;\n deepestIndex = index;\n }\n }\n if (!deepest) return null;\n const projection = rebaseContainerWriterProjection(served, deepest);\n return projection ? { ancestor: deepest, projection } : null;\n}\n\n/**\n * Sign one carried rekey against the path its batch will leave behind. The\n * served projection is fetched by the caller; here it is verified, must sit\n * below one of the rotated containers and in that container's organization,\n * and is signed only if this signer holds its key and write access — which a\n * member able to rotate the ancestor always does, since both inherit downward.\n */\nexport async function planCarriedDescendantRekey(\n input: CarriedRekeyPlanningInput & {\n readonly rotated: readonly SpeculativePath[];\n readonly served: ContainerWriterProjectionResponse;\n },\n): Promise<MaterializedContainerRekeyPlan> {\n // Pin the served head before signing beyond it. The batch is acknowledged\n // against the latest durable pin, and a carried rekey is always past epoch\n // 1, so a device that never pinned this container would otherwise reject\n // its own batch after the server had committed it.\n await verifyContainerWriterProjection({\n execSql: input.execSql,\n principalPolicyCache: input.principalPolicyCache,\n projection: input.served,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const rebased = rebaseOnDeepestAncestor(input.served, input.rotated);\n if (!rebased) {\n throw new Error(\n \"Carried descendant rekey is not below the rotated container\",\n );\n }\n // A batch locks whatever organizations it names, so the server holds each\n // to the rule on its own; a carried rekey belongs to the rotation it rides.\n if (input.served.organizationId !== rebased.ancestor.organizationId) {\n throw new Error(\n \"Carried descendant rekey is outside the rotated container's organization\",\n );\n }\n return buildMaterializedContainerRekeyPlan({\n author: {\n ...input.author,\n organizationId: rebased.ancestor.organizationId,\n },\n execSql: input.execSql,\n knownContainerKeks: input.knownContainerKeks,\n // Nothing here is acknowledged yet: pins move only with the batch.\n persistVerificationCheckpoints: false,\n previousProjection: rebased.projection,\n principalPolicyCache: input.principalPolicyCache,\n replacementPrincipalPolicy: input.replacementPrincipalPolicy\n ? await selectReplacementPrincipalPolicyReferences({\n policy: input.replacementPrincipalPolicy,\n projection: rebased.projection,\n principalPolicyCache: input.principalPolicyCache,\n resolveAuthoredPolicyReferences:\n input.resolveAuthoredPolicyReferences,\n })\n : undefined,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n}\n\n/**\n * Sign the descendant rekeys a rotation must commit with (#2340). The server\n * refuses a rotation that would leave a level above a directly granted\n * container pinned to a retired epoch, because the grantee could never re-key\n * that level itself and its writes would wait on another device. It names the\n * levels; this signs them, parent-first, each against the path the batch will\n * leave behind rather than the one currently served.\n *\n * `requiredContainerIds` is a hint, never an authority: each container is\n * fetched and verified here, and refused unless it sits below a rotation.\n */\nexport async function planCarriedDescendantRekeys(\n input: CarriedRekeyPlanningInput & {\n readonly requiredContainerIds: readonly string[];\n /** Each rotated container's own path once the batch is accepted. */\n readonly rotated: readonly SpeculativePath[];\n },\n): Promise<MaterializedContainerRekeyPlan[]> {\n const plans: MaterializedContainerRekeyPlan[] = [];\n const speculativePaths: SpeculativePath[] = [...input.rotated];\n const knownContainerKeks = new Map(input.knownContainerKeks);\n const planned = new Set<string>();\n for (const containerId of input.requiredContainerIds) {\n if (plans.length >= MAX_ROTATION_CONTAINER_REKEYS) break;\n if (planned.has(containerId)) continue;\n const served =\n await input.apiClient.getContainerWriterProjection(containerId);\n if (!served) {\n throw new Error(\"Carried descendant rekey projection is unavailable\");\n }\n if (served.containerId !== containerId) {\n throw new Error(\"Carried descendant rekey targets another container\");\n }\n const plan = await planCarriedDescendantRekey({\n ...input,\n knownContainerKeks,\n rotated: speculativePaths,\n served,\n });\n planned.add(containerId);\n plans.push(plan);\n speculativePaths.push(plan.writerProjection);\n knownContainerKeks.set(plan.plan.containerKeyEpochId, plan.containerKey);\n }\n return plans;\n}\n"]}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { readContainerState } from "../../../data/containers/shared/projection.js";
|
|
2
|
+
import { dedupeReferencedPrincipalStates, referencedPrincipalPolicyKey, } from "../../../data/keyingProjectionVerification/principalPolicyCache.js";
|
|
3
|
+
/** Current membership with only the historical group citations this path uses. */
|
|
4
|
+
export async function selectReplacementPrincipalPolicyReferences(input) {
|
|
5
|
+
if (!("retainedHistory" in input.policy) ||
|
|
6
|
+
!input.resolveAuthoredPolicyReferences)
|
|
7
|
+
return input.policy;
|
|
8
|
+
const references = dedupeReferencedPrincipalStates(input.projection.path
|
|
9
|
+
.flatMap((manifest) => readContainerState(manifest).referencedPrincipalHeads)
|
|
10
|
+
.filter((reference) => reference.principalType === input.policy.principalType &&
|
|
11
|
+
reference.principalId === input.policy.principalId));
|
|
12
|
+
const selected = await input.resolveAuthoredPolicyReferences(input.policy, references);
|
|
13
|
+
// Planning is sequential: each path selects its own citations before use.
|
|
14
|
+
// Only speculative successor citations use this cache entry. Served historical
|
|
15
|
+
// references still resolve to acknowledged policies and cannot pin our new head.
|
|
16
|
+
input.principalPolicyCache?.set(referencedPrincipalPolicyKey(selected.state), selected);
|
|
17
|
+
return selected;
|
|
18
|
+
}
|
|
19
|
+
//# sourceMappingURL=replacementPrincipalPolicyReferences.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"replacementPrincipalPolicyReferences.js","sourceRoot":"","sources":["replacementPrincipalPolicyReferences.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,MAAM,4CAA4C,CAAC;AAEhF,OAAO,EACL,+BAA+B,EAC/B,4BAA4B,GAC7B,MAAM,iEAAiE,CAAC;AAIzE,kFAAkF;AAClF,MAAM,CAAC,KAAK,UAAU,0CAA0C,CAAC,KAOhE;IACC,IACE,CAAC,CAAC,iBAAiB,IAAI,KAAK,CAAC,MAAM,CAAC;QACpC,CAAC,KAAK,CAAC,+BAA+B;QAEtC,OAAO,KAAK,CAAC,MAAM,CAAC;IACtB,MAAM,UAAU,GAAG,+BAA+B,CAChD,KAAK,CAAC,UAAU,CAAC,IAAI;SAClB,OAAO,CACN,CAAC,QAAQ,EAAE,EAAE,CAAC,kBAAkB,CAAC,QAAQ,CAAC,CAAC,wBAAwB,CACpE;SACA,MAAM,CACL,CAAC,SAAS,EAAE,EAAE,CACZ,SAAS,CAAC,aAAa,KAAK,KAAK,CAAC,MAAM,CAAC,aAAa;QACtD,SAAS,CAAC,WAAW,KAAK,KAAK,CAAC,MAAM,CAAC,WAAW,CACrD,CACJ,CAAC;IACF,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,+BAA+B,CAC1D,KAAK,CAAC,MAAM,EACZ,UAAU,CACX,CAAC;IACF,0EAA0E;IAC1E,+EAA+E;IAC/E,iFAAiF;IACjF,KAAK,CAAC,oBAAoB,EAAE,GAAG,CAC7B,4BAA4B,CAAC,QAAQ,CAAC,KAAK,CAAC,EAC5C,QAAQ,CACT,CAAC;IACF,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { readContainerState } from \"../../../data/containers/shared/projection\";\nimport type { PrincipalPolicyCache } from \"../../../data/keyingProjectionVerification\";\nimport {\n dedupeReferencedPrincipalStates,\n referencedPrincipalPolicyKey,\n} from \"../../../data/keyingProjectionVerification/principalPolicyCache\";\nimport type { CurrentPolicyReferenceResolver } from \"../../../data/principals/currentPolicyReferenceResolver\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../../data/principals/principalPolicyEvidence\";\n\n/** Current membership with only the historical group citations this path uses. */\nexport async function selectReplacementPrincipalPolicyReferences(input: {\n readonly policy: PrincipalPolicyCurrentEvidence;\n readonly projection: ContainerWriterProjectionResponse;\n readonly principalPolicyCache?: PrincipalPolicyCache | undefined;\n readonly resolveAuthoredPolicyReferences?:\n | CurrentPolicyReferenceResolver\n | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence> {\n if (\n !(\"retainedHistory\" in input.policy) ||\n !input.resolveAuthoredPolicyReferences\n )\n return input.policy;\n const references = dedupeReferencedPrincipalStates(\n input.projection.path\n .flatMap(\n (manifest) => readContainerState(manifest).referencedPrincipalHeads,\n )\n .filter(\n (reference) =>\n reference.principalType === input.policy.principalType &&\n reference.principalId === input.policy.principalId,\n ),\n );\n const selected = await input.resolveAuthoredPolicyReferences(\n input.policy,\n references,\n );\n // Planning is sequential: each path selects its own citations before use.\n // Only speculative successor citations use this cache entry. Served historical\n // references still resolve to acknowledged policies and cannot pin our new head.\n input.principalPolicyCache?.set(\n referencedPrincipalPolicyKey(selected.state),\n selected,\n );\n return selected;\n}\n"]}
|
|
@@ -98,6 +98,7 @@ async function commitMissingGroupGrantPolicy(input) {
|
|
|
98
98
|
throw new Error("Container group share requires principal policy signing context");
|
|
99
99
|
}
|
|
100
100
|
const policyApi = {
|
|
101
|
+
recoverPendingPrincipalMutation: input.apiClient.recoverPendingPrincipalMutation?.bind(input.apiClient),
|
|
101
102
|
commitOrganizationGroupPolicy: input.apiClient.commitOrganizationGroupPolicy.bind(input.apiClient),
|
|
102
103
|
getCurrentPrincipalPolicy: input.apiClient.getCurrentPrincipalPolicy.bind(input.apiClient),
|
|
103
104
|
};
|
|
@@ -198,6 +199,9 @@ function loadShareGroupPolicy(input) {
|
|
|
198
199
|
});
|
|
199
200
|
}
|
|
200
201
|
export async function shareRemoteContainerWithGroup(input) {
|
|
202
|
+
if (input.stillCurrent?.() === false)
|
|
203
|
+
return null;
|
|
204
|
+
await input.apiClient.recoverPendingPrincipalMutation?.(input.author.organizationId);
|
|
201
205
|
if (input.stillCurrent?.() === false)
|
|
202
206
|
return null;
|
|
203
207
|
const resolveProjectionUserKey = requireProjectionUserKeyResolver(input.resolveProjectionUserKey, "Remote container share");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"share.js","sourceRoot":"","sources":["share.ts"],"names":[],"mappings":"AAgBA,OAAO,EACL,sCAAsC,EACtC,wCAAwC,EAGxC,gCAAgC,GACjC,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,uCAAuC,EAAE,MAAM,iEAAiE,CAAC;AAC1H,OAAO,EAAE,yBAAyB,EAAE,MAAM,sDAAsD,CAAC;AAGjG,OAAO,EACL,kCAAkC,GAEnC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,yBAAyB,EAAE,MAAM,yCAAyC,CAAC;AACpF,OAAO,EAAE,oCAAoC,EAAE,MAAM,qDAAqD,CAAC;AAC3G,OAAO,EAAE,+CAA+C,EAAE,MAAM,yDAAyD,CAAC;AAC1H,OAAO,EAAE,kCAAkC,EAAE,MAAM,qCAAqC,CAAC;AAEzF,OAAO,EACL,mCAAmC,EACnC,4BAA4B,GAC7B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,8BAA8B,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,EAAE,mCAAmC,EAAE,MAAM,wBAAwB,CAAC;AAC7E,OAAO,EACL,4BAA4B,EAE5B,qCAAqC,GACtC,MAAM,wBAAwB,CAAC;AAEhC,MAAM,oCAAqC,SAAQ,KAAK;CAAG;AAE3D,KAAK,UAAU,8BAA8B,CAC3C,KAAgE;IAEhE,OAAO,wCAAwC,CAAC,GAAG,EAAE,CACnD,mCAAmC,CAAC,KAAK,CAAC,CAC3C,CAAC;AACJ,CAAC;AAED,iFAAiF;AACjF,KAAK,UAAU,sBAAsB,CACnC,KAG0E,EAC1E,wBAAmD;IAEnD,MAAM,gBAAgB,GACpB,KAAK,CAAC,kBAAkB;QACxB,CAAC,MAAM,KAAK,CAAC,SAAS,CAAC,4BAA4B,CAAC,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AAE,KAAK,CAAC,YAAY;QAChC,MAAM,EAAE,GAAG,EAAE,CACX,4BAA4B,CAAC,GAAG,EAAE,CAChC,KAAK,CAAC,SAAS,CAAC,cAAc,CAC5B,KAAK,CAAC,WAAW,EACjB,gBAAgB,CAAC,IAAI,CAAC,OAAO,EAC7B;YACE,qCAAqC,EAAE,KAAK,CAAC,MAAM,CAAC,cAAc;SACnE,CACF,CACF;KACJ,CAAC,CAAC;IACH,IAAI,CAAC,MAAM;QAAE,OAAO,IAAI,CAAC;IAEzB,2EAA2E;IAC3E,yEAAyE;IACzE,0EAA0E;IAC1E,sDAAsD;IACtD,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK,EAAE,CAAC;QACrC,MAAM,yBAAyB,CAC7B,KAAK,CAAC,OAAO,EACb,uBAAuB,CAAC,MAAM,EAC9B,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,EACxB,KAAK,CAAC,MAAM,CAAC,cAAc,EAC3B,EAAE,YAAY,EAAE,KAAK,CAAC,YAAY,EAAE,CACrC,CAAC;IACJ,CAAC;IACD,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IAElD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type {\n ContainerAccessLevel,\n SigningKeyPair,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n ContainerMutationResponse,\n ContainerWriterProjectionResponse,\n PrincipalPolicyBundleResponse,\n} from \"@tearleads/validators/response\";\nimport type {\n ContainerMutationAuthor,\n ContainerShareApi,\n ContainerSharePlan,\n MaterializedContainerSharePlan,\n} from \"../../../data/containers/shared/types\";\nimport {\n isProjectionVerificationCancelledError,\n nullOnProjectionVerificationCancellation,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n requireProjectionUserKeyResolver,\n} from \"../../../data/keyingProjectionVerification\";\nimport { principalPolicyCacheForVerifiedPolicies } from \"../../../data/keyingProjectionVerification/principalPolicyCache\";\nimport { savePrincipalPolicyBundle } from \"../../../data/persistence/principalPolicyPersistence\";\nimport type { SecurityIncidentReporter } from \"../../../data/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n requireTrustedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n} from \"../../../data/trustedUserIdentity\";\nimport { createGroupMetadataAccess } from \"../../organizations/groupMetadataAccess\";\nimport { createGroupMetadataContainerVerifier } from \"../../organizations/groupMetadataContainerAuthority\";\nimport { preparePrincipalContainerRematerializationBatch } from \"../../organizations/principalContainerRematerialization\";\nimport { setOrganizationGroupContainerGrant } from \"../../organizations/principalPolicy\";\nimport type { GroupPolicyNameReader } from \"../../organizations/principalPolicyRequest\";\nimport {\n submitAcknowledgedContainerMutation,\n submitPlainContainerMutation,\n} from \"./mutationSubmit\";\nimport { projectionWithCurrentAncestors } from \"./shareAncestorRepair\";\nimport { buildMaterializedContainerSharePlan } from \"./shareMaterialization\";\nimport {\n advanceVerifiedSharePolicies,\n type ContainerManagedPrincipalShareApi,\n loadVerifiedGroupSharePrincipalPolicy,\n} from \"./sharePrincipalPolicy\";\n\nclass ContainerShareGenerationExpiredError extends Error {}\n\nasync function buildCurrentContainerSharePlan(\n input: Parameters<typeof buildMaterializedContainerSharePlan>[0],\n): Promise<MaterializedContainerSharePlan | null> {\n return nullOnProjectionVerificationCancellation(() =>\n buildMaterializedContainerSharePlan(input),\n );\n}\n\n/** The container's projection, with any lazily stale chain above it repaired. */\nasync function resolveShareProjection(\n input: Omit<\n Parameters<typeof projectionWithCurrentAncestors>[0],\n \"previousProjection\" | \"resolveProjectionUserKey\"\n > & { previousProjection?: ContainerWriterProjectionResponse | undefined },\n resolveProjectionUserKey: ProjectionUserKeyResolver,\n): Promise<ContainerWriterProjectionResponse | null> {\n const servedProjection =\n input.previousProjection ??\n (await input.apiClient.getContainerWriterProjection(input.containerId));\n if (!servedProjection || input.stillCurrent?.() === false) return null;\n const previousProjection = await projectionWithCurrentAncestors({\n ...input,\n previousProjection: servedProjection,\n resolveProjectionUserKey,\n });\n return input.stillCurrent?.() === false ? null : previousProjection;\n}\n\nexport async function shareRemoteContainer(input: {\n reportSecurityIncident: SecurityIncidentReporter;\n accessLevel: ContainerAccessLevel;\n apiClient: ContainerShareApi;\n author: ContainerMutationAuthor;\n containerId: string;\n eventId?: string | undefined;\n execSql: ExecSql;\n previousProjection?: ContainerWriterProjectionResponse | undefined;\n recipientUserId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n signedAt?: string | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<{\n containerKey: Uint8Array;\n plan: ContainerSharePlan;\n response: ContainerMutationResponse;\n} | null> {\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote container share\",\n );\n const resolveTrustedUserIdentity = requireTrustedUserIdentityResolver(\n input.resolveTrustedUserIdentity,\n );\n const recipientIdentity = await resolveTrustedUserIdentity(\n input.recipientUserId,\n );\n if (!recipientIdentity || input.stillCurrent?.() === false) {\n return null;\n }\n const previousProjection = await resolveShareProjection(\n input,\n resolveProjectionUserKey,\n );\n if (!previousProjection) return null;\n\n const materializedPlan = await buildCurrentContainerSharePlan({\n accessLevel: input.accessLevel,\n author: input.author,\n eventId: input.eventId,\n execSql: input.execSql,\n previousProjection,\n recipient: {\n recipientEncapsulationPublicKey: recipientIdentity.encapsulationPublicKey,\n subjectId: input.recipientUserId,\n subjectType: \"user\",\n },\n resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n if (!materializedPlan) return null;\n return submitAcknowledgedContainerMutation({\n reportSecurityIncident: input.reportSecurityIncident,\n recitationPolicies: [],\n apiClient: input.apiClient,\n author: input.author,\n containerKey: materializedPlan.containerKey,\n execSql: input.execSql,\n plan: materializedPlan.plan,\n stillCurrent: input.stillCurrent,\n submit: () =>\n submitPlainContainerMutation(() =>\n input.apiClient.shareContainer(\n input.containerId,\n materializedPlan.plan.request,\n {\n expectedPaymentRequiredOrganizationId: input.author.organizationId,\n },\n ),\n ),\n });\n}\n\ninterface RemoteContainerGroupShareInput {\n reportSecurityIncident: SecurityIncidentReporter;\n accessLevel: ContainerAccessLevel;\n apiClient: ContainerManagedPrincipalShareApi;\n author: ContainerMutationAuthor;\n containerId: string;\n eventId?: string | undefined;\n execSql: ExecSql;\n /**\n * The display name the user chose the group by, checked against the name\n * committed in the verified group policy so a relabeled read-model row\n * cannot redirect the share onto another group. `null` is reserved for the\n * grant-preserving re-wrap: a share that would mint a new grant without a\n * name is refused.\n */\n expectedGroupName: string | null;\n readEncryptedName?: GroupPolicyNameReader | undefined;\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n previousProjection?: ContainerWriterProjectionResponse | undefined;\n recipientGroupId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n signedAt?: string | undefined;\n signingKeyPair?: SigningKeyPair | null | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}\n\ninterface RemoteContainerGroupShareResult {\n containerKey: Uint8Array;\n plan: ContainerSharePlan;\n response: ContainerMutationResponse;\n}\n\nfunction isMaterializedContainerSharePlan(\n value: Awaited<\n ReturnType<typeof preparePrincipalContainerRematerializationBatch>\n >[\"plans\"][number],\n): value is MaterializedContainerSharePlan {\n return value.plan.body.eventType === \"container.grant\";\n}\n\nasync function prepareMissingGroupGrantMutations(input: {\n currentPolicy: PrincipalPolicyBundleResponse;\n nextPolicy: VerifiedPrincipalPolicy;\n shareInput: RemoteContainerGroupShareInput;\n}) {\n const { currentPolicy, nextPolicy, shareInput } = input;\n return preparePrincipalContainerRematerializationBatch({\n reportSecurityIncident: shareInput.reportSecurityIncident,\n apiClient: shareInput.apiClient,\n author: shareInput.author,\n execSql: shareInput.execSql,\n grants: [\n ...new Map(\n [...currentPolicy.currentGrants, ...nextPolicy.grants].map(\n (grant) => [grant.containerId, grant] as const,\n ),\n ).values(),\n ],\n groupId: shareInput.recipientGroupId,\n nextPolicy,\n resolveTrustedUserIdentity: shareInput.resolveTrustedUserIdentity,\n stillCurrent: shareInput.stillCurrent,\n targetSecretKey: shareInput.targetSecretKey,\n warmReferencedPrincipalPolicies: shareInput.warmReferencedPrincipalPolicies,\n });\n}\n\nasync function commitMissingGroupGrantPolicy(\n input: RemoteContainerGroupShareInput,\n): Promise<{\n preparedTarget: Awaited<\n ReturnType<typeof preparePrincipalContainerRematerializationBatch>\n >;\n storedPolicy: Awaited<ReturnType<typeof setOrganizationGroupContainerGrant>>;\n} | null> {\n const signingKeyPair = input.signingKeyPair;\n if (!signingKeyPair) {\n throw new Error(\n \"Container group share requires principal policy signing context\",\n );\n }\n const policyApi = {\n commitOrganizationGroupPolicy:\n input.apiClient.commitOrganizationGroupPolicy.bind(input.apiClient),\n getCurrentPrincipalPolicy: input.apiClient.getCurrentPrincipalPolicy.bind(\n input.apiClient,\n ),\n };\n let preparedTarget:\n | Awaited<\n ReturnType<typeof preparePrincipalContainerRematerializationBatch>\n >\n | undefined;\n try {\n const storedPolicy = await setOrganizationGroupContainerGrant({\n accessLevel: input.accessLevel,\n apiClient: policyApi,\n assertCanCommit: () => {\n if (input.stillCurrent?.() === false) {\n throw new ContainerShareGenerationExpiredError();\n }\n },\n containerId: input.containerId,\n execSql: input.execSql,\n groupId: input.recipientGroupId,\n organizationId: input.author.organizationId,\n prepareContainerMutations: async ({ currentPolicy, nextPolicy }) => {\n preparedTarget = await prepareMissingGroupGrantMutations({\n currentPolicy,\n nextPolicy,\n shareInput: input,\n });\n return preparedTarget;\n },\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n signerUserId: input.author.signerUserId,\n signingFingerprint: input.author.signerKeyFingerprint,\n signingKeyPair,\n });\n if (!preparedTarget) {\n throw new Error(\"Container group share preparation is incomplete\");\n }\n return { preparedTarget, storedPolicy };\n } catch (error) {\n if (\n error instanceof ContainerShareGenerationExpiredError ||\n isProjectionVerificationCancelledError(error)\n ) {\n return null;\n }\n throw error;\n }\n}\n\nasync function commitMissingGroupGrant(\n input: RemoteContainerGroupShareInput,\n): Promise<RemoteContainerGroupShareResult | null> {\n if (!input.signingKeyPair) {\n throw new Error(\n \"Container group share requires principal policy signing context\",\n );\n }\n if (input.stillCurrent?.() === false) return null;\n const committed = await commitMissingGroupGrantPolicy(input);\n if (!committed) return null;\n const { preparedTarget, storedPolicy } = committed;\n const targetIndex = preparedTarget?.plans.findIndex(\n (planned) => planned.plan.containerId === input.containerId,\n );\n const response =\n targetIndex === undefined || targetIndex < 0\n ? undefined\n : storedPolicy.containerMutations[targetIndex];\n const targetPlan =\n targetIndex === undefined || targetIndex < 0\n ? undefined\n : preparedTarget?.plans[targetIndex];\n if (\n !targetPlan ||\n !response ||\n !isMaterializedContainerSharePlan(targetPlan)\n ) {\n throw new Error(\"Container group share acknowledgement is incomplete\");\n }\n return {\n containerKey: targetPlan.containerKey,\n plan: targetPlan.plan,\n response,\n };\n}\n\n// Only a re-wrap of an existing signed grant may run without the chosen name;\n// minting a grant is exactly the operation the name binding protects.\nfunction assertGrantMintNamed(expectedGroupName: string | null): void {\n if (expectedGroupName === null) {\n throw new Error(\n \"Minting a group grant requires the chosen group name; only a re-wrap of an existing signed grant may omit it\",\n );\n }\n}\n\nfunction loadShareGroupPolicy(input: RemoteContainerGroupShareInput) {\n return loadVerifiedGroupSharePrincipalPolicy({\n apiClient: input.apiClient,\n execSql: input.execSql,\n expectedGroupName: input.expectedGroupName ?? undefined,\n readEncryptedName:\n input.readEncryptedName ??\n createGroupMetadataAccess({\n ...input,\n organizationId: input.author.organizationId,\n verifyMetadataContainer: createGroupMetadataContainerVerifier({\n ...input,\n organizationId: input.author.organizationId,\n stillCurrent: input.stillCurrent ?? (() => true),\n }),\n }).readName,\n groupId: input.recipientGroupId,\n organizationId: input.author.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n}\n\nexport async function shareRemoteContainerWithGroup(\n input: RemoteContainerGroupShareInput,\n): Promise<RemoteContainerGroupShareResult | null> {\n if (input.stillCurrent?.() === false) return null;\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote container share\",\n );\n const previousProjection = await resolveShareProjection(\n input,\n resolveProjectionUserKey,\n );\n if (!previousProjection) return null;\n const verifiedPrincipalPolicy = await loadShareGroupPolicy(input);\n if (input.stillCurrent?.() === false) return null;\n await advanceVerifiedSharePolicies(\n input.execSql,\n verifiedPrincipalPolicy,\n input.stillCurrent,\n );\n if (input.stillCurrent?.() === false) return null;\n\n const signedGrant = verifiedPrincipalPolicy.policy.grants.find(\n (grant) => grant.containerId === input.containerId,\n );\n if (!signedGrant || signedGrant.accessLevel !== input.accessLevel) {\n assertGrantMintNamed(input.expectedGroupName);\n return commitMissingGroupGrant(input);\n }\n\n const materializedPlan = await buildCurrentContainerSharePlan({\n accessLevel: input.accessLevel,\n author: input.author,\n eventId: input.eventId,\n execSql: input.execSql,\n knownContainerKeks: input.knownContainerKeks,\n principalPolicyCache: principalPolicyCacheForVerifiedPolicies(\n verifiedPrincipalPolicy.checkpointPolicies,\n ),\n previousProjection,\n recipient: {\n principalPolicy: verifiedPrincipalPolicy.policy,\n subjectId: input.recipientGroupId,\n subjectType: \"group\",\n },\n resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n if (!materializedPlan) return null;\n const result = await submitAcknowledgedContainerMutation({\n reportSecurityIncident: input.reportSecurityIncident,\n recitationPolicies: verifiedPrincipalPolicy.checkpointPolicies,\n apiClient: input.apiClient,\n author: input.author,\n containerKey: materializedPlan.containerKey,\n execSql: input.execSql,\n plan: materializedPlan.plan,\n stillCurrent: input.stillCurrent,\n submit: () =>\n submitPlainContainerMutation(() =>\n input.apiClient.shareContainer(\n input.containerId,\n materializedPlan.plan.request,\n {\n expectedPaymentRequiredOrganizationId: input.author.organizationId,\n },\n ),\n ),\n });\n if (!result) return null;\n\n // Keep the previously cached group epoch available until the old container\n // wrap has been unwrapped and the replacement has committed. Root has no\n // parent fallback, so caching the rotated policy any earlier destroys the\n // only local path to the KEK that must be re-wrapped.\n if (input.stillCurrent?.() !== false) {\n await savePrincipalPolicyBundle(\n input.execSql,\n verifiedPrincipalPolicy.bundle,\n new Date().toISOString(),\n input.author.organizationId,\n { stillCurrent: input.stillCurrent },\n );\n }\n if (input.stillCurrent?.() === false) return null;\n\n return result;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"share.js","sourceRoot":"","sources":["share.ts"],"names":[],"mappings":"AAgBA,OAAO,EACL,sCAAsC,EACtC,wCAAwC,EAGxC,gCAAgC,GACjC,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,uCAAuC,EAAE,MAAM,iEAAiE,CAAC;AAC1H,OAAO,EAAE,yBAAyB,EAAE,MAAM,sDAAsD,CAAC;AAGjG,OAAO,EACL,kCAAkC,GAEnC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,yBAAyB,EAAE,MAAM,yCAAyC,CAAC;AACpF,OAAO,EAAE,oCAAoC,EAAE,MAAM,qDAAqD,CAAC;AAC3G,OAAO,EAAE,+CAA+C,EAAE,MAAM,yDAAyD,CAAC;AAC1H,OAAO,EAAE,kCAAkC,EAAE,MAAM,qCAAqC,CAAC;AAEzF,OAAO,EACL,mCAAmC,EACnC,4BAA4B,GAC7B,MAAM,kBAAkB,CAAC;AAC1B,OA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AE,CAAC;QACrC,MAAM,yBAAyB,CAC7B,KAAK,CAAC,OAAO,EACb,uBAAuB,CAAC,MAAM,EAC9B,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,EACxB,KAAK,CAAC,MAAM,CAAC,cAAc,EAC3B,EAAE,YAAY,EAAE,KAAK,CAAC,YAAY,EAAE,CACrC,CAAC;IACJ,CAAC;IACD,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IAElD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type {\n ContainerAccessLevel,\n SigningKeyPair,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n ContainerMutationResponse,\n ContainerWriterProjectionResponse,\n PrincipalPolicyBundleResponse,\n} from \"@tearleads/validators/response\";\nimport type {\n ContainerMutationAuthor,\n ContainerShareApi,\n ContainerSharePlan,\n MaterializedContainerSharePlan,\n} from \"../../../data/containers/shared/types\";\nimport {\n isProjectionVerificationCancelledError,\n nullOnProjectionVerificationCancellation,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n requireProjectionUserKeyResolver,\n} from \"../../../data/keyingProjectionVerification\";\nimport { principalPolicyCacheForVerifiedPolicies } from \"../../../data/keyingProjectionVerification/principalPolicyCache\";\nimport { savePrincipalPolicyBundle } from \"../../../data/persistence/principalPolicyPersistence\";\nimport type { SecurityIncidentReporter } from \"../../../data/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n requireTrustedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n} from \"../../../data/trustedUserIdentity\";\nimport { createGroupMetadataAccess } from \"../../organizations/groupMetadataAccess\";\nimport { createGroupMetadataContainerVerifier } from \"../../organizations/groupMetadataContainerAuthority\";\nimport { preparePrincipalContainerRematerializationBatch } from \"../../organizations/principalContainerRematerialization\";\nimport { setOrganizationGroupContainerGrant } from \"../../organizations/principalPolicy\";\nimport type { GroupPolicyNameReader } from \"../../organizations/principalPolicyRequest\";\nimport {\n submitAcknowledgedContainerMutation,\n submitPlainContainerMutation,\n} from \"./mutationSubmit\";\nimport { projectionWithCurrentAncestors } from \"./shareAncestorRepair\";\nimport { buildMaterializedContainerSharePlan } from \"./shareMaterialization\";\nimport {\n advanceVerifiedSharePolicies,\n type ContainerManagedPrincipalShareApi,\n loadVerifiedGroupSharePrincipalPolicy,\n} from \"./sharePrincipalPolicy\";\n\nclass ContainerShareGenerationExpiredError extends Error {}\n\nasync function buildCurrentContainerSharePlan(\n input: Parameters<typeof buildMaterializedContainerSharePlan>[0],\n): Promise<MaterializedContainerSharePlan | null> {\n return nullOnProjectionVerificationCancellation(() =>\n buildMaterializedContainerSharePlan(input),\n );\n}\n\n/** The container's projection, with any lazily stale chain above it repaired. */\nasync function resolveShareProjection(\n input: Omit<\n Parameters<typeof projectionWithCurrentAncestors>[0],\n \"previousProjection\" | \"resolveProjectionUserKey\"\n > & { previousProjection?: ContainerWriterProjectionResponse | undefined },\n resolveProjectionUserKey: ProjectionUserKeyResolver,\n): Promise<ContainerWriterProjectionResponse | null> {\n const servedProjection =\n input.previousProjection ??\n (await input.apiClient.getContainerWriterProjection(input.containerId));\n if (!servedProjection || input.stillCurrent?.() === false) return null;\n const previousProjection = await projectionWithCurrentAncestors({\n ...input,\n previousProjection: servedProjection,\n resolveProjectionUserKey,\n });\n return input.stillCurrent?.() === false ? null : previousProjection;\n}\n\nexport async function shareRemoteContainer(input: {\n reportSecurityIncident: SecurityIncidentReporter;\n accessLevel: ContainerAccessLevel;\n apiClient: ContainerShareApi;\n author: ContainerMutationAuthor;\n containerId: string;\n eventId?: string | undefined;\n execSql: ExecSql;\n previousProjection?: ContainerWriterProjectionResponse | undefined;\n recipientUserId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n signedAt?: string | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<{\n containerKey: Uint8Array;\n plan: ContainerSharePlan;\n response: ContainerMutationResponse;\n} | null> {\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote container share\",\n );\n const resolveTrustedUserIdentity = requireTrustedUserIdentityResolver(\n input.resolveTrustedUserIdentity,\n );\n const recipientIdentity = await resolveTrustedUserIdentity(\n input.recipientUserId,\n );\n if (!recipientIdentity || input.stillCurrent?.() === false) {\n return null;\n }\n const previousProjection = await resolveShareProjection(\n input,\n resolveProjectionUserKey,\n );\n if (!previousProjection) return null;\n\n const materializedPlan = await buildCurrentContainerSharePlan({\n accessLevel: input.accessLevel,\n author: input.author,\n eventId: input.eventId,\n execSql: input.execSql,\n previousProjection,\n recipient: {\n recipientEncapsulationPublicKey: recipientIdentity.encapsulationPublicKey,\n subjectId: input.recipientUserId,\n subjectType: \"user\",\n },\n resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n if (!materializedPlan) return null;\n return submitAcknowledgedContainerMutation({\n reportSecurityIncident: input.reportSecurityIncident,\n recitationPolicies: [],\n apiClient: input.apiClient,\n author: input.author,\n containerKey: materializedPlan.containerKey,\n execSql: input.execSql,\n plan: materializedPlan.plan,\n stillCurrent: input.stillCurrent,\n submit: () =>\n submitPlainContainerMutation(() =>\n input.apiClient.shareContainer(\n input.containerId,\n materializedPlan.plan.request,\n {\n expectedPaymentRequiredOrganizationId: input.author.organizationId,\n },\n ),\n ),\n });\n}\n\ninterface RemoteContainerGroupShareInput {\n reportSecurityIncident: SecurityIncidentReporter;\n accessLevel: ContainerAccessLevel;\n apiClient: ContainerManagedPrincipalShareApi;\n author: ContainerMutationAuthor;\n containerId: string;\n eventId?: string | undefined;\n execSql: ExecSql;\n /**\n * The display name the user chose the group by, checked against the name\n * committed in the verified group policy so a relabeled read-model row\n * cannot redirect the share onto another group. `null` is reserved for the\n * grant-preserving re-wrap: a share that would mint a new grant without a\n * name is refused.\n */\n expectedGroupName: string | null;\n readEncryptedName?: GroupPolicyNameReader | undefined;\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n previousProjection?: ContainerWriterProjectionResponse | undefined;\n recipientGroupId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n signedAt?: string | undefined;\n signingKeyPair?: SigningKeyPair | null | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}\n\ninterface RemoteContainerGroupShareResult {\n containerKey: Uint8Array;\n plan: ContainerSharePlan;\n response: ContainerMutationResponse;\n}\n\nfunction isMaterializedContainerSharePlan(\n value: Awaited<\n ReturnType<typeof preparePrincipalContainerRematerializationBatch>\n >[\"plans\"][number],\n): value is MaterializedContainerSharePlan {\n return value.plan.body.eventType === \"container.grant\";\n}\n\nasync function prepareMissingGroupGrantMutations(input: {\n currentPolicy: PrincipalPolicyBundleResponse;\n nextPolicy: VerifiedPrincipalPolicy;\n shareInput: RemoteContainerGroupShareInput;\n}) {\n const { currentPolicy, nextPolicy, shareInput } = input;\n return preparePrincipalContainerRematerializationBatch({\n reportSecurityIncident: shareInput.reportSecurityIncident,\n apiClient: shareInput.apiClient,\n author: shareInput.author,\n execSql: shareInput.execSql,\n grants: [\n ...new Map(\n [...currentPolicy.currentGrants, ...nextPolicy.grants].map(\n (grant) => [grant.containerId, grant] as const,\n ),\n ).values(),\n ],\n groupId: shareInput.recipientGroupId,\n nextPolicy,\n resolveTrustedUserIdentity: shareInput.resolveTrustedUserIdentity,\n stillCurrent: shareInput.stillCurrent,\n targetSecretKey: shareInput.targetSecretKey,\n warmReferencedPrincipalPolicies: shareInput.warmReferencedPrincipalPolicies,\n });\n}\n\nasync function commitMissingGroupGrantPolicy(\n input: RemoteContainerGroupShareInput,\n): Promise<{\n preparedTarget: Awaited<\n ReturnType<typeof preparePrincipalContainerRematerializationBatch>\n >;\n storedPolicy: Awaited<ReturnType<typeof setOrganizationGroupContainerGrant>>;\n} | null> {\n const signingKeyPair = input.signingKeyPair;\n if (!signingKeyPair) {\n throw new Error(\n \"Container group share requires principal policy signing context\",\n );\n }\n const policyApi = {\n recoverPendingPrincipalMutation:\n input.apiClient.recoverPendingPrincipalMutation?.bind(input.apiClient),\n commitOrganizationGroupPolicy:\n input.apiClient.commitOrganizationGroupPolicy.bind(input.apiClient),\n getCurrentPrincipalPolicy: input.apiClient.getCurrentPrincipalPolicy.bind(\n input.apiClient,\n ),\n };\n let preparedTarget:\n | Awaited<\n ReturnType<typeof preparePrincipalContainerRematerializationBatch>\n >\n | undefined;\n try {\n const storedPolicy = await setOrganizationGroupContainerGrant({\n accessLevel: input.accessLevel,\n apiClient: policyApi,\n assertCanCommit: () => {\n if (input.stillCurrent?.() === false) {\n throw new ContainerShareGenerationExpiredError();\n }\n },\n containerId: input.containerId,\n execSql: input.execSql,\n groupId: input.recipientGroupId,\n organizationId: input.author.organizationId,\n prepareContainerMutations: async ({ currentPolicy, nextPolicy }) => {\n preparedTarget = await prepareMissingGroupGrantMutations({\n currentPolicy,\n nextPolicy,\n shareInput: input,\n });\n return preparedTarget;\n },\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n signerUserId: input.author.signerUserId,\n signingFingerprint: input.author.signerKeyFingerprint,\n signingKeyPair,\n });\n if (!preparedTarget) {\n throw new Error(\"Container group share preparation is incomplete\");\n }\n return { preparedTarget, storedPolicy };\n } catch (error) {\n if (\n error instanceof ContainerShareGenerationExpiredError ||\n isProjectionVerificationCancelledError(error)\n ) {\n return null;\n }\n throw error;\n }\n}\n\nasync function commitMissingGroupGrant(\n input: RemoteContainerGroupShareInput,\n): Promise<RemoteContainerGroupShareResult | null> {\n if (!input.signingKeyPair) {\n throw new Error(\n \"Container group share requires principal policy signing context\",\n );\n }\n if (input.stillCurrent?.() === false) return null;\n const committed = await commitMissingGroupGrantPolicy(input);\n if (!committed) return null;\n const { preparedTarget, storedPolicy } = committed;\n const targetIndex = preparedTarget?.plans.findIndex(\n (planned) => planned.plan.containerId === input.containerId,\n );\n const response =\n targetIndex === undefined || targetIndex < 0\n ? undefined\n : storedPolicy.containerMutations[targetIndex];\n const targetPlan =\n targetIndex === undefined || targetIndex < 0\n ? undefined\n : preparedTarget?.plans[targetIndex];\n if (\n !targetPlan ||\n !response ||\n !isMaterializedContainerSharePlan(targetPlan)\n ) {\n throw new Error(\"Container group share acknowledgement is incomplete\");\n }\n return {\n containerKey: targetPlan.containerKey,\n plan: targetPlan.plan,\n response,\n };\n}\n\n// Only a re-wrap of an existing signed grant may run without the chosen name;\n// minting a grant is exactly the operation the name binding protects.\nfunction assertGrantMintNamed(expectedGroupName: string | null): void {\n if (expectedGroupName === null) {\n throw new Error(\n \"Minting a group grant requires the chosen group name; only a re-wrap of an existing signed grant may omit it\",\n );\n }\n}\n\nfunction loadShareGroupPolicy(input: RemoteContainerGroupShareInput) {\n return loadVerifiedGroupSharePrincipalPolicy({\n apiClient: input.apiClient,\n execSql: input.execSql,\n expectedGroupName: input.expectedGroupName ?? undefined,\n readEncryptedName:\n input.readEncryptedName ??\n createGroupMetadataAccess({\n ...input,\n organizationId: input.author.organizationId,\n verifyMetadataContainer: createGroupMetadataContainerVerifier({\n ...input,\n organizationId: input.author.organizationId,\n stillCurrent: input.stillCurrent ?? (() => true),\n }),\n }).readName,\n groupId: input.recipientGroupId,\n organizationId: input.author.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n}\n\nexport async function shareRemoteContainerWithGroup(\n input: RemoteContainerGroupShareInput,\n): Promise<RemoteContainerGroupShareResult | null> {\n if (input.stillCurrent?.() === false) return null;\n await input.apiClient.recoverPendingPrincipalMutation?.(\n input.author.organizationId,\n );\n if (input.stillCurrent?.() === false) return null;\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote container share\",\n );\n const previousProjection = await resolveShareProjection(\n input,\n resolveProjectionUserKey,\n );\n if (!previousProjection) return null;\n const verifiedPrincipalPolicy = await loadShareGroupPolicy(input);\n if (input.stillCurrent?.() === false) return null;\n await advanceVerifiedSharePolicies(\n input.execSql,\n verifiedPrincipalPolicy,\n input.stillCurrent,\n );\n if (input.stillCurrent?.() === false) return null;\n\n const signedGrant = verifiedPrincipalPolicy.policy.grants.find(\n (grant) => grant.containerId === input.containerId,\n );\n if (!signedGrant || signedGrant.accessLevel !== input.accessLevel) {\n assertGrantMintNamed(input.expectedGroupName);\n return commitMissingGroupGrant(input);\n }\n\n const materializedPlan = await buildCurrentContainerSharePlan({\n accessLevel: input.accessLevel,\n author: input.author,\n eventId: input.eventId,\n execSql: input.execSql,\n knownContainerKeks: input.knownContainerKeks,\n principalPolicyCache: principalPolicyCacheForVerifiedPolicies(\n verifiedPrincipalPolicy.checkpointPolicies,\n ),\n previousProjection,\n recipient: {\n principalPolicy: verifiedPrincipalPolicy.policy,\n subjectId: input.recipientGroupId,\n subjectType: \"group\",\n },\n resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n if (!materializedPlan) return null;\n const result = await submitAcknowledgedContainerMutation({\n reportSecurityIncident: input.reportSecurityIncident,\n recitationPolicies: verifiedPrincipalPolicy.checkpointPolicies,\n apiClient: input.apiClient,\n author: input.author,\n containerKey: materializedPlan.containerKey,\n execSql: input.execSql,\n plan: materializedPlan.plan,\n stillCurrent: input.stillCurrent,\n submit: () =>\n submitPlainContainerMutation(() =>\n input.apiClient.shareContainer(\n input.containerId,\n materializedPlan.plan.request,\n {\n expectedPaymentRequiredOrganizationId: input.author.organizationId,\n },\n ),\n ),\n });\n if (!result) return null;\n\n // Keep the previously cached group epoch available until the old container\n // wrap has been unwrapped and the replacement has committed. Root has no\n // parent fallback, so caching the rotated policy any earlier destroys the\n // only local path to the KEK that must be re-wrapped.\n if (input.stillCurrent?.() !== false) {\n await savePrincipalPolicyBundle(\n input.execSql,\n verifiedPrincipalPolicy.bundle,\n new Date().toISOString(),\n input.author.organizationId,\n { stillCurrent: input.stillCurrent },\n );\n }\n if (input.stillCurrent?.() === false) return null;\n\n return result;\n}\n"]}
|
|
@@ -7,6 +7,7 @@ import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
|
|
|
7
7
|
import type { TrustedUserIdentityResolver } from "../../../data/trustedUserIdentity/index.js";
|
|
8
8
|
import { type GroupPolicyNameReader } from "../../organizations/principalPolicyRequest.js";
|
|
9
9
|
export interface ContainerManagedPrincipalShareApi extends ContainerShareApi, Pick<ApiClient, "evictContainerWriterProjection" | "getContainerWriterProjectionResult"> {
|
|
10
|
+
readonly recoverPendingPrincipalMutation?: ((organizationId: string) => Promise<void>) | undefined;
|
|
10
11
|
commitOrganizationGroupPolicy: (organizationId: string, groupId: string, input: CommitOrganizationGroupPolicyRequest) => Promise<CommitOrganizationGroupPolicyResponse | null>;
|
|
11
12
|
getCurrentPrincipalPolicy: (principalType: ManagedPrincipalKind, principalId: string) => Promise<PrincipalPolicyBundleResponse | null>;
|
|
12
13
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sharePrincipalPolicy.js","sourceRoot":"","sources":["sharePrincipalPolicy.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,GAKxB,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EAAE,uCAAuC,EAAE,MAAM,kDAAkD,CAAC;AAC3G,OAAO,EAAE,kCAAkC,EAAE,MAAM,8DAA8D,CAAC;AAClH,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AACtG,OAAO,EAAE,yBAAyB,EAAE,M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E,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IACH,OAAO;QACL,MAAM;QACN,kBAAkB;QAClB,iBAAiB,EAAE,qCAAqC,CACtD,uBAAuB,CACxB,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC;QAC9B,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,MAAM,EAAE,QAAQ,CAAC,KAAK;KACvB,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport {\n KeyingVerificationError,\n type ManagedPrincipalKind,\n type PrincipalPolicyCheckpoint,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { CommitOrganizationGroupPolicyRequest } from \"@tearleads/validators/request\";\nimport type {\n CommitOrganizationGroupPolicyResponse,\n PrincipalPolicyBundleResponse,\n} from \"@tearleads/validators/response\";\nimport type { ContainerShareApi } from \"../../../data/containers/shared/types\";\nimport { throwKeyingVerificationErrorWithContext } from \"../../../data/keyingProjectionVerification/error\";\nimport { advanceKeyingCheckpointsAtomically } from \"../../../data/persistence/keyingCheckpointAdvancePersistence\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../../data/persistence/keyingCheckpointPersistence\";\nimport { savePrincipalPolicyBundle } from \"../../../data/persistence/principalPolicyPersistence\";\nimport { loadPrincipalPolicyBundleForReference } from \"../../../data/persistence/principalPolicyReferencePersistence\";\nimport { retainVerifiedPrincipalPolicyBundle } from \"../../../data/persistence/verifiedPrincipalPolicyRetentionPersistence\";\nimport {\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport {\n principalPolicyReferenceFromBundle,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../../data/principals/principalPolicyAdminSigners\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport { assertGroupMetadataBinding } from \"../../organizations/groupMetadataBinding\";\nimport {\n type GroupPolicyNameReader,\n groupPolicyNameMismatch,\n} from \"../../organizations/principalPolicyRequest\";\nimport {\n externalAdminPolicyPersistenceEntries,\n loadOrganizationExternalAdminPolicy,\n type VerifiedExternalAdminPolicy,\n} from \"../../principals/externalAdminPolicy\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n type PrincipalPolicySignerPublicKeyLoadErrorCode,\n} from \"../../principals/policyVerification\";\n\nexport interface ContainerManagedPrincipalShareApi\n extends ContainerShareApi,\n Pick<\n ApiClient,\n \"evictContainerWriterProjection\" | \"getContainerWriterProjectionResult\"\n > {\n commitOrganizationGroupPolicy: (\n organizationId: string,\n groupId: string,\n input: CommitOrganizationGroupPolicyRequest,\n ) => Promise<CommitOrganizationGroupPolicyResponse | null>;\n getCurrentPrincipalPolicy: (\n principalType: ManagedPrincipalKind,\n principalId: string,\n ) => Promise<PrincipalPolicyBundleResponse | null>;\n}\n\nexport interface VerifiedSharePrincipalPolicy {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly checkpointPolicies: readonly VerifiedPrincipalPolicy[];\n readonly dependencyBundles: readonly PrincipalPolicyBundleResponse[];\n readonly organizationId: string;\n readonly policy: VerifiedPrincipalPolicy;\n}\n\nasync function retainVerifiedSharePolicies(input: {\n bundle: PrincipalPolicyBundleResponse;\n execSql: ExecSql;\n organizationId: string;\n organizationPolicy: VerifiedExternalAdminPolicy | null;\n policy: VerifiedPrincipalPolicy;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<VerifiedPrincipalPolicy[]> {\n const retainedAt = new Date().toISOString();\n if (input.organizationPolicy) {\n for (const entry of externalAdminPolicyPersistenceEntries(\n input.organizationPolicy,\n )) {\n await retainVerifiedPrincipalPolicyBundle({\n ...entry,\n execSql: input.execSql,\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n updatedAt: retainedAt,\n });\n }\n }\n await retainVerifiedPrincipalPolicyBundle({\n bundle: input.bundle,\n execSql: input.execSql,\n organizationId: input.organizationId,\n policy: input.policy,\n stillCurrent: input.stillCurrent,\n updatedAt: retainedAt,\n });\n return [\n ...(input.organizationPolicy\n ? externalAdminPolicyPersistenceEntries(input.organizationPolicy).map(\n (entry) => entry.policy,\n )\n : []),\n input.policy,\n ];\n}\n\n/**\n * Commits the verification a loadVerifiedGroupSharePrincipalPolicy call\n * deferred: advances the keying checkpoints for the verified policies and\n * caches the dependency bundles they were verified against.\n */\nexport async function advanceVerifiedSharePolicies(\n execSql: ExecSql,\n verified: Pick<\n VerifiedSharePrincipalPolicy,\n \"checkpointPolicies\" | \"dependencyBundles\" | \"organizationId\"\n >,\n stillCurrent?: (() => boolean) | undefined,\n): Promise<void> {\n await advanceKeyingCheckpointsAtomically({\n access: [],\n execSql,\n organizationId: verified.organizationId,\n policies: verified.checkpointPolicies,\n stillCurrent,\n });\n if (stillCurrent?.() === false) return;\n for (const bundle of verified.dependencyBundles) {\n await savePrincipalPolicyBundle(\n execSql,\n bundle,\n new Date().toISOString(),\n verified.organizationId,\n { stillCurrent },\n );\n if (stillCurrent?.() === false) return;\n }\n}\n\nfunction assertGroupPolicyTarget(\n bundle: PrincipalPolicyBundleResponse,\n groupId: string,\n): void {\n if (\n bundle.currentState.principalType !== \"group\" ||\n bundle.currentState.principalId !== groupId\n ) {\n throw new Error(\"Container share principal policy target mismatch\");\n }\n}\n\nfunction signerPublicKeyLoadErrorMessage(\n code: PrincipalPolicySignerPublicKeyLoadErrorCode,\n): string {\n switch (code) {\n case \"fingerprint-mismatch\":\n return \"principal policy signer key fingerprint mismatch\";\n case \"not-found\":\n return \"principal policy signer key could not be loaded\";\n }\n}\n\nasync function loadGroupSharePolicyBundle(input: {\n apiClient: ContainerManagedPrincipalShareApi;\n execSql: ExecSql;\n expectedGroupHead?: ReferencedPrincipalHead | undefined;\n groupId: string;\n localCheckpoint: PrincipalPolicyCheckpoint | null;\n}): Promise<PrincipalPolicyBundleResponse> {\n if (\n input.expectedGroupHead &&\n (input.expectedGroupHead.principalType !== \"group\" ||\n input.expectedGroupHead.principalId !== input.groupId)\n ) {\n throw new Error(\"Container share expected group policy target mismatch\");\n }\n const bundleFromCache = input.expectedGroupHead\n ? await loadPrincipalPolicyBundleForReference(\n input.execSql,\n input.expectedGroupHead,\n input.localCheckpoint,\n )\n : null;\n let bundle = bundleFromCache;\n bundle ??= await input.apiClient.getCurrentPrincipalPolicy(\n \"group\",\n input.groupId,\n );\n if (!bundle) {\n throw new Error(\"Container share principal policy could not be loaded\");\n }\n assertGroupPolicyTarget(bundle, input.groupId);\n if (\n input.expectedGroupHead &&\n !principalHeadMatchesReference(\n principalPolicyReferenceFromBundle(bundle),\n input.expectedGroupHead,\n )\n ) {\n throw new Error(\n \"Container share group policy does not match the signed organization directory\",\n );\n }\n return bundle;\n}\n\n/**\n * The chosen group label does not match the name in the group's verified\n * policy. A KeyingVerificationError (so it is reported as an incident), with\n * its own class so a caller can tell this refusal from every other\n * `object_mismatch` and say what happened.\n */\nexport class GroupShareNameMismatchError extends KeyingVerificationError {\n constructor(message: string) {\n super(\"object_mismatch\", message);\n this.name = \"GroupShareNameMismatchError\";\n }\n}\n\n/**\n * The share picker labels groups from the organization read model, which a\n * compromised server can relabel, so the name the user chose must equal the\n * name committed in the target's verified policy. Names compare by their\n * canonical key so look-alike spellings count as the same name. Uniqueness of\n * signed names within an organization is enforced where names enter — group\n * creation verifies every group in the signed directory — so a single\n * verified match identifies the group.\n */\nasync function assertShareGroupName(input: {\n readEncryptedName?: GroupPolicyNameReader | undefined;\n bundle: PrincipalPolicyBundleResponse;\n expectedGroupName: string;\n}): Promise<void> {\n // The label comes from the untrusted read model. Signed names never carry\n // an invisible code point, so a label that does is a look-alike that would\n // only match after canonicalization strips it; refuse it outright.\n const mismatch = await groupPolicyNameMismatch(\n input.bundle,\n input.expectedGroupName,\n input.readEncryptedName,\n );\n if (mismatch === \"forbidden_characters\") {\n throw new GroupShareNameMismatchError(\n \"Container share group name contains control or format characters\",\n );\n }\n if (mismatch === \"name_mismatch\") {\n throw new GroupShareNameMismatchError(\n \"Container share group name does not match the signed group policy\",\n );\n }\n}\n\nexport async function loadVerifiedGroupSharePrincipalPolicy(input: {\n readEncryptedName?: GroupPolicyNameReader | undefined;\n apiClient: ContainerManagedPrincipalShareApi;\n execSql: ExecSql;\n expectedGroupHead?: ReferencedPrincipalHead | undefined;\n /**\n * The display name the user chose the group by. The read model that labels\n * groups is a server projection; only the name committed in the signed\n * group payload can confirm the share lands on the group the user saw.\n */\n expectedGroupName?: string | undefined;\n groupId: string;\n organizationId: string;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<VerifiedSharePrincipalPolicy> {\n const organizationAdminPolicy = await loadOrganizationExternalAdminPolicy({\n execSql: input.execSql,\n getCurrentPrincipalPolicy: (principalType, principalId) =>\n input.apiClient.getCurrentPrincipalPolicy(principalType, principalId),\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n if (!organizationAdminPolicy) {\n throw new Error(\"Organization admin authority could not be verified\");\n }\n const committedGroupHead = requireOrganizationGroupHead(\n organizationAdminPolicy.descriptor,\n input.groupId,\n );\n if (\n input.expectedGroupHead &&\n !principalHeadMatchesReference(input.expectedGroupHead, committedGroupHead)\n ) {\n throw new Error(\n \"Container share expected group head conflicts with the signed organization directory\",\n );\n }\n const localCheckpoint = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n \"group\",\n input.groupId,\n );\n const bundle = await loadGroupSharePolicyBundle({\n ...input,\n expectedGroupHead: committedGroupHead,\n localCheckpoint,\n });\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n throw new Error(signerPublicKeyLoadErrorMessage(signerPublicKeys.error));\n }\n\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle,\n expectedReference: committedGroupHead,\n loadExternalAuthority: async () =>\n organizationAdminPolicy.externalAuthority,\n localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) {\n throwKeyingVerificationErrorWithContext(\n verified.error,\n \"Container share principal policy verification failed\",\n );\n }\n assertGroupMetadataBinding(bundle, organizationAdminPolicy.descriptor);\n if (input.expectedGroupName !== undefined) {\n await assertShareGroupName({\n readEncryptedName: input.readEncryptedName,\n bundle,\n expectedGroupName: input.expectedGroupName,\n });\n }\n\n const checkpointPolicies = await retainVerifiedSharePolicies({\n bundle,\n execSql: input.execSql,\n organizationId: input.organizationId,\n organizationPolicy: organizationAdminPolicy,\n policy: verified.value,\n stillCurrent: input.stillCurrent,\n });\n return {\n bundle,\n checkpointPolicies,\n dependencyBundles: externalAdminPolicyPersistenceEntries(\n organizationAdminPolicy,\n ).map((entry) => entry.bundle),\n organizationId: input.organizationId,\n policy: verified.value,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sharePrincipalPolicy.js","sourceRoot":"","sources":["sharePrincipalPolicy.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,GAKxB,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EAAE,uCAAuC,EAAE,MAAM,kDAAkD,CAAC;AAC3G,OAAO,EAAE,kCAAkC,EAAE,MAAM,8DAA8D,CAAC;AAClH,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AACtG,OAAO,EAAE,yBAAyB,EAAE,MAAM,sDAAsD,CAAC;AACjG,OAAO,EAAE,qCAAqC,EAAE,MAAM,+DAA+D,CAAC;AACtH,OAAO,EAAE,mCAAmC,EAAE,MAAM,uEAAuE,CAAC;AAC5H,OAAO,EACL,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,0DAA0D,CAAC;AAClE,OAAO,EACL,kCAAkC,EAClC,yDAAyD,GAC1D,MAAM,sDAAsD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,CAAC,KAAK;KACvB,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport {\n KeyingVerificationError,\n type ManagedPrincipalKind,\n type PrincipalPolicyCheckpoint,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { CommitOrganizationGroupPolicyRequest } from \"@tearleads/validators/request\";\nimport type {\n CommitOrganizationGroupPolicyResponse,\n PrincipalPolicyBundleResponse,\n} from \"@tearleads/validators/response\";\nimport type { ContainerShareApi } from \"../../../data/containers/shared/types\";\nimport { throwKeyingVerificationErrorWithContext } from \"../../../data/keyingProjectionVerification/error\";\nimport { advanceKeyingCheckpointsAtomically } from \"../../../data/persistence/keyingCheckpointAdvancePersistence\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../../data/persistence/keyingCheckpointPersistence\";\nimport { savePrincipalPolicyBundle } from \"../../../data/persistence/principalPolicyPersistence\";\nimport { loadPrincipalPolicyBundleForReference } from \"../../../data/persistence/principalPolicyReferencePersistence\";\nimport { retainVerifiedPrincipalPolicyBundle } from \"../../../data/persistence/verifiedPrincipalPolicyRetentionPersistence\";\nimport {\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport {\n principalPolicyReferenceFromBundle,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../../data/principals/principalPolicyAdminSigners\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport { assertGroupMetadataBinding } from \"../../organizations/groupMetadataBinding\";\nimport {\n type GroupPolicyNameReader,\n groupPolicyNameMismatch,\n} from \"../../organizations/principalPolicyRequest\";\nimport {\n externalAdminPolicyPersistenceEntries,\n loadOrganizationExternalAdminPolicy,\n type VerifiedExternalAdminPolicy,\n} from \"../../principals/externalAdminPolicy\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n type PrincipalPolicySignerPublicKeyLoadErrorCode,\n} from \"../../principals/policyVerification\";\n\nexport interface ContainerManagedPrincipalShareApi\n extends ContainerShareApi,\n Pick<\n ApiClient,\n \"evictContainerWriterProjection\" | \"getContainerWriterProjectionResult\"\n > {\n readonly recoverPendingPrincipalMutation?:\n | ((organizationId: string) => Promise<void>)\n | undefined;\n commitOrganizationGroupPolicy: (\n organizationId: string,\n groupId: string,\n input: CommitOrganizationGroupPolicyRequest,\n ) => Promise<CommitOrganizationGroupPolicyResponse | null>;\n getCurrentPrincipalPolicy: (\n principalType: ManagedPrincipalKind,\n principalId: string,\n ) => Promise<PrincipalPolicyBundleResponse | null>;\n}\n\nexport interface VerifiedSharePrincipalPolicy {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly checkpointPolicies: readonly VerifiedPrincipalPolicy[];\n readonly dependencyBundles: readonly PrincipalPolicyBundleResponse[];\n readonly organizationId: string;\n readonly policy: VerifiedPrincipalPolicy;\n}\n\nasync function retainVerifiedSharePolicies(input: {\n bundle: PrincipalPolicyBundleResponse;\n execSql: ExecSql;\n organizationId: string;\n organizationPolicy: VerifiedExternalAdminPolicy | null;\n policy: VerifiedPrincipalPolicy;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<VerifiedPrincipalPolicy[]> {\n const retainedAt = new Date().toISOString();\n if (input.organizationPolicy) {\n for (const entry of externalAdminPolicyPersistenceEntries(\n input.organizationPolicy,\n )) {\n await retainVerifiedPrincipalPolicyBundle({\n ...entry,\n execSql: input.execSql,\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n updatedAt: retainedAt,\n });\n }\n }\n await retainVerifiedPrincipalPolicyBundle({\n bundle: input.bundle,\n execSql: input.execSql,\n organizationId: input.organizationId,\n policy: input.policy,\n stillCurrent: input.stillCurrent,\n updatedAt: retainedAt,\n });\n return [\n ...(input.organizationPolicy\n ? externalAdminPolicyPersistenceEntries(input.organizationPolicy).map(\n (entry) => entry.policy,\n )\n : []),\n input.policy,\n ];\n}\n\n/**\n * Commits the verification a loadVerifiedGroupSharePrincipalPolicy call\n * deferred: advances the keying checkpoints for the verified policies and\n * caches the dependency bundles they were verified against.\n */\nexport async function advanceVerifiedSharePolicies(\n execSql: ExecSql,\n verified: Pick<\n VerifiedSharePrincipalPolicy,\n \"checkpointPolicies\" | \"dependencyBundles\" | \"organizationId\"\n >,\n stillCurrent?: (() => boolean) | undefined,\n): Promise<void> {\n await advanceKeyingCheckpointsAtomically({\n access: [],\n execSql,\n organizationId: verified.organizationId,\n policies: verified.checkpointPolicies,\n stillCurrent,\n });\n if (stillCurrent?.() === false) return;\n for (const bundle of verified.dependencyBundles) {\n await savePrincipalPolicyBundle(\n execSql,\n bundle,\n new Date().toISOString(),\n verified.organizationId,\n { stillCurrent },\n );\n if (stillCurrent?.() === false) return;\n }\n}\n\nfunction assertGroupPolicyTarget(\n bundle: PrincipalPolicyBundleResponse,\n groupId: string,\n): void {\n if (\n bundle.currentState.principalType !== \"group\" ||\n bundle.currentState.principalId !== groupId\n ) {\n throw new Error(\"Container share principal policy target mismatch\");\n }\n}\n\nfunction signerPublicKeyLoadErrorMessage(\n code: PrincipalPolicySignerPublicKeyLoadErrorCode,\n): string {\n switch (code) {\n case \"fingerprint-mismatch\":\n return \"principal policy signer key fingerprint mismatch\";\n case \"not-found\":\n return \"principal policy signer key could not be loaded\";\n }\n}\n\nasync function loadGroupSharePolicyBundle(input: {\n apiClient: ContainerManagedPrincipalShareApi;\n execSql: ExecSql;\n expectedGroupHead?: ReferencedPrincipalHead | undefined;\n groupId: string;\n localCheckpoint: PrincipalPolicyCheckpoint | null;\n}): Promise<PrincipalPolicyBundleResponse> {\n if (\n input.expectedGroupHead &&\n (input.expectedGroupHead.principalType !== \"group\" ||\n input.expectedGroupHead.principalId !== input.groupId)\n ) {\n throw new Error(\"Container share expected group policy target mismatch\");\n }\n const bundleFromCache = input.expectedGroupHead\n ? await loadPrincipalPolicyBundleForReference(\n input.execSql,\n input.expectedGroupHead,\n input.localCheckpoint,\n )\n : null;\n let bundle = bundleFromCache;\n bundle ??= await input.apiClient.getCurrentPrincipalPolicy(\n \"group\",\n input.groupId,\n );\n if (!bundle) {\n throw new Error(\"Container share principal policy could not be loaded\");\n }\n assertGroupPolicyTarget(bundle, input.groupId);\n if (\n input.expectedGroupHead &&\n !principalHeadMatchesReference(\n principalPolicyReferenceFromBundle(bundle),\n input.expectedGroupHead,\n )\n ) {\n throw new Error(\n \"Container share group policy does not match the signed organization directory\",\n );\n }\n return bundle;\n}\n\n/**\n * The chosen group label does not match the name in the group's verified\n * policy. A KeyingVerificationError (so it is reported as an incident), with\n * its own class so a caller can tell this refusal from every other\n * `object_mismatch` and say what happened.\n */\nexport class GroupShareNameMismatchError extends KeyingVerificationError {\n constructor(message: string) {\n super(\"object_mismatch\", message);\n this.name = \"GroupShareNameMismatchError\";\n }\n}\n\n/**\n * The share picker labels groups from the organization read model, which a\n * compromised server can relabel, so the name the user chose must equal the\n * name committed in the target's verified policy. Names compare by their\n * canonical key so look-alike spellings count as the same name. Uniqueness of\n * signed names within an organization is enforced where names enter — group\n * creation verifies every group in the signed directory — so a single\n * verified match identifies the group.\n */\nasync function assertShareGroupName(input: {\n readEncryptedName?: GroupPolicyNameReader | undefined;\n bundle: PrincipalPolicyBundleResponse;\n expectedGroupName: string;\n}): Promise<void> {\n // The label comes from the untrusted read model. Signed names never carry\n // an invisible code point, so a label that does is a look-alike that would\n // only match after canonicalization strips it; refuse it outright.\n const mismatch = await groupPolicyNameMismatch(\n input.bundle,\n input.expectedGroupName,\n input.readEncryptedName,\n );\n if (mismatch === \"forbidden_characters\") {\n throw new GroupShareNameMismatchError(\n \"Container share group name contains control or format characters\",\n );\n }\n if (mismatch === \"name_mismatch\") {\n throw new GroupShareNameMismatchError(\n \"Container share group name does not match the signed group policy\",\n );\n }\n}\n\nexport async function loadVerifiedGroupSharePrincipalPolicy(input: {\n readEncryptedName?: GroupPolicyNameReader | undefined;\n apiClient: ContainerManagedPrincipalShareApi;\n execSql: ExecSql;\n expectedGroupHead?: ReferencedPrincipalHead | undefined;\n /**\n * The display name the user chose the group by. The read model that labels\n * groups is a server projection; only the name committed in the signed\n * group payload can confirm the share lands on the group the user saw.\n */\n expectedGroupName?: string | undefined;\n groupId: string;\n organizationId: string;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<VerifiedSharePrincipalPolicy> {\n const organizationAdminPolicy = await loadOrganizationExternalAdminPolicy({\n execSql: input.execSql,\n getCurrentPrincipalPolicy: (principalType, principalId) =>\n input.apiClient.getCurrentPrincipalPolicy(principalType, principalId),\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n if (!organizationAdminPolicy) {\n throw new Error(\"Organization admin authority could not be verified\");\n }\n const committedGroupHead = requireOrganizationGroupHead(\n organizationAdminPolicy.descriptor,\n input.groupId,\n );\n if (\n input.expectedGroupHead &&\n !principalHeadMatchesReference(input.expectedGroupHead, committedGroupHead)\n ) {\n throw new Error(\n \"Container share expected group head conflicts with the signed organization directory\",\n );\n }\n const localCheckpoint = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n \"group\",\n input.groupId,\n );\n const bundle = await loadGroupSharePolicyBundle({\n ...input,\n expectedGroupHead: committedGroupHead,\n localCheckpoint,\n });\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n throw new Error(signerPublicKeyLoadErrorMessage(signerPublicKeys.error));\n }\n\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle,\n expectedReference: committedGroupHead,\n loadExternalAuthority: async () =>\n organizationAdminPolicy.externalAuthority,\n localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) {\n throwKeyingVerificationErrorWithContext(\n verified.error,\n \"Container share principal policy verification failed\",\n );\n }\n assertGroupMetadataBinding(bundle, organizationAdminPolicy.descriptor);\n if (input.expectedGroupName !== undefined) {\n await assertShareGroupName({\n readEncryptedName: input.readEncryptedName,\n bundle,\n expectedGroupName: input.expectedGroupName,\n });\n }\n\n const checkpointPolicies = await retainVerifiedSharePolicies({\n bundle,\n execSql: input.execSql,\n organizationId: input.organizationId,\n organizationPolicy: organizationAdminPolicy,\n policy: verified.value,\n stillCurrent: input.stillCurrent,\n });\n return {\n bundle,\n checkpointPolicies,\n dependencyBundles: externalAdminPolicyPersistenceEntries(\n organizationAdminPolicy,\n ).map((entry) => entry.bundle),\n organizationId: input.organizationId,\n policy: verified.value,\n };\n}\n"]}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { KeyingVerificationError } from "../../internal/crypto/index.js";
|
|
2
|
+
import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, } from "../../data/principals/organizationAuthorityDescriptor.js";
|
|
3
|
+
/** Couple supplied group receipts to the directory acknowledged in the same batch. */
|
|
4
|
+
export function assertAcknowledgedDirectoryBindings(organizationId, receipts) {
|
|
5
|
+
const directories = receipts.filter((receipt) => receipt.currentState.principalType === "organization");
|
|
6
|
+
if (directories.length === 0 &&
|
|
7
|
+
receipts.some((receipt) => receipt.currentState.principalType === "group"))
|
|
8
|
+
throw new KeyingVerificationError("missing_dependency", "Acknowledged groups require their organization directory");
|
|
9
|
+
for (const directory of directories) {
|
|
10
|
+
const descriptor = parseOrganizationAuthorityDescriptor(directory.currentPayload.ciphertext);
|
|
11
|
+
if (directory.currentState.principalId !== organizationId ||
|
|
12
|
+
descriptor.organizationId !== organizationId ||
|
|
13
|
+
receipts.some(({ currentState }) => currentState.principalType === "group" &&
|
|
14
|
+
!descriptor.groupHeads.some((head) => principalHeadMatchesReference(head, currentState))))
|
|
15
|
+
throw new KeyingVerificationError("object_mismatch", "Acknowledged organization does not bind its group receipt");
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
//# sourceMappingURL=acknowledgedDirectoryBindings.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"acknowledgedDirectoryBindings.js","sourceRoot":"","sources":["acknowledgedDirectoryBindings.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,OAAO,EACL,oCAAoC,EACpC,6BAA6B,GAC9B,MAAM,uDAAuD,CAAC;AAE/D,sFAAsF;AACtF,MAAM,UAAU,mCAAmC,CACjD,cAAsB,EACtB,QAAoD;IAEpD,MAAM,WAAW,GAAG,QAAQ,CAAC,MAAM,CACjC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,YAAY,CAAC,aAAa,KAAK,cAAc,CACnE,CAAC;IACF,IACE,WAAW,CAAC,MAAM,KAAK,CAAC;QACxB,QAAQ,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,YAAY,CAAC,aAAa,KAAK,OAAO,CAAC;QAE1E,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,0DAA0D,CAC3D,CAAC;IACJ,KAAK,MAAM,SAAS,IAAI,WAAW,EAAE,CAAC;QACpC,MAAM,UAAU,GAAG,oCAAoC,CACrD,SAAS,CAAC,cAAc,CAAC,UAAU,CACpC,CAAC;QACF,IACE,SAAS,CAAC,YAAY,CAAC,WAAW,KAAK,cAAc;YACrD,UAAU,CAAC,cAAc,KAAK,cAAc;YAC5C,QAAQ,CAAC,IAAI,CACX,CAAC,EAAE,YAAY,EAAE,EAAE,EAAE,CACnB,YAAY,CAAC,aAAa,KAAK,OAAO;gBACtC,CAAC,UAAU,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CACnC,6BAA6B,CAAC,IAAI,EAAE,YAAY,CAAC,CAClD,CACJ;YAED,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,2DAA2D,CAC5D,CAAC;IACN,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyMutationResponse } from \"@tearleads/validators/response\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../data/principals/organizationAuthorityDescriptor\";\n\n/** Couple supplied group receipts to the directory acknowledged in the same batch. */\nexport function assertAcknowledgedDirectoryBindings(\n organizationId: string,\n receipts: readonly PrincipalPolicyMutationResponse[],\n) {\n const directories = receipts.filter(\n (receipt) => receipt.currentState.principalType === \"organization\",\n );\n if (\n directories.length === 0 &&\n receipts.some((receipt) => receipt.currentState.principalType === \"group\")\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Acknowledged groups require their organization directory\",\n );\n for (const directory of directories) {\n const descriptor = parseOrganizationAuthorityDescriptor(\n directory.currentPayload.ciphertext,\n );\n if (\n directory.currentState.principalId !== organizationId ||\n descriptor.organizationId !== organizationId ||\n receipts.some(\n ({ currentState }) =>\n currentState.principalType === \"group\" &&\n !descriptor.groupHeads.some((head) =>\n principalHeadMatchesReference(head, currentState),\n ),\n )\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Acknowledged organization does not bind its group receipt\",\n );\n }\n}\n"]}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { assertProjectionVerificationCurrent } from "../../data/keyingProjectionVerification/types.js";
|
|
2
|
+
import { prepareAuthoredGroupPolicy } from "./groupPolicyMutationAcknowledgement.js";
|
|
3
|
+
import { submitGroupPolicyCommit, } from "./groupPolicyMutationContext.js";
|
|
4
|
+
import { groupPolicyMutationHead } from "./groupPolicyMutationHead.js";
|
|
5
|
+
import { buildOrganizationGroupDirectoryPolicyRequest, replaceOrganizationGroupHead, } from "./organizationGroupDirectory.js";
|
|
6
|
+
import { projectionUserIds, resolveRequiredUserIdentities, } from "./trustedOrganizationUsers.js";
|
|
7
|
+
/** Commit and retain one exact compound successor without rebuilding full history. */
|
|
8
|
+
export async function commitCurrentGroupPolicyMutation(input) {
|
|
9
|
+
const { context } = input;
|
|
10
|
+
assertProjectionVerificationCurrent(context.stillCurrent);
|
|
11
|
+
const [signer] = await resolveRequiredUserIdentities({
|
|
12
|
+
resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,
|
|
13
|
+
userIds: [input.signerUserId],
|
|
14
|
+
});
|
|
15
|
+
if (!signer)
|
|
16
|
+
throw new Error("Group policy signer is unavailable");
|
|
17
|
+
const expectedHead = await groupPolicyMutationHead(input.request);
|
|
18
|
+
const nextPolicy = await prepareAuthoredGroupPolicy({
|
|
19
|
+
verifiedCurrentPolicy: context.verifiedCurrentPolicy,
|
|
20
|
+
expectedHead,
|
|
21
|
+
request: input.request,
|
|
22
|
+
signerPublicKeys: [signer],
|
|
23
|
+
externalAuthority: context.externalAuthority,
|
|
24
|
+
localPolicyCheckpoint: context.localPolicyCheckpoint,
|
|
25
|
+
stillCurrent: context.stillCurrent,
|
|
26
|
+
});
|
|
27
|
+
const prepared = await input.prepareContainerMutations(nextPolicy);
|
|
28
|
+
input.request.containerMutations = [...prepared.requests];
|
|
29
|
+
const adminProjection = context.isOrganizationAdminsGroup
|
|
30
|
+
? input.request.projection
|
|
31
|
+
: context.adminCurrent.current.currentProjection;
|
|
32
|
+
const adminUsers = await resolveRequiredUserIdentities({
|
|
33
|
+
resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,
|
|
34
|
+
userIds: projectionUserIds(adminProjection),
|
|
35
|
+
});
|
|
36
|
+
const organizationRequest = await buildOrganizationGroupDirectoryPolicyRequest({
|
|
37
|
+
adminProjection,
|
|
38
|
+
adminUsers,
|
|
39
|
+
currentPolicy: context.organizationCurrent.current,
|
|
40
|
+
descriptor: context.organizationDescriptor,
|
|
41
|
+
groupHeads: replaceOrganizationGroupHead({
|
|
42
|
+
descriptor: context.organizationDescriptor,
|
|
43
|
+
nextHead: expectedHead,
|
|
44
|
+
}),
|
|
45
|
+
signerUserId: input.signerUserId,
|
|
46
|
+
signingFingerprint: input.signingFingerprint,
|
|
47
|
+
signingKeyPair: input.signingKeyPair,
|
|
48
|
+
});
|
|
49
|
+
assertProjectionVerificationCurrent(context.stillCurrent);
|
|
50
|
+
const response = await submitGroupPolicyCommit({
|
|
51
|
+
apiClient: input.apiClient,
|
|
52
|
+
groupId: input.groupId,
|
|
53
|
+
organizationId: input.organizationId,
|
|
54
|
+
request: input.request,
|
|
55
|
+
organizationRequest,
|
|
56
|
+
carryDescendantRekeys: prepared.carry,
|
|
57
|
+
stillCurrent: context.stillCurrent,
|
|
58
|
+
});
|
|
59
|
+
if (!response)
|
|
60
|
+
throw new Error("Group policy update failed");
|
|
61
|
+
assertProjectionVerificationCurrent(context.stillCurrent);
|
|
62
|
+
await context.retainAcknowledged({
|
|
63
|
+
request: input.request,
|
|
64
|
+
organizationRequest,
|
|
65
|
+
response,
|
|
66
|
+
retiredContainerIds: prepared.retiredContainerIds,
|
|
67
|
+
});
|
|
68
|
+
await prepared.acknowledge(response.groupPolicy.containerMutations, context.stillCurrent);
|
|
69
|
+
assertProjectionVerificationCurrent(context.stillCurrent);
|
|
70
|
+
return response.groupPolicy;
|
|
71
|
+
}
|
|
72
|
+
//# sourceMappingURL=commitCurrentGroupPolicyMutation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"commitCurrentGroupPolicyMutation.js","sourceRoot":"","sources":["commitCurrentGroupPolicyMutation.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AAEpG,OAAO,EAAE,0BAA0B,EAAE,MAAM,sCAAsC,CAAC;AAClF,OAAO,EAEL,uBAAuB,GACxB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EACL,4CAA4C,EAC5C,4BAA4B,GAC7B,MAAM,8BAA8B,CAAC;AAGtC,OAAO,EACL,iBAAiB,EACjB,6BAA6B,GAC9B,MAAM,4BAA4B,CAA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;IAC1D,OAAO,QAAQ,CAAC,WAAW,CAAC;AAC9B,CAAC","sourcesContent":["import type {\n SigningKeyPair,\n VerifiedPrincipalPolicyCurrent,\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 type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport { prepareAuthoredGroupPolicy } from \"./groupPolicyMutationAcknowledgement\";\nimport {\n type PrincipalPolicyReadWriteApi,\n submitGroupPolicyCommit,\n} from \"./groupPolicyMutationContext\";\nimport { groupPolicyMutationHead } from \"./groupPolicyMutationHead\";\nimport {\n buildOrganizationGroupDirectoryPolicyRequest,\n replaceOrganizationGroupHead,\n} from \"./organizationGroupDirectory\";\nimport type { PreparedPrincipalContainerRematerializationBatch } from \"./principalContainerRematerialization\";\nimport type { RuntimeCurrentGroupMutationContext } from \"./runtimeCurrentGroupMutation\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"./trustedOrganizationUsers\";\n\n/** Commit and retain one exact compound successor without rebuilding full history. */\nexport async function commitCurrentGroupPolicyMutation(input: {\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly context: RuntimeCurrentGroupMutationContext;\n readonly groupId: string;\n readonly organizationId: string;\n readonly request: PutPrincipalPolicyRequest;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly prepareContainerMutations: (\n nextPolicy: VerifiedPrincipalPolicyCurrent,\n ) => Promise<PreparedPrincipalContainerRematerializationBatch>;\n}): Promise<PrincipalPolicyMutationResponse> {\n const { context } = input;\n assertProjectionVerificationCurrent(context.stillCurrent);\n const [signer] = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: [input.signerUserId],\n });\n if (!signer) throw new Error(\"Group policy signer is unavailable\");\n const expectedHead = await groupPolicyMutationHead(input.request);\n const nextPolicy = await prepareAuthoredGroupPolicy({\n verifiedCurrentPolicy: context.verifiedCurrentPolicy,\n expectedHead,\n request: input.request,\n signerPublicKeys: [signer],\n externalAuthority: context.externalAuthority,\n localPolicyCheckpoint: context.localPolicyCheckpoint,\n stillCurrent: context.stillCurrent,\n });\n const prepared = await input.prepareContainerMutations(nextPolicy);\n input.request.containerMutations = [...prepared.requests];\n const adminProjection = context.isOrganizationAdminsGroup\n ? input.request.projection\n : context.adminCurrent.current.currentProjection;\n const adminUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(adminProjection),\n });\n const organizationRequest =\n await buildOrganizationGroupDirectoryPolicyRequest({\n adminProjection,\n adminUsers,\n currentPolicy: context.organizationCurrent.current,\n descriptor: context.organizationDescriptor,\n groupHeads: replaceOrganizationGroupHead({\n descriptor: context.organizationDescriptor,\n nextHead: expectedHead,\n }),\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n assertProjectionVerificationCurrent(context.stillCurrent);\n const response = await submitGroupPolicyCommit({\n apiClient: input.apiClient,\n groupId: input.groupId,\n organizationId: input.organizationId,\n request: input.request,\n organizationRequest,\n carryDescendantRekeys: prepared.carry,\n stillCurrent: context.stillCurrent,\n });\n if (!response) throw new Error(\"Group policy update failed\");\n assertProjectionVerificationCurrent(context.stillCurrent);\n await context.retainAcknowledged({\n request: input.request,\n organizationRequest,\n response,\n retiredContainerIds: prepared.retiredContainerIds,\n });\n await prepared.acknowledge(\n response.groupPolicy.containerMutations,\n context.stillCurrent,\n );\n assertProjectionVerificationCurrent(context.stillCurrent);\n return response.groupPolicy;\n}\n"]}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { assertProjectionVerificationCurrent } from "../../data/keyingProjectionVerification/types.js";
|
|
2
|
+
import { advanceKeyingCheckpointsAtomically } from "../../data/persistence/keyingCheckpointAdvancePersistence.js";
|
|
3
|
+
import { principalPolicyReferenceFromBundle } from "../../data/principals/principalPolicyAdminSigners.js";
|
|
4
|
+
import { assertGroupMetadataBinding } from "./groupMetadataBinding.js";
|
|
5
|
+
import { readDirectoryGroupName } from "./groupNameUniqueness.js";
|
|
6
|
+
import { acknowledgeInitialGroupPolicy } from "./groupPolicyMutationAcknowledgement.js";
|
|
7
|
+
import { groupPolicyMutationHead } from "./groupPolicyMutationHead.js";
|
|
8
|
+
import { buildOrganizationGroupDirectoryPolicyRequest, replaceOrganizationGroupHead, } from "./organizationGroupDirectory.js";
|
|
9
|
+
import { buildInitialGroupPolicyRequest, canonicalGroupNameKey, } from "./principalPolicyRequest.js";
|
|
10
|
+
import { projectionUserIds, resolveRequiredUserIdentities, } from "./trustedOrganizationUsers.js";
|
|
11
|
+
/** Create from bounded current evidence and publish its genuine genesis with the directory. */
|
|
12
|
+
export async function createCurrentOrganizationGroup(input) {
|
|
13
|
+
const { context } = input;
|
|
14
|
+
assertProjectionVerificationCurrent(context.stillCurrent);
|
|
15
|
+
const nameKey = canonicalGroupNameKey(input.name);
|
|
16
|
+
// Each current recovery is queued by organization. Retain verified heads one
|
|
17
|
+
// at a time so the walk stays bounded without collecting full group histories.
|
|
18
|
+
for (const head of context.descriptor.groupHeads) {
|
|
19
|
+
const group = await context.readGroup(head.principalId);
|
|
20
|
+
const stillCurrent = () => context.stillCurrent() && group.stillCurrent();
|
|
21
|
+
assertProjectionVerificationCurrent(stillCurrent);
|
|
22
|
+
assertGroupMetadataBinding(group.current, context.descriptor);
|
|
23
|
+
const name = await readDirectoryGroupName({ ...input, readEncryptedName: input.metadataAccess.readName }, group.current);
|
|
24
|
+
// Remember independently verified heads even if uniqueness or dispatch
|
|
25
|
+
// later fails; these are observed policies, never speculative successors.
|
|
26
|
+
await advanceKeyingCheckpointsAtomically({
|
|
27
|
+
execSql: input.execSql,
|
|
28
|
+
organizationId: input.organizationId,
|
|
29
|
+
access: [],
|
|
30
|
+
policies: [...group.dependencies, group.policy],
|
|
31
|
+
stillCurrent,
|
|
32
|
+
});
|
|
33
|
+
if (name !== null && canonicalGroupNameKey(name) === nameKey)
|
|
34
|
+
throw new Error("Another signed group in this organization already carries this name");
|
|
35
|
+
}
|
|
36
|
+
const request = await buildInitialGroupPolicyRequest({
|
|
37
|
+
...input,
|
|
38
|
+
groupId: crypto.randomUUID(),
|
|
39
|
+
includeSignerAsAdmin: false,
|
|
40
|
+
externalAuthority: {
|
|
41
|
+
...principalPolicyReferenceFromBundle(context.admins.current),
|
|
42
|
+
principalType: "group",
|
|
43
|
+
},
|
|
44
|
+
metadataKey: await input.metadataAccess.loadEncryptionKey(),
|
|
45
|
+
});
|
|
46
|
+
const head = await groupPolicyMutationHead(request.initialGroupPolicy);
|
|
47
|
+
const adminProjection = context.admins.policy.projection;
|
|
48
|
+
const organizationRequest = await buildOrganizationGroupDirectoryPolicyRequest({
|
|
49
|
+
...input,
|
|
50
|
+
currentPolicy: context.directory.current,
|
|
51
|
+
descriptor: context.descriptor,
|
|
52
|
+
groupHeads: replaceOrganizationGroupHead({
|
|
53
|
+
descriptor: context.descriptor,
|
|
54
|
+
nextHead: head,
|
|
55
|
+
}),
|
|
56
|
+
adminProjection,
|
|
57
|
+
adminUsers: await resolveRequiredUserIdentities({
|
|
58
|
+
resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,
|
|
59
|
+
userIds: projectionUserIds(adminProjection),
|
|
60
|
+
}),
|
|
61
|
+
});
|
|
62
|
+
assertProjectionVerificationCurrent(context.stillCurrent);
|
|
63
|
+
const stored = await input.apiClient.createOrganizationGroup(input.organizationId, { ...request, organizationPolicy: organizationRequest });
|
|
64
|
+
assertProjectionVerificationCurrent(context.stillCurrent);
|
|
65
|
+
if (!stored)
|
|
66
|
+
throw new Error("Group could not be created");
|
|
67
|
+
// Genesis really has one signed state. Reconstruct only the exact authored
|
|
68
|
+
// artifacts whose commitments match the summary, then verify them privately.
|
|
69
|
+
const { bundle } = await acknowledgeInitialGroupPolicy({
|
|
70
|
+
organizationId: input.organizationId,
|
|
71
|
+
request,
|
|
72
|
+
response: stored.group,
|
|
73
|
+
stateHash: head.stateHash,
|
|
74
|
+
});
|
|
75
|
+
const { previousStates: _previousStates, ...current } = bundle;
|
|
76
|
+
await context.retainCreatedGroup({
|
|
77
|
+
request: request.initialGroupPolicy,
|
|
78
|
+
response: { ...current, containerMutations: [] },
|
|
79
|
+
organizationRequest,
|
|
80
|
+
organizationResponse: stored.organizationPolicy,
|
|
81
|
+
});
|
|
82
|
+
assertProjectionVerificationCurrent(context.stillCurrent);
|
|
83
|
+
return { ...stored.group, name: input.name.trim(), nameUnreadable: false };
|
|
84
|
+
}
|
|
85
|
+
//# sourceMappingURL=createCurrentOrganizationGroup.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"createCurrentOrganizationGroup.js","sourceRoot":"","sources":["createCurrentOrganizationGroup.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,kCAAkC,EAAE,MAAM,2DAA2D,CAAC;AAC/G,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AAKvG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wBAAwB,CAAC;AACpE,OAAO,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAC/D,OAAO,EAAE,6BAA6B,EAAE,MAAM,sCAAsC,CAAC;AAErF,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EACL,4CAA4C,EAC5C,4BAA4B,GAC7B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,8BAA8B,EAC9B,qBAAqB,GACtB,MAAM,0BAA0B,CAAC;AAGlC,OAAO,EACL,iBAAiB,EACjB,6BAA6B,GAC9B,MAAM,4BAA4B,CAA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,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,6BAA6B,CAAC;QACrD,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,OAAO;QACP,QAAQ,EAAE,MAAM,CAAC,KAAK;QACtB,SAAS,EAAE,IAAI,CAAC,SAAS;KAC1B,CAAC,CAAC;IACH,MAAM,EAAE,cAAc,EAAE,eAAe,EAAE,GAAG,OAAO,EAAE,GAAG,MAAM,CAAC;IAC/D,MAAM,OAAO,CAAC,kBAAkB,CAAC;QAC/B,OAAO,EAAE,OAAO,CAAC,kBAAkB;QACnC,QAAQ,EAAE,EAAE,GAAG,OAAO,EAAE,kBAAkB,EAAE,EAAE,EAAE;QAChD,mBAAmB;QACnB,oBAAoB,EAAE,MAAM,CAAC,kBAAkB;KAChD,CAAC,CAAC;IACH,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;IAC1D,OAAO,EAAE,GAAG,MAAM,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI,EAAE,EAAE,cAAc,EAAE,KAAK,EAAE,CAAC;AAC7E,CAAC","sourcesContent":["import type { EncapsulationKeyPair, SigningKeyPair } from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { advanceKeyingCheckpointsAtomically } from \"../../data/persistence/keyingCheckpointAdvancePersistence\";\nimport { principalPolicyReferenceFromBundle } from \"../../data/principals/principalPolicyAdminSigners\";\nimport type { SecurityIncidentReporter } from \"../../data/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport type { createGroupMetadataAccess } from \"./groupMetadataAccess\";\nimport { assertGroupMetadataBinding } from \"./groupMetadataBinding\";\nimport { readDirectoryGroupName } from \"./groupNameUniqueness\";\nimport { acknowledgeInitialGroupPolicy } from \"./groupPolicyMutationAcknowledgement\";\nimport type { OrganizationPrincipalPolicyApi } from \"./groupPolicyMutationContext\";\nimport { groupPolicyMutationHead } from \"./groupPolicyMutationHead\";\nimport {\n buildOrganizationGroupDirectoryPolicyRequest,\n replaceOrganizationGroupHead,\n} from \"./organizationGroupDirectory\";\nimport {\n buildInitialGroupPolicyRequest,\n canonicalGroupNameKey,\n} from \"./principalPolicyRequest\";\nimport type { OrganizationGroupSummary } from \"./readModel\";\nimport type { CurrentOrganizationMutationContext } from \"./runtimeCurrentOrganizationMutation\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"./trustedOrganizationUsers\";\n\n/** Create from bounded current evidence and publish its genuine genesis with the directory. */\nexport async function createCurrentOrganizationGroup(input: {\n readonly apiClient: Pick<\n OrganizationPrincipalPolicyApi,\n \"createOrganizationGroup\"\n >;\n readonly context: CurrentOrganizationMutationContext;\n readonly creatorEncapsulationKeyPair: EncapsulationKeyPair;\n readonly execSql: ExecSql;\n readonly metadataAccess: ReturnType<typeof createGroupMetadataAccess>;\n readonly name: string;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<OrganizationGroupSummary> {\n const { context } = input;\n assertProjectionVerificationCurrent(context.stillCurrent);\n const nameKey = canonicalGroupNameKey(input.name);\n // Each current recovery is queued by organization. Retain verified heads one\n // at a time so the walk stays bounded without collecting full group histories.\n for (const head of context.descriptor.groupHeads) {\n const group = await context.readGroup(head.principalId);\n const stillCurrent = () => context.stillCurrent() && group.stillCurrent();\n assertProjectionVerificationCurrent(stillCurrent);\n assertGroupMetadataBinding(group.current, context.descriptor);\n const name = await readDirectoryGroupName(\n { ...input, readEncryptedName: input.metadataAccess.readName },\n group.current,\n );\n // Remember independently verified heads even if uniqueness or dispatch\n // later fails; these are observed policies, never speculative successors.\n await advanceKeyingCheckpointsAtomically({\n execSql: input.execSql,\n organizationId: input.organizationId,\n access: [],\n policies: [...group.dependencies, group.policy],\n stillCurrent,\n });\n if (name !== null && canonicalGroupNameKey(name) === nameKey)\n throw new Error(\n \"Another signed group in this organization already carries this name\",\n );\n }\n const request = await buildInitialGroupPolicyRequest({\n ...input,\n groupId: crypto.randomUUID(),\n includeSignerAsAdmin: false,\n externalAuthority: {\n ...principalPolicyReferenceFromBundle(context.admins.current),\n principalType: \"group\",\n },\n metadataKey: await input.metadataAccess.loadEncryptionKey(),\n });\n const head = await groupPolicyMutationHead(request.initialGroupPolicy);\n const adminProjection = context.admins.policy.projection;\n const organizationRequest =\n await buildOrganizationGroupDirectoryPolicyRequest({\n ...input,\n currentPolicy: context.directory.current,\n descriptor: context.descriptor,\n groupHeads: replaceOrganizationGroupHead({\n descriptor: context.descriptor,\n nextHead: head,\n }),\n adminProjection,\n adminUsers: await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(adminProjection),\n }),\n });\n assertProjectionVerificationCurrent(context.stillCurrent);\n const stored = await input.apiClient.createOrganizationGroup(\n input.organizationId,\n { ...request, organizationPolicy: organizationRequest },\n );\n assertProjectionVerificationCurrent(context.stillCurrent);\n if (!stored) throw new Error(\"Group could not be created\");\n // Genesis really has one signed state. Reconstruct only the exact authored\n // artifacts whose commitments match the summary, then verify them privately.\n const { bundle } = await acknowledgeInitialGroupPolicy({\n organizationId: input.organizationId,\n request,\n response: stored.group,\n stateHash: head.stateHash,\n });\n const { previousStates: _previousStates, ...current } = bundle;\n await context.retainCreatedGroup({\n request: request.initialGroupPolicy,\n response: { ...current, containerMutations: [] },\n organizationRequest,\n organizationResponse: stored.organizationPolicy,\n });\n assertProjectionVerificationCurrent(context.stillCurrent);\n return { ...stored.group, name: input.name.trim(), nameUnreadable: false };\n}\n"]}
|