@tearleads/client-sdk 0.1.248 → 0.1.250
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/client/organizations/index.js +5 -3
- package/client/organizations/index.js.map +1 -1
- package/client/organizations/organizationGroupPresentation.d.ts +1 -1
- package/client/organizations/organizationGroupPresentation.js.map +1 -1
- package/client/organizations/organizationLeaveRequestVerifier.js +21 -0
- package/client/organizations/organizationLeaveRequestVerifier.js.map +1 -0
- package/client/organizations/{organizationReadModels.d.ts → organizationReadModelCoordinator.d.ts} +18 -16
- package/client/organizations/organizationReadModelCoordinator.js +2 -0
- package/client/organizations/organizationReadModelCoordinator.js.map +1 -0
- package/client/organizations/organizationReadModelPresentation.js +51 -0
- package/client/organizations/organizationReadModelPresentation.js.map +1 -0
- package/client/organizations/organizationReadModelScopes.js +37 -0
- package/client/organizations/organizationReadModelScopes.js.map +1 -0
- package/client/organizations/organizationReadModels.js +131 -88
- package/client/organizations/organizationReadModels.js.map +1 -1
- package/client/organizations/organizationsTypes.d.ts +13 -5
- package/client/organizations/organizationsTypes.js.map +1 -1
- package/client/organizations/principalMutations.d.ts +18 -2
- package/client/organizations/principalMutations.js +29 -15
- package/client/organizations/principalMutations.js.map +1 -1
- package/client/runtime/principalMutationApi.d.ts +2 -0
- package/client/runtime/principalMutationApi.js +2 -0
- package/client/runtime/principalMutationApi.js.map +1 -1
- package/client/runtime/principalMutationDispatch.js +47 -10
- package/client/runtime/principalMutationDispatch.js.map +1 -1
- package/client/runtime/workflowRuntime.js +5 -4
- package/client/runtime/workflowRuntime.js.map +1 -1
- package/data/containers/shared/mutationRequestOptions.d.ts +2 -0
- package/data/containers/shared/mutationRequestOptions.js.map +1 -1
- package/data/containers/shared/types.d.ts +12 -2
- package/data/containers/shared/types.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicy/mergeProjectionPolicyEvidence.js +1 -4
- package/data/keyingProjectionVerification/principalPolicy/mergeProjectionPolicyEvidence.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelRepository.js +20 -2
- package/data/persistence/organizations/organizationReadModelRepository.js.map +1 -1
- package/data/persistence/principalPolicy/heldOrganizationDirectories.js +6 -1
- package/data/persistence/principalPolicy/heldOrganizationDirectories.js.map +1 -1
- package/data/persistence/principalPolicy/principalPolicyBundleIntegrity.js +1 -1
- package/data/persistence/principalPolicy/principalPolicyBundleIntegrity.js.map +1 -1
- package/data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent.js +1 -5
- package/data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent.js.map +1 -1
- package/data/principals/organizationGroupDirectoryRequest.js +0 -2
- package/data/principals/organizationGroupDirectoryRequest.js.map +1 -1
- package/data/principals/organizationPolicyRequest.js +0 -2
- package/data/principals/organizationPolicyRequest.js.map +1 -1
- package/data/principals/principalPolicyRequest.js +0 -2
- package/data/principals/principalPolicyRequest.js.map +1 -1
- package/internal/api-client/ApiClient.d.ts +4 -59
- package/internal/api-client/client/apiClientContext.d.ts +0 -30
- package/internal/api-client/client/containerMutations.d.ts +2 -2
- package/internal/api-client/client/containerMutations.js +2 -1
- package/internal/api-client/client/containerMutations.js.map +1 -1
- package/internal/api-client/client/documents.d.ts +0 -12
- package/internal/api-client/client/principalPolicies.d.ts +3 -18
- package/internal/api-client/client/writerProjections.d.ts +0 -12
- package/internal/api-client/heldDirectoryCitations.d.ts +8 -4
- package/internal/api-client/heldDirectoryCitations.js +6 -10
- package/internal/api-client/heldDirectoryCitations.js.map +1 -1
- package/internal/api-client/organizationPolicyHistory.d.ts +0 -6
- package/internal/api-client/principalPolicyRequests.d.ts +2 -18
- package/internal/api-client/principalPolicyRequests.js +6 -4
- package/internal/api-client/principalPolicyRequests.js.map +1 -1
- package/internal/api-client/routes/containers/mutations.js +3 -3
- package/internal/api-client/routes/containers/mutations.js.map +1 -1
- package/internal/api-client/routes/organizations/createGroup.js +3 -5
- package/internal/api-client/routes/organizations/createGroup.js.map +1 -1
- package/internal/api-client/routes/principals/policy.js +2 -5
- package/internal/api-client/routes/principals/policy.js.map +1 -1
- package/internal/api-client/types.d.ts +6 -0
- package/internal/api-client/types.js.map +1 -1
- package/internal/api-client/verifiedManifestCitations.js +3 -3
- package/internal/api-client/verifiedManifestCitations.js.map +1 -1
- package/internal/crypto/index.d.ts +1 -1
- package/internal/crypto/index.js.map +1 -1
- package/internal/crypto/keying/principalPolicyPayload.js +2 -12
- package/internal/crypto/keying/principalPolicyPayload.js.map +1 -1
- package/internal/crypto/keying/principalPolicyTypes.d.ts +5 -6
- package/internal/crypto/keying/principalPolicyTypes.js.map +1 -1
- package/internal/crypto/principalState.d.ts +1 -1
- package/internal/crypto/principalState.js.map +1 -1
- package/internal/crypto/principalStateTypes.d.ts +0 -1
- package/internal/crypto/principalStateTypes.js.map +1 -1
- package/internal/validators/operation/auth.d.ts +0 -24
- package/internal/validators/operation/containerMutations.d.ts +20 -3
- package/internal/validators/operation/containerMutations.js +18 -20
- package/internal/validators/operation/containerMutations.js.map +1 -1
- package/internal/validators/operation/documentMutations.d.ts +0 -48
- package/internal/validators/operation/index.d.ts +1 -1
- package/internal/validators/operation/index.js +1 -1
- package/internal/validators/operation/index.js.map +1 -1
- package/internal/validators/operation/organizationPolicyHistory.d.ts +0 -24
- package/internal/validators/operation/organizations.d.ts +17 -49
- package/internal/validators/operation/organizations.js +4 -2
- package/internal/validators/operation/organizations.js.map +1 -1
- package/internal/validators/operation/principals.d.ts +17 -57
- package/internal/validators/operation/principals.js +5 -2
- package/internal/validators/operation/principals.js.map +1 -1
- package/internal/validators/operation/writerProjections.d.ts +0 -48
- package/internal/validators/request/index.d.ts +1 -1
- package/internal/validators/request/index.js +1 -1
- package/internal/validators/request/index.js.map +1 -1
- package/internal/validators/request/organization.d.ts +15 -32
- package/internal/validators/request/organization.js +8 -0
- package/internal/validators/request/organization.js.map +1 -1
- package/internal/validators/request/organizationProvisioning.d.ts +0 -72
- package/internal/validators/request/principal.d.ts +4 -48
- package/internal/validators/request/principal.js +4 -2
- package/internal/validators/request/principal.js.map +1 -1
- package/internal/validators/request/registration.d.ts +0 -24
- package/internal/validators/response/areas/organizations.d.ts +3 -2
- package/internal/validators/response/areas/organizations.js +3 -2
- package/internal/validators/response/areas/organizations.js.map +1 -1
- package/internal/validators/response/areas/principals.d.ts +1 -1
- package/internal/validators/response/areas/principals.js +1 -1
- package/internal/validators/response/areas/principals.js.map +1 -1
- package/internal/validators/response/committedReadModel.d.ts +697 -0
- package/internal/validators/response/committedReadModel.js +52 -0
- package/internal/validators/response/committedReadModel.js.map +1 -0
- package/internal/validators/response/container.d.ts +52 -48
- package/internal/validators/response/container.js +3 -3
- package/internal/validators/response/container.js.map +1 -1
- package/internal/validators/response/documentMutation.d.ts +0 -96
- package/internal/validators/response/organization.d.ts +0 -191
- package/internal/validators/response/organization.js +0 -7
- package/internal/validators/response/organization.js.map +1 -1
- package/internal/validators/response/organizationPolicyHistory.d.ts +0 -24
- package/internal/validators/response/organizationReadModel.d.ts +167 -0
- package/internal/validators/response/organizationReadModel.js +5 -0
- package/internal/validators/response/organizationReadModel.js.map +1 -1
- package/internal/validators/response/policyEvidenceWire.d.ts +5 -3
- package/internal/validators/response/policyEvidenceWire.js +6 -4
- package/internal/validators/response/policyEvidenceWire.js.map +1 -1
- package/internal/validators/response/principal.d.ts +0 -451
- package/internal/validators/response/principal.js +0 -8
- package/internal/validators/response/principal.js.map +1 -1
- package/internal/validators/response/principalPolicyPage.d.ts +0 -48
- package/internal/validators/response/principalSnapshot.d.ts +4 -24
- package/internal/validators/response/principalSnapshot.js +4 -6
- package/internal/validators/response/principalSnapshot.js.map +1 -1
- package/internal/validators/response/projectionPolicyEvidence.d.ts +0 -48
- package/package.json +1 -1
- package/workflows/container-contents/container-state/organizationHost.d.ts +9 -0
- package/workflows/container-contents/container-state/organizationHost.js.map +1 -1
- package/workflows/container-contents/container-state/remote.js +6 -0
- package/workflows/container-contents/container-state/remote.js.map +1 -1
- package/workflows/containers/child/share/index.d.ts +4 -2
- package/workflows/containers/child/share/index.js +37 -20
- package/workflows/containers/child/share/index.js.map +1 -1
- package/workflows/organizations/containerContentsHost.js +20 -1
- package/workflows/organizations/containerContentsHost.js.map +1 -1
- package/workflows/organizations/groupPolicy/commitCurrentGroupPolicyMutation.js +5 -1
- package/workflows/organizations/groupPolicy/commitCurrentGroupPolicyMutation.js.map +1 -1
- package/workflows/organizations/groupPolicy/currentPolicyMutationAcknowledgement.js +1 -6
- package/workflows/organizations/groupPolicy/currentPolicyMutationAcknowledgement.js.map +1 -1
- package/workflows/organizations/groupPolicy/groupPolicyMutationAcknowledgement.js +1 -6
- package/workflows/organizations/groupPolicy/groupPolicyMutationAcknowledgement.js.map +1 -1
- package/workflows/organizations/groups/createCurrentOrganizationGroup.js +8 -1
- package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
- package/workflows/organizations/index.d.ts +1 -0
- package/workflows/organizations/index.js +1 -0
- package/workflows/organizations/index.js.map +1 -1
- package/workflows/organizations/policyHistory/organizationPolicyHistoryVerification.js +4 -6
- package/workflows/organizations/policyHistory/organizationPolicyHistoryVerification.js.map +1 -1
- package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js +1 -7
- package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js.map +1 -1
- package/workflows/organizations/readModel/committedReadModel.d.ts +66 -0
- package/workflows/organizations/readModel/committedReadModel.js +150 -0
- package/workflows/organizations/readModel/committedReadModel.js.map +1 -0
- package/workflows/organizations/readModel/readModelProjection.d.ts +15 -2
- package/workflows/organizations/readModel/readModelProjection.js +26 -4
- package/workflows/organizations/readModel/readModelProjection.js.map +1 -1
- package/workflows/principals/policyCache/principalPolicyCacheValidation.js +0 -13
- package/workflows/principals/policyCache/principalPolicyCacheValidation.js.map +1 -1
- package/workflows/principals/publicHistory/publicProjectionDirectory.js +4 -5
- package/workflows/principals/publicHistory/publicProjectionDirectory.js.map +1 -1
- package/workflows/registration/provisioningBootstrapBuilders.d.ts +0 -6
- package/workflows/registration/registrationPrincipalPolicyPersistence.js +1 -7
- package/workflows/registration/registrationPrincipalPolicyPersistence.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalPolicyReceiptArtifacts.js","sourceRoot":"","sources":["principalPolicyReceiptArtifacts.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,EACvB,sBAAsB,EACtB,sCAAsC,EACtC,4BAA4B,EAC5B,yBAAyB,GAC1B,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EAAE,yBAAyB,EAAE,MAAM,oCAAoC,CAAC;AAC/E,OAAO,EACL,eAAe,EACf,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,oDAAoD,CAAC;AAC5D,OAAO,EAAE,6BAA6B,EAAE,MAAM,kEAAkE,CAAC;AAEjH,SAAS,qBAAqB,CAAI,MAAoB,EAAE,KAAa;IACnE,OAAO,CAAC,GAAG,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CACtC,uBAAuB,CACrB,yBAAyB,CAAC,IAAI,EAAE,KAAK,CAAC,EACtC,yBAAyB,CAAC,KAAK,EAAE,KAAK,CAAC,CACxC,CACF,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,8CAA8C,CAC5D,QAAiD,EACjD,QAAiD;IAEjD,MAAM,UAAU,GAAG,CAAC,KAA8C,EAAE,EAAE,CAAC,CAAC;QACtE,GAAG,KAAK;QACR,SAAS,EAAE,qBAAqB,CAC9B,KAAK,CAAC,SAAS,EACf,2BAA2B,CAC5B;KACF,CAAC,CAAC;IACH,IACE,yBAAyB,CACvB,UAAU,CAAC,QAAQ,CAAC,EACpB,qCAAqC,CACtC;QACD,yBAAyB,CACvB,UAAU,CAAC,QAAQ,CAAC,EACpB,iCAAiC,CAClC,EACD,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC1E,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,KAAK,UA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AAK,CAAC,cAAc;KACrC,CAAC;QAEF,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;IACzE,MAAM,uCAAuC,CAAC;QAC5C,QAAQ,EAAE,OAAO,CAAC,kBAAkB,IAAI,EAAE;QAC1C,SAAS,EAAE,QAAQ,CAAC,kBAAkB;KACvC,CAAC,CAAC;IACH,MAAM,EAAE,aAAa,EAAE,WAAW,EAAE,GAAG,KAAK,CAAC;IAC7C,MAAM,EAAE,SAAS,EAAE,GAAG,QAAQ,CAAC;IAC/B,OAAO;QACL,YAAY,EAAE,EAAE,GAAG,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE;QAChD,cAAc,EAAE;YACd,aAAa;YACb,WAAW;YACX,SAAS;YACT,GAAG,OAAO,CAAC,gBAAgB;YAC3B,SAAS;SACV;QACD,iBAAiB,EAAE,OAAO,CAAC,UAAU;QACrC,aAAa,EAAE,OAAO,CAAC,MAAM;QAC7B,sBAAsB,EAAE;YACtB,aAAa;YACb,WAAW;YACX,SAAS;YACT,KAAK,EAAE,KAAK,CAAC,QAAQ;YACrB,SAAS,EAAE,OAAO,CAAC,eAAe;SACnC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n compareCanonicalStrings,\n computeAccessEventHash,\n computeContainerKekRecipientTargetHash,\n computeContainerKeyEpochHash,\n computePrincipalStateHash,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerMutationResponse,\n CurrentPrincipalMemberEnvelopesResponse,\n PrincipalPolicyMutationResponse,\n} from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../../../data/keying/canonicalJson\";\nimport {\n readAccessEvent,\n readContainerKeyEpoch,\n readContainerKeyWrap,\n} from \"../../../data/keyingProjectionVerification/readers\";\nimport { principalHeadMatchesReference } from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\n\nfunction sortedCanonicalValues<T>(values: readonly T[], label: string): T[] {\n return [...values].sort((left, right) =>\n compareCanonicalStrings(\n canonicalKeyingJsonString(left, label),\n canonicalKeyingJsonString(right, label),\n ),\n );\n}\n\nexport function assertGroupPolicyEnvelopesMatchAcknowledgement(\n expected: CurrentPrincipalMemberEnvelopesResponse,\n observed: CurrentPrincipalMemberEnvelopesResponse,\n): void {\n const normalized = (value: CurrentPrincipalMemberEnvelopesResponse) => ({\n ...value,\n envelopes: sortedCanonicalValues(\n value.envelopes,\n \"principal member envelope\",\n ),\n });\n if (\n canonicalKeyingJsonString(\n normalized(expected),\n \"acknowledged group member envelopes\",\n ) !==\n canonicalKeyingJsonString(\n normalized(observed),\n \"observed group member envelopes\",\n )\n ) {\n throw new Error(\"Group member envelopes changed after acknowledgement\");\n }\n}\n\n/**\n * Each rematerialized container's acknowledgement names its commit by hash;\n * match every hash against the request this client authored.\n */\nasync function assertContainerMutationAcknowledgements(input: {\n readonly requests: readonly NonNullable<\n PutPrincipalPolicyRequest[\"containerMutations\"]\n >[number][];\n readonly responses: readonly ContainerMutationResponse[] | undefined;\n}): Promise<void> {\n if (!input.responses || input.responses.length !== input.requests.length) {\n throw new Error(\n \"Group policy container acknowledgement batch is incomplete\",\n );\n }\n for (const [index, request] of input.requests.entries()) {\n const response = input.responses[index];\n if (!response) {\n throw new Error(\n \"Group policy container acknowledgement batch is incomplete\",\n );\n }\n const label = \"authored group policy container mutation\";\n const keyEpoch = readContainerKeyEpoch(request.keyEpoch, label);\n const recipientTargets = sortedCanonicalValues(\n request.wraps.map((value) => {\n const wrap = readContainerKeyWrap(value, label);\n return {\n recipientId: wrap.recipientId,\n recipientKeyEpochId: wrap.recipientKeyEpochId,\n recipientKeyFingerprint: wrap.recipientKeyFingerprint,\n recipientKind: wrap.recipientKind,\n };\n }),\n \"authored recipient target\",\n );\n // The request carries this client's own hash of the manifest it signed\n // and the signed event, whose hashes the acknowledgement must name. The\n // manifest hash commits the epoch, but the request no longer names it,\n // so the receipt's epoch label is not compared here: journal recovery\n // discards the receipt after this check, and the in-process path stores\n // a head only through the plan-based container acknowledgement, which\n // requires the plan's epoch. Every field compared here is one the\n // server received in the request, so this binds the receipt to the\n // request; it never proved a commit, with or without the epoch. A\n // rotation's signed body commits its keyring hash, so a substituted\n // keyring must refuse here, before journal recovery clears the saved\n // request. A grant that keeps its epoch commits none; the container\n // acknowledgement checks the retained keyring against the epoch's own.\n const committedKeyringHash = Reflect.get(\n Object(request.body),\n \"keyringHash\",\n );\n if (\n response.manifestHead.manifestHash !== request.expectedManifestHash ||\n response.eventHash !==\n (await computeAccessEventHash(readAccessEvent(request.event, label))) ||\n response.containerKek.containerKeyEpochId !== keyEpoch.id ||\n response.containerKek.containerKeyEpoch !== keyEpoch.keyEpoch ||\n response.containerKek.keyEpochHash !==\n (await computeContainerKeyEpochHash(keyEpoch)) ||\n (typeof committedKeyringHash === \"string\" &&\n response.containerKek.keyringHash !== committedKeyringHash) ||\n response.containerKek.keyTargetHash !==\n (await computeContainerKekRecipientTargetHash(recipientTargets))\n ) {\n throw new Error(\"Group policy container acknowledgement mismatch\");\n }\n }\n}\n\n/**\n * The current an acknowledgement commits, rebuilt from this client's own\n * signed request: the server returns only the head it stored, the insertion\n * time it assigned to the state and payload, and hash-form container\n * acknowledgements. A head other than the one the request commits to refuses.\n * Nothing here manufactures predecessor history or pins.\n */\nexport async function acknowledgedPrincipalPolicyCurrent(input: {\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n}): Promise<PrincipalPolicyPageCurrent> {\n const { request, response } = input;\n const { state } = request;\n const stateHash = await computePrincipalStateHash(state);\n if (\n !principalHeadMatchesReference(response.head, {\n principalType: state.principalType,\n principalId: state.principalId,\n version: state.version,\n keyEpoch: state.keyEpoch,\n stateHash,\n keyFingerprint: state.keyFingerprint,\n })\n )\n throw new Error(\"Principal policy acknowledgement names another head\");\n await assertContainerMutationAcknowledgements({\n requests: request.containerMutations ?? [],\n responses: response.containerMutations,\n });\n const { principalType, principalId } = state;\n const { createdAt } = response;\n return {\n currentState: { ...state, stateHash, createdAt },\n currentPayload: {\n principalType,\n principalId,\n stateHash,\n ...request.encryptedPayload,\n createdAt,\n },\n currentProjection: request.projection,\n currentGrants: request.grants,\n currentMemberEnvelopes: {\n principalType,\n principalId,\n stateHash,\n epoch: state.keyEpoch,\n envelopes: request.memberEnvelopes,\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"principalPolicyReceiptArtifacts.js","sourceRoot":"","sources":["principalPolicyReceiptArtifacts.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,EACvB,sBAAsB,EACtB,sCAAsC,EACtC,4BAA4B,EAC5B,yBAAyB,GAC1B,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EAAE,yBAAyB,EAAE,MAAM,oCAAoC,CAAC;AAC/E,OAAO,EACL,eAAe,EACf,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,oDAAoD,CAAC;AAC5D,OAAO,EAAE,6BAA6B,EAAE,MAAM,kEAAkE,CAAC;AAEjH,SAAS,qBAAqB,CAAI,MAAoB,EAAE,KAAa;IACnE,OAAO,CAAC,GAAG,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CACtC,uBAAuB,CACrB,yBAAyB,CAAC,IAAI,EAAE,KAAK,CAAC,EACtC,yBAAyB,CAAC,KAAK,EAAE,KAAK,CAAC,CACxC,CACF,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,8CAA8C,CAC5D,QAAiD,EACjD,QAAiD;IAEjD,MAAM,UAAU,GAAG,CAAC,KAA8C,EAAE,EAAE,CAAC,CAAC;QACtE,GAAG,KAAK;QACR,SAAS,EAAE,qBAAqB,CAC9B,KAAK,CAAC,SAAS,EACf,2BAA2B,CAC5B;KACF,CAAC,CAAC;IACH,IACE,yBAAyB,CACvB,UAAU,CAAC,QAAQ,CAAC,EACpB,qCAAqC,CACtC;QACD,yBAAyB,CACv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AAK,CAAC,aAAa;QAClC,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,SAAS;QACT,cAAc,EAAE,KAAK,CAAC,cAAc;KACrC,CAAC;QAEF,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;IACzE,MAAM,uCAAuC,CAAC;QAC5C,QAAQ,EAAE,OAAO,CAAC,kBAAkB,IAAI,EAAE;QAC1C,SAAS,EAAE,QAAQ,CAAC,kBAAkB;KACvC,CAAC,CAAC;IACH,MAAM,EAAE,aAAa,EAAE,WAAW,EAAE,GAAG,KAAK,CAAC;IAC7C,MAAM,EAAE,SAAS,EAAE,GAAG,QAAQ,CAAC;IAC/B,OAAO;QACL,YAAY,EAAE,EAAE,GAAG,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE;QAChD,cAAc,EAAE,EAAE,UAAU,EAAE,OAAO,CAAC,gBAAgB,CAAC,UAAU,EAAE;QACnE,iBAAiB,EAAE,OAAO,CAAC,UAAU;QACrC,aAAa,EAAE,OAAO,CAAC,MAAM;QAC7B,sBAAsB,EAAE;YACtB,aAAa;YACb,WAAW;YACX,SAAS;YACT,KAAK,EAAE,KAAK,CAAC,QAAQ;YACrB,SAAS,EAAE,OAAO,CAAC,eAAe;SACnC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n compareCanonicalStrings,\n computeAccessEventHash,\n computeContainerKekRecipientTargetHash,\n computeContainerKeyEpochHash,\n computePrincipalStateHash,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerMutationResponse,\n CurrentPrincipalMemberEnvelopesResponse,\n PrincipalPolicyMutationResponse,\n} from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../../../data/keying/canonicalJson\";\nimport {\n readAccessEvent,\n readContainerKeyEpoch,\n readContainerKeyWrap,\n} from \"../../../data/keyingProjectionVerification/readers\";\nimport { principalHeadMatchesReference } from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\n\nfunction sortedCanonicalValues<T>(values: readonly T[], label: string): T[] {\n return [...values].sort((left, right) =>\n compareCanonicalStrings(\n canonicalKeyingJsonString(left, label),\n canonicalKeyingJsonString(right, label),\n ),\n );\n}\n\nexport function assertGroupPolicyEnvelopesMatchAcknowledgement(\n expected: CurrentPrincipalMemberEnvelopesResponse,\n observed: CurrentPrincipalMemberEnvelopesResponse,\n): void {\n const normalized = (value: CurrentPrincipalMemberEnvelopesResponse) => ({\n ...value,\n envelopes: sortedCanonicalValues(\n value.envelopes,\n \"principal member envelope\",\n ),\n });\n if (\n canonicalKeyingJsonString(\n normalized(expected),\n \"acknowledged group member envelopes\",\n ) !==\n canonicalKeyingJsonString(\n normalized(observed),\n \"observed group member envelopes\",\n )\n ) {\n throw new Error(\"Group member envelopes changed after acknowledgement\");\n }\n}\n\n/**\n * Each rematerialized container's acknowledgement names its commit by hash;\n * match every hash against the request this client authored.\n */\nasync function assertContainerMutationAcknowledgements(input: {\n readonly requests: readonly NonNullable<\n PutPrincipalPolicyRequest[\"containerMutations\"]\n >[number][];\n readonly responses: readonly ContainerMutationResponse[] | undefined;\n}): Promise<void> {\n if (!input.responses || input.responses.length !== input.requests.length) {\n throw new Error(\n \"Group policy container acknowledgement batch is incomplete\",\n );\n }\n for (const [index, request] of input.requests.entries()) {\n const response = input.responses[index];\n if (!response) {\n throw new Error(\n \"Group policy container acknowledgement batch is incomplete\",\n );\n }\n const label = \"authored group policy container mutation\";\n const keyEpoch = readContainerKeyEpoch(request.keyEpoch, label);\n const recipientTargets = sortedCanonicalValues(\n request.wraps.map((value) => {\n const wrap = readContainerKeyWrap(value, label);\n return {\n recipientId: wrap.recipientId,\n recipientKeyEpochId: wrap.recipientKeyEpochId,\n recipientKeyFingerprint: wrap.recipientKeyFingerprint,\n recipientKind: wrap.recipientKind,\n };\n }),\n \"authored recipient target\",\n );\n // The request carries this client's own hash of the manifest it signed\n // and the signed event, whose hashes the acknowledgement must name. The\n // manifest hash commits the epoch, but the request no longer names it,\n // so the receipt's epoch label is not compared here: journal recovery\n // discards the receipt after this check, and the in-process path stores\n // a head only through the plan-based container acknowledgement, which\n // requires the plan's epoch. Every field compared here is one the\n // server received in the request, so this binds the receipt to the\n // request; it never proved a commit, with or without the epoch. A\n // rotation's signed body commits its keyring hash, so a substituted\n // keyring must refuse here, before journal recovery clears the saved\n // request. A grant that keeps its epoch commits none; the container\n // acknowledgement checks the retained keyring against the epoch's own.\n const committedKeyringHash = Reflect.get(\n Object(request.body),\n \"keyringHash\",\n );\n if (\n response.manifestHead.manifestHash !== request.expectedManifestHash ||\n response.eventHash !==\n (await computeAccessEventHash(readAccessEvent(request.event, label))) ||\n response.containerKek.containerKeyEpochId !== keyEpoch.id ||\n response.containerKek.containerKeyEpoch !== keyEpoch.keyEpoch ||\n response.containerKek.keyEpochHash !==\n (await computeContainerKeyEpochHash(keyEpoch)) ||\n (typeof committedKeyringHash === \"string\" &&\n response.containerKek.keyringHash !== committedKeyringHash) ||\n response.containerKek.keyTargetHash !==\n (await computeContainerKekRecipientTargetHash(recipientTargets))\n ) {\n throw new Error(\"Group policy container acknowledgement mismatch\");\n }\n }\n}\n\n/**\n * The current an acknowledgement commits, rebuilt from this client's own\n * signed request: the server returns only the head it stored, the insertion\n * time it assigned to the state and payload, and hash-form container\n * acknowledgements. A head other than the one the request commits to refuses.\n * Nothing here manufactures predecessor history or pins.\n */\nexport async function acknowledgedPrincipalPolicyCurrent(input: {\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n}): Promise<PrincipalPolicyPageCurrent> {\n const { request, response } = input;\n const { state } = request;\n const stateHash = await computePrincipalStateHash(state);\n if (\n !principalHeadMatchesReference(response.head, {\n principalType: state.principalType,\n principalId: state.principalId,\n version: state.version,\n keyEpoch: state.keyEpoch,\n stateHash,\n keyFingerprint: state.keyFingerprint,\n })\n )\n throw new Error(\"Principal policy acknowledgement names another head\");\n await assertContainerMutationAcknowledgements({\n requests: request.containerMutations ?? [],\n responses: response.containerMutations,\n });\n const { principalType, principalId } = state;\n const { createdAt } = response;\n return {\n currentState: { ...state, stateHash, createdAt },\n currentPayload: { ciphertext: request.encryptedPayload.ciphertext },\n currentProjection: request.projection,\n currentGrants: request.grants,\n currentMemberEnvelopes: {\n principalType,\n principalId,\n stateHash,\n epoch: state.keyEpoch,\n envelopes: request.memberEnvelopes,\n },\n };\n}\n"]}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { OrganizationReadModelDeltaResponse } from "../../../internal/validators/response/index.js";
|
|
2
|
+
import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
|
|
3
|
+
import type { OrganizationDirectoryAndGroups } from "./index.js";
|
|
4
|
+
import { applyOrganizationReadModelPageAt } from "./readModelProjection.js";
|
|
5
|
+
/**
|
|
6
|
+
* The read-model delta one of this device's mutations carried back, and the
|
|
7
|
+
* cursor it held when it sent the mutation: the page a feed read from that
|
|
8
|
+
* cursor returns once the mutation committed.
|
|
9
|
+
*/
|
|
10
|
+
export interface CommittedReadModelOffer {
|
|
11
|
+
readonly delta: OrganizationReadModelDeltaResponse;
|
|
12
|
+
readonly heldCursor: string;
|
|
13
|
+
}
|
|
14
|
+
/** What applying an offer presented; `undefined` when it applied nothing. */
|
|
15
|
+
export type CommittedReadModelOutcome = OrganizationDirectoryAndGroups | null | undefined;
|
|
16
|
+
interface CommittedReadModelScope {
|
|
17
|
+
/** The runtime's domain scope; an identity switch replaces it. */
|
|
18
|
+
readonly domainScope: object;
|
|
19
|
+
readonly execSql: ExecSql;
|
|
20
|
+
readonly organizationId: string;
|
|
21
|
+
/** The runtime's session generation; a logout or new login advances it. */
|
|
22
|
+
readonly sessionGeneration: number;
|
|
23
|
+
readonly userId: string;
|
|
24
|
+
}
|
|
25
|
+
/** A mutation that sent a held cursor; settle it once, when it ends. */
|
|
26
|
+
export interface CommittedReadModelLease {
|
|
27
|
+
readonly heldCursor: string | undefined;
|
|
28
|
+
settle(delta: OrganizationReadModelDeltaResponse | undefined): void;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Begin a mutation that sends the read-model cursor this requester's next
|
|
32
|
+
* reconcile would request from, so its response can carry the delta from it.
|
|
33
|
+
* Until it settles, a realtime hint's cursor check waits for it. No cursor is
|
|
34
|
+
* held while the requester's presentation is denied, since that reconcile
|
|
35
|
+
* requests a snapshot, or when the projection cannot be read.
|
|
36
|
+
*/
|
|
37
|
+
export declare function beginCommittedReadModel(scope: CommittedReadModelScope,
|
|
38
|
+
/** How many cursors the mutation can stamp; a share stamps one. */
|
|
39
|
+
maxStamps?: number): Promise<CommittedReadModelLease>;
|
|
40
|
+
/**
|
|
41
|
+
* Wait, for a bounded time, for this scope's mutations in flight that could
|
|
42
|
+
* be the commit a realtime hint names, then list every unclaimed delta, oldest
|
|
43
|
+
* first: a hint names a commit, and an offer at or past it reflects that
|
|
44
|
+
* commit. A mutation still in flight after the wait leaves the check to read.
|
|
45
|
+
*/
|
|
46
|
+
export declare function awaitCommittedReadModelOffers(scope: CommittedReadModelScope,
|
|
47
|
+
/** Without a hint position, every mutation in flight is waited for. */
|
|
48
|
+
hintPosition: bigint | undefined, maxWaitMs?: number): Promise<readonly CommittedReadModelOffer[]>;
|
|
49
|
+
/**
|
|
50
|
+
* Apply one offer once, by its delta. The first claimant (a hint's cursor
|
|
51
|
+
* check or the mutation's own reconcile) runs `apply`; a later claimant of the
|
|
52
|
+
* same delta shares that outcome instead of reading. `undefined` when the
|
|
53
|
+
* scope holds no such offer.
|
|
54
|
+
*/
|
|
55
|
+
export declare function claimCommittedReadModelOffer(scope: CommittedReadModelScope, delta: OrganizationReadModelDeltaResponse, apply: (offer: CommittedReadModelOffer) => Promise<CommittedReadModelOutcome>): Promise<CommittedReadModelOutcome> | undefined;
|
|
56
|
+
/** The projection cursor a reconcile of this requester would request from. */
|
|
57
|
+
export declare function loadHeldOrganizationReadModelCursor(scope: CommittedReadModelScope): Promise<string | undefined>;
|
|
58
|
+
/**
|
|
59
|
+
* Apply the read-model delta a mutation's response carried as the page a feed
|
|
60
|
+
* read from `requestedCursor` returns, with no request. Resolves `undefined`
|
|
61
|
+
* when it is not applied: its cursor does not advance past the one sent, the
|
|
62
|
+
* projection no longer holds that cursor, or the page applied stale. The
|
|
63
|
+
* caller then reads the feed as before.
|
|
64
|
+
*/
|
|
65
|
+
export declare function applyCommittedOrganizationReadModel(input: Parameters<typeof applyOrganizationReadModelPageAt>[0]): Promise<OrganizationDirectoryAndGroups | null | undefined>;
|
|
66
|
+
export {};
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { organizationReadModelCursorPosition } from "../../../internal/validators/organizationReadModelCursor.js";
|
|
2
|
+
import { OrganizationReadModelRepository } from "../../../data/persistence/organizations/organizationReadModelRepository.js";
|
|
3
|
+
import { isOrganizationPresentationAccessReadable, organizationAccessScopeKey, } from "./organizationPresentationAccessState.js";
|
|
4
|
+
import { applyOrganizationReadModelPageAt } from "./readModelProjection.js";
|
|
5
|
+
/** A settled offer older than this many is dropped unread. */
|
|
6
|
+
const MAX_SETTLED_OFFERS = 4;
|
|
7
|
+
/** A hint's cursor check waits no longer than this for mutations in flight. */
|
|
8
|
+
const MAX_PENDING_WAIT_MS = 10_000;
|
|
9
|
+
// Keyed by domain scope and session generation, so a mutation and a hint
|
|
10
|
+
// check of one session never meet those of a session that replaced it.
|
|
11
|
+
const offersByDomainScope = new WeakMap();
|
|
12
|
+
function scopeOffers(scope) {
|
|
13
|
+
let byScope = offersByDomainScope.get(scope.domainScope);
|
|
14
|
+
if (!byScope) {
|
|
15
|
+
byScope = new Map();
|
|
16
|
+
offersByDomainScope.set(scope.domainScope, byScope);
|
|
17
|
+
}
|
|
18
|
+
const requester = organizationAccessScopeKey(scope.organizationId, scope.userId);
|
|
19
|
+
const key = `${scope.sessionGeneration}:${requester}`;
|
|
20
|
+
let offers = byScope.get(key);
|
|
21
|
+
if (!offers) {
|
|
22
|
+
// A newer session retires the requester's older buckets and their offers.
|
|
23
|
+
for (const [existing] of byScope) {
|
|
24
|
+
const [generation, ...rest] = existing.split(":");
|
|
25
|
+
if (rest.join(":") === requester &&
|
|
26
|
+
Number(generation) < scope.sessionGeneration)
|
|
27
|
+
byScope.delete(existing);
|
|
28
|
+
}
|
|
29
|
+
offers = { applying: new WeakMap(), pending: new Map(), settled: [] };
|
|
30
|
+
byScope.set(key, offers);
|
|
31
|
+
}
|
|
32
|
+
return offers;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Begin a mutation that sends the read-model cursor this requester's next
|
|
36
|
+
* reconcile would request from, so its response can carry the delta from it.
|
|
37
|
+
* Until it settles, a realtime hint's cursor check waits for it. No cursor is
|
|
38
|
+
* held while the requester's presentation is denied, since that reconcile
|
|
39
|
+
* requests a snapshot, or when the projection cannot be read.
|
|
40
|
+
*/
|
|
41
|
+
export async function beginCommittedReadModel(scope,
|
|
42
|
+
/** How many cursors the mutation can stamp; a share stamps one. */
|
|
43
|
+
maxStamps = Number.POSITIVE_INFINITY) {
|
|
44
|
+
// An unreadable cursor only forgoes the delta; the mutation still goes out.
|
|
45
|
+
const heldCursor = await loadHeldOrganizationReadModelCursor(scope).catch(() => undefined);
|
|
46
|
+
if (heldCursor === undefined) {
|
|
47
|
+
return { heldCursor, settle: () => { } };
|
|
48
|
+
}
|
|
49
|
+
const offers = scopeOffers(scope);
|
|
50
|
+
let resolve = () => { };
|
|
51
|
+
const promise = new Promise((settled) => {
|
|
52
|
+
resolve = settled;
|
|
53
|
+
});
|
|
54
|
+
offers.pending.set(promise, {
|
|
55
|
+
heldPosition: organizationReadModelCursorPosition(heldCursor, scope.organizationId),
|
|
56
|
+
maxStamps,
|
|
57
|
+
});
|
|
58
|
+
return {
|
|
59
|
+
heldCursor,
|
|
60
|
+
settle: (delta) => {
|
|
61
|
+
if (!offers.pending.delete(promise))
|
|
62
|
+
return;
|
|
63
|
+
if (delta) {
|
|
64
|
+
offers.settled = [...offers.settled, { delta, heldCursor }].slice(-MAX_SETTLED_OFFERS);
|
|
65
|
+
}
|
|
66
|
+
resolve();
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
/** Whether a mutation in flight could be the commit a hint names. */
|
|
71
|
+
function couldCommit(lease, hintPosition) {
|
|
72
|
+
return (lease.heldPosition !== null &&
|
|
73
|
+
hintPosition > lease.heldPosition &&
|
|
74
|
+
(lease.maxStamps === Number.POSITIVE_INFINITY ||
|
|
75
|
+
hintPosition <= lease.heldPosition + BigInt(lease.maxStamps)));
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Wait, for a bounded time, for this scope's mutations in flight that could
|
|
79
|
+
* be the commit a realtime hint names, then list every unclaimed delta, oldest
|
|
80
|
+
* first: a hint names a commit, and an offer at or past it reflects that
|
|
81
|
+
* commit. A mutation still in flight after the wait leaves the check to read.
|
|
82
|
+
*/
|
|
83
|
+
export async function awaitCommittedReadModelOffers(scope,
|
|
84
|
+
/** Without a hint position, every mutation in flight is waited for. */
|
|
85
|
+
hintPosition, maxWaitMs = MAX_PENDING_WAIT_MS) {
|
|
86
|
+
const offers = scopeOffers(scope);
|
|
87
|
+
let awaited = [...offers.pending]
|
|
88
|
+
.filter(([, lease]) => hintPosition === undefined || couldCommit(lease, hintPosition))
|
|
89
|
+
.map(([promise]) => promise);
|
|
90
|
+
let timer;
|
|
91
|
+
const expired = new Promise((resolve) => {
|
|
92
|
+
timer = setTimeout(resolve, maxWaitMs, "expired");
|
|
93
|
+
});
|
|
94
|
+
// Stop as soon as a settled offer covers the hint, or the wait runs out.
|
|
95
|
+
while (awaited.length > 0 &&
|
|
96
|
+
!offersCover(offers.settled, scope.organizationId, hintPosition)) {
|
|
97
|
+
if ((await Promise.race([...awaited, expired])) === "expired")
|
|
98
|
+
break;
|
|
99
|
+
awaited = awaited.filter((promise) => offers.pending.has(promise));
|
|
100
|
+
}
|
|
101
|
+
clearTimeout(timer);
|
|
102
|
+
// The bucket read before the wait: a newer session may have retired it.
|
|
103
|
+
return offers.settled;
|
|
104
|
+
}
|
|
105
|
+
/** Whether a settled offer reaches the hint's committed cursor. */
|
|
106
|
+
function offersCover(settled, organizationId, hintPosition) {
|
|
107
|
+
return (hintPosition !== undefined &&
|
|
108
|
+
settled.some((offer) => (organizationReadModelCursorPosition(offer.delta.nextCursor, organizationId) ?? -1n) >= hintPosition));
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Apply one offer once, by its delta. The first claimant (a hint's cursor
|
|
112
|
+
* check or the mutation's own reconcile) runs `apply`; a later claimant of the
|
|
113
|
+
* same delta shares that outcome instead of reading. `undefined` when the
|
|
114
|
+
* scope holds no such offer.
|
|
115
|
+
*/
|
|
116
|
+
export function claimCommittedReadModelOffer(scope, delta, apply) {
|
|
117
|
+
const offers = scopeOffers(scope);
|
|
118
|
+
const claimed = offers.applying.get(delta);
|
|
119
|
+
if (claimed)
|
|
120
|
+
return claimed;
|
|
121
|
+
const offer = offers.settled.find((settled) => settled.delta === delta);
|
|
122
|
+
if (!offer)
|
|
123
|
+
return undefined;
|
|
124
|
+
offers.settled = offers.settled.filter((settled) => settled !== offer);
|
|
125
|
+
const outcome = apply(offer);
|
|
126
|
+
offers.applying.set(delta, outcome);
|
|
127
|
+
return outcome;
|
|
128
|
+
}
|
|
129
|
+
/** The projection cursor a reconcile of this requester would request from. */
|
|
130
|
+
export async function loadHeldOrganizationReadModelCursor(scope) {
|
|
131
|
+
if (!isOrganizationPresentationAccessReadable({ ...scope, requesterUserId: scope.userId }, "readModel")) {
|
|
132
|
+
return undefined;
|
|
133
|
+
}
|
|
134
|
+
return ((await new OrganizationReadModelRepository(scope.execSql).loadOrganizationReadModelCursor(scope.organizationId)) ?? undefined);
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Apply the read-model delta a mutation's response carried as the page a feed
|
|
138
|
+
* read from `requestedCursor` returns, with no request. Resolves `undefined`
|
|
139
|
+
* when it is not applied: its cursor does not advance past the one sent, the
|
|
140
|
+
* projection no longer holds that cursor, or the page applied stale. The
|
|
141
|
+
* caller then reads the feed as before.
|
|
142
|
+
*/
|
|
143
|
+
export async function applyCommittedOrganizationReadModel(input) {
|
|
144
|
+
const sent = organizationReadModelCursorPosition(input.requestedCursor, input.organizationId);
|
|
145
|
+
const next = organizationReadModelCursorPosition(input.response.nextCursor, input.organizationId);
|
|
146
|
+
if (sent === null || next === null || next <= sent)
|
|
147
|
+
return undefined;
|
|
148
|
+
return applyOrganizationReadModelPageAt(input);
|
|
149
|
+
}
|
|
150
|
+
//# sourceMappingURL=committedReadModel.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"committedReadModel.js","sourceRoot":"","sources":["committedReadModel.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,mDAAmD,CAAC;AAExG,OAAO,EAAE,+BAA+B,EAAE,MAAM,yEAAyE,CAAC;AAG1H,OAAO,EACL,wCAAwC,EACxC,0BAA0B,GAC3B,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,gCAAgC,EAAE,MAAM,uBAAuB,CAAC;AA4CzE,8DAA8D;AAC9D,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAC7B,+EAA+E;AAC/E,MAAM,mBAAmB,GAAG,MAAM,CAAC;AAEnC,yEAAyE;AACzE,uEAAuE;AACvE,MAAM,mBAAmB,GAAG,IAAI,OAAO,EAAoC,CAAC;AAE5E,SAAS,WAAW,CAAC,KAA8B;IACjD,IAAI,OAAO,GAAG,mBAAmB,CAAC,GAAG,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;IACzD,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,OAAO,GAAG,IAAI,GAAG,EAAE,CAAC;QACpB,mBAAmB,CAAC,GAAG,CAAC,KAAK,CAAC,WAAW,EAAE,O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GAMG;AACH,MAAM,CAAC,KAAK,UAAU,mCAAmC,CACvD,KAA6D;IAE7D,MAAM,IAAI,GAAG,mCAAmC,CAC9C,KAAK,CAAC,eAAe,EACrB,KAAK,CAAC,cAAc,CACrB,CAAC;IACF,MAAM,IAAI,GAAG,mCAAmC,CAC9C,KAAK,CAAC,QAAQ,CAAC,UAAU,EACzB,KAAK,CAAC,cAAc,CACrB,CAAC;IACF,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,IAAI,IAAI;QAAE,OAAO,SAAS,CAAC;IACrE,OAAO,gCAAgC,CAAC,KAAK,CAAC,CAAC;AACjD,CAAC","sourcesContent":["import { organizationReadModelCursorPosition } from \"@tearleads/validators/organizationReadModelCursor\";\nimport type { OrganizationReadModelDeltaResponse } from \"@tearleads/validators/response\";\nimport { OrganizationReadModelRepository } from \"../../../data/persistence/organizations/organizationReadModelRepository\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { OrganizationDirectoryAndGroups } from \"./index\";\nimport {\n isOrganizationPresentationAccessReadable,\n organizationAccessScopeKey,\n} from \"./organizationPresentationAccessState\";\nimport { applyOrganizationReadModelPageAt } from \"./readModelProjection\";\n\n/**\n * The read-model delta one of this device's mutations carried back, and the\n * cursor it held when it sent the mutation: the page a feed read from that\n * cursor returns once the mutation committed.\n */\nexport interface CommittedReadModelOffer {\n readonly delta: OrganizationReadModelDeltaResponse;\n readonly heldCursor: string;\n}\n\n/** A mutation in flight: the cursors it can commit lie in (held, held + stamps]. */\ninterface PendingLease {\n readonly heldPosition: bigint | null;\n readonly maxStamps: number;\n}\n\n/** What applying an offer presented; `undefined` when it applied nothing. */\nexport type CommittedReadModelOutcome =\n | OrganizationDirectoryAndGroups\n | null\n | undefined;\n\ninterface ScopeOffers {\n /** Each claimed offer's one apply, shared by every caller that claims it. */\n readonly applying: WeakMap<\n OrganizationReadModelDeltaResponse,\n Promise<CommittedReadModelOutcome>\n >;\n readonly pending: Map<Promise<void>, PendingLease>;\n settled: readonly CommittedReadModelOffer[];\n}\n\ninterface CommittedReadModelScope {\n /** The runtime's domain scope; an identity switch replaces it. */\n readonly domainScope: object;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n /** The runtime's session generation; a logout or new login advances it. */\n readonly sessionGeneration: number;\n readonly userId: string;\n}\n\n/** A settled offer older than this many is dropped unread. */\nconst MAX_SETTLED_OFFERS = 4;\n/** A hint's cursor check waits no longer than this for mutations in flight. */\nconst MAX_PENDING_WAIT_MS = 10_000;\n\n// Keyed by domain scope and session generation, so a mutation and a hint\n// check of one session never meet those of a session that replaced it.\nconst offersByDomainScope = new WeakMap<object, Map<string, ScopeOffers>>();\n\nfunction scopeOffers(scope: CommittedReadModelScope): ScopeOffers {\n let byScope = offersByDomainScope.get(scope.domainScope);\n if (!byScope) {\n byScope = new Map();\n offersByDomainScope.set(scope.domainScope, byScope);\n }\n const requester = organizationAccessScopeKey(\n scope.organizationId,\n scope.userId,\n );\n const key = `${scope.sessionGeneration}:${requester}`;\n let offers = byScope.get(key);\n if (!offers) {\n // A newer session retires the requester's older buckets and their offers.\n for (const [existing] of byScope) {\n const [generation, ...rest] = existing.split(\":\");\n if (\n rest.join(\":\") === requester &&\n Number(generation) < scope.sessionGeneration\n )\n byScope.delete(existing);\n }\n offers = { applying: new WeakMap(), pending: new Map(), settled: [] };\n byScope.set(key, offers);\n }\n return offers;\n}\n\n/** A mutation that sent a held cursor; settle it once, when it ends. */\nexport interface CommittedReadModelLease {\n readonly heldCursor: string | undefined;\n settle(delta: OrganizationReadModelDeltaResponse | undefined): void;\n}\n\n/**\n * Begin a mutation that sends the read-model cursor this requester's next\n * reconcile would request from, so its response can carry the delta from it.\n * Until it settles, a realtime hint's cursor check waits for it. No cursor is\n * held while the requester's presentation is denied, since that reconcile\n * requests a snapshot, or when the projection cannot be read.\n */\nexport async function beginCommittedReadModel(\n scope: CommittedReadModelScope,\n /** How many cursors the mutation can stamp; a share stamps one. */\n maxStamps = Number.POSITIVE_INFINITY,\n): Promise<CommittedReadModelLease> {\n // An unreadable cursor only forgoes the delta; the mutation still goes out.\n const heldCursor = await loadHeldOrganizationReadModelCursor(scope).catch(\n () => undefined,\n );\n if (heldCursor === undefined) {\n return { heldCursor, settle: () => {} };\n }\n const offers = scopeOffers(scope);\n let resolve = () => {};\n const promise = new Promise<void>((settled) => {\n resolve = settled;\n });\n offers.pending.set(promise, {\n heldPosition: organizationReadModelCursorPosition(\n heldCursor,\n scope.organizationId,\n ),\n maxStamps,\n });\n return {\n heldCursor,\n settle: (delta) => {\n if (!offers.pending.delete(promise)) return;\n if (delta) {\n offers.settled = [...offers.settled, { delta, heldCursor }].slice(\n -MAX_SETTLED_OFFERS,\n );\n }\n resolve();\n },\n };\n}\n\n/** Whether a mutation in flight could be the commit a hint names. */\nfunction couldCommit(lease: PendingLease, hintPosition: bigint): boolean {\n return (\n lease.heldPosition !== null &&\n hintPosition > lease.heldPosition &&\n (lease.maxStamps === Number.POSITIVE_INFINITY ||\n hintPosition <= lease.heldPosition + BigInt(lease.maxStamps))\n );\n}\n\n/**\n * Wait, for a bounded time, for this scope's mutations in flight that could\n * be the commit a realtime hint names, then list every unclaimed delta, oldest\n * first: a hint names a commit, and an offer at or past it reflects that\n * commit. A mutation still in flight after the wait leaves the check to read.\n */\nexport async function awaitCommittedReadModelOffers(\n scope: CommittedReadModelScope,\n /** Without a hint position, every mutation in flight is waited for. */\n hintPosition: bigint | undefined,\n maxWaitMs = MAX_PENDING_WAIT_MS,\n): Promise<readonly CommittedReadModelOffer[]> {\n const offers = scopeOffers(scope);\n let awaited = [...offers.pending]\n .filter(\n ([, lease]) =>\n hintPosition === undefined || couldCommit(lease, hintPosition),\n )\n .map(([promise]) => promise);\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<\"expired\">((resolve) => {\n timer = setTimeout(resolve, maxWaitMs, \"expired\");\n });\n // Stop as soon as a settled offer covers the hint, or the wait runs out.\n while (\n awaited.length > 0 &&\n !offersCover(offers.settled, scope.organizationId, hintPosition)\n ) {\n if ((await Promise.race([...awaited, expired])) === \"expired\") break;\n awaited = awaited.filter((promise) => offers.pending.has(promise));\n }\n clearTimeout(timer);\n // The bucket read before the wait: a newer session may have retired it.\n return offers.settled;\n}\n\n/** Whether a settled offer reaches the hint's committed cursor. */\nfunction offersCover(\n settled: readonly CommittedReadModelOffer[],\n organizationId: string,\n hintPosition: bigint | undefined,\n): boolean {\n return (\n hintPosition !== undefined &&\n settled.some(\n (offer) =>\n (organizationReadModelCursorPosition(\n offer.delta.nextCursor,\n organizationId,\n ) ?? -1n) >= hintPosition,\n )\n );\n}\n\n/**\n * Apply one offer once, by its delta. The first claimant (a hint's cursor\n * check or the mutation's own reconcile) runs `apply`; a later claimant of the\n * same delta shares that outcome instead of reading. `undefined` when the\n * scope holds no such offer.\n */\nexport function claimCommittedReadModelOffer(\n scope: CommittedReadModelScope,\n delta: OrganizationReadModelDeltaResponse,\n apply: (offer: CommittedReadModelOffer) => Promise<CommittedReadModelOutcome>,\n): Promise<CommittedReadModelOutcome> | undefined {\n const offers = scopeOffers(scope);\n const claimed = offers.applying.get(delta);\n if (claimed) return claimed;\n const offer = offers.settled.find((settled) => settled.delta === delta);\n if (!offer) return undefined;\n offers.settled = offers.settled.filter((settled) => settled !== offer);\n const outcome = apply(offer);\n offers.applying.set(delta, outcome);\n return outcome;\n}\n\n/** The projection cursor a reconcile of this requester would request from. */\nexport async function loadHeldOrganizationReadModelCursor(\n scope: CommittedReadModelScope,\n): Promise<string | undefined> {\n if (\n !isOrganizationPresentationAccessReadable(\n { ...scope, requesterUserId: scope.userId },\n \"readModel\",\n )\n ) {\n return undefined;\n }\n return (\n (await new OrganizationReadModelRepository(\n scope.execSql,\n ).loadOrganizationReadModelCursor(scope.organizationId)) ?? undefined\n );\n}\n\n/**\n * Apply the read-model delta a mutation's response carried as the page a feed\n * read from `requestedCursor` returns, with no request. Resolves `undefined`\n * when it is not applied: its cursor does not advance past the one sent, the\n * projection no longer holds that cursor, or the page applied stale. The\n * caller then reads the feed as before.\n */\nexport async function applyCommittedOrganizationReadModel(\n input: Parameters<typeof applyOrganizationReadModelPageAt>[0],\n): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const sent = organizationReadModelCursorPosition(\n input.requestedCursor,\n input.organizationId,\n );\n const next = organizationReadModelCursorPosition(\n input.response.nextCursor,\n input.organizationId,\n );\n if (sent === null || next === null || next <= sent) return undefined;\n return applyOrganizationReadModelPageAt(input);\n}\n"]}
|
|
@@ -11,14 +11,27 @@ interface OrganizationReadModelProjectionInput {
|
|
|
11
11
|
readonly execSql: ExecSql;
|
|
12
12
|
readonly organizationId: string;
|
|
13
13
|
}
|
|
14
|
-
|
|
15
|
-
|
|
14
|
+
/** Applying a page needs no API; `stillCurrent` is rechecked in the write. */
|
|
15
|
+
interface ApplyReadModelPageInput extends OrganizationReadModelProjectionInput {
|
|
16
16
|
readonly logError?: ((message: string | Error, cause?: unknown) => void) | undefined;
|
|
17
|
+
readonly stillCurrent?: (() => boolean) | undefined;
|
|
18
|
+
}
|
|
19
|
+
export interface ReconcileOrganizationDirectoryAndGroupsInput extends ApplyReadModelPageInput {
|
|
20
|
+
readonly apiClient: OrganizationReadModelApi;
|
|
17
21
|
}
|
|
18
22
|
export declare function loadLocalOrganizationDirectoryAndGroups(input: OrganizationReadModelProjectionInput): Promise<OrganizationDirectoryAndGroups | null>;
|
|
19
23
|
export declare function loadLocalOrganizationGroupMembers(input: OrganizationReadModelProjectionInput & {
|
|
20
24
|
readonly groupId: string;
|
|
21
25
|
}): Promise<OrganizationReadModelGroupMembers | null>;
|
|
26
|
+
/**
|
|
27
|
+
* Apply one page as a feed read from `requestedCursor` returns it, with no
|
|
28
|
+
* request, while the projection still holds that cursor. Resolves `undefined`
|
|
29
|
+
* when it is not applied; it is never retried.
|
|
30
|
+
*/
|
|
31
|
+
export declare function applyOrganizationReadModelPageAt(input: ApplyReadModelPageInput & {
|
|
32
|
+
readonly requestedCursor: string;
|
|
33
|
+
readonly response: OrganizationReadModelResponse;
|
|
34
|
+
}): Promise<OrganizationDirectoryAndGroups | null | undefined>;
|
|
22
35
|
/**
|
|
23
36
|
* Resolves the reconciled projection, `null` when the pass completed
|
|
24
37
|
* authoritatively with nothing presentable (including a denial that purged
|
|
@@ -131,6 +131,7 @@ async function applyResponse(input, state, response) {
|
|
|
131
131
|
return {
|
|
132
132
|
kind: "applied",
|
|
133
133
|
result: await repository.applyOrganizationReadModelResponse({
|
|
134
|
+
canCommit: input.stillCurrent,
|
|
134
135
|
currentUserId: input.currentUserId,
|
|
135
136
|
requestedCursor: state.expectedLocalCursor,
|
|
136
137
|
response,
|
|
@@ -189,13 +190,12 @@ async function applyReadModelPage(input, state, response) {
|
|
|
189
190
|
}
|
|
190
191
|
const accessInput = organizationPresentationAccessInput(input);
|
|
191
192
|
return runOrganizationPresentationMutation(input.execSql, async () => {
|
|
192
|
-
if (!reconciliationIsCurrent(input, state)
|
|
193
|
+
if (!reconciliationIsCurrent(input, state) ||
|
|
194
|
+
input.stillCurrent?.() === false)
|
|
193
195
|
return { kind: "done", value: null };
|
|
194
|
-
}
|
|
195
196
|
const preparation = await prepareDeniedProjectionForApply(input, state);
|
|
196
|
-
if (preparation)
|
|
197
|
+
if (preparation)
|
|
197
198
|
return preparation;
|
|
198
|
-
}
|
|
199
199
|
const applied = await applyResponse(input, state, response);
|
|
200
200
|
if (applied.kind !== "applied") {
|
|
201
201
|
return applied;
|
|
@@ -221,6 +221,28 @@ export async function loadLocalOrganizationDirectoryAndGroups(input) {
|
|
|
221
221
|
export async function loadLocalOrganizationGroupMembers(input) {
|
|
222
222
|
return runOrganizationPresentationRead(organizationPresentationAccessInput(input), "readModel", () => new OrganizationReadModelRepository(input.execSql).loadOrganizationReadModelGroupMembers(input.organizationId, input.groupId, input.currentUserId));
|
|
223
223
|
}
|
|
224
|
+
/**
|
|
225
|
+
* Apply one page as a feed read from `requestedCursor` returns it, with no
|
|
226
|
+
* request, while the projection still holds that cursor. Resolves `undefined`
|
|
227
|
+
* when it is not applied; it is never retried.
|
|
228
|
+
*/
|
|
229
|
+
export async function applyOrganizationReadModelPageAt(input) {
|
|
230
|
+
const accessAttempt = captureOrganizationPresentationAccessAttempt(organizationPresentationAccessInput(input), "readModel");
|
|
231
|
+
const projection = await loadProjection(input);
|
|
232
|
+
if (projection?.cursor !== input.requestedCursor)
|
|
233
|
+
return undefined;
|
|
234
|
+
const applied = await applyReadModelPage(input, {
|
|
235
|
+
accessAttempt,
|
|
236
|
+
expectedLocalCursor: projection.cursor,
|
|
237
|
+
preparedDeniedProjection: true,
|
|
238
|
+
projection,
|
|
239
|
+
requestCursor: projection.cursor,
|
|
240
|
+
retriedBindingFailure: true,
|
|
241
|
+
retriedInvalidCursor: true,
|
|
242
|
+
staleRetries: MAX_STALE_RETRIES,
|
|
243
|
+
}, input.response);
|
|
244
|
+
return applied.kind === "done" ? applied.value : undefined;
|
|
245
|
+
}
|
|
224
246
|
/**
|
|
225
247
|
* Resolves the reconciled projection, `null` when the pass completed
|
|
226
248
|
* authoritatively with nothing presentable (including a denial that purged
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"readModelProjection.js","sourceRoot":"","sources":["readModelProjection.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,mCAAmC,GAEpC,MAAM,gCAAgC,CAAC;AAExC,OAAO,EAAE,iCAAiC,EAAE,MAAM,oFAAoF,CAAC;AAKvI,OAAO,EAAE,+BAA+B,EAAE,MAAM,yEAAyE,CAAC;AAG1H,OAAO,EACL,4CAA4C,EAC5C,kCAAkC,EAClC,8CAA8C,EAC9C,wCAAwC,EAGxC,qCAAqC,EACrC,mCAAmC,EACnC,+BAA+B,GAChC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,6CAA6C,EAAE,MAAM,oCAAoC,CAAC;AAEnG,MAAM,oBAAoB,GAAG,GAAG,CAAC;AACjC,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAwB5B,SAAS,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AAC;QACvB,CAAC;QACD,IAAI,OAAO,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;YAChC,SAAS;QACX,CAAC;QACD,MAAM,OAAO,GAAG,MAAM,kBAAkB,CAAC,KAAK,EAAE,KAAK,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC;QACzE,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YAC5B,OAAO,OAAO,CAAC,KAAK,CAAC;QACvB,CAAC;IACH,CAAC;IAED,KAAK,CAAC,QAAQ,EAAE,CACd,4DAA4D,CAC7D,CAAC;IACF,MAAM,QAAQ,GAAG,WAAW,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7D,OAAO,QAAQ,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;AAC1D,CAAC","sourcesContent":["import type {\n RequestResult,\n RequestResultOptions,\n} from \"@tearleads/api-client\";\nimport {\n ORGANIZATION_READ_MODEL_ERROR_CODES,\n type OrganizationReadModelResponse,\n} from \"@tearleads/validators/response\";\nimport type { OrganizationReadModelGroupMembers } from \"../../../data/persistence/organizations/organizationReadModelMemberLoad\";\nimport { OrganizationReadModelBindingError } from \"../../../data/persistence/organizations/organizationReadModelMembershipPersistence\";\nimport type {\n ApplyOrganizationReadModelResponseResult,\n OrganizationReadModelProjection,\n} from \"../../../data/persistence/organizations/organizationReadModelPersistence\";\nimport { OrganizationReadModelRepository } from \"../../../data/persistence/organizations/organizationReadModelRepository\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { OrganizationDirectoryAndGroups } from \"./index\";\nimport {\n captureOrganizationPresentationAccessAttempt,\n denyOrganizationPresentationAccess,\n isOrganizationPresentationAccessAttemptCurrent,\n isOrganizationPresentationAccessReadable,\n type OrganizationPresentationAccessAttempt,\n type OrganizationPresentationAccessInput,\n restoreOrganizationPresentationAccess,\n runOrganizationPresentationMutation,\n runOrganizationPresentationRead,\n} from \"./organizationPresentationAccessState\";\nimport { isOrganizationPresentationAccessDeniedFailure } from \"./organizationPresentationFailures\";\n\nconst MAX_READ_MODEL_PAGES = 100;\nconst MAX_STALE_RETRIES = 1;\n\ninterface OrganizationReadModelApi {\n getOrganizationReadModelResult(\n organizationId: string,\n cursor?: string,\n options?: RequestResultOptions,\n ): Promise<RequestResult<OrganizationReadModelResponse>>;\n}\n\ninterface OrganizationReadModelProjectionInput {\n readonly currentUserId: string;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n}\n\nexport interface ReconcileOrganizationDirectoryAndGroupsInput\n extends OrganizationReadModelProjectionInput {\n readonly apiClient: OrganizationReadModelApi;\n readonly logError?:\n | ((message: string | Error, cause?: unknown) => void)\n | undefined;\n}\n\nfunction toDirectoryAndGroups(\n projection: OrganizationReadModelProjection | null,\n): OrganizationDirectoryAndGroups | null {\n if (!projection?.requester) {\n return null;\n }\n\n return {\n directory: {\n ...projection.directory,\n currentUser: projection.requester,\n },\n // Hydration decides whether a name is unreadable; a stored blank name may\n // only mean the group has not been hydrated yet.\n groups: projection.groups.groups.map((group) => ({\n ...group,\n nameUnreadable: false,\n })),\n memberGroupId: projection.groups.memberGroupId,\n readModelCursor: projection.cursor,\n };\n}\n\nasync function loadProjection(\n input: OrganizationReadModelProjectionInput,\n): Promise<OrganizationReadModelProjection | null> {\n return runOrganizationPresentationRead(\n organizationPresentationAccessInput(input),\n \"readModel\",\n () => loadRawProjection(input),\n );\n}\n\nfunction loadRawProjection(\n input: OrganizationReadModelProjectionInput,\n): Promise<OrganizationReadModelProjection | null> {\n return new OrganizationReadModelRepository(\n input.execSql,\n ).loadOrganizationReadModelProjection(\n input.organizationId,\n input.currentUserId,\n );\n}\n\nfunction organizationPresentationAccessInput(\n input: OrganizationReadModelProjectionInput,\n): OrganizationPresentationAccessInput {\n return {\n execSql: input.execSql,\n organizationId: input.organizationId,\n requesterUserId: input.currentUserId,\n };\n}\n\ninterface ReconciliationState {\n readonly accessAttempt: OrganizationPresentationAccessAttempt;\n expectedLocalCursor: string | null;\n preparedDeniedProjection: boolean;\n projection: OrganizationReadModelProjection | null;\n requestCursor: string | undefined;\n retriedBindingFailure: boolean;\n retriedInvalidCursor: boolean;\n staleRetries: number;\n}\n\ntype ReconciliationStep =\n | { readonly kind: \"continue\" }\n | {\n readonly kind: \"done\";\n readonly value: OrganizationDirectoryAndGroups | null | undefined;\n };\n\ntype PageRequestStep =\n | ReconciliationStep\n | {\n readonly kind: \"response\";\n readonly response: OrganizationReadModelResponse;\n };\n\nfunction localResult(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n outcome: { readonly failed: boolean },\n): ReconciliationStep {\n const accessInput = organizationPresentationAccessInput(input);\n const readable =\n isOrganizationPresentationAccessAttemptCurrent(\n accessInput,\n state.accessAttempt,\n ) && isOrganizationPresentationAccessReadable(accessInput, \"readModel\");\n if (!readable) {\n return { kind: \"done\", value: null };\n }\n // Retained rows are available through the local loader, but are not proof\n // that this pass caught up. Returning them after a failed post-commit read\n // makes mutation callers skip their retry and repaint pre-mutation status.\n if (outcome.failed) {\n return { kind: \"done\", value: undefined };\n }\n return { kind: \"done\", value: toDirectoryAndGroups(state.projection) };\n}\n\nfunction resetRequestCursor(state: ReconciliationState): void {\n state.expectedLocalCursor = state.projection?.cursor ?? null;\n state.requestCursor = state.projection?.cursor ?? undefined;\n}\n\n/** Replays a page that applied stale, up to the retry budget. */\nfunction retryStaleApply(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n): ReconciliationStep {\n if (state.staleRetries >= MAX_STALE_RETRIES) {\n return localResult(input, state, { failed: true });\n }\n state.staleRetries += 1;\n resetRequestCursor(state);\n return { kind: \"continue\" };\n}\n\nfunction isInvalidReadModelCursorFailure(\n result: RequestResult<OrganizationReadModelResponse>,\n): boolean {\n return (\n !result.ok &&\n result.kind === \"http\" &&\n result.status === 400 &&\n result.code === ORGANIZATION_READ_MODEL_ERROR_CODES.cursorInvalid\n );\n}\n\nasync function requestReadModelPage(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n): Promise<PageRequestStep> {\n const result = await input.apiClient.getOrganizationReadModelResult(\n input.organizationId,\n state.requestCursor,\n { reportErrors: false },\n );\n if (result.ok) {\n return { kind: \"response\", response: result.data };\n }\n if (isOrganizationPresentationAccessDeniedFailure(result)) {\n const accessInput = organizationPresentationAccessInput(input);\n denyOrganizationPresentationAccess(accessInput, [\"readModel\", \"usage\"]);\n const repository = new OrganizationReadModelRepository(input.execSql);\n // The durable marker lands before the purge attempt: if the purge fails,\n // an offline restart must still refuse to serve the revoked projection.\n try {\n await runOrganizationPresentationMutation(input.execSql, () =>\n repository.recordOrganizationPresentationDenials(accessInput, [\n \"readModel\",\n \"usage\",\n ]),\n );\n } catch (error) {\n input.logError?.(\"Failed to record denied organization access\", error);\n }\n try {\n await runOrganizationPresentationMutation(input.execSql, () =>\n repository.purgeOrganizationAccessProjection({\n organizationId: input.organizationId,\n requesterUserId: input.currentUserId,\n }),\n );\n } catch (error) {\n input.logError?.(\"Failed to purge denied organization access\", error);\n }\n return { kind: \"done\", value: null };\n }\n if (\n isInvalidReadModelCursorFailure(result) &&\n state.requestCursor !== undefined &&\n !state.retriedInvalidCursor\n ) {\n state.requestCursor = undefined;\n state.retriedInvalidCursor = true;\n return { kind: \"continue\" };\n }\n\n result.report();\n return localResult(input, state, { failed: true });\n}\n\nfunction responseMatchesRequest(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n response: OrganizationReadModelResponse,\n): boolean {\n if (response.organizationId !== input.organizationId) {\n input.logError?.(\n `Organization read-model response scope does not match ${input.organizationId}`,\n );\n return false;\n }\n if (response.hasMore && response.nextCursor === state.expectedLocalCursor) {\n input.logError?.(\"Organization read-model page did not advance its cursor\");\n return false;\n }\n return true;\n}\n\nfunction reconciliationIsCurrent(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n): boolean {\n return isOrganizationPresentationAccessAttemptCurrent(\n organizationPresentationAccessInput(input),\n state.accessAttempt,\n );\n}\n\ntype ApplyResponseStep =\n | ReconciliationStep\n | {\n readonly kind: \"applied\";\n readonly result: ApplyOrganizationReadModelResponseResult;\n };\n\nasync function applyResponse(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n response: OrganizationReadModelResponse,\n): Promise<ApplyResponseStep> {\n const repository = new OrganizationReadModelRepository(input.execSql);\n try {\n return {\n kind: \"applied\",\n result: await repository.applyOrganizationReadModelResponse({\n currentUserId: input.currentUserId,\n requestedCursor: state.expectedLocalCursor,\n response,\n }),\n };\n } catch (error) {\n input.logError?.(\"Failed to apply organization read-model response\", error);\n if (\n !(error instanceof OrganizationReadModelBindingError) ||\n state.retriedBindingFailure\n ) {\n return localResult(input, state, { failed: true });\n }\n state.retriedBindingFailure = true;\n await repository.purgeOrganizationReadModelProjection(input.organizationId);\n if (!reconciliationIsCurrent(input, state)) {\n return { kind: \"done\", value: null };\n }\n state.projection = null;\n resetRequestCursor(state);\n return { kind: \"continue\" };\n }\n}\n\nasync function prepareDeniedProjectionForApply(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n): Promise<ReconciliationStep | null> {\n if (state.preparedDeniedProjection) {\n return null;\n }\n try {\n // The apply that follows replaces the shared rows authoritatively, so\n // only this requester's row is dropped: another local identity sharing\n // the database keeps its access and reads the replacement.\n await new OrganizationReadModelRepository(\n input.execSql,\n ).purgeOrganizationReadModelProjection(input.organizationId, {\n onlyRequesterUserId: input.currentUserId,\n });\n } catch (error) {\n input.logError?.(\"Failed to replace denied organization read model\", error);\n return { kind: \"done\", value: null };\n }\n if (!reconciliationIsCurrent(input, state)) {\n return { kind: \"done\", value: null };\n }\n state.expectedLocalCursor = null;\n state.preparedDeniedProjection = true;\n state.projection = null;\n return null;\n}\n\n/** The last page settles only if presentation access is still restorable. */\nfunction finalPageStep(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n accessInput: OrganizationPresentationAccessInput,\n): ReconciliationStep {\n return restoreOrganizationPresentationAccess(accessInput, state.accessAttempt)\n ? localResult(input, state, { failed: false })\n : { kind: \"done\", value: null };\n}\n\nasync function applyReadModelPage(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n response: OrganizationReadModelResponse,\n): Promise<ReconciliationStep> {\n if (!responseMatchesRequest(input, state, response)) {\n return localResult(input, state, { failed: true });\n }\n\n const accessInput = organizationPresentationAccessInput(input);\n return runOrganizationPresentationMutation(input.execSql, async () => {\n if (!reconciliationIsCurrent(input, state)) {\n return { kind: \"done\", value: null };\n }\n const preparation = await prepareDeniedProjectionForApply(input, state);\n if (preparation) {\n return preparation;\n }\n\n const applied = await applyResponse(input, state, response);\n if (applied.kind !== \"applied\") {\n return applied;\n }\n\n state.projection = await loadRawProjection(input);\n if (!reconciliationIsCurrent(input, state)) {\n return { kind: \"done\", value: null };\n }\n if (applied.result === \"stale\") {\n return retryStaleApply(input, state);\n }\n\n state.expectedLocalCursor = state.projection?.cursor ?? response.nextCursor;\n if (!response.hasMore) {\n return finalPageStep(input, state, accessInput);\n }\n state.requestCursor = response.nextCursor;\n return { kind: \"continue\" };\n });\n}\n\nexport async function loadLocalOrganizationDirectoryAndGroups(\n input: OrganizationReadModelProjectionInput,\n): Promise<OrganizationDirectoryAndGroups | null> {\n return toDirectoryAndGroups(await loadProjection(input));\n}\n\nexport async function loadLocalOrganizationGroupMembers(\n input: OrganizationReadModelProjectionInput & { readonly groupId: string },\n): Promise<OrganizationReadModelGroupMembers | null> {\n return runOrganizationPresentationRead(\n organizationPresentationAccessInput(input),\n \"readModel\",\n () =>\n new OrganizationReadModelRepository(\n input.execSql,\n ).loadOrganizationReadModelGroupMembers(\n input.organizationId,\n input.groupId,\n input.currentUserId,\n ),\n );\n}\n\n/**\n * Resolves the reconciled projection, `null` when the pass completed\n * authoritatively with nothing presentable (including a denial that purged\n * the projection), or `undefined` when the feed failed — even when local\n * rows remain available. A failed pass must not count as caught up.\n */\nexport async function reconcileOrganizationDirectoryAndGroups(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const accessInput = organizationPresentationAccessInput(input);\n const accessAttempt = captureOrganizationPresentationAccessAttempt(\n accessInput,\n \"readModel\",\n );\n const state: ReconciliationState = {\n accessAttempt,\n expectedLocalCursor: null,\n preparedDeniedProjection: !accessAttempt.startedDenied,\n projection: await loadProjection(input),\n requestCursor: undefined,\n retriedBindingFailure: false,\n retriedInvalidCursor: false,\n staleRetries: 0,\n };\n resetRequestCursor(state);\n\n for (let page = 0; page < MAX_READ_MODEL_PAGES; page += 1) {\n const request = await requestReadModelPage(input, state);\n if (request.kind === \"done\") {\n return request.value;\n }\n if (request.kind === \"continue\") {\n continue;\n }\n const applied = await applyReadModelPage(input, state, request.response);\n if (applied.kind === \"done\") {\n return applied.value;\n }\n }\n\n input.logError?.(\n \"Organization read-model reconciliation exceeded page limit\",\n );\n const retained = localResult(input, state, { failed: true });\n return retained.kind === \"done\" ? retained.value : null;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"readModelProjection.js","sourceRoot":"","sources":["readModelProjection.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,mCAAmC,GAEpC,MAAM,gCAAgC,CAAC;AAExC,OAAO,EAAE,iCAAiC,EAAE,MAAM,oFAAoF,CAAC;AAKvI,OAAO,EAAE,+BAA+B,EAAE,MAAM,yEAAyE,CAAC;AAG1H,OAAO,EACL,4CAA4C,EAC5C,kCAAkC,EAClC,8CAA8C,EAC9C,wCAAwC,EAGxC,qCAAqC,EACrC,mCAAmC,EACnC,+BAA+B,GAChC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,6CAA6C,EAAE,MAAM,oCAAoC,CAAC;AAEnG,MAAM,oBAAoB,GAAG,GAAG,CAAC;AACj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,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7D,OAAO,QAAQ,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;AAC1D,CAAC","sourcesContent":["import type {\n RequestResult,\n RequestResultOptions,\n} from \"@tearleads/api-client\";\nimport {\n ORGANIZATION_READ_MODEL_ERROR_CODES,\n type OrganizationReadModelResponse,\n} from \"@tearleads/validators/response\";\nimport type { OrganizationReadModelGroupMembers } from \"../../../data/persistence/organizations/organizationReadModelMemberLoad\";\nimport { OrganizationReadModelBindingError } from \"../../../data/persistence/organizations/organizationReadModelMembershipPersistence\";\nimport type {\n ApplyOrganizationReadModelResponseResult,\n OrganizationReadModelProjection,\n} from \"../../../data/persistence/organizations/organizationReadModelPersistence\";\nimport { OrganizationReadModelRepository } from \"../../../data/persistence/organizations/organizationReadModelRepository\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { OrganizationDirectoryAndGroups } from \"./index\";\nimport {\n captureOrganizationPresentationAccessAttempt,\n denyOrganizationPresentationAccess,\n isOrganizationPresentationAccessAttemptCurrent,\n isOrganizationPresentationAccessReadable,\n type OrganizationPresentationAccessAttempt,\n type OrganizationPresentationAccessInput,\n restoreOrganizationPresentationAccess,\n runOrganizationPresentationMutation,\n runOrganizationPresentationRead,\n} from \"./organizationPresentationAccessState\";\nimport { isOrganizationPresentationAccessDeniedFailure } from \"./organizationPresentationFailures\";\n\nconst MAX_READ_MODEL_PAGES = 100;\nconst MAX_STALE_RETRIES = 1;\n\ninterface OrganizationReadModelApi {\n getOrganizationReadModelResult(\n organizationId: string,\n cursor?: string,\n options?: RequestResultOptions,\n ): Promise<RequestResult<OrganizationReadModelResponse>>;\n}\n\ninterface OrganizationReadModelProjectionInput {\n readonly currentUserId: string;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n}\n\n/** Applying a page needs no API; `stillCurrent` is rechecked in the write. */\ninterface ApplyReadModelPageInput extends OrganizationReadModelProjectionInput {\n readonly logError?:\n | ((message: string | Error, cause?: unknown) => void)\n | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface ReconcileOrganizationDirectoryAndGroupsInput\n extends ApplyReadModelPageInput {\n readonly apiClient: OrganizationReadModelApi;\n}\n\nfunction toDirectoryAndGroups(\n projection: OrganizationReadModelProjection | null,\n): OrganizationDirectoryAndGroups | null {\n if (!projection?.requester) {\n return null;\n }\n\n return {\n directory: {\n ...projection.directory,\n currentUser: projection.requester,\n },\n // Hydration decides whether a name is unreadable; a stored blank name may\n // only mean the group has not been hydrated yet.\n groups: projection.groups.groups.map((group) => ({\n ...group,\n nameUnreadable: false,\n })),\n memberGroupId: projection.groups.memberGroupId,\n readModelCursor: projection.cursor,\n };\n}\n\nasync function loadProjection(\n input: OrganizationReadModelProjectionInput,\n): Promise<OrganizationReadModelProjection | null> {\n return runOrganizationPresentationRead(\n organizationPresentationAccessInput(input),\n \"readModel\",\n () => loadRawProjection(input),\n );\n}\n\nfunction loadRawProjection(\n input: OrganizationReadModelProjectionInput,\n): Promise<OrganizationReadModelProjection | null> {\n return new OrganizationReadModelRepository(\n input.execSql,\n ).loadOrganizationReadModelProjection(\n input.organizationId,\n input.currentUserId,\n );\n}\n\nfunction organizationPresentationAccessInput(\n input: OrganizationReadModelProjectionInput,\n): OrganizationPresentationAccessInput {\n return {\n execSql: input.execSql,\n organizationId: input.organizationId,\n requesterUserId: input.currentUserId,\n };\n}\n\ninterface ReconciliationState {\n readonly accessAttempt: OrganizationPresentationAccessAttempt;\n expectedLocalCursor: string | null;\n preparedDeniedProjection: boolean;\n projection: OrganizationReadModelProjection | null;\n requestCursor: string | undefined;\n retriedBindingFailure: boolean;\n retriedInvalidCursor: boolean;\n staleRetries: number;\n}\n\ntype ReconciliationStep =\n | { readonly kind: \"continue\" }\n | {\n readonly kind: \"done\";\n readonly value: OrganizationDirectoryAndGroups | null | undefined;\n };\n\ntype PageRequestStep =\n | ReconciliationStep\n | {\n readonly kind: \"response\";\n readonly response: OrganizationReadModelResponse;\n };\n\nfunction localResult(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n outcome: { readonly failed: boolean },\n): ReconciliationStep {\n const accessInput = organizationPresentationAccessInput(input);\n const readable =\n isOrganizationPresentationAccessAttemptCurrent(\n accessInput,\n state.accessAttempt,\n ) && isOrganizationPresentationAccessReadable(accessInput, \"readModel\");\n if (!readable) {\n return { kind: \"done\", value: null };\n }\n // Retained rows are available through the local loader, but are not proof\n // that this pass caught up. Returning them after a failed post-commit read\n // makes mutation callers skip their retry and repaint pre-mutation status.\n if (outcome.failed) {\n return { kind: \"done\", value: undefined };\n }\n return { kind: \"done\", value: toDirectoryAndGroups(state.projection) };\n}\n\nfunction resetRequestCursor(state: ReconciliationState): void {\n state.expectedLocalCursor = state.projection?.cursor ?? null;\n state.requestCursor = state.projection?.cursor ?? undefined;\n}\n\n/** Replays a page that applied stale, up to the retry budget. */\nfunction retryStaleApply(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n): ReconciliationStep {\n if (state.staleRetries >= MAX_STALE_RETRIES) {\n return localResult(input, state, { failed: true });\n }\n state.staleRetries += 1;\n resetRequestCursor(state);\n return { kind: \"continue\" };\n}\n\nfunction isInvalidReadModelCursorFailure(\n result: RequestResult<OrganizationReadModelResponse>,\n): boolean {\n return (\n !result.ok &&\n result.kind === \"http\" &&\n result.status === 400 &&\n result.code === ORGANIZATION_READ_MODEL_ERROR_CODES.cursorInvalid\n );\n}\n\nasync function requestReadModelPage(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n): Promise<PageRequestStep> {\n const result = await input.apiClient.getOrganizationReadModelResult(\n input.organizationId,\n state.requestCursor,\n { reportErrors: false },\n );\n if (result.ok) {\n return { kind: \"response\", response: result.data };\n }\n if (isOrganizationPresentationAccessDeniedFailure(result)) {\n const accessInput = organizationPresentationAccessInput(input);\n denyOrganizationPresentationAccess(accessInput, [\"readModel\", \"usage\"]);\n const repository = new OrganizationReadModelRepository(input.execSql);\n // The durable marker lands before the purge attempt: if the purge fails,\n // an offline restart must still refuse to serve the revoked projection.\n try {\n await runOrganizationPresentationMutation(input.execSql, () =>\n repository.recordOrganizationPresentationDenials(accessInput, [\n \"readModel\",\n \"usage\",\n ]),\n );\n } catch (error) {\n input.logError?.(\"Failed to record denied organization access\", error);\n }\n try {\n await runOrganizationPresentationMutation(input.execSql, () =>\n repository.purgeOrganizationAccessProjection({\n organizationId: input.organizationId,\n requesterUserId: input.currentUserId,\n }),\n );\n } catch (error) {\n input.logError?.(\"Failed to purge denied organization access\", error);\n }\n return { kind: \"done\", value: null };\n }\n if (\n isInvalidReadModelCursorFailure(result) &&\n state.requestCursor !== undefined &&\n !state.retriedInvalidCursor\n ) {\n state.requestCursor = undefined;\n state.retriedInvalidCursor = true;\n return { kind: \"continue\" };\n }\n\n result.report();\n return localResult(input, state, { failed: true });\n}\n\nfunction responseMatchesRequest(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n response: OrganizationReadModelResponse,\n): boolean {\n if (response.organizationId !== input.organizationId) {\n input.logError?.(\n `Organization read-model response scope does not match ${input.organizationId}`,\n );\n return false;\n }\n if (response.hasMore && response.nextCursor === state.expectedLocalCursor) {\n input.logError?.(\"Organization read-model page did not advance its cursor\");\n return false;\n }\n return true;\n}\n\nfunction reconciliationIsCurrent(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n): boolean {\n return isOrganizationPresentationAccessAttemptCurrent(\n organizationPresentationAccessInput(input),\n state.accessAttempt,\n );\n}\n\ntype ApplyResponseStep =\n | ReconciliationStep\n | {\n readonly kind: \"applied\";\n readonly result: ApplyOrganizationReadModelResponseResult;\n };\n\nasync function applyResponse(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n response: OrganizationReadModelResponse,\n): Promise<ApplyResponseStep> {\n const repository = new OrganizationReadModelRepository(input.execSql);\n try {\n return {\n kind: \"applied\",\n result: await repository.applyOrganizationReadModelResponse({\n canCommit: input.stillCurrent,\n currentUserId: input.currentUserId,\n requestedCursor: state.expectedLocalCursor,\n response,\n }),\n };\n } catch (error) {\n input.logError?.(\"Failed to apply organization read-model response\", error);\n if (\n !(error instanceof OrganizationReadModelBindingError) ||\n state.retriedBindingFailure\n ) {\n return localResult(input, state, { failed: true });\n }\n state.retriedBindingFailure = true;\n await repository.purgeOrganizationReadModelProjection(input.organizationId);\n if (!reconciliationIsCurrent(input, state)) {\n return { kind: \"done\", value: null };\n }\n state.projection = null;\n resetRequestCursor(state);\n return { kind: \"continue\" };\n }\n}\n\nasync function prepareDeniedProjectionForApply(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n): Promise<ReconciliationStep | null> {\n if (state.preparedDeniedProjection) {\n return null;\n }\n try {\n // The apply that follows replaces the shared rows authoritatively, so\n // only this requester's row is dropped: another local identity sharing\n // the database keeps its access and reads the replacement.\n await new OrganizationReadModelRepository(\n input.execSql,\n ).purgeOrganizationReadModelProjection(input.organizationId, {\n onlyRequesterUserId: input.currentUserId,\n });\n } catch (error) {\n input.logError?.(\"Failed to replace denied organization read model\", error);\n return { kind: \"done\", value: null };\n }\n if (!reconciliationIsCurrent(input, state)) {\n return { kind: \"done\", value: null };\n }\n state.expectedLocalCursor = null;\n state.preparedDeniedProjection = true;\n state.projection = null;\n return null;\n}\n\n/** The last page settles only if presentation access is still restorable. */\nfunction finalPageStep(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n accessInput: OrganizationPresentationAccessInput,\n): ReconciliationStep {\n return restoreOrganizationPresentationAccess(accessInput, state.accessAttempt)\n ? localResult(input, state, { failed: false })\n : { kind: \"done\", value: null };\n}\n\nasync function applyReadModelPage(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n response: OrganizationReadModelResponse,\n): Promise<ReconciliationStep> {\n if (!responseMatchesRequest(input, state, response)) {\n return localResult(input, state, { failed: true });\n }\n\n const accessInput = organizationPresentationAccessInput(input);\n return runOrganizationPresentationMutation(input.execSql, async () => {\n if (\n !reconciliationIsCurrent(input, state) ||\n input.stillCurrent?.() === false\n )\n return { kind: \"done\", value: null };\n const preparation = await prepareDeniedProjectionForApply(input, state);\n if (preparation) return preparation;\n const applied = await applyResponse(input, state, response);\n if (applied.kind !== \"applied\") {\n return applied;\n }\n\n state.projection = await loadRawProjection(input);\n if (!reconciliationIsCurrent(input, state)) {\n return { kind: \"done\", value: null };\n }\n if (applied.result === \"stale\") {\n return retryStaleApply(input, state);\n }\n\n state.expectedLocalCursor = state.projection?.cursor ?? response.nextCursor;\n if (!response.hasMore) {\n return finalPageStep(input, state, accessInput);\n }\n state.requestCursor = response.nextCursor;\n return { kind: \"continue\" };\n });\n}\n\nexport async function loadLocalOrganizationDirectoryAndGroups(\n input: OrganizationReadModelProjectionInput,\n): Promise<OrganizationDirectoryAndGroups | null> {\n return toDirectoryAndGroups(await loadProjection(input));\n}\n\nexport async function loadLocalOrganizationGroupMembers(\n input: OrganizationReadModelProjectionInput & { readonly groupId: string },\n): Promise<OrganizationReadModelGroupMembers | null> {\n return runOrganizationPresentationRead(\n organizationPresentationAccessInput(input),\n \"readModel\",\n () =>\n new OrganizationReadModelRepository(\n input.execSql,\n ).loadOrganizationReadModelGroupMembers(\n input.organizationId,\n input.groupId,\n input.currentUserId,\n ),\n );\n}\n\n/**\n * Apply one page as a feed read from `requestedCursor` returns it, with no\n * request, while the projection still holds that cursor. Resolves `undefined`\n * when it is not applied; it is never retried.\n */\nexport async function applyOrganizationReadModelPageAt(\n input: ApplyReadModelPageInput & {\n readonly requestedCursor: string;\n readonly response: OrganizationReadModelResponse;\n },\n): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const accessAttempt = captureOrganizationPresentationAccessAttempt(\n organizationPresentationAccessInput(input),\n \"readModel\",\n );\n const projection = await loadProjection(input);\n if (projection?.cursor !== input.requestedCursor) return undefined;\n const applied = await applyReadModelPage(\n input,\n {\n accessAttempt,\n expectedLocalCursor: projection.cursor,\n preparedDeniedProjection: true,\n projection,\n requestCursor: projection.cursor,\n retriedBindingFailure: true,\n retriedInvalidCursor: true,\n staleRetries: MAX_STALE_RETRIES,\n },\n input.response,\n );\n return applied.kind === \"done\" ? applied.value : undefined;\n}\n\n/**\n * Resolves the reconciled projection, `null` when the pass completed\n * authoritatively with nothing presentable (including a denial that purged\n * the projection), or `undefined` when the feed failed — even when local\n * rows remain available. A failed pass must not count as caught up.\n */\nexport async function reconcileOrganizationDirectoryAndGroups(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const accessInput = organizationPresentationAccessInput(input);\n const accessAttempt = captureOrganizationPresentationAccessAttempt(\n accessInput,\n \"readModel\",\n );\n const state: ReconciliationState = {\n accessAttempt,\n expectedLocalCursor: null,\n preparedDeniedProjection: !accessAttempt.startedDenied,\n projection: await loadProjection(input),\n requestCursor: undefined,\n retriedBindingFailure: false,\n retriedInvalidCursor: false,\n staleRetries: 0,\n };\n resetRequestCursor(state);\n\n for (let page = 0; page < MAX_READ_MODEL_PAGES; page += 1) {\n const request = await requestReadModelPage(input, state);\n if (request.kind === \"done\") {\n return request.value;\n }\n if (request.kind === \"continue\") {\n continue;\n }\n const applied = await applyReadModelPage(input, state, request.response);\n if (applied.kind === \"done\") {\n return applied.value;\n }\n }\n\n input.logError?.(\n \"Organization read-model reconciliation exceeded page limit\",\n );\n const retained = localResult(input, state, { failed: true });\n return retained.kind === \"done\" ? retained.value : null;\n}\n"]}
|
|
@@ -44,19 +44,6 @@ function getBundleReferenceFailure(reference, bundle) {
|
|
|
44
44
|
message: "member envelope epoch does not match current principal",
|
|
45
45
|
};
|
|
46
46
|
}
|
|
47
|
-
if (bundle.currentPayload.principalType !== bundle.currentState.principalType ||
|
|
48
|
-
bundle.currentPayload.principalId !== bundle.currentState.principalId) {
|
|
49
|
-
return {
|
|
50
|
-
code: "object_mismatch",
|
|
51
|
-
message: "payload principal does not match current principal",
|
|
52
|
-
};
|
|
53
|
-
}
|
|
54
|
-
if (bundle.currentPayload.stateHash !== bundle.currentState.stateHash) {
|
|
55
|
-
return {
|
|
56
|
-
code: "hash_mismatch",
|
|
57
|
-
message: "payload state hash does not match current principal",
|
|
58
|
-
};
|
|
59
|
-
}
|
|
60
47
|
return null;
|
|
61
48
|
}
|
|
62
49
|
function getCheckpointFailure(checkpoint, bundle) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalPolicyCacheValidation.js","sourceRoot":"","sources":["principalPolicyCacheValidation.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EACL,+BAA+B,EAC/B,yDAAyD,GAC1D,MAAM,8DAA8D,CAAC;AACtE,OAAO,EACL,sCAAsC,EAEtC,qBAAqB,GACtB,MAAM,sDAAsD,CAAC;AAC9D,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AASlG,SAAS,yBAAyB,CAChC,SAA2C,EAC3C,MAAqC;IAErC,MAAM,MAAM,GAAG,qBAAqB,CAAC,MAAM,CAAC,CAAC;IAC7C,MAAM,sBAAsB,GAAG,MAAM,CAAC,IAAI,CACxC,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,aAAa,KAAK,SAAS,CAAC,aAAa;QAC/C,KAAK,CAAC,WAAW,KAAK,SAAS,CAAC,WAAW,CAC9C,CAAC;IACF,IAAI,CAAC,sBAAsB,EAAE,CAAC;QAC5B,OAAO;YACL,IAAI,EAAE,iBAAiB;YACvB,OAAO,EAAE,sDAAsD;SAChE,CAAC;IACJ,CAAC;IACD,IACE,CAAC,MAAM,CAAC,IAAI,CACV,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,aAAa,KAAK,SAAS,CAAC,aAAa;QAC/C,KAAK,CAAC,WAAW,KAAK,SAAS,CAAC,WAAW;QAC3C,KAAK,CAAC,OAAO,KAAK,SAAS,CAAC,OAAO;QACnC,KAAK,CAAC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AI,EAAE;YAChC,uBAAuB,GAAG,IAAI,CAAC;YAC/B,MAAM,SAAS,GAAG,CAAC,MAAM,KAAK,CAAC,uBAAuB,EAAE,CAAC;gBACvD,EAAE,iBAAiB,CAAC;YACtB,IAAI,SAAS;gBAAE,OAAO,SAAS,CAAC;YAChC,sEAAsE;YACtE,mEAAmE;YACnE,kEAAkE;YAClE,oEAAoE;YACpE,2DAA2D;YAC3D,IACE,MAAM,+BAA+B,CAAC;gBACpC,0BAA0B,EAAE,KAAK,CAAC,0BAA0B;gBAC5D,MAAM,EAAE,KAAK,CAAC,MAAM;gBACpB,iBAAiB,EAAE,KAAK,CAAC,SAAS;gBAClC,eAAe,EAAE,KAAK,CAAC,eAAe;gBACtC,gBAAgB,EAAE,gBAAgB,CAAC,gBAAgB;aACpD,CAAC,EACF,CAAC;gBACD,MAAM,IAAI,oCAAoC,CAC5C,6CAA6C,CAC9C,CAAC;YACJ,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC;QACD,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,gBAAgB,EAAE,gBAAgB,CAAC,gBAAgB;KACpD,CAAC,CAAC;IACL,IAAI,CAAC,QAAQ,CAAC,EAAE;QAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAC,KAAK,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;IAC9D,OAAO;QACL,mBAAmB,EAAE,uBAAuB;YAC1C,CAAC,CAAC,MAAM,KAAK,CAAC,uBAAuB,EAAE;YACvC,CAAC,CAAC,IAAI;QACR,EAAE,EAAE,IAAI;QACR,MAAM,EAAE,QAAQ,CAAC,KAAK;KACvB,CAAC;AACJ,CAAC","sourcesContent":["import {\n type KeyingVerificationCode,\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport {\n externalAuthorityCouldAuthorize,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n type PrincipalPolicySignerPublicKeyLoadErrorCode,\n principalPolicyStates,\n} from \"../../../data/principals/principalPolicyVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { VerifiedExternalAdminPolicy } from \"../externalAdminPolicy\";\n\ninterface PrincipalPolicyValidationFailure {\n readonly code: KeyingVerificationCode;\n readonly message: string;\n}\n\nfunction getBundleReferenceFailure(\n reference: ReferencedPrincipalStateResponse,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n const states = principalPolicyStates(bundle);\n const hasReferencedPrincipal = states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId,\n );\n if (!hasReferencedPrincipal) {\n return {\n code: \"object_mismatch\",\n message: \"bundle principal does not match referenced principal\",\n };\n }\n if (\n !states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId &&\n state.version === reference.version &&\n state.keyEpoch === reference.keyEpoch &&\n state.stateHash === reference.stateHash &&\n state.keyFingerprint === reference.keyFingerprint,\n )\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"bundle chain does not contain referenced principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.principalType !==\n bundle.currentState.principalType ||\n bundle.currentMemberEnvelopes.principalId !==\n bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"member envelope principal does not match current principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.stateHash !== bundle.currentState.stateHash\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope state hash does not match current principal\",\n };\n }\n if (bundle.currentMemberEnvelopes.epoch !== bundle.currentState.keyEpoch) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope epoch does not match current principal\",\n };\n }\n if (\n bundle.currentPayload.principalType !== bundle.currentState.principalType ||\n bundle.currentPayload.principalId !== bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"payload principal does not match current principal\",\n };\n }\n if (bundle.currentPayload.stateHash !== bundle.currentState.stateHash) {\n return {\n code: \"hash_mismatch\",\n message: \"payload state hash does not match current principal\",\n };\n }\n return null;\n}\n\nfunction getCheckpointFailure(\n checkpoint: PrincipalPolicyCheckpoint | null,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n if (!checkpoint) {\n return null;\n }\n const current = bundle.currentState;\n if (current.version < checkpoint.version) {\n return {\n code: \"rollback\",\n message: \"principal policy state is older than the local checkpoint\",\n };\n }\n if (\n current.version === checkpoint.version &&\n current.stateHash !== checkpoint.stateHash\n ) {\n return {\n code: \"equivocation\",\n message: \"principal policy state conflicts with the local checkpoint\",\n };\n }\n if (current.version === checkpoint.version) {\n return null;\n }\n const checkpointState = principalPolicyStates(bundle).find(\n (state) => state.version === checkpoint.version,\n );\n return checkpointState?.stateHash === checkpoint.stateHash\n ? null\n : {\n code: \"stale_predecessor\",\n message: \"principal policy chain does not extend the local checkpoint\",\n };\n}\n\nfunction signerPublicKeyLoadFailure(\n code: PrincipalPolicySignerPublicKeyLoadErrorCode,\n): PrincipalPolicyValidationFailure {\n switch (code) {\n case \"fingerprint-mismatch\":\n return {\n code: \"signer_mismatch\",\n message: \"signer key fingerprint does not match state signer\",\n };\n case \"not-found\":\n // The identity source throws for transport failures, so an absent\n // signer here is the server asserting the cited user does not exist.\n return {\n code: \"missing_dependency\",\n message: \"signer identity is unknown to the server\",\n };\n }\n}\n\nfunction verificationError(\n failure: PrincipalPolicyValidationFailure,\n): KeyingVerificationError {\n return new KeyingVerificationError(failure.code, failure.message);\n}\n\nexport async function validatePrincipalPolicyBundleForCache(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>;\n readonly localCheckpoint: PrincipalPolicyCheckpoint | null;\n readonly reference: ReferencedPrincipalStateResponse;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** The cache operation's lifetime, checked inside every pin write. */\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<\n | {\n readonly externalAdminPolicy: VerifiedExternalAdminPolicy | null;\n readonly ok: true;\n readonly policy: VerifiedPrincipalPolicy;\n }\n | { readonly error: KeyingVerificationError; readonly ok: false }\n> {\n const referenceFailure = getBundleReferenceFailure(\n input.reference,\n input.bundle,\n );\n if (referenceFailure) {\n return { error: verificationError(referenceFailure), ok: false };\n }\n const checkpointFailure = getCheckpointFailure(\n input.localCheckpoint,\n input.bundle,\n );\n if (checkpointFailure) {\n return { error: verificationError(checkpointFailure), ok: false };\n }\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: input.bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n return {\n error: verificationError(\n signerPublicKeyLoadFailure(signerPublicKeys.error),\n ),\n ok: false,\n };\n }\n\n let usedExternalAdminPolicy = false;\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle: input.bundle,\n expectedReference: input.reference,\n loadExternalAuthority: async () => {\n usedExternalAdminPolicy = true;\n const authority = (await input.loadExternalAdminPolicy())\n ?.externalAuthority;\n if (authority) return authority;\n // The loader returns null when the organization's Admins policy could\n // not be fetched, and an honest server always serves it. When that\n // evidence is all the chain lacks, the gap is availability, not a\n // refused signer, so it must not surface as an incident. A chain no\n // evidence could authorize keeps its unauthorized refusal.\n if (\n await externalAuthorityCouldAuthorize({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n bundle: input.bundle,\n expectedReference: input.reference,\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n })\n ) {\n throw new ProjectionDependencyUnavailableError(\n \"Organization Admins evidence is unavailable\",\n );\n }\n return null;\n },\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) return { error: verified.error, ok: false };\n return {\n externalAdminPolicy: usedExternalAdminPolicy\n ? await input.loadExternalAdminPolicy()\n : null,\n ok: true,\n policy: verified.value,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"principalPolicyCacheValidation.js","sourceRoot":"","sources":["principalPolicyCacheValidation.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EACL,+BAA+B,EAC/B,yDAAyD,GAC1D,MAAM,8DAA8D,CAAC;AACtE,OAAO,EACL,sCAAsC,EAEtC,qBAAqB,GACtB,MAAM,sDAAsD,CAAC;AAC9D,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AASlG,SAAS,yBAAyB,CAChC,SAA2C,EAC3C,MAAqC;IAErC,MAAM,MAAM,GAAG,qBAAqB,CAAC,MAAM,CAAC,CAAC;IAC7C,MAAM,sBAAsB,GAAG,MAAM,CAAC,IAAI,CACxC,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,aAAa,KAAK,SAAS,CAAC,aAAa;QAC/C,KAAK,CAAC,WAAW,KAAK,SAAS,CAAC,WAAW,CAC9C,CAAC;IACF,IAAI,CAAC,sBAAsB,EAAE,CAAC;QAC5B,OAAO;YACL,IAAI,EAAE,iBAAiB;YACvB,OAAO,EAAE,sDAAsD;SAChE,CAAC;IACJ,CAAC;IACD,IACE,CAAC,MAAM,CAAC,IAAI,CACV,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,aAAa,KAAK,SAAS,CAAC,aAAa;QAC/C,KAAK,CAAC,WAAW,KAAK,SAAS,CAAC,WAAW;QAC3C,KAAK,CAAC,OAAO,KAAK,SAAS,CAAC,OAAO;QACnC,KAAK,CAAC,QAAQ,KAAK,SAAS,CAAC,QA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gBAAgB,EAAE,gBAAgB,CAAC,gBAAgB;aACpD,CAAC,EACF,CAAC;gBACD,MAAM,IAAI,oCAAoC,CAC5C,6CAA6C,CAC9C,CAAC;YACJ,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC;QACD,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,gBAAgB,EAAE,gBAAgB,CAAC,gBAAgB;KACpD,CAAC,CAAC;IACL,IAAI,CAAC,QAAQ,CAAC,EAAE;QAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAC,KAAK,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;IAC9D,OAAO;QACL,mBAAmB,EAAE,uBAAuB;YAC1C,CAAC,CAAC,MAAM,KAAK,CAAC,uBAAuB,EAAE;YACvC,CAAC,CAAC,IAAI;QACR,EAAE,EAAE,IAAI;QACR,MAAM,EAAE,QAAQ,CAAC,KAAK;KACvB,CAAC;AACJ,CAAC","sourcesContent":["import {\n type KeyingVerificationCode,\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport {\n externalAuthorityCouldAuthorize,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n type PrincipalPolicySignerPublicKeyLoadErrorCode,\n principalPolicyStates,\n} from \"../../../data/principals/principalPolicyVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { VerifiedExternalAdminPolicy } from \"../externalAdminPolicy\";\n\ninterface PrincipalPolicyValidationFailure {\n readonly code: KeyingVerificationCode;\n readonly message: string;\n}\n\nfunction getBundleReferenceFailure(\n reference: ReferencedPrincipalStateResponse,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n const states = principalPolicyStates(bundle);\n const hasReferencedPrincipal = states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId,\n );\n if (!hasReferencedPrincipal) {\n return {\n code: \"object_mismatch\",\n message: \"bundle principal does not match referenced principal\",\n };\n }\n if (\n !states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId &&\n state.version === reference.version &&\n state.keyEpoch === reference.keyEpoch &&\n state.stateHash === reference.stateHash &&\n state.keyFingerprint === reference.keyFingerprint,\n )\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"bundle chain does not contain referenced principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.principalType !==\n bundle.currentState.principalType ||\n bundle.currentMemberEnvelopes.principalId !==\n bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"member envelope principal does not match current principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.stateHash !== bundle.currentState.stateHash\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope state hash does not match current principal\",\n };\n }\n if (bundle.currentMemberEnvelopes.epoch !== bundle.currentState.keyEpoch) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope epoch does not match current principal\",\n };\n }\n return null;\n}\n\nfunction getCheckpointFailure(\n checkpoint: PrincipalPolicyCheckpoint | null,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n if (!checkpoint) {\n return null;\n }\n const current = bundle.currentState;\n if (current.version < checkpoint.version) {\n return {\n code: \"rollback\",\n message: \"principal policy state is older than the local checkpoint\",\n };\n }\n if (\n current.version === checkpoint.version &&\n current.stateHash !== checkpoint.stateHash\n ) {\n return {\n code: \"equivocation\",\n message: \"principal policy state conflicts with the local checkpoint\",\n };\n }\n if (current.version === checkpoint.version) {\n return null;\n }\n const checkpointState = principalPolicyStates(bundle).find(\n (state) => state.version === checkpoint.version,\n );\n return checkpointState?.stateHash === checkpoint.stateHash\n ? null\n : {\n code: \"stale_predecessor\",\n message: \"principal policy chain does not extend the local checkpoint\",\n };\n}\n\nfunction signerPublicKeyLoadFailure(\n code: PrincipalPolicySignerPublicKeyLoadErrorCode,\n): PrincipalPolicyValidationFailure {\n switch (code) {\n case \"fingerprint-mismatch\":\n return {\n code: \"signer_mismatch\",\n message: \"signer key fingerprint does not match state signer\",\n };\n case \"not-found\":\n // The identity source throws for transport failures, so an absent\n // signer here is the server asserting the cited user does not exist.\n return {\n code: \"missing_dependency\",\n message: \"signer identity is unknown to the server\",\n };\n }\n}\n\nfunction verificationError(\n failure: PrincipalPolicyValidationFailure,\n): KeyingVerificationError {\n return new KeyingVerificationError(failure.code, failure.message);\n}\n\nexport async function validatePrincipalPolicyBundleForCache(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>;\n readonly localCheckpoint: PrincipalPolicyCheckpoint | null;\n readonly reference: ReferencedPrincipalStateResponse;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** The cache operation's lifetime, checked inside every pin write. */\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<\n | {\n readonly externalAdminPolicy: VerifiedExternalAdminPolicy | null;\n readonly ok: true;\n readonly policy: VerifiedPrincipalPolicy;\n }\n | { readonly error: KeyingVerificationError; readonly ok: false }\n> {\n const referenceFailure = getBundleReferenceFailure(\n input.reference,\n input.bundle,\n );\n if (referenceFailure) {\n return { error: verificationError(referenceFailure), ok: false };\n }\n const checkpointFailure = getCheckpointFailure(\n input.localCheckpoint,\n input.bundle,\n );\n if (checkpointFailure) {\n return { error: verificationError(checkpointFailure), ok: false };\n }\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: input.bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n return {\n error: verificationError(\n signerPublicKeyLoadFailure(signerPublicKeys.error),\n ),\n ok: false,\n };\n }\n\n let usedExternalAdminPolicy = false;\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle: input.bundle,\n expectedReference: input.reference,\n loadExternalAuthority: async () => {\n usedExternalAdminPolicy = true;\n const authority = (await input.loadExternalAdminPolicy())\n ?.externalAuthority;\n if (authority) return authority;\n // The loader returns null when the organization's Admins policy could\n // not be fetched, and an honest server always serves it. When that\n // evidence is all the chain lacks, the gap is availability, not a\n // refused signer, so it must not surface as an incident. A chain no\n // evidence could authorize keeps its unauthorized refusal.\n if (\n await externalAuthorityCouldAuthorize({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n bundle: input.bundle,\n expectedReference: input.reference,\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n })\n ) {\n throw new ProjectionDependencyUnavailableError(\n \"Organization Admins evidence is unavailable\",\n );\n }\n return null;\n },\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) return { error: verified.error, ok: false };\n return {\n externalAdminPolicy: usedExternalAdminPolicy\n ? await input.loadExternalAdminPolicy()\n : null,\n ok: true,\n policy: verified.value,\n };\n}\n"]}
|