@tearleads/client-sdk 0.1.242 → 0.1.244

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.
Files changed (137) hide show
  1. package/client/organizations/currentPrincipalMutations.js +1 -0
  2. package/client/organizations/currentPrincipalMutations.js.map +1 -1
  3. package/client/organizations/principalMutations.d.ts +5 -0
  4. package/client/organizations/principalMutations.js +1 -0
  5. package/client/organizations/principalMutations.js.map +1 -1
  6. package/data/containers/shared/mutationAcknowledgement.d.ts +1 -1
  7. package/data/containers/shared/mutationAcknowledgement.js +3 -8
  8. package/data/containers/shared/mutationAcknowledgement.js.map +1 -1
  9. package/data/documents/shared/sync/mutationAcknowledgement.js +11 -2
  10. package/data/documents/shared/sync/mutationAcknowledgement.js.map +1 -1
  11. package/data/keyingProjectionVerification/checkpoints/heldBundleRecovery.d.ts +26 -0
  12. package/data/keyingProjectionVerification/checkpoints/heldBundleRecovery.js +46 -0
  13. package/data/keyingProjectionVerification/checkpoints/heldBundleRecovery.js.map +1 -0
  14. package/data/keyingProjectionVerification/container/containerDestinationVerification.d.ts +7 -4
  15. package/data/keyingProjectionVerification/container/containerDestinationVerification.js +5 -1
  16. package/data/keyingProjectionVerification/container/containerDestinationVerification.js.map +1 -1
  17. package/data/keyingProjectionVerification/container/containerProjectionVerification.js +9 -2
  18. package/data/keyingProjectionVerification/container/containerProjectionVerification.js.map +1 -1
  19. package/data/keyingProjectionVerification/document/documentContainerProjections.js +2 -1
  20. package/data/keyingProjectionVerification/document/documentContainerProjections.js.map +1 -1
  21. package/data/keyingProjectionVerification/document/documentProjectionVerification.js +9 -2
  22. package/data/keyingProjectionVerification/document/documentProjectionVerification.js.map +1 -1
  23. package/data/keyingProjectionVerification/index.d.ts +1 -0
  24. package/data/keyingProjectionVerification/index.js +1 -0
  25. package/data/keyingProjectionVerification/index.js.map +1 -1
  26. package/data/persistence/keyingCheckpoints/keyingCheckpointRepository.js +16 -4
  27. package/data/persistence/keyingCheckpoints/keyingCheckpointRepository.js.map +1 -1
  28. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.d.ts +13 -0
  29. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js +11 -0
  30. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js.map +1 -1
  31. package/data/persistence/verifiedCitations/authoredBundleCitation.d.ts +20 -0
  32. package/data/persistence/verifiedCitations/authoredBundleCitation.js +32 -0
  33. package/data/persistence/verifiedCitations/authoredBundleCitation.js.map +1 -0
  34. package/data/persistence/verifiedManifestBundlePersistence.d.ts +10 -0
  35. package/data/persistence/verifiedManifestBundlePersistence.js +95 -9
  36. package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
  37. package/data/principals/organizationDirectoryKeying.js +136 -0
  38. package/data/principals/organizationDirectoryKeying.js.map +1 -0
  39. package/data/principals/organizationGroupDirectoryRequest.js +17 -11
  40. package/data/principals/organizationGroupDirectoryRequest.js.map +1 -1
  41. package/internal/api-client/ApiClient.d.ts +55 -0
  42. package/internal/api-client/client/containerMutations.d.ts +11 -0
  43. package/internal/api-client/client/documents.d.ts +5 -0
  44. package/internal/api-client/client/organizations.d.ts +20 -0
  45. package/internal/api-client/client/principalPolicies.d.ts +9 -0
  46. package/internal/api-client/client/session.d.ts +10 -0
  47. package/internal/api-client/principalPolicyRequests.d.ts +7 -0
  48. package/internal/api-client/writerProjectionCitations.d.ts +3 -0
  49. package/internal/api-client/writerProjectionCitations.js +12 -0
  50. package/internal/api-client/writerProjectionCitations.js.map +1 -1
  51. package/internal/crypto/index.d.ts +1 -1
  52. package/internal/crypto/index.js +1 -1
  53. package/internal/crypto/index.js.map +1 -1
  54. package/internal/crypto/keying/canonicalJsonGuard.d.ts +13 -0
  55. package/internal/crypto/keying/canonicalJsonGuard.js +23 -0
  56. package/internal/crypto/keying/canonicalJsonGuard.js.map +1 -1
  57. package/internal/crypto/keying/index.d.ts +1 -1
  58. package/internal/crypto/keying/index.js +1 -1
  59. package/internal/crypto/keying/index.js.map +1 -1
  60. package/internal/crypto/keying/keyingHashDomains.d.ts +1 -1
  61. package/internal/crypto/keying/keyingHashDomains.js.map +1 -1
  62. package/internal/validators/operation/auth.d.ts +40 -0
  63. package/internal/validators/operation/containerMutations.d.ts +44 -0
  64. package/internal/validators/operation/documentMutations.d.ts +12 -0
  65. package/internal/validators/operation/organizations.d.ts +48 -0
  66. package/internal/validators/operation/principals.d.ts +16 -0
  67. package/internal/validators/response/areas/containers.d.ts +1 -1
  68. package/internal/validators/response/areas/containers.js +1 -1
  69. package/internal/validators/response/areas/containers.js.map +1 -1
  70. package/internal/validators/response/container.d.ts +16 -0
  71. package/internal/validators/response/container.js +3 -0
  72. package/internal/validators/response/container.js.map +1 -1
  73. package/internal/validators/response/containerMetadata.d.ts +8 -0
  74. package/internal/validators/response/documentMutation.d.ts +8 -0
  75. package/internal/validators/response/documentMutation.js +2 -1
  76. package/internal/validators/response/documentMutation.js.map +1 -1
  77. package/internal/validators/response/organization.d.ts +8 -0
  78. package/internal/validators/response/organizationProvisioning.d.ts +113 -0
  79. package/internal/validators/response/organizationProvisioning.js +2 -1
  80. package/internal/validators/response/organizationProvisioning.js.map +1 -1
  81. package/internal/validators/response/principal.d.ts +16 -0
  82. package/internal/validators/response/registration.d.ts +40 -0
  83. package/internal/validators/response/writerProjectionWire.d.ts +25 -0
  84. package/internal/validators/response/writerProjectionWire.js +109 -3
  85. package/internal/validators/response/writerProjectionWire.js.map +1 -1
  86. package/package.json +1 -1
  87. package/stores/documents/documentStore/rotation/index.js +3 -1
  88. package/stores/documents/documentStore/rotation/index.js.map +1 -1
  89. package/stores/documents/documentStore/sync/syncAttachments.js +4 -1
  90. package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -1
  91. package/stores/documents/documentStore/sync/syncDetachedAttachments.js +3 -1
  92. package/stores/documents/documentStore/sync/syncDetachedAttachments.js.map +1 -1
  93. package/stores/documents/documentStore/sync/syncRequest.js +3 -1
  94. package/stores/documents/documentStore/sync/syncRequest.js.map +1 -1
  95. package/workflows/container-contents/container-state/create/createAdoption.js +11 -3
  96. package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -1
  97. package/workflows/container-contents/container-state/create/createWithMetadata.js +2 -2
  98. package/workflows/container-contents/container-state/create/createWithMetadata.js.map +1 -1
  99. package/workflows/container-contents/container-state/projectionCache.js +3 -0
  100. package/workflows/container-contents/container-state/projectionCache.js.map +1 -1
  101. package/workflows/container-contents/metadata/index.js +5 -2
  102. package/workflows/container-contents/metadata/index.js.map +1 -1
  103. package/workflows/containers/child/recite.js +4 -2
  104. package/workflows/containers/child/recite.js.map +1 -1
  105. package/workflows/documents/create/createAdoption.js +11 -2
  106. package/workflows/documents/create/createAdoption.js.map +1 -1
  107. package/workflows/documents/create/createResponse.js +1 -0
  108. package/workflows/documents/create/createResponse.js.map +1 -1
  109. package/workflows/documents/linkSet/linkSetRemote.js +1 -0
  110. package/workflows/documents/linkSet/linkSetRemote.js.map +1 -1
  111. package/workflows/documents/sync/syncAttemptPlanning.js +8 -2
  112. package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -1
  113. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js +3 -2
  114. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js.map +1 -1
  115. package/workflows/documents/syncRekeys/syncContainerRekeyProjection.js +3 -2
  116. package/workflows/documents/syncRekeys/syncContainerRekeyProjection.js.map +1 -1
  117. package/workflows/organizations/groupPolicy/commitCurrentGroupPolicyMutation.js +1 -0
  118. package/workflows/organizations/groupPolicy/commitCurrentGroupPolicyMutation.js.map +1 -1
  119. package/workflows/organizations/groupShare/currentShareGrantMutation.js +3 -0
  120. package/workflows/organizations/groupShare/currentShareGrantMutation.js.map +1 -1
  121. package/workflows/organizations/groupShare/shareWithGroup.js +2 -0
  122. package/workflows/organizations/groupShare/shareWithGroup.js.map +1 -1
  123. package/workflows/organizations/groups/createCurrentOrganizationGroup.js +3 -0
  124. package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
  125. package/workflows/organizations/groups/deleteCurrentOrganizationGroup.js +1 -0
  126. package/workflows/organizations/groups/deleteCurrentOrganizationGroup.js.map +1 -1
  127. package/workflows/organizations/groups/deleteOrganizationGroup.d.ts +2 -0
  128. package/workflows/organizations/groups/deleteOrganizationGroup.js +1 -0
  129. package/workflows/organizations/groups/deleteOrganizationGroup.js.map +1 -1
  130. package/workflows/organizations/groups/organizationGroupDirectory.js +1 -0
  131. package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
  132. package/workflows/organizations/principalPolicy/index.d.ts +12 -0
  133. package/workflows/organizations/principalPolicy/index.js +11 -0
  134. package/workflows/organizations/principalPolicy/index.js.map +1 -1
  135. package/workflows/registration/organizationCreation/organizationCreationIntent.d.ts +10 -0
  136. package/workflows/registration/provisioningAcknowledgement.js +16 -11
  137. package/workflows/registration/provisioningAcknowledgement.js.map +1 -1
@@ -55,6 +55,7 @@ export function createCurrentPrincipalMutation(input) {
55
55
  const response = await commitCurrentGroupPolicyMutation({
56
56
  ...input,
57
57
  apiClient: input.runtime.apiClient,
58
+ currentUserSecretKey: input.runtime.crypto.encapsulationKeyPair?.secretKey ?? null,
58
59
  groupId,
59
60
  ...primary,
60
61
  member,
@@ -1 +1 @@
1
- {"version":3,"file":"currentPrincipalMutations.js","sourceRoot":"","sources":["currentPrincipalMutations.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,gCAAgC,EAAE,MAAM,kEAAkE,CAAC;AACpH,OAAO,EAAE,yBAAyB,EAAE,MAAM,8DAA8D,CAAC;AACzG,OAAO,EAAE,gCAAgC,EAAE,MAAM,4EAA4E,CAAC;AAC9H,OAAO,EACL,8BAA8B,EAC9B,sCAAsC,EACtC,iCAAiC,GAClC,MAAM,+DAA+D,CAAC;AACvE,OAAO,EACL,iCAAiC,GAElC,MAAM,8EAA8E,CAA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ACN,OAAO,GAAG,MAAM,sCAAsC,CAAC;YACrD,GAAG,MAAM;YACT,kBAAkB,EAAE,QAAQ,CAAC,kBAAkB;YAC/C,YAAY,EAAE,MAAM,YAAY,CAAC,iBAAiB,CAAC,UAAU,CAAC,CAAC;SAChE,CAAC,CAAC;IACL,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { SigningKeyPair } from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { createRuntimeGroupMetadataAccess } from \"../../workflows/organizations/groupMetadata/groupMetadataRuntime\";\nimport { assertGroupMembershipName } from \"../../workflows/organizations/groupNames/groupMembershipName\";\nimport { commitCurrentGroupPolicyMutation } from \"../../workflows/organizations/groupPolicy/commitCurrentGroupPolicyMutation\";\nimport {\n buildAddGroupUserPolicyRequest,\n buildGroupAccessSetShrinkPolicyRequest,\n buildRemoveGroupUserPolicyRequest,\n} from \"../../workflows/organizations/groupPolicy/groupPolicyRequests\";\nimport {\n createRuntimeCurrentGroupMutation,\n type RuntimeCurrentGroupMutationContext,\n} from \"../../workflows/organizations/principalMutations/runtimeCurrentGroupMutation\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"../../workflows/organizations/trustedOrganizationUsers\";\nimport type { InternalWorkflowRuntimeInput } from \"../runtime/workflowRuntime\";\nimport { preparePrincipalContainerMutations } from \"./principalContainerMutations\";\nimport type { GroupMemberAdmission } from \"./recipientAdmission\";\n\ntype CurrentGroupMutation =\n | {\n readonly kind: \"add\";\n readonly expectedGroupName: string;\n readonly targetUserId: string;\n readonly admission: GroupMemberAdmission;\n }\n | {\n readonly kind: \"remove\";\n readonly expectedGroupName: string;\n readonly removedUserId: string;\n }\n | { readonly kind: \"revoke\"; readonly revokedContainerId: string };\n\n/** Built-in hosts with private custody use bounded current-policy mutation work. */\ninterface CurrentPrincipalMutationInput {\n readonly runtime: InternalWorkflowRuntimeInput;\n readonly organizationId: string;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly stillCurrent: () => boolean;\n}\n\nexport function createCurrentPrincipalMutation(\n input: CurrentPrincipalMutationInput,\n) {\n const mutate = createRuntimeCurrentGroupMutation(input.runtime);\n if (!mutate) return undefined;\n return (groupId: string, mutation: CurrentGroupMutation) =>\n mutate(\n {\n groupId,\n organizationId: input.organizationId,\n signerUserId: input.signerUserId,\n stillCurrent: input.stillCurrent,\n },\n async (context) => {\n const prepareChange = async (\n selected: RuntimeCurrentGroupMutationContext,\n change: CurrentGroupMutation,\n ) => ({\n context: selected,\n request: await buildCurrentMutationRequest(input, selected, change),\n prepareContainerMutations: (\n nextPolicy: Parameters<\n typeof preparePrincipalContainerMutations\n >[0][\"nextPolicy\"],\n preceding?: Parameters<\n typeof preparePrincipalContainerMutations\n >[0][\"preceding\"],\n ) =>\n preparePrincipalContainerMutations({\n preceding,\n currentPolicy: selected.currentPolicy,\n nextPolicy,\n groupId: selected.currentPolicy.currentState.principalId,\n organizationId: input.organizationId,\n runtime: input.runtime,\n stillCurrent: selected.stillCurrent,\n recitationStillCurrent: input.stillCurrent,\n resolveAuthoredPolicyReferences:\n selected.resolveAuthoredPolicyReferences,\n revokedContainerId:\n change.kind === \"revoke\"\n ? change.revokedContainerId\n : undefined,\n }),\n });\n const members = await admitCurrentMembers(groupId, context, mutation);\n const stillCurrent = () =>\n context.stillCurrent() && (members?.stillCurrent() ?? true);\n const primary = await prepareChange(context, mutation);\n assertProjectionVerificationCurrent(stillCurrent);\n let member: Awaited<ReturnType<typeof prepareChange>> | undefined;\n if (\n mutation.kind === \"add\" &&\n members &&\n groupId !== context.memberGroupId &&\n !members.currentPolicy.currentProjection.some(\n (entry) => entry.userId === mutation.targetUserId,\n )\n ) {\n // Preparation awaited identities/metadata; recheck direct self/link\n // admission at fresh enrollment even though the Members view is reused.\n await mutation.admission(members.currentPolicy);\n member = await prepareChange(members, {\n ...mutation,\n expectedGroupName: \"Members\",\n });\n }\n assertProjectionVerificationCurrent(stillCurrent);\n const response = await commitCurrentGroupPolicyMutation({\n ...input,\n apiClient: input.runtime.apiClient,\n groupId,\n ...primary,\n member,\n resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,\n });\n return {\n response,\n memberGroupId: context.memberGroupId,\n enrolled: Boolean(member),\n };\n },\n );\n}\n\nasync function admitCurrentMembers(\n groupId: string,\n context: RuntimeCurrentGroupMutationContext,\n mutation: CurrentGroupMutation,\n) {\n if (mutation.kind !== \"add\") return undefined;\n const members =\n groupId === context.memberGroupId\n ? context\n : await context.loadGroup(context.memberGroupId);\n await mutation.admission(members.currentPolicy);\n assertProjectionVerificationCurrent(context.stillCurrent);\n assertProjectionVerificationCurrent(members.stillCurrent);\n return members;\n}\n\nasync function buildCurrentMutationRequest(\n input: CurrentPrincipalMutationInput,\n context: RuntimeCurrentGroupMutationContext,\n mutation: CurrentGroupMutation,\n): Promise<PutPrincipalPolicyRequest> {\n const shared = {\n ...context,\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n };\n if (mutation.kind !== \"revoke\") {\n await assertGroupMembershipName(\n context.currentPolicy,\n mutation.expectedGroupName,\n createRuntimeGroupMetadataAccess(\n input.runtime,\n input.organizationId,\n context.stillCurrent,\n context.verifyMetadataContainer,\n ).readName,\n );\n }\n const resolveUsers = (userIds: readonly string[]) =>\n resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,\n userIds,\n });\n const projection = context.currentPolicy.currentProjection;\n let request: PutPrincipalPolicyRequest;\n if (mutation.kind === \"add\") {\n const currentUserSecretKey =\n input.runtime.crypto.encapsulationKeyPair?.secretKey;\n if (!currentUserSecretKey)\n throw new Error(\"Organization encryption context is unavailable\");\n const identities = await resolveUsers([\n ...projectionUserIds(projection),\n mutation.targetUserId,\n ]);\n const targetUser = identities.find(\n (identity) => identity.userId === mutation.targetUserId,\n );\n if (!targetUser) throw new Error(\"Group target identity is unavailable\");\n request = await buildAddGroupUserPolicyRequest({\n ...shared,\n currentUserSecretKey,\n targetUser,\n currentUsers: identities.filter(\n (identity) => identity.userId !== mutation.targetUserId,\n ),\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n });\n } else if (mutation.kind === \"remove\") {\n request = await buildRemoveGroupUserPolicyRequest({\n ...shared,\n removedUserId: mutation.removedUserId,\n remainingUsers: await resolveUsers(\n projectionUserIds(\n projection.filter(\n (member) => member.userId !== mutation.removedUserId,\n ),\n ),\n ),\n });\n } else {\n request = await buildGroupAccessSetShrinkPolicyRequest({\n ...shared,\n revokedContainerId: mutation.revokedContainerId,\n currentUsers: await resolveUsers(projectionUserIds(projection)),\n });\n }\n\n return request;\n}\n"]}
1
+ {"version":3,"file":"currentPrincipalMutations.js","sourceRoot":"","sources":["currentPrincipalMutations.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,gCAAgC,EAAE,MAAM,kEAAkE,CAAC;AACpH,OAAO,EAAE,yBAAyB,EAAE,MAAM,8DAA8D,CAAC;AACzG,OAAO,EAAE,gCAAgC,EAAE,MAAM,4EAA4E,CAAC;AAC9H,OAAO,EACL,8BAA8B,EAC9B,sCAAsC,EACtC,iCAAiC,GAClC,MAAM,+DAA+D,CAAC;AACvE,OAAO,EACL,iCAAiC,GAElC,MAAM,8EAA8E,CAAC;AACtF,OAAO,EACL,iBAAiB,EACjB,6BAA6B,GAC9B,MAAM,wDAAwD,CAAC;AAEhE,OAAO,EAAE,kCAAkC,EAAE,MAAM,+BAA+B,CAAC;AA2BnF,MAAM,UAAU,8BAA8B,CAC5C,KAAoC;IAEpC,MAAM,MAAM,GAAG,iCAAiC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAChE,IAAI,CAAC,MAAM;QAAE,OAAO,SAAS,CAAC;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AED,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { SigningKeyPair } from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { createRuntimeGroupMetadataAccess } from \"../../workflows/organizations/groupMetadata/groupMetadataRuntime\";\nimport { assertGroupMembershipName } from \"../../workflows/organizations/groupNames/groupMembershipName\";\nimport { commitCurrentGroupPolicyMutation } from \"../../workflows/organizations/groupPolicy/commitCurrentGroupPolicyMutation\";\nimport {\n buildAddGroupUserPolicyRequest,\n buildGroupAccessSetShrinkPolicyRequest,\n buildRemoveGroupUserPolicyRequest,\n} from \"../../workflows/organizations/groupPolicy/groupPolicyRequests\";\nimport {\n createRuntimeCurrentGroupMutation,\n type RuntimeCurrentGroupMutationContext,\n} from \"../../workflows/organizations/principalMutations/runtimeCurrentGroupMutation\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"../../workflows/organizations/trustedOrganizationUsers\";\nimport type { InternalWorkflowRuntimeInput } from \"../runtime/workflowRuntime\";\nimport { preparePrincipalContainerMutations } from \"./principalContainerMutations\";\nimport type { GroupMemberAdmission } from \"./recipientAdmission\";\n\ntype CurrentGroupMutation =\n | {\n readonly kind: \"add\";\n readonly expectedGroupName: string;\n readonly targetUserId: string;\n readonly admission: GroupMemberAdmission;\n }\n | {\n readonly kind: \"remove\";\n readonly expectedGroupName: string;\n readonly removedUserId: string;\n }\n | { readonly kind: \"revoke\"; readonly revokedContainerId: string };\n\n/** Built-in hosts with private custody use bounded current-policy mutation work. */\ninterface CurrentPrincipalMutationInput {\n readonly runtime: InternalWorkflowRuntimeInput;\n readonly organizationId: string;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly stillCurrent: () => boolean;\n}\n\nexport function createCurrentPrincipalMutation(\n input: CurrentPrincipalMutationInput,\n) {\n const mutate = createRuntimeCurrentGroupMutation(input.runtime);\n if (!mutate) return undefined;\n return (groupId: string, mutation: CurrentGroupMutation) =>\n mutate(\n {\n groupId,\n organizationId: input.organizationId,\n signerUserId: input.signerUserId,\n stillCurrent: input.stillCurrent,\n },\n async (context) => {\n const prepareChange = async (\n selected: RuntimeCurrentGroupMutationContext,\n change: CurrentGroupMutation,\n ) => ({\n context: selected,\n request: await buildCurrentMutationRequest(input, selected, change),\n prepareContainerMutations: (\n nextPolicy: Parameters<\n typeof preparePrincipalContainerMutations\n >[0][\"nextPolicy\"],\n preceding?: Parameters<\n typeof preparePrincipalContainerMutations\n >[0][\"preceding\"],\n ) =>\n preparePrincipalContainerMutations({\n preceding,\n currentPolicy: selected.currentPolicy,\n nextPolicy,\n groupId: selected.currentPolicy.currentState.principalId,\n organizationId: input.organizationId,\n runtime: input.runtime,\n stillCurrent: selected.stillCurrent,\n recitationStillCurrent: input.stillCurrent,\n resolveAuthoredPolicyReferences:\n selected.resolveAuthoredPolicyReferences,\n revokedContainerId:\n change.kind === \"revoke\"\n ? change.revokedContainerId\n : undefined,\n }),\n });\n const members = await admitCurrentMembers(groupId, context, mutation);\n const stillCurrent = () =>\n context.stillCurrent() && (members?.stillCurrent() ?? true);\n const primary = await prepareChange(context, mutation);\n assertProjectionVerificationCurrent(stillCurrent);\n let member: Awaited<ReturnType<typeof prepareChange>> | undefined;\n if (\n mutation.kind === \"add\" &&\n members &&\n groupId !== context.memberGroupId &&\n !members.currentPolicy.currentProjection.some(\n (entry) => entry.userId === mutation.targetUserId,\n )\n ) {\n // Preparation awaited identities/metadata; recheck direct self/link\n // admission at fresh enrollment even though the Members view is reused.\n await mutation.admission(members.currentPolicy);\n member = await prepareChange(members, {\n ...mutation,\n expectedGroupName: \"Members\",\n });\n }\n assertProjectionVerificationCurrent(stillCurrent);\n const response = await commitCurrentGroupPolicyMutation({\n ...input,\n apiClient: input.runtime.apiClient,\n currentUserSecretKey:\n input.runtime.crypto.encapsulationKeyPair?.secretKey ?? null,\n groupId,\n ...primary,\n member,\n resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,\n });\n return {\n response,\n memberGroupId: context.memberGroupId,\n enrolled: Boolean(member),\n };\n },\n );\n}\n\nasync function admitCurrentMembers(\n groupId: string,\n context: RuntimeCurrentGroupMutationContext,\n mutation: CurrentGroupMutation,\n) {\n if (mutation.kind !== \"add\") return undefined;\n const members =\n groupId === context.memberGroupId\n ? context\n : await context.loadGroup(context.memberGroupId);\n await mutation.admission(members.currentPolicy);\n assertProjectionVerificationCurrent(context.stillCurrent);\n assertProjectionVerificationCurrent(members.stillCurrent);\n return members;\n}\n\nasync function buildCurrentMutationRequest(\n input: CurrentPrincipalMutationInput,\n context: RuntimeCurrentGroupMutationContext,\n mutation: CurrentGroupMutation,\n): Promise<PutPrincipalPolicyRequest> {\n const shared = {\n ...context,\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n };\n if (mutation.kind !== \"revoke\") {\n await assertGroupMembershipName(\n context.currentPolicy,\n mutation.expectedGroupName,\n createRuntimeGroupMetadataAccess(\n input.runtime,\n input.organizationId,\n context.stillCurrent,\n context.verifyMetadataContainer,\n ).readName,\n );\n }\n const resolveUsers = (userIds: readonly string[]) =>\n resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,\n userIds,\n });\n const projection = context.currentPolicy.currentProjection;\n let request: PutPrincipalPolicyRequest;\n if (mutation.kind === \"add\") {\n const currentUserSecretKey =\n input.runtime.crypto.encapsulationKeyPair?.secretKey;\n if (!currentUserSecretKey)\n throw new Error(\"Organization encryption context is unavailable\");\n const identities = await resolveUsers([\n ...projectionUserIds(projection),\n mutation.targetUserId,\n ]);\n const targetUser = identities.find(\n (identity) => identity.userId === mutation.targetUserId,\n );\n if (!targetUser) throw new Error(\"Group target identity is unavailable\");\n request = await buildAddGroupUserPolicyRequest({\n ...shared,\n currentUserSecretKey,\n targetUser,\n currentUsers: identities.filter(\n (identity) => identity.userId !== mutation.targetUserId,\n ),\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n });\n } else if (mutation.kind === \"remove\") {\n request = await buildRemoveGroupUserPolicyRequest({\n ...shared,\n removedUserId: mutation.removedUserId,\n remainingUsers: await resolveUsers(\n projectionUserIds(\n projection.filter(\n (member) => member.userId !== mutation.removedUserId,\n ),\n ),\n ),\n });\n } else {\n request = await buildGroupAccessSetShrinkPolicyRequest({\n ...shared,\n revokedContainerId: mutation.revokedContainerId,\n currentUsers: await resolveUsers(projectionUserIds(projection)),\n });\n }\n\n return request;\n}\n"]}
@@ -42,6 +42,7 @@ export declare function addUserToOrganizationGroup(input: PrincipalMutationRunti
42
42
  keyTargetHash: string;
43
43
  parentContainerKeyEpochId: string | null;
44
44
  };
45
+ bundleDigest: string;
45
46
  containerId: string;
46
47
  createdAt: string;
47
48
  eventHash: string;
@@ -85,6 +86,7 @@ export declare function deleteGroupForOrganization(input: OrganizationMutationSc
85
86
  keyTargetHash: string;
86
87
  parentContainerKeyEpochId: string | null;
87
88
  };
89
+ bundleDigest: string;
88
90
  containerId: string;
89
91
  createdAt: string;
90
92
  eventHash: string;
@@ -121,6 +123,7 @@ export declare function removeUserFromOrganizationGroup(input: PrincipalMutation
121
123
  keyTargetHash: string;
122
124
  parentContainerKeyEpochId: string | null;
123
125
  };
126
+ bundleDigest: string;
124
127
  containerId: string;
125
128
  createdAt: string;
126
129
  eventHash: string;
@@ -153,6 +156,7 @@ export declare function revokeOrganizationGrant(input: PrincipalMutationRuntime
153
156
  keyTargetHash: string;
154
157
  parentContainerKeyEpochId: string | null;
155
158
  };
159
+ bundleDigest: string;
156
160
  containerId: string;
157
161
  createdAt: string;
158
162
  eventHash: string;
@@ -174,6 +178,7 @@ export declare function revokeOrganizationGrant(input: PrincipalMutationRuntime
174
178
  keyTargetHash: string;
175
179
  parentContainerKeyEpochId: string | null;
176
180
  };
181
+ bundleDigest: string;
177
182
  containerId: string;
178
183
  createdAt: string;
179
184
  eventHash: string;
@@ -108,6 +108,7 @@ export function deleteGroupForOrganization(input) {
108
108
  return mutate({ ...signingContext, stillCurrent: input.stillCurrent }, (context) => deleteCurrentOrganizationGroup({
109
109
  ...signingContext,
110
110
  context,
111
+ currentUserSecretKey: input.runtime.crypto.encapsulationKeyPair?.secretKey ?? null,
111
112
  groupId: input.groupId,
112
113
  apiClient: input.runtime.apiClient,
113
114
  resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,
@@ -1 +1 @@
1
- {"version":3,"file":"principalMutations.js","sourceRoot":"","sources":["principalMutations.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oCAAoC,EAAE,MAAM,yCAAyC,CAAC;AAC/F,OAAO,EAAE,gCAAgC,EAAE,MAAM,qCAAqC,CAAC;AACvF,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,EA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BACnC,IAAI,EAAE,QAAQ;oBACd,kBAAkB,EAAE,KAAK,CAAC,WAAW;iBACtC,CAAC,CACH,CAAC,QAAQ,CAAC;YACb,CAAC;YACD,OAAO,gCAAgC,CAAC;gBACtC,YAAY,EAAE,KAAK,CAAC,YAAY;gBAChC,WAAW,EAAE,KAAK,CAAC,WAAW;gBAC9B,UAAU,EAAE,IAAI,wBAAwB,CAAC;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 { ProjectionDependencyUnavailableError } from \"../../data/shared/dependencyUnavailable\";\nimport { runWithSecurityIncidentReporting } from \"../../data/shared/securityIncidents\";\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,oCAAoC,EAAE,MAAM,yCAAyC,CAAC;AAC/F,OAAO,EAAE,gCAAgC,EAAE,MAAM,qCAAqC,CAAC;AACvF,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;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,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/shared/dependencyUnavailable\";\nimport { runWithSecurityIncidentReporting } from \"../../data/shared/securityIncidents\";\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 currentUserSecretKey:\n input.runtime.crypto.encapsulationKeyPair?.secretKey ?? null,\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,6 +1,6 @@
1
1
  import { type AccessEvent, type AccessManifest, type ContainerAccessManifestState, type ContainerKeyEpoch, type ContainerKeyWrap } from "../../../internal/crypto/index.js";
2
2
  import type { ContainerMutationResponse } from "../../../internal/validators/response/index.js";
3
- import type { LocallyAcknowledgedAccessManifestHead } from "../../persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js";
3
+ import { type LocallyAcknowledgedAccessManifestHead } from "../../persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js";
4
4
  import type { ExecSql } from "../../sqlite/sqlSchema.js";
5
5
  export interface AuthoredContainerMutationHead {
6
6
  readonly body: object;
@@ -1,6 +1,7 @@
1
- import { accessManifestCheckpointFromManifest, compareCanonicalStrings, computeContainerKekKeyringHash, computeContainerKekRecipientTargetHash, computeContainerKeyEpochHash, } from "../../../internal/crypto/index.js";
1
+ import { compareCanonicalStrings, computeContainerKekKeyringHash, computeContainerKekRecipientTargetHash, computeContainerKeyEpochHash, } from "../../../internal/crypto/index.js";
2
2
  import { canonicalKeyingJsonString } from "../../keying/canonicalJson.js";
3
3
  import { KeyingCheckpointRepository } from "../../persistence/keyingCheckpoints/keyingCheckpointRepository.js";
4
+ import { locallyAcknowledgedAuthoredHead, } from "../../persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js";
4
5
  function expectedRecipientTargets(wraps) {
5
6
  return [
6
7
  ...wraps.map((wrap) => ({
@@ -87,13 +88,7 @@ async function assertResponseCommitments(plan, response) {
87
88
  export async function locallyAcknowledgedContainerMutationHead(input) {
88
89
  assertResponseIdentity(input.plan, input.response);
89
90
  await assertResponseCommitments(input.plan, input.response);
90
- return {
91
- checkpoint: accessManifestCheckpointFromManifest({
92
- manifest: input.plan.manifest,
93
- manifestHash: input.plan.manifestHash,
94
- }),
95
- previousManifestHash: input.plan.manifest.previousManifestHash,
96
- };
91
+ return locallyAcknowledgedAuthoredHead(input.plan, input.response.bundleDigest);
97
92
  }
98
93
  /** Correlates an API acknowledgement to the locally signed plan before pinning. */
99
94
  export async function acknowledgeContainerMutation(input) {
@@ -1 +1 @@
1
- {"version":3,"file":"mutationAcknowledgement.js","sourceRoot":"","sources":["mutationAcknowledgement.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,oCAAoC,EAKpC,uBAAuB,EACvB,8BAA8B,EAC9B,sCAAsC,EACtC,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EAAE,0BAA0B,EAAE,MAAM,gEAAgE,CAAC;AAqB5G,SAAS,wBAAwB,CAC/B,KAAkC;IAElC,OAAO;QACL,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;YACtB,WAAW,EAAE,IAAI,CAAC,WAAW;YAC7B,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;YAC7C,uBAAuB,EAAE,IAAI,CAAC,uBAAuB;YACrD,aAAa,EAAE,IAAI,CAAC,aAAa;SAClC,CAAC,CAAC;KACJ,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CACrB,uBAAuB,CACrB,yBAAyB,CAAC,IAAI,EAAE,kBAAkB,CAAC,EACnD,yBAAyB,CAAC,KAAK,EAAE,kBAAkB,CAAC,CACrD,CACF,CAAC;AACJ,CAAC;AAED,SAAS,sBAAsB,CAC7B,IAAmC,EACnC,QAAmC;IAEnC,IACE,QAAQ,CAAC,WAAW,KAAK,IAAI,CAAC,WAAW;QACzC,QAAQ,CAAC,cAAc,KAAK,IAAI,CAAC,KAAK,CAAC,cAAc;QACrD,QAAQ,CAAC,QAAQ,KAAK,IAAI,CAAC,KAAK,CAAC,iBAAiB,EAClD,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC1E,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AC;QACD,OAAO,wCAAwC,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC;IACtE,CAAC,CAAC,CACH,CAAC;IACF,OAAO,IAAI,0BAA0B,CACnC,KAAK,CAAC,OAAO,CACd,CAAC,uDAAuD,CAAC;QACxD,KAAK;QACL,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n type AccessEvent,\n type AccessManifest,\n accessManifestCheckpointFromManifest,\n type ContainerAccessManifestState,\n type ContainerKekRecipientTarget,\n type ContainerKeyEpoch,\n type ContainerKeyWrap,\n compareCanonicalStrings,\n computeContainerKekKeyringHash,\n computeContainerKekRecipientTargetHash,\n computeContainerKeyEpochHash,\n} from \"@tearleads/crypto\";\nimport type { ContainerMutationResponse } from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../../keying/canonicalJson\";\nimport { KeyingCheckpointRepository } from \"../../persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport type { LocallyAcknowledgedAccessManifestHead } from \"../../persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\n\nexport interface AuthoredContainerMutationHead {\n readonly body: object;\n readonly containerId: string;\n readonly event: AccessEvent;\n readonly eventHash: string;\n readonly keyEpoch: ContainerKeyEpoch;\n readonly manifest: AccessManifest;\n readonly manifestHash: string;\n /**\n * The keyring the epoch already had, for mutations that keep their epoch.\n * Its artifact is immutable, so the acknowledged keyring hash must be its.\n */\n readonly previousKeyring?: Record<string, unknown> | null | undefined;\n readonly state: ContainerAccessManifestState;\n readonly wraps: readonly ContainerKeyWrap[];\n}\n\nfunction expectedRecipientTargets(\n wraps: readonly ContainerKeyWrap[],\n): ContainerKekRecipientTarget[] {\n return [\n ...wraps.map((wrap) => ({\n recipientId: wrap.recipientId,\n recipientKeyEpochId: wrap.recipientKeyEpochId,\n recipientKeyFingerprint: wrap.recipientKeyFingerprint,\n recipientKind: wrap.recipientKind,\n })),\n ].sort((left, right) =>\n compareCanonicalStrings(\n canonicalKeyingJsonString(left, \"recipient target\"),\n canonicalKeyingJsonString(right, \"recipient target\"),\n ),\n );\n}\n\nfunction assertResponseIdentity(\n plan: AuthoredContainerMutationHead,\n response: ContainerMutationResponse,\n): void {\n if (\n response.containerId !== plan.containerId ||\n response.organizationId !== plan.state.organizationId ||\n response.parentId !== plan.state.parentContainerId\n ) {\n throw new Error(\"Container mutation response object identity mismatch\");\n }\n // The top-level slot column is what local system-container lookups key on,\n // so it must name the slot this client signed into the manifest state; an\n // omitted slot is the server's spelling of null.\n if ((response.systemSlot ?? null) !== plan.state.systemSlot) {\n throw new Error(\"Container mutation response system slot mismatch\");\n }\n // The manifest hash commits to the signed event (by hash), the derived\n // state, and the key target set, so equal hashes acknowledge exactly the\n // manifest this client signed.\n if (\n response.manifestHead.epoch !== plan.state.epoch ||\n response.manifestHead.manifestHash !== plan.manifestHash ||\n response.eventHash !== plan.eventHash\n ) {\n throw new Error(\"Container mutation response manifest head mismatch\");\n }\n if (\n response.containerKek.containerKeyEpochId !== plan.keyEpoch.id ||\n response.containerKek.containerKeyEpoch !== plan.keyEpoch.keyEpoch\n ) {\n throw new Error(\"Container mutation response KEK identity mismatch\");\n }\n}\n\n/** A rotation body commits a keyring hash; other bodies do not. */\nfunction readOptionalKeyringHash(body: object): string | null {\n const value = Reflect.get(body, \"keyringHash\");\n return typeof value === \"string\" ? value : null;\n}\n\n/**\n * The keyring the server stored must be the one this client's own signed\n * event committed to, or, for a mutation that keeps its epoch, the immutable\n * artifact that epoch already had. The acknowledgement is the moment the\n * response becomes trusted, so the commitment is checked here.\n */\nasync function assertAcknowledgedKeyringHash(\n plan: AuthoredContainerMutationHead,\n keyringHash: string | null,\n): Promise<void> {\n const committedHash = readOptionalKeyringHash(plan.body);\n if (committedHash !== null) {\n if (keyringHash !== committedHash) {\n throw new Error(\n \"Container mutation response keyring does not match its signed event\",\n );\n }\n return;\n }\n const previous = plan.previousKeyring ?? null;\n if (previous === null) {\n // The epoch had no keyring, so the response must not invent one: an\n // injected snapshot would become the next writer projection's history.\n if (keyringHash !== null) {\n throw new Error(\n \"Container mutation response added a keyring to an unchanged epoch\",\n );\n }\n return;\n }\n if (keyringHash === null) {\n throw new Error(\n \"Container mutation response dropped its unchanged keyring\",\n );\n }\n if (keyringHash !== (await computeContainerKekKeyringHash(previous))) {\n throw new Error(\n \"Container mutation response replaced its unchanged keyring\",\n );\n }\n}\n\nasync function assertResponseCommitments(\n plan: AuthoredContainerMutationHead,\n response: ContainerMutationResponse,\n): Promise<void> {\n const kek = response.containerKek;\n await assertAcknowledgedKeyringHash(plan, kek.keyringHash);\n // The recipient target hash is how the #2158 wrong-recipient checks reach\n // the acknowledgement: it commits to every wrap's recipient, so a server\n // that stored a wrap for anyone else cannot match it.\n if (\n kek.keyEpochHash !== (await computeContainerKeyEpochHash(plan.keyEpoch)) ||\n kek.keyTargetHash !==\n (await computeContainerKekRecipientTargetHash(\n expectedRecipientTargets(plan.wraps),\n )) ||\n kek.parentContainerKeyEpochId !== plan.keyEpoch.parentContainerKeyEpochId\n ) {\n throw new Error(\"Container mutation response KEK commitment mismatch\");\n }\n}\n\nexport async function locallyAcknowledgedContainerMutationHead(input: {\n readonly plan: AuthoredContainerMutationHead;\n readonly response: ContainerMutationResponse;\n}): Promise<LocallyAcknowledgedAccessManifestHead> {\n assertResponseIdentity(input.plan, input.response);\n await assertResponseCommitments(input.plan, input.response);\n return {\n checkpoint: accessManifestCheckpointFromManifest({\n manifest: input.plan.manifest,\n manifestHash: input.plan.manifestHash,\n }),\n previousManifestHash: input.plan.manifest.previousManifestHash,\n };\n}\n\n/** Correlates an API acknowledgement to the locally signed plan before pinning. */\nexport async function acknowledgeContainerMutation(input: {\n readonly execSql: ExecSql;\n readonly plan: AuthoredContainerMutationHead;\n readonly response: ContainerMutationResponse;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<boolean> {\n return new KeyingCheckpointRepository(\n input.execSql,\n ).advanceLocallyAcknowledgedAccessManifestHeadsAtomically({\n heads: [\n await locallyAcknowledgedContainerMutationHead({\n plan: input.plan,\n response: input.response,\n }),\n ],\n stillCurrent: input.stillCurrent,\n });\n}\n\n/** Correlates and advances a complete authored mutation batch atomically. */\nexport async function acknowledgeContainerMutationBatch(input: {\n readonly execSql: ExecSql;\n readonly plans: readonly AuthoredContainerMutationHead[];\n readonly responses: readonly ContainerMutationResponse[];\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<boolean> {\n if (input.plans.length !== input.responses.length) {\n throw new Error(\"Container mutation acknowledgement batch is incomplete\");\n }\n const heads = await Promise.all(\n input.plans.map(async (plan, index) => {\n const response = input.responses[index];\n if (!response) {\n throw new Error(\n \"Container mutation acknowledgement batch is incomplete\",\n );\n }\n return locallyAcknowledgedContainerMutationHead({ plan, response });\n }),\n );\n return new KeyingCheckpointRepository(\n input.execSql,\n ).advanceLocallyAcknowledgedAccessManifestHeadsAtomically({\n heads,\n stillCurrent: input.stillCurrent,\n });\n}\n"]}
1
+ {"version":3,"file":"mutationAcknowledgement.js","sourceRoot":"","sources":["mutationAcknowledgement.ts"],"names":[],"mappings":"AAAA,OAAO,EAOL,uBAAuB,EACvB,8BAA8B,EAC9B,sCAAsC,EACtC,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EAAE,0BAA0B,EAAE,MAAM,gEAAgE,CAAC;AAC5G,OAAO,EAEL,+BAA+B,GAChC,MAAM,8EAA8E,CAAC;AAoBtF,SAAS,wBAAwB,CAC/B,KAAkC;IAElC,OAAO;QACL,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;YACtB,WAAW,EAAE,IAAI,CAAC,WAAW;YAC7B,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;YAC7C,uBAAuB,EAAE,IAAI,CAAC,uB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C,MAAM,KAAK,KAAK,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC;QAClD,MAAM,IAAI,KAAK,CAAC,wDAAwD,CAAC,CAAC;IAC5E,CAAC;IACD,MAAM,KAAK,GAAG,MAAM,OAAO,CAAC,GAAG,CAC7B,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE;QACpC,MAAM,QAAQ,GAAG,KAAK,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;QACxC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,MAAM,IAAI,KAAK,CACb,wDAAwD,CACzD,CAAC;QACJ,CAAC;QACD,OAAO,wCAAwC,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC;IACtE,CAAC,CAAC,CACH,CAAC;IACF,OAAO,IAAI,0BAA0B,CACnC,KAAK,CAAC,OAAO,CACd,CAAC,uDAAuD,CAAC;QACxD,KAAK;QACL,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n type AccessEvent,\n type AccessManifest,\n type ContainerAccessManifestState,\n type ContainerKekRecipientTarget,\n type ContainerKeyEpoch,\n type ContainerKeyWrap,\n compareCanonicalStrings,\n computeContainerKekKeyringHash,\n computeContainerKekRecipientTargetHash,\n computeContainerKeyEpochHash,\n} from \"@tearleads/crypto\";\nimport type { ContainerMutationResponse } from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../../keying/canonicalJson\";\nimport { KeyingCheckpointRepository } from \"../../persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport {\n type LocallyAcknowledgedAccessManifestHead,\n locallyAcknowledgedAuthoredHead,\n} from \"../../persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\n\nexport interface AuthoredContainerMutationHead {\n readonly body: object;\n readonly containerId: string;\n readonly event: AccessEvent;\n readonly eventHash: string;\n readonly keyEpoch: ContainerKeyEpoch;\n readonly manifest: AccessManifest;\n readonly manifestHash: string;\n /**\n * The keyring the epoch already had, for mutations that keep their epoch.\n * Its artifact is immutable, so the acknowledged keyring hash must be its.\n */\n readonly previousKeyring?: Record<string, unknown> | null | undefined;\n readonly state: ContainerAccessManifestState;\n readonly wraps: readonly ContainerKeyWrap[];\n}\n\nfunction expectedRecipientTargets(\n wraps: readonly ContainerKeyWrap[],\n): ContainerKekRecipientTarget[] {\n return [\n ...wraps.map((wrap) => ({\n recipientId: wrap.recipientId,\n recipientKeyEpochId: wrap.recipientKeyEpochId,\n recipientKeyFingerprint: wrap.recipientKeyFingerprint,\n recipientKind: wrap.recipientKind,\n })),\n ].sort((left, right) =>\n compareCanonicalStrings(\n canonicalKeyingJsonString(left, \"recipient target\"),\n canonicalKeyingJsonString(right, \"recipient target\"),\n ),\n );\n}\n\nfunction assertResponseIdentity(\n plan: AuthoredContainerMutationHead,\n response: ContainerMutationResponse,\n): void {\n if (\n response.containerId !== plan.containerId ||\n response.organizationId !== plan.state.organizationId ||\n response.parentId !== plan.state.parentContainerId\n ) {\n throw new Error(\"Container mutation response object identity mismatch\");\n }\n // The top-level slot column is what local system-container lookups key on,\n // so it must name the slot this client signed into the manifest state; an\n // omitted slot is the server's spelling of null.\n if ((response.systemSlot ?? null) !== plan.state.systemSlot) {\n throw new Error(\"Container mutation response system slot mismatch\");\n }\n // The manifest hash commits to the signed event (by hash), the derived\n // state, and the key target set, so equal hashes acknowledge exactly the\n // manifest this client signed.\n if (\n response.manifestHead.epoch !== plan.state.epoch ||\n response.manifestHead.manifestHash !== plan.manifestHash ||\n response.eventHash !== plan.eventHash\n ) {\n throw new Error(\"Container mutation response manifest head mismatch\");\n }\n if (\n response.containerKek.containerKeyEpochId !== plan.keyEpoch.id ||\n response.containerKek.containerKeyEpoch !== plan.keyEpoch.keyEpoch\n ) {\n throw new Error(\"Container mutation response KEK identity mismatch\");\n }\n}\n\n/** A rotation body commits a keyring hash; other bodies do not. */\nfunction readOptionalKeyringHash(body: object): string | null {\n const value = Reflect.get(body, \"keyringHash\");\n return typeof value === \"string\" ? value : null;\n}\n\n/**\n * The keyring the server stored must be the one this client's own signed\n * event committed to, or, for a mutation that keeps its epoch, the immutable\n * artifact that epoch already had. The acknowledgement is the moment the\n * response becomes trusted, so the commitment is checked here.\n */\nasync function assertAcknowledgedKeyringHash(\n plan: AuthoredContainerMutationHead,\n keyringHash: string | null,\n): Promise<void> {\n const committedHash = readOptionalKeyringHash(plan.body);\n if (committedHash !== null) {\n if (keyringHash !== committedHash) {\n throw new Error(\n \"Container mutation response keyring does not match its signed event\",\n );\n }\n return;\n }\n const previous = plan.previousKeyring ?? null;\n if (previous === null) {\n // The epoch had no keyring, so the response must not invent one: an\n // injected snapshot would become the next writer projection's history.\n if (keyringHash !== null) {\n throw new Error(\n \"Container mutation response added a keyring to an unchanged epoch\",\n );\n }\n return;\n }\n if (keyringHash === null) {\n throw new Error(\n \"Container mutation response dropped its unchanged keyring\",\n );\n }\n if (keyringHash !== (await computeContainerKekKeyringHash(previous))) {\n throw new Error(\n \"Container mutation response replaced its unchanged keyring\",\n );\n }\n}\n\nasync function assertResponseCommitments(\n plan: AuthoredContainerMutationHead,\n response: ContainerMutationResponse,\n): Promise<void> {\n const kek = response.containerKek;\n await assertAcknowledgedKeyringHash(plan, kek.keyringHash);\n // The recipient target hash is how the #2158 wrong-recipient checks reach\n // the acknowledgement: it commits to every wrap's recipient, so a server\n // that stored a wrap for anyone else cannot match it.\n if (\n kek.keyEpochHash !== (await computeContainerKeyEpochHash(plan.keyEpoch)) ||\n kek.keyTargetHash !==\n (await computeContainerKekRecipientTargetHash(\n expectedRecipientTargets(plan.wraps),\n )) ||\n kek.parentContainerKeyEpochId !== plan.keyEpoch.parentContainerKeyEpochId\n ) {\n throw new Error(\"Container mutation response KEK commitment mismatch\");\n }\n}\n\nexport async function locallyAcknowledgedContainerMutationHead(input: {\n readonly plan: AuthoredContainerMutationHead;\n readonly response: ContainerMutationResponse;\n}): Promise<LocallyAcknowledgedAccessManifestHead> {\n assertResponseIdentity(input.plan, input.response);\n await assertResponseCommitments(input.plan, input.response);\n return locallyAcknowledgedAuthoredHead(\n input.plan,\n input.response.bundleDigest,\n );\n}\n\n/** Correlates an API acknowledgement to the locally signed plan before pinning. */\nexport async function acknowledgeContainerMutation(input: {\n readonly execSql: ExecSql;\n readonly plan: AuthoredContainerMutationHead;\n readonly response: ContainerMutationResponse;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<boolean> {\n return new KeyingCheckpointRepository(\n input.execSql,\n ).advanceLocallyAcknowledgedAccessManifestHeadsAtomically({\n heads: [\n await locallyAcknowledgedContainerMutationHead({\n plan: input.plan,\n response: input.response,\n }),\n ],\n stillCurrent: input.stillCurrent,\n });\n}\n\n/** Correlates and advances a complete authored mutation batch atomically. */\nexport async function acknowledgeContainerMutationBatch(input: {\n readonly execSql: ExecSql;\n readonly plans: readonly AuthoredContainerMutationHead[];\n readonly responses: readonly ContainerMutationResponse[];\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<boolean> {\n if (input.plans.length !== input.responses.length) {\n throw new Error(\"Container mutation acknowledgement batch is incomplete\");\n }\n const heads = await Promise.all(\n input.plans.map(async (plan, index) => {\n const response = input.responses[index];\n if (!response) {\n throw new Error(\n \"Container mutation acknowledgement batch is incomplete\",\n );\n }\n return locallyAcknowledgedContainerMutationHead({ plan, response });\n }),\n );\n return new KeyingCheckpointRepository(\n input.execSql,\n ).advanceLocallyAcknowledgedAccessManifestHeadsAtomically({\n heads,\n stillCurrent: input.stillCurrent,\n });\n}\n"]}
@@ -1,9 +1,18 @@
1
1
  import { KeyingCheckpointRepository } from "../../../persistence/keyingCheckpoints/keyingCheckpointRepository.js";
2
- import { locallyAuthoredAccessManifestHead } from "../../../persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js";
2
+ import { locallyAcknowledgedAuthoredHead, } from "../../../persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js";
3
+ /**
4
+ * A matched document head, carrying its authored bundle for citation when
5
+ * the acknowledgement's digest names exactly it.
6
+ */
7
+ export async function locallyAcknowledgedDocumentHead(plan, bundleDigest) {
8
+ return locallyAcknowledgedAuthoredHead(plan, bundleDigest);
9
+ }
3
10
  /** Advances a document head only after its response was matched to this plan. */
4
11
  export async function acknowledgeDocumentMutation(input) {
5
12
  await new KeyingCheckpointRepository(input.execSql).advanceLocallyAcknowledgedAccessManifestHeadsAtomically({
6
- heads: [locallyAuthoredAccessManifestHead(input.plan)],
13
+ heads: [
14
+ await locallyAcknowledgedDocumentHead(input.plan, input.bundleDigest),
15
+ ],
7
16
  stillCurrent: input.stillCurrent,
8
17
  });
9
18
  }
@@ -1 +1 @@
1
- {"version":3,"file":"mutationAcknowledgement.js","sourceRoot":"","sources":["mutationAcknowledgement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,MAAM,mEAAmE,CAAC;AAC/G,OAAO,EAAE,iCAAiC,EAAE,MAAM,iFAAiF,CAAC;AAGpI,iFAAiF;AACjF,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAAC,KAIjD;IACC,MAAM,IAAI,0BAA0B,CAClC,KAAK,CAAC,OAAO,CACd,CAAC,uDAAuD,CAAC;QACxD,KAAK,EAAE,CAAC,iCAAiC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACtD,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { KeyingCheckpointRepository } from \"../../../persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { locallyAuthoredAccessManifestHead } from \"../../../persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\n\n/** Advances a document head only after its response was matched to this plan. */\nexport async function acknowledgeDocumentMutation(input: {\n readonly execSql: ExecSql;\n readonly plan: Parameters<typeof locallyAuthoredAccessManifestHead>[0];\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<void> {\n await new KeyingCheckpointRepository(\n input.execSql,\n ).advanceLocallyAcknowledgedAccessManifestHeadsAtomically({\n heads: [locallyAuthoredAccessManifestHead(input.plan)],\n stillCurrent: input.stillCurrent,\n });\n}\n"]}
1
+ {"version":3,"file":"mutationAcknowledgement.js","sourceRoot":"","sources":["mutationAcknowledgement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,MAAM,mEAAmE,CAAC;AAC/G,OAAO,EAGL,+BAA+B,GAChC,MAAM,iFAAiF,CAAC;AAGzF;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,+BAA+B,CACnD,IAA4B,EAC5B,YAAoB;IAEpB,OAAO,+BAA+B,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;AAC7D,CAAC;AAED,iFAAiF;AACjF,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAAC,KAKjD;IACC,MAAM,IAAI,0BAA0B,CAClC,KAAK,CAAC,OAAO,CACd,CAAC,uDAAuD,CAAC;QACxD,KAAK,EAAE;YACL,MAAM,+BAA+B,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,YAAY,CAAC;SACtE;QACD,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { KeyingCheckpointRepository } from \"../../../persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport {\n type AuthoredManifestBundle,\n type LocallyAcknowledgedAccessManifestHead,\n locallyAcknowledgedAuthoredHead,\n} from \"../../../persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\n\n/**\n * A matched document head, carrying its authored bundle for citation when\n * the acknowledgement's digest names exactly it.\n */\nexport async function locallyAcknowledgedDocumentHead(\n plan: AuthoredManifestBundle,\n bundleDigest: string,\n): Promise<LocallyAcknowledgedAccessManifestHead> {\n return locallyAcknowledgedAuthoredHead(plan, bundleDigest);\n}\n\n/** Advances a document head only after its response was matched to this plan. */\nexport async function acknowledgeDocumentMutation(input: {\n readonly bundleDigest: string;\n readonly execSql: ExecSql;\n readonly plan: AuthoredManifestBundle;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<void> {\n await new KeyingCheckpointRepository(\n input.execSql,\n ).advanceLocallyAcknowledgedAccessManifestHeadsAtomically({\n heads: [\n await locallyAcknowledgedDocumentHead(input.plan, input.bundleDigest),\n ],\n stillCurrent: input.stillCurrent,\n });\n}\n"]}
@@ -0,0 +1,26 @@
1
+ import type { ExecSql } from "../../sqlite/sqlSchema.js";
2
+ /**
3
+ * Runs a projection verification whose projection may have taken bundles
4
+ * from this device's citation store. A store row is never verifier trust
5
+ * input, but a wrong one (such as a seeded authored bundle) would otherwise
6
+ * fail every read that cites it. When such a projection fails to verify (or
7
+ * a dependency it names, such as its signer, is unavailable), the
8
+ * cited rows are dropped (only those still holding the exact bytes cited, and
9
+ * only while the request is current) and the projection is marked refused so
10
+ * no cache serves it again: the next read fetches those bundles from the
11
+ * server and its verification decides. The refusal itself is reported
12
+ * unchanged, so a failure in freshly served evidence keeps its meaning.
13
+ */
14
+ interface HeldBundleRecoveryInput {
15
+ readonly execSql: ExecSql;
16
+ readonly projection: object;
17
+ readonly stillCurrent?: (() => boolean) | undefined;
18
+ }
19
+ export declare function verifyWithHeldBundleRecovery<T>(input: HeldBundleRecoveryInput, verify: () => Promise<T>): Promise<T>;
20
+ /**
21
+ * The same recovery for a check of a projection's own consistency that runs
22
+ * before verification (such as a document head's hashes before a queued
23
+ * write): any refusal of a projection that took held bundles drops them.
24
+ */
25
+ export declare function checkWithHeldBundleRecovery<T>(input: HeldBundleRecoveryInput, check: () => Promise<T>): Promise<T>;
26
+ export {};
@@ -0,0 +1,46 @@
1
+ import { KeyingVerificationError } from "../../../internal/crypto/index.js";
2
+ import { acceptDecodedProjection, heldBundlesUsedBy, rejectDecodedProjection, } from "../../../internal/validators/response/index.js";
3
+ import { dropHeldManifestBundles, suppressHeldCitations, } from "../../persistence/verifiedManifestBundlePersistence.js";
4
+ import { ProjectionDependencyUnavailableError } from "../../shared/dependencyUnavailable.js";
5
+ export function verifyWithHeldBundleRecovery(input, verify) {
6
+ return runWithHeldBundleRecovery(input, verify, (error) => error instanceof KeyingVerificationError ||
7
+ error instanceof ProjectionDependencyUnavailableError, true);
8
+ }
9
+ /**
10
+ * The same recovery for a check of a projection's own consistency that runs
11
+ * before verification (such as a document head's hashes before a queued
12
+ * write): any refusal of a projection that took held bundles drops them.
13
+ */
14
+ export function checkWithHeldBundleRecovery(input, check) {
15
+ return runWithHeldBundleRecovery(input, check, () => true, false);
16
+ }
17
+ async function runWithHeldBundleRecovery(input, run, recovers, verifies) {
18
+ try {
19
+ const result = await run();
20
+ // Only a full, current verification vouches for every held byte it used;
21
+ // a consistency check covers one bundle and accepts nothing.
22
+ if (verifies && input.stillCurrent?.() !== false)
23
+ acceptDecodedProjection(input.projection);
24
+ return result;
25
+ }
26
+ catch (error) {
27
+ const held = heldBundlesUsedBy(input.projection);
28
+ // A superseded request changes no shared cache state.
29
+ if (held.length > 0 &&
30
+ input.stillCurrent?.() !== false &&
31
+ recovers(error)) {
32
+ // No read cites these rows while they are dropped, and no cache serves
33
+ // this projection again, so the next read fetches the bundles.
34
+ const release = suppressHeldCitations(held.map((bundle) => bundle.manifestHash));
35
+ rejectDecodedProjection(input.projection);
36
+ // Released only once the rows are gone: a drop that failed or was
37
+ // superseded keeps them out of this process's citations rather than
38
+ // citing the same bytes again.
39
+ const dropped = await dropHeldManifestBundles(input.execSql, held, input.stillCurrent).catch(() => false);
40
+ if (dropped)
41
+ release();
42
+ }
43
+ throw error;
44
+ }
45
+ }
46
+ //# sourceMappingURL=heldBundleRecovery.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"heldBundleRecovery.js","sourceRoot":"","sources":["heldBundleRecovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,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/D,MAAM,OAAO,GAAG,qBAAqB,CACnC,IAAI,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,YAAY,CAAC,CAC1C,CAAC;YACF,uBAAuB,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;YAC1C,kEAAkE;YAClE,oEAAoE;YACpE,+BAA+B;YAC/B,MAAM,OAAO,GAAG,MAAM,uBAAuB,CAC3C,KAAK,CAAC,OAAO,EACb,IAAI,EACJ,KAAK,CAAC,YAAY,CACnB,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC;YACrB,IAAI,OAAO;gBAAE,OAAO,EAAE,CAAC;QACzB,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n acceptDecodedProjection,\n heldBundlesUsedBy,\n rejectDecodedProjection,\n} from \"@tearleads/validators/response\";\nimport {\n dropHeldManifestBundles,\n suppressHeldCitations,\n} from \"../../persistence/verifiedManifestBundlePersistence\";\nimport { ProjectionDependencyUnavailableError } from \"../../shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\n\n/**\n * Runs a projection verification whose projection may have taken bundles\n * from this device's citation store. A store row is never verifier trust\n * input, but a wrong one (such as a seeded authored bundle) would otherwise\n * fail every read that cites it. When such a projection fails to verify (or\n * a dependency it names, such as its signer, is unavailable), the\n * cited rows are dropped (only those still holding the exact bytes cited, and\n * only while the request is current) and the projection is marked refused so\n * no cache serves it again: the next read fetches those bundles from the\n * server and its verification decides. The refusal itself is reported\n * unchanged, so a failure in freshly served evidence keeps its meaning.\n */\ninterface HeldBundleRecoveryInput {\n readonly execSql: ExecSql;\n readonly projection: object;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nexport function verifyWithHeldBundleRecovery<T>(\n input: HeldBundleRecoveryInput,\n verify: () => Promise<T>,\n): Promise<T> {\n return runWithHeldBundleRecovery(\n input,\n verify,\n (error) =>\n error instanceof KeyingVerificationError ||\n error instanceof ProjectionDependencyUnavailableError,\n true,\n );\n}\n\n/**\n * The same recovery for a check of a projection's own consistency that runs\n * before verification (such as a document head's hashes before a queued\n * write): any refusal of a projection that took held bundles drops them.\n */\nexport function checkWithHeldBundleRecovery<T>(\n input: HeldBundleRecoveryInput,\n check: () => Promise<T>,\n): Promise<T> {\n return runWithHeldBundleRecovery(input, check, () => true, false);\n}\n\nasync function runWithHeldBundleRecovery<T>(\n input: HeldBundleRecoveryInput,\n run: () => Promise<T>,\n recovers: (error: unknown) => boolean,\n verifies: boolean,\n): Promise<T> {\n try {\n const result = await run();\n // Only a full, current verification vouches for every held byte it used;\n // a consistency check covers one bundle and accepts nothing.\n if (verifies && input.stillCurrent?.() !== false)\n acceptDecodedProjection(input.projection);\n return result;\n } catch (error) {\n const held = heldBundlesUsedBy(input.projection);\n // A superseded request changes no shared cache state.\n if (\n held.length > 0 &&\n input.stillCurrent?.() !== false &&\n recovers(error)\n ) {\n // No read cites these rows while they are dropped, and no cache serves\n // this projection again, so the next read fetches the bundles.\n const release = suppressHeldCitations(\n held.map((bundle) => bundle.manifestHash),\n );\n rejectDecodedProjection(input.projection);\n // Released only once the rows are gone: a drop that failed or was\n // superseded keeps them out of this process's citations rather than\n // citing the same bytes again.\n const dropped = await dropHeldManifestBundles(\n input.execSql,\n held,\n input.stillCurrent,\n ).catch(() => false);\n if (dropped) release();\n }\n throw error;\n }\n}\n"]}
@@ -2,16 +2,19 @@ import type { VerifiedContainerAccessManifest } from "../../../internal/crypto/i
2
2
  import type { ContainerWriterProjectionResponse } from "../../../internal/validators/response/index.js";
3
3
  import type { ExecSql } from "../../sqlite/sqlSchema.js";
4
4
  import type { OpenPrincipalPolicyBundleReader, ProjectionUserKeyResolver, ReferencedPrincipalPolicyWarmer } from "../types.js";
5
- /** Authenticate immutable destination roles without advancing write-authority pins. */
6
- export declare function verifyContainerDestinationProjection(input: {
5
+ interface ContainerDestinationProjectionInput {
7
6
  readonly execSql: ExecSql;
8
7
  readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;
9
8
  readonly projection: ContainerWriterProjectionResponse;
10
9
  readonly resolveUserKey: ProjectionUserKeyResolver;
11
10
  readonly stillCurrent?: (() => boolean) | undefined;
12
11
  readonly warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;
13
- }): Promise<{
12
+ }
13
+ interface VerifiedContainerDestination {
14
14
  readonly path: VerifiedContainerAccessManifest[];
15
15
  /** Every manifest verified on the way, including each head's lineage. */
16
16
  readonly verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;
17
- }>;
17
+ }
18
+ /** Authenticate immutable destination roles without advancing write-authority pins. */
19
+ export declare function verifyContainerDestinationProjection(input: ContainerDestinationProjectionInput): Promise<VerifiedContainerDestination>;
20
+ export {};
@@ -1,11 +1,15 @@
1
1
  import { createProjectionCheckpointContext, finalizeProjectionCheckpoints, observeVerifiedKekLevels, observeVerifiedProjectionBundles, } from "../checkpoints/checkpointContext.js";
2
+ import { verifyWithHeldBundleRecovery } from "../checkpoints/heldBundleRecovery.js";
2
3
  import { verifyProjectionAuthorizationEvidence } from "../principalPolicy/projectionAuthorizationEvidence.js";
3
4
  import { projectionLifetimeGuard } from "../projectionLifetimes.js";
4
5
  import { assertProjectionVerificationCurrent } from "../types.js";
5
6
  import { verifyContainerManifestPath } from "./containerPathVerification.js";
6
7
  import { addContainerWriterProjectionBundles } from "./containerProjectionVerification.js";
7
8
  /** Authenticate immutable destination roles without advancing write-authority pins. */
8
- export async function verifyContainerDestinationProjection(input) {
9
+ export function verifyContainerDestinationProjection(input) {
10
+ return verifyWithHeldBundleRecovery(input, () => verifyContainerDestinationProjectionOnce(input));
11
+ }
12
+ async function verifyContainerDestinationProjectionOnce(input) {
9
13
  const bundlesByHash = new Map();
10
14
  addContainerWriterProjectionBundles(bundlesByHash, input.projection, "Container destination");
11
15
  const verifiedByHash = new Map();
@@ -1 +1 @@
1
- {"version":3,"file":"containerDestinationVerification.js","sourceRoot":"","sources":["containerDestinationVerification.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,iCAAiC,EACjC,6BAA6B,EAC7B,wBAAwB,EACxB,gCAAgC,GACjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,qCAAqC,EAAE,MAAM,oDAAoD,CAAC;AAC3G,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAMjE,OAAO,EAAE,mCAAmC,EAAE,MAAM,UAAU,CAAC;AAC/D,OAAO,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAC;AAC1E,OAAO,EAAE,mCAAmC,EAAE,MAAM,mCAAmC,CAAC;AAExF,uFAAuF;AACvF,MAAM,CAAC,KAAK,UAAU,oCAAoC,CAAC,KAS1D;IAKC,MAAM,aAAa,GAAG,IAAI,GAAG,EAA4C,CAAC;IAC1E,mCAAmC,CACjC,aAAa,EACb,KAAK,CAAC,UAAU,EAChB,uBAAuB,CACxB,CAAC;IACF,MAAM,cAAc,GAAG,IAAI,GAAG,EAA2C,CAAC;IAC1E,MAAM,iBAAiB,GAAG,iCAAiC,CAAC;QAC1D,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;QACtE,cAAc,EAAE,KAAK,CAAC,UAAU,CAAC,cAAc;KAChD,CAAC,CAAC;IACH,MAAM,oBAAoB,GAAG,IAAI,GAAG,EAAE,CAAC;IACvC,MAAM,qBAAqB,GAAG,MAAM,qCAAqC,CAAC;QACxE,OAAO,EAAE,CAAC,GAAG,aAAa,CAAC,MAAM,EAAE,CAAC;QACpC,iBAAiB;QACjB,cAAc,EAAE,KAAK,CAAC,UAAU,CAAC,cAAc;QAC/C,cAAc,EAAE,KAAK,CAAC,UAAU,CAAC,cAAc;QAC/C,oBAAoB;QACpB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;KACvE,CAAC,CAAC;IACH,MAAM,IAAI,GAAG,MAAM,2BAA2B,CAAC;QAC7C,qBAAqB;QACrB,4BAA4B,EAAE,IAAI;QAClC,uBAAuB,EAAE,YAAY;QACrC,aAAa;QACb,iBAAiB;QACjB,uBAAuB,EAAE,KAAK;QAC9B,eAAe,EAAE,KAAK;QACtB,KAAK,EAAE,uBAAuB;QAC9B,IAAI,EAAE,KAAK,CAAC,UAAU,CAAC,IAAI;QAC3B,oBAAoB;QACpB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,cAAc;KACf,CAAC,CAAC;IACH,MAAM,OAAO,GAAG,uBAAuB,CACrC,iBAAiB,EACjB,KAAK,CAAC,YAAY,CACnB,CAAC;IACF,kEAAkE;IAClE,gCAAgC,CAC9B,iBAAiB,EACjB,aAAa,EACb,cAAc,CACf,CAAC;IACF,4EAA4E;IAC5E,qEAAqE;IACrE,mDAAmD;IACnD,wBAAwB,CAAC,iBAAiB,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC;IAChE,MAAM,6BAA6B,CAAC,iBAAiB,EAAE;QACrD,YAAY,EAAE,OAAO;QACrB,8BAA8B,EAAE,KAAK;KACtC,CAAC,CAAC;IACH,mCAAmC,CAAC,OAAO,CAAC,CAAC;IAC7C,OAAO,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC;AAClC,CAAC","sourcesContent":["import type { VerifiedContainerAccessManifest } from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport {\n createProjectionCheckpointContext,\n finalizeProjectionCheckpoints,\n observeVerifiedKekLevels,\n observeVerifiedProjectionBundles,\n} from \"../checkpoints/checkpointContext\";\nimport { verifyProjectionAuthorizationEvidence } from \"../principalPolicy/projectionAuthorizationEvidence\";\nimport { projectionLifetimeGuard } from \"../projectionLifetimes\";\nimport type {\n OpenPrincipalPolicyBundleReader,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../types\";\nimport { assertProjectionVerificationCurrent } from \"../types\";\nimport { verifyContainerManifestPath } from \"./containerPathVerification\";\nimport { addContainerWriterProjectionBundles } from \"./containerProjectionVerification\";\n\n/** Authenticate immutable destination roles without advancing write-authority pins. */\nexport async function verifyContainerDestinationProjection(input: {\n readonly execSql: ExecSql;\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n readonly projection: ContainerWriterProjectionResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): Promise<{\n readonly path: VerifiedContainerAccessManifest[];\n /** Every manifest verified on the way, including each head's lineage. */\n readonly verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n}> {\n const bundlesByHash = new Map<string, AccessManifestBundleWireResponse>();\n addContainerWriterProjectionBundles(\n bundlesByHash,\n input.projection,\n \"Container destination\",\n );\n const verifiedByHash = new Map<string, VerifiedContainerAccessManifest>();\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,\n organizationId: input.projection.organizationId,\n });\n const principalPolicyCache = new Map();\n const authorizationEvidence = await verifyProjectionAuthorizationEvidence({\n bundles: [...bundlesByHash.values()],\n checkpointContext,\n policyEvidence: input.projection.policyEvidence,\n organizationId: input.projection.organizationId,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const path = await verifyContainerManifestPath({\n authorizationEvidence,\n requireAuthorizationEvidence: true,\n authorizationMembership: \"referenced\",\n bundlesByHash,\n checkpointContext,\n enforceLocalCheckpoints: false,\n servedAsCurrent: false,\n label: \"Container destination\",\n path: input.projection.path,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash,\n });\n const current = projectionLifetimeGuard(\n checkpointContext,\n input.stillCurrent,\n );\n // Authenticated bytes, not authority: a later read may cite them.\n observeVerifiedProjectionBundles(\n checkpointContext,\n bundlesByHash,\n verifiedByHash,\n );\n // Destination roles never unwrap these levels; a citation refills them only\n // where the API's current level has the same digest, and the reading\n // verification then checks them like served bytes.\n observeVerifiedKekLevels(checkpointContext, [input.projection]);\n await finalizeProjectionCheckpoints(checkpointContext, {\n stillCurrent: current,\n persistVerificationCheckpoints: false,\n });\n assertProjectionVerificationCurrent(current);\n return { path, verifiedByHash };\n}\n"]}
1
+ {"version":3,"file":"containerDestinationVerification.js","sourceRoot":"","sources":["containerDestinationVerification.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,iCAAiC,EACjC,6BAA6B,EAC7B,wBAAwB,EACxB,gCAAgC,GACjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,4BAA4B,EAAE,MAAM,mCAAmC,CAAC;AACjF,OAAO,EAAE,qCAAqC,EAAE,MAAM,oDAAoD,CAAC;AAC3G,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAMjE,OAAO,EAAE,mCAAmC,EAAE,MAAM,UAAU,CAAC;AAC/D,OAAO,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAC;AAC1E,OAAO,EAAE,mCAAmC,EAAE,MAAM,mCAAmC,CAAC;AAmBxF,uFAAuF;AACvF,MAAM,UAAU,oCAAoC,CAClD,KAA0C;IAE1C,OAAO,4BAA4B,CAAC,KAAK,EAAE,GAAG,EAAE,CAC9C,wCAAwC,CAAC,KAAK,CAAC,CAChD,CAAC;AACJ,CAAC;AAED,KAAK,UAAU,wCAAwC,CACrD,KAA0C;IAE1C,MAAM,aAAa,GAAG,IAAI,GAAG,EAA4C,CAAC;IAC1E,mCAAmC,CACjC,aAAa,EACb,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,mDAAmD;IACnD,wBAAwB,CAAC,iBAAiB,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC;IAChE,MAAM,6BAA6B,CAAC,iBAAiB,EAAE;QACrD,YAAY,EAAE,OAAO;QACrB,8BAA8B,EAAE,KAAK;KACtC,CAAC,CAAC;IACH,mCAAmC,CAAC,OAAO,CAAC,CAAC;IAC7C,OAAO,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC;AAClC,CAAC","sourcesContent":["import type { VerifiedContainerAccessManifest } from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport {\n createProjectionCheckpointContext,\n finalizeProjectionCheckpoints,\n observeVerifiedKekLevels,\n observeVerifiedProjectionBundles,\n} from \"../checkpoints/checkpointContext\";\nimport { verifyWithHeldBundleRecovery } from \"../checkpoints/heldBundleRecovery\";\nimport { verifyProjectionAuthorizationEvidence } from \"../principalPolicy/projectionAuthorizationEvidence\";\nimport { projectionLifetimeGuard } from \"../projectionLifetimes\";\nimport type {\n OpenPrincipalPolicyBundleReader,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../types\";\nimport { assertProjectionVerificationCurrent } from \"../types\";\nimport { verifyContainerManifestPath } from \"./containerPathVerification\";\nimport { addContainerWriterProjectionBundles } from \"./containerProjectionVerification\";\n\ninterface ContainerDestinationProjectionInput {\n readonly execSql: ExecSql;\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n readonly projection: ContainerWriterProjectionResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}\n\ninterface VerifiedContainerDestination {\n readonly path: VerifiedContainerAccessManifest[];\n /** Every manifest verified on the way, including each head's lineage. */\n readonly verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n}\n\n/** Authenticate immutable destination roles without advancing write-authority pins. */\nexport function verifyContainerDestinationProjection(\n input: ContainerDestinationProjectionInput,\n): Promise<VerifiedContainerDestination> {\n return verifyWithHeldBundleRecovery(input, () =>\n verifyContainerDestinationProjectionOnce(input),\n );\n}\n\nasync function verifyContainerDestinationProjectionOnce(\n input: ContainerDestinationProjectionInput,\n): Promise<VerifiedContainerDestination> {\n const bundlesByHash = new Map<string, AccessManifestBundleWireResponse>();\n addContainerWriterProjectionBundles(\n bundlesByHash,\n input.projection,\n \"Container destination\",\n );\n const verifiedByHash = new Map<string, VerifiedContainerAccessManifest>();\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,\n organizationId: input.projection.organizationId,\n });\n const principalPolicyCache = new Map();\n const authorizationEvidence = await verifyProjectionAuthorizationEvidence({\n bundles: [...bundlesByHash.values()],\n checkpointContext,\n policyEvidence: input.projection.policyEvidence,\n organizationId: input.projection.organizationId,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const path = await verifyContainerManifestPath({\n authorizationEvidence,\n requireAuthorizationEvidence: true,\n authorizationMembership: \"referenced\",\n bundlesByHash,\n checkpointContext,\n enforceLocalCheckpoints: false,\n servedAsCurrent: false,\n label: \"Container destination\",\n path: input.projection.path,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash,\n });\n const current = projectionLifetimeGuard(\n checkpointContext,\n input.stillCurrent,\n );\n // Authenticated bytes, not authority: a later read may cite them.\n observeVerifiedProjectionBundles(\n checkpointContext,\n bundlesByHash,\n verifiedByHash,\n );\n // Destination roles never unwrap these levels; a citation refills them only\n // where the API's current level has the same digest, and the reading\n // verification then checks them like served bytes.\n observeVerifiedKekLevels(checkpointContext, [input.projection]);\n await finalizeProjectionCheckpoints(checkpointContext, {\n stillCurrent: current,\n persistVerificationCheckpoints: false,\n });\n assertProjectionVerificationCurrent(current);\n return { path, verifiedByHash };\n}\n"]}
@@ -2,6 +2,7 @@ import { computeContainerKekRecipientTargetHash, computeContainerKeyEpochHash, t
2
2
  import { ProjectionDependencyUnavailableError } from "../../shared/dependencyUnavailable.js";
3
3
  import { addBundleByHash } from "../checkpoints/bundleVerification.js";
4
4
  import { createProjectionCheckpointContext, finalizeProjectionCheckpoints, observeAccessManifestCheckpoints, observeVerifiedKekLevels, observeVerifiedProjectionBundles, } from "../checkpoints/checkpointContext.js";
5
+ import { verifyWithHeldBundleRecovery } from "../checkpoints/heldBundleRecovery.js";
5
6
  import { throwKeyingVerificationShapeFailure } from "../error.js";
6
7
  import { collectReferencedPrincipalPolicies } from "../principalPolicy/principalPolicyVerification.js";
7
8
  import { verifyProjectionAuthorizationEvidence } from "../principalPolicy/projectionAuthorizationEvidence.js";
@@ -169,7 +170,10 @@ export async function verifyContainerWriterProjectionWithContext(input, checkpoi
169
170
  checkpointContext.heldContainerHeads.push(...verifiedPath);
170
171
  return verifiedPath;
171
172
  }
172
- export async function verifyContainerWriterProjection(input) {
173
+ export function verifyContainerWriterProjection(input) {
174
+ return verifyWithHeldBundleRecovery(input, () => verifyContainerWriterProjectionOnce(input));
175
+ }
176
+ async function verifyContainerWriterProjectionOnce(input) {
173
177
  try {
174
178
  assertProjectionVerificationCurrent(input.stillCurrent);
175
179
  const verifiedByHash = input.verifiedByHash ??
@@ -195,7 +199,10 @@ export async function verifyContainerWriterProjection(input) {
195
199
  throwKeyingVerificationShapeFailure(error);
196
200
  }
197
201
  }
198
- export async function collectContainerWriterProjectionPrincipalPolicies(input) {
202
+ export function collectContainerWriterProjectionPrincipalPolicies(input) {
203
+ return verifyWithHeldBundleRecovery(input, () => collectContainerWriterProjectionPrincipalPoliciesOnce(input));
204
+ }
205
+ async function collectContainerWriterProjectionPrincipalPoliciesOnce(input) {
199
206
  try {
200
207
  assertProjectionVerificationCurrent(input.stillCurrent);
201
208
  const warmReferencedPrincipalPolicies = generationGuardedPrincipalPolicyWarmer(input.warmReferencedPrincipalPolicies, input.stillCurrent);