@tearleads/client-sdk 0.1.218 → 0.1.220
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/organizationGroupHistory.js +1 -1
- package/client/organizations/organizationGroupHistory.js.map +1 -1
- package/client/organizations/organizationGroupPresentation.js +1 -1
- package/client/organizations/organizationGroupPresentation.js.map +1 -1
- package/client/organizations/organizationHistory.js +1 -1
- package/client/organizations/organizationHistory.js.map +1 -1
- package/client/organizations/principalMutations.js +1 -1
- package/client/organizations/principalMutations.js.map +1 -1
- package/client/organizations/recipientAdmission.js +1 -1
- package/client/organizations/recipientAdmission.js.map +1 -1
- package/data/keyingProjectionVerification/checkpoints/bundleVerification.js +1 -1
- package/data/keyingProjectionVerification/checkpoints/bundleVerification.js.map +1 -1
- package/data/keyingProjectionVerification/checkpoints/checkpointContext.js +1 -1
- package/data/keyingProjectionVerification/checkpoints/checkpointContext.js.map +1 -1
- package/data/keyingProjectionVerification/container/containerProjectionVerification.js +1 -1
- package/data/keyingProjectionVerification/container/containerProjectionVerification.js.map +1 -1
- package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js +1 -1
- package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js.map +1 -1
- package/data/keyingProjectionVerification/documentPurge/documentPurgeDocumentChainVerification.js +1 -1
- package/data/keyingProjectionVerification/documentPurge/documentPurgeDocumentChainVerification.js.map +1 -1
- package/data/keyingProjectionVerification/error.js +1 -1
- package/data/keyingProjectionVerification/error.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicy/principalPolicySigners.js +1 -1
- package/data/keyingProjectionVerification/principalPolicy/principalPolicySigners.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicy/projectionPolicyEvidence.js +1 -1
- package/data/keyingProjectionVerification/principalPolicy/projectionPolicyEvidence.js.map +1 -1
- package/data/principals/principalIdentityCommitments.js +1 -1
- package/data/principals/principalIdentityCommitments.js.map +1 -1
- package/data/trustedUserIdentity/apiAdapter.js +1 -1
- package/data/trustedUserIdentity/apiAdapter.js.map +1 -1
- package/index.d.ts +2 -2
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/package.json +1 -1
- package/stores/documents/documentStore/history/historyRebuild.js.map +1 -1
- package/stores/documents/documentStore/rotation/index.js +10 -6
- package/stores/documents/documentStore/rotation/index.js.map +1 -1
- package/stores/documents/documentStore/sync/createdDocumentPersistence.js.map +1 -1
- package/stores/documents/documentStore/sync/syncRequest.js +9 -6
- package/stores/documents/documentStore/sync/syncRequest.js.map +1 -1
- package/stores/documents/documentStore/sync/syncShared.js +9 -6
- package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
- package/workflows/blobs/verification/attachmentDecryptor.js +1 -1
- package/workflows/blobs/verification/attachmentDecryptor.js.map +1 -1
- package/workflows/blobs/verification/verifiedWrapScope.js +1 -1
- package/workflows/blobs/verification/verifiedWrapScope.js.map +1 -1
- package/workflows/container-contents/container-state/create/createWithMetadataPlan.js +1 -1
- package/workflows/container-contents/container-state/create/createWithMetadataPlan.js.map +1 -1
- package/workflows/container-contents/container-state/remote.js +1 -1
- package/workflows/container-contents/container-state/remote.js.map +1 -1
- package/workflows/container-contents/container-state/share/groupGrantVerification.js +1 -1
- package/workflows/container-contents/container-state/share/groupGrantVerification.js.map +1 -1
- package/workflows/container-contents/container-state/share/groupShareEpoch.js +1 -1
- package/workflows/container-contents/container-state/share/groupShareEpoch.js.map +1 -1
- package/workflows/container-contents/container-state/types.js.map +1 -1
- package/workflows/container-contents/metadata/metadataRemoteSync.d.ts +4 -6
- package/workflows/container-contents/metadata/metadataRemoteSync.js +11 -7
- package/workflows/container-contents/metadata/metadataRemoteSync.js.map +1 -1
- package/workflows/container-contents/remoteHydration/destination/replacementBinding.js +1 -1
- package/workflows/container-contents/remoteHydration/destination/replacementBinding.js.map +1 -1
- package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +1 -1
- package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
- package/workflows/containers/child/revoke.js +1 -1
- package/workflows/containers/child/revoke.js.map +1 -1
- package/workflows/containers/child/share/index.js +1 -1
- package/workflows/containers/child/share/index.js.map +1 -1
- package/workflows/documents/create/createResponse.js +1 -1
- package/workflows/documents/create/createResponse.js.map +1 -1
- package/workflows/documents/create/index.d.ts +5 -42
- package/workflows/documents/create/index.js +12 -1
- package/workflows/documents/create/index.js.map +1 -1
- package/workflows/documents/create/remoteDocumentCreateRequest.d.ts +47 -0
- package/workflows/documents/create/remoteDocumentCreateRequest.js +2 -0
- package/workflows/documents/create/remoteDocumentCreateRequest.js.map +1 -0
- package/workflows/documents/index.d.ts +5 -4
- package/workflows/documents/index.js +1 -2
- package/workflows/documents/index.js.map +1 -1
- package/workflows/documents/linkSet/linkSetBlobRewraps.js +1 -1
- package/workflows/documents/linkSet/linkSetBlobRewraps.js.map +1 -1
- package/workflows/documents/purge/index.js +1 -1
- package/workflows/documents/purge/index.js.map +1 -1
- package/workflows/documents/remote/remoteDocumentCollaborators.d.ts +6 -4
- package/workflows/documents/remote/remoteDocumentCollaborators.js.map +1 -1
- package/workflows/documents/remote/remoteDocumentService.d.ts +12 -5
- package/workflows/documents/remote/remoteDocumentService.js +14 -4
- package/workflows/documents/remote/remoteDocumentService.js.map +1 -1
- package/workflows/documents/sync/index.js +18 -6
- package/workflows/documents/sync/index.js.map +1 -1
- package/workflows/documents/sync/readOnlySync.js.map +1 -1
- package/workflows/documents/sync/{readOnlySync.d.ts → remoteDocumentSyncPass.d.ts} +18 -18
- package/workflows/documents/sync/remoteDocumentSyncPass.js +2 -0
- package/workflows/documents/sync/remoteDocumentSyncPass.js.map +1 -0
- package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -1
- package/workflows/documents/sync/syncSubmittedResult.js.map +1 -1
- package/workflows/documents/syncFailures/syncAbandon.js.map +1 -1
- package/workflows/documents/syncFailures/syncFailureClassification.js +1 -1
- package/workflows/documents/syncFailures/syncFailureClassification.js.map +1 -1
- package/workflows/documents/syncFailures/syncRepairAccess.js.map +1 -1
- package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js.map +1 -1
- package/workflows/documents/syncRekeys/syncContainerRekeyPreparation.js +4 -3
- package/workflows/documents/syncRekeys/syncContainerRekeyPreparation.js.map +1 -1
- package/workflows/documents/syncRekeys/syncContainerRekeys.js.map +1 -1
- package/workflows/organizations/currentOrganizationAuthority.js +1 -1
- package/workflows/organizations/currentOrganizationAuthority.js.map +1 -1
- package/workflows/organizations/groupMetadata/currentGroupMetadataAuthority.js +1 -1
- package/workflows/organizations/groupMetadata/currentGroupMetadataAuthority.js.map +1 -1
- package/workflows/organizations/groupMetadata/groupMetadataRuntime.js +1 -1
- package/workflows/organizations/groupMetadata/groupMetadataRuntime.js.map +1 -1
- package/workflows/organizations/groupMetadata/runtimeGroupMetadataAuthority.js +1 -1
- package/workflows/organizations/groupMetadata/runtimeGroupMetadataAuthority.js.map +1 -1
- package/workflows/organizations/groupNames/organizationGroupNames.js +1 -1
- package/workflows/organizations/groupNames/organizationGroupNames.js.map +1 -1
- package/workflows/organizations/groupShare/groupShareReplan.js +1 -1
- package/workflows/organizations/groupShare/groupShareReplan.js.map +1 -1
- package/workflows/organizations/memberships/leaveRequestMembersEvidence.js +1 -1
- package/workflows/organizations/memberships/leaveRequestMembersEvidence.js.map +1 -1
- package/workflows/organizations/policyHistory/loadPolicyHistoryDetails.js +1 -1
- package/workflows/organizations/policyHistory/loadPolicyHistoryDetails.js.map +1 -1
- package/workflows/principals/policyCache/principalPolicyCacheValidation.js +1 -1
- package/workflows/principals/policyCache/principalPolicyCacheValidation.js.map +1 -1
- package/workflows/principals/principalPolicyService.js +1 -1
- package/workflows/principals/principalPolicyService.js.map +1 -1
- package/workflows/principals/recoveryOperation/principalRecoveryOutage.js +1 -1
- package/workflows/principals/recoveryOperation/principalRecoveryOutage.js.map +1 -1
- package/workflows/principals/runtimePolicyRecovery.js +1 -1
- package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
- package/workflows/principals/runtimeProjectionPolicyRecovery.js +1 -1
- package/workflows/principals/runtimeProjectionPolicyRecovery.js.map +1 -1
- package/workflows/documents/sync/index.d.ts +0 -3
- /package/data/{keyingProjectionVerification → shared}/dependencyUnavailable.js +0 -0
- /package/data/{keyingProjectionVerification → shared}/dependencyUnavailable.js.map +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { ProjectionDependencyUnavailableError } from "../../data/keyingProjectionVerification/dependencyUnavailable.js";
|
|
2
1
|
import { assertProjectionVerificationCurrent } from "../../data/keyingProjectionVerification/types.js";
|
|
2
|
+
import { ProjectionDependencyUnavailableError } from "../../data/shared/dependencyUnavailable.js";
|
|
3
3
|
import { loadLocalOrganizationPolicyReference } from "../../workflows/organizations/index.js";
|
|
4
4
|
import { buildOrganizationGroupPolicyHistoryPage } from "../../workflows/organizations/policyHistory/groupPolicyHistoryPage.js";
|
|
5
5
|
/** All group history reads use the private paged verifier. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"organizationGroupHistory.js","sourceRoot":"","sources":["organizationGroupHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"organizationGroupHistory.js","sourceRoot":"","sources":["organizationGroupHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,oCAAoC,EAAE,MAAM,yCAAyC,CAAC;AAC/F,OAAO,EAAE,oCAAoC,EAAE,MAAM,+BAA+B,CAAC;AACrF,OAAO,EAAE,uCAAuC,EAAE,MAAM,oEAAoE,CAAC;AAI7H,8DAA8D;AAC9D,MAAM,CAAC,KAAK,UAAU,mCAAmC,CAAC,KAKzD;IACC,MAAM,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;IACzB,MAAM,OAAO,GACX,MAAM,CAAC,OAAO,CAAC,iBAAiB,CAAC,2BAA2B,EAAE,CAAC;IACjE,IAAI,CAAC,OAAO;QACV,MAAM,IAAI,oCAAoC,CAC5C,+CAA+C,CAChD,CAAC;IACJ,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IACxD,MAAM,SAAS,GAAG,MAAM,oCAAoC,CAAC;QAC3D,aAAa,EAAE,MAAM,CAAC,MAAM;QAC5B,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO;QACrC,cAAc,EAAE,MAAM,CAAC,cAAc;QACrC,WAAW,EAAE,KAAK,CAAC,OAAO;QAC1B,aAAa,EAAE,OAAO;KACvB,CAAC,CAAC;IACH,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IACxD,IAAI,CAAC,SAAS;QAAE,OAAO,IAAI,CAAC;IAC5B,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC;QAC7B,cAAc,EAAE,MAAM,CAAC,cAAc;QACrC,SAAS;QACT,kBAAkB,EAAE,IAAI;QACxB,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,WAAW,EACT,KAAK,CAAC,aAAa,KAAK,SAAS;YAC/B,CAAC,CAAC,EAAE;YACJ,CAAC,CAAC,EAAE,aAAa,EAAE,KAAK,CAAC,aAAa,EAAE;KAC7C,CAAC,CAAC;IACH,mCAAmC,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;IAC3D,IAAI,CAAC,QAAQ,CAAC,WAAW;QACvB,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;IACtD,OAAO,uCAAuC,CAAC;QAC7C,IAAI,EAAE,QAAQ,CAAC,WAAW;QAC1B,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,cAAc,EAAE,MAAM,CAAC,cAAc;KACtC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/shared/dependencyUnavailable\";\nimport { loadLocalOrganizationPolicyReference } from \"../../workflows/organizations\";\nimport { buildOrganizationGroupPolicyHistoryPage } from \"../../workflows/organizations/policyHistory/groupPolicyHistoryPage\";\n\nimport type { ActiveOrganizationDataRuntime } from \"./organizationWorkflowRuntime\";\n\n/** All group history reads use the private paged verifier. */\nexport async function loadBoundedOrganizationGroupHistory(input: {\n readonly active: ActiveOrganizationDataRuntime;\n readonly groupId: string;\n readonly beforeVersion?: number | undefined;\n readonly stillCurrent: () => boolean;\n}) {\n const { active } = input;\n const resolve =\n active.runtime.principalPolicies.createCurrentPolicyResolver();\n if (!resolve)\n throw new ProjectionDependencyUnavailableError(\n \"Group history requires private paged recovery\",\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n const reference = await loadLocalOrganizationPolicyReference({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n principalId: input.groupId,\n principalType: \"group\",\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (!reference) return null;\n const resolved = await resolve({\n organizationId: active.organizationId,\n reference,\n preferLocalCurrent: true,\n stillCurrent: input.stillCurrent,\n historyPage:\n input.beforeVersion === undefined\n ? {}\n : { beforeVersion: input.beforeVersion },\n });\n assertProjectionVerificationCurrent(resolved.stillCurrent);\n if (!resolved.historyPage)\n throw new Error(\"Verified history page is missing\");\n return buildOrganizationGroupPolicyHistoryPage({\n page: resolved.historyPage,\n groupId: input.groupId,\n organizationId: active.organizationId,\n });\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ProjectionDependencyUnavailableError } from "../../data/
|
|
1
|
+
import { ProjectionDependencyUnavailableError } from "../../data/shared/dependencyUnavailable.js";
|
|
2
2
|
export async function loadOrganizationGroupPresentationDetails(input) {
|
|
3
3
|
const organizationId = input.runtime.auth.organizationId;
|
|
4
4
|
if (!input.runtime.auth.isAuthenticated ||
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"organizationGroupPresentation.js","sourceRoot":"","sources":["organizationGroupPresentation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oCAAoC,EAAE,MAAM
|
|
1
|
+
{"version":3,"file":"organizationGroupPresentation.js","sourceRoot":"","sources":["organizationGroupPresentation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oCAAoC,EAAE,MAAM,yCAAyC,CAAC;AAI/F,MAAM,CAAC,KAAK,UAAU,wCAAwC,CAAC,KAK9D;IACC,MAAM,cAAc,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,cAAc,CAAC;IACzD,IACE,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,eAAe;QACnC,CAAC,cAAc;QACf,KAAK,CAAC,OAAO,CAAC,MAAM,KAAK,CAAC,EAC1B,CAAC;QACD,OAAO;YACL,OAAO,EAAE,IAAI;YACb,aAAa,EAAE,IAAI;SACpB,CAAC;IACJ,CAAC;IAED,MAAM,CAAC,OAAO,EAAE,aAAa,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;QACjD,KAAK,CAAC,aAAa,KAAK,SAAS;YAC/B,CAAC,CAAC,KAAK,CAAC,oBAAoB,CAAC,qBAAqB,CAC9C,KAAK,CAAC,OAAO,EACb,cAAc,CACf;YACH,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC;QACzB,KAAK,CAAC,oBAAoB;aACvB,sBAAsB,CACrB,KAAK,CAAC,OAAO,EACb,cAAc,EACd,KAAK,CAAC,aAAa,CACpB;aACA,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;YACxB,mEAAmE;YACnE,oEAAoE;YACpE,IACE,KAAK,CAAC,aAAa,KAAK,SAAS;gBACjC,KAAK,YAAY,oCAAoC,EACrD,CAAC;gBACD,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,8BAA8B,EAAE,KAAK,CAAC,CAAC;gBACnE,OAAO,IAAI,CAAC;YACd,CAAC;YACD,MAAM,KAAK,CAAC;QACd,CAAC,CAAC;KACL,CAAC,CAAC;IACH,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,CAAC;AACpC,CAAC","sourcesContent":["import { ProjectionDependencyUnavailableError } from \"../../data/shared/dependencyUnavailable\";\nimport type { InternalWorkflowRuntimeInput } from \"../runtime/workflowRuntime\";\nimport type { OrganizationReadModelCoordinator } from \"./organizationReadModels\";\n\nexport async function loadOrganizationGroupPresentationDetails(input: {\n readonly groupId: string;\n readonly beforeVersion?: number | undefined;\n readonly readModelCoordinator: OrganizationReadModelCoordinator;\n readonly runtime: InternalWorkflowRuntimeInput;\n}) {\n const organizationId = input.runtime.auth.organizationId;\n if (\n !input.runtime.auth.isAuthenticated ||\n !organizationId ||\n input.groupId.length === 0\n ) {\n return {\n members: null,\n policyHistory: null,\n };\n }\n\n const [members, policyHistory] = await Promise.all([\n input.beforeVersion === undefined\n ? input.readModelCoordinator.loadLocalGroupMembers(\n input.groupId,\n organizationId,\n )\n : Promise.resolve(null),\n input.readModelCoordinator\n .loadGroupPolicyHistory(\n input.groupId,\n organizationId,\n input.beforeVersion,\n )\n .catch((error: unknown) => {\n // Missing history must not hide the independent member projection.\n // Older-page failures remain explicit so the caller can retry them.\n if (\n input.beforeVersion === undefined &&\n error instanceof ProjectionDependencyUnavailableError\n ) {\n input.runtime.util.logError(\"Group history is unavailable\", error);\n return null;\n }\n throw error;\n }),\n ]);\n return { members, policyHistory };\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { ProjectionDependencyUnavailableError } from "../../data/keyingProjectionVerification/dependencyUnavailable.js";
|
|
2
1
|
import { assertProjectionVerificationCurrent } from "../../data/keyingProjectionVerification/types.js";
|
|
2
|
+
import { ProjectionDependencyUnavailableError } from "../../data/shared/dependencyUnavailable.js";
|
|
3
3
|
import { loadLocalOrganizationPolicyReference } from "../../workflows/organizations/index.js";
|
|
4
4
|
import { buildOrganizationGroupPolicyHistoryPage } from "../../workflows/organizations/policyHistory/groupPolicyHistoryPage.js";
|
|
5
5
|
import { loadPolicyHistoryDetails } from "../../workflows/organizations/policyHistory/loadPolicyHistoryDetails.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"organizationHistory.js","sourceRoot":"","sources":["organizationHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"organizationHistory.js","sourceRoot":"","sources":["organizationHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,oCAAoC,EAAE,MAAM,yCAAyC,CAAC;AAC/F,OAAO,EAAE,oCAAoC,EAAE,MAAM,+BAA+B,CAAC;AACrF,OAAO,EAAE,uCAAuC,EAAE,MAAM,oEAAoE,CAAC;AAC7H,OAAO,EAAE,wBAAwB,EAAE,MAAM,sEAAsE,CAAC;AAIhH,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAAC,KAIpD;IACC,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,GAAG,KAAK,CAAC;IACvC,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC;IAC3B,MAAM,OAAO,GAAG,OAAO,CAAC,iBAAiB,CAAC,2BAA2B,EAAE,CAAC;IACxE,MAAM,cAAc,GAClB,OAAO,CAAC,iBAAiB,CAAC,+BAA+B,EAAE,CAAC;IAC9D,IAAI,CAAC,OAAO,IAAI,CAAC,cAAc;QAC7B,MAAM,IAAI,oCAAoC,CAC5C,sDAAsD,CACvD,CAAC;IACJ,MAAM,SAAS,GAAG,MAAM,oCAAoC,CAAC;QAC3D,aAAa,EAAE,MAAM,CAAC,MAAM;QAC5B,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO;QAC9B,cAAc,EAAE,MAAM,CAAC,cAAc;QACrC,WAAW,EAAE,MAAM,CAAC,cAAc;QAClC,aAAa,EAAE,cAAc;KAC9B,CAAC,CAAC;IACH,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAClD,IAAI,CAAC,SAAS;QAAE,OAAO,IAAI,CAAC;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AC,KAAK,CAAC,MAAM;QAC5B,SAAS,EAAE,KAAK,CAAC,aAAa,KAAK,SAAS;QAC5C,QAAQ,EAAE,OAAO,CAAC,IAAI,CAAC,QAAQ;QAC/B,sBAAsB,EAAE,OAAO,CAAC,IAAI,CAAC,sBAAsB;KAC5D,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/shared/dependencyUnavailable\";\nimport { loadLocalOrganizationPolicyReference } from \"../../workflows/organizations\";\nimport { buildOrganizationGroupPolicyHistoryPage } from \"../../workflows/organizations/policyHistory/groupPolicyHistoryPage\";\nimport { loadPolicyHistoryDetails } from \"../../workflows/organizations/policyHistory/loadPolicyHistoryDetails\";\n\nimport type { ActiveOrganizationDataRuntime } from \"./organizationWorkflowRuntime\";\n\nexport async function loadBoundedOrganizationHistory(input: {\n readonly active: ActiveOrganizationDataRuntime;\n readonly beforeVersion?: number | undefined;\n readonly stillCurrent: () => boolean;\n}) {\n const { active, stillCurrent } = input;\n const { runtime } = active;\n const resolve = runtime.principalPolicies.createCurrentPolicyResolver();\n const resolveHistory =\n runtime.principalPolicies.createProjectionHistoryResolver();\n if (!resolve || !resolveHistory)\n throw new ProjectionDependencyUnavailableError(\n \"Organization history requires private paged recovery\",\n );\n const reference = await loadLocalOrganizationPolicyReference({\n currentUserId: active.userId,\n execSql: runtime.infra.execSql,\n organizationId: active.organizationId,\n principalId: active.organizationId,\n principalType: \"organization\",\n });\n assertProjectionVerificationCurrent(stillCurrent);\n if (!reference) return null;\n const resolved = await resolve({\n organizationId: active.organizationId,\n reference,\n preferLocalCurrent: true,\n stillCurrent,\n historyPage:\n input.beforeVersion === undefined\n ? {}\n : { beforeVersion: input.beforeVersion },\n });\n assertProjectionVerificationCurrent(resolved.stillCurrent);\n const page = resolved.historyPage;\n if (!page) throw new Error(\"Verified organization history page is missing\");\n const basic = buildOrganizationGroupPolicyHistoryPage({\n page,\n organizationId: active.organizationId,\n groupId: active.organizationId,\n });\n return loadPolicyHistoryDetails({\n apiClient: runtime.apiClient,\n currentUserId: active.userId,\n domainScope: runtime.state.domainScope,\n execSql: runtime.infra.execSql,\n organizationId: active.organizationId,\n head: reference,\n page,\n history: {\n principalId: active.organizationId,\n principalType: \"organization\",\n organizationId: active.organizationId,\n nextBeforeVersion: page.nextBeforeVersion,\n entries: basic.entries.map((entry) => ({ ...entry, groupChanges: null })),\n },\n resolveHistory,\n stillCurrent,\n online: runtime.state.online,\n olderPage: input.beforeVersion !== undefined,\n logError: runtime.util.logError,\n reportSecurityIncident: runtime.util.reportSecurityIncident,\n });\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { ProjectionDependencyUnavailableError } from "../../data/keyingProjectionVerification/dependencyUnavailable.js";
|
|
2
1
|
import { runWithSecurityIncidentReporting } from "../../data/keyingProjectionVerification/error.js";
|
|
2
|
+
import { ProjectionDependencyUnavailableError } from "../../data/shared/dependencyUnavailable.js";
|
|
3
3
|
import { ContainerMutationService } from "../../workflows/containers/index.js";
|
|
4
4
|
import { revokeOrganizationContainerGrant } from "../../workflows/organizations/index.js";
|
|
5
5
|
import { createSelectedCurrentGroupMetadataContainerVerifier } from "../../workflows/organizations/groupMetadata/currentGroupMetadataAuthority.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalMutations.js","sourceRoot":"","sources":["principalMutations.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AACjG,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACtE,OAAO,EAAE,gCAAgC,EAAE,MAAM,+BAA+B,CAAC;AACjF,OAAO,EAAE,mDAAmD,EAAE,MAAM,2EAA2E,CAAC;AAChJ,OAAO,EAAE,gCAAgC,EAAE,MAAM,kEAAkE,CA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ACpE,+BAA+B,EAC7B,KAAK,CAAC,OAAO,CAAC,iBAAiB,CAAC,YAAY,EAAE;gBAChD,GAAG,cAAc;aAClB,CAAC,CAAC;QACL,CAAC,CAAC;QACF,MAAM,QAAQ,GAAG,MAAM,MAAM,EAAE,CAAC;QAChC,MAAM,KAAK,CAAC,oBAAoB,CAAC,sBAAsB,CACrD,cAAc,CAAC,cAAc,CAC9B,CAAC;QACF,OAAO,QAAQ,CAAC;IAClB,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type { ContainerGrantSubjectType } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport { ContainerMutationService } from \"../../workflows/containers\";\nimport { revokeOrganizationContainerGrant } from \"../../workflows/organizations\";\nimport { createSelectedCurrentGroupMetadataContainerVerifier } from \"../../workflows/organizations/groupMetadata/currentGroupMetadataAuthority\";\nimport { createRuntimeGroupMetadataAccess } from \"../../workflows/organizations/groupMetadata/groupMetadataRuntime\";\nimport { createCurrentOrganizationGroup } from \"../../workflows/organizations/groups/createCurrentOrganizationGroup\";\nimport { deleteCurrentOrganizationGroup } from \"../../workflows/organizations/groups/deleteCurrentOrganizationGroup\";\nimport { createRuntimeCurrentOrganizationMutation } from \"../../workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation\";\n\nimport type { ContainerContents } from \"../containerContents\";\nimport type { InternalWorkflowRuntimeInput } from \"../runtime/workflowRuntime\";\nimport { createCurrentPrincipalMutation } from \"./currentPrincipalMutations\";\nimport { syncOrganizationMetadataProfile } from \"./organizationMetadataProfileSync\";\nimport type { OrganizationReadModelCoordinator } from \"./organizationReadModels\";\nimport type { GroupMemberAdmission } from \"./recipientAdmission\";\n\nexport interface OrganizationGrantRef {\n containerId: string;\n subjectId: string;\n subjectType: ContainerGrantSubjectType;\n}\n\nexport interface OrganizationGroupUserMutationInput {\n groupId: string;\n expectedGroupName: string;\n}\n\nexport interface AddOrganizationGroupUserInput\n extends OrganizationGroupUserMutationInput {\n targetUserId: string;\n}\n\nexport interface RemoveOrganizationGroupUserInput\n extends OrganizationGroupUserMutationInput {\n removedUserId: string;\n}\n\ninterface OrganizationSigningContext {\n identityTrustDomain: string;\n organizationId: string;\n signerUserId: string;\n signingFingerprint: string;\n signingKeyPair: NonNullable<\n InternalWorkflowRuntimeInput[\"crypto\"][\"signingKeyPair\"]\n >;\n}\n\n/** The client's fixed trust domain and the mutation's runtime snapshot. */\ninterface OrganizationMutationScope {\n readonly identityTrustDomain: string | null;\n readonly runtime: InternalWorkflowRuntimeInput;\n}\n\nfunction requireSigningContext({\n identityTrustDomain,\n runtime,\n}: OrganizationMutationScope): OrganizationSigningContext {\n if (\n !identityTrustDomain ||\n !runtime.auth.organizationId ||\n !runtime.auth.userId ||\n !runtime.crypto.signingFingerprint ||\n !runtime.crypto.signingKeyPair\n ) {\n throw new Error(\"Organization signing context is unavailable\");\n }\n\n return {\n identityTrustDomain,\n organizationId: runtime.auth.organizationId,\n signerUserId: runtime.auth.userId,\n signingFingerprint: runtime.crypto.signingFingerprint,\n signingKeyPair: runtime.crypto.signingKeyPair,\n };\n}\n\nfunction requireEncapsulationKeyPair(\n runtime: InternalWorkflowRuntimeInput,\n): NonNullable<InternalWorkflowRuntimeInput[\"crypto\"][\"encapsulationKeyPair\"]> {\n if (!runtime.crypto.encapsulationKeyPair) {\n throw new Error(\"Organization encryption context is unavailable\");\n }\n\n return runtime.crypto.encapsulationKeyPair;\n}\n\ninterface PrincipalMutationRuntime extends OrganizationMutationScope {\n readonly stillCurrent: () => boolean;\n readonly containerContents: ContainerContents;\n readonly readModelCoordinator: OrganizationReadModelCoordinator;\n}\n\nexport async function addUserToOrganizationGroup(\n input: PrincipalMutationRuntime &\n AddOrganizationGroupUserInput & {\n readonly admission: GroupMemberAdmission;\n },\n) {\n const signingContext = requireSigningContext(input);\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: input.groupId,\n objectKind: \"principal\",\n operation: \"group.member.add\",\n organizationId: signingContext.organizationId,\n },\n async () => {\n const mutateCurrent = createCurrentPrincipalMutation({\n ...signingContext,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n });\n if (!mutateCurrent)\n throw new ProjectionDependencyUnavailableError(\n \"Principal history recovery is unavailable\",\n );\n const {\n memberGroupId,\n response: bundle,\n enrolled,\n } = await mutateCurrent(input.groupId, {\n kind: \"add\",\n expectedGroupName: input.expectedGroupName,\n targetUserId: input.targetUserId,\n admission: input.admission,\n });\n if (input.groupId === memberGroupId || enrolled) {\n await syncOrganizationMetadataProfile({\n containerContents: input.containerContents,\n log: input.runtime.util.log,\n organizationId: signingContext.organizationId,\n });\n }\n // The verified post-commit read is the mutation's own: callers apply\n // this directory instead of reading the read model a second time.\n const directoryAndGroups =\n await input.readModelCoordinator.reconcileAfterMutation(\n signingContext.organizationId,\n );\n return { directoryAndGroups, receipt: bundle };\n },\n );\n}\n\nexport function createGroupForOrganization(\n input: OrganizationMutationScope & {\n readonly name: string;\n readonly stillCurrent: () => boolean;\n },\n) {\n const signingContext = requireSigningContext(input);\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: signingContext.organizationId,\n objectKind: \"principal\",\n operation: \"group.create\",\n organizationId: signingContext.organizationId,\n },\n () => {\n const creatorEncapsulationKeyPair = requireEncapsulationKeyPair(\n input.runtime,\n );\n const mutate = createRuntimeCurrentOrganizationMutation(input.runtime);\n if (!mutate)\n throw new ProjectionDependencyUnavailableError(\n \"Principal history recovery is unavailable\",\n );\n return mutate(\n { ...signingContext, stillCurrent: input.stillCurrent },\n (context) =>\n createCurrentOrganizationGroup({\n ...signingContext,\n context,\n apiClient: input.runtime.apiClient,\n creatorEncapsulationKeyPair,\n execSql: input.runtime.infra.execSql,\n name: input.name,\n metadataAccess: createRuntimeGroupMetadataAccess(\n input.runtime,\n signingContext.organizationId,\n context.stillCurrent,\n createSelectedCurrentGroupMetadataContainerVerifier({\n authority: context,\n organizationId: signingContext.organizationId,\n stillCurrent: context.stillCurrent,\n }),\n ),\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity:\n input.runtime.resolveTrustedUserIdentity,\n }),\n );\n },\n );\n}\n\nexport function deleteGroupForOrganization(\n input: OrganizationMutationScope & {\n readonly groupId: string;\n readonly stillCurrent: () => boolean;\n },\n) {\n const signingContext = requireSigningContext(input);\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: input.groupId,\n objectKind: \"principal\",\n operation: \"group.delete\",\n organizationId: signingContext.organizationId,\n },\n () => {\n const mutate = createRuntimeCurrentOrganizationMutation(input.runtime);\n if (!mutate)\n throw new ProjectionDependencyUnavailableError(\n \"Principal history recovery is unavailable\",\n );\n return mutate(\n { ...signingContext, stillCurrent: input.stillCurrent },\n (context) =>\n deleteCurrentOrganizationGroup({\n ...signingContext,\n context,\n groupId: input.groupId,\n apiClient: input.runtime.apiClient,\n resolveTrustedUserIdentity:\n input.runtime.resolveTrustedUserIdentity,\n }),\n );\n },\n );\n}\n\nexport async function removeUserFromOrganizationGroup(\n input: PrincipalMutationRuntime & RemoveOrganizationGroupUserInput,\n) {\n const signingContext = requireSigningContext(input);\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: input.groupId,\n objectKind: \"principal\",\n operation: \"group.member.remove\",\n organizationId: signingContext.organizationId,\n },\n async () => {\n const mutateCurrent = createCurrentPrincipalMutation({\n ...signingContext,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n });\n if (!mutateCurrent)\n throw new ProjectionDependencyUnavailableError(\n \"Principal history recovery is unavailable\",\n );\n const { memberGroupId, response: bundle } = await mutateCurrent(\n input.groupId,\n {\n kind: \"remove\",\n expectedGroupName: input.expectedGroupName,\n removedUserId: input.removedUserId,\n },\n );\n if (input.groupId === memberGroupId) {\n await syncOrganizationMetadataProfile({\n containerContents: input.containerContents,\n log: input.runtime.util.log,\n organizationId: signingContext.organizationId,\n });\n }\n // The verified post-commit read is the mutation's own: callers apply\n // this directory instead of reading the read model a second time.\n const directoryAndGroups =\n await input.readModelCoordinator.reconcileAfterMutation(\n signingContext.organizationId,\n );\n return { directoryAndGroups, receipt: bundle };\n },\n );\n}\n\nexport async function revokeOrganizationGrant(\n input: PrincipalMutationRuntime & OrganizationGrantRef,\n) {\n const signingContext = requireSigningContext(input);\n const encapsulationKeyPair = requireEncapsulationKeyPair(input.runtime);\n if (input.runtime.infra.dbStatus !== \"ready\") {\n throw new Error(\"Organization local database is unavailable\");\n }\n\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: input.subjectId,\n objectKind: \"principal\",\n operation: \"principal.grant.revoke\",\n organizationId: signingContext.organizationId,\n },\n async () => {\n const revoke = async () => {\n if (input.subjectType === \"group\") {\n const mutateCurrent = createCurrentPrincipalMutation({\n ...signingContext,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n });\n if (!mutateCurrent)\n throw new ProjectionDependencyUnavailableError(\n \"Principal history recovery is unavailable\",\n );\n return (\n await mutateCurrent(input.subjectId, {\n kind: \"revoke\",\n revokedContainerId: input.containerId,\n })\n ).response;\n }\n return revokeOrganizationContainerGrant({\n stillCurrent: input.stillCurrent,\n containerId: input.containerId,\n containers: new ContainerMutationService({\n api: input.runtime.apiClient,\n encapsulationSecretKey: encapsulationKeyPair.secretKey,\n execSql: input.runtime.infra.execSql,\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity:\n input.runtime.resolveTrustedUserIdentity,\n }),\n revokedSubject: {\n subjectId: input.subjectId,\n subjectType: input.subjectType,\n },\n resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,\n warmReferencedPrincipalPolicies:\n input.runtime.principalPolicies.createWarmer(),\n ...signingContext,\n });\n };\n const response = await revoke();\n await input.readModelCoordinator.reconcileAfterMutation(\n signingContext.organizationId,\n );\n return response;\n },\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"principalMutations.js","sourceRoot":"","sources":["principalMutations.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AACjG,OAAO,EAAE,oCAAoC,EAAE,MAAM,yCAAyC,CAAC;AAC/F,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACtE,OAAO,EAAE,gCAAgC,EAAE,MAAM,+BAA+B,CAAC;AACjF,OAAO,EAAE,mDAAmD,EAAE,MAAM,2EAA2E,CAAC;AAChJ,OAAO,EAAE,gCAAgC,EAAE,MAAM,kEAAkE,CAAC;AACpH,OAAO,EAAE,8BAA8B,EAAE,MAAM,qEAAqE,CAAC;AACrH,OAAO,EAAE,8BAA8B,EAAE,MAAM,qEAAqE,CAAC;AACrH,OAAO,EAAE,wCAAwC,EAAE,MAAM,qFAAqF,CAAC;AAI/I,OAAO,EAAE,8BAA8B,EAAE,MAAM,6BAA6B,CAAC;AAC7E,OAAO,EAAE,+BAA+B,EAAE,MAAM,mCAAmC,CAAC;AAyCpF,SAAS,qBAAqB,CAAC,EAC7B,mBAAmB,EACnB,OAAO,GACmB;IAC1B,IACE,CAAC,mBAAmB;QACpB,CAAC,OAAO,CAAC,IAAI,CAAC,cAAc;QAC5B,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM;QACpB,CAAC,OAAO,CAAC,MAAM,CAAC,kBAAkB;QAClC,CAAC,OAAO,CAAC,MAAM,CAAC,cAAc,EAC9B,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAC;IACjE,CAAC;IAED,OAAO;QACL,mBAAmB;QACnB,cAAc,EAAE,OAAO,CAAC,IAAI,CAAC,cAAc;QAC3C,YAAY,EAAE,OAAO,CAAC,IAAI,CAAC,MAAM;QACjC,kBAAkB,EAAE,OAAO,CAAC,MAAM,CAAC,kBAAkB;QACrD,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oBACvC,GAAG,EAAE,KAAK,CAAC,OAAO,CAAC,SAAS;oBAC5B,sBAAsB,EAAE,oBAAoB,CAAC,SAAS;oBACtD,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO;oBACpC,sBAAsB,EAAE,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,sBAAsB;oBACjE,0BAA0B,EACxB,KAAK,CAAC,OAAO,CAAC,0BAA0B;iBAC3C,CAAC;gBACF,cAAc,EAAE;oBACd,SAAS,EAAE,KAAK,CAAC,SAAS;oBAC1B,WAAW,EAAE,KAAK,CAAC,WAAW;iBAC/B;gBACD,0BAA0B,EAAE,KAAK,CAAC,OAAO,CAAC,0BAA0B;gBACpE,+BAA+B,EAC7B,KAAK,CAAC,OAAO,CAAC,iBAAiB,CAAC,YAAY,EAAE;gBAChD,GAAG,cAAc;aAClB,CAAC,CAAC;QACL,CAAC,CAAC;QACF,MAAM,QAAQ,GAAG,MAAM,MAAM,EAAE,CAAC;QAChC,MAAM,KAAK,CAAC,oBAAoB,CAAC,sBAAsB,CACrD,cAAc,CAAC,cAAc,CAC9B,CAAC;QACF,OAAO,QAAQ,CAAC;IAClB,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type { ContainerGrantSubjectType } from \"@tearleads/crypto\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/shared/dependencyUnavailable\";\nimport { ContainerMutationService } from \"../../workflows/containers\";\nimport { revokeOrganizationContainerGrant } from \"../../workflows/organizations\";\nimport { createSelectedCurrentGroupMetadataContainerVerifier } from \"../../workflows/organizations/groupMetadata/currentGroupMetadataAuthority\";\nimport { createRuntimeGroupMetadataAccess } from \"../../workflows/organizations/groupMetadata/groupMetadataRuntime\";\nimport { createCurrentOrganizationGroup } from \"../../workflows/organizations/groups/createCurrentOrganizationGroup\";\nimport { deleteCurrentOrganizationGroup } from \"../../workflows/organizations/groups/deleteCurrentOrganizationGroup\";\nimport { createRuntimeCurrentOrganizationMutation } from \"../../workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation\";\n\nimport type { ContainerContents } from \"../containerContents\";\nimport type { InternalWorkflowRuntimeInput } from \"../runtime/workflowRuntime\";\nimport { createCurrentPrincipalMutation } from \"./currentPrincipalMutations\";\nimport { syncOrganizationMetadataProfile } from \"./organizationMetadataProfileSync\";\nimport type { OrganizationReadModelCoordinator } from \"./organizationReadModels\";\nimport type { GroupMemberAdmission } from \"./recipientAdmission\";\n\nexport interface OrganizationGrantRef {\n containerId: string;\n subjectId: string;\n subjectType: ContainerGrantSubjectType;\n}\n\nexport interface OrganizationGroupUserMutationInput {\n groupId: string;\n expectedGroupName: string;\n}\n\nexport interface AddOrganizationGroupUserInput\n extends OrganizationGroupUserMutationInput {\n targetUserId: string;\n}\n\nexport interface RemoveOrganizationGroupUserInput\n extends OrganizationGroupUserMutationInput {\n removedUserId: string;\n}\n\ninterface OrganizationSigningContext {\n identityTrustDomain: string;\n organizationId: string;\n signerUserId: string;\n signingFingerprint: string;\n signingKeyPair: NonNullable<\n InternalWorkflowRuntimeInput[\"crypto\"][\"signingKeyPair\"]\n >;\n}\n\n/** The client's fixed trust domain and the mutation's runtime snapshot. */\ninterface OrganizationMutationScope {\n readonly identityTrustDomain: string | null;\n readonly runtime: InternalWorkflowRuntimeInput;\n}\n\nfunction requireSigningContext({\n identityTrustDomain,\n runtime,\n}: OrganizationMutationScope): OrganizationSigningContext {\n if (\n !identityTrustDomain ||\n !runtime.auth.organizationId ||\n !runtime.auth.userId ||\n !runtime.crypto.signingFingerprint ||\n !runtime.crypto.signingKeyPair\n ) {\n throw new Error(\"Organization signing context is unavailable\");\n }\n\n return {\n identityTrustDomain,\n organizationId: runtime.auth.organizationId,\n signerUserId: runtime.auth.userId,\n signingFingerprint: runtime.crypto.signingFingerprint,\n signingKeyPair: runtime.crypto.signingKeyPair,\n };\n}\n\nfunction requireEncapsulationKeyPair(\n runtime: InternalWorkflowRuntimeInput,\n): NonNullable<InternalWorkflowRuntimeInput[\"crypto\"][\"encapsulationKeyPair\"]> {\n if (!runtime.crypto.encapsulationKeyPair) {\n throw new Error(\"Organization encryption context is unavailable\");\n }\n\n return runtime.crypto.encapsulationKeyPair;\n}\n\ninterface PrincipalMutationRuntime extends OrganizationMutationScope {\n readonly stillCurrent: () => boolean;\n readonly containerContents: ContainerContents;\n readonly readModelCoordinator: OrganizationReadModelCoordinator;\n}\n\nexport async function addUserToOrganizationGroup(\n input: PrincipalMutationRuntime &\n AddOrganizationGroupUserInput & {\n readonly admission: GroupMemberAdmission;\n },\n) {\n const signingContext = requireSigningContext(input);\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: input.groupId,\n objectKind: \"principal\",\n operation: \"group.member.add\",\n organizationId: signingContext.organizationId,\n },\n async () => {\n const mutateCurrent = createCurrentPrincipalMutation({\n ...signingContext,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n });\n if (!mutateCurrent)\n throw new ProjectionDependencyUnavailableError(\n \"Principal history recovery is unavailable\",\n );\n const {\n memberGroupId,\n response: bundle,\n enrolled,\n } = await mutateCurrent(input.groupId, {\n kind: \"add\",\n expectedGroupName: input.expectedGroupName,\n targetUserId: input.targetUserId,\n admission: input.admission,\n });\n if (input.groupId === memberGroupId || enrolled) {\n await syncOrganizationMetadataProfile({\n containerContents: input.containerContents,\n log: input.runtime.util.log,\n organizationId: signingContext.organizationId,\n });\n }\n // The verified post-commit read is the mutation's own: callers apply\n // this directory instead of reading the read model a second time.\n const directoryAndGroups =\n await input.readModelCoordinator.reconcileAfterMutation(\n signingContext.organizationId,\n );\n return { directoryAndGroups, receipt: bundle };\n },\n );\n}\n\nexport function createGroupForOrganization(\n input: OrganizationMutationScope & {\n readonly name: string;\n readonly stillCurrent: () => boolean;\n },\n) {\n const signingContext = requireSigningContext(input);\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: signingContext.organizationId,\n objectKind: \"principal\",\n operation: \"group.create\",\n organizationId: signingContext.organizationId,\n },\n () => {\n const creatorEncapsulationKeyPair = requireEncapsulationKeyPair(\n input.runtime,\n );\n const mutate = createRuntimeCurrentOrganizationMutation(input.runtime);\n if (!mutate)\n throw new ProjectionDependencyUnavailableError(\n \"Principal history recovery is unavailable\",\n );\n return mutate(\n { ...signingContext, stillCurrent: input.stillCurrent },\n (context) =>\n createCurrentOrganizationGroup({\n ...signingContext,\n context,\n apiClient: input.runtime.apiClient,\n creatorEncapsulationKeyPair,\n execSql: input.runtime.infra.execSql,\n name: input.name,\n metadataAccess: createRuntimeGroupMetadataAccess(\n input.runtime,\n signingContext.organizationId,\n context.stillCurrent,\n createSelectedCurrentGroupMetadataContainerVerifier({\n authority: context,\n organizationId: signingContext.organizationId,\n stillCurrent: context.stillCurrent,\n }),\n ),\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity:\n input.runtime.resolveTrustedUserIdentity,\n }),\n );\n },\n );\n}\n\nexport function deleteGroupForOrganization(\n input: OrganizationMutationScope & {\n readonly groupId: string;\n readonly stillCurrent: () => boolean;\n },\n) {\n const signingContext = requireSigningContext(input);\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: input.groupId,\n objectKind: \"principal\",\n operation: \"group.delete\",\n organizationId: signingContext.organizationId,\n },\n () => {\n const mutate = createRuntimeCurrentOrganizationMutation(input.runtime);\n if (!mutate)\n throw new ProjectionDependencyUnavailableError(\n \"Principal history recovery is unavailable\",\n );\n return mutate(\n { ...signingContext, stillCurrent: input.stillCurrent },\n (context) =>\n deleteCurrentOrganizationGroup({\n ...signingContext,\n context,\n groupId: input.groupId,\n apiClient: input.runtime.apiClient,\n resolveTrustedUserIdentity:\n input.runtime.resolveTrustedUserIdentity,\n }),\n );\n },\n );\n}\n\nexport async function removeUserFromOrganizationGroup(\n input: PrincipalMutationRuntime & RemoveOrganizationGroupUserInput,\n) {\n const signingContext = requireSigningContext(input);\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: input.groupId,\n objectKind: \"principal\",\n operation: \"group.member.remove\",\n organizationId: signingContext.organizationId,\n },\n async () => {\n const mutateCurrent = createCurrentPrincipalMutation({\n ...signingContext,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n });\n if (!mutateCurrent)\n throw new ProjectionDependencyUnavailableError(\n \"Principal history recovery is unavailable\",\n );\n const { memberGroupId, response: bundle } = await mutateCurrent(\n input.groupId,\n {\n kind: \"remove\",\n expectedGroupName: input.expectedGroupName,\n removedUserId: input.removedUserId,\n },\n );\n if (input.groupId === memberGroupId) {\n await syncOrganizationMetadataProfile({\n containerContents: input.containerContents,\n log: input.runtime.util.log,\n organizationId: signingContext.organizationId,\n });\n }\n // The verified post-commit read is the mutation's own: callers apply\n // this directory instead of reading the read model a second time.\n const directoryAndGroups =\n await input.readModelCoordinator.reconcileAfterMutation(\n signingContext.organizationId,\n );\n return { directoryAndGroups, receipt: bundle };\n },\n );\n}\n\nexport async function revokeOrganizationGrant(\n input: PrincipalMutationRuntime & OrganizationGrantRef,\n) {\n const signingContext = requireSigningContext(input);\n const encapsulationKeyPair = requireEncapsulationKeyPair(input.runtime);\n if (input.runtime.infra.dbStatus !== \"ready\") {\n throw new Error(\"Organization local database is unavailable\");\n }\n\n return runWithSecurityIncidentReporting(\n input.runtime.util.reportSecurityIncident,\n {\n objectId: input.subjectId,\n objectKind: \"principal\",\n operation: \"principal.grant.revoke\",\n organizationId: signingContext.organizationId,\n },\n async () => {\n const revoke = async () => {\n if (input.subjectType === \"group\") {\n const mutateCurrent = createCurrentPrincipalMutation({\n ...signingContext,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n });\n if (!mutateCurrent)\n throw new ProjectionDependencyUnavailableError(\n \"Principal history recovery is unavailable\",\n );\n return (\n await mutateCurrent(input.subjectId, {\n kind: \"revoke\",\n revokedContainerId: input.containerId,\n })\n ).response;\n }\n return revokeOrganizationContainerGrant({\n stillCurrent: input.stillCurrent,\n containerId: input.containerId,\n containers: new ContainerMutationService({\n api: input.runtime.apiClient,\n encapsulationSecretKey: encapsulationKeyPair.secretKey,\n execSql: input.runtime.infra.execSql,\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity:\n input.runtime.resolveTrustedUserIdentity,\n }),\n revokedSubject: {\n subjectId: input.subjectId,\n subjectType: input.subjectType,\n },\n resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,\n warmReferencedPrincipalPolicies:\n input.runtime.principalPolicies.createWarmer(),\n ...signingContext,\n });\n };\n const response = await revoke();\n await input.readModelCoordinator.reconcileAfterMutation(\n signingContext.organizationId,\n );\n return response;\n },\n );\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { computeUserIdentityBundleFingerprint } from "../../internal/crypto/index.js";
|
|
2
|
-
import { ProjectionDependencyUnavailableError } from "../../data/keyingProjectionVerification/dependencyUnavailable.js";
|
|
3
2
|
import { runWithSecurityIncidentReporting } from "../../data/keyingProjectionVerification/error.js";
|
|
4
3
|
import { principalHeadMatchesReference } from "../../data/principals/organizationAuthorityDescriptor.js";
|
|
4
|
+
import { ProjectionDependencyUnavailableError } from "../../data/shared/dependencyUnavailable.js";
|
|
5
5
|
import { DatabaseUnavailableError } from "../../data/sync/databaseUnavailable.js";
|
|
6
6
|
import { UnverifiedUserIdentityError, } from "../../data/trustedUserIdentity/index.js";
|
|
7
7
|
import { isRosterVouchedRecipient, } from "../../workflows/organizations/memberships/rosterVouchedAdmission.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"recipientAdmission.js","sourceRoot":"","sources":["recipientAdmission.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,oCAAoC,EAAE,MAAM,mBAAmB,CAAC;AAEzE,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,gCAA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ACpE,CAAC;YACD,MAAM,IAAI,oCAAoC,CAC5C,uDAAuD,CACxD,CAAC;QACJ,CAAC;QACD,aAAa,EAAE,CAAC;IAClB,CAAC,CAAC;AACJ,CAAC;AAED,kFAAkF;AAClF,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACtC,OAC8C,EAC9C,MAAc;IAEd,MAAM,QAAQ,GAAG,kCAAkC,CAAC,OAAO,CAAC,CAAC;IAC7D,MAAM,SAAS,GAAG,MAAM,2BAA2B,CACjD,OAAO,EACP,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,EAC9B,MAAM,CACP,CAAC;IACF,IAAI,CAAC,QAAQ,CAAC,YAAY,EAAE;QAC1B,MAAM,IAAI,wBAAwB,CAChC,mEAAmE,CACpE,CAAC;IACJ,OAAO,EAAE,GAAG,QAAQ,EAAE,SAAS,EAAE,CAAC;AACpC,CAAC","sourcesContent":["import type {\n ContainerAccessLevel,\n ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { computeUserIdentityBundleFingerprint } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport { principalHeadMatchesReference } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport type { SecurityIncidentReporter } from \"../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { DatabaseUnavailableError } from \"../../data/sync/databaseUnavailable\";\nimport {\n type StagedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n UnverifiedUserIdentityError,\n} from \"../../data/trustedUserIdentity\";\nimport {\n isRosterVouchedRecipient,\n type RosterAdmissionEvidence,\n type RosterAdmissionPin,\n} from \"../../workflows/organizations/memberships/rosterVouchedAdmission\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\nimport {\n currentOrganizationMutation,\n currentOrganizationSigningMutation,\n} from \"./principalMutationScope\";\nimport { createRosterAdmissionEvidence } from \"./rosterAdmissionEvidence\";\n\nexport { loadServedStateEnvelopes } from \"./rosterAdmissionEvidence\";\n\ntype AdmissionRuntimeService = Pick<\n InternalRuntime,\n \"identityLinks\" | \"sessionGeneration\" | \"workflowInput\"\n>;\n\n/** Thrown inside the staged scope so a refused recipient publishes nothing. */\nclass RecipientNotVouched extends Error {}\n\nasync function stagedPin(\n candidate: NonNullable<Awaited<ReturnType<StagedUserIdentityResolver>>>,\n): Promise<RosterAdmissionPin> {\n return {\n encapsulationKeyFingerprint: candidate.encapsulationKeyFingerprint,\n identityBundleFingerprint:\n await computeUserIdentityBundleFingerprint(candidate),\n signingKeyFingerprint: candidate.signingKeyFingerprint,\n verified: false,\n };\n}\n\n/**\n * Admit against the server's first answers without pinning them: the\n * recipient's answer, and that of any historical signer the chain needs but\n * this device has not pinned (a departed admin seen only in older Members\n * states), are staged. Each is checked against its committed Members bundle,\n * and all are pinned as observed only once the signed roster vouches for the\n * recipient's exact identity bundle. A substituted answer leaves no pin, so a\n * corrected retry or the honest identity link still succeeds.\n */\nasync function isStagedRosterVouchedRecipient(\n userId: string,\n evidence: RosterAdmissionEvidence,\n resolver: TrustedUserIdentityResolver,\n assertCurrent: (() => void) | undefined,\n): Promise<boolean> {\n // Without staging, admit only a durable pin: never pin before the roster.\n if (!resolver.withPinnedIdentities)\n return isRosterVouchedRecipient(userId, evidence);\n try {\n return await resolver.withPinnedIdentities(\n [userId],\n async (resolve) => {\n const candidate = await resolve(userId);\n const vouched =\n candidate !== null &&\n (await isRosterVouchedRecipient(userId, {\n ...evidence,\n loadPin: async (id) => {\n const pin = await evidence.loadPin(id);\n if (pin) return pin;\n const staged = id === userId ? candidate : await resolve(id);\n return staged ? stagedPin(staged) : null;\n },\n }));\n if (!vouched) throw new RecipientNotVouched();\n return true;\n },\n { publish: true, assertCurrent },\n );\n } catch (error) {\n if (error instanceof RecipientNotVouched) return false;\n throw error;\n }\n}\n\n/**\n * Whether the signed roster vouches for `userId` on this device, for exactly\n * the domain-scoped signing and encapsulation identity bundle the server\n * serves. Served material that fails verification is recorded as a security\n * incident before the error propagates.\n */\nexport function isReportedRosterVouchedRecipient(input: {\n readonly evidence: RosterAdmissionEvidence;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly userId: string;\n /** The admission's lifetime, checked inside every pin write. */\n readonly assertCurrent?: (() => void) | undefined;\n}): Promise<boolean> {\n const { evidence, userId } = input;\n return runWithSecurityIncidentReporting(\n input.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"container.share.roster_vouch\",\n organizationId: input.organizationId,\n },\n () =>\n isStagedRosterVouchedRecipient(\n userId,\n evidence,\n input.resolveTrustedUserIdentity,\n input.assertCurrent,\n ),\n );\n}\n\ntype RecipientAdmission =\n | { readonly status: \"verified\" }\n | { readonly status: \"roster\"; readonly head: ReferencedPrincipalHead };\n\nasync function requireOrganizationRecipient(\n service: AdmissionRuntimeService,\n admittingExecSql: ExecSql,\n userId: string,\n): Promise<RecipientAdmission> {\n try {\n await service.identityLinks.requireVerified(userId, admittingExecSql);\n return { status: \"verified\" };\n } catch (error) {\n const runtime = service.workflowInput();\n const organizationId = runtime.auth.organizationId;\n if (!(error instanceof UnverifiedUserIdentityError) || !organizationId)\n throw error;\n const evidence = createRosterAdmissionEvidence(\n service,\n admittingExecSql,\n organizationId,\n );\n if (!evidence) throw error;\n let head: ReferencedPrincipalHead | undefined;\n const vouched = await isReportedRosterVouchedRecipient({\n assertCurrent: admissionLifetime(service, admittingExecSql),\n evidence: {\n ...evidence,\n async loadCurrentMembers() {\n const members = await evidence.loadCurrentMembers();\n head = members.head;\n return members;\n },\n },\n organizationId,\n reportSecurityIncident: runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n userId,\n });\n if (!vouched || !head) throw error;\n return { status: \"roster\", head };\n }\n}\n\nfunction admissionLifetime(service: AdmissionRuntimeService, execSql: ExecSql) {\n const scope = currentOrganizationMutation(service);\n return () => {\n if (scope.runtime.infra.execSql !== execSql || !scope.stillCurrent())\n throw new DatabaseUnavailableError(\n \"The active identity or database changed while admitting this user. Try again.\",\n );\n };\n}\n\n/** Full-bundle roster authentication admits read, write, and admin shares. */\nexport async function requireShareRecipient(\n service: AdmissionRuntimeService,\n admittingExecSql: ExecSql,\n userId: string,\n _accessLevel: ContainerAccessLevel,\n): Promise<void> {\n const assertCurrent = admissionLifetime(service, admittingExecSql);\n assertCurrent();\n await requireOrganizationRecipient(service, admittingExecSql, userId);\n assertCurrent();\n}\n\nexport type GroupMemberAdmission = (\n members: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"currentProjection\"\n >,\n) => Promise<void>;\n\n/** The proof is usable only at its exact Members head, within this runtime. */\nexport async function requireGroupMemberAdmission(\n service: AdmissionRuntimeService,\n admittingExecSql: ExecSql,\n userId: string,\n): Promise<GroupMemberAdmission> {\n const assertCurrent = admissionLifetime(service, admittingExecSql);\n assertCurrent();\n const admission = await requireOrganizationRecipient(\n service,\n admittingExecSql,\n userId,\n );\n assertCurrent();\n return async (members) => {\n assertCurrent();\n if (!members.currentProjection.some((member) => member.userId === userId)) {\n // A retry may find the user removed since the proof. Enrollment still\n // requires this device's self/link anchor, never an earlier roster proof.\n await service.identityLinks.requireVerified(userId, admittingExecSql);\n } else if (\n admission.status === \"roster\" &&\n !principalHeadMatchesReference(members.currentState, admission.head)\n ) {\n throw new ProjectionDependencyUnavailableError(\n \"Members changed while admitting this user. Try again.\",\n );\n }\n assertCurrent();\n };\n}\n\n/** Capture the mutation scope before obtaining its head-bound admission proof. */\nexport async function admitGroupMutation(\n service: AdmissionRuntimeService &\n Pick<InternalRuntime, \"identityTrustDomain\">,\n userId: string,\n) {\n const mutation = currentOrganizationSigningMutation(service);\n const admission = await requireGroupMemberAdmission(\n service,\n mutation.runtime.infra.execSql,\n userId,\n );\n if (!mutation.stillCurrent())\n throw new DatabaseUnavailableError(\n \"The active database changed while admitting this user. Try again.\",\n );\n return { ...mutation, admission };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"recipientAdmission.js","sourceRoot":"","sources":["recipientAdmission.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,oCAAoC,EAAE,MAAM,mBAAmB,CAAC;AAEzE,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AACjG,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AACtG,OAAO,EAAE,oCAAoC,EAAE,MAAM,yCAAyC,CAAC;AAG/F,OAAO,EAAE,wBAAwB,EAAE,MAAM,qCAAqC,CAAC;AAC/E,OAAO,EAGL,2BAA2B,GAC5B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,wBAAwB,GAGzB,MAAM,kEAAkE,CAAC;AAE1E,OAAO,EACL,2BAA2B,EAC3B,kCAAkC,GACnC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,6BAA6B,EAAE,MAAM,2BAA2B,CAAC;AAE1E,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AAOrE,+EAA+E;AAC/E,MAAM,mBAAoB,SAAQ,KAAK;CAAG;AAE1C,KAAK,UAAU,SAAS,CACtB,SAAuE;IAEvE,OAAO;QACL,2BAA2B,EAAE,SAAS,CAAC,2BAA2B;QAClE,yBAAyB,EACvB,MAAM,oCAAoC,CAAC,SAAS,CAAC;QACvD,qBAAqB,EAAE,SAAS,CAAC,qBAAqB;QACtD,QAAQ,EAAE,KAAK;KAChB,CAAC;AACJ,CAAC;AAED;;;;;;;;GAQG;AACH,KAAK,UAAU,8BAA8B,CAC3C,MAAc,EACd,QAAiC,EACjC,QAAqC,EACrC,aAAuC;IAEvC,0EAA0E;IAC1E,IAAI,CAAC,QAAQ,CAAC,oBAAoB;QAChC,OAAO,wBAAwB,CA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AiB,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,KAAK,MAAM,CAAC,EAAE,CAAC;YAC1E,sEAAsE;YACtE,0EAA0E;YAC1E,MAAM,OAAO,CAAC,aAAa,CAAC,eAAe,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;QACxE,CAAC;aAAM,IACL,SAAS,CAAC,MAAM,KAAK,QAAQ;YAC7B,CAAC,6BAA6B,CAAC,OAAO,CAAC,YAAY,EAAE,SAAS,CAAC,IAAI,CAAC,EACpE,CAAC;YACD,MAAM,IAAI,oCAAoC,CAC5C,uDAAuD,CACxD,CAAC;QACJ,CAAC;QACD,aAAa,EAAE,CAAC;IAClB,CAAC,CAAC;AACJ,CAAC;AAED,kFAAkF;AAClF,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACtC,OAC8C,EAC9C,MAAc;IAEd,MAAM,QAAQ,GAAG,kCAAkC,CAAC,OAAO,CAAC,CAAC;IAC7D,MAAM,SAAS,GAAG,MAAM,2BAA2B,CACjD,OAAO,EACP,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,EAC9B,MAAM,CACP,CAAC;IACF,IAAI,CAAC,QAAQ,CAAC,YAAY,EAAE;QAC1B,MAAM,IAAI,wBAAwB,CAChC,mEAAmE,CACpE,CAAC;IACJ,OAAO,EAAE,GAAG,QAAQ,EAAE,SAAS,EAAE,CAAC;AACpC,CAAC","sourcesContent":["import type {\n ContainerAccessLevel,\n ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { computeUserIdentityBundleFingerprint } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport { principalHeadMatchesReference } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/shared/dependencyUnavailable\";\nimport type { SecurityIncidentReporter } from \"../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { DatabaseUnavailableError } from \"../../data/sync/databaseUnavailable\";\nimport {\n type StagedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n UnverifiedUserIdentityError,\n} from \"../../data/trustedUserIdentity\";\nimport {\n isRosterVouchedRecipient,\n type RosterAdmissionEvidence,\n type RosterAdmissionPin,\n} from \"../../workflows/organizations/memberships/rosterVouchedAdmission\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\nimport {\n currentOrganizationMutation,\n currentOrganizationSigningMutation,\n} from \"./principalMutationScope\";\nimport { createRosterAdmissionEvidence } from \"./rosterAdmissionEvidence\";\n\nexport { loadServedStateEnvelopes } from \"./rosterAdmissionEvidence\";\n\ntype AdmissionRuntimeService = Pick<\n InternalRuntime,\n \"identityLinks\" | \"sessionGeneration\" | \"workflowInput\"\n>;\n\n/** Thrown inside the staged scope so a refused recipient publishes nothing. */\nclass RecipientNotVouched extends Error {}\n\nasync function stagedPin(\n candidate: NonNullable<Awaited<ReturnType<StagedUserIdentityResolver>>>,\n): Promise<RosterAdmissionPin> {\n return {\n encapsulationKeyFingerprint: candidate.encapsulationKeyFingerprint,\n identityBundleFingerprint:\n await computeUserIdentityBundleFingerprint(candidate),\n signingKeyFingerprint: candidate.signingKeyFingerprint,\n verified: false,\n };\n}\n\n/**\n * Admit against the server's first answers without pinning them: the\n * recipient's answer, and that of any historical signer the chain needs but\n * this device has not pinned (a departed admin seen only in older Members\n * states), are staged. Each is checked against its committed Members bundle,\n * and all are pinned as observed only once the signed roster vouches for the\n * recipient's exact identity bundle. A substituted answer leaves no pin, so a\n * corrected retry or the honest identity link still succeeds.\n */\nasync function isStagedRosterVouchedRecipient(\n userId: string,\n evidence: RosterAdmissionEvidence,\n resolver: TrustedUserIdentityResolver,\n assertCurrent: (() => void) | undefined,\n): Promise<boolean> {\n // Without staging, admit only a durable pin: never pin before the roster.\n if (!resolver.withPinnedIdentities)\n return isRosterVouchedRecipient(userId, evidence);\n try {\n return await resolver.withPinnedIdentities(\n [userId],\n async (resolve) => {\n const candidate = await resolve(userId);\n const vouched =\n candidate !== null &&\n (await isRosterVouchedRecipient(userId, {\n ...evidence,\n loadPin: async (id) => {\n const pin = await evidence.loadPin(id);\n if (pin) return pin;\n const staged = id === userId ? candidate : await resolve(id);\n return staged ? stagedPin(staged) : null;\n },\n }));\n if (!vouched) throw new RecipientNotVouched();\n return true;\n },\n { publish: true, assertCurrent },\n );\n } catch (error) {\n if (error instanceof RecipientNotVouched) return false;\n throw error;\n }\n}\n\n/**\n * Whether the signed roster vouches for `userId` on this device, for exactly\n * the domain-scoped signing and encapsulation identity bundle the server\n * serves. Served material that fails verification is recorded as a security\n * incident before the error propagates.\n */\nexport function isReportedRosterVouchedRecipient(input: {\n readonly evidence: RosterAdmissionEvidence;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly userId: string;\n /** The admission's lifetime, checked inside every pin write. */\n readonly assertCurrent?: (() => void) | undefined;\n}): Promise<boolean> {\n const { evidence, userId } = input;\n return runWithSecurityIncidentReporting(\n input.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"container.share.roster_vouch\",\n organizationId: input.organizationId,\n },\n () =>\n isStagedRosterVouchedRecipient(\n userId,\n evidence,\n input.resolveTrustedUserIdentity,\n input.assertCurrent,\n ),\n );\n}\n\ntype RecipientAdmission =\n | { readonly status: \"verified\" }\n | { readonly status: \"roster\"; readonly head: ReferencedPrincipalHead };\n\nasync function requireOrganizationRecipient(\n service: AdmissionRuntimeService,\n admittingExecSql: ExecSql,\n userId: string,\n): Promise<RecipientAdmission> {\n try {\n await service.identityLinks.requireVerified(userId, admittingExecSql);\n return { status: \"verified\" };\n } catch (error) {\n const runtime = service.workflowInput();\n const organizationId = runtime.auth.organizationId;\n if (!(error instanceof UnverifiedUserIdentityError) || !organizationId)\n throw error;\n const evidence = createRosterAdmissionEvidence(\n service,\n admittingExecSql,\n organizationId,\n );\n if (!evidence) throw error;\n let head: ReferencedPrincipalHead | undefined;\n const vouched = await isReportedRosterVouchedRecipient({\n assertCurrent: admissionLifetime(service, admittingExecSql),\n evidence: {\n ...evidence,\n async loadCurrentMembers() {\n const members = await evidence.loadCurrentMembers();\n head = members.head;\n return members;\n },\n },\n organizationId,\n reportSecurityIncident: runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n userId,\n });\n if (!vouched || !head) throw error;\n return { status: \"roster\", head };\n }\n}\n\nfunction admissionLifetime(service: AdmissionRuntimeService, execSql: ExecSql) {\n const scope = currentOrganizationMutation(service);\n return () => {\n if (scope.runtime.infra.execSql !== execSql || !scope.stillCurrent())\n throw new DatabaseUnavailableError(\n \"The active identity or database changed while admitting this user. Try again.\",\n );\n };\n}\n\n/** Full-bundle roster authentication admits read, write, and admin shares. */\nexport async function requireShareRecipient(\n service: AdmissionRuntimeService,\n admittingExecSql: ExecSql,\n userId: string,\n _accessLevel: ContainerAccessLevel,\n): Promise<void> {\n const assertCurrent = admissionLifetime(service, admittingExecSql);\n assertCurrent();\n await requireOrganizationRecipient(service, admittingExecSql, userId);\n assertCurrent();\n}\n\nexport type GroupMemberAdmission = (\n members: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"currentProjection\"\n >,\n) => Promise<void>;\n\n/** The proof is usable only at its exact Members head, within this runtime. */\nexport async function requireGroupMemberAdmission(\n service: AdmissionRuntimeService,\n admittingExecSql: ExecSql,\n userId: string,\n): Promise<GroupMemberAdmission> {\n const assertCurrent = admissionLifetime(service, admittingExecSql);\n assertCurrent();\n const admission = await requireOrganizationRecipient(\n service,\n admittingExecSql,\n userId,\n );\n assertCurrent();\n return async (members) => {\n assertCurrent();\n if (!members.currentProjection.some((member) => member.userId === userId)) {\n // A retry may find the user removed since the proof. Enrollment still\n // requires this device's self/link anchor, never an earlier roster proof.\n await service.identityLinks.requireVerified(userId, admittingExecSql);\n } else if (\n admission.status === \"roster\" &&\n !principalHeadMatchesReference(members.currentState, admission.head)\n ) {\n throw new ProjectionDependencyUnavailableError(\n \"Members changed while admitting this user. Try again.\",\n );\n }\n assertCurrent();\n };\n}\n\n/** Capture the mutation scope before obtaining its head-bound admission proof. */\nexport async function admitGroupMutation(\n service: AdmissionRuntimeService &\n Pick<InternalRuntime, \"identityTrustDomain\">,\n userId: string,\n) {\n const mutation = currentOrganizationSigningMutation(service);\n const admission = await requireGroupMemberAdmission(\n service,\n mutation.runtime.infra.execSql,\n userId,\n );\n if (!mutation.stillCurrent())\n throw new DatabaseUnavailableError(\n \"The active database changed while admitting this user. Try again.\",\n );\n return { ...mutation, admission };\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { KeyingVerificationError, readKeyingCanonicalJson, verifySignedAccessEvent, } from "../../../internal/crypto/index.js";
|
|
2
2
|
import { canonicalKeyingJsonString, readCanonicalRecord, } from "../../keying/canonicalJson.js";
|
|
3
|
-
import { ProjectionDependencyUnavailableError } from "
|
|
3
|
+
import { ProjectionDependencyUnavailableError } from "../../shared/dependencyUnavailable.js";
|
|
4
4
|
import { readKeyingVerificationShape } from "../error.js";
|
|
5
5
|
import { readAccessEvent, readRecordString, readRequiredRecordValue, } from "../readers.js";
|
|
6
6
|
function canonicalBundleJson(value, label) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bundleVerification.js","sourceRoot":"","sources":["bundleVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,uBAAuB,EACvB,uBAAuB,GACxB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EACL,yBAAyB,EACzB,mBAAmB,GACpB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,oCAAoC,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"bundleVerification.js","sourceRoot":"","sources":["bundleVerification.ts"],"names":[],"mappings":"AAAA,OA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AC,CAAC;IACH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;QACjB,MAAM,QAAQ,CAAC,KAAK,CAAC;IACvB,CAAC;IACD,IAAI,QAAQ,CAAC,KAAK,CAAC,SAAS,KAAK,SAAS,EAAE,CAAC;QAC3C,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,GAAG,KAAK,CAAC,KAAK,sBAAsB,CACrC,CAAC;IACJ,CAAC;IAED,OAAO,QAAQ,CAAC,KAAK,CAAC;AACxB,CAAC;AAED,MAAM,UAAU,uBAAuB,CAAC,KAIvC;IACC,OAAO,iCAAiC,CAAC;QACvC,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,KAAK;QAC1B,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,cAAc,EAAE,KAAK,CAAC,cAAc;KACrC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n readKeyingCanonicalJson,\n verifySignedAccessEvent,\n} from \"@tearleads/crypto\";\nimport type { AccessManifestBundleWireResponse } from \"@tearleads/validators/response\";\nimport type { AccessEventBundleWireResponse } from \"@tearleads/validators/util\";\nimport {\n canonicalKeyingJsonString,\n readCanonicalRecord,\n} from \"../../keying/canonicalJson\";\nimport { ProjectionDependencyUnavailableError } from \"../../shared/dependencyUnavailable\";\nimport { readKeyingVerificationShape } from \"../error\";\nimport {\n readAccessEvent,\n readRecordString,\n readRequiredRecordValue,\n} from \"../readers\";\nimport type { ProjectionUserKeyResolver } from \"../types\";\n\nfunction canonicalBundleJson(value: unknown, label: string): string {\n return readKeyingVerificationShape(() =>\n canonicalKeyingJsonString(value, label),\n );\n}\n\nexport function assertCanonicalEqual(input: {\n readonly actual: unknown;\n readonly expected: unknown;\n readonly label: string;\n}): void {\n if (\n canonicalBundleJson(input.actual, `${input.label} actual`) !==\n canonicalBundleJson(input.expected, `${input.label} expected`)\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n `${input.label} mismatch`,\n );\n }\n}\n\nexport function addBundleByHash(\n bundlesByHash: Map<string, AccessManifestBundleWireResponse>,\n bundle: AccessManifestBundleWireResponse,\n label: string,\n): void {\n const existing = bundlesByHash.get(bundle.manifestHash);\n if (!existing) {\n bundlesByHash.set(bundle.manifestHash, bundle);\n return;\n }\n\n if (\n canonicalBundleJson(existing, `${label} existing`) !==\n canonicalBundleJson(bundle, `${label} duplicate`)\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n `Writer projection has equivocal manifest bundle ${bundle.manifestHash}`,\n );\n }\n}\n\nfunction readStandaloneEventBundle(\n bundle: AccessEventBundleWireResponse,\n label: string,\n) {\n return readKeyingVerificationShape(() => {\n const eventBundle = readCanonicalRecord(bundle, `${label} event bundle`);\n const eventHash = readRecordString(\n eventBundle,\n \"eventHash\",\n `${label} event bundle`,\n );\n const event = readAccessEvent(\n readRequiredRecordValue(eventBundle, \"event\", `${label} event bundle`),\n `${label} signed event`,\n );\n const body = readKeyingCanonicalJson(\n readRequiredRecordValue(eventBundle, \"body\", `${label} event bundle`),\n `${label} event body`,\n );\n return { eventHash, event, body };\n });\n}\n\nexport async function verifyStandaloneAccessEventBundle(input: {\n readonly bundle: AccessEventBundleWireResponse;\n readonly label: string;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n}) {\n const { eventHash, event, body } = readStandaloneEventBundle(\n input.bundle,\n input.label,\n );\n const userKey = await input.resolveUserKey(event.signerUserId);\n if (!userKey) {\n throw new ProjectionDependencyUnavailableError(\n `${input.label} signer public key could not be resolved for ${event.signerUserId}`,\n );\n }\n\n const verified = await verifySignedAccessEvent({\n body,\n event,\n signerPublicKey: userKey.signingPublicKey,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n if (verified.value.eventHash !== eventHash) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n `${input.label} event hash mismatch`,\n );\n }\n\n return verified.value;\n}\n\nexport function verifyAccessEventBundle(input: {\n readonly bundle: AccessManifestBundleWireResponse;\n readonly label: string;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n}) {\n return verifyStandaloneAccessEventBundle({\n bundle: input.bundle.event,\n label: input.label,\n resolveUserKey: input.resolveUserKey,\n });\n}\n"]}
|
|
@@ -2,7 +2,7 @@ import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
|
|
|
2
2
|
import { containerKekWireLevel, } from "../../../internal/validators/response/index.js";
|
|
3
3
|
import { rememberVerifiedContainerHeads } from "../../containers/shared/heldContainerHeads.js";
|
|
4
4
|
import { PrincipalAuthorizationCheckpointUnavailableError } from "../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints.js";
|
|
5
|
-
import { ProjectionDependencyUnavailableError } from "
|
|
5
|
+
import { ProjectionDependencyUnavailableError } from "../../shared/dependencyUnavailable.js";
|
|
6
6
|
import { projectionLifetimeGuard } from "../projectionLifetimes.js";
|
|
7
7
|
import { assertProjectionVerificationCurrent } from "../types.js";
|
|
8
8
|
import { enforceAccessManifestCheckpoints, validateAccessManifestCheckpoints, } from "./accessManifestCheckpointEnforcement.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkpointContext.js","sourceRoot":"","sources":["checkpointContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAGL,qBAAqB,GACtB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,8BAA8B,EAAE,MAAM,4CAA4C,CAAC;AAE5F,OAAO,EAAE,gDAAgD,EAAE,MAAM,uEAAuE,CAAC;AAIzI,OAAO,EAAE,oCAAoC,EAAE,MAAM,0BAA0B,CAAC;AAChF,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EAAE,mCAAmC,EAAE,MAAM,UAAU,CAAC;AAC/D,OAAO,EACL,gCAAgC,EAChC,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;A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CAAC;QACpD,OAAO;IACT,CAAC;IACD,MAAM,2BAA2B,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAClD,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO;IAC7C,MAAM,cAAc,GAClB,OAAO,CAAC,cAAc;QACtB,OAAO,CAAC,kBAAkB,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,cAAc,CAAC;IACtD,IAAI,cAAc,KAAK,SAAS;QAAE,OAAO;IACzC,IAAI,CAAC;QACH,8BAA8B,CAAC;YAC7B,cAAc;YACd,OAAO,EAAE,KAAK,CAAC,OAAO,IAAI,OAAO,CAAC,OAAO;YACzC,KAAK,EAAE,OAAO,CAAC,kBAAkB;YACjC,QAAQ,EAAE,OAAO,CAAC,QAAQ;SAC3B,CAAC,CAAC;IACL,CAAC;IAAC,MAAM,CAAC;QACP,wEAAwE;QACxE,sEAAsE;IACxE,CAAC;AACH,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedContainerAccessManifest,\n type VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport {\n type AccessManifestBundleWireResponse,\n type ContainerKeyingPathResponse,\n containerKekWireLevel,\n} from \"@tearleads/validators/response\";\nimport { rememberVerifiedContainerHeads } from \"../../containers/shared/heldContainerHeads\";\nimport type { DocumentPurgeCheckpoint } from \"../../persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { PrincipalAuthorizationCheckpointUnavailableError } from \"../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints\";\nimport type { VerifiedManifestBundle } from \"../../persistence/verifiedManifestBundlePersistence\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../principals/principalPolicyEvidence\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { ProjectionDependencyUnavailableError } from \"../dependencyUnavailable\";\nimport { projectionLifetimeGuard } from \"../projectionLifetimes\";\nimport { assertProjectionVerificationCurrent } from \"../types\";\nimport {\n enforceAccessManifestCheckpoints,\n validateAccessManifestCheckpoints,\n} from \"./accessManifestCheckpointEnforcement\";\nimport { matchesVerifiedBundleBytes } from \"./verifiedBundleBytes\";\n\nexport interface ProjectionCheckpointContext {\n readonly heldContainerHeads: VerifiedContainerAccessManifest[];\n readonly execSql: ExecSql;\n // Local checkpoints read during this verification, one read per object.\n readonly localCheckpoints: Map<string, AccessManifestCheckpoint | null>;\n organizationId?: string | undefined;\n readonly policies: PrincipalPolicyCheckpointEvidence[];\n readonly authorizationPolicies: VerifiedPrincipalPolicySelection[];\n // Served bundles whose manifests verified, and KEK levels of verified\n // paths, stored at finalization.\n readonly verifiedBundles: VerifiedManifestBundle[];\n readonly verifiedHeads: VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: VerifiedAccessManifestCheckpointEvidence[];\n}\n\nexport function createProjectionCheckpointContext(input: {\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n}): ProjectionCheckpointContext {\n if (typeof input.execSql !== \"function\") {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Projection verification requires durable keying checkpoint storage\",\n );\n }\n\n return {\n heldContainerHeads: [],\n execSql: input.execSql,\n localCheckpoints: new Map(),\n organizationId: input.organizationId,\n policies: [],\n authorizationPolicies: [],\n verifiedBundles: [],\n verifiedHeads: [],\n verifiedManifests: [],\n };\n}\n\nexport function observeAccessManifestCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n },\n): void {\n context.verifiedHeads.push(...input.verifiedHeads);\n context.verifiedManifests.push(...input.verifiedManifests);\n}\n\n/**\n * Records each served bundle whose manifest this verification produced, so\n * the transaction finalizing the checkpoints also stores it for later\n * citation. A bundle the projection carried but verification never reached\n * is skipped.\n */\nexport function observeVerifiedProjectionBundles(\n context: ProjectionCheckpointContext,\n bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>,\n verifiedByHash: ReadonlyMap<\n string,\n { readonly checkpoint: AccessManifestCheckpoint }\n >,\n): void {\n for (const [manifestHash, bundle] of bundlesByHash) {\n const verified = verifiedByHash.get(manifestHash);\n // A cache hit verifies the hash, not these bytes: store only bytes that\n // a fresh verification accepted, so a citation never replays others.\n if (verified && matchesVerifiedBundleBytes(verified, bundle))\n context.verifiedBundles.push({ bundle, checkpoint: verified.checkpoint });\n }\n}\n\n/**\n * Records every KEK level of paths this verification accepted in full, so\n * the finalizing transaction stores them for later citation by digest. A\n * cited level is refilled from these bytes only when the API's current\n * level has the same digest, and is verified again like a served one.\n */\nexport function observeVerifiedKekLevels(\n context: ProjectionCheckpointContext,\n paths: readonly ContainerKeyingPathResponse[],\n): void {\n for (const path of paths)\n for (const kek of path.containerKeks)\n context.verifiedBundles.push({\n kekLevel: containerKekWireLevel(kek),\n organizationId: path.organizationId,\n });\n}\n\nexport function observePrincipalPolicy(\n context: ProjectionCheckpointContext,\n policy: PrincipalPolicyCheckpointEvidence,\n organizationId?: string | undefined,\n): void {\n if (\n organizationId !== undefined &&\n context.organizationId !== undefined &&\n context.organizationId !== organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"projection checkpoint batch crosses organization ownership\",\n );\n }\n context.organizationId ??= organizationId;\n context.policies.push(policy);\n}\n\nexport async function commitProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await enforceAccessManifestCheckpoints({\n documentPurgeCheckpoint: input?.documentPurgeCheckpoint,\n execSql: input?.execSql ?? context.execSql,\n organizationId: context.organizationId,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\n/** Validates against the latest durable pins without persisting new heads. */\nasync function validateProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await validateAccessManifestCheckpoints({\n execSql: input?.execSql ?? context.execSql,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\nexport async function finalizeProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly execSql?: ExecSql | undefined;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n if (input.persistVerificationCheckpoints === false) {\n await validateProjectionCheckpoints(context, input);\n return;\n }\n await commitProjectionCheckpoints(context, input);\n if (input.stillCurrent?.() === false) return;\n const organizationId =\n context.organizationId ??\n context.heldContainerHeads[0]?.state.organizationId;\n if (organizationId === undefined) return;\n try {\n rememberVerifiedContainerHeads({\n organizationId,\n execSql: input.execSql ?? context.execSql,\n heads: context.heldContainerHeads,\n policies: context.policies,\n });\n } catch {\n // Checkpoints are already committed. Optional re-citation evidence must\n // never change successful verification into a caller-visible refusal.\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"checkpointContext.js","sourceRoot":"","sources":["checkpointContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAGL,qBAAqB,GACtB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,8BAA8B,EAAE,MAAM,4CAA4C,CAAC;AAE5F,OAAO,EAAE,gDAAgD,EAAE,MAAM,uEAAuE,CAAC;AAGzI,OAAO,EAAE,oCAAoC,EAAE,MAAM,oCAAoC,CAAC;AAE1F,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EAAE,mCAAmC,EAAE,MAAM,UAAU,CAAC;AAC/D,OAAO,EACL,gCAAgC,EAChC,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AAiBnE,MAAM,UAAU,iCAAiC,CAAC,KAGjD;IACC,IAAI,OAAO,KAAK,CAAC,OAAO,KAAK,UAAU,EAAE,CAAC;QACxC,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,oEAAoE,CACrE,CAAC;IACJ,CAAC;IAED,OAAO;QACL,kBAAkB,EAAE,EAAE;QACtB,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,gBAAgB,EAAE,IAAI,GAAG,EAAE;QAC3B,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,QAAQ,EAAE,EAAE;QACZ,qBAAqB,EAAE,EAAE;QACzB,eAAe,EAAE,EAAE;QACnB,aAAa,EAAE,EAAE;QACjB,iBAAiB,EAAE,EAAE;KACtB,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,gCAAgC,CAC9C,OAAoC,EACpC,KAGC;IAED,OAAO,CAAC,aAAa,CAAC,IAAI,C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AAsE;IACxE,CAAC;AACH,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedContainerAccessManifest,\n type VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport {\n type AccessManifestBundleWireResponse,\n type ContainerKeyingPathResponse,\n containerKekWireLevel,\n} from \"@tearleads/validators/response\";\nimport { rememberVerifiedContainerHeads } from \"../../containers/shared/heldContainerHeads\";\nimport type { DocumentPurgeCheckpoint } from \"../../persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { PrincipalAuthorizationCheckpointUnavailableError } from \"../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints\";\nimport type { VerifiedManifestBundle } from \"../../persistence/verifiedManifestBundlePersistence\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../principals/principalPolicyEvidence\";\nimport { ProjectionDependencyUnavailableError } from \"../../shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { projectionLifetimeGuard } from \"../projectionLifetimes\";\nimport { assertProjectionVerificationCurrent } from \"../types\";\nimport {\n enforceAccessManifestCheckpoints,\n validateAccessManifestCheckpoints,\n} from \"./accessManifestCheckpointEnforcement\";\nimport { matchesVerifiedBundleBytes } from \"./verifiedBundleBytes\";\n\nexport interface ProjectionCheckpointContext {\n readonly heldContainerHeads: VerifiedContainerAccessManifest[];\n readonly execSql: ExecSql;\n // Local checkpoints read during this verification, one read per object.\n readonly localCheckpoints: Map<string, AccessManifestCheckpoint | null>;\n organizationId?: string | undefined;\n readonly policies: PrincipalPolicyCheckpointEvidence[];\n readonly authorizationPolicies: VerifiedPrincipalPolicySelection[];\n // Served bundles whose manifests verified, and KEK levels of verified\n // paths, stored at finalization.\n readonly verifiedBundles: VerifiedManifestBundle[];\n readonly verifiedHeads: VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: VerifiedAccessManifestCheckpointEvidence[];\n}\n\nexport function createProjectionCheckpointContext(input: {\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n}): ProjectionCheckpointContext {\n if (typeof input.execSql !== \"function\") {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Projection verification requires durable keying checkpoint storage\",\n );\n }\n\n return {\n heldContainerHeads: [],\n execSql: input.execSql,\n localCheckpoints: new Map(),\n organizationId: input.organizationId,\n policies: [],\n authorizationPolicies: [],\n verifiedBundles: [],\n verifiedHeads: [],\n verifiedManifests: [],\n };\n}\n\nexport function observeAccessManifestCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n },\n): void {\n context.verifiedHeads.push(...input.verifiedHeads);\n context.verifiedManifests.push(...input.verifiedManifests);\n}\n\n/**\n * Records each served bundle whose manifest this verification produced, so\n * the transaction finalizing the checkpoints also stores it for later\n * citation. A bundle the projection carried but verification never reached\n * is skipped.\n */\nexport function observeVerifiedProjectionBundles(\n context: ProjectionCheckpointContext,\n bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>,\n verifiedByHash: ReadonlyMap<\n string,\n { readonly checkpoint: AccessManifestCheckpoint }\n >,\n): void {\n for (const [manifestHash, bundle] of bundlesByHash) {\n const verified = verifiedByHash.get(manifestHash);\n // A cache hit verifies the hash, not these bytes: store only bytes that\n // a fresh verification accepted, so a citation never replays others.\n if (verified && matchesVerifiedBundleBytes(verified, bundle))\n context.verifiedBundles.push({ bundle, checkpoint: verified.checkpoint });\n }\n}\n\n/**\n * Records every KEK level of paths this verification accepted in full, so\n * the finalizing transaction stores them for later citation by digest. A\n * cited level is refilled from these bytes only when the API's current\n * level has the same digest, and is verified again like a served one.\n */\nexport function observeVerifiedKekLevels(\n context: ProjectionCheckpointContext,\n paths: readonly ContainerKeyingPathResponse[],\n): void {\n for (const path of paths)\n for (const kek of path.containerKeks)\n context.verifiedBundles.push({\n kekLevel: containerKekWireLevel(kek),\n organizationId: path.organizationId,\n });\n}\n\nexport function observePrincipalPolicy(\n context: ProjectionCheckpointContext,\n policy: PrincipalPolicyCheckpointEvidence,\n organizationId?: string | undefined,\n): void {\n if (\n organizationId !== undefined &&\n context.organizationId !== undefined &&\n context.organizationId !== organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"projection checkpoint batch crosses organization ownership\",\n );\n }\n context.organizationId ??= organizationId;\n context.policies.push(policy);\n}\n\nexport async function commitProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await enforceAccessManifestCheckpoints({\n documentPurgeCheckpoint: input?.documentPurgeCheckpoint,\n execSql: input?.execSql ?? context.execSql,\n organizationId: context.organizationId,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\n/** Validates against the latest durable pins without persisting new heads. */\nasync function validateProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await validateAccessManifestCheckpoints({\n execSql: input?.execSql ?? context.execSql,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\nexport async function finalizeProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly execSql?: ExecSql | undefined;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n if (input.persistVerificationCheckpoints === false) {\n await validateProjectionCheckpoints(context, input);\n return;\n }\n await commitProjectionCheckpoints(context, input);\n if (input.stillCurrent?.() === false) return;\n const organizationId =\n context.organizationId ??\n context.heldContainerHeads[0]?.state.organizationId;\n if (organizationId === undefined) return;\n try {\n rememberVerifiedContainerHeads({\n organizationId,\n execSql: input.execSql ?? context.execSql,\n heads: context.heldContainerHeads,\n policies: context.policies,\n });\n } catch {\n // Checkpoints are already committed. Optional re-citation evidence must\n // never change successful verification into a caller-visible refusal.\n }\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { computeContainerKekRecipientTargetHash, computeContainerKeyEpochHash, toFingerprint, verifyContainerKekState, } from "../../../internal/crypto/index.js";
|
|
2
|
+
import { ProjectionDependencyUnavailableError } from "../../shared/dependencyUnavailable.js";
|
|
2
3
|
import { addBundleByHash } from "../checkpoints/bundleVerification.js";
|
|
3
4
|
import { createProjectionCheckpointContext, finalizeProjectionCheckpoints, observeAccessManifestCheckpoints, observeVerifiedKekLevels, observeVerifiedProjectionBundles, } from "../checkpoints/checkpointContext.js";
|
|
4
|
-
import { ProjectionDependencyUnavailableError } from "../dependencyUnavailable.js";
|
|
5
5
|
import { throwKeyingVerificationShapeFailure } from "../error.js";
|
|
6
6
|
import { collectReferencedPrincipalPolicies } from "../principalPolicy/principalPolicyVerification.js";
|
|
7
7
|
import { verifyProjectionAuthorizationEvidence } from "../principalPolicy/projectionAuthorizationEvidence.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"containerProjectionVerification.js","sourceRoot":"","sources":["containerProjectionVerification.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,sCAAsC,EACtC,4BAA4B,EAC5B,aAAa,EAGb,uBAAuB,GACxB,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AACpE,OAAO,EACL,iCAAiC,EACjC,6BAA6B,EAC7B,gCAAgC,EAChC,wBAAwB,EACxB,gCAAgC,GAEjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,oCAAoC,EAAE,MAAM,0BAA0B,CAAC;AAChF,OAAO,EAAE,mCAAmC,EAAE,MAAM,UAAU,CAAC;AAC/D,OAAO,EAAE,kCAAkC,EAAE,MAAM,gDAAgD,CAAC;AACpG,OAAO,EAAE,qCAAqC,EAAE,MAAM,oDAAoD,CAAC;AAC3G,OAAO,EACL,+BAA+B,EAC/B,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,YAAY,CAAC;AAMpB,OAAO,EACL,mCAAmC,EACnC,sCAAsC,EACtC,iCAAiC,GAClC,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAC;AAE1E,KAAK,UAAU,iCAAiC,CAAC,KAGhD;IACC,MAAM,OAAO,GAAG;QACd,GAAG,IAAI,GAAG,CACR,KAAK,CAAC,iBAAiB,CAAC,KAAK,CAAC,YAAY;aACvC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,WAAW,KAAK,MAAM,CAAC;aAC/C,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,SAA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AAE,CAAC,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,wBAAwB,CAAC,CAC5E,CAAC;IAEF,OAAO,kCAAkC,CAAC;QACxC,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,UAAU,EAAE,wBAAwB;QACpC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;KACvE,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { PrincipalPolicyAuthorization } from \"@tearleads/crypto\";\nimport {\n type ContainerUserRecipientKey,\n computeContainerKekRecipientTargetHash,\n computeContainerKeyEpochHash,\n toFingerprint,\n type VerifiedContainerAccessManifest,\n type VerifiedContainerKekState,\n verifyContainerKekState,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../principals/principalPolicyEvidence\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { addBundleByHash } from \"../checkpoints/bundleVerification\";\nimport {\n createProjectionCheckpointContext,\n finalizeProjectionCheckpoints,\n observeAccessManifestCheckpoints,\n observeVerifiedKekLevels,\n observeVerifiedProjectionBundles,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { ProjectionDependencyUnavailableError } from \"../dependencyUnavailable\";\nimport { throwKeyingVerificationShapeFailure } from \"../error\";\nimport { collectReferencedPrincipalPolicies } from \"../principalPolicy/principalPolicyVerification\";\nimport { verifyProjectionAuthorizationEvidence } from \"../principalPolicy/projectionAuthorizationEvidence\";\nimport {\n readContainerKekRecipientTarget,\n readContainerKeyEpoch,\n readContainerKeyWrap,\n} from \"../readers\";\nimport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../types\";\nimport {\n assertProjectionVerificationCurrent,\n generationGuardedPrincipalPolicyWarmer,\n withGenerationGuardedPolicyWarmer,\n} from \"../types\";\nimport { verifyContainerManifestBundle } from \"./containerManifestVerification\";\nimport { verifyContainerManifestPath } from \"./containerPathVerification\";\n\nasync function collectContainerUserRecipientKeys(input: {\n readonly containerManifest: VerifiedContainerAccessManifest;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n}): Promise<ContainerUserRecipientKey[]> {\n const userIds = [\n ...new Set(\n input.containerManifest.state.directGrants\n .filter((grant) => grant.subjectType === \"user\")\n .map((grant) => grant.subjectId),\n ),\n ].sort();\n const userRecipientKeys: ContainerUserRecipientKey[] = [];\n\n for (const userId of userIds) {\n const userKey = await input.resolveUserKey(userId);\n if (!userKey) {\n throw new ProjectionDependencyUnavailableError(\n `Container writer projection recipient key could not be resolved for ${userId}`,\n );\n }\n const recipientKeyFingerprint = await toFingerprint(\n userKey.encapsulationPublicKey,\n );\n userRecipientKeys.push({\n userId,\n recipientKeyEpochId: `user:${userId}:encapsulation:${recipientKeyFingerprint}`,\n recipientKeyFingerprint,\n });\n }\n\n return userRecipientKeys;\n}\n\nfunction containerKekManifestHistory(input: {\n readonly history: readonly VerifiedContainerAccessManifest[];\n readonly verifiedManifest: VerifiedContainerAccessManifest;\n}): VerifiedContainerAccessManifest[] {\n const historyByHash = new Map<string, VerifiedContainerAccessManifest>();\n\n for (const manifest of input.history) {\n if (\n manifest.state.containerId === input.verifiedManifest.state.containerId &&\n manifest.manifestHash !== input.verifiedManifest.manifestHash\n ) {\n historyByHash.set(manifest.manifestHash, manifest);\n }\n }\n\n return [...historyByHash.values()];\n}\n\nasync function verifyContainerKekProjection(input: {\n readonly authorizationEvidence: readonly PrincipalPolicyAuthorization[];\n readonly kek: ContainerWriterProjectionResponse[\"containerKeks\"][number];\n readonly label: string;\n readonly parentKekState: VerifiedContainerKekState | null;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly verifiedManifest: VerifiedContainerAccessManifest;\n readonly verifiedManifestHistory: readonly VerifiedContainerAccessManifest[];\n readonly parentManifestHistory: readonly VerifiedContainerAccessManifest[];\n}): Promise<VerifiedContainerKekState> {\n if (input.verifiedManifest.state.parentContainerId && !input.parentKekState) {\n throw new Error(`${input.label} requires verified parent KEK state`);\n }\n\n const keyEpoch = readContainerKeyEpoch(\n input.kek.keyEpoch,\n `${input.label} key epoch`,\n );\n const wraps = input.kek.wraps.map((wrap, index) =>\n readContainerKeyWrap(wrap, `${input.label} wrap[${index}]`),\n );\n const userRecipientKeys = await collectContainerUserRecipientKeys({\n containerManifest: input.verifiedManifest,\n resolveUserKey: input.resolveUserKey,\n });\n const verifiedKekManifestHistory = containerKekManifestHistory({\n history: input.verifiedManifestHistory,\n verifiedManifest: input.verifiedManifest,\n });\n const verified = await verifyContainerKekState({\n allowHistoricalParentEpoch: true,\n containerManifest: input.verifiedManifest,\n containerManifestHistory: verifiedKekManifestHistory,\n parentManifestHistory: input.parentManifestHistory,\n keyEpoch,\n parentKekState: input.parentKekState,\n principalPolicies: input.authorizationEvidence,\n userRecipientKeys,\n wraps,\n });\n if (!verified.ok) {\n throw new Error(`${input.label} KEK verification failed`);\n }\n\n const keyEpochHash = await computeContainerKeyEpochHash(keyEpoch);\n if (keyEpochHash !== input.kek.keyEpochHash) {\n throw new Error(`${input.label} key epoch hash mismatch`);\n }\n const recipientTargets = input.kek.recipientTargets.map((target, index) =>\n readContainerKekRecipientTarget(\n target,\n `${input.label} recipient target[${index}]`,\n ),\n );\n const keyTargetHash =\n await computeContainerKekRecipientTargetHash(recipientTargets);\n if (\n keyTargetHash !== input.kek.keyTargetHash ||\n keyTargetHash !== verified.value.keyTargetHash\n ) {\n throw new Error(`${input.label} target hash mismatch`);\n }\n if (\n verified.value.containerKeyEpochId !== input.kek.containerKeyEpochId ||\n verified.value.containerKeyEpoch !== input.kek.containerKeyEpoch ||\n verified.value.accessManifestHash !== input.kek.accessManifestHash ||\n verified.value.parentContainerKeyEpochId !==\n input.kek.parentContainerKeyEpochId\n ) {\n throw new Error(`${input.label} identity mismatch`);\n }\n\n return verified.value;\n}\n\ninterface ContainerWriterProjectionVerificationInput {\n readonly execSql: ExecSql;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly principalPolicyCache?: PrincipalPolicyCache | undefined;\n readonly projection: ContainerWriterProjectionResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly verifiedByHash?:\n | Map<string, VerifiedContainerAccessManifest>\n | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}\n\nexport function verifiedContainerManifestsForBundles(\n bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>,\n verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>,\n): VerifiedContainerAccessManifest[] {\n return [...bundlesByHash.keys()].flatMap((manifestHash) => {\n const verified = verifiedByHash.get(manifestHash);\n return verified ? [verified] : [];\n });\n}\n\nfunction collectContainerProjectionBundles(\n projection: ContainerWriterProjectionResponse,\n): Map<string, AccessManifestBundleWireResponse> {\n const bundlesByHash = new Map<string, AccessManifestBundleWireResponse>();\n addContainerWriterProjectionBundles(\n bundlesByHash,\n projection,\n \"Container writer projection\",\n );\n return bundlesByHash;\n}\n\nexport async function verifyContainerWriterProjectionWithContext(\n input: Omit<ContainerWriterProjectionVerificationInput, \"execSql\"> & {\n readonly authorizationEvidence?: readonly PrincipalPolicyAuthorization[];\n },\n checkpointContext: ProjectionCheckpointContext,\n): Promise<VerifiedContainerAccessManifest[]> {\n if (input.projection.path.length !== input.projection.containerKeks.length) {\n throw new Error(\n \"Container writer projection path and KEKs are inconsistent\",\n );\n }\n\n const bundlesByHash = collectContainerProjectionBundles(input.projection);\n\n const verifiedByHash =\n input.verifiedByHash ?? new Map<string, VerifiedContainerAccessManifest>();\n const principalPolicyCache: PrincipalPolicyCache =\n input.principalPolicyCache ?? new Map();\n const verification = {\n checkpointContext,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n };\n const authorizationEvidence =\n input.authorizationEvidence ??\n (await verifyProjectionAuthorizationEvidence({\n ...verification,\n bundles: [...bundlesByHash.values()],\n policyEvidence: input.projection.policyEvidence,\n organizationId: input.projection.organizationId,\n stillCurrent: input.stillCurrent,\n }));\n const verifiedPath = await verifyContainerManifestPath({\n ...verification,\n authorizationEvidence,\n requireAuthorizationEvidence: true,\n servedAsCurrent: true,\n bundlesByHash,\n enforceLocalCheckpoints: true,\n label: \"Container writer projection path\",\n path: input.projection.path,\n verifiedByHash,\n });\n\n const verifiedKekStates: VerifiedContainerKekState[] = [];\n for (const [index, kek] of input.projection.containerKeks.entries()) {\n const verifiedManifest = verifiedPath[index];\n if (!verifiedManifest) {\n throw new Error(`Container writer projection KEK[${index}] is missing`);\n }\n const verifiedManifestHistory: VerifiedContainerAccessManifest[] = [];\n for (const [\n historyIndex,\n bundle,\n ] of kek.containerManifestHistory.entries()) {\n verifiedManifestHistory.push(\n await verifyContainerManifestBundle({\n ...verification,\n authorizationEvidence,\n requireAuthorizationEvidence: true,\n bundle,\n bundlesByHash,\n enforceLocalCheckpoint: false,\n label: `Container writer projection KEK[${index}] history[${historyIndex}]`,\n parentPath: verifiedPath.slice(0, index),\n verifiedByHash,\n }),\n );\n }\n\n const verifiedKekState = await verifyContainerKekProjection({\n authorizationEvidence,\n kek,\n label: `Container writer projection KEK[${index}]`,\n parentKekState: index > 0 ? (verifiedKekStates[index - 1] ?? null) : null,\n resolveUserKey: input.resolveUserKey,\n verifiedManifest,\n verifiedManifestHistory,\n parentManifestHistory: [...verifiedByHash.values()],\n });\n verifiedKekStates.push(verifiedKekState);\n }\n\n observeAccessManifestCheckpoints(checkpointContext, {\n verifiedHeads: verifiedPath,\n verifiedManifests: verifiedContainerManifestsForBundles(\n bundlesByHash,\n verifiedByHash,\n ),\n });\n\n checkpointContext.heldContainerHeads.push(...verifiedPath);\n return verifiedPath;\n}\n\nexport async function verifyContainerWriterProjection(\n input: ContainerWriterProjectionVerificationInput,\n): Promise<VerifiedContainerAccessManifest[]> {\n try {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const verifiedByHash =\n input.verifiedByHash ??\n new Map<string, VerifiedContainerAccessManifest>();\n const guardedInput = {\n ...withGenerationGuardedPolicyWarmer(input),\n verifiedByHash,\n };\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n organizationId: input.projection.organizationId,\n });\n const verifiedPath = await verifyContainerWriterProjectionWithContext(\n guardedInput,\n checkpointContext,\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n observeVerifiedProjectionBundles(\n checkpointContext,\n collectContainerProjectionBundles(input.projection),\n verifiedByHash,\n );\n observeVerifiedKekLevels(checkpointContext, [input.projection]);\n await finalizeProjectionCheckpoints(checkpointContext, input);\n assertProjectionVerificationCurrent(input.stillCurrent);\n return verifiedPath;\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n\nexport async function collectContainerWriterProjectionPrincipalPolicies(\n input: ContainerWriterProjectionVerificationInput,\n): Promise<PrincipalPolicyCurrentEvidence[]> {\n try {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const warmReferencedPrincipalPolicies =\n generationGuardedPrincipalPolicyWarmer(\n input.warmReferencedPrincipalPolicies,\n input.stillCurrent,\n );\n const principalPolicyCache: PrincipalPolicyCache =\n input.principalPolicyCache ?? new Map();\n const verifiedByHash =\n input.verifiedByHash ??\n new Map<string, VerifiedContainerAccessManifest>();\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n organizationId: input.projection.organizationId,\n });\n const verifiedPath = await verifyContainerWriterProjectionWithContext(\n {\n principalPolicyCache,\n projection: input.projection,\n verifiedByHash,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies,\n },\n checkpointContext,\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n\n const policies = await collectPrincipalPoliciesForContainerPaths({\n checkpointContext,\n organizationId: input.projection.organizationId,\n paths: [verifiedPath],\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n observeVerifiedProjectionBundles(\n checkpointContext,\n collectContainerProjectionBundles(input.projection),\n verifiedByHash,\n );\n observeVerifiedKekLevels(checkpointContext, [input.projection]);\n await finalizeProjectionCheckpoints(checkpointContext, input);\n assertProjectionVerificationCurrent(input.stillCurrent);\n return policies;\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n\nexport function addContainerWriterProjectionBundles(\n bundlesByHash: Map<string, AccessManifestBundleWireResponse>,\n projection: ContainerWriterProjectionResponse,\n label: string,\n): void {\n for (const [index, bundle] of projection.path.entries()) {\n addBundleByHash(bundlesByHash, bundle, `${label} path[${index}]`);\n }\n for (const [kekIndex, kek] of projection.containerKeks.entries()) {\n for (const [\n historyIndex,\n bundle,\n ] of kek.containerManifestHistory.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `${label} KEK[${kekIndex}] history[${historyIndex}]`,\n );\n }\n }\n}\n\nasync function collectPrincipalPoliciesForContainerPaths(input: {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n paths: readonly (readonly VerifiedContainerAccessManifest[] | undefined)[];\n principalPolicyCache: PrincipalPolicyCache;\n resolveUserKey: ProjectionUserKeyResolver;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence[]> {\n const referencedPrincipalHeads = input.paths.flatMap((path) =>\n (path ?? []).flatMap((manifest) => manifest.state.referencedPrincipalHeads),\n );\n\n return collectReferencedPrincipalPolicies({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n principalPolicyCache: input.principalPolicyCache,\n references: referencedPrincipalHeads,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"containerProjectionVerification.js","sourceRoot":"","sources":["containerProjectionVerification.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,sCAAsC,EACtC,4BAA4B,EAC5B,aAAa,EAGb,uBAAuB,GACxB,MAAM,mBAAmB,CAAC;AAM3B,OAAO,EAAE,oCAAoC,EAAE,MAAM,oCAAoC,CAAC;AAE1F,OAAO,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AACpE,OAAO,EACL,iCAAiC,EACjC,6BAA6B,EAC7B,gCAAgC,EAChC,wBAAwB,EACxB,gCAAgC,GAEjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,mCAAmC,EAAE,MAAM,UAAU,CAAC;AAC/D,OAAO,EAAE,kCAAkC,EAAE,MAAM,gDAAgD,CAAC;AACpG,OAAO,EAAE,qCAAqC,EAAE,MAAM,oDAAoD,CAAC;AAC3G,OAAO,EACL,+BAA+B,EAC/B,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,YAAY,CAAC;AAMpB,OAAO,EACL,mCAAmC,EACnC,sCAAsC,EACtC,iCAAiC,GAClC,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAC;AAE1E,KAAK,UAAU,iCAAiC,CAAC,KAGhD;IACC,MAAM,OAAO,GAAG;QACd,GAAG,IAAI,GAAG,CACR,KAAK,CAAC,iBAAiB,CAAC,KAAK,CAAC,YAAY;aACvC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,WAAW,KAAK,MAAM,CAAC;aAC/C,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,SAAS,CAAC,CACnC;KACF,CAAC,IAAI,EAAE,CAAC;IACT,MAAM,iBAAiB,GAA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,CAAC,KAAK,CAAC,wBAAwB,CAAC,CAC5E,CAAC;IAEF,OAAO,kCAAkC,CAAC;QACxC,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,UAAU,EAAE,wBAAwB;QACpC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;KACvE,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { PrincipalPolicyAuthorization } from \"@tearleads/crypto\";\nimport {\n type ContainerUserRecipientKey,\n computeContainerKekRecipientTargetHash,\n computeContainerKeyEpochHash,\n toFingerprint,\n type VerifiedContainerAccessManifest,\n type VerifiedContainerKekState,\n verifyContainerKekState,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../principals/principalPolicyEvidence\";\nimport { ProjectionDependencyUnavailableError } from \"../../shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { addBundleByHash } from \"../checkpoints/bundleVerification\";\nimport {\n createProjectionCheckpointContext,\n finalizeProjectionCheckpoints,\n observeAccessManifestCheckpoints,\n observeVerifiedKekLevels,\n observeVerifiedProjectionBundles,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { throwKeyingVerificationShapeFailure } from \"../error\";\nimport { collectReferencedPrincipalPolicies } from \"../principalPolicy/principalPolicyVerification\";\nimport { verifyProjectionAuthorizationEvidence } from \"../principalPolicy/projectionAuthorizationEvidence\";\nimport {\n readContainerKekRecipientTarget,\n readContainerKeyEpoch,\n readContainerKeyWrap,\n} from \"../readers\";\nimport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../types\";\nimport {\n assertProjectionVerificationCurrent,\n generationGuardedPrincipalPolicyWarmer,\n withGenerationGuardedPolicyWarmer,\n} from \"../types\";\nimport { verifyContainerManifestBundle } from \"./containerManifestVerification\";\nimport { verifyContainerManifestPath } from \"./containerPathVerification\";\n\nasync function collectContainerUserRecipientKeys(input: {\n readonly containerManifest: VerifiedContainerAccessManifest;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n}): Promise<ContainerUserRecipientKey[]> {\n const userIds = [\n ...new Set(\n input.containerManifest.state.directGrants\n .filter((grant) => grant.subjectType === \"user\")\n .map((grant) => grant.subjectId),\n ),\n ].sort();\n const userRecipientKeys: ContainerUserRecipientKey[] = [];\n\n for (const userId of userIds) {\n const userKey = await input.resolveUserKey(userId);\n if (!userKey) {\n throw new ProjectionDependencyUnavailableError(\n `Container writer projection recipient key could not be resolved for ${userId}`,\n );\n }\n const recipientKeyFingerprint = await toFingerprint(\n userKey.encapsulationPublicKey,\n );\n userRecipientKeys.push({\n userId,\n recipientKeyEpochId: `user:${userId}:encapsulation:${recipientKeyFingerprint}`,\n recipientKeyFingerprint,\n });\n }\n\n return userRecipientKeys;\n}\n\nfunction containerKekManifestHistory(input: {\n readonly history: readonly VerifiedContainerAccessManifest[];\n readonly verifiedManifest: VerifiedContainerAccessManifest;\n}): VerifiedContainerAccessManifest[] {\n const historyByHash = new Map<string, VerifiedContainerAccessManifest>();\n\n for (const manifest of input.history) {\n if (\n manifest.state.containerId === input.verifiedManifest.state.containerId &&\n manifest.manifestHash !== input.verifiedManifest.manifestHash\n ) {\n historyByHash.set(manifest.manifestHash, manifest);\n }\n }\n\n return [...historyByHash.values()];\n}\n\nasync function verifyContainerKekProjection(input: {\n readonly authorizationEvidence: readonly PrincipalPolicyAuthorization[];\n readonly kek: ContainerWriterProjectionResponse[\"containerKeks\"][number];\n readonly label: string;\n readonly parentKekState: VerifiedContainerKekState | null;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly verifiedManifest: VerifiedContainerAccessManifest;\n readonly verifiedManifestHistory: readonly VerifiedContainerAccessManifest[];\n readonly parentManifestHistory: readonly VerifiedContainerAccessManifest[];\n}): Promise<VerifiedContainerKekState> {\n if (input.verifiedManifest.state.parentContainerId && !input.parentKekState) {\n throw new Error(`${input.label} requires verified parent KEK state`);\n }\n\n const keyEpoch = readContainerKeyEpoch(\n input.kek.keyEpoch,\n `${input.label} key epoch`,\n );\n const wraps = input.kek.wraps.map((wrap, index) =>\n readContainerKeyWrap(wrap, `${input.label} wrap[${index}]`),\n );\n const userRecipientKeys = await collectContainerUserRecipientKeys({\n containerManifest: input.verifiedManifest,\n resolveUserKey: input.resolveUserKey,\n });\n const verifiedKekManifestHistory = containerKekManifestHistory({\n history: input.verifiedManifestHistory,\n verifiedManifest: input.verifiedManifest,\n });\n const verified = await verifyContainerKekState({\n allowHistoricalParentEpoch: true,\n containerManifest: input.verifiedManifest,\n containerManifestHistory: verifiedKekManifestHistory,\n parentManifestHistory: input.parentManifestHistory,\n keyEpoch,\n parentKekState: input.parentKekState,\n principalPolicies: input.authorizationEvidence,\n userRecipientKeys,\n wraps,\n });\n if (!verified.ok) {\n throw new Error(`${input.label} KEK verification failed`);\n }\n\n const keyEpochHash = await computeContainerKeyEpochHash(keyEpoch);\n if (keyEpochHash !== input.kek.keyEpochHash) {\n throw new Error(`${input.label} key epoch hash mismatch`);\n }\n const recipientTargets = input.kek.recipientTargets.map((target, index) =>\n readContainerKekRecipientTarget(\n target,\n `${input.label} recipient target[${index}]`,\n ),\n );\n const keyTargetHash =\n await computeContainerKekRecipientTargetHash(recipientTargets);\n if (\n keyTargetHash !== input.kek.keyTargetHash ||\n keyTargetHash !== verified.value.keyTargetHash\n ) {\n throw new Error(`${input.label} target hash mismatch`);\n }\n if (\n verified.value.containerKeyEpochId !== input.kek.containerKeyEpochId ||\n verified.value.containerKeyEpoch !== input.kek.containerKeyEpoch ||\n verified.value.accessManifestHash !== input.kek.accessManifestHash ||\n verified.value.parentContainerKeyEpochId !==\n input.kek.parentContainerKeyEpochId\n ) {\n throw new Error(`${input.label} identity mismatch`);\n }\n\n return verified.value;\n}\n\ninterface ContainerWriterProjectionVerificationInput {\n readonly execSql: ExecSql;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly principalPolicyCache?: PrincipalPolicyCache | undefined;\n readonly projection: ContainerWriterProjectionResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly verifiedByHash?:\n | Map<string, VerifiedContainerAccessManifest>\n | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}\n\nexport function verifiedContainerManifestsForBundles(\n bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>,\n verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>,\n): VerifiedContainerAccessManifest[] {\n return [...bundlesByHash.keys()].flatMap((manifestHash) => {\n const verified = verifiedByHash.get(manifestHash);\n return verified ? [verified] : [];\n });\n}\n\nfunction collectContainerProjectionBundles(\n projection: ContainerWriterProjectionResponse,\n): Map<string, AccessManifestBundleWireResponse> {\n const bundlesByHash = new Map<string, AccessManifestBundleWireResponse>();\n addContainerWriterProjectionBundles(\n bundlesByHash,\n projection,\n \"Container writer projection\",\n );\n return bundlesByHash;\n}\n\nexport async function verifyContainerWriterProjectionWithContext(\n input: Omit<ContainerWriterProjectionVerificationInput, \"execSql\"> & {\n readonly authorizationEvidence?: readonly PrincipalPolicyAuthorization[];\n },\n checkpointContext: ProjectionCheckpointContext,\n): Promise<VerifiedContainerAccessManifest[]> {\n if (input.projection.path.length !== input.projection.containerKeks.length) {\n throw new Error(\n \"Container writer projection path and KEKs are inconsistent\",\n );\n }\n\n const bundlesByHash = collectContainerProjectionBundles(input.projection);\n\n const verifiedByHash =\n input.verifiedByHash ?? new Map<string, VerifiedContainerAccessManifest>();\n const principalPolicyCache: PrincipalPolicyCache =\n input.principalPolicyCache ?? new Map();\n const verification = {\n checkpointContext,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n };\n const authorizationEvidence =\n input.authorizationEvidence ??\n (await verifyProjectionAuthorizationEvidence({\n ...verification,\n bundles: [...bundlesByHash.values()],\n policyEvidence: input.projection.policyEvidence,\n organizationId: input.projection.organizationId,\n stillCurrent: input.stillCurrent,\n }));\n const verifiedPath = await verifyContainerManifestPath({\n ...verification,\n authorizationEvidence,\n requireAuthorizationEvidence: true,\n servedAsCurrent: true,\n bundlesByHash,\n enforceLocalCheckpoints: true,\n label: \"Container writer projection path\",\n path: input.projection.path,\n verifiedByHash,\n });\n\n const verifiedKekStates: VerifiedContainerKekState[] = [];\n for (const [index, kek] of input.projection.containerKeks.entries()) {\n const verifiedManifest = verifiedPath[index];\n if (!verifiedManifest) {\n throw new Error(`Container writer projection KEK[${index}] is missing`);\n }\n const verifiedManifestHistory: VerifiedContainerAccessManifest[] = [];\n for (const [\n historyIndex,\n bundle,\n ] of kek.containerManifestHistory.entries()) {\n verifiedManifestHistory.push(\n await verifyContainerManifestBundle({\n ...verification,\n authorizationEvidence,\n requireAuthorizationEvidence: true,\n bundle,\n bundlesByHash,\n enforceLocalCheckpoint: false,\n label: `Container writer projection KEK[${index}] history[${historyIndex}]`,\n parentPath: verifiedPath.slice(0, index),\n verifiedByHash,\n }),\n );\n }\n\n const verifiedKekState = await verifyContainerKekProjection({\n authorizationEvidence,\n kek,\n label: `Container writer projection KEK[${index}]`,\n parentKekState: index > 0 ? (verifiedKekStates[index - 1] ?? null) : null,\n resolveUserKey: input.resolveUserKey,\n verifiedManifest,\n verifiedManifestHistory,\n parentManifestHistory: [...verifiedByHash.values()],\n });\n verifiedKekStates.push(verifiedKekState);\n }\n\n observeAccessManifestCheckpoints(checkpointContext, {\n verifiedHeads: verifiedPath,\n verifiedManifests: verifiedContainerManifestsForBundles(\n bundlesByHash,\n verifiedByHash,\n ),\n });\n\n checkpointContext.heldContainerHeads.push(...verifiedPath);\n return verifiedPath;\n}\n\nexport async function verifyContainerWriterProjection(\n input: ContainerWriterProjectionVerificationInput,\n): Promise<VerifiedContainerAccessManifest[]> {\n try {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const verifiedByHash =\n input.verifiedByHash ??\n new Map<string, VerifiedContainerAccessManifest>();\n const guardedInput = {\n ...withGenerationGuardedPolicyWarmer(input),\n verifiedByHash,\n };\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n organizationId: input.projection.organizationId,\n });\n const verifiedPath = await verifyContainerWriterProjectionWithContext(\n guardedInput,\n checkpointContext,\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n observeVerifiedProjectionBundles(\n checkpointContext,\n collectContainerProjectionBundles(input.projection),\n verifiedByHash,\n );\n observeVerifiedKekLevels(checkpointContext, [input.projection]);\n await finalizeProjectionCheckpoints(checkpointContext, input);\n assertProjectionVerificationCurrent(input.stillCurrent);\n return verifiedPath;\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n\nexport async function collectContainerWriterProjectionPrincipalPolicies(\n input: ContainerWriterProjectionVerificationInput,\n): Promise<PrincipalPolicyCurrentEvidence[]> {\n try {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const warmReferencedPrincipalPolicies =\n generationGuardedPrincipalPolicyWarmer(\n input.warmReferencedPrincipalPolicies,\n input.stillCurrent,\n );\n const principalPolicyCache: PrincipalPolicyCache =\n input.principalPolicyCache ?? new Map();\n const verifiedByHash =\n input.verifiedByHash ??\n new Map<string, VerifiedContainerAccessManifest>();\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n organizationId: input.projection.organizationId,\n });\n const verifiedPath = await verifyContainerWriterProjectionWithContext(\n {\n principalPolicyCache,\n projection: input.projection,\n verifiedByHash,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies,\n },\n checkpointContext,\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n\n const policies = await collectPrincipalPoliciesForContainerPaths({\n checkpointContext,\n organizationId: input.projection.organizationId,\n paths: [verifiedPath],\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n observeVerifiedProjectionBundles(\n checkpointContext,\n collectContainerProjectionBundles(input.projection),\n verifiedByHash,\n );\n observeVerifiedKekLevels(checkpointContext, [input.projection]);\n await finalizeProjectionCheckpoints(checkpointContext, input);\n assertProjectionVerificationCurrent(input.stillCurrent);\n return policies;\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n\nexport function addContainerWriterProjectionBundles(\n bundlesByHash: Map<string, AccessManifestBundleWireResponse>,\n projection: ContainerWriterProjectionResponse,\n label: string,\n): void {\n for (const [index, bundle] of projection.path.entries()) {\n addBundleByHash(bundlesByHash, bundle, `${label} path[${index}]`);\n }\n for (const [kekIndex, kek] of projection.containerKeks.entries()) {\n for (const [\n historyIndex,\n bundle,\n ] of kek.containerManifestHistory.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `${label} KEK[${kekIndex}] history[${historyIndex}]`,\n );\n }\n }\n}\n\nasync function collectPrincipalPoliciesForContainerPaths(input: {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n paths: readonly (readonly VerifiedContainerAccessManifest[] | undefined)[];\n principalPolicyCache: PrincipalPolicyCache;\n resolveUserKey: ProjectionUserKeyResolver;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence[]> {\n const referencedPrincipalHeads = input.paths.flatMap((path) =>\n (path ?? []).flatMap((manifest) => manifest.state.referencedPrincipalHeads),\n );\n\n return collectReferencedPrincipalPolicies({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n principalPolicyCache: input.principalPolicyCache,\n references: referencedPrincipalHeads,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n}\n"]}
|
|
@@ -3,12 +3,12 @@ import { accessManifestObjectKey } from "../../persistence/keyingCheckpoints/key
|
|
|
3
3
|
import { KeyingCheckpointRepository } from "../../persistence/keyingCheckpoints/keyingCheckpointRepository.js";
|
|
4
4
|
import { PrincipalAuthorizationCheckpointUnavailableError, validatePrincipalAuthorizationCheckpoints, } from "../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints.js";
|
|
5
5
|
import { PrincipalPolicyBundleRepository } from "../../persistence/principalPolicy/principalPolicyBundleRepository.js";
|
|
6
|
+
import { ProjectionDependencyUnavailableError } from "../../shared/dependencyUnavailable.js";
|
|
6
7
|
import { registerClientSQLiteCommitGuard } from "../../sqlite/sqliteCommitGuards.js";
|
|
7
8
|
import { getClientSQLitePersistenceRuntime } from "../../sqlite/sqlitePersistenceRuntime.js";
|
|
8
9
|
import { runSerializedSqlMutation } from "../../sqlite/sqlSchema.js";
|
|
9
10
|
import { validateAccessManifestCheckpoints } from "../checkpoints/accessManifestCheckpointEnforcement.js";
|
|
10
11
|
import { commitProjectionCheckpoints, } from "../checkpoints/checkpointContext.js";
|
|
11
|
-
import { ProjectionDependencyUnavailableError } from "../dependencyUnavailable.js";
|
|
12
12
|
import { projectionLifetimeGuard } from "../projectionLifetimes.js";
|
|
13
13
|
import { assertProjectionVerificationCurrent } from "../types.js";
|
|
14
14
|
import { admitDocumentPurgePolicyCheckpoints } from "./documentPurgePolicyCheckpoints.js";
|